{"slug": "my-mcp-server-kept-crashing-here-s-the-error-recovery-pattern-that-saved-it", "title": "My MCP Server Kept Crashing. Here's the Error Recovery Pattern That Saved It.", "summary": "A developer built a resilient error recovery pattern for MCP servers after experiencing silent crashes. The pattern wraps tool handlers to catch exceptions and return structured error responses with isError: True, preventing AI agents from hallucinating based on garbage text. The solution has been running on two production servers for three weeks with zero silent failures.", "body_md": "I spent three days wondering why my MCP server would just... stop. No crash logs. No error messages. Clients connected fine, then after a few hours, every tool call returned silence.\n\nTurns out the Model Context Protocol (MCP) spec doesn't force you to handle errors — it *assumes* you will. But the reference implementations are minimal. Your server starts healthy, then bit by bit, things go wrong. A network blip. A malformed tool argument. An external API timeout. And suddenly your AI agent is staring at a blank response.\n\nHere's the pattern I ended up with. It's not clever. It just works.\n\nStart with a wrapper around your tool handlers. Every MCP server framework has some kind of tool registration — this works for the official Python SDK, the TypeScript SDK, and most community frameworks:\n\n``` python\nfrom mcp.server import Server\nfrom mcp.types import ErrorData, INTERNAL_ERROR, INVALID_PARAMS\nimport traceback\nimport json\n\nclass ResilientMCPServer(Server):\n    \"\"\"An MCP server that doesn't silently die.\"\"\"\n\n    async def call_tool(self, name: str, arguments: dict):\n        try:\n            result = await super().call_tool(name, arguments)\n            return result\n        except (ConnectionError, TimeoutError) as e:\n            # Network-level issues — reconnect and retry\n            self._reconnect()\n            return self._error_response(\n                f\"Connection lost while executing {name}: {e}\"\n            )\n        except ValueError as e:\n            # Bad arguments from the client — tell them clearly\n            return self._error_response(\n                f\"Invalid arguments for {name}: {e}\",\n                code=INVALID_PARAMS\n            )\n        except Exception as e:\n            # Everything else — log, don't crash\n            traceback.print_exc()\n            return self._error_response(\n                f\"Tool {name} failed: {e}\",\n                code=INTERNAL_ERROR\n            )\n\n    def _error_response(self, message: str, code: int = INTERNAL_ERROR):\n        return {\n            \"content\": [{\"type\": \"text\", \"text\": f\"ERROR: {message}\"}],\n            \"isError\": True\n        }\n\n    def _reconnect(self):\n        \"\"\"Reset transport layer without restarting the server.\"\"\"\n        # Your reconnection logic here\n        pass\n```\n\nThe key detail most people miss: **set isError: True in the response**. Without it, the client treats your error message as a successful result. Your AI starts hallucinating based on garbage text.\n\nLet me break down what each exception type maps to in practice.\n\n**ConnectionError / TimeoutError** — These happen when your MCP server talks to an external API or database. The STDIO transport itself won't throw these, but your tool handlers will when they call out to the internet. I reconnect the transport layer instead of restarting the process, which drops the ongoing request but keeps the server available for the next one.\n\n**ValueError** — Your AI client sent garbage arguments. Maybe it invented a parameter name, passed a string where a number was expected, or sent an empty array. Instead of crashing, tell it exactly what was wrong. I've seen Claude and GPT both self-correct on the next tool call when they get a clear error.\n\n**Exception (catch-all)** — Everything else. Third-party SDK threw something unexpected. A file was missing. Memory ran out. The catch-all logs the full traceback so you can fix it later, returns a clean error to the client, and keeps the server running. Your agent loses one response but not the whole session.\n\nMCP has a built-in error reporting mechanism through `isError`\n\n, but the SDKs don't enforce it. If your tool handler throws an unhandled exception:\n\n`isError: True`\n\n`isError`\n\n, the client The wrapper pattern guarantees three things:\n\n`isError: True`\n\ntells the LLM \"this response is an error, don't use it\"I've been running this pattern on two production MCP servers for three weeks. Zero silent failures since the deployment. Before the wrapper, I was getting about one per day.\n\n**Don't catch everything blindly.** Some errors *should* crash the server — config validation failures, missing environment variables, corrupted state. I use a separate `FatalError`\n\nexception class for those:\n\n```\nclass FatalError(Exception):\n    \"\"\"Errors that should kill the server process.\"\"\"\n    pass\n\n# In the wrapper: re-raise FatalErrors\nexcept FatalError:\n    raise  # Let it crash — better than running corrupted\n```\n\nThe rule of thumb: if the error means *all future requests will also fail*, crash. If it's transient or specific to one request, catch it.\n\n**Be careful with reconnection in shared-state servers.** If your MCP server maintains in-memory state (caches, active connections), a reconnect might leave stale references. I added a `health_check`\n\ntool that clients can call to verify the server is in a good state:\n\n``` php\n@server.tool()\nasync def health_check() -> dict:\n    return {\n        \"status\": \"ok\",\n        \"connections_active\": len(pool._connections),\n        \"cache_size\": len(cache._store)\n    }\n```\n\nThis is especially useful when using MCP over Streamable HTTP transport. A transport-level reconnect resets the HTTP connection but leaves your in-memory caches intact — which is exactly what you want, as long as those caches aren't holding stale connections.\n\n**The isError flag is per-response, not per-stream.** Each tool call response can independently signal success or failure. This means partial failures are possible — handle them explicitly rather than aborting the whole batch. If one of your tools queries five APIs and three fail, you can return:\n\n```\n{\n    \"content\": [\n        {\"type\": \"text\", \"text\": \"Fetched data from API-A, API-B, API-C. API-D and API-E timed out.\"}\n    ],\n    \"isError\": True\n}\n```\n\nThe client gets the partial data and a clear signal that something failed. The LLM can decide to retry the failed ones or proceed with what it has.\n\nDon't underestimate how much a structured log helps when things go wrong. I added a simple JSON logger that captures every tool call and its outcome:\n\n``` python\nimport logging\nimport json\n\nmcp_logger = logging.getLogger(\"mcp.server\")\nhandler = logging.FileHandler(\"mcp_errors.log\")\nhandler.setFormatter(logging.Formatter(\n    '%(asctime)s | %(levelname)s | %(message)s'\n))\nmcp_logger.addHandler(handler)\n\n# In your wrapper\nmcp_logger.error(json.dumps({\n    \"tool\": name,\n    \"error\": str(e),\n    \"type\": type(e).__name__\n}))\n```\n\nThis saved me twice already — once when I spotted a pattern of timeout errors pointing to a rate-limited API, and once when a ValueError from the client revealed a prompt that was generating malformed tool calls.\n\nHave you run into silent MCP server failures? How do you handle tool-level errors in your agent infrastructure? I'm still figuring out the edges — especially around long-running tools that timeout mid-execution.", "url": "https://wpnews.pro/news/my-mcp-server-kept-crashing-here-s-the-error-recovery-pattern-that-saved-it", "canonical_source": "https://dev.to/chenyuan20509/my-mcp-server-kept-crashing-heres-the-error-recovery-pattern-that-saved-it-nd5", "published_at": "2026-07-14 06:48:08+00:00", "updated_at": "2026-07-14 07:01:23.410748+00:00", "lang": "en", "topics": ["developer-tools", "ai-agents", "large-language-models"], "entities": ["MCP", "Model Context Protocol", "Claude", "GPT"], "alternates": {"html": "https://wpnews.pro/news/my-mcp-server-kept-crashing-here-s-the-error-recovery-pattern-that-saved-it", "markdown": "https://wpnews.pro/news/my-mcp-server-kept-crashing-here-s-the-error-recovery-pattern-that-saved-it.md", "text": "https://wpnews.pro/news/my-mcp-server-kept-crashing-here-s-the-error-recovery-pattern-that-saved-it.txt", "jsonld": "https://wpnews.pro/news/my-mcp-server-kept-crashing-here-s-the-error-recovery-pattern-that-saved-it.jsonld"}}