| import { Client } from '@modelcontextprotocol/sdk/client'; |
| import { |
| StreamableHTTPClientTransport, |
| StreamableHTTPError |
| } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; |
| import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js'; |
| import { WebSocketClientTransport } from '@modelcontextprotocol/sdk/client/websocket.js'; |
| import type { |
| Tool, |
| Prompt, |
| GetPromptResult, |
| ListChangedHandlers |
| } from '@modelcontextprotocol/sdk/types.js'; |
| import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'; |
| import { |
| DEFAULT_MCP_CONFIG, |
| DEFAULT_CLIENT_VERSION, |
| DEFAULT_IMAGE_MIME_TYPE |
| } from '$lib/constants'; |
| import { |
| MCPConnectionPhase, |
| MCPLogLevel, |
| MCPTransportType, |
| MCPContentType, |
| MCPRefType |
| } from '$lib/enums'; |
| import type { |
| MCPServerConfig, |
| ToolCallParams, |
| ToolExecutionResult, |
| Implementation, |
| ClientCapabilities, |
| MCPConnection, |
| MCPPhaseCallback, |
| MCPConnectionLog, |
| MCPServerInfo, |
| MCPResource, |
| MCPResourceTemplate, |
| MCPResourceContent, |
| MCPReadResourceResult |
| } from '$lib/types'; |
| import { buildProxiedUrl, throwIfAborted, isAbortError, createBase64DataUrl } from '$lib/utils'; |
|
|
| interface ToolResultContentItem { |
| type: string; |
| text?: string; |
| data?: string; |
| mimeType?: string; |
| resource?: { text?: string; blob?: string; uri?: string }; |
| } |
|
|
| interface ToolCallResult { |
| content?: ToolResultContentItem[]; |
| isError?: boolean; |
| _meta?: Record<string, unknown>; |
| } |
|
|
| export class MCPService { |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| private static createLog( |
| phase: MCPConnectionPhase, |
| message: string, |
| level: MCPLogLevel = MCPLogLevel.INFO, |
| details?: unknown |
| ): MCPConnectionLog { |
| return { |
| timestamp: new Date(), |
| phase, |
| message, |
| level, |
| details |
| }; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| static isSessionExpiredError(error: unknown): boolean { |
| return error instanceof StreamableHTTPError && error.code === 404; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| static createTransport(config: MCPServerConfig): { |
| transport: Transport; |
| type: MCPTransportType; |
| } { |
| if (!config.url) { |
| throw new Error('MCP server configuration is missing url'); |
| } |
|
|
| const useProxy = config.useProxy ?? false; |
| const requestInit: RequestInit = {}; |
|
|
| if (config.headers) { |
| requestInit.headers = config.headers; |
| } |
|
|
| if (config.credentials) { |
| requestInit.credentials = config.credentials; |
| } |
|
|
| if (config.transport === MCPTransportType.WEBSOCKET) { |
| if (useProxy) { |
| throw new Error( |
| 'WebSocket transport is not supported when using CORS proxy. Use HTTP transport instead.' |
| ); |
| } |
|
|
| const url = new URL(config.url); |
|
|
| if (import.meta.env.DEV) { |
| console.log(`[MCPService] Creating WebSocket transport for ${url.href}`); |
| } |
|
|
| return { |
| transport: new WebSocketClientTransport(url), |
| type: MCPTransportType.WEBSOCKET |
| }; |
| } |
|
|
| const url = useProxy ? buildProxiedUrl(config.url) : new URL(config.url); |
|
|
| if (useProxy && import.meta.env.DEV) { |
| console.log(`[MCPService] Using CORS proxy for ${config.url} -> ${url.href}`); |
| } |
|
|
| try { |
| if (import.meta.env.DEV) { |
| console.log(`[MCPService] Creating StreamableHTTP transport for ${url.href}`); |
| } |
|
|
| return { |
| transport: new StreamableHTTPClientTransport(url, { |
| requestInit |
| }), |
| type: MCPTransportType.STREAMABLE_HTTP |
| }; |
| } catch (httpError) { |
| console.warn(`[MCPService] StreamableHTTP failed, trying SSE transport...`, httpError); |
|
|
| try { |
| return { |
| transport: new SSEClientTransport(url, { requestInit }), |
| type: MCPTransportType.SSE |
| }; |
| } catch (sseError) { |
| const httpMsg = httpError instanceof Error ? httpError.message : String(httpError); |
| const sseMsg = sseError instanceof Error ? sseError.message : String(sseError); |
|
|
| throw new Error(`Failed to create transport. StreamableHTTP: ${httpMsg}; SSE: ${sseMsg}`); |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| private static extractServerInfo(impl: Implementation | undefined): MCPServerInfo | undefined { |
| if (!impl) { |
| return undefined; |
| } |
|
|
| return { |
| name: impl.name, |
| version: impl.version, |
| title: impl.title, |
| description: impl.description, |
| websiteUrl: impl.websiteUrl, |
| icons: impl.icons?.map((icon: { src: string; mimeType?: string; sizes?: string }) => ({ |
| src: icon.src, |
| mimeType: icon.mimeType, |
| sizes: icon.sizes |
| })) |
| }; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| static async connect( |
| serverName: string, |
| serverConfig: MCPServerConfig, |
| clientInfo?: Implementation, |
| capabilities?: ClientCapabilities, |
| onPhase?: MCPPhaseCallback, |
| listChangedHandlers?: ListChangedHandlers |
| ): Promise<MCPConnection> { |
| const startTime = performance.now(); |
| const effectiveClientInfo = clientInfo ?? DEFAULT_MCP_CONFIG.clientInfo; |
| const effectiveCapabilities = capabilities ?? DEFAULT_MCP_CONFIG.capabilities; |
|
|
| |
| onPhase?.( |
| MCPConnectionPhase.TRANSPORT_CREATING, |
| this.createLog( |
| MCPConnectionPhase.TRANSPORT_CREATING, |
| `Creating transport for ${serverConfig.url}` |
| ) |
| ); |
|
|
| if (import.meta.env.DEV) { |
| console.log(`[MCPService][${serverName}] Creating transport...`); |
| } |
|
|
| const { transport, type: transportType } = this.createTransport(serverConfig); |
|
|
| |
| if (transportType === MCPTransportType.WEBSOCKET) { |
| transport.onclose = () => { |
| console.log(`[MCPService][${serverName}] WebSocket closed, notifying for reconnection`); |
| onPhase?.( |
| MCPConnectionPhase.DISCONNECTED, |
| this.createLog(MCPConnectionPhase.DISCONNECTED, 'WebSocket connection closed') |
| ); |
| }; |
| } |
|
|
| |
| onPhase?.( |
| MCPConnectionPhase.TRANSPORT_READY, |
| this.createLog(MCPConnectionPhase.TRANSPORT_READY, `Transport ready (${transportType})`), |
| { transportType } |
| ); |
|
|
| const client = new Client( |
| { |
| name: effectiveClientInfo.name, |
| version: effectiveClientInfo.version ?? DEFAULT_CLIENT_VERSION |
| }, |
| { |
| capabilities: effectiveCapabilities, |
| listChanged: listChangedHandlers |
| } |
| ); |
|
|
| |
| onPhase?.( |
| MCPConnectionPhase.INITIALIZING, |
| this.createLog(MCPConnectionPhase.INITIALIZING, 'Sending initialize request...') |
| ); |
|
|
| console.log(`[MCPService][${serverName}] Connecting to server...`); |
| await client.connect(transport); |
|
|
| const serverVersion = client.getServerVersion(); |
| const serverCapabilities = client.getServerCapabilities(); |
| const instructions = client.getInstructions(); |
| const serverInfo = this.extractServerInfo(serverVersion); |
|
|
| |
| onPhase?.( |
| MCPConnectionPhase.CAPABILITIES_EXCHANGED, |
| this.createLog( |
| MCPConnectionPhase.CAPABILITIES_EXCHANGED, |
| 'Capabilities exchanged successfully', |
| MCPLogLevel.INFO, |
| { |
| serverCapabilities, |
| serverInfo |
| } |
| ), |
| { |
| serverInfo, |
| serverCapabilities, |
| clientCapabilities: effectiveCapabilities, |
| instructions |
| } |
| ); |
|
|
| |
| onPhase?.( |
| MCPConnectionPhase.LISTING_TOOLS, |
| this.createLog(MCPConnectionPhase.LISTING_TOOLS, 'Listing available tools...') |
| ); |
|
|
| console.log(`[MCPService][${serverName}] Connected, listing tools...`); |
| const tools = await this.listTools({ |
| client, |
| transport, |
| tools: [], |
| serverName, |
| transportType, |
| connectionTimeMs: 0 |
| }); |
|
|
| const connectionTimeMs = Math.round(performance.now() - startTime); |
|
|
| |
| onPhase?.( |
| MCPConnectionPhase.CONNECTED, |
| this.createLog( |
| MCPConnectionPhase.CONNECTED, |
| `Connection established with ${tools.length} tools (${connectionTimeMs}ms)` |
| ) |
| ); |
|
|
| console.log( |
| `[MCPService][${serverName}] Initialization complete with ${tools.length} tools in ${connectionTimeMs}ms` |
| ); |
|
|
| return { |
| client, |
| transport, |
| tools, |
| serverName, |
| transportType, |
| serverInfo, |
| serverCapabilities, |
| clientCapabilities: effectiveCapabilities, |
| protocolVersion: DEFAULT_MCP_CONFIG.protocolVersion, |
| instructions, |
| connectionTimeMs |
| }; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| static async disconnect(connection: MCPConnection): Promise<void> { |
| console.log(`[MCPService][${connection.serverName}] Disconnecting...`); |
| try { |
| |
| if (connection.transport.onclose) { |
| connection.transport.onclose = undefined; |
| } |
|
|
| await connection.client.close(); |
| } catch (error) { |
| console.warn(`[MCPService][${connection.serverName}] Error during disconnect:`, error); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| static async listTools(connection: MCPConnection): Promise<Tool[]> { |
| try { |
| const result = await connection.client.listTools(); |
|
|
| return result.tools ?? []; |
| } catch (error) { |
| |
| if (this.isSessionExpiredError(error)) { |
| throw error; |
| } |
|
|
| console.warn(`[MCPService][${connection.serverName}] Failed to list tools:`, error); |
|
|
| return []; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| static async listPrompts(connection: MCPConnection): Promise<Prompt[]> { |
| try { |
| const result = await connection.client.listPrompts(); |
|
|
| return result.prompts ?? []; |
| } catch (error) { |
| |
| if (this.isSessionExpiredError(error)) { |
| throw error; |
| } |
|
|
| console.warn(`[MCPService][${connection.serverName}] Failed to list prompts:`, error); |
|
|
| return []; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| static async getPrompt( |
| connection: MCPConnection, |
| name: string, |
| args?: Record<string, string> |
| ): Promise<GetPromptResult> { |
| try { |
| return await connection.client.getPrompt({ name, arguments: args }); |
| } catch (error) { |
| console.error(`[MCPService][${connection.serverName}] Failed to get prompt:`, error); |
|
|
| throw error; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| static async callTool( |
| connection: MCPConnection, |
| params: ToolCallParams, |
| signal?: AbortSignal |
| ): Promise<ToolExecutionResult> { |
| throwIfAborted(signal); |
|
|
| try { |
| const result = await connection.client.callTool( |
| { name: params.name, arguments: params.arguments }, |
| undefined, |
| { signal } |
| ); |
|
|
| return { |
| content: this.formatToolResult(result as ToolCallResult), |
| isError: (result as ToolCallResult).isError ?? false |
| }; |
| } catch (error) { |
| if (isAbortError(error)) { |
| throw error; |
| } |
|
|
| |
| if (this.isSessionExpiredError(error)) { |
| throw error; |
| } |
|
|
| const message = error instanceof Error ? error.message : String(error); |
|
|
| throw new Error( |
| `Tool "${params.name}" execution failed on server "${connection.serverName}": ${message}`, |
| { cause: error instanceof Error ? error : undefined } |
| ); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| private static formatToolResult(result: ToolCallResult): string { |
| const content = result.content; |
| if (!Array.isArray(content)) return ''; |
|
|
| return content |
| .map((item) => this.formatSingleContent(item)) |
| .filter(Boolean) |
| .join('\n'); |
| } |
|
|
| private static formatSingleContent(content: ToolResultContentItem): string { |
| if (content.type === MCPContentType.TEXT && content.text) { |
| return content.text; |
| } |
|
|
| if (content.type === MCPContentType.IMAGE && content.data) { |
| return createBase64DataUrl(content.mimeType ?? DEFAULT_IMAGE_MIME_TYPE, content.data); |
| } |
|
|
| if (content.type === MCPContentType.RESOURCE && content.resource) { |
| const resource = content.resource; |
|
|
| if (resource.text) return resource.text; |
| if (resource.blob) return resource.blob; |
|
|
| return JSON.stringify(resource); |
| } |
|
|
| if (content.data && content.mimeType) { |
| return createBase64DataUrl(content.mimeType, content.data); |
| } |
|
|
| return JSON.stringify(content); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| static async complete( |
| connection: MCPConnection, |
| ref: { type: MCPRefType.PROMPT; name: string } | { type: MCPRefType.RESOURCE; uri: string }, |
| argument: { name: string; value: string } |
| ): Promise<{ values: string[]; total?: number; hasMore?: boolean } | null> { |
| try { |
| const result = await connection.client.complete({ |
| ref, |
| argument |
| }); |
|
|
| return result.completion; |
| } catch (error) { |
| console.error(`[MCPService] Failed to get completions:`, error); |
|
|
| return null; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| static async listResources( |
| connection: MCPConnection, |
| cursor?: string |
| ): Promise<{ resources: MCPResource[]; nextCursor?: string }> { |
| try { |
| const result = await connection.client.listResources(cursor ? { cursor } : undefined); |
|
|
| return { |
| resources: (result.resources ?? []) as MCPResource[], |
| nextCursor: result.nextCursor |
| }; |
| } catch (error) { |
| if (this.isSessionExpiredError(error)) { |
| throw error; |
| } |
|
|
| console.warn(`[MCPService][${connection.serverName}] Failed to list resources:`, error); |
|
|
| return { resources: [] }; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| static async listAllResources(connection: MCPConnection): Promise<MCPResource[]> { |
| const allResources: MCPResource[] = []; |
| let cursor: string | undefined; |
|
|
| do { |
| const result = await this.listResources(connection, cursor); |
| allResources.push(...result.resources); |
| cursor = result.nextCursor; |
| } while (cursor); |
|
|
| return allResources; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| static async listResourceTemplates( |
| connection: MCPConnection, |
| cursor?: string |
| ): Promise<{ resourceTemplates: MCPResourceTemplate[]; nextCursor?: string }> { |
| try { |
| const result = await connection.client.listResourceTemplates(cursor ? { cursor } : undefined); |
|
|
| return { |
| resourceTemplates: (result.resourceTemplates ?? []) as MCPResourceTemplate[], |
| nextCursor: result.nextCursor |
| }; |
| } catch (error) { |
| if (this.isSessionExpiredError(error)) { |
| throw error; |
| } |
|
|
| console.warn( |
| `[MCPService][${connection.serverName}] Failed to list resource templates:`, |
| error |
| ); |
|
|
| return { resourceTemplates: [] }; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| static async listAllResourceTemplates(connection: MCPConnection): Promise<MCPResourceTemplate[]> { |
| const allTemplates: MCPResourceTemplate[] = []; |
| let cursor: string | undefined; |
|
|
| do { |
| const result = await this.listResourceTemplates(connection, cursor); |
| allTemplates.push(...result.resourceTemplates); |
| cursor = result.nextCursor; |
| } while (cursor); |
|
|
| return allTemplates; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| static async readResource( |
| connection: MCPConnection, |
| uri: string |
| ): Promise<MCPReadResourceResult> { |
| try { |
| const result = await connection.client.readResource({ uri }); |
|
|
| return { |
| contents: (result.contents ?? []) as MCPResourceContent[], |
| _meta: result._meta |
| }; |
| } catch (error) { |
| console.error(`[MCPService][${connection.serverName}] Failed to read resource:`, error); |
|
|
| throw error; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| static async subscribeResource(connection: MCPConnection, uri: string): Promise<void> { |
| try { |
| await connection.client.subscribeResource({ uri }); |
|
|
| console.log(`[MCPService][${connection.serverName}] Subscribed to resource: ${uri}`); |
| } catch (error) { |
| console.error( |
| `[MCPService][${connection.serverName}] Failed to subscribe to resource:`, |
| error |
| ); |
|
|
| throw error; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| static async unsubscribeResource(connection: MCPConnection, uri: string): Promise<void> { |
| try { |
| await connection.client.unsubscribeResource({ uri }); |
|
|
| console.log(`[MCPService][${connection.serverName}] Unsubscribed from resource: ${uri}`); |
| } catch (error) { |
| console.error( |
| `[MCPService][${connection.serverName}] Failed to unsubscribe from resource:`, |
| error |
| ); |
|
|
| throw error; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| static supportsResources(connection: MCPConnection): boolean { |
| |
| |
| return connection.serverCapabilities?.resources !== undefined; |
| } |
|
|
| |
| |
| |
| |
| |
| static supportsResourceSubscriptions(connection: MCPConnection): boolean { |
| return !!connection.serverCapabilities?.resources?.subscribe; |
| } |
| } |
|
|