Repository navigation
Expand file tree
/
Copy pathstreamable_http.go
More file actions
826 lines (718 loc) · 24.5 KB
/
Copy pathstreamable_http.go
File metadata and controls
826 lines (718 loc) · 24.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
package transport
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/util"
)
type StreamableHTTPCOption func(*StreamableHTTP)
// WithContinuousListening enables receiving server-to-client notifications when no request is in flight.
// In particular, if you want to receive global notifications from the server (like ToolListChangedNotification),
// you should enable this option.
//
// It will establish a standalone long-live GET HTTP connection to the server.
// https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#listening-for-messages-from-the-server
// NOTICE: Even enabled, the server may not support this feature.
func WithContinuousListening() StreamableHTTPCOption {
return func(sc *StreamableHTTP) {
sc.getListeningEnabled = true
}
}
// WithHTTPClient sets a custom HTTP client on the StreamableHTTP transport.
func WithHTTPBasicClient(client *http.Client) StreamableHTTPCOption {
return func(sc *StreamableHTTP) {
sc.httpClient = client
}
}
func WithHTTPHeaders(headers map[string]string) StreamableHTTPCOption {
return func(sc *StreamableHTTP) {
sc.headers = headers
}
}
func WithHTTPHeaderFunc(headerFunc HTTPHeaderFunc) StreamableHTTPCOption {
return func(sc *StreamableHTTP) {
sc.headerFunc = headerFunc
}
}
// WithHTTPTimeout sets the timeout for a HTTP request and stream.
func WithHTTPTimeout(timeout time.Duration) StreamableHTTPCOption {
return func(sc *StreamableHTTP) {
sc.httpClient.Timeout = timeout
}
}
// WithHTTPOAuth enables OAuth authentication for the client.
func WithHTTPOAuth(config OAuthConfig) StreamableHTTPCOption {
return func(sc *StreamableHTTP) {
sc.oauthHandler = NewOAuthHandler(config)
}
}
// WithHTTPLogger sets a custom logger for the StreamableHTTP transport.
func WithHTTPLogger(logger util.Logger) StreamableHTTPCOption {
return func(sc *StreamableHTTP) {
sc.logger = logger
}
}
// Deprecated: Use [WithHTTPLogger] instead.
func WithLogger(logger util.Logger) StreamableHTTPCOption {
return WithHTTPLogger(logger)
}
// WithSession creates a client with a pre-configured session
func WithSession(sessionID string) StreamableHTTPCOption {
return func(sc *StreamableHTTP) {
sc.sessionID.Store(sessionID)
}
}
// WithStreamableHTTPHost sets a custom Host header for the StreamableHTTP client, enabling manual DNS resolution.
// This allows connecting to an IP address while sending a specific Host header to the server.
// For example, connecting to "http://192.168.1.100:8080/mcp" but sending Host: "api.example.com"
func WithStreamableHTTPHost(host string) StreamableHTTPCOption {
return func(sc *StreamableHTTP) {
sc.host = host
}
}
// StreamableHTTP implements Streamable HTTP transport.
//
// It transmits JSON-RPC messages over individual HTTP requests. One message per request.
// The HTTP response body can either be a single JSON-RPC response,
// or an upgraded SSE stream that concludes with a JSON-RPC response for the same request.
//
// https://modelcontextprotocol.io/specification/2025-03-26/basic/transports
//
// The current implementation does not support the following features:
// - resuming stream
// (https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#resumability-and-redelivery)
type StreamableHTTP struct {
serverURL *url.URL
httpClient *http.Client
headers map[string]string
headerFunc HTTPHeaderFunc
host string
logger util.Logger
getListeningEnabled bool
sessionID atomic.Value // string
protocolVersion atomic.Value // string
initialized chan struct{}
initializedOnce sync.Once
notificationHandler func(mcp.JSONRPCNotification)
notifyMu sync.RWMutex
// Request handler for incoming server-to-client requests (like sampling)
requestHandler RequestHandler
requestMu sync.RWMutex
closed chan struct{}
closeOnce sync.Once
// OAuth support
oauthHandler *OAuthHandler
}
// NewStreamableHTTP creates a new Streamable HTTP transport with the given server URL.
// Returns an error if the URL is invalid.
func NewStreamableHTTP(serverURL string, options ...StreamableHTTPCOption) (*StreamableHTTP, error) {
parsedURL, err := url.Parse(serverURL)
if err != nil {
return nil, fmt.Errorf("invalid URL: %w", err)
}
smc := &StreamableHTTP{
serverURL: parsedURL,
httpClient: &http.Client{},
headers: make(map[string]string),
closed: make(chan struct{}),
logger: util.DefaultLogger(),
initialized: make(chan struct{}),
}
smc.sessionID.Store("") // set initial value to simplify later usage
for _, opt := range options {
if opt != nil {
opt(smc)
}
}
// If OAuth is configured, set the base URL for metadata discovery
if smc.oauthHandler != nil {
discoveryURL := *parsedURL
discoveryURL.RawQuery = ""
discoveryURL.Fragment = ""
baseURL := discoveryURL.String()
smc.oauthHandler.SetBaseURL(baseURL)
}
return smc, nil
}
// Start initiates the HTTP connection to the server.
func (c *StreamableHTTP) Start(ctx context.Context) error {
// Start is idempotent - check if already initialized
select {
case <-c.initialized:
return nil
default:
}
// For Streamable HTTP, we don't need to establish a persistent connection by default
if c.getListeningEnabled {
go func() {
select {
case <-c.initialized:
ctx, cancel := c.contextAwareOfClientClose(ctx)
defer cancel()
c.listenForever(ctx)
case <-c.closed:
return
case <-ctx.Done():
return
}
}()
}
return nil
}
// Close closes the all the HTTP connections to the server.
func (c *StreamableHTTP) Close() error {
c.closeOnce.Do(func() {
// Cancel all in-flight requests
close(c.closed)
sessionId := c.sessionID.Load().(string)
if sessionId != "" {
c.sessionID.Store("")
// notify server session closed
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, c.serverURL.String(), nil)
if err != nil {
c.logger.Errorf("failed to create close request: %v", err)
return
}
req.Header.Set(HeaderKeySessionID, sessionId)
// Set protocol version header if negotiated
if v := c.protocolVersion.Load(); v != nil {
if version, ok := v.(string); ok && version != "" {
req.Header.Set(HeaderKeyProtocolVersion, version)
}
}
// Set custom Host header if provided
if c.host != "" {
req.Host = c.host
}
res, err := c.httpClient.Do(req)
if err != nil {
c.logger.Errorf("failed to send close request: %v", err)
return
}
res.Body.Close()
}
})
return nil
}
// SetProtocolVersion sets the negotiated protocol version for this connection.
func (c *StreamableHTTP) SetProtocolVersion(version string) {
c.protocolVersion.Store(version)
}
// ErrOAuthAuthorizationRequired is a sentinel error for OAuth authorization required
var ErrOAuthAuthorizationRequired = errors.New("no valid token available, authorization required")
// OAuthAuthorizationRequiredError is returned when OAuth authorization is required
type OAuthAuthorizationRequiredError struct {
Handler *OAuthHandler
}
func (e *OAuthAuthorizationRequiredError) Error() string {
return ErrOAuthAuthorizationRequired.Error()
}
func (e *OAuthAuthorizationRequiredError) Unwrap() error {
return ErrOAuthAuthorizationRequired
}
// SendRequest sends a JSON-RPC request to the server and waits for a response.
// Returns the raw JSON response message or an error if the request fails.
func (c *StreamableHTTP) SendRequest(
ctx context.Context,
request JSONRPCRequest,
) (*JSONRPCResponse, error) {
// Marshal request
requestBody, err := json.Marshal(request)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
ctx, cancel := c.contextAwareOfClientClose(ctx)
resp, err := c.sendHTTP(ctx, http.MethodPost, bytes.NewReader(requestBody), "application/json, text/event-stream", request.Header)
if err != nil {
cancel()
if errors.Is(err, ErrSessionTerminated) && request.Method == string(mcp.MethodInitialize) {
// Per the MCP spec's backwards compatibility section: a 404 on an
// initialize POST means the server likely only supports legacy SSE.
return nil, ErrLegacySSEServer
}
return nil, fmt.Errorf("failed to send request: %w", err)
}
// Only proceed if we have a valid response.
if resp == nil {
cancel()
return nil, fmt.Errorf("failed to send request: no response received")
}
// Cancel the context before closing the body. On HTTP/2, Close() blocks in a
// select on cs.donec (stream cleanup) or cs.ctx.Done() (context cancellation).
// If cc.wmu is contended, cs.donec may never close, making ctx.Done() the only
// exit path. Canceling first guarantees Close() returns promptly.
defer func() { cancel(); resp.Body.Close() }()
// Check if we got an error response
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted {
// Handle unauthorized error
if resp.StatusCode == http.StatusUnauthorized {
if c.oauthHandler != nil {
return nil, &OAuthAuthorizationRequiredError{
Handler: c.oauthHandler,
}
}
return nil, ErrUnauthorized
}
// Per the MCP spec's backwards compatibility section: if an initialize
// POST receives an HTTP 4xx (e.g. 405 Method Not Allowed, 404 Not Found),
// the server likely only supports the legacy HTTP+SSE transport.
if request.Method == string(mcp.MethodInitialize) && resp.StatusCode >= 400 && resp.StatusCode < 500 {
return nil, ErrLegacySSEServer
}
// handle error response
var errResponse JSONRPCResponse
body, _ := io.ReadAll(resp.Body)
if err := json.Unmarshal(body, &errResponse); err == nil {
return &errResponse, nil
}
return nil, fmt.Errorf("request failed with status %d: %s", resp.StatusCode, body)
}
if request.Method == string(mcp.MethodInitialize) {
// saved the received session ID in the response
// empty session ID is allowed
if sessionID := resp.Header.Get(HeaderKeySessionID); sessionID != "" {
c.sessionID.Store(sessionID)
}
c.initializedOnce.Do(func() {
close(c.initialized)
})
}
// Handle different response types
mediaType, _, _ := mime.ParseMediaType(resp.Header.Get("Content-Type"))
switch mediaType {
case "application/json":
// Single response
var response JSONRPCResponse
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
}
// should not be a notification
if response.ID.IsNil() {
return nil, fmt.Errorf("response should contain RPC id: %v", response)
}
return &response, nil
case "text/event-stream":
// Server is using SSE for streaming responses
return c.handleSSEResponse(ctx, resp.Body, false)
default:
return nil, fmt.Errorf("unexpected content type: %s", resp.Header.Get("Content-Type"))
}
}
func (c *StreamableHTTP) sendHTTP(
ctx context.Context,
method string,
body io.Reader,
acceptType string,
header http.Header,
) (resp *http.Response, err error) {
// Create HTTP request
req, err := http.NewRequestWithContext(ctx, method, c.serverURL.String(), body)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
// request headers
if header != nil {
req.Header = header
}
// Set headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", acceptType)
sessionID := c.sessionID.Load().(string)
if sessionID != "" {
req.Header.Set(HeaderKeySessionID, sessionID)
}
// Set protocol version header if negotiated
if v := c.protocolVersion.Load(); v != nil {
if version, ok := v.(string); ok && version != "" {
req.Header.Set(HeaderKeyProtocolVersion, version)
}
}
for k, v := range c.headers {
req.Header.Set(k, v)
}
// Set custom Host header if provided
if c.host != "" {
req.Host = c.host
}
// Add OAuth authorization if configured
if c.oauthHandler != nil {
authHeader, err := c.oauthHandler.GetAuthorizationHeader(ctx)
if err != nil {
// If we get an authorization error, return a specific error that can be handled by the client
if errors.Is(err, ErrOAuthAuthorizationRequired) {
return nil, &OAuthAuthorizationRequiredError{
Handler: c.oauthHandler,
}
}
return nil, fmt.Errorf("failed to get authorization header: %w", err)
}
req.Header.Set("Authorization", authHeader)
}
if c.headerFunc != nil {
for k, v := range c.headerFunc(ctx) {
req.Header.Set(k, v)
}
}
// Send request
resp, err = c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
// universal handling for session terminated
if resp.StatusCode == http.StatusNotFound {
c.sessionID.CompareAndSwap(sessionID, "")
return nil, ErrSessionTerminated
}
return resp, nil
}
// handleSSEResponse processes an SSE stream for a specific request.
// It returns the final result for the request once received, or an error.
// If ignoreResponse is true, it won't return when a response messge is received. This is for continuous listening.
func (c *StreamableHTTP) handleSSEResponse(ctx context.Context, reader io.ReadCloser, ignoreResponse bool) (*JSONRPCResponse, error) {
// Create a channel for this specific request
responseChan := make(chan *JSONRPCResponse, 1)
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// Start a goroutine to process the SSE stream
go func() {
// Ensure this goroutine respects the context
defer close(responseChan)
c.readSSE(ctx, reader, func(event, data string) {
// Try to unmarshal as a response first
var message JSONRPCResponse
if err := json.Unmarshal([]byte(data), &message); err != nil {
c.logger.Infof("failed to unmarshal message (non-fatal): %v", err, "message", data)
return
}
// Handle notification
if message.ID.IsNil() {
var notification mcp.JSONRPCNotification
if err := json.Unmarshal([]byte(data), ¬ification); err != nil {
c.logger.Errorf("failed to unmarshal notification: %v", err)
return
}
c.notifyMu.RLock()
if c.notificationHandler != nil {
c.notificationHandler(notification)
}
c.notifyMu.RUnlock()
return
}
// Check if this is actually a request from the server by looking for method field
var rawMessage map[string]json.RawMessage
if err := json.Unmarshal([]byte(data), &rawMessage); err == nil {
if _, hasMethod := rawMessage["method"]; hasMethod && !message.ID.IsNil() {
var request JSONRPCRequest
if err := json.Unmarshal([]byte(data), &request); err == nil {
// This is a request from the server
c.handleIncomingRequest(ctx, request)
return
}
}
}
if !ignoreResponse {
responseChan <- &message
}
})
}()
// Wait for the response or context cancellation
select {
case response := <-responseChan:
if response == nil {
return nil, fmt.Errorf("unexpected nil response")
}
return response, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
// readSSE reads the SSE stream(reader) and calls the handler for each event and data pair.
// It will end when the reader is closed (or the context is done).
//
// A background goroutine closes the reader when ctx is cancelled, which unblocks
// any in-progress ReadString call. This is necessary because ReadString is blocking
// I/O that does not respect context cancellation on its own.
func (c *StreamableHTTP) readSSE(ctx context.Context, reader io.ReadCloser, handler func(event, data string)) {
// Close the reader when context is cancelled to interrupt blocking reads.
// This ensures ReadString returns immediately with an error instead of
// blocking indefinitely when the SSE stream is open but idle.
go func() {
<-ctx.Done()
reader.Close()
}()
br := bufio.NewReader(reader)
var event, data string
for {
line, err := br.ReadString('\n')
if err != nil {
// Context was cancelled — reader was closed by the goroutine above.
if ctx.Err() != nil {
return
}
if err == io.EOF {
// Process any pending event before exit
if data != "" {
if event == "" {
event = "message"
}
handler(event, data)
}
return
}
c.logger.Errorf("SSE stream error: %v", err)
return
}
// Remove only newline markers
line = strings.TrimRight(line, "\r\n")
if line == "" {
// Empty line means end of event
if data != "" {
if event == "" {
event = "message"
}
handler(event, data)
event = ""
data = ""
}
continue
}
if eventStr, ok := strings.CutPrefix(line, "event:"); ok {
event = strings.TrimSpace(eventStr)
} else if dataStr, ok := strings.CutPrefix(line, "data:"); ok {
data = strings.TrimSpace(dataStr)
}
}
}
func (c *StreamableHTTP) SendNotification(ctx context.Context, notification mcp.JSONRPCNotification) error {
// Marshal request
requestBody, err := json.Marshal(notification)
if err != nil {
return fmt.Errorf("failed to marshal notification: %w", err)
}
// Create HTTP request
ctx, cancel := c.contextAwareOfClientClose(ctx)
resp, err := c.sendHTTP(ctx, http.MethodPost, bytes.NewReader(requestBody), "application/json, text/event-stream", nil)
if err != nil {
cancel()
return fmt.Errorf("failed to send request: %w", err)
}
defer func() { cancel(); resp.Body.Close() }()
switch resp.StatusCode {
case http.StatusOK, http.StatusAccepted, http.StatusNoContent:
return nil
case http.StatusUnauthorized:
if c.oauthHandler != nil {
return &OAuthAuthorizationRequiredError{
Handler: c.oauthHandler,
}
}
return ErrUnauthorized
default:
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf(
"notification failed with status %d: %s",
resp.StatusCode,
body,
)
}
}
func (c *StreamableHTTP) SetNotificationHandler(handler func(mcp.JSONRPCNotification)) {
c.notifyMu.Lock()
defer c.notifyMu.Unlock()
c.notificationHandler = handler
}
// SetRequestHandler sets the handler for incoming requests from the server.
func (c *StreamableHTTP) SetRequestHandler(handler RequestHandler) {
c.requestMu.Lock()
defer c.requestMu.Unlock()
c.requestHandler = handler
}
func (c *StreamableHTTP) GetSessionId() string {
return c.sessionID.Load().(string)
}
// GetOAuthHandler returns the OAuth handler if configured
func (c *StreamableHTTP) GetOAuthHandler() *OAuthHandler {
return c.oauthHandler
}
// IsOAuthEnabled returns true if OAuth is enabled
func (c *StreamableHTTP) IsOAuthEnabled() bool {
return c.oauthHandler != nil
}
func (c *StreamableHTTP) listenForever(ctx context.Context) {
c.logger.Infof("listening to server forever")
for {
// Use the original context for continuous listening - no per-iteration timeout
// The SSE connection itself will detect disconnections via the underlying HTTP transport,
// and the context cancellation will propagate from the parent to stop listening gracefully.
// We don't add an artificial timeout here because:
// 1. Persistent SSE connections are meant to stay open indefinitely
// 2. Network-level timeouts and keep-alives handle connection health
// 3. Context cancellation (user-initiated or system shutdown) provides clean shutdown
err := c.createGETConnectionToServer(ctx)
if errors.Is(err, ErrGetMethodNotAllowed) {
// server does not support listening
c.logger.Errorf("server does not support listening")
return
}
select {
case <-ctx.Done():
return
default:
}
if err != nil {
c.logger.Errorf("failed to listen to server. retry in 1 second: %v", err)
}
// Use context-aware sleep
select {
case <-time.After(retryInterval):
case <-ctx.Done():
return
}
}
}
var (
ErrSessionTerminated = fmt.Errorf("session terminated (404). need to re-initialize")
ErrGetMethodNotAllowed = fmt.Errorf("GET method not allowed")
ErrUnauthorized = fmt.Errorf("unauthorized (401)")
ErrLegacySSEServer = fmt.Errorf("server returned 4xx for initialize POST, likely a legacy SSE server")
retryInterval = 1 * time.Second // a variable is convenient for testing
)
func (c *StreamableHTTP) createGETConnectionToServer(ctx context.Context) error {
resp, err := c.sendHTTP(ctx, http.MethodGet, nil, "text/event-stream", nil)
if err != nil {
return fmt.Errorf("failed to send request: %w", err)
}
// Cancel the context before closing the body to prevent HTTP/2 drain hangs,
// matching the pattern used in SendRequest and SendNotification.
defer func() { resp.Body.Close() }()
// Check if we got an error response
if resp.StatusCode == http.StatusMethodNotAllowed {
return ErrGetMethodNotAllowed
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("request failed with status %d: %s", resp.StatusCode, body)
}
// handle SSE response
contentType := resp.Header.Get("Content-Type")
if contentType != "text/event-stream" {
return fmt.Errorf("unexpected content type: %s", contentType)
}
// When ignoreResponse is true, the function will never return expect context is done.
// NOTICE: Due to the ambiguity of the specification, other SDKs may use the GET connection to transfer the response
// messages. To be more compatible, we should handle this response, however, as the transport layer is message-based,
// currently, there is no convenient way to handle this response.
// So we ignore the response here. It's not a bug, but may be not compatible with other SDKs.
_, err = c.handleSSEResponse(ctx, resp.Body, true)
if err != nil {
return fmt.Errorf("failed to handle SSE response: %w", err)
}
return nil
}
// handleIncomingRequest processes requests from the server (like sampling requests)
func (c *StreamableHTTP) handleIncomingRequest(ctx context.Context, request JSONRPCRequest) {
c.requestMu.RLock()
handler := c.requestHandler
c.requestMu.RUnlock()
if handler == nil {
c.logger.Errorf("received request from server but no handler set: %s", request.Method)
// Send method not found error
errorResponse := NewJSONRPCErrorResponse(
request.ID,
mcp.METHOD_NOT_FOUND,
fmt.Sprintf("no handler configured for method: %s", request.Method),
nil,
)
c.sendResponseToServer(ctx, errorResponse)
return
}
// Handle the request in a goroutine to avoid blocking the SSE reader
go func() {
// Create a new context with timeout for request handling, respecting parent context
requestCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
response, err := handler(requestCtx, request)
if err != nil {
c.logger.Errorf("error handling request %s: %v", request.Method, err)
// Determine appropriate JSON-RPC error code based on error type
var errorCode int
var errorMessage string
// Check for specific sampling-related errors
if errors.Is(err, context.Canceled) {
errorCode = mcp.REQUEST_INTERRUPTED
errorMessage = "request was cancelled"
} else if errors.Is(err, context.DeadlineExceeded) {
errorCode = mcp.REQUEST_INTERRUPTED
errorMessage = "request timed out"
} else {
// Generic error cases
switch request.Method {
case string(mcp.MethodSamplingCreateMessage):
errorCode = mcp.INTERNAL_ERROR
errorMessage = fmt.Sprintf("sampling request failed: %v", err)
default:
errorCode = mcp.INTERNAL_ERROR
errorMessage = err.Error()
}
}
// Send error response
errorResponse := NewJSONRPCErrorResponse(request.ID, errorCode, errorMessage, nil)
c.sendResponseToServer(requestCtx, errorResponse)
return
}
if response != nil {
c.sendResponseToServer(requestCtx, response)
}
}()
}
// sendResponseToServer sends a response back to the server via HTTP POST
func (c *StreamableHTTP) sendResponseToServer(ctx context.Context, response *JSONRPCResponse) {
if response == nil {
c.logger.Errorf("cannot send nil response to server")
return
}
responseBody, err := json.Marshal(response)
if err != nil {
c.logger.Errorf("failed to marshal response: %v", err)
return
}
ctx, cancel := c.contextAwareOfClientClose(ctx)
resp, err := c.sendHTTP(ctx, http.MethodPost, bytes.NewReader(responseBody), "application/json, text/event-stream", nil)
if err != nil {
cancel()
c.logger.Errorf("failed to send response to server: %v", err)
return
}
defer func() { cancel(); resp.Body.Close() }()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted {
body, _ := io.ReadAll(resp.Body)
c.logger.Errorf("server rejected response with status %d: %s", resp.StatusCode, body)
}
}
func (c *StreamableHTTP) contextAwareOfClientClose(ctx context.Context) (context.Context, context.CancelFunc) {
newCtx, cancel := context.WithCancel(ctx)
go func() {
select {
case <-c.closed:
cancel()
case <-newCtx.Done():
// The original context was canceled
cancel()
}
}()
return newCtx, cancel
}