使 LLMs 能够通过你的服务器执行操作
tools/list
tools/call
{ name: string; // 工具的唯一标识符 description?: string; // 人类可读的描述 inputSchema: { // 工具参数的 JSON Schema type: "object", properties: { ... } // 工具特定的参数 } }
const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: { tools: {} } }); // 定义可用工具 server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [{ name: "calculate_sum", description: "将两个数字相加", inputSchema: { type: "object", properties: { a: { type: "number" }, b: { type: "number" } }, required: ["a", "b"] } }] }; }); // 处理工具执行 server.setRequestHandler(CallToolRequestSchema, async (request) => { if (request.params.name === "calculate_sum") { const { a, b } = request.params.arguments; return { content: [ { type: "text", text: String(a + b) } ] }; } throw new Error("Tool not found"); });
{ name: "execute_command", description: "运行 shell 命令", inputSchema: { type: "object", properties: { command: { type: "string" }, args: { type: "array", items: { type: "string" } } } } }
{ name: "github_create_issue", description: "创建 GitHub issue", inputSchema: { type: "object", properties: { title: { type: "string" }, body: { type: "string" }, labels: { type: "array", items: { type: "string" } } } } }
{ name: "analyze_csv", description: "分析 CSV 文件", inputSchema: { type: "object", properties: { filepath: { type: "string" }, operations: { type: "array", items: { enum: ["sum", "average", "count"] } } } } }
notifications/tools/list_changed
isError
true
content
try { // 工具操作 const result = performOperation(); return { content: [ { type: "text", text: `操作成功:${result}` } ] }; } catch (error) { return { isError: true, content: [ { type: "text", text: `错误:${error.message}` } ] }; }