Skip to content

fix(mcp): offload MCPToolProvider._log_activity DB write to asyncio.to_thread - #626

Open
ojaswa072 wants to merge 1 commit into
GenAI-Security-Project:mainfrom
ojaswa072:fix/mcp-sync-db-write-in-async-tool-callable
Open

ojaswa072 wants to merge 1 commit into
GenAI-Security-Project:mainfrom
ojaswa072:fix/mcp-sync-db-write-in-async-tool-callable

Conversation

@ojaswa072

Copy link
Copy Markdown

Problem

MCPToolProvider._log_activity performed a synchronous SQLAlchemy db_session() write directly on the async event loop. This is a hot path, it fires on every MCP tool call (pre-call, success, and failure paths) plus once per server during connect(). Under concurrent sessions this serializes all MCP tool executions through the event loop, adding DB round-trip latency to every agent action and contributing to connection pool pressure.

Fix

  • Extract the blocking SQLAlchemy body into _log_activity_sync (private sync helper).
  • Make _log_activity an async def that dispatches to asyncio.to_thread(_log_activity_sync, ...), keeping the event loop unblocked.
  • await all five call sites: one in connect(), three in call_mcp_tool().
  • Add import asyncio.

Behaviour

No change to the audit log, writes still happen, just on a thread-pool worker. The fix is non-breaking; _log_activity_sync is a private method and no external callers exist.

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