Skip to content

Conversation

@magent-cryptograss
Copy link
Collaborator

Summary

  • Fixes "connection already closed" errors when calling MCP tools
  • Adds with_fresh_connection wrapper that ensures fresh DB connections for each tool call
  • Wraps all 9 MCP tool handlers with this fix

Root Cause

When Django ORM queries are wrapped with sync_to_async in a long-running async process (like the MCP server), database connections can become stale between tool invocations. PostgreSQL connections time out, but Django's connection pool doesn't automatically detect and refresh them.

Solution

Call django.db.close_old_connections() before and after each database operation, forcing Django to establish a fresh connection.

Test plan

  • Redeploy MCP server on maybelle
  • Call bootstrap_memory MCP tool
  • Verify memory bootstrap returns data instead of "connection already closed"

jMyles added 2 commits January 4, 2026 03:35
Same DEFAULT_EXEMPTIONS as secrets_filter.py - prevents redacting
common non-sensitive values like database names (pickipedia, mediawiki, etc.)
When Django ORM queries are wrapped with sync_to_async in a long-running
async process, database connections can become stale. This manifests as
"connection already closed" errors when calling MCP tools.

Solution: Add a with_fresh_connection wrapper that calls
close_old_connections() before and after each database operation,
ensuring a fresh connection for every MCP tool call.
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.

3 participants