My MCP server used to simply stop working. No crash dump. No stack trace in the logs. Clients connected without complaint, then after a few hours the whole thing went mute. Requests disappeared and the AI agent on the other end received nothing but blank air.

This is a frustratingly common story in the Model Context Protocol (MCP) ecosystem. The protocol defines how AI agents discover and call external tools, but the specification assumes you will handle errors yourself. Most tutorials and starter implementations skip past that part. They focus on the happy path: annotate a function, expose it through the server, and return a clean result. They rarely show you what happens when a network blip hits your external API, or when the model hallucinates a parameter name and sends garbage input. The result is a brittle server that looks healthy but has actually been dead for hours.

Why Blank Responses Are Worse Than Crashes

When an unhandled exception slips through in an MCP tool handler, the transport layer often swallows it. The server process stays alive, the socket remains open, but the client gets an empty response. This is more dangerous than a loud crash because your monitoring might not notice. The process is still running. The port is still listening. Yet every tool call returns nothing.

The AI model does not interpret silence as failure. It interprets silence as a successful call that produced no data. That blank response trains the model to improvise. It starts hallucinating facts to fill the gap, or it enters a loop of retrying the same broken call. Small issues like a transient network timeout or an invalid tool argument should never be allowed to cause this kind of behavior.

The Wrapper Pattern: Three Lines of Defense

I fixed this by wrapping every tool handler in a thin error-recovery layer. The wrapper does not try to predict every possible failure. It categorizes them and responds accordingly.

ConnectionError and TimeoutError
These arise when your server talks to an external API and the network wobbles. The instinctive fix is to restart the entire MCP server process. Do not do that. Rebooting drops active client connections, clears any in-memory state, and forces a full re-initialization. Instead, catch the connection failure and reconnect only the transport layer or HTTP client your tool uses. The server stays warm and ready for the next request immediately.

ValueError
This is what you see when the AI client sends malformed arguments. Maybe the model invented a parameter, passed a string where an integer was required, or forgot a required field. If you let this bubble up unhandled, the client gets either a crash or a blank reply. Catch it inside the wrapper, then construct a clear, specific message that tells the model exactly what went wrong. Explain which parameter failed and what was expected. Most modern AI models will read that message and self-correct on the very next turn. A vague error wastes a reasoning cycle. A precise error fixes the problem immediately.

General Exceptions
Keep a safety net. If an error falls outside the categories above, log the details for yourself and return a clean, generic failure response to the client. This prevents one weird edge case from killing the session for everyone. The server survives, the client gets a signal that something failed, and you keep enough context in your logs to debug later.

The isError Flag Is Non-Negotiable

Here is the detail that actually determines whether your fix works. MCP responses include an isError boolean field. If an exception occurs and you return an error message without setting isError to true, the client treats that error text as a successful tool result.

Imagine your external API hits a rate limit. You catch the exception and return the string "API rate limit exceeded" but leave isError as false. The client passes that string into the model's context window as if it were real tool output. The model then tries to reason over that text as if it were data. It might quote the error in a summary, or worse, it might hallucinate relationships between that error text and other facts. You have turned a temporary infrastructure hiccup into a source of misinformation.

Sempre defina isError como true ao retornar um payload de erro. Isso fornece ao cliente um sinal claro de que a chamada da ferramenta falhou, o que permite ao modelo decidir se deve tentar novamente, pedir esclarecimentos ou tentar uma ferramenta completamente diferente.

Saiba o que Capturar e o que Encerrar

Não envolva todo o seu servidor em um try-catch cego que engole tudo. Alguns erros significam que o servidor deve parar imediatamente. Se uma variável de ambiente obrigatória estiver faltando na inicialização, ou se o seu arquivo de configuração estiver corrompido, nenhuma captura no nível da requisição ajudará. Crie uma classe de exceção específica para erros fatais como esses e deixe que eles interrompam o processo.

A regra é simples. Se o erro for temporário ou isolado em uma única requisição, capture-o e recupere-se. Se o erro significar que todas as requisições subsequentes certamente falharão, deixe o servidor morrer de forma ruidosa. Uma falha rápida na inicialização é infinitamente melhor do que um servidor que continua operando precariamente por dias em um estado de erro.

Adicione Observabilidade Antes de Precisar Dela

Assim que tiver o wrapper implementado, combine-o com logs estruturados. Registre cada chamada de ferramenta e seu resultado em formato JSON. Inclua o nome da ferramenta, os argumentos brutos, a latência e se ela teve sucesso, falhou ou foi tentada novamente.

Essa disciplina traz resultados rapidamente. Quando você notar um pico de erros, poderá filtrar por ferramenta e identificar padrões em minutos. Talvez uma API externa específica comece a apresentar timeouts no mesmo horário todos os dias, apontando para uma janela de manutenção agendada que você desconhecia. Talvez uma ferramenta receba argumentos consistentemente malformados, revelando uma falha de engenharia de prompt a montante. Logs em texto puro enterrados em stack traces tornam esse trabalho de detetive doloroso. O JSON estruturado o torna trivial.

O Resultado em Produção

Eu utilizei esse padrão de wrapper em dois servidores MCP de produção nas últimas três semanas. Nesse período, não vi nenhuma falha silenciosa. Antes de adicionar o wrapper, eu tinha uma média de aproximadamente uma falha inexplicável por dia. O padrão não é complexo, mas seu impacto é enorme porque separa o ruído suportável de problemas reais.

Falhas silenciosas custam mais do que crashes. Um crash aciona seu sistema de alerta. O silêncio apenas corrói a confiança. Um dia seu agente de IA retorna dados úteis de ferramentas e, no dia seguinte, ele começa a inventar coisas porque o servidor parou de responder horas atrás. O padrão wrapper fecha essa lacuna. Ele mantém seu servidor funcionando durante turbulências menores, dá ao modelo contexto suficiente para corrigir seus próprios erros e garante que, quando algo verdadeiramente fatal der errado, você saiba imediatamente.

Se você está construindo ferramentas MCP hoje, comece com o wrapper e a flag isError. Todo o resto é apenas limpeza.