Skip to content

Conversation

@Ashish-Abraham
Copy link

fixes #216

Solution

This PR introduces a Leader Election pattern using file locks to ensure only one MCP server instance can perform write operations (e.g., indexing, syncing, clearing) at a time. On startup, each server attempts to acquire an exclusive lock on ~/.context/leader.lock. The successful instance becomes the "leader" and handles all modifications. Other instances become "followers" with read-only access (e.g., search operations).
Followers periodically check (every 5 seconds) if the lock is available, allowing automatic failover if the leader crashes. The OS ensures atomicity and reliability: locks are released automatically on process termination (including via signals like SIGINT and SIGTERM), and critical writes use temporary files with atomic renames to prevent partial updates.
This approach resolves the concurrency issues without requiring complex distributed coordination.

Implementation Details

Lock File: Uses ~/.context/leader.lock for exclusive locking via the proper-lockfile library, which employs flock on supported systems (e.g., Linux, BSD) and falls back to compatible mechanisms on others (e.g., Windows).
Leader Role: Only the leader performs index modifications (e.g., in handleIndexCodebase, handleClearIndex, and syncIndexedCodebasesFromCloud). Followers return a user-friendly message indicating they cannot perform writes.
Periodic Checks: Followers poll the lock availability every 5 seconds for automatic recovery.
In-Memory Tracking: Current operations are tracked in process memory to avoid stale on-disk markers from crashed instances.
Compatibility: Works across platforms, with OS-level guarantees for lock release on process exit. The lock is explicitly released on graceful shutdown signals (e.g., process.on('exit'), SIGINT, SIGTERM).
Dependency: Introduces proper-lockfile as a new dependency for robust locking.

No changes to existing APIs or user-facing behavior for single-instance usage.

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.

multiple MCP servers run on the same computer

1 participant