@njuptlzf/mcp-adapter 2.29.0-0.0.1

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 (131) hide show
  1. package/CHANGELOG.md +1205 -0
  2. package/LICENSE +21 -0
  3. package/MAPPING.md +73 -0
  4. package/README.md +564 -0
  5. package/abort.ts +34 -0
  6. package/adapters/pi-renderer.ts +7 -0
  7. package/adapters/protocol-elicitation-forwarder.ts +164 -0
  8. package/adapters/protocol-sampling-forwarder.ts +108 -0
  9. package/adapters/universal-host.ts +213 -0
  10. package/agent-dir.ts +68 -0
  11. package/agent-plugin-loader.ts +377 -0
  12. package/app-bridge.bundle.js +67 -0
  13. package/banner.png +0 -0
  14. package/bin/mcp-server.ts +282 -0
  15. package/cli.js +392 -0
  16. package/commands.ts +735 -0
  17. package/config.ts +1284 -0
  18. package/consent-manager.ts +64 -0
  19. package/direct-tools.ts +619 -0
  20. package/dist/agent-dir.d.ts +10 -0
  21. package/dist/agent-dir.js +63 -0
  22. package/dist/agent-dir.js.map +1 -0
  23. package/dist/agent-plugin-loader.d.ts +8 -0
  24. package/dist/agent-plugin-loader.js +356 -0
  25. package/dist/agent-plugin-loader.js.map +1 -0
  26. package/dist/config.d.ts +123 -0
  27. package/dist/config.js +1087 -0
  28. package/dist/config.js.map +1 -0
  29. package/dist/metadata-cache.d.ts +19 -0
  30. package/dist/metadata-cache.js +319 -0
  31. package/dist/metadata-cache.js.map +1 -0
  32. package/dist/package-mcp-loader.d.ts +2 -0
  33. package/dist/package-mcp-loader.js +156 -0
  34. package/dist/package-mcp-loader.js.map +1 -0
  35. package/dist/resource-tools.d.ts +1 -0
  36. package/dist/resource-tools.js +15 -0
  37. package/dist/resource-tools.js.map +1 -0
  38. package/dist/types.d.ts +564 -0
  39. package/dist/types.js +287 -0
  40. package/dist/types.js.map +1 -0
  41. package/dist/ui-app-bridge-helpers.d.ts +6 -0
  42. package/dist/ui-app-bridge-helpers.js +37 -0
  43. package/dist/ui-app-bridge-helpers.js.map +1 -0
  44. package/dist/ui-stream-types.d.ts +104 -0
  45. package/dist/ui-stream-types.js +59 -0
  46. package/dist/ui-stream-types.js.map +1 -0
  47. package/dist/ui-tool-visibility.d.ts +4 -0
  48. package/dist/ui-tool-visibility.js +27 -0
  49. package/dist/ui-tool-visibility.js.map +1 -0
  50. package/dist/utils.d.ts +32 -0
  51. package/dist/utils.js +338 -0
  52. package/dist/utils.js.map +1 -0
  53. package/elicitation-handler.ts +348 -0
  54. package/error-signal.ts +21 -0
  55. package/errors.ts +223 -0
  56. package/failure-backoff.ts +23 -0
  57. package/glimpse-ui.ts +80 -0
  58. package/host-html-template.ts +461 -0
  59. package/index.ts +1291 -0
  60. package/init.ts +692 -0
  61. package/interfaces/agent-paths.ts +67 -0
  62. package/interfaces/host-types.ts +102 -0
  63. package/interfaces/sampling.ts +57 -0
  64. package/json-schema-validator.ts +69 -0
  65. package/lifecycle.ts +446 -0
  66. package/logger.ts +169 -0
  67. package/mcp-auth-flow.ts +1026 -0
  68. package/mcp-auth.ts +1000 -0
  69. package/mcp-bearer-store.ts +387 -0
  70. package/mcp-callback-server.ts +534 -0
  71. package/mcp-code.ts +360 -0
  72. package/mcp-keyring-helper.cjs +89 -0
  73. package/mcp-oauth-provider.ts +666 -0
  74. package/mcp-output-guard.ts +496 -0
  75. package/mcp-panel.ts +1044 -0
  76. package/mcp-probe.ts +201 -0
  77. package/mcp-references.ts +368 -0
  78. package/mcp-script-worker.mjs +130 -0
  79. package/mcp-server.mjs +2133 -0
  80. package/mcp-setup-panel.ts +667 -0
  81. package/mcp-status.ts +98 -0
  82. package/mcp-trace.ts +306 -0
  83. package/metadata-cache.ts +382 -0
  84. package/namespace-tools.ts +276 -0
  85. package/npx-resolver.ts +543 -0
  86. package/oauth-handler.ts +30 -0
  87. package/oauth.ts +48 -0
  88. package/onboarding-state.ts +76 -0
  89. package/package-mcp-loader.ts +168 -0
  90. package/package.json +225 -0
  91. package/panel-keys.ts +53 -0
  92. package/prompts.ts +353 -0
  93. package/proxy-modes.ts +1418 -0
  94. package/request-headers-command.ts +330 -0
  95. package/resource-tools.ts +17 -0
  96. package/runtime-owner.ts +91 -0
  97. package/sampling-handler.ts +284 -0
  98. package/search-ranking.ts +278 -0
  99. package/server-manager.ts +1318 -0
  100. package/session-recovery.ts +158 -0
  101. package/skills/README.md +64 -0
  102. package/skills/mcp-adapter/SKILL.md +332 -0
  103. package/skills/mcp-adapter/references/deploy-examples.md +259 -0
  104. package/skills/mcp-adapter/references/deploy.md +89 -0
  105. package/skills/mcp-adapter/references/generate.md +144 -0
  106. package/skills/mcp-adapter/references/resolver.md +105 -0
  107. package/skills/mcp-adapter/references/verify.md +157 -0
  108. package/skills/mcp-scripting/SKILL.md +38 -0
  109. package/skills/resolve-conflicts/SKILL.md +482 -0
  110. package/skills/resolve-conflicts/references/patterns.md +432 -0
  111. package/skills/resolve-conflicts/references/sample-plan.md +96 -0
  112. package/skills/resolve-conflicts/scripts/handle-deleted-modified.sh +183 -0
  113. package/skills/resolve-conflicts/scripts/validate-conflicts.sh +120 -0
  114. package/skills/upstream-merge/SKILL.md +486 -0
  115. package/skills/upstream-merge/references/pi-coupling-markers.md +129 -0
  116. package/skills/upstream-merge/references/special-cases.md +39 -0
  117. package/state.ts +60 -0
  118. package/tool-approval.ts +195 -0
  119. package/tool-metadata.ts +296 -0
  120. package/tool-registrar.ts +253 -0
  121. package/tool-result-renderer.ts +477 -0
  122. package/ts-shape.ts +149 -0
  123. package/types.ts +991 -0
  124. package/ui-app-bridge-helpers.ts +40 -0
  125. package/ui-resource-handler.ts +250 -0
  126. package/ui-server.ts +852 -0
  127. package/ui-session.ts +571 -0
  128. package/ui-stream-types.ts +89 -0
  129. package/ui-tool-visibility.ts +25 -0
  130. package/unix-socket-transport.ts +85 -0
  131. package/utils.ts +382 -0
