@jangmanj/mcp-client 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,574 @@
1
+ /**
2
+ * Connection bridge: owns McpClient instances built from this library and
3
+ * registers their tools with Pi, mirroring the built-in MCP exposure model
4
+ * (codemode default; direct/deferred/hidden; per-tool toolExposure overrides).
5
+ */
6
+
7
+ import { createHash } from "node:crypto";
8
+ import { McpClient } from "../dist/index.js";
9
+ import {
10
+ createOps,
11
+ normalizeContent,
12
+ type Ops,
13
+ type ToolCallResult,
14
+ type ToolEntry,
15
+ } from "../dist/ops/index.js";
16
+ import { HttpTransport } from "../dist/transport-http/index.js";
17
+ import { StdioTransport } from "../dist/transport-stdio/index.js";
18
+ import type { Outcome } from "../dist/index.js";
19
+ import type { Exposure, ResolvedServerConfig } from "./config.ts";
20
+ import { convertBlocks } from "./content.ts";
21
+ import {
22
+ canonicalResource,
23
+ createOAuthProvider,
24
+ FileCredentialStore,
25
+ } from "./oauth.ts";
26
+ import type { ExtensionAPI, ToolAnnotations, ToolResult } from "./pi-api.ts";
27
+
28
+ export type ServerStatus = "connecting" | "connected" | "error" | "disabled";
29
+
30
+ export interface ServerState {
31
+ readonly name: string;
32
+ config: ResolvedServerConfig;
33
+ status: ServerStatus;
34
+ toolCount: number;
35
+ error?: string | undefined;
36
+ description?: string | undefined;
37
+ /** Full server instructions from server/discover, when offered. */
38
+ instructions?: string | undefined;
39
+ client?: McpClient | undefined;
40
+ ops?: Ops | undefined;
41
+ /** Set when the server rejected unauthenticated requests. */
42
+ authRequired?: boolean | undefined;
43
+ /** Closes the loopback redirect listener of an OAuth provider, if any. */
44
+ closeRedirect?: (() => void) | undefined;
45
+ /** Pi tool names registered for this server (persist across reconnects). */
46
+ readonly registeredTools: Set<string>;
47
+ /** Exposures this server's tools were registered with. */
48
+ readonly exposures: Set<Exposure>;
49
+ }
50
+
51
+ export function sanitizeNamePart(s: string): string {
52
+ return s.replace(/[^A-Za-z0-9_]/g, "_");
53
+ }
54
+
55
+ function shortHash(s: string): string {
56
+ return createHash("sha1").update(s).digest("hex").slice(0, 8);
57
+ }
58
+
59
+ /**
60
+ * Map server tool names to Pi tool names: mcp__<server>__<tool>, with a hash
61
+ * suffix for every tool in a collision group (same rule as built-in MCP).
62
+ */
63
+ export function assignToolNames(server: string, toolNames: readonly string[]): Map<string, string> {
64
+ const prefix = `mcp__${sanitizeNamePart(server)}__`;
65
+ const byBase = new Map<string, string[]>();
66
+ for (const t of toolNames) {
67
+ const base = prefix + sanitizeNamePart(t);
68
+ const group = byBase.get(base);
69
+ if (group) group.push(t);
70
+ else byBase.set(base, [t]);
71
+ }
72
+ const out = new Map<string, string>();
73
+ for (const [base, group] of byBase) {
74
+ if (group.length === 1) {
75
+ out.set(group[0] as string, base);
76
+ } else {
77
+ for (const t of group) out.set(t, `${base}_h${shortHash(t)}`);
78
+ }
79
+ }
80
+ return out;
81
+ }
82
+
83
+ /** Per-tool exposure: exact toolExposure key, then first matching `*` pattern, else the server's. */
84
+ export function toolExposureFor(config: ResolvedServerConfig, toolName: string): Exposure {
85
+ const overrides = config.toolExposure;
86
+ if (overrides) {
87
+ const exact = overrides[toolName];
88
+ if (exact !== undefined) return normalizeOverride(exact);
89
+ for (const [pattern, value] of Object.entries(overrides)) {
90
+ if (!pattern.includes("*")) continue;
91
+ const re = new RegExp(`^${pattern.split("*").map(escapeRe).join(".*")}$`);
92
+ if (re.test(toolName)) return normalizeOverride(value);
93
+ }
94
+ }
95
+ return config.exposure;
96
+ }
97
+
98
+ function normalizeOverride(value: string): Exposure {
99
+ return value === "direct" || value === "deferred" || value === "hidden" ? value : "codemode";
100
+ }
101
+
102
+ function escapeRe(s: string): string {
103
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
104
+ }
105
+
106
+ function annotationsOf(entry: ToolEntry): ToolAnnotations | undefined {
107
+ const v = entry.annotations?.value;
108
+ if (typeof v !== "object" || v === null) return undefined;
109
+ const rec = v as Record<string, unknown>;
110
+ const out: ToolAnnotations = {};
111
+ if (typeof rec.readOnlyHint === "boolean") out.readOnlyHint = rec.readOnlyHint;
112
+ if (typeof rec.destructiveHint === "boolean") out.destructiveHint = rec.destructiveHint;
113
+ if (typeof rec.idempotentHint === "boolean") out.idempotentHint = rec.idempotentHint;
114
+ if (typeof rec.openWorldHint === "boolean") out.openWorldHint = rec.openWorldHint;
115
+ return Object.keys(out).length > 0 ? out : undefined;
116
+ }
117
+
118
+ function inputSchemaOf(entry: ToolEntry): Record<string, unknown> {
119
+ const schema = entry.tool.inputSchema;
120
+ if (typeof schema === "object" && schema !== null && !Array.isArray(schema)) {
121
+ return schema as Record<string, unknown>;
122
+ }
123
+ return { type: "object", properties: {} };
124
+ }
125
+
126
+ /** Transport-failure kinds worth one reconnect + retry. */
127
+ const RETRY_KINDS = new Set(["connect", "closed", "stream-broken", "process-exit"]);
128
+
129
+ function isAuthOutcome(outcome: Outcome<unknown>): boolean {
130
+ if (outcome.kind === "auth-failure" || outcome.kind === "auth-unavailable") return true;
131
+ return (
132
+ outcome.kind === "transport-failure" &&
133
+ (outcome.failure.kind === "auth-failure" || outcome.failure.kind === "auth-unavailable")
134
+ );
135
+ }
136
+
137
+ export function describeOutcome(outcome: Exclude<Outcome<unknown>, { kind: "ok" }>): string {
138
+ switch (outcome.kind) {
139
+ case "jsonrpc-error":
140
+ return `JSON-RPC error ${outcome.code}: ${outcome.message}`;
141
+ case "transport-failure":
142
+ return `${outcome.failure.kind}: ${outcome.failure.message}`;
143
+ case "tool-isError":
144
+ return "tool reported an error";
145
+ case "cancelled":
146
+ return "cancelled";
147
+ case "uncertain-write":
148
+ return `uncertain write (${outcome.uncertain.evidence}); not retried`;
149
+ case "mrtr-interim":
150
+ return "server requested mid-request input (elicitations are not supported yet)";
151
+ case "task-handle":
152
+ return "server returned a task handle (task-based calls are not supported yet)";
153
+ default:
154
+ return `${outcome.kind}: ${JSON.stringify("detail" in outcome ? outcome.detail : undefined)?.slice(0, 300)}`;
155
+ }
156
+ }
157
+
158
+ export interface BridgeOptions {
159
+ readonly pi: ExtensionAPI;
160
+ readonly notify: (message: string, level: "info" | "warning" | "error") => void;
161
+ /** Bound for connection waits from tool_call / before_agent_start. */
162
+ readonly waitMs?: number;
163
+ /** Path of the OAuth credential store file; enables OAuth for HTTP servers. */
164
+ readonly credentialStorePath?: string;
165
+ /** Host confirm dialog for OAuth consent prompts. */
166
+ readonly confirm?: (title: string, message: string) => Promise<boolean>;
167
+ /** Browser opener override (tests); defaults to the system browser. */
168
+ readonly browserOpen?: (url: string, signal: AbortSignal) => Promise<void>;
169
+ /** Allow OAuth against insecure loopback HTTP (local dev servers, tests). */
170
+ readonly allowInsecureAuth?: boolean;
171
+ }
172
+
173
+ export class McpBridge {
174
+ private readonly pi: ExtensionAPI;
175
+ private readonly notify: BridgeOptions["notify"];
176
+ private readonly waitMs: number;
177
+ private readonly states = new Map<string, ServerState>();
178
+ private readonly pending = new Map<string, Promise<void>>();
179
+ private readonly credentials: FileCredentialStore | undefined;
180
+ private readonly confirm: BridgeOptions["confirm"];
181
+ private readonly browserOpen: BridgeOptions["browserOpen"];
182
+ private readonly allowInsecureAuth: boolean;
183
+ /** Server name for which an interactive login (/mcp login) is armed. */
184
+ private loginArmed: string | undefined;
185
+
186
+ constructor(opts: BridgeOptions) {
187
+ this.pi = opts.pi;
188
+ this.notify = opts.notify;
189
+ this.waitMs = opts.waitMs ?? 10_000;
190
+ this.credentials = opts.credentialStorePath !== undefined
191
+ ? new FileCredentialStore(opts.credentialStorePath)
192
+ : undefined;
193
+ this.confirm = opts.confirm;
194
+ this.browserOpen = opts.browserOpen;
195
+ this.allowInsecureAuth = opts.allowInsecureAuth ?? false;
196
+ }
197
+
198
+ get(name: string): ServerState | undefined {
199
+ return this.states.get(name);
200
+ }
201
+
202
+ list(): ServerState[] {
203
+ return [...this.states.values()];
204
+ }
205
+
206
+ /** Start connecting every enabled server in the background; mark the rest. */
207
+ sync(configs: ReadonlyMap<string, ResolvedServerConfig>): void {
208
+ for (const [name, cfg] of configs) {
209
+ const existing = this.states.get(name);
210
+ if (existing) {
211
+ const changed = JSON.stringify(existing.config) !== JSON.stringify(cfg);
212
+ existing.config = cfg;
213
+ if (!cfg.enabled) {
214
+ void this.teardown(existing);
215
+ existing.status = "disabled";
216
+ existing.error = undefined;
217
+ } else if (changed || existing.status === "disabled" || existing.status === "error") {
218
+ this.connectInBackground(existing);
219
+ }
220
+ continue;
221
+ }
222
+ const state: ServerState = {
223
+ name,
224
+ config: cfg,
225
+ status: cfg.enabled ? "connecting" : "disabled",
226
+ toolCount: 0,
227
+ registeredTools: new Set(),
228
+ exposures: new Set(),
229
+ };
230
+ this.states.set(name, state);
231
+ if (cfg.enabled) this.connectInBackground(state);
232
+ }
233
+ // Servers removed from configuration: tear down, keep registrations inert.
234
+ for (const [name, state] of this.states) {
235
+ if (!configs.has(name) && state.status !== "disabled") {
236
+ void this.teardown(state);
237
+ state.status = "disabled";
238
+ state.error = "removed from configuration";
239
+ }
240
+ }
241
+ }
242
+
243
+ private connectInBackground(state: ServerState): void {
244
+ state.status = "connecting";
245
+ state.error = undefined;
246
+ const p = this.connect(state)
247
+ .then(() => this.ensureReachTools())
248
+ .catch(() => {});
249
+ this.pending.set(state.name, p);
250
+ void p.finally(() => {
251
+ if (this.pending.get(state.name) === p) this.pending.delete(state.name);
252
+ });
253
+ }
254
+
255
+ /** Wait for pending connections, bounded by waitMs. */
256
+ async waitForPending(predicate?: (state: ServerState) => boolean): Promise<void> {
257
+ const names = [...this.states.values()]
258
+ .filter((s) => (predicate ? predicate(s) : true))
259
+ .map((s) => s.name);
260
+ const pending = names
261
+ .map((n) => this.pending.get(n))
262
+ .filter((p): p is Promise<void> => p !== undefined);
263
+ if (pending.length === 0) return;
264
+ await Promise.race([
265
+ Promise.allSettled(pending),
266
+ new Promise((resolve) => setTimeout(resolve, this.waitMs)),
267
+ ]);
268
+ }
269
+
270
+ async reconnect(name: string): Promise<ServerState> {
271
+ const state = this.states.get(name);
272
+ if (!state) throw new Error(`unknown server: ${name}`);
273
+ await this.teardown(state);
274
+ state.status = "connecting";
275
+ state.error = undefined;
276
+ state.toolCount = 0;
277
+ await this.connect(state);
278
+ this.ensureReachTools();
279
+ return state;
280
+ }
281
+
282
+ /** Interactive OAuth sign-in: arms the consent gate and reconnects. */
283
+ async login(name: string): Promise<ServerState> {
284
+ const state = this.states.get(name);
285
+ if (!state) throw new Error(`unknown server: ${name}`);
286
+ if (state.config.kind !== "http") {
287
+ throw new Error(`mcp "${name}": OAuth applies to HTTP servers only`);
288
+ }
289
+ if (!this.credentials) throw new Error("OAuth is not available (no credential store)");
290
+ this.loginArmed = name;
291
+ try {
292
+ await this.reconnect(name);
293
+ } finally {
294
+ this.loginArmed = undefined;
295
+ }
296
+ return state;
297
+ }
298
+
299
+ /** Delete stored credentials for the server's resource and reconnect. */
300
+ async logout(name: string): Promise<ServerState> {
301
+ const state = this.states.get(name);
302
+ if (!state) throw new Error(`unknown server: ${name}`);
303
+ if (this.credentials && state.config.url !== undefined) {
304
+ await this.credentials.deleteResource(canonicalResource(state.config.url));
305
+ }
306
+ await this.reconnect(name);
307
+ return state;
308
+ }
309
+
310
+ async closeAll(): Promise<void> {
311
+ await Promise.allSettled([...this.pending.values()]);
312
+ await Promise.allSettled([...this.states.values()].map((s) => this.teardown(s)));
313
+ this.states.clear();
314
+ }
315
+
316
+ private async teardown(state: ServerState): Promise<void> {
317
+ const client = state.client;
318
+ state.client = undefined;
319
+ state.ops = undefined;
320
+ state.closeRedirect?.();
321
+ state.closeRedirect = undefined;
322
+ if (client) {
323
+ try {
324
+ await client.close({ graceMs: 500 });
325
+ } catch {
326
+ // close is best-effort
327
+ }
328
+ }
329
+ }
330
+
331
+ private async buildClient(config: ResolvedServerConfig, state: ServerState): Promise<McpClient> {
332
+ let transport: StdioTransport | HttpTransport;
333
+ if (config.kind === "stdio") {
334
+ transport = new StdioTransport({
335
+ command: config.command as string,
336
+ args: config.args ?? [],
337
+ ...(config.cwd !== undefined ? { cwd: config.cwd } : {}),
338
+ ...(config.env !== undefined ? { env: config.env } : {}),
339
+ });
340
+ } else {
341
+ // OAuth attaches when no static Authorization header is configured
342
+ // (mirrors Pi's rule); the flow itself runs on the first 401.
343
+ const hasStaticAuth = Object.keys(config.headers ?? {}).some(
344
+ (k) => k.toLowerCase() === "authorization",
345
+ );
346
+ let authProvider;
347
+ if (!hasStaticAuth && this.credentials) {
348
+ const handle = await createOAuthProvider({
349
+ config,
350
+ store: this.credentials,
351
+ interactive: () => this.loginArmed === config.name,
352
+ ...(this.confirm !== undefined ? { confirm: this.confirm } : {}),
353
+ ...(this.browserOpen !== undefined ? { browserOpen: this.browserOpen } : {}),
354
+ allowInsecureAuth: this.allowInsecureAuth,
355
+ });
356
+ authProvider = handle.provider;
357
+ state.closeRedirect = handle.closeRedirect;
358
+ }
359
+ transport = new HttpTransport({
360
+ url: config.url as string,
361
+ ...(config.headers !== undefined ? { extraHeaders: config.headers } : {}),
362
+ ...(authProvider !== undefined ? { authProvider } : {}),
363
+ });
364
+ }
365
+ return new McpClient({
366
+ transport,
367
+ server: { key: config.name, label: config.name },
368
+ clientInfo: { name: "pi", version: "mcp-client-bridge" },
369
+ defaults: { timeoutMs: config.timeoutMs },
370
+ });
371
+ }
372
+
373
+ private async connect(state: ServerState): Promise<void> {
374
+ const { config } = state;
375
+ try {
376
+ const client = await this.buildClient(config, state);
377
+ const ops = createOps(client);
378
+ state.client = client;
379
+ state.ops = ops;
380
+
381
+ // Best-effort server/discover for instructions used as namespace text.
382
+ try {
383
+ const discovered = await client.discover({ timeoutMs: 10_000 });
384
+ if (discovered.kind === "ok") {
385
+ const instructions = discovered.value.instructions;
386
+ if (typeof instructions === "string" && instructions.trim() !== "") {
387
+ state.description = config.description ?? instructions.split("\n")[0];
388
+ state.instructions = instructions;
389
+ }
390
+ }
391
+ } catch {
392
+ // discover is optional metadata
393
+ }
394
+ if (state.description === undefined && config.description !== undefined) {
395
+ state.description = config.description;
396
+ }
397
+
398
+ const listed = await ops.tools.listAll({ maxItems: 10_000 });
399
+ if (listed.kind === "ok") {
400
+ this.registerTools(state, listed.value.items);
401
+ for (const warning of listed.value.warnings) {
402
+ this.notify(`mcp "${state.name}": ${warning}`, "warning");
403
+ }
404
+ } else if (
405
+ listed.kind === "capability-absent" ||
406
+ (listed.kind === "jsonrpc-error" && listed.code === -32601)
407
+ ) {
408
+ // Server without a tools capability: valid, just nothing to register.
409
+ } else if (isAuthOutcome(listed)) {
410
+ state.authRequired = true;
411
+ throw new Error(`authentication required — sign in with /mcp login ${state.name}`);
412
+ } else {
413
+ throw new Error(describeOutcome(listed));
414
+ }
415
+ state.status = "connected";
416
+ state.error = undefined;
417
+ state.authRequired = undefined;
418
+ } catch (err) {
419
+ state.status = "error";
420
+ state.error = err instanceof Error ? err.message : String(err);
421
+ await this.teardown(state);
422
+ this.notify(`mcp "${state.name}": ${state.error}`, "error");
423
+ }
424
+ }
425
+
426
+ private registerTools(state: ServerState, entries: readonly ToolEntry[]): void {
427
+ const usable = entries.filter((e) => typeof e.name === "string" && e.name !== "");
428
+ const names = assignToolNames(state.name, usable.map((e) => e.name));
429
+ for (const entry of usable) {
430
+ const piName = names.get(entry.name) as string;
431
+ if (state.registeredTools.has(piName)) continue;
432
+ const exposure = toolExposureFor(state.config, entry.name);
433
+ const toolDescription =
434
+ typeof entry.tool.description === "string" ? entry.tool.description : "";
435
+ const annotations = annotationsOf(entry);
436
+ this.pi.registerTool({
437
+ name: piName,
438
+ label: `${state.name}: ${entry.name}`,
439
+ description: toolDescription || `MCP tool ${entry.name} on ${state.name}`,
440
+ parameters: inputSchemaOf(entry),
441
+ exposure,
442
+ namespace: {
443
+ name: `mcp__${sanitizeNamePart(state.name)}`,
444
+ aliases: [state.name, state.name.replace(/-/g, "_")],
445
+ ...(state.description !== undefined ? { description: state.description } : {}),
446
+ ...(state.instructions !== undefined ? { instructions: state.instructions } : {}),
447
+ },
448
+ ...(annotations !== undefined ? { annotations } : {}),
449
+ promptSnippet: toolDescription.split("\n")[0] ?? "",
450
+ execute: (_id, params, signal, onUpdate) =>
451
+ this.callTool(state.name, entry.name, params, signal, onUpdate),
452
+ });
453
+ state.registeredTools.add(piName);
454
+ state.exposures.add(exposure);
455
+ }
456
+ state.toolCount = state.registeredTools.size;
457
+ }
458
+
459
+ private async callTool(
460
+ serverName: string,
461
+ toolName: string,
462
+ params: Record<string, unknown>,
463
+ signal: AbortSignal | undefined,
464
+ onUpdate: ((partial: ToolResult) => void) | undefined,
465
+ ): Promise<ToolResult> {
466
+ let state = this.states.get(serverName);
467
+ if (!state?.ops || state.status !== "connected") {
468
+ throw new Error(
469
+ `MCP server "${serverName}" is not connected (status: ${state?.status ?? "unknown"}${
470
+ state?.error ? `, ${state.error}` : ""
471
+ }). Run /mcp reconnect ${serverName}.`,
472
+ );
473
+ }
474
+ const progress = (p: unknown) => {
475
+ const msg = (p as { message?: unknown })?.message;
476
+ if (typeof msg === "string" && onUpdate) {
477
+ onUpdate({
478
+ content: [{ type: "text", text: `${serverName}/${toolName}: ${msg}` }],
479
+ details: { server: serverName, tool: toolName },
480
+ });
481
+ }
482
+ };
483
+ let outcome = await state.ops.tools.call(toolName, params, {
484
+ validateInput: false, // Pi already validated against the same schema
485
+ allowUnvalidated: true,
486
+ ...(signal !== undefined ? { signal } : {}),
487
+ onProgress: progress,
488
+ });
489
+ if (
490
+ outcome.kind === "transport-failure" &&
491
+ RETRY_KINDS.has(outcome.failure.kind) &&
492
+ !(signal?.aborted ?? false)
493
+ ) {
494
+ // Dropped connection: reconnect once and retry, like built-in MCP does.
495
+ try {
496
+ state = await this.reconnect(serverName);
497
+ } catch {
498
+ // fall through to reporting the original outcome
499
+ }
500
+ if (state.ops && state.status === "connected") {
501
+ outcome = await state.ops.tools.call(toolName, params, {
502
+ validateInput: false,
503
+ allowUnvalidated: true,
504
+ ...(signal !== undefined ? { signal } : {}),
505
+ });
506
+ }
507
+ }
508
+ return this.outcomeToResult(serverName, toolName, outcome);
509
+ }
510
+
511
+ private outcomeToResult(
512
+ serverName: string,
513
+ toolName: string,
514
+ outcome: Outcome<ToolCallResult>,
515
+ ): ToolResult {
516
+ const details = { server: serverName, tool: toolName };
517
+ if (outcome.kind === "ok") {
518
+ const { value } = outcome;
519
+ return {
520
+ content: convertBlocks(value.content),
521
+ details: { ...details, validation: value.validation.status },
522
+ ...(value.structuredContent !== undefined ? { structuredContent: value.structuredContent } : {}),
523
+ };
524
+ }
525
+ if (outcome.kind === "tool-isError") {
526
+ const raw = outcome.result;
527
+ return {
528
+ content: convertBlocks(normalizeContent(raw.content)),
529
+ details,
530
+ isError: true,
531
+ ...(raw.structuredContent !== undefined ? { structuredContent: raw.structuredContent } : {}),
532
+ };
533
+ }
534
+ throw new Error(`mcp ${serverName}/${toolName}: ${describeOutcome(outcome)}`);
535
+ }
536
+
537
+ /**
538
+ * Mirror of built-in behavior: once a codemode-exposure server connects,
539
+ * activate codemode; for deferred, activate tool_search.
540
+ */
541
+ ensureReachTools(): void {
542
+ const exposures = new Set<Exposure>();
543
+ for (const s of this.states.values()) {
544
+ if (s.status === "connected") for (const e of s.exposures) exposures.add(e);
545
+ }
546
+ const autoEnable = this.pi.getSettings?.()?.autoEnableCodemode;
547
+ const all = this.pi.getAllTools();
548
+ const active = new Set(this.pi.getActiveTools());
549
+ const wanted: string[] = [];
550
+ if (exposures.has("codemode") && autoEnable !== false) wanted.push("codemode");
551
+ if (exposures.has("deferred")) wanted.push("tool_search");
552
+ const toAdd = wanted.filter((n) => all.some((t) => t.name === n) && !active.has(n));
553
+ if (toAdd.length > 0) this.pi.setActiveTools([...active, ...toAdd]);
554
+ }
555
+
556
+ statusLines(): string[] {
557
+ if (this.states.size === 0) return ["No MCP servers configured."];
558
+ return [...this.states.values()].map((s) => {
559
+ const base = `${s.name} (${s.config.kind}, ${s.config.source})`;
560
+ switch (s.status) {
561
+ case "connected":
562
+ return `${base}: connected, ${s.toolCount} tool${s.toolCount === 1 ? "" : "s"}`;
563
+ case "connecting":
564
+ return `${base}: connecting…`;
565
+ case "disabled":
566
+ return `${base}: disabled${s.error ? ` (${s.error})` : ""}`;
567
+ case "error":
568
+ return s.authRequired
569
+ ? `${base}: needs sign-in — /mcp login ${s.name}`
570
+ : `${base}: error: ${s.error ?? "unknown"}`;
571
+ }
572
+ });
573
+ }
574
+ }