Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/shared.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 // This file contains code shared between client and server, including
6 // method handler and middleware definitions.
7 //
8 // Much of this is here so that we can factor out commonalities using
9 // generics. If this becomes unwieldy, it can perhaps be simplified with
10 // reflection.
11
12 package mcp
13
14 import (
15 "context"
16 "encoding/json"
17 "errors"
18 "fmt"
19 "log/slog"
20 "net/http"
21 "reflect"
22 "slices"
23 "strings"
24 "time"
25
26 "github.com/modelcontextprotocol/go-sdk/auth"
27 internaljson "github.com/modelcontextprotocol/go-sdk/internal/json"
28 "github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2"
29 "github.com/modelcontextprotocol/go-sdk/jsonrpc"
30 )
31
32 const (
33 // latestProtocolVersion is the latest protocol version that this version of
34 // the SDK supports.
35 //
36 // It is the version that the client sends in the initialization request, and
37 // the default version used by the server.
38 latestProtocolVersion = protocolVersion20251125
39 protocolVersion20260630 = "2026-06-30"
40 protocolVersion20251125 = "2025-11-25"
41 protocolVersion20250618 = "2025-06-18"
42 protocolVersion20250326 = "2025-03-26"
43 protocolVersion20241105 = "2024-11-05"
44 )
45
46 var supportedProtocolVersions = []string{
47 protocolVersion20251125,
48 protocolVersion20250618,
49 protocolVersion20250326,
50 protocolVersion20241105,
51 }
52
53 // negotiatedVersion returns the effective protocol version to use, given a
54 // client version.
55 func negotiatedVersion(clientVersion string) string {
56 // In general, prefer to use the clientVersion, but if we don't support the
57 // client's version, use the latest version.
58 //
59 // This handles the case where a new spec version is released, and the SDK
60 // does not support it yet.
61 if !slices.Contains(supportedProtocolVersions, clientVersion) {
62 return latestProtocolVersion
63 }
64 return clientVersion
65 }
66
67 // A MethodHandler handles MCP messages.
68 // For methods, exactly one of the return values must be nil.
69 // For notifications, both must be nil.
70 type MethodHandler func(ctx context.Context, method string, req Request) (result Result, err error)
71
72 // A Session is either a [ClientSession] or a [ServerSession].
73 type Session interface {
74 // ID returns the session ID, or the empty string if there is none.
75 ID() string
76
77 sendingMethodInfos() map[string]methodInfo
78 receivingMethodInfos() map[string]methodInfo
79 sendingMethodHandler() MethodHandler
80 receivingMethodHandler() MethodHandler
81 getConn() *jsonrpc2.Connection
82 }
83
84 // Middleware is a function from [MethodHandler] to [MethodHandler].
85 type Middleware func(MethodHandler) MethodHandler
86
87 // addMiddleware wraps the handler in the middleware functions.
88 func addMiddleware(handlerp *MethodHandler, middleware []Middleware) {
89 for _, m := range slices.Backward(middleware) {
90 *handlerp = m(*handlerp)
91 }
92 }
93
94 func defaultSendingMethodHandler(ctx context.Context, method string, req Request) (Result, error) {
95 info, ok := req.GetSession().sendingMethodInfos()[method]
96 if !ok {
97 // This can be called from user code, with an arbitrary value for method.
98 return nil, jsonrpc2.ErrNotHandled
99 }
100 params := req.GetParams()
101 if initParams, ok := params.(*InitializeParams); ok {
102 // Fix the marshaling of initialize params, to work around #607.
103 //
104 // The initialize params we produce should never be nil, nor have nil
105 // capabilities, so any panic here is a bug.
106 params = initParams.toV2()
107 }
108 // Notifications don't have results.
109 if strings.HasPrefix(method, "notifications/") {
110 return nil, req.GetSession().getConn().Notify(ctx, method, params)
111 }
112 // Create the result to unmarshal into.
113 // The concrete type of the result is the return type of the receiving function.
114 res := info.newResult()
115 if err := call(ctx, req.GetSession().getConn(), method, params, res); err != nil {
116 return nil, err
117 }
118 return res, nil
119 }
120
121 // Helper method to avoid typed nil.
122 func orZero[T any, P *U, U any](p P) T {
123 if p == nil {
124 var zero T
125 return zero
126 }
127 return any(p).(T)
128 }
129
130 func handleNotify(ctx context.Context, method string, req Request) error {
131 mh := req.GetSession().sendingMethodHandler()
132 _, err := mh(ctx, method, req)
133 return err
134 }
135
136 func handleSend[R Result](ctx context.Context, method string, req Request) (R, error) {
137 mh := req.GetSession().sendingMethodHandler()
138 // mh might be user code, so ensure that it returns the right values for the jsonrpc2 protocol.
139 res, err := mh(ctx, method, req)
140 if err != nil {
141 var z R
142 return z, err
143 }
144 return res.(R), nil
145 }
146
147 // defaultReceivingMethodHandler is the initial MethodHandler for servers and clients, before being wrapped by middleware.
148 func defaultReceivingMethodHandler[S Session](ctx context.Context, method string, req Request) (Result, error) {
149 info, ok := req.GetSession().receivingMethodInfos()[method]
150 if !ok {
151 // This can be called from user code, with an arbitrary value for method.
152 return nil, jsonrpc2.ErrNotHandled
153 }
154 return info.handleMethod(ctx, method, req)
155 }
156
157 func handleReceive[S Session](ctx context.Context, session S, jreq *jsonrpc.Request) (Result, error) {
158 info, err := checkRequest(jreq, session.receivingMethodInfos())
159 if err != nil {
160 return nil, err
161 }
162 params, err := info.unmarshalParams(jreq.Params)
163 if err != nil {
164 return nil, fmt.Errorf("handling '%s': %w", jreq.Method, err)
165 }
166
167 mh := session.receivingMethodHandler()
168 re, _ := jreq.Extra.(*RequestExtra)
169 req := info.newRequest(session, params, re)
170 // mh might be user code, so ensure that it returns the right values for the jsonrpc2 protocol.
171 res, err := mh(ctx, jreq.Method, req)
172 if err != nil {
173 return nil, err
174 }
175 return res, nil
176 }
177
178 // checkRequest checks the given request against the provided method info, to
179 // ensure it is a valid MCP request.
180 //
181 // If valid, the relevant method info is returned. Otherwise, a non-nil error
182 // is returned describing why the request is invalid.
183 //
184 // This is extracted from request handling so that it can be called in the
185 // transport layer to preemptively reject bad requests.
186 func checkRequest(req *jsonrpc.Request, infos map[string]methodInfo) (methodInfo, error) {
187 info, ok := infos[req.Method]
188 if !ok {
189 return methodInfo{}, fmt.Errorf("%w: %q unsupported", jsonrpc2.ErrNotHandled, req.Method)
190 }
191 if info.flags&notification != 0 && req.IsCall() {
192 return methodInfo{}, fmt.Errorf("%w: unexpected id for %q", jsonrpc2.ErrInvalidRequest, req.Method)
193 }
194 if info.flags&notification == 0 && !req.IsCall() {
195 return methodInfo{}, fmt.Errorf("%w: missing id for %q", jsonrpc2.ErrInvalidRequest, req.Method)
196 }
197 // missingParamsOK is checked here to catch the common case where "params" is
198 // missing entirely.
199 //
200 // However, it's checked again after unmarshalling to catch the rare but
201 // possible case where "params" is JSON null (see https://go.dev/issue/33835).
202 if info.flags&missingParamsOK == 0 && len(req.Params) == 0 {
203 return methodInfo{}, fmt.Errorf("%w: missing required \"params\"", jsonrpc2.ErrInvalidRequest)
204 }
205 return info, nil
206 }
207
208 // methodInfo is information about sending and receiving a method.
209 type methodInfo struct {
210 // flags is a collection of flags controlling how the JSONRPC method is
211 // handled. See individual flag values for documentation.
212 flags methodFlags
213 // Unmarshal params from the wire into a Params struct.
214 // Used on the receive side.
215 unmarshalParams func(json.RawMessage) (Params, error)
216 newRequest func(Session, Params, *RequestExtra) Request
217 // Run the code when a call to the method is received.
218 // Used on the receive side.
219 handleMethod MethodHandler
220 // Create a pointer to a Result struct.
221 // Used on the send side.
222 newResult func() Result
223 }
224
225 // The following definitions support converting from typed to untyped method handlers.
226 // Type parameter meanings:
227 // - S: sessions
228 // - P: params
229 // - R: results
230
231 // A typedMethodHandler is like a MethodHandler, but with type information.
232 type (
233 typedClientMethodHandler[P Params, R Result] func(context.Context, *ClientRequest[P]) (R, error)
234 typedServerMethodHandler[P Params, R Result] func(context.Context, *ServerRequest[P]) (R, error)
235 )
236
237 type paramsPtr[T any] interface {
238 *T
239 Params
240 }
241
242 type methodFlags int
243
244 const (
245 notification methodFlags = 1 << iota // method is a notification, not request
246 missingParamsOK // params may be missing or null
247 )
248
249 func newClientMethodInfo[P paramsPtr[T], R Result, T any](d typedClientMethodHandler[P, R], flags methodFlags) methodInfo {
250 mi := newMethodInfo[P, R](flags)
251 mi.newRequest = func(s Session, p Params, _ *RequestExtra) Request {
252 r := &ClientRequest[P]{Session: s.(*ClientSession)}
253 if p != nil {
254 r.Params = p.(P)
255 }
256 return r
257 }
258 mi.handleMethod = MethodHandler(func(ctx context.Context, _ string, req Request) (Result, error) {
259 return d(ctx, req.(*ClientRequest[P]))
260 })
261 return mi
262 }
263
264 func newServerMethodInfo[P paramsPtr[T], R Result, T any](d typedServerMethodHandler[P, R], flags methodFlags) methodInfo {
265 mi := newMethodInfo[P, R](flags)
266 mi.newRequest = func(s Session, p Params, re *RequestExtra) Request {
267 r := &ServerRequest[P]{Session: s.(*ServerSession), Extra: re}
268 if p != nil {
269 r.Params = p.(P)
270 }
271 return r
272 }
273 mi.handleMethod = MethodHandler(func(ctx context.Context, _ string, req Request) (Result, error) {
274 return d(ctx, req.(*ServerRequest[P]))
275 })
276 return mi
277 }
278
279 // newMethodInfo creates a methodInfo from a typedMethodHandler.
280 //
281 // If isRequest is set, the method is treated as a request rather than a
282 // notification.
283 func newMethodInfo[P paramsPtr[T], R Result, T any](flags methodFlags) methodInfo {
284 return methodInfo{
285 flags: flags,
286 unmarshalParams: func(m json.RawMessage) (Params, error) {
287 var p P
288 if m != nil {
289 if err := internaljson.Unmarshal(m, &p); err != nil {
290 return nil, fmt.Errorf("unmarshaling %q into a %T: %w", m, p, err)
291 }
292 }
293 // We must check missingParamsOK here, in addition to checkRequest, to
294 // catch the edge cases where "params" is set to JSON null.
295 // See also https://go.dev/issue/33835.
296 //
297 // We need to ensure that p is non-null to guard against crashes, as our
298 // internal code or externally provided handlers may assume that params
299 // is non-null.
300 if flags&missingParamsOK == 0 && p == nil {
301 return nil, fmt.Errorf("%w: missing required \"params\"", jsonrpc2.ErrInvalidRequest)
302 }
303 return orZero[Params](p), nil
304 },
305 // newResult is used on the send side, to construct the value to unmarshal the result into.
306 // R is a pointer to a result struct. There is no way to "unpointer" it without reflection.
307 // TODO(jba): explore generic approaches to this, perhaps by treating R in
308 // the signature as the unpointered type.
309 newResult: func() Result { return reflect.New(reflect.TypeFor[R]().Elem()).Interface().(R) },
310 }
311 }
312
313 // serverMethod is glue for creating a typedMethodHandler from a method on Server.
314 func serverMethod[P Params, R Result](
315 f func(*Server, context.Context, *ServerRequest[P]) (R, error),
316 ) typedServerMethodHandler[P, R] {
317 return func(ctx context.Context, req *ServerRequest[P]) (R, error) {
318 return f(req.Session.server, ctx, req)
319 }
320 }
321
322 // clientMethod is glue for creating a typedMethodHandler from a method on Client.
323 func clientMethod[P Params, R Result](
324 f func(*Client, context.Context, *ClientRequest[P]) (R, error),
325 ) typedClientMethodHandler[P, R] {
326 return func(ctx context.Context, req *ClientRequest[P]) (R, error) {
327 return f(req.Session.client, ctx, req)
328 }
329 }
330
331 // serverSessionMethod is glue for creating a typedServerMethodHandler from a method on ServerSession.
332 func serverSessionMethod[P Params, R Result](f func(*ServerSession, context.Context, P) (R, error)) typedServerMethodHandler[P, R] {
333 return func(ctx context.Context, req *ServerRequest[P]) (R, error) {
334 return f(req.GetSession().(*ServerSession), ctx, req.Params)
335 }
336 }
337
338 // clientSessionMethod is glue for creating a typedMethodHandler from a method on ServerSession.
339 func clientSessionMethod[P Params, R Result](f func(*ClientSession, context.Context, P) (R, error)) typedClientMethodHandler[P, R] {
340 return func(ctx context.Context, req *ClientRequest[P]) (R, error) {
341 return f(req.GetSession().(*ClientSession), ctx, req.Params)
342 }
343 }
344
345 // MCP-specific error codes.
346 const (
347 // CodeHeaderMismatch indicates that HTTP headers do not match the corresponding values
348 // in the request body, or that required headers are missing or malformed.
349 CodeHeaderMismatch = -32001
350 // CodeResourceNotFound indicates that a requested resource could not be found.
351 CodeResourceNotFound = -32002
352 // CodeURLElicitationRequired indicates that the server requires URL elicitation
353 // before processing the request. The client should execute the elicitation handler
354 // with the elicitations provided in the error data.
355 CodeURLElicitationRequired = -32042
356 )
357
358 // URLElicitationRequiredError returns an error indicating that URL elicitation is required
359 // before the request can be processed. The elicitations parameter should contain the
360 // elicitation requests that must be completed.
361 func URLElicitationRequiredError(elicitations []*ElicitParams) error {
362 // Validate that all elicitations are URL mode
363 for _, elicit := range elicitations {
364 mode := elicit.Mode
365 if mode == "" {
366 mode = "form" // default mode
367 }
368 if mode != "url" {
369 panic(fmt.Sprintf("URLElicitationRequiredError requires all elicitations to be URL mode, got %q", mode))
370 }
371 }
372
373 data, err := json.Marshal(map[string]any{
374 "elicitations": elicitations,
375 })
376 if err != nil {
377 // This should never happen with valid ElicitParams
378 panic(fmt.Sprintf("failed to marshal elicitations: %v", err))
379 }
380 return &jsonrpc.Error{
381 Code: CodeURLElicitationRequired,
382 Message: "URL elicitation required",
383 Data: json.RawMessage(data),
384 }
385 }
386
387 // Internal error codes
388 const (
389 // The error code if the method exists and was called properly, but the peer does not support it.
390 //
391 // TODO(rfindley): this code is wrong, and we should fix it to be
392 // consistent with other SDKs.
393 codeUnsupportedMethod = -31001
394 )
395
396 // notifySessions calls Notify on all the sessions.
397 // Should be called on a copy of the peer sessions.
398 // The logger must be non-nil.
399 func notifySessions[S Session, P Params](sessions []S, method string, params P, logger *slog.Logger) {
400 if sessions == nil {
401 return
402 }
403 // Notify with the background context, so the messages are sent on the
404 // standalone stream.
405 // TODO: make this timeout configurable, or call handleNotify asynchronously.
406 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
407 defer cancel()
408
409 // TODO: there's a potential spec violation here, when the feature list
410 // changes before the session (client or server) is initialized.
411 for _, s := range sessions {
412 req := newRequest(s, params)
413 if err := handleNotify(ctx, method, req); err != nil {
414 logger.Warn(fmt.Sprintf("calling %s: %v", method, err))
415 }
416 }
417 }
418
419 func newRequest[S Session, P Params](s S, p P) Request {
420 switch s := any(s).(type) {
421 case *ClientSession:
422 return &ClientRequest[P]{Session: s, Params: p}
423 case *ServerSession:
424 return &ServerRequest[P]{Session: s, Params: p}
425 default:
426 panic("bad session")
427 }
428 }
429
430 // Meta is additional metadata for requests, responses and other types.
431 type Meta map[string]any
432
433 // GetMeta returns metadata from a value.
434 func (m Meta) GetMeta() map[string]any { return m }
435
436 // SetMeta sets the metadata on a value.
437 func (m *Meta) SetMeta(x map[string]any) { *m = x }
438
439 const progressTokenKey = "progressToken"
440
441 func getProgressToken(p Params) any {
442 return p.GetMeta()[progressTokenKey]
443 }
444
445 func setProgressToken(p Params, pt any) {
446 switch pt.(type) {
447 // Support int32 and int64 for atomic.IntNN.
448 case int, int32, int64, string:
449 default:
450 panic(fmt.Sprintf("progress token %v is of type %[1]T, not int or string", pt))
451 }
452 m := p.GetMeta()
453 if m == nil {
454 m = map[string]any{}
455 p.SetMeta(m)
456 }
457 m[progressTokenKey] = pt
458 }
459
460 // A Request is a method request with parameters and additional information, such as the session.
461 // Request is implemented by [*ClientRequest] and [*ServerRequest].
462 type Request interface {
463 isRequest()
464 GetSession() Session
465 GetParams() Params
466 // GetExtra returns the Extra field for ServerRequests, and nil for ClientRequests.
467 GetExtra() *RequestExtra
468 }
469
470 // A ClientRequest is a request to a client.
471 type ClientRequest[P Params] struct {
472 Session *ClientSession
473 Params P
474 }
475
476 // A ServerRequest is a request to a server.
477 type ServerRequest[P Params] struct {
478 Session *ServerSession
479 Params P
480 Extra *RequestExtra
481 }
482
483 // RequestExtra is extra information included in requests, typically from
484 // the transport layer.
485 type RequestExtra struct {
486 TokenInfo *auth.TokenInfo // bearer token info (e.g. from OAuth) if any
487 Header http.Header // header from HTTP request, if any
488
489 // If set, CloseSSEStream explicitly closes the current SSE request stream.
490 //
491 // [SEP-1699] introduced server-side SSE stream disconnection: for
492 // long-running requests, servers may opt to close the SSE stream and
493 // ask the client to retry at a later time. CloseSSEStream implements this
494 // feature; if RetryAfter is set, an event is sent with a `retry:` field
495 // to configure the reconnection delay.
496 //
497 // [SEP-1699]: https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699
498 CloseSSEStream func(CloseSSEStreamArgs)
499 }
500
501 // CloseSSEStreamArgs are arguments for [RequestExtra.CloseSSEStream].
502 type CloseSSEStreamArgs struct {
503 // RetryAfter configures the reconnection delay sent to the client via the
504 // SSE retry field. If zero, no retry field is sent.
505 RetryAfter time.Duration
506 }
507
508 func (*ClientRequest[P]) isRequest() {}
509 func (*ServerRequest[P]) isRequest() {}
510
511 func (r *ClientRequest[P]) GetSession() Session { return r.Session }
512 func (r *ServerRequest[P]) GetSession() Session { return r.Session }
513
514 func (r *ClientRequest[P]) GetParams() Params { return r.Params }
515 func (r *ServerRequest[P]) GetParams() Params { return r.Params }
516
517 func (r *ClientRequest[P]) GetExtra() *RequestExtra { return nil }
518 func (r *ServerRequest[P]) GetExtra() *RequestExtra { return r.Extra }
519
520 func serverRequestFor[P Params](s *ServerSession, p P) *ServerRequest[P] {
521 return &ServerRequest[P]{Session: s, Params: p}
522 }
523
524 func clientRequestFor[P Params](s *ClientSession, p P) *ClientRequest[P] {
525 return &ClientRequest[P]{Session: s, Params: p}
526 }
527
528 // Params is a parameter (input) type for an MCP call or notification.
529 type Params interface {
530 // GetMeta returns metadata from a value.
531 GetMeta() map[string]any
532 // SetMeta sets the metadata on a value.
533 SetMeta(map[string]any)
534
535 // isParams discourages implementation of Params outside of this package.
536 isParams()
537 }
538
539 // RequestParams is a parameter (input) type for an MCP request.
540 type RequestParams interface {
541 Params
542
543 // GetProgressToken returns the progress token from the params' Meta field, or nil
544 // if there is none.
545 GetProgressToken() any
546
547 // SetProgressToken sets the given progress token into the params' Meta field.
548 // It panics if its argument is not an int or a string.
549 SetProgressToken(any)
550 }
551
552 // Result is a result of an MCP call.
553 type Result interface {
554 // isResult discourages implementation of Result outside of this package.
555 isResult()
556
557 // GetMeta returns metadata from a value.
558 GetMeta() map[string]any
559 // SetMeta sets the metadata on a value.
560 SetMeta(map[string]any)
561 }
562
563 // emptyResult is returned by methods that have no result, like ping.
564 // Those methods cannot return nil, because jsonrpc2 cannot handle nils.
565 type emptyResult struct{}
566
567 func (*emptyResult) isResult() {}
568 func (*emptyResult) GetMeta() map[string]any { panic("should never be called") }
569 func (*emptyResult) SetMeta(map[string]any) { panic("should never be called") }
570
571 type listParams interface {
572 // Returns a pointer to the param's Cursor field.
573 cursorPtr() *string
574 }
575
576 type listResult[T any] interface {
577 // Returns a pointer to the param's NextCursor field.
578 nextCursorPtr() *string
579 }
580
581 // keepaliveSession represents a session that supports keepalive functionality.
582 type keepaliveSession interface {
583 Ping(ctx context.Context, params *PingParams) error
584 Close() error
585 }
586
587 // startKeepalive starts the keepalive mechanism for a session.
588 // It assigns the cancel function to the provided cancelPtr and starts a goroutine
589 // that sends ping messages at the specified interval.
590 //
591 // logger must be non-nil; ping failures (which terminate the keepalive loop and
592 // close the session) are reported via logger so they are not silently dropped.
593 func startKeepalive(session keepaliveSession, interval time.Duration, cancelPtr *context.CancelFunc, logger *slog.Logger) {
594 ctx, cancel := context.WithCancel(context.Background())
595 // Assign cancel function before starting goroutine to avoid race condition.
596 // We cannot return it because the caller may need to cancel during the
597 // window between goroutine scheduling and function return.
598 *cancelPtr = cancel
599
600 go func() {
601 ticker := time.NewTicker(interval)
602 defer ticker.Stop()
603
604 for {
605 select {
606 case <-ctx.Done():
607 return
608 case <-ticker.C:
609 pingCtx, pingCancel := context.WithTimeout(context.Background(), interval/2)
610 err := session.Ping(pingCtx, nil)
611 pingCancel()
612 if err != nil {
613 if errors.Is(err, jsonrpc2.ErrMethodNotFound) {
614 // Peer doesn't support ping, stop the keepalive process.
615 return
616 }
617 // Ping failed; log it before closing the session so the
618 // failure is observable to operators. See #218.
619 logger.Error("keepalive ping failed; closing session", "error", err)
620 _ = session.Close()
621 return
622 }
623 }
624 }
625 }()
626 }