@brainerce/mcp-server 3.8.0 → 3.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/http.js CHANGED
@@ -3,6 +3,7 @@
3
3
 
4
4
  // src/bin/http.ts
5
5
  var import_node_http = require("http");
6
+ var import_node_crypto = require("crypto");
6
7
  var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
7
8
  var import_sse = require("@modelcontextprotocol/sdk/server/sse.js");
8
9
 
@@ -711,7 +712,7 @@ const growProvider = providers.find(p => p.provider === 'grow');
711
712
  const paypalProvider = providers.find(p => p.provider === 'paypal');
712
713
  \`\`\`
713
714
 
714
- Each provider has: \`id\`, \`provider\` (flexible string \u2014 \`'stripe'\`, \`'grow'\`, \`'paypal'\`, \`'cardcom'\`, \`'sandbox'\`, and future providers), \`name\`, \`publicKey\`, \`stripeAccountId\` (Stripe only), \`supportedMethods\`, \`testMode\`, \`isDefault\`.
715
+ Each provider has: \`id\`, \`provider\` (flexible string \u2014 \`'stripe'\`, \`'grow'\`, \`'paypal'\`, \`'cardcom'\`, \`'morning'\`, \`'takbull'\`, \`'sandbox'\`, and future providers), \`name\`, \`publicKey\`, \`stripeAccountId\` (Stripe only), \`supportedMethods\`, \`testMode\`, \`isDefault\`.
715
716
 
716
717
  The payment intent returned from \`createPaymentIntent()\` includes a \`clientSdk\` object whose \`renderType\` tells you exactly how to render \u2014 **branch on THAT, not on the provider name**:
717
718
 
@@ -1155,6 +1156,8 @@ const material = getProductMetafieldValue(product, 'material');
1155
1156
 
1156
1157
  **Metafield fields:** \`definitionName\` (display label), \`definitionKey\` (lookup key), \`value\`, \`type\` (IMAGE, GALLERY, URL, COLOR, BOOLEAN, DATE, DATETIME, TEXT, TEXTAREA, NUMBER, DIMENSION, WEIGHT, JSON)
1157
1158
 
1159
+ **Translations:** When the store has i18n enabled and \`client.setLocale()\` is active, both the \`definitionName\` (the merchant-authored label like "Warranty Info" / "\u05DE\u05D9\u05D3\u05E2 \u05D0\u05D7\u05E8\u05D9\u05D5\u05EA") **and** free-text \`value\` come back already translated. No per-call locale param needed.
1160
+
1158
1161
  ### Product Customization Fields (Customer Input)
1159
1162
 
1160
1163
  Some products allow customers to provide input at purchase time (e.g., text on a cake, upload a logo). Check \`product.customizationFields\` and render input fields accordingly.
@@ -1288,6 +1291,8 @@ await client.removeCoupon(cartId);
1288
1291
  const totals = getCartTotals(cart); // { subtotal, discount, shipping, total }
1289
1292
  \`\`\`
1290
1293
 
1294
+ > **Region-restricted coupons:** a coupon may carry \`regionIds\`. If the buyer's checkout region isn't in that list, \`applyCoupon\` / \`applyCheckoutCoupon\` reject the code even when everything else matches. Empty/omitted \`regionIds\` = valid in all regions.
1295
+
1291
1296
  **On the checkout page** (after checkout session exists \u2014 ALWAYS use this when checkoutId is available):
1292
1297
  \`\`\`typescript
1293
1298
  // Applies to cart AND updates checkout totals in one call
@@ -1615,6 +1620,8 @@ const groups: ModifierGroup[] = product.modifierGroups ?? [];
1615
1620
 
1616
1621
  **Money fields are strings.** \`priceDelta\` is \`"5.00"\` (or \`"-2.00"\` for downsell modifiers \u2014 see below). Use \`parseFloat()\` for display arithmetic; never compute the line total client-side \u2014 the server runs the free-allocation policy and returns the final \`unitPrice\` snapshot on the cart line.
1617
1622
 
1623
+ **Translations are automatic.** Both \`group.name\`/\`group.description\` and each \`modifier.name\`/\`modifier.description\` are overlay-resolved by the server on every read. Call \`client.setLocale('he')\` once and the modifier picker renders in Hebrew with no extra code (\`"\u05EA\u05D5\u05E1\u05E4\u05D5\u05EA"\` / \`"\u05D6\u05D9\u05EA\u05D9\u05DD"\`). See the \`i18n\` topic for the full multi-language flow.
1624
+
1618
1625
  ### Render: SINGLE \u2192 radio, MULTIPLE \u2192 checkbox
1619
1626
 
1620
1627
  Walk \`groups\` and pick the input type by \`selectionType\`. Sort modifiers by \`position\`.
@@ -2016,19 +2023,24 @@ window.location.href = authorizationUrl;
2016
2023
  \`\`\`typescript
2017
2024
  const params = new URLSearchParams(window.location.search);
2018
2025
  if (params.get('oauth_success') === 'true') {
2019
- const token = params.get('token');
2020
- if (token) {
2021
- client.setCustomerToken(token);
2022
- localStorage.setItem('customerToken', token);
2023
- // Optional: read customer_id, customer_email, is_new from params
2026
+ // Single-use auth_code is exchanged for the JWT via POST \u2014 keeps the JWT
2027
+ // out of the URL (browser history, CDN logs, Referer header).
2028
+ const code = params.get('auth_code');
2029
+ if (code) {
2030
+ const result = await client.exchangeOAuthCode(code);
2031
+ client.setCustomerToken(result.token);
2032
+ localStorage.setItem('customerToken', result.token);
2033
+ // Optional: result.customer, result.isNewCustomer, result.redirectUrl
2024
2034
  // Link guest cart: await client.linkCart(cartId);
2025
- window.location.href = '/account';
2035
+ window.location.href = result.redirectUrl || '/account';
2026
2036
  }
2027
2037
  } else if (params.get('oauth_error')) {
2028
2038
  // Show error: params.get('oauth_error')
2029
2039
  }
2030
2040
  \`\`\`
2031
2041
 
2042
+ > The legacy redirect format placed the JWT directly in the URL as \`?token=\`. That format is still emitted for backward compatibility, but it will be removed in the next major release \u2014 migrate to \`auth_code\` + \`exchangeOAuthCode()\` now.
2043
+
2032
2044
  ### Account Page (/account) \u2014 uses getMyProfile() and getMyOrders()
2033
2045
 
2034
2046
  \`\`\`typescript
@@ -2257,7 +2269,17 @@ overlay needed:
2257
2269
  - \`variants[].name\`
2258
2270
  - \`variant.attributes\` keys and values \u2014 \`getVariantOptions(variant)\` returns translated attribute names and option values automatically
2259
2271
  - \`productAttributeOptions[].attribute.name\`, \`attributeOption.name\`
2260
- - \`metafields[].value\`
2272
+ - \`metafields[].value\` (the free-text values customers submit)
2273
+ - \`metafields[].definition.name\`, \`metafields[].definition.description\` (the merchant-authored custom-field labels \u2014 "Warranty Info" / "\u05DE\u05D9\u05D3\u05E2 \u05D0\u05D7\u05E8\u05D9\u05D5\u05EA")
2274
+ - \`modifierGroups[].name\`, \`modifierGroups[].description\` (the group label shown on the PDP \u2014 e.g. "Toppings" / "\u05EA\u05D5\u05E1\u05E4\u05D5\u05EA")
2275
+ - \`modifierGroups[].modifiers[].name\`, \`modifierGroups[].modifiers[].description\` (each individual modifier \u2014 e.g. "Olives" / "\u05D6\u05D9\u05EA\u05D9\u05DD")
2276
+
2277
+ **Promotional surfaces:**
2278
+ - \`cart.bundles[].name\`, \`cart.bundles[].description\` (the bundle's own merchant-typed label, e.g. "Lunch Combo" / "\u05D0\u05E8\u05D5\u05D7\u05EA \u05E6\u05D4\u05E8\u05D9\u05D9\u05DD")
2279
+ - \`cart.bundles[].offeredProducts[].name\`, \`.slug\` (each product inside the bundle \u2014 fetched fresh from \`Product.translations\`)
2280
+ - \`checkout.bumps[].title\`, \`checkout.bumps[].description\` (the bump headline shown at checkout \u2014 falls back to the translated product name when merchant didn't override)
2281
+ - \`checkout.bumps[].bumpProduct.name\`, \`.slug\` (the underlying product)
2282
+ - Discount-rule names/descriptions (when surfaced as banner text via \`displayConfig\`)
2261
2283
 
2262
2284
  **Taxonomy (\`getCategories\`, \`getBrands\`, \`getTags\`):**
2263
2285
  - \`name\` on each item
@@ -2349,6 +2371,67 @@ Read \`storeInfo.i18n.supportedLocales\` and render a switcher in the header
2349
2371
  that navigates to \`/{otherLocale}/{currentPathWithoutLocale}\`. The middleware
2350
2372
  handles the canonical redirect when the user picks the default locale.`;
