From 03001511edb0b094b43d7a8d6c804e99ceae57cf Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 11 Nov 2026 15:16:50 -0500 Subject: [PATCH 1/9] Add a local MCP server core so other apps can use Aiden's chats Aiden can now serve MCP on a dedicated loopback listener, off by default, so Claude Code, Codex or any MCP client on the same computer can list workspaces and chats, read them, and (with Supervised access) start, send to, wait on and stop Aiden turns. Approvals and questions stay with the person in Aiden; no tool can answer them. - Stateless Streamable HTTP on 127.0.0.1 with a stable saved port, exact Host and same-origin checks, no CORS, a 1 MiB body limit and a connection cap. - Outside apps are Remote devices of type "agent" with their own tokens, quota and a Read/Supervised capability ceiling re-applied on every state parse; /api/aiden/v1 refuses them and /mcp refuses phones and Macs. - Per-app turn rate limit and run cap, idempotent clientRequestId, own-run wait and stop, Bot chats and hidden workspaces out of reach. - Revoking an app ends its waits, stops its runs and denies their approvals through the shared revocation path. - Local-only "started by" provenance, never projected. - Main-process status/enable/issue/list/revoke functions for the Settings UI that follows; no UI or CLI wiring yet. Co-Authored-By: Claude Opus 5.5 --- .memory/aiden-mcp-server.md | 63 ++ docs/aiden-mcp-server.md | 113 +++ docs/security/aiden-remote-threat-model.md | 50 + main/services/aiden-mcp-provenance.ts | 106 +++ main/services/aiden-mcp-server.test.ts | 895 ++++++++++++++++++ main/services/aiden-mcp-server.ts | 393 ++++++++ main/services/aiden-mcp-tools.ts | 640 +++++++++++++ main/services/aiden-remote-router.test.ts | 22 +- main/services/aiden-remote-router.ts | 5 +- main/services/aiden-remote-service-main.ts | 92 +- main/services/aiden-remote-service.ts | 15 +- main/services/aiden-remote-state.test.ts | 100 ++ main/services/aiden-remote-state.ts | 229 ++++- main/services/aiden-remote-streams.ts | 42 +- .../host-platform-capabilities.test.ts | 3 + main/services/host-platform-capabilities.ts | 7 + package.json | 2 +- scripts/ci-test-registry.json | 1 + 18 files changed, 2746 insertions(+), 32 deletions(-) create mode 100644 .memory/aiden-mcp-server.md create mode 100644 docs/aiden-mcp-server.md create mode 100644 main/services/aiden-mcp-provenance.ts create mode 100644 main/services/aiden-mcp-server.test.ts create mode 100644 main/services/aiden-mcp-server.ts create mode 100644 main/services/aiden-mcp-tools.ts diff --git a/.memory/aiden-mcp-server.md b/.memory/aiden-mcp-server.md new file mode 100644 index 0000000000..287e7fdd0f --- /dev/null +++ b/.memory/aiden-mcp-server.md @@ -0,0 +1,63 @@ +# Aiden MCP server for outside apps (W4a, 2026-11-11) + +Core only: a loopback MCP server that lets Claude Code, Codex or any MCP client use Aiden's chats. Ported in spirit from T3 Code PR #33196 (no code copied). Off by default, with no Settings UI yet (W4b) and no `aiden serve` wiring (W4c). User docs: `docs/aiden-mcp-server.md`; threat model section 10 of `docs/security/aiden-remote-threat-model.md`. README and PRODUCT.md make no claims until W4b ships. + +## Layout + +- `main/services/aiden-mcp-server.ts` + - `AidenMcpServer`: + - a dedicated `http` listener on 127.0.0.1, `/mcp` only + - each POST builds a fresh SDK `Server` and a stateless `StreamableHTTPServerTransport` with `enableJsonResponse` + - a response close aborts the call's signal, which `aiden_chat_wait` uses + - `AidenMcpHost` owns the on/off reconcile, port selection and commit, and issue, list and revoke. +- `main/services/aiden-mcp-tools.ts` + - `AidenMcpToolRunner` holds the 9 `aiden_*` tools, TypeBox schemas, per-app limits, the `clientRequestId` cache and the run ownership map. + - It calls the shared `AidenRemoteChatService` and `AidenRemoteStreamService`, the same ones phones use. +- `main/services/aiden-mcp-provenance.ts` + - The local-only `startedBy {kind:"app", appId, name, startedAt}` log, in `aiden-mcp-chat-provenance.json` under userData, holding the newest 1,000 entries. + - A failed write is swallowed, so the turn still runs. +- `aiden-remote-state.ts` + - Device type `agent`, with `AGENT_CAPABILITY_CEILING` (read: `server:read` and `chat:read`; supervised adds `chat:write`), re-applied on every parse. + - `MAX_AIDEN_REMOTE_AGENT_APPS = 16`. + - `issueAgentApp`, `listAgentApps`, `mcpServerSettings`, `setMcpServerEnabled` and `commitMcpServerPort`. + - The `mcpServer {enabled, port?}` setting lives in the Remote state document. +- `aiden-remote-router.ts`: an `agent` token on `/api/aiden/v1` gets 401, like an unknown one. +- `aiden-remote-streams.ts`: added `watch` for the wait tool. +- `aiden-remote-service-main.ts` + - Builds the host inside the Remote runtime (`runtime.mcp`). + - `initializeAidenRemoteService` starts the host's reconcile; stop and settle also stop it. + - Exports `aidenMcpServerStatus`, `setAidenMcpServerEnabled`, `issueAidenMcpApp`, `listAidenMcpApps` and `revokeAidenMcpApp` for W4b's IPC. +- `host-platform-capabilities.ts`: `mcpServer` is darwin or linux. + +## Verified behaviour + +- **Port:** + - Release builds use 49400 and the next 7 ports; development builds use 50400 and the next 7. + - The first port that binds is committed. After that only the saved port is tried, and if it is busy the status is `problem: "port_in_use"`. +- **Requests:** + - Host must be `127.0.0.1:` or `localhost:`, and any Origin other than the same loopback origin gets 403. No CORS headers are sent, OPTIONS included. + - A missing or bad token gets 401 with `WWW-Authenticate: Bearer realm="aiden"`. +- **Body limit:** + - Over 1 MiB, declared or streamed, gets 413. + - The server drains the rest for up to 5 s and then destroys the socket. Using `connection: close` instead raced the client's upload, and the client saw ECONNRESET in place of the 413. +- **Write tools:** + - They need `chat:write`, and Read apps do not see them listed. + - Turns are limited to 10 a minute and 2 concurrent runs per app; an idempotent retry does not count. + - Waits are at most 55 s and default to 25 s. +- **Reach:** + - `aiden_workspace_list` and `aiden_chat_start` exclude `noWorkspace` folders and `ASSISTANT_WORKSPACE_ID`. + - Chat list is regular chats only, and `requireOrdinaryChat` refuses Bot chats by id. + - Assistant and feature chats are still readable and sendable by id, as on phones. +- **No approval tool.** `aiden_chat_wait` returns `waiting_for_approval` or `waiting_for_input` with `approveIn` / `answerIn` set to "Aiden on ". +- **Revoke:** + - It runs `revokeAidenRemoteRuntimeDevice`, which denies approvals, cancels runs and closes watchers. + - It then runs `tools.revokeApp`, which aborts that app's waits with "This app was disconnected from Aiden." + - A phone or Mac id returns false. +- **Tests:** `main/services/aiden-mcp-server.test.ts` (13 tests, in `test:aiden-remote` and `scripts/ci-test-registry.json`) runs a real registry, streams and chat service over fakes. + - Its client is `@earendil-works/pi-mcp` `McpClient`. ESLint forbids importing `@modelcontextprotocol/sdk/client*`. + - A fake generation's finish must check `owner.isDestroyed()` first, because `owner.send` throws after revocation. + +## Open for W4b and W4c + +- W4b: the Settings UI and IPC over the five main exports, plus a "Started by" label from provenance (nothing reads it yet). +- W4c: `packages/cli` has no `@modelcontextprotocol/sdk` dependency and no MCP host wiring in `aiden serve`. diff --git a/docs/aiden-mcp-server.md b/docs/aiden-mcp-server.md new file mode 100644 index 0000000000..f69fc217ee --- /dev/null +++ b/docs/aiden-mcp-server.md @@ -0,0 +1,113 @@ +# Aiden MCP server + +Aiden can act as a [Model Context Protocol](https://modelcontextprotocol.io) server, so another app on the same computer (Claude Code, Codex, or any MCP client) can list Aiden's workspaces and chats, read them, and, with permission, start and follow Aiden turns. + +Status (2026-11-11): the server core is in the desktop main process, behind the `mcpServer` host capability (macOS and Linux desktop; see `main/services/host-platform-capabilities.ts`). It is **off by default**. The Settings screen for turning it on and connecting apps is still to come (workstream W4b), and so is a headless `aiden serve` counterpart (W4c). Until those ship, the only way to turn the server on or issue an app is through the main-process functions listed under [Main-process API](#main-process-api). + +## How an app connects + +- **Transport:** stateless MCP Streamable HTTP. Each POST is a whole JSON-RPC exchange, answered as JSON. There are no sessions, no server-sent events and no `GET` stream. +- **Address:** `http://127.0.0.1:/mcp`, loopback only. The server is a dedicated listener and is never served on the Remote Access LAN TLS listener, Tailscale or any other interface. +- **Port:** + - Release builds try 49400 first, then the next seven ports up. Development builds start at 50400. + - The first port that binds is saved in Aiden's Remote state file, so the URL stays the same across restarts and an app's configuration keeps working. + - If another program later holds the saved port, the server reports `port_in_use` rather than moving, because moving would break every configured app silently. +- **Credential:** each app gets its own bearer token, a 43-character base64url secret shown once when it is issued. Aiden stores only a hash. A token is sent as `Authorization: Bearer `. + +Claude Code: + +```sh +claude mcp add --transport http aiden http://127.0.0.1:49400/mcp \ + --header "Authorization: Bearer " +``` + +Codex: + +```sh +export AIDEN_MCP_TOKEN= +codex mcp add aiden --url http://127.0.0.1:49400/mcp --bearer-token-env-var AIDEN_MCP_TOKEN +``` + +Use the port your Aiden reports if it is not 49400. + +## Access levels + +An app is a Remote device of type `agent`. Its capabilities are set to one of two levels when it is issued. When Aiden loads its Remote state, an app record is stripped of anything beyond the Supervised set, so an edit to the state file cannot widen an app's access: + +| Level | Capabilities | Tools | +| --- | --- | --- | +| Read | `server:read`, `chat:read` | `aiden_server_info`, `aiden_workspace_list`, `aiden_chat_list`, `aiden_chat_read`, `aiden_chat_wait` | +| Supervised | Read, plus `chat:write` | Read tools, plus `aiden_chat_start`, `aiden_chat_send`, `aiden_chat_stop` | + +An app is never granted `approval:respond`, files, Git, shell, Bots, schedules, settings, devices or pairing. A Read app does not see the write tools in `tools/list`, and calling one anyway is refused. + +At most 16 apps can be connected at once, separately from the phone and Mac device limit. + +## Tools + +| Tool | What it does | +| --- | --- | +| `aiden_server_info` | Aiden's version, the computer's name, and this app's access level. | +| `aiden_workspace_list` | The person's workspaces. It leaves out the folders Aiden makes for a single chat, and the assistant's own workspace. | +| `aiden_chat_list` | Recent ordinary chats, newest first, with a cursor. It leaves out Bot chats, feature chats and assistant chats. | +| `aiden_chat_read` | A chat's recent messages, paged with `before`. | +| `aiden_chat_wait` | Waits up to `timeoutSeconds` (default 25, maximum 55) for a run this app started. Returns `running`, `waiting_for_approval` or `waiting_for_input` (each with `approveIn`/`answerIn`, for example "Aiden on Studio Mac"), `done` with the final reply, or `failed`. It returns early if the app disconnects. | +| `aiden_chat_start` | Starts a new chat in an offered workspace, with optional `providerId`/`modelId`, and sends the first message. Needs a `clientRequestId`. Retrying with the same one returns the same chat and run, and never starts a second turn. | +| `aiden_chat_send` | Sends a follow-up to an existing ordinary chat (also idempotent by `clientRequestId`). | +| `aiden_chat_stop` | Stops a run **this app** started. Another app's runs, and the person's own, cannot be stopped or waited on. | + +Arguments are validated against each tool's schema, and unknown properties are rejected. A message can be at most 200,000 characters, and messages read back are capped at 20,000 characters each. Bot chats cannot be read or written by id, even when the id is known. + +There is deliberately no tool for approvals or questions. When a turn needs one, `aiden_chat_wait` says so and where, and the person answers it in Aiden on that computer. A turn runs with the permissions of its workspace. In a Full-access workspace, tools run without asking, exactly as if the person had typed the message. + +## Limits + +- **Turns:** each app can start or send 10 turns a minute and have 2 runs at once. A retry of an accepted `clientRequestId` does not count again. +- **Requests:** + - A request body over 1 MiB is answered 413 before any tool runs, whether its size is declared or streamed. + - The server drains the rest of an oversized upload for up to 5 seconds so the app sees the 413, then cuts the connection. + - A body that is not JSON gets JSON-RPC parse error `-32700`. +- **Connections:** at most 16 at once. + +## Threat model + +Who could call the server: + +- **Other software running as the same user.** It can reach loopback but has no token, so it gets 401. The token check is constant-time over hashes, and a missing, malformed, wrong or revoked token gets the same 401 with `WWW-Authenticate: Bearer realm="aiden"`. +- **A web page in the person's browser.** + - DNS rebinding is blocked by requiring the `Host` header to be exactly `127.0.0.1:` or `localhost:`, and refusing any `Origin` other than that same loopback origin, with 403. + - The server sends no CORS headers, `OPTIONS` included, so a page cannot read a response even on a same-machine origin. +- **A phone or paired Mac.** Their Remote credentials are refused on `/mcp`, and an app token is refused on `/api/aiden/v1`, both with 401. The audiences never cross. +- **A connected app that misbehaves.** + - It is limited to its access level, its own runs, ordinary chats and offered workspaces, and the rate and concurrency limits. + - It cannot settle an approval or answer a question. + - A Supervised app can still ask Aiden to do anything the chosen workspace allows without approval, which is why Supervised is a deliberate choice and Full-access workspaces run unattended. + +Revoking an app: + +- Rejects its token on the next request. +- Ends any `aiden_chat_wait` it has open ("This app was disconnected from Aiden."). +- Stops the runs it started, and denies their pending approvals, through the same revocation path as a phone. + +Turning the server off closes the listener and every open connection. + +Privacy: + +- Aiden keeps a local note of which app started a chat (`startedBy {kind: "app", name}`, in `aiden-mcp-chat-provenance.json`, the newest 1,000 entries). It is never sent to phones, Macs or apps. +- App ids never appear in tool results. +- Server logs carry only `started`, `stopped`, `start-failed` (with a problem code) and `request-failed`, never a token, an app name, a path or chat text. +- No analytics events are sent for the MCP server. + +The Remote Access threat model has the matching section: [`docs/security/aiden-remote-threat-model.md`](security/aiden-remote-threat-model.md#10-local-mcp-server-for-outside-apps). + +## Main-process API + +These are exported from `main/services/aiden-remote-service-main.ts` for the Settings IPC in W4b: + +- `aidenMcpServerStatus()` returns `{supported, enabled, running, port?, url?, problem?}`. +- `setAidenMcpServerEnabled(enabled)` turns the server on or off and saves the choice. +- `issueAidenMcpApp({name, access: "read" | "supervised"})` returns `{credential, app}`. The credential is returned only this once. +- `listAidenMcpApps()` lists the connected apps. +- `revokeAidenMcpApp(appId)` disconnects one app. A phone's or Mac's id returns `false`. + +Code: `main/services/aiden-mcp-server.ts` (listener, `AidenMcpHost`), `main/services/aiden-mcp-tools.ts` (tools and limits), `main/services/aiden-mcp-provenance.ts`, and agent-app state in `main/services/aiden-remote-state.ts`. Tests: `main/services/aiden-mcp-server.test.ts` (in `npm run test:aiden-remote`). diff --git a/docs/security/aiden-remote-threat-model.md b/docs/security/aiden-remote-threat-model.md index 424b6f5d6e..ad3c4b81a8 100644 --- a/docs/security/aiden-remote-threat-model.md +++ b/docs/security/aiden-remote-threat-model.md @@ -161,3 +161,53 @@ Before each phase gate: - Verify managed-home ownership/`cwd`, no automatic `.git`, task-needed outside-home access, and authoritative prompt ordering without treating the prompt as enforcement. - Verify Image Playground unavailable/cancel/PCC disclosure, accepted-image-only upload, Mac-side decode/normalization, asset isolation, and temporary-file cleanup on physical supported and unsupported devices. - Run two independent fresh-memory security/architecture reviews and clear all P0/P1 findings. + +## 10. Local MCP server for outside apps + +Added 2026-11-11. Design and tools: [`docs/aiden-mcp-server.md`](../aiden-mcp-server.md). + +```text +Outside app (Claude Code, Codex, any MCP client) on this computer + -> http://127.0.0.1:/mcp (dedicated loopback listener, never the LAN TLS listener) + -> Host/Origin check, no CORS, 1 MiB body limit, connection cap + -> agent-app bearer token (separate audience from phones and Macs) + -> per-tool capability check, schema validation, per-app rate/concurrency limits + -> shared Remote chat and stream services (same generation owner and revocation path as a phone) +``` + +- **Off by default** and gated by the `mcpServer` host capability. It is a separate switch from Remote Access, with its own port saved in the Remote state file. +- **Audience separation.** Agent-app records are Remote devices of type `agent`. `/api/aiden/v1` refuses their tokens, `/mcp` refuses phone and Mac tokens, and revoking an app through the MCP host refuses a phone or Mac id. +- **Capability ceiling.** + - An app holds `server:read` and `chat:read` (Read), plus `chat:write` (Supervised), and nothing else. + - The ceiling is re-applied whenever the state file is parsed, so no edit can grant `approval:respond`, files, Git, Bots, schedules, settings or pairing. + - Apps never answer approvals or questions; the person does, in Aiden on the computer. +- **Browser and rebinding.** `Host` must be the exact loopback host and port, and any `Origin` other than the same loopback origin is refused. No `Access-Control-*` header is ever sent. +- **Reach.** + - Apps see ordinary chats and offered workspaces only. Bot, feature and assistant chats are not listed, Bot chats are refused by id, and new chats cannot be started in one-chat folders or the assistant workspace. + - An app can wait on and stop only runs it started. +- **Residual risk.** A Supervised app is delegated the person's own authority in the chosen workspace. In a Full-access workspace its turns run tools without approval. Supervised access and Full-access workspaces are the person's informed choices; neither is containment. +- **Revocation** goes through `revokeAidenRemoteRuntimeDevice`: + - It rejects the token at once, ends open waits and stops the app's runs. + - It denies the runs' pending approvals. + - Disabling the server closes every connection. +- **Privacy.** + - The app that started a chat is recorded only locally (`aiden-mcp-chat-provenance.json`) and is never projected. + - Logs follow section 7 and carry only content-free events. + - No analytics events are sent. + +Required evidence: `main/services/aiden-mcp-server.test.ts` covers: + +- a missing, wrong or revoked token +- phone and Mac tokens on `/mcp` +- Host and Origin rebinding +- the absent CORS headers +- declared and streamed oversized bodies +- a Read app's write refusals +- idempotent starts +- unanswerable approvals +- own-run stop +- revoke ending a wait +- the rate and concurrency limits +- Bot chats and hidden workspaces out of reach + +`main/services/aiden-remote-router.test.ts` covers agent tokens on `/api/aiden/v1`. `main/services/aiden-remote-state.test.ts` covers the capability ceiling and the app quota. diff --git a/main/services/aiden-mcp-provenance.ts b/main/services/aiden-mcp-provenance.ts new file mode 100644 index 0000000000..56e0ebf721 --- /dev/null +++ b/main/services/aiden-mcp-provenance.ts @@ -0,0 +1,106 @@ +/** + * Which outside app started a chat through Aiden's MCP server. + * + * This is a local record only. It is never projected to a phone, a paired Mac + * or an outside app: the chat itself looks the same as any other, and this + * note exists so Aiden on this computer can say "Started by Claude Code". + */ + +/** One chat an outside app started. */ +export interface AidenMcpChatProvenance { + kind: "app"; + appId: string; + name: string; + /** Epoch milliseconds. */ + startedAt: number; +} + +export interface AidenMcpProvenanceDocument { + version: 1; + /** Oldest first; bounded by the log's limit. */ + entries: Array<{ chatId: string } & AidenMcpChatProvenance>; +} + +export interface AidenMcpProvenanceStorage { + load(): Promise; + save(document: AidenMcpProvenanceDocument): Promise; +} + +export const AIDEN_MCP_PROVENANCE_LIMIT = 1_000; + +export function emptyAidenMcpProvenanceDocument(): AidenMcpProvenanceDocument { + return { version: 1, entries: [] }; +} + +/** Drops anything that is not a well-formed entry, keeping the newest `limit`. */ +export function parseAidenMcpProvenanceDocument( + value: unknown, + limit = AIDEN_MCP_PROVENANCE_LIMIT, +): AidenMcpProvenanceDocument { + if (!value || typeof value !== "object" || Array.isArray(value)) return emptyAidenMcpProvenanceDocument(); + const record = value as { version?: unknown; entries?: unknown }; + if (record.version !== 1 || !Array.isArray(record.entries)) return emptyAidenMcpProvenanceDocument(); + const entries: AidenMcpProvenanceDocument["entries"] = []; + for (const candidate of record.entries) { + if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) continue; + const entry = candidate as Record; + if ( + entry.kind !== "app" || + !shortString(entry.chatId, 128) || + !shortString(entry.appId, 128) || + !shortString(entry.name, 80) || + !Number.isSafeInteger(entry.startedAt) || + (entry.startedAt as number) < 0 + ) { + continue; + } + entries.push({ + chatId: entry.chatId, + kind: "app", + appId: entry.appId, + name: entry.name, + startedAt: entry.startedAt as number, + }); + } + return { version: 1, entries: entries.slice(-limit) }; +} + +export class AidenMcpProvenanceLog { + private queue: Promise = Promise.resolve(); + + constructor( + private readonly storage: AidenMcpProvenanceStorage, + private readonly limit = AIDEN_MCP_PROVENANCE_LIMIT, + ) {} + + /** Notes that `chatId` was started by an outside app. The first note for a chat wins. */ + record(chatId: string, provenance: AidenMcpChatProvenance): Promise { + return this.serialize(async () => { + const document = parseAidenMcpProvenanceDocument(await this.storage.load(), this.limit); + if (document.entries.some((entry) => entry.chatId === chatId)) return; + document.entries.push({ chatId, ...provenance }); + await this.storage.save({ version: 1, entries: document.entries.slice(-this.limit) }); + }); + } + + async get(chatId: string): Promise { + const document = parseAidenMcpProvenanceDocument( + await this.serialize(() => this.storage.load()), + this.limit, + ); + const entry = document.entries.find((candidate) => candidate.chatId === chatId); + if (!entry) return undefined; + const { chatId: _chatId, ...provenance } = entry; + return provenance; + } + + private serialize(action: () => Promise): Promise { + const next = this.queue.then(action, action); + this.queue = next.catch(() => undefined); + return next; + } +} + +function shortString(value: unknown, max: number): value is string { + return typeof value === "string" && value.length > 0 && value.length <= max; +} diff --git a/main/services/aiden-mcp-server.test.ts b/main/services/aiden-mcp-server.test.ts new file mode 100644 index 0000000000..ff3a85ae05 --- /dev/null +++ b/main/services/aiden-mcp-server.test.ts @@ -0,0 +1,895 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { createServer, request as httpRequest, type IncomingHttpHeaders } from "node:http"; +import test from "node:test"; +import { McpClient, StreamableHttpTransport, type CallToolResult } from "@earendil-works/pi-mcp"; + +import { AIDEN_MCP_BODY_LIMIT, AidenMcpHost } from "./aiden-mcp-server.js"; +import { AidenMcpProvenanceLog, emptyAidenMcpProvenanceDocument, type AidenMcpProvenanceDocument } from "./aiden-mcp-provenance.js"; +import { AidenMcpToolRunner, type AidenMcpLimits } from "./aiden-mcp-tools.js"; +import { AidenRemoteChatService } from "./aiden-remote-chats.js"; +import { revokeAidenRemoteRuntimeDevice } from "./aiden-remote-revocation.js"; +import { + AidenRemoteStateRegistry, + createDefaultAidenRemoteState, + type AidenRemoteStateDocument, +} from "./aiden-remote-state.js"; +import { AidenRemoteStreamService } from "./aiden-remote-streams.js"; +import type { AidenRemoteWorkspaceProjection } from "./aiden-remote-workspaces.js"; +import { BotMutationGate } from "./bot-mutation-gate.js"; +import type { Chat, ChatMessage } from "./types.js"; + +type HeldRun = { + chatId: string; + approval(approvalId: string, toolName?: string): void; + finish(text?: string): void; +}; + +const WORKSPACES: AidenRemoteWorkspaceProjection[] = [ + { + id: "workspace-1", + name: "Website", + permission: "ask", + memoryEnabled: true, + hasFolder: true, + isManagedWorktree: false, + createdAt: "2026-11-01T00:00:00.000Z", + updatedAt: "2026-11-01T00:00:00.000Z", + revision: "workspace-rev-1", + }, + { + id: "no-workspace-1", + name: "Chat folder", + permission: "ask", + memoryEnabled: false, + hasFolder: true, + isManagedWorktree: false, + noWorkspace: true, + createdAt: "2026-11-01T00:00:00.000Z", + updatedAt: "2026-11-01T00:00:00.000Z", + revision: "workspace-rev-2", + }, + { + id: "assistant", + name: "Assistant", + permission: "ask", + memoryEnabled: false, + hasFolder: false, + isManagedWorktree: false, + createdAt: "2026-11-01T00:00:00.000Z", + updatedAt: "2026-11-01T00:00:00.000Z", + revision: "workspace-rev-3", + }, +]; + +async function freePort(): Promise { + const server = createServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + await new Promise((resolve) => server.close(() => resolve())); + if (!address || typeof address === "string") throw new Error("no port"); + return address.port; +} + +/** + * A real Remote registry, chat service and stream service behind a real MCP + * listener on loopback. Only the model run is fake: it either answers at once + * or stays running until the test finishes it. + */ +async function harness(options: { + hold?: boolean; + limits?: Partial; + supported?: boolean; + stored?: AidenRemoteStateDocument; + defaultPort?: number; +} = {}) { + let stored: unknown = options.stored ?? createDefaultAidenRemoteState(() => Buffer.alloc(24, 7)); + let random = 0; + let clock = 1_000_000; + const registry = new AidenRemoteStateRegistry( + { + load: async () => structuredClone(stored), + save: async (document) => { + stored = structuredClone(document); + }, + }, + { + now: () => clock, + randomBytes: (size) => Buffer.alloc(size, ++random), + deriveCredentialDigest: async (credential, salt) => + createHash("sha256").update(credential).update(salt).digest(), + }, + ); + await registry.initialize(); + + const chats = new Map(); + const held = new Map(); + const cancelled: string[] = []; + const settled: Array<{ approvalId: string; decision: string }> = []; + let generationStarts = 0; + let lastText: unknown; + + const finishRun = (streamId: string, text = "Answer") => { + const run = held.get(streamId); + run?.finish(text); + }; + + const streams = new AidenRemoteStreamService({ + now: () => Date.now(), + cancel: (streamId) => { + cancelled.push(streamId); + // The model stops and reports it, as a real run does. + setImmediate(() => finishRun(streamId)); + return true; + }, + approve: (approvalId, decision) => { + settled.push({ approvalId, decision }); + return true; + }, + }); + + const stub = async (): Promise => { + throw new Error("not used by the MCP server"); + }; + const service = new AidenRemoteChatService({ + application: { + list: async () => [...chats.values()].map((chat) => structuredClone(chat)), + listRegular: async () => [...chats.values()].map((chat) => structuredClone(chat)), + listSummaryMetadata: async () => [...chats.values()].map((chat) => structuredClone(chat)), + get: async (id: string) => ({ + chat: chats.has(id) ? structuredClone(chats.get(id)!) : null, + imageArtifactRecoveryPending: false, + imageArtifactRecoveryUnavailable: false, + reconciliation: null, + }), + create: async (input) => { + const chat: Chat = { + id: `chat-${chats.size + 1}`, + title: "New chat", + workspaceId: input.workspaceId, + providerId: input.providerId ?? "provider-1", + model: input.model ?? "model-1", + createdAt: 1_000, + updatedAt: 2_000, + messages: [], + }; + chats.set(chat.id, chat); + return structuredClone(chat); + }, + rename: stub, + moveEmptyToWorkspace: stub, + remove: stub, + }, + chatStore: { + get: async (id) => (chats.has(id) ? structuredClone(chats.get(id)!) : null), + appendMessage: async (id, message, meta) => { + const chat = chats.get(id); + if (!chat || !meta?.isCurrent?.()) throw new Error("stale"); + chat.messages.push({ + id: message.id!, + role: message.role, + content: message.content, + createdAt: 3_000, + }); + chat.updatedAt += 1; + return structuredClone(chat); + }, + }, + generation: { + beginChatTurn: () => { + let active = true; + return { + isActive: () => active, + reserveAppendPayload: () => undefined, + reserveSkillPreparation: () => undefined, + prepareSkillInvocation: () => undefined, + settleAsyncWork: () => undefined, + onReleased: () => undefined, + release: () => { + active = false; + }, + }; + }, + start: async (streamId, params, owner, generationOptions) => { + generationStarts += 1; + lastText = (params as unknown as { content?: unknown }).content; + generationOptions.onTurnAccepted(); + const chatId = (params as unknown as { chatId: string }).chatId; + let finished = false; + const run: HeldRun = { + chatId, + approval: (approvalId, toolName = "bash") => + owner.send("chat:approval", { + approvalId, + toolCallId: `call-${approvalId}`, + toolName, + summary: "Run the test suite", + }), + finish: (text = "Answer") => { + // A run whose owner was released (its app was disconnected) reports nothing more. + if (finished || owner.isDestroyed()) return; + finished = true; + const chat = chats.get(chatId)!; + const assistant: ChatMessage = { id: `assistant-${streamId}`, role: "assistant", content: text, createdAt: 4_000 }; + chat.messages.push(assistant); + owner.send("chat:done", { streamId, chat: structuredClone(chat) }); + }, + }; + held.set(streamId, run); + if (!options.hold) run.finish(); + return true; + }, + }, + streams, + models: { + resolve: async (providerId, modelId) => ({ + providerId: providerId ?? "provider-1", + modelId: modelId ?? "model-1", + thinkingLevels: ["low", "high"], + supportsImages: true, + }), + }, + // One real Bot, so its chat classifies as a Bot chat rather than a missing one. + bots: { get: async (id: string) => (id === "bot-1" ? ({ id: "bot-1", name: "Ada" } as never) : null) }, + botMutations: new BotMutationGate(), + botTurnAuthorityPreflight: async () => undefined, + }); + + let provenanceDocument: AidenMcpProvenanceDocument = emptyAidenMcpProvenanceDocument(); + const provenance = new AidenMcpProvenanceLog({ + load: async () => structuredClone(provenanceDocument), + save: async (document) => { + provenanceDocument = structuredClone(document); + }, + }); + const tools = new AidenMcpToolRunner({ + services: async () => ({ chats: service, streams, workspaces: { list: async () => ({ workspaces: WORKSPACES }) } }), + acquireAuthorization: (appId, tracksMutationDrain) => registry.acquireDeviceAuthorization(appId, tracksMutationDrain), + recordProvenance: (chatId, entry) => provenance.record(chatId, entry), + appVersion: "9.9.9", + hostName: async () => "Studio Mac", + now: () => clock, + ...(options.limits ? { limits: options.limits } : {}), + }); + const host = new AidenMcpHost({ + state: registry, + tools, + supported: () => options.supported ?? true, + defaultPort: options.defaultPort ?? (await freePort()), + revokeDevice: (deviceId) => + revokeAidenRemoteRuntimeDevice( + { state: registry, streams, chats: service, workspaceOwners: { revokeDevice: () => undefined } }, + deviceId, + ), + appVersion: "9.9.9", + }); + + const clients: McpClient[] = []; + /** An outside app, connected the way Claude Code or Codex connects (GET stream attempt included). */ + const connect = async (credential: string) => { + const status = await host.status(); + const client = new McpClient({ name: "test-app", version: "1.0.0" }); + await client.connect( + new StreamableHttpTransport({ url: status.url!, headers: { authorization: `Bearer ${credential}` } }), + ); + clients.push(client); + return { + listTools: async () => ({ tools: await client.listTools() }), + callTool: ({ name, arguments: args }: { name: string; arguments?: Record }) => + client.callTool(name, args), + }; + }; + + return { + registry, + host, + streams, + chats, + held, + cancelled, + settled, + connect, + stored: () => structuredClone(stored) as AidenRemoteStateDocument, + provenance: () => structuredClone(provenanceDocument), + generationStarts: () => generationStarts, + lastText: () => lastText, + advance: (ms: number) => { + clock += ms; + }, + async enable() { + const status = await host.setEnabled(true); + assert.equal(status.running, true); + return status; + }, + async close() { + for (const client of clients) await client.close().catch(() => undefined); + await host.stop(); + }, + }; +} + +function structured(result: unknown): Record { + const call = result as CallToolResult; + assert.notEqual(call.isError, true, JSON.stringify(call.content)); + return call.structuredContent as Record; +} + +function refusal(result: unknown): string { + const call = result as CallToolResult; + assert.equal(call.isError, true); + const first = call.content[0]; + assert.equal(first?.type, "text"); + return (first as { text: string }).text; +} + +const INITIALIZE = JSON.stringify({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "raw", version: "1" } }, +}); + +/** A raw request, so tests can send the Host and Origin headers a browser would. */ +function raw( + port: number, + options: { method?: string; path?: string; headers?: Record; body?: string | Buffer; chunked?: boolean }, +): Promise<{ status: number; headers: IncomingHttpHeaders; body: string }> { + return new Promise((resolve, reject) => { + const body = options.body ?? ""; + const request = httpRequest( + { + host: "127.0.0.1", + port, + path: options.path ?? "/mcp", + method: options.method ?? "POST", + headers: { + host: `127.0.0.1:${port}`, + "content-type": "application/json", + accept: "application/json, text/event-stream", + ...(options.chunked ? { "transfer-encoding": "chunked" } : { "content-length": String(Buffer.byteLength(body)) }), + ...options.headers, + }, + }, + (response) => { + responded = true; + const chunks: Buffer[] = []; + response.on("data", (chunk) => chunks.push(Buffer.from(chunk))); + response.on("end", () => { + resolve({ status: response.statusCode ?? 0, headers: response.headers, body: Buffer.concat(chunks).toString("utf8") }); + request.destroy(); + }); + }, + ); + let responded = false; + request.once("error", (error: NodeJS.ErrnoException) => { + // Once the answer is in, a hang-up on the rest of an oversized upload is expected. + if (responded && (error.code === "EPIPE" || error.code === "ECONNRESET")) return; + reject(error); + }); + if (options.chunked) { + const piece = Buffer.alloc(64 * 1024, 0x20); + let sent = 0; + const pump = () => { + while (!responded && sent < AIDEN_MCP_BODY_LIMIT + piece.length) { + sent += piece.length; + if (!request.write(piece)) { + request.once("drain", pump); + return; + } + } + request.end(); + }; + pump(); + } else { + request.end(body); + } + }); +} + +test("the MCP server is off until turned on, keeps its port, and reports a busy saved port", async () => { + const first = await harness(); + try { + assert.deepEqual(await first.host.status(), { supported: true, enabled: false, running: false }); + const on = await first.enable(); + assert.equal(on.enabled, true); + assert.equal(on.url, `http://127.0.0.1:${on.port}/mcp`); + const off = await first.host.setEnabled(false); + assert.equal(off.running, false); + assert.equal(off.port, on.port); + await first.enable(); + } finally { + await first.close(); + } + + // After a restart the same URL keeps working for every connected app. + const saved = first.stored(); + const second = await harness({ stored: saved }); + try { + const status = await second.host.initialize(); + assert.equal(status.running, true); + assert.equal(status.port, saved.mcpServer?.port); + } finally { + await second.close(); + } + + // Another app took the saved port: Aiden says so instead of moving silently. + const squatter = createServer(); + await new Promise((resolve) => squatter.listen(saved.mcpServer!.port!, "127.0.0.1", resolve)); + const third = await harness({ stored: saved }); + try { + const status = await third.host.initialize(); + assert.equal(status.running, false); + assert.equal(status.problem, "port_in_use"); + assert.equal(status.port, saved.mcpServer?.port); + } finally { + await third.close(); + await new Promise((resolve) => squatter.close(() => resolve())); + } +}); + +test("a host without the MCP capability never starts the server or connects an app", async () => { + const unsupported = await harness({ supported: false }); + try { + await assert.rejects(unsupported.host.setEnabled(true), /cannot run Aiden's MCP server/u); + await assert.rejects(unsupported.host.issueApp({ name: "Codex", access: "read" }), /cannot run/u); + assert.deepEqual(await unsupported.host.status(), { supported: false, enabled: false, running: false }); + } finally { + await unsupported.close(); + } +}); + +test("a missing, wrong or revoked token gets 401 and no tool runs", async () => { + const fixture = await harness(); + try { + const { port } = await fixture.enable(); + const { credential, app } = await fixture.host.issueApp({ name: "Claude Code", access: "supervised" }); + for (const authorization of [undefined, `Bearer ${"x".repeat(43)}`, `Basic ${credential}`, credential]) { + const response = await raw(port!, { + body: INITIALIZE, + ...(authorization ? { headers: { authorization } } : {}), + }); + assert.equal(response.status, 401); + assert.match(String(response.headers["www-authenticate"]), /^Bearer /u); + } + const client = await fixture.connect(credential); + assert.ok((await client.listTools()).tools.length > 0); + + assert.equal(await fixture.host.revokeApp(app.id), true); + const after = await raw(port!, { body: INITIALIZE, headers: { authorization: `Bearer ${credential}` } }); + assert.equal(after.status, 401); + await assert.rejects(client.listTools()); + assert.equal(fixture.generationStarts(), 0); + } finally { + await fixture.close(); + } +}); + +test("a phone's or a Mac's Remote credential is refused on /mcp, and cannot be revoked as an app", async () => { + const fixture = await harness(); + try { + const { port } = await fixture.enable(); + for (const type of ["iphone", "mac"] as const) { + const paired = await fixture.registry.issueDevice({ + name: type, + type, + clientVersion: "1", + capabilities: ["server:read", "chat:read", "chat:write"], + }); + const response = await raw(port!, { body: INITIALIZE, headers: { authorization: `Bearer ${paired.credential}` } }); + assert.equal(response.status, 401); + // The app controls only disconnect outside apps. + assert.equal(await fixture.host.revokeApp(paired.device.id), false); + assert.equal((await fixture.registry.authenticate(paired.credential))?.revoked, false); + } + } finally { + await fixture.close(); + } +}); + +test("a foreign Host or Origin is refused, so a web page cannot reach the server by DNS rebinding", async () => { + const fixture = await harness(); + try { + const { port } = await fixture.enable(); + const { credential } = await fixture.host.issueApp({ name: "Codex", access: "read" }); + const authorization = `Bearer ${credential}`; + const refused: Array> = [ + { host: `attacker.example:${port}` }, + { host: "127.0.0.1" }, + { host: `127.0.0.1:${port! + 1}` }, + { host: `127.0.0.1:${port}`, origin: "https://attacker.example" }, + { host: `127.0.0.1:${port}`, origin: `http://attacker.example:${port}` }, + { host: `127.0.0.1:${port}`, origin: "null" }, + ]; + for (const headers of refused) { + const response = await raw(port!, { body: INITIALIZE, headers: { authorization, ...headers } }); + assert.equal(response.status, 403, JSON.stringify(headers)); + assert.equal(response.headers["access-control-allow-origin"], undefined); + } + // A browser preflight gets no CORS grant either. + const preflight = await raw(port!, { + method: "OPTIONS", + headers: { origin: "https://attacker.example", "access-control-request-method": "POST" }, + }); + assert.equal(preflight.status, 403); + assert.equal(preflight.headers["access-control-allow-origin"], undefined); + + for (const host of [`localhost:${port}`, `127.0.0.1:${port}`]) { + const response = await raw(port!, { + body: INITIALIZE, + headers: { authorization, host, origin: `http://${host}` }, + }); + assert.equal(response.status, 200); + assert.equal(response.headers["access-control-allow-origin"], undefined); + } + } finally { + await fixture.close(); + } +}); + +test("a request body over 1 MiB is refused before any tool runs", async () => { + const fixture = await harness(); + try { + const { port } = await fixture.enable(); + const { credential } = await fixture.host.issueApp({ name: "Codex", access: "supervised" }); + const authorization = `Bearer ${credential}`; + const call = (text: string) => + JSON.stringify({ + jsonrpc: "2.0", + id: 2, + method: "tools/call", + params: { + name: "aiden_chat_start", + arguments: { clientRequestId: "request-0001", workspaceId: "workspace-1", text }, + }, + }); + const oversized = call("x".repeat(AIDEN_MCP_BODY_LIMIT)); + const declared = await raw(port!, { body: oversized, headers: { authorization } }); + assert.equal(declared.status, 413); + // An upload that never declares its length is cut off at the limit too. + const streamed = await raw(port!, { chunked: true, headers: { authorization } }); + assert.equal(streamed.status, 413); + const malformed = await raw(port!, { body: "{", headers: { authorization } }); + assert.equal(malformed.status, 400); + assert.equal(JSON.parse(malformed.body).error.code, -32700); + assert.equal(fixture.chats.size, 0); + assert.equal(fixture.generationStarts(), 0); + } finally { + await fixture.close(); + } +}); + +test("a Read app sees only read tools and cannot start, send or stop a turn", async () => { + const fixture = await harness({ hold: true }); + try { + await fixture.enable(); + const writer = await fixture.connect((await fixture.host.issueApp({ name: "Writer", access: "supervised" })).credential); + const started = structured( + await writer.callTool({ + name: "aiden_chat_start", + arguments: { clientRequestId: "writer-request-1", workspaceId: "workspace-1", text: "Hello" }, + }), + ); + + const reader = await fixture.connect((await fixture.host.issueApp({ name: "Reader", access: "read" })).credential); + const listed = (await reader.listTools()).tools; + assert.deepEqual(listed.map((tool) => tool.name).sort(), [ + "aiden_chat_list", + "aiden_chat_read", + "aiden_chat_wait", + "aiden_server_info", + "aiden_workspace_list", + ]); + assert.ok(listed.every((tool) => tool.annotations?.readOnlyHint === true)); + const info = structured(await reader.callTool({ name: "aiden_server_info", arguments: {} })); + assert.deepEqual(info.app, { name: "Reader", access: "read" }); + assert.equal(info.computer, "Studio Mac"); + + const readOnly = "This app is connected to Aiden with Read access, so it cannot start, send or stop turns."; + assert.equal( + refusal( + await reader.callTool({ + name: "aiden_chat_start", + arguments: { clientRequestId: "reader-request-1", workspaceId: "workspace-1", text: "Hi" }, + }), + ), + readOnly, + ); + assert.equal( + refusal( + await reader.callTool({ + name: "aiden_chat_send", + arguments: { clientRequestId: "reader-request-2", chatId: started.chatId, text: "Hi" }, + }), + ), + readOnly, + ); + assert.equal( + refusal(await reader.callTool({ name: "aiden_chat_stop", arguments: { chatId: started.chatId, runId: started.runId } })), + readOnly, + ); + assert.equal(fixture.chats.size, 1); + assert.equal(fixture.generationStarts(), 1); + assert.deepEqual(fixture.cancelled, []); + + // Reads work, and the no-workspace folders Aiden makes for one chat are not offered. + const workspaces = structured(await reader.callTool({ name: "aiden_workspace_list", arguments: {} })); + assert.deepEqual(workspaces.workspaces, [ + { id: "workspace-1", name: "Website", hasFolder: true, toolPermission: "ask" }, + ]); + assert.equal( + refusal(await reader.callTool({ name: "aiden_chat_read", arguments: { chatId: "chat 1" } })), + "The arguments do not match the tool's schema.", + ); + } finally { + await fixture.close(); + } +}); + +test("aiden_chat_start with the same clientRequestId starts one chat and one turn", async () => { + const fixture = await harness(); + try { + await fixture.enable(); + const { credential, app } = await fixture.host.issueApp({ name: "Claude Code", access: "supervised" }); + const client = await fixture.connect(credential); + const args = { clientRequestId: "retry-request-1", workspaceId: "workspace-1", text: "Summarize the README" }; + const [first, second] = await Promise.all([ + client.callTool({ name: "aiden_chat_start", arguments: args }), + client.callTool({ name: "aiden_chat_start", arguments: args }), + ]); + const third = await client.callTool({ name: "aiden_chat_start", arguments: args }); + assert.deepEqual(structured(second), structured(first)); + assert.deepEqual(structured(third), structured(first)); + assert.equal(fixture.chats.size, 1); + assert.equal(fixture.generationStarts(), 1); + const started = structured(first); + assert.equal(started.state, "running"); + + const finished = structured( + await client.callTool({ name: "aiden_chat_wait", arguments: { chatId: started.chatId, runId: started.runId } }), + ); + assert.equal(finished.state, "done"); + assert.equal(finished.outcome, "completed"); + assert.equal((finished.reply as { text: string }).text, "Answer"); + + const read = structured(await client.callTool({ name: "aiden_chat_read", arguments: { chatId: started.chatId } })); + assert.deepEqual( + (read.messages as Array<{ role: string; text: string }>).map(({ role, text }) => [role, text]), + [ + ["user", "Summarize the README"], + ["assistant", "Answer"], + ], + ); + + // Which app started the chat is noted on this computer only, never in what any client reads. + assert.deepEqual(fixture.provenance().entries.map(({ chatId, kind, appId, name }) => ({ chatId, kind, appId, name })), [ + { chatId: started.chatId, kind: "app", appId: app.id, name: "Claude Code" }, + ]); + const list = await client.callTool({ name: "aiden_chat_list", arguments: {} }); + assert.equal(JSON.stringify(list).includes(app.id), false); + assert.equal(JSON.stringify(read).includes(app.id), false); + + // A different id is a different request. + const another = structured( + await client.callTool({ name: "aiden_chat_start", arguments: { ...args, clientRequestId: "retry-request-2" } }), + ); + assert.notEqual(another.chatId, started.chatId); + assert.equal(fixture.generationStarts(), 2); + } finally { + await fixture.close(); + } +}); + +test("an approval waits for the person in Aiden; the app can see it but never answer it", async () => { + const fixture = await harness({ hold: true }); + try { + await fixture.enable(); + const { credential } = await fixture.host.issueApp({ name: "Claude Code", access: "supervised" }); + assert.equal((await fixture.registry.authenticate(credential))?.capabilities.has("approval:respond"), false); + const client = await fixture.connect(credential); + const started = structured( + await client.callTool({ + name: "aiden_chat_start", + arguments: { clientRequestId: "approval-request-1", workspaceId: "workspace-1", text: "Run the tests" }, + }), + ); + const runId = started.runId as string; + const waiting = client.callTool({ name: "aiden_chat_wait", arguments: { chatId: started.chatId, runId, timeoutSeconds: 20 } }); + setTimeout(() => fixture.held.get(runId)!.approval("approval-1"), 50); + const approval = structured(await waiting); + assert.equal(approval.state, "waiting_for_approval"); + assert.equal(approval.approveIn, "Aiden on Studio Mac"); + assert.equal((approval.approval as { toolName: string }).toolName, "bash"); + + // There is no tool for it, and naming one does nothing. + const names = (await client.listTools()).tools.map((tool) => tool.name); + assert.equal(names.some((name) => /approv|question|answer|respond/u.test(name)), false); + for (const name of ["aiden_approval_respond", "aiden_chat_approve"]) { + assert.equal( + refusal(await client.callTool({ name, arguments: { approvalId: "approval-1", decision: "allow" } })), + "Aiden has no tool with that name.", + ); + } + // Waiting again does not settle it either. + const still = structured( + await client.callTool({ name: "aiden_chat_wait", arguments: { chatId: started.chatId, runId, timeoutSeconds: 1 } }), + ); + assert.equal(still.state, "waiting_for_approval"); + assert.deepEqual(fixture.settled, []); + + // The person allows it in Aiden on this computer, and the run carries on. + assert.equal(fixture.streams.respondApprovalFromHost(started.chatId as string, "approval-1", "allow"), true); + assert.deepEqual(fixture.settled, [{ approvalId: "approval-1", decision: "allow" }]); + fixture.held.get(runId)!.finish("All green"); + const done = structured(await client.callTool({ name: "aiden_chat_wait", arguments: { chatId: started.chatId, runId } })); + assert.equal(done.state, "done"); + assert.equal((done.reply as { text: string }).text, "All green"); + } finally { + await fixture.close(); + } +}); + +test("an app stops only its own runs, and another app cannot see them", async () => { + const fixture = await harness({ hold: true }); + try { + await fixture.enable(); + const owner = await fixture.connect((await fixture.host.issueApp({ name: "Owner", access: "supervised" })).credential); + const other = await fixture.connect((await fixture.host.issueApp({ name: "Other", access: "supervised" })).credential); + const started = structured( + await owner.callTool({ + name: "aiden_chat_start", + arguments: { clientRequestId: "stop-request-1", workspaceId: "workspace-1", text: "Long job" }, + }), + ); + const target = { chatId: started.chatId, runId: started.runId }; + const notTracked = "Aiden no longer tracks this run. Read the chat with aiden_chat_read for its result."; + assert.equal(refusal(await other.callTool({ name: "aiden_chat_stop", arguments: target })), notTracked); + assert.equal(refusal(await other.callTool({ name: "aiden_chat_wait", arguments: { ...target, timeoutSeconds: 1 } })), notTracked); + assert.deepEqual(fixture.cancelled, []); + + assert.deepEqual(structured(await owner.callTool({ name: "aiden_chat_stop", arguments: target })), { ...target, stopped: true }); + assert.deepEqual(fixture.cancelled, [started.runId]); + const stopped = structured(await owner.callTool({ name: "aiden_chat_wait", arguments: target })); + assert.equal(stopped.state, "done"); + assert.equal(stopped.outcome, "stopped"); + // Stopping a finished run does nothing. + assert.deepEqual(structured(await owner.callTool({ name: "aiden_chat_stop", arguments: target })), { + ...target, + stopped: false, + state: "done", + }); + assert.deepEqual(fixture.cancelled, [started.runId]); + } finally { + await fixture.close(); + } +}); + +test("disconnecting an app ends its wait, stops its run and retires its token", async () => { + const fixture = await harness({ hold: true }); + try { + await fixture.enable(); + const { credential, app } = await fixture.host.issueApp({ name: "Claude Code", access: "supervised" }); + const client = await fixture.connect(credential); + const started = structured( + await client.callTool({ + name: "aiden_chat_start", + arguments: { clientRequestId: "revoke-request-1", workspaceId: "workspace-1", text: "Long job" }, + }), + ); + const begun = Date.now(); + const waiting = client.callTool({ + name: "aiden_chat_wait", + arguments: { chatId: started.chatId, runId: started.runId, timeoutSeconds: 30 }, + }); + await new Promise((resolve) => setTimeout(resolve, 100)); + assert.equal(await fixture.host.revokeApp(app.id), true); + assert.equal(refusal(await waiting), "This app was disconnected from Aiden."); + assert.ok(Date.now() - begun < 10_000); + assert.deepEqual(fixture.cancelled, [started.runId]); + assert.equal((await fixture.host.listApps()).find((entry) => entry.id === app.id)?.revokedAt !== undefined, true); + await assert.rejects(client.callTool({ name: "aiden_chat_list", arguments: {} })); + } finally { + await fixture.close(); + } +}); + +test("each app has its own turn rate limit and run cap, and a retry does not count twice", async () => { + const fixture = await harness({ hold: true, limits: { turnsPerMinute: 3, concurrentRuns: 2 } }); + try { + await fixture.enable(); + const client = await fixture.connect((await fixture.host.issueApp({ name: "Busy", access: "supervised" })).credential); + const start = (id: string) => + client.callTool({ name: "aiden_chat_start", arguments: { clientRequestId: id, workspaceId: "workspace-1", text: "Go" } }); + + const first = structured(await start("limit-request-1")); + const second = structured(await start("limit-request-2")); + // Replaying a request it already made is not a new turn. + assert.deepEqual(structured(await start("limit-request-2")), second); + assert.equal( + refusal(await start("limit-request-3")), + "This app already has 2 runs going in Aiden. Wait for one to finish or stop one first.", + ); + fixture.held.get(first.runId as string)!.finish(); + await client.callTool({ name: "aiden_chat_wait", arguments: { chatId: first.chatId, runId: first.runId } }); + const third = structured(await start("limit-request-3")); + fixture.held.get(third.runId as string)!.finish(); + await client.callTool({ name: "aiden_chat_wait", arguments: { chatId: third.chatId, runId: third.runId } }); + + assert.equal( + refusal(await start("limit-request-4")), + "This app started 3 turns in the last minute. Try again in 60 seconds.", + ); + assert.equal( + refusal( + await client.callTool({ + name: "aiden_chat_send", + arguments: { clientRequestId: "limit-send-1", chatId: first.chatId, text: "More" }, + }), + ), + "This app started 3 turns in the last minute. Try again in 60 seconds.", + ); + assert.equal(fixture.generationStarts(), 3); + + // Another app is not held back by this one. + const neighbour = await fixture.connect((await fixture.host.issueApp({ name: "Calm", access: "supervised" })).credential); + structured( + await neighbour.callTool({ + name: "aiden_chat_start", + arguments: { clientRequestId: "neighbour-request-1", workspaceId: "workspace-1", text: "Hi" }, + }), + ); + + fixture.advance(61_000); + structured(await start("limit-request-4")); + assert.equal(fixture.generationStarts(), 5); + } finally { + await fixture.close(); + } +}); + +test("Bot chats and the folders Aiden makes for one chat are out of an app's reach", async () => { + const fixture = await harness(); + try { + await fixture.enable(); + fixture.chats.set("bot-chat-1", { + id: "bot-chat-1", + title: "Ada", + workspaceId: "workspace-1", + botId: "bot-1", + createdAt: 1_000, + updatedAt: 9_000, + messages: [{ id: "bot-message-1", role: "assistant", content: "Private Bot note", createdAt: 1_500 }], + } as Chat); + const client = await fixture.connect((await fixture.host.issueApp({ name: "Codex", access: "supervised" })).credential); + + const listed = structured(await client.callTool({ name: "aiden_chat_list", arguments: {} })); + assert.deepEqual(listed.chats, []); + const missing = "This Aiden chat no longer exists."; + assert.equal(refusal(await client.callTool({ name: "aiden_chat_read", arguments: { chatId: "bot-chat-1" } })), missing); + assert.equal( + refusal( + await client.callTool({ + name: "aiden_chat_send", + arguments: { clientRequestId: "bot-send-0001", chatId: "bot-chat-1", text: "Hi Ada" }, + }), + ), + missing, + ); + + for (const workspaceId of ["no-workspace-1", "assistant", "workspace-missing"]) { + assert.equal( + refusal( + await client.callTool({ + name: "aiden_chat_start", + arguments: { clientRequestId: `hidden-${workspaceId}`, workspaceId, text: "Hi" }, + }), + ), + "Aiden has no workspace with that id. List them with aiden_workspace_list.", + ); + } + assert.equal(fixture.chats.size, 1); + assert.equal(fixture.chats.get("bot-chat-1")!.messages.length, 1); + assert.equal(fixture.generationStarts(), 0); + } finally { + await fixture.close(); + } +}); diff --git a/main/services/aiden-mcp-server.ts b/main/services/aiden-mcp-server.ts new file mode 100644 index 0000000000..68b95715af --- /dev/null +++ b/main/services/aiden-mcp-server.ts @@ -0,0 +1,393 @@ +/** + * Aiden's MCP server: lets other apps on this computer (Claude Code, Codex, + * ...) read Aiden chats and, when the person allows it, start turns in them. + * + * Ported in spirit from T3 Code's MCP server (pingdotgg/t3code#33196) and + * hardened like `acp/mcp-bridge.ts`: stateless Streamable HTTP with one SDK + * server per request, a 1 MiB body limit, schema-checked arguments and + * `aiden_`-prefixed tools. It has its own listener on 127.0.0.1 only, never + * the Remote Access LAN listener, and it checks Host and Origin so a web page + * cannot reach it through DNS rebinding. It sends no CORS headers. + * + * Only an outside-app credential (device type `agent`) is accepted here, and + * `/api/aiden/v1` refuses those credentials, so a phone token never works on + * `/mcp` and an app token never works on the Remote API. See + * `docs/aiden-mcp-server.md`. + */ +import { Server } from "@modelcontextprotocol/sdk/server/index.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; +import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js"; +import { createServer, type IncomingMessage, type Server as HttpServer, type ServerResponse } from "node:http"; + +import type { AidenMcpApp, AidenMcpToolRunner } from "./aiden-mcp-tools.js"; +import type { + AidenRemoteAgentAccess, + AidenRemoteAgentAppProjection, + AidenRemoteAuthenticatedDevice, + AidenRemoteStateRegistry, +} from "./aiden-remote-state.js"; + +export const AIDEN_MCP_PATH = "/mcp"; +export const AIDEN_MCP_BODY_LIMIT = 1024 * 1024; +const OVERSIZED_DRAIN_MS = 5_000; +/** Loopback ports clear of the Remote Access LAN ranges (49220+ and 50220+). */ +export const AIDEN_MCP_PRODUCTION_PORT = 49_400; +export const AIDEN_MCP_DEVELOPMENT_PORT = 50_400; +const DEFAULT_PORT_ATTEMPTS = 8; +const MAX_CONNECTIONS = 16; +const BEARER = /^Bearer ([A-Za-z0-9_-]{43})$/u; + +export class AidenMcpPortInUseError extends Error { + constructor(readonly port: number) { + super(`Another app is using port ${port}.`); + this.name = "AidenMcpPortInUseError"; + } +} + +export interface AidenMcpServerOptions { + apps: { authenticate(credential: string): Promise }; + tools: AidenMcpToolRunner; + appVersion: string; + /** Category-only events; never a credential, path, chat text or app name. */ + log?(event: string, details?: Record): void; +} + +/** The ports to try, in order: the one saved earlier, or else the profile default and its neighbours. */ +export function aidenMcpPortCandidates(savedPort: number | undefined, defaultPort: number): number[] { + if (savedPort !== undefined) return [savedPort]; + return Array.from({ length: DEFAULT_PORT_ATTEMPTS }, (_, index) => defaultPort + index); +} + +export class AidenMcpServer { + private server: HttpServer | undefined; + private boundPort: number | undefined; + + constructor(private readonly options: AidenMcpServerOptions) {} + + get port(): number | undefined { + return this.boundPort; + } + + get url(): string | undefined { + return this.boundPort === undefined ? undefined : `http://127.0.0.1:${this.boundPort}${AIDEN_MCP_PATH}`; + } + + /** + * Listens on the first free candidate. A saved port that is busy is an + * error rather than a silent move, because every connected app has that + * URL saved; with no saved port, port 0 lets the system choose as a last + * resort. + */ + async start(candidates: readonly number[], allowAnyPort = false): Promise { + if (this.server && this.boundPort !== undefined) return this.boundPort; + const ports = allowAnyPort ? [...candidates, 0] : [...candidates]; + let lastBusy: number | undefined; + for (const port of ports) { + const server = createServer((request, response) => { + void this.handle(request, response).catch(() => { + this.options.log?.("request-failed"); + if (!response.headersSent) response.writeHead(500, { "content-type": "application/json" }); + response.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32603, message: "Aiden error" } })); + }); + }); + server.maxConnections = MAX_CONNECTIONS; + try { + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(port, "127.0.0.1", () => { + server.off("error", reject); + resolve(); + }); + }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "EADDRINUSE") { + lastBusy = port; + continue; + } + throw error; + } + const address = server.address(); + if (!address || typeof address === "string") { + server.close(); + throw new Error("The MCP server could not start."); + } + this.server = server; + this.boundPort = address.port; + this.options.log?.("started"); + return address.port; + } + throw new AidenMcpPortInUseError(lastBusy ?? candidates[0] ?? 0); + } + + async close(): Promise { + const server = this.server; + this.server = undefined; + this.boundPort = undefined; + if (!server) return; + server.closeAllConnections?.(); + await new Promise((resolve) => server.close(() => resolve())); + this.options.log?.("stopped"); + } + + private async handle(request: IncomingMessage, response: ServerResponse): Promise { + const port = this.boundPort; + if (port === undefined || !allowedHost(request.headers.host, port) || !allowedOrigin(request.headers.origin, port)) { + // A DNS-rebinding page arrives with a foreign Host or Origin. + response.writeHead(403, { "content-type": "text/plain; charset=utf-8" }).end("Forbidden"); + return; + } + if (request.url !== AIDEN_MCP_PATH) { + response.writeHead(404).end(); + return; + } + if (request.method !== "POST") { + // Stateless: no standalone event stream and no sessions to delete. + response.writeHead(405, { allow: "POST" }).end(); + return; + } + const app = await this.authenticate(request.headers.authorization); + if (!app) { + response.writeHead(401, { "www-authenticate": 'Bearer realm="aiden"' }).end(); + return; + } + let body: unknown; + try { + body = await readJson(request); + } catch (error) { + if (error instanceof BodyTooLargeError) { + // Drain what the app is still uploading so the 413 reaches it; closing + // the socket mid-upload resets it and the app sees only a broken pipe. + // An upload that keeps going past the grace period is cut off. + const cutOff = setTimeout(() => request.socket.destroy(), OVERSIZED_DRAIN_MS); + cutOff.unref(); + request.once("end", () => clearTimeout(cutOff)); + request.once("close", () => clearTimeout(cutOff)); + request.resume(); + response.writeHead(413).end(); + return; + } + response.writeHead(400, { "content-type": "application/json" }); + response.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } })); + return; + } + + // A long wait ends as soon as the app hangs up. + const closed = new AbortController(); + response.once("close", () => closed.abort()); + + const protocol = new Server( + { name: "aiden", version: this.options.appVersion }, + { capabilities: { tools: {} } }, + ); + protocol.setRequestHandler(ListToolsRequestSchema, () => ({ tools: this.options.tools.list(app) })); + protocol.setRequestHandler(CallToolRequestSchema, (call) => + this.options.tools.call(app, call.params.name, call.params.arguments, closed.signal), + ); + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true }); + try { + await protocol.connect(transport); + await transport.handleRequest(request, response, body); + } finally { + await transport.close(); + await protocol.close(); + } + } + + private async authenticate(header: string | undefined): Promise { + const match = BEARER.exec(header ?? ""); + if (!match) return null; + const device = await this.options.apps.authenticate(match[1]!); + // A phone's or Mac's credential reads exactly like an unknown one here. + if (!device || device.type !== "agent" || device.revoked) return null; + return { id: device.id, name: device.name, capabilities: device.capabilities }; + } +} + +class BodyTooLargeError extends Error {} + +/** + * Reads at most the body limit. Past it, the rest is drained and dropped + * rather than the request destroyed: destroying it closes the socket, and the + * app would never see the 413. + */ +function readJson(request: IncomingMessage): Promise { + const declared = Number(request.headers["content-length"]); + if (Number.isFinite(declared) && declared > AIDEN_MCP_BODY_LIMIT) return Promise.reject(new BodyTooLargeError()); + return new Promise((resolve, reject) => { + const chunks: Buffer[] = []; + let size = 0; + let tooLarge = false; + request.on("data", (chunk: Buffer | string) => { + if (tooLarge) return; + const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); + size += bytes.length; + if (size > AIDEN_MCP_BODY_LIMIT) { + tooLarge = true; + chunks.length = 0; + reject(new BodyTooLargeError()); + return; + } + chunks.push(bytes); + }); + request.once("end", () => { + if (tooLarge) return; + try { + resolve(JSON.parse(Buffer.concat(chunks).toString("utf8"))); + } catch (error) { + reject(error); + } + }); + request.once("error", reject); + }); +} + +function allowedHost(host: string | undefined, port: number): boolean { + if (!host) return false; + const value = host.toLowerCase(); + return value === `127.0.0.1:${port}` || value === `localhost:${port}`; +} + +/** Command-line apps send no Origin. A browser may only come from this server's own origin. */ +function allowedOrigin(origin: string | undefined, port: number): boolean { + if (origin === undefined) return true; + const value = origin.toLowerCase(); + return value === `http://127.0.0.1:${port}` || value === `http://localhost:${port}`; +} + +export type AidenMcpServerProblem = "port_in_use" | "start_failed"; + +export interface AidenMcpServerStatus { + /** False where this host cannot offer the MCP server at all. */ + supported: boolean; + enabled: boolean; + running: boolean; + port?: number; + /** The URL an outside app is configured with. */ + url?: string; + problem?: AidenMcpServerProblem; +} + +type AidenMcpListener = Pick; + +export interface AidenMcpHostDependencies { + state: Pick< + AidenRemoteStateRegistry, + "mcpServerSettings" | "setMcpServerEnabled" | "commitMcpServerPort" | "issueAgentApp" | "listAgentApps" | "authenticate" + >; + tools: AidenMcpToolRunner; + /** `hostPlatformCapabilities().mcpServer`. */ + supported(): boolean; + /** The first port tried when none is saved yet. */ + defaultPort: number; + /** The Remote runtime's revocation, which fences the credential and ends its streams. */ + revokeDevice(deviceId: string): Promise; + appVersion: string; + log?: AidenMcpServerOptions["log"]; +} + +/** + * The main-process controls for the MCP server: on and off, and connecting, + * listing and disconnecting outside apps. It is off until the person turns + * it on, and it never starts on a host without the `mcpServer` capability. + */ +export class AidenMcpHost { + private readonly server: AidenMcpListener; + private problem: AidenMcpServerProblem | undefined; + private transition: Promise = Promise.resolve(); + + constructor(private readonly dependencies: AidenMcpHostDependencies) { + this.server = new AidenMcpServer({ + apps: dependencies.state, + tools: dependencies.tools, + appVersion: dependencies.appVersion, + ...(dependencies.log ? { log: dependencies.log } : {}), + }); + } + + async status(): Promise { + const supported = this.dependencies.supported(); + const settings = await this.dependencies.state.mcpServerSettings(); + const port = this.server.port ?? settings.port; + return { + supported, + enabled: supported && settings.enabled, + running: this.server.port !== undefined, + ...(port === undefined ? {} : { port, url: `http://127.0.0.1:${port}${AIDEN_MCP_PATH}` }), + ...(this.problem ? { problem: this.problem } : {}), + }; + } + + /** Starts the listener if the person turned it on. Run at launch. */ + initialize(): Promise { + return this.serialize(async () => { + await this.reconcile(); + return this.status(); + }); + } + + setEnabled(enabled: boolean): Promise { + return this.serialize(async () => { + if (typeof enabled !== "boolean") throw new Error("Invalid MCP server setting."); + if (enabled && !this.dependencies.supported()) { + throw new Error("This computer cannot run Aiden's MCP server."); + } + await this.dependencies.state.setMcpServerEnabled(enabled); + await this.reconcile(); + return this.status(); + }); + } + + /** Connects an outside app. The credential is returned once; only its digest is kept. */ + async issueApp(input: { + name: string; + access: AidenRemoteAgentAccess; + }): Promise<{ credential: string; app: AidenRemoteAgentAppProjection }> { + if (!this.dependencies.supported()) throw new Error("This computer cannot run Aiden's MCP server."); + return this.dependencies.state.issueAgentApp(input); + } + + listApps(): Promise { + return this.dependencies.state.listAgentApps(); + } + + /** Disconnects an app: its token stops working, and its waits and run streams end. */ + async revokeApp(appId: string): Promise { + const apps = await this.dependencies.state.listAgentApps(); + // Only an outside app can be disconnected here, never a phone or a Mac. + if (!apps.some((app) => app.id === appId)) return false; + const revoked = await this.dependencies.revokeDevice(appId); + this.dependencies.tools.revokeApp(appId); + return revoked; + } + + stop(): Promise { + return this.serialize(() => this.server.close()); + } + + private async reconcile(): Promise { + const settings = await this.dependencies.state.mcpServerSettings(); + if (!settings.enabled || !this.dependencies.supported()) { + this.problem = undefined; + await this.server.close(); + return; + } + if (this.server.port !== undefined) return; + try { + const port = await this.server.start( + aidenMcpPortCandidates(settings.port, this.dependencies.defaultPort), + settings.port === undefined, + ); + this.problem = undefined; + if (settings.port !== port) await this.dependencies.state.commitMcpServerPort(port); + } catch (error) { + this.problem = error instanceof AidenMcpPortInUseError ? "port_in_use" : "start_failed"; + this.dependencies.log?.("start-failed", { problem: this.problem }); + } + } + + private serialize(action: () => Promise): Promise { + const next = this.transition.then(action, action); + this.transition = next.catch(() => undefined); + return next; + } +} diff --git a/main/services/aiden-mcp-tools.ts b/main/services/aiden-mcp-tools.ts new file mode 100644 index 0000000000..c5fd638a8e --- /dev/null +++ b/main/services/aiden-mcp-tools.ts @@ -0,0 +1,640 @@ +/** + * The tools Aiden's MCP server offers outside apps (Claude Code, Codex, ...). + * + * Ported in spirit from T3 Code's MCP server (pingdotgg/t3code#33196): a small + * catalog with terse descriptions and read/write annotations, where a + * long-running turn is followed with a bounded wait instead of a stream. + * + * Every tool is declared `read` or `write`. A Read app sees and calls only + * reads; a Supervised app may also start, continue and stop turns. Nothing + * here can answer an approval or a question: those stay with the person, in + * Aiden on this computer. Every call goes through the same chat and stream + * services a paired phone uses, so workspace permissions, model resolution, + * idempotency and revocation behave exactly as they do there. + */ +import type { CallToolResult, Tool } from "@modelcontextprotocol/sdk/types.js"; +import { Type, type TSchema } from "typebox"; +import { Value } from "typebox/value"; + +import { ASSISTANT_WORKSPACE_ID } from "../../renderer/shared/assistant.js"; +import type { AidenMcpChatProvenance } from "./aiden-mcp-provenance.js"; +import type { AidenRemoteChatService, AidenRemoteMessageProjection } from "./aiden-remote-chats.js"; +import { AidenRemoteServiceError } from "./aiden-remote-errors.js"; +import type { AidenRemoteCapability } from "./aiden-remote-protocol.js"; +import type { AidenRemoteStreamService, AidenRemoteStreamState } from "./aiden-remote-streams.js"; +import type { AidenRemoteWorkspaceService } from "./aiden-remote-workspaces.js"; + +export const AIDEN_MCP_TOOL_PREFIX = "aiden_"; + +export type AidenMcpToolLevel = "read" | "write"; + +/** The app a request authenticated as. */ +export interface AidenMcpApp { + id: string; + name: string; + capabilities: ReadonlySet; +} + +export interface AidenMcpServices { + chats: Pick; + streams: Pick; + workspaces: Pick; +} + +export interface AidenMcpLimits { + /** Turns (chat_start plus chat_send) one app may start per minute. */ + turnsPerMinute: number; + /** Runs one app may have going at once. */ + concurrentRuns: number; + /** The longest a single `aiden_chat_wait` holds before answering `running`. */ + maxWaitSeconds: number; +} + +export const DEFAULT_AIDEN_MCP_LIMITS: AidenMcpLimits = { + turnsPerMinute: 10, + concurrentRuns: 2, + maxWaitSeconds: 55, +}; + +export interface AidenMcpToolDependencies { + services(): Promise; + /** + * The Remote revocation fence (`AidenRemoteStateRegistry.acquireDeviceAuthorization`). + * Throws once revocation began; a write holds the returned release until it + * finishes, so revocation waits for it. + */ + acquireAuthorization(appId: string, tracksMutationDrain: boolean): () => void; + /** Local only: which app started a chat. Never projected anywhere. */ + recordProvenance?(chatId: string, provenance: AidenMcpChatProvenance): Promise; + appVersion: string; + /** This computer's name, as the person sees it, so an app can say where to approve. */ + hostName(): Promise; + now?(): number; + limits?: Partial; +} + +const WAIT_DEFAULT_SECONDS = 25; +const READ_DEFAULT_MESSAGES = 20; +const READ_MAX_MESSAGES = 50; +const LIST_DEFAULT_CHATS = 20; +const LIST_MAX_CHATS = 50; +/** One message's text, as an app reads it; longer text is cut and flagged. */ +const MESSAGE_TEXT_LIMIT = 20_000; +const TURN_TEXT_LIMIT = 200_000; +const REQUEST_CACHE_LIMIT = 128; +const TERMINAL_STATES: ReadonlySet = new Set(["done", "error", "cancelled", "interrupted"]); + +const ID = { pattern: "^[A-Za-z0-9._:-]{1,128}$", maxLength: 128 } as const; +const CLIENT_REQUEST_ID = Type.String({ + pattern: "^[A-Za-z0-9._:-]{8,96}$", + minLength: 8, + maxLength: 96, + description: "A unique id you choose for this request. Retrying with the same id never starts a second turn.", +}); +const TURN_TEXT = Type.String({ minLength: 1, maxLength: TURN_TEXT_LIMIT, description: "The message to send." }); + +type ToolHandler = (app: AidenMcpApp, args: Record, signal: AbortSignal) => Promise; + +interface ToolDefinition { + name: string; + level: AidenMcpToolLevel; + /** The capability the app must hold. */ + capability: AidenRemoteCapability; + title: string; + description: string; + schema: TSchema; + annotations: NonNullable; + handler: ToolHandler; +} + +class ToolRefusal extends Error {} + +/** + * Owns the tool catalog and per-app state (rate limit, runs in flight, waits). + * One runner lives as long as the MCP server; each HTTP request uses it. + */ +export class AidenMcpToolRunner { + private readonly tools: ToolDefinition[]; + private readonly limits: AidenMcpLimits; + private readonly now: () => number; + private readonly turnTimes = new Map(); + private readonly runs = new Map>(); + private readonly waits = new Map>(); + /** In-flight and recent turn requests, so a retry replays instead of counting again. */ + private readonly requests = new Map>(); + + constructor(private readonly dependencies: AidenMcpToolDependencies) { + this.limits = { ...DEFAULT_AIDEN_MCP_LIMITS, ...dependencies.limits }; + this.now = dependencies.now ?? Date.now; + this.tools = this.defineTools(); + } + + /** The level of a tool, or undefined for a name Aiden does not offer. */ + levelOf(name: string): AidenMcpToolLevel | undefined { + return this.tools.find((tool) => tool.name === name)?.level; + } + + /** The tools this app may call. A Read app is never shown a write tool. */ + list(app: AidenMcpApp): Tool[] { + return this.tools + .filter((tool) => app.capabilities.has(tool.capability)) + .map((tool) => ({ + name: tool.name, + title: tool.title, + description: tool.description, + // Plain JSON Schema: TypeBox metadata never reaches the wire. + inputSchema: JSON.parse(JSON.stringify(tool.schema)) as Tool["inputSchema"], + annotations: { title: tool.title, ...tool.annotations }, + })); + } + + async call(app: AidenMcpApp, name: string, args: unknown, signal: AbortSignal): Promise { + const tool = this.tools.find((candidate) => candidate.name === name); + if (!tool) return toolError("Aiden has no tool with that name."); + if (!app.capabilities.has(tool.capability)) { + return toolError( + tool.level === "write" + ? "This app is connected to Aiden with Read access, so it cannot start, send or stop turns." + : "This app does not have access to that Aiden tool.", + ); + } + const input = args ?? {}; + if (!input || typeof input !== "object" || Array.isArray(input) || !Value.Check(tool.schema, input)) { + return toolError("The arguments do not match the tool's schema."); + } + let release: () => void; + try { + release = this.dependencies.acquireAuthorization(app.id, tool.level === "write"); + } catch { + return toolError("This app was disconnected from Aiden."); + } + try { + return await tool.handler(app, input as Record, signal); + } catch (error) { + if (error instanceof ToolRefusal) return toolError(error.message); + if (error instanceof AidenRemoteServiceError) return toolError(error.message); + return toolError("Aiden could not complete this request."); + } finally { + release(); + } + } + + /** Forgets an app's limiter state and ends its waits. Run when the app is revoked. */ + revokeApp(appId: string): void { + for (const controller of this.waits.get(appId) ?? []) controller.abort(); + this.waits.delete(appId); + this.turnTimes.delete(appId); + this.runs.delete(appId); + for (const key of [...this.requests.keys()]) { + if (key.startsWith(`${appId}\u0000`)) this.requests.delete(key); + } + } + + private defineTools(): ToolDefinition[] { + const read = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }; + return [ + { + name: "aiden_server_info", + level: "read", + capability: "server:read", + title: "Aiden server info", + description: "Which Aiden this is, which computer it runs on, and this app's access.", + schema: Type.Object({}, { additionalProperties: false }), + annotations: read, + handler: async (app) => this.serverInfo(app), + }, + { + name: "aiden_workspace_list", + level: "read", + capability: "chat:read", + title: "List workspaces", + description: "List the person's Aiden workspaces. A new chat starts in one of these.", + schema: Type.Object({}, { additionalProperties: false }), + annotations: read, + handler: async () => this.workspaceList(), + }, + { + name: "aiden_chat_list", + level: "read", + capability: "chat:read", + title: "List chats", + description: "List recent Aiden chats, newest first. Pass nextCursor back to page.", + schema: Type.Object( + { + limit: Type.Optional(Type.Integer({ minimum: 1, maximum: LIST_MAX_CHATS })), + cursor: Type.Optional(Type.String({ minLength: 1, maxLength: 512 })), + }, + { additionalProperties: false }, + ), + annotations: { ...read, idempotentHint: false }, + handler: async (_app, args) => this.chatList(args), + }, + { + name: "aiden_chat_read", + level: "read", + capability: "chat:read", + title: "Read a chat", + description: "Read a chat's most recent messages. Pass `before` (a message id) to read older ones.", + schema: Type.Object( + { + chatId: Type.String(ID), + before: Type.Optional(Type.String(ID)), + limit: Type.Optional(Type.Integer({ minimum: 1, maximum: READ_MAX_MESSAGES })), + }, + { additionalProperties: false }, + ), + annotations: { ...read, idempotentHint: false }, + handler: async (_app, args) => this.chatRead(args), + }, + { + name: "aiden_chat_wait", + level: "read", + capability: "chat:read", + title: "Wait for a run", + description: + "Wait until a run you started stops running, or the timeout passes. Returns running, waiting_for_approval, waiting_for_input, done or failed. Approvals and questions are answered by the person in Aiden; call again to keep waiting.", + schema: Type.Object( + { + chatId: Type.String(ID), + runId: Type.String(ID), + timeoutSeconds: Type.Optional(Type.Integer({ minimum: 1, maximum: this.limits.maxWaitSeconds })), + }, + { additionalProperties: false }, + ), + annotations: { ...read, idempotentHint: false }, + handler: async (app, args, signal) => this.chatWait(app, args, signal), + }, + { + name: "aiden_chat_start", + level: "write", + capability: "chat:write", + title: "Start a chat", + description: + "Start a new Aiden chat in a workspace and send its first message. Tools run with that workspace's permissions; approvals go to the person in Aiden. Follow the run with aiden_chat_wait.", + schema: Type.Object( + { + clientRequestId: CLIENT_REQUEST_ID, + workspaceId: Type.String({ pattern: "^[A-Za-z0-9_-]{1,128}$", maxLength: 128 }), + text: TURN_TEXT, + providerId: Type.Optional(Type.String({ minLength: 1, maxLength: 256 })), + modelId: Type.Optional(Type.String({ minLength: 1, maxLength: 256 })), + }, + { additionalProperties: false }, + ), + annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true }, + handler: async (app, args) => this.turnRequest(app, args, () => this.chatStart(app, args)), + }, + { + name: "aiden_chat_send", + level: "write", + capability: "chat:write", + title: "Send a message", + description: "Send a follow-up message to an Aiden chat. Follow the run with aiden_chat_wait.", + schema: Type.Object( + { clientRequestId: CLIENT_REQUEST_ID, chatId: Type.String(ID), text: TURN_TEXT }, + { additionalProperties: false }, + ), + annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true }, + handler: async (app, args) => this.turnRequest(app, args, () => this.chatSend(app, args)), + }, + { + name: "aiden_chat_stop", + level: "write", + capability: "chat:write", + title: "Stop a run", + description: "Stop a run this app started. Stopping a finished run does nothing.", + schema: Type.Object({ chatId: Type.String(ID), runId: Type.String(ID) }, { additionalProperties: false }), + annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }, + handler: async (app, args) => this.chatStop(app, args), + }, + ]; + } + + private async serverInfo(app: AidenMcpApp): Promise { + return toolResult({ + name: "Aiden", + version: this.dependencies.appVersion, + computer: await this.dependencies.hostName(), + app: { name: app.name, access: app.capabilities.has("chat:write") ? "supervised" : "read" }, + tools: this.list(app).map((tool) => tool.name), + }); + } + + private async workspaceList(): Promise { + return toolResult({ + workspaces: (await offeredWorkspaces(await this.dependencies.services())).map((workspace) => ({ + id: workspace.id, + name: workspace.name, + hasFolder: workspace.hasFolder, + toolPermission: workspace.permission, + })), + }); + } + + private async chatList(args: Record): Promise { + const { chats } = await this.dependencies.services(); + const page = await chats.listSummaries( + (args.limit as number | undefined) ?? LIST_DEFAULT_CHATS, + args.cursor as string | undefined, + ); + return toolResult({ + chats: page.summaries.map((summary) => ({ + id: summary.id, + workspaceId: summary.workspaceId, + title: summary.title, + updatedAt: summary.updatedAt, + running: summary.activity === "active", + ...(summary.lastRunFailed ? { lastRunFailed: true } : {}), + })), + ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}), + }); + } + + private async chatRead(args: Record): Promise { + const services = await this.dependencies.services(); + const chatId = args.chatId as string; + await requireOrdinaryChat(services, chatId); + const window = await services.chats.messagesWindow(chatId, { + ...(typeof args.before === "string" ? { before: args.before } : {}), + limit: (args.limit as number | undefined) ?? READ_DEFAULT_MESSAGES, + }); + return toolResult({ + chatId: window.chatId, + workspaceId: window.workspaceId, + title: window.title, + messages: window.messages.map(projectMessage), + hasOlder: window.hasOlder, + }); + } + + private async chatWait(app: AidenMcpApp, args: Record, signal: AbortSignal): Promise { + const services = await this.dependencies.services(); + const chatId = args.chatId as string; + const runId = args.runId as string; + await requireOrdinaryChat(services, chatId); + const timeoutMs = ((args.timeoutSeconds as number | undefined) ?? Math.min(WAIT_DEFAULT_SECONDS, this.limits.maxWaitSeconds)) * 1_000; + const first = await this.runSnapshot(services, app, chatId, runId); + if (first.state !== "running" || signal.aborted) return toolResult(first); + + const controller = new AbortController(); + const appWaits = this.waits.get(app.id) ?? new Set(); + appWaits.add(controller); + this.waits.set(app.id, appWaits); + let detach: (() => void) | undefined; + let timer: ReturnType | undefined; + try { + const outcome = await new Promise<"changed" | "timeout" | "closed" | "aborted">((resolve) => { + const abort = () => resolve("aborted"); + signal.addEventListener("abort", abort, { once: true }); + controller.signal.addEventListener("abort", () => resolve("closed"), { once: true }); + timer = setTimeout(() => resolve("timeout"), timeoutMs); + try { + detach = services.streams.watch(app.id, runId, { + onChange: () => { + // Most events (text deltas, tool output) leave the run running; + // only a state change answers the wait. + void this.runSnapshot(services, app, chatId, runId) + .then((snapshot) => { + if (snapshot.state !== "running") resolve("changed"); + }) + .catch(() => resolve("changed")); + }, + onClose: () => resolve("closed"), + }); + } catch { + resolve("changed"); + } + }); + if (outcome === "closed") throw new ToolRefusal("This app was disconnected from Aiden."); + if (outcome === "aborted") return toolError("The wait ended because the request closed."); + return toolResult(await this.runSnapshot(services, app, chatId, runId)); + } finally { + if (timer) clearTimeout(timer); + detach?.(); + appWaits.delete(controller); + if (appWaits.size === 0 && this.waits.get(app.id) === appWaits) this.waits.delete(app.id); + } + } + + private async chatStart(app: AidenMcpApp, args: Record): Promise { + const services = await this.dependencies.services(); + const clientRequestId = args.clientRequestId as string; + const providerId = args.providerId as string | undefined; + const modelId = args.modelId as string | undefined; + // Only a workspace aiden_workspace_list offers: never a one-chat folder or the assistant's own. + if (!(await offeredWorkspaces(services)).some((workspace) => workspace.id === args.workspaceId)) { + throw new ToolRefusal("Aiden has no workspace with that id. List them with aiden_workspace_list."); + } + this.admitTurn(services, app); + const chat = await services.chats.create(app.id, `mcp-create:${clientRequestId}`, { + workspaceId: args.workspaceId, + ...(providerId ? { providerId } : {}), + ...(modelId ? { modelId } : {}), + }); + await this.dependencies.recordProvenance?.(chat.id, { + kind: "app", + appId: app.id, + name: app.name, + startedAt: this.now(), + }).catch(() => undefined); + // The first turn goes through the same mutation fence as any other turn. + const classification = await requireOrdinaryChat(services, chat.id); + const turn = await services.chats.runMutation(app.id, chat.id, classification, () => + services.chats.startTurn(app.id, chat.id, `mcp-turn:${clientRequestId}`, { text: args.text }), + ); + this.trackRun(app.id, turn.streamId); + return toolResult({ chatId: chat.id, turnId: turn.turnId, runId: turn.streamId, state: "running" }); + } + + private async chatSend(app: AidenMcpApp, args: Record): Promise { + const services = await this.dependencies.services(); + const chatId = args.chatId as string; + const classification = await requireOrdinaryChat(services, chatId); + this.admitTurn(services, app); + const turn = await services.chats.runMutation(app.id, chatId, classification, () => + services.chats.startTurn(app.id, chatId, `mcp-turn:${args.clientRequestId as string}`, { text: args.text }), + ); + this.trackRun(app.id, turn.streamId); + return toolResult({ chatId, turnId: turn.turnId, runId: turn.streamId, state: "running" }); + } + + private async chatStop(app: AidenMcpApp, args: Record): Promise { + const services = await this.dependencies.services(); + const chatId = args.chatId as string; + const runId = args.runId as string; + const classification = await requireOrdinaryChat(services, chatId); + const status = ownedRunStatus(services, app, chatId, runId); + if (TERMINAL_STATES.has(status.state)) { + return toolResult({ chatId, runId, stopped: false, state: waitState(status.state) }); + } + await services.chats.runMutation(app.id, chatId, classification, () => + services.streams.cancel(app.id, runId, `mcp-stop:${runId}`), + ); + return toolResult({ chatId, runId, stopped: true }); + } + + /** + * Turn requests with the same clientRequestId share one outcome, so a retry + * replays the first answer and is not counted against the rate limit again. + */ + private turnRequest( + app: AidenMcpApp, + args: Record, + run: () => Promise, + ): Promise { + const key = `${app.id}\u0000${args.clientRequestId as string}`; + const existing = this.requests.get(key); + if (existing) return existing; + const pending = run().catch((error: unknown) => { + // A refusal or failure is not cached: the app may retry once it clears. + this.requests.delete(key); + throw error; + }); + this.requests.set(key, pending); + while (this.requests.size > REQUEST_CACHE_LIMIT) { + const oldest = this.requests.keys().next().value; + if (oldest === undefined) break; + this.requests.delete(oldest); + } + return pending; + } + + /** Refuses a turn over this app's rate or concurrency limit, then counts it. */ + private admitTurn(services: AidenMcpServices, app: AidenMcpApp): void { + const now = this.now(); + const recent = (this.turnTimes.get(app.id) ?? []).filter((time) => now - time < 60_000); + if (recent.length >= this.limits.turnsPerMinute) { + this.turnTimes.set(app.id, recent); + const retryAfter = Math.max(1, Math.ceil((60_000 - (now - recent[0]!)) / 1_000)); + throw new ToolRefusal( + `This app started ${this.limits.turnsPerMinute} turns in the last minute. Try again in ${retryAfter} seconds.`, + ); + } + const running = this.liveRuns(services, app.id); + if (running >= this.limits.concurrentRuns) { + throw new ToolRefusal( + `This app already has ${running} runs going in Aiden. Wait for one to finish or stop one first.`, + ); + } + recent.push(now); + this.turnTimes.set(app.id, recent); + } + + private liveRuns(services: AidenMcpServices, appId: string): number { + const runs = this.runs.get(appId); + if (!runs) return 0; + for (const runId of [...runs]) { + try { + if (TERMINAL_STATES.has(services.streams.status(appId, runId).state)) runs.delete(runId); + } catch { + runs.delete(runId); + } + } + return runs.size; + } + + private trackRun(appId: string, runId: string): void { + const runs = this.runs.get(appId) ?? new Set(); + runs.add(runId); + this.runs.set(appId, runs); + } + + private async runSnapshot( + services: AidenMcpServices, + app: AidenMcpApp, + chatId: string, + runId: string, + ): Promise> { + const status = ownedRunStatus(services, app, chatId, runId); + const base = { chatId, runId }; + const approveIn = `Aiden on ${await this.dependencies.hostName()}`; + if (!TERMINAL_STATES.has(status.state)) { + if (services.streams.pendingQuestion(app.id, runId)) { + return { ...base, state: "waiting_for_input", answerIn: approveIn }; + } + const approval = services.streams.pendingApproval(app.id, runId); + if (approval || status.state === "waiting_for_approval") { + return { + ...base, + state: "waiting_for_approval", + approveIn, + ...(approval + ? { approval: { toolName: approval.toolName, summary: approval.summary, expiresAt: approval.expiresAt } } + : {}), + }; + } + return { ...base, state: "running" }; + } + if (status.state === "done" || status.state === "cancelled") { + const reply = await lastAssistantMessage(services, chatId).catch(() => undefined); + return { + ...base, + state: "done", + outcome: status.state === "cancelled" ? "stopped" : "completed", + ...(reply ? { reply } : {}), + }; + } + return { ...base, state: "failed", reason: status.state === "interrupted" ? "interrupted" : "error" }; + } +} + +/** The workspaces an outside app may start chats in: the person's named ones. */ +async function offeredWorkspaces(services: AidenMcpServices) { + const { workspaces } = await services.workspaces.list(); + return workspaces.filter((workspace) => workspace.noWorkspace !== true && workspace.id !== ASSISTANT_WORKSPACE_ID); +} + +/** Bot chats are not offered to outside apps; they read as missing. */ +async function requireOrdinaryChat( + services: AidenMcpServices, + chatId: string, +): Promise>> { + const classification = await services.chats.classify(chatId); + if (classification.botId) throw new ToolRefusal("This Aiden chat no longer exists."); + return classification; +} + +function ownedRunStatus(services: AidenMcpServices, app: AidenMcpApp, chatId: string, runId: string) { + let status; + try { + status = services.streams.status(app.id, runId); + } catch { + throw new ToolRefusal("Aiden no longer tracks this run. Read the chat with aiden_chat_read for its result."); + } + if (status.chatId !== chatId) { + throw new ToolRefusal("Aiden no longer tracks this run. Read the chat with aiden_chat_read for its result."); + } + return status; +} + +function waitState(state: AidenRemoteStreamState): string { + if (state === "done" || state === "cancelled") return "done"; + if (TERMINAL_STATES.has(state)) return "failed"; + return state === "waiting_for_approval" ? state : "running"; +} + +async function lastAssistantMessage(services: AidenMcpServices, chatId: string) { + const window = await services.chats.messagesWindow(chatId, { limit: 5 }); + const message = [...window.messages].reverse().find((candidate) => candidate.role === "assistant"); + return message ? projectMessage(message) : undefined; +} + +function projectMessage(message: AidenRemoteMessageProjection) { + const text = [...message.text]; + return { + id: message.id, + role: message.role, + text: text.length > MESSAGE_TEXT_LIMIT ? text.slice(0, MESSAGE_TEXT_LIMIT).join("") : message.text, + ...(text.length > MESSAGE_TEXT_LIMIT ? { truncated: true } : {}), + createdAt: message.createdAt, + ...(message.outcome ? { outcome: message.outcome.status } : {}), + }; +} + +function toolResult(value: Record): CallToolResult { + return { content: [{ type: "text", text: JSON.stringify(value) }], structuredContent: value }; +} + +function toolError(text: string): CallToolResult { + return { content: [{ type: "text", text }], isError: true }; +} diff --git a/main/services/aiden-remote-router.test.ts b/main/services/aiden-remote-router.test.ts index 8868efbb1f..28e68bc600 100644 --- a/main/services/aiden-remote-router.test.ts +++ b/main/services/aiden-remote-router.test.ts @@ -95,7 +95,7 @@ async function fixture(options: { questionsAvailable?: boolean; skillsAvailable?: boolean; agentInterruptAvailable?: boolean; - deviceType?: "iphone" | "ipad" | "android" | "mac" | "linux"; + deviceType?: "iphone" | "ipad" | "android" | "mac" | "linux" | "agent"; simulators?: AidenRemoteSimulatorRelay; /** `true` installs a recording fake; an object installs that feed service. */ hostFeed?: boolean | NonNullable[0]["hostFeed"]>; @@ -4172,6 +4172,26 @@ test("manual pairing bootstrap is bounded, origin-rejecting, and does not accept } }); +test("an outside app's MCP credential is refused by the Remote API like an unknown one", async () => { + const headers = { authorization: `Bearer ${"a".repeat(43)}`, "aiden-protocol-version": "1" }; + const capabilities: AidenRemoteCapability[] = ["server:read", "chat:read", "chat:write"]; + const phone = await fixture({ deviceType: "iphone", capabilities }); + try { + assert.equal((await fetch(`${phone.base}/chats`, { headers })).status, 200); + } finally { + await phone.close(); + } + const app = await fixture({ deviceType: "agent", capabilities }); + try { + const response = await fetch(`${app.base}/chats`, { headers }); + assert.equal(response.status, 401); + assert.equal((await response.json()).error.code, "authentication_required"); + assert.equal(app.calls.some((entry) => entry.startsWith("chat-list:")), false); + } finally { + await app.close(); + } +}); + test("unknown routes and query aliases fail without reflecting untrusted input", async () => { const app = await fixture(); try { diff --git a/main/services/aiden-remote-router.ts b/main/services/aiden-remote-router.ts index 1509f878d4..9a52845def 100644 --- a/main/services/aiden-remote-router.ts +++ b/main/services/aiden-remote-router.ts @@ -1145,7 +1145,10 @@ async function authenticateCredential( ); } const device = await devices.authenticate(credential); - if (!device) { + // An outside app's credential belongs to the loopback MCP server only. It + // reads here exactly like an unknown credential, so this API never confirms + // that an app token exists. + if (!device || device.type === "agent") { throw new AidenRemoteServiceError( "authentication_required", "This device credential is not valid for this Aiden installation.", diff --git a/main/services/aiden-remote-service-main.ts b/main/services/aiden-remote-service-main.ts index 69909f75d6..ed3b4116ab 100644 --- a/main/services/aiden-remote-service-main.ts +++ b/main/services/aiden-remote-service-main.ts @@ -48,8 +48,23 @@ import { defaultAidenRemoteDisplayName, normalizeAidenRemoteStateForRuntimeProfile, parseAidenRemoteStateDocument, + type AidenRemoteAgentAccess, + type AidenRemoteAgentAppProjection, type AidenRemoteStateDocument, } from "./aiden-remote-state.js"; +import { + AIDEN_MCP_DEVELOPMENT_PORT, + AIDEN_MCP_PRODUCTION_PORT, + AidenMcpHost, + type AidenMcpServerStatus, +} from "./aiden-mcp-server.js"; +import { AidenMcpToolRunner } from "./aiden-mcp-tools.js"; +import { + AidenMcpProvenanceLog, + emptyAidenMcpProvenanceDocument, + parseAidenMcpProvenanceDocument, + type AidenMcpProvenanceDocument, +} from "./aiden-mcp-provenance.js"; import { aidenRemoteDefaultLanPort, aidenRemotePortCandidatesForProfile, @@ -201,6 +216,8 @@ const STATE_FILE = "aiden-remote-v1.json"; const OPERATIONS_FILE = "aiden-remote-operations-v1.json"; const STREAMS_FILE = "aiden-remote-streams-v1.json"; const MAX_STATE_BYTES = 512 * 1_024; +const MCP_PROVENANCE_FILE = "aiden-mcp-chat-provenance.json"; +const MAX_MCP_PROVENANCE_BYTES = 512 * 1_024; const execFileAsync = promisify(execFile); async function mapWithConcurrency( @@ -302,6 +319,8 @@ export interface AidenRemoteRuntime { service: AidenRemoteService; state: AidenRemoteStateRegistry; approvedRoots: AidenRemoteApprovedRootService; + /** The loopback MCP server for outside apps; off unless the person turns it on. */ + mcp: AidenMcpHost; revokeDevice(deviceId: string): Promise; pendingApprovalForChat(chatId: string): AidenRemotePendingApproval | null; pendingQuestionForChat(chatId: string): AidenRemotePendingQuestion | null; @@ -492,6 +511,9 @@ async function createRuntime(): Promise { } return revoked; }; + // Assigned by `workspaceApi` below, so the MCP server and Remote Access share + // one set of chat and stream services whether or not Remote Access is on. + let remoteWorkspaceApi: ((instanceId: string) => ReturnType) | undefined; const service = new AidenRemoteService({ state, appVersion: app.getVersion(), @@ -513,7 +535,7 @@ async function createRuntime(): Promise { hostPlatform: aidenRemoteHostPlatform(process.platform), botRoutineWebhook: async (request) => (await import("./bot-routine-events/sources-main.js")).handleBotRoutineWebhook(request), - workspaceApi: async (instanceId) => { + workspaceApi: remoteWorkspaceApi = async (instanceId) => { // A failed build is retried by the next start rather than replayed. const api = await workspaceApis( instanceId, @@ -1249,10 +1271,44 @@ async function createRuntime(): Promise { }), log: writeRemoteLog, }); + const mcpProvenance = new AidenMcpProvenanceLog(new DataStore( + MCP_PROVENANCE_FILE, + emptyAidenMcpProvenanceDocument(), + () => userData, + { + maxBytes: MAX_MCP_PROVENANCE_BYTES, + fileMode: 0o600, + compact: true, + normalize: (value) => parseAidenMcpProvenanceDocument(value), + }, + )); + const mcpTools = new AidenMcpToolRunner({ + services: async () => { + const api = await remoteWorkspaceApi?.((await state.snapshot()).instanceId); + if (!api) throw new Error("Aiden's chat services are unavailable."); + return api; + }, + acquireAuthorization: (appId, tracksMutationDrain) => + state.acquireDeviceAuthorization(appId, tracksMutationDrain), + recordProvenance: (chatId, provenance) => mcpProvenance.record(chatId, provenance), + appVersion: app.getVersion(), + hostName: async () => (await state.snapshot()).displayName, + }); + const mcp = new AidenMcpHost({ + state, + tools: mcpTools, + supported: () => hostPlatformCapabilities().mcpServer, + defaultPort: runtimeProfile.id === "development" ? AIDEN_MCP_DEVELOPMENT_PORT : AIDEN_MCP_PRODUCTION_PORT, + revokeDevice, + appVersion: app.getVersion(), + // Category-only: never a credential, app name, chat or path. + log: (event, details) => logger.info("aiden-mcp", event, details ?? {}), + }); const runtime: AidenRemoteRuntime = { service, state, approvedRoots: new AidenRemoteApprovedRootService(state), + mcp, revokeDevice, pendingApprovalForChat: (chatId) => activeStreams?.pendingApprovalForChat(chatId) ?? null, pendingQuestionForChat: (chatId) => activeStreams?.pendingQuestionForChat(chatId) ?? null, @@ -1280,15 +1336,43 @@ export function aidenRemoteServiceKeepsApplicationAlive(): boolean { } export async function initializeAidenRemoteService(): Promise { - const service = await getAidenRemoteService(); - await service.initialize(); + const runtime = await getAidenRemoteRuntime(); + // The MCP server is off by default and independent of Remote Access; a + // failure to bind is reported in its status, never thrown into startup. + void runtime.mcp.initialize().catch(() => logger.warn("aiden-mcp", "initialize-failed", {})); + await runtime.service.initialize(); } export function stopAidenRemoteService(): void { - void runtimePromise?.then((runtime) => runtime.service.stop()); + void runtimePromise?.then((runtime) => Promise.all([runtime.mcp.stop(), runtime.service.stop()])); } export async function stopAidenRemoteServiceAndSettle(): Promise { const runtime = await runtimePromise; + await runtime?.mcp.stop(); await runtime?.service.stopAndSettle(); } + +/** Main-process controls for Aiden's MCP server (W4b adds the Settings UI on top). */ +export async function aidenMcpServerStatus(): Promise { + return (await getAidenRemoteRuntime()).mcp.status(); +} + +export async function setAidenMcpServerEnabled(enabled: boolean): Promise { + return (await getAidenRemoteRuntime()).mcp.setEnabled(enabled); +} + +export async function issueAidenMcpApp(input: { + name: string; + access: AidenRemoteAgentAccess; +}): Promise<{ credential: string; app: AidenRemoteAgentAppProjection }> { + return (await getAidenRemoteRuntime()).mcp.issueApp(input); +} + +export async function listAidenMcpApps(): Promise { + return (await getAidenRemoteRuntime()).mcp.listApps(); +} + +export async function revokeAidenMcpApp(appId: string): Promise { + return (await getAidenRemoteRuntime()).mcp.revokeApp(appId); +} diff --git a/main/services/aiden-remote-service.ts b/main/services/aiden-remote-service.ts index 38981d81da..8e922b8c78 100644 --- a/main/services/aiden-remote-service.ts +++ b/main/services/aiden-remote-service.ts @@ -30,10 +30,11 @@ import { createAidenRemoteUpgradeHandler, type AidenRemoteRouterDependencies, } from "./aiden-remote-router.js"; -import type { - AidenRemoteConnectionMode, - AidenRemoteStateDocument, - AidenRemoteStateRegistry, +import { + isAidenRemotePairedDevice, + type AidenRemoteConnectionMode, + type AidenRemoteStateDocument, + type AidenRemoteStateRegistry, } from "./aiden-remote-state.js"; import type { AidenRemoteTlsIdentity } from "./aiden-remote-tls-identity.js"; import { fetchTlsServerSpkiSha256, classifyAidenRemoteTlsEndpointFailure } from "./aiden-remote-tls-identity.js"; @@ -701,7 +702,7 @@ export class AidenRemoteService { }; const mayMoveFreshProfile = !state.lanPortCommitted - && state.devices.length === 0 + && !state.devices.some(isAidenRemotePairedDevice) && state.tailscaleOwnership === undefined; const maySelectAlternatePort = mayMoveFreshProfile || options.allowEndpointRelocation === true; @@ -1487,7 +1488,7 @@ export class AidenRemoteService { const mode = current.connectionMode === "both" ? "both" : transport; // Changing a saved transport can strand existing devices. Keep that an // explicit advanced operation, rather than silently choosing both. - if (mode !== current.connectionMode && (current.devices.length || current.tailscaleOwnership)) { + if (mode !== current.connectionMode && (current.devices.some(isAidenRemotePairedDevice) || current.tailscaleOwnership)) { throw new Error("This computer already has a saved connection. Use its current method, or review Connection settings before changing it."); } if (["finishing", "awaiting_scan"].includes(this.pairingStatus()?.state ?? "")) { @@ -1667,7 +1668,7 @@ export class AidenRemoteService { : tailscaleErrorCode ? { tailscaleErrorCode } : {}), - pairedDeviceCount: state.devices.length, + pairedDeviceCount: state.devices.filter(isAidenRemotePairedDevice).length, approvedRootCount: state.approvedRoots.filter((root) => !root.botsOnly).length, ...(this.options.pairingRequestSettings ? { acceptPairingRequests: await this.loadPairingRequestSetting() } diff --git a/main/services/aiden-remote-state.test.ts b/main/services/aiden-remote-state.test.ts index b85f073565..4087fa9187 100644 --- a/main/services/aiden-remote-state.test.ts +++ b/main/services/aiden-remote-state.test.ts @@ -1041,3 +1041,103 @@ test("bot:activity survives a restart, dies with revocation, and an older stored await reloaded.registry.upgradeDeviceCapabilities(legacy.device.id, ["bot:activity"]); assert.equal((await reloaded.registry.authenticate(legacy.credential))?.capabilities.has("bot:activity"), true); }); + +test("outside apps get only chat capabilities, never approvals, even from a tampered state file", async () => { + const state = fixture(); + await state.registry.initialize(); + const read = await state.registry.issueAgentApp({ name: "Codex", access: "read" }); + const supervised = await state.registry.issueAgentApp({ name: "Claude Code", access: "supervised" }); + assert.deepEqual( + [...(await state.registry.authenticate(read.credential))!.capabilities].sort(), + ["chat:read", "server:read"], + ); + assert.deepEqual( + [...(await state.registry.authenticate(supervised.credential))!.capabilities].sort(), + ["chat:read", "chat:write", "server:read"], + ); + + // Someone edits the state file to widen each app's grant. + const tampered = state.stored(); + for (const device of tampered.devices) { + device.capabilities = [ + ...device.capabilities, + "approval:respond", + "files:read", + "files:write", + "bots:write", + ] as typeof device.capabilities; + device.acceptsBotCapabilities = true; + } + const restored = fixture(tampered); + await restored.registry.initialize(); + const allowed = new Set(["server:read", "chat:read", "chat:write"]); + for (const credential of [read.credential, supervised.credential]) { + const app = await restored.registry.authenticate(credential); + assert.equal(app?.type, "agent"); + assert.equal(app.capabilities.has("approval:respond"), false); + assert.ok([...app.capabilities].every((capability) => allowed.has(capability))); + } + assert.equal((await restored.registry.authenticate(read.credential))!.capabilities.has("chat:write"), false); + // Capability negotiation can never add anything to an app either. + assert.equal(await restored.registry.upgradeDeviceCapabilities(supervised.app.id, ["approval:respond"]), null); + assert.equal(await restored.registry.upgradeDeviceCapabilities(supervised.app.id, ["chat:progress"]), null); +}); + +test("outside apps are connected only through their own call, listed apart from paired devices, with their own quota", async () => { + const state = fixture(); + await state.registry.initialize(); + await assert.rejects( + state.registry.issueDevice({ name: "Sneaky", type: "agent" as never, clientVersion: "1" }), + /Invalid pairing device metadata/u, + ); + await assert.rejects( + state.registry.issueAgentApp({ name: "Wide", access: "full" as never }), + /Invalid outside app metadata/u, + ); + const phone = await state.registry.issueDevice({ name: "iPhone", type: "iphone", clientVersion: "1" }); + const issued: Array>> = []; + for (let index = 0; index < 16; index += 1) { + issued.push(await state.registry.issueAgentApp({ name: `App ${index}`, access: "read" })); + } + await assert.rejects( + state.registry.issueAgentApp({ name: "One too many", access: "read" }), + /outside app capacity/u, + ); + // A full set of apps never blocks pairing a phone. + await state.registry.issueDevice({ name: "iPad", type: "ipad", clientVersion: "1" }); + assert.deepEqual((await state.registry.listDevices()).map((device) => device.type), ["iphone", "ipad"]); + const apps = await state.registry.listAgentApps(); + assert.equal(apps.length, 16); + assert.deepEqual(apps[0], { + id: issued[0]!.app.id, + name: "App 0", + access: "read", + capabilities: ["server:read", "chat:read"], + createdAt: 1_000, + lastSeenAt: 0, + }); + assert.equal(apps.some((app) => app.id === phone.device.id), false); + + // Revoking one frees its slot; the revoked app stays listed as revoked. + await state.registry.revokeDevice(issued[3]!.app.id); + await state.registry.issueAgentApp({ name: "Replacement", access: "supervised" }); + const after = await state.registry.listAgentApps(); + assert.equal(after.find((app) => app.id === issued[3]!.app.id)?.revokedAt, 1_000); + assert.equal((await state.registry.authenticate(issued[3]!.credential))?.revoked, true); +}); + +test("the MCP server is off by default and keeps its switch and port across restarts", async () => { + const state = fixture(); + await state.registry.initialize(); + assert.deepEqual(await state.registry.mcpServerSettings(), { enabled: false }); + await state.registry.setMcpServerEnabled(true); + await state.registry.commitMcpServerPort(49_401); + await assert.rejects(state.registry.commitMcpServerPort(80), /Invalid MCP server port/u); + const restored = fixture(state.stored()); + await restored.registry.initialize(); + assert.deepEqual(await restored.registry.mcpServerSettings(), { enabled: true, port: 49_401 }); + await restored.registry.setMcpServerEnabled(false); + const again = fixture(restored.stored()); + await again.registry.initialize(); + assert.deepEqual(await again.registry.mcpServerSettings(), { enabled: false, port: 49_401 }); +}); diff --git a/main/services/aiden-remote-state.ts b/main/services/aiden-remote-state.ts index fcc7cd26ba..3111a52327 100644 --- a/main/services/aiden-remote-state.ts +++ b/main/services/aiden-remote-state.ts @@ -35,7 +35,54 @@ const LAST_SEEN_WRITE_INTERVAL_MS = 5 * 60_000; export const MAX_AIDEN_REMOTE_DISPLAY_NAME_CHARACTERS = 80; const FALLBACK_AIDEN_REMOTE_DISPLAY_NAME = "Aiden Agent"; -export type AidenRemoteDeviceType = "iphone" | "ipad" | "android" | "mac" | "linux"; +/** + * `agent` is an outside app (Claude Code, Codex, ...) connected to Aiden's + * MCP server. It is never paired through `/api/aiden/v1` and never listed as a + * phone or computer; see `docs/aiden-mcp-server.md`. + */ +export type AidenRemoteDeviceType = "iphone" | "ipad" | "android" | "mac" | "linux" | "agent"; +/** The two access levels an outside app can be connected with. */ +export type AidenRemoteAgentAccess = "read" | "supervised"; +/** At most this many outside apps can be connected at once. */ +export const MAX_AIDEN_REMOTE_AGENT_APPS = 16; +const PAIRED_DEVICE_TYPES = ["iphone", "ipad", "android", "mac", "linux"] as const; +const AGENT_CLIENT_VERSION = "mcp-1"; +/** + * The whole grant an outside app can ever hold. Approvals, questions, files, + * git, Bots, schedules and settings are deliberately absent: an outside app + * can read chats and, when Supervised, start and stop turns, nothing more. + */ +const AGENT_CAPABILITY_CEILING: Readonly> = { + read: ["server:read", "chat:read"], + supervised: ["server:read", "chat:read", "chat:write"], +}; + +/** The capability set an outside app connected at `access` holds. */ +export function aidenRemoteAgentCapabilities(access: AidenRemoteAgentAccess): AidenRemoteCapability[] { + return [...AGENT_CAPABILITY_CEILING[access]]; +} + +function isPairedDeviceType(value: unknown): value is (typeof PAIRED_DEVICE_TYPES)[number] { + return (PAIRED_DEVICE_TYPES as readonly unknown[]).includes(value); +} + +function isDeviceType(value: unknown): value is AidenRemoteDeviceType { + return value === "agent" || isPairedDeviceType(value); +} + +function agentAccess(capabilities: readonly AidenRemoteCapability[]): AidenRemoteAgentAccess { + return capabilities.includes("chat:write") ? "supervised" : "read"; +} + +/** A phone, tablet or computer paired through Remote Access. */ +export type AidenRemotePairedDeviceType = Exclude; + +/** True for a phone, tablet or computer; false for an outside app. */ +export function isAidenRemotePairedDevice( + device: T, +): device is T & { type: AidenRemotePairedDeviceType } { + return device.type !== "agent"; +} export type AidenRemoteConnectionMode = "lan" | "tailscale" | "both"; interface StoredAidenRemoteDevice { @@ -79,6 +126,25 @@ export interface AidenRemoteStateDocument { approvedRoots: AidenRemoteApprovedRoot[]; tailscaleOwnership?: AidenTailscaleOwnership; tailscalePendingOutcome?: AidenTailscalePendingRouteOutcome; + /** The loopback MCP server for outside apps. Absent means off and no port claimed yet. */ + mcpServer?: AidenMcpServerSettings; +} + +export interface AidenMcpServerSettings { + enabled: boolean; + /** The stable loopback port, once one was claimed; kept across restarts so app configs keep working. */ + port?: number; +} + +/** An outside app as the main process lists it. Credentials never leave the registry. */ +export interface AidenRemoteAgentAppProjection { + id: string; + name: string; + access: AidenRemoteAgentAccess; + capabilities: AidenRemoteCapability[]; + createdAt: number; + lastSeenAt: number; + revokedAt?: number; } export interface AidenRemoteStateStorage { @@ -295,6 +361,14 @@ function parsePersistedCapabilities( // Opt-in vocabularies are stripped before validation so an older or corrupt // persisted record can never hold grants it could not have negotiated. const desktop = type === "mac" || type === "linux"; + if (type === "agent") { + // An outside app holds only its ceiling; anything else on disk is dropped, + // so no edit to the state file can widen it. + const ceiling: readonly unknown[] = AGENT_CAPABILITY_CEILING.supervised; + return Array.isArray(value) + ? parseCapabilities(value.filter((capability) => ceiling.includes(capability))) + : null; + } const negotiatedValue = Array.isArray(value) ? value.filter( (capability) => @@ -342,7 +416,7 @@ function parseDevice(value: unknown): StoredAidenRemoteDevice | null { if ( !boundedString(record.id, 128) || !boundedString(record.name, 80) || - (record.type !== "iphone" && record.type !== "ipad" && record.type !== "android" && record.type !== "mac" && record.type !== "linux") || + !isDeviceType(record.type) || !boundedString(record.clientVersion, 40) || !digestString(record.lookupDigest) || !digestString(record.credentialSalt) || @@ -367,8 +441,9 @@ function parseDevice(value: unknown): StoredAidenRemoteDevice | null { credentialSalt: record.credentialSalt, credentialDigest: record.credentialDigest, capabilities, - acceptsBotCapabilities, - acceptsProgressCapabilities, + // An outside app never opts into Bot or progress vocabularies. + acceptsBotCapabilities: record.type !== "agent" && acceptsBotCapabilities, + acceptsProgressCapabilities: record.type !== "agent" && acceptsProgressCapabilities, createdAt: record.createdAt, lastSeenAt: record.lastSeenAt, ...(record.revokedAt === undefined ? {} : { revokedAt: record.revokedAt }), @@ -504,7 +579,7 @@ export function parseAidenRemoteStateDocument( !exactKeys( record, ["version", "instanceId", "enabled", "connectionMode", "lanPort", "devices", "approvedRoots"], - ["displayName", "lanPortCommitted", "tailscaleOwnership", "tailscalePendingOutcome"], + ["displayName", "lanPortCommitted", "tailscaleOwnership", "tailscalePendingOutcome", "mcpServer"], ) || record.version !== STATE_VERSION || !boundedString(record.instanceId, 128) || @@ -540,6 +615,7 @@ export function parseAidenRemoteStateDocument( } const tailscaleOwnership = parseOwnership(record.tailscaleOwnership); const tailscalePendingOutcome = parsePendingOutcome(record.tailscalePendingOutcome); + const mcpServer = parseMcpServerSettings(record.mcpServer); return { version: STATE_VERSION, instanceId: record.instanceId, @@ -556,6 +632,41 @@ export function parseAidenRemoteStateDocument( approvedRoots: approvedRoots as AidenRemoteApprovedRoot[], ...(tailscaleOwnership ? { tailscaleOwnership } : {}), ...(tailscalePendingOutcome ? { tailscalePendingOutcome } : {}), + ...(mcpServer ? { mcpServer } : {}), + }; +} + +function parseMcpServerSettings(value: unknown): AidenMcpServerSettings | undefined { + if (value === undefined) return undefined; + const record = ownRecord(value); + if ( + !record || + !exactKeys(record, ["enabled"], ["port"]) || + typeof record.enabled !== "boolean" || + (record.port !== undefined && !isValidMcpServerPort(record.port)) + ) { + throw new Error("Aiden Remote state contains invalid MCP server settings."); + } + return { + enabled: record.enabled, + ...(record.port === undefined ? {} : { port: record.port as number }), + }; +} + +/** An unprivileged TCP port the loopback MCP listener may claim. */ +export function isValidMcpServerPort(value: unknown): value is number { + return Number.isInteger(value) && Number(value) >= 1_024 && Number(value) <= 65_535; +} + +function projectAgentApp(device: StoredAidenRemoteDevice): AidenRemoteAgentAppProjection { + return { + id: device.id, + name: device.name, + access: agentAccess(device.capabilities), + capabilities: [...device.capabilities], + createdAt: device.createdAt, + lastSeenAt: device.lastSeenAt, + ...(device.revokedAt === undefined ? {} : { revokedAt: device.revokedAt }), }; } @@ -576,7 +687,9 @@ function safeEqual(left: Buffer | null, right: Buffer): boolean { return Boolean(left && left.length === right.length && timingSafeEqual(left, right)); } -function projectDevice(device: StoredAidenRemoteDevice): AidenRemoteDeviceProjection { +function projectDevice( + device: StoredAidenRemoteDevice & { type: T }, +): AidenRemoteDeviceProjection & { type: T } { return { id: device.id, name: device.name, @@ -772,9 +885,65 @@ export class AidenRemoteStateRegistry { }); } - async listDevices(): Promise { + /** Paired phones, tablets and computers. Outside apps are listed by `listAgentApps`. */ + async listDevices(): Promise> { + const document = await this.snapshot(); + return document.devices.filter(isAidenRemotePairedDevice).map(projectDevice); + } + + /** Outside apps connected to the MCP server, revoked ones included. */ + async listAgentApps(): Promise { + const document = await this.snapshot(); + return document.devices.filter((device) => device.type === "agent").map(projectAgentApp); + } + + async mcpServerSettings(): Promise { const document = await this.snapshot(); - return document.devices.map(projectDevice); + return document.mcpServer ? { ...document.mcpServer } : { enabled: false }; + } + + async setMcpServerEnabled(enabled: boolean): Promise { + if (typeof enabled !== "boolean") throw new Error("Invalid MCP server setting."); + await this.mutateIfChanged((draft) => { + if ((draft.mcpServer?.enabled ?? false) === enabled) return { changed: false, value: undefined }; + draft.mcpServer = { ...draft.mcpServer, enabled }; + return { changed: true, value: undefined }; + }); + } + + /** Keeps the port the MCP listener bound so outside apps' saved URLs stay valid. */ + async commitMcpServerPort(port: number): Promise { + if (!isValidMcpServerPort(port)) throw new Error("Invalid MCP server port."); + await this.mutateIfChanged((draft) => { + if (draft.mcpServer?.port === port) return { changed: false, value: undefined }; + draft.mcpServer = { enabled: draft.mcpServer?.enabled ?? false, port }; + return { changed: true, value: undefined }; + }); + } + + /** + * Connects one outside app. Its credential is returned once and only its + * digest is kept. The capability set comes from `access` alone. + */ + async issueAgentApp(input: { + name: string; + access: AidenRemoteAgentAccess; + }): Promise<{ credential: string; app: AidenRemoteAgentAppProjection }> { + if ( + !boundedString(input?.name, 80) || + (input.access !== "read" && input.access !== "supervised") + ) { + throw new Error("Invalid outside app metadata."); + } + const { credential, device } = await this.createCredential({ + name: normalizeAidenRemoteDisplayName(input.name), + type: "agent", + clientVersion: AGENT_CLIENT_VERSION, + capabilities: aidenRemoteAgentCapabilities(input.access), + acceptsBotCapabilities: false, + acceptsProgressCapabilities: false, + }); + return { credential, app: projectAgentApp(device) }; } async updateDeviceName( @@ -823,7 +992,7 @@ export class AidenRemoteStateRegistry { } return this.mutateIfChanged((draft) => { const device = draft.devices.find((candidate) => candidate.id === deviceId); - if (!device || device.revokedAt !== undefined) { + if (!device || device.revokedAt !== undefined || device.type === "agent") { return { changed: false, value: null }; } // Callers check the device type first; a phone can never be granted @@ -873,7 +1042,8 @@ export class AidenRemoteStateRegistry { }): Promise { if ( !boundedString(input.name, 80) || - (input.type !== "iphone" && input.type !== "ipad" && input.type !== "android" && input.type !== "mac" && input.type !== "linux") || + // Outside apps are connected through `issueAgentApp`, never paired. + !isPairedDeviceType(input.type) || !boundedString(input.clientVersion, 40) || (input.acceptsBotCapabilities !== undefined && typeof input.acceptsBotCapabilities !== "boolean") || @@ -899,6 +1069,28 @@ export class AidenRemoteStateRegistry { ) { throw new Error("Invalid device capabilities."); } + const issued = await this.createCredential({ + name: input.name, + type: input.type, + clientVersion: input.clientVersion, + capabilities, + acceptsBotCapabilities: input.acceptsBotCapabilities === true, + acceptsProgressCapabilities: input.acceptsProgressCapabilities === true, + ...(input.authorizeCommit ? { authorizeCommit: input.authorizeCommit } : {}), + }); + return { credential: issued.credential, device: projectDevice(issued.device) }; + } + + private async createCredential(input: { + name: string; + type: AidenRemoteDeviceType; + clientVersion: string; + capabilities: AidenRemoteCapability[]; + acceptsBotCapabilities: boolean; + acceptsProgressCapabilities: boolean; + authorizeCommit?: () => boolean; + }): Promise<{ credential: string; device: StoredAidenRemoteDevice }> { + const capabilities = input.capabilities; const credential = this.dependencies.randomBytes(32).toString("base64url"); const salt = this.dependencies.randomBytes(32); const credentialDigest = await this.dependencies.deriveCredentialDigest( @@ -918,9 +1110,8 @@ export class AidenRemoteStateRegistry { credentialSalt: salt.toString("base64url"), credentialDigest: credentialDigest.toString("base64url"), capabilities, - acceptsBotCapabilities: input.acceptsBotCapabilities === true, - acceptsProgressCapabilities: - input.acceptsProgressCapabilities === true, + acceptsBotCapabilities: input.acceptsBotCapabilities, + acceptsProgressCapabilities: input.acceptsProgressCapabilities, createdAt: now, // Credential issuance is not proof that the client persisted the // credential and successfully authenticated back to this Mac. @@ -934,8 +1125,14 @@ export class AidenRemoteStateRegistry { 403, ); } - if (draft.devices.filter((entry) => entry.revokedAt === undefined).length >= MAX_DEVICES) { - throw new Error("Aiden Remote device capacity reached."); + // Paired devices and outside apps have separate quotas, so connecting + // apps can never crowd out a phone. + const agent = input.type === "agent"; + const active = draft.devices.filter( + (entry) => entry.revokedAt === undefined && (entry.type === "agent") === agent, + ).length; + if (active >= (agent ? MAX_AIDEN_REMOTE_AGENT_APPS : MAX_DEVICES)) { + throw new Error(agent ? "Aiden outside app capacity reached." : "Aiden Remote device capacity reached."); } if (draft.devices.length >= MAX_RETAINED_DEVICES) { const revokedIndex = draft.devices.findIndex( @@ -946,7 +1143,7 @@ export class AidenRemoteStateRegistry { } draft.devices.push(device); }); - return { credential, device: projectDevice(device) }; + return { credential, device }; } async authenticate(credential: string): Promise { diff --git a/main/services/aiden-remote-streams.ts b/main/services/aiden-remote-streams.ts index c0c8dbd41c..79c2ce9239 100644 --- a/main/services/aiden-remote-streams.ts +++ b/main/services/aiden-remote-streams.ts @@ -175,6 +175,13 @@ export interface AidenRemoteStreamSnapshot { interface StreamSubscriber { flush(): void; close(): void; + /** True for a status observer that delivers no journal replay. */ + observer?: boolean; +} + +function hasReplaySubscriber(stream: { subscribers: Set }): boolean { + for (const subscriber of stream.subscribers) if (!subscriber.observer) return true; + return false; } interface StreamRecord { @@ -1178,7 +1185,7 @@ export class AidenRemoteStreamService { .filter((entry) => entry.streamId !== currentStreamId && terminal(entry.state)) .sort((left, right) => left.updatedAt - right.updatedAt); for (const entry of terminalStreams) { - if (entry.subscribers.size > 0 || entry.evictAfterDelivery) { + if (hasReplaySubscriber(entry) || entry.evictAfterDelivery) { // Keep accepted terminal bytes and replay state until delivery settles. // A disconnected or timed-out subscriber may not have received it. // Defer until successful delivery or normal retention expiry, even if @@ -1932,6 +1939,37 @@ export class AidenRemoteStreamService { } } + /** + * Observe one owned stream without reading its journal. `onChange` runs after + * every appended or coalesced event; `onClose` runs once when the owning + * device is revoked. The returned function detaches the observer. Watching + * never defers terminal eviction, because it delivers no replay. + */ + watch( + deviceId: string, + streamId: string, + handlers: { onChange(): void; onClose(): void }, + ): () => void { + const stream = this.requireStream(deviceId, streamId); + let attached = true; + const subscriber: StreamSubscriber = { + observer: true, + flush: () => { + if (attached) handlers.onChange(); + }, + close: () => { + if (!attached) return; + attached = false; + handlers.onClose(); + }, + }; + stream.subscribers.add(subscriber); + return () => { + attached = false; + stream.subscribers.delete(subscriber); + }; + } + openEvents(deviceId: string, streamId: string, after: number, response: ServerResponse): void { const stream = this.requireStream(deviceId, streamId); const lastSequence = stream.events[stream.events.length - 1]?.sequence ?? 0; @@ -1982,7 +2020,7 @@ export class AidenRemoteStreamService { if ( finished && stream.evictAfterDelivery && - stream.subscribers.size === 0 && + !hasReplaySubscriber(stream) && this.streams.get(streamId) === stream ) { stream.owner.invalidate(); diff --git a/main/services/host-platform-capabilities.test.ts b/main/services/host-platform-capabilities.test.ts index ce3c520275..aea1105bc5 100644 --- a/main/services/host-platform-capabilities.test.ts +++ b/main/services/host-platform-capabilities.test.ts @@ -18,6 +18,7 @@ test("Darwin exposes Apple-owned host integrations", () => { macAppConnectors: true, backgroundJobs: true, hooks: true, + mcpServer: true, }); }); test("Linux exposes Bots while keeping Apple-owned host integrations disabled", () => { @@ -35,6 +36,7 @@ test("Linux exposes Bots while keeping Apple-owned host integrations disabled", macAppConnectors: false, backgroundJobs: true, hooks: true, + mcpServer: true, }); }); @@ -49,6 +51,7 @@ test("unsupported hosts cannot widen native capabilities", () => { assert.equal(capabilities.backgroundJobs, false); assert.equal(capabilities.hooks, false); assert.equal(capabilities.badgeCount, false); + assert.equal(capabilities.mcpServer, false); }); test("Bot computers need Apple silicon: Intel Macs and Linux on Arm get none", () => { diff --git a/main/services/host-platform-capabilities.ts b/main/services/host-platform-capabilities.ts index a824da7941..72ee59b4f3 100644 --- a/main/services/host-platform-capabilities.ts +++ b/main/services/host-platform-capabilities.ts @@ -20,6 +20,12 @@ export interface HostPlatformCapabilities { backgroundJobs: boolean; /** Aiden hooks run commands in their own process group, so they need macOS or Linux, as background jobs do. */ hooks: boolean; + /** + * The loopback MCP server that lets other apps on this computer use Aiden + * (`main/services/aiden-mcp-server.ts`). Off until the person turns it on, + * and offered where Remote Access runs: macOS and Linux. + */ + mcpServer: boolean; } /** * Main-owned host capability policy. Persisted settings and renderer state may @@ -45,5 +51,6 @@ export function hostPlatformCapabilities( macAppConnectors: darwin, backgroundJobs: darwin || platform === "linux", hooks: darwin || platform === "linux", + mcpServer: darwin || platform === "linux", }; } diff --git a/package.json b/package.json index 3c9d299094..5be860856d 100644 --- a/package.json +++ b/package.json @@ -67,7 +67,7 @@ "test:remote-chat": "tsx --test renderer/lib/hosts/remote-chat-mapper.test.ts renderer/lib/hosts/remote-queue-fence.test.ts renderer/lib/hosts/remote-turn-selection.test.ts renderer/lib/hosts/remote-bot-session.test.ts renderer/main/remote-bot-chat-view.test.tsx renderer/lib/hosts/remote-stream-translator.test.ts main/services/peer-remote-chat-view.test.ts renderer/main/remote-chat-view.test.tsx renderer/lib/hosts/chat-session-control.test.ts renderer/lib/hosts/local-host-adapter.test.ts renderer/lib/hosts/observed-local-run.test.ts main/services/peer-remote-chat-control.test.ts renderer/lib/hosts/remote-new-chat.test.ts renderer/lib/hosts/host-resources.test.ts renderer/lib/hosts/new-chat-targets.test.ts renderer/main/remote-new-chat-view.test.tsx renderer/main/remote-chat-images.test.tsx main/services/peer-remote-new-chat.test.ts main/services/peer-remote-chat-fork.test.ts main/services/peer-remote-chat-context.test.ts", "test:peer-hosts": "tsx --test main/services/peer-intent-store.test.ts main/handlers/peer-intents.test.ts main/services/peer-host-registry.test.ts main/services/peer-transport.test.ts main/services/peer-operation.test.ts main/services/peer-host-feed-cache.test.ts main/services/peer-run-subscriptions.test.ts main/services/peer-host-manager.test.ts main/handlers/peer-host-live.test.ts main/services/peer-bootstrap-transport.test.ts main/services/peer-host-pairing.test.ts main/services/peer-pairing-client.test.ts main/services/peer-discovery.test.ts main/handlers/peer-pairing.test.ts main/services/peer-lan-addresses.test.ts main/services/peer-multi-host-acceptance.test.ts main/services/peer-bot-sessions.test.ts main/services/peer-project-source.test.ts main/services/peer-project-file-io.test.ts main/handlers/peer-project-clone.test.ts renderer/shared/peer-project-clone.test.ts renderer/main/peer-project-clone-dialog.test.tsx", "pretest:aiden-remote": "npm run build:worktree-file-io", - "test:aiden-remote": "npm run test:peer-hosts && tsx --test main/services/aiden-remote-chat-progress.test.ts main/services/aiden-remote-durable-operation.test.ts main/services/aiden-remote-chat-progress-authorize.test.ts main/handlers/aiden-remote.test.ts main/services/aiden-remote-chat-summaries.test.ts main/services/aiden-remote-approved-roots.test.ts main/services/aiden-remote-revocation.test.ts main/services/aiden-remote-bot-files.test.ts main/services/aiden-remote-bots.test.ts main/services/aiden-remote-bot-session.test.ts main/services/aiden-remote-bot-handoffs.test.ts main/services/aiden-remote-chat-http.test.ts main/services/aiden-remote-chats.test.ts main/services/visual-viewer-document.test.ts main/services/aiden-remote-files.test.ts main/services/aiden-remote-git.test.ts main/services/aiden-remote-models.test.ts main/services/aiden-remote-protocol.test.ts main/services/aiden-remote-opaque-handles.test.ts main/services/aiden-remote-operation-contract.test.ts main/services/aiden-remote-pairing.test.ts main/services/aiden-remote-pairing-requests.test.ts main/services/aiden-remote-pairing-requests-router.test.ts main/services/aiden-remote-pairing-request-host.test.ts main/services/aiden-remote-sealed-envelope.test.ts main/services/aiden-remote-ports.test.ts main/services/aiden-remote-router.test.ts main/services/aiden-remote-schedules.test.ts main/services/aiden-remote-service.test.ts main/services/aiden-remote-state.test.ts main/services/aiden-remote-streams.test.ts main/services/aiden-remote-tailscale-route.test.ts main/services/aiden-remote-tailscale.test.ts main/services/aiden-remote-tls-identity.test.ts main/services/aiden-remote-lan-hostname.test.ts main/services/aiden-remote-workspace-browser.test.ts main/services/aiden-remote-workspace-http.test.ts main/services/aiden-remote-workspaces.test.ts renderer/components/remote-connection-popover.test.tsx renderer/components/remote-pairing-request-sheet.test.tsx renderer/components/settings/remote-access-settings.test.tsx renderer/lib/remote-approval.test.ts renderer/lib/remote-connection-status.test.ts renderer/lib/remote-pairing-lifecycle.test.ts renderer/lib/settings-section.test.ts main/services/run-event-projection.test.ts main/services/host-run-registry.test.ts main/services/host-runs.test.ts main/services/aiden-remote-host-feed.test.ts main/services/aiden-remote-host-runs.test.ts main/services/aiden-remote-approval-schedule.test.ts main/handlers/local-runs.test.ts main/services/repository-identity.test.ts renderer/lib/peer-connections.test.ts renderer/components/settings/connections-settings.test.tsx main/services/aiden-remote-new-worktree.test.ts main/services/aiden-remote-bot-watches.test.ts main/services/aiden-remote-bot-allowed.test.ts && node --test scripts/aiden-remote-lan-transport-spike.test.mjs", + "test:aiden-remote": "npm run test:peer-hosts && tsx --test main/services/aiden-remote-chat-progress.test.ts main/services/aiden-remote-durable-operation.test.ts main/services/aiden-remote-chat-progress-authorize.test.ts main/handlers/aiden-remote.test.ts main/services/aiden-remote-chat-summaries.test.ts main/services/aiden-remote-approved-roots.test.ts main/services/aiden-remote-revocation.test.ts main/services/aiden-remote-bot-files.test.ts main/services/aiden-remote-bots.test.ts main/services/aiden-remote-bot-session.test.ts main/services/aiden-remote-bot-handoffs.test.ts main/services/aiden-remote-chat-http.test.ts main/services/aiden-remote-chats.test.ts main/services/visual-viewer-document.test.ts main/services/aiden-remote-files.test.ts main/services/aiden-remote-git.test.ts main/services/aiden-remote-models.test.ts main/services/aiden-remote-protocol.test.ts main/services/aiden-remote-opaque-handles.test.ts main/services/aiden-remote-operation-contract.test.ts main/services/aiden-remote-pairing.test.ts main/services/aiden-remote-pairing-requests.test.ts main/services/aiden-remote-pairing-requests-router.test.ts main/services/aiden-remote-pairing-request-host.test.ts main/services/aiden-remote-sealed-envelope.test.ts main/services/aiden-remote-ports.test.ts main/services/aiden-remote-router.test.ts main/services/aiden-remote-schedules.test.ts main/services/aiden-remote-service.test.ts main/services/aiden-remote-state.test.ts main/services/aiden-mcp-server.test.ts main/services/aiden-remote-streams.test.ts main/services/aiden-remote-tailscale-route.test.ts main/services/aiden-remote-tailscale.test.ts main/services/aiden-remote-tls-identity.test.ts main/services/aiden-remote-lan-hostname.test.ts main/services/aiden-remote-workspace-browser.test.ts main/services/aiden-remote-workspace-http.test.ts main/services/aiden-remote-workspaces.test.ts renderer/components/remote-connection-popover.test.tsx renderer/components/remote-pairing-request-sheet.test.tsx renderer/components/settings/remote-access-settings.test.tsx renderer/lib/remote-approval.test.ts renderer/lib/remote-connection-status.test.ts renderer/lib/remote-pairing-lifecycle.test.ts renderer/lib/settings-section.test.ts main/services/run-event-projection.test.ts main/services/host-run-registry.test.ts main/services/host-runs.test.ts main/services/aiden-remote-host-feed.test.ts main/services/aiden-remote-host-runs.test.ts main/services/aiden-remote-approval-schedule.test.ts main/handlers/local-runs.test.ts main/services/repository-identity.test.ts renderer/lib/peer-connections.test.ts renderer/components/settings/connections-settings.test.tsx main/services/aiden-remote-new-worktree.test.ts main/services/aiden-remote-bot-watches.test.ts main/services/aiden-remote-bot-allowed.test.ts && node --test scripts/aiden-remote-lan-transport-spike.test.mjs", "test:aiden-remote-chat-summaries": "tsx --test main/services/aiden-remote-chat-summaries.test.ts", "test:memory-policy": "tsx --test main/services/memory-policy.test.ts main/services/aiden-remote-memory-settings.test.ts renderer/components/settings/memory-settings.test.tsx", "test:storage": "tsx --test main/services/storage-usage-core.test.ts main/services/storage-usage.test.ts renderer/components/settings/storage-settings.test.ts", diff --git a/scripts/ci-test-registry.json b/scripts/ci-test-registry.json index fd6f04ee09..e35f2786ab 100644 --- a/scripts/ci-test-registry.json +++ b/scripts/ci-test-registry.json @@ -505,6 +505,7 @@ "main/services/aiden-remote-service.test.ts", "main/services/aiden-remote-simulators.test.ts", "main/services/aiden-remote-speech.test.ts", + "main/services/aiden-mcp-server.test.ts", "main/services/aiden-remote-state.test.ts", "main/services/aiden-remote-streams.test.ts", "main/services/aiden-remote-tailscale-route.test.ts", From 24c277f3225c13fb5083c102c9d1fed139bc5c94 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 11 Nov 2026 15:23:19 -0500 Subject: [PATCH 2/9] MCP apps reach only the chats aiden_chat_list shows An agent credential could read, wait on, send to or stop assistant and design-project chats by id although aiden_chat_list hides them. Every chat tool now refuses any chat the list leaves out with the unknown-id answer, so an app cannot learn such a chat exists. Co-Authored-By: Claude Opus 5.5 --- .memory/aiden-mcp-server.md | 2 +- docs/aiden-mcp-server.md | 2 +- docs/security/aiden-remote-threat-model.md | 3 +- main/services/aiden-mcp-server.test.ts | 45 ++++++++++++++++++++++ main/services/aiden-mcp-tools.ts | 12 ++++-- main/services/aiden-remote-chats.ts | 11 ++++++ 6 files changed, 69 insertions(+), 6 deletions(-) diff --git a/.memory/aiden-mcp-server.md b/.memory/aiden-mcp-server.md index 287e7fdd0f..32231bb36b 100644 --- a/.memory/aiden-mcp-server.md +++ b/.memory/aiden-mcp-server.md @@ -46,7 +46,7 @@ Core only: a loopback MCP server that lets Claude Code, Codex or any MCP client - Waits are at most 55 s and default to 25 s. - **Reach:** - `aiden_workspace_list` and `aiden_chat_start` exclude `noWorkspace` folders and `ASSISTANT_WORKSPACE_ID`. - - Chat list is regular chats only, and `requireOrdinaryChat` refuses Bot chats by id. + - Chat list is regular chats only. `requireOrdinaryChat` refuses by id every chat the list hides (Bot, feature, assistant), via `AidenRemoteChatService.isListedChat`, with the unknown-id answer so existence is not leaked. - Assistant and feature chats are still readable and sendable by id, as on phones. - **No approval tool.** `aiden_chat_wait` returns `waiting_for_approval` or `waiting_for_input` with `approveIn` / `answerIn` set to "Aiden on ". - **Revoke:** diff --git a/docs/aiden-mcp-server.md b/docs/aiden-mcp-server.md index f69fc217ee..40114b72f4 100644 --- a/docs/aiden-mcp-server.md +++ b/docs/aiden-mcp-server.md @@ -56,7 +56,7 @@ At most 16 apps can be connected at once, separately from the phone and Mac devi | `aiden_chat_send` | Sends a follow-up to an existing ordinary chat (also idempotent by `clientRequestId`). | | `aiden_chat_stop` | Stops a run **this app** started. Another app's runs, and the person's own, cannot be stopped or waited on. | -Arguments are validated against each tool's schema, and unknown properties are rejected. A message can be at most 200,000 characters, and messages read back are capped at 20,000 characters each. Bot chats cannot be read or written by id, even when the id is known. +Arguments are validated against each tool's schema, and unknown properties are rejected. A message can be at most 200,000 characters, and messages read back are capped at 20,000 characters each. A chat `aiden_chat_list` leaves out (Bot, feature or assistant) cannot be read, waited on, sent to or stopped by id, even when the id is known. Every chat tool answers it exactly as it answers an unknown id (`This Aiden chat no longer exists.`), so an app cannot tell such a chat exists. MCP apps are trusted less than paired phones, which can open assistant chats. There is deliberately no tool for approvals or questions. When a turn needs one, `aiden_chat_wait` says so and where, and the person answers it in Aiden on that computer. A turn runs with the permissions of its workspace. In a Full-access workspace, tools run without asking, exactly as if the person had typed the message. diff --git a/docs/security/aiden-remote-threat-model.md b/docs/security/aiden-remote-threat-model.md index ad3c4b81a8..1ff1524f89 100644 --- a/docs/security/aiden-remote-threat-model.md +++ b/docs/security/aiden-remote-threat-model.md @@ -183,7 +183,7 @@ Outside app (Claude Code, Codex, any MCP client) on this computer - Apps never answer approvals or questions; the person does, in Aiden on the computer. - **Browser and rebinding.** `Host` must be the exact loopback host and port, and any `Origin` other than the same loopback origin is refused. No `Access-Control-*` header is ever sent. - **Reach.** - - Apps see ordinary chats and offered workspaces only. Bot, feature and assistant chats are not listed, Bot chats are refused by id, and new chats cannot be started in one-chat folders or the assistant workspace. + - Apps see ordinary chats and offered workspaces only. Bot, feature and assistant chats are not listed, and every chat tool refuses them by id with the same not-found answer as an unknown id, so an app cannot learn they exist. MCP apps are trusted less than paired phones, which can open assistant chats. New chats cannot be started in one-chat folders or the assistant workspace. - An app can wait on and stop only runs it started. - **Residual risk.** A Supervised app is delegated the person's own authority in the chosen workspace. In a Full-access workspace its turns run tools without approval. Supervised access and Full-access workspaces are the person's informed choices; neither is containment. - **Revocation** goes through `revokeAidenRemoteRuntimeDevice`: @@ -209,5 +209,6 @@ Required evidence: `main/services/aiden-mcp-server.test.ts` covers: - revoke ending a wait - the rate and concurrency limits - Bot chats and hidden workspaces out of reach +- assistant and feature chats answering every chat tool as an unknown id does `main/services/aiden-remote-router.test.ts` covers agent tokens on `/api/aiden/v1`. `main/services/aiden-remote-state.test.ts` covers the capability ceiling and the app quota. diff --git a/main/services/aiden-mcp-server.test.ts b/main/services/aiden-mcp-server.test.ts index ff3a85ae05..fddd238214 100644 --- a/main/services/aiden-mcp-server.test.ts +++ b/main/services/aiden-mcp-server.test.ts @@ -893,3 +893,48 @@ test("Bot chats and the folders Aiden makes for one chat are out of an app's rea await fixture.close(); } }); + +test("assistant and design-project chats answer every chat tool exactly as an unknown chat does", async () => { + const fixture = await harness(); + try { + await fixture.enable(); + const hidden: Record> = { + "assistant-chat-1": { workspaceId: "assistant" }, + "design-chat-1": { workspaceId: "workspace-1", owner: { kind: "design-project", projectId: "project-1" } }, + }; + for (const [id, fields] of Object.entries(hidden)) { + fixture.chats.set(id, { + id, + title: "Private", + providerId: "provider-1", + model: "model-1", + createdAt: 1_000, + updatedAt: 9_000, + messages: [{ id: `${id}-message`, role: "assistant", content: "Private note", createdAt: 1_500 }], + ...fields, + } as Chat); + } + const client = await fixture.connect((await fixture.host.issueApp({ name: "Codex", access: "supervised" })).credential); + assert.deepEqual(structured(await client.callTool({ name: "aiden_chat_list", arguments: {} })).chats, []); + + const answers = async (chatId: string) => [ + refusal(await client.callTool({ name: "aiden_chat_read", arguments: { chatId } })), + refusal(await client.callTool({ name: "aiden_chat_wait", arguments: { chatId, runId: "run-1", timeoutSeconds: 1 } })), + refusal( + await client.callTool({ + name: "aiden_chat_send", + arguments: { clientRequestId: `send-${chatId}`, chatId, text: "Hi" }, + }), + ), + refusal(await client.callTool({ name: "aiden_chat_stop", arguments: { chatId, runId: "run-1" } })), + ]; + const unknown = await answers("chat-that-never-existed"); + assert.deepEqual(unknown, Array(4).fill("This Aiden chat no longer exists.")); + for (const id of Object.keys(hidden)) assert.deepEqual(await answers(id), unknown, id); + + for (const id of Object.keys(hidden)) assert.equal(fixture.chats.get(id)!.messages.length, 1); + assert.equal(fixture.generationStarts(), 0); + } finally { + await fixture.close(); + } +}); diff --git a/main/services/aiden-mcp-tools.ts b/main/services/aiden-mcp-tools.ts index c5fd638a8e..ff19735eb6 100644 --- a/main/services/aiden-mcp-tools.ts +++ b/main/services/aiden-mcp-tools.ts @@ -36,7 +36,7 @@ export interface AidenMcpApp { } export interface AidenMcpServices { - chats: Pick; + chats: Pick; streams: Pick; workspaces: Pick; } @@ -584,13 +584,19 @@ async function offeredWorkspaces(services: AidenMcpServices) { return workspaces.filter((workspace) => workspace.noWorkspace !== true && workspace.id !== ASSISTANT_WORKSPACE_ID); } -/** Bot chats are not offered to outside apps; they read as missing. */ +/** + * An app reaches only the chats aiden_chat_list shows it. Bot, assistant and + * feature-owned chats read as missing, with the same answer as an unknown id, + * so an app cannot tell they exist. + */ async function requireOrdinaryChat( services: AidenMcpServices, chatId: string, ): Promise>> { const classification = await services.chats.classify(chatId); - if (classification.botId) throw new ToolRefusal("This Aiden chat no longer exists."); + if (classification.botId || !(await services.chats.isListedChat(chatId))) { + throw new ToolRefusal("This Aiden chat no longer exists."); + } return classification; } diff --git a/main/services/aiden-remote-chats.ts b/main/services/aiden-remote-chats.ts index 1a3ecd96a6..8684b07365 100644 --- a/main/services/aiden-remote-chats.ts +++ b/main/services/aiden-remote-chats.ts @@ -1943,6 +1943,17 @@ export class AidenRemoteChatService { }; } + /** + * True when `listSummaries` would show this chat: an ordinary chat with a + * safe id, workspace and timestamps. Never a Bot, assistant or + * feature-owned chat. Transcript-free: one read of the metadata index. + */ + async isListedChat(chatId: string): Promise { + const id = safeId(chatId, "chat"); + const metadata = (await this.options.application.list()).find((entry) => entry.id === id); + return metadata !== undefined && safeSummaryMetadata(metadata) !== null; + } + /** * Resolve only immutable chat classification from the main-owned metadata * index. Authorization callers use this before any payload read that could From fc71b603f8c71dd168c0dd04d9cf6b70d5639d91 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 11 Nov 2026 15:46:20 -0500 Subject: [PATCH 3/9] MCP: wake waits on a missed finish, replay forgotten retries free, send no usage data - aiden_chat_wait re-reads the run once its watch is attached, so a run that finishes in between wakes it at once, and it answers with the finished state it saw even if that run is later evicted. - A clientRequestId Aiden already recorded replays without counting against the rate limit or run cap, after the in-memory cache forgets it or a restart. - Chats and turns from an MCP app (an agent device) send no chat_created or chat_message_sent. Co-Authored-By: Claude Opus 5.5 --- docs/aiden-mcp-server.md | 4 +- docs/analytics.md | 2 + main/services/aiden-mcp-server.test.ts | 27 +++++++++ main/services/aiden-mcp-tools.ts | 55 ++++++++++++------- main/services/aiden-remote-chats.test.ts | 25 ++++++++- main/services/aiden-remote-chats.ts | 25 ++++++++- .../aiden-remote-operation-contract.ts | 9 +++ main/services/aiden-remote-service-main.ts | 3 + .../services/chat-application-service.test.ts | 7 +++ main/services/chat-application-service.ts | 7 ++- 10 files changed, 139 insertions(+), 25 deletions(-) diff --git a/docs/aiden-mcp-server.md b/docs/aiden-mcp-server.md index 40114b72f4..a173f930ea 100644 --- a/docs/aiden-mcp-server.md +++ b/docs/aiden-mcp-server.md @@ -62,7 +62,7 @@ There is deliberately no tool for approvals or questions. When a turn needs one, ## Limits -- **Turns:** each app can start or send 10 turns a minute and have 2 runs at once. A retry of an accepted `clientRequestId` does not count again. +- **Turns:** each app can start or send 10 turns a minute and have 2 runs at once. A retry of an accepted `clientRequestId` does not count again, even after a restart or after many newer requests: Aiden's durable request record answers it. - **Requests:** - A request body over 1 MiB is answered 413 before any tool runs, whether its size is declared or streamed. - The server drains the rest of an oversized upload for up to 5 seconds so the app sees the 413, then cuts the connection. @@ -96,7 +96,7 @@ Privacy: - Aiden keeps a local note of which app started a chat (`startedBy {kind: "app", name}`, in `aiden-mcp-chat-provenance.json`, the newest 1,000 entries). It is never sent to phones, Macs or apps. - App ids never appear in tool results. - Server logs carry only `started`, `stopped`, `start-failed` (with a problem code) and `request-failed`, never a token, an app name, a path or chat text. -- No analytics events are sent for the MCP server. +- No analytics events are sent for the MCP server: a chat an app starts sends no `chat_created`, and its turns send no `chat_message_sent`. The Remote Access threat model has the matching section: [`docs/security/aiden-remote-threat-model.md`](security/aiden-remote-threat-model.md#10-local-mcp-server-for-outside-apps). diff --git a/docs/analytics.md b/docs/analytics.md index 115064cba8..ccce9d0340 100644 --- a/docs/analytics.md +++ b/docs/analytics.md @@ -57,6 +57,8 @@ How the values are limited: - `in_workspace` is true only for a real workspace. Messages to a Bot always report false, and report `origin: bot` whichever surface sent them. - `trigger` is automatic, manual, catch_up, retry, file_change, webhook or watch. `thinking` is the level chosen for the turn, or other when Aiden doesn't know it, as for a message to a Bot. +Chats and turns an outside MCP app starts through the local MCP server are never counted: no `chat_created` and no `chat_message_sent`. + Bot continuity integration: host-issued watch/routine and approved-peer task/result inputs do not count as a person’s `chat_message_sent`, including routines without display labels. A person’s accepted durable input reports only allowlisted IDs from its admitted execution model; analytics never resolves the Bot’s unrelated current default or changes its saved model/fallback choice. Duplicates and Resume do not add message events. ## Crash reports diff --git a/main/services/aiden-mcp-server.test.ts b/main/services/aiden-mcp-server.test.ts index fddd238214..e5e81a89db 100644 --- a/main/services/aiden-mcp-server.test.ts +++ b/main/services/aiden-mcp-server.test.ts @@ -846,6 +846,33 @@ test("each app has its own turn rate limit and run cap, and a retry does not cou } }); +test("a retry the server's request cache has forgotten still replays, without counting as a new turn", async () => { + // Room for exactly the first start, its send and 128 more: then the rate limit is spent. + const fixture = await harness({ limits: { turnsPerMinute: 130, concurrentRuns: 130 } }); + try { + await fixture.enable(); + const client = await fixture.connect((await fixture.host.issueApp({ name: "Retrier", access: "supervised" })).credential); + const start = (id: string) => + client.callTool({ name: "aiden_chat_start", arguments: { clientRequestId: id, workspaceId: "workspace-1", text: "Go" } }); + const sendArgs = (chatId: unknown) => ({ clientRequestId: "evicted-send-1", chatId, text: "More" }); + + const first = structured(await start("evicted-start-1")); + await client.callTool({ name: "aiden_chat_wait", arguments: { chatId: first.chatId, runId: first.runId } }); + const sent = structured(await client.callTool({ name: "aiden_chat_send", arguments: sendArgs(first.chatId) })); + // 128 newer requests push both out of the in-memory cache. + for (let index = 0; index < 128; index += 1) structured(await start(`filler-start-${index}`)); + assert.equal(fixture.generationStarts(), 130); + + assert.deepEqual(structured(await start("evicted-start-1")), first); + assert.deepEqual(structured(await client.callTool({ name: "aiden_chat_send", arguments: sendArgs(first.chatId) })), sent); + assert.equal(fixture.generationStarts(), 130); + // A new request is still held to the limit. + assert.match(refusal(await start("fresh-start-1")), /started 130 turns in the last minute/u); + } finally { + await fixture.close(); + } +}); + test("Bot chats and the folders Aiden makes for one chat are out of an app's reach", async () => { const fixture = await harness(); try { diff --git a/main/services/aiden-mcp-tools.ts b/main/services/aiden-mcp-tools.ts index ff19735eb6..6a2df617b8 100644 --- a/main/services/aiden-mcp-tools.ts +++ b/main/services/aiden-mcp-tools.ts @@ -36,7 +36,7 @@ export interface AidenMcpApp { } export interface AidenMcpServices { - chats: Pick; + chats: Pick; streams: Pick; workspaces: Pick; } @@ -382,32 +382,40 @@ export class AidenMcpToolRunner { this.waits.set(app.id, appWaits); let detach: (() => void) | undefined; let timer: ReturnType | undefined; + // The first snapshot that showed the run had stopped running. It answers + // the wait, so a terminal run evicted afterwards still reads as finished. + let observed: Record | undefined; try { const outcome = await new Promise<"changed" | "timeout" | "closed" | "aborted">((resolve) => { const abort = () => resolve("aborted"); signal.addEventListener("abort", abort, { once: true }); controller.signal.addEventListener("abort", () => resolve("closed"), { once: true }); timer = setTimeout(() => resolve("timeout"), timeoutMs); + // Most events (text deltas, tool output) leave the run running; only a + // state change answers the wait. The run's status is read before the + // snapshot's first await, so it is taken while the event is current. + const look = () => { + void this.runSnapshot(services, app, chatId, runId) + .then((snapshot) => { + if (snapshot.state === "running") return; + observed ??= snapshot; + resolve("changed"); + }) + .catch(() => resolve("changed")); + }; try { - detach = services.streams.watch(app.id, runId, { - onChange: () => { - // Most events (text deltas, tool output) leave the run running; - // only a state change answers the wait. - void this.runSnapshot(services, app, chatId, runId) - .then((snapshot) => { - if (snapshot.state !== "running") resolve("changed"); - }) - .catch(() => resolve("changed")); - }, - onClose: () => resolve("closed"), - }); + detach = services.streams.watch(app.id, runId, { onChange: look, onClose: () => resolve("closed") }); } catch { resolve("changed"); + return; } + // The run may have changed after the first snapshot and before the + // watch attached; the watch reports only later events, so look again. + look(); }); if (outcome === "closed") throw new ToolRefusal("This app was disconnected from Aiden."); if (outcome === "aborted") return toolError("The wait ended because the request closed."); - return toolResult(await this.runSnapshot(services, app, chatId, runId)); + return toolResult(observed ?? (await this.runSnapshot(services, app, chatId, runId))); } finally { if (timer) clearTimeout(timer); detach?.(); @@ -425,8 +433,13 @@ export class AidenMcpToolRunner { if (!(await offeredWorkspaces(services)).some((workspace) => workspace.id === args.workspaceId)) { throw new ToolRefusal("Aiden has no workspace with that id. List them with aiden_workspace_list."); } - this.admitTurn(services, app); - const chat = await services.chats.create(app.id, `mcp-create:${clientRequestId}`, { + // A request Aiden already recorded replays its answer and is not counted + // again, even after the in-memory request cache forgot it or a restart. + const createKey = `mcp-create:${clientRequestId}`; + const turnKey = `mcp-turn:${clientRequestId}`; + const createRecorded = services.chats.hasRecordedRequest(app.id, { kind: "create" }, createKey); + if (!createRecorded) this.admitTurn(services, app); + const chat = await services.chats.create(app.id, createKey, { workspaceId: args.workspaceId, ...(providerId ? { providerId } : {}), ...(modelId ? { modelId } : {}), @@ -439,8 +452,11 @@ export class AidenMcpToolRunner { }).catch(() => undefined); // The first turn goes through the same mutation fence as any other turn. const classification = await requireOrdinaryChat(services, chat.id); + if (createRecorded && !services.chats.hasRecordedRequest(app.id, { kind: "turn", chatId: chat.id }, turnKey)) { + this.admitTurn(services, app); + } const turn = await services.chats.runMutation(app.id, chat.id, classification, () => - services.chats.startTurn(app.id, chat.id, `mcp-turn:${clientRequestId}`, { text: args.text }), + services.chats.startTurn(app.id, chat.id, turnKey, { text: args.text }), ); this.trackRun(app.id, turn.streamId); return toolResult({ chatId: chat.id, turnId: turn.turnId, runId: turn.streamId, state: "running" }); @@ -450,9 +466,10 @@ export class AidenMcpToolRunner { const services = await this.dependencies.services(); const chatId = args.chatId as string; const classification = await requireOrdinaryChat(services, chatId); - this.admitTurn(services, app); + const turnKey = `mcp-turn:${args.clientRequestId as string}`; + if (!services.chats.hasRecordedRequest(app.id, { kind: "turn", chatId }, turnKey)) this.admitTurn(services, app); const turn = await services.chats.runMutation(app.id, chatId, classification, () => - services.chats.startTurn(app.id, chatId, `mcp-turn:${args.clientRequestId as string}`, { text: args.text }), + services.chats.startTurn(app.id, chatId, turnKey, { text: args.text }), ); this.trackRun(app.id, turn.streamId); return toolResult({ chatId, turnId: turn.turnId, runId: turn.streamId, state: "running" }); diff --git a/main/services/aiden-remote-chats.test.ts b/main/services/aiden-remote-chats.test.ts index f7f1e34c2e..277ea0cc27 100644 --- a/main/services/aiden-remote-chats.test.ts +++ b/main/services/aiden-remote-chats.test.ts @@ -76,6 +76,7 @@ function fixture( noWorkspace?: ConstructorParameters[0]["noWorkspace"]; isFolderWorkspace?: ConstructorParameters[0]["isFolderWorkspace"]; deviceIsPeer?: ConstructorParameters[0]["deviceIsPeer"]; + deviceReportsAnalytics?: ConstructorParameters[0]["deviceReportsAnalytics"]; modelSupportsImages?: () => boolean; imageArtifactRecoveryPending?: boolean; imageArtifactRecoveryUnavailable?: boolean; @@ -104,6 +105,7 @@ function fixture( ) { let current: Chat | null = structuredClone(initial); let creates = 0; + const createOptions: Array<{ reportAnalytics?: boolean } | undefined> = []; let appends = 0; let notifications = 0; let begins = 0; @@ -142,8 +144,9 @@ function fixture( reconciliation: null, }; }, - create: async (input) => { + create: async (input, _owner, options) => { creates += 1; + createOptions.push(options); current = chat({ id: `chat-${creates + 1}`, workspaceId: input.workspaceId, @@ -301,6 +304,7 @@ function fixture( ...(fixtureOptions.noWorkspace ? { noWorkspace: fixtureOptions.noWorkspace } : {}), ...(fixtureOptions.isFolderWorkspace ? { isFolderWorkspace: fixtureOptions.isFolderWorkspace } : {}), ...(fixtureOptions.deviceIsPeer ? { deviceIsPeer: fixtureOptions.deviceIsPeer } : {}), + ...(fixtureOptions.deviceReportsAnalytics ? { deviceReportsAnalytics: fixtureOptions.deviceReportsAnalytics } : {}), ...(fixtureOptions.workspaceFolderRefusal ? { workspaceFolderRefusal: fixtureOptions.workspaceFolderRefusal } : {}), @@ -330,6 +334,7 @@ function fixture( service, streams, creates: () => creates, + createOptions: () => createOptions, appends: () => appends, notifications: () => notifications, begins: () => begins, @@ -3376,6 +3381,24 @@ test("a paired Mac's message is not counted as a phone's", async (t) => { assert.equal(sent[0]?.props?.origin, "peer"); }); +test("an outside MCP app's new chat and turns send no usage data, and a phone's still do", async (t) => { + const sent = captureAnalyticsEvents(t); + const app = fixture(chat({ workspaceId: "workspace-9" }), { + deviceReportsAnalytics: async (deviceId) => deviceId !== "app-1", + }); + await app.service.startTurn("app-1", "chat-1", "counted-turn-00000007", { text: "hello" }); + await app.service.create("app-1", "chat-create-key-app01", { workspaceId: "workspace-1" }); + await app.service.create("device-1", "chat-create-key-phone1", { workspaceId: "workspace-1" }); + await analyticsSettled(); + assert.deepEqual(sent, [], "the app's turn is not a phone's message"); + // The chat service is told to keep only the app's create out of chat_created. + assert.deepEqual(app.createOptions().map((options) => options?.reportAnalytics !== false), [false, true]); + + await app.service.startTurn("device-1", "chat-3", "counted-turn-00000008", { text: "hello" }); + await analyticsSettled(); + assert.deepEqual(sent.map(({ event, props }) => [event, (props as { origin?: unknown } | undefined)?.origin]), [["chat_message_sent", "phone"]]); +}); + test("a phone's message outside a real workspace is not counted as in one", async (t) => { const sent = captureAnalyticsEvents(t); const app = fixture(chat({ workspaceId: "assistant" }), { isFolderWorkspace: async () => false }); diff --git a/main/services/aiden-remote-chats.ts b/main/services/aiden-remote-chats.ts index 8684b07365..3e5368a73e 100644 --- a/main/services/aiden-remote-chats.ts +++ b/main/services/aiden-remote-chats.ts @@ -1482,6 +1482,11 @@ export class AidenRemoteChatService { isFolderWorkspace?: (workspaceId: string) => Promise; /** For usage data: this device is another paired Mac or Linux host, not a phone. */ deviceIsPeer?: (deviceId: string) => Promise; + /** + * For usage data: false for a device whose chats and turns send no + * analytics (an outside MCP app). Absent or true: they are reported. + */ + deviceReportsAnalytics?: (deviceId: string) => Promise; /** The Mac's Settings → Appearance inline visuals choice for remote turns. */ inlineVisuals?: () => Promise; /** @@ -1763,6 +1768,22 @@ export class AidenRemoteChatService { ); } + /** + * True when this device already made this create or turn request under + * `key`, so repeating it replays the recorded answer and starts nothing new. + */ + hasRecordedRequest( + deviceId: string, + target: { kind: "create" } | { kind: "turn"; chatId: string }, + key: string, + ): boolean { + return this.idempotency.holds( + target.kind === "create" + ? { deviceId, route: "POST /chats", resourceId: "chat-registry", key } + : { deviceId, route: "POST /chats/{id}/turns", resourceId: safeId(target.chatId, "chat"), key }, + ); + } + private async executeIdempotent( scope: { deviceId: string; route: string; resourceId: string; key: string }, input: unknown, @@ -2166,6 +2187,7 @@ export class AidenRemoteChatService { const workspaceId = assignment?.workspaceId ?? (typeof target === "string" ? target : parsed.workspaceId); let uncertain = false; try { + const reportAnalytics = (await this.options.deviceReportsAnalytics?.(deviceId)) !== false; return await this.options.application.create( { workspaceId, @@ -2174,6 +2196,7 @@ export class AidenRemoteChatService { : {}), }, owner, + ...(reportAnalytics ? [] : [{ reportAnalytics: false }] as const), ); } catch (error) { uncertain = isChatCreateReconciliationRequiredError(error); @@ -2949,7 +2972,7 @@ export class AidenRemoteChatService { surface, owner.owner, ); - if (started) { + if (started && (await this.options.deviceReportsAnalytics?.(deviceId)) !== false) { reportChatMessageSent({ providerId: selection.providerId, model: selection.modelId, diff --git a/main/services/aiden-remote-operation-contract.ts b/main/services/aiden-remote-operation-contract.ts index 682b94df1a..716fa601c3 100644 --- a/main/services/aiden-remote-operation-contract.ts +++ b/main/services/aiden-remote-operation-contract.ts @@ -706,6 +706,15 @@ export class AidenIdempotencyLedger { return this.begin(scope, input, action, reference).result; } + /** + * True when this scope already has an operation, in any phase, so `begin` + * would replay or join it rather than run a new action. + */ + holds(scope: { deviceId: string; route: string; resourceId: string; key: string }): boolean { + this.prune(this.now()); + return this.entries.has(createHash("sha256").update(canonical(scope)).digest("base64url")); + } + /** * `execute`, also saying whether this call owns the operation. Only an owner * runs `action`; any other call replays a settled outcome or joins the owner. diff --git a/main/services/aiden-remote-service-main.ts b/main/services/aiden-remote-service-main.ts index ed3b4116ab..69955a09bc 100644 --- a/main/services/aiden-remote-service-main.ts +++ b/main/services/aiden-remote-service-main.ts @@ -688,6 +688,9 @@ async function createRuntime(): Promise { const device = (await state.snapshot()).devices.find((candidate) => candidate.id === deviceId); return device?.type === "mac" || device?.type === "linux"; }, + // An outside MCP app's chats and turns are never product analytics. + deviceReportsAnalytics: async (deviceId) => + (await state.snapshot()).devices.find((candidate) => candidate.id === deviceId)?.type !== "agent", noWorkspace: { // The desktop's sidebar lists a chat only once it knows the chat's workspace, so a // hidden record made or removed here is announced like any other workspace change. diff --git a/main/services/chat-application-service.test.ts b/main/services/chat-application-service.test.ts index 79989b1f9e..d61ce07981 100644 --- a/main/services/chat-application-service.test.ts +++ b/main/services/chat-application-service.test.ts @@ -741,6 +741,13 @@ test("a created chat counts once with its workspace kind, and a refused create c await application.service.create({ workspaceId: "workspace-1", title: "Chat" }, owner()); assert.deepEqual(sent, [{ event: "chat_created", props: { workspace_kind: "folder" } }]); + // A chat an outside MCP app made is created, but not counted. + const uncounted = await application.service.create({ workspaceId: "workspace-1", title: "Chat" }, owner(), { + reportAnalytics: false, + }); + assert.ok(uncounted?.id); + assert.equal(sent.length, 1); + const stale = owner(); stale.invalidate(); await assert.rejects(application.service.create({ workspaceId: "workspace-1", title: "Chat" }, stale)); diff --git a/main/services/chat-application-service.ts b/main/services/chat-application-service.ts index 2ae2076645..e8803b12f6 100644 --- a/main/services/chat-application-service.ts +++ b/main/services/chat-application-service.ts @@ -239,7 +239,8 @@ export function createChatApplicationService(deps: ChatApplicationDependencies) return deps.llmClient.waitForChatIdle(chatId); }, - async create(input: ParsedPublicChatCreate, owner: ChatApplicationOwner) { + /** `reportAnalytics: false` keeps `chat_created` unsent (an outside MCP app made the chat). */ + async create(input: ParsedPublicChatCreate, owner: ChatApplicationOwner, options?: { reportAnalytics?: boolean }) { if (deps.llmClient.requiresAppendReconciliation(owner.documentId)) { throw new Error(appendReconciliationFailureMessage("blocked")); } @@ -272,7 +273,9 @@ export function createChatApplicationService(deps: ChatApplicationDependencies) }; try { const chat = chatForRenderer(await deps.chatStore.create({ ...input, assertCurrent })); - reportAnalyticsEvent("chat_created", { workspace_kind: analyticsWorkspaceKind(workspace) }); + if (options?.reportAnalytics !== false) { + reportAnalyticsEvent("chat_created", { workspace_kind: analyticsWorkspaceKind(workspace) }); + } return chat; } catch (error) { if (isChatCreateReconciliationRequiredError(error)) { From 8d94068d69fed2c64695d8b4790b3160ccc6aba4 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 11 Nov 2026 15:47:15 -0500 Subject: [PATCH 4/9] Memory: MCP apps cannot reach assistant or feature chats; replay and analytics notes Co-Authored-By: Claude Opus 5.5 --- .memory/aiden-mcp-server.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.memory/aiden-mcp-server.md b/.memory/aiden-mcp-server.md index 32231bb36b..d7798f21e9 100644 --- a/.memory/aiden-mcp-server.md +++ b/.memory/aiden-mcp-server.md @@ -42,12 +42,13 @@ Core only: a loopback MCP server that lets Claude Code, Codex or any MCP client - The server drains the rest for up to 5 s and then destroys the socket. Using `connection: close` instead raced the client's upload, and the client saw ECONNRESET in place of the 413. - **Write tools:** - They need `chat:write`, and Read apps do not see them listed. - - Turns are limited to 10 a minute and 2 concurrent runs per app; an idempotent retry does not count. + - Turns are limited to 10 a minute and 2 concurrent runs per app; an idempotent retry does not count, even after the 128-entry request cache forgets it or a restart (`AidenRemoteChatService.hasRecordedRequest` checks the durable ledger before admission). + - MCP app chats and turns send no `chat_created` / `chat_message_sent` (`deviceReportsAnalytics` is false for `agent` devices). - Waits are at most 55 s and default to 25 s. - **Reach:** - `aiden_workspace_list` and `aiden_chat_start` exclude `noWorkspace` folders and `ASSISTANT_WORKSPACE_ID`. - Chat list is regular chats only. `requireOrdinaryChat` refuses by id every chat the list hides (Bot, feature, assistant), via `AidenRemoteChatService.isListedChat`, with the unknown-id answer so existence is not leaked. - - Assistant and feature chats are still readable and sendable by id, as on phones. + - Phones can still read and send to assistant and feature chats by id; MCP apps cannot. - **No approval tool.** `aiden_chat_wait` returns `waiting_for_approval` or `waiting_for_input` with `approveIn` / `answerIn` set to "Aiden on ". - **Revoke:** - It runs `revokeAidenRemoteRuntimeDevice`, which denies approvals, cancels runs and closes watchers. From be96c7b4704a1a14fb2280619d733950f0cd5053 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 11 Nov 2026 16:11:32 -0500 Subject: [PATCH 5/9] Revoke an MCP app even when Bot storage waits for repair The app's token is tombstoned first; a BotCapabilityUnavailableError from removing its Bot notice audience (no Secret Service on Linux, say) is now logged instead of failing the revoke and leaving the app listed in Settings. Phone revokes still require it. Ported from W4b (#803). Co-Authored-By: Claude Opus 5.5 --- main/services/aiden-remote-service-main.ts | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/main/services/aiden-remote-service-main.ts b/main/services/aiden-remote-service-main.ts index 69955a09bc..dc2f890b55 100644 --- a/main/services/aiden-remote-service-main.ts +++ b/main/services/aiden-remote-service-main.ts @@ -167,6 +167,7 @@ import { botHandoffs } from "./bot-runtime/bot-handoffs-main.js"; import { botRunStarts, botTurnIntents } from "./bot-runtime/bot-turn-intents-main.js"; import { botMutationGate } from "./bot-mutation-gate.js"; import { botApplicationService } from "./bot-application-service-main.js"; +import { BotCapabilityUnavailableError } from "./bot-capability-store-core.js"; import { BOT_DESKTOP_AUDIENCE_ID, botRuntimeAuthority, @@ -482,7 +483,10 @@ async function createRuntime(): Promise { logger.warn("aiden-remote", `Connection request notification ${stage} failed.`); }, }); - const revokeDevice = async (deviceId: string): Promise => { + const revokeDevice = async ( + deviceId: string, + botNotices: "required" | "when-available" = "required", + ): Promise => { activeReadAloud?.revokeDevice(deviceId); activeProgress?.revokeDevice(deviceId); simulatorShareRelay.revokeDevice(deviceId); @@ -507,7 +511,15 @@ async function createRuntime(): Promise { // Cleanup is intentionally idempotent: a retry after a crash between the // device tombstone and notice removal must still remove the acceptance. if (hostPlatformCapabilities().bots) { - await botApplicationService.revokeNoticeAudience(deviceId); + try { + await botApplicationService.revokeNoticeAudience(deviceId); + } catch (error) { + // An outside app's token is already tombstoned above. Bot storage that is + // waiting for repair (no Secret Service on Linux, say) must not make + // Settings report the app as still connected. + if (botNotices === "required" || !(error instanceof BotCapabilityUnavailableError)) throw error; + logger.warn("aiden-mcp", "revoke-bot-notices-unavailable", {}); + } } return revoked; }; @@ -1302,7 +1314,7 @@ async function createRuntime(): Promise { tools: mcpTools, supported: () => hostPlatformCapabilities().mcpServer, defaultPort: runtimeProfile.id === "development" ? AIDEN_MCP_DEVELOPMENT_PORT : AIDEN_MCP_PRODUCTION_PORT, - revokeDevice, + revokeDevice: (appId) => revokeDevice(appId, "when-available"), appVersion: app.getVersion(), // Category-only: never a credential, app name, chat or path. log: (event, details) => logger.info("aiden-mcp", event, details ?? {}), From 50389235faea631dfedadcf00448bc11aa85d419 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 11 Nov 2026 16:18:17 -0500 Subject: [PATCH 6/9] Docs: list the MCP revoke-bot-notices-unavailable log event Co-Authored-By: Claude Opus 5.5 --- docs/aiden-mcp-server.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/aiden-mcp-server.md b/docs/aiden-mcp-server.md index a173f930ea..fa6a2d7d6f 100644 --- a/docs/aiden-mcp-server.md +++ b/docs/aiden-mcp-server.md @@ -95,7 +95,7 @@ Privacy: - Aiden keeps a local note of which app started a chat (`startedBy {kind: "app", name}`, in `aiden-mcp-chat-provenance.json`, the newest 1,000 entries). It is never sent to phones, Macs or apps. - App ids never appear in tool results. -- Server logs carry only `started`, `stopped`, `start-failed` (with a problem code) and `request-failed`, never a token, an app name, a path or chat text. +- Server logs carry only `started`, `stopped`, `start-failed` (with a problem code), `request-failed` and `revoke-bot-notices-unavailable` (an app was disconnected while Bot storage waits for repair), never a token, an app name, a path or chat text. - No analytics events are sent for the MCP server: a chat an app starts sends no `chat_created`, and its turns send no `chat_message_sent`. The Remote Access threat model has the matching section: [`docs/security/aiden-remote-threat-model.md`](security/aiden-remote-threat-model.md#10-local-mcp-server-for-outside-apps). From 27e6113f372ce56d719367b6eca332d4aa6ad366 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 11 Nov 2026 16:37:02 -0500 Subject: [PATCH 7/9] Share the app-revoke Bot notice policy as a tested helper `revokeBotNoticeAudience` in bot-capability-store-core.ts decides when a revoke may skip clearing Bot notices: only for an outside app, and only on BotCapabilityUnavailableError. It has its own behavioral test. Remote main now calls it, and the bots contract matches that call, which fixes the runtime-subagents failure from be96c7b47. Co-Authored-By: Claude Opus 5.5 --- main/handlers/bots.contract.test.ts | 2 +- main/services/aiden-remote-service-main.ts | 16 ++++-------- .../bot-capability-store-core.test.ts | 22 ++++++++++++++++ main/services/bot-capability-store-core.ts | 26 +++++++++++++++++++ 4 files changed, 54 insertions(+), 12 deletions(-) diff --git a/main/handlers/bots.contract.test.ts b/main/handlers/bots.contract.test.ts index 51225be96f..35e8b0f17f 100644 --- a/main/handlers/bots.contract.test.ts +++ b/main/handlers/bots.contract.test.ts @@ -76,7 +76,7 @@ test("Remote production wires Bot notice and retained-chat policy authority", () assert.match(remote, /revokeNoticeAudience\(deviceId\)/u); assert.match( remote, - /const revoked = await revokeAidenRemoteRuntimeDevice[\s\S]*if \(hostPlatformCapabilities\(\)\.bots\) \{\s*await botApplicationService\.revokeNoticeAudience\(deviceId\);\s*\}\s*return revoked;/u, + /const revoked = await revokeAidenRemoteRuntimeDevice[\s\S]*if \(hostPlatformCapabilities\(\)\.bots\) \{\s*await revokeBotNoticeAudience\(\(\) => botApplicationService\.revokeNoticeAudience\(deviceId\), botNotices,[\s\S]*?\);\s*\}\s*return revoked;/u, ); }); diff --git a/main/services/aiden-remote-service-main.ts b/main/services/aiden-remote-service-main.ts index dc2f890b55..15bcfd436c 100644 --- a/main/services/aiden-remote-service-main.ts +++ b/main/services/aiden-remote-service-main.ts @@ -167,7 +167,7 @@ import { botHandoffs } from "./bot-runtime/bot-handoffs-main.js"; import { botRunStarts, botTurnIntents } from "./bot-runtime/bot-turn-intents-main.js"; import { botMutationGate } from "./bot-mutation-gate.js"; import { botApplicationService } from "./bot-application-service-main.js"; -import { BotCapabilityUnavailableError } from "./bot-capability-store-core.js"; +import { revokeBotNoticeAudience, type BotNoticeRevokePolicy } from "./bot-capability-store-core.js"; import { BOT_DESKTOP_AUDIENCE_ID, botRuntimeAuthority, @@ -485,7 +485,7 @@ async function createRuntime(): Promise { }); const revokeDevice = async ( deviceId: string, - botNotices: "required" | "when-available" = "required", + botNotices: BotNoticeRevokePolicy = "required", ): Promise => { activeReadAloud?.revokeDevice(deviceId); activeProgress?.revokeDevice(deviceId); @@ -511,15 +511,9 @@ async function createRuntime(): Promise { // Cleanup is intentionally idempotent: a retry after a crash between the // device tombstone and notice removal must still remove the acceptance. if (hostPlatformCapabilities().bots) { - try { - await botApplicationService.revokeNoticeAudience(deviceId); - } catch (error) { - // An outside app's token is already tombstoned above. Bot storage that is - // waiting for repair (no Secret Service on Linux, say) must not make - // Settings report the app as still connected. - if (botNotices === "required" || !(error instanceof BotCapabilityUnavailableError)) throw error; - logger.warn("aiden-mcp", "revoke-bot-notices-unavailable", {}); - } + await revokeBotNoticeAudience(() => botApplicationService.revokeNoticeAudience(deviceId), botNotices, () => + logger.warn("aiden-mcp", "revoke-bot-notices-unavailable", {}), + ); } return revoked; }; diff --git a/main/services/bot-capability-store-core.test.ts b/main/services/bot-capability-store-core.test.ts index 171ef5674a..322b433cf9 100644 --- a/main/services/bot-capability-store-core.test.ts +++ b/main/services/bot-capability-store-core.test.ts @@ -30,6 +30,7 @@ import { projectBotAccessView, projectBotChatAccessView, projectBotNoticeStatus, + revokeBotNoticeAudience, type BotCapabilityState, } from "./bot-capability-store-core.js"; @@ -861,3 +862,24 @@ test("notice acknowledgement is isolated by stable audience and action admission ); editor.assertBotMayAct({ audienceId: "device:b", botId: "bot:one" }); }); + +test("an app's revoke skips Bot notices only while Bot storage waits for repair", async () => { + const unavailable = () => { throw new BotCapabilityUnavailableError(); }; + let skipped = 0; + await revokeBotNoticeAudience(unavailable, "when-available", () => { skipped += 1; }); + assert.equal(skipped, 1, "the app's revoke goes through and the skip is reported"); + + // A phone's revoke still fails, so a retry removes the acceptance later. + await assert.rejects(revokeBotNoticeAudience(unavailable, "required", () => { skipped += 1; }), BotCapabilityUnavailableError); + // Any other failure is not Bot storage waiting for repair. + await assert.rejects( + revokeBotNoticeAudience(() => Promise.reject(new Error("disk full")), "when-available", () => { skipped += 1; }), + /disk full/u, + ); + assert.equal(skipped, 1); + + let cleared = 0; + await revokeBotNoticeAudience(async () => { cleared += 1; return true; }, "required", () => { skipped += 1; }); + assert.equal(cleared, 1); + assert.equal(skipped, 1, "a revoke that clears its notices reports no skip"); +}); diff --git a/main/services/bot-capability-store-core.ts b/main/services/bot-capability-store-core.ts index b7f0aa2e35..eff3b87bf0 100644 --- a/main/services/bot-capability-store-core.ts +++ b/main/services/bot-capability-store-core.ts @@ -181,6 +181,32 @@ export class BotCapabilityUnavailableError extends Error { } } +/** + * Whether a revoke must also clear the device's Bot notices. A phone's revoke + * fails until they are cleared, so a retry still removes the acceptance. An + * outside app's token is already tombstoned, so Bot storage waiting for repair + * (no Secret Service on Linux, say) must not keep it listed as connected. + */ +export type BotNoticeRevokePolicy = "required" | "when-available"; + +/** + * Runs `revoke` for a revoked device's Bot notice audience. Under + * `when-available` a BotCapabilityUnavailableError calls `onUnavailable` and + * resolves; every other failure, and any failure under `required`, rejects. + */ +export async function revokeBotNoticeAudience( + revoke: () => unknown, + policy: BotNoticeRevokePolicy, + onUnavailable: () => void, +): Promise { + try { + await revoke(); + } catch (error) { + if (policy === "required" || !(error instanceof BotCapabilityUnavailableError)) throw error; + onUnavailable(); + } +} + export class BotCapabilityRevisionConflictError extends Error { readonly currentRevision: string; From b8ae2943626922dafbfe144cffbbb95b45db7212 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 11 Nov 2026 16:59:07 -0500 Subject: [PATCH 8/9] Name each MCP app's token variable from one shared helper aidenMcpTokenEnvName gives every app its own AIDEN_MCP_TOKEN__ variable, so the desktop Settings sheet and aiden apps connect can print the same setup commands and two apps in one shell profile keep separate tokens. Co-Authored-By: Claude Opus 5.5 --- docs/aiden-mcp-server.md | 11 +++++---- package.json | 2 +- renderer/shared/aiden-mcp-token-env.test.ts | 27 +++++++++++++++++++++ renderer/shared/aiden-mcp-token-env.ts | 19 +++++++++++++++ scripts/ci-test-registry.json | 1 + 5 files changed, 54 insertions(+), 6 deletions(-) create mode 100644 renderer/shared/aiden-mcp-token-env.test.ts create mode 100644 renderer/shared/aiden-mcp-token-env.ts diff --git a/docs/aiden-mcp-server.md b/docs/aiden-mcp-server.md index fa6a2d7d6f..f494d0c511 100644 --- a/docs/aiden-mcp-server.md +++ b/docs/aiden-mcp-server.md @@ -14,21 +14,22 @@ Status (2026-11-11): the server core is in the desktop main process, behind the - If another program later holds the saved port, the server reports `port_in_use` rather than moving, because moving would break every configured app silently. - **Credential:** each app gets its own bearer token, a 43-character base64url secret shown once when it is issued. Aiden stores only a hash. A token is sent as `Authorization: Bearer `. -Claude Code: +Claude Code (the single quotes keep `${AIDEN_MCP_TOKEN_CLAUDE_CODE_K3J9QX}` literal in its saved configuration; Claude Code expands it from the environment when it connects): ```sh +export AIDEN_MCP_TOKEN_CLAUDE_CODE_K3J9QX='' claude mcp add --transport http aiden http://127.0.0.1:49400/mcp \ - --header "Authorization: Bearer " + --header 'Authorization: Bearer ${AIDEN_MCP_TOKEN_CLAUDE_CODE_K3J9QX}' ``` Codex: ```sh -export AIDEN_MCP_TOKEN= -codex mcp add aiden --url http://127.0.0.1:49400/mcp --bearer-token-env-var AIDEN_MCP_TOKEN +export AIDEN_MCP_TOKEN_CODEX_P7QD2M='' +codex mcp add aiden --url http://127.0.0.1:49400/mcp --bearer-token-env-var AIDEN_MCP_TOKEN_CODEX_P7QD2M ``` -Use the port your Aiden reports if it is not 49400. +Use the port your Aiden reports if it is not 49400. Each app reads its token from its own variable, `AIDEN_MCP_TOKEN__` (the app's name and the start of its id, from `aidenMcpTokenEnvName` in `renderer/shared/aiden-mcp-token-env.ts`), so the desktop and `aiden apps connect` print the same name and two apps in one shell profile keep separate tokens. ## Access levels diff --git a/package.json b/package.json index 5be860856d..c842255179 100644 --- a/package.json +++ b/package.json @@ -67,7 +67,7 @@ "test:remote-chat": "tsx --test renderer/lib/hosts/remote-chat-mapper.test.ts renderer/lib/hosts/remote-queue-fence.test.ts renderer/lib/hosts/remote-turn-selection.test.ts renderer/lib/hosts/remote-bot-session.test.ts renderer/main/remote-bot-chat-view.test.tsx renderer/lib/hosts/remote-stream-translator.test.ts main/services/peer-remote-chat-view.test.ts renderer/main/remote-chat-view.test.tsx renderer/lib/hosts/chat-session-control.test.ts renderer/lib/hosts/local-host-adapter.test.ts renderer/lib/hosts/observed-local-run.test.ts main/services/peer-remote-chat-control.test.ts renderer/lib/hosts/remote-new-chat.test.ts renderer/lib/hosts/host-resources.test.ts renderer/lib/hosts/new-chat-targets.test.ts renderer/main/remote-new-chat-view.test.tsx renderer/main/remote-chat-images.test.tsx main/services/peer-remote-new-chat.test.ts main/services/peer-remote-chat-fork.test.ts main/services/peer-remote-chat-context.test.ts", "test:peer-hosts": "tsx --test main/services/peer-intent-store.test.ts main/handlers/peer-intents.test.ts main/services/peer-host-registry.test.ts main/services/peer-transport.test.ts main/services/peer-operation.test.ts main/services/peer-host-feed-cache.test.ts main/services/peer-run-subscriptions.test.ts main/services/peer-host-manager.test.ts main/handlers/peer-host-live.test.ts main/services/peer-bootstrap-transport.test.ts main/services/peer-host-pairing.test.ts main/services/peer-pairing-client.test.ts main/services/peer-discovery.test.ts main/handlers/peer-pairing.test.ts main/services/peer-lan-addresses.test.ts main/services/peer-multi-host-acceptance.test.ts main/services/peer-bot-sessions.test.ts main/services/peer-project-source.test.ts main/services/peer-project-file-io.test.ts main/handlers/peer-project-clone.test.ts renderer/shared/peer-project-clone.test.ts renderer/main/peer-project-clone-dialog.test.tsx", "pretest:aiden-remote": "npm run build:worktree-file-io", - "test:aiden-remote": "npm run test:peer-hosts && tsx --test main/services/aiden-remote-chat-progress.test.ts main/services/aiden-remote-durable-operation.test.ts main/services/aiden-remote-chat-progress-authorize.test.ts main/handlers/aiden-remote.test.ts main/services/aiden-remote-chat-summaries.test.ts main/services/aiden-remote-approved-roots.test.ts main/services/aiden-remote-revocation.test.ts main/services/aiden-remote-bot-files.test.ts main/services/aiden-remote-bots.test.ts main/services/aiden-remote-bot-session.test.ts main/services/aiden-remote-bot-handoffs.test.ts main/services/aiden-remote-chat-http.test.ts main/services/aiden-remote-chats.test.ts main/services/visual-viewer-document.test.ts main/services/aiden-remote-files.test.ts main/services/aiden-remote-git.test.ts main/services/aiden-remote-models.test.ts main/services/aiden-remote-protocol.test.ts main/services/aiden-remote-opaque-handles.test.ts main/services/aiden-remote-operation-contract.test.ts main/services/aiden-remote-pairing.test.ts main/services/aiden-remote-pairing-requests.test.ts main/services/aiden-remote-pairing-requests-router.test.ts main/services/aiden-remote-pairing-request-host.test.ts main/services/aiden-remote-sealed-envelope.test.ts main/services/aiden-remote-ports.test.ts main/services/aiden-remote-router.test.ts main/services/aiden-remote-schedules.test.ts main/services/aiden-remote-service.test.ts main/services/aiden-remote-state.test.ts main/services/aiden-mcp-server.test.ts main/services/aiden-remote-streams.test.ts main/services/aiden-remote-tailscale-route.test.ts main/services/aiden-remote-tailscale.test.ts main/services/aiden-remote-tls-identity.test.ts main/services/aiden-remote-lan-hostname.test.ts main/services/aiden-remote-workspace-browser.test.ts main/services/aiden-remote-workspace-http.test.ts main/services/aiden-remote-workspaces.test.ts renderer/components/remote-connection-popover.test.tsx renderer/components/remote-pairing-request-sheet.test.tsx renderer/components/settings/remote-access-settings.test.tsx renderer/lib/remote-approval.test.ts renderer/lib/remote-connection-status.test.ts renderer/lib/remote-pairing-lifecycle.test.ts renderer/lib/settings-section.test.ts main/services/run-event-projection.test.ts main/services/host-run-registry.test.ts main/services/host-runs.test.ts main/services/aiden-remote-host-feed.test.ts main/services/aiden-remote-host-runs.test.ts main/services/aiden-remote-approval-schedule.test.ts main/handlers/local-runs.test.ts main/services/repository-identity.test.ts renderer/lib/peer-connections.test.ts renderer/components/settings/connections-settings.test.tsx main/services/aiden-remote-new-worktree.test.ts main/services/aiden-remote-bot-watches.test.ts main/services/aiden-remote-bot-allowed.test.ts && node --test scripts/aiden-remote-lan-transport-spike.test.mjs", + "test:aiden-remote": "npm run test:peer-hosts && tsx --test main/services/aiden-remote-chat-progress.test.ts main/services/aiden-remote-durable-operation.test.ts main/services/aiden-remote-chat-progress-authorize.test.ts main/handlers/aiden-remote.test.ts main/services/aiden-remote-chat-summaries.test.ts main/services/aiden-remote-approved-roots.test.ts main/services/aiden-remote-revocation.test.ts main/services/aiden-remote-bot-files.test.ts main/services/aiden-remote-bots.test.ts main/services/aiden-remote-bot-session.test.ts main/services/aiden-remote-bot-handoffs.test.ts main/services/aiden-remote-chat-http.test.ts main/services/aiden-remote-chats.test.ts main/services/visual-viewer-document.test.ts main/services/aiden-remote-files.test.ts main/services/aiden-remote-git.test.ts main/services/aiden-remote-models.test.ts main/services/aiden-remote-protocol.test.ts main/services/aiden-remote-opaque-handles.test.ts main/services/aiden-remote-operation-contract.test.ts main/services/aiden-remote-pairing.test.ts main/services/aiden-remote-pairing-requests.test.ts main/services/aiden-remote-pairing-requests-router.test.ts main/services/aiden-remote-pairing-request-host.test.ts main/services/aiden-remote-sealed-envelope.test.ts main/services/aiden-remote-ports.test.ts main/services/aiden-remote-router.test.ts main/services/aiden-remote-schedules.test.ts main/services/aiden-remote-service.test.ts main/services/aiden-remote-state.test.ts main/services/aiden-mcp-server.test.ts renderer/shared/aiden-mcp-token-env.test.ts main/services/aiden-remote-streams.test.ts main/services/aiden-remote-tailscale-route.test.ts main/services/aiden-remote-tailscale.test.ts main/services/aiden-remote-tls-identity.test.ts main/services/aiden-remote-lan-hostname.test.ts main/services/aiden-remote-workspace-browser.test.ts main/services/aiden-remote-workspace-http.test.ts main/services/aiden-remote-workspaces.test.ts renderer/components/remote-connection-popover.test.tsx renderer/components/remote-pairing-request-sheet.test.tsx renderer/components/settings/remote-access-settings.test.tsx renderer/lib/remote-approval.test.ts renderer/lib/remote-connection-status.test.ts renderer/lib/remote-pairing-lifecycle.test.ts renderer/lib/settings-section.test.ts main/services/run-event-projection.test.ts main/services/host-run-registry.test.ts main/services/host-runs.test.ts main/services/aiden-remote-host-feed.test.ts main/services/aiden-remote-host-runs.test.ts main/services/aiden-remote-approval-schedule.test.ts main/handlers/local-runs.test.ts main/services/repository-identity.test.ts renderer/lib/peer-connections.test.ts renderer/components/settings/connections-settings.test.tsx main/services/aiden-remote-new-worktree.test.ts main/services/aiden-remote-bot-watches.test.ts main/services/aiden-remote-bot-allowed.test.ts && node --test scripts/aiden-remote-lan-transport-spike.test.mjs", "test:aiden-remote-chat-summaries": "tsx --test main/services/aiden-remote-chat-summaries.test.ts", "test:memory-policy": "tsx --test main/services/memory-policy.test.ts main/services/aiden-remote-memory-settings.test.ts renderer/components/settings/memory-settings.test.tsx", "test:storage": "tsx --test main/services/storage-usage-core.test.ts main/services/storage-usage.test.ts renderer/components/settings/storage-settings.test.ts", diff --git a/renderer/shared/aiden-mcp-token-env.test.ts b/renderer/shared/aiden-mcp-token-env.test.ts new file mode 100644 index 0000000000..65f35c5a33 --- /dev/null +++ b/renderer/shared/aiden-mcp-token-env.test.ts @@ -0,0 +1,27 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import test from "node:test"; +import { aidenMcpTokenEnvName } from "./aiden-mcp-token-env.js"; + +const APPS = [ + { id: "device_k3j9qxa1", name: "Claude Code", token: "first-token" }, + { id: "device_p7qd2mb2", name: "Claude Code", token: "second-token" }, + { id: "device_zz81aa03", name: "🤖 Codex — work laptop, the long one", token: "third-token" }, + { id: "device_9x", name: "!!!", token: "fourth-token" }, +]; + +test("each app's token variable is a shell name that only that app's export sets", () => { + // A real shell is the oracle: every name must be assignable, and exporting + // all four apps' tokens in one profile must leave each app's own token readable. + const script = [ + ...APPS.map((app) => `export ${aidenMcpTokenEnvName(app)}='${app.token}'`), + ...APPS.map((app) => `printf '%s\\n' "$${aidenMcpTokenEnvName(app)}"`), + ].join("\n"); + const output = execFileSync("/bin/sh", ["-c", script], { encoding: "utf8" }); + assert.deepEqual(output.trim().split("\n"), APPS.map((app) => app.token)); +}); + +test("the variable name tells the person which app's token it holds", () => { + assert.match(aidenMcpTokenEnvName({ id: "device_k3j9qxa1", name: "Claude Code" }), /^AIDEN_MCP_TOKEN_CLAUDE_CODE_K3J9QX$/u); + assert.match(aidenMcpTokenEnvName({ id: "device_p7qd2mb2", name: "Codex" }), /^AIDEN_MCP_TOKEN_CODEX_P7QD2M$/u); +}); diff --git a/renderer/shared/aiden-mcp-token-env.ts b/renderer/shared/aiden-mcp-token-env.ts new file mode 100644 index 0000000000..8e0a0aa0c3 --- /dev/null +++ b/renderer/shared/aiden-mcp-token-env.ts @@ -0,0 +1,19 @@ +/** + * The environment variable an app's setup commands read its Aiden MCP token + * from. Each app gets its own, named after the app and a slice of its id, so + * two apps set up in one shell profile never overwrite each other's token. + * Settings and `aiden apps connect` both print this name. + */ +export function aidenMcpTokenEnvName(app: { id: string; name: string }): string { + const words = app.name + .toUpperCase() + .replace(/[^A-Z0-9]+/gu, "_") + .slice(0, 24) + .replace(/^_+|_+$/gu, ""); + const suffix = app.id + .replace(/^device_/u, "") + .replace(/[^A-Za-z0-9]/gu, "") + .slice(0, 6) + .toUpperCase(); + return ["AIDEN_MCP_TOKEN", words, suffix].filter(Boolean).join("_"); +} diff --git a/scripts/ci-test-registry.json b/scripts/ci-test-registry.json index e35f2786ab..e929a83b02 100644 --- a/scripts/ci-test-registry.json +++ b/scripts/ci-test-registry.json @@ -506,6 +506,7 @@ "main/services/aiden-remote-simulators.test.ts", "main/services/aiden-remote-speech.test.ts", "main/services/aiden-mcp-server.test.ts", + "renderer/shared/aiden-mcp-token-env.test.ts", "main/services/aiden-remote-state.test.ts", "main/services/aiden-remote-streams.test.ts", "main/services/aiden-remote-tailscale-route.test.ts", From 93b47c6457b2f3c32d4fb8da36d4ecd6df174dd1 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Tue, 17 Nov 2026 01:23:47 -0500 Subject: [PATCH 9/9] docs(mcp): describe app turns under approval modes, not Full access A turn an app starts follows the workspace's approval policy (Ask, Auto, Never ask and Allowed in this workspace grants) exactly like the person's own and a phone's. The guide, the threat model and aiden_chat_start's description now say what runs without a card in each mode, and that toolPermission is the phone tier (full whenever anything can run without a card). --- docs/aiden-mcp-server.md | 13 +++++++++++-- docs/security/aiden-remote-threat-model.md | 2 +- main/services/aiden-mcp-tools.ts | 2 +- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/docs/aiden-mcp-server.md b/docs/aiden-mcp-server.md index f494d0c511..f366cd6905 100644 --- a/docs/aiden-mcp-server.md +++ b/docs/aiden-mcp-server.md @@ -59,7 +59,16 @@ At most 16 apps can be connected at once, separately from the phone and Mac devi Arguments are validated against each tool's schema, and unknown properties are rejected. A message can be at most 200,000 characters, and messages read back are capped at 20,000 characters each. A chat `aiden_chat_list` leaves out (Bot, feature or assistant) cannot be read, waited on, sent to or stopped by id, even when the id is known. Every chat tool answers it exactly as it answers an unknown id (`This Aiden chat no longer exists.`), so an app cannot tell such a chat exists. MCP apps are trusted less than paired phones, which can open assistant chats. -There is deliberately no tool for approvals or questions. When a turn needs one, `aiden_chat_wait` says so and where, and the person answers it in Aiden on that computer. A turn runs with the permissions of its workspace. In a Full-access workspace, tools run without asking, exactly as if the person had typed the message. +There is deliberately no tool for approvals or questions. When a turn needs one, `aiden_chat_wait` says so and where, and the person answers it in Aiden on that computer. + +A turn an app starts is approved exactly like a turn the person types in that workspace, and like one a paired phone starts. Aiden reads the workspace's approval policy before every tool call: the global mode in Settings → Approvals, or the workspace's own mode if the person chose Customize, plus the "Allowed in this workspace" grants: + +- **Ask:** anything that sends, spends or changes something waits for the person. Only what the workspace's grants allow (running commands, changing files, Computer Use) runs without a card. +- **Auto:** a model approves routine actions and the rest wait for the person. A Supervised app's turn can therefore run routine tools with nobody watching. +- **Never ask:** only purchases, sharing the person's data and the first use of the computer wait for the person. Everything else runs unattended. +- **Chat only** workspaces cannot read or change their folder in any mode. + +`aiden_workspace_list` reports each workspace's `toolPermission` as the same tier a phone sees (`legacyWorkspaceTier`): `none` for Chat only, `ask` for Ask with nothing allowed in the workspace, and `full` whenever something can run without a card (Auto, Never ask, or any grant). A well-behaved app that should not run tools unattended can start turns only where `toolPermission` is `ask`, but Aiden does not enforce that for it. ## Limits @@ -82,7 +91,7 @@ Who could call the server: - **A connected app that misbehaves.** - It is limited to its access level, its own runs, ordinary chats and offered workspaces, and the rate and concurrency limits. - It cannot settle an approval or answer a question. - - A Supervised app can still ask Aiden to do anything the chosen workspace allows without approval, which is why Supervised is a deliberate choice and Full-access workspaces run unattended. + - A Supervised app can still ask Aiden to do anything the chosen workspace's approval mode and grants allow without a card: routine actions in Auto, nearly everything in Never ask, and whatever is allowed in that workspace in Ask. That is why Supervised is a deliberate choice. Aiden does not narrow a workspace's policy for app turns, and a Supervised app may start turns in any offered workspace, so an app that must never act unattended should be given Read access instead. Revoking an app: diff --git a/docs/security/aiden-remote-threat-model.md b/docs/security/aiden-remote-threat-model.md index 1ff1524f89..8908eef0c8 100644 --- a/docs/security/aiden-remote-threat-model.md +++ b/docs/security/aiden-remote-threat-model.md @@ -185,7 +185,7 @@ Outside app (Claude Code, Codex, any MCP client) on this computer - **Reach.** - Apps see ordinary chats and offered workspaces only. Bot, feature and assistant chats are not listed, and every chat tool refuses them by id with the same not-found answer as an unknown id, so an app cannot learn they exist. MCP apps are trusted less than paired phones, which can open assistant chats. New chats cannot be started in one-chat folders or the assistant workspace. - An app can wait on and stop only runs it started. -- **Residual risk.** A Supervised app is delegated the person's own authority in the chosen workspace. In a Full-access workspace its turns run tools without approval. Supervised access and Full-access workspaces are the person's informed choices; neither is containment. +- **Residual risk.** A Supervised app is delegated the person's own authority in the chosen workspace. Its turns follow the workspace's approval mode and grants like the person's own: in Auto a model approves routine tools, in Never ask nearly everything runs without a card, and in Ask whatever is allowed in that workspace runs without one. Supervised access and the approval mode are the person's informed choices; neither is containment. - **Revocation** goes through `revokeAidenRemoteRuntimeDevice`: - It rejects the token at once, ends open waits and stops the app's runs. - It denies the runs' pending approvals. diff --git a/main/services/aiden-mcp-tools.ts b/main/services/aiden-mcp-tools.ts index 6a2df617b8..ce9f6b455e 100644 --- a/main/services/aiden-mcp-tools.ts +++ b/main/services/aiden-mcp-tools.ts @@ -270,7 +270,7 @@ export class AidenMcpToolRunner { capability: "chat:write", title: "Start a chat", description: - "Start a new Aiden chat in a workspace and send its first message. Tools run with that workspace's permissions; approvals go to the person in Aiden. Follow the run with aiden_chat_wait.", + "Start a new Aiden chat in a workspace and send its first message. Tools follow that workspace's approval mode (Ask, Auto or Never ask, plus anything allowed in that workspace); whatever still needs approval goes to the person in Aiden. Follow the run with aiden_chat_wait.", schema: Type.Object( { clientRequestId: CLIENT_REQUEST_ID,