| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 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 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 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 |
|
| 54 |
|
| 55 |
func negotiatedVersion(clientVersion string) string { |
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
if !slices.Contains(supportedProtocolVersions, clientVersion) { |
| 62 |
return latestProtocolVersion |
| 63 |
} |
| 64 |
return clientVersion |
| 65 |
} |
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
type MethodHandler func(ctx context.Context, method string, req Request) (result Result, err error) |
| 71 |
|
| 72 |
|
| 73 |
type Session interface { |
| 74 |
|
| 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 |
|
| 85 |
type Middleware func(MethodHandler) MethodHandler |
| 86 |
|
| 87 |
|
| 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 |
|
| 98 |
return nil, jsonrpc2.ErrNotHandled |
| 99 |
} |
| 100 |
params := req.GetParams() |
| 101 |
if initParams, ok := params.(*InitializeParams); ok { |
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
params = initParams.toV2() |
| 107 |
} |
| 108 |
|
| 109 |
if strings.HasPrefix(method, "notifications/") { |
| 110 |
return nil, req.GetSession().getConn().Notify(ctx, method, params) |
| 111 |
} |
| 112 |
|
| 113 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 171 |
res, err := mh(ctx, jreq.Method, req) |
| 172 |
if err != nil { |
| 173 |
return nil, err |
| 174 |
} |
| 175 |
return res, nil |
| 176 |
} |
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
|
| 181 |
|
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
|
| 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¬ification != 0 && req.IsCall() { |
| 192 |
return methodInfo{}, fmt.Errorf("%w: unexpected id for %q", jsonrpc2.ErrInvalidRequest, req.Method) |
| 193 |
} |
| 194 |
if info.flags¬ification == 0 && !req.IsCall() { |
| 195 |
return methodInfo{}, fmt.Errorf("%w: missing id for %q", jsonrpc2.ErrInvalidRequest, req.Method) |
| 196 |
} |
| 197 |
|
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
|
| 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 |
|
| 209 |
type methodInfo struct { |
| 210 |
|
| 211 |
|
| 212 |
flags methodFlags |
| 213 |
|
| 214 |
|
| 215 |
unmarshalParams func(json.RawMessage) (Params, error) |
| 216 |
newRequest func(Session, Params, *RequestExtra) Request |
| 217 |
|
| 218 |
|
| 219 |
handleMethod MethodHandler |
| 220 |
|
| 221 |
|
| 222 |
newResult func() Result |
| 223 |
} |
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 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 |
| 246 |
missingParamsOK |
| 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 |
|
| 280 |
|
| 281 |
|
| 282 |
|
| 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 |
|
| 294 |
|
| 295 |
|
| 296 |
|
| 297 |
|
| 298 |
|
| 299 |
|
| 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 |
|
| 306 |
|
| 307 |
|
| 308 |
|
| 309 |
newResult: func() Result { return reflect.New(reflect.TypeFor[R]().Elem()).Interface().(R) }, |
| 310 |
} |
| 311 |
} |
| 312 |
|
| 313 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 346 |
const ( |
| 347 |
|
| 348 |
|
| 349 |
CodeHeaderMismatch = -32001 |
| 350 |
|
| 351 |
CodeResourceNotFound = -32002 |
| 352 |
|
| 353 |
|
| 354 |
|
| 355 |
CodeURLElicitationRequired = -32042 |
| 356 |
) |
| 357 |
|
| 358 |
|
| 359 |
|
| 360 |
|
| 361 |
func URLElicitationRequiredError(elicitations []*ElicitParams) error { |
| 362 |
|
| 363 |
for _, elicit := range elicitations { |
| 364 |
mode := elicit.Mode |
| 365 |
if mode == "" { |
| 366 |
mode = "form" |
| 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 |
|
| 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 |
|
| 388 |
const ( |
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
|
| 393 |
codeUnsupportedMethod = -31001 |
| 394 |
) |
| 395 |
|
| 396 |
|
| 397 |
|
| 398 |
|
| 399 |
func notifySessions[S Session, P Params](sessions []S, method string, params P, logger *slog.Logger) { |
| 400 |
if sessions == nil { |
| 401 |
return |
| 402 |
} |
| 403 |
|
| 404 |
|
| 405 |
|
| 406 |
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 407 |
defer cancel() |
| 408 |
|
| 409 |
|
| 410 |
|
| 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 |
|
| 431 |
type Meta map[string]any |
| 432 |
|
| 433 |
|
| 434 |
func (m Meta) GetMeta() map[string]any { return m } |
| 435 |
|
| 436 |
|
| 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 |
|
| 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 |
|
| 461 |
|
| 462 |
type Request interface { |
| 463 |
isRequest() |
| 464 |
GetSession() Session |
| 465 |
GetParams() Params |
| 466 |
|
| 467 |
GetExtra() *RequestExtra |
| 468 |
} |
| 469 |
|
| 470 |
|
| 471 |
type ClientRequest[P Params] struct { |
| 472 |
Session *ClientSession |
| 473 |
Params P |
| 474 |
} |
| 475 |
|
| 476 |
|
| 477 |
type ServerRequest[P Params] struct { |
| 478 |
Session *ServerSession |
| 479 |
Params P |
| 480 |
Extra *RequestExtra |
| 481 |
} |
| 482 |
|
| 483 |
|
| 484 |
|
| 485 |
type RequestExtra struct { |
| 486 |
TokenInfo *auth.TokenInfo |
| 487 |
Header http.Header |
| 488 |
|
| 489 |
|
| 490 |
|
| 491 |
|
| 492 |
|
| 493 |
|
| 494 |
|
| 495 |
|
| 496 |
|
| 497 |
|
| 498 |
CloseSSEStream func(CloseSSEStreamArgs) |
| 499 |
} |
| 500 |
|
| 501 |
|
| 502 |
type CloseSSEStreamArgs struct { |
| 503 |
|
| 504 |
|
| 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 |
|
| 529 |
type Params interface { |
| 530 |
|
| 531 |
GetMeta() map[string]any |
| 532 |
|
| 533 |
SetMeta(map[string]any) |
| 534 |
|
| 535 |
|
| 536 |
isParams() |
| 537 |
} |
| 538 |
|
| 539 |
|
| 540 |
type RequestParams interface { |
| 541 |
Params |
| 542 |
|
| 543 |
|
| 544 |
|
| 545 |
GetProgressToken() any |
| 546 |
|
| 547 |
|
| 548 |
|
| 549 |
SetProgressToken(any) |
| 550 |
} |
| 551 |
|
| 552 |
|
| 553 |
type Result interface { |
| 554 |
|
| 555 |
isResult() |
| 556 |
|
| 557 |
|
| 558 |
GetMeta() map[string]any |
| 559 |
|
| 560 |
SetMeta(map[string]any) |
| 561 |
} |
| 562 |
|
| 563 |
|
| 564 |
|
| 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 |
|
| 573 |
cursorPtr() *string |
| 574 |
} |
| 575 |
|
| 576 |
type listResult[T any] interface { |
| 577 |
|
| 578 |
nextCursorPtr() *string |
| 579 |
} |
| 580 |
|
| 581 |
|
| 582 |
type keepaliveSession interface { |
| 583 |
Ping(ctx context.Context, params *PingParams) error |
| 584 |
Close() error |
| 585 |
} |
| 586 |
|
| 587 |
|
| 588 |
|
| 589 |
|
| 590 |
|
| 591 |
|
| 592 |
|
| 593 |
func startKeepalive(session keepaliveSession, interval time.Duration, cancelPtr *context.CancelFunc, logger *slog.Logger) { |
| 594 |
ctx, cancel := context.WithCancel(context.Background()) |
| 595 |
|
| 596 |
|
| 597 |
|
| 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 |
|
| 615 |
return |
| 616 |
} |
| 617 |
|
| 618 |
|
| 619 |
logger.Error("keepalive ping failed; closing session", "error", err) |
| 620 |
_ = session.Close() |
| 621 |
return |
| 622 |
} |
| 623 |
} |
| 624 |
} |
| 625 |
}() |
| 626 |
} |