handleToolsCall 处理 tools/call 请求
(w http.ResponseWriter, ctx context.Context, req *cloud.MCPRequest)
| 120 | |
| 121 | // handleToolsCall 处理 tools/call 请求 |
| 122 | func (s *Server) handleToolsCall(w http.ResponseWriter, ctx context.Context, req *cloud.MCPRequest) { |
| 123 | params := req.Params |
| 124 | if params.Name == "" { |
| 125 | writeError(w, req.ID, -32602, "tool name is required", nil) |
| 126 | return |
| 127 | } |
| 128 | |
| 129 | tool, err := s.registry.Create(params.Name, nil) |
| 130 | if err != nil { |
| 131 | writeError(w, req.ID, -32601, "tool not found: "+params.Name, err) |
| 132 | return |
| 133 | } |
| 134 | |
| 135 | var tc *tools.ToolContext |
| 136 | if s.contextFactory != nil { |
| 137 | tc = s.contextFactory(ctx) |
| 138 | } |
| 139 | |
| 140 | // 使用 Executor 执行工具 |
| 141 | result := s.executor.Execute(ctx, &tools.ExecuteRequest{ |
| 142 | Tool: tool, |
| 143 | Input: params.Arguments, |
| 144 | Context: tc, |
| 145 | }) |
| 146 | |
| 147 | if result.Error != nil { |
| 148 | writeError(w, req.ID, -32000, "tool execution failed", result.Error) |
| 149 | return |
| 150 | } |
| 151 | |
| 152 | // MCPResponse.Result 是任意 JSON, 这里直接编码为 raw message |
| 153 | raw, err := json.Marshal(result.Output) |
| 154 | if err != nil { |
| 155 | writeError(w, req.ID, -32001, "marshal tool result failed", err) |
| 156 | return |
| 157 | } |
| 158 | |
| 159 | mcpResp := cloud.MCPResponse{ |
| 160 | JSONRPC: "2.0", |
| 161 | ID: req.ID, |
| 162 | Result: raw, |
| 163 | } |
| 164 | |
| 165 | writeJSON(w, http.StatusOK, mcpResp) |
| 166 | } |
| 167 | |
| 168 | func writeJSON(w http.ResponseWriter, status int, v any) { |
| 169 | w.Header().Set("Content-Type", "application/json; charset=utf-8") |
no test coverage detected