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
Changed the MCP docs after review
Damian Legawiec2eae58aec047
diff --git a/docs/developer/mcp/overview.mdx b/docs/developer/mcp/overview.mdxindex 0fcf86b095..0442cd681d 100644--- a/docs/developer/mcp/overview.mdx+++ b/docs/developer/mcp/overview.mdx@@ -56,4 +56,5 @@ Every tool reaches data by making a real API request inside the process — the## What is not here yet- **A storefront endpoint.** Tools for a customer-facing agent — browsing, carts, order status — need a customer principal and their own catalog.+- **Order editing.** Adding line items, discounts and fees to an existing order runs through paths that are not yet workflows, so no tool offers it. Cancelling, refunding and fulfilling all work today.- **Product status moves.** Activating, drafting and archiving a product run inside the Spree process rather than through an endpoint, because the Admin API has none for them yet.diff --git a/docs/developer/mcp/permissions.mdx b/docs/developer/mcp/permissions.mdxindex 2a1ebd1cc1..404f3d23df 100644--- a/docs/developer/mcp/permissions.mdx+++ b/docs/developer/mcp/permissions.mdx@@ -16,7 +16,7 @@ Three rules bound it:**It is a standing ceiling, not a one-off.** The grant persists until revoked, which is why it is recorded as the intersection rather than as what was asked for. Recorded too wide, it would widen on its own the day that person is promoted.-**It is per person.** Each staff member connects for themselves, so an agent's actions are recorded against whoever approved it, and **Settings → Connected apps** shows each person their own connections.+**It is per person.** Each staff member connects for themselves, and an agent's actions are recorded against whoever approved it. **Settings → AI Agents** lists each agent with the people connected through it, what each of them approved, and a revoke beside each — so taking one person's access away leaves their colleagues working.## What a grant can never hold@@ -36,7 +36,7 @@ The second matters because the first is about what the model knows, not about wh## Revoking-**Settings → Connected apps** lists everything connected, who approved it and when each was last used. Revoking takes effect on the agent's next call: it revokes every live token and grant rather than deleting the registration, so a client that still holds a token stops working immediately and the merchant can reconnect later without re-registering.+**Settings → AI Agents** lists everything connected, who approved it and when. Revoking takes effect on that person's next call: it revokes their access rather than the registration, so they stop working immediately, their colleagues carry on, and they can connect again later without the client being registered afresh.## Registering a clientdiff --git a/docs/developer/mcp/quick-start.mdx b/docs/developer/mcp/quick-start.mdxindex e38688fe36..bbd72edcc9 100644--- a/docs/developer/mcp/quick-start.mdx+++ b/docs/developer/mcp/quick-start.mdx@@ -4,9 +4,21 @@ sidebarTitle: Quick startdescription: "Install the MCP server, connect an AI client and run the first conversation against your store."----## Install the gem+## Check it is installed-The server ships as an optional gem. Add it and restart; there is nothing to configure.+A new Spree store has the server already — `spree_mcp` is in the starter's+`Gemfile`, so the endpoint is live the first time you boot:++```text+https://your-store.com/api/v3/admin/mcp+```++<Note>+ Nothing to configure, and no migration for the server itself. The OAuth+ tables ship with `spree_core` and arrive with Spree's other migrations.+</Note>++Upgrading an older store, or deliberately removed it? Add the gem back:<Tabs><Tab title="Spree CLI">@@ -25,14 +37,6 @@ The server ships as an optional gem. Add it and restart; there is nothing to con</Tab></Tabs>-The endpoint is then live:--```text-https://your-store.com/api/v3/admin/mcp-```--No migration is needed for the server itself. OAuth tables ship with `spree_core` and are installed with Spree's other migrations.-## Connect a clientPaste the URL into your MCP client. It sends you to Spree, you sign in, and you approve what the agent may do.@@ -45,6 +49,11 @@ Paste the URL into your MCP client. It sends you to Spree, you sign in, and you</Tab><Tab title="Claude Desktop / claude.ai">**Settings → Connectors → Add custom connector**, then paste the URL.++ This client asks for a **Client ID** as well. Copy it from+ **Settings → OAuth clients** in your Spree dashboard, where each+ registered client shows one — it is public, and is what identifies the+ connector to your store.</Tab><Tab title="Cursor">```json .cursor/mcp.json@@ -113,18 +122,18 @@ Ask the agent directly — `describe_resource` with no arguments lists every res<AccordionGroup><Accordion title="The client says the server needs authorization and nothing happens">- The endpoint advertises its authorization server at `/api/v3/oauth/protected-resource/mcp`. If your store sits behind a proxy that rewrites the host, the advertised URL has to be one the browser can reach — check that `Spree::Store#url` and the incoming `Host` header agree.+ The endpoint advertises its authorization server at `/api/v3/oauth/protected-resource/admin`. If your store sits behind a proxy that rewrites the host, the advertised URL has to be one the browser can reach — check that `Spree::Store#url` and the incoming `Host` header agree.</Accordion><Accordion title="Connected, but the agent says it cannot do something">- It was not granted that permission. **Settings → Connected apps** shows what each connection holds; revoke and reconnect to approve more. Tools outside the grant are not offered at all, so the agent will say it has no way to do it rather than failing mid-call.+ It was not granted that permission. **Settings → AI Agents** shows what each connection holds; revoke and reconnect to approve more. Tools outside the grant are not offered at all, so the agent will say it has no way to do it rather than failing mid-call.</Accordion><Accordion title="A tool exists but refuses with a permission error">Tool visibility is per permission, but the data behind it is checked per record and per resource. A connection granted `read_reports` can run a report, and will still be refused a dimension that exposes customers unless it also holds `read_customers`.</Accordion>- <Accordion title="Nothing is listed under Connected apps">+ <Accordion title="Nothing is listed under AI Agents">Connections are per person. You are looking at your own; another staff member's connection appears under theirs.</Accordion></AccordionGroup>diff --git a/docs/developer/mcp/tools.mdx b/docs/developer/mcp/tools.mdxindex 25b33ca258..0fdada6101 100644--- a/docs/developer/mcp/tools.mdx+++ b/docs/developer/mcp/tools.mdx@@ -108,7 +108,12 @@ The catalog is deliberately not a mirror of the API's 500-odd operations — a t| `get_import_status` | — | read || `create_export` | — | write |-### Store setup+### Creating, changing and deleting records++Three tools cover every resource the Admin API can write — 38 of them, from+products and orders to markets, tax rates and delivery methods — rather than+one tool per resource. They dispatch to the real endpoint, so a resource whose+controller runs a workflow gets that workflow.| Tool | Permission | || --- | --- | --- |@@ -117,6 +122,10 @@ The catalog is deliberately not a mirror of the API's 500-odd operations — a t| `delete_resource` | — | write || `tax_exemption_certificates_verify` | `write_customers` | write |+The dash is the point: each call is gated on the resource being written, so a+grant holding `write_products` can create a product and is refused a market.+Call `describe_resource` for what a resource accepts.+## Resources@@ -141,11 +150,7 @@ Some things are out of reach whatever a grant holds.## Writing records-Three tools cover every resource the Admin API can write, rather than one tool per resource:--- `create_resource`, `update_resource`, `delete_resource`--They dispatch to the real endpoint, so a resource whose controller runs a workflow gets that workflow. Two things worth knowing:+Two things worth knowing about the generic writes:**Nested records travel with their parent.** A product's variants carry their own options, prices and stock levels in the same write, so creating a product with two sized variants is one call rather than four. `describe_resource` reports what fits inside each list.diff --git a/docs/plans/6.0-mcp-oauth.md b/docs/plans/6.0-mcp-oauth.mdindex 3f08a55ebc..749e7936bf 100644--- a/docs/plans/6.0-mcp-oauth.md+++ b/docs/plans/6.0-mcp-oauth.md@@ -119,6 +119,14 @@ Doorkeeper's resource-indicator support supplies the `aud` to check — but thecheck itself lives in our endpoint and gets its own spec, because a missingaudience check is invisible until it is exploited.+**One audience for the whole Admin API, including MCP.** The endpoint was+first given an audience of its own, which could never work: a tool call+reaches data by dispatching into the Admin API carrying the same token, so+two audiences on one credential meant one of the two checks always refused+it. The scopes are the ceiling a merchant approves, and the MCP endpoint+offers nothing the Admin API does not — the path a token names adds no+protection worth a surface that cannot authenticate itself.+## Migration Path1. **Doorkeeper in, migrations, no endpoints yet.** The gem, its tables, anddiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 3438722062..e0c1b27d00 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -6363,3 +6363,24 @@ 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 anyother adapter may still use it; only the MCP transport refuses one.++## 2026-10-16 — One OAuth audience for the Admin API, MCP included++The MCP endpoint had an audience of its own (`/api/v3/admin/mcp`) while the+Admin API demanded `/api/v3/admin`. A tool call reaches data by dispatching+into the Admin API carrying the caller's own token, so no single credential+could satisfy both checks: every dispatched read and write answered+"authentication required" while the endpoint itself looked healthy.++A workaround minted both audiences for an MCP grant, but only on the consent+preview — the action that writes the grant passed the client's raw `resource`+through, and the indicator is optional, so real grants carried none at all.++There is now one audience. `granted_audience` is gone, the MCP engine+registers no resource, and the endpoint checks the Admin API's audience like+every other admin surface. The scopes a merchant approves are the ceiling;+the path a token names was buying nothing.++The specs that missed this minted tokens in Ruby and dispatched with an admin+JWT, so neither consent nor the OAuth dispatch path was ever exercised. The+MCP suite now walks consent, token exchange and a tool call as a client does.diff --git a/docs/style.css b/docs/style.cssindex 44c7a9a5f1..84f6cd90dc 100644--- a/docs/style.css+++ b/docs/style.css@@ -1,420 +1,65 @@-/* ---------------------------------------------------------------------------- Spree documentation theme.-- Colour tokens are copied from the marketing site's design tokens- (website/src/styles/global.css), which are generated from the Figma- variable set. Keep the two in sync — this file is the docs' only styling- hook, so a token that drifts here shows up as a visible seam between- spreecommerce.org and spreecommerce.org/docs.---------------------------------------------------------------------------- */--:root {- /* Brand */- --spree-accent: #0077ff;- --spree-accent-strong: #0060ce;-- /* Sand — the warm surface ramp the marketing site is built on */- --spree-sand-50: #fcfaf7;- --spree-sand-100: #f7f5f2;- --spree-sand-150: #e9e5dd;- --spree-sand-200: #e2dfd8;-- /* Dark sand — warm darks for inverted surfaces */- --spree-dark-sand-500: #32302e;- --spree-dark-sand-600: #272626;- --spree-dark-sand-700: #1e1c1b;- --spree-dark-sand-800: #191818;-- /* Neutral ramp for text and borders */- --spree-neutral-100: #eaeaea;- --spree-neutral-200: #d5d5d5;- --spree-neutral-400: #999999;- --spree-neutral-600: #666666;- --spree-neutral-700: #4d4d4d;- --spree-neutral-900: #1a1a1a;-- /* Semantic */- --spree-ink: #1a1a1a;- --spree-heading: #061932;- --spree-ink-muted: #666666;- --spree-border: #e2dfd8;-- /* Sidebar (dashboard-like): neutral pills, not accent-tinted */- --spree-sidebar-hover: rgb(0 0 0 / 0.04);- --spree-sidebar-active: rgb(0 0 0 / 0.06);- --spree-sidebar-radius: 0.625rem;- --spree-guide: #d8d4cb;-}--.dark {- --spree-sidebar-hover: rgb(255 255 255 / 0.06);- --spree-sidebar-active: rgb(255 255 255 / 0.10);- --spree-border: #3f3e3c;- --spree-guide: #3f3e3c;-}--/* --- Surfaces ------------------------------------------------------------ */--html:not(.dark) body {- background: var(--spree-sand-50);-}--html.dark body {- background: var(--spree-dark-sand-800);-}--/* Headings pick up the site's navy rather than pure black. */-html:not(.dark) h1,-html:not(.dark) h2,-html:not(.dark) h3,-html:not(.dark) h4 {- color: var(--spree-heading);-}--.nav-logo {- height: 32px;-}--/* --- Sidebar ------------------------------------------------------------- */-/* Mirrors the Spree dashboard:- - the SECTION carries the grey pill when the open page lives inside it- - the active child is bold text only, no background- - children get a background on hover, inset rather than full width- - a hairline guide runs down the children of the open section- Mintlify marks the section holding the current page with- li[data-group-tag][data-active="true"], and the current page itself with- `bg-primary/10 text-primary` — both are repurposed below. */--/* The top-level wrapper ("Develop" / "Manage") exists only because Mintlify- needs a non-empty group name to make its children collapsible. It carries no- meaning for the reader, so its header is hidden while the group still works. */-#sidebar-content .sidebar-group-header {- display: none;-}--#sidebar-content a,-#sidebar-content button:not([class*="group/search"]) {- border-radius: var(--spree-sidebar-radius) !important;- padding-top: 0.3125rem !important;- padding-bottom: 0.3125rem !important;-}--/* Section rows: the primary level of the tree. Same size as their children,- but taller and more widely spaced, so the top level reads as navigation- rather than a list (the rhythm Vendure's sidebar uses). */-#sidebar-content ul.sidebar-group > li > button,-#sidebar-content ul.sidebar-group > li > a {- font-weight: 500;- padding-top: 0.5rem !important;- padding-bottom: 0.5rem !important;-}--/* Breathing room between top-level sections. */-#sidebar-content ul.sidebar-group > li + li {- margin-top: 0.25rem;-}--/* An open section's children sit closer to it than the next section does. */-#sidebar-content li[data-group-tag] > ul {- margin-top: 0.125rem;- margin-bottom: 0.375rem;-}--/* Hover: a soft neutral wash, never the accent. */-#sidebar-content a:hover,-#sidebar-content button:not([class*="group/search"]):hover {- background-color: var(--spree-sidebar-hover) !important;-}--/* The section containing the current page wears the pill. */-#sidebar-content li[data-group-tag][data-active="true"] > button,-#sidebar-content li[data-group-tag][data-active="true"] > a {- background-color: var(--spree-sidebar-active) !important;- color: var(--spree-neutral-900) !important;- font-weight: 600 !important;-}--.dark #sidebar-content li[data-group-tag][data-active="true"] > button,-.dark #sidebar-content li[data-group-tag][data-active="true"] > a {- color: #ffffff !important;-}--/* The current page itself: bold text, no fill. Mintlify's accent tint and the- faux-bold text-shadow it pairs with are both removed. */-#sidebar-content a[class*="bg-primary/10"],-#sidebar-content a[class*="bg-primary-light/10"] {- background-color: transparent !important;- color: var(--spree-neutral-900) !important;- font-weight: 600 !important;- text-shadow: none !important;-}--.dark #sidebar-content a[class*="bg-primary/10"],-.dark #sidebar-content a[class*="bg-primary-light/10"] {- color: #ffffff !important;-}--/* ...but it still highlights on hover, like any other child. */-#sidebar-content a[class*="bg-primary/10"]:hover,-#sidebar-content a[class*="bg-primary-light/10"]:hover {- background-color: var(--spree-sidebar-hover) !important;-}--/* Child rows align with their section's *label*, not its icon: a section row- is 16px padding + a 16px icon + a 12px gap, so children need 44px to line up.- Mintlify's default 28px leaves them hanging 16px to the left. The right- margin keeps the hover pill inset rather than full-bleed. */-#sidebar-content ul:not(.sidebar-group) > li > a,-#sidebar-content ul:not(.sidebar-group) > li > button {- padding-left: 0.5rem !important;- margin-left: 2.25rem;- margin-right: 0.25rem;- width: calc(100% - 2.5rem) !important;-}--/* Third level: the whole row steps right by one indent, so its own guide line- clears the parent's instead of sitting on top of it. */-#sidebar-content ul:not(.sidebar-group) ul:not(.sidebar-group) > li > a,-#sidebar-content ul:not(.sidebar-group) ul:not(.sidebar-group) > li > button {- padding-left: 0.5rem !important;- margin-left: 3.75rem;- width: calc(100% - 4rem) !important;-}--/* Guide line down the open section's children, sitting under the section- icon. The list is a plain <ul> with no border of its own.-- Every open group draws its own, each stepped right by one indent so the- levels read as a nested tree rather than overlapping into one stroke. */-#sidebar-content li[data-group-tag] > ul {- position: relative;-}--#sidebar-content li[data-group-tag] > ul::before {- content: "";- position: absolute;- left: 1.75rem;- top: 0;- bottom: 0;- width: 1px;- background-color: var(--spree-guide);-}--/* A nested group's line steps right by the same indent as its rows. */-#sidebar-content li[data-group-tag] li[data-group-tag] > ul::before {- left: 3.25rem;-}--/* Section icons are mask-based SVGs tinted with a background utility (the- chevrons are stroke-based and must not be touched, hence the class match).- Tie them to the label colour so a row reads as one unit. */-#sidebar-content button svg[class*="bg-gray-"],-#sidebar-content a svg[class*="bg-gray-"] {- background-color: currentColor !important;- opacity: 0.6;-}--#sidebar-content button:hover svg[class*="bg-gray-"],-#sidebar-content a:hover svg[class*="bg-gray-"],-#sidebar-content li[data-group-tag][data-active="true"] > button svg[class*="bg-gray-"] {- opacity: 1;-}--/* The almond theme floats a rounded white panel on the shell; its default- border is a cool grey against our warm sand, which is what makes the header- and sidebar look like a different colour from the content. */-#content-container {- border-color: var(--spree-border) !important;-}--.dark #content-container {- border-color: #3f3e3c !important;-}--/* --- Content width ------------------------------------------------------- */-/* Mintlify caps the article at max-w-xl (576px) and then pads the wrapper by- another 48px, so on a wide screen most of the page is empty. Widen the- measure and reclaim the padding — tables, code blocks and the API reference- are what benefit. Capped rather than fluid so long prose stays readable. */--@media (min-width: 1024px) {- /* The <main> pads by 64px on each side, then the inner wrapper adds another- 48px on the left before the gap to the table of contents. */- #content-container {- padding-left: 3rem !important;- padding-right: 3rem !important;- }-- #content-container > .flex.flex-row-reverse {- padding-left: 0 !important;- column-gap: 2.5rem !important;- }+/* Tables, styled after the dashboard's: a filled header row, a rule between+ rows and an outer border, so a wide table reads as one block rather than+ drifting columns.++ `!important` throughout because Mintlify ships its own table rules and+ loads this stylesheet before them. Fixed colours rather than CSS variables+ for the same reason — the theme's own variables are not in scope here. */+table {+ border: 1px solid #d0d7de !important;+ border-radius: 0.5rem !important;+ border-collapse: separate !important;+ border-spacing: 0 !important;+ overflow: hidden !important;+ width: 100%;}-/* The article itself is capped at max-w-xl (576px); a wider measure is what- actually gives tables, code blocks and API examples room. */-#content-container .flex.flex-row-reverse > .max-w-xl {- max-width: 52rem;+table thead {+ background-color: #f3f4f6 !important;}-/* --- Navbar --------------------------------------------------------------- */-/* The header is transparent by default and only picks up a background once the- page scrolls — on the custom-mode homepage it never does, so the bar floats- over the content. Give it a solid surface and a hairline at all times. */--/* The almond theme lays a 3% black wash (#almond-background-color) across the- viewport at -z-10. The header paints its own opaque background above it, so- it renders lighter than the sidebar, which sits on the washed body — the two- look like different colours despite computing identically. Drop the wash and- let the sand body show through everywhere. */-#almond-background-color {- background-color: transparent !important;-}--#navbar {- background-color: var(--spree-sand-50);-}--.dark #navbar {- background-color: var(--spree-dark-sand-800);-}--/* Only the homepage needs the rule: docs pages already read as separated,- because the white content panel meets the sand header at its own edge.- Mintlify marks custom-mode pages on the header itself. */-#navbar.is-custom {- border-bottom: 1px solid var(--spree-border);+table th {+ font-weight: 500 !important;+ text-align: left;+ color: #4b5563 !important;+ padding: 0.625rem 0.875rem !important;+ border-bottom: 1px solid #d0d7de !important;}-.dark #navbar.is-custom {- border-bottom-color: #3f3e3c;+/* Vertical rules too, so columns in a wide table stay readable across. */+table th + th,+table td + td {+ border-left: 1px solid #e8ebee !important;}-/* Mintlify fades its own backdrop layer in on scroll; with a solid bar behind- it that would double up, so keep it out of the way. */-#navbar > .absolute.inset-0 {- display: none;+table td {+ padding: 0.75rem 0.875rem !important;+ border-bottom: 1px solid #e8ebee !important;+ vertical-align: middle;}-/* --- Homepage bands ------------------------------------------------------- */-/* The homepage alternates white bands on the sand body. These are plain CSS- classes because utility classes passed through an MDX component prop are NOT- compiled by Mintlify (literal JSX classes are) — a dark: variant sent that- way silently produces no CSS. */--.home-band {- background: #ffffff;-}--.dark .home-band {- background: var(--spree-dark-sand-700);-}--.home-band-end {- border-bottom: 1px solid rgb(233 229 221 / 0.8);-}--.dark .home-band-end {- border-bottom-color: #3f3e3c;-}--/* --- Accents ------------------------------------------------------------- */--/* Body links: blue text, no rule beneath it. Mintlify styles `a.link` as dark- text with a 1px blue border-bottom, which reads as an underline. */-/* Scoped to the article: the navbar tabs carry the same `.link` class and must- keep their own colours. */-#content-container .link {+table tbody tr:last-child td {border-bottom: 0 !important;- color: var(--spree-accent) !important;- text-decoration: none !important;-}--#content-container .link:hover {- color: var(--spree-accent-strong) !important;-}--.dark #content-container .link {- color: #4d9fff !important;-}--.dark #content-container .link:hover {- color: #7fb8ff !important;-}--/* --- Changelog ------------------------------------------------------------ */-/* The changelog runs in custom mode so it has no empty sidebar, and custom- mode drops Mintlify's article typography — these rules restore it. The- <Update> entries must stay top-level in the MDX (the RSS feed skips nested- ones), so the page is styled through the container holding the header. */--:has(> .changelog-header) {- max-width: 56rem;- margin: 0 auto;- padding: 4rem 1.25rem 6rem;-}--.changelog-header h1 {- font-size: 2.25rem;- font-weight: 600;- letter-spacing: -0.02em;- margin-bottom: 0.75rem;-}--.changelog-header > p,-.changelog-header > [data-as="p"] {- color: var(--spree-ink-muted);- font-size: 1.0625rem;- margin-bottom: 1.25rem;-}--.changelog-header .changelog-rss {- display: inline-flex;- align-items: center;- gap: 0.5rem;- margin-bottom: 3.5rem;- padding: 0.375rem 0.875rem;- border: 1px solid var(--spree-border);- border-radius: 9999px;- font-size: 0.875rem;- font-weight: 500;- text-decoration: none;-}--.changelog-header .changelog-rss:hover {- border-color: var(--spree-accent);-}--:has(> .changelog-header) p,-:has(> .changelog-header) [data-as="p"] {- display: block !important;- margin: 0 0 1rem;- line-height: 1.7;-}--:has(> .changelog-header) ul {- list-style: disc;- padding-left: 1.25rem;- margin: 0 0 1rem;}-:has(> .changelog-header) li {- margin: 0.25rem 0;- line-height: 1.65;+.dark table {+ border-color: #3d444d !important;}-:has(> .changelog-header) li::marker {- color: var(--spree-neutral-400);+.dark table thead {+ background-color: #21262d !important;}-:has(> .changelog-header) a {- color: var(--spree-accent);+.dark table th {+ color: #9198a1 !important;+ border-bottom-color: #3d444d !important;}-:has(> .changelog-header) a:hover {- color: var(--spree-accent-strong);+.dark table th + th,+.dark table td + td {+ border-left-color: #2a3038 !important;}-.dark :has(> .changelog-header) a {- color: #4d9fff;+.dark table td {+ border-bottom-color: #2a3038 !important;}diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex 5e4feae1ba..1b4e17f72a 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -655,6 +655,7 @@ import type {Locale,Market,Media,+ OauthAccessToken,OauthApplication,OauthConsentRequest,OauthRedirect,@@ -5975,9 +5976,6 @@ export class AdminClient {params: params ? transformListParams(params) : undefined,}),- get: (id: string, options?: RequestOptions): Promise<OauthApplication> =>- this.request<OauthApplication>('GET', `/oauth/applications/${id}`, options ?? {}),-create: (params: { name: string; redirect_uri: string },options?: RequestOptions,@@ -6002,11 +6000,32 @@ export class AdminClient {this.request<void>('DELETE', `/oauth/applications/${id}`, options ?? {}),/**- * Revokes every live token and grant an application holds, keeping the- * registration so a merchant can connect the same client again.+ * The live access a connected client holds, one entry per person who+ * connected it. A store registers a client once and everyone connects+ * to that same registration, so this is who is actually connected.*/- revoke: (id: string, options?: RequestOptions): Promise<void> =>- this.request<void>('DELETE', `/oauth/applications/${id}/tokens`, options ?? {}),+ tokens: {+ list: (+ applicationId: string,+ params?: ListParams,+ options?: RequestOptions,+ ): Promise<PaginatedResponse<OauthAccessToken>> =>+ this.request<PaginatedResponse<OauthAccessToken>>(+ 'GET',+ `/oauth/applications/${applicationId}/tokens`,+ { ...(options ?? {}), params: params ? transformListParams(params) : undefined },+ ),++ /**+ * Revokes one person's access, leaving their colleagues connected.+ */+ delete: (applicationId: string, id: string, options?: RequestOptions): Promise<void> =>+ this.request<void>(+ 'DELETE',+ `/oauth/applications/${applicationId}/tokens/${id}`,+ options ?? {},+ ),+ },},}diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.tsindex b1589e934b..5c2c17d81f 100644--- a/packages/admin-sdk/src/params.ts+++ b/packages/admin-sdk/src/params.ts@@ -456,3 +456,22 @@ export type EmailTemplateLanguageParams = {/** A language code, or `any` (the default) for the version every language uses. */language?: string}++/**+ * The OAuth authorization request, forwarded from the query string the client+ * sent the browser to. Passed through unchanged so the authorization server+ * validates it rather than the dashboard — PKCE and the audience in+ * particular must not be re-derived here.+ */+export interface OauthAuthorizationParams {+ client_id: string+ redirect_uri: string+ response_type: string+ /** Space-delimited permission keys, the same vocabulary as API-key scopes. */+ scope?: string+ state?: string+ code_challenge?: string+ code_challenge_method?: string+ /** RFC 8707: which protected resource the token is being requested for. */+ resource?: string+}diff --git a/packages/admin-sdk/src/types/generated/OauthAccessToken.ts b/packages/admin-sdk/src/types/generated/OauthAccessToken.tsnew file mode 100644index 0000000000..6fcdb6c738--- /dev/null+++ b/packages/admin-sdk/src/types/generated/OauthAccessToken.ts@@ -0,0 +1,16 @@+// Typelizer digest ea88cc20cfb181f24d7727cad8cc3bc3+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.+import type {AdminUser} from '@/types'++interface OauthAccessToken {+ id: string;+ created_at: string;+ owner_id: string | null;+ owner_type: string | null;+ owner?: AdminUser;+ scopes: Array<string>;+ expired: boolean;+}++export default OauthAccessToken;diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.tsindex 1b5cebbe5c..ab71ce8b86 100644--- a/packages/admin-sdk/src/types/index.ts+++ b/packages/admin-sdk/src/types/index.ts@@ -131,6 +131,7 @@ export type { default as LineItem } from './generated/LineItem'export type { default as Locale } from './generated/Locale'export type { default as Market } from './generated/Market'export type { default as Media } from './generated/Media'+export type { default as OauthAccessToken } from './generated/OauthAccessToken'export type { default as OauthApplication } from './generated/OauthApplication'export type { default as OauthConsentRequest } from './generated/OauthConsentRequest'export type { default as OauthRedirect } from './generated/OauthRedirect'diff --git a/packages/admin-sdk/src/zod/generated/OauthAccessToken.ts b/packages/admin-sdk/src/zod/generated/OauthAccessToken.tsnew file mode 100644index 0000000000..bd7c43d605--- /dev/null+++ b/packages/admin-sdk/src/zod/generated/OauthAccessToken.ts@@ -0,0 +1,15 @@+// This file is auto-generated. Do not edit directly.+import { z } from 'zod';+import { AdminUserSchema } from './AdminUser';++export const OauthAccessTokenSchema = z.object({+ id: z.string(),+ created_at: z.string(),+ owner_id: z.string().nullable(),+ owner_type: z.string().nullable(),+ owner: AdminUserSchema.optional(),+ scopes: z.array(z.string()),+ expired: z.boolean(),+});++export type OauthAccessToken = z.infer<typeof OauthAccessTokenSchema>;diff --git a/packages/admin-sdk/src/zod/generated/index.ts b/packages/admin-sdk/src/zod/generated/index.tsindex 23d8fa7abe..388da1a282 100644--- a/packages/admin-sdk/src/zod/generated/index.ts+++ b/packages/admin-sdk/src/zod/generated/index.ts@@ -78,6 +78,7 @@ export { MarketSchema, type Market } from './Market';export { MediaSchema, type Media } from './Media';export { MembershipProductSchema, type MembershipProduct } from './MembershipProduct';export { NewsletterSubscriberSchema, type NewsletterSubscriber } from './NewsletterSubscriber';+export { OauthAccessTokenSchema, type OauthAccessToken } from './OauthAccessToken';export { OauthApplicationSchema, type OauthApplication } from './OauthApplication';export { OauthConsentRequestSchema, type OauthConsentRequest } from './OauthConsentRequest';export { OauthProtectedResourceSchema, type OauthProtectedResource } from './OauthProtectedResource';diff --git a/packages/dashboard-starter/src/routeTree.gen.ts b/packages/dashboard-starter/src/routeTree.gen.tsindex 73f9c5d857..cb9052e034 100644--- a/packages/dashboard-starter/src/routeTree.gen.ts+++ b/packages/dashboard-starter/src/routeTree.gen.ts@@ -59,11 +59,11 @@ import { Route as SellersSellerIdRouteImport } from './../../dashboard/src/routeimport { Route as SellersCommissionRatesRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/sellers/commission-rates'import { Route as SellersTransfersRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/sellers/transfers'import { Route as SettingsIndexRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/index'+import { Route as SettingsAiAgentsRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/ai-agents'import { Route as SettingsAllowedOriginsRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/allowed-origins'import { Route as SettingsApiKeysRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/api-keys'import { Route as SettingsChannelsRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/channels'import { Route as SettingsCommissionRatesRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/commission-rates'-import { Route as SettingsConnectedAppsRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/connected-apps'import { Route as SettingsCustomFieldDefinitionsRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/custom-field-definitions'import { Route as SettingsIntegrationsRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/integrations'import { Route as SettingsMarketplaceRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/marketplace'@@ -364,6 +364,11 @@ const SettingsIndexRoute = SettingsIndexRouteImport.update({path: '/',getParentRoute: () => SettingsRoute,} as any)+const SettingsAiAgentsRoute = SettingsAiAgentsRouteImport.update({+ id: '/ai-agents',+ path: '/ai-agents',+ getParentRoute: () => SettingsRoute,+} as any)const SettingsAllowedOriginsRoute = SettingsAllowedOriginsRouteImport.update({id: '/allowed-origins',path: '/allowed-origins',@@ -384,11 +389,6 @@ const SettingsCommissionRatesRoute = SettingsCommissionRatesRouteImport.update({path: '/commission-rates',getParentRoute: () => SettingsRoute,} as any)-const SettingsConnectedAppsRoute = SettingsConnectedAppsRouteImport.update({- id: '/connected-apps',- path: '/connected-apps',- getParentRoute: () => SettingsRoute,-} as any)const SettingsCustomFieldDefinitionsRoute =SettingsCustomFieldDefinitionsRouteImport.update({id: '/custom-field-definitions',@@ -691,11 +691,11 @@ export interface FileRoutesByFullPath {'/$storeId/sellers/$sellerId': typeof SellersSellerIdRoute'/$storeId/sellers/commission-rates': typeof SellersCommissionRatesRoute'/$storeId/sellers/transfers': typeof SellersTransfersRoute+ '/$storeId/settings/ai-agents': typeof SettingsAiAgentsRoute'/$storeId/settings/allowed-origins': typeof SettingsAllowedOriginsRoute'/$storeId/settings/api-keys': typeof SettingsApiKeysRoute'/$storeId/settings/channels': typeof SettingsChannelsRoute'/$storeId/settings/commission-rates': typeof SettingsCommissionRatesRoute- '/$storeId/settings/connected-apps': typeof SettingsConnectedAppsRoute'/$storeId/settings/custom-field-definitions': typeof SettingsCustomFieldDefinitionsRoute'/$storeId/settings/integrations': typeof SettingsIntegrationsRoute'/$storeId/settings/marketplace': typeof SettingsMarketplaceRoute@@ -794,11 +794,11 @@ export interface FileRoutesByTo {'/$storeId/sellers/$sellerId': typeof SellersSellerIdRoute'/$storeId/sellers/commission-rates': typeof SellersCommissionRatesRoute'/$storeId/sellers/transfers': typeof SellersTransfersRoute+ '/$storeId/settings/ai-agents': typeof SettingsAiAgentsRoute'/$storeId/settings/allowed-origins': typeof SettingsAllowedOriginsRoute'/$storeId/settings/api-keys': typeof SettingsApiKeysRoute'/$storeId/settings/channels': typeof SettingsChannelsRoute'/$storeId/settings/commission-rates': typeof SettingsCommissionRatesRoute- '/$storeId/settings/connected-apps': typeof SettingsConnectedAppsRoute'/$storeId/settings/custom-field-definitions': typeof SettingsCustomFieldDefinitionsRoute'/$storeId/settings/integrations': typeof SettingsIntegrationsRoute'/$storeId/settings/marketplace': typeof SettingsMarketplaceRoute@@ -901,11 +901,11 @@ export interface FileRoutesById {'/_authenticated/$storeId/sellers/$sellerId': typeof SellersSellerIdRoute'/_authenticated/$storeId/sellers/commission-rates': typeof SellersCommissionRatesRoute'/_authenticated/$storeId/sellers/transfers': typeof SellersTransfersRoute+ '/_authenticated/$storeId/settings/ai-agents': typeof SettingsAiAgentsRoute'/_authenticated/$storeId/settings/allowed-origins': typeof SettingsAllowedOriginsRoute'/_authenticated/$storeId/settings/api-keys': typeof SettingsApiKeysRoute'/_authenticated/$storeId/settings/channels': typeof SettingsChannelsRoute'/_authenticated/$storeId/settings/commission-rates': typeof SettingsCommissionRatesRoute- '/_authenticated/$storeId/settings/connected-apps': typeof SettingsConnectedAppsRoute'/_authenticated/$storeId/settings/custom-field-definitions': typeof SettingsCustomFieldDefinitionsRoute'/_authenticated/$storeId/settings/integrations': typeof SettingsIntegrationsRoute'/_authenticated/$storeId/settings/marketplace': typeof SettingsMarketplaceRoute@@ -1008,11 +1008,11 @@ export interface FileRouteTypes {| '/$storeId/sellers/$sellerId'| '/$storeId/sellers/commission-rates'| '/$storeId/sellers/transfers'+ | '/$storeId/settings/ai-agents'| '/$storeId/settings/allowed-origins'| '/$storeId/settings/api-keys'| '/$storeId/settings/channels'| '/$storeId/settings/commission-rates'- | '/$storeId/settings/connected-apps'| '/$storeId/settings/custom-field-definitions'| '/$storeId/settings/integrations'| '/$storeId/settings/marketplace'@@ -1111,11 +1111,11 @@ export interface FileRouteTypes {| '/$storeId/sellers/$sellerId'| '/$storeId/sellers/commission-rates'| '/$storeId/sellers/transfers'+ | '/$storeId/settings/ai-agents'| '/$storeId/settings/allowed-origins'| '/$storeId/settings/api-keys'| '/$storeId/settings/channels'| '/$storeId/settings/commission-rates'- | '/$storeId/settings/connected-apps'| '/$storeId/settings/custom-field-definitions'| '/$storeId/settings/integrations'| '/$storeId/settings/marketplace'@@ -1217,11 +1217,11 @@ export interface FileRouteTypes {| '/_authenticated/$storeId/sellers/$sellerId'| '/_authenticated/$storeId/sellers/commission-rates'| '/_authenticated/$storeId/sellers/transfers'+ | '/_authenticated/$storeId/settings/ai-agents'| '/_authenticated/$storeId/settings/allowed-origins'| '/_authenticated/$storeId/settings/api-keys'| '/_authenticated/$storeId/settings/channels'| '/_authenticated/$storeId/settings/commission-rates'- | '/_authenticated/$storeId/settings/connected-apps'| '/_authenticated/$storeId/settings/custom-field-definitions'| '/_authenticated/$storeId/settings/integrations'| '/_authenticated/$storeId/settings/marketplace'@@ -1645,6 +1645,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SettingsIndexRouteImportparentRoute: typeof SettingsRoute}+ '/_authenticated/$storeId/settings/ai-agents': {+ id: '/_authenticated/$storeId/settings/ai-agents'+ path: '/ai-agents'+ fullPath: '/$storeId/settings/ai-agents'+ preLoaderRoute: typeof SettingsAiAgentsRouteImport+ parentRoute: typeof SettingsRoute+ }'/_authenticated/$storeId/settings/allowed-origins': {id: '/_authenticated/$storeId/settings/allowed-origins'path: '/allowed-origins'@@ -1673,13 +1680,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SettingsCommissionRatesRouteImportparentRoute: typeof SettingsRoute}- '/_authenticated/$storeId/settings/connected-apps': {- id: '/_authenticated/$storeId/settings/connected-apps'- path: '/connected-apps'- fullPath: '/$storeId/settings/connected-apps'- preLoaderRoute: typeof SettingsConnectedAppsRouteImport- parentRoute: typeof SettingsRoute- }'/_authenticated/$storeId/settings/custom-field-definitions': {id: '/_authenticated/$storeId/settings/custom-field-definitions'path: '/custom-field-definitions'@@ -2027,11 +2027,11 @@ declare module '@tanstack/react-router' {}interface SettingsRouteChildren {+ SettingsAiAgentsRoute: typeof SettingsAiAgentsRouteSettingsAllowedOriginsRoute: typeof SettingsAllowedOriginsRouteSettingsApiKeysRoute: typeof SettingsApiKeysRouteSettingsChannelsRoute: typeof SettingsChannelsRouteSettingsCommissionRatesRoute: typeof SettingsCommissionRatesRoute- SettingsConnectedAppsRoute: typeof SettingsConnectedAppsRouteSettingsCustomFieldDefinitionsRoute: typeof SettingsCustomFieldDefinitionsRouteSettingsIntegrationsRoute: typeof SettingsIntegrationsRouteSettingsMarketplaceRoute: typeof SettingsMarketplaceRoute@@ -2064,11 +2064,11 @@ interface SettingsRouteChildren {}const SettingsRouteChildren: SettingsRouteChildren = {+ SettingsAiAgentsRoute: SettingsAiAgentsRoute,SettingsAllowedOriginsRoute: SettingsAllowedOriginsRoute,SettingsApiKeysRoute: SettingsApiKeysRoute,SettingsChannelsRoute: SettingsChannelsRoute,SettingsCommissionRatesRoute: SettingsCommissionRatesRoute,- SettingsConnectedAppsRoute: SettingsConnectedAppsRoute,SettingsCustomFieldDefinitionsRoute: SettingsCustomFieldDefinitionsRoute,SettingsIntegrationsRoute: SettingsIntegrationsRoute,SettingsMarketplaceRoute: SettingsMarketplaceRoute,diff --git a/packages/dashboard/e2e/oauth-clients.spec.ts b/packages/dashboard/e2e/oauth-clients.spec.tsindex d091e84113..66ce4cc229 100644--- a/packages/dashboard/e2e/oauth-clients.spec.ts+++ b/packages/dashboard/e2e/oauth-clients.spec.ts@@ -1,7 +1,7 @@import { expect, type Page, test } from '@playwright/test'import { gotoIndex, login } from './helpers'-const AGENTS_PATH = (storeId: string) => `/${storeId}/settings/connected-apps`+const AGENTS_PATH = (storeId: string) => `/${storeId}/settings/ai-agents`const CLIENTS_PATH = (storeId: string) => `/${storeId}/settings/oauth-clients`const CONNECT_CTA = /connect an agent/iconst REGISTER_CTA = /register a client/i@@ -69,7 +69,7 @@ test.describe('before any agent has been connected', () => {await expect(sheet.getByText(/ready to connect/i)).toBeVisible({ timeout: 15_000 })await sheet.getByRole('button', { name: /^done$/i }).click()- await expect(page.getByRole('row', { name: /Claude/ })).toBeVisible({ timeout: 15_000 })+ await expect(page.getByText('Claude').first()).toBeVisible({ timeout: 15_000 })})})@@ -93,8 +93,8 @@ test.describe('connecting an agent', () => {})// Revoking keeps the registration so the same client can be connected- // again — which is exactly why the row has to say what changed.- test('says whether a registration is connected', async ({ page }) => {+ // again — which is exactly why the card has to say who holds access now.+ test('says who is connected through a registration', async ({ page }) => {const creds = await login(page)await gotoIndex(page, AGENTS_PATH(creds.store_id), CONNECT_CTA)@@ -102,8 +102,10 @@ test.describe('connecting an agent', () => {await expect(sheet.getByText(/ready to connect/i)).toBeVisible({ timeout: 15_000 })await sheet.getByRole('button', { name: /^done$/i }).click()- // Registered but nobody has signed in through it yet.- await expect(page.getByText(/not connected/i).first()).toBeVisible({ timeout: 15_000 })+ // Registered, but nobody has signed in through it yet.+ await expect(page.getByText(/nobody is connected through this agent/i).first()).toBeVisible({+ timeout: 15_000,+ })})})@@ -135,9 +137,7 @@ test.describe('connecting a client we do not know', () => {await expect(sheet.getByRole('tab')).toHaveCount(0)await sheet.getByRole('button', { name: /^done$/i }).click()- await expect(page.getByRole('row', { name: new RegExp(name) })).toBeVisible({- timeout: 15_000,- })+ await expect(page.getByText(name).first()).toBeVisible({ timeout: 15_000 })})})diff --git a/packages/dashboard/src/components/spree/agent-connections-card.tsx b/packages/dashboard/src/components/spree/agent-connections-card.tsxnew file mode 100644index 0000000000..2bd4aa3e37--- /dev/null+++ b/packages/dashboard/src/components/spree/agent-connections-card.tsx@@ -0,0 +1,164 @@+import type { OauthAccessToken, OauthApplication } from '@spree/admin-sdk'+import { getInitials, Subject, usePermissions } from '@spree/dashboard-core'+import {+ Avatar,+ AvatarFallback,+ AvatarImage,+ Badge,+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ RelativeTime,+ RowActions,+ Table,+ TableBody,+ TableCell,+ TableEmpty,+ TableHead,+ TableHeader,+ TableHeaderRow,+ TableRow,+ useConfirm,+} from '@spree/dashboard-ui'+import { useTranslation } from 'react-i18next'+import { useOauthApplicationTokens, useRevokeOauthToken } from '../../hooks/use-oauth'+import { ScopeList } from './api-keys/api-key-table'++interface AgentConnectionsCardProps {+ application: OauthApplication+}++/**+ * One agent and the people connected through it.+ *+ * A store registers an agent once and every staff member connects to that+ * same registration, so permissions belong to each person's connection+ * rather than to the agent — listing them per person is the only way a+ * merchant can see who holds what, and revoke one without the rest.+ */+export function AgentConnectionsCard({ application }: AgentConnectionsCardProps) {+ const { t } = useTranslation()+ const { permissions } = usePermissions()+ const { data, isLoading } = useOauthApplicationTokens(application.id)++ const connections = data?.data ?? []+ const canRevoke = permissions.can('update', Subject.OauthApplication)++ return (+ <Card>+ <CardHeader>+ {/* The count rides in the title rather than a description, so the+ header stays one row and the actions menu sits beside the name+ instead of dropping below it. */}+ <CardTitle>+ {application.name}+ <Badge variant="outline">{connections.length}</Badge>+ </CardTitle>+ </CardHeader>+ <CardContent className="p-0">+ <Table>+ <TableHeader>+ <TableHeaderRow>+ <TableHead>{t('admin.pages.settings.ai_agents.connections.person')}</TableHead>+ <TableHead>{t('admin.pages.settings.ai_agents.table.access')}</TableHead>+ <TableHead>{t('admin.pages.settings.ai_agents.connections.connected')}</TableHead>+ <TableHead className="w-12" />+ </TableHeaderRow>+ </TableHeader>+ <TableBody>+ {connections.length === 0 && !isLoading && (+ <TableEmpty colSpan={4}>+ {t('admin.pages.settings.ai_agents.connections.empty')}+ </TableEmpty>+ )}+ {connections.map((connection) => (+ <ConnectionRow+ key={connection.id}+ application={application}+ connection={connection}+ canRevoke={canRevoke}+ />+ ))}+ </TableBody>+ </Table>+ </CardContent>+ </Card>+ )+}++interface ConnectionRowProps {+ application: OauthApplication+ connection: OauthAccessToken+ canRevoke: boolean+}++function ConnectionRow({ application, connection, canRevoke }: ConnectionRowProps) {+ const { t } = useTranslation()+ const confirm = useConfirm()+ const revoke = useRevokeOauthToken(application.id)++ const owner = connection.owner+ const name =+ owner?.full_name ||+ owner?.email ||+ t('admin.pages.settings.ai_agents.connections.unknown_person')+ const who = owner?.email ?? name++ async function handleRevoke() {+ const ok = await confirm({+ title: t('admin.pages.settings.ai_agents.revoke_confirm.title'),+ message: t('admin.pages.settings.ai_agents.revoke_confirm.message', {+ name: application.name,+ who,+ }),+ variant: 'destructive',+ confirmLabel: t('admin.pages.settings.ai_agents.revoke'),+ })+ if (!ok) return++ await revoke.mutateAsync(connection.id).catch(() => undefined)+ }++ return (+ <TableRow>+ <TableCell>+ <div className="flex items-center gap-3">+ <Avatar className="size-8">+ {owner?.avatar_url && <AvatarImage src={owner.avatar_url} alt="" />}+ <AvatarFallback className="bg-muted text-xs">+ {getInitials(owner?.full_name, owner?.email ?? '?')}+ </AvatarFallback>+ </Avatar>+ <div className="flex flex-col leading-tight">+ <span className="font-medium text-foreground">{name}</span>+ {owner?.full_name && owner.email && (+ <span className="text-muted-foreground text-xs">{owner.email}</span>+ )}+ </div>+ </div>+ </TableCell>+ <TableCell>+ <ScopeList scopes={connection.scopes} previewCount={2} />+ </TableCell>+ <TableCell className="text-muted-foreground text-sm">+ <RelativeTime iso={connection.created_at} />+ </TableCell>+ <TableCell className="text-right">+ {canRevoke && (+ <RowActions+ actions={[+ {+ key: 'revoke',+ label: t('admin.pages.settings.ai_agents.revoke'),+ destructive: true,+ disabled: revoke.isPending,+ onSelect: handleRevoke,+ },+ ]}+ />+ )}+ </TableCell>+ </TableRow>+ )+}diff --git a/packages/dashboard/src/components/spree/api-keys/api-key-table.tsx b/packages/dashboard/src/components/spree/api-keys/api-key-table.tsxindex f09e69fe6b..f510224d16 100644--- a/packages/dashboard/src/components/spree/api-keys/api-key-table.tsx+++ b/packages/dashboard/src/components/spree/api-keys/api-key-table.tsx@@ -318,7 +318,14 @@ function ApiKeyRow({// usual table widths.const SCOPE_PREVIEW_COUNT = 3-export function ScopeList({ scopes }: { scopes: string[] }) {+export function ScopeList({+ scopes,+ previewCount = SCOPE_PREVIEW_COUNT,+}: {+ scopes: string[]+ /** How many chips to show inline. Lower it where the row is tighter. */+ previewCount?: number+}) {const { t } = useTranslation()const { data: catalog } = usePermissionCatalog()@@ -335,8 +342,8 @@ export function ScopeList({ scopes }: { scopes: string[] }) {return <span className="text-sm text-muted-foreground">—</span>}- const preview = scopes.slice(0, SCOPE_PREVIEW_COUNT)- const overflow = scopes.slice(SCOPE_PREVIEW_COUNT)+ const preview = scopes.slice(0, previewCount)+ const overflow = scopes.slice(previewCount)return (<div className="flex max-w-xs flex-wrap items-center gap-1">diff --git a/packages/dashboard/src/hooks/use-oauth.ts b/packages/dashboard/src/hooks/use-oauth.tsindex df0cb83691..f3fdeae35a 100644--- a/packages/dashboard/src/hooks/use-oauth.ts+++ b/packages/dashboard/src/hooks/use-oauth.ts@@ -63,10 +63,26 @@ export function useDeleteOauthApplication() {})}-export function useRevokeOauthApplication() {+/**+ * The people connected through one registered client. A store registers a+ * client once and everyone connects to that same registration, so this is+ * who actually holds access.+ */+export function useOauthApplicationTokens(applicationId: string | undefined) {+ return useQuery({+ queryKey: useResourceKey('oauth-application-tokens', applicationId ?? ''),+ queryFn: () =>+ adminClient.oauth.applications.tokens.list(applicationId as string, {+ expand: ['owner'],+ }),+ enabled: Boolean(applicationId),+ })+}++export function useRevokeOauthToken(applicationId: string) {return useResourceMutation<void, Error, string>({- mutationFn: (id) => adminClient.oauth.applications.revoke(id),- invalidate: [['oauth-applications']],+ mutationFn: (id) => adminClient.oauth.applications.tokens.delete(applicationId, id),+ invalidate: [['oauth-applications'], ['oauth-application-tokens']],successMessage: false,// A failed revoke has no inline form to report into, and the row simply// staying put reads as success — so this one does toast.diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 6711942faf..9671f656ff 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -4132,30 +4132,32 @@"communication_title": "التواصل","commission_tax_title": "الضريبة على العمولة"},- "connected_apps": {- "title": "الوكلاء المتصلون",- "subtitle": "وكلاء الذكاء الاصطناعي الذين منحهم أحد أعضاء الفريق حق الوصول إلى هذا المتجر. يسري الإلغاء فورًا.",+ "ai_agents": {+ "title": "وكلاء الذكاء الاصطناعي",+ "subtitle": "وكلاء الذكاء الاصطناعي المتصلون بمتجرك. اربط Claude و ChatGPT وغيرهما لإدارة متجرك","empty": "لم يتم ربط أي وكيل بعد.","revoke": "إلغاء الوصول","table": {- "name": "الوكيل","access": "الوصول",- "authorized_by": "وافق عليه",- "last_authorized": "آخر تفويض","status": "الحالة"},"revoke_confirm": {"title": "إلغاء الوصول؟",- "message": "سيتوقف {{name}} عن العمل فورًا. وسيحتاج أي شخص يستخدمه إلى الاتصال من جديد."+ "message": "سيفقد {{who}} الوصول إلى {{name}} فورًا. ويبقى الآخرون متصلين."},- "status": {- "connected": "متصل",- "not_connected": "غير متصل"+ "manage_connections": "إدارة الاتصالات",+ "connections": {+ "person": "الشخص",+ "empty": "لا أحد متصل عبر هذا الوكيل.",+ "unknown_person": "غير معروف",+ "count_one": "شخص واحد متصل",+ "count_other": "{{count}} أشخاص متصلون",+ "connected": "متصل"}},"oauth_clients": {"title": "عملاء OAuth",- "subtitle": "عملاء OAuth المسجّلون لهذا المتجر. يتم الربط من صفحة الوكلاء المتصلين.",+ "subtitle": "عملاء OAuth المسجلون لهذا المتجر","empty": "لم يُسجَّل أي عميل بعد.","register": "تسجيل عميل","table": {@@ -5234,7 +5236,7 @@"package_types": "صناديق وكراتين ومنصات وحاويات","suppliers": "من تشتري منه المخزون، وكيفية التواصل معه","marketplace": "مدفوعات البائعين، والموافقة على البائعين، ورسائل البائعين، والضريبة على العمولة",- "connected_apps": "وكلاء الذكاء الاصطناعي الذين لديهم حق الوصول إلى هذا المتجر",+ "ai_agents": "وكلاء الذكاء الاصطناعي الذين لديهم حق الوصول إلى هذا المتجر","oauth_clients": "تسجيل عملاء OAuth وتهيئتهم"},"groups": {@@ -5274,7 +5276,7 @@"package_types": "أنواع التغليف","suppliers": "الموردون","marketplace": "الإعدادات",- "connected_apps": "الوكلاء المتصلون",+ "ai_agents": "وكلاء الذكاء الاصطناعي","oauth_clients": "عملاء OAuth"},"breadcrumbs": {diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex fe6b4a9001..b932f0879c 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -4104,30 +4104,32 @@"communication_title": "Kommunikation","commission_tax_title": "Steuer auf Provision"},- "connected_apps": {- "title": "Verbundene Agenten",- "subtitle": "KI-Agenten, denen ein Teammitglied Zugriff auf diesen Shop gegeben hat. Der Widerruf gilt sofort.",+ "ai_agents": {+ "title": "KI-Agenten",+ "subtitle": "KI-Agenten, die mit Ihrem Store verbunden sind. Verbinden Sie Claude, ChatGPT und andere, um Ihren Store zu verwalten","empty": "Es wurden noch keine Agenten verbunden.","revoke": "Zugriff widerrufen","table": {- "name": "Agent","access": "Zugriff",- "authorized_by": "Genehmigt von",- "last_authorized": "Letzte Autorisierung","status": "Status"},"revoke_confirm": {"title": "Zugriff widerrufen?",- "message": "{{name}} funktioniert ab sofort nicht mehr. Wer es nutzt, muss sich erneut verbinden."+ "message": "{{who}} verliert sofort den Zugriff auf {{name}}. Alle anderen bleiben verbunden."},- "status": {- "connected": "Verbunden",- "not_connected": "Nicht verbunden"+ "manage_connections": "Verbindungen verwalten",+ "connections": {+ "person": "Person",+ "empty": "Niemand ist über diesen Agenten verbunden.",+ "unknown_person": "Unbekannt",+ "count_one": "{{count}} Person verbunden",+ "count_other": "{{count}} Personen verbunden",+ "connected": "Verbunden"}},"oauth_clients": {"title": "OAuth-Clients",- "subtitle": "Die für diesen Shop registrierten OAuth-Clients. Verbunden werden sie unter „Verbundene Agenten“.",+ "subtitle": "Die für diesen Store registrierten OAuth-Clients","empty": "Noch keine Clients registriert.","register": "Client registrieren","table": {@@ -5201,7 +5203,7 @@"package_types": "Kartons, Paletten und Container","suppliers": "Von wem Sie Ware einkaufen und wie Sie sie erreichen","marketplace": "Auszahlungen, Verkäuferfreigabe, Verkäufer-E-Mails und Steuer auf Provision",- "connected_apps": "KI-Agenten mit Zugriff auf diesen Shop",+ "ai_agents": "KI-Agenten mit Zugriff auf diesen Shop","oauth_clients": "OAuth-Clients registrieren und konfigurieren"},"groups": {@@ -5241,7 +5243,7 @@"package_types": "Verpackungsarten","suppliers": "Lieferanten","marketplace": "Einstellungen",- "connected_apps": "Verbundene Agenten",+ "ai_agents": "KI-Agenten","oauth_clients": "OAuth-Clients"},"breadcrumbs": {diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 1ea348239d..e4b04b8d32 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -4104,30 +4104,32 @@"communication_title": "Communication","commission_tax_title": "Commission tax"},- "connected_apps": {- "title": "Connected agents",- "subtitle": "AI agents a team member has given access to this store. Revoking takes effect immediately.",+ "ai_agents": {+ "title": "AI Agents",+ "subtitle": "AI agents connected to your store. Connect Claude, ChatGPT and others to manage your store","empty": "No agents have been connected yet.","revoke": "Revoke access","table": {- "name": "Agent","access": "Access",- "authorized_by": "Approved by",- "last_authorized": "Last authorized","status": "Status"},"revoke_confirm": {"title": "Revoke access?",- "message": "{{name}} will stop working immediately. Anyone using it will need to connect again."+ "message": "{{who}} will lose access to {{name}} immediately. Everyone else stays connected."},- "status": {- "connected": "Connected",- "not_connected": "Not connected"+ "manage_connections": "Manage connections",+ "connections": {+ "person": "Person",+ "empty": "Nobody is connected through this agent.",+ "unknown_person": "Unknown",+ "count_one": "{{count}} person connected",+ "count_other": "{{count}} people connected",+ "connected": "Connected"}},"oauth_clients": {"title": "OAuth clients",- "subtitle": "The OAuth clients registered against this store. A merchant connects one from Connected agents.",+ "subtitle": "The OAuth clients registered against this store","empty": "No clients registered yet.","register": "Register a client","table": {@@ -5201,7 +5203,7 @@"package_types": "Boxes, cartons, pallets and containers","suppliers": "Who you buy stock from, and how to reach them","marketplace": "Seller payouts, seller approval, seller emails and commission tax",- "connected_apps": "AI agents with access to this store",+ "ai_agents": "AI agents with access to this store","oauth_clients": "Register and configure OAuth clients"},"groups": {@@ -5241,7 +5243,7 @@"package_types": "Package types","suppliers": "Suppliers","marketplace": "Settings",- "connected_apps": "Connected agents",+ "ai_agents": "AI Agents","oauth_clients": "OAuth clients"},"breadcrumbs": {diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.jsonindex a9c46221ec..c87ab58a8c 100644--- a/packages/dashboard/src/locales/es.json+++ b/packages/dashboard/src/locales/es.json@@ -720,30 +720,32 @@"communication_title": "Comunicación","commission_tax_title": "Impuesto sobre la comisión"},- "connected_apps": {- "title": "Agentes conectados",- "subtitle": "Agentes de IA a los que un miembro del equipo ha dado acceso a esta tienda. La revocación surte efecto de inmediato.",+ "ai_agents": {+ "title": "Agentes de IA",+ "subtitle": "Agentes de IA conectados a tu tienda. Conecta Claude, ChatGPT y otros para gestionar tu tienda","empty": "Aún no se ha conectado ningún agente.","revoke": "Revocar acceso","table": {- "name": "Agente","access": "Acceso",- "authorized_by": "Aprobado por",- "last_authorized": "Última autorización","status": "Estado"},"revoke_confirm": {"title": "¿Revocar el acceso?",- "message": "{{name}} dejará de funcionar de inmediato. Quien lo use tendrá que conectarse de nuevo."+ "message": "{{who}} perderá el acceso a {{name}} de inmediato. El resto sigue conectado."},- "status": {- "connected": "Conectado",- "not_connected": "No conectado"+ "manage_connections": "Gestionar conexiones",+ "connections": {+ "person": "Persona",+ "empty": "Nadie está conectado mediante este agente.",+ "unknown_person": "Desconocido",+ "count_one": "{{count}} persona conectada",+ "count_other": "{{count}} personas conectadas",+ "connected": "Conectado"}},"oauth_clients": {"title": "Clientes OAuth",- "subtitle": "Los clientes OAuth registrados en esta tienda. La conexión se hace desde Agentes conectados.",+ "subtitle": "Los clientes OAuth registrados para esta tienda","empty": "Aún no hay clientes registrados.","register": "Registrar un cliente","table": {@@ -4272,7 +4274,7 @@"package_types": "Cajas, cajones, palets y contenedores","suppliers": "A quién le comprás stock y cómo contactarlos","marketplace": "Pagos a vendedores, aprobación de vendedores, correos a vendedores e impuesto sobre la comisión",- "connected_apps": "Agentes de IA con acceso a esta tienda",+ "ai_agents": "Agentes de IA con acceso a esta tienda","oauth_clients": "Registrar y configurar clientes OAuth"},"groups": {@@ -4312,7 +4314,7 @@"package_types": "Tipos de empaque","suppliers": "Proveedores","marketplace": "Configuración",- "connected_apps": "Agentes conectados",+ "ai_agents": "Agentes de IA","oauth_clients": "Clientes OAuth"},"breadcrumbs": {diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 8e1ce6129d..cabe4bbfa6 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -4104,30 +4104,32 @@"communication_title": "Communication","commission_tax_title": "Taxe sur la commission"},- "connected_apps": {- "title": "Agents connectés",- "subtitle": "Agents IA auxquels un membre de l'équipe a donné accès à cette boutique. La révocation prend effet immédiatement.",+ "ai_agents": {+ "title": "Agents IA",+ "subtitle": "Agents IA connectés à votre boutique. Connectez Claude, ChatGPT et d'autres pour gérer votre boutique","empty": "Aucun agent n'a encore été connecté.","revoke": "Révoquer l’accès","table": {- "name": "Agent","access": "Accès",- "authorized_by": "Autorisé par",- "last_authorized": "Dernière autorisation","status": "Statut"},"revoke_confirm": {"title": "Révoquer l’accès ?",- "message": "{{name}} cessera de fonctionner immédiatement. Toute personne qui l’utilise devra se connecter à nouveau."+ "message": "{{who}} perdra immédiatement l'accès à {{name}}. Les autres restent connectés."},- "status": {- "connected": "Connecté",- "not_connected": "Non connecté"+ "manage_connections": "Gérer les connexions",+ "connections": {+ "person": "Personne",+ "empty": "Personne n'est connecté via cet agent.",+ "unknown_person": "Inconnu",+ "count_one": "{{count}} personne connectée",+ "count_other": "{{count}} personnes connectées",+ "connected": "Connecté"}},"oauth_clients": {"title": "Clients OAuth",- "subtitle": "Les clients OAuth enregistrés pour cette boutique. La connexion se fait depuis Agents connectés.",+ "subtitle": "Les clients OAuth enregistrés pour cette boutique","empty": "Aucun client enregistré.","register": "Enregistrer un client","table": {@@ -5201,7 +5203,7 @@"package_types": "Cartons, palettes et conteneurs","suppliers": "À qui vous achetez votre stock, et comment les joindre","marketplace": "Paiements, validation des vendeurs, e-mails vendeurs et taxe sur la commission",- "connected_apps": "Agents IA ayant accès à cette boutique",+ "ai_agents": "Agents IA ayant accès à cette boutique","oauth_clients": "Enregistrer et configurer des clients OAuth"},"groups": {@@ -5241,7 +5243,7 @@"package_types": "Types d'emballage","suppliers": "Fournisseurs","marketplace": "Paramètres",- "connected_apps": "Agents connectés",+ "ai_agents": "Agents IA","oauth_clients": "Clients OAuth"},"breadcrumbs": {diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex c6fe42241b..b1c825b20d 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -4158,30 +4158,32 @@"communication_title": "Komunikacja","commission_tax_title": "Podatek od prowizji"},- "connected_apps": {- "title": "Połączone agenty",- "subtitle": "Agenty AI, którym członek zespołu dał dostęp do tego sklepu. Cofnięcie dostępu działa natychmiast.",+ "ai_agents": {+ "title": "Agenci AI",+ "subtitle": "Agenci AI połączeni z Twoim sklepem. Podłącz Claude, ChatGPT i innych, aby zarządzać sklepem","empty": "Nie połączono jeszcze żadnego agenta.","revoke": "Odbierz dostęp","table": {- "name": "Agent","access": "Dostęp",- "authorized_by": "Zatwierdzone przez",- "last_authorized": "Ostatnia autoryzacja","status": "Status"},"revoke_confirm": {"title": "Odebrać dostęp?",- "message": "{{name}} przestanie działać natychmiast. Każdy, kto z niej korzysta, będzie musiał połączyć się ponownie."+ "message": "{{who}} natychmiast straci dostęp do {{name}}. Pozostali pozostaną połączeni."},- "status": {- "connected": "Połączony",- "not_connected": "Niepołączony"+ "manage_connections": "Zarządzaj połączeniami",+ "connections": {+ "person": "Osoba",+ "empty": "Nikt nie jest połączony przez tego agenta.",+ "unknown_person": "Nieznany",+ "count_one": "{{count}} połączona osoba",+ "count_other": "{{count}} połączonych osób",+ "connected": "Połączono"}},"oauth_clients": {"title": "Klienci OAuth",- "subtitle": "Klienci OAuth zarejestrowani w tym sklepie. Połączenie nawiązuje się w Połączonych agentach.",+ "subtitle": "Klienci OAuth zarejestrowani dla tego sklepu","empty": "Nie zarejestrowano jeszcze żadnego klienta.","register": "Zarejestruj klienta","table": {@@ -5265,7 +5267,7 @@"package_types": "Kartony, palety i kontenery","suppliers": "Od kogo kupujesz towar i jak się z nimi skontaktować","marketplace": "Wypłaty, zatwierdzanie sprzedawców, e-maile do sprzedawców i podatek od prowizji",- "connected_apps": "Agenty AI z dostępem do tego sklepu",+ "ai_agents": "Agenty AI z dostępem do tego sklepu","oauth_clients": "Rejestrowanie i konfiguracja klientów OAuth"},"groups": {@@ -5305,7 +5307,7 @@"package_types": "Rodzaje opakowań","suppliers": "Dostawcy","marketplace": "Ustawienia",- "connected_apps": "Połączone agenty",+ "ai_agents": "Agenci AI","oauth_clients": "Klienci OAuth"},"breadcrumbs": {diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex f33279e175..fe89b4cce7 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -4094,30 +4094,32 @@"communication_title": "沟通","commission_tax_title": "佣金税"},- "connected_apps": {- "title": "已连接的代理",- "subtitle": "团队成员授予此店铺访问权限的 AI 代理。撤销立即生效。",+ "ai_agents": {+ "title": "AI 代理",+ "subtitle": "已连接到您商店的 AI 代理。连接 Claude、ChatGPT 等来管理您的商店","empty": "尚未连接任何代理。","revoke": "撤销访问权限","table": {- "name": "代理","access": "访问权限",- "authorized_by": "批准人",- "last_authorized": "最后授权时间","status": "状态"},"revoke_confirm": {"title": "撤销访问权限?",- "message": "{{name}} 将立即停止工作。使用它的人需要重新连接。"+ "message": "{{who}} 将立即失去对 {{name}} 的访问权限。其他人仍保持连接。"},- "status": {- "connected": "已连接",- "not_connected": "未连接"+ "manage_connections": "管理连接",+ "connections": {+ "person": "成员",+ "empty": "尚无人通过此代理连接。",+ "unknown_person": "未知",+ "count_one": "已连接 {{count}} 人",+ "count_other": "已连接 {{count}} 人",+ "connected": "连接时间"}},"oauth_clients": {"title": "OAuth 客户端",- "subtitle": "已在此店铺注册的 OAuth 客户端。连接请在“已连接的代理”中完成。",+ "subtitle": "为此商店注册的 OAuth 客户端","empty": "尚未注册任何客户端。","register": "注册客户端","table": {@@ -5190,7 +5192,7 @@"package_types": "纸箱、外箱、托盘与集装箱","suppliers": "你从谁那里采购库存,以及如何联系他们","marketplace": "卖家付款、卖家审核、卖家邮件与佣金税",- "connected_apps": "有权访问此店铺的 AI 代理",+ "ai_agents": "有权访问此店铺的 AI 代理","oauth_clients": "注册并配置 OAuth 客户端"},"groups": {@@ -5230,7 +5232,7 @@"package_types": "包装类型","suppliers": "供应商","marketplace": "设置",- "connected_apps": "已连接的代理",+ "ai_agents": "AI 代理","oauth_clients": "OAuth 客户端"},"breadcrumbs": {diff --git a/packages/dashboard/src/nav/settings.ts b/packages/dashboard/src/nav/settings.tsindex b3a356f22a..54db79d6c4 100644--- a/packages/dashboard/src/nav/settings.ts+++ b/packages/dashboard/src/nav/settings.ts@@ -109,6 +109,18 @@ settingsNav.add({subject: Subject.Policy,})+settingsNav.add({+ key: 'settings.ai-agents',+ labelKey: 'admin.settings_nav.items.ai_agents',+ descriptionKey: 'admin.settings_nav.descriptions.ai_agents',+ keywords: ['oauth', 'agents', 'mcp', 'claude', 'assistant', 'integrations', 'revoke'],+ path: '/ai-agents',+ icon: BotIcon,+ group: 'store',+ position: 260,+ subject: Subject.OauthApplication,+})+settingsNav.add({key: 'settings.channels',labelKey: 'admin.settings_nav.items.channels',@@ -343,18 +355,6 @@ settingsNav.add({subject: Subject.ApiKey,})-settingsNav.add({- key: 'settings.connected-apps',- labelKey: 'admin.settings_nav.items.connected_apps',- descriptionKey: 'admin.settings_nav.descriptions.connected_apps',- keywords: ['oauth', 'agents', 'mcp', 'integrations', 'revoke'],- path: '/connected-apps',- icon: BotIcon,- group: 'developer',- position: 150,- subject: Subject.OauthApplication,-})-settingsNav.add({key: 'settings.oauth_clients',labelKey: 'admin.settings_nav.items.oauth_clients',diff --git a/packages/dashboard/src/routeTree.gen.ts b/packages/dashboard/src/routeTree.gen.tsindex c51492e6f5..8ae9cad411 100644--- a/packages/dashboard/src/routeTree.gen.ts+++ b/packages/dashboard/src/routeTree.gen.ts@@ -57,11 +57,11 @@ import { Route as SellersSellerIdRouteImport } from './routes/_authenticated/$stimport { Route as SellersCommissionRatesRouteImport } from './routes/_authenticated/$storeId/sellers/commission-rates'import { Route as SellersTransfersRouteImport } from './routes/_authenticated/$storeId/sellers/transfers'import { Route as SettingsIndexRouteImport } from './routes/_authenticated/$storeId/settings/index'+import { Route as SettingsAiAgentsRouteImport } from './routes/_authenticated/$storeId/settings/ai-agents'import { Route as SettingsAllowedOriginsRouteImport } from './routes/_authenticated/$storeId/settings/allowed-origins'import { Route as SettingsApiKeysRouteImport } from './routes/_authenticated/$storeId/settings/api-keys'import { Route as SettingsChannelsRouteImport } from './routes/_authenticated/$storeId/settings/channels'import { Route as SettingsCommissionRatesRouteImport } from './routes/_authenticated/$storeId/settings/commission-rates'-import { Route as SettingsConnectedAppsRouteImport } from './routes/_authenticated/$storeId/settings/connected-apps'import { Route as SettingsCustomFieldDefinitionsRouteImport } from './routes/_authenticated/$storeId/settings/custom-field-definitions'import { Route as SettingsIntegrationsRouteImport } from './routes/_authenticated/$storeId/settings/integrations'import { Route as SettingsMarketplaceRouteImport } from './routes/_authenticated/$storeId/settings/marketplace'@@ -352,6 +352,11 @@ const SettingsIndexRoute = SettingsIndexRouteImport.update({path: '/',getParentRoute: () => SettingsRoute,} as any)+const SettingsAiAgentsRoute = SettingsAiAgentsRouteImport.update({+ id: '/ai-agents',+ path: '/ai-agents',+ getParentRoute: () => SettingsRoute,+} as any)const SettingsAllowedOriginsRoute = SettingsAllowedOriginsRouteImport.update({id: '/allowed-origins',path: '/allowed-origins',@@ -372,11 +377,6 @@ const SettingsCommissionRatesRoute = SettingsCommissionRatesRouteImport.update({path: '/commission-rates',getParentRoute: () => SettingsRoute,} as any)-const SettingsConnectedAppsRoute = SettingsConnectedAppsRouteImport.update({- id: '/connected-apps',- path: '/connected-apps',- getParentRoute: () => SettingsRoute,-} as any)const SettingsCustomFieldDefinitionsRoute =SettingsCustomFieldDefinitionsRouteImport.update({id: '/custom-field-definitions',@@ -678,11 +678,11 @@ export interface FileRoutesByFullPath {'/$storeId/sellers/$sellerId': typeof SellersSellerIdRoute'/$storeId/sellers/commission-rates': typeof SellersCommissionRatesRoute'/$storeId/sellers/transfers': typeof SellersTransfersRoute+ '/$storeId/settings/ai-agents': typeof SettingsAiAgentsRoute'/$storeId/settings/allowed-origins': typeof SettingsAllowedOriginsRoute'/$storeId/settings/api-keys': typeof SettingsApiKeysRoute'/$storeId/settings/channels': typeof SettingsChannelsRoute'/$storeId/settings/commission-rates': typeof SettingsCommissionRatesRoute- '/$storeId/settings/connected-apps': typeof SettingsConnectedAppsRoute'/$storeId/settings/custom-field-definitions': typeof SettingsCustomFieldDefinitionsRoute'/$storeId/settings/integrations': typeof SettingsIntegrationsRoute'/$storeId/settings/marketplace': typeof SettingsMarketplaceRoute@@ -779,11 +779,11 @@ export interface FileRoutesByTo {'/$storeId/sellers/$sellerId': typeof SellersSellerIdRoute'/$storeId/sellers/commission-rates': typeof SellersCommissionRatesRoute'/$storeId/sellers/transfers': typeof SellersTransfersRoute+ '/$storeId/settings/ai-agents': typeof SettingsAiAgentsRoute'/$storeId/settings/allowed-origins': typeof SettingsAllowedOriginsRoute'/$storeId/settings/api-keys': typeof SettingsApiKeysRoute'/$storeId/settings/channels': typeof SettingsChannelsRoute'/$storeId/settings/commission-rates': typeof SettingsCommissionRatesRoute- '/$storeId/settings/connected-apps': typeof SettingsConnectedAppsRoute'/$storeId/settings/custom-field-definitions': typeof SettingsCustomFieldDefinitionsRoute'/$storeId/settings/integrations': typeof SettingsIntegrationsRoute'/$storeId/settings/marketplace': typeof SettingsMarketplaceRoute@@ -884,11 +884,11 @@ export interface FileRoutesById {'/_authenticated/$storeId/sellers/$sellerId': typeof SellersSellerIdRoute'/_authenticated/$storeId/sellers/commission-rates': typeof SellersCommissionRatesRoute'/_authenticated/$storeId/sellers/transfers': typeof SellersTransfersRoute+ '/_authenticated/$storeId/settings/ai-agents': typeof SettingsAiAgentsRoute'/_authenticated/$storeId/settings/allowed-origins': typeof SettingsAllowedOriginsRoute'/_authenticated/$storeId/settings/api-keys': typeof SettingsApiKeysRoute'/_authenticated/$storeId/settings/channels': typeof SettingsChannelsRoute'/_authenticated/$storeId/settings/commission-rates': typeof SettingsCommissionRatesRoute- '/_authenticated/$storeId/settings/connected-apps': typeof SettingsConnectedAppsRoute'/_authenticated/$storeId/settings/custom-field-definitions': typeof SettingsCustomFieldDefinitionsRoute'/_authenticated/$storeId/settings/integrations': typeof SettingsIntegrationsRoute'/_authenticated/$storeId/settings/marketplace': typeof SettingsMarketplaceRoute@@ -989,11 +989,11 @@ export interface FileRouteTypes {| '/$storeId/sellers/$sellerId'| '/$storeId/sellers/commission-rates'| '/$storeId/sellers/transfers'+ | '/$storeId/settings/ai-agents'| '/$storeId/settings/allowed-origins'| '/$storeId/settings/api-keys'| '/$storeId/settings/channels'| '/$storeId/settings/commission-rates'- | '/$storeId/settings/connected-apps'| '/$storeId/settings/custom-field-definitions'| '/$storeId/settings/integrations'| '/$storeId/settings/marketplace'@@ -1090,11 +1090,11 @@ export interface FileRouteTypes {| '/$storeId/sellers/$sellerId'| '/$storeId/sellers/commission-rates'| '/$storeId/sellers/transfers'+ | '/$storeId/settings/ai-agents'| '/$storeId/settings/allowed-origins'| '/$storeId/settings/api-keys'| '/$storeId/settings/channels'| '/$storeId/settings/commission-rates'- | '/$storeId/settings/connected-apps'| '/$storeId/settings/custom-field-definitions'| '/$storeId/settings/integrations'| '/$storeId/settings/marketplace'@@ -1194,11 +1194,11 @@ export interface FileRouteTypes {| '/_authenticated/$storeId/sellers/$sellerId'| '/_authenticated/$storeId/sellers/commission-rates'| '/_authenticated/$storeId/sellers/transfers'+ | '/_authenticated/$storeId/settings/ai-agents'| '/_authenticated/$storeId/settings/allowed-origins'| '/_authenticated/$storeId/settings/api-keys'| '/_authenticated/$storeId/settings/channels'| '/_authenticated/$storeId/settings/commission-rates'- | '/_authenticated/$storeId/settings/connected-apps'| '/_authenticated/$storeId/settings/custom-field-definitions'| '/_authenticated/$storeId/settings/integrations'| '/_authenticated/$storeId/settings/marketplace'@@ -1607,6 +1607,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SettingsIndexRouteImportparentRoute: typeof SettingsRoute}+ '/_authenticated/$storeId/settings/ai-agents': {+ id: '/_authenticated/$storeId/settings/ai-agents'+ path: '/ai-agents'+ fullPath: '/$storeId/settings/ai-agents'+ preLoaderRoute: typeof SettingsAiAgentsRouteImport+ parentRoute: typeof SettingsRoute+ }'/_authenticated/$storeId/settings/allowed-origins': {id: '/_authenticated/$storeId/settings/allowed-origins'path: '/allowed-origins'@@ -1635,13 +1642,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SettingsCommissionRatesRouteImportparentRoute: typeof SettingsRoute}- '/_authenticated/$storeId/settings/connected-apps': {- id: '/_authenticated/$storeId/settings/connected-apps'- path: '/connected-apps'- fullPath: '/$storeId/settings/connected-apps'- preLoaderRoute: typeof SettingsConnectedAppsRouteImport- parentRoute: typeof SettingsRoute- }'/_authenticated/$storeId/settings/custom-field-definitions': {id: '/_authenticated/$storeId/settings/custom-field-definitions'path: '/custom-field-definitions'@@ -1989,11 +1989,11 @@ declare module '@tanstack/react-router' {}interface SettingsRouteChildren {+ SettingsAiAgentsRoute: typeof SettingsAiAgentsRouteSettingsAllowedOriginsRoute: typeof SettingsAllowedOriginsRouteSettingsApiKeysRoute: typeof SettingsApiKeysRouteSettingsChannelsRoute: typeof SettingsChannelsRouteSettingsCommissionRatesRoute: typeof SettingsCommissionRatesRoute- SettingsConnectedAppsRoute: typeof SettingsConnectedAppsRouteSettingsCustomFieldDefinitionsRoute: typeof SettingsCustomFieldDefinitionsRouteSettingsIntegrationsRoute: typeof SettingsIntegrationsRouteSettingsMarketplaceRoute: typeof SettingsMarketplaceRoute@@ -2026,11 +2026,11 @@ interface SettingsRouteChildren {}const SettingsRouteChildren: SettingsRouteChildren = {+ SettingsAiAgentsRoute: SettingsAiAgentsRoute,SettingsAllowedOriginsRoute: SettingsAllowedOriginsRoute,SettingsApiKeysRoute: SettingsApiKeysRoute,SettingsChannelsRoute: SettingsChannelsRoute,SettingsCommissionRatesRoute: SettingsCommissionRatesRoute,- SettingsConnectedAppsRoute: SettingsConnectedAppsRoute,SettingsCustomFieldDefinitionsRoute: SettingsCustomFieldDefinitionsRoute,SettingsIntegrationsRoute: SettingsIntegrationsRoute,SettingsMarketplaceRoute: SettingsMarketplaceRoute,diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/ai-agents.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/ai-agents.tsxnew file mode 100644index 0000000000..6a103f0586--- /dev/null+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/ai-agents.tsx@@ -0,0 +1,46 @@+import { PageHeader } from '@spree/dashboard-core'+import { Button, Empty, Skeleton } from '@spree/dashboard-ui'+import { createFileRoute } from '@tanstack/react-router'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { AgentConnectionsCard } from '../../../../components/spree/agent-connections-card'+import { McpConnectSheet } from '../../../../components/spree/mcp-connect-sheet'+import { useOauthApplications } from '../../../../hooks/use-oauth'++export const Route = createFileRoute('/_authenticated/$storeId/settings/ai-agents')({+ component: AiAgentsSettingsPage,+})++function AiAgentsSettingsPage() {+ const { t } = useTranslation()+ const { data, isLoading } = useOauthApplications()+ const [connectOpen, setConnectOpen] = useState(false)++ const applications = data?.data ?? []++ return (+ <div className="flex flex-col gap-6">+ <PageHeader+ title={t('admin.pages.settings.ai_agents.title')}+ description={t('admin.pages.settings.ai_agents.subtitle')}+ actions={+ <Button size="sm" onClick={() => setConnectOpen(true)}>+ {t('admin.mcp_connect.open_cta')}+ </Button>+ }+ />++ <McpConnectSheet open={connectOpen} onOpenChange={setConnectOpen} />++ {isLoading && <Skeleton className="h-48 w-full" />}++ {!isLoading && applications.length === 0 && (+ <Empty>{t('admin.pages.settings.ai_agents.empty')}</Empty>+ )}++ {applications.map((application) => (+ <AgentConnectionsCard key={application.id} application={application} />+ ))}+ </div>+ )+}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/connected-apps.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/connected-apps.tsxdeleted file mode 100644index 87d8ca0c0c..0000000000--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/connected-apps.tsx+++ /dev/null@@ -1,84 +0,0 @@-import type { OauthApplication } from '@spree/admin-sdk'-import {- adminClient,- PageHeader,- ResourceTable,- resourceSearchSchema,- Subject,- usePermissions,-} from '@spree/dashboard-core'-import { Button, RowActions, useConfirm } from '@spree/dashboard-ui'-import { createFileRoute } from '@tanstack/react-router'-import { useState } from 'react'-import { useTranslation } from 'react-i18next'-import { McpConnectSheet } from '../../../../components/spree/mcp-connect-sheet'-import { useRevokeOauthApplication } from '../../../../hooks/use-oauth'-import '../../../../tables/oauth-applications'--export const Route = createFileRoute('/_authenticated/$storeId/settings/connected-apps')({- validateSearch: resourceSearchSchema,- component: ConnectedAppsSettingsPage,-})--function ConnectedAppsSettingsPage() {- const { t } = useTranslation()- const search = Route.useSearch()- const confirm = useConfirm()- const revoke = useRevokeOauthApplication()- const { permissions } = usePermissions()- const [connectOpen, setConnectOpen] = useState(false)-- async function handleRevoke(application: OauthApplication) {- const ok = await confirm({- title: t('admin.pages.settings.connected_apps.revoke_confirm.title'),- message: t('admin.pages.settings.connected_apps.revoke_confirm.message', {- name: application.name,- }),- variant: 'destructive',- confirmLabel: t('admin.pages.settings.connected_apps.revoke'),- })- if (!ok) return-- await revoke.mutateAsync(application.id).catch(() => undefined)- }-- return (- <div className="flex flex-col gap-6">- <PageHeader- title={t('admin.pages.settings.connected_apps.title')}- description={t('admin.pages.settings.connected_apps.subtitle')}- actions={- <Button size="sm" onClick={() => setConnectOpen(true)}>- {t('admin.mcp_connect.open_cta')}- </Button>- }- />-- <McpConnectSheet open={connectOpen} onOpenChange={setConnectOpen} />-- <ResourceTable<OauthApplication>- tableKey="oauth-applications"- queryKey="oauth-applications"- hideHeader- queryFn={(params) => adminClient.oauth.applications.list(params)}- searchParams={search}- rowActions={(application) => (- <RowActions- actions={[- {- key: 'revoke',- label: t('admin.pages.settings.connected_apps.revoke'),- destructive: true,- // Nothing to revoke on a registration nobody has connected.- visible:- application.connected && permissions.can('update', Subject.OauthApplication),- disabled: revoke.isPending,- onSelect: () => handleRevoke(application),- },- ]}- />- )}- />- </div>- )-}diff --git a/packages/dashboard/src/tables/oauth-applications.tsx b/packages/dashboard/src/tables/oauth-applications.tsxdeleted file mode 100644index 17a457a17d..0000000000--- a/packages/dashboard/src/tables/oauth-applications.tsx+++ /dev/null@@ -1,71 +0,0 @@-import type { OauthApplication } from '@spree/admin-sdk'-import { defineTable } from '@spree/dashboard-core'-import { RelativeTime, ResourceNameCell, StatusBadge } from '@spree/dashboard-ui'-import { PlugIcon } from '@spree/dashboard-ui/icons'-import i18n from 'i18next'-import { ScopeList } from '../components/spree/api-keys/api-key-table'--defineTable<OauthApplication>('oauth-applications', {- title: i18n.t('admin.settings_nav.items.connected_apps'),- description: i18n.t('admin.pages.settings.connected_apps.subtitle'),- emptyIcon: <PlugIcon className="size-8 text-muted-foreground" />,- emptyMessage: i18n.t('admin.pages.settings.connected_apps.empty'),- columns: [- {- key: 'name',- label: i18n.t('admin.pages.settings.connected_apps.table.name'),- default: true,- render: (application) => <ResourceNameCell id={application.id} name={application.name} />,- },- {- key: 'connected',- label: i18n.t('admin.pages.settings.connected_apps.table.status'),- default: true,- // A registration nobody connected and one whose access was revoked- // both show no permissions, so without this the row looks unchanged- // after a merchant presses Revoke.- render: (application) =>- application.connected ? (- <StatusBadge- status="connected"- tone="success"- label={i18n.t('admin.pages.settings.connected_apps.status.connected')}- />- ) : (- <StatusBadge- status="not_connected"- tone="neutral"- label={i18n.t('admin.pages.settings.connected_apps.status.not_connected')}- />- ),- },- {- key: 'scopes',- label: i18n.t('admin.pages.settings.connected_apps.table.access'),- default: true,- render: (application) => <ScopeList scopes={application.scopes} />,- },- {- key: 'authorized_by',- label: i18n.t('admin.pages.settings.connected_apps.table.authorized_by'),- default: true,- render: (application) =>- application.authorized_by ? (- <span className="flex flex-col">- <span>{application.authorized_by}</span>- <span className="text-muted-foreground text-xs">- <RelativeTime iso={application.authorized_at} />- </span>- </span>- ) : (- <span className="text-muted-foreground">—</span>- ),- },- {- key: 'last_authorized_at',- label: i18n.t('admin.pages.settings.connected_apps.table.last_authorized'),- default: true,- render: (application) => <RelativeTime iso={application.last_authorized_at} />,- },- ],-})diff --git a/spree/api/app/controllers/spree/api/v3/admin/oauth/application_tokens_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/oauth/application_tokens_controller.rbindex d3c362fa1f..623b773692 100644--- a/spree/api/app/controllers/spree/api/v3/admin/oauth/application_tokens_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/oauth/application_tokens_controller.rb@@ -3,23 +3,50 @@ module Spreemodule V3module Adminmodule Oauth- # A connected client's live credentials.+ # A connected client's live tokens — one per person who connected it.#- # Revoking is deleting these, not deleting the application: the- # registration stays so the merchant can connect the same client- # again, while anything still holding a token stops working on its- # next call.- class ApplicationTokensController < Spree::Api::V3::Admin::BaseController+ # A store registers a client once and every staff member connects to+ # that same registration, so the application row says that Claude is+ # connected while these say by whom. Revoking one cuts off that+ # person and leaves their colleagues working; deleting the+ # application removes the registration itself.+ class ApplicationTokensController < Spree::Api::V3::Admin::ResourceControllerscoped_resource :oauth_applications+ # Revoking rather than deleting: the row records who held access,+ # and Doorkeeper treats a revoked token as gone on the next call.def destroy- application = current_store.oauth_applications.find_by_prefix_id!(params[:application_id])- authorize! :update, application+ @resource.revoke+ head :no_content+ end- application.access_tokens.where(revoked_at: nil).update_all(revoked_at: Time.current)- application.access_grants.where(revoked_at: nil).update_all(revoked_at: Time.current)+ protected- head :no_content+ def model_class+ Spree::OauthAccessToken+ end++ def serializer_class+ Spree.api.admin_oauth_access_token_serializer+ end++ # Live means unrevoked, not unexpired: an access token lasts+ # hours while the refresh token beside it lasts far longer, so a+ # person whose access has lapsed can mint another at will.+ # Hiding them would hide a connection from the screen that exists+ # to cut it off.+ def scope+ application.live_access_tokens.order(created_at: :desc)+ end++ def collection_includes+ [:resource_owner]+ end++ # Nested under its application, so tenancy comes from the parent+ # rather than from the token's own store column.+ def application+ @application ||= current_store.oauth_applications.find_by_prefix_id!(params[:application_id])endendenddiff --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 1c8a2923e5..129ddc0e91 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@@ -175,9 +175,11 @@ module Spree:code_challenge, :code_challenge_method, :response_mode).to_h.symbolize_keys.merge(scope: known_scopes).- # Carried through raw: RFC 8707 allows one value or several,- # and Doorkeeper's own validator normalizes both shapes.- merge(resource: params[:resource])+ # The audience the grant is written with. Resolved rather+ # than carried through raw, so a client that names nothing —+ # the indicator is optional and most omit it — still gets a+ # grant bound to the Admin API instead of to nothing.+ merge(resource: requested_resource)end# The requested scopes this server knows, with the rest dropped.@@ -197,26 +199,20 @@ module Spree# The audiences the grant is bound to.#- # A client asking for the MCP endpoint is granted the Admin API- # alongside it, because an MCP tool call reaches data by- # dispatching to an Admin API operation — as the same grant, with- # the same scopes, so the ceiling the merchant approved is the one- # that applies. Without it the dispatched call carries a token- # bound to a path the Admin API does not serve, and every tool- # answers "authentication required".+ # Every grant is bound to the Admin API, whatever the client+ # asked for. The MCP endpoint lives inside that API and+ # authenticates the same way, so one audience serves both — and+ # a tool call, which reaches data by dispatching into the Admin+ # API with this same token, is not left carrying a credential+ # bound to a path the Admin API does not serve.#- # This widens the audience, not the authority: the scopes are- # unchanged, and a token for the Admin API alone is still refused- # at the MCP endpoint. RFC 8707 takes a list for exactly this —- # one grant, the surfaces it legitimately needs.+ # The indicator a client sends is honoured for its origin only:+ # a tunnel, a proxy or a custom domain has to appear in the+ # audience as the client knows it.def requested_resource- requested = @pre_auth.resource_indicators.to_a- return requested.first if requested.empty?+ requested = Array(params[:resource]).flat_map { |value| value.to_s.split }- mcp = Spree::Api::Oauth.resources[:mcp]- return requested.join(' ') unless requested.any? { |value| path_of(value) == mcp }-- Spree::Api::Oauth.granted_audience(:mcp, origin_of(requested.first))+ Spree::Api::Oauth.resource_identifier(:admin, origin_of(requested.first))end# The scheme and host the client was given — a tunnel, a proxy, adiff --git a/spree/api/app/serializers/spree/api/v3/admin/oauth_access_token_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/oauth_access_token_serializer.rbnew file mode 100644index 0000000000..49a864f0ff--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/oauth_access_token_serializer.rb@@ -0,0 +1,62 @@+module Spree+ module Api+ module V3+ module Admin+ # One person's live access through a connected client.+ #+ # The token itself is never serialized: it is a bearer credential, and+ # the screen that lists connections only needs to say whose access it+ # is and what that person approved.+ class OauthAccessTokenSerializer < V3::BaseSerializer+ typelize owner_id: [:string, nullable: true],+ owner_type: [:string, nullable: true],+ scopes: [:string, multi: true],+ expired: :boolean++ attributes created_at: :iso8601++ # Who connected, without expanding: the id and the kind, so a+ # client can render a reference or follow it.+ attribute :owner_id do |token|+ token.resource_owner.try(:prefixed_id)+ end++ attribute :owner_type do |token|+ Spree::Base.polymorphic_api_type(token.resource_owner_type)+ end++ # Who connected, as the record itself rather than a summary of it,+ # so the dashboard shows a person the way it does everywhere else:+ # a name over an email, with an avatar.+ #+ # The serializer follows the record's kind, because a grant's owner+ # is polymorphic — an admin today, a customer when a storefront+ # client needs one. Alba hands the proc the object for exactly this.+ one :resource_owner,+ key: :owner,+ resource: proc { |owner| owner_serializer_for(owner) },+ if: proc { expand?('owner') }++ # @param owner [Object] the grant's resource owner+ # @return [Class] the serializer for that kind of owner+ def self.owner_serializer_for(owner)+ case Spree::Base.polymorphic_api_type(owner.class.name)+ when 'customer' then Spree.api.admin_customer_serializer+ else Spree.api.admin_admin_user_serializer+ end.to_s.constantize+ end++ # What this person approved, as permission keys.+ attribute :scopes do |token|+ token.scopes.to_a+ end++ # Whether the current access token has lapsed. The connection is+ # still live — a refresh mints another — but a merchant reading the+ # list deserves to know which agents hold access right now.+ attribute :expired, &:expired?+ end+ end+ end+ end+enddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex b3d8aae7ad..491177e2c3 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -249,8 +249,13 @@ Spree::Core::Engine.add_routes do# The OAuth clients registered against this store. Deleting one# removes the registration; revoking a connection is the nested# `tokens` resource, because that is what revoking deletes.- resources :applications do- resource :tokens, only: :destroy, controller: 'application_tokens'+ #+ # Tokens are plural and addressable: a store registers a client once+ # and every staff member connects to that same registration, so the+ # live tokens are who is connected. Revoking one has to cut off that+ # person and leave their colleagues working.+ resources :applications, except: :show do+ resources :tokens, only: %i[index destroy], controller: 'application_tokens'endenddiff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rbindex 32de23eb70..0cd6271c73 100644--- a/spree/api/lib/spree/api/dependencies.rb+++ b/spree/api/lib/spree/api/dependencies.rb@@ -38,7 +38,7 @@ module Spreechannel order_routing_rule product_publication market delivery_method delivery_method_servicestock_location stock_reservation delivery_rate freight_summary freight_summary_line payment_methodcredit_card store_credit store_credit_event customer_group payment_source digital_asset digital_link- store setup_task update_status api_key oauth_application oauth_consent_request oauth_redirect+ store setup_task update_status api_key oauth_application oauth_access_token oauth_consent_request oauth_redirectoauth_protected_resource allowed_origin webhook_endpoint webhook_event webhook_delivery invitationinvitation_acceptance_link role permission export saved_report import import_row import_mapping promotionpromotion_action promotion_rule coupon_code price_adjustment_tier price_list price_rulediff --git a/spree/api/lib/spree/api/oauth.rb b/spree/api/lib/spree/api/oauth.rbindex e4b1cf06f2..aa6106c9fd 100644--- a/spree/api/lib/spree/api/oauth.rb+++ b/spree/api/lib/spree/api/oauth.rb@@ -18,7 +18,7 @@ module Spree# Protected resources, each registered by the surface that owns it as a# path relative to this application's own origin.#- # Spree::Api::Oauth.register_resource(:mcp, '/api/v3/admin/mcp')+ # Spree::Api::Oauth.register_resource(:admin, '/api/v3/admin')## A path rather than a full URL because the identifier must equal the# URL the client was actually pointed at: the origin comes from the@@ -61,21 +61,18 @@ module Spreeresources.values.map { |path| "#{base}#{path}" }end- # The audiences a grant for one surface is bound to.- #- # An MCP grant carries the Admin API too, because a tool call reaches- # data by dispatching to an Admin API operation — as the same grant,- # with the same scopes. Widening the audience is not widening the- # authority: a token for the Admin API alone is still refused at the- # MCP endpoint.- ## @param key [Symbol]- # @param origin [String, nil] scheme and host the client used- # @return [String] space-separated indicators, as RFC 8707 takes them- def granted_audience(key, origin = nil)- keys = key.to_sym == :mcp ? %i[mcp admin] : [key.to_sym]+ # @param path [String] absolute path this resource answers on+ def register_resource(key, path)+ resources[key.to_sym] = path+ end- keys.filter_map { |name| resource_identifier(name, origin) }.uniq.join(' ')+ # @param origin [String, nil] scheme and host the client used+ # @return [Array<String>] every resource identifier this installation+ # serves+ def resource_identifiers(origin = nil)+ base = origin.presence || application_origin+ resources.values.map { |path| "#{base}#{path}" }end# @param key [Symbol]diff --git a/spree/api/spec/integration/spree/api/v3/admin/oauth/applications_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/oauth/applications_spec.rbindex 27310ed0dd..e2720599ec 100644--- a/spree/api/spec/integration/spree/api/v3/admin/oauth/applications_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/oauth/applications_spec.rb@@ -13,6 +13,14 @@ RSpec.describe 'Admin OAuth Applications API', type: :request, swagger_doc: 'api)end+ # One person's live access through that registration.+ let(:connection) do+ Spree::OauthAccessToken.create!(+ application: application, resource_owner: admin_user, scopes: 'read_products',+ expires_in: 2.hours.to_i, resource: Spree::Api::Oauth.resource_identifier(:mcp)+ )+ end+path '/api/v3/admin/oauth/applications' doget 'List connected applications' dotags 'OAuth'@@ -79,24 +87,6 @@ RSpec.describe 'Admin OAuth Applications API', type: :request, swagger_doc: 'apipath '/api/v3/admin/oauth/applications/{id}' doparameter name: :id, in: :path, type: :string, required: true, description: 'Application ID'- get 'Get an application' do- tags 'OAuth'- produces 'application/json'- security [api_key: [], bearer_auth: []]- admin_scope :read, :oauth_applications-- parameter name: 'x-spree-api-key', in: :header, type: :string, required: true- parameter name: :Authorization, in: :header, type: :string, required: true-- response '200', 'application found' do- let(:id) { application.prefixed_id }-- schema '$ref' => '#/components/schemas/OauthApplication'-- run_test!- end- end-patch 'Update an application' dotags 'OAuth'consumes 'application/json'@@ -145,15 +135,43 @@ RSpec.describe 'Admin OAuth Applications API', type: :request, swagger_doc: 'apiparameter name: :application_id, in: :path, type: :string, required: true,description: 'Application ID'- delete 'Revoke an application\'s access' do+ get 'List who is connected' do+ tags 'OAuth'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description <<~DESC+ A store registers a client once and every staff member connects to+ that same registration, so this lists one entry per person who holds+ access through it. Pass `expand=owner` for who they are.+ DESC+ admin_scope :read, :oauth_applications++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true++ response '200', 'connections listed' do+ let(:application_id) { application.prefixed_id }++ schema SwaggerSchemaHelpers.paginated('OauthAccessToken')++ run_test!+ end+ end+ end++ path '/api/v3/admin/oauth/applications/{application_id}/tokens/{id}' do+ parameter name: :application_id, in: :path, type: :string, required: true,+ description: 'Application ID'+ parameter name: :id, in: :path, type: :string, required: true, description: 'Token ID'++ delete 'Revoke one person\'s access' dotags 'OAuth'produces 'application/json'security [api_key: [], bearer_auth: []]description <<~DESC- The off switch. Revokes every live token and grant this application- holds, so a client that still has a token stops working on its next- call. The registration itself stays, and a merchant can connect it- again.+ Cuts off one person and leaves their colleagues connected. The client+ stops working for them on its next call; the registration stays, and+ they can connect again.DESCadmin_scope :write, :oauth_applications@@ -162,6 +180,7 @@ RSpec.describe 'Admin OAuth Applications API', type: :request, swagger_doc: 'apiresponse '204', 'access revoked' dolet(:application_id) { application.prefixed_id }+ let(:id) { connection.prefixed_id }run_test!enddiff --git a/spree/api/spec/requests/spree/api/v3/admin/oauth/applications_spec.rb b/spree/api/spec/requests/spree/api/v3/admin/oauth/applications_spec.rbindex 7daa5089af..7c9abc2b6f 100644--- a/spree/api/spec/requests/spree/api/v3/admin/oauth/applications_spec.rb+++ b/spree/api/spec/requests/spree/api/v3/admin/oauth/applications_spec.rb@@ -103,19 +103,35 @@ RSpec.describe 'Admin connected applications', type: :request doend# Revoking and deleting are different operations on different things, which- # is why revoking is the nested tokens resource: it deletes the credentials,- # not the client.- describe 'revoking' do- it 'stops the application working without deleting its registration' do- raw = token_for(admin).plaintext_token+ # is why revoking is the nested tokens resource: it deletes one person's+ # credentials, not the client.+ describe 'revoking one person' do+ let(:colleague) { create(:admin_user) }- delete "/api/v3/admin/oauth/applications/#{application.prefixed_id}/tokens",+ it 'stops that person without disconnecting their colleagues' do+ mine = token_for(admin)+ theirs = token_for(colleague)++ delete "/api/v3/admin/oauth/applications/#{application.prefixed_id}/tokens/#{mine.prefixed_id}",headers: { 'X-Spree-API-Key' => api_key.plaintext_token }expect(response).to have_http_status(:no_content)- expect(Spree::OauthAccessToken.by_token(raw)).not_to be_accessible+ expect(Spree::OauthAccessToken.by_token(mine.plaintext_token)).not_to be_accessible+ expect(theirs.reload.revoked_at).to be_nilexpect(store.oauth_applications.find_by(name: 'Claude')).to be_presentend++ it 'lists who is connected, one entry per person' do+ token_for(admin)+ token_for(colleague)++ get "/api/v3/admin/oauth/applications/#{application.prefixed_id}/tokens",+ headers: { 'X-Spree-API-Key' => api_key.plaintext_token }++ expect(response).to have_http_status(:ok)+ owners = json_response['data'].map { |row| row['owner_id'] }+ expect(owners).to contain_exactly(admin.prefixed_id, colleague.prefixed_id)+ endenddescribe 'registering a client' dodiff --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 9c01019419..2e5bfeb9bd 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@@ -105,8 +105,8 @@ module Spreedef oauth_challengeformat('Bearer realm="%<realm>s", resource_metadata="%<metadata>s"',- realm: Spree::Api::Oauth.resource_identifier(:mcp, request.base_url),- metadata: "#{request.base_url}/api/v3/oauth/protected-resource/mcp"+ realm: Spree::Api::Oauth.resource_identifier(:admin, request.base_url),+ metadata: "#{request.base_url}/api/v3/oauth/protected-resource/admin")end@@ -136,34 +136,19 @@ module Spreeend# The token this request may actually act on: live, and issued for- # this endpoint. Named for the hook ScopedAuthorization reads, so a+ # the Admin API. Named for the hook ScopedAuthorization reads, so a# grant narrows authority through the same path every admin# endpoint uses rather than only here.+ #+ # This endpoint shares the Admin API's audience rather than holding+ # one of its own, because a tool call reaches data by dispatching+ # into the Admin API carrying this very token. Two audiences on one+ # credential could never both be satisfied.def current_oauth_tokenreturn @current_oauth_token if defined?(@current_oauth_token)token = bearer_access_token- @current_oauth_token = token if token&.accessible? && audience_matches?(token)- end-- # Deliberately stricter than Doorkeeper's own- # `resource_indicators_match?`, which treats "neither side names a- # resource" as a match. Here an unbound token must be refused: the- # whole point of the audience is that a token minted for another- # resource cannot be replayed against this one, and a token with no- # audience cannot be shown to have been issued for this endpoint.- # Compared by path: a token minted through one hostname must keep- # working through another the same deployment answers on, while a- # token naming a different resource entirely is still refused.- def audience_matches?(token)- expected = Spree::Api::Oauth.resources[:mcp]- return false if expected.blank?-- token.resource.to_s.split.any? do |indicator|- URI.parse(indicator).path == expected- rescue URI::InvalidURIError- false- end+ @current_oauth_token = token if token&.accessible? && admin_audience_matches?(token)enddef oauth_resource_ownerdiff --git a/spree/mcp/lib/spree/mcp/engine.rb b/spree/mcp/lib/spree/mcp/engine.rbindex 8e7c496320..ca5e5843b8 100644--- a/spree/mcp/lib/spree/mcp/engine.rb+++ b/spree/mcp/lib/spree/mcp/engine.rb@@ -4,12 +4,6 @@ module Spreeisolate_namespace Spreeengine_name 'spree_mcp'- # Declares this endpoint as an OAuth protected resource, so a token can- # be audience-bound to it and a client can discover the authorization- # server from a 401 here.- initializer 'spree.mcp.oauth_resource' do- Spree::Api::Oauth.register_resource(:mcp, '/api/v3/admin/mcp')- endendendenddiff --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 d3b8f5f946..55d154d30f 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@@ -16,7 +16,7 @@ RSpec.describe 'Admin MCP endpoint', type: :request do# What consent mints for an MCP client: the MCP endpoint and the Admin API,# because a tool call dispatches to an Admin API operation as the same# grant. A token naming only one surface is exercised below.- let(:resource) { Spree::Api::Oauth.granted_audience(:mcp) }+ let(:resource) { Spree::Api::Oauth.resource_identifier(:admin) }let(:token) { oauth_token(scopes: scopes) }before { Spree::Api::Oauth.register_resource(:mcp, '/api/v3/admin/mcp') }@@ -111,7 +111,7 @@ RSpec.describe 'Admin MCP endpoint', type: :request doexpect(response).to have_http_status(:unauthorized)expect(response.headers['WWW-Authenticate']).to include(- 'resource_metadata="', '/api/v3/oauth/protected-resource/mcp'+ 'resource_metadata="', '/api/v3/oauth/protected-resource/admin')end@@ -192,7 +192,7 @@ RSpec.describe 'Admin MCP endpoint', type: :request do)raw = Spree::OauthAccessToken.create!(application: application, resource_owner: admin, scopes: 'read_products',- expires_in: 2.hours.to_i, resource: Spree::Api::Oauth.granted_audience(:mcp)+ expires_in: 2.hours.to_i, resource: Spree::Api::Oauth.resource_identifier(:admin)).plaintext_tokenbody = post_with_token(raw)@@ -202,6 +202,57 @@ RSpec.describe 'Admin MCP endpoint', type: :request doendend+ # Everything else here hands the controller a token built in Ruby, which+ # proved nothing about the audience a real grant carries: consent is what+ # sets it, and it was setting nothing. This walks the sequence a client+ # actually performs.+ describe 'a client connecting for real' do+ def connect(scope: 'read_products')+ verifier = 'v' * 64+ challenge = Base64.urlsafe_encode64(Digest::SHA256.digest(verifier), padding: false)+ jwt = Spree::Api::V3::TestingSupport.generate_jwt(+ admin, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN+ )++ post '/api/v3/admin/oauth/authorize',+ params: { client_id: application.uid, redirect_uri: application.redirect_uri,+ response_type: 'code', scope: scope,+ code_challenge: challenge, code_challenge_method: 'S256' },+ headers: { 'Authorization' => "Bearer #{jwt}" }++ redirect = JSON.parse(response.body)['redirect_uri']+ code = Rack::Utils.parse_query(URI.parse(redirect).query)['code']++ post '/oauth/token',+ params: { grant_type: 'authorization_code', code: code, client_id: application.uid,+ redirect_uri: application.redirect_uri, code_verifier: verifier }++ JSON.parse(response.body)['access_token']+ end++ it 'calls a tool with the token consent issued' do+ raw = connect++ body = post_rpc('tools/call',+ { name: 'search_resources', arguments: { 'resource' => 'products' } },+ headers: { 'Authorization' => "Bearer #{raw}" })++ expect(response).to have_http_status(:ok)+ expect(body.dig('result', 'isError')).to be(false)+ end++ # The call the tool makes on the caller's behalf runs as the same token,+ # so a grant bound to the wrong audience leaves every tool answering+ # "authentication required" while the endpoint itself looks healthy.+ it 'reaches the Admin API with that same token' do+ raw = connect++ get '/api/v3/admin/products', headers: { 'Authorization' => "Bearer #{raw}" }++ expect(response).to have_http_status(:ok)+ end+ end+describe 'tenancy' doit 'serves the key\'s own store when the header agrees' dobody = post_rpc('tools/call',diff --git a/spree/mcp/spec/spec_helper.rb b/spree/mcp/spec/spec_helper.rbindex e4fb73a4ce..144d44429d 100644--- a/spree/mcp/spec/spec_helper.rb+++ b/spree/mcp/spec/spec_helper.rb@@ -14,6 +14,8 @@ require 'database_cleaner/active_record'require 'spree/testing_support/factories'require 'spree/testing_support/jobs'require 'spree/testing_support/store'+# Minting an admin JWT, so a spec can walk the consent flow a client performs.+require 'spree/api/testing_support/v3/base'RSpec.configure do |config|config.color = true