@fitchmultz/pi-mcp-adapter 5.0.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.
Files changed (176) hide show
  1. package/CHANGELOG.md +750 -0
  2. package/LICENSE +21 -0
  3. package/OAUTH.md +462 -0
  4. package/README.md +820 -0
  5. package/abort.ts +34 -0
  6. package/agent-dir.ts +24 -0
  7. package/app-bridge.bundle.js +67 -0
  8. package/banner.png +0 -0
  9. package/checkpoint.ts +55 -0
  10. package/cli.js +222 -0
  11. package/commands.ts +619 -0
  12. package/config.ts +1204 -0
  13. package/consent-manager.ts +25 -0
  14. package/direct-tools.ts +408 -0
  15. package/dist/abort.d.ts +2 -0
  16. package/dist/abort.js +35 -0
  17. package/dist/agent-dir.d.ts +3 -0
  18. package/dist/agent-dir.js +21 -0
  19. package/dist/app-bridge.bundle.js +67 -0
  20. package/dist/checkpoint.d.ts +18 -0
  21. package/dist/checkpoint.js +53 -0
  22. package/dist/commands.d.ts +20 -0
  23. package/dist/commands.js +521 -0
  24. package/dist/config.d.ts +109 -0
  25. package/dist/config.js +1013 -0
  26. package/dist/consent-manager.d.ts +8 -0
  27. package/dist/consent-manager.js +21 -0
  28. package/dist/direct-tools.d.ts +10 -0
  29. package/dist/direct-tools.js +350 -0
  30. package/dist/docs/client-metadata.json +14 -0
  31. package/dist/elicitation-handler.d.ts +17 -0
  32. package/dist/elicitation-handler.js +308 -0
  33. package/dist/error-signal.d.ts +15 -0
  34. package/dist/error-signal.js +21 -0
  35. package/dist/glimpse-ui.d.ts +9 -0
  36. package/dist/glimpse-ui.js +75 -0
  37. package/dist/host-html-template.d.ts +15 -0
  38. package/dist/host-html-template.js +429 -0
  39. package/dist/index.d.ts +7 -0
  40. package/dist/index.js +840 -0
  41. package/dist/init.d.ts +25 -0
  42. package/dist/init.js +562 -0
  43. package/dist/legacy-migration.d.ts +18 -0
  44. package/dist/legacy-migration.js +45 -0
  45. package/dist/lifecycle.d.ts +40 -0
  46. package/dist/lifecycle.js +167 -0
  47. package/dist/logger.d.ts +38 -0
  48. package/dist/logger.js +102 -0
  49. package/dist/mcp-auth-flow.d.ts +113 -0
  50. package/dist/mcp-auth-flow.js +834 -0
  51. package/dist/mcp-auth.d.ts +127 -0
  52. package/dist/mcp-auth.js +658 -0
  53. package/dist/mcp-callback-server.d.ts +56 -0
  54. package/dist/mcp-callback-server.js +371 -0
  55. package/dist/mcp-code.d.ts +51 -0
  56. package/dist/mcp-code.js +366 -0
  57. package/dist/mcp-keyring-helper.cjs +89 -0
  58. package/dist/mcp-oauth-provider.d.ts +154 -0
  59. package/dist/mcp-oauth-provider.js +672 -0
  60. package/dist/mcp-output-guard.d.ts +59 -0
  61. package/dist/mcp-output-guard.js +332 -0
  62. package/dist/mcp-panel.d.ts +66 -0
  63. package/dist/mcp-panel.js +889 -0
  64. package/dist/mcp-script-worker.mjs +128 -0
  65. package/dist/mcp-setup-panel.d.ts +84 -0
  66. package/dist/mcp-setup-panel.js +561 -0
  67. package/dist/mcp-status.d.ts +11 -0
  68. package/dist/mcp-status.js +96 -0
  69. package/dist/mcp-trace.d.ts +95 -0
  70. package/dist/mcp-trace.js +233 -0
  71. package/dist/metadata-cache.d.ts +18 -0
  72. package/dist/metadata-cache.js +277 -0
  73. package/dist/npx-resolver.d.ts +6 -0
  74. package/dist/npx-resolver.js +448 -0
  75. package/dist/onboarding-state.d.ts +11 -0
  76. package/dist/onboarding-state.js +47 -0
  77. package/dist/panel-keys.d.ts +16 -0
  78. package/dist/panel-keys.js +15 -0
  79. package/dist/prompts.d.ts +56 -0
  80. package/dist/prompts.js +284 -0
  81. package/dist/proxy-modes.d.ts +38 -0
  82. package/dist/proxy-modes.js +1235 -0
  83. package/dist/resource-tools.d.ts +1 -0
  84. package/dist/resource-tools.js +14 -0
  85. package/dist/runtime-owner.d.ts +18 -0
  86. package/dist/runtime-owner.js +117 -0
  87. package/dist/sampling-handler.d.ts +15 -0
  88. package/dist/sampling-handler.js +211 -0
  89. package/dist/search-ranking.d.ts +20 -0
  90. package/dist/search-ranking.js +180 -0
  91. package/dist/server-manager.d.ts +114 -0
  92. package/dist/server-manager.js +1175 -0
  93. package/dist/session-recovery.d.ts +31 -0
  94. package/dist/session-recovery.js +310 -0
  95. package/dist/state.d.ts +63 -0
  96. package/dist/state.js +1 -0
  97. package/dist/tool-approval.d.ts +10 -0
  98. package/dist/tool-approval.js +42 -0
  99. package/dist/tool-metadata.d.ts +9 -0
  100. package/dist/tool-metadata.js +193 -0
  101. package/dist/tool-registrar.d.ts +10 -0
  102. package/dist/tool-registrar.js +64 -0
  103. package/dist/tool-result-renderer.d.ts +45 -0
  104. package/dist/tool-result-renderer.js +224 -0
  105. package/dist/ts-shape.d.ts +2 -0
  106. package/dist/ts-shape.js +147 -0
  107. package/dist/types.d.ts +516 -0
  108. package/dist/types.js +168 -0
  109. package/dist/ui-resource-handler.d.ts +17 -0
  110. package/dist/ui-resource-handler.js +209 -0
  111. package/dist/ui-server.d.ts +51 -0
  112. package/dist/ui-server.js +669 -0
  113. package/dist/ui-session.d.ts +39 -0
  114. package/dist/ui-session.js +463 -0
  115. package/dist/ui-stream-types.d.ts +104 -0
  116. package/dist/ui-stream-types.js +58 -0
  117. package/dist/ui-tool-visibility.d.ts +4 -0
  118. package/dist/ui-tool-visibility.js +26 -0
  119. package/dist/unix-socket-transport.d.ts +15 -0
  120. package/dist/unix-socket-transport.js +84 -0
  121. package/dist/utils.d.ts +30 -0
  122. package/dist/utils.js +276 -0
  123. package/docs/client-metadata.json +14 -0
  124. package/elicitation-handler.ts +349 -0
  125. package/error-signal.ts +21 -0
  126. package/glimpse-ui.ts +80 -0
  127. package/host-html-template.ts +456 -0
  128. package/index.ts +900 -0
  129. package/init.ts +627 -0
  130. package/legacy-migration.ts +47 -0
  131. package/lifecycle.ts +165 -0
  132. package/logger.ts +127 -0
  133. package/mcp-auth-flow.ts +975 -0
  134. package/mcp-auth.ts +793 -0
  135. package/mcp-callback-server.ts +450 -0
  136. package/mcp-code.ts +386 -0
  137. package/mcp-keyring-helper.cjs +89 -0
  138. package/mcp-oauth-provider.ts +774 -0
  139. package/mcp-output-guard.ts +412 -0
  140. package/mcp-panel.ts +978 -0
  141. package/mcp-script-worker.mjs +128 -0
  142. package/mcp-setup-panel.ts +666 -0
  143. package/mcp-status.ts +109 -0
  144. package/mcp-trace.ts +295 -0
  145. package/metadata-cache.ts +333 -0
  146. package/npx-resolver.ts +488 -0
  147. package/onboarding-state.ts +58 -0
  148. package/package.json +182 -0
  149. package/panel-keys.ts +37 -0
  150. package/prompts.ts +337 -0
  151. package/proxy-modes.ts +1361 -0
  152. package/resource-tools.ts +17 -0
  153. package/runtime-owner.ts +123 -0
  154. package/sampling-handler.ts +273 -0
  155. package/scripts/build.mjs +131 -0
  156. package/scripts/prepare.mjs +102 -0
  157. package/search-ranking.ts +196 -0
  158. package/server-manager.ts +1320 -0
  159. package/session-recovery.ts +316 -0
  160. package/skills/mcp-scripting/SKILL.md +38 -0
  161. package/state.ts +64 -0
  162. package/tool-approval.ts +78 -0
  163. package/tool-metadata.ts +235 -0
  164. package/tool-registrar.ts +69 -0
  165. package/tool-result-renderer.ts +286 -0
  166. package/ts-shape.ts +145 -0
  167. package/tsconfig.build.json +13 -0
  168. package/tsconfig.json +16 -0
  169. package/types.ts +810 -0
  170. package/ui-resource-handler.ts +249 -0
  171. package/ui-server.ts +808 -0
  172. package/ui-session.ts +568 -0
  173. package/ui-stream-types.ts +89 -0
  174. package/ui-tool-visibility.ts +25 -0
  175. package/unix-socket-transport.ts +85 -0
  176. package/utils.ts +309 -0
