Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/sse_test.go

raw symbols SCIP
1 // Copyright 2025 The Go MCP SDK Authors. All rights reserved.
2 // Use of this source code is governed by an MIT-style
3 // license that can be found in the LICENSE file.
4
5 package mcp
6
7 import (
8 "bytes"
9 "context"
10 "fmt"
11 "io"
12 "net"
13 "net/http"
14 "net/http/httptest"
15 "sync/atomic"
16 "testing"
17
18 "github.com/google/go-cmp/cmp"
19 )
20
21 func TestSSEServer(t *testing.T) {
22 for _, closeServerFirst := range []bool{false, true} {
23 t.Run(fmt.Sprintf("closeServerFirst=%t", closeServerFirst), func(t *testing.T) {
24 ctx := context.Background()
25 server := NewServer(testImpl, nil)
26 AddTool(server, &Tool{Name: "greet"}, sayHi)
27
28 sseHandler := NewSSEHandler(func(*http.Request) *Server { return server }, nil)
29
30 serverSessions := make(chan *ServerSession, 1)
31 sseHandler.onConnection = func(ss *ServerSession) {
32 select {
33 case serverSessions <- ss:
34 default:
35 }
36 }
37 httpServer := httptest.NewServer(sseHandler)
38 defer httpServer.Close()
39
40 var customClientUsed int64
41 customClient := &http.Client{
42 Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) {
43 atomic.AddInt64(&customClientUsed, 1)
44 return http.DefaultTransport.RoundTrip(req)
45 }),
46 }
47
48 clientTransport := &SSEClientTransport{
49 Endpoint: httpServer.URL,
50 HTTPClient: customClient,
51 }
52
53 c := NewClient(testImpl, nil)
54 cs, err := c.Connect(ctx, clientTransport, nil)
55 if err != nil {
56 t.Fatal(err)
57 }
58 if err := cs.Ping(ctx, nil); err != nil {
59 t.Fatal(err)
60 }
61 ss := <-serverSessions
62 gotHi, err := cs.CallTool(ctx, &CallToolParams{
63 Name: "greet",
64 Arguments: map[string]any{"Name": "user"},
65 })
66 if err != nil {
67 t.Fatal(err)
68 }
69 wantHi := &CallToolResult{
70 Content: []Content{
71 &TextContent{Text: "hi user"},
72 },
73 }
74 if diff := cmp.Diff(wantHi, gotHi, ctrCmpOpts...); diff != "" {
75 t.Errorf("tools/call 'greet' mismatch (-want +got):\n%s", diff)
76 }
77
78 // Verify that customClient was used
79 if atomic.LoadInt64(&customClientUsed) == 0 {
80 t.Error("Expected custom HTTP client to be used, but it wasn't")
81 }
82
83 t.Run("badrequests", func(t *testing.T) {
84 msgEndpoint := cs.mcpConn.(*sseClientConn).msgEndpoint.String()
85
86 // Test some invalid data, and verify that we get 400s.
87 badRequests := []struct {
88 name string
89 body string
90 responseContains string
91 }{
92 {"not a method", `{"jsonrpc":"2.0", "method":"notamethod"}`, "not handled"},
93 {"missing ID", `{"jsonrpc":"2.0", "method":"ping"}`, "missing id"},
94 }
95 for _, r := range badRequests {
96 t.Run(r.name, func(t *testing.T) {
97 resp, err := http.Post(msgEndpoint, "application/json", bytes.NewReader([]byte(r.body)))
98 if err != nil {
99 t.Fatal(err)
100 }
101 defer resp.Body.Close()
102 if got, want := resp.StatusCode, http.StatusBadRequest; got != want {
103 t.Errorf("Sending bad request %q: got status %d, want %d", r.body, got, want)
104 }
105 result, err := io.ReadAll(resp.Body)
106 if err != nil {
107 t.Fatalf("Reading response: %v", err)
108 }
109 if !bytes.Contains(result, []byte(r.responseContains)) {
110 t.Errorf("Response body does not contain %q:\n%s", r.responseContains, string(result))
111 }
112 })
113 }
114 })
115
116 // Test that closing either end of the connection terminates the other
117 // end.
118 if closeServerFirst {
119 cs.Close()
120 ss.Wait()
121 } else {
122 ss.Close()
123 cs.Wait()
124 }
125 })
126 }
127 }
128
129 // roundTripperFunc is a helper to create a custom RoundTripper
130 type roundTripperFunc func(*http.Request) (*http.Response, error)
131
132 func (f roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
133 return f(req)
134 }
135
136 func TestSSEClientTransport_HTTPErrors(t *testing.T) {
137 tests := []struct {
138 name string
139 statusCode int
140 wantErrContain string
141 }{
142 {
143 name: "401 Unauthorized",
144 statusCode: http.StatusUnauthorized,
145 wantErrContain: "Unauthorized",
146 },
147 {
148 name: "403 Forbidden",
149 statusCode: http.StatusForbidden,
150 wantErrContain: "Forbidden",
151 },
152 {
153 name: "404 Not Found",
154 statusCode: http.StatusNotFound,
155 wantErrContain: "Not Found",
156 },
157 {
158 name: "500 Internal Server Error",
159 statusCode: http.StatusInternalServerError,
160 wantErrContain: "Internal Server Error",
161 },
162 }
163
164 for _, tt := range tests {
165 t.Run(tt.name, func(t *testing.T) {
166 // Create a test server that returns the specified status code
167 httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
168 http.Error(w, http.StatusText(tt.statusCode), tt.statusCode)
169 }))
170 defer httpServer.Close()
171
172 clientTransport := &SSEClientTransport{
173 Endpoint: httpServer.URL,
174 }
175
176 c := NewClient(testImpl, nil)
177 _, err := c.Connect(context.Background(), clientTransport, nil)
178
179 if err == nil {
180 t.Fatalf("expected error, got nil")
181 }
182
183 errStr := err.Error()
184 if !bytes.Contains([]byte(errStr), []byte(tt.wantErrContain)) {
185 t.Errorf("error message %q does not contain %q", errStr, tt.wantErrContain)
186 }
187 })
188 }
189 }
190
191 // TestSSE405AllowHeader verifies RFC 9110 ยง15.5.6 compliance:
192 // 405 Method Not Allowed responses MUST include an Allow header.
193 func TestSSE405AllowHeader(t *testing.T) {
194 server := NewServer(testImpl, nil)
195
196 handler := NewSSEHandler(func(req *http.Request) *Server { return server }, nil)
197 httpServer := httptest.NewServer(handler)
198 defer httpServer.Close()
199
200 methods := []string{"PUT", "PATCH", "DELETE", "OPTIONS"}
201 for _, method := range methods {
202 t.Run(method, func(t *testing.T) {
203 req, err := http.NewRequest(method, httpServer.URL, nil)
204 if err != nil {
205 t.Fatal(err)
206 }
207
208 resp, err := http.DefaultClient.Do(req)
209 if err != nil {
210 t.Fatal(err)
211 }
212 defer resp.Body.Close()
213
214 if got, want := resp.StatusCode, http.StatusMethodNotAllowed; got != want {
215 t.Errorf("status code: got %d, want %d", got, want)
216 }
217
218 allow := resp.Header.Get("Allow")
219 if allow != "GET, POST" {
220 t.Errorf("Allow header: got %q, want %q", allow, "GET, POST")
221 }
222 })
223 }
224 }
225
226 // TestSSELocalhostProtection verifies that DNS rebinding protection
227 // is automatically enabled for localhost servers.
228 func TestSSELocalhostProtection(t *testing.T) {
229 server := NewServer(testImpl, nil)
230
231 tests := []struct {
232 name string
233 listenAddr string
234 hostHeader string
235 disableProtection bool
236 wantStatus int
237 }{
238 {
239 name: "127.0.0.1 accepts 127.0.0.1",
240 listenAddr: "127.0.0.1:0",
241 hostHeader: "127.0.0.1:1234",
242 wantStatus: http.StatusOK,
243 },
244 {
245 name: "127.0.0.1 accepts localhost",
246 listenAddr: "127.0.0.1:0",
247 hostHeader: "localhost:1234",
248 wantStatus: http.StatusOK,
249 },
250 {
251 name: "127.0.0.1 rejects evil.com",
252 listenAddr: "127.0.0.1:0",
253 hostHeader: "evil.com",
254 wantStatus: http.StatusForbidden,
255 },
256 {
257 name: "127.0.0.1 rejects evil.com:80",
258 listenAddr: "127.0.0.1:0",
259 hostHeader: "evil.com:80",
260 wantStatus: http.StatusForbidden,
261 },
262 {
263 name: "127.0.0.1 rejects localhost.evil.com",
264 listenAddr: "127.0.0.1:0",
265 hostHeader: "localhost.evil.com",
266 wantStatus: http.StatusForbidden,
267 },
268 {
269 name: "0.0.0.0 via localhost rejects evil.com",
270 listenAddr: "0.0.0.0:0",
271 hostHeader: "evil.com",
272 wantStatus: http.StatusForbidden,
273 },
274 {
275 name: "disabled accepts evil.com",
276 listenAddr: "127.0.0.1:0",
277 hostHeader: "evil.com",
278 disableProtection: true,
279 wantStatus: http.StatusOK,
280 },
281 }
282
283 for _, tt := range tests {
284 t.Run(tt.name, func(t *testing.T) {
285 opts := &SSEOptions{
286 DisableLocalhostProtection: tt.disableProtection,
287 }
288 handler := NewSSEHandler(func(req *http.Request) *Server { return server }, opts)
289
290 listener, err := net.Listen("tcp", tt.listenAddr)
291 if err != nil {
292 t.Fatalf("Failed to listen on %s: %v", tt.listenAddr, err)
293 }
294 defer listener.Close()
295
296 srv := &http.Server{Handler: handler}
297 go srv.Serve(listener)
298 defer srv.Close()
299
300 // Use a GET request since it's the entry point for SSE sessions.
301 // For accepted requests, the response will be a hanging SSE stream,
302 // but we only need to check the initial status code.
303 req, err := http.NewRequest("GET", fmt.Sprintf("http://%s", listener.Addr().String()), nil)
304 if err != nil {
305 t.Fatal(err)
306 }
307 req.Host = tt.hostHeader
308 req.Header.Set("Accept", "text/event-stream")
309
310 resp, err := http.DefaultClient.Do(req)
311 if err != nil {
312 t.Fatal(err)
313 }
314 defer resp.Body.Close()
315
316 if got := resp.StatusCode; got != tt.wantStatus {
317 t.Errorf("Status code: got %d, want %d", got, tt.wantStatus)
318 }
319 })
320 }
321 }