2351
2373
  }
2374
+ function getMultilingualSeoSection() {
2375
+ return `## Multilingual SEO
2376
+
2377
+ ### Slugs per locale (IMPORTANT)
2378
+
2379
+ Brainerce stores per-locale slugs in \`Product.translations[locale].slug\`.
2380
+ The API exposes them as \`product.localeSlugs\` \u2014 a flat \`Record<string, string>\`.
2381
+
2382
+ \`\`\`typescript
2383
+ // product.localeSlugs = { he: '\u05DE\u05D6\u05E8\u05DF-\u05D9\u05D5\u05D2\u05D4', en: 'yoga-mattress', ar: '\u062D\u0635\u064A\u0631\u0629-\u064A\u0648\u063A\u0627' }
2384
+ const locSlug = product.localeSlugs?.[locale] ?? product.slug;
2385
+ \`\`\`
2386
+
2387
+ Use AI translation (\`translateEntities\` / the AI Translate button in the admin) to populate
2388
+ locale-specific slugs automatically. Until translated, all locales fall back to the base slug
2389
+ (which Google still accepts \u2014 it resolves to the correct locale content via Accept-Language).
2390
+
2391
+ ### hreflang tags
2392
+
2393
+ Every product page in a multi-locale store MUST emit bidirectional hreflang tags or Google
2394
+ ignores them entirely. The scaffolded template generates them automatically when
2395
+ \`NEXT_PUBLIC_BRAINERCE_LOCALES=he,en\` is set.
2396
+
2397
+ \`\`\`html
2398
+ <!-- Example output for /en/products/yoga-mattress -->
2399
+ <link rel="alternate" hreflang="he" href="https://store.com/products/\u05DE\u05D6\u05E8\u05DF-\u05D9\u05D5\u05D2\u05D4" />
2400
+ <link rel="alternate" hreflang="en" href="https://store.com/en/products/yoga-mattress" />
2401
+ <link rel="alternate" hreflang="x-default" href="https://store.com/products/\u05DE\u05D6\u05E8\u05DF-\u05D9\u05D5\u05D2\u05D4" />
2402
+ \`\`\`
2403
+
2404
+ If building a custom storefront, add to \`generateMetadata()\`:
2405
+ \`\`\`typescript
2406
+ alternates: {
2407
+ canonical: locale === defaultLoc ? \`/products/\${slug}\` : \`/\${locale}/products/\${slug}\`,
2408
+ languages: {
2409
+ he: \`\${baseUrl}/products/\${localeSlugs.he ?? baseSlug}\`,
2410
+ en: \`\${baseUrl}/en/products/\${localeSlugs.en ?? baseSlug}\`,
2411
+ 'x-default': \`\${baseUrl}/products/\${localeSlugs[defaultLoc] ?? baseSlug}\`,
2412
+ },
2413
+ },
2414
+ \`\`\`
2415
+
2416
+ ### URL structure
2417
+
2418
+ Google-recommended for headless storefronts:
2419
+ - Default locale: \`/products/\u05DE\u05D6\u05E8\u05DF-\u05D9\u05D5\u05D2\u05D4\` (no prefix)
2420
+ - Other locales: \`/en/products/yoga-mattress\` (prefixed)
2421
+ - \u274C Never: \`?locale=he\` query params (Google rates these as "Not recommended")
2422
+
2423
+ ### Sitemap
2424
+
2425
+ The scaffolded \`sitemap.ts\` generates per-locale entries automatically:
2426
+ \`\`\`
2427
+ /products/\u05DE\u05D6\u05E8\u05DF-\u05D9\u05D5\u05D2\u05D4 (he \u2014 default, no prefix)
2428
+ /en/products/yoga-mattress (en)
2429
+ /ar/products/\u062D\u0635\u064A\u0631\u0629-\u064A\u0648\u063A\u0627 (ar)
2430
+ \`\`\`
2431
+
2432
+ Hebrew, Arabic, and other non-Latin slugs are fully supported \u2014 Google recommends
2433
+ using the audience's language in URLs and indexes non-ASCII characters correctly.`;
2434
+ }
2352
2435
  function getAdminApiSection() {
2353
2436
  return `## Admin API (v0.19.0+)
2354
2437
 
@@ -2359,7 +2442,9 @@ const admin = new BrainerceClient({ apiKey: 'brainerce_...' });
2359
2442
 
2360
2443
  // Taxonomy: listCategories(), listBrands(), listTags(), listAttributes()
2361
2444
  // Shipping: listShippingZones(), createZoneShippingRate()
2362
- // Tax: getTaxRates(), createTaxRate()
2445
+ // Tax: getTaxRates(), createTaxRate() \u2014 a rate may target a tax class via taxClassId
2446
+ // Tax classes: getTaxClasses(), createTaxClass(), assignTaxClass(), mergeTaxClasses() (scope tax-classes:*)
2447
+ // Regions: getRegions(), createRegion(), setDefaultRegion(), updateRegionPaymentProviders() (scope regions:*)
2363
2448
  // Metafields: getMetafieldDefinitions(), setProductMetafield()
2364
2449
  // Team: getTeamMembers(), inviteTeamMember()
2365
2450
  // Email: getEmailTemplates(), createEmailTemplate()
@@ -2367,6 +2452,13 @@ const admin = new BrainerceClient({ apiKey: 'brainerce_...' });
2367
2452
  // OAuth: getOAuthProviders(), configureOAuthProvider()
2368
2453
  \`\`\`
2369
2454
 
2455
+ Store-level team management (\`inviteStoreMember\`, \`updateStoreMember\`) is the
2456
+ canonical replacement for the deprecated account-level helpers above. The
2457
+ invite accepts an optional \`salesChannelIds\` (vibe-coded \`connectionId\`s,
2458
+ \`vc_*\`) to restrict a member to specific channels \u2014 omit or pass \`[]\` for all
2459
+ channels. Use \`updateStoreMemberSalesChannels(storeId, memberId, { salesChannelIds })\`
2460
+ to change that scope later.
2461
+
2370
2462
  ### Per-Channel Publishing
2371
2463
 
2372
2464
  Categories, tags, brands, and metafield definitions are gated to specific
@@ -2398,7 +2490,97 @@ calls fail with \`404 Not Found\`.
2398
2490
 
2399
2491
  The vibe-coded read endpoints (used by storefront SDK calls in \`connectionId\`
2400
2492
  mode) automatically filter by these junction tables, so storefronts never see
2401
- entities that weren't published to their site.`;
2493
+ entities that weren't published to their site.
2494
+
2495
+ ### Tax classes (differential tax rates)
2496
+
2497
+ Charge different rates for different product types. A \`TaxRate\` may target a
2498
+ class via \`taxClassId\`; a rate with \`taxClassId: null\` is the **Standard
2499
+ fallback**. Checkout resolves each line's class **variant \u2192 product \u2192 category
2500
+ \u2192 store default \u2192 null**, then picks the matching rate (Standard if none).
2501
+ \`rate\` is a whole percentage (\`7.25\` = 7.25%). Requires the
2502
+ \`tax-classes:read\` / \`tax-classes:write\` scopes.
2503
+
2504
+ \`\`\`typescript
2505
+ const food = await admin.createTaxClass({ name: 'Food', slug: 'food' });
2506
+ await admin.assignTaxClass(food.id, { productIds: ['prod_1'], categoryIds: ['cat_food'] });
2507
+
2508
+ // class-specific rate \u2014 only food lines use it; everything else uses Standard
2509
+ await admin.createTaxRate({ name: 'VAT (Food)', rate: 0, country: 'GB', taxClassId: food.id });
2510
+
2511
+ // delete is blocked (409) while dependents exist \u2014 merge moves FKs then deletes:
2512
+ await admin.mergeTaxClasses(food.id, standardClassId);
2513
+ \`\`\`
2514
+
2515
+ Storefront (public, no apiKey \u2014 \`storeId\` mode): \`getStoreTaxClasses()\` lists
2516
+ the store's classes (storefront-safe fields only) for a transparency badge.
2517
+
2518
+ For a buyer-facing tax preview on PDP / PLP / cart, \`estimateTax({ country,
2519
+ subtotal })\` returns the tax portion at the Standard rate for the buyer's
2520
+ country. **Non-binding** \u2014 the authoritative tax still runs at checkout with
2521
+ the full shipping address (state / postal / per-class). Always render with an
2522
+ "Estimate" affordance.
2523
+
2524
+ \`\`\`typescript
2525
+ const { estimatedTax, rate, currency, note } = await store.estimateTax({
2526
+ country: 'IT', subtotal: 100,
2527
+ });
2528
+ // \u2192 { appliesTax: true, rate: 22, estimatedTax: 22, currency: 'EUR',
2529
+ // note: 'Estimate \u2014 final tax calculated at checkout\u2026' }
2530
+ \`\`\`
2531
+
2532
+ ### Regions (multi-currency / per-region providers)
2533
+
2534
+ A region binds countries \u2192 currency + tax-display mode + enabled payment
2535
+ providers. Manage them via the SDK (scopes \`regions:read\` / \`regions:write\`).
2536
+ \`detectRegion\` is a pure client-side helper to map a buyer's country to a
2537
+ region; pass the resolved \`regionId\` to \`createCheckout\` to associate the
2538
+ checkout with a region (recorded for reporting + provider scoping; currency
2539
+ follows the cart until FX price conversion lands).
2540
+
2541
+ \`\`\`typescript
2542
+ const eu = await admin.createRegion({
2543
+ name: 'EU', currency: 'EUR', countries: ['DE', 'FR'],
2544
+ taxInclusive: true, paymentProviderIds: ['app_inst_stripe'],
2545
+ });
2546
+ await admin.setDefaultRegion(eu.id);
2547
+
2548
+ const { data: regions } = await admin.getRegions();
2549
+ const region = admin.detectRegion('DE', regions); // \u2192 eu, else default, else null
2550
+ \`\`\`
2551
+
2552
+ Storefront (public, no apiKey \u2014 \`storeId\` mode): \`getStoreRegions()\` lists
2553
+ active regions, \`getStoreRegion(id)\` returns one region + its payment providers.
2554
+ Pair with \`detectRegion\` to pick the buyer's region for currency display.
2555
+
2556
+ \`\`\`typescript
2557
+ const store = new BrainerceClient({ storeId: 'store_123' });
2558
+ const { data: regions } = await store.getStoreRegions();
2559
+ const region = await store.getStoreRegion(regions[0].id);
2560
+ \`\`\`
2561
+
2562
+ For a single round trip, \`getAutoRegion(country)\` resolves a buyer's country
2563
+ to a region server-side. Brainerce does NOT derive the country from the request
2564
+ IP (the storefront server is what reaches the backend, not the end-customer) \u2014
2565
+ your storefront extracts the country from its edge runtime (Cloudflare
2566
+ \`CF-IPCountry\`, Vercel \`request.geo?.country\`, Fastly \`client-geo-country\`,
2567
+ etc.) and forwards it. Returns \`matched=true\` on explicit country hit, \`false\`
2568
+ when falling back to the default region.
2569
+
2570
+ \`\`\`typescript
2571
+ const country = headers.get('cf-ipcountry') ?? 'US';
2572
+ const { region, matched } = await store.getAutoRegion(country);
2573
+ \`\`\`
2574
+
2575
+ A shipping zone can be limited to regions via \`regionIds\` \u2014 the zone is then
2576
+ only offered to checkouts that resolved to one of those regions. Empty/omitted =
2577
+ available for any region (default); each id must belong to the same store.
2578
+
2579
+ \`\`\`typescript
2580
+ await admin.createShippingZone({
2581
+ name: 'EU Express', countries: ['DE', 'FR', 'IT'], regionIds: [eu.id],
2582
+ });
2583
+ \`\`\``;
2402
2584
  }
