Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

feat(coding-agent): support ACP MCP programs (#1378)

Konstantin Dunasc75a637b00d3
diff --git a/packages/coding-agent/.changes/1378-acp-mcp-programs.md b/packages/coding-agent/.changes/1378-acp-mcp-programs.md
new file mode 100644
index 0000000000..c6b8a790fb
--- /dev/null
+++ b/packages/coding-agent/.changes/1378-acp-mcp-programs.md
@@ -0,0 +1 @@
+- Added session-scoped ACP MCP servers through the kernel MCP program API ([#1378](https://github.com/PrimeIntellect-ai/prime-agent/pull/1378) by [@hallerite](https://github.com/hallerite)).
diff --git a/packages/coding-agent/docs/acp.md b/packages/coding-agent/docs/acp.md
index a77542597d..bb56ad6cc7 100644
--- a/packages/coding-agent/docs/acp.md
+++ b/packages/coding-agent/docs/acp.md
@@ -28,6 +28,30 @@ One session per connection is a deliberate limit: Prime Agent's underlying sessi
Likewise `session/prompt` refuses a concurrent turn while one is running, and the working directory cannot be changed after startup — a client-supplied `cwd` that differs from the agent's real one is reported back in `_meta` rather than silently ignored.
+## MCP servers
+
+Prime Agent accepts standard stdio and HTTP servers in `session/new.mcpServers`. The servers are
+available through the pre-imported `mcp` Python program for that ACP session:
+
+```python
+tools = await mcp.list_tools("task-tools")
+result = await mcp.call_tool("task-tools", "lookup", {"query": "example"})
+```
+
+HTTP requests use only the URL and headers supplied by the ACP client. They do not read
+`auth.json`, start or refresh Prime Agent OAuth, or modify persistent MCP settings. Stdio servers
+run with the agent's actual session cwd, the supplied command and arguments, a scrubbed base
+environment, and the exact environment values supplied by the ACP client.
+
+The configuration is removed when the ACP session closes or the client disconnects. A same-named
+persistent MCP server can therefore be shadowed for the ACP session without sending its stored
+OAuth credential to the client-supplied HTTP endpoint. Daemon-backed configuration is bound to the
+ACP connection that installed it, so another attached client cannot replace or clear it.
+
+ACP stdio is a trusted-code boundary, not a sandbox. The requested command runs as the Prime Agent
+user and can access any files that user can access, including credential stores. Only accept stdio
+servers from trusted ACP clients or run Prime Agent inside an appropriate sandbox.
+
## Streamed updates
Session activity arrives as `session/update` notifications:
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index ef75fe91d7..4f187593df 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -156,6 +156,7 @@ import {
} from "./goals.js";
import type { HostRequestHandlers, KernelSentAgentMessage } from "./kernel/index.js";
import { type RestoreResult, snapshotPathIn } from "./kernel/state-snapshot.js";
+import type { AcpMcpServerConfig } from "./mcp/acp-mcp-types.js";
import type { McpManager } from "./mcp/mcp-manager.js";
import {
type BashExecutionMessage,
@@ -1303,6 +1304,67 @@ export class AgentSession {
this.agent.state.systemPrompt = this._baseSystemPrompt;
}
+ replaceAcpMcpServers(servers: readonly AcpMcpServerConfig[], ownerId: string): void {
+ if (this.isStreaming) throw new Error("Cannot replace ACP MCP servers while the agent is running");
+ if (!this._mcpManager) {
+ if (servers.length > 0) throw new Error("MCP is unavailable in this session");
+ return;
+ }
+ if (!this._mcpManager.replaceAcpServers(servers, ownerId)) return;
+ this._rebuildRuntimeForAcpMcpServers();
+ }
+
+ async releaseAcpMcpServers(ownerId: string, serverNames: readonly string[]): Promise<void> {
+ if (!this._mcpManager?.canReleaseAcpServers(ownerId)) return;
+ if (this._mcpManager.replaceAcpServers([], ownerId)) {
+ // Host MCP handlers read this manager dynamically, so credentials disappear
+ // before the kernel-side transport is closed.
+ this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());
+ this.agent.state.systemPrompt = this._baseSystemPrompt;
+ }
+ const names = [...new Set(serverNames)];
+ if (names.length === 0) return;
+
+ const inputPause = this.acquireSessionInputPause();
+ try {
+ // Do not rebuild or kill the notebook. Wait for the current turn, then ask
+ // the kernel-owned MCP registry to close only these cached transports.
+ await this.agent.waitForIdle();
+ await this._agentEventQueue;
+ const manager = this._ipythonKernelProvisioner?.manager;
+ if (!manager?.isRunning) return;
+ const code = [
+ "import importlib as _prime_importlib",
+ '_prime_mcp = _prime_importlib.import_module("rlm.mcp")',
+ `_prime_mcp_names = ${JSON.stringify(names)}`,
+ "_prime_mcp_errors = []",
+ "for _prime_mcp_name in _prime_mcp_names:",
+ " try:",
+ " await _prime_mcp.reload(_prime_mcp_name)",
+ " except BaseException as _prime_mcp_error:",
+ " _prime_mcp_errors.append(_prime_mcp_error)",
+ "if _prime_mcp_errors:",
+ " raise _prime_mcp_errors[0]",
+ "del _prime_mcp, _prime_importlib, _prime_mcp_names, _prime_mcp_errors, _prime_mcp_name",
+ ].join("\n");
+ const result = await manager.execute(code);
+ if (result.status !== "ok") {
+ throw new Error(`Failed to close ACP MCP kernel transports: ${result.stderr || "kernel error"}`);
+ }
+ } finally {
+ inputPause.release();
+ }
+ }
+
+ private _rebuildRuntimeForAcpMcpServers(): void {
+ this._buildRuntime({
+ activeToolNames: this.getActiveToolNames(),
+ includeAllExtensionTools: true,
+ });
+ this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());
+ this.agent.state.systemPrompt = this._baseSystemPrompt;
+ }
+
get modelRegistry(): ModelRegistry {
return this._modelRegistry;
}
diff --git a/packages/coding-agent/src/core/mcp/acp-mcp-types.ts b/packages/coding-agent/src/core/mcp/acp-mcp-types.ts
new file mode 100644
index 0000000000..e4d0222060
--- /dev/null
+++ b/packages/coding-agent/src/core/mcp/acp-mcp-types.ts
@@ -0,0 +1,15 @@
+export type AcpMcpServerConfig =
+ | {
+ name: string;
+ type: "http";
+ url: string;
+ headers: Record<string, string>;
+ }
+ | {
+ name: string;
+ type: "stdio";
+ command: string;
+ args: string[];
+ cwd: string;
+ env: Record<string, string>;
+ };
diff --git a/packages/coding-agent/src/core/mcp/mcp-manager.ts b/packages/coding-agent/src/core/mcp/mcp-manager.ts
index fdf8220463..6031651078 100644
--- a/packages/coding-agent/src/core/mcp/mcp-manager.ts
+++ b/packages/coding-agent/src/core/mcp/mcp-manager.ts
@@ -10,6 +10,7 @@ import {
import { registerOAuthProvider, unregisterOAuthProvider } from "@earendil-works/pi-ai/oauth";
import type { AuthStorage } from "../auth-storage.js";
import type { McpServerConfig } from "../settings-manager.js";
+import type { AcpMcpServerConfig } from "./acp-mcp-types.js";
export interface McpManagerOptions {
authStorage: AuthStorage;
@@ -36,6 +37,8 @@ export class McpManager {
private readonly getUserServers: () => Record<string, McpServerConfig> | undefined;
private readonly beginLogin?: (server: string) => Promise<void>;
private integrations = new Map<string, ResolvedIntegration>();
+ private acpServers = new Map<string, AcpMcpServerConfig>();
+ private acpOwnerId?: string;
/** Provider ids we registered for user servers, so refresh can drop removed ones. */
private registeredUserProviderIds = new Set<string>();
@@ -53,6 +56,33 @@ export class McpManager {
this.registerProviders();
}
+ canReleaseAcpServers(ownerId: string): boolean {
+ return this.acpOwnerId === undefined || this.acpOwnerId === ownerId;
+ }
+
+ replaceAcpServers(servers: readonly AcpMcpServerConfig[], ownerId: string): boolean {
+ if (!ownerId) throw new Error("ACP MCP owner id is required");
+ if (servers.length === 0 && this.acpOwnerId !== ownerId) return false;
+ if (servers.length > 0 && this.acpOwnerId && this.acpOwnerId !== ownerId) {
+ throw new Error("ACP MCP configuration is owned by another client");
+ }
+
+ const next = new Map<string, AcpMcpServerConfig>();
+ for (const server of servers) {
+ if (next.has(server.name)) throw new Error(`Duplicate ACP MCP server: ${server.name}`);
+ next.set(server.name, server);
+ }
+ const unchanged =
+ next.size === this.acpServers.size &&
+ Array.from(next).every(
+ ([name, config]) => JSON.stringify(this.acpServers.get(name)) === JSON.stringify(config),
+ );
+ if (unchanged) return false;
+ this.acpServers = next;
+ this.acpOwnerId = next.size > 0 ? ownerId : undefined;
+ return true;
+ }
+
private providerId(server: string): string {
return `mcp:${server}`;
}
@@ -151,6 +181,7 @@ export class McpManager {
"mcp.refresh": async (payload) => {
const server = String(payload.server ?? "");
if (!server) throw new Error("mcp.refresh requires a server");
+ if (this.acpServers.has(server)) throw new Error(`ACP MCP server ${server} does not use host OAuth`);
// getApiKey refreshes + rewrites auth.json under lock; Python re-reads.
// Surface failure (throw) instead of a false success so the kernel can
// report a refresh error rather than a misleading "not enabled".
@@ -163,6 +194,11 @@ export class McpManager {
"mcp.config": async (payload) => {
const server = String(payload.server ?? "");
if (!server) throw new Error("mcp.config requires a server");
+ const acpServer = this.acpServers.get(server);
+ if (acpServer) {
+ const { name: _name, ...config } = acpServer;
+ return { ...config, credentialSource: "acp" };
+ }
const integration = this.integrations.get(server);
if (!integration?.userDeclared || getCatalogEntry(server)) return {};
return { ...integration.config };
@@ -182,9 +218,9 @@ export class McpManager {
return handlers;
}
- /** Enabled user servers available through the generic kernel API. */
+ /** Enabled persistent and session-scoped servers available through the generic kernel API. */
getEnabledGenericServers(): string[] {
- return Array.from(this.integrations.values())
+ const servers = Array.from(this.integrations.values())
.filter(
(integration) =>
integration.userDeclared &&
@@ -192,8 +228,9 @@ export class McpManager {
!getCatalogEntry(integration.server) &&
this.isAuthed(integration),
)
- .map((integration) => integration.server)
- .sort((left, right) => left.localeCompare(right));
+ .map((integration) => integration.server);
+ for (const server of this.acpServers.keys()) servers.push(server);
+ return [...new Set(servers)].sort((left, right) => left.localeCompare(right));
}
/** Status for the /mcp list command. */
diff --git a/packages/coding-agent/src/core/system-prompt.ts b/packages/coding-agent/src/core/system-prompt.ts
index d68d5f51e4..e274a34ef7 100644
--- a/packages/coding-agent/src/core/system-prompt.ts
+++ b/packages/coding-agent/src/core/system-prompt.ts
@@ -187,7 +187,7 @@ function formatGenericMcpGuidance(servers: string[] | undefined): string {
"# Generic MCP Connections",
"",
"Generic MCP connections are accessed through the pre-imported Python `mcp` object in IPython, not as top-level native tool namespaces or installed Python skills.",
- `Enabled user-configured generic MCP servers: ${enabledServers.map((server) => `\`${server}\``).join(", ")}.`,
+ `Enabled generic MCP servers: ${enabledServers.map((server) => `\`${server}\``).join(", ")}.`,
...enabledServers.map(
(server) =>
`For \`${server}\`, first discover its tools with \`await mcp.list_tools("${server}")\`, then call one with \`await mcp.call_tool("${server}", "<tool>", arguments)\`.`,
diff --git a/packages/coding-agent/src/modes/acp/acp-mcp.ts b/packages/coding-agent/src/modes/acp/acp-mcp.ts
new file mode 100644
index 0000000000..f68a87f7c0
--- /dev/null
+++ b/packages/coding-agent/src/modes/acp/acp-mcp.ts
@@ -0,0 +1,95 @@
+import { validateHeaderName, validateHeaderValue } from "node:http";
+import type { McpServer } from "@agentclientprotocol/sdk";
+import { RequestError } from "@agentclientprotocol/sdk";
+import type { AcpMcpServerConfig } from "../../core/mcp/acp-mcp-types.js";
+
+const SERVER_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
+
+function entries(
+ server: string,
+ label: "header" | "environment",
+ values: readonly { name: string; value: string }[],
+): Record<string, string> {
+ const result = Object.create(null) as Record<string, string>;
+ const seen = new Set<string>();
+ for (const entry of values) {
+ if (!entry.name) {
+ throw RequestError.invalidParams({ reason: `MCP server ${server} has an empty ${label} name` });
+ }
+ const identity = label === "header" ? entry.name.toLowerCase() : entry.name;
+ if (seen.has(identity)) {
+ throw RequestError.invalidParams({
+ reason: `MCP server ${server} has duplicate ${label} ${entry.name}`,
+ });
+ }
+ if (label === "header") {
+ try {
+ validateHeaderName(entry.name);
+ validateHeaderValue(entry.name, entry.value);
+ } catch {
+ throw RequestError.invalidParams({ reason: `MCP server ${server} has an invalid HTTP header` });
+ }
+ } else if (entry.name.includes("=") || entry.name.includes("\0") || entry.value.includes("\0")) {
+ throw RequestError.invalidParams({ reason: `MCP server ${server} has an invalid environment entry` });
+ }
+ seen.add(identity);
+ result[entry.name] = entry.value;
+ }
+ return result;
+}
+
+export function resolveAcpMcpServers(servers: readonly McpServer[], cwd: string): AcpMcpServerConfig[] {
+ const names = new Set<string>();
+ return servers.map((server) => {
+ if (!SERVER_NAME_PATTERN.test(server.name)) {
+ throw RequestError.invalidParams({
+ reason:
+ "MCP server names must start with an alphanumeric character and contain at most 64 alphanumeric, underscore, or hyphen characters",
+ });
+ }
+ if (names.has(server.name)) {
+ throw RequestError.invalidParams({ reason: `duplicate MCP server name: ${server.name}` });
+ }
+ names.add(server.name);
+
+ if ("command" in server) {
+ if (!server.command) {
+ throw RequestError.invalidParams({ reason: `MCP server ${server.name} has no stdio command` });
+ }
+ if (server.command.includes("\0") || server.args.some((argument) => argument.includes("\0"))) {
+ throw RequestError.invalidParams({ reason: `MCP server ${server.name} has an invalid stdio command` });
+ }
+ return {
+ name: server.name,
+ type: "stdio",
+ command: server.command,
+ args: [...server.args],
+ cwd,
+ env: entries(server.name, "environment", server.env),
+ };
+ }
+
+ if (server.type !== "http") {
+ throw RequestError.invalidParams({
+ reason: `MCP server ${server.name} uses unsupported ${server.type} transport`,
+ });
+ }
+ let url: URL;
+ try {
+ url = new URL(server.url);
+ } catch {
+ throw RequestError.invalidParams({ reason: `MCP server ${server.name} has an invalid HTTP URL` });
+ }
+ if ((url.protocol !== "http:" && url.protocol !== "https:") || url.username || url.password) {
+ throw RequestError.invalidParams({
+ reason: `MCP server ${server.name} must use an HTTP(S) URL without embedded credentials`,
+ });
+ }
+ return {
+ name: server.name,
+ type: "http",
+ url: url.toString(),
+ headers: entries(server.name, "header", server.headers),
+ };
+ });
+}
diff --git a/packages/coding-agent/src/modes/acp/acp-mode.ts b/packages/coding-agent/src/modes/acp/acp-mode.ts
index 988dac3228..59ae63abeb 100644
--- a/packages/coding-agent/src/modes/acp/acp-mode.ts
+++ b/packages/coding-agent/src/modes/acp/acp-mode.ts
@@ -18,6 +18,7 @@ import type {
} from "../agent-connection/types.js";
import { latestAutonomousGateAttempt } from "../headless-completion.js";
import { type AcpEventMappingState, acpUpdatesForSessionEvent } from "./acp-events.js";
+import { resolveAcpMcpServers } from "./acp-mcp.js";
import { PRIME_AGENT_META_NAMESPACE, type PrimeAgentAutonomousMeta, primeAgentMeta } from "./acp-meta.js";
import { type AcpStopReason, acpStopReason } from "./acp-stop-reason.js";
@@ -466,6 +467,39 @@ export async function runAcpModeWithConnection(
if (options.ownStdout !== false && !options.stream) {
takeOverStdout();
}
+ const supportsMcpServers =
+ connection.supportsAcpMcpServers?.() === true &&
+ connection.replaceAcpMcpServers !== undefined &&
+ connection.releaseAcpMcpServers !== undefined;
+ const acpMcpOwnerId = randomUUID();
+ let acpMcpServerNames: string[] = [];
+ const clearAcpMcpServers = async (serverNames = acpMcpServerNames): Promise<void> => {
+ if (!supportsMcpServers || !connection.releaseAcpMcpServers) return;
+ await connection.releaseAcpMcpServers(acpMcpOwnerId, serverNames);
+ acpMcpServerNames = [];
+ };
+ const replaceAcpMcpServers = async (servers: readonly acp.McpServer[], cwd: string): Promise<void> => {
+ if (acpMcpServerNames.length > 0) {
+ // Retry a prior best-effort close before admitting another session,
+ // including one that does not declare replacement MCP servers.
+ await clearAcpMcpServers();
+ }
+ if (servers.length === 0 && acpMcpServerNames.length === 0) return;
+ if (!supportsMcpServers || !connection.replaceAcpMcpServers) {
+ throw acp.RequestError.invalidParams({ reason: "MCP servers are unavailable in this ACP host" });
+ }
+ const resolved = resolveAcpMcpServers(servers, cwd);
+ const serverNames = resolved.map((server) => server.name);
+ try {
+ await connection.replaceAcpMcpServers(resolved, acpMcpOwnerId);
+ } catch (error) {
+ // The daemon may have applied the configuration before its acknowledgement
+ // was lost. Always attempt owner-scoped cleanup before rejecting admission.
+ await clearAcpMcpServers(serverNames).catch(() => undefined);
+ throw error;
+ }
+ acpMcpServerNames = serverNames;
+ };
// One ACP connection drives one AgentConnection, whose newSession() replaces
// the live session rather than creating a parallel one. Tracking a single
@@ -648,6 +682,7 @@ export async function runAcpModeWithConnection(
agentCapabilities: {
loadSession: false,
promptCapabilities: { image: true, embeddedContext: true },
+ ...(supportsMcpServers ? { mcpCapabilities: { http: true } } : {}),
// Advertise close so a client knows it can release the session (and
// the single-session slot) instead of dropping the connection.
sessionCapabilities: { close: {} },
@@ -669,6 +704,11 @@ export async function runAcpModeWithConnection(
}
sessionNewInFlight = true;
try {
+ const params = ctx.params as acp.NewSessionRequest;
+ const mcpServers = params.mcpServers ?? [];
+ if (mcpServers.length > 0 && !supportsMcpServers) {
+ throw acp.RequestError.invalidParams({ reason: "MCP servers are unavailable in this ACP host" });
+ }
if (!bound) {
// Only latch after a successful bind: a rejected bind must not leave
// extensions permanently unavailable for the rest of the process.
@@ -679,16 +719,23 @@ export async function runAcpModeWithConnection(
// with, so a client-supplied cwd cannot be adopted after the fact.
// Report the real cwd back in `_meta` rather than failing the request or
// letting the client assume a directory the agent is not using.
- const requestedCwd = (ctx.params as { cwd?: unknown } | undefined)?.cwd;
+ const requestedCwd = params.cwd;
+ const actualCwd = await connection
+ .getState()
+ .then((state) => state.cwd)
+ .catch(() => undefined);
+ if (!actualCwd && mcpServers.some((server) => "command" in server)) {
+ throw acp.RequestError.invalidParams({ reason: "Could not resolve the ACP session cwd for stdio MCP" });
+ }
+ await replaceAcpMcpServers(mcpServers, actualCwd ?? "");
let cwdMismatch: { requested: string; actual: string } | undefined;
- if (typeof requestedCwd === "string" && requestedCwd.length > 0) {
- const actual = await connection
- .getState()
- .then((state) => state.cwd)
- .catch(() => undefined);
- if (actual && !sameCwd(requestedCwd, actual)) {
- cwdMismatch = { requested: requestedCwd, actual };
- }
+ if (
+ typeof requestedCwd === "string" &&
+ requestedCwd.length > 0 &&
+ actualCwd &&
+ !sameCwd(requestedCwd, actualCwd)
+ ) {
+ cwdMismatch = { requested: requestedCwd, actual: actualCwd };
}
const sessionId = randomUUID();
// Install the listener before fetching the snapshot. Child updates can arrive
@@ -764,6 +811,7 @@ export async function runAcpModeWithConnection(
} catch (error) {
producer.failSessionNewAdmission();
unsubscribe();
+ await clearAcpMcpServers().catch(() => undefined);
throw error;
}
// Claim the single-session slot only once the subscription and snapshot are
@@ -956,6 +1004,9 @@ export async function runAcpModeWithConnection(
closing.unsubscribe?.();
// Keep the backing session fenced until a replacement ACP session is admitted.
await closing.producer.close();
+ // Host credentials are already gone before kernel release runs. Do not
+ // retain the ACP session slot if best-effort transport reaping fails.
+ await clearAcpMcpServers().catch(() => undefined);
closedInputPause = inputPause;
closedInputPauseKey = inputPauseKey;
if (closing.inputPause === inputPause) {
@@ -1037,6 +1088,7 @@ export async function runAcpModeWithConnection(
await closedInputPause?.release().catch(() => undefined);
closedInputPause = undefined;
closedInputPauseKey = undefined;
+ await clearAcpMcpServers().catch(() => undefined);
await connection.dispose().catch(() => undefined);
// Only the real stdio entrypoint owns the process; a caller-supplied transport
// (tests, embedding) must never have its host exited from under it.
diff --git a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
index b0ef8ffc40..ef48e75645 100644
--- a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
+++ b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
@@ -15,6 +15,7 @@ import type {
AgentHeartbeatManagementAction,
AgentHeartbeatUpdateAction,
} from "../../core/cron-jobs.js";
+import type { AcpMcpServerConfig } from "../../core/mcp/acp-mcp-types.js";
import type { RefinementResult } from "../../core/refinement/index.js";
import type { DeleteSessionFileResult } from "../../core/session-file-actions.js";
import { SessionAlreadyActiveError } from "../../core/session-lease.js";
@@ -499,6 +500,26 @@ export class DaemonAgentConnection implements AgentConnection {
});
}
+ supportsAcpMcpServers(): boolean {
+ return this.client.supportsServerCapability("acp_mcp_servers");
+ }
+
+ async replaceAcpMcpServers(servers: readonly AcpMcpServerConfig[], ownerId: string): Promise<void> {
+ if (!this.supportsAcpMcpServers()) {
+ throw new DaemonCapabilityUnavailableError("replace_acp_mcp_servers", "acp_mcp_servers");
+ }
+ await this.requestOk({
+ type: "replace_acp_mcp_servers",
+ activeSessionId: this.activeSessionId,
+ ownerId,
+ servers: [...servers],
+ });
+ }
+
+ async releaseAcpMcpServers(ownerId: string, _serverNames: readonly string[]): Promise<void> {
+ await this.replaceAcpMcpServers([], ownerId);
+ }
+
async getAvailableModels(): Promise<AgentConnectionModel[]> {
const data = await this.requestData<{ models: AgentConnectionModel[] }>({
type: "get_available_models",
diff --git a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
index e30b71e5a1..b3d4986e28 100644
--- a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
+++ b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
@@ -14,6 +14,7 @@ import type {
AgentHeartbeatUpdateAction,
} from "../../core/cron-jobs.js";
import type { ExtensionUIContext } from "../../core/extensions/types.js";
+import type { AcpMcpServerConfig } from "../../core/mcp/acp-mcp-types.js";
import type { RefinementResult } from "../../core/refinement/index.js";
import { type DeleteSessionFileResult, deleteSessionFile } from "../../core/session-file-actions.js";
import { SessionManager } from "../../core/session-manager.js";
@@ -110,6 +111,18 @@ export class InProcessAgentConnection implements AgentConnection {
await this.bindCurrentSessionExtensions();
}
+ supportsAcpMcpServers(): boolean {
+ return true;
+ }
+
+ async replaceAcpMcpServers(servers: readonly AcpMcpServerConfig[], ownerId: string): Promise<void> {
+ this.runtimeHost.session.replaceAcpMcpServers(servers, ownerId);
+ }
+
+ async releaseAcpMcpServers(ownerId: string, serverNames: readonly string[]): Promise<void> {
+ await this.runtimeHost.session.releaseAcpMcpServers(ownerId, serverNames);
+ }
+
subscribe(listener: AgentConnectionEventListener): () => void {
this.listeners.add(listener);
return () => {
diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.ts
index 33797100c3..bf81de68ad 100644
--- a/packages/coding-agent/src/modes/agent-connection/types.ts
+++ b/packages/coding-agent/src/modes/agent-connection/types.ts
@@ -16,6 +16,7 @@ import type { ReplayBuiltInToolName } from "../../core/extensions/index.js";
import type { InputSource } from "../../core/extensions/types.js";
import type { GoalState } from "../../core/goals.js";
import type { KernelSentAgentMessage } from "../../core/kernel/index.js";
+import type { AcpMcpServerConfig } from "../../core/mcp/acp-mcp-types.js";
import type { RefinementResult } from "../../core/refinement/index.js";
import type { RlmMaxDepthStatus, SetRlmMaxDepthResult } from "../../core/rlm-max-depth.js";
import type {
@@ -691,6 +692,9 @@ export interface AgentConnection {
getToolDefinition(name: string): Promise<AgentConnectionToolDefinition | undefined>;
setSessionEntryLabel(entryId: string, label: string | undefined): Promise<void>;
respondToExtensionUiRequest(requestId: string, response: AgentConnectionExtensionUiResponse): Promise<void>;
+ supportsAcpMcpServers?(): boolean;
+ replaceAcpMcpServers?(servers: readonly AcpMcpServerConfig[], ownerId: string): Promise<void>;
+ releaseAcpMcpServers?(ownerId: string, serverNames: readonly string[]): Promise<void>;
prompt(message: string, options?: AgentConnectionPromptOptions): Promise<void>;
promptAndWait(message: string, options?: AgentConnectionPromptOptions): Promise<void>;
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index 01350cf386..0bda7e5ea5 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -281,6 +281,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
"get_context_tree",
"get_commands",
"get_resource_snapshot",
+ "replace_acp_mcp_servers",
"get_model_catalog",
"get_available_models",
"get_queue",
@@ -460,6 +461,10 @@ export class AgentDaemon {
string,
{ activeSessionId: string; owner: DaemonSocketClient; leaseKey: string; pause: { release(): void } }
>();
+ private readonly acpMcpOwners = new Map<
+ string,
+ { client: DaemonSocketClient; ownerId: string; serverNames: string[]; release?: Promise<void> }
+ >();
private readonly mutationDrain = new MutationDrainLatch();
private updateRestart?: {
id: symbol;
@@ -1487,6 +1492,7 @@ export class AgentDaemon {
}
private refreshReplacedSessionState(state: ActiveSessionState): void {
+ this.acpMcpOwners?.delete(state.activeSessionId);
for (const client of state.clients) {
this.abortSideQuestionsFor(client, state.activeSessionId);
}
@@ -4517,6 +4523,83 @@ export class AgentDaemon {
);
}
+ case "replace_acp_mcp_servers": {
+ if (!command.ownerId) throw new Error("ACP MCP owner id is required");
+ const state = this.getSessionState(command.activeSessionId);
+ if (!state.clients.has(client)) throw new Error("Daemon client is not attached to this session");
+ if (command.servers.length > 0 && state.runtime.session.isStreaming) {
+ throw new Error("Cannot replace ACP MCP servers while the agent is running");
+ }
+ const commandPause =
+ command.servers.length > 0 ? state.runtime.session.acquireSessionInputPause() : undefined;
+ try {
+ let currentOwner = this.acpMcpOwners.get(state.activeSessionId);
+ if (currentOwner?.release) {
+ await currentOwner.release.catch(() => undefined);
+ currentOwner = this.acpMcpOwners.get(state.activeSessionId);
+ }
+ const ownedByClient = currentOwner?.client === client && currentOwner.ownerId === command.ownerId;
+ if (command.servers.length === 0 && !ownedByClient) {
+ return success(command.id, "replace_acp_mcp_servers");
+ }
+ if (command.servers.length === 0) {
+ if (!currentOwner) return success(command.id, "replace_acp_mcp_servers");
+ const release = state.runtime.session.releaseAcpMcpServers(command.ownerId, currentOwner.serverNames);
+ currentOwner.release = release;
+ try {
+ await release;
+ } catch (error) {
+ currentOwner.release = undefined;
+ throw error;
+ }
+ if (this.acpMcpOwners.get(state.activeSessionId) === currentOwner) {
+ this.acpMcpOwners.delete(state.activeSessionId);
+ }
+ return success(command.id, "replace_acp_mcp_servers");
+ }
+
+ if (currentOwner && !ownedByClient) {
+ throw new Error("ACP MCP configuration is owned by another daemon client");
+ }
+ const claim = {
+ client,
+ ownerId: command.ownerId,
+ serverNames: [
+ ...new Set([
+ ...(currentOwner?.serverNames ?? []),
+ ...command.servers.map((server) => server.name),
+ ]),
+ ],
+ };
+ this.acpMcpOwners.set(state.activeSessionId, claim);
+ const rollback = async (): Promise<void> => {
+ try {
+ await state.runtime.session.releaseAcpMcpServers(command.ownerId, claim.serverNames);
+ } catch (error) {
+ this.log(`failed to roll back ACP MCP config: ${String(error)}`);
+ }
+ if (this.acpMcpOwners.get(state.activeSessionId) === claim) {
+ this.acpMcpOwners.delete(state.activeSessionId);
+ }
+ };
+ try {
+ await withClientEnv(state.clientEnv, async () =>
+ state.runtime.session.replaceAcpMcpServers(command.servers, command.ownerId),
+ );
+ } catch (error) {
+ await rollback();
+ throw error;
+ }
+ if (!state.clients.has(client) || this.acpMcpOwners.get(state.activeSessionId) !== claim) {
+ await rollback();
+ throw new Error("Daemon client detached during ACP MCP replacement");
+ }
+ return success(command.id, "replace_acp_mcp_servers");
+ } finally {
+ commandPause?.release();
+ }
+ }
+
case "get_available_models": {
const state = this.getSessionState(command.activeSessionId);
return success(command.id, "get_available_models", {
@@ -5929,6 +6012,18 @@ export class AgentDaemon {
}
private detachClientFromSession(client: DaemonSocketClient, state: ActiveSessionState): void {
+ const acpMcpOwner = this.acpMcpOwners.get(state.activeSessionId);
+ if (acpMcpOwner?.client === client && !acpMcpOwner.release) {
+ const release = state.runtime.session.releaseAcpMcpServers(acpMcpOwner.ownerId, acpMcpOwner.serverNames);
+ acpMcpOwner.release = release;
+ void release
+ .catch((error) => this.log(`failed to release detached ACP MCP config: ${String(error)}`))
+ .finally(() => {
+ if (this.acpMcpOwners.get(state.activeSessionId) === acpMcpOwner) {
+ this.acpMcpOwners.delete(state.activeSessionId);
+ }
+ });
+ }
this.abortSideQuestionsFor(client, state.activeSessionId);
abortClientSnapshotStreaming(client, state.activeSessionId);
detachClientFromActiveSession(client, state);
@@ -6453,6 +6548,7 @@ export class AgentDaemon {
removeDaemonClientSessionCapabilities(client, state.activeSessionId);
}
state.clients.clear();
+ this.acpMcpOwners.delete(state.activeSessionId);
this.sessions.delete(state.activeSessionId);
if (isEmptyDraftSession) {
const sessionFile = state.runtime.session.sessionFile;
diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
index 6f77aeb040..1613538a06 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
@@ -17,6 +17,7 @@ import type {
AgentHeartbeatUpdateAction,
} from "../../core/cron-jobs.js";
import type { InputSource } from "../../core/extensions/types.js";
+import type { AcpMcpServerConfig } from "../../core/mcp/acp-mcp-types.js";
import type { CustomMessage } from "../../core/messages.js";
import type { QueuedMessageLane, QueuedMessageMutation } from "../../core/session-action-store.js";
import type { SessionCwdIssue } from "../../core/session-cwd.js";
@@ -64,8 +65,10 @@ export const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION = 7;
// Revision 18 adds the opt-in RLM quiescence barrier to headless completion.
// Revision 19 adds daemon-held session input pauses.
// Revision 20 lets cancellation target a prompt the session owns but has not started.
-export const DAEMON_SCHEMA_REVISION = 20;
-export const DAEMON_SCHEMA_ID = "protocol-7-schema-20-ed994cc39507";
+// Revision 21 adds capability-gated, session-scoped ACP MCP server replacement.
+// Revision 22 scopes ACP MCP replacement and cleanup to a connection owner.
+export const DAEMON_SCHEMA_REVISION = 22;
+export const DAEMON_SCHEMA_ID = "protocol-7-schema-22-4d515169dc6b";
export type DaemonProtocolName = typeof DAEMON_PROTOCOL_NAME;
export type DaemonProtocolVersion = number;
@@ -109,7 +112,8 @@ export type DaemonServerCapability =
| "owned_session_recovery_context"
| "rlm_quiescence_barrier"
| "session_input_pause"
- | "owned_prompt_cancellation";
+ | "owned_prompt_cancellation"
+ | "acp_mcp_servers";
export type DaemonReplayStatus = "complete" | "partial" | "unavailable";
@@ -153,6 +157,7 @@ export const DAEMON_DEFAULT_SERVER_CAPABILITIES: readonly DaemonServerCapability
"owned_session_recovery_context",
"rlm_quiescence_barrier",
"session_input_pause",
+ "acp_mcp_servers",
];
export interface DaemonRuntimeIdentity {
@@ -534,6 +539,13 @@ export type DaemonCommand =
| { id?: string; type: "get_context_tree"; activeSessionId: string }
| { id?: string; type: "get_commands"; activeSessionId: string }
| { id?: string; type: "get_resource_snapshot"; activeSessionId: string }
+ | {
+ id?: string;
+ type: "replace_acp_mcp_servers";
+ activeSessionId: string;
+ ownerId: string;
+ servers: AcpMcpServerConfig[];
+ }
| { id?: string; type: "get_model_catalog"; activeSessionId: string }
| { id?: string; type: "get_available_models"; activeSessionId: string }
| { id?: string; type: "get_queue"; activeSessionId: string }
@@ -745,6 +757,7 @@ export const DAEMON_COMMAND_COMPATIBILITY = {
get_context_tree: LEGACY_DAEMON_COMMAND,
get_commands: LEGACY_DAEMON_COMMAND,
get_resource_snapshot: LEGACY_DAEMON_COMMAND,
+ replace_acp_mcp_servers: { minProtocol: 7, minSchemaRevision: 22, capability: "acp_mcp_servers" },
get_model_catalog: { minProtocol: 7, capability: "model_catalog" },
get_available_models: LEGACY_DAEMON_COMMAND,
get_queue: LEGACY_DAEMON_COMMAND,
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
index 5fa5f14376..b69a4ad1c2 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
@@ -208,6 +208,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
"get_context_tree",
"get_commands",
"get_resource_snapshot",
+ "replace_acp_mcp_servers",
"get_model_catalog",
"get_available_models",
"get_queue",
diff --git a/packages/coding-agent/test/acp-mcp.test.ts b/packages/coding-agent/test/acp-mcp.test.ts
new file mode 100644
index 0000000000..a09ee0e7fa
--- /dev/null
+++ b/packages/coding-agent/test/acp-mcp.test.ts
@@ -0,0 +1,205 @@
+import * as acp from "@agentclientprotocol/sdk";
+import { describe, expect, it, vi } from "vitest";
+import type { AgentSessionRuntime } from "../src/core/agent-session-runtime.js";
+import { resolveAcpMcpServers } from "../src/modes/acp/acp-mcp.js";
+import { runAcpModeWithConnection } from "../src/modes/acp/acp-mode.js";
+import { InProcessAgentConnection } from "../src/modes/agent-connection/in-process-agent-connection.js";
+import { createHarness } from "./suite/harness.js";
+
+function runtimeHostFor(session: unknown): AgentSessionRuntime {
+ return {
+ session,
+ setRebindSession() {},
+ setBeforeSessionInvalidate() {},
+ async dispose() {},
+ } as unknown as AgentSessionRuntime;
+}
+
+describe("ACP MCP servers", () => {
+ it("installs session MCP config and frees the session slot when kernel release fails", async () => {
+ const harness = await createHarness();
+ const replace = vi.spyOn(harness.session, "replaceAcpMcpServers").mockImplementation(() => undefined);
+ const release = vi
+ .spyOn(harness.session, "releaseAcpMcpServers")
+ .mockRejectedValueOnce(new Error("kernel release failed"))
+ .mockResolvedValue(undefined);
+ const connection = new InProcessAgentConnection(runtimeHostFor(harness.session));
+ const agentCwd = (await connection.getState()).cwd;
+ const toAgent = new TransformStream<Uint8Array, Uint8Array>();
+ const toClient = new TransformStream<Uint8Array, Uint8Array>();
+ const modeDone = runAcpModeWithConnection(connection, {
+ stream: acp.ndJsonStream(toClient.writable, toAgent.readable),
+ });
+ const handle = acp
+ .client({ name: "mcp-test-client" })
+ .connect(acp.ndJsonStream(toAgent.writable, toClient.readable));
+ try {
+ const initialized = await handle.agent.request("initialize", {
+ protocolVersion: acp.PROTOCOL_VERSION,
+ clientCapabilities: {},
+ });
+ expect(initialized.agentCapabilities?.mcpCapabilities?.http).toBe(true);
+
+ const created = await handle.agent.request("session/new", {
+ cwd: harness.tempDir,
+ mcpServers: [
+ {
+ type: "http",
+ name: "TaskTools",
+ url: "https://task.example/mcp",
+ headers: [{ name: "Authorization", value: "Bearer task" }],
+ },
+ {
+ name: "LocalTools",
+ command: "node",
+ args: ["server.js"],
+ env: [{ name: "TASK_TOKEN", value: "task-secret" }],
+ },
+ ],
+ });
+ const ownerId = replace.mock.calls[0]?.[1];
+ expect(ownerId).toEqual(expect.any(String));
+ expect(replace).toHaveBeenCalledWith(
+ [
+ {
+ name: "TaskTools",
+ type: "http",
+ url: "https://task.example/mcp",
+ headers: { Authorization: "Bearer task" },
+ },
+ {
+ name: "LocalTools",
+ type: "stdio",
+ command: "node",
+ args: ["server.js"],
+ cwd: agentCwd,
+ env: { TASK_TOKEN: "task-secret" },
+ },
+ ],
+ ownerId,
+ );
+ await handle.agent.request("session/close", { sessionId: created.sessionId });
+ expect(release).toHaveBeenCalledWith(ownerId, ["TaskTools", "LocalTools"]);
+
+ // The failed release is retried before a new ACP session is admitted, but it
+ // must not leave the single-session slot occupied.
+ const replacement = await handle.agent.request("session/new", {
+ cwd: harness.tempDir,
+ mcpServers: [],
+ });
+ expect(release).toHaveBeenCalledWith(ownerId, ["TaskTools", "LocalTools"]);
+ await handle.agent.request("session/close", { sessionId: replacement.sessionId });
+ } finally {
+ handle.close();
+ await toAgent.writable.close().catch(() => undefined);
+ await modeDone;
+ harness.cleanup();
+ }
+ }, 30_000);
+
+ it("clears owner-scoped config when daemon acknowledgement is lost", async () => {
+ const harness = await createHarness();
+ const connection = new InProcessAgentConnection(runtimeHostFor(harness.session));
+ const replace = vi.spyOn(connection, "replaceAcpMcpServers").mockImplementation(async (servers) => {
+ if (servers.length > 0) throw new Error("replacement acknowledgement lost");
+ });
+ const release = vi.spyOn(connection, "releaseAcpMcpServers").mockResolvedValue(undefined);
+ const toAgent = new TransformStream<Uint8Array, Uint8Array>();
+ const toClient = new TransformStream<Uint8Array, Uint8Array>();
+ const modeDone = runAcpModeWithConnection(connection, {
+ stream: acp.ndJsonStream(toClient.writable, toAgent.readable),
+ });
+ const handle = acp
+ .client({ name: "mcp-lost-ack-test-client" })
+ .connect(acp.ndJsonStream(toAgent.writable, toClient.readable));
+ try {
+ await handle.agent.request("initialize", {
+ protocolVersion: acp.PROTOCOL_VERSION,
+ clientCapabilities: {},
+ });
+ await expect(
+ handle.agent.request("session/new", {
+ cwd: harness.tempDir,
+ mcpServers: [
+ {
+ type: "http",
+ name: "TaskTools",
+ url: "https://task.example/mcp",
+ headers: [],
+ },
+ ],
+ }),
+ ).rejects.toThrow();
+
+ expect(replace.mock.calls[0]?.[0]).toHaveLength(1);
+ const ownerId = replace.mock.calls[0]?.[1];
+ expect(ownerId).toEqual(expect.any(String));
+ expect(release).toHaveBeenCalledWith(ownerId, ["TaskTools"]);
+ } finally {
+ handle.close();
+ await toAgent.writable.close().catch(() => undefined);
+ await modeDone;
+ harness.cleanup();
+ }
+ }, 30_000);
+
+ it("preserves stdio cwd and literal environment", () => {
+ const [server] = resolveAcpMcpServers(
+ [
+ {
+ name: "TaskTools",
+ command: "node",
+ args: ["server.js"],
+ env: [{ name: "TASK_TOKEN", value: "secret" }],
+ },
+ ],
+ "/actual/session",
+ );
+ expect(server).toEqual({
+ name: "TaskTools",
+ type: "stdio",
+ command: "node",
+ args: ["server.js"],
+ cwd: "/actual/session",
+ env: { TASK_TOKEN: "secret" },
+ });
+ });
+
+ it("rejects names that could inject prompt code and ambiguous credentials", () => {
+ expect(() =>
+ resolveAcpMcpServers(
+ [{ type: "http", name: 'bad"\nname', url: "https://task.example/mcp", headers: [] }],
+ "/tmp",
+ ),
+ ).toThrow("Invalid params");
+ expect(() =>
+ resolveAcpMcpServers(
+ [
+ {
+ type: "http",
+ name: "task",
+ url: "https://user:[email protected]/mcp",
+ headers: [],
+ },
+ ],
+ "/tmp",
+ ),
+ ).toThrow("Invalid params");
+ expect(() =>
+ resolveAcpMcpServers(
+ [
+ {
+ type: "http",
+ name: "task",
+ url: "https://task.example/mcp",
+ headers: [
+ { name: "Authorization", value: "one" },
+ { name: "authorization", value: "two" },
+ ],
+ },
+ ],
+ "/tmp",
+ ),
+ ).toThrow("Invalid params");
+ });
+});
diff --git a/packages/coding-agent/test/agent-connection-daemon.test.ts b/packages/coding-agent/test/agent-connection-daemon.test.ts
index 3426fc6dd6..6b22dbb500 100644
--- a/packages/coding-agent/test/agent-connection-daemon.test.ts
+++ b/packages/coding-agent/test/agent-connection-daemon.test.ts
@@ -193,6 +193,8 @@ class FakeDaemonClient {
},
},
};
+ case "replace_acp_mcp_servers":
+ return { type: "response", command: command.type, success: true };
case "get_model_catalog":
return {
type: "response",
@@ -2572,6 +2574,35 @@ describe("DaemonAgentConnection", () => {
});
});
+ it("capability-gates ACP MCP server replacement", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "session-1");
+ expect(connection.supportsAcpMcpServers()).toBe(false);
+ await expect(
+ connection.replaceAcpMcpServers(
+ [
+ {
+ name: "task",
+ type: "http",
+ url: "https://task.example/mcp",
+ headers: { Authorization: "Bearer task" },
+ },
+ ],
+ "owner-a",
+ ),
+ ).rejects.toBeInstanceOf(DaemonCapabilityUnavailableError);
+
+ fakeClient.serverCapabilities.add("acp_mcp_servers");
+ expect(connection.supportsAcpMcpServers()).toBe(true);
+ await connection.releaseAcpMcpServers("owner-a", ["task"]);
+ expect(fakeClient.requests.at(-1)).toMatchObject({
+ type: "replace_acp_mcp_servers",
+ ownerId: "owner-a",
+ servers: [],
+ });
+ await connection.dispose();
+ });
+
it("loads the full model catalog through the daemon protocol", async () => {
const fakeClient = new FakeDaemonClient();
fakeClient.serverCapabilities.add("model_catalog");
diff --git a/packages/coding-agent/test/agent-session-services.test.ts b/packages/coding-agent/test/agent-session-services.test.ts
index 0a3afa5dea..c6e38c878f 100644
--- a/packages/coding-agent/test/agent-session-services.test.ts
+++ b/packages/coding-agent/test/agent-session-services.test.ts
@@ -150,7 +150,7 @@ describe("createAgentSessionFromServices", () => {
expect(initialPrompt).toContain(
"Generic MCP connections are accessed through the pre-imported Python `mcp` object in IPython, not as top-level native tool namespaces or installed Python skills.",
);
- expect(initialPrompt).toContain("Enabled user-configured generic MCP servers: `filesystem`, `zebra`.");
+ expect(initialPrompt).toContain("Enabled generic MCP servers: `filesystem`, `zebra`.");
expect(initialPrompt).toContain('await mcp.list_tools("filesystem")');
expect(initialPrompt).toContain('await mcp.call_tool("filesystem", "<tool>", arguments)');
for (const hidden of [
@@ -166,14 +166,46 @@ describe("createAgentSessionFromServices", () => {
]) {
expect(initialPrompt).not.toContain(hidden);
}
- expect(initialPrompt).not.toContain("Enabled user-configured generic MCP servers: `linear`");
+ expect(initialPrompt).not.toContain("Enabled generic MCP servers: `linear`");
+
+ const rebuildRuntime = vi.spyOn(
+ session as unknown as { _rebuildRuntimeForAcpMcpServers(): void },
+ "_rebuildRuntimeForAcpMcpServers",
+ );
+ session.replaceAcpMcpServers(
+ [
+ {
+ name: "task",
+ type: "http",
+ url: "https://task-secret.example/mcp",
+ headers: { Authorization: "Bearer task-secret" },
+ },
+ ],
+ "owner-a",
+ );
+ expect(session.systemPrompt).toContain("Enabled generic MCP servers: `filesystem`, `task`, `zebra`.");
+ expect(session.systemPrompt).not.toContain("task-secret");
+ rebuildRuntime.mockClear();
+ const waitForIdle = vi.spyOn(session.agent, "waitForIdle");
+ await session.releaseAcpMcpServers("unknown-owner", ["task"]);
+ expect(waitForIdle).not.toHaveBeenCalled();
+ const originalProvisioner = Reflect.get(session, "_ipythonKernelProvisioner");
+ const execute = vi.fn(async (_code: string) => ({ status: "ok" }));
+ Reflect.set(session, "_ipythonKernelProvisioner", { manager: { isRunning: true, execute } });
+ await session.releaseAcpMcpServers("owner-a", ["task"]);
+ Reflect.set(session, "_ipythonKernelProvisioner", originalProvisioner);
+ expect(rebuildRuntime).not.toHaveBeenCalled();
+ expect(execute).toHaveBeenCalledOnce();
+ expect(execute.mock.calls[0]?.[0]).toContain("await _prime_mcp.reload(_prime_mcp_name)");
+ expect(execute.mock.calls[0]?.[0]).toContain('["task"]');
+ expect(session.systemPrompt).toContain("Enabled generic MCP servers: `filesystem`, `zebra`.");
settingsManager.setGlobalMcpServer("added", { type: "stdio", command: "new-secret" });
settingsManager.removeGlobalMcpServer("filesystem");
await settingsManager.flush();
await session.reload();
- expect(session.systemPrompt).toContain("Enabled user-configured generic MCP servers: `added`, `zebra`.");
+ expect(session.systemPrompt).toContain("Enabled generic MCP servers: `added`, `zebra`.");
expect(session.systemPrompt).toContain('await mcp.list_tools("added")');
expect(session.systemPrompt).not.toContain('await mcp.list_tools("filesystem")');
expect(session.systemPrompt).not.toContain("new-secret");
diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.ts
index 58facb9cf4..bc5d92e722 100644
--- a/packages/coding-agent/test/daemon-mode.test.ts
+++ b/packages/coding-agent/test/daemon-mode.test.ts
@@ -182,6 +182,102 @@ describe("daemon mode helpers", () => {
expect(secondClient.attachedActiveSessionIds.has("active")).toBe(false);
});
+ it("releases owner-scoped ACP MCP config when its daemon client detaches", async () => {
+ const daemon = new AgentDaemon("/tmp/prime-agent-acp-owner.sock", {
+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
+ createRuntime: vi.fn(),
+ });
+ const owner = makeClient("owner", "active");
+ const other = makeClient("other", "active");
+ const replaceAcpMcpServers = vi.fn();
+ const releaseAcpMcpServers = vi.fn(async () => {});
+ const state = makeState("active");
+ state.clientEnv = {};
+ state.clients.add(owner);
+ state.clients.add(other);
+ state.extensionUiRequests = new Map();
+ state.runtime = {
+ ...state.runtime,
+ session: {
+ isStreaming: false,
+ replaceAcpMcpServers,
+ releaseAcpMcpServers,
+ acquireSessionInputPause: () => ({ release: vi.fn() }),
+ },
+ } as never;
+ const internals = daemon as unknown as {
+ sessions: Map<string, ActiveSessionState>;
+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<DaemonOutbound | undefined>;
+ detachClientFromSession(client: DaemonSocketClient, state: ActiveSessionState): void;
+ write: ReturnType<typeof vi.fn>;
+ };
+ internals.sessions.set(state.activeSessionId, state);
+ internals.write = vi.fn();
+
+ replaceAcpMcpServers.mockImplementationOnce(() => {
+ throw new Error("replacement failed");
+ });
+ await expect(
+ internals.handleCommand(owner, {
+ type: "replace_acp_mcp_servers",
+ activeSessionId: state.activeSessionId,
+ ownerId: "owner-token",
+ servers: [{ name: "failed", type: "http", url: "https://failed.example/mcp", headers: {} }],
+ }),
+ ).rejects.toThrow("replacement failed");
+ expect(releaseAcpMcpServers).toHaveBeenLastCalledWith("owner-token", ["failed"]);
+
+ await internals.handleCommand(owner, {
+ type: "replace_acp_mcp_servers",
+ activeSessionId: state.activeSessionId,
+ ownerId: "owner-token",
+ servers: [{ name: "task", type: "http", url: "https://task.example/mcp", headers: {} }],
+ });
+ const releaseCount = releaseAcpMcpServers.mock.calls.length;
+ (state.runtime.session as unknown as { isStreaming: boolean }).isStreaming = true;
+ await expect(
+ internals.handleCommand(owner, {
+ type: "replace_acp_mcp_servers",
+ activeSessionId: state.activeSessionId,
+ ownerId: "owner-token",
+ servers: [{ name: "next", type: "http", url: "https://next.example/mcp", headers: {} }],
+ }),
+ ).rejects.toThrow("while the agent is running");
+ expect(releaseAcpMcpServers).toHaveBeenCalledTimes(releaseCount);
+ (state.runtime.session as unknown as { isStreaming: boolean }).isStreaming = false;
+
+ await expect(
+ internals.handleCommand(other, {
+ type: "replace_acp_mcp_servers",
+ activeSessionId: state.activeSessionId,
+ ownerId: "other-token",
+ servers: [{ name: "other", type: "http", url: "https://other.example/mcp", headers: {} }],
+ }),
+ ).rejects.toThrow("owned by another daemon client");
+
+ internals.detachClientFromSession(owner, state);
+ expect(releaseAcpMcpServers).toHaveBeenCalledWith("owner-token", ["task"]);
+
+ await internals.handleCommand(other, {
+ type: "replace_acp_mcp_servers",
+ activeSessionId: state.activeSessionId,
+ ownerId: "other-token",
+ servers: [{ name: "other", type: "http", url: "https://other.example/mcp", headers: {} }],
+ });
+ expect(replaceAcpMcpServers).toHaveBeenLastCalledWith(
+ [{ name: "other", type: "http", url: "https://other.example/mcp", headers: {} }],
+ "other-token",
+ );
+
+ await internals.handleCommand(other, {
+ type: "replace_acp_mcp_servers",
+ activeSessionId: state.activeSessionId,
+ ownerId: "other-token",
+ servers: [],
+ });
+ expect(releaseAcpMcpServers).toHaveBeenLastCalledWith("other-token", ["other"]);
+ });
+
it("cancels pending extension UI requests directly", () => {
const resolve = vi.fn();
const state = {
diff --git a/packages/coding-agent/test/daemon-protocol.test.ts b/packages/coding-agent/test/daemon-protocol.test.ts
index 615008c90f..cee6f9f5af 100644
--- a/packages/coding-agent/test/daemon-protocol.test.ts
+++ b/packages/coding-agent/test/daemon-protocol.test.ts
@@ -127,6 +127,15 @@ describe("daemon protocol helpers", () => {
expect(DAEMON_DEFAULT_SERVER_CAPABILITIES).toContain("delete_rlm_subagent");
});
+ it("capability- and schema-gates ACP MCP server replacement", () => {
+ expect(DAEMON_COMMAND_COMPATIBILITY.replace_acp_mcp_servers).toEqual({
+ minProtocol: 7,
+ minSchemaRevision: 22,
+ capability: "acp_mcp_servers",
+ });
+ expect(DAEMON_DEFAULT_SERVER_CAPABILITIES).toContain("acp_mcp_servers");
+ });
+
it("capability-gates the optional model catalog surface", () => {
expect(DAEMON_COMMAND_COMPATIBILITY.get_model_catalog).toEqual({
minProtocol: 7,
diff --git a/packages/coding-agent/test/mcp-manager.test.ts b/packages/coding-agent/test/mcp-manager.test.ts
index 2518fa7108..fc3589f4fa 100644
--- a/packages/coding-agent/test/mcp-manager.test.ts
+++ b/packages/coding-agent/test/mcp-manager.test.ts
@@ -234,4 +234,59 @@ describe("McpManager", () => {
expect(manager.getDisabledBuiltinSkillOverrides()).toContain("-linear/SKILL.md");
}
});
+ it("keeps ACP credentials session-scoped and isolated from stored OAuth", async () => {
+ authStorage.set("mcp:task", {
+ type: "oauth",
+ access: "stored-oauth-token",
+ refresh: "refresh",
+ expires: Date.now() + 3600_000,
+ endpoint: "https://user.example/mcp",
+ });
+ const manager = new McpManager({
+ authStorage,
+ getUserServers: () => ({ task: { type: "http", url: "https://user.example/mcp", oauth: true } }),
+ });
+ expect(
+ manager.replaceAcpServers(
+ [
+ {
+ name: "task",
+ type: "http",
+ url: "https://task.example/mcp",
+ headers: { Authorization: "Bearer task-token" },
+ },
+ ],
+ "owner-a",
+ ),
+ ).toBe(true);
+ const handlers = manager.hostHandlers();
+ expect(await handlers["mcp.config"]({ server: "task" })).toEqual({
+ type: "http",
+ url: "https://task.example/mcp",
+ headers: { Authorization: "Bearer task-token" },
+ credentialSource: "acp",
+ });
+ await expect(handlers["mcp.refresh"]({ server: "task" })).rejects.toThrow("does not use host OAuth");
+ expect(manager.getEnabledGenericServers()).toContain("task");
+
+ expect(manager.replaceAcpServers([], "owner-b")).toBe(false);
+ expect(() =>
+ manager.replaceAcpServers(
+ [{ name: "other", type: "http", url: "https://other.example/mcp", headers: {} }],
+ "owner-b",
+ ),
+ ).toThrow("owned by another client");
+ expect(await handlers["mcp.config"]({ server: "task" })).toMatchObject({
+ url: "https://task.example/mcp",
+ credentialSource: "acp",
+ });
+
+ expect(manager.replaceAcpServers([], "owner-a")).toBe(true);
+ expect(await handlers["mcp.config"]({ server: "task" })).toEqual({
+ type: "http",
+ url: "https://user.example/mcp",
+ oauth: true,
+ });
+ expect(authStorage.get("mcp:task")).toMatchObject({ access: "stored-oauth-token" });
+ });
});
diff --git a/packages/coding-agent/test/system-prompt.test.ts b/packages/coding-agent/test/system-prompt.test.ts
index 2fc164d54c..4417eaa709 100644
--- a/packages/coding-agent/test/system-prompt.test.ts
+++ b/packages/coding-agent/test/system-prompt.test.ts
@@ -218,7 +218,7 @@ describe("buildSystemPrompt", () => {
genericMcpServers: ["zebra", "filesystem"],
});
- expect(prompt).toContain("Enabled user-configured generic MCP servers: `filesystem`, `zebra`.");
+ expect(prompt).toContain("Enabled generic MCP servers: `filesystem`, `zebra`.");
expect(prompt).toContain('await mcp.list_tools("filesystem")');
expect(prompt).toContain('await mcp.call_tool("filesystem", "<tool>", arguments)');
expect(prompt).toContain("not as top-level native tool namespaces or installed Python skills");
diff --git a/prime-agent-runtime/src/rlm/mcp.py b/prime-agent-runtime/src/rlm/mcp.py
index a5dce19304..13ac0b94d6 100644
--- a/prime-agent-runtime/src/rlm/mcp.py
+++ b/prime-agent-runtime/src/rlm/mcp.py
@@ -357,9 +357,9 @@ class _Registry:
async def _get_locked(self, server: str) -> _Generation:
self._accepting_work()
+ current = self._generations.get(server)
config = await _config(server)
self._accepting_work()
- current = self._generations.get(server)
if current and current.config == config and not current.closed:
return current
if current:
@@ -508,7 +508,8 @@ async def _config(server: str) -> dict[str, Any]:
raise RuntimeError(f"MCP server '{server}' is disabled")
if config.get("type") == "http":
config = dict(config)
- config["_authIdentity"] = await _auth_identity(server, config)
+ if config.get("credentialSource") != "acp":
+ config["_authIdentity"] = await _auth_identity(server, config)
return config
@@ -552,6 +553,8 @@ async def _headers(server: str, config: dict[str, Any]) -> dict[str, str]:
if not isinstance(raw, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in raw.items()):
raise ValueError("MCP HTTP headers must contain strings")
headers = dict(raw)
+ if config.get("credentialSource") == "acp":
+ return headers
env_name = config.get("bearerTokenEnvVar")
token = os.environ.get(env_name, "").strip() if isinstance(env_name, str) else ""
if config.get("oauth") is True and not token:
@@ -569,6 +572,11 @@ def _stdio_env(config: dict[str, Any]) -> dict[str, str]:
raw = config.get("env", {})
if not isinstance(raw, dict):
raise ValueError("MCP stdio env must be an object")
+ if config.get("credentialSource") == "acp":
+ if not all(isinstance(key, str) and isinstance(value, str) for key, value in raw.items()):
+ raise ValueError("ACP MCP stdio env must contain string values")
+ env.update(raw)
+ return env
for key, reference in raw.items():
if not isinstance(key, str) or not isinstance(reference, dict) or set(reference) != {"env"}:
raise ValueError("MCP stdio env values must use {\"env\": \"NAME\"} references")
diff --git a/prime-agent-runtime/test/test_mcp.py b/prime-agent-runtime/test/test_mcp.py
index 361b227aa8..2ff1999752 100644
--- a/prime-agent-runtime/test/test_mcp.py
+++ b/prime-agent-runtime/test/test_mcp.py
@@ -21,6 +21,8 @@ from rlm.mcp_base import _parse_result
_STDIO_FIXTURE = r"""import asyncio, json, os, sys
+if pid_file := os.environ.get("FIXTURE_PID_FILE"):
+ open(pid_file, "w").write(str(os.getpid()))
async def main():
while line := await asyncio.get_running_loop().run_in_executor(None, sys.stdin.readline):
request = json.loads(line)
@@ -33,7 +35,7 @@ async def main():
result = {"tools": [{"name": "fixture/raw.tool", "description": "fixture", "inputSchema": {"type": "object"}}]}
else:
params = request["params"]
- result = {"content": [{"type": "text", "text": json.dumps({"args": sys.argv[1:], "cwd": os.getcwd(), "env": os.environ.get("FIXTURE_ENV"), "arguments": params.get("arguments", {})})}]}
+ result = {"content": [{"type": "text", "text": json.dumps({"args": sys.argv[1:], "cwd": os.getcwd(), "env": os.environ.get("FIXTURE_ENV"), "ambient": os.environ.get("UNRELATED"), "arguments": params.get("arguments", {})})}]}
print(json.dumps({"jsonrpc": "2.0", "id": request["id"], "result": result}), flush=True)
asyncio.run(main())
"""
@@ -145,6 +147,22 @@ class McpRegistryTest(unittest.TestCase):
self.assertTrue(first.closed)
self.assertIs(second, opened[-1])
+ def test_config_failure_preserves_cached_generation(self):
+ generation = self.generation({"type": "http", "url": "a"}, [])
+ mcp._registry._generations["svc"] = generation
+
+ async def unavailable(_server):
+ raise RuntimeError("host request timed out")
+
+ async def scenario():
+ with mock.patch.object(mcp, "_config", unavailable):
+ with self.assertRaises(RuntimeError):
+ await mcp._registry.get("svc")
+
+ run(scenario())
+ self.assertFalse(generation.closed)
+ self.assertIs(mcp._registry._generations["svc"], generation)
+
def test_reload_waits_for_in_flight_first_open(self):
opening = asyncio.Event()
release = asyncio.Event()
@@ -268,6 +286,37 @@ class McpRegistryTest(unittest.TestCase):
self.assertEqual(env, {"PATH": "/bin", "TOKEN": "value"})
self.assertNotIn("UNRELATED", env)
+ def test_acp_headers_never_consult_or_override_host_oauth(self):
+ config = {
+ "type": "http",
+ "url": "https://task.example/mcp",
+ "headers": {"Authorization": "Bearer task-token"},
+ "credentialSource": "acp",
+ }
+ with mock.patch.object(mcp, "_read_auth", side_effect=AssertionError("auth.json must not be read")):
+ headers = run(mcp._headers("linear", config))
+ self.assertEqual(headers, {"Authorization": "Bearer task-token"})
+
+ def test_acp_config_skips_oauth_identity_and_refresh(self):
+ async def host_request(_method, _payload):
+ return {
+ "type": "http",
+ "url": "https://task.example/mcp",
+ "headers": {"Authorization": "Bearer task-token"},
+ "credentialSource": "acp",
+ }
+
+ with mock.patch.object(mcp, "host_request", host_request), mock.patch.object(
+ mcp, "_auth_identity", side_effect=AssertionError("ACP must not resolve host credentials")
+ ):
+ config = run(mcp._config("linear"))
+ self.assertNotIn("_authIdentity", config)
+
+ def test_acp_stdio_env_uses_literal_values_without_ambient_secrets(self):
+ with mock.patch.dict(os.environ, {"PATH": "/bin", "UNRELATED": "ambient-secret"}, clear=True):
+ env = mcp._stdio_env({"credentialSource": "acp", "env": {"TOKEN": "task-secret"}})
+ self.assertEqual(env, {"PATH": "/bin", "TOKEN": "task-secret"})
+
def test_endpoint_bound_credential_never_attaches_to_another_url(self):
cred = {"access": "old-token", "endpoint": "https://old.example/mcp"}
config = {"oauth": True, "url": "https://new.example/mcp"}
@@ -428,6 +477,60 @@ class McpRegistryTest(unittest.TestCase):
return run(scenario())
+ def test_real_acp_stdio_preserves_cwd_and_exact_env(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ fixture = Path(tmp) / "stdio_server.py"
+ fixture.write_text(_STDIO_FIXTURE)
+ config = {
+ "type": "stdio",
+ "command": sys.executable,
+ "args": [str(fixture), "task"],
+ "cwd": str(fixture.parent),
+ "env": {"FIXTURE_ENV": "task-secret"},
+ "credentialSource": "acp",
+ }
+
+ async def scenario():
+ with mock.patch.dict(os.environ, {"UNRELATED": "ambient-secret"}, clear=False):
+ generation = mcp._Generation("task-tools", config)
+ await generation.open()
+ try:
+ result = await generation.call("fixture/raw.tool", {})
+ finally:
+ await generation.close()
+ return json.loads(result)
+
+ output = run(scenario())
+ self.assertEqual(Path(output["cwd"]).resolve(), fixture.parent.resolve())
+ self.assertEqual(output["env"], "task-secret")
+ self.assertIsNone(output["ambient"])
+
+ def test_reload_reaps_real_acp_stdio_process(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ fixture = Path(tmp) / "stdio_server.py"
+ pid_file = Path(tmp) / "stdio.pid"
+ fixture.write_text(_STDIO_FIXTURE)
+ config = {
+ "type": "stdio",
+ "command": sys.executable,
+ "args": [str(fixture)],
+ "cwd": str(fixture.parent),
+ "env": {"FIXTURE_PID_FILE": str(pid_file)},
+ "credentialSource": "acp",
+ }
+
+ async def scenario():
+ with mock.patch.object(mcp, "_config", new=mock.AsyncMock(return_value=config)):
+ await mcp._registry.tools("task-tools")
+ pid = int(pid_file.read_text())
+ os.kill(pid, 0)
+ await mcp._registry.reload("task-tools")
+ return pid
+
+ pid = run(scenario())
+ with self.assertRaises(ProcessLookupError):
+ os.kill(pid, 0)
+
def test_real_stdio_startup_diagnostic_is_safe_bounded_and_reaped(self):
secret = "stdio-secret-SENTINEL"
with tempfile.TemporaryDirectory() as tmp: