convex 1.45.0-alpha.0 → 1.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +8 -1
  2. package/dist/browser.bundle.js +1 -1
  3. package/dist/browser.bundle.js.map +1 -1
  4. package/dist/cjs/cli/lib/indexes.js +1 -1
  5. package/dist/cjs/cli/lib/indexes.js.map +1 -1
  6. package/dist/cjs/cli/mcp.js +16 -6
  7. package/dist/cjs/cli/mcp.js.map +2 -2
  8. package/dist/cjs/index.js +1 -1
  9. package/dist/cjs/index.js.map +1 -1
  10. package/dist/cjs/server/impl/actions_impl.js.map +2 -2
  11. package/dist/cjs/server/index.js.map +2 -2
  12. package/dist/cjs-types/cli/mcp.d.ts.map +1 -1
  13. package/dist/cjs-types/index.d.ts +1 -1
  14. package/dist/cjs-types/index.d.ts.map +1 -1
  15. package/dist/cjs-types/server/impl/actions_impl.d.ts +14 -0
  16. package/dist/cjs-types/server/impl/actions_impl.d.ts.map +1 -1
  17. package/dist/cjs-types/server/index.d.ts +1 -0
  18. package/dist/cjs-types/server/index.d.ts.map +1 -1
  19. package/dist/cli.bundle.cjs +1407 -8
  20. package/dist/cli.bundle.cjs.map +4 -4
  21. package/dist/esm/cli/lib/indexes.js +1 -1
  22. package/dist/esm/cli/lib/indexes.js.map +1 -1
  23. package/dist/esm/cli/mcp.js +17 -7
  24. package/dist/esm/cli/mcp.js.map +2 -2
  25. package/dist/esm/index.js +1 -1
  26. package/dist/esm/index.js.map +1 -1
  27. package/dist/esm/server/impl/actions_impl.js.map +2 -2
  28. package/dist/esm/server/index.js.map +2 -2
  29. package/dist/esm-types/cli/mcp.d.ts.map +1 -1
  30. package/dist/esm-types/index.d.ts +1 -1
  31. package/dist/esm-types/index.d.ts.map +1 -1
  32. package/dist/esm-types/server/impl/actions_impl.d.ts +14 -0
  33. package/dist/esm-types/server/impl/actions_impl.d.ts.map +1 -1
  34. package/dist/esm-types/server/index.d.ts +1 -0
  35. package/dist/esm-types/server/index.d.ts.map +1 -1
  36. package/dist/react.bundle.js +1 -1
  37. package/dist/react.bundle.js.map +1 -1
  38. package/package.json +1 -1
  39. package/src/cli/lib/indexes.ts +1 -1
  40. package/src/cli/mcp.ts +29 -7
  41. package/src/index.ts +1 -1
  42. package/src/server/impl/actions_impl.ts +3 -1
  43. package/src/server/index.ts +0 -3
@@ -47456,7 +47456,7 @@ var version;
47456
47456
  var init_index = __esm({
47457
47457
  "src/index.ts"() {
47458
47458
  "use strict";
47459
- version = "1.45.0-alpha.0";
47459
+ version = "1.45.0";
47460
47460
  }
47461
47461
  });
47462
47462
 
@@ -114645,7 +114645,7 @@ function addProgressLinkIfSlow(msg, deploymentName, start) {
114645
114645
  if (Date.now() - start > 1e4) {
114646
114646
  const dashboardUrl2 = deploymentDashboardUrlPage(
114647
114647
  deploymentName,
114648
- `/data?showSchema=true`
114648
+ `/schema?showSchema=true`
114649
114649
  );
114650
114650
  msg = msg.concat(`
114651
114651
  See progress here: ${dashboardUrl2}`);
@@ -131886,6 +131886,9 @@ var logs = new Command2("logs").summary("Watch logs from your deployment").descr
131886
131886
  });
131887
131887
  });
131888
131888
 
131889
+ // src/cli/mcp.ts
131890
+ init_log();
131891
+
131889
131892
  // ../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs
131890
131893
  var __create2 = Object.create;
131891
131894
  var __defProp2 = Object.defineProperty;
@@ -138681,6 +138684,7 @@ function missingClientCapabilities(required2, declared) {
138681
138684
  return Object.keys(missing).length > 0 ? missing : void 0;
138682
138685
  }
138683
138686
  var FIRST_MODERN_PROTOCOL_VERSION = "2026-07-28";
138687
+ var SUPPORTED_MODERN_PROTOCOL_VERSIONS = [FIRST_MODERN_PROTOCOL_VERSION];
138684
138688
  function isModernProtocolVersion(version4) {
138685
138689
  return version4 >= FIRST_MODERN_PROTOCOL_VERSION;
138686
138690
  }
@@ -141239,6 +141243,25 @@ function isSpecNotificationMethod(method) {
141239
141243
  return ALL_CODECS.some((codec) => codec.hasNotificationMethod(method));
141240
141244
  }
141241
141245
  var ALL_CODECS = [rev2025Codec, rev2026Codec];
141246
+ function isPlainObject$3(value) {
141247
+ return value !== null && typeof value === "object" && !Array.isArray(value);
141248
+ }
141249
+ function requestMetaOf(params) {
141250
+ if (!isPlainObject$3(params)) return void 0;
141251
+ const meta2 = params["_meta"];
141252
+ return isPlainObject$3(meta2) ? meta2 : void 0;
141253
+ }
141254
+ function hasEnvelopeClaim(params) {
141255
+ const meta2 = requestMetaOf(params);
141256
+ return meta2 !== void 0 && PROTOCOL_VERSION_META_KEY in meta2;
141257
+ }
141258
+ function envelopeClaimVersion(params) {
141259
+ const value = requestMetaOf(params)?.[PROTOCOL_VERSION_META_KEY];
141260
+ return typeof value === "string" ? value : void 0;
141261
+ }
141262
+ function validateEnvelopeMeta(meta2) {
141263
+ return codecForVersion(MODERN_WIRE_REVISION).validateEnvelopeMeta(meta2);
141264
+ }
141242
141265
  var schemas_exports2 = /* @__PURE__ */ __exportAll({
141243
141266
  AnnotationsSchema: () => AnnotationsSchema,
141244
141267
  AudioContentSchema: () => AudioContentSchema,
@@ -141412,6 +141435,96 @@ var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value
141412
141435
  var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;
141413
141436
  var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;
141414
141437
  var isInputRequiredResult = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.resultType === "input_required";
141438
+ function assertCompleteRequestPrompt(request) {
141439
+ if (request.params.ref.type !== "ref/prompt") throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);
141440
+ }
141441
+ function assertCompleteRequestResourceTemplate(request) {
141442
+ if (request.params.ref.type !== "ref/resource") throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);
141443
+ }
141444
+ var X_MCP_HEADER_KEY = "x-mcp-header";
141445
+ var RFC9110_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
141446
+ var PERMITTED_X_MCP_HEADER_TYPES = /* @__PURE__ */ new Set([
141447
+ "string",
141448
+ "integer",
141449
+ "boolean",
141450
+ "number"
141451
+ ]);
141452
+ function scanXMcpHeaderDeclarations(inputSchema9) {
141453
+ const declarations = [];
141454
+ const seenLower = /* @__PURE__ */ new Map();
141455
+ const visit = (node, path38, reachable) => {
141456
+ if (node === null || typeof node !== "object") return void 0;
141457
+ const schema2 = node;
141458
+ if (X_MCP_HEADER_KEY in schema2) {
141459
+ if (!reachable || path38.length === 0) return `${pathName(path38)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;
141460
+ const raw = schema2[X_MCP_HEADER_KEY];
141461
+ if (typeof raw !== "string" || raw.length === 0) return `${pathName(path38)}: x-mcp-header MUST be a non-empty string`;
141462
+ if (!RFC9110_TOKEN.test(raw)) return `${pathName(path38)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;
141463
+ const type = typeof schema2.type === "string" ? schema2.type : void 0;
141464
+ if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path38)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? "<none>"}`;
141465
+ const lower = raw.toLowerCase();
141466
+ const prior = seenLower.get(lower);
141467
+ if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`;
141468
+ seenLower.set(lower, raw);
141469
+ declarations.push({
141470
+ path: path38,
141471
+ headerName: raw,
141472
+ type
141473
+ });
141474
+ }
141475
+ const properties = schema2.properties;
141476
+ if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) {
141477
+ const fault$1 = visit(child, [...path38, key], reachable);
141478
+ if (fault$1 !== void 0) return fault$1;
141479
+ }
141480
+ for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) {
141481
+ const sub = schema2[k];
141482
+ if (sub === void 0) continue;
141483
+ const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub];
141484
+ for (const branch of branches) {
141485
+ const fault$1 = visit(branch, [...path38, `<${k}>`], false);
141486
+ if (fault$1 !== void 0) return fault$1;
141487
+ }
141488
+ }
141489
+ };
141490
+ const fault = visit(inputSchema9, [], true);
141491
+ return fault === void 0 ? {
141492
+ valid: true,
141493
+ declarations
141494
+ } : {
141495
+ valid: false,
141496
+ reason: fault
141497
+ };
141498
+ }
141499
+ var NON_REACHABLE_SUBSCHEMA_KEYWORDS = [
141500
+ "items",
141501
+ "prefixItems",
141502
+ "contains",
141503
+ "additionalProperties",
141504
+ "unevaluatedProperties",
141505
+ "unevaluatedItems",
141506
+ "propertyNames",
141507
+ "patternProperties",
141508
+ "dependentSchemas",
141509
+ "oneOf",
141510
+ "anyOf",
141511
+ "allOf",
141512
+ "not",
141513
+ "if",
141514
+ "then",
141515
+ "else",
141516
+ "$defs",
141517
+ "definitions"
141518
+ ];
141519
+ var OBJECT_VALUED_SUBSCHEMA_KEYWORDS = /* @__PURE__ */ new Set([
141520
+ "patternProperties",
141521
+ "dependentSchemas",
141522
+ "$defs",
141523
+ "definitions"
141524
+ ]);
141525
+ function pathName(path38) {
141526
+ return path38.length === 0 ? "<root>" : path38.join(".");
141527
+ }
141415
141528
  var HEADER_MISMATCH_ERROR_CODE = -32020;
