Skip to content

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

TypeScript

feat: guided Discord, Slack, and Gmail connectors, assistant-drafted connectors, and import of existing MCP servers

Alan Buscaglia994abce6cb00
diff --git a/README.md b/README.md
index 292a37c..e80db60 100644
--- a/README.md
+++ b/README.md
@@ -39,7 +39,7 @@ The assistant keeps to its own instance. The agent works in `~/.gentle-dot/works
Memory uses your global Engram (`~/.engram`, server on port 7437, or your own `ENGRAM_DATA_DIR`, `ENGRAM_PORT`, and `ENGRAM_URL`), and everything the assistant remembers goes to the project `gentle-dot`. If Engram is not running, the assistant starts it with your data folder. `GENTLE_DOT_ENGRAM_DATA_DIR` points at another data folder; `GENTLE_DOT_ENGRAM=private` gives the assistant a memory of its own instead (port 7438, `GENTLE_DOT_ENGRAM_PORT`). Memories saved by earlier versions in `~/.gentle-dot/home/.engram` are not moved to the global Engram.
-Connectors let the assistant use Notion, Linear, and Atlassian through their official MCP servers: open Connectors (the plug icon, or type `/connectors`), choose Connect, and approve access in the browser. Each connector is "Read only" (it can search and read) or "Read and send"; even then, the assistant asks you with a preview before every action that sends or changes something. The daemon reads `~/.gentle-dot/connectors.json` once when it starts and keeps your choices in memory; it alone writes that file and the engine's `mcp.json` (`~/.gentle-dot/agent`), and if anything else changes them while it runs, it puts them back and tells you "A change to your connectors was blocked." The assistant cannot read your sign-ins and keys with its file tools; its shell commands are checked too, but that check is best effort, not a security boundary.
+Connectors let the assistant use Notion, Linear, and Atlassian through their official MCP servers: open Connectors (the plug icon, or type `/connectors`), choose Connect, and approve access in the browser. Discord, Slack, and Gmail show a step-by-step guide first: Discord runs a community server (`@pasympa/discord-mcp`, pinned) with a bot token you create; Slack and Gmail use their official servers with an app or Google Cloud project of your own, whose redirect address the guide shows. "Add another connector" asks the assistant in the chat; it answers with a draft card that lists the command or address and the secrets it needs, and nothing is added until you approve it. "Import my MCP servers" reads (only reads) the configs of Claude Desktop, Claude Code, Cursor, VS Code, Windsurf, OpenCode, and Gentle Shell, and lists what it found by name; you pick which to copy. Secrets are always typed in the app, never in the chat, and drafted or imported servers start read only with all of their tools hidden. Each connector is "Read only" (it can search and read) or "Read and send"; even then, the assistant asks you with a preview before every action that sends or changes something. The daemon reads `~/.gentle-dot/connectors.json` once when it starts and keeps your choices in memory; it alone writes that file and the engine's `mcp.json` (`~/.gentle-dot/agent`), and if anything else changes them while it runs, it puts them back and tells you "A change to your connectors was blocked." The assistant cannot read your sign-ins and keys with its file tools; its shell commands are checked too, but that check is best effort, not a security boundary.
## Checks
diff --git a/docs/design.md b/docs/design.md
index 0e267bd..280214b 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -133,10 +133,16 @@ Every daemon message carries `seq` (monotonic per connection) so the UI can dete
### Connectors (S18)
-- 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 a curated list of read-only tools. Slack, Gmail, Discord, assistant-drafted servers (S19), and imports (S20) add catalog entries or drafts that go through the same store.
+- 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`.
+- 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.
- 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: `connected` when `mcp-auth.json` holds tokens under `mcp__<id>|<url>` (token values are dropped while parsing); `needs_signin` otherwise; `error` after a failed sign-in.
+- 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.
- 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.
diff --git a/e2e/serve.ts b/e2e/serve.ts
index 3636b38..c0c7160 100644
--- a/e2e/serve.ts
+++ b/e2e/serve.ts
@@ -2,13 +2,14 @@
// It also starts a second daemon, with the conversations list on, and waits for it first.
import { spawn } from "node:child_process";
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import {
E2E_COMMANDS_FILE,
E2E_CONVERSATIONS_DATA_DIR,
E2E_CONVERSATIONS_PORT,
E2E_DATA_DIR,
+ E2E_IMPORT_HOME,
E2E_TOKEN,
} from "./token.ts";
@@ -46,6 +47,9 @@ process.env.GENTLE_DOT_AGENT_BIN = process.execPath;
process.env.GENTLE_DOT_AGENT_ARGS = JSON.stringify([
fileURLToPath(new URL("../packages/daemon/test/fixtures/fake-agent.ts", import.meta.url)),
]);
+// "Import my MCP servers" scans a stand-in home with other apps' configs, never the developer's.
+process.env.GENTLE_DOT_IMPORT_HOME = E2E_IMPORT_HOME;
+if (!conversations) writeImportHome(E2E_IMPORT_HOME);
if (conversations) {
process.env.GENTLE_DOT_CONVERSATIONS = "1";
} else {
@@ -58,6 +62,38 @@ if (conversations) {
const cli = "../packages/daemon/src/cli.ts";
await import(cli);
+function writeImportHome(home: string): void {
+ rmSync(home, { recursive: true, force: true });
+ const write = (path: string, value: unknown) => {
+ mkdirSync(dirname(join(home, path)), { recursive: true });
+ writeFileSync(join(home, path), JSON.stringify(value, null, 2));
+ };
+ write(".cursor/mcp.json", {
+ mcpServers: {
+ github: {
+ command: "npx",
+ args: ["-y", "@modelcontextprotocol/server-github"],
+ env: { GITHUB_PERSONAL_ACCESS_TOKEN: "ghp_e2e_secret_value" },
+ },
+ },
+ });
+ write(".codeium/windsurf/mcp_config.json", {
+ mcpServers: { oldsse: { serverUrl: "https://old.example.com/sse" } },
+ });
+ write("Library/Application Support/Code/User/mcp.json", {
+ inputs: [{ type: "promptString", id: "key", description: "Search API key", password: true }],
+ servers: {
+ search: {
+ type: "stdio",
+ command: "npx",
+ args: ["-y", "search-mcp"],
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: a VS Code input reference.
+ env: { SEARCH_KEY: "${input:key}" },
+ },
+ },
+ });
+}
+
async function waitForHealth(url: string): Promise<void> {
for (let attempt = 0; attempt < 300; attempt++) {
const up = await fetch(url).then(
diff --git a/e2e/token.ts b/e2e/token.ts
index d45e7e8..52dad54 100644
--- a/e2e/token.ts
+++ b/e2e/token.ts
@@ -9,3 +9,5 @@ export const E2E_COMMANDS_FILE = join(E2E_DATA_DIR, "agent-commands.jsonl");
/** A second daemon with the conversations list on (it is off by default), for the tests of that feature. */
export const E2E_CONVERSATIONS_PORT = 4392;
export const E2E_CONVERSATIONS_DATA_DIR = join(tmpdir(), "gentle-dot-e2e-conversations");
+/** A stand-in home with other apps' MCP configs, scanned by "Import my MCP servers" (never the real one). */
+export const E2E_IMPORT_HOME = join(tmpdir(), "gentle-dot-e2e-import-home");
diff --git a/e2e/web.spec.ts b/e2e/web.spec.ts
index 1d9d342..282c8fe 100644
--- a/e2e/web.spec.ts
+++ b/e2e/web.spec.ts
@@ -1,7 +1,14 @@
-import { existsSync, readFileSync } from "node:fs";
+import { createHash } from "node:crypto";
+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
import { expect, type Page, test } from "@playwright/test";
-import { E2E_COMMANDS_FILE, E2E_CONVERSATIONS_PORT, E2E_DATA_DIR, E2E_TOKEN } from "./token.ts";
+import {
+ E2E_COMMANDS_FILE,
+ E2E_CONVERSATIONS_PORT,
+ E2E_DATA_DIR,
+ E2E_IMPORT_HOME,
+ E2E_TOKEN,
+} from "./token.ts";
const readJson = (path: string) =>
existsSync(path) ? (JSON.parse(readFileSync(path, "utf8")) as unknown) : undefined;
@@ -273,6 +280,112 @@ test("connects Notion from the Connectors screen, switches its mode, and removes
await expect(page.locator(".message-user")).toHaveCount(sent);
});
+/** Every file below `dir` with its hash, to show a scan never changes them. */
+function hashes(dir: string): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const name of readdirSync(dir)) {
+ const path = join(dir, name);
+ if (statSync(path).isDirectory()) Object.assign(out, hashes(path));
+ else out[path] = createHash("sha256").update(readFileSync(path)).digest("hex");
+ }
+ return out;
+}
+
+test("sets up Discord from its guide, imports a found server, and adds the assistant's draft", async ({
+ page,
+}) => {
+ const shots = "/tmp/gentle-dot-t18b";
+ const before = hashes(E2E_IMPORT_HOME);
+ const mcpServers = () =>
+ (
+ JSON.parse(readFileSync(join(E2E_DATA_DIR, "agent", "mcp.json"), "utf8")) as {
+ mcpServers: Record<string, Record<string, unknown>>;
+ }
+ ).mcpServers;
+ await open(page);
+ await page.getByRole("button", { name: "Connectors" }).click();
+ const screen = page.getByRole("region", { name: "Connectors" });
+
+ // Guides: Slack and Gmail show the redirect address to register; Discord asks for the bot token.
+ for (const name of ["Slack", "Gmail"]) {
+ await screen.getByRole("button", { name: `Connect ${name}` }).click();
+ const guide = screen.getByRole("region", { name: `Set up ${name}` });
+ await expect(guide).toContainText("http://localhost:3841");
+ await page.screenshot({ path: `${shots}/guide-${name.toLowerCase()}.png` });
+ await guide.getByRole("button", { name: "Back" }).click();
+ }
+ await screen.getByRole("button", { name: "Connect Discord" }).click();
+ const guide = screen.getByRole("region", { name: "Set up Discord" });
+ await expect(guide).toContainText("Message Content Intent");
+ await page.screenshot({ path: `${shots}/guide-discord.png` });
+ await guide.getByRole("button", { name: "Continue" }).click();
+ await expect(screen).toContainText("Setting up Discord");
+ await screen.getByLabel(/bot token/i).fill("dummy-discord-token");
+ await screen.getByRole("button", { name: "Continue" }).click();
+ await expect(screen.getByRole("status")).toHaveText("Connected to Discord.");
+ await screen.getByRole("button", { name: "Back to connectors" }).click();
+ expect(mcpServers().discord).toMatchObject({ command: "npx", args: ["-y", "@pasympa/[email protected]"] });
+ await expect(page.locator("body")).not.toContainText("dummy-discord-token");
+
+ // Import: names only, with the source app; the old SSE server cannot be imported.
+ await screen.getByRole("button", { name: "Import my MCP servers" }).click();
+ const found = screen.getByRole("region", { name: "Found these servers" });
+ await expect(found.getByRole("checkbox", { name: "github" })).toBeVisible();
+ await expect(found).toContainText("From Cursor");
+ await expect(found).toContainText("GITHUB_PERSONAL_ACCESS_TOKEN");
+ await expect(found.getByRole("checkbox", { name: "oldsse" })).toBeDisabled();
+ await expect(page.locator("body")).not.toContainText("ghp_e2e_secret_value");
+ await page.screenshot({ path: `${shots}/import-list.png` });
+ await found.getByRole("checkbox", { name: "github" }).check();
+ await found.getByRole("checkbox", { name: "search" }).check();
+ await found.getByRole("button", { name: "Import 2 servers" }).click();
+ const github = screen.getByRole("listitem", { name: "github" });
+ await expect(github).toContainText("Imported from Cursor");
+ await expect(github).toContainText("tools stay hidden");
+ await expect(screen.getByRole("listitem", { name: "search" })).toContainText("Needs setup");
+ expect(mcpServers().github).toMatchObject({ toolExposure: { "*": "hidden" } });
+ expect(hashes(E2E_IMPORT_HOME)).toEqual(before);
+
+ // Add another: the request goes to the chat; the assistant's draft comes back as a card.
+ await screen.getByRole("button", { name: "Add another connector" }).click();
+ await screen.getByLabel("What do you want to connect?").fill("Weather");
+ await page.screenshot({ path: `${shots}/add-another.png` });
+ await screen.getByRole("button", { name: "Ask the assistant" }).click();
+ await expect(page.locator(".message-user").last()).toContainText("Weather");
+ const draft = {
+ name: "Weather",
+ description: "Look up forecasts.",
+ transport: "stdio",
+ command: "npx",
+ args: ["-y", "[email protected]"],
+ env_names: ["WEATHER_API_KEY"],
+ };
+ await say(page, `propose:${JSON.stringify(draft)}`);
+ const card = page.getByRole("region", { name: "Add Weather?" });
+ await expect(card).toContainText("npx -y [email protected]");
+ await expect(card).toContainText("WEATHER_API_KEY");
+ await card.scrollIntoViewIfNeeded();
+ await card.screenshot({ path: `${shots}/draft-card.png` });
+ await page.screenshot({ path: `${shots}/draft-card-panel.png` });
+ await card.getByRole("button", { name: "Add Weather" }).click();
+ await expect(screen).toContainText("Setting up Weather");
+ await screen.getByLabel(/WEATHER_API_KEY/).fill("weather-secret-value");
+ await screen.getByRole("button", { name: "Continue" }).click();
+ await expect(screen.getByRole("status")).toHaveText("Connected to Weather.");
+ expect(mcpServers().weather).toMatchObject({ command: "npx", toolExposure: { "*": "hidden" } });
+ await expect(page.locator("body")).not.toContainText("weather-secret-value");
+ await screen.getByRole("button", { name: "Back to connectors" }).click();
+ for (const name of ["github", "Weather"]) {
+ const row = screen.getByRole("listitem", { name });
+ await row.scrollIntoViewIfNeeded();
+ await row.screenshot({ path: `${shots}/connector-row-${name.toLowerCase()}.png` });
+ }
+ for (const name of ["Discord", "github", "search", "Weather"]) {
+ await screen.getByRole("button", { name: `Remove ${name}` }).click();
+ await expect(screen.getByRole("button", { name: `Remove ${name}` })).toHaveCount(0);
+ }
+});
+
test("shows a connector action as an approval card with a preview", async ({ page }) => {
await open(page);
await say(page, "ask:approval");
diff --git a/packages/daemon/src/bridge.ts b/packages/daemon/src/bridge.ts
index 029d0cd..f7c4cda 100644
--- a/packages/daemon/src/bridge.ts
+++ b/packages/daemon/src/bridge.ts
@@ -19,6 +19,7 @@ import {
pageHistory,
resolveConversation,
} from "./conversations.ts";
+import { DRAFT_STATUS_KEY } from "./extensions/approval-guard.ts";
import { describeTool, textOf } from "./presentation.ts";
import {
LiveModelSwitch,
@@ -92,6 +93,8 @@ export class DotBridge {
private nextMessage = 0;
private assistantId: string | undefined;
private restartPending = false;
+ private restarting = false;
+ private restartAgain = false;
/** The running answer is being stopped on purpose, so its end is not an error. */
private stopRequested = false;
/** The conversation switch in progress; messages sent meanwhile wait for it. */
@@ -142,6 +145,8 @@ export class DotBridge {
});
if (this.queued()) this.deliver(client, { type: "queue", ...this.queue });
for (const { ask } of this.asks.values()) this.deliver(client, { type: "ask", ask });
+ for (const draft of this.options.connectors?.drafts() ?? [])
+ this.deliver(client, { type: "connector_draft", draft });
if (this.interrupted) this.deliver(client, { type: "interrupted" });
return () => {
this.clients.delete(client);
@@ -328,11 +333,29 @@ export class DotBridge {
return;
case "connector_connect":
case "connector_signin":
+ case "connector_setup":
case "connector_disconnect":
case "connector_mode":
case "connector_remove":
await this.connectorCommand(client, message);
return;
+ case "connector_draft_reply": {
+ const emit = (payload: ServerPayload) => this.deliver(client, payload);
+ const { draftId, approve } = message;
+ const refused = this.requireConnectors().decideDraft(client, draftId, approve, emit);
+ if (refused) this.deliver(client, { type: "error", ...refused });
+ else this.broadcast({ type: "connector_draft_resolved", draftId, approved: approve });
+ return;
+ }
+ case "connectors_scan":
+ this.deliver(client, { type: "connector_imports", found: this.requireConnectors().scan() });
+ return;
+ case "connector_import":
+ this.deliver(client, {
+ type: "connector_imported",
+ names: this.requireConnectors().importServers(message.ids),
+ });
+ return;
case "profile_save":
case "profile_rename":
case "profile_duplicate":
@@ -466,6 +489,9 @@ export class DotBridge {
case "connector_signin":
refused = connectors.signIn(client, message.connectorId, emit);
break;
+ case "connector_setup":
+ refused = connectors.setup(client, message.connectorId, emit);
+ break;
case "connector_disconnect":
refused = connectors.disconnect(message.connectorId);
break;
@@ -479,6 +505,20 @@ export class DotBridge {
if (refused) this.deliver(client, { type: "error", ...refused });
}
+ /**
+ * A connector the assistant drafted with `propose_connector`. It reaches the daemon on the
+ * engine's own output, and every window shows it as a card; nothing changes until the user answers.
+ */
+ private onConnectorDraft(text: unknown): void {
+ const draft = typeof text === "string" ? this.options.connectors?.propose(text) : undefined;
+ if (!draft) {
+ this.log("ignored a malformed connector draft");
+ return;
+ }
+ this.log(`the assistant drafted a connector: ${draft.name}`);
+ this.broadcast({ type: "connector_draft", draft });
+ }
+
/** The connector files were changed outside the Connectors screen and put back. */
private connectorChangeBlocked(): void {
this.broadcast({ type: "toast", level: "warning", message: "A change to your connectors was blocked." });
@@ -601,9 +641,23 @@ export class DotBridge {
this.restartAgent();
}
+ /** Restarts the engine; changes that arrive during a restart get one more, so the last one is read. */
private restartAgent(): void {
this.restartPending = false;
- this.supervisor.restart().catch((error: Error) => this.log(`agent restart failed: ${error.message}`));
+ if (this.restarting) {
+ this.restartAgain = true;
+ return;
+ }
+ this.restarting = true;
+ this.supervisor
+ .restart()
+ .catch((error: Error) => this.log(`agent restart failed: ${error.message}`))
+ .finally(() => {
+ this.restarting = false;
+ if (!this.restartAgain) return;
+ this.restartAgain = false;
+ this.restartAgent();
+ });
}
/** A profile applied while the assistant was busy switches the model now. */
@@ -792,6 +846,10 @@ export class DotBridge {
this.broadcast({ type: "toast", level, message: presentText(String(event.message ?? "")) });
return;
}
+ if (method === "setStatus" && event.statusKey === DRAFT_STATUS_KEY) {
+ this.onConnectorDraft(event.statusText);
+ return;
+ }
if (!DIALOG_METHODS.has(method) || !requestId) return;
const ask: Ask = {
requestId,
diff --git a/packages/daemon/src/connector-import.ts b/packages/daemon/src/connector-import.ts
new file mode 100644
index 0000000..b7e3019
--- /dev/null
+++ b/packages/daemon/src/connector-import.ts
@@ -0,0 +1,241 @@
+/**
+ * Finds the MCP servers the user set up in other apps (S20), read-only: Claude Desktop, Claude Code,
+ * Cursor, VS Code, Windsurf, OpenCode, and Gentle Shell, on macOS and Linux. Each entry is mapped to
+ * the engine's `mcp.json` schema. Values keep their meaning: a literal stays a literal (escaped, so
+ * the engine neither runs it as `!command` nor expands `$NAME`), an environment reference becomes the
+ * engine's `${NAME}`, and a VS Code input becomes a value the user types in the app (`${input:<id>}`).
+ * The source files are only read; nothing here writes anywhere.
+ */
+import { existsSync, readFileSync, statSync } from "node:fs";
+import { isAbsolute, join } from "node:path";
+import type { ImportCandidate } from "@gentle-dot/protocol";
+import { literal, type ServerTemplate, type SetupField } from "./connectors.ts";
+
+/** One server found in one app's configuration. */
+export interface ScannedServer {
+ /** The app it was found in. */
+ source: string;
+ name: string;
+ transport: ImportCandidate["transport"];
+ /** The engine's server entry; undefined when it cannot be imported. */
+ server?: ServerTemplate;
+ /** Values the user types after the import. */
+ fields: SetupField[];
+ /** Signs in with OAuth: a remote server without an `Authorization` header. */
+ oauth: boolean;
+ reason?: string;
+}
+
+/** How an app writes references in its values. */
+type Syntax = "literal" | "claude-code" | "vscode" | "opencode" | "engine";
+
+const SSE_REASON = "It uses the old SSE transport, which the assistant does not support.";
+const NO_SERVER = "It has no command or address the assistant can use.";
+const MAX_FILE = 50 * 1024 * 1024;
+const MAX_PROJECTS = 200;
+const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
+const INPUT_ID = /^[A-Za-z0-9_.-]{1,64}$/;
+
+type Json = Record<string, unknown>;
+const isRecord = (value: unknown): value is Json =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
+/** Every server in the known configuration files below `home`; files that are missing or broken are skipped. */
+export function scanClientConfigs(home: string): ScannedServer[] {
+ const found: ScannedServer[] = [];
+ const read = (path: string) => readJson(join(home, path));
+ const add = (source: string, servers: unknown, syntax: Syntax, inputs?: unknown) => {
+ if (!isRecord(servers)) return;
+ const fields = inputFields(inputs);
+ for (const [name, raw] of Object.entries(servers))
+ if (isRecord(raw)) found.push(mapServer(source, name, raw, { syntax, home, inputs: fields }));
+ };
+
+ for (const path of [
+ "Library/Application Support/Claude/claude_desktop_config.json",
+ ".config/Claude/claude_desktop_config.json",
+ ])
+ add("Claude Desktop", read(path)?.mcpServers, "literal");
+
+ const claude = read(".claude.json");
+ add("Claude Code", claude?.mcpServers, "claude-code");
+ const projects = isRecord(claude?.projects) ? Object.entries(claude.projects).slice(0, MAX_PROJECTS) : [];
+ for (const [folder, project] of projects) {
+ if (isRecord(project)) add("Claude Code", project.mcpServers, "claude-code");
+ if (isAbsolute(folder))
+ add("Claude Code", readJson(join(folder, ".mcp.json"))?.mcpServers, "claude-code");
+ }
+
+ add("Cursor", read(".cursor/mcp.json")?.mcpServers, "vscode");
+ for (const path of ["Library/Application Support/Code/User/mcp.json", ".config/Code/User/mcp.json"]) {
+ const vscode = read(path);
+ add("VS Code", vscode?.servers, "vscode", vscode?.inputs);
+ }
+ add("Windsurf", read(".codeium/windsurf/mcp_config.json")?.mcpServers, "vscode");
+
+ const opencode = read(".config/opencode/opencode.json");
+ if (isRecord(opencode?.mcp))
+ for (const [name, raw] of Object.entries(opencode.mcp))
+ if (isRecord(raw))
+ found.push(mapServer("OpenCode", name, openCodeEntry(raw), { syntax: "opencode", home }));
+
+ add("Gentle Shell", read(".gentle-shell/agent/mcp.json")?.mcpServers, "engine");
+ return found;
+}
+
+function readJson(path: string): Json | undefined {
+ try {
+ if (!existsSync(path) || statSync(path).size > MAX_FILE) return undefined;
+ const value = JSON.parse(readFileSync(path, "utf8")) as unknown;
+ return isRecord(value) ? value : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/** OpenCode keeps the command line in one array and the environment under `environment`. */
+function openCodeEntry(raw: Json): Json {
+ if (raw.type === "local" && Array.isArray(raw.command)) {
+ const [command, ...args] = raw.command;
+ return { command, args, env: raw.environment };
+ }
+ return { url: raw.url, headers: raw.headers };
+}
+
+/** VS Code's `inputs`: values its own app asks for, by id. */
+function inputFields(inputs: unknown): Map<string, SetupField> {
+ const fields = new Map<string, SetupField>();
+ if (!Array.isArray(inputs)) return fields;
+ for (const input of inputs) {
+ if (!isRecord(input) || typeof input.id !== "string" || !INPUT_ID.test(input.id)) continue;
+ const label = typeof input.description === "string" && input.description ? input.description : input.id;
+ fields.set(input.id, { key: input.id, label, secret: input.password === true });
+ }
+ return fields;
+}
+
+interface MapContext {
+ syntax: Syntax;
+ home: string;
+ inputs?: Map<string, SetupField>;
+}
+
+function mapServer(source: string, name: string, raw: Json, context: MapContext): ScannedServer {
+ const used: SetupField[] = [];
+ const convert = new Converter(context, used);
+ const url =
+ typeof raw.url === "string" ? raw.url : typeof raw.serverUrl === "string" ? raw.serverUrl : undefined;
+ const base = { source, name, fields: used, oauth: false };
+ if (raw.type === "sse" || (url && raw.type === undefined && raw.command === undefined && isSsePath(url)))
+ return { ...base, transport: "sse", reason: SSE_REASON };
+ if (typeof raw.command === "string" && raw.command !== "") {
+ const server: ServerTemplate = { command: convert.raw(raw.command) };
+ if (Array.isArray(raw.args) && raw.args.length > 0)
+ server.args = raw.args
+ .filter((arg): arg is string => typeof arg === "string")
+ .map((arg) => convert.raw(arg));
+ const env = convert.record(raw.env);
+ if (env) server.env = env;
+ if (typeof raw.cwd === "string" && raw.cwd) server.cwd = convert.raw(raw.cwd);
+ return { ...base, transport: "stdio", server };
+ }
+ if (url && URL.canParse(url) && /^https?:$/.test(new URL(url).protocol)) {
+ const server: ServerTemplate = { url: convert.raw(url) };
+ const headers = convert.record(raw.headers);
+ if (headers) server.headers = headers;
+ const oauth = context.syntax === "engine" ? engineOAuth(raw.oauth) : undefined;
+ if (oauth) server.oauth = oauth;
+ const authorized = Object.keys(headers ?? {}).some((key) => key.toLowerCase() === "authorization");
+ return { ...base, transport: "http", server, oauth: !authorized };
+ }
+ return { ...base, transport: url ? "http" : "stdio", reason: NO_SERVER };
+}
+
+function isSsePath(url: string): boolean {
+ return URL.canParse(url) && /\/sse\/?$/i.test(new URL(url).pathname);
+}
+
+/** A Gentle Shell server's own OAuth client settings, which use the engine's schema already. */
+function engineOAuth(
+ value: unknown,
+): NonNullable<Extract<ServerTemplate, { url: string }>["oauth"]> | undefined {
+ if (!isRecord(value)) return undefined;
+ const oauth: NonNullable<Extract<ServerTemplate, { url: string }>["oauth"]> = {};
+ for (const key of ["clientId", "clientSecret", "callbackUrl", "scope"] as const)
+ if (typeof value[key] === "string") oauth[key] = value[key] as string;
+ if (Number.isInteger(value.callbackPort)) oauth.callbackPort = value.callbackPort as number;
+ return Object.keys(oauth).length > 0 ? oauth : undefined;
+}
+
+/** References each app expands in its values, as one pattern per syntax. */
+const REFERENCES: Record<Exclude<Syntax, "literal" | "engine">, RegExp> = {
+ // `${NAME}` and `${NAME:-default}` (the default is dropped: the engine has none).
+ "claude-code": /\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-[^}]*)?\}/g,
+ // `${env:NAME}`, `${input:id}`, and `${userHome}` (VS Code, Cursor, Windsurf).
+ vscode: /\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|input:([A-Za-z0-9_.-]{1,64})|(userHome))\}/g,
+ // `{env:NAME}`.
+ opencode: /\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g,
+};
+
+class Converter {
+ private readonly context: MapContext;
+ private readonly used: SetupField[];
+
+ constructor(context: MapContext, used: SetupField[]) {
+ this.context = context;
+ this.used = used;
+ }
+
+ /** A value the engine resolves (env, headers): references kept, the rest literal. */
+ value(text: string): string {
+ const { syntax } = this.context;
+ if (syntax === "engine") return text;
+ if (syntax === "literal") return literal(text);
+ return this.replace(text, REFERENCES[syntax], literal, (name) => `\${${name}}`);
+ }
+
+ /** A value the engine uses as written (command, args, url): only inputs and the home folder are filled. */
+ raw(text: string): string {
+ if (this.context.syntax !== "vscode") return text;
+ return this.replace(
+ text,
+ REFERENCES.vscode,
+ (part) => part,
+ (_name, match) => match,
+ );
+ }
+
+ record(value: unknown): Record<string, string> | undefined {
+ if (!isRecord(value)) return undefined;
+ const out: Record<string, string> = {};
+ for (const [key, entry] of Object.entries(value))
+ if (typeof entry === "string" && ENV_NAME.test(key.replace(/-/g, "_"))) out[key] = this.value(entry);
+ return Object.keys(out).length > 0 ? out : undefined;
+ }
+
+ private replace(
+ text: string,
+ pattern: RegExp,
+ plain: (part: string) => string,
+ env: (name: string, match: string) => string,
+ ): string {
+ let out = "";
+ let last = 0;
+ for (const match of text.matchAll(pattern)) {
+ out += plain(text.slice(last, match.index));
+ last = match.index + match[0].length;
+ const [whole, name, input, home] = match;
+ if (input) out += this.input(input);
+ else if (home) out += plain(this.context.home);
+ else out += env(name ?? "", whole);
+ }
+ return out + plain(text.slice(last));
+ }
+
+ /** A VS Code input: a value the user types in the app after the import. */
+ private input(id: string): string {
+ const field = this.context.inputs?.get(id) ?? { key: id, label: id, secret: true };
+ if (!this.used.some((f) => f.key === id)) this.used.push(field);
+ return `\${input:${id}}`;
+ }
+}
diff --git a/packages/daemon/src/connectors.ts b/packages/daemon/src/connectors.ts
index fc840da..9503a4f 100644
--- a/packages/daemon/src/connectors.ts
+++ b/packages/daemon/src/connectors.ts
@@ -12,16 +12,51 @@ import {
writeFileSync,
} from "node:fs";
import { createRequire } from "node:module";
+import { homedir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
-import type { ConnectorInfo, ConnectorMode, ServerPayload } from "@gentle-dot/protocol";
+import type {
+ ConnectorDraft,
+ ConnectorGuide,
+ ConnectorInfo,
+ ConnectorMode,
+ ImportCandidate,
+ ServerPayload,
+} from "@gentle-dot/protocol";
+import { type ScannedServer, scanClientConfigs } from "./connector-import.ts";
import { type ConnectorPolicy, POLICY_ENV } from "./extensions/approval-guard.ts";
-/** A service in the catalog: an official remote MCP server with OAuth sign-in. */
+/** A value the user types in the app (a token, client credentials); kept only in the assistant's private state. */
+export interface SetupField {
+ key: string;
+ /** What to ask, in plain words. */
+ label: string;
+ secret: boolean;
+ optional?: true;
+}
+
+/** An OAuth client of the user's own (the engine's `oauth` settings). */
+export interface OAuthTemplate {
+ clientId?: string;
+ clientSecret?: string;
+ callbackUrl?: string;
+ callbackPort?: number;
+ scope?: string;
+}
+
+/**
+ * A server entry of the engine's `mcp.json`. `${input:<key>}` stands for the value of a field; the
+ * values the engine resolves (env, headers, the client secret) are otherwise written in its syntax,
+ * so a literal is escaped with {@link literal}.
+ */
+export type ServerTemplate =
+ | { url: string; headers?: Record<string, string>; oauth?: OAuthTemplate }
+ | { command: string; args?: string[]; env?: Record<string, string>; cwd?: string };
+
+/** A service in the catalog: an official remote MCP server, or a community one the user sets up with a guide. */
export interface CatalogEntry {
id: string;
name: string;
- url: string;
reads: string;
sends: string;
/**
@@ -29,14 +64,34 @@ export interface CatalogEntry {
* anything else needs the user's approval, and read-only mode hides it.
*/
readOnlyTools: readonly string[];
+ server: ServerTemplate;
+ /** Values the user types before connecting. */
+ fields?: readonly SetupField[];
+ /** Signs in through the engine's `mcp login` (OAuth). */
+ oauth: boolean;
+ /** Steps shown before "Connect". */
+ guide?: ConnectorGuide;
}
-/** Official remote servers, checked against each provider's documentation on 2026-10-08. */
+/** Fixed loopback redirects for sign-ins with the user's own OAuth app, so they can be registered once. */
+export const SLACK_REDIRECT = "http://localhost:38417/callback";
+export const GMAIL_REDIRECT = "http://localhost:38418/callback";
+
+const CLIENT_ID: SetupField = { key: "client_id", label: "Client ID", secret: false };
+
+/** Where the value of a field goes in a server entry. */
+export const placeholder = (key: string) => `\${input:${key}}`;
+
+/**
+ * Official remote servers, checked against each provider's documentation on 2026-10-08, and Discord's
+ * community server (Discord has no official one), pinned to an exact version.
+ */
export const CATALOG: readonly CatalogEntry[] = [
{
id: "notion",
name: "Notion",
- url: "https://mcp.notion.com/mcp",
+ server: { url: "https://mcp.notion.com/mcp" },
+ oauth: true,
reads: "Search and read your pages, databases, and comments.",
sends: "Create and edit pages and add comments, after you approve each one.",
readOnlyTools: [
@@ -52,7 +107,8 @@ export const CATALOG: readonly CatalogEntry[] = [
{
id: "linear",
name: "Linear",
- url: "https://mcp.linear.app/mcp",
+ server: { url: "https://mcp.linear.app/mcp" },
+ oauth: true,
reads: "Find and read issues, projects, cycles, and comments.",
sends: "Create and update issues, projects, and comments, after you approve each one.",
readOnlyTools: [
@@ -77,7 +133,8 @@ export const CATALOG: readonly CatalogEntry[] = [
{
id: "atlassian",
name: "Atlassian",
- url: "https://mcp.atlassian.com/v2/mcp",
+ server: { url: "https://mcp.atlassian.com/v2/mcp" },
+ oauth: true,
reads: "Search and read Jira issues and Confluence pages.",
sends: "Create and edit Jira issues and Confluence pages, and comment, after you approve each one.",
readOnlyTools: [
@@ -98,32 +155,296 @@ export const CATALOG: readonly CatalogEntry[] = [
"listConfluenceComments",
],
},
+ {
+ id: "discord",
+ name: "Discord",
+ // Community server (MIT, github.com/PaSympa/discord-mcp); it declares `readOnlyHint` on its tools.
+ server: {
+ command: "npx",
+ args: ["-y", "@pasympa/[email protected]"],
+ env: { DISCORD_TOKEN: placeholder("token") },
+ },
+ fields: [
+ { key: "token", label: "Bot token (from the Bot page of your Discord application)", secret: true },
+ ],
+ 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.",
+ readOnlyTools: [
+ "discord_list_guilds",
+ "discord_get_guild_info",
+ "discord_list_channels",
+ "discord_find_channel_by_name",
+ "discord_read_messages",
+ "discord_search_messages",
+ "discord_search_guild_messages",
+ "discord_get_reactions",
+ "discord_get_message_attachments",
+ "discord_fetch_pinned_messages",
+ "discord_get_forum_channels",
+ "discord_get_forum_post",
+ "discord_list_forum_threads",
+ "discord_get_forum_tags",
+ "discord_list_members",
+ "discord_get_member_info",
+ "discord_search_members",
+ "discord_list_roles",
+ "discord_list_scheduled_events",
+ "discord_get_scheduled_event",
+ ],
+ guide: {
+ steps: [
+ "Open the Discord Developer Portal and choose New Application. Give it a name, for example Gentle Dot.",
+ "Open the Bot page and choose Reset Token. Copy the token and keep it for the last step.",
+ "On the same page, under Privileged Gateway Intents, turn on Message Content Intent and Server Members Intent, then save.",
+ "Open OAuth2, then URL Generator. Check the scope bot, then the permissions View Channels, Read Message History, Send Messages, Send Messages in Threads, and Add Reactions.",
+ "Open the generated address, pick your server, and choose Authorize. The bot can only see the servers you invite it to.",
+ "Choose Continue here and paste the bot token. It stays on this computer, in the assistant's private settings.",
+ ],
+ links: [{ label: "Discord Developer Portal", url: "https://discord.com/developers/applications" }],
+ note: "This uses a community server, not one made by Discord. Your bot acts in Discord with the permissions you gave it.",
+ },
+ },
+ {
+ id: "slack",
+ name: "Slack",
+ server: {
+ url: "https://mcp.slack.com/mcp",
+ oauth: {
+ clientId: placeholder("client_id"),
+ clientSecret: placeholder("client_secret"),
+ callbackUrl: SLACK_REDIRECT,
+ },
+ },
+ fields: [
+ CLIENT_ID,
+ {
+ key: "client_secret",
+ label: "Client Secret (leave it empty if your app uses PKCE)",
+ secret: true,
+ optional: true,
+ },
+ ],
+ 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.",
+ readOnlyTools: [
+ "slack_search_public",
+ "slack_search_public_and_private",
+ "slack_search_channels",
+ "slack_search_users",
+ "slack_read_channel",
+ "slack_read_thread",
+ "slack_read_canvas",
+ "slack_read_user_profile",
+ "slack_list_channel_members",
+ "slack_get_reactions",
+ "slack_read_file",
+ ],
+ guide: {
+ steps: [
+ "Open Slack's app page and choose Create New App, then From scratch. Pick your workspace.",
+ "Open OAuth & Permissions. Under Redirect URLs, add the address below and save it.",
+ "On the same page, turn on PKCE (Slack only accepts a redirect to this computer with it).",
+ "Under User Token Scopes, add search:read.public, search:read.private, search:read.users, channels:history, groups:history, im:history, mpim:history, channels:read, groups:read, users:read, canvases:read, reactions:read, and chat:write.",
+ "Open Basic Information and copy the Client ID (and the Client Secret, if you want to use it).",
+ "Choose Continue here, paste them, and approve access in the page that opens.",
+ ],
+ links: [
+ { label: "Slack apps", url: "https://api.slack.com/apps" },
+ { label: "Slack's MCP server guide", url: "https://docs.slack.dev/ai/slack-mcp-server" },
+ ],
+ redirectUrl: SLACK_REDIRECT,
+ note: "Your workspace admin may need to approve the app. With PKCE on, Slack asks you to sign in again every 30 days.",
+ },
+ },
+ {
+ id: "gmail",
+ name: "Gmail",
+ server: {
+ url: "https://gmailmcp.googleapis.com/mcp/v1",
+ oauth: {
+ clientId: placeholder("client_id"),
+ clientSecret: placeholder("client_secret"),
+ callbackUrl: GMAIL_REDIRECT,
+ scope: "https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/gmail.compose",
+ },
+ },
+ 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.",
+ readOnlyTools: ["search_threads", "get_thread", "get_message", "list_drafts", "list_labels"],
+ guide: {
+ steps: [
+ "In the Google Cloud console, create a project (or pick one of yours).",
+ "Enable the Gmail API and the Gmail MCP API for that project.",
+ "Open Google Auth Platform, then Branding, and choose Get Started. Name the app, pick your email, choose External (or Internal for a Workspace), and finish.",
+ "Open Audience and add your own address as a test user. Open Data Access and add the scopes gmail.readonly and gmail.compose.",
+ "Open Clients, choose Create Client, then Web application. Add the address below as an Authorized redirect URI, create it, and copy the Client ID and the Client Secret.",
+ "Choose Continue here, paste them, and approve access in the page that opens.",
+ ],
+ links: [
+ { label: "Google Cloud console", url: "https://console.cloud.google.com/" },
+ {
+ label: "Gmail MCP server guide",
+ url: "https://developers.google.com/workspace/gmail/api/guides/configure-mcp-server",
+ },
+ ],
+ 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.",
+ },
+ },
];
const catalogEntry = (id: string) => CATALOG.find((entry) => entry.id === id);
+/** A server the user added from the assistant's draft or an import. */
+export interface CustomConnector {
+ name: string;
+ description: string;
+ /** Where it came from, in plain words. */
+ origin: string;
+ server: ServerTemplate;
+ fields: SetupField[];
+ oauth: boolean;
+}
+
+export interface SavedConnector {
+ enabled: boolean;
+ mode: ConnectorMode;
+ /** The values the user typed, by field key; never sent to a window or written to the log. */
+ values?: Record<string, string>;
+ custom?: CustomConnector;
+}
+
export interface ConnectorsState {
- connectors: Record<string, { enabled: boolean; mode: ConnectorMode }>;
+ connectors: Record<string, SavedConnector>;
+}
+
+/** What a connector is, from the catalog or from the user's own server. */
+interface ConnectorSpec {
+ name: string;
+ reads: string;
+ sends: string;
+ readOnlyTools: readonly string[];
+ server: ServerTemplate;
+ fields: readonly SetupField[];
+ oauth: boolean;
+ guide?: ConnectorGuide;
+ custom?: CustomConnector;
+}
+
+function specOf(id: string, saved: SavedConnector | undefined): ConnectorSpec | undefined {
+ const entry = catalogEntry(id);
+ if (entry) return { ...entry, fields: entry.fields ?? [] };
+ const custom = saved?.custom;
+ if (!custom) return undefined;
+ return {
+ name: custom.name,
+ reads: custom.description || "Uses the tools of this server.",
+ sends: "Uses every tool of this server, after you approve each action.",
+ readOnlyTools: [],
+ server: custom.server,
+ fields: custom.fields,
+ oauth: custom.oauth,
+ custom,
+ };
+}
+
+/** True when a value the user must type is missing. */
+function missingValues(spec: ConnectorSpec, values: Record<string, string> | undefined): boolean {
+ return spec.fields.some((field) => !field.optional && !values?.[field.key]);
+}
+
+/** `text` as a literal for a value the engine resolves: it would run a leading `!` and expand `$NAME`. */
+export function literal(text: string): string {
+ return text.replace(/\$/g, "$$$$").replace(/!/g, "$$!");
+}
+
+const PLACEHOLDER = /\$\$|\$\{input:([A-Za-z0-9_.-]{1,64})\}/g;
+
+/** The server entry with the user's values in place, or undefined while a required one is missing. */
+export function fillServer(
+ template: ServerTemplate,
+ fields: readonly SetupField[],
+ values: Record<string, string>,
+): ServerTemplate | undefined {
+ if (fields.some((field) => !field.optional && !values[field.key])) return undefined;
+ const keys = new Set(fields.map((field) => field.key));
+ const fill = (text: string, resolved: boolean) =>
+ text.replace(PLACEHOLDER, (match, key: string | undefined) => {
+ if (!key || !keys.has(key)) return match;
+ const value = values[key] ?? "";
+ return resolved ? literal(value) : value;
+ });
+ // An optional value left empty drops its entry instead of leaving an empty one.
+ const dropped = (text: string) => {
+ const key = /^\$\{input:([A-Za-z0-9_.-]{1,64})\}$/.exec(text)?.[1];
+ return key !== undefined && keys.has(key) && !values[key];
+ };
+ const record = (entries: Record<string, string> | undefined) => {
+ if (!entries) return undefined;
+ const out = Object.fromEntries(
+ Object.entries(entries)
+ .filter(([, text]) => !dropped(text))
+ .map(([key, text]) => [key, fill(text, true)]),
+ );
+ return Object.keys(out).length > 0 ? out : undefined;
+ };
+ if ("url" in template) {
+ const server: ServerTemplate = { url: fill(template.url, false) };
+ const headers = record(template.headers);
+ if (headers) server.headers = headers;
+ if (template.oauth) {
+ const oauth: OAuthTemplate = {};
+ for (const key of ["clientId", "clientSecret", "callbackUrl", "scope"] as const) {
+ const text = template.oauth[key];
+ if (text !== undefined && !dropped(text)) oauth[key] = fill(text, key === "clientSecret");
+ }
+ if (template.oauth.callbackPort !== undefined) oauth.callbackPort = template.oauth.callbackPort;
+ server.oauth = oauth;
+ }
+ return server;
+ }
+ const server: ServerTemplate = { command: fill(template.command, false) };
+ if (template.args) server.args = template.args.map((arg) => fill(arg, false));
+ const env = record(template.env);
+ if (env) server.env = env;
+ if (template.cwd !== undefined) server.cwd = fill(template.cwd, false);
+ return server;
+}
+
+/** The catalog's connectors first, then the user's own servers in the order they were added. */
+function ordered(state: ConnectorsState): [string, SavedConnector][] {
+ const entries = Object.entries(state.connectors);
+ return [
+ ...CATALOG.flatMap((entry) => entries.filter(([id]) => id === entry.id)),
+ ...entries.filter(([id, saved]) => !catalogEntry(id) && saved.custom),
+ ];
}
/**
* The engine's `mcp.json` for the added connectors. The assistant turns codemode off, so every
* server is `direct`. Read only hides every tool (`*`) except the curated ones (exact names win
- * over patterns in the engine), so a tool the catalog does not know stays hidden.
+ * over patterns in the engine), so a tool the catalog does not know stays hidden; a server of the
+ * user's own has no curated list, so all of its tools are hidden. A connector that still waits for
+ * a value the user types is left out.
*/
export function renderMcpJson(state: ConnectorsState): string {
const servers: Record<string, unknown> = {};
- for (const entry of CATALOG) {
- const saved = state.connectors[entry.id];
- if (!saved) continue;
- servers[entry.id] = {
- url: entry.url,
+ for (const [id, saved] of ordered(state)) {
+ const spec = specOf(id, saved);
+ const server = spec && fillServer(spec.server, spec.fields, saved.values ?? {});
+ if (!spec || !server) continue;
+ servers[id] = {
+ ...server,
exposure: "direct",
...(saved.mode === "read_only"
? {
toolExposure: {
"*": "hidden",
- ...Object.fromEntries(entry.readOnlyTools.map((tool) => [tool, "direct"])),
+ ...Object.fromEntries(spec.readOnlyTools.map((tool) => [tool, "direct"])),
},
}
: {}),
@@ -261,9 +582,9 @@ export class ConnectorStore {
policy(): ConnectorPolicy {
const connectors: NonNullable<ConnectorPolicy["connectors"]> = {};
for (const [id, saved] of Object.entries(this.state().connectors)) {
- const entry = catalogEntry(id);
- if (entry && saved.enabled)
- connectors[id] = { name: entry.name, mode: saved.mode, readOnlyTools: [...entry.readOnlyTools] };
+ const spec = specOf(id, saved);
+ if (spec && saved.enabled)
+ connectors[id] = { name: spec.name, mode: saved.mode, readOnlyTools: [...spec.readOnlyTools] };
}
return {
connectors,
@@ -281,17 +602,21 @@ export class ConnectorStore {
}
/**
- * True when the engine stored tokens for the connector (key `mcp__<id>|<url>`). Token values
- * are dropped while parsing, so they are never kept or passed on.
+ * True when the engine stored tokens for the connector (key `mcp__<server>|<url>`, `-` as `_`).
+ * Token values are dropped while parsing, so they are never kept or passed on.
*/
isSignedIn(id: string): boolean {
- const entry = catalogEntry(id);
- if (!entry || !existsSync(this.authFile)) return false;
+ const saved = this.saved.connectors[id];
+ const spec = specOf(id, saved);
+ const server = spec && fillServer(spec.server, spec.fields, saved?.values ?? {});
+ if (!server || !("url" in server) || !URL.canParse(server.url) || !existsSync(this.authFile))
+ return false;
try {
const states = JSON.parse(readFileSync(this.authFile, "utf8"), (key, value) =>
key === "tokens" && typeof value === "object" && value !== null ? {} : value,
) as Record<string, { tokens?: unknown } | undefined>;
- return typeof states[`mcp__${id}|${new URL(entry.url).href}`]?.tokens === "object";
+ const key = `mcp__${id.replace(/-/g, "_")}|${new URL(server.url).href}`;
+ return typeof states[key]?.tokens === "object";
} catch {
return false;
}
@@ -342,15 +667,20 @@ export class ConnectorStore {
private load(): ConnectorsState {
try {
const saved = JSON.parse(readFileSync(this.file, "utf8")) as {
- connectors?: Record<string, { enabled?: unknown; mode?: unknown }>;
+ connectors?: Record<string, Record<string, unknown> | undefined>;
};
const connectors: ConnectorsState["connectors"] = {};
for (const [id, value] of Object.entries(saved.connectors ?? {})) {
- if (!catalogEntry(id)) continue;
- connectors[id] = {
+ const custom = catalogEntry(id) ? undefined : parseCustom(value?.custom);
+ if (!catalogEntry(id) && !custom) continue;
+ const entry: SavedConnector = {
enabled: value?.enabled === true,
mode: value?.mode === "read_write" ? "read_write" : "read_only",
};
+ const values = stringRecord(value?.values);
+ if (values) entry.values = values;
+ if (custom) entry.custom = custom;
+ connectors[id] = entry;
}
return { connectors };
} catch {
@@ -359,6 +689,34 @@ export class ConnectorStore {
}
}
+function stringRecord(value: unknown): Record<string, string> | undefined {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
+ const entries = Object.entries(value).filter(
+ (entry): entry is [string, string] => typeof entry[1] === "string",
+ );
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
+}
+
+/** A saved server of the user's own, or undefined when anything is malformed. */
+function parseCustom(value: unknown): CustomConnector | undefined {
+ if (typeof value !== "object" || value === null) return undefined;
+ const custom = value as Partial<CustomConnector>;
+ if (typeof custom.name !== "string" || typeof custom.origin !== "string") return undefined;
+ const server = custom.server as Record<string, unknown> | undefined;
+ if (typeof server?.url !== "string" && typeof server?.command !== "string") return undefined;
+ const fields = Array.isArray(custom.fields)
+ ? custom.fields.filter((f): f is SetupField => typeof f?.key === "string" && typeof f.label === "string")
+ : [];
+ return {
+ name: custom.name,
+ description: typeof custom.description === "string" ? custom.description : "",
+ origin: custom.origin,
+ server: server as ServerTemplate,
+ fields,
+ oauth: custom.oauth === true,
+ };
+}
+
function lstatOrUndefined(path: string) {
try {
return lstatSync(path);
@@ -390,7 +748,13 @@ export const APPROVAL_GUARD = fileURLToPath(new URL("./extensions/approval-guard
/** Why a connector action did not start; `message` is safe to show. */
export type ConnectorRefusal = {
- code: "connector_busy" | "unknown_connector" | "connector_not_added";
+ code:
+ | "connector_busy"
+ | "unknown_connector"
+ | "connector_not_added"
+ | "connector_no_setup"
+ | "connector_no_signin"
+ | "draft_not_found";
message: string;
};
@@ -398,6 +762,9 @@ const REFUSALS = {
busy: { code: "connector_busy", message: "Another sign-in is in progress. Finish or cancel it first." },
unknown: { code: "unknown_connector", message: "That connector is not available." },
notAdded: { code: "connector_not_added", message: "Connect that service first." },
+ noSetup: { code: "connector_no_setup", message: "That connector has nothing to set up." },
+ noSignin: { code: "connector_no_signin", message: "That connector does not use a sign-in." },
+ noDraft: { code: "draft_not_found", message: "That draft is no longer waiting." },
} as const satisfies Record<string, ConnectorRefusal>;
type Emit = (payload: ServerPayload) => void;
@@ -416,8 +783,24 @@ interface Flow {
output: string;
}
+/** The values a connector needs, asked one at a time in the window that started it. */
+interface Setup {
+ id: string;
+ connectorId: string;
+ owner: object;
+ emit: Emit;
+ fields: readonly SetupField[];
+ values: Record<string, string>;
+ finish: (values: Record<string, string>) => void;
+}
+
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;
@@ -425,14 +808,19 @@ export interface ConnectorManagerOptions {
/** The engine's environment (its own HOME, XDG folders, and memory settings). */
env: NodeJS.ProcessEnv;
cwd: string;
+ /** The home folder "Import my MCP servers" scans; default the user's. */
+ importHome?: string;
log?: (line: string) => void;
}
/**
- * Connects, signs in, changes, and removes connectors. Sign-in runs the engine's own
- * `mcp login <server>` as a separate process (one at a time; its loopback callback port is
- * shared), relays the authorization URL, and can finish with an address the user pastes when
- * the browser could not reach this computer. Nothing typed or printed is logged.
+ * Connects, sets up, signs in, changes, and removes connectors. Values the user types (a bot token,
+ * an OAuth client) are asked one at a time with sign-in prompts, kept in the assistant's private
+ * state, and never logged or sent back. Sign-in runs the engine's own `mcp login <server>` as a
+ * separate process (one at a time; its loopback callback port is shared), relays the authorization
+ * URL, and can finish with an address the user pastes when the browser could not reach this
+ * computer. Drafts from the assistant and servers found in other apps are added only when the user
+ * says so, read only, with every tool hidden. Nothing typed or printed is logged.
*/
export class ConnectorManager {
/** `restart`: the engine must restart (when idle) to read the new `mcp.json`. */
@@ -440,7 +828,10 @@ export class ConnectorManager {
/** A change to the connector files made outside the Connectors screen was put back. */
onBlocked: () => void = () => {};
private flow: Flow | undefined;
+ private setupFlow: Setup | undefined;
private readonly failed = new Set<string>();
+ private readonly waiting = new Map<string, ConnectorDraft>();
+ private scanned = new Map<string, ScannedServer>();
private readonly options: ConnectorManagerOptions;
constructor(options: ConnectorManagerOptions) {
@@ -459,52 +850,88 @@ export class ConnectorManager {
list(): ConnectorInfo[] {
const { connectors } = this.options.store.state();
- return CATALOG.map((entry) => {
- const saved = connectors[entry.id];
- const status = !saved?.enabled
- ? "off"
- : this.failed.has(entry.id)
- ? "error"
- : this.options.store.isSignedIn(entry.id)
- ? "connected"
- : "needs_signin";
- return {
- id: entry.id,
- name: entry.name,
- reads: entry.reads,
- sends: entry.sends,
+ const ids = [
+ ...CATALOG.map((entry) => entry.id),
+ ...ordered({ connectors })
+ .map(([id]) => id)
+ .filter((id) => !catalogEntry(id)),
+ ];
+ return ids.flatMap((id) => {
+ const saved = connectors[id];
+ const spec = specOf(id, saved);
+ if (!spec) return [];
+ const info: ConnectorInfo = {
+ id,
+ name: spec.name,
+ reads: spec.reads,
+ sends: spec.sends,
added: saved !== undefined,
enabled: saved?.enabled === true,
mode: saved?.mode ?? "read_only",
- status,
+ status: this.status(id, spec, saved),
};
+ if (!spec.oauth) info.noSignIn = true;
+ if (spec.guide) info.guide = spec.guide;
+ if (spec.custom) info.custom = { origin: spec.custom.origin, summary: summarize(spec.custom.server) };
+ return [info];
});
}
- /** Adds or turns on a connector, then signs in when it has no sign-in yet. */
+ /** Adds or turns on a connector: asks for the values it still needs, then signs in when it has no sign-in yet. */
connect(owner: object, id: string, emit: Emit): ConnectorRefusal | undefined {
- if (!catalogEntry(id)) return REFUSALS.unknown;
- if (this.flow) return REFUSALS.busy;
- this.options.store.update((state) => {
- state.connectors[id] = { enabled: true, mode: state.connectors[id]?.mode ?? "read_only" };
+ const saved = this.options.store.state().connectors[id];
+ const spec = specOf(id, saved);
+ if (!spec) return REFUSALS.unknown;
+ if (this.busy()) return REFUSALS.busy;
+ if (missingValues(spec, saved?.values)) {
+ // Nothing is added until every value is there.
+ this.askValues(owner, id, spec.fields, emit, (values, flowId) => {
+ this.save(id, (current) => ({ ...current, enabled: true, values }));
+ this.afterSetup(owner, id, emit, flowId);
+ });
+ return undefined;
+ }
+ this.save(id, (current) => ({ ...current, enabled: true }));
+ this.afterSetup(owner, id, emit, `connector-${randomUUID()}`);
+ return undefined;
+ }
+
+ /** Asks again for the values the user typed (a new token, another OAuth client). */
+ setup(owner: object, id: string, emit: Emit): ConnectorRefusal | undefined {
+ const saved = this.options.store.state().connectors[id];
+ const spec = specOf(id, saved);
+ if (!spec) return REFUSALS.unknown;
+ if (!saved) return REFUSALS.notAdded;
+ if (spec.fields.length === 0) return REFUSALS.noSetup;
+ if (this.busy()) return REFUSALS.busy;
+ this.askValues(owner, id, spec.fields, emit, (values, flowId) => {
+ this.save(id, (current) => ({ ...current, values }));
+ this.afterSetup(owner, id, emit, flowId);
});
- this.onChanged(true);
- if (!this.options.store.isSignedIn(id)) this.startLogin(owner, id, emit);
- // Already signed in: the window that asked is told it is done.
- else emit({ type: "auth_done", flowId: `connector-${randomUUID()}`, providerId: id, ok: true });
return undefined;
}
signIn(owner: object, id: string, emit: Emit): ConnectorRefusal | undefined {
- if (!catalogEntry(id)) return REFUSALS.unknown;
- if (this.flow) return REFUSALS.busy;
- if (!this.options.store.state().connectors[id]) return REFUSALS.notAdded;
+ const saved = this.options.store.state().connectors[id];
+ const spec = specOf(id, saved);
+ if (!spec) return REFUSALS.unknown;
+ if (this.busy()) return REFUSALS.busy;
+ if (!saved) return REFUSALS.notAdded;
+ if (!spec.oauth) return REFUSALS.noSignin;
this.startLogin(owner, id, emit);
return undefined;
}
- /** Answers the flow `owner` started: a pasted address, or a cancellation. */
+ /** Answers the flow `owner` started: a typed value, a pasted address, or a cancellation. */
reply(owner: object, flowId: string, answer: { value?: string; cancelled?: boolean }): boolean {
+ const setup = this.setupFlow;
+ if (setup && setup.id === flowId) {
+ if (setup.owner !== owner) return false;
+ if (answer.cancelled) this.cancelSetup(setup);
+ else if (answer.value !== undefined) this.takeValue(setup, answer.value);
+ else return false;
+ return true;
+ }
const flow = this.flow;
if (!flow || flow.id !== flowId || flow.owner !== owner) return false;
if (answer.cancelled) {
@@ -522,10 +949,12 @@ export class ConnectorManager {
/** A window that goes away takes its sign-in with it. */
cancelOwnedBy(owner: object): void {
+ if (this.setupFlow?.owner === owner) this.cancelSetup(this.setupFlow);
if (this.flow?.owner === owner) this.cancel(this.flow);
}
cancelAll(): void {
+ if (this.setupFlow) this.cancelSetup(this.setupFlow);
if (this.flow) this.cancel(this.flow);
}
@@ -540,15 +969,20 @@ export class ConnectorManager {
/** Signs out (`mcp logout`, which needs the server still configured), then forgets the connector. */
async remove(id: string): Promise<ConnectorRefusal | undefined> {
- if (!catalogEntry(id)) return REFUSALS.unknown;
- if (!this.options.store.state().connectors[id]) return REFUSALS.notAdded;
+ const saved = this.options.store.state().connectors[id];
+ const spec = specOf(id, saved);
+ if (!spec) return REFUSALS.unknown;
+ if (!saved) return REFUSALS.notAdded;
if (this.flow?.connectorId === id) this.cancel(this.flow);
- const code = await new Promise<number | null>((done) => {
- const child = this.run("logout", id);
- child.on("error", () => done(-1));
- child.on("close", (exit) => done(exit));
- });
- if (code !== 0) this.log(`sign-out of connector ${id} failed (exit ${code})`);
+ if (this.setupFlow?.connectorId === id) this.cancelSetup(this.setupFlow);
+ if (spec.oauth) {
+ const code = await new Promise<number | null>((done) => {
+ const child = this.run("logout", id);
+ child.on("error", () => done(-1));
+ child.on("close", (exit) => done(exit));
+ });
+ if (code !== 0) this.log(`sign-out of connector ${id} failed (exit ${code})`);
+ }
this.failed.delete(id);
this.options.store.update((state) => {
delete state.connectors[id];
@@ -557,12 +991,259 @@ export class ConnectorManager {
return undefined;
}
+ /**
+ * A draft from `propose_connector` (the engine's status text), checked and kept for the user's
+ * answer; undefined when it is malformed. Only the newest five wait.
+ */
+ propose(text: string): ConnectorDraft | undefined {
+ 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);
+ return draft;
+ }
+
+ drafts(): ConnectorDraft[] {
+ return [...this.waiting.values()];
+ }
+
+ /**
+ * The user's answer to a draft. Declining forgets it. Approving adds the server, turned on, read
+ * only, with every tool hidden, then asks for its secrets in the window that approved it and signs
+ * in when it needs to.
+ */
+ decideDraft(owner: object, draftId: string, approve: boolean, emit: Emit): ConnectorRefusal | undefined {
+ const draft = this.waiting.get(draftId);
+ if (!draft) return REFUSALS.noDraft;
+ if (approve && this.busy()) return REFUSALS.busy;
+ this.waiting.delete(draftId);
+ if (!approve) return undefined;
+ const id = this.newId(draft.name);
+ const server: ServerTemplate =
+ draft.transport === "http"
+ ? { url: draft.url ?? "" }
+ : {
+ command: draft.command ?? "",
+ ...(draft.args?.length ? { args: draft.args } : {}),
+ ...(draft.envNames.length > 0
+ ? { env: Object.fromEntries(draft.envNames.map((name) => [name, placeholder(name)])) }
+ : {}),
+ };
+ const custom: CustomConnector = {
+ name: draft.name,
+ description: draft.description,
+ origin: DRAFT_ORIGIN,
+ server,
+ fields: draft.envNames.map((name) => ({ key: name, label: name, secret: true })),
+ oauth: draft.transport === "http" && draft.needsOAuth,
+ };
+ this.save(id, () => ({ enabled: true, mode: "read_only", custom }));
+ this.log(`added connector ${id} from the assistant's draft`);
+ if (custom.fields.length === 0) this.afterSetup(owner, id, emit, `connector-${randomUUID()}`);
+ else
+ this.askValues(owner, id, custom.fields, emit, (values, flowId) => {
+ this.save(id, (current) => ({ ...current, values }));
+ this.afterSetup(owner, id, emit, flowId);
+ });
+ return undefined;
+ }
+
+ /** Reads the other apps' configurations (only reads them) and lists what it found, without any value. */
+ scan(): ImportCandidate[] {
+ const home = this.options.importHome ?? homedir();
+ const groups = new Map<string, { candidate: ImportCandidate; server: ScannedServer }>();
+ const found = new Map<string, ScannedServer>();
+ for (const server of scanClientConfigs(home)) {
+ const key = server.server ? fingerprint(server.server) : `${server.source}:${server.name}`;
+ const group = groups.get(key);
+ if (group) {
+ if (!group.candidate.sources.includes(server.source)) group.candidate.sources.push(server.source);
+ continue;
+ }
+ const id = `${server.source}:${server.name}`;
+ const candidate = this.describeImport(id, server);
+ groups.set(key, { candidate, server });
+ found.set(id, server);
+ }
+ this.scanned = found;
+ this.log(`found ${found.size} MCP servers in other apps`);
+ return [...groups.values()].map(({ candidate }) => candidate);
+ }
+
+ /** Copies the chosen servers from the last scan, with their values, read only with every tool hidden. */
+ importServers(ids: string[]): string[] {
+ const imported: string[] = [];
+ for (const key of ids) {
+ const found = this.scanned.get(key);
+ if (!found?.server || this.duplicateOf(found.server)) continue;
+ const id = this.newId(found.name);
+ const custom: CustomConnector = {
+ name: found.name,
+ description: "",
+ origin: `Imported from ${found.source}`,
+ server: found.server,
+ fields: found.fields,
+ oauth: found.oauth,
+ };
+ this.options.store.update((state) => {
+ state.connectors[id] = { enabled: true, mode: "read_only", custom };
+ });
+ imported.push(id);
+ }
+ if (imported.length > 0) {
+ this.log(`imported ${imported.length} MCP servers: ${imported.join(", ")}`);
+ this.onChanged(true);
+ }
+ return imported;
+ }
+
+ private describeImport(id: string, server: ScannedServer): ImportCandidate {
+ const template = server.server;
+ const candidate: ImportCandidate = {
+ id,
+ name: server.name,
+ sources: [server.source],
+ transport: server.transport,
+ summary: template ? summarize(template) : "",
+ envNames: template && "command" in template ? Object.keys(template.env ?? {}) : [],
+ headerNames: template && "url" in template ? Object.keys(template.headers ?? {}) : [],
+ inputs: server.fields.map((field) => field.label),
+ importable: template !== undefined,
+ };
+ if (server.reason) candidate.reason = server.reason;
+ const duplicate = template && this.duplicateOf(template);
+ if (duplicate) {
+ candidate.importable = false;
+ candidate.duplicateOf = duplicate;
+ }
+ return candidate;
+ }
+
+ /** The connector with the same server: one the user added, or a catalog entry with a curated list. */
+ private duplicateOf(server: ServerTemplate): string | undefined {
+ const key = fingerprint(server);
+ const { connectors } = this.options.store.state();
+ for (const entry of CATALOG) if (fingerprint(entry.server) === key) return entry.id;
+ for (const [id, saved] of Object.entries(connectors))
+ if (saved.custom && fingerprint(saved.custom.server) === key) return id;
+ return undefined;
+ }
+
+ /** A connector id from a name: lowercase letters, digits, and `-`, not taken yet. */
+ private newId(name: string): string {
+ const base =
+ name
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 32)
+ .replace(/-+$/, "") || "server";
+ const taken = (id: string) =>
+ catalogEntry(id) !== undefined || id in this.options.store.state().connectors;
+ if (!taken(base)) return base;
+ for (let n = 2; ; n++) if (!taken(`${base}-${n}`)) return `${base}-${n}`;
+ }
+
+ private status(
+ id: string,
+ spec: ConnectorSpec,
+ saved: SavedConnector | undefined,
+ ): ConnectorInfo["status"] {
+ if (!saved?.enabled) return "off";
+ if (missingValues(spec, saved.values)) return "needs_setup";
+ if (this.failed.has(id)) return "error";
+ if (spec.oauth && !this.options.store.isSignedIn(id)) return "needs_signin";
+ return "connected";
+ }
+
+ private busy(): boolean {
+ return this.flow !== undefined || this.setupFlow !== undefined;
+ }
+
+ /** Changes one connector, keeping what is not changed, then has the engine read it again. */
+ private save(id: string, update: (current: SavedConnector) => SavedConnector): void {
+ this.options.store.update((state) => {
+ state.connectors[id] = update(state.connectors[id] ?? { enabled: false, mode: "read_only" });
+ });
+ this.onChanged(true);
+ }
+
+ /** After the values are there: sign in when the connector needs it, otherwise it is done. */
+ private afterSetup(owner: object, id: string, emit: Emit, flowId: string): void {
+ const spec = specOf(id, this.options.store.state().connectors[id]);
+ if (spec?.oauth && !this.options.store.isSignedIn(id)) this.startLogin(owner, id, emit, flowId);
+ // Already signed in, or nothing to sign in to: the window that asked is told it is done.
+ else emit({ type: "auth_done", flowId, providerId: id, ok: true });
+ }
+
+ private askValues(
+ owner: object,
+ connectorId: string,
+ fields: readonly SetupField[],
+ emit: Emit,
+ finish: (values: Record<string, string>, flowId: string) => void,
+ ): void {
+ const id = `connector-setup-${randomUUID()}`;
+ this.setupFlow = {
+ id,
+ connectorId,
+ owner,
+ emit,
+ fields,
+ values: {},
+ finish: (values) => finish(values, id),
+ };
+ this.askNext(this.setupFlow);
+ }
+
+ private askNext(setup: Setup, again = false): void {
+ const field = setup.fields[Object.keys(setup.values).length];
+ if (!field) return;
+ setup.emit({
+ type: "auth_prompt",
+ prompt: {
+ flowId: setup.id,
+ kind: field.secret ? "secret" : "text",
+ message: again ? `${field.label} is needed to continue.` : field.label,
+ ...(field.optional ? { optional: true } : {}),
+ },
+ });
+ }
+
+ private takeValue(setup: Setup, typed: string): void {
+ const field = setup.fields[Object.keys(setup.values).length];
+ if (!field) return;
+ const value = typed.trim();
+ if (!value && !field.optional) {
+ this.askNext(setup, true);
+ return;
+ }
+ setup.values[field.key] = value;
+ if (Object.keys(setup.values).length < setup.fields.length) {
+ this.askNext(setup);
+ return;
+ }
+ this.setupFlow = undefined;
+ setup.finish(setup.values);
+ }
+
+ private cancelSetup(setup: Setup): void {
+ if (this.setupFlow === setup) this.setupFlow = undefined;
+ setup.emit({
+ type: "auth_done",
+ flowId: setup.id,
+ providerId: setup.connectorId,
+ ok: false,
+ message: "Setup cancelled.",
+ });
+ }
+
private change(
id: string,
- update: (saved: ConnectorsState["connectors"][string]) => ConnectorsState["connectors"][string],
+ update: (saved: SavedConnector) => SavedConnector,
): ConnectorRefusal | undefined {
- if (!catalogEntry(id)) return REFUSALS.unknown;
const saved = this.options.store.state().connectors[id];
+ if (!specOf(id, saved)) return REFUSALS.unknown;
if (!saved) return REFUSALS.notAdded;
this.options.store.update((state) => {
state.connectors[id] = update(saved);
@@ -580,10 +1261,10 @@ export class ConnectorManager {
});
}
- private startLogin(owner: object, connectorId: string, emit: Emit): void {
+ private startLogin(owner: object, connectorId: string, emit: Emit, flowId?: string): void {
const child = this.run("login", connectorId);
const flow: Flow = {
- id: `connector-${randomUUID()}`,
+ id: flowId ?? `connector-${randomUUID()}`,
connectorId,
owner,
emit,
@@ -613,7 +1294,9 @@ export class ConnectorManager {
const redirect = authorization.searchParams.get("redirect_uri");
if (redirect && URL.canParse(redirect))
flow.redirect = { url: new URL(redirect), state: authorization.searchParams.get("state") };
- const name = catalogEntry(flow.connectorId)?.name ?? flow.connectorId;
+ const name =
+ specOf(flow.connectorId, this.options.store.state().connectors[flow.connectorId])?.name ??
+ flow.connectorId;
flow.emit({
type: "auth_event",
flowId: flow.id,
@@ -699,6 +1382,86 @@ export class ConnectorManager {
}
}
+/** A draft's fields, checked; undefined when anything is missing or malformed. */
+function parseDraft(text: string): ConnectorDraft | undefined {
+ let value: unknown;
+ try {
+ value = JSON.parse(text);
+ } catch {
+ return undefined;
+ }
+ if (typeof value !== "object" || value === null) 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;
+ const envNames = raw.env_names === undefined ? [] : raw.env_names;
+ if (!name || name.length > 60 || typeof description !== "string" || description.length > 500)
+ return undefined;
+ if (
+ !Array.isArray(envNames) ||
+ envNames.length > 20 ||
+ !envNames.every((n) => typeof n === "string" && ENV_NAME.test(n))
+ )
+ return undefined;
+ const base = {
+ draftId: randomUUID(),
+ name,
+ description: description.trim(),
+ envNames: [...new Set(envNames)],
+ };
+ if (raw.transport === "stdio") {
+ const { command, args = [] } = raw;
+ if (typeof command !== "string" || !command.trim() || command.length > 300) return undefined;
+ if (
+ !Array.isArray(args) ||
+ args.length > 40 ||
+ !args.every((a) => typeof a === "string" && a.length <= 500)
+ )
+ return undefined;
+ return { ...base, transport: "stdio", command, ...(args.length > 0 ? { args } : {}), needsOAuth: false };
+ }
+ if (raw.transport === "http") {
+ const url =
+ typeof raw.url === "string" && raw.url.length <= 2000 && URL.canParse(raw.url)
+ ? new URL(raw.url)
+ : undefined;
+ const loopback = url && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);
+ if (!url || !(url.protocol === "https:" || (url.protocol === "http:" && loopback))) return undefined;
+ return { ...base, transport: "http", url: raw.url as string, needsOAuth: raw.needs_oauth === true };
+ }
+ return undefined;
+}
+
+/** Compares servers by what they run or reach: an npm package's version and a URL's query do not count. */
+function fingerprint(server: ServerTemplate): string {
+ if ("url" in server) {
+ const url = URL.canParse(server.url) ? new URL(server.url) : undefined;
+ return url ? `url ${url.origin}${url.pathname.replace(/\/+$/, "")}` : `url ${server.url}`;
+ }
+ const unversioned = (arg: string) => arg.replace(/^(@?[^@\s/]+(?:\/[^@\s]+)?)@[\w.^~<>=*-]+$/, "$1");
+ 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). */
+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}`;
+ }
+ 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(" ");
+}
+
/** The guard's policy for the engine's environment; the engine cannot change its own environment. */
export function policyEnv(store: ConnectorStore): NodeJS.ProcessEnv {
return { [POLICY_ENV]: JSON.stringify(store.policy()) };
diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.ts
index 7a6a48c..f5d60da 100644
--- a/packages/daemon/src/daemon.ts
+++ b/packages/daemon/src/daemon.ts
@@ -43,6 +43,8 @@ export interface DaemonOptions {
authRuntime?: () => Promise<AuthRuntime>;
/** The engine's command line for connector sign-in; default `GENTLE_DOT_MCP_CLI` (JSON array) or the bundled one. */
connectorCli?: McpCli;
+ /** The home folder "Import my MCP servers" reads other apps' configs from; default `GENTLE_DOT_IMPORT_HOME` or the user's. */
+ importHome?: string;
/** Origins allowed to open the WebSocket, besides the daemon's own and the desktop app's. */
allowedOrigins?: string[];
backoffMs?: number[];
@@ -170,6 +172,9 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {
cli: options.connectorCli ?? mcpCliFromEnv(process.env) ?? bundledMcpCli(),
env: { ...agentEnv },
cwd: options.workspace,
+ ...((options.importHome ?? process.env.GENTLE_DOT_IMPORT_HOME)
+ ? { importHome: options.importHome ?? process.env.GENTLE_DOT_IMPORT_HOME }
+ : {}),
log,
});
const historyPage = options.historyPage ?? Number(process.env.GENTLE_DOT_HISTORY_PAGE);
diff --git a/packages/daemon/src/extensions/approval-guard.ts b/packages/daemon/src/extensions/approval-guard.ts
index 98ce3e2..6541082 100644
--- a/packages/daemon/src/extensions/approval-guard.ts
+++ b/packages/daemon/src/extensions/approval-guard.ts
@@ -21,6 +21,10 @@
* best effort, NOT a security boundary: the assistant runs as the user with a shell, so a command
* can still build a name the check does not see. The daemon keeps the connector state in memory
* and puts changed files back (docs/design.md, Connectors), and stage 2 (S25) moves tokens out of reach.
+ * The assistant may draft a new connector with `propose_connector`: the draft goes to the daemon as a
+ * status update on the engine's own output (`ctx.ui.setStatus`), which only the daemon reads, and the
+ * model hears only that the user will review it. The daemon shows the draft as a card and adds it
+ * only after the user approves; secrets are typed in the app, never in the chat.
* This file has no dependencies besides Node, so the engine loads it as is.
*/
import { realpathSync, statSync } from "node:fs";
@@ -28,6 +32,55 @@ import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
export const POLICY_ENV = "GENTLE_DOT_CONNECTOR_POLICY";
+/** The status key of a connector draft; the daemon reads it, nothing shows it. */
+export const DRAFT_STATUS_KEY = "gentle-dot:connector-draft";
+/** A draft longer than this is not sent. */
+const MAX_DRAFT = 20_000;
+
+/** `propose_connector`: a plain JSON schema (the engine accepts one), with secrets by name only. */
+export const PROPOSE_TOOL = {
+ name: "propose_connector",
+ label: "Propose a connector",
+ description:
+ "Draft a new connector (an MCP server) for the user to review in the app. Give the server's name, what it does, and either its command (stdio) or its URL (http). List the secrets it needs by environment variable name only; the app asks the user for their values. The user decides; nothing is added until they approve.",
+ promptGuidelines: [
+ "When the user wants to connect another app or service, find its MCP server (prefer the official one, with a pinned version) and call propose_connector. Never edit connector files, never run `mcp add`, and never ask for tokens or keys in the chat.",
+ ],
+ parameters: {
+ type: "object",
+ properties: {
+ name: { type: "string", description: "Short name, for example GitHub." },
+ description: { type: "string", description: "What it lets the assistant do, in plain words." },
+ transport: { type: "string", enum: ["stdio", "http"] },
+ command: { type: "string", description: "For stdio: the program, for example npx." },
+ args: { type: "array", items: { type: "string" }, description: "For stdio: its arguments." },
+ url: { type: "string", description: "For http: the server's https URL." },
+ env_names: {
+ type: "array",
+ items: { type: "string" },
+ description: "Environment variable names of the secrets it needs (no values).",
+ },
+ needs_oauth: { type: "boolean", description: "For http: the server signs in with OAuth." },
+ },
+ required: ["name", "transport"],
+ additionalProperties: false,
+ },
+} as const;
+
+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.";
+
+/** Sends a draft to the daemon; the text is all the model gets back. */
+export function proposeConnector(
+ params: unknown,
+ ctx: { hasUI: boolean; ui: { setStatus(key: string, text: string | undefined): void } },
+): string {
+ if (!ctx.hasUI) return NO_REVIEW;
+ 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);
+ return REVIEW;
+}
export type ConnectorMode = "read_only" | "read_write";
@@ -283,6 +336,15 @@ export default function approvalGuard(pi: ExtensionAPI): void {
: [];
const policy: ConnectorPolicy = parsed ?? { protectedPaths: fallback };
+ pi.registerTool({
+ ...PROPOSE_TOOL,
+ promptGuidelines: [...PROPOSE_TOOL.promptGuidelines],
+ parameters: PROPOSE_TOOL.parameters as never,
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
+ return { content: [{ type: "text", text: proposeConnector(params, ctx) }], details: {} };
+ },
+ });
+
pi.on("tool_call", async (event, ctx) => {
const annotations = event.toolName.startsWith("mcp__")
? pi.getAllTools().find((tool) => tool.name === event.toolName)?.annotations
diff --git a/packages/daemon/test/approval-guard.test.ts b/packages/daemon/test/approval-guard.test.ts
index 5ad2b39..aba0317 100644
--- a/packages/daemon/test/approval-guard.test.ts
+++ b/packages/daemon/test/approval-guard.test.ts
@@ -288,6 +288,8 @@ function fakePi(tools: { name: string; annotations?: Record<string, boolean> }[]
if (event === "tool_call") handlers.push(handler);
},
getAllTools: () => tools,
+ // The guard also registers propose_connector (connector-drafts.test.ts covers it).
+ registerTool: () => {},
},
};
}
diff --git a/packages/daemon/test/connector-draft-probe.test.ts b/packages/daemon/test/connector-draft-probe.test.ts
new file mode 100644
index 0000000..331dc5c
--- /dev/null
+++ b/packages/daemon/test/connector-draft-probe.test.ts
@@ -0,0 +1,283 @@
+// @real-agent T18b probe: the daemon's command line with the bundled engine, a stand-in model
+// (OpenAI-compatible, 127.0.0.1), a temporary HOME and data folder, a private memory server on a
+// free port, and a stand-in home with another app's MCP config. It checks that the engine offers
+// `propose_connector` and that a draft reaches the daemon as a card; that an approved draft, an
+// imported server, and a guided Discord entry (dummy token, left off so nothing reaches Discord or
+// npm) render into an mcp.json the engine accepts (`mcp list --json`); and that the new servers'
+// tools stay hidden from the model in read-only mode.
+// Opt-in (it installs the engine's companion packages on the first start and needs `engram` and `lsof`):
+// GENTLE_DOT_T18B_PROBE=1 npx vitest run packages/daemon/test/connector-draft-probe.test.ts
+import { type ChildProcess, execFileSync, spawn, spawnSync } from "node:child_process";
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { createServer as createHttpServer } from "node:http";
+import { createServer } from "node:net";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import type { ServerMessage } from "@gentle-dot/protocol";
+import { describe, expect, it } from "vitest";
+import WebSocket from "ws";
+import { bundledMcpCli } from "../src/connectors.ts";
+import { tempDir, waitFor } from "./helpers.ts";
+
+const CLI = fileURLToPath(new URL("../src/cli.ts", import.meta.url));
+const FAKE_SERVER = fileURLToPath(new URL("./fixtures/fake-mcp-server.ts", import.meta.url));
+const enabled = process.env.GENTLE_DOT_T18B_PROBE === "1";
+
+type Rec = Record<string, unknown>;
+
+function freePort(): Promise<number> {
+ return new Promise((resolve) => {
+ const server = createServer();
+ server.listen(0, "127.0.0.1", () => {
+ const { port } = server.address() as { port: number };
+ server.close(() => resolve(port));
+ });
+ });
+}
+
+/** The stand-in model: "propose" calls propose_connector when it is offered; anything else answers. */
+function fakeModel(toolLists: string[][]) {
+ return createHttpServer((req, res) => {
+ let body = "";
+ req.on("data", (chunk: Buffer) => {
+ body += chunk.toString("utf8");
+ });
+ req.on("end", () => {
+ const request = JSON.parse(body) as {
+ tools?: { function?: { name?: string } }[];
+ messages?: { role: string; content?: unknown }[];
+ };
+ const tools = (request.tools ?? []).map((tool) => tool.function?.name ?? "");
+ toolLists.push(tools);
+ const last = request.messages?.at(-1);
+ const text = typeof last?.content === "string" ? last.content : JSON.stringify(last?.content ?? "");
+ res.writeHead(200, { "Content-Type": "text/event-stream" });
+ const chunk = (delta: Rec, finish: string | null) =>
+ res.write(
+ `data: ${JSON.stringify({ id: "c", object: "chat.completion.chunk", created: 0, model: "fake-model", choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`,
+ );
+ if (last?.role === "user" && text.includes("propose") && tools.includes("propose_connector")) {
+ const args = {
+ name: "Probe Tools",
+ description: "A stand-in server for the probe.",
+ transport: "stdio",
+ command: process.execPath,
+ args: [FAKE_SERVER, "--drafted"],
+ };
+ chunk(
+ {
+ role: "assistant",
+ tool_calls: [
+ {
+ index: 0,
+ id: "call_propose",
+ type: "function",
+ function: { name: "propose_connector", arguments: JSON.stringify(args) },
+ },
+ ],
+ },
+ null,
+ );
+ chunk({}, "tool_calls");
+ } else {
+ const reply = last?.role === "tool" ? `Tool said: ${text.slice(0, 200)}` : "Okay.";
+ chunk({ role: "assistant", content: reply }, null);
+ chunk({}, "stop");
+ }
+ res.end("data: [DONE]\n\n");
+ });
+ });
+}
+
+function listener(port: number): number | undefined {
+ try {
+ const pid = execFileSync("lsof", ["-t", "-n", "-P", `-iTCP:${port}`, "-sTCP:LISTEN"])
+ .toString()
+ .trim();
+ return /^\d+$/.test(pid) ? Number(pid) : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+describe.skipIf(!enabled)("@real-agent T18b connector probe", () => {
+ it("takes a draft from the engine to a card, and the engine accepts the guided, drafted, and imported servers", {
+ timeout: 400_000,
+ }, async () => {
+ const home = tempDir();
+ const importHome = tempDir();
+ const dataDir = join(tempDir(), "data");
+ const agentHome = join(dataDir, "agent");
+ mkdirSync(agentHome, { recursive: true });
+ // Another app's config (a fixture, never the user's): one stdio server with a secret value.
+ mkdirSync(join(importHome, ".cursor"), { recursive: true });
+ writeFileSync(
+ join(importHome, ".cursor", "mcp.json"),
+ JSON.stringify({
+ mcpServers: {
+ imported: {
+ command: process.execPath,
+ args: [FAKE_SERVER, "--imported"],
+ env: { PROBE_KEY: "pr0be-$ecret" },
+ },
+ },
+ }),
+ );
+ const toolLists: string[][] = [];
+ const model = fakeModel(toolLists);
+ const modelPort = await freePort();
+ await new Promise<void>((resolve) => model.listen(modelPort, "127.0.0.1", resolve));
+ writeFileSync(
+ join(agentHome, "models.json"),
+ JSON.stringify({
+ providers: {
+ fakeprov: {
+ baseUrl: `http://127.0.0.1:${modelPort}/v1`,
+ api: "openai-completions",
+ apiKey: "not-a-key",
+ models: [{ id: "fake-model" }],
+ },
+ },
+ }),
+ );
+ writeFileSync(
+ join(agentHome, "settings.json"),
+ JSON.stringify({ defaultProvider: "fakeprov", defaultModel: "fake-model" }),
+ );
+ // Discord set up earlier with a dummy token, and turned off.
+ writeFileSync(
+ join(dataDir, "connectors.json"),
+ JSON.stringify({
+ version: 1,
+ connectors: { discord: { enabled: false, mode: "read_only", values: { token: "dummy-token-$!x" } } },
+ }),
+ );
+ const memoryPort = await freePort();
+ const child: ChildProcess = spawn(process.execPath, [CLI], {
+ env: {
+ PATH: process.env.PATH,
+ HOME: home,
+ GENTLE_DOT_DATA_DIR: dataDir,
+ GENTLE_DOT_PORT: "0",
+ GENTLE_DOT_ENGRAM: "private",
+ GENTLE_DOT_ENGRAM_PORT: String(memoryPort),
+ GENTLE_DOT_IMPORT_HOME: importHome,
+ },
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let output = "";
+ child.stdout?.on("data", (chunk: Buffer) => {
+ output += chunk.toString();
+ });
+ child.stderr?.on("data", (chunk: Buffer) => {
+ output += chunk.toString();
+ });
+ const exited = new Promise<void>((resolve) => child.on("close", () => resolve()));
+ const messages: ServerMessage[] = [];
+ try {
+ await waitFor(() => /Gentle Dot is running|failed to start/.test(output), 300_000);
+ const port = /127\.0\.0\.1:(\d+)/.exec(output)?.[1];
+ const health = async () =>
+ ((await (await fetch(`http://127.0.0.1:${port}/health`)).json()) as { agentState: string })
+ .agentState;
+ const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`);
+ ws.on("message", (data) => messages.push(JSON.parse(String(data)) as ServerMessage));
+ await new Promise((resolve) => ws.on("open", resolve));
+ const token = readFileSync(join(dataDir, "token"), "utf8").trim();
+ ws.send(JSON.stringify({ type: "hello", token, protocol: 1 }));
+ await waitFor(() => messages.some((m) => m.type === "ready"), 10_000);
+ const settle = async () => {
+ for (;;) {
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ if ((await health().catch(() => "")) === "idle") return;
+ }
+ };
+ const find = <T extends ServerMessage["type"]>(
+ type: T,
+ where: (m: Extract<ServerMessage, { type: T }>) => boolean = () => true,
+ ) =>
+ waitFor(
+ () =>
+ messages.find(
+ (m): m is Extract<ServerMessage, { type: T }> =>
+ m.type === type && where(m as Extract<ServerMessage, { type: T }>),
+ ),
+ 120_000,
+ );
+ await settle();
+
+ ws.send(JSON.stringify({ type: "send", text: "propose a connector" }));
+ const card = await find("connector_draft");
+ await settle();
+ ws.send(JSON.stringify({ type: "connector_draft_reply", draftId: card.draft.draftId, approve: true }));
+ await find("auth_done", (m) => m.providerId === "probe-tools");
+ ws.send(JSON.stringify({ type: "connectors_scan" }));
+ const scan = await find("connector_imports");
+ const imported = scan.found.find((c) => c.name === "imported");
+ ws.send(JSON.stringify({ type: "connector_import", ids: [imported?.id ?? ""] }));
+ await find("connector_imported");
+ await settle();
+ ws.send(JSON.stringify({ type: "send", text: "which tools do you have" }));
+ await waitFor(() => messages.some((m) => m.type === "agent_state" && m.state === "thinking"), 30_000);
+ await settle();
+
+ const cli = bundledMcpCli();
+ const list = spawnSync(cli.command, [...cli.args, "mcp", "list", "--json"], {
+ cwd: join(dataDir, "workspace"),
+ env: { PATH: process.env.PATH, HOME: home, PI_CODING_AGENT_DIR: agentHome },
+ encoding: "utf8",
+ timeout: 60_000,
+ });
+ const engineList = JSON.parse(list.stdout.slice(list.stdout.indexOf("{"))) as {
+ servers: { name: string; enabled: boolean; state: string; tools: string[]; toolExposure?: Rec }[];
+ errors: string[];
+ };
+ const lastTools = toolLists.at(-1) ?? [];
+ const summary = {
+ card: card.draft,
+ imports: scan.found,
+ engineList,
+ mcpJson: JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8")),
+ toolsOfferedLast: lastTools.filter(
+ (name) => name.startsWith("mcp__") || name === "propose_connector",
+ ),
+ proposeOffered: toolLists.some((tools) => tools.includes("propose_connector")),
+ };
+ console.log(`T18b probe:\n${JSON.stringify(summary, null, 2)}`);
+ ws.close();
+ expect(summary.proposeOffered).toBe(true);
+ expect(card.draft).toMatchObject({
+ name: "Probe Tools",
+ transport: "stdio",
+ command: process.execPath,
+ });
+ expect(JSON.stringify(scan.found)).not.toContain("pr0be-$ecret");
+ expect(engineList.errors).toEqual([]);
+ const byName = Object.fromEntries(engineList.servers.map((s) => [s.name, s]));
+ expect(byName.discord).toMatchObject({ enabled: false, state: "disabled" });
+ expect(byName["probe-tools"]).toMatchObject({ enabled: true, state: "connected" });
+ expect(byName.imported).toMatchObject({ enabled: true, state: "connected" });
+ expect(byName["probe-tools"]?.tools).toContain("send_message");
+ // Read only with no curated list: the model sees none of their tools.
+ expect(lastTools.filter((name) => /^mcp__(probe_tools|imported)__/.test(name))).toEqual([]);
+ expect(summary.mcpJson.mcpServers.discord.env.DISCORD_TOKEN).not.toBe("dummy-token-$!x");
+ } finally {
+ if (child.exitCode === null) child.kill("SIGTERM");
+ await exited;
+ model.close();
+ // The private memory server: stopped by the daemon; if one is still there, stop it by PID,
+ // only after checking it serves this probe's data folder.
+ const pid = listener(memoryPort);
+ const idFile = join(dataDir, "home", ".engram", ".instance-id");
+ const expected = existsSync(idFile) ? readFileSync(idFile, "utf8").trim() : undefined;
+ const served = await fetch(`http://127.0.0.1:${memoryPort}/health`)
+ .then((r) => r.json() as Promise<{ instance_id?: string }>)
+ .catch(() => undefined);
+ if (pid && expected && served?.instance_id === expected) process.kill(pid, "SIGTERM");
+ console.log(
+ `private memory on ${memoryPort}: still listening after close: ${pid ?? "no"}; stopped by the probe: ${Boolean(pid && expected && served?.instance_id === expected)}`,
+ );
+ console.log(output.slice(-3000));
+ }
+ });
+});
diff --git a/packages/daemon/test/connector-drafts.test.ts b/packages/daemon/test/connector-drafts.test.ts
new file mode 100644
index 0000000..a4418af
--- /dev/null
+++ b/packages/daemon/test/connector-drafts.test.ts
@@ -0,0 +1,324 @@
+// 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";
+import { fileURLToPath } from "node:url";
+import type { ServerMessage, ServerPayload } from "@gentle-dot/protocol";
+import { afterEach, describe, expect, it } from "vitest";
+import WebSocket from "ws";
+import { ConnectorManager, ConnectorStore } from "../src/connectors.ts";
+import { type DotDaemon, startDaemon } from "../src/daemon.ts";
+import approvalGuard, {
+ DRAFT_STATUS_KEY,
+ decide,
+ PROPOSE_TOOL,
+ proposeConnector,
+} from "../src/extensions/approval-guard.ts";
+import { fakeAuthRuntime } from "./fake-auth-runtime.ts";
+import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";
+
+const FAKE_CLI = fileURLToPath(new URL("./fixtures/fake-mcp-cli.ts", import.meta.url));
+const SECRET = "gh-token-$top!secret";
+
+const stdioDraft = {
+ name: "GitHub",
+ description: "Read issues and pull requests in your repositories.",
+ transport: "stdio",
+ command: "npx",
+ args: ["-y", "@modelcontextprotocol/[email protected]"],
+ env_names: ["GITHUB_PERSONAL_ACCESS_TOKEN"],
+};
+
+describe("propose_connector in the approval guard", () => {
+ it("hands the draft to the app and tells the model only that the user will review it", async () => {
+ const statuses: [string, string | undefined][] = [];
+ const ui = { setStatus: (key: string, text: string | undefined) => statuses.push([key, text]) };
+ const text = proposeConnector(stdioDraft, { hasUI: true, ui });
+ expect(statuses).toEqual([[DRAFT_STATUS_KEY, JSON.stringify(stdioDraft)]]);
+ expect(text).toMatch(/the user will review/i);
+ expect(text).not.toContain("npx");
+ expect(proposeConnector(stdioDraft, { hasUI: false, ui })).toMatch(/no one can review/i);
+ expect(statuses).toHaveLength(1);
+ });
+
+ it("registers the tool with a schema of names only, and its result carries no draft details", async () => {
+ const tools: { name: string; parameters: unknown; execute: (...args: unknown[]) => Promise<unknown> }[] =
+ [];
+ const pi = {
+ on: () => {},
+ registerTool: (tool: (typeof tools)[number]) => tools.push(tool),
+ getAllTools: () => [],
+ };
+ approvalGuard(pi as never);
+ const tool = tools.find((t) => t.name === "propose_connector");
+ expect(tool).toBeDefined();
+ expect(PROPOSE_TOOL.parameters.properties).toHaveProperty("env_names");
+ expect(PROPOSE_TOOL.parameters.properties).not.toHaveProperty("env");
+ const statuses: string[] = [];
+ const result = (await tool?.execute("call-1", stdioDraft, undefined, undefined, {
+ hasUI: true,
+ ui: { setStatus: (_key: string, text: string) => statuses.push(text) },
+ })) as { content: { type: string; text: string }[] };
+ expect(statuses).toHaveLength(1);
+ expect(JSON.stringify(result)).not.toContain("server-github");
+ expect(result.content[0]?.text).toMatch(/the user will review/i);
+ });
+
+ 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")] };
+ const cwd = tempDir();
+ expect(
+ decide({ toolName: "write", input: { path: join(agentHome, "mcp.json") }, cwd }, policy).action,
+ ).toBe("block");
+ expect(
+ decide({ toolName: "bash", input: { command: "pi mcp add github -- npx server-github" }, cwd }, policy)
+ .action,
+ ).toBe("block");
+ });
+});
+
+const managers: ConnectorManager[] = [];
+afterEach(() => {
+ for (const manager of managers.splice(0)) manager.cancelAll();
+});
+
+function setup(cliEnv: Record<string, string> = {}) {
+ const dataDir = tempDir();
+ const agentHome = join(dataDir, "agent");
+ const logs: string[] = [];
+ const store = new ConnectorStore({ dataDir, agentHome });
+ const manager = new ConnectorManager({
+ store,
+ cli: { command: process.execPath, args: [FAKE_CLI] },
+ env: { ...process.env, HOME: join(dataDir, "home"), ...cliEnv },
+ cwd: dataDir,
+ log: (line) => logs.push(line),
+ });
+ managers.push(manager);
+ const changes: boolean[] = [];
+ manager.onChanged = (restart) => changes.push(restart);
+ const owner = {};
+ const sent: ServerPayload[] = [];
+ const emit = (payload: ServerPayload) => sent.push(payload);
+ const prompts = () => sent.flatMap((m) => (m.type === "auth_prompt" ? [m.prompt] : []));
+ return { dataDir, agentHome, store, manager, changes, owner, sent, emit, prompts, logs };
+}
+
+describe("connector drafts", () => {
+ it("turns a valid draft into an approval card with every detail, and rejects malformed ones", () => {
+ const { manager } = setup();
+ const draft = manager.propose(JSON.stringify(stdioDraft));
+ expect(draft).toEqual({
+ draftId: expect.any(String),
+ name: "GitHub",
+ description: "Read issues and pull requests in your repositories.",
+ transport: "stdio",
+ command: "npx",
+ args: ["-y", "@modelcontextprotocol/[email protected]"],
+ envNames: ["GITHUB_PERSONAL_ACCESS_TOKEN"],
+ needsOAuth: false,
+ });
+ expect(manager.drafts()).toEqual([draft]);
+ expect(
+ manager.propose(
+ JSON.stringify({
+ name: "Docs",
+ transport: "http",
+ url: "https://docs.example.com/mcp",
+ needs_oauth: true,
+ }),
+ ),
+ ).toMatchObject({
+ transport: "http",
+ url: "https://docs.example.com/mcp",
+ envNames: [],
+ needsOAuth: true,
+ description: "",
+ });
+ for (const bad of [
+ "not json",
+ JSON.stringify({ ...stdioDraft, command: undefined }),
+ JSON.stringify({ ...stdioDraft, transport: "sse" }),
+ JSON.stringify({ name: "X", transport: "http", url: "file:///etc/passwd" }),
+ JSON.stringify({ name: "X", transport: "http" }),
+ JSON.stringify({ ...stdioDraft, env_names: ["BAD NAME"] }),
+ JSON.stringify({ ...stdioDraft, args: [3] }),
+ JSON.stringify({ ...stdioDraft, name: "" }),
+ JSON.stringify({ ...stdioDraft, name: "x".repeat(100) }),
+ JSON.stringify({ ...stdioDraft, env_names: Array.from({ length: 30 }, (_, i) => `K${i}`) }),
+ ]) {
+ expect(manager.propose(bad), bad.slice(0, 60)).toBeUndefined();
+ }
+ expect(manager.drafts()).toHaveLength(2);
+ });
+
+ it("changes nothing when the user declines", () => {
+ const { manager, store, owner, emit, agentHome, dataDir, changes } = setup();
+ const draft = manager.propose(JSON.stringify(stdioDraft));
+ expect(manager.decideDraft(owner, draft?.draftId ?? "", false, emit)).toBeUndefined();
+ expect(manager.drafts()).toEqual([]);
+ expect(store.state()).toEqual({ connectors: {} });
+ expect(existsSync(join(agentHome, "mcp.json"))).toBe(false);
+ expect(existsSync(join(dataDir, "connectors.json"))).toBe(false);
+ expect(changes).toEqual([]);
+ expect(manager.decideDraft(owner, draft?.draftId ?? "", true, emit)).toMatchObject({
+ code: "draft_not_found",
+ });
+ });
+
+ it("on approval asks for each secret in the app, then adds the server read only with every tool hidden", async () => {
+ const { manager, store, owner, emit, sent, prompts, agentHome, logs, changes } = setup();
+ const draft = manager.propose(JSON.stringify(stdioDraft));
+ expect(manager.decideDraft(owner, draft?.draftId ?? "", true, emit)).toBeUndefined();
+ const prompt = await waitFor(() => prompts()[0]);
+ expect(prompt).toMatchObject({ kind: "secret", flowId: expect.stringMatching(/^connector-setup-/) });
+ expect(prompt.message).toContain("GITHUB_PERSONAL_ACCESS_TOKEN");
+ manager.reply(owner, prompt.flowId, { value: SECRET });
+ const done = await waitFor(() => sent.find((m) => m.type === "auth_done"));
+ expect(done).toMatchObject({ providerId: "github", ok: true });
+ expect(changes).toContain(true);
+ const saved = store.state().connectors.github;
+ expect(saved).toMatchObject({
+ enabled: true,
+ mode: "read_only",
+ values: { GITHUB_PERSONAL_ACCESS_TOKEN: SECRET },
+ });
+ const server = JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8")).mcpServers.github;
+ expect(server).toMatchObject({
+ command: "npx",
+ args: ["-y", "@modelcontextprotocol/[email protected]"],
+ exposure: "direct",
+ toolExposure: { "*": "hidden" },
+ });
+ expect(server.env.GITHUB_PERSONAL_ACCESS_TOKEN).not.toBe(SECRET);
+ expect(store.policy().connectors?.github).toEqual({
+ name: "GitHub",
+ mode: "read_only",
+ readOnlyTools: [],
+ });
+ const info = manager.list().find((c) => c.id === "github");
+ expect(info).toMatchObject({
+ name: "GitHub",
+ added: true,
+ enabled: true,
+ mode: "read_only",
+ status: "connected",
+ custom: {
+ origin: "Drafted by the assistant",
+ summary: "npx -y @modelcontextprotocol/[email protected]",
+ },
+ });
+ expect(JSON.stringify(sent)).not.toContain(SECRET);
+ expect(JSON.stringify(manager.list())).not.toContain(SECRET);
+ expect(logs.join("\n")).not.toContain(SECRET);
+ // Read and send shows every tool, and each call asks (no curated list).
+ manager.setMode("github", "read_write");
+ expect(
+ JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8")).mcpServers.github.toolExposure,
+ ).toBeUndefined();
+ });
+
+ it("gives a draft with a taken name its own id, and signs in when it needs OAuth", async () => {
+ const { manager, store, owner, emit, sent } = setup({
+ FAKE_MCP_CLI_MODE: "auto",
+ FAKE_MCP_CLI_URL: "https://mcp.notion.com/mcp",
+ });
+ store.update((state) => {
+ state.connectors.notion = { enabled: true, mode: "read_only" };
+ });
+ const draft = manager.propose(
+ JSON.stringify({
+ name: "Notion",
+ transport: "http",
+ url: "https://mcp.notion.com/mcp",
+ needs_oauth: true,
+ }),
+ );
+ manager.decideDraft(owner, draft?.draftId ?? "", true, emit);
+ const done = await waitFor(() => sent.find((m) => m.type === "auth_done"));
+ expect(done).toMatchObject({ providerId: "notion-2", ok: true });
+ expect(Object.keys(store.state().connectors)).toEqual(["notion", "notion-2"]);
+ });
+
+ it("keeps at most five drafts waiting", () => {
+ const { manager } = setup();
+ for (let i = 0; i < 7; i++) manager.propose(JSON.stringify({ ...stdioDraft, name: `Server ${i}` }));
+ expect(manager.drafts().map((d) => d.name)).toEqual([
+ "Server 2",
+ "Server 3",
+ "Server 4",
+ "Server 5",
+ "Server 6",
+ ]);
+ });
+});
+
+const daemons: DotDaemon[] = [];
+afterEach(async () => {
+ await Promise.all(daemons.splice(0).map((d) => d.close()));
+});
+
+async function connect(d: DotDaemon) {
+ const ws = new WebSocket(`ws://127.0.0.1:${d.port}/ws`);
+ const messages: ServerMessage[] = [];
+ ws.on("message", (data) => messages.push(JSON.parse(String(data)) as ServerMessage));
+ await new Promise((resolve) => ws.on("open", resolve));
+ ws.send(JSON.stringify({ type: "hello", token: d.token, protocol: 1 }));
+ await waitFor(() => messages.some((m) => m.type === "ready"));
+ return { ws, messages, send: (m: object) => ws.send(JSON.stringify(m)) };
+}
+
+describe("connector drafts through the daemon", () => {
+ it("shows the engine's draft as a card in every window; only the user's answer adds it", async () => {
+ const dataDir = tempDir();
+ const fake = fakeAuthRuntime();
+ const d = await startDaemon({
+ port: 0,
+ host: "127.0.0.1",
+ dataDir,
+ workspace: join(dataDir, "workspace"),
+ uiDir: dataDir,
+ agentCommand: process.execPath,
+ agentArgs: [FAKE_AGENT],
+ backoffMs: [50],
+ agentHome: join(dataDir, "agent"),
+ authRuntime: async () => fake.runtime,
+ connectorCli: { command: process.execPath, args: [FAKE_CLI] },
+ importHome: tempDir(),
+ });
+ daemons.push(d);
+ const first = await connect(d);
+ first.send({ type: "send", text: `propose:${JSON.stringify({ ...stdioDraft, env_names: [] })}` });
+ const card = await waitFor(() =>
+ first.messages.find(
+ (m): m is Extract<ServerMessage, { type: "connector_draft" }> => m.type === "connector_draft",
+ ),
+ );
+ expect(card.draft).toMatchObject({ name: "GitHub", command: "npx", envNames: [] });
+ // A window that opens later sees the waiting card too.
+ const second = await connect(d);
+ await waitFor(() => second.messages.some((m) => m.type === "connector_draft"));
+ const mcpFile = join(dataDir, "agent", "mcp.json");
+ const before = existsSync(mcpFile) ? readFileSync(mcpFile, "utf8") : undefined;
+ second.send({ type: "connector_draft_reply", draftId: "nope", approve: true });
+ await waitFor(() => second.messages.some((m) => m.type === "error" && m.code === "draft_not_found"));
+ expect(existsSync(mcpFile) ? readFileSync(mcpFile, "utf8") : undefined).toBe(before);
+ second.send({ type: "connector_draft_reply", draftId: card.draft.draftId, approve: true });
+ await waitFor(() =>
+ first.messages.some((m) => m.type === "connector_draft_resolved" && m.draftId === card.draft.draftId),
+ );
+ await waitFor(() =>
+ first.messages.some(
+ (m) =>
+ m.type === "connectors" && m.connectors.some((c) => c.id === "github" && c.custom !== undefined),
+ ),
+ );
+ expect(
+ JSON.parse(readFileSync(join(dataDir, "agent", "mcp.json"), "utf8")).mcpServers.github.toolExposure,
+ ).toEqual({
+ "*": "hidden",
+ });
+ first.ws.close();
+ second.ws.close();
+ });
+});
diff --git a/packages/daemon/test/connector-import.test.ts b/packages/daemon/test/connector-import.test.ts
new file mode 100644
index 0000000..1989e7d
--- /dev/null
+++ b/packages/daemon/test/connector-import.test.ts
@@ -0,0 +1,360 @@
+// biome-ignore-all lint/suspicious/noTemplateCurlyInString: the fixtures are other apps' configs, written with their `${...}` references.
+// S20: the user's MCP servers from other apps, found read-only in a fixture home, imported on request.
+import { createHash } from "node:crypto";
+import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
+import { createRequire } from "node:module";
+import { dirname, join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import type { ImportCandidate, ServerPayload } from "@gentle-dot/protocol";
+import { afterEach, describe, expect, it } from "vitest";
+import { scanClientConfigs } from "../src/connector-import.ts";
+import { ConnectorManager, ConnectorStore } from "../src/connectors.ts";
+import { tempDir, waitFor } from "./helpers.ts";
+
+const FAKE_CLI = fileURLToPath(new URL("./fixtures/fake-mcp-cli.ts", import.meta.url));
+const SECRETS = ["ghp_desktopsecret", "sk_cursorsecret", "bar-secret-value", "lin-token-123"];
+
+function write(home: string, path: string, value: unknown) {
+ const file = join(home, path);
+ mkdirSync(dirname(file), { recursive: true });
+ writeFileSync(file, typeof value === "string" ? value : JSON.stringify(value, null, 2));
+}
+
+/** One config file per client format, as each app writes it. */
+function fixtureHome(): string {
+ const home = tempDir();
+ const github = {
+ command: "npx",
+ args: ["-y", "@modelcontextprotocol/server-github"],
+ env: { GITHUB_PERSONAL_ACCESS_TOKEN: "ghp_desktopsecret" },
+ };
+ write(home, "Library/Application Support/Claude/claude_desktop_config.json", {
+ mcpServers: {
+ filesystem: {
+ command: "npx",
+ args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/x/Docs"],
+ },
+ github,
+ },
+ });
+ write(home, ".config/Claude/claude_desktop_config.json", {
+ mcpServers: { memory: { command: "npx", args: ["-y", "@modelcontextprotocol/server-memory"] } },
+ });
+ write(home, ".claude.json", {
+ numStartups: 3,
+ mcpServers: {
+ sentry: { type: "http", url: "https://mcp.sentry.dev/mcp" },
+ legacy: { type: "sse", url: "https://old.example.com/sse" },
+ },
+ projects: {
+ [join(home, "proj")]: {
+ mcpServers: {
+ local1: { type: "stdio", command: "node", args: ["server.js"], env: { API_KEY: "${API_KEY}" } },
+ },
+ },
+ [join(home, "missing-project")]: {},
+ },
+ });
+ write(home, "proj/.mcp.json", { mcpServers: { projsrv: { command: "uvx", args: ["mcp-server-time"] } } });
+ write(home, ".cursor/mcp.json", {
+ mcpServers: {
+ linear: { url: "https://mcp.linear.app/mcp", headers: { Authorization: "Bearer lin-token-123" } },
+ stripe: {
+ url: "https://mcp.stripe.com?key=sk_cursorsecret",
+ headers: { Authorization: "Bearer sk_cursorsecret" },
+ },
+ github,
+ },
+ });
+ write(home, "Library/Application Support/Code/User/mcp.json", {
+ inputs: [
+ { type: "promptString", id: "perplexity-key", description: "Perplexity API Key", password: true },
+ ],
+ servers: {
+ perplexity: {
+ type: "stdio",
+ command: "npx",
+ args: ["-y", "server-perplexity-ask"],
+ env: { PERPLEXITY_API_KEY: "${input:perplexity-key}" },
+ },
+ copilot: {
+ type: "http",
+ url: "https://api.githubcopilot.com/mcp/",
+ headers: { Authorization: "Bearer ${env:GH_TOKEN}" },
+ },
+ },
+ });
+ write(home, ".config/Code/User/mcp.json", "{oops");
+ write(home, ".codeium/windsurf/mcp_config.json", {
+ mcpServers: {
+ figma: { serverUrl: "https://mcp.figma.com/mcp" },
+ oldsse: { serverUrl: "https://x.example.com/sse" },
+ },
+ });
+ write(home, ".config/opencode/opencode.json", {
+ $schema: "https://opencode.ai/config.json",
+ mcp: {
+ context7: {
+ type: "remote",
+ url: "https://mcp.context7.com/mcp",
+ headers: { CONTEXT7_API_KEY: "{env:CTX7}" },
+ },
+ everything: {
+ type: "local",
+ command: ["npx", "-y", "@modelcontextprotocol/server-everything", "--token", "bar-secret-value"],
+ environment: { FOO: "bar-secret-value" },
+ enabled: true,
+ },
+ },
+ });
+ write(home, ".gentle-shell/agent/mcp.json", {
+ mcpServers: { codegraph: { command: "codegraph", args: ["serve", "--mcp"], exposure: "codemode" } },
+ });
+ return home;
+}
+
+/** Every file below `home` with its hash and modification time. */
+function snapshot(home: string): Record<string, string> {
+ const out: Record<string, string> = {};
+ const walk = (dir: string) => {
+ for (const name of readdirSync(dir)) {
+ const path = join(dir, name);
+ const stat = statSync(path);
+ if (stat.isDirectory()) walk(path);
+ else out[path] = `${createHash("sha256").update(readFileSync(path)).digest("hex")}:${stat.mtimeMs}`;
+ }
+ };
+ walk(home);
+ return out;
+}
+
+async function engine() {
+ const require = createRequire(import.meta.url);
+ const load = async <T>(path: string) => {
+ const file = (require.resolve.paths("@earendil-works/pi-coding-agent") ?? [])
+ .map((dir) => join(dir, "@earendil-works", "pi-coding-agent", "dist", "core", path))
+ .find((candidate) => existsSync(candidate));
+ if (!file) throw new Error("the engine package is missing");
+ return (await import(pathToFileURL(file).href)) as T;
+ };
+ return {
+ ...(await load<{ validateMcpServerConfig(name: string, raw: unknown): unknown }>("mcp-servers.js")),
+ ...(await load<{ resolveConfigValue(config: string): string | undefined }>("resolve-config-value.js")),
+ };
+}
+
+describe("scanning other apps' MCP configs", () => {
+ it("reads every client format and maps it to the engine's schema", () => {
+ const home = fixtureHome();
+ const found = scanClientConfigs(home);
+ const byName = (name: string) => found.find((s) => s.name === name);
+ expect(found.map((s) => `${s.source}:${s.name}`).sort()).toEqual(
+ [
+ "Claude Desktop:filesystem",
+ "Claude Desktop:github",
+ "Claude Desktop:memory",
+ "Claude Code:sentry",
+ "Claude Code:legacy",
+ "Claude Code:local1",
+ "Claude Code:projsrv",
+ "Cursor:linear",
+ "Cursor:stripe",
+ "Cursor:github",
+ "VS Code:perplexity",
+ "VS Code:copilot",
+ "Windsurf:figma",
+ "Windsurf:oldsse",
+ "OpenCode:context7",
+ "OpenCode:everything",
+ "Gentle Shell:codegraph",
+ ].sort(),
+ );
+ expect(byName("filesystem")?.server).toEqual({
+ command: "npx",
+ args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/x/Docs"],
+ });
+ expect(byName("sentry")?.server).toEqual({ url: "https://mcp.sentry.dev/mcp" });
+ for (const name of ["legacy", "oldsse"]) {
+ expect(byName(name)?.server, name).toBeUndefined();
+ expect(byName(name)).toMatchObject({ transport: "sse", reason: expect.stringMatching(/SSE/) });
+ }
+ expect(byName("figma")?.server).toEqual({ url: "https://mcp.figma.com/mcp" });
+ // Claude Code's `${VAR}` and VS Code's `${env:VAR}` / OpenCode's `{env:VAR}` read the environment.
+ expect(byName("local1")?.server).toMatchObject({ env: { API_KEY: "${API_KEY}" } });
+ expect(byName("copilot")?.server).toMatchObject({ headers: { Authorization: "Bearer ${GH_TOKEN}" } });
+ expect(byName("context7")?.server).toMatchObject({ headers: { CONTEXT7_API_KEY: "${CTX7}" } });
+ expect(byName("everything")?.server).toMatchObject({
+ command: "npx",
+ args: ["-y", "@modelcontextprotocol/server-everything", "--token", "bar-secret-value"],
+ env: { FOO: "bar-secret-value" },
+ });
+ // VS Code inputs become values the user types in the app.
+ expect(byName("perplexity")?.server).toMatchObject({
+ env: { PERPLEXITY_API_KEY: "${input:perplexity-key}" },
+ });
+ expect(byName("perplexity")?.fields).toEqual([
+ { key: "perplexity-key", label: "Perplexity API Key", secret: true },
+ ]);
+ // Gentle Shell entries keep their server, not the other app's exposure.
+ expect(byName("codegraph")?.server).toEqual({ command: "codegraph", args: ["serve", "--mcp"] });
+ });
+
+ it("finds nothing in an empty home and skips files it cannot read", () => {
+ expect(scanClientConfigs(tempDir())).toEqual([]);
+ });
+});
+
+const managers: ConnectorManager[] = [];
+afterEach(() => {
+ for (const manager of managers.splice(0)) manager.cancelAll();
+});
+
+function setup(home: string) {
+ const dataDir = tempDir();
+ const agentHome = join(dataDir, "agent");
+ const logs: string[] = [];
+ const store = new ConnectorStore({ dataDir, agentHome });
+ const manager = new ConnectorManager({
+ store,
+ cli: { command: process.execPath, args: [FAKE_CLI] },
+ env: { ...process.env, HOME: join(dataDir, "home") },
+ cwd: dataDir,
+ importHome: home,
+ log: (line) => logs.push(line),
+ });
+ managers.push(manager);
+ const owner = {};
+ const sent: ServerPayload[] = [];
+ const emit = (payload: ServerPayload) => sent.push(payload);
+ return { agentHome, dataDir, store, manager, logs, owner, sent, emit };
+}
+
+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("importing MCP servers", () => {
+ it("lists what it found with the source app and names only, never values", () => {
+ const home = fixtureHome();
+ const { manager, store } = setup(home);
+ store.update((state) => {
+ state.connectors.notion = { enabled: true, mode: "read_only" };
+ });
+ const found = manager.scan();
+ const text = JSON.stringify(found);
+ for (const secret of SECRETS) expect(text).not.toContain(secret);
+ expect(pick(found, "github")).toEqual({
+ id: expect.any(String),
+ name: "github",
+ sources: ["Claude Desktop", "Cursor"],
+ transport: "stdio",
+ summary: "npx -y @modelcontextprotocol/server-github",
+ envNames: ["GITHUB_PERSONAL_ACCESS_TOKEN"],
+ headerNames: [],
+ inputs: [],
+ importable: true,
+ });
+ expect(pick(found, "stripe")).toMatchObject({
+ transport: "http",
+ summary: "https://mcp.stripe.com/",
+ headerNames: ["Authorization"],
+ });
+ expect(pick(found, "everything").summary).toBe(
+ "npx -y @modelcontextprotocol/server-everything --token •••",
+ );
+ expect(pick(found, "perplexity")).toMatchObject({
+ inputs: ["Perplexity API Key"],
+ envNames: ["PERPLEXITY_API_KEY"],
+ });
+ expect(pick(found, "legacy")).toMatchObject({
+ transport: "sse",
+ importable: false,
+ reason: expect.stringMatching(/SSE/),
+ });
+ // The catalog has Linear with a curated list, so its import is offered as a duplicate.
+ expect(pick(found, "linear")).toMatchObject({ importable: false, duplicateOf: "linear" });
+ expect(found.filter((c) => c.name === "github")).toHaveLength(1);
+ });
+
+ it("copies the chosen servers with their values into private state, read only and hidden, without touching the sources", async () => {
+ const home = fixtureHome();
+ const before = snapshot(home);
+ const { manager, store, agentHome, dataDir, logs, owner, emit, sent } = setup(home);
+ const { validateMcpServerConfig, resolveConfigValue } = await engine();
+ const found = manager.scan();
+ const chosen = ["github", "stripe", "copilot", "everything", "perplexity", "legacy", "linear"].map(
+ (name) => pick(found, name).id,
+ );
+ expect(manager.importServers(chosen).sort()).toEqual([
+ "copilot",
+ "everything",
+ "github",
+ "perplexity",
+ "stripe",
+ ]);
+ const mcp = JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8")).mcpServers as Record<
+ string,
+ Record<string, unknown>
+ >;
+ for (const [name, config] of Object.entries(mcp)) {
+ expect(typeof validateMcpServerConfig(name, config), name).toBe("object");
+ expect(config.toolExposure, name).toEqual({ "*": "hidden" });
+ }
+ expect(
+ resolveConfigValue(
+ (mcp.github?.env as Record<string, string> | undefined)?.GITHUB_PERSONAL_ACCESS_TOKEN ?? "",
+ ),
+ ).toBe("ghp_desktopsecret");
+ expect(
+ resolveConfigValue((mcp.stripe?.headers as Record<string, string> | undefined)?.Authorization ?? ""),
+ ).toBe("Bearer sk_cursorsecret");
+ expect((mcp.copilot?.headers as Record<string, string> | undefined)?.Authorization).toBe(
+ "Bearer ${GH_TOKEN}",
+ );
+ // A server that still needs a typed value waits for it.
+ expect(mcp.perplexity).toBeUndefined();
+ const list = manager.list();
+ expect(list.find((c) => c.id === "perplexity")).toMatchObject({
+ status: "needs_setup",
+ mode: "read_only",
+ });
+ expect(list.find((c) => c.id === "github")).toMatchObject({
+ status: "connected",
+ enabled: true,
+ mode: "read_only",
+ custom: {
+ origin: "Imported from Claude Desktop",
+ summary: "npx -y @modelcontextprotocol/server-github",
+ },
+ });
+ expect(store.policy().connectors?.github?.readOnlyTools).toEqual([]);
+ // The import itself is never shown or logged with its values.
+ for (const secret of SECRETS) {
+ expect(JSON.stringify(list)).not.toContain(secret);
+ expect(logs.join("\n")).not.toContain(secret);
+ }
+ expect(readFileSync(join(dataDir, "connectors.json"), "utf8")).toContain("ghp_desktopsecret");
+ // The VS Code input is typed in the app.
+ expect(manager.setup(owner, "perplexity", emit)).toBeUndefined();
+ const prompt = await waitFor(() => sent.flatMap((m) => (m.type === "auth_prompt" ? [m.prompt] : []))[0]);
+ expect(prompt).toMatchObject({ kind: "secret", message: expect.stringContaining("Perplexity API Key") });
+ manager.reply(owner, prompt.flowId, { value: "pplx-typed" });
+ await waitFor(() => sent.find((m) => m.type === "auth_done"));
+ const perplexity = JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8")).mcpServers.perplexity;
+ expect(resolveConfigValue(perplexity.env.PERPLEXITY_API_KEY)).toBe("pplx-typed");
+ expect(JSON.stringify(sent)).not.toContain("pplx-typed");
+ // Importing again adds nothing: they are already connectors.
+ const again = manager.scan();
+ expect(pick(again, "github")).toMatchObject({ importable: false, duplicateOf: "github" });
+ expect(manager.importServers([pick(again, "github").id, "unknown:id"])).toEqual([]);
+ expect(snapshot(home)).toEqual(before);
+ });
+
+ it("imports nothing before a scan", () => {
+ const { manager, store } = setup(fixtureHome());
+ expect(manager.importServers(["Cursor:github"])).toEqual([]);
+ expect(store.state()).toEqual({ connectors: {} });
+ });
+});
diff --git a/packages/daemon/test/connectors-gateway.test.ts b/packages/daemon/test/connectors-gateway.test.ts
index 8fc3a11..2dd75c1 100644
--- a/packages/daemon/test/connectors-gateway.test.ts
+++ b/packages/daemon/test/connectors-gateway.test.ts
@@ -89,10 +89,13 @@ describe("connectors over the protocol", () => {
["notion", "off"],
["linear", "off"],
["atlassian", "off"],
+ ["discord", "off"],
+ ["slack", "off"],
+ ["gmail", "off"],
]);
expect(list.open).toBeUndefined();
send({ type: "send", text: "/connectors" });
- expect((await find("connectors", (m) => m.open === true)).connectors).toHaveLength(3);
+ expect((await find("connectors", (m) => m.open === true)).connectors).toHaveLength(6);
expect(messages.some((m) => m.type === "user_message")).toBe(false);
});
@@ -133,7 +136,7 @@ describe("connectors over the protocol", () => {
const prompt = await find("auth_prompt");
send({ type: "auth_reply", flowId: prompt.prompt.flowId, cancelled: true });
expect(await find("auth_done")).toMatchObject({ ok: false, message: "Sign-in cancelled." });
- send({ type: "connector_signin", connectorId: "gmail" });
+ send({ type: "connector_signin", connectorId: "nope" });
expect(await find("error", (m) => m.code === "unknown_connector")).toBeTruthy();
});
diff --git a/packages/daemon/test/connectors-guided.test.ts b/packages/daemon/test/connectors-guided.test.ts
new file mode 100644
index 0000000..0bb88b0
--- /dev/null
+++ b/packages/daemon/test/connectors-guided.test.ts
@@ -0,0 +1,287 @@
+// biome-ignore-all lint/suspicious/noTemplateCurlyInString: `${input:<key>}` is the placeholder the catalog uses.
+// Guided connectors (S18, L36): Discord with a bot token, Slack and Gmail with the user's own OAuth app.
+import { existsSync, readFileSync } from "node:fs";
+import { createRequire } from "node:module";
+import { join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import type { ServerPayload } from "@gentle-dot/protocol";
+import { afterEach, describe, expect, it } from "vitest";
+import { CATALOG, ConnectorManager, ConnectorStore, renderMcpJson } from "../src/connectors.ts";
+import { tempDir, waitFor } from "./helpers.ts";
+
+const FAKE_CLI = fileURLToPath(new URL("./fixtures/fake-mcp-cli.ts", import.meta.url));
+const TOKEN = "discord-bot-token-$ecret!value";
+const CLIENT_SECRET = "slack-client-secret-value";
+
+/** A module of the engine package, loaded by file path (the package exports only its entry). */
+async function engineModule<T>(path: string): Promise<T> {
+ const require = createRequire(import.meta.url);
+ const file = (require.resolve.paths("@earendil-works/pi-coding-agent") ?? [])
+ .map((dir) => join(dir, "@earendil-works", "pi-coding-agent", "dist", ...path.split("/")))
+ .find((candidate) => existsSync(candidate));
+ if (!file) throw new Error("the engine package is missing");
+ return (await import(pathToFileURL(file).href)) as T;
+}
+
+const engine = () =>
+ Promise.all([
+ engineModule<{
+ validateMcpServerConfig(name: string, raw: unknown): unknown;
+ getMcpToolExposure(config: unknown, tool: string): string;
+ }>("core/mcp-servers.js"),
+ engineModule<{ resolveConfigValue(config: string): string | undefined }>("core/resolve-config-value.js"),
+ ]);
+
+const entry = (id: string) => {
+ const found = CATALOG.find((e) => e.id === id);
+ if (!found) throw new Error(`${id} is not in the catalog`);
+ return found;
+};
+
+describe("guided catalog entries", () => {
+ it("adds Discord, Slack, and Gmail after the one-click servers, each with a guide", () => {
+ expect(CATALOG.map((e) => e.id)).toEqual(["notion", "linear", "atlassian", "discord", "slack", "gmail"]);
+ for (const id of ["discord", "slack", "gmail"]) {
+ const guided = entry(id);
+ expect(guided.guide?.steps.length, id).toBeGreaterThanOrEqual(4);
+ expect(guided.guide?.links.length, id).toBeGreaterThan(0);
+ for (const link of guided.guide?.links ?? []) expect(link.url).toMatch(/^https:\/\//);
+ expect(guided.fields?.length, id).toBeGreaterThan(0);
+ expect(guided.readOnlyTools.length, id).toBeGreaterThan(3);
+ for (const tool of guided.readOnlyTools)
+ expect(tool).not.toMatch(/create|update|edit|delete|send|add|move|_label_|unlabel|ban_|kick/i);
+ }
+ });
+
+ it("runs Discord's community server at an exact version, with the bot token from a secret field", () => {
+ const discord = entry("discord");
+ expect(discord.server).toEqual({
+ command: "npx",
+ args: ["-y", "@pasympa/[email protected]"],
+ env: { DISCORD_TOKEN: "${input:token}" },
+ });
+ expect(discord.fields).toEqual([expect.objectContaining({ key: "token", secret: true })]);
+ expect(discord.oauth).toBe(false);
+ expect(discord.guide?.steps.join(" ")).toMatch(/Message Content Intent/);
+ expect(discord.readOnlyTools).toContain("discord_read_messages");
+ });
+
+ it("signs in to Slack and Gmail with the user's own app on a fixed loopback redirect", () => {
+ const slack = entry("slack");
+ expect(slack.server).toEqual({
+ url: "https://mcp.slack.com/mcp",
+ oauth: {
+ clientId: "${input:client_id}",
+ clientSecret: "${input:client_secret}",
+ callbackUrl: "http://localhost:38417/callback",
+ },
+ });
+ expect(slack.fields?.map(({ key, secret, optional }) => ({ key, secret, optional }))).toEqual([
+ { key: "client_id", secret: false, optional: undefined },
+ { key: "client_secret", secret: true, optional: true },
+ ]);
+ expect(slack.guide?.redirectUrl).toBe("http://localhost:38417/callback");
+ expect(slack.guide?.steps.join(" ")).toMatch(/PKCE/);
+ const gmail = entry("gmail");
+ expect(gmail.server).toEqual({
+ url: "https://gmailmcp.googleapis.com/mcp/v1",
+ oauth: {
+ clientId: "${input:client_id}",
+ clientSecret: "${input:client_secret}",
+ callbackUrl: "http://localhost:38418/callback",
+ scope: "https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/gmail.compose",
+ },
+ });
+ expect(gmail.fields?.map((f) => [f.key, f.secret, f.optional ?? false])).toEqual([
+ ["client_id", false, false],
+ ["client_secret", true, false],
+ ]);
+ expect(gmail.guide?.redirectUrl).toBe("http://localhost:38418/callback");
+ expect(gmail.guide?.note).toMatch(/7 days/);
+ expect(gmail.guide?.note).toMatch(/Developer Preview/);
+ expect(slack.oauth && gmail.oauth).toBe(true);
+ });
+});
+
+describe("guided mcp.json rendering", () => {
+ it("puts typed values in as literals the engine does not run or expand, and hides unknown tools", async () => {
+ const [{ validateMcpServerConfig, getMcpToolExposure }, { resolveConfigValue }] = await engine();
+ const rendered = JSON.parse(
+ renderMcpJson({
+ connectors: {
+ discord: { enabled: true, mode: "read_only", values: { token: TOKEN } },
+ slack: { enabled: true, mode: "read_write", values: { client_id: "123.456", client_secret: "" } },
+ gmail: {
+ enabled: false,
+ mode: "read_only",
+ values: { client_id: "g-id.apps.googleusercontent.com", client_secret: "!echo pwned" },
+ },
+ },
+ }),
+ ) as { mcpServers: Record<string, Record<string, unknown>> };
+ const { discord, slack, gmail } = rendered.mcpServers;
+ for (const [name, config] of Object.entries(rendered.mcpServers))
+ expect(typeof validateMcpServerConfig(name, config), name).toBe("object");
+ expect(discord).toMatchObject({
+ command: "npx",
+ args: ["-y", "@pasympa/[email protected]"],
+ exposure: "direct",
+ });
+ const token = (discord?.env as Record<string, string> | undefined)?.DISCORD_TOKEN ?? "";
+ expect(token).not.toBe(TOKEN);
+ expect(resolveConfigValue(token)).toBe(TOKEN);
+ expect(getMcpToolExposure(discord, "discord_read_messages")).toBe("direct");
+ expect(getMcpToolExposure(discord, "discord_send_message")).toBe("hidden");
+ // An optional value left empty is left out; the client id is used as is.
+ expect(slack?.oauth).toEqual({ clientId: "123.456", callbackUrl: "http://localhost:38417/callback" });
+ expect(slack?.toolExposure).toBeUndefined();
+ const oauth = gmail?.oauth as Record<string, string>;
+ expect(oauth.clientId).toBe("g-id.apps.googleusercontent.com");
+ expect(oauth.clientSecret?.startsWith("!")).toBe(false);
+ expect(resolveConfigValue(oauth.clientSecret ?? "")).toBe("!echo pwned");
+ expect(gmail?.enabled).toBe(false);
+ });
+
+ it("leaves out a guided connector whose required values are missing", () => {
+ const rendered = JSON.parse(
+ renderMcpJson({ connectors: { discord: { enabled: true, mode: "read_only" } } }),
+ ) as { mcpServers: Record<string, unknown> };
+ expect(rendered.mcpServers).toEqual({});
+ });
+});
+
+const managers: ConnectorManager[] = [];
+afterEach(() => {
+ for (const manager of managers.splice(0)) manager.cancelAll();
+});
+
+function setup(cliEnv: Record<string, string> = {}) {
+ const dataDir = tempDir();
+ const agentHome = join(dataDir, "agent");
+ const cliLog = join(dataDir, "cli.jsonl");
+ const logs: string[] = [];
+ const store = new ConnectorStore({ dataDir, agentHome });
+ const manager = new ConnectorManager({
+ store,
+ cli: { command: process.execPath, args: [FAKE_CLI] },
+ env: { ...process.env, HOME: join(dataDir, "home"), FAKE_MCP_CLI_LOG: cliLog, ...cliEnv },
+ cwd: dataDir,
+ log: (line) => logs.push(line),
+ });
+ managers.push(manager);
+ const owner = {};
+ const sent: ServerPayload[] = [];
+ const emit = (payload: ServerPayload) => sent.push(payload);
+ const prompts = () => sent.flatMap((m) => (m.type === "auth_prompt" ? [m.prompt] : []));
+ const cliRuns = () =>
+ existsSync(cliLog)
+ ? readFileSync(cliLog, "utf8")
+ .trim()
+ .split("\n")
+ .map((line) => JSON.parse(line) as { argv: string[] })
+ : [];
+ return { dataDir, agentHome, store, manager, owner, sent, emit, prompts, logs, cliRuns };
+}
+
+describe("guided connector setup", () => {
+ it("asks for the Discord bot token as a secret, then adds it read only; the value is never shown or logged", async () => {
+ const { manager, store, owner, emit, sent, prompts, logs, dataDir, agentHome, cliRuns } = setup();
+ expect(manager.connect(owner, "discord", emit)).toBeUndefined();
+ const prompt = await waitFor(() => prompts()[0]);
+ expect(prompt).toMatchObject({ kind: "secret", flowId: expect.stringMatching(/^connector-setup-/) });
+ expect(prompt.message).toMatch(/token/i);
+ // Nothing is added until the setup is complete.
+ expect(store.state().connectors.discord).toBeUndefined();
+ expect(manager.reply(owner, prompt.flowId, { value: TOKEN })).toBe(true);
+ const done = await waitFor(() => sent.find((m) => m.type === "auth_done"));
+ expect(done).toMatchObject({ flowId: prompt.flowId, providerId: "discord", ok: true });
+ expect(store.state().connectors.discord).toEqual({
+ enabled: true,
+ mode: "read_only",
+ values: { token: TOKEN },
+ });
+ expect(manager.list().find((c) => c.id === "discord")).toMatchObject({
+ added: true,
+ enabled: true,
+ status: "connected",
+ guide: expect.objectContaining({ steps: expect.any(Array) }),
+ });
+ // A server with a token signs in with nothing else; `mcp login` never runs.
+ expect(cliRuns()).toEqual([]);
+ expect(JSON.stringify(manager.list())).not.toContain(TOKEN);
+ expect(JSON.stringify(sent)).not.toContain(TOKEN);
+ expect(logs.join("\n")).not.toContain(TOKEN);
+ expect(readFileSync(join(agentHome, "mcp.json"), "utf8")).toContain("DISCORD_TOKEN");
+ expect(readFileSync(join(dataDir, "connectors.json"), "utf8")).toContain("discord");
+ expect(store.policy().connectors?.discord?.readOnlyTools).toContain("discord_read_messages");
+ });
+
+ it("adds nothing when the setup is cancelled", async () => {
+ const { manager, store, owner, emit, sent, prompts } = setup();
+ manager.connect(owner, "discord", emit);
+ const prompt = await waitFor(() => prompts()[0]);
+ expect(manager.reply({}, prompt.flowId, { cancelled: true })).toBe(false);
+ expect(manager.reply(owner, prompt.flowId, { cancelled: true })).toBe(true);
+ expect(await waitFor(() => sent.find((m) => m.type === "auth_done"))).toMatchObject({ ok: false });
+ expect(store.state().connectors).toEqual({});
+ expect(manager.connect(owner, "slack", emit)).toBeUndefined();
+ });
+
+ it("asks for Slack's client id and an optional secret, writes them to mcp.json, then signs in on the same flow", async () => {
+ const { manager, store, owner, emit, sent, prompts, agentHome, cliRuns, logs } = setup({
+ FAKE_MCP_CLI_MODE: "auto",
+ FAKE_MCP_CLI_URL: "https://mcp.slack.com/mcp",
+ });
+ manager.connect(owner, "slack", emit);
+ const first = await waitFor(() => prompts()[0]);
+ expect(first).toMatchObject({ kind: "text" });
+ expect(first.message).toMatch(/client id/i);
+ manager.reply(owner, first.flowId, { value: "123.456" });
+ const second = await waitFor(() => prompts()[1]);
+ expect(second).toMatchObject({ kind: "secret", optional: true, flowId: first.flowId });
+ expect(manager.reply(owner, second.flowId, { value: CLIENT_SECRET })).toBe(true);
+ const done = await waitFor(() => sent.find((m) => m.type === "auth_done"));
+ expect(done).toMatchObject({ flowId: first.flowId, providerId: "slack", ok: true });
+ expect(cliRuns().map((r) => r.argv)).toEqual([["mcp", "login", "slack"]]);
+ const slack = JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8")).mcpServers.slack;
+ expect(slack.oauth).toMatchObject({
+ clientId: "123.456",
+ callbackUrl: "http://localhost:38417/callback",
+ });
+ expect(manager.list().find((c) => c.id === "slack")?.status).toBe("connected");
+ expect(store.state().connectors.slack?.values).toEqual({
+ client_id: "123.456",
+ client_secret: CLIENT_SECRET,
+ });
+ expect(JSON.stringify(sent)).not.toContain(CLIENT_SECRET);
+ expect(logs.join("\n")).not.toContain(CLIENT_SECRET);
+ });
+
+ it("refuses an empty required value and asks again", async () => {
+ const { manager, owner, emit, prompts } = setup();
+ manager.connect(owner, "discord", emit);
+ const prompt = await waitFor(() => prompts()[0]);
+ manager.reply(owner, prompt.flowId, { value: " " });
+ const again = await waitFor(() => prompts()[1]);
+ expect(again.flowId).toBe(prompt.flowId);
+ expect(again.message).toMatch(/needed/i);
+ });
+
+ it("changes the stored values from Set up, and refuses connectors that need none", async () => {
+ const { manager, store, owner, emit, sent, prompts } = setup();
+ store.update((state) => {
+ state.connectors.discord = { enabled: true, mode: "read_write", values: { token: "old" } };
+ });
+ expect(manager.setup(owner, "discord", emit)).toBeUndefined();
+ const prompt = await waitFor(() => prompts()[0]);
+ manager.reply(owner, prompt.flowId, { value: "new-token" });
+ await waitFor(() => sent.find((m) => m.type === "auth_done"));
+ expect(store.state().connectors.discord).toEqual({
+ enabled: true,
+ mode: "read_write",
+ values: { token: "new-token" },
+ });
+ expect(manager.setup(owner, "notion", emit)).toMatchObject({ code: "connector_not_added" });
+ expect(manager.setup(owner, "nope", emit)).toMatchObject({ code: "unknown_connector" });
+ });
+});
diff --git a/packages/daemon/test/connectors.test.ts b/packages/daemon/test/connectors.test.ts
index c14d863..589820f 100644
--- a/packages/daemon/test/connectors.test.ts
+++ b/packages/daemon/test/connectors.test.ts
@@ -43,10 +43,15 @@ async function engineMcp() {
describe("connectors catalog", () => {
it("lists Notion, Linear, and Atlassian with their official remote servers", () => {
- expect(CATALOG.map(({ id, name, url }) => ({ id, name, url }))).toEqual([
- { id: "notion", name: "Notion", url: "https://mcp.notion.com/mcp" },
- { id: "linear", name: "Linear", url: "https://mcp.linear.app/mcp" },
- { id: "atlassian", name: "Atlassian", url: "https://mcp.atlassian.com/v2/mcp" },
+ expect(CATALOG.slice(0, 3).map(({ id, name, server, oauth }) => ({ id, name, server, oauth }))).toEqual([
+ { id: "notion", name: "Notion", server: { url: "https://mcp.notion.com/mcp" }, oauth: true },
+ { id: "linear", name: "Linear", server: { url: "https://mcp.linear.app/mcp" }, oauth: true },
+ {
+ id: "atlassian",
+ name: "Atlassian",
+ server: { url: "https://mcp.atlassian.com/v2/mcp" },
+ oauth: true,
+ },
]);
for (const entry of CATALOG) {
expect(entry.readOnlyTools.length).toBeGreaterThan(3);
@@ -381,6 +386,9 @@ describe("connector sign-in", () => {
{ id: "notion", added: false, enabled: false, mode: "read_only", status: "off" },
{ id: "linear", added: false, enabled: false, mode: "read_only", status: "off" },
{ id: "atlassian", added: false, enabled: false, mode: "read_only", status: "off" },
+ { id: "discord", added: false, enabled: false, mode: "read_only", status: "off" },
+ { id: "slack", added: false, enabled: false, mode: "read_only", status: "off" },
+ { id: "gmail", added: false, enabled: false, mode: "read_only", status: "off" },
]);
expect(manager.list()[0]).toMatchObject({
name: "Notion",
diff --git a/packages/daemon/test/fixtures/fake-agent.ts b/packages/daemon/test/fixtures/fake-agent.ts
index ad34792..9125bcc 100644
--- a/packages/daemon/test/fixtures/fake-agent.ts
+++ b/packages/daemon/test/fixtures/fake-agent.ts
@@ -7,6 +7,7 @@
// "ask:select" asks a select dialog and echoes the answer
// "ask:confirm" asks a confirm dialog and echoes the answer
// "ask:approval" asks the approval guard's real confirm for a Notion page, and echoes the answer
+// "propose:<json>" runs the approval guard's real propose_connector with <json> as its arguments
// "hang" starts a run that only ends on abort (an aborted answer), or on a
// session switch (Pi then ends it with an error: "This operation was aborted")
// "fail" the provider fails: an answer that ends with stopReason "error"
@@ -353,6 +354,15 @@ async function runPrompt(text: string) {
assistantText(answer.confirmed ? "Created the page" : "I did not create the page");
return endRun();
}
+ if (text.startsWith("propose:")) {
+ const { proposeConnector } = await import("../../src/extensions/approval-guard.ts");
+ const ui = {
+ setStatus: (statusKey: string, statusText: string | undefined) =>
+ out({ type: "extension_ui_request", id: randomUUID(), method: "setStatus", statusKey, statusText }),
+ };
+ assistantText(proposeConnector(JSON.parse(text.slice(8)), { hasUI: true, ui }));
+ return endRun();
+ }
assistantText(`Echo: ${text}`);
endRun();
}
diff --git a/packages/daemon/test/fixtures/fake-mcp-cli.ts b/packages/daemon/test/fixtures/fake-mcp-cli.ts
index 2b1a6f5..ad7b4ad 100644
--- a/packages/daemon/test/fixtures/fake-mcp-cli.ts
+++ b/packages/daemon/test/fixtures/fake-mcp-cli.ts
@@ -2,7 +2,7 @@
// A stand-in for the engine's `mcp login <server>` and `mcp logout <server>` commands.
// login prints the authorization URL like the engine does, then waits on a loopback
// callback (`/callback?code=…&state=fake-state`); on that request it stores a sign-in
-// in `<PI_CODING_AGENT_DIR>/mcp-auth.json` under `mcp__<server>|<url>` and exits 0.
+// in `<PI_CODING_AGENT_DIR>/mcp-auth.json` under `mcp__<server>|<url>` (`-` as `_`, like the engine) and exits 0.
// logout removes that key. Environment:
// FAKE_MCP_CLI_LOG append {argv, env} as JSONL for every run
// FAKE_MCP_CLI_MODE "fail": exit 1 after printing the URL; "auto": finish without a callback
@@ -15,7 +15,7 @@ import { join } from "node:path";
const [command, name] = process.argv.slice(2).filter((arg) => arg !== "mcp");
const agentDir = process.env.PI_CODING_AGENT_DIR ?? ".";
const authFile = join(agentDir, "mcp-auth.json");
-const key = `mcp__${name}|${process.env.FAKE_MCP_CLI_URL ?? "https://mcp.notion.com/mcp"}`;
+const key = `mcp__${name?.replace(/-/g, "_")}|${process.env.FAKE_MCP_CLI_URL ?? "https://mcp.notion.com/mcp"}`;
if (process.env.FAKE_MCP_CLI_LOG) {
appendFileSync(
diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.ts
index 8bcd49d..f74ad3b 100644
--- a/packages/protocol/src/index.ts
+++ b/packages/protocol/src/index.ts
@@ -78,6 +78,8 @@ export interface AuthPrompt {
message: string;
placeholder?: string;
options?: { id: string; label: string; description?: string }[];
+ /** The answer may be left empty. */
+ optional?: boolean;
}
export type AuthEvent =
@@ -89,8 +91,18 @@ export type AuthEvent =
/** What a connector may do: only read, or also act after the user approves each action. */
export type ConnectorMode = "read_only" | "read_write";
-/** `off`: not added or turned off; `error`: the last sign-in failed. */
-export type ConnectorStatus = "off" | "needs_signin" | "connected" | "error";
+/** `off`: not added or turned off; `needs_setup`: a value the user types is missing; `error`: the last sign-in failed. */
+export type ConnectorStatus = "off" | "needs_setup" | "needs_signin" | "connected" | "error";
+
+/** In-app steps for a connector the user sets up with an app or bot of their own. */
+export interface ConnectorGuide {
+ steps: string[];
+ links: { label: string; url: string }[];
+ /** The address to register as the app's redirect URL, for a sign-in with the user's own OAuth app. */
+ redirectUrl?: string;
+ /** Something to know before starting, for example a preview program or a sign-in limit. */
+ note?: string;
+}
/** A service the assistant can connect to (an MCP server the daemon manages). */
export interface ConnectorInfo {
@@ -104,6 +116,46 @@ export interface ConnectorInfo {
enabled: boolean;
mode: ConnectorMode;
status: ConnectorStatus;
+ /** Steps shown before "Connect", for connectors set up with the user's own app or bot. */
+ guide?: ConnectorGuide;
+ /** A server the user added from the assistant's draft or an import; it has no curated read-only list. */
+ custom?: { origin: string; summary: string };
+ /** It has no sign-in of its own (it uses a token, or none). */
+ noSignIn?: true;
+}
+
+/** A connector the assistant drafted with `propose_connector`, waiting for the user's answer. */
+export interface ConnectorDraft {
+ draftId: string;
+ name: string;
+ description: string;
+ transport: "stdio" | "http";
+ command?: string;
+ args?: string[];
+ url?: string;
+ /** Secrets the server needs, by name; the app asks the user for each one. */
+ envNames: string[];
+ needsOAuth: boolean;
+}
+
+/** An MCP server found in another app's configuration; values never leave the daemon. */
+export interface ImportCandidate {
+ id: string;
+ name: string;
+ /** The apps it was found in. */
+ sources: string[];
+ transport: "stdio" | "http" | "sse";
+ /** The command line or address, with values that look secret masked. */
+ summary: string;
+ envNames: string[];
+ headerNames: string[];
+ /** Values the user types after the import (VS Code inputs), by their description. */
+ inputs: string[];
+ importable: boolean;
+ /** Why it cannot be imported. */
+ reason?: string;
+ /** The connector that already has this server. */
+ duplicateOf?: string;
}
/** Reasoning effort levels the engine accepts. */
@@ -201,10 +253,18 @@ export type ClientMessage =
| { type: "profile_save_current"; name: string }
| { type: "connectors_list" }
| {
- type: "connector_connect" | "connector_signin" | "connector_disconnect" | "connector_remove";
+ type:
+ | "connector_connect"
+ | "connector_signin"
+ | "connector_setup"
+ | "connector_disconnect"
+ | "connector_remove";
connectorId: string;
}
- | { type: "connector_mode"; connectorId: string; mode: ConnectorMode };
+ | { type: "connector_mode"; connectorId: string; mode: ConnectorMode }
+ | { type: "connector_draft_reply"; draftId: string; approve: boolean }
+ | { type: "connectors_scan" }
+ | { type: "connector_import"; ids: string[] };
export type ServerPayload =
| { type: "ready"; agentState: AgentState; conversationId?: string; model?: string; features?: Features }
@@ -253,7 +313,11 @@ export type ServerPayload =
}
| { type: "profiles_imported"; imported: { from: string; to: string }[]; missingProviders: string[] }
/** Connector sign-ins reuse `auth_event`, `auth_prompt`, and `auth_done`, with flow ids starting `connector-`. */
- | { type: "connectors"; connectors: ConnectorInfo[]; open?: boolean };
+ | { type: "connectors"; connectors: ConnectorInfo[]; open?: boolean }
+ | { type: "connector_draft"; draft: ConnectorDraft }
+ | { type: "connector_draft_resolved"; draftId: string; approved: boolean }
+ | { type: "connector_imports"; found: ImportCandidate[] }
+ | { type: "connector_imported"; names: string[] };
/** Every daemon message carries a per-connection, monotonic `seq`. */
export type ServerMessage = ServerPayload & { seq: number };
@@ -263,6 +327,8 @@ const isOptional = (value: unknown, check: (v: unknown) => boolean) => value ===
const MAX_TEXT = 100_000;
const CONNECTOR_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
const isConnectorId = (value: unknown): value is string => isString(value) && CONNECTOR_ID.test(value);
+const isShortString = (value: unknown): value is string => isString(value) && value.length <= 200;
+const MAX_IMPORTS = 200;
/**
* Reads the complete queues from the engine's `queue_update` record. A missing
@@ -350,6 +416,7 @@ export function parseClientMessage(raw: string): ClientMessage | undefined {
return isValidProfileName(m.name) ? { type: m.type, name: m.name } : undefined;
case "connector_connect":
case "connector_signin":
+ case "connector_setup":
case "connector_disconnect":
case "connector_remove":
return isConnectorId(m.connectorId) ? { type: m.type, connectorId: m.connectorId } : undefined;
@@ -357,7 +424,16 @@ export function parseClientMessage(raw: string): ClientMessage | undefined {
return isConnectorId(m.connectorId) && (m.mode === "read_only" || m.mode === "read_write")
? { type: "connector_mode", connectorId: m.connectorId, mode: m.mode }
: undefined;
+ case "connector_draft_reply":
+ return isShortString(m.draftId) && typeof m.approve === "boolean"
+ ? { type: "connector_draft_reply", draftId: m.draftId, approve: m.approve }
+ : undefined;
+ case "connector_import":
+ return Array.isArray(m.ids) && m.ids.length <= MAX_IMPORTS && m.ids.every(isShortString)
+ ? { type: "connector_import", ids: m.ids }
+ : undefined;
case "connectors_list":
+ case "connectors_scan":
case "profiles_list":
case "profile_import":
case "abort":
diff --git a/packages/protocol/test/protocol.test.ts b/packages/protocol/test/protocol.test.ts
index c2603b1..f6dad08 100644
--- a/packages/protocol/test/protocol.test.ts
+++ b/packages/protocol/test/protocol.test.ts
@@ -223,4 +223,31 @@ describe("connector messages", () => {
).toBeUndefined();
expect(parseClientMessage('{"type":"connector_mode","connectorId":"notion"}')).toBeUndefined();
});
+
+ it("accepts setup, draft answers, scans, and imports", () => {
+ expect(parseClientMessage('{"type":"connector_setup","connectorId":"discord"}')).toEqual({
+ type: "connector_setup",
+ connectorId: "discord",
+ });
+ expect(parseClientMessage('{"type":"connector_draft_reply","draftId":"d1","approve":true}')).toEqual({
+ type: "connector_draft_reply",
+ draftId: "d1",
+ approve: true,
+ });
+ expect(parseClientMessage('{"type":"connectors_scan"}')).toEqual({ type: "connectors_scan" });
+ expect(parseClientMessage('{"type":"connector_import","ids":["cursor:github"]}')).toEqual({
+ type: "connector_import",
+ ids: ["cursor:github"],
+ });
+ for (const bad of [
+ '{"type":"connector_draft_reply","draftId":"d1"}',
+ '{"type":"connector_draft_reply","draftId":3,"approve":false}',
+ '{"type":"connector_import","ids":"cursor:github"}',
+ '{"type":"connector_import","ids":[3]}',
+ JSON.stringify({ type: "connector_import", ids: Array.from({ length: 201 }, (_, i) => `a:${i}`) }),
+ '{"type":"connector_setup","connectorId":"../x"}',
+ ]) {
+ expect(parseClientMessage(bad), bad.slice(0, 80)).toBeUndefined();
+ }
+ });
});
diff --git a/packages/ui/src/accounts.css b/packages/ui/src/accounts.css
index 3fbf202..b14b1ae 100644
--- a/packages/ui/src/accounts.css
+++ b/packages/ui/src/accounts.css
@@ -120,3 +120,128 @@ button.back {
background: rgba(180, 231, 199, 0.1);
color: var(--green);
}
+
+.chip.connector-needs_setup {
+ color: var(--yellow);
+ border-color: rgba(224, 194, 122, 0.45);
+}
+
+.connector-actions,
+.connector-links {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin: 12px 0;
+}
+
+.connector-guide,
+.connector-imports {
+ margin-top: 12px;
+ padding: 14px 16px;
+ border: 1px solid var(--line);
+ border-radius: var(--radius-md);
+ background: var(--surface);
+}
+
+.connector-guide h3,
+.connector-imports h3 {
+ margin: 0 0 8px;
+ font-size: 15px;
+ font-weight: 700;
+}
+
+.connector-guide ol {
+ margin: 0 0 12px;
+ padding-left: 20px;
+ font-size: 13px;
+ line-height: 19px;
+}
+
+.connector-redirect {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ margin-bottom: 8px;
+ font-size: 12px;
+ color: var(--muted);
+}
+
+.connector-redirect code,
+.connector-imports code,
+.connector-origin code,
+.connector-draft-details code {
+ font: 12px / 17px var(--font-mono);
+ color: var(--text);
+ overflow-wrap: anywhere;
+ user-select: all;
+}
+
+.connector-imports ul {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.connector-step + .connector-step {
+ margin-top: 6px;
+}
+
+.connector-found {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ padding: 10px 0;
+ border-top: 1px solid var(--line);
+}
+
+.connector-import {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 13px;
+}
+
+.connector-import input {
+ accent-color: var(--accent);
+}
+
+.connector-import .muted {
+ font-size: 12px;
+}
+
+.connector-names {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 4px;
+ margin: 0;
+ font-size: 12px;
+}
+
+.connector-origin {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ margin: 0 0 4px;
+ font-size: 12px;
+ color: var(--muted);
+}
+
+.connector-draft-details {
+ display: grid;
+ grid-template-columns: max-content 1fr;
+ gap: 6px 12px;
+ margin: 8px 0;
+ font-size: 12px;
+}
+
+.connector-draft-details dt {
+ color: var(--muted);
+}
+
+.connector-draft-details dd {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ margin: 0;
+}
diff --git a/packages/ui/src/components/AccountsPanel.tsx b/packages/ui/src/components/AccountsPanel.tsx
index 6e410de..e7b2263 100644
--- a/packages/ui/src/components/AccountsPanel.tsx
+++ b/packages/ui/src/components/AccountsPanel.tsx
@@ -301,6 +301,11 @@ export function FlowPrompt({ prompt, send }: { prompt: AuthPrompt; send: Send })
<button type="submit" className="primary" disabled={!value.trim()}>
Continue
</button>
+ {prompt.optional ? (
+ <button type="button" onClick={() => answer("")}>
+ Skip
+ </button>
+ ) : null}
</form>
);
}
diff --git a/packages/ui/src/components/ChatSurface.tsx b/packages/ui/src/components/ChatSurface.tsx
index 2e2835c..ece9c9d 100644
--- a/packages/ui/src/components/ChatSurface.tsx
+++ b/packages/ui/src/components/ChatSurface.tsx
@@ -5,6 +5,7 @@ import { activeTitle, type DotAction, type DotState, isBusy, needsAccount } from
import { AccountsPanel } from "./AccountsPanel.tsx";
import { AskCard } from "./AskCard.tsx";
import { Composer } from "./Composer.tsx";
+import { ConnectorDraftCard } from "./ConnectorDraftCard.tsx";
import { ConnectorsPanel } from "./ConnectorsPanel.tsx";
import {
AccountsIcon,
@@ -238,6 +239,15 @@ export function ChatSurface({
{state.asks.map((ask) => (
<AskCard key={ask.requestId} ask={ask} send={send} />
))}
+ {(state.connectors.drafts ?? []).map((draft) => (
+ <ConnectorDraftCard
+ key={draft.draftId}
+ draft={draft}
+ send={send}
+ // Its secrets are asked in the Connectors screen.
+ approved={() => dispatch({ type: "connector_started", connectorId: draft.name })}
+ />
+ ))}
</main>
{pendingSwitch ? (
diff --git a/packages/ui/src/components/ConnectorDraftCard.tsx b/packages/ui/src/components/ConnectorDraftCard.tsx
new file mode 100644
index 0000000..8abc9c6
--- /dev/null
+++ b/packages/ui/src/components/ConnectorDraftCard.tsx
@@ -0,0 +1,73 @@
+import type { ConnectorDraft } from "@gentle-dot/protocol";
+import { useEffect, useRef } from "react";
+import type { Send } from "./types.ts";
+
+/**
+ * A connector the assistant drafted. Every detail is shown; only "Add" adds it, read only with all
+ * of its tools hidden, and its secrets are then asked in the Connectors screen.
+ */
+export function ConnectorDraftCard({
+ draft,
+ send,
+ approved,
+}: {
+ draft: ConnectorDraft;
+ send: Send;
+ approved: () => void;
+}) {
+ const card = useRef<HTMLElement>(null);
+ useEffect(() => {
+ card.current?.scrollIntoView?.({ block: "nearest" });
+ }, []);
+ const answer = (approve: boolean) =>
+ send({ type: "connector_draft_reply", draftId: draft.draftId, approve });
+ const runs = draft.transport === "http" ? draft.url : [draft.command, ...(draft.args ?? [])].join(" ");
+
+ return (
+ <section ref={card} className="ask-card connector-draft" aria-label={`Add ${draft.name}?`}>
+ <p className="eyebrow">New connector</p>
+ <p className="ask-title">Add {draft.name}?</p>
+ {draft.description ? <p className="connector-note">{draft.description}</p> : null}
+ <dl className="connector-draft-details">
+ <dt>{draft.transport === "http" ? "Address" : "Runs on this computer"}</dt>
+ <dd>
+ <code>{runs}</code>
+ </dd>
+ <dt>Secrets it needs</dt>
+ <dd>
+ {draft.envNames.length > 0
+ ? draft.envNames.map((name) => (
+ <span key={name} className="chip">
+ {name}
+ </span>
+ ))
+ : "None"}
+ </dd>
+ {draft.needsOAuth ? (
+ <>
+ <dt>Sign-in</dt>
+ <dd>You sign in on the service's own page.</dd>
+ </>
+ ) : null}
+ </dl>
+ <p className="connector-note">
+ You type each secret in the app, never in the chat. It starts read only, with all of its tools hidden.
+ </p>
+ <div className="ask-options">
+ <button
+ type="button"
+ className="primary"
+ onClick={() => {
+ answer(true);
+ approved();
+ }}
+ >
+ Add {draft.name}
+ </button>
+ <button type="button" onClick={() => answer(false)}>
+ Decline
+ </button>
+ </div>
+ </section>
+ );
+}
diff --git a/packages/ui/src/components/ConnectorsPanel.tsx b/packages/ui/src/components/ConnectorsPanel.tsx
index dcc837f..90ea85e 100644
--- a/packages/ui/src/components/ConnectorsPanel.tsx
+++ b/packages/ui/src/components/ConnectorsPanel.tsx
@@ -1,4 +1,5 @@
-import type { ConnectorInfo, ConnectorStatus } from "@gentle-dot/protocol";
+import type { ConnectorInfo, ConnectorStatus, ImportCandidate } from "@gentle-dot/protocol";
+import { useState } from "react";
import type { ConnectorsState, DotAction } from "../store.ts";
import "../accounts.css";
import { FlowEvent, FlowPrompt } from "./AccountsPanel.tsx";
@@ -13,20 +14,34 @@ interface ConnectorsPanelProps {
const STATUS_LABELS: Record<ConnectorStatus, string> = {
off: "Off",
+ needs_setup: "Needs setup",
needs_signin: "Needs sign-in",
connected: "Connected",
error: "Sign-in failed",
};
+/** What the chat says for "Add another connector"; the assistant answers with a draft to review. */
+export const addConnectorRequest = (what: string) =>
+ `Please help me add a connector for ${what}. Find its MCP server and draft it for me to review.`;
+
/** The apps the assistant can use, each signed in from here and set to read only or read and send. */
export function ConnectorsPanel({ connectors, send, dispatch, openUrl }: ConnectorsPanelProps) {
+ const [guideFor, setGuideFor] = useState<string>();
+ const [adding, setAdding] = useState(false);
const flow = connectors.flow;
const busy = flow !== undefined && flow.done === undefined;
const name = (id: string) => connectors.list?.find((c) => c.id === id)?.name ?? id;
- const startSignIn = (connector: ConnectorInfo, type: "connector_connect" | "connector_signin") => {
+ const start = (
+ connector: ConnectorInfo,
+ type: "connector_connect" | "connector_signin" | "connector_setup",
+ ) => {
+ setGuideFor(undefined);
dispatch({ type: "connector_started", connectorId: connector.id });
send({ type, connectorId: connector.id });
};
+ const guided = connectors.list?.find((c) => c.id === guideFor && c.guide);
+ // Values are asked first; once the sign-in page is on its way, it is a sign-in.
+ const settingUp = flow?.flowId?.startsWith("connector-setup-") && flow.events.length === 0;
return (
<section className="accounts connectors" aria-label="Connectors">
@@ -47,7 +62,9 @@ export function ConnectorsPanel({ connectors, send, dispatch, openUrl }: Connect
{flow ? (
<div className="auth-flow">
- <p className="auth-flow-title">Signing in to {name(flow.providerId)}</p>
+ <p className="auth-flow-title">
+ {settingUp ? "Setting up" : "Signing in to"} {name(flow.providerId)}
+ </p>
{flow.events.map((event, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: events are append-only and never reordered
<FlowEvent key={`${event.kind}-${i}`} event={event} openUrl={openUrl} />
@@ -77,42 +94,255 @@ export function ConnectorsPanel({ connectors, send, dispatch, openUrl }: Connect
) : null}
</div>
</div>
+ ) : guided?.guide ? (
+ <ConnectorGuideView
+ connector={guided}
+ openUrl={openUrl}
+ back={() => setGuideFor(undefined)}
+ next={() => start(guided, "connector_connect")}
+ />
) : (
- <ul className="providers">
- {(connectors.list ?? []).map((connector) => (
- <ConnectorRow
- key={connector.id}
- connector={connector}
- send={send}
- connect={() => startSignIn(connector, "connector_connect")}
- signIn={() => startSignIn(connector, "connector_signin")}
+ <>
+ <div className="connector-actions">
+ <button type="button" onClick={() => setAdding(!adding)} aria-expanded={adding}>
+ Add another connector
+ </button>
+ <button type="button" onClick={() => send({ type: "connectors_scan" })}>
+ Import my MCP servers
+ </button>
+ </div>
+ {adding ? (
+ <AddAnother
+ cancel={() => setAdding(false)}
+ ask={(what) => {
+ send({ type: "send", text: addConnectorRequest(what) });
+ setAdding(false);
+ dispatch({ type: "connectors", open: false });
+ }}
/>
- ))}
- </ul>
+ ) : null}
+ {connectors.imports ? (
+ <ImportList
+ found={connectors.imports}
+ importServers={(ids) => send({ type: "connector_import", ids })}
+ close={() => dispatch({ type: "connector_imports_closed" })}
+ />
+ ) : null}
+ <ul className="providers">
+ {(connectors.list ?? []).map((connector) => (
+ <ConnectorRow
+ key={connector.id}
+ connector={connector}
+ send={send}
+ connect={() =>
+ connector.guide && !connector.added
+ ? setGuideFor(connector.id)
+ : start(connector, "connector_connect")
+ }
+ signIn={() => start(connector, "connector_signin")}
+ setUp={() => start(connector, "connector_setup")}
+ />
+ ))}
+ </ul>
+ </>
)}
</section>
);
}
+interface ConnectorGuideViewProps {
+ connector: ConnectorInfo;
+ openUrl: (url: string) => void;
+ back: () => void;
+ next: () => void;
+}
+
+/** The steps to create the app or bot the connector signs in with, before "Connect". */
+function ConnectorGuideView({ connector: c, openUrl, back, next }: ConnectorGuideViewProps) {
+ const guide = c.guide;
+ if (!guide) return null;
+ return (
+ <section className="connector-guide" aria-label={`Set up ${c.name}`}>
+ <h3>Set up {c.name}</h3>
+ <ol>
+ {guide.steps.map((step) => (
+ <li key={step} className="connector-step">
+ {step}
+ </li>
+ ))}
+ </ol>
+ {guide.redirectUrl ? (
+ <div className="connector-redirect">
+ <span>Redirect URL to add</span>
+ <code>{guide.redirectUrl}</code>
+ </div>
+ ) : null}
+ <div className="connector-links">
+ {guide.links.map((link) => (
+ <button key={link.url} type="button" className="link" onClick={() => openUrl(link.url)}>
+ Open {link.label}
+ </button>
+ ))}
+ </div>
+ {guide.note ? <p className="connector-note">{guide.note}</p> : null}
+ <div className="auth-actions">
+ <button type="button" onClick={back}>
+ Back
+ </button>
+ <button type="button" className="primary" onClick={next}>
+ Continue
+ </button>
+ </div>
+ </section>
+ );
+}
+
+function AddAnother({ ask, cancel }: { ask: (what: string) => void; cancel: () => void }) {
+ const [what, setWhat] = useState("");
+ return (
+ <form
+ className="auth-step ask-form connector-add"
+ onSubmit={(event) => {
+ event.preventDefault();
+ if (what.trim()) ask(what.trim());
+ }}
+ >
+ <label>
+ <span>What do you want to connect?</span>
+ <input
+ type="text"
+ autoComplete="off"
+ placeholder="For example GitHub or Jira"
+ value={what}
+ onChange={(event) => setWhat(event.target.value)}
+ />
+ </label>
+ <p className="connector-note">
+ The assistant looks for its server and sends you a draft. Nothing is added until you approve it.
+ </p>
+ <div className="auth-actions">
+ <button type="submit" className="primary" disabled={!what.trim()}>
+ Ask the assistant
+ </button>
+ <button type="button" onClick={cancel}>
+ Cancel
+ </button>
+ </div>
+ </form>
+ );
+}
+
+interface ImportListProps {
+ found: ImportCandidate[];
+ importServers: (ids: string[]) => void;
+ close: () => void;
+}
+
+/** What the scan found in the user's other apps: names only, one checkbox each. */
+function ImportList({ found, importServers, close }: ImportListProps) {
+ const [chosen, setChosen] = useState<string[]>([]);
+ const toggle = (id: string) =>
+ setChosen((current) => (current.includes(id) ? current.filter((c) => c !== id) : [...current, id]));
+ const count = chosen.length;
+ return (
+ <section className="connector-imports" aria-label="Found these servers">
+ <h3>Found these servers</h3>
+ {found.length === 0 ? (
+ <p className="muted">No MCP servers were found in your other apps.</p>
+ ) : (
+ <>
+ <p className="connector-note">
+ Imported servers start read only, with all of their tools hidden. Their keys stay on this
+ computer; your other apps are not changed.
+ </p>
+ <ul>
+ {found.map((candidate) => (
+ <li key={candidate.id} className="connector-found">
+ <label className="connector-import">
+ <input
+ type="checkbox"
+ aria-label={candidate.name}
+ disabled={!candidate.importable}
+ checked={chosen.includes(candidate.id)}
+ onChange={() => toggle(candidate.id)}
+ />
+ <b>{candidate.name}</b>
+ <span className="muted">From {candidate.sources.join(", ")}</span>
+ </label>
+ {candidate.summary ? <code>{candidate.summary}</code> : null}
+ <ImportNames label="Keys" names={[...candidate.envNames, ...candidate.headerNames]} />
+ <ImportNames label="You will type" names={candidate.inputs} />
+ {candidate.duplicateOf ? (
+ <p className="connector-note">Already in your connectors as {candidate.duplicateOf}.</p>
+ ) : candidate.reason ? (
+ <p className="connector-note">{candidate.reason}</p>
+ ) : null}
+ </li>
+ ))}
+ </ul>
+ </>
+ )}
+ <div className="auth-actions">
+ {found.length > 0 ? (
+ <button
+ type="button"
+ className="primary"
+ disabled={count === 0}
+ onClick={() => importServers(chosen)}
+ >
+ {count === 0 ? "Import" : `Import ${count} server${count === 1 ? "" : "s"}`}
+ </button>
+ ) : null}
+ <button type="button" onClick={close}>
+ Close the list
+ </button>
+ </div>
+ </section>
+ );
+}
+
+function ImportNames({ label, names }: { label: string; names: string[] }) {
+ if (names.length === 0) return null;
+ return (
+ <p className="connector-names">
+ <span className="muted">{label}:</span>
+ {names.map((name) => (
+ <span key={name} className="chip">
+ {name}
+ </span>
+ ))}
+ </p>
+ );
+}
+
interface ConnectorRowProps {
connector: ConnectorInfo;
send: Send;
connect: () => void;
signIn: () => void;
+ setUp: () => void;
}
-function ConnectorRow({ connector: c, send, connect, signIn }: ConnectorRowProps) {
+function ConnectorRow({ connector: c, send, connect, signIn, setUp }: ConnectorRowProps) {
const nameId = `connector-${c.id}`;
+ const readOnlyNote = c.custom
+ ? "Its tools stay hidden until you choose Read and send. Then it asks you before every action."
+ : "It cannot send or change anything.";
+ const canSignIn = c.enabled && !c.noSignIn && c.status !== "needs_setup";
return (
<li aria-labelledby={nameId}>
<div className="provider-name">
<b id={nameId}>{c.name}</b>
{c.added ? <span className={`chip connector-${c.status}`}>{STATUS_LABELS[c.status]}</span> : null}
</div>
+ {c.custom ? (
+ <p className="connector-origin">
+ <span>{c.custom.origin}</span>
+ <code>{c.custom.summary}</code>
+ </p>
+ ) : null}
<p className="connector-note">{c.reads}</p>
- <p className="connector-note">
- {c.mode === "read_write" ? c.sends : "It cannot send or change anything."}
- </p>
+ <p className="connector-note">{c.mode === "read_write" ? c.sends : readOnlyNote}</p>
{c.enabled ? (
<fieldset className="connector-mode">
<legend>What {c.name} may do</legend>
@@ -140,12 +370,17 @@ function ConnectorRow({ connector: c, send, connect, signIn }: ConnectorRowProps
Connect
</button>
)}
- {c.enabled && c.status !== "connected" ? (
+ {c.enabled && c.status === "needs_setup" ? (
+ <button type="button" className="primary" aria-label={`Set up ${c.name}`} onClick={setUp}>
+ Set up
+ </button>
+ ) : null}
+ {canSignIn && c.status !== "connected" ? (
<button type="button" className="primary" aria-label={`Sign in to ${c.name}`} onClick={signIn}>
Sign in
</button>
) : null}
- {c.enabled && c.status === "connected" ? (
+ {canSignIn && c.status === "connected" ? (
<button type="button" aria-label={`Sign in to ${c.name} again`} onClick={signIn}>
Sign in again
</button>
diff --git a/packages/ui/src/store.ts b/packages/ui/src/store.ts
index c5e46d8..632b4cf 100644
--- a/packages/ui/src/store.ts
+++ b/packages/ui/src/store.ts
@@ -5,9 +5,11 @@ import type {
AuthEvent,
AuthPrompt,
AuthProvider,
+ ConnectorDraft,
ConnectorInfo,
ConversationSummary,
Features,
+ ImportCandidate,
MessageQueue,
ModelOption,
Profile,
@@ -46,8 +48,12 @@ export interface ConnectorsState {
open: boolean;
/** Undefined until the first list arrives. */
list?: ConnectorInfo[];
- /** A connector sign-in; `providerId` is the connector id. */
+ /** 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. */
+ drafts?: ConnectorDraft[];
+ /** The servers the last scan found in other apps, while the list is shown. */
+ imports?: ImportCandidate[];
}
export type ConnectionStatus = "connecting" | "open" | "closed" | "unauthorized";
@@ -98,6 +104,7 @@ export type DotAction =
| { type: "profiles"; open: boolean }
| { type: "connectors"; open: boolean }
| { type: "connector_started"; connectorId: string }
+ | { type: "connector_imports_closed" }
| { type: "auth_started"; providerId: string };
export const initialState: DotState = {
@@ -145,6 +152,10 @@ export function reduce(state: DotState, action: DotAction): DotState {
...openConnectors(state, true),
connectors: { ...state.connectors, open: true, flow: { providerId: action.connectorId, events: [] } },
};
+ case "connector_imports_closed": {
+ const { imports: _imports, ...rest } = state.connectors;
+ return { ...state, connectors: rest };
+ }
case "auth_started":
return {
...state,
@@ -239,6 +250,25 @@ function reduceServer(state: DotState, message: ServerMessage): DotState {
const updated = { ...state, connectors: { ...state.connectors, list: message.connectors } };
return message.open ? openConnectors(updated, true) : updated;
}
+ 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] } };
+ }
+ case "connector_draft_resolved": {
+ const drafts = (state.connectors.drafts ?? []).filter((d) => d.draftId !== message.draftId);
+ return { ...state, connectors: { ...state.connectors, drafts } };
+ }
+ case "connector_imports":
+ return { ...state, connectors: { ...state.connectors, imports: message.found } };
+ case "connector_imported": {
+ const { imports: _imports, ...rest } = state.connectors;
+ const text =
+ message.names.length > 0
+ ? `Imported ${message.names.join(", ")}. Their tools stay hidden until you choose Read and send.`
+ : "Nothing was imported.";
+ return addNotice({ ...state, connectors: rest }, "info", text);
+ }
case "profiles": {
const { type: _type, seq: _seq, open, profiles, active, ...rest } = message;
const next = { ...state.profiles, ...rest, list: profiles };
@@ -307,7 +337,16 @@ function openConnectors(state: DotState, open: boolean): DotState {
const flow = state.connectors.flow;
const keep = open && flow !== undefined && flow.done === undefined;
const others = open ? openProfiles({ ...state, auth: { ...state.auth, open: false } }, false) : state;
- return { ...others, connectors: { ...state.connectors, open, flow: keep ? flow : undefined } };
+ const { imports, ...connectors } = state.connectors;
+ return {
+ ...others,
+ connectors: {
+ ...connectors,
+ ...(open && imports ? { imports } : {}),
+ open,
+ flow: keep ? flow : undefined,
+ },
+ };
}
function closeConnectors(state: DotState, when: boolean): DotState {
diff --git a/packages/ui/test/connectors-more.test.tsx b/packages/ui/test/connectors-more.test.tsx
new file mode 100644
index 0000000..40f1a54
--- /dev/null
+++ b/packages/ui/test/connectors-more.test.tsx
@@ -0,0 +1,304 @@
+import type {
+ ClientMessage,
+ ConnectorDraft,
+ ConnectorInfo,
+ ImportCandidate,
+ ServerMessage,
+ ServerPayload,
+} from "@gentle-dot/protocol";
+import { render, screen, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { useReducer } from "react";
+import { describe, expect, it, vi } from "vitest";
+import { ChatSurface } from "../src/components/ChatSurface.tsx";
+import { ConnectorsPanel } from "../src/components/ConnectorsPanel.tsx";
+import { type DotState, initialState, reduce } from "../src/store.ts";
+
+const connector = (overrides: Partial<ConnectorInfo>): ConnectorInfo => ({
+ id: "discord",
+ name: "Discord",
+ reads: "Read messages in the servers your bot is in.",
+ sends: "Send messages, after you approve each one.",
+ added: false,
+ enabled: false,
+ mode: "read_only",
+ status: "off",
+ ...overrides,
+});
+
+const discord = connector({
+ guide: {
+ steps: [
+ "Open the Discord Developer Portal.",
+ "Add a bot.",
+ "Turn on Message Content Intent.",
+ "Copy the token.",
+ ],
+ links: [{ label: "Discord Developer Portal", url: "https://discord.com/developers/applications" }],
+ },
+});
+const slack = connector({
+ id: "slack",
+ name: "Slack",
+ guide: {
+ steps: ["Create an app.", "Turn on PKCE.", "Add the redirect URL.", "Copy the client ID."],
+ links: [{ label: "Slack apps", url: "https://api.slack.com/apps" }],
+ redirectUrl: "http://localhost:38417/callback",
+ },
+});
+const github = connector({
+ id: "github",
+ name: "GitHub",
+ reads: "Read issues.",
+ sends: "Every action asks you first.",
+ added: true,
+ enabled: true,
+ status: "connected",
+ custom: { origin: "Imported from Cursor", summary: "npx -y @modelcontextprotocol/server-github" },
+});
+const perplexity = connector({
+ id: "perplexity",
+ name: "perplexity",
+ added: true,
+ enabled: true,
+ status: "needs_setup",
+ custom: { origin: "Imported from VS Code", summary: "npx -y server-perplexity-ask" },
+});
+
+const found: ImportCandidate[] = [
+ {
+ id: "Cursor:stripe",
+ name: "stripe",
+ sources: ["Cursor"],
+ transport: "http",
+ summary: "https://mcp.stripe.com/",
+ envNames: [],
+ headerNames: ["Authorization"],
+ inputs: [],
+ importable: true,
+ },
+ {
+ id: "Claude Desktop:github",
+ name: "github",
+ sources: ["Claude Desktop", "Cursor"],
+ transport: "stdio",
+ summary: "npx -y @modelcontextprotocol/server-github",
+ envNames: ["GITHUB_PERSONAL_ACCESS_TOKEN"],
+ headerNames: [],
+ inputs: [],
+ importable: true,
+ },
+ {
+ id: "Claude Code:legacy",
+ name: "legacy",
+ sources: ["Claude Code"],
+ transport: "sse",
+ summary: "https://old.example.com/sse",
+ envNames: [],
+ headerNames: [],
+ inputs: [],
+ importable: false,
+ reason: "Uses the old SSE transport, which the assistant does not support.",
+ },
+ {
+ id: "Cursor:linear",
+ name: "linear",
+ sources: ["Cursor"],
+ transport: "http",
+ summary: "https://mcp.linear.app/mcp",
+ envNames: [],
+ headerNames: [],
+ inputs: [],
+ importable: false,
+ duplicateOf: "linear",
+ },
+];
+
+const draft: ConnectorDraft = {
+ draftId: "d1",
+ name: "GitHub",
+ description: "Read issues and pull requests.",
+ transport: "stdio",
+ command: "npx",
+ args: ["-y", "@modelcontextprotocol/[email protected]"],
+ envNames: ["GITHUB_PERSONAL_ACCESS_TOKEN"],
+ needsOAuth: false,
+};
+
+function apply(state: DotState, ...payloads: ServerPayload[]): DotState {
+ return payloads.reduce(
+ (s, p) => reduce(s, { type: "server", message: { ...p, seq: 1 } as ServerMessage }),
+ state,
+ );
+}
+
+const ready = apply(
+ { ...initialState, connection: "open", agentState: "idle" },
+ {
+ type: "auth_providers",
+ providers: [{ id: "openai", name: "OpenAI", methods: ["api_key"], configured: true }],
+ },
+ { type: "connectors", connectors: [discord, slack, github, perplexity] },
+);
+
+function Harness({ initial, send }: { initial: DotState; send: (m: ClientMessage) => void }) {
+ const [state, dispatch] = useReducer(reduce, initial);
+ return <ChatSurface variant="panel" state={state} send={send} dismiss={vi.fn()} dispatch={dispatch} />;
+}
+
+function panel(state: DotState) {
+ const send = vi.fn();
+ const dispatch = vi.fn();
+ const openUrl = vi.fn();
+ render(<ConnectorsPanel connectors={state.connectors} send={send} dispatch={dispatch} openUrl={openUrl} />);
+ return { send, dispatch, openUrl };
+}
+
+describe("guided connectors", () => {
+ it("shows the step-by-step guide before connecting, then connects", async () => {
+ const send = vi.fn();
+ render(<Harness initial={reduce(ready, { type: "connectors", open: true })} send={send} />);
+ const user = userEvent.setup();
+ await user.click(screen.getByRole("button", { name: "Connect Slack" }));
+ expect(send).not.toHaveBeenCalledWith({ type: "connector_connect", connectorId: "slack" });
+ const guide = within(screen.getByRole("region", { name: "Set up Slack" }));
+ expect(guide.getAllByRole("listitem").map((li) => li.textContent)).toEqual([
+ "Create an app.",
+ "Turn on PKCE.",
+ "Add the redirect URL.",
+ "Copy the client ID.",
+ ]);
+ expect(guide.getByText("http://localhost:38417/callback")).toBeInTheDocument();
+ expect(guide.getByRole("button", { name: "Open Slack apps" })).toBeInTheDocument();
+ await user.click(guide.getByRole("button", { name: "Back" }));
+ expect(screen.queryByRole("region", { name: "Set up Slack" })).toBeNull();
+ await user.click(screen.getByRole("button", { name: "Connect Discord" }));
+ await user.click(screen.getByRole("button", { name: "Continue" }));
+ expect(send).toHaveBeenCalledWith({ type: "connector_connect", connectorId: "discord" });
+ });
+
+ it("titles a setup flow, and lets an optional value be skipped", async () => {
+ let s = reduce(ready, { type: "connector_started", connectorId: "slack" });
+ s = apply(s, {
+ type: "auth_prompt",
+ prompt: {
+ flowId: "connector-setup-1",
+ kind: "secret",
+ message: "Client secret (leave empty if you turned on PKCE)",
+ optional: true,
+ },
+ });
+ const { send } = panel(s);
+ expect(screen.getByText("Setting up Slack")).toBeInTheDocument();
+ expect(screen.getByLabelText(/Client secret/)).toHaveAttribute("type", "password");
+ await userEvent.setup().click(screen.getByRole("button", { name: "Skip" }));
+ expect(send).toHaveBeenCalledWith({ type: "auth_reply", flowId: "connector-setup-1", value: "" });
+ });
+
+ it("shows where a custom connector came from, that its tools are hidden, and offers Set up", async () => {
+ const { send, dispatch } = panel(reduce(ready, { type: "connectors", open: true }));
+ const row = within(screen.getByRole("listitem", { name: "GitHub" }));
+ expect(row.getByText("Imported from Cursor")).toBeInTheDocument();
+ expect(row.getByText("npx -y @modelcontextprotocol/server-github")).toBeInTheDocument();
+ expect(row.getByText(/tools stay hidden until you choose Read and send/)).toBeInTheDocument();
+ const waiting = within(screen.getByRole("listitem", { name: "perplexity" }));
+ expect(waiting.getByText("Needs setup")).toBeInTheDocument();
+ await userEvent.setup().click(waiting.getByRole("button", { name: "Set up perplexity" }));
+ expect(send).toHaveBeenCalledWith({ type: "connector_setup", connectorId: "perplexity" });
+ expect(dispatch).toHaveBeenCalledWith({ type: "connector_started", connectorId: "perplexity" });
+ });
+});
+
+describe("adding another connector", () => {
+ it("asks the assistant in the chat and closes the screen", async () => {
+ const send = vi.fn();
+ render(<Harness initial={reduce(ready, { type: "connectors", open: true })} send={send} />);
+ const user = userEvent.setup();
+ await user.click(screen.getByRole("button", { name: "Add another connector" }));
+ await user.type(screen.getByLabelText("What do you want to connect?"), "Jira Cloud");
+ await user.click(screen.getByRole("button", { name: "Ask the assistant" }));
+ const message = send.mock.calls.map(([m]) => m as ClientMessage).find((m) => m.type === "send");
+ expect(message).toMatchObject({ type: "send", text: expect.stringContaining("Jira Cloud") });
+ expect(screen.queryByRole("region", { name: "Connectors" })).toBeNull();
+ });
+
+ it("shows the assistant's draft as a card with every detail; approving opens its setup", async () => {
+ const send = vi.fn();
+ render(<Harness initial={apply(ready, { type: "connector_draft", draft })} send={send} />);
+ const card = within(screen.getByRole("region", { name: "Add GitHub?" }));
+ expect(card.getByText("Read issues and pull requests.")).toBeInTheDocument();
+ expect(card.getByText("npx -y @modelcontextprotocol/[email protected]")).toBeInTheDocument();
+ expect(card.getByText("GITHUB_PERSONAL_ACCESS_TOKEN")).toBeInTheDocument();
+ expect(card.getByText(/You type each secret in the app/)).toBeInTheDocument();
+ const user = userEvent.setup();
+ await user.click(card.getByRole("button", { name: "Add GitHub" }));
+ expect(send).toHaveBeenCalledWith({ type: "connector_draft_reply", draftId: "d1", approve: true });
+ expect(screen.getByRole("region", { name: "Connectors" })).toBeInTheDocument();
+ });
+
+ it("declines a draft, and drops the card when it is resolved anywhere", async () => {
+ const send = vi.fn();
+ render(<Harness initial={apply(ready, { type: "connector_draft", draft })} send={send} />);
+ await userEvent.setup().click(screen.getByRole("button", { name: "Decline" }));
+ expect(send).toHaveBeenCalledWith({ type: "connector_draft_reply", draftId: "d1", approve: false });
+ const s = apply(
+ ready,
+ { type: "connector_draft", draft },
+ { type: "connector_draft_resolved", draftId: "d1", approved: false },
+ );
+ expect(s.connectors.drafts).toEqual([]);
+ expect(
+ apply(ready, { type: "connector_draft", draft }, { type: "connector_draft", draft }).connectors.drafts,
+ ).toHaveLength(1);
+ });
+});
+
+describe("importing MCP servers", () => {
+ it("scans on request and lists what it found with the source app, names only, and checkboxes", async () => {
+ const send = vi.fn();
+ render(<Harness initial={reduce(ready, { type: "connectors", open: true })} send={send} />);
+ const user = userEvent.setup();
+ await user.click(screen.getByRole("button", { name: "Import my MCP servers" }));
+ expect(send).toHaveBeenCalledWith({ type: "connectors_scan" });
+ });
+
+ it("imports only the servers the user checks", async () => {
+ const { send } = panel(
+ apply(reduce(ready, { type: "connectors", open: true }), { type: "connector_imports", found }),
+ );
+ const list = within(screen.getByRole("region", { name: "Found these servers" }));
+ const stripe = list.getByRole("checkbox", { name: "stripe" });
+ const githubBox = list.getByRole("checkbox", { name: "github" });
+ expect(stripe).not.toBeChecked();
+ expect(list.getByText("From Claude Desktop, Cursor")).toBeInTheDocument();
+ expect(list.getByText("GITHUB_PERSONAL_ACCESS_TOKEN")).toBeInTheDocument();
+ expect(list.getByText("Authorization")).toBeInTheDocument();
+ expect(list.getByRole("checkbox", { name: "legacy" })).toBeDisabled();
+ expect(list.getByText(/old SSE transport/)).toBeInTheDocument();
+ expect(list.getByRole("checkbox", { name: "linear" })).toBeDisabled();
+ expect(list.getByText(/Already in your connectors as linear/)).toBeInTheDocument();
+ const user = userEvent.setup();
+ const importButton = list.getByRole("button", { name: /Import/ });
+ expect(importButton).toBeDisabled();
+ await user.click(stripe);
+ await user.click(githubBox);
+ await user.click(list.getByRole("button", { name: "Import 2 servers" }));
+ expect(send).toHaveBeenCalledWith({
+ type: "connector_import",
+ ids: ["Cursor:stripe", "Claude Desktop:github"],
+ });
+ });
+
+ 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",
+ found: [],
+ });
+ expect(s.connectors.imports).toEqual([]);
+ panel(s);
+ expect(screen.getByText(/No MCP servers were found/)).toBeInTheDocument();
+ s = apply(s, { type: "connector_imports", found }, { type: "connector_imported", names: ["stripe"] });
+ expect(s.connectors.imports).toBeUndefined();
+ expect(s.notices.at(-1)?.message).toMatch(/Imported stripe/);
+ });
+});