@hiberus-magento/magento-rest 0.2.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/README.md CHANGED
@@ -46,6 +46,8 @@ executable to run`.
46
46
  - `magentorest_advanced_product_search` (read-only) — Use this to filter products on one field with a chosen comparison (eq, like, gt, gteq, lt, lteq, in, ...) and sort the result. Returns a bounded page of summaries and the total count.
47
47
  - `magentorest_create_product` — Use this to create a new product. Adds a catalog record; the SKU must be unique. Does not touch stock or categories. Without website_ids it goes to the default website only: the website of store_code's store view, or the store's only website; with several websites and no store_code it refuses and asks for website_ids (magentorest_get_websites lists them).
48
48
  - `magentorest_update_product` — Use this to change fields of an existing product. Only the fields you pass are sent; at least one is required. Overwrites the current values.
49
+ - `magentorest_get_product_content` (read-only) — 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. **Not verified against a live service** — this tool has not been run against a real Magento instance; its request shape and response projection are covered by unit tests against a test double and by the conformance suite.
50
+ - `magentorest_update_product_content` — 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. **Not verified against a live service** — this tool has not been run against a real Magento instance; its request shape and response projection are covered by unit tests against a test double and by the conformance suite.
49
51
  - `magentorest_update_product_attribute` — Use this to set ONE attribute of a product by code (name, price, status, description, a custom attribute, ...). Overwrites the current value. The identity attributes sku, id, entity_id and type_id are refused.
50
52
  - `magentorest_delete_product` — Use this to permanently delete a product by SKU. Irreversible: the product, its images and its URL rewrites are removed.
51
53
  - `magentorest_assign_product_to_category` — Use this to add a product to a category at a position. Adds a link; it does not move the product out of other categories.
@@ -174,7 +176,7 @@ Pin the exact version; pass secrets as environment variable references, never li
174
176
  "args": [
175
177
  "-y",
176
178
  "--package",
177
- "@hiberus-magento/magento-rest@0.2.0",
179
+ "@hiberus-magento/magento-rest@0.3.0",
178
180
  "hiberus-magento-rest-mcp"
179
181
  ],
180
182
  "env": {
@@ -324,6 +326,36 @@ number, status, totals and lines. A `MAGENTO_REST_FIELDS_FILE` cannot add these
324
326
  fields back while the switch is off. The database tools are not filtered: they
325
327
  return what their SQL selects.
326
328
 
329
+ ## Product content per store view
330
+
331
+ `magentorest_get_product_content` reads a product's name, description, short
332
+ description, meta title and meta description, and each image's `id` (a decimal
333
+ string), `file` and `label`, as one store view shows them: its own value, or the
334
+ one it inherits, or `null` when there is none. An unknown SKU returns
335
+ `found: false`; an unknown store view is an `invalid_argument` error on
336
+ `store_view`.
337
+
338
+ `magentorest_update_product_content` (a write tool) changes any of those values in
339
+ **one** store view: `all`, `admin`, an empty or a missing `store_view` are refused
340
+ before anything is sent. It reads the product first, so an unknown SKU or image is
341
+ a `not_found` error and no product is ever created; checks lengths (255 characters
342
+ for the name, meta title, meta description and labels; 65,535 bytes for the
343
+ descriptions), because Magento would silently truncate, and refuses an empty value
344
+ (clearing a store view's value is not supported) or the same image twice; sends only the values
345
+ that differ from what it read (the full media entry for a changed label); and
346
+ returns the content read back. Repeating the same call sends nothing.
347
+
348
+ **Requires Magento 2.4.7 or later.** Magento 2.4.6 pins at store-view level a sent
349
+ value equal to the inherited one, and the patch version cannot be read over REST,
350
+ so this is not checked.
351
+
352
+ **Known side effect.** Magento's REST API has no way to update only some
353
+ attributes. Whenever a product is saved in a store view, Magento writes a
354
+ store-view value (label, position, hidden) for **every image of the product**,
355
+ copied from its current values. What the store shows does not change, but those
356
+ images stop inheriting later changes made to the default values in that store
357
+ view.
358
+
327
359
  ## Using it from an MCP host (`server.json`)
328
360
 
329
361
  The package ships a `server.json` (the MCP registry's server manifest, schema
@@ -333,7 +365,9 @@ form from it sees four variables: `MAGENTO_REST_BASE_URL` and `MAGENTO_REST_TOKE
333
365
  (required, the token secret), `MAGENTO_REST_GROUPS`, and `MCP_WRITES_ENABLED`
334
366
  (boolean, default `false`). The standalone write switch, customer data, the field
335
367
  file and the database are deliberately not declared, so a host's form cannot turn
336
- them on.
368
+ them on. A host launches the bin named after the unscoped package, `magento-rest`,
369
+ which starts the MCP server (as `hiberus-magento-rest-mcp` does), so
370
+ `npx -y @hiberus-magento/magento-rest` works without naming a bin.
337
371
 
338
372
  ## Tool groups
339
373
 
@@ -357,7 +391,7 @@ server, because the tools it names cannot exist.
357
391
 
358
392
  | Group | Covers | Tools (`*` = write) |
359
393
  |---|---|---|
360
- | `products` | Catalog products: read, search, create, update, delete, category assignment | get_product_by_sku, search_products, advanced_product_search, create_product*, update_product*, update_product_attribute*, delete_product*, assign_product_to_category*, remove_product_from_category* |
394
+ | `products` | Catalog products: read, search, create, update, delete, category assignment, content per store view | get_product_by_sku, search_products, advanced_product_search, get_product_content, create_product*, update_product*, update_product_content*, update_product_attribute*, delete_product*, assign_product_to_category*, remove_product_from_category* |
361
395
  | `store` | Store configuration: store views, websites, store groups, countries, currency | get_store_configs, get_store_views, get_websites, get_store_groups, get_countries, get_currency_info |
362
396
  | `categories` | Category tree and the products in a category | get_category_tree, get_category_by_id, list_categories, get_products_in_category, create_category*, update_category*, delete_category*, move_category* |
363
397
  | `customers` | Customers, their groups and addresses | get_customer_by_id, search_customers, get_customer_groups, get_customer_addresses, create_customer*, update_customer*, delete_customer* |
package/dist/cli.js CHANGED
@@ -9128,8 +9128,8 @@ function ko_default() {
9128
9128
  }
9129
9129
 
9130
9130
  // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/lt.js
