feat(mcp): Added file locking mechanism to prevent concurrent snapshot file modification #234
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.