| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
package mcp |
| 10 |
|
| 11 |
import ( |
| 12 |
"bytes" |
| 13 |
"context" |
| 14 |
crand "crypto/rand" |
| 15 |
"encoding/json" |
| 16 |
"errors" |
| 17 |
"fmt" |
| 18 |
"io" |
| 19 |
"log/slog" |
| 20 |
"maps" |
| 21 |
"math" |
| 22 |
"math/rand/v2" |
| 23 |
"mime" |
| 24 |
"net" |
| 25 |
"net/http" |
| 26 |
"slices" |
| 27 |
"strconv" |
| 28 |
"strings" |
| 29 |
"sync" |
| 30 |
"sync/atomic" |
| 31 |
"time" |
| 32 |
|
| 33 |
"github.com/modelcontextprotocol/go-sdk/auth" |
| 34 |
internaljson "github.com/modelcontextprotocol/go-sdk/internal/json" |
| 35 |
"github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2" |
| 36 |
"github.com/modelcontextprotocol/go-sdk/internal/mcpgodebug" |
| 37 |
"github.com/modelcontextprotocol/go-sdk/internal/util" |
| 38 |
"github.com/modelcontextprotocol/go-sdk/internal/xcontext" |
| 39 |
"github.com/modelcontextprotocol/go-sdk/jsonrpc" |
| 40 |
) |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
type StreamableHTTPHandler struct { |
| 47 |
getServer func(*http.Request) *Server |
| 48 |
opts StreamableHTTPOptions |
| 49 |
|
| 50 |
onTransportDeletion func(sessionID string) |
| 51 |
|
| 52 |
mu sync.Mutex |
| 53 |
sessions map[string]*sessionInfo |
| 54 |
} |
| 55 |
|
| 56 |
type sessionInfo struct { |
| 57 |
session *ServerSession |
| 58 |
transport *StreamableServerTransport |
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
userID string |
| 63 |
|
| 64 |
|
| 65 |
timeout time.Duration |
| 66 |
timerMu sync.Mutex |
| 67 |
refs int |
| 68 |
timer *time.Timer |
| 69 |
} |
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
func (i *sessionInfo) startPOST() { |
| 79 |
if i.timeout <= 0 { |
| 80 |
return |
| 81 |
} |
| 82 |
|
| 83 |
i.timerMu.Lock() |
| 84 |
defer i.timerMu.Unlock() |
| 85 |
|
| 86 |
if i.timer == nil { |
| 87 |
return |
| 88 |
} |
| 89 |
if i.refs == 0 { |
| 90 |
i.timer.Stop() |
| 91 |
} |
| 92 |
i.refs++ |
| 93 |
} |
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
func (i *sessionInfo) endPOST() { |
| 98 |
if i.timeout <= 0 { |
| 99 |
return |
| 100 |
} |
| 101 |
|
| 102 |
i.timerMu.Lock() |
| 103 |
defer i.timerMu.Unlock() |
| 104 |
|
| 105 |
if i.timer == nil { |
| 106 |
return |
| 107 |
} |
| 108 |
|
| 109 |
i.refs-- |
| 110 |
assert(i.refs >= 0, "negative ref count") |
| 111 |
if i.refs == 0 { |
| 112 |
i.timer.Reset(i.timeout) |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
|
| 117 |
func (i *sessionInfo) stopTimer() { |
| 118 |
i.timerMu.Lock() |
| 119 |
defer i.timerMu.Unlock() |
| 120 |
if i.timer != nil { |
| 121 |
i.timer.Stop() |
| 122 |
i.timer = nil |
| 123 |
} |
| 124 |
} |
| 125 |
|
| 126 |
|
| 127 |
type StreamableHTTPOptions struct { |
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
Stateless bool |
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
. |
| 142 |
|
| 143 |
r |
| 144 |
JSONResponse bool |
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
Logger *slog.Logger |
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
EventStore EventStore |
| 155 |
|
| 156 |
|
| 157 |
|
| 158 |
|
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
SessionTimeout time.Duration |
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
|
| 171 |
|
| 172 |
DisableLocalhostProtection bool |
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
|
| 181 |
|
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
|
| 186 |
CrossOriginProtection *http.CrossOriginProtection |
| 187 |
} |
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
func NewStreamableHTTPHandler(getServer func(*http.Request) *Server, opts *StreamableHTTPOptions) *StreamableHTTPHandler { |
| 195 |
h := &StreamableHTTPHandler{ |
| 196 |
getServer: getServer, |
| 197 |
sessions: make(map[string]*sessionInfo), |
| 198 |
} |
| 199 |
if opts != nil { |
| 200 |
h.opts = *opts |
| 201 |
} |
| 202 |
|
| 203 |
h.opts.Logger = ensureLogger(h.opts.Logger) |
| 204 |
|
| 205 |
if h.opts.CrossOriginProtection == nil && enableoriginverification == "1" { |
| 206 |
h.opts.CrossOriginProtection = &http.CrossOriginProtection{} |
| 207 |
} |
| 208 |
|
| 209 |
return h |
| 210 |
} |
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
|
| 215 |
|
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
func (h *StreamableHTTPHandler) closeAll() { |
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
h.mu.Lock() |
| 227 |
sessionInfos := slices.Collect(maps.Values(h.sessions)) |
| 228 |
h.sessions = nil |
| 229 |
h.mu.Unlock() |
| 230 |
for _, s := range sessionInfos { |
| 231 |
s.session.Close() |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
var disablelocalhostprotection = mcpgodebug.Value("disablelocalhostprotection") |
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
var enableoriginverification = mcpgodebug.Value("enableoriginverification") |
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
var disablecontenttypecheck = mcpgodebug.Value("disablecontenttypecheck") |
| 254 |
|
| 255 |
func (h *StreamableHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { |
| 256 |
|
| 257 |
|
| 258 |
if !h.opts.DisableLocalhostProtection && disablelocalhostprotection != "1" { |
| 259 |
if localAddr, ok := req.Context().Value(http.LocalAddrContextKey).(net.Addr); ok && localAddr != nil { |
| 260 |
if util.IsLoopback(localAddr.String()) && !util.IsLoopback(req.Host) { |
| 261 |
http.Error(w, fmt.Sprintf("Forbidden: invalid Host header %q", req.Host), http.StatusForbidden) |
| 262 |
return |
| 263 |
} |
| 264 |
} |
| 265 |
} |
| 266 |
|
| 267 |
if h.opts.CrossOriginProtection != nil { |
| 268 |
|
| 269 |
if err := h.opts.CrossOriginProtection.Check(req); err != nil { |
| 270 |
http.Error(w, err.Error(), http.StatusForbidden) |
| 271 |
return |
| 272 |
} |
| 273 |
} |
| 274 |
|
| 275 |
|
| 276 |
if disablecontenttypecheck != "1" && req.Method == http.MethodPost && baseMediaType(req.Header.Get("Content-Type")) != "application/json" { |
| 277 |
http.Error(w, "Content-Type must be 'application/json'", http.StatusUnsupportedMediaType) |
| 278 |
return |
| 279 |
} |
| 280 |
|
| 281 |
|
| 282 |
|
| 283 |
jsonOK, streamOK := streamableAccepts(req.Header.Values("Accept")) |
| 284 |
|
| 285 |
if req.Method == http.MethodGet { |
| 286 |
if !streamOK { |
| 287 |
http.Error(w, "Accept must contain 'text/event-stream' for GET requests", http.StatusBadRequest) |
| 288 |
return |
| 289 |
} |
| 290 |
} else if (!jsonOK || !streamOK) && req.Method != http.MethodDelete { |
| 291 |
http.Error(w, "Accept must contain both 'application/json' and 'text/event-stream'", http.StatusBadRequest) |
| 292 |
return |
| 293 |
} |
| 294 |
|
| 295 |
sessionID := req.Header.Get(sessionIDHeader) |
| 296 |
var sessInfo *sessionInfo |
| 297 |
if sessionID != "" { |
| 298 |
h.mu.Lock() |
| 299 |
sessInfo = h.sessions[sessionID] |
| 300 |
h.mu.Unlock() |
| 301 |
if sessInfo == nil && !h.opts.Stateless { |
| 302 |
|
| 303 |
|
| 304 |
|
| 305 |
|
| 306 |
http.Error(w, "session not found", http.StatusNotFound) |
| 307 |
return |
| 308 |
} |
| 309 |
|
| 310 |
|
| 311 |
if sessInfo != nil && sessInfo.userID != "" { |
| 312 |
tokenInfo := auth.TokenInfoFromContext(req.Context()) |
| 313 |
if tokenInfo == nil || tokenInfo.UserID != sessInfo.userID { |
| 314 |
http.Error(w, "session user mismatch", http.StatusForbidden) |
| 315 |
return |
| 316 |
} |
| 317 |
} |
| 318 |
} |
| 319 |
|
| 320 |
if req.Method == http.MethodDelete { |
| 321 |
if sessionID == "" { |
| 322 |
http.Error(w, "Bad Request: DELETE requires an Mcp-Session-Id header", http.StatusBadRequest) |
| 323 |
return |
| 324 |
} |
| 325 |
if sessInfo != nil { |
| 326 |
|
| 327 |
|
| 328 |
sessInfo.session.Close() |
| 329 |
} |
| 330 |
w.WriteHeader(http.StatusNoContent) |
| 331 |
return |
| 332 |
} |
| 333 |
|
| 334 |
switch req.Method { |
| 335 |
case http.MethodPost, http.MethodGet: |
| 336 |
if req.Method == http.MethodGet && (h.opts.Stateless || sessionID == "") { |
| 337 |
if h.opts.Stateless { |
| 338 |
|
| 339 |
|
| 340 |
. |
| 341 |
w.Header().Set("Allow", "POST") |
| 342 |
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed) |
| 343 |
} else { |
| 344 |
|
| 345 |
|
| 346 |
http.Error(w, "Bad Request: GET requires an Mcp-Session-Id header", http.StatusBadRequest) |
| 347 |
} |
| 348 |
return |
| 349 |
} |
| 350 |
default: |
| 351 |
. |
| 352 |
if h.opts.Stateless { |
| 353 |
w.Header().Set("Allow", "POST") |
| 354 |
} else { |
| 355 |
w.Header().Set("Allow", "GET, POST, DELETE") |
| 356 |
} |
| 357 |
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed) |
| 358 |
return |
| 359 |
} |
| 360 |
|
| 361 |
: |
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
|
| 367 |
|
| 368 |
|
| 369 |
|
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
|
| 374 |
|
| 375 |
|
| 376 |
|
| 377 |
|
| 378 |
|
| 379 |
|
| 380 |
|
| 381 |
|
| 382 |
|
| 383 |
|
| 384 |
|
| 385 |
|
| 386 |
|
| 387 |
|
| 388 |
|
| 389 |
|
| 390 |
r |
| 391 |
protocolVersion := req.Header.Get(protocolVersionHeader) |
| 392 |
if protocolVersion == "" { |
| 393 |
protocolVersion = protocolVersion20250326 |
| 394 |
} |
| 395 |
if !slices.Contains(supportedProtocolVersions, protocolVersion) { |
| 396 |
http.Error(w, fmt.Sprintf("Bad Request: Unsupported protocol version (supported versions: %s)", strings.Join(supportedProtocolVersions, ",")), http.StatusBadRequest) |
| 397 |
return |
| 398 |
} |
| 399 |
|
| 400 |
if sessInfo == nil { |
| 401 |
server := h.getServer(req) |
| 402 |
if server == nil { |
| 403 |
|
| 404 |
http.Error(w, "no server available", http.StatusBadRequest) |
| 405 |
return |
| 406 |
} |
| 407 |
if sessionID == "" { |
| 408 |
|
| 409 |
|
| 410 |
sessionID = server.opts.GetSessionID() |
| 411 |
} |
| 412 |
transport := &StreamableServerTransport{ |
| 413 |
SessionID: sessionID, |
| 414 |
Stateless: h.opts.Stateless, |
| 415 |
EventStore: h.opts.EventStore, |
| 416 |
jsonResponse: h.opts.JSONResponse, |
| 417 |
logger: h.opts.Logger, |
| 418 |
} |
| 419 |
|
| 420 |
|
| 421 |
|
| 422 |
stateless := h.opts.Stateless || sessionID == "" |
| 423 |
|
| 424 |
|
| 425 |
var connectOpts *ServerSessionOptions |
| 426 |
if stateless { |
| 427 |
|
| 428 |
|
| 429 |
var hasInitialize, hasInitialized bool |
| 430 |
{ |
| 431 |
|
| 432 |
|
| 433 |
body, err := io.ReadAll(req.Body) |
| 434 |
if err != nil { |
| 435 |
http.Error(w, "failed to read body", http.StatusBadRequest) |
| 436 |
return |
| 437 |
} |
| 438 |
req.Body.Close() |
| 439 |
|
| 440 |
|
| 441 |
req.Body = io.NopCloser(bytes.NewBuffer(body)) |
| 442 |
|
| 443 |
msgs, _, err := readBatch(body) |
| 444 |
if err == nil { |
| 445 |
for _, msg := range msgs { |
| 446 |
if req, ok := msg.(*jsonrpc.Request); ok { |
| 447 |
switch req.Method { |
| 448 |
case methodInitialize: |
| 449 |
hasInitialize = true |
| 450 |
case notificationInitialized: |
| 451 |
hasInitialized = true |
| 452 |
} |
| 453 |
} |
| 454 |
} |
| 455 |
} |
| 456 |
} |
| 457 |
|
| 458 |
|
| 459 |
|
| 460 |
state := new(ServerSessionState) |
| 461 |
if !hasInitialize { |
| 462 |
state.InitializeParams = &InitializeParams{ |
| 463 |
ProtocolVersion: protocolVersion, |
| 464 |
} |
| 465 |
} |
| 466 |
if !hasInitialized { |
| 467 |
state.InitializedParams = new(InitializedParams) |
| 468 |
} |
| 469 |
state.LogLevel = "info" |
| 470 |
connectOpts = &ServerSessionOptions{ |
| 471 |
State: state, |
| 472 |
} |
| 473 |
} else { |
| 474 |
|
| 475 |
|
| 476 |
connectOpts = &ServerSessionOptions{ |
| 477 |
onClose: func() { |
| 478 |
h.mu.Lock() |
| 479 |
defer h.mu.Unlock() |
| 480 |
if info, ok := h.sessions[transport.SessionID]; ok { |
| 481 |
info.stopTimer() |
| 482 |
delete(h.sessions, transport.SessionID) |
| 483 |
if h.onTransportDeletion != nil { |
| 484 |
h.onTransportDeletion(transport.SessionID) |
| 485 |
} |
| 486 |
} |
| 487 |
}, |
| 488 |
} |
| 489 |
} |
| 490 |
|
| 491 |
|
| 492 |
|
| 493 |
|
| 494 |
session, err := server.Connect(req.Context(), transport, connectOpts) |
| 495 |
if err != nil { |
| 496 |
http.Error(w, "failed connection", http.StatusInternalServerError) |
| 497 |
return |
| 498 |
} |
| 499 |
|
| 500 |
|
| 501 |
var userID string |
| 502 |
if tokenInfo := auth.TokenInfoFromContext(req.Context()); tokenInfo != nil { |
| 503 |
userID = tokenInfo.UserID |
| 504 |
} |
| 505 |
sessInfo = &sessionInfo{ |
| 506 |
session: session, |
| 507 |
transport: transport, |
| 508 |
userID: userID, |
| 509 |
} |
| 510 |
|
| 511 |
if stateless { |
| 512 |
|
| 513 |
defer session.Close() |
| 514 |
} else { |
| 515 |
|
| 516 |
|
| 517 |
|
| 518 |
|
| 519 |
|
| 520 |
|
| 521 |
if h.opts.SessionTimeout > 0 { |
| 522 |
sessInfo.timeout = h.opts.SessionTimeout |
| 523 |
sessInfo.timer = time.AfterFunc(sessInfo.timeout, func() { |
| 524 |
sessInfo.session.Close() |
| 525 |
}) |
| 526 |
} |
| 527 |
h.mu.Lock() |
| 528 |
h.sessions[transport.SessionID] = sessInfo |
| 529 |
h.mu.Unlock() |
| 530 |
defer func() { |
| 531 |
|
| 532 |
if session.InitializeParams() == nil { |
| 533 |
|
| 534 |
session.Close() |
| 535 |
} |
| 536 |
}() |
| 537 |
} |
| 538 |
} |
| 539 |
|
| 540 |
if req.Method == http.MethodPost { |
| 541 |
sessInfo.startPOST() |
| 542 |
defer sessInfo.endPOST() |
| 543 |
} |
| 544 |
|
| 545 |
sessInfo.transport.ServeHTTP(w, req) |
| 546 |
} |
| 547 |
|
| 548 |
func streamableAccepts(values []string) (jsonOK, streamOK bool) { |
| 549 |
for _, value := range values { |
| 550 |
for _, raw := range strings.Split(value, ",") { |
| 551 |
token := strings.TrimSpace(raw) |
| 552 |
|
| 553 |
base, _, _ := strings.Cut(token, ";") |
| 554 |
switch strings.ToLower(strings.TrimSpace(base)) { |
| 555 |
case "application/json", "application/*": |
| 556 |
jsonOK = true |
| 557 |
case "text/event-stream", "text/*": |
| 558 |
streamOK = true |
| 559 |
case "*/*": |
| 560 |
jsonOK = true |
| 561 |
streamOK = true |
| 562 |
} |
| 563 |
} |
| 564 |
} |
| 565 |
return jsonOK, streamOK |
| 566 |
} |
| 567 |
|
| 568 |
func baseMediaType(value string) string { |
| 569 |
mediaType, _, err := mime.ParseMediaType(value) |
| 570 |
if err != nil { |
| 571 |
return "" |
| 572 |
} |
| 573 |
return mediaType |
| 574 |
} |
| 575 |
|
| 576 |
|
| 577 |
|
| 578 |
|
| 579 |
|
| 580 |
|
| 581 |
|
| 582 |
|
| 583 |
|
| 584 |
|
| 585 |
|
| 586 |
|
| 587 |
|
| 588 |
|
| 589 |
|
| 590 |
|
| 591 |
|
| 592 |
|
| 593 |
|
| 594 |
|
| 595 |
type StreamableServerTransport struct { |
| 596 |
|
| 597 |
|
| 598 |
|
| 599 |
|
| 600 |
|
| 601 |
|
| 602 |
|
| 603 |
SessionID string |
| 604 |
|
| 605 |
|
| 606 |
|
| 607 |
|
| 608 |
|
| 609 |
|
| 610 |
Stateless bool |
| 611 |
|
| 612 |
|
| 613 |
|
| 614 |
|
| 615 |
|
| 616 |
EventStore EventStore |
| 617 |
|
| 618 |
|
| 619 |
|
| 620 |
|
| 621 |
|
| 622 |
|
| 623 |
|
| 624 |
|
| 625 |
|
| 626 |
|
| 627 |
|
| 628 |
|
| 629 |
jsonResponse bool |
| 630 |
|
| 631 |
|
| 632 |
|
| 633 |
|
| 634 |
|
| 635 |
logger *slog.Logger |
| 636 |
|
| 637 |
|
| 638 |
connection *streamableServerConn |
| 639 |
} |
| 640 |
|
| 641 |
|
| 642 |
func (t *StreamableServerTransport) Connect(ctx context.Context) (Connection, error) { |
| 643 |
if t.connection != nil { |
| 644 |
return nil, fmt.Errorf("transport already connected") |
| 645 |
} |
| 646 |
t.connection = &streamableServerConn{ |
| 647 |
sessionID: t.SessionID, |
| 648 |
stateless: t.Stateless, |
| 649 |
eventStore: t.EventStore, |
| 650 |
jsonResponse: t.jsonResponse, |
| 651 |
logger: ensureLogger(t.logger), |
| 652 |
incoming: make(chan jsonrpc.Message, 10), |
| 653 |
done: make(chan struct{}), |
| 654 |
streams: make(map[string]*stream), |
| 655 |
requestStreams: make(map[jsonrpc.ID]string), |
| 656 |
} |
| 657 |
|
| 658 |
|
| 659 |
|
| 660 |
|
| 661 |
var err error |
| 662 |
t.connection.streams[""], err = t.connection.newStream(ctx, nil, "") |
| 663 |
if err != nil { |
| 664 |
return nil, err |
| 665 |
} |
| 666 |
return t.connection, nil |
| 667 |
} |
| 668 |
|
| 669 |
type streamableServerConn struct { |
| 670 |
sessionID string |
| 671 |
stateless bool |
| 672 |
jsonResponse bool |
| 673 |
eventStore EventStore |
| 674 |
|
| 675 |
logger *slog.Logger |
| 676 |
|
| 677 |
incoming chan jsonrpc.Message |
| 678 |
|
| 679 |
mu sync.Mutex |
| 680 |
|
| 681 |
|
| 682 |
isDone bool |
| 683 |
done chan struct{} |
| 684 |
|
| 685 |
|
| 686 |
|
| 687 |
|
| 688 |
|
| 689 |
|
| 690 |
|
| 691 |
|
| 692 |
|
| 693 |
|
| 694 |
|
| 695 |
|
| 696 |
|
| 697 |
|
| 698 |
streams map[string]*stream |
| 699 |
|
| 700 |
|
| 701 |
|
| 702 |
|
| 703 |
requestStreams map[jsonrpc.ID]string |
| 704 |
} |
| 705 |
|
| 706 |
func (c *streamableServerConn) SessionID() string { |
| 707 |
return c.sessionID |
| 708 |
} |
| 709 |
|
| 710 |
|
| 711 |
|
| 712 |
|
| 713 |
|
| 714 |
|
| 715 |
|
| 716 |
|
| 717 |
type stream struct { |
| 718 |
|
| 719 |
|
| 720 |
|
| 721 |
id string |
| 722 |
|
| 723 |
|
| 724 |
logger *slog.Logger |
| 725 |
|
| 726 |
|
| 727 |
|
| 728 |
mu sync.Mutex |
| 729 |
|
| 730 |
|
| 731 |
|
| 732 |
|
| 733 |
|
| 734 |
|
| 735 |
|
| 736 |
pendingJSONMessages []json.RawMessage |
| 737 |
|
| 738 |
|
| 739 |
|
| 740 |
|
| 741 |
w http.ResponseWriter |
| 742 |
|
| 743 |
|
| 744 |
|
| 745 |
|
| 746 |
|
| 747 |
|
| 748 |
done chan struct{} |
| 749 |
|
| 750 |
|
| 751 |
|
| 752 |
lastIdx int |
| 753 |
|
| 754 |
|
| 755 |
protocolVersion string |
| 756 |
|
| 757 |
|
| 758 |
|
| 759 |
|
| 760 |
|
| 761 |
|
| 762 |
|
| 763 |
requests map[jsonrpc.ID]struct{} |
| 764 |
} |
| 765 |
|
| 766 |
|
| 767 |
|
| 768 |
|
| 769 |
|
| 770 |
|
| 771 |
func (s *stream) close(reconnectAfter time.Duration) { |
| 772 |
s.mu.Lock() |
| 773 |
defer s.mu.Unlock() |
| 774 |
if s.done == nil { |
| 775 |
return |
| 776 |
} |
| 777 |
if s.protocolVersion >= protocolVersion20251125 && reconnectAfter > 0 { |
| 778 |
reconnectStr := strconv.FormatInt(reconnectAfter.Milliseconds(), 10) |
| 779 |
if _, err := writeEvent(s.w, Event{ |
| 780 |
Name: "close", |
| 781 |
Retry: reconnectStr, |
| 782 |
}); err != nil { |
| 783 |
s.logger.Warn(fmt.Sprintf("Writing close event: %v", err)) |
| 784 |
} |
| 785 |
} |
| 786 |
close(s.done) |
| 787 |
s.done = nil |
| 788 |
} |
| 789 |
|
| 790 |
|
| 791 |
|
| 792 |
func (s *stream) release() { |
| 793 |
s.mu.Lock() |
| 794 |
defer s.mu.Unlock() |
| 795 |
s.w = nil |
| 796 |
s.done = nil |
| 797 |
} |
| 798 |
|
| 799 |
|
| 800 |
|
| 801 |
|
| 802 |
|
| 803 |
|
| 804 |
|
| 805 |
|
| 806 |
|
| 807 |
|
| 808 |
|
| 809 |
|
| 810 |
func (s *stream) deliverLocked(data []byte, eventID string, responseTo jsonrpc.ID) (done bool, err error) { |
| 811 |
|
| 812 |
|
| 813 |
|
| 814 |
if responseTo.IsValid() { |
| 815 |
delete(s.requests, responseTo) |
| 816 |
} |
| 817 |
|
| 818 |
done = len(s.requests) == 0 && s.id != "" |
| 819 |
if s.done == nil { |
| 820 |
return done, fmt.Errorf("stream not connected or already closed") |
| 821 |
} |
| 822 |
if done { |
| 823 |
defer func() { close(s.done); s.done = nil }() |
| 824 |
} |
| 825 |
|
| 826 |
|
| 827 |
|
| 828 |
|
| 829 |
|
| 830 |
|
| 831 |
if s.pendingJSONMessages != nil { |
| 832 |
s.pendingJSONMessages = append(s.pendingJSONMessages, data) |
| 833 |
if done { |
| 834 |
|
| 835 |
var toWrite []byte |
| 836 |
if len(s.pendingJSONMessages) == 1 { |
| 837 |
toWrite = s.pendingJSONMessages[0] |
| 838 |
} else { |
| 839 |
toWrite, err = json.Marshal(s.pendingJSONMessages) |
| 840 |
if err != nil { |
| 841 |
return done, err |
| 842 |
} |
| 843 |
} |
| 844 |
if _, err := s.w.Write(toWrite); err != nil { |
| 845 |
return done, err |
| 846 |
} |
| 847 |
} |
| 848 |
} else { |
| 849 |
|
| 850 |
s.lastIdx++ |
| 851 |
if _, err := writeEvent(s.w, Event{Name: "message", Data: data, ID: eventID}); err != nil { |
| 852 |
return done, err |
| 853 |
} |
| 854 |
} |
| 855 |
return done, nil |
| 856 |
} |
| 857 |
|
| 858 |
|
| 859 |
|
| 860 |
|
| 861 |
|
| 862 |
|
| 863 |
|
| 864 |
|
| 865 |
func (s *stream) doneLocked() bool { |
| 866 |
return len(s.requests) == 0 && s.id != "" |
| 867 |
} |
| 868 |
|
| 869 |
func (c *streamableServerConn) newStream(ctx context.Context, requests map[jsonrpc.ID]struct{}, id string) (*stream, error) { |
| 870 |
if c.eventStore != nil { |
| 871 |
if err := c.eventStore.Open(ctx, c.sessionID, id); err != nil { |
| 872 |
return nil, err |
| 873 |
} |
| 874 |
} |
| 875 |
return &stream{ |
| 876 |
id: id, |
| 877 |
requests: requests, |
| 878 |
lastIdx: -1, |
| 879 |
logger: c.logger, |
| 880 |
}, nil |
| 881 |
} |
| 882 |
|
| 883 |
|
| 884 |
|
| 885 |
|
| 886 |
|
| 887 |
|
| 888 |
|
| 889 |
|
| 890 |
|
| 891 |
|
| 892 |
|
| 893 |
|
| 894 |
|
| 895 |
|
| 896 |
|
| 897 |
|
| 898 |
|
| 899 |
|
| 900 |
|
| 901 |
|
| 902 |
|
| 903 |
|
| 904 |
type idContextKey struct{} |
| 905 |
|
| 906 |
|
| 907 |
func (t *StreamableServerTransport) ServeHTTP(w http.ResponseWriter, req *http.Request) { |
| 908 |
if t.connection == nil { |
| 909 |
http.Error(w, "transport not connected", http.StatusInternalServerError) |
| 910 |
return |
| 911 |
} |
| 912 |
switch req.Method { |
| 913 |
case http.MethodGet: |
| 914 |
t.connection.serveGET(w, req) |
| 915 |
case http.MethodPost: |
| 916 |
t.connection.servePOST(w, req) |
| 917 |
default: |
| 918 |
|
| 919 |
w.Header().Set("Allow", "GET, POST") |
| 920 |
http.Error(w, "unsupported method", http.StatusMethodNotAllowed) |
| 921 |
return |
| 922 |
} |
| 923 |
} |
| 924 |
|
| 925 |
|
| 926 |
|
| 927 |
|
| 928 |
|
| 929 |
func (c *streamableServerConn) serveGET(w http.ResponseWriter, req *http.Request) { |
| 930 |
|
| 931 |
streamID := "" |
| 932 |
|
| 933 |
|
| 934 |
lastIdx := -1 |
| 935 |
if len(req.Header.Values(lastEventIDHeader)) > 0 { |
| 936 |
eid := req.Header.Get(lastEventIDHeader) |
| 937 |
var ok bool |
| 938 |
streamID, lastIdx, ok = parseEventID(eid) |
| 939 |
if !ok { |
| 940 |
http.Error(w, fmt.Sprintf("malformed Last-Event-ID %q", eid), http.StatusBadRequest) |
| 941 |
return |
| 942 |
} |
| 943 |
if c.eventStore == nil { |
| 944 |
http.Error(w, "stream replay unsupported", http.StatusBadRequest) |
| 945 |
return |
| 946 |
} |
| 947 |
} |
| 948 |
|
| 949 |
ctx := req.Context() |
| 950 |
|
| 951 |
|
| 952 |
|
| 953 |
protocolVersion := req.Header.Get(protocolVersionHeader) |
| 954 |
if protocolVersion == "" { |
| 955 |
protocolVersion = protocolVersion20250326 |
| 956 |
} |
| 957 |
|
| 958 |
stream, done := c.acquireStream(ctx, w, streamID, lastIdx, protocolVersion) |
| 959 |
if stream == nil { |
| 960 |
return |
| 961 |
} |
| 962 |
defer stream.release() |
| 963 |
c.hangResponse(ctx, done) |
| 964 |
} |
| 965 |
|
| 966 |
|
| 967 |
|
| 968 |
|
| 969 |
|
| 970 |
|
| 971 |
|
| 972 |
|
| 973 |
func (c *streamableServerConn) hangResponse(ctx context.Context, done <-chan struct{}) { |
| 974 |
select { |
| 975 |
case <-ctx.Done(): |
| 976 |
case <-done: |
| 977 |
case <-c.done: |
| 978 |
} |
| 979 |
} |
| 980 |
|
| 981 |
|
| 982 |
|
| 983 |
|
| 984 |
|
| 985 |
|
| 986 |
|
| 987 |
|
| 988 |
|
| 989 |
|
| 990 |
|
| 991 |
|
| 992 |
|
| 993 |
|
| 994 |
|
| 995 |
func (c *streamableServerConn) acquireStream(ctx context.Context, w http.ResponseWriter, streamID string, lastIdx int, protocolVersion string) (*stream, chan struct{}) { |
| 996 |
|
| 997 |
|
| 998 |
|
| 999 |
|
| 1000 |
|
| 1001 |
tempStream := false |
| 1002 |
c.mu.Lock() |
| 1003 |
s, ok := c.streams[streamID] |
| 1004 |
if !ok { |
| 1005 |
|
| 1006 |
|
| 1007 |
|
| 1008 |
|
| 1009 |
|
| 1010 |
tempStream = true |
| 1011 |
s = &stream{ |
| 1012 |
id: streamID, |
| 1013 |
w: w, |
| 1014 |
} |
| 1015 |
c.streams[streamID] = s |
| 1016 |
|
| 1017 |
|
| 1018 |
defer func() { |
| 1019 |
c.mu.Lock() |
| 1020 |
delete(c.streams, streamID) |
| 1021 |
c.mu.Unlock() |
| 1022 |
}() |
| 1023 |
} |
| 1024 |
c.mu.Unlock() |
| 1025 |
|
| 1026 |
s.mu.Lock() |
| 1027 |
defer s.mu.Unlock() |
| 1028 |
|
| 1029 |
|
| 1030 |
if !tempStream && s.w != nil { |
| 1031 |
http.Error(w, "stream ID conflicts with ongoing stream", http.StatusConflict) |
| 1032 |
return nil, nil |
| 1033 |
} |
| 1034 |
|
| 1035 |
|
| 1036 |
|
| 1037 |
|
| 1038 |
|
| 1039 |
|
| 1040 |
|
| 1041 |
var toReplay [][]byte |
| 1042 |
if c.eventStore != nil { |
| 1043 |
for data, err := range c.eventStore.After(ctx, c.SessionID(), s.id, lastIdx) { |
| 1044 |
if err != nil { |
| 1045 |
|
| 1046 |
|
| 1047 |
|
| 1048 |
|
| 1049 |
|
| 1050 |
|
| 1051 |
|
| 1052 |
|
| 1053 |
http.Error(w, "failed to replay events", http.StatusBadRequest) |
| 1054 |
return nil, nil |
| 1055 |
} |
| 1056 |
if len(data) > 0 { |
| 1057 |
toReplay = append(toReplay, data) |
| 1058 |
} |
| 1059 |
} |
| 1060 |
} |
| 1061 |
|
| 1062 |
w.Header().Set("Cache-Control", "no-cache, no-transform") |
| 1063 |
w.Header().Set("Content-Type", "text/event-stream") |
| 1064 |
w.Header().Set("Connection", "keep-alive") |
| 1065 |
|
| 1066 |
if s.id == "" { |
| 1067 |
|
| 1068 |
|
| 1069 |
w.WriteHeader(http.StatusOK) |
| 1070 |
rc := http.NewResponseController(w) |
| 1071 |
|
| 1072 |
_ = rc.Flush() |
| 1073 |
} |
| 1074 |
|
| 1075 |
for _, data := range toReplay { |
| 1076 |
lastIdx++ |
| 1077 |
e := Event{Name: "message", Data: data} |
| 1078 |
if c.eventStore != nil { |
| 1079 |
e.ID = formatEventID(s.id, lastIdx) |
| 1080 |
} |
| 1081 |
if _, err := writeEvent(w, e); err != nil { |
| 1082 |
return nil, nil |
| 1083 |
} |
| 1084 |
} |
| 1085 |
|
| 1086 |
if tempStream || s.doneLocked() { |
| 1087 |
|
| 1088 |
return nil, nil |
| 1089 |
} |
| 1090 |
|
| 1091 |
|
| 1092 |
|
| 1093 |
s.w = w |
| 1094 |
s.done = make(chan struct{}) |
| 1095 |
s.lastIdx = lastIdx |
| 1096 |
s.protocolVersion = protocolVersion |
| 1097 |
return s, s.done |
| 1098 |
} |
| 1099 |
|
| 1100 |
|
| 1101 |
|
| 1102 |
|
| 1103 |
|
| 1104 |
|
| 1105 |
func (c *streamableServerConn) servePOST(w http.ResponseWriter, req *http.Request) { |
| 1106 |
if len(req.Header.Values(lastEventIDHeader)) > 0 { |
| 1107 |
http.Error(w, "can't send Last-Event-ID for POST request", http.StatusBadRequest) |
| 1108 |
return |
| 1109 |
} |
| 1110 |
|
| 1111 |
|
| 1112 |
body, err := io.ReadAll(req.Body) |
| 1113 |
if err != nil { |
| 1114 |
http.Error(w, "failed to read body", http.StatusBadRequest) |
| 1115 |
return |
| 1116 |
} |
| 1117 |
if len(body) == 0 { |
| 1118 |
http.Error(w, "POST requires a non-empty body", http.StatusBadRequest) |
| 1119 |
return |
| 1120 |
} |
| 1121 |
|
| 1122 |
|
| 1123 |
|
| 1124 |
incoming, isBatch, err := readBatch(body) |
| 1125 |
if err != nil { |
| 1126 |
http.Error(w, fmt.Sprintf("malformed payload: %v", err), http.StatusBadRequest) |
| 1127 |
return |
| 1128 |
} |
| 1129 |
|
| 1130 |
protocolVersion := req.Header.Get(protocolVersionHeader) |
| 1131 |
if protocolVersion == "" { |
| 1132 |
protocolVersion = protocolVersion20250326 |
| 1133 |
} |
| 1134 |
|
| 1135 |
if isBatch && protocolVersion >= protocolVersion20250618 { |
| 1136 |
http.Error(w, fmt.Sprintf("JSON-RPC batching is not supported in %s and later (request version: %s)", protocolVersion20250618, protocolVersion), http.StatusBadRequest) |
| 1137 |
return |
| 1138 |
} |
| 1139 |
|
| 1140 |
|
| 1141 |
|
| 1142 |
|
| 1143 |
|
| 1144 |
|
| 1145 |
|
| 1146 |
|
| 1147 |
calls := make(map[jsonrpc.ID]struct{}) |
| 1148 |
tokenInfo := auth.TokenInfoFromContext(req.Context()) |
| 1149 |
isInitialize := false |
| 1150 |
var initializeProtocolVersion string |
| 1151 |
for _, msg := range incoming { |
| 1152 |
if jreq, ok := msg.(*jsonrpc.Request); ok { |
| 1153 |
|
| 1154 |
|
| 1155 |
|
| 1156 |
if _, err := checkRequest(jreq, serverMethodInfos); err != nil { |
| 1157 |
http.Error(w, err.Error(), http.StatusBadRequest) |
| 1158 |
return |
| 1159 |
} |
| 1160 |
if jreq.Method == methodInitialize { |
| 1161 |
isInitialize = true |
| 1162 |
|
| 1163 |
var params InitializeParams |
| 1164 |
if err := internaljson.Unmarshal(jreq.Params, ¶ms); err == nil { |
| 1165 |
initializeProtocolVersion = params.ProtocolVersion |
| 1166 |
} |
| 1167 |
} |
| 1168 |
|
| 1169 |
jreq.Extra = &RequestExtra{ |
| 1170 |
TokenInfo: tokenInfo, |
| 1171 |
Header: req.Header, |
| 1172 |
} |
| 1173 |
if jreq.IsCall() { |
| 1174 |
calls[jreq.ID] = struct{}{} |
| 1175 |
|
| 1176 |
|
| 1177 |
jreq.Extra.(*RequestExtra).CloseSSEStream = func(args CloseSSEStreamArgs) { |
| 1178 |
c.mu.Lock() |
| 1179 |
streamID, ok := c.requestStreams[jreq.ID] |
| 1180 |
var stream *stream |
| 1181 |
if ok { |
| 1182 |
stream = c.streams[streamID] |
| 1183 |
} |
| 1184 |
c.mu.Unlock() |
| 1185 |
|
| 1186 |
if stream != nil { |
| 1187 |
stream.close(args.RetryAfter) |
| 1188 |
} |
| 1189 |
} |
| 1190 |
} |
| 1191 |
} |
| 1192 |
} |
| 1193 |
|
| 1194 |
|
| 1195 |
if !isBatch && len(incoming) == 1 { |
| 1196 |
if err := validateMcpHeaders(req.Header, incoming[0]); err != nil { |
| 1197 |
resp := &jsonrpc.Response{ |
| 1198 |
Error: jsonrpc2.NewError(CodeHeaderMismatch, err.Error()), |
| 1199 |
} |
| 1200 |
if jreq, ok := incoming[0].(*jsonrpc.Request); ok { |
| 1201 |
resp.ID = jreq.ID |
| 1202 |
} |
| 1203 |
w.Header().Set("Content-Type", "application/json") |
| 1204 |
w.WriteHeader(http.StatusBadRequest) |
| 1205 |
if data, err := jsonrpc2.EncodeMessage(resp); err == nil { |
| 1206 |
w.Write(data) |
| 1207 |
} |
| 1208 |
return |
| 1209 |
} |
| 1210 |
} |
| 1211 |
|
| 1212 |
|
| 1213 |
|
| 1214 |
|
| 1215 |
effectiveVersion := protocolVersion |
| 1216 |
if isInitialize && initializeProtocolVersion != "" { |
| 1217 |
effectiveVersion = initializeProtocolVersion |
| 1218 |
} |
| 1219 |
|
| 1220 |
|
| 1221 |
|
| 1222 |
|
| 1223 |
e |
| 1224 |
|
| 1225 |
|
| 1226 |
r |
| 1227 |
if len(calls) == 0 { |
| 1228 |
for _, msg := range incoming { |
| 1229 |
select { |
| 1230 |
case c.incoming <- msg: |
| 1231 |
case <-c.done: |
| 1232 |
|
| 1233 |
|
| 1234 |
http.Error(w, "session is closing", http.StatusNotFound) |
| 1235 |
return |
| 1236 |
} |
| 1237 |
} |
| 1238 |
w.WriteHeader(http.StatusAccepted) |
| 1239 |
return |
| 1240 |
} |
| 1241 |
|
| 1242 |
|
| 1243 |
|
| 1244 |
|
| 1245 |
|
| 1246 |
|
| 1247 |
|
| 1248 |
stream, err := c.newStream(req.Context(), calls, crand.Text()) |
| 1249 |
if err != nil { |
| 1250 |
http.Error(w, fmt.Sprintf("storing stream: %v", err), http.StatusInternalServerError) |
| 1251 |
return |
| 1252 |
} |
| 1253 |
|
| 1254 |
|
| 1255 |
w.Header().Set("Cache-Control", "no-cache, no-transform") |
| 1256 |
if c.jsonResponse { |
| 1257 |
w.Header().Set("Content-Type", "application/json") |
| 1258 |
} else { |
| 1259 |
w.Header().Set("Content-Type", "text/event-stream") |
| 1260 |
w.Header().Set("Connection", "keep-alive") |
| 1261 |
} |
| 1262 |
if c.sessionID != "" && isInitialize { |
| 1263 |
w.Header().Set(sessionIDHeader, c.sessionID) |
| 1264 |
} |
| 1265 |
|
| 1266 |
|
| 1267 |
stream.w = w |
| 1268 |
done := make(chan struct{}) |
| 1269 |
stream.done = done |
| 1270 |
stream.protocolVersion = effectiveVersion |
| 1271 |
if c.jsonResponse { |
| 1272 |
|
| 1273 |
|
| 1274 |
|
| 1275 |
stream.pendingJSONMessages = []json.RawMessage{} |
| 1276 |
} else { |
| 1277 |
|
| 1278 |
if c.eventStore != nil && effectiveVersion >= protocolVersion20251125 { |
| 1279 |
. |
| 1280 |
|
| 1281 |
r |
| 1282 |
|
| 1283 |
|
| 1284 |
|
| 1285 |
if err := c.eventStore.Append(req.Context(), c.sessionID, stream.id, nil); err != nil { |
| 1286 |
c.logger.Warn(fmt.Sprintf("Storing priming event: %v", err)) |
| 1287 |
} |
| 1288 |
stream.lastIdx++ |
| 1289 |
e := Event{Name: "prime", ID: formatEventID(stream.id, stream.lastIdx)} |
| 1290 |
if _, err := writeEvent(w, e); err != nil { |
| 1291 |
c.logger.Warn(fmt.Sprintf("Writing priming event: %v", err)) |
| 1292 |
} |
| 1293 |
} |
| 1294 |
} |
| 1295 |
|
| 1296 |
|
| 1297 |
|
| 1298 |
defer stream.release() |
| 1299 |
|
| 1300 |
|
| 1301 |
|
| 1302 |
|
| 1303 |
c.mu.Lock() |
| 1304 |
c.streams[stream.id] = stream |
| 1305 |
for reqID := range calls { |
| 1306 |
c.requestStreams[reqID] = stream.id |
| 1307 |
} |
| 1308 |
c.mu.Unlock() |
| 1309 |
|
| 1310 |
|
| 1311 |
for _, msg := range incoming { |
| 1312 |
select { |
| 1313 |
case c.incoming <- msg: |
| 1314 |
|
| 1315 |
|
| 1316 |
|
| 1317 |
|
| 1318 |
|
| 1319 |
case <-c.done: |
| 1320 |
|
| 1321 |
|
| 1322 |
return |
| 1323 |
} |
| 1324 |
} |
| 1325 |
|
| 1326 |
c.hangResponse(req.Context(), done) |
| 1327 |
} |
| 1328 |
|
| 1329 |
|
| 1330 |
|
| 1331 |
|
| 1332 |
|
| 1333 |
|
| 1334 |
|
| 1335 |
|
| 1336 |
func formatEventID(sid string, idx int) string { |
| 1337 |
return fmt.Sprintf("%s_%d", sid, idx) |
| 1338 |
} |
| 1339 |
|
| 1340 |
|
| 1341 |
|
| 1342 |
|
| 1343 |
|
| 1344 |
func parseEventID(eventID string) (streamID string, idx int, ok bool) { |
| 1345 |
parts := strings.Split(eventID, "_") |
| 1346 |
if len(parts) != 2 { |
| 1347 |
return "", 0, false |
| 1348 |
} |
| 1349 |
streamID = parts[0] |
| 1350 |
idx, err := strconv.Atoi(parts[1]) |
| 1351 |
if err != nil || idx < 0 { |
| 1352 |
return "", 0, false |
| 1353 |
} |
| 1354 |
return streamID, idx, true |
| 1355 |
} |
| 1356 |
|
| 1357 |
|
| 1358 |
func (c *streamableServerConn) Read(ctx context.Context) (jsonrpc.Message, error) { |
| 1359 |
select { |
| 1360 |
case <-ctx.Done(): |
| 1361 |
return nil, ctx.Err() |
| 1362 |
case msg, ok := <-c.incoming: |
| 1363 |
if !ok { |
| 1364 |
return nil, io.EOF |
| 1365 |
} |
| 1366 |
return msg, nil |
| 1367 |
case <-c.done: |
| 1368 |
return nil, io.EOF |
| 1369 |
} |
| 1370 |
} |
| 1371 |
|
| 1372 |
|
| 1373 |
func (c *streamableServerConn) Write(ctx context.Context, msg jsonrpc.Message) error { |
| 1374 |
|
| 1375 |
|
| 1376 |
|
| 1377 |
|
| 1378 |
|
| 1379 |
|
| 1380 |
data, err := jsonrpc2.EncodeMessage(msg) |
| 1381 |
if err != nil { |
| 1382 |
return err |
| 1383 |
} |
| 1384 |
|
| 1385 |
if req, ok := msg.(*jsonrpc.Request); ok && req.IsCall() && (c.stateless || c.sessionID == "") { |
| 1386 |
|
| 1387 |
return fmt.Errorf("%w: stateless servers cannot make requests", jsonrpc2.ErrRejected) |
| 1388 |
} |
| 1389 |
|
| 1390 |
|
| 1391 |
var ( |
| 1392 |
relatedRequest jsonrpc.ID |
| 1393 |
responseTo jsonrpc.ID |
| 1394 |
) |
| 1395 |
if resp, ok := msg.(*jsonrpc.Response); ok { |
| 1396 |
|
| 1397 |
relatedRequest = resp.ID |
| 1398 |
responseTo = resp.ID |
| 1399 |
} else { |
| 1400 |
|
| 1401 |
|
| 1402 |
|
| 1403 |
if v := ctx.Value(idContextKey{}); v != nil { |
| 1404 |
relatedRequest = v.(jsonrpc.ID) |
| 1405 |
} |
| 1406 |
} |
| 1407 |
|
| 1408 |
|
| 1409 |
|
| 1410 |
if c.jsonResponse && !responseTo.IsValid() { |
| 1411 |
relatedRequest = jsonrpc.ID{} |
| 1412 |
} |
| 1413 |
|
| 1414 |
|
| 1415 |
var s *stream |
| 1416 |
c.mu.Lock() |
| 1417 |
if relatedRequest.IsValid() { |
| 1418 |
if streamID, ok := c.requestStreams[relatedRequest]; ok { |
| 1419 |
s = c.streams[streamID] |
| 1420 |
} |
| 1421 |
} else { |
| 1422 |
s = c.streams[""] |
| 1423 |
} |
| 1424 |
if responseTo.IsValid() { |
| 1425 |
|
| 1426 |
|
| 1427 |
delete(c.requestStreams, responseTo) |
| 1428 |
} |
| 1429 |
sessionClosed := c.isDone |
| 1430 |
c.mu.Unlock() |
| 1431 |
|
| 1432 |
if s == nil { |
| 1433 |
|
| 1434 |
|
| 1435 |
|
| 1436 |
|
| 1437 |
|
| 1438 |
return fmt.Errorf("%w: write to closed stream", jsonrpc2.ErrRejected) |
| 1439 |
} |
| 1440 |
if sessionClosed { |
| 1441 |
return errors.New("session is closed") |
| 1442 |
} |
| 1443 |
|
| 1444 |
s.mu.Lock() |
| 1445 |
defer s.mu.Unlock() |
| 1446 |
|
| 1447 |
|
| 1448 |
|
| 1449 |
|
| 1450 |
delivered := false |
| 1451 |
var errs []error |
| 1452 |
if c.eventStore != nil { |
| 1453 |
if err := c.eventStore.Append(ctx, c.sessionID, s.id, data); err != nil { |
| 1454 |
errs = append(errs, err) |
| 1455 |
} else { |
| 1456 |
delivered = true |
| 1457 |
} |
| 1458 |
} |
| 1459 |
|
| 1460 |
|
| 1461 |
|
| 1462 |
var eventID string |
| 1463 |
if c.eventStore != nil { |
| 1464 |
eventID = formatEventID(s.id, s.lastIdx+1) |
| 1465 |
} |
| 1466 |
|
| 1467 |
done, err := s.deliverLocked(data, eventID, responseTo) |
| 1468 |
if err != nil { |
| 1469 |
errs = append(errs, err) |
| 1470 |
} else { |
| 1471 |
delivered = true |
| 1472 |
} |
| 1473 |
|
| 1474 |
if done { |
| 1475 |
c.mu.Lock() |
| 1476 |
delete(c.streams, s.id) |
| 1477 |
c.mu.Unlock() |
| 1478 |
} |
| 1479 |
|
| 1480 |
if !delivered { |
| 1481 |
return fmt.Errorf("%w: undelivered message: %v", jsonrpc2.ErrRejected, errors.Join(errs...)) |
| 1482 |
} |
| 1483 |
return nil |
| 1484 |
} |
| 1485 |
|
| 1486 |
|
| 1487 |
func (c *streamableServerConn) Close() error { |
| 1488 |
c.mu.Lock() |
| 1489 |
defer c.mu.Unlock() |
| 1490 |
if !c.isDone { |
| 1491 |
c.isDone = true |
| 1492 |
close(c.done) |
| 1493 |
if c.eventStore != nil { |
| 1494 |
|
| 1495 |
|
| 1496 |
return c.eventStore.SessionClosed(context.TODO(), c.sessionID) |
| 1497 |
} |
| 1498 |
} |
| 1499 |
return nil |
| 1500 |
} |
| 1501 |
|
| 1502 |
|
| 1503 |
|
| 1504 |
|
| 1505 |
type StreamableClientTransport struct { |
| 1506 |
Endpoint string |
| 1507 |
HTTPClient *http.Client |
| 1508 |
|
| 1509 |
|
| 1510 |
MaxRetries int |
| 1511 |
|
| 1512 |
|
| 1513 |
|
| 1514 |
|
| 1515 |
|
| 1516 |
|
| 1517 |
|
| 1518 |
|
| 1519 |
|
| 1520 |
|
| 1521 |
|
| 1522 |
|
| 1523 |
|
| 1524 |
|
| 1525 |
|
| 1526 |
|
| 1527 |
|
| 1528 |
|
| 1529 |
|
| 1530 |
DisableStandaloneSSE bool |
| 1531 |
|
| 1532 |
|
| 1533 |
OAuthHandler auth.OAuthHandler |
| 1534 |
|
| 1535 |
|
| 1536 |
|
| 1537 |
|
| 1538 |
strict bool |
| 1539 |
|
| 1540 |
|
| 1541 |
logger *slog.Logger |
| 1542 |
} |
| 1543 |
|
| 1544 |
|
| 1545 |
|
| 1546 |
const ( |
| 1547 |
|
| 1548 |
|
| 1549 |
|
| 1550 |
reconnectGrowFactor = 1.5 |
| 1551 |
|
| 1552 |
reconnectMaxDelay = 30 * time.Second |
| 1553 |
) |
| 1554 |
|
| 1555 |
var ( |
| 1556 |
|
| 1557 |
|
| 1558 |
|
| 1559 |
reconnectInitialDelay atomic.Int64 |
| 1560 |
) |
| 1561 |
|
| 1562 |
func init() { |
| 1563 |
reconnectInitialDelay.Store(int64(1 * time.Second)) |
| 1564 |
} |
| 1565 |
|
| 1566 |
|
| 1567 |
|
| 1568 |
|
| 1569 |
|
| 1570 |
|
| 1571 |
|
| 1572 |
|
| 1573 |
|
| 1574 |
func (t *StreamableClientTransport) Connect(ctx context.Context) (Connection, error) { |
| 1575 |
client := t.HTTPClient |
| 1576 |
if client == nil { |
| 1577 |
client = http.DefaultClient |
| 1578 |
} |
| 1579 |
maxRetries := t.MaxRetries |
| 1580 |
if maxRetries == 0 { |
| 1581 |
maxRetries = 5 |
| 1582 |
} else if maxRetries < 0 { |
| 1583 |
maxRetries = 0 |
| 1584 |
} |
| 1585 |
|
| 1586 |
|
| 1587 |
|
| 1588 |
|
| 1589 |
|
| 1590 |
|
| 1591 |
|
| 1592 |
|
| 1593 |
|
| 1594 |
|
| 1595 |
|
| 1596 |
|
| 1597 |
|
| 1598 |
|
| 1599 |
|
| 1600 |
|
| 1601 |
connCtx, cancel := context.WithCancel(xcontext.Detach(ctx)) |
| 1602 |
conn := &streamableClientConn{ |
| 1603 |
url: t.Endpoint, |
| 1604 |
client: client, |
| 1605 |
incoming: make(chan jsonrpc.Message, 10), |
| 1606 |
done: make(chan struct{}), |
| 1607 |
maxRetries: maxRetries, |
| 1608 |
strict: t.strict, |
| 1609 |
logger: ensureLogger(t.logger), |
| 1610 |
ctx: connCtx, |
| 1611 |
cancel: cancel, |
| 1612 |
failed: make(chan struct{}), |
| 1613 |
disableStandaloneSSE: t.DisableStandaloneSSE, |
| 1614 |
oauthHandler: t.OAuthHandler, |
| 1615 |
} |
| 1616 |
return conn, nil |
| 1617 |
} |
| 1618 |
|
| 1619 |
type streamableClientConn struct { |
| 1620 |
url string |
| 1621 |
client *http.Client |
| 1622 |
ctx context.Context |
| 1623 |
cancel context.CancelFunc |
| 1624 |
incoming chan jsonrpc.Message |
| 1625 |
maxRetries int |
| 1626 |
strict bool |
| 1627 |
logger *slog.Logger |
| 1628 |
|
| 1629 |
|
| 1630 |
|
| 1631 |
disableStandaloneSSE bool |
| 1632 |
|
| 1633 |
|
| 1634 |
oauthHandler auth.OAuthHandler |
| 1635 |
|
| 1636 |
|
| 1637 |
closeOnce sync.Once |
| 1638 |
closeErr error |
| 1639 |
done chan struct{} |
| 1640 |
|
| 1641 |
|
| 1642 |
|
| 1643 |
|
| 1644 |
|
| 1645 |
|
| 1646 |
|
| 1647 |
|
| 1648 |
failOnce sync.Once |
| 1649 |
_failure error |
| 1650 |
failed chan struct{} |
| 1651 |
|
| 1652 |
|
| 1653 |
mu sync.Mutex |
| 1654 |
initializedResult *InitializeResult |
| 1655 |
sessionID string |
| 1656 |
} |
| 1657 |
|
| 1658 |
var _ clientConnection = (*streamableClientConn)(nil) |
| 1659 |
|
| 1660 |
func (c *streamableClientConn) sessionUpdated(state clientSessionState) { |
| 1661 |
c.mu.Lock() |
| 1662 |
c.initializedResult = state.InitializeResult |
| 1663 |
c.mu.Unlock() |
| 1664 |
|
| 1665 |
|
| 1666 |
|
| 1667 |
|
| 1668 |
e |
| 1669 |
|
| 1670 |
|
| 1671 |
|
| 1672 |
|
| 1673 |
|
| 1674 |
|
| 1675 |
n |
| 1676 |
|
| 1677 |
|
| 1678 |
if !c.disableStandaloneSSE { |
| 1679 |
c.connectStandaloneSSE() |
| 1680 |
} |
| 1681 |
} |
| 1682 |
|
| 1683 |
func (c *streamableClientConn) connectStandaloneSSE() { |
| 1684 |
resp, err := c.connectSSE(c.ctx, "", 0, true) |
| 1685 |
if err != nil { |
| 1686 |
|
| 1687 |
|
| 1688 |
if c.ctx.Err() == nil { |
| 1689 |
c.fail(fmt.Errorf("standalone SSE request failed (session ID: %v): %v", c.sessionID, err)) |
| 1690 |
} |
| 1691 |
return |
| 1692 |
} |
| 1693 |
|
| 1694 |
: |
| 1695 |
|
| 1696 |
|
| 1697 |
|
| 1698 |
|
| 1699 |
r |
| 1700 |
if resp.StatusCode == http.StatusMethodNotAllowed { |
| 1701 |
|
| 1702 |
resp.Body.Close() |
| 1703 |
return |
| 1704 |
} |
| 1705 |
if baseMediaType(resp.Header.Get("Content-Type")) != "text/event-stream" { |
| 1706 |
|
| 1707 |
|
| 1708 |
|
| 1709 |
c.logger.Warn(fmt.Sprintf("got Content-Type %s instead of text/event-stream for standalone SSE stream", resp.Header.Get("Content-Type"))) |
| 1710 |
resp.Body.Close() |
| 1711 |
return |
| 1712 |
} |
| 1713 |
if resp.StatusCode >= 400 && resp.StatusCode < 500 && !c.strict { |
| 1714 |
|
| 1715 |
|
| 1716 |
|
| 1717 |
|
| 1718 |
|
| 1719 |
c.logger.Warn(fmt.Sprintf("got %d instead of 405 for standalone SSE stream", resp.StatusCode)) |
| 1720 |
resp.Body.Close() |
| 1721 |
return |
| 1722 |
} |
| 1723 |
summary := "standalone SSE stream" |
| 1724 |
if err := c.checkResponse(summary, resp); err != nil { |
| 1725 |
c.fail(err) |
| 1726 |
return |
| 1727 |
} |
| 1728 |
go c.handleSSE(c.ctx, summary, resp, nil) |
| 1729 |
} |
| 1730 |
|
| 1731 |
|
| 1732 |
|
| 1733 |
|
| 1734 |
|
| 1735 |
|
| 1736 |
|
| 1737 |
|
| 1738 |
|
| 1739 |
func (c *streamableClientConn) fail(err error) { |
| 1740 |
if err != nil { |
| 1741 |
c.failOnce.Do(func() { |
| 1742 |
c._failure = err |
| 1743 |
close(c.failed) |
| 1744 |
}) |
| 1745 |
} |
| 1746 |
} |
| 1747 |
|
| 1748 |
func (c *streamableClientConn) failure() error { |
| 1749 |
select { |
| 1750 |
case <-c.failed: |
| 1751 |
return c._failure |
| 1752 |
default: |
| 1753 |
return nil |
| 1754 |
} |
| 1755 |
} |
| 1756 |
|
| 1757 |
func (c *streamableClientConn) SessionID() string { |
| 1758 |
c.mu.Lock() |
| 1759 |
defer c.mu.Unlock() |
| 1760 |
return c.sessionID |
| 1761 |
} |
| 1762 |
|
| 1763 |
|
| 1764 |
func (c *streamableClientConn) Read(ctx context.Context) (jsonrpc.Message, error) { |
| 1765 |
if err := c.failure(); err != nil { |
| 1766 |
return nil, err |
| 1767 |
} |
| 1768 |
select { |
| 1769 |
case <-ctx.Done(): |
| 1770 |
return nil, ctx.Err() |
| 1771 |
case <-c.failed: |
| 1772 |
return nil, c.failure() |
| 1773 |
case <-c.done: |
| 1774 |
return nil, io.EOF |
| 1775 |
case msg := <-c.incoming: |
| 1776 |
return msg, nil |
| 1777 |
} |
| 1778 |
} |
| 1779 |
|
| 1780 |
|
| 1781 |
func (c *streamableClientConn) Write(ctx context.Context, msg jsonrpc.Message) error { |
| 1782 |
if err := c.failure(); err != nil { |
| 1783 |
return err |
| 1784 |
} |
| 1785 |
|
| 1786 |
var requestSummary string |
| 1787 |
var forCall *jsonrpc.Request |
| 1788 |
switch msg := msg.(type) { |
| 1789 |
case *jsonrpc.Request: |
| 1790 |
requestSummary = fmt.Sprintf("sending %q", msg.Method) |
| 1791 |
if msg.IsCall() { |
| 1792 |
forCall = msg |
| 1793 |
} |
| 1794 |
case *jsonrpc.Response: |
| 1795 |
requestSummary = fmt.Sprintf("sending jsonrpc response #%d", msg.ID) |
| 1796 |
default: |
| 1797 |
panic("unreachable") |
| 1798 |
} |
| 1799 |
|
| 1800 |
data, err := jsonrpc.EncodeMessage(msg) |
| 1801 |
if err != nil { |
| 1802 |
return fmt.Errorf("%s: %v", requestSummary, err) |
| 1803 |
} |
| 1804 |
|
| 1805 |
doRequest := func() (*http.Request, *http.Response, error) { |
| 1806 |
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, bytes.NewReader(data)) |
| 1807 |
if err != nil { |
| 1808 |
return nil, nil, err |
| 1809 |
} |
| 1810 |
req.Header.Set("Content-Type", "application/json") |
| 1811 |
req.Header.Set("Accept", "application/json, text/event-stream") |
| 1812 |
if err := c.setMCPHeaders(req); err != nil { |
| 1813 |
|
| 1814 |
|
| 1815 |
|
| 1816 |
return nil, nil, fmt.Errorf("%s: %w: %w", requestSummary, jsonrpc2.ErrRejected, err) |
| 1817 |
} |
| 1818 |
|
| 1819 |
|
| 1820 |
setStandardHeaders(req.Header, msg) |
| 1821 |
resp, err := c.client.Do(req) |
| 1822 |
if err != nil { |
| 1823 |
|
| 1824 |
|
| 1825 |
|
| 1826 |
err = fmt.Errorf("%s: %w: %w", requestSummary, jsonrpc2.ErrRejected, err) |
| 1827 |
} |
| 1828 |
return req, resp, err |
| 1829 |
} |
| 1830 |
|
| 1831 |
req, resp, err := doRequest() |
| 1832 |
if err != nil { |
| 1833 |
return err |
| 1834 |
} |
| 1835 |
|
| 1836 |
if (resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden) && c.oauthHandler != nil { |
| 1837 |
if err := c.oauthHandler.Authorize(ctx, req, resp); err != nil { |
| 1838 |
|
| 1839 |
|
| 1840 |
|
| 1841 |
|
| 1842 |
|
| 1843 |
|
| 1844 |
|
| 1845 |
|
| 1846 |
|
| 1847 |
|
| 1848 |
|
| 1849 |
|
| 1850 |
ctxErr := ctx.Err() |
| 1851 |
if errors.Is(ctxErr, context.Canceled) || errors.Is(ctxErr, context.DeadlineExceeded) { |
| 1852 |
c.fail(fmt.Errorf("%s: authorization cancelled: %w", requestSummary, err)) |
| 1853 |
} |
| 1854 |
|
| 1855 |
|
| 1856 |
|
| 1857 |
return fmt.Errorf("%s: %w: %w", requestSummary, jsonrpc2.ErrRejected, err) |
| 1858 |
} |
| 1859 |
|
| 1860 |
_, resp, err = doRequest() |
| 1861 |
if err != nil { |
| 1862 |
return err |
| 1863 |
} |
| 1864 |
} |
| 1865 |
|
| 1866 |
if err := c.checkResponse(requestSummary, resp); err != nil { |
| 1867 |
|
| 1868 |
|
| 1869 |
if !errors.Is(err, jsonrpc2.ErrRejected) { |
| 1870 |
c.fail(err) |
| 1871 |
} |
| 1872 |
return err |
| 1873 |
} |
| 1874 |
|
| 1875 |
if sessionID := resp.Header.Get(sessionIDHeader); sessionID != "" { |
| 1876 |
c.mu.Lock() |
| 1877 |
hadSessionID := c.sessionID |
| 1878 |
if hadSessionID == "" { |
| 1879 |
c.sessionID = sessionID |
| 1880 |
} |
| 1881 |
c.mu.Unlock() |
| 1882 |
if hadSessionID != "" && hadSessionID != sessionID { |
| 1883 |
resp.Body.Close() |
| 1884 |
return fmt.Errorf("mismatching session IDs %q and %q", hadSessionID, sessionID) |
| 1885 |
} |
| 1886 |
} |
| 1887 |
|
| 1888 |
if forCall == nil { |
| 1889 |
resp.Body.Close() |
| 1890 |
|
| 1891 |
: |
| 1892 |
|
| 1893 |
|
| 1894 |
r |
| 1895 |
if resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusAccepted { |
| 1896 |
errMsg := fmt.Sprintf("unexpected status code %d from non-call", resp.StatusCode) |
| 1897 |
|
| 1898 |
|
| 1899 |
|
| 1900 |
c.logger.Warn(errMsg) |
| 1901 |
if c.strict { |
| 1902 |
return errors.New(errMsg) |
| 1903 |
} |
| 1904 |
} |
| 1905 |
return nil |
| 1906 |
} |
| 1907 |
|
| 1908 |
contentType := baseMediaType(resp.Header.Get("Content-Type")) |
| 1909 |
switch contentType { |
| 1910 |
case "application/json": |
| 1911 |
go c.handleJSON(requestSummary, resp) |
| 1912 |
|
| 1913 |
case "text/event-stream": |
| 1914 |
var forCall *jsonrpc.Request |
| 1915 |
if jsonReq, ok := msg.(*jsonrpc.Request); ok && jsonReq.IsCall() { |
| 1916 |
forCall = jsonReq |
| 1917 |
} |
| 1918 |
|
| 1919 |
|
| 1920 |
|
| 1921 |
|
| 1922 |
go c.handleSSE(ctx, requestSummary, resp, forCall) |
| 1923 |
|
| 1924 |
default: |
| 1925 |
resp.Body.Close() |
| 1926 |
return fmt.Errorf("%s: unsupported content type %q", requestSummary, contentType) |
| 1927 |
} |
| 1928 |
return nil |
| 1929 |
} |
| 1930 |
|
| 1931 |
func (c *streamableClientConn) setMCPHeaders(req *http.Request) error { |
| 1932 |
c.mu.Lock() |
| 1933 |
defer c.mu.Unlock() |
| 1934 |
|
| 1935 |
if c.oauthHandler != nil { |
| 1936 |
ts, err := c.oauthHandler.TokenSource(c.ctx) |
| 1937 |
if err != nil { |
| 1938 |
return err |
| 1939 |
} |
| 1940 |
if ts != nil { |
| 1941 |
token, err := ts.Token() |
| 1942 |
if err != nil { |
| 1943 |
return err |
| 1944 |
} |
| 1945 |
if token != nil { |
| 1946 |
req.Header.Set("Authorization", "Bearer "+token.AccessToken) |
| 1947 |
} |
| 1948 |
} |
| 1949 |
} |
| 1950 |
if c.initializedResult != nil { |
| 1951 |
req.Header.Set(protocolVersionHeader, c.initializedResult.ProtocolVersion) |
| 1952 |
} |
| 1953 |
if c.sessionID != "" { |
| 1954 |
req.Header.Set(sessionIDHeader, c.sessionID) |
| 1955 |
} |
| 1956 |
|
| 1957 |
return nil |
| 1958 |
} |
| 1959 |
|
| 1960 |
func (c *streamableClientConn) handleJSON(requestSummary string, resp *http.Response) { |
| 1961 |
body, err := io.ReadAll(resp.Body) |
| 1962 |
resp.Body.Close() |
| 1963 |
if err != nil { |
| 1964 |
c.fail(fmt.Errorf("%s: failed to read body: %v", requestSummary, err)) |
| 1965 |
return |
| 1966 |
} |
| 1967 |
msg, err := jsonrpc.DecodeMessage(body) |
| 1968 |
if err != nil { |
| 1969 |
c.fail(fmt.Errorf("%s: failed to decode response: %v", requestSummary, err)) |
| 1970 |
return |
| 1971 |
} |
| 1972 |
select { |
| 1973 |
case c.incoming <- msg: |
| 1974 |
case <-c.done: |
| 1975 |
|
| 1976 |
} |
| 1977 |
} |
| 1978 |
|
| 1979 |
|
| 1980 |
|
| 1981 |
|
| 1982 |
|
| 1983 |
|
| 1984 |
|
| 1985 |
func (c *streamableClientConn) handleSSE(ctx context.Context, requestSummary string, resp *http.Response, forCall *jsonrpc2.Request) { |
| 1986 |
|
| 1987 |
|
| 1988 |
|
| 1989 |
|
| 1990 |
var prevLastEventID string |
| 1991 |
retriesWithoutProgress := 0 |
| 1992 |
|
| 1993 |
for { |
| 1994 |
lastEventID, reconnectDelay, clientClosed := c.processStream(ctx, requestSummary, resp, forCall) |
| 1995 |
|
| 1996 |
|
| 1997 |
if clientClosed { |
| 1998 |
return |
| 1999 |
} |
| 2000 |
|
| 2001 |
|
| 2002 |
|
| 2003 |
if lastEventID == "" && forCall != nil { |
| 2004 |
return |
| 2005 |
} |
| 2006 |
|
| 2007 |
|
| 2008 |
|
| 2009 |
if lastEventID != "" && lastEventID != prevLastEventID { |
| 2010 |
|
| 2011 |
retriesWithoutProgress = 0 |
| 2012 |
prevLastEventID = lastEventID |
| 2013 |
} else { |
| 2014 |
|
| 2015 |
retriesWithoutProgress++ |
| 2016 |
if retriesWithoutProgress > c.maxRetries { |
| 2017 |
if ctx.Err() == nil { |
| 2018 |
c.fail(fmt.Errorf("%s: exceeded %d retries without progress (session ID: %v)", requestSummary, c.maxRetries, c.sessionID)) |
| 2019 |
} |
| 2020 |
return |
| 2021 |
} |
| 2022 |
} |
| 2023 |
|
| 2024 |
|
| 2025 |
newResp, err := c.connectSSE(ctx, lastEventID, reconnectDelay, false) |
| 2026 |
if err != nil { |
| 2027 |
|
| 2028 |
|
| 2029 |
if ctx.Err() == nil { |
| 2030 |
|
| 2031 |
c.fail(fmt.Errorf("%s: failed to reconnect (session ID: %v): %v", requestSummary, c.sessionID, err)) |
| 2032 |
} |
| 2033 |
return |
| 2034 |
} |
| 2035 |
|
| 2036 |
resp = newResp |
| 2037 |
if err := c.checkResponse(requestSummary, resp); err != nil { |
| 2038 |
c.fail(err) |
| 2039 |
return |
| 2040 |
} |
| 2041 |
} |
| 2042 |
} |
| 2043 |
|
| 2044 |
|
| 2045 |
|
| 2046 |
|
| 2047 |
|
| 2048 |
func (c *streamableClientConn) checkResponse(requestSummary string, resp *http.Response) (err error) { |
| 2049 |
defer func() { |
| 2050 |
if err != nil { |
| 2051 |
resp.Body.Close() |
| 2052 |
} |
| 2053 |
}() |
| 2054 |
r |
| 2055 |
|
| 2056 |
|
| 2057 |
if resp.StatusCode == http.StatusNotFound { |
| 2058 |
|
| 2059 |
|
| 2060 |
return fmt.Errorf("%s: failed to connect (session ID: %v): %w", requestSummary, c.sessionID, ErrSessionMissing) |
| 2061 |
} |
| 2062 |
|
| 2063 |
|
| 2064 |
if isTransientHTTPStatus(resp.StatusCode) { |
| 2065 |
return fmt.Errorf("%w: %s: %v", jsonrpc2.ErrRejected, requestSummary, http.StatusText(resp.StatusCode)) |
| 2066 |
} |
| 2067 |
if resp.StatusCode < 200 || resp.StatusCode >= 300 { |
| 2068 |
return fmt.Errorf("%s: %v", requestSummary, http.StatusText(resp.StatusCode)) |
| 2069 |
} |
| 2070 |
return nil |
| 2071 |
} |
| 2072 |
|
| 2073 |
|
| 2074 |
|
| 2075 |
|
| 2076 |
|
| 2077 |
func (c *streamableClientConn) processStream(ctx context.Context, requestSummary string, resp *http.Response, forCall *jsonrpc.Request) (lastEventID string, reconnectDelay time.Duration, clientClosed bool) { |
| 2078 |
defer func() { |
| 2079 |
|
| 2080 |
io.Copy(io.Discard, resp.Body) |
| 2081 |
resp.Body.Close() |
| 2082 |
}() |
| 2083 |
for evt, err := range scanEvents(resp.Body) { |
| 2084 |
if err != nil { |
| 2085 |
if ctx.Err() != nil { |
| 2086 |
return "", 0, true |
| 2087 |
} |
| 2088 |
|
| 2089 |
|
| 2090 |
|
| 2091 |
if errors.Is(err, errMalformedEvent) { |
| 2092 |
c.fail(fmt.Errorf("%s: %v", requestSummary, err)) |
| 2093 |
return "", 0, true |
| 2094 |
} |
| 2095 |
|
| 2096 |
break |
| 2097 |
} |
| 2098 |
|
| 2099 |
if evt.ID != "" { |
| 2100 |
lastEventID = evt.ID |
| 2101 |
} |
| 2102 |
|
| 2103 |
if evt.Retry != "" { |
| 2104 |
if n, err := strconv.ParseInt(evt.Retry, 10, 64); err == nil { |
| 2105 |
reconnectDelay = time.Duration(n) * time.Millisecond |
| 2106 |
} |
| 2107 |
} |
| 2108 |
|
| 2109 |
|
| 2110 |
|
| 2111 |
|
| 2112 |
|
| 2113 |
if len(evt.Data) == 0 { |
| 2114 |
continue |
| 2115 |
} |
| 2116 |
|
| 2117 |
|
| 2118 |
if evt.Name != "" && evt.Name != "message" { |
| 2119 |
continue |
| 2120 |
} |
| 2121 |
|
| 2122 |
msg, err := jsonrpc.DecodeMessage(evt.Data) |
| 2123 |
if err != nil { |
| 2124 |
c.fail(fmt.Errorf("%s: failed to decode event: %v", requestSummary, err)) |
| 2125 |
return "", 0, true |
| 2126 |
} |
| 2127 |
|
| 2128 |
select { |
| 2129 |
case c.incoming <- msg: |
| 2130 |
|
| 2131 |
|
| 2132 |
if jsonResp, ok := msg.(*jsonrpc.Response); ok && forCall != nil { |
| 2133 |
|
| 2134 |
|
| 2135 |
if jsonResp.ID == forCall.ID { |
| 2136 |
return "", 0, true |
| 2137 |
} |
| 2138 |
} |
| 2139 |
|
| 2140 |
case <-c.done: |
| 2141 |
|
| 2142 |
return "", 0, true |
| 2143 |
} |
| 2144 |
} |
| 2145 |
|
| 2146 |
|
| 2147 |
|
| 2148 |
|
| 2149 |
|
| 2150 |
|
| 2151 |
|
| 2152 |
if lastEventID == "" && forCall != nil { |
| 2153 |
errmsg := &jsonrpc2.Response{ |
| 2154 |
ID: forCall.ID, |
| 2155 |
Error: fmt.Errorf("request terminated without response"), |
| 2156 |
} |
| 2157 |
select { |
| 2158 |
case c.incoming <- errmsg: |
| 2159 |
case <-c.done: |
| 2160 |
} |
| 2161 |
} |
| 2162 |
return lastEventID, reconnectDelay, false |
| 2163 |
} |
| 2164 |
|
| 2165 |
|
| 2166 |
|
| 2167 |
|
| 2168 |
|
| 2169 |
|
| 2170 |
|
| 2171 |
|
| 2172 |
|
| 2173 |
|
| 2174 |
|
| 2175 |
|
| 2176 |
|
| 2177 |
|
| 2178 |
|
| 2179 |
func (c *streamableClientConn) connectSSE(ctx context.Context, lastEventID string, reconnectDelay time.Duration, initial bool) (*http.Response, error) { |
| 2180 |
var finalErr error |
| 2181 |
attempt := 0 |
| 2182 |
if !initial { |
| 2183 |
|
| 2184 |
|
| 2185 |
|
| 2186 |
|
| 2187 |
|
| 2188 |
|
| 2189 |
attempt = 1 |
| 2190 |
} |
| 2191 |
delay := calculateReconnectDelay(attempt) |
| 2192 |
if reconnectDelay > 0 { |
| 2193 |
delay = reconnectDelay |
| 2194 |
} |
| 2195 |
for ; attempt <= c.maxRetries; attempt++ { |
| 2196 |
select { |
| 2197 |
case <-c.done: |
| 2198 |
return nil, fmt.Errorf("connection closed by client during reconnect") |
| 2199 |
|
| 2200 |
case <-ctx.Done(): |
| 2201 |
|
| 2202 |
|
| 2203 |
return nil, ctx.Err() |
| 2204 |
|
| 2205 |
case <-time.After(delay): |
| 2206 |
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.url, nil) |
| 2207 |
if err != nil { |
| 2208 |
return nil, err |
| 2209 |
} |
| 2210 |
if err := c.setMCPHeaders(req); err != nil { |
| 2211 |
return nil, err |
| 2212 |
} |
| 2213 |
if lastEventID != "" { |
| 2214 |
req.Header.Set(lastEventIDHeader, lastEventID) |
| 2215 |
} |
| 2216 |
req.Header.Set("Accept", "text/event-stream") |
| 2217 |
resp, err := c.client.Do(req) |
| 2218 |
if err != nil { |
| 2219 |
finalErr = err |
| 2220 |
delay = calculateReconnectDelay(attempt + 1) |
| 2221 |
continue |
| 2222 |
} |
| 2223 |
return resp, nil |
| 2224 |
} |
| 2225 |
} |
| 2226 |
|
| 2227 |
if finalErr != nil { |
| 2228 |
return nil, fmt.Errorf("connection failed after %d attempts: %w", c.maxRetries, finalErr) |
| 2229 |
} |
| 2230 |
return nil, fmt.Errorf("connection aborted after %d attempts", c.maxRetries) |
| 2231 |
} |
| 2232 |
|
| 2233 |
|
| 2234 |
func (c *streamableClientConn) Close() error { |
| 2235 |
c.closeOnce.Do(func() { |
| 2236 |
if errors.Is(c.failure(), ErrSessionMissing) { |
| 2237 |
|
| 2238 |
} else { |
| 2239 |
req, err := http.NewRequestWithContext(c.ctx, http.MethodDelete, c.url, nil) |
| 2240 |
if err != nil { |
| 2241 |
c.closeErr = err |
| 2242 |
} else { |
| 2243 |
if err := c.setMCPHeaders(req); err != nil { |
| 2244 |
c.closeErr = err |
| 2245 |
} else if _, err := c.client.Do(req); err != nil { |
| 2246 |
c.closeErr = err |
| 2247 |
} |
| 2248 |
} |
| 2249 |
} |
| 2250 |
|
| 2251 |
|
| 2252 |
c.cancel() |
| 2253 |
close(c.done) |
| 2254 |
}) |
| 2255 |
return c.closeErr |
| 2256 |
} |
| 2257 |
|
| 2258 |
|
| 2259 |
func calculateReconnectDelay(attempt int) time.Duration { |
| 2260 |
if attempt == 0 { |
| 2261 |
return 0 |
| 2262 |
} |
| 2263 |
|
| 2264 |
backoffDuration := time.Duration(float64(reconnectInitialDelay.Load()) * math.Pow(reconnectGrowFactor, float64(attempt-1))) |
| 2265 |
|
| 2266 |
backoffDuration = min(backoffDuration, reconnectMaxDelay) |
| 2267 |
|
| 2268 |
|
| 2269 |
jitter := rand.N(backoffDuration) |
| 2270 |
|
| 2271 |
return backoffDuration + jitter |
| 2272 |
} |
| 2273 |
|
| 2274 |
|
| 2275 |
|
| 2276 |
func isTransientHTTPStatus(statusCode int) bool { |
| 2277 |
switch statusCode { |
| 2278 |
case http.StatusInternalServerError, |
| 2279 |
http.StatusBadGateway, |
| 2280 |
http.StatusServiceUnavailable, |
| 2281 |
http.StatusGatewayTimeout, |
| 2282 |
http.StatusTooManyRequests: |
| 2283 |
return true |
| 2284 |
} |
| 2285 |
return false |
| 2286 |
} |