@hiberus-magento/magento-rest 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -40,6 +40,110 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
40
40
  ));
41
41
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
42
42
 
43
+ // ../../node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js
44
+ var require_content_type = __commonJS({
45
+ "../../node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js"(exports) {
46
+ "use strict";
47
+ var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g;
48
+ var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/;
49
+ var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
50
+ var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g;
51
+ var QUOTE_REGEXP = /([\\"])/g;
52
+ var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
53
+ exports.format = format;
54
+ exports.parse = parse3;
55
+ function format(obj) {
56
+ if (!obj || typeof obj !== "object") {
57
+ throw new TypeError("argument obj is required");
58
+ }
59
+ var parameters = obj.parameters;
60
+ var type = obj.type;
61
+ if (!type || !TYPE_REGEXP.test(type)) {
62
+ throw new TypeError("invalid type");
63
+ }
64
+ var string4 = type;
65
+ if (parameters && typeof parameters === "object") {
66
+ var param;
67
+ var params2 = Object.keys(parameters).sort();
68
+ for (var i = 0; i < params2.length; i++) {
69
+ param = params2[i];
70
+ if (!TOKEN_REGEXP.test(param)) {
71
+ throw new TypeError("invalid parameter name");
72
+ }
73
+ string4 += "; " + param + "=" + qstring(parameters[param]);
74
+ }
75
+ }
76
+ return string4;
77
+ }
78
+ function parse3(string4) {
79
+ if (!string4) {
80
+ throw new TypeError("argument string is required");
81
+ }
82
+ var header = typeof string4 === "object" ? getcontenttype(string4) : string4;
83
+ if (typeof header !== "string") {
84
+ throw new TypeError("argument string is required to be a string");
85
+ }
86
+ var index = header.indexOf(";");
87
+ var type = index !== -1 ? header.slice(0, index).trim() : header.trim();
88
+ if (!TYPE_REGEXP.test(type)) {
89
+ throw new TypeError("invalid media type");
90
+ }
91
+ var obj = new ContentType(type.toLowerCase());
92
+ if (index !== -1) {
93
+ var key;
94
+ var match;
95
+ var value;
96
+ PARAM_REGEXP.lastIndex = index;
97
+ while (match = PARAM_REGEXP.exec(header)) {
98
+ if (match.index !== index) {
99
+ throw new TypeError("invalid parameter format");
100
+ }
101
+ index += match[0].length;
102
+ key = match[1].toLowerCase();
103
+ value = match[2];
104
+ if (value.charCodeAt(0) === 34) {
105
+ value = value.slice(1, -1);
106
+ if (value.indexOf("\\") !== -1) {
107
+ value = value.replace(QESC_REGEXP, "$1");
108
+ }
109
+ }
110
+ obj.parameters[key] = value;
111
+ }
112
+ if (index !== header.length) {
113
+ throw new TypeError("invalid parameter format");
114
+ }
115
+ }
116
+ return obj;
117
+ }
118
+ function getcontenttype(obj) {
119
+ var header;
120
+ if (typeof obj.getHeader === "function") {
121
+ header = obj.getHeader("content-type");
122
+ } else if (typeof obj.headers === "object") {
123
+ header = obj.headers && obj.headers["content-type"];
124
+ }
125
+ if (typeof header !== "string") {
126
+ throw new TypeError("content-type header is missing from object");
127
+ }
128
+ return header;
129
+ }
130
+ function qstring(val) {
131
+ var str = String(val);
132
+ if (TOKEN_REGEXP.test(str)) {
133
+ return str;
134
+ }
135
+ if (str.length > 0 && !TEXT_REGEXP.test(str)) {
136
+ throw new TypeError("invalid parameter value");
137
+ }
138
+ return '"' + str.replace(QUOTE_REGEXP, "\\$1") + '"';
139
+ }
140
+ function ContentType(type) {
141
+ this.parameters = /* @__PURE__ */ Object.create(null);
142
+ this.type = type;
143
+ }
144
+ }
145
+ });
146
+
43
147
  // ../../node_modules/.pnpm/sql-escaper@1.5.2/node_modules/sql-escaper/lib/index.js
44
148
  var require_lib = __commonJS({
45
149
  "../../node_modules/.pnpm/sql-escaper@1.5.2/node_modules/sql-escaper/lib/index.js"(exports) {
@@ -1215,19 +1319,19 @@ var require_ring_queue = __commonJS({
1215
1319
  return items;
1216
1320
  }
1217
1321
  _grow() {
1218
- const list2 = this._list;
1219
- const capacity = list2.length;
1322
+ const list3 = this._list;
1323
+ const capacity = list3.length;
1220
1324
  if (this._head === 0) {
1221
1325
  this._tail = capacity;
1222
- list2.length = capacity << 1;
1326
+ list3.length = capacity << 1;
1223
1327
  } else {
1224
1328
  const grown = new Array(capacity << 1);
1225
1329
  let count = 0;
1226
1330
  for (let slot = this._head; slot < capacity; slot++) {
1227
- grown[count++] = list2[slot];
1331
+ grown[count++] = list3[slot];
1228
1332
  }
1229
1333
  for (let slot = 0; slot < this._tail; slot++) {
1230
- grown[count++] = list2[slot];
1334
+ grown[count++] = list3[slot];
1231
1335
  }
1232
1336
  this._list = grown;
1233
1337
  this._head = 0;
@@ -6512,11 +6616,11 @@ ${msg}:
6512
6616
  `);
6513
6617
  }
6514
6618
  exports.printDebugWithCode = printDebugWithCode;
6515
- function typeMatch(type, list2, Types) {
6516
- if (Array.isArray(list2)) {
6517
- return list2.some((t) => type === Types[t]);
6619
+ function typeMatch(type, list3, Types) {
6620
+ if (Array.isArray(list3)) {
6621
+ return list3.some((t) => type === Types[t]);
6518
6622
  }
6519
- return !!list2;
6623
+ return !!list3;
6520
6624
  }
6521
6625
  exports.typeMatch = typeMatch;
6522
6626
  var privateObjectProps = /* @__PURE__ */ new Set([
@@ -8125,9 +8229,9 @@ var require_client = __commonJS({
8125
8229
  var require_auth_41 = __commonJS({
8126
8230
  "../../node_modules/.pnpm/mysql2@3.24.6_@types+node@26.5.0/node_modules/mysql2/lib/auth_41.js"(exports) {
8127
8231
  "use strict";
8128
- var crypto = __require("crypto");
8232
+ var crypto2 = __require("crypto");
8129
8233
  function sha1(msg, msg1, msg2) {
8130
- const hash2 = crypto.createHash("sha1");
8234
+ const hash2 = crypto2.createHash("sha1");
8131
8235
  hash2.update(msg);
8132
8236
  if (msg1) {
8133
8237
  hash2.update(msg1);
@@ -10553,7 +10657,7 @@ var require_sha256_password = __commonJS({
10553
10657
  "../../node_modules/.pnpm/mysql2@3.24.6_@types+node@26.5.0/node_modules/mysql2/lib/auth_plugins/sha256_password.js"(exports, module) {
10554
10658
  "use strict";
10555
10659
  var PLUGIN_NAME = "sha256_password";
10556
- var crypto = __require("crypto");
10660
+ var crypto2 = __require("crypto");
10557
10661
  var { xorRotating } = require_auth_41();
10558
10662
  var Tls = __require("tls");
10559
10663
  var REQUEST_SERVER_KEY_PACKET = Buffer.from([1]);
@@ -10562,7 +10666,7 @@ var require_sha256_password = __commonJS({
10562
10666
  var STATE_FINAL = -1;
10563
10667
  function encrypt(password, scramble, key) {
10564
10668
  const stage1 = xorRotating(Buffer.from(`${password}\0`, "utf8"), scramble);
10565
- return crypto.publicEncrypt(
10669
+ return crypto2.publicEncrypt(
10566
10670
  {
10567
10671
  key,
10568
10672
  oaepHash: "sha1"
@@ -10614,7 +10718,7 @@ var require_caching_sha2_password = __commonJS({
10614
10718
  "../../node_modules/.pnpm/mysql2@3.24.6_@types+node@26.5.0/node_modules/mysql2/lib/auth_plugins/caching_sha2_password.js"(exports, module) {
10615
10719
  "use strict";
10616
10720
  var PLUGIN_NAME = "caching_sha2_password";
10617
- var crypto = __require("crypto");
10721
+ var crypto2 = __require("crypto");
10618
10722
  var { xor: xor2, xorRotating } = require_auth_41();
10619
10723
  var REQUEST_SERVER_KEY_PACKET = Buffer.from([2]);
10620
10724
  var FAST_AUTH_SUCCESS_PACKET = Buffer.from([3]);
@@ -10624,7 +10728,7 @@ var require_caching_sha2_password = __commonJS({
10624
10728
  var STATE_WAIT_SERVER_KEY = 2;
10625
10729
  var STATE_FINAL = -1;
10626
10730
  function sha256(msg) {
10627
- const hash2 = crypto.createHash("sha256");
10731
+ const hash2 = crypto2.createHash("sha256");
10628
10732
  hash2.update(msg);
10629
10733
  return hash2.digest();
10630
10734
  }
@@ -10639,11 +10743,11 @@ var require_caching_sha2_password = __commonJS({
10639
10743
  }
10640
10744
  function encrypt(password, scramble, key) {
10641
10745
  const stage1 = xorRotating(Buffer.from(`${password}\0`, "utf8"), scramble);
10642
- return crypto.publicEncrypt(
10746
+ return crypto2.publicEncrypt(
10643
10747
  {
10644
10748
  key,
10645
10749
  oaepHash: "sha1",
10646
- padding: crypto.constants.RSA_PKCS1_OAEP_PADDING
10750
+ padding: crypto2.constants.RSA_PKCS1_OAEP_PADDING
10647
10751
  },
10648
10752
  stage1
10649
10753
  );
@@ -14640,11 +14744,11 @@ var require_connection = __commonJS({
14640
14744
  this.once("error", onError);
14641
14745
  }),
14642
14746
  () => {
14643
- const server2 = getServerContext(config2);
14747
+ const server = getServerContext(config2);
14644
14748
  return {
14645
14749
  database: config2.database || "",
14646
- serverAddress: server2.serverAddress,
14647
- serverPort: server2.serverPort,
14750
+ serverAddress: server.serverAddress,
14751
+ serverPort: server.serverPort,
14648
14752
  user: config2.user || ""
14649
14753
  };
14650
14754
  }
@@ -15062,13 +15166,13 @@ var require_connection = __commonJS({
15062
15166
  },
15063
15167
  0,
15064
15168
  () => {
15065
- const server2 = getServerContext(this.config);
15169
+ const server = getServerContext(this.config);
15066
15170
  return {
15067
15171
  query: cmdQuery.sql,
15068
15172
  values: cmdQuery.values,
15069
15173
  database: this.config.database || "",
15070
- serverAddress: server2.serverAddress,
15071
- serverPort: server2.serverPort
15174
+ serverAddress: server.serverAddress,
15175
+ serverPort: server.serverPort
15072
15176
  };
15073
15177
  },
15074
15178
  null,
@@ -15083,13 +15187,13 @@ var require_connection = __commonJS({
15083
15187
  this.addCommand(cmdQuery);
15084
15188
  }),
15085
15189
  () => {
15086
- const server2 = getServerContext(this.config);
15190
+ const server = getServerContext(this.config);
15087
15191
  return {
15088
15192
  query: cmdQuery.sql,
15089
15193
  values: cmdQuery.values,
15090
15194
  database: this.config.database || "",
15091
- serverAddress: server2.serverAddress,
15092
- serverPort: server2.serverPort
15195
+ serverAddress: server.serverAddress,
15196
+ serverPort: server.serverPort
15093
15197
  };
15094
15198
  }
15095
15199
  ).catch(() => {
@@ -15211,13 +15315,13 @@ var require_connection = __commonJS({
15211
15315
  },
15212
15316
  0,
15213
15317
  () => {
15214
- const server2 = getServerContext(this.config);
15318
+ const server = getServerContext(this.config);
15215
15319
  return {
15216
15320
  query: options.sql,
15217
15321
  values: options.values,
15218
15322
  database: this.config.database || "",
15219
- serverAddress: server2.serverAddress,
15220
- serverPort: server2.serverPort
15323
+ serverAddress: server.serverAddress,
15324
+ serverPort: server.serverPort
15221
15325
  };
15222
15326
  },
15223
15327
  null,
@@ -15234,13 +15338,13 @@ var require_connection = __commonJS({
15234
15338
  executeCommand.once("end", () => resolve());
15235
15339
  }),
15236
15340
  () => {
15237
- const server2 = getServerContext(this.config);
15341
+ const server = getServerContext(this.config);
15238
15342
  return {
15239
15343
  query: options.sql,
15240
15344
  values: options.values,
15241
15345
  database: this.config.database || "",
15242
- serverAddress: server2.serverAddress,
15243
- serverPort: server2.serverPort
15346
+ serverAddress: server.serverAddress,
15347
+ serverPort: server.serverPort
15244
15348
  };
15245
15349
  }
15246
15350
  ).catch(() => {
@@ -15997,11 +16101,11 @@ var require_pool = __commonJS({
15997
16101
  _getConnection,
15998
16102
  0,
15999
16103
  () => {
16000
- const server2 = getServerContext(config2);
16104
+ const server = getServerContext(config2);
16001
16105
  return {
16002
16106
  database: config2.database || "",
16003
- serverAddress: server2.serverAddress,
16004
- serverPort: server2.serverPort
16107
+ serverAddress: server.serverAddress,
16108
+ serverPort: server.serverPort
16005
16109
  };
16006
16110
  },
16007
16111
  null,
@@ -17046,7 +17150,7 @@ var RealStdoutWritable = class extends Writable {
17046
17150
  function createStdioServer() {
17047
17151
  const realStream = process.stdout;
17048
17152
  const realWrite = realStream.write.bind(realStream);
17049
- const stdout2 = new RealStdoutWritable(realWrite, realStream);
17153
+ const stdout = new RealStdoutWritable(realWrite, realStream);
17050
17154
  const diverted = ((chunk, encodingOrCallback, maybeCallback) => {
17051
17155
  const encoding = typeof encodingOrCallback === "string" ? encodingOrCallback : void 0;
17052
17156
  const callback = typeof encodingOrCallback === "function" ? encodingOrCallback : maybeCallback;
@@ -17055,7 +17159,7 @@ function createStdioServer() {
17055
17159
  return true;
17056
17160
  });
17057
17161
  process.stdout.write = diverted;
17058
- return { stdout: stdout2 };
17162
+ return { stdout };
17059
17163
  }
17060
17164
 
17061
17165
  // ../mcp-core/src/bootstrap/logger.ts
@@ -17080,6 +17184,259 @@ var logger = {
17080
17184
  import { realpathSync } from "fs";
17081
17185
  import { fileURLToPath } from "url";
17082
17186
 
17187
+ // ../mcp-core/src/http/http-endpoint.ts
17188
+ import { createHash, timingSafeEqual } from "crypto";
17189
+ var MIN_TOKEN_LENGTH = 32;
17190
+ var DEFAULT_PATH = "/mcp";
17191
+ var DEFAULT_HOST = "127.0.0.1";
17192
+ var DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
17193
+ var CARRIED_METHOD = "POST";
17194
+ var BEARER_PREFIX = /^bearer /i;
17195
+ var MAX_LOGGED_NAME = 100;
17196
+ var BodyTooLargeError = class extends Error {
17197
+ };
17198
+ function digest(value) {
17199
+ return createHash("sha256").update(value).digest();
17200
+ }
17201
+ function bearerMatches(header, expected) {
17202
+ if (header === void 0 || !BEARER_PREFIX.test(header)) {
17203
+ return false;
17204
+ }
17205
+ return timingSafeEqual(digest(header.slice("Bearer ".length)), expected);
17206
+ }
17207
+ function reply(response, status2, message, headers = {}) {
17208
+ response.writeHead(status2, { "content-type": "application/json", "cache-control": "no-store", ...headers });
17209
+ response.end(JSON.stringify({ error: message }));
17210
+ }
17211
+ async function readBody(request, limit) {
17212
+ const declared = Number(request.headers["content-length"]);
17213
+ if (Number.isFinite(declared) && declared > limit) {
17214
+ throw new BodyTooLargeError();
17215
+ }
17216
+ const chunks = [];
17217
+ let total = 0;
17218
+ for await (const chunk of request) {
17219
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
17220
+ total += buffer.length;
17221
+ if (total > limit) {
17222
+ throw new BodyTooLargeError();
17223
+ }
17224
+ chunks.push(buffer);
17225
+ }
17226
+ return Buffer.concat(chunks);
17227
+ }
17228
+ function toHeaders(incoming) {
17229
+ const headers = new Headers();
17230
+ for (const [name2, value] of Object.entries(incoming)) {
17231
+ if (value === void 0) {
17232
+ continue;
17233
+ }
17234
+ headers.set(name2, Array.isArray(value) ? value.join(", ") : value);
17235
+ }
17236
+ return headers;
17237
+ }
17238
+ function loggable(value) {
17239
+ return value.replace(/[^\w./:-]/g, "?").slice(0, MAX_LOGGED_NAME);
17240
+ }
17241
+ function describeRpc(body) {
17242
+ let parsed;
17243
+ try {
17244
+ parsed = JSON.parse(body.toString("utf8"));
17245
+ } catch {
17246
+ return "";
17247
+ }
17248
+ if (Array.isArray(parsed)) {
17249
+ return `batch(${parsed.length})`;
17250
+ }
17251
+ if (typeof parsed !== "object" || parsed === null) {
17252
+ return "";
17253
+ }
17254
+ const { method, params: params2 } = parsed;
17255
+ if (typeof method !== "string") {
17256
+ return "";
17257
+ }
17258
+ const name2 = typeof params2?.name === "string" ? ` ${loggable(params2.name)}` : "";
17259
+ return `${loggable(method)}${name2}`;
17260
+ }
17261
+ var GONE = /* @__PURE__ */ Symbol("client gone");
17262
+ async function relay(response, target) {
17263
+ const headers = {};
17264
+ response.headers.forEach((value, name2) => {
17265
+ headers[name2] = value;
17266
+ });
17267
+ target.writeHead(response.status, headers);
17268
+ if (response.body === null) {
17269
+ target.end();
17270
+ return;
17271
+ }
17272
+ const reader = response.body.getReader();
17273
+ const gone = new Promise((resolve) => target.once("close", () => resolve(GONE)));
17274
+ try {
17275
+ for (; ; ) {
17276
+ const next = await Promise.race([reader.read(), gone]);
17277
+ if (next === GONE) {
17278
+ await reader.cancel();
17279
+ return;
17280
+ }
17281
+ if (next.done) {
17282
+ break;
17283
+ }
17284
+ if (!target.write(next.value)) {
17285
+ const drained = await Promise.race([new Promise((resolve) => target.once("drain", resolve)), gone]);
17286
+ if (drained === GONE) {
17287
+ await reader.cancel();
17288
+ return;
17289
+ }
17290
+ }
17291
+ }
17292
+ } finally {
17293
+ reader.releaseLock();
17294
+ target.end();
17295
+ }
17296
+ }
17297
+ async function startHttpEndpoint(options) {
17298
+ if (options.token.length < MIN_TOKEN_LENGTH) {
17299
+ throw new Error(`The HTTP bearer token must be at least ${MIN_TOKEN_LENGTH} characters; generate one with \`openssl rand -hex 32\`.`);
17300
+ }
17301
+ const expected = digest(options.token);
17302
+ const host = options.host ?? DEFAULT_HOST;
17303
+ const path = options.path ?? DEFAULT_PATH;
17304
+ const maxBodyBytes = options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
17305
+ const allowedOrigins = new Set((options.allowedOrigins ?? []).map((origin) => origin.toLowerCase()));
17306
+ const allowedHosts = new Set((options.allowedHosts ?? []).map((value) => value.toLowerCase()));
17307
+ const { createServer } = await import("http");
17308
+ const server = createServer((request, response) => {
17309
+ const started = performance.now();
17310
+ const context = { rpc: "" };
17311
+ response.once("close", () => {
17312
+ const status2 = response.statusCode;
17313
+ const pathname = loggable((request.url ?? "/").split("?")[0] ?? "/");
17314
+ const rpc = context.rpc === "" ? "" : ` ${context.rpc}`;
17315
+ const line = `http: ${loggable(request.method ?? "?")} ${pathname} ${status2}${rpc} ${Math.round(performance.now() - started)}ms`;
17316
+ if (status2 >= 500) {
17317
+ logger.error(line);
17318
+ } else if (status2 >= 400) {
17319
+ logger.warn(line);
17320
+ } else {
17321
+ logger.info(line);
17322
+ }
17323
+ });
17324
+ void handle(request, response, context).catch((error61) => {
17325
+ logger.error(`http endpoint: handler failed (${error61 instanceof Error ? error61.constructor.name : "unknown"})`);
17326
+ if (!response.headersSent) {
17327
+ reply(response, 500, "Internal error");
17328
+ } else {
17329
+ response.destroy();
17330
+ }
17331
+ });
17332
+ });
17333
+ async function handle(request, response, context) {
17334
+ const hostHeader = request.headers.host?.toLowerCase();
17335
+ if (hostHeader === void 0 || !allowedHosts.has(hostHeader)) {
17336
+ reply(response, 403, "Host not allowed");
17337
+ return;
17338
+ }
17339
+ const origin = request.headers.origin;
17340
+ if (origin !== void 0 && !allowedOrigins.has(origin.toLowerCase())) {
17341
+ reply(response, 403, "Origin not allowed");
17342
+ return;
17343
+ }
17344
+ if (!bearerMatches(request.headers.authorization, expected)) {
17345
+ reply(response, 401, "Unauthorized", { "www-authenticate": 'Bearer realm="mcp"' });
17346
+ return;
17347
+ }
17348
+ const url2 = new URL(request.url ?? "/", `http://${hostHeader}`);
17349
+ if (url2.pathname !== path) {
17350
+ reply(response, 404, "Not found");
17351
+ return;
17352
+ }
17353
+ const method = request.method ?? "GET";
17354
+ if (method !== CARRIED_METHOD) {
17355
+ reply(response, 405, "Method not allowed", { allow: CARRIED_METHOD });
17356
+ return;
17357
+ }
17358
+ let body;
17359
+ try {
17360
+ body = await readBody(request, maxBodyBytes);
17361
+ } catch (error61) {
17362
+ if (error61 instanceof BodyTooLargeError) {
17363
+ reply(response, 413, "Request body too large");
17364
+ request.destroy();
17365
+ return;
17366
+ }
17367
+ throw error61;
17368
+ }
17369
+ context.rpc = describeRpc(body);
17370
+ const aborted2 = new AbortController();
17371
+ response.on("close", () => {
17372
+ if (!response.writableEnded) {
17373
+ aborted2.abort();
17374
+ }
17375
+ });
17376
+ const webRequest = new Request(url2, {
17377
+ method,
17378
+ headers: toHeaders(request.headers),
17379
+ body: new Uint8Array(body),
17380
+ signal: aborted2.signal
17381
+ });
17382
+ await relay(await options.handler(webRequest), response);
17383
+ }
17384
+ await new Promise((resolve, reject) => {
17385
+ server.once("error", reject);
17386
+ server.listen(options.port, host, () => {
17387
+ server.off("error", reject);
17388
+ resolve();
17389
+ });
17390
+ });
17391
+ const address = server.address();
17392
+ for (const name2 of ["127.0.0.1", "localhost", "[::1]"]) {
17393
+ allowedHosts.add(`${name2}:${address.port}`);
17394
+ }
17395
+ return {
17396
+ host,
17397
+ port: address.port,
17398
+ address,
17399
+ close: (graceMs = 0) => new Promise((resolve) => {
17400
+ server.close(() => resolve());
17401
+ server.closeIdleConnections();
17402
+ if (graceMs <= 0) {
17403
+ server.closeAllConnections();
17404
+ } else {
17405
+ setTimeout(() => server.closeAllConnections(), graceMs).unref();
17406
+ }
17407
+ })
17408
+ };
17409
+ }
17410
+
17411
+ // ../mcp-core/src/http/http-config.ts
17412
+ var DEFAULT_HOST2 = "127.0.0.1";
17413
+ var MAX_PORT = 65535;
17414
+ function list(value) {
17415
+ return (value ?? "").split(",").map((item) => item.trim()).filter((item) => item.length > 0);
17416
+ }
17417
+ function readHttpConfig(names, env) {
17418
+ const rawPort = env[names.port]?.trim();
17419
+ if (rawPort === void 0 || rawPort === "") {
17420
+ return { enabled: false };
17421
+ }
17422
+ const port = Number(rawPort);
17423
+ if (!Number.isInteger(port) || port < 0 || port > MAX_PORT) {
17424
+ throw new Error(`${names.port} must be an integer between 0 and ${MAX_PORT}.`);
17425
+ }
17426
+ const token = env[names.token]?.trim();
17427
+ if (token === void 0 || token === "") {
17428
+ throw new Error(`${names.token} is required when ${names.port} is set. Generate one with \`openssl rand -hex 32\`.`);
17429
+ }
17430
+ return {
17431
+ enabled: true,
17432
+ port,
17433
+ host: env[names.host]?.trim() || DEFAULT_HOST2,
17434
+ token,
17435
+ allowedHosts: list(env[names.allowedHosts]),
17436
+ allowedOrigins: list(env[names.allowedOrigins])
17437
+ };
17438
+ }
17439
+
17083
17440
  // ../mcp-core/src/version/server-version.ts
17084
17441
  var SERVER_VERSION_DEFINE = "__MCP_SERVER_VERSION__";
17085
17442
  function resolveServerVersion(injected) {
@@ -17091,7 +17448,7 @@ function resolveServerVersion(injected) {
17091
17448
  return injected;
17092
17449
  }
17093
17450
  function serverVersion() {
17094
- return resolveServerVersion(false ? void 0 : "0.1.0");
17451
+ return resolveServerVersion(false ? void 0 : "0.2.0");
17095
17452
  }
17096
17453
 
17097
17454
  // ../mcp-core/src/credentials/token-provider.ts
@@ -17150,6 +17507,7 @@ function defineTool(def) {
17150
17507
  name: def.name,
17151
17508
  description: def.description,
17152
17509
  inputSchema: def.inputSchema,
17510
+ ...def.outputSchema !== void 0 ? { outputSchema: def.outputSchema } : {},
17153
17511
  annotations: def.annotations,
17154
17512
  handler: def.handler,
17155
17513
  async invoke(rawArgs, ctx) {
@@ -17163,6 +17521,17 @@ function defineTool(def) {
17163
17521
  }
17164
17522
  throw error61;
17165
17523
  }
17524
+ if (def.outputSchema !== void 0) {
17525
+ const json2 = JSON.stringify(result);
17526
+ const bytes = Buffer.byteLength(json2, "utf8");
17527
+ if (bytes > DEFAULT_MAX_OUTPUT_BYTES) {
17528
+ return {
17529
+ content: [{ type: "text", text: `The result is ${bytes} bytes, over the ${DEFAULT_MAX_OUTPUT_BYTES}-byte limit; ask for fewer records.` }],
17530
+ isError: true
17531
+ };
17532
+ }
17533
+ return { content: [{ type: "text", text: json2 }], structuredContent: result };
17534
+ }
17166
17535
  const text3 = truncate(toTextContent(result), DEFAULT_MAX_OUTPUT_BYTES);
17167
17536
  return { content: [{ type: "text", text: text3 }] };
17168
17537
  }
@@ -40259,6 +40628,7 @@ function getLiteralValue(schema) {
40259
40628
 
40260
40629
  // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.5.4/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
40261
40630
  var LATEST_PROTOCOL_VERSION = "2025-11-25";
40631
+ var DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26";
40262
40632
  var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"];
40263
40633
  var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";
40264
40634
  var JSONRPC_VERSION = "2.0";
@@ -40587,6 +40957,7 @@ var InitializeRequestSchema = RequestSchema.extend({
40587
40957
  method: literal("initialize"),
40588
40958
  params: InitializeRequestParamsSchema
40589
40959
  });
40960
+ var isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success;
40590
40961
  var ServerCapabilitiesSchema = object({
40591
40962
  /**
40592
40963
  * Experimental, non-standard capabilities that the server supports.
@@ -43295,11 +43666,11 @@ var Protocol = class {
43295
43666
  *
43296
43667
  * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.
43297
43668
  */
43298
- async connect(transport2) {
43669
+ async connect(transport) {
43299
43670
  if (this._transport) {
43300
43671
  throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");
43301
43672
  }
43302
- this._transport = transport2;
43673
+ this._transport = transport;
43303
43674
  const _onclose = this.transport?.onclose;
43304
43675
  this._transport.onclose = () => {
43305
43676
  _onclose?.();
@@ -44898,8 +45269,8 @@ var McpServer = class {
44898
45269
  *
44899
45270
  * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.
44900
45271
  */
44901
- async connect(transport2) {
44902
- return await this.server.connect(transport2);
45272
+ async connect(transport) {
45273
+ return await this.server.connect(transport);
44903
45274
  }
44904
45275
  /**
44905
45276
  * Closes the connection.
@@ -45764,6 +46135,773 @@ var StdioServerTransport = class {
45764
46135
  }
45765
46136
  };
45766
46137
 
46138
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.5.4/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.js
46139
+ var import_content_type = __toESM(require_content_type(), 1);
46140
+ function mediaTypeEssence(header) {
46141
+ if (!header) {
46142
+ return void 0;
46143
+ }
46144
+ try {
46145
+ return import_content_type.default.parse(header).type;
46146
+ } catch {
46147
+ const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase();
46148
+ if (essence === "" || header.slice(essence.length).includes(",")) {
46149
+ return void 0;
46150
+ }
46151
+ return essence;
46152
+ }
46153
+ }
46154
+ function isJsonContentType(header) {
46155
+ if (header === "application/json") {
46156
+ return true;
46157
+ }
46158
+ return mediaTypeEssence(header) === "application/json";
46159
+ }
46160
+
46161
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.5.4/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sseKeepAlive.js
46162
+ var DEFAULT_SSE_KEEP_ALIVE_MS = 15e3;
46163
+ var MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
46164
+ function armSseKeepAlive(intervalMs, onTick) {
46165
+ if (!Number.isFinite(intervalMs) || intervalMs < 1) {
46166
+ return void 0;
46167
+ }
46168
+ const timer = setInterval(onTick, Math.min(intervalMs, MAX_TIMER_DELAY_MS));
46169
+ timer.unref?.();
46170
+ return timer;
46171
+ }
46172
+
46173
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.5.4/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js
46174
+ var WebStandardStreamableHTTPServerTransport = class {
46175
+ constructor(options = {}) {
46176
+ this._started = false;
46177
+ this._hasHandledRequest = false;
46178
+ this._streamMapping = /* @__PURE__ */ new Map();
46179
+ this._requestToStreamMapping = /* @__PURE__ */ new Map();
46180
+ this._resumableStreams = /* @__PURE__ */ new Set();
46181
+ this._requestResponseMap = /* @__PURE__ */ new Map();
46182
+ this._initialized = false;
46183
+ this._enableJsonResponse = false;
46184
+ this._standaloneSseStreamId = "_GET_stream";
46185
+ this._closed = false;
46186
+ this.sessionIdGenerator = options.sessionIdGenerator;
46187
+ this._enableJsonResponse = options.enableJsonResponse ?? false;
46188
+ this._eventStore = options.eventStore;
46189
+ this._onsessioninitialized = options.onsessioninitialized;
46190
+ this._onsessionclosed = options.onsessionclosed;
46191
+ this._allowedHosts = options.allowedHosts;
46192
+ this._allowedOrigins = options.allowedOrigins;
46193
+ this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false;
46194
+ this._retryInterval = options.retryInterval;
46195
+ this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS;
46196
+ }
46197
+ /**
46198
+ * Arms a keep-alive interval for an SSE stream that periodically writes an SSE
46199
+ * comment frame so intermediaries and idle timeouts don't kill the connection.
46200
+ * The returned timer is owned by the stream it was armed for: the stream's
46201
+ * cancel/cleanup callbacks must clear it. The interval clears itself if a
46202
+ * write fails (stream already closed/cancelled).
46203
+ */
46204
+ startKeepAlive(controller, encoder) {
46205
+ if (this._closed)
46206
+ return void 0;
46207
+ const timer = armSseKeepAlive(this._keepAliveMs, () => {
46208
+ try {
46209
+ controller.enqueue(encoder.encode(": keepalive\n\n"));
46210
+ } catch {
46211
+ if (timer !== void 0)
46212
+ clearInterval(timer);
46213
+ }
46214
+ });
46215
+ return timer;
46216
+ }
46217
+ /**
46218
+ * Starts the transport. This is required by the Transport interface but is a no-op
46219
+ * for the Streamable HTTP transport as connections are managed per-request.
46220
+ */
46221
+ async start() {
46222
+ if (this._started) {
46223
+ throw new Error("Transport already started");
46224
+ }
46225
+ this._started = true;
46226
+ }
46227
+ /**
46228
+ * Helper to create a JSON error response
46229
+ */
46230
+ createJsonErrorResponse(status2, code, message, options) {
46231
+ const error61 = { code, message };
46232
+ if (options?.data !== void 0) {
46233
+ error61.data = options.data;
46234
+ }
46235
+ return new Response(JSON.stringify({
46236
+ jsonrpc: "2.0",
46237
+ error: error61,
46238
+ id: null
46239
+ }), {
46240
+ status: status2,
46241
+ headers: {
46242
+ "Content-Type": "application/json",
46243
+ ...options?.headers
46244
+ }
46245
+ });
46246
+ }
46247
+ /**
46248
+ * Validates request headers for DNS rebinding protection.
46249
+ * @returns Error response if validation fails, undefined if validation passes.
46250
+ */
46251
+ validateRequestHeaders(req) {
46252
+ if (!this._enableDnsRebindingProtection) {
46253
+ return void 0;
46254
+ }
46255
+ if (this._allowedHosts && this._allowedHosts.length > 0) {
46256
+ const hostHeader = req.headers.get("host");
46257
+ if (!hostHeader || !this._allowedHosts.includes(hostHeader)) {
46258
+ const error61 = `Invalid Host header: ${hostHeader}`;
46259
+ this.onerror?.(new Error(error61));
46260
+ return this.createJsonErrorResponse(403, -32e3, error61);
46261
+ }
46262
+ }
46263
+ if (this._allowedOrigins && this._allowedOrigins.length > 0) {
46264
+ const originHeader = req.headers.get("origin");
46265
+ if (originHeader && !this._allowedOrigins.includes(originHeader)) {
46266
+ const error61 = `Invalid Origin header: ${originHeader}`;
46267
+ this.onerror?.(new Error(error61));
46268
+ return this.createJsonErrorResponse(403, -32e3, error61);
46269
+ }
46270
+ }
46271
+ return void 0;
46272
+ }
46273
+ /**
46274
+ * Handles an incoming HTTP request, whether GET, POST, or DELETE
46275
+ * Returns a Response object (Web Standard)
46276
+ */
46277
+ async handleRequest(req, options) {
46278
+ if (this._closed) {
46279
+ return this.createJsonErrorResponse(404, -32001, "Session not found");
46280
+ }
46281
+ if (!this.sessionIdGenerator && this._hasHandledRequest) {
46282
+ throw new Error("Stateless transport cannot be reused across requests. Create a new transport per request.");
46283
+ }
46284
+ this._hasHandledRequest = true;
46285
+ const validationError = this.validateRequestHeaders(req);
46286
+ if (validationError) {
46287
+ return validationError;
46288
+ }
46289
+ switch (req.method) {
46290
+ case "POST":
46291
+ return this.handlePostRequest(req, options);
46292
+ case "GET":
46293
+ return this.handleGetRequest(req);
46294
+ case "DELETE":
46295
+ return this.handleDeleteRequest(req);
46296
+ default:
46297
+ return this.handleUnsupportedRequest();
46298
+ }
46299
+ }
46300
+ /**
46301
+ * Writes a priming event to establish resumption capability.
46302
+ * Only sends if eventStore is configured (opt-in for resumability) and
46303
+ * the client's protocol version supports empty SSE data (>= 2025-11-25).
46304
+ */
46305
+ async writePrimingEvent(controller, encoder, streamId, protocolVersion) {
46306
+ if (!this._eventStore) {
46307
+ return;
46308
+ }
46309
+ if (protocolVersion < "2025-11-25") {
46310
+ return;
46311
+ }
46312
+ const primingEventId = await this._eventStore.storeEvent(streamId, {});
46313
+ let primingEvent = `id: ${primingEventId}
46314
+ data:
46315
+
46316
+ `;
46317
+ if (this._retryInterval !== void 0) {
46318
+ primingEvent = `id: ${primingEventId}
46319
+ retry: ${this._retryInterval}
46320
+ data:
46321
+
46322
+ `;
46323
+ }
46324
+ controller.enqueue(encoder.encode(primingEvent));
46325
+ this._resumableStreams.add(streamId);
46326
+ }
46327
+ /**
46328
+ * Handles GET requests for SSE stream
46329
+ */
46330
+ async handleGetRequest(req) {
46331
+ const acceptHeader = req.headers.get("accept");
46332
+ if (!acceptHeader?.includes("text/event-stream")) {
46333
+ this.onerror?.(new Error("Not Acceptable: Client must accept text/event-stream"));
46334
+ return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept text/event-stream");
46335
+ }
46336
+ const sessionError = this.validateSession(req);
46337
+ if (sessionError) {
46338
+ return sessionError;
46339
+ }
46340
+ const protocolError = this.validateProtocolVersion(req);
46341
+ if (protocolError) {
46342
+ return protocolError;
46343
+ }
46344
+ if (this._eventStore) {
46345
+ const lastEventId = req.headers.get("last-event-id");
46346
+ if (lastEventId) {
46347
+ return this.replayEvents(lastEventId);
46348
+ }
46349
+ }
46350
+ if (this._streamMapping.get(this._standaloneSseStreamId) !== void 0) {
46351
+ this.onerror?.(new Error("Conflict: Only one SSE stream is allowed per session"));
46352
+ return this.createJsonErrorResponse(409, -32e3, "Conflict: Only one SSE stream is allowed per session");
46353
+ }
46354
+ const encoder = new TextEncoder();
46355
+ let streamController;
46356
+ let keepAliveTimer = void 0;
46357
+ const readable = new ReadableStream({
46358
+ start: (controller) => {
46359
+ streamController = controller;
46360
+ },
46361
+ cancel: () => {
46362
+ if (keepAliveTimer !== void 0) {
46363
+ clearInterval(keepAliveTimer);
46364
+ }
46365
+ if (this._streamMapping.get(this._standaloneSseStreamId)?.controller === streamController) {
46366
+ this._streamMapping.delete(this._standaloneSseStreamId);
46367
+ }
46368
+ }
46369
+ });
46370
+ const headers = {
46371
+ "Content-Type": "text/event-stream",
46372
+ "Cache-Control": "no-cache, no-transform",
46373
+ Connection: "keep-alive",
46374
+ "X-Accel-Buffering": "no"
46375
+ };
46376
+ if (this.sessionId !== void 0) {
46377
+ headers["mcp-session-id"] = this.sessionId;
46378
+ }
46379
+ this._streamMapping.set(this._standaloneSseStreamId, {
46380
+ controller: streamController,
46381
+ encoder,
46382
+ cleanup: () => {
46383
+ if (keepAliveTimer !== void 0) {
46384
+ clearInterval(keepAliveTimer);
46385
+ }
46386
+ this._streamMapping.delete(this._standaloneSseStreamId);
46387
+ try {
46388
+ streamController.close();
46389
+ } catch {
46390
+ }
46391
+ }
46392
+ });
46393
+ keepAliveTimer = this.startKeepAlive(streamController, encoder);
46394
+ return new Response(readable, { headers });
46395
+ }
46396
+ /**
46397
+ * Replays events that would have been sent after the specified event ID
46398
+ * Only used when resumability is enabled
46399
+ */
46400
+ async replayEvents(lastEventId) {
46401
+ if (!this._eventStore) {
46402
+ this.onerror?.(new Error("Event store not configured"));
46403
+ return this.createJsonErrorResponse(400, -32e3, "Event store not configured");
46404
+ }
46405
+ try {
46406
+ let streamId;
46407
+ if (this._eventStore.getStreamIdForEventId) {
46408
+ streamId = await this._eventStore.getStreamIdForEventId(lastEventId);
46409
+ if (!streamId) {
46410
+ this.onerror?.(new Error("Invalid event ID format"));
46411
+ return this.createJsonErrorResponse(400, -32e3, "Invalid event ID format");
46412
+ }
46413
+ if (this._streamMapping.get(streamId) !== void 0) {
46414
+ this.onerror?.(new Error("Conflict: Stream already has an active connection"));
46415
+ return this.createJsonErrorResponse(409, -32e3, "Conflict: Stream already has an active connection");
46416
+ }
46417
+ }
46418
+ const headers = {
46419
+ "Content-Type": "text/event-stream",
46420
+ "Cache-Control": "no-cache, no-transform",
46421
+ Connection: "keep-alive",
46422
+ "X-Accel-Buffering": "no"
46423
+ };
46424
+ if (this.sessionId !== void 0) {
46425
+ headers["mcp-session-id"] = this.sessionId;
46426
+ }
46427
+ const encoder = new TextEncoder();
46428
+ let streamController;
46429
+ let keepAliveTimer = void 0;
46430
+ let replayedStreamId = void 0;
46431
+ let cancelled2 = false;
46432
+ const readable = new ReadableStream({
46433
+ start: (controller) => {
46434
+ streamController = controller;
46435
+ },
46436
+ cancel: () => {
46437
+ cancelled2 = true;
46438
+ if (keepAliveTimer !== void 0) {
46439
+ clearInterval(keepAliveTimer);
46440
+ }
46441
+ if (replayedStreamId !== void 0 && this._streamMapping.get(replayedStreamId)?.controller === streamController) {
46442
+ this._streamMapping.delete(replayedStreamId);
46443
+ }
46444
+ }
46445
+ });
46446
+ const replayedEventIds = /* @__PURE__ */ new Set();
46447
+ replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, {
46448
+ send: async (eventId, message) => {
46449
+ const success2 = this.writeSSEEvent(streamController, encoder, message, eventId);
46450
+ if (!success2) {
46451
+ this.onerror?.(new Error("Failed replay events"));
46452
+ try {
46453
+ streamController.close();
46454
+ } catch {
46455
+ }
46456
+ } else {
46457
+ replayedEventIds.add(eventId);
46458
+ }
46459
+ }
46460
+ });
46461
+ if (this._closed || cancelled2) {
46462
+ try {
46463
+ streamController.close();
46464
+ } catch {
46465
+ }
46466
+ return this.createJsonErrorResponse(404, -32001, "Session not found");
46467
+ }
46468
+ this._streamMapping.get(replayedStreamId)?.cleanup();
46469
+ this._streamMapping.set(replayedStreamId, {
46470
+ controller: streamController,
46471
+ encoder,
46472
+ replayedEventIds,
46473
+ cleanup: () => {
46474
+ if (keepAliveTimer !== void 0) {
46475
+ clearInterval(keepAliveTimer);
46476
+ }
46477
+ this._streamMapping.delete(replayedStreamId);
46478
+ try {
46479
+ streamController.close();
46480
+ } catch {
46481
+ }
46482
+ }
46483
+ });
46484
+ this._resumableStreams.add(replayedStreamId);
46485
+ keepAliveTimer = this.startKeepAlive(streamController, encoder);
46486
+ return new Response(readable, { headers });
46487
+ } catch (error61) {
46488
+ this.onerror?.(error61);
46489
+ return this.createJsonErrorResponse(500, -32e3, "Error replaying events");
46490
+ }
46491
+ }
46492
+ /**
46493
+ * Writes an event to an SSE stream via controller with proper formatting
46494
+ */
46495
+ writeSSEEvent(controller, encoder, message, eventId) {
46496
+ try {
46497
+ let eventData = `event: message
46498
+ `;
46499
+ if (eventId) {
46500
+ eventData += `id: ${eventId}
46501
+ `;
46502
+ }
46503
+ eventData += `data: ${JSON.stringify(message)}
46504
+
46505
+ `;
46506
+ controller.enqueue(encoder.encode(eventData));
46507
+ return true;
46508
+ } catch (error61) {
46509
+ this.onerror?.(error61);
46510
+ return false;
46511
+ }
46512
+ }
46513
+ /**
46514
+ * Handles unsupported requests (PUT, PATCH, etc.)
46515
+ */
46516
+ handleUnsupportedRequest() {
46517
+ this.onerror?.(new Error("Method not allowed."));
46518
+ return new Response(JSON.stringify({
46519
+ jsonrpc: "2.0",
46520
+ error: {
46521
+ code: -32e3,
46522
+ message: "Method not allowed."
46523
+ },
46524
+ id: null
46525
+ }), {
46526
+ status: 405,
46527
+ headers: {
46528
+ Allow: "GET, POST, DELETE",
46529
+ "Content-Type": "application/json"
46530
+ }
46531
+ });
46532
+ }
46533
+ /**
46534
+ * Handles POST requests containing JSON-RPC messages
46535
+ */
46536
+ async handlePostRequest(req, options) {
46537
+ try {
46538
+ const acceptHeader = req.headers.get("accept");
46539
+ if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
46540
+ this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream"));
46541
+ return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept both application/json and text/event-stream");
46542
+ }
46543
+ const ct = req.headers.get("content-type");
46544
+ if (!isJsonContentType(ct)) {
46545
+ this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json"));
46546
+ return this.createJsonErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json");
46547
+ }
46548
+ const requestInfo = {
46549
+ headers: Object.fromEntries(req.headers.entries()),
46550
+ url: new URL(req.url)
46551
+ };
46552
+ let rawMessage;
46553
+ if (options?.parsedBody !== void 0) {
46554
+ rawMessage = options.parsedBody;
46555
+ } else {
46556
+ try {
46557
+ rawMessage = await req.json();
46558
+ } catch {
46559
+ this.onerror?.(new Error("Parse error: Invalid JSON"));
46560
+ return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON");
46561
+ }
46562
+ }
46563
+ let messages;
46564
+ try {
46565
+ if (Array.isArray(rawMessage)) {
46566
+ messages = rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
46567
+ } else {
46568
+ messages = [JSONRPCMessageSchema.parse(rawMessage)];
46569
+ }
46570
+ } catch {
46571
+ this.onerror?.(new Error("Parse error: Invalid JSON-RPC message"));
46572
+ return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON-RPC message");
46573
+ }
46574
+ if (this._closed) {
46575
+ return this.createJsonErrorResponse(404, -32001, "Session not found");
46576
+ }
46577
+ const isInitializationRequest = messages.some(isInitializeRequest);
46578
+ if (isInitializationRequest) {
46579
+ if (this._initialized && this.sessionId !== void 0) {
46580
+ this.onerror?.(new Error("Invalid Request: Server already initialized"));
46581
+ return this.createJsonErrorResponse(400, -32600, "Invalid Request: Server already initialized");
46582
+ }
46583
+ if (messages.length > 1) {
46584
+ this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed"));
46585
+ return this.createJsonErrorResponse(400, -32600, "Invalid Request: Only one initialization request is allowed");
46586
+ }
46587
+ this.sessionId = this.sessionIdGenerator?.();
46588
+ this._initialized = true;
46589
+ if (this.sessionId && this._onsessioninitialized) {
46590
+ await Promise.resolve(this._onsessioninitialized(this.sessionId));
46591
+ }
46592
+ }
46593
+ if (!isInitializationRequest) {
46594
+ const sessionError = this.validateSession(req);
46595
+ if (sessionError) {
46596
+ return sessionError;
46597
+ }
46598
+ const protocolError = this.validateProtocolVersion(req);
46599
+ if (protocolError) {
46600
+ return protocolError;
46601
+ }
46602
+ }
46603
+ if (this._closed) {
46604
+ return this.createJsonErrorResponse(404, -32001, "Session not found");
46605
+ }
46606
+ const hasRequests = messages.some(isJSONRPCRequest);
46607
+ if (!hasRequests) {
46608
+ for (const message of messages) {
46609
+ this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo });
46610
+ }
46611
+ return new Response(null, { status: 202 });
46612
+ }
46613
+ const streamId = crypto.randomUUID();
46614
+ const initRequest = messages.find((m) => isInitializeRequest(m));
46615
+ const clientProtocolVersion = initRequest ? initRequest.params.protocolVersion : req.headers.get("mcp-protocol-version") ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION;
46616
+ if (this._enableJsonResponse) {
46617
+ return new Promise((resolve) => {
46618
+ this._streamMapping.set(streamId, {
46619
+ resolveJson: resolve,
46620
+ cleanup: () => {
46621
+ this._streamMapping.delete(streamId);
46622
+ }
46623
+ });
46624
+ for (const message of messages) {
46625
+ if (isJSONRPCRequest(message)) {
46626
+ this._requestToStreamMapping.set(message.id, streamId);
46627
+ }
46628
+ }
46629
+ for (const message of messages) {
46630
+ this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo });
46631
+ }
46632
+ });
46633
+ }
46634
+ const encoder = new TextEncoder();
46635
+ let streamController;
46636
+ let keepAliveTimer = void 0;
46637
+ const readable = new ReadableStream({
46638
+ start: (controller) => {
46639
+ streamController = controller;
46640
+ },
46641
+ cancel: () => {
46642
+ if (keepAliveTimer !== void 0) {
46643
+ clearInterval(keepAliveTimer);
46644
+ }
46645
+ if (this._streamMapping.get(streamId)?.controller === streamController) {
46646
+ this._streamMapping.delete(streamId);
46647
+ }
46648
+ }
46649
+ });
46650
+ const headers = {
46651
+ "Content-Type": "text/event-stream",
46652
+ "Cache-Control": "no-cache, no-transform",
46653
+ Connection: "keep-alive",
46654
+ "X-Accel-Buffering": "no"
46655
+ };
46656
+ if (this.sessionId !== void 0) {
46657
+ headers["mcp-session-id"] = this.sessionId;
46658
+ }
46659
+ for (const message of messages) {
46660
+ if (isJSONRPCRequest(message)) {
46661
+ this._streamMapping.set(streamId, {
46662
+ controller: streamController,
46663
+ encoder,
46664
+ cleanup: () => {
46665
+ if (keepAliveTimer !== void 0) {
46666
+ clearInterval(keepAliveTimer);
46667
+ }
46668
+ this._streamMapping.delete(streamId);
46669
+ try {
46670
+ streamController.close();
46671
+ } catch {
46672
+ }
46673
+ }
46674
+ });
46675
+ this._requestToStreamMapping.set(message.id, streamId);
46676
+ }
46677
+ }
46678
+ try {
46679
+ await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion);
46680
+ for (const message of messages) {
46681
+ let closeSSEStream;
46682
+ let closeStandaloneSSEStream;
46683
+ if (isJSONRPCRequest(message) && this._eventStore && clientProtocolVersion >= "2025-11-25") {
46684
+ closeSSEStream = () => {
46685
+ this.closeSSEStream(message.id);
46686
+ };
46687
+ closeStandaloneSSEStream = () => {
46688
+ this.closeStandaloneSSEStream();
46689
+ };
46690
+ }
46691
+ this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo, closeSSEStream, closeStandaloneSSEStream });
46692
+ }
46693
+ } catch (error61) {
46694
+ this._streamMapping.get(streamId)?.cleanup();
46695
+ this._resumableStreams.delete(streamId);
46696
+ for (const message of messages) {
46697
+ if (isJSONRPCRequest(message)) {
46698
+ this._requestToStreamMapping.delete(message.id);
46699
+ }
46700
+ }
46701
+ throw error61;
46702
+ }
46703
+ if (this._streamMapping.get(streamId)?.controller === streamController) {
46704
+ keepAliveTimer = this.startKeepAlive(streamController, encoder);
46705
+ }
46706
+ return new Response(readable, { status: 200, headers });
46707
+ } catch (error61) {
46708
+ this.onerror?.(error61);
46709
+ return this.createJsonErrorResponse(400, -32700, "Parse error", { data: String(error61) });
46710
+ }
46711
+ }
46712
+ /**
46713
+ * Handles DELETE requests to terminate sessions
46714
+ */
46715
+ async handleDeleteRequest(req) {
46716
+ const sessionError = this.validateSession(req);
46717
+ if (sessionError) {
46718
+ return sessionError;
46719
+ }
46720
+ const protocolError = this.validateProtocolVersion(req);
46721
+ if (protocolError) {
46722
+ return protocolError;
46723
+ }
46724
+ try {
46725
+ await Promise.resolve(this._onsessionclosed?.(this.sessionId));
46726
+ return new Response(null, { status: 200 });
46727
+ } finally {
46728
+ await this.close();
46729
+ }
46730
+ }
46731
+ /**
46732
+ * Validates session ID for non-initialization requests.
46733
+ * Returns Response error if invalid, undefined otherwise
46734
+ */
46735
+ validateSession(req) {
46736
+ if (this.sessionIdGenerator === void 0) {
46737
+ return void 0;
46738
+ }
46739
+ if (!this._initialized) {
46740
+ this.onerror?.(new Error("Bad Request: Server not initialized"));
46741
+ return this.createJsonErrorResponse(400, -32e3, "Bad Request: Server not initialized");
46742
+ }
46743
+ const sessionId = req.headers.get("mcp-session-id");
46744
+ if (!sessionId) {
46745
+ this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required"));
46746
+ return this.createJsonErrorResponse(400, -32e3, "Bad Request: Mcp-Session-Id header is required");
46747
+ }
46748
+ if (sessionId !== this.sessionId) {
46749
+ this.onerror?.(new Error("Session not found"));
46750
+ return this.createJsonErrorResponse(404, -32001, "Session not found");
46751
+ }
46752
+ return void 0;
46753
+ }
46754
+ /**
46755
+ * Validates the MCP-Protocol-Version header on incoming requests.
46756
+ *
46757
+ * For initialization: Version negotiation handles unknown versions gracefully
46758
+ * (server responds with its supported version).
46759
+ *
46760
+ * For subsequent requests with MCP-Protocol-Version header:
46761
+ * - Accept if in supported list
46762
+ * - 400 if unsupported
46763
+ *
46764
+ * For HTTP requests without the MCP-Protocol-Version header:
46765
+ * - Accept and default to the version negotiated at initialization
46766
+ */
46767
+ validateProtocolVersion(req) {
46768
+ const protocolVersion = req.headers.get("mcp-protocol-version");
46769
+ if (protocolVersion !== null && !SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) {
46770
+ this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")})`));
46771
+ return this.createJsonErrorResponse(400, -32e3, `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")})`);
46772
+ }
46773
+ return void 0;
46774
+ }
46775
+ async close() {
46776
+ if (this._closed) {
46777
+ return;
46778
+ }
46779
+ this._closed = true;
46780
+ this._streamMapping.forEach(({ cleanup }) => {
46781
+ cleanup();
46782
+ });
46783
+ this._streamMapping.clear();
46784
+ this._requestResponseMap.clear();
46785
+ this._resumableStreams.clear();
46786
+ this.onclose?.();
46787
+ }
46788
+ /**
46789
+ * Close an SSE stream for a specific request, triggering client reconnection.
46790
+ * Use this to implement polling behavior during long-running operations -
46791
+ * client will reconnect after the retry interval specified in the priming event.
46792
+ */
46793
+ closeSSEStream(requestId) {
46794
+ const streamId = this._requestToStreamMapping.get(requestId);
46795
+ if (!streamId)
46796
+ return;
46797
+ const stream = this._streamMapping.get(streamId);
46798
+ if (stream) {
46799
+ stream.cleanup();
46800
+ }
46801
+ }
46802
+ /**
46803
+ * Close the standalone GET SSE stream, triggering client reconnection.
46804
+ * Use this to implement polling behavior for server-initiated notifications.
46805
+ */
46806
+ closeStandaloneSSEStream() {
46807
+ const stream = this._streamMapping.get(this._standaloneSseStreamId);
46808
+ if (stream) {
46809
+ stream.cleanup();
46810
+ }
46811
+ }
46812
+ async send(message, options) {
46813
+ let requestId = options?.relatedRequestId;
46814
+ if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
46815
+ requestId = message.id;
46816
+ }
46817
+ if (requestId === void 0) {
46818
+ if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
46819
+ throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");
46820
+ }
46821
+ let eventId;
46822
+ if (this._eventStore) {
46823
+ eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message);
46824
+ }
46825
+ const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId);
46826
+ if (standaloneSse === void 0) {
46827
+ return;
46828
+ }
46829
+ if (standaloneSse.controller && standaloneSse.encoder && (eventId === void 0 || !standaloneSse.replayedEventIds?.has(eventId))) {
46830
+ this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId);
46831
+ }
46832
+ return;
46833
+ }
46834
+ const streamId = this._requestToStreamMapping.get(requestId);
46835
+ if (!streamId) {
46836
+ throw new Error(`No connection established for request ID: ${String(requestId)}`);
46837
+ }
46838
+ let stream = this._streamMapping.get(streamId);
46839
+ if (!this._enableJsonResponse) {
46840
+ let eventId;
46841
+ if (this._eventStore) {
46842
+ eventId = await this._eventStore.storeEvent(streamId, message);
46843
+ stream = this._streamMapping.get(streamId);
46844
+ }
46845
+ if (stream?.controller && stream?.encoder && (eventId === void 0 || !stream.replayedEventIds?.has(eventId))) {
46846
+ const written = this.writeSSEEvent(stream.controller, stream.encoder, message, eventId);
46847
+ if (written && eventId !== void 0) {
46848
+ this._resumableStreams.add(streamId);
46849
+ }
46850
+ }
46851
+ }
46852
+ if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
46853
+ this._requestResponseMap.set(requestId, message);
46854
+ const relatedIds = Array.from(this._requestToStreamMapping.entries()).filter(([_, sid]) => sid === streamId).map(([id]) => id);
46855
+ const allResponsesReady = relatedIds.every((id) => this._requestResponseMap.has(id));
46856
+ if (allResponsesReady) {
46857
+ if (!stream) {
46858
+ if (this._closed) {
46859
+ for (const id of relatedIds) {
46860
+ this._requestResponseMap.delete(id);
46861
+ this._requestToStreamMapping.delete(id);
46862
+ }
46863
+ return;
46864
+ }
46865
+ if (!this._enableJsonResponse && this._eventStore && this._resumableStreams.has(streamId)) {
46866
+ for (const id of relatedIds) {
46867
+ this._requestResponseMap.delete(id);
46868
+ this._requestToStreamMapping.delete(id);
46869
+ }
46870
+ this._resumableStreams.delete(streamId);
46871
+ return;
46872
+ }
46873
+ for (const id of relatedIds) {
46874
+ this._requestResponseMap.delete(id);
46875
+ this._requestToStreamMapping.delete(id);
46876
+ }
46877
+ throw new Error(`No connection established for request ID: ${String(requestId)}`);
46878
+ }
46879
+ if (this._enableJsonResponse && stream.resolveJson) {
46880
+ const headers = {
46881
+ "Content-Type": "application/json"
46882
+ };
46883
+ if (this.sessionId !== void 0) {
46884
+ headers["mcp-session-id"] = this.sessionId;
46885
+ }
46886
+ const responses = relatedIds.map((id) => this._requestResponseMap.get(id));
46887
+ if (responses.length === 1) {
46888
+ stream.resolveJson(new Response(JSON.stringify(responses[0]), { status: 200, headers }));
46889
+ } else {
46890
+ stream.resolveJson(new Response(JSON.stringify(responses), { status: 200, headers }));
46891
+ }
46892
+ } else {
46893
+ stream.cleanup();
46894
+ }
46895
+ for (const id of relatedIds) {
46896
+ this._requestResponseMap.delete(id);
46897
+ this._requestToStreamMapping.delete(id);
46898
+ }
46899
+ this._resumableStreams.delete(streamId);
46900
+ }
46901
+ }
46902
+ }
46903
+ };
46904
+
45767
46905
  // src/db/connection.ts