141416
141529
  var INBOUND_VALIDATION_LADDER = [
141417
141530
  {
@@ -141499,6 +141612,45 @@ var LADDER_ERROR_HTTP_STATUS = {
141499
141612
  [ProtocolErrorCode.MissingRequiredClientCapability]: 400,
141500
141613
  [HEADER_MISMATCH_ERROR_CODE]: 400
141501
141614
  };
141615
+ function rejection(rung, cell, httpStatus, error3, settled) {
141616
+ return {
141617
+ kind: "reject",
141618
+ rung,
141619
+ cell,
141620
+ httpStatus,
141621
+ code: error3.code,
141622
+ message: error3.message,
141623
+ ...error3.data !== void 0 && { data: error3.data },
141624
+ settled
141625
+ };
141626
+ }
141627
+ function carriesValidModernEnvelopeClaim(params) {
141628
+ if (!hasEnvelopeClaim(params)) return false;
141629
+ const claimedVersion = envelopeClaimVersion(params);
141630
+ if (claimedVersion === void 0 || !isModernProtocolVersion(claimedVersion)) return false;
141631
+ const meta2 = requestMetaOf(params);
141632
+ return meta2 !== void 0 && validateEnvelopeMeta(meta2).length === 0;
141633
+ }
141634
+ function modernOnlyStrictRejection(route, supportedVersions) {
141635
+ switch (route.reason) {
141636
+ case "http-method":
141637
+ return rejection("http-method", "modern-only-method-not-allowed", 405, new ProtocolError(-32e3, "Method not allowed."), true);
141638
+ case "batch":
141639
+ return rejection("jsonrpc-shape", "modern-only-batch-not-supported", 400, new ProtocolError(ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches are not supported by this endpoint"), true);
141640
+ case "response":
141641
+ return rejection("jsonrpc-shape", "modern-only-response-post", 400, new ProtocolError(ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC responses cannot be posted to this endpoint"), true);
141642
+ case "notification":
141643
+ return;
141644
+ case "initialize":
141645
+ case "no-claim": {
141646
+ const requested = route.requestedVersion;
141647
+ return rejection("era-classification", "modern-only-missing-envelope", 400, requested === void 0 ? new ProtocolError(ProtocolErrorCode.UnsupportedProtocolVersion, "Unsupported protocol version: the request did not name a protocol version", { supported: [...supportedVersions] }) : new UnsupportedProtocolVersionError({
141648
+ supported: [...supportedVersions],
141649
+ requested
141650
+ }), true);
141651
+ }
141652
+ }
141653
+ }
141502
141654
  function parseSchema(schema2, data2) {
141503
141655
  return safeParse2(schema2, data2);
141504
141656
  }
@@ -141613,6 +141765,16 @@ function isLibraryFormatPattern(format5, pattern, vendor) {
141613
141765
  if (vendor !== "zod") return true;
141614
141766
  return referencePatternsForFormat(format5, pattern).has(pattern);
141615
141767
  }
141768
+ function promptArgumentsFromStandardSchema(schema2) {
141769
+ const jsonSchema = standardSchemaToJsonSchema(schema2, "input");
141770
+ const properties = jsonSchema.properties || {};
141771
+ const required2 = jsonSchema.required || [];
141772
+ return Object.entries(properties).map(([name, prop]) => ({
141773
+ name,
141774
+ description: prop?.description,
141775
+ required: required2.includes(name)
141776
+ }));
141777
+ }
141616
141778
  function isJsonObject(value) {
141617
141779
  return typeof value === "object" && value !== null && !Array.isArray(value);
141618
141780
  }
@@ -142050,6 +142212,9 @@ function withRequestStateValue(ctx, value) {
142050
142212
  };
142051
142213
  }
142052
142214
  var writeNegotiatedProtocolVersion;
142215
+ function setNegotiatedProtocolVersion(instance, version4) {
142216
+ writeNegotiatedProtocolVersion(instance, version4);
142217
+ }
142053
142218
  var Protocol = class {
142054
142219
  _transport;
142055
142220
  _requestMessageId = 0;
@@ -142908,6 +143073,68 @@ function deserializeMessage(line) {
142908
143073
  function serializeMessage(message) {
142909
143074
  return JSON.stringify(message) + "\n";
142910
143075
  }
143076
+ var TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/;
143077
+ function validateToolName(name) {
143078
+ const warnings = [];
143079
+ if (name.length === 0) return {
143080
+ isValid: false,
143081
+ warnings: ["Tool name cannot be empty"]
143082
+ };
143083
+ if (name.length > 128) return {
143084
+ isValid: false,
143085
+ warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]
143086
+ };
143087
+ if (name.includes(" ")) warnings.push("Tool name contains spaces, which may cause parsing issues");
143088
+ if (name.includes(",")) warnings.push("Tool name contains commas, which may cause parsing issues");
143089
+ if (name.startsWith("-") || name.endsWith("-")) warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");
143090
+ if (name.startsWith(".") || name.endsWith(".")) warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");
143091
+ if (!TOOL_NAME_REGEX.test(name)) {
143092
+ const invalidChars = [...name].filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index);
143093
+ warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)");
143094
+ return {
143095
+ isValid: false,
143096
+ warnings
143097
+ };
143098
+ }
143099
+ return {
143100
+ isValid: true,
143101
+ warnings
143102
+ };
143103
+ }
143104
+ function issueToolNameWarning(name, warnings) {
143105
+ if (warnings.length > 0) {
143106
+ console.warn(`Tool name validation warning for "${name}":`);
143107
+ for (const warning2 of warnings) console.warn(` - ${warning2}`);
143108
+ console.warn("Tool registration will proceed, but this may cause compatibility issues.");
143109
+ console.warn("Consider updating the tool name to conform to the MCP tool naming standard.");
143110
+ console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.");
143111
+ }
143112
+ }
143113
+ function validateAndWarnToolName(name) {
143114
+ const result = validateToolName(name);
143115
+ issueToolNameWarning(name, result.warnings);
143116
+ return result.isValid;
143117
+ }
143118
+ function isZodV4Schema(v) {
143119
+ return typeof v === "object" && v !== null && "_zod" in v;
143120
+ }
143121
+ function looksLikeZodV3(v) {
143122
+ return typeof v === "object" && v !== null && !("_zod" in v) && "_def" in v && typeof v._def?.typeName === "string";
143123
+ }
143124
+ function isZodRawShape(obj) {
143125
+ if (typeof obj !== "object" || obj === null) return false;
143126
+ if (isStandardSchema(obj)) return false;
143127
+ const proto2 = Object.getPrototypeOf(obj);
143128
+ if (proto2 !== Object.prototype && proto2 !== null) return false;
143129
+ return Object.values(obj).every((v) => isZodV4Schema(v));
143130
+ }
143131
+ function normalizeRawShapeSchema(schema2) {
143132
+ if (schema2 === void 0) return void 0;
143133
+ if (isZodRawShape(schema2)) return object(schema2);
143134
+ if (typeof schema2 === "object" && schema2 !== null && !isStandardSchema(schema2) && Object.values(schema2).some((v) => looksLikeZodV3(v))) throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");
143135
+ if (!isStandardSchema(schema2)) throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");
143136
+ return schema2;
143137
+ }
142911
143138
 
142912
143139
  // ../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/ajvProvider-CEoC__sr.mjs
142913
143140
  var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports2) => {
@@ -149924,7 +150151,197 @@ var import_node_process16 = __toESM(require("node:process"), 1);
149924
150151
 
149925
150152
  // ../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/mcp-DXXb3Vv3.mjs
149926
150153
  var COMPLETABLE_SYMBOL = Symbol.for("mcp.completable");
150154
+ function isCompletable(schema2) {
150155
+ return !!schema2 && typeof schema2 === "object" && COMPLETABLE_SYMBOL in schema2;
150156
+ }
150157
+ function getCompleter(schema2) {
150158
+ return schema2[COMPLETABLE_SYMBOL]?.complete;
150159
+ }
149927
150160
  var MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
150161
+ function listenFilterAccepts(filter, event) {
150162
+ switch (event.kind) {
150163
+ case "tools_list_changed":
150164
+ return filter.toolsListChanged === true;
150165
+ case "prompts_list_changed":
150166
+ return filter.promptsListChanged === true;
150167
+ case "resources_list_changed":
150168
+ return filter.resourcesListChanged === true;
150169
+ case "resource_updated":
150170
+ return filter.resourceSubscriptions !== void 0 && filter.resourceSubscriptions.includes(event.uri);
150171
+ }
150172
+ }
150173
+ function honoredSubset(requested, capabilities) {
150174
+ const honored = {};
150175
+ const allow = (bit) => capabilities === void 0 || bit === true;
150176
+ if (requested.toolsListChanged === true && allow(capabilities?.tools?.listChanged)) honored.toolsListChanged = true;
150177
+ if (requested.promptsListChanged === true && allow(capabilities?.prompts?.listChanged)) honored.promptsListChanged = true;
150178
+ if (requested.resourcesListChanged === true && allow(capabilities?.resources?.listChanged)) honored.resourcesListChanged = true;
150179
+ if (requested.resourceSubscriptions !== void 0 && requested.resourceSubscriptions.length > 0 && allow(capabilities?.resources?.subscribe)) honored.resourceSubscriptions = [...requested.resourceSubscriptions];
150180
+ return honored;
150181
+ }
150182
+ var DEFAULT_MAX_SUBSCRIPTIONS = 1024;
150183
+ function stampSubscriptionId(notification, subscriptionId) {
150184
+ return {
150185
+ method: notification.method,
150186
+ params: {
150187
+ ...notification.params,
150188
+ _meta: {
150189
+ ...notification.params?._meta,
150190
+ [SUBSCRIPTION_ID_META_KEY]: subscriptionId
150191
+ }
150192
+ }
150193
+ };
150194
+ }
150195
+ function parseListenFilter(message) {
150196
+ const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen", message);
150197
+ return outcome.ok ? outcome.value.params?.notifications : void 0;
150198
+ }
150199
+ var CHANGE_NOTIFICATION_METHODS = /* @__PURE__ */ new Set([
150200
+ "notifications/tools/list_changed",
150201
+ "notifications/prompts/list_changed",
150202
+ "notifications/resources/list_changed",
150203
+ "notifications/resources/updated"
150204
+ ]);
150205
+ var StdioListenRouter = class {
150206
+ /** Active subscriptions, keyed by the listen request's JSON-RPC id verbatim. */
150207
+ _subs = /* @__PURE__ */ new Map();
150208
+ /**
150209
+ * The serving instance's declared capabilities. Filled in by the entry
150210
+ * once the modern instance is constructed (the router is created before
150211
+ * the instance exists), so the acknowledged filter is narrowed against
150212
+ * what the server can actually deliver.
150213
+ */
150214
+ _serverCapabilities;
150215
+ /**
150216
+ * The serving instance's identity, stamped onto the graceful-close
150217
+ * results' `_meta` (the spec's `SubscriptionsListenResultMeta` extends
150218
+ * `ResultMetaObject`). Handed over together with the capabilities.
150219
+ */
150220
+ _serverInfo;
150221
+ constructor(_maxSubscriptions = DEFAULT_MAX_SUBSCRIPTIONS, serverCapabilities, serverInfo) {
150222
+ this._maxSubscriptions = _maxSubscriptions;
150223
+ this._serverCapabilities = serverCapabilities;
150224
+ this._serverInfo = serverInfo;
150225
+ }
150226
+ /**
150227
+ * Record the serving instance's declared capabilities and identity once
150228
+ * it has been constructed. Called by `serveStdio`'s connect path;
150229
+ * subsequent `serve()` calls narrow the honored filter against the
150230
+ * capabilities, and `teardownAll()` stamps the identity.
150231
+ */
150232
+ setServerCapabilities(capabilities, serverInfo) {
150233
+ this._serverCapabilities = capabilities;
150234
+ if (serverInfo !== void 0) this._serverInfo = serverInfo;
150235
+ }
150236
+ /** Whether `id` is an active listen subscription on this connection. */
150237
+ has(id) {
150238
+ return this._subs.has(id);
150239
+ }
150240
+ /**
150241
+ * Serve one inbound `subscriptions/listen` request: registers the
150242
+ * subscription and returns the stamped acknowledged notification (or, on
150243
+ * capacity / params rejection, the in-band JSON-RPC error response).
150244
+ *
150245
+ * @throws when called before {@linkcode setServerCapabilities} (or the
150246
+ * constructor) has supplied the serving instance's capabilities. Honoring a
150247
+ * filter without knowing the server's advertised capabilities would fail
150248
+ * open (deliver unadvertised types); the entry guarantees capabilities are
150249
+ * set before any listen request is routed here.
150250
+ */
150251
+ serve(message) {
150252
+ if (this._serverCapabilities === void 0) throw new Error("StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities");
150253
+ if (this._subs.size >= this._maxSubscriptions) return {
150254
+ jsonrpc: "2.0",
150255
+ id: message.id,
150256
+ error: {
150257
+ code: -32603,
150258
+ message: "Subscription limit reached"
150259
+ }
150260
+ };
150261
+ const filter = parseListenFilter(message);
150262
+ if (filter === void 0) return {
150263
+ jsonrpc: "2.0",
150264
+ id: message.id,
150265
+ error: {
150266
+ code: -32602,
150267
+ message: "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter"
150268
+ }
150269
+ };
150270
+ const honored = honoredSubset(filter, this._serverCapabilities);
150271
+ this._subs.set(message.id, honored);
150272
+ return stampSubscriptionId({
150273
+ method: "notifications/subscriptions/acknowledged",
150274
+ params: { notifications: honored }
150275
+ }, message.id);
150276
+ }
150277
+ /**
150278
+ * Tear down one subscription (inbound `notifications/cancelled`). Returns
150279
+ * `true` when a subscription was removed. After this call NOTHING further
150280
+ * is delivered for that subscription id (the post-cancel hardening).
150281
+ */
150282
+ cancel(id) {
150283
+ return this._subs.delete(id);
150284
+ }
150285
+ /**
150286
+ * Route an outbound notification through the active subscriptions.
150287
+ *
150288
+ * - For a subscription-gated change notification, returns one stamped copy
150289
+ * per subscription that opted in to it (an empty array means it is
150290
+ * dropped — the modern era never delivers an un-requested change type).
150291
+ * - For any other outbound message, returns `'passthrough'` (the entry
150292
+ * forwards it as-is).
150293
+ */
150294
+ routeOutbound(message) {
150295
+ if (!CHANGE_NOTIFICATION_METHODS.has(message.method)) return "passthrough";
150296
+ const uriParam = message.params?.["uri"];
150297
+ const uri = typeof uriParam === "string" ? uriParam : void 0;
150298
+ const event = notificationToServerEvent(message.method, uri);
150299
+ const out = [];
150300
+ for (const [subscriptionId, filter] of this._subs) if (listenFilterAccepts(filter, event)) out.push(stampSubscriptionId({
150301
+ method: message.method,
150302
+ params: message.params ?? {}
150303
+ }, subscriptionId));
150304
+ return out;
150305
+ }
150306
+ /**
150307
+ * Server-side graceful teardown of every active subscription: returns the
150308
+ * empty `subscriptions/listen` JSON-RPC result for each subscription id —
150309
+ * the spec's graceful-close signal, `_meta` carrying the subscription id
150310
+ * and the serving instance's identity — for the entry to emit before
150311
+ * closing the wire. Clears the set so nothing further is delivered.
150312
+ */
150313
+ teardownAll() {
150314
+ const out = [];
150315
+ for (const id of this._subs.keys()) out.push({
150316
+ jsonrpc: "2.0",
150317
+ id,
150318
+ result: {
150319
+ resultType: "complete",
150320
+ _meta: {
150321
+ [SUBSCRIPTION_ID_META_KEY]: id,
150322
+ ...this._serverInfo !== void 0 && { [SERVER_INFO_META_KEY]: this._serverInfo }
150323
+ }
150324
+ }
150325
+ });
150326
+ this._subs.clear();
150327
+ return out;
150328
+ }
150329
+ };
150330
+ function notificationToServerEvent(method, uri) {
150331
+ switch (method) {
150332
+ case "notifications/tools/list_changed":
150333
+ return { kind: "tools_list_changed" };
150334
+ case "notifications/prompts/list_changed":
150335
+ return { kind: "prompts_list_changed" };
150336
+ case "notifications/resources/list_changed":
150337
+ return { kind: "resources_list_changed" };
150338
+ default:
150339
+ return {
150340
+ kind: "resource_updated",
150341
+ uri: uri ?? ""
150342
+ };
150343
+ }
150344
+ }
149928
150345
  var DEFAULT_LEGACY_SHIM_MAX_ROUNDS = 8;
149929
150346
  var DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS = 6e5;
149930
150347
  function resolveLegacyShimOptions(options) {
@@ -150062,6 +150479,12 @@ var INPUT_REQUIRED_CAPABLE_METHODS = /* @__PURE__ */ new Set([
150062
150479
  var writeClientIdentity;
150063
150480
  var installDiscoverHandler;
150064
150481
  var readServerIdentity;
150482
+ function installModernOnlyHandlers(server, servedModernVersions) {
150483
+ installDiscoverHandler(server, servedModernVersions);
150484
+ }
150485
+ function serverIdentityOf(server) {
150486
+ return readServerIdentity(server);
150487
+ }
150065
150488
  var Server = class extends Protocol {
150066
150489
  _clientCapabilities;
150067
150490
  _clientVersion;
@@ -150673,6 +151096,579 @@ var Server = class extends Protocol {
150673
151096
  function discoverAdvertisedCapabilities(capabilities) {
150674
151097
  return { ...capabilities };
150675
151098
  }
151099
+ var McpServer = class {
151100
+ /**
151101
+ * The underlying {@linkcode Server} instance, useful for advanced operations like sending notifications.
151102
+ */
151103
+ server;
151104
+ _registeredResources = {};
151105
+ _registeredResourceTemplates = {};
151106
+ _registeredTools = {};
151107
+ _registeredPrompts = {};
151108
+ /**
151109
+ * Per-tool JSON-converted `inputSchema`, memoized so the SEP-2243
151110
+ * registration-time scan and the pre-dispatch validation step share one
151111
+ * conversion instead of paying it twice per request under the
151112
+ * per-request-factory `createMcpHandler` model.
151113
+ */
151114
+ _toolInputSchemaJson = {};
151115
+ /**
151116
+ * The JSON-serialized `inputSchema` of a registered tool, or `undefined`
151117
+ * when no such tool is registered. Used by the HTTP entry's pre-dispatch
151118
+ * SEP-2243 `Mcp-Param-*` validation step (which needs the same JSON Schema
151119
+ * `tools/list` would emit, before dispatch reaches the handler).
151120
+ *
151121
+ * @internal
151122
+ */
151123
+ toolInputSchemaJson(name) {
151124
+ const tool = this._registeredTools[name];
151125
+ if (tool === void 0 || !tool.enabled) return void 0;
151126
+ if (Object.hasOwn(this._toolInputSchemaJson, name)) return this._toolInputSchemaJson[name];
151127
+ if (tool.inputSchema === void 0) return EMPTY_OBJECT_JSON_SCHEMA;
151128
+ try {
151129
+ const json = standardSchemaToJsonSchema(tool.inputSchema, "input");
151130
+ this._toolInputSchemaJson[name] = json;
151131
+ return json;
151132
+ } catch {
151133
+ return;
151134
+ }
151135
+ }
151136
+ constructor(serverInfo, options) {
151137
+ this.server = new Server(serverInfo, options);
151138
+ if (options?.capabilities?.tools) this.setToolRequestHandlers();
151139
+ if (options?.capabilities?.resources) this.setResourceRequestHandlers();
151140
+ if (options?.capabilities?.prompts) this.setPromptRequestHandlers();
151141
+ }
151142
+ /**
151143
+ * Attaches to the given transport, starts it, and starts listening for messages.
151144
+ *
151145
+ * The `server` object assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward.
151146
+ *
151147
+ * @example
151148
+ * ```ts source="./mcp.examples.ts#McpServer_connect_stdio"
151149
+ * const server = new McpServer({ name: 'my-server', version: '1.0.0' });
151150
+ * const transport = new StdioServerTransport();
151151
+ * await server.connect(transport);
151152
+ * ```
151153
+ */
151154
+ async connect(transport) {
151155
+ return await this.server.connect(transport);
151156
+ }
151157
+ /**
151158
+ * Closes the connection.
151159
+ */
151160
+ async close() {
151161
+ await this.server.close();
151162
+ }
151163
+ _toolHandlersInitialized = false;
151164
+ setToolRequestHandlers() {
151165
+ if (this._toolHandlersInitialized) return;
151166
+ this.server.assertCanSetRequestHandler("tools/list");
151167
+ this.server.assertCanSetRequestHandler("tools/call");
151168
+ this.server.registerCapabilities({ tools: { listChanged: this.server.getCapabilities().tools?.listChanged ?? true } });
151169
+ this.server.setRequestHandler("tools/list", () => ({ tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => {
151170
+ const toolDefinition = {
151171
+ name,
151172
+ title: tool.title,
151173
+ description: tool.description,
151174
+ inputSchema: tool.inputSchema ? standardSchemaToJsonSchema(tool.inputSchema, "input") : EMPTY_OBJECT_JSON_SCHEMA,
151175
+ annotations: tool.annotations,
151176
+ icons: tool.icons,
151177
+ execution: tool.execution,
151178
+ _meta: tool._meta
151179
+ };
151180
+ if (tool.outputSchema) toolDefinition.outputSchema = standardSchemaToJsonSchema(tool.outputSchema, "output");
151181
+ return toolDefinition;
151182
+ }) }));
151183
+ this.server.setRequestHandler("tools/call", async (request, ctx) => {
151184
+ const tool = this._registeredTools[request.params.name];
151185
+ if (!tool) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} not found`);
151186
+ if (!tool.enabled) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} disabled`);
151187
+ try {
151188
+ const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);
151189
+ const result = await this.executeToolHandler(tool, args, ctx);
151190
+ await this.validateToolOutput(tool, result, request.params.name);
151191
+ if (isInputRequiredResult(result)) return result;
151192
+ return this.server.projectCallToolResult(result, tool.outputSchemaJson);
151193
+ } catch (error3) {
151194
+ if (error3 instanceof ProtocolError && error3.code === ProtocolErrorCode.UrlElicitationRequired) throw error3;
151195
+ return this.createToolError(error3 instanceof Error ? error3.message : String(error3));
151196
+ }
151197
+ });
151198
+ this._toolHandlersInitialized = true;
151199
+ }
151200
+ /**
151201
+ * Creates a tool error result.
151202
+ *
151203
+ * @param errorMessage - The error message.
151204
+ * @returns The tool error result.
151205
+ */
151206
+ createToolError(errorMessage) {
151207
+ return {
151208
+ content: [{
151209
+ type: "text",
151210
+ text: errorMessage
151211
+ }],
151212
+ isError: true
151213
+ };
151214
+ }
151215
+ /**
151216
+ * Validates tool input arguments against the tool's input schema.
151217
+ */
151218
+ async validateToolInput(tool, args, toolName) {
151219
+ if (!tool.inputSchema) return;
151220
+ const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {});
151221
+ if (!parseResult.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`);
151222
+ return parseResult.data;
151223
+ }
151224
+ /**
151225
+ * Validates tool output against the tool's output schema.
151226
+ */
151227
+ async validateToolOutput(tool, result, toolName) {
151228
+ if (!tool.outputSchema) return;
151229
+ if (isInputRequiredResult(result)) return;
151230
+ if (result.isError) return;
151231
+ if (result.structuredContent === void 0) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);
151232
+ const parseResult = await validateStandardSchema(tool.outputSchema, result.structuredContent);
151233
+ if (!parseResult.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`);
151234
+ }
151235
+ /**
151236
+ * Executes a tool handler.
151237
+ */
151238
+ async executeToolHandler(tool, args, ctx) {
151239
+ return tool.executor(args, ctx);
151240
+ }
151241
+ _completionHandlerInitialized = false;
151242
+ setCompletionRequestHandler() {
151243
+ if (this._completionHandlerInitialized) return;
151244
+ this.server.assertCanSetRequestHandler("completion/complete");
151245
+ this.server.registerCapabilities({ completions: {} });
151246
+ this.server.setRequestHandler("completion/complete", async (request) => {
151247
+ switch (request.params.ref.type) {
151248
+ case "ref/prompt":
151249
+ assertCompleteRequestPrompt(request);
151250
+ return this.handlePromptCompletion(request, request.params.ref);
151251
+ case "ref/resource":
151252
+ assertCompleteRequestResourceTemplate(request);
151253
+ return this.handleResourceCompletion(request, request.params.ref);
151254
+ default:
151255
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`);
151256
+ }
151257
+ });
151258
+ this._completionHandlerInitialized = true;
151259
+ }
151260
+ async handlePromptCompletion(request, ref) {
151261
+ const prompt = this._registeredPrompts[ref.name];
151262
+ if (!prompt) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} not found`);
151263
+ if (!prompt.enabled) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} disabled`);
151264
+ if (!prompt.argsSchema) return EMPTY_COMPLETION_RESULT;
151265
+ const field = unwrapOptionalSchema(getSchemaShape(prompt.argsSchema)?.[request.params.argument.name]);
151266
+ if (!isCompletable(field)) return EMPTY_COMPLETION_RESULT;
151267
+ const completer = getCompleter(field);
151268
+ if (!completer) return EMPTY_COMPLETION_RESULT;
151269
+ return createCompletionResult(await completer(request.params.argument.value, request.params.context));
151270
+ }
151271
+ async handleResourceCompletion(request, ref) {
151272
+ const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri);
151273
+ if (!template) {
151274
+ if (this._registeredResources[ref.uri]) return EMPTY_COMPLETION_RESULT;
151275
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`);
151276
+ }
151277
+ const completer = template.resourceTemplate.completeCallback(request.params.argument.name);
151278
+ if (!completer) return EMPTY_COMPLETION_RESULT;
151279
+ return createCompletionResult(await completer(request.params.argument.value, request.params.context));
151280
+ }
151281
+ _resourceHandlersInitialized = false;
151282
+ setResourceRequestHandlers() {
151283
+ if (this._resourceHandlersInitialized) return;
151284
+ this.server.assertCanSetRequestHandler("resources/list");
151285
+ this.server.assertCanSetRequestHandler("resources/templates/list");
151286
+ this.server.assertCanSetRequestHandler("resources/read");
151287
+ this.server.registerCapabilities({ resources: { listChanged: this.server.getCapabilities().resources?.listChanged ?? true } });
151288
+ this.server.setRequestHandler("resources/list", async (_request, ctx) => {
151289
+ const resources = Object.entries(this._registeredResources).filter(([_, resource2]) => resource2.enabled).map(([uri, resource2]) => ({
151290
+ uri,
151291
+ name: resource2.name,
151292
+ ...resource2.metadata
151293
+ }));
151294
+ const templateResources = [];
151295
+ for (const template of Object.values(this._registeredResourceTemplates)) {
151296
+ if (!template.resourceTemplate.listCallback) continue;
151297
+ const result = await template.resourceTemplate.listCallback(ctx);
151298
+ for (const resource2 of result.resources) templateResources.push({
151299
+ ...template.metadata,
151300
+ ...resource2
151301
+ });
151302
+ }
151303
+ return { resources: [...resources, ...templateResources] };
151304
+ });
151305
+ this.server.setRequestHandler("resources/templates/list", async () => {
151306
+ return { resourceTemplates: Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({
151307
+ name,
151308
+ uriTemplate: template.resourceTemplate.uriTemplate.toString(),
151309
+ ...template.metadata
151310
+ })) };
151311
+ });
151312
+ this.server.setRequestHandler("resources/read", async (request, ctx) => {
151313
+ let uri;
151314
+ try {
151315
+ uri = new URL(request.params.uri);
151316
+ } catch {
151317
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Resource URI ${request.params.uri} is invalid`, {
151318
+ uri: request.params.uri,
151319
+ reason: "invalid_uri"
151320
+ });
151321
+ }
151322
+ const resource2 = this._registeredResources[uri.toString()];
151323
+ if (resource2) {
151324
+ if (!resource2.enabled) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Resource ${uri} disabled`);
151325
+ return attachCacheHintFallback(await resource2.readCallback(uri, ctx), resource2.cacheHint);
151326
+ }
151327
+ for (const template of Object.values(this._registeredResourceTemplates)) {
151328
+ const variables = template.resourceTemplate.uriTemplate.match(uri.toString());
151329
+ if (variables) return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint);
151330
+ }
151331
+ throw new ResourceNotFoundError(request.params.uri);
151332
+ });
151333
+ this._resourceHandlersInitialized = true;
151334
+ }
151335
+ _promptHandlersInitialized = false;
151336
+ setPromptRequestHandlers() {
151337
+ if (this._promptHandlersInitialized) return;
151338
+ this.server.assertCanSetRequestHandler("prompts/list");
151339
+ this.server.assertCanSetRequestHandler("prompts/get");
151340
+ this.server.registerCapabilities({ prompts: { listChanged: this.server.getCapabilities().prompts?.listChanged ?? true } });
151341
+ this.server.setRequestHandler("prompts/list", () => ({ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => {
151342
+ return {
151343
+ name,
151344
+ title: prompt.title,
151345
+ description: prompt.description,
151346
+ arguments: prompt.argsSchema ? promptArgumentsFromStandardSchema(prompt.argsSchema) : void 0,
151347
+ icons: prompt.icons,
151348
+ _meta: prompt._meta
151349
+ };
151350
+ }) }));
151351
+ this.server.setRequestHandler("prompts/get", async (request, ctx) => {
151352
+ const prompt = this._registeredPrompts[request.params.name];
151353
+ if (!prompt) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} not found`);
151354
+ if (!prompt.enabled) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`);
151355
+ return prompt.handler(request.params.arguments, ctx);
151356
+ });
151357
+ this._promptHandlersInitialized = true;
151358
+ }
151359
+ registerResource(name, uriOrTemplate, config3, readCallback) {
151360
+ const cacheHint = config3.cacheHint;
151361
+ let metadata = config3;
151362
+ if (cacheHint !== void 0) {
151363
+ assertValidCacheHint(cacheHint, `resource ${name}`);
151364
+ const rest = { ...config3 };
151365
+ delete rest.cacheHint;
151366
+ metadata = rest;
151367
+ }
151368
+ if (typeof uriOrTemplate === "string") {
151369
+ if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`);
151370
+ const registeredResource = this._createRegisteredResource(name, config3.title, uriOrTemplate, metadata, readCallback);
151371
+ if (cacheHint !== void 0) registeredResource.cacheHint = cacheHint;
151372
+ this.setResourceRequestHandlers();
151373
+ this.sendResourceListChanged();
151374
+ return registeredResource;
151375
+ } else {
151376
+ if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`);
151377
+ const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config3.title, uriOrTemplate, metadata, readCallback);
151378
+ if (cacheHint !== void 0) registeredResourceTemplate.cacheHint = cacheHint;
151379
+ this.setResourceRequestHandlers();
151380
+ this.sendResourceListChanged();
151381
+ return registeredResourceTemplate;
151382
+ }
151383
+ }
151384
+ _createRegisteredResource(name, title, uri, metadata, readCallback) {
151385
+ const registeredResource = {
151386
+ name,
151387
+ title,
151388
+ metadata,
151389
+ readCallback,
151390
+ enabled: true,
151391
+ disable: () => registeredResource.update({ enabled: false }),
151392
+ enable: () => registeredResource.update({ enabled: true }),
151393
+ remove: () => registeredResource.update({ uri: null }),
151394
+ update: (updates) => {
151395
+ if (updates.uri !== void 0 && updates.uri !== uri) {
151396
+ delete this._registeredResources[uri];
151397
+ if (updates.uri) this._registeredResources[updates.uri] = registeredResource;
151398
+ }
151399
+ if (updates.name !== void 0) registeredResource.name = updates.name;
151400
+ if (updates.title !== void 0) registeredResource.title = updates.title;
151401
+ if (updates.metadata !== void 0) registeredResource.metadata = updates.metadata;
151402
+ if (updates.callback !== void 0) registeredResource.readCallback = updates.callback;
151403
+ if (updates.enabled !== void 0) registeredResource.enabled = updates.enabled;
151404
+ this.sendResourceListChanged();
151405
+ }
151406
+ };
151407
+ this._registeredResources[uri] = registeredResource;
151408
+ return registeredResource;
151409
+ }
151410
+ _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) {
151411
+ const registeredResourceTemplate = {
151412
+ resourceTemplate: template,
151413
+ title,
151414
+ metadata,
151415
+ readCallback,
151416
+ enabled: true,
151417
+ disable: () => registeredResourceTemplate.update({ enabled: false }),
151418
+ enable: () => registeredResourceTemplate.update({ enabled: true }),
151419
+ remove: () => registeredResourceTemplate.update({ name: null }),
151420
+ update: (updates) => {
151421
+ if (updates.name !== void 0 && updates.name !== name) {
151422
+ delete this._registeredResourceTemplates[name];
151423
+ if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate;
151424
+ }
151425
+ if (updates.title !== void 0) registeredResourceTemplate.title = updates.title;
151426
+ if (updates.template !== void 0) registeredResourceTemplate.resourceTemplate = updates.template;
151427
+ if (updates.metadata !== void 0) registeredResourceTemplate.metadata = updates.metadata;
151428
+ if (updates.callback !== void 0) registeredResourceTemplate.readCallback = updates.callback;
151429
+ if (updates.enabled !== void 0) registeredResourceTemplate.enabled = updates.enabled;
151430
+ this.sendResourceListChanged();
151431
+ }
151432
+ };
151433
+ this._registeredResourceTemplates[name] = registeredResourceTemplate;
151434
+ const variableNames = template.uriTemplate.variableNames;
151435
+ if (Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v))) this.setCompletionRequestHandler();
151436
+ return registeredResourceTemplate;
151437
+ }
151438
+ _createRegisteredPrompt(name, title, description8, argsSchema, callback, icons, _meta) {
151439
+ let currentArgsSchema = argsSchema;
151440
+ let currentCallback = callback;
151441
+ const registeredPrompt = {
151442
+ title,
151443
+ description: description8,
151444
+ argsSchema,
151445
+ icons,
151446
+ _meta,
151447
+ handler: createPromptHandler(name, argsSchema, callback),
151448
+ enabled: true,
151449
+ disable: () => registeredPrompt.update({ enabled: false }),
151450
+ enable: () => registeredPrompt.update({ enabled: true }),
151451
+ remove: () => registeredPrompt.update({ name: null }),
151452
+ update: (updates) => {
151453
+ if (updates.name !== void 0 && updates.name !== name) {
151454
+ delete this._registeredPrompts[name];
151455
+ if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt;
151456
+ }
151457
+ if (updates.title !== void 0) registeredPrompt.title = updates.title;
151458
+ if (updates.description !== void 0) registeredPrompt.description = updates.description;
151459
+ if (updates.icons !== void 0) registeredPrompt.icons = updates.icons;
151460
+ if (updates._meta !== void 0) registeredPrompt._meta = updates._meta;
151461
+ let needsHandlerRegen = false;
151462
+ if (updates.argsSchema !== void 0) {
151463
+ registeredPrompt.argsSchema = updates.argsSchema;
151464
+ currentArgsSchema = updates.argsSchema;
151465
+ needsHandlerRegen = true;
151466
+ }
151467
+ if (updates.callback !== void 0) {
151468
+ currentCallback = updates.callback;
151469
+ needsHandlerRegen = true;
151470
+ }
151471
+ if (needsHandlerRegen) registeredPrompt.handler = createPromptHandler(name, currentArgsSchema, currentCallback);
151472
+ if (updates.enabled !== void 0) registeredPrompt.enabled = updates.enabled;
151473
+ this.sendPromptListChanged();
151474
+ }
151475
+ };
151476
+ this._registeredPrompts[name] = registeredPrompt;
151477
+ if (argsSchema) {
151478
+ const shape = getSchemaShape(argsSchema);
151479
+ if (shape) {
151480
+ if (Object.values(shape).some((field) => {
151481
+ return isCompletable(unwrapOptionalSchema(field));
151482
+ })) this.setCompletionRequestHandler();
151483
+ }
151484
+ }
151485
+ return registeredPrompt;
151486
+ }
151487
+ _createRegisteredTool(name, title, description8, inputSchema9, outputSchema9, annotations, icons, execution, _meta, handler) {
151488
+ validateAndWarnToolName(name);
151489
+ if (inputSchema9 !== void 0) try {
151490
+ const json = standardSchemaToJsonSchema(inputSchema9, "input");
151491
+ this._toolInputSchemaJson[name] = json;
151492
+ const scan = scanXMcpHeaderDeclarations(json);
151493
+ if (!scan.valid) console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`);
151494
+ } catch {
151495
+ }
151496
+ let currentHandler = handler;
151497
+ const registeredTool = {
151498
+ title,
151499
+ description: description8,
151500
+ inputSchema: inputSchema9,
151501
+ outputSchema: outputSchema9,
151502
+ outputSchemaJson: convertOutputSchemaJson(outputSchema9),
151503
+ annotations,
151504
+ icons,
151505
+ execution,
151506
+ _meta,
151507
+ handler,
151508
+ executor: createToolExecutor(inputSchema9, handler),
151509
+ enabled: true,
151510
+ disable: () => registeredTool.update({ enabled: false }),
151511
+ enable: () => registeredTool.update({ enabled: true }),
151512
+ remove: () => registeredTool.update({ name: null }),
151513
+ update: (updates) => {
151514
+ if (updates.name !== void 0 && updates.name !== name) {
151515
+ if (typeof updates.name === "string") validateAndWarnToolName(updates.name);
151516
+ delete this._registeredTools[name];
151517
+ delete this._toolInputSchemaJson[name];
151518
+ if (updates.name) {
151519
+ delete this._toolInputSchemaJson[updates.name];
151520
+ this._registeredTools[updates.name] = registeredTool;
151521
+ name = updates.name;
151522
+ }
151523
+ }
151524
+ if (updates.title !== void 0) registeredTool.title = updates.title;
151525
+ if (updates.description !== void 0) registeredTool.description = updates.description;
151526
+ let needsExecutorRegen = false;
151527
+ if (updates.paramsSchema !== void 0) {
151528
+ registeredTool.inputSchema = updates.paramsSchema;
151529
+ delete this._toolInputSchemaJson[name];
151530
+ needsExecutorRegen = true;
151531
+ }
151532
+ if (updates.callback !== void 0) {
151533
+ registeredTool.handler = updates.callback;
151534
+ currentHandler = updates.callback;
151535
+ needsExecutorRegen = true;
151536
+ }
151537
+ if (needsExecutorRegen) registeredTool.executor = createToolExecutor(registeredTool.inputSchema, currentHandler);
151538
+ if (updates.outputSchema !== void 0) {
151539
+ registeredTool.outputSchema = updates.outputSchema;
151540
+ registeredTool.outputSchemaJson = convertOutputSchemaJson(updates.outputSchema);
151541
+ }
151542
+ if (updates.annotations !== void 0) registeredTool.annotations = updates.annotations;
151543
+ if (updates.icons !== void 0) registeredTool.icons = updates.icons;
151544
+ if (updates._meta !== void 0) registeredTool._meta = updates._meta;
151545
+ if (updates.enabled !== void 0) registeredTool.enabled = updates.enabled;
151546
+ this.sendToolListChanged();
151547
+ }
151548
+ };
151549
+ this._registeredTools[name] = registeredTool;
151550
+ this.setToolRequestHandlers();
151551
+ this.sendToolListChanged();
151552
+ return registeredTool;
151553
+ }
151554
+ registerTool(name, config3, cb) {
151555
+ if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`);
151556
+ const { title, description: description8, inputSchema: inputSchema9, outputSchema: outputSchema9, annotations, icons, _meta } = config3;
151557
+ return this._createRegisteredTool(name, title, description8, normalizeRawShapeSchema(inputSchema9), normalizeRawShapeSchema(outputSchema9), annotations, icons, void 0, _meta, cb);
151558
+ }
151559
+ registerPrompt(name, config3, cb) {
151560
+ if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`);
151561
+ const { title, description: description8, argsSchema, icons, _meta } = config3;
151562
+ const registeredPrompt = this._createRegisteredPrompt(name, title, description8, normalizeRawShapeSchema(argsSchema), cb, icons, _meta);
151563
+ this.setPromptRequestHandlers();
151564
+ this.sendPromptListChanged();
151565
+ return registeredPrompt;
151566
+ }
151567
+ /**
151568
+ * Checks if the server is connected to a transport.
151569
+ * @returns `true` if the server is connected
151570
+ */
151571
+ isConnected() {
151572
+ return this.server.transport !== void 0;
151573
+ }
151574
+ /**
151575
+ * Sends a logging message to the client, if connected.
151576
+ * Note: You only need to send the parameters object, not the entire JSON-RPC message.
151577
+ * @see {@linkcode LoggingMessageNotification}
151578
+ * @param params
151579
+ * @param sessionId Optional for stateless transports and backward compatibility.
151580
+ *
151581
+ * @example
151582
+ * ```ts source="./mcp.examples.ts#McpServer_sendLoggingMessage_basic"
151583
+ * await server.sendLoggingMessage({
151584
+ * level: 'info',
151585
+ * data: 'Processing complete'
151586
+ * });
151587
+ * ```
151588
+ *
151589
+ * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).
151590
+ * Remains functional during the deprecation window (at least twelve months).
151591
+ * Migrate to stderr logging (STDIO servers) or OpenTelemetry.
151592
+ */
151593
+ async sendLoggingMessage(params, sessionId) {
151594
+ return this.server.sendLoggingMessage(params, sessionId);
151595
+ }
151596
+ /**
151597
+ * Sends a resource list changed event to the client, if connected.
151598
+ */
151599
+ sendResourceListChanged() {
151600
+ if (this.isConnected()) this.server.sendResourceListChanged();
151601
+ }
151602
+ /**
151603
+ * Sends a tool list changed event to the client, if connected.
151604
+ */
151605
+ sendToolListChanged() {
151606
+ if (this.isConnected()) this.server.sendToolListChanged();
151607
+ }
151608
+ /**
151609
+ * Sends a prompt list changed event to the client, if connected.
151610
+ */
151611
+ sendPromptListChanged() {
151612
+ if (this.isConnected()) this.server.sendPromptListChanged();
151613
+ }
151614
+ };
151615
+ function createToolExecutor(inputSchema9, handler) {
151616
+ if (inputSchema9) {
151617
+ const callback$1 = handler;
151618
+ return async (args, ctx) => callback$1(args, ctx);
151619
+ }
151620
+ const callback = handler;
151621
+ return async (_args, ctx) => callback(ctx);
151622
+ }
151623
+ var EMPTY_OBJECT_JSON_SCHEMA = {
151624
+ type: "object",
151625
+ properties: {}
151626
+ };
151627
+ function convertOutputSchemaJson(outputSchema9) {
151628
+ if (outputSchema9 === void 0) return void 0;
151629
+ try {
151630
+ return standardSchemaToJsonSchema(outputSchema9, "output");
151631
+ } catch {
151632
+ return;
151633
+ }
151634
+ }
151635
+ function createPromptHandler(name, argsSchema, callback) {
151636
+ if (argsSchema) {
151637
+ const typedCallback = callback;
151638
+ return async (args, ctx) => {
151639
+ const parseResult = await validateStandardSchema(argsSchema, args);
151640
+ if (!parseResult.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid arguments for prompt ${name}: ${parseResult.error}`);
151641
+ return typedCallback(parseResult.data, ctx);
151642
+ };
151643
+ } else {
151644
+ const typedCallback = callback;
151645
+ return async (_args, ctx) => {
151646
+ return typedCallback(ctx);
151647
+ };
151648
+ }
151649
+ }
151650
+ function createCompletionResult(suggestions) {
151651
+ return { completion: {
151652
+ values: suggestions.map(String).slice(0, 100),
151653
+ total: suggestions.length,
151654
+ hasMore: suggestions.length > 100
151655
+ } };
151656
+ }
151657
+ var EMPTY_COMPLETION_RESULT = { completion: {
151658
+ values: [],
151659
+ hasMore: false
151660
+ } };
151661
+ function getSchemaShape(schema2) {
151662
+ const candidate = schema2;
151663
+ if (candidate.shape && typeof candidate.shape === "object") return candidate.shape;
151664
+ }
151665
+ function isOptionalSchema(schema2) {
151666
+ return schema2?.type === "optional";
151667
+ }
151668
+ function unwrapOptionalSchema(schema2) {
151669
+ if (!isOptionalSchema(schema2)) return schema2;
151670
+ return schema2.def?.innerType ?? schema2;
151671
+ }
150676
151672
 
