@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,916 @@
1
+ /**
2
+ * mcp-client-plugin · schema-driven server editor.
3
+ *
4
+ * A modal dialog rendering every `ServerEntry` field from the published
5
+ * schema (`schema.ts` owns widget selection; anything unmapped falls back to a
6
+ * validated JSON editor, so no field is ever hidden). ONE transport at a time
7
+ * (tabs; switching clears the other transport's keys). Saving writes the
8
+ * COMPLETE entry (`buildEntry`: unknown fields preserved, redaction sentinels
9
+ * never sent, the inactive transport's keys and project-scope `auth` dropped).
10
+ *
11
+ * The exposure alias `codemode-deferred` displays as `codemode` but is kept
12
+ * unless the operator changes the select. Secret values (schema `x-secret`
13
+ * fields and credential-named env/header keys) render masked with a per-field
14
+ * reveal — except `${NAME}` references and `!` commands, shown as written.
15
+ * A folder override pre-fill arrives with secrets + `auth` already removed and
16
+ * lists them as `omitted` warnings. Renaming or changing the URL of an OAuth
17
+ * HTTP server warns that a new sign-in is needed (pi keys credentials by
18
+ * name + URL). Closing with unsaved changes asks for confirmation.
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, useRef, useState } from "react";
25
+ import { authModeOf, isValidServerName, transportOf } from "../core/pi-rules.js";
26
+ import type { Scope } from "../core/types.js";
27
+ import { ApiError, fetchSchema, saveServer, scopeToWire } from "./api.js";
28
+ import { invalidateEffective } from "./hooks.js";
29
+ import {
30
+ buildEntry,
31
+ clone,
32
+ deepEqual,
33
+ type FieldSchema,
34
+ fieldsOf,
35
+ getPath,
36
+ isMaskedValue,
37
+ type RawText,
38
+ setPath,
39
+ TRANSPORT_FIELDS,
40
+ type Transport,
41
+ validateDraft,
42
+ visibleUnderTransport,
43
+ } from "./schema.js";
44
+
45
+ /** Common fields render at the top; the rest sit behind the Advanced disclosure. */
46
+ const COMMON_FIELDS = new Set([
47
+ "command",
48
+ "args",
49
+ "env",
50
+ "cwd",
51
+ "url",
52
+ "headers",
53
+ "auth",
54
+ "oauth",
55
+ "description",
56
+ "exposure",
57
+ "enabled",
58
+ ]);
59
+ const TABS: Transport[] = ["command", "url"];
60
+
61
+ /** The editor tab an entry opens on: the transport pi picks, as a tab. */
62
+ function initialTab(entry: Record<string, unknown>): Transport {
63
+ return typeof entry.url === "string" && entry.type !== "stdio" ? "url" : "command";
64
+ }
65
+
66
+ const INPUT_CLS =
67
+ "w-full min-h-11 sm:min-h-0 text-xs bg-transparent border border-[var(--border-secondary)] rounded px-1.5 py-1 text-[var(--text-primary)] outline-none focus-visible:ring-1 focus-visible:ring-[var(--accent-primary,#60a5fa)]";
68
+ const BTN_CLS =
69
+ "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";
70
+ const PRIMARY_BTN_CLS = `${BTN_CLS} border-[var(--accent-primary,#60a5fa)] text-[var(--accent-primary,#60a5fa)]`;
71
+ const ERROR_CLS = "text-[11px] text-[var(--status-error,#f87171)] m-0";
72
+
73
+ export interface ServerEditorProps {
74
+ /** `null` → add a new server (the name input starts empty). */
75
+ name: string | null;
76
+ /**
77
+ * The pre-fill: an own-layer entry verbatim for an edit, the global entry
78
+ * minus secrets + `auth` for a folder override, `{}` for add.
79
+ */
80
+ entry: Record<string, unknown>;
81
+ /** Dotted fields an override pre-fill dropped — each renders a warning. */
82
+ omitted?: readonly string[];
83
+ /** Write scope (default global). The folder page passes `{ kind: "project", cwd }`. */
84
+ scope?: Scope;
85
+ /** Folder page: use `mcp-folder-editor` as the dialog testid. */
86
+ dialogTestId?: string;
87
+ onClose: () => void;
88
+ /** Called after a successful write so the page re-fetches. */
89
+ onChanged: () => void;
90
+ }
91
+
92
+ type Translate = ReturnType<typeof useT>;
93
+
94
+ function editorTitle(t: Translate, name: string | null): string {
95
+ if (name === null) return t("mcpEditorAddTitle", undefined, "Add server");
96
+ return t("mcpEditorEditTitle", { name }, `Edit server ${name}`);
97
+ }
98
+
99
+ /** Map a save rejection onto the error state (`ApiError.fields` win over field errors). */
100
+ function failureState(
101
+ e: unknown,
102
+ fieldErrors: Record<string, string>,
103
+ ): { errors?: Record<string, string>; summary: string } {
104
+ if (e instanceof ApiError) {
105
+ const merged = { ...fieldErrors };
106
+ for (const field of e.fields) merged[field] = e.message;
107
+ return { errors: merged, summary: e.message };
108
+ }
109
+ return { summary: String(e) };
110
+ }
111
+
112
+ /** Client-side save blockers: the visible fields' widgets, unknown-field JSON, the name. */
113
+ function collectSaveErrors(
114
+ target: string,
115
+ nameErrorEmpty: string,
116
+ nameErrorInvalid: string,
117
+ fields: FieldSchema[],
118
+ draft: Record<string, unknown>,
119
+ tab: Transport,
120
+ raw: RawText,
121
+ unknownKeys: string[],
122
+ ): Record<string, string> {
123
+ const errors = validateDraft(fields, draft, tab, raw);
124
+ for (const key of unknownKeys) {
125
+ const text = raw[key] ?? JSON.stringify(draft[key]);
126
+ if (text.trim() === "") continue;
127
+ try {
128
+ JSON.parse(text);
129
+ } catch {
130
+ errors[key] = "Invalid JSON";
131
+ }
132
+ }
133
+ if (target === "") errors.name = nameErrorEmpty;
134
+ else if (!isValidServerName(target)) errors.name = nameErrorInvalid;
135
+ return errors;
136
+ }
137
+
138
+ export function ServerEditor({
139
+ name,
140
+ entry,
141
+ omitted,
142
+ scope = { kind: "global" },
143
+ dialogTestId,
144
+ onClose,
145
+ onChanged,
146
+ }: ServerEditorProps): React.ReactElement {
147
+ const t = useT();
148
+ const [schema, setSchema] = useState<Record<string, unknown> | null>(null);
149
+ const [schemaError, setSchemaError] = useState<Error | null>(null);
150
+ const [draft, setDraft] = useState<Record<string, unknown>>(() => clone(entry));
151
+ const [tab, setTab] = useState<Transport>(() => initialTab(entry));
152
+ const [revealed, setRevealed] = useState<ReadonlySet<string>>(() => new Set());
153
+ const [raw, setRaw] = useState<RawText>({});
154
+ const [errors, setErrors] = useState<Record<string, string>>({});
155
+ const [summary, setSummary] = useState<string | null>(null);
156
+ const [serverName, setServerName] = useState(name ?? "");
157
+ const [saving, setSaving] = useState(false);
158
+ // Dirty tracking for the discard guard: against the INITIAL pre-fill.
159
+ const initialDraft = useRef(clone(entry));
160
+ const initialName = name ?? "";
161
+
162
+ useEffect(() => {
163
+ fetchSchema().then(setSchema, (e: unknown) =>
164
+ setSchemaError(e instanceof Error ? e : new Error(String(e))),
165
+ );
166
+ }, []);
167
+
168
+ // Focus moves into the dialog on open and returns to the trigger on close.
169
+ const dialogRef = useRef<HTMLDivElement>(null);
170
+ const triggerRef = useRef<Element | null>(null);
171
+ useEffect(() => {
172
+ triggerRef.current = document.activeElement;
173
+ dialogRef.current?.focus();
174
+ return () => {
175
+ (triggerRef.current as HTMLElement | null)?.focus?.();
176
+ };
177
+ }, []);
178
+
179
+ const fields = schema ? fieldsOf(schema) : [];
180
+ const schemaFieldNames = new Set(fields.map((f) => f.name));
181
+ const visible = fields.filter((f) => visibleUnderTransport(f.name, tab));
182
+ const unknownKeys = Object.keys(draft).filter(
183
+ (k) => !schemaFieldNames.has(k) && getPath(draft, [k]) !== undefined,
184
+ );
185
+
186
+ const write = (path: string[], value: unknown) => setDraft((d) => setPath(d, path, value));
187
+ const toggleReveal = (key: string) =>
188
+ setRevealed((prev) => {
189
+ const next = new Set(prev);
190
+ if (next.has(key)) next.delete(key);
191
+ else next.add(key);
192
+ return next;
193
+ });
194
+ const setRawText = (key: string, value: string) => setRaw((r) => ({ ...r, [key]: value }));
195
+
196
+ function switchTab(next: Transport): void {
197
+ if (next === tab) return;
198
+ setDraft((d) => {
199
+ let next0 = d;
200
+ for (const other of TABS) {
201
+ if (other === next) continue;
202
+ for (const field of TRANSPORT_FIELDS[other]) next0 = setPath(next0, [field], undefined);
203
+ }
204
+ return next0;
205
+ });
206
+ setTab(next);
207
+ }
208
+
209
+ const dirty = !deepEqual(draft, initialDraft.current) || serverName !== initialName;
210
+
211
+ function attemptClose(): void {
212
+ if (dirty && !window.confirm(t("mcpDiscardConfirm", undefined, "Discard unsaved changes?"))) return;
213
+ onClose();
214
+ }
215
+
216
+ // Renaming or re-pointing an OAuth HTTP server needs a fresh sign-in.
217
+ const oauthWarning =
218
+ name !== null &&
219
+ transportOf(entry) === "http" &&
220
+ authModeOf(entry)?.kind === "oauth" &&
221
+ (serverName.trim() !== name || draft.url !== entry.url);
222
+
223
+ async function save(): Promise<void> {
224
+ const target = serverName.trim();
225
+ const allErrors = collectSaveErrors(
226
+ target,
227
+ t("mcpEditorNameRequired", undefined, "Server name is required."),
228
+ t("mcpEditorNameInvalid", undefined, 'Invalid server name (use letters, digits, "_" and "-").'),
229
+ visible,
230
+ draft,
231
+ tab,
232
+ raw,
233
+ unknownKeys,
234
+ );
235
+ if (Object.keys(allErrors).length > 0) {
236
+ setErrors(allErrors);
237
+ setSummary(t("mcpEditorInvalidSummary", undefined, "Fix the errors before saving."));
238
+ return;
239
+ }
240
+ setSaving(true);
241
+ try {
242
+ await saveServer(target, {
243
+ ...scopeToWire(scope),
244
+ entry: buildEntry(draft, tab, scope),
245
+ ...(name !== null && target !== name ? { previousName: name } : {}),
246
+ ...(name === null ? { create: true } : {}),
247
+ });
248
+ invalidateEffective(scope.kind === "project" ? scope.cwd : undefined);
249
+ onChanged();
250
+ onClose();
251
+ } catch (e) {
252
+ const failure = failureState(e, {});
253
+ if (failure.errors) setErrors(failure.errors);
254
+ setSummary(failure.summary);
255
+ } finally {
256
+ setSaving(false);
257
+ }
258
+ }
259
+
260
+ const summaryText = summary ?? (schemaError ? `Could not load the field schema: ${schemaError.message}` : null);
261
+ const title = editorTitle(t, name);
262
+ const projectScope = scope.kind === "project";
263
+
264
+ const ctx: EditorCtx = {
265
+ draft,
266
+ write,
267
+ revealed,
268
+ toggleReveal,
269
+ raw,
270
+ setRawText,
271
+ errors,
272
+ projectScope,
273
+ };
274
+
275
+ return (
276
+ <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center">
277
+ <button
278
+ type="button"
279
+ aria-label={t("mcpEditorClose", undefined, "Close")}
280
+ onClick={attemptClose}
281
+ data-testid="mcp-editor-backdrop"
282
+ className="absolute inset-0 bg-black/40 cursor-default"
283
+ />
284
+ <div
285
+ ref={dialogRef}
286
+ role="dialog"
287
+ aria-modal="true"
288
+ aria-label={title}
289
+ tabIndex={-1}
290
+ data-testid={dialogTestId ?? "mcp-editor-dialog"}
291
+ onKeyDown={(e) => {
292
+ if (e.key === "Escape") attemptClose();
293
+ }}
294
+ className="relative w-full sm:max-w-lg max-h-[85vh] overflow-y-auto bg-[var(--bg-primary)] border border-[var(--border-secondary)] rounded-t-lg sm:rounded-lg p-3 space-y-2 outline-none"
295
+ >
296
+ <h2 className="text-sm font-semibold m-0 text-[var(--text-primary)]">{title}</h2>
297
+
298
+ <EditorNameField value={serverName} onChange={setServerName} error={errors.name} />
299
+ {summaryText && <EditorSummary text={summaryText} errors={errors} />}
300
+ {!schema && <EditorSkeleton />}
301
+ {schema && (
302
+ <>
303
+ {omitted && omitted.length > 0 && <OmittedWarnings omitted={omitted} />}
304
+ {oauthWarning && (
305
+ <p
306
+ data-testid="mcp-oauth-warning"
307
+ role="alert"
308
+ className="text-[11px] text-amber-500 border border-amber-500 rounded px-2 py-1.5 m-0"
309
+ >
310
+ {t(
311
+ "mcpOauthReloginWarning",
312
+ { name: serverName.trim() },
313
+ "Changing the name or URL requires a new sign-in: pi keys OAuth credentials by server name + URL. Run /mcp login after saving.",
314
+ )}
315
+ </p>
316
+ )}
317
+ <TransportTabs tab={tab} onSelect={switchTab} />
318
+ <div className="space-y-2">
319
+ <FieldRows fields={visible.filter((f) => COMMON_FIELDS.has(f.name))} ctx={ctx} />
320
+ </div>
321
+ <AdvancedFields visible={visible} ctx={ctx} />
322
+ {unknownKeys.length > 0 && <UnknownFields keys={unknownKeys} ctx={ctx} />}
323
+ </>
324
+ )}
325
+ <EditorFooter saving={saving} onSave={save} onClose={attemptClose} />
326
+ </div>
327
+ </div>
328
+ );
329
+ }
330
+
331
+ interface EditorCtx {
332
+ draft: Record<string, unknown>;
333
+ write: (path: string[], value: unknown) => void;
334
+ revealed: ReadonlySet<string>;
335
+ toggleReveal: (key: string) => void;
336
+ raw: RawText;
337
+ setRawText: (key: string, value: string) => void;
338
+ errors: Record<string, string>;
339
+ projectScope: boolean;
340
+ }
341
+
342
+ function OmittedWarnings({ omitted }: { omitted: readonly string[] }): React.ReactElement {
343
+ const t = useT();
344
+ return (
345
+ <div
346
+ data-testid="mcp-omitted-warnings"
347
+ role="alert"
348
+ className="text-[11px] text-amber-500 border border-amber-500 rounded px-2 py-1.5 space-y-0.5"
349
+ >
350
+ <p className="m-0 font-medium">
351
+ {t("mcpOmittedHeading", undefined, "Not inherited — re-enter or the folder entry will lack them:")}
352
+ </p>
353
+ {omitted.map((dotted) => (
354
+ <p key={dotted} data-testid={`mcp-omitted-${dotted}`} className="m-0">
355
+ {dotted}
356
+ {dotted === "auth"
357
+ ? t("mcpOmittedAuth", undefined, " — provider auth is global-only; a folder entry cannot carry it.")
358
+ : t("mcpOmittedField", undefined, " — will be absent unless re-entered.")}
359
+ </p>
360
+ ))}
361
+ </div>
362
+ );
363
+ }
364
+
365
+ function EditorNameField({
366
+ value,
367
+ onChange,
368
+ error,
369
+ }: {
370
+ value: string;
371
+ onChange: (value: string) => void;
372
+ error?: string;
373
+ }): React.ReactElement {
374
+ const t = useT();
375
+ return (
376
+ <div data-testid="mcp-field-name" className="space-y-1">
377
+ <span className="block text-[11px] text-[var(--text-secondary)]">
378
+ {t("mcpEditorNameLabel", undefined, "Server name")}
379
+ </span>
380
+ <input
381
+ type="text"
382
+ aria-label={t("mcpEditorNameLabel", undefined, "Server name")}
383
+ data-testid="mcp-editor-name"
384
+ value={value}
385
+ onChange={(e) => onChange(e.target.value)}
386
+ className={INPUT_CLS}
387
+ />
388
+ {error && (
389
+ <p data-testid="mcp-editor-name-error" role="alert" className={ERROR_CLS}>
390
+ {error}
391
+ </p>
392
+ )}
393
+ </div>
394
+ );
395
+ }
396
+
397
+ function EditorSummary({
398
+ text,
399
+ errors,
400
+ }: {
401
+ text: string;
402
+ errors: Record<string, string>;
403
+ }): React.ReactElement {
404
+ return (
405
+ <div
406
+ data-testid="mcp-summary-error"
407
+ role="alert"
408
+ className="text-[11px] text-[var(--status-error,#f87171)] border border-[var(--status-error,#f87171)] rounded px-2 py-1.5 space-y-0.5"
409
+ >
410
+ <p className="m-0">{text}</p>
411
+ {Object.entries(errors).map(([field, message]) => (
412
+ <p key={field} className="m-0">
413
+ {field}: {message}
414
+ </p>
415
+ ))}
416
+ </div>
417
+ );
418
+ }
419
+
420
+ function EditorSkeleton(): React.ReactElement {
421
+ return (
422
+ <div data-testid="mcp-editor-loading" className="space-y-2 py-2">
423
+ {[0, 1, 2].map((i) => (
424
+ <div
425
+ key={i}
426
+ className="h-5 rounded bg-[var(--bg-tertiary,#27272a)] animate-pulse"
427
+ style={{ width: `${100 - i * 15}%` }}
428
+ />
429
+ ))}
430
+ </div>
431
+ );
432
+ }
433
+
434
+ function TransportTabs({
435
+ tab,
436
+ onSelect,
437
+ }: {
438
+ tab: Transport;
439
+ onSelect: (next: Transport) => void;
440
+ }): React.ReactElement {
441
+ const t = useT();
442
+ return (
443
+ <div role="tablist" aria-label={t("mcpEditorTransport", undefined, "Transport")} className="flex gap-1">
444
+ {TABS.map((tr) => (
445
+ <button
446
+ key={tr}
447
+ type="button"
448
+ role="tab"
449
+ aria-selected={tab === tr}
450
+ data-testid={`mcp-tab-${tr}`}
451
+ onClick={() => onSelect(tr)}
452
+ className={`${BTN_CLS} ${tab === tr ? "border-[var(--accent-primary,#60a5fa)] text-[var(--accent-primary,#60a5fa)]" : ""}`}
453
+ >
454
+ {tr}
455
+ </button>
456
+ ))}
457
+ </div>
458
+ );
459
+ }
460
+
461
+ function EditorFooter({
462
+ saving,
463
+ onSave,
464
+ onClose,
465
+ }: {
466
+ saving: boolean;
467
+ onSave: () => Promise<void>;
468
+ onClose: () => void;
469
+ }): React.ReactElement {
470
+ const t = useT();
471
+ return (
472
+ <div data-testid="mcp-editor-footer" className="flex items-center justify-end gap-2 pt-1">
473
+ <button
474
+ type="button"
475
+ onClick={() => void onSave()}
476
+ disabled={saving}
477
+ data-testid="mcp-save"
478
+ className={PRIMARY_BTN_CLS}
479
+ >
480
+ {t("mcpEditorSave", undefined, "Save")}
481
+ </button>
482
+ <button type="button" onClick={onClose} data-testid="mcp-editor-close" className={BTN_CLS}>
483
+ {t("mcpEditorCloseLabel", undefined, "Close")}
484
+ </button>
485
+ </div>
486
+ );
487
+ }
488
+
489
+ // ─── field rendering ─────────────────────────────────────────────────────────
490
+
491
+ function FieldRows({ fields, ctx }: { fields: FieldSchema[]; ctx: EditorCtx }): React.ReactElement {
492
+ return (
493
+ <>
494
+ {fields.map((f) => (
495
+ <FieldRow key={f.name} field={f} ctx={ctx} />
496
+ ))}
497
+ </>
498
+ );
499
+ }
500
+
501
+ function AdvancedFields({ visible, ctx }: { visible: FieldSchema[]; ctx: EditorCtx }): React.ReactElement {
502
+ const t = useT();
503
+ return (
504
+ <details data-testid="mcp-advanced" className="border border-[var(--border-secondary)] rounded p-1.5">
505
+ <summary className="text-[11px] text-[var(--text-secondary)] cursor-pointer min-h-11 sm:min-h-0 flex items-center">
506
+ {t("mcpEditorAdvanced", undefined, "Advanced")}
507
+ </summary>
508
+ <div className="space-y-2 pt-2">
509
+ <FieldRows fields={visible.filter((f) => !COMMON_FIELDS.has(f.name))} ctx={ctx} />
510
+ </div>
511
+ </details>
512
+ );
513
+ }
514
+
515
+ function FieldRow({ field, ctx }: { field: FieldSchema; ctx: EditorCtx }): React.ReactElement {
516
+ return (
517
+ <div data-testid={`mcp-field-${field.name}`} className="space-y-1">
518
+ <span className="block text-[11px] text-[var(--text-secondary)]">{field.name}</span>
519
+ {field.globalOnly && ctx.projectScope ? (
520
+ <p data-testid="mcp-global-only-auth" className="text-[11px] text-[var(--text-secondary)] m-0">
521
+ provider auth is global-only: pi reads auth only from ~/.pi/agent/mcp.json, so a folder
522
+ entry cannot set it.
523
+ </p>
524
+ ) : (
525
+ <FieldControl field={field} ctx={ctx} />
526
+ )}
527
+ {ctx.errors[field.name] && (
528
+ <p data-testid={`mcp-field-error-${field.name}`} role="alert" className={ERROR_CLS}>
529
+ {ctx.errors[field.name]}
530
+ </p>
531
+ )}
532
+ </div>
533
+ );
534
+ }
535
+
536
+ function FieldControl({ field, ctx }: { field: FieldSchema; ctx: EditorCtx }): React.ReactElement {
537
+ switch (field.widget) {
538
+ case "text":
539
+ return <TextControl field={field} ctx={ctx} />;
540
+ case "number":
541
+ return <NumberControl field={field} ctx={ctx} />;
542
+ case "boolean":
543
+ return <BooleanControl field={field} ctx={ctx} />;
544
+ case "enum":
545
+ return <EnumControl field={field} ctx={ctx} />;
546
+ case "string-list": {
547
+ const rows = asStrings(getPath(ctx.draft, field.path));
548
+ return (
549
+ <StringListEditor
550
+ field={field}
551
+ rows={rows}
552
+ onRows={(next) => ctx.write(field.path, next.length === 0 ? undefined : next)}
553
+ />
554
+ );
555
+ }
556
+ case "record":
557
+ return <RecordControl field={field} ctx={ctx} />;
558
+ case "nested-group":
559
+ return (
560
+ <div className="space-y-2 border-l border-[var(--border-secondary)] pl-2">
561
+ {(field.children ?? []).map((child) => (
562
+ <FieldRow key={child.name} field={child} ctx={ctx} />
563
+ ))}
564
+ </div>
565
+ );
566
+ default:
567
+ return <JsonControl field={field} ctx={ctx} />;
568
+ }
569
+ }
570
+
571
+ function asStrings(value: unknown): string[] {
572
+ return Array.isArray(value) ? value.map((v) => String(v)) : [];
573
+ }
574
+
575
+ function RevealButton({ name, shown, ctx }: { name: string; shown: boolean; ctx: EditorCtx }): React.ReactElement {
576
+ const t = useT();
577
+ return (
578
+ <button
579
+ type="button"
580
+ data-testid={`mcp-reveal-${name}`}
581
+ aria-pressed={shown}
582
+ aria-label={shown ? t("mcpHide", { name }, `Hide ${name}`) : t("mcpReveal", { name }, `Reveal ${name}`)}
583
+ onClick={() => ctx.toggleReveal(name)}
584
+ className={BTN_CLS}
585
+ >
586
+ {shown ? t("mcpHideLabel", undefined, "Hide") : t("mcpRevealLabel", undefined, "Show")}
587
+ </button>
588
+ );
589
+ }
590
+
591
+ function TextControl({ field, ctx }: { field: FieldSchema; ctx: EditorCtx }): React.ReactElement {
592
+ const value = getPath(ctx.draft, field.path);
593
+ if (field.secret) return <SecretTextControl field={field} ctx={ctx} value={value} />;
594
+ return (
595
+ <input
596
+ type="text"
597
+ aria-label={field.name}
598
+ data-testid={`mcp-field-input-${field.name}`}
599
+ value={typeof value === "string" ? value : ""}
600
+ onChange={(e) => ctx.write(field.path, e.target.value)}
601
+ className={INPUT_CLS}
602
+ />
603
+ );
604
+ }
605
+
606
+ function SecretTextControl({
607
+ field,
608
+ ctx,
609
+ value,
610
+ }: {
611
+ field: FieldSchema;
612
+ ctx: EditorCtx;
613
+ value: unknown;
614
+ }): React.ReactElement {
615
+ const shown = ctx.revealed.has(field.name);
616
+ // A ${NAME} reference or !command is a pointer, not a secret: show as written.
617
+ const inputType = shown || !isMaskedValue(true, field.name, value) ? "text" : "password";
618
+ return (
619
+ <span className="flex items-center gap-1">
620
+ <input
621
+ type={inputType}
622
+ aria-label={field.name}
623
+ data-testid={`mcp-field-input-${field.name}`}
624
+ value={typeof value === "string" ? value : ""}
625
+ onChange={(e) => ctx.write(field.path, e.target.value)}
626
+ className={INPUT_CLS}
627
+ />
628
+ <RevealButton name={field.name} shown={shown} ctx={ctx} />
629
+ </span>
630
+ );
631
+ }
632
+
633
+ function NumberControl({ field, ctx }: { field: FieldSchema; ctx: EditorCtx }): React.ReactElement {
634
+ const value = getPath(ctx.draft, field.path);
635
+ const text = ctx.raw[field.name] ?? (typeof value === "number" ? String(value) : "");
636
+ return (
637
+ <input
638
+ type="number"
639
+ aria-label={field.name}
640
+ data-testid={`mcp-field-input-${field.name}`}
641
+ value={text}
642
+ onChange={(e) => {
643
+ ctx.setRawText(field.name, e.target.value);
644
+ if (e.target.value.trim() === "") ctx.write(field.path, undefined);
645
+ else {
646
+ const parsed = Number(e.target.value);
647
+ if (Number.isFinite(parsed)) ctx.write(field.path, parsed);
648
+ }
649
+ }}
650
+ className={INPUT_CLS}
651
+ />
652
+ );
653
+ }
654
+
655
+ function BooleanControl({ field, ctx }: { field: FieldSchema; ctx: EditorCtx }): React.ReactElement {
656
+ const value = getPath(ctx.draft, field.path);
657
+ return (
658
+ // The label is the hit area: a 16px box cannot meet the 44px mobile floor.
659
+ <label className="inline-flex items-center justify-center min-h-11 min-w-11 sm:min-h-0 sm:min-w-0">
660
+ <input
661
+ type="checkbox"
662
+ aria-label={field.name}
663
+ data-testid={`mcp-field-input-${field.name}`}
664
+ checked={value === true}
665
+ onChange={(e) => ctx.write(field.path, e.target.checked)}
666
+ className="w-4 h-4 flex-none"
667
+ />
668
+ </label>
669
+ );
670
+ }
671
+
672
+ function EnumControl({ field, ctx }: { field: FieldSchema; ctx: EditorCtx }): React.ReactElement {
673
+ const t = useT();
674
+ const value = getPath(ctx.draft, field.path);
675
+ // The stored alias displays resolved (`codemode-deferred` → `codemode`) but
676
+ // is kept unless the operator picks another option.
677
+ const display =
678
+ value !== undefined && field.displayResolver ? field.displayResolver(value) : value;
679
+ return (
680
+ <select
681
+ aria-label={field.name}
682
+ data-testid={`mcp-field-input-${field.name}`}
683
+ value={value === undefined ? "" : String(display)}
684
+ onChange={(e) => ctx.write(field.path, e.target.value === "" ? undefined : e.target.value)}
685
+ className={INPUT_CLS}
686
+ >
687
+ <option value="">{t("mcpEnumInherit", undefined, "(inherit)")}</option>
688
+ {(field.enumValues ?? []).map((option) => (
689
+ <option key={option} value={option}>
690
+ {option}
691
+ </option>
692
+ ))}
693
+ </select>
694
+ );
695
+ }
696
+
697
+ function StringListEditor({
698
+ field,
699
+ rows,
700
+ onRows,
701
+ }: {
702
+ field: FieldSchema;
703
+ rows: string[];
704
+ onRows: (rows: string[]) => void;
705
+ }): React.ReactElement {
706
+ const t = useT();
707
+ return (
708
+ <div className="space-y-1">
709
+ {rows.map((row, i) => (
710
+ <div key={i} className="flex items-center gap-1">
711
+ <input
712
+ aria-label={`${field.name} ${i + 1}`}
713
+ data-testid={`mcp-list-input-${field.name}-${i}`}
714
+ value={row}
715
+ onChange={(e) => onRows(rows.map((r, j) => (j === i ? e.target.value : r)))}
716
+ className={INPUT_CLS}
717
+ />
718
+ <button
719
+ type="button"
720
+ aria-label={t("mcpRemoveRow", undefined, "Remove row")}
721
+ data-testid={`mcp-list-remove-${field.name}-${i}`}
722
+ onClick={() => onRows(rows.filter((_, j) => j !== i))}
723
+ className={BTN_CLS}
724
+ >
725
+ −
726
+ </button>
727
+ </div>
728
+ ))}
729
+ <button
730
+ type="button"
731
+ aria-label={t("mcpAddRow", undefined, "Add row")}
732
+ data-testid={`mcp-list-add-${field.name}`}
733
+ onClick={() => onRows([...rows, ""])}
734
+ className={BTN_CLS}
735
+ >
736
+ + {t("mcpAddRowLabel", undefined, "Add")}
737
+ </button>
738
+ </div>
739
+ );
740
+ }
741
+
742
+ function RecordControl({ field, ctx }: { field: FieldSchema; ctx: EditorCtx }): React.ReactElement {
743
+ const t = useT();
744
+ const value = getPath(ctx.draft, field.path);
745
+ const rows =
746
+ value !== null && typeof value === "object" && !Array.isArray(value)
747
+ ? (value as Record<string, unknown>)
748
+ : {};
749
+ const writeRecord = (next: Record<string, unknown>) => ctx.write(field.path, next);
750
+
751
+ return (
752
+ <div className="space-y-1" data-testid={`mcp-record-${field.name}`}>
753
+ {Object.entries(rows).map(([key, entry]) => {
754
+ const rowName = `${field.name}.${key}`;
755
+ const masked = isMaskedValue(field.secret, key, entry);
756
+ const shown = ctx.revealed.has(rowName);
757
+ return (
758
+ <div key={key} data-testid={`mcp-record-row-${rowName}`} className="flex items-center gap-1">
759
+ <input
760
+ aria-label={`${rowName} key`}
761
+ data-testid={`mcp-record-key-${rowName}`}
762
+ value={key}
763
+ onChange={(e) => {
764
+ const next = { ...rows };
765
+ delete next[key];
766
+ next[e.target.value] = entry;
767
+ writeRecord(next);
768
+ }}
769
+ className={`${INPUT_CLS} w-1/3`}
770
+ />
771
+ {field.valueEnum ? (
772
+ <select
773
+ aria-label={`${rowName} exposure`}
774
+ data-testid={`mcp-record-value-${rowName}`}
775
+ value={field.displayResolver ? field.displayResolver(entry) : String(entry)}
776
+ onChange={(e) => {
777
+ const next = { ...rows };
778
+ if (e.target.value === "") delete next[key];
779
+ else next[key] = e.target.value;
780
+ writeRecord(next);
781
+ }}
782
+ className={`${INPUT_CLS}`}
783
+ >
784
+ <option value="">{t("mcpEnumInherit", undefined, "(inherit)")}</option>
785
+ {field.valueEnum.map((option) => (
786
+ <option key={option} value={option}>
787
+ {option}
788
+ </option>
789
+ ))}
790
+ </select>
791
+ ) : typeof entry === "string" ? (
792
+ <>
793
+ <input
794
+ type={masked && !shown ? "password" : "text"}
795
+ aria-label={`${rowName} value`}
796
+ data-testid={`mcp-record-value-${rowName}`}
797
+ value={entry}
798
+ onChange={(e) => writeRecord({ ...rows, [key]: e.target.value })}
799
+ className={INPUT_CLS}
800
+ />
801
+ {masked && <RevealButton name={rowName} shown={shown} ctx={ctx} />}
802
+ </>
803
+ ) : (
804
+ <textarea
805
+ aria-label={`${rowName} value (JSON)`}
806
+ data-testid={`mcp-record-value-${rowName}`}
807
+ rows={2}
808
+ value={ctx.raw[rowName] ?? JSON.stringify(entry)}
809
+ onChange={(e) => {
810
+ ctx.setRawText(rowName, e.target.value);
811
+ try {
812
+ writeRecord({ ...rows, [key]: JSON.parse(e.target.value) });
813
+ } catch {
814
+ /* keep the last parsed value; validation flags the raw text */
815
+ }
816
+ }}
817
+ className={`${INPUT_CLS} font-mono`}
818
+ />
819
+ )}
820
+ <button
821
+ type="button"
822
+ aria-label={t("mcpRemoveRow", undefined, "Remove row")}
823
+ data-testid={`mcp-record-remove-${rowName}`}
824
+ onClick={() => {
825
+ const next = { ...rows };
826
+ delete next[key];
827
+ writeRecord(next);
828
+ }}
829
+ className={BTN_CLS}
830
+ >
831
+ −
832
+ </button>
833
+ </div>
834
+ );
835
+ })}
836
+ <button
837
+ type="button"
838
+ aria-label={t("mcpAddEntry", { name: field.name }, `Add ${field.name} entry`)}
839
+ data-testid={`mcp-record-add-${field.name}`}
840
+ onClick={() => writeRecord({ ...rows, "": field.valueEnum ? "" : "" })}
841
+ className={BTN_CLS}
842
+ >
843
+ + {t("mcpAddRowLabel", undefined, "Add")}
844
+ </button>
845
+ </div>
846
+ );
847
+ }
848
+
849
+ function JsonControl({ field, ctx }: { field: FieldSchema; ctx: EditorCtx }): React.ReactElement {
850
+ const value = getPath(ctx.draft, field.path);
851
+ const text = ctx.raw[field.name] ?? (value === undefined ? "" : JSON.stringify(value, null, 2));
852
+ return (
853
+ <textarea
854
+ aria-label={field.name}
855
+ data-testid={`mcp-field-input-${field.name}`}
856
+ rows={3}
857
+ value={text}
858
+ onChange={(e) => {
859
+ ctx.setRawText(field.name, e.target.value);
860
+ if (e.target.value.trim() === "") ctx.write(field.path, undefined);
861
+ else {
862
+ try {
863
+ ctx.write(field.path, JSON.parse(e.target.value));
864
+ } catch {
865
+ /* keep the last parsed value; validation flags the raw text */
866
+ }
867
+ }
868
+ }}
869
+ className={`${INPUT_CLS} font-mono`}
870
+ />
871
+ );
872
+ }
873
+
874
+ /** Top-level keys with no schema field: a validated JSON editor each, preserved on save. */
875
+ function UnknownFields({ keys, ctx }: { keys: string[]; ctx: EditorCtx }): React.ReactElement {
876
+ const t = useT();
877
+ return (
878
+ <div data-testid="mcp-unknown-fields" className="space-y-2 border border-[var(--border-secondary)] rounded p-1.5">
879
+ <span className="block text-[11px] text-[var(--text-secondary)]">
880
+ {t("mcpUnknownFields", undefined, "Other fields (JSON)")}
881
+ </span>
882
+ {keys.map((key) => {
883
+ const value = ctx.draft[key];
884
+ const text = ctx.raw[key] ?? (value === undefined ? "" : JSON.stringify(value, null, 2));
885
+ return (
886
+ <div key={key} className="space-y-1">
887
+ <span className="block text-[11px] text-[var(--text-secondary)]">{key}</span>
888
+ <textarea
889
+ aria-label={key}
890
+ data-testid={`mcp-unknown-field-input-${key}`}
891
+ rows={3}
892
+ value={text}
893
+ onChange={(e) => {
894
+ ctx.setRawText(key, e.target.value);
895
+ if (e.target.value.trim() === "") ctx.write([key], undefined);
896
+ else {
897
+ try {
898
+ ctx.write([key], JSON.parse(e.target.value));
899
+ } catch {
900
+ /* keep the last parsed value; save validation flags the raw text */
901
+ }
902
+ }
903
+ }}
904
+ className={`${INPUT_CLS} font-mono`}
905
+ />
906
+ {ctx.errors[key] && (
907
+ <p data-testid={`mcp-unknown-field-error-${key}`} role="alert" className={ERROR_CLS}>
908
+ {ctx.errors[key]}
909
+ </p>
910
+ )}
911
+ </div>
912
+ );
913
+ })}
914
+ </div>
915
+ );
916
+ }