refactor(runner): remove the direct assigned-gateway path (#21311)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - An agent reaches the tools of its app connections through an MCP
gateway.
> - Before #21274, some native harnesses got the gateway URL and a
bearer token and connected to the gateway directly. The Runner has code
for that: an HTTP MCP server for ACPX providers, a server entry in the
Codex `config.toml`, a server entry in the OpenCode config, and the
lists that pass the three `PAPERCLIP_NATIVE_MCP_*` variables to a
sidecar.
> - #21274 gives each native harness its gateway tools through the PRP
relay. Core removes the three variables from each Runner environment.
The direct code path gets no binding.
> - Code that cannot run still needs maintenance, and it can still put a
token in a provider process if a variable arrives by another way.
> - This pull request deletes the direct path from the Runner.
> - The benefit is one path for assigned gateway tools, and no Runner
code that can give a gateway token to a provider.

## Linked Issues or Issue Description

No public issue exists. The issue is described here.

This pull request is in a stack. Its base branch is
`fix/keep-quiet-claude-provider-between-turns` (#21293). It depends on
#21274, which is the bottom of the stack. On `master` without #21274,
the direct path is still in use.

**What existing behavior does this improve?**

The Runner code that connects a provider directly to the assigned MCP
gateway.

**Subsystem affected**

Paperclip Runner: the TypeScript drivers and the Rust `runner-core`
environment lists.

**Current behavior**

After #21274, Core never gives `PAPERCLIP_NATIVE_MCP_NAME`,
`PAPERCLIP_NATIVE_MCP_URL` or `PAPERCLIP_NATIVE_MCP_TOKEN` to a Runner.
The Runner still has the code that reads them and configures a direct
gateway server for ACPX providers, Codex and OpenCode.

**Proposed behavior**

The Runner has no code that reads the three variables to configure a
provider. If the variables are in the environment of a Runner, no
provider environment, sidecar, Codex `config.toml` or OpenCode config
gets them.

**Reason and benefit**

Less code, one path, and no way for a gateway token to reach a provider
process through the Runner.

## What Changed

- Deleted `packages/paperclip-runner/src/drivers/native-mcp.ts`
(`nativeMcpLaunchBinding`).
- `drivers/acpx/runtime-host.ts`: removed the native gateway server
entry and the name conflict check. The admission gate keeps its message.
A run with a binding id is admitted when the sidecar uses the PRP
transport with its tool bridge, as the production sidecar always does.
- `drivers/acpx/environment.ts`: the name and the URL are not in the
provider allowlist.
- `drivers/runtime-context-materializer.ts` and
`live/runnerd-codex-transport.ts`: the Codex home functions have no
`nativeMcp` parameter. The sidecar token pass-through is gone.
- `drivers/opencode/opencode-server-driver.ts`: removed the read of the
binding, its trace redaction value, and the gateway server entry in the
OpenCode config.
- `drivers/stdio-mcp.ts` and `runner-core/src/stdio_mcp.rs`: removed the
reservation of the gateway server name. No gateway server exists, so no
name can conflict. The names `paperclip` and `paperclip_runner_*` stay
reserved.
- `runner-core/src/acpx_sidecar_transport.rs` and `codex_provider.rs`:
the three variables are not in the pass-through lists.
- `control-plane/durable-prp-control-plane.ts`: the three variables are
not in the platform environment list.
- `packages/paperclip-runner/README.md`: the text about direct callers
and assigned servers.
- Kept: the three names stay in the reserved lists
(`src/configured-environment.ts`,
`runner-core/src/configured_environment.rs`). A user cannot configure
them. Tests in both languages now check all three names.
- No server code changed. The relay needs the gateway token and URL on
the control plane.

23 files, 73 lines added and 211 lines removed.

## State saved by the previous release

- This pull request changes no persisted shape. The provider server
lists, the launch profile digests, the protocol versions and the sidecar
contract are the same as with #21274.
- A Runner or sidecar that the previous release started keeps its own
code until its run ends, as #21274 describes.
- A kept Codex home that has the old gateway server in `config.toml` is
written again at the next start and at a recovery of the same run. A
test covers this.
- If the old variables reach a new Runner, no provider gets them. Tests
cover this for ACPX, Codex and OpenCode.

## Verification

From `packages/paperclip-runner`:

- `npx vitest run src/drivers/acpx/runtime-host.test.ts
src/live/runnerd-codex-transport.test.ts
src/drivers/acpx/environment.test.ts
src/drivers/opencode/opencode-server-driver.test.ts
src/live/runnerd-codex-transport-warm-attachment.test.ts
src/drivers/runtime-context-materializer.test.ts
src/drivers/agent-observability.test.ts src/drivers/stdio-mcp.test.ts
src/control-plane/durable-prp-control-plane.test.ts
src/configured-environment.test.ts`: `10 passed (10)` files, `807
passed` tests.
- `npx tsc --noEmit -p tsconfig.json` and `-p tsconfig.test.json`: no
errors.
- `cargo fmt --manifest-path runner/Cargo.toml --all -- --check`: no
changes.
- `cargo test -p paperclip-runner-core --test acpx_sidecar_transport`:
20 passed. `cargo test -p paperclip-runner-core --lib`: 639 passed, 4
ignored.

Tests that failed with the old code and pass now:

- `runtime-host.test.ts`: "admits a relayed … run with a binding id and
ignores a previous-release gateway binding", for Claude, Codex and
Cursor.
- `runnerd-codex-transport.test.ts`: "drops a previous-release gateway
binding from the … runner environment", for ACPX Claude, Codex, Pi,
Cursor, Copilot and Kimi, and for OpenCode.
- `opencode-server-driver.test.ts`: the OpenCode config has only the
task bridge.
- `runnerd-codex-transport-warm-attachment.test.ts`: a restored Codex
home has no gateway server and no gateway credential in `config.toml`.
- `environment.test.ts`: a provider environment has none of the three
variables.
- Rust
`previous_release_gateway_binding_and_unrelated_secrets_never_reach_the_sidecar`:
a Runner that starts with the old variables gives none of them to the
sidecar, for five agents.

Mutation check: with the three names put back in the Rust pass-through
list, the Rust test fails.

Not run: a live run with a real provider. Not run: `pnpm verify` and the
full suite. CI supplies that coverage.

## Risks

- **This pull request is safe only after #21274.** The stack order keeps
that.
- **A developer who sets the three variables by hand for
`eval-session`** no longer gets direct gateway tools. No document
describes that use.
- **The warm attachment test uses the staged Runner binary from
preflight.** That binary does not have the Rust changes of this pull
request. The Codex path of that test does not use the changed lists.
- The evidence that no entry point supplies a binding comes from a read
of the code: Core removes the variables before it builds each Runner
environment, and a native run cannot use the in-process path.

> 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 Fable 5.2 (`claude-fable-5-2`) in Claude Code planned the
change, reviewed the diff, and ran the verification and a mutation check
again.
- Claude Opus 5.5 (`claude-opus-5-5`), as a Claude Code subagent with
tool use (shell, file edits, local test runs), traced each code path and
wrote the change and the tests.

## 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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Nicky LeachandClaude Fable 5.2 authored and GitHub committed 2026-11-13 13:33:47 -08:00
1 parent 12aa08721c
commit 0aaab644fe
23 files changed
+73 -211

No files matched your search

+5 -5
View File
@@ -208,8 +208,8 @@ shape changes; sessions from the previous release retain their existing behavior
If the controller sends assigned MCP tools in the PRP catalog, the sidecar uses
its authenticated tool bridge.
Isolated provider admission accepts this route without a separate native MCP endpoint.
Direct runtime-host callers must supply the native gateway binding unless they select
PRP tool delivery and supply the semantic tool bridge.
When the runtime context names an assigned MCP binding, direct runtime-host callers
must select PRP tool delivery and supply the semantic tool bridge.
PRP delivery keeps the controller's exact operation names, including compact MCP catalog tools.
The selected permission and read-only policies still apply.
@@ -1062,8 +1062,8 @@ qualification before this mode can be enabled for them.
## Assigned local MCP servers
An execution host can assign local stdio MCP servers alongside the existing
`PAPERCLIP_NATIVE_MCP_NAME` / `URL` / `TOKEN` HTTP gateway. This is general transport
An execution host can assign local stdio MCP servers. Assigned gateway tools reach
the provider through the controller's PRP relay, not as a server here. This is general transport
support for local MCP implementations that satisfy the executable-verification
and private Unix socket requirements below. Runner uses each server's own tool
schemas and responses. Set
@@ -1080,7 +1080,7 @@ with the ownership and path requirements below.
Set `PAPERCLIP_NATIVE_MCP_PROXY` to the assigned Runner executable. These are
execution-host inputs, excluded from configurable task environment and provider
shell inheritance. Names use letters, digits, underscores or hyphens and cannot
replace the internal task server or gateway. Commands are verified against their
replace the internal task server. Commands are verified against their
assigned digest before execution. The backend receives only its assigned environment.
Runner supplies these session-local bindings to native Codex and through the
@@ -295,11 +295,6 @@ impl AcpxSidecarTransport {
"no_proxy",
"all_proxy",
"RUST_BACKTRACE",
"PAPERCLIP_NATIVE_MCP_NAME",
"PAPERCLIP_NATIVE_MCP_URL",
// The qualified sidecar configures the runner-owned gateway. Keep
// its credential with the name/URL; unrelated secrets stay excluded.
"PAPERCLIP_NATIVE_MCP_TOKEN",
"PAPERCLIP_NATIVE_MCP_STDIO",
"PAPERCLIP_NATIVE_MCP_PROXY",
"PAPERCLIP_ACPX_BUILTIN_ROOT",
@@ -98,9 +98,6 @@ const OPENCODE_PROVIDER_ENVIRONMENT_KEYS: &[&str] = &[
"PAPERCLIP_AGENT_PUBLIC_KEY",
"PAPERCLIP_AGENT_PRIVATE_KEY",
"OPENROUTER_API_KEY",
"PAPERCLIP_NATIVE_MCP_NAME",
"PAPERCLIP_NATIVE_MCP_URL",
"PAPERCLIP_NATIVE_MCP_TOKEN",
"PAPERCLIP_OPENCODE_PERMISSION_MODE",
"PAPERCLIP_OPENCODE_RUNTIME_DIR",
"PAPERCLIP_OPENCODE_PERFORMANCE_DIAGNOSTICS",
@@ -241,6 +241,9 @@ mod tests {
"[\"PAPERCLIP_RUNTIME_NOTIFICATION_HELPER\"]",
"[\"OPENAI_API_KEY\"]",
"[\"KIMI_API_KEY\"]",
"[\"PAPERCLIP_NATIVE_MCP_NAME\"]",
"[\"PAPERCLIP_NATIVE_MCP_URL\"]",
"[\"PAPERCLIP_NATIVE_MCP_TOKEN\"]",
"[\"LD_PRELOAD\"]",
"[\"bad=name\"]",
"[\"CUSTOM\",\"CUSTOM\"]",
@@ -95,9 +95,6 @@ pub fn assigned_bindings() -> McpResult<Vec<StdioMcpBinding>> {
return Err(invalid("too many stdio MCP bindings"));
}
let mut names = BTreeSet::new();
if let Ok(gateway) = std::env::var("PAPERCLIP_NATIVE_MCP_NAME") {
names.insert(gateway);
}
for binding in &bindings {
binding.validate()?;
if !names.insert(binding.name.clone()) {
@@ -324,13 +324,13 @@ fn preserves_only_allowlisted_stderr_categories_when_the_process_exits() {
}
#[test]
fn assigned_gateway_binding_reaches_qualified_sidecar_without_unrelated_secrets() {
fn previous_release_gateway_binding_and_unrelated_secrets_never_reach_the_sidecar() {
const CHILD: &str = "PAPERCLIP_TEST_MCP_ENV_CHILD";
if std::env::var_os(CHILD).is_none() {
let status = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"assigned_gateway_binding_reaches_qualified_sidecar_without_unrelated_secrets",
"previous_release_gateway_binding_and_unrelated_secrets_never_reach_the_sidecar",
"--nocapture",
])
.env(CHILD, "1")
@@ -386,11 +386,11 @@ fn assigned_gateway_binding_reaches_qualified_sidecar_without_unrelated_secrets(
let response = sidecar
.request(GeneratedAcpxSidecarCommand::Initialize, json!({}))
.unwrap();
assert_eq!(response["name"], "paperclip-assigned");
assert_eq!(response["url"], "http://127.0.0.1:3100/mcp");
assert_eq!(response["name"], serde_json::Value::Null);
assert_eq!(response["url"], serde_json::Value::Null);
assert_eq!(
response["hasToken"], true,
"assigned gateway credential was dropped"
response["hasToken"], false,
"previous-release gateway credential reached the sidecar"
);
assert_eq!(response["hasUnrelatedSecret"], false);
let expected = match agent {
@@ -98,7 +98,7 @@ describe("configured environment authority", () => {
} finally { vi.unstubAllEnvs(); }
});
it.each(["not-json", "[1]", '["NODE_OPTIONS"]', '["PAPERCLIP_API_KEY"]', '["PAPERCLIP_RUNNER_BOOTSTRAP_TICKET"]', '["OPENAI_API_KEY"]', '["KIMI_API_KEY"]', '["LD_PRELOAD"]', '["bad=name"]', '["CUSTOM","CUSTOM"]', '["MISSING"]'])
it.each(["not-json", "[1]", '["NODE_OPTIONS"]', '["PAPERCLIP_API_KEY"]', '["PAPERCLIP_RUNNER_BOOTSTRAP_TICKET"]', '["OPENAI_API_KEY"]', '["KIMI_API_KEY"]', '["PAPERCLIP_NATIVE_MCP_NAME"]', '["PAPERCLIP_NATIVE_MCP_URL"]', '["PAPERCLIP_NATIVE_MCP_TOKEN"]', '["LD_PRELOAD"]', '["bad=name"]', '["CUSTOM","CUSTOM"]', '["MISSING"]'])
("rejects malformed or reserved projection %s", raw => {
expect(() => configuredEnvironment({ [CONFIGURED_ENVIRONMENT_KEYS]: raw })).toThrow("Invalid configured environment");
});
@@ -4887,9 +4887,6 @@ const runnerExplicitProviderEnvironmentKeys = [
"PAPERCLIP_RUNNER_INSTANCE_ID",
"PAPERCLIP_RUN_ID",
"PAPERCLIP_NORMALIZED_SESSION_ID",
"PAPERCLIP_NATIVE_MCP_NAME",
"PAPERCLIP_NATIVE_MCP_URL",
"PAPERCLIP_NATIVE_MCP_TOKEN",
"PAPERCLIP_NATIVE_MCP_STDIO",
"PAPERCLIP_NATIVE_MCP_PROXY",
"PAPERCLIP_NATIVE_RUNTIME_CONTEXT_PATH",
@@ -185,7 +185,7 @@ describe("ACPX launch environment", () => {
expect(createSanitizedAcpxSpawnInput(source, "pi").env).toEqual({ COPILOT_GITHUB_TOKEN: "copilot-key" });
});
it("strips configured Kimi model redirects and home overrides while retaining selected task and MCP values", () => {
it("strips configured Kimi model redirects, home overrides and retired gateway values while retaining selected task values", () => {
const overrides = {
KIMI_MODEL_NAME: "__kimi_env_model__", KIMI_MODEL_API_KEY: "unselected-model-key",
KIMI_MODEL_BASE_URL: "https://unselected.invalid/v1", KIMI_MODEL_PROVIDER_TYPE: "openai_legacy",
@@ -200,8 +200,8 @@ describe("ACPX launch environment", () => {
for (const environment of [sidecar, createSanitizedAcpxSpawnInput(source, "kimi").env,
createSanitizedAcpxSpawnInput(sidecar, "kimi").env]) {
for (const name of Object.keys(overrides)) expect(environment).not.toHaveProperty(name);
expect(environment).toMatchObject({ KIMI_API_KEY: "selected-code-key", CUSTOM_SETTING: "allowed",
PAPERCLIP_NATIVE_MCP_NAME: "assigned", PAPERCLIP_NATIVE_MCP_URL: "https://assigned.example/mcp" });
expect(environment).toMatchObject({ KIMI_API_KEY: "selected-code-key", CUSTOM_SETTING: "allowed" });
if (environment !== sidecar) for (const name of ["PAPERCLIP_NATIVE_MCP_NAME", "PAPERCLIP_NATIVE_MCP_URL", "PAPERCLIP_NATIVE_MCP_TOKEN"]) expect(environment).not.toHaveProperty(name);
expect(JSON.parse(environment[CONFIGURED_ENVIRONMENT_KEYS]!)).toEqual(["CUSTOM_SETTING"]);
}
expect(createSanitizedAcpxSpawnInput(source, "kimi").env).not.toHaveProperty("PAPERCLIP_NATIVE_MCP_TOKEN");
@@ -144,10 +144,8 @@ export function createSanitizedAcpxSpawnInput(
"no_proxy",
"all_proxy",
"RUST_BACKTRACE",
"PAPERCLIP_NATIVE_MCP_NAME",
"PAPERCLIP_RUNTIME_NOTIFICATION_CONTEXT",
"PAPERCLIP_RUNTIME_NOTIFICATION_HELPER",
"PAPERCLIP_NATIVE_MCP_URL",
...(environment === undefined ? [] : ["PAPERCLIP_AGENT_KEY_ID", "PAPERCLIP_AGENT_PUBLIC_KEY", "PAPERCLIP_AGENT_PRIVATE_KEY"]),
...credentialNames,
...(agent === "claude" ? CLAUDE_ROUTING_ENV_KEYS : []),
@@ -374,17 +374,6 @@ describe("ACPX runtime host", () => {
expect(await readFile(auth, "utf8")).toBe('{"user_owned":true}');
});
it.each([
{ PAPERCLIP_NATIVE_MCP_NAME: "paperclip-assigned" },
{ PAPERCLIP_NATIVE_MCP_NAME: "paperclip", PAPERCLIP_NATIVE_MCP_URL: "http://127.0.0.1:3211/mcp", PAPERCLIP_NATIVE_MCP_TOKEN: "x".repeat(40) },
{ PAPERCLIP_NATIVE_MCP_NAME: "paperclip-assigned", PAPERCLIP_NATIVE_MCP_URL: "http://external.example/mcp", PAPERCLIP_NATIVE_MCP_TOKEN: "x".repeat(40) },
])("rejects invalid assigned connection bindings before runtime launch", async (environment) => {
const fixture = await hostFixture();
const openRuntime = vi.fn();
await expect(AcpxRuntimeHost.open({ ...fixture.options, agent: "claude", model: "claude-sonnet-5", permissionMode: "approve-reads", environment }, fixture.dependencies({ openRuntime }))).rejects.toThrow(/assigned native MCP/);
expect(openRuntime).not.toHaveBeenCalled();
});
it("leaves an active Claude owner's effort settings unchanged when a second opener loses the lifetime lease", async () => {
const fixture = await hostFixture();
let settingsPath = "";
@@ -487,28 +476,34 @@ describe("ACPX runtime host", () => {
expect(openRuntime).toHaveBeenCalledTimes(1);
});
it("registers the assigned connection gateway alongside the Claude task bridge", async () => {
it.each([
{ agent: "claude" as const, model: "claude-sonnet-5", environment: {} },
{ agent: "codex" as const, model: "gpt-5.6-sol", environment: { OPENAI_API_KEY: "synthetic-test-key" } },
{ agent: "cursor" as const, model: "explicit-test-model", environment: { CURSOR_API_KEY: "test" } },
])("admits a relayed $agent run with a binding id and ignores a previous-release gateway binding", async ({ agent, model, environment }) => {
const fixture = await hostFixture();
let servers: AcpxRuntimePortOpenOptions["mcpServers"] = [];
const retiredGateway = {
PAPERCLIP_NATIVE_MCP_NAME: "paperclip-assigned",
PAPERCLIP_NATIVE_MCP_URL: "http://127.0.0.1:3211/mcp/gateways/previous-release",
PAPERCLIP_NATIVE_MCP_TOKEN: "previous-release-gateway-token-".repeat(2),
};
let launch: AcpxRuntimePortOpenOptions | undefined;
const host = await AcpxRuntimeHost.open({
...fixture.options,
agent: "claude", model: "claude-sonnet-5",
permissionMode: "approve-reads",
environment: {
PAPERCLIP_NATIVE_MCP_NAME: "paperclip-assigned",
PAPERCLIP_NATIVE_MCP_URL: "http://127.0.0.1:3211/mcp/gateway",
PAPERCLIP_NATIVE_MCP_TOKEN: "fixture-gateway-token-".repeat(3),
},
...fixture.options, agent, model, permissionMode: "approve-all",
runtimeContext: { skills: [], instructions: {}, mcp: { bindingId: "assigned-run" } } as unknown as NativeRuntimeContextSnapshot,
environment: { ...environment, ...retiredGateway },
assignedMcpTransport: "prp",
semanticTools: { tools: [], handler: async () => ({}) },
}, fixture.dependencies({ openRuntime: async (options) => {
servers = options.mcpServers;
return runtimePort({ getStatus: async () => ({ models: { currentModelId: "claude-sonnet-5" } }) });
}, fixture.dependencies({ openRuntime: async options => {
launch = options;
return runtimePort({ getStatus: async () => ({ models: { currentModelId: model } }),
...(agent === "cursor" ? { identity: async () => ({ acpxRecordId: "record-1", backendSessionId: "backend-1", agentSessionId: "agent-1", mode: "agent" }) } : {}) });
} }));
try {
expect(servers.map(server => server.name)).toEqual(["paperclip", "paperclip-assigned"]);
expect(servers[1]).toEqual({ name: "paperclip-assigned", url: "http://127.0.0.1:3211/mcp/gateway",
bearerToken: "fixture-gateway-token-".repeat(3), runnerOwned: true });
} finally { await host.close({ reason: "gateway test complete" }); }
expect(launch!.mcpServers.map(server => server.name)).toEqual(["paperclip"]);
for (const name of Object.keys(retiredGateway)) expect(launch!.launchEnvironment).not.toHaveProperty(name);
expect(JSON.stringify(launch!.launchEnvironment)).not.toContain("previous-release");
} finally { await host.close({ reason: "relayed admission verified" }); }
});
it.each([false, true])("keeps stdio registration session-local and omits it for readOnly=%s", async readOnly => {
@@ -21,7 +21,6 @@ import { stageManagedGrokCredential } from "./grok-credentials.js";
import { stageManagedAntigravityCredential } from "./antigravity-credentials.js";
import { claudeNativeSkillPrompt } from "./native-skill-prompt.js";
import { prepareStdioMcpBindings } from "../stdio-mcp.js";
import { nativeMcpLaunchBinding } from "../native-mcp.js";
import type {
AcpRuntimeOptions,
@@ -381,11 +380,7 @@ export class AcpxRuntimeHost {
}
// shortcut: qualify session permissions that deny Runner state before enabling this provider.
if (preconfigured && options.agent === "codex") throw new Error("preconfigured ACPX Codex cannot protect Runner state; use native Codex or isolated mode");
const nativeMcp = preconfigured ? null : nativeMcpLaunchBinding(options.environment);
if (nativeMcp?.name === "paperclip") {
throw new Error("assigned native MCP name conflicts with the task bridge");
}
if (!preconfigured && options.runtimeContext?.mcp.bindingId && !nativeMcp
if (!preconfigured && options.runtimeContext?.mcp.bindingId
&& !(options.assignedMcpTransport === "prp" && options.semanticTools)) {
throw new Error("assigned native MCP launch binding is unavailable");
}
@@ -710,10 +705,6 @@ export class AcpxRuntimeHost {
...(options.providerPolicy?.readOnly ? [] : prepareStdioMcpBindings(options.environment ?? {}, sandbox.root)),
...(toolBridge ? [{ name: preconfigured ? `paperclip_runner_${binding.profileSessionKey.slice(-16)}` : "paperclip", url: toolBridge.url,
bearerToken: toolBridge.secret, runnerOwned: true }] : []),
// This is Paperclip's authenticated gateway, not a direct upstream
// binding. Its existing grants and approval checks remain authoritative.
...(nativeMcp ? [{ name: nativeMcp.name, url: nativeMcp.url,
bearerToken: nativeMcp.token, runnerOwned: true }] : []),
],
...(options.onGoalUpdate === undefined
? {}
@@ -24,14 +24,13 @@ it("transports a valid encoded header set in both Codex exporters without reject
expect(providerObservabilityEnvironment({ PAPERCLIP_OBSERVABILITY_CODEX_CONFIG: value }, "codex")).toEqual({ PAPERCLIP_OBSERVABILITY_CODEX_CONFIG: value });
expect(() => providerObservabilityEnvironment({ PAPERCLIP_OBSERVABILITY_CODEX_CONFIG: "x".repeat(128 * 1024 + 1) }, "codex")).toThrow("Invalid observability launch environment");
});
it("materializes the real native home with both governed MCP and protected export config", async () => {
it("materializes the real native home with protected export config and no MCP servers", async () => {
const home = await mkdtemp(join(tmpdir(), "paperclip-native-otel-")); roots.push(home);
await mkdir(join(home, "source"));
await writeFile(join(home, "source", "auth.json"), '{"OPENAI_API_KEY":"fixture"}');
await prepareIsolatedCodexHome({ context: null, codexHome: home, sourceCodexHome: join(home, "source"), observability: launch,
nativeMcp: { name: "paperclip-assigned", url: "https://paperclip.example/mcp", token: "mcp-secret" } });
await prepareIsolatedCodexHome({ context: null, codexHome: home, sourceCodexHome: join(home, "source"), observability: launch });
const config = parse(await readFile(join(home, "config.toml"), "utf8"));
expect(config.otel).toEqual(launch.otelConfig); expect(config.mcp_servers).toHaveProperty("paperclip-assigned");
expect(config.otel).toEqual(launch.otelConfig); expect(config.mcp_servers).toBeUndefined();
expect(JSON.stringify(config)).not.toContain("secret-canary");
expect((await stat(join(home, "config.toml"))).mode & 0o777).toBe(0o600);
});
@@ -1,41 +0,0 @@
export interface NativeMcpLaunchBinding {
name: string;
url: string;
token: string;
}
export function nativeMcpLaunchBinding(
environment: NodeJS.ProcessEnv = process.env,
): NativeMcpLaunchBinding | null {
const name = environment.PAPERCLIP_NATIVE_MCP_NAME?.trim();
const url = environment.PAPERCLIP_NATIVE_MCP_URL?.trim();
const token = environment.PAPERCLIP_NATIVE_MCP_TOKEN?.trim();
if (!name && !url && !token) return null;
if (
!name
|| !url
|| !token
|| token.length < 32
|| token.length > 4096
|| url.length > 2048
) {
throw new Error("assigned native MCP launch binding is incomplete");
}
if (!/^[a-zA-Z0-9_.-]{1,128}$/.test(name)) {
throw new Error("assigned native MCP name is invalid");
}
const endpoint = new URL(url);
if (endpoint.username || endpoint.password || endpoint.hash) {
throw new Error("assigned native MCP endpoint contains forbidden URL data");
}
if (
endpoint.protocol !== "https:"
&& !(endpoint.protocol === "http:"
&& ["127.0.0.1", "localhost"].includes(endpoint.hostname))
) {
throw new Error(
"assigned native MCP endpoint requires HTTPS or loopback HTTP",
);
}
return { name, url: endpoint.toString(), token };
}
@@ -2107,7 +2107,7 @@ describe("OpenCodeServerDriver", () => {
await session.close({ reason: "test" });
});
it.each([false, true])("uses the native system channel, selected skill tree, instruction root, and assigned MCP gateway after startup retry=%s", async (retryStartup) => {
it.each([false, true])("uses the native system channel, selected skill tree, instruction root, and only the task bridge after startup retry=%s", async (retryStartup) => {
await chmod(fixture, 0o755);
const root = await mkdtemp(join(tmpdir(), "paperclip-opencode-context-"));
const workspace = await mkdtemp(
@@ -2209,12 +2209,10 @@ describe("OpenCodeServerDriver", () => {
},
mcp: {
paperclip: { enabled: true },
"paperclip-assigned": {
url: "https://paperclip.example/mcp",
enabled: true,
},
},
});
expect(Object.keys(config.mcp)).toEqual(["paperclip"]);
expect(JSON.stringify(config)).not.toContain("x".repeat(40));
await expect(
readFile(join(instructionRoot, "sibling.md"), "utf8"),
).resolves.toBe("instruction sibling\n");
@@ -95,7 +95,6 @@ import {
type OpenCodeMcpBridge,
type OpenCodeMcpBridgeOptions,
} from "./mcp-bridge.js";
import { nativeMcpLaunchBinding } from "../native-mcp.js";
import { toolCallMarkupStart, visibleBeforeToolCallMarkup } from "./tool-call-markup.js";
import {
materializeNativeRuntimeSkills,
@@ -2676,9 +2675,6 @@ async function startRuntime(input: {
await removeIsolatedHome(isolatedHome).catch(() => undefined);
throw error;
});
const assignedMcp = nativeMcpLaunchBinding(
input.options.environment ?? process.env,
);
const identityKey = input.options.environment?.PAPERCLIP_AGENT_PRIVATE_KEY;
const identityValues = identityKey ? [identityKey, JSON.stringify(identityKey).slice(1, -1),
...identityKey.split(/\r?\n/).filter(line => line && !line.startsWith("-----"))] : [];
@@ -2690,7 +2686,6 @@ async function startRuntime(input: {
password,
authHeader,
bridge.secret,
assignedMcp?.token,
providerEnvironment.OPENROUTER_API_KEY,
providerEnvironment.PAPERCLIP_AI_PROVIDER_KEY,
].filter((value): value is string => Boolean(value));
@@ -2822,18 +2817,6 @@ async function startRuntime(input: {
// must still remain pending and block replay after client expiry.
timeout: input.options.durableToolRequests ? 60 * 60 * 1_000 : 30_000,
},
...(assignedMcp
? {
[assignedMcp.name]: {
type: "remote",
url: assignedMcp.url,
enabled: true,
oauth: false,
headers: { Authorization: `Bearer ${assignedMcp.token}` },
timeout: 30_000,
},
}
: {}),
},
};
await writeFile(
@@ -24,7 +24,6 @@ import {
parseNativeRuntimeContext,
type NativeRuntimeContextSnapshot,
} from "../contracts/runtime-context.js";
import { nativeMcpLaunchBinding } from "./native-mcp.js";
import {
materializeNativeRuntimeSkills,
prepareIsolatedCodexRecoveryHome,
@@ -106,21 +105,7 @@ describe("runtime context materialization", () => {
expect(parseNativeRuntimeContext(next).instructions.workingCopy?.kind).toBe("agent_files");
});
it("validates native MCP launch bindings before they reach Codex", () => {
expect(nativeMcpLaunchBinding({})).toBeNull();
expect(() => nativeMcpLaunchBinding({
PAPERCLIP_NATIVE_MCP_NAME: "paperclip",
PAPERCLIP_NATIVE_MCP_URL: "http://paperclip.example/mcp",
PAPERCLIP_NATIVE_MCP_TOKEN: "x".repeat(40),
})).toThrow("requires HTTPS or loopback HTTP");
expect(() => nativeMcpLaunchBinding({
PAPERCLIP_NATIVE_MCP_NAME: "paperclip",
PAPERCLIP_NATIVE_MCP_URL: "https://user:pass@paperclip.example/mcp#secret",
PAPERCLIP_NATIVE_MCP_TOKEN: "x".repeat(40),
})).toThrow("contains forbidden URL data");
});
it("copies only assigned skills and writes an isolated MCP config", async () => {
it("copies only assigned skills and writes an isolated config with no MCP servers", async () => {
const root = await mkdtemp(join(tmpdir(), "paperclip-runtime-context-"));
roots.push(root);
const assigned = join(root, "assigned-source");
@@ -144,11 +129,6 @@ describe("runtime context materialization", () => {
context: context(assigned, instructions),
codexHome,
sourceCodexHome: join(root, "host-home"),
nativeMcp: nativeMcpLaunchBinding({
PAPERCLIP_NATIVE_MCP_NAME: "paperclip-assigned",
PAPERCLIP_NATIVE_MCP_URL: "https://paperclip.example/mcp",
PAPERCLIP_NATIVE_MCP_TOKEN: "x".repeat(40),
}),
});
await expect(readFile(
@@ -162,9 +142,8 @@ describe("runtime context materialization", () => {
).toBe(0);
const config = await readFile(join(codexHome, "config.toml"), "utf8");
expect(config).toContain("shell_snapshot = false");
expect(config).toContain("paperclip-assigned");
expect(config).toContain('default_tools_approval_mode = "approve"');
expect(config).toContain("Bearer ");
expect(parse(config).mcp_servers).toBeUndefined();
expect(config).not.toContain("Bearer ");
expect(config).not.toContain("unassigned");
});
@@ -530,18 +509,13 @@ base_url = "https://example.com/v1"
wire_api = "responses"
requires_openai_auth = false
`);
const nativeMcp = mode === "selected"
? { name: "assigned", url: "https://paperclip.example/mcp/current", token: "current-assigned-gateway-credential" }
: null;
await prepareIsolatedCodexRecoveryHome({ codexHome, sourceCodexHome, nativeMcp });
await prepareIsolatedCodexRecoveryHome({ codexHome, sourceCodexHome });
const restoredConfig = await readFile(join(codexHome, "config.toml"), "utf8");
expect(restoredConfig).not.toContain("attacker.invalid");
expect(restoredConfig).not.toContain("mcp_servers.stale");
expect(restoredConfig).toContain('cli_auth_credentials_store = "file"');
expect(restoredConfig).toContain("shell_snapshot = false");
expect(parse(restoredConfig).mcp_servers ?? {}).toEqual(nativeMcp ? {
assigned: { url: nativeMcp.url, default_tools_approval_mode: "approve", http_headers: { Authorization: `Bearer ${nativeMcp.token}` } },
} : {});
expect(parse(restoredConfig).mcp_servers).toBeUndefined();
expect(restoredConfig.includes("https://example.com/v1")).toBe(mode === "routing");
expect(await readFile(join(codexHome, "skills", "retained"), "utf8")).toBe("source skills");
if (mode === "selected") {
@@ -550,7 +524,7 @@ requires_openai_auth = false
} else await expect(stat(join(codexHome, "auth.json"))).rejects.toMatchObject({ code: "ENOENT" });
});
it.each(["next_run", "same_run_recovery"] as const)("drops a retained direct gateway server when the relayed launch has no binding (%s)", async mode => {
it.each(["next_run", "same_run_recovery"] as const)("drops a retained direct gateway server from a previous-release Codex home (%s)", async mode => {
const root = await mkdtemp(join(tmpdir(), "paperclip-relayed-codex-home-"));
roots.push(root);
const codexHome = join(root, "retained-provider");
@@ -566,9 +540,8 @@ requires_openai_auth = false
'http_headers = { Authorization = "Bearer revoked-previous-release-gateway-token" }',
"",
].join("\n"));
const nativeMcp = nativeMcpLaunchBinding({});
if (mode === "next_run") await prepareIsolatedCodexHome({ context: null, codexHome, nativeMcp });
else await prepareIsolatedCodexRecoveryHome({ codexHome, nativeMcp });
if (mode === "next_run") await prepareIsolatedCodexHome({ context: null, codexHome });
else await prepareIsolatedCodexRecoveryHome({ codexHome });
const config = await readFile(join(codexHome, "config.toml"), "utf8");
expect(parse(config).mcp_servers).toBeUndefined();
expect(config).not.toContain("revoked-previous-release-gateway-token");
@@ -17,7 +17,6 @@ import { parse as parseToml } from "smol-toml";
import { codexObservabilityToml } from "./agent-observability.js";
import type { NativeRuntimeContextSnapshot } from "../contracts/runtime-context.js";
import type { NativeMcpLaunchBinding } from "./native-mcp.js";
async function assertSafeTree(root: string, child = ""): Promise<void> {
const directory = child ? join(root, child) : root;
@@ -337,7 +336,6 @@ export async function prepareIsolatedCodexHome(input: {
context: NativeRuntimeContextSnapshot | null;
codexHome: string;
sourceCodexHome?: string | null;
nativeMcp?: NativeMcpLaunchBinding | null;
apiKey?: string | null;
}): Promise<void> {
await materializeNativeRuntimeSkills(
@@ -350,7 +348,7 @@ export async function prepareIsolatedCodexHome(input: {
await writeIsolatedCodexAuth(input, providerConfig);
}
async function writeIsolatedCodexConfig(input: CodexAuthInput & { nativeMcp?: NativeMcpLaunchBinding | null }, providerConfig: string): Promise<void> {
async function writeIsolatedCodexConfig(input: CodexAuthInput, providerConfig: string): Promise<void> {
const configPath = join(input.codexHome, "config.toml");
await mkdir(input.codexHome, { recursive: true, mode: 0o700 });
await chmod(input.codexHome, 0o700);
@@ -366,18 +364,6 @@ async function writeIsolatedCodexConfig(input: CodexAuthInput & { nativeMcp?: Na
"[features]",
"shell_snapshot = false",
"",
...(input.nativeMcp
? [
`[mcp_servers.${JSON.stringify(input.nativeMcp.name)}]`,
`url = ${JSON.stringify(input.nativeMcp.url)}`,
// This endpoint is Paperclip's authenticated policy gateway, not an
// upstream server. It enforces connection grants and human approvals
// for every operation; the provider must deliver calls to that gate.
'default_tools_approval_mode = "approve"',
`http_headers = { Authorization = ${JSON.stringify(`Bearer ${input.nativeMcp.token}`)} }`,
"",
]
: []),
].join("\n"), { mode: 0o600, flag: "wx" });
await rename(temporaryConfig, configPath);
await chmod(configPath, 0o600);
@@ -391,7 +377,7 @@ type CodexAuthInput = {
observability?: import("./agent-observability.js").ProviderObservabilityLaunch;
};
export async function prepareIsolatedCodexRecoveryHome(input: CodexAuthInput & { nativeMcp?: NativeMcpLaunchBinding | null }): Promise<void> {
export async function prepareIsolatedCodexRecoveryHome(input: CodexAuthInput): Promise<void> {
const providerConfig = await managedCodexProviderConfig(input.sourceCodexHome);
await writeIsolatedCodexConfig(input, providerConfig);
await writeIsolatedCodexAuth(input, providerConfig);
@@ -56,9 +56,9 @@ describe("assigned stdio MCP bindings", () => {
expect(() => stdioMcpLaunchBindings(environment)).toThrow();
}
});
it("rejects duplicate names and collisions with the existing HTTP gateway", () => {
it("rejects duplicate names and the task bridge name", () => {
const { binding, environment } = fixture();
expect(() => stdioMcpLaunchBindings({ ...environment, [STDIO_MCP_BINDINGS_ENV]: JSON.stringify([binding, binding]) })).toThrow();
expect(() => stdioMcpLaunchBindings({ ...environment, PAPERCLIP_NATIVE_MCP_NAME: binding.name })).toThrow();
expect(() => stdioMcpLaunchBindings({ ...environment, [STDIO_MCP_BINDINGS_ENV]: JSON.stringify([{ ...binding, name: "paperclip" }]) })).toThrow();
});
});
@@ -21,7 +21,7 @@ export function stdioMcpLaunchBindings(environment: NodeJS.ProcessEnv): StdioMcp
let values: unknown;
try { values = JSON.parse(raw); } catch { throw invalid(); }
if (!Array.isArray(values) || values.length > 8) throw invalid();
const names = new Set<string>(["paperclip", environment.PAPERCLIP_NATIVE_MCP_NAME ?? ""]);
const names = new Set<string>(["paperclip"]);
return values.map((value: unknown) => {
if (!value || typeof value !== "object" || Array.isArray(value)) throw invalid();
const binding = value as Record<string, unknown>;
@@ -1513,9 +1513,9 @@ it.each([false, true, "restart-before-bootstrap", "unknown-semantic", "accountin
expect(retainedCore.commands.some((command: { type: string }) => command.type === "run.attach")).toBe(false);
if (credentialsCleaned) {
const config = await readFile(join(stateDirectory, "codex-home", "config.toml"), "utf8");
expect(config).toContain("https://paperclip.example/mcp/current");
expect(config).toContain("current-assigned-gateway-credential");
expect(config).not.toContain("first-assigned-gateway-credential");
expect(config).not.toContain("mcp_servers");
expect(config).not.toContain("paperclip.example/mcp");
expect(config).not.toContain("assigned-gateway-credential");
expect(currentHandler).not.toHaveBeenCalled();
}
}
@@ -6456,15 +6456,17 @@ it.each([
}
}, 30_000);
it.each(["claude", "codex"] as const)("keeps the explicitly assigned gateway in the %s runner environment", (agent) => {
it.each([
["acpx", "claude"], ["acpx", "codex"], ["acpx", "pi"], ["acpx", "cursor"], ["acpx", "copilot"], ["acpx", "kimi"], ["opencode", undefined],
] as const)("drops a previous-release gateway binding from the %s %s runner environment", (provider, agent) => {
const gateway = {
PAPERCLIP_NATIVE_MCP_NAME: "paperclip-assigned",
PAPERCLIP_NATIVE_MCP_URL: "http://127.0.0.1:3100/mcp/gateway",
PAPERCLIP_NATIVE_MCP_URL: "http://127.0.0.1:3100/mcp/gateways/previous-release",
PAPERCLIP_NATIVE_MCP_TOKEN: "fixture-scoped-gateway-token-1234567890",
};
const environment = createCapabilityRunnerdProviderEnvironment({
provider: "acpx",
options: { provider: "acpx", acpxAgent: agent, environment: {
provider,
options: { provider, ...(agent ? { acpxAgent: agent } : {}), environment: {
PATH: "/bin", ...gateway, PAPERCLIP_API_KEY: "must-not-cross", DATABASE_URL: "must-not-cross",
} },
identity: { runnerInstanceId: "runner-1", environmentLeaseId: "lease-1", runId: "run-1",
@@ -6472,7 +6474,9 @@ it.each(["claude", "codex"] as const)("keeps the explicitly assigned gateway in
codexHome: "/isolated/home", runtimeContextPath: "/isolated/context.json", hasRuntimeContext: true,
acpxSidecarPath: "/verified/provider-pack/dist/cli/acpx-runtime-sidecar.cjs",
});
expect(environment).toMatchObject(gateway);
for (const name of Object.keys(gateway)) expect(environment).not.toHaveProperty(name);
expect(JSON.stringify(environment)).not.toContain("fixture-scoped-gateway-token");
expect(JSON.stringify(environment)).not.toContain("previous-release");
expect(environment.PAPERCLIP_API_KEY).toBeUndefined();
expect(environment.DATABASE_URL).toBeUndefined();
});
@@ -98,7 +98,6 @@ import type {
NativeAcpxPermissionMode,
NativeOpenCodePermissionMode,
} from "../contracts/native-execution.js";
import { nativeMcpLaunchBinding } from "../drivers/native-mcp.js";
import {
prepareIsolatedCodexHome,
prepareIsolatedCodexRecoveryHome,
@@ -3793,16 +3792,10 @@ function createCapabilityRunnerdProviderEnvironmentBase(input: {
const providerPackageAuthority = acpxProviderPackageAuthority(
sidecarPath, packageRoot, input.options.acpxAgent,
);
// This is the trusted runner/sidecar boundary. The provider sandbox still
// uses createSanitizedAcpxSpawnInput and does not inherit gateway tokens.
const assignedGateway = nativeMcpLaunchBinding(input.options.environment ?? {});
const credentialBinding = createAcpxCredentialBinding(
input.options.environment, input.options.acpxAgent ?? "codex", input.identity.normalizedSessionId,
);
return {
...(assignedGateway ? {
PAPERCLIP_NATIVE_MCP_TOKEN: assignedGateway.token,
} : {}),
...createSanitizedAcpxSpawnInput(
input.options.environment,
input.options.acpxAgent ?? "codex",
@@ -3890,9 +3883,6 @@ const OPEN_CODE_RUNNER_ENVIRONMENT_KEYS = new Set([
"WINDIR",
"RUST_BACKTRACE",
"OPENROUTER_API_KEY",
"PAPERCLIP_NATIVE_MCP_NAME",
"PAPERCLIP_NATIVE_MCP_URL",
"PAPERCLIP_NATIVE_MCP_TOKEN",
]);
function createSanitizedOpenCodeRunnerEnvironment(
@@ -6088,7 +6078,6 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
apiKey:
this.options.environment?.CODEX_API_KEY ??
this.options.environment?.OPENAI_API_KEY,
nativeMcp: nativeMcpLaunchBinding(this.options.environment),
});
}
this.#assertStartupOpen();
@@ -7212,7 +7201,6 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
await prepareIsolatedCodexRecoveryHome({
...auth,
observability: this.options.observability,
nativeMcp: nativeMcpLaunchBinding(this.options.environment),
});
} else {
await releaseMaterializedNativeRuntimeSkills(resolve(localCodexHome, "skills"));
@@ -7221,7 +7209,6 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
...auth,
context: sourceRuntimeContext,
observability: this.options.observability,
nativeMcp: nativeMcpLaunchBinding(this.options.environment),
});
}
}