Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(composer): reject empty MCP selections

vastsaf80e61d1edd0
diff --git a/apps/desktop/electron/main/composer-mcp.ts b/apps/desktop/electron/main/composer-mcp.ts
index 3e66db515..f1ab0429c 100644
--- a/apps/desktop/electron/main/composer-mcp.ts
+++ b/apps/desktop/electron/main/composer-mcp.ts
@@ -1,7 +1,11 @@
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[]) {
+export function expandMcpInvocation(
+ content: string,
+ commands: ComposerCommand[],
+ hasAttachments = false,
+) {
const match = /^\/(mcp:\S+)(?:\s|$)/.exec(content);
if (!match) return null;
const command = commands.find((entry) => entry.name === match[1]);
@@ -12,6 +16,11 @@ export function expandMcpInvocation(content: string, commands: ComposerCommand[]
});
}
const body = content.slice(match[0].length).trim();
+ if (!body && !hasAttachments) {
+ throw Object.assign(new Error("Add a task or attachment after the MCP selection."), {
+ errorCode: "COMPOSER_MCP_REQUEST_REQUIRED",
+ });
+ }
return {
command: content,
mcpServerIds: [command.mcpServerId],
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.ts
index 83ab6fdea..ddab84553 100644
--- a/apps/desktop/electron/main/ipc/agent-ipc.ts
+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts
@@ -289,7 +289,11 @@ export function registerAgentIpc({
"agent.steeringContext", { sessionId: req.sessionId, expectedTurnId: req.expectedTurnId },
);
const mcpExpansion = /^\/mcp:\S/.test(req.content)
- ? expandMcpInvocation(req.content, await composerCommandService.buildComposerCommands(context.projectPath ?? null))
+ ? expandMcpInvocation(
+ req.content,
+ await composerCommandService.buildComposerCommands(context.projectPath ?? null),
+ Boolean(req.attachments?.length),
+ )
: null;
const prepared = await preparePromptAttachments(
dataDir, req.sessionId, context.projectPath, req.attachments ?? [], context.supportsVision,
@@ -373,9 +377,13 @@ export function registerAgentIpc({
// 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,
- ))
+ ? expandMcpInvocation(
+ req.content,
+ await composerCommandService.buildComposerCommands(
+ typeof session.projectPath === "string" ? session.projectPath.trim() || null : null,
+ ),
+ Boolean(req.attachments?.length),
+ )
: null;
const truncateFromMessageId =
diff --git a/apps/desktop/test/composer-mcp.test.mjs b/apps/desktop/test/composer-mcp.test.mjs
index 09761ad29..1b67a12c9 100644
--- a/apps/desktop/test/composer-mcp.test.mjs
+++ b/apps/desktop/test/composer-mcp.test.mjs
@@ -1,5 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
+import { fileURLToPath } from "node:url";
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");
@@ -39,11 +40,16 @@ test("selection uses stable encoded IDs even when labels match", async () => {
assert.deepEqual(expansion.mcpServerIds, ["docs/two"]);
assert.doesNotMatch(expansion.expanded, /ToolSearch|mcp_docs_two_/);
assert.match(expansion.expanded, /find API docs$/);
+ assert.throws(() => expandMcpInvocation("/mcp:docs%2Ftwo", commands), { errorCode: "COMPOSER_MCP_REQUEST_REQUIRED" });
+ assert.deepEqual(
+ expandMcpInvocation("/mcp:docs%2Ftwo", commands, true).mcpServerIds,
+ ["docs/two"],
+ );
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) {
+function promptFixture(commandService, projectPath = "/repo") {
const handlers = new Map();
const calls = [];
const sidecarCalls = [];
@@ -51,7 +57,7 @@ function promptFixture(commandService) {
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.get") return { session: { id: "target", projectPath, messages: [] } };
if (method === "session.beginTurn") return { turnId: "turn-1" };
if (method === "session.appendMessage") return {};
assert.fail(`unexpected RPC ${method}`);
@@ -61,7 +67,7 @@ function promptFixture(commandService) {
getHost: () => host,
getSidecar: () => ({ setProjectInstructionRoot() {}, async call(method, params) {
sidecarCalls.push({ method, params });
- if (method === "agent.steeringContext") return { projectPath: "/repo", supportsVision: false };
+ if (method === "agent.steeringContext") return { projectPath, supportsVision: false };
return { accepted: true, turnId: "turn-1" };
} }),
getAgentHostBridge: () => null,
@@ -70,19 +76,19 @@ function promptFixture(commandService) {
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",
+ projectPath, 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",
+ optionalWorkspaceRoot: async () => projectPath,
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" }),
+ steer: (content, extra = {}) => handlers.get(IPC.invoke.agentSteer)({ sessionId: "target", content, expectedTurnId: "turn-1", ...extra }),
};
}
@@ -100,6 +106,29 @@ test("menu selection reaches runtime with MCP instructions and preserves the vis
assert.equal(fixture.released(), true);
});
+test("an attachment alone supplies request context for an MCP selection", async () => {
+ const projectPath = process.cwd();
+ const fixture = promptFixture(service([record("docs")], [ready("docs")]), projectPath);
+ const input = "/mcp:docs";
+ await fixture.prompt(input, {
+ attachments: [{ path: fileURLToPath(new URL("../package.json", import.meta.url)), name: "package.json", kind: "file" }],
+ });
+ const message = fixture.calls.find(c => c.method === "session.appendMessage").params.message;
+ assert.equal(message.command, input);
+ assert.equal(message.attachments.length, 1);
+ assert.deepEqual(fixture.sidecarCalls[0].params.mcpServerIds, ["docs"]);
+});
+
+for (const method of ["prompt", "steer"]) {
+ test(`command-only MCP ${method} is rejected before dispatching work`, async () => {
+ const fixture = promptFixture(service([record("docs")], [ready("docs")]));
+ await assert.rejects(fixture[method]("/mcp:docs"), { errorCode: "COMPOSER_MCP_REQUEST_REQUIRED" });
+ assert(!fixture.calls.some(c => ["session.beginTurn", "session.appendMessage"].includes(c.method)));
+ assert(!fixture.sidecarCalls.some(c => c.method === `agent.${method}`));
+ assert.equal(fixture.released(), method === "prompt");
+ });
+}
+
for (const change of ["disconnect", "disable", "scope"]) {
test(`send revalidates ${change} before opening or persisting a turn`, async () => {
const records = [record("docs")];
diff --git a/docs/adr/composer-mcp-invocations.md b/docs/adr/composer-mcp-invocations.md
index 3d045c616..237892754 100644
--- a/docs/adr/composer-mcp-invocations.md
+++ b/docs/adr/composer-mcp-invocations.md
@@ -48,10 +48,12 @@ 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.
+Selection makes tools available but does not force execution. Main rejects a
+server or tool command without task text or an attachment before opening a
+turn, so the model cannot infer an operation from the selection alone. With
+task text or attachment context, the model chooses arguments and calls. A
+renderer-driven tool call would duplicate runtime argument selection and
+permission handling.
## Unreleased user-facing change
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index 9fabfe19e..9bdca3b16 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -86,7 +86,9 @@ 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`.
+on-demand discovery. Main rejects a selected MCP command without task text or
+an attachment before opening or persisting a turn. See
+`docs/adr/composer-mcp-invocations.md`.
## 3. Common Tool Constraints
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 6d681079f..80f722739 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -2337,6 +2337,9 @@ identify the platform validation still needed.
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.
+- Submit a server/tool command with no task text or attachment. Main rejects it
+ before opening or persisting a turn; adding task text or an attachment allows
+ the selected tools to be offered to the model.
- 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.
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 6ea62ee9f..bc8f0813b 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -2585,6 +2585,7 @@ sklm: {
},
"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.",
+ COMPOSER_MCP_REQUEST_REQUIRED: "Gib nach der Auswahl eines MCP-Servers oder Tools einen Auftragstext ein oder füge einen Anhang hinzu.",
"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.ts
index e5aa796c0..776740761 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -2723,6 +2723,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.",
+ COMPOSER_MCP_REQUEST_REQUIRED: "Add task text or an attachment after selecting an MCP server or tool.",
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.ts
index 874fb4ec1..a935cc71b 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -2583,6 +2583,7 @@ sklm: {
},
"errors": {
COMPOSER_MCP_UNAVAILABLE: "El servidor MCP seleccionado está desconectado o no está disponible en este proyecto. Vuelve a conectarlo y seleccionarlo.",
+ COMPOSER_MCP_REQUEST_REQUIRED: "Después de elegir un servidor o una herramienta MCP, escribe una tarea o añade un archivo adjunto.",
"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.ts
index 1f1d8bd5b..07be0301b 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -2583,6 +2583,7 @@ sklm: {
},
"errors": {
COMPOSER_MCP_UNAVAILABLE: "Le serveur MCP sélectionné est déconnecté ou indisponible dans ce projet. Reconnectez-le et sélectionnez-le à nouveau.",
+ COMPOSER_MCP_REQUEST_REQUIRED: "Après avoir sélectionné un serveur ou un outil MCP, saisissez une tâche ou ajoutez une pièce jointe.",
"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.ts
index bdb36fbfe..422a65b85 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -2619,6 +2619,7 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이
},
errors: {
COMPOSER_MCP_UNAVAILABLE: "선택한 MCP 서버의 연결이 끊겼거나 현재 프로젝트에서 사용할 수 없습니다. 다시 연결하고 선택하세요.",
+ COMPOSER_MCP_REQUEST_REQUIRED: "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.ts
index 2bd58647c..87bed5ad7 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -2539,6 +2539,7 @@ export const ptBR = {
},
errors: {
COMPOSER_MCP_UNAVAILABLE: "O servidor MCP selecionado está desconectado ou indisponível neste projeto. Reconecte-o e selecione-o novamente.",
+ COMPOSER_MCP_REQUEST_REQUIRED: "Depois de escolher um servidor ou ferramenta MCP, informe uma tarefa ou adicione um anexo.",
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.ts
index d8414f4de..b6782b682 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -2609,6 +2609,7 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç
},
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.",
+ COMPOSER_MCP_REQUEST_REQUIRED: "Bir MCP sunucusu veya aracı seçtikten sonra görev metni girin ya da bir ek ekleyin.",
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.ts
index da43951e7..0ad6e4230 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -2648,6 +2648,7 @@ sklm: {
},
errors: {
COMPOSER_MCP_UNAVAILABLE: "所选 MCP 服务器已断开或在当前项目中不可用。请重新连接并选择。",
+ COMPOSER_MCP_REQUEST_REQUIRED: "选择 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.ts
index 9b034665f..d98259532 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -2598,6 +2598,7 @@ sklm: {
},
errors: {
COMPOSER_MCP_UNAVAILABLE: "所選 MCP 伺服器已中斷連線或在目前專案中無法使用。請重新連線並選取。",
+ COMPOSER_MCP_REQUEST_REQUIRED: "選取 MCP 伺服器或工具後,請輸入任務內容或新增附件。",
HOST_UNAVAILABLE: "本地服務不可用",
MODEL_NOT_CONFIGURED: "該模型尚未配置,或當前 AI 服務不提供此模型。",
TOOL_DENIED: "此操作的許可權已被拒絕",
diff --git a/scripts/e2e-composer-mcp.mjs b/scripts/e2e-composer-mcp.mjs
index f9df3b73c..59a083297 100644
--- a/scripts/e2e-composer-mcp.mjs
+++ b/scripts/e2e-composer-mcp.mjs
@@ -78,6 +78,9 @@ try {
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";
+ assert.throws(() => expandMcpInvocation("/mcp:chosen", commands), {
+ errorCode: "COMPOSER_MCP_REQUEST_REQUIRED",
+ });
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"]);