Skip to content

Commit c258d9f

Browse files
stefanskiasanclaude
andcommitted
fix: Preserve session metadata in external storage mode
- Call onsessioninitialized handler BEFORE storing session data - Merge existing session data (including metadata) when updating - Prevents overwrites of custom metadata (e.g., serverId) set by handlers This fix ensures that applications using external session storage can store additional metadata (like serverId for cross-pod recovery) via the onsessioninitialized callback without it being overwritten by the SDK's internal storeSession call. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 30a3633 commit c258d9f

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

src/server/streamableHttp.ts

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -768,22 +768,30 @@ export class StreamableHTTPServerTransport implements Transport {
768768
this.sessionId = this.sessionIdGenerator?.();
769769
this._initialized = true;
770770

771-
// Store session in external store if using external storage mode
771+
// If we have a session ID and an onsessioninitialized handler, call it FIRST
772+
// This allows the handler to store metadata (e.g., serverId) before we update the session
773+
if (this.sessionId && this._onsessioninitialized) {
774+
await Promise.resolve(this._onsessioninitialized(this.sessionId));
775+
}
776+
777+
// Store/update session in external store if using external storage mode
778+
// This runs AFTER onsessioninitialized so we can merge with any existing metadata
772779
if (this._sessionStorageMode === 'external' && this._sessionStore && this.sessionId) {
780+
// Try to get existing session data (may have been stored by onsessioninitialized)
781+
const existingData = await this._sessionStore.getSession(this.sessionId);
782+
const now = Date.now();
783+
773784
const sessionData: SessionData = {
774785
sessionId: this.sessionId,
775786
initialized: true,
776-
createdAt: Date.now(),
777-
lastActivity: Date.now()
787+
createdAt: existingData?.createdAt ?? now,
788+
lastActivity: now,
789+
// Preserve any existing metadata (e.g., serverId set by onsessioninitialized)
790+
metadata: existingData?.metadata
778791
};
779792
await this._sessionStore.storeSession(this.sessionId, sessionData);
780793
}
781794

782-
// If we have a session ID and an onsessioninitialized handler, call it immediately
783-
// This is needed in cases where the server needs to keep track of multiple sessions
784-
if (this.sessionId && this._onsessioninitialized) {
785-
await Promise.resolve(this._onsessioninitialized(this.sessionId));
786-
}
787795
}
788796
if (!isInitializationRequest) {
789797
// If an Mcp-Session-Id is returned by the server during initialization,

0 commit comments

Comments
 (0)