mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents call Google Workspace through Google's MCP servers. Paperclip
checks the arguments before it sends a call (#22815, #22706)
> - The Paperclip Runner wrapper for assigned tools sends the agent only
a stable code. It does not send the provider's free text (#22723)
> - Paperclip's own refusals had no code. Google's errors had no code.
So the agent saw only `assigned_tool_error: The connected tool reported
an error.`
> - The agent did not know which argument to remove, or that it must
delete one occurrence. It retried blindly and stopped
> - This pull request gives each Paperclip refusal a stable code and
sends its Paperclip-written text. It gives each Google error a stable
code from Google's status. It records the code on the failed call event
> - The benefit is that the agent can fix its call, and an admin can see
why a call failed
## Linked Issues or Issue Description
Refs #22815
Refs #22723
Refs #22842
**What happened?**
On the staging tester (build 1b4ebec), a Workspace Tester agent on
OpenCode + DeepSeek on the native runtime ran a QA task. Three Calendar
calls returned only `assigned_tool_error: The connected tool reported an
error.`:
1. `list_calendars` with an extra argument `bogus: 1`. Paperclip refused
it before dispatch (`dispatched: false`).
2. `delete_event` with a recurring series ID. Paperclip refused it
before dispatch (`dispatched: false`).
3. `respond_to_event` "accepted" on an event that the user organises.
Google returned an error. The agent retried blindly and stopped. The
failed call event had an empty `errorCode` and `errorMessage`.
**What did you expect to happen?**
1. The agent sees `unknown_argument:` and the refusal text that names
the unknown argument and lists the accepted arguments.
2. The agent sees `recurring_series_delete_refused:` and the text that
tells it to pass one occurrence.
3. The agent sees a stable code from Google's structured error, for
example `google_permission_denied`. The failed call event records this
code.
**Steps to reproduce**
1. Connect Google Workspace on Google's MCP servers and give an agent on
the Paperclip Runner access.
2. Call Calendar `list_calendars` with `{ "bogus": 1 }`.
3. Call Calendar `delete_event` with the ID of a recurring series.
4. Call Calendar `respond_to_event` on an event that Google refuses.
5. Each call returns only `assigned_tool_error: The connected tool
reported an error.`
## What Changed
- `argument-guards.ts`: each refusal now returns `{ code, message }`.
The codes are `unknown_argument`, `invalid_arguments`,
`invalid_file_id`, `request_kind_refused`,
`recurring_series_delete_refused` and `delete_target_unverified`.
- `tool-gateway.ts`: a Google MCP preflight refusal returns
`errorDetails` with the code and the Paperclip text (`paperclipRefusal`)
beside the result. Only Paperclip code sets this field, so a provider
result cannot forge it. A Google MCP error result gets `errorDetails`
from the new `googleWorkspaceMcpErrorDetails`. The three tool error
throw sites use these details first.
- `google-workspace-rest-dispatch.ts`: `googleWorkspaceMcpErrorDetails`
finds Google's HTTP status (`error.code`, a status name such as
`PERMISSION_DENIED` mapped to its canonical HTTP status, or `HTTP 403`
in the text). It gives the status and Google's error body to the REST
tools' `googleError`, so there is one Google classification. The code is
`google_<kind>`, for example `google_permission_denied`,
`google_invalid_argument`, `google_not_found`, `google_unavailable`, or
`google_unauthenticated` / `google_insufficient_scope`. Otherwise the
code is `google_error`. `google_rate_limited` is retryable.
`google_unavailable` is retryable only for a read action: a write can
already be applied when Google reports a server error. Google's text
never becomes a code.
- `assigned-mcp-tools.ts`: `toolReportedError` sends `paperclipRefusal`
text after the code, bounded to 2,000 characters. Without it, the
message stays `<code>: The connected tool reported an error.` (#22723
rule).
- Every failed call event writer (`tool_call_events`, `call_failed`:
agent call, approved action, connection test, plugin tool) now records
`errorCode` (the tool code, else the reason code) and `errorMessage`
through one helper. The 30-day Google Technical Information sweep from
#22842 already clears `tool_call_events.error_message` for Google
connections. The invocation row is unchanged (`errorCode: tool_error`,
`errorMessage`: the text).
- README of the Google Workspace tools: the codes and what the agent
sees.
Why Google's text stays out: #22723 sends only a stable code because
provider text is untrusted. It can carry prompt injection or internal
details. This reasoning applies to Google's text, so this change keeps
it. In a test, an injection-style Google error message was blocked by
the result screen, which shows that this text is a real risk.
Paperclip's refusal text is trusted: Paperclip wrote it. It echoes only
the argument names that the agent sent and the argument names from the
tool's schema, which the agent already has.
## Verification
- Red/green: the first three new tests in
`server/src/__tests__/google-workspace-mcp-transport.test.ts` ("what an
agent on the Paperclip Runner sees when a call fails") use the fake
Google MCP server and the native-runtime assigned tool path
(`buildPaperclipRuntimeMcpServers` + `createAssignedMcpTools`). With the
gateway and wrapper changes reverted, all three fail. With the changes,
all three pass:
- `list_calendars { bogus: 1 }` → `unknown_argument: Invalid arguments
for list_calendars: unknown argument "bogus". Accepted arguments:
pageSize, pageToken. Nothing was sent to Google.` Event `errorCode:
unknown_argument`, `dispatched: false`, nothing sent to Google.
- `delete_event` on a series → `recurring_series_delete_refused: This ID
is a whole recurring series. … Pass one occurrence's ID (from
list_events). Nothing was deleted.` Event `errorCode:
recurring_series_delete_refused`, `dispatched: false`.
- `respond_to_event` with a Google 403 `PERMISSION_DENIED` →
`google_permission_denied: The connected tool reported an error.` with
no Google text. Event `errorCode: google_permission_denied`,
`errorMessage`: Google's text.
- A fourth test approves an Ask first `respond_to_event` that Google
refuses. The failed call event has `errorCode: google_permission_denied`
and Google's text.
- Unit tests: guard codes (`argument-guards.test.ts`),
`googleWorkspaceMcpErrorDetails` classification, 5xx retry for reads
only, and its free-text refusal
(`google-workspace-rest-dispatch.test.ts`), refusal text only from the
gateway detail and bounded (`assigned-mcp-tools.test.ts`).
- Focused run: `npx vitest run` on the tool gateway, tool gateway
service, content deletion, Google connection removal, Google Workspace
tools, dispatch, assigned tools and MCP transport tests: 63 files, 1,925
tests passed.
- `pnpm exec tsc --noEmit -p server/tsconfig.json`: passed.
- `pnpm verify`: exit 2 (the README is a broad input). Required CI
covers the rest.
## Risks
- Low. The change touches only connected tool errors. Approval,
revocation and gateway failures are unchanged.
- A failed call event now records `errorMessage` for every connection,
not only Google. The invocation row and the audit event already hold
this text. For Google connections, the 30-day sweep clears it.
- `errorCode` on the call event holds a short code such as
`google_permission_denied`, not Google text. The sweep does not clear
it, as on the invocation row.
- The ACPX runner feedback (Rust) keeps only the leading code from a
failed tool result. Harnesses on that path now see the stable code (for
example `unknown_argument`) but not the refusal text. OpenCode on the
native runtime sees the full text. A runner change is out of scope.
- A JSON-RPC protocol error from Google (not a tool error result) keeps
its current path (`remote_mcp_error`).
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code, with tool use
and code execution.
## 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>
499 lines
25 KiB
TypeScript
499 lines
25 KiB
TypeScript
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, toolResultErrorDetails, type ToolGatewayDescriptor, type ToolGatewayService } from "../tool-gateway.js";
|
|
|
|
type WorkMode = "standard" | "planning" | "ask" | "skill_test";
|
|
type ToolDefinition = Record<string, unknown>;
|
|
|
|
const SEARCH_TOOL = "paperclip_search_assigned_tools";
|
|
const CALL_TOOL = "paperclip_call_assigned_tool";
|
|
// A single valid runner schema can be 512 KiB. Leave room for its description
|
|
// while keeping the complete result below the 768 KiB provider-result bound.
|
|
const SEARCH_PAGE_BYTES = 640 * 1024;
|
|
const SCHEMA_CHUNK_CHARACTERS = 64 * 1024;
|
|
const ON_DEMAND_TOOLS: ToolDefinition[] = [
|
|
{
|
|
name: SEARCH_TOOL,
|
|
description: "Search your assigned app tools by name or description and read their input schemas. Pass {\"query\":\"search terms\"}, or an empty query to browse. Use limit from 1 to 20 (default 5). Omit unused optional fields instead of sending null. To fetch the next page, pass the returned nextOffset as offset. A large definition returns inputSchemaRef: set schemaTool to that name with an empty query, then pass the returned nextSchemaOffset as schemaOffset until null. Concatenate schemaJson chunks and parse JSON. Use paperclip_call_assigned_tool with a returned name and arguments matching its inputSchema.",
|
|
inputSchema: {
|
|
type: "object", additionalProperties: false,
|
|
properties: {
|
|
query: { type: "string", maxLength: 200 },
|
|
offset: { type: "integer", minimum: 0 },
|
|
limit: { type: "integer", minimum: 1, maximum: 20, default: 5, description: "Maximum results per page (1 to 20; default 5)." },
|
|
schemaTool: { type: "string", description: "Exact inputSchemaRef from a search result. Omit or leave blank for a normal tool search." },
|
|
schemaOffset: { type: "integer", minimum: 0, description: "Schema chunk offset. A positive offset requires an exact inputSchemaRef in schemaTool." },
|
|
},
|
|
required: ["query"],
|
|
},
|
|
},
|
|
{
|
|
name: CALL_TOOL,
|
|
description: "Call an assigned app tool discovered with paperclip_search_assigned_tools. Use its exact returned name and arguments matching its inputSchema. The same permissions, approvals, and audit rules apply as for direct app tools.",
|
|
inputSchema: {
|
|
type: "object", additionalProperties: false,
|
|
properties: { name: { type: "string" }, arguments: { type: "object", additionalProperties: true } },
|
|
required: ["name", "arguments"],
|
|
},
|
|
},
|
|
];
|
|
|
|
function object(value: unknown): Record<string, unknown> {
|
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
throw new Error("assigned_mcp_tool_invalid_arguments");
|
|
}
|
|
return value as Record<string, unknown>;
|
|
}
|
|
|
|
// Execution must use the app's configured gateway, including deployment
|
|
// restrictions, OAuth refresh, and approval delivery. Never fall back to an
|
|
// isolated gateway whose defaults differ from the running instance.
|
|
const assignedMcpGateways = new WeakMap<Db, ToolGatewayService>();
|
|
|
|
export function registerAssignedMcpGateway(db: Db, gateway: ToolGatewayService): void {
|
|
assignedMcpGateways.set(db, gateway);
|
|
}
|
|
|
|
export function getAssignedMcpGateway(db: Db): ToolGatewayService {
|
|
const gateway = assignedMcpGateways.get(db);
|
|
if (!gateway) throw new Error("assigned_mcp_gateway_unavailable");
|
|
return gateway;
|
|
}
|
|
|
|
/** No configured gateway means no authorized connection tools or instructions. */
|
|
export async function resolveAssignedConnectionInstructionsForRun(db: Db, binding: { companyId: string; agentId: string; runId: string }) {
|
|
const gateway = assignedMcpGateways.get(db);
|
|
return gateway ? gateway.resolveConnectionInstructionsForRun(binding) : null;
|
|
}
|
|
|
|
/** MCP Skills: approved skills of the agent's usable connections; none without a configured gateway. */
|
|
export async function resolveMcpConnectionSkillsForRun(db: Db, binding: { companyId: string; agentId: string; runId: string }) {
|
|
const gateway = assignedMcpGateways.get(db);
|
|
return gateway ? gateway.resolveConnectionSkillsForRun(binding) : null;
|
|
}
|
|
|
|
/** The name native runners give a gateway tool; transcripts show this name. */
|
|
export function assignedToolName(name: string): string {
|
|
const sanitize = (value: string) => value.replace(/[^a-zA-Z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
|
|
const separator = name.lastIndexOf(":");
|
|
const readable = separator >= 0
|
|
? `${sanitize(name.slice(0, separator)).slice(0, 20) || "tool"}_${sanitize(name.slice(separator + 1)).slice(-26) || "action"}`
|
|
: sanitize(name).slice(0, 47) || "tool";
|
|
const digest = createHash("sha256").update(name).digest("hex").slice(0, 12);
|
|
return `app_${readable}_${digest}`;
|
|
}
|
|
|
|
function editDistance(left: string, right: string): number {
|
|
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
for (let leftIndex = 1; leftIndex <= left.length; leftIndex += 1) {
|
|
const current = [leftIndex];
|
|
for (let rightIndex = 1; rightIndex <= right.length; rightIndex += 1) {
|
|
const substitutionCost = left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1;
|
|
current[rightIndex] = Math.min(current[rightIndex - 1]! + 1, previous[rightIndex]! + 1, previous[rightIndex - 1]! + substitutionCost);
|
|
}
|
|
previous = current;
|
|
}
|
|
return previous[right.length]!;
|
|
}
|
|
|
|
function closestNames(reference: string, names: string[]): string {
|
|
const target = reference.trim().toLowerCase();
|
|
const closest = names
|
|
.map(name => ({ name, limit: Math.floor(Math.max(target.length, name.length) / 3) }))
|
|
.filter(({ name, limit }) => Math.abs(target.length - name.length) <= limit)
|
|
.map(({ name, limit }) => ({ name, limit, distance: editDistance(target, name.toLowerCase()) }))
|
|
.filter(({ distance, limit }) => distance <= limit)
|
|
.sort((a, b) => a.distance - b.distance || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
|
|
.slice(0, 3)
|
|
.map(({ name }) => name);
|
|
return closest.length > 0 ? ` Closest assigned names: ${closest.join(", ")}.` : "";
|
|
}
|
|
|
|
export const ASSIGNED_SCHEMA_LISTING_BUDGET_BYTES = 768 * 1024;
|
|
export const ASSIGNED_SCHEMA_ADMISSION_CACHE_ENTRIES = 1024;
|
|
|
|
type AssignedSchemaOutcome = { ok: true } | { ok: false; reason: string };
|
|
type AssignedSchemaAdmission = { ok: true; schema: Record<string, unknown> } | { ok: false; reason: string };
|
|
const assignedSchemaOutcomes = new Map<string, AssignedSchemaOutcome>();
|
|
|
|
export function assignedSchemaAdmissionCacheSize(): number {
|
|
return assignedSchemaOutcomes.size;
|
|
}
|
|
|
|
async function admitAssignedToolSchema(key: string, schema: Record<string, unknown>): Promise<AssignedSchemaAdmission> {
|
|
let outcome = assignedSchemaOutcomes.get(key);
|
|
if (!outcome) {
|
|
await new Promise<void>(resolve => setImmediate(resolve));
|
|
outcome = assignedSchemaOutcomes.get(key);
|
|
}
|
|
if (!outcome) {
|
|
const admission = admitToolInputSchema(schema);
|
|
outcome = admission.ok ? { ok: true } : { ok: false, reason: admission.reason };
|
|
}
|
|
assignedSchemaOutcomes.delete(key);
|
|
assignedSchemaOutcomes.set(key, outcome);
|
|
while (assignedSchemaOutcomes.size > ASSIGNED_SCHEMA_ADMISSION_CACHE_ENTRIES) {
|
|
assignedSchemaOutcomes.delete(assignedSchemaOutcomes.keys().next().value!);
|
|
}
|
|
return outcome.ok ? { ok: true, schema: canonicalToolInputSchema(schema)!.schema } : outcome;
|
|
}
|
|
|
|
type AssignedTool = Readonly<{ name: string; displayName: string; description: string; risk: ToolGatewayDescriptor["risk"] }>;
|
|
type AssignedCatalogTool = Readonly<{ tool: AssignedTool; schema: Readonly<Record<string, unknown>>; definition: Readonly<ToolDefinition> }>;
|
|
type AssignedCatalog = Readonly<{
|
|
identity: string;
|
|
bytes: number;
|
|
tools: ReadonlyMap<string, AssignedCatalogTool>;
|
|
definitions: readonly Readonly<ToolDefinition>[];
|
|
readDefinitions: readonly Readonly<ToolDefinition>[];
|
|
unavailable: readonly Readonly<{ tool: string; reason: string }>[];
|
|
unchecked: readonly string[];
|
|
}>;
|
|
type AssignedListingEntry = { name: string; tool: AssignedTool; raw: Record<string, unknown>; bytes: number; digest: string };
|
|
type SharedCatalogEntry = { bytes: number; catalog: WeakRef<AssignedCatalog>; holders: number };
|
|
|
|
export const ASSIGNED_CATALOG_CACHE_ENTRIES = 512;
|
|
export const ASSIGNED_CATALOG_CACHE_BYTES = 256 * 1024 * 1024;
|
|
|
|
const sharedCatalogs = new Map<string, SharedCatalogEntry>();
|
|
const pendingCatalogs = new Map<string, Promise<AssignedCatalog>>();
|
|
let sharedCatalogBytes = 0;
|
|
const collectedSessions = new FinalizationRegistry<() => void>(release => release());
|
|
const collectedCatalogs = new FinalizationRegistry<{ key: string; catalog: WeakRef<AssignedCatalog> }>(({ key, catalog }) => {
|
|
if (sharedCatalogs.get(key)?.catalog === catalog) forgetSharedCatalog(key);
|
|
});
|
|
|
|
function forgetSharedCatalog(key: string): void {
|
|
const entry = sharedCatalogs.get(key);
|
|
if (!entry) return;
|
|
sharedCatalogs.delete(key);
|
|
sharedCatalogBytes -= entry.bytes;
|
|
}
|
|
|
|
export function assignedCatalogCacheStats(): { entries: number; bytes: number } {
|
|
return { entries: sharedCatalogs.size, bytes: sharedCatalogBytes };
|
|
}
|
|
|
|
function deepFreeze<T>(value: T): T {
|
|
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
Object.freeze(value);
|
|
for (const nested of Object.values(value)) deepFreeze(nested);
|
|
}
|
|
return value;
|
|
}
|
|
|
|
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 const PAPERCLIP_REFUSAL_MAX_CHARACTERS = 2000;
|
|
|
|
export function toolReportedError(details: { toolCode?: string; retryable?: boolean; paperclipRefusal?: string }): ToolGatewayHttpError {
|
|
const reason = details.paperclipRefusal?.slice(0, PAPERCLIP_REFUSAL_MAX_CHARACTERS) || "The connected tool reported an error.";
|
|
return new ToolGatewayHttpError(details.retryable ? 429 : 422, `${runnerToolCode(details.toolCode)}: ${reason}`,
|
|
"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 }> = [];
|
|
const unchecked: string[] = [];
|
|
let listingSchemaBytes = 0;
|
|
let bytes = identity.length;
|
|
for (const entry of listing) {
|
|
const compilable = entry.bytes <= TOOL_INPUT_SCHEMA_MAX_BYTES
|
|
&& (listingSchemaBytes += entry.bytes) <= ASSIGNED_SCHEMA_LISTING_BUDGET_BYTES;
|
|
let schema: Record<string, unknown>;
|
|
if (compilable) {
|
|
const admission = await admitAssignedToolSchema(entry.digest, entry.raw);
|
|
if (!admission.ok) {
|
|
unavailable.push({ tool: entry.tool.name, reason: admission.reason });
|
|
continue;
|
|
}
|
|
schema = admission.schema;
|
|
} else {
|
|
schema = structuredClone(entry.raw);
|
|
unchecked.push(entry.tool.name);
|
|
}
|
|
const definition = Object.freeze({
|
|
name: entry.name, description: `${entry.tool.displayName}: ${entry.tool.description}`, inputSchema: deepFreeze(schema),
|
|
});
|
|
bytes += entry.bytes + definition.description.length;
|
|
tools.set(entry.name, Object.freeze({ tool: entry.tool, schema: definition.inputSchema, definition }));
|
|
}
|
|
const entries = [...tools.values()];
|
|
return Object.freeze({
|
|
identity, bytes, tools,
|
|
definitions: Object.freeze(entries.map(entry => entry.definition)),
|
|
readDefinitions: Object.freeze(entries.filter(entry => entry.tool.risk === "read").map(entry => entry.definition)),
|
|
unavailable: deepFreeze(unavailable),
|
|
unchecked: Object.freeze(unchecked),
|
|
});
|
|
}
|
|
|
|
function sharedAssignedCatalog(key: string, identity: string): AssignedCatalog | undefined {
|
|
const entry = sharedCatalogs.get(key);
|
|
const catalog = entry?.catalog.deref();
|
|
if (!entry || catalog?.identity !== identity) return undefined;
|
|
sharedCatalogs.delete(key);
|
|
sharedCatalogs.set(key, entry);
|
|
return catalog;
|
|
}
|
|
|
|
function shareAssignedCatalog(key: string, catalog: AssignedCatalog): void {
|
|
if (catalog.bytes > ASSIGNED_CATALOG_CACHE_BYTES) return;
|
|
forgetSharedCatalog(key);
|
|
const reference = new WeakRef(catalog);
|
|
sharedCatalogs.set(key, { bytes: catalog.bytes, catalog: reference, holders: 0 });
|
|
sharedCatalogBytes += catalog.bytes;
|
|
collectedCatalogs.register(catalog, { key, catalog: reference });
|
|
for (const oldest of sharedCatalogs.keys()) {
|
|
if (sharedCatalogs.size <= ASSIGNED_CATALOG_CACHE_ENTRIES && sharedCatalogBytes <= ASSIGNED_CATALOG_CACHE_BYTES) break;
|
|
forgetSharedCatalog(oldest);
|
|
}
|
|
}
|
|
|
|
async function resolveAssignedCatalog(companyId: string | undefined, listing: readonly AssignedListingEntry[]) {
|
|
const identity = JSON.stringify([companyId ?? null, listing.map(entry =>
|
|
[entry.name, entry.tool.name, entry.tool.displayName, entry.tool.description, entry.tool.risk, entry.digest])]);
|
|
if (!companyId) return { catalog: await buildAssignedCatalog(identity, listing), release: () => {} };
|
|
const key = sha256(identity);
|
|
let catalog = sharedAssignedCatalog(key, identity);
|
|
const pending = catalog ? undefined : pendingCatalogs.get(key);
|
|
if (pending) {
|
|
const joined = await pending;
|
|
catalog = joined.identity === identity ? joined : undefined;
|
|
}
|
|
if (!catalog) {
|
|
const building = buildAssignedCatalog(identity, listing);
|
|
pendingCatalogs.set(key, building);
|
|
try {
|
|
catalog = await building;
|
|
} finally {
|
|
if (pendingCatalogs.get(key) === building) pendingCatalogs.delete(key);
|
|
}
|
|
if (sharedAssignedCatalog(key, identity) !== catalog) shareAssignedCatalog(key, catalog);
|
|
}
|
|
const holder = sharedCatalogs.get(key);
|
|
if (!holder || holder.catalog.deref() !== catalog) return { catalog, release: () => {} };
|
|
holder.holders += 1;
|
|
let released = false;
|
|
return {
|
|
catalog,
|
|
release: () => {
|
|
if (released) return;
|
|
released = true;
|
|
holder.holders -= 1;
|
|
if (holder.holders === 0 && sharedCatalogs.get(key) === holder) forgetSharedCatalog(key);
|
|
},
|
|
};
|
|
}
|
|
|
|
/** Server-owned MCP bindings projected into the runner's existing tool channel. */
|
|
export async function createAssignedMcpTools(input: {
|
|
gateway: ToolGatewayService;
|
|
gatewayPublicId: string;
|
|
bearerToken: string;
|
|
companyId?: string;
|
|
workMode?: WorkMode;
|
|
/** Bound provider grammar complexity independently of protocol byte capacity. */
|
|
delivery?: "on_demand";
|
|
}) {
|
|
const listed = await input.gateway.listToolsForNamedGateway({
|
|
gatewayPublicId: input.gatewayPublicId,
|
|
bearerToken: input.bearerToken,
|
|
});
|
|
const listing: AssignedListingEntry[] = [];
|
|
const listedNames = new Map<string, string>();
|
|
for (const descriptor of deduplicateToolDescriptors(listed)) {
|
|
const name = assignedToolName(descriptor.name);
|
|
const previous = listedNames.get(name);
|
|
if (previous !== undefined) {
|
|
throw new ToolGatewayHttpError(409,
|
|
`Assigned MCP tool name collision for ${JSON.stringify([previous, descriptor.name])}.`,
|
|
"assigned_mcp_tool_name_collision");
|
|
}
|
|
listedNames.set(name, descriptor.name);
|
|
const raw = (descriptor.parametersSchema ?? { type: "object", properties: {} }) as Record<string, unknown>;
|
|
const serialized = JSON.stringify(raw);
|
|
listing.push({
|
|
name, raw, bytes: Buffer.byteLength(serialized, "utf8"), digest: sha256(serialized),
|
|
tool: Object.freeze({ name: descriptor.name, displayName: `${descriptor.displayName}`, description: `${descriptor.description}`, risk: descriptor.risk }),
|
|
});
|
|
}
|
|
const { catalog, release } = await resolveAssignedCatalog(input.companyId, listing);
|
|
const { tools, unavailable, unchecked } = catalog;
|
|
if (unavailable.length > 0) {
|
|
logger.warn({ gatewayPublicId: input.gatewayPublicId, unavailable },
|
|
"assigned MCP tools whose input schema the Runner cannot validate are not offered");
|
|
}
|
|
if (unchecked.length > 0) {
|
|
logger.warn({ gatewayPublicId: input.gatewayPublicId, unchecked },
|
|
"assigned MCP tools whose input schema is over the compile budget are offered only through assigned-tool search");
|
|
}
|
|
const permits = (tool: Pick<ToolGatewayDescriptor, "risk">, mode: WorkMode = input.workMode ?? "standard") => mode === "standard" || tool.risk === "read";
|
|
// OpenCode's HTTP bridge returns at most 64K JSON characters. Leave room
|
|
// for the envelope and for JSON escaping when returning a schema chunk.
|
|
// Other harnesses retain the larger PRP page and chunk budgets.
|
|
const searchPageBytes = input.delivery === "on_demand" ? 32 * 1024 : SEARCH_PAGE_BYTES;
|
|
const schemaChunkCharacters = input.delivery === "on_demand" ? 16 * 1024 : SCHEMA_CHUNK_CHARACTERS;
|
|
|
|
function resolveAssignedName(reference: string, argument: "name" | "schemaTool"): string | undefined {
|
|
const trimmed = reference.trim();
|
|
if (tools.has(trimmed)) return trimmed;
|
|
const matches = [...tools].filter(([, { tool }]) => tool.name === trimmed || tool.displayName === trimmed);
|
|
if (matches.length > 1) {
|
|
throw new Error(`assigned_mcp_tool_unknown: ${argument} matches more than one assigned tool. Use the exact ${argument === "name" ? "name" : "inputSchemaRef"} returned by paperclip_search_assigned_tools.`);
|
|
}
|
|
return matches[0]?.[0];
|
|
}
|
|
|
|
// Intersect fresh grants with this session's pinned catalog. Revocations
|
|
// take effect immediately; newly assigned tools require a new session.
|
|
async function authorizedTools(currentWorkMode?: WorkMode) {
|
|
const current = new Map(deduplicateToolDescriptors(await input.gateway.listToolsForNamedGateway({
|
|
gatewayPublicId: input.gatewayPublicId, bearerToken: input.bearerToken,
|
|
})).map(tool => [tool.name, tool]));
|
|
return [...tools].filter(([, { tool }]) => {
|
|
const fresh = current.get(tool.name);
|
|
return fresh && permits(tool) && permits(tool, currentWorkMode) &&
|
|
permits(fresh) && permits(fresh, currentWorkMode);
|
|
});
|
|
}
|
|
|
|
async function search(argumentsValue: unknown, currentWorkMode?: WorkMode) {
|
|
const args = object(argumentsValue);
|
|
const offset = args.offset ?? 0;
|
|
const limit = args.limit ?? 5;
|
|
const schemaOffset = args.schemaOffset ?? 0;
|
|
const hasSchemaTool = typeof args.schemaTool === "string" && args.schemaTool.trim().length > 0;
|
|
if (typeof args.query !== "string" || args.query.length > 200 ||
|
|
typeof offset !== "number" || !Number.isSafeInteger(offset) || offset < 0 ||
|
|
typeof limit !== "number" || !Number.isSafeInteger(limit) || limit < 1 || limit > 20 ||
|
|
(args.schemaTool !== undefined && typeof args.schemaTool !== "string") ||
|
|
typeof schemaOffset !== "number" || !Number.isSafeInteger(schemaOffset) || schemaOffset < 0) {
|
|
throw new Error("assigned_mcp_tool_invalid_arguments");
|
|
}
|
|
if (schemaOffset > 0 && !hasSchemaTool) {
|
|
throw new Error("assigned_mcp_tool_invalid_arguments: A positive schemaOffset requires an exact inputSchemaRef in schemaTool. Omit schemaTool and schemaOffset to search assigned tools.");
|
|
}
|
|
const terms = args.query.toLowerCase().trim().split(/\s+/).filter(Boolean);
|
|
const authorized = await authorizedTools(currentWorkMode);
|
|
if (hasSchemaTool) {
|
|
const reference = resolveAssignedName(args.schemaTool as string, "schemaTool");
|
|
const selected = authorized.find(([name]) => name === reference);
|
|
if (!selected) {
|
|
throw new Error(`assigned_mcp_tool_unknown: schemaTool must match an authorized inputSchemaRef.${closestNames(args.schemaTool as string, authorized.map(([name]) => name))} Omit schemaTool to search assigned tools, then use an exact inputSchemaRef from the results.`);
|
|
}
|
|
const schema = JSON.stringify(selected[1].schema);
|
|
const end = schemaOffset + schemaChunkCharacters;
|
|
return {
|
|
name: selected[0], schemaJson: schema.slice(schemaOffset, end),
|
|
nextSchemaOffset: end < schema.length ? end : null,
|
|
};
|
|
}
|
|
// Keep offsets anchored to the pinned catalog while fresh grants only
|
|
// decide which entries are returned from that stable sequence.
|
|
const authorizedNames = new Set(authorized.map(([name]) => name));
|
|
const matches = [...tools].filter(([, { tool }]) => permits(tool)).filter(([name, { tool }]) =>
|
|
terms.every(term => `${name} ${tool.displayName} ${tool.description}`.toLowerCase().includes(term)))
|
|
.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
const page: ToolDefinition[] = [];
|
|
let nextOffset = offset;
|
|
while (nextOffset < matches.length && page.length < limit) {
|
|
const [name, entry] = matches[nextOffset]!;
|
|
if (!authorizedNames.has(name)) {
|
|
nextOffset += 1;
|
|
continue;
|
|
}
|
|
let next: ToolDefinition = structuredClone(entry.definition);
|
|
if (Buffer.byteLength(JSON.stringify([next]), "utf8") > searchPageBytes) {
|
|
// One large schema must not block browsing the tools after it. Expose
|
|
// a reference whose schema can be fetched in bounded, reauthorized
|
|
// chunks, without weakening the gateway's argument validation.
|
|
next = { name, description: String(next.description).slice(0, 2000), inputSchemaRef: name };
|
|
}
|
|
if (Buffer.byteLength(JSON.stringify([...page, next]), "utf8") > searchPageBytes) {
|
|
break;
|
|
}
|
|
page.push(next);
|
|
nextOffset += 1;
|
|
}
|
|
return { tools: page, nextOffset: nextOffset < matches.length ? nextOffset : null };
|
|
}
|
|
|
|
const assigned = {
|
|
definitions(fits?: (definitions: ToolDefinition[]) => boolean): ToolDefinition[] {
|
|
const direct = [...((input.workMode ?? "standard") === "standard" ? catalog.definitions : catalog.readDefinitions)] as ToolDefinition[];
|
|
if (input.delivery !== "on_demand" && unchecked.length === 0 && (!fits || fits(direct))) return direct;
|
|
const compact = structuredClone(ON_DEMAND_TOOLS);
|
|
if (fits && !fits(compact)) throw new Error("assigned_mcp_tool_catalog_capacity_exceeded");
|
|
return compact;
|
|
},
|
|
has(name: string): boolean {
|
|
return tools.has(name) || name === SEARCH_TOOL || name === CALL_TOOL;
|
|
},
|
|
async execute(call: { tool: string; arguments: unknown }, currentWorkMode?: WorkMode): Promise<unknown> {
|
|
if (call.tool === SEARCH_TOOL) return search(call.arguments, currentWorkMode);
|
|
let name = call.tool;
|
|
let parameters = call.arguments;
|
|
if (name === CALL_TOOL) {
|
|
const args = object(parameters);
|
|
if (typeof args.name !== "string") throw new Error("assigned_mcp_tool_invalid_arguments");
|
|
parameters = object(args.arguments);
|
|
const resolved = resolveAssignedName(args.name, "name");
|
|
if (!resolved) {
|
|
const authorized = await authorizedTools(currentWorkMode).then(entries => entries.map(([candidate]) => candidate), () => []);
|
|
throw new Error(`assigned_mcp_tool_unknown: name must be an exact name returned by paperclip_search_assigned_tools.${closestNames(args.name, authorized)} Search assigned tools again and use the returned name.`);
|
|
}
|
|
name = resolved;
|
|
}
|
|
const descriptor = tools.get(name)?.tool;
|
|
if (!descriptor) throw new Error("assigned_mcp_tool_unknown");
|
|
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.
|
|
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,
|
|
paperclipRefusal: typeof error.details.paperclipRefusal === "string" ? error.details.paperclipRefusal : undefined,
|
|
});
|
|
}
|
|
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 toolReportedError(toolResultErrorDetails(result.result as Record<string, unknown>));
|
|
}
|
|
return result.result;
|
|
},
|
|
close(): void {
|
|
collectedSessions.unregister(assigned);
|
|
release();
|
|
},
|
|
};
|
|
collectedSessions.register(assigned, release, assigned);
|
|
return assigned;
|
|
}
|