pi-mcp-adapter 2.4.0 → 2.4.2

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.
package/index.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { ExtensionAPI, ToolInfo } from "@mariozechner/pi-coding-agent";
2
2
  import type { McpExtensionState } from "./state.js";
3
- import { Type } from "@sinclair/typebox";
4
- import { showStatus, showTools, reconnectServers, authenticateServer, openMcpPanel } from "./commands.js";
3
+ import { Type } from "typebox";
4
+ import { showStatus, showTools, reconnectServers, authenticateServer, openMcpPanel, openMcpSetup } from "./commands.js";
5
5
  import { loadMcpConfig } from "./config.js";
6
6
  import { buildProxyDescription, createDirectToolExecutor, getMissingConfiguredDirectToolServers, resolveDirectTools } from "./direct-tools.js";
7
7
  import { flushMetadataCache, initializeMcp, updateStatusBar } from "./init.js";
@@ -178,11 +178,23 @@ export default function mcpAdapter(pi: ExtensionAPI) {
178
178
  case "tools":
179
179
  await showTools(state, ctx);
180
180
  break;
181
+ case "setup": {
182
+ const result = await openMcpSetup(state, pi, ctx, earlyConfigPath, "setup");
183
+ if (result?.configChanged) {
184
+ await ctx.reload();
185
+ return;
186
+ }
187
+ break;
188
+ }
181
189
  case "status":
182
190
  case "":
183
191
  default:
184
192
  if (ctx.hasUI) {
185
- await openMcpPanel(state, pi, ctx, earlyConfigPath);
193
+ const result = await openMcpPanel(state, pi, ctx, earlyConfigPath);
194
+ if (result?.configChanged) {
195
+ await ctx.reload();
196
+ return;
197
+ }
186
198
  } else {
187
199
  await showStatus(state, ctx);
188
200
  }
package/mcp-panel.ts CHANGED
@@ -108,6 +108,7 @@ interface VisibleItem {
108
108
  }
109
109
 
110
110
  class McpPanel {
111
+ private noticeLines: string[];
111
112
  private prefix: "server" | "none" | "short";
112
113
  private servers: ServerState[] = [];
113
114
  private cursorIndex = 0;
@@ -134,8 +135,10 @@ class McpPanel {
134
135
  private callbacks: McpPanelCallbacks,
135
136
  tui: { requestRender(): void },
136
137
  private done: (result: McpPanelResult) => void,
138
+ noticeLines: string[] = [],
137
139
  ) {
138
140
  this.tui = tui;
141
+ this.noticeLines = noticeLines;
139
142
  this.prefix = config.settings?.toolPrefix ?? "server";
140
143
 
141
144
  for (const [serverName, definition] of Object.entries(config.mcpServers)) {
@@ -566,6 +569,12 @@ class McpPanel {
566
569
  }
567
570
 
568
571
  lines.push(emptyRow());
572
+ if (this.noticeLines.length > 0) {
573
+ for (const notice of this.noticeLines) {
574
+ lines.push(row(fg(t.hint, italic(notice))));
575
+ }
576
+ lines.push(emptyRow());
577
+ }
569
578
  lines.push(divider());
570
579
 
571
580
  if (this.servers.length === 0) {
@@ -735,6 +744,7 @@ export function createMcpPanel(
735
744
  callbacks: McpPanelCallbacks,
736
745
  tui: { requestRender(): void },
737
746
  done: (result: McpPanelResult) => void,
747
+ options?: { noticeLines?: string[] },
738
748
  ): McpPanel & { dispose(): void } {
739
- return new McpPanel(config, cache, provenance, callbacks, tui, done);
749
+ return new McpPanel(config, cache, provenance, callbacks, tui, done, options?.noticeLines ?? []);
740
750
  }
@@ -0,0 +1,576 @@
1
+ import { matchesKey, truncateToWidth, visibleWidth } from "@mariozechner/pi-tui";
2
+ import type { ImportKind } from "./types.js";
3
+ import type { ConfigWritePreview, McpDiscoverySummary } from "./config.js";
4
+ import type { McpOnboardingState } from "./onboarding-state.js";
5
+
6
+ interface SetupTheme {
7
+ border: string;
8
+ title: string;
9
+ selected: string;
10
+ hint: string;
11
+ success: string;
12
+ warning: string;
13
+ muted: string;
14
+ }
15
+
16
+ const DEFAULT_THEME: SetupTheme = {
17
+ border: "2",
18
+ title: "36",
19
+ selected: "32",
20
+ hint: "2",
21
+ success: "32",
22
+ warning: "33",
23
+ muted: "2;3",
24
+ };
25
+
26
+ function fg(code: string, text: string): string {
27
+ return code ? `\x1b[${code}m${text}\x1b[0m` : text;
28
+ }
29
+
30
+ function wrapText(text: string, width: number): string[] {
31
+ if (width <= 8) return [text];
32
+ const words = text.split(/\s+/).filter(Boolean);
33
+ const lines: string[] = [];
34
+ let current = "";
35
+ for (const word of words) {
36
+ const candidate = current ? `${current} ${word}` : word;
37
+ if (visibleWidth(candidate) <= width) {
38
+ current = candidate;
39
+ continue;
40
+ }
41
+ if (current) lines.push(current);
42
+ current = word;
43
+ }
44
+ if (current) lines.push(current);
45
+ return lines.length > 0 ? lines : [""];
46
+ }
47
+
48
+ export interface SetupPanelCallbacks {
49
+ previewImports: (imports: ImportKind[]) => ConfigWritePreview;
50
+ previewStarterProject: () => ConfigWritePreview;
51
+ previewRepoPrompt: () => ConfigWritePreview | null;
52
+ adoptImports: (imports: ImportKind[]) => Promise<{ added: ImportKind[]; path: string }>;
53
+ scaffoldProjectConfig: () => Promise<{ path: string }>;
54
+ addRepoPrompt: () => Promise<{ path: string; serverName: string }>;
55
+ openPath: (path: string) => Promise<void>;
56
+ markSetupCompleted: () => void;
57
+ }
58
+
59
+ export interface SetupPanelOptions {
60
+ mode: "empty" | "setup";
61
+ onboardingState: McpOnboardingState;
62
+ }
63
+
64
+ type Screen = "empty" | "setup" | "imports" | "paths";
65
+
66
+ type ActionId =
67
+ | "run-setup"
68
+ | "adopt-imports"
69
+ | "view-example"
70
+ | "show-precedence"
71
+ | "open-paths"
72
+ | "add-repoprompt"
73
+ | "scaffold-project"
74
+ | "close";
75
+
76
+ interface Action {
77
+ id: ActionId;
78
+ label: string;
79
+ description: string;
80
+ }
81
+
82
+ export class McpSetupPanel {
83
+ private screen: Screen;
84
+ private actionCursor = 0;
85
+ private importCursor = 0;
86
+ private pathCursor = 0;
87
+ private selectedImports = new Set<ImportKind>();
88
+ private busy = false;
89
+ private notice: { text: string; tone: "success" | "warning" | "muted" } | null = null;
90
+ private tui: { requestRender(): void };
91
+ private t = DEFAULT_THEME;
92
+ private inactivityTimeout: ReturnType<typeof setTimeout> | null = null;
93
+ private static readonly INACTIVITY_MS = 60_000;
94
+
95
+ constructor(
96
+ private discovery: McpDiscoverySummary,
97
+ private callbacks: SetupPanelCallbacks,
98
+ private options: SetupPanelOptions,
99
+ tui: { requestRender(): void },
100
+ private done: () => void,
101
+ ) {
102
+ this.tui = tui;
103
+ this.screen = options.mode;
104
+ for (const entry of discovery.imports) {
105
+ this.selectedImports.add(entry.kind);
106
+ }
107
+ this.resetInactivityTimeout();
108
+ }
109
+
110
+ private resetInactivityTimeout(): void {
111
+ if (this.inactivityTimeout) clearTimeout(this.inactivityTimeout);
112
+ this.inactivityTimeout = setTimeout(() => {
113
+ this.cleanup();
114
+ this.done();
115
+ }, McpSetupPanel.INACTIVITY_MS);
116
+ }
117
+
118
+ private cleanup(): void {
119
+ if (this.inactivityTimeout) {
120
+ clearTimeout(this.inactivityTimeout);
121
+ this.inactivityTimeout = null;
122
+ }
123
+ }
124
+
125
+ private getActions(): Action[] {
126
+ const actions: Action[] = [];
127
+ if (this.screen === "empty") {
128
+ actions.push({ id: "run-setup", label: "Run setup", description: "Inspect detected configs, adopt imports, and scaffold a minimal `.mcp.json`." });
129
+ }
130
+ if (this.discovery.imports.length > 0) {
131
+ actions.push({ id: "adopt-imports", label: "Adopt detected compatibility imports", description: `Choose which host-specific MCP configs Pi should import into its own override file. ${this.discovery.imports.length} source${this.discovery.imports.length === 1 ? "" : "s"} found.` });
132
+ }
133
+ actions.push({ id: "view-example", label: "View example `.mcp.json`", description: "Preview a working shared MCP config you can paste or adapt." });
134
+ if (!this.discovery.sources.some((source) => source.id === "shared-project" && source.exists)) {
135
+ actions.push({ id: "scaffold-project", label: "Scaffold project `.mcp.json`", description: "Write a minimal project config using the standard shared MCP file path, then reload Pi." });
136
+ }
137
+ actions.push({ id: "show-precedence", label: "Explain config precedence", description: "Show the read order and where Pi writes compatibility settings." });
138
+ if (this.getDetectedPaths().length > 0) {
139
+ actions.push({ id: "open-paths", label: "Open detected config paths", description: "Browse the actual config files that Pi discovered on this machine." });
140
+ }
141
+ if (!this.discovery.repoPrompt.configured && this.discovery.repoPrompt.executablePath && this.discovery.repoPrompt.targetPath && this.discovery.repoPrompt.entry && this.discovery.repoPrompt.serverName) {
142
+ actions.push({ id: "add-repoprompt", label: "Add RepoPrompt to shared MCP config", description: "Write a standard MCP entry for RepoPrompt to the recommended shared target, then reload MCP in-session." });
143
+ }
144
+ actions.push({ id: "close", label: "Close", description: "Exit the onboarding flow." });
145
+ return actions;
146
+ }
147
+
148
+ private getDetectedPaths(): string[] {
149
+ const paths = [
150
+ ...this.discovery.sources.filter((source) => source.exists).map((source) => source.path),
151
+ ...this.discovery.imports.map((entry) => entry.path),
152
+ ];
153
+ return [...new Set(paths)];
154
+ }
155
+
156
+ private getSelectedAction(): Action | null {
157
+ const actions = this.getActions();
158
+ return actions[this.actionCursor] ?? null;
159
+ }
160
+
161
+ handleInput(data: string): void {
162
+ this.resetInactivityTimeout();
163
+ if (!this.busy) this.notice = null;
164
+
165
+ if (matchesKey(data, "ctrl+c")) {
166
+ this.cleanup();
167
+ this.done();
168
+ return;
169
+ }
170
+
171
+ if (matchesKey(data, "escape")) {
172
+ if (this.screen === "imports" || this.screen === "paths") {
173
+ this.screen = this.discovery.hasAnyConfig ? "setup" : "empty";
174
+ this.tui.requestRender();
175
+ return;
176
+ }
177
+ this.cleanup();
178
+ this.done();
179
+ return;
180
+ }
181
+
182
+ if (this.busy) return;
183
+
184
+ if (this.screen === "imports") {
185
+ this.handleImportsInput(data);
186
+ return;
187
+ }
188
+ if (this.screen === "paths") {
189
+ this.handlePathsInput(data);
190
+ return;
191
+ }
192
+
193
+ const actions = this.getActions();
194
+ if (matchesKey(data, "up")) {
195
+ this.actionCursor = Math.max(0, this.actionCursor - 1);
196
+ this.tui.requestRender();
197
+ return;
198
+ }
199
+ if (matchesKey(data, "down")) {
200
+ this.actionCursor = Math.min(actions.length - 1, this.actionCursor + 1);
201
+ this.tui.requestRender();
202
+ return;
203
+ }
204
+ if (matchesKey(data, "return")) {
205
+ const selected = this.getSelectedAction();
206
+ if (selected) void this.runAction(selected.id);
207
+ }
208
+ }
209
+
210
+ private handleImportsInput(data: string): void {
211
+ const imports = this.discovery.imports;
212
+ if (matchesKey(data, "up")) {
213
+ this.importCursor = Math.max(0, this.importCursor - 1);
214
+ this.tui.requestRender();
215
+ return;
216
+ }
217
+ if (matchesKey(data, "down")) {
218
+ this.importCursor = Math.min(imports.length - 1, this.importCursor + 1);
219
+ this.tui.requestRender();
220
+ return;
221
+ }
222
+ if (matchesKey(data, "space")) {
223
+ const current = imports[this.importCursor];
224
+ if (!current) return;
225
+ if (this.selectedImports.has(current.kind)) {
226
+ this.selectedImports.delete(current.kind);
227
+ } else {
228
+ this.selectedImports.add(current.kind);
229
+ }
230
+ this.tui.requestRender();
231
+ return;
232
+ }
233
+ if (matchesKey(data, "return")) {
234
+ void this.applySelectedImports();
235
+ }
236
+ }
237
+
238
+ private handlePathsInput(data: string): void {
239
+ const paths = this.getDetectedPaths();
240
+ if (matchesKey(data, "up")) {
241
+ this.pathCursor = Math.max(0, this.pathCursor - 1);
242
+ this.tui.requestRender();
243
+ return;
244
+ }
245
+ if (matchesKey(data, "down")) {
246
+ this.pathCursor = Math.min(paths.length - 1, this.pathCursor + 1);
247
+ this.tui.requestRender();
248
+ return;
249
+ }
250
+ if (matchesKey(data, "return")) {
251
+ const selected = paths[this.pathCursor];
252
+ if (!selected) return;
253
+ void this.runBusy(async () => {
254
+ await this.callbacks.openPath(selected);
255
+ this.notice = { text: `Opened ${selected}`, tone: "success" };
256
+ });
257
+ }
258
+ }
259
+
260
+ private async runAction(action: ActionId): Promise<void> {
261
+ if (action === "run-setup") {
262
+ this.screen = "setup";
263
+ this.actionCursor = 0;
264
+ this.tui.requestRender();
265
+ return;
266
+ }
267
+ if (action === "adopt-imports") {
268
+ this.screen = "imports";
269
+ this.importCursor = 0;
270
+ this.tui.requestRender();
271
+ return;
272
+ }
273
+ if (action === "open-paths") {
274
+ this.screen = "paths";
275
+ this.pathCursor = 0;
276
+ this.tui.requestRender();
277
+ return;
278
+ }
279
+ if (action === "scaffold-project") {
280
+ await this.runBusy(async () => {
281
+ const result = await this.callbacks.scaffoldProjectConfig();
282
+ this.callbacks.markSetupCompleted();
283
+ this.notice = { text: `Wrote starter config to ${result.path}. Pi will reload after this panel closes.`, tone: "success" };
284
+ });
285
+ return;
286
+ }
287
+ if (action === "add-repoprompt") {
288
+ await this.runBusy(async () => {
289
+ const result = await this.callbacks.addRepoPrompt();
290
+ this.callbacks.markSetupCompleted();
291
+ this.notice = { text: `Added ${result.serverName} to ${result.path}. Pi will reload after this panel closes.`, tone: "success" };
292
+ });
293
+ return;
294
+ }
295
+ if (action === "close") {
296
+ this.cleanup();
297
+ this.done();
298
+ return;
299
+ }
300
+
301
+ this.notice = { text: "Review the details below. Press Enter on an action with a side effect to apply it.", tone: "muted" };
302
+ this.tui.requestRender();
303
+ }
304
+
305
+ private async applySelectedImports(): Promise<void> {
306
+ const selected = this.discovery.imports.filter((entry) => this.selectedImports.has(entry.kind)).map((entry) => entry.kind);
307
+ if (selected.length === 0) {
308
+ this.notice = { text: "Select at least one compatibility import first.", tone: "warning" };
309
+ this.tui.requestRender();
310
+ return;
311
+ }
312
+
313
+ await this.runBusy(async () => {
314
+ const result = await this.callbacks.adoptImports(selected);
315
+ this.callbacks.markSetupCompleted();
316
+ this.notice = result.added.length > 0
317
+ ? { text: `Added ${result.added.join(", ")} to ${result.path}. Pi will reload after this panel closes.`, tone: "success" }
318
+ : { text: `No changes needed in ${result.path}.`, tone: "muted" };
319
+ this.screen = this.discovery.hasAnyConfig ? "setup" : "empty";
320
+ this.actionCursor = 0;
321
+ });
322
+ }
323
+
324
+ private async runBusy(fn: () => Promise<void>): Promise<void> {
325
+ this.busy = true;
326
+ this.notice = { text: "Working...", tone: "muted" };
327
+ this.tui.requestRender();
328
+ try {
329
+ await fn();
330
+ } catch (error) {
331
+ this.notice = {
332
+ text: error instanceof Error ? error.message : String(error),
333
+ tone: "warning",
334
+ };
335
+ } finally {
336
+ this.busy = false;
337
+ this.tui.requestRender();
338
+ }
339
+ }
340
+
341
+ render(width: number): string[] {
342
+ const innerW = Math.max(40, width - 2);
343
+ const lines: string[] = [];
344
+ const border = fg(this.t.border, "─".repeat(innerW));
345
+ lines.push(`┌${border}┐`);
346
+ lines.push(this.padLine(fg(this.t.title, "MCP setup"), innerW));
347
+ lines.push(this.padLine(this.discoverySummaryLine(), innerW));
348
+ lines.push(this.padLine(fg(this.t.muted, this.secondarySummaryLine()), innerW));
349
+ lines.push(this.padLine("", innerW));
350
+
351
+ if (this.notice) {
352
+ const tone = this.notice.tone === "success" ? this.t.success : this.notice.tone === "warning" ? this.t.warning : this.t.hint;
353
+ for (const line of wrapText(this.notice.text, innerW - 6)) {
354
+ lines.push(this.padLine(fg(tone, line), innerW));
355
+ }
356
+ lines.push(this.padLine("", innerW));
357
+ }
358
+
359
+ lines.push(`├${border}┤`);
360
+
361
+ if (this.screen === "imports") {
362
+ lines.push(...this.renderImports(innerW));
363
+ } else if (this.screen === "paths") {
364
+ lines.push(...this.renderPaths(innerW));
365
+ } else {
366
+ lines.push(...this.renderActions(innerW));
367
+ }
368
+
369
+ lines.push(`└${border}┘`);
370
+ return lines;
371
+ }
372
+
373
+ private renderActions(innerW: number): string[] {
374
+ const lines: string[] = [];
375
+ const actions = this.getActions();
376
+ for (let index = 0; index < actions.length; index++) {
377
+ const action = actions[index];
378
+ const selected = index === this.actionCursor;
379
+ const cursor = selected ? fg(this.t.selected, "›") : " ";
380
+ lines.push(this.padLine(`${cursor} ${truncateToWidth(action.label, innerW - 4)}`, innerW));
381
+ }
382
+ lines.push(this.padLine("", innerW));
383
+
384
+ const preview = this.getActionPreview(this.getSelectedAction()?.id ?? "view-example");
385
+ for (const line of preview) {
386
+ lines.push(this.padLine(line, innerW));
387
+ }
388
+ lines.push(this.padLine("", innerW));
389
+ lines.push(this.padLine(fg(this.t.muted, "Enter selects, Esc goes back, Ctrl+C closes."), innerW));
390
+ return lines;
391
+ }
392
+
393
+ private renderImports(innerW: number): string[] {
394
+ const lines: string[] = [];
395
+ lines.push(this.padLine("Select compatibility imports. Space toggles, Enter saves, Esc goes back.", innerW));
396
+ lines.push(this.padLine("", innerW));
397
+ for (let index = 0; index < this.discovery.imports.length; index++) {
398
+ const entry = this.discovery.imports[index];
399
+ const selected = this.selectedImports.has(entry.kind) ? "[x]" : "[ ]";
400
+ const cursor = index === this.importCursor ? fg(this.t.selected, "›") : " ";
401
+ lines.push(this.padLine(`${cursor} ${selected} ${entry.kind} ${entry.path}`, innerW));
402
+ }
403
+ lines.push(this.padLine("", innerW));
404
+ const selected = this.discovery.imports.filter((entry) => this.selectedImports.has(entry.kind)).map((entry) => entry.kind);
405
+ const preview = this.callbacks.previewImports(selected);
406
+ for (const line of this.formatWritePreview("Compatibility import write preview", preview)) {
407
+ lines.push(this.padLine(line, innerW));
408
+ }
409
+ return lines;
410
+ }
411
+
412
+ private renderPaths(innerW: number): string[] {
413
+ const lines: string[] = [];
414
+ lines.push(this.padLine("Select a detected config path to open. Enter opens it, Esc goes back.", innerW));
415
+ lines.push(this.padLine("", innerW));
416
+ const paths = this.getDetectedPaths();
417
+ for (let index = 0; index < paths.length; index++) {
418
+ const cursor = index === this.pathCursor ? fg(this.t.selected, "›") : " ";
419
+ lines.push(this.padLine(`${cursor} ${paths[index]}`, innerW));
420
+ }
421
+ return lines;
422
+ }
423
+
424
+ private discoverySummaryLine(): string {
425
+ if (!this.discovery.hasAnyConfig) {
426
+ return fg(this.t.warning, this.options.onboardingState.setupCompleted
427
+ ? "No MCP servers are active right now."
428
+ : "No MCP config is active yet.");
429
+ }
430
+
431
+ if (this.discovery.totalServerCount === 0 && (this.discovery.imports.length > 0 || !!this.discovery.repoPrompt.executablePath)) {
432
+ return fg(this.t.warning, "Pi found MCP-related setup options, but none are active in Pi yet.");
433
+ }
434
+
435
+ const shared = this.discovery.sources.filter((source) => source.kind === "shared" && source.serverCount > 0).length;
436
+ const piOwned = this.discovery.sources.filter((source) => source.kind === "pi" && source.serverCount > 0).length;
437
+ return fg(this.t.hint, `Detected ${this.discovery.totalServerCount} configured servers across ${shared} shared and ${piOwned} Pi-owned source${shared + piOwned === 1 ? "" : "s"}.`);
438
+ }
439
+
440
+ private secondarySummaryLine(): string {
441
+ if (!this.discovery.hasAnyConfig) {
442
+ return "Create a shared `.mcp.json`, adopt host imports, or quick-add RepoPrompt from this screen.";
443
+ }
444
+ if (this.discovery.totalServerCount === 0 && this.discovery.imports.length > 0) {
445
+ return `Detected ${this.discovery.imports.length} compatibility import source${this.discovery.imports.length === 1 ? "" : "s"}. Adopt them into Pi or inspect the underlying files.`;
446
+ }
447
+ return "Shared MCP files are preferred. Pi-owned files are only for compatibility imports and adapter-specific overrides.";
448
+ }
449
+
450
+ private getActionPreview(action: ActionId): string[] {
451
+ switch (action) {
452
+ case "run-setup":
453
+ return this.formatPreview([
454
+ "Run setup to adopt host-specific imports, inspect detected paths, and scaffold a minimal `.mcp.json` if needed.",
455
+ ]);
456
+ case "adopt-imports":
457
+ return this.formatWritePreview(
458
+ "Compatibility import write preview",
459
+ this.callbacks.previewImports(this.discovery.imports.filter((entry) => this.selectedImports.has(entry.kind)).map((entry) => entry.kind)),
460
+ [
461
+ `Detected imports: ${this.discovery.imports.map((entry) => `${entry.kind} (${entry.serverCount} servers)`).join(", ")}`,
462
+ "Selected imports are written into `~/.pi/agent/mcp.json` as Pi-owned compatibility state.",
463
+ ],
464
+ );
465
+ case "view-example":
466
+ return this.formatPreview([
467
+ "Example shared `.mcp.json`:",
468
+ "{",
469
+ ' "mcpServers": {',
470
+ ' "chrome-devtools": {',
471
+ ' "command": "npx",',
472
+ ' "args": ["-y", "chrome-devtools-mcp@latest"]',
473
+ " }",
474
+ " }",
475
+ "}",
476
+ "",
477
+ "Use Scaffold project `.mcp.json` when you want a safe empty shell instead of a live example server.",
478
+ ]);
479
+ case "show-precedence":
480
+ return this.formatPreview([
481
+ "Read order:",
482
+ "1. ~/.config/mcp/mcp.json",
483
+ "2. ~/.pi/agent/mcp.json",
484
+ "3. .mcp.json",
485
+ "4. .pi/mcp.json",
486
+ "Pi writes compatibility imports and adapter-only overrides to Pi-owned files.",
487
+ ]);
488
+ case "open-paths":
489
+ return this.formatPreview(this.getDetectedPaths().length > 0
490
+ ? ["Detected paths:", ...this.getDetectedPaths()]
491
+ : ["No config paths were detected."]);
492
+ case "add-repoprompt": {
493
+ const repoPrompt = this.discovery.repoPrompt;
494
+ const preview = this.callbacks.previewRepoPrompt();
495
+ if (!preview) {
496
+ return this.formatPreview(["RepoPrompt is not available to add from this setup screen."]);
497
+ }
498
+ return this.formatWritePreview(
499
+ "RepoPrompt write preview",
500
+ preview,
501
+ [
502
+ `Executable: ${repoPrompt.executablePath ?? "not found"}`,
503
+ `Target: ${repoPrompt.targetPath ?? "n/a"}`,
504
+ `Server name: ${repoPrompt.serverName ?? "repoprompt"}`,
505
+ ],
506
+ );
507
+ }
508
+ case "scaffold-project":
509
+ return this.formatWritePreview(
510
+ "Starter project `.mcp.json` write preview",
511
+ this.callbacks.previewStarterProject(),
512
+ [
513
+ "This writes a minimal `.mcp.json` in the current project using the shared MCP layout.",
514
+ "It intentionally avoids adding a fake placeholder server that would fail on first reload.",
515
+ ],
516
+ );
517
+ case "close":
518
+ default:
519
+ return this.formatPreview(["Close the setup flow."]);
520
+ }
521
+ }
522
+
523
+ private formatPreview(lines: string[]): string[] {
524
+ const preview: string[] = [];
525
+ for (const line of lines) {
526
+ preview.push(...wrapText(line, 74));
527
+ }
528
+ return preview;
529
+ }
530
+
531
+ private formatWritePreview(title: string, preview: ConfigWritePreview, intro: string[] = []): string[] {
532
+ const lines: string[] = [];
533
+ for (const line of intro) {
534
+ lines.push(...wrapText(line, 74));
535
+ }
536
+ if (intro.length > 0) lines.push("");
537
+ lines.push(...wrapText(`${title}: ${preview.path}`, 74));
538
+ lines.push(...wrapText(preview.existed ? "Existing file detected. Showing exact before/after diff." : "New file will be created. Showing exact content diff.", 74));
539
+ lines.push("");
540
+ const diffLines = preview.diffText.split("\n");
541
+ const maxLines = 18;
542
+ const shown = diffLines.slice(0, maxLines);
543
+ for (const line of shown) {
544
+ lines.push(...wrapText(line, 74));
545
+ }
546
+ if (diffLines.length > maxLines) {
547
+ lines.push(...wrapText(`… ${diffLines.length - maxLines} more diff line${diffLines.length - maxLines === 1 ? "" : "s"}`, 74));
548
+ }
549
+ return lines;
550
+ }
551
+
552
+ private padLine(text: string, innerW: number): string {
553
+ const inset = 2;
554
+ const contentW = Math.max(0, innerW - inset * 2);
555
+ const fitted = truncateToWidth(text, contentW, "…", true);
556
+ const plainWidth = visibleWidth(fitted);
557
+ const padding = Math.max(0, contentW - plainWidth);
558
+ return `│${" ".repeat(inset)}${fitted}${" ".repeat(padding)}${" ".repeat(inset)}│`;
559
+ }
560
+
561
+ invalidate(): void {}
562
+
563
+ dispose(): void {
564
+ this.cleanup();
565
+ }
566
+ }
567
+
568
+ export function createMcpSetupPanel(
569
+ discovery: McpDiscoverySummary,
570
+ callbacks: SetupPanelCallbacks,
571
+ options: SetupPanelOptions,
572
+ tui: { requestRender(): void },
573
+ done: () => void,
574
+ ): McpSetupPanel & { dispose(): void } {
575
+ return new McpSetupPanel(discovery, callbacks, options, tui, done);
576
+ }