diff --git a/src/commands/commands.ts b/src/commands/commands.ts index ab0569f11..407b74c4a 100644 --- a/src/commands/commands.ts +++ b/src/commands/commands.ts @@ -57,6 +57,11 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [ description: "Switch configuration", category: "system", }, + { + name: "mcp", + description: "Manage MCP server connections", + category: "system", + }, ]; // Remote mode specific commands diff --git a/src/mcp.test.ts b/src/mcp.test.ts new file mode 100644 index 000000000..94e08d4df --- /dev/null +++ b/src/mcp.test.ts @@ -0,0 +1,191 @@ +import { + describe, + it, + expect, + beforeEach, + afterEach, + jest, +} from "@jest/globals"; +import { AssistantConfig } from "@continuedev/sdk"; +import { MCPService } from "./mcp.js"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; + +// Mock the logger +jest.mock("./src/util/logger", () => ({ + default: { + debug: jest.fn(), + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + }, +})); + +// Mock the MCP SDK +const mockClient = { + connect: jest.fn(), + getServerCapabilities: jest.fn(() => ({ prompts: true, tools: true })), + listPrompts: jest.fn(() => Promise.resolve({ prompts: [] })), + listTools: jest.fn(() => Promise.resolve({ tools: [] })), + callTool: jest.fn(() => Promise.resolve({})), + close: jest.fn(() => Promise.resolve()), +}; + +jest.mock("@modelcontextprotocol/sdk/client/index.js", () => ({ + Client: jest.fn(() => mockClient), +})); + +jest.mock("@modelcontextprotocol/sdk/client/stdio.js", () => ({ + StdioClientTransport: jest.fn(), +})); + +describe("MCPService", () => { + let mcpService: MCPService; + let mockAssistant: AssistantConfig; + + beforeEach(() => { + mcpService = new MCPService(); + mockAssistant = { + name: "test-assistant", + version: "1.0.0", + mcpServers: [ + { + name: "test-server", + command: "echo", + args: ["hello"], + env: { TEST: "value" }, + }, + ], + } as AssistantConfig; + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + describe("initialization", () => { + it("should initialize with empty state", () => { + const state = mcpService.getState(); + expect(state.isReady).toBe(false); + expect(state.connections).toEqual([]); + expect(state.toolCount).toBe(0); + expect(state.promptCount).toBe(0); + }); + + it("should initialize with no servers", async () => { + const emptyAssistant = { + name: "empty", + version: "1.0.0", + } as AssistantConfig; + const state = await mcpService.initialize(emptyAssistant); + + expect(state.isReady).toBe(true); + expect(state.connections).toEqual([]); + expect(state.toolCount).toBe(0); + expect(state.promptCount).toBe(0); + }); + + it("should initialize and return immediately even with server configs", async () => { + const state = await mcpService.initialize(mockAssistant); + + // Should return immediately with ready state + expect(state.isReady).toBe(true); + expect(state.mcpService).toBe(mcpService); + }); + }); + + describe("service management", () => { + beforeEach(async () => { + await mcpService.initialize(mockAssistant); + }); + + it("should provide service info", () => { + const info = mcpService.getMCPInfo(); + expect(info).toHaveProperty("toolCount"); + expect(info).toHaveProperty("promptCount"); + expect(info).toHaveProperty("connectionCount"); + }); + + it("should handle service updates", async () => { + const newAssistant = { + name: "updated-assistant", + version: "1.0.0", + mcpServers: [], + } as AssistantConfig; + + const state = await mcpService.update(newAssistant); + expect(state.isReady).toBe(true); + }); + + it("should get overall status with no connections", () => { + const status = mcpService.getOverallStatus(); + expect(status.status).toBe("idle"); + expect(status.hasWarnings).toBe(false); + }); + }); + + describe("server management", () => { + beforeEach(async () => { + await mcpService.initialize(mockAssistant); + }); + + it("should handle restart all servers", async () => { + await expect(mcpService.restartAllServers()).resolves.not.toThrow(); + }); + + it("should handle stop all servers", async () => { + await expect(mcpService.stopAllServers()).resolves.not.toThrow(); + }); + + it("should handle server not found error", async () => { + await expect(mcpService.restartServer("nonexistent")).rejects.toThrow( + "Server nonexistent not found in configuration" + ); + }); + + it("should handle stop individual server", async () => { + 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", () => { + beforeEach(async () => { + await mcpService.initialize(mockAssistant); + }); + + 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); + }); + + it("should throw error for unknown tool", async () => { + await expect(mcpService.runTool("unknown-tool", {})).rejects.toThrow( + "Tool unknown-tool not found" + ); + }); + }); + + describe("shutdown", () => { + it("should handle shutdown gracefully", async () => { + await mcpService.initialize(mockAssistant); + await expect(mcpService.shutdown()).resolves.not.toThrow(); + + const state = mcpService.getState(); + expect(state.isReady).toBe(false); + expect(state.mcpService).toBeNull(); + }); + + it("should handle multiple shutdown calls", async () => { + await mcpService.initialize(mockAssistant); + await mcpService.shutdown(); + await expect(mcpService.shutdown()).resolves.not.toThrow(); + }); + }); +}); diff --git a/src/mcp.ts b/src/mcp.ts index bc52f0a9b..494128d31 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -4,18 +4,23 @@ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js" import logger from "./util/logger.js"; import { MCPServiceState } from "./services/types.js"; +export type MCPServerStatus = "idle" | "connecting" | "connected" | "error"; + export interface MCPConnectionInfo { + name: string; command: string; - status: 'connected' | 'disconnected' | 'error'; + status: MCPServerStatus; toolCount: number; promptCount: number; error?: Error; + warnings: string[]; } export class MCPService { - private connections: MCPConnection[] = []; + private connections: Map = new Map(); private currentState: MCPServiceState; private assistant: AssistantConfig | null = null; + private isShuttingDown = false; constructor() { this.currentState = { @@ -23,57 +28,103 @@ export class MCPService { connections: [], toolCount: 0, promptCount: 0, - isReady: false + isReady: false, }; + + // Register shutdown handler + process.on("exit", () => this.shutdown()); + process.on("SIGINT", () => this.shutdown()); + process.on("SIGTERM", () => this.shutdown()); } /** * Initialize the MCP service */ async initialize(assistant: AssistantConfig): Promise { - logger.debug('Initializing MCPService'); - - try { - this.assistant = assistant; - this.connections = []; - - if (assistant.mcpServers?.length) { - logger.debug('Creating MCP connections', { serverCount: assistant.mcpServers.length }); - const connectionPromises = assistant.mcpServers.map((server) => - MCPConnection.create(server) - ); - const connections = await Promise.all(connectionPromises); - this.connections.push(...connections); - logger.debug('MCP connections established', { connectionCount: connections.length }); - } + logger.debug("Initializing MCPService"); - this.currentState = { - mcpService: this, - connections: this.getConnectionInfo(), - toolCount: this.getTools().length, - promptCount: this.getPrompts().length, - isReady: true - }; + this.assistant = assistant; + this.connections.clear(); - logger.debug('MCPService initialized successfully', { - toolCount: this.currentState.toolCount, - promptCount: this.currentState.promptCount, - connectionCount: this.connections.length + // Service initialization should not block on server connections + if (assistant.mcpServers?.length) { + logger.debug("Starting MCP server connections", { + serverCount: assistant.mcpServers.length, }); - return this.currentState; - } catch (error: any) { - logger.error('Failed to initialize MCPService:', error); - this.currentState = { - mcpService: null, - connections: [], - toolCount: 0, - promptCount: 0, - isReady: false, - error - }; - throw error; + // Initialize all servers simultaneously without blocking + const connectionPromises = assistant.mcpServers.map( + async (serverConfig, index) => { + if (!serverConfig) return; + + const serverName = serverConfig.name || `server-${index}`; + try { + const connection = await MCPConnection.create( + serverConfig, + serverName + ); + this.connections.set(serverName, connection); + logger.debug("MCP server connected", { + name: serverName, + command: serverConfig.command, + }); + } catch (error: any) { + logger.error("MCP server connection failed", { + name: serverName, + error: error.message, + }); + // Create a failed connection entry + const failedConnection = new MCPConnection( + null, + serverConfig.command || "unknown", + serverName + ); + failedConnection.status = "error"; + failedConnection.error = error; + this.connections.set(serverName, failedConnection); + } + } + ); + + // Don't await - let connections happen in background + Promise.all(connectionPromises) + .then(() => { + this.updateState(); + logger.debug("All MCP server connections completed"); + }) + .catch(() => { + // Individual errors are already handled above + this.updateState(); + }); } + + // Return immediately with current state + this.updateState(); + return this.currentState; + } + + /** + * Update internal state based on current connections + */ + private updateState(): void { + const connections = Array.from(this.connections.values()); + const connectedConnections = connections.filter( + (c) => c.status === "connected" + ); + + this.currentState = { + 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 + ), + isReady: true, + }; } /** @@ -87,17 +138,12 @@ export class MCPService { * Update the MCP service with a new assistant config */ async update(assistant: AssistantConfig): Promise { - logger.debug('Updating MCPService'); - - try { - // Close existing connections - this.connections = []; - - return await this.initialize(assistant); - } catch (error: any) { - logger.error('Failed to update MCPService:', error); - throw error; - } + logger.debug("Updating MCPService"); + + // Shutdown existing connections + await this.shutdownConnections(); + + return await this.initialize(assistant); } /** @@ -111,98 +157,365 @@ export class MCPService { * Get connection information for display */ getConnectionInfo(): MCPConnectionInfo[] { - return this.connections.map(connection => ({ + return Array.from(this.connections.values()).map((connection) => ({ + name: connection.name, command: connection.command, - status: 'connected', + status: connection.status, toolCount: connection.tools.length, - promptCount: connection.prompts.length + promptCount: connection.prompts.length, + error: connection.error, + warnings: connection.warnings, })); } + /** + * Get overall status for UI indicator + */ + getOverallStatus(): { + status: "idle" | "connecting" | "connected" | "error"; + hasWarnings: boolean; + } { + const connections = Array.from(this.connections.values()); + + if (connections.length === 0) { + return { status: "idle", hasWarnings: false }; + } + + const hasConnecting = connections.some((c) => c.status === "connecting"); + const hasError = connections.some((c) => c.status === "error"); + const hasConnected = connections.some((c) => c.status === "connected"); + const hasWarnings = connections.some((c) => c.warnings.length > 0); + + if (hasConnecting) { + return { status: "connecting", hasWarnings }; + } + if (hasError) { + return { status: "error", hasWarnings }; + } + if (hasConnected) { + return { status: "connected", hasWarnings }; + } + + return { status: "idle", hasWarnings }; + } + /** * Get MCP service information for display */ - getMCPInfo(): { toolCount: number; promptCount: number; connectionCount: number } { + getMCPInfo(): { + toolCount: number; + promptCount: number; + connectionCount: number; + } { return { toolCount: this.currentState.toolCount, promptCount: this.currentState.promptCount, - connectionCount: this.connections.length + connectionCount: this.connections.size, }; } + /** + * Get all prompts from connected servers only + */ public getPrompts() { - return this.connections.flatMap((connection) => connection.prompts); + 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 this.connections.flatMap((connection) => connection.tools); + return Array.from(this.connections.values()) + .filter((connection) => connection.status === "connected") + .flatMap((connection) => connection.tools); } + /** + * Run a tool by name + */ public async runTool(name: string, args: Record) { - for (const connection of this.connections) { - const tool = connection.tools.find((t) => t.name === name); - if (tool) { - return await connection.client.callTool({ - name, - arguments: args, - }); + for (const connection of this.connections.values()) { + if (connection.status === "connected" && connection.client) { + const tool = connection.tools.find((t) => t.name === name); + if (tool) { + return await connection.client.callTool({ + name, + arguments: args, + }); + } } } throw new Error(`Tool ${name} not found`); } + + /** + * Restart all servers + */ + public async restartAllServers(): Promise { + if (!this.assistant) return; + + logger.debug("Restarting all MCP servers"); + await this.shutdownConnections(); + await this.initialize(this.assistant); + } + + /** + * Stop all servers + */ + public async stopAllServers(): Promise { + logger.debug("Stopping all MCP servers"); + await this.shutdownConnections(); + this.updateState(); + } + + /** + * Restart a specific server + */ + public async restartServer(serverName: string): Promise { + if (!this.assistant || !this.assistant.mcpServers) return; + + const serverConfig = this.assistant.mcpServers.find( + (s, index) => s && (s.name || `server-${index}`) === serverName + ); + + if (!serverConfig) { + throw new Error(`Server ${serverName} not found in configuration`); + } + + logger.debug("Restarting MCP server", { name: serverName }); + + // Stop existing connection + const existingConnection = this.connections.get(serverName); + if (existingConnection) { + await this.shutdownConnection(existingConnection); + } + + // Start new connection + try { + const connection = await MCPConnection.create(serverConfig, serverName); + this.connections.set(serverName, connection); + logger.debug("MCP server restarted successfully", { name: serverName }); + } catch (error: any) { + logger.error("Failed to restart MCP server", { + name: serverName, + error: error.message, + }); + const failedConnection = new MCPConnection( + null, + serverConfig.command || "unknown", + serverName + ); + failedConnection.status = "error"; + failedConnection.error = error; + this.connections.set(serverName, failedConnection); + } + + this.updateState(); + } + + /** + * Stop a specific server + */ + public async stopServer(serverName: string): Promise { + logger.debug("Stopping MCP server", { name: serverName }); + + const connection = this.connections.get(serverName); + if (connection) { + await this.shutdownConnection(connection); + this.connections.delete(serverName); + } + + this.updateState(); + } + + /** + * Get a specific server connection info + */ + public getServerInfo(serverName: string): MCPConnectionInfo | null { + const connection = this.connections.get(serverName); + if (!connection) return null; + + return { + name: connection.name, + command: connection.command, + status: connection.status, + toolCount: connection.tools.length, + promptCount: connection.prompts.length, + error: connection.error, + warnings: connection.warnings, + }; + } + + /** + * Shutdown all connections + */ + private async shutdownConnections(): Promise { + const shutdownPromises = Array.from(this.connections.values()).map( + (connection) => this.shutdownConnection(connection) + ); + + await Promise.all(shutdownPromises); + this.connections.clear(); + } + + /** + * Shutdown a single connection + */ + private async shutdownConnection(connection: MCPConnection): Promise { + try { + if (connection.client) { + await connection.client.close(); + } + } catch (error: any) { + logger.warn("Error shutting down MCP connection", { + name: connection.name, + error: error.message, + }); + } + } + + /** + * Shutdown the entire service + */ + public async shutdown(): Promise { + if (this.isShuttingDown) return; + + this.isShuttingDown = true; + logger.debug("Shutting down MCPService"); + + await this.shutdownConnections(); + + this.currentState = { + mcpService: null, + connections: [], + toolCount: 0, + promptCount: 0, + isReady: false, + }; + } } export class MCPConnection { - prompts: Awaited>["prompts"] = []; - tools: Awaited>["tools"] = []; + public prompts: Awaited>["prompts"] = []; + public tools: Awaited>["tools"] = []; + public status: MCPServerStatus = "idle"; + public error?: Error; + public warnings: string[] = []; public readonly command: string; + public readonly name: string; - private constructor(public readonly client: Client, command: string) { + constructor( + public readonly client: Client | null, + command: string, + name: string + ) { this.command = command; + this.name = name; } public static async create( - config: NonNullable[number] - ) { - const client = new Client( - { - name: "continue-cli-client", - version: "1.0.0", - }, - { capabilities: {} } + config: NonNullable[number], + name: string + ): Promise { + if (!config) { + throw new Error("MCP server config is null"); + } + + const connection = new MCPConnection( + null, + config.command || "unknown", + name ); + connection.status = "connecting"; - // Construct transport - const env: Record = config?.env || {}; - if (process.env.PATH !== undefined) { - env.PATH = process.env.PATH; + try { + const client = new Client( + { + name: "continue-cli-client", + version: "1.0.0", + }, + { capabilities: {} } + ); + + // Construct transport + const env: Record = config.env || {}; + if (process.env.PATH !== undefined) { + env.PATH = process.env.PATH; + } + + if (!config.command) { + throw new Error("MCP server command is not specified"); + } + + const transport = new StdioClientTransport({ + command: config.command, + args: config.args, + env, + }); + + // Connect + logger.debug("Connecting to MCP server", { + name, + command: config.command, + }); + await client.connect(transport); + + // Update connection with successful client + (connection as any).client = client; + connection.status = "connected"; + + const capabilities = client.getServerCapabilities(); + logger.debug("MCP server capabilities", { + name, + hasPrompts: !!capabilities?.prompts, + hasTools: !!capabilities?.tools, + }); + + // Load prompts + if (capabilities?.prompts) { + try { + connection.prompts = (await client.listPrompts()).prompts; + logger.debug("Loaded MCP prompts", { + name, + count: connection.prompts.length, + }); + } catch (error: any) { + connection.warnings.push(`Failed to load prompts: ${error.message}`); + logger.warn("Failed to load MCP prompts", { + name, + error: error.message, + }); + } + } + + // Load tools + if (capabilities?.tools) { + try { + connection.tools = (await client.listTools()).tools; + logger.debug("Loaded MCP tools", { + name, + count: connection.tools.length, + }); + } catch (error: any) { + connection.warnings.push(`Failed to load tools: ${error.message}`); + logger.warn("Failed to load MCP tools", { + name, + error: error.message, + }); + } + } + + return connection; + } catch (error: any) { + connection.status = "error"; + connection.error = error; + logger.error("Failed to connect to MCP server", { + name, + error: error.message, + }); + throw error; } - - if (!config?.command) { - throw new Error("MCP server command is not specified"); - } - - const transport = new StdioClientTransport({ - command: config.command, - args: config?.args, - env, - }); - - // Connect and get all prompts and tools - const connection = new MCPConnection(client, config.command); - logger.debug('Connecting to MCP server', { command: config.command }); - await client.connect(transport); - const capabilities = client.getServerCapabilities(); - logger.debug('MCP server capabilities', { hasPrompts: !!capabilities?.prompts, hasTools: !!capabilities?.tools }); - - if (capabilities?.prompts) { - connection.prompts = (await client.listPrompts()).prompts; - } - - if (capabilities?.tools) { - connection.tools = (await client.listTools()).tools; - } - - return connection; } } diff --git a/src/services/types.ts b/src/services/types.ts index 5e22f2b27..9db9aadfe 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -52,11 +52,13 @@ export interface ModelServiceState { export interface MCPServiceState { mcpService: MCPService | null; connections: Array<{ + name: string; command: string; - status: 'connected' | 'disconnected' | 'error'; + status: 'idle' | 'connecting' | 'connected' | 'error'; toolCount: number; promptCount: number; error?: Error; + warnings: string[]; }>; toolCount: number; promptCount: number; diff --git a/src/slashCommands.ts b/src/slashCommands.ts index ce7afaade..345fc3113 100644 --- a/src/slashCommands.ts +++ b/src/slashCommands.ts @@ -20,6 +20,7 @@ export async function handleSlashCommands( clear?: boolean; openConfigSelector?: boolean; openModelSelector?: boolean; + openMCPSelector?: boolean; } | null> { // Only trigger slash commands if slash is the very first character if (input.startsWith("/") && input.trim().startsWith("/")) { @@ -129,6 +130,12 @@ export async function handleSlashCommands( // Open model selector UI return { openModelSelector: true }; + case "mcp": + posthogService.capture("useSlashCommand", { + name: "mcp", + }); + // Open MCP management UI + return { openMCPSelector: true }; case "org": posthogService.capture("useSlashCommand", { diff --git a/src/ui/MCPSelector.tsx b/src/ui/MCPSelector.tsx new file mode 100644 index 000000000..9ca1dc04c --- /dev/null +++ b/src/ui/MCPSelector.tsx @@ -0,0 +1,354 @@ +import { Box, Text, useInput } from "ink"; +import React, { useState } from "react"; +import { useServices } from "../hooks/useService.js"; +import { MCPServiceState } from "../services/types.js"; + +interface MCPSelectorProps { + onCancel: () => void; +} + +type MCPMenuState = "main" | "servers" | "server-detail"; + +interface MCPMenuItem { + label: string; + value: string; + disabled?: boolean; +} + +const MCPSelector: React.FC = ({ onCancel }) => { + const [menuState, setMenuState] = useState("main"); + const [selectedServer, setSelectedServer] = useState(null); + const [selectedIndex, setSelectedIndex] = useState(0); + const [isLoading, setIsLoading] = useState(false); + const [message, setMessage] = useState(null); + + const { services } = useServices<{ mcp: MCPServiceState }>(["mcp"]); + const mcpService = services.mcp?.mcpService; + + const handleBack = () => { + if (menuState === "server-detail") { + setSelectedServer(null); + setMenuState("servers"); + } else if (menuState === "servers") { + setMenuState("main"); + } else { + onCancel(); + } + setSelectedIndex(0); + setMessage(null); + }; + + // Main menu items + const getMainMenuItems = (): MCPMenuItem[] => { + const connections = services.mcp?.connections || []; + + if (connections.length === 0) { + return [ + { label: "No servers configured", value: "no-servers", disabled: true }, + { label: "← Back", value: "back" }, + ]; + } + + return [ + { label: "🔄 Restart all servers", value: "restart-all" }, + { label: "âšī¸ Stop all servers", value: "stop-all" }, + { label: "đŸ‘ī¸ View servers", value: "view-servers" }, + { label: "← Back", value: "back" }, + ]; + }; + + // Server list items + const getServerItems = (): MCPMenuItem[] => { + const connections = services.mcp?.connections || []; + + if (connections.length === 0) { + return [ + { label: "No servers", value: "no-servers", disabled: true }, + { label: "← Back", value: "back" }, + ]; + } + + const serverItems = connections.map((conn) => { + let statusIcon = "âšĒ"; // idle + if (conn.status === "connecting") statusIcon = "🟡"; + else if (conn.status === "error") statusIcon = "🔴"; + else if (conn.status === "connected") { + statusIcon = conn.warnings.length > 0 ? "🟡" : "đŸŸĸ"; + } + + return { + label: `${statusIcon} ${conn.name}`, + value: conn.name, + }; + }); + + return [...serverItems, { label: "← Back", value: "back" }]; + }; + + // Server detail items + const getServerDetailItems = (): MCPMenuItem[] => { + if (!selectedServer) return []; + + const serverInfo = mcpService?.getServerInfo(selectedServer); + if (!serverInfo) return []; + + const items: MCPMenuItem[] = [ + { label: "🔄 Restart server", value: "restart" }, + { label: "âšī¸ Stop server", value: "stop" }, + ]; + + // Add warnings if any + if (serverInfo.warnings.length > 0) { + items.push({ label: "", value: "spacer", disabled: true }); + items.push({ + label: "âš ī¸ Warnings:", + value: "warnings-header", + disabled: true, + }); + serverInfo.warnings.forEach((warning, index) => { + items.push({ + label: ` ${warning}`, + value: `warning-${index}`, + disabled: true, + }); + }); + } + + // Add prompts if any + if (serverInfo.promptCount > 0) { + items.push({ label: "", value: "spacer2", disabled: true }); + items.push({ + label: `📝 Prompts (${serverInfo.promptCount}):`, + value: "prompts-header", + disabled: true, + }); + } + + // Add tools if any + if (serverInfo.toolCount > 0) { + items.push({ label: "", value: "spacer3", disabled: true }); + items.push({ + label: `🔧 Tools (${serverInfo.toolCount}):`, + value: "tools-header", + disabled: true, + }); + } + + items.push({ label: "", value: "spacer4", disabled: true }); + items.push({ label: "← Back", value: "back" }); + + return items; + }; + + let items: MCPMenuItem[] = []; + + switch (menuState) { + case "main": + items = getMainMenuItems(); + break; + case "servers": + items = getServerItems(); + break; + case "server-detail": + items = getServerDetailItems(); + break; + } + + // Filter out disabled items for navigation + const navigableItems = items.filter((item) => !item.disabled); + const maxIndex = Math.max(0, navigableItems.length - 1); + + useInput(async (input, key) => { + if (isLoading) return; + + if (key.escape) { + handleBack(); + return; + } + + if (key.upArrow) { + const currentNavigableIndex = navigableItems.findIndex( + (item) => item === items[selectedIndex] + ); + const newNavigableIndex = Math.max(0, currentNavigableIndex - 1); + const newIndex = items.findIndex( + (item) => item === navigableItems[newNavigableIndex] + ); + setSelectedIndex(newIndex); + return; + } + + if (key.downArrow) { + const currentNavigableIndex = navigableItems.findIndex( + (item) => item === items[selectedIndex] + ); + const newNavigableIndex = Math.min(maxIndex, currentNavigableIndex + 1); + const newIndex = items.findIndex( + (item) => item === navigableItems[newNavigableIndex] + ); + setSelectedIndex(newIndex); + return; + } + + if (key.return) { + const selectedItem = items[selectedIndex]; + if (!selectedItem || selectedItem.disabled) return; + + setIsLoading(true); + setMessage(null); + + try { + switch (menuState) { + case "main": + await handleMainMenuSelect(selectedItem.value); + break; + case "servers": + handleServerSelect(selectedItem.value); + break; + case "server-detail": + await handleServerAction(selectedItem.value); + break; + } + } catch (error: any) { + setMessage(`Error: ${error.message}`); + } finally { + setIsLoading(false); + } + } + }); + + const handleMainMenuSelect = async (value: string) => { + if (!mcpService) return; + + switch (value) { + case "restart-all": + await mcpService.restartAllServers(); + setMessage("All servers restarted successfully"); + break; + case "stop-all": + await mcpService.stopAllServers(); + setMessage("All servers stopped"); + break; + case "view-servers": + setMenuState("servers"); + setSelectedIndex(0); + break; + case "back": + onCancel(); + return; + } + }; + + const handleServerSelect = (value: string) => { + if (value === "back") { + handleBack(); + } else if (value !== "no-servers") { + setSelectedServer(value); + setMenuState("server-detail"); + setSelectedIndex(0); + } + }; + + const handleServerAction = async (action: string) => { + if (!mcpService || !selectedServer) return; + + switch (action) { + case "restart": + await mcpService.restartServer(selectedServer); + setMessage(`Server "${selectedServer}" restarted successfully`); + break; + case "stop": + await mcpService.stopServer(selectedServer); + setMessage(`Server "${selectedServer}" stopped`); + break; + case "back": + handleBack(); + return; + } + }; + + const renderHeader = () => { + let title = "MCP Management"; + let subtitle = ""; + + if (menuState === "servers") { + title = "MCP Servers"; + } else if (menuState === "server-detail" && selectedServer) { + const serverInfo = mcpService?.getServerInfo(selectedServer); + title = `Server: ${selectedServer}`; + if (serverInfo) { + let statusText = serverInfo.status; + if ( + serverInfo.status === "connected" && + serverInfo.warnings.length > 0 + ) { + statusText += " (with warnings)"; + } + subtitle = `Status: ${statusText} â€ĸ Command: ${serverInfo.command}`; + } + } + + return ( + + + {title} + + {subtitle && {subtitle}} + + ); + }; + + return ( + + {renderHeader()} + + {message && ( + + + {message} + + + )} + + {isLoading ? ( + + Working... + + ) : ( + + {items.map((item, index) => { + const isSelected = index === selectedIndex && !item.disabled; + const canSelect = !item.disabled; + + return ( + + + {isSelected && canSelect ? "> " : " "} + {item.label} + + + ); + })} + + )} + + + + Use ↑/↓ to navigate, Enter to select, Esc to go back + + + + ); +}; + +export default MCPSelector; diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index 7fa5c4fc0..29953ee7a 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -20,12 +20,14 @@ import { useModelSelector } from "./hooks/useModelSelector.js"; import { useOrganizationSelector } from "./hooks/useOrganizationSelector.js"; import IntroMessage from "./IntroMessage.js"; import LoadingAnimation from "./LoadingAnimation.js"; +import MCPSelector from "./MCPSelector.js"; import ModelSelector from "./ModelSelector.js"; import OrganizationSelector from "./OrganizationSelector.js"; import Timer from "./Timer.js"; import UpdateNotification from "./UpdateNotification.js"; import UserInput from "./UserInput.js"; import ModeIndicator from "./components/ModeIndicator.js"; +import MCPStatusIndicator from "./components/MCPStatusIndicator.js"; import { getGitRemoteUrl, getRepoUrl, isGitRepo } from "../util/git.js"; import useTerminalSize from "./hooks/useTerminalSize.js"; import { modeService } from "../services/ModeService.js"; @@ -107,6 +109,9 @@ const TUIChat: React.FC = ({ modeService.getCurrentMode() ); + // State for MCP selector + const [showMCPSelector, setShowMCPSelector] = useState(false); + // Listen for mode changes to update UI useEffect(() => { const handleModeChange = (newMode: PermissionMode) => { @@ -198,6 +203,7 @@ const TUIChat: React.FC = ({ onShowOrgSelector: () => showOrganizationSelector(), onShowConfigSelector: () => showConfigSelectorUI(), onShowModelSelector: () => showModelSelectorUI(), + onShowMCPSelector: () => setShowMCPSelector(true), onLoginPrompt: handleLoginPrompt, onReload: handleReload, // Remote mode configuration @@ -266,12 +272,18 @@ const TUIChat: React.FC = ({ showConfigSelectorUI(); }; + // MCP selector handlers + const handleMCPCancel = () => { + setShowMCPSelector(false); + }; + // Determine if input should be disabled // Allow input even when services are loading, but disable for UI overlays const isInputDisabled = showOrgSelector || showConfigSelector || showModelSelector || + showMCPSelector || !!loginPrompt || isShowingFreeTrialTransition || !!activePermissionRequest; @@ -368,6 +380,13 @@ const TUIChat: React.FC = ({ /> )} + {/* MCP selector - shows above input when active */} + {showMCPSelector && ( + + )} + {/* Free trial transition UI - replaces input when active */} {isShowingFreeTrialTransition && ( = ({ )} + {services.mcp && ( + <> + + + + )} {!isRemoteMode && services.model?.model && ( diff --git a/src/ui/components/MCPStatusIndicator.tsx b/src/ui/components/MCPStatusIndicator.tsx new file mode 100644 index 000000000..d880b4b95 --- /dev/null +++ b/src/ui/components/MCPStatusIndicator.tsx @@ -0,0 +1,40 @@ +import { Box, Text } from "ink"; +import React from "react"; +import { MCPServiceState } from "../../services/types.js"; + +interface MCPStatusIndicatorProps { + mcpState: MCPServiceState | null; +} + +const MCPStatusIndicator: React.FC = ({ mcpState }) => { + if (!mcpState?.mcpService || mcpState.connections.length === 0) { + return null; + } + + // Determine overall status and color + const hasConnecting = mcpState.connections.some(c => c.status === 'connecting'); + const hasError = mcpState.connections.some(c => c.status === 'error'); + const hasConnected = mcpState.connections.some(c => c.status === 'connected'); + const hasWarnings = mcpState.connections.some(c => c.warnings.length > 0); + + let statusChar = "●"; + let color = "gray"; + + if (hasConnecting) { + statusChar = "◐"; // Loading spinner character + color = "yellow"; + } else if (hasError) { + color = "red"; + } else if (hasConnected) { + color = hasWarnings ? "yellow" : "green"; + } + + return ( + + MCP + {statusChar} + + ); +}; + +export default MCPStatusIndicator; \ No newline at end of file diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index 35382771a..8758b41a4 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -30,6 +30,7 @@ interface UseChatProps { onShowOrgSelector: () => void; onShowConfigSelector: () => void; onShowModelSelector?: () => void; + onShowMCPSelector?: () => void; onLoginPrompt?: (promptText: string) => Promise; onReload?: () => Promise; // Remote mode props @@ -47,6 +48,7 @@ export function useChat({ onShowOrgSelector, onShowConfigSelector, onShowModelSelector, + onShowMCPSelector, onLoginPrompt, onReload, isRemoteMode = false, @@ -354,6 +356,11 @@ export function useChat({ return; } + if (commandResult.openMCPSelector && onShowMCPSelector) { + onShowMCPSelector(); + return; + } + if (commandResult.clear) { const systemMessage = chatHistory.find( (msg) => msg.role === "system"