Skip to content

feat: implement MCP connection keepalive logic#562

Open
szmania wants to merge 2 commits into
cecli-dev:mainfrom
szmania:cli-37-mcp-connection-keepalive
Open

feat: implement MCP connection keepalive logic#562
szmania wants to merge 2 commits into
cecli-dev:mainfrom
szmania:cli-37-mcp-connection-keepalive

Conversation

@szmania
Copy link
Copy Markdown

@szmania szmania commented Jun 7, 2026

Purpose

Implement a keepalive mechanism to maintain active MCP connections during periods of inactivity, preventing connection errors when tools are subsequently called.

Design Considerations

  • Background Task: Implemented as an asyncio.Task within the HttpBasedMcpServer class.
  • Heartbeat Mechanism: Uses lightweight OPTIONS requests to check server availability.
  • State Machine: Manages connection health through CONNECTED, UNHEALTHY, and DISCONNECTED states.
  • Resilience: Implements exponential backoff with jitter for automatic reconnection.
  • Configurability: Supports a configurable keepalive_interval in the server configuration.
  • Security: Includes jitter to prevent timing analysis and supports optional authentication headers.

Changes Made

  • Added ConnectionState enum to cecli/mcp/server.py.
  • Implemented start_keepalive(), _keepalive_loop(), and reconnect() in HttpBasedMcpServer.
  • Updated connect() and disconnect() to manage the keepalive task lifecycle.
  • Added validation for keepalive_interval configuration.

Testing Performed

  • Unit Tests: Verified state transitions and reconnection logic.
  • Integration Tests: Validated heartbeat frequency and connection maintenance with a mock server.
  • Resilience Tests: Simulated network failures and verified automatic recovery.
  • Concurrency Tests: Ensured the keepalive task does not interfere with other operations and cleans up correctly on disconnect.
  • Configuration Tests: Verified validation of interval ranges and types.

Refer to .cecli.plans.md for full implementation and testing details.

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.

1 participant