MCPcopy Create free account
hub / github.com/astercloud/aster / CallTool

Method CallTool

pkg/sandbox/cloud/mcp.go:49–110  ·  view source on GitHub ↗

CallTool 调用 MCP 工具

(ctx context.Context, toolName string, params map[string]any)

Source from the content-addressed store, hash-verified

47
48// CallTool 调用 MCP 工具
49func (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)

Callers 13

ExecMethod · 0.45
initOSSMethod · 0.45
ReadMethod · 0.45
WriteMethod · 0.45
StatMethod · 0.45
GlobMethod · 0.45
ExecMethod · 0.45
DisposeMethod · 0.45
initSessionMethod · 0.45
ReadMethod · 0.45
WriteMethod · 0.45
StatMethod · 0.45

Calls 2

SetMethod · 0.65
CloseMethod · 0.65

Tested by

no test coverage detected