mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 05:47:10 +01:00
fix(tools): show agents the stable code of a connected tool's own error (#22723)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents call connected tools (plugin connectors and remote MCP servers) through the tool gateway, and the runner reports a failed call back to the model > - The runner keeps only a leading stable error code from a failed tool result and drops free text and 5xx errors, so internal diagnostics never reach the model > - The gateway raised every error a connected tool reported about itself as a 502 with the code buried in free text, and stringified an MCP error's content array as "[object Object]" > - So an agent saw only "Paperclip semantic operation failed" for a rate limit, a concurrency refusal or a validation error, and retried blindly > - This pull request re-raises a tool's own error as a 4xx whose message starts with the tool's stable code > - The benefit is that agents see why a tool refused (for example `read_concurrency_limit` or `validation_error`) and can wait or fix their input ## Linked Issues or Issue Description **What happened?** An agent refreshing a tracker ran reads in parallel. The Customer success connector refused all but two at a time with `read_concurrency_limit`, and Notion refused some queries with validation errors. The agent saw "Paperclip semantic operation failed" for every one. Cloud recorded 299 concurrency refusals against 10 completed reads before the run gave up. **Expected behavior** The agent sees the tool's stable error code, for example `Paperclip semantic operation failed: read_concurrency_limit`. **Steps to reproduce** 1. Have an assigned connected tool fail with a tool-reported error (the gateway raises `ToolGatewayHttpError(502, "... (code: read_concurrency_limit, retryable)", "tool_error")`). 2. Call it through the runner's assigned tools. 3. The model receives only the generic failure text. ## What Changed - `server/src/services/native-runtime/assigned-mcp-tools.ts`: a `tool_error` from the gateway, or an `isError` result, is re-raised as a 422 `tool_error` whose message starts with the tool's stable code. The code comes from a plugin's `(code: ...)`, a JSON `"code"` field, or a leading `code:` prefix, with `assigned_tool_error` as the fallback. The message carries no provider free text. - `server/src/services/tool-gateway.ts`: tool error messages use the text of MCP content items instead of `String(array)`. - Tests for each code source and the fallback; the old tests that expected the raw 502 object now cover approval and revocation only. ## Verification - `npx vitest run src/services/native-runtime/assigned-mcp-tools.test.ts`: 63 passed. - The runner's ACPX feedback already keeps a leading `code:` prefix from a failed tool result's text (existing Rust tests), and the Codex driver passes a thrown error's message as that text. ## Risks - Low. Only errors that a connected tool reported about itself change. Approval, revocation and gateway failures are unchanged. The reason code stays `tool_error`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code, with tool use. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
92e3ad1de9
commit
d1339f1fe4
4 files changed
+195
-19
No files matched your search
@@ -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);
|
||||
|
||||
@@ -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<string, unknown> = {}) {
|
||||
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" } });
|
||||
|
||||
@@ -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<string, unknown>;
|
||||
@@ -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<AssignedCatalog> {
|
||||
const tools = new Map<string, AssignedCatalogTool>();
|
||||
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<ReturnType<ToolGatewayService["executeTool"]>>;
|
||||
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<string, unknown>));
|
||||
}
|
||||
return result.result;
|
||||
},
|
||||
|
||||
@@ -485,6 +485,53 @@ export interface ToolGatewaySession {
|
||||
|
||||
export type ToolGatewayRuntimeSlot = ToolRuntimeSlotView;
|
||||
|
||||
export function toolResultErrorMessage(result: Record<string, unknown>, 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<string, unknown>): { toolCode?: string; retryable?: true } {
|
||||
const object = (value: unknown) => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
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<string, unknown>, 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
|
||||
|
||||
Reference in new issue
Block a user