MCP Sessions

Tracks per-agent MCP sessions from connection to disconnection. Each session records the agent name, token, request count, and timestamps.

Session Lifecycle

Agent connects
  -> initialize request -> create session row in DB (connected_at = now)
  -> tools/list, tools/call, ... -> increment request_count in memory
  -> Agent disconnects (SSE stream closes)
  -> flush request_count to DB, set disconnected_at = now

Crash Recovery

On daemon startup, all sessions with disconnected_at IS NULL are closed with disconnected_at = now. This handles sessions that were open when the daemon was killed without a clean shutdown.

Key Concepts

  • Sessions are created when an agent sends the initialize request
  • agent_name is normalised from client_info.name (e.g., “Claude Code” becomes “claude-code”)
  • request_count is tracked in-memory and flushed on disconnect
  • On startup, orphaned sessions are closed automatically
  • Anonymous sessions (no valid auth token) are still recorded with token_id = NULL