@ant0/mcp 0.0.0-stage → 0.3.22-beta.8

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 (54) hide show
  1. package/LICENSE +28 -0
  2. package/README.md +95 -2
  3. package/THIRD_PARTY_NOTICES +311 -0
  4. package/dist/api/generated/schema.d.ts +7340 -0
  5. package/dist/api/generated/schema.js +6 -0
  6. package/dist/api/index.d.ts +171 -0
  7. package/dist/api/index.js +332 -0
  8. package/dist/bin.d.ts +3 -0
  9. package/dist/bin.js +59 -0
  10. package/dist/call-permits.d.ts +10 -0
  11. package/dist/call-permits.js +67 -0
  12. package/dist/connection.d.ts +20 -0
  13. package/dist/connection.js +157 -0
  14. package/dist/credential-file.d.ts +33 -0
  15. package/dist/credential-file.js +773 -0
  16. package/dist/daemon.d.ts +7 -0
  17. package/dist/daemon.js +306 -0
  18. package/dist/errors.d.ts +92 -0
  19. package/dist/errors.js +101 -0
  20. package/dist/export-files.d.ts +37 -0
  21. package/dist/export-files.js +167 -0
  22. package/dist/grant.d.ts +5 -0
  23. package/dist/grant.js +11 -0
  24. package/dist/http-local.d.ts +38 -0
  25. package/dist/http-local.js +324 -0
  26. package/dist/http.d.ts +66 -0
  27. package/dist/http.js +556 -0
  28. package/dist/index.d.ts +21 -0
  29. package/dist/index.js +86 -0
  30. package/dist/key-contract.d.ts +325 -0
  31. package/dist/key-contract.js +241 -0
  32. package/dist/limits.d.ts +22 -0
  33. package/dist/limits.js +22 -0
  34. package/dist/local-routes.d.ts +30 -0
  35. package/dist/local-routes.js +231 -0
  36. package/dist/output-descriptor.d.ts +3 -0
  37. package/dist/output-descriptor.js +19 -0
  38. package/dist/output-worker-body.d.ts +3 -0
  39. package/dist/output-worker-body.js +77 -0
  40. package/dist/output-worker.d.ts +2 -0
  41. package/dist/output-worker.js +4 -0
  42. package/dist/output-writer.d.ts +39 -0
  43. package/dist/output-writer.js +199 -0
  44. package/dist/peer-watchdog.d.ts +4 -0
  45. package/dist/peer-watchdog.js +55 -0
  46. package/dist/server.d.ts +28 -0
  47. package/dist/server.js +33 -0
  48. package/dist/text-budget.d.ts +13 -0
  49. package/dist/text-budget.js +42 -0
  50. package/dist/tools.d.ts +39 -0
  51. package/dist/tools.js +1893 -0
  52. package/dist/transport.d.ts +45 -0
  53. package/dist/transport.js +313 -0
  54. package/package.json +66 -4
