Expose business errors as structured tool results
In this article (5 sections)
“Something went wrong” cannot tell a workflow whether to retry, repair input, abstain or escalate. Stable error codes make control flow testable.
Compare two business failures
The MCP contract lab creates authored results.
from mcp_cases import business_error_case
result = business_error_case()
assert result["stable_codes"] == ["METRIC_NOT_FOUND", "SOURCE_DELAYED"]
assert result["retryable_codes"] == ["SOURCE_DELAYED"]
assert result["exceptions_exposed_as_prose_only"] is FalseUnknown metric is permanent until input changes; delayed source may retry within budget. No backend runs.
Design a small error model
Return status, stable code, retryable flag, safe message, field/details where appropriate, operation receipt and retry-after. Separate protocol/transport errors from domain outcomes.
Do not expose stack traces, SQL, credentials or unauthorized resource existence. The model can explain a safe error, but code applies retry and authorization policy.
Test caller behaviour
For every code, assert attempts, final state, user message and side effects. Add unknown-code handling that fails safely. Version semantic changes and monitor error-rate shifts.
The Generative & Agentic AI course connects structured errors to agent recovery and observability.
Exercise
Define eight domain codes and write a table-driven router. Prove no permanent failure retries and no error message leaks secrets or cross-tenant existence.
Continue learning
This article is part of the MCP and integration contracts sequence. Use the neighbouring tasks when you need the prerequisite or the next application.
- Review the prerequisite or neighbouring task in Build contract tests for an external tool integration.
- Continue with Keep secrets out of tool descriptions and logs.
Reference: Google API error model.
Pankit Kumar has 10 years in Data Science & AI, building and shipping production systems in regulated pharma and clinical environments. He is a freelance trainer at Boston Institute of Analytics, AnalytixLabs and Scaler, and has taught this material to thousands of working professionals.
This article is part of our Generative & Agentic AI programme — 3 months. Add practical GenAI, retrieval and agent-building skills to your existing toolkit.
Explore Generative & Agentic AI