CallTool 调用 MCP 工具
(ctx context.Context, toolName string, params map[string]any)
| 47 | |
| 48 | // CallTool 调用 MCP 工具 |
| 49 | func (mc *MCPClient) CallTool(ctx context.Context, toolName string, params map[string]any) (json.RawMessage, error) { |
| 50 | // 构建 MCP 请求 |
| 51 | request := &MCPRequest{ |
| 52 | JSONRPC: "2.0", |
| 53 | Method: "tools/call", |
| 54 | ID: time.Now().UnixNano(), |
| 55 | Params: MCPCallParams{ |
| 56 | Name: toolName, |
| 57 | Arguments: params, |
| 58 | }, |
| 59 | } |
| 60 | |
| 61 | reqBody, err := json.Marshal(request) |
| 62 | if err != nil { |
| 63 | return nil, fmt.Errorf("marshal request: %w", err) |
| 64 | } |
| 65 | |
| 66 | // 创建 HTTP 请求 |
| 67 | httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, mc.endpoint, bytes.NewReader(reqBody)) |
| 68 | if err != nil { |
| 69 | return nil, fmt.Errorf("create request: %w", err) |
| 70 | } |
| 71 | |
| 72 | // 设置请求头 |
| 73 | httpReq.Header.Set("Content-Type", "application/json") |
| 74 | httpReq.Header.Set("X-Access-Key-Id", mc.accessKeyID) |
| 75 | httpReq.Header.Set("X-Access-Key-Secret", mc.accessKeySecret) |
| 76 | if mc.securityToken != "" { |
| 77 | httpReq.Header.Set("X-Security-Token", mc.securityToken) |
| 78 | } |
| 79 | |
| 80 | // 发送请求 |
| 81 | resp, err := mc.httpClient.Do(httpReq) |
| 82 | if err != nil { |
| 83 | return nil, fmt.Errorf("send request: %w", err) |
| 84 | } |
| 85 | defer func() { _ = resp.Body.Close() }() |
| 86 | |
| 87 | // 读取响应 |
| 88 | respBody, err := io.ReadAll(resp.Body) |
| 89 | if err != nil { |
| 90 | return nil, fmt.Errorf("read response: %w", err) |
| 91 | } |
| 92 | |
| 93 | // 检查 HTTP 状态码 |
| 94 | if resp.StatusCode != http.StatusOK { |
| 95 | return nil, fmt.Errorf("http error: %d - %s", resp.StatusCode, string(respBody)) |
| 96 | } |
| 97 | |
| 98 | // 解析 MCP 响应 |
| 99 | var mcpResp MCPResponse |
| 100 | if err := json.Unmarshal(respBody, &mcpResp); err != nil { |
| 101 | return nil, fmt.Errorf("unmarshal response: %w", err) |
| 102 | } |
| 103 | |
| 104 | // 检查 MCP 错误 |
| 105 | if mcpResp.Error != nil { |
| 106 | return nil, fmt.Errorf("mcp error: %s (code: %d)", mcpResp.Error.Message, mcpResp.Error.Code) |