package/dist/http.js ADDED
@@ -0,0 +1,556 @@
1
+ import { createServer } from "node:http";
2
+ import { createRemoteJWKSet, decodeJwt, jwtVerify } from "jose";
3
+ import { OAuthError, OAuthErrorCode, bearerAuthChallengeResponse, createMcpHandler, getOAuthProtectedResourceMetadataUrl, hostHeaderValidationResponse, requireBearerAuth, } from "@modelcontextprotocol/server";
4
+ import { resolveHome } from "./api/index.js";
5
+ import { CallPermits } from "./call-permits.js";
6
+ import { discoverConnection, keyMode } from "./connection.js";
7
+ import { daemonClient } from "./daemon.js";
8
+ import { McpFailure, safeFailure } from "./errors.js";
9
+ import { startExportSweeper } from "./export-files.js";
10
+ import { resolveGrant } from "./grant.js";
11
+ import { buildServer } from "./server.js";
12
+ import { toolScope, toolsForCredential } from "./tools.js";
13
+ import { MODERN_VERSIONS } from "./transport.js";
14
+ /** OAuth scopes this resource server understands. Nothing else widens or changes the tool set. */
15
+ export const HTTP_SCOPE_READ = "ant0.read";
16
+ export const HTTP_SCOPE_RUN = "ant0.run";
17
+ export const HTTP_SCOPES = [HTTP_SCOPE_READ, HTTP_SCOPE_RUN];
18
+ /**
19
+ * The tools one token scope may reach, before intersecting with the key's own grant:
20
+ * `ant0.read` is every key read tool (status, licence, profiles, sessions, proxies) and
21
+ * `ant0.run` is profile_run and profile_stop. No scope reaches a local-only tool.
22
+ */
23
+ export function toolsForHttpScope(scope) {
24
+ const wanted = scope === HTTP_SCOPE_READ
25
+ ? (keyScope) => keyScope.endsWith(":read")
26
+ : scope === HTTP_SCOPE_RUN
27
+ ? (keyScope) => keyScope === "profiles:run" || keyScope === "profiles:stop"
28
+ : () => false;
29
+ return toolsForCredential()
30
+ .map((tool) => tool.name)
31
+ .filter((name) => {
32
+ const keyScope = toolScope(name);
33
+ return keyScope !== undefined && keyScope !== "local" && wanted(keyScope);
34
+ });
35
+ }
36
+ const DEFAULT_PORT = 27180;
37
+ export const MAX_TOKEN_CHARS = 8192;
38
+ const ALGORITHMS = [
39
+ "RS256",
40
+ "RS384",
41
+ "RS512",
42
+ "PS256",
43
+ "PS384",
44
+ "PS512",
45
+ "ES256",
46
+ "ES384",
47
+ "ES512",
48
+ "EdDSA",
49
+ ];
50
+ const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
51
+ function refuse(reason) {
52
+ // The reason goes to stderr (never a protocol stream); the thrown failure stays fixed.
53
+ process.stderr.write(`ant0-mcp: ${reason}\n`);
54
+ throw new McpFailure("configuration");
55
+ }
56
+ function loopbackHost(host) {
57
+ return LOOPBACK_HOSTS.has(host) || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host);
58
+ }
59
+ function csv(value) {
60
+ return (value ?? "")
61
+ .split(",")
62
+ .map((part) => part.trim())
63
+ .filter(Boolean);
64
+ }
65
+ /**
66
+ * HTTP options from the environment, or undefined unless `ANT0_MCP_HTTP=1`.
67
+ * ANT0_MCP_HTTP_HOST / ANT0_MCP_HTTP_PORT (default 127.0.0.1:27180),
68
+ * ANT0_MCP_HTTP_ALLOW_NON_LOOPBACK=1, ANT0_MCP_RESOURCE (canonical resource URL),
69
+ * ANT0_MCP_AUTH_ISSUERS and ANT0_MCP_AUTH_JWKS_URLS (comma lists, same length, paired by
70
+ * position), ANT0_MCP_ALLOWED_ORIGINS (comma list of full origins, e.g. https://app.example.test).
71
+ */
72
+ export function httpOptionsFromEnv(env = process.env) {
73
+ if (env.ANT0_MCP_HTTP !== "1")
74
+ return undefined;
75
+ const issuers = csv(env.ANT0_MCP_AUTH_ISSUERS);
76
+ const jwks = csv(env.ANT0_MCP_AUTH_JWKS_URLS);
77
+ if (issuers.length !== jwks.length)
78
+ refuse("ANT0_MCP_AUTH_ISSUERS and ANT0_MCP_AUTH_JWKS_URLS must pair up");
79
+ const port = env.ANT0_MCP_HTTP_PORT;
80
+ if (port !== undefined && !/^[1-9]\d{0,4}$/.test(port))
81
+ refuse("invalid ANT0_MCP_HTTP_PORT");
82
+ return {
83
+ env,
84
+ ...(env.ANT0_MCP_HTTP_HOST !== undefined ? { host: env.ANT0_MCP_HTTP_HOST } : {}),
85
+ ...(port !== undefined ? { listenPort: Number(port) } : {}),
86
+ allowNonLoopback: env.ANT0_MCP_HTTP_ALLOW_NON_LOOPBACK === "1",
87
+ resource: env.ANT0_MCP_RESOURCE ?? "",
88
+ authorizationServers: issuers.map((issuer, index) => ({ issuer, jwksUrl: jwks[index] })),
89
+ allowedOrigins: csv(env.ANT0_MCP_ALLOWED_ORIGINS),
90
+ };
91
+ }
92
+ /** Normalized origins from the configured list; anything but a bare http(s) origin is refused. */
93
+ function parseOrigins(entries) {
94
+ const origins = new Set();
95
+ for (const entry of entries) {
96
+ let url;
97
+ try {
98
+ url = new URL(entry);
99
+ }
100
+ catch {
101
+ return refuse("ANT0_MCP_ALLOWED_ORIGINS entries must be full origins such as https://host");
102
+ }
103
+ if ((url.protocol !== "https:" && url.protocol !== "http:") ||
104
+ url.pathname !== "/" ||
105
+ url.search ||
106
+ url.hash ||
107
+ url.username ||
108
+ url.password)
109
+ refuse("ANT0_MCP_ALLOWED_ORIGINS entries must be full origins such as https://host");
110
+ origins.add(url.origin);
111
+ }
112
+ return origins;
113
+ }
114
+ /** True when an Origin header names exactly one allowed origin (scheme, host and port). */
115
+ function originAllowed(header, allowed) {
116
+ try {
117
+ const url = new URL(header);
118
+ return url.origin === header && allowed.has(url.origin);
119
+ }
120
+ catch {
121
+ return false;
122
+ }
123
+ }
124
+ /** Same sanitizing as the stdio transport: fixed text, a code from the known set, no SDK data. */
125
+ function sanitizeMessage(value) {
126
+ if (Array.isArray(value))
127
+ return value.map(sanitizeMessage);
128
+ if (typeof value !== "object" || value === null || !("error" in value))
129
+ return value;
130
+ const { id, error } = value;
131
+ const code = [-32700, -32600, -32601, -32602, -32603, -32000, -32020, -32021, -32022].includes(error?.code)
132
+ ? error.code
133
+ : -32603;
134
+ return {
135
+ jsonrpc: "2.0",
136
+ id: id ?? null,
137
+ error: {
138
+ code,
139
+ message: code === -32000 ? "Too many concurrent calls" : "MCP request rejected",
140
+ ...(code === -32022 ? { data: { supported: [...MODERN_VERSIONS] } } : {}),
141
+ },
142
+ };
143
+ }
144
+ function sanitizeJsonText(text) {
145
+ try {
146
+ return JSON.stringify(sanitizeMessage(JSON.parse(text)));
147
+ }
148
+ catch {
149
+ return text;
150
+ }
151
+ }
152
+ /** Rewrites every JSON-RPC error in a JSON or SSE response; results and other bodies pass. */
153
+ export async function sanitizeResponse(response) {
154
+ const type = response.headers.get("content-type") ?? "";
155
+ const headers = new Headers(response.headers);
156
+ headers.delete("content-length");
157
+ if (type.includes("application/json")) {
158
+ const text = await response.text();
159
+ return new Response(sanitizeJsonText(text), { status: response.status, headers });
160
+ }
161
+ if (type.includes("text/event-stream") && response.body) {
162
+ const decoder = new TextDecoder();
163
+ const encoder = new TextEncoder();
164
+ let pending = "";
165
+ const line = (raw) => raw.startsWith("data:") ? `data: ${sanitizeJsonText(raw.slice(5).trim())}` : raw;
166
+ const body = response.body.pipeThrough(new TransformStream({
167
+ transform(chunk, controller) {
168
+ pending += decoder.decode(chunk, { stream: true });
169
+ const lines = pending.split("\n");
170
+ pending = lines.pop() ?? "";
171
+ if (lines.length > 0)
172
+ controller.enqueue(encoder.encode(lines.map(line).join("\n") + "\n"));
173
+ },
174
+ flush(controller) {
175
+ if (pending)
176
+ controller.enqueue(encoder.encode(line(pending)));
177
+ },
178
+ }));
179
+ return new Response(body, { status: response.status, headers });
180
+ }
181
+ return response;
182
+ }
183
+ function strippedResource(url) {
184
+ const copy = new URL(url.href);
185
+ copy.hash = "";
186
+ return copy.href.replace(/\/$/, "");
187
+ }
188
+ function parseResource(value) {
189
+ let url;
190
+ try {
191
+ url = new URL(value);
192
+ }
193
+ catch {
194
+ return refuse("ANT0_MCP_RESOURCE must be the canonical https URL of this endpoint");
195
+ }
196
+ const local = loopbackHost(url.hostname);
197
+ if ((url.protocol !== "https:" && !(url.protocol === "http:" && local)) ||
198
+ url.hash ||
199
+ url.search ||
200
+ url.username ||
201
+ url.password)
202
+ refuse("the resource URL must be https (http only on loopback) with no query or fragment");
203
+ return url;
204
+ }
205
+ function parseIssuer(server) {
206
+ let issuer;
207
+ let jwks;
208
+ try {
209
+ issuer = new URL(server.issuer);
210
+ jwks = new URL(server.jwksUrl);
211
+ }
212
+ catch {
213
+ return refuse("an authorization server issuer or JWKS URL is not a URL");
214
+ }
215
+ for (const url of [issuer, jwks])
216
+ if ((url.protocol !== "https:" && !(url.protocol === "http:" && loopbackHost(url.hostname))) ||
217
+ url.hash ||
218
+ url.username ||
219
+ url.password)
220
+ refuse("authorization server URLs must be https (http only on loopback)");
221
+ // Compare issuers exactly as configured; the value is what the token's iss must equal.
222
+ return { issuer: server.issuer, jwks };
223
+ }
224
+ /** Verifies a JWT access token against the configured issuers' JWKS. Never forwards the token. */
225
+ function jwtVerifier(issuers, resource) {
226
+ const keys = new Map(issuers.map(({ issuer, jwks }) => [
227
+ issuer,
228
+ createRemoteJWKSet(jwks, {
229
+ timeoutDuration: 5000,
230
+ cooldownDuration: 30_000,
231
+ cacheMaxAge: 600_000,
232
+ }),
233
+ ]));
234
+ const canonical = strippedResource(resource);
235
+ const invalid = () => new OAuthError(OAuthErrorCode.InvalidToken, "Invalid access token");
236
+ return {
237
+ async verifyAccessToken(token) {
238
+ if (token.length > MAX_TOKEN_CHARS)
239
+ throw invalid();
240
+ try {
241
+ // Only picks which configured key set to use; jwtVerify then requires iss to match.
242
+ const claimed = decodeJwt(token).iss;
243
+ const jwks = typeof claimed === "string" ? keys.get(claimed) : undefined;
244
+ if (!jwks)
245
+ throw invalid();
246
+ const { payload } = await jwtVerify(token, jwks, {
247
+ issuer: claimed,
248
+ algorithms: ALGORITHMS,
249
+ requiredClaims: ["exp", "iss", "aud"],
250
+ clockTolerance: 5,
251
+ });
252
+ const audience = [].concat(payload.aud);
253
+ const match = audience.some((value) => typeof value === "string" && value.split("#")[0].replace(/\/$/, "") === canonical);
254
+ if (!match)
255
+ throw invalid();
256
+ return authInfo(payload, resource);
257
+ }
258
+ catch {
259
+ throw invalid();
260
+ }
261
+ },
262
+ };
263
+ }
264
+ function authInfo(payload, resource) {
265
+ const scope = typeof payload.scope === "string"
266
+ ? payload.scope.split(" ")
267
+ : Array.isArray(payload.scp)
268
+ ? payload.scp
269
+ : [];
270
+ const clientId = [payload.client_id, payload.azp, payload.sub].find((value) => typeof value === "string");
271
+ return {
272
+ // The access token is deliberately not kept: it is verified here and nothing downstream
273
+ // (the factory context, the daemon client) can read or forward it.
274
+ token: "",
275
+ clientId: clientId ?? "unknown",
276
+ scopes: scope.filter((value) => typeof value === "string" && value !== ""),
277
+ expiresAt: payload.exp,
278
+ resource,
279
+ };
280
+ }
281
+ /** Read a body of at most `limit` bytes, or undefined when it is larger (or the client aborts). */
282
+ export async function boundedBody(req, limit) {
283
+ const declared = req.headers["content-length"];
284
+ if (declared !== undefined && (!/^\d+$/.test(declared) || Number(declared) > limit))
285
+ return undefined;
286
+ const chunks = [];
287
+ let size = 0;
288
+ for await (const chunk of req) {
289
+ size += chunk.length;
290
+ if (size > limit)
291
+ return undefined;
292
+ chunks.push(chunk);
293
+ }
294
+ return Buffer.concat(chunks);
295
+ }
296
+ export function webHeaders(req) {
297
+ const headers = new Headers();
298
+ for (const [name, value] of Object.entries(req.headers)) {
299
+ if (value === undefined)
300
+ continue;
301
+ for (const item of Array.isArray(value) ? value : [value])
302
+ headers.append(name, item);
303
+ }
304
+ return headers;
305
+ }
306
+ /**
307
+ * Serve the Streamable HTTP endpoint as an OAuth resource server. Opt-in only; it refuses to
308
+ * start without a delegated API key credential, a canonical resource URL and at least one
309
+ * authorization server. The key (never the OAuth token) is what authenticates to ant0d.
310
+ */
311
+ export async function serveHttp(options) {
312
+ const host = options.host ?? "127.0.0.1";
313
+ const local = loopbackHost(host);
314
+ if (!local && options.allowNonLoopback !== true)
315
+ refuse("HTTP mode listens on loopback only; a non-loopback address needs ANT0_MCP_HTTP_ALLOW_NON_LOOPBACK=1");
316
+ if (options.authorizationServers.length === 0)
317
+ refuse("HTTP mode needs at least one authorization server (issuer and JWKS URL)");
318
+ const resource = parseResource(options.resource);
319
+ const issuers = options.authorizationServers.map(parseIssuer);
320
+ const maxBody = options.maxBodyBytes ?? 1024 * 1024;
321
+ const lifetime = new AbortController();
322
+ const permits = new CallPermits();
323
+ let stopSweeper;
324
+ let server;
325
+ let handler;
326
+ const closeAll = async () => {
327
+ lifetime.abort();
328
+ stopSweeper?.();
329
+ await handler?.close().catch(() => { });
330
+ if (server?.listening)
331
+ await new Promise((resolve) => {
332
+ server.close(() => resolve());
333
+ server.closeAllConnections();
334
+ });
335
+ };
336
+ try {
337
+ const connection = discoverConnection(options);
338
+ // Scoped keys only: with the local bearer the daemon would let every request through.
339
+ if (!keyMode(connection))
340
+ refuse("HTTP mode requires a delegated API key (--credential-file or ANT0_API_KEY), not the local token");
341
+ const home = resolveHome({
342
+ ...(options.home !== undefined ? { home: options.home } : {}),
343
+ env: options.env ?? process.env,
344
+ });
345
+ stopSweeper = startExportSweeper(home);
346
+ const client = daemonClient(connection, lifetime.signal);
347
+ const grant = await resolveGrant(connection, client, "mcp", lifetime.signal);
348
+ if (!grant)
349
+ refuse("HTTP mode could not resolve the key's scopes");
350
+ const tools = toolsForCredential(grant);
351
+ // Defence in depth: a "local" tool can never be in a scoped key's list.
352
+ if (tools.some((tool) => toolScope(tool.name) === "local" || toolScope(tool.name) === undefined))
353
+ throw new McpFailure("internal");
354
+ const resourcePath = resource.pathname;
355
+ const metadataUrl = getOAuthProtectedResourceMetadataUrl(resource);
356
+ const wellKnown = new URL(metadataUrl).pathname;
357
+ const metadata = {
358
+ resource: strippedResource(resource),
359
+ authorization_servers: issuers.map(({ issuer }) => issuer),
360
+ scopes_supported: [...HTTP_SCOPES],
361
+ bearer_methods_supported: ["header"],
362
+ resource_name: "Ant0 MCP",
363
+ };
364
+ const verifier = jwtVerifier(issuers, resource);
365
+ const gate = requireBearerAuth({
366
+ verifier,
367
+ resourceMetadataUrl: metadataUrl,
368
+ expectedResource: resource,
369
+ });
370
+ // Hostnames only (the SDK compares without port). The public resource host may differ from
371
+ // the listen address when a TLS proxy sits in front.
372
+ const listenName = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
373
+ const allowedHosts = [
374
+ ...new Set([resource.hostname, listenName, "localhost", "127.0.0.1", "[::1]"]),
375
+ ];
376
+ const allowedOrigins = parseOrigins(options.allowedOrigins ?? []);
377
+ handler = createMcpHandler((ctx) => {
378
+ // The tool set of this one request: the key's tools narrowed by the token's scopes. No
379
+ // authInfo means no tools at all (the gate above makes that unreachable).
380
+ const allowed = new Set();
381
+ for (const scope of ctx.authInfo?.scopes ?? [])
382
+ for (const name of toolsForHttpScope(scope))
383
+ allowed.add(name);
384
+ return buildServer({
385
+ client,
386
+ tools,
387
+ grant,
388
+ home,
389
+ permits,
390
+ lifetime: lifetime.signal,
391
+ allowed,
392
+ });
393
+ }, { maxRequestBodySize: maxBody, legacy: "stateless" });
394
+ const mcp = handler;
395
+ server = createServer({
396
+ maxHeaderSize: 16 * 1024,
397
+ requestTimeout: 30_000,
398
+ headersTimeout: 10_000,
399
+ keepAliveTimeout: 5_000,
400
+ }, (req, res) => {
401
+ void (async () => {
402
+ const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
403
+ const web = new Request(url, { method: req.method ?? "GET", headers: webHeaders(req) });
404
+ const send = async (response, cors = true) => {
405
+ res.statusCode = response.status;
406
+ response.headers.forEach((value, name) => res.setHeader(name, value));
407
+ const origin = req.headers.origin;
408
+ if (cors && typeof origin === "string" && allowedOrigins.size > 0) {
409
+ res.setHeader("Vary", "Origin");
410
+ res.setHeader("Access-Control-Allow-Origin", origin);
411
+ res.setHeader("Access-Control-Expose-Headers", "WWW-Authenticate");
412
+ }
413
+ res.setHeader("Cache-Control", "no-store");
414
+ res.setHeader("X-Content-Type-Options", "nosniff");
415
+ if (!response.body)
416
+ return void res.end();
417
+ const reader = response.body.getReader();
418
+ res.on("close", () => void reader.cancel().catch(() => { }));
419
+ try {
420
+ for (;;) {
421
+ const { done, value } = await reader.read();
422
+ if (done)
423
+ break;
424
+ if (!res.write(value))
425
+ await new Promise((resolve) => res.once("drain", resolve));
426
+ }
427
+ }
428
+ catch {
429
+ // The peer went away; the SDK cancels the exchange from the aborted signal.
430
+ }
431
+ res.end();
432
+ };
433
+ const status = (code, headers = {}) => send(new Response(null, { status: code, headers }), false);
434
+ // DNS-rebinding and cross-origin defences come first, on every route.
435
+ const origin = req.headers.origin;
436
+ const bad = hostHeaderValidationResponse(web, allowedHosts) ??
437
+ (typeof origin === "string" && !originAllowed(origin, allowedOrigins)
438
+ ? Response.json({ error: "forbidden_origin" }, { status: 403 })
439
+ : undefined);
440
+ if (bad)
441
+ return void (await send(bad, false));
442
+ if (url.pathname === wellKnown ||
443
+ url.pathname === "/.well-known/oauth-protected-resource") {
444
+ if (req.method !== "GET" && req.method !== "HEAD")
445
+ return void (await status(405, { Allow: "GET, HEAD" }));
446
+ return void (await send(Response.json(metadata)));
447
+ }
448
+ if (url.pathname !== resourcePath)
449
+ return void (await status(404));
450
+ if (req.method === "OPTIONS" && typeof req.headers.origin === "string")
451
+ return void (await status(204, {
452
+ "Access-Control-Allow-Methods": "POST",
453
+ "Access-Control-Allow-Headers": "authorization, content-type, mcp-protocol-version, mcp-method, mcp-name, accept",
454
+ "Access-Control-Max-Age": "600",
455
+ ...(allowedOrigins.size > 0
456
+ ? { "Access-Control-Allow-Origin": req.headers.origin, Vary: "Origin" }
457
+ : {}),
458
+ }));
459
+ // The 2026-07-28 endpoint is POST only: no GET stream, no DELETE session.
460
+ if (req.method !== "POST")
461
+ return void (await status(405, { Allow: "POST" }));
462
+ const header = req.headers.authorization;
463
+ if (typeof header === "string" && header.length > MAX_TOKEN_CHARS + 7)
464
+ return void (await send(bearerAuthChallengeResponse(new OAuthError(OAuthErrorCode.InvalidToken, "Invalid access token"), {
465
+ resourceMetadataUrl: metadataUrl,
466
+ })));
467
+ const auth = await gate(web);
468
+ if (auth instanceof Response)
469
+ return void (await send(auth.status === 401
470
+ ? bearerAuthChallengeResponse(new OAuthError(OAuthErrorCode.InvalidToken, "Invalid access token"), { requiredScopes: [...HTTP_SCOPES], resourceMetadataUrl: metadataUrl })
471
+ : auth));
472
+ if (!auth.scopes.some((scope) => HTTP_SCOPES.includes(scope)))
473
+ return void (await send(bearerAuthChallengeResponse(new OAuthError(OAuthErrorCode.InsufficientScope, "Insufficient scope"), {
474
+ requiredScopes: [HTTP_SCOPE_READ],
475
+ resourceMetadataUrl: metadataUrl,
476
+ })));
477
+ const body = await boundedBody(req, maxBody);
478
+ if (body === undefined)
479
+ return void (await status(413));
480
+ // Peek the (already bounded, in-memory) body: the gate runs before the SDK parses it.
481
+ let peeked;
482
+ try {
483
+ const parsed = JSON.parse(body.toString("utf8"));
484
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed))
485
+ peeked = parsed;
486
+ }
487
+ catch {
488
+ // Not JSON: the SDK answers it.
489
+ }
490
+ // No listChanged capability is advertised, so there is nothing to subscribe to. A
491
+ // listen stream would outlive the token and could hold a connection slot for good.
492
+ if (peeked?.method === "subscriptions/listen")
493
+ return void (await send(Response.json({
494
+ jsonrpc: "2.0",
495
+ id: typeof peeked.id === "string" || typeof peeked.id === "number"
496
+ ? peeked.id
497
+ : null,
498
+ error: { code: -32601, message: "MCP request rejected" },
499
+ }, { status: 200 })));
500
+ // A tool the key grants but the token's scopes do not cover: tell the client which
501
+ // scope to ask for (RFC 6750 step-up). Never reaches the SDK or the daemon.
502
+ if (peeked?.method === "tools/call" && typeof peeked.params?.name === "string") {
503
+ const name = peeked.params.name;
504
+ const covered = auth.scopes.some((scope) => toolsForHttpScope(scope).includes(name));
505
+ const needed = HTTP_SCOPES.find((scope) => toolsForHttpScope(scope).includes(name));
506
+ if (!covered && needed !== undefined && tools.some((tool) => tool.name === name))
507
+ return void (await send(bearerAuthChallengeResponse(new OAuthError(OAuthErrorCode.InsufficientScope, "Insufficient scope"), { requiredScopes: [needed], resourceMetadataUrl: metadataUrl })));
508
+ }
509
+ const abort = new AbortController();
510
+ res.on("close", () => abort.abort());
511
+ const headers = webHeaders(req);
512
+ // No token passthrough: the bearer is not even visible to the MCP layer's request.
513
+ headers.delete("authorization");
514
+ const request = new Request(url, {
515
+ method: "POST",
516
+ headers,
517
+ body: new Uint8Array(body),
518
+ signal: abort.signal,
519
+ });
520
+ let response;
521
+ try {
522
+ response = await mcp.fetch(request, { authInfo: auth });
523
+ }
524
+ catch {
525
+ response = Response.json({
526
+ jsonrpc: "2.0",
527
+ id: null,
528
+ error: { code: -32603, message: "MCP request rejected" },
529
+ }, { status: 500 });
530
+ }
531
+ await send(await sanitizeResponse(response));
532
+ })().catch(() => {
533
+ if (!res.headersSent)
534
+ res.statusCode = 500;
535
+ res.end();
536
+ });
537
+ });
538
+ server.maxConnections = 64;
539
+ await new Promise((resolve, reject) => {
540
+ server.once("error", reject);
541
+ server.listen(options.listenPort ?? DEFAULT_PORT, host.replace(/^\[|\]$/g, ""), () => resolve());
542
+ });
543
+ const port = server.address().port;
544
+ options.signal?.addEventListener("abort", () => void closeAll(), { once: true });
545
+ return {
546
+ url: `http://${host.includes(":") && !host.startsWith("[") ? `[${host}]` : host}:${port}${resourcePath}`,
547
+ port,
548
+ close: closeAll,
549
+ };
550
+ }
551
+ catch (error) {
552
+ await closeAll();
553
+ throw error instanceof McpFailure ? error : safeFailure(error);
554
+ }
555
+ }
556
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1,21 @@
1
+ import type { Readable, Writable } from "node:stream";
2
+ import { type DiscoveryOptions } from "./connection.js";
3
+ import type { OutputWorkerCommand } from "./output-writer.js";
4
+ export { McpFailure } from "./errors.js";
5
+ export { discoverConnection, canonicalOrigin } from "./connection.js";
6
+ export { daemonClient } from "./daemon.js";
7
+ export { keyMode } from "./connection.js";
8
+ export { resolveGrant } from "./grant.js";
9
+ export { serveHttp, httpOptionsFromEnv } from "./http.js";
10
+ export { serveDesktopLocalHttp, serveDesktopLocalFromStdin, bearerMatches, PortInUseFailure, DESKTOP_TOKEN_PATTERN, } from "./http-local.js";
11
+ export type { DesktopLocalOptions } from "./http-local.js";
12
+ export type { AuthorizationServer, HttpOptions, HttpServerHandle } from "./http.js";
13
+ export type { OutputWorkerCommand } from "./output-writer.js";
14
+ export interface ServeOptions extends DiscoveryOptions {
15
+ stdin?: Readable;
16
+ stdout?: Writable;
17
+ signal?: AbortSignal;
18
+ }
19
+ /** Serve one stdio connection. Resolves on EOF/signal; rejects with fixed diagnostics only. */
20
+ export declare function serveStdio(options?: ServeOptions, outputWorkerCommand?: OutputWorkerCommand): Promise<void>;
21
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,86 @@
1
+ import { serveStdio as serveSdkStdio, } from "@modelcontextprotocol/server/stdio";
2
+ import { discoverConnection } from "./connection.js";
3
+ import { daemonClient } from "./daemon.js";
4
+ import { McpFailure, safeFailure } from "./errors.js";
5
+ import { CallPermits } from "./call-permits.js";
6
+ import { toolsForCredential } from "./tools.js";
7
+ import { buildServer } from "./server.js";
8
+ import { resolveGrant } from "./grant.js";
9
+ import { resolveHome } from "./api/index.js";
10
+ import { startExportSweeper } from "./export-files.js";
11
+ import { BoundedStdioTransport } from "./transport.js";
12
+ import { watchPeer } from "./peer-watchdog.js";
13
+ export { McpFailure } from "./errors.js";
14
+ export { discoverConnection, canonicalOrigin } from "./connection.js";
15
+ export { daemonClient } from "./daemon.js";
16
+ export { keyMode } from "./connection.js";
17
+ export { resolveGrant } from "./grant.js";
18
+ export { serveHttp, httpOptionsFromEnv } from "./http.js";
19
+ export { serveDesktopLocalHttp, serveDesktopLocalFromStdin, bearerMatches, PortInUseFailure, DESKTOP_TOKEN_PATTERN, } from "./http-local.js";
20
+ /** Serve one stdio connection. Resolves on EOF/signal; rejects with fixed diagnostics only. */
21
+ export async function serveStdio(options = {}, outputWorkerCommand) {
22
+ const lifetime = new AbortController();
23
+ const transport = new BoundedStdioTransport(options.stdin ?? process.stdin, options.stdout ?? process.stdout, outputWorkerCommand);
24
+ transport.closedSignal.addEventListener("abort", () => lifetime.abort(), { once: true });
25
+ const stop = () => {
26
+ lifetime.abort();
27
+ void transport.close();
28
+ };
29
+ const permits = new CallPermits();
30
+ let stopSweeper;
31
+ let handle;
32
+ try {
33
+ const connection = discoverConnection(options);
34
+ const home = resolveHome({
35
+ ...(options.home !== undefined ? { home: options.home } : {}),
36
+ env: options.env ?? process.env,
37
+ });
38
+ // Real 24 h retention: sweep at start and hourly, not only when a new export is written.
39
+ stopSweeper = startExportSweeper(home);
40
+ const client = daemonClient(connection, lifetime.signal);
41
+ const grant = await resolveGrant(connection, client, "mcp", lifetime.signal);
42
+ const tools = toolsForCredential(grant);
43
+ const parts = { client, tools, grant, home, permits, lifetime: lifetime.signal };
44
+ process.on("SIGINT", stop);
45
+ process.on("SIGTERM", stop);
46
+ options.signal?.addEventListener("abort", stop, { once: true });
47
+ if (options.signal?.aborted)
48
+ return;
49
+ const failed = (error) => transport.fail(error instanceof McpFailure ? error.code : "input");
50
+ // The factory runs once for the `server/discover` probe and again if the client falls back to
51
+ // `initialize`, so everything resolved above is shared and nothing here is started once-only.
52
+ // The probe instance is closed on fallback; its close must not end the connection (transport
53
+ // shutdown does that, through `closedSignal`).
54
+ handle = serveSdkStdio((ctx) => {
55
+ const server = buildServer(parts);
56
+ server.onerror = failed;
57
+ // ping and server-to-client requests exist only on `initialize` connections; a modern
58
+ // (2026-07-28) connection ends on stdin EOF, which the transport already detects.
59
+ if (ctx.era === "legacy") {
60
+ // Starts after the writer is up (the transport starts before the first message), so a
61
+ // ping can never precede the writer's startup budget.
62
+ const stopWatching = watchPeer(server, lifetime.signal, () => transport.fail("peer"));
63
+ server.onclose = stopWatching;
64
+ }
65
+ return server;
66
+ }, { transport, legacy: "serve", onerror: failed });
67
+ const failure = await transport.done;
68
+ if (failure)
69
+ throw failure;
70
+ }
71
+ catch (error) {
72
+ if (lifetime.signal.aborted && error instanceof McpFailure && error.code === "cancelled")
73
+ return;
74
+ throw safeFailure(error);
75
+ }
76
+ finally {
77
+ stopSweeper?.();
78
+ lifetime.abort();
79
+ await handle?.close().catch(() => { });
80
+ await transport.close();
81
+ process.off("SIGINT", stop);
82
+ process.off("SIGTERM", stop);
83
+ options.signal?.removeEventListener("abort", stop);
84
+ }
85
+ }
86
+ //# sourceMappingURL=index.js.map