-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathsse_server.go
More file actions
1719 lines (1482 loc) · 53.2 KB
/
Copy pathsse_server.go
File metadata and controls
1719 lines (1482 loc) · 53.2 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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Tencent is pleased to support the open source community by making trpc-mcp-go available.
//
// Copyright (C) 2025 Tencent. All rights reserved.
//
// trpc-mcp-go is licensed under the Apache License Version 2.0.
package mcp
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/google/uuid"
icontext "trpc.group/trpc-go/trpc-mcp-go/internal/context"
)
// SessionIDGenerator defines an interface for generating custom session IDs.
type SessionIDGenerator interface {
// GenerateSessionID generates a session ID based on the HTTP request.
// This allows implementations to include client IP, port, headers, etc.
GenerateSessionID(r *http.Request) string
}
// defaultSessionIDGenerator is the default implementation that generates
// UUID-based session IDs following the same pattern as trpc-agent-go.
type defaultSessionIDGenerator struct{}
// GenerateSessionID generates a UUID-based session ID.
func (g *defaultSessionIDGenerator) GenerateSessionID(r *http.Request) string {
return fmt.Sprintf("sse-%s", uuid.New().String())
}
// sseSession represents an active SSE connection.
type sseSession struct {
done chan struct{} // Channel for signaling when the session is done.
eventQueue chan string // Queue for events to be sent.
sessionID string // Session identifier.
notificationChannel chan *JSONRPCNotification // Channel for notifications.
initialized atomic.Bool // Whether the session has been initialized.
writeMu sync.Mutex // Write mutex to prevent concurrent writes.
createdAt time.Time // Session creation time.
lastActivity time.Time // Last activity time.
data map[string]interface{} // Session data.
dataMu sync.RWMutex // Data mutex.
}
// sseStream wraps the components required to write SSE responses safely.
type sseStream struct {
logger Logger
writer http.ResponseWriter
flusher http.Flusher
mu *sync.Mutex
}
// serializedRequest contains all necessary information to process an HTTP
// request on a remote node when using a distributed SessionPubSub.
// It intentionally mirrors the structure used in the internal mcp-go project
// to maximize cross-project compatibility for multi-node deployments.
type serializedRequest struct {
Method string `json:"method"`
URL string `json:"url"`
Headers map[string][]string `json:"headers"`
Body []byte `json:"body"`
RemoteAddr string `json:"remote_addr,omitempty"`
Query url.Values `json:"query"`
Deadline *time.Time `json:"deadline,omitempty"`
}
// SessionID returns the session ID.
func (s *sseSession) SessionID() string {
return s.sessionID
}
// GetID returns the session ID (alias for SessionID for compatibility).
func (s *sseSession) GetID() string {
return s.sessionID
}
// GetCreatedAt returns the session creation time.
func (s *sseSession) GetCreatedAt() time.Time {
return s.createdAt
}
// GetLastActivity returns the last activity time.
func (s *sseSession) GetLastActivity() time.Time {
s.dataMu.RLock()
defer s.dataMu.RUnlock()
return s.lastActivity
}
// UpdateActivity updates the last activity time.
func (s *sseSession) UpdateActivity() {
s.dataMu.Lock()
defer s.dataMu.Unlock()
s.lastActivity = time.Now()
}
// GetData gets session data.
func (s *sseSession) GetData(key string) (interface{}, bool) {
s.dataMu.RLock()
defer s.dataMu.RUnlock()
if s.data == nil {
return nil, false
}
value, ok := s.data[key]
return value, ok
}
// SetData sets session data.
func (s *sseSession) SetData(key string, value interface{}) {
s.dataMu.Lock()
defer s.dataMu.Unlock()
if s.data == nil {
s.data = make(map[string]interface{})
}
s.data[key] = value
}
// Initialize marks the session as initialized.
func (s *sseSession) Initialize() {
s.initialized.Store(true)
}
// Initialized returns whether the session has been initialized.
func (s *sseSession) Initialized() bool {
return s.initialized.Load()
}
// NotificationChannel returns the notification channel.
func (s *sseSession) NotificationChannel() chan<- *JSONRPCNotification {
return s.notificationChannel
}
// jsonRPCEnvelope is a common structure for parsing JSON-RPC messages.
// It's used to avoid duplicate anonymous struct definitions across functions
// and can handle both success and error responses.
type jsonRPCEnvelope struct {
JSONRPC string `json:"jsonrpc"`
ID interface{} `json:"id"`
Result json.RawMessage `json:"result,omitempty"`
Error json.RawMessage `json:"error,omitempty"`
Method string `json:"method,omitempty"`
}
// SSEServer implements a Server-Sent Events (SSE) based MCP server.
type SSEServer struct {
mcpHandler *mcpHandler // MCP handler.
toolManager *toolManager // Tool manager.
resourceManager *resourceManager // Resource manager.
promptManager *promptManager // Prompt manager.
serverInfo Implementation // Server information.
basePath string // Base path for the server (e.g., "/mcp").
messageEndpoint string // Path for the message endpoint (e.g., "/message").
sseEndpoint string // Path for the SSE endpoint (e.g., "/sse").
sessions sync.Map // Active sessions.
httpServer *http.Server // HTTP server.
contextFunc func(ctx context.Context, r *http.Request) context.Context // HTTP context function.
sessionIDGenerator SessionIDGenerator // Custom session ID generator.
sessionPubSub SessionPubSub // Optional session Pub/Sub for distributed sessions.
keepAlive bool // Whether to keep the connection alive.
keepAliveInterval time.Duration // Keep-alive interval.
logger Logger // Logger for this server.
requestID atomic.Int64 // Request ID counter for generating unique request IDs.
responses map[uint64]interface{} // Map for storing response channels.
responsesMu sync.RWMutex // Mutex for responses map.
notificationHandlers map[string]ServerNotificationHandler // Map of notification handlers by method name.
notificationMu sync.RWMutex // Mutex for notification handlers map.
}
// SSEOption defines a function type for configuring the SSE server.
type SSEOption func(*SSEServer)
// SessionMessageHandler handles messages delivered via a SessionPubSub
// implementation for a specific session ID.
type SessionMessageHandler func(ctx context.Context, sessionID string, payload []byte) error
// SessionPubSub defines an interface for distributed session messaging.
// Implementations can be backed by Redis, message queues, or any other
// Pub/Sub mechanism. The payload is transport-agnostic and typically a
// JSON-encoded serializedRequest.
type SessionPubSub interface {
Publish(ctx context.Context, sessionID string, payload []byte) error
Subscribe(ctx context.Context, sessionID string, handler SessionMessageHandler) error
Unsubscribe(ctx context.Context, sessionID string) error
}
// NewSSEServer creates a new SSE server for MCP communication.
func NewSSEServer(name, version string, opts ...SSEOption) *SSEServer {
// Create server info.
serverInfo := Implementation{
Name: name,
Version: version,
}
// Create managers.
toolManager := newToolManager()
resourceManager := newResourceManager()
promptManager := newPromptManager()
lifecycleManager := newLifecycleManager(serverInfo)
// Set up manager relationships.
lifecycleManager.withToolManager(toolManager)
lifecycleManager.withResourceManager(resourceManager)
lifecycleManager.withPromptManager(promptManager)
// Create MCP handler.
mcpHandler := newMCPHandler(
withToolManager(toolManager),
withLifecycleManager(lifecycleManager),
withResourceManager(resourceManager),
withPromptManager(promptManager),
)
s := &SSEServer{
mcpHandler: mcpHandler,
toolManager: toolManager,
resourceManager: resourceManager,
promptManager: promptManager,
serverInfo: serverInfo,
sseEndpoint: "/sse",
messageEndpoint: "/message",
sessionIDGenerator: &defaultSessionIDGenerator{}, // Default session ID generator
keepAlive: true,
keepAliveInterval: 30 * time.Second,
logger: GetDefaultLogger(),
responses: make(map[uint64]interface{}),
notificationHandlers: make(map[string]ServerNotificationHandler),
}
// Apply all options.
for _, opt := range opts {
opt(s)
}
// Set logger for lifecycle manager.
lifecycleManager.withLogger(s.logger)
return s
}
// WithBasePath sets the base path for the server.
func WithBasePath(basePath string) SSEOption {
return func(s *SSEServer) {
if !strings.HasPrefix(basePath, "/") {
basePath = "/" + basePath
}
s.basePath = strings.TrimSuffix(basePath, "/")
}
}
// WithSessionPubSub sets a SessionPubSub implementation to enable distributed
// session routing across multiple server nodes.
func WithSessionPubSub(pubSub SessionPubSub) SSEOption {
return func(s *SSEServer) {
s.sessionPubSub = pubSub
}
}
// WithMessageEndpoint sets the message endpoint path.
func WithMessageEndpoint(endpoint string) SSEOption {
return func(s *SSEServer) {
s.messageEndpoint = endpoint
}
}
// WithSSEEndpoint sets the SSE endpoint path.
func WithSSEEndpoint(endpoint string) SSEOption {
return func(s *SSEServer) {
s.sseEndpoint = endpoint
}
}
// WithHTTPServer sets the HTTP server instance.
func WithHTTPServer(srv *http.Server) SSEOption {
return func(s *SSEServer) {
s.httpServer = srv
}
}
// WithKeepAlive enables or disables keep-alive for SSE connections.
func WithKeepAlive(keepAlive bool) SSEOption {
return func(s *SSEServer) {
s.keepAlive = keepAlive
}
}
// WithKeepAliveInterval sets the interval for keep-alive messages.
func WithKeepAliveInterval(interval time.Duration) SSEOption {
return func(s *SSEServer) {
s.keepAliveInterval = interval
s.keepAlive = true
}
}
// WithSSEContextFunc sets a function to modify the context from the request.
func WithSSEContextFunc(fn func(ctx context.Context, r *http.Request) context.Context) SSEOption {
return func(s *SSEServer) {
s.contextFunc = fn
}
}
// WithSSEServerLogger sets the logger for the SSE server.
func WithSSEServerLogger(logger Logger) SSEOption {
return func(s *SSEServer) {
s.logger = logger
}
}
// WithSSEToolListFilter sets a tool list filter for the SSE server.
func WithSSEToolListFilter(filter ToolListFilter) SSEOption {
return func(s *SSEServer) {
s.toolManager.withToolListFilter(filter)
}
}
// WithSSEPromptListFilter sets a prompt list filter for the SSE server.
func WithSSEPromptListFilter(filter PromptListFilter) SSEOption {
return func(s *SSEServer) {
s.promptManager.withPromptListFilter(filter)
}
}
// WithSSEResourceListFilter sets a resource list filter for the SSE server.
func WithSSEResourceListFilter(filter ResourceListFilter) SSEOption {
return func(s *SSEServer) {
s.resourceManager.withResourceListFilter(filter)
}
}
// WithSSESessionIDGenerator sets a custom session ID generator for the SSE server.
// This allows users to customize session ID generation, for example, to include
// client IP and port information for load balancing node affinity.
func WithSSESessionIDGenerator(generator SessionIDGenerator) SSEOption {
return func(s *SSEServer) {
s.sessionIDGenerator = generator
}
}
// WithSSEMiddleware registers one or more middlewares to the SSE server.
// Middlewares are executed in the order they are provided.
// All middlewares must be configured at server creation time.
//
// Example:
//
// server := mcp.NewSSEServer("name", "1.0.0",
// mcp.WithSSEEndpoint("/sse"),
// mcp.WithSSEMiddleware(LoggingMiddleware, MetricsMiddleware),
// )
func WithSSEMiddleware(middlewares ...Middleware) SSEOption {
return func(s *SSEServer) {
for _, mw := range middlewares {
s.mcpHandler.use(mw)
}
}
}
// Start starts the SSE server on the given address.
func (s *SSEServer) Start(addr string) error {
return http.ListenAndServe(addr, s)
}
// Shutdown gracefully stops the SSE server.
func (s *SSEServer) Shutdown(ctx context.Context) error {
srv := s.httpServer
if srv != nil {
// Close all sessions.
s.sessions.Range(func(key, value interface{}) bool {
if session, ok := value.(*sseSession); ok {
closeSessionDone(s.logger, session)
}
s.sessions.Delete(key)
return true
})
return srv.Shutdown(ctx)
}
return nil
}
// getMessageEndpointForClient returns the message endpoint URL for a client.
// with the given session ID, using a relative path.
func (s *SSEServer) getMessageEndpointForClient(sessionID string) string {
endpoint := s.messageEndpoint
if !strings.HasPrefix(endpoint, "/") {
endpoint = "/" + endpoint
}
// Ensure the base path is properly formatted.
basePath := s.basePath
if basePath != "" && !strings.HasPrefix(basePath, "/") {
basePath = "/" + basePath
}
// Construct the relative path.
fullPath := basePath + endpoint
// Append session ID as a query parameter.
if strings.Contains(fullPath, "?") {
fullPath += "&sessionId=" + sessionID
} else {
fullPath += "?sessionId=" + sessionID
}
return fullPath
}
// trySubscribe registers the current server instance as a subscriber for the
// given session ID if a SessionPubSub implementation is configured.
func (s *SSEServer) trySubscribe(ctx context.Context, sessionID string) {
if s.sessionPubSub == nil {
return
}
if err := s.sessionPubSub.Subscribe(ctx, sessionID, s.handleSessionMessage); err != nil {
if s.logger != nil {
s.logger.Errorf("Failed to subscribe to session %s: %v", sessionID, err)
}
}
}
// tryUnsubscribe removes the subscription for the given session ID if a
// SessionPubSub implementation is configured.
func (s *SSEServer) tryUnsubscribe(ctx context.Context, sessionID string) {
if s.sessionPubSub == nil {
return
}
if err := s.sessionPubSub.Unsubscribe(ctx, sessionID); err != nil {
if s.logger != nil {
s.logger.Errorf("Failed to unsubscribe from session %s: %v", sessionID, err)
}
}
}
// handleSSE handles SSE connection requests.
func (s *SSEServer) handleSSE(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
s.logger.Errorf("Method not allowed: %s", r.Method)
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
flusher, ok := w.(http.Flusher)
if !ok {
s.logger.Errorf("Streaming not supported by client")
http.Error(w, "Streaming not supported", http.StatusInternalServerError)
return
}
// Set SSE headers and immediately flush.
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Access-Control-Allow-Origin", "*")
flusher.Flush()
// Create session.
sessionID := s.sessionIDGenerator.GenerateSessionID(r)
session := &sseSession{
done: make(chan struct{}),
eventQueue: make(chan string, 100),
sessionID: sessionID,
notificationChannel: make(chan *JSONRPCNotification, 100),
createdAt: time.Now(),
lastActivity: time.Now(),
data: make(map[string]interface{}),
}
s.sessions.Store(sessionID, session)
// Apply context function.
ctx := r.Context()
if s.contextFunc != nil {
ctx = s.contextFunc(ctx, r)
}
// Set server instance to context.
ctx = setServerToContext(ctx, s)
// Set session information to context.
ctx = setSessionToContext(ctx, session)
// Subscribe to distributed SessionPubSub if configured.
if s.sessionPubSub != nil {
s.trySubscribe(ctx, sessionID)
defer func() {
// Use a detached context with timeout to ensure unsubscribe has a chance
// to complete even if the request context is already canceled.
detached := icontext.WithoutCancel(context.Background())
unsubCtx, cancel := context.WithTimeout(detached, 5*time.Second)
defer cancel()
s.tryUnsubscribe(unsubCtx, sessionID)
}()
}
stream := &sseStream{
logger: s.logger,
writer: w,
flusher: flusher,
mu: &session.writeMu,
}
// Send endpoint event.
endpointURL := s.getMessageEndpointForClient(sessionID)
if !stream.SendEvent("endpoint", endpointURL) {
return
}
// Send initial connection message.
stream.SendComment("connection established")
// Start notification handler.
go handleNotifications(ctx, s.logger, w, flusher, session)
// Start event queue handler.
go handleEventQueue(ctx, s.logger, w, flusher, session)
// Start keep-alive handler.
if s.keepAlive {
go handleKeepAlive(ctx, s.logger, w, flusher, session, s.keepAliveInterval)
}
// Wait for connection to close.
select {
case <-ctx.Done():
s.logger.Debugf("Context cancelled for session %s", sessionID)
case <-r.Context().Done():
s.logger.Debugf("Request context cancelled for session %s", sessionID)
case <-session.done:
s.logger.Debugf("Session %s closed", sessionID)
}
// Clean up resources.
closeSessionDone(s.logger, session)
s.sessions.Delete(sessionID)
s.logger.Debugf("Cleaned up session %s", sessionID)
}
// closeSessionDone safely closes the session done channel with panic protection.
func closeSessionDone(logger Logger, session *sseSession) {
defer func() {
if r := recover(); r != nil && logger != nil {
logger.Errorf("Recovered from panic while closing session %s: %v", session.sessionID, r)
}
}()
if session != nil && session.done != nil {
close(session.done)
}
}
// safeFlush flushes the HTTP response writer with panic protection.
func safeFlush(logger Logger, flusher http.Flusher) {
defer func() {
if r := recover(); r != nil && logger != nil {
logger.Errorf("Recovered from panic while flushing SSE response: %v", r)
}
}()
if flusher != nil {
flusher.Flush()
}
}
// SendEvent sends an SSE event and returns whether it is successful.
func (s *sseStream) SendEvent(eventType, data string) bool {
s.mu.Lock()
defer s.mu.Unlock()
event := fmt.Sprintf("event: %s\ndata: %s\n\n", eventType, data)
if _, err := fmt.Fprint(s.writer, event); err != nil {
if s.logger != nil {
s.logger.Errorf("Error writing SSE event %s: %v", eventType, err)
}
return false
}
safeFlush(s.logger, s.flusher)
return true
}
// SendComment sends an SSE comment frame.
func (s *sseStream) SendComment(comment string) {
s.mu.Lock()
defer s.mu.Unlock()
fmt.Fprintf(s.writer, ": %s\n\n", comment)
safeFlush(s.logger, s.flusher)
}
// handleNotifications handles notification messages.
func handleNotifications(ctx context.Context, logger Logger, w http.ResponseWriter, flusher http.Flusher, session *sseSession) {
defer func() {
if r := recover(); r != nil && logger != nil {
logger.Errorf("Recovered from panic in SSE notification handler for session %s: %v", session.sessionID, r)
}
}()
for {
select {
case notification := <-session.notificationChannel:
data, err := json.Marshal(notification)
if err != nil {
logger.Errorf("Error serializing notification: %v", err)
continue
}
session.writeMu.Lock()
fmt.Fprintf(w, "event: message\ndata: %s\n\n", data)
safeFlush(logger, flusher)
session.writeMu.Unlock()
case <-session.done:
return
case <-ctx.Done():
if logger != nil {
logger.Debugf("Notification handler context done for session %s", session.sessionID)
}
return
}
}
}
// handleEventQueue handles event queue.
func handleEventQueue(ctx context.Context, logger Logger, w http.ResponseWriter, flusher http.Flusher, session *sseSession) {
defer func() {
if r := recover(); r != nil && logger != nil {
logger.Errorf("Recovered from panic in SSE event queue handler for session %s: %v", session.sessionID, r)
}
}()
for {
select {
case event := <-session.eventQueue:
session.writeMu.Lock()
fmt.Fprint(w, event)
safeFlush(logger, flusher)
session.writeMu.Unlock()
case <-session.done:
logger.Debugf("Event queue handler terminated for session %s", session.sessionID)
return
case <-ctx.Done():
if logger != nil {
logger.Debugf("Event queue handler context done for session %s", session.sessionID)
}
return
}
}
}
// handleKeepAlive handles keep-alive messages.
func handleKeepAlive(ctx context.Context, logger Logger, w http.ResponseWriter, flusher http.Flusher, session *sseSession, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
defer func() {
if r := recover(); r != nil && logger != nil {
logger.Errorf("Recovered from panic in SSE keepalive handler for session %s: %v", session.sessionID, r)
}
}()
for {
select {
case <-ticker.C:
session.writeMu.Lock()
fmt.Fprint(w, ": keepalive\n\n")
safeFlush(logger, flusher)
session.writeMu.Unlock()
case <-session.done:
logger.Debugf("Keepalive handler terminated for session %s", session.sessionID)
return
case <-ctx.Done():
if logger != nil {
logger.Debugf("Keepalive handler context done for session %s", session.sessionID)
}
return
}
}
}
// handleMessage handles client message requests.
func (s *SSEServer) handleMessage(w http.ResponseWriter, r *http.Request) {
// Check method.
if r.Method != http.MethodPost {
s.logger.Errorf("Invalid method for message endpoint: %s", r.Method)
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Get session from request.
session, err := s.getSessionFromRequest(r)
if err != nil {
// If the session is not found but a SessionPubSub is configured, try to
// publish the request to the node that owns the session.
if s.sessionPubSub != nil && errors.Is(err, ErrSessionNotFound) {
sessionID := r.URL.Query().Get("sessionId")
if sessionID == "" {
s.handleSessionError(w, err)
return
}
if err := s.tryPublish(r.Context(), sessionID, r); err != nil {
if s.logger != nil {
s.logger.Errorf("Failed to publish message for remote session %s: %v", sessionID, err)
}
s.handleSessionError(w, err)
return
}
// Successfully handed off to another node.
w.WriteHeader(http.StatusAccepted)
return
}
s.handleSessionError(w, err)
return
}
// Read and parse the raw message.
var rawMessage json.RawMessage
if err := json.NewDecoder(r.Body).Decode(&rawMessage); err != nil {
s.logger.Errorf("Error reading request body: %v", err)
s.writeJSONRPCError(w, nil, ErrCodeParse, "Parse error")
return
}
// Parse base message to determine type.
var base baseMessage
if err := json.Unmarshal(rawMessage, &base); err != nil {
s.logger.Errorf("Error parsing base message: %v", err)
s.writeJSONRPCError(w, nil, ErrCodeParse, "Invalid JSON-RPC message")
return
}
// Apply context function first.
ctx := r.Context()
if s.contextFunc != nil {
ctx = s.contextFunc(ctx, r)
}
// Create context with session.
ctx = s.createSessionContext(ctx, session)
// Immediately return HTTP 202 Accepted status code, indicating request has been received.
w.WriteHeader(http.StatusAccepted)
// Handle different message types based on presence of ID and Method.
if base.ID != nil && base.Method != "" {
// JSON-RPC Request (has both ID and Method).
s.handleRequestMessage(ctx, rawMessage, session)
} else if base.ID == nil && base.Method != "" {
// JSON-RPC Notification (has Method but no ID).
s.handleNotificationMessage(ctx, rawMessage, session)
} else if base.ID != nil && base.Method == "" {
// JSON-RPC Response (has ID but no Method) - like roots/list response.
s.handleResponseMessage(ctx, rawMessage, session)
} else {
// Invalid message format.
s.logger.Errorf("Invalid JSON-RPC message: missing required fields")
s.writeJSONRPCError(w, nil, ErrCodeInvalidRequest, "Invalid JSON-RPC message format")
return
}
}
// handleRequestMessage processes JSON-RPC requests.
func (s *SSEServer) handleRequestMessage(ctx context.Context, rawMessage json.RawMessage, session *sseSession) {
var request JSONRPCRequest
if err := json.Unmarshal(rawMessage, &request); err != nil {
s.logger.Errorf("Error parsing request: %v", err)
return
}
// Process request in background.
go s.processRequestAsync(ctx, &request, session)
}
// handleNotificationMessage processes JSON-RPC notifications.
func (s *SSEServer) handleNotificationMessage(ctx context.Context, rawMessage json.RawMessage, session *sseSession) {
var notification JSONRPCNotification
if err := json.Unmarshal(rawMessage, ¬ification); err != nil {
s.logger.Errorf("Error parsing notification: %v", err)
return
}
// Handle notification asynchronously.
go func() {
// Create a context that will not be canceled due to HTTP connection closure.
detachedCtx := icontext.WithoutCancel(ctx)
// Process notification (currently just log it, but can be extended).
if err := s.handleNotification(detachedCtx, ¬ification, session); err != nil {
s.logger.Errorf("Error handling notification %s: %v", notification.Method, err)
}
}()
}
// handleNotification processes notifications (can be extended for different notification types).
func (s *SSEServer) handleNotification(ctx context.Context, notification *JSONRPCNotification, session *sseSession) error {
// Check if there's a registered handler for this notification method.
s.notificationMu.RLock()
handler, exists := s.notificationHandlers[notification.Method]
s.notificationMu.RUnlock()
if exists {
go func() {
// Call the handler with the notification pointer and context.
if err := handler(ctx, notification); err != nil && s.logger != nil {
s.logger.Errorf("Error handling notification %s: %v", notification.Method, err)
}
}()
} else if s.logger != nil {
s.logger.Warnf("Received notification with no handler registered: %s", notification.Method)
}
return nil
}
// handleResponseMessage processes JSON-RPC responses (like roots/list responses).
func (s *SSEServer) handleResponseMessage(ctx context.Context, rawMessage json.RawMessage, session *sseSession) {
var response jsonRPCEnvelope
if err := json.Unmarshal(rawMessage, &response); err != nil {
s.logger.Errorf("Error parsing response: %v", err)
return
}
// Convert ID to uint64.
requestIDUint, ok := s.parseRequestID(response.ID)
if !ok {
s.logger.Errorf("Invalid request ID in response: %v", response.ID)
return
}
// Get the response channel.
s.responsesMu.RLock()
responseChanInterface, exists := s.responses[requestIDUint]
s.responsesMu.RUnlock()
if !exists {
s.logger.Debugf("Received response for unknown request ID: %d", requestIDUint)
return
}
// Type assert to the correct channel type.
responseChan, ok := responseChanInterface.(chan *json.RawMessage)
if !ok {
s.logger.Errorf("Invalid response channel type for request ID: %d", requestIDUint)
return
}
// Prepare response data.
var responseMessage *json.RawMessage
// Handle error response.
if response.Error != nil {
// Create error result.
errorBytes, _ := json.Marshal(map[string]interface{}{
"error": response.Error,
})
errorMsg := json.RawMessage(errorBytes)
responseMessage = &errorMsg
} else if response.Result != nil {
// Handle success response.
resultBytes, err := json.Marshal(response.Result)
if err != nil {
s.logger.Errorf("Failed to marshal response result: %v", err)
return
}
resultMsg := json.RawMessage(resultBytes)
responseMessage = &resultMsg
} else {
// Invalid response - neither error nor result.
s.logger.Errorf("Invalid JSON-RPC response: missing both result and error for ID: %d", requestIDUint)
return
}
// Deliver the response.
select {
case responseChan <- responseMessage:
default:
s.logger.Errorf("Failed to deliver response: channel full or closed for request ID: %d", requestIDUint)
}
}
// getSessionFromRequest extracts and validates the session from the request.
func (s *SSEServer) getSessionFromRequest(r *http.Request) (*sseSession, error) {
// Get and record all query parameters.
queryParams := r.URL.Query()
// Get session ID (only use sessionId parameter).
sessionID := queryParams.Get("sessionId")
if sessionID == "" {
return nil, fmt.Errorf("missing sessionId parameter")
}
// Get session.
sessionValue, ok := s.sessions.Load(sessionID)
if !ok {
return nil, fmt.Errorf("%w: %s", ErrSessionNotFound, sessionID)
}
// Type assertion.
session, ok := sessionValue.(*sseSession)
if !ok {
return nil, fmt.Errorf("invalid session type for session ID: %s", sessionID)
}
// Update session activity.
session.UpdateActivity()
return session, nil
}
// handleSessionError handles errors related to session retrieval.
func (s *SSEServer) handleSessionError(w http.ResponseWriter, err error) {
errMsg := err.Error()
s.logger.Errorf("%s", errMsg)
switch {
case strings.Contains(errMsg, "missing sessionId"):
http.Error(w, "Missing sessionId parameter", http.StatusBadRequest)
case errors.Is(err, ErrSessionNotFound):
http.Error(w, "Session not found", http.StatusNotFound)
default:
http.Error(w, "Invalid session", http.StatusInternalServerError)
}
}
// tryPublish serializes and publishes an HTTP request to a remote node via the
// configured SessionPubSub implementation. It is used when the local server
// does not have the requested session but other nodes may.
func (s *SSEServer) tryPublish(ctx context.Context, sessionID string, r *http.Request) error {
if s.sessionPubSub == nil {
return fmt.Errorf("session pubsub not configured")
}
// Read the request body.
body, err := io.ReadAll(r.Body)
if err != nil {
return fmt.Errorf("failed to read request body: %w", err)
}
defer r.Body.Close()
// Build serialized request compatible with mcp-go.
serialized := serializedRequest{
Method: r.Method,
URL: r.URL.String(),
Headers: r.Header,
Body: body,
RemoteAddr: r.RemoteAddr,
Query: r.URL.Query(),
}
// Preserve deadline if present on context.
if deadline, ok := ctx.Deadline(); ok {
serialized.Deadline = &deadline
}
payload, err := json.Marshal(&serialized)
if err != nil {
return fmt.Errorf("failed to serialize request: %w", err)
}
if err := s.sessionPubSub.Publish(ctx, sessionID, payload); err != nil {
return fmt.Errorf("failed to publish message for session %s: %w", sessionID, err)
}
return nil
}
// parseJSONRPCRequest reads and parses the JSON-RPC request from the request body.
func (s *SSEServer) parseJSONRPCRequest(r *http.Request) (*JSONRPCRequest, error) {
// Read request body content.
requestBody, err := io.ReadAll(r.Body)
if err != nil {
return nil, fmt.Errorf("error reading request body: %v", err)
}
// Re-create request body.
r.Body = io.NopCloser(bytes.NewBuffer(requestBody))
// Parse request body.
var request JSONRPCRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
return nil, fmt.Errorf("error decoding request: %v", err)
}
return &request, nil
}
// createSessionContext creates a context with session information.
func (s *SSEServer) createSessionContext(ctx context.Context, session *sseSession) context.Context {
// Use the global setSessionToContext function to ensure consistent context key.
ctx = setSessionToContext(ctx, session)
// Set server instance to context.
ctx = setServerToContext(ctx, s)