A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
feat(connectors): front every connector with an MCP proxy in the daemon
Alan Buscaglia6016b43d0745
diff --git a/docs/design.md b/docs/design.mdindex e72f63e..3635648 100644--- a/docs/design.md+++ b/docs/design.md@@ -64,7 +64,7 @@ docs/ design, deployment guide, security checklist- Spawns the bundled engine (`node <gentle-pi>/bin/gentle-shell.mjs --home <dataDir>/agent --mode rpc --session-dir <dataDir>/sessions --append-system-prompt <identity file>`) with `cwd` = the assistant's own workspace, `<dataDir>/workspace`, so the engine never reads a `.pi` project config from the user's home. A custom `workspace` (config or `GENTLE_DOT_WORKSPACE`) is never used as `cwd` and nothing is written there; it is passed as one more `--append-system-prompt` text: "The user's preferred working folder is <path>. Use absolute paths there unless told otherwise."- Isolation (S12): the child runs with its own `HOME=<dataDir>/home` (0700) and `XDG_CONFIG_HOME`, `XDG_DATA_HOME`, `XDG_CACHE_HOME`, and `XDG_STATE_HOME` under it, plus `GENTLE_PI_CONFIG_HOME=<dataDir>/gentle-ai`. `PATH` is kept, and `GIT_CONFIG_GLOBAL` points at the user's real `~/.gitconfig` when it exists, to keep their git identity. Inherited `PI_CODING_AGENT_DIR`, `GENTLE_PI_AGENT_HOME`, and `GENTLE_SHELL_CONFIG` are removed. `GENTLE_PI_AGENTS=0` turns Gentle Shell's subagents off (no `subagent_*` or `orchestrator_*` tools) until S25. The engine's first run otherwise writes into the real `~` (`~/.gentle-shell`, `~/.pi/agent/pi-pretty`, `~/.gentle-ai`), which `--home` alone does not prevent.- Memory (S23): the engine uses the user's global Engram, always in the project `gentle-dot`. The memory plugin accepts a server only when `engram instance-id` (read from the Engram data folder, by default `$HOME/.engram`) matches the server's `/health` `instance_id`, so the child gets `ENGRAM_DATA_DIR=<real ~/.engram>` (the inherited `ENGRAM_DATA_DIR` when set; override `GENTLE_DOT_ENGRAM_DATA_DIR`) and keeps the user's own `ENGRAM_PORT` and `ENGRAM_URL` (default server 7437). If the global Engram is not running, the plugin starts it with that data folder, as Gentle Shell does. The project comes from Engram's per-folder setting: the daemon writes `<dataDir>/workspace/.engram/config.json` (`{"project_name":"gentle-dot"}`) at every start, and Engram reads it before any other detection (source `config`). The plugin has no per-client project override (`ENGRAM_PROJECT` only applies to the Engram process itself, which is the user's shared server). Memories the assistant saved earlier in its private memory (`<dataDir>/home/.engram`) are not moved. `GENTLE_DOT_ENGRAM=private` restores a private memory: no `ENGRAM_DATA_DIR`, `ENGRAM_URL` removed, `ENGRAM_PORT=7438` (override `GENTLE_DOT_ENGRAM_PORT`), data under `<dataDir>/home/.engram`. The memory server the engine starts there outlives the engine, so when nothing listened on the private port as the daemon started, the daemon stops it when it closes: the PID listening on that port (`lsof`), only when its `/health` `instance_id` matches `<dataDir>/home/.engram/.instance-id`.-- Connectors (S18): before every spawn (first start, restart, respawn) the supervisor's `prepareSpawn` hook puts back the connector files from the daemon's in-memory state (§4, Connectors), then hands the approval guard its policy, also from memory, in the child's environment (`GENTLE_DOT_CONNECTOR_POLICY`, JSON: the turned-on connectors, their modes and curated read-only tools, and the protected files). The engine cannot change its own environment, so the policy cannot be edited by the assistant. The assistant's own engine loads the guard with `-e packages/daemon/src/extensions/approval-guard.ts` (TypeScript loads as is).+- Connectors (S18): before every spawn (first start, restart, respawn) the supervisor's `prepareSpawn` hook puts back the connector files from the daemon's in-memory state (§4, Connectors), then points `mcp.json` at the daemon's MCP proxy with a fresh key for this launch (S25.4; the previous key stops working), then hands the approval guard its policy, also from memory, in the child's environment (`GENTLE_DOT_CONNECTOR_POLICY`, JSON: the turned-on connectors, their modes and curated read-only tools, which of them the proxy fronts (`proxied`), and the protected files). The engine cannot change its own environment, so the policy cannot be edited by the assistant. The assistant's own engine loads the guard with `-e packages/daemon/src/extensions/approval-guard.ts` (TypeScript loads as is).- Parses stdout with strict LF framing on a byte stream. Never Node `readline` (it splits on U+2028/U+2029, which are valid inside JSON).- Correlates commands by `id`; stdout records without `id` are session events.- Reads stderr only as diagnostics (logged, never parsed).@@ -93,7 +93,7 @@ Client to daemon:| `auth_login` | `providerId`, `method` (`oauth` \| `api_key`) | daemon `ModelRuntime.login()`; one flow at a time || `auth_reply` | `flowId`, `value` \| `cancelled` | answers the flow's current prompt || `auth_logout` | `providerId` | daemon `ModelRuntime.logout()` |-| `connectors_list` | — | daemon `connectors.json` and `mcp-auth.json` key presence |+| `connectors_list` | — | daemon `connectors.json` and `<data>/connector-signin/mcp-auth.json` key presence || `connector_connect` | `connectorId` | adds or turns on the connector (new `mcp.json`, agent restart when idle), then `mcp login` when not signed in || `connector_signin` | `connectorId` | `mcp login <id>`; one flow at a time || `connector_disconnect` | `connectorId` | turns it off (the sign-in stays); agent restart when idle |@@ -137,16 +137,18 @@ Every daemon message carries `seq` (monotonic per connection) so the UI can dete- Discord: the community server `npx -y @pasympa/[email protected]` (MIT, monthly releases, declares `readOnlyHint` on its tools; Discord has no official server), with the bot token in `env.DISCORD_TOKEN`. The guide covers the application, the bot, the Message Content and Server Members intents, and the invite (scope `bot` with read, send, and react permissions).- Slack: the official `https://mcp.slack.com/mcp` (no dynamic client registration) with the user's own Slack app: `oauth.clientId`, an optional `oauth.clientSecret`, and the fixed redirect `http://localhost:38417/callback` (`oauth.callbackUrl`, sent exactly as written). Slack accepts a loopback redirect only with PKCE turned on, which makes the app a public client (refresh tokens last 30 days), so the secret may be left empty; the guide lists the user token scopes.- Gmail: the official `https://gmailmcp.googleapis.com/mcp/v1` (Developer Preview) with the user's own Google Cloud project: the Gmail API and Gmail MCP API enabled, the consent screen in testing (refresh tokens last 7 days), and a Web application client with the redirect `http://localhost:38418/callback`; `oauth.scope` asks for `gmail.readonly` and `gmail.compose`. `gmail.compose` can also send mail, so the copy says so: drafting and sending ask for approval each time, and read only hides them. Each guided connector's copy describes only what its guide's permissions allow (Slack: send and schedule messages with `chat:write`; Discord: send messages and reactions).-- Typed values (S18, S19): a connector's `fields` are asked one at a time with sign-in prompts (`auth_prompt` `secret` or `text`, flow id `connector-setup-*`, `optional` when the answer may be empty), in the window that started them. A catalog connector is added only when every required value is there (cancel changes nothing); an approved draft or an import is added first and stays `needs_setup` until its values are typed. The values live in the in-memory state and `connectors.json` (both protected), are written into `mcp.json` in place of `${input:<key>}` placeholders, and are never sent to a window or logged. The engine resolves env values, headers, and `oauth.clientSecret` (a leading `!` runs a shell command and `$NAME` expands), so typed and imported literals are escaped (`$` → `$$`, `!` → `$!`); `clientId`, the command, its arguments, and URLs are used as written. `connector_setup` asks again (a new token). A connector whose value is missing is `needs_setup` and is left out of `mcp.json`.+- Typed values (S18, S19): a connector's `fields` are asked one at a time with sign-in prompts (`auth_prompt` `secret` or `text`, flow id `connector-setup-*`, `optional` when the answer may be empty), in the window that started them. A catalog connector is added only when every required value is there (cancel changes nothing); an approved draft or an import is added first and stays `needs_setup` until its values are typed. The values live in the in-memory state and `connectors.json` (both protected), are written into the sign-in home's `mcp.json` in place of `${input:<key>}` placeholders (never into the engine's), and are never sent to a window or logged. Env values, headers, and `oauth.clientSecret` follow the engine's syntax (a leading `!` runs a shell command and `$NAME` expands), so typed and imported literals are escaped (`$` → `$$`, `!` → `$!`); the proxy resolves them the same way before it sends them upstream, so a typed value arrives exactly as typed. `clientId`, the command, its arguments, and URLs are used as written. `connector_setup` asks again (a new token). A connector whose value is missing is `needs_setup` and is left out of `mcp.json`.- Drafts (S19): the approval guard registers `propose_connector({name, description, transport, command?, args?, url?, env_names?, needs_oauth?})`, with secrets by name only. Its result to the model is only "The user will review this connector in the app". The draft travels to the daemon as `ctx.ui.setStatus("gentle-dot:connector-draft", <json>)`: a fire-and-forget record on the engine's own RPC output, which only the daemon reads (the agent's commands cannot write to it, and no file, socket, or key is added that the agent could reach). A typed value (`${input:NAME}`) may only stand for an env value (or an http server's header): anywhere else (the command, its arguments, the URL) it would put the secret into the command line or an address the model chose, so the guard answers the model "Secrets can only go into environment variables." and sends nothing, and the daemon refuses such a draft as well. The daemon checks it (lengths, `https` or loopback URLs, env names, typed values), keeps the newest five (`MAX_CONNECTOR_DRAFTS`; the windows keep the same five and take the waiting list again after each `ready`), and shows every window a card (`connector_draft`) with the command or URL and the secret names. `connector_draft_reply` decides: declining forgets it; approving adds the server (`origin` "Drafted by the assistant"), turned on, read only with every tool hidden (`toolExposure {"*": "hidden"}`, no curated list, so in "Read and send" every call asks), then asks for each secret in the app and signs in when `needs_oauth`. The assistant still cannot write `mcp.json` or run `mcp add` (guard), so the card is the only way in. Residual, as for the rest of the state (S25): `connectors.json` edited while the daemon is not running is loaded at its next start, and it can now hold a server of the user's own (a command).- Import (S20, `packages/daemon/src/connector-import.ts`): "Import my MCP servers" (`connectors_scan`) reads, never writes, the configs below the user's home (`GENTLE_DOT_IMPORT_HOME` in tests): Claude Desktop (`Library/Application Support/Claude/` and `.config/Claude/claude_desktop_config.json`), Claude Code (`.claude.json` `mcpServers`, its `projects[*].mcpServers`, and each project's `.mcp.json`), Cursor (`.cursor/mcp.json`), VS Code (`User/mcp.json` with `servers` and `inputs`, macOS and Linux), Windsurf (`.codeium/windsurf/mcp_config.json`, `serverUrl`), OpenCode (`.config/opencode/opencode.json`, `mcp` with command arrays and `environment`), and Gentle Shell (`.gentle-shell/agent/mcp.json`). Each entry maps to the engine's schema: `${VAR}` (Claude Code), `${env:VAR}` (VS Code, Cursor, Windsurf), and `{env:VAR}` (OpenCode) become `${VAR}`; `${userHome}` becomes the home folder; a VS Code `${input:id}` becomes a value the user types after the import; everything else is a literal. SSE servers (`type: "sse"`, or an address ending in `/sse`) are listed as not importable. The list (`connector_imports`) shows the name, the source apps, the command or address (`summary`), and env and header names only; values stay in the daemon. The summary, also shown for a custom connector in the Connectors list, is masked by structure, not by a word list: an address (an argument or the server URL, any scheme) keeps its scheme, host, and path, loses its user and password and its fragment, shows its query keys with every value as `•••`, and masks long opaque path segments (20 or more letters, digits, `_`, or `-`, mixing digits or cases); the argument after `--header`/`-H`, the value of `--header=`, and any `Name: value` argument whose name looks like a credential (Authorization, Cookie, `*key*`, `*token*`, `*secret*`, and so on) keep only the name; the argument after a flag named like a credential (`/token|secret|key|pass|auth|cred|bearer/i`) and the value of `name=value` forms of the same are masked; known token prefixes (`ghp_`, `sk-`, `xoxb-`, `AKIA`, `glpat-`, and others) and long opaque words are masked. Values the engine resolves at start are noted before the import (`notes`): "Runs a command on your computer to get this value." for a leading `!` (the command is not shown), and "Reads the environment variable NAME." for `$NAME`/`${NAME}`. Duplicates (the same command without npm versions, or the same URL) of a connector the user has, or of a catalog entry, are marked and cannot be imported. `connector_import` copies the chosen entries with their values into the private state, read only with every tool hidden, and never touches the source files.-- The daemon holds the approved connector state (each connector's `enabled` and `mode`) in memory. It reads `<dataDir>/connectors.json` once, when it starts; after that the state changes only through the Connectors screen. The daemon is the only writer of `connectors.json` and `<agentHome>/mcp.json`, both rendered from memory, atomically, mode 0600. The engine's policy (below) also comes from memory, never from the files. The files are watched (folder watches plus a check every second, because file events on macOS can be missed right after a watch starts), and they are also checked before every agent start and after every run. A change made by anything else is put back, a project `<workspace>/.pi/mcp.json` is removed (a `.pi` link loses the link, never its target), and every window gets "A change to your connectors was blocked." Residual: a change made to the files while the daemon is not running is loaded at its next start; stage 2 (S25) moves enforcement out of the files. Every server is `exposure: "direct"` (the assistant turns codemode off). "Read only" adds `toolExposure: {"*": "hidden", <curated tool>: "direct"}`; the engine prefers exact names over patterns, so an unknown tool stays hidden.-- Sign-in runs the engine's own command line as a separate process, `node <pi-coding-agent>/dist/bundle/cli.js mcp login <id>`, with the agent's isolated environment and `PI_CODING_AGENT_DIR=<agentHome>`. The daemon relays the printed authorization URL (`auth_event` `auth_url`) and offers a `manual_code` prompt: when the browser cannot reach this computer's loopback callback, the user pastes the address it ended on, and the daemon opens it locally only when its origin and path equal the authorization URL's `redirect_uri` and its `state` matches. Cancel stops the process by PID. Flow ids start with `connector-`, so `auth_reply` reaches the right flow; typed and printed text is never logged (URLs are masked).-- Status: `needs_setup` while a typed value is missing; for servers that sign in with OAuth, `connected` when `mcp-auth.json` holds tokens under `mcp__<id>|<url>` (the id with `-` as `_`, like the engine; token values are dropped while parsing) and `needs_signin` otherwise; `connected` for servers with a token or none; `error` after a failed sign-in.-- Approval guard (`packages/daemon/src/extensions/approval-guard.ts`, `tool_call` hook, nested calls included): a connector tool runs without asking only when it declares `readOnlyHint: true` AND it is on the curated list. Anything else asks through `ctx.ui.confirm`: an ask card ("Allow Notion to create pages?") with every argument, key fields first, up to 8,000 characters (beyond that it says "(truncated, N more characters)"), shown in a scrollable block. It is blocked when declined, when no one can answer, or when the connector is "Read only". A server outside the policy is blocked; without a valid policy every connector call asks.-- Credential and control files: `<agentHome>/auth.json`, `mcp-auth.json`, `models.json` (it can hold API keys), `mcp.json`, `<dataDir>/connectors.json`, `<dataDir>/token`, and the guard itself. The file tools (`read`, `write`, `edit`, `grep`, `find`, `ls`) are blocked on them by resolved path (any spelling, `@` prefix, case, symlink, or hard link), and `grep` also on any folder that contains one. Commands (`bash`) are blocked when, with quotes, backslashes, and string concatenation removed, they name one of those files (any case; a pattern such as `mcp-a*` counts), the data folder `.gentle-dot`, `PI_CODING_AGENT_DIR`, `security find-generic-password` (or other keychain reads), or `mcp add|login|logout|remove`. The command check is best effort, not a security boundary: the assistant runs as the user with a shell, so a command can always build a name the check does not see. The in-memory connector state above does not depend on it, and stage 2 (S25) moves tokens out of the engine's reach.+- The daemon holds the approved connector state (each connector's `enabled` and `mode`) in memory. It reads `<dataDir>/connectors.json` once, when it starts; after that the state changes only through the Connectors screen. The daemon is the only writer of `connectors.json`, `<agentHome>/mcp.json`, and the sign-in home's `mcp.json`, all rendered from memory, atomically, mode 0600. The sign-in home's `mcp-auth.json` changes only while a sign-in command runs or when the proxy saves a refreshed token; any other change is put back to what those left (or the file is removed when there was none). The engine's policy (below) also comes from memory, never from the files. The files are watched (folder watches plus a check every second, because file events on macOS can be missed right after a watch starts), and they are also checked before every agent start and after every run. A change made by anything else is put back, a project `<workspace>/.pi/mcp.json` is removed (a `.pi` link loses the link, never its target), and every window gets "A change to your connectors was blocked." Residual: a change made to the files while the daemon is not running is loaded at its next start; stage 2 (S25) moves enforcement out of the files. Every server is `exposure: "direct"` (the assistant turns codemode off). Read only is enforced by the proxy (above); the sign-in home's `mcp.json` still carries `toolExposure: {"*": "hidden", <curated tool>: "direct"}` for read only, as the engine would read it.+- MCP proxy (S25.4, `packages/daemon/src/mcp-proxy.ts`): the engine's `<agentHome>/mcp.json` lists every connector as `{url: "http://127.0.0.1:<port>/mcp/<id>", headers: {Authorization: "Bearer <proxy key>"}, exposure: "direct", timeout: 300}` (plus `enabled: false` when turned off) and nothing else: no real address, token, environment, or command. The key is random, kept only in memory, and new for every engine launch; the proxy accepts it only in the `Authorization` header (401 otherwise, never from the address) and refuses any request with an `Origin`. It answers JSON-RPC 2.0 as plain `application/json` over POST, like the computer helper (GET is 405, notifications 202): `initialize`, `ping`, `tools/list`, `tools/call`, `resources/list`, `resources/read`, `resources/templates/list`, `prompts/list`, and `prompts/get`. Upstream, the daemon keeps one pi-mcp `McpClient` per connector, connected on first use: streamable HTTP for a remote server, with its headers and the stored sign-in (sent as a bearer token and refreshed after a 401 with the stored refresh token, never a new browser sign-in), or stdio for a server the daemon runs itself, with the engine's environment plus the server's values. A dropped connection is made again on the next request; turning a connector off, removing it, or changing its server or values closes it, and so does the daemon's shutdown. Every request reads the connector's state from the daemon's memory, so a mode change applies at once, without an engine restart (the engine still restarts to list newly allowed tools). Policy: `tools/list` shows in read only only the tools that declare `readOnlyHint: true` AND are on the curated list (the same `isReadOnlyTool` rule the guard uses), and every tool in "Read and send"; `tools/call` refuses a hidden or unknown tool with a JSON-RPC error however it is called, taking the annotations from the server's own list, never the caller; a sending action (any tool that is not read-only) is forwarded only after the user approves its preview (connector, tool, and every argument) on the ask card (`DotBridge.confirm`, same card as the engine's approvals; T23c moves it to the app's native dialog). Declining, an ask that cannot be shown (no window), an answer that is stopped, or a connector changed while the card was open refuses it with a JSON-RPC error that says nothing was sent. Resources and prompts are reads: they are shown in "Read and send", and in read only only for a connector with a curated read-only list (the catalog's); a server of the user's own in read only exposes no resources or prompts, like its tools. Errors from the server are passed on with their code and message; a refused sign-in says to sign in again in Connectors; anything else says the connector could not be reached (the log masks addresses).+- Sign-in home: the engine's `mcp login`/`mcp logout` read the server from `mcp.json`, so they run with `PI_CODING_AGENT_DIR=<data>/connector-signin` (0700), the daemon's own folder: its `mcp.json` (0600) holds the real servers in the engine's format, rendered from memory, and its `mcp-auth.json` (0600) the sign-ins in pi-mcp's OAuth state format, keyed `mcp__<id>|<url>`. The first start with the proxy moves `<agentHome>/mcp-auth.json` there once (the copy is read back before the old file is removed; a file that shows up there later is not taken over). T23d moves these secrets to the Keychain.+- Sign-in runs the engine's own command line as a separate process, `node <pi-coding-agent>/dist/bundle/cli.js mcp login <id>`, with the agent's isolated environment and `PI_CODING_AGENT_DIR=<data>/connector-signin`. The daemon relays the printed authorization URL (`auth_event` `auth_url`) and offers a `manual_code` prompt: when the browser cannot reach this computer's loopback callback, the user pastes the address it ended on, and the daemon opens it locally only when its origin and path equal the authorization URL's `redirect_uri` and its `state` matches. Cancel stops the process by PID. Flow ids start with `connector-`, so `auth_reply` reaches the right flow; typed and printed text is never logged (URLs are masked).+- Status: `needs_setup` while a typed value is missing; for servers that sign in with OAuth, `connected` when the sign-in home's `mcp-auth.json` holds tokens under `mcp__<id>|<url>` (the id with `-` as `_`, like the engine; token values are dropped while parsing) and `needs_signin` otherwise; `connected` for servers with a token or none; `error` after a failed sign-in.+- Approval guard (`packages/daemon/src/extensions/approval-guard.ts`, `tool_call` hook, nested calls included): the tools of a connector the proxy fronts (`proxied` in the policy: turned on and set up) pass, since the proxy filters them and asks itself; a card here would ask twice. A turned-off connector is not in `proxied` or the approved list, so its tools stay blocked here as well. For any other connector tool: it runs without asking only when it declares `readOnlyHint: true` AND it is on the curated list. Anything else asks through `ctx.ui.confirm`: an ask card ("Allow Notion to create pages?") with every argument, key fields first, up to 8,000 characters (beyond that it says "(truncated, N more characters)"), shown in a scrollable block. It is blocked when declined, when no one can answer, or when the connector is "Read only". A server outside the policy is blocked; without a valid policy every connector call asks.+- Credential and control files: `<agentHome>/auth.json`, `mcp-auth.json` (where it was before the proxy), `models.json` (it can hold API keys), `mcp.json`, the sign-in home `<dataDir>/connector-signin` with its `mcp.json` and `mcp-auth.json`, `<dataDir>/connectors.json`, `<dataDir>/token`, and the guard itself. The file tools (`read`, `write`, `edit`, `grep`, `find`, `ls`) are blocked on them by resolved path (any spelling, `@` prefix, case, symlink, or hard link), and `grep` also on any folder that contains one. Commands (`bash`) are blocked when, with quotes, backslashes, and string concatenation removed, they name one of those files (any case; a pattern such as `mcp-a*` counts), the data folder `.gentle-dot`, `PI_CODING_AGENT_DIR`, `security find-generic-password` (or other keychain reads), or `mcp add|login|logout|remove`. The command check is best effort, not a security boundary: the assistant runs as the user with a shell, so a command can always build a name the check does not see. The in-memory connector state above does not depend on it, and stage 2 (S25) moves tokens out of the engine's reach.- Stage 2 integrity (S25) must cover the user's own servers too. Today `connectors.json` is trusted when the daemon starts, so a file edited while the daemon is not running can add a custom or imported server that runs an arbitrary command, turn it on, claim any `origin` ("Imported from …", "Drafted by the assistant"), and carry env or header values that are not escaped (`!command`, `$NAME`), which the engine runs or expands at the next start. S25's integrity check (state the agent cannot write, or a signature it cannot forge) must cover every field of those entries: command, arguments, URL, env, headers, `enabled`, `mode`, and `origin`.-- Subagents are off in the assistant's engine (`GENTLE_PI_AGENTS=0`, §3): Gentle Shell's subagent child engines get only its own child extensions, not the approval guard, so a child could run connector tools or read credentials unchecked. Turning them back on needs S25 (enforcement in the daemon) or forwarding the guard to child engines.+- Subagents are off in the assistant's engine (`GENTLE_PI_AGENTS=0`, §3): Gentle Shell's subagent child engines get only its own child extensions, not the approval guard, so a child could run connector tools or read credentials unchecked. Turning them back on needs S25 (enforcement in the daemon) or forwarding the guard to child engines. With the proxy (S25.4) a child's connector calls are filtered and approved by the daemon too; subagents stay off until T23f checks the rest (credential reads, a real-engine probe).### Switching and history races (S21)@@ -281,7 +283,7 @@ The user changes the main assistant's model from the chat, in the panel and the- The daemon binds `127.0.0.1` only. A random 256-bit token is stored in `~/.gentle-dot/token` (mode 0600). The desktop app reads it; the browser receives it once by URL fragment.- WebSocket upgrades check `Origin` against an allowlist (`http://127.0.0.1:4317`, `tauri://localhost`).- The VPS guide requires HTTPS, a reverse proxy with authentication, and a dedicated Docker container with no access to personal machines.-- The assistant's engine runs as the user with a shell. Its file tools cannot read the token, sign-ins, or connector files, and the connector state lives in the daemon's memory (§4, Connectors), but shell checks are best effort: a determined command can still read what the user's account can read. Stage 2 (S25) moves connector tokens and enforcement into the daemon.+- The assistant's engine runs as the user with a shell. Its file tools cannot read the token, sign-ins, or connector files, and the connector state lives in the daemon's memory (§4, Connectors), but shell checks are best effort: a determined command can still read what the user's account can read. Stage 2 (S25) moves connector tokens and enforcement into the daemon: the MCP proxy (S25.4, done) keeps every token, real address, and server environment out of the engine's `mcp.json`, and enforces mode, hidden tools, and approvals in the daemon. Still open: the sign-ins are files in the daemon's sign-in home (Keychain in T23d), approval answers still come over the WebSocket (native dialogs and the app key in T23b/T23c), and the proxy key is in the engine's `mcp.json`, so the agent's shell could call the proxy directly; that reaches only what the proxy allows, and every sending action still needs the user's approval.## 9. Desktop shell contract (Tauri 2 <-> UI)diff --git a/packages/daemon/package.json b/packages/daemon/package.jsonindex 48360d0..ca4772a 100644--- a/packages/daemon/package.json+++ b/packages/daemon/package.json@@ -12,6 +12,7 @@"dependencies": {"@earendil-works/pi-ai": "1.0.4","@earendil-works/pi-coding-agent": "1.0.4",+ "@earendil-works/pi-mcp": "1.0.4","@earendil-works/pi-tui": "1.0.4","@gentle-dot/protocol": "workspace:*","gentle-pi": "4.0.0",diff --git a/packages/daemon/src/bridge.ts b/packages/daemon/src/bridge.tsindex b9aadc4..793a031 100644--- a/packages/daemon/src/bridge.ts+++ b/packages/daemon/src/bridge.ts@@ -1,3 +1,4 @@+import { randomUUID } from "node:crypto";import { join } from "node:path";import {type AgentState,@@ -79,8 +80,16 @@ type ProfileCommand = Extract<const DIALOG_METHODS = new Set(["select", "confirm", "input", "editor"]);-/** An open dialog; `options` keeps the agent's original option strings for the answer. */-type PendingAsk = { ask: Ask; options?: string[]; timer?: NodeJS.Timeout };+/**+ * An open dialog; `options` keeps the agent's original option strings for the answer. `settle` is set+ * for the daemon's own questions (the MCP proxy's approvals): the answer goes there, not to the agent.+ */+type PendingAsk = {+ ask: Ask;+ options?: string[];+ timer?: NodeJS.Timeout;+ settle?: (allowed: boolean) => void;+};const REMEMBERED_REQUEST_IDS = 500;const READY_TIMEOUT_MS = 60_000;const ANSWER_FAILED = "Something went wrong while answering. Please try again.";@@ -146,6 +155,30 @@ export class DotBridge {return this.state;}+ /**+ * Asks every window to confirm an action of the daemon's own (a connector's sending action through+ * the MCP proxy), on the same card as the engine's approvals. Resolves true only when the user+ * confirms; declining, stopping the answer, or `signal` resolves false. Rejects when no window can+ * answer. T23c moves this to the desktop app's native dialog.+ */+ confirm(title: string, message: string, signal?: AbortSignal): Promise<boolean> {+ if (this.clients.size === 0) return Promise.reject(new Error("no window can answer"));+ if (signal?.aborted) return Promise.resolve(false);+ const requestId = `daemon-${randomUUID()}`;+ return new Promise((resolve) => {+ const ask: Ask = {+ requestId,+ method: "confirm",+ title: presentText(title),+ message: presentText(message),+ };+ this.asks.set(requestId, { ask, settle: resolve });+ signal?.addEventListener("abort", () => this.resolveAsk(requestId), { once: true });+ this.broadcast({ type: "ask", ask });+ this.refreshState();+ });+ }+attach(client: BridgeClient): () => void {this.clients.add(client);this.deliver(client, {@@ -261,6 +294,11 @@ export class DotBridge {return;}const { requestId } = message;+ if (pending.settle) {+ pending.settle(message.confirmed === true && !message.cancelled);+ this.resolveAsk(requestId);+ return;+ }const answer: Record<string, unknown> = {};if (message.cancelled) answer.cancelled = true;else if (message.confirmed !== undefined) answer.confirmed = message.confirmed;@@ -1098,6 +1136,8 @@ export class DotBridge {const entry = this.asks.get(requestId);if (!entry) return;clearTimeout(entry.timer);+ // A question of the daemon's that closes unanswered is a refusal (its answer, if any, came first).+ entry.settle?.(false);this.asks.delete(requestId);this.broadcast({ type: "ask_resolved", requestId });this.refreshState();diff --git a/packages/daemon/src/connector-credentials.ts b/packages/daemon/src/connector-credentials.tsnew file mode 100644index 0000000..67de479--- /dev/null+++ b/packages/daemon/src/connector-credentials.ts@@ -0,0 +1,136 @@+/**+ * The values the daemon's MCP proxy adds to a connector's real server (S25.4). For now they come+ * from where they lived before the proxy: the values the user typed (kept in `connectors.json`) and+ * the OAuth sign-ins in pi-mcp's state format (`mcp-auth.json`, now in the daemon's own sign-in+ * home). T23d moves them to the Keychain.+ */+import { execFileSync } from "node:child_process";+import type { AuthProvider } from "@earendil-works/pi-mcp";+import {+ authorizeMcp,+ McpOAuthAuthorizationRequiredError,+ McpOAuthProvider,+ type McpOAuthStateStore,+ parseWwwAuthenticate,+} from "@earendil-works/pi-mcp/oauth";++const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;+/** Where a refresh says it would redirect when nothing is stored; refreshing never redirects. */+const FALLBACK_REDIRECT = "http://127.0.0.1/callback";++/**+ * A value in the engine's syntax, resolved the way the engine resolved it before the proxy: a+ * leading `!` runs the rest as a command and takes its output, `$NAME` and `${NAME}` read the+ * environment, `$$` is `$` and `$!` is `!`. Throws when a variable or the command gives nothing.+ */+export function resolveValue(text: string, env: NodeJS.ProcessEnv, label: string): string {+ if (text.startsWith("!")) {+ let output = "";+ try {+ output = execFileSync("/bin/sh", ["-c", text.slice(1)], {+ encoding: "utf8",+ timeout: 10_000,+ stdio: ["ignore", "pipe", "ignore"],+ env,+ }).trim();+ } catch {}+ if (!output) throw new Error(`${label} could not be read: its command gave nothing.`);+ return output;+ }+ let resolved = "";+ for (let index = 0; index < text.length; ) {+ const dollar = text.indexOf("$", index);+ if (dollar < 0) {+ resolved += text.slice(index);+ break;+ }+ resolved += text.slice(index, dollar);+ const next = text[dollar + 1];+ if (next === "$" || next === "!") {+ resolved += next;+ index = dollar + 2;+ continue;+ }+ const braced = next === "{" ? /^\$\{([^}]*)\}/.exec(text.slice(dollar)) : undefined;+ const name = braced ? braced[1] : /^\$([A-Za-z_][A-Za-z0-9_]*)/.exec(text.slice(dollar))?.[1];+ if (!name || !ENV_NAME.test(name)) {+ resolved += braced ? braced[0] : "$";+ index = dollar + (braced ? braced[0].length : 1);+ continue;+ }+ const value = env[name];+ if (!value) throw new Error(`${label} needs the environment variable ${name}.`);+ resolved += value;+ index = dollar + (braced ? braced[0].length : 1 + name.length);+ }+ return resolved;+}++/** Every value of a record resolved with {@link resolveValue}; undefined when there is none. */+export function resolveRecord(+ values: Record<string, string> | undefined,+ env: NodeJS.ProcessEnv,+ label: string,+): Record<string, string> | undefined {+ if (!values || Object.keys(values).length === 0) return undefined;+ return Object.fromEntries(+ Object.entries(values).map(([key, text]) => [key, resolveValue(text, env, `${label} ${key}`)]),+ );+}++export interface OAuthClientSettings {+ clientId?: string;+ clientSecret?: string;+ /** The redirect registered for the user's own OAuth app; a refresh sends it as is. */+ redirectUrl?: string;+}++/**+ * Sends the stored access token and, after a 401, refreshes it with the stored refresh token, like+ * the engine did: concurrent 401s share one refresh, a token another sign-in already replaced is+ * just retried, and when the user must sign in again (no refresh token, a refused refresh, or more+ * scope) it throws `McpOAuthAuthorizationRequiredError`. Never starts a browser sign-in.+ */+export function storedSignIn(+ serverUrl: string,+ store: McpOAuthStateStore,+ settings: () => OAuthClientSettings,+): AuthProvider {+ let refreshing: Promise<void> | undefined;+ return {+ token: async () => (await store.load())?.tokens?.access_token,+ onUnauthorized: async (context) => {+ const challenge = parseWwwAuthenticate(context.response.headers.get("www-authenticate"));+ if (challenge.error === "insufficient_scope") throw new McpOAuthAuthorizationRequiredError();+ refreshing ??= (async () => {+ const state = await store.load();+ if (state?.tokens?.access_token !== context.token) return;+ if (!state?.tokens?.refresh_token) throw new McpOAuthAuthorizationRequiredError();+ const { clientId, clientSecret, redirectUrl } = settings();+ const registered = state.clientInformation;+ const provider = new McpOAuthProvider({+ serverUrl,+ redirectUrl:+ redirectUrl ??+ (registered && "redirect_uris" in registered ? registered.redirect_uris[0] : undefined) ??+ FALLBACK_REDIRECT,+ clientMetadata: { client_name: "Gentle Dot" },+ ...(clientId ? { clientId } : {}),+ ...(clientSecret ? { clientSecret } : {}),+ store,+ onRedirect: () => {},+ });+ const result = await authorizeMcp(provider, {+ serverUrl,+ fetch: context.fetch,+ ...(challenge.resourceMetadataUrl ? { resourceMetadataUrl: challenge.resourceMetadataUrl } : {}),+ ...(challenge.scope ? { scope: challenge.scope } : {}),+ });+ if (result === "REDIRECT") throw new McpOAuthAuthorizationRequiredError();+ })().finally(() => {+ refreshing = undefined;+ });+ await refreshing;+ },+ };+}diff --git a/packages/daemon/src/connectors.ts b/packages/daemon/src/connectors.tsindex cc70208..fb5883c 100644--- a/packages/daemon/src/connectors.ts+++ b/packages/daemon/src/connectors.ts@@ -1,5 +1,5 @@import { type ChildProcess, spawn } from "node:child_process";-import { randomUUID } from "node:crypto";+import { createHash, randomUUID } from "node:crypto";import {existsSync,type FSWatcher,@@ -15,6 +15,7 @@ import { createRequire } from "node:module";import { homedir } from "node:os";import { join } from "node:path";import { fileURLToPath } from "node:url";+import type { McpOAuthState } from "@earendil-works/pi-mcp/oauth";import type {ConnectorDraft,ConnectorGuide,@@ -24,8 +25,11 @@ import type {ServerPayload,} from "@gentle-dot/protocol";import { MAX_CONNECTOR_DRAFTS } from "@gentle-dot/protocol";+import { resolveRecord, resolveValue, storedSignIn } from "./connector-credentials.ts";import { type ScannedServer, scanClientConfigs, valueNotes } from "./connector-import.ts";import { type ConnectorPolicy, draftSecretProblem, POLICY_ENV } from "./extensions/approval-guard.ts";+import { ensurePrivateDir } from "./isolation.ts";+import type { ProxiedConnector, UpstreamCredentials } from "./mcp-proxy.ts";import { runtimeDir, runtimeModules } from "./runtime.ts";/** A value the user types in the app (a token, client credentials); kept only in the assistant's private state. */@@ -307,10 +311,19 @@ export interface ComputerEndpoint {token: string;}+/** The daemon's MCP proxy (S25.4) for this engine launch: its base address (`…/mcp`) and its key. */+export interface ProxyEndpoint {+ url: string;+ key: string;+}+/** The built-in server's name in `mcp.json`; no connector can take it. */export const COMPUTER_ID = "computer";-/** Seconds the engine waits for one helper call: enough to answer its grant or confirmation dialog. */-const COMPUTER_TIMEOUT_SECONDS = 300;+/**+ * Seconds the engine waits for one call to the helper or the proxy: enough for the user to answer+ * a dialog or an approval card (the engine's 30 s default would cut them).+ */+const CALL_TIMEOUT_SECONDS = 300;const COMPUTER_INFO = {id: COMPUTER_ID,@@ -445,19 +458,59 @@ function ordered(state: ConnectorsState): [string, SavedConnector][] {];}+/** The real server of a connector with the user's values in place, or undefined while one is missing. */+function filledServer(id: string, saved: SavedConnector | undefined) {+ const spec = specOf(id, saved);+ const server = spec && fillServer(spec.server, spec.fields, saved?.values ?? {});+ return spec && server ? { spec, server } : undefined;+}+/**- * The engine's `mcp.json` for the added connectors. The assistant turns codemode off, so every- * server is `direct`. Read only hides every tool (`*`) except the curated ones (exact names win- * over patterns in the engine), so a tool the catalog does not know stays hidden; a server of the- * user's own has no curated list, so all of its tools are hidden. A connector that still waits for- * a value the user types is left out.+ * The engine's `mcp.json` (S25.4): every connector is the daemon's proxy address for it, with this+ * launch's key, and nothing else: no real address, token, environment, or command. The proxy filters+ * the tools by mode and asks before sending actions, so every server is `direct` (the assistant+ * turns codemode off). Until the proxy listens, the connectors are left out. A connector that still+ * waits for a value the user types is left out too.*/-export function renderMcpJson(state: ConnectorsState, computer?: ComputerEndpoint): string {+export function renderMcpJson(+ state: ConnectorsState,+ computer?: ComputerEndpoint,+ proxy?: ProxyEndpoint,+): string {+ const servers: Record<string, unknown> = {};+ if (proxy)+ for (const [id, saved] of ordered(state)) {+ if (!filledServer(id, saved)) continue;+ servers[id] = {+ url: `${proxy.url}/${encodeURIComponent(id)}`,+ headers: { Authorization: `Bearer ${literal(proxy.key)}` },+ exposure: "direct",+ timeout: CALL_TIMEOUT_SECONDS,+ ...(saved.enabled ? {} : { enabled: false }),+ };+ }+ // The helper checks its own key and asks the user itself, so all of its tools are direct.+ if (computer)+ servers[COMPUTER_ID] = {+ url: computer.url,+ headers: { Authorization: `Bearer ${literal(computer.token)}` },+ exposure: "direct",+ timeout: CALL_TIMEOUT_SECONDS,+ };+ return `${JSON.stringify({ mcpServers: servers }, null, 2)}\n`;+}++/**+ * The real servers, in the engine's format, for the daemon's own sign-in home: only the engine's+ * `mcp login` and `mcp logout` commands read it, never the engine that talks to the model. Read only+ * still hides every tool (`*`) except the curated ones, as the engine would have.+ */+export function renderSigninMcpJson(state: ConnectorsState): string {const servers: Record<string, unknown> = {};for (const [id, saved] of ordered(state)) {- const spec = specOf(id, saved);- const server = spec && fillServer(spec.server, spec.fields, saved.values ?? {});- if (!spec || !server) continue;+ const filled = filledServer(id, saved);+ if (!filled) continue;+ const { spec, server } = filled;servers[id] = {...server,exposure: "direct",@@ -472,15 +525,6 @@ export function renderMcpJson(state: ConnectorsState, computer?: ComputerEndpoin...(saved.enabled ? {} : { enabled: false }),};}- // The helper checks its own key and asks the user itself, so all of its tools are direct.- // Its calls wait while the user answers a native dialog, so the engine's 30 s default would cut them.- if (computer)- servers[COMPUTER_ID] = {- url: computer.url,- headers: { Authorization: `Bearer ${literal(computer.token)}` },- exposure: "direct",- timeout: COMPUTER_TIMEOUT_SECONDS,- };return `${JSON.stringify({ mcpServers: servers }, null, 2)}\n`;}@@ -492,8 +536,10 @@ function writePrivate(path: string, text: string): void {export interface ConnectorStoreOptions {dataDir: string;- /** The engine's home, which holds `mcp.json` and `mcp-auth.json`. */+ /** The engine's home, which holds its `mcp.json` (and held `mcp-auth.json` before the proxy). */agentHome: string;+ /** The environment the values of imported servers may read (`$NAME`); default the daemon's. */+ env?: NodeJS.ProcessEnv;/** The engine's working folder; a project `.pi/mcp.json` there would add servers. */workspace?: string;/** The approval guard's own file, protected like the connector files. */@@ -504,20 +550,40 @@ export interface ConnectorStoreOptions {/*** The connectors the user approved. The daemon reads `<data>/connectors.json` once, when it* starts, and from then on the state lives in memory and changes only through the Connectors- * screen. The files (`connectors.json`, the engine's `mcp.json`) are written from memory; a change- * made by anything else (the assistant has a shell) is put back, and a project `.pi/mcp.json` in- * the workspace is removed. Checked on every file event, before every engine start, and after- * every run. A change made while the daemon is not running is loaded at its next start (stage 2, S25).+ * screen. The files (`connectors.json`, the engine's `mcp.json`, and the sign-in home's `mcp.json`)+ * are written from memory; a change made by anything else (the assistant has a shell) is put back,+ * and a project `.pi/mcp.json` in the workspace is removed. The sign-ins (`mcp-auth.json`) change+ * only during a sign-in or a token refresh; other changes are put back too. Checked on every file+ * event, before every engine start, and after every run. A change made while the daemon is not+ * running is loaded at its next start (S25.6).+ *+ * The engine's `mcp.json` lists only the daemon's proxy (S25.4). The real servers and the sign-ins+ * are in the daemon's own sign-in home (`<data>/connector-signin`), which only the engine's+ * `mcp login`/`mcp logout` commands are pointed at.*/export class ConnectorStore {readonly file: string;readonly mcpFile: string;+ /** The daemon's own folder for the sign-in command: the real servers and the sign-ins. */+ readonly signinHome: string;+ readonly signinMcpFile: string;+ /** The sign-ins (pi-mcp's OAuth state by `mcp__<server>|<url>`), in the sign-in home. */readonly authFile: string;+ /** Where the engine kept the sign-ins before the proxy; moved once into the sign-in home. */+ readonly legacyAuthFile: string;/** Called after a change made outside the Connectors screen was put back. */onReverted: () => void = () => {};+ /** Called after every change to the state (the proxy closes what it no longer may use). */+ onUpdated: () => void = () => {};private saved: ConnectorsState;/** The desktop app's helper while a window has it registered; only in memory and `mcp.json`. */private computer: ComputerEndpoint | undefined;+ /** The daemon's proxy for the running engine; only in memory and `mcp.json`. */+ private proxy: ProxyEndpoint | undefined;+ /** The sign-ins as the last sign-in or refresh left them (undefined: no file). */+ private authText: string | undefined;+ /** Sign-in commands running now; they write the sign-ins themselves. */+ private signins = 0;private watchers: FSWatcher[] = [];private readonly options: ConnectorStoreOptions;@@ -525,7 +591,12 @@ export class ConnectorStore {this.options = options;this.file = join(options.dataDir, "connectors.json");this.mcpFile = join(options.agentHome, "mcp.json");- this.authFile = join(options.agentHome, "mcp-auth.json");+ this.signinHome = join(options.dataDir, "connector-signin");+ this.signinMcpFile = join(this.signinHome, "mcp.json");+ this.authFile = join(this.signinHome, "mcp-auth.json");+ this.legacyAuthFile = join(options.agentHome, "mcp-auth.json");+ this.moveLegacySignIns();+ this.authText = readOrUndefined(this.authFile);const { state, renamed } = this.load();this.saved = state;if (renamed) writePrivate(this.file, this.recordText());@@ -539,14 +610,17 @@ export class ConnectorStore {return structuredClone(this.saved);}- /** Changes the state, then writes both files (each atomically, mode 0600). */+ /** Changes the state, then writes the files (each atomically, mode 0600). */update(change: (state: ConnectorsState) => void): void {const state = this.state();change(state);this.saved = state;mkdirSync(this.options.agentHome, { recursive: true, mode: 0o700 });+ ensurePrivateDir(this.signinHome);writePrivate(this.file, this.recordText());- writePrivate(this.mcpFile, renderMcpJson(state, this.computer));+ writePrivate(this.mcpFile, this.engineMcpText());+ writePrivate(this.signinMcpFile, renderSigninMcpJson(state));+ this.onUpdated();}/** Adds, replaces, or removes the computer helper in `mcp.json`; true when that changed it. */@@ -555,10 +629,94 @@ export class ConnectorStore {if (same) return false;this.computer = endpoint ? { ...endpoint } : undefined;mkdirSync(this.options.agentHome, { recursive: true, mode: 0o700 });- writePrivate(this.mcpFile, renderMcpJson(this.saved, this.computer));+ writePrivate(this.mcpFile, this.engineMcpText());return true;}+ /** Points `mcp.json` at the proxy with the key for the next engine launch; true when that changed it. */+ setProxy(endpoint: ProxyEndpoint): boolean {+ if (endpoint.url === this.proxy?.url && endpoint.key === this.proxy?.key) return false;+ this.proxy = { ...endpoint };+ mkdirSync(this.options.agentHome, { recursive: true, mode: 0o700 });+ writePrivate(this.mcpFile, this.engineMcpText());+ return true;+ }++ /** A connector as the proxy sees it, from the state in memory; undefined when it cannot run. */+ proxyView(id: string): ProxiedConnector | undefined {+ const saved = this.saved.connectors[id];+ const filled = saved && filledServer(id, saved);+ if (!saved || !filled) return undefined;+ const { spec, server } = filled;+ return {+ id,+ name: spec.name,+ enabled: saved.enabled,+ mode: saved.mode,+ readOnlyTools: [...spec.readOnlyTools],+ server:+ "url" in server+ ? { url: server.url }+ : {+ command: server.command,+ ...(server.args ? { args: [...server.args] } : {}),+ ...(server.cwd !== undefined ? { cwd: server.cwd } : {}),+ },+ // The server with its values: a new token or address makes a new connection.+ revision: createHash("sha256").update(JSON.stringify(server)).digest("hex"),+ };+ }++ /**+ * What the proxy adds to the real server: the values the user typed (headers, a stdio server's+ * environment) as they were typed, and for a remote server without its own Authorization header,+ * the stored sign-in, refreshed when it expires.+ */+ async credentials(id: string): Promise<UpstreamCredentials> {+ const filled = filledServer(id, this.saved.connectors[id]);+ if (!filled) throw new Error(`The connector ${id} is not set up.`);+ const { spec, server } = filled;+ const env = this.options.env ?? process.env;+ if ("command" in server) {+ const resolved = resolveRecord(server.env, env, spec.name);+ return resolved ? { env: resolved } : {};+ }+ const headers = resolveRecord(server.headers, env, spec.name);+ const ownAuthorization = Object.keys(server.headers ?? {}).some(+ (h) => h.toLowerCase() === "authorization",+ );+ if (ownAuthorization) return headers ? { headers } : {};+ const key = authKey(id, server.url);+ const { oauth } = server;+ const authProvider = storedSignIn(+ server.url,+ { load: () => this.signIn(key), save: (state) => this.saveSignIn(key, state) },+ () => ({+ ...(oauth?.clientId ? { clientId: oauth.clientId } : {}),+ ...(oauth?.clientSecret+ ? { clientSecret: resolveValue(oauth.clientSecret, env, `${spec.name} client secret`) }+ : {}),+ ...(oauth?.callbackUrl ? { redirectUrl: oauth.callbackUrl } : {}),+ }),+ );+ return { ...(headers ? { headers } : {}), authProvider };+ }++ /**+ * While the engine's sign-in command runs, it writes the sign-ins itself; call the returned+ * function when it ended, so what it wrote is kept.+ */+ signingIn(): () => void {+ this.signins++;+ let done = false;+ return () => {+ if (done) return;+ done = true;+ this.signins--;+ this.authText = readOrUndefined(this.authFile);+ };+ }+/** The helper's address while it is registered (never its key). */computerUrl(): string | undefined {return this.computer?.url;@@ -575,14 +733,25 @@ export class ConnectorStore {const changed: string[] = [];for (const [file, text, empty] of [[this.file, this.recordText(), noConnectors],- [this.mcpFile, renderMcpJson(this.saved, this.computer), noConnectors && !this.computer],+ [this.mcpFile, this.engineMcpText(), noConnectors && !this.computer],+ [this.signinMcpFile, renderSigninMcpJson(this.saved), noConnectors],] as const) {- const current = existsSync(file) ? readFileSync(file, "utf8") : undefined;+ const current = readOrUndefined(file);if (current === text || (current === undefined && empty)) continue;mkdirSync(this.options.agentHome, { recursive: true, mode: 0o700 });+ ensurePrivateDir(this.signinHome);writePrivate(file, text);changed.push(file);}+ // The sign-ins change only through a sign-in or a refresh.+ if (this.signins === 0 && readOrUndefined(this.authFile) !== this.authText) {+ if (this.authText === undefined) unlinkSync(this.authFile);+ else {+ ensurePrivateDir(this.signinHome);+ writePrivate(this.authFile, this.authText);+ }+ changed.push(this.authFile);+ }if (this.removeProjectConfig()) changed.push("the workspace's .pi/mcp.json");if (changed.length === 0 || !report) return changed.length > 0;this.options.log?.(@@ -610,7 +779,8 @@ export class ConnectorStore {this.watchProjectConfig();}, 20);};- const folders = [this.options.dataDir, this.options.agentHome, this.options.workspace];+ ensurePrivateDir(this.signinHome);+ const folders = [this.options.dataDir, this.options.agentHome, this.signinHome, this.options.workspace];for (const folder of folders) {if (!folder) continue;mkdirSync(folder, { recursive: true, mode: 0o700 });@@ -629,19 +799,28 @@ export class ConnectorStore {this.projectWatcher = undefined;}- /** What the approval guard enforces: the turned-on connectors and the files only the daemon writes. */+ /**+ * What the approval guard enforces: the turned-on connectors, which of them the proxy fronts (it+ * filters and asks, so the guard lets their tools through), and the files only the daemon writes.+ */policy(): ConnectorPolicy {const connectors: NonNullable<ConnectorPolicy["connectors"]> = {};- for (const [id, saved] of Object.entries(this.state().connectors)) {+ const proxied: string[] = [];+ for (const [id, saved] of ordered(this.saved)) {const spec = specOf(id, saved);- if (spec && saved.enabled)- connectors[id] = { name: spec.name, mode: saved.mode, readOnlyTools: [...spec.readOnlyTools] };+ if (!spec || !saved.enabled) continue;+ connectors[id] = { name: spec.name, mode: saved.mode, readOnlyTools: [...spec.readOnlyTools] };+ if (filledServer(id, saved)) proxied.push(id);}return {connectors,+ proxied,// Sign-ins and keys, connector state, and the daemon's access key.protectedPaths: [this.mcpFile,+ this.legacyAuthFile,+ this.signinHome,+ this.signinMcpFile,this.authFile,join(this.options.agentHome, "auth.json"),join(this.options.agentHome, "models.json"),@@ -654,26 +833,72 @@ export class ConnectorStore {}/**- * True when the engine stored tokens for the connector (key `mcp__<server>|<url>`, `-` as `_`).- * Token values are dropped while parsing, so they are never kept or passed on.+ * True when the sign-in command stored tokens for the connector (key `mcp__<server>|<url>`, `-`+ * as `_`). Token values are dropped while parsing, so they are never kept or passed on.*/isSignedIn(id: string): boolean {- const saved = this.saved.connectors[id];- const spec = specOf(id, saved);- const server = spec && fillServer(spec.server, spec.fields, saved?.values ?? {});+ const server = filledServer(id, this.saved.connectors[id])?.server;if (!server || !("url" in server) || !URL.canParse(server.url) || !existsSync(this.authFile))return false;try {const states = JSON.parse(readFileSync(this.authFile, "utf8"), (key, value) =>key === "tokens" && typeof value === "object" && value !== null ? {} : value,) as Record<string, { tokens?: unknown } | undefined>;- const key = `mcp__${id.replace(/-/g, "_")}|${new URL(server.url).href}`;- return typeof states[key]?.tokens === "object";+ return typeof states[authKey(id, server.url)]?.tokens === "object";} catch {return false;}}+ /** One server's stored sign-in, for the proxy. */+ private signIn(key: string): McpOAuthState | undefined {+ try {+ const states = JSON.parse(readFileSync(this.authFile, "utf8")) as Record<+ string,+ McpOAuthState | undefined+ >;+ return states[key];+ } catch {+ return undefined;+ }+ }++ /** Keeps a refreshed sign-in; the file is then what it should be. */+ private saveSignIn(key: string, state: McpOAuthState): void {+ let states: Record<string, unknown> = {};+ try {+ states = JSON.parse(readFileSync(this.authFile, "utf8")) as Record<string, unknown>;+ } catch {}+ states[key] = state;+ const text = `${JSON.stringify(states, null, 2)}\n`;+ ensurePrivateDir(this.signinHome);+ writePrivate(this.authFile, text);+ this.authText = text;+ }++ /**+ * Before the proxy, the engine kept the sign-ins in its home. They move once, the first time the+ * sign-in home is made: the copy is read back before the old file is removed. A file that shows up+ * in the engine's home later is never taken over.+ */+ private moveLegacySignIns(): void {+ if (existsSync(this.signinHome)) return;+ ensurePrivateDir(this.signinHome);+ const text = readOrUndefined(this.legacyAuthFile);+ if (text === undefined) return;+ writePrivate(this.authFile, text);+ if (readOrUndefined(this.authFile) !== text) {+ this.options.log?.("could not move the connector sign-ins; they stay where they were");+ return;+ }+ unlinkSync(this.legacyAuthFile);+ this.options.log?.("moved the connector sign-ins to the daemon's sign-in folder");+ }++ private engineMcpText(): string {+ return renderMcpJson(this.saved, this.computer, this.proxy);+ }+private check: () => void = () => {};private poll: NodeJS.Timeout | undefined;private projectWatcher: FSWatcher | undefined;@@ -783,6 +1008,19 @@ function parseCustom(value: unknown): CustomConnector | undefined {};}+/** A sign-in's key in `mcp-auth.json`, like the engine's (`mcp__<server>|<url>`, `-` as `_`). */+function authKey(id: string, url: string): string {+ return `mcp__${id.replace(/-/g, "_")}|${new URL(url).href}`;+}++function readOrUndefined(path: string): string | undefined {+ try {+ return readFileSync(path, "utf8");+ } catch {+ return undefined;+ }+}+function lstatOrUndefined(path: string) {try {return lstatSync(path);@@ -1371,13 +1609,18 @@ export class ConnectorManager {return undefined;}+ /** The engine's sign-in command, pointed at the daemon's sign-in home (the real servers), never the engine's. */private run(subcommand: "login" | "logout", id: string): ChildProcess {- const { cli, env, cwd } = this.options;- return spawn(cli.command, [...cli.args, "mcp", subcommand, id], {+ const { cli, env, cwd, store } = this.options;+ const done = store.signingIn();+ const child = spawn(cli.command, [...cli.args, "mcp", subcommand, id], {cwd,- env: { ...env, PI_CODING_AGENT_DIR: this.options.store.agentHome },+ env: { ...env, PI_CODING_AGENT_DIR: store.signinHome },stdio: ["ignore", "pipe", "pipe"],});+ child.on("error", done);+ child.on("close", done);+ return child;}private startLogin(owner: object, connectorId: string, emit: Emit, flowId?: string): void {diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.tsindex 83dad28..739a13e 100644--- a/packages/daemon/src/daemon.ts+++ b/packages/daemon/src/daemon.ts@@ -3,6 +3,7 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSyncimport { createServer, type IncomingMessage, type ServerResponse } from "node:http";import type { AddressInfo } from "node:net";import { extname, join, resolve, sep } from "node:path";+import type { McpTransport } from "@earendil-works/pi-mcp";import {type AttachmentLimits,type ClientMessage,@@ -21,7 +22,9 @@ import {type McpCli,policyEnv,} from "./connectors.ts";+import { approvalCard } from "./extensions/approval-guard.ts";import { ensureMemoryProject, ensurePrivateDir, isolatedAgentEnv, privateMemory } from "./isolation.ts";+import { MCP_PREFIX, McpProxy, type ProxiedConnector, type UpstreamCredentials } from "./mcp-proxy.ts";import { defaultImportPath, ProfileStore } from "./profiles.ts";import { type RotationLimits, rotationLimits } from "./rotation.ts";import { AgentSupervisor } from "./supervisor.ts";@@ -55,6 +58,8 @@ export interface DaemonOptions {connectorCli?: McpCli;/** The home folder "Import my MCP servers" reads other apps' configs from; default `GENTLE_DOT_IMPORT_HOME` or the user's. */importHome?: string;+ /** The connection the MCP proxy makes to a connector's real server; tests pass a stand-in. */+ connectorTransport?: (connector: ProxiedConnector, credentials: UpstreamCredentials) => McpTransport;/** Origins allowed to open the WebSocket, besides the daemon's own and the desktop app's. */allowedOrigins?: string[];backoffMs?: number[];@@ -143,8 +148,25 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {agentHome,workspace: options.workspace,guardPath: APPROVAL_GUARD,+ env: agentEnv,+ log,+ });+ // The engine reaches every connector through the proxy (S25.4); its key changes with every launch.+ let port = options.port;+ const proxy = new McpProxy({+ connector: (id) => connectorStore.proxyView(id),+ credentials: (id) => connectorStore.credentials(id),+ // For now on the same card path as the engine's approvals; T23c moves it to the app's native dialog.+ approve: (preview, signal) => {+ const card = approvalCard(preview.connector, preview.connectorId, preview.tool, preview.arguments);+ return bridge.confirm(card.title, card.message, signal);+ },+ ...(options.connectorTransport ? { transport: options.connectorTransport } : {}),+ env: agentEnv,+ cwd: options.workspace,log,});+ connectorStore.onUpdated = () => proxy.sync();// The assistant's own engine loads the approval guard for connector actions.const guardArgs = options.agentHome ? ["-e", APPROVAL_GUARD] : [];const supervisor = new AgentSupervisor({@@ -161,8 +183,10 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {env: agentEnv,// mcp.json is read when a session starts: put back anything not approved, and hand the guard// its policy from the daemon's memory, never from the files.+ // The proxy's key changes with every launch (after the check, so a change is still reported).prepareSpawn: () => {connectors.enforce();+ connectorStore.setProxy({ url: `http://127.0.0.1:${port}/mcp`, key: proxy.rotateKey() });return policyEnv(connectorStore);},// The first start in a new home installs the engine's companion packages.@@ -217,14 +241,18 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {connectorStore.watch();const server = createServer((req, res) => {- if (new URL(req.url ?? "/", "http://localhost").pathname === "/upload") {+ const { pathname } = new URL(req.url ?? "/", "http://localhost");+ if (pathname === "/upload") {void handleUpload(req, res, token, allowedOrigins(port, options), uploads);return;}+ if (pathname.startsWith(MCP_PREFIX)) {+ proxy.handle(req, res);+ return;+ }handleHttp(req, res, options.uiDir, bridge);});const wss = new WebSocketServer({ noServer: true, maxPayload: 1024 * 1024 });- let port = options.port;server.on("upgrade", (req, socket, head) => {const url = new URL(req.url ?? "/", "http://localhost");@@ -253,6 +281,8 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {async close() {for (const client of wss.clients) client.terminate();wss.close();+ // Stops waiting approvals and the connectors' servers (stdio ones are processes of the daemon).+ await proxy.close();await new Promise<void>((done) => server.close(() => done()));await supervisor.stop();connectorStore.close();diff --git a/packages/daemon/src/extensions/approval-guard.ts b/packages/daemon/src/extensions/approval-guard.tsindex df3ce18..6eb1874 100644--- a/packages/daemon/src/extensions/approval-guard.ts+++ b/packages/daemon/src/extensions/approval-guard.ts@@ -1,12 +1,15 @@/*** Approval guard, loaded into the engine with `-e` (docs/design.md §3).*- * Connector tools (`mcp__<server>__<tool>`) run without asking only when they are read-only:- * the server marks them `readOnlyHint: true` AND they are on the connector's curated list.- * Anything else asks the user through a confirm card with a preview, and is blocked when the- * user declines, when nobody can answer, or when the connector is set to read only. Calls made- * by other tools (nested calls) go through the same hook. The built-in computer server (the desktop- * app's helper, S24) runs without cards: the app grants sessions and confirms risky actions itself.+ * The connectors the user added reach the engine only through the daemon's MCP proxy (S25.4), which+ * filters their tools by mode, refuses hidden ones, and asks before every sending action, so their+ * tools (`mcp__<server>__<tool>`) pass here. A connector tool the proxy does not front (a server the+ * daemon did not put in `mcp.json`) runs without asking only when it is read-only: the server marks+ * it `readOnlyHint: true` AND it is on the connector's curated list. Anything else asks the user+ * through a confirm card with a preview, and is blocked when the user declines, when nobody can+ * answer, or when the connector is set to read only or is not approved. Calls made by other tools+ * (nested calls) go through the same hook. The built-in computer server (the desktop app's helper,+ * S24) runs without cards: the app grants sessions and confirms risky actions itself.** The policy (approved connectors, modes, curated lists, protected files) comes from the* daemon in this process's environment, which the assistant cannot change. Without a valid@@ -21,7 +24,8 @@* removed), the data folder, the keychain, or the engine's home variable is blocked. That check is* best effort, NOT a security boundary: the assistant runs as the user with a shell, so a command* can still build a name the check does not see. The daemon keeps the connector state in memory- * and puts changed files back (docs/design.md, Connectors), and stage 2 (S25) moves tokens out of reach.+ * and puts changed files back (docs/design.md, Connectors); the engine's `mcp.json` holds no tokens+ * (the proxy injects them upstream), and stage 2 (S25) moves the tokens out of reach.* The assistant may draft a new connector with `propose_connector`: the draft goes to the daemon as a* status update on the engine's own output (`ctx.ui.setStatus`), which only the daemon reads, and the* model hears only that the user will review it. The daemon shows the draft as a card and adds it@@ -121,6 +125,11 @@ export interface ConnectorPolicy {* helper, which asks the user itself (session grant, risky-action confirmations) outside the engine.*/builtin?: string[];+ /**+ * Connectors the daemon's MCP proxy fronts (S25.4): the proxy shows only what their mode allows,+ * refuses hidden tools, and asks before every sending action, so their tools run without a card here.+ */+ proxied?: string[];}/** The only server that can be built in. */@@ -165,14 +174,27 @@ const PREVIEW_LIMIT = 8000;/** Like the engine's tool names: everything but letters, digits, and `_` becomes `_`. */const toolId = (server: string, tool: string) => `mcp__${server}__${tool}`.replace(/[^A-Za-z0-9_]/g, "_");-/** Read-only only when the server declares it AND the curated list names it (fail closed). */+/**+ * The read-only rule, shared with the daemon's MCP proxy: a tool (by its MCP name) only reads when+ * the server declares it (`readOnlyHint: true`) AND the connector's curated list names it (fail closed).+ */+export function isReadOnlyTool(+ tool: string,+ readOnlyHint: unknown,+ readOnlyTools: readonly string[],+): boolean {+ return readOnlyHint === true && readOnlyTools.includes(tool);+}++/** {@link isReadOnlyTool} for an engine tool name (`mcp__<server>__<tool>`). */export function isReadOnlyCall(server: string,toolName: string,readOnlyHint: unknown,readOnlyTools: readonly string[],): boolean {- return readOnlyHint === true && readOnlyTools.some((tool) => toolId(server, tool) === toolName);+ const tool = readOnlyTools.find((name) => toolId(server, name) === toolName);+ return tool !== undefined && isReadOnlyTool(tool, readOnlyHint, readOnlyTools);}/** The policy from the daemon, or undefined when it is missing or malformed. */@@ -200,12 +222,21 @@ export function parsePolicy(raw: string | undefined): ConnectorPolicy | undefineentry.readOnlyTools.every((tool) => typeof tool === "string");if (!valid) return undefined;}- const { builtin } = policy;- if (builtin === undefined) return { connectors, protectedPaths: policy.protectedPaths };+ const { builtin, proxied } = policy;const known: readonly string[] = BUILTIN_SERVERS;- if (!Array.isArray(builtin) || !builtin.every((id) => typeof id === "string" && known.includes(id)))+ if (+ builtin !== undefined &&+ (!Array.isArray(builtin) || !builtin.every((id) => typeof id === "string" && known.includes(id)))+ )+ return undefined;+ if (proxied !== undefined && (!Array.isArray(proxied) || !proxied.every((id) => typeof id === "string")))return undefined;- return { connectors, protectedPaths: policy.protectedPaths, builtin };+ return {+ connectors,+ protectedPaths: policy.protectedPaths,+ ...(builtin !== undefined ? { builtin } : {}),+ ...(proxied !== undefined ? { proxied } : {}),+ };}export function decide(call: GuardCall, policy: ConnectorPolicy): GuardDecision {@@ -230,6 +261,8 @@ export function decide(call: GuardCall, policy: ConnectorPolicy): GuardDecision}if (!toolName.startsWith("mcp__")) return { action: "pass" };if (policy.builtin?.some((id) => toolName.startsWith(toolId(id, "")))) return { action: "pass" };+ // The proxy decides, and asks the user itself; a card here would ask twice.+ if (policy.proxied?.some((id) => toolName.startsWith(toolId(id, "")))) return { action: "pass" };const approved = policy.connectors;const server = approved@@ -249,19 +282,35 @@ export function decide(call: GuardCall, policy: ConnectorPolicy): GuardDecisionaction: "block",reason: `${name} is set to read only, so this action was not run. If the user wants it, ask them to switch ${name} to "Read and send" in Connectors.`,};- const action = describeAction(toolName, server ?? "");return {action: "ask",+ ...approvalCard(name, server ?? "", toolName.slice(toolId(server ?? "", "").length), input),+ };+}++/**+ * The approval card for a sending action: the action in words and every argument. Shared with the+ * daemon's MCP proxy, which asks before it forwards a connector's sending action (S25.4).+ */+export function approvalCard(+ name: string,+ server: string,+ tool: string,+ input: Record<string, unknown>,+): { title: string; message: string } {+ const action = describeAction(tool, server);+ return {title: `Allow ${name} to ${action}?`,message: `The assistant wants to ${action} in ${name}.\n\n${preview(input)}`.trimEnd(),};}-/** `mcp__notion__notion_create_pages` -> "create pages". */-function describeAction(toolName: string, server: string): string {- let action = toolName.slice(toolId(server, "").length);- if (action.startsWith(`${server}_`)) action = action.slice(server.length + 1);- const words = action.split("_").filter(Boolean).join(" ");+/** `notion_create_pages` (or `notion-create-pages`) of `notion` -> "create pages". */+function describeAction(tool: string, server: string): string {+ let action = tool;+ if (action.startsWith(`${server}_`) || action.startsWith(`${server}-`))+ action = action.slice(server.length + 1);+ const words = action.split(/[_-]/).filter(Boolean).join(" ");return words ? words.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase() : "use a tool";}diff --git a/packages/daemon/src/mcp-proxy.ts b/packages/daemon/src/mcp-proxy.tsnew file mode 100644index 0000000..284bef3--- /dev/null+++ b/packages/daemon/src/mcp-proxy.ts@@ -0,0 +1,521 @@+/**+ * The daemon's MCP proxy (S25.4, docs/design.md "Connectors"). The engine's `mcp.json` lists every+ * connector as `http://127.0.0.1:<port>/mcp/<id>` with a key made for that engine launch; the daemon+ * answers there and talks to the real server itself: a remote one over streamable HTTP with the+ * headers and tokens it injects, or a stdio one it runs. The engine never sees an upstream address,+ * a token, or a server's environment.+ *+ * Every request reads the connector's state from the daemon's memory, so a mode change applies to+ * the next request without restarting the engine. `tools/list` shows only what the mode allows,+ * `tools/call` refuses hidden and unknown tools however they are called, and a sending action is+ * forwarded only after the user approves its full preview. Resources and prompts are reads: they are+ * shown in "read and send", and in read only only for a connector with a curated read-only list (the+ * catalog's); a server of the user's own in read only exposes nothing, like its tools.+ *+ * Answers are plain `application/json` over POST, like the desktop app's computer helper: no event+ * streams (GET is 405) and notifications get 202.+ */+import { randomBytes, timingSafeEqual } from "node:crypto";+import type { IncomingMessage, ServerResponse } from "node:http";+import { homedir } from "node:os";+import { join, resolve } from "node:path";+import {+ type AuthProvider,+ JSON_RPC_ERROR_CODES,+ LATEST_PROTOCOL_VERSION,+ McpAuthRequiredError,+ McpClient,+ McpError,+ type McpTransport,+ StdioTransport,+ StreamableHttpTransport,+ SUPPORTED_PROTOCOL_VERSIONS,+ type Tool,+} from "@earendil-works/pi-mcp";+import { McpOAuthAuthorizationRequiredError } from "@earendil-works/pi-mcp/oauth";+import { type ConnectorMode, isReadOnlyTool } from "./extensions/approval-guard.ts";++/** Where the engine reaches a connector: `/mcp/<id>`. */+export const MCP_PREFIX = "/mcp/";++/** A connector as the proxy sees it: the daemon's live state, without any secret. */+export interface ProxiedConnector {+ id: string;+ name: string;+ enabled: boolean;+ mode: ConnectorMode;+ /** The curated read-only tools (empty for a server of the user's own). */+ readOnlyTools: readonly string[];+ /** The real server: its address, or the command the daemon runs. Secrets come from the credentials. */+ server: { url: string } | { command: string; args?: string[]; cwd?: string };+ /** Changes whenever the server or its values change, so the connection to it is made again. */+ revision: string;+}++/** What the daemon adds to the real server's requests: headers and tokens, or a stdio server's environment. */+export interface UpstreamCredentials {+ headers?: Record<string, string>;+ env?: Record<string, string>;+ authProvider?: AuthProvider;+}++/** What the user approves before a sending action is forwarded: everything that will be sent. */+export interface ApprovalPreview {+ connectorId: string;+ /** The connector's name, as the user knows it. */+ connector: string;+ tool: string;+ arguments: Record<string, unknown>;+}++export interface McpProxyOptions {+ /** The connector's current state, read on every request. */+ connector(id: string): ProxiedConnector | undefined;+ credentials(id: string): Promise<UpstreamCredentials>;+ /** Asks the user; false or a failure refuses the action. The signal aborts when the engine gave up. */+ approve(preview: ApprovalPreview, signal: AbortSignal): Promise<boolean>;+ /** The transport to the real server; by default streamable HTTP or stdio, from the server. */+ transport?: (connector: ProxiedConnector, credentials: UpstreamCredentials) => McpTransport;+ /** The environment stdio servers start from (the engine's own), and their working folder. */+ env?: NodeJS.ProcessEnv;+ cwd?: string;+ log?: (line: string) => void;+}++/** JSON-RPC errors the proxy answers with itself; `message` is safe to show and tells the model what to do. */+class ProxyError extends Error {+ readonly code: number;+ constructor(code: number, message: string) {+ super(message);+ this.code = code;+ }+}++const UNAUTHORIZED = -32001;+/** Refusals and upstream failures (the JSON-RPC server-error range). */+const REFUSED = -32000;+const MAX_BODY = 8 * 1024 * 1024;+/** A tool call may wait for the user's approval and then the server: just under the engine's 300 s. */+const CALL_TIMEOUT_MS = 290_000;+const REQUEST_TIMEOUT_MS = 60_000;++interface Upstream {+ client: McpClient;+ revision: string;+ connecting: Promise<void>;+ /** The tools from the last list, for their annotations. */+ tools?: Tool[];+}++type Message = { jsonrpc?: unknown; id?: unknown; method?: unknown; params?: unknown };++export class McpProxy {+ private key = "";+ private readonly upstreams = new Map<string, Upstream>();+ /** Requests being answered, by connector and request id, so a `notifications/cancelled` stops them. */+ private readonly running = new Map<string, AbortController>();+ private readonly options: McpProxyOptions;++ constructor(options: McpProxyOptions) {+ this.options = options;+ }++ /** A fresh key for the next engine launch; the previous one stops working at once. */+ rotateKey(): string {+ this.key = randomBytes(32).toString("base64url");+ return this.key;+ }++ /** Answers one HTTP request to `/mcp/<id>`. */+ handle(req: IncomingMessage, res: ServerResponse): void {+ void this.serve(req, res).catch((error: Error) => {+ this.log(`connector proxy request failed: ${error.message}`);+ if (!res.headersSent) res.writeHead(500).end();+ });+ }++ /** Closes the connection of every connector that is gone, turned off, or whose server changed. */+ sync(): void {+ for (const [id, upstream] of this.upstreams) {+ const connector = this.options.connector(id);+ if (!connector?.enabled || connector.revision !== upstream.revision) this.drop(id, upstream);+ }+ }++ async close(): Promise<void> {+ for (const controller of this.running.values()) controller.abort();+ const closing = [...this.upstreams.values()].map((upstream) => upstream.client.close().catch(() => {}));+ this.upstreams.clear();+ await Promise.all(closing);+ }++ private async serve(req: IncomingMessage, res: ServerResponse): Promise<void> {+ res.setHeader("Cache-Control", "no-store");+ res.setHeader("X-Content-Type-Options", "nosniff");+ // Only the engine calls here; a page in a browser never may, even with the key.+ if (req.headers.origin !== undefined) return this.empty(req, res, 403);+ if (!this.authorized(req.headers.authorization))+ return this.reply(req, res, 401, null, { error: { code: UNAUTHORIZED, message: "Unauthorized" } });+ const url = new URL(req.url ?? "/", "http://localhost");+ const id = url.pathname.slice(MCP_PREFIX.length);+ if (req.method !== "POST") return this.empty(req, res, 405);+ const body = await readBody(req);+ if (body === undefined) return this.empty(req, res, 413);+ let message: Message;+ try {+ message = JSON.parse(body) as Message;+ } catch {+ return this.reply(req, res, 400, null, {+ error: { code: JSON_RPC_ERROR_CODES.parseError, message: "Parse error" },+ });+ }+ if (typeof message !== "object" || message === null || Array.isArray(message))+ return this.reply(req, res, 400, null, {+ error: { code: JSON_RPC_ERROR_CODES.invalidRequest, message: "Invalid request" },+ });+ const rpcId = message.id;+ // Notifications and responses get no reply; a cancellation stops the request it names.+ if (typeof message.method !== "string" || (typeof rpcId !== "string" && typeof rpcId !== "number")) {+ if (message.method === "notifications/cancelled") {+ const cancelled = (message.params as { requestId?: unknown } | undefined)?.requestId;+ this.running.get(`${id}\u0000${String(cancelled)}`)?.abort();+ }+ return this.empty(req, res, 202);+ }+ const connector = this.options.connector(id);+ if (!connector)+ return this.reply(req, res, 404, rpcId, {+ error: { code: REFUSED, message: "That connector does not exist." },+ });+ const controller = new AbortController();+ const key = `${id}\u0000${String(rpcId)}`;+ this.running.set(key, controller);+ // The engine gave up (its timeout, or the user stopped the answer): nothing is forwarded after that.+ res.on("close", () => {+ if (!res.writableFinished) controller.abort();+ });+ try {+ const result = await this.dispatch(+ connector,+ message.method,+ asRecord(message.params),+ controller.signal,+ );+ this.reply(req, res, 200, rpcId, { result });+ } catch (error) {+ this.reply(req, res, 200, rpcId, { error: this.rpcError(connector, error) });+ } finally {+ if (this.running.get(key) === controller) this.running.delete(key);+ }+ }++ private async dispatch(+ connector: ProxiedConnector,+ method: string,+ params: Record<string, unknown>,+ signal: AbortSignal,+ ): Promise<unknown> {+ if (method === "ping") return {};+ if (!connector.enabled)+ throw new ProxyError(+ REFUSED,+ `${connector.name} is turned off. If the user wants it, ask them to turn it on in Connectors.`,+ );+ const reads = readsAllowed(connector);+ switch (method) {+ case "initialize": {+ const asked = params.protocolVersion;+ const versions: readonly string[] = SUPPORTED_PROTOCOL_VERSIONS;+ return {+ protocolVersion:+ typeof asked === "string" && versions.includes(asked) ? asked : LATEST_PROTOCOL_VERSION,+ capabilities: {+ tools: { listChanged: false },+ ...(reads ? { resources: { listChanged: false }, prompts: { listChanged: false } } : {}),+ },+ serverInfo: { name: `gentle-dot-${connector.id}`, version: "1.0.0" },+ };+ }+ case "tools/list": {+ const tools = await this.listTools(connector, signal);+ return { tools: tools.filter((tool) => visible(connector, tool)) };+ }+ case "tools/call":+ return this.callTool(connector, params, signal);+ case "resources/list":+ if (!reads) return { resources: [] };+ return { resources: await this.all(connector, (c) => c.listResources({ signal })) };+ case "resources/templates/list":+ if (!reads) return { resourceTemplates: [] };+ return {+ resourceTemplates: await this.all(connector, (c) => c.listResourceTemplates({ signal })),+ };+ case "prompts/list":+ if (!reads) return { prompts: [] };+ return { prompts: await this.all(connector, (c) => listPrompts(c, signal)) };+ case "resources/read":+ case "prompts/get": {+ if (!reads) throw new ProxyError(JSON_RPC_ERROR_CODES.invalidParams, notAvailable(connector));+ const upstream = await this.upstream(connector);+ return await upstream.client.request(method, params, { signal, timeoutMs: REQUEST_TIMEOUT_MS });+ }+ default:+ throw new ProxyError(JSON_RPC_ERROR_CODES.methodNotFound, `Method not found: ${method}`);+ }+ }++ private async callTool(+ connector: ProxiedConnector,+ params: Record<string, unknown>,+ signal: AbortSignal,+ ): Promise<unknown> {+ const name = params.name;+ if (typeof name !== "string")+ throw new ProxyError(JSON_RPC_ERROR_CODES.invalidParams, "Invalid params: `name` is required");+ const args = asRecord(params.arguments);+ const upstream = await this.upstream(connector);+ // The annotations come from the server's own list, never from the caller.+ let tool = upstream.tools?.find((t) => t.name === name);+ if (!tool) tool = (await this.listTools(connector, signal)).find((t) => t.name === name);+ if (!tool) throw new ProxyError(JSON_RPC_ERROR_CODES.invalidParams, `Unknown tool: ${name}`);+ refuseHidden(connector, tool);+ if (!isReadOnlyTool(tool.name, tool.annotations?.readOnlyHint, connector.readOnlyTools)) {+ const preview: ApprovalPreview = {+ connectorId: connector.id,+ connector: connector.name,+ tool: tool.name,+ arguments: args,+ };+ let allowed = false;+ try {+ allowed = await this.options.approve(preview, signal);+ } catch (error) {+ this.log(`the approval for ${connector.id} could not be asked: ${(error as Error).message}`);+ throw new ProxyError(+ REFUSED,+ "This action needs the user's approval, and it could not be asked right now. Nothing was sent.",+ );+ }+ if (signal.aborted) throw new ProxyError(REFUSED, "The request was cancelled. Nothing was sent.");+ if (!allowed)+ throw new ProxyError(+ REFUSED,+ "The user did not allow this action, so nothing was sent. Do not try it again unless the user asks.",+ );+ // The user may have changed the connector while the card was open.+ const now = this.options.connector(connector.id);+ if (!now?.enabled || now.revision !== connector.revision)+ throw new ProxyError(+ REFUSED,+ `${connector.name} changed while the user was asked. Nothing was sent.`,+ );+ refuseHidden(now, tool);+ }+ const current = await this.upstream(connector);+ return await current.client.callTool(name, args, { signal, timeoutMs: CALL_TIMEOUT_MS });+ }++ private async listTools(connector: ProxiedConnector, signal: AbortSignal): Promise<Tool[]> {+ const upstream = await this.upstream(connector);+ const tools = await upstream.client.listTools({ signal, timeoutMs: REQUEST_TIMEOUT_MS });+ upstream.tools = tools;+ return tools;+ }++ /** A list method; a server that does not have it has an empty list. */+ private async all<T>(connector: ProxiedConnector, list: (client: McpClient) => Promise<T[]>): Promise<T[]> {+ const upstream = await this.upstream(connector);+ try {+ return await list(upstream.client);+ } catch (error) {+ if (error instanceof McpError && error.code === JSON_RPC_ERROR_CODES.methodNotFound) return [];+ throw error;+ }+ }++ /** The connection to the connector's server, made when it is first needed and again after it failed. */+ private async upstream(connector: ProxiedConnector): Promise<Upstream> {+ let upstream = this.upstreams.get(connector.id);+ if (+ upstream &&+ (upstream.revision !== connector.revision || upstream.client.connectionState === "closed")+ ) {+ this.drop(connector.id, upstream);+ upstream = undefined;+ }+ if (!upstream) {+ const client = new McpClient({+ name: "gentle-dot",+ version: "1.0.0",+ requestTimeoutMs: REQUEST_TIMEOUT_MS,+ });+ const created: Upstream = {+ client,+ revision: connector.revision,+ connecting: (async () => {+ const credentials = await this.options.credentials(connector.id);+ await client.connect(this.transport(connector, credentials));+ })(),+ };+ client.onClose(() => {+ if (this.upstreams.get(connector.id) === created) this.upstreams.delete(connector.id);+ });+ this.upstreams.set(connector.id, created);+ upstream = created;+ }+ try {+ await upstream.connecting;+ } catch (error) {+ this.drop(connector.id, upstream);+ throw error;+ }+ return upstream;+ }++ private transport(connector: ProxiedConnector, credentials: UpstreamCredentials): McpTransport {+ if (this.options.transport) return this.options.transport(connector, credentials);+ const { server } = connector;+ if ("url" in server)+ return new StreamableHttpTransport({+ url: server.url,+ ...(credentials.headers ? { headers: credentials.headers } : {}),+ ...(credentials.authProvider ? { authProvider: credentials.authProvider } : {}),+ // Nothing listens for the server's own messages.+ openGetStream: false,+ });+ const cwd = this.options.cwd ?? process.cwd();+ return new StdioTransport({+ command: expandHome(server.command),+ ...(server.args ? { args: server.args.map(expandHome) } : {}),+ cwd: resolve(cwd, expandHome(server.cwd ?? ".")),+ env: { ...stringEnv(this.options.env ?? process.env), ...credentials.env },+ inheritEnv: false,+ stderr: "pipe",+ });+ }++ private drop(id: string, upstream: Upstream): void {+ if (this.upstreams.get(id) === upstream) this.upstreams.delete(id);+ void upstream.client.close().catch(() => {});+ }++ private rpcError(connector: ProxiedConnector, error: unknown): { code: number; message: string } {+ if (error instanceof ProxyError) return { code: error.code, message: error.message };+ // The server's own answer, passed on as it came.+ if (error instanceof McpError) return { code: error.code, message: error.message };+ const upstream = this.upstreams.get(connector.id);+ if (upstream) this.drop(connector.id, upstream);+ if (error instanceof McpOAuthAuthorizationRequiredError || error instanceof McpAuthRequiredError) {+ this.log(`connector ${connector.id} needs a new sign-in`);+ return {+ code: REFUSED,+ message: `${connector.name} needs the user to sign in again. Ask them to sign in to ${connector.name} in Connectors.`,+ };+ }+ const detail = ((error as Error)?.message ?? String(error)).replace(/https?:\/\/\S+/g, "[address]");+ this.log(`could not reach connector ${connector.id}: ${detail.slice(0, 200)}`);+ return { code: REFUSED, message: `Could not reach ${connector.name} right now. Try again in a moment.` };+ }++ private authorized(header: string | undefined): boolean {+ const given = /^Bearer\s+(\S+)\s*$/i.exec(header ?? "")?.[1];+ if (!given || !this.key) return false;+ const a = Buffer.from(given);+ const b = Buffer.from(this.key);+ return a.length === b.length && timingSafeEqual(a, b);+ }++ private reply(+ req: IncomingMessage,+ res: ServerResponse,+ status: number,+ id: unknown,+ body: { result?: unknown; error?: { code: number; message: string } },+ ): void {+ req.resume();+ if (res.headersSent || res.destroyed) return;+ res.writeHead(status, { "Content-Type": "application/json" });+ res.end(JSON.stringify({ jsonrpc: "2.0", id: id ?? null, ...body }));+ }++ private empty(req: IncomingMessage, res: ServerResponse, status: number): void {+ req.resume();+ if (res.headersSent || res.destroyed) return;+ res.writeHead(status).end();+ }++ private log(line: string): void {+ this.options.log?.(line);+ }+}++/** Reads like resources and prompts: in "read and send", or in read only for a connector with a curated list. */+function readsAllowed(connector: ProxiedConnector): boolean {+ return connector.enabled && (connector.mode === "read_write" || connector.readOnlyTools.length > 0);+}++/** Read only shows only read-only tools; "read and send" shows all of them. */+function visible(connector: ProxiedConnector, tool: Tool): boolean {+ return (+ connector.mode === "read_write" ||+ isReadOnlyTool(tool.name, tool.annotations?.readOnlyHint, connector.readOnlyTools)+ );+}++function refuseHidden(connector: ProxiedConnector, tool: Tool): void {+ if (visible(connector, tool)) return;+ throw new ProxyError(+ JSON_RPC_ERROR_CODES.invalidParams,+ `${connector.name} is set to read only, so ${tool.name} is not available and nothing was sent. If the user wants it, ask them to switch ${connector.name} to "Read and send" in Connectors.`,+ );+}++function notAvailable(connector: ProxiedConnector): string {+ return `${connector.name} is set to read only, so this is not available. If the user wants it, ask them to switch ${connector.name} to "Read and send" in Connectors.`;+}++/** Every prompt, following `nextCursor` (pi-mcp's client has no helper for prompts). */+async function listPrompts(client: McpClient, signal: AbortSignal): Promise<unknown[]> {+ const prompts: unknown[] = [];+ let cursor: string | undefined;+ do {+ const page = await client.request<{ prompts?: unknown[]; nextCursor?: string }>(+ "prompts/list",+ cursor ? { cursor } : {},+ { signal, timeoutMs: REQUEST_TIMEOUT_MS },+ );+ prompts.push(...(page.prompts ?? []));+ cursor = page.nextCursor;+ } while (cursor);+ return prompts;+}++function asRecord(value: unknown): Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : {};+}++/** The body, or undefined when it is larger than the limit. */+async function readBody(req: IncomingMessage): Promise<string | undefined> {+ const chunks: Buffer[] = [];+ let size = 0;+ for await (const chunk of req) {+ size += (chunk as Buffer).length;+ if (size > MAX_BODY) return undefined;+ chunks.push(chunk as Buffer);+ }+ return Buffer.concat(chunks).toString("utf8");+}++function stringEnv(env: NodeJS.ProcessEnv): Record<string, string> {+ return Object.fromEntries(+ Object.entries(env).filter((entry): entry is [string, string] => typeof entry[1] === "string"),+ );+}++/** `~` and `~/…` name the home folder, as the engine reads a server's command. */+function expandHome(value: string): string {+ if (value === "~") return homedir();+ return value.startsWith("~/") ? join(homedir(), value.slice(2)) : value;+}diff --git a/packages/daemon/test/computer.test.ts b/packages/daemon/test/computer.test.tsindex 7a0926a..bd721da 100644--- a/packages/daemon/test/computer.test.ts+++ b/packages/daemon/test/computer.test.ts@@ -63,7 +63,10 @@ async function setup(options: Setup = {}) {existsSync(mcpFile) ? JSON.parse(readFileSync(mcpFile, "utf8")).mcpServers : {};const agentEnv = () => readFileSync(envFile, "utf8");const policy = () =>- JSON.parse(JSON.parse(agentEnv()).GENTLE_DOT_CONNECTOR_POLICY ?? "{}") as { builtin?: string[] };+ JSON.parse(JSON.parse(agentEnv()).GENTLE_DOT_CONNECTOR_POLICY ?? "{}") as {+ builtin?: string[];+ connectors?: Record<string, { mode: string }>;+ };return {d,dataDir,@@ -231,7 +234,7 @@ describe("computer control registration (S24.7)", () => {});it("cannot be changed or removed through the connector messages, and a saved connector with its name is renamed", async () => {- const { servers, send, messages, list } = await setup({+ const { d, servers, send, messages, list } = await setup({saved: {version: 1,connectors: {@@ -249,7 +252,8 @@ describe("computer control registration (S24.7)", () => {name: "Computer",enabled: true,});- expect(servers()["computer-2"]).toMatchObject({ url: "http://127.0.0.1:9/mcp" });+ // The engine reaches it through the proxy; its real address stays in the daemon.+ expect(servers()["computer-2"]).toMatchObject({ url: `http://127.0.0.1:${d.port}/mcp/computer-2` });send({ type: "computer_register", url: HELPER, token: KEY });await waitFor(() => servers().computer);@@ -323,7 +327,7 @@ describe("computer control registration (S24.7)", () => {describe("connectors next to the computer (regression)", () => {it("connects, changes, and removes a connector while the helper is registered, and puts back a tampered mcp.json", async () => {- const { mcpFile, servers, send, find, list } = await setup({ cliMode: "auto" });+ const { d, mcpFile, servers, send, find, list, policy } = await setup({ cliMode: "auto" });send({ type: "computer_register", url: HELPER, token: KEY });await waitFor(() => servers().computer);@@ -340,10 +344,13 @@ describe("connectors next to the computer (regression)", () => {["computer", "connected"],]);expect(Object.keys(servers())).toEqual(["notion", "computer"]);- expect(servers().notion).toMatchObject({ url: "https://mcp.notion.com/mcp", exposure: "direct" });+ expect(servers().notion).toMatchObject({+ url: `http://127.0.0.1:${d.port}/mcp/notion`,+ exposure: "direct",+ });send({ type: "connector_mode", connectorId: "notion", mode: "read_write" });- await waitFor(() => !(servers().notion as { toolExposure?: unknown }).toolExposure);+ await waitFor(() => d.supervisor.state === "ready" && policy().connectors?.notion?.mode === "read_write");writeFileSync(mcpFile, '{"mcpServers":{}}\n');await waitFor(() => servers().computer && servers().notion);diff --git a/packages/daemon/test/connector-draft-probe.test.ts b/packages/daemon/test/connector-draft-probe.test.tsindex 331dc5c..35501d5 100644--- a/packages/daemon/test/connector-draft-probe.test.ts+++ b/packages/daemon/test/connector-draft-probe.test.ts@@ -238,6 +238,7 @@ describe.skipIf(!enabled)("@real-agent T18b connector probe", () => {imports: scan.found,engineList,mcpJson: JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8")),+ signinMcpJson: JSON.parse(readFileSync(join(dataDir, "connector-signin", "mcp.json"), "utf8")),toolsOfferedLast: lastTools.filter((name) => name.startsWith("mcp__") || name === "propose_connector",),@@ -257,10 +258,12 @@ describe.skipIf(!enabled)("@real-agent T18b connector probe", () => {expect(byName.discord).toMatchObject({ enabled: false, state: "disabled" });expect(byName["probe-tools"]).toMatchObject({ enabled: true, state: "connected" });expect(byName.imported).toMatchObject({ enabled: true, state: "connected" });- expect(byName["probe-tools"]?.tools).toContain("send_message");- // Read only with no curated list: the model sees none of their tools.+ // Read only with no curated list: the proxy shows none of their tools (S25.4).+ expect(byName["probe-tools"]?.tools).toEqual([]);expect(lastTools.filter((name) => /^mcp__(probe_tools|imported)__/.test(name))).toEqual([]);- expect(summary.mcpJson.mcpServers.discord.env.DISCORD_TOKEN).not.toBe("dummy-token-$!x");+ // The engine's mcp.json holds only proxy addresses; the real servers are in the sign-in home.+ expect(JSON.stringify(summary.mcpJson)).not.toContain("DISCORD_TOKEN");+ expect(summary.signinMcpJson.mcpServers.discord.env.DISCORD_TOKEN).not.toBe("dummy-token-$!x");} finally {if (child.exitCode === null) child.kill("SIGTERM");await exited;diff --git a/packages/daemon/test/connector-drafts.test.ts b/packages/daemon/test/connector-drafts.test.tsindex ad99c94..e0bdb13 100644--- a/packages/daemon/test/connector-drafts.test.ts+++ b/packages/daemon/test/connector-drafts.test.ts@@ -234,7 +234,7 @@ describe("connector drafts", () => {});it("on approval asks for each secret in the app, then adds the server read only with every tool hidden", async () => {- const { manager, store, owner, emit, sent, prompts, agentHome, logs, changes } = setup();+ const { manager, store, owner, emit, sent, prompts, logs, changes } = setup();const draft = manager.propose(JSON.stringify(stdioDraft));expect(manager.decideDraft(owner, draft?.draftId ?? "", true, emit)).toBeUndefined();const prompt = await waitFor(() => prompts()[0]);@@ -250,7 +250,7 @@ describe("connector drafts", () => {mode: "read_only",values: { GITHUB_PERSONAL_ACCESS_TOKEN: SECRET },});- const server = JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8")).mcpServers.github;+ const server = JSON.parse(readFileSync(store.signinMcpFile, "utf8")).mcpServers.github;expect(server).toMatchObject({command: "npx",args: ["-y", "@modelcontextprotocol/[email protected]"],@@ -281,8 +281,9 @@ describe("connector drafts", () => {// Read and send shows every tool, and each call asks (no curated list).manager.setMode("github", "read_write");expect(- JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8")).mcpServers.github.toolExposure,+ JSON.parse(readFileSync(store.signinMcpFile, "utf8")).mcpServers.github.toolExposure,).toBeUndefined();+ expect(store.proxyView("github")).toMatchObject({ mode: "read_write", readOnlyTools: [] });});it("gives a draft with a taken name its own id, and signs in when it needs OAuth", async () => {@@ -381,10 +382,15 @@ describe("connector drafts through the daemon", () => {),);expect(- JSON.parse(readFileSync(join(dataDir, "agent", "mcp.json"), "utf8")).mcpServers.github.toolExposure,+ JSON.parse(readFileSync(join(dataDir, "connector-signin", "mcp.json"), "utf8")).mcpServers.github+ .toolExposure,).toEqual({"*": "hidden",});+ // The engine reaches it only through the proxy.+ expect(+ JSON.parse(readFileSync(join(dataDir, "agent", "mcp.json"), "utf8")).mcpServers.github.url,+ ).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/mcp\/github$/);first.ws.close();second.ws.close();});diff --git a/packages/daemon/test/connector-import.test.ts b/packages/daemon/test/connector-import.test.tsindex 4532c1a..3446c86 100644--- a/packages/daemon/test/connector-import.test.ts+++ b/packages/daemon/test/connector-import.test.ts@@ -294,7 +294,7 @@ describe("importing MCP servers", () => {"perplexity","stripe",]);- const mcp = JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8")).mcpServers as Record<+ const mcp = JSON.parse(readFileSync(store.signinMcpFile, "utf8")).mcpServers as Record<string,Record<string, unknown>>;@@ -342,8 +342,11 @@ describe("importing MCP servers", () => {expect(prompt).toMatchObject({ kind: "secret", message: expect.stringContaining("Perplexity API Key") });manager.reply(owner, prompt.flowId, { value: "pplx-typed" });await waitFor(() => sent.find((m) => m.type === "auth_done"));- const perplexity = JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8")).mcpServers.perplexity;+ const perplexity = JSON.parse(readFileSync(store.signinMcpFile, "utf8")).mcpServers.perplexity;expect(resolveConfigValue(perplexity.env.PERPLEXITY_API_KEY)).toBe("pplx-typed");+ // The proxy hands the server what was typed, and what it reads from the environment.+ expect((await store.credentials("perplexity")).env).toEqual({ PERPLEXITY_API_KEY: "pplx-typed" });+ expect(readFileSync(join(agentHome, "mcp.json"), "utf8")).not.toContain("pplx-typed");expect(JSON.stringify(sent)).not.toContain("pplx-typed");// Importing again adds nothing: they are already connectors.const again = manager.scan();diff --git a/packages/daemon/test/connector-probe.test.ts b/packages/daemon/test/connector-probe.test.tsindex 47fbc15..dd9a524 100644--- a/packages/daemon/test/connector-probe.test.ts+++ b/packages/daemon/test/connector-probe.test.ts@@ -227,8 +227,9 @@ describe.skipIf(!enabled)("@real-agent connector probe", () => {version: 1,connectors: { notion: { enabled: false, mode: "read_only" } },});+ // The engine reaches Notion only through the daemon's proxy (S25.4), and it stays off.expect(JSON.parse(summary.mcpJson).mcpServers.notion).toMatchObject({- url: "https://mcp.notion.com/mcp",+ url: expect.stringMatching(/^http:\/\/127\.0\.0\.1:\d+\/mcp\/notion$/),exposure: "direct",enabled: false,});diff --git a/packages/daemon/test/connectors-gateway.test.ts b/packages/daemon/test/connectors-gateway.test.tsindex 2dd75c1..50ed507 100644--- a/packages/daemon/test/connectors-gateway.test.ts+++ b/packages/daemon/test/connectors-gateway.test.ts@@ -11,6 +11,9 @@ import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";const FAKE_CLI = fileURLToPath(new URL("./fixtures/fake-mcp-cli.ts", import.meta.url));const GUARD = fileURLToPath(new URL("../src/extensions/approval-guard.ts", import.meta.url));+/** The engine's mcp.json without the proxy key, which changes with every engine launch. */+const withoutKey = (text: string) => text.replace(/Bearer [^"]+/g, "Bearer <key>");+const daemons: DotDaemon[] = [];afterEach(async () => {await Promise.all(daemons.splice(0).map((d) => d.close()));@@ -149,7 +152,8 @@ describe("connectors over the protocol", () => {const approved = readFileSync(file, "utf8");writeFileSync(file, JSON.stringify({ mcpServers: { evil: { command: "sh", args: ["-c", "id"] } } }));await d.supervisor.restart();- expect(readFileSync(file, "utf8")).toBe(approved);+ expect(withoutKey(readFileSync(file, "utf8"))).toBe(withoutKey(approved));+ expect(readFileSync(file, "utf8")).not.toBe(approved);expect(logs.some((l) => l.includes("put back"))).toBe(true);});@@ -170,8 +174,9 @@ describe("connectors over the protocol", () => {// The new engine got the user's state, not the edited files.const policy = JSON.parse(agentEnv().GENTLE_DOT_CONNECTOR_POLICY ?? "{}");expect(policy.connectors).toEqual({});+ expect(policy.proxied).toEqual([]);expect(readFileSync(join(dataDir, "connectors.json"), "utf8")).toBe(approved.connectors);- expect(readFileSync(join(agentHome, "mcp.json"), "utf8")).toBe(approved.mcp);+ expect(withoutKey(readFileSync(join(agentHome, "mcp.json"), "utf8"))).toBe(withoutKey(approved.mcp));expect(existsSync(join(dataDir, "workspace", ".pi", "mcp.json"))).toBe(false);await find("toast", (m) => m.message === "A change to your connectors was blocked.");send({ type: "connectors_list" });diff --git a/packages/daemon/test/connectors-guided.test.ts b/packages/daemon/test/connectors-guided.test.tsindex 89a81f8..8e54fc5 100644--- a/packages/daemon/test/connectors-guided.test.ts+++ b/packages/daemon/test/connectors-guided.test.ts@@ -6,7 +6,7 @@ import { join } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";import type { ServerPayload } from "@gentle-dot/protocol";import { afterEach, describe, expect, it } from "vitest";-import { CATALOG, ConnectorManager, ConnectorStore, renderMcpJson } from "../src/connectors.ts";+import { CATALOG, ConnectorManager, ConnectorStore, renderSigninMcpJson } from "../src/connectors.ts";import { tempDir, waitFor } from "./helpers.ts";const FAKE_CLI = fileURLToPath(new URL("./fixtures/fake-mcp-cli.ts", import.meta.url));@@ -124,11 +124,11 @@ describe("guided catalog entries", () => {});});-describe("guided mcp.json rendering", () => {+describe("guided mcp.json rendering (the sign-in home)", () => {it("puts typed values in as literals the engine does not run or expand, and hides unknown tools", async () => {const [{ validateMcpServerConfig, getMcpToolExposure }, { resolveConfigValue }] = await engine();const rendered = JSON.parse(- renderMcpJson({+ renderSigninMcpJson({connectors: {discord: { enabled: true, mode: "read_only", values: { token: TOKEN } },slack: { enabled: true, mode: "read_write", values: { client_id: "123.456", client_secret: "" } },@@ -165,7 +165,7 @@ describe("guided mcp.json rendering", () => {it("leaves out a guided connector whose required values are missing", () => {const rendered = JSON.parse(- renderMcpJson({ connectors: { discord: { enabled: true, mode: "read_only" } } }),+ renderSigninMcpJson({ connectors: { discord: { enabled: true, mode: "read_only" } } }),) as { mcpServers: Record<string, unknown> };expect(rendered.mcpServers).toEqual({});});@@ -232,7 +232,10 @@ describe("guided connector setup", () => {expect(JSON.stringify(manager.list())).not.toContain(TOKEN);expect(JSON.stringify(sent)).not.toContain(TOKEN);expect(logs.join("\n")).not.toContain(TOKEN);- expect(readFileSync(join(agentHome, "mcp.json"), "utf8")).toContain("DISCORD_TOKEN");+ // The real server is only in the daemon's sign-in home; the proxy hands the token to the server it runs.+ expect(readFileSync(store.signinMcpFile, "utf8")).toContain("DISCORD_TOKEN");+ expect(readFileSync(join(agentHome, "mcp.json"), "utf8")).not.toContain("DISCORD_TOKEN");+ expect((await store.credentials("discord")).env).toEqual({ DISCORD_TOKEN: TOKEN });expect(readFileSync(join(dataDir, "connectors.json"), "utf8")).toContain("discord");expect(store.policy().connectors?.discord?.readOnlyTools).toContain("discord_read_messages");});@@ -249,7 +252,7 @@ describe("guided connector setup", () => {});it("asks for Slack's client id and an optional secret, writes them to mcp.json, then signs in on the same flow", async () => {- const { manager, store, owner, emit, sent, prompts, agentHome, cliRuns, logs } = setup({+ const { manager, store, owner, emit, sent, prompts, cliRuns, logs } = setup({FAKE_MCP_CLI_MODE: "auto",FAKE_MCP_CLI_URL: "https://mcp.slack.com/mcp",});@@ -264,7 +267,7 @@ describe("guided connector setup", () => {const done = await waitFor(() => sent.find((m) => m.type === "auth_done"));expect(done).toMatchObject({ flowId: first.flowId, providerId: "slack", ok: true });expect(cliRuns().map((r) => r.argv)).toEqual([["mcp", "login", "slack"]]);- const slack = JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8")).mcpServers.slack;+ const slack = JSON.parse(readFileSync(store.signinMcpFile, "utf8")).mcpServers.slack;expect(slack.oauth).toMatchObject({clientId: "123.456",callbackUrl: "http://localhost:38417/callback",diff --git a/packages/daemon/test/connectors-proxy-gateway.test.ts b/packages/daemon/test/connectors-proxy-gateway.test.tsnew file mode 100644index 0000000..3aed691--- /dev/null+++ b/packages/daemon/test/connectors-proxy-gateway.test.ts@@ -0,0 +1,221 @@+// The MCP proxy inside the daemon, end to end with the fake agent (S25.4): the engine's mcp.json+// leads to the daemon, a read-only call runs without a card, a sending action asks once on the+// ask-card path, and a declined one never reaches the server.+import { readFileSync } from "node:fs";+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { McpClient, McpError, StreamableHttpTransport, type Tool } from "@earendil-works/pi-mcp";+import type { ServerMessage } from "@gentle-dot/protocol";+import { afterEach, describe, expect, it } from "vitest";+import WebSocket from "ws";+import { type DotDaemon, startDaemon } from "../src/daemon.ts";+import { fakeAuthRuntime } from "./fake-auth-runtime.ts";+import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";++const FAKE_CLI = fileURLToPath(new URL("./fixtures/fake-mcp-cli.ts", import.meta.url));+/** What the fake sign-in command stores (see fixtures/fake-mcp-cli.ts). */+const SIGNED_IN_TOKEN = "fake-access-token-value";++const TOOLS: Tool[] = [+ { name: "notion-search", inputSchema: { type: "object" }, annotations: { readOnlyHint: true } },+ { name: "notion-create-pages", inputSchema: { type: "object" } },+];++type Rec = Record<string, unknown>;++const daemons: DotDaemon[] = [];+const closers: (() => Promise<unknown>)[] = [];+afterEach(async () => {+ await Promise.all(closers.splice(0).map((close) => close().catch(() => undefined)));+ await Promise.all(daemons.splice(0).map((d) => d.close()));+});++/** Notion's server, as far as the proxy can tell: plain JSON over HTTP, recording every request. */+async function fakeNotion() {+ const seen: { authorization?: string; method: string; params?: Rec }[] = [];+ const server: Server = createServer((req, res) => {+ let body = "";+ req.on("data", (chunk: Buffer) => {+ body += chunk.toString("utf8");+ });+ req.on("end", () => {+ if (req.method !== "POST") {+ res.writeHead(405).end();+ return;+ }+ const message = JSON.parse(body) as { id?: number; method: string; params?: Rec };+ seen.push({ authorization: req.headers.authorization, method: message.method, params: message.params });+ if (message.id === undefined) {+ res.writeHead(202).end();+ return;+ }+ const result =+ message.method === "initialize"+ ? {+ protocolVersion: message.params?.protocolVersion,+ capabilities: { tools: {} },+ serverInfo: { name: "notion", version: "1" },+ }+ : message.method === "tools/list"+ ? { tools: TOOLS }+ : { content: [{ type: "text", text: `notion ran ${String(message.params?.name)}` }] };+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }));+ });+ });+ await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));+ closers.push(() => new Promise((done) => server.close(done)));+ const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/mcp`;+ const calls = () => seen.filter((r) => r.method === "tools/call").map((r) => r.params?.name);+ return { url, seen, calls };+}++async function setup() {+ const dataDir = tempDir();+ const agentHome = join(dataDir, "agent");+ const notion = await fakeNotion();+ const fake = fakeAuthRuntime();+ const d = await startDaemon({+ port: 0,+ host: "127.0.0.1",+ dataDir,+ workspace: join(dataDir, "workspace"),+ uiDir: dataDir,+ agentCommand: process.execPath,+ agentArgs: [FAKE_AGENT],+ agentHome,+ backoffMs: [50],+ agentEnv: { ...process.env, FAKE_MCP_CLI_MODE: "auto" },+ authRuntime: async () => fake.runtime,+ connectorCli: { command: process.execPath, args: [FAKE_CLI] },+ // The real credentials, sent to a stand-in for Notion's address.+ connectorTransport: (_connector, credentials) =>+ new StreamableHttpTransport({+ url: notion.url,+ ...(credentials.headers ? { headers: credentials.headers } : {}),+ ...(credentials.authProvider ? { authProvider: credentials.authProvider } : {}),+ openGetStream: false,+ }),+ });+ daemons.push(d);+ const ws = new WebSocket(`ws://127.0.0.1:${d.port}/ws`);+ const messages: ServerMessage[] = [];+ ws.on("message", (data) => messages.push(JSON.parse(String(data)) as ServerMessage));+ await new Promise((resolve) => ws.on("open", resolve));+ closers.push(async () => ws.close());+ ws.send(JSON.stringify({ type: "hello", token: d.token, protocol: 1 }));+ await waitFor(() => messages.some((m) => m.type === "ready"));+ const send = (m: object) => ws.send(JSON.stringify(m));+ const mcpText = () => readFileSync(join(agentHome, "mcp.json"), "utf8");+ /** Connects to a server of the engine's mcp.json exactly as the engine would: its URL and headers. */+ const engineClient = async (id: string) => {+ const entry = JSON.parse(mcpText()).mcpServers[id] as { url: string; headers: Record<string, string> };+ const client = new McpClient({ name: "engine", version: "1" });+ closers.push(() => client.close());+ await client.connect(new StreamableHttpTransport({ url: entry.url, headers: entry.headers }));+ return client;+ };+ const closeWindow = () =>+ new Promise<void>((done) => {+ ws.once("close", () => done());+ ws.close();+ });+ return { d, dataDir, agentHome, notion, messages, send, mcpText, engineClient, closeWindow };+}++describe("connectors through the daemon's proxy (regression, S25.4)", () => {+ it("connects, then a read-only call reaches the server with the stored sign-in and no card", async () => {+ const { d, notion, send, messages, mcpText, engineClient } = await setup();+ const pid = d.supervisor.pid;+ send({ type: "connector_connect", connectorId: "notion" });+ await waitFor(() => messages.find((m) => m.type === "auth_done" && m.ok));+ await waitFor(() => d.supervisor.pid !== pid && d.supervisor.state === "ready");+ await waitFor(() => JSON.parse(mcpText()).mcpServers.notion);+ const text = mcpText();+ expect(JSON.parse(text).mcpServers.notion.url).toBe(`http://127.0.0.1:${d.port}/mcp/notion`);+ expect(text).not.toContain(SIGNED_IN_TOKEN);+ expect(text).not.toContain("mcp.notion.com");+ const client = await engineClient("notion");+ // Read only: only the curated read-only tool.+ expect((await client.listTools()).map((t) => t.name)).toEqual(["notion-search"]);+ expect(await client.callTool("notion-search", { query: "plans" })).toEqual({+ content: [{ type: "text", text: "notion ran notion-search" }],+ });+ expect(notion.calls()).toEqual(["notion-search"]);+ for (const request of notion.seen) expect(request.authorization).toBe(`Bearer ${SIGNED_IN_TOKEN}`);+ expect(messages.some((m) => m.type === "ask")).toBe(false);+ });++ it("asks once before a sending action in read and send, forwards nothing when declined, and runs it when allowed", async () => {+ const { d, notion, send, messages, mcpText, engineClient } = await setup();+ send({ type: "connector_connect", connectorId: "notion" });+ await waitFor(() => messages.find((m) => m.type === "auth_done" && m.ok));+ const pid = d.supervisor.pid;+ send({ type: "connector_mode", connectorId: "notion", mode: "read_write" });+ await waitFor(() => d.supervisor.pid !== pid && d.supervisor.state === "ready");+ const oldKey = JSON.parse(mcpText()).mcpServers.notion.headers.Authorization;+ const client = await engineClient("notion");+ expect((await client.listTools()).map((t) => t.name)).toEqual(["notion-search", "notion-create-pages"]);+ const args = { parent: "Team space", title: "Plan", content: "x".repeat(9000) };++ const declined = client.callTool("notion-create-pages", args);+ const ask = await waitFor(() => messages.find((m) => m.type === "ask"));+ if (ask.type !== "ask") throw new Error("not an ask");+ expect(ask.ask).toMatchObject({ method: "confirm", title: "Allow Notion to create pages?" });+ expect(ask.ask.message).toContain("parent: Team space");+ expect(ask.ask.message).toContain("title: Plan");+ await waitFor(() => d.bridge.agentState === "needs_you");+ send({ type: "ui_response", requestId: ask.ask.requestId, confirmed: false });+ const error = await declined.then(+ () => undefined,+ (e: unknown) => e,+ );+ expect(error).toBeInstanceOf(McpError);+ expect((error as McpError).message).toMatch(/did not allow/);+ expect(notion.calls()).toEqual([]);+ await waitFor(() => messages.find((m) => m.type === "ask_resolved" && m.requestId === ask.ask.requestId));++ const allowed = client.callTool("notion-create-pages", args);+ const second = await waitFor(() =>+ messages.find((m) => m.type === "ask" && m.ask.requestId !== ask.ask.requestId),+ );+ if (second.type !== "ask") throw new Error("not an ask");+ send({ type: "ui_response", requestId: second.ask.requestId, confirmed: true });+ expect(await allowed).toMatchObject({ content: [{ text: "notion ran notion-create-pages" }] });+ expect(notion.calls()).toEqual(["notion-create-pages"]);+ expect(messages.filter((m) => m.type === "ask")).toHaveLength(2);++ // The next engine launch gets a new key; the old one no longer works.+ const restarted = d.supervisor.pid;+ send({ type: "connector_mode", connectorId: "notion", mode: "read_only" });+ await waitFor(() => d.supervisor.pid !== restarted && d.supervisor.state === "ready");+ const newKey = JSON.parse(mcpText()).mcpServers.notion.headers.Authorization;+ expect(newKey).not.toBe(oldKey);+ const stale = await fetch(`http://127.0.0.1:${d.port}/mcp/notion`, {+ method: "POST",+ headers: { authorization: oldKey, "content-type": "application/json" },+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "ping" }),+ });+ expect(stale.status).toBe(401);+ });++ it("refuses a sending action when no window can answer", async () => {+ const { d, notion, send, messages, engineClient, closeWindow } = await setup();+ send({ type: "connector_connect", connectorId: "notion" });+ await waitFor(() => messages.find((m) => m.type === "auth_done" && m.ok));+ const pid = d.supervisor.pid;+ send({ type: "connector_mode", connectorId: "notion", mode: "read_write" });+ await waitFor(() => d.supervisor.pid !== pid && d.supervisor.state === "ready");+ const client = await engineClient("notion");+ await closeWindow();+ await new Promise((resolve) => setTimeout(resolve, 100));+ const error = await client.callTool("notion-create-pages", { title: "x" }).then(+ () => undefined,+ (e: unknown) => e,+ );+ expect((error as McpError).message).toMatch(/approval/);+ expect(notion.calls()).toEqual([]);+ });+});diff --git a/packages/daemon/test/connectors-proxy.test.ts b/packages/daemon/test/connectors-proxy.test.tsnew file mode 100644index 0000000..a6f2663--- /dev/null+++ b/packages/daemon/test/connectors-proxy.test.ts@@ -0,0 +1,351 @@+// biome-ignore-all lint/suspicious/noTemplateCurlyInString: `${input:<key>}` and `${NAME}` are the placeholders connectors use.+// The connector files with the MCP proxy (S25.4): the engine's mcp.json lists only the daemon's+// proxy addresses, the real servers and their secrets stay in the daemon's own sign-in home, and the+// approval guard lets proxied tools through (the proxy asks) while it keeps protecting the files.+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";+import { createRequire } from "node:module";+import { join } from "node:path";+import { pathToFileURL } from "node:url";+import { afterEach, describe, expect, it } from "vitest";+import { ConnectorStore, type CustomConnector, renderMcpJson } from "../src/connectors.ts";+import { decide, parsePolicy } from "../src/extensions/approval-guard.ts";+import { tempDir, waitFor } from "./helpers.ts";++const NOTION_KEY = "mcp__notion|https://mcp.notion.com/mcp";+const KEY = "proxy-key-for-this-launch-0123456789abcdef";+const PROXY = { url: "http://127.0.0.1:4999/mcp", key: KEY };+/** Every secret the files below hold; none may reach the engine's mcp.json. */+const SECRETS = {+ discordToken: "discord-bot-token-value-$weird!",+ slackSecret: "slack-client-secret-value",+ headerToken: "custom-header-token-value",+ envToken: "custom-env-token-value",+ oauthAccess: "oauth-access-token-value",+ oauthRefresh: "oauth-refresh-token-value",+};++async function engineMcp() {+ const require = createRequire(import.meta.url);+ const file = (require.resolve.paths("@earendil-works/pi-coding-agent") ?? [])+ .map((dir) => join(dir, "@earendil-works", "pi-coding-agent", "dist", "core", "mcp-servers.js"))+ .find((path) => existsSync(path));+ if (!file) throw new Error("the engine package is missing");+ return (await import(pathToFileURL(file).href)) as {+ validateMcpServerConfig(name: string, raw: unknown): unknown;+ };+}++const stores: ConnectorStore[] = [];+afterEach(() => {+ for (const s of stores.splice(0)) s.close();+});++function setup(options: { env?: NodeJS.ProcessEnv } = {}) {+ const dataDir = tempDir();+ const agentHome = join(dataDir, "agent");+ const workspace = join(dataDir, "workspace");+ mkdirSync(agentHome);+ mkdirSync(workspace);+ const make = () => {+ const s = new ConnectorStore({+ dataDir,+ agentHome,+ workspace,+ guardPath: "/app/guard.ts",+ ...(options.env ? { env: options.env } : {}),+ });+ stores.push(s);+ return s;+ };+ return { dataDir, agentHome, workspace, make };+}++const httpCustom: CustomConnector = {+ name: "Tracker",+ description: "",+ origin: "Imported from Cursor",+ server: { url: "https://tracker.example.com/mcp", headers: { Authorization: "Bearer ${input:TRACKER}" } },+ fields: [{ key: "TRACKER", label: "TRACKER", secret: true }],+ oauth: false,+};+const stdioCustom: CustomConnector = {+ name: "Files",+ description: "",+ origin: "Drafted by the assistant",+ server: { command: "npx", args: ["-y", "[email protected]"], env: { FILES_TOKEN: "${input:FILES_TOKEN}" } },+ fields: [{ key: "FILES_TOKEN", label: "FILES_TOKEN", secret: true }],+ oauth: false,+};++function fill(s: ConnectorStore) {+ s.update((state) => {+ state.connectors.notion = { enabled: true, mode: "read_only" };+ state.connectors.linear = { enabled: false, mode: "read_write" };+ state.connectors.discord = { enabled: true, mode: "read_write", values: { token: SECRETS.discordToken } };+ state.connectors.slack = {+ enabled: true,+ mode: "read_only",+ values: { client_id: "slack-client-id", client_secret: SECRETS.slackSecret },+ };+ state.connectors.tracker = {+ enabled: true,+ mode: "read_only",+ values: { TRACKER: SECRETS.headerToken },+ custom: httpCustom,+ };+ state.connectors.files = {+ enabled: true,+ mode: "read_write",+ values: { FILES_TOKEN: SECRETS.envToken },+ custom: stdioCustom,+ };+ });+}++describe("the engine's mcp.json with the proxy", () => {+ it("lists every connector as a proxy address with this launch's key, and nothing else", async () => {+ const { validateMcpServerConfig } = await engineMcp();+ const { make, agentHome, dataDir } = setup();+ const s = make();+ s.setProxy(PROXY);+ fill(s);+ writeFileSync(+ s.authFile,+ JSON.stringify({+ [NOTION_KEY]: { tokens: { access_token: SECRETS.oauthAccess, refresh_token: SECRETS.oauthRefresh } },+ }),+ );+ const text = readFileSync(join(agentHome, "mcp.json"), "utf8");+ const servers = JSON.parse(text).mcpServers as Record<string, Record<string, unknown>>;+ expect(Object.keys(servers)).toEqual(["notion", "linear", "discord", "slack", "tracker", "files"]);+ const entry = (id: string) => ({+ url: `http://127.0.0.1:4999/mcp/${id}`,+ headers: { Authorization: `Bearer ${KEY}` },+ exposure: "direct",+ timeout: 300,+ });+ expect(servers.notion).toEqual(entry("notion"));+ expect(servers.linear).toEqual({ ...entry("linear"), enabled: false });+ expect(servers.files).toEqual(entry("files"));+ for (const [name, config] of Object.entries(servers))+ expect(typeof validateMcpServerConfig(name, config)).toBe("object");+ for (const secret of Object.values(SECRETS)) expect(text).not.toContain(secret);+ for (const upstream of [+ "notion.com",+ "linear.app",+ "slack.com",+ "tracker.example.com",+ "npx",+ "discord-mcp",+ ])+ expect(text).not.toContain(upstream);+ for (const name of ["DISCORD_TOKEN", "FILES_TOKEN", "env", "oauth", "toolExposure", "command"])+ expect(text).not.toContain(name);+ // The real servers are only in the daemon's own sign-in home, for the sign-in command.+ expect(s.signinHome).toBe(join(dataDir, "connector-signin"));+ const signin = JSON.parse(readFileSync(s.signinMcpFile, "utf8")).mcpServers;+ expect(signin.notion.url).toBe("https://mcp.notion.com/mcp");+ expect(signin.slack.oauth.clientId).toBe("slack-client-id");+ expect(statSync(s.signinHome).mode & 0o777).toBe(0o700);+ expect(statSync(s.signinMcpFile).mode & 0o777).toBe(0o600);+ });++ it("leaves the connectors out until the proxy listens, keeps the computer helper as it is, and changes the key per launch", () => {+ const { make, agentHome } = setup();+ const s = make();+ s.update((state) => {+ state.connectors.notion = { enabled: true, mode: "read_only" };+ });+ const read = () => JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8")).mcpServers;+ expect(read()).toEqual({});+ s.setComputer({ url: "http://127.0.0.1:5555/mcp", token: "helper-key" });+ expect(s.setProxy(PROXY)).toBe(true);+ expect(s.setProxy(PROXY)).toBe(false);+ expect(read().computer).toEqual({+ url: "http://127.0.0.1:5555/mcp",+ headers: { Authorization: "Bearer helper-key" },+ exposure: "direct",+ timeout: 300,+ });+ expect(read().notion.headers.Authorization).toBe(`Bearer ${KEY}`);+ s.setProxy({ ...PROXY, key: "next-launch-key-0123456789abcdef0123" });+ expect(read().notion.headers.Authorization).toBe("Bearer next-launch-key-0123456789abcdef0123");+ expect(JSON.parse(renderMcpJson({ connectors: {} }, undefined, PROXY))).toEqual({ mcpServers: {} });+ });+});++describe("the proxy's view of a connector and its credentials", () => {+ it("gives the proxy each connector's live state without secrets, and a new revision when its values change", () => {+ const { make } = setup();+ const s = make();+ fill(s);+ expect(s.proxyView("notion")).toMatchObject({+ id: "notion",+ name: "Notion",+ enabled: true,+ mode: "read_only",+ server: { url: "https://mcp.notion.com/mcp" },+ });+ expect(s.proxyView("notion")?.readOnlyTools).toContain("notion-search");+ expect(s.proxyView("linear")).toMatchObject({ enabled: false });+ expect(s.proxyView("files")).toMatchObject({+ mode: "read_write",+ readOnlyTools: [],+ server: { command: "npx", args: ["-y", "[email protected]"] },+ });+ for (const id of ["discord", "slack", "tracker", "files"]) {+ const text = JSON.stringify(s.proxyView(id));+ for (const secret of Object.values(SECRETS)) expect(text).not.toContain(secret);+ }+ expect(s.proxyView("atlassian")).toBeUndefined();+ const before = s.proxyView("files")?.revision;+ s.update((state) => {+ const files = state.connectors.files;+ if (files) files.mode = "read_only";+ });+ expect(s.proxyView("files")?.revision).toBe(before);+ s.update((state) => {+ const files = state.connectors.files;+ if (files) files.values = { FILES_TOKEN: "another" };+ });+ expect(s.proxyView("files")?.revision).not.toBe(before);+ });++ it("injects the typed values as they were typed, the environment references, and the stored sign-in", async () => {+ const { make } = setup({ env: { PATH: "/usr/bin", TEAM_ID: "team-7" } });+ const s = make();+ fill(s);+ s.update((state) => {+ state.connectors.team = {+ enabled: true,+ mode: "read_only",+ custom: {+ name: "Team",+ description: "",+ origin: "Imported from Claude Code",+ server: {+ url: "https://team.example.com/mcp",+ headers: { "X-Team": "${TEAM_ID}", "X-Price": "$$5" },+ },+ fields: [],+ oauth: false,+ },+ };+ });+ expect((await s.credentials("discord")).env).toEqual({ DISCORD_TOKEN: SECRETS.discordToken });+ expect((await s.credentials("files")).env).toEqual({ FILES_TOKEN: SECRETS.envToken });+ const tracker = await s.credentials("tracker");+ expect(tracker.headers).toEqual({ Authorization: `Bearer ${SECRETS.headerToken}` });+ // A server with its own Authorization header does not sign in.+ expect(tracker.authProvider).toBeUndefined();+ expect((await s.credentials("team")).headers).toEqual({ "X-Team": "team-7", "X-Price": "$5" });+ const notion = await s.credentials("notion");+ expect(await notion.authProvider?.token()).toBeUndefined();+ writeFileSync(+ s.authFile,+ JSON.stringify({ [NOTION_KEY]: { tokens: { access_token: SECRETS.oauthAccess } } }),+ );+ expect(await notion.authProvider?.token()).toBe(SECRETS.oauthAccess);+ });+});++describe("the daemon's sign-in home", () => {+ it("moves the engine's old mcp-auth.json there once, after checking the copy", () => {+ const { make, agentHome, dataDir } = setup();+ const old = join(agentHome, "mcp-auth.json");+ const stored = JSON.stringify({ [NOTION_KEY]: { tokens: { access_token: SECRETS.oauthAccess } } });+ writeFileSync(old, stored);+ const s = make();+ expect(existsSync(old)).toBe(false);+ expect(readFileSync(s.authFile, "utf8")).toBe(stored);+ expect(s.authFile).toBe(join(dataDir, "connector-signin", "mcp-auth.json"));+ expect(statSync(s.authFile).mode & 0o777).toBe(0o600);+ expect(s.isSignedIn("notion")).toBe(true);+ expect(s.isSignedIn("linear")).toBe(false);+ // Not again: a file that shows up in the engine's home later is not taken over.+ writeFileSync(old, JSON.stringify({ [NOTION_KEY]: { tokens: { access_token: "planted" } } }));+ const next = make();+ expect(readFileSync(next.authFile, "utf8")).toBe(stored);+ expect(readdirSync(join(dataDir, "connector-signin")).filter((f) => f.includes(".tmp"))).toEqual([]);+ });++ it("protects the sign-in home and its files from the file tools and shell commands like the other credential files", () => {+ const { make, agentHome, dataDir } = setup();+ const s = make();+ fill(s);+ const policy = s.policy();+ const signin = join(dataDir, "connector-signin");+ expect(policy.protectedPaths).toEqual(+ expect.arrayContaining([+ join(agentHome, "mcp.json"),+ join(agentHome, "mcp-auth.json"),+ signin,+ join(signin, "mcp.json"),+ join(signin, "mcp-auth.json"),+ ]),+ );+ writeFileSync(s.authFile, "{}");+ const cwd = join(dataDir, "workspace");+ for (const call of [+ { toolName: "read", input: { path: join(signin, "mcp-auth.json") } },+ { toolName: "read", input: { path: "../connector-signin/mcp.json" } },+ { toolName: "ls", input: { path: signin } },+ { toolName: "grep", input: { pattern: "token", path: dataDir } },+ { toolName: "write", input: { path: join(signin, "mcp.json"), content: "{}" } },+ { toolName: "bash", input: { command: "cat ../connector-signin/mcp-auth.json" } },+ { toolName: "bash", input: { command: "ls ../connector-signin" } },+ ])+ expect(decide({ ...call, cwd }, policy).action).toBe("block");+ });++ it("puts back the sign-in files when they change outside a sign-in, and keeps what a sign-in wrote", async () => {+ const { make } = setup();+ const s = make();+ fill(s);+ const signinMcp = readFileSync(s.signinMcpFile, "utf8");+ writeFileSync(+ s.signinMcpFile,+ JSON.stringify({ mcpServers: { notion: { url: "https://evil.example/mcp" } } }),+ );+ expect(s.enforce()).toBe(true);+ expect(readFileSync(s.signinMcpFile, "utf8")).toBe(signinMcp);+ // Planted sign-in state is removed while no sign-in runs.+ writeFileSync(s.authFile, JSON.stringify({ [NOTION_KEY]: { tokens: { access_token: "planted" } } }));+ expect(s.enforce()).toBe(true);+ expect(existsSync(s.authFile)).toBe(false);+ // A sign-in writes it, and what it wrote is kept.+ const done = s.signingIn();+ const signedIn = JSON.stringify({ [NOTION_KEY]: { tokens: { access_token: SECRETS.oauthAccess } } });+ writeFileSync(s.authFile, signedIn);+ expect(s.enforce()).toBe(false);+ done();+ expect(s.enforce()).toBe(false);+ writeFileSync(s.authFile, "{}");+ expect(s.enforce()).toBe(true);+ expect(readFileSync(s.authFile, "utf8")).toBe(signedIn);+ // And the watcher does the same while the daemon runs.+ s.watch();+ rmSync(s.signinMcpFile);+ await waitFor(() => existsSync(s.signinMcpFile) && readFileSync(s.signinMcpFile, "utf8") === signinMcp);+ writeFileSync(s.authFile, "{}");+ await waitFor(() => readFileSync(s.authFile, "utf8") === signedIn);+ });+});++describe("the approval guard with proxied connectors", () => {+ it("lets the tools of a proxied connector through (the proxy asks), and still blocks one that is turned off", () => {+ const { make, dataDir } = setup();+ const s = make();+ fill(s);+ const policy = parsePolicy(JSON.stringify(s.policy()));+ if (!policy) throw new Error("the policy did not parse");+ expect(policy.proxied).toEqual(["notion", "discord", "slack", "tracker", "files"]);+ const cwd = join(dataDir, "workspace");+ const call = (toolName: string) => decide({ toolName, input: { body: "hi" }, cwd }, policy).action;+ expect(call("mcp__notion__notion_create_pages")).toBe("pass");+ expect(call("mcp__files__delete_everything")).toBe("pass");+ expect(call("mcp__linear__create_issue")).toBe("block");+ expect(call("mcp__unknown__x")).toBe("block");+ expect(parsePolicy(JSON.stringify({ ...s.policy(), proxied: [7] }))).toBeUndefined();+ });+});diff --git a/packages/daemon/test/connectors.test.ts b/packages/daemon/test/connectors.test.tsindex 8496ed6..ae9ca5d 100644--- a/packages/daemon/test/connectors.test.ts+++ b/packages/daemon/test/connectors.test.ts@@ -21,6 +21,7 @@ import {ConnectorManager,ConnectorStore,renderMcpJson,+ renderSigninMcpJson,} from "../src/connectors.ts";import { isReadOnlyCall } from "../src/extensions/approval-guard.ts";import { tempDir, waitFor } from "./helpers.ts";@@ -74,10 +75,10 @@ describe("connectors catalog", () => {});describe("mcp.json rendering", () => {- it("renders direct servers the engine accepts; read only hides every tool but the curated ones", async () => {+ it("renders the real servers for the sign-in command as the engine accepts them; read only hides every tool but the curated ones", async () => {const { validateMcpServerConfig, getMcpToolExposure } = await engineMcp();const rendered = JSON.parse(- renderMcpJson({+ renderSigninMcpJson({connectors: {notion: { enabled: true, mode: "read_only" },linear: { enabled: true, mode: "read_write" },@@ -106,6 +107,7 @@ describe("mcp.json rendering", () => {it("renders an empty server list when nothing is added", () => {expect(JSON.parse(renderMcpJson({ connectors: {} }))).toEqual({ mcpServers: {} });+ expect(JSON.parse(renderSigninMcpJson({ connectors: {} }))).toEqual({ mcpServers: {} });});});@@ -152,14 +154,16 @@ describe("connector store", () => {s.update((state) => {state.connectors.notion = { enabled: true, mode: "read_only" };});- const mcp = readFileSync(join(agentHome, "mcp.json"), "utf8");- expect(JSON.parse(mcp).mcpServers.notion.url).toBe("https://mcp.notion.com/mcp");+ expect(JSON.parse(readFileSync(s.signinMcpFile, "utf8")).mcpServers.notion.url).toBe(+ "https://mcp.notion.com/mcp",+ );expect(JSON.parse(readFileSync(join(dataDir, "connectors.json"), "utf8"))).toEqual({version: 1,connectors: { notion: { enabled: true, mode: "read_only" } },});expect(statSync(join(dataDir, "connectors.json")).mode & 0o777).toBe(0o600);expect(statSync(join(agentHome, "mcp.json")).mode & 0o777).toBe(0o600);+ expect(statSync(s.signinMcpFile).mode & 0o777).toBe(0o600);expect(readdirSync(agentHome).filter((f) => f.includes(".tmp"))).toEqual([]);const next = new ConnectorStore({ dataDir, agentHome, workspace });stores.push(next);@@ -220,7 +224,7 @@ describe("connector store", () => {version: 1,connectors: { linear: { enabled: true, mode: "read_write" } },});- expect(JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8")).mcpServers.linear).toBeDefined();+ expect(JSON.parse(readFileSync(s.signinMcpFile, "utf8")).mcpServers.linear).toBeDefined();expect(s.enforce()).toBe(false);});@@ -313,9 +317,13 @@ describe("connector store", () => {mode: "read_write",readOnlyTools: CATALOG[0]?.readOnlyTools,});+ expect(policy.proxied).toEqual(["notion"]);expect(policy.protectedPaths).toEqual([join(agentHome, "mcp.json"),join(agentHome, "mcp-auth.json"),+ join(dataDir, "connector-signin"),+ join(dataDir, "connector-signin", "mcp.json"),+ join(dataDir, "connector-signin", "mcp-auth.json"),join(agentHome, "auth.json"),join(agentHome, "models.json"),join(dataDir, "connectors.json"),@@ -325,17 +333,17 @@ describe("connector store", () => {});it("tells a stored sign-in from a pending one without exposing token values", () => {- const { store: s, agentHome } = store();+ const { store: s } = store();expect(s.isSignedIn("notion")).toBe(false);- writeFileSync(join(agentHome, "mcp-auth.json"), "{oops");+ writeFileSync(s.authFile, "{oops");expect(s.isSignedIn("notion")).toBe(false);writeFileSync(- join(agentHome, "mcp-auth.json"),+ s.authFile,JSON.stringify({ [NOTION_KEY]: { clientInformation: { client_id: "c" }, codeVerifier: "v" } }),);expect(s.isSignedIn("notion")).toBe(false);writeFileSync(- join(agentHome, "mcp-auth.json"),+ s.authFile,JSON.stringify({ [NOTION_KEY]: { tokens: { access_token: "secret-token-value" } } }),);expect(s.isSignedIn("notion")).toBe(true);@@ -441,7 +449,7 @@ describe("connector sign-in", () => {});it("connects: adds the server, relays the sign-in link, finishes through a pasted address", async () => {- const { manager, store, agentHome, dataDir, changes, owner, emit, find, sent, logs, cliRuns } = setup();+ const { manager, store, dataDir, changes, owner, emit, find, sent, logs, cliRuns } = setup();expect(manager.connect(owner, "notion", emit)).toBeUndefined();expect(store.state().connectors.notion).toEqual({ enabled: true, mode: "read_only" });expect(changes).toEqual([true]);@@ -456,7 +464,8 @@ describe("connector sign-in", () => {expect(prompt.prompt).toMatchObject({ flowId: link.flowId, kind: "manual_code" });const [run] = cliRuns();expect(run?.argv).toEqual(["mcp", "login", "notion"]);- expect(run?.env).toEqual({ PI_CODING_AGENT_DIR: agentHome, HOME: join(dataDir, "home") });+ // The sign-in command reads the real servers from the daemon's sign-in home, never the engine's.+ expect(run?.env).toEqual({ PI_CODING_AGENT_DIR: store.signinHome, HOME: join(dataDir, "home") });const redirect = new URL(new URL(link.event.kind === "auth_url" ? link.event.url : "").searchParams.get("redirect_uri") ?? "",);@@ -566,7 +575,7 @@ describe("connector sign-in", () => {manager.connect(owner, "notion", emit);await find("auth_done");expect(manager.setMode("notion", "read_write")).toBeUndefined();- expect(JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8")).mcpServers.notion).toEqual({+ expect(JSON.parse(readFileSync(store.signinMcpFile, "utf8")).mcpServers.notion).toEqual({url: "https://mcp.notion.com/mcp",exposure: "direct",});@@ -590,7 +599,8 @@ describe("connector sign-in", () => {]);expect(store.state().connectors).toEqual({});expect(JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8"))).toEqual({ mcpServers: {} });- expect(JSON.parse(readFileSync(join(agentHome, "mcp-auth.json"), "utf8"))).toEqual({});+ expect(JSON.parse(readFileSync(store.signinMcpFile, "utf8"))).toEqual({ mcpServers: {} });+ expect(JSON.parse(readFileSync(store.authFile, "utf8"))).toEqual({});expect(manager.list()[0]).toMatchObject({ added: false, status: "off" });expect(changes).toEqual([true, false, true, true, true]);expect(manager.setMode("notion", "read_only")).toMatchObject({ code: "connector_not_added" });diff --git a/packages/daemon/test/fixtures/fake-mcp-server.ts b/packages/daemon/test/fixtures/fake-mcp-server.tsindex 7b01047..1a082b6 100644--- a/packages/daemon/test/fixtures/fake-mcp-server.ts+++ b/packages/daemon/test/fixtures/fake-mcp-server.ts@@ -2,8 +2,12 @@// A minimal MCP server over stdio (newline-delimited JSON-RPC) with three tools: `list_messages`// and `notion-search` (named like Notion's curated one), which declare themselves read-only, and// `send_message`, which does not. Each call is appended to-// FAKE_MCP_SERVER_CALLS as JSONL, so a test can tell which calls really ran.-import { appendFileSync } from "node:fs";+// FAKE_MCP_SERVER_CALLS as JSONL, so a test can tell which calls really ran, and the process id+// is written to FAKE_MCP_SERVER_PID_FILE when set.+import { appendFileSync, writeFileSync } from "node:fs";++if (process.env.FAKE_MCP_SERVER_PID_FILE)+ writeFileSync(process.env.FAKE_MCP_SERVER_PID_FILE, String(process.pid));type Request = { jsonrpc: "2.0"; id?: number | string; method: string; params?: Record<string, unknown> };diff --git a/packages/daemon/test/mcp-proxy.test.ts b/packages/daemon/test/mcp-proxy.test.tsnew file mode 100644index 0000000..878a204--- /dev/null+++ b/packages/daemon/test/mcp-proxy.test.ts@@ -0,0 +1,528 @@+// The daemon's MCP proxy (S25.4): the engine talks to `/mcp/<connector>` with a per-launch key, and+// the daemon talks to the real server. Exercised through HTTP with pi-mcp's own client (as the engine+// connects), against in-memory, stdio, and HTTP upstreams.+import { readFileSync } from "node:fs";+import { createServer, type IncomingMessage, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import {+ type JsonRpcMessage,+ McpClient,+ McpError,+ type McpTransport,+ StreamableHttpTransport,+ type Tool,+} from "@earendil-works/pi-mcp";+import { createInMemoryTransportPair } from "@earendil-works/pi-mcp/testing";+import { afterEach, describe, expect, it } from "vitest";+import {+ type ApprovalPreview,+ McpProxy,+ type ProxiedConnector,+ type UpstreamCredentials,+} from "../src/mcp-proxy.ts";+import { tempDir, waitFor } from "./helpers.ts";++const FAKE_SERVER = fileURLToPath(new URL("./fixtures/fake-mcp-server.ts", import.meta.url));++const TOOLS: Tool[] = [+ { name: "search", inputSchema: { type: "object" }, annotations: { readOnlyHint: true } },+ // Curated, but the server does not say it only reads: it is not read-only.+ { name: "fetch", inputSchema: { type: "object" } },+ // Says it only reads, but nobody curated it.+ { name: "peek", inputSchema: { type: "object" }, annotations: { readOnlyHint: true } },+ { name: "send", inputSchema: { type: "object" }, annotations: { readOnlyHint: false } },+ { name: "explode", inputSchema: { type: "object" }, annotations: { readOnlyHint: true } },+];++type Rec = Record<string, unknown>;++/** An MCP server behind an in-memory transport: every request it got, and how often it was closed. */+function memoryUpstream() {+ const requests: { method: string; params: Rec }[] = [];+ const state = { closed: 0, connects: 0, dropNext: false };+ const answer = (method: string, params: Rec): { result?: unknown; error?: Rec } => {+ switch (method) {+ case "initialize":+ return {+ result: {+ protocolVersion: params.protocolVersion,+ capabilities: { tools: {}, resources: {}, prompts: {} },+ serverInfo: { name: "upstream", version: "1" },+ },+ };+ case "tools/list":+ return { result: { tools: TOOLS } };+ case "tools/call":+ if (params.name === "explode") return { error: { code: -32042, message: "the upstream exploded" } };+ return { result: { content: [{ type: "text", text: `ran ${String(params.name)}` }] } };+ case "resources/list":+ return { result: { resources: [{ uri: "file:///a", name: "a" }] } };+ case "resources/templates/list":+ return { result: { resourceTemplates: [{ uriTemplate: "file:///{x}", name: "x" }] } };+ case "resources/read":+ return { result: { contents: [{ uri: params.uri, text: "contents" }] } };+ case "prompts/list":+ return { result: { prompts: [{ name: "summary" }] } };+ case "prompts/get":+ return { result: { messages: [{ role: "user", content: { type: "text", text: "hi" } }] } };+ default:+ return { result: {} };+ }+ };+ const transport = (): McpTransport => {+ state.connects++;+ const { client, server } = createInMemoryTransportPair();+ server.onClose(() => {+ state.closed++;+ });+ server.onMessage((message: JsonRpcMessage) => {+ if (!("method" in message) || !("id" in message)) return;+ const params = (message.params ?? {}) as Rec;+ requests.push({ method: message.method, params });+ if (state.dropNext && message.method === "tools/call") {+ state.dropNext = false;+ void server.close();+ return;+ }+ void server.send({+ jsonrpc: "2.0",+ id: message.id,+ ...answer(message.method, params),+ } as JsonRpcMessage);+ });+ void server.start();+ return client;+ };+ const called = () => requests.filter((r) => r.method === "tools/call").map((r) => r.params.name);+ return { transport, requests, called, state };+}++function connector(overrides: Partial<ProxiedConnector> = {}): ProxiedConnector {+ return {+ id: "notes",+ name: "Notes",+ enabled: true,+ mode: "read_only",+ readOnlyTools: ["search", "fetch", "explode"],+ server: { url: "https://notes.example.com/mcp" },+ revision: "r1",+ ...overrides,+ };+}++const servers: Server[] = [];+const proxies: McpProxy[] = [];+const clients: McpClient[] = [];+afterEach(async () => {+ await Promise.all(clients.splice(0).map((c) => c.close().catch(() => undefined)));+ await Promise.all(proxies.splice(0).map((p) => p.close()));+ await Promise.all(servers.splice(0).map((s) => new Promise((done) => s.close(done))));+});++async function listen(handler: (req: IncomingMessage, res: import("node:http").ServerResponse) => void) {+ const server = createServer(handler);+ servers.push(server);+ await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));+ return `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+}++async function setup(+ options: {+ connectors?: ProxiedConnector[];+ approve?: (preview: ApprovalPreview) => Promise<boolean>;+ credentials?: (id: string) => Promise<UpstreamCredentials>;+ upstream?: ReturnType<typeof memoryUpstream>;+ inMemory?: boolean;+ } = {},+) {+ const views = new Map((options.connectors ?? [connector()]).map((c) => [c.id, c]));+ const upstream = options.upstream ?? memoryUpstream();+ const previews: ApprovalPreview[] = [];+ const logs: string[] = [];+ const proxy = new McpProxy({+ connector: (id) => views.get(id),+ credentials: options.credentials ?? (async () => ({})),+ approve: async (preview) => {+ previews.push(preview);+ return options.approve ? options.approve(preview) : true;+ },+ ...(options.inMemory === false ? {} : { transport: upstream.transport }),+ env: process.env,+ cwd: tempDir(),+ log: (line) => logs.push(line),+ });+ proxies.push(proxy);+ const base = await listen((req, res) => proxy.handle(req, res));+ const key = proxy.rotateKey();+ /** A client like the engine's: plain streamable HTTP with the key in a header. */+ const open = async (id = "notes", withKey = key) => {+ const client = new McpClient({ name: "engine", version: "1" });+ clients.push(client);+ await client.connect(+ new StreamableHttpTransport({+ url: `${base}/mcp/${id}`,+ headers: { Authorization: `Bearer ${withKey}` },+ }),+ );+ return client;+ };+ const post = (path: string, body: unknown, headers: Record<string, string> = {}) =>+ fetch(`${base}${path}`, {+ method: "POST",+ headers: { "content-type": "application/json", accept: "application/json", ...headers },+ body: JSON.stringify(body),+ });+ return { proxy, views, upstream, previews, logs, base, key, open, post };+}++const rpc = (method: string, params: Rec = {}) => ({ jsonrpc: "2.0", id: 1, method, params });++async function rpcError(promise: Promise<unknown>): Promise<McpError> {+ const error = await promise.then(+ () => undefined,+ (e: unknown) => e,+ );+ expect(error).toBeInstanceOf(McpError);+ return error as McpError;+}++describe("MCP proxy: the engine's side (S25.4)", () => {+ it("answers only requests carrying this launch's key in the Authorization header", async () => {+ const { post, key, proxy, upstream } = await setup();+ const noKey = await post("/mcp/notes", rpc("ping"));+ expect(noKey.status).toBe(401);+ expect(noKey.headers.get("content-type")).toMatch(/^application\/json/);+ expect((await noKey.json()) as Rec).toMatchObject({ error: { code: -32001 } });+ expect((await post("/mcp/notes", rpc("ping"), { authorization: "Bearer nope" })).status).toBe(401);+ // The key is never taken from the address.+ expect((await post(`/mcp/notes?token=${key}&key=${key}`, rpc("ping"))).status).toBe(401);+ const ok = await post("/mcp/notes", rpc("ping"), { authorization: `Bearer ${key}` });+ expect(ok.status).toBe(200);+ expect(ok.headers.get("content-type")).toMatch(/^application\/json/);+ expect(await ok.json()).toEqual({ jsonrpc: "2.0", id: 1, result: {} });+ // A new engine launch gets a new key; the old one stops working.+ const next = proxy.rotateKey();+ expect(next).not.toBe(key);+ expect(next.length).toBeGreaterThanOrEqual(40);+ expect((await post("/mcp/notes", rpc("ping"), { authorization: `Bearer ${key}` })).status).toBe(401);+ expect((await post("/mcp/notes", rpc("ping"), { authorization: `Bearer ${next}` })).status).toBe(200);+ expect(upstream.state.connects).toBe(0);+ });++ it("speaks plain JSON: GET is 405, notifications are 202, unknown connectors and methods are errors", async () => {+ const { post, key, base } = await setup();+ const auth = { authorization: `Bearer ${key}` };+ expect((await fetch(`${base}/mcp/notes`, { headers: auth })).status).toBe(405);+ const note = await post("/mcp/notes", { jsonrpc: "2.0", method: "notifications/initialized" }, auth);+ expect(note.status).toBe(202);+ expect(await note.text()).toBe("");+ expect(((await (await post("/mcp/notes", rpc("nope/nothing"), auth)).json()) as Rec).error).toMatchObject(+ {+ code: -32601,+ },+ );+ const unknown = await post("/mcp/other", rpc("ping"), auth);+ expect(unknown.status).toBe(404);+ expect(((await unknown.json()) as Rec).error).toMatchObject({ code: -32000 });+ const broken = await fetch(`${base}/mcp/notes`, { method: "POST", headers: auth, body: "{oops" });+ expect(((await broken.json()) as Rec).error).toMatchObject({ code: -32700 });+ // A page in a browser cannot use it, even with the key.+ expect((await post("/mcp/notes", rpc("ping"), { ...auth, origin: "https://evil.example" })).status).toBe(+ 403,+ );+ });++ it("is accepted by pi-mcp's client, as the engine connects, and connects upstream only when needed", async () => {+ const { open, upstream } = await setup();+ const client = await open();+ expect(client.serverCapabilities?.tools).toBeDefined();+ expect(upstream.state.connects).toBe(0);+ await client.listTools();+ expect(upstream.state.connects).toBe(1);+ await client.listTools();+ expect(upstream.state.connects).toBe(1);+ });+});++describe("MCP proxy: policy from the live connector state", () => {+ it("lists only curated tools the server marks read-only in read only, and every tool in read and send", async () => {+ const { open, views } = await setup();+ const client = await open();+ expect((await client.listTools()).map((t) => t.name)).toEqual(["search", "explode"]);+ views.set("notes", connector({ mode: "read_write" }));+ // The same connection sees the change: no engine restart.+ expect((await client.listTools()).map((t) => t.name)).toEqual([+ "search",+ "fetch",+ "peek",+ "send",+ "explode",+ ]);+ views.set("notes", connector({ mode: "read_only" }));+ expect((await client.listTools()).map((t) => t.name)).toEqual(["search", "explode"]);+ });++ it("refuses hidden and unknown tools even when called directly, and forwards nothing", async () => {+ const { open, upstream, previews } = await setup();+ const client = await open();+ for (const name of ["send", "peek", "fetch"]) {+ const error = await rpcError(client.callTool(name, { to: "x" }));+ expect(error.code).toBe(-32602);+ expect(error.message).toContain("read only");+ }+ const unknown = await rpcError(client.callTool("format_disk", {}));+ expect(unknown.code).toBe(-32602);+ expect(unknown.message).toContain("format_disk");+ expect(upstream.called()).toEqual([]);+ expect(previews).toEqual([]);+ // A read-only call runs without asking.+ expect(await client.callTool("search", { q: "x" })).toEqual({+ content: [{ type: "text", text: "ran search" }],+ });+ expect(upstream.called()).toEqual(["search"]);+ expect(previews).toEqual([]);+ });++ it("asks once with the full preview before a sending action, and forwards nothing when declined", async () => {+ let allow = false;+ const { open, upstream, previews } = await setup({+ connectors: [connector({ mode: "read_write" })],+ approve: async () => allow,+ });+ const client = await open();+ const long = "x".repeat(10_000);+ const args = { to: "[email protected]", body: long, nested: { list: [1, 2, 3] } };+ const declined = await rpcError(client.callTool("send", args));+ expect(declined.message).toMatch(/did not allow/);+ expect(previews).toEqual([{ connectorId: "notes", connector: "Notes", tool: "send", arguments: args }]);+ expect(upstream.called()).toEqual([]);+ allow = true;+ expect(await client.callTool("send", args)).toEqual({ content: [{ type: "text", text: "ran send" }] });+ expect(previews).toHaveLength(2);+ expect(upstream.requests.find((r) => r.method === "tools/call")?.params).toEqual({+ name: "send",+ arguments: args,+ });+ // Read-only tools never ask, in either mode.+ await client.callTool("search", {});+ expect(previews).toHaveLength(2);+ });++ it("refuses when asking fails, and when the connector changed while the user was asked", async () => {+ const state: { fail: boolean; views?: Map<string, ProxiedConnector> } = { fail: true };+ const { open, upstream, views } = await setup({+ connectors: [connector({ mode: "read_write" })],+ approve: async () => {+ if (state.fail) throw new Error("no window");+ state.views?.set("notes", connector({ mode: "read_only" }));+ return true;+ },+ });+ state.views = views;+ const client = await open();+ expect((await rpcError(client.callTool("send", {}))).message).toMatch(/could not be asked|approval/i);+ state.fail = false;+ // Approved, but the user switched the connector to read only meanwhile.+ expect((await rpcError(client.callTool("send", {}))).message).toContain("read only");+ expect(upstream.called()).toEqual([]);+ });++ it("shows resources and prompts in read and send, and in read only only for a connector with a curated list", async () => {+ const { open, views, upstream } = await setup();+ const client = await open();+ expect(client.serverCapabilities?.resources).toBeDefined();+ expect(await client.listResources()).toEqual([{ uri: "file:///a", name: "a" }]);+ expect(await client.listResourceTemplates()).toHaveLength(1);+ expect((await client.readResource("file:///a")).contents).toHaveLength(1);+ expect(await client.request("prompts/list")).toEqual({ prompts: [{ name: "summary" }] });+ expect(await client.request("prompts/get", { name: "summary" })).toMatchObject({+ messages: [{ role: "user" }],+ });+ // A server of the user's own (no curated list) in read only exposes nothing.+ views.set("notes", connector({ readOnlyTools: [] }));+ const before = upstream.requests.length;+ expect(await client.listResources()).toEqual([]);+ expect(await client.listResourceTemplates()).toEqual([]);+ expect(await client.request("prompts/list")).toEqual({ prompts: [] });+ expect((await rpcError(client.readResource("file:///a"))).code).toBe(-32602);+ expect((await rpcError(client.request("prompts/get", { name: "summary" }))).code).toBe(-32602);+ expect(await client.listTools()).toEqual([]);+ expect(upstream.requests.slice(before).filter((r) => r.method !== "tools/list")).toEqual([]);+ views.set("notes", connector({ readOnlyTools: [], mode: "read_write" }));+ expect(await client.listResources()).toHaveLength(1);+ });++ it("refuses everything for a connector that is turned off", async () => {+ const { open, views, upstream } = await setup();+ const client = await open();+ views.set("notes", connector({ enabled: false }));+ const error = await rpcError(client.listTools());+ expect(error.message).toContain("turned off");+ expect(upstream.state.connects).toBe(0);+ });+});++describe("MCP proxy: upstream connections", () => {+ it("passes the upstream's errors on, and reconnects after the upstream dropped", async () => {+ const { open, upstream, logs } = await setup();+ const client = await open();+ const failed = await rpcError(client.callTool("explode", {}));+ expect([failed.code, failed.message]).toEqual([-32042, "the upstream exploded"]);+ upstream.state.dropNext = true;+ const dropped = await rpcError(client.callTool("search", {}));+ expect(dropped.message).toMatch(/could not reach notes|Notes/i);+ expect(upstream.state.connects).toBe(1);+ expect(await client.callTool("search", {})).toMatchObject({ content: [{ text: "ran search" }] });+ expect(upstream.state.connects).toBe(2);+ expect(logs.join("\n")).not.toContain("Bearer");+ });++ it("closes a connector's upstream when it is removed, turned off, or its server changed, and all of them on close", async () => {+ const { open, views, upstream, proxy } = await setup();+ const client = await open();+ await client.listTools();+ proxy.sync();+ expect(upstream.state.closed).toBe(0);+ views.set("notes", connector({ mode: "read_write" }));+ proxy.sync();+ // A mode change keeps the connection.+ expect(upstream.state.closed).toBe(0);+ views.set("notes", connector({ revision: "r2" }));+ proxy.sync();+ await waitFor(() => upstream.state.closed === 1);+ await client.listTools();+ views.set("notes", connector({ enabled: false }));+ proxy.sync();+ await waitFor(() => upstream.state.closed === 2);+ views.set("notes", connector());+ await client.listTools();+ views.delete("notes");+ proxy.sync();+ await waitFor(() => upstream.state.closed === 3);+ views.set("notes", connector());+ await client.listTools();+ await proxy.close();+ await waitFor(() => upstream.state.closed === 4);+ });++ it("runs a stdio server itself, with the environment from the credentials, and stops it when removed", async () => {+ const dir = tempDir();+ const calls = join(dir, "calls.jsonl");+ const pidFile = join(dir, "pid");+ const stdio = connector({+ id: "chat",+ name: "Chat",+ mode: "read_write",+ readOnlyTools: ["list_messages"],+ server: { command: process.execPath, args: [FAKE_SERVER] },+ });+ const { open, views, proxy, previews } = await setup({+ connectors: [stdio],+ inMemory: false,+ credentials: async (id) => {+ expect(id).toBe("chat");+ return { env: { FAKE_MCP_SERVER_CALLS: calls, FAKE_MCP_SERVER_PID_FILE: pidFile } };+ },+ });+ const client = await open("chat");+ expect((await client.listTools()).map((t) => t.name)).toEqual([+ "list_messages",+ "notion-search",+ "send_message",+ ]);+ expect(await client.callTool("list_messages", {})).toMatchObject({+ content: [{ text: "ran list_messages" }],+ });+ await client.callTool("send_message", { to: "a", body: "b" });+ expect(previews.map((p) => p.tool)).toEqual(["send_message"]);+ expect(+ readFileSync(calls, "utf8")+ .trim()+ .split("\n")+ .map((l) => JSON.parse(l).name),+ ).toEqual(["list_messages", "send_message"]);+ const pid = Number(readFileSync(pidFile, "utf8"));+ const alive = () => {+ try {+ process.kill(pid, 0);+ return true;+ } catch {+ return false;+ }+ };+ expect(alive()).toBe(true);+ views.delete("chat");+ proxy.sync();+ await waitFor(() => !alive());+ });++ it("talks to a remote server over HTTP with the headers and token from the credentials", async () => {+ const seen: { authorization?: string; team?: string; method: string }[] = [];+ const upstreamUrl = await listen((req, res) => {+ let body = "";+ req.on("data", (chunk: Buffer) => {+ body += chunk.toString("utf8");+ });+ req.on("end", () => {+ if (req.method !== "POST") {+ res.writeHead(405).end();+ return;+ }+ const message = JSON.parse(body) as { id?: number; method: string; params?: Rec };+ seen.push({+ authorization: req.headers.authorization,+ team: req.headers["x-team"] as string | undefined,+ method: message.method,+ });+ if (message.id === undefined) {+ res.writeHead(202).end();+ return;+ }+ const result =+ message.method === "initialize"+ ? {+ protocolVersion: message.params?.protocolVersion,+ capabilities: { tools: {} },+ serverInfo: { name: "remote", version: "1" },+ }+ : message.method === "tools/list"+ ? { tools: TOOLS }+ : { content: [{ type: "text", text: "remote ran" }] };+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }));+ });+ });+ const { open } = await setup({+ connectors: [connector({ server: { url: `${upstreamUrl}/mcp` } })],+ inMemory: false,+ credentials: async () => ({+ headers: { "X-Team": "blue" },+ authProvider: { token: async () => "upstream-access-token" },+ }),+ });+ const client = await open();+ expect(await client.callTool("search", {})).toMatchObject({ content: [{ text: "remote ran" }] });+ expect(seen.length).toBeGreaterThan(0);+ for (const request of seen) {+ expect(request.authorization).toBe("Bearer upstream-access-token");+ expect(request.team).toBe("blue");+ }+ expect(seen.map((r) => r.method)).toContain("tools/call");+ });++ it("says the user must sign in again when the upstream refuses the credentials", async () => {+ const upstreamUrl = await listen((req, res) => {+ req.resume();+ res.writeHead(401, { "content-type": "application/json" }).end("{}");+ });+ const { open } = await setup({+ connectors: [connector({ server: { url: `${upstreamUrl}/mcp` } })],+ inMemory: false,+ });+ const client = await open();+ const error = await rpcError(client.listTools());+ expect(error.message).toMatch(/sign in/i);+ });+});diff --git a/packages/daemon/test/runtime-build.test.ts b/packages/daemon/test/runtime-build.test.tsindex 0916c93..bf7dd87 100644--- a/packages/daemon/test/runtime-build.test.ts+++ b/packages/daemon/test/runtime-build.test.ts@@ -68,6 +68,7 @@ describe("build:runtime", () => {expect(manifest.dependencies).toEqual({"@earendil-works/pi-ai": "1.0.4","@earendil-works/pi-coding-agent": "1.0.4",+ "@earendil-works/pi-mcp": "1.0.4","@earendil-works/pi-tui": "1.0.4","gentle-pi": "4.0.0",jiti: "2.7.0",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex cdc5950..b7891f7 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -38,6 +38,9 @@ importers:'@earendil-works/pi-coding-agent':specifier: 1.0.4+ '@earendil-works/pi-mcp':+ specifier: 1.0.4+ version: 1.0.4'@earendil-works/pi-tui':specifier: 1.0.4version: 1.0.4