Skip to content

Add single-instance guard for MCP stdio server#31

Open
Hohlas wants to merge 1 commit intolyonzin:masterfrom
Hohlas:single-instance-guard
Open

Add single-instance guard for MCP stdio server#31
Hohlas wants to merge 1 commit intolyonzin:masterfrom
Hohlas:single-instance-guard

Conversation

@Hohlas
Copy link
Copy Markdown
Contributor

@Hohlas Hohlas commented May 6, 2026

Hi @lyonzin,

This PR adds a single-instance guard for the knowledge-rag MCP server.

Problem

Some MCP stdio clients can start multiple knowledge-rag processes even during a single visible user session/request. In my case this happened from one chat: the client opened additional internal MCP connections during approval/review flow, so several independent knowledge-rag processes were spawned although I was not intentionally running parallel chats.

Each process loads its own embedding model, ChromaDB client, BM25 state, and file watcher. On larger local indexes this can quickly consume several GB of RAM and may exhaust system memory.

Fix

The server now creates data/knowledge-rag.lock on startup and refuses to start a second instance while the first one is still alive.

The guard:

  • writes the current PID to the lock file;
  • checks whether an existing PID is still running;
  • exits with code 75 if another server is active;
  • removes stale lock files when the previous process is gone;
  • cleans up the lock on normal termination and SIGINT/SIGTERM.

The lock is applied in server.main(), so it protects all entry points that run the MCP server, including direct knowledge-rag, python -m mcp_server.server, and wrapper-based launches.

Validation

I reproduced the issue by starting multiple MCP stdio server instances with open stdin. Each instance stayed alive independently and loaded its own model/watcher.

After this patch, the second server exits immediately with:

knowledge-rag MCP server is already running

Added tests cover:

  • rejecting a second running instance;
  • recovering from a stale lock file.

@Hohlas Hohlas requested a review from lyonzin as a code owner May 6, 2026 17:11
@Hohlas Hohlas force-pushed the single-instance-guard branch 2 times, most recently from 285427f to 683500a Compare May 6, 2026 17:26
@Hohlas Hohlas force-pushed the single-instance-guard branch from 683500a to 32c5f35 Compare May 6, 2026 17:34
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