2403
2585
  function getContactInquiriesSection() {
2404
2586
  return `## Contact Inquiries & Forms (optional)
@@ -2853,6 +3035,146 @@ entries \u2014 pick a descriptive slug (\`'shipping'\`, \`'returns'\`, \`'about'
2853
3035
  - \`get-type-definitions\` with \`domain: 'content'\` for the TypeScript
2854
3036
  interfaces.`;
2855
3037
  }
3038
+ function getBlogSection() {
3039
+ return `## Blog
3040
+
3041
+ Merchants write and schedule blog posts in **Content \u2192 Blog** in the dashboard.
3042
+ Storefronts choose their own URL scheme \u2014 render posts at \`/blog/[slug]\`,
3043
+ \`/articles/[slug]\`, or whatever fits the brand.
3044
+
3045
+ Public reads carry \`Cache-Control: public, max-age=300, stale-while-revalidate=60\`.
3046
+
3047
+ **Scheduling:** A post is visible once \`status === 'PUBLISHED'\` and
3048
+ \`publishedAt <= now()\`. Set a future \`publishedAt\` while publishing to
3049
+ schedule \u2014 no cron needed; visibility is computed at query time.
3050
+
3051
+ ### Reading posts (any SDK mode)
3052
+
3053
+ \`\`\`typescript
3054
+ // List published posts
3055
+ const { data: posts, meta } = await client.blog.getPosts({ page: 1, limit: 10 });
3056
+
3057
+ // Filter by category or tag
3058
+ const { data: news } = await client.blog.getPosts({ category: 'news' });
3059
+ const { data: tips } = await client.blog.getPosts({ tag: 'tutorial' });
3060
+
3061
+ // Fetch one by slug (returns null on 404)
3062
+ const post = await client.blog.getPost('my-first-post');
3063
+ if (post) {
3064
+ console.log(post.title); // string
3065
+ console.log(post.content); // HTML string from rich-text editor
3066
+ console.log(post.excerpt); // optional short summary
3067
+ console.log(post.tags); // string[]
3068
+ console.log(post.coverImageUrl, post.coverImageAlt);
3069
+ console.log(post.publishedAt); // ISO 8601 or undefined
3070
+ }
3071
+ \`\`\`
3072
+
3073
+ ### BlogPost fields
3074
+
3075
+ | Field | Type | Notes |
3076
+ | ----------------- | ----------- | ------------------------------------- |
3077
+ | \`id\` | string | |
3078
+ | \`title\` | string | |
3079
+ | \`slug\` | string | Unique per store, URL-safe |
3080
+ | \`category\` | string? | Free-form (e.g. \`'news'\`) |
3081
+ | \`content\` | string | HTML from rich-text editor |
3082
+ | \`excerpt\` | string? | Short summary for listing cards |
3083
+ | \`coverImageUrl\` | string? | |
3084
+ | \`coverImageAlt\` | string? | |
3085
+ | \`author\` | string? | |
3086
+ | \`tags\` | string[] | |
3087
+ | \`publishedAt\` | string? | ISO 8601; null = publish immediately |
3088
+ | \`seoTitle\` | string? | |
3089
+ | \`seoDescription\`| string? | |
3090
+ | \`ogImageUrl\` | string? | |
3091
+
3092
+ ### Rendering blog content
3093
+
3094
+ \`\`\`tsx
3095
+ // app/blog/[slug]/page.tsx
3096
+ import DOMPurify from 'isomorphic-dompurify';
3097
+
3098
+ const post = await brainerce.blog.getPost(params.slug);
3099
+ if (!post) notFound();
3100
+
3101
+ // Always sanitize before rendering HTML \u2014 treat external-origin content as untrusted
3102
+ const safeHtml = DOMPurify.sanitize(post.content);
3103
+ return <div dangerouslySetInnerHTML={{ __html: safeHtml }} className="prose" />;
3104
+ \`\`\`
3105
+
3106
+ The \`content\` field is HTML produced by the Lexical rich-text editor.
3107
+ **Always sanitize with DOMPurify (or equivalent) before rendering via
3108
+ \`dangerouslySetInnerHTML\`** \u2014 even though the content originates from your
3109
+ own editor, defense-in-depth prevents any stored-XSS path if content is ever
3110
+ migrated or imported from an external source.
3111
+ Apply a \`prose\` class (Tailwind Typography) for automatic styling.
3112
+
3113
+ ### REST endpoints
3114
+
3115
+ | Method | Path | Returns |
3116
+ |--------|------|---------|
3117
+ | GET | \`/api/stores/:storeId/blog/posts\` | \`BlogPostListResponse\` |
3118
+ | GET | \`/api/stores/:storeId/blog/posts/:slug\` | \`BlogPost\` or 404 |
3119
+ | GET | \`/api/vc/:connectionId/blog/posts\` | Same, channel-scoped |
3120
+ | GET | \`/api/vc/:connectionId/blog/posts/:slug\` | \`BlogPost\` or 404 |
3121
+ `;
3122
+ }
3123
+ function getStorefrontBotSection(connectionId) {
3124
+ return `## Storefront Bot (AI chat widget)
3125
+
3126
+ The store's AI shopping assistant. ALL configuration (name, avatar, colors,
3127
+ greeting, starter questions, capabilities, guardrails) lives in the merchant
3128
+ dashboard \u2014 the embed never decides behavior, and the widget renders nothing
3129
+ until the merchant switches the bot Live.
3130
+
3131
+ ### Zero-code embed (any site)
3132
+
3133
+ \`\`\`html
3134
+ <script src="https://cdn.brainerce.com/bot.js" data-connection-id="${connectionId}" defer></script>
3135
+ \`\`\`
3136
+
3137
+ Keep the tag exactly this bare \u2014 do NOT add \`integrity\` or \`crossorigin\`
3138
+ (the bootstrap is intentionally mutable; it is origin-pinned by CSP instead).
3139
+
3140
+ ### SDK mount (React / Next.js / any bundler)
3141
+
3142
+ \`\`\`ts
3143
+ import { BrainerceBot } from 'brainerce/bot';
3144
+
3145
+ // client-side only (e.g. in a useEffect) \u2014 mounts a floating chat bubble
3146
+ const bot = await BrainerceBot.mount({ connectionId: '${connectionId}' });
3147
+ bot?.destroy(); // optional teardown
3148
+ \`\`\`
3149
+
3150
+ \`mount\` resolves to \`null\` when the bot is disabled (FREE plan, switched
3151
+ off, or unconfigured) \u2014 safe to call unconditionally. Options: \`connectionId\`
3152
+ (required), \`baseUrl\` (API origin override), \`target\` (mount element),
3153
+ \`onAddToCart\` (\`({ productId, variantId, quantity }) => boolean | Promise<boolean>\`
3154
+ \u2014 route the widget's cart adds through the site's own cart; \`variantId\` is
3155
+ null for simple products; return false to fall back to the product page).
3156
+
3157
+ Behavior: persists an anonymous session in localStorage, restores the
3158
+ conversation on revisit, streams answers, and shows product recommendation
3159
+ cards (image, price, add-to-cart / view). Multi-variant products get an
3160
+ in-card variant picker; shoppers can also ask the assistant to add an item
3161
+ and it goes through the same cart chain. Zero-result searches feed the
3162
+ merchant's "unmet demand" analytics. Aside from shopper-initiated cart adds,
3163
+ the bot is read-only.
3164
+
3165
+ Add-to-cart resolution chain: \`onAddToCart\` option \u2192 cancelable
3166
+ \`brainerce:bot:add-to-cart\` CustomEvent on window
3167
+ (\`detail: { productId, variantId, quantity, connectionId }\`; call
3168
+ preventDefault() after handling) \u2192 navigate to the product page.
3169
+
3170
+ Rules:
3171
+ - Mount once per page; do not pass any visual config \u2014 the dashboard owns it.
3172
+ - Do not wrap or restyle the widget; it renders in its own Shadow DOM.
3173
+ - Product card links expect the conventional \`/products/<slug>\` route.
3174
+ - Wire \`onAddToCart\` to the site's cart (see the cart section) so the header
3175
+ count updates when the bot adds items.
3176
+ `;
3177
+ }
2856
3178
  function getSectionByTopic(topic, connectionId, currency) {
2857
3179
  const cid = connectionId || "vc_YOUR_CONNECTION_ID";
2858
3180
  const cur = currency || "USD";
@@ -2891,6 +3213,10 @@ function getSectionByTopic(topic, connectionId, currency) {
2891
3213
  return getTaxDisplaySection(cur);
2892
3214
  case "i18n":
2893
3215
  return getI18nSection();
3216
+ case "multilingual-seo":
3217
+ case "hreflang":
3218
+ case "seo-i18n":
3219
+ return getMultilingualSeoSection();
2894
3220
  case "critical-rules":
2895
3221
  return getCriticalRulesSection() + "\n\n" + getTypeQuickReference();
2896
3222
  case "type-reference":
@@ -2901,6 +3227,10 @@ function getSectionByTopic(topic, connectionId, currency) {
2901
3227
  return getContactInquiriesSection();
2902
3228
  case "content":
2903
3229
  return getContentSection();
3230
+ case "blog":
3231
+ return getBlogSection();
3232
+ case "storefront-bot":
3233
+ return getStorefrontBotSection(cid);
2904
3234
  case "all":
2905
3235
  return [
2906
3236
  "# Brainerce SDK \u2014 full topic dump",
@@ -2985,6 +3315,10 @@ function getSectionByTopic(topic, connectionId, currency) {
2985
3315
  "",
2986
3316
  "---",
2987
3317
  "",
3318
+ getMultilingualSeoSection(),
3319
+ "",
3320
+ "---",
3321
+ "",
2988
3322
  getAdminApiSection(),
2989
3323
  "",
2990
3324
  "---",
@@ -2993,10 +3327,18 @@ function getSectionByTopic(topic, connectionId, currency) {
2993
3327
  "",
2994
3328
  "---",
2995
3329
  "",
2996
- getContentSection()
3330
+ getContentSection(),
3331
+ "",
3332
+ "---",
3333
+ "",
3334
+ getBlogSection(),
3335
+ "",
3336
+ "---",
3337
+ "",
3338
+ getStorefrontBotSection(cid)
2997
3339
  ].join("\n");
2998
3340
  default:
2999
- return `Unknown topic: "${topic}". Available topics: setup, products, cart, checkout, checkout-custom-fields, payment, auth, order-confirmation, inventory, discounts, recommendations, product-customization-fields, tax, i18n, critical-rules, type-reference, admin, inquiries, content, all`;
3341
+ return `Unknown topic: "${topic}". Available topics: setup, products, cart, checkout, checkout-custom-fields, payment, auth, order-confirmation, inventory, discounts, recommendations, product-customization-fields, tax, i18n, critical-rules, type-reference, admin, inquiries, content, blog, all`;
3000
3342
  }
3001
3343
  }
3002
3344
 
@@ -3025,6 +3367,7 @@ var GET_SDK_DOCS_SCHEMA = {
3025
3367
  "admin",
3026
3368
  "inquiries",
3027
3369
  "content",
3370
+ "storefront-bot",
3028
3371
  "all"
3029
3372
  ]).describe("The SDK documentation topic to retrieve"),
3030
3373
  salesChannelId: import_zod.z.string().optional().describe("Sales channel ID (starts with vc_). Used to personalize setup code."),
@@ -3056,12 +3399,18 @@ interface Product {
3056
3399
  description?: string | null;
3057
3400
  descriptionFormat?: 'text' | 'html' | 'markdown' | null;
3058
3401
  sku: string;
3059
- basePrice: string; // Use parseFloat() for calculations
3060
- salePrice?: string | null;
3402
+ basePrice: string; // For VARIABLE products: MIN(variants.price). For SIMPLE: the parent price. parseFloat() for math.
3403
+ salePrice?: string | null; // For VARIABLE: MIN(variants.salePrice WHERE NOT NULL) \u2014 null iff no variant is on sale (WC is_on_sale() semantic). For SIMPLE: the parent sale price. Reliable "on sale?" check: product.salePrice !== null.
3061
3404
  costPrice?: string | null;
3062
- priceMin?: string | null; // Lowest variant price (VARIABLE products). Use for catalog/JSON-LD range display.
3063
- priceMax?: string | null; // Highest variant price (VARIABLE products).
3405
+ priceMin?: string | null; // Lowest variant price (VARIABLE products) \u2014 same as basePrice for VARIABLE, kept for back-compat and JSON-LD range display.
3406
+ priceMax?: string | null; // Highest variant price (VARIABLE products). Use with priceMin for "\u20AA49 \u2013 \u20AA199" range.
3064
3407
  priceVaries?: boolean; // true when variant prices differ \u2014 show "\u20AA49 \u2013 \u20AA199" range.
3408
+ // FX DISPLAY overlay (PRD \xA723). Set only when getProducts({ regionId }) was called AND region.currency !== store.currency. basePrice/salePrice above stay in store currency \u2014 these are additive, display-only. The buyer is still charged in store currency at checkout; payment provider handles customer-side FX.
3409
+ displayPrice?: string; // basePrice \xD7 daily FX rate, in displayCurrency.
3410
+ displaySalePrice?: string; // salePrice \xD7 rate (if salePrice present).
3411
+ displayPriceMin?: string; // priceMin \xD7 rate (VARIABLE products).
3412
+ displayPriceMax?: string; // priceMax \xD7 rate (VARIABLE products).
3413
+ displayCurrency?: string; // ISO 4217 of the region \u2014 e.g. "EUR".
3065
3414
  status: string;
3066
3415
  type: 'SIMPLE' | 'VARIABLE';
3067
3416
  isDownloadable?: boolean;
@@ -3105,6 +3454,10 @@ interface ProductVariant {
3105
3454
  name?: string | null;
3106
3455
  price?: string | null;
3107
3456
  salePrice?: string | null;
3457
+ // FX DISPLAY overlay (PRD \xA723) \u2014 same semantics as on the parent Product.
3458
+ displayPrice?: string;
3459
+ displaySalePrice?: string;
3460
+ displayCurrency?: string;
3108
3461
  attributes?: Record<string, string> | null;
3109
3462
  options?: Array<{ name: string; value: string }>;
3110
3463
  inventory?: InventoryInfo | null;
@@ -3176,6 +3529,11 @@ interface ProductQueryParams {
3176
3529
  metafields?: Record<string, string | string[]>;
3177
3530
  sortBy?: 'name' | 'price' | 'createdAt';
3178
3531
  sortOrder?: 'asc' | 'desc';
3532
+ // PRD \xA722: resolve DISPLAY prices for this region. When set + valid, each
3533
+ // product/variant gains resolvedPrice/resolvedCurrency/priceSource (additive;
3534
+ // basePrice/salePrice untouched). Absent/invalid region \u2192 nothing attached.
3535
+ // Display-only. Ignored in vibe-coded (vc_*) mode (storefront/admin paths only).
3536
+ regionId?: string;
3179
3537
  }
3180
3538
 
3181
3539
  interface SearchSuggestions {
@@ -3301,6 +3659,7 @@ interface Checkout {
3301
3659
  status: CheckoutStatus;
3302
3660
  email?: string | null;
3303
3661
  customerId?: string | null;
3662
+ regionId?: string | null; // multi-region: recorded for reporting + provider scoping (currency follows the cart until FX lands)
3304
3663
  shippingAddress?: CheckoutAddress | null;
3305
3664
  billingAddress?: CheckoutAddress | null;
3306
3665
  shippingRateId?: string | null;
@@ -3377,6 +3736,7 @@ interface CreateCheckoutDto {
3377
3736
  cartId: string;
3378
3737
  customerId?: string;
3379
3738
  selectedItemIds?: string[]; // Partial checkout
3739
+ regionId?: string; // multi-region: associate the checkout with a region (must belong to the store; 400 if unknown)
3380
3740
  }
3381
3741
 
3382
3742
  // startGuestCheckout() return type \u2014 DISCRIMINATED UNION
@@ -3395,6 +3755,8 @@ interface TaxBreakdownItem {
3395
3755
  name: string;
3396
3756
  rate: number; // decimal: 0.17 = 17%
3397
3757
  amount: number;
3758
+ taxClassId?: string | null; // rate's tax class (null = Standard)
3759
+ taxClassSlug?: string | null; // class slug for attribution (null = Standard)
3398
3760
  }`;
3399
3761
  var ORDERS_TYPES = `// ---- Orders ----
3400
3762
 
@@ -3452,6 +3814,7 @@ interface OrderItem {
3452
3814
  // Snapshot of buyer-submitted customization values captured at checkout.
3453
3815
  // Keyed by metafield slug. \`value\` is string[] for MULTI_SELECT / GALLERY, string otherwise.
3454
3816
  customizations?: Record<string, { label: string; value: string | string[]; type: string }>;
3817
+ taxClassSlug?: string; // frozen slug of the line's resolved tax class (omitted = Standard fallback)
3455
3818
  }
3456
3819
 
3457
3820
  interface OrderCustomer {
@@ -3634,7 +3997,7 @@ function formatPrice(priceString: string | number | undefined | null, options?:
3634
3997
  function getProductPrice(product: Pick<Product, 'basePrice' | 'salePrice'>): number;
3635
3998
  function getProductPriceInfo(product: Pick<Product, 'basePrice' | 'salePrice' | 'discount' | 'priceMin' | 'priceVaries'>): {
3636
3999
  price: number; originalPrice: number; isOnSale: boolean; discountAmount: number; discountPercent: number;
3637
- }; // Falls back to priceMin when basePrice=0 (VARIABLE products)
4000
+ }; // For VARIABLE products, basePrice/salePrice are pre-aggregated (MIN of variants) \u2014 the helper just reads them. Use this whenever you need an "on sale?" badge or a "X% off" label.
3638
4001
  function getVariantPrice(variant: Pick<ProductVariant, 'price' | 'salePrice'>, productBasePrice: string): number;
3639
4002
 
3640
4003
  // Cart helpers
@@ -4167,6 +4530,122 @@ export interface Content<T extends ContentType = ContentType> extends ContentSum
4167
4530
  // stale-while-revalidate=60. Storefront changes propagate within ~5 min
4168
4531
  // of the merchant publishing. Do not add extra client-side caching
4169
4532
  // beyond Next.js's default fetch cache.`;
4533
+ var REGIONS_TYPES = `// ---- Regions & Tax Classes (Admin mode, apiKey) ----
4534
+ // storeId is derived from the API key \u2014 never pass it on admin calls.
4535
+
4536
+ // ---- Regions ---- (scopes: regions:read / regions:write)
4537
+ // A region binds countries \u2192 currency + tax-display mode + payment providers.
4538
+ interface Region {
4539
+ id: string;
4540
+ accountId: string;
4541
+ storeId: string;
4542
+ name: string;
4543
+ slug: string;
4544
+ currency: string; // ISO 4217, e.g. "EUR"
4545
+ countries: string[]; // ISO 3166-1 alpha-2, e.g. ["DE","FR"]
4546
+ taxInclusive: boolean; // show prices tax-inclusive in this region?
4547
+ automaticTaxes: boolean;
4548
+ isDefault: boolean; // fallback when buyer's country maps to no region
4549
+ isActive: boolean;
4550
+ paymentProviders?: RegionPaymentProvider[];
4551
+ createdAt: string;
4552
+ updatedAt: string;
4553
+ }
4554
+
4555
+ interface RegionPaymentProvider {
4556
+ id: string;
4557
+ regionId: string;
4558
+ appInstallationId: string;
4559
+ isEnabled: boolean;
4560
+ createdAt: string;
4561
+ }
4562
+
4563
+ interface CreateRegionDto {
4564
+ name: string;
4565
+ currency: string; // ISO 4217
4566
+ countries: string[]; // ISO 3166-1 alpha-2
4567
+ taxInclusive?: boolean;
4568
+ automaticTaxes?: boolean;
4569
+ isDefault?: boolean;
4570
+ paymentProviderIds?: string[]; // AppInstallation IDs to enable here
4571
+ }
4572
+ interface UpdateRegionDto extends Partial<CreateRegionDto> { isActive?: boolean }
4573
+
4574
+ // client.detectRegion(country, regions): Region | null \u2014 pure, no network.
4575
+ // \u2192 region whose countries includes the code, else the default region, else null.
4576
+ // Pass the resolved regionId to createCheckout to associate the checkout with a
4577
+ // region (recorded for reporting + provider scoping; currency follows the cart
4578
+ // until FX price conversion lands).
4579
+ //
4580
+ // Storefront (public, no apiKey \u2014 storeId mode):
4581
+ interface PublicRegion {
4582
+ id: string; name: string; slug: string; currency: string;
4583
+ countries: string[]; taxInclusive: boolean; isDefault: boolean;
4584
+ }
4585
+ interface PublicRegionDetail extends PublicRegion {
4586
+ paymentProviders: Array<{ id: string; appId: string; name: string | null }>;
4587
+ }
4588
+ // getStoreRegions(): { data: PublicRegion[] } \u2014 active regions, default first.
4589
+ // getStoreRegion(regionId): PublicRegionDetail \u2014 one region + its providers.
4590
+ interface AutoRegionResponse {
4591
+ region: PublicRegion | null;
4592
+ matched: boolean; // true=country was in a region's list; false=fell back to default
4593
+ country: string; // upper-cased ISO-3166-1 alpha-2; '' when caller omitted it
4594
+ }
4595
+ // getAutoRegion(country): AutoRegionResponse \u2014 server-side resolution in one
4596
+ // round trip. Pair with the country your edge runtime extracts
4597
+ // (CF-IPCountry / request.geo.country / etc.) \u2014 Brainerce does NOT derive the
4598
+ // country from the request IP server-side (storefront != end-customer).
4599
+
4600
+ // ---- Tax Classes ---- (scopes: tax-classes:read / tax-classes:write)
4601
+ // Charge differential rates by product type. A TaxRate may target a class via
4602
+ // taxClassId; a rate with taxClassId=null is the Standard fallback. Per-line
4603
+ // resolution: variant \u2192 product \u2192 category \u2192 store default \u2192 null.
4604
+ interface TaxClass {
4605
+ id: string;
4606
+ accountId: string;
4607
+ storeId: string;
4608
+ name: string;
4609
+ slug: string; // kebab-case, unique per store
4610
+ description?: string | null;
4611
+ isDefault: boolean; // auto-applied to products without an explicit class
4612
+ createdAt: string;
4613
+ updatedAt: string;
4614
+ }
4615
+ interface CreateTaxClassDto { name: string; slug: string; description?: string; isDefault?: boolean }
4616
+ type UpdateTaxClassDto = Partial<CreateTaxClassDto>;
4617
+ // Bulk-assign a class to entities:
4618
+ interface AssignTaxClassDto { productIds?: string[]; variantIds?: string[]; categoryIds?: string[] }
4619
+
4620
+ // TaxRate / CreateTaxRateDto carry an optional taxClassId (null = Standard).
4621
+ // rate is a WHOLE PERCENTAGE (7.25 = 7.25%).
4622
+ //
4623
+ // SDK methods (admin):
4624
+ // Regions: getRegions(), getRegion(id), createRegion(dto), updateRegion(id, dto),
4625
+ // deleteRegion(id), setDefaultRegion(id), updateRegionPaymentProviders(id, ids),
4626
+ // addRegionCountries(id, codes), removeRegionCountry(id, code),
4627
+ // getRegionCompatibleProviders(id), detectRegion(country, regions)
4628
+ // Tax classes: getTaxClasses(), getTaxClass(id), createTaxClass(dto), updateTaxClass(id, dto),
4629
+ // deleteTaxClass(id), setDefaultTaxClass(id), assignTaxClass(id, dto),
4630
+ // mergeTaxClasses(id, targetId)
4631
+ //
4632
+ // SDK methods (storefront, public \u2014 storeId mode, no apiKey):
4633
+ // getStoreRegions(), getStoreRegion(id), getAutoRegion(country)
4634
+ // getStoreTaxClasses(), estimateTax({ country?, subtotal })
4635
+ //
4636
+ // estimateTax returns:
4637
+ interface TaxEstimateResponse {
4638
+ appliesTax: boolean;
4639
+ rate: number | null; // percent (18 = 18%) \u2014 null when no matching rule
4640
+ rateName: string | null;
4641
+ estimatedTax: number; // tax portion of subtotal in store currency
4642
+ pricesIncludeTax: boolean;
4643
+ currency: string; // store currency (cart/order currency)
4644
+ note: string; // disclaimer \u2014 preview is non-binding
4645
+ }
4646
+ // Non-binding by design: the authoritative tax runs at checkout against the
4647
+ // full shipping address. The country comes from your edge runtime
4648
+ // (CF-IPCountry / request.geo.country / etc.), NOT the request IP.`;
4170
4649
  var TYPES_BY_DOMAIN = {
4171
4650
  products: PRODUCTS_TYPES,
4172
4651
  cart: CART_TYPES,
@@ -4178,7 +4657,8 @@ var TYPES_BY_DOMAIN = {
4178
4657
  inquiries: INQUIRIES_TYPES,
4179
4658
  reviews: REVIEWS_TYPES,
4180
4659
  "modifier-groups": MODIFIER_GROUPS_TYPES,
4181
- content: CONTENT_TYPES
4660
+ content: CONTENT_TYPES,
4661
+ regions: REGIONS_TYPES
4182
4662
  };
4183
4663
  function getTypesByDomain(domain) {
4184
4664
  if (domain === "all") {
@@ -4209,10 +4689,12 @@ var GET_TYPE_DEFINITIONS_SCHEMA = {
4209
4689
  "helpers",
4210
4690
  "inquiries",
4211
4691
  "reviews",
4692
+ "modifier-groups",
4212
4693
  "content",
4694
+ "regions",
4213
4695
  "all"
4214
4696
  ]).describe(
4215
- 'The domain of types to retrieve. Use "helpers" for helper function signatures and common types like StoreInfo, PaginatedResponse. Use "content" for FAQ / Footer / Header / Announcement / RichText / Page.'
4697
+ 'The domain of types to retrieve. Use "helpers" for helper function signatures and common types like StoreInfo, PaginatedResponse. Use "content" for FAQ / Footer / Header / Announcement / RichText / Page. Use "regions" for Region / TaxClass admin types.'
4216
4698
  )
4217
4699
  };
4218
4700
  async function handleGetTypeDefinitions(args) {
@@ -6002,11 +6484,16 @@ Build both steps EVEN IF the store has no email provider configured today \u2014
6002
6484
  });
6003
6485
  window.location.href = authorizationUrl; // full-page redirect, NOT a popup
6004
6486
  \`\`\`
6005
- 3. **On the callback page** the URL contains \`token\` + \`oauth_success\` (or \`oauth_error\`) query params. Extract and apply the token:
6487
+ 3. **On the callback page** the URL contains \`auth_code\` + \`oauth_success\` (or \`oauth_error\`) query params. Exchange the single-use code for the JWT \u2014 never read the token from the URL:
6006
6488
  \`\`\`ts
6007
- const token = new URLSearchParams(location.search).get('token');
6008
- if (token) client.setCustomerToken(token); // then redirect to account
6489
+ const params = new URLSearchParams(location.search);
6490
+ const code = params.get('auth_code');
6491
+ if (code) {
6492
+ const result = await client.exchangeOAuthCode(code);
6493
+ client.setCustomerToken(result.token); // then redirect to account
6494
+ }
6009
6495
  \`\`\`
6496
+ The legacy \`?token=\` URL param is still emitted for backward compatibility but will be removed in the next major release \u2014 migrate to \`auth_code\` now.
6010
6497
  4. **On \`oauth_error\`:** redirect to login with an error message.
6011
6498
 
6012
6499
  Build the OAuth button region AND the callback handler even when no providers are configured. They auto-hide.`
@@ -6488,7 +6975,9 @@ function renderCapabilitiesSummary(caps) {
6488
6975
  );
6489
6976
  lines.push(`- Downloadable products: ${caps.features.hasDownloadableProducts ? "yes" : "no"}`);
6490
6977
  lines.push(`- Checkout custom fields: ${caps.features.hasCheckoutCustomFields ? "yes" : "no"}`);
6491
- lines.push(`- Content (FAQ/footer/header/announcements/pages): ${caps.features.hasContent ? "seeded" : "none \u2014 build chrome UI with fallbacks"}`);
6978
+ lines.push(
6979
+ `- Content (FAQ/footer/header/announcements/pages): ${caps.features.hasContent ? "seeded" : "none \u2014 build chrome UI with fallbacks"}`
6980
+ );
6492
6981
  lines.push(
6493
6982
  `- Email verification: ${caps.connection.requireEmailVerification ? "required" : "not required (still build the verify-email flow)"}`
6494
6983
  );
@@ -6817,14 +7306,149 @@ function createServer() {
6817
7306
 
6818
7307
  // src/bin/http.ts
6819
7308
  var PORT = parseInt(process.env.PORT || "3100", 10);
6820
- var CORS_ORIGIN = process.env.CORS_ORIGIN || "*";
6821
7309
  var SSE_KEEPALIVE_MS = 1e4;
6822
7310
  var SESSION_MAX_AGE_MS = 4 * 60 * 60 * 1e3;
7311
+ var NODE_ENV = process.env.NODE_ENV || "development";
7312
+ var IS_DEV = NODE_ENV === "development";
7313
+ var AUTH_TOKENS = (process.env.MCP_AUTH_TOKENS || "").split(",").map((t) => t.trim()).filter((t) => t.length > 0).map((t) => Buffer.from(t, "utf8"));
7314
+ if (AUTH_TOKENS.length === 0 && !IS_DEV) {
7315
+ console.error(
7316
+ "FATAL: MCP_AUTH_TOKENS is not set. The MCP HTTP server must run with at least one Bearer token in non-development environments.\nMint a token (e.g., `mcp_<random>`) via the dashboard and add it (comma-separated) to MCP_AUTH_TOKENS."
7317
+ );
7318
+ process.exit(1);
7319
+ }
7320
+ if (AUTH_TOKENS.length === 0 && IS_DEV) {
7321
+ console.warn(
7322
+ "WARN: MCP_AUTH_TOKENS is not set. Running in development mode \u2014 any non-empty Bearer token will be accepted."
7323
+ );
7324
+ }
7325
+ var ALLOWED_ORIGINS = (process.env.MCP_ALLOWED_ORIGINS || "").split(",").map((o) => o.trim()).filter((o) => o.length > 0);
7326
+ var LOCALHOST_ORIGIN_RE = /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/;
7327
+ var RATE_LIMIT_WINDOW_MS = parseInt(process.env.MCP_RATE_LIMIT_WINDOW_MS || "60000", 10);
7328
+ var RATE_LIMIT_MAX = parseInt(process.env.MCP_RATE_LIMIT_MAX || "60", 10);
7329
+ var rateBuckets = /* @__PURE__ */ new Map();
7330
+ var MAX_BODY_BYTES = parseInt(process.env.MCP_MAX_BODY_BYTES || String(100 * 1024), 10);
7331
+ function safeEqual(a, b) {
7332
+ if (a.length !== b.length) {
7333
+ const max = Math.max(a.length, b.length);
7334
+ const ax = Buffer.alloc(max);
7335
+ const bx = Buffer.alloc(max);
7336
+ a.copy(ax);
7337
+ b.copy(bx);
7338
+ (0, import_node_crypto.timingSafeEqual)(ax, bx);
7339
+ return false;
7340
+ }
7341
+ return (0, import_node_crypto.timingSafeEqual)(a, b);
7342
+ }
7343
+ function authenticate(req, res) {
7344
+ const header = req.headers["authorization"];
7345
+ if (typeof header !== "string" || !header.toLowerCase().startsWith("bearer ")) {
7346
+ writeJson(res, 401, {
7347
+ error: "Missing or malformed Authorization header. Expected: Bearer <token>."
7348
+ });
7349
+ return false;
7350
+ }
7351
+ const presented = header.slice(7).trim();
7352
+ if (presented.length === 0) {
7353
+ writeJson(res, 401, { error: "Empty Bearer token." });
7354
+ return false;
7355
+ }
7356
+ if (AUTH_TOKENS.length === 0 && IS_DEV) {
7357
+ return true;
7358
+ }
7359
+ const presentedBuf = Buffer.from(presented, "utf8");
7360
+ let matched = false;
7361
+ for (const token of AUTH_TOKENS) {
7362
+ if (safeEqual(presentedBuf, token)) {
7363
+ matched = true;
7364
+ }
7365
+ }
7366
+ if (!matched) {
7367
+ writeJson(res, 401, { error: "Invalid Bearer token." });
7368
+ return false;
7369
+ }
7370
+ return true;
7371
+ }
7372
+ function clientIp(req) {
7373
+ const xff = req.headers["x-forwarded-for"];
7374
+ if (typeof xff === "string" && xff.length > 0) {
7375
+ return xff.split(",")[0].trim();
7376
+ }
7377
+ return req.socket.remoteAddress || "unknown";
7378
+ }
7379
+ function rateLimit(req, res) {
7380
+ const ip = clientIp(req);
7381
+ const now = Date.now();
7382
+ const bucket = rateBuckets.get(ip);
7383
+ if (!bucket || bucket.resetAt <= now) {
7384
+ rateBuckets.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS });
7385
+ return true;
7386
+ }
7387
+ if (bucket.count >= RATE_LIMIT_MAX) {
7388
+ const retryAfter = Math.max(1, Math.ceil((bucket.resetAt - now) / 1e3));
7389
+ res.setHeader("Retry-After", String(retryAfter));
7390
+ writeJson(res, 429, { error: "Rate limit exceeded. Try again later." });
7391
+ return false;
7392
+ }
7393
+ bucket.count += 1;
7394
+ return true;
7395
+ }
7396
+ var rateLimitGcTimer = setInterval(
7397
+ () => {
7398
+ const now = Date.now();
7399
+ for (const [ip, bucket] of rateBuckets) {
7400
+ if (bucket.resetAt <= now) rateBuckets.delete(ip);
7401
+ }
7402
+ },
7403
+ 5 * 60 * 1e3
7404
+ );
7405
+ rateLimitGcTimer.unref();
7406
+ function resolveCorsOrigin(origin) {
7407
+ if (!origin) return null;
7408
+ if (ALLOWED_ORIGINS.includes(origin)) return origin;
7409
+ if (IS_DEV && LOCALHOST_ORIGIN_RE.test(origin)) return origin;
7410
+ return null;
7411
+ }
7412
+ function setCors(req, res) {
7413
+ const origin = typeof req.headers.origin === "string" ? req.headers.origin : void 0;
7414
+ const allowed = resolveCorsOrigin(origin);
7415
+ if (allowed) {
7416
+ res.setHeader("Access-Control-Allow-Origin", allowed);
7417
+ res.setHeader("Vary", "Origin");
7418
+ }
7419
+ res.setHeader("Access-Control-Allow-Credentials", "false");
7420
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
7421
+ res.setHeader(
7422
+ "Access-Control-Allow-Headers",
7423
+ "Content-Type, Accept, Authorization, Mcp-Session-Id"
7424
+ );
7425
+ res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id");
7426
+ }
7427
+ function writeJson(res, status, body) {
7428
+ if (res.headersSent) return;
7429
+ res.writeHead(status, { "Content-Type": "application/json" });
7430
+ res.end(JSON.stringify(body));
7431
+ }
6823
7432
  function parseBody(req) {
6824
7433
  return new Promise((resolve, reject) => {
6825
7434
  const chunks = [];
6826
- req.on("data", (chunk) => chunks.push(chunk));
7435
+ let total = 0;
7436
+ let aborted = false;
7437
+ req.on("data", (chunk) => {
7438
+ if (aborted) return;
7439
+ total += chunk.length;
7440
+ if (total > MAX_BODY_BYTES) {
7441
+ aborted = true;
7442
+ const err = new Error("Request body exceeds maximum allowed size");
7443
+ err.statusCode = 413;
7444
+ reject(err);
7445
+ req.destroy();
7446
+ return;
7447
+ }
7448
+ chunks.push(chunk);
7449
+ });
6827
7450
  req.on("end", () => {
7451
+ if (aborted) return;
6828
7452
  if (chunks.length === 0) return resolve(void 0);
6829
7453
  try {
6830
7454
  resolve(JSON.parse(Buffer.concat(chunks).toString()));
@@ -6861,14 +7485,8 @@ async function main() {
6861
7485
  5 * 60 * 1e3
6862
7486
  );
6863
7487
  cleanupTimer.unref();
6864
- function setCors(res) {
6865
- res.setHeader("Access-Control-Allow-Origin", CORS_ORIGIN);
6866
- res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
6867
- res.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Mcp-Session-Id");
6868
- res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id");
6869
- }
6870
7488
  const httpServer = (0, import_node_http.createServer)(async (req, res) => {
6871
- setCors(res);
7489
+ setCors(req, res);
6872
7490
  if (req.method === "OPTIONS") {
6873
7491
  res.writeHead(204);
6874
7492
  res.end();
@@ -6885,6 +7503,8 @@ async function main() {
6885
7503
  );
6886
7504
  return;
6887
7505
  }
7506
+ if (!rateLimit(req, res)) return;
7507
+ if (!authenticate(req, res)) return;
6888
7508
  if (req.url === "/mcp") {
6889
7509
  try {
6890
7510
  const server = createServer();
@@ -6897,8 +7517,7 @@ async function main() {
6897
7517
  } catch (error) {
6898
7518
  console.error("MCP request error:", error);
6899
7519
  if (!res.headersSent) {
6900
- res.writeHead(500, { "Content-Type": "application/json" });
6901
- res.end(JSON.stringify({ error: "Internal server error" }));
7520
+ writeJson(res, 500, { error: "Internal server error" });
6902
7521
  }
6903
7522
  }
6904
7523
  return;
@@ -6939,8 +7558,7 @@ async function main() {
6939
7558
  } catch (error) {
6940
7559
  console.error("SSE connection error:", error);
6941
7560
  if (!res.headersSent) {
6942
- res.writeHead(500, { "Content-Type": "application/json" });
6943
- res.end(JSON.stringify({ error: "Internal server error" }));
7561
+ writeJson(res, 500, { error: "Internal server error" });
6944
7562
  }
6945
7563
  }
6946
7564
  return;
@@ -6949,8 +7567,7 @@ async function main() {
6949
7567
  const url = new URL(req.url, `http://${req.headers.host || "localhost"}`);
6950
7568
  const sessionId = url.searchParams.get("sessionId");
6951
7569
  if (!sessionId || !sseSessions.has(sessionId)) {
6952
- res.writeHead(400, { "Content-Type": "application/json" });
6953
- res.end(JSON.stringify({ error: "Invalid or missing sessionId" }));
7570
+ writeJson(res, 400, { error: "Invalid or missing sessionId" });
6954
7571
  return;
6955
7572
  }
6956
7573
  try {
@@ -6958,20 +7575,23 @@ async function main() {
6958
7575
  const body = await parseBody(req);
6959
7576
  await session.transport.handlePostMessage(req, res, body);
6960
7577
  } catch (error) {
6961
- console.error("SSE message error:", error);
7578
+ const status = error && typeof error === "object" && "statusCode" in error ? error.statusCode || 500 : 500;
7579
+ if (status !== 500) {
7580
+ console.warn("SSE message rejected:", error.message);
7581
+ } else {
7582
+ console.error("SSE message error:", error);
7583
+ }
6962
7584
  if (!res.headersSent) {
6963
- res.writeHead(500, { "Content-Type": "application/json" });
6964
- res.end(JSON.stringify({ error: "Internal server error" }));
7585
+ writeJson(res, status, {
7586
+ error: status === 413 ? "Payload too large" : "Internal server error"
7587
+ });
6965
7588
  }
6966
7589
  }
6967
7590
  return;
6968
7591
  }
6969
- res.writeHead(404, { "Content-Type": "application/json" });
6970
- res.end(
6971
- JSON.stringify({
6972
- error: "Not found. Use /mcp (Streamable HTTP), /sse (legacy SSE), or /health."
6973
- })
6974
- );
7592
+ writeJson(res, 404, {
7593
+ error: "Not found. Use /mcp (Streamable HTTP), /sse (legacy SSE), or /health."
7594
+ });
6975
7595
  });
6976
7596
  function shutdown(signal) {
6977
7597
  console.info(`
@@ -6999,6 +7619,16 @@ ${signal} received \u2014 shutting down gracefully...`);
6999
7619
  console.info(` Streamable HTTP: http://localhost:${PORT}/mcp`);
7000
7620
  console.info(` Legacy SSE: http://localhost:${PORT}/sse`);
7001
7621
  console.info(` Health check: http://localhost:${PORT}/health`);
7622
+ console.info(
7623
+ ` Auth tokens: ${AUTH_TOKENS.length} configured${AUTH_TOKENS.length === 0 && IS_DEV ? " (dev: any non-empty Bearer accepted)" : ""}`
7624
+ );
7625
+ console.info(
7626
+ ` CORS: ${ALLOWED_ORIGINS.length} allow-listed origin(s)${IS_DEV ? " + localhost (dev)" : ""}`
7627
+ );
7628
+ console.info(
7629
+ ` Rate limit: ${RATE_LIMIT_MAX} req / ${Math.round(RATE_LIMIT_WINDOW_MS / 1e3)}s per IP`
7630
+ );
7631
+ console.info(` Max body: ${MAX_BODY_BYTES} bytes`);
7002
7632
  });
7003
7633
  }
7004
7634
  main().catch((error) => {