From a6055912fe759e32f177e2d79cb1a68192cb33dd Mon Sep 17 00:00:00 2001 From: iamnbutler Date: Thu, 12 Nov 2026 20:18:23 -0500 Subject: [PATCH 1/3] MCP launcher: dist/mcp.js only hands over to the app's own server (#237) The Node MCP server is gone. desktop-tools-mcp from npm finds the server beside the client the app links in its state folder, or beside the client --client names, passes --socket and --name on, and hands stdin and stdout over; --wire 2 is accepted and ignored. With no server to run, it exits with a message: no linked client, a Desktop Tools from before 0.17.0 (named with its version and the release to install), or an embedder's app that ships no desktop-tools-mcp. version-skew.test.mjs, whose subject was the Node server, gives way to launcher tests that run anywhere. parity, both bench scripts and live-check default to the app's own server; a command that names an existing file runs whole, since the app's path has spaces. docs/mcp.md leads with the app path. Co-Authored-By: Claude Opus 5.5 --- ...2RX9XD8J8G-the-version-skew-note-applie.md | 0 ...NZ9KCCPZB6-only-the-server-instructions.md | 0 ...B6KKZ0CFH2-the-server-instructions-mirr.md | 8 + ...EKXMV8RKAE-the-app-must-keep-linking-st.md | 8 + CHANGELOG.md | 1 + README.md | 2 +- dist/mcp.js | 222 ++++------------- docs/live-checks.md | 2 +- docs/mcp.md | 31 +-- native2/README.md | 4 +- native2/scripts/bench.mjs | 9 +- native2/scripts/parity.mjs | 10 +- scripts/bench.mjs | 7 +- scripts/live-check.mjs | 21 +- src/mcp.ts | 226 ++++-------------- test/mcp-launcher.test.mjs | 97 ++++++++ test/version-skew.test.mjs | 72 ------ 17 files changed, 247 insertions(+), 473 deletions(-) rename .lane/{memory => attic}/src/mcp.ts/01M5R4BTBKNM2AQC2RX9XD8J8G-the-version-skew-note-applie.md (100%) rename .lane/{memory => attic}/src/mcp.ts/01M797D9876WM2MRNZ9KCCPZB6-only-the-server-instructions.md (100%) create mode 100644 .lane/memory/native2/Sources/DesktopProtocol/ContractTools.swift/01M797QZADYX1MDFB6KKZ0CFH2-the-server-instructions-mirr.md create mode 100644 .lane/memory/native2/Sources/desktop-tools-app/app.swift/01M797QZB7GB6ADBEKXMV8RKAE-the-app-must-keep-linking-st.md create mode 100644 test/mcp-launcher.test.mjs delete mode 100644 test/version-skew.test.mjs diff --git a/.lane/memory/src/mcp.ts/01M5R4BTBKNM2AQC2RX9XD8J8G-the-version-skew-note-applie.md b/.lane/attic/src/mcp.ts/01M5R4BTBKNM2AQC2RX9XD8J8G-the-version-skew-note-applie.md similarity index 100% rename from .lane/memory/src/mcp.ts/01M5R4BTBKNM2AQC2RX9XD8J8G-the-version-skew-note-applie.md rename to .lane/attic/src/mcp.ts/01M5R4BTBKNM2AQC2RX9XD8J8G-the-version-skew-note-applie.md diff --git a/.lane/memory/src/mcp.ts/01M797D9876WM2MRNZ9KCCPZB6-only-the-server-instructions.md b/.lane/attic/src/mcp.ts/01M797D9876WM2MRNZ9KCCPZB6-only-the-server-instructions.md similarity index 100% rename from .lane/memory/src/mcp.ts/01M797D9876WM2MRNZ9KCCPZB6-only-the-server-instructions.md rename to .lane/attic/src/mcp.ts/01M797D9876WM2MRNZ9KCCPZB6-only-the-server-instructions.md diff --git a/.lane/memory/native2/Sources/DesktopProtocol/ContractTools.swift/01M797QZADYX1MDFB6KKZ0CFH2-the-server-instructions-mirr.md b/.lane/memory/native2/Sources/DesktopProtocol/ContractTools.swift/01M797QZADYX1MDFB6KKZ0CFH2-the-server-instructions-mirr.md new file mode 100644 index 0000000..f884fdd --- /dev/null +++ b/.lane/memory/native2/Sources/DesktopProtocol/ContractTools.swift/01M797QZADYX1MDFB6KKZ0CFH2-the-server-instructions-mirr.md @@ -0,0 +1,8 @@ +--- +id: 01M797QZADYX1MDFB6KKZ0CFH2 +anchor: instructions(app:) +created: 2026-11-13T01:18:23Z +norm: '1' +--- + +The server instructions mirror githubnext/ace packages/channel/src/desktop.ts guidance; keep the two alike when either changes diff --git a/.lane/memory/native2/Sources/desktop-tools-app/app.swift/01M797QZB7GB6ADBEKXMV8RKAE-the-app-must-keep-linking-st.md b/.lane/memory/native2/Sources/desktop-tools-app/app.swift/01M797QZB7GB6ADBEKXMV8RKAE-the-app-must-keep-linking-st.md new file mode 100644 index 0000000..3e3f178 --- /dev/null +++ b/.lane/memory/native2/Sources/desktop-tools-app/app.swift/01M797QZB7GB6ADBEKXMV8RKAE-the-app-must-keep-linking-st.md @@ -0,0 +1,8 @@ +--- +id: 01M797QZB7GB6ADBEKXMV8RKAE +anchor: '@file' +created: 2026-11-13T01:18:23Z +norm: '1' +--- + +The app must keep linking /desktop-client to its bundled client, beside its desktop-tools-mcp: npx launchers pinned to any release since v0.17.0 find the app's server only through that link (#237) diff --git a/CHANGELOG.md b/CHANGELOG.md index a6aaf52..afe2860 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Notable changes to Desktop Tools, newest first. Each release's GitHub release no ### Changed +- `desktop-tools-mcp` from npm (`dist/mcp.js`) is now only a launcher: it runs the app's own Swift server and hands stdin and stdout over to it, so no MCP traffic passes through Node. The Node MCP server is gone. With options, which used to keep the Node server, it now runs the server of the app that `--client` names, passing `--socket` and `--name` on. An app without a server of its own (Desktop Tools before 0.17.0, or an embedder's app that ships none beside its client) makes it exit with a message naming the app, its version and what to install, where a Node server used to fail every call. Prefer pointing the MCP config at `/Applications/Desktop Tools.app/Contents/MacOS/desktop-tools-mcp`, which needs no Node. Parity, bench and live-check scripts default to the app's own server. ([#237](https://github.com/githubnext/desktop-tools/issues/237)) - Tool descriptions, schemas and the rules they share are declared in Swift, in `native2/Sources/DesktopProtocol/ContractTools.swift`, which the app's MCP server serves. `@githubnext/desktop-tools/tools` and the key and wait-condition lists in `/protocol` are generated from those declarations (`npm run contract`) and export the same values as before. `desktopRequest` no longer checks the exclusive argument forms of `desktop_clipboard_write` and `desktop_dialog_answer` itself: the host refuses them with the same text. `DESKTOP_EXPECT_OPS` lists its ops in tool order. ([#237](https://github.com/githubnext/desktop-tools/issues/237)) ### Fixed diff --git a/README.md b/README.md index 217cab0..ca1c743 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ You need macOS 15 or later. The MCP server ships inside the app. } ``` - An `npx` setup, `npx -y --package=github:githubnext/desktop-tools#v0.20.0 desktop-tools-mcp` (Node 22 or later), also works: it hands over to the app's server. One pinned before v0.17.0 is refused with `CLIENT_OUTDATED`, so update its tag. Updating the tag doesn't update the app, which holds the macOS permissions: install the app's release of the same version, since an app from before v0.17.0 has no server to hand over to, and a failed call then names both versions. A background job, such as `claude --bg`, doesn't load nvm from your shell, so give `npx` by its absolute path there. + An `npx` setup, `npx -y --package=github:githubnext/desktop-tools#v0.20.0 desktop-tools-mcp` (Node 22 or later), also works: it runs only a launcher that hands over to the app's server, so no MCP traffic passes through Node. One pinned before v0.17.0 is refused with `CLIENT_OUTDATED`, so update its tag. Updating the tag doesn't update the app, which holds the macOS permissions: install the app's release of the same version, since an app from before v0.17.0 has no server to hand over to, and the launcher then exits naming its version. A background job, such as `claude --bg`, doesn't load nvm from your shell, so give `npx` by its absolute path there. 4. **Verify.** Ask the agent to call `desktop_apps`. It should list the running apps with an `inventory_completeness` of `complete`. If it says the socket is missing, open the app. diff --git a/dist/mcp.js b/dist/mcp.js index 20b659e..082be97 100644 --- a/dist/mcp.js +++ b/dist/mcp.js @@ -1,202 +1,66 @@ #!/usr/bin/env node +// desktop-tools-mcp for npx setups and checkouts: it runs the Desktop Tools app's own MCP server, written in Swift, and +// hands stdin and stdout over to it. No MCP traffic passes through Node. Point the MCP config at the app's +// `desktop-tools-mcp` directly to need no Node at all (#237). import { spawn } from "node:child_process"; import { existsSync, readFileSync, realpathSync } from "node:fs"; import { constants as osConstants, homedir } from "node:os"; import { dirname, join } from "node:path"; -import { createInterface } from "node:readline"; import { parseArgs } from "node:util"; -import { createDesktop } from "./client.js"; -import { isDesktopAction } from "./protocol.js"; -import { desktopRequest, desktopToolRules, desktopTools } from "./tools.js"; const { values } = parseArgs({ options: { client: { type: "string" }, socket: { type: "string" }, name: { type: "string" }, wire: { type: "string" } }, strict: true, }); -// Desktop Tools.app links its client and serves its socket here; pass all three to use another host app. -const state = process.env.DESKTOP_TOOLS_STATE || join(homedir(), ".local", "state", "desktop-tools"); -// The app bundles its own MCP server beside the client it links (0.17.0 and later), so existing npx configs hand over to -// it. Any option keeps this server, which forwards each call through that client, as does an app without one. -const bundled = (() => { - try { - return join(dirname(realpathSync(join(state, "desktop-client"))), "desktop-tools-mcp"); - } - catch { - return undefined; - } -})(); -if (Object.keys(values).length === 0 && bundled && existsSync(bundled)) { - const server = spawn(bundled, [], { stdio: "inherit" }); - for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) - process.on(signal, () => server.kill(signal)); - server.on("error", (error) => { - process.stderr.write(`Cannot run ${bundled}: ${error.message}\n`); - process.exit(1); - }); - server.on("exit", (code, signal) => process.exit(code ?? (signal ? 128 + osConstants.signals[signal] : 1))); - // The bundled server owns stdin and stdout from here. - await new Promise(() => { }); -} -const { client = join(state, "desktop-client"), socket = join(state, "desktop.sock"), name: host = "Desktop Tools", } = values; -// --wire 2 chose the Swift host's wire while the Peekaboo stack's was the default. It is the only wire now, but the option -// still keeps this server instead of handing over. +// --wire 2 chose the Swift host's wire while the Peekaboo stack's was the default; it is the only wire now. if (values.wire !== undefined && values.wire !== "2") { throw new Error("--wire 1 was the Peekaboo stack, which is gone; pass --wire 2 or leave it out."); } -const config = { client, socket, name: host }; -const desktop = createDesktop(config); const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")); -// An app from before 0.17.0 bundles no MCP server, so this one stays, and an npx tag updated without the app runs -// against an older client and host (#179), whose Peekaboo wire this server no longer speaks. Every failed call names -// both versions, since nothing else shows the skew. -const app = (() => { +// Desktop Tools.app links its client here. --client names another app's, as .app/Contents/MacOS/desktop-tools-client; +// that app's own server, beside it, is the one that serves it, since a signed host serves only its own app's programs. +const state = process.env.DESKTOP_TOOLS_STATE || join(homedir(), ".local", "state", "desktop-tools"); +const client = values.client ?? join(state, "desktop-client"); +const linked = (() => { try { - // .app/Contents/MacOS/desktop-tools-client - const contents = dirname(dirname(realpathSync(client))); - if (!contents.endsWith(".app/Contents")) - return undefined; - const plist = readFileSync(join(contents, "Info.plist"), "utf8"); - const found = /CFBundleShortVersionString<\/key>\s*([^<]+)<\/string>/.exec(plist); - return found ? { path: dirname(contents), version: found[1] } : undefined; + return realpathSync(client); } catch { return undefined; } })(); -const skew = app && app.version !== version - ? `${app.path} is version ${app.version}, but this MCP server is ${version}. Updating the npx tag doesn't update the app, ` - + `which holds the macOS permissions: ask the user to install Desktop Tools ${version} from its GitHub release, or to pin ` - + `the MCP server to v${app.version}.` - : undefined; -if (skew) - process.stderr.write(`desktop-tools-mcp: ${skew}\n`); -// Newest first; an unsupported client version gets the newest, as the MCP lifecycle requires. -const VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]; -// Guidance mirrors Ace's desktop extension so agents behave alike; tools and their shared rules come from the shared definitions. -const instructions = [ - `Use desktop_* tools to observe and operate native apps on this Mac through ${host}, which holds the macOS permissions.`, - "Shell commands remain appropriate for builds, files, and preparing clipboard fixtures directly.", - "", - "Do not silently substitute AppleScript, osascript, System Events, or self-built Accessibility or CGEvent programs for desktop tools.", - "Apple Events can raise a separate macOS Automation prompt for each target app, attributed to the calling terminal or agent; Accessibility and Screen Recording grants do not cover them.", - "Custom input programs bypass the desktop tools' snapshot and exact-target checks, even when they raise no permission prompt.", - "Before using a fallback, tell the user which native tool or capability cannot do the step and why the fallback is needed, including any Automation prompts it can trigger.", - "Use the user's existing authorization; this guidance adds no separate approval requirement.", - "", - "Action results start with their outcome: completed, refused, or unknown.", - "For a refusal before dispatch, follow its concrete recovery hint once when applicable, then refresh the observation; a refusal alone does not prove the capability is missing.", - "After completed, interrupted, or uncertain input, inspect the current target before deciding whether another action is needed. Never replay input just because its follow-up observation failed.", - "", - ...desktopToolRules(host), -].join("\n"); -const tools = desktopTools({ place: "this Mac", app: host }); -const byName = new Map(tools.map((tool) => [tool.name, tool])); -const listed = tools.map(({ name, op, description, parameters }) => ({ - name, - description, - inputSchema: parameters, - annotations: { readOnlyHint: !isDesktopAction({ op }) }, -})); -// The host labels the window in use with the agent's name; unknown clients show as "Agent". -const AGENTS = [ - [/claude/i, "Claude"], - [/codex/i, "Codex"], - [/cursor/i, "Cursor"], - [/gemini/i, "Gemini"], - [/copilot/i, "Copilot"], -]; -function agentName(info) { - const { name, title } = (info ?? {}); - const known = AGENTS.find(([pattern]) => typeof name === "string" && pattern.test(name)); - if (known) - return known[1]; - return typeof title === "string" && title.trim() ? title.trim().slice(0, 40) : undefined; -} -const send = (value) => process.stdout.write(`${JSON.stringify(value)}\n`); -const fail = (id, code, message) => send({ jsonrpc: "2.0", id, error: { code, message } }); -const running = new Map(); -// Actions run one at a time, as in Ace; each input depends on the state the previous one left. -let actions = Promise.resolve(); -async function call(tool, args, signal) { - try { - const result = await desktop(desktopRequest(tool, args), signal); - const content = [{ type: "text", text: result.text }]; - if (result.outcome) - content.unshift({ type: "text", text: `Outcome: ${result.outcome}.` }); - if (result.image) - content.push({ type: "image", ...result.image }); - if (result.isError && skew) - content.push({ type: "text", text: skew }); - return { content, isError: result.isError || false }; - } - catch (error) { - const text = error instanceof Error ? error.message : String(error); - return { content: [{ type: "text", text }, ...(skew ? [{ type: "text", text: skew }] : [])], isError: true }; - } -} -async function handle(message) { - const { id, method, params = {} } = message; - // This server sends no requests, so a message without a method is a stray response. - if (!method) - return; - if (id === undefined) { - if (method === "notifications/cancelled") { - running.get(params.requestId)?.abort(new Error(String(params.reason || "Cancelled."))); +const server = linked && join(dirname(linked), "desktop-tools-mcp"); +if (!server || !existsSync(server)) { + const releases = `https://github.com/githubnext/desktop-tools/releases/tag/v${version}`; + // .app/Contents/MacOS/desktop-tools-client + const contents = linked && dirname(dirname(linked)); + const plist = (() => { + try { + return contents?.endsWith(".app/Contents") ? readFileSync(join(contents, "Info.plist"), "utf8") : undefined; } - return; - } - if (method === "initialize") { - const requested = String(params.protocolVersion); - config.agent = agentName(params.clientInfo); - return send({ - jsonrpc: "2.0", - id, - result: { - protocolVersion: VERSIONS.includes(requested) ? requested : VERSIONS[0], - capabilities: { tools: {} }, - serverInfo: { name: "desktop-tools", version }, - instructions, - }, - }); - } - if (method === "ping") - return send({ jsonrpc: "2.0", id, result: {} }); - if (method === "tools/list") - return send({ jsonrpc: "2.0", id, result: { tools: listed } }); - if (method !== "tools/call") - return fail(id, -32601, `Method not found: ${method}`); - const tool = byName.get(String(params.name)); - if (!tool) - return fail(id, -32602, `Unknown tool: ${params.name}`); - const args = (params.arguments || {}); - const controller = new AbortController(); - running.set(id, controller); - const { signal } = controller; - let pending; - if (isDesktopAction({ op: tool.op })) { - pending = actions.then(() => call(tool, args, signal)); - actions = pending; - } - else { - pending = call(tool, args, signal); - } - const result = await pending; - running.delete(id); - // A cancelled request gets no response. - if (!signal.aborted) - send({ jsonrpc: "2.0", id, result }); + catch { + return undefined; + } + })(); + const appVersion = plist && /CFBundleShortVersionString<\/key>\s*([^<]+)<\/string>/.exec(plist)?.[1]; + const appName = plist && /CFBundleName<\/key>\s*([^<]+)<\/string>/.exec(plist)?.[1]; + const found = !linked + ? `No Desktop Tools app has linked its client at ${client}: install and open Desktop Tools ${version} (${releases}).` + : appName && !appName.startsWith("Desktop Tools") + // An embedder's app serves MCP only if it bundles desktop-tools-mcp beside its client (docs/embed.md). + ? `${appName} bundles no desktop-tools-mcp beside ${linked}, so it can't serve the desktop tools over MCP. ` + + "An embedding app can ship desktop-tools-mcp from a native build beside its client (docs/embed.md)." + : `${dirname(contents)} is version ${appVersion ?? "unknown"}, which has no MCP server of its own (0.17.0 and later ` + + `bundle one): install Desktop Tools ${version} (${releases}).`; + process.stderr.write(`desktop-tools-mcp: ${found} Then set the MCP server up as "/Applications/Desktop Tools.app/Contents/MacOS/desktop-tools-mcp", ` + + "which needs no Node.\n"); + process.exit(1); } -createInterface({ input: process.stdin }).on("line", (line) => { - if (!line.trim()) - return; - let message; - try { - message = JSON.parse(line); - } - catch { - return fail(null, -32700, "Parse error"); - } - if (!message || typeof message !== "object" || Array.isArray(message)) { - return fail(null, -32600, "Invalid request"); - } - void handle(message); +const args = [...(values.socket ? ["--socket", values.socket] : []), ...(values.name ? ["--name", values.name] : [])]; +const child = spawn(server, args, { stdio: "inherit" }); +for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) + process.on(signal, () => child.kill(signal)); +child.on("error", (error) => { + process.stderr.write(`desktop-tools-mcp: Cannot run ${server}: ${error.message}\n`); + process.exit(1); }); +child.on("exit", (code, signal) => process.exit(code ?? (signal ? 128 + osConstants.signals[signal] : 1))); diff --git a/docs/live-checks.md b/docs/live-checks.md index db744ed..a4a1a8f 100644 --- a/docs/live-checks.md +++ b/docs/live-checks.md @@ -1,6 +1,6 @@ # Live checks -The live checks in [#42](https://github.com/githubnext/desktop-tools/issues/42) need an unlocked Mac. `npm run live-check` runs the ones that can be automated, through the same MCP server (`dist/mcp.js`) and host that agents use: +The live checks in [#42](https://github.com/githubnext/desktop-tools/issues/42) need an unlocked Mac. `npm run live-check` runs the ones that can be automated, through the app's own MCP server (`.app/Contents/MacOS/desktop-tools-mcp`, found through the client the app links in its state folder) and host that agents use: ```sh npm run live-check # the installed app diff --git a/docs/mcp.md b/docs/mcp.md index 66eef82..047b125 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,34 +1,27 @@ # Use from an MCP client -`desktop-tools-mcp` (`dist/mcp.js`) serves the desktop tools over stdio MCP, with Ace's native-first guidance as its instructions. By default it uses the [Desktop Tools app](app.md)'s signed client and socket in `~/.local/state/desktop-tools`. Run it from this repository with `npx`, pinned to a release tag, or from a checkout with `node`: +The [Desktop Tools app](app.md) bundles the MCP server, `Desktop Tools.app/Contents/MacOS/desktop-tools-mcp`, written in Swift. It serves the desktop tools over stdio MCP, with Ace's native-first guidance as its instructions, and needs no Node. Set it up by its path: ```sh -claude mcp add desktop -- npx -y --package=github:githubnext/desktop-tools#v0.20.0 desktop-tools-mcp -claude mcp add desktop -- node /dist/mcp.js +claude mcp add desktop -- "/Applications/Desktop Tools.app/Contents/MacOS/desktop-tools-mcp" ``` -The [README](https://github.com/githubnext/desktop-tools#set-up-for-an-agent) has the setup for Codex and for clients configured with JSON. +For Codex, in `~/.codex/config.toml`: -The app bundles its own MCP server (since 0.17.0), `Desktop Tools.app/Contents/MacOS/desktop-tools-mcp`, written in Swift. Run with no options, `dist/mcp.js` finds it beside the client the app links and hands stdio over to it, so an `npx` setup needs no change. Any option keeps the Node server, which forwards each call through the host's `desktop-tools-client` as [`createDesktop`](node.md) does; `--wire 2` is accepted for that, and `--wire 1`, the removed Peekaboo stack, is refused. An app from before 0.17.0 has no server of its own and its client speaks the Peekaboo stack's wire, which the Node server no longer does, so every call fails, ending with both versions when they differ: updating the `npx` tag doesn't update the app. +```toml +[mcp_servers.desktop] +command = "/Applications/Desktop Tools.app/Contents/MacOS/desktop-tools-mcp" +``` -The app's server needs no Node. It serves the socket in its app's state folder (`DESKTOP_TOOLS_STATE`, else the folder its bundle ID chooses), or `--socket `, and names its app in the instructions and rules: the app it ships in, or `--name `. So the [development app](build.md#development-app)'s server, `Desktop Tools Dev.app/Contents/MacOS/desktop-tools-mcp`, serves `~/.local/state/desktop-tools-dev` as **Desktop Tools Dev** with no options. +The [README](https://github.com/githubnext/desktop-tools#set-up-for-an-agent) has the setup for clients configured with JSON. -To use another signed host's grants instead, pass its client, socket, and name. The host must embed the Swift runtime from `native2/`; one that still embeds the Peekaboo stack's can't be served. For Ace Canary: +The server serves the socket in its app's state folder (`DESKTOP_TOOLS_STATE`, else the folder its bundle ID chooses), or `--socket `, and names its app in the instructions and rules: the app it ships in, or `--name `. So the [development app](build.md#development-app)'s server, `Desktop Tools Dev.app/Contents/MacOS/desktop-tools-mcp`, serves `~/.local/state/desktop-tools-dev` as **Desktop Tools Dev** with no options. A signed host serves only its own app's programs, so another app's grants are used through that app's own `desktop-tools-mcp`, which an [embedding app](embed.md) can ship beside its client. -```sh -claude mcp add desktop -- node /dist/mcp.js \ - --client ~/.local/state/ace-canary/desktop-client \ - --socket ~/.local/state/ace-canary/desktop.sock \ - --name "Ace Canary" -``` +## npx setups -For Codex, in `~/.codex/config.toml`: +`npx -y --package=github:githubnext/desktop-tools#v0.20.0 desktop-tools-mcp` (Node 22 or later) also works. It runs only a launcher, `dist/mcp.js`, which finds the app's server beside the client the app links in its state folder and hands stdin and stdout over to it; no MCP traffic passes through Node. `--client .app/Contents/MacOS/desktop-tools-client` runs that app's server instead, and `--socket` and `--name` are passed on to it. `--wire 2` is accepted and ignored, and `--wire 1`, the removed Peekaboo stack, is refused. -```toml -[mcp_servers.desktop] -command = "npx" -args = ["-y", "--package=github:githubnext/desktop-tools#v0.20.0", "desktop-tools-mcp"] -``` +When there is no server to hand over to, the launcher exits with a message instead: no app has linked its client, the app is from before 0.17.0 and has no server of its own (the message names its version and the release to install), or `--client` names an embedder's app that ships no `desktop-tools-mcp`. Updating the `npx` tag doesn't update the app, which holds the macOS permissions. A setup pinned before v0.17.0 is refused with `CLIENT_OUTDATED`, so update its tag, or better, point it at the app's server. The tool names, descriptions, and argument schemas are declared in Swift (`native2/Sources/DesktopProtocol/ContractTools.swift`), and `@githubnext/desktop-tools/tools` (`desktopTools`, `desktopRequest`) exports them, generated from that file, for Ace's `desktop_*` tools and other embedders. [Tools](tools.md) lists them. The descriptions don't repeat the rules every tool shares: exact targets, single-use snapshots, background and foreground input, what each outcome means, pausing, `desktop_wait` and `expect`, and the recipes. `desktopToolRules(app)` returns those rules, and the server adds them to its instructions; a host with its own agent guidance should include them too. diff --git a/native2/README.md b/native2/README.md index cf8e732..f7a0cfc 100644 --- a/native2/README.md +++ b/native2/README.md @@ -14,7 +14,7 @@ The desktop tools' only native code: a Swift MCP server, host and embedding runt | `desktop-tools-host` | A standalone host, run from a terminal for development; it uses the terminal's macOS grants | | `desktop-tools-app` | The Desktop Tools menu bar app, which loads `libDesktopTools.dylib` | | `desktop-tools-mcp` | The stdio MCP server, which forwards each call to the host: its app's socket, or `--socket`, naming its app, or `--name`, in the instructions. `--contract` prints the tool declarations instead | -| `desktop-tools-client` | One tool call per run, or every call over one connection with `--serve`, for `createDesktop` and `dist/mcp.js` with options (docs/node.md) | +| `desktop-tools-client` | One tool call per run, or every call over one connection with `--serve`, for `createDesktop` (docs/node.md) and MCP launchers pinned to v0.17.0–v0.20.0 run with options | | `DesktopTools` | `libDesktopTools.dylib`, the menu bar app's embedding runtime with the C ABI in docs/embed.md: it serves the host's `Server` and draws the agent cursor, window outline and activity list through `DesktopHost/Hooks.swift` | The standalone host serves `~/.local/state/desktop-tools2/desktop.sock`, or `$DESKTOP_TOOLS2_STATE/desktop.sock`, so it runs beside the installed Desktop Tools, which serves `~/.local/state/desktop-tools`. It accepts a connection only from the same user, and, when the host is signed, only from an MCP binary signed by the same team with the expected identifier (`DesktopPeer/Peer.swift`: the socket's audit token, checked with Security and a CDHash read before and after). In turn, a signed client or MCP server sends nothing to a host that isn't the same user's and signed by its team (`DesktopAppLink/Trust.swift`). @@ -38,7 +38,7 @@ node native2/scripts/parity.mjs calls native2/scripts/calls-core.json # argume node native2/scripts/parity.mjs steps native2/scripts/steps-core.json # actions on the fixture window ``` -`parity.mjs` runs each entry through two MCP servers, one at a time, and prints where they differ: `--server` (this checkout's release build by default) and `--baseline` (`node dist/mcp.js` by default, which hands over to the installed app's bundled server). `calls` sends each `[tool, args]` as is. `steps` inspects the fixture window first and fills in `"$snapshot"`, `"$pid"`, `"$window"`, `"$role:AXTextField"` and `"$label:Press me"`. Add each fix's calls and steps entries to the files. Run calls-text between `clip save` and `clip restore`, since it writes the clipboard. The steps files act on live windows; they and `node scripts/live-check.mjs --server native2/.build/release/desktop-tools-mcp` need an unlocked session. +`parity.mjs` runs each entry through two MCP servers, one at a time, and prints where they differ: `--server` (this checkout's release build by default) and `--baseline` (the installed app's own server, `/Applications/Desktop Tools.app/Contents/MacOS/desktop-tools-mcp`, by default; a command that names an existing file runs as is, spaces and all). `calls` sends each `[tool, args]` as is. `steps` inspects the fixture window first and fills in `"$snapshot"`, `"$pid"`, `"$window"`, `"$role:AXTextField"` and `"$label:Press me"`. Add each fix's calls and steps entries to the files. Run calls-text between `clip save` and `clip restore`, since it writes the clipboard. The steps files act on live windows; they and `node scripts/live-check.mjs --server native2/.build/release/desktop-tools-mcp` need an unlocked session. The fixture is a small AppKit window that logs every mouse event it receives: diff --git a/native2/scripts/bench.mjs b/native2/scripts/bench.mjs index 6a92b08..93f248e 100644 --- a/native2/scripts/bench.mjs +++ b/native2/scripts/bench.mjs @@ -1,14 +1,15 @@ #!/usr/bin/env node import { spawn } from "node:child_process"; -function server(cmd){const [f,...a]=cmd.split(" ");const c=spawn(f,a,{stdio:["pipe","pipe","inherit"]});let buf="",n=1;const w=new Map(); +import { existsSync } from "node:fs"; +function server(cmd){const [f,...a]=existsSync(cmd)?[cmd]:cmd.split(" ");const c=spawn(f,a,{stdio:["pipe","pipe","inherit"]});let buf="",n=1;const w=new Map(); c.stdout.on("data",d=>{buf+=d;let i;while((i=buf.indexOf("\n"))>=0){const l=buf.slice(0,i);buf=buf.slice(i+1);const m=JSON.parse(l);w.get(m.id)?.(m.result??m.error);}}); const req=(method,params={})=>new Promise(r=>{const id=n++;w.set(id,r);c.stdin.write(JSON.stringify({jsonrpc:"2.0",id,method,params})+"\n")}); return {req,call:(name,args)=>req("tools/call",{name,arguments:args}),stop:()=>c.kill()}} const j=r=>{const t=r.content.find(c=>c.text?.startsWith("{"));return t?JSON.parse(t.text):{}}; -// Times the core tools on the fixture window through this checkout's release build and the installed app's server, which -// node dist/mcp.js hands over to: node native2/scripts/bench.mjs [runs] +// Times the core tools on the fixture window through this checkout's release build and the installed app's own server: +// node native2/scripts/bench.mjs [runs] const runs=Number(process.argv[2]??10); -const S={build:"native2/.build/release/desktop-tools-mcp",installed:"node dist/mcp.js"}; +const S={build:"native2/.build/release/desktop-tools-mcp",installed:"/Applications/Desktop Tools.app/Contents/MacOS/desktop-tools-mcp"}; const p=(xs,q)=>{const s=[...xs].sort((a,b)=>a-b);return Math.round(s[Math.min(s.length-1,Math.floor(q*s.length))])}; const res={}; for(const [name,cmd] of Object.entries(S)){ diff --git a/native2/scripts/parity.mjs b/native2/scripts/parity.mjs index f68997c..4c37e78 100644 --- a/native2/scripts/parity.mjs +++ b/native2/scripts/parity.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node // Runs the same tool calls through two MCP servers and prints where their results differ: by default this checkout's -// release build and `node dist/mcp.js`, which hands over to the installed app's bundled server, so a change is checked -// against the last release. +// release build and the installed app's own server, so a change is checked against the last release. A command that +// names an existing file is run as is, so a path may contain spaces. // // node native2/scripts/parity.mjs calls each [tool, args], sent as is // node native2/scripts/parity.mjs steps each [tool, args] after a fresh inspect of the fixture window @@ -16,14 +16,14 @@ // start identities, the route (local, or bridge from servers before the cutover), timings and the observation's own fields are ignored, so an // action compares by its action object and the observation's field names. import { spawn } from "node:child_process"; -import { readFileSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; import { parseArgs } from "node:util"; const { values, positionals } = parseArgs({ allowPositionals: true, options: { server: { type: "string", default: "native2/.build/release/desktop-tools-mcp" }, - baseline: { type: "string", default: "node dist/mcp.js" }, + baseline: { type: "string", default: "/Applications/Desktop Tools.app/Contents/MacOS/desktop-tools-mcp" }, app: { type: "string", default: "fixture" }, window: { type: "string", default: "Click Fixture" }, window2: { type: "string" }, @@ -39,7 +39,7 @@ if (!["calls", "steps"].includes(mode) || !file) { const entries = JSON.parse(readFileSync(file, "utf8")); function server(command) { - const [executable, ...args] = command.split(" ").filter(Boolean); + const [executable, ...args] = existsSync(command) ? [command] : command.split(" ").filter(Boolean); const child = spawn(executable, args, { stdio: ["pipe", "pipe", "inherit"] }); const waiting = new Map(); let buffer = "", next = 1; diff --git a/scripts/bench.mjs b/scripts/bench.mjs index 74f03a8..2d8203b 100644 --- a/scripts/bench.mjs +++ b/scripts/bench.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node // Times read-only tools through any MCP server, so two builds or releases run the same scenarios. import { spawn } from "node:child_process"; -import { writeFileSync } from "node:fs"; +import { existsSync, writeFileSync } from "node:fs"; import { performance } from "node:perf_hooks"; import { parseArgs } from "node:util"; @@ -18,7 +18,7 @@ const { values } = parseArgs({ if (values.help || !values.server?.length) { console.log(`Usage: node scripts/bench.mjs --server "" [--server ""] [--runs 20] [--only apps,windows] [--json ] -Each server command is split on spaces and spoken to over stdio. Only read-only tools run.`); +Each server command is split on spaces, unless it names an existing file, and spoken to over stdio. Only read-only tools run.`); process.exit(values.help ? 0 : 1); } const runs = Number(values.runs); @@ -26,7 +26,8 @@ const only = values.only ? new Set(values.only.split(",")) : undefined; class Mcp { constructor(command) { - const [file, ...args] = command.split(" ").filter(Boolean); + // A command that names an existing file runs as is, so a path may contain spaces. + const [file, ...args] = existsSync(command) ? [command] : command.split(" ").filter(Boolean); this.next = 1; this.waiting = new Map(); this.child = spawn(file, args, { stdio: ["pipe", "pipe", "inherit"] }); diff --git a/scripts/live-check.mjs b/scripts/live-check.mjs index 3544269..27f36ca 100644 --- a/scripts/live-check.mjs +++ b/scripts/live-check.mjs @@ -3,9 +3,9 @@ // It works only on fixtures it creates and windows it opens, and closes them at the end, even on failure. import { spawn } from "node:child_process"; import { createHash, randomBytes } from "node:crypto"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { homedir, tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { pathToFileURL } from "node:url"; import { parseArgs } from "node:util"; import { deflateSync } from "node:zlib"; @@ -25,8 +25,8 @@ if (values.help) { console.log(`Usage: npm run live-check -- [--only [,]] [--list] [--json ] [--keep-fixtures] [--server ] Drives the installed Desktop Tools, or the dev app whose state folder is DESKTOP_TOOLS_STATE -(~/.local/state/desktop-tools-dev for npm run dev-app), through dist/mcp.js, or through the MCP server executable ---server names. Refuses to run while the screen is locked. See docs/live-checks.md.`); +(~/.local/state/desktop-tools-dev for npm run dev-app), through that app's own MCP server, or through the MCP server +executable --server names. Refuses to run while the screen is locked. See docs/live-checks.md.`); process.exit(0); } const only = new Set((values.only ?? []).flatMap((v) => v.split(",")).map((v) => v.trim().replace(/^#/, "")).filter(Boolean)); @@ -41,12 +41,23 @@ const STATE = process.env.DESKTOP_TOOLS_STATE || join(homedir(), ".local", "stat // ---------- MCP client ---------- +/** The MCP server of the app whose client STATE links, as agents set it up: .app/Contents/MacOS/desktop-tools-mcp. */ +function appServer() { + let client; + try { + client = realpathSync(join(STATE, "desktop-client")); + } catch { + throw new Error(`No app has linked its client at ${join(STATE, "desktop-client")}; open it, or pass --server.`); + } + return join(dirname(client), "desktop-tools-mcp"); +} + class Mcp { /** `launcher` runs the server under another program, which the host then sees as its caller. */ constructor(launcher = []) { this.next = 1; this.waiting = new Map(); - const server = values.server ? [values.server] : [process.execPath, new URL("../dist/mcp.js", import.meta.url).pathname]; + const server = [values.server ?? appServer()]; const command = [...launcher, ...server]; this.child = spawn(command[0], command.slice(1), { stdio: ["pipe", "pipe", "inherit"], diff --git a/src/mcp.ts b/src/mcp.ts index 27f316b..fa5fed6 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -1,207 +1,69 @@ #!/usr/bin/env node +// desktop-tools-mcp for npx setups and checkouts: it runs the Desktop Tools app's own MCP server, written in Swift, and +// hands stdin and stdout over to it. No MCP traffic passes through Node. Point the MCP config at the app's +// `desktop-tools-mcp` directly to need no Node at all (#237). import { spawn } from "node:child_process"; import { existsSync, readFileSync, realpathSync } from "node:fs"; import { constants as osConstants, homedir } from "node:os"; import { dirname, join } from "node:path"; -import { createInterface } from "node:readline"; import { parseArgs } from "node:util"; -import { type DesktopConfig, createDesktop } from "./client.js"; -import { type DesktopRequest, isDesktopAction } from "./protocol.js"; -import { type DesktopTool, desktopRequest, desktopToolRules, desktopTools } from "./tools.js"; - const { values } = parseArgs({ options: { client: { type: "string" }, socket: { type: "string" }, name: { type: "string" }, wire: { type: "string" } }, strict: true, }); -// Desktop Tools.app links its client and serves its socket here; pass all three to use another host app. -const state = process.env.DESKTOP_TOOLS_STATE || join(homedir(), ".local", "state", "desktop-tools"); - -// The app bundles its own MCP server beside the client it links (0.17.0 and later), so existing npx configs hand over to -// it. Any option keeps this server, which forwards each call through that client, as does an app without one. -const bundled = (() => { - try { - return join(dirname(realpathSync(join(state, "desktop-client"))), "desktop-tools-mcp"); - } catch { - return undefined; - } -})(); -if (Object.keys(values).length === 0 && bundled && existsSync(bundled)) { - const server = spawn(bundled, [], { stdio: "inherit" }); - for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) process.on(signal, () => server.kill(signal)); - server.on("error", (error) => { - process.stderr.write(`Cannot run ${bundled}: ${error.message}\n`); - process.exit(1); - }); - server.on("exit", (code, signal) => process.exit(code ?? (signal ? 128 + osConstants.signals[signal] : 1))); - // The bundled server owns stdin and stdout from here. - await new Promise(() => {}); -} -const { - client = join(state, "desktop-client"), - socket = join(state, "desktop.sock"), - name: host = "Desktop Tools", -} = values; -// --wire 2 chose the Swift host's wire while the Peekaboo stack's was the default. It is the only wire now, but the option -// still keeps this server instead of handing over. +// --wire 2 chose the Swift host's wire while the Peekaboo stack's was the default; it is the only wire now. if (values.wire !== undefined && values.wire !== "2") { throw new Error("--wire 1 was the Peekaboo stack, which is gone; pass --wire 2 or leave it out."); } -const config: DesktopConfig = { client, socket, name: host }; -const desktop = createDesktop(config); -const { version } = JSON.parse( - readFileSync(new URL("../package.json", import.meta.url), "utf8"), -) as { version: string }; +const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version: string }; -// An app from before 0.17.0 bundles no MCP server, so this one stays, and an npx tag updated without the app runs -// against an older client and host (#179), whose Peekaboo wire this server no longer speaks. Every failed call names -// both versions, since nothing else shows the skew. -const app = (() => { +// Desktop Tools.app links its client here. --client names another app's, as .app/Contents/MacOS/desktop-tools-client; +// that app's own server, beside it, is the one that serves it, since a signed host serves only its own app's programs. +const state = process.env.DESKTOP_TOOLS_STATE || join(homedir(), ".local", "state", "desktop-tools"); +const client = values.client ?? join(state, "desktop-client"); +const linked = (() => { try { - // .app/Contents/MacOS/desktop-tools-client - const contents = dirname(dirname(realpathSync(client))); - if (!contents.endsWith(".app/Contents")) return undefined; - const plist = readFileSync(join(contents, "Info.plist"), "utf8"); - const found = /CFBundleShortVersionString<\/key>\s*([^<]+)<\/string>/.exec(plist); - return found ? { path: dirname(contents), version: found[1]! } : undefined; + return realpathSync(client); } catch { return undefined; } })(); -const skew = app && app.version !== version - ? `${app.path} is version ${app.version}, but this MCP server is ${version}. Updating the npx tag doesn't update the app, ` - + `which holds the macOS permissions: ask the user to install Desktop Tools ${version} from its GitHub release, or to pin ` - + `the MCP server to v${app.version}.` - : undefined; -if (skew) process.stderr.write(`desktop-tools-mcp: ${skew}\n`); - -// Newest first; an unsupported client version gets the newest, as the MCP lifecycle requires. -const VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]; - -// Guidance mirrors Ace's desktop extension so agents behave alike; tools and their shared rules come from the shared definitions. -const instructions = [ - `Use desktop_* tools to observe and operate native apps on this Mac through ${host}, which holds the macOS permissions.`, - "Shell commands remain appropriate for builds, files, and preparing clipboard fixtures directly.", - "", - "Do not silently substitute AppleScript, osascript, System Events, or self-built Accessibility or CGEvent programs for desktop tools.", - "Apple Events can raise a separate macOS Automation prompt for each target app, attributed to the calling terminal or agent; Accessibility and Screen Recording grants do not cover them.", - "Custom input programs bypass the desktop tools' snapshot and exact-target checks, even when they raise no permission prompt.", - "Before using a fallback, tell the user which native tool or capability cannot do the step and why the fallback is needed, including any Automation prompts it can trigger.", - "Use the user's existing authorization; this guidance adds no separate approval requirement.", - "", - "Action results start with their outcome: completed, refused, or unknown.", - "For a refusal before dispatch, follow its concrete recovery hint once when applicable, then refresh the observation; a refusal alone does not prove the capability is missing.", - "After completed, interrupted, or uncertain input, inspect the current target before deciding whether another action is needed. Never replay input just because its follow-up observation failed.", - "", - ...desktopToolRules(host), -].join("\n"); - -const tools = desktopTools({ place: "this Mac", app: host }); -const byName = new Map(tools.map((tool) => [tool.name, tool])); -const listed = tools.map(({ name, op, description, parameters }) => ({ - name, - description, - inputSchema: parameters, - annotations: { readOnlyHint: !isDesktopAction({ op } as DesktopRequest) }, -})); - -// The host labels the window in use with the agent's name; unknown clients show as "Agent". -const AGENTS: [RegExp, string][] = [ - [/claude/i, "Claude"], - [/codex/i, "Codex"], - [/cursor/i, "Cursor"], - [/gemini/i, "Gemini"], - [/copilot/i, "Copilot"], -]; -function agentName(info: unknown): string | undefined { - const { name, title } = (info ?? {}) as { name?: unknown; title?: unknown }; - const known = AGENTS.find(([pattern]) => typeof name === "string" && pattern.test(name)); - if (known) return known[1]; - return typeof title === "string" && title.trim() ? title.trim().slice(0, 40) : undefined; -} +const server = linked && join(dirname(linked), "desktop-tools-mcp"); -type Id = string | number; -type Message = { jsonrpc: "2.0"; id?: Id; method?: string; params?: Record }; -type Content = { type: "text"; text: string } | { type: "image"; data: string; mimeType: string }; - -const send = (value: unknown) => process.stdout.write(`${JSON.stringify(value)}\n`); -const fail = (id: Id | null, code: number, message: string) => - send({ jsonrpc: "2.0", id, error: { code, message } }); - -const running = new Map(); -// Actions run one at a time, as in Ace; each input depends on the state the previous one left. -let actions: Promise = Promise.resolve(); - -async function call(tool: DesktopTool, args: Record, signal: AbortSignal) { - try { - const result = await desktop(desktopRequest(tool, args), signal); - const content: Content[] = [{ type: "text", text: result.text }]; - if (result.outcome) content.unshift({ type: "text", text: `Outcome: ${result.outcome}.` }); - if (result.image) content.push({ type: "image", ...result.image }); - if (result.isError && skew) content.push({ type: "text", text: skew }); - return { content, isError: result.isError || false }; - } catch (error) { - const text = error instanceof Error ? error.message : String(error); - return { content: [{ type: "text", text }, ...(skew ? [{ type: "text", text: skew } as const] : [])], isError: true }; - } -} - -async function handle(message: Message) { - const { id, method, params = {} } = message; - // This server sends no requests, so a message without a method is a stray response. - if (!method) return; - if (id === undefined) { - if (method === "notifications/cancelled") { - running.get(params.requestId as Id)?.abort(new Error(String(params.reason || "Cancelled."))); +if (!server || !existsSync(server)) { + const releases = `https://github.com/githubnext/desktop-tools/releases/tag/v${version}`; + // .app/Contents/MacOS/desktop-tools-client + const contents = linked && dirname(dirname(linked)); + const plist = (() => { + try { + return contents?.endsWith(".app/Contents") ? readFileSync(join(contents, "Info.plist"), "utf8") : undefined; + } catch { + return undefined; } - return; - } - if (method === "initialize") { - const requested = String(params.protocolVersion); - config.agent = agentName(params.clientInfo); - return send({ - jsonrpc: "2.0", - id, - result: { - protocolVersion: VERSIONS.includes(requested) ? requested : VERSIONS[0], - capabilities: { tools: {} }, - serverInfo: { name: "desktop-tools", version }, - instructions, - }, - }); - } - if (method === "ping") return send({ jsonrpc: "2.0", id, result: {} }); - if (method === "tools/list") return send({ jsonrpc: "2.0", id, result: { tools: listed } }); - if (method !== "tools/call") return fail(id, -32601, `Method not found: ${method}`); - const tool = byName.get(String(params.name)); - if (!tool) return fail(id, -32602, `Unknown tool: ${params.name}`); - const args = (params.arguments || {}) as Record; - const controller = new AbortController(); - running.set(id, controller); - const { signal } = controller; - let pending: Promise; - if (isDesktopAction({ op: tool.op } as DesktopRequest)) { - pending = actions.then(() => call(tool, args, signal)); - actions = pending; - } else { - pending = call(tool, args, signal); - } - const result = await pending; - running.delete(id); - // A cancelled request gets no response. - if (!signal.aborted) send({ jsonrpc: "2.0", id, result }); + })(); + const appVersion = plist && /CFBundleShortVersionString<\/key>\s*([^<]+)<\/string>/.exec(plist)?.[1]; + const appName = plist && /CFBundleName<\/key>\s*([^<]+)<\/string>/.exec(plist)?.[1]; + const found = !linked + ? `No Desktop Tools app has linked its client at ${client}: install and open Desktop Tools ${version} (${releases}).` + : appName && !appName.startsWith("Desktop Tools") + // An embedder's app serves MCP only if it bundles desktop-tools-mcp beside its client (docs/embed.md). + ? `${appName} bundles no desktop-tools-mcp beside ${linked}, so it can't serve the desktop tools over MCP. ` + + "An embedding app can ship desktop-tools-mcp from a native build beside its client (docs/embed.md)." + : `${dirname(contents!)} is version ${appVersion ?? "unknown"}, which has no MCP server of its own (0.17.0 and later ` + + `bundle one): install Desktop Tools ${version} (${releases}).`; + process.stderr.write( + `desktop-tools-mcp: ${found} Then set the MCP server up as "/Applications/Desktop Tools.app/Contents/MacOS/desktop-tools-mcp", ` + + "which needs no Node.\n", + ); + process.exit(1); } -createInterface({ input: process.stdin }).on("line", (line) => { - if (!line.trim()) return; - let message: Message; - try { - message = JSON.parse(line) as Message; - } catch { - return fail(null, -32700, "Parse error"); - } - if (!message || typeof message !== "object" || Array.isArray(message)) { - return fail(null, -32600, "Invalid request"); - } - void handle(message); +const args = [...(values.socket ? ["--socket", values.socket] : []), ...(values.name ? ["--name", values.name] : [])]; +const child = spawn(server, args, { stdio: "inherit" }); +for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) process.on(signal, () => child.kill(signal)); +child.on("error", (error) => { + process.stderr.write(`desktop-tools-mcp: Cannot run ${server}: ${error.message}\n`); + process.exit(1); }); +child.on("exit", (code, signal) => process.exit(code ?? (signal ? 128 + osConstants.signals[signal] : 1))); diff --git a/test/mcp-launcher.test.mjs b/test/mcp-launcher.test.mjs new file mode 100644 index 0000000..2c0867b --- /dev/null +++ b/test/mcp-launcher.test.mjs @@ -0,0 +1,97 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; + +const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")); +const launcher = new URL("../dist/mcp.js", import.meta.url).pathname; + +/** An app bundle with a client, and a server that prints its arguments and stdin unless `server` is false. */ +function app({ name = "Desktop Tools", appVersion = version, server = true } = {}) { + const directory = realpathSync(mkdtempSync(join(tmpdir(), "desktop-tools-launcher-"))); + const bundle = join(directory, `${name}.app`); + const macos = join(bundle, "Contents", "MacOS"); + mkdirSync(macos, { recursive: true }); + writeFileSync(join(bundle, "Contents", "Info.plist"), ` + + CFBundleName${name} + CFBundleShortVersionString${appVersion} + +`); + const client = join(macos, "desktop-tools-client"); + writeFileSync(client, "#!/bin/sh\nexit 1\n"); + chmodSync(client, 0o755); + if (server) { + writeFileSync(join(macos, "desktop-tools-mcp"), `#!/bin/sh\necho "args:$*"\ncat\nexit 7\n`); + chmodSync(join(macos, "desktop-tools-mcp"), 0o755); + } + const state = join(directory, "state"); + mkdirSync(state); + symlinkSync(client, join(state, "desktop-client")); + return { bundle, client, state, done: () => rmSync(directory, { recursive: true, force: true }) }; +} + +const run = (args, state) => + spawnSync(process.execPath, [launcher, ...args], { + input: "hello\n", encoding: "utf8", env: { ...process.env, DESKTOP_TOOLS_STATE: state }, + }); + +test("it hands stdin, stdout and the exit status over to the app's own server", () => { + const { state, done } = app(); + try { + const result = run([], state); + assert.equal(result.stdout, "args:\nhello\n"); + assert.equal(result.status, 7); + } finally { + done(); + } +}); + +test("--client runs that app's server, passing --socket and --name on; --wire 2 is accepted", () => { + const { client, done } = app({ name: "Desktop Tools Dev" }); + try { + const result = run(["--client", client, "--socket", "/tmp/x.sock", "--name", "Dev", "--wire", "2"], "/nonexistent"); + assert.equal(result.stdout, "args:--socket /tmp/x.sock --name Dev\nhello\n"); + } finally { + done(); + } +}); + +test("an app without a server of its own fails with its version and what to install", () => { + const { bundle, state, done } = app({ appVersion: "0.14.0", server: false }); + try { + const result = run([], state); + assert.equal(result.status, 1); + assert.equal(result.stdout, ""); + assert.match(result.stderr, new RegExp(`${bundle.replaceAll(".", "\\.")} is version 0\\.14\\.0, which has no MCP server`)); + assert.match(result.stderr, new RegExp(`install Desktop Tools ${version.replaceAll(".", "\\.")} `)); + assert.match(result.stderr, /Desktop Tools\.app\/Contents\/MacOS\/desktop-tools-mcp", which needs no Node/); + } finally { + done(); + } +}); + +test("an embedder's app without a server says it can't serve MCP", () => { + const { client, done } = app({ name: "Ace Canary", server: false }); + try { + const result = run(["--client", client], "/nonexistent"); + assert.equal(result.status, 1); + assert.match(result.stderr, /Ace Canary bundles no desktop-tools-mcp beside .*, so it can't serve the desktop tools over MCP/); + } finally { + done(); + } +}); + +test("no linked client says to install the app", () => { + const result = run([], "/nonexistent"); + assert.equal(result.status, 1); + assert.match(result.stderr, /No Desktop Tools app has linked its client at \/nonexistent\/desktop-client/); +}); + +test("--wire 1 is refused", () => { + const result = run(["--wire", "1"], "/nonexistent"); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /--wire 1 was the Peekaboo stack/); +}); diff --git a/test/version-skew.test.mjs b/test/version-skew.test.mjs deleted file mode 100644 index 05f1f7c..0000000 --- a/test/version-skew.test.mjs +++ /dev/null @@ -1,72 +0,0 @@ -import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; -import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { test } from "node:test"; - -const macOS = { skip: process.platform !== "darwin" && "the client runs only on macOS" }; -const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")); -const server = new URL("../dist/mcp.js", import.meta.url).pathname; - -/** - * An app from before 0.17.0, with no MCP server of its own, whose client fails as a 0.14 one did (#179): it speaks the - * Peekaboo stack's wire, not the one this server forwards on, so every call fails. - */ -function oldApp(appVersion) { - const directory = realpathSync(mkdtempSync(join(tmpdir(), "desktop-tools-skew-"))); - const app = join(directory, "Desktop Tools.app"); - mkdirSync(join(app, "Contents", "MacOS"), { recursive: true }); - writeFileSync(join(app, "Contents", "Info.plist"), ` - - CFBundleShortVersionString${appVersion} - -`); - const client = join(app, "Contents", "MacOS", "desktop-tools-client"); - writeFileSync(client, `#!/usr/bin/env node -process.stdout.write(${JSON.stringify(JSON.stringify({ success: false, error: { code: "HOST_NOT_SERVING", message: "HOST_NOT_SERVING: Desktop Tools isn't serving its socket, so nothing ran." } }))}); -process.exit(1); -`); - chmodSync(client, 0o755); - const state = join(directory, "state"); - mkdirSync(state); - symlinkSync(client, join(state, "desktop-client")); - writeFileSync(join(state, "desktop.sock"), ""); - return { app, state, done: () => rmSync(directory, { recursive: true, force: true }) }; -} - -function callApps(state) { - const input = [ - { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", clientInfo: { name: "test" } } }, - { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "desktop_apps", arguments: {} } }, - ].map((message) => JSON.stringify(message)).join("\n") + "\n"; - const lines = execFileSync(process.execPath, [server], { - input, encoding: "utf8", env: { ...process.env, DESKTOP_TOOLS_STATE: state }, - }).trim().split("\n").map((line) => JSON.parse(line)); - return lines.find((line) => line.id === 2).result; -} - -test("a failed call names the app's version when it differs from the MCP server's", macOS, () => { - const { app, state, done } = oldApp("0.14.0"); - try { - const result = callApps(state); - assert.equal(result.isError, true); - assert.match(result.content[0].text, /^The native desktop client exited with status 1\.$/); - assert.equal(result.content.at(-1).text, `${app} is version 0.14.0, but this MCP server is ${version}. Updating the npx tag ` - + `doesn't update the app, which holds the macOS permissions: ask the user to install Desktop Tools ${version} from ` - + `its GitHub release, or to pin the MCP server to v0.14.0.`); - } finally { - done(); - } -}); - -test("a failed call says nothing about versions when the app matches", macOS, () => { - const { state, done } = oldApp(version); - try { - const result = callApps(state); - assert.equal(result.isError, true); - assert.equal(result.content.length, 1); - } finally { - done(); - } -}); From 8ce7d3e358085332670afd099c29bbcd2a7df1df Mon Sep 17 00:00:00 2001 From: iamnbutler Date: Thu, 12 Nov 2026 20:18:28 -0500 Subject: [PATCH 2/3] Lane note: the client's --serve mode serves pinned launchers too Co-Authored-By: Claude Opus 5.5 --- ...97R1R6VA9K7WETQ00ZKQNQ-serve-must-keep-working-crea.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 .lane/memory/native2/Sources/desktop-tools-client/main.swift/01M797R1R6VA9K7WETQ00ZKQNQ-serve-must-keep-working-crea.md diff --git a/.lane/memory/native2/Sources/desktop-tools-client/main.swift/01M797R1R6VA9K7WETQ00ZKQNQ-serve-must-keep-working-crea.md b/.lane/memory/native2/Sources/desktop-tools-client/main.swift/01M797R1R6VA9K7WETQ00ZKQNQ-serve-must-keep-working-crea.md new file mode 100644 index 0000000..c9dfc3f --- /dev/null +++ b/.lane/memory/native2/Sources/desktop-tools-client/main.swift/01M797R1R6VA9K7WETQ00ZKQNQ-serve-must-keep-working-crea.md @@ -0,0 +1,8 @@ +--- +id: 01M797R1R6VA9K7WETQ00ZKQNQ +anchor: '@file' +created: 2026-11-13T01:18:26Z +norm: '1' +--- + +--serve must keep working: createDesktop uses it, and npx setups pinned to v0.17.0 through v0.20.0 with --client, --socket or --name run their Node server through it (#237) From 8f96d606d2579ea4c68124f7cc0c779939beb39f Mon Sep 17 00:00:00 2001 From: iamnbutler Date: Sat, 14 Nov 2026 15:03:57 -0500 Subject: [PATCH 3/3] MCP launcher: tell an embedder to bundle desktop-tools-mcp (#237) An embedding app's --client without a server of its own now says to bundle desktop-tools-mcp from the same native build beside its client, linking docs/embed.md, instead of pointing at Desktop Tools.app. docs/mcp.md gets a section on serving another app's grants. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- dist/mcp.js | 20 ++++++++++++-------- docs/mcp.md | 14 ++++++++++++-- src/mcp.ts | 22 ++++++++++++---------- test/mcp-launcher.test.mjs | 5 ++++- 5 files changed, 41 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index afe2860..c502c08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ Notable changes to Desktop Tools, newest first. Each release's GitHub release no ### Changed -- `desktop-tools-mcp` from npm (`dist/mcp.js`) is now only a launcher: it runs the app's own Swift server and hands stdin and stdout over to it, so no MCP traffic passes through Node. The Node MCP server is gone. With options, which used to keep the Node server, it now runs the server of the app that `--client` names, passing `--socket` and `--name` on. An app without a server of its own (Desktop Tools before 0.17.0, or an embedder's app that ships none beside its client) makes it exit with a message naming the app, its version and what to install, where a Node server used to fail every call. Prefer pointing the MCP config at `/Applications/Desktop Tools.app/Contents/MacOS/desktop-tools-mcp`, which needs no Node. Parity, bench and live-check scripts default to the app's own server. ([#237](https://github.com/githubnext/desktop-tools/issues/237)) +- `desktop-tools-mcp` from npm (`dist/mcp.js`) is now only a launcher: it runs the app's own Swift server and hands stdin and stdout over to it, so no MCP traffic passes through Node. The Node MCP server is gone. With options, which used to keep the Node server, it now runs the server of the app that `--client` names, passing `--socket` and `--name` on. An app without a server of its own makes it exit with a message instead: Desktop Tools before 0.17.0 is named with its version and the release to install, and an embedding app that ships no `desktop-tools-mcp` beside its client, such as Ace Canary passed with `--client` today, is told to bundle one (docs/embed.md). Such setups used to run the Node server through that app's client. Prefer pointing the MCP config at `/Applications/Desktop Tools.app/Contents/MacOS/desktop-tools-mcp`, which needs no Node. Parity, bench and live-check scripts default to the app's own server. ([#237](https://github.com/githubnext/desktop-tools/issues/237)) - Tool descriptions, schemas and the rules they share are declared in Swift, in `native2/Sources/DesktopProtocol/ContractTools.swift`, which the app's MCP server serves. `@githubnext/desktop-tools/tools` and the key and wait-condition lists in `/protocol` are generated from those declarations (`npm run contract`) and export the same values as before. `desktopRequest` no longer checks the exclusive argument forms of `desktop_clipboard_write` and `desktop_dialog_answer` itself: the host refuses them with the same text. `DESKTOP_EXPECT_OPS` lists its ops in tool order. ([#237](https://github.com/githubnext/desktop-tools/issues/237)) ### Fixed diff --git a/dist/mcp.js b/dist/mcp.js index 082be97..8dc35d2 100644 --- a/dist/mcp.js +++ b/dist/mcp.js @@ -43,16 +43,20 @@ if (!server || !existsSync(server)) { })(); const appVersion = plist && /CFBundleShortVersionString<\/key>\s*([^<]+)<\/string>/.exec(plist)?.[1]; const appName = plist && /CFBundleName<\/key>\s*([^<]+)<\/string>/.exec(plist)?.[1]; - const found = !linked - ? `No Desktop Tools app has linked its client at ${client}: install and open Desktop Tools ${version} (${releases}).` + const appPath = "/Applications/Desktop Tools.app/Contents/MacOS/desktop-tools-mcp"; + const message = !linked + ? `No Desktop Tools app has linked its client at ${client}: install and open Desktop Tools ${version} (${releases}). ` + + `Then set the MCP server up as "${appPath}", which needs no Node.` : appName && !appName.startsWith("Desktop Tools") - // An embedder's app serves MCP only if it bundles desktop-tools-mcp beside its client (docs/embed.md). - ? `${appName} bundles no desktop-tools-mcp beside ${linked}, so it can't serve the desktop tools over MCP. ` - + "An embedding app can ship desktop-tools-mcp from a native build beside its client (docs/embed.md)." + // A signed host serves only its own app's programs, so an embedder's app serves MCP only through its own server. + ? `${appName} bundles no desktop-tools-mcp beside its client, ${linked}, so it can't serve the desktop tools over MCP. ` + + `To serve them, ${appName} must bundle desktop-tools-mcp from the same native build beside that client, signed with ` + + `the client's identifier: see https://github.com/githubnext/desktop-tools/blob/main/docs/embed.md. ` + + "Then set the MCP server up as that desktop-tools-mcp, with --socket for the socket the app serves." : `${dirname(contents)} is version ${appVersion ?? "unknown"}, which has no MCP server of its own (0.17.0 and later ` - + `bundle one): install Desktop Tools ${version} (${releases}).`; - process.stderr.write(`desktop-tools-mcp: ${found} Then set the MCP server up as "/Applications/Desktop Tools.app/Contents/MacOS/desktop-tools-mcp", ` - + "which needs no Node.\n"); + + `bundle one): install Desktop Tools ${version} (${releases}). Then set the MCP server up as "${appPath}", ` + + "which needs no Node."; + process.stderr.write(`desktop-tools-mcp: ${message}\n`); process.exit(1); } const args = [...(values.socket ? ["--socket", values.socket] : []), ...(values.name ? ["--name", values.name] : [])]; diff --git a/docs/mcp.md b/docs/mcp.md index 047b125..c6489af 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -15,13 +15,23 @@ command = "/Applications/Desktop Tools.app/Contents/MacOS/desktop-tools-mcp" The [README](https://github.com/githubnext/desktop-tools#set-up-for-an-agent) has the setup for clients configured with JSON. -The server serves the socket in its app's state folder (`DESKTOP_TOOLS_STATE`, else the folder its bundle ID chooses), or `--socket `, and names its app in the instructions and rules: the app it ships in, or `--name `. So the [development app](build.md#development-app)'s server, `Desktop Tools Dev.app/Contents/MacOS/desktop-tools-mcp`, serves `~/.local/state/desktop-tools-dev` as **Desktop Tools Dev** with no options. A signed host serves only its own app's programs, so another app's grants are used through that app's own `desktop-tools-mcp`, which an [embedding app](embed.md) can ship beside its client. +The server serves the socket in its app's state folder (`DESKTOP_TOOLS_STATE`, else the folder its bundle ID chooses), or `--socket `, and names its app in the instructions and rules: the app it ships in, or `--name `. So the [development app](build.md#development-app)'s server, `Desktop Tools Dev.app/Contents/MacOS/desktop-tools-mcp`, serves `~/.local/state/desktop-tools-dev` as **Desktop Tools Dev** with no options. + +## Another app's grants + +A signed host serves only its own app's programs, so an app that embeds Desktop Tools, such as Ace, serves MCP only through its own `desktop-tools-mcp`. To offer that, **bundle `desktop-tools-mcp` from the same native build beside the app's `desktop-tools-client`, signed with the client's identifier**, as [Embed](embed.md) describes. Then set the MCP server up as that file, with `--socket` for the socket the app serves: + +```sh +claude mcp add desktop -- "/Applications/Example.app/Contents/MacOS/desktop-tools-mcp" --socket ~/.local/state/example/desktop.sock +``` + +It names its app (its `CFBundleName`) in the instructions and rules; `--name` overrides that. Without a bundled server, an `npx` setup that passes `--client` for that app exits with a message saying to bundle one. ## npx setups `npx -y --package=github:githubnext/desktop-tools#v0.20.0 desktop-tools-mcp` (Node 22 or later) also works. It runs only a launcher, `dist/mcp.js`, which finds the app's server beside the client the app links in its state folder and hands stdin and stdout over to it; no MCP traffic passes through Node. `--client .app/Contents/MacOS/desktop-tools-client` runs that app's server instead, and `--socket` and `--name` are passed on to it. `--wire 2` is accepted and ignored, and `--wire 1`, the removed Peekaboo stack, is refused. -When there is no server to hand over to, the launcher exits with a message instead: no app has linked its client, the app is from before 0.17.0 and has no server of its own (the message names its version and the release to install), or `--client` names an embedder's app that ships no `desktop-tools-mcp`. Updating the `npx` tag doesn't update the app, which holds the macOS permissions. A setup pinned before v0.17.0 is refused with `CLIENT_OUTDATED`, so update its tag, or better, point it at the app's server. +When there is no server to hand over to, the launcher exits with a message instead: no app has linked its client, the app is from before 0.17.0 and has no server of its own (the message names its version and the release to install), or `--client` names an embedder's app that ships no `desktop-tools-mcp` (bundle one, as [above](#another-apps-grants)). Updating the `npx` tag doesn't update the app, which holds the macOS permissions. A setup pinned before v0.17.0 is refused with `CLIENT_OUTDATED`, so update its tag, or better, point it at the app's server. The tool names, descriptions, and argument schemas are declared in Swift (`native2/Sources/DesktopProtocol/ContractTools.swift`), and `@githubnext/desktop-tools/tools` (`desktopTools`, `desktopRequest`) exports them, generated from that file, for Ace's `desktop_*` tools and other embedders. [Tools](tools.md) lists them. The descriptions don't repeat the rules every tool shares: exact targets, single-use snapshots, background and foreground input, what each outcome means, pausing, `desktop_wait` and `expect`, and the recipes. `desktopToolRules(app)` returns those rules, and the server adds them to its instructions; a host with its own agent guidance should include them too. diff --git a/src/mcp.ts b/src/mcp.ts index fa5fed6..e7f2fd6 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -44,18 +44,20 @@ if (!server || !existsSync(server)) { })(); const appVersion = plist && /CFBundleShortVersionString<\/key>\s*([^<]+)<\/string>/.exec(plist)?.[1]; const appName = plist && /CFBundleName<\/key>\s*([^<]+)<\/string>/.exec(plist)?.[1]; - const found = !linked - ? `No Desktop Tools app has linked its client at ${client}: install and open Desktop Tools ${version} (${releases}).` + const appPath = "/Applications/Desktop Tools.app/Contents/MacOS/desktop-tools-mcp"; + const message = !linked + ? `No Desktop Tools app has linked its client at ${client}: install and open Desktop Tools ${version} (${releases}). ` + + `Then set the MCP server up as "${appPath}", which needs no Node.` : appName && !appName.startsWith("Desktop Tools") - // An embedder's app serves MCP only if it bundles desktop-tools-mcp beside its client (docs/embed.md). - ? `${appName} bundles no desktop-tools-mcp beside ${linked}, so it can't serve the desktop tools over MCP. ` - + "An embedding app can ship desktop-tools-mcp from a native build beside its client (docs/embed.md)." + // A signed host serves only its own app's programs, so an embedder's app serves MCP only through its own server. + ? `${appName} bundles no desktop-tools-mcp beside its client, ${linked}, so it can't serve the desktop tools over MCP. ` + + `To serve them, ${appName} must bundle desktop-tools-mcp from the same native build beside that client, signed with ` + + `the client's identifier: see https://github.com/githubnext/desktop-tools/blob/main/docs/embed.md. ` + + "Then set the MCP server up as that desktop-tools-mcp, with --socket for the socket the app serves." : `${dirname(contents!)} is version ${appVersion ?? "unknown"}, which has no MCP server of its own (0.17.0 and later ` - + `bundle one): install Desktop Tools ${version} (${releases}).`; - process.stderr.write( - `desktop-tools-mcp: ${found} Then set the MCP server up as "/Applications/Desktop Tools.app/Contents/MacOS/desktop-tools-mcp", ` - + "which needs no Node.\n", - ); + + `bundle one): install Desktop Tools ${version} (${releases}). Then set the MCP server up as "${appPath}", ` + + "which needs no Node."; + process.stderr.write(`desktop-tools-mcp: ${message}\n`); process.exit(1); } diff --git a/test/mcp-launcher.test.mjs b/test/mcp-launcher.test.mjs index 2c0867b..f12d98b 100644 --- a/test/mcp-launcher.test.mjs +++ b/test/mcp-launcher.test.mjs @@ -78,7 +78,10 @@ test("an embedder's app without a server says it can't serve MCP", () => { try { const result = run(["--client", client], "/nonexistent"); assert.equal(result.status, 1); - assert.match(result.stderr, /Ace Canary bundles no desktop-tools-mcp beside .*, so it can't serve the desktop tools over MCP/); + assert.match(result.stderr, /Ace Canary bundles no desktop-tools-mcp beside its client, .*, so it can't serve the desktop tools over MCP/); + assert.match(result.stderr, /Ace Canary must bundle desktop-tools-mcp from the same native build beside that client/); + assert.match(result.stderr, /https:\/\/github\.com\/githubnext\/desktop-tools\/blob\/main\/docs\/embed\.md/); + assert.doesNotMatch(result.stderr, /Desktop Tools\.app/); } finally { done(); }