@fitchmultz/pi-mcp-adapter 6.0.0 → 7.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 (105) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +12 -8
  3. package/dist/app-bridge.bundle.js +14 -14
  4. package/dist/config.js +41 -16
  5. package/dist/gateway-arguments.d.ts +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/lifecycle.d.ts +2 -2
  8. package/dist/lifecycle.js +2 -2
  9. package/dist/mcp-auth-flow.js +2 -2
  10. package/dist/mcp-auth.d.ts +1 -1
  11. package/dist/mcp-auth.js +3 -3
  12. package/dist/mcp-code.d.ts +6 -6
  13. package/dist/mcp-code.js +11 -10
  14. package/dist/mcp-oauth-provider.d.ts +5 -5
  15. package/dist/mcp-oauth-provider.js +5 -5
  16. package/dist/mcp-output-guard.d.ts +1 -1
  17. package/dist/mcp-panel.d.ts +2 -2
  18. package/dist/mcp-panel.js +2 -2
  19. package/dist/mcp-setup-panel.d.ts +5 -4
  20. package/dist/mcp-setup-panel.js +15 -7
  21. package/dist/mcp-trace.d.ts +1 -1
  22. package/dist/mcp-trace.js +1 -1
  23. package/dist/npx-resolver.js +8 -4
  24. package/dist/proxy-modes.d.ts +2 -2
  25. package/dist/proxy-modes.js +9 -9
  26. package/dist/sampling-handler.js +1 -0
  27. package/dist/search-ranking.js +6 -2
  28. package/dist/server-manager.d.ts +2 -2
  29. package/dist/server-manager.js +44 -27
  30. package/dist/session-recovery.d.ts +7 -4
  31. package/dist/session-recovery.js +76 -10
  32. package/dist/tool-metadata.d.ts +43 -43
  33. package/dist/tool-result-renderer.d.ts +3 -3
  34. package/dist/tool-result-renderer.js +3 -3
  35. package/dist/ui-resource-handler.d.ts +2 -2
  36. package/dist/ui-resource-handler.js +2 -2
  37. package/dist/ui-server.js +4 -3
  38. package/dist/ui-stream-types.d.ts +8 -8
  39. package/dist/unix-socket-transport.d.ts +1 -1
  40. package/dist/unix-socket-transport.js +1 -1
  41. package/dist/utils.d.ts +1 -0
  42. package/dist/utils.js +14 -0
  43. package/package.json +34 -98
  44. package/abort.ts +0 -34
  45. package/agent-dir.ts +0 -24
  46. package/app-bridge.bundle.js +0 -109
  47. package/banner.png +0 -0
  48. package/checkpoint.ts +0 -55
  49. package/commands.ts +0 -622
  50. package/config.ts +0 -1204
  51. package/consent-manager.ts +0 -25
  52. package/direct-tools.ts +0 -75
  53. package/elicitation-handler.ts +0 -349
  54. package/error-signal.ts +0 -21
  55. package/gateway-arguments.ts +0 -73
  56. package/glimpse-ui.ts +0 -80
  57. package/host-html-template.ts +0 -456
  58. package/index.ts +0 -767
  59. package/init.ts +0 -613
  60. package/legacy-migration.ts +0 -47
  61. package/lifecycle.ts +0 -165
  62. package/logger.ts +0 -127
  63. package/mcp-auth-flow.ts +0 -975
  64. package/mcp-auth.ts +0 -793
  65. package/mcp-callback-server.ts +0 -450
  66. package/mcp-code.ts +0 -412
  67. package/mcp-keyring-helper.cjs +0 -89
  68. package/mcp-oauth-provider.ts +0 -774
  69. package/mcp-output-guard.ts +0 -530
  70. package/mcp-panel.ts +0 -907
  71. package/mcp-script-worker.mjs +0 -131
  72. package/mcp-setup-panel.ts +0 -666
  73. package/mcp-status.ts +0 -110
  74. package/mcp-trace.ts +0 -295
  75. package/metadata-cache.ts +0 -271
  76. package/npx-resolver.ts +0 -488
  77. package/onboarding-state.ts +0 -58
  78. package/panel-keys.ts +0 -37
  79. package/prompts.ts +0 -337
  80. package/proxy-modes.ts +0 -1109
  81. package/resource-tools.ts +0 -52
  82. package/runtime-owner.ts +0 -123
  83. package/sampling-handler.ts +0 -276
  84. package/scripts/build-app-bridge.mjs +0 -15
  85. package/scripts/build.mjs +0 -132
  86. package/scripts/prepare.mjs +0 -103
  87. package/search-ranking.ts +0 -132
  88. package/server-manager.ts +0 -1320
  89. package/session-recovery.ts +0 -316
  90. package/state.ts +0 -64
  91. package/tool-approval.ts +0 -78
  92. package/tool-loader.ts +0 -153
  93. package/tool-metadata.ts +0 -240
  94. package/tool-registrar.ts +0 -74
  95. package/tool-result-renderer.ts +0 -294
  96. package/tsconfig.build.json +0 -13
  97. package/tsconfig.json +0 -16
  98. package/types.ts +0 -785
  99. package/ui-resource-handler.ts +0 -249
  100. package/ui-server.ts +0 -808
  101. package/ui-session.ts +0 -568
  102. package/ui-stream-types.ts +0 -89
  103. package/ui-tool-visibility.ts +0 -25
  104. package/unix-socket-transport.ts +0 -85
  105. package/utils.ts +0 -307
