Skip to content

A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.

TypeScript

fix(security): mask credentials in imported server summaries and keep typed secrets out of argv

Alan Buscaglia63c8e9c825ef
diff --git a/docs/design.md b/docs/design.md
index 280214b..43b23eb 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -136,15 +136,16 @@ Every daemon message carries `seq` (monotonic per connection) so the UI can dete
- Catalog (`packages/daemon/src/connectors.ts`): Notion `https://mcp.notion.com/mcp`, Linear `https://mcp.linear.app/mcp`, and Atlassian `https://mcp.atlassian.com/v2/mcp`, each remote OAuth with one click; then three guided connectors (L36), each with in-app steps shown before "Connect" and a curated list of read-only tools (fail closed):
- Discord: the community server `npx -y @pasympa/[email protected]` (MIT, monthly releases, declares `readOnlyHint` on its tools; Discord has no official server), with the bot token in `env.DISCORD_TOKEN`. The guide covers the application, the bot, the Message Content and Server Members intents, and the invite (scope `bot` with read, send, and react permissions).
- Slack: the official `https://mcp.slack.com/mcp` (no dynamic client registration) with the user's own Slack app: `oauth.clientId`, an optional `oauth.clientSecret`, and the fixed redirect `http://localhost:38417/callback` (`oauth.callbackUrl`, sent exactly as written). Slack accepts a loopback redirect only with PKCE turned on, which makes the app a public client (refresh tokens last 30 days), so the secret may be left empty; the guide lists the user token scopes.
- - Gmail: the official `https://gmailmcp.googleapis.com/mcp/v1` (Developer Preview) with the user's own Google Cloud project: the Gmail API and Gmail MCP API enabled, the consent screen in testing (refresh tokens last 7 days), and a Web application client with the redirect `http://localhost:38418/callback`; `oauth.scope` asks for `gmail.readonly` and `gmail.compose`.
+ - Gmail: the official `https://gmailmcp.googleapis.com/mcp/v1` (Developer Preview) with the user's own Google Cloud project: the Gmail API and Gmail MCP API enabled, the consent screen in testing (refresh tokens last 7 days), and a Web application client with the redirect `http://localhost:38418/callback`; `oauth.scope` asks for `gmail.readonly` and `gmail.compose`. `gmail.compose` can also send mail, so the copy says so: drafting and sending ask for approval each time, and read only hides them. Each guided connector's copy describes only what its guide's permissions allow (Slack: send and schedule messages with `chat:write`; Discord: send messages and reactions).
- Typed values (S18, S19): a connector's `fields` are asked one at a time with sign-in prompts (`auth_prompt` `secret` or `text`, flow id `connector-setup-*`, `optional` when the answer may be empty), in the window that started them. A catalog connector is added only when every required value is there (cancel changes nothing); an approved draft or an import is added first and stays `needs_setup` until its values are typed. The values live in the in-memory state and `connectors.json` (both protected), are written into `mcp.json` in place of `${input:<key>}` placeholders, and are never sent to a window or logged. The engine resolves env values, headers, and `oauth.clientSecret` (a leading `!` runs a shell command and `$NAME` expands), so typed and imported literals are escaped (`$` → `$$`, `!` → `$!`); `clientId`, the command, its arguments, and URLs are used as written. `connector_setup` asks again (a new token). A connector whose value is missing is `needs_setup` and is left out of `mcp.json`.
-- Drafts (S19): the approval guard registers `propose_connector({name, description, transport, command?, args?, url?, env_names?, needs_oauth?})`, with secrets by name only. Its result to the model is only "The user will review this connector in the app". The draft travels to the daemon as `ctx.ui.setStatus("gentle-dot:connector-draft", <json>)`: a fire-and-forget record on the engine's own RPC output, which only the daemon reads (the agent's commands cannot write to it, and no file, socket, or key is added that the agent could reach). The daemon checks it (lengths, `https` or loopback URLs, env names), keeps the newest five, and shows every window a card (`connector_draft`) with the command or URL and the secret names. `connector_draft_reply` decides: declining forgets it; approving adds the server (`origin` "Drafted by the assistant"), turned on, read only with every tool hidden (`toolExposure {"*": "hidden"}`, no curated list, so in "Read and send" every call asks), then asks for each secret in the app and signs in when `needs_oauth`. The assistant still cannot write `mcp.json` or run `mcp add` (guard), so the card is the only way in. Residual, as for the rest of the state (S25): `connectors.json` edited while the daemon is not running is loaded at its next start, and it can now hold a server of the user's own (a command).
-- Import (S20, `packages/daemon/src/connector-import.ts`): "Import my MCP servers" (`connectors_scan`) reads, never writes, the configs below the user's home (`GENTLE_DOT_IMPORT_HOME` in tests): Claude Desktop (`Library/Application Support/Claude/` and `.config/Claude/claude_desktop_config.json`), Claude Code (`.claude.json` `mcpServers`, its `projects[*].mcpServers`, and each project's `.mcp.json`), Cursor (`.cursor/mcp.json`), VS Code (`User/mcp.json` with `servers` and `inputs`, macOS and Linux), Windsurf (`.codeium/windsurf/mcp_config.json`, `serverUrl`), OpenCode (`.config/opencode/opencode.json`, `mcp` with command arrays and `environment`), and Gentle Shell (`.gentle-shell/agent/mcp.json`). Each entry maps to the engine's schema: `${VAR}` (Claude Code), `${env:VAR}` (VS Code, Cursor, Windsurf), and `{env:VAR}` (OpenCode) become `${VAR}`; `${userHome}` becomes the home folder; a VS Code `${input:id}` becomes a value the user types after the import; everything else is a literal. SSE servers (`type: "sse"`, or an address ending in `/sse`) are listed as not importable. The list (`connector_imports`) shows the name, the source apps, the command or address with secret-looking arguments and the query masked, and env and header names only; values stay in the daemon. Duplicates (the same command without npm versions, or the same URL) of a connector the user has, or of a catalog entry, are marked and cannot be imported. `connector_import` copies the chosen entries with their values into the private state, read only with every tool hidden, and never touches the source files.
+- Drafts (S19): the approval guard registers `propose_connector({name, description, transport, command?, args?, url?, env_names?, needs_oauth?})`, with secrets by name only. Its result to the model is only "The user will review this connector in the app". The draft travels to the daemon as `ctx.ui.setStatus("gentle-dot:connector-draft", <json>)`: a fire-and-forget record on the engine's own RPC output, which only the daemon reads (the agent's commands cannot write to it, and no file, socket, or key is added that the agent could reach). A typed value (`${input:NAME}`) may only stand for an env value (or an http server's header): anywhere else (the command, its arguments, the URL) it would put the secret into the command line or an address the model chose, so the guard answers the model "Secrets can only go into environment variables." and sends nothing, and the daemon refuses such a draft as well. The daemon checks it (lengths, `https` or loopback URLs, env names, typed values), keeps the newest five (`MAX_CONNECTOR_DRAFTS`; the windows keep the same five and take the waiting list again after each `ready`), and shows every window a card (`connector_draft`) with the command or URL and the secret names. `connector_draft_reply` decides: declining forgets it; approving adds the server (`origin` "Drafted by the assistant"), turned on, read only with every tool hidden (`toolExposure {"*": "hidden"}`, no curated list, so in "Read and send" every call asks), then asks for each secret in the app and signs in when `needs_oauth`. The assistant still cannot write `mcp.json` or run `mcp add` (guard), so the card is the only way in. Residual, as for the rest of the state (S25): `connectors.json` edited while the daemon is not running is loaded at its next start, and it can now hold a server of the user's own (a command).
+- Import (S20, `packages/daemon/src/connector-import.ts`): "Import my MCP servers" (`connectors_scan`) reads, never writes, the configs below the user's home (`GENTLE_DOT_IMPORT_HOME` in tests): Claude Desktop (`Library/Application Support/Claude/` and `.config/Claude/claude_desktop_config.json`), Claude Code (`.claude.json` `mcpServers`, its `projects[*].mcpServers`, and each project's `.mcp.json`), Cursor (`.cursor/mcp.json`), VS Code (`User/mcp.json` with `servers` and `inputs`, macOS and Linux), Windsurf (`.codeium/windsurf/mcp_config.json`, `serverUrl`), OpenCode (`.config/opencode/opencode.json`, `mcp` with command arrays and `environment`), and Gentle Shell (`.gentle-shell/agent/mcp.json`). Each entry maps to the engine's schema: `${VAR}` (Claude Code), `${env:VAR}` (VS Code, Cursor, Windsurf), and `{env:VAR}` (OpenCode) become `${VAR}`; `${userHome}` becomes the home folder; a VS Code `${input:id}` becomes a value the user types after the import; everything else is a literal. SSE servers (`type: "sse"`, or an address ending in `/sse`) are listed as not importable. The list (`connector_imports`) shows the name, the source apps, the command or address (`summary`), and env and header names only; values stay in the daemon. The summary, also shown for a custom connector in the Connectors list, is masked by structure, not by a word list: an address (an argument or the server URL, any scheme) keeps its scheme, host, and path, loses its user and password and its fragment, shows its query keys with every value as `•••`, and masks long opaque path segments (20 or more letters, digits, `_`, or `-`, mixing digits or cases); the argument after `--header`/`-H`, the value of `--header=`, and any `Name: value` argument whose name looks like a credential (Authorization, Cookie, `*key*`, `*token*`, `*secret*`, and so on) keep only the name; the argument after a flag named like a credential (`/token|secret|key|pass|auth|cred|bearer/i`) and the value of `name=value` forms of the same are masked; known token prefixes (`ghp_`, `sk-`, `xoxb-`, `AKIA`, `glpat-`, and others) and long opaque words are masked. Values the engine resolves at start are noted before the import (`notes`): "Runs a command on your computer to get this value." for a leading `!` (the command is not shown), and "Reads the environment variable NAME." for `$NAME`/`${NAME}`. Duplicates (the same command without npm versions, or the same URL) of a connector the user has, or of a catalog entry, are marked and cannot be imported. `connector_import` copies the chosen entries with their values into the private state, read only with every tool hidden, and never touches the source files.
- The daemon holds the approved connector state (each connector's `enabled` and `mode`) in memory. It reads `<dataDir>/connectors.json` once, when it starts; after that the state changes only through the Connectors screen. The daemon is the only writer of `connectors.json` and `<agentHome>/mcp.json`, both rendered from memory, atomically, mode 0600. The engine's policy (below) also comes from memory, never from the files. The files are watched (folder watches plus a check every second, because file events on macOS can be missed right after a watch starts), and they are also checked before every agent start and after every run. A change made by anything else is put back, a project `<workspace>/.pi/mcp.json` is removed (a `.pi` link loses the link, never its target), and every window gets "A change to your connectors was blocked." Residual: a change made to the files while the daemon is not running is loaded at its next start; stage 2 (S25) moves enforcement out of the files. Every server is `exposure: "direct"` (the assistant turns codemode off). "Read only" adds `toolExposure: {"*": "hidden", <curated tool>: "direct"}`; the engine prefers exact names over patterns, so an unknown tool stays hidden.
- Sign-in runs the engine's own command line as a separate process, `node <pi-coding-agent>/dist/bundle/cli.js mcp login <id>`, with the agent's isolated environment and `PI_CODING_AGENT_DIR=<agentHome>`. The daemon relays the printed authorization URL (`auth_event` `auth_url`) and offers a `manual_code` prompt: when the browser cannot reach this computer's loopback callback, the user pastes the address it ended on, and the daemon opens it locally only when its origin and path equal the authorization URL's `redirect_uri` and its `state` matches. Cancel stops the process by PID. Flow ids start with `connector-`, so `auth_reply` reaches the right flow; typed and printed text is never logged (URLs are masked).
- Status: `needs_setup` while a typed value is missing; for servers that sign in with OAuth, `connected` when `mcp-auth.json` holds tokens under `mcp__<id>|<url>` (the id with `-` as `_`, like the engine; token values are dropped while parsing) and `needs_signin` otherwise; `connected` for servers with a token or none; `error` after a failed sign-in.
- Approval guard (`packages/daemon/src/extensions/approval-guard.ts`, `tool_call` hook, nested calls included): a connector tool runs without asking only when it declares `readOnlyHint: true` AND it is on the curated list. Anything else asks through `ctx.ui.confirm`: an ask card ("Allow Notion to create pages?") with every argument, key fields first, up to 8,000 characters (beyond that it says "(truncated, N more characters)"), shown in a scrollable block. It is blocked when declined, when no one can answer, or when the connector is "Read only". A server outside the policy is blocked; without a valid policy every connector call asks.
- Credential and control files: `<agentHome>/auth.json`, `mcp-auth.json`, `models.json` (it can hold API keys), `mcp.json`, `<dataDir>/connectors.json`, `<dataDir>/token`, and the guard itself. The file tools (`read`, `write`, `edit`, `grep`, `find`, `ls`) are blocked on them by resolved path (any spelling, `@` prefix, case, symlink, or hard link), and `grep` also on any folder that contains one. Commands (`bash`) are blocked when, with quotes, backslashes, and string concatenation removed, they name one of those files (any case; a pattern such as `mcp-a*` counts), the data folder `.gentle-dot`, `PI_CODING_AGENT_DIR`, `security find-generic-password` (or other keychain reads), or `mcp add|login|logout|remove`. The command check is best effort, not a security boundary: the assistant runs as the user with a shell, so a command can always build a name the check does not see. The in-memory connector state above does not depend on it, and stage 2 (S25) moves tokens out of the engine's reach.
+- Stage 2 integrity (S25) must cover the user's own servers too. Today `connectors.json` is trusted when the daemon starts, so a file edited while the daemon is not running can add a custom or imported server that runs an arbitrary command, turn it on, claim any `origin` ("Imported from …", "Drafted by the assistant"), and carry env or header values that are not escaped (`!command`, `$NAME`), which the engine runs or expands at the next start. S25's integrity check (state the agent cannot write, or a signature it cannot forge) must cover every field of those entries: command, arguments, URL, env, headers, `enabled`, `mode`, and `origin`.
- Subagents are off in the assistant's engine (`GENTLE_PI_AGENTS=0`, §3): Gentle Shell's subagent child engines get only its own child extensions, not the approval guard, so a child could run connector tools or read credentials unchecked. Turning them back on needs S25 (enforcement in the daemon) or forwarding the guard to child engines.
### Switching and history races (S21)
diff --git a/packages/daemon/src/connector-import.ts b/packages/daemon/src/connector-import.ts
index b7e3019..132d749 100644
--- a/packages/daemon/src/connector-import.ts
+++ b/packages/daemon/src/connector-import.ts
@@ -151,6 +151,44 @@ function mapServer(source: string, name: string, raw: Json, context: MapContext)
return { ...base, transport: url ? "http" : "stdio", reason: NO_SERVER };
}
+/**
+ * What the engine does with each value it resolves (env, headers, the OAuth client secret) when the
+ * server starts, in plain words: a leading `!` runs a command, and `$NAME` or `${NAME}` reads an
+ * environment variable (`$$` and `$!` are literals). The command itself is never repeated.
+ */
+export function valueNotes(server: ServerTemplate): string[] {
+ const values: [string, string][] = [
+ ...Object.entries("command" in server ? (server.env ?? {}) : (server.headers ?? {})),
+ ...("url" in server && server.oauth?.clientSecret !== undefined
+ ? [["Client Secret", server.oauth.clientSecret] as [string, string]]
+ : []),
+ ];
+ return values.flatMap(([key, text]) => {
+ if (text.startsWith("!")) return [`${key}: Runs a command on your computer to get this value.`];
+ const names = envReferences(text);
+ if (names.length === 0) return [];
+ const list = names.join(", ");
+ return [`${key}: Reads the environment variable${names.length > 1 ? "s" : ""} ${list}.`];
+ });
+}
+
+/** The environment variables a value reads, as the engine parses its templates. */
+function envReferences(text: string): string[] {
+ const names: string[] = [];
+ for (let index = text.indexOf("$"); index >= 0; index = text.indexOf("$", index)) {
+ const next = text[index + 1];
+ if (next === "$" || next === "!") {
+ index += 2;
+ continue;
+ }
+ const braced = next === "{" ? /^\$\{([^}]*)\}/.exec(text.slice(index)) : undefined;
+ const name = braced ? braced[1] : /^\$([A-Za-z_][A-Za-z0-9_]*)/.exec(text.slice(index))?.[1];
+ if (name && ENV_NAME.test(name) && !names.includes(name)) names.push(name);
+ index += braced ? braced[0].length : 1 + (name?.length ?? 0);
+ }
+ return names;
+}
+
function isSsePath(url: string): boolean {
return URL.canParse(url) && /\/sse\/?$/i.test(new URL(url).pathname);
}
diff --git a/packages/daemon/src/connectors.ts b/packages/daemon/src/connectors.ts
index 9503a4f..23c7ce8 100644
--- a/packages/daemon/src/connectors.ts
+++ b/packages/daemon/src/connectors.ts
@@ -23,8 +23,9 @@ import type {
ImportCandidate,
ServerPayload,
} from "@gentle-dot/protocol";
-import { type ScannedServer, scanClientConfigs } from "./connector-import.ts";
-import { type ConnectorPolicy, POLICY_ENV } from "./extensions/approval-guard.ts";
+import { MAX_CONNECTOR_DRAFTS } from "@gentle-dot/protocol";
+import { type ScannedServer, scanClientConfigs, valueNotes } from "./connector-import.ts";
+import { type ConnectorPolicy, draftSecretProblem, POLICY_ENV } from "./extensions/approval-guard.ts";
/** A value the user types in the app (a token, client credentials); kept only in the assistant's private state. */
export interface SetupField {
@@ -169,7 +170,7 @@ export const CATALOG: readonly CatalogEntry[] = [
],
oauth: false,
reads: "Read channels, messages, threads, and members in the servers your bot was invited to.",
- sends: "Send and react to messages and manage channels as your bot, after you approve each one.",
+ sends: "Send messages and reactions as your bot, after you approve each one. Read only hides them.",
readOnlyTools: [
"discord_list_guilds",
"discord_get_guild_info",
@@ -226,8 +227,8 @@ export const CATALOG: readonly CatalogEntry[] = [
},
],
oauth: true,
- reads: "Search messages, channels, files, and people, and read channels and threads.",
- sends: "Send and schedule messages, add reactions, and create canvases, after you approve each one.",
+ reads: "Search messages, channels, and people, and read channels, threads, and canvases.",
+ sends: "Send and schedule messages as you, after you approve each one. Read only hides them.",
readOnlyTools: [
"slack_search_public",
"slack_search_public_and_private",
@@ -273,7 +274,7 @@ export const CATALOG: readonly CatalogEntry[] = [
fields: [CLIENT_ID, { key: "client_secret", label: "Client Secret", secret: true }],
oauth: true,
reads: "Search and read your email threads, drafts, and labels.",
- sends: "Create drafts and label messages, after you approve each one. It never sends mail.",
+ sends: "Draft and send mail as you, after you approve each one. Read only hides them.",
readOnlyTools: ["search_threads", "get_thread", "get_message", "list_drafts", "list_labels"],
guide: {
steps: [
@@ -292,7 +293,7 @@ export const CATALOG: readonly CatalogEntry[] = [
},
],
redirectUrl: GMAIL_REDIRECT,
- note: "Gmail's server is a Developer Preview: your account must be in the Google Workspace Developer Preview Program. While the app is in testing, Google asks you to sign in again every 7 days.",
+ note: "Gmail's server is a Developer Preview: your account must be in the Google Workspace Developer Preview Program. While the app is in testing, Google asks you to sign in again every 7 days. The gmail.compose permission lets the assistant draft and send mail: each draft or message asks for your approval first, and read only hides them.",
},
},
];
@@ -797,10 +798,7 @@ interface Setup {
const PASTE_PROMPT =
"If the browser shows an error page after you approve, copy the full address from its address bar and paste it here.";
const DRAFT_ORIGIN = "Drafted by the assistant";
-const MAX_DRAFTS = 5;
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
-/** Arguments named like these hold a secret; the value after them is masked in summaries. */
-const SECRET_NAME = /token|key|secret|password|passwd|auth|bearer|credential/i;
export interface ConnectorManagerOptions {
store: ConnectorStore;
@@ -999,7 +997,8 @@ export class ConnectorManager {
const draft = parseDraft(text);
if (!draft) return undefined;
this.waiting.set(draft.draftId, draft);
- for (const id of this.waiting.keys()) if (this.waiting.size > MAX_DRAFTS) this.waiting.delete(id);
+ for (const id of this.waiting.keys())
+ if (this.waiting.size > MAX_CONNECTOR_DRAFTS) this.waiting.delete(id);
return draft;
}
@@ -1110,6 +1109,8 @@ export class ConnectorManager {
inputs: server.fields.map((field) => field.label),
importable: template !== undefined,
};
+ const notes = template ? valueNotes(template) : [];
+ if (notes.length > 0) candidate.notes = notes;
if (server.reason) candidate.reason = server.reason;
const duplicate = template && this.duplicateOf(template);
if (duplicate) {
@@ -1391,6 +1392,8 @@ function parseDraft(text: string): ConnectorDraft | undefined {
return undefined;
}
if (typeof value !== "object" || value === null) return undefined;
+ // A typed value in the command line or the address would hand the secret to the model's choice.
+ if (draftSecretProblem(value)) return undefined;
const raw = value as Record<string, unknown>;
const name = typeof raw.name === "string" ? raw.name.trim() : "";
const description = raw.description === undefined ? "" : raw.description;
@@ -1442,24 +1445,78 @@ function fingerprint(server: ServerTemplate): string {
return ["cmd", server.command, ...(server.args ?? []).map(unversioned)].join("\u0000");
}
-/** The command line or address, with values that look secret masked (never an env value or header). */
+const MASK = "•••";
+/** A flag or name whose value is a credential. */
+const SECRET_FLAG = /token|secret|key|pass|auth|cred|bearer/i;
+/** A header that carries a credential (`Name: value`). */
+const SECRET_HEADER =
+ /^(authorization|proxy-authorization|cookie|set-cookie)$|token|secret|key|auth|pass|cred|session|bearer/i;
+const HEADER_FLAG = /^(--header|-H)$/;
+/** Known credential prefixes: GitHub, OpenAI and Stripe style, Slack, AWS, GitLab. */
+const SECRET_PREFIX = /^(ghp_|gho_|ghu_|ghs_|ghr_|github_pat_|sk-|sk_|rk_|xox[abprse]-|AKIA|ASIA|glpat-)/;
+/** A long run of letters and digits with no separators, as tokens are (a word-only name is kept). */
+const OPAQUE = (min: number) =>
+ new RegExp(`^(?=[A-Za-z0-9_-]{${min},}$)(?=.*\\d|.*[a-z].*[A-Z]|.*[A-Z].*[a-z])`);
+const OPAQUE_SEGMENT = OPAQUE(20);
+const OPAQUE_WORD = OPAQUE(32);
+const URL_LIKE = /^[A-Za-z][A-Za-z0-9+.-]*:\/\//;
+
+/**
+ * The command line or address as the user can recognize it (command, host, path), with every value
+ * that can hold a credential masked: an address loses its user and password, its query values, and
+ * long opaque path segments; a header passed as an argument keeps only its name; the value of a
+ * flag named like a credential is masked, and so are known token prefixes. Env values and headers
+ * are never part of it.
+ */
export function summarize(server: ServerTemplate): string {
- if ("url" in server) {
- if (!URL.canParse(server.url)) return server.url.replace(/[?#].*$/, "");
- const url = new URL(server.url);
- return `${url.origin}${url.pathname}`;
- }
+ if ("url" in server) return maskAddress(server.url);
const words = [server.command, ...(server.args ?? [])];
- return words
- .map((word, index) => {
- const flag = /^(--?[^=]+)=(.*)$/.exec(word);
- if (flag?.[1] && SECRET_NAME.test(flag[1])) return `${flag[1]}=•••`;
- const previous = words[index - 1];
- if (index > 1 && previous?.startsWith("-") && SECRET_NAME.test(previous) && !word.startsWith("-"))
- return "•••";
- return /^(ghp_|gho_|github_pat_|sk-|sk_|xox[abp]-|AKIA)/.test(word) ? "•••" : word;
- })
- .join(" ");
+ return words.map((word, index) => maskWord(word, index > 0 ? words[index - 1] : undefined)).join(" ");
+}
+
+function maskWord(word: string, previous: string | undefined): string {
+ if (previous !== undefined && HEADER_FLAG.test(previous)) return maskHeader(word, true);
+ if (
+ previous !== undefined &&
+ /^--?[A-Za-z0-9][\w.-]*$/.test(previous) &&
+ SECRET_FLAG.test(previous) &&
+ !word.startsWith("-")
+ )
+ return MASK;
+ if (previous !== undefined && /^(bearer|basic|token)$/i.test(previous)) return MASK;
+ if (URL_LIKE.test(word)) return maskAddress(word);
+ const assignment = /^(-{0,2}[A-Za-z0-9_][\w.-]*)=(.*)$/s.exec(word);
+ if (assignment) {
+ const [, name = "", value = ""] = assignment;
+ if (HEADER_FLAG.test(name)) return `${name}=${maskHeader(value, true)}`;
+ if (SECRET_FLAG.test(name)) return `${name}=${MASK}`;
+ return `${name}=${maskWord(value, undefined)}`;
+ }
+ const header = maskHeader(word, false);
+ if (header !== word) return header;
+ return SECRET_PREFIX.test(word) || OPAQUE_WORD.test(word) ? MASK : word;
+}
+
+/** `Name: value` with the value masked when the name carries a credential, or always after `--header`. */
+function maskHeader(word: string, always: boolean): string {
+ const header = /^([A-Za-z][A-Za-z0-9_-]*)\s*:\s*(.*)$/s.exec(word);
+ if (!header) return always ? MASK : word;
+ const [, name = ""] = header;
+ return always || SECRET_HEADER.test(name) ? `${name}: ${MASK}` : word;
+}
+
+/** An address as scheme, host, and path: no user or password, query values masked, no fragment. */
+function maskAddress(text: string): string {
+ if (!URL.canParse(text)) return text.replace(/[?#].*$/s, "").replace(/^([^/]*\/\/)[^/@]*@/, "$1");
+ const url = new URL(text);
+ const path = url.pathname
+ .split("/")
+ .map((segment) => (OPAQUE_SEGMENT.test(segment) || SECRET_PREFIX.test(segment) ? MASK : segment))
+ .join("/");
+ const keys = [...new Set(url.searchParams.keys())];
+ const query =
+ keys.length > 0 ? `?${keys.map((key) => `${maskWord(key, undefined)}=${MASK}`).join("&")}` : "";
+ return `${url.protocol}//${url.host}${path}${query}`;
}
/** The guard's policy for the engine's environment; the engine cannot change its own environment. */
diff --git a/packages/daemon/src/extensions/approval-guard.ts b/packages/daemon/src/extensions/approval-guard.ts
index 6541082..c730bdd 100644
--- a/packages/daemon/src/extensions/approval-guard.ts
+++ b/packages/daemon/src/extensions/approval-guard.ts
@@ -69,6 +69,29 @@ export const PROPOSE_TOOL = {
const REVIEW = "The user will review this connector in the app. Do not ask for its secrets in the chat.";
const NO_REVIEW = "No one can review a connector right now. Ask the user to open the app.";
+const SECRETS_ONLY_IN_ENV = "Secrets can only go into environment variables.";
+const TYPED_VALUE = /\$\{\s*input\s*:/i;
+
+/**
+ * Why a draft cannot be sent: a value the user types (`${input:NAME}`) anywhere but an environment
+ * value (or an http server's header) would put the secret into the command line or an address the
+ * model chose. The daemon checks the same before it shows a draft.
+ */
+export function draftSecretProblem(params: unknown): string | undefined {
+ const http =
+ typeof params === "object" && params !== null && (params as { transport?: unknown }).transport === "http";
+ const misplaced = (value: unknown, top: boolean): boolean => {
+ if (typeof value === "string") return TYPED_VALUE.test(value);
+ if (typeof value !== "object" || value === null) return false;
+ return Object.entries(value).some(([key, entry]) => {
+ const values = top && (key === "env" || (http && key === "headers"));
+ if (values && typeof entry === "object" && entry !== null && !Array.isArray(entry))
+ return Object.keys(entry).some((name) => TYPED_VALUE.test(name));
+ return TYPED_VALUE.test(key) || misplaced(entry, false);
+ });
+ };
+ return misplaced(params, true) ? SECRETS_ONLY_IN_ENV : undefined;
+}
/** Sends a draft to the daemon; the text is all the model gets back. */
export function proposeConnector(
@@ -76,6 +99,8 @@ export function proposeConnector(
ctx: { hasUI: boolean; ui: { setStatus(key: string, text: string | undefined): void } },
): string {
if (!ctx.hasUI) return NO_REVIEW;
+ const problem = draftSecretProblem(params);
+ if (problem) return problem;
const text = JSON.stringify(params ?? {});
if (text.length > MAX_DRAFT) return "That draft is too long. Keep it to the server's command or URL.";
ctx.ui.setStatus(DRAFT_STATUS_KEY, text);
diff --git a/packages/daemon/test/connector-drafts.test.ts b/packages/daemon/test/connector-drafts.test.ts
index a4418af..ad99c94 100644
--- a/packages/daemon/test/connector-drafts.test.ts
+++ b/packages/daemon/test/connector-drafts.test.ts
@@ -1,3 +1,4 @@
+// biome-ignore-all lint/suspicious/noTemplateCurlyInString: drafts name typed values with the `${input:NAME}` placeholder.
// S19: the assistant drafts a connector with `propose_connector`; only the user's approval adds it.
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
@@ -10,6 +11,7 @@ import { type DotDaemon, startDaemon } from "../src/daemon.ts";
import approvalGuard, {
DRAFT_STATUS_KEY,
decide,
+ draftSecretProblem,
PROPOSE_TOOL,
proposeConnector,
} from "../src/extensions/approval-guard.ts";
@@ -19,6 +21,28 @@ import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";
const FAKE_CLI = fileURLToPath(new URL("./fixtures/fake-mcp-cli.ts", import.meta.url));
const SECRET = "gh-token-$top!secret";
+/** Drafts that would put a typed secret into the command line or an address the model chose. */
+const secretPlacements: Record<string, unknown>[] = [
+ {
+ name: "A",
+ transport: "stdio",
+ command: "npx",
+ args: ["server", "--token", "${input:TOKEN}"],
+ env_names: ["TOKEN"],
+ },
+ { name: "B", transport: "stdio", command: "npx", args: ["--token=${input:TOKEN}"] },
+ { name: "C", transport: "stdio", command: "${input:TOKEN}" },
+ {
+ name: "D",
+ transport: "http",
+ url: "https://evil.example.com/mcp?k=${input:TOKEN}",
+ env_names: ["TOKEN"],
+ },
+ { name: "E", transport: "http", url: "https://${input:TOKEN}@mcp.example.com/mcp" },
+ { name: "F", transport: "stdio", command: "npx", args: ["x"], cwd: "/tmp/${ input:TOKEN }" },
+ { name: "G ${input:TOKEN}", transport: "stdio", command: "npx" },
+];
+
const stdioDraft = {
name: "GitHub",
description: "Read issues and pull requests in your repositories.",
@@ -63,6 +87,45 @@ describe("propose_connector in the approval guard", () => {
expect(result.content[0]?.text).toMatch(/the user will review/i);
});
+ it("refuses a typed secret anywhere but an environment variable, and tells the model why", async () => {
+ const statuses: string[] = [];
+ const ui = { setStatus: (_key: string, text: string | undefined) => statuses.push(text ?? "") };
+ const SECRETS_ONLY_IN_ENV = "Secrets can only go into environment variables.";
+ for (const bad of secretPlacements) {
+ expect(draftSecretProblem(bad), JSON.stringify(bad)).toBe(SECRETS_ONLY_IN_ENV);
+ expect(proposeConnector(bad, { hasUI: true, ui }), JSON.stringify(bad)).toBe(SECRETS_ONLY_IN_ENV);
+ }
+ expect(statuses).toEqual([]);
+ // Env values (and an http server's headers) may name a typed value.
+ for (const good of [
+ stdioDraft,
+ { ...stdioDraft, env: { GITHUB_TOKEN: "${input:GITHUB_TOKEN}" } },
+ {
+ name: "Docs",
+ transport: "http",
+ url: "https://docs.example.com/mcp",
+ headers: { "X-Key": "${input:KEY}" },
+ },
+ ])
+ expect(draftSecretProblem(good), JSON.stringify(good)).toBeUndefined();
+ expect(draftSecretProblem({ ...stdioDraft, headers: { Authorization: "Bearer ${input:TOKEN}" } })).toBe(
+ SECRETS_ONLY_IN_ENV,
+ );
+ // Through the registered tool, the model gets the same plain reason.
+ const tools: { name: string; execute: (...args: unknown[]) => Promise<unknown> }[] = [];
+ approvalGuard({
+ on: () => {},
+ registerTool: (tool: (typeof tools)[number]) => tools.push(tool),
+ } as never);
+ const result = (await tools
+ .find((t) => t.name === "propose_connector")
+ ?.execute("call-2", secretPlacements[0], undefined, undefined, { hasUI: true, ui })) as {
+ content: { text: string }[];
+ };
+ expect(result.content[0]?.text).toBe(SECRETS_ONLY_IN_ENV);
+ expect(statuses).toEqual([]);
+ });
+
it("still blocks the assistant from writing mcp.json or running mcp add itself", () => {
const agentHome = tempDir();
const policy = { connectors: {}, protectedPaths: [join(agentHome, "mcp.json")] };
@@ -150,6 +213,10 @@ describe("connector drafts", () => {
expect(manager.propose(bad), bad.slice(0, 60)).toBeUndefined();
}
expect(manager.drafts()).toHaveLength(2);
+ // The daemon refuses a typed secret outside the environment too, even if the guard was skipped.
+ for (const bad of secretPlacements)
+ expect(manager.propose(JSON.stringify(bad)), JSON.stringify(bad)).toBeUndefined();
+ expect(manager.drafts()).toHaveLength(2);
});
it("changes nothing when the user declines", () => {
diff --git a/packages/daemon/test/connector-import.test.ts b/packages/daemon/test/connector-import.test.ts
index 1989e7d..4532c1a 100644
--- a/packages/daemon/test/connector-import.test.ts
+++ b/packages/daemon/test/connector-import.test.ts
@@ -258,7 +258,7 @@ describe("importing MCP servers", () => {
});
expect(pick(found, "stripe")).toMatchObject({
transport: "http",
- summary: "https://mcp.stripe.com/",
+ summary: "https://mcp.stripe.com/?key=•••",
headerNames: ["Authorization"],
});
expect(pick(found, "everything").summary).toBe(
@@ -358,3 +358,53 @@ describe("importing MCP servers", () => {
expect(store.state()).toEqual({ connectors: {} });
});
});
+
+describe("values the engine resolves in an import", () => {
+ it("notes a value that runs a command or reads an environment variable, without showing the command", () => {
+ const home = tempDir();
+ write(home, ".gentle-shell/agent/mcp.json", {
+ mcpServers: {
+ vault: {
+ command: "vault-mcp",
+ env: {
+ VAULT_TOKEN: "!security find-generic-password -w -s vault",
+ PLAIN: "a$$b",
+ REGION: "$AWS_REGION",
+ },
+ },
+ remote: {
+ url: "https://mcp.example.com/mcp",
+ headers: { Authorization: "Bearer ${GH_TOKEN}", "X-Team": "literal-team" },
+ oauth: { clientSecret: "!op read op://vault/item/secret" },
+ },
+ plain: { command: "plain-mcp", env: { MODE: "fast", ESCAPED: "$$HOME and $!bang" } },
+ },
+ });
+ const { manager } = setup(home);
+ const found = manager.scan();
+ expect(pick(found, "vault").notes).toEqual([
+ "VAULT_TOKEN: Runs a command on your computer to get this value.",
+ "REGION: Reads the environment variable AWS_REGION.",
+ ]);
+ expect(pick(found, "remote").notes).toEqual([
+ "Authorization: Reads the environment variable GH_TOKEN.",
+ "Client Secret: Runs a command on your computer to get this value.",
+ ]);
+ expect(pick(found, "plain").notes).toBeUndefined();
+ const text = JSON.stringify(found);
+ for (const command of ["security find-generic-password", "op read"]) expect(text).not.toContain(command);
+ // Other apps' references become the engine's, so they get the same note.
+ const other = tempDir();
+ write(other, ".cursor/mcp.json", {
+ mcpServers: {
+ copilot: {
+ url: "https://api.githubcopilot.com/mcp/",
+ headers: { Authorization: "Bearer ${env:GH_TOKEN}" },
+ },
+ },
+ });
+ expect(pick(setup(other).manager.scan(), "copilot").notes).toEqual([
+ "Authorization: Reads the environment variable GH_TOKEN.",
+ ]);
+ });
+});
diff --git a/packages/daemon/test/connector-masking.test.ts b/packages/daemon/test/connector-masking.test.ts
new file mode 100644
index 0000000..11c33e3
--- /dev/null
+++ b/packages/daemon/test/connector-masking.test.ts
@@ -0,0 +1,227 @@
+// biome-ignore-all lint/suspicious/noTemplateCurlyInString: the fixtures are other apps' configs, written with their `${...}` references.
+// S20 hardening: what the import list and the Connectors screen show of a server never carries a credential,
+// wherever it sits in the command line or address, and still shows the useful shape (command, host, path).
+import { mkdirSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import type { ImportCandidate } from "@gentle-dot/protocol";
+import { afterEach, describe, expect, it } from "vitest";
+import { ConnectorManager, ConnectorStore, summarize } from "../src/connectors.ts";
+import { tempDir } from "./helpers.ts";
+
+const FAKE_CLI = fileURLToPath(new URL("./fixtures/fake-mcp-cli.ts", import.meta.url));
+
+function write(home: string, path: string, value: unknown) {
+ const file = join(home, path);
+ mkdirSync(dirname(file), { recursive: true });
+ writeFileSync(file, JSON.stringify(value, null, 2));
+}
+
+const OPAQUE = "Zk3pQ9vT2mX8rL5wN1bY7cH4";
+
+/** Each server hides one secret in a different place of its command line or address. */
+const CASES: { name: string; secret: string; summary: string; server: Record<string, unknown> }[] = [
+ {
+ name: "remote-header",
+ secret: "hdr-secret-aaaa",
+ summary: "npx -y mcp-remote https://mcp.acme.dev/mcp --header Authorization: •••",
+ server: {
+ command: "npx",
+ args: [
+ "-y",
+ "mcp-remote",
+ "https://mcp.acme.dev/mcp",
+ "--header",
+ "Authorization: Bearer hdr-secret-aaaa",
+ ],
+ },
+ },
+ {
+ name: "remote-h",
+ secret: "xkey-secret-bbbb",
+ summary: "npx mcp-remote https://mcp.acme.dev/mcp -H X-API-Key: •••",
+ server: {
+ command: "npx",
+ args: ["mcp-remote", "https://mcp.acme.dev/mcp", "-H", "X-API-Key: xkey-secret-bbbb"],
+ },
+ },
+ {
+ name: "remote-header-inline",
+ secret: "inline-secret-cccc",
+ summary: "npx mcp-remote https://mcp.acme.dev/mcp --header=Authorization: •••",
+ server: {
+ command: "npx",
+ args: ["mcp-remote", "https://mcp.acme.dev/mcp", "--header=Authorization:Bearer inline-secret-cccc"],
+ },
+ },
+ {
+ name: "header-arg",
+ secret: "cookie-secret-dddd",
+ summary: "node proxy.js Cookie: ••• Accept: application/json",
+ server: {
+ command: "node",
+ args: ["proxy.js", "Cookie: session=cookie-secret-dddd", "Accept: application/json"],
+ },
+ },
+ {
+ name: "query-arg",
+ secret: "query-secret-eeee",
+ summary: "npx mcp-remote https://api.example.com/mcp?api_key=•••&team=•••",
+ server: {
+ command: "npx",
+ args: ["mcp-remote", "https://api.example.com/mcp?api_key=query-secret-eeee&team=t1#frag"],
+ },
+ },
+ {
+ name: "postgres",
+ secret: "db-pass-ffff",
+ summary: "npx -y @modelcontextprotocol/server-postgres postgresql://db.example.com:5432/app",
+ server: {
+ command: "npx",
+ args: [
+ "-y",
+ "@modelcontextprotocol/server-postgres",
+ "postgresql://dbuser:[email protected]:5432/app",
+ ],
+ },
+ },
+ {
+ name: "path-token-arg",
+ secret: OPAQUE,
+ summary: "npx mcp-remote https://hooks.example.com/mcp/•••/sse-free",
+ server: { command: "npx", args: ["mcp-remote", `https://hooks.example.com/mcp/${OPAQUE}/sse-free`] },
+ },
+ {
+ name: "url-flag",
+ secret: "flag-url-secret-gggg",
+ summary: "uvx some-server --url=https://x.example.com/mcp?token=•••",
+ server: {
+ command: "uvx",
+ args: ["some-server", "--url=https://x.example.com/mcp?token=flag-url-secret-gggg"],
+ },
+ },
+ {
+ name: "secret-flags",
+ secret: "flag-secret-hhhh",
+ summary:
+ "tool --api-key ••• --password=••• --auth ••• --client-credentials ••• --bearer ••• --verbose API_TOKEN=••• --name demo",
+ server: {
+ command: "tool",
+ args: [
+ "--api-key",
+ "flag-secret-hhhh-1",
+ "--password=flag-secret-hhhh-2",
+ "--auth",
+ "flag-secret-hhhh-3",
+ "--client-credentials",
+ "flag-secret-hhhh-4",
+ "--bearer",
+ "flag-secret-hhhh-5",
+ "--verbose",
+ "API_TOKEN=flag-secret-hhhh-6",
+ "--name",
+ "demo",
+ ],
+ },
+ },
+ {
+ name: "prefixes",
+ secret: "prefixsecretiiii",
+ summary: "run ••• ••• •••",
+ server: {
+ command: "run",
+ args: ["ghp_prefixsecretiiii", "sk-prefixsecretiiii", "xoxb-prefixsecretiiii"],
+ },
+ },
+ {
+ name: "http-userinfo",
+ secret: "userinfo-secret-jjjj",
+ summary: "https://mcp.example.org/v1/mcp",
+ server: { type: "http", url: "https://me:[email protected]/v1/mcp" },
+ },
+ {
+ name: "http-query",
+ secret: "http-query-secret-kkkk",
+ summary: "https://mcp.example.net/mcp?apiKey=•••&workspace=•••",
+ server: { type: "http", url: "https://mcp.example.net/mcp?apiKey=http-query-secret-kkkk&workspace=w9#x" },
+ },
+ {
+ name: "http-path-token",
+ secret: OPAQUE,
+ summary: "https://hooks.example.io/services/•••/mcp",
+ server: { type: "http", url: `https://hooks.example.io/services/${OPAQUE}/mcp` },
+ },
+];
+
+function fixtureHome(): string {
+ const home = tempDir();
+ write(home, ".claude.json", {
+ mcpServers: Object.fromEntries(CASES.map(({ name, server }) => [name, server])),
+ });
+ return home;
+}
+
+const managers: ConnectorManager[] = [];
+afterEach(() => {
+ for (const manager of managers.splice(0)) manager.cancelAll();
+});
+
+function setup(home: string) {
+ const dataDir = tempDir();
+ const store = new ConnectorStore({ dataDir, agentHome: join(dataDir, "agent") });
+ const manager = new ConnectorManager({
+ store,
+ cli: { command: process.execPath, args: [FAKE_CLI] },
+ env: { ...process.env, HOME: join(dataDir, "home") },
+ cwd: dataDir,
+ importHome: home,
+ });
+ managers.push(manager);
+ return { store, manager };
+}
+
+const pick = (found: ImportCandidate[], name: string) => {
+ const candidate = found.find((c) => c.name === name);
+ if (!candidate) throw new Error(`${name} was not found`);
+ return candidate;
+};
+
+describe("masking credentials in server summaries", () => {
+ it("keeps every credential out of the import list and shows the command, host, and path", () => {
+ const { manager } = setup(fixtureHome());
+ const found = manager.scan();
+ for (const { name, secret, summary } of CASES) {
+ const candidate = pick(found, name);
+ expect(candidate.summary, name).toBe(summary);
+ expect(JSON.stringify(candidate), name).not.toContain(secret);
+ }
+ });
+
+ it("keeps every credential out of the Connectors list after the import", () => {
+ const { manager } = setup(fixtureHome());
+ const found = manager.scan();
+ const imported = manager.importServers(found.map((c) => c.id));
+ expect(imported).toHaveLength(CASES.length);
+ const list = manager.list();
+ for (const { name, secret, summary } of CASES) {
+ const info = list.find((c) => c.name === name);
+ expect(info?.custom?.summary, name).toBe(summary);
+ expect(JSON.stringify(info), name).not.toContain(secret);
+ }
+ });
+
+ it("leaves ordinary arguments, package names, and paths as they are", () => {
+ expect(
+ summarize({
+ command: "npx",
+ args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/x/Docs", "--port", "8080"],
+ }),
+ ).toBe("npx -y @modelcontextprotocol/server-filesystem /Users/x/Docs --port 8080");
+ expect(summarize({ command: "npx", args: ["-y", "mcp-server-sequential-thinking-tools"] })).toBe(
+ "npx -y mcp-server-sequential-thinking-tools",
+ );
+ expect(summarize({ url: "https://mcp.notion.com/mcp" })).toBe("https://mcp.notion.com/mcp");
+ // An address that does not parse still loses its query and credentials.
+ expect(summarize({ url: "https://me:pw-secret@bad host/mcp?key=v" })).toBe("https://bad host/mcp");
+ });
+});
diff --git a/packages/daemon/test/connectors-guided.test.ts b/packages/daemon/test/connectors-guided.test.ts
index 0bb88b0..89a81f8 100644
--- a/packages/daemon/test/connectors-guided.test.ts
+++ b/packages/daemon/test/connectors-guided.test.ts
@@ -101,6 +101,27 @@ describe("guided catalog entries", () => {
expect(gmail.guide?.note).toMatch(/Developer Preview/);
expect(slack.oauth && gmail.oauth).toBe(true);
});
+
+ it("describes what each guided connector can send as its permissions allow, and that read only hides it", () => {
+ // Gmail's gmail.compose scope can send mail, so the copy never promises otherwise.
+ const gmail = entry("gmail");
+ expect(gmail.sends).not.toMatch(/never/i);
+ expect(gmail.sends).toMatch(/send/i);
+ expect(gmail.sends).toMatch(/draft/i);
+ expect(gmail.sends).toMatch(/approve each/i);
+ expect(gmail.guide?.note).toMatch(/gmail\.compose/);
+ expect(gmail.guide?.note).toMatch(/send/i);
+ // Slack's guide asks only for chat:write, so it can send and schedule messages, not react or create canvases.
+ const slack = entry("slack");
+ expect(slack.guide?.steps.join(" ")).not.toMatch(/reactions:write|canvases:write/);
+ expect(slack.sends).not.toMatch(/reaction|canvas/i);
+ expect(slack.sends).toMatch(/send/i);
+ // Discord's guide gives the bot no Manage Channels permission.
+ const discord = entry("discord");
+ expect(discord.guide?.steps.join(" ")).not.toMatch(/Manage Channels/);
+ expect(discord.sends).not.toMatch(/manage/i);
+ for (const guided of [gmail, slack, discord]) expect(guided.sends, guided.id).toMatch(/read only hides/i);
+ });
});
describe("guided mcp.json rendering", () => {
diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.ts
index f74ad3b..5d69613 100644
--- a/packages/protocol/src/index.ts
+++ b/packages/protocol/src/index.ts
@@ -124,6 +124,9 @@ export interface ConnectorInfo {
noSignIn?: true;
}
+/** The daemon keeps at most this many drafts waiting; a newer one drops the oldest. */
+export const MAX_CONNECTOR_DRAFTS = 5;
+
/** A connector the assistant drafted with `propose_connector`, waiting for the user's answer. */
export interface ConnectorDraft {
draftId: string;
@@ -151,6 +154,8 @@ export interface ImportCandidate {
headerNames: string[];
/** Values the user types after the import (VS Code inputs), by their description. */
inputs: string[];
+ /** Values that run a command or read an environment variable when the server starts, in plain words. */
+ notes?: string[];
importable: boolean;
/** Why it cannot be imported. */
reason?: string;
diff --git a/packages/ui/src/components/ConnectorsPanel.tsx b/packages/ui/src/components/ConnectorsPanel.tsx
index 90ea85e..8eae156 100644
--- a/packages/ui/src/components/ConnectorsPanel.tsx
+++ b/packages/ui/src/components/ConnectorsPanel.tsx
@@ -272,6 +272,11 @@ function ImportList({ found, importServers, close }: ImportListProps) {
{candidate.summary ? <code>{candidate.summary}</code> : null}
<ImportNames label="Keys" names={[...candidate.envNames, ...candidate.headerNames]} />
<ImportNames label="You will type" names={candidate.inputs} />
+ {candidate.notes?.map((note) => (
+ <p key={note} className="connector-note">
+ {note}
+ </p>
+ ))}
{candidate.duplicateOf ? (
<p className="connector-note">Already in your connectors as {candidate.duplicateOf}.</p>
) : candidate.reason ? (
diff --git a/packages/ui/src/store.ts b/packages/ui/src/store.ts
index 632b4cf..394a4c2 100644
--- a/packages/ui/src/store.ts
+++ b/packages/ui/src/store.ts
@@ -16,6 +16,7 @@ import type {
ProfileRole,
ServerMessage,
} from "@gentle-dot/protocol";
+import { MAX_CONNECTOR_DRAFTS } from "@gentle-dot/protocol";
export interface AuthFlowState {
providerId: string;
@@ -50,7 +51,10 @@ export interface ConnectorsState {
list?: ConnectorInfo[];
/** A connector sign-in or setup; `providerId` is the connector id (or the draft's name). */
flow?: AuthFlowState;
- /** Connectors the assistant drafted, waiting for the user's answer. */
+ /**
+ * Connectors the assistant drafted, waiting for the user's answer: like the daemon, only the newest
+ * five, and replaced by what the daemon sends after each `ready`.
+ */
drafts?: ConnectorDraft[];
/** The servers the last scan found in other apps, while the list is shown. */
imports?: ImportCandidate[];
@@ -177,6 +181,8 @@ function reduceServer(state: DotState, message: ServerMessage): DotState {
conversationId: message.conversationId ?? state.conversationId,
model: message.model ?? state.model,
features: message.features ?? initialState.features,
+ // The daemon sends the drafts still waiting right after ready.
+ connectors: { ...state.connectors, drafts: [] },
};
case "agent_state":
return { ...state, agentState: message.state };
@@ -253,7 +259,8 @@ function reduceServer(state: DotState, message: ServerMessage): DotState {
case "connector_draft": {
const drafts = state.connectors.drafts ?? [];
if (drafts.some((d) => d.draftId === message.draft.draftId)) return state;
- return { ...state, connectors: { ...state.connectors, drafts: [...drafts, message.draft] } };
+ const kept = [...drafts, message.draft].slice(-MAX_CONNECTOR_DRAFTS);
+ return { ...state, connectors: { ...state.connectors, drafts: kept } };
}
case "connector_draft_resolved": {
const drafts = (state.connectors.drafts ?? []).filter((d) => d.draftId !== message.draftId);
diff --git a/packages/ui/test/connectors-more.test.tsx b/packages/ui/test/connectors-more.test.tsx
index 40f1a54..a0c514b 100644
--- a/packages/ui/test/connectors-more.test.tsx
+++ b/packages/ui/test/connectors-more.test.tsx
@@ -251,6 +251,19 @@ describe("adding another connector", () => {
apply(ready, { type: "connector_draft", draft }, { type: "connector_draft", draft }).connectors.drafts,
).toHaveLength(1);
});
+
+ it("keeps only the drafts the daemon still holds: the newest five, and none it resolved while away", () => {
+ const many = Array.from({ length: 7 }, (_, i) => ({ ...draft, draftId: `d${i}`, name: `Server ${i}` }));
+ const s = apply(ready, ...many.map((d): ServerPayload => ({ type: "connector_draft", draft: d })));
+ expect(s.connectors.drafts?.map((d) => d.draftId)).toEqual(["d2", "d3", "d4", "d5", "d6"]);
+ // After a reconnect the daemon sends the drafts still waiting right after ready.
+ const again = apply(
+ s,
+ { type: "ready", agentState: "idle" },
+ { type: "connector_draft", draft: many[6] as ConnectorDraft },
+ );
+ expect(again.connectors.drafts?.map((d) => d.draftId)).toEqual(["d6"]);
+ });
});
describe("importing MCP servers", () => {
@@ -289,6 +302,32 @@ describe("importing MCP servers", () => {
});
});
+ it("notes a value that runs a command or reads an environment variable before the import", () => {
+ const vault: ImportCandidate = {
+ id: "Gentle Shell:vault",
+ name: "vault",
+ sources: ["Gentle Shell"],
+ transport: "stdio",
+ summary: "vault-mcp",
+ envNames: ["VAULT_TOKEN", "REGION"],
+ headerNames: [],
+ inputs: [],
+ importable: true,
+ notes: [
+ "VAULT_TOKEN: Runs a command on your computer to get this value.",
+ "REGION: Reads the environment variable AWS_REGION.",
+ ],
+ };
+ panel(
+ apply(reduce(ready, { type: "connectors", open: true }), { type: "connector_imports", found: [vault] }),
+ );
+ const list = within(screen.getByRole("region", { name: "Found these servers" }));
+ expect(
+ list.getByText("VAULT_TOKEN: Runs a command on your computer to get this value."),
+ ).toBeInTheDocument();
+ expect(list.getByText("REGION: Reads the environment variable AWS_REGION.")).toBeInTheDocument();
+ });
+
it("says when nothing was found, and closes the list after an import", () => {
let s = apply(reduce(ready, { type: "connectors", open: true }), {
type: "connector_imports",