@fitchmultz/pi-mcp-adapter 5.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 (129) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/OAUTH.md +3 -3
  3. package/README.md +160 -88
  4. package/dist/app-bridge.bundle.js +75 -33
  5. package/dist/commands.js +9 -6
  6. package/dist/config.js +41 -16
  7. package/dist/direct-tools.d.ts +2 -4
  8. package/dist/direct-tools.js +21 -319
  9. package/dist/gateway-arguments.d.ts +33 -0
  10. package/dist/gateway-arguments.js +63 -0
  11. package/dist/index.js +181 -276
  12. package/dist/init.js +6 -20
  13. package/dist/lifecycle.d.ts +2 -2
  14. package/dist/lifecycle.js +2 -2
  15. package/dist/mcp-auth-flow.js +2 -2
  16. package/dist/mcp-auth.d.ts +1 -1
  17. package/dist/mcp-auth.js +3 -3
  18. package/dist/mcp-code.d.ts +7 -6
  19. package/dist/mcp-code.js +98 -51
  20. package/dist/mcp-oauth-provider.d.ts +5 -5
  21. package/dist/mcp-oauth-provider.js +5 -5
  22. package/dist/mcp-output-guard.d.ts +57 -2
  23. package/dist/mcp-output-guard.js +129 -24
  24. package/dist/mcp-panel.d.ts +3 -3
  25. package/dist/mcp-panel.js +36 -99
  26. package/dist/mcp-script-worker.mjs +5 -2
  27. package/dist/mcp-setup-panel.d.ts +5 -4
  28. package/dist/mcp-setup-panel.js +15 -7
  29. package/dist/mcp-status.js +2 -1
  30. package/dist/mcp-trace.d.ts +1 -1
  31. package/dist/mcp-trace.js +1 -1
  32. package/dist/metadata-cache.d.ts +1 -1
  33. package/dist/metadata-cache.js +25 -88
  34. package/dist/npx-resolver.js +8 -4
  35. package/dist/prompts.d.ts +1 -1
  36. package/dist/prompts.js +1 -1
  37. package/dist/proxy-modes.d.ts +41 -7
  38. package/dist/proxy-modes.js +275 -490
  39. package/dist/resource-tools.d.ts +15 -0
  40. package/dist/resource-tools.js +26 -1
  41. package/dist/sampling-handler.js +5 -1
  42. package/dist/search-ranking.d.ts +0 -2
  43. package/dist/search-ranking.js +70 -137
  44. package/dist/server-manager.d.ts +2 -2
  45. package/dist/server-manager.js +44 -27
  46. package/dist/session-recovery.d.ts +7 -4
  47. package/dist/session-recovery.js +76 -10
  48. package/dist/state.d.ts +1 -1
  49. package/dist/tool-loader.d.ts +32 -0
  50. package/dist/tool-loader.js +152 -0
  51. package/dist/tool-metadata.d.ts +67 -0
  52. package/dist/tool-metadata.js +23 -17
  53. package/dist/tool-registrar.d.ts +4 -4
  54. package/dist/tool-registrar.js +18 -13
  55. package/dist/tool-result-renderer.d.ts +6 -3
  56. package/dist/tool-result-renderer.js +11 -6
  57. package/dist/types.d.ts +11 -36
  58. package/dist/ui-resource-handler.d.ts +2 -2
  59. package/dist/ui-resource-handler.js +2 -2
  60. package/dist/ui-server.js +4 -3
  61. package/dist/ui-stream-types.d.ts +8 -8
  62. package/dist/unix-socket-transport.d.ts +1 -1
  63. package/dist/unix-socket-transport.js +1 -1
  64. package/dist/utils.d.ts +1 -0
  65. package/dist/utils.js +16 -4
  66. package/package.json +37 -96
  67. package/skills/mcp-scripting/SKILL.md +67 -20
  68. package/abort.ts +0 -34
  69. package/agent-dir.ts +0 -24
  70. package/app-bridge.bundle.js +0 -67
  71. package/banner.png +0 -0
  72. package/checkpoint.ts +0 -55
  73. package/commands.ts +0 -619
  74. package/config.ts +0 -1204
  75. package/consent-manager.ts +0 -25
  76. package/direct-tools.ts +0 -408
  77. package/dist/ts-shape.d.ts +0 -2
  78. package/dist/ts-shape.js +0 -147
  79. package/elicitation-handler.ts +0 -349
  80. package/error-signal.ts +0 -21
  81. package/glimpse-ui.ts +0 -80
  82. package/host-html-template.ts +0 -456
  83. package/index.ts +0 -900
  84. package/init.ts +0 -627
  85. package/legacy-migration.ts +0 -47
  86. package/lifecycle.ts +0 -165
  87. package/logger.ts +0 -127
  88. package/mcp-auth-flow.ts +0 -975
  89. package/mcp-auth.ts +0 -793
  90. package/mcp-callback-server.ts +0 -450
  91. package/mcp-code.ts +0 -386
  92. package/mcp-keyring-helper.cjs +0 -89
  93. package/mcp-oauth-provider.ts +0 -774
  94. package/mcp-output-guard.ts +0 -412
  95. package/mcp-panel.ts +0 -978
  96. package/mcp-script-worker.mjs +0 -128
  97. package/mcp-setup-panel.ts +0 -666
  98. package/mcp-status.ts +0 -109
  99. package/mcp-trace.ts +0 -295
  100. package/metadata-cache.ts +0 -333
  101. package/npx-resolver.ts +0 -488
  102. package/onboarding-state.ts +0 -58
  103. package/panel-keys.ts +0 -37
  104. package/prompts.ts +0 -337
  105. package/proxy-modes.ts +0 -1361
  106. package/resource-tools.ts +0 -17
  107. package/runtime-owner.ts +0 -123
  108. package/sampling-handler.ts +0 -273
  109. package/scripts/build.mjs +0 -131
  110. package/scripts/prepare.mjs +0 -102
  111. package/search-ranking.ts +0 -196
  112. package/server-manager.ts +0 -1320
  113. package/session-recovery.ts +0 -316
  114. package/state.ts +0 -64
  115. package/tool-approval.ts +0 -78
  116. package/tool-metadata.ts +0 -235
  117. package/tool-registrar.ts +0 -69
  118. package/tool-result-renderer.ts +0 -286
  119. package/ts-shape.ts +0 -145
  120. package/tsconfig.build.json +0 -13
  121. package/tsconfig.json +0 -16
  122. package/types.ts +0 -810
  123. package/ui-resource-handler.ts +0 -249
  124. package/ui-server.ts +0 -808
  125. package/ui-session.ts +0 -568
  126. package/ui-stream-types.ts +0 -89
  127. package/ui-tool-visibility.ts +0 -25
  128. package/unix-socket-transport.ts +0 -85
  129. package/utils.ts +0 -309
