@fitchmultz/pi-mcp-adapter 6.0.0 → 7.1.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 (111) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/OAUTH.md +1 -1
  3. package/README.md +27 -18
  4. package/dist/app-bridge.bundle.js +14 -14
  5. package/dist/config.js +41 -16
  6. package/dist/direct-tools.js +1 -1
  7. package/dist/gateway-arguments.d.ts +1 -1
  8. package/dist/index.js +38 -59
  9. package/dist/lifecycle.d.ts +2 -2
  10. package/dist/lifecycle.js +2 -2
  11. package/dist/mcp-auth-flow.js +2 -2
  12. package/dist/mcp-auth.d.ts +1 -1
  13. package/dist/mcp-auth.js +3 -3
  14. package/dist/mcp-code.d.ts +6 -6
  15. package/dist/mcp-code.js +11 -10
  16. package/dist/mcp-oauth-provider.d.ts +5 -5
  17. package/dist/mcp-oauth-provider.js +5 -5
  18. package/dist/mcp-output-guard.d.ts +1 -1
  19. package/dist/mcp-output-guard.js +1 -1
  20. package/dist/mcp-panel.d.ts +2 -2
  21. package/dist/mcp-panel.js +2 -2
  22. package/dist/mcp-setup-panel.d.ts +5 -4
  23. package/dist/mcp-setup-panel.js +15 -7
  24. package/dist/mcp-trace.d.ts +1 -1
  25. package/dist/mcp-trace.js +1 -1
  26. package/dist/npx-resolver.js +8 -4
  27. package/dist/proxy-modes.d.ts +2 -2
  28. package/dist/proxy-modes.js +20 -19
  29. package/dist/sampling-handler.js +1 -0
  30. package/dist/search-ranking.js +6 -2
  31. package/dist/server-manager.d.ts +2 -2
  32. package/dist/server-manager.js +44 -27
  33. package/dist/session-recovery.d.ts +7 -4
  34. package/dist/session-recovery.js +76 -10
  35. package/dist/tool-loader.d.ts +7 -2
  36. package/dist/tool-loader.js +56 -5
  37. package/dist/tool-metadata.d.ts +43 -43
  38. package/dist/tool-result-renderer.d.ts +3 -3
  39. package/dist/tool-result-renderer.js +3 -3
  40. package/dist/ui-resource-handler.d.ts +2 -2
  41. package/dist/ui-resource-handler.js +2 -2
  42. package/dist/ui-server.js +5 -4
  43. package/dist/ui-stream-types.d.ts +8 -8
  44. package/dist/unix-socket-transport.d.ts +1 -1
  45. package/dist/unix-socket-transport.js +1 -1
  46. package/dist/utils.d.ts +1 -0
  47. package/dist/utils.js +14 -0
  48. package/package.json +34 -98
  49. package/skills/mcp-scripting/SKILL.md +2 -0
  50. package/abort.ts +0 -34
  51. package/agent-dir.ts +0 -24
  52. package/app-bridge.bundle.js +0 -109
  53. package/banner.png +0 -0
  54. package/checkpoint.ts +0 -55
  55. package/commands.ts +0 -622
  56. package/config.ts +0 -1204
  57. package/consent-manager.ts +0 -25
  58. package/direct-tools.ts +0 -75
  59. package/elicitation-handler.ts +0 -349
  60. package/error-signal.ts +0 -21
  61. package/gateway-arguments.ts +0 -73
  62. package/glimpse-ui.ts +0 -80
  63. package/host-html-template.ts +0 -456
  64. package/index.ts +0 -767
  65. package/init.ts +0 -613
  66. package/legacy-migration.ts +0 -47
  67. package/lifecycle.ts +0 -165
  68. package/logger.ts +0 -127
  69. package/mcp-auth-flow.ts +0 -975
  70. package/mcp-auth.ts +0 -793
  71. package/mcp-callback-server.ts +0 -450
  72. package/mcp-code.ts +0 -412
  73. package/mcp-keyring-helper.cjs +0 -89
  74. package/mcp-oauth-provider.ts +0 -774
  75. package/mcp-output-guard.ts +0 -530
  76. package/mcp-panel.ts +0 -907
  77. package/mcp-script-worker.mjs +0 -131
  78. package/mcp-setup-panel.ts +0 -666
  79. package/mcp-status.ts +0 -110
  80. package/mcp-trace.ts +0 -295
  81. package/metadata-cache.ts +0 -271
  82. package/npx-resolver.ts +0 -488
  83. package/onboarding-state.ts +0 -58
  84. package/panel-keys.ts +0 -37
  85. package/prompts.ts +0 -337
  86. package/proxy-modes.ts +0 -1109
  87. package/resource-tools.ts +0 -52
  88. package/runtime-owner.ts +0 -123
  89. package/sampling-handler.ts +0 -276
  90. package/scripts/build-app-bridge.mjs +0 -15
  91. package/scripts/build.mjs +0 -132
  92. package/scripts/prepare.mjs +0 -103
  93. package/search-ranking.ts +0 -132
  94. package/server-manager.ts +0 -1320
  95. package/session-recovery.ts +0 -316
  96. package/state.ts +0 -64
  97. package/tool-approval.ts +0 -78
  98. package/tool-loader.ts +0 -153
  99. package/tool-metadata.ts +0 -240
  100. package/tool-registrar.ts +0 -74
  101. package/tool-result-renderer.ts +0 -294
  102. package/tsconfig.build.json +0 -13
  103. package/tsconfig.json +0 -16
  104. package/types.ts +0 -785
  105. package/ui-resource-handler.ts +0 -249
  106. package/ui-server.ts +0 -808
  107. package/ui-session.ts +0 -568
  108. package/ui-stream-types.ts +0 -89
  109. package/ui-tool-visibility.ts +0 -25
  110. package/unix-socket-transport.ts +0 -85
  111. package/utils.ts +0 -307
