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
Added AI coding agent setup: docs MCP server and spree add ai (#14908)
Damian Legawiec02ac2cf3c34c
diff --git a/.changeset/create-spree-app-docs-mcp.md b/.changeset/create-spree-app-docs-mcp.mdnew file mode 100644index 0000000000..0cf556bce3--- /dev/null+++ b/.changeset/create-spree-app-docs-mcp.md@@ -0,0 +1,6 @@+---+"create-spree-app": minor+"@spree/cli": minor+---++Added `spree add ai`, which installs the Spree agent skills and connects Claude Code, Cursor and VS Code to the Spree docs MCP server, so existing projects can get the same AI agent setup as new ones. It keeps the servers a project's config files already list and is safe to re-run. New projects now run it during setup: the agent skills question reads "Set up AI coding agents?" and covers both, and `--docs-mcp` / `--no-docs-mcp` answer the docs half on their own.diff --git a/README.md b/README.mdindex 45e3f3adf1..4dc0d09174 100755--- a/README.md+++ b/README.md@@ -82,13 +82,13 @@ Thank you for supporting Spree open-source ❤️### Agentic Development-Building with an AI coding agent? Install the [Spree agent skills](https://github.com/spree/agent-skills) — they teach Claude Code, Cursor, Copilot, and 60+ other tools Spree's conventions, customization patterns, and upgrade flows:+Building with an AI coding agent? `create-spree-app` sets it up for you — answer yes to **Set up AI coding agents?** In an existing project, run:```bash-npx skills add spree/agent-skills+npx spree add ai```-Then connect the [docs MCP server](https://spreecommerce.org/docs/developer/agentic/mcp) and let your agent build with you. Learn more in the [Agentic Development docs](https://spreecommerce.org/docs/developer/agentic/overview).+This installs the [Spree agent skills](https://github.com/spree/agent-skills), which teach Claude Code, Codex, Cursor, Copilot and 60+ other tools Spree's conventions, customization patterns and upgrade flows. It also connects Claude Code, Cursor and VS Code to the [docs MCP server](https://spreecommerce.org/docs/developer/agentic/mcp), so your agent can search the latest docs. Learn more in the [Agentic Development docs](https://spreecommerce.org/docs/developer/agentic/overview).### Spree CLI@@ -122,7 +122,7 @@ Everything below ships in this repository under the BSD 3-Clause license.* **[Security & Identity](https://spreecommerce.org/docs/developer/providers/sso)** — [OpenID Connect](https://spreecommerce.org/docs/developer/providers/sso) single sign-on for staff and customers, [custom auth adapters](https://spreecommerce.org/docs/developer/how-to/custom-api-authentication) for any JWT issuer, [role-based permissions](https://spreecommerce.org/docs/developer/customization/permissions) scoped per store, and a [PCI-compliant](https://spreecommerce.org/docs/developer/security/pci_compliance) payment architecture where card data never touches your server.* **[MeiliSearch Integration](https://spreecommerce.org/docs/integrations/search/meilisearch)** — typo-tolerant product search and faceted filtering, or [bring your own search provider](https://spreecommerce.org/docs/developer/how-to/custom-search-provider).* **Integrations & Extensibility** — [Event Bus](https://spreecommerce.org/docs/developer/core-concepts/events), [Webhooks](https://spreecommerce.org/docs/developer/core-concepts/webhooks), [OpenTelemetry](spree/opentelemetry) instrumentation, and native integrations ([GA4](https://spreecommerce.org/docs/integrations/analytics/google-analytics), [GTM](https://spreecommerce.org/docs/integrations/analytics/google-tag-manager), [Klaviyo](https://spreecommerce.org/docs/integrations/marketing/klaviyo)).-* **[Agentic Development](https://spreecommerce.org/docs/developer/agentic/overview)** — [agent skills](https://github.com/spree/agent-skills) (`npx skills add spree/agent-skills`) teaching AI coding agents Spree's conventions, a [docs MCP server](https://spreecommerce.org/docs/developer/agentic/mcp), [LLM-ready documentation](https://spreecommerce.org/docs/developer/agentic/llm-docs) (llms.txt, per-page Markdown, offline npm package), and a generated AGENTS.md/CLAUDE.md in every scaffolded project.+* **[Agentic Development](https://spreecommerce.org/docs/developer/agentic/overview)** — [agent skills](https://github.com/spree/agent-skills) teaching AI coding agents Spree's conventions and a [docs MCP server](https://spreecommerce.org/docs/developer/agentic/mcp), both set up with one command (`spree add ai`), plus [LLM-ready documentation](https://spreecommerce.org/docs/developer/agentic/llm-docs) (llms.txt, per-page Markdown, offline npm package), and a generated AGENTS.md/CLAUDE.md in every scaffolded project.## Deploymentdiff --git a/docs/developer/agentic/agent-skills.mdx b/docs/developer/agentic/agent-skills.mdxindex 87adbead8a..a624805c6c 100644--- a/docs/developer/agentic/agent-skills.mdx+++ b/docs/developer/agentic/agent-skills.mdx@@ -15,7 +15,13 @@ The skills target Spree 6. For a Spree 5 project, use the [`v0.3.0` release](htt</Note>-Projects created with [create-spree-app](/developer/create-spree-app/quickstart) install every skill during setup, unless you answer no or pass `--no-agent-skills`. To add them to any other project, run from your project directory:+Projects created with [create-spree-app](/developer/create-spree-app/quickstart) install every skill during setup, unless you answer no or pass `--no-agent-skills`. To add them to an existing create-spree-app project, run from the project directory:++```bash+npx spree add ai+```++This also connects your agent to the [docs MCP server](/developer/agentic/mcp); pass `--no-mcp` to install only the skills. In any other project, use the skills CLI directly:```bashnpx skills add spree/agent-skillsdiff --git a/docs/developer/agentic/mcp.mdx b/docs/developer/agentic/mcp.mdxindex 591597d18c..d9916c613a 100644--- a/docs/developer/agentic/mcp.mdx+++ b/docs/developer/agentic/mcp.mdx@@ -14,6 +14,17 @@ The server exposes two tools: full-text **search** across the documentation, and## Setup+In a [create-spree-app](/developer/create-spree-app/quickstart) project, one command connects Claude Code, Cursor and VS Code at once, and installs the [agent skills](/developer/agentic/agent-skills) too:++```bash+npx spree add ai # skills + docs MCP server+npx spree add ai --no-skills # docs MCP server only+```++It adds the server to `.mcp.json`, `.cursor/mcp.json` and `.vscode/mcp.json`, keeping any servers those files already list, and points the project's `AGENTS.md` at it. Running it again changes nothing. Commit the files so your team gets the same setup.++To connect a single tool by hand, or one outside a create-spree-app project:+<Tabs><Tab title="Claude Code">```bash@@ -70,5 +81,5 @@ The server exposes two tools: full-text **search** across the documentation, and| **[Agent skills](/developer/agentic/agent-skills)** | Conventions and how-to knowledge the agent should apply without searching at all |<Note>- In create-spree-app projects the generated `AGENTS.md` already points agents at the local `@spree/docs` package first — MCP complements it for anything newer than your installed docs version.+ New [create-spree-app](/developer/create-spree-app/quickstart) projects come connected (skip it with `--no-docs-mcp`) — Claude Code asks you to approve the server the first time you open the project. The project's `AGENTS.md` tells agents to search here and read pages from the local `@spree/docs` package, which matches the Spree version the project runs.</Note>diff --git a/docs/developer/agentic/overview.mdx b/docs/developer/agentic/overview.mdxindex 23f82dd284..b8d7ccd638 100644--- a/docs/developer/agentic/overview.mdx+++ b/docs/developer/agentic/overview.mdx@@ -33,8 +33,8 @@ Spree ships first-class tooling for AI-assisted development. Whether you use Cla## A typical agentic workflow1. **Scaffold** a project with `npx create-spree-app@latest my-store` — it generates an `AGENTS.md`, installs `@spree/docs` for local reference, and wires up the CLI.-2. **Keep the agent skills** the scaffold offers to install (or add them later with `npx skills add spree/agent-skills`) so your agent knows the decision tree for customizations (subscriber vs decorator vs dependency injection vs generator) before it writes a line of code.-3. **Connect the docs MCP server** so questions the skills don't cover get answered from the live documentation.+2. **Say yes to "Set up AI coding agents?"** — the scaffold installs the agent skills, so your agent knows the decision tree for customizations (subscriber vs decorator vs dependency injection vs generator) before it writes a line of code, and connects it to the docs MCP server, so questions the skills don't cover get answered from the live documentation. In an existing project, run `spree add ai` to get both.+3. **Commit the agent files** (`.agents/skills/`, `.mcp.json`, `.cursor/mcp.json`, `.vscode/mcp.json`) so everyone on the team works with the same setup.4. **Let the agent work** — generate an API resource (`spree generate api_resource Brand name:string`), customize checkout, integrate a payment provider, or run an upgrade with `spree upgrade`.<Tip>diff --git a/docs/developer/cli/quickstart.mdx b/docs/developer/cli/quickstart.mdxindex 8c2cf885a4..2cc1b98b9d 100644--- a/docs/developer/cli/quickstart.mdx+++ b/docs/developer/cli/quickstart.mdx@@ -130,6 +130,18 @@ After ejecting, the Docker image is built from `server/Dockerfile`. Edit files iSee [Customizing the Backend](/developer/create-spree-app/quickstart#customizing-the-backend) for details on what you can customize.+### `spree add`++Add an optional part to an existing project.++```bash+spree add dashboard # the Admin Dashboard app in apps/dashboard/, to customize it+spree add seller-dashboard # the marketplace Seller Panel in apps/seller-dashboard/+spree add ai # Spree agent skills + the docs MCP server for coding agents+```++`spree add ai` installs the [Spree agent skills](/developer/agentic/agent-skills) and connects Claude Code, Cursor and VS Code to the [docs MCP server](/developer/agentic/mcp). It keeps the MCP servers your config files already list and is safe to re-run. Pass `--no-skills` or `--no-mcp` to set up only one of the two.+### `spree logs`Stream service logs.@@ -373,4 +385,4 @@ spree task spree:price_history:prune## Pair with AI agents-The CLI's predictable command surface is what AI coding agents drive when working on Spree projects. The [Spree agent skills](/developer/agentic/agent-skills) teach agents these commands and conventions, and the Claude Code plugin adds `/spree:doctor` (stack diagnosis) and `/spree:audit-upgrade` (upgrade-readiness audit) on top. See [Agentic Development](/developer/agentic/overview).+The CLI's predictable command surface is what AI coding agents drive when working on Spree projects. The [Spree agent skills](/developer/agentic/agent-skills) teach agents these commands and conventions (install them with `spree add ai`), and the Claude Code plugin adds `/spree:doctor` (stack diagnosis) and `/spree:audit-upgrade` (upgrade-readiness audit) on top. See [Agentic Development](/developer/agentic/overview).diff --git a/docs/developer/create-spree-app/quickstart.mdx b/docs/developer/create-spree-app/quickstart.mdxindex e4f487a6ad..69747803e6 100644--- a/docs/developer/create-spree-app/quickstart.mdx+++ b/docs/developer/create-spree-app/quickstart.mdx@@ -14,7 +14,7 @@ The CLI walks you through an interactive setup:1. Include **Next.js Storefront** (default: yes)2. Include the **Seller Panel**, for marketplaces (default: yes)-3. Install the **[Spree agent skills](/developer/agentic/agent-skills)**, which teach AI coding agents how to work with Spree (default: yes)+3. **Set up AI coding agents** (default: yes) — installs the [Spree agent skills](/developer/agentic/agent-skills), which teach agents how to work with Spree, and connects Claude Code, Cursor and VS Code to the [Spree docs MCP server](/developer/agentic/mcp) so they can search the latest docs4. **Start Docker services** immediately (default: yes)Once complete, your store is running at [http://localhost:3000](http://localhost:3000) — setup pulls the latest Spree image, seeds the database, and configures API keys, then prints a summary with your admin credentials and keys. If you skipped starting services, the first `pnpm dev` completes setup automatically.@@ -42,6 +42,8 @@ npx create-spree-app@latest my-store --no-seller-dashboard --no-storefront --no-| `--no-storefront` | Skip Next.js storefront setup || `--agent-skills` | Install the Spree agent skills without asking || `--no-agent-skills` | Skip installing the Spree agent skills |+| `--docs-mcp` | Connect coding agents to the Spree docs MCP server without asking |+| `--no-docs-mcp` | Skip connecting coding agents to the Spree docs MCP server || `--no-start` | Don't start Docker services after scaffolding || `--port <number>` | Port for the Spree backend (default: `3000`) || `--use-npm` | Use npm as package manager |@@ -80,6 +82,9 @@ my-store/├── .gitignore├── package.json # Scripts and the pinned @spree/cli├── .agents/skills/ # Spree agent skills (unless --no-agent-skills)+├── .mcp.json # Spree docs MCP server for Claude Code (unless --no-docs-mcp)+├── .cursor/mcp.json # …for Cursor+├── .vscode/mcp.json # …for VS Code (Copilot)├── AGENTS.md # Instructions for coding agents├── CLAUDE.md # Imports AGENTS.md for Claude Code└── README.md # How to run everything@@ -124,6 +129,7 @@ The project includes [@spree/cli](/developer/cli/quickstart) for managing your S| `spree eject` | Switch from prebuilt image to building from `server/` || `spree add dashboard` | Add the Admin Dashboard to an existing project, to customize it || `spree add seller-dashboard` | Add the marketplace seller panel to an existing project |+| `spree add ai` | Install the Spree agent skills and connect coding agents to the Spree docs MCP server || `spree build --production` | Build the production image — the Spree API plus your dashboard, in one || `spree logs` | View backend logs || `spree logs worker` | View background jobs logs |diff --git a/docs/developer/getting-started/quickstart.mdx b/docs/developer/getting-started/quickstart.mdxindex af66b7f4e5..3995e9712f 100644--- a/docs/developer/getting-started/quickstart.mdx+++ b/docs/developer/getting-started/quickstart.mdx@@ -71,7 +71,7 @@ See the [Spree CLI guide](/developer/cli/quickstart) for all commands and the [AIn a hurry? Jump straight to the [tutorial](/developer/tutorial/introduction) to build a feature end to end, the [Next.js Storefront](/developer/storefront/nextjs/quickstart) to put a storefront in front of it, or the [API reference](/api-reference/admin-api/introduction) to see what you can do with the Admin API.<Tip>- Using an AI coding agent? `create-spree-app` installs the [Spree agent skills](/developer/agentic/agent-skills) unless you said no — if you skipped them, run `npx skills add spree/agent-skills` in your project. They teach your agent the customization patterns before you write a line of code. See [Agentic Development](/developer/agentic/overview).+ Using an AI coding agent? `create-spree-app` installs the [Spree agent skills](/developer/agentic/agent-skills) and connects your agent to the [docs MCP server](/developer/agentic/mcp) unless you said no — if you skipped them, run `npx spree add ai` in your project. Your agent then knows the customization patterns before you write a line of code. See [Agentic Development](/developer/agentic/overview).</Tip>---diff --git a/docs/developer/tutorial/introduction.mdx b/docs/developer/tutorial/introduction.mdxindex efedb4f85f..7baaa0e310 100644--- a/docs/developer/tutorial/introduction.mdx+++ b/docs/developer/tutorial/introduction.mdx@@ -63,5 +63,5 @@ my-store/</Note><Tip>- Using an AI coding agent? Install the [Spree agent skills](/developer/agentic/agent-skills) (`npx skills add spree/agent-skills`) and connect the [docs MCP server](/developer/agentic/mcp) before starting. Your agent will know the conventions this tutorial teaches and can follow along with you. See [AI-assisted development](/developer/agentic/overview).+ Using an AI coding agent? Run `npx spree add ai` in your project before starting — it installs the [Spree agent skills](/developer/agentic/agent-skills) and connects the [docs MCP server](/developer/agentic/mcp). Your agent will know the conventions this tutorial teaches and can follow along with you. See [AI-assisted development](/developer/agentic/overview).</Tip>diff --git a/packages/cli/README.md b/packages/cli/README.mdindex 8184d6bceb..abebfdf93e 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -21,6 +21,7 @@ Run from your Spree project directory:| `spree eject` | Switch from the prebuilt image to building from `backend/` || `spree add dashboard` | Add the Admin Dashboard to an existing project, to customize it || `spree add seller-dashboard` | Add the marketplace seller panel to an existing project |+| `spree add ai` | Install the Spree agent skills and connect coding agents to the Spree docs MCP server || `spree build --production` | Build the production image — the Spree API plus your dashboard, in one || `spree console` / `spree shell` / `spree logs` | Rails console, container shell, log tailing || `spree migrate` / `spree seed` / `spree sample-data` | Database tasks |diff --git a/packages/cli/src/commands/add.ts b/packages/cli/src/commands/add.tsindex 24e3f62342..2fe8a57cfb 100644--- a/packages/cli/src/commands/add.ts+++ b/packages/cli/src/commands/add.ts@@ -8,6 +8,13 @@ import pc from 'picocolors'import { isNotFound } from '../config.js'import { DASHBOARD_PORT, SELLER_DASHBOARD_PORT } from '../constants.js'import { detectProject } from '../context.js'+import {+ AGENT_SKILLS_REPO,+ addDocsMcpServer,+ addDocsSectionToAgentInstructions,+ dlxCommand,+ installAgentSkills,+} from '../lib/ai.js'import type { ProjectContext } from '../types.js'/**@@ -55,26 +62,54 @@ interface AddDashboardOptions {quiet?: boolean}+interface AddAiOptions {+ /** Install the Spree agent skills. */+ skills: boolean+ /** Connect coding agents to the Spree docs MCP server. */+ mcp: boolean+ /** Skip the final summary note — create-spree-app prints its own. */+ quiet?: boolean+}+// `spree add <thing>` — bolt an optional component onto an existing project.-// Dashboard and seller panel for now; storefront parity is planned (see-// docs/plans/5.6-project-layout-and-dashboard.md).+// Dashboard, seller panel and the AI coding agent setup for now; storefront+// parity is planned (see docs/plans/5.6-project-layout-and-dashboard.md).export function registerAddCommand(program: Command) {program.command('add').description('Add an optional component to your project')- .argument('<thing>', 'Component to add: dashboard or seller-dashboard')+ .argument('<thing>', 'Component to add: dashboard, seller-dashboard or ai').option('--template <src>','Starter template: git URL or local path (default: the template bundled with the CLI; env SPREE_DASHBOARD_TEMPLATE / SPREE_SELLER_DASHBOARD_TEMPLATE overrides)',).option('--no-install', 'Skip dependency install')+ .option('--no-skills', 'ai: skip installing the Spree agent skills')+ .option('--no-mcp', 'ai: skip connecting coding agents to the Spree docs MCP server').option('--quiet', 'Skip the final summary note (for wrapping tools that print their own)').action(- async (thing: string, flags: { template?: string; install: boolean; quiet?: boolean }) => {+ async (+ thing: string,+ flags: {+ template?: string+ install: boolean+ skills: boolean+ mcp: boolean+ quiet?: boolean+ },+ ) => {+ if (thing === 'ai') {+ if (!flags.quiet) p.intro(pc.bgCyan(pc.black(' Spree AI coding agents ')))+ const ready = await addAi(detectProject(), flags)+ if (!flags.quiet) p.outro(ready ? 'Done!' : 'Done, with warnings.')+ if (!ready) process.exit(1)+ return+ }+const app = APPS[thing]if (!app) {console.error(- `\n${pc.red('Error:')} Unknown component: ${thing}. Try: ${Object.keys(APPS).join(', ')}\n`,+ `\n${pc.red('Error:')} Unknown component: ${thing}. Try: ${[...Object.keys(APPS), 'ai'].join(', ')}\n`,)process.exit(2)}@@ -92,6 +127,72 @@ export function registerAddCommand(program: Command) {)}+/**+ * Set a project up for AI coding agents: connect each agent to the Spree docs+ * MCP server, point the agent instructions at it, and install the Spree agent+ * skills. Safe to re-run — servers already configured are kept as they are.+ *+ * @return false when a step failed and the project is only partly set up+ */+export async function addAi(ctx: ProjectContext, opts: AddAiOptions): Promise<boolean> {+ let ready = true++ if (opts.mcp) {+ const outcomes = addDocsMcpServer(ctx.projectDir)+ for (const [file, outcome] of Object.entries(outcomes)) {+ if (outcome === 'unreadable' || outcome === 'unwritable') {+ ready = false+ p.log.warn(+ `Could not ${outcome === 'unreadable' ? 'read' : 'write'} ${pc.bold(file)}${outcome === 'unreadable' ? ' as JSON' : ''}, so it was left as it is. Add the server by hand: https://spreecommerce.org/docs/developer/agentic/mcp`,+ )+ } else if (!opts.quiet) {+ p.log.info(+ outcome === 'added'+ ? `Added the Spree docs MCP server to ${pc.bold(file)}`+ : `${pc.bold(file)} already lists the Spree docs MCP server`,+ )+ }+ }+ const instructions = addDocsSectionToAgentInstructions(ctx.projectDir)+ for (const file of instructions.updated) {+ if (!opts.quiet) p.log.info(`Pointed ${pc.bold(file)} at the Spree docs MCP server`)+ }+ for (const file of instructions.failed) {+ ready = false+ p.log.warn(`Could not update ${pc.bold(file)}, so agents may not know about the docs server.`)+ }+ }++ if (opts.skills) {+ const packageManager = detectPackageManager(ctx.projectDir, ctx.projectDir)+ const s = p.spinner()+ s.start('Installing Spree agent skills...')+ try {+ await installAgentSkills(ctx.projectDir, packageManager)+ s.stop('Spree agent skills installed.')+ } catch (err) {+ ready = false+ s.stop(pc.yellow('Spree agent skills were not installed.'))+ p.log.warn(+ `Install them later with ${pc.bold(`${dlxCommand(packageManager).join(' ')} skills add ${AGENT_SKILLS_REPO}`)}.\n${err instanceof Error ? err.message : String(err)}`,+ )+ }+ }++ if (!opts.quiet && opts.mcp) {+ p.note(+ [+ 'Claude Code asks you to approve the docs server the first time you open',+ 'the project; Cursor and VS Code list it in their MCP settings.',+ 'Commit the new files so your team gets the same setup.',+ ].join('\n'),+ 'AI coding agents set up',+ )+ }++ return ready+}+/*** Clone the dashboard starter into `apps/dashboard/` and point it at the* project's API. Writes no credentials — the dashboard authenticates adminsdiff --git a/packages/cli/src/lib/ai.ts b/packages/cli/src/lib/ai.tsnew file mode 100644index 0000000000..81f1aa7a32--- /dev/null+++ b/packages/cli/src/lib/ai.ts@@ -0,0 +1,193 @@+import fs from 'node:fs'+import path from 'node:path'+import { execa } from 'execa'+import { isNotFound } from '../config.js'++export const DOCS_MCP_URL = 'https://spreecommerce.org/docs/mcp'+export const DOCS_MCP_SERVER_NAME = 'spree-docs'+export const AGENT_SKILLS_REPO = 'spree/agent-skills'++/**+ * Project-level MCP files of each coding agent that reads one. Claude Code and+ * Cursor share a format; VS Code names its root `servers` and needs `type`.+ */+const MCP_CONFIGS = [+ { file: '.mcp.json', root: 'mcpServers', entry: { type: 'http', url: DOCS_MCP_URL } },+ { file: '.cursor/mcp.json', root: 'mcpServers', entry: { url: DOCS_MCP_URL } },+ { file: '.vscode/mcp.json', root: 'servers', entry: { type: 'http', url: DOCS_MCP_URL } },+] as const++export type McpConfigOutcome = 'added' | 'present' | 'unreadable' | 'unwritable'++/**+ * Add the Spree docs MCP server to every agent's project config, keeping the+ * servers already listed there. A file that is not plain JSON (VS Code allows+ * comments) is reported as `unreadable` and left untouched — never rewritten.+ * A file that cannot be written is reported as `unwritable`; the others are+ * still updated.+ *+ * @param projectDir the project root+ * @return each config file's path with what happened to it+ */+export function addDocsMcpServer(projectDir: string): Record<string, McpConfigOutcome> {+ const outcomes: Record<string, McpConfigOutcome> = {}++ for (const { file, root, entry } of MCP_CONFIGS) {+ const filePath = path.join(projectDir, file)+ let config: Record<string, unknown> = {}+ try {+ config = JSON.parse(fs.readFileSync(filePath, 'utf-8'))+ } catch (error) {+ if (!isNotFound(error)) {+ outcomes[file] = 'unreadable'+ continue+ }+ }+ if (!isObject(config) || (config[root] !== undefined && !isObject(config[root]))) {+ outcomes[file] = 'unreadable'+ continue+ }++ const servers = (config[root] as Record<string, unknown> | undefined) ?? {}+ if (servers[DOCS_MCP_SERVER_NAME] !== undefined) {+ outcomes[file] = 'present'+ continue+ }++ config[root] = { ...servers, [DOCS_MCP_SERVER_NAME]: entry }+ try {+ fs.mkdirSync(path.dirname(filePath), { recursive: true })+ writeFileAtomically(filePath, `${JSON.stringify(config, null, 2)}\n`)+ outcomes[file] = 'added'+ } catch {+ outcomes[file] = 'unwritable'+ }+ }++ return outcomes+}++// Projects scaffolded before `@spree/docs` was a dependency have no local+// copy, so the section only points at one that is installed.+function docsSection(hasLocalDocs: boolean): string {+ const lines = [+ '## Searching the Spree docs',+ '',+ `The \`${DOCS_MCP_SERVER_NAME}\` MCP server (configured in \`.mcp.json\`, \`.cursor/mcp.json\` and`,+ '`.vscode/mcp.json`) searches the latest published Spree docs.',+ ]+ if (hasLocalDocs) {+ lines.push(+ 'Use it when you do not know which page covers a topic, then read the page from',+ '`node_modules/@spree/docs/dist/`. The server can be ahead of the Spree version this',+ 'project runs — when the two disagree, the local files are right for this project.',+ )+ } else {+ lines.push('Search it before relying on what you remember about Spree.')+ }+ lines.push('')+ return lines.join('\n')+}++function hasLocalDocs(projectDir: string): boolean {+ try {+ const pkg = JSON.parse(fs.readFileSync(path.join(projectDir, 'package.json'), 'utf-8'))+ return Boolean(pkg.dependencies?.['@spree/docs'] ?? pkg.devDependencies?.['@spree/docs'])+ } catch {+ return false+ }+}++/**+ * Append the docs-search section to each agent instructions file an agent+ * reads on its own: `AGENTS.md`, and `CLAUDE.md` unless it only imports+ * `AGENTS.md` (Claude Code reads CLAUDE.md alone). Files that already mention+ * the server are left as they are, and a file that cannot be written does+ * not stop the others.+ *+ * @param projectDir the project root+ * @return the files that were updated, and those that could not be+ */+export function addDocsSectionToAgentInstructions(projectDir: string): {+ updated: string[]+ failed: string[]+} {+ const updated: string[] = []+ const failed: string[] = []+ const section = docsSection(hasLocalDocs(projectDir))++ for (const file of ['AGENTS.md', 'CLAUDE.md']) {+ const filePath = path.join(projectDir, file)+ if (!fs.existsSync(filePath)) continue++ try {+ const content = fs.readFileSync(filePath, 'utf-8')+ if (content.includes(DOCS_MCP_SERVER_NAME)) continue+ if (file === 'CLAUDE.md' && /^@AGENTS\.md\s*$/m.test(content)) continue++ const separator = content.endsWith('\n\n') ? '' : content.endsWith('\n') ? '\n' : '\n\n'+ writeFileAtomically(filePath, `${content}${separator}${section}`)+ updated.push(file)+ } catch {+ failed.push(file)+ }+ }+ return { updated, failed }+}++/**+ * Runner for a one-off remote package. Yarn 1 has no `dlx`, and a lockfile+ * does not say which Yarn a project uses, so Yarn projects use `npx`, which+ * ships with every Node install.+ */+export function dlxCommand(packageManager: string): string[] {+ if (packageManager === 'pnpm') return ['pnpm', 'dlx']+ return ['npx', '--yes']+}++/**+ * Install every Spree agent skill for each coding agent the `skills` CLI+ * detects, without prompting.+ *+ * @param projectDir the project root+ * @param packageManager the project's package manager, which runs the `skills` CLI+ */+export async function installAgentSkills(+ projectDir: string,+ packageManager: string,+): Promise<void> {+ const [command, ...runnerArgs] = dlxCommand(packageManager)+ await execa(+ command,+ [...runnerArgs, 'skills', 'add', AGENT_SKILLS_REPO, '--skill', '*', '--yes'],+ // A stalled download must fail rather than hang the command.+ { cwd: projectDir, stdio: 'ignore', timeout: 120_000 },+ )+}++// These files hold the developer's own content, so a failed write must leave+// the original whole: write a sibling file, then rename it over the target.+// The sibling takes the original's permissions, so a private file stays private.+function writeFileAtomically(filePath: string, content: string): void {+ let mode: number | undefined+ if (fs.existsSync(filePath)) {+ // A rename replaces even a read-only file, so refuse those up front.+ fs.accessSync(filePath, fs.constants.W_OK)+ mode = fs.statSync(filePath).mode & 0o777+ }++ const temporaryPath = `${filePath}.${process.pid}.tmp`+ try {+ fs.writeFileSync(temporaryPath, content, { mode: mode ?? 0o666 })+ // The mode given on creation is narrowed by the umask; set it exactly.+ if (mode !== undefined) fs.chmodSync(temporaryPath, mode)+ fs.renameSync(temporaryPath, filePath)+ } catch (error) {+ fs.rmSync(temporaryPath, { force: true })+ throw error+ }+}++function isObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}diff --git a/packages/cli/tests/add-ai.test.ts b/packages/cli/tests/add-ai.test.tsnew file mode 100644index 0000000000..934730bece--- /dev/null+++ b/packages/cli/tests/add-ai.test.ts@@ -0,0 +1,213 @@+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { execa } from 'execa'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { addAi } from '../src/commands/add.js'+import type { ProjectContext } from '../src/types.js'++vi.mock('execa', () => ({ execa: vi.fn(async () => ({})) }))++const URL = 'https://spreecommerce.org/docs/mcp'++describe('addAi', () => {+ let projectDir: string++ function ctx(): ProjectContext {+ return { mode: 'docker', projectDir, port: 3000 }+ }++ function read(file: string): string {+ return fs.readFileSync(path.join(projectDir, file), 'utf-8')+ }++ function write(file: string, content: string): void {+ fs.mkdirSync(path.dirname(path.join(projectDir, file)), { recursive: true })+ fs.writeFileSync(path.join(projectDir, file), content)+ }++ beforeEach(() => {+ projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'spree-add-ai-'))+ write('docker-compose.yml', 'services: {}\n')+ vi.mocked(execa).mockClear()+ })++ afterEach(() => {+ fs.rmSync(projectDir, { recursive: true, force: true })+ })++ it('connects each coding agent to the docs MCP server', async () => {+ expect(await addAi(ctx(), { skills: false, mcp: true, quiet: true })).toBe(true)++ expect(JSON.parse(read('.mcp.json'))).toEqual({+ mcpServers: { 'spree-docs': { type: 'http', url: URL } },+ })+ expect(JSON.parse(read('.cursor/mcp.json'))).toEqual({+ mcpServers: { 'spree-docs': { url: URL } },+ })+ expect(JSON.parse(read('.vscode/mcp.json'))).toEqual({+ servers: { 'spree-docs': { type: 'http', url: URL } },+ })+ })++ // Existing projects already list their own servers — adding ours must not+ // drop them, and re-running must not duplicate or rewrite ours.+ it('keeps the servers a project already lists and is safe to re-run', async () => {+ const own = { mcpServers: { github: { url: 'https://example.com/mcp' } }, other: true }+ write('.mcp.json', JSON.stringify(own))++ await addAi(ctx(), { skills: false, mcp: true, quiet: true })+ const once = read('.mcp.json')+ await addAi(ctx(), { skills: false, mcp: true, quiet: true })++ expect(read('.mcp.json')).toBe(once)+ expect(JSON.parse(once)).toEqual({+ mcpServers: { ...own.mcpServers, 'spree-docs': { type: 'http', url: URL } },+ other: true,+ })+ })++ // VS Code allows comments in mcp.json; rewriting it from a failed parse+ // would wipe the developer's own servers.+ it('leaves a config it cannot parse untouched and reports the failure', async () => {+ const commented = '{\n // my servers\n "servers": {}\n}\n'+ write('.vscode/mcp.json', commented)++ expect(await addAi(ctx(), { skills: false, mcp: true, quiet: true })).toBe(false)++ expect(read('.vscode/mcp.json')).toBe(commented)+ expect(JSON.parse(read('.mcp.json')).mcpServers['spree-docs']).toBeDefined()+ })++ it('points the agent instructions at the docs server once', async () => {+ write('AGENTS.md', '# My project\n')+ write('CLAUDE.md', '@AGENTS.md\n')++ await addAi(ctx(), { skills: false, mcp: true, quiet: true })+ await addAi(ctx(), { skills: false, mcp: true, quiet: true })++ expect(read('AGENTS.md').match(/## Searching the Spree docs/g)).toHaveLength(1)+ expect(read('AGENTS.md')).toMatch(/^# My project\n\n## Searching the Spree docs/)+ expect(read('CLAUDE.md')).toBe('@AGENTS.md\n')+ })++ // Claude Code reads CLAUDE.md alone, so one that does not import AGENTS.md+ // needs the section itself.+ it('also updates a CLAUDE.md that does not import AGENTS.md', async () => {+ write('AGENTS.md', '# Shared\n')+ write('CLAUDE.md', '# Claude only\n')++ await addAi(ctx(), { skills: false, mcp: true, quiet: true })++ expect(read('AGENTS.md')).toContain('`spree-docs` MCP server')+ expect(read('CLAUDE.md')).toContain('`spree-docs` MCP server')+ })++ it('installs the skills with npx in Yarn projects, since Yarn 1 has no dlx', async () => {+ write('yarn.lock', '')++ await addAi(ctx(), { skills: true, mcp: false, quiet: true })++ expect(vi.mocked(execa)).toHaveBeenCalledWith(+ 'npx',+ ['--yes', 'skills', 'add', 'spree/agent-skills', '--skill', '*', '--yes'],+ expect.anything(),+ )+ })++ it('falls back to CLAUDE.md in projects without AGENTS.md', async () => {+ write('CLAUDE.md', '# Older project\n')++ await addAi(ctx(), { skills: false, mcp: true, quiet: true })++ expect(read('CLAUDE.md')).toContain('`spree-docs` MCP server')+ })++ it('points at the local docs only when the project installs them', async () => {+ write('AGENTS.md', '# Without local docs\n')+ await addAi(ctx(), { skills: false, mcp: true, quiet: true })+ expect(read('AGENTS.md')).not.toContain('node_modules/@spree/docs')++ write('AGENTS.md', '# With local docs\n')+ write('package.json', JSON.stringify({ dependencies: { '@spree/docs': 'latest' } }))+ await addAi(ctx(), { skills: false, mcp: true, quiet: true })+ expect(read('AGENTS.md')).toContain('node_modules/@spree/docs/dist/')+ })++ // One file that cannot be written must not stop the rest of the setup, and+ // must be left whole. The failure is injected: file permissions do not+ // stop a test run as root.+ it('still installs the skills when an instructions file cannot be written', async () => {+ write('AGENTS.md', '# Mine\n')+ const rename = fs.renameSync+ const failure = vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => {+ if (String(to).endsWith('AGENTS.md')) throw new Error('disk full')+ rename(from, to)+ })++ try {+ expect(await addAi(ctx(), { skills: true, mcp: true, quiet: true })).toBe(false)+ } finally {+ failure.mockRestore()+ }++ expect(read('AGENTS.md')).toBe('# Mine\n')+ expect(fs.readdirSync(projectDir).filter((file) => file.endsWith('.tmp'))).toEqual([])+ expect(JSON.parse(read('.mcp.json')).mcpServers['spree-docs']).toBeDefined()+ expect(vi.mocked(execa)).toHaveBeenCalledWith(+ expect.any(String),+ expect.arrayContaining(['skills', 'add', 'spree/agent-skills']),+ expect.anything(),+ )+ })++ it('keeps the permissions of the files it updates', async () => {+ write('.mcp.json', '{}')+ write('AGENTS.md', '# Private\n')+ fs.chmodSync(path.join(projectDir, '.mcp.json'), 0o600)+ fs.chmodSync(path.join(projectDir, 'AGENTS.md'), 0o640)++ await addAi(ctx(), { skills: false, mcp: true, quiet: true })++ const mode = (file: string) => fs.statSync(path.join(projectDir, file)).mode & 0o777+ expect(read('.mcp.json')).toContain('spree-docs')+ expect(mode('.mcp.json')).toBe(0o600)+ expect(mode('AGENTS.md')).toBe(0o640)+ })++ it('does not replace a read-only instructions file', async () => {+ write('AGENTS.md', '# Read-only\n')+ const access = vi.spyOn(fs, 'accessSync').mockImplementation(() => {+ throw Object.assign(new Error('permission denied'), { code: 'EACCES' })+ })++ try {+ expect(await addAi(ctx(), { skills: false, mcp: true, quiet: true })).toBe(false)+ } finally {+ access.mockRestore()+ }++ expect(read('AGENTS.md')).toBe('# Read-only\n')+ })++ it("installs the agent skills with the project's package manager", async () => {+ write('pnpm-lock.yaml', '')++ expect(await addAi(ctx(), { skills: true, mcp: false, quiet: true })).toBe(true)++ expect(vi.mocked(execa)).toHaveBeenCalledWith(+ 'pnpm',+ ['dlx', 'skills', 'add', 'spree/agent-skills', '--skill', '*', '--yes'],+ expect.objectContaining({ cwd: projectDir }),+ )+ expect(fs.existsSync(path.join(projectDir, '.mcp.json'))).toBe(false)+ })++ it('reports a failed skills install without undoing the docs server', async () => {+ vi.mocked(execa).mockRejectedValueOnce(new Error('network down'))++ expect(await addAi(ctx(), { skills: true, mcp: true, quiet: true })).toBe(false)++ expect(JSON.parse(read('.mcp.json')).mcpServers['spree-docs']).toBeDefined()+ })+})diff --git a/packages/create-spree-app/README.md b/packages/create-spree-app/README.mdindex 2663ab1f15..8779d42805 100644--- a/packages/create-spree-app/README.md+++ b/packages/create-spree-app/README.md@@ -15,7 +15,9 @@ npx create-spree-app my-store| `--no-seller-dashboard` | Skip the marketplace seller panel (also available later via `spree add seller-dashboard`) || `--no-storefront` | Skip Next.js storefront setup || `--agent-skills` | Install the Spree agent skills without asking |-| `--no-agent-skills` | Skip installing the Spree agent skills |+| `--no-agent-skills` | Skip installing the Spree agent skills (also available later via `spree add ai`) |+| `--docs-mcp` | Connect coding agents to the Spree docs MCP server without asking |+| `--no-docs-mcp` | Skip connecting coding agents to the Spree docs MCP server (also available later via `spree add ai`) || `--no-start` | Don't start Docker services (the first `dev` run completes setup instead) || `--port <number>` | Port for the Spree backend (default: `3000`) || `--use-npm` / `--use-yarn` / `--use-pnpm` | Package manager (auto-detected from how you run the command) |diff --git a/packages/create-spree-app/src/agent-skills.ts b/packages/create-spree-app/src/agent-skills.tsdeleted file mode 100644index d7c6f8881c..0000000000--- a/packages/create-spree-app/src/agent-skills.ts+++ /dev/null@@ -1,24 +0,0 @@-import { execa } from 'execa'-import { AGENT_SKILLS_REPO } from './constants.js'-import type { PackageManager } from './types.js'-import { dlxCommand } from './utils.js'--/**- * Install every Spree agent skill into the project, for each coding agent the- * `skills` CLI detects, without prompting.- *- * @param projectDir absolute path to the generated project- * @param pm the scaffold's package manager, which runs the `skills` CLI- */-export async function installAgentSkills(projectDir: string, pm: PackageManager): Promise<void> {- const [command, ...runnerArgs] = dlxCommand(pm).split(' ')- // npx asks before downloading a package it has not cached; --yes answers it.- if (pm === 'npm') runnerArgs.push('--yes')-- await execa(- command,- [...runnerArgs, 'skills', 'add', AGENT_SKILLS_REPO, '--skill', '*', '--yes'],- // A stalled download must fail, so the scaffold can warn and move on.- { cwd: projectDir, stdio: 'ignore', timeout: 120_000 },- )-}diff --git a/packages/create-spree-app/src/agents.ts b/packages/create-spree-app/src/agents.tsnew file mode 100644index 0000000000..c6a7389680--- /dev/null+++ b/packages/create-spree-app/src/agents.ts@@ -0,0 +1,21 @@+import { execa } from 'execa'+import type { PackageManager } from './types.js'+import { runCommand } from './utils.js'++/**+ * Set the project up for AI coding agents by delegating to the project-local+ * CLI: `spree add ai` installs the Spree agent skills and connects each agent+ * to the Spree docs MCP server — the same command existing projects run.+ *+ * @param projectDir absolute path to the generated project+ * @param opts which halves to set up, and the scaffold's package manager+ */+export async function setupAgents(+ projectDir: string,+ opts: { skills: boolean; mcp: boolean; packageManager: PackageManager },+): Promise<void> {+ const args = ['spree', 'add', 'ai', '--quiet']+ if (!opts.skills) args.push('--no-skills')+ if (!opts.mcp) args.push('--no-mcp')+ await execa(runCommand(opts.packageManager), args, { cwd: projectDir, stdio: 'inherit' })+}diff --git a/packages/create-spree-app/src/constants.ts b/packages/create-spree-app/src/constants.tsindex 01619ec76a..bfc008e2b7 100644--- a/packages/create-spree-app/src/constants.ts+++ b/packages/create-spree-app/src/constants.ts@@ -4,9 +4,7 @@ export const DASHBOARD_PORT = 5173// Seller panel dev server; 5174 matches @spree/cli's own default.export const SELLER_DASHBOARD_PORT = 5174-export const DOCS_MCP_URL = 'https://spreecommerce.org/docs/mcp'export const STOREFRONT_REPO = 'https://github.com/spree/storefront.git'-export const AGENT_SKILLS_REPO = 'spree/agent-skills'/*** pnpm pinned into the generated root package.json's `packageManager` field.diff --git a/packages/create-spree-app/src/index.ts b/packages/create-spree-app/src/index.tsindex 87fd2291f3..17ac9f0d3b 100644--- a/packages/create-spree-app/src/index.ts+++ b/packages/create-spree-app/src/index.ts@@ -20,6 +20,8 @@ const program = new Command().option('--no-storefront', 'skip Next.js storefront setup').option('--agent-skills', 'install the Spree agent skills without asking').option('--no-agent-skills', 'skip installing the Spree agent skills')+ .option('--docs-mcp', 'connect coding agents to the Spree docs MCP server without asking')+ .option('--no-docs-mcp', 'skip connecting coding agents to the Spree docs MCP server')// Deprecated: the dashboard is included by default. Hidden, kept so// existing scripts keep working..addOption(new Option('--react-dashboard').hideHelp())@@ -49,6 +51,7 @@ const program = new Command()flags.sellerDashboard === undefined ? undefined : flags.sellerDashboard === false,noDashboard: flags.dashboard === false,noAgentSkills: flags.agentSkills === undefined ? undefined : flags.agentSkills === false,+ noDocsMcp: flags.docsMcp === undefined ? undefined : flags.docsMcp === false,noStart: flags.start === false ? true : undefined,packageManager,})diff --git a/packages/create-spree-app/src/prompts.ts b/packages/create-spree-app/src/prompts.tsindex 6d7ca7f090..afe2481846 100644--- a/packages/create-spree-app/src/prompts.ts+++ b/packages/create-spree-app/src/prompts.ts@@ -8,6 +8,7 @@ interface PromptFlags {noSellerDashboard?: booleannoDashboard?: booleannoAgentSkills?: boolean+ noDocsMcp?: booleannoStart?: booleanpackageManager?: PackageManager}@@ -69,21 +70,24 @@ export async function runPrompts(sellerDashboard = sellerResult}- let agentSkills: boolean- if (flags.noAgentSkills !== undefined) {- agentSkills = !flags.noAgentSkills- } else {- const skillsResult = await p.confirm({- message: `Install Spree agent skills?\n${pc.dim('Teaches AI coding agents (Claude Code, Codex, Cursor, Copilot and others) how to work with Spree')}`,+ // One question covers both agent conveniences. Passing either flag means the+ // run is scripted, so the other half takes its default instead of asking —+ // scripts that only pass --no-agent-skills must not start blocking on input.+ let agentSetup = true+ if (flags.noAgentSkills === undefined && flags.noDocsMcp === undefined) {+ const agentResult = await p.confirm({+ message: `Set up AI coding agents?\n${pc.dim('Installs the Spree agent skills (Claude Code, Codex, Cursor, Copilot and others) and connects Claude Code, Cursor and VS Code to the Spree docs')}`,initialValue: true,})- if (p.isCancel(skillsResult)) {+ if (p.isCancel(agentResult)) {p.cancel('Setup cancelled.')process.exit(0)}- agentSkills = skillsResult+ agentSetup = agentResult}+ const agentSkills = flags.noAgentSkills === undefined ? agentSetup : !flags.noAgentSkills+ const docsMcp = flags.noDocsMcp === undefined ? agentSetup : !flags.noDocsMcplet start: booleanif (flags.noStart !== undefined) {@@ -107,6 +111,7 @@ export async function runPrompts(dashboard,sellerDashboard,agentSkills,+ docsMcp,start,packageManager: flags.packageManager ?? 'npm',}diff --git a/packages/create-spree-app/src/scaffold.ts b/packages/create-spree-app/src/scaffold.tsindex ac1c9dc42a..ce9711f638 100644--- a/packages/create-spree-app/src/scaffold.ts+++ b/packages/create-spree-app/src/scaffold.ts@@ -3,14 +3,8 @@ import path from 'node:path'import * as p from '@clack/prompts'import { execa } from 'execa'import pc from 'picocolors'-import { installAgentSkills } from './agent-skills.js'-import {- AGENT_SKILLS_REPO,- DASHBOARD_PORT,- DOCS_MCP_URL,- SELLER_DASHBOARD_PORT,- STOREFRONT_REPO,-} from './constants.js'+import { setupAgents } from './agents.js'+import { DASHBOARD_PORT, SELLER_DASHBOARD_PORT, STOREFRONT_REPO } from './constants.js'import { scaffoldApp } from './dashboard.js'import { downloadServer } from './server.js'import { installRootDeps, scaffoldStorefront } from './storefront.js'@@ -22,7 +16,6 @@ import { rootPackageJsonContent } from './templates/package-json.js'import { readmeContent } from './templates/readme.js'import type { PackageManager, ScaffoldOptions } from './types.js'import {- dlxCommand,generateEncryptionKeys,generateSecretKeyBase,installCommand,@@ -177,20 +170,23 @@ export async function scaffold(options: ScaffoldOptions): Promise<void> {dependabotContent(storefrontReady, dashboardReady, sellerDashboardReady),)- // A failed install warns and continues, like the apps: skills are a+ // Runs after AGENTS.md exists, which `spree add ai` points at the docs+ // server. A failure warns and continues, like the apps: agent setup is a// convenience, never a reason to stop before Phase 4.- let agentSkillsReady = false- if (options.agentSkills) {- s.start('Installing Spree agent skills...')+ let agentsReady = options.agentSkills && options.docsMcp+ if (options.agentSkills || options.docsMcp) {+ s.start('Setting up AI coding agents...')try {- await installAgentSkills(projectDir, options.packageManager)- agentSkillsReady = true- s.stop('Spree agent skills installed.')+ await setupAgents(projectDir, {+ skills: options.agentSkills,+ mcp: options.docsMcp,+ packageManager: options.packageManager,+ })+ s.stop('AI coding agents set up.')} catch (err) {- s.stop('Spree agent skills were not installed.')- p.log.warn(- `Install them later with ${pc.bold(`${dlxCommand(options.packageManager)} skills add ${AGENT_SKILLS_REPO}`)}.\n${errorMessage(err)}`,- )+ agentsReady = false+ s.stop('AI coding agents were only partly set up.')+ p.log.warn(errorMessage(err))}}@@ -228,6 +224,7 @@ export async function scaffold(options: ScaffoldOptions): Promise<void> {// No dashboard line here — with the dashboard chosen, `spree init`'s// summary already leads with it (served at /dashboard, plus the// customize command).+ if (!agentsReady) p.note(agentSetupHint(options.packageManager).join('\n'), 'AI coding agents')} else {printSuccessWithoutDocker(projectName,@@ -235,7 +232,7 @@ export async function scaffold(options: ScaffoldOptions): Promise<void> {storefrontReady,dashboardReady,sellerDashboardReady,- agentSkillsReady,+ agentsReady,options.packageManager,)}@@ -247,7 +244,7 @@ function printSuccessWithoutDocker(hasStorefront: boolean,hasDashboard: boolean,hasSellerDashboard: boolean,- hasAgentSkills: boolean,+ agentsReady: boolean,pm: PackageManager,): void {const run = runCommand(pm)@@ -310,22 +307,9 @@ function printSuccessWithoutDocker('',)- if (!hasAgentSkills) {- lines.push(- `${pc.bold('Agent skills (optional)')}`,- ` ${dlxCommand(pm)} skills add ${AGENT_SKILLS_REPO}`,- ` ${pc.dim('# Teaches whichever AI agents you use how to work with Spree')}`,- ` ${pc.dim('# (Claude Code, Codex, Cursor, Copilot, Cline, Aider, +60 others)')}`,- '',- )- }+ if (!agentsReady) lines.push(...agentSetupHint(pm), '')lines.push(- `${pc.bold('Spree docs MCP server (optional)')}`,- ` claude mcp add --transport http spree-docs ${DOCS_MCP_URL}`,- ` ${pc.dim('# Lets your AI agent search the latest Spree docs. Other agents:')}`,- ` ${pc.dim('# https://spreecommerce.org/docs/developer/agentic/mcp')}`,- '',`${pc.bold('Join our Discord')}`,` https://discord.spreecommerce.org`,'',@@ -336,6 +320,16 @@ function printSuccessWithoutDocker(p.note(lines.join('\n'), 'Project created!')}+/** How to finish the agent setup the scaffold skipped or could not complete. */+function agentSetupHint(pm: PackageManager): string[] {+ return [+ `${pc.bold('AI coding agents (optional)')}`,+ ` ${runCommand(pm)} spree add ai`,+ ` ${pc.dim('# Installs the Spree agent skills and connects your agent to the Spree docs')}`,+ ` ${pc.dim('# Safe to re-run; --no-skills or --no-mcp sets up only one of the two')}`,+ ]+}+function errorMessage(err: unknown): string {return err instanceof Error ? err.message : String(err)}diff --git a/packages/create-spree-app/src/templates/agents-md.ts b/packages/create-spree-app/src/templates/agents-md.tsindex 2a1c558cff..08ccf0628b 100644--- a/packages/create-spree-app/src/templates/agents-md.ts+++ b/packages/create-spree-app/src/templates/agents-md.ts@@ -1,5 +1,5 @@import type { PackageManager } from '../types.js'-import { dlxCommand, runCommand } from '../utils.js'+import { runCommand } from '../utils.js'/*** Root CLAUDE.md for a generated project. Claude Code reads CLAUDE.md, not@@ -140,7 +140,7 @@ export function agentsMdContent('','The official Spree skills cover API conventions, the data model, events, testing,','security, deployment, the Admin Dashboard and the storefront. If `.agents/skills/`',- `is missing, install them with \`${dlxCommand(pm)} skills add spree/agent-skills\`.`,+ `is missing, install them with \`${spree} add ai --no-mcp\`.`,'',)diff --git a/packages/create-spree-app/src/templates/package-json.ts b/packages/create-spree-app/src/templates/package-json.tsindex 41bd0313be..52936d876f 100644--- a/packages/create-spree-app/src/templates/package-json.ts+++ b/packages/create-spree-app/src/templates/package-json.ts@@ -40,7 +40,7 @@ export function rootPackageJsonContent(name: string, pm: PackageManager = 'pnpm'// SPREE_CLI_VERSION overrides the spec for testing unreleased CLIs —// a range, or a `file:`/`link:` path to a packed tarball / checkout// (mirrors the starter Dockerfile's ARG of the same name).- '@spree/cli': process.env.SPREE_CLI_VERSION ?? '^3.0.0',+ '@spree/cli': process.env.SPREE_CLI_VERSION ?? '^3.4.0','@spree/docs': 'latest',},}diff --git a/packages/create-spree-app/src/types.ts b/packages/create-spree-app/src/types.tsindex 1adf41dbf1..efdb2c7e50 100644--- a/packages/create-spree-app/src/types.ts+++ b/packages/create-spree-app/src/types.ts@@ -6,6 +6,7 @@ export interface ScaffoldOptions {dashboard: booleansellerDashboard: booleanagentSkills: boolean+ docsMcp: booleanstart: booleanpackageManager: PackageManagerport: numberdiff --git a/packages/create-spree-app/src/utils.ts b/packages/create-spree-app/src/utils.tsindex 7a4c0ae296..28665fa5ac 100644--- a/packages/create-spree-app/src/utils.ts+++ b/packages/create-spree-app/src/utils.ts@@ -97,13 +97,6 @@ export function runCommand(pm: PackageManager): string {return 'pnpm'}-/** Runner for a one-off remote package (e.g. `npx skills`, `pnpm dlx skills`). */-export function dlxCommand(pm: PackageManager): string {- if (pm === 'npm') return 'npx'- if (pm === 'yarn') return 'yarn dlx'- return 'pnpm dlx'-}-/** Global-install command for a package (e.g. `npm install -g`, `pnpm add -g`). */export function globalAddCommand(pm: PackageManager): string {if (pm === 'npm') return 'npm install -g'diff --git a/packages/create-spree-app/tests/prompts.test.ts b/packages/create-spree-app/tests/prompts.test.tsindex c03e2310d2..e76a5c5d64 100644--- a/packages/create-spree-app/tests/prompts.test.ts+++ b/packages/create-spree-app/tests/prompts.test.ts@@ -15,6 +15,7 @@ const ANSWERED = {noStorefront: true,noSellerDashboard: false,noAgentSkills: false,+ noDocsMcp: false,noStart: true,packageManager: 'pnpm',} as const@@ -44,22 +45,40 @@ describe('runPrompts', () => {)})- it('asks about the agent skills, defaulting to yes', async () => {+ it('asks one question about the agent skills and docs MCP server, defaulting to yes', async () => {const { confirm } = await import('@clack/prompts')vi.mocked(confirm).mockClear()vi.mocked(confirm).mockResolvedValueOnce(true)- const options = await runPrompts({ ...ANSWERED, noAgentSkills: undefined })+ const options = await runPrompts({+ ...ANSWERED,+ noAgentSkills: undefined,+ noDocsMcp: undefined,+ })expect(options.agentSkills).toBe(true)+ expect(options.docsMcp).toBe(true)+ expect(vi.mocked(confirm)).toHaveBeenCalledTimes(1)expect(vi.mocked(confirm)).toHaveBeenCalledWith(expect.objectContaining({- message: expect.stringContaining('Install Spree agent skills?'),+ message: expect.stringContaining('Set up AI coding agents?'),initialValue: true,}),)})+ // Scripted runs (CI) pass only the flag they care about and cannot answer.+ it('does not ask when either agent flag is passed, defaulting the other half to yes', async () => {+ const { confirm } = await import('@clack/prompts')+ vi.mocked(confirm).mockClear()++ const options = await runPrompts({ ...ANSWERED, noAgentSkills: true, noDocsMcp: undefined })++ expect(options.agentSkills).toBe(false)+ expect(options.docsMcp).toBe(true)+ expect(vi.mocked(confirm)).not.toHaveBeenCalled()+ })+// Sample data is loaded on demand with `spree sample-data`, never as part of// the scaffold: the seed runs before the store is configured through the// first-run setup UI.diff --git a/packages/create-spree-app/tests/scaffold.test.ts b/packages/create-spree-app/tests/scaffold.test.tsindex f20654ee34..df3ed5d02d 100644--- a/packages/create-spree-app/tests/scaffold.test.ts+++ b/packages/create-spree-app/tests/scaffold.test.ts@@ -368,7 +368,7 @@ describe('scaffold (no-start)', () => {expect(fs.readFileSync(path.join(projectDir, 'CLAUDE.md'), 'utf-8')).toBe('@AGENTS.md\n')})- it('installs the agent skills when chosen', async () => {+ it('delegates the agent setup to `spree add ai`, passing what was declined', async () => {const { execa } = await import('execa')vi.mocked(execa).mockClear()const projectDir = getTempProjectDir()@@ -377,7 +377,8 @@ describe('scaffold (no-start)', () => {directory: projectDir,storefront: false,dashboard: false,- agentSkills: true,+ agentSkills: false,+ docsMcp: true,start: false,packageManager: 'npm',port: 3000,@@ -385,17 +386,36 @@ describe('scaffold (no-start)', () => {expect(vi.mocked(execa)).toHaveBeenCalledWith('npx',- ['--yes', 'skills', 'add', 'spree/agent-skills', '--skill', '*', '--yes'],+ ['spree', 'add', 'ai', '--quiet', '--no-skills'],expect.objectContaining({ cwd: path.resolve(projectDir) }),)})- // Skills are a convenience: a failed install must not stop first-run setup.- it('continues to first-run setup when the agent skills fail to install', async () => {+ it('skips the agent setup when both halves are declined', async () => {+ const { execa } = await import('execa')+ vi.mocked(execa).mockClear()++ await scaffold({+ directory: getTempProjectDir(),+ storefront: false,+ dashboard: false,+ agentSkills: false,+ docsMcp: false,+ start: false,+ packageManager: 'npm',+ port: 3000,+ })++ const addAi = vi.mocked(execa).mock.calls.find(([, args]) => (args as string[])?.[2] === 'ai')+ expect(addAi).toBeUndefined()+ })++ // Agent setup is a convenience: a failure must not stop first-run setup.+ it('continues to first-run setup when the agent setup fails', async () => {const { execa } = await import('execa')vi.mocked(execa).mockClear()vi.mocked(execa).mockImplementation((async (_command: string, args: string[]) => {- if (args.includes('skills')) throw new Error('network down')+ if (args.includes('ai')) throw new Error('network down')}) as never)await scaffold({diff --git a/packages/create-spree-app/tests/templates.test.ts b/packages/create-spree-app/tests/templates.test.tsindex 8448900028..8f257d886f 100644--- a/packages/create-spree-app/tests/templates.test.ts+++ b/packages/create-spree-app/tests/templates.test.ts@@ -90,7 +90,7 @@ describe('rootPackageJsonContent', () => {const pkg = JSON.parse(rootPackageJsonContent('my-store'))// The floor must admit every CLI capability the scaffold calls — the// seller-dashboard component landed in 3.0.- expect(pkg.dependencies['@spree/cli']).toBe('^3.0.0')+ expect(pkg.dependencies['@spree/cli']).toBe('^3.4.0')})it('includes convenience scripts using spree cli', () => {