9131
- var capitalizeFirstCharacter = (text3) => {
9132
- return text3.charAt(0).toUpperCase() + text3.slice(1);
9131
+ var capitalizeFirstCharacter = (text4) => {
9132
+ return text4.charAt(0).toUpperCase() + text4.slice(1);
9133
9133
  };
9134
9134
  function getUnitTypeFromNumber(number4) {
9135
9135
  const abs = Math.abs(number4);
@@ -19052,11 +19052,15 @@ function readTokenFromStdin() {
19052
19052
  // src/client/errors.ts
19053
19053
  var MAX_MESSAGE_CHARS = 240;
19054
19054
  var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
19055
- var MagentoRestError = class extends Error {
19055
+ var MagentoRestError = class _MagentoRestError extends Error {
19056
19056
  kind;
19057
19057
  status;
19058
19058
  retryable;
19059
19059
  remedy;
19060
+ resources;
19061
+ retryAfterMs;
19062
+ timedOut;
19063
+ answer;
19060
19064
  constructor(init) {
19061
19065
  super(init.message, init.cause !== void 0 ? { cause: init.cause } : void 0);
19062
19066
  this.name = "MagentoRestError";
@@ -19064,6 +19068,25 @@ var MagentoRestError = class extends Error {
19064
19068
  this.status = init.status;
19065
19069
  this.retryable = init.retryable ?? false;
19066
19070
  this.remedy = init.remedy;
19071
+ this.resources = init.resources;
19072
+ this.retryAfterMs = init.retryAfterMs;
19073
+ this.timedOut = init.timedOut;
19074
+ this.answer = init.answer;
19075
+ }
19076
+ /** The same error, carrying where and when Magento gave it. */
19077
+ withAnswer(answer) {
19078
+ return new _MagentoRestError({
19079
+ kind: this.kind,
19080
+ message: this.message,
19081
+ retryable: this.retryable,
19082
+ ...this.status !== void 0 ? { status: this.status } : {},
19083
+ ...this.remedy !== void 0 ? { remedy: this.remedy } : {},
19084
+ ...this.resources !== void 0 ? { resources: this.resources } : {},
19085
+ ...this.retryAfterMs !== void 0 ? { retryAfterMs: this.retryAfterMs } : {},
19086
+ ...this.timedOut !== void 0 ? { timedOut: this.timedOut } : {},
19087
+ ...this.cause !== void 0 ? { cause: this.cause } : {},
19088
+ answer
19089
+ });
19067
19090
  }
19068
19091
  };
19069
19092
  function kindForStatus(status2) {
@@ -19114,7 +19137,7 @@ function extractAclResources(status2, bodyText) {
19114
19137
  }
19115
19138
  return void 0;
19116
19139
  }
19117
- function classifyFailure(status2, bodyText) {
19140
+ function classifyFailure(status2, bodyText, retryAfterMs2) {
19118
19141
  const kind = kindForStatus(status2);
19119
19142
  const template = extractTemplate(bodyText);
19120
19143
  const resources = extractAclResources(status2, bodyText);
@@ -19125,7 +19148,9 @@ function classifyFailure(status2, bodyText) {
19125
19148
  message,
19126
19149
  status: status2,
19127
19150
  retryable: RETRYABLE_STATUSES.has(status2),
19128
- ...remedy !== void 0 ? { remedy } : {}
19151
+ ...remedy !== void 0 ? { remedy } : {},
19152
+ ...resources !== void 0 ? { resources } : {},
19153
+ ...retryAfterMs2 !== void 0 ? { retryAfterMs: retryAfterMs2 } : {}
19129
19154
  });
19130
19155
  }
19131
19156
 
@@ -19256,7 +19281,7 @@ function createRestTransport(deps) {
19256
19281
  headers["Content-Type"] = "application/json";
19257
19282
  }
19258
19283
  let response;
19259
- let text3;
19284
+ let text4;
19260
19285
  try {
19261
19286
  response = await deps.fetch(`${root}${request.path}${request.query !== void 0 && request.query !== "" ? `?${request.query}` : ""}`, {
19262
19287
  method: request.method,
@@ -19267,7 +19292,7 @@ function createRestTransport(deps) {
19267
19292
  signal: request.signal !== void 0 ? AbortSignal.any([request.signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs),
19268
19293
  ...hasBody ? { body: JSON.stringify(request.body) } : {}
19269
19294
  });
19270
- text3 = await response.text();
19295
+ text4 = await response.text();
19271
19296
  } catch (cause) {
19272
19297
  if (request.signal?.aborted === true) {
19273
19298
  return { failure: cancelled(cause) };
@@ -19278,19 +19303,20 @@ function createRestTransport(deps) {
19278
19303
  kind: "transport",
19279
19304
  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.",
19280
19305
  retryable: true,
19306
+ ...timedOut ? { timedOut: true } : {},
19281
19307
  cause
19282
19308
  })
19283
19309
  };
19284
19310
  }
19285
19311
  if (!response.ok) {
19286
19312
  const after = retryAfterMs(response);
19287
- return { failure: classifyFailure(response.status, text3), ...after !== void 0 ? { retryAfterMs: after } : {} };
19313
+ return { failure: classifyFailure(response.status, text4, after), ...after !== void 0 ? { retryAfterMs: after } : {} };
19288
19314
  }
19289
- if (text3 === "") {
19315
+ if (text4 === "") {
19290
19316
  return { value: void 0 };
19291
19317
  }
19292
19318
  try {
19293
- return { value: JSON.parse(text3) };
19319
+ return { value: JSON.parse(text4) };
19294
19320
  } catch {
19295
19321
  return {
19296
19322
  failure: new MagentoRestError({ kind: "unparseable", message: "Magento REST returned a success status with a body that is not JSON.", status: response.status })
@@ -19328,7 +19354,7 @@ function createRestTransport(deps) {
19328
19354
  random
19329
19355
  );
19330
19356
  if (!decision.retry) {
19331
- throw outcome.failure;
19357
+ throw outcome.failure.status !== void 0 ? outcome.failure.withAnswer(answerFor(request, root)) : outcome.failure;
19332
19358
  }
19333
19359
  await deps.sleep(decision.delayMs);
19334
19360
  }
@@ -19405,14 +19431,14 @@ function buildSearchCriteria(input2) {
19405
19431
 
19406
19432
  // src/client/paths.ts
19407
19433
  function encodeSegment(value) {
19408
- const text3 = String(value);
19409
- if (text3 === "") {
19434
+ const text4 = String(value);
19435
+ if (text4 === "") {
19410
19436
  throw new Error("restPath: an empty path segment is not allowed");
19411
19437
  }
19412
- if (/^\.+$/.test(text3)) {
19413
- return text3.replaceAll(".", "%2E");
19438
+ if (/^\.+$/.test(text4)) {
19439
+ return text4.replaceAll(".", "%2E");
19414
19440
  }
19415
- return encodeURIComponent(text3);
19441
+ return encodeURIComponent(text4);
19416
19442
  }
19417
19443
  function restPath(strings, ...values) {
19418
19444
  let out = strings[0] ?? "";
@@ -19460,15 +19486,15 @@ var NAMES = {
19460
19486
  };
19461
19487
  var MAX_INPUT_LENGTH = 64;
19462
19488
  function normalizeCountry(input2) {
19463
- const text3 = input2.trim().toLowerCase();
19464
- if (text3.length === 0 || text3.length > MAX_INPUT_LENGTH) {
19489
+ const text4 = input2.trim().toLowerCase();
19490
+ if (text4.length === 0 || text4.length > MAX_INPUT_LENGTH) {
19465
19491
  return void 0;
19466
19492
  }
19467
- const named = NAMES[text3];
19468
- if (named !== void 0 && Object.hasOwn(NAMES, text3)) {
19493
+ const named = NAMES[text4];
19494
+ if (named !== void 0 && Object.hasOwn(NAMES, text4)) {
19469
19495
  return named;
19470
19496
  }
19471
- return /^[a-z]{2}$/.test(text3) ? text3.toUpperCase() : void 0;
19497
+ return /^[a-z]{2}$/.test(text4) ? text4.toUpperCase() : void 0;
19472
19498
  }
19473
19499
 
19474
19500
  // src/client/date-range.ts
@@ -19486,8 +19512,8 @@ function formatMagentoTimestamp(date5) {
19486
19512
  function formatDay(date5) {
19487
19513
  return date5.toISOString().slice(0, 10);
19488
19514
  }
19489
- function parseDay(text3) {
19490
- const match = DAY_PATTERN.exec(text3);
19515
+ function parseDay(text4) {
19516
+ const match = DAY_PATTERN.exec(text4);
19491
19517
  if (match === null) {
19492
19518
  return void 0;
19493
19519
  }
@@ -20604,11 +20630,194 @@ var provenanceSchema = external_exports.object({
20604
20630
  store_view: external_exports.string().optional()
20605
20631
  });
20606
20632
 
20633
+ // src/tools/rest-tool.ts
20634
+ function provenanceOf(answers) {
20635
+ const first = answers[0];
20636
+ const last = answers.at(-1);
20637
+ if (first === void 0 || last === void 0) {
20638
+ throw new Error("The read produced no Magento answer to cite, so its result cannot carry provenance.");
20639
+ }
20640
+ const endpoints = [...new Set(answers.map((answer) => answer.endpoint))];
20641
+ return {
20642
+ endpoint: first.endpoint,
20643
+ ...endpoints.length > 1 ? { endpoints } : {},
20644
+ api_version: "V1",
20645
+ read_at: last.readAt,
20646
+ ...first.storeView !== void 0 ? { store_view: first.storeView } : {}
20647
+ };
20648
+ }
20649
+
20607
20650
  // src/tools/database-tools.ts
20608
20651
  var SQL_PARAM = external_exports.union([external_exports.string().max(2e3), external_exports.number(), external_exports.boolean(), external_exports.null()]);
20609
20652
  var params = external_exports.array(SQL_PARAM).max(50).optional().describe("Values for the ? placeholders in the statement, in order. Always pass values here instead of writing them into the SQL.");
20610
20653
  var tableName = external_exports.string().regex(/^[A-Za-z0-9_]{1,64}$/, "letters, digits and underscore only (max 64)");
20611
20654
 
20655
+ // src/tools/tool-error.ts
20656
+ var ToolArgumentError = class extends Error {
20657
+ code;
20658
+ argument;
20659
+ constructor(code, argument, message) {
20660
+ super(message);
20661
+ this.name = "ToolArgumentError";
20662
+ this.code = code;
20663
+ this.argument = argument;
20664
+ }
20665
+ };
20666
+
20667
+ // src/tools/product-content-tools.ts
20668
+ var PRODUCT_CONTENT_READ_TOOL = "magentorest_get_product_content";
20669
+ var PRODUCT_CONTENT_WRITE_TOOL = "magentorest_update_product_content";
20670
+ var CONTENT_FIELDS = ["name", "description", "short_description", "meta_title", "meta_description"];
20671
+ var MAX_CHARS = { name: 255, meta_title: 255, meta_description: 255 };
20672
+ var MAX_TEXT_BYTES = 65535;
20673
+ var MAX_LABEL_CHARS = 255;
20674
+ var STORE_VIEW = /^[A-Za-z][A-Za-z0-9_]{0,31}$/;
20675
+ var GLOBAL_SCOPES = /* @__PURE__ */ new Set(["all", "admin"]);
20676
+ var UNKNOWN_ROUTE = "Request does not match any route";
20677
+ var contentSchema = external_exports.object(Object.fromEntries(CONTENT_FIELDS.map((field2) => [field2, external_exports.string().nullable()])));
20678
+ var imageSchema = external_exports.object({ id: external_exports.string(), file: external_exports.string().nullable(), label: external_exports.string().nullable() });
20679
+ var productContentSchema = external_exports.object({
20680
+ found: external_exports.boolean(),
20681
+ sku: external_exports.string(),
20682
+ store_view: external_exports.string(),
20683
+ content: contentSchema.optional(),
20684
+ images: external_exports.array(imageSchema).optional(),
20685
+ provenance: provenanceSchema
20686
+ });
20687
+ var isRecord3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
20688
+ var text3 = (value) => typeof value === "string" && value !== "" ? value : null;
20689
+ function parseProduct(body) {
20690
+ const record2 = isRecord3(body) ? body : {};
20691
+ const custom2 = /* @__PURE__ */ new Map();
20692
+ for (const attribute of Array.isArray(record2["custom_attributes"]) ? record2["custom_attributes"] : []) {
20693
+ if (isRecord3(attribute) && typeof attribute["attribute_code"] === "string") custom2.set(attribute["attribute_code"], attribute["value"]);
20694
+ }
20695
+ const content2 = Object.fromEntries(CONTENT_FIELDS.map((field2) => [field2, text3(field2 === "name" ? record2["name"] : custom2.get(field2))]));
20696
+ const media = [];
20697
+ for (const entry of Array.isArray(record2["media_gallery_entries"]) ? record2["media_gallery_entries"] : []) {
20698
+ if (isRecord3(entry) && typeof entry["id"] === "number") media.push({ id: entry["id"], label: text3(entry["label"]), file: text3(entry["file"]), raw: entry });
20699
+ }
20700
+ return { content: content2, media };
20701
+ }
20702
+ function shaped(skuValue, storeView, product, provenance) {
20703
+ return {
20704
+ found: true,
20705
+ sku: skuValue,
20706
+ store_view: storeView,
20707
+ content: product.content,
20708
+ images: product.media.map((entry) => ({ id: String(entry.id), file: entry.file, label: entry.label })),
20709
+ provenance
20710
+ };
20711
+ }
20712
+ function checkedStoreView(value, forWrite) {
20713
+ if (value === void 0 || value === "") {
20714
+ throw new ToolArgumentError("invalid_argument", "store_view", "store_view is required: the code of the store view to read or write (for example default).");
20715
+ }
20716
+ if (!STORE_VIEW.test(value)) {
20717
+ throw new ToolArgumentError("invalid_argument", "store_view", "store_view must be a store view code: letters, digits and underscores.");
20718
+ }
20719
+ if (forWrite && GLOBAL_SCOPES.has(value.toLowerCase())) {
20720
+ 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.");
20721
+ }
20722
+ return value;
20723
+ }
20724
+ var isUnknownStoreView = (error61) => error61 instanceof MagentoRestError && error61.kind === "not-found" && error61.message.includes(UNKNOWN_ROUTE);
20725
+ var isMissingProduct = (error61) => error61 instanceof MagentoRestError && error61.kind === "not-found" && !error61.message.includes(UNKNOWN_ROUTE);
20726
+ async function readProduct(client, skuValue) {
20727
+ try {
20728
+ return parseProduct(await client.get(restPath`/products/${skuValue}`));
20729
+ } catch (error61) {
20730
+ if (isUnknownStoreView(error61)) throw new ToolArgumentError("invalid_argument", "store_view", "Magento has no store view with that code.");
20731
+ throw error61;
20732
+ }
20733
+ }
20734
+ var storeViewInput = external_exports.string().optional().describe("The store view code (for example default). Required; checked by the tool.");
20735
+ 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.");
20736
+ 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.");
20737
+ function checkedChange(content2, images) {
20738
+ for (const field2 of CONTENT_FIELDS) {
20739
+ const value = content2?.[field2];
20740
+ if (value === void 0) continue;
20741
+ const argument = `content.${field2}`;
20742
+ if (value === "") throw new ToolArgumentError("invalid_argument", argument, `${field2} cannot be empty: clearing a value is not supported.`);
20743
+ const maxChars = MAX_CHARS[field2];
20744
+ if (maxChars !== void 0 && [...value].length > maxChars) throw new ToolArgumentError("invalid_argument", argument, `${field2} is at most ${maxChars} characters.`);
20745
+ 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.`);
20746
+ }
20747
+ const seen = /* @__PURE__ */ new Set();
20748
+ const checkedImages = (images ?? []).map((image, index) => {
20749
+ 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".');
20750
+ if (seen.has(image.id)) throw new ToolArgumentError("invalid_argument", `images[${index}].id`, "Each image id may appear once.");
20751
+ seen.add(image.id);
20752
+ if (image.label === "") throw new ToolArgumentError("invalid_argument", `images[${index}].label`, "A label cannot be empty: Magento stores an empty label as no label.");
20753
+ if ([...image.label].length > MAX_LABEL_CHARS) throw new ToolArgumentError("invalid_argument", `images[${index}].label`, `A label is at most ${MAX_LABEL_CHARS} characters.`);
20754
+ return { id: Number(image.id), label: image.label };
20755
+ });
20756
+ return { content: content2 ?? {}, images: checkedImages };
20757
+ }
20758
+ function productContentTools({ shapedTool }) {
20759
+ return [
20760
+ shapedTool({
20761
+ name: PRODUCT_CONTENT_READ_TOOL,
20762
+ 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.",
20763
+ input: external_exports.object({ sku, store_view: storeViewInput }).strict(),
20764
+ output: productContentSchema,
20765
+ run: async ({ sku: skuValue, store_view }, track) => {
20766
+ const storeView = checkedStoreView(store_view, false);
20767
+ const read = track();
20768
+ try {
20769
+ const product = await readProduct(read.client.with({ scope: storeView }), skuValue);
20770
+ return shaped(skuValue, storeView, product, provenanceOf(read.answers));
20771
+ } catch (error61) {
20772
+ if (isMissingProduct(error61) && error61 instanceof MagentoRestError && error61.answer !== void 0) {
20773
+ return { found: false, sku: skuValue, store_view: storeView, provenance: provenanceOf([error61.answer]) };
20774
+ }
20775
+ throw error61;
20776
+ }
20777
+ }
20778
+ }),
20779
+ shapedTool({
20780
+ name: PRODUCT_CONTENT_WRITE_TOOL,
20781
+ 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.",
20782
+ effect: "update",
20783
+ input: external_exports.object({ sku, store_view: storeViewInput, content: contentInput, images: imagesInput }).strict(),
20784
+ output: productContentSchema,
20785
+ run: async ({ sku: skuValue, store_view, content: content2, images }, track) => {
20786
+ const storeView = checkedStoreView(store_view, true);
20787
+ const change = checkedChange(content2, images);
20788
+ const before = track();
20789
+ let current;
20790
+ try {
20791
+ current = await readProduct(before.client.with({ scope: storeView }), skuValue);
20792
+ } catch (error61) {
20793
+ if (isMissingProduct(error61)) throw new ToolArgumentError("not_found", "sku", "No product with that SKU: nothing was written.");
20794
+ throw error61;
20795
+ }
20796
+ const entries = change.images.map((image, index) => {
20797
+ const found = current.media.find((entry) => entry.id === image.id);
20798
+ if (found === void 0) throw new ToolArgumentError("not_found", `images[${index}].id`, "The product has no image with that id: nothing was written.");
20799
+ return { entry: found, label: image.label };
20800
+ });
20801
+ const scoped = before.client.with({ scope: storeView });
20802
+ const changedFields = CONTENT_FIELDS.filter((field2) => change.content[field2] !== void 0 && change.content[field2] !== current.content[field2]);
20803
+ if (changedFields.length > 0) {
20804
+ const custom2 = changedFields.filter((field2) => field2 !== "name").map((field2) => ({ attribute_code: field2, value: change.content[field2] }));
20805
+ await scoped.put(restPath`/products/${skuValue}`, {
20806
+ product: { sku: skuValue, ...changedFields.includes("name") ? { name: change.content.name } : {}, ...custom2.length > 0 ? { custom_attributes: custom2 } : {} }
20807
+ });
20808
+ }
20809
+ for (const { entry, label: label2 } of entries) {
20810
+ if (label2 === entry.label) continue;
20811
+ await scoped.put(restPath`/products/${skuValue}/media/${entry.id}`, { entry: { ...entry.raw, label: label2 } });
20812
+ }
20813
+ const after = track();
20814
+ const product = await readProduct(after.client.with({ scope: storeView }), skuValue);
20815
+ return shaped(skuValue, storeView, product, provenanceOf(after.answers));
20816
+ }
20817
+ })
20818
+ ];
20819
+ }
20820
+
20612
20821
  // src/tools/products-tools.ts
20613
20822
  var IDENTITY_ATTRIBUTES = /* @__PURE__ */ new Set(["sku", "id", "entity_id", "type_id"]);
20614
20823
  var primitiveValue = external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()]);
@@ -20978,11 +21187,11 @@ var LIST_PAGE_SIZE7 = 20;
20978
21187
  var statusCode = (what) => external_exports.string().regex(/^[a-z0-9_]{1,32}$/, "lowercase letters, digits and underscores only").describe(what);
20979
21188
  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.");
20980
21189
  var orderId = entityId("order (entity ID, not the order number)");
20981
- function isRecord3(value) {
21190
+ function isRecord4(value) {
20982
21191
  return value !== null && typeof value === "object" && !Array.isArray(value);
20983
21192
  }
20984
21193
  function arrayField(record2, key) {
20985
- if (isRecord3(record2)) {
21194
+ if (isRecord4(record2)) {
20986
21195
  const value = record2[key];
20987
21196
  return Array.isArray(value) ? value : [];
20988
21197
  }
@@ -21407,7 +21616,7 @@ function taxTools({ readTool, shapes }) {
21407
21616
 
21408
21617
  // src/tools/index.ts
21409
21618
  var GROUPS = {
21410
- products: productTools,
21619
+ products: (factory) => [...productTools(factory), ...productContentTools(factory)],
21411
21620
  store: storeTools,
21412
21621
  categories: categoryTools,
21413
21622
  customers: customerTools,
package/dist/mcp.js CHANGED
@@ -207,7 +207,7 @@ var require_lib = __commonJS({
207
207
  SET_CLAUSE_TERMINATORS_BY_FIRST[first] = [word];
208
208
  }
209
209
  var hasOwnProperty = Object.prototype.hasOwnProperty;
210
- 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);
211
211
  var isWordChar = (code) => code >= 65 && code <= 90 || code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 95;
212
212
  var isWhitespace = (code) => code === charCode.space || code === charCode.tab || code === charCode.newline || code === charCode.carriageReturn;
213
213
  var toLower = (code) => code | 32;
@@ -566,7 +566,7 @@ var require_lib = __commonJS({
566
566
  return String(value.toSqlString());
567
567
  if (!(stringifyObjects === void 0 || stringifyObjects === null))
568
568
  return escapeString(String(value));
569
- if (isRecord4(value) || value instanceof Map)
569
+ if (isRecord5(value) || value instanceof Map)
570
570
  return (0, exports.objectToValues)(value, timezone);
571
571
  return escapeString(String(value));
572
572
  }
@@ -604,7 +604,7 @@ var require_lib = __commonJS({
604
604
  else if (typeof currentValue === "number" || typeof currentValue === "bigint")
605
605
  escapedValue = `${currentValue}`;
606
606
  else if (typeof currentValue === "object" && currentValue !== null && !stringifyObjects) {
607
- 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);
608
608
  if (expandable) {
609
609
  let previous = placeholderPosition - 1;
610
610
  while (previous >= chunkIndex && isWhitespace(sql.charCodeAt(previous)))
@@ -6599,12 +6599,12 @@ var require_helpers = __commonJS({
6599
6599
  const REQUIRE_TERMINATOR = "";
6600
6600
  highlightFn = __require(`cardinal${REQUIRE_TERMINATOR}`).highlight;
6601
6601
  } catch {
6602
- highlightFn = (text3) => {
6602
+ highlightFn = (text4) => {
6603
6603
  if (!cardinalRecommended) {
6604
6604
  console.log("For nicer debug output consider install cardinal@^2.0.0");
6605
6605
  cardinalRecommended = true;
6606
6606
  }
6607
- return text3;
6607
+ return text4;
6608
6608
  };
6609
6609
  }
6610
6610
  function printDebugWithCode(msg, code) {
@@ -17448,7 +17448,7 @@ function resolveServerVersion(injected) {
17448
17448
  return injected;
17449
17449
  }
17450
17450
  function serverVersion() {
17451
- return resolveServerVersion(false ? void 0 : "0.2.0");
17451
+ return resolveServerVersion(false ? void 0 : "0.3.0");
17452
17452
  }
17453
17453
 
17454
17454
  // ../mcp-core/src/credentials/token-provider.ts
@@ -17517,7 +17517,7 @@ function defineTool(def) {
17517
17517
  result = await def.handler(parsed, ctx);
17518
17518
  } catch (error61) {
17519
17519
  if (error61 instanceof MissingCredentialError || error61 instanceof CredentialExpiredError) {
17520
- return { content: [{ type: "text", text: error61.message }], isError: true };
17520
+ return { content: [{ type: "text", text: error61.message }], isError: true, errorKind: "credential" };
17521
17521
  }
17522
17522
  throw error61;
17523
17523
  }
@@ -17527,13 +17527,14 @@ function defineTool(def) {
17527
17527
  if (bytes > DEFAULT_MAX_OUTPUT_BYTES) {
17528
17528
  return {
17529
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
17530
+ isError: true,
17531
+ errorKind: "too_large"
17531
17532
  };
17532
17533
  }
17533
17534
  return { content: [{ type: "text", text: json2 }], structuredContent: result };
17534
17535
  }
17535
- const text3 = truncate(toTextContent(result), DEFAULT_MAX_OUTPUT_BYTES);
17536
- return { content: [{ type: "text", text: text3 }] };
17536
+ const text4 = truncate(toTextContent(result), DEFAULT_MAX_OUTPUT_BYTES);
17537
+ return { content: [{ type: "text", text: text4 }] };
17537
17538
  }
17538
17539
  };
17539
17540
  }
@@ -26620,8 +26621,8 @@ function ko_default() {
26620
26621
  }
26621
26622
 
26622
26623
  // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/lt.js
26623
- var capitalizeFirstCharacter = (text3) => {
26624
- return text3.charAt(0).toUpperCase() + text3.slice(1);
26624
+ var capitalizeFirstCharacter = (text4) => {
26625
+ return text4.charAt(0).toUpperCase() + text4.slice(1);
26625
26626
  };
26626
26627
  function getUnitTypeFromNumber(number4) {
26627
26628
  const abs = Math.abs(number4);
@@ -47025,8 +47026,8 @@ function tokenize(sql) {
47025
47026
  const tokens = [];
47026
47027
  let depth = 0;
47027
47028
  let i = 0;
47028
- const push = (kind, text3, start) => {
47029
- tokens.push({ kind, text: text3, depth, start });
47029
+ const push = (kind, text4, start) => {
47030
+ tokens.push({ kind, text: text4, depth, start });
47030
47031
  };
47031
47032
  while (i < sql.length) {
47032
47033
  const ch = sql[i];
@@ -47133,8 +47134,8 @@ function singleStatement(sql) {
47133
47134
  if (body.length === 0) {
47134
47135
  throw new SqlGuardError("the statement is empty");
47135
47136
  }
47136
- const text3 = semicolons.length === 1 && last !== void 0 ? sql.slice(0, last.start).trimEnd() : sql.trim();
47137
- 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 };
47138
47139
  }
47139
47140
  function checkCommon(tokens) {
47140
47141
  for (const [index, token] of tokens.entries()) {
@@ -47225,7 +47226,7 @@ function checkStars(tokens) {
47225
47226
  }
47226
47227
  }
47227
47228
  function guardReadQuery(sql, maxRows) {
47228
- const { tokens, text: text3 } = singleStatement(sql);
47229
+ const { tokens, text: text4 } = singleStatement(sql);
47229
47230
  const first = tokens[0];
47230
47231
  if (first?.kind !== "word" || first.text !== "SELECT") {
47231
47232
  throw new SqlGuardError("only a SELECT is allowed here");
@@ -47249,7 +47250,7 @@ function guardReadQuery(sql, maxRows) {
47249
47250
  }
47250
47251
  const limitIndex = tokens.findIndex((t) => t.depth === 0 && t.kind === "word" && t.text === "LIMIT");
47251
47252
  if (limitIndex < 0) {
47252
- return { sql: `${text3} LIMIT ${maxRows}` };
47253
+ return { sql: `${text4} LIMIT ${maxRows}` };
47253
47254
  }
47254
47255
  const tail = tokens.slice(limitIndex + 1);
47255
47256
  const isNumber = (t) => t?.kind === "number";
@@ -47264,10 +47265,10 @@ function guardReadQuery(sql, maxRows) {
47264
47265
  if (!(count <= maxRows)) {
47265
47266
  throw new SqlGuardError(`LIMIT ${count} is over the cap of ${maxRows} rows per call; lower it or page with OFFSET`);
47266
47267
  }
47267
- return { sql: text3 };
47268
+ return { sql: text4 };
47268
47269
  }
47269
47270
  function guardWriteStatement(sql) {
47270
- const { tokens, text: text3 } = singleStatement(sql);
47271
+ const { tokens, text: text4 } = singleStatement(sql);
47271
47272
  const first = tokens[0];
47272
47273
  const kind = first?.kind === "word" ? first.text.toLowerCase() : void 0;
47273
47274
  if (kind !== "insert" && kind !== "update" && kind !== "delete") {
@@ -47286,7 +47287,7 @@ function guardWriteStatement(sql) {
47286
47287
  throw new SqlGuardError("INTO is only allowed in an INSERT");
47287
47288
  }
47288
47289
  }
47289
- return { sql: text3, kind };
47290
+ return { sql: text4, kind };
47290
47291
  }
47291
47292
 
47292
47293
  // src/db/rows.ts
@@ -47308,8 +47309,8 @@ function cell(value) {
47308
47309
  return value.toISOString();
47309
47310
  }
47310
47311
  if (typeof value === "string") {
47311
- const text3 = value.length > MAX_CELL_CHARS ? `${value.slice(0, MAX_CELL_CHARS)}\u2026 [truncated, ${value.length} characters]` : value;
47312
- 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);
47313
47314
  }
47314
47315
  if (typeof value === "object") {
47315
47316
  return redact(JSON.stringify(value, (_key, v) => typeof v === "bigint" ? v.toString() : v));
@@ -47478,11 +47479,15 @@ function createDatabaseAccess(options) {
47478
47479
  // src/client/errors.ts
47479
47480
  var MAX_MESSAGE_CHARS = 240;
47480
47481
  var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
47481
- var MagentoRestError = class extends Error {
47482
+ var MagentoRestError = class _MagentoRestError extends Error {
47482
47483
  kind;
47483
47484
  status;
47484
47485
  retryable;
47485
47486
  remedy;
47487
+ resources;
47488
+ retryAfterMs;
47489
+ timedOut;
47490
+ answer;
47486
47491
  constructor(init) {
47487
47492
  super(init.message, init.cause !== void 0 ? { cause: init.cause } : void 0);
47488
47493
  this.name = "MagentoRestError";
@@ -47490,6 +47495,25 @@ var MagentoRestError = class extends Error {
47490
47495
  this.status = init.status;
47491
47496
  this.retryable = init.retryable ?? false;
47492
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
+ });
47493
47517
  }
47494
47518
  };
47495
47519
  function kindForStatus(status2) {
@@ -47540,7 +47564,7 @@ function extractAclResources(status2, bodyText) {
47540
47564
  }
47541
47565
  return void 0;
47542
47566
  }
47543
- function classifyFailure(status2, bodyText) {
47567
+ function classifyFailure(status2, bodyText, retryAfterMs2) {
47544
47568
  const kind = kindForStatus(status2);
47545
47569
  const template = extractTemplate(bodyText);
47546
47570
  const resources = extractAclResources(status2, bodyText);
@@ -47551,7 +47575,9 @@ function classifyFailure(status2, bodyText) {
47551
47575
  message,
47552
47576
  status: status2,
47553
47577
  retryable: RETRYABLE_STATUSES.has(status2),
47554
- ...remedy !== void 0 ? { remedy } : {}
47578
+ ...remedy !== void 0 ? { remedy } : {},
47579
+ ...resources !== void 0 ? { resources } : {},
47580
+ ...retryAfterMs2 !== void 0 ? { retryAfterMs: retryAfterMs2 } : {}
47555
47581
  });
47556
47582
  }
47557
47583
 
@@ -47682,7 +47708,7 @@ function createRestTransport(deps) {
47682
47708
  headers["Content-Type"] = "application/json";
47683
47709
  }
47684
47710
  let response;
47685
- let text3;
47711
+ let text4;
47686
47712
  try {
47687
47713
  response = await deps.fetch(`${root}${request.path}${request.query !== void 0 && request.query !== "" ? `?${request.query}` : ""}`, {
47688
47714
  method: request.method,
@@ -47693,7 +47719,7 @@ function createRestTransport(deps) {
47693
47719
  signal: request.signal !== void 0 ? AbortSignal.any([request.signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs),
47694
47720
  ...hasBody ? { body: JSON.stringify(request.body) } : {}
47695
47721
  });
47696
- text3 = await response.text();
47722
+ text4 = await response.text();
47697
47723
  } catch (cause) {
47698
47724
  if (request.signal?.aborted === true) {
47699
47725
  return { failure: cancelled(cause) };
@@ -47704,19 +47730,20 @@ function createRestTransport(deps) {
47704
47730
  kind: "transport",
47705
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.",
47706
47732
  retryable: true,
47733
+ ...timedOut ? { timedOut: true } : {},
47707
47734
  cause
47708
47735
  })
47709
47736
  };
47710
47737
  }
47711
47738
  if (!response.ok) {
47712
47739
  const after = retryAfterMs(response);
47713
- return { failure: classifyFailure(response.status, text3), ...after !== void 0 ? { retryAfterMs: after } : {} };
47740
+ return { failure: classifyFailure(response.status, text4, after), ...after !== void 0 ? { retryAfterMs: after } : {} };
47714
47741
  }
47715
- if (text3 === "") {
47742
+ if (text4 === "") {
47716
47743
  return { value: void 0 };
47717
47744
  }
47718
47745
  try {
47719
- return { value: JSON.parse(text3) };
47746
+ return { value: JSON.parse(text4) };
47720
47747
  } catch {
47721
47748
  return {
47722
47749
  failure: new MagentoRestError({ kind: "unparseable", message: "Magento REST returned a success status with a body that is not JSON.", status: response.status })
@@ -47754,7 +47781,7 @@ function createRestTransport(deps) {
47754
47781
  random
47755
47782
  );
47756
47783
  if (!decision.retry) {
47757
- throw outcome.failure;
47784
+ throw outcome.failure.status !== void 0 ? outcome.failure.withAnswer(answerFor(request, root)) : outcome.failure;
47758
47785
  }
47759
47786
  await deps.sleep(decision.delayMs);
47760
47787
  }
@@ -47831,14 +47858,14 @@ function buildSearchCriteria(input2) {
47831
47858
 
47832
47859
  // src/client/paths.ts
47833
47860
  function encodeSegment(value) {
47834
- const text3 = String(value);
47835
- if (text3 === "") {
47861
+ const text4 = String(value);
47862
+ if (text4 === "") {
47836
47863
  throw new Error("restPath: an empty path segment is not allowed");
47837
47864
  }
47838
- if (/^\.+$/.test(text3)) {
47839
- return text3.replaceAll(".", "%2E");
47865
+ if (/^\.+$/.test(text4)) {
47866
+ return text4.replaceAll(".", "%2E");
47840
47867
  }
47841
- return encodeURIComponent(text3);
47868
+ return encodeURIComponent(text4);
47842
47869
  }
47843
47870
  function restPath(strings, ...values) {
47844
47871
  let out = strings[0] ?? "";
@@ -47886,15 +47913,15 @@ var NAMES = {
47886
47913
  };
47887
47914
  var MAX_INPUT_LENGTH = 64;
47888
47915
  function normalizeCountry(input2) {
47889
- const text3 = input2.trim().toLowerCase();
47890
- 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) {
47891
47918
  return void 0;
47892
47919
  }
47893
- const named = NAMES[text3];
47894
- if (named !== void 0 && Object.hasOwn(NAMES, text3)) {
47920
+ const named = NAMES[text4];
47921
+ if (named !== void 0 && Object.hasOwn(NAMES, text4)) {
47895
47922
  return named;
47896
47923
  }
47897
- return /^[a-z]{2}$/.test(text3) ? text3.toUpperCase() : void 0;
47924
+ return /^[a-z]{2}$/.test(text4) ? text4.toUpperCase() : void 0;
47898
47925
  }
47899
47926
 
47900
47927
  // src/client/date-range.ts
@@ -47912,8 +47939,8 @@ function formatMagentoTimestamp(date5) {
47912
47939
  function formatDay(date5) {
47913
47940
  return date5.toISOString().slice(0, 10);
47914
47941
  }
47915
- function parseDay(text3) {
47916
- const match = DAY_PATTERN.exec(text3);
47942
+ function parseDay(text4) {
47943
+ const match = DAY_PATTERN.exec(text4);
47917
47944
  if (match === null) {
47918
47945
  return void 0;
47919
47946
  }
@@ -49515,8 +49542,30 @@ function createToolFactory(getClient, options = {}) {
49515
49542
  });
49516
49543
  return { ...tool, access };
49517
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);
49562
+ }
49563
+ });
49564
+ return { ...tool, access };
49565
+ }
49518
49566
  return {
49519
49567
  shapes,
49568
+ shapedTool: (spec) => buildShaped(spec),
49520
49569
  readTool: (spec) => build(spec, READ_ONLY_ANNOTATIONS, "read"),
49521
49570
  writeTool: (spec) => build(spec, WRITE_ANNOTATIONS[spec.effect], "write")
49522
49571
  };
@@ -49744,10 +49793,10 @@ function readPaths(resource, key, value, validate2) {
49744
49793
  }
49745
49794
  return paths;
49746
49795
  }
49747
- function parseFieldConfig(text3) {
49796
+ function parseFieldConfig(text4) {
49748
49797
  let parsed;
49749
49798
  try {
49750
- parsed = JSON.parse(text3);
49799
+ parsed = JSON.parse(text4);
49751
49800
  } catch (cause) {
49752
49801
  throw new FieldConfigError(`field configuration is not valid JSON: ${cause instanceof Error ? cause.message : "parse failure"}`);
49753
49802
  }
@@ -49852,6 +49901,216 @@ function applyFieldConfig(base, config2) {
49852
49901
  return changed2;
49853
49902
  }
49854
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
+
49855
50114
  // src/tools/products-tools.ts
49856
50115
  var IDENTITY_ATTRIBUTES = /* @__PURE__ */ new Set(["sku", "id", "entity_id", "type_id"]);
49857
50116
  var primitiveValue = external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()]);
@@ -50221,11 +50480,11 @@ var LIST_PAGE_SIZE7 = 20;
50221
50480
  var statusCode = (what) => external_exports.string().regex(/^[a-z0-9_]{1,32}$/, "lowercase letters, digits and underscores only").describe(what);
50222
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.");
50223
50482
  var orderId = entityId("order (entity ID, not the order number)");
50224
- function isRecord3(value) {
50483
+ function isRecord4(value) {
50225
50484
  return value !== null && typeof value === "object" && !Array.isArray(value);
50226
50485
  }
50227
50486
  function arrayField(record2, key) {
50228
- if (isRecord3(record2)) {
50487
+ if (isRecord4(record2)) {
50229
50488
  const value = record2[key];
50230
50489
  return Array.isArray(value) ? value : [];
50231
50490
  }
@@ -50650,7 +50909,7 @@ function taxTools({ readTool, shapes }) {
50650
50909
 
50651
50910
  // src/tools/index.ts
50652
50911
  var GROUPS = {
50653
- products: productTools,
50912
+ products: (factory) => [...productTools(factory), ...productContentTools(factory)],
50654
50913
  store: storeTools,
50655
50914
  categories: categoryTools,
50656
50915
  customers: customerTools,
@@ -50797,22 +51056,22 @@ function readDatabaseSettingsFromEnv() {
50797
51056
  }
50798
51057
  return { target: parseDatabaseConnection(connection), writesEnabled: writes2 };
50799
51058
  }
50800
- function errorResult(text3) {
50801
- 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) } };
50802
51061
  }
50803
51062
  function toErrorResult(error61) {
50804
51063
  if (error61 instanceof MagentoRestError) {
50805
51064
  return errorResult(error61.remedy !== void 0 ? `${error61.message}
50806
- Remedy: ${error61.remedy}` : error61.message);
51065
+ Remedy: ${error61.remedy}` : error61.message, error61);
50807
51066
  }
50808
- if (error61 instanceof SqlGuardError || error61 instanceof DatabaseError || error61 instanceof DatabaseConfigError) {
50809
- 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);
50810
51069
  }
50811
51070
  if (error61 instanceof ZodError) {
50812
51071
  const issues = error61.issues.map((issue2) => `${issue2.path.length > 0 ? issue2.path.join(".") : "(root)"}: ${issue2.message}`);
50813
- return errorResult(`Invalid arguments: ${issues.join("; ")}`);
51072
+ return errorResult(`Invalid arguments: ${issues.join("; ")}`, error61);
50814
51073
  }
50815
- 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);
50816
51075
  }
50817
51076
  var MAX_FIELDS_FILE_BYTES = 64 * 1024;
50818
51077
  function readFieldConfigFromEnv() {
@@ -50820,12 +51079,12 @@ function readFieldConfigFromEnv() {
50820
51079
  if (path === void 0 || path === "") {
50821
51080
  return {};
50822
51081
  }
50823
- let text3;
51082
+ let text4;
50824
51083
  try {
50825
51084
  if (statSync2(path).size > MAX_FIELDS_FILE_BYTES) {
50826
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`);
50827
51086
  }
50828
- text3 = readFileSync2(path, "utf8");
51087
+ text4 = readFileSync2(path, "utf8");
50829
51088
  } catch (error61) {
50830
51089
  if (error61 instanceof FieldConfigError) {
50831
51090
  throw error61;
@@ -50833,7 +51092,7 @@ function readFieldConfigFromEnv() {
50833
51092
  throw new FieldConfigError(`${FIELDS_FILE_ENV_VAR}: cannot read ${path}: ${error61 instanceof Error ? error61.message : "unknown failure"}`);
50834
51093
  }
50835
51094
  try {
50836
- const config2 = parseFieldConfig(text3);
51095
+ const config2 = parseFieldConfig(text4);
50837
51096
  applyFieldConfig(BASE_SHAPES, config2);
50838
51097
  return config2;
50839
51098
  } catch (error61) {
@@ -50904,10 +51163,13 @@ function buildServer() {
50904
51163
  async (args, extra) => {
50905
51164
  try {
50906
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
+ }
50907
51169
  return { content: [...result.content], ...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : {}, isError: result.isError };
50908
51170
  } catch (error61) {
50909
51171
  const rendered = toErrorResult(error61);
50910
- return { content: [...rendered.content], isError: rendered.isError };
51172
+ return { content: [...rendered.content], structuredContent: rendered.structuredContent, isError: rendered.isError };
50911
51173
  }
50912
51174
  }
50913
51175
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hiberus-magento/magento-rest",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "MCP server and CLI for the Magento 2 REST API — catalog, orders, customers, stock and content reads, with opt-in write tools.",
5
5
  "mcpName": "io.github.hiberus-magento/magento-rest",
6
6
  "keywords": [
@@ -34,7 +34,8 @@
34
34
  },
35
35
  "bin": {
36
36
  "hiberus-magento-rest": "dist/cli.js",
37
- "hiberus-magento-rest-mcp": "dist/mcp.js"
37
+ "hiberus-magento-rest-mcp": "dist/mcp.js",
38
+ "magento-rest": "dist/mcp.js"
38
39
  },
39
40
  "files": [
40
41
  "dist",
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "io.github.hiberus-magento/magento-rest",
4
4
  "title": "Magento 2 / Adobe Commerce (REST)",
5
5
  "description": "Read and act on a Magento 2 / Adobe Commerce store through its REST API.",
6
- "version": "0.2.0",
6
+ "version": "0.3.0",
7
7
  "repository": {
8
8
  "url": "https://github.com/hiberus-magento/mcp-servers",
9
9
  "source": "github",
@@ -13,7 +13,7 @@
13
13
  {
14
14
  "registryType": "npm",
15
15
  "identifier": "@hiberus-magento/magento-rest",
16
- "version": "0.2.0",
16
+ "version": "0.3.0",
17
17
  "transport": {
18
18
  "type": "stdio"
19
19
  },