Repository navigation
Closed
Description
Context
Today, when an MCP tool call fails, callers usually see one of two things:
- An
McpErrorthrown by a tool (for exampleSTALE_HEAD,PRECONDITION_FAILED) that carries only acode, amessageand an HTTP-likestatus. - Anything else (a GitHub
RequestError, a Knex error, a Zod error, a timeout, a queue failure) whichMcpOperations.runinpackages/api/mcp/operations.tscollapses into a single opaque value:
{ "error": { "code": "OUTCOME_UNKNOWN", "message": "Outcome uncertain. Inspect the target before issuing a new action." } }This is exactly what happened repeatedly with publish_plan: the plan failed, the receipt said OUTCOME_UNKNOWN, and nobody could tell whether GitHub rejected the request, the database was locked, or the process was restarted. An agent cannot relay anything useful to the user from that.
This issue is the foundation for the whole "observable MCP surface" epic. Later issues (operation lifecycle, publish failure detail, merge precondition detail, preview tools, docs tools) all throw and store errors through the envelope introduced here, so it must land first.
Requirements
- Define one error envelope type used for every failed MCP tool call (mutating or read-only) and for every stored operation failure:
interface McpErrorEnvelope { code: string; // stable, UPPER_SNAKE_CASE, documented message: string; // human readable, safe to show the user stage: McpErrorStage | null; // where it failed, when known retryable: boolean; // is it safe to call again with a NEW idempotency key? status: number; // HTTP-like status (400/403/404/409/429/5xx) details?: Record<string, unknown>; // optional structured, redacted detail cause?: { code: string; message: string }; // for OUTCOME_UNKNOWN: what actually happened underneath }
- Extend
McpError(inpackages/api/mcp/config.ts) so that tools can attachstage,retryableanddetailswithout changing any existing call site (all new arguments optional, existingnew McpError(code, message, status)keeps working). - Add a single classifier
classifyError(error, { sideEffectsPossible })that maps:McpError→ its own fields.- Zod validation errors →
INVALID_INPUT, stagevalidation, not retryable,details.issues(path + message only). - Octokit/GitHub
RequestErrors →GITHUB_AUTH_FAILED(401),GITHUB_FORBIDDEN(403),GITHUB_RATE_LIMITED(403/429 with rate-limit headers, retryable),GITHUB_NOT_FOUND(404),GITHUB_REJECTED(409/422, with GitHub'smessageanderrors[].message),GITHUB_UNAVAILABLE(5xx, retryable); stagegithub. - Network/time-out errors (
ECONNRESET,ETIMEDOUT,ECONNREFUSED,AbortError,TimeoutError) →UPSTREAM_TIMEOUT/UPSTREAM_UNREACHABLE, stagetransport, retryable. - SQLite busy/locked errors (
SQLITE_BUSY,SQLITE_LOCKED) →DATABASE_BUSY, stagedatabase, retryable. - Anything else →
INTERNAL_ERROR, stageinternal, not retryable. - When
sideEffectsPossibleistrue(a mutating tool failed with a non-McpError), the envelope code staysOUTCOME_UNKNOWN(so existing safety semantics are not weakened: never blindly retry a possibly-applied mutation) andretryableis forced tofalse, but the underlying classification is preserved incauseandstage. This is the key change: the caller still learns "GitHub rejected with 422: Validation Failed" instead of nothing.
- All messages and details pass through
redactSecrets/redactDetails. Redaction must remove GitHub tokens (ghp_,gho_,ghs_,ghu_,ghr_,github_pat_),Bearer …values, credentialed git URLs (https://x-access-token:…@), MCP tokens (pia_mcp_…), signed URL query parameters (X-Amz-Signature,token,access_token,signature), and any detail key whose name matches/token|secret|password|authorization|cookie|private.?key|credential/i. Local filesystem paths must never be echoed indetails(strip absolute paths to their basename). McpOperations.runstores the full envelope (result.error) instead of the fixed opaque message.- The MCP transport (
packages/api/mcp/toolExecution.ts/packages/api/mcp/server.ts) returns failed tool calls asisError: truewith both a text content block containing{"error": envelope}andstructuredContent: { error: envelope }so both old and new SDK clients can read it. - The access log (
mcp_access_log.error_code) keeps recording the envelopecode(no payloads, as today).
Implementation Specification
- New file
packages/api/mcp/errorEnvelope.tswithMcpErrorStage,McpErrorEnvelope,classifyError,redactSecrets,redactDetails,toToolErrorResult. - Edit
packages/api/mcp/config.ts→McpErrorgainsstage,retryable,details, andtoEnvelope(). - Edit
packages/api/mcp/operations.ts→ thecatchblock inrunusesclassifyError(error, { sideEffectsPossible: true }). - Edit
packages/api/mcp/toolExecution.ts(theexecuteToolre-exported fromtools.ts) and whereverserver.tsconverts a thrown error into aCallToolResult→ usetoToolErrorResult(classifyError(error, { sideEffectsPossible: false }))for read-only tools and non-operation paths. - New test file
packages/api/test/mcpErrorEnvelope.test.ts. - Add the new file to the
test:mcpscript list if that script enumerates files explicitly.
Acceptance Criteria
- A thrown
new McpError('STALE_HEAD', 'Pull request head changed.', 409)produces{ code: 'STALE_HEAD', stage: null, retryable: false, status: 409 }— no existing call site changed. -
new McpError('CHECKS_PENDING', '…', 409, { stage: 'precondition', retryable: true, details: { pending: 2 } })round-trips all fields. - A GitHub 422 thrown inside a mutating tool yields a stored receipt whose
result.erroris{ code: 'OUTCOME_UNKNOWN', retryable: false, stage: 'github', cause: { code: 'GITHUB_REJECTED', message: 'Validation Failed: …' } }. - A GitHub 422 thrown inside a read-only tool yields
isError: truewithstructuredContent.error.code === 'GITHUB_REJECTED'. - Unit tests prove that
ghp_…,github_pat_…,Bearer abc,https://x-access-token:[email protected]/…,?X-Amz-Signature=…and adetails.accessTokenfield never appear in any envelope. -
npm run test:mcp,npm run typecheck -w @propr/apiand API lint pass.
Created by ProPR AI Planner
Activity
propr-dev commentedon Sep 28, 2026
Suggested Implementation:
Implementation Approach
We centralise error classification in one module (
errorEnvelope.ts) and make every failure path — the operation ledger, the tool executor and the SDK transport — go through it. The alternative of teaching each tool to catch and describe its own failures was rejected: there are ~150 tools, the result would drift, and forgetting one reproduces theOUTCOME_UNKNOWNblack hole we are trying to close. A consistent envelope also means one place to audit for secret leakage.Key decisions:
McpError. Existingnew McpError(code, message, status)calls keep compiling; the new 4th argument is an optional options bag. This lets later issues addstage/retryable/detailsincrementally.OUTCOME_UNKNOWNis kept for mutating tools. A transport failure after a POST to GitHub may already have created the issue/comment. Reporting it as retryable would invite duplicates. We keep the code andretryable: false, but addcause+stageso the agent can still tell the user what failed. This preserves the existing safety contract documented indocs/mcp.md("an interrupted or uncertain external operation is not blindly replayed").detailscould carry anything. We redact by pattern and by key name, and strip absolute paths, before the envelope leaves the process or is persisted.File:
packages/api/mcp/errorEnvelope.ts(new file)Why this file: Single source of truth for the envelope shape, classification rules and redaction. Every other MCP module imports from here, so the rules cannot diverge.
File:
packages/api/mcp/config.tsWhy this file:
McpErroris the error type every tool already throws. Extending it (rather than introducing a second error class) means later issues can add stage/retryable detail to existing throws with a one-line change.Locate
export class McpError extends Errorand replace it with the version below. Keep the existing constructor parameter order.File:
packages/api/mcp/operations.tsWhy this file: This is where the opaque
OUTCOME_UNKNOWNis manufactured today. Storing the classified envelope makes every receipt (get_operation) explain its failure.File:
packages/api/mcp/toolExecution.tsandpackages/api/mcp/server.tsWhy these files:
executeTool(re-exported fromtools.ts) is the single dispatch point for every tool call and access-log record;server.tsregisters tools with the SDK and converts thrown errors intoCallToolResult. Converting there makes the envelope apply to every tool, including read-only ones that never go throughMcpOperations.In
executeTool, wrap the non-operation branch (read-only tools and any code beforeoperations.run) so that thrown values are classified once and re-thrown as anMcpErrorcarrying the envelope:In
server.ts, where the tool callback catches an error and builds the SDK result, replace the ad-hoc text error with:Also when an operation receipt with
statefailed/unknownis returned, includeresult.erroruntouched (it is already an envelope after this change).File:
packages/api/test/mcpErrorEnvelope.test.ts(new file)Why this file: Locks down the public contract (codes, retryable flags) and, most importantly, redaction — regressions there would leak credentials into agent transcripts.
propr-dev commentedon Sep 28, 2026
🤖 AI processing has started for this issue using codex agent with gpt-5.6-sol model.
I'll analyze the problem and work on a solution. This may take a few minutes.
Processing Details:
codexgpt-5.6-sol2593/gpt-5.6-sol-mcp-introduce-a-structure-20260928-2357-n392593-epic-mcp-observability-cf6issue-2593-20260928-2357-gpt-5.6-sol-n39🔍 Track Task Execution
fix(ai): Resolve issue #2593 - MCP: introduce a structured error enve…
fix(ai): Resolve issue #2593 - MCP: introduce a structured error enve…