Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/transport.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 "context"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "io"
13 "log/slog"
14 "net"
15 "os"
16 "sync"
17 "time"
18
19 internaljson "github.com/modelcontextprotocol/go-sdk/internal/json"
20 "github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2"
21 "github.com/modelcontextprotocol/go-sdk/jsonrpc"
22 )
23
24 // notifyCancellationTimeout bounds the cancellation notification we send to
25 // the peer when the caller's context is cancelled. The notification is
26 // best-effort: a degraded connection (e.g. an OAuth flow that has been
27 // abandoned) must not be able to block the caller's return path or
28 // re-trigger expensive recovery on its behalf. See issue #882.
29 const notifyCancellationTimeout = 5 * time.Second
30
31 // ErrConnectionClosed is returned when sending a message to a connection that
32 // is closed or in the process of closing.
33 var ErrConnectionClosed = errors.New("connection closed")
34
35 // ErrSessionMissing is returned when the session is known to not be present on
36 // the server.
37 var ErrSessionMissing = errors.New("session not found")
38
39 // A Transport is used to create a bidirectional connection between MCP client
40 // and server.
41 //
42 // Transports should be used for at most one call to [Server.Connect] or
43 // [Client.Connect].
44 type Transport interface {
45 // Connect returns the logical JSON-RPC connection..
46 //
47 // It is called exactly once by [Server.Connect] or [Client.Connect].
48 Connect(ctx context.Context) (Connection, error)
49 }
50
51 // A Connection is a logical bidirectional JSON-RPC connection.
52 type Connection interface {
53 // Read reads the next message to process off the connection.
54 //
55 // Connections must allow Read to be called concurrently with Close. In
56 // particular, calling Close should unblock a Read waiting for input.
57 Read(context.Context) (jsonrpc.Message, error)
58
59 // Write writes a new message to the connection.
60 //
61 // Write may be called concurrently, as calls or responses may occur
62 // concurrently in user code.
63 Write(context.Context, jsonrpc.Message) error
64
65 // Close closes the connection. It is implicitly called whenever a Read or
66 // Write fails.
67 //
68 // Close may be called multiple times, potentially concurrently.
69 Close() error
70
71 // TODO(#148): remove SessionID from this interface.
72 SessionID() string
73 }
74
75 // A ClientConnection is a [Connection] that is specific to the MCP client.
76 //
77 // If client connections implement this interface, they may receive information
78 // about changes to the client session.
79 //
80 // TODO: should this interface be exported?
81 type clientConnection interface {
82 Connection
83
84 // sessionUpdated is called whenever the client session state changes.
85 sessionUpdated(clientSessionState)
86 }
87
88 // A serverConnection is a Connection that is specific to the MCP server.
89 //
90 // If server connections implement this interface, they receive information
91 // about changes to the server session.
92 //
93 // TODO: should this interface be exported?
94 type serverConnection interface {
95 Connection
96 sessionUpdated(ServerSessionState)
97 }
98
99 // A StdioTransport is a [Transport] that communicates over stdin/stdout using
100 // newline-delimited JSON.
101 type StdioTransport struct{}
102
103 // Connect implements the [Transport] interface.
104 func (*StdioTransport) Connect(context.Context) (Connection, error) {
105 return newIOConn(rwc{os.Stdin, nopCloserWriter{os.Stdout}}), nil
106 }
107
108 // nopCloserWriter is an io.WriteCloser with a trivial Close method.
109 type nopCloserWriter struct {
110 io.Writer
111 }
112
113 func (nopCloserWriter) Close() error { return nil }
114
115 // An IOTransport is a [Transport] that communicates over separate
116 // io.ReadCloser and io.WriteCloser using newline-delimited JSON.
117 type IOTransport struct {
118 Reader io.ReadCloser
119 Writer io.WriteCloser
120 }
121
122 // Connect implements the [Transport] interface.
123 func (t *IOTransport) Connect(context.Context) (Connection, error) {
124 return newIOConn(rwc{t.Reader, t.Writer}), nil
125 }
126
127 // An InMemoryTransport is a [Transport] that communicates over an in-memory
128 // network connection, using newline-delimited JSON.
129 //
130 // InMemoryTransports should be constructed using [NewInMemoryTransports],
131 // which returns two transports connected to each other.
132 type InMemoryTransport struct {
133 rwc io.ReadWriteCloser
134 }
135
136 // Connect implements the [Transport] interface.
137 func (t *InMemoryTransport) Connect(context.Context) (Connection, error) {
138 return newIOConn(t.rwc), nil
139 }
140
141 // NewInMemoryTransports returns two [InMemoryTransport] objects that connect
142 // to each other.
143 //
144 // The resulting transports are symmetrical: use either to connect to a server,
145 // and then the other to connect to a client. Servers must be connected before
146 // clients, as the client initializes the MCP session during connection.
147 func NewInMemoryTransports() (*InMemoryTransport, *InMemoryTransport) {
148 c1, c2 := net.Pipe()
149 return &InMemoryTransport{c1}, &InMemoryTransport{c2}
150 }
151
152 type binder[T handler, State any] interface {
153 // TODO(rfindley): the bind API has gotten too complicated. Simplify.
154 bind(Connection, *jsonrpc2.Connection, State, func()) T
155 disconnect(T)
156 }
157
158 type handler interface {
159 handle(ctx context.Context, req *jsonrpc.Request) (any, error)
160 }
161
162 // connect wires a transport to a binder. logger must be non-nil; it receives
163 // jsonrpc2 internal errors that would otherwise be dropped (see #218).
164 func connect[H handler, State any](ctx context.Context, t Transport, b binder[H, State], s State, onClose func(), logger *slog.Logger) (H, error) {
165 var zero H
166 mcpConn, err := t.Connect(ctx)
167 if err != nil {
168 return zero, err
169 }
170 // If logging is configured, write message logs.
171 reader, writer := jsonrpc2.Reader(mcpConn), jsonrpc2.Writer(mcpConn)
172 var (
173 h H
174 preempter canceller
175 )
176 bind := func(conn *jsonrpc2.Connection) jsonrpc2.Handler {
177 h = b.bind(mcpConn, conn, s, onClose)
178 preempter.conn = conn
179 return jsonrpc2.HandlerFunc(h.handle)
180 }
181 _ = jsonrpc2.NewConnection(ctx, jsonrpc2.ConnectionConfig{
182 Reader: reader,
183 Writer: writer,
184 Closer: mcpConn,
185 Bind: bind,
186 Preempter: &preempter,
187 OnDone: func() {
188 b.disconnect(h)
189 },
190 OnInternalError: func(err error) {
191 logger.Error("jsonrpc2 internal error", "error", err)
192 },
193 })
194 assert(preempter.conn != nil, "unbound preempter")
195 return h, nil
196 }
197
198 // A canceller is a jsonrpc2.Preempter that cancels in-flight requests on MCP
199 // cancelled notifications.
200 type canceller struct {
201 conn *jsonrpc2.Connection
202 }
203
204 // Preempt implements [jsonrpc2.Preempter].
205 func (c *canceller) Preempt(ctx context.Context, req *jsonrpc.Request) (result any, err error) {
206 if req.Method == notificationCancelled {
207 var params CancelledParams
208 if err := internaljson.Unmarshal(req.Params, &params); err != nil {
209 return nil, err
210 }
211 id, err := jsonrpc2.MakeID(params.RequestID)
212 if err != nil {
213 return nil, err
214 }
215 go c.conn.Cancel(id)
216 }
217 return nil, jsonrpc2.ErrNotHandled
218 }
219
220 // call executes and awaits a jsonrpc2 call on the given connection,
221 // translating errors into the mcp domain.
222 func call(ctx context.Context, conn *jsonrpc2.Connection, method string, params Params, result Result) error {
223 // The "%w"s in this function expose jsonrpc.Error as part of the API.
224 call := conn.Call(ctx, method, params)
225 err := call.Await(ctx, result)
226 switch {
227 case errors.Is(err, jsonrpc2.ErrClientClosing), errors.Is(err, jsonrpc2.ErrServerClosing):
228 return fmt.Errorf("%w: calling %q: %v", ErrConnectionClosed, method, err)
229 case ctx.Err() != nil:
230 notifyCtx, cancelNotify := context.WithTimeout(context.WithoutCancel(ctx), notifyCancellationTimeout)
231 defer cancelNotify()
232 err := conn.Notify(notifyCtx, notificationCancelled, &CancelledParams{
233 Reason: ctx.Err().Error(),
234 RequestID: call.ID().Raw(),
235 })
236 // By default, the jsonrpc2 library waits for graceful shutdown when the
237 // connection is closed, meaning it expects all outgoing and incoming
238 // requests to complete. However, for MCP this expectation is unrealistic,
239 // and can lead to hanging shutdown. For example, if a streamable client is
240 // killed, the server will not be able to detect this event, except via
241 // keepalive pings (if they are configured), and so outgoing calls may hang
242 // indefinitely.
243 //
244 // Therefore, we choose to eagerly retire calls, removing them from the
245 // outgoingCalls map, when the caller context is cancelled: if the caller
246 // will never receive the response, there's no need to track it.
247 conn.Retire(call, ctx.Err())
248 return errors.Join(ctx.Err(), err)
249 case err != nil:
250 return fmt.Errorf("calling %q: %w", method, err)
251 }
252 return nil
253 }
254
255 // A LoggingTransport is a [Transport] that delegates to another transport,
256 // writing RPC logs to an io.Writer.
257 type LoggingTransport struct {
258 Transport Transport
259 Writer io.Writer
260 }
261
262 // Connect connects the underlying transport, returning a [Connection] that writes
263 // logs to the configured destination.
264 func (t *LoggingTransport) Connect(ctx context.Context) (Connection, error) {
265 delegate, err := t.Transport.Connect(ctx)
266 if err != nil {
267 return nil, err
268 }
269 return &loggingConn{delegate: delegate, w: t.Writer}, nil
270 }
271
272 type loggingConn struct {
273 delegate Connection
274
275 mu sync.Mutex
276 w io.Writer
277 }
278
279 func (c *loggingConn) SessionID() string { return c.delegate.SessionID() }
280
281 // Read is a stream middleware that logs incoming messages.
282 func (s *loggingConn) Read(ctx context.Context) (jsonrpc.Message, error) {
283 msg, err := s.delegate.Read(ctx)
284
285 if err != nil {
286 s.mu.Lock()
287 fmt.Fprintf(s.w, "read error: %v\n", err)
288 s.mu.Unlock()
289 } else {
290 data, err := jsonrpc2.EncodeMessage(msg)
291 s.mu.Lock()
292 if err != nil {
293 fmt.Fprintf(s.w, "LoggingTransport: failed to marshal: %v", err)
294 }
295 fmt.Fprintf(s.w, "read: %s\n", string(data))
296 s.mu.Unlock()
297 }
298
299 return msg, err
300 }
301
302 // Write is a stream middleware that logs outgoing messages.
303 func (s *loggingConn) Write(ctx context.Context, msg jsonrpc.Message) error {
304 err := s.delegate.Write(ctx, msg)
305 if err != nil {
306 s.mu.Lock()
307 fmt.Fprintf(s.w, "write error: %v\n", err)
308 s.mu.Unlock()
309 } else {
310 data, err := jsonrpc2.EncodeMessage(msg)
311 s.mu.Lock()
312 if err != nil {
313 fmt.Fprintf(s.w, "LoggingTransport: failed to marshal: %v", err)
314 }
315 fmt.Fprintf(s.w, "write: %s\n", string(data))
316 s.mu.Unlock()
317 }
318 return err
319 }
320
321 func (s *loggingConn) Close() error {
322 return s.delegate.Close()
323 }
324
325 // A rwc binds an io.ReadCloser and io.WriteCloser together to create an
326 // io.ReadWriteCloser.
327 type rwc struct {
328 rc io.ReadCloser
329 wc io.WriteCloser
330 }
331
332 func (r rwc) Read(p []byte) (n int, err error) {
333 return r.rc.Read(p)
334 }
335
336 func (r rwc) Write(p []byte) (n int, err error) {
337 return r.wc.Write(p)
338 }
339
340 func (r rwc) Close() error {
341 rcErr := r.rc.Close()
342
343 var wcErr error
344 if r.wc != nil { // we only allow a nil writer in unit tests
345 wcErr = r.wc.Close()
346 }
347
348 return errors.Join(rcErr, wcErr)
349 }
350
351 // An ioConn is a transport that delimits messages with newlines across
352 // a bidirectional stream, and supports jsonrpc.2 message batching.
353 //
354 // See https://github.com/ndjson/ndjson-spec for discussion of newline
355 // delimited JSON.
356 //
357 // See [msgBatch] for more discussion of message batching.
358 type ioConn struct {
359 // protocolVersion is the negotiated version of the protocol,
360 // set during session initialization.
361 // Since writes may be concurrent to reads, we need to guard this with a mutex.
362 sessionMu sync.Mutex
363 protocolVersion string
364
365 writeMu sync.Mutex // guards Write, which must be concurrency safe.
366 rwc io.ReadWriteCloser // the underlying stream
367
368 // incoming receives messages from the read loop started in [newIOConn].
369 incoming <-chan msgOrErr
370
371 // If outgoiBatch has a positive capacity, it will be used to batch requests
372 // and notifications before sending.
373 outgoingBatch []jsonrpc.Message
374
375 // Unread messages in the last batch. Since reads are serialized, there is no
376 // need to guard here.
377 queue []jsonrpc.Message
378
379 // batches correlate incoming requests to the batch in which they arrived.
380 // Since writes may be concurrent to reads, we need to guard this with a mutex.
381 batchMu sync.Mutex
382 batches map[jsonrpc2.ID]*msgBatch // lazily allocated
383
384 closeOnce sync.Once
385 closed chan struct{}
386 closeErr error
387 }
388
389 type msgOrErr struct {
390 msg json.RawMessage
391 err error
392 }
393
394 func newIOConn(rwc io.ReadWriteCloser) *ioConn {
395 var (
396 incoming = make(chan msgOrErr)
397 closed = make(chan struct{})
398 )
399 // Start a goroutine for reads, so that we can select on the incoming channel
400 // in [ioConn.Read] and unblock the read as soon as Close is called (see #224).
401 //
402 // This leaks a goroutine if rwc.Read does not unblock after it is closed,
403 // but that is unavoidable since AFAIK there is no (easy and portable) way to
404 // guarantee that reads of stdin are unblocked when closed.
405 go func() {
406 dec := json.NewDecoder(rwc)
407 for {
408 var raw json.RawMessage
409 err := dec.Decode(&raw)
410 // If decoding was successful, check for trailing data at the end of the stream.
411 if err == nil {
412 // Read the next byte to check if there is trailing data.
413 var tr [1]byte
414 if n, readErr := dec.Buffered().Read(tr[:]); n > 0 {
415 // If read byte is not a newline, it is an error.
416 // Support both Unix (\n) and Windows (\r\n) line endings.
417 if tr[0] != '\n' && tr[0] != '\r' {
418 err = fmt.Errorf("invalid trailing data at the end of stream")
419 }
420 } else if readErr != nil && readErr != io.EOF {
421 err = readErr
422 }
423 }
424 select {
425 case incoming <- msgOrErr{msg: raw, err: err}:
426 case <-closed:
427 return
428 }
429 if err != nil {
430 return
431 }
432 }
433 }()
434 return &ioConn{
435 rwc: rwc,
436 incoming: incoming,
437 closed: closed,
438 }
439 }
440
441 func (c *ioConn) SessionID() string { return "" }
442
443 func (c *ioConn) sessionUpdated(state ServerSessionState) {
444 protocolVersion := ""
445 if state.InitializeParams != nil {
446 protocolVersion = state.InitializeParams.ProtocolVersion
447 }
448 if protocolVersion == "" {
449 // 2025-03-26 is used, because it's the last spec version
450 // where specifying the protocol version in the HTTP header
451 // was not required.
452 protocolVersion = protocolVersion20250326
453 }
454 protocolVersion = negotiatedVersion(protocolVersion)
455 c.sessionMu.Lock()
456 c.protocolVersion = protocolVersion
457 c.sessionMu.Unlock()
458 }
459
460 // addBatch records a msgBatch for an incoming batch payload.
461 // It returns an error if batch is malformed, containing previously seen IDs.
462 //
463 // See [msgBatch] for more.
464 func (t *ioConn) addBatch(batch *msgBatch) error {
465 t.batchMu.Lock()
466 defer t.batchMu.Unlock()
467 for id := range batch.unresolved {
468 if _, ok := t.batches[id]; ok {
469 return fmt.Errorf("%w: batch contains previously seen request %v", jsonrpc2.ErrInvalidRequest, id.Raw())
470 }
471 }
472 for id := range batch.unresolved {
473 if t.batches == nil {
474 t.batches = make(map[jsonrpc2.ID]*msgBatch)
475 }
476 t.batches[id] = batch
477 }
478 return nil
479 }
480
481 // updateBatch records a response in the message batch tracking the
482 // corresponding incoming call, if any.
483 //
484 // The second result reports whether resp was part of a batch. If this is true,
485 // the first result is nil if the batch is still incomplete, or the full set of
486 // batch responses if resp completed the batch.
487 func (t *ioConn) updateBatch(resp *jsonrpc.Response) ([]*jsonrpc.Response, bool) {
488 t.batchMu.Lock()
489 defer t.batchMu.Unlock()
490
491 if batch, ok := t.batches[resp.ID]; ok {
492 idx, ok := batch.unresolved[resp.ID]
493 if !ok {
494 panic("internal error: inconsistent batches")
495 }
496 batch.responses[idx] = resp
497 delete(batch.unresolved, resp.ID)
498 delete(t.batches, resp.ID)
499 if len(batch.unresolved) == 0 {
500 return batch.responses, true
501 }
502 return nil, true
503 }
504 return nil, false
505 }
506
507 // A msgBatch records information about an incoming batch of jsonrpc.2 calls.
508 //
509 // The jsonrpc.2 spec (https://www.jsonrpc.org/specification#batch) says:
510 //
511 // "The Server should respond with an Array containing the corresponding
512 // Response objects, after all of the batch Request objects have been
513 // processed. A Response object SHOULD exist for each Request object, except
514 // that there SHOULD NOT be any Response objects for notifications. The Server
515 // MAY process a batch rpc call as a set of concurrent tasks, processing them
516 // in any order and with any width of parallelism."
517 //
518 // Therefore, a msgBatch keeps track of outstanding calls and their responses.
519 // When there are no unresolved calls, the response payload is sent.
520 type msgBatch struct {
521 unresolved map[jsonrpc2.ID]int
522 responses []*jsonrpc.Response
523 }
524
525 func (t *ioConn) Read(ctx context.Context) (jsonrpc.Message, error) {
526 // As a matter of principle, enforce that reads on a closed context return an
527 // error.
528 select {
529 case <-ctx.Done():
530 return nil, ctx.Err()
531 default:
532 }
533 if len(t.queue) > 0 {
534 next := t.queue[0]
535 t.queue = t.queue[1:]
536 return next, nil
537 }
538
539 var raw json.RawMessage
540 select {
541 case <-ctx.Done():
542 return nil, ctx.Err()
543
544 case v := <-t.incoming:
545 if v.err != nil {
546 return nil, v.err
547 }
548 raw = v.msg
549
550 case <-t.closed:
551 return nil, io.EOF
552 }
553
554 msgs, batch, err := readBatch(raw)
555 if err != nil {
556 return nil, err
557 }
558 var protocolVersion string
559 t.sessionMu.Lock()
560 protocolVersion = t.protocolVersion
561 t.sessionMu.Unlock()
562 if batch && protocolVersion >= protocolVersion20250618 {
563 return nil, fmt.Errorf("JSON-RPC batching is not supported in %s and later (request version: %s)", protocolVersion20250618, protocolVersion)
564 }
565
566 t.queue = msgs[1:]
567
568 if batch {
569 var respBatch *msgBatch // track incoming requests in the batch
570 for _, msg := range msgs {
571 if req, ok := msg.(*jsonrpc.Request); ok {
572 if respBatch == nil {
573 respBatch = &msgBatch{
574 unresolved: make(map[jsonrpc2.ID]int),
575 }
576 }
577 if _, ok := respBatch.unresolved[req.ID]; ok {
578 return nil, fmt.Errorf("duplicate message ID %q", req.ID)
579 }
580 respBatch.unresolved[req.ID] = len(respBatch.responses)
581 respBatch.responses = append(respBatch.responses, nil)
582 }
583 }
584 if respBatch != nil {
585 // The batch contains one or more incoming requests to track.
586 if err := t.addBatch(respBatch); err != nil {
587 return nil, err
588 }
589 }
590 }
591 return msgs[0], err
592 }
593
594 // readBatch reads batch data, which may be either a single JSON-RPC message,
595 // or an array of JSON-RPC messages.
596 func readBatch(data []byte) (msgs []jsonrpc.Message, isBatch bool, _ error) {
597 // Try to read an array of messages first.
598 var rawBatch []json.RawMessage
599 if err := internaljson.Unmarshal(data, &rawBatch); err == nil {
600 if len(rawBatch) == 0 {
601 return nil, true, fmt.Errorf("empty batch")
602 }
603 for _, raw := range rawBatch {
604 msg, err := jsonrpc2.DecodeMessage(raw)
605 if err != nil {
606 return nil, true, err
607 }
608 msgs = append(msgs, msg)
609 }
610 return msgs, true, nil
611 }
612 // Try again with a single message.
613 msg, err := jsonrpc2.DecodeMessage(data)
614 return []jsonrpc.Message{msg}, false, err
615 }
616
617 func (t *ioConn) Write(ctx context.Context, msg jsonrpc.Message) error {
618 // As in [ioConn.Read], enforce that Writes on a closed context are an error.
619 select {
620 case <-ctx.Done():
621 return ctx.Err()
622 default:
623 }
624
625 t.writeMu.Lock()
626 defer t.writeMu.Unlock()
627
628 // Batching support: if msg is a Response, it may have completed a batch, so
629 // check that first. Otherwise, it is a request or notification, and we may
630 // want to collect it into a batch before sending, if we're configured to use
631 // outgoing batches.
632 if resp, ok := msg.(*jsonrpc.Response); ok {
633 if batch, ok := t.updateBatch(resp); ok {
634 if len(batch) > 0 {
635 data, err := marshalMessages(batch)
636 if err != nil {
637 return err
638 }
639 data = append(data, '\n')
640 _, err = t.rwc.Write(data)
641 return err
642 }
643 return nil
644 }
645 } else if len(t.outgoingBatch) < cap(t.outgoingBatch) {
646 t.outgoingBatch = append(t.outgoingBatch, msg)
647 if len(t.outgoingBatch) == cap(t.outgoingBatch) {
648 data, err := marshalMessages(t.outgoingBatch)
649 t.outgoingBatch = t.outgoingBatch[:0]
650 if err != nil {
651 return err
652 }
653 data = append(data, '\n')
654 _, err = t.rwc.Write(data)
655 return err
656 }
657 return nil
658 }
659 data, err := jsonrpc2.EncodeMessage(msg)
660 if err != nil {
661 return fmt.Errorf("marshaling message: %v", err)
662 }
663 data = append(data, '\n') // newline delimited
664 _, err = t.rwc.Write(data)
665 return err
666 }
667
668 func (t *ioConn) Close() error {
669 t.closeOnce.Do(func() {
670 t.closeErr = t.rwc.Close()
671 close(t.closed)
672 })
673 return t.closeErr
674 }
675
676 func marshalMessages[T jsonrpc.Message](msgs []T) ([]byte, error) {
677 var rawMsgs []json.RawMessage
678 for _, msg := range msgs {
679 raw, err := jsonrpc2.EncodeMessage(msg)
680 if err != nil {
681 return nil, fmt.Errorf("encoding batch message: %w", err)
682 }
683 rawMsgs = append(rawMsgs, raw)
684 }
685 return json.Marshal(rawMsgs)
686 }