mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
feat(connections): add experimental memory providers and remote MCP access (#13942)
## Thinking Path > - Paperclip manages AI agents and their work. > - Connections give agents governed access to external tools. > - Agents need durable memory across tasks and execution environments. > - Mem0, Zep, Supermemory, Cognee, and Honcho provide hosted memory tools. > - This pull request adds their setup flows behind an experimental toggle. > - It also delivers assigned MCP tools through the native remote Codex runner. > - Operators can connect a provider once and use the same governed tools locally or in Daytona. ## Linked Issues or Issue Description **Problem or motivation** The Apps catalog lacks a complete set of memory providers. Remote native Codex agents also need access to assigned managed MCP tools without receiving provider credentials. **Proposed solution** Add five memory connectors behind the disabled-by-default Experimental memory connectors setting. Use the existing connection setup and permissions UI. Default their tools to Allowed. Preserve company boundaries, operator permission changes, provider scopes, and audit attribution. **Alternatives considered** Direct provider credentials in each sandbox would duplicate setup and bypass the managed gateway. The remote runner instead uses its existing protocol channel to call the gateway on the server. **Roadmap alignment** This maintainer-requested experiment supports the Memory / Knowledge and Connected Apps roadmap areas. It adds provider connections without introducing a separate memory UI. Related connector authoring documentation is tracked in #13692; no duplicate memory-provider implementation was found. ## What Changed - Add provider definitions, official branding, and the experimental setting for all five providers. - Use OAuth for Zep and Supermemory, API credentials for Mem0 and Honcho, and a bundled Cloud API bridge for Cognee with no runtime downloads or subprocesses. - Default memory tools to Allowed and classify destructive actions explicitly. - Fix personal remote credential resolution and propagate provider tool errors. - Relay assigned managed MCP tools to remote native Codex through the runner protocol. Recheck current authority for each call and rotate stale tool contracts. - Add 21 Storybook states and complete OAuth walkthrough fixtures. - Document provider research, sanitized tool inventory, and live local and Daytona proof. ## Verification - Passed workspace typecheck: `pnpm -r typecheck`. - Passed production build: `pnpm build`. - Full local `pnpm test:run`: 13,273 passed, with failures from process/readiness timeouts under parallel load. Reran all 16 affected suites with one worker: 456 passed, leaving two macOS `/var` versus `/private/var` path assertions. Both passed with `TMPDIR=/private/tmp`. No test failures remain unverified. Latest-head remote CI passes all 54 checks (two optional Storybook jobs skipped). Greptile is 5/5 with no unresolved findings. - Latest Cognee gateway regression: 71 passed, including public deployment without a runtime host and immediate recovery after a provider error. Bundled bridge tests: 25 passed. - Browser setup and real agent tasks exercised all five providers. Mem0, Cognee, Zep, and Honcho have successful store/retrieve proof. - Supermemory now has scoped read/write consent. Local storage and real Daytona write, document read, and semantic recall passed; indexing completion was verified before claiming success. - All five providers were exercised through a real Daytona sandbox and its native runner MCP relay. Provider credentials remained on the server. The final bundled Cognee bridge also passed a fresh Daytona store/recall run. All disposable sandboxes were removed and verified absent after testing. - Storybook is rebuilt and contains the experimental toggle, catalog, setup, permissions, and error states. The Zep and Supermemory access steps advance correctly. ## Risks - Provider OAuth scopes and plan limits remain independent of Paperclip tool permissions. An Allowed tool can still be rejected by the provider. - Providers can queue memory indexing; save acceptance does not prove that semantic recall is ready. - Remote tool contracts must stay synchronized with current connection authority. Regression tests cover revocation and stale contracts. - This change has no database migration. Existing connections remain usable when the experimental catalog toggle is disabled. ## Model Used OpenAI Codex, GPT-6 Astra (`gpt-6-astra`), with reasoning, repository edits, code execution, and browser automation. The exact context window size is not exposed in this session. Live acceptance agents used `gpt-5.6-sol`. ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
e006c18f20
commit
18dac1e1ef
54 files changed
+3066
-135
No files matched your search
@@ -0,0 +1,149 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { ToolGatewayHttpError, type ToolGatewayDescriptor, type ToolGatewayService } from "../tool-gateway.js";
|
||||
import { createAssignedMcpTools, getAssignedMcpGateway, registerAssignedMcpGateway } from "./assigned-mcp-tools.js";
|
||||
|
||||
function descriptor(name: string, risk: ToolGatewayDescriptor["risk"] = "read"): ToolGatewayDescriptor {
|
||||
return { name, displayName: name, description: `Use ${name}`, parametersSchema: { type: "object", properties: { query: { type: "string" } } }, pluginId: "fixture", providerType: "mcp_remote_http", risk };
|
||||
}
|
||||
|
||||
function fixture(tools: ToolGatewayDescriptor[]) {
|
||||
const listToolsForNamedGateway = vi.fn().mockResolvedValue(tools);
|
||||
const executeTool = vi.fn().mockResolvedValue({ status: "completed", result: { content: [{ type: "text", text: "memory found" }] } });
|
||||
const gateway = { listToolsForNamedGateway, executeTool } as unknown as ToolGatewayService;
|
||||
return { gateway, listToolsForNamedGateway, executeTool, gatewayPublicId: "gateway-fixture", bearerToken: "private-run-token-never-project" };
|
||||
}
|
||||
|
||||
describe("assigned MCP runner tools", () => {
|
||||
it("requires a configured gateway registered for the exact database instance", () => {
|
||||
const firstDb = {} as Db;
|
||||
const secondDb = {} as Db;
|
||||
const first = fixture([]).gateway;
|
||||
const second = fixture([]).gateway;
|
||||
expect(() => getAssignedMcpGateway(firstDb)).toThrow("assigned_mcp_gateway_unavailable");
|
||||
registerAssignedMcpGateway(firstDb, first);
|
||||
expect(getAssignedMcpGateway(firstDb)).toBe(first);
|
||||
expect(() => getAssignedMcpGateway(secondDb)).toThrow("assigned_mcp_gateway_unavailable");
|
||||
registerAssignedMcpGateway(secondDb, second);
|
||||
expect(getAssignedMcpGateway(secondDb)).toBe(second);
|
||||
expect(getAssignedMcpGateway(firstDb)).toBe(first);
|
||||
registerAssignedMcpGateway(firstDb, second);
|
||||
expect(getAssignedMcpGateway(firstDb)).toBe(second);
|
||||
});
|
||||
|
||||
it("projects only authorized gateway tools with stable bounded collision-resistant names", async () => {
|
||||
const names = ["memory.search", "memory-search", "x".repeat(120), "🧠"];
|
||||
const f = fixture(names.map(name => descriptor(name)));
|
||||
const first = await createAssignedMcpTools(f);
|
||||
const reversed = await createAssignedMcpTools({ ...f, gateway: fixture([...names].reverse().map(name => descriptor(name))).gateway });
|
||||
const projected = first.definitions().map(tool => tool.name as string);
|
||||
expect(new Set(projected).size).toBe(names.length);
|
||||
for (const name of projected) {
|
||||
expect(name).toMatch(/^app_[a-zA-Z0-9_]+_[a-f0-9]{12}$/);
|
||||
expect(name.length).toBeLessThanOrEqual(64);
|
||||
expect(first.has(name)).toBe(true);
|
||||
}
|
||||
expect(reversed.definitions().map(tool => tool.name)).toEqual([...projected].reverse());
|
||||
expect(f.listToolsForNamedGateway).toHaveBeenCalledWith({ gatewayPublicId: f.gatewayPublicId, bearerToken: f.bearerToken });
|
||||
});
|
||||
|
||||
it("keeps the provider and action readable for fully namespaced gateway tools", async () => {
|
||||
const prefix = "mcp.app-gallery-mem0-60062edb-c211-4aae-a787-b4fa12a5ea24-f4ece062";
|
||||
const tools = ["add-memory", "search-memories", "delete-memory"].map(action => ({
|
||||
...descriptor(`${prefix}:${action}`), displayName: `Mem0 ${action}`,
|
||||
}));
|
||||
const assigned = await createAssignedMcpTools(fixture(tools));
|
||||
for (const [index, definition] of assigned.definitions().entries()) {
|
||||
const name = definition.name as string;
|
||||
expect(name).toContain("mem0");
|
||||
expect(name).toContain(tools[index]!.name.split(":").at(-1)!.replaceAll("-", "_"));
|
||||
expect(name.length).toBeLessThanOrEqual(64);
|
||||
expect(definition.description).toBe(`${tools[index]!.displayName}: ${tools[index]!.description}`);
|
||||
}
|
||||
const long = await createAssignedMcpTools(fixture([descriptor(`${prefix}:${"long-action-".repeat(10)}`)]));
|
||||
expect((long.definitions()[0]!.name as string).length).toBeLessThanOrEqual(64);
|
||||
});
|
||||
|
||||
it("does not project gateway secrets, URLs, or provider metadata and returns only the tool result", async () => {
|
||||
const tool = { ...descriptor("recall"), providerMetadata: { token: "private-provider-token", url: "https://private-gateway.example" } };
|
||||
const f = fixture([tool]);
|
||||
f.executeTool.mockResolvedValue({ status: "completed", invocationId: "internal", result: { memories: [] } });
|
||||
const assigned = await createAssignedMcpTools(f);
|
||||
const definitions = assigned.definitions();
|
||||
expect(Object.keys(definitions[0]!)).toEqual(["name", "description", "inputSchema"]);
|
||||
expect(JSON.stringify(definitions)).not.toMatch(/private-|gateway-fixture|https:/);
|
||||
const args = { query: "synthetic memory" };
|
||||
expect(await assigned.execute({ tool: definitions[0]!.name as string, arguments: args })).toEqual({ memories: [] });
|
||||
expect(f.executeTool).toHaveBeenCalledExactlyOnceWith({ gatewayPublicId: f.gatewayPublicId, sessionToken: f.bearerToken, tool: "recall", parameters: args });
|
||||
(definitions[0]!.inputSchema as Record<string, unknown>).type = "string";
|
||||
expect(assigned.definitions()[0]!.inputSchema).toEqual(tool.parametersSchema);
|
||||
});
|
||||
|
||||
it("rejects unknown names without invoking the gateway", async () => {
|
||||
const f = fixture([descriptor("recall")]);
|
||||
const assigned = await createAssignedMcpTools(f);
|
||||
expect(assigned.has("unassigned")).toBe(false);
|
||||
await expect(assigned.execute({ tool: "unassigned", arguments: {} })).rejects.toThrow("assigned_mcp_tool_unknown");
|
||||
expect(f.executeTool).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["planning", "ask"] as const)("exposes and permits only read tools in %s mode", async workMode => {
|
||||
const f = fixture([descriptor("read"), descriptor("remember", "write"), descriptor("forget", "destructive")]);
|
||||
const standard = await createAssignedMcpTools(f);
|
||||
const restricted = await createAssignedMcpTools({ ...f, workMode });
|
||||
expect(restricted.definitions()).toEqual([standard.definitions()[0]]);
|
||||
for (const tool of standard.definitions().slice(1)) {
|
||||
await expect(restricted.execute({ tool: tool.name as string, arguments: {} })).rejects.toThrow("paperclip_runner_tool_mode_denied");
|
||||
}
|
||||
expect(f.executeTool).not.toHaveBeenCalled();
|
||||
await restricted.execute({ tool: restricted.definitions()[0]!.name as string, arguments: {} });
|
||||
expect(f.executeTool).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("uses the gateway for write and destructive tools under standard mode without approval overrides", async () => {
|
||||
const f = fixture([descriptor("remember", "write"), descriptor("forget", "destructive")]);
|
||||
const assigned = await createAssignedMcpTools(f);
|
||||
for (const tool of assigned.definitions()) await assigned.execute({ tool: tool.name as string, arguments: {} });
|
||||
expect(f.executeTool).toHaveBeenCalledTimes(2);
|
||||
for (const [call] of f.executeTool.mock.calls) expect(call).not.toHaveProperty("approvedActionRequestId");
|
||||
});
|
||||
|
||||
it.each(["planning", "ask"] as const)("enforces fresh %s mode without relaxing the pinned mode", async currentMode => {
|
||||
const f = fixture([descriptor("read"), descriptor("remember", "write")]);
|
||||
const standard = await createAssignedMcpTools(f);
|
||||
const restricted = await createAssignedMcpTools({ ...f, workMode: currentMode });
|
||||
const write = { tool: standard.definitions()[1]!.name as string, arguments: {} };
|
||||
await expect(standard.execute(write, currentMode)).rejects.toThrow("paperclip_runner_tool_mode_denied");
|
||||
await expect(restricted.execute(write, "standard")).rejects.toThrow("paperclip_runner_tool_mode_denied");
|
||||
expect(f.executeTool).not.toHaveBeenCalled();
|
||||
await standard.execute({ tool: standard.definitions()[0]!.name as string, arguments: {} }, currentMode);
|
||||
expect(f.executeTool).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it.each(["tool_error", "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);
|
||||
const assigned = await createAssignedMcpTools(f);
|
||||
await expect(assigned.execute({ tool: assigned.definitions()[0]!.name as string, arguments: {} })).rejects.toBe(error);
|
||||
});
|
||||
|
||||
it("propagates discovery denial", async () => {
|
||||
const f = fixture([]);
|
||||
const error = new Error("gateway_token_revoked");
|
||||
f.listToolsForNamedGateway.mockRejectedValue(error);
|
||||
await expect(createAssignedMcpTools(f)).rejects.toBe(error);
|
||||
});
|
||||
|
||||
it("rejects error payloads and incomplete outcomes, and accepts successful replay", async () => {
|
||||
const f = fixture([descriptor("recall")]);
|
||||
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" });
|
||||
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" } });
|
||||
await expect(assigned.execute(call)).resolves.toEqual({ memory: "synthetic" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { ToolGatewayHttpError, type ToolGatewayDescriptor, type ToolGatewayService } from "../tool-gateway.js";
|
||||
|
||||
type WorkMode = "standard" | "planning" | "ask";
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
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}`;
|
||||
}
|
||||
|
||||
/** Server-owned MCP bindings projected into the runner's existing tool channel. */
|
||||
export async function createAssignedMcpTools(input: {
|
||||
gateway: ToolGatewayService;
|
||||
gatewayPublicId: string;
|
||||
bearerToken: string;
|
||||
workMode?: WorkMode;
|
||||
}) {
|
||||
const listed = await input.gateway.listToolsForNamedGateway({
|
||||
gatewayPublicId: input.gatewayPublicId,
|
||||
bearerToken: input.bearerToken,
|
||||
});
|
||||
const tools = new Map<string, ToolGatewayDescriptor>();
|
||||
for (const descriptor of listed) {
|
||||
const name = assignedToolName(descriptor.name);
|
||||
if (tools.has(name)) throw new Error("assigned_mcp_tool_name_collision");
|
||||
tools.set(name, descriptor);
|
||||
}
|
||||
const permits = (tool: ToolGatewayDescriptor, mode: WorkMode = input.workMode ?? "standard") => mode === "standard" || tool.risk === "read";
|
||||
|
||||
return {
|
||||
definitions(): Array<Record<string, unknown>> {
|
||||
return [...tools].filter(([, tool]) => permits(tool)).map(([name, tool]) => ({
|
||||
name,
|
||||
description: `${tool.displayName}: ${tool.description}`,
|
||||
inputSchema: structuredClone(tool.parametersSchema),
|
||||
}));
|
||||
},
|
||||
has(name: string): boolean {
|
||||
return tools.has(name);
|
||||
},
|
||||
async execute(call: { tool: string; arguments: unknown }, currentWorkMode?: WorkMode): Promise<unknown> {
|
||||
const descriptor = tools.get(call.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: call.arguments,
|
||||
});
|
||||
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;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -127,6 +127,7 @@ const durableRunnerState = (
|
||||
});
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
createAssignedMcpTools: vi.fn(),
|
||||
execute: vi.fn(),
|
||||
cleanup: vi.fn(),
|
||||
retireCleanup: vi.fn(),
|
||||
@@ -219,6 +220,11 @@ vi.mock("./paperclip-runner-tool-authority.js", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("./assigned-mcp-tools.js", () => ({
|
||||
createAssignedMcpTools: state.createAssignedMcpTools,
|
||||
getAssignedMcpGateway: () => ({}),
|
||||
}));
|
||||
|
||||
vi.mock("./native-runner-file-handoff.js", () => ({
|
||||
stageNativeRunnerWakeAttachments: state.stageNativeRunnerWakeAttachments,
|
||||
renderNativeRunnerStagedAttachmentPrompt:
|
||||
@@ -304,6 +310,7 @@ import {
|
||||
} from "./native-session-executor.js";
|
||||
|
||||
beforeEach(() => {
|
||||
state.createAssignedMcpTools.mockReset();
|
||||
state.resolveRunnerBinary.mockReset().mockReturnValue("/tmp/paperclip-runnerd");
|
||||
state.resolveCurrentWakeCommentsBinding.mockReset().mockResolvedValue(null);
|
||||
state.assertCurrentWakeCommentsRead.mockReset().mockResolvedValue(undefined);
|
||||
@@ -7997,6 +8004,52 @@ describe("runnerd provider runtime wiring", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ PAPERCLIP_NATIVE_MCP_NAME: "paperclip-assigned" },
|
||||
{ PAPERCLIP_NATIVE_MCP_URL: "http://127.0.0.1:3217/mcp/gateways/test" },
|
||||
{ PAPERCLIP_NATIVE_MCP_TOKEN: "private-run-token" },
|
||||
])("rejects partial remote assigned MCP bindings", async (runnerEnvironment) => {
|
||||
await expect(createRunnerdBackend({
|
||||
db: leaseDb(execution), execution, runnerInstanceId: "runner-partial-mcp", runnerEnvironment,
|
||||
runnerExecutionTarget: {
|
||||
kind: "remote", transport: "sandbox", providerKey: "daytona",
|
||||
leaseId: "lease-partial-mcp", remoteCwd: "/home/daytona/paperclip-workspace",
|
||||
runner: { execute: vi.fn() },
|
||||
} as never,
|
||||
})).rejects.toThrow("assigned native MCP launch binding is incomplete");
|
||||
expect(state.createAssignedMcpTools).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps assigned MCP credentials on the control plane for remote Codex", async () => {
|
||||
const assignedMcpTools = { definitions: () => [], has: () => false, execute: vi.fn() };
|
||||
state.createAssignedMcpTools.mockResolvedValueOnce(assignedMcpTools);
|
||||
state.createBackend.mockClear();
|
||||
state.createTransport.mockClear();
|
||||
state.toolAuthorityDefinitions.mockClear();
|
||||
await createRunnerdBackend({
|
||||
db: leaseDb(execution), execution, runnerInstanceId: "runner-assigned-mcp",
|
||||
runnerEnvironment: {
|
||||
PAPERCLIP_NATIVE_MCP_NAME: "paperclip-assigned",
|
||||
PAPERCLIP_NATIVE_MCP_URL: "http://127.0.0.1:3217/mcp/gateways/assigned-test",
|
||||
PAPERCLIP_NATIVE_MCP_TOKEN: "private-run-token",
|
||||
},
|
||||
runnerExecutionTarget: {
|
||||
kind: "remote", transport: "sandbox", providerKey: "daytona",
|
||||
leaseId: "lease-assigned-mcp", remoteCwd: "/home/daytona/paperclip-workspace",
|
||||
runner: { execute: vi.fn() },
|
||||
} as never,
|
||||
});
|
||||
expect(state.createAssignedMcpTools).toHaveBeenCalledWith(expect.objectContaining({
|
||||
gatewayPublicId: "assigned-test", bearerToken: "private-run-token",
|
||||
}));
|
||||
expect(state.toolAuthorityDefinitions).toHaveBeenCalledWith(expect.objectContaining({ assignedMcpTools }));
|
||||
state.createBackend.mock.calls[0]![1].codexTransportFactory!();
|
||||
const options = state.createTransport.mock.calls[0]![0] as { environment: NodeJS.ProcessEnv };
|
||||
expect(options.environment.PAPERCLIP_NATIVE_MCP_NAME).toBeUndefined();
|
||||
expect(options.environment.PAPERCLIP_NATIVE_MCP_URL).toBeUndefined();
|
||||
expect(options.environment.PAPERCLIP_NATIVE_MCP_TOKEN).toBeUndefined();
|
||||
});
|
||||
|
||||
it("makes remote authority archival idempotent and returns the archived state", async () => {
|
||||
const remoteExecute = vi.fn();
|
||||
const remoteTarget = {
|
||||
|
||||
@@ -122,6 +122,7 @@ import { PaperclipControlPlanePort } from "./paperclip-control-plane-port.js";
|
||||
import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js";
|
||||
import { nativeSha256 } from "./canonical.js";
|
||||
import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js";
|
||||
import { createAssignedMcpTools, getAssignedMcpGateway } from "./assigned-mcp-tools.js";
|
||||
import { getNativeReviewAssignment, readNativeReviewAssignmentContext } from "./native-review-participant.js";
|
||||
import { NativeChatAttachmentReadScope } from "./chat-attachment-read.js";
|
||||
import {
|
||||
@@ -10463,9 +10464,35 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
if (nativeReview && !await getNativeReviewAssignment(input.db, {
|
||||
...input.execution.binding, contextSnapshot: nativeReview,
|
||||
})) throw new Error("native_review_assignment_no_longer_available");
|
||||
// Remote Codex already sends dynamic tool calls over authenticated PRP. Keep
|
||||
// the assigned gateway on the control plane instead of asking the sandbox to
|
||||
// reach the host's HTTP origin (which may be private or loopback-only).
|
||||
const relayAssignedMcp = remoteTarget !== null && input.execution.provider.kind === "codex";
|
||||
const assignedMcpUrl = input.runnerEnvironment?.PAPERCLIP_NATIVE_MCP_URL;
|
||||
const assignedMcpToken = input.runnerEnvironment?.PAPERCLIP_NATIVE_MCP_TOKEN;
|
||||
const assignedMcpName = input.runnerEnvironment?.PAPERCLIP_NATIVE_MCP_NAME;
|
||||
const hasAssignedMcp = Boolean(assignedMcpName || assignedMcpUrl || assignedMcpToken);
|
||||
if (relayAssignedMcp && hasAssignedMcp && (!assignedMcpName?.trim() || !assignedMcpUrl?.trim() || !assignedMcpToken?.trim())) {
|
||||
throw new Error("assigned native MCP launch binding is incomplete");
|
||||
}
|
||||
const assignedGatewayPublicId = relayAssignedMcp && assignedMcpUrl
|
||||
? new URL(assignedMcpUrl).pathname.match(/^\/mcp\/gateways\/([a-zA-Z0-9_-]+)$/)?.[1]
|
||||
: undefined;
|
||||
if (relayAssignedMcp && hasAssignedMcp && !assignedGatewayPublicId) {
|
||||
throw new Error("assigned native MCP gateway path is invalid");
|
||||
}
|
||||
const assignedMcpTools = relayAssignedMcp && !nativeReview && assignedMcpUrl && assignedMcpToken
|
||||
? await createAssignedMcpTools({
|
||||
gateway: getAssignedMcpGateway(input.db),
|
||||
gatewayPublicId: assignedGatewayPublicId!,
|
||||
bearerToken: assignedMcpToken,
|
||||
workMode: input.execution.task.workMode,
|
||||
})
|
||||
: undefined;
|
||||
const authority = new PaperclipRunnerToolAuthority(input.db, {
|
||||
...(nativeReview ? { nativeReview } : {}),
|
||||
connectorAssignments: connectorAssignments.filter((assignment) => pinnedSkills.has(assignment.skillKey)),
|
||||
assignedMcpTools,
|
||||
companyId: input.execution.binding.companyId,
|
||||
issueId: input.execution.binding.issueId,
|
||||
runId: input.execution.binding.runId,
|
||||
@@ -12024,6 +12051,13 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
const effectiveRunnerEnvironmentBase: NodeJS.ProcessEnv = {
|
||||
...(input.runnerEnvironment ?? process.env),
|
||||
};
|
||||
if (relayAssignedMcp) {
|
||||
// The server-held tool authority owns this credential. Do not deliver a
|
||||
// duplicate HTTP MCP server or its bearer token to the remote provider.
|
||||
delete effectiveRunnerEnvironmentBase.PAPERCLIP_NATIVE_MCP_NAME;
|
||||
delete effectiveRunnerEnvironmentBase.PAPERCLIP_NATIVE_MCP_URL;
|
||||
delete effectiveRunnerEnvironmentBase.PAPERCLIP_NATIVE_MCP_TOKEN;
|
||||
}
|
||||
// This authority bit is derived only from the selected execution target.
|
||||
// Never let an agent, environment binding, or host variable disable the
|
||||
// Codex sandbox for a local runner by supplying the same key.
|
||||
|
||||
@@ -38,6 +38,9 @@ export function nativeToolContractFingerprintForTarget(
|
||||
"always_advertised_run_issue_agent_binding_gated_current_task_description.v2",
|
||||
semanticCompletion: "finish_accessible_deliverable_evidence.v4",
|
||||
connectorTools: "assigned_resources_and_pinned_skill_bundle.v1",
|
||||
...(executionTargetKind === "remote"
|
||||
? { assignedMcpTools: "codex_server_gateway_prp_relay.v1" }
|
||||
: {}),
|
||||
},
|
||||
tools: [
|
||||
{ name: "register_deliverable", version: 2 },
|
||||
|
||||
@@ -596,6 +596,34 @@ describe("PaperclipRunnerToolAuthority", () => {
|
||||
).resolves.toMatchObject({ approval: { id: approvalId }, tasks: [] });
|
||||
});
|
||||
|
||||
it("relays assigned MCP calls only while the native run still owns its task", async () => {
|
||||
const tool = { name: "app_mem0_recall", description: "Recall memory", inputSchema: { type: "object" } };
|
||||
const execute = vi.fn().mockResolvedValue({ content: "synthetic memory" });
|
||||
const authority = new PaperclipRunnerToolAuthority(db, {
|
||||
companyId, agentId, issueId, runId,
|
||||
assignedMcpTools: { definitions: () => [tool], has: (name) => name === tool.name, execute },
|
||||
});
|
||||
expect(authority.definitions()).toContainEqual(tool);
|
||||
const call = { tool: tool.name, callId: "assigned-mcp", arguments: { query: "compass" } };
|
||||
await expect(authority.execute(call)).resolves.toEqual({ content: "synthetic memory" });
|
||||
expect(execute).toHaveBeenCalledWith(call, "standard");
|
||||
await db.update(issues).set({ workMode: "ask" }).where(eq(issues.id, issueId));
|
||||
try {
|
||||
await authority.execute(call);
|
||||
expect(execute).toHaveBeenLastCalledWith(call, "ask");
|
||||
} finally {
|
||||
await db.update(issues).set({ workMode: "standard" }).where(eq(issues.id, issueId));
|
||||
}
|
||||
execute.mockClear();
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, runId));
|
||||
try {
|
||||
await expect(authority.execute(call)).rejects.toThrow("paperclip_runner_tool_binding_not_authorized");
|
||||
expect(execute).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await db.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, runId));
|
||||
}
|
||||
});
|
||||
|
||||
it("does not advertise delegation tools during pre-acceptance planning", () => {
|
||||
const authority = new PaperclipRunnerToolAuthority(db, {
|
||||
companyId,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { publicChatTaskUrl } from "../chat-task-url.js";
|
||||
import type { createAssignedMcpTools } from "./assigned-mcp-tools.js";
|
||||
import { assertAssignableAgent } from "../agent-assignability.js";
|
||||
import { authorizationService } from "../authorization.js";
|
||||
import { handoffPlanContext } from "./handoff-plan-context.js";
|
||||
@@ -104,6 +105,7 @@ type Binding = {
|
||||
storage?: StorageService;
|
||||
/** Server-owned suppression for baseline evals; true never overrides operator opt-in. */
|
||||
connectorAssignments?: ConnectorAssignment[];
|
||||
assignedMcpTools?: Awaited<ReturnType<typeof createAssignedMcpTools>>;
|
||||
apiToolsEnabled?: boolean;
|
||||
workMode?: "standard" | "planning" | "ask";
|
||||
workspaceRoot?: string;
|
||||
@@ -223,7 +225,7 @@ export class PaperclipRunnerToolAuthority {
|
||||
definitions.push(LIST_CHAT_ATTACHMENTS_TOOL_DEFINITION);
|
||||
definitions.push(REUSE_CHAT_ATTACHMENT_TOOL_DEFINITION);
|
||||
definitions.push(READ_CHAT_ATTACHMENT_TOOL_DEFINITION);
|
||||
return [...RUNTIME_CONNECTION_TOOL_DEFINITIONS, ...(this.binding.connectorAssignments ?? []).flatMap((assignment) => assignment.tools), ...definitions];
|
||||
return [...RUNTIME_CONNECTION_TOOL_DEFINITIONS, ...(this.binding.connectorAssignments ?? []).flatMap((assignment) => assignment.tools), ...(this.binding.assignedMcpTools?.definitions() ?? []), ...definitions];
|
||||
}
|
||||
|
||||
async execute(call: {
|
||||
@@ -237,6 +239,10 @@ export class PaperclipRunnerToolAuthority {
|
||||
throw forbidden("This review run may only inspect the assigned task and resolve its review.");
|
||||
}
|
||||
}
|
||||
if (this.binding.assignedMcpTools?.has(call.tool)) {
|
||||
const current = await this.#boundContext();
|
||||
return this.binding.assignedMcpTools.execute(call, current.issue.workMode as "standard" | "planning" | "ask");
|
||||
}
|
||||
if (isConnectorTool(call.tool)) {
|
||||
if (!(this.binding.connectorAssignments ?? []).some((assignment) => assignment.tools.some((tool) => tool.name === call.tool))) throw forbidden("Connector tool is not available to this run");
|
||||
const { run } = await this.#boundContext();
|
||||
|
||||
Reference in new issue
Block a user