150677
151673
  // ../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/stdio.mjs
150678
151674
  var StdioServerTransport = class {
@@ -150763,6 +151759,400 @@ var StdioServerTransport = class {
150763
151759
  });
150764
151760
  }
150765
151761
  };
151762
+ var DISCARD_ANSWER_TIMEOUT_MS = 3e3;
151763
+ var StdioConnectionChannel = class {
151764
+ onclose;
151765
+ onerror;
151766
+ onmessage;
151767
+ _closed = false;
151768
+ /** Request ids the entry delivered to the instance that the instance has not yet answered. */
151769
+ _pendingRequests = /* @__PURE__ */ new Set();
151770
+ _drainWaiters = [];
151771
+ constructor(_wire, _onInstanceClose, _outboundIntercept) {
151772
+ this._wire = _wire;
151773
+ this._onInstanceClose = _onInstanceClose;
151774
+ this._outboundIntercept = _outboundIntercept;
151775
+ }
151776
+ async start() {
151777
+ }
151778
+ async send(message, options) {
151779
+ if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
151780
+ const { id } = message;
151781
+ if (id !== void 0) this._settle(id);
151782
+ }
151783
+ if (this._closed) return;
151784
+ if (this._outboundIntercept?.(message) === "handled") return;
151785
+ return this._wire.send(message, options);
151786
+ }
151787
+ setProtocolVersion = (version4) => {
151788
+ this._wire.setProtocolVersion?.(version4);
151789
+ };
151790
+ /** Forwards one inbound message to the connected instance. */
151791
+ deliver(message, extra) {
151792
+ if (this._closed) return;
151793
+ if (isJSONRPCRequest(message)) this._pendingRequests.add(message.id);
151794
+ else if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") {
151795
+ const cancelledId = message.params?.requestId;
151796
+ if (cancelledId !== void 0) this._settle(cancelledId);
151797
+ }
151798
+ this.onmessage?.(message, extra);
151799
+ }
151800
+ /**
151801
+ * Resolves once every request delivered to the instance has been answered
151802
+ * through {@linkcode send}, settled by a delivered cancellation, or the
151803
+ * channel has been closed and nothing further can be answered. The wait is
151804
+ * bounded by `timeoutMs` as a backstop so no edge can hold the caller
151805
+ * indefinitely; resolves `false` only when the bound elapsed with requests
151806
+ * still unanswered. Used by the probe-discard path so a probe request the
151807
+ * entry accepted is never silently dropped.
151808
+ */
151809
+ async whenRequestsAnswered(timeoutMs) {
151810
+ if (this._closed || this._pendingRequests.size === 0) return true;
151811
+ return await new Promise((resolve2) => {
151812
+ const waiter = () => {
151813
+ clearTimeout(timer);
151814
+ resolve2(true);
151815
+ };
151816
+ const timer = setTimeout(() => {
151817
+ this._drainWaiters = this._drainWaiters.filter((pending) => pending !== waiter);
151818
+ resolve2(false);
151819
+ }, timeoutMs);
151820
+ this._drainWaiters.push(waiter);
151821
+ });
151822
+ }
151823
+ async close() {
151824
+ if (this._closed) return;
151825
+ this._closed = true;
151826
+ this._pendingRequests.clear();
151827
+ this._releaseDrainWaiters();
151828
+ try {
151829
+ this._onInstanceClose();
151830
+ } finally {
151831
+ this.onclose?.();
151832
+ }
151833
+ }
151834
+ _settle(id) {
151835
+ this._pendingRequests.delete(id);
151836
+ if (this._pendingRequests.size === 0) this._releaseDrainWaiters();
151837
+ }
151838
+ _releaseDrainWaiters() {
151839
+ const waiters = this._drainWaiters;
151840
+ this._drainWaiters = [];
151841
+ for (const waiter of waiters) waiter();
151842
+ }
151843
+ };
151844
+ function classifyOpeningMessage(message) {
151845
+ const params = message.params;
151846
+ if (message.method === "initialize" && !carriesValidModernEnvelopeClaim(params)) {
151847
+ const requestedVersion = params !== null && typeof params === "object" && typeof params.protocolVersion === "string" ? params.protocolVersion : void 0;
151848
+ return {
151849
+ kind: "legacy",
151850
+ reason: "initialize",
151851
+ ...requestedVersion !== void 0 && { requestedVersion }
151852
+ };
151853
+ }
151854
+ if (!hasEnvelopeClaim(params)) return {
151855
+ kind: "legacy",
151856
+ reason: "no-claim"
151857
+ };
151858
+ const meta2 = requestMetaOf(params);
151859
+ const firstIssue = (meta2 === void 0 ? [] : validateEnvelopeMeta(meta2))[0];
151860
+ if (firstIssue !== void 0) return {
151861
+ kind: "invalid-envelope",
151862
+ issue: firstIssue
151863
+ };
151864
+ const claimedVersion = envelopeClaimVersion(params);
151865
+ if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) return {
151866
+ kind: "unsupported-revision",
151867
+ requested: claimedVersion ?? "unknown"
151868
+ };
151869
+ return {
151870
+ kind: "modern",
151871
+ revision: claimedVersion,
151872
+ classification: {
151873
+ era: "modern",
151874
+ revision: claimedVersion
151875
+ }
151876
+ };
151877
+ }
151878
+ function serveStdio(factory, options = {}) {
151879
+ const legacyMode = options.legacy ?? "serve";
151880
+ const wire = options.transport ?? new StdioServerTransport();
151881
+ let state = { phase: "opening" };
151882
+ let discarding;
151883
+ let closing = false;
151884
+ const isTornDown = () => closing || state.phase === "closed";
151885
+ const reportError = (error3) => {
151886
+ try {
151887
+ options.onerror?.(error3);
151888
+ } catch {
151889
+ }
151890
+ };
151891
+ const writeErrorResponse = (id, code2, message, data2) => wire.send({
151892
+ jsonrpc: "2.0",
151893
+ id,
151894
+ error: {
151895
+ code: code2,
151896
+ message,
151897
+ ...data2 !== void 0 && { data: data2 }
151898
+ }
151899
+ }).catch((error3) => reportError(toError(error3)));
151900
+ const listenRouter = new StdioListenRouter(options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS);
151901
+ const modernOutboundIntercept = (message) => {
151902
+ if (!isJSONRPCNotification(message)) return void 0;
151903
+ const routed = listenRouter.routeOutbound(message);
151904
+ if (routed === "passthrough") return void 0;
151905
+ for (const stamped of routed) wire.send({
151906
+ jsonrpc: "2.0",
151907
+ ...stamped
151908
+ }).catch((error3) => reportError(toError(error3)));
151909
+ return "handled";
151910
+ };
151911
+ const tryServeListen = async (message) => {
151912
+ if (isJSONRPCRequest(message) && message.method === "subscriptions/listen") {
151913
+ const meta2 = requestMetaOf(message.params);
151914
+ const issue2 = hasEnvelopeClaim(message.params) ? (meta2 === void 0 ? [] : validateEnvelopeMeta(meta2))[0] : {
151915
+ key: "_meta",
151916
+ problem: "the per-request envelope is required on protocol revision 2026-07-28"
151917
+ };
151918
+ const claimedVersion = envelopeClaimVersion(message.params);
151919
+ let reply;
151920
+ if (issue2 !== void 0) reply = {
151921
+ jsonrpc: "2.0",
151922
+ id: message.id,
151923
+ error: {
151924
+ code: -32602,
151925
+ message: `Invalid _meta envelope: ${issue2.key}: ${issue2.problem}`
151926
+ }
151927
+ };
151928
+ else if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) {
151929
+ const error3 = new UnsupportedProtocolVersionError({
151930
+ supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS],
151931
+ requested: claimedVersion ?? "unknown"
151932
+ });
151933
+ reply = {
151934
+ jsonrpc: "2.0",
151935
+ id: message.id,
151936
+ error: {
151937
+ code: error3.code,
151938
+ message: error3.message,
151939
+ data: error3.data
151940
+ }
151941
+ };
151942
+ } else reply = listenRouter.serve(message);
151943
+ await wire.send("error" in reply ? reply : {
151944
+ jsonrpc: "2.0",
151945
+ method: reply.method,
151946
+ params: reply.params
151947
+ }).catch((error3) => reportError(toError(error3)));
151948
+ return true;
151949
+ }
151950
+ if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") {
151951
+ const cancelledId = message.params?.requestId;
151952
+ if (cancelledId !== void 0 && listenRouter.cancel(cancelledId)) return true;
151953
+ }
151954
+ return false;
151955
+ };
151956
+ const answerLegacyRejection = (request, reason, requestedVersion) => {
151957
+ const rejection2 = modernOnlyStrictRejection({
151958
+ kind: "legacy",
151959
+ reason,
151960
+ ...requestedVersion !== void 0 && { requestedVersion }
151961
+ }, SUPPORTED_MODERN_PROTOCOL_VERSIONS);
151962
+ if (rejection2 === void 0) return Promise.resolve();
151963
+ reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only stdio connection (${rejection2.cell}): ${rejection2.message}`));
151964
+ return writeErrorResponse(request.id, rejection2.code, rejection2.message, rejection2.data);
151965
+ };
151966
+ const onInstanceClosed = (channel) => {
151967
+ if (closing || channel === discarding) return;
151968
+ closeAll();
151969
+ };
151970
+ const connectInstance = async (era, revision) => {
151971
+ const product = await factory({ era });
151972
+ const server = product instanceof McpServer ? product.server : product;
151973
+ if (era === "modern") {
151974
+ setNegotiatedProtocolVersion(server, revision);
151975
+ installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS);
151976
+ listenRouter.setServerCapabilities(server.getCapabilities(), serverIdentityOf(server));
151977
+ }
151978
+ const channel = new StdioConnectionChannel(wire, () => onInstanceClosed(channel), era === "modern" ? modernOutboundIntercept : void 0);
151979
+ await product.connect(channel);
151980
+ return {
151981
+ product,
151982
+ channel
151983
+ };
151984
+ };
151985
+ const disposeLateInstance = (instance) => instance.product.close().catch((error3) => reportError(toError(error3)));
151986
+ const discardProbeInstance = async (instance) => {
151987
+ discarding = instance.channel;
151988
+ try {
151989
+ if (!await instance.channel.whenRequestsAnswered(DISCARD_ANSWER_TIMEOUT_MS)) reportError(/* @__PURE__ */ new Error(`Discarded the probe instance with requests still unanswered after ${DISCARD_ANSWER_TIMEOUT_MS}ms; continuing with the fallback`));
151990
+ await instance.product.close();
151991
+ } catch (error3) {
151992
+ reportError(toError(error3));
151993
+ } finally {
151994
+ discarding = void 0;
151995
+ }
151996
+ };
151997
+ const processMessage = async (message) => {
151998
+ if (state.phase === "closed") return;
151999
+ if (state.phase === "pinned") {
152000
+ if (state.era === "modern" && isJSONRPCRequest(message) && message.method === "initialize" && !carriesValidModernEnvelopeClaim(message.params)) {
152001
+ await answerLegacyRejection(message, "initialize", message.params !== null && typeof message.params === "object" && typeof message.params.protocolVersion === "string" ? message.params.protocolVersion : void 0);
152002
+ return;
152003
+ }
152004
+ if (state.era === "modern" && await tryServeListen(message)) return;
152005
+ state.instance.channel.deliver(message);
152006
+ return;
152007
+ }
152008
+ if (!isJSONRPCRequest(message) && !isJSONRPCNotification(message)) {
152009
+ reportError(/* @__PURE__ */ new Error("Discarded a JSON-RPC response received before the connection negotiated an era"));
152010
+ return;
152011
+ }
152012
+ const opening = classifyOpeningMessage(message);
152013
+ switch (opening.kind) {
152014
+ case "invalid-envelope": {
152015
+ const detail = `Invalid _meta envelope for protocol revision 2026-07-28: ${opening.issue.key}: ${opening.issue.problem}`;
152016
+ if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InvalidParams, detail, { envelope: opening.issue });
152017
+ else reportError(/* @__PURE__ */ new Error(`Discarded a notification with a malformed envelope: ${detail}`));
152018
+ return;
152019
+ }
152020
+ case "unsupported-revision":
152021
+ if (isJSONRPCRequest(message)) {
152022
+ const error3 = new UnsupportedProtocolVersionError({
152023
+ supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS],
152024
+ requested: opening.requested
152025
+ });
152026
+ reportError(error3);
152027
+ await writeErrorResponse(message.id, error3.code, error3.message, error3.data);
152028
+ } else reportError(/* @__PURE__ */ new Error(`Discarded a notification claiming unsupported protocol revision ${opening.requested}`));
152029
+ return;
152030
+ case "modern":
152031
+ if (isJSONRPCRequest(message) && message.method === "server/discover") {
152032
+ if (state.phase === "probe") {
152033
+ state.instance.channel.deliver(message, { classification: opening.classification });
152034
+ return;
152035
+ }
152036
+ const instance = await connectInstance("modern", opening.revision);
152037
+ if (isTornDown()) {
152038
+ await disposeLateInstance(instance);
152039
+ return;
152040
+ }
152041
+ state = {
152042
+ phase: "probe",
152043
+ instance
152044
+ };
152045
+ instance.channel.deliver(message, { classification: opening.classification });
152046
+ return;
152047
+ }
152048
+ if (state.phase === "probe") {
152049
+ if (isJSONRPCNotification(message)) {
152050
+ state.instance.channel.deliver(message, { classification: opening.classification });
152051
+ return;
152052
+ }
152053
+ state = {
152054
+ phase: "pinned",
152055
+ era: "modern",
152056
+ instance: state.instance
152057
+ };
152058
+ } else {
152059
+ const instance = await connectInstance("modern", opening.revision);
152060
+ if (isTornDown()) {
152061
+ await disposeLateInstance(instance);
152062
+ return;
152063
+ }
152064
+ state = {
152065
+ phase: "pinned",
152066
+ era: "modern",
152067
+ instance
152068
+ };
152069
+ }
152070
+ if (await tryServeListen(message)) return;
152071
+ state.instance.channel.deliver(message, { classification: opening.classification });
152072
+ return;
152073
+ case "legacy": {
152074
+ if (legacyMode === "reject") {
152075
+ if (isJSONRPCRequest(message)) await answerLegacyRejection(message, opening.reason, opening.requestedVersion);
152076
+ return;
152077
+ }
152078
+ if (state.phase === "probe") {
152079
+ await discardProbeInstance(state.instance);
152080
+ if (isTornDown()) return;
152081
+ state = { phase: "opening" };
152082
+ }
152083
+ const instance = await connectInstance("legacy");
152084
+ if (isTornDown()) {
152085
+ await disposeLateInstance(instance);
152086
+ return;
152087
+ }
152088
+ state = {
152089
+ phase: "pinned",
152090
+ era: "legacy",
152091
+ instance
152092
+ };
152093
+ state.instance.channel.deliver(message);
152094
+ return;
152095
+ }
152096
+ }
152097
+ };
152098
+ const queue = [];
152099
+ let pumping = false;
152100
+ const pump = async () => {
152101
+ if (pumping) return;
152102
+ pumping = true;
152103
+ try {
152104
+ while (queue.length > 0) {
152105
+ const message = queue.shift();
152106
+ try {
152107
+ await processMessage(message);
152108
+ } catch (error3) {
152109
+ if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InternalError, "Internal server error");
152110
+ reportError(toError(error3));
152111
+ }
152112
+ }
152113
+ } finally {
152114
+ pumping = false;
152115
+ }
152116
+ };
152117
+ const closeAll = async () => {
152118
+ if (closing || state.phase === "closed") return;
152119
+ closing = true;
152120
+ const current = state;
152121
+ state = { phase: "closed" };
152122
+ for (const result of listenRouter.teardownAll()) await wire.send(result).catch((error3) => reportError(toError(error3)));
152123
+ if (current.phase === "probe" || current.phase === "pinned") await current.instance.product.close().catch((error3) => reportError(toError(error3)));
152124
+ await wire.close().catch((error3) => reportError(toError(error3)));
152125
+ };
152126
+ wire.onmessage = (message) => {
152127
+ queue.push(message);
152128
+ pump();
152129
+ };
152130
+ wire.onerror = (error3) => {
152131
+ reportError(error3);
152132
+ if (state.phase === "probe" || state.phase === "pinned") state.instance.channel.onerror?.(error3);
152133
+ };
152134
+ wire.onclose = () => {
152135
+ if (closing || state.phase === "closed") return;
152136
+ closing = true;
152137
+ const current = state;
152138
+ state = { phase: "closed" };
152139
+ if (current.phase === "probe" || current.phase === "pinned") current.instance.product.close().catch((error3) => reportError(toError(error3)));
152140
+ };
152141
+ const started = wire.start().catch((error3) => {
152142
+ reportError(toError(error3));
152143
+ throw error3;
152144
+ });
152145
+ started.catch(() => {
152146
+ });
152147
+ return { close: async () => {
152148
+ await started.catch(() => {
152149
+ });
152150
+ await closeAll();
152151
+ } };
152152
+ }
152153
+ function toError(value) {
152154
+ return value instanceof Error ? value : new Error(String(value));
152155
+ }
150766
152156
 
150767
152157
  // src/cli/lib/mcp/requestContext.ts
150768
152158
  init_fs();
@@ -153159,11 +154549,7 @@ mcp.command("start").summary("Start the MCP server").description(
153159
154549
  ).addDeploymentSelectionOptions(actionDescription("Run the MCP server on")).action(async (options) => {
153160
154550
  const ctx = await oneoffContext(options);
153161
154551
  try {
153162
- const server = makeServer(options);
153163
- const transport = new StdioServerTransport();
153164
- await server.connect(transport);
153165
- await new Promise(() => {
153166
- });
154552
+ enabledTools(options);
153167
154553
  } catch (error3) {
153168
154554
  await ctx.crash({
153169
154555
  exitCode: 1,
@@ -153172,8 +154558,17 @@ mcp.command("start").summary("Start the MCP server").description(
153172
154558
  printedMessage: `Failed to start MCP server: ${error3}`
153173
154559
  });
153174
154560
  }
154561
+ serveStdio(() => makeServer(options), {
154562
+ legacy: "serve",
154563
+ // The only channel for out-of-band failures (transport errors, dropped
154564
+ // malformed notifications). stdout carries the protocol, so they go to
154565
+ // stderr.
154566
+ onerror: (error3) => logError(`MCP server error: ${error3.message}`)
154567
+ });
154568
+ await new Promise(() => {
154569
+ });
153175
154570
  });
153176
- function makeServer(options) {
154571
+ function enabledTools(options) {
153177
154572
  const disabledToolNames = /* @__PURE__ */ new Set();
153178
154573
  for (const toolName of options.disableTools?.split(",") ?? []) {
153179
154574
  const name = toolName.trim();
@@ -153190,6 +154585,10 @@ function makeServer(options) {
153190
154585
  enabledToolsByName[tool.name] = tool;
153191
154586
  }
153192
154587
  }
154588
+ return enabledToolsByName;
154589
+ }
154590
+ function makeServer(options) {
154591
+ const enabledToolsByName = enabledTools(options);
153193
154592
  const mutex = new Mutex();
153194
154593
  const server = new Server(
153195
154594
  {