1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
| import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js"; import { z } from "zod";
const server = new Server( { name: "my-ts-server", version: "1.0.0", }, { capabilities: { tools: {}, }, } );
const GreetSchema = z.object({ name: z.string().min(1).describe("要问候的人名"), language: z.enum(["zh", "en"]).optional().default("zh").describe("语言"), });
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [ { name: "greet", description: "向用户问好", inputSchema: { type: "object", properties: { name: { type: "string", description: "要问候的人名" }, language: { type: "string", enum: ["zh", "en"], description: "语言", default: "zh", }, }, required: ["name"], }, }, { name: "calculate", description: "执行数学计算", inputSchema: { type: "object", properties: { a: { type: "number", description: "第一个数字" }, b: { type: "number", description: "第二个数字" }, operation: { type: "string", enum: ["add", "subtract", "multiply", "divide"], description: "计算操作", }, }, required: ["a", "b", "operation"], }, }, ], }));
server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name, arguments: args } = request.params;
switch (name) { case "greet": { const { name: personName, language } = GreetSchema.parse(args); const greeting = language === "zh" ? `你好,${personName}!` : `Hello, ${personName}!`; return { content: [{ type: "text", text: greeting }], }; }
case "calculate": { const { a, b, operation } = args as { a: number; b: number; operation: string }; let result: number;
switch (operation) { case "add": result = a + b; break; case "subtract": result = a - b; break; case "multiply": result = a * b; break; case "divide": if (b === 0) { return { isError: true, content: [{ type: "text", text: "错误:除数不能为零" }], }; } result = a / b; break; default: return { isError: true, content: [{ type: "text", text: `不支持的运算:${operation}` }], }; }
return { content: [{ type: "text", text: `${a} ${operation} ${b} = ${result}` }], }; }
default: return { isError: true, content: [{ type: "text", text: `未知工具:${name}` }], }; } });
async function main() { const transport = new StdioServerTransport(); await server.connect(transport); console.error("✅ TypeScript MCP 服务器已启动"); }
main().catch((error) => { console.error("服务器启动失败:", error); process.exit(1); });
|