|
| 1 | +import { Server } from "@modelcontextprotocol/sdk/server/index.js"; |
| 2 | +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; |
| 3 | +import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js"; |
| 4 | +import { z } from 'zod'; |
| 5 | +import { zodToJsonSchema } from 'zod-to-json-schema'; |
| 6 | +import { isGiteeError } from "./errors.js"; |
| 7 | + |
| 8 | +type MCPServerOptions = { |
| 9 | + name: string; |
| 10 | + version: string; |
| 11 | +}; |
| 12 | + |
| 13 | +type ToolDefinition = { |
| 14 | + name: string; |
| 15 | + description: string; |
| 16 | + schema: z.ZodType<any, any, any>; |
| 17 | + handler: (params: any) => Promise<any>; |
| 18 | +}; |
| 19 | + |
| 20 | +export class MCPServer { |
| 21 | + private server: Server; |
| 22 | + private tools: Map<string, ToolDefinition> = new Map(); |
| 23 | + |
| 24 | + constructor(options: MCPServerOptions) { |
| 25 | + this.server = new Server( |
| 26 | + { |
| 27 | + name: options.name, |
| 28 | + version: options.version, |
| 29 | + }, |
| 30 | + { |
| 31 | + capabilities: { |
| 32 | + tools: {}, |
| 33 | + }, |
| 34 | + } |
| 35 | + ); |
| 36 | + |
| 37 | + this.setupRequestHandlers(); |
| 38 | + } |
| 39 | + |
| 40 | + private setupRequestHandlers() { |
| 41 | + this.server.setRequestHandler(ListToolsRequestSchema, async () => { |
| 42 | + const toolsList = Array.from(this.tools.values()).map((tool) => ({ |
| 43 | + name: tool.name, |
| 44 | + description: tool.description, |
| 45 | + inputSchema: zodToJsonSchema(tool.schema), |
| 46 | + })); |
| 47 | + |
| 48 | + return { |
| 49 | + tools: toolsList, |
| 50 | + }; |
| 51 | + }); |
| 52 | + |
| 53 | + this.server.setRequestHandler(CallToolRequestSchema, async (request) => { |
| 54 | + try { |
| 55 | + if (!request.params.arguments) { |
| 56 | + throw new Error("Parameters are necessary."); |
| 57 | + } |
| 58 | + |
| 59 | + const tool = this.tools.get(request.params.name); |
| 60 | + if (!tool) { |
| 61 | + throw new Error(`Unknown tool: ${request.params.name}`); |
| 62 | + } |
| 63 | + |
| 64 | + const args = tool.schema.parse(request.params.arguments); |
| 65 | + const result = await tool.handler(args); |
| 66 | + |
| 67 | + return { |
| 68 | + content: [{ type: "text", text: JSON.stringify(result, null, 2) }], |
| 69 | + }; |
| 70 | + } catch (error) { |
| 71 | + if (error instanceof z.ZodError) { |
| 72 | + throw new Error(`Invalid input: ${JSON.stringify(error.errors)}`); |
| 73 | + } |
| 74 | + if (isGiteeError(error)) { |
| 75 | + throw error; |
| 76 | + } |
| 77 | + throw error; |
| 78 | + } |
| 79 | + }); |
| 80 | + } |
| 81 | + |
| 82 | + public registerTool(tool: ToolDefinition) { |
| 83 | + this.tools.set(tool.name, tool); |
| 84 | + } |
| 85 | + |
| 86 | + public async connect(transport: StdioServerTransport) { |
| 87 | + await this.server.connect(transport); |
| 88 | + } |
| 89 | +} |
0 commit comments