PUBLIC BETA OFFER

Save 50% off on an Eligible Learning PlanValid for 1-month plan, 3-month plan, 12-month plan · Code LPXBETA50 · Ends Dec 6, 2026

Implement structured error responses for MCP tools

Preserve error layers and recovery meaning across MCP results and API adapters.

Distinguish MCP protocol failures, tool errors, partial results, and successful searches with no matches. A UTC interval example shows actionable business-rule errors and boundary checks, while recovery guidance separates safe retries from uncertain writes.

Knowledge domain
Tool Design & MCP Integration
Topics & tags
Published
Author
LearningPathX Editorial TeamContent version 1.0
Resources

Implement structured error responses for MCP tools

Learning objectives

By the end of this topic, you should be able to:

  • Distinguish protocol failures, execution errors and successful empty results.
  • Return actionable error categories and recovery metadata.
  • Decide whether to retry, change input, request access or escalate.
  • Preserve partial work and customer-friendly explanations without claiming a failed operation succeeded.

Separate the protocol layer from the tool outcome

MCP can report a protocol-level failure, such as an invalid request or unknown tool, separately from a tool that ran and returned an error result. A native MCP CallToolResult can mark a tool outcome with isError: true and include diagnostic content. MCP means Model Context Protocol. In this source account, structural unknown-tool or malformed-request failures use JSON-RPC errors; upstream HTTP/SDK, client conversion and actual tool-origin results remain different layers.

Do not mix that native result with the Claude Messages API envelope. An adapter may represent a client-tool failure using is_error in an API tool_result block, associated with the actual tool_use_id. Camel-case isError and snake-case is_error belong to different contracts. Preserve the assistant request and return the result through the interface the application is actually using.

A tool failure can provide useful feedback without ending the conversation. A protocol or transport failure may also be recoverable by the application, but it must not be silently converted into a successful result merely so the model can continue.

Classify the cause before choosing recovery

The protocol layer alone does not determine whether an operation is retryable. Use the observed cause and the operation's side effects:

Error category Appropriate recovery
Transient service failure or rate limit Consider bounded retry with the appropriate delay, if repeating the operation is safe.
Invalid input Explain the offending field and expected format; correct supported input before another attempt.
Business-rule violation Preserve the rule and request an authorized alternative or review.
Permission or authentication failure Resolve access through the responsible account or owner; do not bypass it with prompt changes.
Protocol or adapter mismatch Repair the tool name, request structure or conversion at the correct layer.
Timeout after a possible write Inspect whether the write already happened before retrying.

An internal server error is not universally permanent, and an execution error is not universally safe to retry. A fixed retry count from one client's discovery behavior is not a policy for every MCP tool. Keep attempt, time and resource bounds explicit.

Return actionable metadata

"Operation failed" leaves the agent unable to distinguish a bad date from a denied account. A useful application-level error payload includes a category, stable error code, human-readable explanation, whether an unchanged automatic retry is permitted and an appropriate next step. Add a field name, expected format or request identifier where relevant.

Names such as errorCategory, isRetryable and retriable are application conventions rather than universal MCP fields. Choose a contract and document any adapter mapping. Do not assume that two differently named booleans are automatically interpreted identically.

A validation error can be non-retryable for the unchanged request while still allowing a corrected request. This distinction prevents the model from repeatedly sending the same invalid value. Never fabricate missing facts to make the next input pass validation.

Preserve diagnostic evidence while protecting credentials and unnecessary private information. A customer-friendly message should explain the supported next step, not expose a stack trace or falsely imply the action completed. Error text from an external source remains untrusted data.

Worked example: a date-range restriction

In this invented export contract, the interval starts at start and ends just before end. Both must be valid UTC timestamps, and end must be later than start, so the interval is nonempty. The duration may be at most 30 elapsed days, including exactly 30; missing dates must be clarified. This is a teaching rule, not a universal export policy.

With start fixed at 2026-09-01T00:00:00Z, the expected range checks are:

End input Elapsed duration Expected handling
2026-09-30T00:00:00Z 29 days Within the limit.
2026-10-01T00:00:00Z 30 days Within the limit, including the boundary.
2026-10-02T00:00:00Z 31 days Reject this request and explain the limit.
Missing Unknown Request the end timestamp before judging the range.
2026-09-01T00:00:00Z 0 days Reject: the interval is empty.
2026-08-31T00:00:00Z -1 day Reject: the end precedes the start.
2026-10-01T00:00:01Z 30 days and 1 second Reject: do not truncate elapsed time to whole days.
not-a-timestamp Invalid Reject the invalid value before calculating a duration.
2026-09-30T00:00:00 No explicit timezone Reject this timestamp and request an explicit UTC value; do not assume a timezone.

