@wix/mcp 1.0.81 → 1.0.83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +3 -1
  2. package/build/bin-standalone.js +847 -4
  3. package/build/cjs/index.cjs +900 -20
  4. package/build/cjs/toolkit.cjs +844 -4
  5. package/build/dts/bin.d.ts +1 -1
  6. package/build/dts/bin.js +13 -1
  7. package/build/dts/config/default-config.d.ts +1 -0
  8. package/build/dts/config/default-config.js +33 -2
  9. package/build/dts/config/param-descriptions.d.ts +21 -0
  10. package/build/dts/config/param-descriptions.js +21 -0
  11. package/build/dts/graphql/constants.d.ts +8 -0
  12. package/build/dts/graphql/constants.js +11 -0
  13. package/build/dts/graphql/index.d.ts +30 -0
  14. package/build/dts/graphql/index.js +259 -0
  15. package/build/dts/graphql/introspection.d.ts +106 -0
  16. package/build/dts/graphql/introspection.js +282 -0
  17. package/build/dts/graphql/search.d.ts +25 -0
  18. package/build/dts/graphql/search.js +277 -0
  19. package/build/dts/import-claude-design-tool/index.js +2 -2
  20. package/build/dts/index.d.ts +2 -1
  21. package/build/dts/index.js +3 -1
  22. package/build/dts/site-widget-tools/constants.d.ts +12 -5
  23. package/build/dts/site-widget-tools/constants.js +20 -11
  24. package/build/dts/site-widget-tools/site-builder-tool/index.js +1 -1
  25. package/build/dts/site-widget-tools/site-creation-tool/index.js +3 -2
  26. package/build/dts/site-widget-tools/suggested-domain-tool/index.js +25 -5
  27. package/build/dts/toolkit-entry.d.cts +12 -0
  28. package/build/dts/toolkit-entry.d.ts +12 -0
  29. package/build/dts/toolkit-entry.js +4 -0
  30. package/build/dts/toolkit.js +14 -0
  31. package/build/dts/wix-mcp-server.d.ts +2 -0
  32. package/build/dts/wix-mcp-server.js +5 -0
  33. package/build/esm/index.js +892 -20
  34. package/build/esm/toolkit.js +839 -4
  35. package/package.json +2 -2
