Skip to content

feat(acp): honour client-supplied mcpServers with a per-session tool registry - #1914

Merged
addyCooks merged 4 commits into
Nano-Collective:mainfrom
addyCooks:feat/acp-session-mcp-servers
Oct 29, 2026
Merged

addyCooks merged 4 commits into
Nano-Collective:mainfrom
addyCooks:feat/acp-session-mcp-servers

Conversation

@addyCooks

Copy link
Copy Markdown
Collaborator

Description

The ACP agent ignored the mcpServers a client sends on session/new, session/load and session/resume. MCP servers came only from the user's own config, loaded once into one ToolManager shared by every session.

  • The stdio and HTTP servers a client sends are now connected for that session only. SSE (and MCP-over-ACP) entries are skipped with a log line, since Nanocoder has no such transport.
  • A session with client servers gets a ToolManager layered over the shared one (ToolManager.forSession(), backed by a ToolRegistry that can sit on a parent). Its MCP tools are visible and runnable in that session and no other, the shared tools are still read live, and the subagents the session starts use the same tools.
  • session/load and session/resume replace the session's previous set (an empty list returns it to the shared tools). session/close, session/delete and re-registering the same session ID disconnect only that session's servers. Each session manager keeps its own shutdown handler, so closing one never removes the shared manager's.
  • A server that fails to connect is logged and skipped, and the request still succeeds. A tool whose name an existing tool already has is skipped with a warning.
  • initialize now reports mcpCapabilities: {http: true}.
  • The user's MCP config files are never read or changed by this. A session with no mcpServers behaves exactly as before.

Client servers follow the same approval rules as MCP tools from the user's own config (they ask in normal mode and run unprompted in auto-accept and yolo; the client cannot pre-approve them). They are trusted like the rest of what the client sends, since it launched the agent, so they skip the project-config security check.

Closes #1889

Type of Change

  • Bug fix
  • New feature
  • Breaking change
  • Documentation update

Changeset

  • Added a changeset (pnpm changeset) describing this change for the changelog

Testing

Automated Tests

  • New features include passing tests in .spec.ts/tsx files
  • All existing tests pass (pnpm test:all completes successfully)
  • Tests cover both success and error scenarios

Manual Testing

  • Tested with Ollama
  • Tested with OpenRouter
  • Tested with OpenAI-compatible API
  • Tested MCP integration (if applicable)

Checklist

  • If this was for an open issue, I was assigned to it
  • Code follows project style guidelines
  • Self-review completed
  • Documentation updated (if needed)
  • No breaking changes (or clearly documented)
  • Appropriate logging added using structured logging (see CONTRIBUTING.md)

…registry

session/new, session/load and session/resume now connect the stdio and HTTP mcpServers a client sends, for that session only. A session with servers gets a ToolManager layered over the shared one, so its MCP tools are visible and runnable there and nowhere else, and the subagents it starts use the same tools. Load and resume replace the session's set; close, delete and re-registering the session disconnect it, and each session manager keeps its own shutdown handler. A server that fails to connect, or uses SSE, is logged and skipped. A tool whose name already exists is skipped. initialize now reports mcpCapabilities. Sessions with no servers are unchanged. Closes Nano-Collective#1889
@github-actions github-actions Bot added area:tools Tool implementations and tool-calling area:docs Documentation labels Oct 29, 2026
@github-actions

Copy link
Copy Markdown
Contributor

nc-review: comments — 1 important, 5 nits

@addyCooks — a few things worth a look, none blocking.

The PR makes Nanocoder's ACP agent honour client-supplied mcpServers by layering a per-session ToolManager over the shared one: a parent-linked ToolRegistry gives each session its own MCP tools while still reading the shared set live, and the session manager is threaded through ToolExecutionContext -> processToolUse -> SubagentExecutor so top-level calls and subagents both resolve against it. The isolation design is sound — no global registry mutation, per-manager MCP clients, unique shutdown-handler names so closing a session does not clobber the shared mcp-client handler, and release wired into closeSession/deleteSession/resumeSession — and the test coverage is substantial and genuinely exercises the new paths. Two things to fix before merging: buildApprovalMeta still reads the shared manager, so the advisory alwaysAllow list the client is told about omits the session's own MCP tools, and the mcpCapabilities: {http: true} shape could not be verified against @agentclientprotocol/sdk v1.3.0 offline. The feature is warranted and I found no duplicate among the open PRs, though it touches the same MCP-tool-shadowing area as #1863 without overlapping it.

🟠 important · completeness · source/acp/acp-agent.ts:924

