From 2085a236cc7b519b2bb91e398eac6fa72f41b4af Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 10 Nov 2026 18:12:20 +0800 Subject: [PATCH] fix(cua-mcp): refuse unlisted tools before the executor and release the Agent after a failed close A `tools/call` that names anything but the listed `cua_run_code` registration or `cua_reset` now fails as an unknown tool before it reaches the tool executor, so a tool another row registers for the connection's Agent cannot be called without being listed, and the sandbox-escalation refusal applies to every program call. `dispose()` releases the connection's Agent even when closing the protocol server rejects. The `cua_reset` description states that a running program is cancelled, and an `isEscalationField` guard replaces the two type assertions. Documentation follows the code: the README states that a Host without a provider lists only `cua_reset`, that the Web plugin page hides the bundle while the Host inventory still reports it, that the documented Codex configuration carries the output budget, which client entries were exercised, that the sandbox root is the client's launch directory, and that the registration's escalation guidance has no effect in this profile. The unused `zod` dependency is removed. --- ...26-11-09-computer-use-mcp-server.i18n.yaml | 4 +- .../2026-11-09-computer-use-mcp-server.md | 2 +- .../2026-11-09-computer-use-mcp-server.zh.md | 2 +- .../profiles/cua-mcp/expected/tools.json | 2 +- apps/web/tests/preview-boot.e2e.ts | 7 +-- .../experimental/cua-mcp/README.i18n.yaml | 20 ++++---- packages/experimental/cua-mcp/README.md | 13 ++--- packages/experimental/cua-mcp/README.zh.md | 13 ++--- packages/experimental/cua-mcp/package.json | 3 +- packages/experimental/cua-mcp/src/server.ts | 48 +++++++++++-------- .../cua-mcp/tests/composition.spec.ts | 2 +- .../experimental/cua-mcp/tests/server.spec.ts | 28 ++++++++++- pnpm-lock.yaml | 3 -- scripts/optional-bundles.spec.ts | 4 +- 14 files changed, 92 insertions(+), 59 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.i18n.yaml index c6eba6815f..33c0b2f3b4 100644 --- a/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.i18n.yaml @@ -15,5 +15,5 @@ en: 9cc99401cdf7753a zh: 894b5f6024d3eabd /agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server/consequences: - en: a56d01b8ec6b3969 - zh: aa3b0879ce5da84f + en: 42e6518c4cce28cf + zh: eb844d9a0d8cf94e diff --git a/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.md b/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.md index d83d97af57..a0883ba56f 100644 --- a/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.md +++ b/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.md @@ -46,4 +46,4 @@ The composition lists its dependency closure, twenty-five rows, instead of layer ## Consequences -Every installation carries the bundle and its optional macOS provider dependency; `verify-default-product-isolation` keeps it out of default templates. A profile that layers the bundle over `dsh-base` duplicates row ids and is unsupported; the Web plugin page lists the bundle without a switch. Hosts without a provider list only `cua_reset`, and a `cua_run_code` call fails as `unknown tool`. Clients see state loss on process exit, `cua_reset`, or Agent disposal and recreate objects. Consent elicitation depends on the 2025 MCP request model; clients on the 2026-07-28 revision use `allow`. The tool description and the reference text in the first result are pinned by the profile's expected-output test and change with the installed CUA packages. A provider description longer than 4,096 characters reaches Claude Code models cut. +Every installation carries the bundle and its optional macOS provider dependency; `verify-default-product-isolation` keeps it out of default templates. A profile that layers the bundle over `dsh-base` duplicates row ids and is unsupported; the Web plugin page hides the bundle through `HIDDEN_BUNDLES` while the Host inventory still reports it as optional. Hosts without a provider list only `cua_reset`, and a `cua_run_code` call fails as `unknown tool`. Clients see state loss on process exit, `cua_reset`, or Agent disposal and recreate objects. Consent elicitation depends on the 2025 MCP request model; clients on the 2026-07-28 revision use `allow`. The tool description and the reference text in the first result are pinned by the profile's expected-output test and change with the installed CUA packages. A provider description longer than 4,096 characters reaches Claude Code models cut. diff --git a/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.zh.md b/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.zh.md index 5dbe0b959b..707df4e242 100644 --- a/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.zh.md @@ -46,4 +46,4 @@ Computer Use 的训练数据应来自多个 agent harness,而不只是 DSH 会 ## 后果 -每个安装都携带该组合包及其可选的 macOS 提供方依赖;`verify-default-product-isolation` 让它留在默认模板之外。把组合包叠在 `dsh-base` 之上的 profile 会出现重复的行 id,不受支持;Web 插件页列出该组合包但不提供开关。没有提供方的 Host 只列出 `cua_reset`,调用 `cua_run_code` 以 `unknown tool` 失败。客户端会在进程退出、`cua_reset` 或 Agent 销毁时看到状态丢失并重新创建对象。授权 elicitation 依赖 2025 版 MCP 请求模型;使用 2026-07-28 修订版的客户端改用 `allow`。工具描述与首个结果中的参考文本由 profile 的期望输出测试固定,并随已安装的 CUA 包变化。提供方描述超过 4,096 个字符时,Claude Code 的模型只看到被截断的部分。 +每个安装都携带该组合包及其可选的 macOS 提供方依赖;`verify-default-product-isolation` 让它留在默认模板之外。把组合包叠在 `dsh-base` 之上的 profile 会出现重复的行 id,不受支持;Web 插件页通过 `HIDDEN_BUNDLES` 隐藏该组合包,而 Host 清单仍把它报告为可选组合包。没有提供方的 Host 只列出 `cua_reset`,调用 `cua_run_code` 以 `unknown tool` 失败。客户端会在进程退出、`cua_reset` 或 Agent 销毁时看到状态丢失并重新创建对象。授权 elicitation 依赖 2025 版 MCP 请求模型;使用 2026-07-28 修订版的客户端改用 `allow`。工具描述与首个结果中的参考文本由 profile 的期望输出测试固定,并随已安装的 CUA 包变化。提供方描述超过 4,096 个字符时,Claude Code 的模型只看到被截断的部分。 diff --git a/apps/cli/tests/profiles/cua-mcp/expected/tools.json b/apps/cli/tests/profiles/cua-mcp/expected/tools.json index b05bfc73eb..33e6ce7236 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/tools.json +++ b/apps/cli/tests/profiles/cua-mcp/expected/tools.json @@ -34,7 +34,7 @@ { "name": "cua_reset", "title": "Reset computer use program state", - "description": "Discard the program environment of this connection: every variable, import, and application or window object held by earlier cua_run_code calls. Application access grants and the desktop applications themselves are unaffected; the next cua_run_code call starts a fresh environment and its result repeats the `cua` API reference. Use it when a declaration conflicts with an earlier call or the environment has become unusable.", + "description": "Discard the program environment of this connection: every variable, import, and application or window object held by earlier cua_run_code calls. A running cua_run_code program is cancelled. Application access grants and the desktop applications themselves are unaffected; the next cua_run_code call starts a fresh environment and its result repeats the `cua` API reference. Use it when a declaration conflicts with an earlier call or the environment has become unusable.", "inputSchema": { "type": "object", "properties": {} diff --git a/apps/web/tests/preview-boot.e2e.ts b/apps/web/tests/preview-boot.e2e.ts index d486407e23..72d4511a26 100644 --- a/apps/web/tests/preview-boot.e2e.ts +++ b/apps/web/tests/preview-boot.e2e.ts @@ -51,7 +51,7 @@ import { captureStableAria, compareOrRefreshGolden, webSnapshotMode } from './sc import { expandOwningTurnProcess, newEnglishPage, REPO_ROOT, saveFailureShot } from './support.ts' const DIST_ROOT = fileURLToPath(new URL('../dist', import.meta.url)) -/** Optional bundles that compose a profile of their own; the Web plugin page lists them without a switch. */ +/** Optional bundles that compose a profile of their own; the Web plugin page hides them, the Host inventory still reports them. */ const STANDALONE_PROFILE_BUNDLES: readonly string[] = ['@deepseek-ai/dsh-cua-mcp'] /** Where the client looks for the image: the runtime's own name, beside the page. */ @@ -685,7 +685,8 @@ async function toggleOptionalBundles(page: Page): Promise { // The packed worker composition cannot mount the Liveshare declaration row and its share host in // the same patch batch without racing the declaration service; the ordinary Web scaffold covers // that bundle's enable/disable path (plugin-manager.e2e.ts), so the packed toggle list skips it. A bundle that - // composes a profile of its own is listed but never layered over the Web profile, so the toggle list skips it too. + // composes a profile of its own is reported by the Host inventory but never layered over the Web profile, so the + // toggle list skips it too. for (const entry of bundles.filter(candidate => candidate.optional && candidate.name !== '@deepseek-ai/dsh-experimental-liveshare' && !standalone.includes(candidate.name))) { const enable = await remote<{ application: string; error?: unknown }>('pluginManager/setBundleEnabled', { name: entry.name, enabled: true }) @@ -715,7 +716,7 @@ async function toggleOptionalBundles(page: Page): Promise { } }, { standalone }) expect(result.optional.map(entry => entry.name).sort()).toEqual([...OPTIONAL_BUNDLES].sort()) - // The standalone bundle is listed with its metadata and stays switched off; no toggle targets it. + // The Host inventory reports the standalone bundle with its metadata, switched off; no toggle targets it. expect(result.toggles.map(toggle => toggle.name).filter(name => standalone.includes(name))).toEqual([]) expect(result.optional.filter(entry => entry.enabled || entry.availability !== 'installation')).toEqual([]) expect(result.optional.filter(entry => entry.error !== null)).toEqual([ diff --git a/packages/experimental/cua-mcp/README.i18n.yaml b/packages/experimental/cua-mcp/README.i18n.yaml index 13b4cc437e..86e36307b6 100644 --- a/packages/experimental/cua-mcp/README.i18n.yaml +++ b/packages/experimental/cua-mcp/README.i18n.yaml @@ -18,14 +18,14 @@ en: bbff250eba0f1b89 zh: 0a618f05cc88ee2b /deepseek-ai-dsh-cua-mcp/use-this-package/start-the-server: - en: 1f522266153ffbe5 - zh: 707deabdb0ded1c4 + en: ce44d68f2ede2c0f + zh: 1d7bbd8a9aabc7f5 /deepseek-ai-dsh-cua-mcp/use-this-package/connect-a-client: - en: 65cb4b0fb5cb2119 - zh: 98bb700cf459d8b2 + en: 71984217de74d42d + zh: 5aa6d28626d124b2 /deepseek-ai-dsh-cua-mcp/use-this-package/what-you-get: - en: 6ac4dc23b5f775c0 - zh: 255f4dee8d11be7e + en: 3579cb1b766aadd5 + zh: 81324f75fac6422a /deepseek-ai-dsh-cua-mcp/configuration: en: 8996e07a265596a5 zh: 8cf79827c51f2a2d @@ -45,14 +45,14 @@ en: 15b1420b7a13c50d zh: 072189c2f84a7772 /deepseek-ai-dsh-cua-mcp/model-experience/external-harness-model/token-effect: - en: 77aae66c401136c6 - zh: 8d4cd7b78c8e463b + en: 80328f91c62930e2 + zh: 7dbb1993a006764d /deepseek-ai-dsh-cua-mcp/model-experience/external-harness-model/kv-cache-effect: en: 2c22520787915229 zh: 21dafc45d1a4bc0d /deepseek-ai-dsh-cua-mcp/known-limitations-and-deferred-work: - en: 2afe31cfa86497dc - zh: 3d885bf475623ab9 + en: faa70bd5dfd6d4d6 + zh: 9bf93d899911b2dc /deepseek-ai-dsh-cua-mcp/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 8ec3e73528ddb1a6 diff --git a/packages/experimental/cua-mcp/README.md b/packages/experimental/cua-mcp/README.md index 50bfa20c69..8c99546487 100644 --- a/packages/experimental/cua-mcp/README.md +++ b/packages/experimental/cua-mcp/README.md @@ -28,7 +28,7 @@ This experimental bundle composes the standalone `cua-mcp` profile, an MCP stdio ### Start the server -The bundle is a runtime dependency of the `dsh` installation, so a profile that selects it as its only layer loads it from the installation; no pnpm, registry, or network access is involved. Create the profile once under the Harness home (`$DSH_HOME`, by default `~/.dsh`); `dsh --profile cua-mcp` is then the stdio command, and a source checkout runs it through `pnpm dsh` after `pnpm run build`. Do not add the bundle to a profile that already composes `dsh-base`, such as the one `dsh plugin --profile cua-mcp add` creates: both compositions declare the same row ids, which is also why the Web plugin page lists this bundle without a switch. +The bundle is a runtime dependency of the `dsh` installation, so a profile that selects it as its only layer loads it from the installation; no pnpm, registry, or network access is involved. Create the profile once under the Harness home (`$DSH_HOME`, by default `~/.dsh`); `dsh --profile cua-mcp` is then the stdio command, and a source checkout runs it through `pnpm dsh` after `pnpm run build`. Do not add the bundle to a profile that already composes `dsh-base`, such as the one `dsh plugin --profile cua-mcp add` creates: both compositions declare the same row ids, which is also why the Web plugin page hides this bundle while the Host inventory still reports it as optional. ```sh mkdir -p "${DSH_HOME:-$HOME/.dsh}/profiles/cua-mcp" @@ -67,15 +67,15 @@ output_token_limit = 25000 claude mcp add-json dsh_cua '{"type":"stdio","command":"/absolute/path/to/dsh","args":["--profile","cua-mcp"],"env":{"DSH_HOME":"/absolute/path/to/dsh-home","DSH_CUA_CONSENT":"elicit"},"timeout":600000,"alwaysLoad":true}' ``` -Other clients take the same `command`, `args`, and `env` under `mcpServers`. Codex forwards elicitations only with `approval_policy.granular.mcp_elicitations = true`. DSH's own `dsh-mcp-client` declares no elicitation capability, and Claude Code 2.1 print mode declines elicitations, so unattended runs through those clients need `DSH_CUA_CONSENT=allow`. +Other clients take the same `command`, `args`, and `env` under `mcpServers`. The Claude Code and `dsh-mcp-client` entries were exercised against a real desktop; the Codex entry follows the Codex configuration reference and the `.mcp.json` of its bundled Computer Use plugin and was not exercised here. As of 2026-11-10, Codex forwards elicitations only with `approval_policy.granular.mcp_elicitations = true`. DSH's own `dsh-mcp-client` declares no elicitation capability, and Claude Code 2.1 print mode declines elicitations, so unattended runs through those clients need `DSH_CUA_CONSENT=allow`. -On macOS the profile prepares the signed Computer Use helper on first start and needs Accessibility and Screen Recording permissions for it; the [macOS provider](../cua-macos/README.md) owns that setup. This profile has no permission page, so grant both in System Settings → Privacy & Security by adding the helper application: a source checkout prepares `DSH Computer Use Dev.app` under the macOS provider package's `native/.build/prepared///` directory, where `current.json` names the selected build; an installed package ships `DSH Computer Use.app`. Until both are granted, `await cua.getCapabilities()` reports the missing flags and application operations fail; a locked desktop fails them with `SESSION_LOCKED`. On other Hosts the profile starts without a provider, and both tools return an error naming the missing provider. +On macOS the profile prepares the signed Computer Use helper on first start and needs Accessibility and Screen Recording permissions for it; the [macOS provider](../cua-macos/README.md) owns that setup. This profile has no permission page, so grant both in System Settings → Privacy & Security by adding the helper application: a source checkout prepares `DSH Computer Use Dev.app` under the macOS provider package's `native/.build/prepared///` directory, where `current.json` names the selected build; an installed package ships `DSH Computer Use.app`. Until both are granted, `await cua.getCapabilities()` reports the missing flags and application operations fail; a locked desktop fails them with `SESSION_LOCKED`. On other Hosts the profile starts without a provider: the listing carries only `cua_reset`, a `cua_run_code` call fails as `unknown tool`, and `cua_reset` returns an error naming the missing provider. ### What you get `cua_run_code` is the Agent's DSH registration served as an MCP tool: every `tools/list` reads its name, description, and parameter schema from the tool registry, so the provider's definition is the only source, `description` is required as that definition declares, and `timeoutMs` bounds one program. The projection omits the registration's sandbox-escalation fields, `sandbox_permissions` and `justification`, and a call naming them is refused before execution; every other argument passes to the DSH tool executor unchanged, which validates them and answers unknown names, so an invalid call returns DSH's error result. The program runs as TypeScript REPL statements against the global `cua` object in the provider's retained Node environment. The result carries the program's printed lines and final expression as text, then every screenshot the program captured as an inline image in the exact version the program observed, so pixel coordinates in the text match the image. The first result of a connection starts with the `cua` API reference; the tool description carries the execution rules. Programs run one at a time per connection in arrival order; a cancelled call cancels its program. -`cua_reset` discards the program environment: variables, imports, and application or window objects. Application grants, native connections, and the applications themselves stay; the next program starts a fresh process and its result repeats the API reference. Use it after a conflicting declaration or an unusable environment. +`cua_reset` discards the program environment: variables, imports, and application or window objects, and cancels a `cua_run_code` program that is still running. Application grants, native connections, and the applications themselves stay; the next program starts a fresh process and its result repeats the API reference. Use it after a conflicting declaration or an unusable environment. The connection's Agent is created before the stdio transport opens, so the first listing already carries its registration, and disposed when the client closes stdin, which also exits the process. Application consent follows the [CUA consent rules](../cua/README.md) for that Agent: `DSH_CUA_CONSENT=allow` grants each request for the session without a human, and the default `elicit` forwards the request to the client as a form elicitation whose answers are the CUA labels; a declined form records a denial for the session, and a client without elicitation receives an error that names the `allow` mode. @@ -130,7 +130,7 @@ The connected harness's model sees the Agent's `cua_run_code` definition, `cua_r #### Token effect -The tool description carries the 2,200-character execution rules of the registration; the first result adds the API reference, about 13,000 characters with the current macOS provider, once per connection or reset, about 3,300 tokens by the repository's four-character estimate. Screenshots are inline images at the provider's `screenshotTarget` size. Clients cap tool output; the generated Codex configuration raises the `cua_run_code` budget to 25,000 tokens. Clients also cap tool descriptions: Claude Code 2.1.309 forwards the first 4,096 characters of an MCP tool description and appends `… [truncated]`; DSH's `dsh-mcp-client` forwards a 20,000-character description intact. The registration's description fits that budget; the reference does not and travels in the first result. +The tool description carries the 2,200-character execution rules of the registration; the first result adds the API reference, about 13,000 characters with the current macOS provider, once per connection or reset, about 3,300 tokens by the repository's four-character estimate. Screenshots are inline images at the provider's `screenshotTarget` size. Clients cap tool output; the documented Codex configuration raises the `cua_run_code` budget to 25,000 tokens. Clients also cap tool descriptions: Claude Code 2.1.309 forwards the first 4,096 characters of an MCP tool description and appends `… [truncated]`; DSH's `dsh-mcp-client` forwards a 20,000-character description intact. The registration's description fits that budget; the reference does not and travels in the first result. #### KV Cache effect @@ -142,7 +142,8 @@ The tool catalog and instructions are stable for one installation. The first res - Only macOS Hosts have a provider; the Windows provider mounts here once it exists. Other Hosts list only `cua_reset`: a `cua_run_code` call fails as `unknown tool`, and `cua_reset` names the missing provider. - Elicitation uses the 2025 MCP request model; a client that negotiates the 2026-07-28 revision receives an error for consent requests and should use `DSH_CUA_CONSENT=allow`. -- Program sandbox escalation and the raw `cua` tool are not exposed; `DSH_PERMISSION_MODE` selects the launch-time file sandbox of program processes. +- Program sandbox escalation and the raw `cua` tool are not exposed; `DSH_PERMISSION_MODE` selects the launch-time file sandbox of program processes, and its `workspace-write` root is the directory the client started the server in, which some clients set to `/`. Override the `sandbox-policy` row's `workspaceRoot` in the profile patch to pin it. +- The registration's description still carries the PTC sandbox-escalation guidance ("A sandbox escalation approves this complete program …"); a program that follows it is refused before execution and told that `DSH_PERMISSION_MODE` selects the sandbox. - A provider description longer than 4,096 characters reaches Claude Code 2.1.309 models cut; the projection does not shorten it. - Root tool calls are not Session events; the connected harness's transcript is the record of calls and results. - The patch lists the profile's dependency closure explicitly; a new service injection in the CUA or PTC packages leaves the provider row inactive, reported on stderr, and `cua_run_code` out of the listing until the patch adds the row. diff --git a/packages/experimental/cua-mcp/README.zh.md b/packages/experimental/cua-mcp/README.zh.md index 57302b15df..f77b053d54 100644 --- a/packages/experimental/cua-mcp/README.zh.md +++ b/packages/experimental/cua-mcp/README.zh.md @@ -28,7 +28,7 @@ kind: "package-bundle" ### 启动服务器 -组合包是 `dsh` 安装的运行时依赖,因此只选它这一层的 profile 直接从安装中加载它;不涉及 pnpm、registry 或网络。在 Harness home(`$DSH_HOME`,默认 `~/.dsh`)下创建一次 profile,之后 `dsh --profile cua-mcp` 就是 stdio 命令,源码检出在 `pnpm run build` 之后通过 `pnpm dsh` 运行它。不要把组合包加进已经组合了 `dsh-base` 的 profile(例如 `dsh plugin --profile cua-mcp add` 创建的那种):两套组合声明同样的行 id,Web 插件页也因此只列出本组合包而不提供开关。 +组合包是 `dsh` 安装的运行时依赖,因此只选它这一层的 profile 直接从安装中加载它;不涉及 pnpm、registry 或网络。在 Harness home(`$DSH_HOME`,默认 `~/.dsh`)下创建一次 profile,之后 `dsh --profile cua-mcp` 就是 stdio 命令,源码检出在 `pnpm run build` 之后通过 `pnpm dsh` 运行它。不要把组合包加进已经组合了 `dsh-base` 的 profile(例如 `dsh plugin --profile cua-mcp add` 创建的那种):两套组合声明同样的行 id,Web 插件页也因此隐藏本组合包,而 Host 清单仍把它报告为可选组合包。 ```sh mkdir -p "${DSH_HOME:-$HOME/.dsh}/profiles/cua-mcp" @@ -67,15 +67,15 @@ output_token_limit = 25000 claude mcp add-json dsh_cua '{"type":"stdio","command":"/absolute/path/to/dsh","args":["--profile","cua-mcp"],"env":{"DSH_HOME":"/absolute/path/to/dsh-home","DSH_CUA_CONSENT":"elicit"},"timeout":600000,"alwaysLoad":true}' ``` -其他客户端在 `mcpServers` 下使用同样的 `command`、`args` 与 `env`。Codex 只有在 `approval_policy.granular.mcp_elicitations = true` 时才转发 elicitation。DSH 自己的 `dsh-mcp-client` 未声明 elicitation 能力,Claude Code 2.1 的 print 模式会拒绝 elicitation,因此经这两类客户端的无人值守运行需要 `DSH_CUA_CONSENT=allow`。 +其他客户端在 `mcpServers` 下使用同样的 `command`、`args` 与 `env`。Claude Code 与 `dsh-mcp-client` 两条配置经真实桌面验证;Codex 配置按 Codex 配置参考及其自带 Computer Use 插件的 `.mcp.json` 给出,未在此实测。截至 2026-11-10,Codex 只有在 `approval_policy.granular.mcp_elicitations = true` 时才转发 elicitation。DSH 自己的 `dsh-mcp-client` 未声明 elicitation 能力,Claude Code 2.1 的 print 模式会拒绝 elicitation,因此经这两类客户端的无人值守运行需要 `DSH_CUA_CONSENT=allow`。 -在 macOS 上,profile 首次启动时准备已签名的 Computer Use helper,并需要为其授予辅助功能与屏幕录制权限;[macOS 提供方](../cua-macos/README.zh.md)负责这部分设置。本 profile 没有权限页面,因此要在「系统设置 → 隐私与安全性」中添加 helper 应用来授予这两项权限:源码检出在 macOS 提供方包的 `native/.build/prepared///` 目录下准备 `DSH Computer Use Dev.app`,其中 `current.json` 记录当前选中的构建;已安装的包附带 `DSH Computer Use.app`。两项权限都授予之前,`await cua.getCapabilities()` 会报告缺失的标志,应用操作会失败;桌面处于锁定状态时这些操作以 `SESSION_LOCKED` 失败。在其他 Host 上 profile 没有提供方也能启动,两个工具都返回指出缺少提供方的错误。 +在 macOS 上,profile 首次启动时准备已签名的 Computer Use helper,并需要为其授予辅助功能与屏幕录制权限;[macOS 提供方](../cua-macos/README.zh.md)负责这部分设置。本 profile 没有权限页面,因此要在「系统设置 → 隐私与安全性」中添加 helper 应用来授予这两项权限:源码检出在 macOS 提供方包的 `native/.build/prepared///` 目录下准备 `DSH Computer Use Dev.app`,其中 `current.json` 记录当前选中的构建;已安装的包附带 `DSH Computer Use.app`。两项权限都授予之前,`await cua.getCapabilities()` 会报告缺失的标志,应用操作会失败;桌面处于锁定状态时这些操作以 `SESSION_LOCKED` 失败。在其他 Host 上 profile 没有提供方也能启动:列表只有 `cua_reset`,调用 `cua_run_code` 以 `unknown tool` 失败,`cua_reset` 返回指出缺少提供方的错误。 ### 你会得到什么 `cua_run_code` 就是该 Agent 的 DSH 注册项以 MCP 工具的形式提供:每次 `tools/list` 都从工具注册表读取它的名称、描述和参数 schema,因此提供方的定义是唯一来源,`description` 按该定义必填,`timeoutMs` 限制单个程序。投影省略注册项中的沙箱提权字段 `sandbox_permissions` 与 `justification`,指定它们的调用在执行前被拒绝;其余参数原样交给 DSH 工具执行器,由它校验参数并回答未知名称,因此非法调用返回 DSH 的错误结果。程序作为 TypeScript REPL 语句在提供方保留的 Node 环境中对全局 `cua` 对象运行。结果以文本携带程序打印的行和最终表达式,随后把程序捕获的每张截图以内联图片附上,且图片正是程序观察到的那一版,因此文本中的像素坐标与图片一致。一个连接的首个结果以 `cua` API 参考开头;执行规则在工具描述里。同一连接的程序按到达顺序逐个运行;取消调用会取消其程序。 -`cua_reset` 丢弃程序环境:变量、导入以及应用或窗口对象。应用授权、本机连接和应用本身保留;下一个程序在新进程中启动,其结果重复 API 参考。在声明冲突或环境不可用之后使用它。 +`cua_reset` 丢弃程序环境:变量、导入以及应用或窗口对象,并取消仍在运行的 `cua_run_code` 程序。应用授权、本机连接和应用本身保留;下一个程序在新进程中启动,其结果重复 API 参考。在声明冲突或环境不可用之后使用它。 连接的 Agent 在 stdio 传输打开之前创建,因此首次列表就带有它的注册项;客户端关闭 stdin 时销毁,进程随之退出。应用授权按该 Agent 遵循 [CUA 授权规则](../cua/README.zh.md):`DSH_CUA_CONSENT=allow` 在无人值守下为本会话放行每个请求;默认的 `elicit` 把请求作为表单 elicitation 转发给客户端,答案即 CUA 的选项标签;被拒绝的表单为本会话记录一次拒绝,不支持 elicitation 的客户端会收到指明 `allow` 模式的错误。 @@ -130,7 +130,7 @@ patch 还以 `screenshotTarget: { longEdge: 2048, maxBytes: 2097152 }` 挂载提 #### Token 影响 -工具描述携带注册项 2,200 个字符的执行规则;首个结果每个连接或每次重置增加 API 参考,使用当前 macOS 提供方时约 13,000 个字符,按仓库四字符/token 估算约 3,300 token。截图是提供方 `screenshotTarget` 尺寸的内联图片。客户端会限制工具输出;生成的 Codex 配置把 `cua_run_code` 的预算提高到 25,000 token。客户端同样限制工具描述:Claude Code 2.1.309 只转发 MCP 工具描述的前 4,096 个字符并追加 `… [truncated]`;DSH 的 `dsh-mcp-client` 原样转发 20,000 个字符的描述。注册项的描述在该预算之内;参考超出预算,因此随首个结果传递。 +工具描述携带注册项 2,200 个字符的执行规则;首个结果每个连接或每次重置增加 API 参考,使用当前 macOS 提供方时约 13,000 个字符,按仓库四字符/token 估算约 3,300 token。截图是提供方 `screenshotTarget` 尺寸的内联图片。客户端会限制工具输出;文档给出的 Codex 配置把 `cua_run_code` 的预算提高到 25,000 token。客户端同样限制工具描述:Claude Code 2.1.309 只转发 MCP 工具描述的前 4,096 个字符并追加 `… [truncated]`;DSH 的 `dsh-mcp-client` 原样转发 20,000 个字符的描述。注册项的描述在该预算之内;参考超出预算,因此随首个结果传递。 #### KV Cache 影响 @@ -142,7 +142,8 @@ patch 还以 `screenshotTarget: { longEdge: 2048, maxBytes: 2097152 }` 挂载提 - 只有 macOS Host 有提供方;Windows 提供方就位后在此挂载。其他 Host 只列出 `cua_reset`:调用 `cua_run_code` 以 `unknown tool` 失败,`cua_reset` 指出缺少提供方。 - Elicitation 使用 2025 版 MCP 请求模型;协商到 2026-07-28 修订版的客户端在授权请求时收到错误,应改用 `DSH_CUA_CONSENT=allow`。 -- 不暴露程序沙箱提权和原始 `cua` 工具;`DSH_PERMISSION_MODE` 选择程序进程启动时的文件沙箱。 +- 不暴露程序沙箱提权和原始 `cua` 工具;`DSH_PERMISSION_MODE` 选择程序进程启动时的文件沙箱,其 `workspace-write` 根是客户端启动服务器时所在的目录,有些客户端会把它设为 `/`。在 profile patch 里覆盖 `sandbox-policy` 行的 `workspaceRoot` 可以固定它。 +- 注册项的描述仍带有 PTC 的沙箱提权说明("A sandbox escalation approves this complete program …");按它请求提权的程序会在执行前被拒绝,并被告知 `DSH_PERMISSION_MODE` 决定沙箱。 - 提供方描述超过 4,096 个字符时,Claude Code 2.1.309 的模型只看到被截断的部分;投影不会缩短它。 - 根工具调用不是 Session 事件;接入 harness 的 transcript 才是调用与结果的记录。 - patch 显式列出该 profile 的依赖闭包;CUA 或 PTC 包新增服务注入时,提供方行无法激活并在 stderr 上报告,列表里没有 `cua_run_code`,直到 patch 补上该行。 diff --git a/packages/experimental/cua-mcp/package.json b/packages/experimental/cua-mcp/package.json index d6a7e235ab..617c05b6fc 100644 --- a/packages/experimental/cua-mcp/package.json +++ b/packages/experimental/cua-mcp/package.json @@ -73,8 +73,7 @@ "@deepseek-ai/dsh-working-directory": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", "@modelcontextprotocol/server": "2.2.0", - "commander": "^15.0.0", - "zod": "4.6.6" + "commander": "^15.0.0" }, "optionalDependencies": { "@deepseek-ai/dsh-experimental-cua-macos": "workspace:*" diff --git a/packages/experimental/cua-mcp/src/server.ts b/packages/experimental/cua-mcp/src/server.ts index 17d45e6b94..39af7a380a 100644 --- a/packages/experimental/cua-mcp/src/server.ts +++ b/packages/experimental/cua-mcp/src/server.ts @@ -52,6 +52,10 @@ const PROGRAM_TOOL = 'cua_run_code' */ const ESCALATION_FIELDS = ['sandbox_permissions', 'justification'] as const +function isEscalationField(field: string): field is typeof ESCALATION_FIELDS[number] { + return (ESCALATION_FIELDS as readonly string[]).includes(field) +} + /** MCP presentation of the program tool; its name, description, and schema come from the registration. */ const PROGRAM_TOOL_PRESENTATION = { title: 'Computer use program', @@ -63,9 +67,10 @@ const RESET_TOOL: Tool = { name: 'cua_reset', title: 'Reset computer use program state', description: 'Discard the program environment of this connection: every variable, import, and application or ' - + 'window object held by earlier cua_run_code calls. Application access grants and the desktop applications themselves ' - + 'are unaffected; the next cua_run_code call starts a fresh environment and its result repeats the `cua` API reference. ' - + 'Use it when a declaration conflicts with an earlier call or the environment has become unusable.', + + 'window object held by earlier cua_run_code calls. A running cua_run_code program is cancelled. Application access ' + + 'grants and the desktop applications themselves are unaffected; the next cua_run_code call starts a fresh environment ' + + 'and its result repeats the `cua` API reference. Use it when a declaration conflicts with an earlier call or the ' + + 'environment has become unusable.', inputSchema: { type: 'object', properties: {} }, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }, } @@ -96,12 +101,9 @@ function projectProgramTool(definition: ToolDefinition): Tool { const inputSchema = { ...rest, ...properties === undefined ? {} : { - properties: Object.fromEntries(Object.entries(properties as Record) - .filter(([field]) => !ESCALATION_FIELDS.includes(field as typeof ESCALATION_FIELDS[number]))), + properties: Object.fromEntries(Object.entries(properties as Record).filter(([field]) => !isEscalationField(field))), }, - ...Array.isArray(required) - ? { required: required.filter(field => !ESCALATION_FIELDS.includes(field as typeof ESCALATION_FIELDS[number])) } - : {}, + ...Array.isArray(required) ? { required: (required as string[]).filter(field => !isEscalationField(field)) } : {}, } const result = specTypeSchemas.Tool['~standard'].validate({ name: definition.name, description: definition.description, inputSchema, ...PROGRAM_TOOL_PRESENTATION, @@ -115,10 +117,12 @@ function projectProgramTool(definition: ToolDefinition): Tool { /** * Create the MCP server for one stdio connection. The connection's Agent is created first, mounts the profile's * default preset, and lives until disposal; the provider registers `cua_run_code` for it, and each `tools/list` - * re-reads that registration. `cua_run_code` calls pass their arguments to the ordinary tool executor unchanged, - * one at a time in arrival order, so argument validation and unknown names are answered by DSH; `cua_reset` - * bypasses the queue and cancels the running program. Consent questions of that Agent are answered by the - * configured mode. A call the executor cannot settle, including a cancelled one, fails as a protocol error. + * re-reads that registration. A call names one of the two listed tools or fails as an unknown tool before it + * reaches the executor, so a tool another row registers for the Agent is never callable without being listed. + * `cua_run_code` calls pass their arguments to the ordinary tool executor unchanged, one at a time in arrival + * order, so argument validation is answered by DSH; `cua_reset` bypasses the queue and cancels the running program. + * Consent questions of that Agent are answered by the configured mode. A call the executor cannot settle, + * including a cancelled one, fails as a protocol error. * @param ctx - Profile context with Agents, presets, tools, the system prompt, and the attachment store. * @param options - Consent mode, working directory, and lifetime. * @returns The protocol server, not yet connected to a transport, its Agent, and its disposer. @@ -167,9 +171,10 @@ export async function createCuaMcpServer(ctx: Context, options: CuaMcpServerOpti const guidance = assembly.sections.find(section => section.name === CUA_PROMPT_SECTION_NAME)?.text return guidance === undefined ? undefined : `## cua API reference\n\n${guidance}` } - const runTool = async (name: string, args: Record, signal: AbortSignal): Promise => { + const runTool = async (args: Record, signal: AbortSignal): Promise => { + const name = PROGRAM_TOOL const escalation = ESCALATION_FIELDS.filter(field => field in args) - if (name === PROGRAM_TOOL && escalation.length > 0) { + if (escalation.length > 0) { return failure(`Program sandbox escalation is not available through cua-mcp: remove ${escalation.join(' and ')}. ` + 'The launch-time DSH_PERMISSION_MODE selects the file sandbox of program processes.') } @@ -180,7 +185,7 @@ export async function createCuaMcpServer(ctx: Context, options: CuaMcpServerOpti const outcome = batch.results[0] if (outcome === undefined) throw new Error(`The tool executor settled without a ${name} result`) const preface: string[] = [] - if (name === PROGRAM_TOOL && !referenceSent) { + if (!referenceSent) { const reference = await apiReference() if (reference !== undefined) { preface.push(reference) @@ -212,7 +217,9 @@ export async function createCuaMcpServer(ctx: Context, options: CuaMcpServerOpti server.setRequestHandler('tools/call', (request, extra) => { const { name, arguments: args = {} } = request.params if (name === RESET_TOOL.name) return resetEnvironment() - return serialize(() => runTool(name, args, AbortSignal.any([options.signal, extra.mcpReq.signal]))) + // The same judgement as tools/list: only the listed registration reaches the executor. + if (name !== PROGRAM_TOOL || ctx.tools.get(PROGRAM_TOOL, agent) === undefined) return failure(`unknown tool ${JSON.stringify(name)}`) + return serialize(() => runTool(args, AbortSignal.any([options.signal, extra.mcpReq.signal]))) }) return { @@ -220,9 +227,12 @@ export async function createCuaMcpServer(ctx: Context, options: CuaMcpServerOpti agent, async dispose() { unregisterAnswerer() - await server.close() - await queue - await handle.dispose() + try { + await server.close() + } finally { + await queue + await handle.dispose() + } }, } } diff --git a/packages/experimental/cua-mcp/tests/composition.spec.ts b/packages/experimental/cua-mcp/tests/composition.spec.ts index d5d05389c2..d4a9464efc 100644 --- a/packages/experimental/cua-mcp/tests/composition.spec.ts +++ b/packages/experimental/cua-mcp/tests/composition.spec.ts @@ -267,7 +267,7 @@ describe('Computer Use MCP composition', () => { it('serves only cua_reset on a Host without a CUA provider and releases the connection Agent on disposal', async () => { const { ctx, run, client, adapter } = await setup({ provider: false }) expect((await client.listTools()).tools.map(tool => tool.name)).toEqual(['cua_reset']) - // No registration exists for the Agent, so the executor, not cua-mcp, refuses the program tool. + // No registration exists for the Agent, so the call is refused as an unknown tool before it reaches the executor. const result = await run('1') expect(result.isError).toBe(true) expect(texts(result)[0]).toContain('unknown tool "cua_run_code"') diff --git a/packages/experimental/cua-mcp/tests/server.spec.ts b/packages/experimental/cua-mcp/tests/server.spec.ts index 04ffe33eef..67e4c6b91b 100644 --- a/packages/experimental/cua-mcp/tests/server.spec.ts +++ b/packages/experimental/cua-mcp/tests/server.spec.ts @@ -166,8 +166,8 @@ describe('Computer Use MCP server', () => { expect(dispose).not.toHaveBeenCalled() }) - it('lists only cua_reset without a registration and lets the executor answer unknown tools', async () => { - const { client, run } = await setup({ registered: false, programs: false, reference: false }) + it('lists only cua_reset without a registration and refuses every unlisted name before the executor', async () => { + const { client, run, execute } = await setup({ registered: false, programs: false, reference: false }) expect((await client.listTools()).tools.map(tool => tool.name)).toEqual(['cua_reset']) const unknown = await run({ code: '1', description: 'Probe' }) expect(unknown.isError).toBe(true) @@ -175,11 +175,27 @@ describe('Computer Use MCP server', () => { const other = await client.callTool({ name: 'cua_other', arguments: {} }) expect(other.isError).toBe(true) expect(texts(other)).toEqual(['unknown tool "cua_other"']) + expect(execute).not.toHaveBeenCalled() const reset = await client.callTool({ name: 'cua_reset', arguments: {} }) expect(reset.isError).toBe(true) expect(texts(reset).join('')).toContain('no active CUA provider') }) + it('serves program results without a preface when the provider registers no guidance', async () => { + const { run, execute } = await setup({ reference: false }) + expect(texts(await run({ code: '1', description: 'First' }))).toEqual(['program output']) + expect(texts(await run({ code: '2', description: 'Second' }))).toEqual(['program output']) + expect(execute).toHaveBeenCalledTimes(2) + }) + + it('refuses a registered tool the listing does not carry', async () => { + const { client, execute } = await setup() + const other = await client.callTool({ name: 'cua_other', arguments: { sandbox_permissions: 'danger-full-access' } }) + expect(other.isError).toBe(true) + expect(texts(other)).toEqual(['unknown tool "cua_other"']) + expect(execute).not.toHaveBeenCalled() + }) + it('fails the call as a protocol error when the executor settles without a result, reports reset failures, and repeats the reference after a reset', async () => { const { run, client, reset, execute } = await setup() execute.mockResolvedValueOnce({ results: [], additionalContexts: [], concluded: false }) @@ -213,4 +229,12 @@ describe('Computer Use MCP server', () => { await served.adapter.dispose() expect(served.dispose).toHaveBeenCalledOnce() }) + + it('disposes the Agent when closing the protocol server fails', async () => { + const served = await setup() + vi.spyOn(served.adapter.server, 'close').mockRejectedValueOnce(new Error('transport is broken')) + await expect(served.adapter.dispose()).rejects.toThrow('transport is broken') + expect(served.dispose).toHaveBeenCalledOnce() + await served.client.close() + }) }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fbb78baf17..5f7c1a89d3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -10227,9 +10227,6 @@ importers: commander: specifier: ^15.0.0 version: 15.0.0 - zod: - specifier: 4.6.6 - version: 4.6.6 devDependencies: '@deepseek-ai/cordis': specifier: workspace:~ diff --git a/scripts/optional-bundles.spec.ts b/scripts/optional-bundles.spec.ts index 7b6fdfa959..3178495098 100644 --- a/scripts/optional-bundles.spec.ts +++ b/scripts/optional-bundles.spec.ts @@ -32,7 +32,7 @@ function bundle(name: string): { dir: string; patches: ReturnType loadOverlayPatches('test', path)) } } -/** Optional bundles that compose a profile of their own; the plugin page lists them without a switch. */ +/** Optional bundles that compose a profile of their own; the plugin page hides them, the Host inventory still reports them. */ const STANDALONE_PROFILE_BUNDLES: readonly string[] = ['@deepseek-ai/dsh-cua-mcp'] const lightweight = [ @@ -109,7 +109,7 @@ describe('optional bundles', () => { expect(OPTIONAL_BUNDLES).not.toContain('@deepseek-ai/dsh-experimental-inspector') }) - // A bundle that composes a profile of its own is never layered over a GUI profile; the plugin page lists it without a switch. + // A bundle that composes a profile of its own is never layered over a GUI profile; HIDDEN_BUNDLES keeps it off the plugin page. const standalone = OPTIONAL_BUNDLES.filter(name => STANDALONE_PROFILE_BUNDLES.includes(name)) const layered = OPTIONAL_BUNDLES.filter(name => !standalone.includes(name))