@@ -0,0 +1,561 @@
1
+ import { matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
2
+ import { createPanelKeys } from "./panel-keys.js";
3
+ import { KNOWN_SERVER_PRESETS } from "./config.js";
4
+ const DEFAULT_THEME = {
5
+ border: "2",
6
+ title: "36",
7
+ selected: "32",
8
+ hint: "2",
9
+ success: "32",
10
+ warning: "33",
11
+ muted: "2;3",
12
+ };
13
+ const MIN_PANEL_WIDTH = 24;
14
+ const COMPACT_WIDTH = 60;
15
+ const COMPACT_ACTION_ROWS = 7;
16
+ const DESKTOP_PREVIEW_WIDTH = 74;
17
+ function fg(code, text) {
18
+ return code ? `\x1b[${code}m${text}\x1b[0m` : text;
19
+ }
20
+ function wrapText(text, width) {
21
+ if (width <= 8)
22
+ return [text];
23
+ const words = text.split(/\s+/).filter(Boolean);
24
+ const lines = [];
25
+ let current = "";
26
+ for (const word of words) {
27
+ const candidate = current ? `${current} ${word}` : word;
28
+ if (visibleWidth(candidate) <= width) {
29
+ current = candidate;
30
+ continue;
31
+ }
32
+ if (current)
33
+ lines.push(current);
34
+ current = word;
35
+ }
36
+ if (current)
37
+ lines.push(current);
38
+ return lines.length > 0 ? lines : [""];
39
+ }
40
+ export class McpSetupPanel {
41
+ discovery;
42
+ callbacks;
43
+ options;
44
+ done;
45
+ screen;
46
+ actionCursor = 0;
47
+ importCursor = 0;
48
+ pathCursor = 0;
49
+ selectedImports = new Set();
50
+ busy = false;
51
+ notice = null;
52
+ tui;
53
+ t = DEFAULT_THEME;
54
+ keys;
55
+ inactivityTimeout = null;
56
+ static INACTIVITY_MS = 60_000;
57
+ constructor(discovery, callbacks, options, tui, done) {
58
+ this.discovery = discovery;
59
+ this.callbacks = callbacks;
60
+ this.options = options;
61
+ this.done = done;
62
+ this.tui = tui;
63
+ this.keys = createPanelKeys(options.keybindings);
64
+ this.screen = options.mode;
65
+ for (const entry of discovery.imports) {
66
+ this.selectedImports.add(entry.kind);
67
+ }
68
+ this.resetInactivityTimeout();
69
+ }
70
+ resetInactivityTimeout() {
71
+ if (this.inactivityTimeout)
72
+ clearTimeout(this.inactivityTimeout);
73
+ this.inactivityTimeout = setTimeout(() => {
74
+ this.cleanup();
75
+ this.done();
76
+ }, McpSetupPanel.INACTIVITY_MS);
77
+ }
78
+ cleanup() {
79
+ if (this.inactivityTimeout) {
80
+ clearTimeout(this.inactivityTimeout);
81
+ this.inactivityTimeout = null;
82
+ }
83
+ }
84
+ getActions() {
85
+ const actions = [];
86
+ if (this.screen === "empty") {
87
+ actions.push({ id: "run-setup", label: "Run setup", description: "Inspect detected configs, adopt imports, and scaffold a minimal `.mcp.json`." });
88
+ }
89
+ if (this.discovery.imports.length > 0) {
90
+ 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.` });
91
+ }
92
+ actions.push({ id: "view-example", label: "View example `.mcp.json`", description: "Preview a working shared MCP config you can paste or adapt." });
93
+ if (!this.discovery.sources.some((source) => source.id === "shared-project" && source.exists)) {
94
+ 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." });
95
+ }
96
+ actions.push({ id: "show-precedence", label: "Explain config precedence", description: "Show the read order and where Pi writes compatibility settings." });
97
+ if (this.getDetectedPaths().length > 0) {
98
+ actions.push({ id: "open-paths", label: "Open detected config paths", description: "Browse the actual config files that Pi discovered on this machine." });
99
+ }
100
+ for (const preset of KNOWN_SERVER_PRESETS) {
101
+ actions.push({ id: "add-known-server", label: preset.name, description: preset.summary, preset });
102
+ }
103
+ if (!this.discovery.repoPrompt.configured && this.discovery.repoPrompt.executablePath && this.discovery.repoPrompt.targetPath && this.discovery.repoPrompt.entry && this.discovery.repoPrompt.serverName) {
104
+ 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." });
105
+ }
106
+ actions.push({ id: "close", label: "Close", description: "Exit the onboarding flow." });
107
+ return actions;
108
+ }
109
+ getDetectedPaths() {
110
+ const paths = [
111
+ ...this.discovery.sources.filter((source) => source.exists).map((source) => source.path),
112
+ ...this.discovery.imports.map((entry) => entry.path),
113
+ ];
114
+ return [...new Set(paths)];
115
+ }
116
+ getSelectedAction() {
117
+ const actions = this.getActions();
118
+ return actions[this.actionCursor];
119
+ }
120
+ handleInput(data) {
121
+ this.resetInactivityTimeout();
122
+ if (!this.busy)
123
+ this.notice = null;
124
+ if (matchesKey(data, "ctrl+c")) {
125
+ this.cleanup();
126
+ this.done();
127
+ return;
128
+ }
129
+ if (matchesKey(data, "escape")) {
130
+ if (this.screen === "imports" || this.screen === "paths") {
131
+ this.screen = this.discovery.hasAnyConfig ? "setup" : "empty";
132
+ this.tui.requestRender();
133
+ return;
134
+ }
135
+ this.cleanup();
136
+ this.done();
137
+ return;
138
+ }
139
+ if (this.busy)
140
+ return;
141
+ if (this.screen === "imports") {
142
+ this.handleImportsInput(data);
143
+ return;
144
+ }
145
+ if (this.screen === "paths") {
146
+ this.handlePathsInput(data);
147
+ return;
148
+ }
149
+ const actions = this.getActions();
150
+ if (this.keys.selectUp(data)) {
151
+ this.actionCursor = Math.max(0, this.actionCursor - 1);
152
+ this.tui.requestRender();
153
+ return;
154
+ }
155
+ if (this.keys.selectDown(data)) {
156
+ this.actionCursor = Math.min(actions.length - 1, this.actionCursor + 1);
157
+ this.tui.requestRender();
158
+ return;
159
+ }
160
+ if (this.keys.selectConfirm(data)) {
161
+ const selected = this.getSelectedAction();
162
+ if (selected)
163
+ void this.runAction(selected);
164
+ }
165
+ }
166
+ handleImportsInput(data) {
167
+ const imports = this.discovery.imports;
168
+ if (this.keys.selectUp(data)) {
169
+ this.importCursor = Math.max(0, this.importCursor - 1);
170
+ this.tui.requestRender();
171
+ return;
172
+ }
173
+ if (this.keys.selectDown(data)) {
174
+ this.importCursor = Math.min(imports.length - 1, this.importCursor + 1);
175
+ this.tui.requestRender();
176
+ return;
177
+ }
178
+ if (matchesKey(data, "space")) {
179
+ const current = imports[this.importCursor];
180
+ if (!current)
181
+ return;
182
+ if (this.selectedImports.has(current.kind)) {
183
+ this.selectedImports.delete(current.kind);
184
+ }
185
+ else {
186
+ this.selectedImports.add(current.kind);
187
+ }
188
+ this.tui.requestRender();
189
+ return;
190
+ }
191
+ if (this.keys.selectConfirm(data)) {
192
+ void this.applySelectedImports();
193
+ }
194
+ }
195
+ handlePathsInput(data) {
196
+ const paths = this.getDetectedPaths();
197
+ if (this.keys.selectUp(data)) {
198
+ this.pathCursor = Math.max(0, this.pathCursor - 1);
199
+ this.tui.requestRender();
200
+ return;
201
+ }
202
+ if (this.keys.selectDown(data)) {
203
+ this.pathCursor = Math.min(paths.length - 1, this.pathCursor + 1);
204
+ this.tui.requestRender();
205
+ return;
206
+ }
207
+ if (this.keys.selectConfirm(data)) {
208
+ const selected = paths[this.pathCursor];
209
+ if (!selected)
210
+ return;
211
+ void this.runBusy(async () => {
212
+ await this.callbacks.openPath(selected);
213
+ this.notice = { text: `Opened ${selected}`, tone: "success" };
214
+ });
215
+ }
216
+ }
217
+ async runAction(action) {
218
+ if (action.id === "run-setup") {
219
+ this.screen = "setup";
220
+ this.actionCursor = 0;
221
+ this.tui.requestRender();
222
+ return;
223
+ }
224
+ if (action.id === "adopt-imports") {
225
+ this.screen = "imports";
226
+ this.importCursor = 0;
227
+ this.tui.requestRender();
228
+ return;
229
+ }
230
+ if (action.id === "open-paths") {
231
+ this.screen = "paths";
232
+ this.pathCursor = 0;
233
+ this.tui.requestRender();
234
+ return;
235
+ }
236
+ if (action.id === "scaffold-project") {
237
+ await this.runBusy(async () => {
238
+ const result = await this.callbacks.scaffoldProjectConfig();
239
+ this.callbacks.markSetupCompleted();
240
+ this.notice = { text: `Wrote starter config to ${result.path}. Pi will reload after this panel closes.`, tone: "success" };
241
+ });
242
+ return;
243
+ }
244
+ if (action.id === "add-repoprompt") {
245
+ await this.runBusy(async () => {
246
+ const result = await this.callbacks.addRepoPrompt();
247
+ this.callbacks.markSetupCompleted();
248
+ this.notice = { text: `Added ${result.serverName} to ${result.path}. Pi will reload after this panel closes.`, tone: "success" };
249
+ });
250
+ return;
251
+ }
252
+ if (action.id === "add-known-server" && action.preset) {
253
+ const preset = action.preset;
254
+ await this.runBusy(async () => {
255
+ const result = await this.callbacks.addKnownServer(preset);
256
+ this.callbacks.markSetupCompleted();
257
+ this.notice = { text: `Added ${result.serverName} to ${result.path}. Pi will reload after this panel closes.`, tone: "success" };
258
+ });
259
+ return;
260
+ }
261
+ if (action.id === "close") {
262
+ this.cleanup();
263
+ this.done();
264
+ return;
265
+ }
266
+ this.notice = { text: "Review the details below. Press Enter on an action with a side effect to apply it.", tone: "muted" };
267
+ this.tui.requestRender();
268
+ }
269
+ async applySelectedImports() {
270
+ const selected = this.discovery.imports.filter((entry) => this.selectedImports.has(entry.kind)).map((entry) => entry.kind);
271
+ if (selected.length === 0) {
272
+ this.notice = { text: "Select at least one compatibility import first.", tone: "warning" };
273
+ this.tui.requestRender();
274
+ return;
275
+ }
276
+ await this.runBusy(async () => {
277
+ const result = await this.callbacks.adoptImports(selected);
278
+ this.callbacks.markSetupCompleted();
279
+ this.notice = result.added.length > 0
280
+ ? { text: `Added ${result.added.join(", ")} to ${result.path}. Pi will reload after this panel closes.`, tone: "success" }
281
+ : { text: `No changes needed in ${result.path}.`, tone: "muted" };
282
+ this.screen = this.discovery.hasAnyConfig ? "setup" : "empty";
283
+ this.actionCursor = 0;
284
+ });
285
+ }
286
+ async runBusy(fn) {
287
+ this.busy = true;
288
+ this.notice = { text: "Working...", tone: "muted" };
289
+ this.tui.requestRender();
290
+ try {
291
+ await fn();
292
+ }
293
+ catch (error) {
294
+ this.notice = {
295
+ text: error instanceof Error ? error.message : String(error),
296
+ tone: "warning",
297
+ };
298
+ }
299
+ finally {
300
+ this.busy = false;
301
+ this.tui.requestRender();
302
+ }
303
+ }
304
+ render(width) {
305
+ const panelW = Math.max(MIN_PANEL_WIDTH, width);
306
+ const innerW = panelW - 2;
307
+ const contentW = this.contentWidth(innerW);
308
+ const lines = [];
309
+ const border = fg(this.t.border, "─".repeat(innerW));
310
+ lines.push(`┌${border}┐`);
311
+ lines.push(this.padLine(fg(this.t.title, "MCP setup"), innerW));
312
+ for (const line of wrapText(this.discoverySummaryLine(), contentW)) {
313
+ lines.push(this.padLine(line, innerW));
314
+ }
315
+ for (const line of wrapText(this.secondarySummaryLine(), contentW)) {
316
+ lines.push(this.padLine(fg(this.t.muted, line), innerW));
317
+ }
318
+ lines.push(this.padLine("", innerW));
319
+ if (this.notice) {
320
+ const tone = this.notice.tone === "success" ? this.t.success : this.notice.tone === "warning" ? this.t.warning : this.t.hint;
321
+ for (const line of wrapText(this.notice.text, contentW)) {
322
+ lines.push(this.padLine(fg(tone, line), innerW));
323
+ }
324
+ lines.push(this.padLine("", innerW));
325
+ }
326
+ lines.push(`├${border}┤`);
327
+ if (this.screen === "imports") {
328
+ lines.push(...this.renderImports(innerW));
329
+ }
330
+ else if (this.screen === "paths") {
331
+ lines.push(...this.renderPaths(innerW));
332
+ }
333
+ else {
334
+ lines.push(...this.renderActions(innerW));
335
+ }
336
+ lines.push(`└${border}┘`);
337
+ return lines;
338
+ }
339
+ renderActions(innerW) {
340
+ const lines = [];
341
+ const actions = this.getActions();
342
+ const compact = innerW < COMPACT_WIDTH;
343
+ const { start, end } = compact
344
+ ? this.visibleActionRange(actions.length)
345
+ : { start: 0, end: actions.length };
346
+ if (start > 0) {
347
+ lines.push(this.padLine(fg(this.t.muted, `… ${start} more above`), innerW));
348
+ }
349
+ for (let index = start; index < end; index++) {
350
+ const action = actions[index];
351
+ if (!action)
352
+ continue;
353
+ if (action.id === "add-known-server" && (index === start || actions[index - 1]?.id !== "add-known-server")) {
354
+ lines.push(this.padLine(fg(this.t.title, "Add a known server"), innerW));
355
+ }
356
+ const selected = index === this.actionCursor;
357
+ const cursor = selected ? fg(this.t.selected, "›") : " ";
358
+ lines.push(this.padLine(`${cursor} ${truncateToWidth(action.label, this.contentWidth(innerW) - 2)}`, innerW));
359
+ }
360
+ if (end < actions.length) {
361
+ lines.push(this.padLine(fg(this.t.muted, `… ${actions.length - end} more below`), innerW));
362
+ }
363
+ lines.push(this.padLine("", innerW));
364
+ const preview = this.getActionPreview(this.getSelectedAction(), this.previewWidth(innerW));
365
+ for (const line of preview) {
366
+ lines.push(this.padLine(line, innerW));
367
+ }
368
+ lines.push(this.padLine("", innerW));
369
+ const hint = compact ? "Enter select · Esc back" : "Enter selects, Esc goes back, Ctrl+C closes.";
370
+ lines.push(this.padLine(fg(this.t.muted, hint), innerW));
371
+ return lines;
372
+ }
373
+ renderImports(innerW) {
374
+ const lines = [];
375
+ lines.push(this.padLine("Select compatibility imports. Space toggles, Enter saves, Esc goes back.", innerW));
376
+ lines.push(this.padLine("", innerW));
377
+ for (let index = 0; index < this.discovery.imports.length; index++) {
378
+ const entry = this.discovery.imports[index];
379
+ if (!entry)
380
+ continue;
381
+ const selected = this.selectedImports.has(entry.kind) ? "[x]" : "[ ]";
382
+ const cursor = index === this.importCursor ? fg(this.t.selected, "›") : " ";
383
+ lines.push(this.padLine(`${cursor} ${selected} ${entry.kind} ${entry.path}`, innerW));
384
+ }
385
+ lines.push(this.padLine("", innerW));
386
+ const selected = this.discovery.imports.filter((entry) => this.selectedImports.has(entry.kind)).map((entry) => entry.kind);
387
+ const preview = this.callbacks.previewImports(selected);
388
+ for (const line of this.formatWritePreview("Compatibility import write preview", preview, [], this.previewWidth(innerW))) {
389
+ lines.push(this.padLine(line, innerW));
390
+ }
391
+ return lines;
392
+ }
393
+ renderPaths(innerW) {
394
+ const lines = [];
395
+ lines.push(this.padLine("Select a detected config path to open. Enter opens it, Esc goes back.", innerW));
396
+ lines.push(this.padLine("", innerW));
397
+ const paths = this.getDetectedPaths();
398
+ for (let index = 0; index < paths.length; index++) {
399
+ const cursor = index === this.pathCursor ? fg(this.t.selected, "›") : " ";
400
+ const path = paths[index];
401
+ if (path !== undefined)
402
+ lines.push(this.padLine(`${cursor} ${path}`, innerW));
403
+ }
404
+ return lines;
405
+ }
406
+ discoverySummaryLine() {
407
+ if (!this.discovery.hasAnyConfig) {
408
+ return fg(this.t.warning, this.options.onboardingState.setupCompleted
409
+ ? "No MCP servers are active right now."
410
+ : "No MCP config is active yet.");
411
+ }
412
+ if (this.discovery.totalServerCount === 0 && (this.discovery.imports.length > 0 || !!this.discovery.repoPrompt.executablePath)) {
413
+ return fg(this.t.warning, "Pi found MCP-related setup options, but none are active in Pi yet.");
414
+ }
415
+ const shared = this.discovery.sources.filter((source) => source.kind === "shared" && source.serverCount > 0).length;
416
+ const piOwned = this.discovery.sources.filter((source) => source.kind === "pi" && source.serverCount > 0).length;
417
+ return fg(this.t.hint, `Detected ${this.discovery.totalServerCount} configured servers across ${shared} shared and ${piOwned} Pi-owned source${shared + piOwned === 1 ? "" : "s"}.`);
418
+ }
419
+ secondarySummaryLine() {
420
+ const hostNote = this.discovery.hostConfigs.length > 0
421
+ ? ` Host discovery is ${this.discovery.hostConfigDiscovery}; ${this.discovery.hostConfigs.length} host source${this.discovery.hostConfigs.length === 1 ? "" : "s"} detected.`
422
+ : "";
423
+ const conflictNote = this.discovery.conflicts.length > 0
424
+ ? ` ${this.discovery.conflicts.length} same-name conflict${this.discovery.conflicts.length === 1 ? "" : "s"} reported.`
425
+ : "";
426
+ if (!this.discovery.hasAnyConfig) {
427
+ return `Create a shared .mcp.json, adopt host imports, or quick-add RepoPrompt from this screen.${hostNote}${conflictNote}`;
428
+ }
429
+ if (this.discovery.totalServerCount === 0 && this.discovery.imports.length > 0) {
430
+ return `Detected ${this.discovery.imports.length} compatibility import source${this.discovery.imports.length === 1 ? "" : "s"}. Adopt them into Pi or inspect the underlying files.${hostNote}${conflictNote}`;
431
+ }
432
+ return `Shared MCP files are preferred. Pi-owned files are only for compatibility imports and adapter-specific overrides.${hostNote}${conflictNote}`;
433
+ }
434
+ visibleActionRange(total) {
435
+ if (total <= COMPACT_ACTION_ROWS)
436
+ return { start: 0, end: total };
437
+ const half = Math.floor(COMPACT_ACTION_ROWS / 2);
438
+ const start = Math.min(Math.max(0, this.actionCursor - half), Math.max(0, total - COMPACT_ACTION_ROWS));
439
+ return { start, end: Math.min(total, start + COMPACT_ACTION_ROWS) };
440
+ }
441
+ contentWidth(innerW) {
442
+ return Math.max(8, innerW - 4);
443
+ }
444
+ previewWidth(innerW) {
445
+ return Math.max(12, Math.min(DESKTOP_PREVIEW_WIDTH, this.contentWidth(innerW)));
446
+ }
447
+ getActionPreview(action, previewW = DESKTOP_PREVIEW_WIDTH) {
448
+ switch (action?.id) {
449
+ case "run-setup":
450
+ return this.formatPreview([
451
+ "Run setup to adopt host-specific imports, inspect detected paths, and scaffold a minimal `.mcp.json` if needed.",
452
+ ], previewW);
453
+ case "adopt-imports":
454
+ return this.formatWritePreview("Compatibility import write preview", this.callbacks.previewImports(this.discovery.imports.filter((entry) => this.selectedImports.has(entry.kind)).map((entry) => entry.kind)), [
455
+ `Detected imports: ${this.discovery.imports.map((entry) => `${entry.kind} (${entry.serverCount} servers)`).join(", ")}`,
456
+ "Selected imports are written into the Pi agent dir config as Pi-owned compatibility state.",
457
+ ], previewW);
458
+ case "view-example":
459
+ return this.formatPreview([
460
+ "Example shared `.mcp.json`:",
461
+ "{",
462
+ ' "mcpServers": {',
463
+ ' "chrome-devtools": {',
464
+ ' "command": "npx",',
465
+ ' "args": ["-y", "chrome-devtools-mcp@latest"]',
466
+ " }",
467
+ " }",
468
+ "}",
469
+ "",
470
+ "Use Scaffold project `.mcp.json` when you want a safe empty shell instead of a live example server.",
471
+ ], previewW);
472
+ case "show-precedence":
473
+ return this.formatPreview([
474
+ "Read order (later entries win):",
475
+ "0. detected host configs (opt-in lowest-precedence fallback)",
476
+ "1. ~/.config/mcp/mcp.json",
477
+ "2. ~/.agents/mcp.json",
478
+ "3. ~/.agents/mcp/mcp.json",
479
+ "4. <Pi agent dir>/fitch-mcp-adapter/mcp.json",
480
+ "5. .mcp.json",
481
+ "6. .pi/fitch-mcp-adapter/mcp.json",
482
+ `Host discovery: ${this.discovery.hostConfigDiscovery}. Conflicts reported: ${this.discovery.conflicts.length}.`,
483
+ ...this.discovery.conflicts.slice(0, 8).map((conflict) => `${conflict.serverName}: ${conflict.sources.map((source) => source.path).join(" -> ")} (winner: ${conflict.winner.path})`),
484
+ "Pi writes compatibility imports and adapter-only overrides to Pi-owned files."
485
+ ], previewW);
486
+ case "open-paths":
487
+ return this.formatPreview(this.getDetectedPaths().length > 0
488
+ ? ["Detected paths:", ...this.getDetectedPaths()]
489
+ : ["No config paths were detected."], previewW);
490
+ case "add-repoprompt": {
491
+ const repoPrompt = this.discovery.repoPrompt;
492
+ const preview = this.callbacks.previewRepoPrompt();
493
+ if (!preview) {
494
+ return this.formatPreview(["RepoPrompt is not available to add from this setup screen."], previewW);
495
+ }
496
+ return this.formatWritePreview("RepoPrompt write preview", preview, [
497
+ `Executable: ${repoPrompt.executablePath ?? "not found"}`,
498
+ `Target: ${repoPrompt.targetPath ?? "n/a"}`,
499
+ `Server name: ${repoPrompt.serverName ?? "repoprompt"}`,
500
+ ], previewW);
501
+ }
502
+ case "add-known-server": {
503
+ const preset = action.preset;
504
+ if (!preset)
505
+ return this.formatPreview(["Known server preset is unavailable."], previewW);
506
+ return this.formatWritePreview(`${preset.name} write preview`, this.callbacks.previewKnownServer(preset), [preset.summary], previewW);
507
+ }
508
+ case "scaffold-project":
509
+ return this.formatWritePreview("Starter project `.mcp.json` write preview", this.callbacks.previewStarterProject(), [
510
+ "This writes a minimal `.mcp.json` in the current project using the shared MCP layout.",
511
+ "It intentionally avoids adding a fake placeholder server that would fail on first reload.",
512
+ ], previewW);
513
+ case "close":
514
+ default:
515
+ return this.formatPreview(["Close the setup flow."], previewW);
516
+ }
517
+ }
518
+ formatPreview(lines, width = DESKTOP_PREVIEW_WIDTH) {
519
+ const preview = [];
520
+ for (const line of lines) {
521
+ preview.push(...wrapText(line, width));
522
+ }
523
+ return preview;
524
+ }
525
+ formatWritePreview(title, preview, intro = [], width = DESKTOP_PREVIEW_WIDTH) {
526
+ const lines = [];
527
+ for (const line of intro) {
528
+ lines.push(...wrapText(line, width));
529
+ }
530
+ if (intro.length > 0)
531
+ lines.push("");
532
+ lines.push(...wrapText(`${title}: ${preview.path}`, width));
533
+ lines.push(...wrapText(preview.existed ? "Existing file detected. Showing exact before/after diff." : "New file will be created. Showing exact content diff.", width));
534
+ lines.push("");
535
+ const diffLines = preview.diffText.split("\n");
536
+ const maxLines = 18;
537
+ const shown = diffLines.slice(0, maxLines);
538
+ for (const line of shown) {
539
+ lines.push(...wrapText(line, width));
540
+ }
541
+ if (diffLines.length > maxLines) {
542
+ lines.push(...wrapText(`… ${diffLines.length - maxLines} more diff line${diffLines.length - maxLines === 1 ? "" : "s"}`, width));
543
+ }
544
+ return lines;
545
+ }
546
+ padLine(text, innerW) {
547
+ const inset = 2;
548
+ const contentW = Math.max(0, innerW - inset * 2);
549
+ const fitted = truncateToWidth(text, contentW, "…", true);
550
+ const plainWidth = visibleWidth(fitted);
551
+ const padding = Math.max(0, contentW - plainWidth);
552
+ return `│${" ".repeat(inset)}${fitted}${" ".repeat(padding)}${" ".repeat(inset)}│`;
553
+ }
554
+ invalidate() { }
555
+ dispose() {
556
+ this.cleanup();
557
+ }
558
+ }
559
+ export function createMcpSetupPanel(discovery, callbacks, options, tui, done) {
560
+ return new McpSetupPanel(discovery, callbacks, options, tui, done);
561
+ }
@@ -0,0 +1,11 @@
1
+ import type { McpExtensionState } from "./state.ts";
2
+ import { type McpStatusSnapshot } from "./types.ts";
3
+ export interface McpStatusEventBus {
4
+ emit(channel: string, data: unknown): void;
5
+ }
6
+ /** Build a sanitized snapshot without connecting or querying any MCP server. */
7
+ export declare function createMcpStatusSnapshot(state: McpExtensionState): McpStatusSnapshot;
8
+ export declare function publishMcpStatusSnapshot(state: McpExtensionState, snapshot?: McpStatusSnapshot): void;
9
+ export declare function publishMcpStatusShutdown(events: McpStatusEventBus | undefined): void;
10
+ export type { McpServerStatusSnapshot, McpStatusSnapshot } from "./types.ts";
11
+ export { MCP_STATUS_EVENT, MCP_STATUS_SNAPSHOT_VERSION } from "./types.ts";
@@ -0,0 +1,96 @@
1
+ import { MCP_STATUS_EVENT, MCP_STATUS_SNAPSHOT_VERSION, } from "./types.js";
2
+ const FAILURE_BACKOFF_MS = 60 * 1000;
3
+ function getActiveFailureAgeSeconds(state, serverName) {
4
+ const failedAt = state.failureTracker.get(serverName);
5
+ if (!failedAt)
6
+ return undefined;
7
+ const ageMs = Date.now() - failedAt;
8
+ if (ageMs > FAILURE_BACKOFF_MS)
9
+ return undefined;
10
+ return Math.round(ageMs / 1000);
11
+ }
12
+ /** Build a sanitized snapshot without connecting or querying any MCP server. */
13
+ export function createMcpStatusSnapshot(state) {
14
+ const servers = [];
15
+ let totalTools = 0;
16
+ let totalResources = 0;
17
+ let connectedCount = 0;
18
+ let disabledCount = 0;
19
+ for (const name of Object.keys(state.config.mcpServers)) {
20
+ const definition = state.config.mcpServers[name];
21
+ const disabled = definition?.disabled === true;
22
+ const connection = disabled ? undefined : state.manager.getConnection(name);
23
+ const metadata = disabled ? undefined : state.toolMetadata.get(name);
24
+ const toolCount = metadata?.length ?? (connection?.status === "connected" ? connection.tools.length : 0);
25
+ const resourceCount = disabled
26
+ ? undefined
27
+ : state.resourceCounts?.get(name) ?? (connection?.status === "connected" ? connection.resources.length : undefined);
28
+ const failedAgoSeconds = disabled ? undefined : getActiveFailureAgeSeconds(state, name);
29
+ let status = "not-connected";
30
+ if (disabled) {
31
+ status = "disabled";
32
+ disabledCount++;
33
+ }
34
+ else if (connection?.status === "connected") {
35
+ status = "connected";
36
+ connectedCount++;
37
+ }
38
+ else if (connection?.status === "needs-auth") {
39
+ status = "needs-auth";
40
+ }
41
+ else if (failedAgoSeconds !== undefined) {
42
+ status = "failed";
43
+ }
44
+ else if (metadata !== undefined) {
45
+ status = "cached";
46
+ }
47
+ totalTools += disabled ? 0 : toolCount;
48
+ if (!disabled && resourceCount !== undefined)
49
+ totalResources += resourceCount;
50
+ servers.push({
51
+ name,
52
+ status,
53
+ toolCount,
54
+ ...(resourceCount !== undefined ? { resourceCount } : {}),
55
+ ...(status === "failed" && failedAgoSeconds !== undefined ? { failedAgoSeconds } : {}),
56
+ disabled,
57
+ });
58
+ }
59
+ return {
60
+ version: MCP_STATUS_SNAPSHOT_VERSION,
61
+ servers,
62
+ totalTools,
63
+ totalResources,
64
+ connectedCount,
65
+ disabledCount,
66
+ };
67
+ }
68
+ export function publishMcpStatusSnapshot(state, snapshot) {
69
+ const events = state.statusEvents;
70
+ if (!events)
71
+ return;
72
+ try {
73
+ events.emit(MCP_STATUS_EVENT, snapshot ?? createMcpStatusSnapshot(state));
74
+ }
75
+ catch {
76
+ // Event consumers must not be able to interrupt MCP operations.
77
+ }
78
+ }
79
+ export function publishMcpStatusShutdown(events) {
80
+ if (!events)
81
+ return;
82
+ try {
83
+ events.emit(MCP_STATUS_EVENT, {
84
+ version: MCP_STATUS_SNAPSHOT_VERSION,
85
+ servers: [],
86
+ totalTools: 0,
87
+ totalResources: 0,
88
+ connectedCount: 0,
89
+ disabledCount: 0,
90
+ });
91
+ }
92
+ catch {
93
+ // Event consumers must not be able to interrupt MCP shutdown.
94
+ }
95
+ }
96
+ export { MCP_STATUS_EVENT, MCP_STATUS_SNAPSHOT_VERSION } from "./types.js";