ListTools 列出可用工具
(ctx context.Context)
| 111 | |
| 112 | // ListTools 列出可用工具 |
| 113 | func (mc *MCPClient) ListTools(ctx context.Context) ([]MCPTool, error) { |
| 114 | request := &MCPRequest{ |
| 115 | JSONRPC: "2.0", |
| 116 | Method: "tools/list", |
| 117 | ID: time.Now().UnixNano(), |
| 118 | } |
| 119 | |
| 120 | reqBody, err := json.Marshal(request) |
| 121 | if err != nil { |
| 122 | return nil, fmt.Errorf("marshal request: %w", err) |
| 123 | } |
| 124 | |
| 125 | httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, mc.endpoint, bytes.NewReader(reqBody)) |
| 126 | if err != nil { |
| 127 | return nil, fmt.Errorf("create request: %w", err) |
| 128 | } |
| 129 | |
| 130 | httpReq.Header.Set("Content-Type", "application/json") |
| 131 | httpReq.Header.Set("X-Access-Key-Id", mc.accessKeyID) |
| 132 | httpReq.Header.Set("X-Access-Key-Secret", mc.accessKeySecret) |
| 133 | if mc.securityToken != "" { |
| 134 | httpReq.Header.Set("X-Security-Token", mc.securityToken) |
| 135 | } |
| 136 | |
| 137 | resp, err := mc.httpClient.Do(httpReq) |
| 138 | if err != nil { |
| 139 | return nil, fmt.Errorf("send request: %w", err) |
| 140 | } |
| 141 | defer func() { _ = resp.Body.Close() }() |
| 142 | |
| 143 | respBody, err := io.ReadAll(resp.Body) |
| 144 | if err != nil { |
| 145 | return nil, fmt.Errorf("read response: %w", err) |
| 146 | } |
| 147 | |
| 148 | if resp.StatusCode != http.StatusOK { |
| 149 | return nil, fmt.Errorf("http error: %d - %s", resp.StatusCode, string(respBody)) |
| 150 | } |
| 151 | |
| 152 | var mcpResp struct { |
| 153 | JSONRPC string `json:"jsonrpc"` |
| 154 | ID int64 `json:"id"` |
| 155 | Result struct { |
| 156 | Tools []MCPTool `json:"tools"` |
| 157 | } `json:"result"` |
| 158 | Error *MCPError `json:"error,omitempty"` |
| 159 | } |
| 160 | |
| 161 | if err := json.Unmarshal(respBody, &mcpResp); err != nil { |
| 162 | return nil, fmt.Errorf("unmarshal response: %w", err) |
| 163 | } |
| 164 | |
| 165 | if mcpResp.Error != nil { |
| 166 | return nil, fmt.Errorf("mcp error: %s", mcpResp.Error.Message) |
| 167 | } |
| 168 | |
| 169 | return mcpResp.Result.Tools, nil |
| 170 | } |