|
| 1 | +import { Server } from "@modelcontextprotocol/sdk/server/index.js"; |
| 2 | +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; |
| 3 | +import { |
| 4 | + CallToolRequestSchema, |
| 5 | + ListToolsRequestSchema, |
| 6 | +} from "@modelcontextprotocol/sdk/types.js"; |
| 7 | +import { ToolLoader, ToolLoaderOptions } from "./toolLoader.js"; |
| 8 | +import { BaseTool } from "../tools/BaseTool.js"; |
| 9 | + |
| 10 | +export interface MCPServerConfig { |
| 11 | + name: string; |
| 12 | + version: string; |
| 13 | + toolsDir?: string; |
| 14 | + excludeTools?: string[]; |
| 15 | +} |
| 16 | + |
| 17 | +export class MCPServer { |
| 18 | + private server: Server; |
| 19 | + private toolsMap: Map<string, BaseTool> = new Map(); |
| 20 | + private toolLoader: ToolLoader; |
| 21 | + |
| 22 | + constructor(config: MCPServerConfig) { |
| 23 | + this.server = new Server( |
| 24 | + { |
| 25 | + name: config.name, |
| 26 | + version: config.version, |
| 27 | + }, |
| 28 | + { |
| 29 | + capabilities: { |
| 30 | + tools: {}, |
| 31 | + }, |
| 32 | + } |
| 33 | + ); |
| 34 | + |
| 35 | + this.toolLoader = new ToolLoader({ |
| 36 | + toolsDir: config.toolsDir, |
| 37 | + exclude: config.excludeTools, |
| 38 | + }); |
| 39 | + |
| 40 | + this.setupHandlers(); |
| 41 | + } |
| 42 | + |
| 43 | + private setupHandlers() { |
| 44 | + this.server.setRequestHandler(ListToolsRequestSchema, async () => ({ |
| 45 | + tools: Array.from(this.toolsMap.values()).map( |
| 46 | + (tool) => tool.toolDefinition |
| 47 | + ), |
| 48 | + })); |
| 49 | + |
| 50 | + this.server.setRequestHandler(CallToolRequestSchema, async (request) => { |
| 51 | + const tool = this.toolsMap.get(request.params.name); |
| 52 | + if (!tool) { |
| 53 | + throw new Error( |
| 54 | + `Unknown tool: ${request.params.name}. Available tools: ${Array.from( |
| 55 | + this.toolsMap.keys() |
| 56 | + ).join(", ")}` |
| 57 | + ); |
| 58 | + } |
| 59 | + return tool.toolCall(request); |
| 60 | + }); |
| 61 | + } |
| 62 | + |
| 63 | + async start() { |
| 64 | + try { |
| 65 | + const tools = await this.toolLoader.loadTools(); |
| 66 | + this.toolsMap = new Map(tools.map((tool: BaseTool) => [tool.name, tool])); |
| 67 | + |
| 68 | + const transport = new StdioServerTransport(); |
| 69 | + await this.server.connect(transport); |
| 70 | + } catch (error) { |
| 71 | + console.error("Server initialization error:", error); |
| 72 | + throw error; |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments