@@ -0,0 +1,347 @@
1+package mcp
2+
3+import (
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.
19+type 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.
28+func 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.
39+func (c *Client) nextID() int64 {
40+ return c.requestID.Add(1)
41+}
42+
43+// Call makes an MCP request and returns the response.
44+func (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.
55+func (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.
129+func (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.
176+func (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.
195+func (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.
231+func (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
Cut short: this commit's diff is over 1000 lines.