For the 31-day request, a native MCP tool result can carry an application error as text:

{
  "isError": true,
  "content": [
    {
      "type": "text",
      "text": "{\"errorCategory\":\"business\",\"errorCode\":\"RANGE_TOO_LARGE\",\"isRetryable\":false,\"explanation\":\"The requested interval is 31 UTC days; this export permits at most 30. Provide an approved narrower interval or request review.\"}"
    }
  ]
}

The outer flag reports the tool error; the inner fields explain its meaning. A supported customer message is: "This export was not completed because the requested interval exceeds the 30-day limit. Please provide an approved narrower interval or request review." It must not claim that an export file exists. Splitting the request to evade a restriction is not a valid recovery merely because each smaller call would parse. The original source-shaped inner text object is {"error":"BusinessRuleViolation","retriable":false,"explanation":"The requested data export exceeds the maximum allowed date range of 30 days. Please narrow your date range and try again."}. A consumer must explicitly map that declared retriable flag if it instead uses the teaching isRetryable field above; the names are not automatically interchangeable or native loop controls.

The timestamps and durations should be recomputed before using this expected-result table. A date-only rule with inclusive calendar days would be a different contract and could produce a different count.

Distinguish no matches from no access

Suppose a separate search contract returns query_completed: true and items: [] after successfully searching the authorized scope. That is a valid empty result: no matches in the stated scope. It does not prove the record is absent from every possible system.

A timeout, an authorization failure or an unreadable source is not an empty search result. Keep the failure visible and avoid reporting "no matching records" when the search never completed. An empty content array or an absent error flag alone may be insufficient; inspect the tool's documented success shape and execution status.

Truncated or file-referenced results need similar care. Follow the supported artifact reference if authorized, retain a partial-result marker and do not turn a missing tail into proof that nothing else exists.

Recover locally and propagate unresolved scope

A worker can handle a safe transient read failure locally under a bounded retry policy. If recovery fails, return the error category, completed portion, partial evidence, attempts made and specific remaining dependency to the coordinator. Do not restart successful partitions unnecessarily.

For an uncertain write, local recovery first checks destination state or the operation's request identity. A generic timeout retry can duplicate a side effect. Resume only when the environment and authorization permit it, and retain failed-attempt consumption in accounting. When recovery or cross-worker access diagnosis needs it, retain the necessary nonsecret workspace/account/worker identity and, where credentials are relevant, only a credential identity or an approved secret-store reference. Do not copy actual keys, tokens, or passwords into prompts, logs, or handoff records. Knowing a reference or sharing configuration does not by itself authorize retrieving a secret, using credentials, or executing a tool; use an already authorized context or report blocked and seek authorized help rather than switching accounts or guessing access.

The coordinator should report whether the requested result is complete, partial, blocked or failed. A worker's final text after an API error may contain useful partial findings; it is not automatically a complete answer. Validate actual results instead of treating the presence of text as success.

Preserve the exact interface and lifecycle

In the cited MCP schema, CallToolResult.isError is optional and omission is interpreted as false. The cited normative wording says tool-origin errors SHOULD be reported in result content with isError: true; the source's stronger mandatory language should not erase that distinction. Clients SHOULD expose execution errors and MAY expose protocol errors. Neither false/unset nor an empty array proves a correct completed domain query.

Three envelopes are distinct: native MCP CallToolResult.isError, connector mcp_tool_result.is_error, and Messages client-tool tool_result.is_error. An adapter must preserve the actual error value, content and matching request identifier. Keep the initiating assistant message and return every result with its actual tool_use_id, in the supported user-turn result-first ordering before additional text. Where the API requires received thinking and redacted_thinking blocks, preserve all blocks opaquely, unchanged and in order, including empty signed blocks. This is transport preservation, not permission to reveal or reconstruct private reasoning. The source connector success shape is {"type":"mcp_tool_result","tool_use_id":"example_mcp_1","is_error":false,"content":[{"type":"text","text":"Hello"}]} with an illustrative matching request ID. A separate client-API result-first teaching turn is {"role":"user","content":[{"type":"tool_result","tool_use_id":"example_call_1","is_error":true,"content":"Requested range exceeds the allowed limit."},{"type":"text","text":"What should I do next?"}]} immediately after its actual initiating assistant tool request. The original displayed JSON includes a comment placeholder and does not supply that complete assistant request, so it is not runnable strict JSON or a complete loop. The source opaque-block violation example gives HTTP 400 invalid_request_error and a position such as messages.1.content.0; that diagnostic belongs to the supporting API, not every MCP failure.

