xonecas.io
60255
Zn

Zoea-Nova / files

Zoea-Nova / internal / mcp / client.go

8.8 KB
1package mcp
2
3import (
4	"bufio"
5	"bytes"
6	"context"
7	"encoding/json"
8	"fmt"
9	"io"
10	"net/http"
11	"strings"
12	"sync/atomic"
13	"time"
14)
15
16// Client is an MCP client that communicates with an upstream server.
17type Client struct {
18	endpoint        string
19	httpClient      *http.Client
20	requestID       atomic.Int64
21	sessionID       string // Session ID from server, included in subsequent requests
22	protocolVersion string // Negotiated protocol version
23}
24
25// NewClient creates a new MCP client.
26func NewClient(endpoint string) *Client {
27	return &Client{
28		endpoint: endpoint,
29		httpClient: &http.Client{
30			Timeout: 30 * time.Second, // 30s timeout to prevent hanging requests
31		},
32		protocolVersion: "2024-11-05", // Default, may be updated during initialization
33	}
34}
35
36// nextID returns the next request ID.
37func (c *Client) nextID() int64 {
38	return c.requestID.Add(1)
39}
40
41// Call makes an MCP request and returns the response.
42func (c *Client) Call(ctx context.Context, method string, params interface{}) (*Response, error) {
43	req, err := NewRequest(c.nextID(), method, params)
44	if err != nil {
45		return nil, fmt.Errorf("create request: %w", err)
46	}
47
48	return c.send(ctx, req)
49}
50
51// send sends a request and receives a response.
52// Supports both JSON and SSE (Streamable HTTP) responses per MCP spec.
53func (c *Client) send(ctx context.Context, req *Request) (*Response, error) {
54	body, err := json.Marshal(req)
55	if err != nil {
56		return nil, fmt.Errorf("marshal request: %w", err)
57	}
58
59	httpReq, err := http.NewRequestWithContext(ctx, "POST", c.endpoint, bytes.NewReader(body))
60	if err != nil {
61		return nil, fmt.Errorf("create http request: %w", err)
62	}
63
64	httpReq.Header.Set("Content-Type", "application/json")
65	httpReq.Header.Set("Accept", "application/json, text/event-stream")
66
67	// Include session ID if we have one (required after initialization)
68	if c.sessionID != "" {
69		httpReq.Header.Set("Mcp-Session-Id", c.sessionID)
70	}
71
72	// Include protocol version header
73	if c.protocolVersion != "" {
74		httpReq.Header.Set("MCP-Protocol-Version", c.protocolVersion)
75	}
76
77	httpResp, err := c.httpClient.Do(httpReq)
78	if err != nil {
79		return nil, fmt.Errorf("http request: %w", err)
80	}
81	defer httpResp.Body.Close()
82
83	if httpResp.StatusCode != http.StatusOK {
84		respBody, _ := io.ReadAll(httpResp.Body)
85
86		// For 429 rate limits, include Retry-After header if present
87		if httpResp.StatusCode == http.StatusTooManyRequests {
88			if retryAfter := httpResp.Header.Get("Retry-After"); retryAfter != "" {
89				return nil, fmt.Errorf("http error %d: %s (Retry-After: %s)", httpResp.StatusCode, string(respBody), retryAfter)
90			}
91		}
92
93		return nil, fmt.Errorf("http error %d: %s", httpResp.StatusCode, string(respBody))
94	}
95
96	// Capture session ID from response if present
97	if sessionID := httpResp.Header.Get("Mcp-Session-Id"); sessionID != "" {
98		c.sessionID = sessionID
99	}
100
101	contentType := httpResp.Header.Get("Content-Type")
102
103	// Handle SSE (Server-Sent Events) response
104	if strings.HasPrefix(contentType, "text/event-stream") {
105		return c.parseSSEResponse(httpResp.Body)
106	}
107
108	// Handle plain JSON response
109	respBody, err := io.ReadAll(httpResp.Body)
110	if err != nil {
111		return nil, fmt.Errorf("read response: %w", err)
112	}
113
114	var resp Response
115	if err := json.Unmarshal(respBody, &resp); err != nil {
116		return nil, fmt.Errorf("unmarshal response: %w", err)
117	}
118
119	return &resp, nil
120}
121
122// parseSSEResponse parses a Server-Sent Events stream for MCP responses.
123func (c *Client) parseSSEResponse(body io.Reader) (*Response, error) {
124	scanner := bufio.NewScanner(body)
125	maxTokenSize := 2 * 1024 * 1024
126	scanner.Buffer(make([]byte, 0, 64*1024), maxTokenSize)
127	var dataLines []string
128
129	for scanner.Scan() {
130		line := scanner.Text()
131
132		// SSE format: "data: {...json...}" or "event: message"
133		if strings.HasPrefix(line, "data: ") {
134			dataLines = append(dataLines, strings.TrimPrefix(line, "data: "))
135		} else if line == "" && len(dataLines) > 0 {
136			// Empty line marks end of event, try to parse accumulated data
137			data := strings.Join(dataLines, "")
138			dataLines = nil
139
140			var resp Response
141			if err := json.Unmarshal([]byte(data), &resp); err != nil {
142				continue // Skip malformed events
143			}
144
145			// Return first valid response with our request ID
146			if resp.ID != nil {
147				return &resp, nil
148			}
149		}
150	}
151
152	if err := scanner.Err(); err != nil {
153		return nil, fmt.Errorf("read SSE stream: %w", err)
154	}
155
156	// If we collected data but no empty line terminated it
157	if len(dataLines) > 0 {
158		data := strings.Join(dataLines, "")
159		var resp Response
160		if err := json.Unmarshal([]byte(data), &resp); err != nil {
161			return nil, fmt.Errorf("unmarshal final SSE data: %w", err)
162		}
163		return &resp, nil
164	}
165
166	return nil, fmt.Errorf("no response in SSE stream")
167}
168
169// ListTools requests the list of available tools from the server.
170func (c *Client) ListTools(ctx context.Context) ([]Tool, error) {
171	resp, err := c.Call(ctx, "tools/list", nil)
172	if err != nil {
173		return nil, err
174	}
175
176	if resp.Error != nil {
177		return nil, fmt.Errorf("mcp error %d: %s", resp.Error.Code, resp.Error.Message)
178	}
179
180	var result ListToolsResult
181	if err := json.Unmarshal(resp.Result, &result); err != nil {
182		return nil, fmt.Errorf("unmarshal tools: %w", err)
183	}
184
185	return result.Tools, nil
186}
187
188// CallTool invokes a tool on the server.
189func (c *Client) CallTool(ctx context.Context, name string, arguments interface{}) (*ToolResult, error) {
190	var argsJSON json.RawMessage
191	if arguments != nil {
192		data, err := json.Marshal(arguments)
193		if err != nil {
194			return nil, fmt.Errorf("marshal arguments: %w", err)
195		}
196		argsJSON = data
197	}
198
199	params := CallToolParams{
200		Name:      name,
201		Arguments: argsJSON,
202	}
203
204	resp, err := c.Call(ctx, "tools/call", params)
205	if err != nil {
206		return nil, err
207	}
208
209	if resp.Error != nil {
210		return &ToolResult{
211			Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Error: %s", resp.Error.Message)}},
212			IsError: true,
213		}, nil
214	}
215
216	var result ToolResult
217	if err := json.Unmarshal(resp.Result, &result); err != nil {
218		return nil, fmt.Errorf("unmarshal result: %w", err)
219	}
220
221	return &result, nil
222}
223
224// Initialize sends the initialize request to the server and completes the handshake.
225func (c *Client) Initialize(ctx context.Context, clientInfo map[string]interface{}) (*Response, error) {
226	params := map[string]interface{}{
227		"protocolVersion": "2024-11-05",
228		"capabilities":    map[string]interface{}{},
229		"clientInfo":      clientInfo,
230	}
231
232	var resp *Response
233	var err error
234	maxRetries := 3
235	backoff := 1 * time.Second
236
237	for i := 0; i < maxRetries; i++ {
238		if i > 0 {
239			// Wait with backoff
240			select {
241			case <-ctx.Done():
242				return nil, ctx.Err()
243			case <-time.After(backoff):
244				backoff *= 2
245			}
246		}
247
248		resp, err = c.Call(ctx, "initialize", params)
249		if err == nil {
250			break
251		}
252		// Log attempt (using fmt to avoid dependency on logger)
253		fmt.Printf("MCP connection attempt %d/%d failed: %v\n", i+1, maxRetries, err)
254	}
255
256	if err != nil {
257		return nil, fmt.Errorf("initialize failed after %d attempts: %w", maxRetries, err)
258	}
259
260	if resp.Error != nil {
261		return resp, nil
262	}
263
264	// Send initialized notification to complete handshake
265	if err := c.Notify(ctx, "notifications/initialized", nil); err != nil {
266		return nil, fmt.Errorf("send initialized notification: %w", err)
267	}
268
269	return resp, nil
270}
271
272// Notify sends a notification (no response expected).
273func (c *Client) Notify(ctx context.Context, method string, params interface{}) error {
274	// Notifications have no ID
275	req := &Request{
276		JSONRPC: "2.0",
277		Method:  method,
278	}
279
280	if params != nil {
281		data, err := json.Marshal(params)
282		if err != nil {
283			return fmt.Errorf("marshal params: %w", err)
284		}
285		req.Params = data
286	}
287
288	body, err := json.Marshal(req)
289	if err != nil {
290		return fmt.Errorf("marshal request: %w", err)
291	}
292
293	httpReq, err := http.NewRequestWithContext(ctx, "POST", c.endpoint, bytes.NewReader(body))
294	if err != nil {
295		return fmt.Errorf("create http request: %w", err)
296	}
297
298	httpReq.Header.Set("Content-Type", "application/json")
299	httpReq.Header.Set("Accept", "application/json, text/event-stream")
300
301	// Include session ID if we have one
302	if c.sessionID != "" {
303		httpReq.Header.Set("Mcp-Session-Id", c.sessionID)
304	}
305
306	// Include protocol version header
307	if c.protocolVersion != "" {
308		httpReq.Header.Set("MCP-Protocol-Version", c.protocolVersion)
309	}
310
311	httpResp, err := c.httpClient.Do(httpReq)
312	if err != nil {
313		return fmt.Errorf("http request: %w", err)
314	}
315	defer httpResp.Body.Close()
316
317	// Capture session ID from response if present
318	if sessionID := httpResp.Header.Get("Mcp-Session-Id"); sessionID != "" {
319		c.sessionID = sessionID
320	}
321
322	// Notifications may return 200/202/204, we just check for success
323	if httpResp.StatusCode >= 400 {
324		respBody, _ := io.ReadAll(httpResp.Body)
325		return fmt.Errorf("http error %d: %s", httpResp.StatusCode, string(respBody))
326	}
327
328	return nil
329}
330
331// Close closes idle HTTP connections
332func (c *Client) Close() error {
333	if c.httpClient != nil {
334		c.httpClient.CloseIdleConnections()
335	}
336	return nil
337}