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.

قم دائمًا بضبط isError على true عند إرجاع حمولة خطأ (error payload). يوفر هذا إشارة واضحة للعميل بأن استدعاء الأداة قد فشل، مما يتيح للنموذج اتخاذ القرار بشأن إعادة المحاولة، أو طلب توضيح، أو تجربة أداة مختلفة تمامًا.

اعرف ما يجب معالجته وما يجب إيقافه

لا تقم بتغليف خادمك بالكامل بكتلة try-catch عمياء تبتلع كل شيء. فبعض الأخطاء تعني وجوب توقف الخادم فورًا. إذا كان هناك متغير بيئة (environment variable) مطلوب مفقودًا عند بدء التشغيل، أو كان ملف التكوين الخاص بك تالفًا، فلن تجدي أي محاولة لمعالجة الأخطاء على مستوى الطلب نفعًا. قم بإنشاء فئة استثناء (exception class) محددة للأخطاء القاتلة مثل هذه واتركها تتسبب في توقف العملية (crash the process).

القاعدة بسيطة. إذا كان الخطأ مؤقتًا أو مقتصرًا على طلب واحد، فقم بمعالجته والتعافي منه. أما إذا كان الخطأ يعني أن كل طلب لاحق سيفشل بالتأكيد، فاترك الخادم يتوقف بشكل صريح. فالفشل السريع عند بدء التشغيل أفضل بمراحل من خادم يستمر في العمل بشكل متعثر لأيام في حالة معطلة.

أضف خاصية القابلية للمراقبة (Observability) قبل أن تحتاج إليها

بمجرد وضع الغلاف (wrapper) في مكانه، قم بدمجه مع تسجيل منظم (structured logging). قم بتسجيل كل استدعاء للأداة ونتيجته بتنسيق JSON. قم بتضمين اسم الأداة، والوسائط الخام (raw arguments)، وزمن الاستجابة (latency)، وما إذا كانت العملية قد نجحت، أو فشلت، أو تمت إعادة المحاولة.

هذا الانضباط يؤتي ثماره سريعًا. فعندما تلاحظ ارتفاعًا مفاجئًا في الأخطاء، يمكنك التصفية حسب الأداة ورصد الأنماط في دقائق. ربما تبدأ واجهة برمجة تطبيقات (API) خارجية معينة في إرسال مهلات زمنية (timeouts) في نفس الوقت كل يوم، مما يشير إلى نافذة صيانة مجدولة لم تكن تعلم عنها. ربما تتلقى أداة واحدة وسائط مشوهة باستمرار، مما يكشف عن خلل في هندسة الأوامر (prompt engineering) في مرحلة سابقة. إن سجلات النصوص العادية المدفونة في تتبعات المكدس (stack traces) تجعل عمل التحري هذا مؤلمًا، بينما يجعل تنسيق JSON المنظم الأمر سهلاً للغاية.

النتيجة في بيئة الإنتاج

لقد قمت بتشغيل نمط الغلاف هذا على خادمي MCP في بيئة الإنتاج طوال الأسابيع الثلاثة الماضية. وخلال تلك الفترة، لم أشهد أي حالات فشل صامتة. قبل إضافة الغلاف، كان متوسط الفشل غير المفسر يوميًا حوالي مرة واحدة. النمط ليس معقدًا، لكن تأثيره هائل لأنه يفصل بين الضجيج الذي يمكن تجاوزه والمشاكل الحقيقية.

الفشل الصامت يكلف أكثر من الانهيار (crash). فالانهيار يفعل نظام التنبيه لديك، أما الصمت فيؤدي فقط إلى تآكل الثقة. في يوم ما، يعيد وكيل الذكاء الاصطناعي الخاص بك بيانات مفيدة من الأداة، وفي اليوم التالي يبدأ في اختلاق الأمور لأن الخادم توقف عن الاستجابة منذ ساعات. يسد نمط الغلاف هذه الفجوة؛ فهو يحافظ على تشغيل خادمك خلال الاضطرابات الطفيفة، ويمنح النموذج سياقًا كافيًا لإصلاح أخطائه بنفسه، ويضمن أنه عندما يحدث خطأ قاتل حقًا، ستسمع عنه على الفور.

إذا كنت تبني أدوات MCP اليوم، فابدأ بالغلاف وعلم isError. كل شيء آخر ليس سوى مجرد تحسينات لاحقة.