buildApprovalMeta still uses the shared manager while the PR moved the prompt builder to the session's manager:

private async buildApprovalMeta(session: AcpSession) {
    return {
        'nanocoder/approval': {
            alwaysAllow: await getAlwaysAllowedTools(
                this.initContext.toolManager,
                session.developmentMode,
                getAppConfig().alwaysAllow ?? [],
            ),
        },
    };
}

buildSystemPromptForSession was changed to this.toolManagerFor(session.sessionId), but this one was not. getAlwaysAllowedTools walks getAvailableToolNames(), so for a session with its own MCP servers the advertised list omits those tools entirely, and the client is told a session offers fewer auto-approved tools than it does. The docs added by this PR state that the session's MCP tools "follow the same approval rules as MCP tools from your own config", which the client cannot see. Use this.toolManagerFor(session.sessionId) here too.

Note this list is advisory (the client shows it; it does not change how approvals are decided), so nothing is wrongly auto-approved today — but the metadata now contradicts the session's actual tool set.

⚪ nit · correctness · source/acp/acp-capabilities.ts:46

The advertised capability is mcpCapabilities: {http: true}, with the comment "stdio is always supported; Nanocoder has no SSE transport". I could not verify this against @agentclientprotocol/sdk v1.3.0 — node_modules is not present in this checkout and the SDK types are not vendored, so the shape of AgentCapabilities.mcpCapabilities in that version is unconfirmed. If the SDK declares it as {http: boolean; sse: boolean} with both required, this is a type error and the advertised value misreports SSE support as simply absent rather than false. Worth a check against the installed SDK before merge; the comment already explains the intent, so only the literal may need to change.

⚪ nit · design · source/acp/acp-conversation.ts:744

RunAcpConversationOptions now carries both toolManager and sessionTools, and in the ACP path they are always the same object — toolManagerFor(sessionId) returns this.sessionToolManagers.get(sessionId) when the session has its own servers, and sessionTools is that same map lookup. The tool list offered to the model comes from toolManager, while execution resolves through sessionTools, so the two must agree; today they do only because they are literally the same value. If they ever diverge, the model would be offered a tool whose handler processToolUse cannot resolve, and the failure would surface as Unknown tool: <name> at call time rather than at wiring time. Either pass one value, or have the second be derived from the first so the coupling cannot drift.

⚪ nit · design · source/tools/tool-manager.ts:259

The session manager's MCP client is obtained with if (this.parent) return this.parent.createMCPClient();. This is correct — the parent's factory constructs a fresh MCPClient, so the session gets its own and the parent's mcpClient field is untouched — but it reads as though the parent hands over its existing client, which would break the isolation the PR is built on. A reader checking getMCPClient() on the parent after a session connects would reasonably expect a shared instance here. Inverting it to construct the client directly in the session branch (and letting createMCPClient remain the base-only hook) would make the independence explicit. The test forSession - disconnecting a session removes only its tools and leaves the shared ones connected already pins the behaviour.

⚪ nit · security · source/acp/acp-capabilities.ts:46

A client-supplied stdio MCP server is spawned as an arbitrary command (command + args + env, with no allowlisting in TransportFactory.createStdioTransport), and MCP tool entries carry an approval policy that skips the prompt in auto-accept — the mode ACP sessions start in. So an editor that sends mcpServers gets unprompted command execution with no gate, whereas execute_bash still asks in that mode. I read this as acceptable: the client is the editor that launched the agent and is already inside the trust boundary (it could equally ask the agent to run a shell command), and the PR documents the behaviour explicitly in docs/features/acp.md. Flagging only so it is a deliberate, recorded decision rather than an accident — if the ACP surface is ever exposed to a less-trusted client, this is the line that moves.

⚪ nit · tests · source/tools/tool-manager.spec.ts:1344

The forSession tests are thorough on the tool-visibility axis (live parent reads, two sessions not seeing each other, per-session disconnect, unique shutdown handler, name collision skipped) but two behaviours are untested. First, getMCPToolInfo on a session manager now falls back to the parent, so a session manager must still report a shared MCP tool as an MCP tool — getAlwaysAllowedTools in source/acp/acp-approval.ts depends on that, and a regression there would silently drop shared MCP tools from the client's advertised allow-list. Second, buildApprovalMeta still reads this.initContext.toolManager rather than the session's manager, so nothing pins the advisory list for a session that has its own servers. A test asserting session.getMCPToolInfo('shared_mcp') returns {isMCPTool: true} would cover the fallback; the buildApprovalMeta gap is filed separately as a completeness finding.


🔴 blocking · 🟠 a reviewer would ask for a change · ⚪ optional

Automated code review — correctness, security, design, tests, plus duplicates and scope. A human still decides; this is not a substitute for review and is not exhaustive. The required status checks separately cover lint, formatting, types, unused dependencies, the test suite and the build. This bot never merges. Maintainers can rerun with /re-review.

@github-actions github-actions Bot added the agent:comments nc-review left non-blocking findings label Oct 29, 2026
buildApprovalMeta read the shared tool manager, so the alwaysAllow list sent to the client left out the tools of a session's own MCP servers. It now reads the session's manager, as the system prompt does. The manager handed to a turn is derived from the same lookup that supplies the tools its calls run against, so the two cannot differ. Pins that a session manager still reports a shared MCP tool as one.
@addyCooks

Copy link
Copy Markdown
Collaborator Author

/re-review

@github-actions

Copy link
Copy Markdown
Contributor

nc-review: comments — 1 important, 3 nits

@addyCooks — a few things worth a look, none blocking.

The PR makes Nanocoder's ACP agent honour client-supplied mcpServers by layering a per-session ToolManager over the shared one: a parent-linked ToolRegistry gives each session its own MCP tools while still reading the shared set live, and the session manager is threaded through ToolExecutionContext -> processToolUse -> SubagentExecutor so top-level calls and subagents both resolve against it. The isolation design is sound - no global registry mutation, per-manager MCP clients, unique shutdown-handler names so closing a session does not clobber the shared mcp-client handler, and release wired into closeSession/deleteSession/resumeSession - and the test coverage is substantial and genuinely exercises the new paths (a real stdio MCP fixture, two isolated sessions, per-session disconnect, load/resume replacement, a failing server skipped, SSE skipped, a name collision skipped). The one thing to fix before merging is that the branch is built on a commit older than the current base, so the diff for source/tools/agent-tool.tsx and source/types/core.ts predates the delegationContext() helper and the toolCallId/subagentRunId plumbing; a rebase has to add toolManager alongside those IDs rather than replace them, or the ACP subagent-run correlation silently stops working. The feature is warranted, it resolves the linked issue, and I found no duplicate among the open PRs, though it touches the same MCP-tool-shadowing area as #1863 without overlapping it.

Addressed since the last review

  • ✅ buildApprovalMeta now resolves against the session's own manager (this.toolManagerFor(session.sessionId)) instead of the shared one, and a new ACP agent test pins the advisory alwaysAllow list to include the session's own MCP tool - the contradiction I flagged is gone.
  • ✅ The getMCPToolInfo parent fallback is now covered by a test (forSession - still reports a shared MCP tool as an MCP tool), so a regression there can no longer silently drop shared MCP tools from the advertised allow-list.
  • ✅ createMCPClient on a session manager now carries the comment "The parent's factory builds a new client; its own is not handed over", which makes the independence explicit and answers my readability concern about that seam.
  • ✅ The trust decision for client-supplied servers - arbitrary stdio command execution, unprompted in auto-accept, no project-config security check - is now written down in docs/features/acp.md, so it reads as deliberate rather than accidental.

🟠 important · correctness · source/tools/agent-tool.tsx:58

This branch is behind main, and the conflict resolution needs care. The diff's hunk for this file applies to an inline context object:

const executionContext = {
	sessionId: options?.sessionId,
	workingDirectory: options?.workingDirectory,
	...(options?.toolManager && {toolManager: options.toolManager}),
};

The current base has no such literal - it has a delegationContext() helper that also carries the call and run ids:

function delegationContext(options?: ToolExecutionContext) {
	return {
		sessionId: options?.sessionId,
		workingDirectory: options?.workingDirectory,
		...(options?.toolCallId !== undefined && {toolCallId: options.toolCallId}),
		...(options?.subagentRunId !== undefined && {
			subagentRunId: options.subagentRunId,
		}),
	};
}

The same drift shows in source/types/core.ts (the PR's ToolExecutionContext hunk has no toolCallId/subagentRunId) and in source/acp/acp-conversation.ts (the PR's processToolUse hunk has no toolCallId: toolCall.id). Those ids are load-bearing: executionContext?.toolCallId and executionContext?.subagentRunId are what emitSubagentRunEvent reports as toolCallId and parentRunId (source/subagents/subagent-executor.ts:307), which is how a client correlates a nanocoder/subagent run with the agent call that started it. So when this branch is rebased, please add toolManager into delegationContext() rather than resolving the conflict by restoring the old inline literal - a silent drop of the two ids breaks the already-shipped subagent-events feature, and it fails quietly (no error, just missing correlation metadata in the notification).

⚪ nit · correctness · source/acp/acp-capabilities.ts:46

Still unverified: the advertised capability is mcpCapabilities: {http: true}, with the comment "stdio is always supported; Nanocoder has no SSE transport". I could not check this against @agentclientprotocol/sdk v1.3.0 - node_modules is not present in this checkout and the SDK types are not vendored, so the shape of AgentCapabilities.mcpCapabilities in that version is unconfirmed. If the SDK declares it as {http: boolean; sse: boolean} with both required, this is a type error and the advertised value reports SSE support as merely absent rather than false. Worth a check against the installed SDK before merge; the comment already explains the intent, so only the literal may need to change.

⚪ nit · design · source/acp/acp-conversation.ts:744

RunAcpConversationOptions now carries both toolManager and sessionTools, and in the ACP path they are always the same object - toolManagerFor(sessionId) returns this.sessionToolManagers.get(sessionId) when the session has its own servers, and sessionTools is that same map lookup. The tool list offered to the model comes from toolManager, while execution resolves through sessionTools, so the two must agree; today they do only because they are literally the same value. If they ever diverge, the model would be offered a tool whose handler processToolUse cannot resolve, and the failure would surface as Unknown tool: <name> at call time rather than at wiring time. Either pass one value, or have the second be derived from the first so the coupling cannot drift.

⚪ nit · design · source/acp/acp-agent.ts:941

applyMcpServers is awaited inside newSession, loadSession and resumeSession, so the ACP request now blocks on the connect handshake of every client-supplied server. acpMcpServersToConfig produces no timeout, and MCPClient.connectToServer only passes a connect timeout when the server config carries one (typeof normalizedServer.timeout === 'number' && normalizedServer.timeout > 0), so the SDK's own default applies - a client pointing at an HTTP endpoint that accepts the connection but never answers will hold session/new open for that long. Failures are handled correctly (logged, skipped, the request still succeeds), and awaiting is the right call so the tools are ready before the first turn, but an explicit short timeout on client-supplied servers would bound the wait instead of inheriting the SDK default.


🔴 blocking · 🟠 a reviewer would ask for a change · ⚪ optional

Automated code review — correctness, security, design, tests, plus duplicates and scope. A human still decides; this is not a substitute for review and is not exhaustive. The required status checks separately cover lint, formatting, types, unused dependencies, the test suite and the build. This bot never merges. Maintainers can rerun with /re-review.

@addyCooks
addyCooks merged commit 5b0fbf6 into Nano-Collective:main Oct 29, 2026
18 checks passed
addyCooks added a commit to addyCooks/nanocoder that referenced this pull request Oct 30, 2026
Resolves the conflicts with the per-session tool registry (Nano-Collective#1914) and disabled tools (Nano-Collective#1915) on main: a session now builds its prompt with its own tool manager, provider and model, and keeps its disabled tools when it is created or loaded.

Also addresses the nc-review comments: aggressive compaction is now a per-session preset passed to auto-compact instead of the process-wide one, so one session switching provider cannot change when another compacts; switching to a provider that lists no models gives the session that provider's (empty) model instead of the previous provider's, and does not record it as the last-used selection; and the mid-turn test now observes the prompt rebuild directly.
diyaavirmani added a commit to diyaavirmani/nanocoder that referenced this pull request Nov 2, 2026
Resolves the conflicts with Nano-Collective#1914, which gives each ACP session a
ToolManager layered over the shared one and skips a session MCP tool
whose name the parent already offers.

- registerMCPEntries replaces registerMcpTools. The layered registry's
  hasTool already sees the parent's tools, so a name the parent offers
  is skipped by the same check as a built-in, and is also reported in
  skippedTools. Upstream's warning log is kept for every skip.
- mcpReadOnly reads only names this manager's MCP client registered,
  then falls back to the parent. Upstream's version read the client's
  mapping for any name, which let a skipped tool's annotation decide
  whether plan mode offers the built-in ("plan mode keeps a built-in
  that an unannotated MCP tool is named like" fails without this).
- getMCPToolInfo keeps the registered-name lookup and upstream's parent
  fallback.
- New spec: a session's skipped MCP tool is reported and does not mark
  the existing tool as an MCP tool.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent:comments nc-review left non-blocking findings area:docs Documentation area:tools Tool implementations and tool-calling

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Honor client-supplied mcpServers in ACP sessions, with a per-session tool registry

1 participant