* 调用 MCP 工具
(toolName: string, args: Record<string, any>)
| 284 | * 调用 MCP 工具 |
| 285 | */ |
| 286 | async callTool(toolName: string, args: Record<string, any>): Promise<any> { |
| 287 | if (!this.client) { |
| 288 | throw new Error('MCP 客户端未初始化'); |
| 289 | } |
| 290 | |
| 291 | // 查找包含该工具的服务器 |
| 292 | for (const [sessionId, tools] of this.tools.entries()) { |
| 293 | const tool = tools.find(t => t.name === toolName); |
| 294 | if (tool) { |
| 295 | try { |
| 296 | const result = await this.client.callTool(sessionId, { |
| 297 | name: toolName, |
| 298 | arguments: args, |
| 299 | }); |
| 300 | |
| 301 | if (result.isError) { |
| 302 | throw new Error(`工具执行错误: ${result.content[0]?.text || '未知错误'}`); |
| 303 | } |
| 304 | |
| 305 | return result.content[0]?.text || result; |
| 306 | } catch (error) { |
| 307 | this.log(`调用 MCP 工具失败 ${toolName}: ${error}`); |
| 308 | throw error; |
| 309 | } |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | throw new Error(`未找到 MCP 工具: ${toolName}`); |
| 314 | } |
| 315 | |
| 316 | /** |
| 317 | * 搜索资源 |