Skip to content

Commit b7d6aa9

Browse files
committed
fix: make session requestID unique and incremental
1 parent be2c2e3 commit b7d6aa9

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

server/streamable_http.go

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -106,8 +106,9 @@ func WithLogger(logger util.Logger) StreamableHTTPOption {
106106
// - Batching of requests/notifications/responses in arrays.
107107
// - Stream Resumability
108108
type StreamableHTTPServer struct {
109-
server *MCPServer
110-
sessionTools *sessionToolsStore
109+
server *MCPServer
110+
sessionTools *sessionToolsStore
111+
sessionRequestIDs sync.Map // sessionId --> last requestID(*atomic.Int64)
111112

112113
httpServer *http.Server
113114
mu sync.RWMutex
@@ -394,7 +395,7 @@ func (s *StreamableHTTPServer) handleGet(w http.ResponseWriter, r *http.Request)
394395
case <-ticker.C:
395396
message := mcp.JSONRPCRequest{
396397
JSONRPC: "2.0",
397-
ID: mcp.NewRequestId(session.requestID.Add(1)),
398+
ID: mcp.NewRequestId(s.nextRequestID(sessionID)),
398399
Request: mcp.Request{
399400
Method: "ping",
400401
},
@@ -448,6 +449,9 @@ func (s *StreamableHTTPServer) handleDelete(w http.ResponseWriter, r *http.Reque
448449
// remove the session relateddata from the sessionToolsStore
449450
s.sessionTools.set(sessionID, nil)
450451

452+
// remove current session's requstID information
453+
s.sessionRequestIDs.Delete(sessionID)
454+
451455
w.WriteHeader(http.StatusOK)
452456
}
453457

@@ -479,6 +483,13 @@ func (s *StreamableHTTPServer) writeJSONRPCError(
479483
}
480484
}
481485

486+
// nextRequestID gets the next incrementing requestID for the current session
487+
func (s *StreamableHTTPServer) nextRequestID(sessionID string) int64 {
488+
actual, _ := s.sessionRequestIDs.LoadOrStore(sessionID, new(atomic.Int64))
489+
counter := actual.(*atomic.Int64)
490+
return counter.Add(1)
491+
}
492+
482493
// --- session ---
483494

484495
type sessionToolsStore struct {
@@ -512,7 +523,6 @@ type streamableHttpSession struct {
512523
notificationChannel chan mcp.JSONRPCNotification // server -> client notifications
513524
tools *sessionToolsStore
514525
upgradeToSSE atomic.Bool
515-
requestID atomic.Int64
516526
}
517527

518528
func newStreamableHttpSession(sessionID string, toolStore *sessionToolsStore) *streamableHttpSession {

0 commit comments

Comments
 (0)