@hiberus-magento/magento-rest 0.1.0 → 0.3.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) {
@@ -103,7 +207,7 @@ var require_lib = __commonJS({
103
207
  SET_CLAUSE_TERMINATORS_BY_FIRST[first] = [word];
104
208
  }
105
209
  var hasOwnProperty = Object.prototype.hasOwnProperty;
106
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Set) && !(value instanceof Map);
210
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Set) && !(value instanceof Map);
107
211
  var isWordChar = (code) => code >= 65 && code <= 90 || code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 95;
108
212
  var isWhitespace = (code) => code === charCode.space || code === charCode.tab || code === charCode.newline || code === charCode.carriageReturn;
109
213
  var toLower = (code) => code | 32;
@@ -462,7 +566,7 @@ var require_lib = __commonJS({
462
566
  return String(value.toSqlString());
463
567
  if (!(stringifyObjects === void 0 || stringifyObjects === null))
464
568
  return escapeString(String(value));
465
- if (isRecord4(value) || value instanceof Map)
569
+ if (isRecord5(value) || value instanceof Map)
466
570
  return (0, exports.objectToValues)(value, timezone);
467
571
  return escapeString(String(value));
468
572
  }
@@ -500,7 +604,7 @@ var require_lib = __commonJS({
500
604
  else if (typeof currentValue === "number" || typeof currentValue === "bigint")
501
605
  escapedValue = `${currentValue}`;
502
606
  else if (typeof currentValue === "object" && currentValue !== null && !stringifyObjects) {
503
- const expandable = !(Array.isArray(currentValue) || currentValue instanceof Uint8Array || currentValue instanceof Date || hasSqlString(currentValue) || isDate(currentValue)) && (isRecord4(currentValue) || currentValue instanceof Map);
607
+ const expandable = !(Array.isArray(currentValue) || currentValue instanceof Uint8Array || currentValue instanceof Date || hasSqlString(currentValue) || isDate(currentValue)) && (isRecord5(currentValue) || currentValue instanceof Map);
504
608
  if (expandable) {
505
609
  let previous = placeholderPosition - 1;
506
610
  while (previous >= chunkIndex && isWhitespace(sql.charCodeAt(previous)))
@@ -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;
@@ -6495,12 +6599,12 @@ var require_helpers = __commonJS({
6495
6599
  const REQUIRE_TERMINATOR = "";
6496
6600
  highlightFn = __require(`cardinal${REQUIRE_TERMINATOR}`).highlight;
6497
6601
  } catch {
6498
- highlightFn = (text3) => {
6602
+ highlightFn = (text4) => {
6499
6603
  if (!cardinalRecommended) {
6500
6604
  console.log("For nicer debug output consider install cardinal@^2.0.0");
6501
6605
  cardinalRecommended = true;
6502
6606
  }
6503
- return text3;
6607
+ return text4;
6504
6608
  };
6505
6609
  }
6506
6610
  function printDebugWithCode(msg, code) {
@@ -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.3.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) {
@@ -17159,12 +17517,24 @@ function defineTool(def) {
17159
17517
  result = await def.handler(parsed, ctx);
17160
17518
  } catch (error61) {
17161
17519
  if (error61 instanceof MissingCredentialError || error61 instanceof CredentialExpiredError) {
17162
- return { content: [{ type: "text", text: error61.message }], isError: true };
17520
+ return { content: [{ type: "text", text: error61.message }], isError: true, errorKind: "credential" };
17163
17521
  }
17164
17522
  throw error61;
17165
17523
  }
17166
- const text3 = truncate(toTextContent(result), DEFAULT_MAX_OUTPUT_BYTES);
17167
- return { content: [{ type: "text", text: text3 }] };
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
+ errorKind: "too_large"
17532
+ };
17533
+ }
17534
+ return { content: [{ type: "text", text: json2 }], structuredContent: result };
17535
+ }
17536
+ const text4 = truncate(toTextContent(result), DEFAULT_MAX_OUTPUT_BYTES);
17537
+ return { content: [{ type: "text", text: text4 }] };
17168
17538
  }
17169
17539
  };
17170
17540
  }
@@ -26251,8 +26621,8 @@ function ko_default() {
26251
26621
  }
26252
26622
 
26253
26623
  // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/lt.js
26254
- var capitalizeFirstCharacter = (text3) => {
26255
- return text3.charAt(0).toUpperCase() + text3.slice(1);
26624
+ var capitalizeFirstCharacter = (text4) => {
26625
+ return text4.charAt(0).toUpperCase() + text4.slice(1);
26256
26626
  };
26257
26627
  function getUnitTypeFromNumber(number4) {
26258
26628
  const abs = Math.abs(number4);
@@ -40259,6 +40629,7 @@ function getLiteralValue(schema) {
40259
40629
 
40260
40630
  // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.5.4/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
40261
40631
  var LATEST_PROTOCOL_VERSION = "2025-11-25";
40632
+ var DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26";
40262
40633
  var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"];
40263
40634
  var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";
40264
40635
  var JSONRPC_VERSION = "2.0";
@@ -40587,6 +40958,7 @@ var InitializeRequestSchema = RequestSchema.extend({
40587
40958
  method: literal("initialize"),
40588
40959
  params: InitializeRequestParamsSchema
40589
40960
  });
40961
+ var isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success;
40590
40962
  var ServerCapabilitiesSchema = object({
40591
40963
  /**
40592
40964
  * Experimental, non-standard capabilities that the server supports.
@@ -43295,11 +43667,11 @@ var Protocol = class {
43295
43667
  *
43296
43668
  * 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
43669
  */
43298
- async connect(transport2) {
43670
+ async connect(transport) {
43299
43671
  if (this._transport) {
43300
43672
  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
43673
  }
43302
- this._transport = transport2;
43674
+ this._transport = transport;
43303
43675
  const _onclose = this.transport?.onclose;
43304
43676
  this._transport.onclose = () => {
43305
43677
  _onclose?.();
@@ -44898,8 +45270,8 @@ var McpServer = class {
44898
45270
  *
44899
45271
  * 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
45272
  */
44901
- async connect(transport2) {
44902
- return await this.server.connect(transport2);
45273
+ async connect(transport) {
45274
+ return await this.server.connect(transport);
44903
45275
  }
44904
45276
  /**
44905
45277
  * Closes the connection.
@@ -45764,6 +46136,773 @@ var StdioServerTransport = class {
45764
46136
  }
45765
46137
  };
45766
46138
 
46139
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.5.4/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.js
46140
+ var import_content_type = __toESM(require_content_type(), 1);
46141
+ function mediaTypeEssence(header) {
46142
+ if (!header) {
46143
+ return void 0;
46144
+ }
46145
+ try {
46146
+ return import_content_type.default.parse(header).type;
46147
+ } catch {
46148
+ const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase();
46149
+ if (essence === "" || header.slice(essence.length).includes(",")) {
46150
+ return void 0;
46151
+ }
46152
+ return essence;
46153
+ }
46154
+ }
46155
+ function isJsonContentType(header) {
46156
+ if (header === "application/json") {
46157
+ return true;
46158
+ }
46159
+ return mediaTypeEssence(header) === "application/json";
46160
+ }
46161
+
46162
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.5.4/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sseKeepAlive.js
46163
+ var DEFAULT_SSE_KEEP_ALIVE_MS = 15e3;
46164
+ var MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
46165
+ function armSseKeepAlive(intervalMs, onTick) {
46166
+ if (!Number.isFinite(intervalMs) || intervalMs < 1) {
46167
+ return void 0;
46168
+ }
46169
+ const timer = setInterval(onTick, Math.min(intervalMs, MAX_TIMER_DELAY_MS));
46170
+ timer.unref?.();
46171
+ return timer;
46172
+ }
46173
+
46174
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.5.4/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js
46175
+ var WebStandardStreamableHTTPServerTransport = class {
46176
+ constructor(options = {}) {
46177
+ this._started = false;
46178
+ this._hasHandledRequest = false;
46179
+ this._streamMapping = /* @__PURE__ */ new Map();
46180
+ this._requestToStreamMapping = /* @__PURE__ */ new Map();
46181
+ this._resumableStreams = /* @__PURE__ */ new Set();
46182
+ this._requestResponseMap = /* @__PURE__ */ new Map();
46183
+ this._initialized = false;
46184
+ this._enableJsonResponse = false;
46185
+ this._standaloneSseStreamId = "_GET_stream";
46186
+ this._closed = false;
46187
+ this.sessionIdGenerator = options.sessionIdGenerator;
46188
+ this._enableJsonResponse = options.enableJsonResponse ?? false;
46189
+ this._eventStore = options.eventStore;
46190
+ this._onsessioninitialized = options.onsessioninitialized;
46191
+ this._onsessionclosed = options.onsessionclosed;
46192
+ this._allowedHosts = options.allowedHosts;
46193
+ this._allowedOrigins = options.allowedOrigins;
46194
+ this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false;
46195
+ this._retryInterval = options.retryInterval;
46196
+ this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS;
46197
+ }
46198
+ /**
46199
+ * Arms a keep-alive interval for an SSE stream that periodically writes an SSE
46200
+ * comment frame so intermediaries and idle timeouts don't kill the connection.
46201
+ * The returned timer is owned by the stream it was armed for: the stream's
46202
+ * cancel/cleanup callbacks must clear it. The interval clears itself if a
46203
+ * write fails (stream already closed/cancelled).
46204
+ */
46205
+ startKeepAlive(controller, encoder) {
46206
+ if (this._closed)
46207
+ return void 0;
46208
+ const timer = armSseKeepAlive(this._keepAliveMs, () => {
46209
+ try {
46210
+ controller.enqueue(encoder.encode(": keepalive\n\n"));
46211
+ } catch {
46212
+ if (timer !== void 0)
46213
+ clearInterval(timer);
46214
+ }
46215
+ });
46216
+ return timer;
46217
+ }
46218
+ /**
46219
+ * Starts the transport. This is required by the Transport interface but is a no-op
46220
+ * for the Streamable HTTP transport as connections are managed per-request.
46221
+ */
46222
+ async start() {
46223
+ if (this._started) {
46224
+ throw new Error("Transport already started");
46225
+ }
46226
+ this._started = true;
46227
+ }
46228
+ /**
46229
+ * Helper to create a JSON error response
46230
+ */
46231
+ createJsonErrorResponse(status2, code, message, options) {
46232
+ const error61 = { code, message };
46233
+ if (options?.data !== void 0) {
46234
+ error61.data = options.data;
46235
+ }
46236
+ return new Response(JSON.stringify({
46237
+ jsonrpc: "2.0",
46238
+ error: error61,
46239
+ id: null
46240
+ }), {
46241
+ status: status2,
46242
+ headers: {
46243
+ "Content-Type": "application/json",
46244
+ ...options?.headers
46245
+ }
46246
+ });
46247
+ }
46248
+ /**
46249
+ * Validates request headers for DNS rebinding protection.
46250
+ * @returns Error response if validation fails, undefined if validation passes.
46251
+ */
46252
+ validateRequestHeaders(req) {
46253
+ if (!this._enableDnsRebindingProtection) {
46254
+ return void 0;
46255
+ }
46256
+ if (this._allowedHosts && this._allowedHosts.length > 0) {
46257
+ const hostHeader = req.headers.get("host");
46258
+ if (!hostHeader || !this._allowedHosts.includes(hostHeader)) {
46259
+ const error61 = `Invalid Host header: ${hostHeader}`;
46260
+ this.onerror?.(new Error(error61));
46261
+ return this.createJsonErrorResponse(403, -32e3, error61);
46262
+ }
46263
+ }
46264
+ if (this._allowedOrigins && this._allowedOrigins.length > 0) {
46265
+ const originHeader = req.headers.get("origin");
46266
+ if (originHeader && !this._allowedOrigins.includes(originHeader)) {
46267
+ const error61 = `Invalid Origin header: ${originHeader}`;
46268
+ this.onerror?.(new Error(error61));
46269
+ return this.createJsonErrorResponse(403, -32e3, error61);
46270
+ }
46271
+ }
46272
+ return void 0;
46273
+ }
46274
+ /**
46275
+ * Handles an incoming HTTP request, whether GET, POST, or DELETE
46276
+ * Returns a Response object (Web Standard)
46277
+ */
46278
+ async handleRequest(req, options) {
46279
+ if (this._closed) {
46280
+ return this.createJsonErrorResponse(404, -32001, "Session not found");
46281
+ }
46282
+ if (!this.sessionIdGenerator && this._hasHandledRequest) {
46283
+ throw new Error("Stateless transport cannot be reused across requests. Create a new transport per request.");
46284
+ }
46285
+ this._hasHandledRequest = true;
46286
+ const validationError = this.validateRequestHeaders(req);
46287
+ if (validationError) {
46288
+ return validationError;
46289
+ }
46290
+ switch (req.method) {
46291
+ case "POST":
46292
+ return this.handlePostRequest(req, options);
46293
+ case "GET":
46294
+ return this.handleGetRequest(req);
46295
+ case "DELETE":
46296
+ return this.handleDeleteRequest(req);
46297
+ default:
46298
+ return this.handleUnsupportedRequest();
46299
+ }
46300
+ }
46301
+ /**
46302
+ * Writes a priming event to establish resumption capability.
46303
+ * Only sends if eventStore is configured (opt-in for resumability) and
46304
+ * the client's protocol version supports empty SSE data (>= 2025-11-25).
46305
+ */
46306
+ async writePrimingEvent(controller, encoder, streamId, protocolVersion) {
46307
+ if (!this._eventStore) {
46308
+ return;
46309
+ }
46310
+ if (protocolVersion < "2025-11-25") {
46311
+ return;
46312
+ }
46313
+ const primingEventId = await this._eventStore.storeEvent(streamId, {});
46314
+ let primingEvent = `id: ${primingEventId}
46315
+ data:
46316
+
46317
+ `;
46318
+ if (this._retryInterval !== void 0) {
46319
+ primingEvent = `id: ${primingEventId}
46320
+ retry: ${this._retryInterval}
46321
+ data:
46322
+
46323
+ `;
46324
+ }
46325
+ controller.enqueue(encoder.encode(primingEvent));
46326
+ this._resumableStreams.add(streamId);
46327
+ }
46328
+ /**
46329
+ * Handles GET requests for SSE stream
46330
+ */
46331
+ async handleGetRequest(req) {
46332
+ const acceptHeader = req.headers.get("accept");
46333
+ if (!acceptHeader?.includes("text/event-stream")) {
46334
+ this.onerror?.(new Error("Not Acceptable: Client must accept text/event-stream"));
46335
+ return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept text/event-stream");
46336
+ }
46337
+ const sessionError = this.validateSession(req);
46338
+ if (sessionError) {
46339
+ return sessionError;
46340
+ }
46341
+ const protocolError = this.validateProtocolVersion(req);
46342
+ if (protocolError) {
46343
+ return protocolError;
46344
+ }
46345
+ if (this._eventStore) {
46346
+ const lastEventId = req.headers.get("last-event-id");
46347
+ if (lastEventId) {
46348
+ return this.replayEvents(lastEventId);
46349
+ }
46350
+ }
46351
+ if (this._streamMapping.get(this._standaloneSseStreamId) !== void 0) {
46352
+ this.onerror?.(new Error("Conflict: Only one SSE stream is allowed per session"));
46353
+ return this.createJsonErrorResponse(409, -32e3, "Conflict: Only one SSE stream is allowed per session");
46354
+ }
46355
+ const encoder = new TextEncoder();
46356
+ let streamController;
46357
+ let keepAliveTimer = void 0;
46358
+ const readable = new ReadableStream({
46359
+ start: (controller) => {
46360
+ streamController = controller;
46361
+ },
46362
+ cancel: () => {
46363
+ if (keepAliveTimer !== void 0) {
46364
+ clearInterval(keepAliveTimer);
46365
+ }
46366
+ if (this._streamMapping.get(this._standaloneSseStreamId)?.controller === streamController) {
46367
+ this._streamMapping.delete(this._standaloneSseStreamId);
46368
+ }
46369
+ }
46370
+ });
46371
+ const headers = {
46372
+ "Content-Type": "text/event-stream",
46373
+ "Cache-Control": "no-cache, no-transform",
46374
+ Connection: "keep-alive",
46375
+ "X-Accel-Buffering": "no"
46376
+ };
46377
+ if (this.sessionId !== void 0) {
46378
+ headers["mcp-session-id"] = this.sessionId;
46379
+ }
46380
+ this._streamMapping.set(this._standaloneSseStreamId, {
46381
+ controller: streamController,
46382
+ encoder,
46383
+ cleanup: () => {
46384
+ if (keepAliveTimer !== void 0) {
46385
+ clearInterval(keepAliveTimer);
46386
+ }
46387
+ this._streamMapping.delete(this._standaloneSseStreamId);
46388
+ try {
46389
+ streamController.close();
46390
+ } catch {
46391
+ }
46392
+ }
46393
+ });
46394
+ keepAliveTimer = this.startKeepAlive(streamController, encoder);
46395
+ return new Response(readable, { headers });
46396
+ }
46397
+ /**
46398
+ * Replays events that would have been sent after the specified event ID
46399
+ * Only used when resumability is enabled
46400
+ */
46401
+ async replayEvents(lastEventId) {
46402
+ if (!this._eventStore) {
46403
+ this.onerror?.(new Error("Event store not configured"));
46404
+ return this.createJsonErrorResponse(400, -32e3, "Event store not configured");
46405
+ }
46406
+ try {
46407
+ let streamId;
46408
+ if (this._eventStore.getStreamIdForEventId) {
46409
+ streamId = await this._eventStore.getStreamIdForEventId(lastEventId);
46410
+ if (!streamId) {
46411
+ this.onerror?.(new Error("Invalid event ID format"));
46412
+ return this.createJsonErrorResponse(400, -32e3, "Invalid event ID format");
46413
+ }
46414
+ if (this._streamMapping.get(streamId) !== void 0) {
46415
+ this.onerror?.(new Error("Conflict: Stream already has an active connection"));
46416
+ return this.createJsonErrorResponse(409, -32e3, "Conflict: Stream already has an active connection");
46417
+ }
46418
+ }
46419
+ const headers = {
46420
+ "Content-Type": "text/event-stream",
46421
+ "Cache-Control": "no-cache, no-transform",
46422
+ Connection: "keep-alive",
46423
+ "X-Accel-Buffering": "no"
46424
+ };
46425
+ if (this.sessionId !== void 0) {
46426
+ headers["mcp-session-id"] = this.sessionId;
46427
+ }
46428
+ const encoder = new TextEncoder();
46429
+ let streamController;
46430
+ let keepAliveTimer = void 0;
46431
+ let replayedStreamId = void 0;
46432
+ let cancelled2 = false;
46433
+ const readable = new ReadableStream({
46434
+ start: (controller) => {
46435
+ streamController = controller;
46436
+ },
46437
+ cancel: () => {
46438
+ cancelled2 = true;
46439
+ if (keepAliveTimer !== void 0) {
46440
+ clearInterval(keepAliveTimer);
46441
+ }
46442
+ if (replayedStreamId !== void 0 && this._streamMapping.get(replayedStreamId)?.controller === streamController) {
46443
+ this._streamMapping.delete(replayedStreamId);
46444
+ }
46445
+ }
46446
+ });
46447
+ const replayedEventIds = /* @__PURE__ */ new Set();
46448
+ replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, {
46449
+ send: async (eventId, message) => {
46450
+ const success2 = this.writeSSEEvent(streamController, encoder, message, eventId);
46451
+ if (!success2) {
46452
+ this.onerror?.(new Error("Failed replay events"));
46453
+ try {
46454
+ streamController.close();
46455
+ } catch {
46456
+ }
46457
+ } else {
46458
+ replayedEventIds.add(eventId);
46459
+ }
46460
+ }
46461
+ });
46462
+ if (this._closed || cancelled2) {
46463
+ try {
46464
+ streamController.close();
46465
+ } catch {
46466
+ }
46467
+ return this.createJsonErrorResponse(404, -32001, "Session not found");
46468
+ }
46469
+ this._streamMapping.get(replayedStreamId)?.cleanup();
46470
+ this._streamMapping.set(replayedStreamId, {
46471
+ controller: streamController,
46472
+ encoder,
46473
+ replayedEventIds,
46474
+ cleanup: () => {
46475
+ if (keepAliveTimer !== void 0) {
46476
+ clearInterval(keepAliveTimer);
46477
+ }
46478
+ this._streamMapping.delete(replayedStreamId);
46479
+ try {
46480
+ streamController.close();
46481
+ } catch {
46482
+ }
46483
+ }
46484
+ });
46485
+ this._resumableStreams.add(replayedStreamId);
46486
+ keepAliveTimer = this.startKeepAlive(streamController, encoder);
46487
+ return new Response(readable, { headers });
46488
+ } catch (error61) {
46489
+ this.onerror?.(error61);
46490
+ return this.createJsonErrorResponse(500, -32e3, "Error replaying events");
46491
+ }
46492
+ }
46493
+ /**
46494
+ * Writes an event to an SSE stream via controller with proper formatting
46495
+ */
46496
+ writeSSEEvent(controller, encoder, message, eventId) {
46497
+ try {
46498
+ let eventData = `event: message
46499
+ `;
46500
+ if (eventId) {
46501
+ eventData += `id: ${eventId}
46502
+ `;
46503
+ }
46504
+ eventData += `data: ${JSON.stringify(message)}
46505
+
46506
+ `;
46507
+ controller.enqueue(encoder.encode(eventData));
46508
+ return true;
46509
+ } catch (error61) {
46510
+ this.onerror?.(error61);
46511
+ return false;
46512
+ }
46513
+ }
46514
+ /**
46515
+ * Handles unsupported requests (PUT, PATCH, etc.)
46516
+ */
46517
+ handleUnsupportedRequest() {
46518
+ this.onerror?.(new Error("Method not allowed."));
46519
+ return new Response(JSON.stringify({
46520
+ jsonrpc: "2.0",
46521
+ error: {
46522
+ code: -32e3,
46523
+ message: "Method not allowed."
46524
+ },
46525
+ id: null
46526
+ }), {
46527
+ status: 405,
46528
+ headers: {
46529
+ Allow: "GET, POST, DELETE",
46530
+ "Content-Type": "application/json"
46531
+ }
46532
+ });
46533
+ }
46534
+ /**
46535
+ * Handles POST requests containing JSON-RPC messages
46536
+ */
46537
+ async handlePostRequest(req, options) {
46538
+ try {
46539
+ const acceptHeader = req.headers.get("accept");
46540
+ if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
46541
+ this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream"));
46542
+ return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept both application/json and text/event-stream");
46543
+ }
46544
+ const ct = req.headers.get("content-type");
46545
+ if (!isJsonContentType(ct)) {
46546
+ this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json"));
46547
+ return this.createJsonErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json");
46548
+ }
46549
+ const requestInfo = {
46550
+ headers: Object.fromEntries(req.headers.entries()),
46551
+ url: new URL(req.url)
46552
+ };
46553
+ let rawMessage;
46554
+ if (options?.parsedBody !== void 0) {
46555
+ rawMessage = options.parsedBody;
46556
+ } else {
46557
+ try {
46558
+ rawMessage = await req.json();
46559
+ } catch {
46560
+ this.onerror?.(new Error("Parse error: Invalid JSON"));
46561
+ return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON");
46562
+ }
46563
+ }
46564
+ let messages;
46565
+ try {
46566
+ if (Array.isArray(rawMessage)) {
46567
+ messages = rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
46568
+ } else {
46569
+ messages = [JSONRPCMessageSchema.parse(rawMessage)];
46570
+ }
46571
+ } catch {
46572
+ this.onerror?.(new Error("Parse error: Invalid JSON-RPC message"));
46573
+ return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON-RPC message");
46574
+ }
46575
+ if (this._closed) {
46576
+ return this.createJsonErrorResponse(404, -32001, "Session not found");
46577
+ }
46578
+ const isInitializationRequest = messages.some(isInitializeRequest);
46579
+ if (isInitializationRequest) {
46580
+ if (this._initialized && this.sessionId !== void 0) {
46581
+ this.onerror?.(new Error("Invalid Request: Server already initialized"));
46582
+ return this.createJsonErrorResponse(400, -32600, "Invalid Request: Server already initialized");
46583
+ }
46584
+ if (messages.length > 1) {
46585
+ this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed"));
46586
+ return this.createJsonErrorResponse(400, -32600, "Invalid Request: Only one initialization request is allowed");
46587
+ }
46588
+ this.sessionId = this.sessionIdGenerator?.();
46589
+ this._initialized = true;
46590
+ if (this.sessionId && this._onsessioninitialized) {
46591
+ await Promise.resolve(this._onsessioninitialized(this.sessionId));
46592
+ }
46593
+ }
46594
+ if (!isInitializationRequest) {
46595
+ const sessionError = this.validateSession(req);
46596
+ if (sessionError) {
46597
+ return sessionError;
46598
+ }
46599
+ const protocolError = this.validateProtocolVersion(req);
46600
+ if (protocolError) {
46601
+ return protocolError;
46602
+ }
46603
+ }
46604
+ if (this._closed) {
46605
+ return this.createJsonErrorResponse(404, -32001, "Session not found");
46606
+ }
46607
+ const hasRequests = messages.some(isJSONRPCRequest);
46608
+ if (!hasRequests) {
46609
+ for (const message of messages) {
46610
+ this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo });
46611
+ }
46612
+ return new Response(null, { status: 202 });
46613
+ }
46614
+ const streamId = crypto.randomUUID();
46615
+ const initRequest = messages.find((m) => isInitializeRequest(m));
46616
+ const clientProtocolVersion = initRequest ? initRequest.params.protocolVersion : req.headers.get("mcp-protocol-version") ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION;
46617
+ if (this._enableJsonResponse) {
46618
+ return new Promise((resolve) => {
46619
+ this._streamMapping.set(streamId, {
46620
+ resolveJson: resolve,
46621
+ cleanup: () => {
46622
+ this._streamMapping.delete(streamId);
46623
+ }
46624
+ });
46625
+ for (const message of messages) {
46626
+ if (isJSONRPCRequest(message)) {
46627
+ this._requestToStreamMapping.set(message.id, streamId);
46628
+ }
46629
+ }
46630
+ for (const message of messages) {
46631
+ this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo });
46632
+ }
46633
+ });
46634
+ }
46635
+ const encoder = new TextEncoder();
46636
+ let streamController;
46637
+ let keepAliveTimer = void 0;
46638
+ const readable = new ReadableStream({
46639
+ start: (controller) => {
46640
+ streamController = controller;
46641
+ },
46642
+ cancel: () => {
46643
+ if (keepAliveTimer !== void 0) {
46644
+ clearInterval(keepAliveTimer);
46645
+ }
46646
+ if (this._streamMapping.get(streamId)?.controller === streamController) {
46647
+ this._streamMapping.delete(streamId);
46648
+ }
46649
+ }
46650
+ });
46651
+ const headers = {
46652
+ "Content-Type": "text/event-stream",
46653
+ "Cache-Control": "no-cache, no-transform",
46654
+ Connection: "keep-alive",
46655
+ "X-Accel-Buffering": "no"
46656
+ };
46657
+ if (this.sessionId !== void 0) {
46658
+ headers["mcp-session-id"] = this.sessionId;
46659
+ }
46660
+ for (const message of messages) {
46661
+ if (isJSONRPCRequest(message)) {
46662
+ this._streamMapping.set(streamId, {
46663
+ controller: streamController,
46664
+ encoder,
46665
+ cleanup: () => {
46666
+ if (keepAliveTimer !== void 0) {
46667
+ clearInterval(keepAliveTimer);
46668
+ }
46669
+ this._streamMapping.delete(streamId);
46670
+ try {
46671
+ streamController.close();
46672
+ } catch {
46673
+ }
46674
+ }
46675
+ });
46676
+ this._requestToStreamMapping.set(message.id, streamId);
46677
+ }
46678
+ }
46679
+ try {
46680
+ await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion);
46681
+ for (const message of messages) {
46682
+ let closeSSEStream;
46683
+ let closeStandaloneSSEStream;
46684
+ if (isJSONRPCRequest(message) && this._eventStore && clientProtocolVersion >= "2025-11-25") {
46685
+ closeSSEStream = () => {
46686
+ this.closeSSEStream(message.id);
46687
+ };
46688
+ closeStandaloneSSEStream = () => {
46689
+ this.closeStandaloneSSEStream();
46690
+ };
46691
+ }
46692
+ this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo, closeSSEStream, closeStandaloneSSEStream });
46693
+ }
46694
+ } catch (error61) {
46695
+ this._streamMapping.get(streamId)?.cleanup();
46696
+ this._resumableStreams.delete(streamId);
46697
+ for (const message of messages) {
46698
+ if (isJSONRPCRequest(message)) {
46699
+ this._requestToStreamMapping.delete(message.id);
46700
+ }
46701
+ }
46702
+ throw error61;
46703
+ }
46704
+ if (this._streamMapping.get(streamId)?.controller === streamController) {
46705
+ keepAliveTimer = this.startKeepAlive(streamController, encoder);
46706
+ }
46707
+ return new Response(readable, { status: 200, headers });
46708
+ } catch (error61) {
46709
+ this.onerror?.(error61);
46710
+ return this.createJsonErrorResponse(400, -32700, "Parse error", { data: String(error61) });
46711
+ }
46712
+ }
46713
+ /**
46714
+ * Handles DELETE requests to terminate sessions
46715
+ */
46716
+ async handleDeleteRequest(req) {
46717
+ const sessionError = this.validateSession(req);
46718
+ if (sessionError) {
46719
+ return sessionError;
46720
+ }
46721
+ const protocolError = this.validateProtocolVersion(req);
46722
+ if (protocolError) {
46723
+ return protocolError;
46724
+ }
46725
+ try {
46726
+ await Promise.resolve(this._onsessionclosed?.(this.sessionId));
46727
+ return new Response(null, { status: 200 });
46728
+ } finally {
46729
+ await this.close();
46730
+ }
46731
+ }
46732
+ /**
46733
+ * Validates session ID for non-initialization requests.
46734
+ * Returns Response error if invalid, undefined otherwise
46735
+ */
46736
+ validateSession(req) {
46737
+ if (this.sessionIdGenerator === void 0) {
46738
+ return void 0;
46739
+ }
46740
+ if (!this._initialized) {
46741
+ this.onerror?.(new Error("Bad Request: Server not initialized"));
46742
+ return this.createJsonErrorResponse(400, -32e3, "Bad Request: Server not initialized");
46743
+ }
46744
+ const sessionId = req.headers.get("mcp-session-id");
46745
+ if (!sessionId) {
46746
+ this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required"));
46747
+ return this.createJsonErrorResponse(400, -32e3, "Bad Request: Mcp-Session-Id header is required");
46748
+ }
46749
+ if (sessionId !== this.sessionId) {
46750
+ this.onerror?.(new Error("Session not found"));
46751
+ return this.createJsonErrorResponse(404, -32001, "Session not found");
46752
+ }
46753
+ return void 0;
46754
+ }
46755
+ /**
46756
+ * Validates the MCP-Protocol-Version header on incoming requests.
46757
+ *
46758
+ * For initialization: Version negotiation handles unknown versions gracefully
46759
+ * (server responds with its supported version).
46760
+ *
46761
+ * For subsequent requests with MCP-Protocol-Version header:
46762
+ * - Accept if in supported list
46763
+ * - 400 if unsupported
46764
+ *
46765
+ * For HTTP requests without the MCP-Protocol-Version header:
46766
+ * - Accept and default to the version negotiated at initialization
46767
+ */
46768
+ validateProtocolVersion(req) {
46769
+ const protocolVersion = req.headers.get("mcp-protocol-version");
46770
+ if (protocolVersion !== null && !SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) {
46771
+ this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")})`));
46772
+ return this.createJsonErrorResponse(400, -32e3, `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")})`);
46773
+ }
46774
+ return void 0;
46775
+ }
46776
+ async close() {
46777
+ if (this._closed) {
46778
+ return;
46779
+ }
46780
+ this._closed = true;
46781
+ this._streamMapping.forEach(({ cleanup }) => {
46782
+ cleanup();
46783
+ });
46784
+ this._streamMapping.clear();
46785
+ this._requestResponseMap.clear();
46786
+ this._resumableStreams.clear();
46787
+ this.onclose?.();
46788
+ }
46789
+ /**
46790
+ * Close an SSE stream for a specific request, triggering client reconnection.
46791
+ * Use this to implement polling behavior during long-running operations -
46792
+ * client will reconnect after the retry interval specified in the priming event.
46793
+ */
46794
+ closeSSEStream(requestId) {
46795
+ const streamId = this._requestToStreamMapping.get(requestId);
46796
+ if (!streamId)
46797
+ return;
46798
+ const stream = this._streamMapping.get(streamId);
46799
+ if (stream) {
46800
+ stream.cleanup();
46801
+ }
46802
+ }
46803
+ /**
46804
+ * Close the standalone GET SSE stream, triggering client reconnection.
46805
+ * Use this to implement polling behavior for server-initiated notifications.
46806
+ */
46807
+ closeStandaloneSSEStream() {
46808
+ const stream = this._streamMapping.get(this._standaloneSseStreamId);
46809
+ if (stream) {
46810
+ stream.cleanup();
46811
+ }
46812
+ }
46813
+ async send(message, options) {
46814
+ let requestId = options?.relatedRequestId;
46815
+ if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
46816
+ requestId = message.id;
46817
+ }
46818
+ if (requestId === void 0) {
46819
+ if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
46820
+ throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");
46821
+ }
46822
+ let eventId;
46823
+ if (this._eventStore) {
46824
+ eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message);
46825
+ }
46826
+ const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId);
46827
+ if (standaloneSse === void 0) {
46828
+ return;
46829
+ }
46830
+ if (standaloneSse.controller && standaloneSse.encoder && (eventId === void 0 || !standaloneSse.replayedEventIds?.has(eventId))) {
46831
+ this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId);
46832
+ }
46833
+ return;
46834
+ }
46835
+ const streamId = this._requestToStreamMapping.get(requestId);
46836
+ if (!streamId) {
46837
+ throw new Error(`No connection established for request ID: ${String(requestId)}`);
46838
+ }
46839
+ let stream = this._streamMapping.get(streamId);
46840
+ if (!this._enableJsonResponse) {
46841
+ let eventId;
46842
+ if (this._eventStore) {
46843
+ eventId = await this._eventStore.storeEvent(streamId, message);
46844
+ stream = this._streamMapping.get(streamId);
46845
+ }
46846
+ if (stream?.controller && stream?.encoder && (eventId === void 0 || !stream.replayedEventIds?.has(eventId))) {
46847
+ const written = this.writeSSEEvent(stream.controller, stream.encoder, message, eventId);
46848
+ if (written && eventId !== void 0) {
46849
+ this._resumableStreams.add(streamId);
46850
+ }
46851
+ }
46852
+ }
46853
+ if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
46854
+ this._requestResponseMap.set(requestId, message);
46855
+ const relatedIds = Array.from(this._requestToStreamMapping.entries()).filter(([_, sid]) => sid === streamId).map(([id]) => id);
46856
+ const allResponsesReady = relatedIds.every((id) => this._requestResponseMap.has(id));
46857
+ if (allResponsesReady) {
46858
+ if (!stream) {
46859
+ if (this._closed) {
46860
+ for (const id of relatedIds) {
46861
+ this._requestResponseMap.delete(id);
46862
+ this._requestToStreamMapping.delete(id);
46863
+ }
46864
+ return;
46865
+ }
46866
+ if (!this._enableJsonResponse && this._eventStore && this._resumableStreams.has(streamId)) {
46867
+ for (const id of relatedIds) {
46868
+ this._requestResponseMap.delete(id);
46869
+ this._requestToStreamMapping.delete(id);
46870
+ }
46871
+ this._resumableStreams.delete(streamId);
46872
+ return;
46873
+ }
46874
+ for (const id of relatedIds) {
46875
+ this._requestResponseMap.delete(id);
46876
+ this._requestToStreamMapping.delete(id);
46877
+ }
46878
+ throw new Error(`No connection established for request ID: ${String(requestId)}`);
46879
+ }
46880
+ if (this._enableJsonResponse && stream.resolveJson) {
46881
+ const headers = {
46882
+ "Content-Type": "application/json"
46883
+ };
46884
+ if (this.sessionId !== void 0) {
46885
+ headers["mcp-session-id"] = this.sessionId;
46886
+ }
46887
+ const responses = relatedIds.map((id) => this._requestResponseMap.get(id));
46888
+ if (responses.length === 1) {
46889
+ stream.resolveJson(new Response(JSON.stringify(responses[0]), { status: 200, headers }));
46890
+ } else {
46891
+ stream.resolveJson(new Response(JSON.stringify(responses), { status: 200, headers }));
46892
+ }
46893
+ } else {
46894
+ stream.cleanup();
46895
+ }
46896
+ for (const id of relatedIds) {
46897
+ this._requestResponseMap.delete(id);
46898
+ this._requestToStreamMapping.delete(id);
46899
+ }
46900
+ this._resumableStreams.delete(streamId);
46901
+ }
46902
+ }
46903
+ }
46904
+ };
46905
+
45767
46906
  // src/db/connection.ts
45768
46907
  var DATABASE_CONNECTION_ENV_VAR = "MAGENTO_REST_DATABASE_CONNECTION";
45769
46908
  var DATABASE_PASSWORD_ENV_VAR = "MAGENTO_REST_DATABASE_PASSWORD";
@@ -45887,8 +47026,8 @@ function tokenize(sql) {
45887
47026
  const tokens = [];
45888
47027
  let depth = 0;
45889
47028
  let i = 0;
45890
- const push = (kind, text3, start) => {
45891
- tokens.push({ kind, text: text3, depth, start });
47029
+ const push = (kind, text4, start) => {
47030
+ tokens.push({ kind, text: text4, depth, start });
45892
47031
  };
45893
47032
  while (i < sql.length) {
45894
47033
  const ch = sql[i];
@@ -45995,8 +47134,8 @@ function singleStatement(sql) {
45995
47134
  if (body.length === 0) {
45996
47135
  throw new SqlGuardError("the statement is empty");
45997
47136
  }
45998
- const text3 = semicolons.length === 1 && last !== void 0 ? sql.slice(0, last.start).trimEnd() : sql.trim();
45999
- return { tokens: body, text: text3 };
47137
+ const text4 = semicolons.length === 1 && last !== void 0 ? sql.slice(0, last.start).trimEnd() : sql.trim();
47138
+ return { tokens: body, text: text4 };
46000
47139
  }
46001
47140
  function checkCommon(tokens) {
46002
47141
  for (const [index, token] of tokens.entries()) {
@@ -46087,7 +47226,7 @@ function checkStars(tokens) {
46087
47226
  }
46088
47227
  }
46089
47228
  function guardReadQuery(sql, maxRows) {
46090
- const { tokens, text: text3 } = singleStatement(sql);
47229
+ const { tokens, text: text4 } = singleStatement(sql);
46091
47230
  const first = tokens[0];
46092
47231
  if (first?.kind !== "word" || first.text !== "SELECT") {
46093
47232
  throw new SqlGuardError("only a SELECT is allowed here");
@@ -46111,7 +47250,7 @@ function guardReadQuery(sql, maxRows) {
46111
47250
  }
46112
47251
  const limitIndex = tokens.findIndex((t) => t.depth === 0 && t.kind === "word" && t.text === "LIMIT");
46113
47252
  if (limitIndex < 0) {
46114
- return { sql: `${text3} LIMIT ${maxRows}` };
47253
+ return { sql: `${text4} LIMIT ${maxRows}` };
46115
47254
  }
46116
47255
  const tail = tokens.slice(limitIndex + 1);
46117
47256
  const isNumber = (t) => t?.kind === "number";
@@ -46126,10 +47265,10 @@ function guardReadQuery(sql, maxRows) {
46126
47265
  if (!(count <= maxRows)) {
46127
47266
  throw new SqlGuardError(`LIMIT ${count} is over the cap of ${maxRows} rows per call; lower it or page with OFFSET`);
46128
47267
  }
46129
- return { sql: text3 };
47268
+ return { sql: text4 };
46130
47269
  }
46131
47270
  function guardWriteStatement(sql) {
46132
- const { tokens, text: text3 } = singleStatement(sql);
47271
+ const { tokens, text: text4 } = singleStatement(sql);
46133
47272
  const first = tokens[0];
46134
47273
  const kind = first?.kind === "word" ? first.text.toLowerCase() : void 0;
46135
47274
  if (kind !== "insert" && kind !== "update" && kind !== "delete") {
@@ -46148,7 +47287,7 @@ function guardWriteStatement(sql) {
46148
47287
  throw new SqlGuardError("INTO is only allowed in an INSERT");
46149
47288
  }
46150
47289
  }
46151
- return { sql: text3, kind };
47290
+ return { sql: text4, kind };
46152
47291
  }
46153
47292
 
46154
47293
  // src/db/rows.ts
@@ -46170,8 +47309,8 @@ function cell(value) {
46170
47309
  return value.toISOString();
46171
47310
  }
46172
47311
  if (typeof value === "string") {
46173
- const text3 = value.length > MAX_CELL_CHARS ? `${value.slice(0, MAX_CELL_CHARS)}\u2026 [truncated, ${value.length} characters]` : value;
46174
- return redact(text3);
47312
+ const text4 = value.length > MAX_CELL_CHARS ? `${value.slice(0, MAX_CELL_CHARS)}\u2026 [truncated, ${value.length} characters]` : value;
47313
+ return redact(text4);
46175
47314
  }
46176
47315
  if (typeof value === "object") {
46177
47316
  return redact(JSON.stringify(value, (_key, v) => typeof v === "bigint" ? v.toString() : v));
@@ -46340,11 +47479,15 @@ function createDatabaseAccess(options) {
46340
47479
  // src/client/errors.ts
46341
47480
  var MAX_MESSAGE_CHARS = 240;
46342
47481
  var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
46343
- var MagentoRestError = class extends Error {
47482
+ var MagentoRestError = class _MagentoRestError extends Error {
46344
47483
  kind;
46345
47484
  status;
46346
47485
  retryable;
46347
47486
  remedy;
47487
+ resources;
47488
+ retryAfterMs;
47489
+ timedOut;
47490
+ answer;
46348
47491
  constructor(init) {
46349
47492
  super(init.message, init.cause !== void 0 ? { cause: init.cause } : void 0);
46350
47493
  this.name = "MagentoRestError";
@@ -46352,6 +47495,25 @@ var MagentoRestError = class extends Error {
46352
47495
  this.status = init.status;
46353
47496
  this.retryable = init.retryable ?? false;
46354
47497
  this.remedy = init.remedy;
47498
+ this.resources = init.resources;
47499
+ this.retryAfterMs = init.retryAfterMs;
47500
+ this.timedOut = init.timedOut;
47501
+ this.answer = init.answer;
47502
+ }
47503
+ /** The same error, carrying where and when Magento gave it. */
47504
+ withAnswer(answer) {
47505
+ return new _MagentoRestError({
47506
+ kind: this.kind,
47507
+ message: this.message,
47508
+ retryable: this.retryable,
47509
+ ...this.status !== void 0 ? { status: this.status } : {},
47510
+ ...this.remedy !== void 0 ? { remedy: this.remedy } : {},
47511
+ ...this.resources !== void 0 ? { resources: this.resources } : {},
47512
+ ...this.retryAfterMs !== void 0 ? { retryAfterMs: this.retryAfterMs } : {},
47513
+ ...this.timedOut !== void 0 ? { timedOut: this.timedOut } : {},
47514
+ ...this.cause !== void 0 ? { cause: this.cause } : {},
47515
+ answer
47516
+ });
46355
47517
  }
46356
47518
  };
46357
47519
  function kindForStatus(status2) {
@@ -46402,7 +47564,7 @@ function extractAclResources(status2, bodyText) {
46402
47564
  }
46403
47565
  return void 0;
46404
47566
  }
46405
- function classifyFailure(status2, bodyText) {
47567
+ function classifyFailure(status2, bodyText, retryAfterMs2) {
46406
47568
  const kind = kindForStatus(status2);
46407
47569
  const template = extractTemplate(bodyText);
46408
47570
  const resources = extractAclResources(status2, bodyText);
@@ -46413,7 +47575,9 @@ function classifyFailure(status2, bodyText) {
46413
47575
  message,
46414
47576
  status: status2,
46415
47577
  retryable: RETRYABLE_STATUSES.has(status2),
46416
- ...remedy !== void 0 ? { remedy } : {}
47578
+ ...remedy !== void 0 ? { remedy } : {},
47579
+ ...resources !== void 0 ? { resources } : {},
47580
+ ...retryAfterMs2 !== void 0 ? { retryAfterMs: retryAfterMs2 } : {}
46417
47581
  });
46418
47582
  }
46419
47583
 
@@ -46501,7 +47665,7 @@ function normalizeBaseUrl(baseUrl) {
46501
47665
  }
46502
47666
  return baseUrl.replace(/\/+$/, "");
46503
47667
  }
46504
- var SCOPED_BASE = /^(.*\/rest)(?:\/[A-Za-z0-9_]+)?\/V1$/;
47668
+ var SCOPED_BASE = /^(.*\/rest)(?:\/([A-Za-z0-9_]+))?\/V1$/;
46505
47669
  var STORE_CODE = /^[A-Za-z][A-Za-z0-9_]{0,31}$/;
46506
47670
  function scopedBase(restRoot, scope) {
46507
47671
  if (!STORE_CODE.test(scope)) {
@@ -46529,7 +47693,9 @@ function retryAfterMs(response) {
46529
47693
  }
46530
47694
  function createRestTransport(deps) {
46531
47695
  const baseUrl = normalizeBaseUrl(deps.baseUrl);
46532
- const restRoot = SCOPED_BASE.exec(baseUrl)?.[1];
47696
+ const scopedMatch = SCOPED_BASE.exec(baseUrl);
47697
+ const restRoot = scopedMatch?.[1];
47698
+ const baseStoreView = scopedMatch?.[2];
46533
47699
  const random = deps.random ?? Math.random;
46534
47700
  const timeoutMs = deps.timeoutMs ?? DEFAULT_REST_TIMEOUT_MS;
46535
47701
  const rateLimiter = new TokenBucketRateLimiter(REST_PACE, { now: deps.now, sleep: deps.sleep });
@@ -46542,7 +47708,7 @@ function createRestTransport(deps) {
46542
47708
  headers["Content-Type"] = "application/json";
46543
47709
  }
46544
47710
  let response;
46545
- let text3;
47711
+ let text4;
46546
47712
  try {
46547
47713
  response = await deps.fetch(`${root}${request.path}${request.query !== void 0 && request.query !== "" ? `?${request.query}` : ""}`, {
46548
47714
  method: request.method,
@@ -46553,7 +47719,7 @@ function createRestTransport(deps) {
46553
47719
  signal: request.signal !== void 0 ? AbortSignal.any([request.signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs),
46554
47720
  ...hasBody ? { body: JSON.stringify(request.body) } : {}
46555
47721
  });
46556
- text3 = await response.text();
47722
+ text4 = await response.text();
46557
47723
  } catch (cause) {
46558
47724
  if (request.signal?.aborted === true) {
46559
47725
  return { failure: cancelled(cause) };
@@ -46564,25 +47730,37 @@ function createRestTransport(deps) {
46564
47730
  kind: "transport",
46565
47731
  message: timedOut ? `Magento REST request timed out after ${Math.round(timeoutMs / 1e3)} s without a response.` : "Magento REST request failed before a response was received.",
46566
47732
  retryable: true,
47733
+ ...timedOut ? { timedOut: true } : {},
46567
47734
  cause
46568
47735
  })
46569
47736
  };
46570
47737
  }
46571
47738
  if (!response.ok) {
46572
47739
  const after = retryAfterMs(response);
46573
- return { failure: classifyFailure(response.status, text3), ...after !== void 0 ? { retryAfterMs: after } : {} };
47740
+ return { failure: classifyFailure(response.status, text4, after), ...after !== void 0 ? { retryAfterMs: after } : {} };
46574
47741
  }
46575
- if (text3 === "") {
47742
+ if (text4 === "") {
46576
47743
  return { value: void 0 };
46577
47744
  }
46578
47745
  try {
46579
- return { value: JSON.parse(text3) };
47746
+ return { value: JSON.parse(text4) };
46580
47747
  } catch {
46581
47748
  return {
46582
47749
  failure: new MagentoRestError({ kind: "unparseable", message: "Magento REST returned a success status with a body that is not JSON.", status: response.status })
46583
47750
  };
46584
47751
  }
46585
47752
  }
47753
+ function answerFor(request, root) {
47754
+ const pathname = new URL(`${root}${request.path}`).pathname;
47755
+ const fromRest = pathname.indexOf("/rest/");
47756
+ const scope = request.scope ?? baseStoreView;
47757
+ const storeView = scope === "all" ? void 0 : scope;
47758
+ return {
47759
+ endpoint: `${request.method} ${fromRest >= 0 ? pathname.slice(fromRest) : pathname}`,
47760
+ readAt: new Date(deps.now()).toISOString(),
47761
+ ...storeView !== void 0 ? { storeView } : {}
47762
+ };
47763
+ }
46586
47764
  return {
46587
47765
  async request(request) {
46588
47766
  assertPath(request.path);
@@ -46594,6 +47772,7 @@ function createRestTransport(deps) {
46594
47772
  }
46595
47773
  const outcome = await attemptOnce(request, root);
46596
47774
  if ("value" in outcome) {
47775
+ request.onAnswered?.(answerFor(request, root));
46597
47776
  return outcome.value;
46598
47777
  }
46599
47778
  const decision = decideRetry(
@@ -46602,7 +47781,7 @@ function createRestTransport(deps) {
46602
47781
  random
46603
47782
  );
46604
47783
  if (!decision.retry) {
46605
- throw outcome.failure;
47784
+ throw outcome.failure.status !== void 0 ? outcome.failure.withAnswer(answerFor(request, root)) : outcome.failure;
46606
47785
  }
46607
47786
  await deps.sleep(decision.delayMs);
46608
47787
  }
@@ -46679,14 +47858,14 @@ function buildSearchCriteria(input2) {
46679
47858
 
46680
47859
  // src/client/paths.ts
46681
47860
  function encodeSegment(value) {
46682
- const text3 = String(value);
46683
- if (text3 === "") {
47861
+ const text4 = String(value);
47862
+ if (text4 === "") {
46684
47863
  throw new Error("restPath: an empty path segment is not allowed");
46685
47864
  }
46686
- if (/^\.+$/.test(text3)) {
46687
- return text3.replaceAll(".", "%2E");
47865
+ if (/^\.+$/.test(text4)) {
47866
+ return text4.replaceAll(".", "%2E");
46688
47867
  }
46689
- return encodeURIComponent(text3);
47868
+ return encodeURIComponent(text4);
46690
47869
  }
46691
47870
  function restPath(strings, ...values) {
46692
47871
  let out = strings[0] ?? "";
@@ -46734,15 +47913,15 @@ var NAMES = {
46734
47913
  };
46735
47914
  var MAX_INPUT_LENGTH = 64;
46736
47915
  function normalizeCountry(input2) {
46737
- const text3 = input2.trim().toLowerCase();
46738
- if (text3.length === 0 || text3.length > MAX_INPUT_LENGTH) {
47916
+ const text4 = input2.trim().toLowerCase();
47917
+ if (text4.length === 0 || text4.length > MAX_INPUT_LENGTH) {
46739
47918
  return void 0;
46740
47919
  }
46741
- const named = NAMES[text3];
46742
- if (named !== void 0 && Object.hasOwn(NAMES, text3)) {
47920
+ const named = NAMES[text4];
47921
+ if (named !== void 0 && Object.hasOwn(NAMES, text4)) {
46743
47922
  return named;
46744
47923
  }
46745
- return /^[a-z]{2}$/.test(text3) ? text3.toUpperCase() : void 0;
47924
+ return /^[a-z]{2}$/.test(text4) ? text4.toUpperCase() : void 0;
46746
47925
  }
46747
47926
 
46748
47927
  // src/client/date-range.ts
@@ -46760,8 +47939,8 @@ function formatMagentoTimestamp(date5) {
46760
47939
  function formatDay(date5) {
46761
47940
  return date5.toISOString().slice(0, 10);
46762
47941
  }
46763
- function parseDay(text3) {
46764
- const match = DAY_PATTERN.exec(text3);
47942
+ function parseDay(text4) {
47943
+ const match = DAY_PATTERN.exec(text4);
46765
47944
  if (match === null) {
46766
47945
  return void 0;
46767
47946
  }
@@ -46850,8 +48029,8 @@ function readSearchBody(body) {
46850
48029
  function createMagentoRestClient(deps) {
46851
48030
  return clientView(createRestTransport(deps), {});
46852
48031
  }
46853
- function clientView(transport2, options) {
46854
- const send = (request) => transport2.request({ ...request, ...options });
48032
+ function clientView(transport, options) {
48033
+ const send = (request) => transport.request({ ...request, ...options });
46855
48034
  async function search(path, criteria) {
46856
48035
  return readSearchBody(await send({ method: "GET", path, query: buildSearchCriteria(criteria) }));
46857
48036
  }
@@ -46879,7 +48058,7 @@ function clientView(transport2, options) {
46879
48058
  }
46880
48059
  return { items, totalCount, truncated: true };
46881
48060
  },
46882
- with: (more) => clientView(transport2, { ...options, ...more })
48061
+ with: (more) => clientView(transport, { ...options, ...more })
46883
48062
  };
46884
48063
  }
46885
48064
 
@@ -46906,7 +48085,7 @@ function num(value) {
46906
48085
  return Number.isFinite(n) ? n : 0;
46907
48086
  }
46908
48087
  var round2 = (value) => Number(value.toFixed(2));
46909
- function list(value) {
48088
+ function list2(value) {
46910
48089
  return Array.isArray(value) ? value : [];
46911
48090
  }
46912
48091
  function money(order, baseKey, plainKey) {
@@ -46970,7 +48149,7 @@ function coverage(fetched) {
46970
48149
  }
46971
48150
  function inCountry(order, code) {
46972
48151
  const billing = text(field(field(order, "billing_address"), "country_id"));
46973
- const assignment = list(field(field(order, "extension_attributes"), "shipping_assignments"))[0];
48152
+ const assignment = list2(field(field(order, "extension_attributes"), "shipping_assignments"))[0];
46974
48153
  const shipping = text(field(field(field(assignment, "shipping"), "address"), "country_id"));
46975
48154
  return [billing, shipping].some((candidate) => candidate?.toUpperCase() === code);
46976
48155
  }
@@ -47093,7 +48272,7 @@ function analyticsTools({ readTool }) {
47093
48272
  const products = /* @__PURE__ */ new Map();
47094
48273
  for (const order of orders) {
47095
48274
  revenue += money(order, "base_grand_total", "grand_total");
47096
- for (const item of list(field(order, "items"))) {
48275
+ for (const item of list2(field(order, "items"))) {
47097
48276
  const sku2 = text(field(item, "sku"));
47098
48277
  const qty = num(field(item, "qty_ordered"));
47099
48278
  itemCount += 1;
@@ -47153,7 +48332,7 @@ function analyticsTools({ readTool }) {
47153
48332
  }),
47154
48333
  readTool({
47155
48334
  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.",
48335
+ 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
48336
  input: external_exports.object({ email: external_exports.email().max(254).describe("The customer's email address (exact)."), max_pages: maxPages }).strict(),
47158
48337
  shape: [
47159
48338
  ["customer", ["id", "email", "firstname", "lastname"]],
@@ -47177,7 +48356,7 @@ function analyticsTools({ readTool }) {
47177
48356
  created_at: field(order, "created_at"),
47178
48357
  status: field(order, "status"),
47179
48358
  total: field(order, "grand_total"),
47180
- items: list(field(order, "items"))
48359
+ items: list2(field(order, "items"))
47181
48360
  })),
47182
48361
  coverage: { orders_returned: analysed, orders_total: fetched.totalCount, truncated: fetched.truncated },
47183
48362
  ...fetched.truncated ? { warning: `Partial result: only ${analysed} of ${fetched.totalCount} orders were returned. Raise max_pages (up to 50) to see more.` } : {}
@@ -47579,7 +48758,7 @@ function cartTools({ readTool, shapes }) {
47579
48758
  return [
47580
48759
  readTool({
47581
48760
  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.",
48761
+ 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
48762
  input: external_exports.object({ cart_id: cartId }).strict(),
47584
48763
  shape: shapes.cart,
47585
48764
  run: ({ cart_id }, client) => client.get(restPath`/carts/${cart_id}`)
@@ -47624,7 +48803,7 @@ function cartTools({ readTool, shapes }) {
47624
48803
  }),
47625
48804
  readTool({
47626
48805
  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.",
48806
+ 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
48807
  input: external_exports.object({
47629
48808
  days_old: external_exports.number().int().min(0).max(3650).optional().describe("Minimum days since the cart was last updated (default 7)."),
47630
48809
  page_size: pageSize,
@@ -47968,7 +49147,7 @@ function customerTools({ readTool, writeTool, shapes }) {
47968
49147
  return [
47969
49148
  readTool({
47970
49149
  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.",
49150
+ 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
49151
  input: external_exports.object({ customer_id: entityId("customer") }).strict(),
47973
49152
  shape: shapes.customer,
47974
49153
  run: ({ customer_id }, client) => client.get(restPath`/customers/${customer_id}`)
@@ -48017,7 +49196,7 @@ function customerTools({ readTool, writeTool, shapes }) {
48017
49196
  }),
48018
49197
  readTool({
48019
49198
  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.",
49199
+ 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
49200
  input: external_exports.object({ customer_id: entityId("customer") }).strict(),
48022
49201
  shape: shapes.customer_address,
48023
49202
  run: async ({ customer_id }, client) => {
@@ -48089,6 +49268,91 @@ function customerTools({ readTool, writeTool, shapes }) {
48089
49268
  ];
48090
49269
  }
48091
49270
 
49271
+ // src/tools/customer-data.ts
49272
+ var PERSONAL_FIELDS = /* @__PURE__ */ new Set([
49273
+ "email",
49274
+ "firstname",
49275
+ "middlename",
49276
+ "lastname",
49277
+ "prefix",
49278
+ "suffix",
49279
+ "telephone",
49280
+ "fax",
49281
+ "street",
49282
+ "company",
49283
+ "dob",
49284
+ "taxvat",
49285
+ "gender",
49286
+ "remote_ip",
49287
+ "x_forwarded_for",
49288
+ // A cart's embedded customer record.
49289
+ "customer",
49290
+ // An order's copy of the customer's identity. `customer_is_guest` stays: it says nothing about who.
49291
+ "customer_id",
49292
+ "customer_email",
49293
+ "customer_firstname",
49294
+ "customer_middlename",
49295
+ "customer_lastname",
49296
+ "customer_prefix",
49297
+ "customer_suffix",
49298
+ "customer_name",
49299
+ "customer_dob",
49300
+ "customer_taxvat",
49301
+ "customer_gender",
49302
+ "customer_note"
49303
+ ]);
49304
+ var CUSTOMER_ADDRESS_FIELDS = /* @__PURE__ */ new Set(["city", "postcode"]);
49305
+ function without(shape, fields) {
49306
+ const kept = [];
49307
+ for (const entry of shape) {
49308
+ if (typeof entry === "string") {
49309
+ if (!fields.has(entry)) kept.push(entry);
49310
+ } else if (!fields.has(entry[0])) {
49311
+ kept.push([entry[0], without(entry[1], fields)]);
49312
+ }
49313
+ }
49314
+ return kept;
49315
+ }
49316
+ function withoutCustomerData(shape) {
49317
+ return without(shape, PERSONAL_FIELDS);
49318
+ }
49319
+ function withoutCustomerDataShapes(shapes) {
49320
+ const stripped = Object.fromEntries(Object.entries(shapes).map(([resource, shape]) => [resource, withoutCustomerData(shape)]));
49321
+ return { ...stripped, customer_address: without(stripped.customer_address, CUSTOMER_ADDRESS_FIELDS) };
49322
+ }
49323
+
49324
+ // src/tools/output-schema.ts
49325
+ var primitive = external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null()]);
49326
+ function objectFor(shape) {
49327
+ const fields = {};
49328
+ for (const entry of shape) {
49329
+ if (typeof entry === "string") {
49330
+ fields[entry] = external_exports.unknown().optional();
49331
+ } else {
49332
+ fields[entry[0]] = valueFor(entry[1]).optional();
49333
+ }
49334
+ }
49335
+ return external_exports.object(fields);
49336
+ }
49337
+ function valueFor(shape) {
49338
+ const element = external_exports.union([objectFor(shape), primitive]);
49339
+ return external_exports.union([element, external_exports.array(element)]);
49340
+ }
49341
+ var provenanceSchema = external_exports.object({
49342
+ /** The first request: method and path from `/rest` on, with no host, query string or token. */
49343
+ endpoint: external_exports.string(),
49344
+ /** Each distinct endpoint, in the order first used, when the tool used more than one (a paged walk counts once). */
49345
+ endpoints: external_exports.array(external_exports.string()).optional(),
49346
+ api_version: external_exports.literal("V1"),
49347
+ /** ISO 8601 UTC, when Magento answered the last request. */
49348
+ read_at: external_exports.string(),
49349
+ /** The store view the requests addressed, when the URL named one. */
49350
+ store_view: external_exports.string().optional()
49351
+ });
49352
+ function readOutputSchema(shape) {
49353
+ return external_exports.object({ result: valueFor(shape), provenance: provenanceSchema });
49354
+ }
49355
+
48092
49356
  // src/tools/project.ts
48093
49357
  function isPrimitive(value) {
48094
49358
  return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
@@ -48233,30 +49497,75 @@ var WRITE_ANNOTATIONS = {
48233
49497
  delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
48234
49498
  action: { readOnlyHint: false, destructiveHint: true, idempotentHint: false }
48235
49499
  };
49500
+ function provenanceOf(answers) {
49501
+ const first = answers[0];
49502
+ const last = answers.at(-1);
49503
+ if (first === void 0 || last === void 0) {
49504
+ throw new Error("The read produced no Magento answer to cite, so its result cannot carry provenance.");
49505
+ }
49506
+ const endpoints = [...new Set(answers.map((answer) => answer.endpoint))];
49507
+ return {
49508
+ endpoint: first.endpoint,
49509
+ ...endpoints.length > 1 ? { endpoints } : {},
49510
+ api_version: "V1",
49511
+ read_at: last.readAt,
49512
+ ...first.storeView !== void 0 ? { store_view: first.storeView } : {}
49513
+ };
49514
+ }
48236
49515
  function createToolFactory(getClient, options = {}) {
48237
49516
  const liveVerified = options.liveVerified ?? LIVE_VERIFIED_TOOLS;
48238
49517
  const shapes = options.shapes ?? BASE_SHAPES;
48239
- function build(spec, annotations, access) {
49518
+ function build(given, annotations, access) {
49519
+ const spec = options.withoutCustomerData === true ? { ...given, shape: withoutCustomerData(given.shape) } : given;
49520
+ const structured = access === "read";
48240
49521
  const description = liveVerified.has(spec.name) ? spec.description : `${spec.description} ${UNVERIFIED_MARKER} \u2014 ${UNVERIFIED_DETAIL}`;
48241
49522
  const tool = defineTool({
48242
49523
  name: spec.name,
48243
49524
  description,
48244
49525
  inputSchema: spec.input,
49526
+ ...structured ? { outputSchema: readOutputSchema(spec.shape) } : {},
48245
49527
  annotations,
48246
49528
  handler: async (args, ctx) => {
48247
49529
  const client = getClient();
48248
- const raw = await spec.run(args, ctx.signal !== void 0 ? client.with({ signal: ctx.signal }) : client);
49530
+ const answers = [];
49531
+ const requestOptions = { ...ctx.signal !== void 0 ? { signal: ctx.signal } : {}, ...structured ? { onAnswered: (answer) => answers.push(answer) } : {} };
49532
+ const raw = await spec.run(args, Object.keys(requestOptions).length > 0 ? client.with(requestOptions) : client);
48249
49533
  const projected = project(raw, spec.shape);
49534
+ let result;
48250
49535
  if (hasContent(raw) && isEmptyShell(projected)) {
48251
- return NOTHING_REPORTED_NOTICE;
49536
+ result = NOTHING_REPORTED_NOTICE;
49537
+ } else {
49538
+ result = projected === void 0 ? null : projected;
48252
49539
  }
48253
- return projected === void 0 ? null : projected;
49540
+ return structured ? { result, provenance: provenanceOf(answers) } : result;
49541
+ }
49542
+ });
49543
+ return { ...tool, access };
49544
+ }
49545
+ function buildShaped(spec) {
49546
+ const description = liveVerified.has(spec.name) ? spec.description : `${spec.description} ${UNVERIFIED_MARKER} \u2014 ${UNVERIFIED_DETAIL}`;
49547
+ const access = spec.effect === void 0 ? "read" : "write";
49548
+ const tool = defineTool({
49549
+ name: spec.name,
49550
+ description,
49551
+ inputSchema: spec.input,
49552
+ outputSchema: spec.output,
49553
+ annotations: spec.effect === void 0 ? READ_ONLY_ANNOTATIONS : WRITE_ANNOTATIONS[spec.effect],
49554
+ handler: async (args, ctx) => {
49555
+ const base = getClient();
49556
+ const bound = ctx.signal !== void 0 ? base.with({ signal: ctx.signal }) : base;
49557
+ const track = () => {
49558
+ const answers = [];
49559
+ return { client: bound.with({ onAnswered: (answer) => answers.push(answer) }), answers };
49560
+ };
49561
+ return spec.run(args, track);
48254
49562
  }
48255
49563
  });
48256
49564
  return { ...tool, access };
48257
49565
  }
48258
49566
  return {
48259
49567
  shapes,
49568
+ shapedTool: (spec) => buildShaped(spec),
48260
49569
  readTool: (spec) => build(spec, READ_ONLY_ANNOTATIONS, "read"),
48261
49570
  writeTool: (spec) => build(spec, WRITE_ANNOTATIONS[spec.effect], "write")
48262
49571
  };
@@ -48484,10 +49793,10 @@ function readPaths(resource, key, value, validate2) {
48484
49793
  }
48485
49794
  return paths;
48486
49795
  }
48487
- function parseFieldConfig(text3) {
49796
+ function parseFieldConfig(text4) {
48488
49797
  let parsed;
48489
49798
  try {
48490
- parsed = JSON.parse(text3);
49799
+ parsed = JSON.parse(text4);
48491
49800
  } catch (cause) {
48492
49801
  throw new FieldConfigError(`field configuration is not valid JSON: ${cause instanceof Error ? cause.message : "parse failure"}`);
48493
49802
  }
@@ -48592,6 +49901,216 @@ function applyFieldConfig(base, config2) {
48592
49901
  return changed2;
48593
49902
  }
48594
49903
 
49904
+ // src/tools/tool-error.ts
49905
+ var DEFAULT_RETRY_AFTER_MS = 4e3;
49906
+ var ToolArgumentError = class extends Error {
49907
+ code;
49908
+ argument;
49909
+ constructor(code, argument, message) {
49910
+ super(message);
49911
+ this.name = "ToolArgumentError";
49912
+ this.code = code;
49913
+ this.argument = argument;
49914
+ }
49915
+ };
49916
+ function forMagento(error61) {
49917
+ const status2 = error61.status !== void 0 ? { http_status: error61.status } : {};
49918
+ switch (error61.kind) {
49919
+ case "unauthorized":
49920
+ case "forbidden":
49921
+ if (error61.resources !== void 0) return { code: "permission_missing", resource: error61.resources, ...status2 };
49922
+ return error61.kind === "unauthorized" ? { code: "unauthorized", ...status2 } : { code: "upstream_error", ...status2 };
49923
+ case "rate-limited":
49924
+ return { code: "rate_limited", retry_after_ms: error61.retryAfterMs ?? DEFAULT_RETRY_AFTER_MS, ...status2 };
49925
+ case "transport":
49926
+ return error61.timedOut === true ? { code: "timeout" } : { code: "unavailable" };
49927
+ case "server":
49928
+ return { code: "unavailable", ...status2 };
49929
+ default:
49930
+ return { code: "upstream_error", ...status2 };
49931
+ }
49932
+ }
49933
+ function bodyWithoutMessage(error61) {
49934
+ if (error61 instanceof ToolArgumentError) return { code: error61.code, argument: error61.argument };
49935
+ if (error61 instanceof MagentoRestError) return forMagento(error61);
49936
+ if (error61 instanceof ZodError) {
49937
+ const first = error61.issues[0];
49938
+ return { code: "invalid_argument", argument: first !== void 0 && first.path.length > 0 ? first.path.map(String).join(".") : "arguments" };
49939
+ }
49940
+ if (error61 instanceof SqlGuardError) return { code: "invalid_argument", argument: "sql" };
49941
+ if (error61 instanceof DatabaseConfigError) return { code: "unavailable" };
49942
+ return { code: "upstream_error" };
49943
+ }
49944
+ function errorBodyFor(error61, message) {
49945
+ const text4 = message ?? (error61 instanceof Error ? redact(error61.message) : void 0);
49946
+ return { ...bodyWithoutMessage(error61), ...text4 !== void 0 ? { message: text4 } : {} };
49947
+ }
49948
+ var SIZE_ARGUMENTS = ["page_size", "max_pages", "max_rows"];
49949
+ function invokeErrorBody(result, tool) {
49950
+ const message = result.content[0]?.text;
49951
+ const withMessage = message !== void 0 ? { message } : {};
49952
+ if (result.errorKind === "too_large") {
49953
+ const argument = SIZE_ARGUMENTS.find((name2) => Object.hasOwn(tool.inputSchema.shape, name2)) ?? "arguments";
49954
+ return { code: "invalid_argument", argument, ...withMessage };
49955
+ }
49956
+ if (result.errorKind === "credential") return { code: "unauthorized", ...withMessage };
49957
+ return { code: "upstream_error", ...withMessage };
49958
+ }
49959
+
49960
+ // src/tools/product-content-tools.ts
49961
+ var PRODUCT_CONTENT_READ_TOOL = "magentorest_get_product_content";
49962
+ var PRODUCT_CONTENT_WRITE_TOOL = "magentorest_update_product_content";
49963
+ var CONTENT_FIELDS = ["name", "description", "short_description", "meta_title", "meta_description"];
49964
+ var MAX_CHARS = { name: 255, meta_title: 255, meta_description: 255 };
49965
+ var MAX_TEXT_BYTES = 65535;
49966
+ var MAX_LABEL_CHARS = 255;
49967
+ var STORE_VIEW = /^[A-Za-z][A-Za-z0-9_]{0,31}$/;
49968
+ var GLOBAL_SCOPES = /* @__PURE__ */ new Set(["all", "admin"]);
49969
+ var UNKNOWN_ROUTE = "Request does not match any route";
49970
+ var contentSchema = external_exports.object(Object.fromEntries(CONTENT_FIELDS.map((field2) => [field2, external_exports.string().nullable()])));
49971
+ var imageSchema = external_exports.object({ id: external_exports.string(), file: external_exports.string().nullable(), label: external_exports.string().nullable() });
49972
+ var productContentSchema = external_exports.object({
49973
+ found: external_exports.boolean(),
49974
+ sku: external_exports.string(),
49975
+ store_view: external_exports.string(),
49976
+ content: contentSchema.optional(),
49977
+ images: external_exports.array(imageSchema).optional(),
49978
+ provenance: provenanceSchema
49979
+ });
49980
+ var isRecord3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
49981
+ var text3 = (value) => typeof value === "string" && value !== "" ? value : null;
49982
+ function parseProduct(body) {
49983
+ const record2 = isRecord3(body) ? body : {};
49984
+ const custom2 = /* @__PURE__ */ new Map();
49985
+ for (const attribute of Array.isArray(record2["custom_attributes"]) ? record2["custom_attributes"] : []) {
49986
+ if (isRecord3(attribute) && typeof attribute["attribute_code"] === "string") custom2.set(attribute["attribute_code"], attribute["value"]);
49987
+ }
49988
+ const content2 = Object.fromEntries(CONTENT_FIELDS.map((field2) => [field2, text3(field2 === "name" ? record2["name"] : custom2.get(field2))]));
49989
+ const media = [];
49990
+ for (const entry of Array.isArray(record2["media_gallery_entries"]) ? record2["media_gallery_entries"] : []) {
49991
+ if (isRecord3(entry) && typeof entry["id"] === "number") media.push({ id: entry["id"], label: text3(entry["label"]), file: text3(entry["file"]), raw: entry });
49992
+ }
49993
+ return { content: content2, media };
49994
+ }
49995
+ function shaped(skuValue, storeView, product, provenance) {
49996
+ return {
49997
+ found: true,
49998
+ sku: skuValue,
49999
+ store_view: storeView,
50000
+ content: product.content,
50001
+ images: product.media.map((entry) => ({ id: String(entry.id), file: entry.file, label: entry.label })),
50002
+ provenance
50003
+ };
50004
+ }
50005
+ function checkedStoreView(value, forWrite) {
50006
+ if (value === void 0 || value === "") {
50007
+ throw new ToolArgumentError("invalid_argument", "store_view", "store_view is required: the code of the store view to read or write (for example default).");
50008
+ }
50009
+ if (!STORE_VIEW.test(value)) {
50010
+ throw new ToolArgumentError("invalid_argument", "store_view", "store_view must be a store view code: letters, digits and underscores.");
50011
+ }
50012
+ if (forWrite && GLOBAL_SCOPES.has(value.toLowerCase())) {
50013
+ throw new ToolArgumentError("invalid_argument", "store_view", "Content is written to one store view only: all and admin are the global scope, which would change every language and market.");
50014
+ }
50015
+ return value;
50016
+ }
50017
+ var isUnknownStoreView = (error61) => error61 instanceof MagentoRestError && error61.kind === "not-found" && error61.message.includes(UNKNOWN_ROUTE);
50018
+ var isMissingProduct = (error61) => error61 instanceof MagentoRestError && error61.kind === "not-found" && !error61.message.includes(UNKNOWN_ROUTE);
50019
+ async function readProduct(client, skuValue) {
50020
+ try {
50021
+ return parseProduct(await client.get(restPath`/products/${skuValue}`));
50022
+ } catch (error61) {
50023
+ if (isUnknownStoreView(error61)) throw new ToolArgumentError("invalid_argument", "store_view", "Magento has no store view with that code.");
50024
+ throw error61;
50025
+ }
50026
+ }
50027
+ var storeViewInput = external_exports.string().optional().describe("The store view code (for example default). Required; checked by the tool.");
50028
+ var contentInput = external_exports.object(Object.fromEntries(CONTENT_FIELDS.map((field2) => [field2, external_exports.string().optional()]))).strict().optional().describe("The content fields to set, each optional: name, description, short_description, meta_title, meta_description.");
50029
+ var imagesInput = external_exports.array(external_exports.object({ id: external_exports.string().describe('The media entry id, as a string (for example "12").'), label: external_exports.string().describe("The new label (alt text).") }).strict()).max(100).optional().describe("Image labels to set, by media entry id.");
50030
+ function checkedChange(content2, images) {
50031
+ for (const field2 of CONTENT_FIELDS) {
50032
+ const value = content2?.[field2];
50033
+ if (value === void 0) continue;
50034
+ const argument = `content.${field2}`;
50035
+ if (value === "") throw new ToolArgumentError("invalid_argument", argument, `${field2} cannot be empty: clearing a value is not supported.`);
50036
+ const maxChars = MAX_CHARS[field2];
50037
+ if (maxChars !== void 0 && [...value].length > maxChars) throw new ToolArgumentError("invalid_argument", argument, `${field2} is at most ${maxChars} characters.`);
50038
+ if (maxChars === void 0 && Buffer.byteLength(value, "utf8") > MAX_TEXT_BYTES) throw new ToolArgumentError("invalid_argument", argument, `${field2} is at most ${MAX_TEXT_BYTES} bytes.`);
50039
+ }
50040
+ const seen = /* @__PURE__ */ new Set();
50041
+ const checkedImages = (images ?? []).map((image, index) => {
50042
+ if (!/^[1-9][0-9]{0,9}$/.test(image.id)) throw new ToolArgumentError("invalid_argument", `images[${index}].id`, 'An image id is the media entry id as a decimal string, for example "12".');
50043
+ if (seen.has(image.id)) throw new ToolArgumentError("invalid_argument", `images[${index}].id`, "Each image id may appear once.");
50044
+ seen.add(image.id);
50045
+ if (image.label === "") throw new ToolArgumentError("invalid_argument", `images[${index}].label`, "A label cannot be empty: Magento stores an empty label as no label.");
50046
+ if ([...image.label].length > MAX_LABEL_CHARS) throw new ToolArgumentError("invalid_argument", `images[${index}].label`, `A label is at most ${MAX_LABEL_CHARS} characters.`);
50047
+ return { id: Number(image.id), label: image.label };
50048
+ });
50049
+ return { content: content2 ?? {}, images: checkedImages };
50050
+ }
50051
+ function productContentTools({ shapedTool }) {
50052
+ return [
50053
+ shapedTool({
50054
+ name: PRODUCT_CONTENT_READ_TOOL,
50055
+ description: "Use this to read a product's content as one store view shows it: name, description, short description, meta title and meta description, and each image's id, file and label. Each value is the store view's own or the one it inherits, null when there is none. An unknown SKU returns found: false.",
50056
+ input: external_exports.object({ sku, store_view: storeViewInput }).strict(),
50057
+ output: productContentSchema,
50058
+ run: async ({ sku: skuValue, store_view }, track) => {
50059
+ const storeView = checkedStoreView(store_view, false);
50060
+ const read = track();
50061
+ try {
50062
+ const product = await readProduct(read.client.with({ scope: storeView }), skuValue);
50063
+ return shaped(skuValue, storeView, product, provenanceOf(read.answers));
50064
+ } catch (error61) {
50065
+ if (isMissingProduct(error61) && error61 instanceof MagentoRestError && error61.answer !== void 0) {
50066
+ return { found: false, sku: skuValue, store_view: storeView, provenance: provenanceOf([error61.answer]) };
50067
+ }
50068
+ throw error61;
50069
+ }
50070
+ }
50071
+ }),
50072
+ shapedTool({
50073
+ name: PRODUCT_CONTENT_WRITE_TOOL,
50074
+ description: "Use this to change a product's content in ONE store view: any of name, description, short description, meta title and meta description, and image labels by id. Only the values that differ from the current ones are sent; the result is the content read back. A store view is required (all and admin are refused). Requires Magento 2.4.7 or later. Side effect: Magento then writes a store-view value for every image of the product, so those images stop inheriting later changes made to the default values in this store view.",
50075
+ effect: "update",
50076
+ input: external_exports.object({ sku, store_view: storeViewInput, content: contentInput, images: imagesInput }).strict(),
50077
+ output: productContentSchema,
50078
+ run: async ({ sku: skuValue, store_view, content: content2, images }, track) => {
50079
+ const storeView = checkedStoreView(store_view, true);
50080
+ const change = checkedChange(content2, images);
50081
+ const before = track();
50082
+ let current;
50083
+ try {
50084
+ current = await readProduct(before.client.with({ scope: storeView }), skuValue);
50085
+ } catch (error61) {
50086
+ if (isMissingProduct(error61)) throw new ToolArgumentError("not_found", "sku", "No product with that SKU: nothing was written.");
50087
+ throw error61;
50088
+ }
50089
+ const entries = change.images.map((image, index) => {
50090
+ const found = current.media.find((entry) => entry.id === image.id);
50091
+ if (found === void 0) throw new ToolArgumentError("not_found", `images[${index}].id`, "The product has no image with that id: nothing was written.");
50092
+ return { entry: found, label: image.label };
50093
+ });
50094
+ const scoped = before.client.with({ scope: storeView });
50095
+ const changedFields = CONTENT_FIELDS.filter((field2) => change.content[field2] !== void 0 && change.content[field2] !== current.content[field2]);
50096
+ if (changedFields.length > 0) {
50097
+ const custom2 = changedFields.filter((field2) => field2 !== "name").map((field2) => ({ attribute_code: field2, value: change.content[field2] }));
50098
+ await scoped.put(restPath`/products/${skuValue}`, {
50099
+ product: { sku: skuValue, ...changedFields.includes("name") ? { name: change.content.name } : {}, ...custom2.length > 0 ? { custom_attributes: custom2 } : {} }
50100
+ });
50101
+ }
50102
+ for (const { entry, label: label2 } of entries) {
50103
+ if (label2 === entry.label) continue;
50104
+ await scoped.put(restPath`/products/${skuValue}/media/${entry.id}`, { entry: { ...entry.raw, label: label2 } });
50105
+ }
50106
+ const after = track();
50107
+ const product = await readProduct(after.client.with({ scope: storeView }), skuValue);
50108
+ return shaped(skuValue, storeView, product, provenanceOf(after.answers));
50109
+ }
50110
+ })
50111
+ ];
50112
+ }
50113
+
48595
50114
  // src/tools/products-tools.ts
48596
50115
  var IDENTITY_ATTRIBUTES = /* @__PURE__ */ new Set(["sku", "id", "entity_id", "type_id"]);
48597
50116
  var primitiveValue = external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()]);
@@ -48961,11 +50480,11 @@ var LIST_PAGE_SIZE7 = 20;
48961
50480
  var statusCode = (what) => external_exports.string().regex(/^[a-z0-9_]{1,32}$/, "lowercase letters, digits and underscores only").describe(what);
48962
50481
  var incrementId = external_exports.string().regex(/^[A-Za-z0-9-]{1,32}$/, "letters, digits and hyphens only (max 32)").describe("The increment ID (order number) shown to the customer.");
48963
50482
  var orderId = entityId("order (entity ID, not the order number)");
48964
- function isRecord3(value) {
50483
+ function isRecord4(value) {
48965
50484
  return value !== null && typeof value === "object" && !Array.isArray(value);
48966
50485
  }
48967
50486
  function arrayField(record2, key) {
48968
- if (isRecord3(record2)) {
50487
+ if (isRecord4(record2)) {
48969
50488
  const value = record2[key];
48970
50489
  return Array.isArray(value) ? value : [];
48971
50490
  }
@@ -48975,7 +50494,7 @@ function orderTools({ readTool, writeTool, shapes }) {
48975
50494
  return [
48976
50495
  readTool({
48977
50496
  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.",
50497
+ 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
50498
  input: external_exports.object({ order_id: orderId }).strict(),
48980
50499
  shape: shapes.order,
48981
50500
  run: ({ order_id }, client) => client.get(restPath`/orders/${order_id}`)
@@ -49390,7 +50909,7 @@ function taxTools({ readTool, shapes }) {
49390
50909
 
49391
50910
  // src/tools/index.ts
49392
50911
  var GROUPS = {
49393
- products: productTools,
50912
+ products: (factory) => [...productTools(factory), ...productContentTools(factory)],
49394
50913
  store: storeTools,
49395
50914
  categories: categoryTools,
49396
50915
  customers: customerTools,
@@ -49421,20 +50940,20 @@ function parseGroups(value) {
49421
50940
  assertKnownGroups(names);
49422
50941
  return names;
49423
50942
  }
49424
- function assertUniqueNames(tools) {
50943
+ function assertUniqueNames(tools2) {
49425
50944
  const seen = /* @__PURE__ */ new Set();
49426
- for (const tool of tools) {
50945
+ for (const tool of tools2) {
49427
50946
  if (seen.has(tool.name)) {
49428
50947
  throw new Error(`Duplicate tool name registered: ${tool.name}`);
49429
50948
  }
49430
50949
  seen.add(tool.name);
49431
50950
  }
49432
50951
  }
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;
50952
+ function assemble(getRuntime2, shapes, groups2 = REST_GROUP_NAMES, customerData2 = true) {
50953
+ const factory = createToolFactory(() => getRuntime2().client, { shapes: customerData2 ? shapes : withoutCustomerDataShapes(shapes), withoutCustomerData: !customerData2 });
50954
+ const tools2 = groups2.flatMap((group) => GROUPS[group](factory));
50955
+ assertUniqueNames(tools2);
50956
+ return tools2;
49438
50957
  }
49439
50958
  function createMagentoRestTools(options) {
49440
50959
  const chosen = assertKnownGroups(options.groups ?? []);
@@ -49442,14 +50961,14 @@ function createMagentoRestTools(options) {
49442
50961
  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
50962
  }
49444
50963
  const restGroups = (chosen.length > 0 ? chosen : REST_GROUP_NAMES).filter(isGroupName);
49445
- const rest = assemble(options.getRuntime, applyFieldConfig(BASE_SHAPES, options.fieldConfig ?? {}), restGroups);
50964
+ const rest = assemble(options.getRuntime, applyFieldConfig(BASE_SHAPES, options.fieldConfig ?? {}), restGroups, options.customerData === true);
49446
50965
  const restTools = options.writesEnabled ? rest : rest.filter((tool) => tool.access === "read");
49447
50966
  const database2 = options.database;
49448
50967
  const wantsDatabase = database2 !== void 0 && (chosen.length === 0 || chosen.includes(DATABASE_GROUP));
49449
50968
  const dbTools = wantsDatabase ? databaseTools(database2).filter((tool) => tool.access === "read" || database2.writesEnabled) : [];
49450
- const tools = [...restTools, ...dbTools];
49451
- assertUniqueNames(tools);
49452
- return tools;
50969
+ const tools2 = [...restTools, ...dbTools];
50970
+ assertUniqueNames(tools2);
50971
+ return tools2;
49453
50972
  }
49454
50973
 
49455
50974
  // src/tools/runtime.ts
@@ -49485,6 +51004,8 @@ function createMagentoTokenProvider(configDir) {
49485
51004
  // src/tools/runtime.ts
49486
51005
  var BASE_URL_ENV_VAR = "MAGENTO_REST_BASE_URL";
49487
51006
  var ALLOW_WRITES_ENV_VAR = "MAGENTO_REST_ALLOW_WRITES";
51007
+ var MCP_WRITES_ENV_VAR = "MCP_WRITES_ENABLED";
51008
+ var CUSTOMER_DATA_ENV_VAR = "MAGENTO_REST_CUSTOMER_DATA";
49488
51009
  var FIELDS_FILE_ENV_VAR = "MAGENTO_REST_FIELDS_FILE";
49489
51010
  var GROUPS_ENV_VAR = "MAGENTO_REST_GROUPS";
49490
51011
  function createRuntimeResolver() {
@@ -49509,7 +51030,13 @@ function createRuntimeResolver() {
49509
51030
  };
49510
51031
  }
49511
51032
  function writesEnabled() {
49512
- return process.env[ALLOW_WRITES_ENV_VAR] === "true";
51033
+ return process.env[writesSwitchName()] === "true";
51034
+ }
51035
+ function writesSwitchName() {
51036
+ return process.env[MCP_WRITES_ENV_VAR] !== void 0 ? MCP_WRITES_ENV_VAR : ALLOW_WRITES_ENV_VAR;
51037
+ }
51038
+ function customerDataEnabled() {
51039
+ return process.env[CUSTOMER_DATA_ENV_VAR] === "true";
49513
51040
  }
49514
51041
  function readGroupsFromEnv() {
49515
51042
  try {
@@ -49529,22 +51056,22 @@ function readDatabaseSettingsFromEnv() {
49529
51056
  }
49530
51057
  return { target: parseDatabaseConnection(connection), writesEnabled: writes2 };
49531
51058
  }
49532
- function errorResult(text3) {
49533
- return { isError: true, content: [{ type: "text", text: text3 }] };
51059
+ function errorResult(text4, error61) {
51060
+ return { isError: true, content: [{ type: "text", text: text4 }], structuredContent: { error: errorBodyFor(error61, text4) } };
49534
51061
  }
49535
51062
  function toErrorResult(error61) {
49536
51063
  if (error61 instanceof MagentoRestError) {
49537
51064
  return errorResult(error61.remedy !== void 0 ? `${error61.message}
49538
- Remedy: ${error61.remedy}` : error61.message);
51065
+ Remedy: ${error61.remedy}` : error61.message, error61);
49539
51066
  }
49540
- if (error61 instanceof SqlGuardError || error61 instanceof DatabaseError || error61 instanceof DatabaseConfigError) {
49541
- return errorResult(redact(error61.message));
51067
+ if (error61 instanceof ToolArgumentError || error61 instanceof SqlGuardError || error61 instanceof DatabaseError || error61 instanceof DatabaseConfigError) {
51068
+ return errorResult(redact(error61.message), error61);
49542
51069
  }
49543
51070
  if (error61 instanceof ZodError) {
49544
51071
  const issues = error61.issues.map((issue2) => `${issue2.path.length > 0 ? issue2.path.join(".") : "(root)"}: ${issue2.message}`);
49545
- return errorResult(`Invalid arguments: ${issues.join("; ")}`);
51072
+ return errorResult(`Invalid arguments: ${issues.join("; ")}`, error61);
49546
51073
  }
49547
- return errorResult(`Unexpected error: ${error61 instanceof Error ? redact(error61.message) : "unknown failure"}`);
51074
+ return errorResult(`Unexpected error: ${error61 instanceof Error ? redact(error61.message) : "unknown failure"}`, error61);
49548
51075
  }
49549
51076
  var MAX_FIELDS_FILE_BYTES = 64 * 1024;
49550
51077
  function readFieldConfigFromEnv() {
@@ -49552,12 +51079,12 @@ function readFieldConfigFromEnv() {
49552
51079
  if (path === void 0 || path === "") {
49553
51080
  return {};
49554
51081
  }
49555
- let text3;
51082
+ let text4;
49556
51083
  try {
49557
51084
  if (statSync2(path).size > MAX_FIELDS_FILE_BYTES) {
49558
51085
  throw new FieldConfigError(`${FIELDS_FILE_ENV_VAR}: ${path} is larger than 64 KB; a field configuration is a short list, not a data file`);
49559
51086
  }
49560
- text3 = readFileSync2(path, "utf8");
51087
+ text4 = readFileSync2(path, "utf8");
49561
51088
  } catch (error61) {
49562
51089
  if (error61 instanceof FieldConfigError) {
49563
51090
  throw error61;
@@ -49565,7 +51092,7 @@ function readFieldConfigFromEnv() {
49565
51092
  throw new FieldConfigError(`${FIELDS_FILE_ENV_VAR}: cannot read ${path}: ${error61 instanceof Error ? error61.message : "unknown failure"}`);
49566
51093
  }
49567
51094
  try {
49568
- const config2 = parseFieldConfig(text3);
51095
+ const config2 = parseFieldConfig(text4);
49569
51096
  applyFieldConfig(BASE_SHAPES, config2);
49570
51097
  return config2;
49571
51098
  } catch (error61) {
@@ -49609,39 +51136,45 @@ function loadDatabase() {
49609
51136
  var fieldConfig = loadFieldConfig();
49610
51137
  var groups = loadGroups();
49611
51138
  var database = loadDatabase();
49612
- var server = new McpServer(
49613
- {
49614
- name: "magento-rest",
49615
- version: serverVersion()
49616
- },
49617
- {
49618
- jsonSchemaValidator: noElicitationValidator
49619
- }
49620
- );
49621
51139
  var getRuntime = createRuntimeResolver();
49622
51140
  var writes = writesEnabled();
51141
+ var customerData = customerDataEnabled();
49623
51142
  function assembleTools() {
49624
51143
  try {
49625
- return createMagentoRestTools({ getRuntime, writesEnabled: writes, fieldConfig, groups, ...database !== void 0 ? { database } : {} });
51144
+ return createMagentoRestTools({ getRuntime, writesEnabled: writes, customerData, fieldConfig, groups, ...database !== void 0 ? { database } : {} });
49626
51145
  } catch (error61) {
49627
51146
  logger.error(`magento-rest: refusing to start \u2014 ${error61 instanceof Error ? error61.message : "invalid tool configuration"}`);
49628
51147
  process.exit(1);
49629
51148
  }
49630
51149
  }
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 };
51150
+ var tools = assembleTools();
51151
+ function buildServer() {
51152
+ const server = new McpServer({ name: "magento-rest", version: serverVersion() }, { jsonSchemaValidator: noElicitationValidator });
51153
+ for (const tool of tools) {
51154
+ server.registerTool(
51155
+ tool.name,
51156
+ {
51157
+ description: tool.description,
51158
+ inputSchema: tool.inputSchema.shape,
51159
+ // A read tool declares the shape of its `structuredContent` (Kora contract R-2); the SDK lists it and checks every answer against it.
51160
+ ...tool.outputSchema !== void 0 ? { outputSchema: tool.outputSchema.shape } : {},
51161
+ annotations: tool.annotations
51162
+ },
51163
+ async (args, extra) => {
51164
+ try {
51165
+ const result = await tool.invoke(args, { signal: extra.signal });
51166
+ if (result.isError === true && result.structuredContent === void 0) {
51167
+ return { content: [...result.content], structuredContent: { error: invokeErrorBody(result, tool) }, isError: true };
51168
+ }
51169
+ return { content: [...result.content], ...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : {}, isError: result.isError };
51170
+ } catch (error61) {
51171
+ const rendered = toErrorResult(error61);
51172
+ return { content: [...rendered.content], structuredContent: rendered.structuredContent, isError: rendered.isError };
51173
+ }
49642
51174
  }
49643
- }
49644
- );
51175
+ );
51176
+ }
51177
+ return server;
49645
51178
  }
49646
51179
  var changed = Object.entries(fieldConfig).map(([resource, change]) => `${resource} +${change.add?.length ?? 0} -${change.remove?.length ?? 0}`);
49647
51180
  if (changed.length > 0) {
@@ -49653,14 +51186,78 @@ if (groups.length > 0) {
49653
51186
  if (database !== void 0) {
49654
51187
  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
51188
  }
51189
+ if (customerData) {
51190
+ logger.warn("magento-rest: customer personal data is ON (MAGENTO_REST_CUSTOMER_DATA=true); results carry customer names, emails and order identities.");
51191
+ }
49656
51192
  if (writes) {
49657
- logger.warn("magento-rest: write tools are ENABLED (MAGENTO_REST_ALLOW_WRITES=true); this server can change Magento data.");
51193
+ logger.warn(`magento-rest: write tools are ENABLED (${writesSwitchName()}=true); this server can change Magento data.`);
51194
+ }
51195
+ var HTTP_PORT_ENV_VAR = "MAGENTO_REST_HTTP_PORT";
51196
+ var HTTP_TOKEN_ENV_VAR = "MAGENTO_REST_HTTP_TOKEN";
51197
+ var HTTP_HOST_ENV_VAR = "MAGENTO_REST_HTTP_HOST";
51198
+ var HTTP_ALLOWED_HOSTS_ENV_VAR = "MAGENTO_REST_HTTP_ALLOWED_HOSTS";
51199
+ var HTTP_ALLOWED_ORIGINS_ENV_VAR = "MAGENTO_REST_HTTP_ALLOWED_ORIGINS";
51200
+ var HTTP_ENV_NAMES = {
51201
+ port: HTTP_PORT_ENV_VAR,
51202
+ token: HTTP_TOKEN_ENV_VAR,
51203
+ host: HTTP_HOST_ENV_VAR,
51204
+ allowedHosts: HTTP_ALLOWED_HOSTS_ENV_VAR,
51205
+ allowedOrigins: HTTP_ALLOWED_ORIGINS_ENV_VAR
51206
+ };
51207
+ function loadHttp() {
51208
+ try {
51209
+ return readHttpConfig(HTTP_ENV_NAMES, process.env);
51210
+ } catch (error61) {
51211
+ logger.error(`magento-rest: refusing to start \u2014 ${error61 instanceof Error ? error61.message : "invalid HTTP configuration"}`);
51212
+ process.exit(1);
51213
+ }
51214
+ }
51215
+ var http = loadHttp();
51216
+ var HTTP_SHUTDOWN_GRACE_MS = 5e3;
51217
+ if (http.enabled) {
51218
+ try {
51219
+ const endpoint = await startHttpEndpoint({
51220
+ token: http.token,
51221
+ host: http.host,
51222
+ port: http.port,
51223
+ allowedHosts: http.allowedHosts,
51224
+ allowedOrigins: http.allowedOrigins,
51225
+ handler: async (request) => {
51226
+ const transport = new WebStandardStreamableHTTPServerTransport({ enableJsonResponse: true });
51227
+ const server = buildServer();
51228
+ await server.connect(transport);
51229
+ try {
51230
+ return await transport.handleRequest(request);
51231
+ } finally {
51232
+ await server.close();
51233
+ }
51234
+ }
51235
+ });
51236
+ for (const signal of ["SIGTERM", "SIGINT"]) {
51237
+ process.once(signal, () => {
51238
+ logger.info(`magento-rest: ${signal} received, closing the HTTP endpoint`);
51239
+ void endpoint.close(HTTP_SHUTDOWN_GRACE_MS).then(() => process.exit(0));
51240
+ });
51241
+ }
51242
+ logger.info(`magento-rest: listening on http://${endpoint.host}:${endpoint.port}/mcp`);
51243
+ } catch (error61) {
51244
+ logger.error(`magento-rest: refusing to start \u2014 ${error61 instanceof Error ? error61.message : "invalid HTTP configuration"}`);
51245
+ process.exit(1);
51246
+ }
51247
+ } else {
51248
+ const { stdout } = createStdioServer();
51249
+ const transport = new StdioServerTransport(process.stdin, stdout);
51250
+ await buildServer().connect(transport);
49658
51251
  }
49659
- var { stdout } = createStdioServer();
49660
- var transport = new StdioServerTransport(process.stdin, stdout);
49661
- await server.connect(transport);
49662
51252
  /*! Bundled license information:
49663
51253
 
51254
+ content-type/index.js:
51255
+ (*!
51256
+ * content-type
51257
+ * Copyright(c) 2015 Douglas Christopher Wilson
51258
+ * MIT Licensed
51259
+ *)
51260
+
49664
51261
  long/umd/index.js:
49665
51262
  (**
49666
51263
  * @license