@brainerce/mcp-server 3.8.0 → 3.9.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 +388 -44
- package/dist/bin/stdio.js +222 -20
- package/dist/index.js +222 -20
- package/dist/index.mjs +222 -20
- package/package.json +1 -1
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
|
|
|
@@ -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
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
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
|
|
@@ -2359,7 +2381,9 @@ const admin = new BrainerceClient({ apiKey: 'brainerce_...' });
|
|
|
2359
2381
|
|
|
2360
2382
|
// Taxonomy: listCategories(), listBrands(), listTags(), listAttributes()
|
|
2361
2383
|
// Shipping: listShippingZones(), createZoneShippingRate()
|
|
2362
|
-
// Tax: getTaxRates(), createTaxRate()
|
|
2384
|
+
// Tax: getTaxRates(), createTaxRate() \u2014 a rate may target a tax class via taxClassId
|
|
2385
|
+
// Tax classes: getTaxClasses(), createTaxClass(), assignTaxClass(), mergeTaxClasses() (scope tax-classes:*)
|
|
2386
|
+
// Regions: getRegions(), createRegion(), setDefaultRegion(), updateRegionPaymentProviders() (scope regions:*)
|
|
2363
2387
|
// Metafields: getMetafieldDefinitions(), setProductMetafield()
|
|
2364
2388
|
// Team: getTeamMembers(), inviteTeamMember()
|
|
2365
2389
|
// Email: getEmailTemplates(), createEmailTemplate()
|
|
@@ -2367,6 +2391,13 @@ const admin = new BrainerceClient({ apiKey: 'brainerce_...' });
|
|
|
2367
2391
|
// OAuth: getOAuthProviders(), configureOAuthProvider()
|
|
2368
2392
|
\`\`\`
|
|
2369
2393
|
|
|
2394
|
+
Store-level team management (\`inviteStoreMember\`, \`updateStoreMember\`) is the
|
|
2395
|
+
canonical replacement for the deprecated account-level helpers above. The
|
|
2396
|
+
invite accepts an optional \`salesChannelIds\` (vibe-coded \`connectionId\`s,
|
|
2397
|
+
\`vc_*\`) to restrict a member to specific channels \u2014 omit or pass \`[]\` for all
|
|
2398
|
+
channels. Use \`updateStoreMemberSalesChannels(storeId, memberId, { salesChannelIds })\`
|
|
2399
|
+
to change that scope later.
|
|
2400
|
+
|
|
2370
2401
|
### Per-Channel Publishing
|
|
2371
2402
|
|
|
2372
2403
|
Categories, tags, brands, and metafield definitions are gated to specific
|
|
@@ -2398,7 +2429,70 @@ calls fail with \`404 Not Found\`.
|
|
|
2398
2429
|
|
|
2399
2430
|
The vibe-coded read endpoints (used by storefront SDK calls in \`connectionId\`
|
|
2400
2431
|
mode) automatically filter by these junction tables, so storefronts never see
|
|
2401
|
-
entities that weren't published to their site
|
|
2432
|
+
entities that weren't published to their site.
|
|
2433
|
+
|
|
2434
|
+
### Tax classes (differential tax rates)
|
|
2435
|
+
|
|
2436
|
+
Charge different rates for different product types. A \`TaxRate\` may target a
|
|
2437
|
+
class via \`taxClassId\`; a rate with \`taxClassId: null\` is the **Standard
|
|
2438
|
+
fallback**. Checkout resolves each line's class **variant \u2192 product \u2192 category
|
|
2439
|
+
\u2192 store default \u2192 null**, then picks the matching rate (Standard if none).
|
|
2440
|
+
\`rate\` is a whole percentage (\`7.25\` = 7.25%). Requires the
|
|
2441
|
+
\`tax-classes:read\` / \`tax-classes:write\` scopes.
|
|
2442
|
+
|
|
2443
|
+
\`\`\`typescript
|
|
2444
|
+
const food = await admin.createTaxClass({ name: 'Food', slug: 'food' });
|
|
2445
|
+
await admin.assignTaxClass(food.id, { productIds: ['prod_1'], categoryIds: ['cat_food'] });
|
|
2446
|
+
|
|
2447
|
+
// class-specific rate \u2014 only food lines use it; everything else uses Standard
|
|
2448
|
+
await admin.createTaxRate({ name: 'VAT (Food)', rate: 0, country: 'GB', taxClassId: food.id });
|
|
2449
|
+
|
|
2450
|
+
// delete is blocked (409) while dependents exist \u2014 merge moves FKs then deletes:
|
|
2451
|
+
await admin.mergeTaxClasses(food.id, standardClassId);
|
|
2452
|
+
\`\`\`
|
|
2453
|
+
|
|
2454
|
+
Storefront (public, no apiKey \u2014 \`storeId\` mode): \`getStoreTaxClasses()\` lists
|
|
2455
|
+
the store's classes (storefront-safe fields only) for a transparency badge.
|
|
2456
|
+
|
|
2457
|
+
### Regions (multi-currency / per-region providers)
|
|
2458
|
+
|
|
2459
|
+
A region binds countries \u2192 currency + tax-display mode + enabled payment
|
|
2460
|
+
providers. Manage them via the SDK (scopes \`regions:read\` / \`regions:write\`).
|
|
2461
|
+
\`detectRegion\` is a pure client-side helper to map a buyer's country to a
|
|
2462
|
+
region; pass the resolved \`regionId\` to \`createCheckout\` to associate the
|
|
2463
|
+
checkout with a region (recorded for reporting + provider scoping; currency
|
|
2464
|
+
follows the cart until FX price conversion lands).
|
|
2465
|
+
|
|
2466
|
+
\`\`\`typescript
|
|
2467
|
+
const eu = await admin.createRegion({
|
|
2468
|
+
name: 'EU', currency: 'EUR', countries: ['DE', 'FR'],
|
|
2469
|
+
taxInclusive: true, paymentProviderIds: ['app_inst_stripe'],
|
|
2470
|
+
});
|
|
2471
|
+
await admin.setDefaultRegion(eu.id);
|
|
2472
|
+
|
|
2473
|
+
const { data: regions } = await admin.getRegions();
|
|
2474
|
+
const region = admin.detectRegion('DE', regions); // \u2192 eu, else default, else null
|
|
2475
|
+
\`\`\`
|
|
2476
|
+
|
|
2477
|
+
Storefront (public, no apiKey \u2014 \`storeId\` mode): \`getStoreRegions()\` lists
|
|
2478
|
+
active regions, \`getStoreRegion(id)\` returns one region + its payment providers.
|
|
2479
|
+
Pair with \`detectRegion\` to pick the buyer's region for currency display.
|
|
2480
|
+
|
|
2481
|
+
\`\`\`typescript
|
|
2482
|
+
const store = new BrainerceClient({ storeId: 'store_123' });
|
|
2483
|
+
const { data: regions } = await store.getStoreRegions();
|
|
2484
|
+
const region = await store.getStoreRegion(regions[0].id);
|
|
2485
|
+
\`\`\`
|
|
2486
|
+
|
|
2487
|
+
A shipping zone can be limited to regions via \`regionIds\` \u2014 the zone is then
|
|
2488
|
+
only offered to checkouts that resolved to one of those regions. Empty/omitted =
|
|
2489
|
+
available for any region (default); each id must belong to the same store.
|
|
2490
|
+
|
|
2491
|
+
\`\`\`typescript
|
|
2492
|
+
await admin.createShippingZone({
|
|
2493
|
+
name: 'EU Express', countries: ['DE', 'FR', 'IT'], regionIds: [eu.id],
|
|
2494
|
+
});
|
|
2495
|
+
\`\`\``;
|
|
2402
2496
|
}
|
|
2403
2497
|
function getContactInquiriesSection() {
|
|
2404
2498
|
return `## Contact Inquiries & Forms (optional)
|
|
@@ -3056,11 +3150,11 @@ interface Product {
|
|
|
3056
3150
|
description?: string | null;
|
|
3057
3151
|
descriptionFormat?: 'text' | 'html' | 'markdown' | null;
|
|
3058
3152
|
sku: string;
|
|
3059
|
-
basePrice: string; //
|
|
3060
|
-
salePrice?: string | null;
|
|
3153
|
+
basePrice: string; // For VARIABLE products: MIN(variants.price). For SIMPLE: the parent price. parseFloat() for math.
|
|
3154
|
+
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
3155
|
costPrice?: string | null;
|
|
3062
|
-
priceMin?: string | null; // Lowest variant price (VARIABLE products)
|
|
3063
|
-
priceMax?: string | null; // Highest variant price (VARIABLE products).
|
|
3156
|
+
priceMin?: string | null; // Lowest variant price (VARIABLE products) \u2014 same as basePrice for VARIABLE, kept for back-compat and JSON-LD range display.
|
|
3157
|
+
priceMax?: string | null; // Highest variant price (VARIABLE products). Use with priceMin for "\u20AA49 \u2013 \u20AA199" range.
|
|
3064
3158
|
priceVaries?: boolean; // true when variant prices differ \u2014 show "\u20AA49 \u2013 \u20AA199" range.
|
|
3065
3159
|
status: string;
|
|
3066
3160
|
type: 'SIMPLE' | 'VARIABLE';
|
|
@@ -3176,6 +3270,11 @@ interface ProductQueryParams {
|
|
|
3176
3270
|
metafields?: Record<string, string | string[]>;
|
|
3177
3271
|
sortBy?: 'name' | 'price' | 'createdAt';
|
|
3178
3272
|
sortOrder?: 'asc' | 'desc';
|
|
3273
|
+
// PRD \xA722: resolve DISPLAY prices for this region. When set + valid, each
|
|
3274
|
+
// product/variant gains resolvedPrice/resolvedCurrency/priceSource (additive;
|
|
3275
|
+
// basePrice/salePrice untouched). Absent/invalid region \u2192 nothing attached.
|
|
3276
|
+
// Display-only. Ignored in vibe-coded (vc_*) mode (storefront/admin paths only).
|
|
3277
|
+
regionId?: string;
|
|
3179
3278
|
}
|
|
3180
3279
|
|
|
3181
3280
|
interface SearchSuggestions {
|
|
@@ -3301,6 +3400,7 @@ interface Checkout {
|
|
|
3301
3400
|
status: CheckoutStatus;
|
|
3302
3401
|
email?: string | null;
|
|
3303
3402
|
customerId?: string | null;
|
|
3403
|
+
regionId?: string | null; // multi-region: recorded for reporting + provider scoping (currency follows the cart until FX lands)
|
|
3304
3404
|
shippingAddress?: CheckoutAddress | null;
|
|
3305
3405
|
billingAddress?: CheckoutAddress | null;
|
|
3306
3406
|
shippingRateId?: string | null;
|
|
@@ -3377,6 +3477,7 @@ interface CreateCheckoutDto {
|
|
|
3377
3477
|
cartId: string;
|
|
3378
3478
|
customerId?: string;
|
|
3379
3479
|
selectedItemIds?: string[]; // Partial checkout
|
|
3480
|
+
regionId?: string; // multi-region: associate the checkout with a region (must belong to the store; 400 if unknown)
|
|
3380
3481
|
}
|
|
3381
3482
|
|
|
3382
3483
|
// startGuestCheckout() return type \u2014 DISCRIMINATED UNION
|
|
@@ -3395,6 +3496,8 @@ interface TaxBreakdownItem {
|
|
|
3395
3496
|
name: string;
|
|
3396
3497
|
rate: number; // decimal: 0.17 = 17%
|
|
3397
3498
|
amount: number;
|
|
3499
|
+
taxClassId?: string | null; // rate's tax class (null = Standard)
|
|
3500
|
+
taxClassSlug?: string | null; // class slug for attribution (null = Standard)
|
|
3398
3501
|
}`;
|
|
3399
3502
|
var ORDERS_TYPES = `// ---- Orders ----
|
|
3400
3503
|
|
|
@@ -3452,6 +3555,7 @@ interface OrderItem {
|
|
|
3452
3555
|
// Snapshot of buyer-submitted customization values captured at checkout.
|
|
3453
3556
|
// Keyed by metafield slug. \`value\` is string[] for MULTI_SELECT / GALLERY, string otherwise.
|
|
3454
3557
|
customizations?: Record<string, { label: string; value: string | string[]; type: string }>;
|
|
3558
|
+
taxClassSlug?: string; // frozen slug of the line's resolved tax class (omitted = Standard fallback)
|
|
3455
3559
|
}
|
|
3456
3560
|
|
|
3457
3561
|
interface OrderCustomer {
|
|
@@ -3634,7 +3738,7 @@ function formatPrice(priceString: string | number | undefined | null, options?:
|
|
|
3634
3738
|
function getProductPrice(product: Pick<Product, 'basePrice' | 'salePrice'>): number;
|
|
3635
3739
|
function getProductPriceInfo(product: Pick<Product, 'basePrice' | 'salePrice' | 'discount' | 'priceMin' | 'priceVaries'>): {
|
|
3636
3740
|
price: number; originalPrice: number; isOnSale: boolean; discountAmount: number; discountPercent: number;
|
|
3637
|
-
}; //
|
|
3741
|
+
}; // 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
3742
|
function getVariantPrice(variant: Pick<ProductVariant, 'price' | 'salePrice'>, productBasePrice: string): number;
|
|
3639
3743
|
|
|
3640
3744
|
// Cart helpers
|
|
@@ -4167,6 +4271,95 @@ export interface Content<T extends ContentType = ContentType> extends ContentSum
|
|
|
4167
4271
|
// stale-while-revalidate=60. Storefront changes propagate within ~5 min
|
|
4168
4272
|
// of the merchant publishing. Do not add extra client-side caching
|
|
4169
4273
|
// beyond Next.js's default fetch cache.`;
|
|
4274
|
+
var REGIONS_TYPES = `// ---- Regions & Tax Classes (Admin mode, apiKey) ----
|
|
4275
|
+
// storeId is derived from the API key \u2014 never pass it on admin calls.
|
|
4276
|
+
|
|
4277
|
+
// ---- Regions ---- (scopes: regions:read / regions:write)
|
|
4278
|
+
// A region binds countries \u2192 currency + tax-display mode + payment providers.
|
|
4279
|
+
interface Region {
|
|
4280
|
+
id: string;
|
|
4281
|
+
accountId: string;
|
|
4282
|
+
storeId: string;
|
|
4283
|
+
name: string;
|
|
4284
|
+
slug: string;
|
|
4285
|
+
currency: string; // ISO 4217, e.g. "EUR"
|
|
4286
|
+
countries: string[]; // ISO 3166-1 alpha-2, e.g. ["DE","FR"]
|
|
4287
|
+
taxInclusive: boolean; // show prices tax-inclusive in this region?
|
|
4288
|
+
automaticTaxes: boolean;
|
|
4289
|
+
isDefault: boolean; // fallback when buyer's country maps to no region
|
|
4290
|
+
isActive: boolean;
|
|
4291
|
+
paymentProviders?: RegionPaymentProvider[];
|
|
4292
|
+
createdAt: string;
|
|
4293
|
+
updatedAt: string;
|
|
4294
|
+
}
|
|
4295
|
+
|
|
4296
|
+
interface RegionPaymentProvider {
|
|
4297
|
+
id: string;
|
|
4298
|
+
regionId: string;
|
|
4299
|
+
appInstallationId: string;
|
|
4300
|
+
isEnabled: boolean;
|
|
4301
|
+
createdAt: string;
|
|
4302
|
+
}
|
|
4303
|
+
|
|
4304
|
+
interface CreateRegionDto {
|
|
4305
|
+
name: string;
|
|
4306
|
+
currency: string; // ISO 4217
|
|
4307
|
+
countries: string[]; // ISO 3166-1 alpha-2
|
|
4308
|
+
taxInclusive?: boolean;
|
|
4309
|
+
automaticTaxes?: boolean;
|
|
4310
|
+
isDefault?: boolean;
|
|
4311
|
+
paymentProviderIds?: string[]; // AppInstallation IDs to enable here
|
|
4312
|
+
}
|
|
4313
|
+
interface UpdateRegionDto extends Partial<CreateRegionDto> { isActive?: boolean }
|
|
4314
|
+
|
|
4315
|
+
// client.detectRegion(country, regions): Region | null \u2014 pure, no network.
|
|
4316
|
+
// \u2192 region whose countries includes the code, else the default region, else null.
|
|
4317
|
+
// Pass the resolved regionId to createCheckout to associate the checkout with a
|
|
4318
|
+
// region (recorded for reporting + provider scoping; currency follows the cart
|
|
4319
|
+
// until FX price conversion lands).
|
|
4320
|
+
//
|
|
4321
|
+
// Storefront (public, no apiKey \u2014 storeId mode):
|
|
4322
|
+
interface PublicRegion {
|
|
4323
|
+
id: string; name: string; slug: string; currency: string;
|
|
4324
|
+
countries: string[]; taxInclusive: boolean; isDefault: boolean;
|
|
4325
|
+
}
|
|
4326
|
+
interface PublicRegionDetail extends PublicRegion {
|
|
4327
|
+
paymentProviders: Array<{ id: string; appId: string; name: string | null }>;
|
|
4328
|
+
}
|
|
4329
|
+
// getStoreRegions(): { data: PublicRegion[] } \u2014 active regions, default first.
|
|
4330
|
+
// getStoreRegion(regionId): PublicRegionDetail \u2014 one region + its providers.
|
|
4331
|
+
|
|
4332
|
+
// ---- Tax Classes ---- (scopes: tax-classes:read / tax-classes:write)
|
|
4333
|
+
// Charge differential rates by product type. A TaxRate may target a class via
|
|
4334
|
+
// taxClassId; a rate with taxClassId=null is the Standard fallback. Per-line
|
|
4335
|
+
// resolution: variant \u2192 product \u2192 category \u2192 store default \u2192 null.
|
|
4336
|
+
interface TaxClass {
|
|
4337
|
+
id: string;
|
|
4338
|
+
accountId: string;
|
|
4339
|
+
storeId: string;
|
|
4340
|
+
name: string;
|
|
4341
|
+
slug: string; // kebab-case, unique per store
|
|
4342
|
+
description?: string | null;
|
|
4343
|
+
isDefault: boolean; // auto-applied to products without an explicit class
|
|
4344
|
+
createdAt: string;
|
|
4345
|
+
updatedAt: string;
|
|
4346
|
+
}
|
|
4347
|
+
interface CreateTaxClassDto { name: string; slug: string; description?: string; isDefault?: boolean }
|
|
4348
|
+
type UpdateTaxClassDto = Partial<CreateTaxClassDto>;
|
|
4349
|
+
// Bulk-assign a class to entities:
|
|
4350
|
+
interface AssignTaxClassDto { productIds?: string[]; variantIds?: string[]; categoryIds?: string[] }
|
|
4351
|
+
|
|
4352
|
+
// TaxRate / CreateTaxRateDto carry an optional taxClassId (null = Standard).
|
|
4353
|
+
// rate is a WHOLE PERCENTAGE (7.25 = 7.25%).
|
|
4354
|
+
//
|
|
4355
|
+
// SDK methods (admin):
|
|
4356
|
+
// Regions: getRegions(), getRegion(id), createRegion(dto), updateRegion(id, dto),
|
|
4357
|
+
// deleteRegion(id), setDefaultRegion(id), updateRegionPaymentProviders(id, ids),
|
|
4358
|
+
// addRegionCountries(id, codes), removeRegionCountry(id, code),
|
|
4359
|
+
// getRegionCompatibleProviders(id), detectRegion(country, regions)
|
|
4360
|
+
// Tax classes: getTaxClasses(), getTaxClass(id), createTaxClass(dto), updateTaxClass(id, dto),
|
|
4361
|
+
// deleteTaxClass(id), setDefaultTaxClass(id), assignTaxClass(id, dto),
|
|
4362
|
+
// mergeTaxClasses(id, targetId)`;
|
|
4170
4363
|
var TYPES_BY_DOMAIN = {
|
|
4171
4364
|
products: PRODUCTS_TYPES,
|
|
4172
4365
|
cart: CART_TYPES,
|
|
@@ -4178,7 +4371,8 @@ var TYPES_BY_DOMAIN = {
|
|
|
4178
4371
|
inquiries: INQUIRIES_TYPES,
|
|
4179
4372
|
reviews: REVIEWS_TYPES,
|
|
4180
4373
|
"modifier-groups": MODIFIER_GROUPS_TYPES,
|
|
4181
|
-
content: CONTENT_TYPES
|
|
4374
|
+
content: CONTENT_TYPES,
|
|
4375
|
+
regions: REGIONS_TYPES
|
|
4182
4376
|
};
|
|
4183
4377
|
function getTypesByDomain(domain) {
|
|
4184
4378
|
if (domain === "all") {
|
|
@@ -4209,10 +4403,12 @@ var GET_TYPE_DEFINITIONS_SCHEMA = {
|
|
|
4209
4403
|
"helpers",
|
|
4210
4404
|
"inquiries",
|
|
4211
4405
|
"reviews",
|
|
4406
|
+
"modifier-groups",
|
|
4212
4407
|
"content",
|
|
4408
|
+
"regions",
|
|
4213
4409
|
"all"
|
|
4214
4410
|
]).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.'
|
|
4411
|
+
'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
4412
|
)
|
|
4217
4413
|
};
|
|
4218
4414
|
async function handleGetTypeDefinitions(args) {
|
|
@@ -6002,11 +6198,16 @@ Build both steps EVEN IF the store has no email provider configured today \u2014
|
|
|
6002
6198
|
});
|
|
6003
6199
|
window.location.href = authorizationUrl; // full-page redirect, NOT a popup
|
|
6004
6200
|
\`\`\`
|
|
6005
|
-
3. **On the callback page** the URL contains \`
|
|
6201
|
+
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
6202
|
\`\`\`ts
|
|
6007
|
-
const
|
|
6008
|
-
|
|
6203
|
+
const params = new URLSearchParams(location.search);
|
|
6204
|
+
const code = params.get('auth_code');
|
|
6205
|
+
if (code) {
|
|
6206
|
+
const result = await client.exchangeOAuthCode(code);
|
|
6207
|
+
client.setCustomerToken(result.token); // then redirect to account
|
|
6208
|
+
}
|
|
6009
6209
|
\`\`\`
|
|
6210
|
+
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
6211
|
4. **On \`oauth_error\`:** redirect to login with an error message.
|
|
6011
6212
|
|
|
6012
6213
|
Build the OAuth button region AND the callback handler even when no providers are configured. They auto-hide.`
|
|
@@ -6488,7 +6689,9 @@ function renderCapabilitiesSummary(caps) {
|
|
|
6488
6689
|
);
|
|
6489
6690
|
lines.push(`- Downloadable products: ${caps.features.hasDownloadableProducts ? "yes" : "no"}`);
|
|
6490
6691
|
lines.push(`- Checkout custom fields: ${caps.features.hasCheckoutCustomFields ? "yes" : "no"}`);
|
|
6491
|
-
lines.push(
|
|
6692
|
+
lines.push(
|
|
6693
|
+
`- Content (FAQ/footer/header/announcements/pages): ${caps.features.hasContent ? "seeded" : "none \u2014 build chrome UI with fallbacks"}`
|
|
6694
|
+
);
|
|
6492
6695
|
lines.push(
|
|
6493
6696
|
`- Email verification: ${caps.connection.requireEmailVerification ? "required" : "not required (still build the verify-email flow)"}`
|
|
6494
6697
|
);
|
|
@@ -6817,14 +7020,149 @@ function createServer() {
|
|
|
6817
7020
|
|
|
6818
7021
|
// src/bin/http.ts
|
|
6819
7022
|
var PORT = parseInt(process.env.PORT || "3100", 10);
|
|
6820
|
-
var CORS_ORIGIN = process.env.CORS_ORIGIN || "*";
|
|
6821
7023
|
var SSE_KEEPALIVE_MS = 1e4;
|
|
6822
7024
|
var SESSION_MAX_AGE_MS = 4 * 60 * 60 * 1e3;
|
|
7025
|
+
var NODE_ENV = process.env.NODE_ENV || "development";
|
|
7026
|
+
var IS_DEV = NODE_ENV === "development";
|
|
7027
|
+
var AUTH_TOKENS = (process.env.MCP_AUTH_TOKENS || "").split(",").map((t) => t.trim()).filter((t) => t.length > 0).map((t) => Buffer.from(t, "utf8"));
|
|
7028
|
+
if (AUTH_TOKENS.length === 0 && !IS_DEV) {
|
|
7029
|
+
console.error(
|
|
7030
|
+
"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."
|
|
7031
|
+
);
|
|
7032
|
+
process.exit(1);
|
|
7033
|
+
}
|
|
7034
|
+
if (AUTH_TOKENS.length === 0 && IS_DEV) {
|
|
7035
|
+
console.warn(
|
|
7036
|
+
"WARN: MCP_AUTH_TOKENS is not set. Running in development mode \u2014 any non-empty Bearer token will be accepted."
|
|
7037
|
+
);
|
|
7038
|
+
}
|
|
7039
|
+
var ALLOWED_ORIGINS = (process.env.MCP_ALLOWED_ORIGINS || "").split(",").map((o) => o.trim()).filter((o) => o.length > 0);
|
|
7040
|
+
var LOCALHOST_ORIGIN_RE = /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/;
|
|
7041
|
+
var RATE_LIMIT_WINDOW_MS = parseInt(process.env.MCP_RATE_LIMIT_WINDOW_MS || "60000", 10);
|
|
7042
|
+
var RATE_LIMIT_MAX = parseInt(process.env.MCP_RATE_LIMIT_MAX || "60", 10);
|
|
7043
|
+
var rateBuckets = /* @__PURE__ */ new Map();
|
|
7044
|
+
var MAX_BODY_BYTES = parseInt(process.env.MCP_MAX_BODY_BYTES || String(100 * 1024), 10);
|
|
7045
|
+
function safeEqual(a, b) {
|
|
7046
|
+
if (a.length !== b.length) {
|
|
7047
|
+
const max = Math.max(a.length, b.length);
|
|
7048
|
+
const ax = Buffer.alloc(max);
|
|
7049
|
+
const bx = Buffer.alloc(max);
|
|
7050
|
+
a.copy(ax);
|
|
7051
|
+
b.copy(bx);
|
|
7052
|
+
(0, import_node_crypto.timingSafeEqual)(ax, bx);
|
|
7053
|
+
return false;
|
|
7054
|
+
}
|
|
7055
|
+
return (0, import_node_crypto.timingSafeEqual)(a, b);
|
|
7056
|
+
}
|
|
7057
|
+
function authenticate(req, res) {
|
|
7058
|
+
const header = req.headers["authorization"];
|
|
7059
|
+
if (typeof header !== "string" || !header.toLowerCase().startsWith("bearer ")) {
|
|
7060
|
+
writeJson(res, 401, {
|
|
7061
|
+
error: "Missing or malformed Authorization header. Expected: Bearer <token>."
|
|
7062
|
+
});
|
|
7063
|
+
return false;
|
|
7064
|
+
}
|
|
7065
|
+
const presented = header.slice(7).trim();
|
|
7066
|
+
if (presented.length === 0) {
|
|
7067
|
+
writeJson(res, 401, { error: "Empty Bearer token." });
|
|
7068
|
+
return false;
|
|
7069
|
+
}
|
|
7070
|
+
if (AUTH_TOKENS.length === 0 && IS_DEV) {
|
|
7071
|
+
return true;
|
|
7072
|
+
}
|
|
7073
|
+
const presentedBuf = Buffer.from(presented, "utf8");
|
|
7074
|
+
let matched = false;
|
|
7075
|
+
for (const token of AUTH_TOKENS) {
|
|
7076
|
+
if (safeEqual(presentedBuf, token)) {
|
|
7077
|
+
matched = true;
|
|
7078
|
+
}
|
|
7079
|
+
}
|
|
7080
|
+
if (!matched) {
|
|
7081
|
+
writeJson(res, 401, { error: "Invalid Bearer token." });
|
|
7082
|
+
return false;
|
|
7083
|
+
}
|
|
7084
|
+
return true;
|
|
7085
|
+
}
|
|
7086
|
+
function clientIp(req) {
|
|
7087
|
+
const xff = req.headers["x-forwarded-for"];
|
|
7088
|
+
if (typeof xff === "string" && xff.length > 0) {
|
|
7089
|
+
return xff.split(",")[0].trim();
|
|
7090
|
+
}
|
|
7091
|
+
return req.socket.remoteAddress || "unknown";
|
|
7092
|
+
}
|
|
7093
|
+
function rateLimit(req, res) {
|
|
7094
|
+
const ip = clientIp(req);
|
|
7095
|
+
const now = Date.now();
|
|
7096
|
+
const bucket = rateBuckets.get(ip);
|
|
7097
|
+
if (!bucket || bucket.resetAt <= now) {
|
|
7098
|
+
rateBuckets.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS });
|
|
7099
|
+
return true;
|
|
7100
|
+
}
|
|
7101
|
+
if (bucket.count >= RATE_LIMIT_MAX) {
|
|
7102
|
+
const retryAfter = Math.max(1, Math.ceil((bucket.resetAt - now) / 1e3));
|
|
7103
|
+
res.setHeader("Retry-After", String(retryAfter));
|
|
7104
|
+
writeJson(res, 429, { error: "Rate limit exceeded. Try again later." });
|
|
7105
|
+
return false;
|
|
7106
|
+
}
|
|
7107
|
+
bucket.count += 1;
|
|
7108
|
+
return true;
|
|
7109
|
+
}
|
|
7110
|
+
var rateLimitGcTimer = setInterval(
|
|
7111
|
+
() => {
|
|
7112
|
+
const now = Date.now();
|
|
7113
|
+
for (const [ip, bucket] of rateBuckets) {
|
|
7114
|
+
if (bucket.resetAt <= now) rateBuckets.delete(ip);
|
|
7115
|
+
}
|
|
7116
|
+
},
|
|
7117
|
+
5 * 60 * 1e3
|
|
7118
|
+
);
|
|
7119
|
+
rateLimitGcTimer.unref();
|
|
7120
|
+
function resolveCorsOrigin(origin) {
|
|
7121
|
+
if (!origin) return null;
|
|
7122
|
+
if (ALLOWED_ORIGINS.includes(origin)) return origin;
|
|
7123
|
+
if (IS_DEV && LOCALHOST_ORIGIN_RE.test(origin)) return origin;
|
|
7124
|
+
return null;
|
|
7125
|
+
}
|
|
7126
|
+
function setCors(req, res) {
|
|
7127
|
+
const origin = typeof req.headers.origin === "string" ? req.headers.origin : void 0;
|
|
7128
|
+
const allowed = resolveCorsOrigin(origin);
|
|
7129
|
+
if (allowed) {
|
|
7130
|
+
res.setHeader("Access-Control-Allow-Origin", allowed);
|
|
7131
|
+
res.setHeader("Vary", "Origin");
|
|
7132
|
+
}
|
|
7133
|
+
res.setHeader("Access-Control-Allow-Credentials", "false");
|
|
7134
|
+
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
|
|
7135
|
+
res.setHeader(
|
|
7136
|
+
"Access-Control-Allow-Headers",
|
|
7137
|
+
"Content-Type, Accept, Authorization, Mcp-Session-Id"
|
|
7138
|
+
);
|
|
7139
|
+
res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id");
|
|
7140
|
+
}
|
|
7141
|
+
function writeJson(res, status, body) {
|
|
7142
|
+
if (res.headersSent) return;
|
|
7143
|
+
res.writeHead(status, { "Content-Type": "application/json" });
|
|
7144
|
+
res.end(JSON.stringify(body));
|
|
7145
|
+
}
|
|
6823
7146
|
function parseBody(req) {
|
|
6824
7147
|
return new Promise((resolve, reject) => {
|
|
6825
7148
|
const chunks = [];
|
|
6826
|
-
|
|
7149
|
+
let total = 0;
|
|
7150
|
+
let aborted = false;
|
|
7151
|
+
req.on("data", (chunk) => {
|
|
7152
|
+
if (aborted) return;
|
|
7153
|
+
total += chunk.length;
|
|
7154
|
+
if (total > MAX_BODY_BYTES) {
|
|
7155
|
+
aborted = true;
|
|
7156
|
+
const err = new Error("Request body exceeds maximum allowed size");
|
|
7157
|
+
err.statusCode = 413;
|
|
7158
|
+
reject(err);
|
|
7159
|
+
req.destroy();
|
|
7160
|
+
return;
|
|
7161
|
+
}
|
|
7162
|
+
chunks.push(chunk);
|
|
7163
|
+
});
|
|
6827
7164
|
req.on("end", () => {
|
|
7165
|
+
if (aborted) return;
|
|
6828
7166
|
if (chunks.length === 0) return resolve(void 0);
|
|
6829
7167
|
try {
|
|
6830
7168
|
resolve(JSON.parse(Buffer.concat(chunks).toString()));
|
|
@@ -6861,14 +7199,8 @@ async function main() {
|
|
|
6861
7199
|
5 * 60 * 1e3
|
|
6862
7200
|
);
|
|
6863
7201
|
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
7202
|
const httpServer = (0, import_node_http.createServer)(async (req, res) => {
|
|
6871
|
-
setCors(res);
|
|
7203
|
+
setCors(req, res);
|
|
6872
7204
|
if (req.method === "OPTIONS") {
|
|
6873
7205
|
res.writeHead(204);
|
|
6874
7206
|
res.end();
|
|
@@ -6885,6 +7217,8 @@ async function main() {
|
|
|
6885
7217
|
);
|
|
6886
7218
|
return;
|
|
6887
7219
|
}
|
|
7220
|
+
if (!rateLimit(req, res)) return;
|
|
7221
|
+
if (!authenticate(req, res)) return;
|
|
6888
7222
|
if (req.url === "/mcp") {
|
|
6889
7223
|
try {
|
|
6890
7224
|
const server = createServer();
|
|
@@ -6897,8 +7231,7 @@ async function main() {
|
|
|
6897
7231
|
} catch (error) {
|
|
6898
7232
|
console.error("MCP request error:", error);
|
|
6899
7233
|
if (!res.headersSent) {
|
|
6900
|
-
res
|
|
6901
|
-
res.end(JSON.stringify({ error: "Internal server error" }));
|
|
7234
|
+
writeJson(res, 500, { error: "Internal server error" });
|
|
6902
7235
|
}
|
|
6903
7236
|
}
|
|
6904
7237
|
return;
|
|
@@ -6939,8 +7272,7 @@ async function main() {
|
|
|
6939
7272
|
} catch (error) {
|
|
6940
7273
|
console.error("SSE connection error:", error);
|
|
6941
7274
|
if (!res.headersSent) {
|
|
6942
|
-
res
|
|
6943
|
-
res.end(JSON.stringify({ error: "Internal server error" }));
|
|
7275
|
+
writeJson(res, 500, { error: "Internal server error" });
|
|
6944
7276
|
}
|
|
6945
7277
|
}
|
|
6946
7278
|
return;
|
|
@@ -6949,8 +7281,7 @@ async function main() {
|
|
|
6949
7281
|
const url = new URL(req.url, `http://${req.headers.host || "localhost"}`);
|
|
6950
7282
|
const sessionId = url.searchParams.get("sessionId");
|
|
6951
7283
|
if (!sessionId || !sseSessions.has(sessionId)) {
|
|
6952
|
-
res
|
|
6953
|
-
res.end(JSON.stringify({ error: "Invalid or missing sessionId" }));
|
|
7284
|
+
writeJson(res, 400, { error: "Invalid or missing sessionId" });
|
|
6954
7285
|
return;
|
|
6955
7286
|
}
|
|
6956
7287
|
try {
|
|
@@ -6958,20 +7289,23 @@ async function main() {
|
|
|
6958
7289
|
const body = await parseBody(req);
|
|
6959
7290
|
await session.transport.handlePostMessage(req, res, body);
|
|
6960
7291
|
} catch (error) {
|
|
6961
|
-
|
|
7292
|
+
const status = error && typeof error === "object" && "statusCode" in error ? error.statusCode || 500 : 500;
|
|
7293
|
+
if (status !== 500) {
|
|
7294
|
+
console.warn("SSE message rejected:", error.message);
|
|
7295
|
+
} else {
|
|
7296
|
+
console.error("SSE message error:", error);
|
|
7297
|
+
}
|
|
6962
7298
|
if (!res.headersSent) {
|
|
6963
|
-
res
|
|
6964
|
-
|
|
7299
|
+
writeJson(res, status, {
|
|
7300
|
+
error: status === 413 ? "Payload too large" : "Internal server error"
|
|
7301
|
+
});
|
|
6965
7302
|
}
|
|
6966
7303
|
}
|
|
6967
7304
|
return;
|
|
6968
7305
|
}
|
|
6969
|
-
res
|
|
6970
|
-
|
|
6971
|
-
|
|
6972
|
-
error: "Not found. Use /mcp (Streamable HTTP), /sse (legacy SSE), or /health."
|
|
6973
|
-
})
|
|
6974
|
-
);
|
|
7306
|
+
writeJson(res, 404, {
|
|
7307
|
+
error: "Not found. Use /mcp (Streamable HTTP), /sse (legacy SSE), or /health."
|
|
7308
|
+
});
|
|
6975
7309
|
});
|
|
6976
7310
|
function shutdown(signal) {
|
|
6977
7311
|
console.info(`
|
|
@@ -6999,6 +7333,16 @@ ${signal} received \u2014 shutting down gracefully...`);
|
|
|
6999
7333
|
console.info(` Streamable HTTP: http://localhost:${PORT}/mcp`);
|
|
7000
7334
|
console.info(` Legacy SSE: http://localhost:${PORT}/sse`);
|
|
7001
7335
|
console.info(` Health check: http://localhost:${PORT}/health`);
|
|
7336
|
+
console.info(
|
|
7337
|
+
` Auth tokens: ${AUTH_TOKENS.length} configured${AUTH_TOKENS.length === 0 && IS_DEV ? " (dev: any non-empty Bearer accepted)" : ""}`
|
|
7338
|
+
);
|
|
7339
|
+
console.info(
|
|
7340
|
+
` CORS: ${ALLOWED_ORIGINS.length} allow-listed origin(s)${IS_DEV ? " + localhost (dev)" : ""}`
|
|
7341
|
+
);
|
|
7342
|
+
console.info(
|
|
7343
|
+
` Rate limit: ${RATE_LIMIT_MAX} req / ${Math.round(RATE_LIMIT_WINDOW_MS / 1e3)}s per IP`
|
|
7344
|
+
);
|
|
7345
|
+
console.info(` Max body: ${MAX_BODY_BYTES} bytes`);
|
|
7002
7346
|
});
|
|
7003
7347
|
}
|
|
7004
7348
|
main().catch((error) => {
|