package/ui-server.ts ADDED
@@ -0,0 +1,852 @@
1
+ import http, { type IncomingMessage, type ServerResponse } from "node:http";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { buildAllowAttribute } from "./ui-app-bridge-helpers.ts";
6
+ import {
7
+ type CallToolRequest,
8
+ type CallToolResult,
9
+ } from "@modelcontextprotocol/client";
10
+ import { ContentBlockSchema } from "@modelcontextprotocol/core";
11
+ import type { ConsentManager } from "./consent-manager.ts";
12
+ import { ServerError, wrapError } from "./errors.ts";
13
+ import { formatAuthRequiredMessage, normalizeToolArguments } from "./utils.ts";
14
+ import { buildHostHtmlTemplate, buildCspMetaContent } from "./host-html-template.ts";
15
+ import { logger } from "./logger.ts";
16
+ import type { McpServerManager } from "./server-manager.ts";
17
+ import type { McpExtensionState } from "./state.ts";
18
+ import { SessionRecoveryAuthRequiredError, withSessionRecovery, type SessionRecoveryDeps } from "./session-recovery.ts";
19
+ import { ensureToolCallApproved, isToolCallApprovalRequired } from "./tool-approval.ts";
20
+ import { extractUiToolVisibility, isUiToolCallableByApp, isUiToolVisibleToModel } from "./ui-tool-visibility.ts";
21
+ import { resourceNameToToolName } from "./resource-tools.ts";
22
+ import {
23
+ createUiModelContextUpdate,
24
+ extractUiPromptText,
25
+ getVisualizationStreamEnvelope,
26
+ isServerDisabled,
27
+ type McpConfig,
28
+ type UiDisplayMode,
29
+ type UiDisplayModeRequest,
30
+ type UiDisplayModeResult,
31
+ type UiHostContext,
32
+ type UiMessageParams,
33
+ type UiModelContextParams,
34
+ type UiOpenLinkResult,
35
+ type UiProxyRequestBody,
36
+ type UiProxyResult,
37
+ type UiResourceContent,
38
+ type UiServerHandle,
39
+ type UiSessionMessages,
40
+ type UiStreamSummary,
41
+ } from "./types.ts";
42
+
43
+ export type { UiServerHandle };
44
+
45
+ const MAX_BODY_SIZE = 2 * 1024 * 1024;
46
+ const ABANDONED_GRACE_MS = 60_000;
47
+ const WATCHDOG_INTERVAL_MS = 5_000;
48
+ const MAX_EVENT_LOG = 128;
49
+ const MAX_CONTEXT_UPDATES = 20;
50
+ const MOSHI_DISCOVERY_PORT_START = 8377;
51
+ const MOSHI_DISCOVERY_PORT_END = 8396;
52
+ let nextMoshiDiscoveryPort = MOSHI_DISCOVERY_PORT_START;
53
+
54
+ export interface UiServerOptions {
55
+ serverName: string;
56
+ toolName: string;
57
+ toolArgs: Record<string, unknown>;
58
+ resource: UiResourceContent;
59
+ manager: McpServerManager;
60
+ /**
61
+ * Live extension config, used to re-read the server definition when
62
+ * recovering a terminated Streamable HTTP session (see
63
+ * session-recovery.ts). Optional so existing embedders/tests that don't
64
+ * need session recovery aren't forced to supply it; without it, proxied
65
+ * tool calls run without recovery (unchanged pre-existing behavior).
66
+ */
67
+ config?: McpConfig;
68
+ /** Live state enables TUI approval prompts for iframe-originated tool calls. */
69
+ state?: McpExtensionState;
70
+ onNeedsAuth?: SessionRecoveryDeps["onNeedsAuth"];
71
+ consentManager: ConsentManager;
72
+ hostContext?: UiHostContext;
73
+ initialResultPromise?: Promise<CallToolResult>;
74
+ sessionToken?: string;
75
+ port?: number;
76
+ onMessage?: (params: UiMessageParams) => Promise<void> | void;
77
+ onContextUpdate?: (params: UiModelContextParams) => Promise<void> | void;
78
+ onComplete?: (reason: string) => void;
79
+ }
80
+
81
+ export async function startUiServer(options: UiServerOptions): Promise<UiServerHandle> {
82
+ const sessionToken = options.sessionToken ?? randomUUID();
83
+ const uiResourceToken = randomUUID();
84
+ const log = logger.child({
85
+ component: "UiServer",
86
+ server: options.serverName,
87
+ tool: options.toolName,
88
+ session: sessionToken.slice(0, 8),
89
+ });
90
+
91
+ log.debug("Starting UI server");
92
+
93
+ const sseClients = new Set<ServerResponse>();
94
+ let completed = false;
95
+ let lastHeartbeatAt = Date.now();
96
+ let watchdog: NodeJS.Timeout | null = null;
97
+ let currentDisplayMode: UiDisplayMode = options.hostContext?.displayMode ?? "inline";
98
+ let nextEventId = 1;
99
+ const eventLog: Array<{ id: number; name: string; payload: unknown }> = [];
100
+ let latestCheckpointEventId: number | undefined;
101
+ let streamSummary: UiStreamSummary | undefined;
102
+
103
+ // Track messages from UI for retrieval
104
+ const sessionMessages: UiSessionMessages = {
105
+ prompts: [],
106
+ notifications: [],
107
+ intents: [],
108
+ contexts: [],
109
+ };
110
+
111
+ const hostContext: UiHostContext = {
112
+ displayMode: currentDisplayMode,
113
+ availableDisplayModes: ["inline", "fullscreen", "pip"],
114
+ platform: "desktop",
115
+ ...options.hostContext,
116
+ // Only include toolInfo if caller provides full tool definition with inputSchema
117
+ // The App validates toolInfo.tool.inputSchema as required object
118
+ };
119
+
120
+ const initialStreamContext = hostContext["pi-mcp-adapter/stream"];
121
+ if (initialStreamContext && typeof initialStreamContext === "object") {
122
+ const streamId = (initialStreamContext as { streamId?: unknown }).streamId;
123
+ const mode = (initialStreamContext as { mode?: unknown }).mode;
124
+ if (typeof streamId === "string" && (mode === "eager" || mode === "stream-first")) {
125
+ streamSummary = {
126
+ streamId,
127
+ mode,
128
+ frames: 0,
129
+ phases: [],
130
+ };
131
+ }
132
+ }
133
+
134
+ const isAppOnlyTool = (toolName: string): boolean => {
135
+ const toolDefinition = options.manager.getConnection(options.serverName)?.tools?.find((tool) => tool.name === toolName);
136
+ if (!toolDefinition) return false;
137
+ const visibility = extractUiToolVisibility(toolDefinition._meta);
138
+ return isUiToolCallableByApp(visibility) && !isUiToolVisibleToModel(visibility);
139
+ };
140
+
141
+ const recordUiMessage = async (msgParams: UiMessageParams): Promise<void> => {
142
+ const promptText = extractUiPromptText(msgParams);
143
+
144
+ // Track messages by type (order: prompt → intent → notify)
145
+ // Must match the order in index.ts onMessage handler
146
+ if (promptText) {
147
+ sessionMessages.prompts.push(promptText);
148
+ log.debug("UI prompt received", { prompt: promptText.slice(0, 100) });
149
+ } else if (msgParams.type === "intent" || msgParams.intent) {
150
+ const intentName = msgParams.intent ?? "";
151
+ if (intentName) {
152
+ sessionMessages.intents.push({
153
+ intent: intentName,
154
+ ...(msgParams.params !== undefined ? { params: msgParams.params } : {}),
155
+ });
156
+ log.debug("UI intent received", { intent: intentName });
157
+ }
158
+ } else if (msgParams.type === "notify" || msgParams.message) {
159
+ const notifyText = msgParams.message ?? "";
160
+ if (notifyText) {
161
+ sessionMessages.notifications.push(notifyText);
162
+ log.debug("UI notification", { message: notifyText.slice(0, 100) });
163
+ }
164
+ }
165
+
166
+ await options.onMessage?.(msgParams);
167
+ };
168
+
169
+ const touchHeartbeat = () => {
170
+ lastHeartbeatAt = Date.now();
171
+ };
172
+
173
+ const updateStreamSummary = (eventId: number, payload: unknown) => {
174
+ const envelope = getVisualizationStreamEnvelope((payload as { structuredContent?: unknown } | null)?.structuredContent);
175
+ if (!envelope) return;
176
+ if (envelope.frameType === "checkpoint" || envelope.frameType === "final") {
177
+ latestCheckpointEventId = eventId;
178
+ }
179
+ if (!streamSummary) {
180
+ streamSummary = {
181
+ streamId: envelope.streamId,
182
+ mode: "eager",
183
+ frames: 0,
184
+ phases: [],
185
+ };
186
+ }
187
+ streamSummary.frames += 1;
188
+ if (!streamSummary.phases.includes(envelope.phase)) {
189
+ streamSummary.phases.push(envelope.phase);
190
+ }
191
+ streamSummary.finalStatus = envelope.status;
192
+ if (envelope.message !== undefined) streamSummary.lastMessage = envelope.message;
193
+ else delete streamSummary.lastMessage;
194
+ };
195
+
196
+ const serializeEvent = (eventId: number, name: string, payload: unknown): string => {
197
+ return `id: ${eventId}\nevent: ${name}\ndata: ${JSON.stringify(payload)}\n\n`;
198
+ };
199
+
200
+ const getLatestCheckpointIndex = () => {
201
+ const firstEventId = eventLog[0]?.id;
202
+ if (latestCheckpointEventId === undefined || firstEventId === undefined || latestCheckpointEventId < firstEventId) return -1;
203
+ return latestCheckpointEventId - firstEventId;
204
+ };
205
+
206
+ const pruneEventLog = () => {
207
+ if (eventLog.length <= MAX_EVENT_LOG) return;
208
+ const latestCheckpointIndex = getLatestCheckpointIndex();
209
+
210
+ if (latestCheckpointIndex > 0) {
211
+ eventLog.splice(0, latestCheckpointIndex);
212
+ }
213
+
214
+ if (eventLog.length > MAX_EVENT_LOG) {
215
+ eventLog.splice(0, eventLog.length - MAX_EVENT_LOG);
216
+ }
217
+ };
218
+
219
+ const pushEvent = (name: string, payload: unknown) => {
220
+ if (completed) return;
221
+ const eventId = nextEventId++;
222
+ eventLog.push({ id: eventId, name, payload });
223
+ updateStreamSummary(eventId, payload);
224
+ pruneEventLog();
225
+ const chunk = serializeEvent(eventId, name, payload);
226
+ for (const client of sseClients) {
227
+ try {
228
+ client.write(chunk);
229
+ } catch {
230
+ sseClients.delete(client);
231
+ }
232
+ }
233
+ };
234
+
235
+ const replayEvents = (res: ServerResponse, lastEventIdHeader?: string | null) => {
236
+ const parsedLastId = lastEventIdHeader ? Number(lastEventIdHeader) : Number.NaN;
237
+ const eventsToReplay = Number.isFinite(parsedLastId)
238
+ ? eventLog.filter((entry) => entry.id > parsedLastId)
239
+ : (() => {
240
+ const latestCheckpointIndex = getLatestCheckpointIndex();
241
+ return latestCheckpointIndex >= 0 ? eventLog.slice(latestCheckpointIndex) : eventLog;
242
+ })();
243
+
244
+ for (const entry of eventsToReplay) {
245
+ try {
246
+ res.write(serializeEvent(entry.id, entry.name, entry.payload));
247
+ } catch {
248
+ sseClients.delete(res);
249
+ return;
250
+ }
251
+ }
252
+ };
253
+
254
+ const closeSse = () => {
255
+ for (const client of sseClients) {
256
+ try {
257
+ client.end();
258
+ } catch {}
259
+ }
260
+ sseClients.clear();
261
+ };
262
+
263
+ const stopWatchdog = () => {
264
+ if (!watchdog) return;
265
+ clearInterval(watchdog);
266
+ watchdog = null;
267
+ };
268
+
269
+ const markCompleted = (reason: string) => {
270
+ if (completed) return;
271
+ log.debug("Session completed", { reason });
272
+ pushEvent("session-complete", { reason });
273
+ completed = true;
274
+ stopWatchdog();
275
+ options.onComplete?.(reason);
276
+ };
277
+
278
+ const server = http.createServer(async (req, res) => {
279
+ try {
280
+ const method = req.method || "GET";
281
+ const hostHeader = req.headers.host;
282
+ const url = new URL(req.url || "/", `http://${hostHeader || "127.0.0.1"}`);
283
+ if (hostHeader !== undefined && !isAllowedHost(url.hostname)) {
284
+ sendText(res, 403, "Invalid host");
285
+ return;
286
+ }
287
+
288
+ if (method === "HEAD" && url.pathname === "/") {
289
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
290
+ res.end();
291
+ return;
292
+ }
293
+
294
+ if (method === "GET" && url.pathname === "/") {
295
+ if (!url.searchParams.has("session")) {
296
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
297
+ res.end(
298
+ "<!doctype html><html><head><meta charset=\"utf-8\"><title>MCP UI</title></head>" +
299
+ "<body><p>Open the authenticated MCP UI URL shown by Pi.</p></body></html>",
300
+ );
301
+ return;
302
+ }
303
+ if (!validateTokenQuery(url, sessionToken, res)) return;
304
+ touchHeartbeat();
305
+
306
+ const html = buildHostHtmlTemplate({
307
+ sessionToken,
308
+ uiResourceToken,
309
+ serverName: options.serverName,
310
+ toolName: options.toolName,
311
+ toolArgs: options.toolArgs,
312
+ resource: options.resource,
313
+ allowAttribute: buildAllowAttribute(options.resource.meta.permissions),
314
+ requireToolConsent: options.consentManager.requiresPrompt(options.serverName),
315
+ cacheToolConsent: options.consentManager.shouldCacheConsent(),
316
+ hostContext,
317
+ });
318
+
319
+ res.writeHead(200, {
320
+ "Content-Type": "text/html; charset=utf-8",
321
+ "Cache-Control": "no-store",
322
+ });
323
+ res.end(html);
324
+ return;
325
+ }
326
+
327
+ if (method === "GET" && url.pathname === "/events") {
328
+ if (!validateTokenQuery(url, sessionToken, res)) return;
329
+ touchHeartbeat();
330
+ log.debug("SSE client connected", { clientCount: sseClients.size + 1 });
331
+ res.writeHead(200, {
332
+ "Content-Type": "text/event-stream",
333
+ "Cache-Control": "no-cache, no-transform",
334
+ Connection: "keep-alive",
335
+ "X-Accel-Buffering": "no",
336
+ });
337
+ res.write(": connected\n\n");
338
+ sseClients.add(res);
339
+ replayEvents(res, req.headers["last-event-id"] ? String(req.headers["last-event-id"]) : null);
340
+ req.on("close", () => {
341
+ sseClients.delete(res);
342
+ });
343
+ return;
344
+ }
345
+
346
+ if (method === "GET" && url.pathname === "/health") {
347
+ if (!validateTokenQuery(url, sessionToken, res)) return;
348
+ sendJson(res, 200, { ok: true, result: { healthy: true } });
349
+ return;
350
+ }
351
+
352
+ if (method === "GET" && url.pathname === "/ui-app") {
353
+ if (!validateTokenQuery(url, uiResourceToken, res, "resource")) return;
354
+ touchHeartbeat();
355
+ // Enforce host metadata independently of where app HTML places its document head.
356
+ const cspContent = buildCspMetaContent(options.resource.meta.csp);
357
+ res.writeHead(200, {
358
+ "Content-Type": "text/html; charset=utf-8",
359
+ "Cache-Control": "no-store",
360
+ "Content-Security-Policy": cspContent,
361
+ });
362
+ res.end(options.resource.html);
363
+ return;
364
+ }
365
+
366
+ if (method === "GET" && url.pathname === "/app-bridge.bundle.js") {
367
+ // Serve the pre-bundled AppBridge module
368
+ const bundlePath = path.join(import.meta.dirname, "app-bridge.bundle.js");
369
+ try {
370
+ const content = await fs.readFile(bundlePath, "utf-8");
371
+ res.writeHead(200, {
372
+ "Content-Type": "application/javascript",
373
+ "Cache-Control": "public, max-age=31536000",
374
+ });
375
+ res.end(content);
376
+ } catch {
377
+ sendJson(res, 500, { ok: false, error: "Bundle not found" });
378
+ }
379
+ return;
380
+ }
381
+
382
+ if (method !== "POST") {
383
+ sendJson(res, 404, { ok: false, error: "Not found" });
384
+ return;
385
+ }
386
+
387
+ const body = await parseBody(req, res);
388
+ if (!body) return;
389
+ if (!validateTokenBody(body, sessionToken, res)) return;
390
+ const params = body.params ?? {};
391
+ touchHeartbeat();
392
+
393
+ if (url.pathname === "/proxy/tools/call") {
394
+ options.consentManager.ensureApproved(options.serverName);
395
+ const callParams = params as CallToolRequest["params"];
396
+ if (!callParams || typeof callParams.name !== "string" || !callParams.name.trim()) {
397
+ sendJson(res, 400, { ok: false, error: "Invalid tools/call params" });
398
+ return;
399
+ }
400
+
401
+ const connection = options.manager.getConnection(options.serverName);
402
+ if (!connection || connection.status !== "connected") {
403
+ sendJson(res, 503, { ok: false, error: `Server "${options.serverName}" is not connected` });
404
+ return;
405
+ }
406
+ if (isServerDisabled(options.config?.mcpServers[options.serverName]) || isServerDisabled(connection.definition)) {
407
+ sendJson(res, 503, { ok: false, error: `Server "${options.serverName}" is disabled` });
408
+ return;
409
+ }
410
+
411
+ const toolDefinitions = Array.isArray(connection.tools) ? connection.tools : [];
412
+ const toolDefinition = toolDefinitions.find((tool) => tool.name === callParams.name);
413
+ if (!toolDefinition) {
414
+ sendJson(res, 403, { ok: false, error: `MCP tool "${callParams.name}" is not callable by apps` });
415
+ return;
416
+ }
417
+ const uiVisibility = extractUiToolVisibility(toolDefinition._meta);
418
+ if (!isUiToolCallableByApp(uiVisibility)) {
419
+ sendJson(res, 403, { ok: false, error: `MCP tool "${callParams.name}" is not callable by apps` });
420
+ return;
421
+ }
422
+
423
+ let normalizedArguments: Record<string, unknown>;
424
+ try {
425
+ normalizedArguments = normalizeToolArguments(callParams.arguments, `tool "${callParams.name}" arguments`);
426
+ } catch (error) {
427
+ sendJson(res, 400, { ok: false, error: error instanceof Error ? error.message : String(error) });
428
+ return;
429
+ }
430
+ const callArgs = {
431
+ name: callParams.name,
432
+ arguments: normalizedArguments,
433
+ };
434
+ const toolMeta = {
435
+ name: callParams.name,
436
+ originalName: callParams.name,
437
+ description: toolDefinition?.description ?? "",
438
+ ...(toolDefinition?.inputSchema !== undefined ? { inputSchema: toolDefinition.inputSchema } : {}),
439
+ ...(uiVisibility !== undefined ? { uiVisibility } : {}),
440
+ };
441
+ const approvalMetadata = new Map(options.state?.toolMetadata);
442
+ const definition = options.config?.mcpServers[options.serverName] ?? options.state?.config.mcpServers[options.serverName];
443
+ approvalMetadata.set(options.serverName, [
444
+ ...connection.tools.map(tool => ({
445
+ name: tool.name,
446
+ originalName: tool.name,
447
+ description: tool.description ?? "",
448
+ })),
449
+ ...(definition?.exposeResources !== false ? (connection.resources ?? []).map(resource => {
450
+ const originalName = `read_${resourceNameToToolName(resource.name)}`;
451
+ return {
452
+ name: originalName,
453
+ originalName,
454
+ description: resource.description ?? `Read resource: ${resource.uri}`,
455
+ };
456
+ }) : []),
457
+ ]);
458
+ const approval = options.state
459
+ ? await ensureToolCallApproved(
460
+ options.state,
461
+ options.serverName,
462
+ toolMeta,
463
+ callArgs.arguments,
464
+ options.state.owner?.signal,
465
+ "iframe",
466
+ approvalMetadata,
467
+ )
468
+ : options.config && isToolCallApprovalRequired(options.config, options.serverName, toolMeta, approvalMetadata)
469
+ ? { ok: false as const, reason: "approval_required_headless" as const }
470
+ : { ok: true as const };
471
+ if (approval.ok === false) {
472
+ const denied = approval.reason === "denied";
473
+ const message = denied
474
+ ? `The user declined approval to run MCP tool "${callParams.name}" on server "${options.serverName}".`
475
+ : `MCP tool "${callParams.name}" on server "${options.serverName}" is approval-gated and requires an interactive session.`;
476
+ sendJson(res, 200, {
477
+ ok: true,
478
+ result: {
479
+ content: [{ type: "text" as const, text: message }],
480
+ details: {
481
+ error: denied ? "approval_denied" : "approval_required",
482
+ server: options.serverName,
483
+ tool: callParams.name,
484
+ },
485
+ },
486
+ });
487
+ return;
488
+ }
489
+
490
+ try {
491
+ options.manager.touch(options.serverName);
492
+ options.manager.incrementInFlight(options.serverName);
493
+ const result = options.config
494
+ ? await withSessionRecovery(
495
+ {
496
+ manager: options.manager,
497
+ config: options.config,
498
+ ...(options.onNeedsAuth ? { onNeedsAuth: options.onNeedsAuth } : {}),
499
+ },
500
+ options.serverName,
501
+ (conn) => conn.client.callTool(callArgs, options.manager.getRequestOptions?.(options.serverName)),
502
+ )
503
+ : await connection.client.callTool(callArgs, options.manager.getRequestOptions?.(options.serverName));
504
+ sendJson(res, 200, { ok: true, result });
505
+ } finally {
506
+ options.manager.decrementInFlight(options.serverName);
507
+ options.manager.touch(options.serverName);
508
+ }
509
+ return;
510
+ }
511
+
512
+ if (url.pathname === "/proxy/ui/consent") {
513
+ const approved = !!(params as { approved?: boolean }).approved;
514
+ options.consentManager.registerDecision(options.serverName, approved);
515
+ sendJson(res, 200, { ok: true, result: { approved } });
516
+ return;
517
+ }
518
+
519
+ if (url.pathname === "/proxy/ui/generated-tool-call-intent") {
520
+ const tool = typeof params.tool === "string" ? params.tool : undefined;
521
+ if (tool && isAppOnlyTool(tool)) {
522
+ log.debug("Ignored generated app-only tool call intent", { tool });
523
+ } else {
524
+ await recordUiMessage({
525
+ type: "intent",
526
+ intent: "call_tool",
527
+ params: {
528
+ ...(tool !== undefined ? { tool } : {}),
529
+ ...(params.arguments !== undefined ? { arguments: params.arguments } : {}),
530
+ ...(params.isError !== undefined ? { isError: params.isError } : {}),
531
+ },
532
+ });
533
+ }
534
+ sendJson(res, 200, { ok: true, result: {} });
535
+ return;
536
+ }
537
+
538
+ if (url.pathname === "/proxy/ui/message") {
539
+ await recordUiMessage(params as UiMessageParams);
540
+ sendJson(res, 200, { ok: true, result: {} });
541
+ return;
542
+ }
543
+
544
+ if (url.pathname === "/proxy/ui/context") {
545
+ const content = params.content;
546
+ const structuredContent = params.structuredContent;
547
+ if (
548
+ (content !== undefined && (!Array.isArray(content) || content.some((block) => !ContentBlockSchema.safeParse(block).success))) ||
549
+ (structuredContent !== undefined && (!structuredContent || typeof structuredContent !== "object" || Array.isArray(structuredContent)))
550
+ ) {
551
+ sendJson(res, 400, { ok: false, error: "Invalid update-model-context params" });
552
+ return;
553
+ }
554
+ const ctxParams: UiModelContextParams = {
555
+ ...(content !== undefined ? { content: content as NonNullable<UiModelContextParams["content"]> } : {}),
556
+ ...(structuredContent !== undefined ? { structuredContent: structuredContent as Record<string, unknown> } : {}),
557
+ };
558
+ const update = createUiModelContextUpdate(ctxParams);
559
+ if (update) {
560
+ sessionMessages.contexts.push(update);
561
+ while (sessionMessages.contexts.length > MAX_CONTEXT_UPDATES) {
562
+ sessionMessages.contexts.shift();
563
+ }
564
+ }
565
+ log.debug("UI context update", { hasContent: !!ctxParams.content, hasUpdate: !!update });
566
+ await options.onContextUpdate?.(ctxParams);
567
+ sendJson(res, 200, { ok: true, result: {} });
568
+ return;
569
+ }
570
+
571
+ if (url.pathname === "/proxy/ui/open-link") {
572
+ const openParams = params as { url?: string };
573
+ if (!openParams?.url || typeof openParams.url !== "string") {
574
+ sendJson(res, 400, { ok: false, error: "Invalid open-link params" });
575
+ return;
576
+ }
577
+ let result: UiOpenLinkResult = {};
578
+ try {
579
+ new URL(openParams.url);
580
+ } catch {
581
+ result = { isError: true };
582
+ }
583
+ sendJson(res, 200, { ok: true, result });
584
+ return;
585
+ }
586
+
587
+ if (url.pathname === "/proxy/ui/download-file") {
588
+ sendJson(res, 200, { ok: true, result: { isError: true } });
589
+ return;
590
+ }
591
+
592
+ if (url.pathname === "/proxy/ui/request-display-mode") {
593
+ const displayParams = params as UiDisplayModeRequest;
594
+ const requested = displayParams?.mode;
595
+ const available = hostContext.availableDisplayModes ?? ["inline"];
596
+ if (requested && available.includes(requested)) {
597
+ currentDisplayMode = requested;
598
+ }
599
+ hostContext.displayMode = currentDisplayMode;
600
+ pushEvent("host-context", { displayMode: currentDisplayMode });
601
+ const result: UiDisplayModeResult = { mode: currentDisplayMode };
602
+ sendJson(res, 200, { ok: true, result });
603
+ return;
604
+ }
605
+
606
+ if (url.pathname === "/proxy/ui/heartbeat") {
607
+ sendJson(res, 200, { ok: true, result: {} });
608
+ return;
609
+ }
610
+
611
+ if (url.pathname === "/proxy/ui/complete") {
612
+ const reason = typeof (params as { reason?: string }).reason === "string"
613
+ ? (params as { reason?: string }).reason!
614
+ : "done";
615
+ markCompleted(reason);
616
+ sendJson(res, 200, { ok: true, result: {} });
617
+ setTimeout(() => {
618
+ try {
619
+ server.close();
620
+ } catch {}
621
+ closeSse();
622
+ }, 20).unref();
623
+ return;
624
+ }
625
+
626
+ sendJson(res, 404, { ok: false, error: "Not found" });
627
+ } catch (error) {
628
+ if (error instanceof SessionRecoveryAuthRequiredError) {
629
+ const fallback = `Server "${options.serverName}" requires OAuth authentication. Run mcp({ action: "auth-start", server: "${options.serverName}" }) to get a browser URL, or /mcp-auth ${options.serverName} in an interactive local session.`;
630
+ const message = error.authMessage ?? (options.config
631
+ ? formatAuthRequiredMessage(options.config, options.serverName, fallback)
632
+ : fallback);
633
+ sendJson(res, 401, { ok: false, error: message });
634
+ return;
635
+ }
636
+ const wrapped = wrapError(error, { server: options.serverName, tool: options.toolName });
637
+ const status = /approval required|denied/i.test(wrapped.message) ? 403 : 500;
638
+ if (status === 500) {
639
+ log.error("Request handler error", error instanceof Error ? error : undefined);
640
+ }
641
+ sendJson(res, status, { ok: false, error: wrapped.message });
642
+ }
643
+ });
644
+
645
+ if (options.initialResultPromise) {
646
+ options.initialResultPromise.then(
647
+ (result) => pushEvent("tool-result", result),
648
+ (error) => {
649
+ const reason = error instanceof Error ? error.message : String(error);
650
+ pushEvent("tool-cancelled", { reason });
651
+ }
652
+ );
653
+ }
654
+
655
+ watchdog = setInterval(() => {
656
+ if (completed) return;
657
+ if (Date.now() - lastHeartbeatAt <= ABANDONED_GRACE_MS) return;
658
+ markCompleted("stale");
659
+ try {
660
+ server.close();
661
+ } catch {}
662
+ closeSse();
663
+ }, WATCHDOG_INTERVAL_MS);
664
+ watchdog.unref();
665
+
666
+ return new Promise((resolve, reject) => {
667
+ const candidates = resolvePortCandidates(options.port);
668
+ let candidateIndex = 0;
669
+
670
+ const listen = () => {
671
+ server.once("error", onError);
672
+ server.listen(candidates[candidateIndex], "127.0.0.1", onListening);
673
+ };
674
+
675
+ const onError = (error: NodeJS.ErrnoException) => {
676
+ server.off("listening", onListening);
677
+ if (error.code === "EADDRINUSE" && candidateIndex < candidates.length - 1) {
678
+ candidateIndex += 1;
679
+ listen();
680
+ return;
681
+ }
682
+ log.error("Failed to start server", error);
683
+ const port = candidates[candidateIndex];
684
+ reject(new ServerError(error.message, {
685
+ ...(port !== undefined ? { port } : {}),
686
+ cause: error,
687
+ }));
688
+ };
689
+
690
+ const onListening = () => {
691
+ server.off("error", onError);
692
+ const address = server.address();
693
+ if (!address || typeof address === "string") {
694
+ const err = new ServerError("invalid address");
695
+ log.error("Invalid server address", err);
696
+ reject(err);
697
+ return;
698
+ }
699
+
700
+ log.debug("Server started", { port: address.port });
701
+ rememberMoshiDiscoveryPort(address.port);
702
+
703
+ const handle: UiServerHandle = {
704
+ url: `http://localhost:${address.port}/?session=${sessionToken}`,
705
+ port: address.port,
706
+ sessionToken,
707
+ serverName: options.serverName,
708
+ toolName: options.toolName,
709
+ close: (reason?: string) => {
710
+ markCompleted(reason ?? "closed");
711
+ try {
712
+ server.close();
713
+ } catch {}
714
+ closeSse();
715
+ },
716
+ sendToolInput: (args: Record<string, unknown>) => {
717
+ pushEvent("tool-input", { arguments: args });
718
+ },
719
+ sendToolResult: (result: CallToolResult) => {
720
+ pushEvent("tool-result", result);
721
+ },
722
+ sendResultPatch: (result: CallToolResult) => {
723
+ pushEvent("result-patch", result);
724
+ },
725
+ sendToolCancelled: (reason: string) => {
726
+ pushEvent("tool-cancelled", { reason });
727
+ },
728
+ sendHostContext: (context: UiHostContext) => {
729
+ Object.assign(hostContext, context);
730
+ pushEvent("host-context", context);
731
+ },
732
+ getSessionMessages: () => ({ ...sessionMessages }),
733
+ getStreamSummary: () => streamSummary ? { ...streamSummary, phases: [...streamSummary.phases] } : undefined,
734
+ };
735
+
736
+ resolve(handle);
737
+ };
738
+
739
+ listen();
740
+ });
741
+ }
742
+
743
+ async function parseBody(
744
+ req: IncomingMessage,
745
+ res: ServerResponse,
746
+ ): Promise<UiProxyRequestBody<Record<string, unknown>> | null> {
747
+ try {
748
+ const body = await readBody(req);
749
+ if (!body || typeof body !== "object") {
750
+ sendJson(res, 400, { ok: false, error: "Invalid request body" });
751
+ return null;
752
+ }
753
+ return body as UiProxyRequestBody<Record<string, unknown>>;
754
+ } catch (error) {
755
+ sendJson(res, 400, { ok: false, error: error instanceof Error ? error.message : "Invalid body" });
756
+ return null;
757
+ }
758
+ }
759
+
760
+ function readBody(req: IncomingMessage): Promise<unknown> {
761
+ return new Promise((resolve, reject) => {
762
+ let size = 0;
763
+ const chunks: Buffer[] = [];
764
+
765
+ req.on("data", (chunk: Buffer) => {
766
+ size += chunk.length;
767
+ if (size > MAX_BODY_SIZE) {
768
+ req.destroy();
769
+ reject(new Error("Request body too large"));
770
+ return;
771
+ }
772
+ chunks.push(chunk);
773
+ });
774
+
775
+ req.on("end", () => {
776
+ try {
777
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
778
+ } catch (error) {
779
+ reject(error);
780
+ }
781
+ });
782
+
783
+ req.on("error", reject);
784
+ });
785
+ }
786
+
787
+ function resolvePortCandidates(port: number | undefined): number[] {
788
+ if (port !== undefined) return [port];
789
+ const candidates: number[] = [];
790
+ const count = MOSHI_DISCOVERY_PORT_END - MOSHI_DISCOVERY_PORT_START + 1;
791
+ for (let offset = 0; offset < count; offset += 1) {
792
+ const candidate = MOSHI_DISCOVERY_PORT_START + ((nextMoshiDiscoveryPort - MOSHI_DISCOVERY_PORT_START + offset) % count);
793
+ candidates.push(candidate);
794
+ }
795
+ candidates.push(0);
796
+ return candidates;
797
+ }
798
+
799
+ function rememberMoshiDiscoveryPort(port: number): void {
800
+ if (port < MOSHI_DISCOVERY_PORT_START || port > MOSHI_DISCOVERY_PORT_END) return;
801
+ nextMoshiDiscoveryPort = port >= MOSHI_DISCOVERY_PORT_END ? MOSHI_DISCOVERY_PORT_START : port + 1;
802
+ }
803
+
804
+ function isAllowedHost(hostname: string): boolean {
805
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
806
+ }
807
+
808
+ function validateTokenQuery(
809
+ url: URL,
810
+ expected: string,
811
+ res: ServerResponse,
812
+ parameter = "session",
813
+ ): boolean {
814
+ const token = url.searchParams.get(parameter);
815
+ if (token !== expected) {
816
+ sendJson(res, 403, { ok: false, error: "Invalid session" });
817
+ return false;
818
+ }
819
+ return true;
820
+ }
821
+
822
+ function validateTokenBody(
823
+ body: UiProxyRequestBody<Record<string, unknown>>,
824
+ expected: string,
825
+ res: ServerResponse,
826
+ ): boolean {
827
+ if (body.token !== expected) {
828
+ sendJson(res, 403, { ok: false, error: "Invalid session" });
829
+ return false;
830
+ }
831
+ return true;
832
+ }
833
+
834
+ function sendJson<T>(
835
+ res: ServerResponse,
836
+ status: number,
837
+ payload: UiProxyResult<T>,
838
+ ): void {
839
+ res.writeHead(status, {
840
+ "Content-Type": "application/json; charset=utf-8",
841
+ "Cache-Control": "no-store",
842
+ });
843
+ res.end(JSON.stringify(payload));
844
+ }
845
+
846
+ function sendText(res: ServerResponse, status: number, text: string): void {
847
+ res.writeHead(status, {
848
+ "Content-Type": "text/plain; charset=utf-8",
849
+ "Cache-Control": "no-store",
850
+ });
851
+ res.end(text);
852
+ }