diff --git a/server/src/__tests__/tool-gateway.test.ts b/server/src/__tests__/tool-gateway.test.ts index 81d7751a28b..f5a4342cf3b 100644 --- a/server/src/__tests__/tool-gateway.test.ts +++ b/server/src/__tests__/tool-gateway.test.ts @@ -678,6 +678,38 @@ describeEmbeddedPostgres("tool gateway acceptance", () => { } }); + it.each([ + [{ content: [{ type: "text", text: "Allowance used." }], structuredContent: { code: "usage_limit_reached", retryability: "later" }, isError: true }, + { toolCode: "usage_limit_reached", retryable: true }], + [{ content: [{ type: "text", text: "Busy now (code: busy_now, retryable)" }], isError: true }, { toolCode: "busy_now", retryable: true }], + [{ content: [{ type: "text", text: "Search denied: outside consented tag" }], isError: true }, {}], + ])("attaches the tool's own error code and retryability to a session tool_error: %#", async (result, expected) => { + const company = await createCompany(db); + const agent = await createAgent(db, company.id); + const { run } = await createIssueAndRun(db, company.id, agent.id); + const remote = await startFakeRemoteMcpServer(({ body }) => ({ body: { jsonrpc: "2.0", id: body?.id, result } })); + try { + const { application, connection, catalogEntry } = await createRemoteMcpTool(db, company.id, { + url: remote.url, toolName: "query_rows", riskLevel: "read", + }); + await db.update(toolCatalogEntries).set({ + inputSchema: { type: "object", properties: {}, additionalProperties: false }, + }).where(eq(toolCatalogEntries.id, catalogEntry.id)); + const toolName = expectedConnectedToolName({ applicationKey: application.applicationKey, + connectionId: connection.id, toolName: catalogEntry.toolName }); + await allowToolsForAgent(db, company.id, agent.id, [toolName]); + const gateway = createTestToolGatewayService(db); + const session = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id }); + const failure = await gateway.executeTool({ sessionToken: session.token, tool: toolName, parameters: {} }) + .catch(error => error); + expect(failure).toMatchObject({ reasonCode: "tool_error" }); + expect({ toolCode: failure.details.toolCode, retryable: failure.details.retryable }).toEqual({ + toolCode: (expected as { toolCode?: string }).toolCode, retryable: (expected as { retryable?: boolean }).retryable }); + } finally { + await remote.close(); + } + }); + it.each(["managed", "mcp-key"])("returns %s GitHub recovery guidance directly to MCP callers without a pending approval", async method => { const company = await createCompany(db); const agent = await createAgent(db, company.id); diff --git a/server/src/services/native-runtime/assigned-mcp-tools.test.ts b/server/src/services/native-runtime/assigned-mcp-tools.test.ts index 67af5f7e069..0075ad2bcb0 100644 --- a/server/src/services/native-runtime/assigned-mcp-tools.test.ts +++ b/server/src/services/native-runtime/assigned-mcp-tools.test.ts @@ -4,7 +4,7 @@ import { setFlagsFromString } from "node:v8"; import { runInNewContext } from "node:vm"; import { describe, expect, it, vi } from "vitest"; import type { Db } from "@paperclipai/db"; -import { ToolGatewayHttpError, type ToolGatewayDescriptor, type ToolGatewayService } from "../tool-gateway.js"; +import { ToolGatewayHttpError, toolResultErrorDetails, toolResultErrorMessage, type ToolGatewayDescriptor, type ToolGatewayService } from "../tool-gateway.js"; import { ASSIGNED_CATALOG_CACHE_BYTES, ASSIGNED_CATALOG_CACHE_ENTRIES, assignedCatalogCacheStats, ASSIGNED_SCHEMA_ADMISSION_CACHE_ENTRIES, ASSIGNED_SCHEMA_LISTING_BUDGET_BYTES, assignedSchemaAdmissionCacheSize, @@ -38,6 +38,10 @@ function fixture(tools: ToolGatewayDescriptor[]) { return { gateway, listToolsForNamedGateway, executeTool, gatewayPublicId: "gateway-fixture", bearerToken: "private-run-token-never-project" }; } +function gatewayToolError(text: string, extra: Record = {}) { + return new ToolGatewayHttpError(502, text, "tool_error", toolResultErrorDetails({ error: text, ...extra })); +} + describe("assigned MCP runner tools", () => { const searchName = "paperclip_search_assigned_tools"; const callName = "paperclip_call_assigned_tool"; @@ -439,7 +443,7 @@ describe("assigned MCP runner tools", () => { expect(discovery).toEqual({ tools: [assigned.definitions()[0]], nextOffset: null }); }); - it.each(["approval_required", "connection_revoked", "tool_error"])("preserves %s through the call wrapper", async reason => { + it.each(["approval_required", "connection_revoked"])("preserves %s through the call wrapper", async reason => { const f = fixture([descriptor("write", "write")]); const assigned = await createAssignedMcpTools(f); const error = new ToolGatewayHttpError(403, "Denied", reason); @@ -686,7 +690,7 @@ describe("assigned MCP runner tools", () => { expect(f.executeTool).toHaveBeenCalledOnce(); }); - it.each(["tool_error", "approval_required", "connection_revoked"])("propagates %s without converting it to success", async reason => { + it.each(["approval_required", "connection_revoked"])("propagates %s without converting it to success", async reason => { const f = fixture([descriptor("recall")]); const error = new ToolGatewayHttpError(403, "Gateway refused execution", reason); f.executeTool.mockRejectedValue(error); @@ -694,6 +698,83 @@ describe("assigned MCP runner tools", () => { await expect(assigned.execute({ tool: assigned.definitions()[0]!.name as string, arguments: {} })).rejects.toBe(error); }); + it.each([ + ["Two reads are already running; wait for them to finish. (code: read_concurrency_limit, retryable)", "read_concurrency_limit", 429], + ['{"object":"error","status":400,"code":"validation_error","message":"Bad property"}', "validation_error", 422], + ["rate_limited: slow down", "rate_limited", 422], + ['Allowance used.\n\n{"error":{"code":"usage_limit_reached","retryability":"later"}}', "usage_limit_reached", 429], + ["Something went wrong", "assigned_tool_error", 422], + ['{"code":"validation_error","retryable":false}', "validation_error", 422], + ["This operation is not retryable (code: validation_error)", "validation_error", 422], + ])("reports a tool's own error with its stable code instead of a server failure: %s", async (detail, code, status) => { + const f = fixture([descriptor("recall")]); + f.executeTool.mockRejectedValue(gatewayToolError(detail)); + const assigned = await createAssignedMcpTools(f); + await expect(assigned.execute({ tool: assigned.definitions()[0]!.name as string, arguments: {} })).rejects.toMatchObject({ + status, reasonCode: "tool_error", message: `${code}: The connected tool reported an error.`, + }); + }); + + it.each([ + [{ isError: true, content: [{ type: "text", text: '{"code":"validation_error","message":"Bad property"}' }] }, "validation_error", 422], + [{ isError: true, content: [{ type: "text", text: "rate_limited: slow down" }] }, "rate_limited", 422], + [{ isError: true, content: [], structuredContent: { code: "quota_exceeded" } }, "quota_exceeded", 422], + [{ isError: true, content: [], structuredContent: { code: "quota_exceeded", retryability: "later" } }, "quota_exceeded", 429], + [{ isError: true, data: { content: [{ type: "text", text: "rate_limited: slow down" }], structuredContent: { retryable: true } } }, "rate_limited", 429], + ])("reads the code from a returned error result's content: %#", async (result, code, status) => { + const f = fixture([descriptor("recall")]); + f.executeTool.mockResolvedValue({ status: "completed", result }); + const assigned = await createAssignedMcpTools(f); + await expect(assigned.execute({ tool: assigned.definitions()[0]!.name as string, arguments: {} })).rejects.toMatchObject({ + reasonCode: "tool_error", status, message: `${code}: The connected tool reported an error.`, + }); + }); + + it("never turns prose into a code and prefers the tool's structured code", async () => { + const f = fixture([descriptor("recall")]); + const assigned = await createAssignedMcpTools(f); + const call = { tool: assigned.definitions()[0]!.name as string, arguments: {} }; + for (const prose of ["validation failed\nreason: missing field", "reason: missing field", "error: invalid input", "code: invalid"]) { + f.executeTool.mockRejectedValueOnce(gatewayToolError(prose)); + await expect(assigned.execute(call)).rejects.toMatchObject({ message: "assigned_tool_error: The connected tool reported an error." }); + } + f.executeTool.mockRejectedValueOnce(gatewayToolError('error: invalid_grant\n{"code":"invalid_grant"}')); + await expect(assigned.execute(call)).rejects.toMatchObject({ message: "invalid_grant: The connected tool reported an error." }); + f.executeTool.mockResolvedValueOnce({ status: "completed", result: { isError: true, + structuredContent: { code: "quota_exceeded" }, content: [{ type: "text", text: '{"code":"upstream_thing"}' }] } }); + await expect(assigned.execute(call)).rejects.toMatchObject({ message: "quota_exceeded: The connected tool reported an error." }); + f.executeTool.mockRejectedValueOnce(new ToolGatewayHttpError(502, "MCP tool returned an error result", "tool_error", + { toolCode: "quota_exceeded", retryable: true })); + await expect(assigned.execute(call)).rejects.toMatchObject({ status: 429, message: "quota_exceeded: The connected tool reported an error." }); + }); + + it.each([ + [new ToolGatewayHttpError(502, "MCP tool returned an error result", "tool_error", { toolCode: "timeout" }), "tool_timeout", 422], + [gatewayToolError("Busy now (code: busy, retryable)"), "tool_busy", 429], + [gatewayToolError('{"object":"error","code":"conflict"}'), "tool_conflict", 422], + ])("keeps a single-word tool code in a form the runner keeps: %#", async (error, code, status) => { + const f = fixture([descriptor("recall")]); + f.executeTool.mockRejectedValue(error); + const assigned = await createAssignedMcpTools(f); + await expect(assigned.execute({ tool: assigned.definitions()[0]!.name as string, arguments: {} })).rejects.toMatchObject({ + status, message: `${code}: The connected tool reported an error.`, + }); + }); + + it("builds gateway tool error messages and details from MCP results", () => { + expect(toolResultErrorMessage({ isError: true, content: [{ type: "text", text: "(code: validation_error)" }] })) + .toBe("(code: validation_error)"); + expect(toolResultErrorMessage({ isError: true, content: [{ type: "image", data: "x" }] })).toBe("The tool returned an error."); + expect(toolResultErrorMessage({ error: "Denied" }, "Reconnect it.")).toBe("Denied\n\nReconnect it."); + expect(toolResultErrorDetails({ structuredContent: { code: "quota_exceeded", retryability: "later" } })) + .toEqual({ toolCode: "quota_exceeded", retryable: true }); + expect(toolResultErrorDetails({ data: { code: "read_rate_limit", retryable: true } })).toEqual({ toolCode: "read_rate_limit", retryable: true }); + expect(toolResultErrorDetails({ structuredContent: { code: "Not A Code" } })).toEqual({}); + expect(toolResultErrorDetails({ structuredContent: { code: "timeout" } })).toEqual({ toolCode: "timeout" }); + expect(toolResultErrorDetails({ content: "Busy now (code: busy, retryable)", error: "Tool failed" })).toEqual({ toolCode: "busy", retryable: true }); + expect(toolResultErrorDetails({ isError: true, code: "rate_limited" })).toEqual({ toolCode: "rate_limited" }); + }); + it("propagates discovery denial", async () => { const f = fixture([]); const error = new Error("gateway_token_revoked"); @@ -706,7 +787,8 @@ describe("assigned MCP runner tools", () => { const assigned = await createAssignedMcpTools(f); const call = { tool: assigned.definitions()[0]!.name as string, arguments: {} }; f.executeTool.mockResolvedValueOnce({ status: "completed", result: { isError: true, content: [] } }); - await expect(assigned.execute(call)).rejects.toMatchObject({ reasonCode: "tool_error" }); + await expect(assigned.execute(call)).rejects.toMatchObject({ reasonCode: "tool_error", status: 422, + message: "assigned_tool_error: The connected tool reported an error." }); f.executeTool.mockResolvedValueOnce({ status: "pending", result: {} }); await expect(assigned.execute(call)).rejects.toThrow("assigned_mcp_tool_execution_incomplete"); f.executeTool.mockResolvedValueOnce({ status: "replayed", result: { memory: "synthetic" } }); diff --git a/server/src/services/native-runtime/assigned-mcp-tools.ts b/server/src/services/native-runtime/assigned-mcp-tools.ts index 129c579c6a4..7d1c3b1b98f 100644 --- a/server/src/services/native-runtime/assigned-mcp-tools.ts +++ b/server/src/services/native-runtime/assigned-mcp-tools.ts @@ -2,7 +2,7 @@ import { createHash } from "node:crypto"; import type { Db } from "@paperclipai/db"; import { logger } from "../../middleware/logger.js"; import { admitToolInputSchema, canonicalToolInputSchema, TOOL_INPUT_SCHEMA_MAX_BYTES } from "../../vendor/paperclip-runner/index.js"; -import { deduplicateToolDescriptors, ToolGatewayHttpError, type ToolGatewayDescriptor, type ToolGatewayService } from "../tool-gateway.js"; +import { deduplicateToolDescriptors, ToolGatewayHttpError, toolResultErrorDetails, type ToolGatewayDescriptor, type ToolGatewayService } from "../tool-gateway.js"; type WorkMode = "standard" | "planning" | "ask" | "skill_test"; type ToolDefinition = Record; @@ -188,6 +188,16 @@ function sha256(value: string): string { return createHash("sha256").update(value).digest("hex"); } +function runnerToolCode(code: string | undefined): string { + if (!code) return "assigned_tool_error"; + return /[_.-]/.test(code) ? code : `tool_${code}`; +} + +export function toolReportedError(details: { toolCode?: string; retryable?: boolean }): ToolGatewayHttpError { + return new ToolGatewayHttpError(details.retryable ? 429 : 422, `${runnerToolCode(details.toolCode)}: The connected tool reported an error.`, + "tool_error", details.retryable ? { retryable: true } : undefined); +} + async function buildAssignedCatalog(identity: string, listing: readonly AssignedListingEntry[]): Promise { const tools = new Map(); const unavailable: Array<{ tool: string; reason: string }> = []; @@ -447,19 +457,27 @@ export async function createAssignedMcpTools(input: { if (!permits(descriptor) || !permits(descriptor, currentWorkMode)) throw new Error("paperclip_runner_tool_mode_denied"); // Reauthorize through the existing gateway on every call. Discovery is // not a grant: revocation, policy, approval, and audit remain server-owned. - const result = await input.gateway.executeTool({ - gatewayPublicId: input.gatewayPublicId, - sessionToken: input.bearerToken, - tool: descriptor.name, - parameters, - }); + let result: Awaited>; + try { + result = await input.gateway.executeTool({ + gatewayPublicId: input.gatewayPublicId, + sessionToken: input.bearerToken, + tool: descriptor.name, + parameters, + }); + } catch (error) { + if (error instanceof ToolGatewayHttpError && error.reasonCode === "tool_error") { + throw toolReportedError({ toolCode: typeof error.details.toolCode === "string" ? error.details.toolCode : undefined, retryable: error.details.retryable === true }); + } + throw error; + } if (result.status !== "completed" && result.status !== "replayed") { throw new Error("assigned_mcp_tool_execution_incomplete"); } // The gateway normally throws provider errors. Keep a malformed or older // provider response from being reported as successful through PRP. if (result.result && typeof result.result === "object" && "isError" in result.result && result.result.isError === true) { - throw new ToolGatewayHttpError(502, "The assigned tool returned an error.", "tool_error"); + throw toolReportedError(toolResultErrorDetails(result.result as Record)); } return result.result; }, diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 56a77d116d1..18caa403fcb 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -485,6 +485,53 @@ export interface ToolGatewaySession { export type ToolGatewayRuntimeSlot = ToolRuntimeSlotView; +export function toolResultErrorMessage(result: Record, failureInstructions?: string): string { + const content = Array.isArray(result.content) + ? result.content.map((item) => (item && typeof item === "object" && typeof (item as { text?: unknown }).text === "string" + ? (item as { text: string }).text : "")).filter(Boolean).join("\n") + : result.content; + const error = typeof result.error === "string" ? result.error : ""; + const message = (typeof content === "string" && content) || error || "The tool returned an error."; + return failureInstructions ? `${message}\n\n${failureInstructions}` : message; +} + + +const TOOL_CODE = "[a-z][a-z0-9_.-]{0,90}"; +const PLUGIN_TOOL_CODE = new RegExp(`\\(code: (${TOOL_CODE})[,)]`); +const JSON_TOOL_CODE = new RegExp(`"code"\\s*:\\s*"(${TOOL_CODE})"`, "g"); +const PREFIX_TOOL_CODE = new RegExp(`^(${TOOL_CODE}):`); +const RETRYABLE_TOOL_TEXT = new RegExp(`\\(code: ${TOOL_CODE}, retryable\\)|"retryable"\\s*:\\s*true|"retryability"\\s*:\\s*"later"`); + +function explicitToolCode(code: unknown): string | undefined { + return typeof code === "string" && code.length <= 91 && /^[a-z][a-z0-9_.-]*$/.test(code) && !/[_.-]$/.test(code) ? code : undefined; +} + +/** + * A connected tool's own stable error code and retryability, normalized once for + * every caller. Structured fields win; then the plugin marker, a JSON "code", and + * a first-line prefix that contains a separator, so prose labels are never codes. + */ +export function toolResultErrorDetails(result: Record): { toolCode?: string; retryable?: true } { + const object = (value: unknown) => value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; + const data = object(result.data); + const structured = object(result.structuredContent ?? data.structuredContent); + const sources = [result, structured, data]; + const content = Array.isArray(result.content) ? result.content : Array.isArray(data.content) ? data.content : []; + const text = [ + ...(typeof result.content === "string" ? [result.content] : []), + ...content.flatMap((item) => typeof object(item).text === "string" ? [object(item).text as string] : []), + ...(typeof result.error === "string" ? [result.error] : []), + ].join("\n"); + const firstLine = text.trim().split("\n")[0] ?? ""; + const prefixCode = PREFIX_TOOL_CODE.exec(firstLine)?.[1]; + const toolCode = [result.code, structured.code, data.code].map(explicitToolCode).find(Boolean) + ?? explicitToolCode(PLUGIN_TOOL_CODE.exec(text)?.[1]) + ?? [...text.matchAll(JSON_TOOL_CODE)].map((match) => explicitToolCode(match[1])).find(Boolean) + ?? (prefixCode && /[_.-]/.test(prefixCode) ? explicitToolCode(prefixCode) : undefined); + const retryable = sources.some((source) => source.retryable === true || source.retryability === "later") || RETRYABLE_TOOL_TEXT.test(text); + return { ...(toolCode ? { toolCode } : {}), ...(retryable ? { retryable: true as const } : {}) }; +} + export class ToolGatewayHttpError extends Error { constructor( public readonly status: number, @@ -7493,11 +7540,6 @@ export function createToolGatewayService( return normalized; } - function toolResultErrorMessage(result: Record, failureInstructions?: string) { - const message = String(result.content || result.error); - return failureInstructions ? `${message}\n\n${failureInstructions}` : message; - } - // ── MCP Tasks (io.modelcontextprotocol/tasks) ───────────────────────────── // A provider may answer tools/call with a durable task. The live call waits // on it up to the normal tool timeout; past that the row keeps it, background @@ -10214,7 +10256,8 @@ export function createToolGatewayService( if (providerResult?.error) { throw new ToolGatewayHttpError(providerResult.errorCode === "github_access_denied" ? 403 : 502, toolResultErrorMessage(providerResult, connectedMcpExecution.failureInstructions), - providerResult.errorCode === "github_access_denied" ? "github_access_denied" : "tool_error", { execution: connectedMcpExecution.execution }); + providerResult.errorCode === "github_access_denied" ? "github_access_denied" : "tool_error", + { execution: connectedMcpExecution.execution, ...toolResultErrorDetails(providerResult) }); } } catch (err) { const status = err instanceof ToolGatewayHttpError ? err.status : 502; @@ -11101,6 +11144,7 @@ export function createToolGatewayService( resultRecord.errorCode === "github_access_denied" ? 403 : 502, toolResultErrorMessage(resultRecord, connectedMcpExecution?.failureInstructions), resultRecord.errorCode === "github_access_denied" ? "github_access_denied" : "tool_execution_failed", + toolResultErrorDetails(resultRecord), ); const now = new Date(); await db @@ -14116,7 +14160,7 @@ export function createToolGatewayService( validatedMcpResult.errorCode === "github_access_denied" ? 403 : 502, toolResultErrorMessage(validatedMcpResult, connectedMcpExecution?.failureInstructions), validatedMcpResult.errorCode === "github_access_denied" ? "github_access_denied" : "tool_error", - { execution: connectedMcpExecution?.execution }, + { execution: connectedMcpExecution?.execution, ...toolResultErrorDetails(validatedMcpResult) }, ); } await db