From bc38dab36cbc3682a1969fb9b7d15e8022b6d117 Mon Sep 17 00:00:00 2001 From: bitkyc08-arch Date: Thu, 23 Jul 2026 23:06:41 +0900 Subject: [PATCH 01/13] release: v2.7.36-preview.20260723 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 6a0e39a59a4..0ee48be336f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@bitkyc08/opencodex", - "version": "2.7.35", + "version": "2.7.36-preview.20260723", "description": "Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code", "type": "module", "main": "./bin/package-main.mjs", From 9eb3df544a5e4471bd3e35969bf21328f92eea20 Mon Sep 17 00:00:00 2001 From: bitkyc08-arch Date: Thu, 23 Jul 2026 23:28:09 +0900 Subject: [PATCH 02/13] release: v2.7.36 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 0ee48be336f..be0ae994659 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@bitkyc08/opencodex", - "version": "2.7.36-preview.20260723", + "version": "2.7.36", "description": "Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code", "type": "module", "main": "./bin/package-main.mjs", From b9a5d39878a6e7253298d97fd147a2ac975854d2 Mon Sep 17 00:00:00 2001 From: jun Date: Fri, 24 Jul 2026 15:23:24 +0900 Subject: [PATCH 03/13] release: v2.7.37 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index be0ae994659..352e78e2df8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@bitkyc08/opencodex", - "version": "2.7.36", + "version": "2.7.37", "description": "Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code", "type": "module", "main": "./bin/package-main.mjs", From 357acee62458684bc027e9d524e95bd066df3a43 Mon Sep 17 00:00:00 2001 From: jun Date: Fri, 24 Jul 2026 15:45:17 +0900 Subject: [PATCH 04/13] release: v2.7.39 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 352e78e2df8..ef31cde0d9d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@bitkyc08/opencodex", - "version": "2.7.37", + "version": "2.7.39", "description": "Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code", "type": "module", "main": "./bin/package-main.mjs", From dff68d0b02284239d792b23622f86b6dbf3c6d89 Mon Sep 17 00:00:00 2001 From: Wibias <37517432+Wibias@users.noreply.github.com> Date: Fri, 24 Jul 2026 12:28:08 +0200 Subject: [PATCH 05/13] fix(cursor): stop false shell/read blocked reports (#399) Treat shell_command/exec_command as one Codex bridge, pin it through catalog truncation, and rewrite native-exec rejection copy so policy routing is not mistaken for a sandbox denial. --- src/adapters/cursor/native-exec-fs.ts | 2 +- src/adapters/cursor/native-exec-network.ts | 2 +- src/adapters/cursor/native-exec-shell.ts | 2 +- src/adapters/cursor/request-builder.ts | 10 ++- src/adapters/cursor/tool-definitions.ts | 72 +++++++++++++++------- tests/cursor-blob.test.ts | 12 ++-- tests/cursor-native-exec.test.ts | 17 ++--- tests/cursor-request-builder.test.ts | 17 +++++ tests/cursor-tool-definitions.test.ts | 54 ++++++++++++++-- 9 files changed, 143 insertions(+), 45 deletions(-) diff --git a/src/adapters/cursor/native-exec-fs.ts b/src/adapters/cursor/native-exec-fs.ts index 7804202c072..1d4648f7498 100644 --- a/src/adapters/cursor/native-exec-fs.ts +++ b/src/adapters/cursor/native-exec-fs.ts @@ -44,7 +44,7 @@ function codexNativeMutationRefusal(operation: "write" | "delete"): string { } const NATIVE_LOCAL_EXEC_DISABLED = - "Cursor native local filesystem execution is not available for this request. Use the exec_command tool with equivalent shell commands (cat, head, ls, rg, grep) for file reads and searches, or apply_patch for file edits."; + "Cursor-native local filesystem execution is disabled by OpenCodex policy for this request. This is not a Codex sandbox denial. Use the Codex Responses bridge shell tool (`shell_command` / `exec_command`, or the listed `mcp_opencodex-responses_*` display alias) with equivalent shell commands (cat, head, ls, rg, grep) for file reads and searches, or `apply_patch` for file edits. Never tell the user that shell or read access is blocked unless that bridge tool also fails."; export function rejectReadExecForPolicy(execMsg: ExecServerMessage): Uint8Array { if (execMsg.message.case !== "readArgs") throw new Error("invalid read exec"); diff --git a/src/adapters/cursor/native-exec-network.ts b/src/adapters/cursor/native-exec-network.ts index c5042669597..7ef90260a4d 100644 --- a/src/adapters/cursor/native-exec-network.ts +++ b/src/adapters/cursor/native-exec-network.ts @@ -7,7 +7,7 @@ export interface CursorNativeNetworkDeps { } const NATIVE_FETCH_DISABLED = - "Cursor native fetch execution is not available for this request. Use the exec_command tool with curl or wget to make network requests instead."; + "Cursor-native fetch is disabled by OpenCodex policy for this request (not a Codex sandbox denial). Use the Codex shell bridge tool `shell_command` (aliases: `exec_command`, `mcp_opencodex-responses_shell_command`, `mcp_opencodex-responses_exec_command`) with curl or wget instead."; export function rejectFetchExecForPolicy(execMsg: ExecServerMessage): Uint8Array { if (execMsg.message.case !== "fetchArgs") throw new Error("invalid fetch exec"); diff --git a/src/adapters/cursor/native-exec-shell.ts b/src/adapters/cursor/native-exec-shell.ts index 994606959e2..4d3f6e4ebce 100644 --- a/src/adapters/cursor/native-exec-shell.ts +++ b/src/adapters/cursor/native-exec-shell.ts @@ -24,7 +24,7 @@ const backgroundShells = new Map function toolPriority(tool: OcxTool, selectedNames: ReadonlySet): number { if (toolChoiceAliases(tool).some(name => selectedNames.has(name))) return 0; - if (tool.loadedFromToolSearch) return 1; - if (!tool.namespace) return 2; - return 3; + // Keep the shell bridge and apply_patch through truncation so models always have a working + // Codex-local execution path even when niche MCP tools are dropped (#399). + if (isBareCodexShellBridgeTool(tool) || (!tool.namespace && tool.name === "apply_patch")) return 1; + if (tool.loadedFromToolSearch) return 2; + if (!tool.namespace) return 3; + return 4; } /** diff --git a/src/adapters/cursor/tool-definitions.ts b/src/adapters/cursor/tool-definitions.ts index b6f8ade987c..8ad24fcf3db 100644 --- a/src/adapters/cursor/tool-definitions.ts +++ b/src/adapters/cursor/tool-definitions.ts @@ -6,22 +6,27 @@ import { McpToolDefinitionSchema, McpToolsSchema, type McpToolDefinition } from export const OCX_RESPONSES_TOOL_PROVIDER = "opencodex-responses"; export const CODEX_EXEC_COMMAND_TOOL = "exec_command"; +export const CODEX_SHELL_COMMAND_TOOL = "shell_command"; export const CODEX_APPLY_PATCH_TOOL = "apply_patch"; export const CURSOR_EXEC_COMMAND_TOOL = CODEX_EXEC_COMMAND_TOOL; -export const CURSOR_SHELL_ALIAS_SYSTEM_NOTE = 'Shell commands use the `exec_command` tool with JSON arguments like {"cmd":"..."}.'; -export const CURSOR_SHELL_ALIAS_USER_HINT = "Use exec_command for this shell command."; +export const CODEX_SHELL_BRIDGE_TOOL_NAMES = [CODEX_EXEC_COMMAND_TOOL, CODEX_SHELL_COMMAND_TOOL] as const; +export const CURSOR_SHELL_ALIAS_SYSTEM_NOTE = + 'Shell commands use the Codex shell bridge tool shown in this turn\'s catalog (`shell_command` or `exec_command`) with JSON arguments like {"cmd":"..."}. The long `mcp_opencodex-responses_*` display name is the same tool. This is not a sandbox denial.'; +export const CURSOR_SHELL_ALIAS_USER_HINT = + "Use the Codex shell bridge tool listed this turn (`shell_command` or `exec_command`, including the long `mcp_opencodex-responses_*` name). Do not tell the user shell access is blocked unless that bridge tool also fails."; const NEIGHBOR_AGENT_TOOL_NAMES = ["Read", "Grep", "Glob", "Bash", "LS"] as const; export const CURSOR_GENERIC_TOOL_USE_USER_HINT = [ - "For generic tool-use/count demos, satisfy the request with repeated `exec_command` calls for harmless commands.", - "`exec_command` is the Codex Responses bridge exec tool exposed through Cursor's tool protocol; do not describe it as an external MCP server tool.", + "For generic tool-use/count demos, satisfy the request with repeated Codex shell bridge calls (`shell_command` or `exec_command`) for harmless commands.", + "`shell_command` / `exec_command` are the Codex Responses shell bridge exposed through Cursor's tool protocol; do not describe them as an external MCP server tool.", "Do not use `run_shell` unless this turn's tool catalog lists it.", - "A request for N tools means N separate `exec_command` invocations/results; never satisfy it with one chained shell command such as `cmd1 && cmd2`.", - "For independent read-only or output-only commands, emit all requested `exec_command` calls in the same response before waiting when the runtime supports parallel tool calls.", + "A request for N tools means N separate shell-bridge invocations/results; never satisfy it with one chained shell command such as `cmd1 && cmd2`.", + "For independent read-only or output-only commands, emit all requested shell-bridge calls in the same response before waiting when the runtime supports parallel tool calls.", "The Cursor bridge may suspend after the first returned bridge tool call, so emit sibling calls together before any result is needed.", - "If parallel emission is unavailable, continue with separate `exec_command` calls until the requested count has returned.", + "If parallel emission is unavailable, continue with separate shell-bridge calls until the requested count has returned.", "Do not use `tool_search`, external MCP, or resource discovery just to pad the count unless explicitly asked.", "Do not suggest or switch to neighboring-agent tools such as `Grep`, `Read`, `Glob`, `Bash`, or `LS` unless this turn's catalog lists those exact names.", + "Never tell the user that shell or read access is blocked unless the Codex shell bridge tool itself fails.", ].join(" "); export const CURSOR_EXEC_COMMAND_INPUT_SCHEMA = { @@ -38,8 +43,17 @@ export const CURSOR_EXEC_COMMAND_INPUT_SCHEMA = { additionalProperties: false, } as const; +export function isCodexShellBridgeToolName(name: string): boolean { + return (CODEX_SHELL_BRIDGE_TOOL_NAMES as readonly string[]).includes(name); +} + +export function isBareCodexShellBridgeTool(tool: Pick): boolean { + return !tool.namespace && isCodexShellBridgeToolName(tool.name); +} + +/** @deprecated Prefer isBareCodexShellBridgeTool; kept for older call sites/tests. */ function isBareCodexExecCommandTool(tool: Pick): boolean { - return !tool.namespace && tool.name === CODEX_EXEC_COMMAND_TOOL; + return isBareCodexShellBridgeTool(tool); } export function cursorRequestHasShellAlias(tools: readonly Pick[] | undefined): boolean { @@ -60,8 +74,9 @@ export function cursorToolWireName(tool: Pick): s /** * Cursor's harness shows MCP tools to the model as `mcp__`; models * sometimes call that display name verbatim instead of the advertised short name (live 20:41/21:00 - * sessions: `mcp_opencodex-responses_exec_command`). Fold the display prefix back to the advertised - * wire name so both spellings resolve to the same client tool instead of "unknown Responses tool". + * sessions: `mcp_opencodex-responses_exec_command` / `mcp_opencodex-responses_shell_command`). + * Fold the display prefix back to the advertised wire name, and treat `shell_command` / + * `exec_command` as the same Codex shell bridge, so alias thrash does not become "tool not found". */ const CURSOR_MCP_DISPLAY_PREFIX = `mcp_${OCX_RESPONSES_TOOL_PROVIDER}_`; @@ -71,7 +86,15 @@ export function normalizeCursorWireName(name: string): string { export function responsesToolNameFromCursorWire(name: string, cursorToolNameMap?: ReadonlyMap): string { const normalized = normalizeCursorWireName(name); - return cursorToolNameMap?.get(normalized) ?? normalized; + const direct = cursorToolNameMap?.get(normalized); + if (direct) return direct; + if (cursorToolNameMap && isCodexShellBridgeToolName(normalized)) { + for (const alias of CODEX_SHELL_BRIDGE_TOOL_NAMES) { + const mapped = cursorToolNameMap.get(alias); + if (mapped) return mapped; + } + } + return normalized; } export function cursorToolInputSchema(tool: OcxTool): unknown { @@ -79,7 +102,7 @@ export function cursorToolInputSchema(tool: OcxTool): unknown { } function activeTextMentionsExecCommand(text: string): boolean { - return /\bexec_command\b/i.test(text); + return /\b(?:exec_command|shell_command)\b/i.test(text); } function looksLikeShellCommandRequest(text: string): boolean { @@ -127,9 +150,9 @@ function cursorGenericToolUseHint(text: string): string { const count = requestedCursorToolUseCount(text); if (!count) return CURSOR_GENERIC_TOOL_USE_USER_HINT; return [ - `This turn requests ${count} tool uses: emit exactly ${count} separate \`exec_command\` function calls/results.`, - `One \`exec_command\` containing chained commands counts as 1 tool call, not ${count}.`, - `Prefer one parallel tool-call batch containing all ${count} independent \`exec_command\` calls before waiting for results.`, + `This turn requests ${count} tool uses: emit exactly ${count} separate Codex shell bridge function calls/results (\`shell_command\` or \`exec_command\`).`, + `One shell-bridge call containing chained commands counts as 1 tool call, not ${count}.`, + `Prefer one parallel tool-call batch containing all ${count} independent shell-bridge calls before waiting for results.`, CURSOR_GENERIC_TOOL_USE_USER_HINT, ].join(" "); } @@ -238,7 +261,9 @@ export function buildCursorToolGuidanceSystemNote( if (wireNames.length === 0) return undefined; const listedNames = quotedNames(wireNames); - const hasBareExec = wireNames.includes(CODEX_EXEC_COMMAND_TOOL); + const shellBridgeNames = wireNames.filter(isCodexShellBridgeToolName); + const hasBareExec = shellBridgeNames.length > 0; + const shellBridgeLabel = quotedNames(shellBridgeNames.length > 0 ? shellBridgeNames : [...CODEX_SHELL_BRIDGE_TOOL_NAMES]); const hasApplyPatch = cursorRequestAdvertisesApplyPatch(tools, toolChoice); const discoveryTools = discoveryToolLabel(wireNames); const unavailableNeighborNames = unavailableNeighborAgentToolNames(wireNames); @@ -249,31 +274,34 @@ export function buildCursorToolGuidanceSystemNote( ? `This turn does not expose neighboring-agent tool names ${quotedNames(unavailableNeighborNames)}; do not call or suggest them unless the catalog lists them.` : undefined, hasBareExec - ? "`exec_command` is the Codex Responses bridge exec tool for this turn, exposed through Cursor's tool protocol; it is not an external MCP server tool." + ? `${shellBridgeLabel} is the Codex Responses shell bridge for this turn, exposed through Cursor's tool protocol; it is not an external MCP server tool. \`shell_command\` and \`exec_command\` are aliases of the same bridge.` + : undefined, + hasBareExec + ? "Your tool list may display it under a longer `mcp_opencodex-responses_shell_command` / `mcp_opencodex-responses_exec_command` name; those are the SAME tool — call whichever your list shows, and do not comment on the naming difference to the user." : undefined, hasBareExec - ? "Your tool list may display it under the longer name `mcp_opencodex-responses_exec_command`; both names are the SAME tool — call whichever your list shows, and do not comment on the naming difference to the user." + ? "Never tell the user that shell or read access is blocked unless the Codex shell bridge tool itself fails. Cursor-native Shell/Read being unavailable is policy routing, not a sandbox denial." : undefined, "Cursor product features (Chronicle, screen recording, Notes, Plans, background agents) are available only if this turn's catalog lists a matching tool; do not offer or promise them otherwise.", hasBareExec - ? "For file read/search/listing, use `exec_command` when no more specific listed tool is available." + ? `For file read/search/listing, use ${shellBridgeLabel} when no more specific listed tool is available.` : undefined, hasApplyPatch ? "For file edits, use the `apply_patch` tool, not built-in file write/delete tools." : undefined, hasBareExec - ? "For tool-count demos, each counted tool must be a separate `exec_command` invocation/result; do not collapse several requested tools into one chained shell command." + ? "For tool-count demos, each counted tool must be a separate Codex shell-bridge invocation/result; do not collapse several requested tools into one chained shell command." : undefined, "For independent read-only tool-count or batch requests, prefer one response containing multiple tool calls before waiting for results when the runtime supports parallel tool calls.", hasBareExec - ? "For bridge tool-count batches, emit sibling `exec_command` calls together before any result is needed because the bridge may suspend after a returned tool call." + ? "For bridge tool-count batches, emit sibling shell-bridge calls together before any result is needed because the bridge may suspend after a returned tool call." : undefined, discoveryTools ? `Use ${discoveryTools} only for explicit discovery/resource tasks, not generic tool-count demos.` : undefined, "Do not count or report a tool call unless a tool result was actually returned.", hasBareExec - ? "If a built-in file read, directory listing, grep, or shell operation is rejected by the runtime, use \`exec_command\` with the equivalent shell command instead (e.g. \`cat\`, \`ls\`, \`rg\`, \`grep\`). For file edits, use \`apply_patch\` when available." + ? `If a Cursor-native file read, directory listing, grep, or shell operation is rejected by the runtime, use ${shellBridgeLabel} with the equivalent shell command instead (e.g. \`cat\`, \`ls\`, \`rg\`, \`grep\`). That rejection is not a sandbox denial. For file edits, use \`apply_patch\` when available.` : undefined, ].filter((note): note is string => typeof note === "string"); return notes.join(" "); diff --git a/tests/cursor-blob.test.ts b/tests/cursor-blob.test.ts index 6ee7c447780..1c2395be25e 100644 --- a/tests/cursor-blob.test.ts +++ b/tests/cursor-blob.test.ts @@ -325,7 +325,7 @@ describe("Cursor blob handshake", () => { expect(JSON.stringify(roots)).toContain("Shell commands use"); expect(JSON.stringify(roots)).toContain("exec_command"); expect(actionText(bytes)).toContain("Run: echo OCX via your shell tool, report stdout."); - expect(actionText(bytes)).toContain("Use exec_command for this shell command."); + expect(actionText(bytes)).toContain("Use the Codex shell bridge tool listed this turn"); }); test("adds generic exec_command guidance for active tool-count demo prompts", () => { @@ -347,18 +347,18 @@ describe("Cursor blob handshake", () => { const text = actionText(bytes); expect(text).toContain("아무 tool 10개 써봐"); expect(text).toContain("This turn requests 10 tool uses"); - expect(text).toContain("exactly 10 separate `exec_command` function calls/results"); - expect(text).toContain("One `exec_command` containing chained commands counts as 1 tool call, not 10"); + expect(text).toContain("exactly 10 separate Codex shell bridge function calls/results"); + expect(text).toContain("One shell-bridge call containing chained commands counts as 1 tool call, not 10"); expect(text).toContain("one parallel tool-call batch containing all 10"); - expect(text).toContain("repeated `exec_command` calls"); - expect(text).toContain("Codex Responses bridge exec tool"); + expect(text).toContain("repeated Codex shell bridge calls"); + expect(text).toContain("Codex Responses shell bridge"); expect(text).toContain("external MCP server tool"); expect(text).toContain("bridge may suspend"); expect(text).toContain("Do not use `run_shell`"); expect(text).toContain("Do not use `tool_search`, external MCP, or resource discovery just to pad the count"); expect(text).toContain("neighboring-agent tools"); expect(text).toContain("unless this turn's catalog lists those exact names"); - expect(text).not.toContain("Use exec_command for this shell command."); + expect(text).not.toContain("Use the Codex shell bridge tool listed this turn"); const roots = JSON.stringify(decodeRootMessages(bytes)); expect(roots).toContain("available tool names are exactly `exec_command`"); expect(roots).not.toContain("available tool names are exactly `exec_command`, `tool_search`"); diff --git a/tests/cursor-native-exec.test.ts b/tests/cursor-native-exec.test.ts index e7943296b8e..7be1b1d8a9c 100644 --- a/tests/cursor-native-exec.test.ts +++ b/tests/cursor-native-exec.test.ts @@ -104,7 +104,8 @@ describe("Cursor native exec bridge", () => { expect(deniedRead.message.case).toBe("readResult"); expect(deniedRead.message.value.result.case).toBe("error"); if (deniedRead.message.value.result.case === "error") { - expect(deniedRead.message.value.result.value.error).toContain("not available for this request"); + expect(deniedRead.message.value.result.value.error).toContain("disabled by OpenCodex policy"); + expect(deniedRead.message.value.result.value.error).toContain("not a Codex sandbox denial"); } const deniedShell = decode((await handleCursorNativeExec(execMessage({ @@ -114,7 +115,8 @@ describe("Cursor native exec bridge", () => { expect(deniedShell.message.case).toBe("shellResult"); expect(deniedShell.message.value.result.case).toBe("failure"); if (deniedShell.message.value.result.case === "failure") { - expect(deniedShell.message.value.result.value.stderr).toContain("exec_command"); + expect(deniedShell.message.value.result.value.stderr).toContain("shell_command"); + expect(deniedShell.message.value.result.value.stderr).toContain("not a Codex sandbox denial"); } const deniedStream = await handleCursorNativeExec(execMessage({ @@ -126,7 +128,8 @@ describe("Cursor native exec bridge", () => { .flatMap(msg => (msg.message.case === "execClientMessage" ? [msg.message.value] : [])) .flatMap(frame => (frame.message.case === "shellStream" && frame.message.value.event.case === "stderr" ? [frame.message.value.event.value.data] : [])) .join("\n"); - expect(streamText).toContain("exec_command"); + expect(streamText).toContain("shell_command"); + expect(streamText).toContain("not a Codex sandbox denial"); const deniedBackground = decode((await handleCursorNativeExec(execMessage({ case: "backgroundShellSpawnArgs", @@ -135,7 +138,7 @@ describe("Cursor native exec bridge", () => { expect(deniedBackground.message.case).toBe("backgroundShellSpawnResult"); expect(deniedBackground.message.value.result.case).toBe("error"); if (deniedBackground.message.value.result.case === "error") { - expect(deniedBackground.message.value.result.value.error).toContain("exec_command"); + expect(deniedBackground.message.value.result.value.error).toContain("shell_command"); } const deniedStdin = decode((await handleCursorNativeExec(execMessage({ @@ -145,7 +148,7 @@ describe("Cursor native exec bridge", () => { expect(deniedStdin.message.case).toBe("writeShellStdinResult"); expect(deniedStdin.message.value.result.case).toBe("error"); if (deniedStdin.message.value.result.case === "error") { - expect(deniedStdin.message.value.result.value.error).toContain("exec_command"); + expect(deniedStdin.message.value.result.value.error).toContain("shell_command"); } const deniedFetch = decode((await handleCursorNativeExec(execMessage({ @@ -155,7 +158,7 @@ describe("Cursor native exec bridge", () => { expect(deniedFetch.message.case).toBe("fetchResult"); expect(deniedFetch.message.value.result.case).toBe("error"); if (deniedFetch.message.value.result.case === "error") { - expect(deniedFetch.message.value.result.value.error).toContain("not available for this request"); + expect(deniedFetch.message.value.result.value.error).toContain("disabled by OpenCodex policy"); } }); @@ -193,7 +196,7 @@ describe("Cursor native exec bridge", () => { expect(shell.message.value.result.case).toBe("failure"); if (shell.message.value.result.case === "failure") { expect(shell.message.value.result.value.stdout).toBe(""); - expect(shell.message.value.result.value.stderr).toContain("exec_command"); + expect(shell.message.value.result.value.stderr).toContain("shell_command"); } }); diff --git a/tests/cursor-request-builder.test.ts b/tests/cursor-request-builder.test.ts index 1f63ca7c490..3f68ab5d247 100644 --- a/tests/cursor-request-builder.test.ts +++ b/tests/cursor-request-builder.test.ts @@ -312,6 +312,23 @@ describe("Cursor request builder", () => { expect(cursorMcpToolsEncodedSize(budget.tools, "auto")).toBeLessThanOrEqual(CURSOR_TOOL_BYTES_LIMIT); }); + test("pins the Codex shell bridge and apply_patch through truncation", () => { + const regular = Array.from({ length: CURSOR_TOOL_COUNT_LIMIT + 20 }, (_, index) => ({ + name: `regular_${index}`, + namespace: "mcp__regular", + description: "Regular", + parameters: {}, + })); + const shell = { name: "shell_command", description: "Run", parameters: {} }; + const patch = { name: "apply_patch", description: "Patch", parameters: {}, freeform: true }; + const budget = applyCursorToolBudget([...regular, shell, patch], "auto"); + + expect(budget.tools).toContain(shell); + expect(budget.tools).toContain(patch); + expect(budget.tools.length).toBeLessThanOrEqual(CURSOR_TOOL_COUNT_LIMIT); + expect(cursorMcpToolsEncodedSize(budget.tools, "auto")).toBeLessThanOrEqual(CURSOR_TOOL_BYTES_LIMIT); + }); + test("adds an honest recovery note only when tool_search survives", () => { const tools = [ { name: "tool_search", description: "Discover", parameters: {}, toolSearch: true }, diff --git a/tests/cursor-tool-definitions.test.ts b/tests/cursor-tool-definitions.test.ts index 9485df8cb5f..eb8cad7c587 100644 --- a/tests/cursor-tool-definitions.test.ts +++ b/tests/cursor-tool-definitions.test.ts @@ -59,6 +59,31 @@ describe("Cursor tool definitions", () => { expect(toJson(ValueSchema, fromBinary(ValueSchema, defs[0]!.inputSchema))).toEqual(CURSOR_EXEC_COMMAND_INPUT_SCHEMA); }); + test("advertises bare shell_command with the same compact native exec schema", () => { + const tool: OcxTool = { + name: "shell_command", + description: "Run a command", + parameters: { + type: "object", + properties: { + cmd: { type: "string" }, + yield_time_ms: { type: "number" }, + max_output_chars: { type: "number" }, + }, + required: ["cmd", "yield_time_ms"], + additionalProperties: true, + }, + }; + + expect(cursorToolWireName(tool)).toBe("shell_command"); + const defs = buildCursorToolDefinitions([tool]); + + expect(defs).toHaveLength(1); + expect(defs[0]?.name).toBe("shell_command"); + expect(defs[0]?.toolName).toBe("shell_command"); + expect(toJson(ValueSchema, fromBinary(ValueSchema, defs[0]!.inputSchema))).toEqual(CURSOR_EXEC_COMMAND_INPUT_SCHEMA); + }); + test("does not alias namespaced exec_command tools", () => { const tool: OcxTool = { name: "exec_command", @@ -103,11 +128,11 @@ describe("Cursor tool definitions", () => { expect(hinted).toContain(prompt); expect(hinted).toContain("This turn requests 10 tool uses"); - expect(hinted).toContain("exactly 10 separate `exec_command` function calls/results"); - expect(hinted).toContain("One `exec_command` containing chained commands counts as 1 tool call, not 10"); + expect(hinted).toContain("exactly 10 separate Codex shell bridge function calls/results (`shell_command` or `exec_command`)"); + expect(hinted).toContain("One shell-bridge call containing chained commands counts as 1 tool call, not 10"); expect(hinted).toContain("one parallel tool-call batch containing all 10"); - expect(hinted).toContain("repeated `exec_command` calls"); - expect(hinted).toContain("Codex Responses bridge exec tool"); + expect(hinted).toContain("repeated Codex shell bridge calls (`shell_command` or `exec_command`)"); + expect(hinted).toContain("Codex Responses shell bridge"); expect(hinted).toContain("external MCP server tool"); expect(hinted).toContain("bridge may suspend"); expect(hinted).toContain("Do not use `tool_search`, external MCP, or resource discovery"); @@ -138,6 +163,15 @@ describe("Cursor tool definitions", () => { ]); }); + test("filters generic tool-count demos when only shell_command is available", () => { + const tools: OcxTool[] = [ + { name: "shell_command", description: "Run", parameters: {} }, + { name: "tool_search", description: "Search tools", parameters: {} }, + ]; + + expect(cursorToolsForActivePrompt(tools, "Use any 10 tools")?.map(tool => cursorToolWireName(tool))).toEqual(["shell_command"]); + }); + test("does not erase explicit non-exec tool_choice for generic tool-count prompts", () => { const tools: OcxTool[] = [ { name: "exec_command", description: "Run", parameters: {} }, @@ -185,12 +219,24 @@ describe("Cursor tool definitions", () => { expect(note).toContain("current tool catalog as ground truth"); expect(note).toContain("This turn does not expose neighboring-agent tool names `Read`, `Grep`, `Glob`, `Bash`, `LS`"); expect(note).toContain("not an external MCP server tool"); + expect(note).toContain("Never tell the user that shell or read access is blocked"); expect(note).toContain("prefer one response containing multiple tool calls"); expect(note).toContain("Use MCP only for explicit discovery/resource tasks"); expect(note).toContain("not generic tool-count demos"); expect(note).toContain("Do not count or report a tool call unless a tool result was actually returned."); }); + test("builds shell_command guidance with alias and anti-false-block wording", () => { + const note = buildCursorToolGuidanceSystemNote([{ name: "shell_command", description: "Run", parameters: {} }]); + expect(note).toBeDefined(); + if (!note) throw new Error("Expected Cursor tool guidance note"); + + expect(note).toContain("`shell_command`"); + expect(note).toContain("`shell_command` and `exec_command` are aliases of the same bridge"); + expect(note).toContain("mcp_opencodex-responses_shell_command"); + expect(note).toContain("Never tell the user that shell or read access is blocked"); + }); + test("adds codex-native edit guidance only when apply_patch is advertised", () => { const tools: OcxTool[] = [ { name: "exec_command", description: "Run", parameters: {} }, From 24e34d4deeac20d5ad65a45fe858f4eacc671b4a Mon Sep 17 00:00:00 2001 From: Wibias <37517432+Wibias@users.noreply.github.com> Date: Fri, 24 Jul 2026 12:42:29 +0200 Subject: [PATCH 06/13] fix(cursor): rewrite shell bridge cmd args to command (#399) Cursor advertises cmd, but Codex validates command. Normalize completed tool args against the Responses-side schema so shell_command stops failing with missing field command. --- src/adapters/cursor/live-transport.ts | 7 +++- src/adapters/cursor/tool-definitions.ts | 55 +++++++++++++++++++++++++ tests/cursor-protobuf-events.test.ts | 21 ++++++++++ tests/cursor-tool-definitions.test.ts | 31 ++++++++++++++ 4 files changed, 112 insertions(+), 2 deletions(-) diff --git a/src/adapters/cursor/live-transport.ts b/src/adapters/cursor/live-transport.ts index c00debdb398..5d2a954700a 100644 --- a/src/adapters/cursor/live-transport.ts +++ b/src/adapters/cursor/live-transport.ts @@ -50,7 +50,7 @@ import { buildCursorToolDefinitions, cursorRequestAdvertisesApplyPatch, cursorRequestHasShellAlias, - cursorToolInputSchema, + cursorToolArgNormalizeSchema, cursorToolWireName, cursorToolsForActivePrompt, isGenericToolUseCountDemoPrompt, @@ -506,7 +506,10 @@ class LiveCursorTransport implements CursorTransport { const cursorToolNameMap = new Map(); for (const tool of cursorVisibleTools ?? []) { const cursorWireName = cursorToolWireName(tool); - toolSchemas.set(cursorWireName, cursorToolInputSchema(tool)); + // Normalize against Responses/Codex field names, not the Cursor advertisement schema. + // Advertising `cmd` while also storing that schema here left `cmd` unmapped and Codex + // rejected shell_command with "missing field `command`" (#399). + toolSchemas.set(cursorWireName, cursorToolArgNormalizeSchema(tool)); cursorToolNameMap.set(cursorWireName, namespacedToolName(tool.namespace, tool.name)); } state = createCursorProtobufEventState({ diff --git a/src/adapters/cursor/tool-definitions.ts b/src/adapters/cursor/tool-definitions.ts index 8ad24fcf3db..8057cce75fc 100644 --- a/src/adapters/cursor/tool-definitions.ts +++ b/src/adapters/cursor/tool-definitions.ts @@ -43,6 +43,25 @@ export const CURSOR_EXEC_COMMAND_INPUT_SCHEMA = { additionalProperties: false, } as const; +/** + * Responses/Codex-side schema used ONLY for arg-key normalization after Cursor returns a call. + * Cursor models are trained to emit `cmd`; Codex `shell_command` / `exec_command` validate + * `command`. Keeping `cmd` out of this schema lets `normalizeArgKeys` rewrite `cmd` → `command`. + */ +export const CODEX_SHELL_BRIDGE_ARG_NORMALIZE_SCHEMA = { + type: "object", + properties: { + command: { type: "string", description: "Shell command to execute." }, + workdir: { type: "string", description: "Working directory for the command. Defaults to the turn cwd." }, + shell: { type: "string", description: "Shell binary to launch. Defaults to the user's default shell." }, + tty: { type: "boolean", description: "True allocates a PTY for the command; false or omitted uses plain pipes." }, + yield_time_ms: { type: "number", description: "Wait before yielding output. Defaults to 10000 ms; effective range is 250-30000 ms." }, + max_output_tokens: { type: "number", description: "Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy." }, + max_output_chars: { type: "number", description: "Output character budget when the Responses tool uses chars instead of tokens." }, + }, + required: ["command"], +} as const; + export function isCodexShellBridgeToolName(name: string): boolean { return (CODEX_SHELL_BRIDGE_TOOL_NAMES as readonly string[]).includes(name); } @@ -97,10 +116,46 @@ export function responsesToolNameFromCursorWire(name: string, cursorToolNameMap? return normalized; } +/** Schema advertised to Cursor for this tool (may use Cursor-preferred field names like `cmd`). */ export function cursorToolInputSchema(tool: OcxTool): unknown { return isBareCodexExecCommandTool(tool) ? CURSOR_EXEC_COMMAND_INPUT_SCHEMA : (tool.parameters ?? {}); } +/** + * Schema used to normalize completed Cursor tool args back to Responses/Codex field names. + * Must NOT reuse `cursorToolInputSchema` for the shell bridge: advertising `cmd` while also + * treating `cmd` as canonical prevents the `cmd` → `command` rewrite Codex requires (#399). + */ +export function cursorToolArgNormalizeSchema(tool: OcxTool): unknown { + if (isBareCodexShellBridgeTool(tool)) { + return shellBridgeArgNormalizeSchema(tool.parameters); + } + return tool.parameters ?? {}; +} + +function shellBridgeArgNormalizeSchema(parameters: unknown): unknown { + if (!parameters || typeof parameters !== "object") return CODEX_SHELL_BRIDGE_ARG_NORMALIZE_SCHEMA; + const base = parameters as Record; + const rawProps = base.properties && typeof base.properties === "object" + ? { ...(base.properties as Record) } + : {}; + // Drop Cursor-preferred aliases so normalizeArgKeys can rewrite them to Responses keys. + delete rawProps.cmd; + const properties = { + ...CODEX_SHELL_BRIDGE_ARG_NORMALIZE_SCHEMA.properties, + ...rawProps, + command: rawProps.command ?? CODEX_SHELL_BRIDGE_ARG_NORMALIZE_SCHEMA.properties.command, + }; + return { + ...base, + type: "object", + properties, + required: Array.isArray(base.required) && (base.required as unknown[]).includes("command") + ? base.required + : ["command"], + }; +} + function activeTextMentionsExecCommand(text: string): boolean { return /\b(?:exec_command|shell_command)\b/i.test(text); } diff --git a/tests/cursor-protobuf-events.test.ts b/tests/cursor-protobuf-events.test.ts index be2894ca810..a332da82222 100644 --- a/tests/cursor-protobuf-events.test.ts +++ b/tests/cursor-protobuf-events.test.ts @@ -428,6 +428,27 @@ describe("Cursor protobuf tool-call events", () => { expect(delta && delta.type === "tool_call_delta" ? JSON.parse(delta.arguments) : null).toEqual({ path: "a.txt" }); }); + test("rewrites shell_command cmd args to command for Codex Responses validation", () => { + const toolSchemas = new Map([ + ["shell_command", { type: "object", properties: { command: { type: "string" }, workdir: { type: "string" } }, required: ["command"] }], + ]); + const state = createCursorProtobufEventState({ + clientToolNames: ["shell_command"], + toolSchemas, + cursorToolNameMap: new Map([["shell_command", "shell_command"]]), + }); + const toolCall = mcpToolCall("shell_command", { cmd: "git status", workdir: "C:/repo" }); + const events = mapCursorProtobufServerMessage(interaction({ + case: "toolCallCompleted", + value: create(ToolCallCompletedUpdateSchema, { callId: "call_1", modelCallId: "model_1", toolCall }), + }), state); + const delta = events.find(e => e.type === "tool_call_delta"); + expect(delta && delta.type === "tool_call_delta" ? JSON.parse(delta.arguments) : null).toEqual({ + command: "git status", + workdir: "C:/repo", + }); + }); + test("normalizes mis-keyed args that arrived only via streamed text (no completed map)", () => { // The P1 audit case: model streamed `{"filepath":"a.txt"}` complete and the completion has no // map bytes. Buffered text must still be schema-normalized to `path` before reaching Codex. diff --git a/tests/cursor-tool-definitions.test.ts b/tests/cursor-tool-definitions.test.ts index eb8cad7c587..22e023857ba 100644 --- a/tests/cursor-tool-definitions.test.ts +++ b/tests/cursor-tool-definitions.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from "bun:test"; import { fromBinary, toJson } from "@bufbuild/protobuf"; import { ValueSchema } from "@bufbuild/protobuf/wkt"; +import { normalizeArgKeys } from "../src/adapters/cursor/arg-normalize"; import { appendCursorGenericToolUseHint, buildCursorToolDefinitions, @@ -8,6 +9,8 @@ import { buildCursorToolGuidanceSystemNote, CURSOR_EXEC_COMMAND_INPUT_SCHEMA, cursorRequestAdvertisesApplyPatch, + cursorToolArgNormalizeSchema, + cursorToolInputSchema, cursorToolWireName, isGenericToolUseCountDemoPrompt, } from "../src/adapters/cursor/tool-definitions"; @@ -84,6 +87,34 @@ describe("Cursor tool definitions", () => { expect(toJson(ValueSchema, fromBinary(ValueSchema, defs[0]!.inputSchema))).toEqual(CURSOR_EXEC_COMMAND_INPUT_SCHEMA); }); + test("normalizes advertised shell_command cmd args to Responses command before Codex sees them", () => { + // Live #399 failure: Cursor advertisement requires `cmd`, models send `cmd`, but Codex + // shell_command validates `command` → "missing field `command`". Normalization must use the + // Responses-side schema, not the Cursor advertisement schema. + const tool: OcxTool = { + name: "shell_command", + description: "Run a command", + parameters: { + type: "object", + properties: { + command: { type: "string" }, + workdir: { type: "string" }, + }, + required: ["command"], + }, + }; + + expect(cursorToolInputSchema(tool)).toEqual(CURSOR_EXEC_COMMAND_INPUT_SCHEMA); + expect(normalizeArgKeys({ cmd: "git status" }, cursorToolInputSchema(tool))).toEqual({ cmd: "git status" }); + expect(normalizeArgKeys({ cmd: "git status", workdir: "C:/repo" }, cursorToolArgNormalizeSchema(tool))).toEqual({ + command: "git status", + workdir: "C:/repo", + }); + expect(normalizeArgKeys({ command: "git status" }, cursorToolArgNormalizeSchema(tool))).toEqual({ + command: "git status", + }); + }); + test("does not alias namespaced exec_command tools", () => { const tool: OcxTool = { name: "exec_command", From 9262e8993b475360483ab9d2e131fb02cad9e170 Mon Sep 17 00:00:00 2001 From: Wibias <37517432+Wibias@users.noreply.github.com> Date: Fri, 24 Jul 2026 12:58:00 +0200 Subject: [PATCH 07/13] fix(cursor): harden shell-bridge alias admission and budget pinning (#399) Accept shell_command/exec_command as one advertised bridge at the client-tool gate, force-keep the bridge through byte-budget truncation, update native-exec policy assertions, and sharpen anti-false-block guidance for Cursor-native Shell. --- src/adapters/cursor/protobuf-events.ts | 53 ++++++++++++++++---- src/adapters/cursor/request-builder.ts | 64 ++++++++++++++++++++----- src/adapters/cursor/tool-definitions.ts | 2 +- tests/cursor-native-exec-policy.test.ts | 8 ++-- tests/cursor-protobuf-events.test.ts | 26 ++++++++++ tests/cursor-request-builder.test.ts | 20 ++++++++ 6 files changed, 149 insertions(+), 24 deletions(-) diff --git a/src/adapters/cursor/protobuf-events.ts b/src/adapters/cursor/protobuf-events.ts index bb2fdc06ff9..99a580a9118 100644 --- a/src/adapters/cursor/protobuf-events.ts +++ b/src/adapters/cursor/protobuf-events.ts @@ -2,7 +2,13 @@ import type { OcxUsage } from "../../types"; import type { AgentServerMessage, McpArgs, ToolCall } from "./gen/agent_pb"; import { decodeCursorArgsMap } from "./arg-codec"; import { normalizeArgKeys } from "./arg-normalize"; -import { OCX_RESPONSES_TOOL_PROVIDER, normalizeCursorWireName, responsesToolNameFromCursorWire } from "./tool-definitions"; +import { + CODEX_SHELL_BRIDGE_TOOL_NAMES, + isCodexShellBridgeToolName, + normalizeCursorWireName, + OCX_RESPONSES_TOOL_PROVIDER, + responsesToolNameFromCursorWire, +} from "./tool-definitions"; import type { CursorServerMessage } from "./types"; const DEFAULT_CONTEXT_USAGE_MAX_ENTRIES = 200; @@ -212,12 +218,38 @@ function decodeMcpArgs(args: McpArgs | undefined): string { return JSON.stringify(decodeCursorArgsMap(args?.args)); } +/** Resolve an advertised client-tool wire name, including shell_command/exec_command aliases (#399). */ +function resolveAdvertisedClientToolName( + state: CursorProtobufEventState, + cursorWireName: string, +): string | undefined { + const normalized = normalizeCursorWireName(cursorWireName); + if (!state.clientToolNames) return normalized; + if (state.clientToolNames.has(normalized)) return normalized; + if (isCodexShellBridgeToolName(normalized)) { + for (const alias of CODEX_SHELL_BRIDGE_TOOL_NAMES) { + if (state.clientToolNames.has(alias)) return alias; + } + } + return undefined; +} + +function toolSchemaForWireName(state: CursorProtobufEventState, toolName: string | undefined): unknown | undefined { + if (!toolName || !state.toolSchemas) return undefined; + if (state.toolSchemas.has(toolName)) return state.toolSchemas.get(toolName); + if (isCodexShellBridgeToolName(toolName)) { + for (const alias of CODEX_SHELL_BRIDGE_TOOL_NAMES) { + if (state.toolSchemas.has(alias)) return state.toolSchemas.get(alias); + } + } + return undefined; +} + function decodeMcpArgsNormalized(args: McpArgs | undefined, state: CursorProtobufEventState): string { const decoded = decodeCursorArgsMap(args?.args); const toolName = mcpWireNameFromArgs(args); - if (toolName && state.toolSchemas?.has(toolName)) { - return JSON.stringify(normalizeArgKeys(decoded, state.toolSchemas.get(toolName))); - } + const schema = toolSchemaForWireName(state, toolName); + if (schema) return JSON.stringify(normalizeArgKeys(decoded, schema)); return JSON.stringify(decoded); } @@ -237,11 +269,12 @@ function isCompleteJson(text: string): boolean { /** Schema-normalize a JSON-text argument blob for a named tool, if a schema is known. */ function normalizeJsonText(text: string, toolName: string | undefined, state: CursorProtobufEventState): string { - if (!toolName || !state.toolSchemas?.has(toolName)) return text; + const schema = toolSchemaForWireName(state, toolName); + if (!schema) return text; try { const parsed = JSON.parse(text); if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) { - return JSON.stringify(normalizeArgKeys(parsed as Record, state.toolSchemas.get(toolName))); + return JSON.stringify(normalizeArgKeys(parsed as Record, schema)); } } catch { // Not parseable as an object: leave as-is. @@ -305,10 +338,14 @@ export function mapSyntheticMcpExecToToolEvents( function recordToolCall(state: CursorProtobufEventState, callId: string, cursorWireName: string): CursorServerMessage[] { if (state.completedToolCalls.has(callId)) return []; if (state.openToolCalls.has(callId)) return []; - if (state.clientToolNames && !state.clientToolNames.has(cursorWireName)) { + const advertisedName = resolveAdvertisedClientToolName(state, cursorWireName); + if (state.clientToolNames && !advertisedName) { return [{ type: "error", message: `Cursor requested unknown Responses tool: ${cursorWireName}` }]; } - state.openToolCalls.set(callId, { name: responsesToolNameFromCursorWire(cursorWireName, state.cursorToolNameMap), args: "" }); + // Prefer the advertised catalog name for Responses mapping so shell_command/exec_command aliases + // land on the tool Codex actually exposed this turn (#399). + const mapKey = advertisedName ?? normalizeCursorWireName(cursorWireName); + state.openToolCalls.set(callId, { name: responsesToolNameFromCursorWire(mapKey, state.cursorToolNameMap), args: "" }); state.startedClientToolCalls++; return []; } diff --git a/src/adapters/cursor/request-builder.ts b/src/adapters/cursor/request-builder.ts index 57e61c63bbd..885d615b742 100644 --- a/src/adapters/cursor/request-builder.ts +++ b/src/adapters/cursor/request-builder.ts @@ -37,12 +37,16 @@ function explicitlySelectedNames(choice: OcxToolChoice | undefined): Set function toolPriority(tool: OcxTool, selectedNames: ReadonlySet): number { if (toolChoiceAliases(tool).some(name => selectedNames.has(name))) return 0; - // Keep the shell bridge and apply_patch through truncation so models always have a working - // Codex-local execution path even when niche MCP tools are dropped (#399). - if (isBareCodexShellBridgeTool(tool) || (!tool.namespace && tool.name === "apply_patch")) return 1; - if (tool.loadedFromToolSearch) return 2; - if (!tool.namespace) return 3; - return 4; + // Shell bridge before apply_patch so a large patch schema cannot starve the only execution path (#399). + if (isBareCodexShellBridgeTool(tool)) return 1; + if (!tool.namespace && tool.name === "apply_patch") return 2; + if (tool.loadedFromToolSearch) return 3; + if (!tool.namespace) return 4; + return 5; +} + +function isPinnedCursorTool(tool: OcxTool, selectedNames: ReadonlySet): boolean { + return toolPriority(tool, selectedNames) <= 2; } /** @@ -68,15 +72,51 @@ export function applyCursorToolBudget( const keptSet = new Set(); let keptBytes = 0; - for (const candidate of candidates) { - if (kept.length >= CURSOR_TOOL_COUNT_LIMIT) continue; + const tryKeep = (tool: OcxTool): boolean => { + if (keptSet.has(tool) || kept.length >= CURSOR_TOOL_COUNT_LIMIT) return keptSet.has(tool); // Repeated protobuf message fields serialize as concatenated tag/length/value entries, // so each one-entry wrapper size is the exact additive contribution to McpTools. - const candidateBytes = cursorMcpToolEncodedSize(candidate.tool, toolChoice); - if (keptBytes + candidateBytes > CURSOR_TOOL_BYTES_LIMIT) continue; - kept.push(candidate.tool); - keptSet.add(candidate.tool); + const candidateBytes = cursorMcpToolEncodedSize(tool, toolChoice); + if (keptBytes + candidateBytes > CURSOR_TOOL_BYTES_LIMIT) return false; + kept.push(tool); + keptSet.add(tool); keptBytes += candidateBytes; + return true; + }; + + // Phase 1: selected tools + shell bridge + apply_patch (priority <= 2). + for (const candidate of candidates) { + if (!isPinnedCursorTool(candidate.tool, selectedNames)) continue; + tryKeep(candidate.tool); + } + + // If a shell bridge tool is still omitted, evict lower-priority non-pinned tools to make room. + for (const candidate of candidates) { + if (!isBareCodexShellBridgeTool(candidate.tool) || keptSet.has(candidate.tool)) continue; + const need = cursorMcpToolEncodedSize(candidate.tool, toolChoice); + if (need > CURSOR_TOOL_BYTES_LIMIT) continue; + while ( + (!keptSet.has(candidate.tool)) + && (kept.length >= CURSOR_TOOL_COUNT_LIMIT || keptBytes + need > CURSOR_TOOL_BYTES_LIMIT) + ) { + let evictAt = -1; + for (let i = kept.length - 1; i >= 0; i--) { + if (!isPinnedCursorTool(kept[i]!, selectedNames)) { + evictAt = i; + break; + } + } + if (evictAt < 0) break; + const evicted = kept.splice(evictAt, 1)[0]!; + keptSet.delete(evicted); + keptBytes -= cursorMcpToolEncodedSize(evicted, toolChoice); + } + tryKeep(candidate.tool); + } + + // Phase 2: remaining tools by priority. + for (const candidate of candidates) { + tryKeep(candidate.tool); } return { diff --git a/src/adapters/cursor/tool-definitions.ts b/src/adapters/cursor/tool-definitions.ts index 8057cce75fc..59893eca078 100644 --- a/src/adapters/cursor/tool-definitions.ts +++ b/src/adapters/cursor/tool-definitions.ts @@ -13,7 +13,7 @@ export const CODEX_SHELL_BRIDGE_TOOL_NAMES = [CODEX_EXEC_COMMAND_TOOL, CODEX_SHE export const CURSOR_SHELL_ALIAS_SYSTEM_NOTE = 'Shell commands use the Codex shell bridge tool shown in this turn\'s catalog (`shell_command` or `exec_command`) with JSON arguments like {"cmd":"..."}. The long `mcp_opencodex-responses_*` display name is the same tool. This is not a sandbox denial.'; export const CURSOR_SHELL_ALIAS_USER_HINT = - "Use the Codex shell bridge tool listed this turn (`shell_command` or `exec_command`, including the long `mcp_opencodex-responses_*` name). Do not tell the user shell access is blocked unless that bridge tool also fails."; + "Use the Codex shell bridge tool listed this turn (`shell_command` or `exec_command`, including the long `mcp_opencodex-responses_*` name). Cursor-native Shell/Read being unavailable is expected policy routing — silently use the bridge tool and do not tell the user shell access is blocked unless that bridge tool also fails."; const NEIGHBOR_AGENT_TOOL_NAMES = ["Read", "Grep", "Glob", "Bash", "LS"] as const; export const CURSOR_GENERIC_TOOL_USE_USER_HINT = [ diff --git a/tests/cursor-native-exec-policy.test.ts b/tests/cursor-native-exec-policy.test.ts index c1f74e44d40..199e0a41cad 100644 --- a/tests/cursor-native-exec-policy.test.ts +++ b/tests/cursor-native-exec-policy.test.ts @@ -121,14 +121,16 @@ describe("Cursor native exec sandbox policy", () => { value: create(ReadArgsSchema, { path }), }), { unsafeAllowNativeLocalExec }))[0]); const deniedText = stringify(denied); - expect(deniedText).toContain("Cursor native local filesystem execution is not available for this request"); + expect(deniedText).toContain("disabled by OpenCodex policy"); + expect(deniedText).toContain("not a Codex sandbox denial"); expect(deniedText).not.toContain(content); const deniedShell = decode((await handleCursorNativeExec(execMessage({ case: "shellArgs", value: create(ShellArgsSchema, { command: "printf SHOULD_NOT_RUN", workingDirectory: dir, hardTimeout: 2000 }), }), { unsafeAllowNativeLocalExec }))[0]); - expect(stringify(deniedShell)).toContain("Cursor native shell execution is not available for this request"); + expect(stringify(deniedShell)).toContain("disabled by OpenCodex policy"); + expect(stringify(deniedShell)).toContain("shell_command"); expect(deniedShell.message.case).toBe("shellResult"); expect(deniedShell.message.value.result.case).toBe("failure"); if (deniedShell.message.value.result.case === "failure") { @@ -147,7 +149,7 @@ describe("Cursor native exec sandbox policy", () => { }, }))[0]); expect(fetchCalled).toBe(false); - expect(stringify(deniedFetch)).toContain("Cursor native fetch execution is not available for this request"); + expect(stringify(deniedFetch)).toContain("disabled by OpenCodex policy"); expect(stringify(deniedFetch)).not.toContain("SHOULD_NOT_FETCH"); } diff --git a/tests/cursor-protobuf-events.test.ts b/tests/cursor-protobuf-events.test.ts index a332da82222..1f17798d275 100644 --- a/tests/cursor-protobuf-events.test.ts +++ b/tests/cursor-protobuf-events.test.ts @@ -650,4 +650,30 @@ describe("Cursor MCP display-name alias", () => { }), state); expect(events.some(e => e.type === "error")).toBe(true); }); + + test("accepts exec_command when only shell_command was advertised", () => { + const toolSchemas = new Map([ + ["shell_command", { type: "object", properties: { command: { type: "string" } }, required: ["command"] }], + ]); + const state = createCursorProtobufEventState({ + clientToolNames: ["shell_command"], + toolSchemas, + cursorToolNameMap: new Map([["shell_command", "shell_command"]]), + }); + const toolCall = mcpToolCall("exec_command", { cmd: "echo ok" }); + + expect(mapCursorProtobufServerMessage(interaction({ + case: "toolCallStarted", + value: create(ToolCallStartedUpdateSchema, { callId: "call_alias", modelCallId: "m3", toolCall }), + }), state)).toEqual([]); + + const events = mapCursorProtobufServerMessage(interaction({ + case: "toolCallCompleted", + value: create(ToolCallCompletedUpdateSchema, { callId: "call_alias", modelCallId: "m3", toolCall }), + }), state); + const start = events.find(e => e.type === "tool_call_start"); + const delta = events.find(e => e.type === "tool_call_delta"); + expect(start && start.type === "tool_call_start" ? start.name : undefined).toBe("shell_command"); + expect(delta && delta.type === "tool_call_delta" ? JSON.parse(delta.arguments) : null).toEqual({ command: "echo ok" }); + }); }); diff --git a/tests/cursor-request-builder.test.ts b/tests/cursor-request-builder.test.ts index 3f68ab5d247..0c5baa75226 100644 --- a/tests/cursor-request-builder.test.ts +++ b/tests/cursor-request-builder.test.ts @@ -329,6 +329,26 @@ describe("Cursor request builder", () => { expect(cursorMcpToolsEncodedSize(budget.tools, "auto")).toBeLessThanOrEqual(CURSOR_TOOL_BYTES_LIMIT); }); + test("keeps shell_command even when a large apply_patch would otherwise consume the byte budget first", () => { + const hugePatch = { + name: "apply_patch", + description: "x".repeat(Math.floor(CURSOR_TOOL_BYTES_LIMIT * 0.7)), + parameters: { type: "object", properties: {} }, + freeform: true, + }; + const shell = { name: "shell_command", description: "Run", parameters: { type: "object", properties: { command: { type: "string" } } } }; + const filler = Array.from({ length: 40 }, (_, index) => ({ + name: `filler_${index}`, + namespace: "mcp__filler", + description: "y".repeat(2_000), + parameters: { type: "object", properties: {} }, + })); + const budget = applyCursorToolBudget([hugePatch, ...filler, shell], "auto"); + + expect(budget.tools).toContain(shell); + expect(cursorMcpToolsEncodedSize(budget.tools, "auto")).toBeLessThanOrEqual(CURSOR_TOOL_BYTES_LIMIT); + }); + test("adds an honest recovery note only when tool_search survives", () => { const tools = [ { name: "tool_search", description: "Discover", parameters: {}, toolSearch: true }, From 824f29906f5330f4f14fec8da3edc7aa1e4f1289 Mon Sep 17 00:00:00 2001 From: Wibias <37517432+Wibias@users.noreply.github.com> Date: Fri, 24 Jul 2026 13:11:28 +0200 Subject: [PATCH 08/13] fix(cursor): address CodeRabbit shell-bridge review (#399) Share one shell-bridge alias resolver and extend budget eviction so apply_patch is force-kept like the shell bridge when filler tools crowd the Cursor catalog. --- src/adapters/cursor/protobuf-events.ts | 19 +++------------- src/adapters/cursor/request-builder.ts | 6 +++-- src/adapters/cursor/tool-definitions.ts | 30 +++++++++++++++++-------- tests/cursor-request-builder.test.ts | 24 ++++++++++++++++++++ 4 files changed, 52 insertions(+), 27 deletions(-) diff --git a/src/adapters/cursor/protobuf-events.ts b/src/adapters/cursor/protobuf-events.ts index 99a580a9118..b85a2578083 100644 --- a/src/adapters/cursor/protobuf-events.ts +++ b/src/adapters/cursor/protobuf-events.ts @@ -3,10 +3,9 @@ import type { AgentServerMessage, McpArgs, ToolCall } from "./gen/agent_pb"; import { decodeCursorArgsMap } from "./arg-codec"; import { normalizeArgKeys } from "./arg-normalize"; import { - CODEX_SHELL_BRIDGE_TOOL_NAMES, - isCodexShellBridgeToolName, normalizeCursorWireName, OCX_RESPONSES_TOOL_PROVIDER, + resolveShellBridgeAliasKey, responsesToolNameFromCursorWire, } from "./tool-definitions"; import type { CursorServerMessage } from "./types"; @@ -225,24 +224,12 @@ function resolveAdvertisedClientToolName( ): string | undefined { const normalized = normalizeCursorWireName(cursorWireName); if (!state.clientToolNames) return normalized; - if (state.clientToolNames.has(normalized)) return normalized; - if (isCodexShellBridgeToolName(normalized)) { - for (const alias of CODEX_SHELL_BRIDGE_TOOL_NAMES) { - if (state.clientToolNames.has(alias)) return alias; - } - } - return undefined; + return resolveShellBridgeAliasKey(normalized, alias => (state.clientToolNames!.has(alias) ? alias : undefined)); } function toolSchemaForWireName(state: CursorProtobufEventState, toolName: string | undefined): unknown | undefined { if (!toolName || !state.toolSchemas) return undefined; - if (state.toolSchemas.has(toolName)) return state.toolSchemas.get(toolName); - if (isCodexShellBridgeToolName(toolName)) { - for (const alias of CODEX_SHELL_BRIDGE_TOOL_NAMES) { - if (state.toolSchemas.has(alias)) return state.toolSchemas.get(alias); - } - } - return undefined; + return resolveShellBridgeAliasKey(toolName, alias => state.toolSchemas!.get(alias)); } function decodeMcpArgsNormalized(args: McpArgs | undefined, state: CursorProtobufEventState): string { diff --git a/src/adapters/cursor/request-builder.ts b/src/adapters/cursor/request-builder.ts index 885d615b742..51be10bfecf 100644 --- a/src/adapters/cursor/request-builder.ts +++ b/src/adapters/cursor/request-builder.ts @@ -90,9 +90,11 @@ export function applyCursorToolBudget( tryKeep(candidate.tool); } - // If a shell bridge tool is still omitted, evict lower-priority non-pinned tools to make room. + // If a pinned tool is still omitted, evict lower-priority non-pinned tools to make room (#399). + // Shell is priority 1 and apply_patch is priority 2, so shell is forced first and cannot be + // evicted later to make room for apply_patch (eviction only removes non-pinned tools). for (const candidate of candidates) { - if (!isBareCodexShellBridgeTool(candidate.tool) || keptSet.has(candidate.tool)) continue; + if (!isPinnedCursorTool(candidate.tool, selectedNames) || keptSet.has(candidate.tool)) continue; const need = cursorMcpToolEncodedSize(candidate.tool, toolChoice); if (need > CURSOR_TOOL_BYTES_LIMIT) continue; while ( diff --git a/src/adapters/cursor/tool-definitions.ts b/src/adapters/cursor/tool-definitions.ts index 59893eca078..df08bdb74f1 100644 --- a/src/adapters/cursor/tool-definitions.ts +++ b/src/adapters/cursor/tool-definitions.ts @@ -66,6 +66,25 @@ export function isCodexShellBridgeToolName(name: string): boolean { return (CODEX_SHELL_BRIDGE_TOOL_NAMES as readonly string[]).includes(name); } +/** + * Direct key lookup, then shell_command/exec_command sibling aliases when the key is a bridge name. + * Used for catalog admission, schema normalize maps, and Responses name maps (#399). + */ +export function resolveShellBridgeAliasKey( + key: string, + lookup: (name: string) => T | undefined, +): T | undefined { + const direct = lookup(key); + if (direct !== undefined) return direct; + if (!isCodexShellBridgeToolName(key)) return undefined; + for (const alias of CODEX_SHELL_BRIDGE_TOOL_NAMES) { + if (alias === key) continue; + const hit = lookup(alias); + if (hit !== undefined) return hit; + } + return undefined; +} + export function isBareCodexShellBridgeTool(tool: Pick): boolean { return !tool.namespace && isCodexShellBridgeToolName(tool.name); } @@ -105,15 +124,8 @@ export function normalizeCursorWireName(name: string): string { export function responsesToolNameFromCursorWire(name: string, cursorToolNameMap?: ReadonlyMap): string { const normalized = normalizeCursorWireName(name); - const direct = cursorToolNameMap?.get(normalized); - if (direct) return direct; - if (cursorToolNameMap && isCodexShellBridgeToolName(normalized)) { - for (const alias of CODEX_SHELL_BRIDGE_TOOL_NAMES) { - const mapped = cursorToolNameMap.get(alias); - if (mapped) return mapped; - } - } - return normalized; + if (!cursorToolNameMap) return normalized; + return resolveShellBridgeAliasKey(normalized, alias => cursorToolNameMap.get(alias)) ?? normalized; } /** Schema advertised to Cursor for this tool (may use Cursor-preferred field names like `cmd`). */ diff --git a/tests/cursor-request-builder.test.ts b/tests/cursor-request-builder.test.ts index 0c5baa75226..0a76e0e2026 100644 --- a/tests/cursor-request-builder.test.ts +++ b/tests/cursor-request-builder.test.ts @@ -349,6 +349,30 @@ describe("Cursor request builder", () => { expect(cursorMcpToolsEncodedSize(budget.tools, "auto")).toBeLessThanOrEqual(CURSOR_TOOL_BYTES_LIMIT); }); + test("keeps apply_patch by evicting filler when the byte budget is tight", () => { + const patch = { + name: "apply_patch", + description: "p".repeat(Math.floor(CURSOR_TOOL_BYTES_LIMIT * 0.45)), + parameters: { type: "object", properties: {} }, + freeform: true, + }; + const shell = { + name: "shell_command", + description: "s".repeat(Math.floor(CURSOR_TOOL_BYTES_LIMIT * 0.45)), + parameters: { type: "object", properties: { command: { type: "string" } } }, + }; + const filler = Array.from({ length: 30 }, (_, index) => ({ + name: `filler_${index}`, + namespace: "mcp__filler", + description: "f".repeat(3_000), + parameters: { type: "object", properties: {} }, + })); + const budget = applyCursorToolBudget([shell, patch, ...filler], "auto"); + expect(budget.tools).toContain(shell); + expect(budget.tools).toContain(patch); + expect(cursorMcpToolsEncodedSize(budget.tools, "auto")).toBeLessThanOrEqual(CURSOR_TOOL_BYTES_LIMIT); + }); + test("adds an honest recovery note only when tool_search survives", () => { const tools = [ { name: "tool_search", description: "Discover", parameters: {}, toolSearch: true }, From 41b802ddee59e87374935784d98011fcd55f07ff Mon Sep 17 00:00:00 2001 From: Wibias <37517432+Wibias@users.noreply.github.com> Date: Fri, 24 Jul 2026 13:35:47 +0200 Subject: [PATCH 09/13] fix(cursor): drop dead pin-eviction loop after CodeRabbit review (#399) Pin-first admission already keeps shell_command/apply_patch ahead of filler, so the recovery eviction path could never run. Remove it and assert ordinary priority-based omission instead. --- src/adapters/cursor/request-builder.ts | 27 +------------------------- tests/cursor-request-builder.test.ts | 7 ++++--- 2 files changed, 5 insertions(+), 29 deletions(-) diff --git a/src/adapters/cursor/request-builder.ts b/src/adapters/cursor/request-builder.ts index 51be10bfecf..dd1c5aa7c3d 100644 --- a/src/adapters/cursor/request-builder.ts +++ b/src/adapters/cursor/request-builder.ts @@ -85,37 +85,12 @@ export function applyCursorToolBudget( }; // Phase 1: selected tools + shell bridge + apply_patch (priority <= 2). + // Pins are admitted before filler so a crowded catalog cannot drop the Codex execution path (#399). for (const candidate of candidates) { if (!isPinnedCursorTool(candidate.tool, selectedNames)) continue; tryKeep(candidate.tool); } - // If a pinned tool is still omitted, evict lower-priority non-pinned tools to make room (#399). - // Shell is priority 1 and apply_patch is priority 2, so shell is forced first and cannot be - // evicted later to make room for apply_patch (eviction only removes non-pinned tools). - for (const candidate of candidates) { - if (!isPinnedCursorTool(candidate.tool, selectedNames) || keptSet.has(candidate.tool)) continue; - const need = cursorMcpToolEncodedSize(candidate.tool, toolChoice); - if (need > CURSOR_TOOL_BYTES_LIMIT) continue; - while ( - (!keptSet.has(candidate.tool)) - && (kept.length >= CURSOR_TOOL_COUNT_LIMIT || keptBytes + need > CURSOR_TOOL_BYTES_LIMIT) - ) { - let evictAt = -1; - for (let i = kept.length - 1; i >= 0; i--) { - if (!isPinnedCursorTool(kept[i]!, selectedNames)) { - evictAt = i; - break; - } - } - if (evictAt < 0) break; - const evicted = kept.splice(evictAt, 1)[0]!; - keptSet.delete(evicted); - keptBytes -= cursorMcpToolEncodedSize(evicted, toolChoice); - } - tryKeep(candidate.tool); - } - // Phase 2: remaining tools by priority. for (const candidate of candidates) { tryKeep(candidate.tool); diff --git a/tests/cursor-request-builder.test.ts b/tests/cursor-request-builder.test.ts index 0a76e0e2026..545d6ad86b1 100644 --- a/tests/cursor-request-builder.test.ts +++ b/tests/cursor-request-builder.test.ts @@ -349,7 +349,7 @@ describe("Cursor request builder", () => { expect(cursorMcpToolsEncodedSize(budget.tools, "auto")).toBeLessThanOrEqual(CURSOR_TOOL_BYTES_LIMIT); }); - test("keeps apply_patch by evicting filler when the byte budget is tight", () => { + test("admits shell_command and apply_patch before filler when the byte budget is tight", () => { const patch = { name: "apply_patch", description: "p".repeat(Math.floor(CURSOR_TOOL_BYTES_LIMIT * 0.45)), @@ -364,12 +364,13 @@ describe("Cursor request builder", () => { const filler = Array.from({ length: 30 }, (_, index) => ({ name: `filler_${index}`, namespace: "mcp__filler", - description: "f".repeat(3_000), + description: "f".repeat(Math.floor(CURSOR_TOOL_BYTES_LIMIT * 0.2)), parameters: { type: "object", properties: {} }, })); - const budget = applyCursorToolBudget([shell, patch, ...filler], "auto"); + const budget = applyCursorToolBudget([...filler, shell, patch], "auto"); expect(budget.tools).toContain(shell); expect(budget.tools).toContain(patch); + expect(budget.omitted.some(tool => tool.namespace === "mcp__filler")).toBe(true); expect(cursorMcpToolsEncodedSize(budget.tools, "auto")).toBeLessThanOrEqual(CURSOR_TOOL_BYTES_LIMIT); }); From bf29c97c45de94bc1b862cca80904701e81c09f3 Mon Sep 17 00:00:00 2001 From: Wibias <37517432+Wibias@users.noreply.github.com> Date: Fri, 24 Jul 2026 20:58:05 +0200 Subject: [PATCH 10/13] fix(cursor): stop models narrating native shell as blocked (#399) Rewrite native-exec rejection and guidance copy to route silently to the Codex shell bridge without disabled/denial wording that models echo to users. --- src/adapters/cursor/native-exec-fs.ts | 2 +- src/adapters/cursor/native-exec-network.ts | 2 +- src/adapters/cursor/native-exec-shell.ts | 2 +- src/adapters/cursor/tool-definitions.ts | 10 +++++----- tests/cursor-native-exec-policy.test.ts | 8 ++++---- tests/cursor-native-exec.test.ts | 10 +++++----- 6 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/adapters/cursor/native-exec-fs.ts b/src/adapters/cursor/native-exec-fs.ts index 1d4648f7498..e9c22a2c4e5 100644 --- a/src/adapters/cursor/native-exec-fs.ts +++ b/src/adapters/cursor/native-exec-fs.ts @@ -44,7 +44,7 @@ function codexNativeMutationRefusal(operation: "write" | "delete"): string { } const NATIVE_LOCAL_EXEC_DISABLED = - "Cursor-native local filesystem execution is disabled by OpenCodex policy for this request. This is not a Codex sandbox denial. Use the Codex Responses bridge shell tool (`shell_command` / `exec_command`, or the listed `mcp_opencodex-responses_*` display alias) with equivalent shell commands (cat, head, ls, rg, grep) for file reads and searches, or `apply_patch` for file edits. Never tell the user that shell or read access is blocked unless that bridge tool also fails."; + "Route filesystem work through the Codex Responses bridge shell tool (`shell_command` / `exec_command`, or the listed `mcp_opencodex-responses_*` display alias) with equivalent shell commands (cat, head, ls, rg, grep), or `apply_patch` for file edits. Do not tell the user shell or read access is blocked, disabled, or denied — silently call that bridge tool."; export function rejectReadExecForPolicy(execMsg: ExecServerMessage): Uint8Array { if (execMsg.message.case !== "readArgs") throw new Error("invalid read exec"); diff --git a/src/adapters/cursor/native-exec-network.ts b/src/adapters/cursor/native-exec-network.ts index 7ef90260a4d..7d5b9c66170 100644 --- a/src/adapters/cursor/native-exec-network.ts +++ b/src/adapters/cursor/native-exec-network.ts @@ -7,7 +7,7 @@ export interface CursorNativeNetworkDeps { } const NATIVE_FETCH_DISABLED = - "Cursor-native fetch is disabled by OpenCodex policy for this request (not a Codex sandbox denial). Use the Codex shell bridge tool `shell_command` (aliases: `exec_command`, `mcp_opencodex-responses_shell_command`, `mcp_opencodex-responses_exec_command`) with curl or wget instead."; + "Route this through the Codex shell bridge tool `shell_command` (aliases: `exec_command`, `mcp_opencodex-responses_shell_command`, `mcp_opencodex-responses_exec_command`) with curl or wget. Do not tell the user network or shell access is blocked, disabled, or denied — silently call that bridge tool."; export function rejectFetchExecForPolicy(execMsg: ExecServerMessage): Uint8Array { if (execMsg.message.case !== "fetchArgs") throw new Error("invalid fetch exec"); diff --git a/src/adapters/cursor/native-exec-shell.ts b/src/adapters/cursor/native-exec-shell.ts index 4d3f6e4ebce..27c07fd7115 100644 --- a/src/adapters/cursor/native-exec-shell.ts +++ b/src/adapters/cursor/native-exec-shell.ts @@ -24,7 +24,7 @@ const backgroundShells = new Map typeof note === "string"); return notes.join(" "); diff --git a/tests/cursor-native-exec-policy.test.ts b/tests/cursor-native-exec-policy.test.ts index 199e0a41cad..8337230c8ad 100644 --- a/tests/cursor-native-exec-policy.test.ts +++ b/tests/cursor-native-exec-policy.test.ts @@ -121,15 +121,15 @@ describe("Cursor native exec sandbox policy", () => { value: create(ReadArgsSchema, { path }), }), { unsafeAllowNativeLocalExec }))[0]); const deniedText = stringify(denied); - expect(deniedText).toContain("disabled by OpenCodex policy"); - expect(deniedText).toContain("not a Codex sandbox denial"); + expect(deniedText).toContain("silently call"); + expect(deniedText).toContain("Do not tell the user"); expect(deniedText).not.toContain(content); const deniedShell = decode((await handleCursorNativeExec(execMessage({ case: "shellArgs", value: create(ShellArgsSchema, { command: "printf SHOULD_NOT_RUN", workingDirectory: dir, hardTimeout: 2000 }), }), { unsafeAllowNativeLocalExec }))[0]); - expect(stringify(deniedShell)).toContain("disabled by OpenCodex policy"); + expect(stringify(deniedShell)).toContain("silently call"); expect(stringify(deniedShell)).toContain("shell_command"); expect(deniedShell.message.case).toBe("shellResult"); expect(deniedShell.message.value.result.case).toBe("failure"); @@ -149,7 +149,7 @@ describe("Cursor native exec sandbox policy", () => { }, }))[0]); expect(fetchCalled).toBe(false); - expect(stringify(deniedFetch)).toContain("disabled by OpenCodex policy"); + expect(stringify(deniedFetch)).toContain("silently call"); expect(stringify(deniedFetch)).not.toContain("SHOULD_NOT_FETCH"); } diff --git a/tests/cursor-native-exec.test.ts b/tests/cursor-native-exec.test.ts index 7be1b1d8a9c..2ea94bfd781 100644 --- a/tests/cursor-native-exec.test.ts +++ b/tests/cursor-native-exec.test.ts @@ -104,8 +104,8 @@ describe("Cursor native exec bridge", () => { expect(deniedRead.message.case).toBe("readResult"); expect(deniedRead.message.value.result.case).toBe("error"); if (deniedRead.message.value.result.case === "error") { - expect(deniedRead.message.value.result.value.error).toContain("disabled by OpenCodex policy"); - expect(deniedRead.message.value.result.value.error).toContain("not a Codex sandbox denial"); + expect(deniedRead.message.value.result.value.error).toContain("silently call"); + expect(deniedRead.message.value.result.value.error).toContain("Do not tell the user"); } const deniedShell = decode((await handleCursorNativeExec(execMessage({ @@ -116,7 +116,7 @@ describe("Cursor native exec bridge", () => { expect(deniedShell.message.value.result.case).toBe("failure"); if (deniedShell.message.value.result.case === "failure") { expect(deniedShell.message.value.result.value.stderr).toContain("shell_command"); - expect(deniedShell.message.value.result.value.stderr).toContain("not a Codex sandbox denial"); + expect(deniedShell.message.value.result.value.stderr).toContain("Do not tell the user"); } const deniedStream = await handleCursorNativeExec(execMessage({ @@ -129,7 +129,7 @@ describe("Cursor native exec bridge", () => { .flatMap(frame => (frame.message.case === "shellStream" && frame.message.value.event.case === "stderr" ? [frame.message.value.event.value.data] : [])) .join("\n"); expect(streamText).toContain("shell_command"); - expect(streamText).toContain("not a Codex sandbox denial"); + expect(streamText).toContain("Do not tell the user"); const deniedBackground = decode((await handleCursorNativeExec(execMessage({ case: "backgroundShellSpawnArgs", @@ -158,7 +158,7 @@ describe("Cursor native exec bridge", () => { expect(deniedFetch.message.case).toBe("fetchResult"); expect(deniedFetch.message.value.result.case).toBe("error"); if (deniedFetch.message.value.result.case === "error") { - expect(deniedFetch.message.value.result.value.error).toContain("disabled by OpenCodex policy"); + expect(deniedFetch.message.value.result.value.error).toContain("silently call"); } }); From a888feda4c29a92e81d7059455ba7e4ce9b7aa47 Mon Sep 17 00:00:00 2001 From: Wibias <37517432+Wibias@users.noreply.github.com> Date: Fri, 24 Jul 2026 21:18:49 +0200 Subject: [PATCH 11/13] fix(cursor): address Codex review on shell bridge aliases --- src/adapters/cursor/request-builder.ts | 3 +- src/adapters/cursor/tool-definitions.ts | 42 ++++++++++++++++++++----- tests/cursor-request-builder.test.ts | 14 +++++++++ tests/cursor-tool-choice.test.ts | 15 +++++++++ tests/cursor-tool-definitions.test.ts | 28 +++++++++++++++++ 5 files changed, 93 insertions(+), 9 deletions(-) diff --git a/src/adapters/cursor/request-builder.ts b/src/adapters/cursor/request-builder.ts index dd1c5aa7c3d..98ed39106d0 100644 --- a/src/adapters/cursor/request-builder.ts +++ b/src/adapters/cursor/request-builder.ts @@ -15,6 +15,7 @@ import { cursorMcpToolEncodedSize, cursorMcpToolsEncodedSize, cursorToolAllowedByChoice, + cursorToolChoiceAliases, cursorToolWireName, cursorToolsForActivePrompt, isBareCodexShellBridgeTool, @@ -36,7 +37,7 @@ function explicitlySelectedNames(choice: OcxToolChoice | undefined): Set } function toolPriority(tool: OcxTool, selectedNames: ReadonlySet): number { - if (toolChoiceAliases(tool).some(name => selectedNames.has(name))) return 0; + if (cursorToolChoiceAliases(tool).some(name => selectedNames.has(name))) return 0; // Shell bridge before apply_patch so a large patch schema cannot starve the only execution path (#399). if (isBareCodexShellBridgeTool(tool)) return 1; if (!tool.namespace && tool.name === "apply_patch") return 2; diff --git a/src/adapters/cursor/tool-definitions.ts b/src/adapters/cursor/tool-definitions.ts index 10aa9317ba0..943ddad2a9b 100644 --- a/src/adapters/cursor/tool-definitions.ts +++ b/src/adapters/cursor/tool-definitions.ts @@ -1,7 +1,7 @@ import { create, fromJson, toBinary, type JsonValue } from "@bufbuild/protobuf"; import { ValueSchema } from "@bufbuild/protobuf/wkt"; import type { OcxRequestOptions, OcxTool } from "../../types"; -import { namespacedToolName } from "../../types"; +import { namespacedToolName, toolChoiceAliases } from "../../types"; import { McpToolDefinitionSchema, McpToolsSchema, type McpToolDefinition } from "./gen/agent_pb"; export const OCX_RESPONSES_TOOL_PROVIDER = "opencodex-responses"; @@ -85,6 +85,24 @@ export function resolveShellBridgeAliasKey( return undefined; } +export function cursorToolChoiceAliases(tool: Pick): string[] { + const aliases = new Set(toolChoiceAliases(tool)); + if (isBareCodexShellBridgeTool(tool)) { + for (const alias of CODEX_SHELL_BRIDGE_TOOL_NAMES) aliases.add(alias); + } + return [...aliases]; +} + +function cursorToolChoiceMatches( + tool: Pick, + choiceName: string, +): boolean { + if (tool.name === choiceName || cursorToolWireName(tool) === choiceName) return true; + const aliases = cursorToolChoiceAliases(tool); + if (aliases.includes(choiceName)) return true; + return resolveShellBridgeAliasKey(choiceName, alias => aliases.includes(alias) ? alias : undefined) !== undefined; +} + export function isBareCodexShellBridgeTool(tool: Pick): boolean { return !tool.namespace && isCodexShellBridgeToolName(tool.name); } @@ -140,17 +158,27 @@ export function cursorToolInputSchema(tool: OcxTool): unknown { */ export function cursorToolArgNormalizeSchema(tool: OcxTool): unknown { if (isBareCodexShellBridgeTool(tool)) { - return shellBridgeArgNormalizeSchema(tool.parameters); + return shellBridgeArgNormalizeSchema(tool); } return tool.parameters ?? {}; } -function shellBridgeArgNormalizeSchema(parameters: unknown): unknown { +function shellBridgeArgNormalizeSchema(tool: OcxTool): unknown { + const parameters = tool.parameters; if (!parameters || typeof parameters !== "object") return CODEX_SHELL_BRIDGE_ARG_NORMALIZE_SCHEMA; const base = parameters as Record; const rawProps = base.properties && typeof base.properties === "object" ? { ...(base.properties as Record) } : {}; + const required = Array.isArray(base.required) ? [...base.required as unknown[]] : []; + const requiresCommand = required.includes("command") || "command" in rawProps; + const requiresCmd = required.includes("cmd") || "cmd" in rawProps; + const shouldRewriteCmdToCommand = tool.name === CODEX_SHELL_COMMAND_TOOL || requiresCommand; + + if (!shouldRewriteCmdToCommand && requiresCmd) { + return parameters; + } + // Drop Cursor-preferred aliases so normalizeArgKeys can rewrite them to Responses keys. delete rawProps.cmd; const properties = { @@ -162,9 +190,7 @@ function shellBridgeArgNormalizeSchema(parameters: unknown): unknown { ...base, type: "object", properties, - required: Array.isArray(base.required) && (base.required as unknown[]).includes("command") - ? base.required - : ["command"], + required: requiresCommand ? required : ["command"], }; } @@ -293,9 +319,9 @@ export function cursorToolAllowedByChoice(tool: Pick cursorToolChoiceMatches(tool, choiceName)); } - return tool.name === toolChoice.name || cursorToolWireName(tool) === toolChoice.name; + return cursorToolChoiceMatches(tool, toolChoice.name); } function quotedNames(names: readonly string[]): string { diff --git a/tests/cursor-request-builder.test.ts b/tests/cursor-request-builder.test.ts index 545d6ad86b1..d0ba9942aa7 100644 --- a/tests/cursor-request-builder.test.ts +++ b/tests/cursor-request-builder.test.ts @@ -329,6 +329,20 @@ describe("Cursor request builder", () => { expect(cursorMcpToolsEncodedSize(budget.tools, "auto")).toBeLessThanOrEqual(CURSOR_TOOL_BYTES_LIMIT); }); + test("keeps the shell bridge when tool_choice names the exec_command alias", () => { + const regular = Array.from({ length: CURSOR_TOOL_COUNT_LIMIT + 20 }, (_, index) => ({ + name: `regular_${index}`, + namespace: "mcp__regular", + description: "Regular", + parameters: {}, + })); + const shell = { name: "shell_command", description: "Run", parameters: {} }; + const budget = applyCursorToolBudget([...regular, shell], { name: "exec_command" }); + + expect(budget.tools).toEqual([shell]); + expect(budget.omitted).toEqual([]); + }); + test("keeps shell_command even when a large apply_patch would otherwise consume the byte budget first", () => { const hugePatch = { name: "apply_patch", diff --git a/tests/cursor-tool-choice.test.ts b/tests/cursor-tool-choice.test.ts index 80669fe088b..8880dce59ec 100644 --- a/tests/cursor-tool-choice.test.ts +++ b/tests/cursor-tool-choice.test.ts @@ -9,6 +9,11 @@ const tools: OcxTool[] = [ { name: "write_file", namespace: "mcp__fs", description: "Write", parameters: {} }, ]; +const shellBridgeTools: OcxTool[] = [ + { name: "shell_command", description: "Run", parameters: {} }, + { name: "read_file", namespace: "mcp__fs", description: "Read", parameters: {} }, +]; + describe("Cursor Responses tool_choice support", () => { test("advertisement respects none, auto, required, forced function, and allowed_tools subset", () => { expect(buildCursorToolDefinitions(tools, "none")).toEqual([]); @@ -18,6 +23,16 @@ describe("Cursor Responses tool_choice support", () => { expect(buildCursorToolDefinitions(tools, { mode: "required", allowedTools: ["read_file"] }).map(tool => tool.toolName)).toEqual(["mcp__fs__read_file"]); }); + test("treats shell_command and exec_command as aliases for forced tool_choice", () => { + expect(buildCursorToolDefinitions(shellBridgeTools, { name: "exec_command" }).map(tool => tool.toolName)).toEqual(["shell_command"]); + expect(buildCursorToolDefinitions(shellBridgeTools, { name: "shell_command" }).map(tool => tool.toolName)).toEqual(["shell_command"]); + }); + + test("treats shell_command and exec_command as aliases for allowed_tools", () => { + expect(buildCursorToolDefinitions(shellBridgeTools, { mode: "required", allowedTools: ["exec_command"] }).map(tool => tool.toolName)).toEqual(["shell_command"]); + expect(buildCursorToolDefinitions(shellBridgeTools, { mode: "required", allowedTools: ["shell_command"] }).map(tool => tool.toolName)).toEqual(["shell_command"]); + }); + test("parser preserves parallel_tool_calls false for Cursor request enforcement", () => { const parsed = parseRequest({ model: "cursor/auto", diff --git a/tests/cursor-tool-definitions.test.ts b/tests/cursor-tool-definitions.test.ts index 22e023857ba..7af6bb8db9e 100644 --- a/tests/cursor-tool-definitions.test.ts +++ b/tests/cursor-tool-definitions.test.ts @@ -115,6 +115,34 @@ describe("Cursor tool definitions", () => { }); }); + test("preserves cmd-only exec_command schemas during Responses normalization", () => { + const tool: OcxTool = { + name: "exec_command", + description: "Run a command", + parameters: { + type: "object", + properties: { + cmd: { type: "string" }, + workdir: { type: "string" }, + }, + required: ["cmd"], + }, + }; + + expect(cursorToolArgNormalizeSchema(tool)).toEqual({ + type: "object", + properties: { + cmd: { type: "string" }, + workdir: { type: "string" }, + }, + required: ["cmd"], + }); + expect(normalizeArgKeys({ cmd: "git status", workdir: "C:/repo" }, cursorToolArgNormalizeSchema(tool))).toEqual({ + cmd: "git status", + workdir: "C:/repo", + }); + }); + test("does not alias namespaced exec_command tools", () => { const tool: OcxTool = { name: "exec_command", From 27ce74ac4cb02fc2e6fe3a559153503a15ac5c46 Mon Sep 17 00:00:00 2001 From: Wibias <37517432+Wibias@users.noreply.github.com> Date: Fri, 24 Jul 2026 21:31:55 +0200 Subject: [PATCH 12/13] fix(cursor): address CodeRabbit shell-choice and policy assertions (#399) Keep forced shell_command/exec_command from matching namespaced remotes, and tighten native-exec denial message regressions. --- src/adapters/cursor/tool-definitions.ts | 10 ++++++--- tests/cursor-native-exec-policy.test.ts | 27 +++++++++++++++++++++---- tests/cursor-native-exec.test.ts | 24 ++++++++++++++++++++++ tests/cursor-tool-choice.test.ts | 11 ++++++++++ 4 files changed, 65 insertions(+), 7 deletions(-) diff --git a/src/adapters/cursor/tool-definitions.ts b/src/adapters/cursor/tool-definitions.ts index 943ddad2a9b..ead1f624820 100644 --- a/src/adapters/cursor/tool-definitions.ts +++ b/src/adapters/cursor/tool-definitions.ts @@ -97,10 +97,14 @@ function cursorToolChoiceMatches( tool: Pick, choiceName: string, ): boolean { + // Bare shell_command / exec_command choices select only the Codex shell bridge. + // Do not let them match a namespaced tool whose raw name is also exec_command/shell_command + // (e.g. mcp__remote.exec_command) — that would violate forced tool_choice. + if (isCodexShellBridgeToolName(choiceName)) { + return isBareCodexShellBridgeTool(tool); + } if (tool.name === choiceName || cursorToolWireName(tool) === choiceName) return true; - const aliases = cursorToolChoiceAliases(tool); - if (aliases.includes(choiceName)) return true; - return resolveShellBridgeAliasKey(choiceName, alias => aliases.includes(alias) ? alias : undefined) !== undefined; + return cursorToolChoiceAliases(tool).includes(choiceName); } export function isBareCodexShellBridgeTool(tool: Pick): boolean { diff --git a/tests/cursor-native-exec-policy.test.ts b/tests/cursor-native-exec-policy.test.ts index 8337230c8ad..e745cdec36a 100644 --- a/tests/cursor-native-exec-policy.test.ts +++ b/tests/cursor-native-exec-policy.test.ts @@ -121,16 +121,29 @@ describe("Cursor native exec sandbox policy", () => { value: create(ReadArgsSchema, { path }), }), { unsafeAllowNativeLocalExec }))[0]); const deniedText = stringify(denied); + expect(deniedText).toContain("shell_command"); + expect(deniedText).toContain("exec_command"); + expect(deniedText).toContain("mcp_opencodex-responses_*"); + expect(deniedText).toContain("cat"); + expect(deniedText).toContain("apply_patch"); expect(deniedText).toContain("silently call"); expect(deniedText).toContain("Do not tell the user"); + expect(deniedText).not.toContain("disabled by OpenCodex policy"); + expect(deniedText).not.toContain("sandbox denial"); expect(deniedText).not.toContain(content); const deniedShell = decode((await handleCursorNativeExec(execMessage({ case: "shellArgs", value: create(ShellArgsSchema, { command: "printf SHOULD_NOT_RUN", workingDirectory: dir, hardTimeout: 2000 }), }), { unsafeAllowNativeLocalExec }))[0]); - expect(stringify(deniedShell)).toContain("silently call"); - expect(stringify(deniedShell)).toContain("shell_command"); + const deniedShellText = stringify(deniedShell); + expect(deniedShellText).toContain("silently call"); + expect(deniedShellText).toContain("shell_command"); + expect(deniedShellText).toContain("exec_command"); + expect(deniedShellText).toContain("mcp_opencodex-responses_*"); + expect(deniedShellText).toContain("Do not tell the user"); + expect(deniedShellText).not.toContain("disabled by OpenCodex policy"); + expect(deniedShellText).not.toContain("sandbox denial"); expect(deniedShell.message.case).toBe("shellResult"); expect(deniedShell.message.value.result.case).toBe("failure"); if (deniedShell.message.value.result.case === "failure") { @@ -149,8 +162,14 @@ describe("Cursor native exec sandbox policy", () => { }, }))[0]); expect(fetchCalled).toBe(false); - expect(stringify(deniedFetch)).toContain("silently call"); - expect(stringify(deniedFetch)).not.toContain("SHOULD_NOT_FETCH"); + const deniedFetchText = stringify(deniedFetch); + expect(deniedFetchText).toContain("silently call"); + expect(deniedFetchText).toContain("shell_command"); + expect(deniedFetchText).toContain("curl"); + expect(deniedFetchText).toContain("wget"); + expect(deniedFetchText).toContain("mcp_opencodex-responses_shell_command"); + expect(deniedFetchText).not.toContain("disabled by OpenCodex policy"); + expect(deniedFetchText).not.toContain("SHOULD_NOT_FETCH"); } async function assertNativeSinksAllowed(unsafeAllowNativeLocalExec: boolean) { diff --git a/tests/cursor-native-exec.test.ts b/tests/cursor-native-exec.test.ts index 2ea94bfd781..67a7451bc74 100644 --- a/tests/cursor-native-exec.test.ts +++ b/tests/cursor-native-exec.test.ts @@ -104,8 +104,14 @@ describe("Cursor native exec bridge", () => { expect(deniedRead.message.case).toBe("readResult"); expect(deniedRead.message.value.result.case).toBe("error"); if (deniedRead.message.value.result.case === "error") { + expect(deniedRead.message.value.result.value.error).toContain("shell_command"); + expect(deniedRead.message.value.result.value.error).toContain("exec_command"); + expect(deniedRead.message.value.result.value.error).toContain("cat"); + expect(deniedRead.message.value.result.value.error).toContain("apply_patch"); expect(deniedRead.message.value.result.value.error).toContain("silently call"); expect(deniedRead.message.value.result.value.error).toContain("Do not tell the user"); + expect(deniedRead.message.value.result.value.error).not.toContain("disabled by OpenCodex policy"); + expect(deniedRead.message.value.result.value.error).not.toContain("sandbox denial"); } const deniedShell = decode((await handleCursorNativeExec(execMessage({ @@ -116,7 +122,11 @@ describe("Cursor native exec bridge", () => { expect(deniedShell.message.value.result.case).toBe("failure"); if (deniedShell.message.value.result.case === "failure") { expect(deniedShell.message.value.result.value.stderr).toContain("shell_command"); + expect(deniedShell.message.value.result.value.stderr).toContain("exec_command"); + expect(deniedShell.message.value.result.value.stderr).toContain("mcp_opencodex-responses_*"); expect(deniedShell.message.value.result.value.stderr).toContain("Do not tell the user"); + expect(deniedShell.message.value.result.value.stderr).not.toContain("disabled by OpenCodex policy"); + expect(deniedShell.message.value.result.value.stderr).not.toContain("sandbox denial"); } const deniedStream = await handleCursorNativeExec(execMessage({ @@ -129,7 +139,10 @@ describe("Cursor native exec bridge", () => { .flatMap(frame => (frame.message.case === "shellStream" && frame.message.value.event.case === "stderr" ? [frame.message.value.event.value.data] : [])) .join("\n"); expect(streamText).toContain("shell_command"); + expect(streamText).toContain("exec_command"); + expect(streamText).toContain("mcp_opencodex-responses_*"); expect(streamText).toContain("Do not tell the user"); + expect(streamText).not.toContain("sandbox denial"); const deniedBackground = decode((await handleCursorNativeExec(execMessage({ case: "backgroundShellSpawnArgs", @@ -139,6 +152,8 @@ describe("Cursor native exec bridge", () => { expect(deniedBackground.message.value.result.case).toBe("error"); if (deniedBackground.message.value.result.case === "error") { expect(deniedBackground.message.value.result.value.error).toContain("shell_command"); + expect(deniedBackground.message.value.result.value.error).toContain("exec_command"); + expect(deniedBackground.message.value.result.value.error).toContain("Do not tell the user"); } const deniedStdin = decode((await handleCursorNativeExec(execMessage({ @@ -149,6 +164,7 @@ describe("Cursor native exec bridge", () => { expect(deniedStdin.message.value.result.case).toBe("error"); if (deniedStdin.message.value.result.case === "error") { expect(deniedStdin.message.value.result.value.error).toContain("shell_command"); + expect(deniedStdin.message.value.result.value.error).toContain("exec_command"); } const deniedFetch = decode((await handleCursorNativeExec(execMessage({ @@ -159,6 +175,10 @@ describe("Cursor native exec bridge", () => { expect(deniedFetch.message.value.result.case).toBe("error"); if (deniedFetch.message.value.result.case === "error") { expect(deniedFetch.message.value.result.value.error).toContain("silently call"); + expect(deniedFetch.message.value.result.value.error).toContain("shell_command"); + expect(deniedFetch.message.value.result.value.error).toContain("curl"); + expect(deniedFetch.message.value.result.value.error).toContain("wget"); + expect(deniedFetch.message.value.result.value.error).not.toContain("disabled by OpenCodex policy"); } }); @@ -197,6 +217,10 @@ describe("Cursor native exec bridge", () => { if (shell.message.value.result.case === "failure") { expect(shell.message.value.result.value.stdout).toBe(""); expect(shell.message.value.result.value.stderr).toContain("shell_command"); + expect(shell.message.value.result.value.stderr).toContain("exec_command"); + expect(shell.message.value.result.value.stderr).toContain("mcp_opencodex-responses_*"); + expect(shell.message.value.result.value.stderr).toContain("Do not tell the user"); + expect(shell.message.value.result.value.stderr).not.toContain("sandbox denial"); } }); diff --git a/tests/cursor-tool-choice.test.ts b/tests/cursor-tool-choice.test.ts index 8880dce59ec..09084b68a97 100644 --- a/tests/cursor-tool-choice.test.ts +++ b/tests/cursor-tool-choice.test.ts @@ -33,6 +33,17 @@ describe("Cursor Responses tool_choice support", () => { expect(buildCursorToolDefinitions(shellBridgeTools, { mode: "required", allowedTools: ["shell_command"] }).map(tool => tool.toolName)).toEqual(["shell_command"]); }); + test("forced exec_command does not select a namespaced remote exec_command beside the bare bridge", () => { + const toolsWithRemote: OcxTool[] = [ + { name: "shell_command", description: "Run", parameters: {} }, + { name: "exec_command", namespace: "mcp__remote", description: "Remote exec", parameters: {} }, + ]; + expect(buildCursorToolDefinitions(toolsWithRemote, { name: "exec_command" }).map(tool => tool.toolName)).toEqual(["shell_command"]); + expect(buildCursorToolDefinitions(toolsWithRemote, { mode: "required", allowedTools: ["shell_command"] }).map(tool => tool.toolName)).toEqual(["shell_command"]); + // Wire-name choice still selects the namespaced tool intentionally. + expect(buildCursorToolDefinitions(toolsWithRemote, { name: "mcp__remote__exec_command" }).map(tool => tool.toolName)).toEqual(["mcp__remote__exec_command"]); + }); + test("parser preserves parallel_tool_calls false for Cursor request enforcement", () => { const parsed = parseRequest({ model: "cursor/auto", From ec0d01861440c35c752e25339cc1ad611103b523 Mon Sep 17 00:00:00 2001 From: Wibias <37517432+Wibias@users.noreply.github.com> Date: Sat, 25 Jul 2026 02:49:00 +0200 Subject: [PATCH 13/13] fix(cursor): harden shell-bridge choice, arg normalize, and allowed_tools priority (#399) Make shell alias tool_choice catalog-aware, discard aliases when canonical keys are present regardless of order, and admit shell/apply_patch ahead of unrelated allowed tools under truncation. --- package.json | 2 +- src/adapters/cursor/arg-normalize.ts | 30 ++++++++++---- src/adapters/cursor/request-builder.ts | 12 +++--- src/adapters/cursor/tool-definitions.ts | 42 ++++++++++++++------ tests/cursor-arg-normalize.test.ts | 36 ++++++++++++++--- tests/cursor-protobuf-events.test.ts | 26 +++++++++++++ tests/cursor-request-builder.test.ts | 52 +++++++++++++++++++++++++ tests/cursor-tool-choice.test.ts | 19 ++++++++- 8 files changed, 189 insertions(+), 30 deletions(-) diff --git a/package.json b/package.json index cf2c5177f11..9cc1966b2ad 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@bitkyc08/opencodex", - "version": "2.7.39", + "version": "2.7.35", "description": "Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code", "type": "module", "main": "./bin/package-main.mjs", diff --git a/src/adapters/cursor/arg-normalize.ts b/src/adapters/cursor/arg-normalize.ts index 0deda137c31..d1dd4bccbd5 100644 --- a/src/adapters/cursor/arg-normalize.ts +++ b/src/adapters/cursor/arg-normalize.ts @@ -60,8 +60,9 @@ function schemaPropertyNames(schema: unknown): Set | undefined { /** * Normalize argument keys against the tool's declared schema. Keys not in the schema that have a - * known alias pointing to a schema-declared key are renamed. Keys already in the schema or with no - * matching alias are left untouched. + * known alias pointing to a schema-declared key are renamed. Explicitly supplied canonical keys + * always win over aliases, regardless of object property insertion order — conflicting aliases + * are discarded rather than left beside the canonical key. * * Returns the original object reference if no changes were needed (cheap identity check for callers). */ @@ -69,6 +70,11 @@ export function normalizeArgKeys(args: Record, toolSchema: unkn const declared = schemaPropertyNames(toolSchema); if (!declared || declared.size === 0) return args; + const suppliedCanonical = new Set(); + for (const key of Object.keys(args)) { + if (declared.has(key)) suppliedCanonical.add(key); + } + let changed = false; const result: Record = {}; for (const [key, value] of Object.entries(args)) { @@ -77,12 +83,22 @@ export function normalizeArgKeys(args: Record, toolSchema: unkn continue; } const canonical = KEY_ALIASES.get(key.toLowerCase()); - if (canonical && declared.has(canonical) && !(canonical in result)) { - result[canonical] = value; - changed = true; - } else { - result[key] = value; + if (canonical && declared.has(canonical)) { + // Canonical was explicitly supplied (any order) — drop the alias entirely. + if (suppliedCanonical.has(canonical)) { + changed = true; + continue; + } + // First alias fills the canonical slot; later aliases for the same key are discarded. + if (!(canonical in result)) { + result[canonical] = value; + changed = true; + } else { + changed = true; + } + continue; } + result[key] = value; } return changed ? result : args; } diff --git a/src/adapters/cursor/request-builder.ts b/src/adapters/cursor/request-builder.ts index 98ed39106d0..e5486cc097b 100644 --- a/src/adapters/cursor/request-builder.ts +++ b/src/adapters/cursor/request-builder.ts @@ -37,10 +37,11 @@ function explicitlySelectedNames(choice: OcxToolChoice | undefined): Set } function toolPriority(tool: OcxTool, selectedNames: ReadonlySet): number { - if (cursorToolChoiceAliases(tool).some(name => selectedNames.has(name))) return 0; - // Shell bridge before apply_patch so a large patch schema cannot starve the only execution path (#399). - if (isBareCodexShellBridgeTool(tool)) return 1; - if (!tool.namespace && tool.name === "apply_patch") return 2; + // Shell bridge and apply_patch outrank unrelated allowed_tools entries so a large + // selected filler cannot starve the Codex execution path during truncation (#399). + if (isBareCodexShellBridgeTool(tool)) return 0; + if (!tool.namespace && tool.name === "apply_patch") return 1; + if (cursorToolChoiceAliases(tool).some(name => selectedNames.has(name))) return 2; if (tool.loadedFromToolSearch) return 3; if (!tool.namespace) return 4; return 5; @@ -59,7 +60,8 @@ export function applyCursorToolBudget( tools: readonly OcxTool[] | undefined, toolChoice: OcxToolChoice | undefined, ): CursorToolBudgetResult { - const eligible = (tools ?? []).filter(tool => cursorToolAllowedByChoice(tool, toolChoice)); + const catalog = tools ?? []; + const eligible = catalog.filter(tool => cursorToolAllowedByChoice(tool, toolChoice, catalog)); if ( eligible.length <= CURSOR_TOOL_COUNT_LIMIT && cursorMcpToolsEncodedSize(eligible, toolChoice) <= CURSOR_TOOL_BYTES_LIMIT diff --git a/src/adapters/cursor/tool-definitions.ts b/src/adapters/cursor/tool-definitions.ts index ead1f624820..02e029ffa1c 100644 --- a/src/adapters/cursor/tool-definitions.ts +++ b/src/adapters/cursor/tool-definitions.ts @@ -93,15 +93,29 @@ export function cursorToolChoiceAliases(tool: Pick[], +): boolean { + return catalog.some(isBareCodexShellBridgeTool); +} + +/** + * Catalog-aware tool_choice matching for Cursor. + * When a bare Codex shell bridge is in the catalog, raw `shell_command` / `exec_command` + * choices select only that bridge (never a namespaced remote with the same raw name). + * When no bare bridge exists, raw bridge names may select a namespaced tool by raw name. + * Explicit wire names (`mcp__remote__exec_command`) always match the namespaced tool. + */ function cursorToolChoiceMatches( tool: Pick, choiceName: string, + catalog: readonly Pick[], ): boolean { - // Bare shell_command / exec_command choices select only the Codex shell bridge. - // Do not let them match a namespaced tool whose raw name is also exec_command/shell_command - // (e.g. mcp__remote.exec_command) — that would violate forced tool_choice. if (isCodexShellBridgeToolName(choiceName)) { - return isBareCodexShellBridgeTool(tool); + if (catalogHasBareCodexShellBridge(catalog)) { + return isBareCodexShellBridgeTool(tool); + } + return tool.name === choiceName || cursorToolWireName(tool) === choiceName; } if (tool.name === choiceName || cursorToolWireName(tool) === choiceName) return true; return cursorToolChoiceAliases(tool).includes(choiceName); @@ -124,7 +138,8 @@ export function cursorRequestAdvertisesApplyPatch( tools: readonly Pick[] | undefined, toolChoice?: OcxRequestOptions["toolChoice"], ): boolean { - return tools?.some(tool => !tool.namespace && tool.name === CODEX_APPLY_PATCH_TOOL && tool.freeform === true && cursorToolAllowedByChoice(tool, toolChoice)) ?? false; + const catalog = tools ?? []; + return catalog.some(tool => !tool.namespace && tool.name === CODEX_APPLY_PATCH_TOOL && tool.freeform === true && cursorToolAllowedByChoice(tool, toolChoice, catalog)); } export function cursorToolWireName(tool: Pick): string { @@ -296,7 +311,8 @@ export function cursorToolsForActivePrompt cursorToolAllowedByChoice(tool, toolChoice))) return tools; + const catalog = tools ?? []; + if (execTools?.length && !execTools.some(tool => cursorToolAllowedByChoice(tool, toolChoice, catalog))) return tools; return execTools && execTools.length > 0 ? execTools : tools; } @@ -319,13 +335,17 @@ export function appendCursorShellAliasHint( return `${text}${text.endsWith("\n") ? "\n" : "\n\n"}${CURSOR_SHELL_ALIAS_USER_HINT}`; } -export function cursorToolAllowedByChoice(tool: Pick, toolChoice: OcxRequestOptions["toolChoice"] | undefined): boolean { +export function cursorToolAllowedByChoice( + tool: Pick, + toolChoice: OcxRequestOptions["toolChoice"] | undefined, + catalog: readonly Pick[] = [tool], +): boolean { if (!toolChoice || toolChoice === "auto" || toolChoice === "required") return true; if (toolChoice === "none") return false; if ("allowedTools" in toolChoice) { - return toolChoice.allowedTools.some(choiceName => cursorToolChoiceMatches(tool, choiceName)); + return toolChoice.allowedTools.some(choiceName => cursorToolChoiceMatches(tool, choiceName, catalog)); } - return cursorToolChoiceMatches(tool, toolChoice.name); + return cursorToolChoiceMatches(tool, toolChoice.name, catalog); } function quotedNames(names: readonly string[]): string { @@ -352,7 +372,7 @@ export function buildCursorToolGuidanceSystemNote( if (!tools?.length) return undefined; const wireNames = [...new Set( tools - .filter(tool => cursorToolAllowedByChoice(tool, toolChoice)) + .filter(tool => cursorToolAllowedByChoice(tool, toolChoice, tools)) .map(tool => cursorToolWireName(tool)), )]; if (wireNames.length === 0) return undefined; @@ -416,7 +436,7 @@ export function buildCursorToolDefinitions( toolChoice?: OcxRequestOptions["toolChoice"], ): McpToolDefinition[] { if (!tools?.length) return []; - return tools.filter(tool => cursorToolAllowedByChoice(tool, toolChoice)).map(tool => { + return tools.filter(tool => cursorToolAllowedByChoice(tool, toolChoice, tools)).map(tool => { const wireName = cursorToolWireName(tool); return create(McpToolDefinitionSchema, { name: wireName, diff --git a/tests/cursor-arg-normalize.test.ts b/tests/cursor-arg-normalize.test.ts index e720a786228..fc16102f184 100644 --- a/tests/cursor-arg-normalize.test.ts +++ b/tests/cursor-arg-normalize.test.ts @@ -29,11 +29,30 @@ describe("normalizeArgKeys", () => { expect(normalizeArgKeys({ cmd: "ls" }, narrow)).toEqual({ cmd: "ls" }); }); - test("does not clobber an existing canonical key", () => { - // Both `path` (canonical) and `filepath` (alias) present -> keep canonical, keep alias as-is. - const result = normalizeArgKeys({ path: "real.txt", filepath: "alias.txt" }, schema); - expect(result.path).toBe("real.txt"); - expect(result.filepath).toBe("alias.txt"); + test("canonical key wins over alias regardless of property insertion order", () => { + expect(normalizeArgKeys({ command: "canonical", cmd: "alias" }, schema)).toEqual({ command: "canonical" }); + expect(normalizeArgKeys({ cmd: "alias", command: "canonical" }, schema)).toEqual({ command: "canonical" }); + expect(normalizeArgKeys({ path: "real.txt", filepath: "alias.txt" }, schema)).toEqual({ path: "real.txt" }); + expect(normalizeArgKeys({ filepath: "alias.txt", path: "real.txt" }, schema)).toEqual({ path: "real.txt" }); + }); + + test("alias-only payloads still rewrite to the canonical key", () => { + expect(normalizeArgKeys({ cmd: "alias" }, schema)).toEqual({ command: "alias" }); + expect(normalizeArgKeys({ filepath: "a.txt" }, schema)).toEqual({ path: "a.txt" }); + }); + + test("identical alias and canonical values keep only the canonical key", () => { + expect(normalizeArgKeys({ command: "same", cmd: "same" }, schema)).toEqual({ command: "same" }); + expect(normalizeArgKeys({ cmd: "same", command: "same" }, schema)).toEqual({ command: "same" }); + }); + + test("conflicting alias and canonical values keep only the canonical key", () => { + expect(normalizeArgKeys({ command: "safe command", cmd: "different command" }, schema)).toEqual({ + command: "safe command", + }); + expect(normalizeArgKeys({ cmd: "different command", command: "safe command" }, schema)).toEqual({ + command: "safe command", + }); }); test("returns args unchanged when schema has no properties", () => { @@ -45,4 +64,11 @@ describe("normalizeArgKeys", () => { test("is case-insensitive on the alias key", () => { expect(normalizeArgKeys({ FilePath: "a.txt" }, schema)).toEqual({ path: "a.txt" }); }); + + test("preserves unrelated unknown keys", () => { + expect(normalizeArgKeys({ cmd: "ls", workdir: "C:/repo" }, schema)).toEqual({ + command: "ls", + workdir: "C:/repo", + }); + }); }); diff --git a/tests/cursor-protobuf-events.test.ts b/tests/cursor-protobuf-events.test.ts index 1f17798d275..888443eeb1b 100644 --- a/tests/cursor-protobuf-events.test.ts +++ b/tests/cursor-protobuf-events.test.ts @@ -449,6 +449,32 @@ describe("Cursor protobuf tool-call events", () => { }); }); + test("completed shell payload with both command and cmd keeps only canonical command", () => { + const toolSchemas = new Map([ + ["shell_command", { type: "object", properties: { command: { type: "string" }, workdir: { type: "string" } }, required: ["command"] }], + ]); + for (const [index, args] of [ + { command: "safe command", cmd: "different command", workdir: "C:/repo" }, + { cmd: "different command", command: "safe command", workdir: "C:/repo" }, + ].entries()) { + const state = createCursorProtobufEventState({ + clientToolNames: ["shell_command"], + toolSchemas, + cursorToolNameMap: new Map([["shell_command", "shell_command"]]), + }); + const toolCall = mcpToolCall("shell_command", args); + const events = mapCursorProtobufServerMessage(interaction({ + case: "toolCallCompleted", + value: create(ToolCallCompletedUpdateSchema, { callId: `call_${index}`, modelCallId: `model_${index}`, toolCall }), + }), state); + const delta = events.find(e => e.type === "tool_call_delta"); + expect(delta && delta.type === "tool_call_delta" ? JSON.parse(delta.arguments) : null).toEqual({ + command: "safe command", + workdir: "C:/repo", + }); + } + }); + test("normalizes mis-keyed args that arrived only via streamed text (no completed map)", () => { // The P1 audit case: model streamed `{"filepath":"a.txt"}` complete and the completion has no // map bytes. Buffered text must still be schema-normalized to `path` before reaching Codex. diff --git a/tests/cursor-request-builder.test.ts b/tests/cursor-request-builder.test.ts index d0ba9942aa7..6db299ce167 100644 --- a/tests/cursor-request-builder.test.ts +++ b/tests/cursor-request-builder.test.ts @@ -388,6 +388,58 @@ describe("Cursor request builder", () => { expect(cursorMcpToolsEncodedSize(budget.tools, "auto")).toBeLessThanOrEqual(CURSOR_TOOL_BYTES_LIMIT); }); + test("allowed_tools keeps shell and apply_patch ahead of a near-limit unrelated selected tool", () => { + const huge = { + name: "huge_tool", + namespace: "mcp__huge", + description: "x".repeat(CURSOR_TOOL_BYTES_LIMIT - 2_000), + parameters: { type: "object", properties: {} }, + }; + const shell = { + name: "shell_command", + description: "s".repeat(8_000), + parameters: { type: "object", properties: { command: { type: "string" } } }, + }; + const patch = { + name: "apply_patch", + description: "p".repeat(8_000), + parameters: { type: "object", properties: {} }, + freeform: true, + }; + const choice = { + mode: "required" as const, + allowedTools: ["huge_tool", "shell_command", "apply_patch"], + }; + // Combined catalog exceeds the byte budget; shell+patch alone must still fit. + expect(cursorMcpToolsEncodedSize([huge, shell, patch], choice)).toBeGreaterThan(CURSOR_TOOL_BYTES_LIMIT); + expect(cursorMcpToolsEncodedSize([shell, patch], choice)).toBeLessThanOrEqual(CURSOR_TOOL_BYTES_LIMIT); + + const budget = applyCursorToolBudget([huge, shell, patch], choice); + + expect(budget.tools).toContain(shell); + expect(budget.tools).toContain(patch); + expect(budget.tools).not.toContain(huge); + expect(cursorMcpToolsEncodedSize(budget.tools, choice)).toBeLessThanOrEqual(CURSOR_TOOL_BYTES_LIMIT); + }); + + test("allowed_tools keeps shell and apply_patch when count limit would otherwise drop later selected tools", () => { + const regular = Array.from({ length: CURSOR_TOOL_COUNT_LIMIT + 5 }, (_, index) => ({ + name: `regular_${index}`, + namespace: "mcp__regular", + description: "Regular", + parameters: {}, + })); + const shell = { name: "shell_command", description: "Run", parameters: {} }; + const patch = { name: "apply_patch", description: "Patch", parameters: {}, freeform: true }; + const allowedTools = [...regular.map(tool => tool.name), "shell_command", "apply_patch"]; + const choice = { mode: "required" as const, allowedTools }; + const budget = applyCursorToolBudget([...regular, shell, patch], choice); + + expect(budget.tools).toContain(shell); + expect(budget.tools).toContain(patch); + expect(budget.tools.length).toBeLessThanOrEqual(CURSOR_TOOL_COUNT_LIMIT); + }); + test("adds an honest recovery note only when tool_search survives", () => { const tools = [ { name: "tool_search", description: "Discover", parameters: {}, toolSearch: true }, diff --git a/tests/cursor-tool-choice.test.ts b/tests/cursor-tool-choice.test.ts index 09084b68a97..fe6da06331e 100644 --- a/tests/cursor-tool-choice.test.ts +++ b/tests/cursor-tool-choice.test.ts @@ -39,11 +39,28 @@ describe("Cursor Responses tool_choice support", () => { { name: "exec_command", namespace: "mcp__remote", description: "Remote exec", parameters: {} }, ]; expect(buildCursorToolDefinitions(toolsWithRemote, { name: "exec_command" }).map(tool => tool.toolName)).toEqual(["shell_command"]); - expect(buildCursorToolDefinitions(toolsWithRemote, { mode: "required", allowedTools: ["shell_command"] }).map(tool => tool.toolName)).toEqual(["shell_command"]); + expect(buildCursorToolDefinitions(toolsWithRemote, { mode: "required", allowedTools: ["exec_command"] }).map(tool => tool.toolName)).toEqual(["shell_command"]); // Wire-name choice still selects the namespaced tool intentionally. expect(buildCursorToolDefinitions(toolsWithRemote, { name: "mcp__remote__exec_command" }).map(tool => tool.toolName)).toEqual(["mcp__remote__exec_command"]); }); + test("raw exec_command selects namespaced remote when no bare shell bridge exists", () => { + const remoteOnly: OcxTool[] = [ + { name: "exec_command", namespace: "mcp__remote", description: "Remote exec", parameters: {} }, + ]; + expect(buildCursorToolDefinitions(remoteOnly, { name: "exec_command" }).map(tool => tool.toolName)).toEqual(["mcp__remote__exec_command"]); + expect(buildCursorToolDefinitions(remoteOnly, { mode: "required", allowedTools: ["exec_command"] }).map(tool => tool.toolName)).toEqual(["mcp__remote__exec_command"]); + expect(buildCursorToolDefinitions(remoteOnly, { name: "mcp__remote__exec_command" }).map(tool => tool.toolName)).toEqual(["mcp__remote__exec_command"]); + }); + + test("raw shell_command selects namespaced remote when no bare shell bridge exists", () => { + const remoteOnly: OcxTool[] = [ + { name: "shell_command", namespace: "mcp__remote", description: "Remote shell", parameters: {} }, + ]; + expect(buildCursorToolDefinitions(remoteOnly, { name: "shell_command" }).map(tool => tool.toolName)).toEqual(["mcp__remote__shell_command"]); + expect(buildCursorToolDefinitions(remoteOnly, { mode: "required", allowedTools: ["shell_command"] }).map(tool => tool.toolName)).toEqual(["mcp__remote__shell_command"]); + }); + test("parser preserves parallel_tool_calls false for Cursor request enforcement", () => { const parsed = parseRequest({ model: "cursor/auto",