discourse/plugins/discourse-ai/lib/mcp/oauth_token_store.rb
Sam b2d73b346d
FEATURE: Add MCP server integration to AI agents (#38706)
Introduce support for Model Context Protocol (MCP) servers in the
discourse-ai plugin, allowing AI agents to connect to external tool
servers via the MCP standard.

Key additions:
- AiMcpServer model with CRUD admin UI, health tracking, and
  tool caching (hourly refresh via scheduled job)
- MCP client (Streamable HTTP transport) with session management
  and tool invocation
- Full OAuth 2.1 flow support (discovery, dynamic registration,
  authorization code grant, token refresh, and disconnect)
- MCP tool type for AI agents that proxies tool calls to remote
  MCP servers at runtime
- Agent editor updated to show combined tool/token counts from
  both local tools and MCP servers
- Agent import/export includes MCP server associations
- Admin secrets UI updated to surface MCP server usage
- Comprehensive specs for models, controllers, client, tool
  registry, and OAuth flow
2026-03-25 17:32:27 +11:00

50 lines
1 KiB
Ruby
Vendored

# frozen_string_literal: true
module DiscourseAi
module Mcp
class OAuthTokenStore
def initialize(server)
@server = server
end
def access_token
record&.access_token
end
def refresh_token
record&.refresh_token
end
def write!(access_token:, refresh_token:)
oauth_token = record || server.build_oauth_token
oauth_token.access_token = access_token unless access_token.nil?
oauth_token.refresh_token = refresh_token unless refresh_token.nil?
if oauth_token.access_token.blank? && oauth_token.refresh_token.blank?
oauth_token.destroy! if oauth_token.persisted?
else
oauth_token.save!
end
reset_association_cache
end
def clear!
record&.destroy!
reset_association_cache
end
private
attr_reader :server
def record
server.oauth_token
end
def reset_association_cache
server.association(:oauth_token).reset
end
end
end
end