For the source hook snapshot, validation rejection happens before execution and fires neither PreToolUse nor PostToolUseFailure; permission denial fires PreToolUse but not PostToolUseFailure; a tool that starts then fails can fire the failure hook with tool_name, tool_input and error details. These are interface/version-specific lifecycle rules. Missing failure events do not establish success. The same source snapshot returns pre-execution validation failures as tool_use_error and separately says built-in output-schema mismatches are ignored while MCP output is passed through without output-schema validation. Those output policies are client-specific; they must not be mistaken for evidence that the returned content is valid or that input validation did not occur.

The source _meta["anthropic/requiresUserInteraction"]: true contract requires real user interaction despite the listed acceptEdits, auto or bypassPermissions modes. Its dontAsk path denies, and its --permission-prompt-tool path cannot substitute an automated allow. Preserve the explicit denial and seek the actual supported authorized path; repeating the call or changing its error flag does not repair permission.

Validate schemas and diagnose adapter errors

An illustrative corrected JSON schema is {"type":"object","properties":{"text":{"type":"string"},"count":{"type":"integer","minimum":0}},"required":["text"]}. Text is required; count is optional, but when supplied must be an integer at least zero. {"text":"hello"} and {"text":"hello","count":0} meet this structural contract; {"text":"hello","count":-1} does not. The source's trailing-comma listing is not strict JSON and its decorator signature is not a complete validator. The source conversion account says supported combinators can be nested under properties but not placed at the root; its additional statement that root-combinator tools remain available does not prove the unsupported schema will validate. Scope that claim, schema subset and type mapping to the actual selected API/SDK. Under this same schema, omitted count is valid, but supplied null, true, 1.5 or "0" fails the integer constraint; count=-1 fails the lower bound. Missing text or nonstring text is invalid. JSON Schema integer is a mathematical integer: 2.0 has an integer value and is not rejected merely for its decimal spelling. These are expected structural judgments, not executed MCP validation. The supplied glossary establishes terminology, while the Dxx domain documents remain the primary factual sources. Glossary entries and candidate metadata do not certify an actual schema, configuration, tool registration, or current runtime behavior.

The cited MCP-version account uses a nonnull JSON Schema object, a default 2020-12 dialect if $schema is absent, 1–128-character tool-name bounds and ASCII letters, digits, underscores, hyphens and dots as its stated name convention. It says names SHOULD NOT contain spaces/commas/other special characters; do not silently strengthen recommended wording into a different universal protocol rule. Retain its MUST/SHOULD distinctions, including recommended case sensitivity/uniqueness. A parameterless {"type":"object","additionalProperties":false} accepts only an empty object; bare {"type":"object"} permits extra properties. Optional title/icons/annotations are not execution guarantees. The native MCP tool-definition key is inputSchema, distinct from the Messages custom-tool input_schema spelling. In the cited version account, valid nonnull JSON Schema objects and the inclusive 1–128-character name length are MUST requirements; case sensitivity and per-server uniqueness are SHOULD recommendations. Do not flatten those strengths into either one universal prohibition or one optional hint.

For a local teaching-only name-shape check, the inputs below are actual ASCII strings and length is their derived integer character count, not a caller-supplied numeric length. The cited source length bound is inclusive: 1 <= characters <= 128. This check reports whether that length condition is met; it does not claim how an actual server rejects, truncates, or otherwise handles an overlong name. It also does not establish uniqueness, recommended character conventions, a complete tool schema, or registration.

Actual name input Derived ASCII characters Expected local length-shape result
"" 0 outside the cited length bound
"A" 1 within the cited length bound
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" 127 within the cited length bound
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" 128 within the cited length bound
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" 129 outside the cited length bound

