@blackbelt-technology/pi-dashboard-mcp-client-plugin 0.8.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,427 @@
1
+ /**
2
+ * mcp-client · server list (settings section + folder page).
3
+ *
4
+ * Rows render pi's own vocabulary: name, description, transport, exposure,
5
+ * the enabled switch, live state + tool count from `/live` ("state unknown"
6
+ * when absent), the auth mode for HTTP rows, provenance badges (Pi global /
7
+ * Pi folder, "overrides Pi global" for a whole-entry folder override), the
8
+ * "ignored by pi" flag with a one-click convert for adapter leftovers, pi's
9
+ * rejection message, and inactive reasons. Layer parse errors render as their
10
+ * own rows (pi skips the whole file).
11
+ *
12
+ * The switch writes `enabled` at the row's scope (pending until the write
13
+ * completes, reverting with an inline error on failure). A folder-scope enable
14
+ * that needs re-entered secrets surfaces the needs-choice result; a disable
15
+ * that omitted secrets surfaces the omitted list.
16
+ *
17
+ * Folder-page rows are keyed `${provenance}:${name}` — two rows can share a
18
+ * name (the folder entry replaces the global one only when pi trusts it).
19
+ *
20
+ * See change: migrate-mcp-to-pi-builtin.
21
+ */
22
+ import { useT } from "@blackbelt-technology/dashboard-plugin-runtime";
23
+ import type React from "react";
24
+ import { useEffect, useState } from "react";
25
+ import { authModeOf } from "../core/pi-rules.js";
26
+ import type { EffectiveServerView, LayerStatus, LiveState, Scope } from "../core/types.js";
27
+ import { ApiError, convertServer, scopeToWire, setEnabled } from "./api.js";
28
+ import { provenanceLabel } from "./folder-view.js";
29
+ import { invalidateEffective } from "./hooks.js";
30
+
31
+ const GLOBAL_SCOPE: Scope = { kind: "global" };
32
+
33
+ /** Identifies one row to the page: rows can share a name across provenance. */
34
+ export interface RowRef {
35
+ key: string;
36
+ name: string;
37
+ provenance: EffectiveServerView["provenance"];
38
+ }
39
+
40
+ /** Row testid key: folder rows can share a name across provenance. */
41
+ function keyOf(server: EffectiveServerView, folder: boolean): string {
42
+ return folder ? `${server.provenance}:${server.name}` : server.name;
43
+ }
44
+
45
+ /** The human phrase for an inactive row that the switch cannot explain. */
46
+ function inactiveText(reason: string | undefined): string | null {
47
+ switch (reason) {
48
+ case "project-not-trusted":
49
+ return "project not trusted";
50
+ case "global-only-auth":
51
+ return "auth is global-only";
52
+ case "name-collision":
53
+ return "name collision";
54
+ default:
55
+ return null;
56
+ }
57
+ }
58
+
59
+ interface ServerRowProps {
60
+ server: EffectiveServerView;
61
+ /** Write scope for the enable switch (default global). */
62
+ scope?: Scope;
63
+ live: LiveState | null;
64
+ liveLoading: boolean;
65
+ onOpen: (name: string, provenance: EffectiveServerView["provenance"]) => void;
66
+ onChanged: () => void;
67
+ /**
68
+ * Folder page: a pi-folder row with the same name exists, so a folder-scope
69
+ * write for this name lands on THAT entry — this global row's write actions
70
+ * (toggle, Override…) are disabled rather than silently replacing it.
71
+ */
72
+ writeShadowed?: boolean;
73
+ onNeedsChoice?: (row: RowRef, omitted: string[]) => void;
74
+ onOmitted?: (row: RowRef, omitted: string[]) => void;
75
+ /** Folder page: remove the whole folder entry for this server. */
76
+ onRemoveOverride?: (name: string) => void;
77
+ /** Folder page: the chip's inline remove control hides below 640px. */
78
+ chipsRemovable?: boolean;
79
+ }
80
+
81
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: one row = write state + pi vocabulary (live, auth, leftovers, inactive reasons)
82
+ function ServerRow({
83
+ server,
84
+ scope = GLOBAL_SCOPE,
85
+ live,
86
+ liveLoading,
87
+ onOpen,
88
+ onChanged,
89
+ onNeedsChoice,
90
+ onOmitted,
91
+ onRemoveOverride,
92
+ chipsRemovable = true,
93
+ writeShadowed = false,
94
+ }: ServerRowProps): React.ReactElement {
95
+ const { name, entry } = server;
96
+ const folder = scope.kind === "project";
97
+ const key = keyOf(server, folder);
98
+ const persistedEnabled = server.enabled;
99
+
100
+ const [optimistic, setOptimistic] = useState<boolean | null>(null);
101
+ const [pending, setPending] = useState(false);
102
+ const [error, setError] = useState<string | null>(null);
103
+ // A persisted value change (the reload landing) releases the optimistic value.
104
+ // biome-ignore lint/correctness/useExhaustiveDependencies: keyed on the persisted value only
105
+ useEffect(() => setOptimistic(null), [persistedEnabled]);
106
+ const enabled = optimistic ?? persistedEnabled;
107
+
108
+ const liveRow = live?.ok ? live.servers[name] : undefined;
109
+ const authMode = server.transport === "http" ? authModeOf(entry) : undefined;
110
+ const needsAuth = liveRow?.state === "needs-auth" && authMode?.kind === "oauth";
111
+
112
+ async function toggle(next: boolean): Promise<void> {
113
+ setOptimistic(next);
114
+ setPending(true);
115
+ setError(null);
116
+ try {
117
+ const result = await setEnabled(name, next, scopeToWire(scope));
118
+ if (!result.ok) {
119
+ setOptimistic(null);
120
+ setError(result.refusal.message);
121
+ return;
122
+ }
123
+ if (result.action === "needs-choice") {
124
+ setOptimistic(null);
125
+ onNeedsChoice?.({ key, name, provenance: server.provenance }, result.omitted);
126
+ return;
127
+ }
128
+ if (result.omitted && result.omitted.length > 0) {
129
+ onOmitted?.({ key, name, provenance: server.provenance }, result.omitted);
130
+ }
131
+ invalidateEffective(folder ? scope.cwd : undefined);
132
+ onChanged();
133
+ } catch (e) {
134
+ setOptimistic(null);
135
+ setError(e instanceof ApiError ? e.message : String(e));
136
+ } finally {
137
+ setPending(false);
138
+ }
139
+ }
140
+
141
+ async function convert(): Promise<void> {
142
+ setPending(true);
143
+ setError(null);
144
+ try {
145
+ await convertServer(name, scopeToWire(scope));
146
+ invalidateEffective(folder ? scope.cwd : undefined);
147
+ onChanged();
148
+ } catch (e) {
149
+ setError(e instanceof ApiError ? e.message : String(e));
150
+ } finally {
151
+ setPending(false);
152
+ }
153
+ }
154
+
155
+ const actionLabel = folder && server.provenance !== "pi-folder" ? "Override…" : "Edit";
156
+ const actionTestId = folder ? `mcp-folder-action-${key}` : `mcp-server-action-${name}`;
157
+ const description = typeof entry.description === "string" ? entry.description : null;
158
+ const inactiveReason = inactiveText(server.inactiveReason);
159
+
160
+ return (
161
+ <li
162
+ data-testid={folder ? `mcp-folder-row-${key}` : `mcp-server-row-${name}`}
163
+ className="flex flex-col gap-1 py-1.5 border-b border-[var(--border-secondary)] last:border-b-0"
164
+ >
165
+ <div className="flex items-center gap-2 min-h-11 sm:min-h-0 flex-wrap">
166
+ <label className="inline-flex items-center justify-center min-h-11 min-w-11 sm:min-h-0 sm:min-w-0 flex-none">
167
+ <input
168
+ type="checkbox"
169
+ role="switch"
170
+ aria-label={`Enable ${name}`}
171
+ aria-busy={pending}
172
+ checked={enabled}
173
+ disabled={pending || writeShadowed}
174
+ title={writeShadowed ? "The folder entry of the same name is the folder-scope write target" : undefined}
175
+ onChange={(e) => void toggle(e.target.checked)}
176
+ data-testid={`mcp-server-toggle-${key}`}
177
+ className="w-4 h-4"
178
+ />
179
+ </label>
180
+ <span className="text-xs font-medium text-[var(--text-primary)] truncate">{name}</span>
181
+ {description && (
182
+ <span data-testid={`mcp-server-description-${key}`} className="text-[11px] text-[var(--text-secondary)] truncate">
183
+ {description}
184
+ </span>
185
+ )}
186
+ <code data-testid={`mcp-transport-${key}`} className="text-[10px] text-[var(--text-tertiary)] flex-none">
187
+ {typeof entry.command === "string" ? "command" : "url"}
188
+ </code>
189
+ <span data-testid={`mcp-exposure-${key}`} className="text-[10px] text-[var(--text-tertiary)] flex-none">
190
+ {server.exposure}
191
+ </span>
192
+ {authMode && (
193
+ <span data-testid={`mcp-authmode-${key}`} className="text-[10px] text-[var(--text-tertiary)] flex-none">
194
+ {authMode.kind === "provider"
195
+ ? `auth: ${authMode.provider}`
196
+ : authMode.kind === "header"
197
+ ? "header"
198
+ : "OAuth"}
199
+ </span>
200
+ )}
201
+ <span className="flex items-center gap-1 flex-wrap">
202
+ <span
203
+ data-testid={`mcp-badge-${key}-${provenanceLabel(server.provenance)}`}
204
+ className="inline-flex items-center gap-0.5 text-[10px] px-1.5 py-0.5 rounded-full border border-[var(--border-secondary)] text-[var(--text-secondary)]"
205
+ >
206
+ {provenanceLabel(server.provenance)}
207
+ </span>
208
+ {server.overridesGlobal && (
209
+ <span
210
+ data-testid={`mcp-badge-${key}-overrides Pi global`}
211
+ className="inline-flex items-center text-[10px] px-1.5 py-0.5 rounded-full border border-[var(--accent-primary,#60a5fa)] text-[var(--accent-primary,#60a5fa)]"
212
+ >
213
+ overrides Pi global
214
+ </span>
215
+ )}
216
+ {folder && server.provenance === "pi-folder" && (
217
+ <span
218
+ data-testid={`mcp-folder-override-chip-${key}`}
219
+ className="inline-flex items-center gap-0.5 text-[10px] px-1.5 py-0.5 rounded-full border border-[var(--accent-primary,#60a5fa)] text-[var(--accent-primary,#60a5fa)]"
220
+ >
221
+ folder entry
222
+ {chipsRemovable && onRemoveOverride && (
223
+ <button
224
+ type="button"
225
+ aria-label={`Remove folder override for ${name}`}
226
+ data-testid={`mcp-folder-chip-remove-${key}`}
227
+ onClick={() => onRemoveOverride(name)}
228
+ className="px-1 min-h-11 min-w-11 sm:min-h-0 sm:min-w-0"
229
+ >
230
+ ✕
231
+ </button>
232
+ )}
233
+ </span>
234
+ )}
235
+ </span>
236
+ {live !== undefined && !(liveLoading && live === null) && (
237
+ <span data-testid={`mcp-live-${key}`} className="text-[10px] text-[var(--text-tertiary)] flex-none">
238
+ {liveRow ? `${liveRow.state} · ${liveRow.tools} tools` : "state unknown"}
239
+ </span>
240
+ )}
241
+ {needsAuth && (
242
+ <span
243
+ data-testid={`mcp-signin-hint-${key}`}
244
+ className="text-[10px] text-[var(--text-secondary)] flex-none"
245
+ >
246
+ sign in: /mcp login {name}
247
+ </span>
248
+ )}
249
+ {server.adapterLeftovers.length > 0 && (!folder || server.provenance === "pi-folder") && (
250
+ <span className="inline-flex items-center gap-1 flex-none">
251
+ <span
252
+ data-testid={`mcp-leftovers-${key}`}
253
+ className="inline-flex items-center text-[10px] px-1.5 py-0.5 rounded-full border border-amber-500 text-amber-500"
254
+ title={`pi ignores: ${server.adapterLeftovers.join(", ")}`}
255
+ >
256
+ ignored by pi: {server.adapterLeftovers.join(", ")}
257
+ </span>
258
+ <button
259
+ type="button"
260
+ aria-label={`Convert ${name} to pi's entry shape`}
261
+ data-testid={`mcp-convert-${key}`}
262
+ disabled={pending}
263
+ onClick={() => void convert()}
264
+ className="text-[10px] px-1.5 py-0.5 min-h-11 min-w-11 sm:min-h-0 sm:min-w-0 rounded border border-[var(--border-secondary)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] disabled:opacity-50"
265
+ >
266
+ Convert
267
+ </button>
268
+ </span>
269
+ )}
270
+ <button
271
+ type="button"
272
+ onClick={() => onOpen(name, server.provenance)}
273
+ disabled={writeShadowed}
274
+ title={writeShadowed ? "The folder entry of the same name is the folder-scope write target — edit that row" : undefined}
275
+ data-testid={actionTestId}
276
+ className="ml-auto text-[11px] px-2 py-1 min-h-11 min-w-11 sm:min-h-0 sm:min-w-0 rounded border border-[var(--border-secondary)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] disabled:opacity-50"
277
+ >
278
+ {actionLabel}
279
+ </button>
280
+ </div>
281
+ {server.piError && (
282
+ <p
283
+ data-testid={`mcp-pi-error-${key}`}
284
+ role="alert"
285
+ className="text-[11px] text-[var(--status-error,#f87171)] m-0"
286
+ >
287
+ {server.piError}
288
+ </p>
289
+ )}
290
+ {inactiveReason && (
291
+ <p data-testid={`mcp-inactive-${key}`} className="text-[11px] text-[var(--text-secondary)] m-0">
292
+ {inactiveReason}
293
+ </p>
294
+ )}
295
+ {error && (
296
+ <p
297
+ role="alert"
298
+ data-testid={`mcp-server-error-${key}`}
299
+ className="text-[11px] text-[var(--status-error,#f87171)]"
300
+ >
301
+ {error}
302
+ </p>
303
+ )}
304
+ </li>
305
+ );
306
+ }
307
+
308
+ function SkeletonRows(): React.ReactElement {
309
+ return (
310
+ <div data-testid="mcp-list-skeleton" className="space-y-2 py-2">
311
+ {[0, 1, 2].map((i) => (
312
+ <div
313
+ key={i}
314
+ className="h-5 rounded bg-[var(--bg-tertiary,#27272a)] animate-pulse"
315
+ style={{ width: `${100 - i * 15}%` }}
316
+ />
317
+ ))}
318
+ </div>
319
+ );
320
+ }
321
+
322
+ export interface ServerListProps {
323
+ servers: EffectiveServerView[];
324
+ /** Parse status per layer: a failed layer renders a "pi skips the file" row. */
325
+ layers: LayerStatus[];
326
+ /** True until the first effective view arrives. */
327
+ loading: boolean;
328
+ /** Write scope for every row (default global). */
329
+ scope?: Scope;
330
+ /** Live state from `/live`; `null` while absent → rows read "state unknown". */
331
+ live?: LiveState | null;
332
+ liveLoading?: boolean;
333
+ onOpen: (name: string, provenance: EffectiveServerView["provenance"]) => void;
334
+ onAdd: () => void;
335
+ onChanged: () => void;
336
+ /** Folder page: a folder enable that needs re-entered secrets. */
337
+ onNeedsChoice?: (row: RowRef, omitted: string[]) => void;
338
+ /** Folder page: a folder disable that wrote a copy omitting secrets. */
339
+ onOmitted?: (row: RowRef, omitted: string[]) => void;
340
+ /** Folder page: remove the whole folder entry for this server. */
341
+ onRemoveOverride?: (name: string) => void;
342
+ /** Folder page: the chip's inline remove control hides below 640px. */
343
+ chipsRemovable?: boolean;
344
+ }
345
+
346
+ export function ServerList({
347
+ servers,
348
+ layers,
349
+ loading,
350
+ scope,
351
+ live,
352
+ liveLoading = false,
353
+ onOpen,
354
+ onAdd,
355
+ onChanged,
356
+ onNeedsChoice,
357
+ onOmitted,
358
+ onRemoveOverride,
359
+ chipsRemovable,
360
+ }: ServerListProps): React.ReactElement {
361
+ const t = useT();
362
+ if (loading && servers.length === 0 && layers.every((l) => l.ok)) return <SkeletonRows />;
363
+
364
+ const sorted = [...servers].sort(
365
+ (a, b) => (a.name === b.name ? a.provenance.localeCompare(b.provenance) : a.name.localeCompare(b.name)),
366
+ );
367
+ const folderNames = new Set(sorted.filter((s) => s.provenance === "pi-folder").map((s) => s.name));
368
+ const brokenLayers = layers.filter((l) => !l.ok);
369
+ const empty = sorted.length === 0 && brokenLayers.length === 0;
370
+
371
+ return (
372
+ <ul data-testid="mcp-server-list" className="list-none m-0 p-0">
373
+ {brokenLayers.map((l) => (
374
+ <li
375
+ key={l.path}
376
+ data-testid="mcp-layer-error"
377
+ role="alert"
378
+ className="text-[11px] py-1.5 border-b border-[var(--border-secondary)] text-[var(--status-error,#f87171)]"
379
+ >
380
+ <code>{l.path}</code>: {l.message} — pi skips this file.
381
+ </li>
382
+ ))}
383
+ {sorted.map((s) => (
384
+ <ServerRow
385
+ key={`${s.provenance}:${s.name}`}
386
+ server={s}
387
+ scope={scope}
388
+ live={live ?? null}
389
+ liveLoading={liveLoading}
390
+ onOpen={onOpen}
391
+ onChanged={onChanged}
392
+ onNeedsChoice={onNeedsChoice}
393
+ onOmitted={onOmitted}
394
+ onRemoveOverride={onRemoveOverride}
395
+ chipsRemovable={chipsRemovable}
396
+ writeShadowed={scope?.kind === "project" && s.provenance === "pi-global" && folderNames.has(s.name)}
397
+ />
398
+ ))}
399
+ {empty && (
400
+ <li data-testid="mcp-empty" className="py-3 text-center">
401
+ <p className="text-xs text-[var(--text-secondary)] m-0 mb-1.5">
402
+ {t("mcpEmptyState", undefined, "No MCP servers configured.")}
403
+ </p>
404
+ <div className="flex items-center justify-center gap-3 text-[11px]">
405
+ <button
406
+ type="button"
407
+ onClick={onAdd}
408
+ data-testid="mcp-empty-add"
409
+ className="px-2 py-1 min-h-11 min-w-11 sm:min-h-0 sm:min-w-0 rounded border border-[var(--border-secondary)] text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
410
+ >
411
+ Add server
412
+ </button>
413
+ <a
414
+ href="https://github.com/earendil-works/pi/blob/main/docs/mcp.md"
415
+ target="_blank"
416
+ rel="noreferrer"
417
+ data-testid="mcp-docs-link"
418
+ className="text-[var(--accent-primary,#60a5fa)]"
419
+ >
420
+ MCP configuration docs
421
+ </a>
422
+ </div>
423
+ </li>
424
+ )}
425
+ </ul>
426
+ );
427
+ }
@@ -0,0 +1,149 @@
1
+ /**
2
+ * mcp-client-plugin · client REST surface.
3
+ *
4
+ * A thin typed wrapper over `/api/mcp-client/*`. No caching and no React here —
5
+ * `hooks.ts` owns dedupe + cache. Types are imported TYPE-ONLY from `../core`
6
+ * so this browser bundle never pulls the core's `node:*` imports.
7
+ *
8
+ * Wire shapes mirror the route handlers in `../server/routes.ts`.
9
+ * See change: migrate-mcp-to-pi-builtin.
10
+ */
11
+ import type { EffectiveView, LiveState, Scope, SetEnabledResult } from "../core/types.js";
12
+
13
+ const API_BASE = "/api/mcp-client";
14
+
15
+ /** The wire body of every scoped write. */
16
+ export interface ScopeWire {
17
+ scope: "global" | "project";
18
+ cwd?: string;
19
+ }
20
+
21
+ export function scopeToWire(scope: Scope): ScopeWire {
22
+ return scope.kind === "global" ? { scope: "global" } : { scope: "project", cwd: scope.cwd };
23
+ }
24
+
25
+ /** A refusal from any route, carrying the closed `error` code + optional fields. */
26
+ export class ApiError extends Error {
27
+ readonly status: number;
28
+ readonly code: string;
29
+ readonly fields: string[];
30
+
31
+ constructor(status: number, code: string, message: string, fields?: string[]) {
32
+ super(message);
33
+ this.name = "ApiError";
34
+ this.status = status;
35
+ this.code = code;
36
+ this.fields = fields ?? [];
37
+ }
38
+
39
+ /** A cwd outside the dashboard's known-folder set (403 `not-allowed`). */
40
+ get isNotAllowed(): boolean {
41
+ return this.status === 403 && this.code === "not-allowed";
42
+ }
43
+ }
44
+
45
+ interface ErrorBody {
46
+ error?: unknown;
47
+ message?: unknown;
48
+ fields?: unknown;
49
+ }
50
+
51
+ async function failure(res: Response): Promise<ApiError> {
52
+ let body: ErrorBody = {};
53
+ try {
54
+ body = (await res.json()) as ErrorBody;
55
+ } catch {
56
+ /* a non-JSON body carries no code — fall back to the status */
57
+ }
58
+ return new ApiError(
59
+ res.status,
60
+ typeof body.error === "string" ? body.error : `http-${res.status}`,
61
+ typeof body.message === "string" ? body.message : `request failed (${res.status})`,
62
+ Array.isArray(body.fields) ? body.fields.filter((f): f is string => typeof f === "string") : [],
63
+ );
64
+ }
65
+
66
+ async function readJson<T>(res: Response): Promise<T> {
67
+ if (!res.ok) throw await failure(res);
68
+ return (await res.json()) as T;
69
+ }
70
+
71
+ function methodWith(method: string, body: unknown): RequestInit {
72
+ return {
73
+ method,
74
+ headers: { "content-type": "application/json" },
75
+ body: JSON.stringify(body),
76
+ };
77
+ }
78
+
79
+ /** `GET /effective` — the effective view for a cwd, or global when omitted. */
80
+ export async function fetchEffective(cwd?: string): Promise<EffectiveView> {
81
+ const qs = cwd ? `?cwd=${encodeURIComponent(cwd)}` : "";
82
+ return readJson<EffectiveView>(await fetch(`${API_BASE}/effective${qs}`));
83
+ }
84
+
85
+ /**
86
+ * `GET /live` — live state from `pi mcp list --json`. SLOW (up to 30 s):
87
+ * call on page view and on an explicit refresh only; render from `/effective`
88
+ * first.
89
+ */
90
+ export async function fetchLive(cwd?: string, opts?: { fresh?: boolean }): Promise<LiveState> {
91
+ const params = new URLSearchParams();
92
+ if (cwd) params.set("cwd", cwd);
93
+ // An explicit refresh bypasses the server's 30 s per-cwd cache.
94
+ if (opts?.fresh) params.set("fresh", "1");
95
+ const qs = params.toString();
96
+ return readJson<LiveState>(await fetch(`${API_BASE}/live${qs ? `?${qs}` : ""}`));
97
+ }
98
+
99
+ /** `GET /schema` — the published JSON Schema for `ServerEntry`. */
100
+ export async function fetchSchema(): Promise<Record<string, unknown>> {
101
+ return readJson<Record<string, unknown>>(await fetch(`${API_BASE}/schema`));
102
+ }
103
+
104
+ /** The body of `PUT /servers/:name` — a WHOLE-entry save; `previousName` renames. */
105
+ export interface SaveServerBody extends ScopeWire {
106
+ entry: Record<string, unknown>;
107
+ previousName?: string;
108
+ /** A new server: refused (409 name-collision) when the name already exists. */
109
+ create?: boolean;
110
+ }
111
+
112
+ /** `PUT /servers/:name` — replace the entry at one scope. */
113
+ export async function saveServer(name: string, body: SaveServerBody): Promise<void> {
114
+ await readJson<unknown>(
115
+ await fetch(`${API_BASE}/servers/${encodeURIComponent(name)}`, methodWith("PUT", body)),
116
+ );
117
+ }
118
+
119
+ /** `DELETE /servers/:name` — returns the removed raw entry (the undo payload). */
120
+ export async function removeServer(
121
+ name: string,
122
+ wire: ScopeWire,
123
+ ): Promise<{ removed?: Record<string, unknown> }> {
124
+ const params = new URLSearchParams();
125
+ params.set("scope", wire.scope);
126
+ if (wire.cwd !== undefined) params.set("cwd", wire.cwd);
127
+ return readJson<{ removed?: Record<string, unknown> }>(
128
+ await fetch(`${API_BASE}/servers/${encodeURIComponent(name)}?${params.toString()}`, { method: "DELETE" }),
129
+ );
130
+ }
131
+
132
+ /** `PUT /servers/:name/enabled` — the row switch write. */
133
+ export async function setEnabled(
134
+ name: string,
135
+ enabled: boolean,
136
+ wire: ScopeWire,
137
+ ): Promise<SetEnabledResult> {
138
+ return readJson<SetEnabledResult>(
139
+ await fetch(`${API_BASE}/servers/${encodeURIComponent(name)}/enabled`, methodWith("PUT", { ...wire, enabled })),
140
+ );
141
+ }
142
+
143
+ /** `POST /servers/:name/convert` — adapter leftovers → pi's entry shape. */
144
+ export async function convertServer(name: string, wire: ScopeWire): Promise<void> {
145
+ await readJson<unknown>(
146
+ await fetch(`${API_BASE}/servers/${encodeURIComponent(name)}/convert`, methodWith("POST", wire)),
147
+ );
148
+ }
149
+
@@ -0,0 +1,67 @@
1
+ /**
2
+ * mcp-client-plugin · folder-scope view helpers.
3
+ *
4
+ * The folder override pre-fill: pi replaces a global entry WHOLE, so
5
+ * "Override…" starts from the complete global entry EXCEPT the secret-bearing
6
+ * fields (`headers`, `env`, `oauth.clientSecret`) and `auth` — those are left
7
+ * out and flagged, never copied silently (the server's redaction markers are
8
+ * never sent back either).
9
+ *
10
+ * See change: migrate-mcp-to-pi-builtin.
11
+ */
12
+ import type { Provenance } from "../core/types.js";
13
+ import { stripRedacted } from "./schema.js";
14
+
15
+ /**
16
+ * Secret-bearing fields a folder copy must NOT inherit silently. Copied from
17
+ * `core/config-writer.ts` (`FOLDER_COPY_OMITTED`) — that module imports node
18
+ * built-ins, so the browser bundle copies the constant instead.
19
+ */
20
+ const FOLDER_COPY_OMITTED = ["headers", "env", "oauth.clientSecret", "auth"] as const;
21
+
22
+ export interface FolderOverridePrefill {
23
+ /** The entry to open the editor with (secrets + auth removed, sentinels stripped). */
24
+ draft: Record<string, unknown>;
25
+ /** Dotted field names that were present on the global entry and dropped. */
26
+ omitted: string[];
27
+ }
28
+
29
+ function hasPath(entry: Record<string, unknown>, path: string[]): boolean {
30
+ let current: unknown = entry;
31
+ for (const key of path) {
32
+ if (current === null || typeof current !== "object") return false;
33
+ current = (current as Record<string, unknown>)[key];
34
+ }
35
+ return current !== undefined;
36
+ }
37
+
38
+ function deletePath(draft: Record<string, unknown>, path: string[]): void {
39
+ let parent: Record<string, unknown> = draft;
40
+ for (let i = 0; i < path.length - 1; i++) {
41
+ const next = parent[path[i] as string];
42
+ if (next === null || typeof next !== "object") return;
43
+ parent = next as Record<string, unknown>;
44
+ }
45
+ delete parent[path[path.length - 1] as string];
46
+ }
47
+
48
+ /** A copy of a global entry for a folder override, without secrets or `auth`. */
49
+ export function folderOverrideDraftOf(entry: Record<string, unknown>): FolderOverridePrefill {
50
+ // Flag against the RAW entry (the server's redaction sentinels mark the
51
+ // secret fields), then strip the markers and the flagged paths.
52
+ const omitted = FOLDER_COPY_OMITTED.filter((dotted) => hasPath(entry, dotted.split(".")));
53
+ const draft = (stripRedacted(entry) ?? {}) as Record<string, unknown>;
54
+ for (const dotted of omitted) deletePath(draft, dotted.split("."));
55
+ if (Object.keys(draft.oauth ?? {}).length === 0) delete draft.oauth;
56
+ return { draft, omitted };
57
+ }
58
+
59
+ /** UI label for a row's defining layer. */
60
+ export function provenanceLabel(provenance: Provenance): string {
61
+ return provenance === "pi-folder" ? "Pi folder" : "Pi global";
62
+ }
63
+
64
+ /** True when the FOLDER layer defines the server (row editor edits it directly). */
65
+ export function isFolderOwned(provenance: Provenance): boolean {
66
+ return provenance === "pi-folder";
67
+ }