@@ -1,85 +0,0 @@
1
- import { createConnection, type Socket } from "node:net";
2
- import { ReadBuffer, serializeMessage } from "@modelcontextprotocol/client";
3
- import type { Transport } from "@modelcontextprotocol/client";
4
- import type { JSONRPCMessage } from "@modelcontextprotocol/client";
5
-
6
- /** MCP JSONL transport for an explicitly configured Unix-domain socket. */
7
- export class UnixSocketClientTransport implements Transport {
8
- private socket: Socket | undefined;
9
- private readonly readBuffer = new ReadBuffer();
10
-
11
- onclose?: () => void;
12
- onerror?: (error: Error) => void;
13
- onmessage?: (message: JSONRPCMessage) => void;
14
-
15
- constructor(private readonly socketPath: string) {}
16
-
17
- async start(): Promise<void> {
18
- if (this.socket) {
19
- throw new Error("UnixSocketClientTransport already started");
20
- }
21
-
22
- await new Promise<void>((resolve, reject) => {
23
- const socket = createConnection(this.socketPath);
24
- this.socket = socket;
25
- let connected = false;
26
-
27
- socket.once("connect", () => {
28
- connected = true;
29
- resolve();
30
- });
31
- socket.on("data", chunk => {
32
- try {
33
- this.readBuffer.append(chunk);
34
- while (true) {
35
- const message = this.readBuffer.readMessage();
36
- if (message === null) break;
37
- this.onmessage?.(message);
38
- }
39
- } catch (error) {
40
- const cause = error instanceof Error ? error : new Error(String(error));
41
- this.onerror?.(cause);
42
- void this.close();
43
- }
44
- });
45
- socket.on("error", error => {
46
- if (!connected) reject(error);
47
- this.onerror?.(error);
48
- });
49
- socket.on("close", () => {
50
- if (this.socket === socket) this.socket = undefined;
51
- this.readBuffer.clear();
52
- this.onclose?.();
53
- });
54
- });
55
- }
56
-
57
- async close(): Promise<void> {
58
- const socket = this.socket;
59
- this.socket = undefined;
60
- this.readBuffer.clear();
61
- if (!socket || socket.destroyed) return;
62
-
63
- await new Promise<void>(resolve => {
64
- const timeout = setTimeout(() => socket.destroy(), 2_000);
65
- timeout.unref();
66
- socket.once("close", () => {
67
- clearTimeout(timeout);
68
- resolve();
69
- });
70
- socket.end();
71
- });
72
- }
73
-
74
- async send(message: JSONRPCMessage): Promise<void> {
75
- const socket = this.socket;
76
- if (!socket || socket.destroyed) throw new Error("Unix socket is not connected");
77
-
78
- await new Promise<void>((resolve, reject) => {
79
- socket.write(serializeMessage(message), error => {
80
- if (error) reject(error);
81
- else resolve();
82
- });
83
- });
84
- }
85
- }
package/utils.ts DELETED
@@ -1,307 +0,0 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import { spawnSync } from "node:child_process";
3
- import { homedir, platform } from "node:os";
4
- import { join } from "node:path";
5
- import type { McpConfig, ServerEntry } from "./types.ts";
6
-
7
- export function normalizeRequestTimeoutMs(timeoutMs: number | undefined): number | undefined {
8
- return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0
9
- ? timeoutMs
10
- : undefined;
11
- }
12
-
13
- async function execOpen(pi: ExtensionAPI, target: string, browser?: string, signal?: AbortSignal) {
14
- const os = platform();
15
-
16
- if (os === "darwin") {
17
- return browser
18
- ? pi.exec("open", ["-a", browser, target], signal ? { signal } : {})
19
- : pi.exec("open", [target], signal ? { signal } : {});
20
- }
21
- if (os === "win32") {
22
- return browser
23
- ? pi.exec("cmd", ["/c", "start", "", browser, target], signal ? { signal } : {})
24
- : pi.exec("cmd", ["/c", "start", "", target], signal ? { signal } : {});
25
- }
26
- return browser
27
- ? pi.exec(browser, [target], signal ? { signal } : {})
28
- : pi.exec("xdg-open", [target], signal ? { signal } : {});
29
- }
30
-
31
- export async function openUrl(pi: ExtensionAPI, url: string, browser?: string, signal?: AbortSignal): Promise<void> {
32
- const result = await execOpen(pi, url, browser, signal);
33
- if (result.code !== 0) {
34
- throw new Error(result.stderr || `Failed to open browser (exit code ${result.code})`);
35
- }
36
- }
37
-
38
- export async function openPath(pi: ExtensionAPI, targetPath: string): Promise<void> {
39
- const result = await execOpen(pi, targetPath);
40
- if (result.code !== 0) {
41
- throw new Error(result.stderr || `Failed to open path (exit code ${result.code})`);
42
- }
43
- }
44
-
45
- export async function parallelLimit<T, R>(
46
- items: T[],
47
- limit: number,
48
- fn: (item: T) => Promise<R>
49
- ): Promise<R[]> {
50
- const results: R[] = [];
51
- const iterator = items.entries();
52
-
53
- async function worker() {
54
- while (true) {
55
- const next = iterator.next();
56
- if (next.done) return;
57
- const [index, item] = next.value;
58
- results[index] = await fn(item);
59
- }
60
- }
61
-
62
- const workers = Array(Math.min(limit, items.length)).fill(null).map(() => worker());
63
- await Promise.all(workers);
64
- return results;
65
- }
66
-
67
-
68
- export function interpolateEnvVars(value: string): string {
69
- return value
70
- .replace(/\$\{(\w+)\}/g, (_, name) => process.env[name] ?? "")
71
- .replace(/\$env:(\w+)/g, (_, name) => process.env[name] ?? "")
72
- .replace(/\{env:(\w+)\}/g, (_, name) => process.env[name] ?? "");
73
- }
74
-
75
- function getMissingEnvVars(value: string): string[] {
76
- const missing = new Set<string>();
77
- for (const match of value.matchAll(/\$\{(\w+)\}|\$env:(\w+)|\{env:(\w+)\}/g)) {
78
- const name = match[1] ?? match[2] ?? match[3];
79
- if (name && process.env[name] === undefined) {
80
- missing.add(name);
81
- }
82
- }
83
- return [...missing];
84
- }
85
-
86
- export function toStringRecord(value: unknown): Record<string, string> | undefined {
87
- if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
88
-
89
- const result: Record<string, string> = {};
90
- for (const [key, entry] of Object.entries(value)) {
91
- if (typeof entry === "string") result[key] = entry;
92
- }
93
- return Object.keys(result).length > 0 ? result : undefined;
94
- }
95
-
96
- function interpolateSecretExpression(value: string): string {
97
- if (value.startsWith("!!")) return interpolateEnvVars(value.slice(1));
98
- return value.startsWith("!") ? value : interpolateEnvVars(value);
99
- }
100
-
101
- export function interpolateEnvRecord(values: Record<string, string> | undefined): Record<string, string> | undefined {
102
- if (!values) return undefined;
103
-
104
- return Object.fromEntries(Object.entries(values).map(([key, value]) => [
105
- key,
106
- interpolateSecretExpression(value),
107
- ]));
108
- }
109
-
110
- const COMMAND_SECRET_TIMEOUT_MS = 10_000;
111
- const COMMAND_SECRET_MAX_OUTPUT_BYTES = 1024 * 1024;
112
-
113
- /** Resolve a secret value, executing only a single leading `!` command marker. */
114
- export function resolveCommandSecret(value: string, context: string): string;
115
- export function resolveCommandSecret(value: undefined, context: string): undefined;
116
- export function resolveCommandSecret(value: string | undefined, context: string): string | undefined;
117
- export function resolveCommandSecret(value: string | undefined, context: string): string | undefined {
118
- if (value === undefined) return undefined;
119
- if (value.startsWith("!!")) return interpolateEnvVars(value.slice(1));
120
- if (!value.startsWith("!")) return interpolateEnvVars(value);
121
-
122
- let result;
123
- try {
124
- result = spawnSync(value.slice(1), {
125
- shell: true,
126
- encoding: "utf8",
127
- timeout: COMMAND_SECRET_TIMEOUT_MS,
128
- maxBuffer: COMMAND_SECRET_MAX_OUTPUT_BYTES,
129
- stdio: ["ignore", "pipe", "ignore"],
130
- windowsHide: true,
131
- });
132
- } catch {
133
- throw new Error(`Failed to resolve ${context}: command failed to start`);
134
- }
135
- if (result.error) {
136
- const code = (result.error as NodeJS.ErrnoException).code;
137
- const reason = code === "ETIMEDOUT"
138
- ? "command timed out after 10 seconds"
139
- : code === "ENOBUFS"
140
- ? "command output exceeded 1 MiB"
141
- : "command failed to start";
142
- throw new Error(`Failed to resolve ${context}: ${reason}`);
143
- }
144
- if (result.status !== 0) {
145
- throw new Error(`Failed to resolve ${context}: command exited with code ${result.status ?? "unknown"}`);
146
- }
147
-
148
- const resolved = result.stdout.trim();
149
- if (!resolved) throw new Error(`Failed to resolve ${context}: command returned empty output`);
150
- return resolved;
151
- }
152
-
153
- /** Resolve command markers in a configured record without mutating the input. */
154
- export function resolveCommandSecretsRecord(
155
- values: Record<string, string> | undefined,
156
- context: (key: string) => string,
157
- ): Record<string, string> | undefined {
158
- if (!values) return undefined;
159
-
160
- return Object.fromEntries(Object.entries(values).map(([key, value]) => [
161
- key,
162
- resolveCommandSecret(value, context(key)),
163
- ]));
164
- }
165
-
166
- export function resolveServerUrl(definition: Pick<ServerEntry, "url">): string | undefined {
167
- if (definition.url == null) return undefined;
168
- if (typeof definition.url !== "string") {
169
- throw new Error("MCP server URL must be a string");
170
- }
171
-
172
- const missing = getMissingEnvVars(definition.url);
173
- if (missing.length > 0) {
174
- throw new Error(`Missing environment variable${missing.length === 1 ? "" : "s"} in MCP server URL: ${missing.join(", ")}`);
175
- }
176
-
177
- const resolved = interpolateEnvVars(definition.url);
178
- try {
179
- new URL(resolved);
180
- } catch (error) {
181
- throw new Error(`Invalid MCP server URL after environment interpolation: ${resolved}`, { cause: error });
182
- }
183
- return resolved;
184
- }
185
-
186
- export function resolveConfigPath(value: string | undefined): string | undefined {
187
- if (value === undefined) return undefined;
188
-
189
- const resolved = interpolateEnvVars(value);
190
- if (resolved === "~") return homedir();
191
- if (resolved.startsWith("~/") || resolved.startsWith("~\\")) {
192
- return join(homedir(), resolved.slice(2));
193
- }
194
- return resolved;
195
- }
196
-
197
- export function resolveBearerToken(definition: Pick<ServerEntry, "bearerToken" | "bearerTokenEnv">): string | undefined {
198
- if (definition.bearerToken !== undefined) {
199
- return interpolateSecretExpression(definition.bearerToken);
200
- }
201
- return definition.bearerTokenEnv ? process.env[definition.bearerTokenEnv] : undefined;
202
- }
203
-
204
- /** Remove OSC control strings, including payloads that have no terminator. */
205
- export function stripOscSequences(text: string): string {
206
- let result = "";
207
- let index = 0;
208
- while (index < text.length) {
209
- const isEscOsc = text.charCodeAt(index) === 0x1b && text[index + 1] === "]";
210
- const isC1Osc = text.charCodeAt(index) === 0x9d;
211
- if (!isEscOsc && !isC1Osc) {
212
- result += text[index++];
213
- continue;
214
- }
215
-
216
- index += isEscOsc ? 2 : 1;
217
- while (index < text.length) {
218
- const code = text.charCodeAt(index++);
219
- if (code === 0x07 || code === 0x9c) break;
220
- if (code === 0x1b && text[index] === "\\") {
221
- index++;
222
- break;
223
- }
224
- }
225
- }
226
- return result;
227
- }
228
-
229
- export function sanitizeTerminalText(text: string): string {
230
- return stripOscSequences(text)
231
- .replace(/(?:\x1b\[[0-?]*[ -/]*[@-~]|\x1b[@-Z\\-_])/g, "")
232
- .replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ")
233
- .replace(/\s+/g, " ")
234
- .trim();
235
- }
236
-
237
- export function formatTerminalError(error: unknown): string {
238
- const messages: string[] = [];
239
- const seen = new Set<unknown>();
240
- const collect = (value: unknown) => {
241
- if (seen.has(value)) return;
242
- if ((typeof value === "object" && value !== null) || typeof value === "function") seen.add(value);
243
-
244
- if (value instanceof AggregateError) {
245
- const countBefore = messages.length;
246
- for (const nested of value.errors) collect(nested);
247
- if (value.cause !== undefined) collect(value.cause);
248
- if (messages.length === countBefore && value.message) messages.push(value.message);
249
- return;
250
- }
251
- if (value instanceof Error) {
252
- if (value.message) messages.push(value.message);
253
- if (value.cause !== undefined) collect(value.cause);
254
- return;
255
- }
256
- messages.push(String(value));
257
- };
258
-
259
- collect(error);
260
- return sanitizeTerminalText([...new Set(messages)].join(": "));
261
- }
262
-
263
- export function truncateAtWord(text: string, target: number): string {
264
- if (!text || text.length <= target) return text;
265
-
266
- const truncated = text.slice(0, target);
267
- const lastSpace = truncated.lastIndexOf(" ");
268
-
269
- if (lastSpace > target * 0.6) {
270
- return truncated.slice(0, lastSpace) + "...";
271
- }
272
-
273
- return truncated + "...";
274
- }
275
-
276
- export function normalizeDirectToolInputSchema(schema: unknown): Record<string, unknown> {
277
- return schema && typeof schema === "object" && !Array.isArray(schema)
278
- ? structuredClone(schema) as Record<string, unknown>
279
- : { type: "object", properties: {} };
280
- }
281
-
282
- export function formatAuthRequiredMessage(
283
- config: Pick<McpConfig, "settings">,
284
- serverName: string,
285
- defaultMessage: string,
286
- ): string {
287
- const template = config.settings?.authRequiredMessage;
288
- return template ? template.replaceAll("${server}", serverName) : defaultMessage;
289
- }
290
-
291
- export function formatMcpStatus(config: Pick<McpConfig, "settings">, message: string): string | undefined {
292
- if (config.settings?.mcpFooterStatus === "off") return undefined;
293
- return `${config.settings?.showStatusIcon === false ? "MCP: " : "🔌 MCP: "}${message}`;
294
- }
295
-
296
- /**
297
- * Extract the adapter-owned UI stream mode from tool metadata.
298
- */
299
- export function extractToolUiStreamMode(toolMeta: Record<string, unknown> | undefined): "eager" | "stream-first" | undefined {
300
- const uiMeta = toolMeta?.ui;
301
- if (!uiMeta || typeof uiMeta !== "object") return undefined;
302
- const streamMode = (uiMeta as Record<string, unknown>)["pi-mcp-adapter.streamMode"];
303
- if (streamMode === "eager" || streamMode === "stream-first") {
304
- return streamMode;
305
- }
306
- return undefined;
307
- }