A missing name leaves no string to validate and requires clarification. In this local teaching contract, null, boolean true or false, and numbers such as 0, -1, or 1.5 are wrong input types, not names with those lengths; no implicit string conversion occurs. A one-character string such as "0" has length 1 and meets only the length condition. The empty string is a concrete zero-length input; a negative string length cannot be derived. These are expected local classifications, not observed MCP/client responses.

The source names Python UnsupportedMCPValueError, Go UnsupportedValueError and Java/C# AnthropicInvalidDataException for unsupported values/content/MIME or unresolved resources in particular conversion libraries. Inspect the actual incompatible value, resolve only permitted supported resources, retain provenance, convert and validate the real result before continuing. An unchanged model retry cannot repair an incompatible adapter.

Upstream HTTP/API errors have their own structured error.type, message and diagnostic request_id account. The source gives SDK-specific typed/status examples such as Python NotFoundError and Go status branching. Use the actual supported structured exception/status, handle more specific cases first and retain unknown new types. Fragile message matching should not determine business success. Catching an exception also does not prove an external write rolled back. The source 404 mapping specifically names Python anthropic.NotFoundError, Ruby Anthropic::Errors::NotFoundError, Java com.anthropic.errors.NotFoundException and Go *anthropic.Error with StatusCode branching. These are attributed SDK/language examples whose installed support must be checked, not one exception class shared by all clients.

The source beta runner/model IDs, connector URL/beta strings and wrapper signatures are illustrative compatibility claims, not live verified configurations. YOUR_TOKEN is a placeholder, not a real secret or an approved storage mechanism. A TypeScript-labeled listing mixes JavaScript const with Python arguments/comprehensions and is not runnable as labeled. Its concrete connector sample uses model="claude-opus-5", server type="url", name="example-mcp", URL https://example-server.modelcontextprotocol.io/sse, authorization_token="YOUR_TOKEN", tools=[{"type":"mcp_toolset","mcp_server_name":"example-mcp"}] and betas=["mcp-client-2025-11-20"]. Separately, the source lists MCP tools and converts them through async_mcp_tool or mcp_tool into client.beta.messages.tool_runner, then awaits runner.until_done(). These are unverified source fragments, not a complete supported call, an available model, a verified endpoint or permission to install/connect anything.

Keep discovery retries, persistence and routing extensions scoped

The source describes eligible post-connection tools/list, prompts/list and resources/list requests retried up to three times with short backoff, excluding authentication, 4xx and request-timeout cases. Its tips instead say “exactly three”; preserve that inconsistency and observe the actual policy/attempts rather than invent whether the initial request is included. These discovery rules are not a replay policy for every tool, and exhaustion proves unresolved failure rather than a permanent outage.

The same source describes absent model-visible failed-connection notices when search is disabled, under custom ANTHROPIC_BASE_URL, ENABLE_TOOL_SEARCH=false and the named Amazon Bedrock, Google Cloud Agent Platform and Microsoft Foundry configurations. These are supporting-client snapshot claims. Inspect actual client diagnostics; absence of a notice is not connection success or a timeless provider support matrix.

The source tool-list extension _meta["anthropic/maxResultSizeChars"] raises a per-tool persist-to-disk threshold with a stated 500,000-character ceiling. Persistence as a file reference differs from truncation, an execution error and context capacity. Obtain the actual authorized file content needed for diagnosis; do not retry a valid large response merely because it is referenced. Character counts are not token limits.

The source HTTP extension x-mcp-header maps a parameter such as region: "us-west1" to Mcp-Param-Region. Only an implemented supporting client/server can perform this mapping. Validate the real permitted environment value and transport; a header-shaped string does not repair arbitrary routing failures.

Complete the range example and worker recovery states

For the invented range contract above, a completed authorized exactly-30-day export could return {"status":"completed","export_id":"EXAMPLE-R7","interval_start":"2026-09-01T00:00:00Z","interval_end":"2026-10-01T00:00:00Z","record_count":0,"artifact_ref":"authorized://exports/EXAMPLE-R7"}. The identifier/reference are invented expected teaching values, not an actual artifact. Zero records is legitimate only after the query/export actually completed under this declared result contract. A real implementation must define its own supported resolvable artifact mechanism. The source parameterless export sample supplies no range or existing state and therefore cannot demonstrate the advertised date validation. Concretely, that source names DATA_EXPORT_v2 and invokes it with {} under inputSchema={"type":"object","additionalProperties":false}. Neither the invocation nor defined prior state supplies start/end dates; a range judgment cannot be inferred from those empty inputs.

