MCP OAuth2 Authentication¶
Overview¶
The MCP (Model Context Protocol) server supports OAuth 2.1 authentication per the MCP specification (2025-03-26). MCP clients like Claude Code and Claude Desktop authenticate via the central auth server (auth.bdgr.co.uk) using Authorization Code + PKCE flow, rather than static API keys.
One URL for every shop, or one per shop¶
There are two ways to connect:
- The central URL,
https://mcp.bdgr.co.uk/mcp(staginghttps://mcp.bdgr-demo.co.uk/mcp, localhttps://mcp.bdgr.localhost/mcp). This is the URL of the Claude directory listing, and it works as a custom connector too. The person chooses the shop on the consent screen; the token carries it assite_id, and every request through that connection acts on that shop. To use another shop, reconnect and choose it. - A shop's own URL,
https://<shop domain>/mcp. The shop comes from the Host header. This still works exactly as before, so existing connectors need no change, and it is the way to use two shops at once in one Claude account.
Platform operators have a third: the Badger Platform connection,
https://mcp.bdgr.co.uk/mcp/platform (staging https://mcp.bdgr-demo.co.uk/mcp/platform), for
System's tenant jobs rather than one shop. See The Badger Platform connection.
Both shop connections use the same auth server, scopes and roles. There is no tool for switching shop inside a connection: the server keeps no state between requests, and a "current shop" stored per token or per user would be shared by every chat using the connector, so one chat switching could send another chat's changes to the wrong shop.
Architecture¶
MCP Client (Claude Code / Claude Desktop)
│
├─1─► /.well-known/oauth-authorization-server (on web app — RFC 8414)
│ → Returns auth server metadata (endpoints, scopes, grant types)
│
├─2─► auth.bdgr.co.uk /oauth2/register (RFC 7591 Dynamic Client Registration)
│ → Client auto-registers as public PKCE client
│
├─3─► auth.bdgr.co.uk /oauth2/authorize (Authorization Code + PKCE)
│ → User logs in, sees consent screen, approves MCP access
│
├─4─► auth.bdgr.co.uk /oauth2/token
│ → Client exchanges code for JWT access token
│
└─5─► shop.example.com/mcp (Bearer token)
→ MCP server validates JWT, checks ROLE_MCP + scopes, executes tools
Authorization Server Metadata (RFC 8414)¶
The MCP spec requires clients discover the authorization server via GET /.well-known/oauth-authorization-server on the MCP server's base URL (path stripped). Since the auth server runs on a separate origin, the web app serves a metadata document that points to the auth server's actual endpoints.
GET https://shop.example.com/.well-known/oauth-authorization-server returns:
{
"issuer": "https://auth.bdgr.co.uk",
"authorization_endpoint": "https://auth.bdgr.co.uk/oauth2/authorize",
"token_endpoint": "https://auth.bdgr.co.uk/oauth2/token",
"registration_endpoint": "https://auth.bdgr.co.uk/connect/register",
"scopes_supported": ["openid", "mcp:read", "mcp:write", "mcp:admin"],
"response_types_supported": ["code"],
"grant_types_supported": ["authorization_code", "refresh_token", "client_credentials"],
"code_challenge_methods_supported": ["S256"]
}
Implementation: McpAuthorizationServerMetadataController in the ai module.
Protected Resource Metadata (RFC 9728)¶
Also available at GET /.well-known/oauth-protected-resource for non-MCP OAuth2 clients:
{
"resource": "https://shop.example.com/mcp",
"authorization_servers": ["https://auth.bdgr.co.uk"],
"scopes_supported": ["openid", "mcp:read", "mcp:write", "mcp:admin"],
"bearer_methods_supported": ["header"]
}
The resource field is https://<host>/mcp on a shop's own host. On the central host it is the
configured central URL exactly (MCP_CENTRAL_URL), since the auth server compares it with the
resource parameter the client sends, and resource_name is "Badger Commerce". The document is
also served at the path-suffixed /.well-known/oauth-protected-resource/mcp (RFC 9728 §3.1). Both
discovery documents are answered without looking up a shop, so they work on the central host,
which is no shop's domain.
A 401 from /mcp carries WWW-Authenticate: Bearer resource_metadata="<origin>/.well-known/oauth-protected-resource"
(MCP 2025-06-18), pointing the client at this document.
Transport and Sessions¶
The MCP server speaks Streamable HTTP on a single endpoint, POST /mcp, in Spring AI's
STATELESS mode:
Every request is self-contained. The server never mints an Mcp-Session-Id, never holds
per-client state in heap, and never needs the next request to come back to the same JVM.
Why stateless and not STREAMABLE. STREAMABLE assigns each client a session and keeps it
in memory. badger-web runs 2 replicas behind badger-web-service, a plain ClusterIP service
with no sessionAffinity, so kube-proxy spreads requests across both pods. A client that
initialises against pod A and then calls a tool on pod B gets Session not found. Rather than
introduce sticky sessions at the edge or replicate session state between pods, we drop the
session: McpAuthFilter authenticates the Bearer token and resolves the tenant on every
request anyway, so there is nothing left for a session to carry.
This is only safe because none of our tools need a session. Every @McpTool method is plain
request/response — no sampling, no elicitation, no roots, no progress notifications, no resource
subscriptions. Adding a tool that needs any of those would mean reintroducing session state, so
don't.
Don't just delete the protocol key
Spring AI defaults to STREAMABLE — the one mode that breaks across our replicas. (Before
2.0.1 it defaulted to SSE, the deprecated 2024-11-05 transport, so removing the property has
never been safe.) The valid values are SSE, STREAMABLE, and STATELESS.
Protocol version¶
We build on Spring AI 2.0.1 and io.modelcontextprotocol.sdk 2.0.1, which advertises
protocol versions 2024-11-05, 2025-03-26, 2025-06-18, and 2025-11-25.
The current MCP specification, 2026-07-28,
removes protocol-level sessions outright — no Mcp-Session-Id, no GET stream, no Last-Event-ID
resumability — along with the initialize handshake, in favour of per-request protocol metadata
and a server/discover RPC. That matches how we already run the server, but Java is a Tier 2 SDK
and does not implement 2026-07-28 yet. When the SDK ships support, adopting it should be a
version bump plus a re-test rather than an architectural change, because we are not carrying any
session state to unwind.
Authentication¶
OAuth2 JWT Bearer tokens issued by the auth server are the only accepted credential. There is no second way in.
The mcp_* API key path was retired
MCP originally also accepted a per-tenant static API key held in the mcp-api-key site
config. That path is gone: McpApiKeyService was deleted, the config key was removed, and a
system update purges any stored values. A mcp_* token now fails JWT decoding and gets the
same 401 as any other invalid bearer token — clients still presenting one must re-authorise
through the OAuth2 flow above.
Retiring it also let McpToolAuthorizationAspect fail closed. It previously waved through any
non-JWT authentication on the grounds that API key clients held every scope; it now denies.
OAuth2 Scopes¶
| Scope | Description | Required Role |
|---|---|---|
mcp:read |
Read store data (products, collections, orders, statistics) | ROLE_MCP |
mcp:write |
Create, update, and delete store data | ROLE_MCP + any admin role |
mcp:admin |
Access admin settings, pipelines, site configuration | ROLE_MCP + any admin role |
A token never holds more than the user ticked on the consent screen, and never more than their roles allow on the site being called. Where that cap is applied depends on the token:
- Tenant-bound tokens (clients with a fixed
badger.site-group-id, or an allow-listedsite_idon the authorize request): the auth server filters the scopes when it issues the token. Users withoutROLE_MCPlose every MCP scope;ROLE_MCPwithout an admin role keeps onlymcp:read. - Central URL tokens (any client connecting to the central URL): bound to the shop chosen on
the consent screen, and capped like tenant-bound tokens when issued. They carry the shop
(
site_id) but not the user's roles, and the access token's audience is the central URL (RFC 8707).McpAuthFilterreads the roles from the database and caps the scopes again on each request. The ID token names neither the shop nor the roles. - Unbound tokens (dynamically registered clients such as claude.ai and Claude Code, on a
shop's own URL): there's no tenant at issue time, so the token carries exactly the scopes the
user consented to.
McpAuthFilterapplies the same role cap per request, using the user's roles on the site in the request's Host header.
A token with no MCP scope at all gets a 401 from /mcp so the client reconnects. That is also
what tokens issued before October 2026 get: the auth server used to strip their MCP scopes and
McpAuthFilter granted scopes from roles instead, which meant unticking a scope on the consent
screen had no effect.
Scopes nest: mcp:admin implies mcp:write, which implies mcp:read (McpScopes). A token
that only asked for mcp:admin can still call read and write tools.
Customer details need mcp:write. Because every ROLE_MCP user gets mcp:read, customer
names, emails, phone numbers and addresses (orders, subscriptions, gift cards) are only returned
to tokens holding mcp:write — in practice, store admins. Other tokens get the rest of the record
with customerDetailsHidden: true. The customers tool is read-only but needs mcp:write
for the same reason, as does filtering orders list by customerEmail (which reveals whether
someone has shopped here). A dedicated mcp:customers scope would be cleaner, but needs
the auth server, consent screen and every registered client updated, so it hasn't been done.
ROLE_MCP¶
The MCP role gates who can use MCP. Assign this role to users via the admin UI to grant MCP access. Without this role, JWT authentication to the MCP server will be rejected with 403.
For dynamically registered clients (RFC 7591), the JWT may not contain tenant-specific roles. In this case, McpAuthFilter falls back to a database lookup — it resolves the user's roles on the tenant identified by the request domain.
Dynamic Client Registration¶
MCP clients register automatically via RFC 7591 (POST /oauth2/register). The registration endpoint is discovered from the authorization server metadata. Clients register as public clients with PKCE:
{
"client_name": "Claude Code",
"redirect_uris": ["http://127.0.0.1:{port}/callback"],
"grant_types": ["authorization_code", "refresh_token"],
"response_types": ["code"],
"token_endpoint_auth_method": "none"
}
scope is optional. claude.ai connectors send "scope": "openid mcp:read mcp:write mcp:admin",
so the registration request may name any of openid profile email offline_access mcp:read
mcp:write mcp:admin. Any other scope is rejected with 400 invalid_scope (RFC 7591 §3.2.2).
Whatever the client asks for, the registered client is granted openid profile email mcp:read
mcp:write mcp:admin, and scopes are requested again on the authorize call.
Spring Authorization Server 7's default validator rejects every scope at registration, which made
claude.ai fail with "Couldn't register with ... sign-in service". McpDynamicClientRegistration
(in the auth module) replaces only the scope check with the allow-list above; the default
redirect_uris checks (no fragment, no javascript:/data: schemes) and the https-only
jwks_uri check still apply. Dynamically registered clients always require consent and get 1h
access tokens. The refresh token lasts as long as the user chose on the consent screen (see
below); 24h is only the fallback when no choice is on record.
Public clients get no refresh token
Claude Code registers with token_endpoint_auth_method: none. Spring Authorization Server
issues no refresh token to a public client on the authorization-code grant, and only
authenticates public clients on PKCE code exchanges, so they can't use the refresh grant
either. A public client therefore re-authorises when its 1h access token expires, whatever
duration was chosen. Confidential clients (claude.ai connectors) are unaffected. The one
exception is Badger's own POS app, named in badger.auth.trusted-public-client-ids (see
Mobile POS); a self-registered client is never on that list.
Pre-registered clients (e.g., via admin UI or MongoOidcClientRegistrationService) can include badger.site-group-id and badger.site-id in client settings for tenant-specific token claims.
Consent Screen¶
When an MCP client initiates OAuth2 authorization, users see a consent screen listing the
requested scopes with human-readable descriptions (all ticked by default) and a Stay connected
for choice: 24 hours, 7 days, 30 days (default), 3 months or 6 months (GrantDuration). Consent
decisions are persisted to MongoDB and remembered for future authorization requests; a later
consent for the same client starts from the duration chosen last time.
The duration is the refresh token's lifetime and the absolute length of the connection: once it
passes, the user signs in and approves again. Refresh tokens rotate (each refresh returns a new one
and the old one stops working, as Claude's connector directory requires), but every new token keeps
the first one's expiry, so refreshing never extends the connection. It is
stored as a GRANT_DURATION_<name> authority on the consent (GrantDuration.CONSENT_CUSTOMIZER)
and applied when the refresh token is minted (GrantDurationRefreshTokenGenerator). Clients that
never show a consent page, like the admin UI, keep their configured lifetimes. Whether a client
reuses or rotates is stored on its registration (reuseRefreshTokens); dynamically registered
clients saved before that was stored rotate, and first-party clients keep reusing.
Deny denies. Both buttons submit the same form, ticked scopes included, and Spring
Authorization Server only reads the scopes, so Deny used to grant whatever was ticked. The consent
customizer now clears the consent when consent_action=deny, and the server answers
access_denied.
Authorizations are stored in MongoDB (oauth2_authorizations, MongoOAuth2AuthorizationService),
with a SHA-256 hash of each token value for lookups and a TTL index on the latest token expiry.
They used to be in Redis, which in k3s has no volume, so every Redis restart deleted every refresh
token and logged every MCP client out, in practice well before the old 24h limit.
Choosing the shop (central URL)¶
When the authorize request's resource (RFC 8707, which MCP clients send) is the central URL, the
consent screen also lists the shops the person can connect to: every site in each site group where
their account has ROLE_MCP, superadmins included (UserSitesService.mcpSites, which also backs
"Your sites" on the account page). It starts on the shop chosen last time. With no such shop it
says so and offers only Deny. For central requests the consent screen is shown every time, even
when every scope was approved before, because reconnecting is how the shop is changed.
- The choice (
mcp_site_id) is checked against that list and recorded on the consent as anMCP_SITE_<siteId>authority (McpShopConsent). Anything else is a denial. BadgerOAuth2TokenCustomizerbinds the token to it: from the consent when the code is exchanged, and on a refresh from the connection's current token, so a later consent elsewhere can't move an existing connection. It checks again that the site exists and the person still hasROLE_MCPthere; if not, the code exchange fails withaccess_deniedand a refresh withinvalid_grant, which makes the client sign in again.- On the central host
McpAuthFiltertakes the tenant from the token'ssite_id. A token with none (one issued for a shop's own URL) or for a shop that no longer exists gets a401, so the client reconnects. After that, the role and scope checks are the same as on a shop's own host. - The model learns which shop it is working on from
getDesignBrief(shop.name,shop.url); the server instructions tell it to check before its first change.
A fleet endpoint for superadmins, where each call names its site, is designed in
docs/implementation-plan/mcp-fleet-connection.md but not built. It would share the central host
and be told apart by the token.
The Badger Platform connection¶
The jobs in System's Tenants pages, for platform operators through Claude: a second MCP server on
the central host at /mcp/platform, with its own tools and instructions. Its URL is the central
URL plus /platform (https://mcp.bdgr.co.uk/mcp/platform); it exists wherever the central URL
does and only on the central host (a 404 on a shop's domain). Operators add it as a connector of
its own beside their shop connector.
Who can use it. A platform operator: an account for the signed-in email holding both
ROLE_SUPERADMIN and ROLE_MCP. Superadmin is never granted through the admin, so this can't be
self-assigned. It is checked on the consent page (McpPlatformConsent), when each token is issued
or refreshed (BadgerOAuth2TokenCustomizer, invalid_grant once it's gone), and on every request
(McpAuthFilter, a 403 otherwise).
The consent page has no shop picker. It names the connection and what it can do, offers "stay connected" for 24 hours or 7 days only (a longer value from a hand-edited form is recorded as 7 days), and for anyone who isn't an operator shows the refusal and only Deny.
Tokens carry bdgr_platform: true and no site_id. McpAuthFilter accepts only such tokens
on /mcp/platform and refuses them on every shop endpoint (central or a shop's own host), so a
platform connection can't touch a shop's catalogue and a shop connection can't reach the platform.
No tenant is set for platform requests; every tool names its tenant with siteId. Each tool also
checks for a platform token itself (PlatformAccess). Writes are logged with the operator's
account id, never their email.
Tools (ai/.../mcp/platform/tools, marked @PlatformMcpTools, which keeps them off the shop
server's list):
| Tool | Scope | What it does |
|---|---|---|
tenants |
mcp:read |
list (search, status), get, checkAvailability of a site id |
manageTenants |
mcp:admin |
create (with an optional owner who signs in by emailed code), update name, primary domain, theme and time zone, add or remove an extra domain, archive (confirm = the site id), reactivate, clear caches, turn central auth on or off, start a site transfer export (confirm = the site id) and fetch its status and download link |
siteUsers |
mcp:read |
a tenant's accounts and roles, optionally by role |
manageSiteUsers |
mcp:admin |
add someone (no password: they sign in with an emailed code), replace their roles, remove them |
platformUpgrades |
mcp:read |
which platform upgrades each tenant has applied |
Not available, by design: permanently deleting a tenant, the System initialisation page, importing data, the platform-wide settings and granting superadmin (refused even though System's own users page can). Those stay in System.
Configuration¶
MCP has no per-tenant configuration keys. Access is granted entirely through ROLE_MCP on the
user plus the OAuth2 scopes the auth server issues.
MCP_CENTRAL_URL (badger.mcp.central-url) turns on the central URL, and with it the Badger
Platform connection at that URL plus /platform. Set it to the same value on web and auth, e.g.
https://mcp.bdgr.co.uk/mcp. Its host must not be any site's domain. Blank (the default) turns
central and platform connections off; shops' own URLs are unaffected. DNS and ingress are
wildcards, so the host needs no other set-up. The platform server's instructions are
badger.mcp.platform-instructions in web's application.yml.
The web app validates MCP tokens against the issuer in AUTH_ISSUER_URL. Every deployment
must set it explicitly (the web app's fallback is https://localhost:9463, unlike the auth
server and REST API which fall back to https://auth.bdgr.co.uk), and it must equal the
issuer the auth server publishes at /.well-known/openid-configuration.
The retired mcp-api-key and mcp-oauth2-enabled keys were removed; system updates 81.json
and 82.json delete any values left in the siteConfiguration collection.
Tool Conventions¶
These are enforced by McpToolConventionsTest in the ai module.
Read and write tools are separate. Each domain has a read tool named after the thing
(products, collections, orders...) and, where writes exist, a manage* tool
(manageProducts, manageCollections...). That split exists so that:
- a read-only token (
mcp:read) can list and inspect everything, and a write needsmcp:write; - the MCP tool annotations are truthful and complete. Every tool has a human-readable
title(shown by clients in place of the tool name, and required by Claude's connector directory). Read tools setreadOnlyHint = true, and every tool setsopenWorldHint = falseexceptmanageMedia, whoseimportfetches a URL the caller supplies (OPEN_WORLD_TOOLSin the test lists the exceptions). Clients use these to auto-approve reads and warn before destructive calls. Before the split, every tool advertised the defaults (readOnlyHint = false,destructiveHint = true,openWorldHint = true), reads included.
Each tool method carries @McpScope(McpScopes.READ | WRITE | ADMIN). pipelines,
managePipelines, siteConfig and manageSiteConfig need mcp:admin.
Each connection only sees the tools it can use. Clients send the tool list to the model
on every turn, so tools/list is filtered per request (McpToolListFilter, using
McpToolVisibility):
- tools the token's scope can't call are left out, so a read-only token doesn't see the
manage*tools; - a tool marked
@ListedWhen(McpFeature...)is only listed once the shop uses that feature (McpFeatureState). Tools stay in the list if this can't be worked out.
| Feature | Tools | Listed when |
|---|---|---|
RESTAURANT |
modifierGroups, manageModifierGroups |
restaurant ordering, table bookings or table service is on |
DINING |
diningRoom, reservations, manageReservations |
table bookings or table service is on |
TABLE_SERVICE |
tableService |
table service is on |
APPOINTMENTS |
appointments, manageAppointments |
the booking business kind is appointments, or a location's room takes appointments |
CHANNELS |
channels, manageChannels |
marketplace channels are on |
SUBSCRIPTIONS |
subscriptions, manageSubscriptions, subscriptionPrices, manageSubscriptionPrices |
subscriptions or donations are on, or the shop holds subscriptions |
PRINT_ON_DEMAND |
podCatalogue, managePodProducts |
the shop has a Prodigi API key for its mode (sandbox or live) |
This saves tokens. It is not a permission check: a hidden tool can still be called, and
@McpScope still decides whether the call is allowed. Clients fetch the list when they connect,
so after a feature is switched on (manageSiteConfig) the agent has to reconnect to see its
tools; the server instructions say so.
McpToolConventionsTest keeps two size budgets: the whole list (an admin token on a shop using
every feature) and the list a shop using none of the optional features gets. The second is the
one most shops pay for. A new tool only some shops need should get a @ListedWhen feature rather
than a bigger budget.
Failures are MCP error results. Tools throw McpToolException (via McpArgs helpers) for
anything the caller can fix: unknown action, missing argument, not found, missing scope.
McpToolInvocationAspect returns it as a CallToolResult with isError = true and the message
as its only text, so the model can correct itself. Unexpected exceptions are logged at ERROR and
the model gets a generic message, without internal details. No tool returns null or an
{"error": ...} map. Every @McpTool method is declared to return Object, because the aspect
may substitute the error result.
Pages are capped. size defaults to 20 and is capped at 50 (McpArgs.MAX_PAGE_SIZE). Every
row a tool returns stays in the model's context for the rest of the conversation.
Server instructions. spring.ai.mcp.server.instructions in web/application.yml holds the
domain primer (how products, collections, extensions, stereotypes and taxonomy fit together,
minor-unit money, identifiers, paging, error handling). Every client receives it once at
initialize, so it doesn't depend on the badger-skills plugin. Keep it short; long
reference material belongs in that plugin or in extensions getPromptSection.
Parcel labels. shipments (mcp:read) lists an order's labels or a location's labels
awaiting collection; manageShipments (mcp:write, open-world because it spends the shop's money
with its label provider) quotes, buys and voids labels, books and cancels courier collections and
sends return labels. See Parcel Labels.
Fulfilment and refunds. manageFulfilment (mcp:write) packs and dispatches orders
(dispatch takes an optional carrier, trackingNumber and trackingUrl, recorded on the order
and shown in the dispatch email; see Dispatch, Cancellations & Returns),
readies and hands over the items a customer collects (markReady, markCollected), and on an
order partly collected and partly delivered packs and dispatches only the delivered items (orders
get shows such an order's collection store, collectionLocationCode and collectionSlot beside
its deliveryMethod and deliverySlot, splitHandover, and each line's handover: COLLECT or
SHIP; see Partly collected, partly delivered). On every order,
deliveryMethod is now the delivery only and collection the store collecting: an order collected
entirely has a collection and no deliveryMethod, where deliveryMethod used to name the store;
and
manageRefunds (mcp:admin) refunds them. Both run the site's own packOrder,
dispatchOrder and refundOrder pipelines, so per-site pipeline changes apply. Unlike the REST
admin API, which uses a made-up "system" user, they run as the admin behind the token
(McpActingUser), so the order history names who acted. An action is refused if that user has no
account on the tenant. Refunds have extra guards, because retries and model mistakes move real
money:
- an
idempotencyKeyis required. A retry with the same key replays the first result instead of refunding again. This uses the Redis-backedPosIdempotencyServiceunder themcp-refundscope. If the provider refunded but a later pipeline step failed, the key is kept, so a retry can't refund twice. - the amount can't exceed what's left to refund: the captured amount (or the authorised amount
before capture), minus what has already been refunded.
orders getshowsrefundableAmount. - the
mcp-refund-limitsite config key (payment-config, minor units, default 0 = no limit) caps any single MCP refund. Staff refunds in the admin aren't affected. dryRunpreviews a refund without calling the payment provider.- the refund and its
reasonare written to the order's activity log asREFUNDED_BY_AI_AGENT.
manageCancellations (mcp:admin) cancels a SUBMITTED or PACKING order through
OrderCancellationService and the site's cancelOrder pipeline: it refunds or releases the
payment, restores stock and emails the customer. It reuses the refund guards: a required
idempotencyKey (scope mcp-cancel, keyed to the order), mcp-refund-limit on the refund part,
and dryRun. The key is only freed if the order didn't end up cancelled. With part
(COLLECTION or DELIVERY) it cancels only that part of a split order, through
OrderCancellationService.cancelPart and the cancelOrderPart pipeline (see
Cancelling one part of a split order);
the key is then keyed to the order and part, and the limit applies to the part's refund.
returns (mcp:read) lists and reads returns (RMAs); the customer's name and email on get
need mcp:write. manageReturns (mcp:write) creates, approves (a customer's
PENDING_APPROVAL request), receives and rejects them through
ReturnService. Its refund action also checks for mcp:admin inside the tool, and has the same
guards as manageRefunds: a required idempotencyKey (scope mcp-return-refund),
mcp-refund-limit, dryRun, and the key is kept if money moved.
Like the POS API, idempotency fails open. If Redis is down, the refund goes ahead without a recorded key, and only the balance check and the site limit protect against a duplicate.
Subscription prices. subscriptionPrices (mcp:read) lists the Stripe recurring prices the
shop's subscription SKUs bill at (with the SKUs using each, live subscriber counts, and the SKUs
that have no price), gets one, and checks every SKU against Stripe without changing anything.
manageSubscriptionPrices (mcp:write) does what the admin's price screens do, through
SubscriptionPriceService: create (a price for a sku, in minor units, monthly unless
interval says otherwise), change (a new price replaces the old on every SKU and the old one is
archived; subscribers is stay by default or move to bill existing subscribers the new amount
from their next renewal), link (an existing price to a SKU; a price made in the Stripe dashboard is
adopted), unlink, archive (only an unused price) and sync. dryRun previews change
(the SKUs repointed and how many subscribers stay or move), archive and sync. create and
change take an optional idempotencyKey, passed to Stripe so a retry makes no second price. One
sku parameter takes a variant SKU, or the product SKU of a product without variants. See
Subscriptions.
Customer service. customers searches accounts by email or name (the query is quoted before
it reaches the Mongo $regex). get returns a profile with the latest orders, the customer's saved
addresses (label, address, whether each is the default for delivery or billing, when last used) and a
consent summary from their contact (absent when they have none on the shop), read as the admin
customer page reads it: the contactId (open it with contacts get for the full history), each
marketing list they decided about (subscribed, pending confirmation or unsubscribed) and the
terms of sale version they last accepted, each with when and how. It is read-only: addresses and consent are changed by the customer or in the admin. Guest checkouts have
no account, so orders list customerEmail matches the email captured on each order
(OrderService.findOrdersByCustomerEmail, exact and case-insensitive). manageOrderEmails
resends the order confirmation or the dispatch email (with its tracking) to the customer, or the
order to the site's fulfilment partners, through OrderEmailResendService. It refuses to send the
same email for an order again within 15 minutes, based on the order's activity log, so a looping
agent can't flood a customer. For the dispatch email, the send made by the dispatch itself counts
too.
Contacts and contact requests. contacts and contactRequests are read-only, but every field is
personal data (names, email addresses, consent history, message text), so they need mcp:write like
customers. They only ever read the shop the connection is authorised for. contacts has search (a
query that is the start of an email address or part of a name, optionally narrowed to a status of
subscribed, pending or unsubscribed on a list given as topic, default the general list), get (one
contact: address, whether it is verified, the current consent for each list, the last 50 consent
records with their source and method, and their contact requests) and summary (subscribers, pending
and unsubscribed per list). contactRequests has list (status NEW by default, or any status, all, or needs_reply for open
requests whose customer is waiting, longest-waiting first, as they also come first on the other lists; a
query over name, email and subject; about (ORDER, RETURN, BOOKING, SUBSCRIPTION or GENERAL) and topic
(WHERE_IS_MY_ORDER...) to narrow it; each row says what it's about, its topic and whether it needs a reply) and get (the whole message, what it's
about, its topic and the conversation: customer messages, replies sent and staff notes).
Unsubscribing, erasing and replying stay in the admin (Customers > Contacts and Contact requests), so an
agent can find out who asked for what but not act on it. See
Customer Messaging and Consent.
Email campaigns. campaigns (mcp:read) and manageCampaigns (mcp:write) run
Email Campaigns for the shop the connection is authorised for. Campaign
content and counts are not personal data, so reading needs only mcp:read; no tool returns a
recipient's address, and the do-not-email list is not exposed over MCP at all.
campaignshastopics(the shop's mailing lists: key, name, description, confirmed subscriber count and whether archived; call it first to choose a list),list(optionally by status),get,stats(counts, delivery, bounce, complaint and unsubscribe rates, open and click rates when tracking is on, and failures by code),preview(the text version of the email for a sample recipient, with anything that would stop it being sent),audience(topic, defaultgeneral: the list's name and how many people it reaches now) andsendingDomain(status, problems, the DNS records to publish and the from address, or{configured: false}).manageCampaignshascreate(name, subject, topic, preheader, blocks),update(with theversionlast read; only the fields given change; a stale version is refused),duplicate,delete(drafts only),testSend(at most 5 addresses, 20 test sends a shop an hour, marked as a test; the addresses are not stored or logged),schedule,unschedule,pause,resumeandcancel. Blocks are{type, params}with the types and params of the campaign editor, or the params beside the type.setSendingDomain,checkSendingDomainandremoveSendingDomainchange the shop's email domain, so they needmcp:admin(the tool itself only needsmcp:write; these actions check the higher scope).removeSendingDomainmirrors the admin's typed confirmation:domainNamemust repeat the current domain, otherwise nothing is removed, and it is refused while a campaign is scheduled, sending or paused.
A send has to be confirmed. schedule refuses unless confirmAudience equals the list's current
estimate, so an agent has to read campaigns audience first and say how many people it is about to
email. If the list changed in between, the refusal gives the new number and nothing is scheduled.
Omitting sendAt sends now; sendAt is an ISO time with an offset, or the shop's local time
(2026-11-03T09:00). There is no action that takes a recipient: a campaign reaches the people who
are subscribed, confirmed and not on the do-not-email list, as decided when it sends, and nobody else.
Every action is attributed to the admin behind the token. manageCampaigns carries
openWorldHint because it sends email.
Legal documents. legalDocuments (mcp:read, read-only) covers the terms of sale and privacy
notice. current (optionally one kind, TERMS_OF_SALE or PRIVACY_NOTICE) gives the page, label
and link in use, the hash of the page's text now, whether that text is already stored, any drift
problems (no page set, page missing or unreadable, edited without a new label, one label on several
texts) and the newest stored text. snapshots (kind) lists the stored texts, newest first, with when
each was first shown, its hash and how many acceptances carry it (the newest 20; total says how
many exist). get (snapshotId) returns one text's metadata and its text only when it is short;
otherwise textOmitted is true and its length is given. Changing the pages and labels is done in
Settings and Customers > Legal documents.
Print on demand. podCatalogue (mcp:read) searches Prodigi's catalogue, lists a product's
SKUs, options and print areas, lists this shop's mappings and the print orders that need someone
(orders); managePodProducts (mcp:write) quotes Prodigi's prices (they are the shop's cost
prices, so not under mcp:read), uploads artwork, makes mock-ups, creates print products, maps and
unmaps SKUs, syncs cost prices and connects Prodigi's webhook. See
Print on Demand.
Ops inbox and low stock. opsInbox (mcp:read, counts only) returns, in one call:
- orders to pack (SUBMITTED) and to dispatch (PACKING), each with the oldest order's age in hours;
- PAYMENT_FAILED orders created in the last 7 days;
- subscriptions that are
past_dueorunpaid; - returns to approve (PENDING_APPROVAL, asked for by customers), to receive (REQUESTED) and to refund (RECEIVED);
- low-stock SKUs;
- parcels with delivery problems (
deliveryProblems: live outbound labels the carrier reports as an exception, a failed delivery attempt or returned, with the oldest one's age; see Parcel Tracking); - late deliveries (
lateDeliveries: orders past the last day of their delivery promise and not yet delivered, with how many hours the longest has been late; see Delivery promise); - with Prodigi print on demand in use:
prodigiOrdersNeedingAttention, print orders that couldn't be sent (send_failed), are held (on_hold), paused, failed, left as a draft, were cancelled by Prodigi (cancelled_by_prodigi) or weren't cancelled at Prodigi when the order was (cancel_failed), plus any stillqueued,sendingorpending_submissionafter an hour;podCatalogue orderslists them; - with marketplace channels on: channel accounts that need reconnecting, marketplace updates (ship, cancel, refund) that kept failing, marketplace orders that couldn't be imported and listings in ERROR, with the oldest failure's age where there is one;
- customer messages waiting for a reply (
contactRequests: new or in-progress requests whose customer wrote after the last reply, or that nobody has answered, with the longest wait in hours; the next step iscontactRequests list status needs_reply, then reply in Customers > Contact requests); - email campaigns (
campaigns: campaigns the system paused, which have a status reason, such as a domain that stopped being verified, plus a sending domain in ACTION_NEEDED; the next step iscampaigns list status PAUSED, thencampaigns sendingDomain); - setup still to do (
setup: the admin home page's Finish setting up list). The response'ssetuplist holds every outstanding item in full:id,feature,status(TODO or BLOCKED),text,fixWith(the tool call, when an agent can fix it),adminPageand, for a blocked item,waitingOn.
Each item names the tool call that shows the detail. The sections are read independently, so a failing source shows as unavailable instead of failing the whole call. The platform's admin notification events (new orders, media uploads, basket adds) are an activity feed, not work to do, so they aren't included.
inventory lowStock lists tracked SKUs at or below a threshold, lowest first. The default
threshold comes from the low-stock-threshold site config key (admin-site-config, default 5),
which the admin product list and the storefront's "only N left" listing badges also use.
It uses the new InventoryService.findLowStock. Untracked SKUs (negative stock, meaning in stock
by default) and SKUs with no stock record aren't reported. Inventory backends other than Mongo
inherit a default that reports low stock as unsupported.
Marketplace channels. channels (mcp:read) and manageChannels (mcp:write) run
marketplace channels (eBay, Google Shopping) through the channel
services and ChannelOperations, the same path as the admin Channels screens. Both refuse, saying
how to turn them on, while channels-enabled is off. Both are openWorldHint tools: category
search, category schemas, eBay policies, connecting and saving a mapping call the marketplace.
channels:accounts(status and message, connected or not, whether the platform has the channel set up, listing counts by state, failed updates, orders that couldn't import, last syncs and error, settings),listings(by account, optionally by states, paged, with each listing's issues and live URL),listing(overrides, attributes, pending AI suggestions, issues and a preview of what would be published: title, category, attributes, per-SKU price and quantity),mappings,searchCategories,categorySchema(required and recommended attributes, closedallowedValuesor openexampleValues),policies(eBay business policies),payouts(optionally unreconciled only, with lines on request) andfailedUpdates.manageChannels:createAccount,connectLink,connectGoogle,updateSettings(priceAdjustmentPercentis stored as basis points; unknown settings are refused),enableProductsanddisableProducts(product ids or SKUs, or a collection, at most 1,000 per call),updateListing(price in minor units, 0 clears; an empty attribute value removes it),checkListings,publish,saveMapping,deleteMapping,suggestAttributes,acceptSuggestions,pause,resumeandretryUpdate.
An agent can't connect eBay. eBay access is granted by the owner signing in to eBay.
createAccount (and connectLink later) returns a single-use connectUrl, valid for 15 minutes,
for the agent to hand to the owner; they can also connect from Channels in the admin. Google
accounts connect with the Merchant Center id (connectGoogle) once the owner has added the service
account that createAccount returns in connectionDetails.
Nothing returns credentials: accounts say only whether they're connected, and the ship-from
postcode is reported as set or not. Failed updates, import problems and payout lines carry order
ids, order numbers and marketplace order ids, never buyer details or tracking numbers.
AI attribute suggestions. suggestAttributes asks the site's own AI provider
(AiChannelAttributeSuggester, the ChannelAttributeSuggester for ChannelSuggestionService)
for the attributes a listing is missing. The prompt holds only the product's title, description and
known attributes, with the channel's specs for each missing attribute; it tells the model to leave
out anything the product doesn't state (no invented brands, MPNs or GTINs). The reply is checked
against the specs: unknown names, values outside a closed list and over-long values are dropped,
and single-valued attributes keep one value. The values are stored as suggestions for the owner
(or agent) to accept with acceptSuggestions; nothing is published from them directly.
What shoppers see. Collection, page and product results carry url, the shopper-facing
address (/collection/…, /p/…, /product/… on the site's domain), so an agent quotes real
links rather than guessing them.
menusmarks the storefront's main navigationmain(thedefault-menu-idsite config key).getreturns the editableitemsandrendered, the links as shoppers see them.manageMenus setItemsreplaces a menu's whole tree, the way the admin menu editor saves it, and refuses a target that doesn't exist, since the storefront silently drops those links. An item can link to a category page with typeMERCHANDISING_NODEand the page's canonical path as the target (/c/fixings/screws), checked against the primary merchandising tree.- A second-level item can have children of its own: the storefront's mega menu shows it as a
column heading over those links, and it can be a heading with text and no link. Sending a
child's
children(even an empty list) replaces what it had; leaving them out keeps them. - Some item settings can only be set in the admin menu editor: a collection item that lists its
sub-collections as its dropdown (traverse tree and depth), members-only, mega or content-panel
display, and items below the third level.
setItemskeeps them from the current item with the same type and target (or, for a heading, the same text), so changing one link no longer turns the Shop dropdown into a plain link.getshows them assubCollectionDepth,loggedInOnlyanddisplayType. A new item, or one whose link changed, starts without them. setMainchanges which menu is the main navigation, and deleting the main menu is refused.footer(menuId) shows a menu as footer link columns on every page. There is no site-wide extension layer, so it gives each of the site's stereotypes amenuGeneratorExtensionin thefooterslot with layoutfooterColumnspointing at the menu, or repoints the one it already has. Running it again changes nothing; pages with no stereotype are left alone, and a stereotype created later needs it run again.- Sites created before the current menu model have a legacy menu (
legacy: true).setItemson one writes a current-model menu under the same menuId, which the storefront then renders instead. - New sites now point
default-menu-idat themain-menuthey are created with. Before this, the key defaulted tomainMenu, which no new site has, so new shops had no navigation at all.
manageExtensionConfig refuses a slot the item doesn't render (a block there would never show;
mainSection, for example, doesn't exist on a collection). It stores jsonComponent,
heroConfig and sceneConfig specs as the JSON strings those extensions read, even when they
arrive as objects, and validates jsonComponent with JsonComponentValidator. Each slot in a
heroConfig (title, cta, ...) is validated the same way: a slot that isn't a component object,
or whose component is invalid, is refused, because the hero would otherwise drop it from the page
without a word. update can also move a block (pageLocation) and show or hide it (enabled); a
property sent as null or "" is removed (extensions read a blank value as unset, and some MCP
clients drop nulls from tool arguments). extensionConfig lists the blocks an item inherits from
its stereotype, and whether its own blocks replace them.
Writes that save but may not render as meant come back with warnings: the validator's warnings for
jsonComponent and hero slots (unknown props or style tokens), a hero slot name the hero doesn't
render, and properties the extension's schema (extensions getSchema) doesn't list. Unlisted
properties are still saved, since older configurations may rely on them; displayPriority,
pageLocation and pageTemplateOverride are accepted for every extension.
For a page, draft: true makes manageExtensionConfig change the page's unpublished draft
instead of the live page, previewDraft answers the shop preview's link on the page, and
publishDraft / discardDraft (with force for a conflict) finish it; extensionConfig reports and, with draft: true, lists the draft. See
Block Drafts.
manageExtensionConfig add and update return a compact result: id, index, extensionName,
pageLocation, enabled, displayPriority and propertySizes (each property's length in
characters). jsonComponent and heroConfig specs run to 5-30KB, and echoing them on every call
made bulk page builds very token-heavy. Pass echoValues: true to get the stored
configurationProperties back; extensionConfig (the read tool) always returns the full values.
extensions getSchema returns real config fields for the extensions that predate the v2
editable-field model too (blogMastheadExtension, faqExtension, the static and scrolling
carousels), through BadgerExtension.getDeclaredConfigFields(). Other legacy extensions still
return a null configSchema until they declare theirs.
Branding. getDesignBrief also returns shop, which holds the shop's name, URL and logo, and
customCss, a summary of the hand-written stylesheet (chars, version), or null if the shop has none.
Pass includeCss: true to get the stylesheet's text in customCss.css too. It is left out by default
because it can be up to 100KB. shop also carries the current theme and the tenant's
productImagePath, read-only: it is the base every media URL (blog cards, mastheads, product
images) is resolved against, so if images 400, check it points at a working image host. Only a
superadmin can change it (System > Tenants, see multi-tenancy), not a site admin, so the MCP does not
either; ask the platform operator.
manageBranding (mcp:write) has these actions:
setDesignBriefdeep-merges the sections it is given into the current brief (or the defaults), checks that palette colours are hex, and saves throughDesignBriefService.saveBrief, which recompiles the tenant's theme CSS.schemes(block colour schemes) is merged by key rather than replaced: a scheme sent with colours or a name replaces the stored one for that key, one sent with only its key goes back to following the palette, and keys must bedefault,subtle,inverse,brand,custom-1orcustom-2(ColourSchemes.validate).getDesignBriefreturns every scheme with its colours filled in asschemes; a block picks one with itscolourSchemeproperty (Colour schemes).setIdentitychanges the shop name and logo throughSiteManagementService.updateSite.logoUrltakes a media id, a mediaurlorkey, or any http(s) URL; a media id or key is stored as the absolute image-host URL, as the admin upload stores it.socialAccountssets the social profiles (facebook,instagram,twitter,linkedin,pinterest,youtube, andtiktok, which only the structured data lists).iconUrltakes the same forms aslogoUrland becomes the shop icon (ShopIconService.setIcon: favicon and home-screen icon sized from it, any hand-named icon files cleared; empty removes it); it needs no site update, andgetDesignBriefshows it asshop.iconUrl.socialAccountsis merged into the current ones, a blank value removes a network, a profile URL is kept as given and a handle loses its leading@(SocialProfileslinks a URL as it is and a handle after the network's address).getDesignBriefshows them asshop.socialAccounts. AndshowSiteName(true/false) sets whether the header shows the name beside the logo: false for a wordmark logo that already spells it (thehideSiteNameInNavtheme option). It is refused on a theme without that option (none of the shipped themes lacks it).getDesignBriefreports it asshop.showSiteName.timeZonesets the shop's time zone (an IANA id such asEurope/London; anythingZoneId.ofrefuses is rejected), which event times, the scanner's "today" and admin dates use. The read view reportsshop.timeZone(the zone in use) andshop.timeZoneSource:set,locale(implied by the shop's language) ordefault(Europe/London assumed, worth setting). The domain and live/demo mode are deliberately not exposed; they stay in the admin UI.listThemesreturns the storefront themes (name, family, description, bestFor) and the current one.setTheme(themeName) switches the storefront theme. It goes through the same site update the admin tenant editor uses, after checking the name against the theme catalogue, and needs the same authority as the admin (mcp:write, which only admin-level roles are granted). It returns the previous and new theme. The admin's own selector page also keeps nav settings per theme; those are not touched.-
setCustomCssreplaces the whole of the tenant's hand-written stylesheet ($cssOverride$/global.css). It is the same file the admin CSS editor (Settings > CSS Editor) edits, and it goes through the sameCustomCssService.GlobalCSSThemeExtensionstill links it after the Design Brief'stheme.css, so authored rules win. An emptycssremoves the stylesheet. Every save bumpscss-override-version, which busts the five-day browser cache on/dynamic/css/global.css?v=N. Shoppers see the change once the extension's five-minute per-site cache expires. The tool refuses a stylesheet over 100,000 characters. It also refuses</style,<script,expression(andjavascript:, in any case, with whitespace between tokens, and after stripping comments and decoding CSS escapes. These checks are defence in depth; the file is served astext/css. The tool description steers agents to the storefront tokens (var(--color-*),var(--font-family-*), and so on) so a later brief change still restyles the page. -
previewTheme,previewDesignBriefandpreviewCustomCsstake the same parameters assetTheme,setDesignBriefandsetCustomCssand check them the same way, but stage the change in the shop's private preview (Theme and Style Preview) instead of saving it. Previews add up, andpreviewDesignBriefmerges into the draft brief the preview already holds. Each answers the preview's shareurl(works without signing in untilexpiresAt, seven days after the last change),changes(theme,designBrief,customCssChars; 0 means publishing removes the stylesheet), and, as relevant, the merged draftbrief, itscontrastand the stylesheet'snotes. The tool description points agents at these as the safer route than theset*actions, which go live at once. publishPreviewputs everything the preview holds live throughSitePreviewPublisher(the admin's Publish) and returnstheme,designBrief,customCss, the brief'scontrastandshopUrl; it fails when the shop has no preview.discardPreviewdrops it and returns{discarded}.getDesignBriefreports the open preview aspreview(null when there is none).
Because setCustomCss replaces content, manageBranding is annotated destructiveHint: true.
Site Text. siteText lists the shop's Site Text overrides (list, the first 50, optionally
those whose key starts with keyPrefix) and shows one key (get: its overrides by locale and the
platform's own text). manageSiteText sets a key's text for a locale (set, creating or replacing
the override) or removes overrides (delete, one locale or all, so the storefront goes back to the
platform's wording). The locale defaults to the site's default locale, else en. Both go through
SiteTextService, the same path as Admin → Settings → Site text, and BadgerMessageSource drops
the cached text on every pod, so a change is live at once. set refuses a key no
messages*.properties bundle defines (unless the site already overrides it), since such a key would
save and do nothing, and refuses script (<script, javascript:, on…= handlers). Some keys, such
as footer.disclaimer, are rendered as HTML.
Search. synonyms lists a site's search synonyms (list, optionally by status), explains a
search (explain: hit count, top results, applying synonyms, whether a given product is indexed and
which query words it lacks, and what to fix) and lists the searches that found nothing (gaps).
manageSynonyms creates, updates and deletes synonyms (live immediately), accepts or rejects
AI suggestions, asks the AI for new ones (suggest, saved as suggestions for review) and resyncs
search from the saved set. See Search Synonyms; the search-tuning skill
walks an agent through it.
Search rules: pins, boosts, buries, redirects and banners. Products can be named by SKU,
variant SKU, URL name or exact name (ignoring case), and a category (category) by node id, path
such as /c/tools/drills, or name in the primary tree; an ambiguous name is refused with the
candidates (products' names and SKUs, categories' paths). productRanking lists the search-term
rules (rules: id, term, pinned, boosted and buried products as SKU and name, redirect and
banner), shows a category's ranking (category; manualList: true means the category is a
hand-ordered list, so its ranking is ignored) and previews a listing (preview, by category,
query or both: the first limit results, default 12 and at most 48, in the order shoppers see
under "Featured", each marked pinned, boosted, buried or normal, plus pinnedNotListed).
manageProductRanking changes one product at a time for a category or a query: pin (at
position, 1-based, default after the existing pins), boost, bury and unrank take products
and leave the rest of the ranking (and a rule's redirect and banner) as it was; a term with no rule
gets one, and unranking a rule's last product deletes it unless it has a redirect or banner.
setRule (updates the term's existing rule, or the rule with the given id, otherwise creates
one) and setCategory replace the whole thing: the three lists (pinned, boosted, buried)
and, for setRule, redirect and banner (bannerText, bannerLinkUrl, bannerLinkText), so a
value left out is cleared. deleteRule (by id or query) and clearCategory remove them. A rule
needs at least one product, a redirect (a site path such as /p/returns, never /search) or
bannerText (plain text, at most 300 characters; the link a site path or an https:// address).
A variant stands for its product and each list holds at most 100. A rule applies when a search
matches its term exactly (normalised); a category's ranking applies when browsing it with no search
term; both only under the default "Featured" sort. They go through SearchRankingRuleService and
MerchandisingTreeService.setNodeRanking, as the admin UI does; names are resolved by
ProductReferenceResolver and CategoryReferenceResolver, and preview runs
MerchandisingQueryService.search.
Landing pages. The same two tools hold a category's landing-page
rules (brand or attribute pages such as
/c/womens/dresses/colour/red). productRanking landing shows a category's mode (inherit,
off or own), its own rules, the tree default and the pages it has now (path, value, product
count); with no category it shows the primary tree's default rules and the facets a rule can
use. manageProductRanking setLanding replaces a category's own rules with landingRules
([] switches its pages off), or the tree default when no category is given; inheritLanding
drops a category's own rules so the default applies. Each rule is {facetId, pathSegment,
minProducts, overrides: [{value, heading, metaTitle, metaDescription, intro, excluded}]}; they are
validated by FacetLandingRuleService (an invalid rule is a tool error naming the problem), the
path the admin page and REST API use.
Category trees. merchandisingTrees (mcp:read) reads the merchandising trees behind the
/c/... pages: trees (id, name, slug, primary, category count), outline (every category of a
tree, by id or slug and the primary one by default, depth first: path, name, a short backing
such as collection:wood-screws, taxonomy:lvl-1 +2 filters, query, list:12 or group, and
hidden, notProductHome and replaces when set; at most 300, then truncated) and node (one
category by id, path or name: its full backing, SEO title and description, own facets,
replacesCollections, excludeAsProductHome, parent and children, and storefront url).
manageMerchandisingTrees (mcp:write) has createTree, updateTree (only the fields passed
change; primary: true demotes the current primary), deleteTree, buildFromCollections (name,
slug: one category per collection, as the admin's Build it from the shop's collections),
matchCollections, createNode (name, backing, parent; seoName is made from the name when
left out, and position places it), updateNode, moveNode (parent, where /c is the top
level, and/or a 1-based position), deleteNode (with everything under it),
setReplacesCollections and setExcludeAsProductHome. A backing is the JSON node returns,
{type, ...}, with type one of manualCollection (collectionSeoName), taxonomyProjection
(taxonomyLevelId, attributeFilters), virtualQuery (query), manualList (productSkuIds;
products may be named as for rankings and are stored as SKUs) or group. Everything goes through
MerchandisingTreeService's validated createTree, updateTree, createNode, updateNode and
moveNode, as the REST API does, and its refusals come back as tool errors. With a tree named,
categories are looked up in that tree; otherwise by id in any tree, or by path or name in the
primary one. Rankings and landing pages stay in productRanking / manageProductRanking.
manageProducts takes mainCategory (a category id, path or name; none clears it): the
product's chosen breadcrumb home (primaryCategoryNodeId). products get returns it as
mainCategory (the category's path) beside homeCategory, the category the breadcrumb actually
leads to (CategoryNavigationService.findHomeNode: the chosen one when it is a visible category of
the primary tree, otherwise worked out from the product's taxonomy level and collections).
Building taxonomies. taxonomies reads them (list and get say which one is active: the
site's configured taxonomy, not the document's legacy flag; get gives every level's levelId,
parentLevelId and description, and every attribute's id, type, values, rules and display
settings). manageTaxonomies (mcp:write) builds and edits them one change at a time: create
(name, description), update, setActive, delete, addLevel (name, parentLevelId, left
out for a top-level category, and a 0-based position), updateLevel, moveLevel (with its
sub-levels), removeLevel (likewise), addAttribute (levelId, attribute; an optional
attributeId, otherwise made from the name, and the same id on sibling levels is one filter),
updateAttribute (only the keys given change, a key sent as null clears it, and addValues /
removeValues edit the allowed values in place) and removeAttribute. The attribute object takes
name, type, mandatory, allowedValues, helpText, displayOnProductPage, displayLabel,
facetDisplay, unit, swatches and the rules minLength, maxLength, minValue, maxValue,
pattern and errorMessage; an unknown key is refused. Structure edits go through
TaxonomyEditService, which applies the change to a copy of the stored tree and saves it with
TaxonomyService.saveStructure, the editor's write path: the same normalising and validation
(every problem returned in one tool error), and a revision check so an edit made in the admin
meanwhile is never overwritten. Every edit is previewed with TaxonomyImpactService.previewChanges
first. dryRun: true returns that preview (impact: {kind, label, products} for levels removed or
moved, attributes removed or changed to another type, and allowed values removed that products
hold) and writes nothing; a real edit of the active taxonomy that has an impact is refused unless
confirm: true. setActive checks the taxonomy engine entitlement and previews with
previewActivation; switching from another active taxonomy clears every product's classification,
so, like the admin's typed confirmation, it needs mcp:admin and confirm. delete needs
mcp:admin (the admin's ADMIN role) and refuses the active taxonomy. The taxonomy skill walks an
agent through designing one, and badger-mcp through building it and classifying products.
Taxonomy filters. taxonomies get shows each attribute's facetDisplay, unit and
swatches. manageProductTaxonomy setFilterDisplay (no skuId) sets them on an attribute of the
active taxonomy: facetDisplay LIST, SWATCH or RANGE; unit for a range (mm); swatches
(value → #hex or colour name) for values not named after a colour. An omitted unit or
swatches keeps the current one, and a swatch colour the storefront would ignore is refused with
the values named. It saves through TaxonomyService.updateFacetDisplay, as the taxonomy editor's Shown in filters as setting
does, which queues a search reindex.
Variant option filters. variantGroups list shows each group's taxonomyAttributeId (the
filter its options count towards; null means the attribute whose id is the group's code) and
attributeValues (option → filter value). manageVariantGroups setFilterMapping sets both for a
group by code (attributeId, attributeValues); a blank attributeId and no values clear the
mapping, and an unknown code is a tool error. It saves through VariantGroupService.setFilterMapping,
as the taxonomy editor's Variant options card does, which queues a search reindex.
manageVariantGroups setSwatches sets the colour dots Nova's variant picker draws on a group's
options (swatches: option → #hex or colour name; empty clears; a value that isn't a colour is a
tool error), through VariantGroupService.setSwatches; variantGroups list shows them.
manageVariantGroups setOptionLabel sets what the picker's buttons say (optionLabel: price for each
option's price, as donation amounts want, or name, the default; anything else is a tool error), through
VariantGroupService.setOptionLabel; variantGroups list shows it.
Products. manageProducts create and update also set miniDescription, comparePrice,
shippingRequired, taxable, productTypeDecorators, quantityType and min/maxQuantity.
update changes only the fields passed; 0 clears comparePrice or maxQuantity, and []
clears the decorators. Decorator names are checked against ProductDecoratorService's registered
decorators, and quantityType against QuantityType; an unknown value is refused with the valid
ones listed, and nothing is saved. A created product is shippable unless it is a donationProduct,
which defaults to shippingRequired=false and quantityType=PRICE_AS_QUANTITY (the shopper enters
an amount, with the product priced at one currency unit) unless those are passed. Create and
update return the full product, as products get does, so the applied defaults are visible.
Product attributes. manageProducts create and update take attributes: label → value
pairs merged into the product's attributes, the rows the attributeDisplayExtension block
shows (for example {"Fabric": "100% cotton", "Fit": "Relaxed"}). Existing keys keep their place
and new ones are added at the end, which is the order the block shows them in. A blank or null
value removes the key. Values are text, numbers or true/false; a list or object is refused. Keys
the platform manages through other parameters (searchTerms and an event's details and tickets,
ProductTools.MANAGED_ATTRIBUTES) are refused, and nothing is saved. products get returns
them in attributes.
Product search terms. Extra words a product should be found by (they are indexed as
searchTerms alongside the name and description) live in the product's attributes.searchTerms,
comma-separated. products get returns them as a searchTerms list. manageProducts create and
update take searchTerms (replaces the whole list; [] clears), addSearchTerms and
removeSearchTerms; they apply in that order, so one call can say "these, plus X, minus Y".
Terms are trimmed, blanks dropped and duplicates removed (case-insensitively; the stored
spelling is kept). A term containing a comma is refused, since it would be stored as two; so is a
term over 50 characters, or a list that would leave a product more than 50. These rules live in
ProductSearchTerms and are shared with the admin editor
(Search section). The save
goes through ProductService, so the product is reindexed like any other edit.
Media. media (mcp:read) lists and reads media items. manageMedia (mcp:write) has four
actions, and all take title, altText and tags (comma-separated; update replaces the set,
empty clears it). import and update also take focalPoint ("x y" percentages from the top
left, top/center/bottom/left/right, or none to clear; see
Image Focal Point), and every reply includes it:
importadds an image, either fromurl(a public https URL the server fetches) or fromcontent(base64, optionally adata:URL, with an optionalfilename; capped at 64 KB because the model has to write every character and one slip corrupts the image).filenamenames the stored file for either source. It returns the new media'sid,url,key,tagsand, for JPEG, PNG and GIF, itswidthandheight. Aurlimport records the address it came from (Media.sourceUrl); importing the same address again returns the item already in the library (alreadyImported: true, any title, alt text or tags passed are applied to it) instead of storing a second copy. The image is stored throughMediaService.uploadNew, the same path as the admin image upload (/admin/imageUpload), so it lands in the tenant's bucket at<siteId>/media/<millis><name>and AI image tagging runs when enabled. Every upload route reduces the name to one safe segment (StorageKeys.filename: no folders, no../), so a caller can't choose where in the bucket the file goes. AI tagging only fills a blank title or alt text, so values passed toimportare kept.- Every media reply gives
urlas an absolute address: the shop's image host (productImagePath, e.g.https://images.bdgr.co.uk) pluskey, the stored path (<siteId>/media/<millis><name>), built byMediaUrls.absolute. Useurlwherever an image is referenced: markdown (),setIdentity'slogoUrl, another site. deleteremoves a media item bymediaId(permanent; an id from another shop is "not found"). It removes the library entry only, like the admin delete, so check nothing still points at the image.prepareUploadis how an agent sends a file from its own machine. It returns a one-timeuploadUrl(https://<shop>/media-upload/<token>) and a ready-madecurl -Tcommand; the agent runs the command and the file's bytes go straight to the server without passing through the model. The reply is the new media'sid, absoluteurlandkey. The title, alt text, tags andfilenamegiven toprepareUploadare applied to the new item. The link works once, for ten minutes, and only on the shop it was issued for. The token is the only credential, so Badger stores just a hash of it, and a spent, expired or unknown link all answer 404. The upload is checked like any other import: the bytes must really be a JPEG, PNG, GIF, WebP or AVIF of up to 10 MB, and a rejected upload still uses the link up, so ask for a new one. It needs a shell that can reach the shop; where the agent has none, useurl. The endpoint isMediaUploadControlleroverMediaUploadLinkService, outside/mcpbecause that prefix needs an OAuth bearer token. A shop in demo or restricted mode lets/media-upload/through without the demo password (DemoServiceImpl), since the one-time token is the credential.update(mediaId) edits an existing item.titleis editable because auto-captioning can guess wrong (a "Grey T-shirt with Mountain Rescue Bolton logo" for another team's shirt).
URL fetches go through SafeHttpFetcher (commerce-core), which guards against SSRF:
- https only, on port 443, with no credentials in the URL;
- every address the host resolves to must be public. Loopback, private (including the k3s pod
and service ranges), link-local (including cloud metadata at
169.254.169.254), carrier-grade NAT, multicast, reserved, and IPv6 forms that wrap one of those are refused. The check runs inside the HTTP client's DNS resolver, so the connection uses exactly the addresses that were checked, and DNS rebinding can't slip past it. An unresolvable host gets the same error as a private one, so the tool can't be used to probe internal DNS names; - redirects are followed by hand, at most 3, and each hop is checked the same way;
- no proxy, cookies or retries. It times out after 5 s to connect, 10 s between reads and 30 s
overall, and refuses a body over 10 MB while reading, whatever
Content-Lengthsays; - the response must declare JPEG, PNG, GIF, WebP or AVIF, and the bytes must be one of those too. The type the bytes turn out to be is what gets stored as the object's Content-Type and file extension. SVG isn't accepted, because it can carry script.
Delivery options. manageDeliveryOptions create gives a new option the same countries as the
shop's existing options, unless countryCodes (two-letter ISO codes) says otherwise, because checkout
offers an option with no country list to every country. It also copies their currency. update can
change countryCodes.
localDelivery (location, minimumOrder in pence, travelMinutes) makes an option the
restaurant's own delivery from that location; {"off": true} makes it a posted option again.
A delivery option has no "free over a spend" threshold: free delivery over £X is a promotion
(managePromotions with freeDelivery and minimumSpend, and freeDeliveryOptions to limit it
to some delivery option codes), which counts only the items being delivered.
Catalogue reads and writes.
products getreturns the product'sstereotypeId(its page layout; adding the first variant moves a plain product ontovariantProduct) andproductTypeDecorators, empty for a plain product.collections products(collectionId or seoName, paged) lists a collection's products in the order its page shows them: highestrankfirst, then oldest, disabled ones flagged. The rank is the product'scollectionOrderingattribute (the admin's "Promotion rank"), set withmanageProducts updateattributes: {"collectionOrdering": 10}; it applies in every collection the product is in.manageProducts setImagesalso takes a variant's skuId, setting that variant's own images (a colourway's photos), which the variant picker shows when the variant is chosen.- Gift card products are made with
manageProducts createandproductTypeDecoratorsvirtualGiftCard,physicalGiftCardorgiftCardTopUp, as the admin's new gift card product screen makes them: a virtual card or top-up needs no delivery (unlessshippingRequiredsays otherwise) and gets the add-to-basket form that asks for the recipient or the card to top up.giftCardsreads the cards sold. siteConfig listtakessearch, text matched against each key, its admin name and description (e.g.announcement), alone or within acategory. Results are paged (totalElementssays how many match).siteConfig billingreads the shop's own Badger Commerce plan: name, state (TRIALING,ACTIVE,PAST_DUE,CANCELLING,PAUSED), trial end and days left, price and total without VAT, add-ons, extra locations, a booked change, and usage against each limit (warningOnlyfor the monthly customer limit). No Stripe ids or payment details, and no way to change the plan: that is Plan & billing in the admin.
Shoppable images. shoppableImages (list, get by handle) and manageShoppableImages (save,
delete) read and edit pictures with the products in them. save with an unknown handle creates one
(title, mediaId and items needed); items replaces the products: [{sku, options, quantity, x, y}],
options the variant choices pictured by group code, x/y the hotspot as percentages. The
shoppableImage block shows one. See Shoppable images.
Restaurant ordering. modifierGroups / manageModifierGroups read and edit menu choices (save
creates or patches a group, options replaces its options; setAvailable is the sold-out switch for
one option). manageProducts takes a menu object for menuItem products: dietary, allergens
(the 14 UK codes) and modifierGroupIds in display order, each replacing what was there; unknown codes
and group ids are refused. manageLocations takes ordering (the location's ordering settings, keys
given change) and deliveryArea (postcodePrefixes, blockedPostcodePrefixes, radiusKm), plus
pause (optional minutes) and resume. orders kitchen lists each kitchen's orders by state
(status new, active or done; new and active by default), with the choices, notes and
allergens on each line; orders get shows a restaurant order's kitchen state. See
Restaurant ordering.
Table bookings. reservations reads a location's diary for a date (diary) or one booking by id
or reference (get); it needs mcp:write, as bookings carry guest details. diningRoom reads a
location's room (get, with menuRootSeoName, the collection whose children are the table menu's sections) and runs the booking tester (test: date, partySize, online false for
staff), naming the tables each time takes and why other times are refused. manageReservations acts
as staff: book (a phone booking at a local startsAt, with name and a phone or email in
contact), amend, cancel, arrive, seat (optional tables), finish, noShow, walkIn
(tables required), approve, decline, and saveRoom (the whole room as diningRoom get
returns it; the room's problems come back as the error; stations, courses and menuRootSeoName left out keep what the room has), and placeTables (placements: {name, shape, x, y, w, h, rotation} in centimetres, matched to tables by name; only those fields change, and the reply lists the tables placed, unknown names, tables still unplaced and overlaps). See Table reservations.
Appointments. appointments (needs mcp:write, as it returns customer details) reads a location's
diary for a date (diary), one appointment (get), the team, appointment types and how Any available is
chosen (setup) and runs the booking tester (test: date, type, practitioner, online false for staff),
naming who takes each time and why others are held back. manageAppointments acts as staff: book (a local
startsAt, a type, a practitioner or none for Any available, name and a phone or email in contact),
amend, cancel, arrive, start, finish, noShow, reassign, block and unblock (time set aside on a
practitioner's day) and saveSetup (the whole setup as appointments setup returns it; a type's
paymentMode can only be NONE until online payment ships). See Appointments.
Table service. tableService is read-only (mcp:read): tabs lists the tabs still using their
tables (table, covers, state, total and paid so far), today gives a day's tabs, covers, takings
(card and cash), service charge, tips and voids and comps (from as the day, today by default), and
tips the tips and service charge for a period (from, to, this month by default; at most 400
days) as totals, card, cash and the monthly pool per place of business, never per worker. Each takes
an optional locationCode. See Table service.
Pages. managePages create gives a page the defaultPage stereotype when none is passed (the
admin page editor's default), so it gets the stereotype's blocks (nav menu generator, footer, CSS);
a blog post passed blogPost keeps that, and update leaves the stereotype alone unless given one.
A blog (blogPage) created without a parent is filed under blogs, as the admin's Blog screen
files it, so the admin blog list and the RSS feed find it.
managePages setImages sets a page's image from the shop's media library (mediaIds,
pageId or seoName). A page shows one image, so it takes a single id, and [] removes it. The
image is stored as the blog masthead's mediaId, which the masthead, the blog list and
latest-posts cards, and og:image all read, and which the admin masthead editor shows. A masthead
inherited from the stereotype is copied onto the page first, the same as editing it in the admin.
A page with no masthead (an ordinary page) keeps the image in its socialImageId attribute
instead: it shows nowhere on the page itself, but link previews (og:image, the Twitter/X card) and
the page's share kit use it. create and update take publishedDate (2023-04-15, or an ISO
instant) for posts imported from an old site. It is stored as the page's createdDate, which the
blog templates show and the blog extensions sort by, and which the admin post editor already edits
as the post's date. pages get returns publishedDate, imageMediaId and imageUrl (absolute,
on the shop's image host).
create and update take attributes, a JSON object of strings ("" removes one): author,
the byline the blog masthead shows under a post's title; metaTitle, the <title> and link-preview
title in place of the page name; and metaDesc, the search and link-preview description in place
of the page description. The last two are the admin page editor's SEO Title and Description. Any
other key is refused.
The admin, MCP and change requests build pages with the same defaults
(stereotype, blog parent, post template and seoName prefix, masthead image).
Wherever a page is named by seoName (pages get, managePages update and setImages), a
leading slash doesn't matter, and a post can be named by its own slug without its blog's prefix
(first-post for blog/first-post); a slug that matches posts under two parents is refused with
both seoNames listed. pages list with a searchTerm matches it literally, ignoring case, in the
site's page names, seoNames, descriptions and meta descriptions, blog posts included.
create also takes body, markdown saved as a markdownFragment block in mainSection (styled
as an article on a post, in the page-width container elsewhere), and mediaIds, the page's image
as setImages sets it (PageAuthoringService.addMarkdownBody and setPageImage). A blogPost
created with a body also gets a related-articles block after it, unless its stereotype already
shows one. So a post with its text, masthead image, byline and meta description is one call. To
show a library image inside the markdown, use the media's absolute url (the shop's image host
followed by the media's key): .
A bare key or a made-up URL won't load.
Drafts and previews. managePages create with draft: true saves an unpublished draft (see
Content Management). A draft is dated when it is published, unless it was
given a publishedDate (on create or with update): the preview then shows that date and
publishing keeps it. previewLink (pageId) returns a 14-day previewUrl that shows a draft or
hidden page as it will look. publish (pageId) puts it live and records the user behind the token
as its approver. pages get returns draft and, for a hidden site page, previewUrl;
pages list and listChildren return draft.
Site traffic and searches. siteTraffic (mcp:read, counts only) has five actions.
timeSeries and topPages read the page-view statistics (group pageViews, productViews,
collectionViews or skusAdded; daysBack). topSearches and zeroResultSearches read the site's
search term analytics (see Search and Discovery):
the most-searched terms, and the terms whose searches found nothing, each with count and the
latest search's lastResultCount. They take optional from and to (yyyy-MM-dd, default the
last 30 days, with from clamped to the 90-day retention) and limit (default 10, max 50), and
return the range actually used. searchPerformance takes the same parameters and returns, for the
most-searched terms, searches, clicks, addToBaskets, orders and revenue (minor units),
the rates per search (clickThroughRate, addToBasketRate, conversionRate, 0 to 1) and
rarelyClicked (searched at least 10 times, finds products, under 10% clicked: a candidate for a
synonym or a search rule), plus tracking (false when the site's
search-click-tracking-enabled is off, so the click and sales counts stay 0). Terms carry no user,
session or IP data. productEngagement reports per-product engagement in one listing (see
Product Engagement): group names it (blank or all, a category by path,
name or id, or search:<term>), with the same from/to and limit. It returns the listing's
totals, its most-shown products, viewedRarelyBought and sellsWellRarelyShown, each with
impressions, averagePosition, clicks, views, adds, orders, units, revenue and revenue per thousand
impressions (minor units), click-through per impression and add and conversion rates per view, plus
recording and rankingEligibility (Enterprise, and orders in the last 30 days against the
minimum). It never includes margin, and there is no MCP tool for cost prices: they are
commercially sensitive and stay out of AI conversations (see Cost Prices).
productRanking action goals and manageProductRanking actions setGoal and
deleteGoalSchedule manage what ranking by what sells optimises: setGoal
takes goal (units, conversion, revenue or margin) and sets the shop default, or with
category that category's own goal (a blank goal makes it inherit), or with from, to and
name adds a dated schedule (limited to category if given). goals returns the shop default,
active and the reason it isn't, category goals and schedules, and with category the goal
applying there today and why (appliesNow). productRanking action boosts lists the
learned boosts waiting or applied (listing, product, goal, score against the
listing's average, orders, usual position, status, reason) and the shop's mode;
manageProductRanking actions acceptBoost and rejectBoost take its id.
Token budget. McpToolConventionsTest prints the serialised tools/list size and fails if it
exceeds its budget. The list is re-sent on every turn, so treat description growth as a cost.
McpToolListCompactor takes Spring AI's boilerplate out of every listed tool before the server is
built: the input schema's $schema URL, number formats (int32), a title that repeats the name,
and the idempotent and open-world hints at MCP's defaults (plus destructive and idempotent on
read-only tools). readOnlyHint, and destructiveHint on tools that write, always stay, because
Claude's connector directory requires every tool to state them. About 13% of the list, with nothing
a client reads differently; the budget is measured after it.
Security Details¶
- JWT validation: Tokens are validated against the auth server's JWK set (
/oauth2/jwks) - Tenant isolation: The
site_idclaim in the JWT (if present) must match the tenant resolved from the request domain; on the central host the tenant is that claim, and a token without one is refused - Cross-tenant prevention: Tokens with a
site_idclaim for one site cannot be used on another - Dynamic registration fallback: When JWT lacks tenant-specific roles, McpAuthFilter resolves roles from the database and caps the token's consented MCP scopes by them
- MCP tokens don't work on the REST API: any client can register itself, and the person connecting it agreed to the MCP scopes on the consent screen, not to the client acting as them everywhere. The REST API (
BadgerJwtAuthenticationConverter) answers401to a token with anmcp:*scope or an MCP URL as its audience. Central tokens also leave the user's roles out, so they wouldn't pass the REST API's role checks even without that refusal - WWW-Authenticate header: 401 responses include a
Bearerchallenge withresource_metadata; MCP clients then initiate OAuth2 discovery - Platform separation: platform tokens (
bdgr_platform) work only on/mcp/platformof the central host, and only for a platform operator; shop tokens are refused there
Testing¶
- In the build:
McpHttpEndToEndIntegrationTest(web module) drives/mcpthe way a client does. It sends JSON-RPC over HTTP through Jetty,McpAuthFilter, the tool aspects and Spring AI's stateless transport. It checks the 401 challenge,initializeinstructions,tools/listhints, scope refusal, readable errors and a write round trip on its own tenant.McpCentralEndpointIntegrationTestdoes the same for the central URL: two shops behind one host, each token reaching only its own, and a token bound to no shop sent back to reconnect.McpPlatformEndpointIntegrationTestcovers the platform connection: its own tool list (and none of it on the shop server), an operator giving someone access to a tenant, and the refusals between platform and shop tokens. The*ToolsIntegrationTestclasses call the tool beans directly, so on their own they can't catch transport, filter or serialisation breaks. - Against the local stack:
dev-scripts/mcp/has the sandbox tenant (sandbox.sh), a headless OAuth client and scripted smoke test (mcp_client.py), and standard scenario prompts that an agent runs headlessly and that are then checked (run-scenario.sh). See its README.
Debugging¶
Diagnostic Filters (dev profile only)¶
Two diagnostic filters log every OAuth2 handshake step:
McpOAuthDiagnosticFilter(web app) — logs requests to/.well-known/*and/mcpOAuthDiagnosticFilter(auth server) — logs requests to/.well-known/*,/oauth2/*,/connect/*
Look for [MCP-DIAG] and [AUTH-DIAG] prefixes in the dev server logs.
Test Script¶
Run ./dev-scripts/test-mcp-oauth-flow.sh to validate each step of the OAuth2 flow with curl:
./dev-scripts/test-mcp-oauth-flow.sh # defaults
./dev-scripts/test-mcp-oauth-flow.sh https://mysite:9443 https://localhost:9463
Token rejected straight after login¶
If an MCP client logs in successfully but every call gets a 401 with
OAuth2 authentication temporarily unavailable, the web app couldn't build its JWT decoder, so
it rejects every token on every site. The JWT decoder unavailable warning from
McpAuthFilter logs the underlying cause: usually AUTH_ISSUER_URL doesn't match the auth
server's published issuer, or the pod can't fetch the auth server's key set.
Spring fetches the key set (/oauth2/jwks) from the public issuer URL with the Java/<version>
user agent, which Cloudflare can answer with a 403 challenge. Point the web app at the
in-cluster auth service instead with
SPRING_SECURITY_OAUTH2_RESOURCESERVER_JWT_JWKSETURI=<AUTH_INTERNAL_BASE_URL>/oauth2/jwks;
tokens are still checked against the AUTH_ISSUER_URL issuer.
Enhanced Logging¶
For deeper debugging, add to application-dev.yml: