xonecas.io
62159
Sy

symb / files

symb / internal / mcp / client.go

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