45768
46906
  var DATABASE_CONNECTION_ENV_VAR = "MAGENTO_REST_DATABASE_CONNECTION";
45769
46907
  var DATABASE_PASSWORD_ENV_VAR = "MAGENTO_REST_DATABASE_PASSWORD";
@@ -46501,7 +47639,7 @@ function normalizeBaseUrl(baseUrl) {
46501
47639
  }
46502
47640
  return baseUrl.replace(/\/+$/, "");
46503
47641
  }
46504
- var SCOPED_BASE = /^(.*\/rest)(?:\/[A-Za-z0-9_]+)?\/V1$/;
47642
+ var SCOPED_BASE = /^(.*\/rest)(?:\/([A-Za-z0-9_]+))?\/V1$/;
46505
47643
  var STORE_CODE = /^[A-Za-z][A-Za-z0-9_]{0,31}$/;
46506
47644
  function scopedBase(restRoot, scope) {
46507
47645
  if (!STORE_CODE.test(scope)) {
@@ -46529,7 +47667,9 @@ function retryAfterMs(response) {
46529
47667
  }
46530
47668
  function createRestTransport(deps) {
46531
47669
  const baseUrl = normalizeBaseUrl(deps.baseUrl);
46532
- const restRoot = SCOPED_BASE.exec(baseUrl)?.[1];
47670
+ const scopedMatch = SCOPED_BASE.exec(baseUrl);
47671
+ const restRoot = scopedMatch?.[1];
47672
+ const baseStoreView = scopedMatch?.[2];
46533
47673
  const random = deps.random ?? Math.random;
46534
47674
  const timeoutMs = deps.timeoutMs ?? DEFAULT_REST_TIMEOUT_MS;
46535
47675
  const rateLimiter = new TokenBucketRateLimiter(REST_PACE, { now: deps.now, sleep: deps.sleep });
@@ -46583,6 +47723,17 @@ function createRestTransport(deps) {
46583
47723
  };
46584
47724
  }
46585
47725
  }
47726
+ function answerFor(request, root) {
47727
+ const pathname = new URL(`${root}${request.path}`).pathname;
47728
+ const fromRest = pathname.indexOf("/rest/");
47729
+ const scope = request.scope ?? baseStoreView;
47730
+ const storeView = scope === "all" ? void 0 : scope;
47731
+ return {
47732
+ endpoint: `${request.method} ${fromRest >= 0 ? pathname.slice(fromRest) : pathname}`,
47733
+ readAt: new Date(deps.now()).toISOString(),
47734
+ ...storeView !== void 0 ? { storeView } : {}
47735
+ };
47736
+ }
46586
47737
  return {
46587
47738
  async request(request) {
46588
47739
  assertPath(request.path);
@@ -46594,6 +47745,7 @@ function createRestTransport(deps) {
46594
47745
  }
46595
47746
  const outcome = await attemptOnce(request, root);
46596
47747
  if ("value" in outcome) {
47748
+ request.onAnswered?.(answerFor(request, root));
46597
47749
  return outcome.value;
46598
47750
  }
46599
47751
  const decision = decideRetry(
@@ -46850,8 +48002,8 @@ function readSearchBody(body) {
46850
48002
  function createMagentoRestClient(deps) {
46851
48003
  return clientView(createRestTransport(deps), {});
46852
48004
  }
46853
- function clientView(transport2, options) {
46854
- const send = (request) => transport2.request({ ...request, ...options });
48005
+ function clientView(transport, options) {
48006
+ const send = (request) => transport.request({ ...request, ...options });
46855
48007
  async function search(path, criteria) {
46856
48008
  return readSearchBody(await send({ method: "GET", path, query: buildSearchCriteria(criteria) }));
46857
48009
  }
@@ -46879,7 +48031,7 @@ function clientView(transport2, options) {
46879
48031
  }
46880
48032
  return { items, totalCount, truncated: true };
46881
48033
  },
46882
- with: (more) => clientView(transport2, { ...options, ...more })
48034
+ with: (more) => clientView(transport, { ...options, ...more })
46883
48035
  };
46884
48036
  }
46885
48037
 
@@ -46906,7 +48058,7 @@ function num(value) {
46906
48058
  return Number.isFinite(n) ? n : 0;
46907
48059
  }
46908
48060
  var round2 = (value) => Number(value.toFixed(2));
46909
- function list(value) {
48061
+ function list2(value) {
46910
48062
  return Array.isArray(value) ? value : [];
46911
48063
  }
46912
48064
  function money(order, baseKey, plainKey) {
@@ -46970,7 +48122,7 @@ function coverage(fetched) {
46970
48122
  }
46971
48123
  function inCountry(order, code) {
46972
48124
  const billing = text(field(field(order, "billing_address"), "country_id"));
46973
- const assignment = list(field(field(order, "extension_attributes"), "shipping_assignments"))[0];
48125
+ const assignment = list2(field(field(order, "extension_attributes"), "shipping_assignments"))[0];
46974
48126
  const shipping = text(field(field(field(assignment, "shipping"), "address"), "country_id"));
46975
48127
  return [billing, shipping].some((candidate) => candidate?.toUpperCase() === code);
46976
48128
  }
@@ -47093,7 +48245,7 @@ function analyticsTools({ readTool }) {
47093
48245
  const products = /* @__PURE__ */ new Map();
47094
48246
  for (const order of orders) {
47095
48247
  revenue += money(order, "base_grand_total", "grand_total");
47096
- for (const item of list(field(order, "items"))) {
48248
+ for (const item of list2(field(order, "items"))) {
47097
48249
  const sku2 = text(field(item, "sku"));
47098
48250
  const qty = num(field(item, "qty_ordered"));
47099
48251
  itemCount += 1;
@@ -47153,7 +48305,7 @@ function analyticsTools({ readTool }) {
47153
48305
  }),
47154
48306
  readTool({
47155
48307
  name: "magentorest_get_customer_ordered_products_by_email",
47156
- description: "Use this to list every order of one customer, found by exact email, with each order's lines (SKU, name, price, quantity). Returns the customer's id, name and email, never their addresses. For a product's own detail use magentorest_get_product_by_sku. Reads at most max_pages pages of 100 orders and says when the result is partial.",
48308
+ description: "Use this to list every order of one customer, found by exact email, with each order's lines (SKU, name, price, quantity). Returns the customer's id, name and email only when the server runs with MAGENTO_REST_CUSTOMER_DATA=true, never their addresses. For a product's own detail use magentorest_get_product_by_sku. Reads at most max_pages pages of 100 orders and says when the result is partial.",
47157
48309
  input: external_exports.object({ email: external_exports.email().max(254).describe("The customer's email address (exact)."), max_pages: maxPages }).strict(),
47158
48310
  shape: [
47159
48311
  ["customer", ["id", "email", "firstname", "lastname"]],
@@ -47177,7 +48329,7 @@ function analyticsTools({ readTool }) {
47177
48329
  created_at: field(order, "created_at"),
47178
48330
  status: field(order, "status"),
47179
48331
  total: field(order, "grand_total"),
47180
- items: list(field(order, "items"))
48332
+ items: list2(field(order, "items"))
47181
48333
  })),
47182
48334
  coverage: { orders_returned: analysed, orders_total: fetched.totalCount, truncated: fetched.truncated },
47183
48335
  ...fetched.truncated ? { warning: `Partial result: only ${analysed} of ${fetched.totalCount} orders were returned. Raise max_pages (up to 50) to see more.` } : {}
@@ -47579,7 +48731,7 @@ function cartTools({ readTool, shapes }) {
47579
48731
  return [
47580
48732
  readTool({
47581
48733
  name: "magentorest_get_cart_by_id",
47582
- description: "Use this to read one cart by ID: activity, item count and quantity, currency, the customer's identity (id, name, email, group) and the cart lines. Addresses are not returned.",
48734
+ description: "Use this to read one cart by ID: activity, item count and quantity, currency and the cart lines; the customer's identity (id, name, email, group) only when the server runs with MAGENTO_REST_CUSTOMER_DATA=true. Addresses are not returned.",
47583
48735
  input: external_exports.object({ cart_id: cartId }).strict(),
47584
48736
  shape: shapes.cart,
47585
48737
  run: ({ cart_id }, client) => client.get(restPath`/carts/${cart_id}`)
@@ -47624,7 +48776,7 @@ function cartTools({ readTool, shapes }) {
47624
48776
  }),
47625
48777
  readTool({
47626
48778
  name: "magentorest_get_abandoned_carts",
47627
- description: "Use this to find abandoned carts: active, non-empty carts not updated for at least a number of days, most recently updated first. Each entry names the owner (or Guest), the item count and the dates. Returns a bounded page, the total count and the cutoff used.",
48779
+ description: "Use this to find abandoned carts: active, non-empty carts not updated for at least a number of days, most recently updated first. Each entry gives the item count and the dates, and names the owner (or Guest) only when the server runs with MAGENTO_REST_CUSTOMER_DATA=true. Returns a bounded page, the total count and the cutoff used.",
47628
48780
  input: external_exports.object({
47629
48781
  days_old: external_exports.number().int().min(0).max(3650).optional().describe("Minimum days since the cart was last updated (default 7)."),
47630
48782
  page_size: pageSize,
@@ -47968,7 +49120,7 @@ function customerTools({ readTool, writeTool, shapes }) {
47968
49120
  return [
47969
49121
  readTool({
47970
49122
  name: "magentorest_get_customer_by_id",
47971
- description: "Use this to read one customer by numeric ID: name, email, group, website, store and the default address IDs. Date of birth, tax number and the address book are not returned.",
49123
+ description: "Use this to read one customer by numeric ID: group, website, store and the default address IDs, plus name and email only when the server runs with MAGENTO_REST_CUSTOMER_DATA=true. Date of birth, tax number and the address book are not returned.",
47972
49124
  input: external_exports.object({ customer_id: entityId("customer") }).strict(),
47973
49125
  shape: shapes.customer,
47974
49126
  run: ({ customer_id }, client) => client.get(restPath`/customers/${customer_id}`)
@@ -48017,7 +49169,7 @@ function customerTools({ readTool, writeTool, shapes }) {
48017
49169
  }),
48018
49170
  readTool({
48019
49171
  name: "magentorest_get_customer_addresses",
48020
- description: "Use this to list a customer's addresses by location: country, region, city, postcode and which is the default billing or shipping address. Street, telephone and the addressee are not returned.",
49172
+ description: "Use this to list a customer's addresses by location: country, region and which is the default billing or shipping address, plus city and postcode only when the server runs with MAGENTO_REST_CUSTOMER_DATA=true. Street, telephone and the addressee are not returned.",
48021
49173
  input: external_exports.object({ customer_id: entityId("customer") }).strict(),
48022
49174
  shape: shapes.customer_address,
48023
49175
  run: async ({ customer_id }, client) => {
@@ -48089,6 +49241,91 @@ function customerTools({ readTool, writeTool, shapes }) {
48089
49241
  ];
48090
49242
  }
48091
49243
 
49244
+ // src/tools/customer-data.ts
49245
+ var PERSONAL_FIELDS = /* @__PURE__ */ new Set([
49246
+ "email",
49247
+ "firstname",
49248
+ "middlename",
49249
+ "lastname",
49250
+ "prefix",
49251
+ "suffix",
49252
+ "telephone",
49253
+ "fax",
49254
+ "street",
49255
+ "company",
49256
+ "dob",
49257
+ "taxvat",
49258
+ "gender",
49259
+ "remote_ip",
49260
+ "x_forwarded_for",
49261
+ // A cart's embedded customer record.
49262
+ "customer",
49263
+ // An order's copy of the customer's identity. `customer_is_guest` stays: it says nothing about who.
49264
+ "customer_id",
49265
+ "customer_email",
49266
+ "customer_firstname",
49267
+ "customer_middlename",
49268
+ "customer_lastname",
49269
+ "customer_prefix",
49270
+ "customer_suffix",
49271
+ "customer_name",
49272
+ "customer_dob",
49273
+ "customer_taxvat",
49274
+ "customer_gender",
49275
+ "customer_note"
49276
+ ]);
49277
+ var CUSTOMER_ADDRESS_FIELDS = /* @__PURE__ */ new Set(["city", "postcode"]);
49278
+ function without(shape, fields) {
49279
+ const kept = [];
49280
+ for (const entry of shape) {
49281
+ if (typeof entry === "string") {
49282
+ if (!fields.has(entry)) kept.push(entry);
49283
+ } else if (!fields.has(entry[0])) {
49284
+ kept.push([entry[0], without(entry[1], fields)]);
49285
+ }
49286
+ }
49287
+ return kept;
49288
+ }
49289
+ function withoutCustomerData(shape) {
49290
+ return without(shape, PERSONAL_FIELDS);
49291
+ }
49292
+ function withoutCustomerDataShapes(shapes) {
49293
+ const stripped = Object.fromEntries(Object.entries(shapes).map(([resource, shape]) => [resource, withoutCustomerData(shape)]));
49294
+ return { ...stripped, customer_address: without(stripped.customer_address, CUSTOMER_ADDRESS_FIELDS) };
49295
+ }
49296
+
49297
+ // src/tools/output-schema.ts
49298
+ var primitive = external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null()]);
49299
+ function objectFor(shape) {
49300
+ const fields = {};
49301
+ for (const entry of shape) {
49302
+ if (typeof entry === "string") {
49303
+ fields[entry] = external_exports.unknown().optional();
49304
+ } else {
49305
+ fields[entry[0]] = valueFor(entry[1]).optional();
49306
+ }
49307
+ }
49308
+ return external_exports.object(fields);
49309
+ }
49310
+ function valueFor(shape) {
49311
+ const element = external_exports.union([objectFor(shape), primitive]);
49312
+ return external_exports.union([element, external_exports.array(element)]);
49313
+ }
49314
+ var provenanceSchema = external_exports.object({
49315
+ /** The first request: method and path from `/rest` on, with no host, query string or token. */
49316
+ endpoint: external_exports.string(),
49317
+ /** Each distinct endpoint, in the order first used, when the tool used more than one (a paged walk counts once). */
49318
+ endpoints: external_exports.array(external_exports.string()).optional(),
49319
+ api_version: external_exports.literal("V1"),
49320
+ /** ISO 8601 UTC, when Magento answered the last request. */
49321
+ read_at: external_exports.string(),
49322
+ /** The store view the requests addressed, when the URL named one. */
49323
+ store_view: external_exports.string().optional()
49324
+ });
49325
+ function readOutputSchema(shape) {
49326
+ return external_exports.object({ result: valueFor(shape), provenance: provenanceSchema });
49327
+ }
49328
+
48092
49329
  // src/tools/project.ts
48093
49330
  function isPrimitive(value) {
48094
49331
  return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
@@ -48233,24 +49470,47 @@ var WRITE_ANNOTATIONS = {
48233
49470
  delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
48234
49471
  action: { readOnlyHint: false, destructiveHint: true, idempotentHint: false }
48235
49472
  };
49473
+ function provenanceOf(answers) {
49474
+ const first = answers[0];
49475
+ const last = answers.at(-1);
49476
+ if (first === void 0 || last === void 0) {
49477
+ throw new Error("The read produced no Magento answer to cite, so its result cannot carry provenance.");
49478
+ }
49479
+ const endpoints = [...new Set(answers.map((answer) => answer.endpoint))];
49480
+ return {
49481
+ endpoint: first.endpoint,
49482
+ ...endpoints.length > 1 ? { endpoints } : {},
49483
+ api_version: "V1",
49484
+ read_at: last.readAt,
49485
+ ...first.storeView !== void 0 ? { store_view: first.storeView } : {}
49486
+ };
49487
+ }
48236
49488
  function createToolFactory(getClient, options = {}) {
48237
49489
  const liveVerified = options.liveVerified ?? LIVE_VERIFIED_TOOLS;
48238
49490
  const shapes = options.shapes ?? BASE_SHAPES;
48239
- function build(spec, annotations, access) {
49491
+ function build(given, annotations, access) {
49492
+ const spec = options.withoutCustomerData === true ? { ...given, shape: withoutCustomerData(given.shape) } : given;
49493
+ const structured = access === "read";
48240
49494
  const description = liveVerified.has(spec.name) ? spec.description : `${spec.description} ${UNVERIFIED_MARKER} \u2014 ${UNVERIFIED_DETAIL}`;
48241
49495
  const tool = defineTool({
48242
49496
  name: spec.name,
48243
49497
  description,
48244
49498
  inputSchema: spec.input,
49499
+ ...structured ? { outputSchema: readOutputSchema(spec.shape) } : {},
48245
49500
  annotations,
48246
49501
  handler: async (args, ctx) => {
48247
49502
  const client = getClient();
48248
- const raw = await spec.run(args, ctx.signal !== void 0 ? client.with({ signal: ctx.signal }) : client);
49503
+ const answers = [];
49504
+ const requestOptions = { ...ctx.signal !== void 0 ? { signal: ctx.signal } : {}, ...structured ? { onAnswered: (answer) => answers.push(answer) } : {} };
49505
+ const raw = await spec.run(args, Object.keys(requestOptions).length > 0 ? client.with(requestOptions) : client);
48249
49506
  const projected = project(raw, spec.shape);
49507
+ let result;
48250
49508
  if (hasContent(raw) && isEmptyShell(projected)) {
48251
- return NOTHING_REPORTED_NOTICE;
49509
+ result = NOTHING_REPORTED_NOTICE;
49510
+ } else {
49511
+ result = projected === void 0 ? null : projected;
48252
49512
  }
48253
- return projected === void 0 ? null : projected;
49513
+ return structured ? { result, provenance: provenanceOf(answers) } : result;
48254
49514
  }
48255
49515
  });
48256
49516
  return { ...tool, access };
@@ -48975,7 +50235,7 @@ function orderTools({ readTool, writeTool, shapes }) {
48975
50235
  return [
48976
50236
  readTool({
48977
50237
  name: "magentorest_get_order_by_id",
48978
- description: "Use this to read one order by entity ID: status, state, totals, currency, the customer as the order records it, and the order lines. Billing and shipping addresses and payment details are not returned.",
50238
+ description: "Use this to read one order by entity ID: status, state, totals, currency and the order lines; who placed it (customer ID, name, email) only when the server runs with MAGENTO_REST_CUSTOMER_DATA=true. Billing and shipping addresses and payment details are not returned.",
48979
50239
  input: external_exports.object({ order_id: orderId }).strict(),
48980
50240
  shape: shapes.order,
48981
50241
  run: ({ order_id }, client) => client.get(restPath`/orders/${order_id}`)
@@ -49421,20 +50681,20 @@ function parseGroups(value) {
49421
50681
  assertKnownGroups(names);
49422
50682
  return names;
49423
50683
  }
49424
- function assertUniqueNames(tools) {
50684
+ function assertUniqueNames(tools2) {
49425
50685
  const seen = /* @__PURE__ */ new Set();
49426
- for (const tool of tools) {
50686
+ for (const tool of tools2) {
49427
50687
  if (seen.has(tool.name)) {
49428
50688
  throw new Error(`Duplicate tool name registered: ${tool.name}`);
49429
50689
  }
49430
50690
  seen.add(tool.name);
49431
50691
  }
49432
50692
  }
49433
- function assemble(getRuntime2, shapes, groups2 = REST_GROUP_NAMES) {
49434
- const factory = createToolFactory(() => getRuntime2().client, { shapes });
49435
- const tools = groups2.flatMap((group) => GROUPS[group](factory));
49436
- assertUniqueNames(tools);
49437
- return tools;
50693
+ function assemble(getRuntime2, shapes, groups2 = REST_GROUP_NAMES, customerData2 = true) {
50694
+ const factory = createToolFactory(() => getRuntime2().client, { shapes: customerData2 ? shapes : withoutCustomerDataShapes(shapes), withoutCustomerData: !customerData2 });
50695
+ const tools2 = groups2.flatMap((group) => GROUPS[group](factory));
50696
+ assertUniqueNames(tools2);
50697
+ return tools2;
49438
50698
  }
49439
50699
  function createMagentoRestTools(options) {
49440
50700
  const chosen = assertKnownGroups(options.groups ?? []);
@@ -49442,14 +50702,14 @@ function createMagentoRestTools(options) {
49442
50702
  throw new Error("The database group needs a database: set MAGENTO_REST_DATABASE_CONNECTION (and its password), or leave `database` out of MAGENTO_REST_GROUPS.");
49443
50703
  }
49444
50704
  const restGroups = (chosen.length > 0 ? chosen : REST_GROUP_NAMES).filter(isGroupName);
49445
- const rest = assemble(options.getRuntime, applyFieldConfig(BASE_SHAPES, options.fieldConfig ?? {}), restGroups);
50705
+ const rest = assemble(options.getRuntime, applyFieldConfig(BASE_SHAPES, options.fieldConfig ?? {}), restGroups, options.customerData === true);
49446
50706
  const restTools = options.writesEnabled ? rest : rest.filter((tool) => tool.access === "read");
49447
50707
  const database2 = options.database;
49448
50708
  const wantsDatabase = database2 !== void 0 && (chosen.length === 0 || chosen.includes(DATABASE_GROUP));
49449
50709
  const dbTools = wantsDatabase ? databaseTools(database2).filter((tool) => tool.access === "read" || database2.writesEnabled) : [];
49450
- const tools = [...restTools, ...dbTools];
49451
- assertUniqueNames(tools);
49452
- return tools;
50710
+ const tools2 = [...restTools, ...dbTools];
50711
+ assertUniqueNames(tools2);
50712
+ return tools2;
49453
50713
  }
49454
50714
 
49455
50715
  // src/tools/runtime.ts
@@ -49485,6 +50745,8 @@ function createMagentoTokenProvider(configDir) {
49485
50745
  // src/tools/runtime.ts
49486
50746
  var BASE_URL_ENV_VAR = "MAGENTO_REST_BASE_URL";
49487
50747
  var ALLOW_WRITES_ENV_VAR = "MAGENTO_REST_ALLOW_WRITES";
50748
+ var MCP_WRITES_ENV_VAR = "MCP_WRITES_ENABLED";
50749
+ var CUSTOMER_DATA_ENV_VAR = "MAGENTO_REST_CUSTOMER_DATA";
49488
50750
  var FIELDS_FILE_ENV_VAR = "MAGENTO_REST_FIELDS_FILE";
49489
50751
  var GROUPS_ENV_VAR = "MAGENTO_REST_GROUPS";
49490
50752
  function createRuntimeResolver() {
@@ -49509,7 +50771,13 @@ function createRuntimeResolver() {
49509
50771
  };
49510
50772
  }
49511
50773
  function writesEnabled() {
49512
- return process.env[ALLOW_WRITES_ENV_VAR] === "true";
50774
+ return process.env[writesSwitchName()] === "true";
50775
+ }
50776
+ function writesSwitchName() {
50777
+ return process.env[MCP_WRITES_ENV_VAR] !== void 0 ? MCP_WRITES_ENV_VAR : ALLOW_WRITES_ENV_VAR;
50778
+ }
50779
+ function customerDataEnabled() {
50780
+ return process.env[CUSTOMER_DATA_ENV_VAR] === "true";
49513
50781
  }
49514
50782
  function readGroupsFromEnv() {
49515
50783
  try {
@@ -49609,39 +50877,42 @@ function loadDatabase() {
49609
50877
  var fieldConfig = loadFieldConfig();
49610
50878
  var groups = loadGroups();
49611
50879
  var database = loadDatabase();
49612
- var server = new McpServer(
49613
- {
49614
- name: "magento-rest",
49615
- version: serverVersion()
49616
- },
49617
- {
49618
- jsonSchemaValidator: noElicitationValidator
49619
- }
49620
- );
49621
50880
  var getRuntime = createRuntimeResolver();
49622
50881
  var writes = writesEnabled();
50882
+ var customerData = customerDataEnabled();
49623
50883
  function assembleTools() {
49624
50884
  try {
49625
- return createMagentoRestTools({ getRuntime, writesEnabled: writes, fieldConfig, groups, ...database !== void 0 ? { database } : {} });
50885
+ return createMagentoRestTools({ getRuntime, writesEnabled: writes, customerData, fieldConfig, groups, ...database !== void 0 ? { database } : {} });
49626
50886
  } catch (error61) {
49627
50887
  logger.error(`magento-rest: refusing to start \u2014 ${error61 instanceof Error ? error61.message : "invalid tool configuration"}`);
49628
50888
  process.exit(1);
49629
50889
  }
49630
50890
  }
49631
- for (const tool of assembleTools()) {
49632
- server.registerTool(
49633
- tool.name,
49634
- { description: tool.description, inputSchema: tool.inputSchema.shape, annotations: tool.annotations },
49635
- async (args, extra) => {
49636
- try {
49637
- const result = await tool.invoke(args, { signal: extra.signal });
49638
- return { content: [...result.content], isError: result.isError };
49639
- } catch (error61) {
49640
- const rendered = toErrorResult(error61);
49641
- return { content: [...rendered.content], isError: rendered.isError };
50891
+ var tools = assembleTools();
50892
+ function buildServer() {
50893
+ const server = new McpServer({ name: "magento-rest", version: serverVersion() }, { jsonSchemaValidator: noElicitationValidator });
50894
+ for (const tool of tools) {
50895
+ server.registerTool(
50896
+ tool.name,
50897
+ {
50898
+ description: tool.description,
50899
+ inputSchema: tool.inputSchema.shape,
50900
+ // A read tool declares the shape of its `structuredContent` (Kora contract R-2); the SDK lists it and checks every answer against it.
50901
+ ...tool.outputSchema !== void 0 ? { outputSchema: tool.outputSchema.shape } : {},
50902
+ annotations: tool.annotations
50903
+ },
50904
+ async (args, extra) => {
50905
+ try {
50906
+ const result = await tool.invoke(args, { signal: extra.signal });
50907
+ return { content: [...result.content], ...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : {}, isError: result.isError };
50908
+ } catch (error61) {
50909
+ const rendered = toErrorResult(error61);
50910
+ return { content: [...rendered.content], isError: rendered.isError };
50911
+ }
49642
50912
  }
49643
- }
49644
- );
50913
+ );
50914
+ }
50915
+ return server;
49645
50916
  }
49646
50917
  var changed = Object.entries(fieldConfig).map(([resource, change]) => `${resource} +${change.add?.length ?? 0} -${change.remove?.length ?? 0}`);
49647
50918
  if (changed.length > 0) {
@@ -49653,14 +50924,78 @@ if (groups.length > 0) {
49653
50924
  if (database !== void 0) {
49654
50925
  logger.warn(`magento-rest: database tools are enabled (MAGENTO_REST_DATABASE_CONNECTION); queries run in a read-only session${database.writesEnabled ? ", and db_execute is ENABLED (MAGENTO_REST_DATABASE_ALLOW_WRITES=true): this server can change database rows." : "."}`);
49655
50926
  }
50927
+ if (customerData) {
50928
+ logger.warn("magento-rest: customer personal data is ON (MAGENTO_REST_CUSTOMER_DATA=true); results carry customer names, emails and order identities.");
50929
+ }
49656
50930
  if (writes) {
49657
- logger.warn("magento-rest: write tools are ENABLED (MAGENTO_REST_ALLOW_WRITES=true); this server can change Magento data.");
50931
+ logger.warn(`magento-rest: write tools are ENABLED (${writesSwitchName()}=true); this server can change Magento data.`);
50932
+ }
50933
+ var HTTP_PORT_ENV_VAR = "MAGENTO_REST_HTTP_PORT";
50934
+ var HTTP_TOKEN_ENV_VAR = "MAGENTO_REST_HTTP_TOKEN";
50935
+ var HTTP_HOST_ENV_VAR = "MAGENTO_REST_HTTP_HOST";
50936
+ var HTTP_ALLOWED_HOSTS_ENV_VAR = "MAGENTO_REST_HTTP_ALLOWED_HOSTS";
50937
+ var HTTP_ALLOWED_ORIGINS_ENV_VAR = "MAGENTO_REST_HTTP_ALLOWED_ORIGINS";
50938
+ var HTTP_ENV_NAMES = {
50939
+ port: HTTP_PORT_ENV_VAR,
50940
+ token: HTTP_TOKEN_ENV_VAR,
50941
+ host: HTTP_HOST_ENV_VAR,
50942
+ allowedHosts: HTTP_ALLOWED_HOSTS_ENV_VAR,
50943
+ allowedOrigins: HTTP_ALLOWED_ORIGINS_ENV_VAR
50944
+ };
50945
+ function loadHttp() {
50946
+ try {
50947
+ return readHttpConfig(HTTP_ENV_NAMES, process.env);
50948
+ } catch (error61) {
50949
+ logger.error(`magento-rest: refusing to start \u2014 ${error61 instanceof Error ? error61.message : "invalid HTTP configuration"}`);
50950
+ process.exit(1);
50951
+ }
50952
+ }
50953
+ var http = loadHttp();
50954
+ var HTTP_SHUTDOWN_GRACE_MS = 5e3;
50955
+ if (http.enabled) {
50956
+ try {
50957
+ const endpoint = await startHttpEndpoint({
50958
+ token: http.token,
50959
+ host: http.host,
50960
+ port: http.port,
50961
+ allowedHosts: http.allowedHosts,
50962
+ allowedOrigins: http.allowedOrigins,
50963
+ handler: async (request) => {
50964
+ const transport = new WebStandardStreamableHTTPServerTransport({ enableJsonResponse: true });
50965
+ const server = buildServer();
50966
+ await server.connect(transport);
50967
+ try {
50968
+ return await transport.handleRequest(request);
50969
+ } finally {
50970
+ await server.close();
50971
+ }
50972
+ }
50973
+ });
50974
+ for (const signal of ["SIGTERM", "SIGINT"]) {
50975
+ process.once(signal, () => {
50976
+ logger.info(`magento-rest: ${signal} received, closing the HTTP endpoint`);
50977
+ void endpoint.close(HTTP_SHUTDOWN_GRACE_MS).then(() => process.exit(0));
50978
+ });
50979
+ }
50980
+ logger.info(`magento-rest: listening on http://${endpoint.host}:${endpoint.port}/mcp`);
50981
+ } catch (error61) {
50982
+ logger.error(`magento-rest: refusing to start \u2014 ${error61 instanceof Error ? error61.message : "invalid HTTP configuration"}`);
50983
+ process.exit(1);
50984
+ }
50985
+ } else {
50986
+ const { stdout } = createStdioServer();
50987
+ const transport = new StdioServerTransport(process.stdin, stdout);
50988
+ await buildServer().connect(transport);
49658
50989
  }
49659
- var { stdout } = createStdioServer();
49660
- var transport = new StdioServerTransport(process.stdin, stdout);
49661
- await server.connect(transport);
49662
50990
  /*! Bundled license information:
49663
50991
 
50992
+ content-type/index.js:
50993
+ (*!
50994
+ * content-type
50995
+ * Copyright(c) 2015 Douglas Christopher Wilson
50996
+ * MIT Licensed
50997
+ *)
50998
+
49664
50999
  long/umd/index.js:
49665
51000
  (**
49666
51001
  * @license