Skip to content

armgit / spree

Public Imported from GitHub
0

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.

Fix: Added Claude Code's localhost callback to the Claude preset (#15052)

Damian Legawiec16421ce3fbb3
diff --git a/docs/developer/mcp/quick-start.mdx b/docs/developer/mcp/quick-start.mdx
index 4b392aa774..33e5afe3da 100644
--- a/docs/developer/mcp/quick-start.mdx
+++ b/docs/developer/mcp/quick-start.mdx
@@ -43,18 +43,18 @@ Paste the URL into your MCP client. It sends you to your store, you sign in, and
<Tabs>
<Tab title="Claude Code">
- Register Claude Code under **Settings → OAuth clients** in your Spree
- dashboard with the redirect URI `http://localhost:3118/callback`. Any
- free port other than 80 works, as long as the same port is passed below. Then add the
- server with the client ID that registration shows:
+ In your Spree dashboard, go to **Settings → AI Agents**, click
+ **Connect an agent**, choose **Claude** and click **Continue**. The
+ **Claude Code** tab shows the command to run, with your client ID
+ already in it:
```bash
claude mcp add --transport http --client-id <client-id> --callback-port 3118 \
spree https://your-store.com/api/v3/admin/mcp
```
- The port must be fixed: Claude Code calls back on `localhost`, and your
- store only accepts the exact port that was registered.
+ Keep `--callback-port 3118`. Claude Code calls back on `localhost`, and
+ your store only accepts the exact port that was registered.
</Tab>
<Tab title="Claude Desktop / claude.ai">
**Settings → Connectors → Add custom connector**, then paste the URL.
diff --git a/docs/user/ai-agents/ai-agents.mdx b/docs/user/ai-agents/ai-agents.mdx
index 11991a7901..caa40f18e3 100644
--- a/docs/user/ai-agents/ai-agents.mdx
+++ b/docs/user/ai-agents/ai-agents.mdx
@@ -46,7 +46,7 @@ The panel then shows two values, each with a button that copies it:
<Note>Choosing **Something else** asks for a name and the agent's redirect URI, which is where the agent expects to be sent back to after you sign in. It comes from that agent's own documentation. For Claude and ChatGPT this is filled in for you, so there is nothing to look up.</Note>
-<Note>Registering the same assistant twice reconnects the one already registered rather than creating a second. One Claude registration covers claude.ai, Claude Desktop and Claude Code together, and everyone on your team connects through it.</Note>
+<Note>Registering the same assistant twice reconnects the one already registered rather than creating a second, and brings its settings up to date. One Claude registration covers claude.ai, Claude Desktop and Claude Code together, and everyone on your team connects through it.</Note>
<Note>Registering an agent creates an entry under **Settings → OAuth clients**, which holds its Client ID and the address the assistant is sent back to. For Claude and ChatGPT that entry is filled in for you, and the only reason to open it is to look the Client ID up again or to remove the agent outright.</Note>
diff --git a/packages/dashboard/e2e/ai-agents.spec.ts b/packages/dashboard/e2e/ai-agents.spec.ts
index 69cf6491d2..6b2f7d5e49 100644
--- a/packages/dashboard/e2e/ai-agents.spec.ts
+++ b/packages/dashboard/e2e/ai-agents.spec.ts
@@ -6,7 +6,9 @@ import {
CONNECT_CTA,
clearRegistrations,
connectKnownClient,
+ listClients,
REGISTER_CTA,
+ registerClient,
seedConnection,
} from './oauth-helpers'
@@ -55,6 +57,45 @@ test.describe('connecting an agent', () => {
await expect(sheet.getByText(/claude mcp add/i)).toBeVisible()
})
+ // Claude Code calls back on `localhost` and the store only accepts the
+ // registered port, so the command has to carry the client id and pin it.
+ test('gives Claude Code a command with its client id and callback port', async ({ page }) => {
+ const creds = await login(page)
+ await clearRegistrations(page, creds.store_id, creds.accessToken)
+ await gotoIndex(page, AGENTS_PATH(creds.store_id), CONNECT_CTA)
+
+ const sheet = await connectKnownClient(page)
+ await expect(sheet.getByText(/ready to connect/i)).toBeVisible({ timeout: 15_000 })
+ await sheet.getByRole('tab', { name: /claude code/i }).click()
+ const [client] = await listClients(page, creds.store_id, creds.accessToken)
+ await expect(
+ sheet.getByText(`--client-id ${client.client_id} --callback-port 3118`),
+ ).toBeVisible()
+ })
+
+ // A Claude registration made before Claude Code's callback was added would
+ // refuse it at sign-in, so connecting Claude again brings it up to date.
+ test('adds the Claude Code callback to an older Claude registration', async ({ page }) => {
+ const creds = await login(page)
+ await clearRegistrations(page, creds.store_id, creds.accessToken)
+ await registerClient(page, creds.store_id, creds.accessToken, {
+ name: 'Claude',
+ redirect_uri: 'https://claude.ai/api/mcp/auth_callback\nhttp://127.0.0.1/callback',
+ })
+
+ await gotoIndex(page, AGENTS_PATH(creds.store_id), CONNECT_CTA)
+ const sheet = await connectKnownClient(page)
+ await expect(sheet.getByText(/ready to connect/i)).toBeVisible({ timeout: 15_000 })
+ await sheet.getByRole('button', { name: /^done$/i }).click()
+
+ // The missing callback is added and the ones already registered stay.
+ await gotoIndex(page, CLIENTS_PATH(creds.store_id), REGISTER_CTA)
+ const row = page.getByRole('row', { name: /Claude/ })
+ await expect(row.getByText(/localhost:3118\/callback/)).toBeVisible({ timeout: 15_000 })
+ await expect(row.getByText(/claude\.ai\/api\/mcp\/auth_callback/)).toBeVisible()
+ await expect(row.getByText(/127\.0\.0\.1\/callback/)).toBeVisible()
+ })
+
// Revoking keeps the registration so the same client can be connected
// again — which is exactly why the card has to say who holds access now.
test('says who is connected through a registration', async ({ page }) => {
@@ -102,6 +143,33 @@ test.describe('connecting a client we do not know', () => {
await sheet.getByRole('button', { name: /^done$/i }).click()
await expect(page.getByText(name).first()).toBeVisible({ timeout: 15_000 })
})
+ // Reconnecting under the same name is how a developer adds a callback
+ // their client now uses; the ones already registered stay.
+ test('adds a new callback when the same client connects again', async ({ page }) => {
+ const creds = await login(page)
+ const name = `CI reconnect ${Date.now()}`
+ await registerClient(page, creds.store_id, creds.accessToken, {
+ name,
+ redirect_uri: 'https://old.example.com/oauth/callback',
+ })
+ await gotoIndex(page, AGENTS_PATH(creds.store_id), CONNECT_CTA)
+
+ await page.getByRole('button', { name: CONNECT_CTA }).click()
+ const sheet = page.getByRole('dialog')
+ await sheet.getByText(/any other client that speaks mcp/i).click()
+ await sheet.locator('#mcp-other-name').fill(name)
+ await sheet.locator('#mcp-other-uri').fill('https://new.example.com/oauth/callback')
+ await sheet.getByRole('button', { name: /^continue$/i }).click()
+ await expect(sheet.getByText(/ready to connect/i)).toBeVisible({ timeout: 15_000 })
+
+ const client = (await listClients(page, creds.store_id, creds.accessToken)).find(
+ (candidate) => candidate.name === name,
+ )
+ expect(client?.redirect_uri.split(/\s+/)).toEqual([
+ 'https://old.example.com/oauth/callback',
+ 'https://new.example.com/oauth/callback',
+ ])
+ })
})
// A store registers an agent once and every staff member connects to that
diff --git a/packages/dashboard/e2e/oauth-clients.spec.ts b/packages/dashboard/e2e/oauth-clients.spec.ts
index 93fcd6c737..88ff51ac02 100644
--- a/packages/dashboard/e2e/oauth-clients.spec.ts
+++ b/packages/dashboard/e2e/oauth-clients.spec.ts
@@ -43,6 +43,48 @@ test.describe('oauth clients', () => {
})
})
+// Claude Code listens on plain http on the developer's own machine, so a
+// `localhost` callback is exempt from https — but only with an explicit port,
+// the only shape that can ever match a sign-in.
+test.describe('a localhost callback', () => {
+ test('is accepted with an explicit port', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, CLIENTS_PATH(creds.store_id), REGISTER_CTA)
+
+ const name = `CI localhost ${Date.now()}`
+ await page.getByRole('button', { name: REGISTER_CTA }).click()
+ const sheet = page.getByRole('dialog')
+ await sheet.locator('#oauth-application-name').fill(name)
+ await sheet.locator('#oauth-application-redirect-uri').fill('http://localhost:3118/callback')
+ await sheet.getByRole('button', { name: /^save$/i }).click()
+
+ await expect(page.getByRole('row', { name: new RegExp(name) })).toBeVisible({
+ timeout: 15_000,
+ })
+ })
+
+ // Neither shape can ever match what a client sends at sign-in.
+ for (const [label, uri] of [
+ ['without a port', 'http://localhost/callback'],
+ ['written in capitals', 'http://LocalHost:3118/callback'],
+ ]) {
+ test(`is refused ${label}`, async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, CLIENTS_PATH(creds.store_id), REGISTER_CTA)
+
+ await page.getByRole('button', { name: REGISTER_CTA }).click()
+ const sheet = page.getByRole('dialog')
+ await sheet.locator('#oauth-application-name').fill(`CI refused ${Date.now()}`)
+ await sheet.locator('#oauth-application-redirect-uri').fill(uri)
+ await sheet.getByRole('button', { name: /^save$/i }).click()
+
+ await expect(
+ sheet.getByRole('alert').filter({ hasText: /must start with https/i }),
+ ).toBeVisible({ timeout: 15_000 })
+ })
+ }
+})
+
test.describe('managing a registered client', () => {
test('renames one, and removes it', async ({ page }) => {
const creds = await login(page)
diff --git a/packages/dashboard/e2e/oauth-helpers.ts b/packages/dashboard/e2e/oauth-helpers.ts
index 165ff27c01..7bcc7e721f 100644
--- a/packages/dashboard/e2e/oauth-helpers.ts
+++ b/packages/dashboard/e2e/oauth-helpers.ts
@@ -31,10 +31,7 @@ export async function connectKnownClient(page: Page) {
*/
export async function clearRegistrations(page: Page, storeId: string, accessToken: string) {
const headers = { 'X-Spree-Store-Id': storeId, Authorization: `Bearer ${accessToken}` }
- const res = await page.request.get('/api/v3/admin/oauth/applications?limit=100', { headers })
- if (!res.ok()) throw new Error(`Listing clients failed: ${res.status()} ${await res.text()}`)
-
- for (const client of (await res.json()).data ?? []) {
+ for (const client of await listClients(page, storeId, accessToken)) {
const deleted = await page.request.delete(`/api/v3/admin/oauth/applications/${client.id}`, {
headers,
})
@@ -44,6 +41,38 @@ export async function clearRegistrations(page: Page, storeId: string, accessToke
}
}
+/** Every client this store has registered, read straight from the API. */
+export async function listClients(page: Page, storeId: string, accessToken: string) {
+ const headers = { 'X-Spree-Store-Id': storeId, Authorization: `Bearer ${accessToken}` }
+ const res = await page.request.get('/api/v3/admin/oauth/applications?limit=100', { headers })
+ if (!res.ok()) throw new Error(`Listing clients failed: ${res.status()} ${await res.text()}`)
+ return ((await res.json()).data ?? []) as {
+ id: string
+ name: string
+ client_id: string
+ redirect_uri: string
+ }[]
+}
+
+/** Registers a client straight through the API, as a store set up earlier would hold it. */
+export async function registerClient(
+ page: Page,
+ storeId: string,
+ accessToken: string,
+ data: { name: string; redirect_uri: string },
+) {
+ const registered = await page.request.post('/api/v3/admin/oauth/applications', {
+ headers: { 'X-Spree-Store-Id': storeId, Authorization: `Bearer ${accessToken}` },
+ data,
+ })
+ if (!registered.ok()) {
+ throw new Error(
+ `Registering ${data.name} failed: ${registered.status()} ${await registered.text()}`,
+ )
+ }
+ return registered.json()
+}
+
/**
* Connects an agent for real: registers a client, then walks consent and the
* token exchange exactly as a client does.
@@ -60,14 +89,10 @@ export async function seedConnection(
) {
const headers = { 'X-Spree-Store-Id': storeId, Authorization: `Bearer ${accessToken}` }
- const registered = await page.request.post('/api/v3/admin/oauth/applications', {
- headers,
- data: { name, redirect_uri: 'https://example.test/callback' },
+ const application = await registerClient(page, storeId, accessToken, {
+ name,
+ redirect_uri: 'https://example.test/callback',
})
- if (!registered.ok()) {
- throw new Error(`Registering ${name} failed: ${registered.status()} ${await registered.text()}`)
- }
- const application = await registered.json()
// A fixed verifier and its S256 challenge. The pair only has to be
// self-consistent — the server checks one against the other.
diff --git a/packages/dashboard/src/components/spree/mcp-connect-sheet.tsx b/packages/dashboard/src/components/spree/mcp-connect-sheet.tsx
index 2e6392fb30..442ec5c6ab 100644
--- a/packages/dashboard/src/components/spree/mcp-connect-sheet.tsx
+++ b/packages/dashboard/src/components/spree/mcp-connect-sheet.tsx
@@ -1,5 +1,4 @@
import type { OauthApplication } from '@spree/admin-sdk'
-import { adminClient } from '@spree/dashboard-core'
import {
Alert,
AlertDescription,
@@ -20,10 +19,9 @@ import {
TabsTrigger,
} from '@spree/dashboard-ui'
import { CircleAlertIcon, InfoIcon } from '@spree/dashboard-ui/icons'
-import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { useOauthApplications } from '../../hooks/use-oauth'
+import { useOauthApplications, useSaveOauthApplication } from '../../hooks/use-oauth'
import { ChoiceCardPicker } from './choice-card-picker'
type McpConnectSheetProps = {
@@ -44,23 +42,38 @@ type McpConnectSheetProps = {
/**
* The loopback callback a terminal client listens on.
*
- * Registered alongside the hosted one because Claude Code and Codex redirect
- * to a local port rather than the vendor's servers, and the port is chosen
- * at run time. RFC 8252 §7.3 says to compare loopback redirects ignoring the
+ * Registered alongside the hosted one because terminal clients such as Codex
+ * redirect to a local port rather than the vendor's servers, and the port is
+ * chosen at run time. RFC 8252 §7.3 says to compare loopback redirects ignoring the
* port, which Doorkeeper does — but only for an IP literal, since it decides
- * by parsing the host as an address. `localhost` is a name, so it parses as
- * nothing and every ephemeral port is refused.
+ * by parsing the host as an address.
*/
const LOOPBACK_CALLBACK = 'http://127.0.0.1/callback'
+/**
+ * Claude Code only ever calls back on `localhost`, never the IP literal, and
+ * Doorkeeper compares a `localhost` callback exactly, port included. So the
+ * registration names a fixed port and the command pins Claude Code to it.
+ */
+const CLAUDE_CODE_PORT = 3118
+const CLAUDE_CODE_CALLBACK = `http://localhost:${CLAUDE_CODE_PORT}/callback`
+
const KNOWN_CLIENTS = [
{
value: 'claude',
name: 'Claude',
- redirectUris: ['https://claude.ai/api/mcp/auth_callback', LOOPBACK_CALLBACK],
+ redirectUris: [
+ 'https://claude.ai/api/mcp/auth_callback',
+ LOOPBACK_CALLBACK,
+ CLAUDE_CODE_CALLBACK,
+ ],
surfaces: [
{ id: 'app', command: null },
- { id: 'cli', command: (url: string) => `claude mcp add --transport http spree ${url}` },
+ {
+ id: 'cli',
+ command: (url: string, clientId: string) =>
+ `claude mcp add --transport http --client-id ${clientId} --callback-port ${CLAUDE_CODE_PORT} spree ${url}`,
+ },
],
},
{
@@ -78,7 +91,6 @@ const OTHER = 'other'
export function McpConnectSheet({ open, onOpenChange }: McpConnectSheetProps) {
const { t } = useTranslation()
- const queryClient = useQueryClient()
const [choice, setChoice] = useState<string>(KNOWN_CLIENTS[0].value)
const [created, setCreated] = useState<OauthApplication | null>(null)
const [customName, setCustomName] = useState('')
@@ -93,14 +105,7 @@ export function McpConnectSheet({ open, onOpenChange }: McpConnectSheetProps) {
const endpoint = `${apiOrigin}/api/v3/admin/mcp`
const selected = KNOWN_CLIENTS.find((client) => client.value === choice)
- const register = useMutation({
- mutationFn: (params: { name: string; redirect_uri: string }) =>
- adminClient.oauth.applications.create(params),
- onSuccess: (application) => {
- queryClient.invalidateQueries({ queryKey: ['oauth-applications'] })
- setCreated(application)
- },
- })
+ const register = useSaveOauthApplication()
async function connect() {
setFailure(null)
@@ -113,13 +118,32 @@ export function McpConnectSheet({ open, onOpenChange }: McpConnectSheetProps) {
// second one — two rows with two ids would leave a merchant guessing
// which to paste.
const already = existing?.data?.find((candidate) => candidate.name === name)
- if (already) {
- setCreated(already)
- return
- }
try {
- await register.mutateAsync({ name, redirect_uri: redirectUri })
+ if (!already) {
+ setCreated(await register.mutateAsync({ name, redirect_uri: redirectUri }))
+ return
+ }
+
+ // A callback the registration lacks — added to a preset since, or
+ // typed in for a custom client — would be refused at sign-in, so
+ // reconnecting adds it.
+ const registered = (already.redirect_uri ?? '').split(/\s+/).filter(Boolean)
+ const offered: readonly string[] = selected
+ ? selected.redirectUris
+ : redirectUri.split(/\s+/).filter(Boolean)
+ const missing = offered.filter((uri) => !registered.includes(uri))
+ if (missing.length === 0) {
+ setCreated(already)
+ return
+ }
+ setCreated(
+ await register.mutateAsync({
+ id: already.id,
+ name,
+ redirect_uri: [...registered, ...missing].join('\n'),
+ }),
+ )
} catch (error) {
setFailure(error instanceof Error ? error.message : t('admin.common.error'))
}
@@ -298,7 +322,7 @@ function ConnectInstructions({
<TabsContent value="cli" className="flex flex-col gap-4 pt-4">
<CopyableValue
label={t('admin.mcp_connect.run_label')}
- value={cli.command(endpoint)}
+ value={cli.command(endpoint, clientId)}
copyLabel={t('admin.mcp_connect.copy_command')}
/>
<p className="text-muted-foreground text-sm">
diff --git a/packages/dashboard/src/hooks/use-oauth.ts b/packages/dashboard/src/hooks/use-oauth.ts
index f3fdeae35a..04eae0ee5f 100644
--- a/packages/dashboard/src/hooks/use-oauth.ts
+++ b/packages/dashboard/src/hooks/use-oauth.ts
@@ -1,4 +1,9 @@
-import type { OauthAuthorizationParams, OauthConsentRequest, OauthRedirect } from '@spree/admin-sdk'
+import type {
+ OauthApplication,
+ OauthAuthorizationParams,
+ OauthConsentRequest,
+ OauthRedirect,
+} from '@spree/admin-sdk'
import { adminClient, useResourceKey, useResourceMutation } from '@spree/dashboard-core'
import { useQuery } from '@tanstack/react-query'
@@ -55,6 +60,26 @@ export function useOauthRegistrations() {
})
}
+/**
+ * Registers a client, or replaces the callbacks of the registration `id`
+ * names. Failures are left to the caller, which shows them in place.
+ */
+export function useSaveOauthApplication() {
+ return useResourceMutation<
+ OauthApplication,
+ Error,
+ { id?: string; name: string; redirect_uri: string }
+ >({
+ mutationFn: ({ id, name, redirect_uri }) =>
+ id
+ ? adminClient.oauth.applications.update(id, { redirect_uri })
+ : adminClient.oauth.applications.create({ name, redirect_uri }),
+ invalidate: [['oauth-applications']],
+ successMessage: false,
+ errorMessage: false,
+ })
+}
+
/** Removes the registration, and every grant and token with it. */
export function useDeleteOauthApplication() {
return useResourceMutation<void, Error, string>({
diff --git a/spree/api/lib/spree/api/oauth.rb b/spree/api/lib/spree/api/oauth.rb
index 318f7dd5d6..60f6aed1cc 100644
--- a/spree/api/lib/spree/api/oauth.rb
+++ b/spree/api/lib/spree/api/oauth.rb
@@ -35,9 +35,10 @@ module Spree
# Whether a redirect URI may use plain http: an IP-literal loopback, or
# `localhost` with an explicit port.
#
- # Claude Code only ever calls back on `http://localhost:<port>`. The port
- # is required because Doorkeeper ignores it only for IP literals, so a
- # port-less `localhost` registration could never match an authorization.
+ # Claude Code only ever calls back on `http://localhost:<port>`. Doorkeeper
+ # compares a `localhost` callback exactly, so the host must be lowercase
+ # and the port explicit: anything else could never match an
+ # authorization.
#
# @param uri [URI, String]
# @return [Boolean]
@@ -45,7 +46,7 @@ module Spree
uri = URI.parse(uri.to_s) unless uri.respond_to?(:host)
return true if loopback_uri?(uri)
- uri.host.to_s.casecmp?('localhost') &&
+ uri.host == 'localhost' &&
(1..65_535).cover?(uri.port) && uri.port != uri.default_port
rescue StandardError
false
@@ -211,8 +212,9 @@ module Spree
# plain-http one hands them to anyone on the path — except a
# loopback or `localhost` one, which never leaves the machine. A
# terminal client listens on a local port and has no certificate
- # for it, so RFC 8252 §7.3 makes that the recommended shape, and
- # refusing it would lock out Claude Code and Codex entirely.
+ # for it. RFC 8252 §7.3 recommends the IP literal, but Claude Code
+ # only sends `localhost`, so refusing it would lock Claude Code
+ # out entirely.
#
# Passed as a callable so the exemption is per URI rather than
# per environment: everything else still has to be https.
diff --git a/spree/api/spec/lib/spree/api/oauth_redirect_uri_spec.rb b/spree/api/spec/lib/spree/api/oauth_redirect_uri_spec.rb
index d5017a55cc..4cd34e8a48 100644
--- a/spree/api/spec/lib/spree/api/oauth_redirect_uri_spec.rb
+++ b/spree/api/spec/lib/spree/api/oauth_redirect_uri_spec.rb
@@ -58,6 +58,12 @@ RSpec.describe 'OAuth redirect URIs' do
expect(build_with('http://localhost:65536/callback')).not_to be_valid
end
+ # Doorkeeper matches a `localhost` callback exactly, and clients send it
+ # lowercase.
+ it 'refuses localhost written in capitals' do
+ expect(build_with('http://LocalHost:3118/callback')).not_to be_valid
+ end
+
it 'refuses a host that only starts with localhost' do
expect(build_with('http://localhost.example.test:3118/callback')).not_to be_valid
end