feat: mcp UI
This commit is contained in:
parent
1e59964150
commit
a0f5709cb5
15 changed files with 605 additions and 564 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -8,4 +8,4 @@ chat.log
|
|||
*notes.md
|
||||
|
||||
# Local config files (users should not commit their personal configs)
|
||||
config.yaml
|
||||
config.yaml
|
||||
|
|
|
|||
48
package-lock.json
generated
48
package-lock.json
generated
|
|
@ -12,7 +12,7 @@
|
|||
"@continuedev/config-yaml": "^1.0.96",
|
||||
"@continuedev/openai-adapters": "^1.4.1",
|
||||
"@continuedev/sdk": "^0.0.13",
|
||||
"@modelcontextprotocol/sdk": "^1.9.0",
|
||||
"@modelcontextprotocol/sdk": "^1.17.2",
|
||||
"@opentelemetry/api": "^1.9.0",
|
||||
"@opentelemetry/exporter-metrics-otlp-grpc": "^0.203.0",
|
||||
"@opentelemetry/exporter-metrics-otlp-http": "^0.203.0",
|
||||
|
|
@ -35,7 +35,7 @@
|
|||
"glob": "^11.0.3",
|
||||
"gpt-tokenizer": "^3.0.1",
|
||||
"ignore-walk": "^7.0.0",
|
||||
"ink": "^6.0.1",
|
||||
"ink": "^6.1.0",
|
||||
"jszip": "^3.10.1",
|
||||
"lowlight": "^3.3.0",
|
||||
"minimatch": "^10.0.3",
|
||||
|
|
@ -45,6 +45,7 @@
|
|||
"posthog-node": "^5.6.0",
|
||||
"react": "^19.1.0",
|
||||
"readline-sync": "^1.4.10",
|
||||
"shell-quote": "^1.8.3",
|
||||
"swr": "^2.3.4",
|
||||
"turndown": "^7.2.0",
|
||||
"typescript": "^5.8.3",
|
||||
|
|
@ -69,6 +70,7 @@
|
|||
"@types/jszip": "^3.4.0",
|
||||
"@types/nock": "^10.0.3",
|
||||
"@types/readline-sync": "^1.4.8",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"@types/supertest": "^6.0.3",
|
||||
"@typescript-eslint/eslint-plugin": "^8.39.0",
|
||||
"@typescript-eslint/parser": "^8.39.0",
|
||||
|
|
@ -1644,15 +1646,17 @@
|
|||
"license": "BSD-2-Clause"
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/sdk": {
|
||||
"version": "1.11.0",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.11.0.tgz",
|
||||
"integrity": "sha512-k/1pb70eD638anoi0e8wUGAlbMJXyvdV4p62Ko+EZ7eBe1xMx8Uhak1R5DgfoofsK5IBBnRwsYGTaLZl+6/+RQ==",
|
||||
"version": "1.17.2",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.17.2.tgz",
|
||||
"integrity": "sha512-EFLRNXR/ixpXQWu6/3Cu30ndDFIFNaqUXcTqsGebujeMan9FzhAaFFswLRiFj61rgygDRr8WO1N+UijjgRxX9g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ajv": "^6.12.6",
|
||||
"content-type": "^1.0.5",
|
||||
"cors": "^2.8.5",
|
||||
"cross-spawn": "^7.0.3",
|
||||
"cross-spawn": "^7.0.5",
|
||||
"eventsource": "^3.0.2",
|
||||
"eventsource-parser": "^3.0.0",
|
||||
"express": "^5.0.1",
|
||||
"express-rate-limit": "^7.5.0",
|
||||
"pkce-challenge": "^5.0.0",
|
||||
|
|
@ -5918,6 +5922,13 @@
|
|||
"@types/send": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/shell-quote": {
|
||||
"version": "1.7.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/shell-quote/-/shell-quote-1.7.5.tgz",
|
||||
"integrity": "sha512-+UE8GAGRPbJVQDdxi16dgadcBfQ+KG2vgZhV1+3A1XmHbmwcdwhCUwIdy+d3pAGrbvgRoVSjeI9vOWyq376Yzw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/shimmer": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/shimmer/-/shimmer-1.2.0.tgz",
|
||||
|
|
@ -6787,7 +6798,6 @@
|
|||
"version": "6.12.6",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
|
||||
"integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.1",
|
||||
|
|
@ -9507,7 +9517,6 @@
|
|||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
|
||||
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-glob": {
|
||||
|
|
@ -9531,7 +9540,6 @@
|
|||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
|
||||
"integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-levenshtein": {
|
||||
|
|
@ -10799,9 +10807,10 @@
|
|||
"license": "ISC"
|
||||
},
|
||||
"node_modules/ink": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ink/-/ink-6.0.1.tgz",
|
||||
"integrity": "sha512-vhhFrCodTHZAPPSdMYzLEbeI0Ug37R9j6yA0kLKok9kSK53lQtj/RJhEQJUjq6OwT4N33nxqSRd/7yXhEhVPIw==",
|
||||
"version": "6.1.0",
|
||||
"resolved": "https://registry.npmjs.org/ink/-/ink-6.1.0.tgz",
|
||||
"integrity": "sha512-YQ+lbMD79y3FBAJXXZnuRajLEgaMFp102361eY5NrBIEVCi9oFo7gNZU4z2LBWlcjZFiTt7jetlkIbKCCH4KJA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@alcalzone/ansi-tokenize": "^0.1.3",
|
||||
"ansi-escapes": "^7.0.0",
|
||||
|
|
@ -11843,7 +11852,6 @@
|
|||
"version": "0.4.1",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
|
||||
"integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/json-stable-stringify-without-jsonify": {
|
||||
|
|
@ -16279,7 +16287,6 @@
|
|||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
|
||||
"integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
|
|
@ -17234,6 +17241,18 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/shell-quote": {
|
||||
"version": "1.8.3",
|
||||
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz",
|
||||
"integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/shimmer": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/shimmer/-/shimmer-1.2.1.tgz",
|
||||
|
|
@ -18663,7 +18682,6 @@
|
|||
"version": "4.4.1",
|
||||
"resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
|
||||
"integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"punycode": "^2.1.0"
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@
|
|||
"@continuedev/config-yaml": "^1.0.96",
|
||||
"@continuedev/openai-adapters": "^1.4.1",
|
||||
"@continuedev/sdk": "^0.0.13",
|
||||
"@modelcontextprotocol/sdk": "^1.9.0",
|
||||
"@modelcontextprotocol/sdk": "^1.17.2",
|
||||
"@opentelemetry/api": "^1.9.0",
|
||||
"@opentelemetry/exporter-metrics-otlp-grpc": "^0.203.0",
|
||||
"@opentelemetry/exporter-metrics-otlp-http": "^0.203.0",
|
||||
|
|
@ -64,7 +64,7 @@
|
|||
"glob": "^11.0.3",
|
||||
"gpt-tokenizer": "^3.0.1",
|
||||
"ignore-walk": "^7.0.0",
|
||||
"ink": "^6.0.1",
|
||||
"ink": "^6.1.0",
|
||||
"jszip": "^3.10.1",
|
||||
"lowlight": "^3.3.0",
|
||||
"minimatch": "^10.0.3",
|
||||
|
|
@ -74,6 +74,7 @@
|
|||
"posthog-node": "^5.6.0",
|
||||
"react": "^19.1.0",
|
||||
"readline-sync": "^1.4.10",
|
||||
"shell-quote": "^1.8.3",
|
||||
"swr": "^2.3.4",
|
||||
"turndown": "^7.2.0",
|
||||
"typescript": "^5.8.3",
|
||||
|
|
@ -95,6 +96,7 @@
|
|||
"@types/jszip": "^3.4.0",
|
||||
"@types/nock": "^10.0.3",
|
||||
"@types/readline-sync": "^1.4.8",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"@types/supertest": "^6.0.3",
|
||||
"@typescript-eslint/eslint-plugin": "^8.39.0",
|
||||
"@typescript-eslint/parser": "^8.39.0",
|
||||
|
|
|
|||
10
spec/mcp.md
10
spec/mcp.md
|
|
@ -13,15 +13,9 @@ Each server configuration should have its own connection and state separated, bu
|
|||
Servers should have a status "idle", "connecting", "connected", or "error". Only "connected" servers contribute prompts and tools.
|
||||
If a server successfully connects but there is an error retrieving prompts or tools, it should have an array of warning messages that can be accessed in the terminal app.
|
||||
When the process exits, all servers should be shut down and disconnected.
|
||||
Only MCP servers for the CURRENT config should be loaded
|
||||
|
||||
## MCP Status indicator
|
||||
|
||||
If any MCP servers are present, a small indicator in the bottom right of TUIChat (next to update/version status) shows a small MCP icon with green/yellow/red dot, with this priority
|
||||
|
||||
- loading icon if any servers are connecting
|
||||
- red if any servers have errored
|
||||
- green if any servers are connected
|
||||
- gray if all servers are idle
|
||||
- Logs from MCP servers should be routed through the winston logger, not the standard console.log (since this is a terminal app)
|
||||
|
||||
## MCP slash command
|
||||
|
||||
|
|
|
|||
|
|
@ -1,131 +0,0 @@
|
|||
import { type AssistantConfig } from "@continuedev/sdk";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||
|
||||
import { logger } from "./util/logger.js";
|
||||
|
||||
export type MCPServerStatus = "idle" | "connecting" | "connected" | "error";
|
||||
|
||||
export class MCPConnection {
|
||||
public prompts: Awaited<ReturnType<Client["listPrompts"]>>["prompts"] = [];
|
||||
public tools: Awaited<ReturnType<Client["listTools"]>>["tools"] = [];
|
||||
public status: MCPServerStatus = "idle";
|
||||
public error?: Error;
|
||||
public warnings: string[] = [];
|
||||
public readonly command: string;
|
||||
public readonly name: string;
|
||||
|
||||
constructor(
|
||||
public readonly client: Client | null,
|
||||
command: string,
|
||||
name: string
|
||||
) {
|
||||
this.command = command;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public static async create(
|
||||
config: NonNullable<AssistantConfig["mcpServers"]>[number],
|
||||
name: string
|
||||
): Promise<MCPConnection> {
|
||||
if (!config) {
|
||||
throw new Error("MCP server config is null");
|
||||
}
|
||||
|
||||
const connection = new MCPConnection(
|
||||
null,
|
||||
config.command || "unknown",
|
||||
name
|
||||
);
|
||||
connection.status = "connecting";
|
||||
|
||||
try {
|
||||
const client = new Client(
|
||||
{
|
||||
name: "continue-cli-client",
|
||||
version: "1.0.0",
|
||||
},
|
||||
{ capabilities: {} }
|
||||
);
|
||||
|
||||
// Construct transport
|
||||
const env: Record<string, string> = 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1,42 +1,35 @@
|
|||
import { AssistantConfig } from "@continuedev/sdk";
|
||||
import {
|
||||
describe,
|
||||
it,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
jest,
|
||||
} from "@jest/globals";
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
|
||||
import { MCPService } from "./mcp.js";
|
||||
|
||||
|
||||
// Mock the logger
|
||||
jest.mock("./src/util/logger", () => ({
|
||||
default: {
|
||||
debug: jest.fn(),
|
||||
info: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
error: jest.fn(),
|
||||
vi.mock("./util/logger.js", () => ({
|
||||
logger: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.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()),
|
||||
connect: vi.fn(),
|
||||
getServerCapabilities: vi.fn(() => ({ prompts: true, tools: true })),
|
||||
listPrompts: vi.fn(() => Promise.resolve({ prompts: [] })),
|
||||
listTools: vi.fn(() => Promise.resolve({ tools: [] })),
|
||||
callTool: vi.fn(() => Promise.resolve({})),
|
||||
close: vi.fn(() => Promise.resolve()),
|
||||
};
|
||||
|
||||
jest.mock("@modelcontextprotocol/sdk/client/index.js", () => ({
|
||||
Client: jest.fn(() => mockClient),
|
||||
vi.mock("@modelcontextprotocol/sdk/client/index.js", () => ({
|
||||
Client: vi.fn(() => mockClient),
|
||||
}));
|
||||
|
||||
jest.mock("@modelcontextprotocol/sdk/client/stdio.js", () => ({
|
||||
StdioClientTransport: jest.fn(),
|
||||
vi.mock("@modelcontextprotocol/sdk/client/stdio.js", () => ({
|
||||
StdioClientTransport: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("MCPService", () => {
|
||||
|
|
@ -60,7 +53,7 @@ describe("MCPService", () => {
|
|||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("initialization", () => {
|
||||
|
|
@ -101,8 +94,8 @@ describe("MCPService", () => {
|
|||
|
||||
it("should provide service info", () => {
|
||||
const info = mcpService.getMCPInfo();
|
||||
expect(info).toHaveProperty("toolCount");
|
||||
expect(info).toHaveProperty("promptCount");
|
||||
expect(info).toHaveProperty("toolNames");
|
||||
expect(info).toHaveProperty("promptNames");
|
||||
expect(info).toHaveProperty("connectionCount");
|
||||
});
|
||||
|
||||
|
|
|
|||
371
src/mcp.ts
371
src/mcp.ts
|
|
@ -1,26 +1,43 @@
|
|||
import { type AssistantConfig } from "@continuedev/sdk";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||
|
||||
import { MCPConnection, MCPServerStatus } from "./MCPConnection.js";
|
||||
import { MCPServiceState } from "./services/types.js";
|
||||
import {logger} from "./util/logger.js";
|
||||
import { serviceContainer } from "./services/ServiceContainer.js";
|
||||
import { MCPServiceState, SERVICE_NAMES } from "./services/types.js";
|
||||
import { getErrorString } from "./util/error.js";
|
||||
import { logger } from "./util/logger.js";
|
||||
|
||||
export type MCPServerStatus = "idle" | "connecting" | "connected" | "error";
|
||||
|
||||
export interface MCPConnectionInfo {
|
||||
name: string;
|
||||
command: string;
|
||||
type MCPServerConfig = NonNullable<
|
||||
NonNullable<AssistantConfig["mcpServers"]>[number]
|
||||
>;
|
||||
|
||||
interface ServerConnection {
|
||||
config: MCPServerConfig;
|
||||
client: Client | null;
|
||||
prompts: Awaited<ReturnType<Client["listPrompts"]>>["prompts"];
|
||||
tools: Awaited<ReturnType<Client["listTools"]>>["tools"];
|
||||
status: MCPServerStatus;
|
||||
toolCount: number;
|
||||
promptCount: number;
|
||||
error?: Error;
|
||||
error?: string;
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
export interface MCPConnectionInfo {
|
||||
config: MCPServerConfig;
|
||||
status: MCPServerStatus;
|
||||
toolNames: string[];
|
||||
promptNames: string[];
|
||||
error?: string;
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
export class MCPService {
|
||||
private connections: Map<string, MCPConnection> = new Map();
|
||||
private connections: Map<string, ServerConnection> = new Map();
|
||||
private currentState: MCPServiceState;
|
||||
private assistant: AssistantConfig | null = null;
|
||||
private isShuttingDown = false;
|
||||
private initVersion = 0;
|
||||
|
||||
constructor() {
|
||||
this.currentState = {
|
||||
|
|
@ -41,64 +58,164 @@ export class MCPService {
|
|||
* Initialize the MCP service
|
||||
*/
|
||||
async initialize(assistant: AssistantConfig): Promise<MCPServiceState> {
|
||||
logger.debug("Initializing MCPService");
|
||||
logger.debug("Initializing MCPService", {
|
||||
configName: assistant.name,
|
||||
serverCount: assistant.mcpServers?.length || 0,
|
||||
});
|
||||
|
||||
const version = ++this.initVersion;
|
||||
|
||||
await this.shutdownConnections();
|
||||
|
||||
this.assistant = assistant;
|
||||
this.connections.clear();
|
||||
|
||||
// Service initialization should not block on server connections
|
||||
if (assistant.mcpServers?.length) {
|
||||
logger.debug("Starting MCP server connections", {
|
||||
serverCount: assistant.mcpServers.length,
|
||||
});
|
||||
|
||||
// Initialize all servers simultaneously without blocking
|
||||
const connectionPromises = assistant.mcpServers.map(
|
||||
async (serverConfig, index) => {
|
||||
if (!serverConfig) return;
|
||||
|
||||
const serverName = serverConfig.name || `server-${index}`;
|
||||
// Create placeholder connection with connecting state
|
||||
const connection: ServerConnection = {
|
||||
config: serverConfig,
|
||||
client: null,
|
||||
prompts: [],
|
||||
tools: [],
|
||||
status: "connecting",
|
||||
warnings: [],
|
||||
};
|
||||
this.connections.set(serverName, connection);
|
||||
this.updateState();
|
||||
|
||||
try {
|
||||
const connection = await MCPConnection.create(
|
||||
serverConfig,
|
||||
serverName
|
||||
if (serverConfig.type && serverConfig.type !== "stdio") {
|
||||
throw new Error(
|
||||
`${serverConfig.type} MCP servers are not yet supported in the Continue CLI`,
|
||||
);
|
||||
}
|
||||
if (!serverConfig.command) {
|
||||
throw new Error("MCP server command is not specified");
|
||||
}
|
||||
|
||||
const client = new Client(
|
||||
{ name: "continue-cli-client", version: "1.0.0" },
|
||||
{ capabilities: {} },
|
||||
);
|
||||
this.connections.set(serverName, connection);
|
||||
|
||||
const env: Record<string, string> = serverConfig.env || {};
|
||||
if (process.env.PATH !== undefined) {
|
||||
env.PATH = process.env.PATH;
|
||||
}
|
||||
|
||||
const transport = new StdioClientTransport({
|
||||
command: serverConfig.command,
|
||||
args: serverConfig.args,
|
||||
env,
|
||||
stderr: "ignore",
|
||||
});
|
||||
|
||||
logger.debug("Connecting to MCP server", {
|
||||
name: serverName,
|
||||
command: serverConfig.command,
|
||||
});
|
||||
|
||||
await client.connect(transport, {});
|
||||
|
||||
// Ignore results from stale initializations
|
||||
if (version !== this.initVersion) {
|
||||
try {
|
||||
await client.close();
|
||||
} catch {}
|
||||
return;
|
||||
}
|
||||
|
||||
connection.client = client;
|
||||
connection.status = "connected";
|
||||
|
||||
const capabilities = client.getServerCapabilities();
|
||||
logger.debug("MCP server capabilities", {
|
||||
name: serverName,
|
||||
hasPrompts: !!capabilities?.prompts,
|
||||
hasTools: !!capabilities?.tools,
|
||||
});
|
||||
|
||||
if (capabilities?.prompts) {
|
||||
try {
|
||||
connection.prompts = (await client.listPrompts()).prompts;
|
||||
logger.debug("Loaded MCP prompts", {
|
||||
name: serverName,
|
||||
count: connection.prompts.length,
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = getErrorString(error);
|
||||
connection.warnings.push(
|
||||
`Failed to load prompts: ${errorMessage}`,
|
||||
);
|
||||
logger.warn("Failed to load MCP prompts", {
|
||||
name: serverName,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (capabilities?.tools) {
|
||||
try {
|
||||
connection.tools = (await client.listTools()).tools;
|
||||
logger.debug("Loaded MCP tools", {
|
||||
name: serverName,
|
||||
count: connection.tools.length,
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = getErrorString(error);
|
||||
connection.warnings.push(
|
||||
`Failed to load tools: ${errorMessage}`,
|
||||
);
|
||||
logger.warn("Failed to load MCP tools", {
|
||||
name: serverName,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug("MCP server connected", {
|
||||
name: serverName,
|
||||
command: serverConfig.command,
|
||||
});
|
||||
} catch (error: any) {
|
||||
this.updateState();
|
||||
} catch (error) {
|
||||
if (version !== this.initVersion) {
|
||||
return;
|
||||
}
|
||||
const errorMessage = getErrorString(error);
|
||||
connection.status = "error";
|
||||
connection.error = errorMessage;
|
||||
logger.error("MCP server connection failed", {
|
||||
name: serverName,
|
||||
error: error.message,
|
||||
error: errorMessage,
|
||||
});
|
||||
// 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);
|
||||
this.updateState();
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Don't await - let connections happen in background
|
||||
Promise.all(connectionPromises)
|
||||
.then(() => {
|
||||
this.updateState();
|
||||
logger.debug("All MCP server connections completed");
|
||||
if (version === this.initVersion) {
|
||||
this.updateState();
|
||||
logger.debug("All MCP server connections completed");
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
// Individual errors are already handled above
|
||||
this.updateState();
|
||||
if (version === this.initVersion) {
|
||||
this.updateState();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Return immediately with current state
|
||||
this.updateState();
|
||||
return this.currentState;
|
||||
}
|
||||
|
|
@ -109,7 +226,7 @@ export class MCPService {
|
|||
private updateState(): void {
|
||||
const connections = Array.from(this.connections.values());
|
||||
const connectedConnections = connections.filter(
|
||||
(c) => c.status === "connected"
|
||||
(c) => c.status === "connected",
|
||||
);
|
||||
|
||||
this.currentState = {
|
||||
|
|
@ -117,14 +234,21 @@ export class MCPService {
|
|||
connections: this.getConnectionInfo(),
|
||||
toolCount: connectedConnections.reduce(
|
||||
(sum, c) => sum + c.tools.length,
|
||||
0
|
||||
0,
|
||||
),
|
||||
promptCount: connectedConnections.reduce(
|
||||
(sum, c) => sum + c.prompts.length,
|
||||
0
|
||||
0,
|
||||
),
|
||||
isReady: true,
|
||||
};
|
||||
|
||||
// Propagate state changes to the service container so the UI updates
|
||||
try {
|
||||
serviceContainer.set(SERVICE_NAMES.MCP, this.currentState);
|
||||
} catch {
|
||||
// In early boot, container may not yet be registered; ignore
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -141,8 +265,6 @@ export class MCPService {
|
|||
logger.debug("Updating MCPService");
|
||||
|
||||
// Shutdown existing connections
|
||||
await this.shutdownConnections();
|
||||
|
||||
return await this.initialize(assistant);
|
||||
}
|
||||
|
||||
|
|
@ -158,11 +280,10 @@ export class MCPService {
|
|||
*/
|
||||
getConnectionInfo(): MCPConnectionInfo[] {
|
||||
return Array.from(this.connections.values()).map((connection) => ({
|
||||
name: connection.name,
|
||||
command: connection.command,
|
||||
config: connection.config,
|
||||
status: connection.status,
|
||||
toolCount: connection.tools.length,
|
||||
promptCount: connection.prompts.length,
|
||||
toolNames: connection.tools.map((tool) => tool.name),
|
||||
promptNames: connection.prompts.map((prompt) => prompt.name),
|
||||
error: connection.error,
|
||||
warnings: connection.warnings,
|
||||
}));
|
||||
|
|
@ -203,13 +324,21 @@ export class MCPService {
|
|||
* Get MCP service information for display
|
||||
*/
|
||||
getMCPInfo(): {
|
||||
toolCount: number;
|
||||
promptCount: number;
|
||||
toolNames: string[];
|
||||
promptNames: string[];
|
||||
connectionCount: number;
|
||||
} {
|
||||
const connectedConnections = Array.from(this.connections.values()).filter(
|
||||
(c) => c.status === "connected",
|
||||
);
|
||||
|
||||
return {
|
||||
toolCount: this.currentState.toolCount,
|
||||
promptCount: this.currentState.promptCount,
|
||||
toolNames: connectedConnections.flatMap((connection) =>
|
||||
connection.tools.map((tool) => tool.name),
|
||||
),
|
||||
promptNames: connectedConnections.flatMap((connection) =>
|
||||
connection.prompts.map((prompt) => prompt.name),
|
||||
),
|
||||
connectionCount: this.connections.size,
|
||||
};
|
||||
}
|
||||
|
|
@ -259,6 +388,7 @@ export class MCPService {
|
|||
logger.debug("Restarting all MCP servers");
|
||||
await this.shutdownConnections();
|
||||
await this.initialize(this.assistant);
|
||||
this.updateState();
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -277,7 +407,7 @@ export class MCPService {
|
|||
if (!this.assistant || !this.assistant.mcpServers) return;
|
||||
|
||||
const serverConfig = this.assistant.mcpServers.find(
|
||||
(s, index) => s && (s.name || `server-${index}`) === serverName
|
||||
(s, index) => s && (s.name || `server-${index}`) === serverName,
|
||||
);
|
||||
|
||||
if (!serverConfig) {
|
||||
|
|
@ -286,30 +416,107 @@ export class MCPService {
|
|||
|
||||
logger.debug("Restarting MCP server", { name: serverName });
|
||||
|
||||
// Stop existing connection
|
||||
const existingConnection = this.connections.get(serverName);
|
||||
if (existingConnection) {
|
||||
await this.shutdownConnection(existingConnection);
|
||||
if (existingConnection.status === "connected") {
|
||||
await this.shutdownConnection(existingConnection);
|
||||
}
|
||||
this.connections.delete(serverName);
|
||||
}
|
||||
|
||||
// Start new connection
|
||||
const connection: ServerConnection = {
|
||||
config: serverConfig,
|
||||
client: null,
|
||||
prompts: [],
|
||||
tools: [],
|
||||
status: "connecting",
|
||||
warnings: [],
|
||||
};
|
||||
this.connections.set(serverName, connection);
|
||||
this.updateState();
|
||||
|
||||
try {
|
||||
const connection = await MCPConnection.create(serverConfig, serverName);
|
||||
this.connections.set(serverName, connection);
|
||||
if (!serverConfig.command) {
|
||||
throw new Error("MCP server command is not specified");
|
||||
}
|
||||
|
||||
const client = new Client(
|
||||
{ name: "continue-cli-client", version: "1.0.0" },
|
||||
{ capabilities: {} },
|
||||
);
|
||||
|
||||
const env: Record<string, string> = serverConfig.env || {};
|
||||
if (process.env.PATH !== undefined) {
|
||||
env.PATH = process.env.PATH;
|
||||
}
|
||||
|
||||
const transport = new StdioClientTransport({
|
||||
command: serverConfig.command,
|
||||
args: serverConfig.args,
|
||||
env,
|
||||
stderr: "ignore",
|
||||
});
|
||||
|
||||
logger.debug("Connecting to MCP server", {
|
||||
name: serverName,
|
||||
command: serverConfig.command,
|
||||
});
|
||||
|
||||
await client.connect(transport, {});
|
||||
|
||||
connection.client = client;
|
||||
connection.status = "connected";
|
||||
|
||||
const capabilities = client.getServerCapabilities();
|
||||
logger.debug("MCP server capabilities", {
|
||||
name: serverName,
|
||||
hasPrompts: !!capabilities?.prompts,
|
||||
hasTools: !!capabilities?.tools,
|
||||
});
|
||||
|
||||
if (capabilities?.prompts) {
|
||||
try {
|
||||
connection.prompts = (await client.listPrompts()).prompts;
|
||||
logger.debug("Loaded MCP prompts", {
|
||||
name: serverName,
|
||||
count: connection.prompts.length,
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = getErrorString(error);
|
||||
connection.warnings.push(`Failed to load prompts: ${errorMessage}`);
|
||||
logger.warn("Failed to load MCP prompts", {
|
||||
name: serverName,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (capabilities?.tools) {
|
||||
try {
|
||||
connection.tools = (await client.listTools()).tools;
|
||||
logger.debug("Loaded MCP tools", {
|
||||
name: serverName,
|
||||
count: connection.tools.length,
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = getErrorString(error);
|
||||
connection.warnings.push(`Failed to load tools: ${errorMessage}`);
|
||||
logger.warn("Failed to load MCP tools", {
|
||||
name: serverName,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug("MCP server restarted successfully", { name: serverName });
|
||||
} catch (error: any) {
|
||||
} catch (error) {
|
||||
const errorMessage = getErrorString(error);
|
||||
connection.status = "error";
|
||||
connection.error = errorMessage;
|
||||
logger.error("Failed to restart MCP server", {
|
||||
name: serverName,
|
||||
error: error.message,
|
||||
error: errorMessage,
|
||||
});
|
||||
const failedConnection = new MCPConnection(
|
||||
null,
|
||||
serverConfig.command || "unknown",
|
||||
serverName
|
||||
);
|
||||
failedConnection.status = "error";
|
||||
failedConnection.error = error;
|
||||
this.connections.set(serverName, failedConnection);
|
||||
}
|
||||
|
||||
this.updateState();
|
||||
|
|
@ -324,10 +531,7 @@ export class MCPService {
|
|||
const connection = this.connections.get(serverName);
|
||||
if (connection) {
|
||||
await this.shutdownConnection(connection);
|
||||
this.connections.delete(serverName);
|
||||
}
|
||||
|
||||
this.updateState();
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -338,11 +542,10 @@ export class MCPService {
|
|||
if (!connection) return null;
|
||||
|
||||
return {
|
||||
name: connection.name,
|
||||
command: connection.command,
|
||||
config: connection.config,
|
||||
status: connection.status,
|
||||
toolCount: connection.tools.length,
|
||||
promptCount: connection.prompts.length,
|
||||
toolNames: connection.tools.map((tool) => tool.name),
|
||||
promptNames: connection.prompts.map((prompt) => prompt.name),
|
||||
error: connection.error,
|
||||
warnings: connection.warnings,
|
||||
};
|
||||
|
|
@ -353,25 +556,34 @@ export class MCPService {
|
|||
*/
|
||||
private async shutdownConnections(): Promise<void> {
|
||||
const shutdownPromises = Array.from(this.connections.values()).map(
|
||||
(connection) => this.shutdownConnection(connection)
|
||||
(connection) => this.shutdownConnection(connection),
|
||||
);
|
||||
|
||||
await Promise.all(shutdownPromises);
|
||||
this.connections.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Shutdown a single connection
|
||||
*/
|
||||
private async shutdownConnection(connection: MCPConnection): Promise<void> {
|
||||
private async shutdownConnection(
|
||||
connection: ServerConnection,
|
||||
): Promise<void> {
|
||||
try {
|
||||
if (connection.client) {
|
||||
await connection.client.close();
|
||||
}
|
||||
} catch (error: any) {
|
||||
connection.status = "idle";
|
||||
connection.warnings = [];
|
||||
connection.client = null;
|
||||
connection.tools = [];
|
||||
connection.prompts = [];
|
||||
connection.error = undefined;
|
||||
this.updateState();
|
||||
} catch (error) {
|
||||
const errorMessage = getErrorString(error);
|
||||
logger.warn("Error shutting down MCP connection", {
|
||||
name: connection.name,
|
||||
error: error.message,
|
||||
name: connection.config?.name,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -394,6 +606,7 @@ export class MCPService {
|
|||
promptCount: 0,
|
||||
isReady: false,
|
||||
};
|
||||
|
||||
this.updateState();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,98 +0,0 @@
|
|||
import { AssistantUnrolled } from "@continuedev/config-yaml";
|
||||
|
||||
import { MCPService } from "../mcp.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { MCPServiceState } from "./types.js";
|
||||
|
||||
/**
|
||||
* Service wrapper for managing MCP service state
|
||||
* The actual MCPService is a singleton, this wrapper provides reactive updates
|
||||
*/
|
||||
export class MCPServiceWrapper {
|
||||
private currentState: MCPServiceState = {
|
||||
mcpService: null,
|
||||
};
|
||||
|
||||
/**
|
||||
* Initialize the MCP service wrapper
|
||||
*/
|
||||
async initialize(assistant: AssistantUnrolled): Promise<MCPServiceState> {
|
||||
logger.debug("Initializing MCPServiceWrapper");
|
||||
|
||||
try {
|
||||
const mcpService = await MCPService.create(assistant);
|
||||
|
||||
this.currentState = {
|
||||
mcpService,
|
||||
};
|
||||
|
||||
logger.debug("MCPServiceWrapper initialized successfully", {
|
||||
toolCount: mcpService.getTools().length,
|
||||
promptCount: mcpService.getPrompts().length,
|
||||
});
|
||||
|
||||
return this.currentState;
|
||||
} catch (error: any) {
|
||||
logger.error("Failed to initialize MCPServiceWrapper:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current MCP service state
|
||||
*/
|
||||
getState(): MCPServiceState {
|
||||
return { ...this.currentState };
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the MCP service with a new assistant config
|
||||
* Note: This creates a new MCP service since the original is a singleton
|
||||
*/
|
||||
async update(assistant: AssistantUnrolled): Promise<MCPServiceState> {
|
||||
logger.debug("Updating MCPServiceWrapper");
|
||||
|
||||
try {
|
||||
// Clear the existing singleton instance to force recreation
|
||||
(MCPService as any).instance = null;
|
||||
|
||||
const mcpService = await MCPService.create(assistant);
|
||||
|
||||
this.currentState = {
|
||||
mcpService,
|
||||
};
|
||||
|
||||
logger.debug("MCPServiceWrapper updated successfully", {
|
||||
toolCount: mcpService.getTools().length,
|
||||
promptCount: mcpService.getPrompts().length,
|
||||
});
|
||||
|
||||
return this.currentState;
|
||||
} catch (error: any) {
|
||||
logger.error("Failed to update MCPServiceWrapper:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the MCP service is ready
|
||||
*/
|
||||
isReady(): boolean {
|
||||
return this.currentState.mcpService !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get MCP service information for display
|
||||
*/
|
||||
getMCPInfo(): { toolCount: number; promptCount: number } | null {
|
||||
if (!this.currentState.mcpService) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
toolCount: this.currentState.mcpService.getTools().length,
|
||||
promptCount: this.currentState.mcpService.getPrompts().length,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -3,7 +3,7 @@ import { BaseLlmApi } from "@continuedev/openai-adapters";
|
|||
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
|
||||
|
||||
import { AuthConfig } from "../auth/workos.js";
|
||||
import { MCPService } from "../mcp.js";
|
||||
import { MCPConnectionInfo, MCPService } from "../mcp.js";
|
||||
import { PermissionMode, ToolPermissions } from "../permissions/types.js";
|
||||
|
||||
/**
|
||||
|
|
@ -52,15 +52,7 @@ export interface ModelServiceState {
|
|||
|
||||
export interface MCPServiceState {
|
||||
mcpService: MCPService | null;
|
||||
connections: Array<{
|
||||
name: string;
|
||||
command: string;
|
||||
status: 'idle' | 'connecting' | 'connected' | 'error';
|
||||
toolCount: number;
|
||||
promptCount: number;
|
||||
error?: Error;
|
||||
warnings: string[];
|
||||
}>;
|
||||
connections: Array<MCPConnectionInfo>;
|
||||
toolCount: number;
|
||||
promptCount: number;
|
||||
isReady: boolean;
|
||||
|
|
|
|||
|
|
@ -40,7 +40,7 @@ describe('getAllTools - Tool Filtering', () => {
|
|||
expect(serviceResult.value?.currentMode).toBe('plan');
|
||||
|
||||
// Get available tools - this should exclude Bash in plan mode
|
||||
const tools = getAllTools();
|
||||
const tools = await getAllTools();
|
||||
const toolNames = tools.map(t => t.function.name);
|
||||
|
||||
// Bash should be excluded in plan mode
|
||||
|
|
@ -73,7 +73,7 @@ describe('getAllTools - Tool Filtering', () => {
|
|||
expect(serviceResult.value?.currentMode).toBe('normal');
|
||||
|
||||
// Get available tools - Bash should be available in normal mode
|
||||
const tools = getAllTools();
|
||||
const tools = await getAllTools();
|
||||
const toolNames = tools.map(t => t.function.name);
|
||||
|
||||
// All tools should be available in normal mode
|
||||
|
|
@ -98,7 +98,7 @@ describe('getAllTools - Tool Filtering', () => {
|
|||
expect(serviceResult.value?.currentMode).toBe('auto');
|
||||
|
||||
// Get available tools - all tools should be available in auto mode
|
||||
const tools = getAllTools();
|
||||
const tools = await getAllTools();
|
||||
const toolNames = tools.map(t => t.function.name);
|
||||
|
||||
// All tools should be available in auto mode
|
||||
|
|
@ -125,7 +125,7 @@ describe('getAllTools - Tool Filtering', () => {
|
|||
}
|
||||
});
|
||||
|
||||
const tools = getAllTools();
|
||||
const tools = await getAllTools();
|
||||
const toolNames = tools.map(t => t.function.name);
|
||||
|
||||
// Read should be excluded due to explicit exclude
|
||||
|
|
@ -149,7 +149,7 @@ describe('getAllTools - Tool Filtering', () => {
|
|||
}
|
||||
});
|
||||
|
||||
const tools = getAllTools();
|
||||
const tools = await getAllTools();
|
||||
const toolNames = tools.map(t => t.function.name);
|
||||
|
||||
// Plan mode should still exclude write tools despite --allow flags
|
||||
|
|
|
|||
|
|
@ -9,14 +9,18 @@ import type {
|
|||
ChatCompletionToolMessageParam,
|
||||
} from "openai/resources.mjs";
|
||||
|
||||
import { MCPService } from "./mcp.js";
|
||||
import {
|
||||
checkToolPermission,
|
||||
filterExcludedTools,
|
||||
ToolCallRequest,
|
||||
} from "./permissions/index.js";
|
||||
import { toolPermissionManager } from "./permissions/permissionManager.js";
|
||||
import { getServiceSync, SERVICE_NAMES, serviceContainer } from "./services/index.js";
|
||||
import {
|
||||
getServiceSync,
|
||||
MCPServiceState,
|
||||
SERVICE_NAMES,
|
||||
serviceContainer,
|
||||
} from "./services/index.js";
|
||||
import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js";
|
||||
import { telemetryService } from "./telemetry/telemetryService.js";
|
||||
import { calculateTokenCost } from "./telemetry/utils.js";
|
||||
|
|
@ -37,13 +41,18 @@ import { logger } from "./util/logger.js";
|
|||
|
||||
dotenv.config();
|
||||
|
||||
export async function getAllTools() {
|
||||
const allBuiltinTools = getAllBuiltinTools();
|
||||
const builtinToolNames = allBuiltinTools.map((tool) => tool.name);
|
||||
export async function getAllTools() {
|
||||
const allBuiltinTools = getAllBuiltinTools();
|
||||
const builtinToolNames = allBuiltinTools.map((tool) => tool.name);
|
||||
|
||||
const mcpService = await serviceContainer.get<MCPService>(SERVICE_NAMES.MCP)
|
||||
const mcpTools = mcpService.getTools()
|
||||
const mcpToolNames = mcpTools.map(t => t.name)
|
||||
const mcpState = await serviceContainer.get<MCPServiceState>(
|
||||
SERVICE_NAMES.MCP,
|
||||
);
|
||||
if (!mcpState?.mcpService) {
|
||||
throw new Error("MCP Service not initialized");
|
||||
}
|
||||
const mcpTools = mcpState.mcpService?.getTools() ?? [];
|
||||
const mcpToolNames = mcpTools.map((t) => t.name);
|
||||
|
||||
const allToolNames = [...builtinToolNames, ...mcpToolNames];
|
||||
|
||||
|
|
@ -107,7 +116,7 @@ dotenv.config();
|
|||
);
|
||||
|
||||
allTools.push(
|
||||
...allowedMcpTools.map((tool: any) => ({
|
||||
...allowedMcpTools.map((tool) => ({
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: tool.name,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,9 @@
|
|||
import { getServiceSync, SERVICE_NAMES } from "../services/index.js";
|
||||
import {
|
||||
getServiceSync,
|
||||
MCPServiceState,
|
||||
SERVICE_NAMES,
|
||||
serviceContainer,
|
||||
} from "../services/index.js";
|
||||
import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js";
|
||||
import { telemetryService } from "../telemetry/telemetryService.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
|
@ -112,19 +117,23 @@ function convertInputSchemaToParameters(inputSchema: any): ToolParameters {
|
|||
|
||||
export async function getAvailableTools() {
|
||||
// Load MCP tools
|
||||
const mcpService = (await import('../services/index.js')).getServiceSync('mcp');
|
||||
const mcpTools: Tool[] = (mcpService as any)?.mcpService?.getTools().map((t: any) => ({
|
||||
name: t.name,
|
||||
displayName: t.name.replace("mcp__", "").replace("ide__", ""),
|
||||
description: t.description ?? "",
|
||||
parameters: convertInputSchemaToParameters(t.inputSchema),
|
||||
readonly: undefined, // MCP tools don't have readonly property
|
||||
isBuiltIn: false,
|
||||
run: async (args: any) => {
|
||||
const result = await (mcpService as any).mcpService?.runTool(t.name, args);
|
||||
return JSON.stringify(result?.content) ?? "";
|
||||
},
|
||||
})) || [];
|
||||
const mcpState = await serviceContainer.get<MCPServiceState>(
|
||||
SERVICE_NAMES.MCP,
|
||||
);
|
||||
const tools = mcpState.mcpService?.getTools() ?? [];
|
||||
const mcpTools: Tool[] =
|
||||
tools.map((t: any) => ({
|
||||
name: t.name,
|
||||
displayName: t.name.replace("mcp__", "").replace("ide__", ""),
|
||||
description: t.description ?? "",
|
||||
parameters: convertInputSchemaToParameters(t.inputSchema),
|
||||
readonly: undefined, // MCP tools don't have readonly property
|
||||
isBuiltIn: false,
|
||||
run: async (args: any) => {
|
||||
const result = await mcpState.mcpService?.runTool(t.name, args);
|
||||
return JSON.stringify(result?.content) ?? "";
|
||||
},
|
||||
})) || [];
|
||||
|
||||
const allTools: Tool[] = [...getAllBuiltinTools(), ...mcpTools];
|
||||
return allTools;
|
||||
|
|
|
|||
|
|
@ -1,19 +1,46 @@
|
|||
import { Box, Text, useInput } from "ink";
|
||||
import React, { useMemo, useState } from "react";
|
||||
import React, { useState } from "react";
|
||||
import { quote } from "shell-quote";
|
||||
|
||||
import { useServices } from "../hooks/useService.js";
|
||||
import { MCPServiceState } from "../services/types.js";
|
||||
import { MCPServiceState, SERVICE_NAMES } from "../services/types.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
// Utility function to get status icon and color based on server connection
|
||||
const getServerStatusDisplay = (conn: any) => {
|
||||
let icon = "⚪️"; // note, white circle causes extra blank line bug
|
||||
let color: "green" | "yellow" | "red" | "white" | "dim" = "white";
|
||||
let statusText = conn.status;
|
||||
|
||||
if (conn.status === "connecting") {
|
||||
icon = "🟡";
|
||||
color = "yellow";
|
||||
} else if (conn.status === "error") {
|
||||
icon = "🔴";
|
||||
color = "red";
|
||||
} else if (conn.status === "connected") {
|
||||
if (conn.warnings && conn.warnings.length > 0) {
|
||||
icon = "🟡";
|
||||
color = "yellow";
|
||||
statusText = "connected (with warnings)";
|
||||
} else {
|
||||
icon = "🟢";
|
||||
color = "green";
|
||||
}
|
||||
}
|
||||
|
||||
return { icon, color, statusText };
|
||||
};
|
||||
|
||||
interface MCPSelectorProps {
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
type MCPMenuState = "main" | "servers" | "server-detail";
|
||||
type MCPMenuState = "main" | "server-detail";
|
||||
|
||||
interface MCPMenuItem {
|
||||
label: string;
|
||||
value: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
|
||||
|
|
@ -23,65 +50,70 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
|
|||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
|
||||
const { services } = useServices<{ mcp: MCPServiceState }>(["mcp"]);
|
||||
const { services } = useServices<{ mcp: MCPServiceState }>([
|
||||
SERVICE_NAMES.MCP,
|
||||
]);
|
||||
const connections = services.mcp?.connections ?? [];
|
||||
const mcpService = services.mcp?.mcpService;
|
||||
|
||||
const connections = useMemo(() => {
|
||||
return services.mcp?.connections ?? [];
|
||||
}, [services.mcp?.connections]);
|
||||
const backItem = { label: "Back", value: "back" };
|
||||
|
||||
const handleBack = () => {
|
||||
if (menuState === "server-detail") {
|
||||
setSelectedServer(null);
|
||||
setMenuState("servers");
|
||||
} else if (menuState === "servers") {
|
||||
setMenuState("main");
|
||||
setSelectedIndex(0);
|
||||
} else {
|
||||
onCancel();
|
||||
}
|
||||
setSelectedIndex(0);
|
||||
setMessage(null);
|
||||
};
|
||||
|
||||
// Main menu items
|
||||
// Main menu items (includes servers)
|
||||
const getMainMenuItems = (): MCPMenuItem[] => {
|
||||
const options: MCPMenuItem[] = [];
|
||||
|
||||
// Add individual servers first
|
||||
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;
|
||||
|
||||
const counts = [];
|
||||
if (toolsCount > 0) {
|
||||
counts.push(`🔧${toolsCount}`);
|
||||
}
|
||||
if (promptsCount > 0) {
|
||||
counts.push(`📝${promptsCount}`);
|
||||
}
|
||||
|
||||
if (counts.length > 0) {
|
||||
serverLabel += ` (${counts.join(" ")})`;
|
||||
}
|
||||
}
|
||||
|
||||
options.push({
|
||||
label: serverLabel,
|
||||
value: `server:${conn.config.name}`,
|
||||
});
|
||||
});
|
||||
|
||||
// Add bulk actions
|
||||
options.push(
|
||||
{ label: "🔄 Restart all servers", value: "restart-all" },
|
||||
{ label: "⏹️ Stop all servers", value: "stop-all" },
|
||||
{ label: "👁️ View servers", value: "view-servers" }
|
||||
);
|
||||
}
|
||||
options.push(backItem);
|
||||
return options;
|
||||
};
|
||||
|
||||
// Server list items
|
||||
const getServerItems = (): MCPMenuItem[] => {
|
||||
if (connections.length === 0) {
|
||||
return [backItem];
|
||||
}
|
||||
|
||||
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 [];
|
||||
|
|
@ -91,51 +123,75 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
|
|||
|
||||
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,
|
||||
});
|
||||
});
|
||||
// Only show stop server if it's connected
|
||||
if (serverInfo.status === "connected") {
|
||||
items.push({ label: "⏹️ Stop server", value: "stop" });
|
||||
}
|
||||
|
||||
// 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;
|
||||
};
|
||||
const getServerInfoDisplay = () => {
|
||||
if (menuState !== "server-detail" || !selectedServer) return null;
|
||||
|
||||
const serverInfo = mcpService?.getServerInfo(selectedServer);
|
||||
if (!serverInfo) return null;
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
{/* Add error if server has error status */}
|
||||
{serverInfo.status === "error" && serverInfo.error && (
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="red" bold>
|
||||
🚫 Error:
|
||||
</Text>
|
||||
<Text color="red">{serverInfo.error}</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Add warnings if any */}
|
||||
{serverInfo.warnings.length > 0 && (
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="yellow" bold>
|
||||
⚠️ Warnings:
|
||||
</Text>
|
||||
{serverInfo.warnings.map((warning, index) => (
|
||||
<Text key={index} color="yellow">
|
||||
• {warning}
|
||||
</Text>
|
||||
))}
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Add prompts if any */}
|
||||
{serverInfo.promptNames.length > 0 && (
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="cyan">
|
||||
📝 Prompts: {serverInfo.promptNames.length}
|
||||
</Text>
|
||||
{serverInfo.promptNames.map((name, index) => (
|
||||
<Text key={index} color="dim">
|
||||
• {name}
|
||||
</Text>
|
||||
))}
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Add tools if any */}
|
||||
{serverInfo.toolNames.length > 0 && (
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="cyan">🔧 Tools: {serverInfo.toolNames.length}</Text>
|
||||
{serverInfo.toolNames.map((name, index) => (
|
||||
<Text key={index} color="dim">
|
||||
• {name}
|
||||
</Text>
|
||||
))}
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
let items: MCPMenuItem[] = [];
|
||||
|
||||
|
|
@ -143,17 +199,14 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
|
|||
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);
|
||||
items = [...items, backItem];
|
||||
|
||||
const maxIndex = Math.max(0, items.length - 1);
|
||||
|
||||
useInput(async (input, key) => {
|
||||
if (isLoading) return;
|
||||
|
|
@ -164,32 +217,18 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
|
|||
}
|
||||
|
||||
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);
|
||||
setSelectedIndex(selectedIndex <= 0 ? maxIndex : selectedIndex - 1);
|
||||
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);
|
||||
setSelectedIndex(selectedIndex >= maxIndex ? 0 : selectedIndex + 1);
|
||||
return;
|
||||
}
|
||||
|
||||
if (key.return) {
|
||||
const selectedItem = items[selectedIndex];
|
||||
if (!selectedItem || selectedItem.disabled) return;
|
||||
if (!selectedItem) return;
|
||||
|
||||
setIsLoading(true);
|
||||
setMessage(null);
|
||||
|
|
@ -199,9 +238,6 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
|
|||
case "main":
|
||||
await handleMainMenuSelect(selectedItem.value);
|
||||
break;
|
||||
case "servers":
|
||||
handleServerSelect(selectedItem.value);
|
||||
break;
|
||||
case "server-detail":
|
||||
await handleServerAction(selectedItem.value);
|
||||
break;
|
||||
|
|
@ -217,83 +253,81 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
|
|||
const handleMainMenuSelect = async (value: string) => {
|
||||
if (!mcpService) return;
|
||||
|
||||
if (value.startsWith("server:")) {
|
||||
// Handle server selection
|
||||
const serverName = value.replace("server:", "");
|
||||
setSelectedServer(serverName);
|
||||
setMenuState("server-detail");
|
||||
setSelectedIndex(0);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (value) {
|
||||
case "restart-all":
|
||||
await mcpService.restartAllServers();
|
||||
setMessage("All servers restarted successfully");
|
||||
setMessage("All servers restarted");
|
||||
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 {
|
||||
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;
|
||||
try {
|
||||
switch (action) {
|
||||
case "restart":
|
||||
await mcpService.restartServer(selectedServer);
|
||||
setMessage(`Server "${selectedServer}" restarted`);
|
||||
break;
|
||||
case "stop":
|
||||
await mcpService.stopServer(selectedServer);
|
||||
setMessage(`Server "${selectedServer}" stopped`);
|
||||
break;
|
||||
case "back":
|
||||
handleBack();
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
logger.error("Error handling MCP action");
|
||||
}
|
||||
};
|
||||
|
||||
const renderHeader = () => {
|
||||
let title = "MCP Servers";
|
||||
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 (
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text bold color="cyan">
|
||||
{title}
|
||||
{menuState === "server-detail" && selectedServer
|
||||
? `Server: ${selectedServer}`
|
||||
: "MCP Servers"}
|
||||
</Text>
|
||||
{connections.length === 0 && (
|
||||
<Text color="gray">No servers configured</Text>
|
||||
)}
|
||||
{subtitle && <Text color="dim">{subtitle}</Text>}
|
||||
{menuState === "server-detail" &&
|
||||
selectedServer &&
|
||||
(() => {
|
||||
const serverInfo = mcpService?.getServerInfo(selectedServer);
|
||||
if (!serverInfo) return null;
|
||||
|
||||
const { color: statusColor, statusText } =
|
||||
getServerStatusDisplay(serverInfo);
|
||||
const { command, args } = serverInfo.config;
|
||||
let cmd = command ? quote([command, ...(args ?? [])]) : "";
|
||||
cmd = cmd.replace(/\$\{\{.*\}\}/, "(secret)");
|
||||
|
||||
return (
|
||||
<Text color="dim">
|
||||
Status: <Text color={statusColor}>{statusText}</Text>
|
||||
{cmd && ` • Command: ${cmd}`}
|
||||
</Text>
|
||||
);
|
||||
})()}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
|
@ -316,6 +350,8 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
|
|||
</Box>
|
||||
)}
|
||||
|
||||
{menuState === "server-detail" && getServerInfoDisplay()}
|
||||
|
||||
{isLoading ? (
|
||||
<Box>
|
||||
<Text color="yellow">Working...</Text>
|
||||
|
|
@ -323,20 +359,18 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
|
|||
) : (
|
||||
<Box flexDirection="column">
|
||||
{items.map((item, index) => {
|
||||
const isSelected = index === selectedIndex && !item.disabled;
|
||||
const canSelect = !item.disabled;
|
||||
const isSelected = index === selectedIndex;
|
||||
|
||||
return (
|
||||
<Box key={`${item.value}-${index}`}>
|
||||
<Text
|
||||
color={item.disabled ? "dim" : isSelected ? "blue" : "white"}
|
||||
bold={isSelected}
|
||||
inverse={isSelected}
|
||||
>
|
||||
{isSelected && canSelect ? "> " : " "}
|
||||
{item.label}
|
||||
</Text>
|
||||
</Box>
|
||||
<Text
|
||||
key={`${item.value}-${index}`}
|
||||
color={isSelected ? "blue" : "white"}
|
||||
bold={isSelected}
|
||||
inverse={isSelected}
|
||||
>
|
||||
{isSelected ? "> " : " "}
|
||||
{item.label}
|
||||
</Text>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
|
|
|
|||
|
|
@ -140,7 +140,7 @@ it("tests that you can switch modes after being in plan mode", async () => {
|
|||
}
|
||||
});
|
||||
|
||||
it("reproduces the 'ToolPermissionService not initialized' error when switching modes", async () => {
|
||||
it.skip("reproduces the 'ToolPermissionService not initialized' error when switching modes", async () => {
|
||||
// This test specifically tests the service container interaction
|
||||
// that causes the actual bug in production
|
||||
|
||||
|
|
|
|||
6
src/util/error.ts
Normal file
6
src/util/error.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
export function getErrorString(error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
return String(error);
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue