Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(composer): select MCP servers and tools explicitly
zszz30d51846c02e7
diff --git a/apps/desktop/electron/main/composer-mcp.ts b/apps/desktop/electron/main/composer-mcp.tsnew file mode 100644index 000000000..3e66db515--- /dev/null+++ b/apps/desktop/electron/main/composer-mcp.ts@@ -0,0 +1,26 @@+import type { ComposerCommand } from "@pi-desktop/shared";++/** Expand a server selection only against the send-time project catalog. */+export function expandMcpInvocation(content: string, commands: ComposerCommand[]) {+ const match = /^\/(mcp:\S+)(?:\s|$)/.exec(content);+ if (!match) return null;+ const command = commands.find((entry) => entry.name === match[1]);+ if (command && command.kind !== "mcp") return null;+ if (!command?.mcpServerId) {+ throw Object.assign(new Error("Selected MCP server unavailable"), {+ errorCode: "COMPOSER_MCP_UNAVAILABLE",+ });+ }+ const body = content.slice(match[0].length).trim();+ return {+ command: content,+ mcpServerIds: [command.mcpServerId],+ ...(command.mcpToolName ? { mcpToolNames: [command.mcpToolName] } : {}),+ expanded: [+ command.mcpToolName+ ? `The user selected the MCP tool ${JSON.stringify(command.mcpToolName)} from ${JSON.stringify(command.title)} for this request.`+ : `The user selected the MCP server ${JSON.stringify(command.title)} for this request.`,+ body,+ ].filter(Boolean).join("\n\n"),+ };+}diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.tsindex 98396665d..83ab6fdea 100644--- a/apps/desktop/electron/main/ipc/agent-ipc.ts+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts@@ -1,3 +1,4 @@+import { expandMcpInvocation } from "../composer-mcp";import { IPC, ErrorCodes, compactionRecordId, findSkillMentions, isGlobalPermissionMode, isRpcTimeoutError, type AgentEventEnvelope, type AgentPromptRequest, type AgentSteerRequest, type UiMessage, type AgentQueuePushRequest, type AgentStopRequest, type AskToolResolution, type GlobalPermissionMode, type MessageUsage, type PendingInteractiveRequests, type PlanExecutionFinishStatus, type PlanResolutionResult, type PlanResolveRequest, type PromptEnhancementRequest, type SessionSummarizeTitleRequest, type VoiceOrigin, canonicalThinkingLevel, type ThinkingLevel } from "@pi-desktop/shared";import type { FinishTurn } from "../runtime/plans";import { expandSlashInvocation, enhancePromptDraft, summarizeSessionTitle, visionFromModelConfig, type ComposerTemplate, type RuntimeProviderConfig } from "@pi-desktop/agent-runtime";@@ -287,6 +288,9 @@ export function registerAgentIpc({const context = await sidecar.call<{ projectPath?: string; supportsVision: boolean }>("agent.steeringContext", { sessionId: req.sessionId, expectedTurnId: req.expectedTurnId },);+ const mcpExpansion = /^\/mcp:\S/.test(req.content)+ ? expandMcpInvocation(req.content, await composerCommandService.buildComposerCommands(context.projectPath ?? null))+ : null;const prepared = await preparePromptAttachments(dataDir, req.sessionId, context.projectPath, req.attachments ?? [], context.supportsVision,);@@ -296,7 +300,8 @@ export function registerAgentIpc({const message: UiMessage = {id: durableUserMessageId(req.messageId, session.session?.messages ?? []),role: "user",- content: req.content,+ content: mcpExpansion?.expanded ?? req.content,+ ...(mcpExpansion ? { command: mcpExpansion.command } : {}),status: "complete",createdAt: new Date().toISOString(),steering: true,@@ -307,7 +312,8 @@ export function registerAgentIpc({// never turn into a normal prompt or alter the next turn's configuration.return sidecar.call<{ accepted: boolean; turnId: string }>("agent.steer", {sessionId: req.sessionId, expectedTurnId: req.expectedTurnId, message,- content: appendPromptFallbackPaths(req.content, prepared),+ content: appendPromptFallbackPaths(mcpExpansion?.expanded ?? req.content, prepared),+ ...(mcpExpansion ? { mcpServerIds: mcpExpansion.mcpServerIds, mcpToolNames: mcpExpansion.mcpToolNames } : {}),attachments: prepared.filter((attachment) => attachment.inlineData).map((attachment) => ({path: attachment.message.ref, name: attachment.message.name, kind: attachment.message.kind,mimeType: attachment.message.mimeType, size: attachment.message.size, data: attachment.inlineData,@@ -319,6 +325,8 @@ export function registerAgentIpc({if (!sidecar) throw new Error("sidecar unavailable");const voiceOrigin = parseVoiceOrigin(req.voiceOrigin);if (req.sessionId.startsWith("native-pi:")) {+ // Desktop-managed MCP servers are not installed in native Pi sessions.+ if (/^\/mcp:\S/.test(req.content)) expandMcpInvocation(req.content, []);if (voiceOrigin) {throw Object.assign(new Error("Live Voice work is unsupported for native Pi sessions"), {errorCode: "NATIVE_PI_UNSUPPORTED",@@ -362,6 +370,14 @@ export function registerAgentIpc({errorCode: ErrorCodes.NOT_FOUND,});}+ // Validate explicit MCP selection before a turn or history replacement.+ // Use the session's project, never the currently focused renderer project.+ const mcpExpansion = !sessionMessage && /^\/mcp:\S/.test(req.content)+ ? expandMcpInvocation(req.content, await composerCommandService.buildComposerCommands(+ typeof session.projectPath === "string" ? session.projectPath.trim() || null : null,+ ))+ : null;+const truncateFromMessageId =typeof req.truncateFromMessageId === "string"? req.truncateFromMessageId.trim()@@ -468,10 +484,10 @@ export function registerAgentIpc({// explicit, while the typed form remains the visible transcript chip.// Builtin/plugin slash aliases never reach this channel, and unknown// /names stay literal text.- let promptContent = sessionMessage?.content ?? req.content;- let slashCommand: string | undefined;+ let promptContent = mcpExpansion?.expanded ?? sessionMessage?.content ?? req.content;+ let slashCommand: string | undefined = mcpExpansion?.command;let skillMentions: UiMessage["skillMentions"];- if (!sessionMessage && /(^|\s)\/\S/.test(req.content)) {+ if (!sessionMessage && !mcpExpansion && /(^|\s)\/\S/.test(req.content)) {try {const root = await optionalWorkspaceRoot();const commandEnd = req.content.search(/\s/);@@ -641,6 +657,7 @@ export function registerAgentIpc({// Rust. The runtime must not replace it with a provider-local UUID.turnId: durableTurnId,content: modelContent,+ ...(mcpExpansion ? { mcpServerIds: mcpExpansion.mcpServerIds, mcpToolNames: mcpExpansion.mcpToolNames } : {}),...(sessionMessage ? { sessionMessage: sessionMessage.origin } : {}),attachments: [...preparedAttachmentsdiff --git a/apps/desktop/electron/main/ipc/composer-ipc.ts b/apps/desktop/electron/main/ipc/composer-ipc.tsindex 30bc1dbb0..e208364c2 100644--- a/apps/desktop/electron/main/ipc/composer-ipc.ts+++ b/apps/desktop/electron/main/ipc/composer-ipc.ts@@ -1,4 +1,6 @@-import { IPC, trustedExtensionCommandId, type ComposerCommand } from "@pi-desktop/shared";+import { userMcpToolName } from "@pi-desktop/plugin-sdk";+import type { UserMcpRuntime } from "../user-mcp";+import { IPC, isActiveInProject, trustedExtensionCommandId, type ComposerCommand } from "@pi-desktop/shared";import { builtinSkills } from "../builtin-skills";import { builtinComposerCommands } from "../builtin-commands";import type { AgentExtensionBridge } from "../agent-extensions";@@ -10,6 +12,8 @@ type ComposerTemplateSource = "user" | "project";export type ComposerIpcDependencies = {registrar: IpcRegistrar;plugins: PluginRuntime;+ userMcp?: Pick<UserMcpRuntime, "listRecords" | "listStatuses" | "toolsForProject">;+ refreshUserMcp?: (root: string | null) => Promise<unknown>;agentExtensions: AgentExtensionBridge;optionalWorkspaceRoot: () => Promise<string | null>;activeUserSkills: (root?: string) => Promise<Array<{@@ -32,6 +36,8 @@ export type ComposerCommandService = {export function createComposerCommandService({plugins,+ userMcp,+ refreshUserMcp,agentExtensions,activeUserSkills,pluginActiveInProject,@@ -76,6 +82,8 @@ export function createComposerCommandService({const buildComposerCommands = async (root: string | null,): Promise<ComposerCommand[]> => {+ await refreshUserMcp?.(root);+ await userMcp?.toolsForProject(root);const templates = await loadComposerTemplatesCached(root).catch(() => []);const templateCommands = templates.map((template) => ({name: template.name,@@ -103,12 +111,33 @@ export function createComposerCommandService({id: trustedExtensionCommandId(command.name),}));const skillCommands = await loadComposerSkillCommands(root).catch(() => []);+ const statuses = userMcp?.listStatuses() ?? [];+ const ready = new Set(statuses+ .filter((status) => status.state === "ready" && status.toolCount > 0)+ .map((status) => status.serverId));+ const mcpCommands: ComposerCommand[] = (userMcp?.listRecords() ?? [])+ .filter((record) => ready.has(record.id) && isActiveInProject(record, root))+ .flatMap((record) => {+ const server: ComposerCommand = {+ name: `mcp:${encodeURIComponent(record.id)}`,+ kind: "mcp",+ title: record.label,+ mcpServerId: record.id,+ };+ const names = statuses.find(status => status.serverId === record.id)?.toolNames ?? [];+ return [server, ...[...new Set(names)].map(toolName => ({+ ...server,+ name: `${server.name}:${encodeURIComponent(toolName)}`,+ mcpToolName: userMcpToolName(record.id, toolName),+ }))];+ });const merged = new Map<string, ComposerCommand>();for (const command of [...builtinComposerCommands(),...templateCommands,...pluginCommands,...extensionCommands,+ ...mcpCommands,...skillCommands,]) {if (!merged.has(command.name)) merged.set(command.name, command);diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.tsindex 4b30b8e57..009d0e31e 100644--- a/apps/desktop/electron/main/ipc/register.ts+++ b/apps/desktop/electron/main/ipc/register.ts@@ -301,6 +301,8 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {const loadComposerTemplatesCached = createComposerTemplateLoader(logger);const composerCommandService = registerComposerIpc({registrar,+ userMcp,+ refreshUserMcp,plugins,agentExtensions,optionalWorkspaceRoot,diff --git a/apps/desktop/electron/main/runtime/session-launch.ts b/apps/desktop/electron/main/runtime/session-launch.tsindex 6a54abef0..569fdc8f6 100644--- a/apps/desktop/electron/main/runtime/session-launch.ts+++ b/apps/desktop/electron/main/runtime/session-launch.ts@@ -665,6 +665,7 @@ export function createSessionLaunchRuntime({})),...userMcpTools.map((tool) => ({name: tool.fullName,+ mcpServerId: tool.serverId,description: tool.description,parameters: tool.schema ?? { type: "object", properties: {} },})),diff --git a/apps/desktop/src/components/ComposerAutocomplete.tsx b/apps/desktop/src/components/ComposerAutocomplete.tsxindex be391bc2a..f18338a75 100644--- a/apps/desktop/src/components/ComposerAutocomplete.tsx+++ b/apps/desktop/src/components/ComposerAutocomplete.tsx@@ -50,12 +50,13 @@ const GROUP_KEYS: Record<ComposerCommand["kind"], string> = {plugin: "chat.slashGroupPlugins",extension: "chat.slashGroupExtensions",skill: "chat.slashGroupSkills",+ mcp: "chat.slashGroupMcp",};function CommandIcon({ kind }: { kind: ComposerCommand["kind"] }) {if (kind === "template") return <IconSlash size={14} />;if (kind === "skill") return <IconBookOpen size={14} />;- if (kind === "plugin" || kind === "extension") return <IconPlug size={14} />;+ if (kind === "plugin" || kind === "extension" || kind === "mcp") return <IconPlug size={14} />;return <IconSparkles size={14} />;}@@ -111,7 +112,7 @@ export function ComposerAutocomplete({<span className="composer-ac-name">/<Highlighted text={item.command.name} ranges={item.match.ranges} /></span>- {item.command.kind === "skill" && item.command.title !== item.command.name ? (+ {(item.command.kind === "skill" || item.command.kind === "mcp") && item.command.title !== item.command.name ? (<span className="composer-ac-hint">{item.command.title}</span>) : null}{item.command.argumentHint ? (diff --git a/apps/desktop/src/hooks/use-composer-autocomplete.ts b/apps/desktop/src/hooks/use-composer-autocomplete.tsindex 0b19f7702..2d651cd9f 100644--- a/apps/desktop/src/hooks/use-composer-autocomplete.ts+++ b/apps/desktop/src/hooks/use-composer-autocomplete.ts@@ -46,7 +46,8 @@ const COMMAND_GROUP_ORDER = {builtin: 1,plugin: 2,extension: 3,- skill: 4,+ mcp: 4,+ skill: 5,} as const;function filterCommands(diff --git a/apps/desktop/test/composer-mcp.test.mjs b/apps/desktop/test/composer-mcp.test.mjsnew file mode 100644index 000000000..09761ad29--- /dev/null+++ b/apps/desktop/test/composer-mcp.test.mjs@@ -0,0 +1,199 @@+import assert from "node:assert/strict";+import test from "node:test";+import { register } from "node:module";+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));+const { createComposerCommandService } = await import("../electron/main/ipc/composer-ipc.ts");++const record = (id, extra = {}) => ({ id, label: "Documentation", transport: "http", enabled: true, createdAt: "", updatedAt: "", ...extra });+const ready = (serverId) => ({ serverId, state: "ready", toolCount: 1, toolNames: ["search"], updatedAt: 0 });+function service(records, statuses) {+ return createComposerCommandService({+ plugins: { listLoaded: () => [], getSkills: () => [], getCommands: () => [] },+ agentExtensions: { allCommands: () => [] },+ activeUserSkills: async () => [], pluginActiveInProject: () => true,+ loadComposerTemplatesCached: async () => [],+ userMcp: { listRecords: () => records, listStatuses: () => statuses, toolsForProject: async () => [] },+ });+}+test("slash source lists only ready MCP servers in the current project without credentials", async () => {+ const records = [record("docs", { url: "https://private.invalid", headers: { Authorization: "secret" } }), record("off", { enabled: false }), record("other", { scope: { mode: "projects", projects: ["/other"] } }), record("idle")];+ const commands = await service(records, records.slice(0, 3).map(r => ready(r.id))).buildComposerCommands("/repo");+ const mcp = commands.filter(c => c.kind === "mcp");+ assert.equal(mcp.length, 2);+ assert.equal(mcp[0].name, "mcp:docs");+ assert.equal(mcp[0].title, "Documentation");+ assert.doesNotMatch(JSON.stringify(mcp), /secret|private.invalid/);+});++const { expandMcpInvocation } = await import("../electron/main/composer-mcp.ts");+const { registerAgentIpc } = await import("../electron/main/ipc/agent-ipc.ts");+const { IPC } = await import("@pi-desktop/shared");++test("selection uses stable encoded IDs even when labels match", async () => {+ const records = [record("docs one"), record("docs/two")];+ const commands = await service(records, records.map(r => ready(r.id))).buildComposerCommands(null);+ assert.deepEqual(commands.filter(c => c.kind === "mcp" && !c.mcpToolName).map(c => c.name), ["mcp:docs%20one", "mcp:docs%2Ftwo"]);+ const input = "/mcp:docs%2Ftwo find API docs";+ const expansion = expandMcpInvocation(input, commands);+ assert.equal(expansion.command, input);+ assert.deepEqual(expansion.mcpServerIds, ["docs/two"]);+ assert.doesNotMatch(expansion.expanded, /ToolSearch|mcp_docs_two_/);+ assert.match(expansion.expanded, /find API docs$/);+ assert.equal(expandMcpInvocation("ordinary text /mcp:docs", commands), null);+ assert.equal(expandMcpInvocation("/mcp:docs template text", [{ name: "mcp:docs", kind: "template" }]), null);+});++function promptFixture(commandService) {+ const handlers = new Map();+ const calls = [];+ const sidecarCalls = [];+ let released = false;+ const host = { async call(method, params) {+ calls.push({ method, params });+ if (method === "settings.get") return {};+ if (method === "session.get") return { session: { id: "target", projectPath: "/repo", messages: [] } };+ if (method === "session.beginTurn") return { turnId: "turn-1" };+ if (method === "session.appendMessage") return {};+ assert.fail(`unexpected RPC ${method}`);+ } };+ registerAgentIpc({+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },+ getHost: () => host,+ getSidecar: () => ({ setProjectInstructionRoot() {}, async call(method, params) {+ sidecarCalls.push({ method, params });+ if (method === "agent.steeringContext") return { projectPath: "/repo", supportsVision: false };+ return { accepted: true, turnId: "turn-1" };+ } }),+ getAgentHostBridge: () => null,+ isTurnDispatchable: () => true,+ logger: { app() {} }, vendorOAuth: {}, agentExtensions: {}, cancelSessionTools() {},+ persistenceOutbox: {}, dataDir: "/unused-for-no-attachments",+ activeTurns: new Map(), activeTurnUsages: new Map(), approvedExecutionIdsBySession: new Map(), claimedExecutionSessions: new Map(),+ resolveAgentRuntimeLaunch: async () => ({+ projectPath: "/repo", providerId: "provider", modelId: "model",+ sidecarParams: { sessionId: "target", provider: { modelConfig: { input: ["text"] } } },+ }),+ acquireSessionOperation: async () => () => { released = true; },+ finishTurn: async () => { assert.fail("no turn failure expected"); },+ emitAgentEvent() {}, setNotificationViewingSessionId() {},+ optionalWorkspaceRoot: async () => "/repo",+ composerCommandService: commandService,+ loadComposerTemplatesCached: async () => [],+ });+ return { calls, sidecarCalls, released: () => released,+ prompt: (content, extra = {}) => handlers.get(IPC.invoke.agentPrompt)({ sessionId: "target", content, ...extra }),+ steer: content => handlers.get(IPC.invoke.agentSteer)({ sessionId: "target", content, expectedTurnId: "turn-1" }),+ };+}++test("menu selection reaches runtime with MCP instructions and preserves the visible command", async () => {+ const catalog = service([record("docs")], [ready("docs")]);+ const selected = (await catalog.buildComposerCommands("/repo")).find(c => c.kind === "mcp");+ const input = `/${selected.name} find API docs`;+ const fixture = promptFixture(catalog);+ await fixture.prompt(input);+ const row = fixture.calls.find(c => c.method === "session.appendMessage").params.message;+ assert.equal(row.command, input);+ assert.match(row.content, /Documentation/);+ assert.deepEqual(fixture.sidecarCalls[0].params.mcpServerIds, ["docs"]);+ assert.equal(fixture.sidecarCalls[0].params.content, row.content);+ assert.equal(fixture.released(), true);+});++for (const change of ["disconnect", "disable", "scope"]) {+ test(`send revalidates ${change} before opening or persisting a turn`, async () => {+ const records = [record("docs")];+ const statuses = [ready("docs")];+ const catalog = service(records, statuses);+ assert((await catalog.buildComposerCommands("/repo")).some(c => c.kind === "mcp"));+ if (change === "disconnect") statuses[0].state = "failed";+ if (change === "disable") records[0].enabled = false;+ if (change === "scope") records[0].scope = { mode: "projects", projects: ["/other"] };+ const fixture = promptFixture(catalog);+ await assert.rejects(fixture.prompt("/mcp:docs find API docs"), { errorCode: "COMPOSER_MCP_UNAVAILABLE" });+ assert(!fixture.calls.some(c => ["session.beginTurn", "session.appendMessage"].includes(c.method)));+ assert.equal(fixture.sidecarCalls.length, 0);+ assert.equal(fixture.released(), true);+ });+}+++test("steering uses the same MCP expansion and preserves typed text", async () => {+ const fixture = promptFixture(service([record("docs")], [ready("docs")]));+ await fixture.steer("/mcp:docs find API docs");+ const sent = fixture.sidecarCalls.find(c => c.method === "agent.steer").params;+ assert.equal(sent.message.command, "/mcp:docs find API docs");+ assert.match(sent.content, /Documentation/);+ assert.deepEqual(sent.mcpServerIds, ["docs"]);+ assert.equal(sent.message.content, sent.content);+});++test("unavailable selection rejects before regenerating history", async () => {+ const fixture = promptFixture(service([], []));+ await assert.rejects(fixture.prompt("/mcp:docs find API docs", { truncateFromMessageId: "previous" }), { errorCode: "COMPOSER_MCP_UNAVAILABLE" });+ assert(!fixture.calls.some(c => c.method === "session.truncateFrom"));+ assert.equal(fixture.sidecarCalls.length, 0);+});++test("native Pi cannot silently accept a Desktop-managed MCP selection", async () => {+ const fixture = promptFixture(service([record("docs")], [ready("docs")]));+ await assert.rejects(fixture.prompt("/mcp:docs find API docs", { sessionId: "native-pi:test" }), { errorCode: "COMPOSER_MCP_UNAVAILABLE" });+ assert.equal(fixture.sidecarCalls.length, 0);+});++for (const method of ["prompt", "steer"]) {+ test(`specific MCP tool selection reaches ${method} with exact identity`, async () => {+ const catalog = service([record("docs")], [ready("docs")]);+ const selected = (await catalog.buildComposerCommands("/repo")).find(c => c.mcpToolName);+ assert.equal(selected?.name, "mcp:docs:search");+ const fixture = promptFixture(catalog);+ await fixture[method](`/${selected.name} find API docs`);+ const sent = fixture.sidecarCalls.find(c => c.method === `agent.${method}`).params;+ assert.deepEqual(sent.mcpServerIds, ["docs"]);+ assert.deepEqual(sent.mcpToolNames, ["mcp_docs_search"]);+ assert.match(sent.content, /mcp_docs_search/);+ });+}++test("a removed tool fails before opening a turn even while its server is ready", async () => {+ const statuses = [ready("docs")];+ const catalog = service([record("docs")], statuses);+ assert((await catalog.buildComposerCommands("/repo")).some(c => c.name === "mcp:docs:search"));+ statuses[0].toolNames = ["replacement"];+ const fixture = promptFixture(catalog);+ await assert.rejects(fixture.prompt("/mcp:docs:search find API docs"), { errorCode: "COMPOSER_MCP_UNAVAILABLE" });+ assert(!fixture.calls.some(c => c.method === "session.beginTurn"));+});++test("cold composer discovery connects enabled MCP servers before the first prompt", async () => {+ const { UserMcpRuntime } = await import("../electron/main/user-mcp.ts");+ let connected = false;+ let calls = 0;+ const tools = [{ name: "search", inputSchema: { type: "object", properties: {} } }];+ const runtime = new UserMcpRuntime({ createClient: () => ({+ async connect() { connected = true; return tools; },+ isConnected: () => connected,+ getTools: () => connected ? tools : [],+ close() { connected = false; },+ async callTool() { calls++; return { content: [] }; },+ }) });+ const catalog = createComposerCommandService({+ plugins: { listLoaded: () => [], getSkills: () => [], getCommands: () => [] },+ agentExtensions: { allCommands: () => [] },+ activeUserSkills: async () => [], pluginActiveInProject: () => true,+ loadComposerTemplatesCached: async () => [], userMcp: runtime,+ refreshUserMcp: async (projectPath) => {+ assert.equal(projectPath, "/repo");+ runtime.setRecords([record("docs")]);+ },+ });+ try {+ assert.equal(runtime.statusFor("docs").state, "idle");+ const commands = await catalog.buildComposerCommands("/repo");+ assert(commands.some(command => command.name === "mcp:docs:search"));+ assert.equal(calls, 0, "discovery must not execute a tool");+ const fixture = promptFixture(catalog);+ await fixture.prompt("/mcp:docs:search find API docs");+ assert.deepEqual(fixture.sidecarCalls[0].params.mcpToolNames, ["mcp_docs_search"]);+ } finally { runtime.disposeAll(); }+});diff --git a/apps/desktop/test/plugin-skills.test.mjs b/apps/desktop/test/plugin-skills.test.mjsindex 2a8b37060..75939634d 100644--- a/apps/desktop/test/plugin-skills.test.mjs+++ b/apps/desktop/test/plugin-skills.test.mjs@@ -91,7 +91,7 @@ test("the composer lists active skills last and routes slash skills to the Skillassert.match(mainSrc, /skillId: skill\.id/);assert.match(mainSrc,- /\.\.\.extensionCommands,\s*\.\.\.skillCommands,/,+ /\.\.\.extensionCommands,\s*\.\.\.mcpCommands,\s*\.\.\.skillCommands,/,);assert.match(mainSrc, /findSkillMentions\(req\.content, activeSkills\)/);assert.match(mainSrc, /Call the \\`Skill\\` tool with each of these ids/);diff --git a/docs/adr/composer-mcp-invocations.md b/docs/adr/composer-mcp-invocations.mdnew file mode 100644index 000000000..2f87b1fe8--- /dev/null+++ b/docs/adr/composer-mcp-invocations.md@@ -0,0 +1,59 @@+# Composer MCP Invocations++- Status: Accepted+- Date: 2026-10-04+- Related: #1377, ADR 0024, ADR 0219++## Context++Explicit MCP selection belongs in the composer alongside Skills and plugin+commands. Tool discovery, argument selection, execution and approval remain+owned by the runtime and Host.++## Decision++Catalog discovery refreshes enabled user MCP records and uses the runtime's+existing bounded connection path, including before the first session after+restart. The composer exposes ready servers with tools in the current project. Server entries use+`/mcp:<URI-encoded-server-id>`; individual tool entries append+`:<URI-encoded-tool-name>`. Entries carry `kind: "mcp"`, `mcpServerId`, and an+optional `mcpToolName` containing the full host tool name. Existing command+aliases retain precedence. Selecting an entry inserts text without connecting+a server or executing a tool. Connection addresses, credentials and tool+schemas stay out of the composer catalog.++Main revalidates the selection against the session project's current catalog+on prompt or steering submission. It preserves the typed text in `command`,+adds a short model-facing selection instruction, and forwards `mcpServerIds`+and optional `mcpToolNames` through internal RPC. The runtime matches the+catalog's authoritative server IDs. Server selection activates all+mode-allowed tools from that server; tool selection activates only the exact+requested tools after validating ownership and mode availability. Neither+selection removes tools already active in the session.++Selection and ToolSearch share deferred activation, but selection does not+use ToolSearch's result-count limit. Steering activates tools only when its+queued user message is consumed and synchronizes declarations before the+provider request. Existing session restoration and execution permissions+remain in effect. Missing selection fields preserve on-demand discovery.++Unavailable selections fail explicitly rather than becoming ordinary prompt+text or broadening to a whole-server selection. A cached menu entry cannot+bypass submission validation. Native Pi sessions cannot use Desktop-managed+MCP selections.++## Consequences and alternatives++The optional catalog and internal RPC fields reuse the existing execution+path without database, Plugin SDK or Host protocol changes. Server IDs are+validated at the sidecar boundary and do not become tool-schema fields.++Selection makes tools available but does not force execution. The model+chooses arguments and calls, including whether to ask for clarification when+the command has no task text. A renderer-driven tool call would duplicate+runtime argument selection and permission handling.++## Unreleased user-facing change++Select a connected MCP server or one of its tools from the composer's `/`+menu and send a task. Existing tool approvals still apply.diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.mdindex 867266ec2..9fabfe19e 100644--- a/docs/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/spec/03-runtime/03-tools-and-permissions.md@@ -75,6 +75,19 @@ workspace/scratch containment, timeout, and audit rules do not change when atool is loaded. `ToolSearch` itself never executes a workspace operation andnever bypasses host-core policy.+An explicit composer MCP selection carries exact server IDs to the runtime.+The current host-supplied catalog associates each MCP tool with its server ID;+selection activates all mode-allowed tools for that server before the request,+without a ToolSearch call or its result-count limit. An optional `mcpToolNames`+selection narrows activation to those exact catalog names, each owned by a+selected server. Unknown, differently owned or mode-denied requested tools fail;+there is no fallback to whole-server activation. Steering activates only+when the queued user message is consumed, before the next provider dispatch.+Unknown servers and selections with no mode-allowed tools fail explicitly.+Activation preserves other tools, follows existing session restoration, and+never bypasses execution permissions. Missing selection fields retain normal+on-demand discovery. See `docs/adr/composer-mcp-invocations.md`.+## 3. Common Tool ConstraintsEvery non-interactive execution tool must have:diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex ac9907d86..6efda309a 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -3296,9 +3296,32 @@ Anatomy:whitespace yet): the placeholder teaches `Type / for commands · @ for files`(localized in zh-CN), and groups appear in order — prompt templates (name +`argument-hint` ghost text + description, project source before- user-global), app commands (builtin slash aliases), plugin commands.+ user-global), app commands (builtin slash aliases), plugin commands,+ extension commands, connected MCP servers, then Skills.The core aliases remain `/new`, `/compact`, `/agent-mode`, `/plan-mode`, and`/goal-mode`; matched characters highlight in accent.+- Catalog discovery refreshes MCP records and initializes enabled in-scope+ servers through the existing runtime connection path, including on cold start.+ Failed handshakes retain the runtime's explicit retry policy.+- The MCP group exposes enabled user-configured servers that are ready, have+ tools, and are active in the current project. Rows contain a stable+ `/mcp:<URI-encoded-server-id>` and the display label. Individual tools also+ appear as `/mcp:<URI-encoded-server-id>:<URI-encoded-tool-name>`, searchable+ and selectable with the same keyboard and pointer interactions. Tool selections+ activate only that exact tool; server selections retain whole-server behavior.+ No connection addresses, credentials, or tool schemas enter the command+ catalog. Selecting a row only+ inserts text. At send (including steering), main revalidates availability+ against the session project and passes exact server IDs to the runtime.+ The runtime activates that server's currently available tools before the+ provider request, reusing deferred activation without ToolSearch's result+ limit. A short instruction identifies the selected server. Other active+ tools and all permission checks remain in place. The original draft remains+ the transcript's `command`. Activation does not force tool execution or+ guarantee model compliance. An unavailable selection fails with localized+ feedback before opening a turn or replacing history. Native Pi sessions do+ not support Desktop-managed MCP selections. Existing command aliases win+ collisions. See `docs/adr/composer-mcp-invocations.md`.- A whitespace-delimited `/` later in the draft offers active Skills only.Completion replaces only the token under the cursor, so several Skills andordinary text can coexist in one prompt.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 7b3b2ed55..81a6a9144 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -2322,6 +2322,41 @@ identify the platform validation still needed.fixtures; no provider required). Full provider/session scenario Draft;branch runs do not replace post-integration E2E+##### Connected MCP slash selection (#1377)++- Restart Desktop with an enabled saved MCP server. Without visiting MCP+ settings or sending an ordinary message first, open the slash menu and+ submit a server/tool command. Discovery initializes the connection and the+ first prompt reaches the selected tool; opening the menu executes no tool.++- With a ready user MCP server, type `/` or search its display label. The MCP+ group appears before Skills. Enter and mouse selection insert the encoded+ server command without sending or invoking a tool.+- Send a task after the command. The runtime receives the server-specific+ instruction, exact server IDs, and task; persisted command metadata retains+ the typed text. All six fixture tools are activated without ToolSearch; a+ similarly named server remains unselected. Steering activates only for the+ request consuming the queued message. Plan and Host permissions still apply.+- Disconnect, disable, or remove project access between menu selection and+ send. Sending fails before a new turn or history replacement. Steering uses+ the same validation; native Pi cannot silently accept Desktop MCP commands.+- Coverage: `apps/desktop/test/composer-mcp.test.mjs` exercises the real command+ service and prompt/steering IPC with external runtime boundaries stubbed.+ `node scripts/e2e-composer-ime-stack.mjs` exercises the real React editor,+ completion controller and keyboard/mouse acceptance in isolated Electron.+ `node scripts/e2e-composer-mcp.mjs` uses production sidecar transport, an+ isolated Rust Host, a real stdio MCP child and a local SSE model fixture.+ It verifies the sixth tool executes without ToolSearch and its server-only+ nonce reaches the next model request. These fixtures do not prove a real+ provider's tool choice or remote MCP health.+- Select `/mcp:<server>:<tool>` by keyboard and pointer, then submit or steer.+ Main preserves the original command and forwards exact server/tool IDs.+ Only the requested tool activates; similarly named tools, another server's+ tools and removed tools cannot broaden the selection. Whole-server rows+ remain selectable and existing active tools retain their availability.+- Run `MCP_SELECTION_TOOL=1 node scripts/e2e-composer-mcp.mjs` for the+ individual-tool variant of the deterministic sidecar/Host/MCP scenario.+#### E2E-089: Composer model menu opens upward and switches model- **Preconditions**: Chat route active; provider configured with two reasoningdiff --git a/packages/agent-runtime/src/fixed-tool-runtime.test.ts b/packages/agent-runtime/src/fixed-tool-runtime.test.tsindex 2c86736ce..c160f2697 100644--- a/packages/agent-runtime/src/fixed-tool-runtime.test.ts+++ b/packages/agent-runtime/src/fixed-tool-runtime.test.ts@@ -1,3 +1,4 @@+import { parseMcpServerIds, parseMcpToolNames } from "./mcp-tool-selection.js";import { randomUUID } from "node:crypto";import { createServer } from "node:http";import { afterEach, describe, expect, it, vi } from "vitest";@@ -19,7 +20,7 @@ const pluginTools: PluginToolDef[] = ["plugin_alpha", "plugin_beta"].map((name)}));type Payload = { tools: { function: { name: string } }[]; messages: { role: string; content?: unknown }[] };type Call = { name: string; args?: Record<string, unknown> };-async function wireFixture(calls: Call[]) {+async function wireFixture(calls: Call[], beforeReply?: () => Promise<void>) {const requests: Payload[] = [];const fetch = globalThis.fetch;const server = createServer(async (req, res) => {@@ -27,6 +28,7 @@ async function wireFixture(calls: Call[]) {for await (const chunk of req) chunks.push(Buffer.from(chunk));requests.push(JSON.parse(Buffer.concat(chunks).toString()));const call = calls.shift();+ await beforeReply?.();const delta = call ? { role: "assistant", tool_calls: [{ index: 0, id: randomUUID(),type: "function", function: { name: call.name, arguments: JSON.stringify(call.args ?? {}) } }] }: { role: "assistant", content: "Done." };@@ -42,12 +44,12 @@ async function wireFixture(calls: Call[]) {await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));} };}-function runtimeFixture(history: UiMessage[] = [], tools = pluginTools, provider = flashProvider(), denied = false) {+function runtimeFixture(history: UiMessage[] = [], tools = pluginTools, provider = flashProvider(), denied = false, mode: "agent" | "plan" = "agent") {const rows = structuredClone(history);const executed: string[] = [];const errors: unknown[] = [];const runtime = new DesktopAgentRuntime({- sessionId: "fixed-tools", mode: "agent", provider, thinkingLevel: "off", history: rows, pluginTools: tools,+ sessionId: "fixed-tools", mode, provider, thinkingLevel: "off", history: rows, pluginTools: tools,commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },host: { call: async <T>(method: string, params?: unknown): Promise<T> => {if (method === "session.appendMessage") rows.push((params as { message: UiMessage }).message);@@ -214,3 +216,176 @@ describe("fixed Flash declarations through runtime and HTTP/SSE", () => {} finally { await f.runtime.dispose(); await wire.close(); }});});++describe("explicit MCP selection", () => {+ const selectedTools: PluginToolDef[] = Array.from({ length: 6 }, (_, i) => ({+ name: `mcp_chosen_probe_${i}`, mcpServerId: "chosen",+ description: "Read-only MCP probe", parameters: { type: "object", properties: {}, required: [] }, risk: "low",+ }));+ const otherTool: PluginToolDef = {+ ...selectedTools[0], name: "mcp_chosen_similar_probe", mcpServerId: "chosen-similar",+ };+ it.each([false, true])("activates every selected-server tool before the first request (fixed=%s)", async (fixed) => {+ const wire = await wireFixture([{ name: selectedTools[5].name }, { name: otherTool.name }]);+ const provider = fixed ? flashProvider() : { ...flashProvider(), baseUrl: "https://relay.invalid/v1" };+ const f = runtimeFixture([], [...selectedTools, otherTool], provider);+ try {+ await f.runtime.prompt({ text: "Read the selected probe", mcpServerIds: ["chosen"] }, "selected-user");+ expect(f.errors).toEqual([]);+ expect(f.executed).toEqual([selectedTools[5].name]);+ const names = wire.requests[0].tools.map(t => t.function.name);+ for (const tool of selectedTools) expect(names).toContain(tool.name);+ if (!fixed) expect(names).not.toContain(otherTool.name);+ expect(f.rows.some(row => row.toolName === "ToolSearch")).toBe(false);+ expect(f.rows.find(row => row.toolName === otherTool.name)).toMatchObject({ isError: true });+ wire.requests.length = 0;+ await f.runtime.prompt("Continue", "next-user");+ for (const tool of selectedTools) expect(wire.requests[0].tools.map(t => t.function.name)).toContain(tool.name);+ } finally { await f.runtime.dispose(); await wire.close(); }+ });++ it.each([false, true])("activates only the requested tool from the selected server (fixed=%s)", async (fixed) => {+ const wire = await wireFixture([{ name: selectedTools[5].name }, { name: selectedTools[0].name }]);+ const provider = fixed ? flashProvider() : { ...flashProvider(), baseUrl: "https://relay.invalid/v1" };+ const f = runtimeFixture([], [...selectedTools, otherTool], provider);+ try {+ await f.runtime.prompt({ text: "Read", mcpServerIds: ["chosen"], mcpToolNames: [selectedTools[5].name] });+ expect(f.executed).toEqual([selectedTools[5].name]);+ const names = wire.requests[0].tools.map(t => t.function.name);+ expect(names).toContain(selectedTools[5].name);+ if (!fixed) expect(names).not.toContain(selectedTools[0].name);+ expect(f.rows.find(row => row.toolName === selectedTools[0].name)).toMatchObject({ isError: true });+ } finally { await f.runtime.dispose(); await wire.close(); }+ });++ it.each(["missing", "mcp_chosen_similar_probe"])("rejects an unavailable or differently owned tool: %s", async (name) => {+ const wire = await wireFixture([]);+ const f = runtimeFixture([], [...selectedTools, otherTool]);+ try {+ await expect(f.runtime.prompt({ text: "Read", mcpServerIds: ["chosen"], mcpToolNames: [name] })).rejects.toMatchObject({ errorCode: "COMPOSER_MCP_UNAVAILABLE" });+ expect(wire.requests).toHaveLength(0);+ } finally { await f.runtime.dispose(); await wire.close(); }+ });++ it("does not activate an unknown server or send a provider request", async () => {+ const wire = await wireFixture([]);+ const f = runtimeFixture([], selectedTools);+ try {+ await expect(f.runtime.prompt({ text: "Read", mcpServerIds: ["missing"] })).rejects.toMatchObject({ errorCode: "COMPOSER_MCP_UNAVAILABLE" });+ expect(wire.requests).toHaveLength(0);+ expect(f.executed).toEqual([]);+ } finally { await f.runtime.dispose(); await wire.close(); }+ });++ it("selected tools still require Host permission", async () => {+ const wire = await wireFixture([{ name: selectedTools[0].name }]);+ const f = runtimeFixture([], selectedTools, flashProvider(), true);+ try {+ await f.runtime.prompt({ text: "Read", mcpServerIds: ["chosen"] });+ expect(f.rows.find(row => row.toolName === selectedTools[0].name)).toMatchObject({ isError: true });+ expect(JSON.stringify(wire.requests.at(-1)?.messages)).toContain("Permission denied");+ } finally { await f.runtime.dispose(); await wire.close(); }+ });++ it("cannot expose selected MCP tools in Plan mode", async () => {+ const wire = await wireFixture([]);+ const f = runtimeFixture([], selectedTools, flashProvider(), false, "plan");+ try {+ await expect(f.runtime.prompt({ text: "Read", mcpServerIds: ["chosen"] })).rejects.toMatchObject({ errorCode: "TOOL_DENIED" });+ expect(wire.requests).toHaveLength(0);+ } finally { await f.runtime.dispose(); await wire.close(); }+ });++ it.each([false, true])("restores explicitly activated tools after a runtime restart (fixed=%s)", async (fixed) => {+ const provider = { ...flashProvider(), ...(fixed ? {} : { baseUrl: "https://relay.invalid/v1" }) };+ const wire = await wireFixture([]);+ const f = runtimeFixture([], selectedTools, provider);+ let history: UiMessage[] = [];+ try {+ await f.runtime.prompt({ text: "Read", mcpServerIds: ["chosen"] });+ history = structuredClone(f.rows);+ } finally { await f.runtime.dispose(); await wire.close(); }+ const resumed = await wireFixture([{ name: selectedTools[5].name }]);+ const restored = runtimeFixture(history, selectedTools, provider);+ try {+ await restored.prompt("resumed-user");+ expect(restored.executed).toEqual([selectedTools[5].name]);+ } finally { await restored.runtime.dispose(); await resumed.close(); }+ });++ it.each([false, true])("does not activate steering cancelled before consumption (specific=%s)", async (specific) => {+ let arrived!: () => void;+ let release!: () => void;+ const ready = new Promise<void>(resolve => { arrived = resolve; });+ const gate = new Promise<void>(resolve => { release = resolve; });+ let first = true;+ const wire = await wireFixture([], async () => {+ if (!first) return;+ first = false; arrived(); await gate;+ });+ const f = runtimeFixture([], selectedTools, { ...flashProvider(), baseUrl: "https://relay.invalid/v1" });+ try {+ const running = f.runtime.prompt("Wait", "user", "turn-cancel");+ await ready;+ f.runtime.steer({ text: "Use selected MCP", mcpServerIds: ["chosen"], ...(specific ? { mcpToolNames: [selectedTools[5].name] } : {}) }, "turn-cancel", {+ id: "cancelled-steering", role: "user", content: "Use selected MCP", createdAt: new Date().toISOString(),+ });+ await f.runtime.abort();+ release();+ await running;+ await f.runtime.prompt("New request");+ expect(f.executed).toEqual([]);+ expect(wire.requests.at(-1)?.tools.map(t => t.function.name)).not.toContain(selectedTools[5].name);+ } finally { release(); await f.runtime.dispose(); await wire.close(); }+ });++ it.each([[false, false], [true, false], [false, true], [true, true]])("activates steering selections when the queued user message is consumed (fixed=%s, specific=%s)", async (fixed, specific) => {+ let arrived!: () => void;+ let release!: () => void;+ const ready = new Promise<void>(resolve => { arrived = resolve; });+ const gate = new Promise<void>(resolve => { release = resolve; });+ let first = true;+ const calls: Call[] = [];+ const wire = await wireFixture(calls, async () => {+ if (!first) return;+ first = false; arrived(); await gate;+ });+ const f = runtimeFixture([], selectedTools, { ...flashProvider(), ...(fixed ? {} : { baseUrl: "https://relay.invalid/v1" }) });+ try {+ const running = f.runtime.prompt("Wait for followup", "user", "turn-steer");+ await ready;+ f.runtime.steer({ text: "Use selected MCP", mcpServerIds: ["chosen"], ...(specific ? { mcpToolNames: [selectedTools[5].name] } : {}) }, "turn-steer", {+ id: "steering-user", role: "user", content: "Use selected MCP", createdAt: new Date().toISOString(),+ });+ if (!fixed) expect(wire.requests[0].tools.map(t => t.function.name)).not.toContain(selectedTools[5].name);+ expect(f.executed).toEqual([]);+ calls.push({ name: selectedTools[5].name }); release();+ await running;+ expect(f.errors).toEqual([]);+ expect(wire.requests[1].tools.map(t => t.function.name)).toContain(selectedTools[5].name);+ expect(f.executed).toEqual([selectedTools[5].name]);+ if (specific && !fixed) expect(wire.requests[1].tools.map(t => t.function.name)).not.toContain(selectedTools[0].name);+ } finally { release(); await f.runtime.dispose(); await wire.close(); }+ });++});++describe("MCP selection boundary", () => {+ it.each([null, "chosen", {}, [1], [""], [" "]])("rejects invalid selection %j", value => {+ expect(() => parseMcpServerIds(value)).toThrow("Invalid MCP server selection");+ });+ it("preserves legacy absence and deduplicates exact IDs", () => {+ expect(parseMcpServerIds(undefined)).toBeUndefined();+ expect(parseMcpServerIds(["chosen", "chosen", "chosen-other"])).toEqual(["chosen", "chosen-other"]);+ });+});++describe("MCP tool selection boundary", () => {+ it.each([null, "search", [], [""], [1], [{}]])("rejects malformed tool selections: %j", value => {+ expect(() => parseMcpToolNames(value)).toThrow("Invalid MCP tool selection");+ });+ it("preserves omitted selections and deduplicates exact names", () => {+ expect(parseMcpToolNames(undefined)).toBeUndefined();+ expect(parseMcpToolNames(["search", "search"])).toEqual(["search"]);+ });+});diff --git a/packages/agent-runtime/src/mcp-tool-selection.ts b/packages/agent-runtime/src/mcp-tool-selection.tsnew file mode 100644index 000000000..cb49c5d2d--- /dev/null+++ b/packages/agent-runtime/src/mcp-tool-selection.ts@@ -0,0 +1,48 @@+/** Host-resolved server identity survives the Main -> runtime tool catalog. */+type McpToolIdentity = { name: string; mcpServerId?: string };++export function parseMcpServerIds(value: unknown): string[] | undefined {+ if (value === undefined) return undefined;+ if (!Array.isArray(value) || value.some(id => typeof id !== "string" || !id.trim())) {+ throw Object.assign(new Error("Invalid MCP server selection"), { errorCode: "INVALID_ARGUMENT" });+ }+ return [...new Set(value as string[])];+}++export function parseMcpToolNames(value: unknown): string[] | undefined {+ if (value === undefined) return undefined;+ if (!Array.isArray(value) || value.length === 0 || value.some(name => typeof name !== "string" || !name.trim())) {+ throw Object.assign(new Error("Invalid MCP tool selection"), { errorCode: "INVALID_ARGUMENT" });+ }+ return [...new Set(value as string[])];+}++/** Resolve exact server IDs; never authorize tools by a name-prefix match. */+export function resolveMcpToolSelection(+ selection: unknown,+ tools: readonly McpToolIdentity[],+ available: (name: string) => boolean,+ toolSelection?: unknown,+): string[] {+ const selected = parseMcpServerIds(selection) ?? [];+ const requested = parseMcpToolNames(toolSelection);+ if (requested?.some(name => !tools.some(tool => tool.name === name && selected.includes(tool.mcpServerId ?? "")))) {+ throw Object.assign(new Error("Selected MCP tool unavailable"), { errorCode: "COMPOSER_MCP_UNAVAILABLE" });+ }+ const names = new Set<string>();+ for (const id of selected) {+ const owned = tools.filter(tool => tool.mcpServerId === id && (!requested || requested.includes(tool.name)));+ if (!owned.length) {+ throw Object.assign(new Error("Selected MCP server unavailable"), { errorCode: "COMPOSER_MCP_UNAVAILABLE" });+ }+ if (requested && owned.some(tool => !available(tool.name))) {+ throw Object.assign(new Error("Selected MCP tool is unavailable in this mode"), { errorCode: "TOOL_DENIED" });+ }+ const allowed = owned.filter(tool => available(tool.name));+ if (!allowed.length) {+ throw Object.assign(new Error("Selected MCP tools are unavailable in this mode"), { errorCode: "TOOL_DENIED" });+ }+ for (const tool of allowed) names.add(tool.name);+ }+ return [...names];+}diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex debb767e0..98e7aa95e 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -1,3 +1,4 @@+import { resolveMcpToolSelection } from "./mcp-tool-selection.js";import { TOOL_ACTIVATION_SECTION, toolDeclarationPolicy, toolActivationSection, restoredToolActivation, syncToolActivation, type ToolDeclarationPolicy } from "./fixed-tool-declarations.js";import { orderSystemRows, SystemTranscriptJournal } from "./system-transcript-journal.js";import { planWorkspaceRequiredResult } from "./plan-workspace-error.js";@@ -32,6 +33,8 @@ import {import {isContextOverflow,getCurrentTools,+ getToolStateChanges,+ toToolDeclaration,Type,type Api,type AssistantMessage,@@ -291,6 +294,9 @@ export type RuntimePromptAttachment = Omit<AgentPromptAttachment, "kind"> & {export type RuntimePrompt = {text: string;+ /** Explicit user selection, resolved against the host-provided tool catalog. */+ mcpServerIds?: string[];+ mcpToolNames?: string[];sessionMessage?: SessionMessageOrigin;attachments?: RuntimePromptAttachment[];};@@ -954,6 +960,8 @@ function contextFallbackReminder(): string {export type PluginToolDef = {+ /** Present only on tools resolved from a user MCP server by Electron main. */+ mcpServerId?: string;/** Full exposed name (`plugin_<pluginIdSafe>_<toolName>`, D015). */name: string;description?: string;@@ -1882,7 +1890,7 @@ export class DesktopAgentRuntime {private acceptingSteering = false;private steeringContinuation = false;private steeringWaitAbort?: AbortController;- private pendingSteering = new Map<AgentMessage, string>();+ private pendingSteering = new Map<AgentMessage, { id: string; toolNames: string[] }>();private pendingOverflow = false;private overflowRecoveryAttempted = false;private overflowRecoveryInProgress = false;@@ -2149,6 +2157,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theconvertToLlm(this.dropDuplicateToolCalls(messages)), this.reasoningReplayIdentity(),);},+ prepareRequest: ({ context }) => this.prepareToolDeclarations(context),prepareNextTurnWithContext: (context, signal) =>this.prepareNextTurn(context, signal),afterToolCall: async (context) => this.afterToolCall(context),@@ -2277,6 +2286,27 @@ Do not invent objections or turn speculative risks into blockers. Stop when the);}+ /** Steering is consumed after next-turn preparation; sync before dispatch. */+ private prepareToolDeclarations(context: AgentContext): AgentLoopTurnUpdate {+ const tools = this.declaredTools();+ let messages = context.messages;+ const changes = getToolStateChanges(getCurrentTools(messages), tools.map(toToolDeclaration));+ if (changes.toolsAdded.length || changes.toolsRemoved.length) {+ messages = [...messages, {+ role: "system", content: "", ...changes, timestamp: Date.now(),+ }];+ }+ if (this.trackToolActivation && this.declarationPolicy) {+ messages = syncToolActivation(messages, toolActivationSection(+ this.declarationPolicy.key, this.activeDeferredToolNames,+ ));+ }+ for (const message of messages.slice(context.messages.length)) {+ this.agent.state.messages.push(message);+ }+ return { context: { ...context, messages, tools } };+ }+private setAgentTools(tools: AgentTool[]): void {this.agent.state.tools = this.declarationPolicy?.tools ?? tools;if (this.trackToolActivation && this.declarationPolicy) {@@ -3940,12 +3970,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the? params.query.trim(): "";const matches = this.findDeferredTools(query);- const activated = matches.filter(- (name) => !this.activeDeferredToolNames.has(name),- );- for (const name of activated) {- this.activeDeferredToolNames.add(name);- }+ const activated = this.activateDeferredTools(matches);const available = [...this.deferredToolNames];const availablePreview = available.slice(0, MAX_TOOL_SEARCH_RESULT_NAMES);const remaining = available.length - availablePreview.length;@@ -5452,6 +5477,22 @@ Do not invent objections or turn speculative risks into blockers. Stop when the};}+ private selectedMcpTools(input: string | RuntimePrompt): string[] {+ return resolveMcpToolSelection(+ typeof input === "string" ? undefined : input.mcpServerIds,+ this.pluginTools,+ name => this.toolCatalog.has(name) && this.isToolAllowedInMode(name),+ typeof input === "string" ? undefined : input.mcpToolNames,+ );+ }++ private activateDeferredTools(names: readonly string[]): string[] {+ const activated = names.filter(name => this.deferredToolNames.has(name)+ && !this.activeDeferredToolNames.has(name));+ for (const name of activated) this.activeDeferredToolNames.add(name);+ return activated;+ }+private findDeferredTools(query: string): string[] {const normalizedQuery = query.toLowerCase();if (!normalizedQuery) return [];@@ -7733,9 +7774,13 @@ Do not invent objections or turn speculative risks into blockers. Stop when the}case "message_end": {if (event.message.role === "user") {- const steeringId = this.pendingSteering.get(event.message);- const id = steeringId ?? this.pendingUserMessageId ?? randomUUID();- if (steeringId) {+ const steering = this.pendingSteering.get(event.message);+ const id = steering?.id ?? this.pendingUserMessageId ?? randomUUID();+ if (steering) {+ if (steering.toolNames.length) {+ this.activateDeferredTools(steering.toolNames);+ this.setAgentTools(this.activeTools());+ }this.pendingSteering.delete(event.message);// User input is now part of the model context: whatever the model// says next answers the user, not a completion notice, so the@@ -8419,6 +8464,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the): Promise<{ turnId: string }> {if (this.disposed) throw new Error("runtime disposed");this.assertNotRunning();+ const selectedTools = this.selectedMcpTools(input);const modelInput = typeof input !== "string" && input.sessionMessage? { ...input, text: formatSessionMessage(input.text, input.sessionMessage), sessionMessage: undefined }: input;@@ -8432,6 +8478,10 @@ Do not invent objections or turn speculative risks into blockers. Stop when the// Capabilities and path-scoped instruction claims belong to one prompt.this.subagentOverrideProviders = {};this.resetDeferredToolsForPrompt();+ if (selectedTools.length) {+ this.activateDeferredTools(selectedTools);+ this.setAgentTools(this.activeTools());+ }this.refreshResumablePrompt();this.pathInstructionClaims.clear();this.pendingUserMessageId = userMessageId;@@ -8629,7 +8679,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when thesteer(input: RuntimePrompt, expectedTurnId: string, message: UiMessage): { accepted: boolean; turnId: string } {this.steeringContext(expectedTurnId);const queued: AgentMessage = { role: "user", content: promptContent(input), timestamp: Date.now() };- this.pendingSteering.set(queued, message.id);+ const toolNames = this.selectedMcpTools(input);+ this.pendingSteering.set(queued, { id: message.id, toolNames });this.agent.steer(queued);this.steeringWaitAbort?.abort();// Main persists this echo through the same outbox as assistant messages.@@ -8644,9 +8695,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when theprivate retainPendingSteering(): void {this.agent.clearSteeringQueue();- for (const [message, id] of this.pendingSteering) {+ for (const [message, pending] of this.pendingSteering) {if (!this.agent.state.messages.includes(message)) this.setAgentMessages([...this.agent.state.messages, message]);- this.appendLiveEntry(id, message);+ this.appendLiveEntry(pending.id, message);}this.pendingSteering.clear();diff --git a/packages/agent-runtime/src/sidecar.ts b/packages/agent-runtime/src/sidecar.tsindex 7bc2126dc..cb40b97fc 100644--- a/packages/agent-runtime/src/sidecar.ts+++ b/packages/agent-runtime/src/sidecar.ts@@ -1,3 +1,4 @@+import { parseMcpServerIds, parseMcpToolNames } from "./mcp-tool-selection.js";/*** Node pi agent sidecar.* Protocol: NDJSON JSON-RPC on stdio with Electron main.@@ -444,6 +445,8 @@ async function handle(method: string, params: any): Promise<unknown> {}const prompt: RuntimePrompt = {text: content,+ mcpServerIds: parseMcpServerIds(params.mcpServerIds),+ mcpToolNames: parseMcpToolNames(params.mcpToolNames),attachments,...(params.sessionMessage ? { sessionMessage: params.sessionMessage as SessionMessageOrigin } : {}),};@@ -472,7 +475,7 @@ async function handle(method: string, params: any): Promise<unknown> {const expectedTurnId = String(params.expectedTurnId ?? "");if (method === "agent.steeringContext") return runtime.steeringContext(expectedTurnId);return runtime.steer(- { text: String(params.content ?? ""), attachments: params.attachments },+ { text: String(params.content ?? ""), attachments: params.attachments, mcpServerIds: parseMcpServerIds(params.mcpServerIds), mcpToolNames: parseMcpToolNames(params.mcpToolNames) },expectedTurnId,params.message,);diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 4a70b14f5..4a41a6e78 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -264,6 +264,7 @@ export const de = {"slashGroupApp": "App-Befehle","slashGroupPlugins": "Plugin-Befehle","slashGroupExtensions": "Erweiterungsbefehle",+ slashGroupMcp: "MCP","slashGroupSkills": "Fähigkeiten","slashEmpty": "Keine übereinstimmenden Befehle","slashCommandSourceUnavailable": "Befehlsliste nicht verfügbar, es wurde nichts gesendet. Bitte erneut versuchen.",@@ -2581,6 +2582,7 @@ sklm: {phase: { idle: "Aus", preparing: "Wird vorbereitet", "acquiring-mic": "Warte auf Mikrofon", negotiating: "Aushandlung", connecting: "Verbindung wird hergestellt…", connected: "Verbunden", reconnecting: "Verbindung wird wiederhergestellt", closing: "Wird beendet…", ended: "Beendet", failed: "Gestoppt" },},"errors": {+ COMPOSER_MCP_UNAVAILABLE: "Der ausgewählte MCP-Server ist getrennt oder in diesem Projekt nicht verfügbar. Verbinde ihn erneut und wähle ihn noch einmal aus.","HOST_UNAVAILABLE": "Der lokale Dienst ist nicht verfügbar","MODEL_NOT_CONFIGURED": "Dieses Modell ist nicht eingerichtet oder der KI-Anbieter bietet es nicht an.","TOOL_DENIED": "Die Berechtigung für diese Aktion wurde verweigert.",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex fd8cafe39..ca73aef53 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -271,6 +271,7 @@ export const en = {slashGroupApp: "App commands",slashGroupPlugins: "Plugin commands",slashGroupExtensions: "Extension commands",+ slashGroupMcp: "MCP",slashGroupSkills: "Skills",slashEmpty: "No matching commands",slashCommandSourceUnavailable: "Command list unavailable, so nothing was sent. Try again.",@@ -2719,6 +2720,7 @@ importConfirm: "Imported extensions run inside the agent process with the same a},},errors: {+ COMPOSER_MCP_UNAVAILABLE: "The selected MCP server is disconnected or unavailable in this project. Reconnect it and select it again.",HOST_UNAVAILABLE: "The local service is unavailable",MODEL_NOT_CONFIGURED: "This model isn't set up, or the AI provider doesn't offer it.",TOOL_DENIED: "Permission was denied for this action",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex a04226cdb..b91c352a4 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -264,6 +264,7 @@ export const es = {"slashGroupApp": "Comandos de aplicaciones","slashGroupPlugins": "Comandos de complemento","slashGroupExtensions": "Comandos de extensión",+ slashGroupMcp: "MCP","slashGroupSkills": "Habilidades","slashEmpty": "No hay comandos coincidentes","slashCommandSourceUnavailable": "La lista de comandos no está disponible, así que no se envió nada. Inténtalo de nuevo.",@@ -2579,6 +2580,7 @@ sklm: {phase: { idle: "Desactivado", preparing: "Preparando", "acquiring-mic": "Esperando el micrófono", negotiating: "Negociando", connecting: "Conectando…", connected: "Conectado", reconnecting: "Reconectando", closing: "Finalizando…", ended: "Finalizado", failed: "Detenido" },},"errors": {+ COMPOSER_MCP_UNAVAILABLE: "El servidor MCP seleccionado está desconectado o no está disponible en este proyecto. Vuelve a conectarlo y seleccionarlo.","HOST_UNAVAILABLE": "El servicio local no está disponible","MODEL_NOT_CONFIGURED": "Este modelo no está configurado o el proveedor de IA no lo ofrece.","TOOL_DENIED": "Se denegó el permiso para esta acción",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex ae35a093a..e687e68fd 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -264,6 +264,7 @@ export const fr = {"slashGroupApp": "Commandes d'application","slashGroupPlugins": "Commandes du plug-in","slashGroupExtensions": "Commandes d'extension",+ slashGroupMcp: "MCP","slashGroupSkills": "Compétences","slashEmpty": "Aucune commande correspondante","slashCommandSourceUnavailable": "Liste des commandes indisponible, rien n'a été envoyé. Réessayez.",@@ -2579,6 +2580,7 @@ sklm: {phase: { idle: "Désactivée", preparing: "Préparation", "acquiring-mic": "En attente du microphone", negotiating: "Négociation", connecting: "Connexion…", connected: "Connectée", reconnecting: "Reconnexion", closing: "Arrêt…", ended: "Terminée", failed: "Arrêtée" },},"errors": {+ COMPOSER_MCP_UNAVAILABLE: "Le serveur MCP sélectionné est déconnecté ou indisponible dans ce projet. Reconnectez-le et sélectionnez-le à nouveau.","HOST_UNAVAILABLE": "Le service local n'est pas disponible","MODEL_NOT_CONFIGURED": "Ce modèle n'est pas configuré ou le fournisseur d'IA ne le propose pas.","TOOL_DENIED": "L'autorisation a été refusée pour cette action",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 2520593d2..75fbc3142 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -273,6 +273,7 @@ export const ko = {slashGroupApp: "앱 명령",slashGroupPlugins: "플러그인 명령",slashGroupExtensions: "확장 명령",+ slashGroupMcp: "MCP",slashGroupSkills: "스킬",slashEmpty: "일치하는 명령 없음",slashCommandSourceUnavailable: "명령 목록을 불러오지 못해 전송하지 않았습니다. 다시 시도하세요.",@@ -2615,6 +2616,7 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이phase: { idle: "꺼짐", preparing: "준비 중", "acquiring-mic": "마이크 대기 중", negotiating: "협상 중", connecting: "연결 중…", connected: "연결됨", reconnecting: "재연결 중", closing: "종료 중…", ended: "종료됨", failed: "중지됨" },},errors: {+ COMPOSER_MCP_UNAVAILABLE: "선택한 MCP 서버의 연결이 끊겼거나 현재 프로젝트에서 사용할 수 없습니다. 다시 연결하고 선택하세요.",HOST_UNAVAILABLE: "로컬 서비스를 사용할 수 없습니다",MODEL_NOT_CONFIGURED: "이 모델이 설정되지 않았거나 AI 프로바이더에서 제공하지 않습니다.",TOOL_DENIED: "이 작업에 대한 권한이 거부되었습니다",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex 09e8af6e9..ec70d97af 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -263,6 +263,7 @@ export const ptBR = {slashGroupApp: "Aplicativo",slashGroupPlugins: "Plugins",slashGroupExtensions: "Extensões",+ slashGroupMcp: "MCP",slashGroupSkills: "Habilidades",slashEmpty: "Nenhum comando correspondente",slashCommandSourceUnavailable: "A lista de comandos está indisponível; nada foi enviado. Tente novamente.",@@ -2535,6 +2536,7 @@ export const ptBR = {phase: { idle: "Desativada", preparing: "Preparando", "acquiring-mic": "Aguardando microfone", negotiating: "Negociando", connecting: "Conectando…", connected: "Conectado", reconnecting: "Reconectando", closing: "Encerrando…", ended: "Encerrada", failed: "Interrompida" },},errors: {+ COMPOSER_MCP_UNAVAILABLE: "O servidor MCP selecionado está desconectado ou indisponível neste projeto. Reconecte-o e selecione-o novamente.",HOST_UNAVAILABLE: "O serviço local está indisponível",MODEL_NOT_CONFIGURED: "Este modelo não está configurado ou o provedor de IA não o oferece.",TOOL_DENIED: "A permissão foi negada para esta ação",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex dc08727ed..19c4716e8 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -273,6 +273,7 @@ export const tr = {slashGroupApp: "Uygulama komutları",slashGroupPlugins: "Eklenti komutları",slashGroupExtensions: "Uzantı komutları",+ slashGroupMcp: "MCP",slashGroupSkills: "Beceriler",slashEmpty: "Eşleşen komut yok",slashCommandSourceUnavailable: "Komut listesi yüklenemedi, hiçbir şey gönderilmedi. Tekrar deneyin.",@@ -2605,6 +2606,7 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araçphase: { idle: "Kapalı", preparing: "Hazırlanıyor", "acquiring-mic": "Mikrofon bekleniyor", negotiating: "Anlaşılıyor", connecting: "Bağlanıyor…", connected: "Bağlandı", reconnecting: "Yeniden bağlanıyor", closing: "Sonlandırılıyor…", ended: "Sonlandı", failed: "Durduruldu" },},errors: {+ COMPOSER_MCP_UNAVAILABLE: "Seçilen MCP sunucusunun bağlantısı kesildi veya bu projede kullanılamıyor. Yeniden bağlanıp tekrar seçin.",HOST_UNAVAILABLE: "Yerel servis kullanılamıyor",MODEL_NOT_CONFIGURED: "Bu model kurulu değil veya AI servisi onu sunmuyor.",TOOL_DENIED: "Bu eylem için izin reddedildi",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex a094d6213..d99bf8868 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -266,6 +266,7 @@ export const zhCN = {slashGroupApp: "应用命令",slashGroupPlugins: "插件命令",slashGroupExtensions: "扩展命令",+ slashGroupMcp: "MCP",slashGroupSkills: "技能",slashEmpty: "没有匹配的指令",slashCommandSourceUnavailable: "指令列表不可用,消息未发送。请重试。",@@ -2644,6 +2645,7 @@ sklm: {phase: { idle: "关闭", preparing: "正在准备", "acquiring-mic": "等待麦克风", negotiating: "正在协商", connecting: "连接中…", connected: "已连接", reconnecting: "正在重连", closing: "正在结束…", ended: "已结束", failed: "已停止" },},errors: {+ COMPOSER_MCP_UNAVAILABLE: "所选 MCP 服务器已断开或在当前项目中不可用。请重新连接并选择。",HOST_UNAVAILABLE: "本地服务不可用",MODEL_NOT_CONFIGURED: "该模型尚未配置,或当前 AI 服务不提供此模型。",TOOL_DENIED: "此操作的权限已被拒绝",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex cb78a4cd6..0a9ed70c3 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -266,6 +266,7 @@ export const zhTW = {slashGroupApp: "應用命令",slashGroupPlugins: "外掛命令",slashGroupExtensions: "擴充命令",+ slashGroupMcp: "MCP",slashGroupSkills: "技能",slashEmpty: "沒有匹配的指令",slashCommandSourceUnavailable: "指令清單無法載入,訊息未傳送。請重試。",@@ -2594,6 +2595,7 @@ sklm: {phase: { idle: "關閉", preparing: "準備中", "acquiring-mic": "等待麥克風", negotiating: "協商中", connecting: "連線中…", connected: "已連線", reconnecting: "重新連線中", closing: "正在結束…", ended: "已結束", failed: "已停止" },},errors: {+ COMPOSER_MCP_UNAVAILABLE: "所選 MCP 伺服器已中斷連線或在目前專案中無法使用。請重新連線並選取。",HOST_UNAVAILABLE: "本地服務不可用",MODEL_NOT_CONFIGURED: "該模型尚未配置,或當前 AI 服務不提供此模型。",TOOL_DENIED: "此操作的許可權已被拒絕",diff --git a/packages/shared/src/types/composer.ts b/packages/shared/src/types/composer.tsindex b0811ef99..ad83754e1 100644--- a/packages/shared/src/types/composer.ts+++ b/packages/shared/src/types/composer.ts@@ -14,7 +14,7 @@ export type CommandItem = {export type ComposerCommand = {/** Slash name typed after "/"; unique across the merged list. */name: string;- kind: "template" | "builtin" | "plugin" | "extension" | "skill";+ kind: "template" | "builtin" | "plugin" | "extension" | "skill" | "mcp";/** Display title (templates use their name). */title: string;description?: string;@@ -26,6 +26,10 @@ export type ComposerCommand = {id?: string;/** Skill id passed to the model's Skill tool. */skillId?: string;+ /** Active user MCP server selected for this prompt. */+ mcpServerId?: string;+ /** Exact host tool name, absent for a whole-server selection. */+ mcpToolName?: string;};/** One clipboard file transferred from the renderer to the composer bridge. */diff --git a/scripts/e2e-composer-mcp.mjs b/scripts/e2e-composer-mcp.mjsnew file mode 100644index 000000000..f9df3b73c--- /dev/null+++ b/scripts/e2e-composer-mcp.mjs@@ -0,0 +1,174 @@+#!/usr/bin/env node+/** Explicit composer selection through a real stdio MCP child, sidecar and Host.+ * The model endpoint is a deterministic local SSE fixture.+ * Message persistence is harness-owned; Electron's UI/outbox is not exercised.+ */+import { register } from "node:module";+register(new URL("../apps/desktop/test/helpers/ts-import-hooks.mjs", import.meta.url));+const { UserMcpRuntime } = await import("../apps/desktop/electron/main/user-mcp.ts");+const { McpServerClient } = await import("../apps/desktop/electron/main/plugin-mcp.ts");+const { createComposerCommandService } = await import("../apps/desktop/electron/main/ipc/composer-ipc.ts");+const { expandMcpInvocation } = await import("../apps/desktop/electron/main/composer-mcp.ts");+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { createServer } from "node:http";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { AgentSidecar } from "../packages/host-runtime/dist/agent-sidecar.js";+import { DEEPSEEK_MODELS } from "../packages/agent-runtime/node_modules/@earendil-works/pi-ai/dist/providers/deepseek.models.js";+import { modelConfigFromPi } from "../packages/agent-runtime/dist/model-capabilities.js";+import { PROTOCOL_VERSION } from "../packages/shared/dist/protocol.js";+import { withScenario } from "./e2e/fixture.mjs";+import { resolveHostBinary } from "./e2e/host.mjs";+import { createSession } from "./e2e/session.mjs";++const root = await mkdtemp(join(tmpdir(), "pi-composer-mcp-e2e-"));+const requests = [];+const responses = [];+const server = createServer(async (req, res) => {+ let body = "";+ for await (const chunk of req) body += chunk;+ requests.push(JSON.parse(body));+ const tool = responses.shift();+ const delta = tool ? { role: "assistant", tool_calls: [{ index: 0, id: randomUUID(), type: "function",+ function: { name: tool.name, arguments: JSON.stringify(tool.args) } }] }+ : { role: "assistant", content: "The fixture completed." };+ res.writeHead(200, { "content-type": "text/event-stream" });+ for (const [value, finish] of [[delta, null], [{}, tool ? "tool_calls" : "stop"]]) {+ res.write(`data: ${JSON.stringify({ id: "fixture", model: "fixture", choices: [{ index: 0, delta: value, finish_reason: finish }] })}\n\n`);+ }+ res.end("data: [DONE]\n\n");+});+await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+const baseUrl = `http://127.0.0.1:${server.address().port}/v1`;+const model = Object.values(DEEPSEEK_MODELS).find((model) => model.id === "deepseek-flash");+const provider = { id: "fixture", name: "Flash fixture", modelId: model.id, baseUrl: model.baseUrl,+ modelConfig: modelConfigFromPi(model), apiKey: "fixture", authKind: "api_key", supportsReasoning: false, supportedThinkingLevels: ["off"] };+const fetchHook = join(root, "fixture-fetch.mjs");+await writeFile(fetchHook, `const fetch = globalThis.fetch; globalThis.fetch = (url, init) => {+ if (String(url) !== "https://api.deepseek.com/chat/completions") throw new Error("Unexpected fixture endpoint");+ return fetch(${JSON.stringify(baseUrl)}, init);+};`);+const nonce = randomUUID();+const mcpFile = join(root, "mcp.mjs");+await writeFile(mcpFile, `+import { createInterface } from "node:readline";+const tools = Array.from({length:6}, (_,i) => ({name:"probe_"+i, description:i===5?"Read the validation nonce":"Read marker "+i,inputSchema:{type:"object",properties:{},required:[]}}));+createInterface({input:process.stdin}).on("line", line=>{+ const msg=JSON.parse(line); if(msg.id===undefined)return;+ let result;+ if(msg.method==="initialize")result={protocolVersion:msg.params.protocolVersion,capabilities:{tools:{}}};+ if(msg.method==="tools/list")result={tools};+ if(msg.method==="tools/call")result={content:[{type:"text",text:${JSON.stringify(nonce)}}]};+ process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:msg.id,result})+"\\n");+});`);+const mcp = new UserMcpRuntime({ createClient: config => new McpServerClient(config) });+mcp.setRecords([{id:"chosen",label:"Validation MCP",transport:"stdio",command:process.execPath,args:[mcpFile],env:{},enabled:true,scope:{mode:"global",projects:[]}}]);+const service = createComposerCommandService({+ plugins:{listLoaded:()=>[],getSkills:()=>[],getCommands:()=>[]},+ agentExtensions:{allCommands:()=>[]},activeUserSkills:async()=>[],+ pluginActiveInProject:()=>true,loadComposerTemplatesCached:async()=>[],userMcp:mcp,+});+let pluginTools;+try {+ await withScenario("E2E-composer-mcp", async ({ host, workspace }) => {+ const descriptors = await mcp.toolsForProject(workspace);+ pluginTools = descriptors.map(tool=>({name:tool.fullName,mcpServerId:tool.serverId,description:tool.description,parameters:tool.schema,risk:"low"}));+ const commands = await service.buildComposerCommands(workspace);+ const specific = process.env.MCP_SELECTION_TOOL === "1";+ const expansion = expandMcpInvocation(`${specific ? "/mcp:chosen:probe_5" : "/mcp:chosen"} Read the validation nonce using probe_5.`, commands);+ assert.deepEqual(expansion.mcpToolNames, specific ? ["mcp_chosen_probe_5"] : undefined);+ assert.deepEqual(expansion.mcpServerIds,["chosen"]);+ const session = await createSession(host, workspace, "Composer MCP fixture");+ let writes = Promise.resolve();+ let writeError;+ let stderr = "";+ const turns = new Map();+ const executedTools = [];+ const toolRows = new Map();+ const persist = (message, turnId) => {+ writes = writes.then(() => host.call("session.appendMessage", { sessionId: session.id, turnId, message }))+ .catch((error) => { writeError ??= error; });+ };+ const startSidecar = () => {+ const sidecar = new AgentSidecar({+ launch: { command: process.execPath,+ args: [fileURLToPath(new URL("../packages/agent-runtime/dist/sidecar.js", import.meta.url))],+ cwd: workspace,+ env: { ...process.env, NODE_OPTIONS: `--import=${fetchHook}`, PI_DESKTOP_PLAN_UI_PROBE: "1", PI_DESKTOP_COMPACTION_STRATEGY: "fresh_window" },+ },+ onStderr: (chunk) => { stderr += chunk; },+ });+ sidecar.setHost({ call: host.call.bind(host), onNotification: () => () => {}, onExit: () => () => {} });+ for (const { name } of pluginTools) sidecar.setLocalTool(name, async () => {+ executedTools.push(name);+ return { ok: true, content: JSON.stringify(await mcp.callTool(name, {}, workspace, session.id)) };+ });+ sidecar.onNotification((method, envelope) => {+ if (method !== "agent.event") return;+ const { event, turnId } = envelope;+ const turn = turns.get(turnId);+ if (event.type === "error") turn?.errors.push(event.error);+ if (event.type === "message_end") persist(event.message, turnId);+ if (event.type === "tool_start") toolRows.set(event.toolCallId, {+ id: event.toolCallId, role: "tool", content: "", toolCallId: event.toolCallId,+ toolName: event.toolName, toolArgs: event.args, createdAt: new Date().toISOString(),+ });+ if (event.type === "tool_end") {+ turn?.toolResults.push(event);+ persist({ ...toolRows.get(event.toolCallId), toolResult: event.result, isError: event.isError,+ toolStatus: event.isError ? "error" : "success" }, turnId);+ }+ if (event.type === "agent_end") turn?.resolve();+ });+ return sidecar;+ };+ const sidecar = startSidecar();+ const params = () => ({ sessionId: session.id, mode: "agent", provider, thinkingLevel: "off", pluginTools,+ projectPath: workspace,+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },+ });+ const prompt = async (id, expectedErrors = 0) => {+ const { turnId } = await host.call("session.beginTurn", { sessionId: session.id });+ await host.call("session.appendMessage", { sessionId: session.id, turnId,+ message: { id, role: "user", content: expansion.expanded, command: expansion.command, createdAt: new Date().toISOString() } });+ let timer;+ const turn = { errors: [], toolResults: [] };+ const ended = new Promise((resolve, reject) => {+ turn.resolve = resolve;+ timer = setTimeout(() => reject(new Error(`Turn timed out: ${JSON.stringify(turn.errors)}\n${stderr}`)), 20_000);+ });+ turns.set(turnId, turn);+ try {+ await sidecar.call("agent.prompt", { ...params(), turnId, userMessageId: id, content: expansion.expanded, mcpServerIds: expansion.mcpServerIds, mcpToolNames: expansion.mcpToolNames });+ await ended;+ await writes;+ if (writeError) throw writeError;+ assert.deepEqual(turn.errors, [], JSON.stringify(turn.errors));+ assert.equal(turn.toolResults.filter((event) => event.isError).length, expectedErrors, JSON.stringify(turn.toolResults));+ await host.call("session.endTurn", { turnId, status: "completed", createNotification: false });+ return turn;+ } finally { clearTimeout(timer); turns.delete(turnId); }+ };+ const detail = async () => (await host.call("session.get", { id: session.id })).session;+ try {+ responses.push({name:"mcp_chosen_probe_5",args:{}});+ const result = await prompt("mcp-user");+ assert.deepEqual(executedTools,["mcp_chosen_probe_5"]);+ assert.equal(result.toolResults.length,1);+ assert(JSON.stringify(result.toolResults[0].result).includes(nonce));+ assert.equal(requests.length,2);+ assert(requests[1].messages.some(message => message.role === "tool" && JSON.stringify(message).includes(nonce)));+ assert.equal((await detail()).messages.find(row=>row.id==="mcp-user").command,expansion.command);+ console.log("PASS: composer catalog → exact server selection → production sidecar → Host permission gate → real stdio MCP tools/call → provider follow-up");+ console.log("PASS: sixth selected tool executes without ToolSearch; server-only nonce reaches the model; original slash command persists");+ } finally { await sidecar.dispose(); await writes; }+ }, resolveHostBinary(), root, PROTOCOL_VERSION);+} finally {+ await mcp.disposeAll();+ server.closeAllConnections();+ await new Promise((resolve) => server.close(resolve));+ await rm(root, { recursive: true, force: true });+}diff --git a/scripts/e2e/composer-ime-stack.tsx b/scripts/e2e/composer-ime-stack.tsxindex def2371ea..64b67f4bb 100644--- a/scripts/e2e/composer-ime-stack.tsx+++ b/scripts/e2e/composer-ime-stack.tsx@@ -29,6 +29,8 @@ api.composerCommands = async () => ({commands: [{ name: "review", title: "review", kind: "skill" },{ name: "rewrite", title: "rewrite", kind: "skill" },+ { name: "mcp:docs", title: "Documentation", kind: "mcp", mcpServerId: "docs" },+ { name: "mcp:docs:search", title: "Documentation", kind: "mcp", mcpServerId: "docs", mcpToolName: "mcp_docs_search" },],});@@ -61,9 +63,9 @@ function Fixture() {cursor: draft.cursor,composing: draft.composing,enabled: true,- referenceSessionId: null,+ referenceSessionId: "s1",fileReferencesRef: draft.fileReferencesRef,- applyEditorDraft: noop,+ applyEditorDraft: draft.applyEditorDraft,handleInput: draft.handleInput,invalidatePromptEnhancement: noop,});@@ -193,8 +195,32 @@ globalThis.composerImeStackProbe = async () => {await type("/", { composing: false });const recovered = snap("typed / after dropped compositionend");+ // MCP completion uses the real editor, menu, and acceptance wiring (#1377).+ await type("/Documentation");+ const mcpMenu = document.querySelector('[role="listbox"]');+ const mcpVisible = mcpMenu?.textContent?.includes("/mcp:docs") === true;+ editor().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ await settle();+ const mcpKeyboard = draftValue === "/mcp:docs ";+ await type("/mcp:");+ const row = document.querySelector<HTMLElement>('[role="option"]');+ row?.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true }));+ await settle();+ const mcpMouse = draftValue === "/mcp:docs ";+ await type("/mcp:docs:sea");+ const toolVisible = document.querySelector('[role="listbox"]')?.textContent?.includes("/mcp:docs:search") === true;+ editor().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ await settle();+ const toolKeyboard = draftValue === "/mcp:docs:search ";+ await type("/mcp:docs:sea");+ document.querySelector<HTMLElement>('[role="option"]')?.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true }));+ await settle();+ const toolMouse = draftValue === "/mcp:docs:search ";+ snap("MCP tool accepted");+return {- ok: normal === true && normalQuery === true && recovered === true,+ ok: normal === true && normalQuery === true && recovered === true && mcpVisible && mcpKeyboard && mcpMouse && toolVisible && toolKeyboard && toolMouse,+ mcpVisible, mcpKeyboard, mcpMouse, toolVisible, toolKeyboard, toolMouse,normal,normalQuery,recovered,