@@ -12177,6 +12177,8 @@ var SITE_CREATION_COPY = {
12177
12177
  var SITE_GUIDANCE = dedent_default`
12178
12178
  A new-site request has two things to settle: what the site is for, and how to build it. The how is AI generation vs. starting from a template, so naming templates, a template id or Wix Studio (Wix Studio is also the template side) already settles it.
12179
12179
 
12180
+ One case skips all of this: the user ALREADY HAS the finished site as files — hand-written HTML/CSS/JS, a zip, or the export of an AI builder. There is nothing to build, so don't offer AI or templates and don't call any site-creation tool. Send them to https://www.wix.com/headless/drop?utm_campaign=mcp — they drag the files in and get a live Wix-hosted site. Give that URL exactly as written, keeping the utm_campaign=mcp parameter.
12181
+
12180
12182
  Settle what the site is for first: its purpose, topic, business type, audience, or main visitor action. Naming a method is not a description of the site, and neither is the business or industry on its own.
12181
12183
  If you can't tell yet, ask the preferred question below and nothing else — one question, no creation-method question in the same reply, and no internal tool names.
12182
12184
  Once the purpose is clear, unless the user already named a method, ${SITE_CREATION_COPY.unstatedMethod.nonWidget}. A method they named is settled — never re-open it. Never default to AI or to templates, and never ask the user to choose between Harmony and Wix Studio; infer that from their words.
@@ -12509,7 +12511,8 @@ function buildToolDescriptions(includeReadme, includeImageUploadGuidance = true)
12509
12511
  After calling, you MUST speak the message provided in the tool result to the user as your reply — do not stay silent and do not replace it with a one-line pointer to the widget. Write out ALL of it, word for word: its opening line (the "Ready to set up your … site?" question INCLUDING "Choose your path in the widget above:"), BOTH of its option bullets, and its "Next up:" line, each on its own line and in that order. Do not summarize, shorten, drop any line, invent your own opener, rename the options, or add an intro or outro.
12510
12512
  `,
12511
12513
  "import-claude-design-from-url": dedent_default`
12512
- Import a design into Wix from a publicly fetchable URL. The file is a self-contained HTML bundle with all images, fonts, and styles inlined. Creates a live Wix-hosted site and returns its URL.
12514
+ Import a design created in Claude's design tool into Wix. Takes the signed claudeusercontent.com URL Claude Design produces for its self-contained HTML bundle (all images, fonts, and styles inlined); any other host is rejected. Creates a live Wix-hosted site and returns its URL.
12515
+ NOT for site files the user provides themselves (their own HTML/CSS/JS, a zip, another builder's export) — for those, don't call this tool: send the user to https://www.wix.com/headless/drop?utm_campaign=mcp, where they upload the files and get a live hosted site. Give that URL exactly as written, keeping the utm_campaign=mcp parameter.
12513
12516
  `,
12514
12517
  RunWixCliCommand: dedent_default`
12515
12518
  Executes Wix CLI commands for Wix app development and management.
@@ -12906,10 +12909,37 @@ function buildToolDescriptions(includeReadme, includeImageUploadGuidance = true)
12906
12909
 
12907
12910
  Call this when the user provides a specific template by \`metaSiteId\` or \`templateId\`. Use this only when the user gives a valid \`metaSiteId\` or \`templateId\` directly. To browse or choose a template first, call \`SearchSiteTemplates\`.
12908
12911
 
12912
+ `,
12913
+ SearchWixGraphQLOperations: dedent_default`
12914
+ Discover Wix GraphQL operations by intent (ranked keyword search over the root fields). Wix exposes ONE GraphQL schema over all Wix public APIs (Developer Preview) at POST https://www.wixapis.com/graphql/alpha: about 100 query roots and 580 mutation roots named <app><Service><Version><Verb/Entity>, e.g. \`storesProductsV3V3Products\`, \`crmContactsV4Contacts\`, \`crmContactsV4CreateContact\`, \`ecomOrdersV1SearchOrders\`.
12915
+
12916
+ GraphQL flow (3 steps, keep to it): SearchWixGraphQLOperations (find the operation) -> InspectWixGraphQLSchema (read its exact input and return types) -> ExecuteWixGraphQL (run it). Never write an operation or field name you did not see in one of these results.
12917
+
12918
+ When to prefer GraphQL over the REST tools:
12919
+ - Reading several related entities in ONE round-trip: related entities are resolved fields (product -> inventoryItems / collections, order -> fulfillments, booking -> contact), and independent root fields (products + contacts + orders) can share one request.
12920
+ - Picking exactly the fields you need, so responses stay small.
12921
+ - Answering "how many / list / show" questions: a query root plus \`pageInfo\` (\`hasNext\`, and \`total\` where the API provides it).
12922
+ Prefer the REST tools when a recipe or code example already gives you the exact REST call, for uploads/media, or when the GraphQL schema has no matching operation.
12923
+
12924
+ Conventions: query roots take \`queryInput\`; list roots (plural names) take \`queryInput: { query: { paging | cursorPaging, filter, sort } }\` and return \`{ items, pageInfo }\`; singular roots take the entity id. \`filter\`/\`sort\` are a JSON scalar in REST filter syntax (e.g. {"info.name.first": {"$eq": "Ada"}}) — pass them as variables. Mutations take \`input\`; a few read operations (search/list) are exposed as mutations, so search kind "all" unless you are sure.
12925
+ Results list \`kind name(arg: InputType): ReturnType\` plus a one-line description; pass the chosen name to InspectWixGraphQLSchema next.
12926
+ `,
12927
+ InspectWixGraphQLSchema: dedent_default`
12928
+ Read the exact Wix GraphQL schema for an operation and its types, as compact SDL with field descriptions. Pass \`operation\` (a root query/mutation name from SearchWixGraphQLOperations) to get its arguments, input type and return type expanded \`depth\` levels (default 2). Types that were referenced but not expanded are listed at the end — pass the ones you need in \`typeNames\` (optionally together with \`operation\`) instead of raising depth for everything.
12929
+ Use it before every ExecuteWixGraphQL call that introduces a new operation or new fields: read the INPUT type before writing a mutation or filter, and the RETURN type before writing the selection set. GraphQL rejects unknown fields and arguments, and every object-typed field needs its own selection set. \`JSON\` scalar fields (filter, sort, free-form data) accept any JSON — pass them as variables. Never guess a type or field name; if a validation error names a field, come back here.
12930
+ `,
12931
+ ExecuteWixGraphQL: dedent_default`
12932
+ Execute a GraphQL query or mutation against the Wix GraphQL API (POST https://www.wixapis.com/graphql/alpha) with the user's credentials. Authentication is injected — never add Authorization or site/account headers.
12933
+ Site targeting: site-level operations (anything that reads or writes inside a site: products, inventory, orders, contacts, bookings, CMS data, blog, members ...) require \`siteId\`; resolve it with GetSiteContext or ListWixSites first. Use \`scope: "account"\` only for account-level operations.
12934
+ Grounding: every root field, argument and selected field must come from SearchWixGraphQLOperations / InspectWixGraphQLSchema results in this conversation — never from memory. If the response says "Cannot query field" or "Unknown argument", re-inspect the schema and fix the name; do not retry with another guess.
12935
+ Compose: put independent reads in one document as several root fields, and use related-entity fields (e.g. \`inventoryItems\`, \`collections\`, \`fulfillments\`) instead of extra round-trips. Select only the fields you need; every object field needs a selection set. Variables: use them for \`JSON\` scalars (filter, sort) and plain scalars (String, Int, ID), declared in the document (e.g. \`query Q($f: JSON) { ... filter: $f ... }\`). Write mutation inputs and any object that contains an enum INLINE as GraphQL literals with enum values unquoted (e.g. \`input: { product: { name: "Mug", productType: PHYSICAL } }\`) — this endpoint fails with 503 when an enum value arrives inside an object-typed variable. For lists page with \`cursorPaging\` or \`paging\` exactly as the input type declares (never the other one), and request \`pageInfo { hasNext total }\`; \`total\` is only populated with offset \`paging\`, so for a cursor-paged list count by walking pages or use a count operation.
12936
+ Results: each root field fails independently — \`errors[].path\` names the failing field and \`errors[].extensions.message\` the cause (e.g. PERMISSION_DENIED); \`data\` still holds the fields that succeeded. Mutations return the created/updated entity — read the IDs from it and do not re-query to verify. Large results are truncated: narrow the selection or page size instead of re-running.
12937
+ Set \`hasMutations: true\` for any document containing a mutation root field.
12909
12938
  `,
12910
12939
  CreateWixBusinessGuide: dedent_default`
12911
12940
  Provides comprehensive documentation for creating a new Wix business (site, app, etc.).
12912
12941
  Call this ONLY when the user explicitly asks for a headless site, a Wix Classic Editor site, or manual/advanced account/API-based site creation — these don't need the site's purpose first. For normal site-creation ${SITE_CREATION_COPY.normalCreationRoute.nonWidget}; for a specific template id, call \`CreateSiteFromTemplate\`.
12942
+ Exception, even when the user says "headless": if they ALREADY HAVE the finished site as files (their own HTML/CSS/JS, a zip, an AI-builder export) and want those files hosted, don't call this tool — send them to https://www.wix.com/headless/drop?utm_campaign=mcp to upload the files and get a live hosted site (give that URL exactly, keeping the utm_campaign=mcp parameter). This guide's CLI flow is for BUILDING a headless frontend, not for hosting ready-made files.
12913
12943
 
12914
12944
  ## What This Tool Contains
12915
12945
 
@@ -13024,7 +13054,8 @@ function mergeConfig(base, overrides) {
13024
13054
  dynamicContextEnabled: overrides.dynamicContextEnabled ?? base.dynamicContextEnabled,
13025
13055
  partnerContextEnabled: overrides.partnerContextEnabled ?? base.partnerContextEnabled,
13026
13056
  usePlatformizedSearch: overrides.usePlatformizedSearch ?? base.usePlatformizedSearch,
13027
- skillsPrOverrideEnabled: overrides.skillsPrOverrideEnabled ?? base.skillsPrOverrideEnabled
13057
+ skillsPrOverrideEnabled: overrides.skillsPrOverrideEnabled ?? base.skillsPrOverrideEnabled,
13058
+ graphqlEnabled: overrides.graphqlEnabled ?? base.graphqlEnabled
13028
13059
  };
13029
13060
  }
13030
13061
  var defaultConfig = {
@@ -13375,7 +13406,16 @@ var known_apps_default = {
13375
13406
  "1480c568-5cbd-9392-5604-1148f5faffa0": "Promote SEO",
13376
13407
  "ff5d6eb1-65e4-4f9a-8b14-64d34c12cc2e": "Wix Rentals"
13377
13408
  };
13378
- var DYNAMIC_CONTEXT_URL = "https://dev.wix.com/_api/dynamic-context/v1/dynamic-context";
13409
+ var DYNAMIC_CONTEXT_PATH = "/_api/dynamic-context/v1/dynamic-context";
13410
+ var DYNAMIC_CONTEXT_URL = `https://dev.wix.com${DYNAMIC_CONTEXT_PATH}`;
13411
+ var isWixHost = (hostname) => hostname === "wix.com" || hostname.endsWith(".wix.com");
13412
+ var dynamicContextUrl = () => {
13413
+ if (typeof window === "undefined") {
13414
+ return DYNAMIC_CONTEXT_URL;
13415
+ }
13416
+ const hostname = window.location?.hostname;
13417
+ return typeof hostname === "string" && isWixHost(hostname) ? DYNAMIC_CONTEXT_PATH : DYNAMIC_CONTEXT_URL;
13418
+ };
13379
13419
  var COUNT_SITES_URL = "https://www.wixapis.com/site-list/v2/sites/count";
13380
13420
  var MAX_SITES_FOR_DYNAMIC_CONTEXT = 10;
13381
13421
  var DYNAMIC_CONTEXT_PETRI_OVERRIDE = "shouldReturnDynamicContextInMCP#B";
@@ -13427,7 +13467,7 @@ async function getDynamicContext(auth, httpClient, filter, options) {
13427
13467
  if (filter?.siteId) body.site_id = filter.siteId;
13428
13468
  else if (filter?.siteName) body.site_name = filter.siteName;
13429
13469
  const dynamicContextPromise = httpClient.request({
13430
- url: DYNAMIC_CONTEXT_URL,
13470
+ url: dynamicContextUrl(),
13431
13471
  method: "POST",
13432
13472
  headers: {
13433
13473
  ...accountHeaders,
@@ -13621,6 +13661,27 @@ var paramDescriptions = {
13621
13661
  mimeType: 'MIME type of the image (e.g. "image/jpeg", "image/png", "image/webp"). Required when imageBase64 does not include a data URL prefix.',
13622
13662
  displayName: "Optional display name for the file in Media Manager. If not provided, uses the original filename."
13623
13663
  },
13664
+ SearchWixGraphQLOperations: {
13665
+ query: 'Free-text intent or entity, e.g. "products with inventory", "create contact", "orders", "blog posts", "booking services". Operation names encode app + service + version + verb/entity (e.g. storesProductsV3V3Products, crmContactsV4CreateContact), so a noun plus a verb (query/get/create/update/delete) ranks best. You may also pass an exact operation name.',
13666
+ kind: 'Restrict to "query" (reads), "mutation" (writes \u2014 note a few reads such as search/list calls are exposed as mutations), or "all" (default).',
13667
+ maxResults: "Maximum number of operations to return (default 10, max 50).",
13668
+ reason: "One sentence describing the original user request and why you are looking for a GraphQL operation."
13669
+ },
13670
+ InspectWixGraphQLSchema: {
13671
+ operation: 'Exact root query or mutation name from SearchWixGraphQLOperations (e.g. "crmContactsV4Contacts"). Returns its arguments, input type and return type as compact SDL, expanded `depth` levels.',
13672
+ typeNames: 'Type names to expand, e.g. ones listed as "Not expanded" in a previous result, or a nested input/object/enum type you need before writing the request. Can be combined with `operation`.',
13673
+ depth: "How many levels of referenced types to expand (1-4, default 2). Level 1 is the given types, level 2 the types their fields reference, and so on. Keep it small and expand specific types with typeNames instead of dumping everything.",
13674
+ reason: "One sentence describing the original user request and why you need this part of the GraphQL schema."
13675
+ },
13676
+ ExecuteWixGraphQL: {
13677
+ query: "The GraphQL document (a query or a mutation). Every root field, argument and selected field MUST come from SearchWixGraphQLOperations / InspectWixGraphQLSchema results in this conversation, never from memory. Declare variables for filters, sort and large inputs, e.g. `query Q($f: JSON) { crmContactsV4Contacts(queryInput: { query: { filter: $f, paging: { limit: 50 } } }) { items { id } pageInfo { hasNext } } }`. Object-typed fields need a selection set. You can put several independent root fields in one document.",
13678
+ variables: 'Variables object for the document, as a JSON object (not a string). Use it for JSON-scalar filters/sort (REST filter syntax, e.g. {"info.name.first": {"$eq": "Ada"}}) and plain scalars. Do NOT pass object inputs that contain enum values (product types, statuses, registration types ...) through variables \u2014 write those inline in the document with the enum unquoted; the endpoint returns 503 otherwise.',
13679
+ operationName: "Operation to run when the document defines more than one named operation.",
13680
+ siteId: "The Wix site to run against. Required for site-level operations (anything reading or writing inside a site \u2014 products, orders, contacts, bookings, CMS, blog, members ...). Resolve it with GetSiteContext or ListWixSites; never pass a guessed value.",
13681
+ scope: '"site" (default when siteId is given) runs with a site-scoped credential; "account" runs account-level operations (sites, account settings) and ignores siteId.',
13682
+ hasMutations: "Whether this document creates, updates, deletes or otherwise mutates Wix data. True for any mutation root field (in any operation of the document) even when the intent is inspection; false only for pure queries. This flag alone decides whether a transient server error may be retried, so never mark a document that writes as false.",
13683
+ reason: "One sentence explaining the original user request and why you are running this GraphQL operation to complete it."
13684
+ },
13624
13685
  RunWixCliCommand: {
13625
13686
  appPath: "The full path to the Wix CLI app to run the command on.",
13626
13687
  extensionType: "The type of extension to generate. You MUST provide this for commands that generate extensions.",
@@ -15607,6 +15668,761 @@ function truncateResponse(content, maxChars = DEFAULT_MAX_CHARS) {
15607
15668
  Response was ~${estimatedTokens.toLocaleString()} tokens (limit: ${limitTokens.toLocaleString()}). Refine your code to return less data.`;
15608
15669
  }
15609
15670
 
15671
+ // src/graphql/constants.ts
15672
+ var WIX_GRAPHQL_ENDPOINT = "https://www.wixapis.com/graphql/alpha";
15673
+ var SEARCH_GRAPHQL_TOOL_NAME = "SearchWixGraphQLOperations";
15674
+ var INSPECT_GRAPHQL_TOOL_NAME = "InspectWixGraphQLSchema";
15675
+ var EXECUTE_GRAPHQL_TOOL_NAME = "ExecuteWixGraphQL";
15676
+ var GRAPHQL_TOOL_NAMES = [
15677
+ SEARCH_GRAPHQL_TOOL_NAME,
15678
+ INSPECT_GRAPHQL_TOOL_NAME,
15679
+ EXECUTE_GRAPHQL_TOOL_NAME
15680
+ ];
15681
+
15682
+ // src/graphql/introspection.ts
15683
+ var TYPE_REF_FRAGMENT = `
15684
+ fragment TR on __Type { kind name ofType { kind name ofType { kind name ofType { kind name } } } }`;
15685
+ var ROOT_OPERATIONS_QUERY = `{
15686
+ __schema {
15687
+ queryType { fields { name description args { name type { ...TR } } type { ...TR } } }
15688
+ mutationType { fields { name description args { name type { ...TR } } type { ...TR } } }
15689
+ }
15690
+ }${TYPE_REF_FRAGMENT}`;
15691
+ var TYPE_DETAILS_FRAGMENT = `
15692
+ fragment TD on __Type {
15693
+ kind name description
15694
+ fields { name description type { ...TR } args { name type { ...TR } } }
15695
+ inputFields { name description type { ...TR } defaultValue }
15696
+ enumValues { name description }
15697
+ possibleTypes { name }
15698
+ }`;
15699
+ var ROOT_CACHE_TTL_MS = 6 * 60 * 60 * 1e3;
15700
+ var rootCache;
15701
+ var typeCache = /* @__PURE__ */ new Map();
15702
+ var RETRY_DELAYS_MS = [800, 2e3, 4e3];
15703
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
15704
+ async function fetchWithRetry(fetchImpl, url, init, delays = RETRY_DELAYS_MS) {
15705
+ let attempt = 0;
15706
+ for (; ; ) {
15707
+ const resp = await fetchImpl(url, init);
15708
+ if (resp.status < 500 || attempt >= delays.length) return resp;
15709
+ await sleep(delays[attempt++]);
15710
+ }
15711
+ }
15712
+ async function postIntrospection(query, options) {
15713
+ const fetchImpl = options.fetchImpl ?? fetch;
15714
+ const endpoint = options.endpoint ?? WIX_GRAPHQL_ENDPOINT;
15715
+ const resp = await fetchWithRetry(
15716
+ fetchImpl,
15717
+ endpoint,
15718
+ {
15719
+ method: "POST",
15720
+ headers: {
15721
+ "Content-Type": "application/json",
15722
+ Accept: "application/json"
15723
+ },
15724
+ body: JSON.stringify({ query })
15725
+ },
15726
+ options.retryDelaysMs
15727
+ );
15728
+ const text = await resp.text();
15729
+ if (!resp.ok) {
15730
+ const body = /^\s*<(!doctype|html)/i.test(text) ? "(HTML error page \u2014 the endpoint is temporarily unavailable; try again in a moment)" : text.slice(0, 500);
15731
+ throw new Error(
15732
+ `GraphQL introspection failed (${resp.status} ${resp.statusText}): ${body}`
15733
+ );
15734
+ }
15735
+ const json = JSON.parse(text);
15736
+ if (json.errors?.length && !json.data) {
15737
+ throw new Error(
15738
+ `GraphQL introspection returned errors: ${JSON.stringify(json.errors).slice(0, 500)}`
15739
+ );
15740
+ }
15741
+ return json.data;
15742
+ }
15743
+ function getRootOperations(options = {}) {
15744
+ const now = Date.now();
15745
+ if (rootCache && now - rootCache.fetchedAt < ROOT_CACHE_TTL_MS) {
15746
+ return rootCache.promise;
15747
+ }
15748
+ const promise = postIntrospection(ROOT_OPERATIONS_QUERY, options).then(
15749
+ (data) => {
15750
+ const toOps = (fields, kind) => (fields ?? []).map((f) => ({
15751
+ kind,
15752
+ name: f.name,
15753
+ description: f.description ?? "",
15754
+ args: f.args ?? [],
15755
+ type: f.type
15756
+ }));
15757
+ return [
15758
+ ...toOps(data?.__schema?.queryType?.fields, "query"),
15759
+ ...toOps(data?.__schema?.mutationType?.fields, "mutation")
15760
+ ];
15761
+ }
15762
+ );
15763
+ promise.catch(() => {
15764
+ if (rootCache?.promise === promise) rootCache = void 0;
15765
+ });
15766
+ rootCache = { promise, fetchedAt: now };
15767
+ return promise;
15768
+ }
15769
+ var GRAPHQL_NAME = /^[_A-Za-z][_0-9A-Za-z]*$/;
15770
+ var TYPE_BATCH_SIZE = 10;
15771
+ async function getTypes(names, options = {}) {
15772
+ const unique = [...new Set(names)].filter((n) => GRAPHQL_NAME.test(n));
15773
+ const missing = unique.filter((n) => !typeCache.has(n));
15774
+ for (let start = 0; start < missing.length; start += TYPE_BATCH_SIZE) {
15775
+ const chunk = missing.slice(start, start + TYPE_BATCH_SIZE);
15776
+ const selections = chunk.map((n, i) => `t${i}: __type(name: "${n}") { ...TD }`).join("\n");
15777
+ const query = `{
15778
+ ${selections}
15779
+ }${TYPE_DETAILS_FRAGMENT}${TYPE_REF_FRAGMENT}`;
15780
+ const batch = postIntrospection(query, options);
15781
+ chunk.forEach((n, i) => {
15782
+ const p = batch.then(
15783
+ (data) => data?.[`t${i}`] ?? null
15784
+ );
15785
+ p.catch(() => {
15786
+ if (typeCache.get(n) === p) typeCache.delete(n);
15787
+ });
15788
+ typeCache.set(n, p);
15789
+ });
15790
+ await batch.catch(() => void 0);
15791
+ }
15792
+ const result = /* @__PURE__ */ new Map();
15793
+ await Promise.all(
15794
+ unique.map(async (n) => {
15795
+ result.set(n, await typeCache.get(n));
15796
+ })
15797
+ );
15798
+ return result;
15799
+ }
15800
+ function renderTypeRef(ref) {
15801
+ if (!ref) return "Unknown";
15802
+ if (ref.kind === "NON_NULL") return `${renderTypeRef(ref.ofType)}!`;
15803
+ if (ref.kind === "LIST") return `[${renderTypeRef(ref.ofType)}]`;
15804
+ return ref.name ?? "Unknown";
15805
+ }
15806
+ function namedType(ref) {
15807
+ let cur = ref;
15808
+ while (cur && (cur.kind === "NON_NULL" || cur.kind === "LIST")) {
15809
+ cur = cur.ofType ?? null;
15810
+ }
15811
+ return cur?.name ?? null;
15812
+ }
15813
+ var BUILTIN_SCALARS = /* @__PURE__ */ new Set([
15814
+ "String",
15815
+ "Int",
15816
+ "Float",
15817
+ "Boolean",
15818
+ "ID",
15819
+ "JSON"
15820
+ ]);
15821
+ function isBuiltinScalar(name) {
15822
+ return !!name && BUILTIN_SCALARS.has(name);
15823
+ }
15824
+ function oneLine(text, max) {
15825
+ if (!text) return "";
15826
+ const flat = text.replace(/\s+/g, " ").trim();
15827
+ return flat.length > max ? `${flat.slice(0, max - 1)}\u2026` : flat;
15828
+ }
15829
+ function renderField(field, isInput) {
15830
+ const args = !isInput && field.args?.length ? `(${field.args.map((a) => `${a.name}: ${renderTypeRef(a.type)}`).join(", ")})` : "";
15831
+ const def = isInput && field.defaultValue != null ? ` = ${field.defaultValue}` : "";
15832
+ const comment = field.description ? ` # ${oneLine(field.description, 140)}` : "";
15833
+ return ` ${field.name}${args}: ${renderTypeRef(field.type)}${def}${comment}`;
15834
+ }
15835
+ function renderType(type) {
15836
+ const references = /* @__PURE__ */ new Set();
15837
+ const collect = (ref) => {
15838
+ const n = namedType(ref);
15839
+ if (n && !isBuiltinScalar(n) && n !== type.name) references.add(n);
15840
+ };
15841
+ const header = type.description ? `# ${oneLine(type.description, 200)}
15842
+ ` : "";
15843
+ let body;
15844
+ switch (type.kind) {
15845
+ case "ENUM":
15846
+ body = `enum ${type.name} {
15847
+ ${(type.enumValues ?? []).map(
15848
+ (v) => ` ${v.name}${v.description ? ` # ${oneLine(v.description, 100)}` : ""}`
15849
+ ).join("\n")}
15850
+ }`;
15851
+ break;
15852
+ case "INPUT_OBJECT":
15853
+ (type.inputFields ?? []).forEach((f) => collect(f.type));
15854
+ body = `input ${type.name} {
15855
+ ${(type.inputFields ?? []).map((f) => renderField(f, true)).join("\n")}
15856
+ }`;
15857
+ break;
15858
+ case "UNION":
15859
+ (type.possibleTypes ?? []).forEach((p) => references.add(p.name));
15860
+ body = `union ${type.name} = ${(type.possibleTypes ?? []).map((p) => p.name).join(" | ")}`;
15861
+ break;
15862
+ case "SCALAR":
15863
+ body = `scalar ${type.name}`;
15864
+ break;
15865
+ default: {
15866
+ (type.fields ?? []).forEach((f) => {
15867
+ collect(f.type);
15868
+ f.args?.forEach((a) => collect(a.type));
15869
+ });
15870
+ const keyword = type.kind === "INTERFACE" ? "interface" : "type";
15871
+ body = `${keyword} ${type.name} {
15872
+ ${(type.fields ?? []).map((f) => renderField(f, false)).join("\n")}
15873
+ }`;
15874
+ }
15875
+ }
15876
+ return { text: header + body, references: [...references] };
15877
+ }
15878
+ function renderOperationSignature(op) {
15879
+ const args = op.args.map((a) => `${a.name}: ${renderTypeRef(a.type)}`).join(", ");
15880
+ return `${op.kind === "query" ? "Query" : "Mutation"}.${op.name}(${args}): ${renderTypeRef(op.type)}`;
15881
+ }
15882
+ async function expandTypes(rootTypeNames, options = {}) {
15883
+ const depth = Math.max(1, Math.min(options.depth ?? 2, 5));
15884
+ const maxTypes = options.maxTypes ?? 40;
15885
+ const rendered = [];
15886
+ const unknown = [];
15887
+ const seen = /* @__PURE__ */ new Set();
15888
+ let frontier = [...new Set(rootTypeNames)].filter((n) => !isBuiltinScalar(n));
15889
+ let level = 1;
15890
+ let overflow = [];
15891
+ while (frontier.length > 0 && level <= depth) {
15892
+ const room = maxTypes - seen.size;
15893
+ if (room <= 0) {
15894
+ overflow = frontier;
15895
+ break;
15896
+ }
15897
+ const batch = frontier.slice(0, room);
15898
+ overflow = frontier.slice(room);
15899
+ batch.forEach((n) => seen.add(n));
15900
+ const types = await getTypes(batch, options);
15901
+ const next = /* @__PURE__ */ new Set();
15902
+ for (const name of batch) {
15903
+ const type = types.get(name);
15904
+ if (!type) {
15905
+ unknown.push(name);
15906
+ continue;
15907
+ }
15908
+ const { text, references } = renderType(type);
15909
+ rendered.push(text);
15910
+ references.forEach((r) => {
15911
+ if (!seen.has(r)) next.add(r);
15912
+ });
15913
+ }
15914
+ frontier = [...next];
15915
+ level++;
15916
+ }
15917
+ const unexpanded = [.../* @__PURE__ */ new Set([...overflow, ...frontier])].filter(
15918
+ (n) => !seen.has(n) && !isBuiltinScalar(n)
15919
+ );
15920
+ return { rendered, unexpanded, unknown };
15921
+ }
15922
+
15923
+ // src/graphql/search.ts
15924
+ function tokenize(text) {
15925
+ return text.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/([a-zA-Z])([0-9])/g, "$1 $2").replace(/([0-9])([a-zA-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length > 0);
15926
+ }
15927
+ var STOP_WORDS = /* @__PURE__ */ new Set([
15928
+ "a",
15929
+ "an",
15930
+ "the",
15931
+ "of",
15932
+ "for",
15933
+ "to",
15934
+ "in",
15935
+ "on",
15936
+ "with",
15937
+ "and",
15938
+ "or",
15939
+ "by",
15940
+ "all",
15941
+ "my",
15942
+ "me",
15943
+ "i",
15944
+ "from",
15945
+ "is",
15946
+ "are",
15947
+ "be",
15948
+ "it",
15949
+ "this",
15950
+ "that",
15951
+ "wix",
15952
+ "api",
15953
+ "graphql"
15954
+ ]);
15955
+ function stem(token) {
15956
+ if (token.length > 4 && token.endsWith("ies"))
15957
+ return `${token.slice(0, -3)}y`;
15958
+ if (token.length > 3 && token.endsWith("es") && !token.endsWith("ses"))
15959
+ return token.slice(0, -1);
15960
+ if (token.length > 3 && token.endsWith("s") && !token.endsWith("ss"))
15961
+ return token.slice(0, -1);
15962
+ return token;
15963
+ }
15964
+ var VERB_SYNONYMS = {
15965
+ list: ["query", "list", "search"],
15966
+ find: ["query", "search", "get"],
15967
+ fetch: ["get", "query"],
15968
+ read: ["get", "query"],
15969
+ show: ["get", "query"],
15970
+ count: ["count", "query"],
15971
+ add: ["create", "add"],
15972
+ new: ["create"],
15973
+ insert: ["create"],
15974
+ edit: ["update"],
15975
+ change: ["update"],
15976
+ modify: ["update"],
15977
+ set: ["update"],
15978
+ remove: ["delete", "remove"],
15979
+ destroy: ["delete"],
15980
+ cancel: ["cancel", "delete"],
15981
+ customer: ["contact", "member"],
15982
+ client: ["contact", "member"],
15983
+ item: ["product", "item"],
15984
+ inventory: ["inventory", "stock"],
15985
+ stock: ["inventory", "stock"],
15986
+ post: ["post", "blog"],
15987
+ article: ["post", "blog"],
15988
+ appointment: ["booking", "session"],
15989
+ collection: ["collection", "category", "data"],
15990
+ cms: ["data", "collection"],
15991
+ store: ["stores", "store"]
15992
+ };
15993
+ function expandQueryTokens(tokens) {
15994
+ const out = /* @__PURE__ */ new Set();
15995
+ for (const raw of tokens) {
15996
+ if (STOP_WORDS.has(raw)) continue;
15997
+ const s = stem(raw);
15998
+ out.add(s);
15999
+ for (const syn of VERB_SYNONYMS[raw] ?? VERB_SYNONYMS[s] ?? []) {
16000
+ out.add(stem(syn));
16001
+ }
16002
+ }
16003
+ return out;
16004
+ }
16005
+ var READ_VERBS = /* @__PURE__ */ new Set([
16006
+ "list",
16007
+ "get",
16008
+ "query",
16009
+ "find",
16010
+ "fetch",
16011
+ "read",
16012
+ "show",
16013
+ "retrieve",
16014
+ "search",
16015
+ "count",
16016
+ "view",
16017
+ "see"
16018
+ ]);
16019
+ var WRITE_VERBS = /* @__PURE__ */ new Set([
16020
+ "create",
16021
+ "add",
16022
+ "new",
16023
+ "insert",
16024
+ "update",
16025
+ "edit",
16026
+ "change",
16027
+ "modify",
16028
+ "set",
16029
+ "delete",
16030
+ "remove",
16031
+ "destroy",
16032
+ "cancel",
16033
+ "bulk",
16034
+ "merge",
16035
+ "publish",
16036
+ "send"
16037
+ ]);
16038
+ var isVersionToken = (t) => t === "v" || /^\d+$/.test(t);
16039
+ function stripMarkdown(text) {
16040
+ return text.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1").replace(/[`*_]/g, "");
16041
+ }
16042
+ function firstSentence(text, max = 220) {
16043
+ const flat = stripMarkdown(text).replace(/\s+/g, " ").trim();
16044
+ const cut = flat.search(/(?<=[.!?])\s/);
16045
+ const sentence = cut > 0 ? flat.slice(0, cut) : flat;
16046
+ return sentence.length > max ? `${sentence.slice(0, max - 1)}\u2026` : sentence;
16047
+ }
16048
+ var indexCache = /* @__PURE__ */ new WeakMap();
16049
+ function indexOperations(ops) {
16050
+ let indexed = indexCache.get(ops);
16051
+ if (!indexed) {
16052
+ indexed = ops.map((op) => ({
16053
+ op,
16054
+ nameTokens: new Set(tokenize(op.name).map(stem)),
16055
+ descTokens: new Set(tokenize(op.description.slice(0, 600)).map(stem))
16056
+ }));
16057
+ indexCache.set(ops, indexed);
16058
+ }
16059
+ return indexed;
16060
+ }
16061
+ function searchOperations(ops, query, options = {}) {
16062
+ const { kind = "all", maxResults = 10 } = options;
16063
+ const rawTokens = tokenize(query);
16064
+ const terms = expandQueryTokens(rawTokens);
16065
+ const originalTerms = new Set(
16066
+ rawTokens.filter((t) => !STOP_WORDS.has(t)).map(stem)
16067
+ );
16068
+ const exactName = query.trim();
16069
+ const hasWriteVerb = rawTokens.some((t) => WRITE_VERBS.has(t));
16070
+ const nounTokens = rawTokens.filter(
16071
+ (t) => !STOP_WORDS.has(t) && !READ_VERBS.has(t) && !WRITE_VERBS.has(t)
16072
+ );
16073
+ const pluralIntent = nounTokens.length > 0 && nounTokens.some((t) => stem(t) !== t);
16074
+ const readIntent = !hasWriteVerb;
16075
+ const matches = [];
16076
+ for (const { op, nameTokens, descTokens } of indexOperations(ops)) {
16077
+ if (kind !== "all" && op.kind !== kind) continue;
16078
+ let score = 0;
16079
+ let originalHits = 0;
16080
+ const matchedNameTokens = /* @__PURE__ */ new Set();
16081
+ for (const term of terms) {
16082
+ const isOriginal = originalTerms.has(term);
16083
+ if (op.kind === "query" && readIntent && READ_VERBS.has(term)) {
16084
+ score += isOriginal ? 4 : 2;
16085
+ if (isOriginal) originalHits++;
16086
+ if (nameTokens.has(term)) matchedNameTokens.add(term);
16087
+ continue;
16088
+ }
16089
+ if (nameTokens.has(term)) {
16090
+ matchedNameTokens.add(term);
16091
+ score += isOriginal ? 4 : 2;
16092
+ if (isOriginal) originalHits++;
16093
+ continue;
16094
+ }
16095
+ let prefixHit = false;
16096
+ for (const nt of nameTokens) {
16097
+ if (term.length >= 3 && (nt.startsWith(term) || term.startsWith(nt))) {
16098
+ prefixHit = true;
16099
+ matchedNameTokens.add(nt);
16100
+ break;
16101
+ }
16102
+ }
16103
+ if (prefixHit) {
16104
+ score += isOriginal ? 2 : 1;
16105
+ if (isOriginal) originalHits++;
16106
+ continue;
16107
+ }
16108
+ if (descTokens.has(term)) {
16109
+ score += 1;
16110
+ if (isOriginal) originalHits++;
16111
+ }
16112
+ }
16113
+ if (score <= 0 && op.name !== exactName) continue;
16114
+ if (op.name === exactName) score += 100;
16115
+ if (originalTerms.size > 0 && originalHits === originalTerms.size) {
16116
+ score += 3;
16117
+ }
16118
+ const lastToken = tokenize(op.name).filter((t) => !isVersionToken(t)).pop();
16119
+ if (lastToken && nounTokens.length > 0) {
16120
+ const pluralOp = stem(lastToken) !== lastToken;
16121
+ score += pluralOp === pluralIntent ? 0.5 : -0.5;
16122
+ }
16123
+ if (/DoNotCall/i.test(op.name)) score -= 2;
16124
+ for (const nt of nameTokens) {
16125
+ if (!isVersionToken(nt) && !matchedNameTokens.has(nt)) score -= 0.3;
16126
+ }
16127
+ if (readIntent && op.kind === "mutation" && [...nameTokens].some((t) => WRITE_VERBS.has(t))) {
16128
+ score -= 6;
16129
+ }
16130
+ if (op.kind === "query" && readIntent) score += 1;
16131
+ const version = op.name.match(/V(\d+)/);
16132
+ if (version) score += Math.min(Number(version[1]), 5) * 0.1;
16133
+ if (!op.description) score -= 0.5;
16134
+ score -= op.name.length / 200;
16135
+ if (score <= 0) continue;
16136
+ matches.push({
16137
+ operation: op.name,
16138
+ kind: op.kind,
16139
+ signature: `${op.name}(${op.args.map((a) => `${a.name}: ${renderTypeRef(a.type)}`).join(", ")}): ${renderTypeRef(op.type)}`,
16140
+ description: firstSentence(op.description),
16141
+ inputType: op.args[0] ? namedType(op.args[0].type) : null,
16142
+ returnType: namedType(op.type),
16143
+ score: Math.round(score * 100) / 100
16144
+ });
16145
+ }
16146
+ matches.sort(
16147
+ (a, b) => b.score - a.score || a.operation.localeCompare(b.operation)
16148
+ );
16149
+ return matches.slice(0, Math.max(1, Math.min(maxResults, 50)));
16150
+ }
16151
+
16152
+ // src/graphql/index.ts
16153
+ var textResult = (text) => ({
16154
+ content: [{ type: "text", text }]
16155
+ });
16156
+ var errorResult = (text) => ({
16157
+ isError: true,
16158
+ content: [{ type: "text", text }]
16159
+ });
16160
+ var SCHEMA_MAX_RESPONSE_CHARS = 48e3;
16161
+ function addGraphqlTools(server, options = {}) {
16162
+ const { authStrategy, disableTools = [], toolDescriptions } = options;
16163
+ const getDescription = (name) => toolDescriptions?.[name] ?? defaultToolDescriptions[name];
16164
+ if (!disableTools.includes(SEARCH_GRAPHQL_TOOL_NAME)) {
16165
+ addSearchGraphqlTool(
16166
+ server,
16167
+ getDescription(SEARCH_GRAPHQL_TOOL_NAME),
16168
+ options
16169
+ );
16170
+ }
16171
+ if (!disableTools.includes(INSPECT_GRAPHQL_TOOL_NAME)) {
16172
+ addInspectGraphqlTool(
16173
+ server,
16174
+ getDescription(INSPECT_GRAPHQL_TOOL_NAME),
16175
+ options
16176
+ );
16177
+ }
16178
+ if (authStrategy && !disableTools.includes(EXECUTE_GRAPHQL_TOOL_NAME)) {
16179
+ addExecuteGraphqlTool(
16180
+ server,
16181
+ getDescription(EXECUTE_GRAPHQL_TOOL_NAME),
16182
+ authStrategy,
16183
+ options
16184
+ );
16185
+ }
16186
+ }
16187
+ function introspectionOptions(options) {
16188
+ return {
16189
+ endpoint: options.endpoint,
16190
+ fetchImpl: options.fetchImpl,
16191
+ retryDelaysMs: options.retryDelaysMs
16192
+ };
16193
+ }
16194
+ function addSearchGraphqlTool(server, description, options) {
16195
+ const d = desc("SearchWixGraphQLOperations");
16196
+ server.tool(
16197
+ SEARCH_GRAPHQL_TOOL_NAME,
16198
+ description,
16199
+ {
16200
+ query: external_exports.string().describe(d.query),
16201
+ kind: external_exports.enum(["query", "mutation", "all"]).optional().describe(d.kind),
16202
+ maxResults: external_exports.number().int().min(1).max(50).optional().describe(d.maxResults),
16203
+ reason: external_exports.string().describe(d.reason)
16204
+ },
16205
+ { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
16206
+ async ({ query, kind, maxResults, reason }) => {
16207
+ logger.log(
16208
+ `[${SEARCH_GRAPHQL_TOOL_NAME}] query="${query}" kind=${kind ?? "all"} reason="${reason}"`
16209
+ );
16210
+ try {
16211
+ const ops = await getRootOperations(introspectionOptions(options));
16212
+ const matches = searchOperations(ops, query, {
16213
+ kind: kind ?? "all",
16214
+ maxResults: maxResults ?? 10
16215
+ });
16216
+ if (matches.length === 0) {
16217
+ return textResult(
16218
+ `No GraphQL operations matched "${query}". Try other words for the entity (e.g. "contact" instead of "customer", "product" instead of "item") or the verb (query/get/create/update/delete), or search a single noun.`
16219
+ );
16220
+ }
16221
+ const lines = matches.map(
16222
+ (m, i) => `${i + 1}. ${m.kind} ${m.signature}
16223
+ ${m.description || "(no description)"}`
16224
+ );
16225
+ const text = [
16226
+ `Top ${matches.length} of ${ops.length} Wix GraphQL root operations for "${query}":`,
16227
+ "",
16228
+ ...lines,
16229
+ "",
16230
+ `Next: call ${INSPECT_GRAPHQL_TOOL_NAME} with \`operation\` set to the chosen name to read its exact input type and return type before writing the request.`
16231
+ ].join("\n");
16232
+ return textResult(text);
16233
+ } catch (err) {
16234
+ const message = err instanceof Error ? err.message : String(err);
16235
+ logger.log(`[${SEARCH_GRAPHQL_TOOL_NAME}] Error: ${message}`);
16236
+ return errorResult(`GraphQL schema search error: ${message}`);
16237
+ }
16238
+ }
16239
+ );
16240
+ }
16241
+ function addInspectGraphqlTool(server, description, options) {
16242
+ const d = desc("InspectWixGraphQLSchema");
16243
+ const maxChars = options.maxResponseSize ?? SCHEMA_MAX_RESPONSE_CHARS;
16244
+ server.tool(
16245
+ INSPECT_GRAPHQL_TOOL_NAME,
16246
+ description,
16247
+ {
16248
+ operation: external_exports.string().optional().describe(d.operation),
16249
+ typeNames: external_exports.array(external_exports.string()).optional().describe(d.typeNames),
16250
+ depth: external_exports.number().int().min(1).max(4).optional().describe(d.depth),
16251
+ reason: external_exports.string().describe(d.reason)
16252
+ },
16253
+ { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
16254
+ async ({ operation, typeNames, depth, reason }) => {
16255
+ logger.log(
16256
+ `[${INSPECT_GRAPHQL_TOOL_NAME}] operation=${operation ?? "-"} typeNames=${JSON.stringify(typeNames ?? [])} depth=${depth ?? 2} reason="${reason}"`
16257
+ );
16258
+ if (!operation && !(typeNames && typeNames.length > 0)) {
16259
+ return errorResult(
16260
+ "Pass `operation` (a root query/mutation name from SearchWixGraphQLOperations) and/or `typeNames` (type names to expand)."
16261
+ );
16262
+ }
16263
+ try {
16264
+ const io = introspectionOptions(options);
16265
+ const sections = [];
16266
+ const roots = [];
16267
+ if (operation) {
16268
+ const ops = await getRootOperations(io);
16269
+ const op = ops.find((o) => o.name === operation);
16270
+ if (!op) {
16271
+ const suggestions = searchOperations(ops, operation, {
16272
+ maxResults: 5
16273
+ });
16274
+ return errorResult(
16275
+ `No root operation named "${operation}". ${suggestions.length ? `Did you mean: ${suggestions.map((s) => `${s.kind} ${s.operation}`).join(", ")}? Use SearchWixGraphQLOperations to discover the exact name.` : "Use SearchWixGraphQLOperations to discover the exact name."}`
16276
+ );
16277
+ }
16278
+ sections.push(
16279
+ `# ${renderOperationSignature(op)}`,
16280
+ op.description ? op.description.trim().split("\n").map((l) => `# ${l}`).join("\n") : "# (no description)"
16281
+ );
16282
+ op.args.forEach((a) => {
16283
+ const n = namedType(a.type);
16284
+ if (n) roots.push(n);
16285
+ });
16286
+ const ret = namedType(op.type);
16287
+ if (ret) roots.push(ret);
16288
+ }
16289
+ if (typeNames?.length) roots.push(...typeNames);
16290
+ const { rendered, unexpanded, unknown } = await expandTypes(roots, {
16291
+ ...io,
16292
+ depth: depth ?? 2
16293
+ });
16294
+ sections.push(...rendered);
16295
+ if (unknown.length) {
16296
+ sections.push(
16297
+ `# Unknown type names (not in the schema): ${unknown.join(", ")}`
16298
+ );
16299
+ }
16300
+ if (unexpanded.length) {
16301
+ sections.push(
16302
+ `# Not expanded (pass any of these in \`typeNames\` to read them): ${unexpanded.join(", ")}`
16303
+ );
16304
+ }
16305
+ sections.push(
16306
+ "# Notes: `JSON` scalar fields (filter, sort, free-form data) take any JSON \u2014 pass them as variables. Every object-typed field in a selection needs its own { ... } selection set. Only fields listed above exist. Paging: use exactly the paging style the input type declares \u2014 `paging` (offset) or `cursorPaging` (cursor) \u2014 never the other one. `pageInfo.total` is only populated with offset paging; with cursor paging, count by walking pages (`pageInfo.hasNext` + cursor) or use a dedicated count operation if one exists."
16307
+ );
16308
+ return textResult(truncateResponse(sections.join("\n\n"), maxChars));
16309
+ } catch (err) {
16310
+ const message = err instanceof Error ? err.message : String(err);
16311
+ logger.log(`[${INSPECT_GRAPHQL_TOOL_NAME}] Error: ${message}`);
16312
+ return errorResult(`GraphQL schema inspection error: ${message}`);
16313
+ }
16314
+ }
16315
+ );
16316
+ }
16317
+ function addExecuteGraphqlTool(server, description, authStrategy, options) {
16318
+ const d = desc("ExecuteWixGraphQL");
16319
+ const endpoint = options.endpoint ?? WIX_GRAPHQL_ENDPOINT;
16320
+ const fetchImpl = options.fetchImpl ?? fetch;
16321
+ server.tool(
16322
+ EXECUTE_GRAPHQL_TOOL_NAME,
16323
+ description,
16324
+ {
16325
+ query: external_exports.string().describe(d.query),
16326
+ variables: external_exports.record(external_exports.unknown()).optional().describe(d.variables),
16327
+ operationName: external_exports.string().optional().describe(d.operationName),
16328
+ siteId: external_exports.string().optional().describe(d.siteId),
16329
+ scope: external_exports.enum(["site", "account"]).optional().describe(d.scope),
16330
+ hasMutations: external_exports.boolean().describe(d.hasMutations),
16331
+ reason: external_exports.string().describe(d.reason)
16332
+ },
16333
+ { readOnlyHint: false, destructiveHint: true, openWorldHint: false },
16334
+ async ({ query, variables, operationName, siteId, scope, hasMutations, reason }, extra) => {
16335
+ const effectiveScope = scope ?? (siteId ? "site" : "account");
16336
+ logger.log(
16337
+ `[${EXECUTE_GRAPHQL_TOOL_NAME}] scope=${effectiveScope} siteId=${siteId ?? "none"} hasMutations=${hasMutations} operationName=${operationName ?? "-"} reason="${reason}"`
16338
+ );
16339
+ if (effectiveScope === "site" && !siteId) {
16340
+ return errorResult(
16341
+ 'A `siteId` is required for site-level GraphQL operations (anything that reads or writes inside a site). Resolve it with GetSiteContext or ListWixSites, or set scope: "account" for account-level operations.'
16342
+ );
16343
+ }
16344
+ if (!query.trim()) {
16345
+ return errorResult("`query` must be a non-empty GraphQL document.");
16346
+ }
16347
+ const authHeaders = effectiveScope === "site" ? await authStrategy.getSiteAuthHeaders(siteId) : await authStrategy.getAccountAuthHeaders();
16348
+ try {
16349
+ const init = {
16350
+ method: "POST",
16351
+ headers: {
16352
+ "Content-Type": "application/json",
16353
+ Accept: "application/json",
16354
+ ...authHeaders
16355
+ },
16356
+ body: JSON.stringify({
16357
+ query,
16358
+ ...variables ? { variables } : {},
16359
+ ...operationName ? { operationName } : {}
16360
+ })
16361
+ };
16362
+ const resp = hasMutations ? await fetchImpl(endpoint, init) : await fetchWithRetry(
16363
+ fetchImpl,
16364
+ endpoint,
16365
+ init,
16366
+ options.retryDelaysMs
16367
+ );
16368
+ const requestId = resp.headers?.get("x-wix-request-id") ?? void 0;
16369
+ extra?.setToolBiParams?.({ siteId, requestId });
16370
+ const text = await resp.text();
16371
+ if (!resp.ok) {
16372
+ await authStrategy.enforceValidWixToken?.({
16373
+ status: resp.status,
16374
+ response: { status: resp.status }
16375
+ });
16376
+ const body2 = /^\s*<(!doctype|html)/i.test(text) ? "(HTML error page)" : text.slice(0, 2e3);
16377
+ const hasObjectVariables = !!variables && Object.values(variables).some(
16378
+ (v) => v !== null && typeof v === "object"
16379
+ );
16380
+ const hint = resp.status >= 500 ? hasObjectVariables ? ` The Wix GraphQL endpoint (Developer Preview) returns 503 when an object-typed variable carries an enum value. Rewrite the document with the input INLINE as a GraphQL literal (enum values unquoted, e.g. productType: PHYSICAL), keep variables only for JSON scalars and plain scalars, and retry once. If it still fails and REST tools (ExecuteWixAPI / CallWixSiteAPI) are available, use the equivalent REST method.` : ` The Wix GraphQL endpoint (Developer Preview) failed for this operation. Do not retry the same document more than once. If REST tools (ExecuteWixAPI / CallWixSiteAPI) are available, complete the task through the equivalent REST method instead; otherwise report the failure with the request id.` : "";
16381
+ return errorResult(
16382
+ `Wix GraphQL request failed: ${resp.status} ${resp.statusText}.${requestId ? ` request id: ${requestId}.` : ""}${hint}
16383
+ ${body2}`
16384
+ );
16385
+ }
16386
+ let json;
16387
+ try {
16388
+ json = JSON.parse(text);
16389
+ } catch {
16390
+ return errorResult(
16391
+ `Wix GraphQL returned a non-JSON body:
16392
+ ${text.slice(0, 2e3)}`
16393
+ );
16394
+ }
16395
+ const hasData = json.data != null && Object.values(json.data).some((v) => v !== null && v !== void 0);
16396
+ const errors = json.errors ?? [];
16397
+ if (!hasData && errors.length > 0) {
16398
+ const permissionDenied = errors.some(
16399
+ (e) => e.extensions?.message === "PERMISSION_DENIED"
16400
+ );
16401
+ return errorResult(
16402
+ [
16403
+ `Wix GraphQL returned errors and no data${requestId ? ` (request id: ${requestId})` : ""}:`,
16404
+ JSON.stringify(errors, null, 2).slice(0, 4e3),
16405
+ permissionDenied ? "PERMISSION_DENIED usually means the operation is site-level and was called without the right `siteId`, the app behind it is not installed on the site, or the credential lacks that permission scope." : 'Validation errors ("Cannot query field ...", "Unknown argument ...") mean a name was guessed \u2014 re-read the exact fields with InspectWixGraphQLSchema and retry.'
16406
+ ].join("\n")
16407
+ );
16408
+ }
16409
+ const body = { data: json.data };
16410
+ if (errors.length > 0) {
16411
+ body.errors = errors;
16412
+ body.note = "Partial result: some root fields failed (see errors[].path). Fields present in data succeeded.";
16413
+ }
16414
+ return textResult(truncateResponse(body, options.maxResponseSize));
16415
+ } catch (err) {
16416
+ rethrowIfUnauthorized(err);
16417
+ await authStrategy.enforceValidWixToken?.(err);
16418
+ const message = err instanceof Error ? err.message : String(err);
16419
+ logger.log(`[${EXECUTE_GRAPHQL_TOOL_NAME}] Error: ${message}`);
16420
+ return errorResult(`Wix GraphQL execution error: ${message}`);
16421
+ }
16422
+ }
16423
+ );
16424
+ }
16425
+
15610
16426
  // src/code-mode/validation.ts
15611
16427
  var EXECUTE_FUNCTION_EXPRESSION_HINT = 'ExecuteWixAPI code must be a function expression, not a script body. Pass code like: async () => { const response = await wix.request({ scope: "site", method: "GET", url: "https://www.wixapis.com/..." }); return response.data; }. Do not write top-level const/await/return outside the function and do not invoke the function yourself.';
15612
16428
  function validateExecuteCode(code) {
@@ -17927,6 +18743,20 @@ function createWixToolkit(options) {
17927
18743
  maxResponseSize
17928
18744
  });
17929
18745
  }
18746
+ const requestedGraphqlTools = GRAPHQL_TOOL_NAMES.filter(
18747
+ (name) => requestedTools.has(name)
18748
+ );
18749
+ if (requestedGraphqlTools.length > 0) {
18750
+ addGraphqlTools(server, {
18751
+ authStrategy,
18752
+ disableTools: [
18753
+ ...disableTools ?? [],
18754
+ ...GRAPHQL_TOOL_NAMES.filter((n) => !requestedTools.has(n))
18755
+ ],
18756
+ toolDescriptions: effectiveToolDescriptions,
18757
+ maxResponseSize
18758
+ });
18759
+ }
17930
18760
  } else {
17931
18761
  addApiCallTool(
17932
18762
  server,
@@ -18108,10 +18938,15 @@ function createWixToolkit(options) {
18108
18938
  }
18109
18939
  export {
18110
18940
  EXECUTE_FUNCTION_EXPRESSION_HINT,
18941
+ EXECUTE_GRAPHQL_TOOL_NAME,
18942
+ GRAPHQL_TOOL_NAMES,
18943
+ INSPECT_GRAPHQL_TOOL_NAME,
18111
18944
  RECIPES_INDEX_URL,
18945
+ SEARCH_GRAPHQL_TOOL_NAME,
18112
18946
  SYSTEM_REMINDER,
18113
18947
  SYSTEM_REMINDER_GUIDELINES,
18114
18948
  UNAUTHORIZED_ERROR_NAME,
18949
+ WIX_GRAPHQL_ENDPOINT,
18115
18950
  WixFetchError,
18116
18951
  attachConsoleLogger,
18117
18952
  createWixToolkit,