Files
PaperClipAI/server/src/services/native-runtime/assigned-mcp-tools.ts
T
DottaandClaude Opus 5.5 11f4a76743 perf(native-runtime): share one frozen assigned tool catalog across sessions (#21482)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - One server process controls every native agent session. Each session
gets the app tools (MCP tools) that are assigned to its agent.
> - Each live or warm session kept two private copies of its assigned
tool catalog: the gateway descriptors and a canonical copy of every
input schema.
> - With 400 tools of about 5.7 KB each, that was about 7.6 MB of heap
for each session. With 800 tools, it was about 15 MB. Warm sessions stay
for 5 minutes after the last turn, so idle agents also hold this memory.
> - At 1,000 concurrent agents, this is 7 to 15 GB of heap, and the
server cannot get there.
> - This pull request keeps one deeply frozen catalog for all sessions
of the same company that get the same admitted tools and schemas.
> - The benefit is that each additional session on the same catalog adds
about 40 to 80 KB of heap instead of 7.6 to 15 MB, and session start is
faster.

## Linked Issues or Issue Description

Refs #21415 (releases a finished session's tool authority). Refs #21440
(adds the catalog memory benchmark that this change extends).

**What existing behavior does this improve?**
`createAssignedMcpTools` in
`server/src/services/native-runtime/assigned-mcp-tools.ts`. Each call
kept every gateway descriptor (with its provider metadata) and a
separate canonical clone of each input schema. Each `definitions()` call
also made a new `structuredClone` of every schema.

**Subsystem affected**
Native runtime: assigned app tools (MCP) for native agent sessions.

**Current behavior**
Retained heap grows by one full catalog for each session. Measured with
the real `createAssignedMcpTools` (5.7 KB schemas): 400 tools is 7.58 MB
per session, and 800 tools is 15.1 MB per session, for 1, 10, and 100
sessions. Each `definitions()` call takes 14 to 41 ms because it clones
every schema.

**Proposed behavior**
Sessions of the same company that get identical admitted tools share one
frozen catalog. The total for 100 sessions is about one catalog: 4.2 MB
at 400 tools and 8.1 MB at 800 tools. `definitions()` takes 0.01 ms.

**Reason and benefit**
The server must hold 1,000 concurrent agents in one process. The catalog
was the largest per-session heap cost. Revocation and authorization do
not change: every call is still authorized again by the gateway, and
every new session still reads a fresh listing.

**Breaking changes**
None in the API or data. The direct definitions that `definitions()`
returns are now frozen. A consumer that writes to a returned definition
or schema gets a `TypeError` and does not change other sessions. No
production consumer writes to them (see Risks).

## What Changed

- `server/src/services/native-runtime/assigned-mcp-tools.ts`:
- A session keeps only a small frozen record for each tool (gateway
name, display name, description, risk), plus the frozen schema and the
frozen definition. It does not keep the gateway descriptors.
- New per-process index of shared catalogs. The key is the SHA-256 of an
identity string: `[companyId, [[assignedName, gatewayName, displayName,
description, risk, sha256(JSON of the input schema)] for each listed
tool, in listing order]]`. On a hit, the code also compares the full
identity string, so a hash collision cannot give a wrong catalog.
- The identity is computed from the fresh listing that the gateway
returns for this session. The gateway applies all per-agent, per-run,
per-profile, and policy filtering, and the approval description suffix,
before it returns the listing. Thus two sessions share only if they were
given exactly the same tools, names, descriptions, risks, and schemas in
the same company. Without `companyId`, nothing is shared.
- Schemas, definitions, tool records, and the definition arrays are
deeply frozen. Search results still return cloned copies.
- Sessions that start at the same time with the same catalog wait for
one build and share it.
- The index holds each catalog through a `WeakRef`, so it never keeps a
catalog alive. The index has at most 512 entries and 256 MiB (accounted
schema and description bytes). The oldest entries are removed first. A
catalog that is larger than the byte limit is not indexed.
- New `close()` on the assigned tools. When the last session that holds
a catalog closes, the index entry is removed. A `FinalizationRegistry`
also removes entries whose catalog was collected.
- `definitions()` returns the shared frozen definitions for the
session's work mode. It no longer clones every schema on each call.
-
`server/src/services/native-runtime/paperclip-runner-tool-authority.ts`:
`close()` also closes the assigned tools. The session executor already
closes the authority when it revokes a session's tool authority.
- `server/src/services/native-runtime/native-session-executor.ts`: one
line. It passes the run binding's `companyId` to
`createAssignedMcpTools`.
- `server/scripts/benchmark-assigned-mcp-tools-memory.ts`: passes
`companyId`, adds `--companies`, measures session start and
`definitions()` time, and returns fresh copies of fixed rows (like
database reads).
- Tests in `assigned-mcp-tools.test.ts` and
`paperclip-runner-tool-authority.test.ts`.

## Verification

Red/green tests in
`server/src/services/native-runtime/assigned-mcp-tools.test.ts` ("shared
assigned tool catalogs"):

- Retained heap: 20 sessions of one company on a 60-tool, 4 KB-schema
catalog. The heap for the other 19 sessions must be less than two
catalogs. Red on master: `expected 14025976 to be less than 3788112`.
Green with this change.
- Shared deeply frozen schemas, also for sessions that start together.
Red on master (`Object.is` equality fails).
- Mutation isolation: writes to a returned definition, schema property,
and `required` array, and a delete, throw `TypeError`. Changes to the
gateway's source rows and to a search result do not change any session.
Red on master (no throw).
- Release and bounds: the entry stays while one session holds it and
goes when the last session closes. `close()` is idempotent. A new
session after release builds a new catalog. 517 companies keep the index
at 512 entries or fewer. Red on master (no `close` or stats).
- Guard tests: two companies with identical catalogs do not share.
Sessions without a company do not share. Fewer tools, an edited schema,
an edited description, or a different risk do not share. A revoked or
edited tool is served from fresh discovery. On master these pass,
because master never shares. To prove they test the key, I removed
`companyId` and the schema digest from the identity: three guard tests
failed, and they pass with the full key.
- An existing test changed: "does not project gateway secrets..." now
expects a write to a returned schema to throw `TypeError` (before, the
write changed only a private clone). The isolation check after the write
is the same.
- `paperclip-runner-tool-authority.test.ts`: `authority.close()` closes
the assigned tools.

Heap (post-GC `heapUsed` delta, `node --expose-gc`, 5.7 KB schemas, one
company). Command: `cd server && node --expose-gc --import tsx
scripts/benchmark-assigned-mcp-tools-memory.ts --tools <N>
--schema-bytes 5700 --sessions <S> --turns 5`.

| Tools | Sessions | Total before | Per session before | Total after |
Per session after |
| --- | --- | --- | --- | --- | --- |
| 400 | 1 | 7.60 MB | 7.60 MB | 3.96 MB | 3.96 MB |
| 400 | 10 | 75.9 MB | 7.59 MB | 4.04 MB | 0.40 MB |
| 400 | 100 | 757.9 MB | 7.58 MB | 4.18 MB | 0.042 MB |
| 800 | 1 | 15.2 MB | 15.2 MB | 7.91 MB | 7.91 MB |
| 800 | 10 | 151.4 MB | 15.1 MB | 7.98 MB | 0.80 MB |
| 800 | 100 | 1,513 MB | 15.1 MB | 8.13 MB | 0.081 MB |

The first session also uses about half the heap of before, because the
session no longer keeps the gateway descriptors. When all sessions are
dropped without `close()`, the catalog is collected (0 bytes held after
release).

Session start, interleaved A/B in one process (old and new
`createAssignedMcpTools` alternate, 40 starts each, median of the last
35, includes a fresh copy of the listing; the machine had a load average
of 25 to 65):

| Tools | Listing copy only | Before | After |
| --- | --- | --- | --- |
| 400 | 22.6 ms | 68.0 ms | 37.6 ms |
| 800 | 30.5 ms | 72.5 ms | 41.2 ms |

A start that reuses a catalog does no schema clone and no admission. It
still serializes and hashes each schema to compute the key. The first
start of a new catalog does the same admission work as before (the cold
first start was about 600 to 750 ms in both versions on this busy
machine).

`definitions()` median: 14 to 41 ms before, 0.01 ms after.

Other checks:

- `cd server && npx vitest run
src/services/native-runtime/assigned-mcp-tools.test.ts
src/services/native-runtime/paperclip-runner-tool-authority.test.ts
src/services/native-runtime/runner-api.integration.test.ts
src/services/native-runtime/runner-tool-results-prp.integration.test.ts
src/__tests__/deployment-connections.test.ts`: 204 passed.
- `cd server && npx vitest run
src/services/native-runtime/native-session-executor.test.ts -t
"assigned|tool authority|released|MCP"`: 31 passed.
- `cd server && npx vitest run
src/__tests__/chat-channels.integration.test.ts -t "assigned"`: 10
passed.
- `cd server && npx tsc --noEmit`: pass.
- `pnpm check:module-boundaries`: pass.
- `pnpm verify` selects a broad plan (the benchmark script is a broad
input), so CI supplies the full suite.

## Risks

- Frozen definitions: the direct definitions now go to the runner
drivers as frozen objects. I checked the consumers.
`PaperclipRunnerToolAuthority.definitions()` filters and spreads them.
The Codex, Cursor Cloud, OpenCode, ACPX, and runnerd drivers read them,
spread them, clone them (`structuredClone` in ACPX and the OpenCode MCP
bridge), or serialize them. Their types are `readonly
Readonly<Record<string, unknown>>[]`. The first-party semantic tool
definitions are already shared module constants that go through the same
path without clones. If a consumer that I did not find writes to a
definition, it gets a `TypeError` instead of a silent change. Catalogs
over 256 tools or over the listing budget use the two on-demand tools
and are not affected.
- Authorization: the shared data is only the result of a listing that
the gateway already authorized for that session, keyed on the full
content plus the company. Execution still goes through the gateway with
the session's own token on every call. Search still intersects with a
fresh listing. A new session still reads a fresh listing, so a revoked
or edited tool takes effect for new sessions and for existing sessions
at the same points as before.
- Several server processes: the index is a per-process memo of the
listing content. Each process builds its own catalog from its own
listing. Nothing is stored or shared outside the process.
- The index is bounded (512 entries, 256 MiB) and holds catalogs only
weakly. Index eviction only stops future sharing. It never frees memory
that a session uses.
- No schema change. No migration.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Claude Code agent with tool use
(shell, file edit, test runs, heap and timing benchmarks).

## 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
- [ ] I have updated relevant documentation to reflect my changes (no
documented behavior or command 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>
2026-11-13 14:36:30 -06:00

426 lines
21 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, 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}`;
}
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");
}
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;
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.");
}
// Intersect fresh grants with this session's pinned catalog. Revocations
// take effect immediately; newly assigned tools require a new session.
const current = new Map(deduplicateToolDescriptors(await input.gateway.listToolsForNamedGateway({
gatewayPublicId: input.gatewayPublicId, bearerToken: input.bearerToken,
})).map(tool => [tool.name, tool]));
const terms = args.query.toLowerCase().trim().split(/\s+/).filter(Boolean);
const authorized = [...tools].filter(([, { tool }]) => {
const fresh = current.get(tool.name);
return fresh && permits(tool) && permits(tool, currentWorkMode) &&
permits(fresh) && permits(fresh, currentWorkMode);
});
if (hasSchemaTool) {
const selected = authorized.find(([name]) => name === args.schemaTool);
if (!selected) throw new Error("assigned_mcp_tool_unknown: schemaTool must match an authorized inputSchemaRef. 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");
name = args.name;
parameters = object(args.arguments);
}
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.
const result = await input.gateway.executeTool({
gatewayPublicId: input.gatewayPublicId,
sessionToken: input.bearerToken,
tool: descriptor.name,
parameters,
});
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");
}
return result.result;
},
close(): void {
collectedSessions.unregister(assigned);
release();
},
};
collectedSessions.register(assigned, release, assigned);
return assigned;
}