Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): structure MCP operation failures (#2991)

Colton Paddena37938d3d225
diff --git a/.changeset/mcp-structured-operation-errors.md b/.changeset/mcp-structured-operation-errors.md
new file mode 100644
index 000000000..8fa3487da
--- /dev/null
+++ b/.changeset/mcp-structured-operation-errors.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+MCP tool calls that are rejected now return `structuredContent.error` with a stable `code` (`invalid_input`, `not_found`, `conflict`, `internal`), a short `message`, and `retryable`, so clients can act without parsing text. Unexpected server failures no longer forward their raw message; they return an `errorId` that correlates with eve's logs.
diff --git a/docs/channels/mcp.mdx b/docs/channels/mcp.mdx
index e12c9c909..6cc24908a 100644
--- a/docs/channels/mcp.mdx
+++ b/docs/channels/mcp.mdx
@@ -191,10 +191,14 @@ The invocation response is discriminated by `status`:
- `failed`: inspect the structured `error`.
- `cancelled`: cancellation reached a terminal state.
-A tool result with `isError: true` means the call itself was rejected (unknown invocation, no input
-pending, incomplete response batch, invalid output schema). A `failed` status means the call
-succeeded and the task itself failed. Handle them differently: correct the call in the first case,
-report the task failure in the second.
+A tool result with `isError: true` means the call itself was rejected. A `failed` status means the call succeeded and the task itself failed. Handle them differently: correct the call in the first case, report the task failure in the second. Rejected calls carry `structuredContent.error` with a stable `code`, a short `message`, and `retryable`:
+
+| `code` | Meaning | `retryable` |
+| --------------- | ------------------------------------------------------------------------------ | ----------- |
+| `invalid_input` | An argument was rejected, for example an oversized or external `outputSchema`. | `false` |
+| `not_found` | The invocation does not exist, has expired, or belongs to another caller. | `false` |
+| `conflict` | The invocation is not in the expected state; read it with `agent_get` first. | `true` |
+| `internal` | eve failed; `errorId` correlates with server logs. No details are exposed. | `false` |
Cancellation is cooperative, so call `agent_get` after `agent_cancel` until the state becomes terminal.
diff --git a/packages/eve/src/internal/mcp/streamable-http-server.test.ts b/packages/eve/src/internal/mcp/streamable-http-server.test.ts
index 1cbc20e7f..f9cac1f50 100644
--- a/packages/eve/src/internal/mcp/streamable-http-server.test.ts
+++ b/packages/eve/src/internal/mcp/streamable-http-server.test.ts
@@ -7,6 +7,7 @@ import {
defineMcpTool,
MCP_LEGACY_PROTOCOL_VERSION,
MCP_PROTOCOL_VERSION,
+ McpToolOperationError,
} from "#internal/mcp/streamable-http-server.js";
const MCP_PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion";
@@ -271,6 +272,95 @@ describe("stateless MCP Streamable HTTP server", () => {
expect(call).not.toHaveBeenCalled();
});
+ it("returns structured operation errors for expected tool failures", async () => {
+ const handle = createMcpStreamableHttpServer({
+ authenticate: async () => auth,
+ name: "eve-test",
+ tools: [
+ defineMcpTool({
+ call: async () => {
+ throw new McpToolOperationError("conflict", "Invocation is not waiting for input.");
+ },
+ definition: { inputSchema: z.strictObject({}), name: "conflicting" },
+ }),
+ ],
+ version: "0.0.0",
+ });
+
+ for (const request_ of [
+ modernRequest({
+ id: "modern",
+ jsonrpc: "2.0",
+ method: "tools/call",
+ params: { arguments: {}, name: "conflicting" },
+ }),
+ request({
+ id: "legacy",
+ jsonrpc: "2.0",
+ method: "tools/call",
+ params: { arguments: {}, name: "conflicting" },
+ }),
+ ]) {
+ await expect(jsonRpcResponse(await handle(request_))).resolves.toMatchObject({
+ result: {
+ content: [{ text: "Invocation is not waiting for input.", type: "text" }],
+ isError: true,
+ structuredContent: {
+ error: {
+ code: "conflict",
+ message: "Invocation is not waiting for input.",
+ retryable: true,
+ },
+ },
+ },
+ });
+ }
+ });
+
+ it("sanitizes unexpected tool failures behind an error id", async () => {
+ const handle = createMcpStreamableHttpServer({
+ authenticate: async () => auth,
+ name: "eve-test",
+ tools: [
+ defineMcpTool({
+ call: async () => {
+ throw new Error("ECONNREFUSED 10.0.0.7:5432 while reading secret=abc");
+ },
+ definition: { inputSchema: z.strictObject({}), name: "exploding" },
+ }),
+ ],
+ version: "0.0.0",
+ });
+
+ const body = (await jsonRpcResponse(
+ await handle(
+ modernRequest({
+ id: "boom",
+ jsonrpc: "2.0",
+ method: "tools/call",
+ params: { arguments: {}, name: "exploding" },
+ }),
+ ),
+ )) as {
+ result: {
+ content: Array<{ text: string }>;
+ isError: boolean;
+ structuredContent: { error: Record<string, unknown> };
+ };
+ };
+ expect(body.result.isError).toBe(true);
+ expect(body.result.structuredContent.error).toMatchObject({
+ code: "internal",
+ errorId: expect.any(String),
+ retryable: false,
+ });
+ expect(JSON.stringify(body.result)).not.toContain("ECONNREFUSED");
+ expect(JSON.stringify(body.result)).not.toContain("secret=");
+ expect(body.result.content[0]?.text).toContain(
+ String(body.result.structuredContent.error.errorId),
+ );
+ });
+
it("returns JSON-RPC errors and acknowledges notifications", async () => {
const { handle } = server();
const unknown = await handle(modernRequest({ id: 3, jsonrpc: "2.0", method: "unknown" }));
diff --git a/packages/eve/src/internal/mcp/streamable-http-server.ts b/packages/eve/src/internal/mcp/streamable-http-server.ts
index 9a72c07a6..d42dd3ad2 100644
--- a/packages/eve/src/internal/mcp/streamable-http-server.ts
+++ b/packages/eve/src/internal/mcp/streamable-http-server.ts
@@ -6,6 +6,9 @@ import {
} from "#compiled/@modelcontextprotocol/server/index.js";
import type { SessionAuthContext } from "#channel/types.js";
+import { createLogger, logError } from "#internal/logging.js";
+
+const log = createLogger("mcp.server");
export const MCP_PROTOCOL_VERSION = "2026-07-28";
export const MCP_LEGACY_PROTOCOL_VERSION = "2025-11-25";
@@ -26,13 +29,46 @@ export interface McpCallToolResult<
> {
readonly content: readonly McpContent[];
readonly isError?: boolean;
- readonly structuredContent?: TStructured;
+ readonly structuredContent?: TStructured | McpToolOperationErrorEnvelope;
+}
+
+export interface McpToolOperationErrorEnvelope {
+ readonly error: McpToolOperationErrorData;
}
export type McpContent =
| { readonly type: "text"; readonly text: string }
| { readonly type: "resource_link"; readonly name: string; readonly uri: string };
+/**
+ * Stable, client-actionable reason a tool call was rejected before it could
+ * return a result. `invalid_input` and `conflict` mean the caller should
+ * change or re-read something; `not_found` means stop; `internal` means the
+ * server failed and `errorId` correlates with its logs.
+ */
+export type McpToolOperationErrorCode = "invalid_input" | "not_found" | "conflict" | "internal";
+
+export interface McpToolOperationErrorData {
+ readonly code: McpToolOperationErrorCode;
+ readonly errorId?: string;
+ readonly message: string;
+ readonly retryable: boolean;
+}
+
+/** Thrown by tool handlers to produce a structured `isError` result. */
+export class McpToolOperationError extends Error {
+ readonly code: McpToolOperationErrorCode;
+
+ constructor(code: McpToolOperationErrorCode, message: string) {
+ super(message);
+ this.name = "McpToolOperationError";
+ this.code = code;
+ }
+}
+
+/** Only `conflict` is retryable: the caller re-reads state and tries again. */
+const RETRYABLE_CODES: ReadonlySet<McpToolOperationErrorCode> = new Set(["conflict"]);
+
export interface McpServerTool {
readonly name: string;
register(server: McpServer, auth: SessionAuthContext | null): void;
@@ -327,15 +363,35 @@ async function callTool<TInput, TStructured extends Readonly<Record<string, unkn
try {
return await call(input, { auth, signal });
} catch (error) {
- return toolError(error instanceof Error ? error.message : "Tool call failed.");
+ if (error instanceof McpToolOperationError) {
+ return toolError({
+ code: error.code,
+ message: error.message,
+ retryable: RETRYABLE_CODES.has(error.code),
+ });
+ }
+ // Unexpected failures never forward their message: it may carry provider
+ // responses, hostnames, or workflow payloads. The errorId is the handle.
+ const errorId = logError(log, "MCP tool call failed", error);
+ return toolError({
+ code: "internal",
+ errorId,
+ message: "The server could not complete this tool call.",
+ retryable: false,
+ });
}
}
function toolError<TStructured extends Readonly<Record<string, unknown>>>(
- message: string,
+ error: McpToolOperationErrorData,
): McpCallToolResult<TStructured> {
+ const text =
+ error.errorId === undefined ? error.message : `${error.message} (errorId: ${error.errorId})`;
+ // The SDK skips outputSchema validation when isError is set, so this shape
+ // does not need to appear in each tool's declared output schema.
return {
- content: [{ type: "text", text: message }],
+ content: [{ type: "text", text }],
isError: true,
+ structuredContent: { error },
};
}
diff --git a/packages/eve/src/public/channels/mcp.test.ts b/packages/eve/src/public/channels/mcp.test.ts
index 96f07d960..55a856b65 100644
--- a/packages/eve/src/public/channels/mcp.test.ts
+++ b/packages/eve/src/public/channels/mcp.test.ts
@@ -244,6 +244,13 @@ describe("mcpChannel", () => {
},
],
isError: true,
+ structuredContent: {
+ error: {
+ code: "invalid_input",
+ message: "outputSchema external $ref values are not supported.",
+ retryable: false,
+ },
+ },
},
});
expect(createSession).not.toHaveBeenCalled();
diff --git a/packages/eve/src/public/channels/mcp.ts b/packages/eve/src/public/channels/mcp.ts
index 5df260de0..651cf39ef 100644
--- a/packages/eve/src/public/channels/mcp.ts
+++ b/packages/eve/src/public/channels/mcp.ts
@@ -20,6 +20,7 @@ import { validateMcpHttpRequest, validateMcpMetadataRequest } from "#internal/mc
import {
createMcpStreamableHttpServer,
defineMcpTool,
+ McpToolOperationError,
type McpCallToolResult,
type McpServerTool,
} from "#internal/mcp/streamable-http-server.js";
@@ -523,8 +524,15 @@ function createInvocationTools(
return tools;
}
+// Unknown, expired, and foreign-principal invocations all read as not found
+// so the response never confirms that another caller's invocation exists.
+const INVOCATION_NOT_FOUND =
+ "Invocation not found. It may have expired or belong to another caller.";
+
function requiredInvocation(invocation: AgentInvocation | undefined): AgentInvocation {
- if (invocation === undefined) throw new Error("Invocation not found.");
+ if (invocation === undefined) {
+ throw new McpToolOperationError("not_found", INVOCATION_NOT_FOUND);
+ }
return invocation;
}
@@ -533,9 +541,12 @@ function requiredMutation(result: AgentInvocationMutationResult): AgentInvocatio
case "success":
return result.invocation;
case "conflict":
- throw new Error(result.message);
+ throw new McpToolOperationError(
+ "conflict",
+ `${result.message} Call agent_get to read the current state before answering again.`,
+ );
case "not_found":
- throw new Error("Invocation not found.");
+ throw new McpToolOperationError("not_found", INVOCATION_NOT_FOUND);
}
}
@@ -549,9 +560,16 @@ function invocationResult(invocation: AgentInvocation): McpCallToolResult {
function asJsonObject(value: unknown): JsonObject | undefined {
if (value === undefined) return undefined;
- const schema = parseJsonObject(value);
- validateOutputSchemaComplexity(schema);
- return schema;
+ try {
+ const schema = parseJsonObject(value);
+ validateOutputSchemaComplexity(schema);
+ return schema;
+ } catch (error) {
+ throw new McpToolOperationError(
+ "invalid_input",
+ error instanceof Error ? error.message : "outputSchema must be a JSON object.",
+ );
+ }
}
const AUTHORIZATION_CHALLENGE_SCHEMA = z.strictObject({