A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.

0 downloads

dbbasic-browser/apps/browser/src/mcp-service.ts
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-browser.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-browser.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-browser.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 site icons (favicons) in tabs, address bar suggestions and the bookmarks panel 7249579 15 hours, 50 minutes ago History
mcp-service.ts · 32.5 KB · 725 lines
1/**
2 * MCP connections for the assistant: which servers there are, whether you are signed in to each, and the tools they add.
3 *
4 * Rules (the point of the design):
5 * - Tokens live here and in the OS-encrypted store, never in a page, the chrome UI or a log. Without OS encryption
6 * they are kept in memory only (you sign in again after a restart) and the state says so.
7 * - A server adds only the tools its entry names, not everything it offers. Tools that only read run when the assistant
8 * asks; every other tool is asked about every time, even in Auto mode.
9 * - Some arguments are fixed by the entry (for example the one project saved links go in, set per person in mcp-servers.json), whatever the model asks for,
10 * and some fields are dropped from results (notes, interactions) before the model sees them.
11 * - What comes back is untrusted data, like page text.
12 * - Off while the caller network is on.
13 */
14
15import { readFileSync } from "node:fs";
16import type { ToolDef } from "./chat-core.js";
17import { McpAuthError, McpClient, type McpTool } from "./mcp-client.js";
18import { DONE_PAGE, OAuthError, REDIRECT_PORTS, authorizeUrl, discover, exchangeCode, listenForCode, newPkce, newState, redirectUri, refreshTokens, register, revoke, type Fetch, type ServerMeta, type Tokens } from "./mcp-oauth.js";
19
20export interface McpServerConfig {
21 id: string;
22 name: string;
23 url: string;
24 /** The only tools the assistant is given. */
25 tools: string[];
26 /** The ones that only read. Every other enabled tool asks every time. */
27 readOnly: string[];
28 /** Tools the browser itself may call (saving a kept copy, for example) that the assistant is never offered. */
29 browserOnly?: string[];
30 /**
31 * Writes that only add something new (a task, a note, a comment) and change nothing that exists. They are still asked
32 * about every time, but not marked risky. Every other write is.
33 */
34 addsOnly?: string[];
35 /** Arguments forced on a tool, whatever the model sends (and hidden from the model). */
36 fixedArgs?: Record<string, Record<string, unknown>>;
37 /** Result fields removed before the model sees them, per tool. */
38 dropFields?: Record<string, string[]>;
39 /**
40 * Permissions asked for at sign-in beyond the ones the server publishes (a server need not list every scope it has). If the
41 * server refuses them, the sign-in is tried once more without them, so an older server still works.
42 */
43 extraScopes?: string[];
44}
45
46export const DEFAULT_SERVERS: McpServerConfig[] = [
47 {
48 id: "askrobots",
49 name: "askrobots.com",
50 url: "https://askrobots.com/api/mcp/",
51 // What the assistant may do for you on askrobots. Left out on purpose: sending mail, reading your mail, deleting,
52 // money (finance, ads), approving or cancelling tasks, running code, paid image generation, anything public (feed
53 // posts, following), and rewriting whole articles. Typed "/" commands are separate: you run those yourself.
54 tools: [
55 "global_search", "web_search", "list_contacts", "get_contact", "list_notes", "list_tasks", "get_task", "list_projects", "list_links",
56 "list_articles", "get_article", "get_running_timer",
57 "create_link", "create_task", "add_task_comment", "update_task", "create_note", "create_article", "create_contact", "start_timer", "stop_timer",
58 // Searching your browsing history: not read-only on purpose, so the person approves each search (the results go to
59 // the assistant's AI company). Recording, listing and forgetting history are the browser's own (browserOnly).
60 "search_history",
61 ],
62 browserOnly: ["upload_file", "add_history", "list_history", "forget_history", "history_settings"],
63 // (search_history is here only so its approval is not marked risky: it changes nothing.)
64 addsOnly: ["create_link", "create_task", "add_task_comment", "create_note", "create_article", "create_contact", "start_timer", "stop_timer", "search_history"],
65 readOnly: ["global_search", "web_search", "list_contacts", "get_contact", "list_notes", "list_tasks", "get_task", "list_projects", "list_links", "list_articles", "get_article", "get_running_timer"],
66 // Saved links are private. To keep them in one project, put its id in this entry's fixedArgs in mcp-servers.json.
67 // Every write is asked about each time (none is readOnly), and what the assistant makes stays private.
68 fixedArgs: { create_link: { is_public: false }, create_note: { is_public: false }, create_article: { is_public: false }, upload_file: { is_public: false, category: "browser/kept" } },
69 dropFields: { get_contact: ["notes", "interactions"], list_contacts: ["notes", "interactions"] },
70 // Saving the pictures and text of kept pages in your Files is a separate permission, shown on the consent page.
71 extraScopes: ["files:upload", "history"],
72 },
73];
74
75const ID = /^[a-z0-9-]{1,32}$/;
76const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
77const strings = (v: unknown, max: number): string[] | null => (Array.isArray(v) && v.length <= max && v.every((x) => typeof x === "string" && x.length > 0 && x.length <= 80) ? (v as string[]) : null);
78
79/** Extra servers from a file you edit by hand. A bad entry is skipped (and reported), never half-used. */
80export function parseServerConfigs(text: string): { servers: McpServerConfig[]; problems: string[] } {
81 const problems: string[] = [];
82 let raw: unknown;
83 try {
84 raw = JSON.parse(text);
85 } catch {
86 return { servers: [], problems: ["the servers file is not valid JSON"] };
87 }
88 const servers: McpServerConfig[] = [];
89 for (const [i, e] of (Array.isArray(raw) ? raw : []).entries()) {
90 const where = `entry ${i + 1}`;
91 if (!isObj(e) || typeof e.id !== "string" || !ID.test(e.id) || typeof e.name !== "string" || typeof e.url !== "string") {
92 problems.push(`${where}: needs an id (lowercase letters, digits, dashes), a name and a url`);
93 continue;
94 }
95 let ok = false;
96 try {
97 const u = new URL(e.url);
98 ok = u.protocol === "https:" || (u.protocol === "http:" && (u.hostname === "127.0.0.1" || u.hostname === "localhost")) ;
99 } catch {
100 /* not a url */
101 }
102 const tools = strings(e.tools, 40);
103 const readOnly = strings(e.readOnly ?? [], 40);
104 const browserOnly = strings(e.browserOnly ?? [], 20);
105 const addsOnly = strings(e.addsOnly ?? [], 40);
106 const extraScopes = strings(e.extraScopes ?? [], 10);
107 if (!ok || !tools || !tools.length || !readOnly || !readOnly.every((r) => tools.includes(r)) || !browserOnly || !addsOnly || !extraScopes || !extraScopes.every((x) => /^[\x21\x23-\x5b\x5d-\x7e]+$/.test(x))) {
108 problems.push(`${where} (${e.id}): url must be https, "tools" must list the tools to allow, "readOnly" must be among them, and "extraScopes" must be plain scope names`);
109 continue;
110 }
111 servers.push({
112 id: e.id,
113 name: e.name.slice(0, 60),
114 url: e.url,
115 tools,
116 readOnly,
117 ...(browserOnly && browserOnly.length ? { browserOnly } : {}),
118 ...(addsOnly && addsOnly.length ? { addsOnly: addsOnly.filter((x) => tools.includes(x) && !readOnly.includes(x)) } : {}),
119 ...(isObj(e.fixedArgs) ? { fixedArgs: e.fixedArgs as Record<string, Record<string, unknown>> } : {}),
120 ...(isObj(e.dropFields) ? { dropFields: e.dropFields as Record<string, string[]> } : {}),
121 ...(Array.isArray(e.extraScopes) ? { extraScopes } : {}), // an empty list is kept: it means "none", not "the built-in ones"
122 });
123 }
124 return { servers, problems };
125}
126
127export function loadServerConfigs(file: string | undefined, read: (p: string) => string = (p) => readFileSync(p, "utf8")): { servers: McpServerConfig[]; problems: string[] } {
128 let extra: ReturnType<typeof parseServerConfigs> = { servers: [], problems: [] };
129 if (file) {
130 try {
131 extra = parseServerConfigs(read(file));
132 } catch {
133 /* no file is normal */
134 }
135 }
136 const byId = new Map(DEFAULT_SERVERS.map((s) => [s.id, s]));
137 for (const s of extra.servers) {
138 // A file entry replaces the built-in one with the same id, but keeps the permissions it asks for unless it names its own
139 // (otherwise a personal copy made earlier silently loses a permission added later).
140 // Likewise which writes only add (that only takes away a "risky" label; they are still asked about), limited to the
141 // writes this entry allows.
142 const built = byId.get(s.id);
143 let merged = built?.extraScopes && !s.extraScopes ? { ...s, extraScopes: built.extraScopes } : s;
144 if (built?.addsOnly && !s.addsOnly) merged = { ...merged, addsOnly: built.addsOnly.filter((x) => s.tools.includes(x) && !s.readOnly.includes(x)) };
145 byId.set(s.id, merged);
146 }
147 return { servers: [...byId.values()], problems: extra.problems };
148}
149
150// ---- storage -----------------------------------------------------------------------------------------------------
151
152export interface Store {
153 /** False when nothing is written to disk (no OS encryption): sign-ins last until the browser closes. Asking may reach the system keychain, so ask only when it matters. */
154 readonly persistent: boolean;
155 load(): string | null;
156 save(text: string | null): void;
157}
158export interface Encryption {
159 isEncryptionAvailable(): boolean;
160 encryptString(s: string): Buffer;
161 decryptString(b: Buffer): string;
162}
163export interface Files {
164 read(p: string): Buffer | null;
165 write(p: string, b: Buffer | null): void;
166}
167
168/**
169 * Tokens go to disk only encrypted with the operating system's keychain; otherwise nowhere.
170 * Nothing here touches the keychain until it has to: on macOS even asking whether encryption is available can raise a system
171 * password prompt, so a browser that starts and never uses a connection must not ask. Loading looks for the file first and only
172 * decrypts when there is one; saving is where a first sign-in reaches the keychain.
173 */
174export function createStore(path: string, enc: Encryption, files: Files): Store {
175 let memory: string | null = null;
176 let available: boolean | null = null;
177 const canEncrypt = (): boolean => (available ??= enc.isEncryptionAvailable());
178 return {
179 get persistent() {
180 return canEncrypt();
181 },
182 load() {
183 let b: Buffer | null = null;
184 try {
185 b = files.read(path);
186 } catch {
187 b = null;
188 }
189 if (!b) return memory; // no file: nothing to decrypt, so no keychain
190 if (!canEncrypt()) return memory;
191 try {
192 return enc.decryptString(b);
193 } catch {
194 return null; // unreadable or from another user: start signed out
195 }
196 },
197 save(text) {
198 if (!canEncrypt()) {
199 memory = text;
200 return;
201 }
202 files.write(path, text == null ? null : enc.encryptString(text));
203 },
204 };
205}
206
207// ---- the service -------------------------------------------------------------------------------------------------
208
209interface Saved {
210 /** `scope`: what the client was registered for, so asking for more registers again. */
211 servers: Record<string, { clientId?: string; issuer?: string; scope?: string; tokens?: Tokens }>;
212}
213
214export interface McpDeps {
215 fetch: Fetch;
216 store: Store;
217 servers: McpServerConfig[];
218 /** Open the person's own browser on the consent page (the fallback, and for scripts). */
219 openExternal(url: string): void | Promise<void>;
220 /** Open the consent page in a tab of this browser and return the tab's id. The redirect back is caught inside the browser (see captureRedirect), so nothing listens on a port. */
221 openTab?(url: string): Promise<number | null>;
222 closeTab?(id: number): Promise<void>;
223 callerNetworkOn(): boolean;
224 announce(payload: Record<string, unknown>): void;
225 now?(): number;
226 /** Shown to the server during registration. */
227 appName?: string;
228 /** Reaching the server to sign in may be refused on purpose (tests, a stricter policy). */
229 timeoutMs?: number;
230}
231
232export interface McpServerState {
233 id: string;
234 name: string;
235 host: string;
236 signedIn: boolean;
237 connecting: boolean;
238 tools: string[];
239 persistent: boolean;
240 /** Permissions this entry asks for that the current sign-in does not have (connect again to give them). */
241 missingScopes?: string[];
242 error?: string;
243}
244
245const TOOL_CACHE_MS = 5 * 60_000;
246
247/** Remove the named keys, at any depth, from JSON text. Text that is not JSON is returned as it is. */
248export function dropKeys(text: string, keys: string[]): string {
249 if (!keys.length) return text;
250 let v: unknown;
251 try {
252 v = JSON.parse(text);
253 } catch {
254 return text;
255 }
256 const strip = (x: unknown): unknown => {
257 if (Array.isArray(x)) return x.map(strip);
258 if (isObj(x)) return Object.fromEntries(Object.entries(x).filter(([k]) => !keys.includes(k)).map(([k, val]) => [k, strip(val)]));
259 return x;
260 };
261 return JSON.stringify(strip(v));
262}
263
264/** What a write is, in words, for the approval question. */
265const ACTIONS: Record<string, string> = {
266 create_link: "Save a link",
267 create_task: "Add a task",
268 add_task_comment: "Comment on a task",
269 update_task: "Change a task",
270 create_note: "Add a note",
271 create_article: "Add an article",
272 create_contact: "Add a contact",
273 start_timer: "Start the timer",
274 stop_timer: "Stop the timer",
275 search_history: "Search your browsing history (what it finds goes to the assistant's AI)",
276};
277
278/**
279 * The approval question for a write: what it does and every argument it sends, one per line, in full (up to a limit), so
280 * the person reads what will be sent rather than a cut-off blob. Forced arguments are included: they are sent too.
281 */
282export function writeSummary(server: string, tool: string, args: Record<string, unknown>): string {
283 const head = ACTIONS[tool] ? `${ACTIONS[tool]} on ${server}` : `Ask ${server} to ${tool}`;
284 const lines = Object.entries(args)
285 .filter(([, v]) => v !== undefined && v !== null && v !== "")
286 .map(([k, v]) => {
287 const text = typeof v === "string" ? v : typeof v === "boolean" ? (v ? "yes" : "no") : JSON.stringify(v);
288 return `${k}: ${text.length > 1200 ? `${text.slice(0, 1199)}…` : text}`;
289 });
290 return lines.length ? `${head}:\n${lines.join("\n")}` : head;
291}
292
293export class McpService {
294 private meta = new Map<string, ServerMeta>();
295 private flows = new Map<string, { cancel(): void }>();
296 private errors = new Map<string, string>();
297 private refreshing = new Map<string, Promise<string>>();
298 private clients = new Map<string, McpClient>();
299 private toolCache = new Map<string, { at: number; tools: McpTool[] }>();
300 /** Sign-ins waiting for the redirect to arrive inside this browser, by their secret state. */
301 private expecting = new Map<string, { redirect: string; resolve(code: string): void; reject(e: Error): void; timer: NodeJS.Timeout }>();
302
303 private loaded: Saved | null = null;
304
305 /** What is saved, read the first time something needs it (not at start-up: reading may reach the keychain). */
306 private get saved(): Saved {
307 if (!this.loaded) {
308 let s: Saved = { servers: {} };
309 try {
310 const t = this.d.store.load();
311 const j = t ? (JSON.parse(t) as Saved) : null;
312 if (j && isObj(j.servers)) s = j;
313 } catch {
314 /* start signed out */
315 }
316 this.loaded = s;
317 }
318 return this.loaded;
319 }
320
321 constructor(private d: McpDeps) {}
322
323 private now() {
324 return (this.d.now ?? Date.now)();
325 }
326 private persist() {
327 this.d.store.save(JSON.stringify(this.saved));
328 }
329 private cfg(id: string): McpServerConfig {
330 const c = this.d.servers.find((s) => s.id === id);
331 if (!c) throw new Error(`no MCP server called ${id}`);
332 return c;
333 }
334 private refuseInCallerMode() {
335 if (this.d.callerNetworkOn()) throw new Error("MCP connections are switched off while the caller network is on.");
336 }
337
338 state(): McpServerState[] {
339 return this.d.servers.map((c) => ({
340 id: c.id,
341 name: c.name,
342 host: new URL(c.url).host,
343 signedIn: !!this.saved.servers[c.id]?.tokens,
344 connecting: this.flows.has(c.id),
345 tools: c.tools,
346 persistent: this.saved.servers[c.id]?.tokens ? this.d.store.persistent : true, // only asked when signed in, so a closed panel never reaches the keychain
347 ...(this.missingScopes(c.id).length ? { missingScopes: this.missingScopes(c.id) } : {}),
348 ...(this.errors.has(c.id) ? { error: this.errors.get(c.id) as string } : {}),
349 }));
350 }
351
352 /** The entry's extra permissions the current sign-in lacks. Unknown (the server did not say what it granted) counts as none missing. */
353 /** The service's own origin (where the pages of the things it makes live). */
354 origin(id: string): string {
355 return new URL(this.cfg(id).url).origin;
356 }
357
358 missingScopes(id: string): string[] {
359 const c = this.d.servers.find((s) => s.id === id);
360 const granted = this.saved.servers[id]?.tokens?.scope;
361 if (!c?.extraScopes?.length || granted == null) return [];
362 const have = new Set(granted.split(/\s+/));
363 return c.extraScopes.filter((x) => !have.has(x));
364 }
365
366 private async metaFor(c: McpServerConfig): Promise<ServerMeta> {
367 let m = this.meta.get(c.id);
368 if (!m) {
369 m = await discover(c.url, this.d.fetch);
370 this.meta.set(c.id, m);
371 }
372 return m;
373 }
374
375 /**
376 * The redirect back from the consent page, if it belongs to a sign-in waiting for it: the browser's request layer hands every
377 * request here first. The code is taken and a short "you are signed in" page is shown; no request is made, so nothing needs to
378 * listen on a port. Only the exact redirect address with the right secret state counts; anything else returns null and is
379 * treated as the ordinary request it is.
380 */
381 captureRedirect(rawUrl: string): { status: number; html: string } | null {
382 if (this.expecting.size === 0) return null;
383 let u: URL;
384 try {
385 u = new URL(rawUrl);
386 } catch {
387 return null;
388 }
389 const state = u.searchParams.get("state");
390 const e = state ? this.expecting.get(state) : undefined;
391 if (!e || `${u.origin}${u.pathname}` !== e.redirect) return null;
392 clearTimeout(e.timer);
393 this.expecting.delete(state as string);
394 const err = u.searchParams.get("error");
395 const code = u.searchParams.get("code");
396 if (err === "invalid_scope") e.reject(new OAuthError("scope", "the server does not offer every permission asked for"));
397 else if (err) e.reject(new OAuthError("denied", err === "access_denied" ? "sign-in was declined" : `the server refused the sign-in (${err.slice(0, 60)})`));
398 else if (code) e.resolve(code);
399 else e.reject(new OAuthError("denied", "the server sent no code"));
400 return { status: err || !code ? 400 : 200, html: DONE_PAGE(!err && !!code) };
401 }
402
403 private expectRedirect(state: string, redirect: string, timeoutMs: number): { code: Promise<string>; cancel(): void } {
404 let resolve!: (c: string) => void;
405 let reject!: (e: Error) => void;
406 const code = new Promise<string>((res, rej) => {
407 resolve = res;
408 reject = rej;
409 });
410 code.catch(() => {});
411 const timer = setTimeout(() => {
412 this.expecting.delete(state);
413 reject(new OAuthError("timeout", "nobody approved the sign-in in time"));
414 }, timeoutMs);
415 this.expecting.set(state, { redirect, resolve, reject, timer });
416 return {
417 code,
418 cancel: () => {
419 clearTimeout(timer);
420 this.expecting.delete(state);
421 reject(new OAuthError("denied", "sign-in was cancelled"));
422 },
423 };
424 }
425
426 /**
427 * Start signing in. Returns the consent address at once; `done` settles when the person has approved (or not).
428 * `via`: "tab" (the default when the browser can open one) shows the consent page in a tab of this browser and catches the
429 * redirect itself; "system" opens the person's own browser and listens for the redirect on 127.0.0.1; "none" only returns the
430 * address and listens, so a script can do what the person's browser would.
431 */
432 async connect(id: string, opts: { open?: boolean; via?: "tab" | "system" | "none"; withoutExtras?: boolean } = {}): Promise<{ authorizeUrl: string; done: Promise<void> }> {
433 this.refuseInCallerMode();
434 const c = this.cfg(id);
435 const via = opts.via ?? (opts.open === false ? "none" : this.d.openTab ? "tab" : "system");
436 this.flows.get(id)?.cancel();
437 this.errors.delete(id);
438 const found = await this.metaFor(c);
439 const extras = opts.withoutExtras ? [] : (c.extraScopes ?? []).filter((x) => !found.scopes.includes(x));
440 const meta: ServerMeta = extras.length ? { ...found, scopes: [...(found.scopes.length ? found.scopes : []), ...extras] } : found;
441 const scope = meta.scopes.join(" ");
442 const prev = this.saved.servers[id] ?? (this.saved.servers[id] = {});
443 let entry: Saved["servers"][string] = prev;
444 if (!prev.clientId || prev.issuer !== meta.issuer) {
445 entry = this.saved.servers[id] = { clientId: await register(meta, this.d.fetch, this.d.appName ?? "dbbasic-browser"), issuer: meta.issuer, scope };
446 this.persist();
447 } else if ((prev.scope ?? found.scopes.join(" ")) !== scope) {
448 // Asking for different permissions: registered again, in case the server holds a client to what it registered with. The
449 // new client is kept only once this sign-in works, so a current sign-in (and its refreshes) is untouched until then.
450 entry = { clientId: await register(meta, this.d.fetch, this.d.appName ?? "dbbasic-browser"), issuer: meta.issuer, scope };
451 }
452 const clientId = entry.clientId as string;
453 const { verifier, challenge } = newPkce();
454 const state = newState();
455 const timeoutMs = this.d.timeoutMs ?? 300_000;
456 let redirect: string;
457 let waiter: { code: Promise<string>; cancel(): void };
458 if (via === "tab") {
459 redirect = redirectUri(REDIRECT_PORTS[0] as number); // a registered address; it is never connected to, only recognised
460 waiter = this.expectRedirect(state, redirect, timeoutMs);
461 } else {
462 const cb = await listenForCode(state, { timeoutMs });
463 redirect = cb.redirectUri;
464 waiter = { code: cb.code, cancel: cb.cancel };
465 }
466 const url = authorizeUrl(meta, clientId, redirect, challenge, state);
467 let tabId: number | null = null;
468 this.flows.set(id, { cancel: waiter.cancel });
469 const done = (async () => {
470 let again = false;
471 try {
472 const code = await waiter.code;
473 const tokens = await exchangeCode(meta, this.d.fetch, { clientId, code, verifier, redirect }, this.now());
474 this.saved.servers[id] = { clientId, issuer: entry.issuer ?? meta.issuer, scope: entry.scope ?? scope, tokens };
475 this.persist();
476 this.toolCache.delete(id);
477 this.clients.delete(id);
478 this.d.announce({ kind: "mcp-signed-in", server: c.id, host: new URL(c.url).host });
479 } catch (e) {
480 if (e instanceof OAuthError && e.code === "scope" && extras.length) again = true; // an older server: sign in without the extras
481 else {
482 this.errors.set(id, e instanceof Error ? e.message : String(e));
483 throw e;
484 }
485 } finally {
486 this.flows.delete(id);
487 if (tabId != null) await this.d.closeTab?.(tabId).catch(() => {});
488 }
489 if (again) await (await this.connect(id, { ...opts, withoutExtras: true })).done;
490 })();
491 done.catch(() => {}); // the caller decides whether to look; the error is also kept in state()
492 try {
493 if (via === "tab") tabId = (await this.d.openTab?.(url)) ?? null;
494 else if (via === "system") await this.d.openExternal(url);
495 } catch (e) {
496 waiter.cancel();
497 throw e;
498 }
499 return { authorizeUrl: url, done };
500 }
501
502 cancelConnect(id: string): void {
503 this.flows.get(id)?.cancel();
504 }
505
506 async disconnect(id: string): Promise<{ revoked: boolean }> {
507 const c = this.cfg(id);
508 this.flows.get(id)?.cancel();
509 const e = this.saved.servers[id];
510 let revoked = false;
511 if (e?.tokens && e.clientId && !this.d.callerNetworkOn()) {
512 try {
513 const m = await this.metaFor(c);
514 revoked = await revoke(m, this.d.fetch, e.clientId, e.tokens.refresh ?? e.tokens.access);
515 } catch {
516 /* forgetting it here is what matters */
517 }
518 }
519 if (e) delete e.tokens;
520 this.clients.delete(id);
521 this.toolCache.delete(id);
522 this.errors.delete(id);
523 this.persist();
524 this.d.announce({ kind: "mcp-signed-out", server: c.id, revoked });
525 return { revoked };
526 }
527
528 /** A valid access token, refreshed shortly before it runs out. Throws McpAuthError when you must sign in again. */
529 async token(id: string): Promise<string> {
530 const e = this.saved.servers[id];
531 const t = e?.tokens;
532 if (!t) throw new McpAuthError(`not signed in to ${this.cfg(id).name}`);
533 if (t.expiresAt - 60_000 > this.now()) return t.access;
534 const running = this.refreshing.get(id);
535 if (running) return running;
536 const p = (async () => {
537 try {
538 if (!t.refresh || !e.clientId) throw new OAuthError("refresh", "no refresh token");
539 const next = await refreshTokens(await this.metaFor(this.cfg(id)), this.d.fetch, { clientId: e.clientId, refresh: t.refresh }, this.now());
540 e.tokens = next;
541 this.persist();
542 return next.access;
543 } catch (err) {
544 if (err instanceof OAuthError && err.code === "refresh" && /\b(400|401)\b|no refresh/.test(err.message)) {
545 delete e.tokens; // the refresh token is no good: signed out
546 this.persist();
547 this.errors.set(id, "you were signed out; connect again");
548 throw new McpAuthError(`signed out of ${this.cfg(id).name}; connect again`);
549 }
550 throw err;
551 } finally {
552 this.refreshing.delete(id);
553 }
554 })();
555 this.refreshing.set(id, p);
556 return p;
557 }
558
559 /**
560 * Refresh the access token now, whatever its age, and say whether the server also issued a NEW refresh token (rotation).
561 * Never returns a token. For checking how a server behaves, and for a sign-in that seems stale.
562 */
563 async refreshNow(id: string): Promise<{ ok: true; rotated: boolean; expiresInSeconds: number } | { ok: false; message: string }> {
564 this.refuseInCallerMode();
565 const e = this.saved.servers[id];
566 const t = e?.tokens;
567 if (!t || !t.refresh || !e.clientId) return { ok: false, message: t ? "this sign-in has no refresh token" : `not signed in to ${this.cfg(id).name}` };
568 try {
569 const next = await refreshTokens(await this.metaFor(this.cfg(id)), this.d.fetch, { clientId: e.clientId, refresh: t.refresh }, this.now());
570 const rotated = next.refresh !== t.refresh;
571 e.tokens = next;
572 this.persist();
573 return { ok: true, rotated, expiresInSeconds: Math.round((next.expiresAt - this.now()) / 1000) };
574 } catch (err) {
575 return { ok: false, message: err instanceof Error ? err.message : String(err) };
576 }
577 }
578
579 /** True once the saved sign-ins have been read this session (so asking about them costs nothing). */
580 isLoaded(): boolean {
581 return this.loaded !== null;
582 }
583
584 /** Signed in to this server. Reads the saved sign-ins if that has not happened yet (which may reach the keychain). */
585 isSignedIn(id: string): boolean {
586 return !!this.saved.servers[id]?.tokens;
587 }
588
589 /**
590 * Call one of a server's allowed tools for the browser itself (not for the assistant): the bookmarks list, for example.
591 * `fixed` applies the entry's fixed arguments (used when saving, so a saved link goes where the entry says). Fields the entry
592 * drops are dropped here too.
593 */
594 async callDirect(id: string, tool: string, args: Record<string, unknown>, opts: { fixed: boolean }): Promise<string> {
595 this.refuseInCallerMode();
596 const c = this.cfg(id);
597 if (!c.tools.includes(tool) && !(c.browserOnly ?? []).includes(tool)) throw new Error(`${tool} is not one of the tools allowed for ${c.name}`);
598 if (!this.isSignedIn(id)) throw new Error(`not signed in to ${c.name}`);
599 const fixed = opts.fixed ? (c.fixedArgs?.[tool] ?? {}) : {};
600 let res;
601 try {
602 res = await this.client(id).callTool(tool, { ...args, ...fixed });
603 } catch (e) {
604 if (e instanceof McpAuthError) {
605 this.errors.set(id, "you were signed out; connect again");
606 throw new Error(`${c.name} wants a fresh sign-in; connect again in the assistant panel`);
607 }
608 throw e;
609 }
610 const text = dropKeys(res.text, c.dropFields?.[tool] ?? []);
611 if (res.isError) throw new Error(text.slice(0, 300) || `${c.name} reported an error`);
612 return text;
613 }
614
615 /**
616 * Every tool this sign-in may use, as the server lists them (the server decides per account and permission), except the
617 * browser's own. For commands you type yourself in the address bar; the assistant still gets only the entry's allow-list.
618 */
619 async commandTools(id: string): Promise<McpTool[]> {
620 this.refuseInCallerMode();
621 const c = this.cfg(id);
622 if (!this.isSignedIn(id)) return [];
623 return (await this.listed(id)).filter((t) => !(c.browserOnly ?? []).includes(t.name));
624 }
625
626 /** The arguments the entry always sets on a tool (never asked for). */
627 fixedArgNames(id: string, tool: string): string[] {
628 return Object.keys(this.cfg(id).fixedArgs?.[tool] ?? {});
629 }
630
631 /** Run a command you typed: one of `commandTools`, with the entry's fixed arguments forced and its dropped fields dropped. */
632 async runCommand(id: string, tool: string, args: Record<string, unknown>): Promise<string> {
633 this.refuseInCallerMode();
634 const c = this.cfg(id);
635 if (!(await this.commandTools(id)).some((t) => t.name === tool)) throw new Error(`${c.name} does not offer ${tool} to this sign-in`);
636 let res;
637 try {
638 res = await this.client(id).callTool(tool, { ...args, ...(c.fixedArgs?.[tool] ?? {}) });
639 } catch (e) {
640 if (e instanceof McpAuthError) {
641 this.errors.set(id, "you were signed out; connect again");
642 throw new Error(`${c.name} wants a fresh sign-in; connect again in the assistant panel`);
643 }
644 throw e;
645 }
646 const text = dropKeys(res.text, c.dropFields?.[tool] ?? []);
647 if (res.isError) throw new Error(text.slice(0, 500) || `${c.name} reported an error`);
648 return text;
649 }
650
651 private client(id: string): McpClient {
652 let c = this.clients.get(id);
653 if (!c) {
654 c = new McpClient(this.cfg(id).url, () => this.token(id), this.d.fetch);
655 this.clients.set(id, c);
656 }
657 return c;
658 }
659
660 private async listed(id: string): Promise<McpTool[]> {
661 const hit = this.toolCache.get(id);
662 if (hit && this.now() - hit.at < TOOL_CACHE_MS) return hit.tools;
663 const tools = await this.client(id).listTools();
664 this.toolCache.set(id, { at: this.now(), tools });
665 return tools;
666 }
667
668 /** The chat tools from every server you are signed in to. A server that cannot be reached adds none (and the reason is in state()). */
669 async toolDefs(): Promise<ToolDef[]> {
670 if (this.d.callerNetworkOn()) return [];
671 const out: ToolDef[] = [];
672 for (const c of this.d.servers) {
673 if (!this.saved.servers[c.id]?.tokens) continue;
674 let tools: McpTool[];
675 try {
676 tools = await this.listed(c.id);
677 } catch (e) {
678 this.errors.set(c.id, e instanceof McpAuthError ? "you were signed out; connect again" : `could not list tools: ${(e as Error).message}`);
679 continue;
680 }
681 for (const t of tools) {
682 if (!c.tools.includes(t.name)) continue;
683 out.push(this.toToolDef(c, t));
684 }
685 }
686 return out;
687 }
688
689 private toToolDef(c: McpServerConfig, t: McpTool): ToolDef {
690 const fixed = c.fixedArgs?.[t.name] ?? {};
691 const schema = JSON.parse(JSON.stringify(t.inputSchema ?? { type: "object", properties: {} })) as { properties?: Record<string, unknown>; required?: string[] };
692 for (const k of Object.keys(fixed)) {
693 if (schema.properties) delete schema.properties[k];
694 if (schema.required) schema.required = schema.required.filter((r) => r !== k);
695 }
696 const reads = c.readOnly.includes(t.name);
697 const name = `${c.id}__${t.name}`.slice(0, 64);
698 const def: ToolDef = {
699 name,
700 description: `[${c.name}] ${(t.description ?? t.name).slice(0, 500)}`,
701 input_schema: schema as Record<string, unknown>,
702 risk: reads ? "read" : "act",
703 origin: "account",
704 private: true, // what a connected account returns is private: after it, typing and opening addresses always ask
705 run: async (input) => {
706 this.refuseInCallerMode();
707 let res;
708 try {
709 res = await this.client(c.id).callTool(t.name, { ...input, ...fixed });
710 } catch (e) {
711 if (e instanceof McpAuthError) {
712 this.errors.set(c.id, "you were signed out; connect again");
713 throw new Error(`${c.name} wants a fresh sign-in. Tell the person to connect again in the chat panel.`);
714 }
715 throw e;
716 }
717 const text = dropKeys(res.text, c.dropFields?.[t.name] ?? []);
718 if (res.isError) throw new Error(text.slice(0, 500) || `${c.name} reported an error`);
719 return text;
720 },
721 };
722 if (!reads) def.plan = async (input) => ({ summary: writeSummary(c.name, t.name, { ...input, ...fixed }), danger: !(c.addsOnly ?? []).includes(t.name) });
723 return def;
724 }
725}