pi-soly 1.9.3 → 1.11.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 (104) hide show
  1. package/ask/index.ts +12 -11
  2. package/ask/picker.ts +356 -76
  3. package/ask/prompt.ts +6 -2
  4. package/ask/tests/picker.test.ts +273 -82
  5. package/codemap.ts +276 -0
  6. package/hotreload.ts +239 -0
  7. package/init.ts +302 -0
  8. package/mcp/CHANGELOG.md +384 -0
  9. package/mcp/LICENSE +21 -0
  10. package/mcp/OAUTH.md +355 -0
  11. package/mcp/README.md +410 -0
  12. package/mcp/__tests__/agent-dir-paths.upstream-test.ts +80 -0
  13. package/mcp/__tests__/cli.upstream-test.ts +97 -0
  14. package/mcp/__tests__/commands-onboarding.upstream-test.ts +157 -0
  15. package/mcp/__tests__/config.upstream-test.ts +303 -0
  16. package/mcp/__tests__/consent-manager.upstream-test.ts +151 -0
  17. package/mcp/__tests__/direct-tools-auto-auth.upstream-test.ts +218 -0
  18. package/mcp/__tests__/direct-tools.upstream-test.ts +299 -0
  19. package/mcp/__tests__/elicitation-handler.upstream-test.ts +346 -0
  20. package/mcp/__tests__/elicitation-sdk-integration.upstream-test.ts +140 -0
  21. package/mcp/__tests__/errors.upstream-test.ts +218 -0
  22. package/mcp/__tests__/fixtures/elicitation-server.mjs +98 -0
  23. package/mcp/__tests__/host-html-template.upstream-test.ts +278 -0
  24. package/mcp/__tests__/index-lifecycle.upstream-test.ts +484 -0
  25. package/mcp/__tests__/init-elicitation.upstream-test.ts +86 -0
  26. package/mcp/__tests__/interactive-visualizer-server.upstream-test.ts +28 -0
  27. package/mcp/__tests__/logger.upstream-test.ts +175 -0
  28. package/mcp/__tests__/mcp-auth-flow-client-credentials.upstream-test.ts +612 -0
  29. package/mcp/__tests__/mcp-auth-storage.upstream-test.ts +47 -0
  30. package/mcp/__tests__/mcp-callback-server-unref.upstream-test.ts +264 -0
  31. package/mcp/__tests__/mcp-oauth-provider.upstream-test.ts +216 -0
  32. package/mcp/__tests__/mcp-panel-auth.upstream-test.ts +206 -0
  33. package/mcp/__tests__/mcp-panel-exclude-tools.upstream-test.ts +69 -0
  34. package/mcp/__tests__/mcp-panel-keybindings.upstream-test.ts +186 -0
  35. package/mcp/__tests__/npx-resolver.upstream-test.ts +54 -0
  36. package/mcp/__tests__/oauth-handler.upstream-test.ts +77 -0
  37. package/mcp/__tests__/onboarding-state.upstream-test.ts +52 -0
  38. package/mcp/__tests__/package-manifest.upstream-test.ts +22 -0
  39. package/mcp/__tests__/proxy-modes-auto-auth.upstream-test.ts +253 -0
  40. package/mcp/__tests__/proxy-modes-discovery.upstream-test.ts +84 -0
  41. package/mcp/__tests__/proxy-modes-manual-auth.upstream-test.ts +91 -0
  42. package/mcp/__tests__/proxy-modes-ui-messages.upstream-test.ts +72 -0
  43. package/mcp/__tests__/sampling-handler.upstream-test.ts +285 -0
  44. package/mcp/__tests__/server-manager-http-auth.upstream-test.ts +144 -0
  45. package/mcp/__tests__/server-manager-sampling.upstream-test.ts +236 -0
  46. package/mcp/__tests__/tool-metadata.upstream-test.ts +111 -0
  47. package/mcp/__tests__/tool-result-renderer.upstream-test.ts +147 -0
  48. package/mcp/__tests__/ui-integration.upstream-test.ts +551 -0
  49. package/mcp/__tests__/ui-resource-handler.upstream-test.ts +303 -0
  50. package/mcp/__tests__/ui-server.upstream-test.ts +967 -0
  51. package/mcp/__tests__/ui-session-messages.upstream-test.ts +72 -0
  52. package/mcp/__tests__/ui-streaming.upstream-test.ts +543 -0
  53. package/mcp/agent-dir.ts +20 -0
  54. package/mcp/app-bridge.bundle.js +67 -0
  55. package/mcp/cli.js +184 -0
  56. package/mcp/commands.ts +422 -0
  57. package/mcp/config.ts +666 -0
  58. package/mcp/consent-manager.ts +64 -0
  59. package/mcp/direct-tools.ts +439 -0
  60. package/mcp/elicitation-handler.ts +347 -0
  61. package/mcp/errors.ts +219 -0
  62. package/mcp/glimpse-ui.ts +80 -0
  63. package/mcp/host-html-template.ts +427 -0
  64. package/mcp/index.ts +362 -0
  65. package/mcp/init.ts +362 -0
  66. package/mcp/lifecycle.ts +93 -0
  67. package/mcp/logger.ts +169 -0
  68. package/mcp/mcp-auth-flow.ts +559 -0
  69. package/mcp/mcp-auth-flow.upstream-test.ts +259 -0
  70. package/mcp/mcp-auth.ts +302 -0
  71. package/mcp/mcp-auth.upstream-test.ts +373 -0
  72. package/mcp/mcp-callback-server.ts +372 -0
  73. package/mcp/mcp-callback-server.upstream-test.ts +416 -0
  74. package/mcp/mcp-oauth-provider.ts +369 -0
  75. package/mcp/mcp-oauth-provider.upstream-test.ts +518 -0
  76. package/mcp/mcp-panel.ts +829 -0
  77. package/mcp/mcp-setup-panel.ts +580 -0
  78. package/mcp/metadata-cache.ts +201 -0
  79. package/mcp/notify.ts +111 -0
  80. package/mcp/npx-resolver.ts +424 -0
  81. package/mcp/oauth-handler.ts +57 -0
  82. package/mcp/onboarding-state.ts +68 -0
  83. package/mcp/package.json +106 -0
  84. package/mcp/panel-keys.ts +37 -0
  85. package/mcp/proxy-modes.ts +949 -0
  86. package/mcp/resource-tools.ts +17 -0
  87. package/mcp/sampling-handler.ts +268 -0
  88. package/mcp/server-manager.ts +545 -0
  89. package/mcp/state.ts +41 -0
  90. package/mcp/tool-metadata.ts +216 -0
  91. package/mcp/tool-registrar.ts +46 -0
  92. package/mcp/tool-result-renderer.ts +161 -0
  93. package/mcp/types.ts +448 -0
  94. package/mcp/ui-resource-handler.ts +146 -0
  95. package/mcp/ui-server.ts +623 -0
  96. package/mcp/ui-session.ts +386 -0
  97. package/mcp/ui-stream-types.ts +89 -0
  98. package/mcp/utils.ts +129 -0
  99. package/mcp/vitest.config.ts +14 -0
  100. package/migrate.ts +258 -0
  101. package/notification.ts +218 -0
  102. package/notifications-log.ts +83 -0
  103. package/package.json +20 -3
  104. package/status.ts +140 -0
