Skip to content

Conversation

@naji247
Copy link
Member

@naji247 naji247 commented Nov 13, 2025

Summary

This PR improves session management in MCPCat with several key enhancements:

  • MCP Protocol Session Support: Prioritizes MCP-provided sessionIds over MCPCat-generated ones, with deterministic KSUID derivation for consistency across server restarts
  • Session Reconnection: Implements user session reconnection logic to handle cases where users reconnect without an MCP sessionId
  • Global Identity Cache: Prevents duplicate identify events across server instance restarts using an LRU cache
  • Server Reinitialization Protection: Adds guard to prevent duplicate tracking setup when track() is called multiple times
  • Per-Server Instance Tracking: Fixes listToolsTracingSetup to work correctly with multiple server instances

Technical Changes

Session Management

  • Modified getServerSessionId() to accept optional extra parameter containing MCP sessionId
  • Added deriveSessionIdFromMCPSession() to create deterministic KSUIDs from MCP sessionIds
  • Introduced sessionSource field to track whether session is MCP or MCPCat-generated
  • Added lastMcpSessionId tracking to detect session changes

Identity Management

  • Created global IdentityCache class with LRU eviction to persist identities across server restarts
  • Created UserSessionCache for user reconnection support
  • Refactored identity handling into centralized handleIdentify() function in internal.ts
  • Identity cache now shared across all server instances (max 1000 entries)

Server Instance Management

  • Added check in track() to prevent duplicate initialization
  • Changed listToolsTracingSetup from boolean to WeakMap for per-instance tracking
  • Ensured all tracing functions properly handle multiple server instances

Test Coverage

Added comprehensive test suite in src/tests/session-id.test.ts covering:

  • MCP sessionId prioritization
  • Deterministic session ID derivation
  • Session reconnection logic
  • Identity caching across restarts
  • User session mapping
  • Multi-user session separation

Updated src/tests/identify.test.ts to reflect new session separation behavior for different users.

Breaking Changes

None - all changes are backward compatible. If no MCP sessionId is provided, behavior falls back to the previous MCPCat-generated session logic.

@naji247 naji247 requested a review from kashishhora November 13, 2025 22:59
@naji247 naji247 merged commit 5e36d5f into main Nov 13, 2025
8 checks passed
@naji247 naji247 deleted the fixes-for-cloudflare branch November 13, 2025 23:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants