From 60b5491e1bb9995cf42902f082a468a8ed09a746 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 14 Aug 2025 20:16:33 -0700 Subject: [PATCH] fix: simplify mcp service --- src/services/MCPService.test.ts | 29 ++---- src/services/MCPService.ts | 157 +++++++------------------------- src/services/types.ts | 26 +++++- src/streamChatResponse.ts | 5 +- src/tools/index.ts | 2 +- src/ui/IntroMessage.tsx | 2 +- src/ui/MCPSelector.tsx | 39 ++++---- 7 files changed, 86 insertions(+), 174 deletions(-) diff --git a/src/services/MCPService.test.ts b/src/services/MCPService.test.ts index d9e20ef00..4e7181e0e 100644 --- a/src/services/MCPService.test.ts +++ b/src/services/MCPService.test.ts @@ -51,8 +51,8 @@ describe("MCPService", () => { const state = mcpService.getState(); expect(mcpService.isReady()).toBe(false); expect(state.connections).toEqual([]); - expect(state.toolCount).toBe(0); - expect(state.promptCount).toBe(0); + expect(state.tools.length).toBe(0); + expect(state.prompts.length).toBe(0); }); it("should initialize with no servers", async () => { @@ -64,8 +64,8 @@ describe("MCPService", () => { expect(mcpService.isReady()).toBe(true); expect(state.connections).toEqual([]); - expect(state.toolCount).toBe(0); - expect(state.promptCount).toBe(0); + expect(state.tools.length).toBe(0); + expect(state.prompts.length).toBe(0); }); it("should initialize and return immediately even with server configs", async () => { @@ -82,15 +82,7 @@ describe("MCPService", () => { await mcpService.initialize(mockAssistant); }); - it("should provide service info", () => { - const info = mcpService.getMCPInfo(); - expect(info).toHaveProperty("toolNames"); - expect(info).toHaveProperty("promptNames"); - expect(info).toHaveProperty("connectionCount"); - }); - it("should get overall status", async () => { - console.log(mcpService.getConnectionInfo()) const firstStatus = mcpService.getOverallStatus(); expect(firstStatus.status).toBe("connected"); expect(firstStatus.hasWarnings).toBe(false); @@ -110,7 +102,7 @@ describe("MCPService", () => { }); it("should handle stop all servers", async () => { - await expect(mcpService.stopAllServers()).resolves.not.toThrow(); + await expect(mcpService.shutdownConnections()).resolves.not.toThrow(); }); it("should handle server not found error", async () => { @@ -123,10 +115,6 @@ describe("MCPService", () => { await expect(mcpService.stopServer("test-server")).resolves.not.toThrow(); }); - it("should return null for nonexistent server info", () => { - const info = mcpService.getServerInfo("nonexistent"); - expect(info).toBeNull(); - }); }); describe("tools and prompts", () => { @@ -135,11 +123,8 @@ describe("MCPService", () => { }); it("should return empty arrays for tools and prompts initially", () => { - const tools = mcpService.getTools(); - const prompts = mcpService.getPrompts(); - - expect(Array.isArray(tools)).toBe(true); - expect(Array.isArray(prompts)).toBe(true); + expect(Array.isArray(mcpService.getState().tools)).toBe(true); + expect(Array.isArray(mcpService.getState().tools)).toBe(true); }); it("should throw error for unknown tool", async () => { diff --git a/src/services/MCPService.ts b/src/services/MCPService.ts index 104500092..da56e0712 100644 --- a/src/services/MCPService.ts +++ b/src/services/MCPService.ts @@ -6,39 +6,25 @@ import { getErrorString } from "../util/error.js"; import { logger } from "../util/logger.js"; import { BaseService, ServiceWithDependencies } from "./BaseService.js"; -import { MCPServiceState, SERVICE_NAMES } from "./types.js"; +import { serviceContainer } from "./ServiceContainer.js"; +import { + MCPConnectionInfo, + MCPServiceState, + SERVICE_NAMES, + MCPServerConfig, +} from "./types.js"; -export type MCPServerStatus = "idle" | "connecting" | "connected" | "error"; -export type MCPTool = Awaited>["tools"][number]; -type MCPServerConfig = NonNullable< - NonNullable[number] ->; - -interface ServerConnection { - config: MCPServerConfig; - status: MCPServerStatus; +interface ServerConnection extends MCPConnectionInfo { client: Client | null; - prompts: Awaited>["prompts"]; - tools: MCPTool[]; - error?: string; - warnings: string[]; -} - -export interface MCPConnectionInfo { - config: MCPServerConfig; - status: MCPServerStatus; - toolNames: string[]; - promptNames: string[]; - error?: string; - warnings: string[]; } export const EMPTY_MCP_STATE: MCPServiceState = { mcpService: null, connections: [], - toolCount: 0, - promptCount: 0, + tools: [], + prompts: [], }; + export class MCPService extends BaseService implements ServiceWithDependencies @@ -94,12 +80,14 @@ export class MCPService logger.debug("MCP connections established", { connectionCount: connections.length, }); + this.updateState(); }, ); if (waitForConnections) { await connectionInit; + } else { + this.updateState(); } - this.updateState(); return this.currentState; } @@ -107,24 +95,24 @@ export class MCPService /** * Update internal state based on current connections */ - private updateState(): void { - const connections = Array.from(this.connections.values()); - const connectedConnections = connections.filter( + private updateState() { + const connections: MCPConnectionInfo[] = Array.from( + this.connections.values(), + ).map(({ client: _, ...rest }) => rest); + const connectedServers = connections.filter( (c) => c.status === "connected", ); + const tools = connectedServers.flatMap((s) => s.tools); + const prompts = connectedServers.flatMap((s) => s.prompts); - this.setState({ + const newState: MCPServiceState = { mcpService: this, - connections: this.getConnectionInfo(), - toolCount: connectedConnections.reduce( - (sum, c) => sum + c.tools.length, - 0, - ), - promptCount: connectedConnections.reduce( - (sum, c) => sum + c.prompts.length, - 0, - ), - }); + connections, + tools, + prompts, + }; + this.setState(newState); + serviceContainer.set(SERVICE_NAMES.MCP, newState); } /** @@ -134,20 +122,6 @@ export class MCPService return { ...this.currentState }; } - /** - * Get connection information for display - */ - getConnectionInfo(): MCPConnectionInfo[] { - return Array.from(this.connections.values()).map((connection) => ({ - config: connection.config, - status: connection.status, - toolNames: connection.tools.map((tool) => tool.name), - promptNames: connection.prompts.map((prompt) => prompt.name), - error: connection.error, - warnings: connection.warnings, - })); - } - /** * Get overall status for UI indicator */ @@ -171,47 +145,6 @@ export class MCPService return { status: "idle", hasWarnings }; } - /** - * Get MCP service information for display - */ - getMCPInfo(): { - toolNames: string[]; - promptNames: string[]; - connectionCount: number; - } { - const connectedConnections = Array.from(this.connections.values()).filter( - (c) => c.status === "connected", - ); - - return { - toolNames: connectedConnections.flatMap((connection) => - connection.tools.map((tool) => tool.name), - ), - promptNames: connectedConnections.flatMap((connection) => - connection.prompts.map((prompt) => prompt.name), - ), - connectionCount: this.connections.size, - }; - } - - /** - * Get all prompts from connected servers only - */ - public getPrompts() { - return Array.from(this.connections.values()) - .filter((connection) => connection.status === "connected") - .flatMap((connection) => connection.prompts); - } - - /** - * Get all tools from connected servers only - */ - public getTools() { - return Array.from(this.connections.values()) - .filter((connection) => connection.status === "connected") - .flatMap((connection) => connection.tools); - } - /** * Run a tool by name */ @@ -239,16 +172,6 @@ export class MCPService logger.debug("Restarting all MCP servers"); await this.shutdownConnections(); await this.initialize(this.assistant); - this.updateState(); - } - - /** - * Stop all servers - */ - public async stopAllServers(): Promise { - logger.debug("Stopping all MCP servers"); - await this.shutdownConnections(); - this.updateState(); } /** @@ -323,10 +246,10 @@ export class MCPService }); await client.connect(transport, {}); - // client.setLoggingLevel("critical"); connection.client = client; connection.status = "connected"; + this.updateState(); const capabilities = client.getServerCapabilities(); logger.debug("MCP server capabilities", { @@ -395,32 +318,15 @@ export class MCPService } } - /** - * Get a specific server connection info - */ - public getServerInfo(serverName: string): MCPConnectionInfo | null { - const connection = this.connections.get(serverName); - if (!connection) return null; - - return { - config: connection.config, - status: connection.status, - toolNames: connection.tools.map((tool) => tool.name), - promptNames: connection.prompts.map((prompt) => prompt.name), - error: connection.error, - warnings: connection.warnings, - }; - } - /** * Shutdown all connections */ - private async shutdownConnections(): Promise { + public async shutdownConnections(): Promise { const shutdownPromises = Array.from(this.connections.values()).map( (connection) => this.shutdownConnection(connection), ); - await Promise.all(shutdownPromises); + this.updateState(); } /** @@ -456,6 +362,5 @@ export class MCPService this.removeAllListeners(); logger.debug("Shutting down MCPService"); await this.shutdownConnections(); - this.updateState(); } } diff --git a/src/services/types.ts b/src/services/types.ts index a670ec2e4..11dd1ce79 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -1,11 +1,13 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; +import { AssistantConfig } from "@continuedev/sdk"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { AuthConfig } from "../auth/workos.js"; import { PermissionMode, ToolPermissions } from "../permissions/types.js"; -import { MCPConnectionInfo, MCPService } from "./MCPService.js"; +import { MCPService } from "./MCPService.js"; /** * Service lifecycle states @@ -51,11 +53,29 @@ export interface ModelServiceState { model: ModelConfig | null; } +export type MCPServerStatus = "idle" | "connecting" | "connected" | "error"; +export type MCPTool = Awaited>["tools"][number]; +export type MCPPrompt = Awaited< + ReturnType +>["prompts"][number]; +export type MCPServerConfig = NonNullable< + NonNullable[number] +>; + +export interface MCPConnectionInfo { + config: MCPServerConfig; + status: MCPServerStatus; + tools: MCPTool[]; + prompts: MCPPrompt[]; + error?: string; + warnings: string[]; +} + export interface MCPServiceState { mcpService: MCPService | null; connections: Array; - toolCount: number; - promptCount: number; + tools: MCPTool[]; + prompts: MCPPrompt[]; } export interface ApiClientServiceState { diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index 0e0187525..16097cda2 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -11,9 +11,9 @@ import { filterExcludedTools } from "./permissions/index.js"; import { getServiceSync, MCPServiceState, + MCPTool, SERVICE_NAMES, } from "./services/index.js"; -import { MCPTool } from "./services/MCPService.js"; import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js"; import { processChunkContent, @@ -131,8 +131,7 @@ export async function getAllTools() { SERVICE_NAMES.TOOL_PERMISSIONS, ); if (mcpServiceResult.state === "ready") { - mcpTools = mcpServiceResult?.value?.mcpService?.getTools() ?? []; - + mcpTools = mcpServiceResult?.value?.tools ?? []; mcpToolNames = mcpTools.map((t) => t.name); } else { // MCP is lazy diff --git a/src/tools/index.ts b/src/tools/index.ts index 2bc20cc48..aa0f1b969 100644 --- a/src/tools/index.ts +++ b/src/tools/index.ts @@ -123,7 +123,7 @@ export async function getAvailableTools() { const mcpState = await serviceContainer.get( SERVICE_NAMES.MCP, ); - const tools = mcpState.mcpService?.getTools() ?? []; + const tools = mcpState.tools ?? []; const mcpTools: Tool[] = tools.map((t) => ({ name: t.name, diff --git a/src/ui/IntroMessage.tsx b/src/ui/IntroMessage.tsx index bfa4787bb..7a5e6ec38 100644 --- a/src/ui/IntroMessage.tsx +++ b/src/ui/IntroMessage.tsx @@ -20,7 +20,7 @@ const IntroMessage: React.FC = ({ model, mcpService, }) => { - const mcpPrompts = mcpService.getPrompts() ?? []; + const mcpPrompts = mcpService.getState().prompts ?? []; // Get all slash commands from central definition const allCommands = getAllSlashCommands(config); diff --git a/src/ui/MCPSelector.tsx b/src/ui/MCPSelector.tsx index e89fa5cc9..fb84a4c60 100644 --- a/src/ui/MCPSelector.tsx +++ b/src/ui/MCPSelector.tsx @@ -77,14 +77,13 @@ export const MCPSelector: React.FC = ({ onCancel }) => { if (connections.length > 0) { connections.forEach((conn) => { const { icon } = getServerStatusDisplay(conn); - const serverInfo = mcpService?.getServerInfo(conn.config.name); let serverLabel = `${icon} ${conn.config.name}`; // Add tools and prompts count if server is connected - if (serverInfo && serverInfo.status === "connected") { - const toolsCount = serverInfo.toolNames.length; - const promptsCount = serverInfo.promptNames.length; + if (conn.status === "connected") { + const toolsCount = conn.tools.length; + const promptsCount = conn.prompts.length; const counts = []; if (toolsCount > 0) { @@ -118,7 +117,9 @@ export const MCPSelector: React.FC = ({ onCancel }) => { const getServerDetailItems = (): MCPMenuItem[] => { if (!selectedServer) return []; - const serverInfo = mcpService?.getServerInfo(selectedServer); + const serverInfo = connections.find( + (conn) => conn.config.name === selectedServer, + ); if (!serverInfo) return []; const items: MCPMenuItem[] = [ @@ -135,7 +136,9 @@ export const MCPSelector: React.FC = ({ onCancel }) => { const getServerInfoDisplay = () => { if (menuState !== "server-detail" || !selectedServer) return null; - const serverInfo = mcpService?.getServerInfo(selectedServer); + const serverInfo = connections.find( + (conn) => conn.config.name === selectedServer, + ); if (!serverInfo) return null; return ( @@ -165,26 +168,24 @@ export const MCPSelector: React.FC = ({ onCancel }) => { )} {/* Add prompts if any */} - {serverInfo.promptNames.length > 0 && ( + {serverInfo.prompts.length > 0 && ( - - 📝 Prompts: {serverInfo.promptNames.length} - - {serverInfo.promptNames.map((name, index) => ( + 📝 Prompts: {serverInfo.prompts.length} + {serverInfo.prompts.map((prompt, index) => ( - • {name} + • {prompt.name} ))} )} {/* Add tools if any */} - {serverInfo.toolNames.length > 0 && ( + {serverInfo.tools.length > 0 && ( - 🔧 Tools: {serverInfo.toolNames.length} - {serverInfo.toolNames.map((name, index) => ( + 🔧 Tools: {serverInfo.tools.length} + {serverInfo.tools.map((tool, index) => ( - • {name} + • {tool.name} ))} @@ -268,7 +269,7 @@ export const MCPSelector: React.FC = ({ onCancel }) => { setMessage("All servers restarted"); break; case "stop-all": - await mcpService.stopAllServers(); + await mcpService.shutdownConnections(); setMessage("All servers stopped"); break; case "back": @@ -312,7 +313,9 @@ export const MCPSelector: React.FC = ({ onCancel }) => { {menuState === "server-detail" && selectedServer && (() => { - const serverInfo = mcpService?.getServerInfo(selectedServer); + const serverInfo = connections.find( + (conn) => conn.config.name === selectedServer, + ); if (!serverInfo) return null; const { color: statusColor, statusText } =