@fitchmultz/pi-mcp-adapter 5.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.
- package/CHANGELOG.md +750 -0
- package/LICENSE +21 -0
- package/OAUTH.md +462 -0
- package/README.md +820 -0
- package/abort.ts +34 -0
- package/agent-dir.ts +24 -0
- package/app-bridge.bundle.js +67 -0
- package/banner.png +0 -0
- package/checkpoint.ts +55 -0
- package/cli.js +222 -0
- package/commands.ts +619 -0
- package/config.ts +1204 -0
- package/consent-manager.ts +25 -0
- package/direct-tools.ts +408 -0
- package/dist/abort.d.ts +2 -0
- package/dist/abort.js +35 -0
- package/dist/agent-dir.d.ts +3 -0
- package/dist/agent-dir.js +21 -0
- package/dist/app-bridge.bundle.js +67 -0
- package/dist/checkpoint.d.ts +18 -0
- package/dist/checkpoint.js +53 -0
- package/dist/commands.d.ts +20 -0
- package/dist/commands.js +521 -0
- package/dist/config.d.ts +109 -0
- package/dist/config.js +1013 -0
- package/dist/consent-manager.d.ts +8 -0
- package/dist/consent-manager.js +21 -0
- package/dist/direct-tools.d.ts +10 -0
- package/dist/direct-tools.js +350 -0
- package/dist/docs/client-metadata.json +14 -0
- package/dist/elicitation-handler.d.ts +17 -0
- package/dist/elicitation-handler.js +308 -0
- package/dist/error-signal.d.ts +15 -0
- package/dist/error-signal.js +21 -0
- package/dist/glimpse-ui.d.ts +9 -0
- package/dist/glimpse-ui.js +75 -0
- package/dist/host-html-template.d.ts +15 -0
- package/dist/host-html-template.js +429 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +840 -0
- package/dist/init.d.ts +25 -0
- package/dist/init.js +562 -0
- package/dist/legacy-migration.d.ts +18 -0
- package/dist/legacy-migration.js +45 -0
- package/dist/lifecycle.d.ts +40 -0
- package/dist/lifecycle.js +167 -0
- package/dist/logger.d.ts +38 -0
- package/dist/logger.js +102 -0
- package/dist/mcp-auth-flow.d.ts +113 -0
- package/dist/mcp-auth-flow.js +834 -0
- package/dist/mcp-auth.d.ts +127 -0
- package/dist/mcp-auth.js +658 -0
- package/dist/mcp-callback-server.d.ts +56 -0
- package/dist/mcp-callback-server.js +371 -0
- package/dist/mcp-code.d.ts +51 -0
- package/dist/mcp-code.js +366 -0
- package/dist/mcp-keyring-helper.cjs +89 -0
- package/dist/mcp-oauth-provider.d.ts +154 -0
- package/dist/mcp-oauth-provider.js +672 -0
- package/dist/mcp-output-guard.d.ts +59 -0
- package/dist/mcp-output-guard.js +332 -0
- package/dist/mcp-panel.d.ts +66 -0
- package/dist/mcp-panel.js +889 -0
- package/dist/mcp-script-worker.mjs +128 -0
- package/dist/mcp-setup-panel.d.ts +84 -0
- package/dist/mcp-setup-panel.js +561 -0
- package/dist/mcp-status.d.ts +11 -0
- package/dist/mcp-status.js +96 -0
- package/dist/mcp-trace.d.ts +95 -0
- package/dist/mcp-trace.js +233 -0
- package/dist/metadata-cache.d.ts +18 -0
- package/dist/metadata-cache.js +277 -0
- package/dist/npx-resolver.d.ts +6 -0
- package/dist/npx-resolver.js +448 -0
- package/dist/onboarding-state.d.ts +11 -0
- package/dist/onboarding-state.js +47 -0
- package/dist/panel-keys.d.ts +16 -0
- package/dist/panel-keys.js +15 -0
- package/dist/prompts.d.ts +56 -0
- package/dist/prompts.js +284 -0
- package/dist/proxy-modes.d.ts +38 -0
- package/dist/proxy-modes.js +1235 -0
- package/dist/resource-tools.d.ts +1 -0
- package/dist/resource-tools.js +14 -0
- package/dist/runtime-owner.d.ts +18 -0
- package/dist/runtime-owner.js +117 -0
- package/dist/sampling-handler.d.ts +15 -0
- package/dist/sampling-handler.js +211 -0
- package/dist/search-ranking.d.ts +20 -0
- package/dist/search-ranking.js +180 -0
- package/dist/server-manager.d.ts +114 -0
- package/dist/server-manager.js +1175 -0
- package/dist/session-recovery.d.ts +31 -0
- package/dist/session-recovery.js +310 -0
- package/dist/state.d.ts +63 -0
- package/dist/state.js +1 -0
- package/dist/tool-approval.d.ts +10 -0
- package/dist/tool-approval.js +42 -0
- package/dist/tool-metadata.d.ts +9 -0
- package/dist/tool-metadata.js +193 -0
- package/dist/tool-registrar.d.ts +10 -0
- package/dist/tool-registrar.js +64 -0
- package/dist/tool-result-renderer.d.ts +45 -0
- package/dist/tool-result-renderer.js +224 -0
- package/dist/ts-shape.d.ts +2 -0
- package/dist/ts-shape.js +147 -0
- package/dist/types.d.ts +516 -0
- package/dist/types.js +168 -0
- package/dist/ui-resource-handler.d.ts +17 -0
- package/dist/ui-resource-handler.js +209 -0
- package/dist/ui-server.d.ts +51 -0
- package/dist/ui-server.js +669 -0
- package/dist/ui-session.d.ts +39 -0
- package/dist/ui-session.js +463 -0
- package/dist/ui-stream-types.d.ts +104 -0
- package/dist/ui-stream-types.js +58 -0
- package/dist/ui-tool-visibility.d.ts +4 -0
- package/dist/ui-tool-visibility.js +26 -0
- package/dist/unix-socket-transport.d.ts +15 -0
- package/dist/unix-socket-transport.js +84 -0
- package/dist/utils.d.ts +30 -0
- package/dist/utils.js +276 -0
- package/docs/client-metadata.json +14 -0
- package/elicitation-handler.ts +349 -0
- package/error-signal.ts +21 -0
- package/glimpse-ui.ts +80 -0
- package/host-html-template.ts +456 -0
- package/index.ts +900 -0
- package/init.ts +627 -0
- package/legacy-migration.ts +47 -0
- package/lifecycle.ts +165 -0
- package/logger.ts +127 -0
- package/mcp-auth-flow.ts +975 -0
- package/mcp-auth.ts +793 -0
- package/mcp-callback-server.ts +450 -0
- package/mcp-code.ts +386 -0
- package/mcp-keyring-helper.cjs +89 -0
- package/mcp-oauth-provider.ts +774 -0
- package/mcp-output-guard.ts +412 -0
- package/mcp-panel.ts +978 -0
- package/mcp-script-worker.mjs +128 -0
- package/mcp-setup-panel.ts +666 -0
- package/mcp-status.ts +109 -0
- package/mcp-trace.ts +295 -0
- package/metadata-cache.ts +333 -0
- package/npx-resolver.ts +488 -0
- package/onboarding-state.ts +58 -0
- package/package.json +182 -0
- package/panel-keys.ts +37 -0
- package/prompts.ts +337 -0
- package/proxy-modes.ts +1361 -0
- package/resource-tools.ts +17 -0
- package/runtime-owner.ts +123 -0
- package/sampling-handler.ts +273 -0
- package/scripts/build.mjs +131 -0
- package/scripts/prepare.mjs +102 -0
- package/search-ranking.ts +196 -0
- package/server-manager.ts +1320 -0
- package/session-recovery.ts +316 -0
- package/skills/mcp-scripting/SKILL.md +38 -0
- package/state.ts +64 -0
- package/tool-approval.ts +78 -0
- package/tool-metadata.ts +235 -0
- package/tool-registrar.ts +69 -0
- package/tool-result-renderer.ts +286 -0
- package/ts-shape.ts +145 -0
- package/tsconfig.build.json +13 -0
- package/tsconfig.json +16 -0
- package/types.ts +810 -0
- package/ui-resource-handler.ts +249 -0
- package/ui-server.ts +808 -0
- package/ui-session.ts +568 -0
- package/ui-stream-types.ts +89 -0
- package/ui-tool-visibility.ts +25 -0
- package/unix-socket-transport.ts +85 -0
- package/utils.ts +309 -0
|
@@ -0,0 +1,669 @@
|
|
|
1
|
+
import http 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 "@modelcontextprotocol/ext-apps/app-bridge";
|
|
6
|
+
import { ContentBlockSchema } from "@modelcontextprotocol/core";
|
|
7
|
+
import { formatAuthRequiredMessage } from "./utils.js";
|
|
8
|
+
import { buildHostHtmlTemplate, buildCspMetaContent } from "./host-html-template.js";
|
|
9
|
+
import { logger } from "./logger.js";
|
|
10
|
+
import { SessionRecoveryAuthRequiredError, withSessionRecovery } from "./session-recovery.js";
|
|
11
|
+
import { ensureToolCallApproved, isToolCallApprovalRequired } from "./tool-approval.js";
|
|
12
|
+
import { extractUiToolVisibility, isUiToolCallableByApp } from "./ui-tool-visibility.js";
|
|
13
|
+
import { createUiModelContextUpdate, extractUiPromptText, getVisualizationStreamEnvelope, isServerDisabled, } from "./types.js";
|
|
14
|
+
const MAX_BODY_SIZE = 2 * 1024 * 1024;
|
|
15
|
+
const ABANDONED_GRACE_MS = 60_000;
|
|
16
|
+
const WATCHDOG_INTERVAL_MS = 5_000;
|
|
17
|
+
const MAX_EVENT_LOG = 128;
|
|
18
|
+
const MAX_CONTEXT_UPDATES = 20;
|
|
19
|
+
const MOSHI_DISCOVERY_PORT_START = 8377;
|
|
20
|
+
const MOSHI_DISCOVERY_PORT_END = 8396;
|
|
21
|
+
let nextMoshiDiscoveryPort = MOSHI_DISCOVERY_PORT_START;
|
|
22
|
+
export async function startUiServer(options) {
|
|
23
|
+
const sessionToken = options.sessionToken ?? randomUUID();
|
|
24
|
+
const uiResourceToken = randomUUID();
|
|
25
|
+
const log = logger.child({
|
|
26
|
+
component: "UiServer",
|
|
27
|
+
server: options.serverName,
|
|
28
|
+
tool: options.toolName,
|
|
29
|
+
session: sessionToken.slice(0, 8),
|
|
30
|
+
});
|
|
31
|
+
log.debug("Starting UI server");
|
|
32
|
+
const sseClients = new Set();
|
|
33
|
+
let completed = false;
|
|
34
|
+
let lastHeartbeatAt = Date.now();
|
|
35
|
+
let watchdog = null;
|
|
36
|
+
let currentDisplayMode = options.hostContext?.displayMode ?? "inline";
|
|
37
|
+
let nextEventId = 1;
|
|
38
|
+
const eventLog = [];
|
|
39
|
+
let streamSummary;
|
|
40
|
+
// Track messages from UI for retrieval
|
|
41
|
+
const sessionMessages = {
|
|
42
|
+
prompts: [],
|
|
43
|
+
notifications: [],
|
|
44
|
+
intents: [],
|
|
45
|
+
contexts: [],
|
|
46
|
+
};
|
|
47
|
+
const hostContext = {
|
|
48
|
+
displayMode: currentDisplayMode,
|
|
49
|
+
availableDisplayModes: ["inline", "fullscreen", "pip"],
|
|
50
|
+
platform: "desktop",
|
|
51
|
+
...options.hostContext,
|
|
52
|
+
// Only include toolInfo if caller provides full tool definition with inputSchema
|
|
53
|
+
// The App validates toolInfo.tool.inputSchema as required object
|
|
54
|
+
};
|
|
55
|
+
const initialStreamContext = hostContext["pi-mcp-adapter/stream"];
|
|
56
|
+
if (initialStreamContext && typeof initialStreamContext === "object") {
|
|
57
|
+
const streamId = initialStreamContext.streamId;
|
|
58
|
+
const mode = initialStreamContext.mode;
|
|
59
|
+
if (typeof streamId === "string" && (mode === "eager" || mode === "stream-first")) {
|
|
60
|
+
streamSummary = {
|
|
61
|
+
streamId,
|
|
62
|
+
mode,
|
|
63
|
+
frames: 0,
|
|
64
|
+
phases: [],
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const touchHeartbeat = () => {
|
|
69
|
+
lastHeartbeatAt = Date.now();
|
|
70
|
+
};
|
|
71
|
+
const updateStreamSummary = (payload) => {
|
|
72
|
+
const envelope = getVisualizationStreamEnvelope(payload?.structuredContent);
|
|
73
|
+
if (!envelope)
|
|
74
|
+
return;
|
|
75
|
+
if (!streamSummary) {
|
|
76
|
+
streamSummary = {
|
|
77
|
+
streamId: envelope.streamId,
|
|
78
|
+
mode: "eager",
|
|
79
|
+
frames: 0,
|
|
80
|
+
phases: [],
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
streamSummary.frames += 1;
|
|
84
|
+
if (!streamSummary.phases.includes(envelope.phase)) {
|
|
85
|
+
streamSummary.phases.push(envelope.phase);
|
|
86
|
+
}
|
|
87
|
+
streamSummary.finalStatus = envelope.status;
|
|
88
|
+
if (envelope.message !== undefined)
|
|
89
|
+
streamSummary.lastMessage = envelope.message;
|
|
90
|
+
else
|
|
91
|
+
delete streamSummary.lastMessage;
|
|
92
|
+
};
|
|
93
|
+
const serializeEvent = (eventId, name, payload) => {
|
|
94
|
+
return `id: ${eventId}\nevent: ${name}\ndata: ${JSON.stringify(payload)}\n\n`;
|
|
95
|
+
};
|
|
96
|
+
const getLatestCheckpointIndex = () => {
|
|
97
|
+
for (let index = eventLog.length - 1; index >= 0; index -= 1) {
|
|
98
|
+
const entry = eventLog[index];
|
|
99
|
+
if (!entry)
|
|
100
|
+
continue;
|
|
101
|
+
const envelope = getVisualizationStreamEnvelope(entry.payload?.structuredContent);
|
|
102
|
+
if (envelope?.frameType === "checkpoint" || envelope?.frameType === "final") {
|
|
103
|
+
return index;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return -1;
|
|
107
|
+
};
|
|
108
|
+
const pruneEventLog = () => {
|
|
109
|
+
if (eventLog.length <= MAX_EVENT_LOG)
|
|
110
|
+
return;
|
|
111
|
+
const latestCheckpointIndex = getLatestCheckpointIndex();
|
|
112
|
+
if (latestCheckpointIndex > 0) {
|
|
113
|
+
eventLog.splice(0, latestCheckpointIndex);
|
|
114
|
+
}
|
|
115
|
+
if (eventLog.length > MAX_EVENT_LOG) {
|
|
116
|
+
eventLog.splice(0, eventLog.length - MAX_EVENT_LOG);
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
const pushEvent = (name, payload) => {
|
|
120
|
+
if (completed)
|
|
121
|
+
return;
|
|
122
|
+
const eventId = nextEventId++;
|
|
123
|
+
eventLog.push({ id: eventId, name, payload });
|
|
124
|
+
updateStreamSummary(payload);
|
|
125
|
+
pruneEventLog();
|
|
126
|
+
const chunk = serializeEvent(eventId, name, payload);
|
|
127
|
+
for (const client of sseClients) {
|
|
128
|
+
try {
|
|
129
|
+
client.write(chunk);
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
sseClients.delete(client);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
const replayEvents = (res, lastEventIdHeader) => {
|
|
137
|
+
const parsedLastId = lastEventIdHeader ? Number(lastEventIdHeader) : Number.NaN;
|
|
138
|
+
const eventsToReplay = Number.isFinite(parsedLastId)
|
|
139
|
+
? eventLog.filter((entry) => entry.id > parsedLastId)
|
|
140
|
+
: (() => {
|
|
141
|
+
const latestCheckpointIndex = getLatestCheckpointIndex();
|
|
142
|
+
return latestCheckpointIndex >= 0 ? eventLog.slice(latestCheckpointIndex) : eventLog;
|
|
143
|
+
})();
|
|
144
|
+
for (const entry of eventsToReplay) {
|
|
145
|
+
try {
|
|
146
|
+
res.write(serializeEvent(entry.id, entry.name, entry.payload));
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
sseClients.delete(res);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
const closeSse = () => {
|
|
155
|
+
for (const client of sseClients) {
|
|
156
|
+
try {
|
|
157
|
+
client.end();
|
|
158
|
+
}
|
|
159
|
+
catch { }
|
|
160
|
+
}
|
|
161
|
+
sseClients.clear();
|
|
162
|
+
};
|
|
163
|
+
const stopWatchdog = () => {
|
|
164
|
+
if (!watchdog)
|
|
165
|
+
return;
|
|
166
|
+
clearInterval(watchdog);
|
|
167
|
+
watchdog = null;
|
|
168
|
+
};
|
|
169
|
+
const markCompleted = (reason) => {
|
|
170
|
+
if (completed)
|
|
171
|
+
return;
|
|
172
|
+
log.debug("Session completed", { reason });
|
|
173
|
+
pushEvent("session-complete", { reason });
|
|
174
|
+
completed = true;
|
|
175
|
+
stopWatchdog();
|
|
176
|
+
options.onComplete?.(reason);
|
|
177
|
+
};
|
|
178
|
+
const server = http.createServer(async (req, res) => {
|
|
179
|
+
try {
|
|
180
|
+
const method = req.method || "GET";
|
|
181
|
+
const hostHeader = req.headers.host;
|
|
182
|
+
const url = new URL(req.url || "/", `http://${hostHeader || "127.0.0.1"}`);
|
|
183
|
+
if (hostHeader !== undefined && !isAllowedHost(url.hostname)) {
|
|
184
|
+
sendText(res, 403, "Invalid host");
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (method === "HEAD" && url.pathname === "/") {
|
|
188
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
189
|
+
res.end();
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (method === "GET" && url.pathname === "/") {
|
|
193
|
+
if (!url.searchParams.has("session")) {
|
|
194
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
|
|
195
|
+
res.end("<!doctype html><html><head><meta charset=\"utf-8\"><title>MCP UI</title></head>" +
|
|
196
|
+
"<body><p>Open the authenticated MCP UI URL shown by Pi.</p></body></html>");
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (!validateTokenQuery(url, sessionToken, res))
|
|
200
|
+
return;
|
|
201
|
+
touchHeartbeat();
|
|
202
|
+
const html = buildHostHtmlTemplate({
|
|
203
|
+
sessionToken,
|
|
204
|
+
uiResourceToken,
|
|
205
|
+
serverName: options.serverName,
|
|
206
|
+
toolName: options.toolName,
|
|
207
|
+
toolArgs: options.toolArgs,
|
|
208
|
+
resource: options.resource,
|
|
209
|
+
allowAttribute: buildAllowAttribute(options.resource.meta.permissions),
|
|
210
|
+
requireToolConsent: options.consentManager.requiresPrompt(options.serverName),
|
|
211
|
+
hostContext,
|
|
212
|
+
});
|
|
213
|
+
res.writeHead(200, {
|
|
214
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
215
|
+
"Cache-Control": "no-store",
|
|
216
|
+
});
|
|
217
|
+
res.end(html);
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
if (method === "GET" && url.pathname === "/events") {
|
|
221
|
+
if (!validateTokenQuery(url, sessionToken, res))
|
|
222
|
+
return;
|
|
223
|
+
touchHeartbeat();
|
|
224
|
+
log.debug("SSE client connected", { clientCount: sseClients.size + 1 });
|
|
225
|
+
res.writeHead(200, {
|
|
226
|
+
"Content-Type": "text/event-stream",
|
|
227
|
+
"Cache-Control": "no-cache, no-transform",
|
|
228
|
+
Connection: "keep-alive",
|
|
229
|
+
"X-Accel-Buffering": "no",
|
|
230
|
+
});
|
|
231
|
+
res.write(": connected\n\n");
|
|
232
|
+
sseClients.add(res);
|
|
233
|
+
replayEvents(res, req.headers["last-event-id"] ? String(req.headers["last-event-id"]) : null);
|
|
234
|
+
req.on("close", () => {
|
|
235
|
+
sseClients.delete(res);
|
|
236
|
+
});
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
if (method === "GET" && url.pathname === "/health") {
|
|
240
|
+
if (!validateTokenQuery(url, sessionToken, res))
|
|
241
|
+
return;
|
|
242
|
+
sendJson(res, 200, { ok: true, result: { healthy: true } });
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
if (method === "GET" && url.pathname === "/ui-app") {
|
|
246
|
+
if (!validateTokenQuery(url, uiResourceToken, res, "resource"))
|
|
247
|
+
return;
|
|
248
|
+
touchHeartbeat();
|
|
249
|
+
// Enforce host metadata independently of where app HTML places its document head.
|
|
250
|
+
const cspContent = buildCspMetaContent(options.resource.meta.csp);
|
|
251
|
+
res.writeHead(200, {
|
|
252
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
253
|
+
"Cache-Control": "no-store",
|
|
254
|
+
"Content-Security-Policy": cspContent,
|
|
255
|
+
});
|
|
256
|
+
res.end(options.resource.html);
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
if (method === "GET" && url.pathname === "/app-bridge.bundle.js") {
|
|
260
|
+
// Serve the pre-bundled AppBridge module
|
|
261
|
+
const bundlePath = path.join(import.meta.dirname, "app-bridge.bundle.js");
|
|
262
|
+
try {
|
|
263
|
+
const content = await fs.readFile(bundlePath, "utf-8");
|
|
264
|
+
res.writeHead(200, {
|
|
265
|
+
"Content-Type": "application/javascript",
|
|
266
|
+
"Cache-Control": "public, max-age=31536000",
|
|
267
|
+
});
|
|
268
|
+
res.end(content);
|
|
269
|
+
}
|
|
270
|
+
catch {
|
|
271
|
+
sendJson(res, 500, { ok: false, error: "Bundle not found" });
|
|
272
|
+
}
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
if (method !== "POST") {
|
|
276
|
+
sendJson(res, 404, { ok: false, error: "Not found" });
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
const body = await parseBody(req, res);
|
|
280
|
+
if (!body)
|
|
281
|
+
return;
|
|
282
|
+
if (!validateTokenBody(body, sessionToken, res))
|
|
283
|
+
return;
|
|
284
|
+
const params = body.params ?? {};
|
|
285
|
+
touchHeartbeat();
|
|
286
|
+
if (url.pathname === "/proxy/tools/call") {
|
|
287
|
+
options.consentManager.ensureApproved(options.serverName);
|
|
288
|
+
const callParams = params;
|
|
289
|
+
if (!callParams || typeof callParams.name !== "string" || !callParams.name.trim()) {
|
|
290
|
+
sendJson(res, 400, { ok: false, error: "Invalid tools/call params" });
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
const connection = options.manager.getConnection(options.serverName);
|
|
294
|
+
if (!connection || connection.status !== "connected") {
|
|
295
|
+
sendJson(res, 503, { ok: false, error: `Server "${options.serverName}" is not connected` });
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
if (isServerDisabled(options.config?.mcpServers[options.serverName]) || isServerDisabled(connection.definition)) {
|
|
299
|
+
sendJson(res, 503, { ok: false, error: `Server "${options.serverName}" is disabled` });
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
const toolDefinitions = Array.isArray(connection.tools) ? connection.tools : [];
|
|
303
|
+
const toolDefinition = toolDefinitions.find((tool) => tool.name === callParams.name);
|
|
304
|
+
if (!toolDefinition) {
|
|
305
|
+
sendJson(res, 403, { ok: false, error: `MCP tool "${callParams.name}" is not callable by apps` });
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
const uiVisibility = extractUiToolVisibility(toolDefinition._meta);
|
|
309
|
+
if (!isUiToolCallableByApp(uiVisibility)) {
|
|
310
|
+
sendJson(res, 403, { ok: false, error: `MCP tool "${callParams.name}" is not callable by apps` });
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
const callArgs = {
|
|
314
|
+
name: callParams.name,
|
|
315
|
+
arguments: callParams.arguments && typeof callParams.arguments === "object" && !Array.isArray(callParams.arguments)
|
|
316
|
+
? callParams.arguments
|
|
317
|
+
: {},
|
|
318
|
+
};
|
|
319
|
+
const toolMeta = {
|
|
320
|
+
name: callParams.name,
|
|
321
|
+
originalName: callParams.name,
|
|
322
|
+
description: toolDefinition?.description ?? "",
|
|
323
|
+
...(toolDefinition?.inputSchema !== undefined ? { inputSchema: toolDefinition.inputSchema } : {}),
|
|
324
|
+
...(uiVisibility !== undefined ? { uiVisibility } : {}),
|
|
325
|
+
};
|
|
326
|
+
const approval = options.state
|
|
327
|
+
? await ensureToolCallApproved(options.state, options.serverName, toolMeta, callArgs.arguments, options.state.owner?.signal)
|
|
328
|
+
: options.config && isToolCallApprovalRequired(options.config, options.serverName, toolMeta)
|
|
329
|
+
? { ok: false, reason: "approval_required_headless" }
|
|
330
|
+
: { ok: true };
|
|
331
|
+
if (approval.ok === false) {
|
|
332
|
+
const denied = approval.reason === "denied";
|
|
333
|
+
const message = denied
|
|
334
|
+
? `The user declined approval to run MCP tool "${callParams.name}" on server "${options.serverName}".`
|
|
335
|
+
: `MCP tool "${callParams.name}" on server "${options.serverName}" is approval-gated and requires an interactive session.`;
|
|
336
|
+
sendJson(res, 200, {
|
|
337
|
+
ok: true,
|
|
338
|
+
result: {
|
|
339
|
+
content: [{ type: "text", text: message }],
|
|
340
|
+
details: {
|
|
341
|
+
error: denied ? "approval_denied" : "approval_required",
|
|
342
|
+
server: options.serverName,
|
|
343
|
+
tool: callParams.name,
|
|
344
|
+
},
|
|
345
|
+
},
|
|
346
|
+
});
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
try {
|
|
350
|
+
options.manager.touch(options.serverName);
|
|
351
|
+
options.manager.incrementInFlight(options.serverName);
|
|
352
|
+
const result = options.config
|
|
353
|
+
? await withSessionRecovery({
|
|
354
|
+
manager: options.manager,
|
|
355
|
+
config: options.config,
|
|
356
|
+
...(options.onNeedsAuth ? { onNeedsAuth: options.onNeedsAuth } : {}),
|
|
357
|
+
}, options.serverName, (conn) => conn.client.callTool(callArgs, options.manager.getRequestOptions?.(options.serverName)))
|
|
358
|
+
: await connection.client.callTool(callArgs, options.manager.getRequestOptions?.(options.serverName));
|
|
359
|
+
sendJson(res, 200, { ok: true, result });
|
|
360
|
+
}
|
|
361
|
+
finally {
|
|
362
|
+
options.manager.decrementInFlight(options.serverName);
|
|
363
|
+
options.manager.touch(options.serverName);
|
|
364
|
+
}
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
if (url.pathname === "/proxy/ui/consent") {
|
|
368
|
+
const approved = !!params.approved;
|
|
369
|
+
options.consentManager.registerDecision(options.serverName, approved);
|
|
370
|
+
sendJson(res, 200, { ok: true, result: { approved } });
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
if (url.pathname === "/proxy/ui/message") {
|
|
374
|
+
const msgParams = params;
|
|
375
|
+
const promptText = extractUiPromptText(msgParams);
|
|
376
|
+
// Track messages by type (order: prompt → intent → notify)
|
|
377
|
+
// Must match the order in index.ts onMessage handler
|
|
378
|
+
if (promptText) {
|
|
379
|
+
sessionMessages.prompts.push(promptText);
|
|
380
|
+
log.debug("UI prompt received", { prompt: promptText.slice(0, 100) });
|
|
381
|
+
}
|
|
382
|
+
else if (msgParams.type === "intent" || msgParams.intent) {
|
|
383
|
+
const intentName = msgParams.intent ?? "";
|
|
384
|
+
if (intentName) {
|
|
385
|
+
sessionMessages.intents.push({
|
|
386
|
+
intent: intentName,
|
|
387
|
+
...(msgParams.params !== undefined ? { params: msgParams.params } : {}),
|
|
388
|
+
});
|
|
389
|
+
log.debug("UI intent received", { intent: intentName });
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
else if (msgParams.type === "notify" || msgParams.message) {
|
|
393
|
+
const notifyText = msgParams.message ?? "";
|
|
394
|
+
if (notifyText) {
|
|
395
|
+
sessionMessages.notifications.push(notifyText);
|
|
396
|
+
log.debug("UI notification", { message: notifyText.slice(0, 100) });
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
await options.onMessage?.(msgParams);
|
|
400
|
+
sendJson(res, 200, { ok: true, result: {} });
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
if (url.pathname === "/proxy/ui/context") {
|
|
404
|
+
const content = params.content;
|
|
405
|
+
const structuredContent = params.structuredContent;
|
|
406
|
+
if ((content !== undefined && (!Array.isArray(content) || content.some((block) => !ContentBlockSchema.safeParse(block).success))) ||
|
|
407
|
+
(structuredContent !== undefined && (!structuredContent || typeof structuredContent !== "object" || Array.isArray(structuredContent)))) {
|
|
408
|
+
sendJson(res, 400, { ok: false, error: "Invalid update-model-context params" });
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
const ctxParams = {
|
|
412
|
+
...(content !== undefined ? { content: content } : {}),
|
|
413
|
+
...(structuredContent !== undefined ? { structuredContent: structuredContent } : {}),
|
|
414
|
+
};
|
|
415
|
+
const update = createUiModelContextUpdate(ctxParams);
|
|
416
|
+
if (update) {
|
|
417
|
+
sessionMessages.contexts.push(update);
|
|
418
|
+
while (sessionMessages.contexts.length > MAX_CONTEXT_UPDATES) {
|
|
419
|
+
sessionMessages.contexts.shift();
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
log.debug("UI context update", { hasContent: !!ctxParams.content, hasUpdate: !!update });
|
|
423
|
+
await options.onContextUpdate?.(ctxParams);
|
|
424
|
+
sendJson(res, 200, { ok: true, result: {} });
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
if (url.pathname === "/proxy/ui/open-link") {
|
|
428
|
+
const openParams = params;
|
|
429
|
+
if (!openParams?.url || typeof openParams.url !== "string") {
|
|
430
|
+
sendJson(res, 400, { ok: false, error: "Invalid open-link params" });
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
let result = {};
|
|
434
|
+
try {
|
|
435
|
+
new URL(openParams.url);
|
|
436
|
+
}
|
|
437
|
+
catch {
|
|
438
|
+
result = { isError: true };
|
|
439
|
+
}
|
|
440
|
+
sendJson(res, 200, { ok: true, result });
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
if (url.pathname === "/proxy/ui/download-file") {
|
|
444
|
+
sendJson(res, 200, { ok: true, result: { isError: true } });
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
if (url.pathname === "/proxy/ui/request-display-mode") {
|
|
448
|
+
const displayParams = params;
|
|
449
|
+
const requested = displayParams?.mode;
|
|
450
|
+
const available = hostContext.availableDisplayModes ?? ["inline"];
|
|
451
|
+
if (requested && available.includes(requested)) {
|
|
452
|
+
currentDisplayMode = requested;
|
|
453
|
+
}
|
|
454
|
+
hostContext.displayMode = currentDisplayMode;
|
|
455
|
+
pushEvent("host-context", { displayMode: currentDisplayMode });
|
|
456
|
+
const result = { mode: currentDisplayMode };
|
|
457
|
+
sendJson(res, 200, { ok: true, result });
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
if (url.pathname === "/proxy/ui/heartbeat") {
|
|
461
|
+
sendJson(res, 200, { ok: true, result: {} });
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
if (url.pathname === "/proxy/ui/complete") {
|
|
465
|
+
const reason = typeof params.reason === "string"
|
|
466
|
+
? params.reason
|
|
467
|
+
: "done";
|
|
468
|
+
markCompleted(reason);
|
|
469
|
+
sendJson(res, 200, { ok: true, result: {} });
|
|
470
|
+
setTimeout(() => {
|
|
471
|
+
try {
|
|
472
|
+
server.close();
|
|
473
|
+
}
|
|
474
|
+
catch { }
|
|
475
|
+
closeSse();
|
|
476
|
+
}, 20).unref();
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
sendJson(res, 404, { ok: false, error: "Not found" });
|
|
480
|
+
}
|
|
481
|
+
catch (error) {
|
|
482
|
+
if (error instanceof SessionRecoveryAuthRequiredError) {
|
|
483
|
+
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.`;
|
|
484
|
+
const message = error.authMessage ?? (options.config
|
|
485
|
+
? formatAuthRequiredMessage(options.config, options.serverName, fallback)
|
|
486
|
+
: fallback);
|
|
487
|
+
sendJson(res, 401, { ok: false, error: message });
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
491
|
+
const status = /approval required|denied/i.test(message) ? 403 : 500;
|
|
492
|
+
if (status === 500) {
|
|
493
|
+
log.error("Request handler error", error instanceof Error ? error : undefined);
|
|
494
|
+
}
|
|
495
|
+
sendJson(res, status, { ok: false, error: message });
|
|
496
|
+
}
|
|
497
|
+
});
|
|
498
|
+
if (options.initialResultPromise) {
|
|
499
|
+
options.initialResultPromise.then((result) => pushEvent("tool-result", result), (error) => {
|
|
500
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
501
|
+
pushEvent("tool-cancelled", { reason });
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
watchdog = setInterval(() => {
|
|
505
|
+
if (completed)
|
|
506
|
+
return;
|
|
507
|
+
if (Date.now() - lastHeartbeatAt <= ABANDONED_GRACE_MS)
|
|
508
|
+
return;
|
|
509
|
+
markCompleted("stale");
|
|
510
|
+
try {
|
|
511
|
+
server.close();
|
|
512
|
+
}
|
|
513
|
+
catch { }
|
|
514
|
+
closeSse();
|
|
515
|
+
}, WATCHDOG_INTERVAL_MS);
|
|
516
|
+
watchdog.unref();
|
|
517
|
+
return new Promise((resolve, reject) => {
|
|
518
|
+
const candidates = resolvePortCandidates(options.port);
|
|
519
|
+
let candidateIndex = 0;
|
|
520
|
+
const listen = () => {
|
|
521
|
+
server.once("error", onError);
|
|
522
|
+
server.listen(candidates[candidateIndex], "127.0.0.1", onListening);
|
|
523
|
+
};
|
|
524
|
+
const onError = (error) => {
|
|
525
|
+
server.off("listening", onListening);
|
|
526
|
+
if (error.code === "EADDRINUSE" && candidateIndex < candidates.length - 1) {
|
|
527
|
+
candidateIndex += 1;
|
|
528
|
+
listen();
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
log.error("Failed to start server", error);
|
|
532
|
+
reject(new Error(`UI server error: ${error.message}`, { cause: error }));
|
|
533
|
+
};
|
|
534
|
+
const onListening = () => {
|
|
535
|
+
server.off("error", onError);
|
|
536
|
+
const address = server.address();
|
|
537
|
+
if (!address || typeof address === "string") {
|
|
538
|
+
const err = new Error("UI server error: invalid address");
|
|
539
|
+
log.error("Invalid server address", err);
|
|
540
|
+
reject(err);
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
log.debug("Server started", { port: address.port });
|
|
544
|
+
rememberMoshiDiscoveryPort(address.port);
|
|
545
|
+
const handle = {
|
|
546
|
+
url: `http://localhost:${address.port}/?session=${sessionToken}`,
|
|
547
|
+
port: address.port,
|
|
548
|
+
sessionToken,
|
|
549
|
+
serverName: options.serverName,
|
|
550
|
+
toolName: options.toolName,
|
|
551
|
+
close: (reason) => {
|
|
552
|
+
markCompleted(reason ?? "closed");
|
|
553
|
+
try {
|
|
554
|
+
server.close();
|
|
555
|
+
}
|
|
556
|
+
catch { }
|
|
557
|
+
closeSse();
|
|
558
|
+
},
|
|
559
|
+
sendToolInput: (args) => {
|
|
560
|
+
pushEvent("tool-input", { arguments: args });
|
|
561
|
+
},
|
|
562
|
+
sendToolResult: (result) => {
|
|
563
|
+
pushEvent("tool-result", result);
|
|
564
|
+
},
|
|
565
|
+
sendResultPatch: (result) => {
|
|
566
|
+
pushEvent("result-patch", result);
|
|
567
|
+
},
|
|
568
|
+
sendToolCancelled: (reason) => {
|
|
569
|
+
pushEvent("tool-cancelled", { reason });
|
|
570
|
+
},
|
|
571
|
+
sendHostContext: (context) => {
|
|
572
|
+
Object.assign(hostContext, context);
|
|
573
|
+
pushEvent("host-context", context);
|
|
574
|
+
},
|
|
575
|
+
getSessionMessages: () => ({ ...sessionMessages }),
|
|
576
|
+
getStreamSummary: () => streamSummary ? { ...streamSummary, phases: [...streamSummary.phases] } : undefined,
|
|
577
|
+
};
|
|
578
|
+
resolve(handle);
|
|
579
|
+
};
|
|
580
|
+
listen();
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
async function parseBody(req, res) {
|
|
584
|
+
try {
|
|
585
|
+
const body = await readBody(req);
|
|
586
|
+
if (!body || typeof body !== "object") {
|
|
587
|
+
sendJson(res, 400, { ok: false, error: "Invalid request body" });
|
|
588
|
+
return null;
|
|
589
|
+
}
|
|
590
|
+
return body;
|
|
591
|
+
}
|
|
592
|
+
catch (error) {
|
|
593
|
+
sendJson(res, 400, { ok: false, error: error instanceof Error ? error.message : "Invalid body" });
|
|
594
|
+
return null;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
function readBody(req) {
|
|
598
|
+
return new Promise((resolve, reject) => {
|
|
599
|
+
let size = 0;
|
|
600
|
+
const chunks = [];
|
|
601
|
+
req.on("data", (chunk) => {
|
|
602
|
+
size += chunk.length;
|
|
603
|
+
if (size > MAX_BODY_SIZE) {
|
|
604
|
+
req.destroy();
|
|
605
|
+
reject(new Error("Request body too large"));
|
|
606
|
+
return;
|
|
607
|
+
}
|
|
608
|
+
chunks.push(chunk);
|
|
609
|
+
});
|
|
610
|
+
req.on("end", () => {
|
|
611
|
+
try {
|
|
612
|
+
resolve(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
|
|
613
|
+
}
|
|
614
|
+
catch (error) {
|
|
615
|
+
reject(error);
|
|
616
|
+
}
|
|
617
|
+
});
|
|
618
|
+
req.on("error", reject);
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
function resolvePortCandidates(port) {
|
|
622
|
+
if (port !== undefined)
|
|
623
|
+
return [port];
|
|
624
|
+
const candidates = [];
|
|
625
|
+
const count = MOSHI_DISCOVERY_PORT_END - MOSHI_DISCOVERY_PORT_START + 1;
|
|
626
|
+
for (let offset = 0; offset < count; offset += 1) {
|
|
627
|
+
const candidate = MOSHI_DISCOVERY_PORT_START + ((nextMoshiDiscoveryPort - MOSHI_DISCOVERY_PORT_START + offset) % count);
|
|
628
|
+
candidates.push(candidate);
|
|
629
|
+
}
|
|
630
|
+
candidates.push(0);
|
|
631
|
+
return candidates;
|
|
632
|
+
}
|
|
633
|
+
function rememberMoshiDiscoveryPort(port) {
|
|
634
|
+
if (port < MOSHI_DISCOVERY_PORT_START || port > MOSHI_DISCOVERY_PORT_END)
|
|
635
|
+
return;
|
|
636
|
+
nextMoshiDiscoveryPort = port >= MOSHI_DISCOVERY_PORT_END ? MOSHI_DISCOVERY_PORT_START : port + 1;
|
|
637
|
+
}
|
|
638
|
+
function isAllowedHost(hostname) {
|
|
639
|
+
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
|
|
640
|
+
}
|
|
641
|
+
function validateTokenQuery(url, expected, res, parameter = "session") {
|
|
642
|
+
const token = url.searchParams.get(parameter);
|
|
643
|
+
if (token !== expected) {
|
|
644
|
+
sendJson(res, 403, { ok: false, error: "Invalid session" });
|
|
645
|
+
return false;
|
|
646
|
+
}
|
|
647
|
+
return true;
|
|
648
|
+
}
|
|
649
|
+
function validateTokenBody(body, expected, res) {
|
|
650
|
+
if (body.token !== expected) {
|
|
651
|
+
sendJson(res, 403, { ok: false, error: "Invalid session" });
|
|
652
|
+
return false;
|
|
653
|
+
}
|
|
654
|
+
return true;
|
|
655
|
+
}
|
|
656
|
+
function sendJson(res, status, payload) {
|
|
657
|
+
res.writeHead(status, {
|
|
658
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
659
|
+
"Cache-Control": "no-store",
|
|
660
|
+
});
|
|
661
|
+
res.end(JSON.stringify(payload));
|
|
662
|
+
}
|
|
663
|
+
function sendText(res, status, text) {
|
|
664
|
+
res.writeHead(status, {
|
|
665
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
666
|
+
"Cache-Control": "no-store",
|
|
667
|
+
});
|
|
668
|
+
res.end(text);
|
|
669
|
+
}
|