For source v2.1.199, foreground API failure may return previously produced text plus a cutoff note; no-text or tool-calls-only failure is distinguished by Agent terminated early due to an API error. The background path marks failure and includes last output. Preserve mode, real retained effects and validated partial results; no text does not prove no work occurred and last text is not completion. The same snapshot contrasts pre-v2.1.199 tools-only interruptions, which could return an empty partial result with only a cutoff note, with the newer explicit error detail. Retain the version/mode distinction instead of assuming an empty old result proved that no side effect occurred.

An implemented asynchronous queue/receipt can isolate step recovery. A heartbeat policy needs a declared clock, timeout and real liveness state; the source supplies no universal duration. A stale heartbeat never authorizes guessing a missing dependency or repeating unknown live effects. Continue only independent permitted work with an explicit gap, or reconcile/cancel/resume through the actual supported mechanism.

Reserve a conservative cost/token ceiling before expensive retry or fan-out using one declared unit. Reconcile actual incurred usage, including failed attempts, and release only verified unused reservation. Tokens and currency require an explicit conversion before comparison. A receipt is signed or tamper-evident only if an actual integrity mechanism is implemented and verified; ordinary JSON fields or timestamps do not supply that property.

A declared application-owned classification contract

The following is a custom teaching contract for this application's error classifier. It adds no MCP fields or MCP defaults. First use the actual supported native/API envelope to identify the outcome: a genuine tool failure can enter this classifier; a JSON-RPC error stays on the protocol/client repair path. A normal successful MCP result does not need errorCategory, isRetryable or retriable, and their absence must not turn success into an error or a hold. Its actual domain result still needs validation, as the completed-search example explains. An omitted native isError has the cited protocol-assumed-false meaning, independently of this custom classification policy.

For an already identified tool failure, this application parses a designated error JSON text payload, not arbitrary prose or every text block. The application's inner object requires four fields: errorCategory is exactly one of transient, validation, business, or permission; errorCode and explanation are nonempty JSON strings after trimming; and isRetryable is a JSON boolean. The optional nextStep, if supplied, must also be a nonempty string. Additional fields remain diagnostic data and cannot change these rules. This example chooses these names and values for its own producer/consumer agreement; other actual tools need their own declared contract and adapter.

For the source-shaped {"error":"BusinessRuleViolation","retriable":false,"explanation":"The requested data export exceeds the maximum allowed date range of 30 days. Please narrow your date range and try again."}, an explicitly selected adapter can map error to errorCode: "BusinessRuleViolation", map this known error to errorCategory: "business", copy the exact explanation, and map the actual boolean retriable: false to isRetryable: false. That mapping is application-owned, not an MCP conversion rule. If no mapping is selected, the source error kind is unknown, retry flags conflict, or the supplied value is string "false", leave that mapping unresolved instead of guessing.

This classifier emits six fields for the failure cases below: native_outcome, metadata_status, category, retry_hint, recovery_state, and automatic_retry_dispatched. native_outcome: "tool_error" preserves the already observed failure; metadata validation cannot change it to success. Missing designated metadata gives metadata_status: "missing"; a valid nonempty but unrecognized category string gives "unknown_category"; invalid JSON, a non-object payload, missing required fields or wrong/empty field values give "malformed". Validate the required field types and nonempty strings before interpreting a well-formed category string. These three states all produce null category/hint and recovery_state: "hold_for_diagnosis" under this application's explicit policy. Preserve sanitized raw evidence and the correlation ID separately for diagnosis; a hold is not proof that no external side effect occurred.

For valid metadata, the output preserves the actual category and boolean. Only transient with boolean true gives "consider_bounded_retry"; boolean false or any nontransient category gives "stop_unchanged_replay". Thus even a well-formed validation error with a true hint does not authorize repeating invalid input. Corrected input, permission repair or an approved new business request remains a separate action. The classifier does not execute any action, so every example has automatic_retry_dispatched: false. Considering retry still requires the real consumer to verify trusted authorization, bounded attempts/time/resources, safe repetition or implemented idempotence, and any unknown prior write outcome. Neither the error text nor a retry hint provides those permissions or guarantees that a model stops.

These complete input/output pairs are static expected teaching fixtures after a real failure has been recognized. The input object is the designated inner error metadata, not the outer MCP result. They are not observed MCP responses, live retries or proof of completed exports.

