Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/sse.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 "crypto/rand"
11 "fmt"
12 "io"
13 "mime"
14 "net"
15 "net/http"
16 "net/url"
17 "sync"
18
19 "github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2"
20 "github.com/modelcontextprotocol/go-sdk/internal/util"
21 "github.com/modelcontextprotocol/go-sdk/jsonrpc"
22 )
23
24 // This file implements support for SSE (HTTP with server-sent events)
25 // transport server and client.
26 // https://modelcontextprotocol.io/specification/2024-11-05/basic/transports
27 //
28 // The transport is simple, at least relative to the new streamable transport
29 // introduced in the 2025-03-26 version of the spec. In short:
30 //
31 // 1. Sessions are initiated via a hanging GET request, which streams
32 // server->client messages as SSE 'message' events.
33 // 2. The first event in the SSE stream must be an 'endpoint' event that
34 // informs the client of the session endpoint.
35 // 3. The client POSTs client->server messages to the session endpoint.
36 //
37 // Therefore, the each new GET request hands off its responsewriter to an
38 // [SSEServerTransport] type that abstracts the transport as follows:
39 // - Write writes a new event to the responseWriter, or fails if the GET has
40 // exited.
41 // - Read reads off a message queue that is pushed to via POST requests.
42 // - Close causes the hanging GET to exit.
43
44 // SSEHandler is an http.Handler that serves SSE-based MCP sessions as defined by
45 // the [2024-11-05 version] of the MCP spec.
46 //
47 // [2024-11-05 version]: https://modelcontextprotocol.io/specification/2024-11-05/basic/transports
48 type SSEHandler struct {
49 getServer func(request *http.Request) *Server
50 opts SSEOptions
51 onConnection func(*ServerSession) // for testing; must not block
52
53 mu sync.Mutex
54 sessions map[string]*SSEServerTransport
55 }
56
57 // SSEOptions specifies options for an [SSEHandler].
58 type SSEOptions struct {
59 // DisableLocalhostProtection disables automatic DNS rebinding protection.
60 // By default, requests arriving via a localhost address (127.0.0.1, [::1])
61 // that have a non-localhost Host header are rejected with 403 Forbidden.
62 // This protects against DNS rebinding attacks regardless of whether the
63 // server is listening on localhost specifically or on 0.0.0.0.
64 //
65 // Only disable this if you understand the security implications.
66 // See: https://modelcontextprotocol.io/specification/2025-11-25/basic/security_best_practices#local-mcp-server-compromise
67 DisableLocalhostProtection bool
68 }
69
70 // NewSSEHandler returns a new [SSEHandler] that creates and manages MCP
71 // sessions created via incoming HTTP requests.
72 //
73 // Sessions are created when the client issues a GET request to the server,
74 // which must accept text/event-stream responses (server-sent events).
75 // For each such request, a new [SSEServerTransport] is created with a distinct
76 // messages endpoint, and connected to the server returned by getServer.
77 // The SSEHandler also handles requests to the message endpoints, by
78 // delegating them to the relevant server transport.
79 //
80 // The getServer function may return a distinct [Server] for each new
81 // request, or reuse an existing server. If it returns nil, the handler
82 // will return a 400 Bad Request.
83 func NewSSEHandler(getServer func(request *http.Request) *Server, opts *SSEOptions) *SSEHandler {
84 s := &SSEHandler{
85 getServer: getServer,
86 sessions: make(map[string]*SSEServerTransport),
87 }
88
89 if opts != nil {
90 s.opts = *opts
91 }
92
93 return s
94 }
95
96 // A SSEServerTransport is a logical SSE session created through a hanging GET
97 // request.
98 //
99 // Use [SSEServerTransport.Connect] to initiate the flow of messages.
100 //
101 // When connected, it returns the following [Connection] implementation:
102 // - Writes are SSE 'message' events to the GET response.
103 // - Reads are received from POSTs to the session endpoint, via
104 // [SSEServerTransport.ServeHTTP].
105 // - Close terminates the hanging GET.
106 //
107 // The transport is itself an [http.Handler]. It is the caller's responsibility
108 // to ensure that the resulting transport serves HTTP requests on the given
109 // session endpoint.
110 //
111 // Each SSEServerTransport may be connected (via [Server.Connect]) at most
112 // once, since [SSEServerTransport.ServeHTTP] serves messages to the connected
113 // session.
114 //
115 // Most callers should instead use an [SSEHandler], which transparently handles
116 // the delegation to SSEServerTransports.
117 type SSEServerTransport struct {
118 // Endpoint is the endpoint for this session, where the client can POST
119 // messages.
120 Endpoint string
121
122 // Response is the hanging response body to the incoming GET request.
123 Response http.ResponseWriter
124
125 // incoming is the queue of incoming messages.
126 // It is never closed, and by convention, incoming is non-nil if and only if
127 // the transport is connected.
128 incoming chan jsonrpc.Message
129
130 // We must guard both pushes to the incoming queue and writes to the response
131 // writer, because incoming POST requests are arbitrarily concurrent and we
132 // need to ensure we don't write push to the queue, or write to the
133 // ResponseWriter, after the session GET request exits.
134 mu sync.Mutex // also guards writes to Response
135 closed bool // set when the stream is closed
136 done chan struct{} // closed when the connection is closed
137 }
138
139 // ServeHTTP handles POST requests to the transport endpoint.
140 func (t *SSEServerTransport) ServeHTTP(w http.ResponseWriter, req *http.Request) {
141 if t.incoming == nil {
142 http.Error(w, "session not connected", http.StatusInternalServerError)
143 return
144 }
145
146 // Read and parse the message.
147 data, err := io.ReadAll(req.Body)
148 if err != nil {
149 http.Error(w, "failed to read body", http.StatusBadRequest)
150 return
151 }
152 // Optionally, we could just push the data onto a channel, and let the
153 // message fail to parse when it is read. This failure seems a bit more
154 // useful
155 msg, err := jsonrpc2.DecodeMessage(data)
156 if err != nil {
157 http.Error(w, "failed to parse body", http.StatusBadRequest)
158 return
159 }
160 if req, ok := msg.(*jsonrpc.Request); ok {
161 if _, err := checkRequest(req, serverMethodInfos); err != nil {
162 http.Error(w, err.Error(), http.StatusBadRequest)
163 return
164 }
165 }
166 select {
167 case t.incoming <- msg:
168 w.WriteHeader(http.StatusAccepted)
169 case <-t.done:
170 http.Error(w, "session closed", http.StatusBadRequest)
171 }
172 }
173
174 // Connect sends the 'endpoint' event to the client.
175 // See [SSEServerTransport] for more details on the [Connection] implementation.
176 func (t *SSEServerTransport) Connect(context.Context) (Connection, error) {
177 if t.incoming != nil {
178 return nil, fmt.Errorf("already connected")
179 }
180 t.incoming = make(chan jsonrpc.Message, 100)
181 t.done = make(chan struct{})
182 _, err := writeEvent(t.Response, Event{
183 Name: "endpoint",
184 Data: []byte(t.Endpoint),
185 })
186 if err != nil {
187 return nil, err
188 }
189 return &sseServerConn{t: t}, nil
190 }
191
192 func (h *SSEHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
193 // DNS rebinding protection: auto-enabled for localhost servers.
194 // See: https://modelcontextprotocol.io/specification/2025-11-25/basic/security_best_practices#local-mcp-server-compromise
195 if !h.opts.DisableLocalhostProtection && disablelocalhostprotection != "1" {
196 if localAddr, ok := req.Context().Value(http.LocalAddrContextKey).(net.Addr); ok && localAddr != nil {
197 if util.IsLoopback(localAddr.String()) && !util.IsLoopback(req.Host) {
198 http.Error(w, fmt.Sprintf("Forbidden: invalid Host header %q", req.Host), http.StatusForbidden)
199 return
200 }
201 }
202 }
203
204 // Validate 'Content-Type' header.
205 if disablecontenttypecheck != "1" && req.Method == http.MethodPost {
206 mediaType, _, err := mime.ParseMediaType(req.Header.Get("Content-Type"))
207 if err != nil || mediaType != "application/json" {
208 http.Error(w, "Content-Type must be 'application/json'", http.StatusUnsupportedMediaType)
209 return
210 }
211 }
212
213 sessionID := req.URL.Query().Get("sessionid")
214
215 // For POST requests, the message body is a message to send to a session.
216 if req.Method == http.MethodPost {
217 // Look up the session.
218 if sessionID == "" {
219 http.Error(w, "sessionid must be provided", http.StatusBadRequest)
220 return
221 }
222 h.mu.Lock()
223 session := h.sessions[sessionID]
224 h.mu.Unlock()
225 if session == nil {
226 http.Error(w, "session not found", http.StatusNotFound)
227 return
228 }
229
230 session.ServeHTTP(w, req)
231 return
232 }
233
234 if req.Method != http.MethodGet {
235 w.Header().Set("Allow", "GET, POST")
236 http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
237 return
238 }
239
240 // GET requests create a new session, and serve messages over SSE.
241
242 // TODO: it's not entirely documented whether we should check Accept here.
243 // Let's again be lax and assume the client will accept SSE.
244
245 w.Header().Set("Content-Type", "text/event-stream")
246 w.Header().Set("Cache-Control", "no-cache")
247 w.Header().Set("Connection", "keep-alive")
248
249 sessionID = rand.Text()
250 endpoint, err := req.URL.Parse("?sessionid=" + sessionID)
251 if err != nil {
252 http.Error(w, "internal error: failed to create endpoint", http.StatusInternalServerError)
253 return
254 }
255
256 transport := &SSEServerTransport{Endpoint: endpoint.RequestURI(), Response: w}
257
258 // The session is terminated when the request exits.
259 h.mu.Lock()
260 h.sessions[sessionID] = transport
261 h.mu.Unlock()
262 defer func() {
263 h.mu.Lock()
264 delete(h.sessions, sessionID)
265 h.mu.Unlock()
266 }()
267
268 server := h.getServer(req)
269 if server == nil {
270 // The getServer argument to NewSSEHandler returned nil.
271 http.Error(w, "no server available", http.StatusBadRequest)
272 return
273 }
274 ss, err := server.Connect(req.Context(), transport, nil)
275 if err != nil {
276 http.Error(w, "connection failed", http.StatusInternalServerError)
277 return
278 }
279 if h.onConnection != nil {
280 h.onConnection(ss)
281 }
282 defer ss.Close() // close the transport when the GET exits
283
284 select {
285 case <-req.Context().Done():
286 case <-transport.done:
287 }
288 }
289
290 // sseServerConn implements the [Connection] interface for a single [SSEServerTransport].
291 // It hides the Connection interface from the SSEServerTransport API.
292 type sseServerConn struct {
293 t *SSEServerTransport
294 }
295
296 // TODO(jba): get the session ID. (Not urgent because SSE transports have been removed from the spec.)
297 func (s *sseServerConn) SessionID() string { return "" }
298
299 // Read implements jsonrpc2.Reader.
300 func (s *sseServerConn) Read(ctx context.Context) (jsonrpc.Message, error) {
301 select {
302 case <-ctx.Done():
303 return nil, ctx.Err()
304 case msg := <-s.t.incoming:
305 return msg, nil
306 case <-s.t.done:
307 return nil, io.EOF
308 }
309 }
310
311 // Write implements jsonrpc2.Writer.
312 func (s *sseServerConn) Write(ctx context.Context, msg jsonrpc.Message) error {
313 if ctx.Err() != nil {
314 return ctx.Err()
315 }
316
317 data, err := jsonrpc2.EncodeMessage(msg)
318 if err != nil {
319 return err
320 }
321
322 s.t.mu.Lock()
323 defer s.t.mu.Unlock()
324
325 // Note that it is invalid to write to a ResponseWriter after ServeHTTP has
326 // exited, and so we must lock around this write and check isDone, which is
327 // set before the hanging GET exits.
328 if s.t.closed {
329 return io.EOF
330 }
331
332 _, err = writeEvent(s.t.Response, Event{Name: "message", Data: data})
333 return err
334 }
335
336 // Close implements io.Closer, and closes the session.
337 //
338 // It must be safe to call Close more than once, as the close may
339 // asynchronously be initiated by either the server closing its connection, or
340 // by the hanging GET exiting.
341 func (s *sseServerConn) Close() error {
342 s.t.mu.Lock()
343 defer s.t.mu.Unlock()
344 if !s.t.closed {
345 s.t.closed = true
346 close(s.t.done)
347 }
348 return nil
349 }
350
351 // An SSEClientTransport is a [Transport] that can communicate with an MCP
352 // endpoint serving the SSE transport defined by the 2024-11-05 version of the
353 // spec.
354 //
355 // https://modelcontextprotocol.io/specification/2024-11-05/basic/transports
356 type SSEClientTransport struct {
357 // Endpoint is the SSE endpoint to connect to.
358 Endpoint string
359
360 // HTTPClient is the client to use for making HTTP requests. If nil,
361 // http.DefaultClient is used.
362 HTTPClient *http.Client
363 }
364
365 // Connect connects through the client endpoint.
366 func (c *SSEClientTransport) Connect(ctx context.Context) (Connection, error) {
367 parsedURL, err := url.Parse(c.Endpoint)
368 if err != nil {
369 return nil, fmt.Errorf("invalid endpoint: %v", err)
370 }
371 req, err := http.NewRequestWithContext(ctx, "GET", c.Endpoint, nil)
372 if err != nil {
373 return nil, err
374 }
375 httpClient := c.HTTPClient
376 if httpClient == nil {
377 httpClient = http.DefaultClient
378 }
379 req.Header.Set("Accept", "text/event-stream")
380 resp, err := httpClient.Do(req)
381 if err != nil {
382 return nil, err
383 }
384
385 // Check HTTP status code before attempting to parse SSE events.
386 // This ensures proper error reporting for authentication failures (401),
387 // authorization failures (403), and other HTTP errors.
388 if resp.StatusCode < 200 || resp.StatusCode >= 300 {
389 resp.Body.Close()
390 return nil, fmt.Errorf("failed to connect: %s", http.StatusText(resp.StatusCode))
391 }
392
393 msgEndpoint, err := func() (*url.URL, error) {
394 var evt Event
395 for evt, err = range scanEvents(resp.Body) {
396 break
397 }
398 if err != nil {
399 return nil, err
400 }
401 if evt.Name != "endpoint" {
402 return nil, fmt.Errorf("first event is %q, want %q", evt.Name, "endpoint")
403 }
404 raw := string(evt.Data)
405 return parsedURL.Parse(raw)
406 }()
407 if err != nil {
408 resp.Body.Close()
409 return nil, fmt.Errorf("missing endpoint: %v", err)
410 }
411
412 // From here on, the stream takes ownership of resp.Body.
413 s := &sseClientConn{
414 client: httpClient,
415 msgEndpoint: msgEndpoint,
416 incoming: make(chan []byte, 100),
417 body: resp.Body,
418 done: make(chan struct{}),
419 }
420
421 go func() {
422 defer s.Close() // close the transport when the GET exits
423
424 for evt, err := range scanEvents(resp.Body) {
425 if err != nil {
426 return
427 }
428 select {
429 case s.incoming <- evt.Data:
430 case <-s.done:
431 return
432 }
433 }
434 }()
435
436 return s, nil
437 }
438
439 // An sseClientConn is a logical jsonrpc2 connection that implements the client
440 // half of the SSE protocol:
441 // - Writes are POSTS to the session endpoint.
442 // - Reads are SSE 'message' events, and pushes them onto a buffered channel.
443 // - Close terminates the GET request.
444 type sseClientConn struct {
445 client *http.Client // HTTP client to use for requests
446 msgEndpoint *url.URL // session endpoint for POSTs
447 incoming chan []byte // queue of incoming messages
448
449 mu sync.Mutex
450 body io.ReadCloser // body of the hanging GET
451 closed bool // set when the stream is closed
452 done chan struct{} // closed when the stream is closed
453 }
454
455 // TODO(jba): get the session ID. (Not urgent because SSE transports have been removed from the spec.)
456 func (c *sseClientConn) SessionID() string { return "" }
457
458 func (c *sseClientConn) isDone() bool {
459 c.mu.Lock()
460 defer c.mu.Unlock()
461 return c.closed
462 }
463
464 func (c *sseClientConn) Read(ctx context.Context) (jsonrpc.Message, error) {
465 select {
466 case <-ctx.Done():
467 return nil, ctx.Err()
468
469 case <-c.done:
470 return nil, io.EOF
471
472 case data := <-c.incoming:
473 // TODO(rfindley): do we really need to check this? We receive from c.done above.
474 if c.isDone() {
475 return nil, io.EOF
476 }
477 msg, err := jsonrpc2.DecodeMessage(data)
478 if err != nil {
479 return nil, err
480 }
481 return msg, nil
482 }
483 }
484
485 func (c *sseClientConn) Write(ctx context.Context, msg jsonrpc.Message) error {
486 data, err := jsonrpc2.EncodeMessage(msg)
487 if err != nil {
488 return err
489 }
490 if c.isDone() {
491 return io.EOF
492 }
493 req, err := http.NewRequestWithContext(ctx, "POST", c.msgEndpoint.String(), bytes.NewReader(data))
494 if err != nil {
495 return err
496 }
497 req.Header.Set("Content-Type", "application/json")
498 resp, err := c.client.Do(req)
499 if err != nil {
500 return err
501 }
502 defer resp.Body.Close()
503 if resp.StatusCode < 200 || resp.StatusCode >= 300 {
504 return fmt.Errorf("failed to write: %s", resp.Status)
505 }
506 return nil
507 }
508
509 func (c *sseClientConn) Close() error {
510 c.mu.Lock()
511 defer c.mu.Unlock()
512 if !c.closed {
513 c.closed = true
514 _ = c.body.Close()
515 close(c.done)
516 }
517 return nil
518 }