refactor: update tool registration to support multiple clients and transports

This commit is contained in:
samanhappy
2025-03-31 18:11:24 +08:00
parent c34e176563
commit c34e54673b
2 changed files with 44 additions and 19 deletions

View File

@@ -12,7 +12,7 @@ const server = new McpServer({
});
// Register all MCP tools from the modular structure
registerAllTools(server);
await registerAllTools(server);
const app = express();
const PORT = process.env.PORT || 3000;

View File

@@ -1,11 +1,11 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { ZodType, ZodRawShape } from 'zod';
const transport = new SSEClientTransport(new URL('http://localhost:3001/sse'));
const client = new Client(
const transport1 = new SSEClientTransport(new URL('http://localhost:3001/sse'));
const client1 = new Client(
{
name: 'example-client',
version: '1.0.0',
@@ -19,22 +19,46 @@ const client = new Client(
},
);
const transport2 = new StdioClientTransport({
command: 'python3',
args: ['-m', 'mcp_server_time', '--local-timezone=America/New_York'],
});
const client2 = new Client(
{
name: 'example-client',
version: '1.0.0',
},
{
capabilities: {
prompts: {},
resources: {},
tools: {},
},
},
);
const clients = [client1, client2];
const transports = [transport1, transport2];
export const registerAllTools = async (server: McpServer) => {
await client.connect(transport);
const tools = await client.listTools();
for (const tool of tools.tools) {
await server.tool(
tool.name,
tool.description || '',
cast(tool.inputSchema.properties),
async (params) => {
const result = await client.callTool({
name: tool.name,
arguments: params,
});
return { content: [{ type: 'text', text: JSON.stringify(result) }] };
},
);
for (const client of clients) {
await client.connect(transports[clients.indexOf(client)]);
const tools = await client.listTools();
for (const tool of tools.tools) {
console.log(`Registering tool: ${JSON.stringify(tool)}`);
await server.tool(
tool.name,
tool.description || '',
cast(tool.inputSchema.properties),
async (params) => {
const result = await client1.callTool({
name: tool.name,
arguments: params,
});
return { content: [{ type: 'text', text: JSON.stringify(result) }] };
},
);
}
}
};
@@ -51,5 +75,6 @@ function cast(inputSchema: unknown): ZodRawShape {
}
}
console.log(`Casted schema: ${JSON.stringify(castedSchema)}`);
return castedSchema;
}