@@ -0,0 +1,347 @@
1
+ import type { ExtensionUIContext } from "@earendil-works/pi-coding-agent";
2
+ import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
3
+ import {
4
+ ElicitRequestSchema,
5
+ ErrorCode,
6
+ McpError,
7
+ type ElicitRequest,
8
+ type ElicitRequestFormParams,
9
+ type ElicitRequestURLParams,
10
+ type ElicitResult,
11
+ } from "@modelcontextprotocol/sdk/types.js";
12
+ import { AjvJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/ajv";
13
+ import type { JsonSchemaType } from "@modelcontextprotocol/sdk/validation/types.js";
14
+ import open from "open";
15
+
16
+ export type ElicitationValue = string | number | boolean | string[] | undefined;
17
+ type FormProperty = ElicitRequestFormParams["requestedSchema"]["properties"][string];
18
+
19
+ export type ElicitationUIContext = ExtensionUIContext;
20
+
21
+ export interface ElicitationHandlerOptions {
22
+ serverName: string;
23
+ ui: ElicitationUIContext;
24
+ allowUrl: boolean;
25
+ onUrlAccepted?: (elicitationId: string) => void;
26
+ }
27
+
28
+ export type ServerElicitationConfig = Omit<ElicitationHandlerOptions, "serverName" | "onUrlAccepted">;
29
+
30
+ export function registerElicitationHandler(client: Client, options: ElicitationHandlerOptions): void {
31
+ client.setRequestHandler(ElicitRequestSchema, (request) =>
32
+ handleElicitationRequest(options, request));
33
+ }
34
+
35
+ export async function handleElicitationRequest(
36
+ options: ElicitationHandlerOptions,
37
+ request: ElicitRequest,
38
+ ): Promise<ElicitResult> {
39
+ return request.params.mode === "url"
40
+ ? handleUrlElicitation(options, request.params)
41
+ : handleFormElicitation(options, request.params);
42
+ }
43
+
44
+ export async function handleFormElicitation(
45
+ options: ElicitationHandlerOptions,
46
+ params: ElicitRequestFormParams,
47
+ ): Promise<ElicitResult> {
48
+ const decision = await options.ui.select(
49
+ `MCP Input Request\nServer: ${options.serverName}\n\n${params.message}`,
50
+ ["Continue", "Decline"],
51
+ );
52
+ if (decision === undefined) return { action: "cancel" };
53
+ if (decision === "Decline") return { action: "decline" };
54
+
55
+ const values: Record<string, ElicitationValue> = {};
56
+ const properties = Object.entries(params.requestedSchema.properties);
57
+ for (const [name, schema] of properties) {
58
+ const value = await collectValidField(options.ui, params, name, schema);
59
+ if (!("value" in value)) return { action: "cancel" };
60
+ values[name] = value.value;
61
+ }
62
+
63
+ while (true) {
64
+ const content = coerceAndValidateFormValues(params, values);
65
+ const action = await options.ui.select(
66
+ formatReview(options.serverName, properties, content),
67
+ properties.length > 0 ? ["Submit", "Edit", "Decline"] : ["Submit", "Decline"],
68
+ );
69
+ if (action === undefined) return { action: "cancel" };
70
+ if (action === "Decline") return { action: "decline" };
71
+ if (action === "Submit") return { action: "accept", content };
72
+
73
+ const labels = properties.map(([name, schema]) => `${schema.title ?? humanizeName(name)} (${name})`);
74
+ const selected = await options.ui.select("Choose a field to edit", labels);
75
+ if (selected === undefined) return { action: "cancel" };
76
+ const property = properties[labels.indexOf(selected)];
77
+ if (!property) continue;
78
+ const [name, schema] = property;
79
+ const value = await collectValidField(options.ui, params, name, schema, values[name]);
80
+ if (!("value" in value)) return { action: "cancel" };
81
+ values[name] = value.value;
82
+ }
83
+ }
84
+
85
+ async function collectValidField(
86
+ ui: ElicitationUIContext,
87
+ params: ElicitRequestFormParams,
88
+ name: string,
89
+ schema: FormProperty,
90
+ current?: ElicitationValue,
91
+ ): Promise<{ cancelled: true } | { cancelled: false; value: ElicitationValue }> {
92
+ const required = params.requestedSchema.required?.includes(name) === true;
93
+ while (true) {
94
+ const result = await collectField(ui, params, name, schema, current);
95
+ if (!("value" in result)) return result;
96
+ try {
97
+ coerceAndValidateFormValues({
98
+ ...params,
99
+ requestedSchema: {
100
+ type: "object",
101
+ properties: { [name]: schema },
102
+ ...(required ? { required: [name] } : {}),
103
+ },
104
+ }, { [name]: result.value });
105
+ return result;
106
+ } catch (error) {
107
+ ui.notify(error instanceof Error ? error.message : String(error), "error");
108
+ current = result.value;
109
+ }
110
+ }
111
+ }
112
+
113
+ async function collectField(
114
+ ui: ElicitationUIContext,
115
+ params: ElicitRequestFormParams,
116
+ name: string,
117
+ schema: FormProperty,
118
+ current?: ElicitationValue,
119
+ ): Promise<{ cancelled: true } | { cancelled: false; value: ElicitationValue }> {
120
+ const required = params.requestedSchema.required?.includes(name) === true;
121
+ const title = [schema.title ?? humanizeName(name), required ? "(required)" : "", schema.description]
122
+ .filter(Boolean)
123
+ .join(" ");
124
+
125
+ if (schema.type === "string" && ("enum" in schema || "oneOf" in schema)) {
126
+ const choices = "oneOf" in schema
127
+ ? schema.oneOf.map(option => ({ value: option.const, display: formatChoice(option.const, option.title) }))
128
+ : schema.enum.map((value, index) => ({
129
+ value,
130
+ display: formatChoice(value, "enumNames" in schema ? schema.enumNames?.[index] : undefined),
131
+ }));
132
+ const displays = uniqueLabels(choices.map(choice => choice.display));
133
+ const actions = [...displays];
134
+ const useDefault = schema.default === undefined ? undefined : uniqueAction("Use default", actions);
135
+ if (useDefault) actions.push(useDefault);
136
+ const omit = required ? undefined : uniqueAction("Omit", actions);
137
+ if (omit) actions.push(omit);
138
+ const action = await ui.select(title, actions);
139
+ if (action === undefined) return { cancelled: true };
140
+ if (action === useDefault) return { cancelled: false, value: schema.default };
141
+ if (action === omit) return { cancelled: false, value: undefined };
142
+ return { cancelled: false, value: choices[displays.indexOf(action)]?.value };
143
+ }
144
+
145
+ if (schema.type === "boolean") {
146
+ const actions = ["Yes", "No"];
147
+ if (schema.default !== undefined) actions.push("Use default");
148
+ if (!required) actions.push("Omit");
149
+ const action = await ui.select(title, actions);
150
+ if (action === undefined) return { cancelled: true };
151
+ if (action === "Use default") return { cancelled: false, value: schema.default };
152
+ if (action === "Omit") return { cancelled: false, value: undefined };
153
+ return { cancelled: false, value: action === "Yes" };
154
+ }
155
+
156
+ if (schema.type === "array") {
157
+ const actions = ["Choose values"];
158
+ if (schema.default !== undefined) actions.push("Use default");
159
+ if (!required) actions.push("Omit");
160
+ const action = await ui.select(title, actions);
161
+ if (action === undefined) return { cancelled: true };
162
+ if (action === "Use default") return { cancelled: false, value: schema.default };
163
+ if (action === "Omit") return { cancelled: false, value: undefined };
164
+
165
+ const choices = extractMultiSelectOptions(schema);
166
+ const selected = new Set(Array.isArray(current) ? current : []);
167
+ while (true) {
168
+ const displays = uniqueLabels(choices.map(choice => selected.has(choice.value) ? `✓ ${choice.display}` : choice.display));
169
+ const done = uniqueAction("Done", displays);
170
+ const picked = await ui.select(title, [...displays, done]);
171
+ if (picked === undefined) return { cancelled: true };
172
+ if (picked === done) return { cancelled: false, value: [...selected] };
173
+ const choice = choices[displays.indexOf(picked)];
174
+ if (!choice) continue;
175
+ if (selected.has(choice.value)) selected.delete(choice.value);
176
+ else selected.add(choice.value);
177
+ }
178
+ }
179
+
180
+ const actions = ["Enter value"];
181
+ if (schema.default !== undefined) actions.push("Use default");
182
+ if (!required) actions.push("Omit");
183
+ const action = await ui.select(title, actions);
184
+ if (action === undefined) return { cancelled: true };
185
+ if (action === "Use default") return { cancelled: false, value: schema.default };
186
+ if (action === "Omit") return { cancelled: false, value: undefined };
187
+ const entered = await ui.input(title, current === undefined ? undefined : String(current));
188
+ return entered === undefined ? { cancelled: true } : { cancelled: false, value: entered };
189
+ }
190
+
191
+ export function coerceAndValidateFormValues(
192
+ params: ElicitRequestFormParams,
193
+ values: Record<string, ElicitationValue>,
194
+ ): Record<string, string | number | boolean | string[]> {
195
+ const output: Record<string, string | number | boolean | string[]> = {};
196
+ const required = new Set(params.requestedSchema.required ?? []);
197
+ for (const [name, schema] of Object.entries(params.requestedSchema.properties)) {
198
+ const value = values[name];
199
+ if (value === undefined) {
200
+ if (required.has(name)) throw new Error(`Missing required elicitation field: ${name}`);
201
+ continue;
202
+ }
203
+ if (schema.type === "string") {
204
+ const stringValue = String(value);
205
+ const limits = schema as typeof schema & { minLength?: number; maxLength?: number };
206
+ if (limits.minLength !== undefined && stringValue.length < limits.minLength) {
207
+ throw new Error(`Elicitation field ${name} is shorter than minimum length ${limits.minLength}`);
208
+ }
209
+ if (limits.maxLength !== undefined && stringValue.length > limits.maxLength) {
210
+ throw new Error(`Elicitation field ${name} is longer than maximum length ${limits.maxLength}`);
211
+ }
212
+ if ("enum" in schema && !schema.enum.includes(stringValue)) {
213
+ throw new Error(`Elicitation field ${name} is not an allowed value`);
214
+ }
215
+ if ("oneOf" in schema && !schema.oneOf.some(option => option.const === stringValue)) {
216
+ throw new Error(`Elicitation field ${name} is not an allowed value`);
217
+ }
218
+ output[name] = stringValue;
219
+ continue;
220
+ }
221
+ if (schema.type === "number" || schema.type === "integer") {
222
+ if (typeof value === "string" && value.trim() === "") {
223
+ throw new Error(`Elicitation field ${name} must be a number`);
224
+ }
225
+ const numberValue = typeof value === "number" ? value : Number(value);
226
+ if (!Number.isFinite(numberValue)) throw new Error(`Elicitation field ${name} must be a number`);
227
+ if (schema.type === "integer" && !Number.isInteger(numberValue)) {
228
+ throw new Error(`Elicitation field ${name} must be an integer`);
229
+ }
230
+ if (schema.minimum !== undefined && numberValue < schema.minimum) {
231
+ throw new Error(`Elicitation field ${name} is below minimum ${schema.minimum}`);
232
+ }
233
+ if (schema.maximum !== undefined && numberValue > schema.maximum) {
234
+ throw new Error(`Elicitation field ${name} is above maximum ${schema.maximum}`);
235
+ }
236
+ output[name] = numberValue;
237
+ continue;
238
+ }
239
+ if (schema.type === "boolean") {
240
+ output[name] = typeof value === "boolean" ? value : value === "true";
241
+ continue;
242
+ }
243
+ if (schema.type === "array") {
244
+ if (!Array.isArray(value)) throw new Error(`Elicitation field ${name} must be a list`);
245
+ const allowed = new Set(extractMultiSelectOptions(schema).map(option => option.value));
246
+ const arrayValue = value.map(String);
247
+ if (schema.minItems !== undefined && arrayValue.length < schema.minItems) {
248
+ throw new Error(`Elicitation field ${name} has fewer than ${schema.minItems} selections`);
249
+ }
250
+ if (schema.maxItems !== undefined && arrayValue.length > schema.maxItems) {
251
+ throw new Error(`Elicitation field ${name} has more than ${schema.maxItems} selections`);
252
+ }
253
+ if (arrayValue.some(item => !allowed.has(item))) {
254
+ throw new Error(`Elicitation field ${name} contains an invalid selection`);
255
+ }
256
+ output[name] = arrayValue;
257
+ }
258
+ }
259
+ const validation = new AjvJsonSchemaValidator()
260
+ .getValidator(params.requestedSchema as JsonSchemaType)(output);
261
+ if (!validation.valid) {
262
+ throw new Error(`Invalid elicitation response: ${validation.errorMessage}`);
263
+ }
264
+ return output;
265
+ }
266
+
267
+ function formatChoice(value: string, title?: string): string {
268
+ return title && title !== value ? `${title} (${value})` : value;
269
+ }
270
+
271
+ function uniqueLabels(labels: string[]): string[] {
272
+ const used = new Set<string>();
273
+ return labels.map(label => {
274
+ let unique = label;
275
+ while (used.has(unique)) unique += "…";
276
+ used.add(unique);
277
+ return unique;
278
+ });
279
+ }
280
+
281
+ function uniqueAction(label: string, choices: string[]): string {
282
+ let unique = label;
283
+ while (choices.includes(unique)) unique += "…";
284
+ return unique;
285
+ }
286
+
287
+ function extractMultiSelectOptions(schema: Extract<FormProperty, { type: "array" }>): Array<{ value: string; display: string }> {
288
+ const items = schema.items as { enum?: string[]; anyOf?: Array<{ const: string; title: string }> };
289
+ return items.anyOf
290
+ ? items.anyOf.map(option => ({ value: option.const, display: formatChoice(option.const, option.title) }))
291
+ : (items.enum ?? []).map(value => ({ value, display: value }));
292
+ }
293
+
294
+ function formatReview(
295
+ serverName: string,
296
+ properties: Array<[string, FormProperty]>,
297
+ content: Record<string, string | number | boolean | string[]>,
298
+ ): string {
299
+ const rows = properties.map(([name, schema]) =>
300
+ `${schema.title ?? humanizeName(name)}: ${content[name] === undefined ? "(omitted)" : String(content[name])}`);
301
+ return [`Review input for ${serverName}`, "", ...rows].join("\n");
302
+ }
303
+
304
+ export async function handleUrlElicitation(
305
+ options: ElicitationHandlerOptions,
306
+ params: ElicitRequestURLParams,
307
+ ): Promise<ElicitResult> {
308
+ if (!options.allowUrl) throw new McpError(ErrorCode.InvalidParams, "URL elicitation is not supported");
309
+
310
+ let parsed: URL;
311
+ try {
312
+ parsed = new URL(params.url);
313
+ } catch {
314
+ throw new McpError(ErrorCode.InvalidParams, "URL elicitation supplied an invalid URL");
315
+ }
316
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
317
+ throw new McpError(ErrorCode.InvalidParams, "URL elicitation only supports HTTP and HTTPS URLs");
318
+ }
319
+
320
+ const decision = await options.ui.select([
321
+ "MCP Browser Request",
322
+ `Server: ${options.serverName}`,
323
+ "",
324
+ params.message,
325
+ "",
326
+ `Host: ${parsed.host}`,
327
+ `Full URL: ${params.url}`,
328
+ "",
329
+ "Open this URL in your browser?",
330
+ ].join("\n"), ["Open", "Decline"]);
331
+ if (decision === undefined) return { action: "cancel" };
332
+ if (decision === "Decline") return { action: "decline" };
333
+
334
+ try {
335
+ await open(params.url);
336
+ } catch (error) {
337
+ options.ui.notify(`Could not open MCP elicitation URL: ${error instanceof Error ? error.message : String(error)}`, "error");
338
+ return { action: "cancel" };
339
+ }
340
+ options.onUrlAccepted?.(params.elicitationId);
341
+ options.ui.notify("Opened browser for MCP elicitation.", "info");
342
+ return { action: "accept" };
343
+ }
344
+
345
+ function humanizeName(name: string): string {
346
+ return name.replace(/[_-]+/g, " ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/^./, char => char.toUpperCase());
347
+ }
package/mcp/errors.ts ADDED
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Custom error types for MCP UI operations.
3
+ * Provides structured errors with context and recovery hints.
4
+ */
5
+
6
+ export interface McpUiErrorContext {
7
+ server?: string;
8
+ tool?: string;
9
+ uri?: string;
10
+ session?: string;
11
+ [key: string]: unknown;
12
+ }
13
+
14
+ /**
15
+ * Base error class for MCP UI errors.
16
+ */
17
+ export class McpUiError extends Error {
18
+ readonly code: string;
19
+ readonly context: McpUiErrorContext;
20
+ readonly recoveryHint?: string;
21
+ readonly cause?: Error;
22
+
23
+ constructor(
24
+ message: string,
25
+ options: {
26
+ code: string;
27
+ context?: McpUiErrorContext;
28
+ recoveryHint?: string;
29
+ cause?: Error;
30
+ }
31
+ ) {
32
+ super(message);
33
+ this.name = "McpUiError";
34
+ this.code = options.code;
35
+ this.context = options.context ?? {};
36
+ this.recoveryHint = options.recoveryHint;
37
+ this.cause = options.cause;
38
+
39
+ // Maintain proper stack trace
40
+ if (Error.captureStackTrace) {
41
+ Error.captureStackTrace(this, this.constructor);
42
+ }
43
+ }
44
+
45
+ toJSON(): Record<string, unknown> {
46
+ return {
47
+ name: this.name,
48
+ code: this.code,
49
+ message: this.message,
50
+ context: this.context,
51
+ recoveryHint: this.recoveryHint,
52
+ stack: this.stack,
53
+ };
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Error fetching a UI resource from the MCP server.
59
+ */
60
+ export class ResourceFetchError extends McpUiError {
61
+ constructor(
62
+ uri: string,
63
+ reason: string,
64
+ options?: { server?: string; cause?: Error }
65
+ ) {
66
+ super(`Failed to fetch UI resource "${uri}": ${reason}`, {
67
+ code: "RESOURCE_FETCH_ERROR",
68
+ context: { uri, server: options?.server },
69
+ recoveryHint: "Check that the MCP server is connected and the resource URI is valid.",
70
+ cause: options?.cause,
71
+ });
72
+ this.name = "ResourceFetchError";
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Error parsing or validating UI resource content.
78
+ */
79
+ export class ResourceParseError extends McpUiError {
80
+ constructor(
81
+ uri: string,
82
+ reason: string,
83
+ options?: { server?: string; mimeType?: string }
84
+ ) {
85
+ super(`Invalid UI resource "${uri}": ${reason}`, {
86
+ code: "RESOURCE_PARSE_ERROR",
87
+ context: { uri, server: options?.server, mimeType: options?.mimeType },
88
+ recoveryHint: "Ensure the resource returns valid HTML with the correct MIME type.",
89
+ });
90
+ this.name = "ResourceParseError";
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Error connecting to the AppBridge.
96
+ */
97
+ export class BridgeConnectionError extends McpUiError {
98
+ constructor(reason: string, options?: { session?: string; cause?: Error }) {
99
+ super(`AppBridge connection failed: ${reason}`, {
100
+ code: "BRIDGE_CONNECTION_ERROR",
101
+ context: { session: options?.session },
102
+ recoveryHint: "Check browser console for detailed errors. The iframe may have failed to load.",
103
+ cause: options?.cause,
104
+ });
105
+ this.name = "BridgeConnectionError";
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Error related to user consent for tool calls.
111
+ */
112
+ export class ConsentError extends McpUiError {
113
+ readonly denied: boolean;
114
+
115
+ constructor(
116
+ server: string,
117
+ options: { denied?: boolean; requiresApproval?: boolean }
118
+ ) {
119
+ const message = options.denied
120
+ ? `Tool calls for "${server}" were denied for this session`
121
+ : `Tool call approval required for "${server}"`;
122
+
123
+ super(message, {
124
+ code: options.denied ? "CONSENT_DENIED" : "CONSENT_REQUIRED",
125
+ context: { server },
126
+ recoveryHint: options.denied
127
+ ? "The user denied tool access. Start a new session to try again."
128
+ : "Prompt the user for consent before calling tools.",
129
+ });
130
+ this.name = "ConsentError";
131
+ this.denied = options.denied ?? false;
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Error with UI server session management.
137
+ */
138
+ export class SessionError extends McpUiError {
139
+ constructor(
140
+ reason: string,
141
+ options?: { session?: string; cause?: Error }
142
+ ) {
143
+ super(`Session error: ${reason}`, {
144
+ code: "SESSION_ERROR",
145
+ context: { session: options?.session },
146
+ recoveryHint: "The session may have expired or been closed. Try opening the UI again.",
147
+ cause: options?.cause,
148
+ });
149
+ this.name = "SessionError";
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Error starting or operating the UI server.
155
+ */
156
+ export class ServerError extends McpUiError {
157
+ constructor(
158
+ reason: string,
159
+ options?: { port?: number; cause?: Error }
160
+ ) {
161
+ super(`UI server error: ${reason}`, {
162
+ code: "SERVER_ERROR",
163
+ context: { port: options?.port },
164
+ recoveryHint: "Check if the port is available. Another process may be using it.",
165
+ cause: options?.cause,
166
+ });
167
+ this.name = "ServerError";
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Error communicating with the MCP server.
173
+ */
174
+ export class McpServerError extends McpUiError {
175
+ constructor(
176
+ server: string,
177
+ reason: string,
178
+ options?: { tool?: string; cause?: Error }
179
+ ) {
180
+ super(`MCP server "${server}" error: ${reason}`, {
181
+ code: "MCP_SERVER_ERROR",
182
+ context: { server, tool: options?.tool },
183
+ recoveryHint: "Check that the MCP server is running and responsive.",
184
+ cause: options?.cause,
185
+ });
186
+ this.name = "McpServerError";
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Wrap an unknown error into an McpUiError.
192
+ */
193
+ export function wrapError(error: unknown, context?: McpUiErrorContext): McpUiError {
194
+ if (error instanceof McpUiError) {
195
+ // Merge contexts
196
+ return new McpUiError(error.message, {
197
+ code: error.code,
198
+ context: { ...error.context, ...context },
199
+ recoveryHint: error.recoveryHint,
200
+ cause: error.cause,
201
+ });
202
+ }
203
+
204
+ const cause = error instanceof Error ? error : undefined;
205
+ const message = error instanceof Error ? error.message : String(error);
206
+
207
+ return new McpUiError(message, {
208
+ code: "UNKNOWN_ERROR",
209
+ context,
210
+ cause,
211
+ });
212
+ }
213
+
214
+ /**
215
+ * Check if an error is a specific MCP UI error type.
216
+ */
217
+ export function isErrorCode(error: unknown, code: string): boolean {
218
+ return error instanceof McpUiError && error.code === code;
219
+ }
@@ -0,0 +1,80 @@
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
+ }