Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Removed API key authentication from the MCP endpoint
Damian Legawiecf0c3812627a3
diff --git a/docs/developer/agentic/admin-mcp.mdx b/docs/developer/agentic/admin-mcp.mdxindex bfd3c3a14b..2de5585613 100644--- a/docs/developer/agentic/admin-mcp.mdx+++ b/docs/developer/agentic/admin-mcp.mdx@@ -20,119 +20,25 @@ https://your-store.com/api/v3/admin/mcp```</Note>-## Two ways to connect+## Connecting-| | Who it is for | What the agent may do |-| --- | --- | --- |-| **Sign in** (OAuth) | A merchant connecting a consumer client — claude.ai, Claude Desktop, ChatGPT | What the signed-in person approves, never more than their own role allows |-| **A secret API key** | A developer configuring an agent they run themselves — Claude Code, Cursor, VS Code, your own code | Exactly the scopes on the key |--Signing in needs nothing created first: paste your store's MCP URL into the client, and it will walk you through approving access. Everything below the next section is the key-based path.--## Signing in--A consumer client asks for your store URL, then opens a Spree page listing what it wants to do. Approve it and the client is connected; nothing is copied or pasted.+Paste your store's MCP URL into the client. It will send you to Spree, where you sign in and approve what the agent may do.```texthttps://your-store.com/api/v3/admin/mcp```+That is the whole setup — there is no key to mint or paste. Every MCP client works this way: Claude Code, Cursor, VS Code, claude.ai, Claude Desktop, ChatGPT and anything else implementing the protocol's authorization.+What you approve matters more than it looks:- **An agent never gets more than you have.** The grant narrows your own permissions, so a staff member who cannot issue refunds cannot approve an agent that can.- **Only what you approved.** Approving product access does not quietly include orders — the tools for anything else are not even offered.-- **Revoke whenever you like.** **Settings → Connected apps** lists everything connected, with the last time each was used. Revoking stops it on its next call.--Each person connects for themselves, so an agent's actions are recorded against the person who approved it.--## Mint a key first--For an agent you run yourself, the credential is an ordinary Spree secret API key, and its scopes decide what the agent is even told exists. A key that can read orders is never shown a refund tool.--1. In the dashboard, go to **Settings → API keys** and create a **secret** key.-2. Name it after the agent that will hold it — "Claude Code, orders" — so you know what you are revoking later.-3. Grant only the scopes that agent needs. `read_products` for a merchandising assistant; add `write_orders` only if it should genuinely be able to cancel and refund.-4. Copy the key. It is shown once.--Revoking the key in the dashboard is the off switch, and it takes effect on the agent's next call.--<Warning>- Give an agent the narrowest scopes that let it do its job. A tool that moves money — refunds, payment capture — is offered to any key holding `write_orders`, and the only thing standing between the model and the action is your client's confirmation prompt.-</Warning>--## Setup with a key--The key travels as a header on every request. Spree accepts it as `X-Spree-API-Key` — the Admin API's own header — or as `Authorization: Bearer`, for clients that only offer a bearer-token field.--<Tabs>- <Tab title="Claude Code">- ```bash- claude mcp add --transport http spree-admin https://your-store.com/api/v3/admin/mcp \- --header "X-Spree-API-Key: sk_your_key"- ```-- To share the connection with your team without putting the key in git, commit a project `.mcp.json` that reads it from the environment and let each developer export their own:-- ```json .mcp.json- {- "mcpServers": {- "spree-admin": {- "type": "http",- "url": "https://your-store.com/api/v3/admin/mcp",- "headers": { "X-Spree-API-Key": "${SPREE_API_KEY}" }- }- }- }- ```- </Tab>- <Tab title="Cursor">- Add to `~/.cursor/mcp.json` for yourself, or `.cursor/mcp.json` in the project to share it with your team:-- ```json- {- "mcpServers": {- "spree-admin": {- "url": "https://your-store.com/api/v3/admin/mcp",- "headers": { "X-Spree-API-Key": "sk_your_key" }- }- }- }- ```-- Cursor reads the key from the file, so a project config puts a live credential in your repository. Either keep it in `~/.cursor/mcp.json`, which is outside the project, or add `.cursor/mcp.json` to `.gitignore` and have each developer mint their own key.- </Tab>- <Tab title="VS Code (Copilot)">- Add to `.vscode/mcp.json`. The `inputs` block prompts for the key instead of storing it in the file:-- ```json- {- "inputs": [- { "id": "spree-key", "type": "promptString", "description": "Spree secret API key", "password": true }- ],- "servers": {- "spree-admin": {- "type": "http",- "url": "https://your-store.com/api/v3/admin/mcp",- "headers": { "X-Spree-API-Key": "${input:spree-key}" }- }- }- }- ```- </Tab>- <Tab title="Your own agent">- Any HTTP client works. Post one JSON-RPC message per request:-- ```bash- curl https://your-store.com/api/v3/admin/mcp \- -H "Content-Type: application/json" \- -H "X-Spree-API-Key: sk_your_key" \- -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'- ```- </Tab>-</Tabs>+- **It is yours, not the store's.** Each person connects for themselves, so an agent's actions are recorded against whoever approved it.+- **Revoke whenever you like.** **Settings → Connected apps** lists everything connected, who approved it and when each was last used. Revoking stops it on the next call.<Note>- Every client above carries the key in its own configuration. A consumer connector — claude.ai, Claude Desktop's connector UI, ChatGPT — has nowhere to put one: it connects from the vendor's servers rather than your machine. Those sign in instead, as described above.+ A Spree API key is not accepted here, and that is deliberate: an agent acts for a person, so it carries that person's own permissions rather than a standing credential with nobody behind it. For scripted access that cannot sign in — a CI job, a server-side integration — use the [`spree api` CLI](/developer/cli/admin-api), which is what API keys are for.</Note>## What the agent can do@@ -221,7 +127,16 @@ A tool is offered only to a credential holding its `permission`, so a key that c## Choosing between this and the CLI-The [`spree api` CLI](/developer/cli/admin-api) reaches every endpoint, handles bulk work, and its output pipes into other commands, so an agent with a shell should generally use it. Reach for this server when the shell is not available, or when the work is conversational — a tool shaped like "cancel this order" gives a model far less room to go wrong than composing the HTTP call itself, and each one runs the same workflow the dashboard runs.+The two surfaces take different credentials, and the difference is the point: **this server takes a person's approval, the CLI takes an API key.**++| | Admin MCP | [`spree api` CLI](/developer/cli/admin-api) |+| --- | --- | --- |+| Credential | Sign in and approve | A secret API key |+| Suits | An agent acting for someone, conversationally | Scripts, CI, bulk work, anything without a browser |+| Reach | The tools listed above | Every endpoint |+| Actions recorded against | The person who approved | The key |++Reach for the CLI when the work is scripted or needs the full API. Reach for this server when an agent is doing the work on someone's behalf — a tool shaped like "cancel this order" gives a model far less room to go wrong than composing the HTTP call itself, and each one runs the same workflow the dashboard runs.## See alsodiff --git a/docs/plans/6.0-mcp-oauth.md b/docs/plans/6.0-mcp-oauth.mdindex d1fe7bdfa7..df19bffc70 100644--- a/docs/plans/6.0-mcp-oauth.md+++ b/docs/plans/6.0-mcp-oauth.md@@ -43,10 +43,13 @@ reach is what makes it a feature rather than a duplicate.indicators and the port-agnostic loopback redirect that Claude Code needs.What it does not carry is the discovery layer, which is small anddeclarative.-- **The API key path stays, permanently.** It is not a stopgap that OAuth- retires. A header is how a CI job, a server-side integration and a- developer's editor authenticate, and none of them should be made to run a- browser flow. commercetools ships both deliberately; so do we.+- **One credential per surface: MCP takes a grant, the CLI takes a key.**+ An agent acts for a person, so it carries that person's own permissions —+ a standing key names neither who approved the agent nor what they allowed,+ and survives the staff member who created it. Scripted callers that cannot+ sign in are served by the `spree api` CLI, which is what API keys are for.+ The MCP endpoint refuses a key outright rather than accepting a second,+ weaker way in.- **No dynamic client registration.** The 2026-07-28 revision deprecatedRFC 7591 in favour of client ID metadata documents, Doorkeeper neversupported DCR, and neither claude.ai nor ChatGPT requires it. Pre-registered@@ -138,9 +141,9 @@ Steps 1–3 are the substance; a merchant sees nothing until 4 and 5.## Constraints on Current Work-- **Do not retire the API key path.** Anything built on the assumption that- MCP authentication means OAuth will break the developer clients that work- today.+- **Do not add a key path back to MCP.** A second credential would be a way+ to bypass consent: the grant's scopes and the approving person are the+ whole of what makes an agent's authority accountable.- **Do not widen the 401.** It means "no usable credential", nothing else.Permission refusals stay as `{ error: '…' }` inside a 200, where MCP putstool-level failures; promoting one to an HTTP status would send consumerdiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 147401a1da..d05f346e20 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -6323,3 +6323,27 @@ their products' stock held in marketplace locations.**Plans amended:** `5.6-admin-spa-csv-import.md` (stock is per location),`6.0-stock-reservations.md` and `6.0-typed-stock-movements.md` (the "readavailability, never the shelf" constraints name the write-back exception).++## 2026-10-05 — MCP takes a grant, the CLI takes a key++The MCP endpoint accepted a secret API key as well as an OAuth token, which+made it the one surface with two ways in. The key path is now removed: a+request without a grant is refused with the discovery challenge, whatever+credential it carried.++The reasoning is what each credential can say. A grant names the person who+approved the agent and the subset of their permissions they allowed, and both+are re-read on every call — narrowing a role or deleting the user takes effect+immediately. A key says neither: it is a standing credential with nobody+behind it, and it outlives whoever created it. For an agent acting on+someone's behalf that is the wrong shape, however convenient.++Keys keep their place on every other Admin API surface and in the `spree api`+CLI, which is what scripted callers that cannot open a browser should use.++**Consequences for other work.** A workflow run through MCP now records the+approving admin as the actor rather than an API key, so anything asserting a+key principal there is wrong. The store comes from the token's application,+so `X-Spree-Store-Id` is not consulted on this endpoint. `Spree::AgentTools::+Context` keeps its `api_key:` principal — the dashboard assistant and any+other adapter may still use it; only the MCP transport refuses one.diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex 436fc9e6dd..aa7813ddb5 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -5966,6 +5966,18 @@ export class AdminClient {/** Applications a merchant has connected, for the revoke screen. */applications: {+ /**+ * Every client registered for this store, connected or not. A merchant+ * needs the id of one they have not connected yet, which is exactly+ * what `list` leaves out.+ */+ registrations: (options?: RequestOptions): Promise<{ data: OauthApplication[] }> =>+ this.request<{ data: OauthApplication[] }>(+ 'GET',+ '/oauth/applications/registrations',+ options ?? {},+ ),+list: (params?: ListParams & Record<string, unknown>,options?: RequestOptions,diff --git a/packages/dashboard/src/components/spree/mcp-connect-sheet.tsx b/packages/dashboard/src/components/spree/mcp-connect-sheet.tsxindex 7ea1bbe0ee..8cbe3a55b2 100644--- a/packages/dashboard/src/components/spree/mcp-connect-sheet.tsx+++ b/packages/dashboard/src/components/spree/mcp-connect-sheet.tsx@@ -1,25 +1,15 @@-import type { ApiKey } from '@spree/admin-sdk'-import { Subject, usePermissions } from '@spree/dashboard-core'import {Alert,AlertDescription,- Button,- Checkbox,CopyToClipboardButton,Sheet,SheetContent,SheetDescription,SheetHeader,SheetTitle,- Tabs,- TabsContent,- TabsList,- TabsTrigger,} from '@spree/dashboard-ui'-import { useId, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useCreateApiKey } from '../../hooks/use-api-keys'-import { useOauthApplications } from '../../hooks/use-oauth'+import { useOauthRegistrations } from '../../hooks/use-oauth'type McpConnectSheetProps = {open: boolean@@ -27,167 +17,35 @@ type McpConnectSheetProps = {}/**- * Connects an agent to this store without anyone hand-building a config- * file. A key is minted on demand with read-only scopes, and each client's- * snippet is rendered ready to paste — the token appears here once, because- * that is the only moment the API returns it.+ * How a merchant points an agent at this store.+ *+ * There is nothing to mint: the client sends the person here to sign in and+ * approve what the agent may do, so the only thing to hand over is the URL.+ * An API key is not accepted by the MCP endpoint — that credential belongs+ * to the CLI, where there is no person to approve anything.*/export function McpConnectSheet({ open, onOpenChange }: McpConnectSheetProps) {const { t } = useTranslation()- const { data: applications } = useOauthApplications()- const createKey = useCreateApiKey()- const { permissions } = usePermissions()- const [minted, setMinted] = useState<ApiKey | null>(null)- const [writable, setWritable] = useState(false)- const [mintError, setMintError] = useState<string | null>(null)- const writableId = useId()+ const { data: registrations } = useOauthRegistrations()// Where this dashboard's own API calls go — either a configured origin or// the page's own, which is what a proxied or multi-hostname deployment- // actually answers on. The store record's URL describes the storefront and- // is frequently neither.+ // actually answers on.const apiOrigin = import.meta.env.VITE_SPREE_API_URL || window.location.originconst endpoint = `${apiOrigin}/api/v3/admin/mcp`- const clientIds = (applications?.data ?? []).map((application) => ({- name: application.name,- clientId: application.client_id,- }))- const token = minted?.plaintext_token ?? 'YOUR_SECRET_KEY'- const canMint = permissions.can('create', Subject.ApiKey)-- async function mint() {- setMintError(null)-- try {- // Named with a timestamp because a key's name is unique within the- // store while it is live — a second agent connected on the same day- // would otherwise collide with the first.- const key = await createKey.mutateAsync({- name: `MCP agent ${new Date().toISOString().slice(0, 16).replace('T', ' ')}`,- key_type: 'secret',- scopes: writable ? ['write_all'] : ['read_all'],- })- setMinted(key)- } catch (error) {- setMintError(error instanceof Error ? error.message : t('admin.mcp_connect.mint_failed'))- }- }-- const snippets = {- claude: `claude mcp add --transport http spree ${endpoint} \\- --header "X-Spree-API-Key: ${token}"`,- cursor: JSON.stringify(- { mcpServers: { spree: { url: endpoint, headers: { 'X-Spree-API-Key': token } } } },- null,- 2,- ),- vscode: JSON.stringify(- {- servers: {- spree: { type: 'http', url: endpoint, headers: { 'X-Spree-API-Key': token } },- },- },- null,- 2,- ),- curl: `curl ${endpoint} \\- -H "Content-Type: application/json" \\- -H "X-Spree-API-Key: ${token}" \\- -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'`,- }+ const clients = registrations?.data ?? []return (<Sheet open={open} onOpenChange={onOpenChange}>- <SheetContent className="w-full overflow-y-auto sm:max-w-2xl">+ <SheetContent className="w-full overflow-y-auto sm:max-w-xl"><SheetHeader><SheetTitle>{t('admin.mcp_connect.title')}</SheetTitle><SheetDescription>{t('admin.mcp_connect.subtitle')}</SheetDescription></SheetHeader><div className="flex flex-col gap-6 px-4 pb-8">- {minted ? (- <Alert>- <AlertDescription>{t('admin.mcp_connect.token_shown_once')}</AlertDescription>- </Alert>- ) : (- <div className="flex flex-col gap-3">- <p className="text-muted-foreground text-sm">{t('admin.mcp_connect.mint_help')}</p>- {canMint ? (- <>- <label- htmlFor={writableId}- className="flex cursor-pointer items-start gap-2 text-sm"- >- <Checkbox- id={writableId}- checked={writable}- onCheckedChange={(checked) => setWritable(checked === true)}- />- <span>- {t('admin.mcp_connect.allow_writes')}- <span className="block text-muted-foreground text-xs">- {t('admin.mcp_connect.allow_writes_help')}- </span>- </span>- </label>- {mintError ? (- <Alert variant="destructive">- <AlertDescription>{mintError}</AlertDescription>- </Alert>- ) : null}- <Button className="self-start" disabled={createKey.isPending} onClick={mint}>- {t('admin.mcp_connect.mint_cta')}- </Button>- </>- ) : (- <Alert variant="destructive">- <AlertDescription>{t('admin.mcp_connect.mint_denied')}</AlertDescription>- </Alert>- )}- </div>- )}-- <Tabs defaultValue="claude">- <TabsList>- <TabsTrigger value="claude">Claude Code</TabsTrigger>- <TabsTrigger value="cursor">Cursor</TabsTrigger>- <TabsTrigger value="vscode">VS Code</TabsTrigger>- <TabsTrigger value="curl">{t('admin.mcp_connect.tab_other')}</TabsTrigger>- </TabsList>-- {(['claude', 'cursor', 'vscode', 'curl'] as const).map((client) => (- <TabsContent key={client} value={client}>- <div className="relative">- <pre className="overflow-x-auto rounded-md bg-muted p-4 pr-12 text-xs leading-relaxed">- <code>{snippets[client]}</code>- </pre>- <CopyToClipboardButton- aria-label={t('admin.actions.copy')}- className="absolute top-2 right-2"- value={snippets[client]}- />- </div>- {client === 'cursor' ? (- <p className="mt-2 text-muted-foreground text-xs">- {t('admin.mcp_connect.cursor_path')}- </p>- ) : null}- {client === 'vscode' ? (- <p className="mt-2 text-muted-foreground text-xs">- {t('admin.mcp_connect.vscode_path')}- </p>- ) : null}- </TabsContent>- ))}- </Tabs>-- {/* A consumer connector takes a URL, not a key — it signs in. There- is no deep link that would open one of these apps on a given- server, so the useful thing is the URL itself, ready to paste- into the connector dialog. */}- <div className="flex flex-col gap-2 border-t pt-4">- <p className="font-medium text-sm">{t('admin.mcp_connect.consumer_title')}</p>- <p className="text-muted-foreground text-xs">{t('admin.mcp_connect.consumer_note')}</p>+ <div className="flex flex-col gap-2">+ <p className="font-medium text-sm">{t('admin.mcp_connect.url_label')}</p><div className="relative"><pre className="overflow-x-auto rounded-md bg-muted p-3 pr-12 text-xs"><code>{endpoint}</code>@@ -198,31 +56,46 @@ export function McpConnectSheet({ open, onOpenChange }: McpConnectSheetProps) {value={endpoint}/></div>- {/* A connector that asks for a client id needs this store's own:- the id is issued per store, so it cannot be published in- documentation. */}- {clientIds.length > 0 ? (- <div className="flex flex-col gap-1">- <p className="text-muted-foreground text-xs">- {t('admin.mcp_connect.client_id_help')}- </p>- {clientIds.map(({ name, clientId }) => (- <div key={clientId} className="relative">+ </div>++ <ol className="flex list-decimal flex-col gap-2 pl-5 text-sm">+ <li>{t('admin.mcp_connect.step_paste')}</li>+ <li>{t('admin.mcp_connect.step_sign_in')}</li>+ <li>{t('admin.mcp_connect.step_approve')}</li>+ </ol>++ {/* Some clients ask for a client ID before they will start the+ sign-in flow. It is issued per store, so it cannot be published+ anywhere — a merchant has to be able to read this store's own. */}+ {clients.length > 0 ? (+ <div className="flex flex-col gap-2">+ <p className="font-medium text-sm">{t('admin.mcp_connect.client_id_label')}</p>+ <p className="text-muted-foreground text-xs">+ {t('admin.mcp_connect.client_id_help')}+ </p>+ {clients.map((client) => (+ <div key={client.id} className="flex flex-col gap-1">+ <p className="text-xs">{client.name}</p>+ <div className="relative"><pre className="overflow-x-auto rounded-md bg-muted p-3 pr-12 text-xs">- <code>- {name}: {clientId}- </code>+ <code>{client.client_id}</code></pre><CopyToClipboardButtonaria-label={t('admin.actions.copy')}className="absolute top-1.5 right-2"- value={clientId}+ value={client.client_id}/></div>- ))}- </div>- ) : null}- </div>+ </div>+ ))}+ </div>+ ) : null}++ <Alert>+ <AlertDescription>{t('admin.mcp_connect.scope_note')}</AlertDescription>+ </Alert>++ <p className="text-muted-foreground text-xs">{t('admin.mcp_connect.cli_note')}</p></div></SheetContent></Sheet>diff --git a/packages/dashboard/src/hooks/use-oauth.ts b/packages/dashboard/src/hooks/use-oauth.tsindex a019f54fb1..cf0680da54 100644--- a/packages/dashboard/src/hooks/use-oauth.ts+++ b/packages/dashboard/src/hooks/use-oauth.ts@@ -39,6 +39,18 @@ export function useDenyOauthAuthorization() {})}+/**+ * Every registered client, for the setup panel — unlike the connected list,+ * which answers what to revoke.+ */+export function useOauthRegistrations() {+ return useQuery({+ queryKey: useResourceKey('oauth-registrations'),+ queryFn: () => adminClient.oauth.applications.registrations(),+ staleTime: 30 * 60 * 1000,+ })+}+export function useOauthApplications() {return useQuery({queryKey: useResourceKey('oauth-applications'),diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 3dd35f7b54..cb07b7c7f7 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -4198,7 +4198,8 @@"approve": "السماح بالوصول","deny": "إلغاء","invalid_request": "طلب الترخيص هذا غير صالح. ابدأ من جديد من التطبيق الذي أرسلك إلى هنا.",- "decision_failed": "تعذّر تسجيل القرار. حاول مرة أخرى."+ "decision_failed": "تعذّر تسجيل القرار. حاول مرة أخرى.",+ "withheld": "غير متاح، لأن دورك لا يشمل: {{permissions}}"}}},@@ -6374,20 +6375,13 @@"mcp_connect": {"open_cta": "ربط وكيل","title": "ربط وكيل",- "subtitle": "امنح مساعد الذكاء الاصطناعي حق الوصول إلى هذا المتجر. انسخ الإعداد الخاص بعميلك والصقه.",- "mint_help": "يتم إنشاء مفتاح للقراءة فقط للوكيل. وللسماح له بإجراء تغييرات، أنشئ بدلاً من ذلك مفتاحًا بالصلاحيات التي تريدها من صفحة مفاتيح API.",- "mint_cta": "إنشاء مفتاح",- "mint_denied": "ليست لديك صلاحية إنشاء مفاتيح API.",- "token_shown_once": "انسخ الإعداد الآن — يُعرض المفتاح هذه المرة فقط.",- "tab_other": "شيء آخر",- "cursor_path": "احفظه باسم .cursor/mcp.json في مشروعك، أو ~/.cursor/mcp.json لك وحدك.",- "vscode_path": "احفظه باسم .vscode/mcp.json في مشروعك.",- "consumer_note": "تتصل هذه عبر تسجيل الدخول بدلاً من استخدام مفتاح. أضف موصّلاً في العميل، والصق هذا العنوان، ثم وافق على الطلب هنا.",- "allow_writes": "السماح لهذا الوكيل بإجراء تغييرات",- "allow_writes_help": "اتركه مُعطّلاً للوكيل الذي يقرأ فقط. فالمفتاح القادر على التغيير يستطيع أيضًا إلغاء الطلبات وإصدار المبالغ المستردة.",- "mint_failed": "تعذّر إنشاء المفتاح.",- "consumer_title": "Claude Desktop وclaude.ai وChatGPT",- "client_id_help": "إذا طلب الموصّل معرّف عميل، فاستخدم المعرّف الخاص بعميلك — فهي تُصدر لكل متجر على حدة."+ "subtitle": "وجّه مساعد الذكاء الاصطناعي إلى هذا المتجر. سيعيدك إلى هنا للموافقة على ما يمكنه فعله.",+ "url_label": "عنوان MCP الخاص بمتجرك",+ "step_paste": "الصق هذا العنوان في الموصّل أو إعدادات MCP في عميلك.",+ "step_sign_in": "سيعيدك إلى هنا لتسجيل الدخول.",+ "step_approve": "وافق على ما يمكن للوكيل فعله. ويمكنك سحب ذلك في أي وقت من هذه الصفحة.",+ "scope_note": "لا يحصل الوكيل أبدًا على أكثر مما تملكه أنت، وعلى ما توافق عليه فقط. والموافقة على المنتجات لا تشمل الطلبات.",+ "cli_note": "للبرامج النصية أو CI أو أي شيء لا يمكنه تسجيل الدخول، استخدم Spree CLI مع مفتاح API — فمفاتيح API غير مقبولة هنا."}}}diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 6f639af84a..b318e70637 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -4170,7 +4170,8 @@"approve": "Zugriff erlauben","deny": "Abbrechen","invalid_request": "Diese Autorisierungsanfrage ist ungültig. Beginnen Sie erneut in der Anwendung, die Sie hierher geschickt hat.",- "decision_failed": "Die Entscheidung konnte nicht gespeichert werden. Versuchen Sie es erneut."+ "decision_failed": "Die Entscheidung konnte nicht gespeichert werden. Versuchen Sie es erneut.",+ "withheld": "Nicht angeboten, da Ihre eigene Rolle Folgendes nicht umfasst: {{permissions}}"}}},@@ -6334,20 +6335,13 @@"mcp_connect": {"open_cta": "Agent verbinden","title": "Agent verbinden",- "subtitle": "Geben Sie einem KI-Assistenten Zugriff auf diesen Shop. Kopieren Sie die Einrichtung für Ihren Client und fügen Sie sie ein.",- "mint_help": "Für den Agenten wird ein Schlüssel nur zum Lesen erstellt. Damit er Änderungen vornehmen darf, erstellen Sie stattdessen auf der Seite API-Schlüssel einen Schlüssel mit den gewünschten Berechtigungen.",- "mint_cta": "Schlüssel erstellen",- "mint_denied": "Sie haben keine Berechtigung, API-Schlüssel zu erstellen.",- "token_shown_once": "Kopieren Sie die Einrichtung jetzt — der Schlüssel wird nur dieses eine Mal angezeigt.",- "tab_other": "Etwas anderes",- "cursor_path": "Als .cursor/mcp.json im Projekt speichern oder als ~/.cursor/mcp.json für Sie persönlich.",- "vscode_path": "Als .vscode/mcp.json im Projekt speichern.",- "consumer_note": "Diese verbinden sich per Anmeldung statt mit einem Schlüssel. Fügen Sie im Client einen Connector hinzu, fügen Sie diese URL ein und bestätigen Sie die Anfrage hier.",- "allow_writes": "Diesem Agenten Änderungen erlauben",- "allow_writes_help": "Für einen Agenten, der nur liest, ausgeschaltet lassen. Ein Schlüssel mit Schreibrechten kann auch Bestellungen stornieren und Rückerstattungen auslösen.",- "mint_failed": "Der Schlüssel konnte nicht erstellt werden.",- "consumer_title": "Claude Desktop, claude.ai und ChatGPT",- "client_id_help": "Falls der Connector eine Client-ID verlangt, verwenden Sie die für Ihren Client — diese werden pro Shop vergeben."+ "subtitle": "Richten Sie einen KI-Assistenten auf diesen Shop. Er schickt Sie hierher zurück, um die Freigabe zu erteilen.",+ "url_label": "Die MCP-Adresse Ihres Shops",+ "step_paste": "Fügen Sie diese Adresse in den Connector oder die MCP-Einstellungen Ihres Clients ein.",+ "step_sign_in": "Sie werden zur Anmeldung hierher geschickt.",+ "step_approve": "Geben Sie frei, was der Agent tun darf. Sie können dies jederzeit auf dieser Seite zurücknehmen.",+ "scope_note": "Ein Agent erhält nie mehr, als Sie selbst haben, und nur das, was Sie freigeben. Eine Freigabe für Produkte schließt Bestellungen nicht ein.",+ "cli_note": "Für Skripte, CI oder alles, was sich nicht anmelden kann, verwenden Sie die Spree CLI mit einem API-Schlüssel — hier werden API-Schlüssel nicht akzeptiert."}}}diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 5cdfe555f6..af3693ec82 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -4170,7 +4170,8 @@"approve": "Allow access","deny": "Cancel","invalid_request": "This authorization request is not valid. Start again from the application that sent you here.",- "decision_failed": "The decision could not be recorded. Try again."+ "decision_failed": "The decision could not be recorded. Try again.",+ "withheld": "Not offered, because your own role does not include: {{permissions}}"}}},@@ -6334,20 +6335,13 @@"mcp_connect": {"open_cta": "Connect an agent","title": "Connect an agent",- "subtitle": "Give an AI assistant access to this store. Copy the setup for your client and paste it in.",- "mint_help": "A read-only key is created for the agent. To let it make changes, create a key with the scopes you want on the API keys page instead.",- "mint_cta": "Create a key",- "mint_denied": "You do not have permission to create API keys.",- "token_shown_once": "Copy the setup below now — the key is shown only this once.",- "tab_other": "Anything else",- "cursor_path": "Save as .cursor/mcp.json in your project, or ~/.cursor/mcp.json for yourself.",- "vscode_path": "Save as .vscode/mcp.json in your project.",- "consumer_note": "These connect by signing in rather than with a key. Add a connector in the client, paste this URL, and approve the request here.",- "allow_writes": "Let this agent make changes",- "allow_writes_help": "Leave off for an agent that only reads. A key that can change things can also cancel orders and issue refunds.",- "mint_failed": "The key could not be created.",- "consumer_title": "Claude Desktop, claude.ai and ChatGPT",- "client_id_help": "If the connector asks for a client ID, use the one for your client — these are issued per store."+ "subtitle": "Point an AI assistant at this store. It will send you back here to approve what it may do.",+ "url_label": "Your store’s MCP address",+ "step_paste": "Paste this address into your client’s connector or MCP settings.",+ "step_sign_in": "It sends you here to sign in.",+ "step_approve": "Approve what the agent may do. You can take it back at any time on this page.",+ "scope_note": "An agent never gets more than you have, and only what you approve. Approving product access does not include orders.",+ "cli_note": "For scripts, CI or anything that cannot sign in, use the Spree CLI with an API key instead — API keys are not accepted here."}}}diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.jsonindex 0e259640d5..d9c27b9f02 100644--- a/packages/dashboard/src/locales/es.json+++ b/packages/dashboard/src/locales/es.json@@ -1062,7 +1062,8 @@"approve": "Permitir acceso","deny": "Cancelar","invalid_request": "Esta solicitud de autorización no es válida. Vuelva a empezar desde la aplicación que le envió aquí.",- "decision_failed": "No se pudo registrar la decisión. Inténtelo de nuevo."+ "decision_failed": "No se pudo registrar la decisión. Inténtelo de nuevo.",+ "withheld": "No se ofrece porque su propio rol no incluye: {{permissions}}"}}},@@ -6334,20 +6335,13 @@"mcp_connect": {"open_cta": "Conectar un agente","title": "Conectar un agente",- "subtitle": "Dé a un asistente de IA acceso a esta tienda. Copie la configuración de su cliente y péguela.",- "mint_help": "Se crea una clave de solo lectura para el agente. Para que pueda hacer cambios, cree una clave con los permisos que desee en la página de Claves API.",- "mint_cta": "Crear una clave",- "mint_denied": "No tiene permiso para crear claves API.",- "token_shown_once": "Copie la configuración ahora: la clave se muestra solo esta vez.",- "tab_other": "Otra cosa",- "cursor_path": "Guárdelo como .cursor/mcp.json en su proyecto, o ~/.cursor/mcp.json para usted.",- "vscode_path": "Guárdelo como .vscode/mcp.json en su proyecto.",- "consumer_note": "Estos se conectan iniciando sesión en lugar de con una clave. Añada un conector en el cliente, pegue esta URL y apruebe la solicitud aquí.",- "allow_writes": "Permitir que este agente haga cambios",- "allow_writes_help": "Déjelo desactivado para un agente que solo lee. Una clave que puede cambiar cosas también puede cancelar pedidos y emitir reembolsos.",- "mint_failed": "No se pudo crear la clave.",- "consumer_title": "Claude Desktop, claude.ai y ChatGPT",- "client_id_help": "Si el conector pide un ID de cliente, use el de su cliente: se emiten por tienda."+ "subtitle": "Apunte un asistente de IA a esta tienda. Le enviará de vuelta aquí para aprobar lo que puede hacer.",+ "url_label": "La dirección MCP de su tienda",+ "step_paste": "Pegue esta dirección en el conector o la configuración MCP de su cliente.",+ "step_sign_in": "Le enviará aquí para iniciar sesión.",+ "step_approve": "Apruebe lo que puede hacer el agente. Puede retirarlo en cualquier momento en esta página.",+ "scope_note": "Un agente nunca obtiene más de lo que usted tiene, y solo lo que apruebe. Aprobar el acceso a productos no incluye los pedidos.",+ "cli_note": "Para scripts, CI o cualquier cosa que no pueda iniciar sesión, use la CLI de Spree con una clave API: aquí no se aceptan claves API."}}}diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 9decc2fb82..8636b1c3aa 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -4170,7 +4170,8 @@"approve": "Autoriser l’accès","deny": "Annuler","invalid_request": "Cette demande d’autorisation n’est pas valide. Recommencez depuis l’application qui vous a envoyé ici.",- "decision_failed": "La décision n’a pas pu être enregistrée. Réessayez."+ "decision_failed": "La décision n’a pas pu être enregistrée. Réessayez.",+ "withheld": "Non proposé, car votre propre rôle ne comprend pas : {{permissions}}"}}},@@ -6334,20 +6335,13 @@"mcp_connect": {"open_cta": "Connecter un agent","title": "Connecter un agent",- "subtitle": "Donnez à un assistant IA accès à cette boutique. Copiez la configuration de votre client et collez-la.",- "mint_help": "Une clé en lecture seule est créée pour l’agent. Pour qu’il puisse apporter des modifications, créez plutôt une clé avec les autorisations voulues sur la page Clés API.",- "mint_cta": "Créer une clé",- "mint_denied": "Vous n’avez pas l’autorisation de créer des clés API.",- "token_shown_once": "Copiez la configuration maintenant — la clé n’est affichée qu’une seule fois.",- "tab_other": "Autre chose",- "cursor_path": "Enregistrez sous .cursor/mcp.json dans votre projet, ou ~/.cursor/mcp.json pour vous.",- "vscode_path": "Enregistrez sous .vscode/mcp.json dans votre projet.",- "consumer_note": "Ceux-ci se connectent en se connectant à votre compte plutôt qu’avec une clé. Ajoutez un connecteur dans le client, collez cette URL et approuvez la demande ici.",- "allow_writes": "Autoriser cet agent à apporter des modifications",- "allow_writes_help": "Laissez désactivé pour un agent qui ne fait que lire. Une clé qui peut modifier peut aussi annuler des commandes et émettre des remboursements.",- "mint_failed": "La clé n’a pas pu être créée.",- "consumer_title": "Claude Desktop, claude.ai et ChatGPT",- "client_id_help": "Si le connecteur demande un identifiant client, utilisez celui de votre client — ils sont émis par boutique."+ "subtitle": "Dirigez un assistant IA vers cette boutique. Il vous renverra ici pour approuver ce qu’il peut faire.",+ "url_label": "L’adresse MCP de votre boutique",+ "step_paste": "Collez cette adresse dans le connecteur ou les réglages MCP de votre client.",+ "step_sign_in": "Il vous renvoie ici pour vous connecter.",+ "step_approve": "Approuvez ce que l’agent peut faire. Vous pouvez le retirer à tout moment sur cette page.",+ "scope_note": "Un agent n’obtient jamais plus que vous, et uniquement ce que vous approuvez. Approuver l’accès aux produits n’inclut pas les commandes.",+ "cli_note": "Pour les scripts, la CI ou tout ce qui ne peut pas se connecter, utilisez la CLI Spree avec une clé API — les clés API ne sont pas acceptées ici."}}}diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 44411a960d..1db0db7ae9 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -4224,7 +4224,8 @@"approve": "Zezwól na dostęp","deny": "Anuluj","invalid_request": "To żądanie autoryzacji jest nieprawidłowe. Zacznij ponownie z aplikacji, która Cię tu skierowała.",- "decision_failed": "Nie udało się zapisać decyzji. Spróbuj ponownie."+ "decision_failed": "Nie udało się zapisać decyzji. Spróbuj ponownie.",+ "withheld": "Niedostępne, ponieważ Twoja rola nie obejmuje: {{permissions}}"}}},@@ -6402,20 +6403,13 @@"mcp_connect": {"open_cta": "Połącz agenta","title": "Połącz agenta",- "subtitle": "Daj asystentowi AI dostęp do tego sklepu. Skopiuj konfigurację dla swojego klienta i wklej ją.",- "mint_help": "Dla agenta tworzony jest klucz tylko do odczytu. Aby mógł wprowadzać zmiany, utwórz klucz z wybranymi uprawnieniami na stronie Klucze API.",- "mint_cta": "Utwórz klucz",- "mint_denied": "Nie masz uprawnień do tworzenia kluczy API.",- "token_shown_once": "Skopiuj konfigurację teraz — klucz jest pokazywany tylko ten jeden raz.",- "tab_other": "Coś innego",- "cursor_path": "Zapisz jako .cursor/mcp.json w projekcie lub ~/.cursor/mcp.json dla siebie.",- "vscode_path": "Zapisz jako .vscode/mcp.json w projekcie.",- "consumer_note": "Łączą się przez zalogowanie, a nie kluczem. Dodaj konektor w kliencie, wklej ten adres i zatwierdź prośbę tutaj.",- "allow_writes": "Pozwól temu agentowi wprowadzać zmiany",- "allow_writes_help": "Zostaw wyłączone dla agenta, który tylko czyta. Klucz, który może zmieniać dane, może też anulować zamówienia i wystawiać zwroty.",- "mint_failed": "Nie udało się utworzyć klucza.",- "consumer_title": "Claude Desktop, claude.ai i ChatGPT",- "client_id_help": "Jeśli konektor poprosi o identyfikator klienta, użyj tego dla swojego klienta — są wydawane osobno dla każdego sklepu."+ "subtitle": "Wskaż asystentowi AI ten sklep. Odeśle Cię tutaj, abyś zatwierdził, co może robić.",+ "url_label": "Adres MCP Twojego sklepu",+ "step_paste": "Wklej ten adres w konektorze lub ustawieniach MCP swojego klienta.",+ "step_sign_in": "Odeśle Cię tutaj, abyś się zalogował.",+ "step_approve": "Zatwierdź, co agent może robić. Możesz to cofnąć w dowolnej chwili na tej stronie.",+ "scope_note": "Agent nigdy nie dostaje więcej niż Ty i tylko to, co zatwierdzisz. Zgoda na produkty nie obejmuje zamówień.",+ "cli_note": "Do skryptów, CI i wszystkiego, co nie może się zalogować, użyj Spree CLI z kluczem API — tutaj klucze API nie są akceptowane."}}}diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 70b8f12a20..5c5af4f5c4 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -4160,7 +4160,8 @@"approve": "允许访问","deny": "取消","invalid_request": "此授权请求无效。请从引导您来此的应用重新开始。",- "decision_failed": "无法记录此决定,请重试。"+ "decision_failed": "无法记录此决定,请重试。",+ "withheld": "未提供,因为您自己的角色不包含:{{permissions}}"}}},@@ -6321,20 +6322,13 @@"mcp_connect": {"open_cta": "连接代理","title": "连接代理",- "subtitle": "让 AI 助手访问此店铺。复制适用于您客户端的设置并粘贴。",- "mint_help": "系统会为代理创建一个只读密钥。若要允许其进行更改,请改在“API 密钥”页面创建具有所需权限的密钥。",- "mint_cta": "创建密钥",- "mint_denied": "您没有创建 API 密钥的权限。",- "token_shown_once": "请立即复制下面的设置——密钥仅显示这一次。",- "tab_other": "其他",- "cursor_path": "保存为项目中的 .cursor/mcp.json,或保存为您个人的 ~/.cursor/mcp.json。",- "vscode_path": "保存为项目中的 .vscode/mcp.json。",- "consumer_note": "它们通过登录而非密钥连接。在客户端中添加连接器,粘贴此网址,然后在此处批准请求。",- "allow_writes": "允许此代理进行更改",- "allow_writes_help": "仅读取的代理请保持关闭。可更改数据的密钥同样可以取消订单和发起退款。",- "mint_failed": "无法创建密钥。",- "consumer_title": "Claude Desktop、claude.ai 和 ChatGPT",- "client_id_help": "如果连接器需要客户端 ID,请使用对应客户端的 ID——它们按店铺分别签发。"+ "subtitle": "将 AI 助手指向此店铺。它会把您送回这里,确认它可以做什么。",+ "url_label": "您店铺的 MCP 地址",+ "step_paste": "将此地址粘贴到客户端的连接器或 MCP 设置中。",+ "step_sign_in": "它会把您送到这里登录。",+ "step_approve": "确认代理可以做什么。您随时可以在此页面收回。",+ "scope_note": "代理获得的权限绝不会超过您自己,且仅限您确认的范围。确认商品访问权限并不包含订单。",+ "cli_note": "对于脚本、CI 或任何无法登录的场景,请改用 Spree CLI 配合 API 密钥——此处不接受 API 密钥。"}}}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/oauth/authorize.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/oauth/authorize.tsxindex ca345f01e8..8d40b0900f 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/oauth/authorize.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/oauth/authorize.tsx@@ -1,8 +1,16 @@import { PageHeader } from '@spree/dashboard-core'-import { Alert, AlertDescription, Button, Card, CardContent, Skeleton } from '@spree/dashboard-ui'-import { CheckIcon, ShieldIcon } from '@spree/dashboard-ui/icons'+import {+ Alert,+ AlertDescription,+ Button,+ Card,+ CardContent,+ Checkbox,+ Skeleton,+} from '@spree/dashboard-ui'+import { ShieldIcon } from '@spree/dashboard-ui/icons'import { createFileRoute } from '@tanstack/react-router'-import { useState } from 'react'+import { useId, useState } from 'react'import { useTranslation } from 'react-i18next'import { z } from 'zod'import { permissionKeyLabel } from '../../../../components/spree/permission-picker'@@ -38,6 +46,22 @@ function OauthAuthorizePage() {const { data, isLoading, error } = useOauthAuthorization(search)const errorDetail = error instanceof Error ? error.message : undefinedconst [decisionError, setDecisionError] = useState<string | null>(null)+ // Null until the request loads, then every permission this person could+ // hand over — pre-ticked, because the client asked for them and declining+ // one should be a deliberate act rather than the default.+ const [granted, setGranted] = useState<string[] | null>(null)+ const scopeFieldId = useId()++ const grantable = data?.grantable_scopes ?? []+ const withheld = (data?.scopes ?? []).filter((key) => !grantable.includes(key))+ const selected = granted ?? grantable++ const toggle = (key: string) =>+ setSelected(selected.includes(key) ? selected.filter((k) => k !== key) : [...selected, key])++ function setSelected(next: string[]) {+ setGranted(next)+ }const { data: catalog } = usePermissionCatalog()const approve = useApproveOauthAuthorization()const deny = useDenyOauthAuthorization()@@ -51,7 +75,10 @@ function OauthAuthorizePage() {setDecisionError(null)try {- const result = await mutation.mutateAsync(search)+ // The scope the merchant settled on, not the one the client asked+ // for — Doorkeeper records whatever reaches it, so a trimmed list+ // becomes the token's authority.+ const result = await mutation.mutateAsync({ ...search, scope: selected.join(' ') })window.location.href = result.redirect_uri} catch (failure) {setDecisionError(@@ -108,17 +135,40 @@ function OauthAuthorizePage() {<h2 className="font-medium text-sm">{t('admin.pages.oauth.authorize.permissions_heading')}</h2>+ {/* Each one is a choice, not a notice: a merchant can hand+ over less than the client asked for, and the grant is+ whatever they leave ticked. Labelled client-side so the+ one screen that says what is being granted follows the+ merchant's own language, not the server's. */}<ul className="flex flex-col gap-2">- {data.scopes.map((key) => (- <li key={key} className="flex items-start gap-2 text-sm">- <CheckIcon className="mt-0.5 size-4 shrink-0 text-muted-foreground" />- {/* Labelled client-side so the one screen that tells a- merchant what they are granting follows their own- language, not the server's. */}- <span>{permissionKeyLabel(t, catalog?.data, key)}</span>+ {grantable.map((key) => (+ <li key={key}>+ <label+ htmlFor={`${scopeFieldId}-${key}`}+ className="flex cursor-pointer items-start gap-2 text-sm"+ >+ <Checkbox+ id={`${scopeFieldId}-${key}`}+ checked={selected.includes(key)}+ onCheckedChange={() => toggle(key)}+ />+ <span>{permissionKeyLabel(t, catalog?.data, key)}</span>+ </label></li>))}</ul>+ {/* Asked for but not this person's to give — saying so is+ better than silently dropping it, because the agent will+ behave as though it has them. */}+ {withheld.length > 0 ? (+ <p className="text-muted-foreground text-xs">+ {t('admin.pages.oauth.authorize.withheld', {+ permissions: withheld+ .map((key) => permissionKeyLabel(t, catalog?.data, key))+ .join(', '),+ })}+ </p>+ ) : null}</div><Alert>diff --git a/spree/api/app/controllers/spree/api/v3/admin/oauth/applications_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/oauth/applications_controller.rbindex 9e1f574945..e6d63f5c2a 100644--- a/spree/api/app/controllers/spree/api/v3/admin/oauth/applications_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/oauth/applications_controller.rb@@ -36,6 +36,19 @@ module Spree}end+ # Every client registered for this store, connected or not — a+ # merchant needs the id of one they have not connected yet, which+ # is precisely what `index` leaves out.+ def registrations+ applications = current_store.oauth_applications.+ includes(live_access_tokens: :resource_owner).+ order(:name)++ render json: {+ data: Spree.api.admin_oauth_application_serializer.new(applications).serializable_hash+ }+ end+def destroyapplication = current_store.oauth_applications.find_by_prefix_id!(params[:id])diff --git a/spree/api/app/controllers/spree/api/v3/admin/oauth/authorizations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/oauth/authorizations_controller.rbindex 4a87ecfcb8..a430e7d64c 100644--- a/spree/api/app/controllers/spree/api/v3/admin/oauth/authorizations_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/oauth/authorizations_controller.rb@@ -30,11 +30,20 @@ module Spreerender json: {client_name: client_name,scopes: requested_permissions,+ # What the merchant may hand over, which is the intersection+ # of what the client asked for and what they themselves hold.+ # A grant can only ever narrow their own authority, so+ # offering more than they have would be offering a refusal.+ grantable_scopes: grantable_scopes,resource: requested_resource,redirect_uri: @pre_auth.redirect_uri}end+ # The merchant may approve less than the client asked for. Doing+ # so narrows the grant, not the request: Doorkeeper records+ # whatever scope reaches it here, so a trimmed list becomes the+ # token's authority.def createrender json: { redirect_uri: code_request.authorize.redirect_uri }end@@ -88,6 +97,17 @@ module Spree)end+ # What this person can actually grant: the requested scopes minus+ # anything their own role does not carry.+ #+ # @return [Array<String>]+ def grantable_scopes+ held = current_ability.try(:permission_keys)&.map(&:to_s) || []+ requested = Spree.permissions.expand_keys(@pre_auth.scopes.to_a)++ (requested & held).sort+ end+# Symbol keys: PreAuthorization reads them that way, and a hash of# strings silently produces an unauthorizable request.def pre_authorization_paramsdiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex 642a5b947e..ce3af7bb45 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -246,7 +246,9 @@ Spree::Core::Engine.add_routes dopost 'authorize', to: 'authorizations#create'delete 'authorize', to: 'authorizations#destroy'- resources :applications, only: %i[index destroy]+ resources :applications, only: %i[index destroy] do+ get :registrations, on: :collection+ endend# Semantic reporting (docs/plans/6.0-analytics-semantic-layer.md)diff --git a/spree/api/spec/tools/spree/agent_tools/reporting_tools_spec.rb b/spree/api/spec/tools/spree/agent_tools/reporting_tools_spec.rbindex 0a1ea0f4b7..d74c69de64 100644--- a/spree/api/spec/tools/spree/agent_tools/reporting_tools_spec.rb+++ b/spree/api/spec/tools/spree/agent_tools/reporting_tools_spec.rb@@ -39,6 +39,21 @@ RSpec.describe 'agent reporting tools' doenddescribe 'query_report' do+ # A grouped row holds a raw primary key. Handing a model+ # `{"product" => 3}` answers "which products sell best" with a number it+ # cannot read, so the key is resolved the same way the Admin API+ # resolves it.+ it 'names what a dimension grouped by' do+ product = create(:product, store: store, name: 'Rotary Shaver 9000')+ order = create(:completed_order_with_totals, store: store)+ order.line_items.first.update!(variant: product.master)++ result = tool('query_report').call(metrics: ['units_sold'], dimensions: ['product'])++ expect(result[:error]).to be_nil+ expect(result[:rows].map { |row| row[:dimensions][:product] }).to include('Rotary Shaver 9000')+ end+before { create(:completed_order_with_totals, store: store) }it 'answers with totals' dodiff --git a/spree/core/app/tools/spree/agent_tools/query_report.rb b/spree/core/app/tools/spree/agent_tools/query_report.rbindex 5049145502..8108df24ff 100644--- a/spree/core/app/tools/spree/agent_tools/query_report.rb+++ b/spree/core/app/tools/spree/agent_tools/query_report.rb@@ -93,8 +93,14 @@ module Spree# Totals first: most reporting questions are answered by them alone,# and the rows are what fills a context window.+ #+ # Dimension keys are hydrated the same way the Admin API hydrates them.+ # A grouped row holds a raw primary key, and handing a model+ # `{"product": 3}` answers "which products sell best" with a number it+ # cannot read — the label is the answer.def shape(result)- rows = Array(result.rows)+ hydration = Spree::Reporting::Hydration.new(result, store: context.store)+ rows = Array(result.rows).map { |row| hydrate_row(row, hydration) }{totals: result.totals,@@ -104,6 +110,18 @@ module Spree}.compactend+ # Only the label and the id: the API's shape also carries slugs and+ # thumbnail URLs, which cost context and answer nothing a report was+ # asked.+ def hydrate_row(row, hydration)+ dimensions = (row[:dimensions] || {}).to_h do |name, raw|+ value = hydration.value(name, raw)+ [name, value.is_a?(Hash) ? value.values_at(:label, :id).compact.first : value]+ end++ row.merge(dimensions: dimensions)+ end+endendenddiff --git a/spree/mcp/app/controllers/spree/api/v3/admin/mcp_controller.rb b/spree/mcp/app/controllers/spree/api/v3/admin/mcp_controller.rbindex 449b288735..fffc7d4b28 100644--- a/spree/mcp/app/controllers/spree/api/v3/admin/mcp_controller.rb+++ b/spree/mcp/app/controllers/spree/api/v3/admin/mcp_controller.rb@@ -18,22 +18,16 @@ module Spreeclass McpController < Spree::Api::V3::Admin::BaseController# The scope gate is per tool, not per request: a call carries the# tool it wants inside the JSON-RPC body, and every tool already- # declares the permission it needs. Checking one scope for the whole- # endpoint would mean either refusing a key that may legitimately- # read, or waving through a write the key cannot make.+ # declares the permission it needs. Checking one grant's scopes for+ # the whole endpoint would mean either refusing a read it covers or+ # waving through a write it does not.skip_scope_check!# Prepended so it answers before the inherited authentication does.# The generic "Authentication required" is useless to an agent: this# text is what both the model and the person actually read when a- # client is misconfigured, so it has to say which credential to- # send and where it comes from.- #- # A JWT is still refused. It belongs to a signed-in admin in a- # browser, and a dashboard session is not what should drive an- # agent — the dashboard assistant is that path, over the same- # registry.- prepend_before_action :require_agent_credential!+ # client is misconfigured.+ prepend_before_action :require_oauth_token!def createrender json: server.handle_json(request.body.read), content_type: 'application/json'@@ -41,14 +35,17 @@ module Spreeprotected- # An OAuth token is a third credential the inherited concern knows- # nothing about, so it is resolved here. The grant already bound- # the token to a real admin user and this request's audience check- # confirmed it was issued for this store's endpoint, which is the- # same assurance `require_store_membership!` gives a JWT.+ # The only credential this endpoint takes. An agent acts for a+ # person, so it carries that person's grant: the token names who+ # approved it and what they allowed, both of which a standing key+ # cannot express. A secret key authenticates the rest of the Admin+ # API and the `spree api` CLI; it is deliberately not accepted+ # here.+ #+ # The grant already bound the token to a real admin user and the+ # audience check confirmed it was issued for this endpoint, which+ # is the assurance `require_store_membership!` gives a JWT.def authenticate_admin!- return super if current_oauth_token.blank?-owner = oauth_resource_ownerreturn false if owner.nil?@@ -57,28 +54,11 @@ module Spreetrueend- # The key in either of the two forms clients offer. Several MCP- # clients have a bearer-token field and no way to set a custom- # header, so a secret key is accepted there too. The `sk_` prefix- # keeps it unambiguous against the JWTs the Admin API also accepts- # in `Authorization`, and a JWT presented here resolves to no key- # and is refused below.- def extract_api_key- super.presence || bearer_secret_key- end-private# Split rather than matched: a regex with `\s+(.+)` backtracks on a# header of many spaces, and this one is attacker-supplied on an# unauthenticated request.- def bearer_secret_key- value = bearer_value- value if value&.start_with?(Spree::ApiKey::PREFIXES['secret'])- end-- # Split rather than matched, for the same reason: this header is- # attacker-supplied on an unauthenticated request.def bearer_valuescheme, value = request.headers['Authorization'].to_s.split(' ', 2)return unless scheme&.casecmp?('Bearer')@@ -90,20 +70,16 @@ module SpreeSpree::Mcp::Server.for(agent_context)end- # Either credential resolves into the same context, so the tool- # catalog never learns which one a request used. A key's authority- # is its scopes; a token's is the admin user's own permissions,- # resolved fresh here rather than frozen when the token was issued.+ # The caller's authority is the admin user's own permissions,+ # narrowed by what they consented to — resolved on every request+ # rather than frozen when the token was issued, so narrowing a role+ # takes effect immediately.def agent_context- if current_oauth_token.present?- Spree::AgentTools::Context.new(- store: current_store,- user: oauth_resource_owner,- granted_scopes: current_oauth_token.scopes.to_a- )- else- Spree::AgentTools::Context.new(store: current_store, api_key: current_api_key)- end+ Spree::AgentTools::Context.new(+ store: current_store,+ user: oauth_resource_owner,+ granted_scopes: current_oauth_token.scopes.to_a+ )end# RFC 6750: the challenge names where to discover the authorization@@ -147,12 +123,7 @@ module Spreereturn @bearer_access_token if defined?(@bearer_access_token)raw = bearer_value- @bearer_access_token =- if raw.blank? || raw.start_with?(Spree::ApiKey::PREFIXES['secret'])- nil- else- Spree::OauthAccessToken.by_token(raw)- end+ @bearer_access_token = raw.present? ? Spree::OauthAccessToken.by_token(raw) : nilend# The token this request may actually act on: live, and issued for@@ -198,8 +169,11 @@ module Spree# token a merchant approved. A 401 carries the OAuth challenge, so# a consumer client that arrives with nothing discovers how to sign# in rather than simply failing.- def require_agent_credential!- return if secret_api_key.present? || current_oauth_token.present?+ # A 401 carrying the discovery header, which is how a client that+ # arrived with nothing learns where to sign in rather than simply+ # failing.+ def require_oauth_token!+ return if current_oauth_token.present?response.headers['WWW-Authenticate'] = oauth_challenge@@ -208,11 +182,11 @@ module Spreeid: nil,error: {code: -32_001,- message: 'Authentication is required. Either sign in through this store (your ' \- 'client will offer that when it reads the challenge on this response), ' \- 'or send a secret API key as `X-Spree-API-Key: sk_…` or ' \- '`Authorization: Bearer sk_…` — mint one in the dashboard under ' \- 'Settings → API keys, granting only the scopes this agent needs.'+ message: 'Sign in to this store to continue. Your client will offer that when ' \+ 'it reads the challenge on this response. A Spree API key is not ' \+ 'accepted here — an agent acts for a person, so it carries that ' \+ "person's own permissions. Use the `spree api` CLI for scripted " \+ 'access that cannot sign in.'}}, status: :unauthorizedenddiff --git a/spree/mcp/lib/spree/mcp/tool_adapter.rb b/spree/mcp/lib/spree/mcp/tool_adapter.rbindex 527d029301..3153659086 100644--- a/spree/mcp/lib/spree/mcp/tool_adapter.rb+++ b/spree/mcp/lib/spree/mcp/tool_adapter.rb@@ -103,10 +103,34 @@ module Spree# record into the model's context twice — on exactly the results the# design requires to stay compact. Without a summary this says what# came back, and the structured half carries it.+ # What the model reads.+ #+ # A client may render the structured half, the text half, or both —+ # the protocol does not say — so the text has to carry the answer+ # rather than point at it. Naming the keys and trusting the client to+ # look elsewhere leaves a model with nothing to work from.+ #+ # The exception is a list of records: those already carry a summary+ # line, and repeating every row would put the payload into the+ # model's context twice on exactly the results meant to stay compact.def text_for(result)return result.to_s unless result.is_a?(Hash)- result[:summary].presence || describe(result)+ summary = result[:summary].presence+ return summary if summary+ return describe(result) if record_list?(result)++ JSON.generate(result)+ end++ # A page of records the caller can fetch individually.+ #+ # Only `records` counts. A report's rows look similar but are+ # computed figures that exist nowhere else — summarising them as+ # "returned 2 results" hands the model a row count where it asked+ # for the numbers.+ def record_list?(result)+ result.key?(:records)end# A sentence about a payload that carries no summary of its own: whatdiff --git a/spree/mcp/spec/lib/spree/mcp/server_spec.rb b/spree/mcp/spec/lib/spree/mcp/server_spec.rbindex 35ece5533c..a696fc1345 100644--- a/spree/mcp/spec/lib/spree/mcp/server_spec.rb+++ b/spree/mcp/spec/lib/spree/mcp/server_spec.rb@@ -154,6 +154,19 @@ RSpec.describe Spree::Mcp::Server doexpect(text.length).to be < structured.lengthend+ # The other half of the rule. A client may render the structured half,+ # the text half, or both — the protocol does not say — so a result whose+ # whole body is the answer has to carry it in the text. Naming the keys+ # and trusting the client to look elsewhere left a model reading+ # "Returned meta, families, metrics…" where it asked for the schema.+ it 'carries the answer as text when the payload is not a record list' do+ response = call('tools/call', name: 'describe_reporting', arguments: {})+ text = response.dig('result', 'content', 0, 'text').to_s++ expect(text).to include('metrics')+ expect(JSON.parse(text)).to include('families')+ end+it 'says what a payload holds when the tool offers no summary' docreate_list(:product, 2, store: store)diff --git a/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rb b/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rbindex 5af5af4fa1..b845911465 100644--- a/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rb+++ b/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rb@@ -6,9 +6,24 @@ require 'benchmark'# store it selects, and a JSON-RPC body that never touches a view.RSpec.describe 'Admin MCP endpoint', type: :request dolet(:store) { @default_store }- let(:api_key) { create(:api_key, :secret, store: store, scopes: scopes) }- let(:scopes) { ['write_all'] }- let(:token) { api_key.plaintext_token }+ let(:admin) { create(:admin_user) }+ let(:scopes) { 'write_all' }+ let(:application) do+ store.oauth_applications.create!(+ name: 'Probe', redirect_uri: 'https://example.test/callback', confidential: false+ )+ end+ let(:resource) { Spree::Api::Oauth.resource_identifier(:mcp) }+ let(:token) { oauth_token(scopes: scopes) }++ before { Spree::Api::Oauth.register_resource(:mcp, '/api/v3/admin/mcp') }++ def oauth_token(scopes:, audience: resource, owner: admin, application: self.application)+ Spree::OauthAccessToken.create!(+ application: application, resource_owner: owner,+ scopes: Array(scopes).join(' '), expires_in: 2.hours.to_i, resource: audience+ ).token+ enddef post_rpc(method, params = nil, headers: {}, id: 1)message = { jsonrpc: '2.0', id: id, method: method }@@ -19,21 +34,36 @@ RSpec.describe 'Admin MCP endpoint', type: :request doJSON.parse(response.body)end+ def post_with_token(raw_token, method = 'tools/list', params = nil)+ post_rpc(method, params, headers: { 'Authorization' => "Bearer #{raw_token}" })+ end++ # An agent acts for a person, so the only credential this endpoint takes is+ # that person's grant. A secret key authenticates the rest of the Admin API+ # and the CLI; here it would be a standing credential with nobody behind+ # it, naming neither who approved the agent nor what they allowed.describe 'authentication' do- it 'accepts the Admin API header' do- body = post_rpc('tools/list', headers: { 'X-Spree-API-Key' => token })+ it 'accepts an OAuth token' do+ body = post_with_token(token)expect(response).to have_http_status(:ok)expect(body['result']['tools']).to be_presentend- # Several MCP clients offer a bearer-token field and no custom header, so- # the same key is accepted there.- it 'accepts the key as a bearer token' do- body = post_rpc('tools/list', headers: { 'Authorization' => "Bearer #{token}" })+ it 'refuses a secret API key in the Admin API header' do+ api_key = create(:api_key, :secret, store: store, scopes: ['write_all'])- expect(response).to have_http_status(:ok)- expect(body['result']['tools']).to be_present+ post_rpc('tools/list', headers: { 'X-Spree-API-Key' => api_key.plaintext_token })++ expect(response).to have_http_status(:unauthorized)+ end++ it 'refuses a secret API key as a bearer token' do+ api_key = create(:api_key, :secret, store: store, scopes: ['write_all'])++ post_with_token(api_key.plaintext_token)++ expect(response).to have_http_status(:unauthorized)end# Parsing the bearer header must not backtrack: this header arrives@@ -47,35 +77,19 @@ RSpec.describe 'Admin MCP endpoint', type: :request doexpect(elapsed).to be < 1.0end- it 'accepts a bearer key with extra whitespace' do+ it 'accepts a bearer token with extra whitespace' dopost_rpc('tools/list', headers: { 'Authorization' => "Bearer #{token}" })expect(response).to have_http_status(:ok)end- it 'refuses a request with no key, naming the header to set' do+ # The message is what a person reads when their client is misconfigured,+ # so it has to say what to do rather than only that something failed.+ it 'refuses an anonymous request, pointing at signing in' dobody = post_rpc('tools/list')expect(response).to have_http_status(:unauthorized)- expect(body.dig('error', 'message')).to include('X-Spree-API-Key')- end-- it 'refuses a publishable key' do- publishable = create(:api_key, :publishable, store: store)-- post_rpc('tools/list', headers: { 'X-Spree-API-Key' => publishable.token })-- expect(response).to have_http_status(:unauthorized)- end-- it 'refuses a revoked key' do- revoked = create(:api_key, :secret, store: store)- plaintext = revoked.plaintext_token- revoked.revoke!-- post_rpc('tools/list', headers: { 'X-Spree-API-Key' => plaintext })-- expect(response).to have_http_status(:unauthorized)+ expect(body.dig('error', 'message')).to include('Sign in')end# This is a machine surface: a browser session belongs to the dashboard@@ -112,26 +126,7 @@ RSpec.describe 'Admin MCP endpoint', type: :request do# A merchant grants part of their own authority to a client. Two properties# carry the whole arrangement: the grant can only narrow what the user may# do, and a token issued for some other resource cannot be replayed here.- describe 'OAuth authentication' do- let(:admin) { create(:admin_user) }- let(:resource) { Spree::Api::Oauth.resource_identifier(:mcp) }- let(:application) do- store.oauth_applications.create!(- name: 'Probe', redirect_uri: 'https://example.test/callback', confidential: false- )- end-- def oauth_token(scopes:, audience: resource, owner: admin)- Spree::OauthAccessToken.create!(- application: application, resource_owner: owner,- scopes: Array(scopes).join(' '), expires_in: 2.hours.to_i, resource: audience- ).token- end-- def post_with_token(raw_token, method = 'tools/list')- post_rpc(method, headers: { 'Authorization' => "Bearer #{raw_token}" })- end-+ describe 'the grant' doit 'authenticates a token and acts as its owner' dobody = post_with_token(oauth_token(scopes: 'read_products'))@@ -141,9 +136,9 @@ RSpec.describe 'Admin MCP endpoint', type: :request doit 'narrows the catalog to what the merchant consented to' dogranted = post_with_token(oauth_token(scopes: 'read_products'))['result']['tools']- key_offers = post_rpc('tools/list', headers: { 'X-Spree-API-Key' => token })['result']['tools']+ everything = post_with_token(oauth_token(scopes: 'write_all'))['result']['tools']- expect(granted.size).to be < key_offers.size+ expect(granted.size).to be < everything.sizeexpect(granted.map { |tool| tool['name'] }).not_to include('orders_cancel')end@@ -204,22 +199,27 @@ RSpec.describe 'Admin MCP endpoint', type: :request doit 'serves the key\'s own store when the header agrees' dobody = post_rpc('tools/call',{ name: 'search_resources', arguments: { 'resource' => 'products' } },- headers: { 'X-Spree-API-Key' => token, 'X-Spree-Store-Id' => store.prefixed_id })+ headers: { 'Authorization' => "Bearer #{token}", 'X-Spree-Store-Id' => store.prefixed_id })expect(response).to have_http_status(:ok)expect(body.dig('result', 'isError')).to be(false)end- # The key selects the store; a header naming a different one is refused- # outright rather than quietly served the key's own store.- it 'refuses a header naming another store' do+ # The grant selects the store, through the application it was issued+ # for. A header naming another store cannot widen that: the audience the+ # token carries is the whole answer, so the header is simply not+ # consulted.+ it 'ignores a header naming another store' doother_store = create(:store, code: "other-#{SecureRandom.hex(4)}")+ other_product = create(:product, store: other_store)- post_rpc('tools/call',- { name: 'search_resources', arguments: { 'resource' => 'products' } },- headers: { 'X-Spree-API-Key' => token, 'X-Spree-Store-Id' => other_store.prefixed_id })+ body = post_rpc('tools/call',+ { name: 'get_resource',+ arguments: { 'resource' => 'products', 'id' => other_product.prefixed_id } },+ headers: { 'Authorization' => "Bearer #{token}",+ 'X-Spree-Store-Id' => other_store.prefixed_id })- expect(response).to have_http_status(:forbidden)+ expect(body.dig('result', 'isError')).to be(true)endit 'does not find another store\'s record' do@@ -227,7 +227,7 @@ RSpec.describe 'Admin MCP endpoint', type: :request dobody = post_rpc('tools/call',{ name: 'get_resource', arguments: { 'resource' => 'products', 'id' => other_product.prefixed_id } },- headers: { 'X-Spree-API-Key' => token })+ headers: { 'Authorization' => "Bearer #{token}" })expect(body.dig('result', 'isError')).to be(true)end@@ -242,29 +242,32 @@ RSpec.describe 'Admin MCP endpoint', type: :request dobody = post_rpc('tools/call',{ name: 'fulfillments_mark_delivered', arguments: { 'fulfillment' => fulfillment.prefixed_id } },- headers: { 'X-Spree-API-Key' => token })+ headers: { 'Authorization' => "Bearer #{token}" })expect(body.dig('result', 'isError')).to be(false)expect(fulfillment.reload.status).to eq('delivered')end- it 'records the API key as the actor when it cancels an order' do+ # The grant names a person, so that is who the timeline records — an+ # audit later shows which admin's agent did it, not an anonymous+ # credential.+ it 'records the approving admin as the actor when it cancels an order' doreason = create(:order_cancellation_reason, store: store)body = post_rpc('tools/call',{ name: 'orders_cancel',arguments: { 'order' => order.prefixed_id, 'reason' => reason.prefixed_id } },- headers: { 'X-Spree-API-Key' => token })+ headers: { 'Authorization' => "Bearer #{token}" })expect(body.dig('result', 'isError')).to be(false)expect(order.reload.status).to eq('canceled')- expect(order.canceler).to eq(api_key)+ expect(order.canceler).to eq(admin)endit 'carries the workflow\'s own refusal back as a tool error' dobody = post_rpc('tools/call',{ name: 'orders_cancel', arguments: { 'order' => 'order_nope' } },- headers: { 'X-Spree-API-Key' => token })+ headers: { 'Authorization' => "Bearer #{token}" })expect(body.dig('result', 'isError')).to be(true)expect(body.dig('result', 'content').first['text']).to include('order')@@ -275,7 +278,7 @@ RSpec.describe 'Admin MCP endpoint', type: :request dolet(:scopes) { ['read_orders'] }it 'offers only what the key\'s scopes permit' do- body = post_rpc('tools/list', headers: { 'X-Spree-API-Key' => token })+ body = post_rpc('tools/list', headers: { 'Authorization' => "Bearer #{token}" })names = body.dig('result', 'tools').map { |tool| tool['name'] }expect(names).to include('search_resources')