package/prompts.ts DELETED
@@ -1,337 +0,0 @@
1
- import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
- import type {
3
- GetPromptResult,
4
- PromptMessage,
5
- } from "@modelcontextprotocol/client";
6
- import type { McpExtensionState } from "./state.ts";
7
- import { isServerDisabled, type McpConfig, type PromptMetadata } from "./types.ts";
8
- import { lazyConnect } from "./init.ts";
9
- import { isServerCacheValid, loadMetadataCache, reconstructPromptMetadata } from "./metadata-cache.ts";
10
- import { logger } from "./logger.ts";
11
- import { truncateAtWord } from "./utils.ts";
12
-
13
- /**
14
- * Resolve prompt metadata for slash-command registration at extension load
15
- * time. Like typed tool registration, reads the persistent metadata cache so
16
- * commands are available before any server connects.
17
- */
18
- export function resolveCachedPrompts(config: McpConfig, cacheEnabled = true): PromptMetadata[] {
19
- const cache = loadMetadataCache(cacheEnabled);
20
- if (!cache?.servers) return [];
21
-
22
- const prefix = config.settings?.toolPrefix ?? "server";
23
- const specs: PromptMetadata[] = [];
24
-
25
- for (const [serverName, entry] of Object.entries(cache.servers)) {
26
- const definition = config.mcpServers[serverName];
27
- if (!definition || isServerDisabled(definition)) continue;
28
- if (!entry?.prompts?.length || !isServerCacheValid(entry, definition)) continue;
29
- specs.push(...reconstructPromptMetadata(serverName, entry.prompts, prefix, definition));
30
- }
31
-
32
- return specs;
33
- }
34
-
35
- /**
36
- * Parse a slash-command argument string into positional and named MCP prompt
37
- * arguments. Supports bash-style quoting so callers can pass values with
38
- * spaces:
39
- *
40
- * /mcp__demo__brief today "important tasks"
41
- * /mcp__demo__brief day=today topic="important tasks"
42
- */
43
- export function parsePromptArgs(input: string): { positional: string[]; named: Record<string, string> } {
44
- const positional: string[] = [];
45
- const named: Record<string, string> = {};
46
-
47
- const tokens = tokenizeArgs(input);
48
- for (const token of tokens) {
49
- const eq = findUnquotedEquals(token);
50
- if (eq > 0) {
51
- const key = token.slice(0, eq).trim();
52
- const value = stripQuotes(token.slice(eq + 1).trim());
53
- if (key) {
54
- named[key] = value;
55
- continue;
56
- }
57
- }
58
- positional.push(stripQuotes(token));
59
- }
60
-
61
- return { positional, named };
62
- }
63
-
64
- function tokenizeArgs(input: string): string[] {
65
- const tokens: string[] = [];
66
- let current = "";
67
- let quote: '"' | "'" | null = null;
68
- let escaped = false;
69
-
70
- for (const char of input) {
71
- if (escaped) {
72
- current += char;
73
- escaped = false;
74
- continue;
75
- }
76
- if (char === "\\" && quote !== "'") {
77
- escaped = true;
78
- continue;
79
- }
80
- if (quote) {
81
- current += char;
82
- if (char === quote) quote = null;
83
- continue;
84
- }
85
- if (char === '"' || char === "'") {
86
- quote = char;
87
- current += char;
88
- continue;
89
- }
90
- if (/\s/.test(char)) {
91
- if (current.length > 0) {
92
- tokens.push(current);
93
- current = "";
94
- }
95
- continue;
96
- }
97
- current += char;
98
- }
99
-
100
- if (current.length > 0) tokens.push(current);
101
- return tokens;
102
- }
103
-
104
- function findUnquotedEquals(token: string): number {
105
- let quote: '"' | "'" | null = null;
106
- for (let i = 0; i < token.length; i++) {
107
- const ch = token[i];
108
- if (quote) {
109
- if (ch === quote) quote = null;
110
- continue;
111
- }
112
- if (ch === '"' || ch === "'") quote = ch;
113
- else if (ch === "=") return i;
114
- }
115
- return -1;
116
- }
117
-
118
- function stripQuotes(value: string): string {
119
- if (value.length >= 2 && (value.startsWith('"') || value.startsWith("'")) && value.endsWith(value.charAt(0))) {
120
- return value.slice(1, -1);
121
- }
122
- return value;
123
- }
124
-
125
- export interface ResolvedPromptArgs {
126
- ok: boolean;
127
- /** Present when `ok === true`. */
128
- args?: Record<string, string>;
129
- /** Present when `ok === false`. */
130
- error?: string;
131
- }
132
-
133
- /**
134
- * Map positional and named arguments onto the prompt's declared argument
135
- * list. Named arguments win over positional when both target the same slot.
136
- * Missing required arguments produce a helpful usage message that the
137
- * command handler surfaces via `ctx.ui.notify`.
138
- */
139
- export function resolvePromptArgs(
140
- metadata: PromptMetadata,
141
- parsed: { positional: string[]; named: Record<string, string> },
142
- ): ResolvedPromptArgs {
143
- const args: Record<string, string> = {};
144
-
145
- const declared = metadata.arguments;
146
- let positionalIndex = 0;
147
- for (const argDef of declared) {
148
- const value = parsed.named[argDef.name] ?? parsed.positional[positionalIndex++];
149
- if (value !== undefined && value !== "") {
150
- args[argDef.name] = value;
151
- }
152
- }
153
-
154
- // Preserve named arguments the prompt did not declare so servers with
155
- // permissive schemas still receive them. The MCP spec allows arbitrary
156
- // string key/values in `prompts/get` params.arguments.
157
- for (const [key, value] of Object.entries(parsed.named)) {
158
- if (!(key in args)) args[key] = value;
159
- }
160
-
161
- const missing = declared.filter(a => a.required && (args[a.name] === undefined || args[a.name] === ""));
162
- if (missing.length > 0) {
163
- return { ok: false, error: buildUsageMessage(metadata, missing) };
164
- }
165
-
166
- return { ok: true, args };
167
- }
168
-
169
- function buildUsageMessage(metadata: PromptMetadata, missing: PromptMetadata["arguments"]): string {
170
- const usage = metadata.arguments
171
- .map(a => (a.required ? `<${a.name}>` : `[${a.name}]`))
172
- .join(" ");
173
- const missingList = missing.map(a => a.name).join(", ");
174
- return `Missing required argument${missing.length > 1 ? "s" : ""}: ${missingList}.\nUsage: /${metadata.commandName} ${usage}`.trim();
175
- }
176
-
177
- /**
178
- * Flatten a `GetPromptResult` into a single string suitable for
179
- * `pi.sendUserMessage`. MCP prompts can contain multiple messages with
180
- * mixed roles; we preserve role attribution as inline markers so the model
181
- * still sees the intended conversational shape without needing a
182
- * multi-message replay API on the pi side.
183
- */
184
- export function formatPromptResult(result: GetPromptResult): string {
185
- const lines: string[] = [];
186
- for (const message of result.messages) {
187
- const text = extractMessageText(message);
188
- if (!text) continue;
189
- if (message.role === "user" && result.messages.length === 1) {
190
- lines.push(text);
191
- } else {
192
- lines.push(`[${message.role}] ${text}`);
193
- }
194
- }
195
- return lines.join("\n\n").trim();
196
- }
197
-
198
- function extractMessageText(message: PromptMessage): string {
199
- const content = message.content;
200
- if (!content || typeof content !== "object") return "";
201
- switch (content.type) {
202
- case "text":
203
- return content.text ?? "";
204
- case "resource": {
205
- const resource = content.resource;
206
- if (!resource) return "";
207
- if ("text" in resource && typeof resource.text === "string") {
208
- return `[resource ${resource.uri}]\n${resource.text}`;
209
- }
210
- return `[resource ${resource.uri}]`;
211
- }
212
- case "resource_link":
213
- return `[resource_link ${content.uri ?? ""}${content.name ? ` — ${content.name}` : ""}]`;
214
- case "image":
215
- return `[image ${content.mimeType ?? "unknown"}${content.data ? " (embedded)" : ""}]`;
216
- case "audio":
217
- return `[audio ${content.mimeType ?? "unknown"}]`;
218
- default:
219
- return "";
220
- }
221
- }
222
-
223
- /**
224
- * Build the pi command definition for a single MCP prompt. Registered once
225
- * per prompt at extension load time from the metadata cache; the same
226
- * factory is reused by tests to invoke the handler without a running pi.
227
- */
228
- export function createPromptCommand(
229
- pi: ExtensionAPI,
230
- getState: () => McpExtensionState | null,
231
- metadata: PromptMetadata,
232
- ) {
233
- const description = buildCommandDescription(metadata);
234
-
235
- return {
236
- description,
237
- handler: async (args: string, ctx: ExtensionCommandContext) => {
238
- const state = getState();
239
- if (!state) {
240
- if (ctx.hasUI) ctx.ui.notify("MCP not initialized", "error");
241
- return;
242
- }
243
-
244
- const liveMetadata = findLivePromptMetadata(state, metadata.serverName, metadata.originalName);
245
- if (state.promptMetadataLive?.has(metadata.serverName) && !liveMetadata) {
246
- if (ctx.hasUI) {
247
- ctx.ui.notify(
248
- `MCP prompt "${metadata.originalName}" is no longer advertised by server "${metadata.serverName}". Run /mcp reconnect to refresh.`,
249
- "error",
250
- );
251
- }
252
- return;
253
- }
254
- const live = liveMetadata ?? metadata;
255
- const parsed = parsePromptArgs(args ?? "");
256
- const resolved = resolvePromptArgs(live, parsed);
257
- if (!resolved.ok) {
258
- if (ctx.hasUI) ctx.ui.notify(resolved.error ?? "Invalid prompt arguments", "error");
259
- return;
260
- }
261
- const promptArgs = resolved.args ?? {};
262
-
263
- if (!state.config.mcpServers[metadata.serverName]) {
264
- if (ctx.hasUI) {
265
- ctx.ui.notify(
266
- `MCP prompt "${live.originalName}" is no longer configured. Run /mcp reconnect to refresh.`,
267
- "error",
268
- );
269
- }
270
- return;
271
- }
272
-
273
- const connected = await lazyConnect(state, metadata.serverName, ctx.signal);
274
- if (!connected) {
275
- if (ctx.hasUI) {
276
- const conn = state.manager.getConnection(metadata.serverName);
277
- const message = conn?.status === "needs-auth"
278
- ? `MCP server "${metadata.serverName}" needs authentication. Run /mcp-auth ${metadata.serverName}.`
279
- : `MCP server "${metadata.serverName}" is not available. Run /mcp reconnect ${metadata.serverName}.`;
280
- ctx.ui.notify(message, "error");
281
- }
282
- return;
283
- }
284
-
285
- const refreshed = findLivePromptMetadata(state, metadata.serverName, metadata.originalName);
286
- if (state.promptMetadataLive?.has(metadata.serverName) && !refreshed) {
287
- if (ctx.hasUI) {
288
- ctx.ui.notify(
289
- `MCP prompt "${metadata.originalName}" is no longer advertised by server "${metadata.serverName}". Run /mcp reconnect to refresh.`,
290
- "error",
291
- );
292
- }
293
- return;
294
- }
295
- const dispatchMetadata = refreshed ?? live;
296
- let result: GetPromptResult;
297
- try {
298
- result = await state.manager.getPrompt(
299
- metadata.serverName,
300
- dispatchMetadata.originalName,
301
- Object.keys(promptArgs).length > 0 ? promptArgs : undefined,
302
- ctx.signal,
303
- );
304
- } catch (error) {
305
- const message = error instanceof Error ? error.message : String(error);
306
- logger.debug(`MCP prompt "${live.originalName}" on ${metadata.serverName} failed: ${message}`);
307
- if (ctx.hasUI) {
308
- ctx.ui.notify(`MCP prompt "${live.originalName}" failed: ${message}`, "error");
309
- }
310
- return;
311
- }
312
-
313
- const text = formatPromptResult(result);
314
- if (!text) {
315
- if (ctx.hasUI) {
316
- ctx.ui.notify(`MCP prompt "${live.originalName}" returned no text content.`, "warning");
317
- }
318
- return;
319
- }
320
-
321
- pi.sendUserMessage(text);
322
- },
323
- };
324
- }
325
-
326
- function findLivePromptMetadata(
327
- state: McpExtensionState,
328
- serverName: string,
329
- originalName: string,
330
- ): PromptMetadata | undefined {
331
- return state.promptMetadata?.get(serverName)?.find(p => p.originalName === originalName);
332
- }
333
-
334
- function buildCommandDescription(metadata: PromptMetadata): string {
335
- const base = metadata.description || metadata.title || `MCP prompt from ${metadata.serverName}`;
336
- return truncateAtWord(`MCP: ${base}`, 120) || `MCP prompt from ${metadata.serverName}`;
337
- }