package/ui-session.ts DELETED
@@ -1,568 +0,0 @@
1
- import { execFile } from "node:child_process";
2
- import { randomUUID } from "node:crypto";
3
- import net from "node:net";
4
- import { UrlElicitationRequiredError, type CallToolResult } from "@modelcontextprotocol/client";
5
- import type { McpExtensionState } from "./state.ts";
6
- import {
7
- createUiModelContextUpdate,
8
- extractUiPromptText,
9
- UI_STREAM_HOST_CONTEXT_KEY,
10
- UI_STREAM_REQUEST_META_KEY,
11
- UI_STREAM_STRUCTURED_CONTENT_KEY,
12
- type UiHostContext,
13
- type UiMessageParams,
14
- type UiModelContextParams,
15
- type UiStreamMode,
16
- } from "./types.ts";
17
- import { logger } from "./logger.ts";
18
- import { startUiServer, type UiServerHandle } from "./ui-server.ts";
19
- import { isGlimpseAvailable, openGlimpseWindow } from "./glimpse-ui.ts";
20
- import type { SessionRecoveryDeps } from "./session-recovery.ts";
21
- import { combineAbortSignals, isAbortError } from "./runtime-owner.ts";
22
- import { throwIfAborted } from "./abort.ts";
23
-
24
- let activeGlimpseWindow: { close(): void } | null = null;
25
-
26
- export interface UiSessionRequest {
27
- serverName: string;
28
- toolName: string;
29
- toolArgs: Record<string, unknown>;
30
- uiResourceUri: string;
31
- streamMode?: UiStreamMode;
32
- signal?: AbortSignal;
33
- onNeedsAuth?: SessionRecoveryDeps["onNeedsAuth"];
34
- }
35
-
36
- export type UiSessionViewer = "browser" | "glimpse" | "suppressed";
37
-
38
- export interface UiSessionRuntime {
39
- serverName: string;
40
- toolName: string;
41
- reused: boolean;
42
- streamId?: string;
43
- streamToken?: string;
44
- streamMode?: UiStreamMode;
45
- requestMeta?: Record<string, unknown>;
46
- url: string;
47
- viewer: UiSessionViewer;
48
- windowOpen: boolean;
49
- isActive: () => boolean;
50
- sendToolResult: (result: CallToolResult) => void;
51
- sendResultPatch: (result: CallToolResult) => void;
52
- sendToolCancelled: (reason: string) => void;
53
- close: (reason?: string) => void;
54
- }
55
-
56
- export interface UiSessionResultSummary {
57
- message: string;
58
- uiOpen: boolean;
59
- uiViewer?: UiSessionViewer;
60
- uiUrl?: string;
61
- }
62
-
63
- export function summarizeUiSessionResult(uiSession: UiSessionRuntime | null): UiSessionResultSummary {
64
- if (!uiSession) {
65
- return {
66
- message: "Interactive UI was unavailable; returning the tool result inline.",
67
- uiOpen: false,
68
- };
69
- }
70
-
71
- if (!uiSession.windowOpen) {
72
- const action = uiSession.reused ? "Updated the suppressed MCP UI session." : "MCP UI window was suppressed.";
73
- return {
74
- message: `${action} Open manually: ${uiSession.url}`,
75
- uiOpen: false,
76
- uiViewer: uiSession.viewer,
77
- uiUrl: uiSession.url,
78
- };
79
- }
80
-
81
- return {
82
- message: uiSession.reused
83
- ? "Updated the open UI."
84
- : "Interactive UI is open. I'll respond to your prompts and intents as you interact with it.",
85
- uiOpen: true,
86
- uiViewer: uiSession.viewer,
87
- uiUrl: uiSession.url,
88
- };
89
- }
90
-
91
- const MAX_COMPLETED_SESSIONS = 10;
92
-
93
- function withStreamEnvelope(
94
- result: CallToolResult,
95
- streamId: string | undefined,
96
- sequence: number,
97
- ): CallToolResult {
98
- if (!streamId) {
99
- return result;
100
- }
101
-
102
- const structuredContent: Record<string, unknown> = result.structuredContent && typeof result.structuredContent === "object" && !Array.isArray(result.structuredContent)
103
- ? { ...result.structuredContent }
104
- : {};
105
-
106
- const rawEnvelope = structuredContent[UI_STREAM_STRUCTURED_CONTENT_KEY];
107
- const envelope = rawEnvelope && typeof rawEnvelope === "object" && !Array.isArray(rawEnvelope)
108
- ? { ...rawEnvelope as Record<string, unknown> }
109
- : {
110
- frameType: "final",
111
- phase: "settled",
112
- status: result.isError ? "error" : "ok",
113
- };
114
-
115
- structuredContent[UI_STREAM_STRUCTURED_CONTENT_KEY] = {
116
- ...envelope,
117
- streamId,
118
- sequence,
119
- };
120
-
121
- return {
122
- ...result,
123
- structuredContent,
124
- };
125
- }
126
-
127
- async function openInBrowser(state: McpExtensionState, url: string, signal: AbortSignal): Promise<string | null> {
128
- throwIfAborted(signal);
129
- try {
130
- await state.openBrowser(url);
131
- throwIfAborted(signal);
132
- return null;
133
- } catch (error) {
134
- if (isAbortError(error, signal)) throw error;
135
- const message = error instanceof Error ? error.message : String(error);
136
- if (state.owner?.isActive() === false) return null;
137
- state.ui?.notify(`MCP UI browser open failed: ${message}`, "warning");
138
- return message;
139
- }
140
- }
141
-
142
- function isRemoteSession(): boolean {
143
- return Boolean(process.env.SSH_CONNECTION || process.env.SSH_TTY);
144
- }
145
-
146
- function hasActiveRemoteLogin(): Promise<boolean> {
147
- return new Promise((resolve) => {
148
- execFile("who", { encoding: "utf8", timeout: 2000 }, (error, out) => {
149
- if (error) {
150
- resolve(false);
151
- return;
152
- }
153
- resolve(/\(.+\)\s*$/m.test(out));
154
- });
155
- });
156
- }
157
-
158
- function probeMoshiGateway(): Promise<boolean> {
159
- return new Promise((resolve) => {
160
- const socket = net.connect({ host: "127.0.0.1", port: 24543 });
161
- const done = (ok: boolean) => {
162
- socket.destroy();
163
- resolve(ok);
164
- };
165
- socket.setTimeout(300);
166
- socket.once("connect", () => done(true));
167
- socket.once("timeout", () => done(false));
168
- socket.once("error", () => done(false));
169
- });
170
- }
171
-
172
- function remoteAccessHint(opts: { url: string; port: number; moshi: boolean; openError: string | null; openedOnHost?: boolean }): string {
173
- const lines = [
174
- opts.openError !== null
175
- ? "Couldn't open MCP UI here. Open it from your own device:"
176
- : opts.openedOnHost
177
- ? "MCP UI opened on this host. If you're controlling this session remotely, open it from your own device:"
178
- : "This looks like a remote session - if no MCP UI appeared, open it from your own device:",
179
- ` ${opts.url}`,
180
- ];
181
- if (opts.openError !== null) {
182
- lines.push(`Browser launch failed: ${opts.openError}`);
183
- }
184
- if (opts.moshi) {
185
- lines.push("Moshi: tap the preview button in the terminal title bar and pick this MCP UI server.");
186
- }
187
- lines.push(
188
- `SSH: run \`ssh -L ${opts.port}:127.0.0.1:${opts.port} <this-host>\` on your local machine, then open the URL above.`,
189
- "mosh can't forward ports - run that ssh command in a separate terminal.",
190
- );
191
- return lines.join("\n");
192
- }
193
-
194
- export async function maybeStartUiSession(
195
- state: McpExtensionState,
196
- request: UiSessionRequest,
197
- ): Promise<UiSessionRuntime | null> {
198
- const log = logger.child({
199
- component: "UiSession",
200
- server: request.serverName,
201
- tool: request.toolName,
202
- });
203
- const runtimeSignal = combineAbortSignals(state.owner?.signal, request.signal) ?? new AbortController().signal;
204
-
205
- try {
206
- throwIfAborted(runtimeSignal);
207
- if (
208
- state.uiServer &&
209
- state.uiServer.serverName === request.serverName &&
210
- state.uiServer.toolName === request.toolName
211
- ) {
212
- const existingHandle = state.uiServer;
213
- const streamMode = request.streamMode;
214
- const streamId = streamMode ? randomUUID() : undefined;
215
- const streamToken = streamMode ? randomUUID() : undefined;
216
- let active = true;
217
- let nextStreamSequence = 0;
218
-
219
- const cleanupStreamListener = () => {
220
- if (streamToken) {
221
- state.manager.removeUiStreamListener(streamToken);
222
- }
223
- };
224
-
225
- existingHandle.sendToolInput(request.toolArgs);
226
-
227
- if (streamToken) {
228
- state.manager.registerUiStreamListener(streamToken, (serverName, notification) => {
229
- if (!active || state.uiServer !== existingHandle) return;
230
- if (serverName !== request.serverName) return;
231
- nextStreamSequence += 1;
232
- existingHandle.sendResultPatch(
233
- withStreamEnvelope(notification.result as CallToolResult, streamId, nextStreamSequence),
234
- );
235
- });
236
- }
237
-
238
- return {
239
- serverName: request.serverName,
240
- toolName: request.toolName,
241
- reused: true,
242
- ...(streamId !== undefined ? { streamId } : {}),
243
- ...(streamToken !== undefined ? { streamToken } : {}),
244
- ...(streamMode !== undefined ? { streamMode } : {}),
245
- ...(streamToken ? { requestMeta: { [UI_STREAM_REQUEST_META_KEY]: streamToken } } : {}),
246
- url: existingHandle.url,
247
- viewer: existingHandle.viewer ?? "browser",
248
- windowOpen: existingHandle.windowOpen ?? true,
249
- isActive: () => active && state.uiServer === existingHandle,
250
- sendToolResult: (result: CallToolResult) => {
251
- if (!active || state.uiServer !== existingHandle) return;
252
- nextStreamSequence += 1;
253
- existingHandle.sendToolResult(withStreamEnvelope(result, streamId, nextStreamSequence));
254
- },
255
- sendResultPatch: (result: CallToolResult) => {
256
- if (!active || state.uiServer !== existingHandle) return;
257
- nextStreamSequence += 1;
258
- existingHandle.sendResultPatch(withStreamEnvelope(result, streamId, nextStreamSequence));
259
- },
260
- sendToolCancelled: (reason: string) => {
261
- if (!active || state.uiServer !== existingHandle) return;
262
- nextStreamSequence += 1;
263
- existingHandle.sendToolResult(
264
- withStreamEnvelope(
265
- {
266
- isError: true,
267
- content: [{ type: "text", text: reason }],
268
- },
269
- streamId,
270
- nextStreamSequence,
271
- ),
272
- );
273
- },
274
- close: () => {
275
- active = false;
276
- cleanupStreamListener();
277
- },
278
- };
279
- }
280
-
281
- const resource = await state.uiResourceHandler.readUiResource(request.serverName, request.uiResourceUri, {
282
- config: state.config,
283
- signal: runtimeSignal,
284
- onNeedsAuth: request.onNeedsAuth,
285
- });
286
- throwIfAborted(runtimeSignal);
287
-
288
- if (state.uiServer) {
289
- state.uiServer.close("replaced");
290
- state.uiServer = null;
291
- }
292
- if (activeGlimpseWindow) {
293
- activeGlimpseWindow.close();
294
- activeGlimpseWindow = null;
295
- }
296
-
297
- const streamMode = request.streamMode;
298
- const streamId = streamMode ? randomUUID() : undefined;
299
- const streamToken = streamMode ? randomUUID() : undefined;
300
- const hostContext: UiHostContext | undefined = streamMode && streamId
301
- ? {
302
- [UI_STREAM_HOST_CONTEXT_KEY]: {
303
- mode: streamMode,
304
- streamId,
305
- intermediateResultPatches: streamMode === "stream-first",
306
- partialInput: false,
307
- },
308
- }
309
- : undefined;
310
-
311
- let active = true;
312
- let nextStreamSequence = 0;
313
- let handle: UiServerHandle;
314
-
315
- const cleanupStreamListener = () => {
316
- if (streamToken) {
317
- state.manager.removeUiStreamListener(streamToken);
318
- }
319
- };
320
-
321
- handle = await startUiServer({
322
- serverName: request.serverName,
323
- toolName: request.toolName,
324
- toolArgs: streamMode === "stream-first" ? {} : request.toolArgs,
325
- resource,
326
- manager: state.manager,
327
- config: state.config,
328
- state,
329
- ...(request.onNeedsAuth ? { onNeedsAuth: request.onNeedsAuth } : {}),
330
- consentManager: state.consentManager,
331
- ...(hostContext !== undefined ? { hostContext } : {}),
332
-
333
- onMessage: (params: UiMessageParams) => {
334
- const prompt = extractUiPromptText(params);
335
- if (prompt) {
336
- if (state.sendMessage) {
337
- state.sendMessage(
338
- {
339
- customType: "mcp-ui-prompt",
340
- content: [{ type: "text", text: `User sent prompt from ${request.serverName} UI: "${prompt}"` }],
341
- display: `💬 UI Prompt: ${prompt}`,
342
- details: { server: request.serverName, tool: request.toolName, prompt },
343
- },
344
- { triggerTurn: true },
345
- );
346
- log.debug("Triggered agent turn for UI prompt", { prompt: prompt.slice(0, 50) });
347
- }
348
- } else if (params.type === "intent" || params.intent) {
349
- const intent = params.intent ?? "";
350
- const intentParams = params.params;
351
- if (intent && state.sendMessage) {
352
- const paramsStr = intentParams ? ` ${JSON.stringify(intentParams)}` : "";
353
- state.sendMessage(
354
- {
355
- customType: "mcp-ui-intent",
356
- content: [{ type: "text", text: `User triggered intent from ${request.serverName} UI: ${intent}${paramsStr}` }],
357
- display: `🎯 UI Intent: ${intent}`,
358
- details: { server: request.serverName, tool: request.toolName, intent, params: intentParams },
359
- },
360
- { triggerTurn: true },
361
- );
362
- log.debug("Triggered agent turn for UI intent", { intent });
363
- }
364
- } else if (params.type === "notify" || params.message) {
365
- const text = params.message ?? "";
366
- if (text && state.ui) {
367
- state.ui.notify(`[${request.serverName}] ${text}`, "info");
368
- }
369
- }
370
- },
371
-
372
- onContextUpdate: (params: UiModelContextParams) => {
373
- const update = createUiModelContextUpdate(params);
374
- log.debug("Model context update from UI", {
375
- hasContent: !!params.content,
376
- hasStructured: !!params.structuredContent,
377
- hasUpdate: !!update,
378
- });
379
- if (update && state.sendMessage) {
380
- state.sendMessage(
381
- {
382
- customType: "mcp-ui-context",
383
- content: [{ type: "text", text: `User submitted model context from ${request.serverName} UI:\n${update.summary}` }],
384
- display: "UI Context submitted",
385
- details: { server: request.serverName, tool: request.toolName, context: update },
386
- },
387
- { triggerTurn: true },
388
- );
389
- }
390
- },
391
-
392
- onComplete: (reason: string) => {
393
- active = false;
394
- cleanupStreamListener();
395
-
396
- if (state.uiServer === handle) {
397
- const messages = handle.getSessionMessages();
398
- const stream = handle.getStreamSummary();
399
- const hasContent =
400
- messages.prompts.length > 0 ||
401
- messages.intents.length > 0 ||
402
- messages.notifications.length > 0 ||
403
- messages.contexts.length > 0 ||
404
- !!stream;
405
-
406
- if (hasContent) {
407
- state.completedUiSessions.push({
408
- serverName: handle.serverName,
409
- toolName: handle.toolName,
410
- completedAt: new Date(),
411
- reason,
412
- messages,
413
- ...(stream !== undefined ? { stream } : {}),
414
- });
415
-
416
- while (state.completedUiSessions.length > MAX_COMPLETED_SESSIONS) {
417
- state.completedUiSessions.shift();
418
- }
419
-
420
- log.debug("Session completed", {
421
- reason,
422
- prompts: messages.prompts.length,
423
- intents: messages.intents.length,
424
- notifications: messages.notifications.length,
425
- contexts: messages.contexts.length,
426
- streamFrames: stream?.frames ?? 0,
427
- });
428
- }
429
-
430
- state.uiServer = null;
431
- if (activeGlimpseWindow) {
432
- activeGlimpseWindow.close();
433
- activeGlimpseWindow = null;
434
- }
435
- }
436
- },
437
- });
438
-
439
- if (state.owner?.isActive() === false || runtimeSignal.aborted) {
440
- handle.close("runtime_owner_stopped");
441
- throwIfAborted(runtimeSignal);
442
- throw new Error("MCP UI session became stale before registration");
443
- }
444
-
445
- if (streamToken) {
446
- state.manager.registerUiStreamListener(streamToken, (serverName, notification) => {
447
- if (!active || state.uiServer !== handle) return;
448
- if (serverName !== request.serverName) return;
449
- nextStreamSequence += 1;
450
- handle.sendResultPatch(withStreamEnvelope(notification.result as CallToolResult, streamId, nextStreamSequence));
451
- });
452
- }
453
-
454
- state.uiServer = handle;
455
-
456
- const viewerPref = process.env.MCP_UI_VIEWER?.toLowerCase();
457
- const uiSuppressed = viewerPref === "none" || viewerPref === "off" || viewerPref === "disabled";
458
-
459
- let viewer: UiSessionViewer = "browser";
460
- let windowOpen = true;
461
- const remoteByEnv = isRemoteSession();
462
-
463
- if (uiSuppressed) {
464
- viewer = "suppressed";
465
- windowOpen = false;
466
- state.ui?.notify(`MCP UI window suppressed (MCP_UI_VIEWER=${viewerPref}). Open manually: ${handle.url}`, "info");
467
- log.info("Suppressing MCP UI window (MCP_UI_VIEWER=" + viewerPref + ")", { url: handle.url });
468
- } else {
469
- const remoteLikely = remoteByEnv || await hasActiveRemoteLogin();
470
- const emitRemoteHint = async (openError: string | null, openedOnHost = false) => {
471
- state.ui?.notify(remoteAccessHint({
472
- url: handle.url,
473
- port: handle.port,
474
- moshi: await probeMoshiGateway(),
475
- openError,
476
- openedOnHost,
477
- }), openError === null ? "info" : "warning");
478
- };
479
- const glimpseDetected = !remoteByEnv && isGlimpseAvailable();
480
- const useGlimpse = !remoteByEnv && (viewerPref === "glimpse" ||
481
- (viewerPref !== "browser" && glimpseDetected));
482
-
483
- if (useGlimpse) {
484
- try {
485
- const glimpseHtml = `<!DOCTYPE html><html><head><meta charset="utf-8"><style>body{margin:0;padding:0;width:100vw;height:100vh;overflow:hidden}iframe{width:100%;height:100%;border:none}</style></head><body><iframe src="${handle.url}"></iframe></body></html>`;
486
- const glimpseWindow = await openGlimpseWindow(glimpseHtml, {
487
- title: `MCP · ${request.serverName} · ${request.toolName}`,
488
- width: 1000,
489
- height: 800,
490
- onClosed: () => {
491
- if (active) handle.close("glimpse-closed");
492
- },
493
- });
494
- if (state.owner?.isActive() === false || runtimeSignal.aborted) {
495
- glimpseWindow.close();
496
- throwIfAborted(runtimeSignal);
497
- throw new Error("MCP Glimpse window became stale before registration");
498
- }
499
- activeGlimpseWindow = glimpseWindow;
500
- viewer = "glimpse";
501
- if (remoteLikely) {
502
- await emitRemoteHint(null, true);
503
- }
504
- } catch (error) {
505
- log.debug("Glimpse unavailable, using browser", {
506
- error: error instanceof Error ? error.message : String(error),
507
- });
508
- const openError = await openInBrowser(state, handle.url, runtimeSignal);
509
- if (openError !== null || remoteLikely) {
510
- await emitRemoteHint(openError);
511
- }
512
- viewer = "browser";
513
- }
514
- } else {
515
- const openError = await openInBrowser(state, handle.url, runtimeSignal);
516
- if (openError !== null || remoteLikely) {
517
- await emitRemoteHint(openError);
518
- }
519
- }
520
- }
521
-
522
- throwIfAborted(runtimeSignal);
523
- handle.viewer = viewer;
524
- handle.windowOpen = windowOpen;
525
-
526
- return {
527
- serverName: request.serverName,
528
- toolName: request.toolName,
529
- reused: false,
530
- ...(streamId !== undefined ? { streamId } : {}),
531
- ...(streamToken !== undefined ? { streamToken } : {}),
532
- ...(streamMode !== undefined ? { streamMode } : {}),
533
- ...(streamToken ? { requestMeta: { [UI_STREAM_REQUEST_META_KEY]: streamToken } } : {}),
534
- url: handle.url,
535
- viewer,
536
- windowOpen,
537
- isActive: () => active && state.uiServer === handle,
538
- sendToolResult: (result: CallToolResult) => {
539
- if (!active || state.uiServer !== handle) return;
540
- nextStreamSequence += 1;
541
- handle.sendToolResult(withStreamEnvelope(result, streamId, nextStreamSequence));
542
- },
543
- sendResultPatch: (result: CallToolResult) => {
544
- if (!active || state.uiServer !== handle) return;
545
- nextStreamSequence += 1;
546
- handle.sendResultPatch(withStreamEnvelope(result, streamId, nextStreamSequence));
547
- },
548
- sendToolCancelled: (reason: string) => {
549
- if (!active || state.uiServer !== handle) return;
550
- handle.sendToolCancelled(reason);
551
- },
552
- close: (reason?: string) => {
553
- active = false;
554
- cleanupStreamListener();
555
- handle.close(reason);
556
- },
557
- };
558
- } catch (error) {
559
- if (error instanceof UrlElicitationRequiredError || isAbortError(error, runtimeSignal)) throw error;
560
- const message = error instanceof Error ? error.message : String(error);
561
- log.error("Failed to start UI session", error instanceof Error ? error : undefined);
562
- state.ui?.notify(
563
- `MCP UI unavailable for ${request.toolName} (${request.serverName}): ${message}`,
564
- "warning",
565
- );
566
- return null;
567
- }
568
- }
@@ -1,89 +0,0 @@
1
- import { z } from "zod";
2
-
3
- export const UI_STREAM_HOST_CONTEXT_KEY = "pi-mcp-adapter/stream";
4
- export const UI_STREAM_REQUEST_META_KEY = "pi-mcp-adapter/stream-token";
5
- export const UI_STREAM_RESULT_PATCH_METHOD = "notifications/pi-mcp-adapter/ui-result-patch";
6
- export const SERVER_STREAM_RESULT_PATCH_METHOD = "notifications/pi-mcp-adapter/result-patch";
7
- export const UI_STREAM_STRUCTURED_CONTENT_KEY = "pi-mcp-adapter/stream";
8
-
9
- export const uiStreamModeSchema = z.enum(["eager", "stream-first"]);
10
- export type UiStreamMode = z.infer<typeof uiStreamModeSchema>;
11
-
12
- export const visualizationStreamPhaseSchema = z.enum(["shell", "narrative", "structure", "detail", "settled"]);
13
- export type VisualizationStreamPhase = z.infer<typeof visualizationStreamPhaseSchema>;
14
-
15
- export const visualizationStreamFrameTypeSchema = z.enum(["patch", "checkpoint", "final"]);
16
- export type VisualizationStreamFrameType = z.infer<typeof visualizationStreamFrameTypeSchema>;
17
-
18
- export const visualizationStreamStatusSchema = z.enum(["ok", "error"]);
19
- export type VisualizationStreamStatus = z.infer<typeof visualizationStreamStatusSchema>;
20
-
21
- const looseRecordSchema = z.record(z.string(), z.unknown());
22
- const looseArraySchema = z.array(z.unknown());
23
-
24
- export const uiStreamHostContextSchema = z.object({
25
- mode: uiStreamModeSchema,
26
- streamId: z.string().min(1),
27
- intermediateResultPatches: z.boolean(),
28
- partialInput: z.boolean(),
29
- });
30
- export type UiStreamHostContext = z.infer<typeof uiStreamHostContextSchema>;
31
-
32
- export const visualizationStreamEnvelopeSchema = z.object({
33
- streamId: z.string().min(1),
34
- sequence: z.number().int().nonnegative(),
35
- frameType: visualizationStreamFrameTypeSchema,
36
- phase: visualizationStreamPhaseSchema,
37
- status: visualizationStreamStatusSchema,
38
- message: z.string().optional(),
39
- spec: looseRecordSchema.optional(),
40
- checkpoint: looseRecordSchema.optional(),
41
- });
42
- export type VisualizationStreamEnvelope = z.infer<typeof visualizationStreamEnvelopeSchema>;
43
-
44
- export const uiStreamCallToolResultSchema = z.object({
45
- content: looseArraySchema.optional(),
46
- structuredContent: looseRecordSchema.optional(),
47
- isError: z.boolean().optional(),
48
- _meta: looseRecordSchema.optional(),
49
- }).passthrough();
50
- export type UiStreamCallToolResult = z.infer<typeof uiStreamCallToolResultSchema>;
51
-
52
- export const uiStreamResultPatchNotificationSchema = z.object({
53
- method: z.literal(UI_STREAM_RESULT_PATCH_METHOD),
54
- params: uiStreamCallToolResultSchema,
55
- });
56
- export type UiStreamResultPatchNotification = z.infer<typeof uiStreamResultPatchNotificationSchema>;
57
-
58
- export const serverStreamResultPatchNotificationSchema = z.object({
59
- method: z.literal(SERVER_STREAM_RESULT_PATCH_METHOD),
60
- params: z.object({
61
- streamToken: z.string().min(1),
62
- result: uiStreamCallToolResultSchema,
63
- }),
64
- });
65
- export type ServerStreamResultPatchNotification = z.infer<typeof serverStreamResultPatchNotificationSchema>;
66
-
67
- export interface UiStreamSummary {
68
- streamId: string;
69
- mode: UiStreamMode;
70
- frames: number;
71
- phases: VisualizationStreamPhase[];
72
- finalStatus?: VisualizationStreamStatus;
73
- lastMessage?: string;
74
- }
75
-
76
- export function getUiStreamHostContext(hostContext: Record<string, unknown> | undefined): UiStreamHostContext | undefined {
77
- const candidate = hostContext?.[UI_STREAM_HOST_CONTEXT_KEY];
78
- const parsed = uiStreamHostContextSchema.safeParse(candidate);
79
- return parsed.success ? parsed.data : undefined;
80
- }
81
-
82
- export function getVisualizationStreamEnvelope(structuredContent: unknown): VisualizationStreamEnvelope | undefined {
83
- if (!structuredContent || typeof structuredContent !== "object" || Array.isArray(structuredContent)) {
84
- return undefined;
85
- }
86
- const candidate = (structuredContent as Record<string, unknown>)[UI_STREAM_STRUCTURED_CONTENT_KEY];
87
- const parsed = visualizationStreamEnvelopeSchema.safeParse(candidate);
88
- return parsed.success ? parsed.data : undefined;
89
- }
@@ -1,25 +0,0 @@
1
- export type UiToolVisibility = "model" | "app";
2
-
3
- export function extractUiToolVisibility(meta: Record<string, unknown> | undefined): UiToolVisibility[] | undefined {
4
- if (!meta || typeof meta !== "object") return undefined;
5
- const ui = meta.ui;
6
- if (!ui || typeof ui !== "object" || Array.isArray(ui)) return undefined;
7
- const visibility = (ui as Record<string, unknown>).visibility;
8
- if (visibility === undefined) return undefined;
9
- if (!Array.isArray(visibility)) return [];
10
-
11
- const values: UiToolVisibility[] = [];
12
- for (const entry of visibility) {
13
- if (entry !== "model" && entry !== "app") return [];
14
- if (!values.includes(entry)) values.push(entry);
15
- }
16
- return values;
17
- }
18
-
19
- export function isUiToolVisibleToModel(visibility: readonly UiToolVisibility[] | undefined): boolean {
20
- return visibility === undefined || visibility.includes("model");
21
- }
22
-
23
- export function isUiToolCallableByApp(visibility: readonly UiToolVisibility[] | undefined): boolean {
24
- return visibility === undefined || visibility.includes("app");
25
- }