Turn meetings into live agent loops. Record, transcribe, and analyze meetings with real-time AI intelligence — before, during, and after calls.
feat: MCP client improved setup
Om Gateea6990d80013
diff --git a/src/main/services/mcp/connection-orchestrator.service.ts b/src/main/services/mcp/connection-orchestrator.service.tsindex 5eff6f8..c365bdc 100644--- a/src/main/services/mcp/connection-orchestrator.service.ts+++ b/src/main/services/mcp/connection-orchestrator.service.ts@@ -10,6 +10,7 @@ import { v4 as uuid } from 'uuid';import { logger } from '../../lib/logger';import { getConnectionRegistry, ConnectionRegistryService } from './connection-registry.service';import { getHealthMonitor, HealthMonitorService } from './health-monitor.service';+import { getMCPAuthService, MCPAuthService, type MCPOAuthConfig } from './mcp-auth.service';import { MCPClientService } from './mcp-client.service';import {getAllMCPServers,@@ -36,12 +37,41 @@ const log = logger.child({ module: 'mcp-orchestrator' });export class ConnectionOrchestratorService extends EventEmitter {private registry: ConnectionRegistryService;private healthMonitor: HealthMonitorService;+ private authService: MCPAuthService;private initialized: boolean = false;constructor() {super();this.registry = getConnectionRegistry();this.healthMonitor = getHealthMonitor();+ this.authService = getMCPAuthService();++ // Forward auth events from registry+ this.registry.on('auth-required', (data) => {+ this.emit('auth-required', data);+ });++ // Forward auth events from auth service and auto-reconnect+ this.authService.on('auth-success', async (data: { serverId: string }) => {+ this.emit('auth-success', data);++ // Auto-reconnect after successful OAuth+ log.info({ serverId: data.serverId }, 'OAuth success, auto-reconnecting...');+ try {+ await this.connect(data.serverId);+ log.info({ serverId: data.serverId }, 'Auto-reconnect after OAuth succeeded');+ } catch (error) {+ log.error({ serverId: data.serverId, error }, 'Auto-reconnect after OAuth failed');+ }+ });++ this.authService.on('auth-error', (data) => {+ this.emit('auth-error', data);+ });++ this.authService.on('tokens-refreshed', (data) => {+ this.emit('tokens-refreshed', data);+ });}/**@@ -58,10 +88,13 @@ export class ConnectionOrchestratorService extends EventEmitter {// Load all servers from databaseconst servers = getAllMCPServers();- // Register all servers+ // Register all servers with auth provider for HTTP transportfor (const server of servers) {const config = this.dbServerToConfig(server);- this.registry.register(config);+ const options = config.transport === 'http'+ ? { authProvider: this.createDefaultAuthProvider(config.id, config.name) }+ : {};+ this.registry.register(config, options);}// Connect to auto-connect servers@@ -123,8 +156,11 @@ export class ConnectionOrchestratorService extends EventEmitter {const config = this.dbServerToConfig(server);- // Register the connection- this.registry.register(config);+ // Register the connection with auth provider for HTTP transport+ const options = config.transport === 'http'+ ? { authProvider: this.createDefaultAuthProvider(config.id, config.name) }+ : {};+ this.registry.register(config, options);log.info({ serverId: id, name: request.name }, 'Created new MCP server');@@ -366,6 +402,145 @@ export class ConnectionOrchestratorService extends EventEmitter {return states;}+ /**+ * Start OAuth authorization flow for a server+ */+ async startOAuthFlow(serverId: string, oauthConfig: MCPOAuthConfig): Promise<void> {+ log.info({ serverId }, 'Starting OAuth flow for server');++ try {+ const tokens = await this.authService.authorize(oauthConfig);++ // After successful auth, reconnect with the new tokens+ const client = this.registry.getClient(serverId);+ if (client) {+ const authProvider = this.authService.createAuthProvider(serverId, oauthConfig);+ client.setAuthProvider(authProvider);++ // Try reconnecting+ await this.connect(serverId);+ }+ } catch (error) {+ log.error({ serverId, error }, 'OAuth flow failed');+ throw error;+ }+ }++ /**+ * Connect with OAuth (if server requires auth)+ */+ async connectWithAuth(serverId: string, oauthConfig?: MCPOAuthConfig): Promise<MCPTool[]> {+ const client = this.registry.get(serverId);+ if (!client) {+ throw new Error(`Server ${serverId} not registered`);+ }++ // If OAuth config provided and we have valid tokens, set up auth provider+ if (oauthConfig && this.authService.hasValidToken(serverId)) {+ // Check if tokens need refresh+ if (this.authService.needsRefresh(serverId)) {+ await this.authService.refreshTokens(serverId);+ }++ const authProvider = this.authService.createAuthProvider(serverId, oauthConfig);+ client.setAuthProvider(authProvider);+ }++ return this.connect(serverId);+ }++ /**+ * Check if a server requires OAuth+ */+ serverRequiresAuth(serverId: string): boolean {+ return this.registry.requiresAuth(serverId);+ }++ /**+ * Check if server has valid OAuth tokens+ */+ hasValidTokens(serverId: string): boolean {+ return this.authService.hasValidToken(serverId);+ }++ /**+ * Delete OAuth tokens for a server+ */+ deleteTokens(serverId: string): void {+ this.authService.deleteTokens(serverId);+ }++ /**+ * Create a default auth provider for HTTP servers+ * This works with SDK-discovered OAuth (server provides OAuth metadata)+ */+ private createDefaultAuthProvider(serverId: string, serverName: string) {+ const authService = this.authService;+ const redirectUri = 'meetingcopilot://oauth/callback';++ return {+ get redirectUrl() {+ return redirectUri;+ },++ get clientMetadata() {+ return {+ client_name: 'Meeting Copilot',+ redirect_uris: [redirectUri],+ };+ },++ clientInformation() {+ // Return undefined to trigger dynamic client registration+ // The SDK will register with the server and get a client_id+ return undefined;+ },++ async saveClientInformation(info: { client_id: string; client_secret?: string }) {+ // Store the dynamically registered client info+ log.info({ serverId, clientId: info.client_id }, 'Saving dynamic client registration');+ // We could persist this in DB if needed for future connections+ },++ async tokens() {+ const tokens = authService.getTokens(serverId);+ if (!tokens) return undefined;++ return {+ access_token: tokens.accessToken,+ refresh_token: tokens.refreshToken,+ token_type: tokens.tokenType,+ };+ },++ async saveTokens(tokens: { access_token: string; token_type: string; refresh_token?: string; expires_in?: number }) {+ authService.saveTokens(serverId, {+ accessToken: tokens.access_token,+ refreshToken: tokens.refresh_token,+ tokenType: tokens.token_type || 'Bearer',+ expiresAt: tokens.expires_in ? new Date(Date.now() + tokens.expires_in * 1000) : undefined,+ });+ },++ async redirectToAuthorization(authorizationUrl: URL) {+ const { shell } = await import('electron');+ log.info({ serverId, authUrl: authorizationUrl.toString() }, 'Opening OAuth authorization URL');+ await shell.openExternal(authorizationUrl.toString());+ },++ async saveCodeVerifier(verifier: string) {+ // Store code verifier temporarily (in memory via authService)+ (authService as any)._codeVerifiers = (authService as any)._codeVerifiers || new Map();+ (authService as any)._codeVerifiers.set(serverId, verifier);+ },++ async codeVerifier() {+ const verifiers = (authService as any)._codeVerifiers;+ return verifiers?.get(serverId) || '';+ },+ };+ }+/*** Convert database server record to MCPServerConfig*/diff --git a/src/main/services/mcp/connection-registry.service.ts b/src/main/services/mcp/connection-registry.service.tsindex 94ff0b4..aece9c3 100644--- a/src/main/services/mcp/connection-registry.service.ts+++ b/src/main/services/mcp/connection-registry.service.ts@@ -5,8 +5,9 @@* Provides centralized access to all active MCP connections.*/+import { EventEmitter } from 'events';import { logger } from '../../lib/logger';-import { MCPClientService } from './mcp-client.service';+import { MCPClientService, type MCPClientOptions } from './mcp-client.service';import type {MCPServerConfig,MCPTool,@@ -21,25 +22,32 @@ interface ConnectionEntry {status: MCPConnectionStatus;lastError?: string;connectedAt?: Date;+ requiresAuth?: boolean;}-export class ConnectionRegistryService {+export class ConnectionRegistryService extends EventEmitter {private connections: Map<string, ConnectionEntry> = new Map();+ constructor() {+ super();+ }+/*** Register a new connection*/- register(config: MCPServerConfig): MCPClientService {+ register(config: MCPServerConfig, options: MCPClientOptions = {}): MCPClientService {if (this.connections.has(config.id)) {log.warn({ serverId: config.id }, 'Connection already registered, returning existing');return this.connections.get(config.id)!.client;}- const client = new MCPClientService(config);+ const client = new MCPClientService(config, options);// Set up event listenersclient.on('connected', ({ tools }) => {this.updateStatus(config.id, 'connected');+ const entry = this.connections.get(config.id);+ if (entry) entry.requiresAuth = false;log.info({ serverId: config.id, toolCount: tools.length }, 'Connection established');});@@ -53,6 +61,13 @@ export class ConnectionRegistryService {log.error({ serverId: config.id, error }, 'Connection error');});+ client.on('auth-required', ({ serverId }) => {+ const entry = this.connections.get(serverId);+ if (entry) entry.requiresAuth = true;+ this.emit('auth-required', { serverId, serverName: config.name });+ log.info({ serverId }, 'Server requires OAuth authentication');+ });+this.connections.set(config.id, {client,config,@@ -224,6 +239,20 @@ export class ConnectionRegistryService {return this.getConnectedServerIds().length > 0;}+ /**+ * Check if a server requires authentication+ */+ requiresAuth(serverId: string): boolean {+ return this.connections.get(serverId)?.requiresAuth ?? false;+ }++ /**+ * Get client instance (for setting auth provider)+ */+ getClient(serverId: string): MCPClientService | undefined {+ return this.connections.get(serverId)?.client;+ }+/*** Get connection count*/diff --git a/src/main/services/mcp/index.ts b/src/main/services/mcp/index.tsindex 19846ec..c39063f 100644--- a/src/main/services/mcp/index.ts+++ b/src/main/services/mcp/index.ts@@ -62,3 +62,12 @@ export {resetMCPAgent,type MCPAgentResult,} from './mcp-agent.service';++// MCP Auth Service (OAuth for MCP servers)+export {+ MCPAuthService,+ getMCPAuthService,+ resetMCPAuthService,+ type MCPOAuthConfig,+ type OAuthTokens,+} from './mcp-auth.service';diff --git a/src/main/services/mcp/mcp-auth.service.ts b/src/main/services/mcp/mcp-auth.service.tsnew file mode 100644index 0000000..4f0d83f--- /dev/null+++ b/src/main/services/mcp/mcp-auth.service.ts@@ -0,0 +1,498 @@+/**+ * MCP Auth Service+ *+ * Handles OAuth authentication for MCP servers that require it.+ * Implements token storage, refresh, and the full OAuth flow with+ * browser-based authorization via custom protocol handler.+ */++import { EventEmitter } from 'events';+import { BrowserWindow, shell } from 'electron';+import crypto from 'crypto';+import { logger } from '../../lib/logger';+import { encrypt, decrypt } from '../../utils/encryption';+import {+ getMCPOauthToken,+ upsertMCPOauthToken,+ deleteMCPOauthToken,+} from '../../db';+import type { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';+import type { MCPOAuthConfig } from '../../../shared/types/mcp.types';++const log = logger.child({ module: 'mcp-auth' });++// Token refresh buffer - refresh 5 minutes before expiry+const TOKEN_REFRESH_BUFFER_MS = 5 * 60 * 1000;++// Re-export for convenience+export type { MCPOAuthConfig };++export interface OAuthTokens {+ accessToken: string;+ refreshToken?: string;+ tokenType: string;+ expiresAt?: Date;+ scope?: string;+}++interface PendingAuth {+ serverId: string;+ config: MCPOAuthConfig;+ codeVerifier: string;+ state: string;+ resolve: (tokens: OAuthTokens) => void;+ reject: (error: Error) => void;+}++export class MCPAuthService extends EventEmitter {+ private pendingAuths: Map<string, PendingAuth> = new Map();+ private authWindow: BrowserWindow | null = null;++ constructor() {+ super();+ }++ /**+ * Check if a server has valid OAuth tokens+ */+ hasValidToken(serverId: string): boolean {+ const tokenRecord = getMCPOauthToken(serverId);+ if (!tokenRecord) return false;++ // Check expiry+ if (tokenRecord.expiresAt) {+ const expiresAt = new Date(tokenRecord.expiresAt);+ const now = new Date();+ if (expiresAt <= now) {+ return false;+ }+ }++ return true;+ }++ /**+ * Check if token needs refresh (expires within buffer period)+ */+ needsRefresh(serverId: string): boolean {+ const tokenRecord = getMCPOauthToken(serverId);+ if (!tokenRecord) return false;++ if (!tokenRecord.expiresAt) return false;++ const expiresAt = new Date(tokenRecord.expiresAt);+ const refreshThreshold = new Date(Date.now() + TOKEN_REFRESH_BUFFER_MS);++ return expiresAt <= refreshThreshold;+ }++ /**+ * Get stored tokens for a server+ */+ getTokens(serverId: string): OAuthTokens | null {+ const tokenRecord = getMCPOauthToken(serverId);+ if (!tokenRecord) return null;++ try {+ return {+ accessToken: decrypt(tokenRecord.accessToken),+ refreshToken: tokenRecord.refreshToken ? decrypt(tokenRecord.refreshToken) : undefined,+ tokenType: tokenRecord.tokenType,+ expiresAt: tokenRecord.expiresAt ? new Date(tokenRecord.expiresAt) : undefined,+ scope: tokenRecord.scope || undefined,+ };+ } catch (error) {+ log.error({ serverId, error }, 'Failed to decrypt tokens');+ return null;+ }+ }++ /**+ * Store tokens for a server+ */+ saveTokens(serverId: string, tokens: OAuthTokens, authServerUrl?: string): void {+ upsertMCPOauthToken({+ serverId,+ accessToken: encrypt(tokens.accessToken),+ refreshToken: tokens.refreshToken ? encrypt(tokens.refreshToken) : undefined,+ tokenType: tokens.tokenType,+ expiresAt: tokens.expiresAt?.toISOString(),+ scope: tokens.scope,+ authServerUrl,+ });++ log.info({ serverId }, 'OAuth tokens saved');+ this.emit('tokens-saved', { serverId });+ }++ /**+ * Delete tokens for a server+ */+ deleteTokens(serverId: string): void {+ deleteMCPOauthToken(serverId);+ log.info({ serverId }, 'OAuth tokens deleted');+ this.emit('tokens-deleted', { serverId });+ }++ /**+ * Start OAuth authorization flow+ * Opens browser for user authorization and waits for callback+ */+ async authorize(config: MCPOAuthConfig): Promise<OAuthTokens> {+ log.info({ serverId: config.serverId, serverName: config.serverName }, 'Starting OAuth flow');++ // Generate PKCE values+ const codeVerifier = this.generateCodeVerifier();+ const codeChallenge = this.generateCodeChallenge(codeVerifier);+ const state = crypto.randomBytes(16).toString('hex');++ // Build authorization URL+ const redirectUri = config.redirectUri || 'meetingcopilot://oauth/callback';+ const authUrl = new URL(config.authorizationUrl);+ authUrl.searchParams.set('client_id', config.clientId);+ authUrl.searchParams.set('redirect_uri', redirectUri);+ authUrl.searchParams.set('response_type', 'code');+ authUrl.searchParams.set('state', state);+ authUrl.searchParams.set('code_challenge', codeChallenge);+ authUrl.searchParams.set('code_challenge_method', 'S256');++ if (config.scopes?.length) {+ authUrl.searchParams.set('scope', config.scopes.join(' '));+ }++ return new Promise((resolve, reject) => {+ // Store pending auth+ this.pendingAuths.set(state, {+ serverId: config.serverId,+ config,+ codeVerifier,+ state,+ resolve,+ reject,+ });++ // Open in external browser (more reliable than BrowserWindow for OAuth)+ shell.openExternal(authUrl.toString()).catch((error) => {+ this.pendingAuths.delete(state);+ reject(new Error(`Failed to open authorization URL: ${error.message}`));+ });++ log.info({ serverId: config.serverId, authUrl: authUrl.toString() }, 'OAuth: Opened browser for authorization');++ // Set timeout for auth flow (5 minutes)+ setTimeout(() => {+ if (this.pendingAuths.has(state)) {+ this.pendingAuths.delete(state);+ reject(new Error('OAuth authorization timed out'));+ }+ }, 5 * 60 * 1000);+ });+ }++ /**+ * Handle OAuth callback from protocol handler+ */+ async handleCallback(callbackUrl: string): Promise<void> {+ log.info({ callbackUrl }, 'OAuth: Received callback');++ const url = new URL(callbackUrl);+ const code = url.searchParams.get('code');+ const state = url.searchParams.get('state');+ const error = url.searchParams.get('error');+ const errorDescription = url.searchParams.get('error_description');++ if (!state) {+ log.error('OAuth callback missing state parameter');+ return;+ }++ const pendingAuth = this.pendingAuths.get(state);+ if (!pendingAuth) {+ log.error({ state }, 'OAuth callback for unknown state');+ return;+ }++ this.pendingAuths.delete(state);++ if (error) {+ pendingAuth.reject(new Error(`OAuth error: ${error} - ${errorDescription}`));+ return;+ }++ if (!code) {+ pendingAuth.reject(new Error('OAuth callback missing authorization code'));+ return;+ }++ try {+ // Exchange code for tokens+ const tokens = await this.exchangeCodeForTokens(+ pendingAuth.config,+ code,+ pendingAuth.codeVerifier+ );++ // Save tokens+ this.saveTokens(pendingAuth.serverId, tokens, pendingAuth.config.tokenUrl);++ pendingAuth.resolve(tokens);++ this.emit('auth-success', { serverId: pendingAuth.serverId });+ } catch (err) {+ pendingAuth.reject(err instanceof Error ? err : new Error(String(err)));+ this.emit('auth-error', { serverId: pendingAuth.serverId, error: String(err) });+ }+ }++ /**+ * Exchange authorization code for tokens+ */+ private async exchangeCodeForTokens(+ config: MCPOAuthConfig,+ code: string,+ codeVerifier: string+ ): Promise<OAuthTokens> {+ const redirectUri = config.redirectUri || 'meetingcopilot://oauth/callback';++ const body = new URLSearchParams({+ grant_type: 'authorization_code',+ code,+ redirect_uri: redirectUri,+ client_id: config.clientId,+ code_verifier: codeVerifier,+ });++ if (config.clientSecret) {+ body.set('client_secret', config.clientSecret);+ }++ const response = await fetch(config.tokenUrl, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/x-www-form-urlencoded',+ },+ body: body.toString(),+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`Token exchange failed: ${response.status} - ${errorText}`);+ }++ const data = await response.json() as {+ access_token: string;+ refresh_token?: string;+ token_type?: string;+ expires_in?: number;+ scope?: string;+ };++ const tokens: OAuthTokens = {+ accessToken: data.access_token,+ refreshToken: data.refresh_token,+ tokenType: data.token_type || 'Bearer',+ scope: data.scope,+ };++ if (data.expires_in) {+ tokens.expiresAt = new Date(Date.now() + data.expires_in * 1000);+ }++ log.info({ serverId: config.serverId }, 'OAuth: Token exchange successful');++ return tokens;+ }++ /**+ * Refresh tokens using refresh_token+ */+ async refreshTokens(serverId: string): Promise<OAuthTokens | null> {+ const tokenRecord = getMCPOauthToken(serverId);+ if (!tokenRecord || !tokenRecord.refreshToken || !tokenRecord.authServerUrl) {+ log.warn({ serverId }, 'Cannot refresh tokens: missing refresh token or auth server URL');+ return null;+ }++ try {+ const refreshToken = decrypt(tokenRecord.refreshToken);++ const body = new URLSearchParams({+ grant_type: 'refresh_token',+ refresh_token: refreshToken,+ });++ const response = await fetch(tokenRecord.authServerUrl, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/x-www-form-urlencoded',+ },+ body: body.toString(),+ });++ if (!response.ok) {+ const errorText = await response.text();+ log.error({ serverId, status: response.status, error: errorText }, 'Token refresh failed');++ // If refresh fails with 400/401, tokens are invalid - delete them+ if (response.status === 400 || response.status === 401) {+ this.deleteTokens(serverId);+ }+ return null;+ }++ const data = await response.json() as {+ access_token: string;+ refresh_token?: string;+ token_type?: string;+ expires_in?: number;+ scope?: string;+ };++ const tokens: OAuthTokens = {+ accessToken: data.access_token,+ refreshToken: data.refresh_token || refreshToken, // Keep old refresh token if not provided+ tokenType: data.token_type || 'Bearer',+ scope: data.scope || tokenRecord.scope || undefined,+ };++ if (data.expires_in) {+ tokens.expiresAt = new Date(Date.now() + data.expires_in * 1000);+ }++ // Save refreshed tokens+ this.saveTokens(serverId, tokens, tokenRecord.authServerUrl);++ log.info({ serverId }, 'OAuth: Tokens refreshed successfully');+ this.emit('tokens-refreshed', { serverId });++ return tokens;+ } catch (error) {+ log.error({ serverId, error }, 'Failed to refresh tokens');+ return null;+ }+ }++ /**+ * Create an OAuthClientProvider for the MCP SDK+ */+ createAuthProvider(serverId: string, config: MCPOAuthConfig): OAuthClientProvider {+ const self = this;++ return {+ get redirectUrl() {+ return config.redirectUri || 'meetingcopilot://oauth/callback';+ },++ get clientMetadata() {+ return {+ client_id: config.clientId,+ client_name: 'Meeting Copilot',+ redirect_uris: [config.redirectUri || 'meetingcopilot://oauth/callback'],+ };+ },++ clientInformation() {+ return {+ client_id: config.clientId,+ client_secret: config.clientSecret,+ };+ },++ async tokens() {+ const tokens = self.getTokens(serverId);+ if (!tokens) return undefined;++ return {+ access_token: tokens.accessToken,+ refresh_token: tokens.refreshToken,+ token_type: tokens.tokenType,+ expires_at: tokens.expiresAt ? Math.floor(tokens.expiresAt.getTime() / 1000) : undefined,+ };+ },++ async saveTokens(tokens) {+ self.saveTokens(serverId, {+ accessToken: tokens.access_token,+ refreshToken: tokens.refresh_token,+ tokenType: tokens.token_type || 'Bearer',+ expiresAt: tokens.expires_in ? new Date(Date.now() + tokens.expires_in * 1000) : undefined,+ }, config.tokenUrl);+ },++ async redirectToAuthorization(authorizationUrl: URL) {+ await shell.openExternal(authorizationUrl.toString());+ },++ async saveCodeVerifier(verifier: string) {+ // Store temporarily - the SDK manages this+ self.pendingAuths.set(`verifier:${serverId}`, {+ serverId,+ config,+ codeVerifier: verifier,+ state: '',+ resolve: () => {},+ reject: () => {},+ });+ },++ async codeVerifier() {+ const pending = self.pendingAuths.get(`verifier:${serverId}`);+ return pending?.codeVerifier || '';+ },+ };+ }++ /**+ * Generate PKCE code verifier+ */+ private generateCodeVerifier(): string {+ return crypto.randomBytes(32).toString('base64url');+ }++ /**+ * Generate PKCE code challenge from verifier+ */+ private generateCodeChallenge(verifier: string): string {+ return crypto.createHash('sha256').update(verifier).digest('base64url');+ }++ /**+ * Check if there's a pending auth for a server+ */+ hasPendingAuth(serverId: string): boolean {+ for (const pending of this.pendingAuths.values()) {+ if (pending.serverId === serverId) {+ return true;+ }+ }+ return false;+ }++ /**+ * Cancel pending auth for a server+ */+ cancelPendingAuth(serverId: string): void {+ for (const [state, pending] of this.pendingAuths.entries()) {+ if (pending.serverId === serverId) {+ pending.reject(new Error('Authorization cancelled'));+ this.pendingAuths.delete(state);+ }+ }+ }+}++// Singleton instance+let instance: MCPAuthService | null = null;++export function getMCPAuthService(): MCPAuthService {+ if (!instance) {+ instance = new MCPAuthService();+ }+ return instance;+}++export function resetMCPAuthService(): void {+ instance = null;+}++export default MCPAuthService;diff --git a/src/main/services/mcp/mcp-client.service.ts b/src/main/services/mcp/mcp-client.service.tsindex 14eed6e..c35fd8e 100644--- a/src/main/services/mcp/mcp-client.service.ts+++ b/src/main/services/mcp/mcp-client.service.ts@@ -9,6 +9,7 @@ import { EventEmitter } from 'events';import { Client } from '@modelcontextprotocol/sdk/client/index.js';import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';import { logger } from '../../lib/logger';import type {MCPServerConfig,@@ -17,6 +18,7 @@ import type {MCPConnectionStatus,} from '../../../shared/types/mcp.types';import { decryptCredentials } from '../../utils/encryption';+import type { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';const log = logger.child({ module: 'mcp-client' });@@ -24,19 +26,26 @@ export interface MCPClientEvents {'connected': { serverId: string; tools: MCPTool[] };'disconnected': { serverId: string; reason: string };'error': { serverId: string; error: string };+ 'auth-required': { serverId: string; authServerUrl?: string };'tool-result': MCPToolResult;}+export interface MCPClientOptions {+ authProvider?: OAuthClientProvider;+}+export class MCPClientService extends EventEmitter {private client: Client | null = null;- private transport: StdioClientTransport | SSEClientTransport | null = null;+ private transport: StdioClientTransport | SSEClientTransport | StreamableHTTPClientTransport | null = null;private config: MCPServerConfig;+ private options: MCPClientOptions;private tools: MCPTool[] = [];private connectionStatus: MCPConnectionStatus = 'disconnected';- constructor(config: MCPServerConfig) {+ constructor(config: MCPServerConfig, options: MCPClientOptions = {}) {super();this.config = config;+ this.options = options;}/**@@ -138,9 +147,17 @@ export class MCPClientService extends EventEmitter {}// Parse args- const args = typeof this.config.args === 'string'- ? JSON.parse(this.config.args)- : this.config.args || [];+ let args: string[] = [];+ if (typeof this.config.args === 'string') {+ try {+ args = JSON.parse(this.config.args);+ } catch {+ log.warn({ serverId: this.config.id }, 'Failed to parse args as JSON, treating as single argument');+ args = [this.config.args];+ }+ } else {+ args = this.config.args || [];+ }this.transport = new StdioClientTransport({command: this.config.command,@@ -152,7 +169,7 @@ export class MCPClientService extends EventEmitter {}/**- * Connect via HTTP/SSE transport+ * Connect via HTTP transport (Streamable HTTP with SSE fallback)*/private async connectHttp(): Promise<void> {if (!this.config.url) {@@ -174,13 +191,99 @@ export class MCPClientService extends EventEmitter {}}- this.transport = new SSEClientTransport(new URL(this.config.url), {- requestInit: {- headers,- },- });+ const url = new URL(this.config.url);+ const { authProvider } = this.options;- await this.client!.connect(this.transport);+ // Try modern Streamable HTTP transport first+ try {+ this.transport = new StreamableHTTPClientTransport(url, {+ authProvider,+ requestInit: { headers },+ });+ await this.client!.connect(this.transport);+ log.info({ serverId: this.config.id }, 'Connected via Streamable HTTP transport');+ } catch (streamableError) {+ // Check if this is an auth error+ if (this.isAuthError(streamableError)) {+ log.info({ serverId: this.config.id }, 'Server requires OAuth authentication');+ this.emit('auth-required', { serverId: this.config.id });+ throw streamableError;+ }++ // Fall back to legacy SSE transport+ log.warn(+ { serverId: this.config.id, error: streamableError },+ 'Streamable HTTP failed, falling back to SSE'+ );++ try {+ this.transport = new SSEClientTransport(url, {+ requestInit: { headers },+ });+ await this.client!.connect(this.transport);+ log.info({ serverId: this.config.id }, 'Connected via SSE transport (fallback)');+ } catch (sseError) {+ // Check if SSE also fails with auth error+ if (this.isAuthError(sseError)) {+ log.info({ serverId: this.config.id }, 'Server requires OAuth authentication (SSE)');+ this.emit('auth-required', { serverId: this.config.id });+ }+ throw sseError;+ }+ }+ }++ /**+ * Check if an error is an authentication error (401)+ */+ private isAuthError(error: unknown): boolean {+ log.debug({ error, errorType: typeof error, isError: error instanceof Error }, 'Checking if auth error');++ // Check Error instance message+ if (error instanceof Error) {+ const message = error.message.toLowerCase();+ if (message.includes('401') ||+ message.includes('unauthorized') ||+ message.includes('authentication required')) {+ log.info({ serverId: this.config.id, message: error.message }, 'Detected auth error from Error message');+ return true;+ }+ }++ // Check plain object with code property+ if (typeof error === 'object' && error !== null) {+ const errorObj = error as Record<string, unknown>;++ // Direct code check+ if (errorObj.code === 401 || errorObj.status === 401) {+ log.info({ serverId: this.config.id }, 'Detected auth error from error.code/status');+ return true;+ }++ // Check nested event object (SSE errors have this structure)+ if (typeof errorObj.event === 'object' && errorObj.event !== null) {+ const event = errorObj.event as Record<string, unknown>;+ if (event.code === 401 || event.status === 401) {+ log.info({ serverId: this.config.id }, 'Detected auth error from error.event.code');+ return true;+ }+ }++ // Check if it has a message property with 401+ if (typeof errorObj.message === 'string' && errorObj.message.includes('401')) {+ log.info({ serverId: this.config.id }, 'Detected auth error from error.message string');+ return true;+ }+ }++ return false;+ }++ /**+ * Set auth provider (for reconnecting with auth)+ */+ setAuthProvider(authProvider: OAuthClientProvider): void {+ this.options.authProvider = authProvider;}/**@@ -294,12 +397,12 @@ export class MCPClientService extends EventEmitter {log.info({ serverId: this.config.id, reason }, 'Disconnecting from MCP server');try {- if (this.transport) {- await this.transport.close();- this.transport = null;+ if (this.client) {+ await this.client.close();}this.client = null;+ this.transport = null;this.tools = [];this.connectionStatus = 'disconnected';