[
  {
    "case": "transient_boolean_true",
    "input": {"errorCategory":"transient","errorCode":"SERVICE_UNAVAILABLE","isRetryable":true,"explanation":"The service was unavailable for this request."},
    "expected": {"native_outcome":"tool_error","metadata_status":"valid","category":"transient","retry_hint":true,"recovery_state":"consider_bounded_retry","automatic_retry_dispatched":false}
  },
  {
    "case": "business_boolean_false",
    "input": {"errorCategory":"business","errorCode":"RANGE_TOO_LARGE","isRetryable":false,"explanation":"The requested interval is 31 UTC days; this export permits at most 30."},
    "expected": {"native_outcome":"tool_error","metadata_status":"valid","category":"business","retry_hint":false,"recovery_state":"stop_unchanged_replay","automatic_retry_dispatched":false}
  },
  {
    "case": "validation_true_does_not_override_cause",
    "input": {"errorCategory":"validation","errorCode":"INVALID_COUNT","isRetryable":true,"explanation":"count must be an integer at least zero."},
    "expected": {"native_outcome":"tool_error","metadata_status":"valid","category":"validation","retry_hint":true,"recovery_state":"stop_unchanged_replay","automatic_retry_dispatched":false}
  },
  {
    "case": "permission_false_needs_real_access_repair",
    "input": {"errorCategory":"permission","errorCode":"ACCESS_DENIED","isRetryable":false,"explanation":"The authenticated identity lacks access to this resource."},
    "expected": {"native_outcome":"tool_error","metadata_status":"valid","category":"permission","retry_hint":false,"recovery_state":"stop_unchanged_replay","automatic_retry_dispatched":false}
  },
  {
    "case": "designated_metadata_absent",
    "input": null,
    "expected": {"native_outcome":"tool_error","metadata_status":"missing","category":null,"retry_hint":null,"recovery_state":"hold_for_diagnosis","automatic_retry_dispatched":false}
  },
  {
    "case": "unknown_category_is_not_inferred_retryable",
    "input": {"errorCategory":"quota","errorCode":"UNRECOGNIZED_QUOTA_CONDITION","isRetryable":true,"explanation":"An unfamiliar quota condition was returned."},
    "expected": {"native_outcome":"tool_error","metadata_status":"unknown_category","category":null,"retry_hint":null,"recovery_state":"hold_for_diagnosis","automatic_retry_dispatched":false}
  },
  {
    "case": "string_false_is_not_boolean_false",
    "input": {"errorCategory":"business","errorCode":"RANGE_TOO_LARGE","isRetryable":"false","explanation":"The range exceeds the stated limit."},
    "expected": {"native_outcome":"tool_error","metadata_status":"malformed","category":null,"retry_hint":null,"recovery_state":"hold_for_diagnosis","automatic_retry_dispatched":false}
  },
  {
    "case": "required_field_missing",
    "input": {"errorCategory":"business","errorCode":"RANGE_TOO_LARGE","explanation":"The range exceeds the stated limit."},
    "expected": {"native_outcome":"tool_error","metadata_status":"malformed","category":null,"retry_hint":null,"recovery_state":"hold_for_diagnosis","automatic_retry_dispatched":false}
  },
  {
    "case": "description_wrong_type",
    "input": {"errorCategory":"transient","errorCode":"SERVICE_UNAVAILABLE","isRetryable":true,"explanation":null},
    "expected": {"native_outcome":"tool_error","metadata_status":"malformed","category":null,"retry_hint":null,"recovery_state":"hold_for_diagnosis","automatic_retry_dispatched":false}
  }
]

In particular, valid boolean false preserves a known nonreplay decision, whereas string "false" leaves this custom classification malformed. Both keep the observed native failure visible, but their diagnostic meanings differ. Unknown classification is not automatically transient. The actual protocol outcome, application classification, and authorized execution decision remain three separate layers.

Summary

Structured errors support cause-specific recovery. Preserve the native protocol contract, distinguish application metadata from MCP fields and classify the actual failure before retrying. Successful empty results, access failures and partial results carry different meanings that must survive every handoff.

PUBLIC BETA OFFER

Save 50% off on an Eligible Learning Plan

Valid for 1-month plan, 3-month plan, 12-month plan · Code LPXBETA50 · Ends Dec 6, 2026

Ready to put this into practice?

Start guided practice →