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