@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,25 +0,0 @@
1
- import { logger } from "./logger.ts";
2
-
3
- export class ConsentManager {
4
- private decisions = new Map<string, boolean>();
5
- private log = logger.child({ component: "ConsentManager" });
6
-
7
- hasDecisions(): boolean { return this.decisions.size > 0; }
8
-
9
- requiresPrompt(serverName: string): boolean {
10
- return this.decisions.get(serverName) !== true;
11
- }
12
-
13
- registerDecision(serverName: string, approved: boolean): void {
14
- this.decisions.set(serverName, approved);
15
- this.log.debug(`Consent ${approved ? "granted" : "denied"}`, { server: serverName });
16
- }
17
-
18
- ensureApproved(serverName: string): void {
19
- const decision = this.decisions.get(serverName);
20
- if (decision === true) return;
21
- throw new Error(decision === false
22
- ? `Tool calls for "${serverName}" were denied for this session`
23
- : `Tool call approval required for "${serverName}"`);
24
- }
25
- }
package/direct-tools.ts DELETED
@@ -1,75 +0,0 @@
1
- import type { AgentToolResult, AgentToolUpdateCallback, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import type { McpExtensionState } from "./state.ts";
3
- import type { DirectToolSpec, McpAdapterOptions, McpConfig } from "./types.ts";
4
- import { abortable, throwIfAborted } from "./abort.ts";
5
- import { parseDirectToolSelectors } from "./metadata-cache.ts";
6
- export { getMissingConfiguredDirectToolServers } from "./metadata-cache.ts";
7
- import { executeCall } from "./proxy-modes.ts";
8
- import { isServerDisabled } from "./types.ts";
9
-
10
- export function directToolSelection(config: McpConfig, serverName: string, envOverride?: string[]): true | string[] | false {
11
- if (envOverride) {
12
- const selection = parseDirectToolSelectors(envOverride);
13
- if (selection.servers.has(serverName)) return true;
14
- return selection.tools.has(serverName) ? [...selection.tools.get(serverName)!] : false;
15
- }
16
- return config.mcpServers[serverName]?.directTools ?? config.settings?.directTools ?? false;
17
- }
18
-
19
- export function buildProxyDescription(config: McpConfig): string {
20
- const servers = Object.entries(config.mcpServers).filter(([, definition]) => !isServerDisabled(definition)).map(([name]) => name).sort();
21
- return [
22
- "MCP gateway. Use mcp_search to discover and load typed tools; mcp_script for multi-call composition. Native Pi tools are called directly.",
23
- `Configured servers: ${servers.join(", ") || "none"}. Catalog discovery is lazy.`,
24
- "Actions: status; list/search/describe; call (tool,args,server?); connect (server); instructions (server); resources (server); read-resource (server,uri); read-result (ref,path?,fields?,offset?,limit?); auth-start/auth-complete (server,args?); ui-messages.",
25
- "Use call when a discovered direct tool is unavailable in this host. read-result reads a retained response without repeating the remote operation.",
26
- ].join("\n");
27
- }
28
-
29
- type DirectToolExecute = (
30
- toolCallId: string,
31
- params: Record<string, unknown>,
32
- signal: AbortSignal | undefined,
33
- onUpdate: AgentToolUpdateCallback<Record<string, unknown>> | undefined,
34
- ctx: ExtensionContext,
35
- ) => Promise<AgentToolResult<Record<string, unknown>>>;
36
-
37
- export function createDirectToolExecutor(
38
- getState: () => McpExtensionState | null,
39
- getInitPromise: () => Promise<McpExtensionState> | null,
40
- spec: DirectToolSpec,
41
- beforeExecute?: McpAdapterOptions["beforeExecute"],
42
- ): DirectToolExecute {
43
- return async function execute(toolCallId, params, signal, _onUpdate, ctx) {
44
- throwIfAborted(signal);
45
- let state = getState();
46
- const initPromise = getInitPromise();
47
-
48
- if (!state && initPromise) {
49
- try {
50
- state = await abortable(initPromise, signal);
51
- } catch (error) {
52
- throwIfAborted(signal);
53
- const message = error instanceof Error ? error.message : String(error);
54
- return {
55
- content: [{ type: "text" as const, text: `MCP initialization failed: ${message}` }],
56
- details: { error: "init_failed", message },
57
- };
58
- }
59
- }
60
- if (!state) {
61
- return {
62
- content: [{ type: "text" as const, text: "MCP not initialized" }],
63
- details: { error: "not_initialized" },
64
- };
65
- }
66
-
67
- const result = await executeCall(
68
- state, spec.originalName, params, spec.serverName, undefined, signal, { toolCallId },
69
- beforeExecute ? (callSignal, operation) => beforeExecute(toolCallId, { ...ctx, signal: callSignal }, operation) : undefined,
70
- { exactOriginalName: true, ...(spec.resourceUri ? { resourceUri: spec.resourceUri } : {}) },
71
- );
72
- const { mode: _mode, ...details } = result.details;
73
- return { ...result, details };
74
- };
75
- }
@@ -1,349 +0,0 @@
1
- import type { ExtensionUIContext } from "@earendil-works/pi-coding-agent";
2
- import type { Client } from "@modelcontextprotocol/client";
3
- import {
4
- ProtocolErrorCode,
5
- ProtocolError,
6
- type ElicitRequest,
7
- type ElicitRequestFormParams,
8
- type ElicitRequestURLParams,
9
- type ElicitResult,
10
- } from "@modelcontextprotocol/client";
11
- import { AjvJsonSchemaValidator } from "@modelcontextprotocol/client/validators/ajv";
12
- import type { JsonSchemaType } from "@modelcontextprotocol/client";
13
- import open from "open";
14
-
15
- export type ElicitationValue = string | number | boolean | string[] | undefined;
16
- type FormProperty = ElicitRequestFormParams["requestedSchema"]["properties"][string];
17
-
18
- export type ElicitationUIContext = ExtensionUIContext;
19
-
20
- export interface ElicitationHandlerOptions {
21
- serverName: string;
22
- ui: ElicitationUIContext;
23
- allowUrl: boolean;
24
- onUrlAccepted?: (elicitationId: string) => void;
25
- }
26
-
27
- export type ServerElicitationConfig = Omit<ElicitationHandlerOptions, "serverName" | "onUrlAccepted">;
28
-
29
- export function registerElicitationHandler(
30
- client: Client,
31
- options: ElicitationHandlerOptions,
32
- own: (run: () => Promise<ElicitResult>) => Promise<ElicitResult> = run => run(),
33
- ): void {
34
- client.setRequestHandler("elicitation/create", request => own(() => handleElicitationRequest(options, request)));
35
- }
36
-
37
- export async function handleElicitationRequest(
38
- options: ElicitationHandlerOptions,
39
- request: ElicitRequest,
40
- ): Promise<ElicitResult> {
41
- return request.params.mode === "url"
42
- ? handleUrlElicitation(options, request.params)
43
- : handleFormElicitation(options, request.params);
44
- }
45
-
46
- export async function handleFormElicitation(
47
- options: ElicitationHandlerOptions,
48
- params: ElicitRequestFormParams,
49
- ): Promise<ElicitResult> {
50
- const decision = await options.ui.select(
51
- `MCP Input Request\nServer: ${options.serverName}\n\n${params.message}`,
52
- ["Continue", "Decline"],
53
- );
54
- if (decision === undefined) return { action: "cancel" };
55
- if (decision === "Decline") return { action: "decline" };
56
-
57
- const values: Record<string, ElicitationValue> = {};
58
- const properties = Object.entries(params.requestedSchema.properties);
59
- for (const [name, schema] of properties) {
60
- const value = await collectValidField(options.ui, params, name, schema);
61
- if (!("value" in value)) return { action: "cancel" };
62
- values[name] = value.value;
63
- }
64
-
65
- while (true) {
66
- const content = coerceAndValidateFormValues(params, values);
67
- const action = await options.ui.select(
68
- formatReview(options.serverName, properties, content),
69
- properties.length > 0 ? ["Submit", "Edit", "Decline"] : ["Submit", "Decline"],
70
- );
71
- if (action === undefined) return { action: "cancel" };
72
- if (action === "Decline") return { action: "decline" };
73
- if (action === "Submit") return { action: "accept", content };
74
-
75
- const labels = properties.map(([name, schema]) => `${schema.title ?? humanizeName(name)} (${name})`);
76
- const selected = await options.ui.select("Choose a field to edit", labels);
77
- if (selected === undefined) return { action: "cancel" };
78
- const property = properties[labels.indexOf(selected)];
79
- if (!property) continue;
80
- const [name, schema] = property;
81
- const value = await collectValidField(options.ui, params, name, schema, values[name]);
82
- if (!("value" in value)) return { action: "cancel" };
83
- values[name] = value.value;
84
- }
85
- }
86
-
87
- async function collectValidField(
88
- ui: ElicitationUIContext,
89
- params: ElicitRequestFormParams,
90
- name: string,
91
- schema: FormProperty,
92
- current?: ElicitationValue,
93
- ): Promise<{ cancelled: true } | { cancelled: false; value: ElicitationValue }> {
94
- const required = params.requestedSchema.required?.includes(name) === true;
95
- while (true) {
96
- const result = await collectField(ui, params, name, schema, current);
97
- if (!("value" in result)) return result;
98
- try {
99
- coerceAndValidateFormValues({
100
- ...params,
101
- requestedSchema: {
102
- type: "object",
103
- properties: { [name]: schema },
104
- ...(required ? { required: [name] } : {}),
105
- },
106
- }, { [name]: result.value });
107
- return result;
108
- } catch (error) {
109
- ui.notify(error instanceof Error ? error.message : String(error), "error");
110
- current = result.value;
111
- }
112
- }
113
- }
114
-
115
- async function collectField(
116
- ui: ElicitationUIContext,
117
- params: ElicitRequestFormParams,
118
- name: string,
119
- schema: FormProperty,
120
- current?: ElicitationValue,
121
- ): Promise<{ cancelled: true } | { cancelled: false; value: ElicitationValue }> {
122
- const required = params.requestedSchema.required?.includes(name) === true;
123
- const title = [schema.title ?? humanizeName(name), required ? "(required)" : "", schema.description]
124
- .filter(Boolean)
125
- .join(" ");
126
-
127
- if (schema.type === "string" && ("enum" in schema || "oneOf" in schema)) {
128
- const choices = "oneOf" in schema
129
- ? schema.oneOf.map(option => ({ value: option.const, display: formatChoice(option.const, option.title) }))
130
- : schema.enum.map((value, index) => ({
131
- value,
132
- display: formatChoice(value, "enumNames" in schema ? schema.enumNames?.[index] : undefined),
133
- }));
134
- const displays = uniqueLabels(choices.map(choice => choice.display));
135
- const actions = [...displays];
136
- const useDefault = schema.default === undefined ? undefined : uniqueAction("Use default", actions);
137
- if (useDefault) actions.push(useDefault);
138
- const omit = required ? undefined : uniqueAction("Omit", actions);
139
- if (omit) actions.push(omit);
140
- const action = await ui.select(title, actions);
141
- if (action === undefined) return { cancelled: true };
142
- if (action === useDefault) return { cancelled: false, value: schema.default };
143
- if (action === omit) return { cancelled: false, value: undefined };
144
- return { cancelled: false, value: choices[displays.indexOf(action)]?.value };
145
- }
146
-
147
- if (schema.type === "boolean") {
148
- const actions = ["Yes", "No"];
149
- if (schema.default !== undefined) actions.push("Use default");
150
- if (!required) actions.push("Omit");
151
- const action = await ui.select(title, actions);
152
- if (action === undefined) return { cancelled: true };
153
- if (action === "Use default") return { cancelled: false, value: schema.default };
154
- if (action === "Omit") return { cancelled: false, value: undefined };
155
- return { cancelled: false, value: action === "Yes" };
156
- }
157
-
158
- if (schema.type === "array") {
159
- const actions = ["Choose values"];
160
- if (schema.default !== undefined) actions.push("Use default");
161
- if (!required) actions.push("Omit");
162
- const action = await ui.select(title, actions);
163
- if (action === undefined) return { cancelled: true };
164
- if (action === "Use default") return { cancelled: false, value: schema.default };
165
- if (action === "Omit") return { cancelled: false, value: undefined };
166
-
167
- const choices = extractMultiSelectOptions(schema);
168
- const selected = new Set(Array.isArray(current) ? current : []);
169
- while (true) {
170
- const displays = uniqueLabels(choices.map(choice => selected.has(choice.value) ? `✓ ${choice.display}` : choice.display));
171
- const done = uniqueAction("Done", displays);
172
- const picked = await ui.select(title, [...displays, done]);
173
- if (picked === undefined) return { cancelled: true };
174
- if (picked === done) return { cancelled: false, value: [...selected] };
175
- const choice = choices[displays.indexOf(picked)];
176
- if (!choice) continue;
177
- if (selected.has(choice.value)) selected.delete(choice.value);
178
- else selected.add(choice.value);
179
- }
180
- }
181
-
182
- const actions = ["Enter value"];
183
- if (schema.default !== undefined) actions.push("Use default");
184
- if (!required) actions.push("Omit");
185
- const action = await ui.select(title, actions);
186
- if (action === undefined) return { cancelled: true };
187
- if (action === "Use default") return { cancelled: false, value: schema.default };
188
- if (action === "Omit") return { cancelled: false, value: undefined };
189
- const entered = await ui.input(title, current === undefined ? undefined : String(current));
190
- return entered === undefined ? { cancelled: true } : { cancelled: false, value: entered };
191
- }
192
-
193
- export function coerceAndValidateFormValues(
194
- params: ElicitRequestFormParams,
195
- values: Record<string, ElicitationValue>,
196
- ): Record<string, string | number | boolean | string[]> {
197
- const output: Record<string, string | number | boolean | string[]> = {};
198
- const required = new Set(params.requestedSchema.required ?? []);
199
- for (const [name, schema] of Object.entries(params.requestedSchema.properties)) {
200
- const value = values[name];
201
- if (value === undefined) {
202
- if (required.has(name)) throw new Error(`Missing required elicitation field: ${name}`);
203
- continue;
204
- }
205
- if (schema.type === "string") {
206
- const stringValue = String(value);
207
- const limits = schema as typeof schema & { minLength?: number; maxLength?: number };
208
- if (limits.minLength !== undefined && stringValue.length < limits.minLength) {
209
- throw new Error(`Elicitation field ${name} is shorter than minimum length ${limits.minLength}`);
210
- }
211
- if (limits.maxLength !== undefined && stringValue.length > limits.maxLength) {
212
- throw new Error(`Elicitation field ${name} is longer than maximum length ${limits.maxLength}`);
213
- }
214
- if ("enum" in schema && !schema.enum.includes(stringValue)) {
215
- throw new Error(`Elicitation field ${name} is not an allowed value`);
216
- }
217
- if ("oneOf" in schema && !schema.oneOf.some(option => option.const === stringValue)) {
218
- throw new Error(`Elicitation field ${name} is not an allowed value`);
219
- }
220
- output[name] = stringValue;
221
- continue;
222
- }
223
- if (schema.type === "number" || schema.type === "integer") {
224
- if (typeof value === "string" && value.trim() === "") {
225
- throw new Error(`Elicitation field ${name} must be a number`);
226
- }
227
- const numberValue = typeof value === "number" ? value : Number(value);
228
- if (!Number.isFinite(numberValue)) throw new Error(`Elicitation field ${name} must be a number`);
229
- if (schema.type === "integer" && !Number.isInteger(numberValue)) {
230
- throw new Error(`Elicitation field ${name} must be an integer`);
231
- }
232
- if (schema.minimum !== undefined && numberValue < schema.minimum) {
233
- throw new Error(`Elicitation field ${name} is below minimum ${schema.minimum}`);
234
- }
235
- if (schema.maximum !== undefined && numberValue > schema.maximum) {
236
- throw new Error(`Elicitation field ${name} is above maximum ${schema.maximum}`);
237
- }
238
- output[name] = numberValue;
239
- continue;
240
- }
241
- if (schema.type === "boolean") {
242
- output[name] = typeof value === "boolean" ? value : value === "true";
243
- continue;
244
- }
245
- if (schema.type === "array") {
246
- if (!Array.isArray(value)) throw new Error(`Elicitation field ${name} must be a list`);
247
- const allowed = new Set(extractMultiSelectOptions(schema).map(option => option.value));
248
- const arrayValue = value.map(String);
249
- if (schema.minItems !== undefined && arrayValue.length < schema.minItems) {
250
- throw new Error(`Elicitation field ${name} has fewer than ${schema.minItems} selections`);
251
- }
252
- if (schema.maxItems !== undefined && arrayValue.length > schema.maxItems) {
253
- throw new Error(`Elicitation field ${name} has more than ${schema.maxItems} selections`);
254
- }
255
- if (arrayValue.some(item => !allowed.has(item))) {
256
- throw new Error(`Elicitation field ${name} contains an invalid selection`);
257
- }
258
- output[name] = arrayValue;
259
- }
260
- }
261
- const validation = new AjvJsonSchemaValidator()
262
- .getValidator(params.requestedSchema as JsonSchemaType)(output);
263
- if (!validation.valid) {
264
- throw new Error(`Invalid elicitation response: ${validation.errorMessage}`);
265
- }
266
- return output;
267
- }
268
-
269
- function formatChoice(value: string, title?: string): string {
270
- return title && title !== value ? `${title} (${value})` : value;
271
- }
272
-
273
- function uniqueLabels(labels: string[]): string[] {
274
- const used = new Set<string>();
275
- return labels.map(label => {
276
- let unique = label;
277
- while (used.has(unique)) unique += "…";
278
- used.add(unique);
279
- return unique;
280
- });
281
- }
282
-
283
- function uniqueAction(label: string, choices: string[]): string {
284
- let unique = label;
285
- while (choices.includes(unique)) unique += "…";
286
- return unique;
287
- }
288
-
289
- function extractMultiSelectOptions(schema: Extract<FormProperty, { type: "array" }>): Array<{ value: string; display: string }> {
290
- const items = schema.items as { enum?: string[]; anyOf?: Array<{ const: string; title: string }> };
291
- return items.anyOf
292
- ? items.anyOf.map(option => ({ value: option.const, display: formatChoice(option.const, option.title) }))
293
- : (items.enum ?? []).map(value => ({ value, display: value }));
294
- }
295
-
296
- function formatReview(
297
- serverName: string,
298
- properties: Array<[string, FormProperty]>,
299
- content: Record<string, string | number | boolean | string[]>,
300
- ): string {
301
- const rows = properties.map(([name, schema]) =>
302
- `${schema.title ?? humanizeName(name)}: ${content[name] === undefined ? "(omitted)" : String(content[name])}`);
303
- return [`Review input for ${serverName}`, "", ...rows].join("\n");
304
- }
305
-
306
- export async function handleUrlElicitation(
307
- options: ElicitationHandlerOptions,
308
- params: ElicitRequestURLParams,
309
- ): Promise<ElicitResult> {
310
- if (!options.allowUrl) throw new ProtocolError(ProtocolErrorCode.InvalidParams, "URL elicitation is not supported");
311
-
312
- let parsed: URL;
313
- try {
314
- parsed = new URL(params.url);
315
- } catch {
316
- throw new ProtocolError(ProtocolErrorCode.InvalidParams, "URL elicitation supplied an invalid URL");
317
- }
318
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
319
- throw new ProtocolError(ProtocolErrorCode.InvalidParams, "URL elicitation only supports HTTP and HTTPS URLs");
320
- }
321
-
322
- const decision = await options.ui.select([
323
- "MCP Browser Request",
324
- `Server: ${options.serverName}`,
325
- "",
326
- params.message,
327
- "",
328
- `Host: ${parsed.host}`,
329
- `Full URL: ${params.url}`,
330
- "",
331
- "Open this URL in your browser?",
332
- ].join("\n"), ["Open", "Decline"]);
333
- if (decision === undefined) return { action: "cancel" };
334
- if (decision === "Decline") return { action: "decline" };
335
-
336
- try {
337
- await open(params.url);
338
- } catch (error) {
339
- options.ui.notify(`Could not open MCP elicitation URL: ${error instanceof Error ? error.message : String(error)}`, "error");
340
- return { action: "cancel" };
341
- }
342
- options.onUrlAccepted?.(params.elicitationId);
343
- options.ui.notify("Opened browser for MCP elicitation.", "info");
344
- return { action: "accept" };
345
- }
346
-
347
- function humanizeName(name: string): string {
348
- return name.replace(/[_-]+/g, " ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/^./, char => char.toUpperCase());
349
- }
package/error-signal.ts DELETED
@@ -1,21 +0,0 @@
1
- /**
2
- * Decide the `isError` override for a finished tool result in the `tool_result` hook.
3
- *
4
- * A failed MCP tool call is *returned* (not thrown), tagged `details.error: "tool_error"` (the server
5
- * returned an error result) or `"call_failed"` (the call itself threw and was caught). pi never reads a
6
- * result-level `isError`, so without this such a call is recorded as a success. Returning
7
- * `{ isError: true }` (and nothing else) flips the flag; pi's field-by-field merge keeps the original
8
- * `content` and `details` intact.
9
- *
10
- * Limited to those two codes: the adapter's other `details.error` values (`auth_required`, connection
11
- * states, search/validation feedback, ...) are not failed tool calls, so they get no override.
12
- */
13
- export function toolErrorOverride(details: unknown): { isError: true } | undefined {
14
- if (details && typeof details === "object" && "error" in details) {
15
- const code = (details as { error?: unknown }).error;
16
- if (code === "tool_error" || code === "call_failed") {
17
- return { isError: true };
18
- }
19
- }
20
- return undefined;
21
- }
@@ -1,73 +0,0 @@
1
- import { Type } from "typebox";
2
- import { MAX_PAGE_SIZE, MAX_TOOL_NAME_LENGTH } from "./search-ranking.ts";
3
-
4
- const actions = ["status", "search", "list", "describe", "call", "connect", "instructions", "resources", "read-resource", "read-result", "auth-start", "auth-complete", "ui-messages"] as const;
5
- export type GatewayArguments = {
6
- action: typeof actions[number];
7
- server?: string;
8
- tool?: string;
9
- args?: Record<string, unknown>;
10
- query?: string;
11
- includeSchemas?: boolean;
12
- limit?: number;
13
- offset?: number;
14
- uri?: string;
15
- ref?: string;
16
- path?: string;
17
- fields?: string[];
18
- };
19
-
20
- const requirements: Partial<Record<GatewayArguments["action"], string[]>> = {
21
- search: ["query"], list: ["server"], describe: ["tool"], call: ["tool"],
22
- connect: ["server"], instructions: ["server"], resources: ["server"],
23
- "read-resource": ["server", "uri"], "read-result": ["ref"], "auth-start": ["server"], "auth-complete": ["server"],
24
- };
25
-
26
- export const gatewayParameters = Type.Object({
27
- action: Type.Unsafe<GatewayArguments["action"]>({ type: "string", enum: [...actions] }),
28
- server: Type.Optional(Type.String({ description: "MCP server; required for server and resource actions." })),
29
- tool: Type.Optional(Type.String({ maxLength: MAX_TOOL_NAME_LENGTH, description: "Exact tool name for call or describe. Use server to disambiguate." })),
30
- args: Type.Optional(Type.Object({}, { additionalProperties: true, description: "Tool arguments, or {redirectUrl} for auth-complete." })),
31
- query: Type.Optional(Type.String({ description: "Search terms. Prefer mcp_search to discover and load tools." })),
32
- includeSchemas: Type.Optional(Type.Boolean({ description: "Include complete schemas in search results (default true)." })),
33
- limit: Type.Optional(Type.Integer({ minimum: 1, description: "Page size (default 12, max 100); for read-result, characters of selected JSON." })),
34
- offset: Type.Optional(Type.Integer({ minimum: 0, description: "Zero-based item offset; for read-result, character offset in selected JSON." })),
35
- uri: Type.Optional(Type.String({ description: "Exact MCP resource URI for read-resource." })),
36
- ref: Type.Optional(Type.String({ description: "Saved result reference returned by an earlier MCP call; read-result never calls the server again." })),
37
- path: Type.Optional(Type.String({ description: "JSON Pointer into a saved result, e.g. /structuredContent/rows." })),
38
- fields: Type.Optional(Type.Array(Type.String(), { description: "Immediate object fields to retain when reading a saved result." })),
39
- }, {
40
- additionalProperties: false,
41
- allOf: [
42
- ...Object.entries(requirements).map(([action, required]) => ({ if: { properties: { action: { const: action } } }, then: { required } })),
43
- { if: { properties: { action: { enum: ["search", "list", "connect", "resources"] } } }, then: { properties: { limit: { maximum: MAX_PAGE_SIZE } } } },
44
- ],
45
- });
46
-
47
- /** Migrate stored v5 calls before host validation; the advertised schema stays explicit. */
48
- export function prepareGatewayArguments(input: unknown): GatewayArguments {
49
- if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("MCP arguments must be an object");
50
- const value = input as Record<string, unknown>;
51
- let action = value.action;
52
- const result = { ...value };
53
- if (action === undefined) {
54
- action = value.tool ? "call" : value.connect ? "connect" : value.describe ? "describe" : value.instructions ? "instructions" : value.search !== undefined ? "search" : value.server ? "list" : "status";
55
- if (action === "connect") result.server = value.connect;
56
- if (action === "describe") result.tool = value.describe;
57
- if (action === "instructions") result.server = value.instructions;
58
- if (action === "search") result.query = value.search;
59
- }
60
- for (const key of ["connect", "describe", "instructions", "search"]) delete result[key];
61
- if (!actions.includes(action as GatewayArguments["action"])) throw new Error(`Unknown MCP action: ${String(action)}`);
62
- result.action = action;
63
- if (typeof result.args === "string") {
64
- result.args = result.args === "" ? undefined : JSON.parse(result.args);
65
- }
66
- if (result.args !== undefined && (!result.args || typeof result.args !== "object" || Array.isArray(result.args))) {
67
- throw new Error("Invalid args: expected a JSON object");
68
- }
69
- for (const field of requirements[action as GatewayArguments["action"]] ?? []) {
70
- if (typeof result[field] !== "string" || (field !== "query" && result[field] === "")) throw new Error(`${action} requires ${field}`);
71
- }
72
- return result as GatewayArguments;
73
- }
package/glimpse-ui.ts DELETED
@@ -1,80 +0,0 @@
1
- import { existsSync } from "node:fs";
2
- import { execFileSync } from "node:child_process";
3
- import { join, dirname } from "node:path";
4
- import { platform } from "node:os";
5
- import { createRequire } from "node:module";
6
-
7
- let glimpseAvailable: boolean | null = null;
8
- let resolvedBinaryPath: string | null = null;
9
-
10
- export function isGlimpseAvailable(): boolean {
11
- if (glimpseAvailable !== null) return glimpseAvailable;
12
-
13
- if (platform() !== "darwin") {
14
- glimpseAvailable = false;
15
- return false;
16
- }
17
-
18
- resolvedBinaryPath = getGlimpseBinaryPath();
19
- glimpseAvailable = resolvedBinaryPath !== null;
20
- return glimpseAvailable;
21
- }
22
-
23
- function getGlimpseBinaryPath(): string | null {
24
- if (process.env.GLIMPSE_BINARY && existsSync(process.env.GLIMPSE_BINARY)) {
25
- return process.env.GLIMPSE_BINARY;
26
- }
27
-
28
- // Local node_modules
29
- try {
30
- const require = createRequire(import.meta.url);
31
- const glimpseuiPath = require.resolve("glimpseui");
32
- const binaryPath = join(dirname(glimpseuiPath), "glimpse");
33
- if (existsSync(binaryPath)) return binaryPath;
34
- } catch {}
35
-
36
- // Global npm install
37
- try {
38
- const globalRoot = execFileSync("npm", ["root", "-g"], { encoding: "utf-8" }).trim();
39
- const binaryPath = join(globalRoot, "glimpseui", "src", "glimpse");
40
- if (existsSync(binaryPath)) return binaryPath;
41
- } catch {}
42
-
43
- return null;
44
- }
45
-
46
- export async function openGlimpseWindow(
47
- html: string,
48
- options: {
49
- title: string;
50
- width?: number;
51
- height?: number;
52
- onClosed: () => void;
53
- },
54
- ) {
55
- const modulePath = resolvedBinaryPath
56
- ? join(dirname(resolvedBinaryPath), "glimpse.mjs")
57
- : "glimpseui";
58
- const glimpse = await import(modulePath);
59
-
60
- let active = true;
61
- const win = glimpse.open(html, {
62
- width: options.width ?? 900,
63
- height: options.height ?? 700,
64
- title: options.title,
65
- });
66
-
67
- win.on("closed", () => {
68
- if (!active) return;
69
- active = false;
70
- options.onClosed();
71
- });
72
-
73
- return {
74
- close: () => {
75
- if (!active) return;
76
- active = false;
77
- win.close();
78
- },
79
- };
80
- }