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.
spree api — Admin API command group in @spree/cli
Status: In Progress
Target: Spree 5.5.x (CLI minor + one core patch)
Depends on: 5.5-admin-api-key-scopes.md (shipped), 6.0-admin-api.md (conventions), 5.5-agent-skills.md (distribution of the companion skill)
Author: Damian Legawiec ([email protected])
Last updated: 2026-06-12
Summary
Add a gh api-style command group to @spree/cli: generic HTTP verbs against the Admin API v3 (spree api get|post|patch|delete <path>), schema introspection from the bundled OpenAPI spec (spree api endpoints, spree api schema), and layered credential resolution (flags > env > project auto-mint > profiles). This turns the CLI into the first executable agent surface for Spree's back office — usable by Claude Code, Cursor, CI scripts, and humans alike — before any MCP server exists.
This is a deliberate sequencing decision ("CLI-first"): developer agents already have shell access and need zero client configuration; the consumer MCP clients that would justify a hosted Admin MCP (claude.ai, ChatGPT) reject static API keys and are blocked on the OAuth 2.1 work in 6.0-platform-auth regardless; and a CLI is immune to MCP protocol churn (a breaking, stateless MCP spec revision lands 2026-07-28). Shopify made the same call — there is no official Shopify Admin MCP; agent store management goes through their AI Toolkit CLI. Everything built here (credential bootstrap, generic verbs, schema tools, the SPREE_BASE_URL/SPREE_API_KEY env contract) becomes the substrate a later spree mcp wrapper exposes as MCP tools, so nothing is throwaway.
Key Decisions (do not deviate without discussion)
- CLI-first; MCP servers come later and get their own plans. This plan deliberately contains zero MCP code. The future lanes are: a shopper-facing Storefront MCP (
/api/mcp, separate plan, highest strategic priority since it has no CLI substitute), a hosted Admin MCP riding6.0-platform-authOAuth, and an optionalspree mcpstdio wrapper over this command group. None of them start beforespree apiships. - Generic verbs, not per-resource subcommands.
spree api get /products— neverspree products list. A per-resource command family (~38 resources) would duplicate@spree/admin-sdk, sprawl the CLI, and add nothing for agents, which compose generic verbs with the schema tools. Precedents:gh api, and the Wix/Datadog/Harness redesigns away from API-parity toward few generic verbs. - Layered credential resolution, in this order:
- flags (
--base-url,--api-key— the key flag is supported but discouraged: it leaks into shell history and process lists) - env vars
SPREE_BASE_URL+SPREE_API_KEY(the agent/CI/sandbox path) - project context: inside a spree-starter directory (
detectProject()), resolve the base URL from.envand auto-mint a key through Docker on first use — zero configuration - named profiles in
~/.config/spree/config.json, selected via--profileor a default
- flags (
sk_secret keys are the only credential. They are store-bound (tenant resolution is free), scoped, HMAC-digest stored, and revocable from the admin dashboard — revocation is the kill switch. No JWT support: ~1h expiry with refresh rotation is the admin SPA's model, not a CLI's. A browser/device-code login becomes a fifth resolution source once6.0-platform-authships an OAuth stack; the resolution chain is designed so it slots in without breaking anything.- Auto-minted keys get
read_allonly. Write scopes always require an explicitspree api-key create --scopes write_products,.... An agent pointed at a long-lived dev database must not be able to mutate by accident. spree apiandspree authwork without a Docker project. Today every CLI command hard-requiresdocker-compose.ymlviadetectProject()(packages/cli/src/context.ts). The new commands consult project context only as resolution layer 3 and otherwise run standalone against any Spree 5.5+ host — local or remote.- The CLI gains a dependency on
@spree/admin-sdk(it currently depends on neither SDK). Retry with backoff,Retry-Afterhonoring, automaticIdempotency-Keyon writes,SpreeErrorwith code/status/details, andX-Spree-Store-Idhandling all come free. No hand-rolled fetch layer. - JSON to stdout by default; humans opt into tables. Agents and
jqare the primary consumers.--format tablerenders collections for humans. Errors go to stderr with non-zero exit codes; a 403 scope denial prints therequired_scopefrom the error payload plus the exactspree api-key create --scopes ...remediation. - Schema tools read a bundled, versioned
admin.yamlsnapshot.docs/api-reference/admin.yamlis rswag-generated (never hand-edited) and already drives@spree/admin-sdkcodegen — the CLI bundles a snapshot per release and parses it at startup. No live spec fetch in v1; version skew is surfaced as a warning when the server's Spree version (fromspree api status) doesn't match the bundled snapshot's. - Two core fixes ship first as a 5.5.x patch (the CLI is unusable against unpatched servers otherwise):
spree:cli:create_api_keycannot mint secret keys at all today —Spree::ApiKeypresence-validatesscopeson secret keys (spree/core/app/models/spree/api_key.rb) and the task passes none, soKEY_TYPE=secretraisesRecordInvalid. Add aSCOPESenv var (comma-separated, validated againstSpree::ApiKey::SCOPES).Spree::ApiKey::SCOPEShas noread_promotions/write_promotionseven though the promotions controllers declarescoped_resource :promotions— promotion endpoints are reachable only by*_allkeys. Add both scopes.
- Pair with an agent skill, distributed per
5.5-agent-skills.md. Aspree-cliskill inspree/agent-skillsteaches agents the credential flow, the verb + schema-tool loop, and the read-before-write conventions. Skills are the guidance channel; the CLI is the execution channel — don't duplicate conventions into CLI help text beyond--helpbasics.
Design Details
Command surface
# Reads — Ransack filters as repeatable -q, JSON:API-style sort
spree api get /products -q status_eq=active -q name_cont=shirt --sort -created_at --limit 10
spree api get /orders/ord_x8k2J9aQ --expand items,payments,fulfillments
# Writes — JSON body inline, from file, or from stdin
spree api post /products -d '{"name":"Classic Tee","prices":[{"currency":"USD","amount":"29.99"}]}'
spree api post /orders/ord_x8k2J9aQ/refunds -d @refund.json
cat batch.json | spree api post /prices/bulk_upsert -d -
# State-machine and custom actions are just paths
spree api patch /orders/ord_x8k2J9aQ/cancel
spree api delete /products/prod_86Rf07xd
# Schema introspection (bundled admin.yaml)
spree api endpoints --resource orders # method, path, summary, required scope
spree api schema "POST /orders/{id}/refunds" # request/response JSON Schema, Ransack fields
spree api status # server reachability, Spree version, credential + scopes
# Credentials
spree auth login --profile prod --base-url https://store.example.com # prompts for sk_ on stdin
spree auth status # profile, base URL, key prefix (sk_a1b2c3d4e5f6…), scopes
spree auth logout --profile prod
spree api-key create --scopes read_all # extended with --scopes (maps to rake SCOPES env)
Flag conventions:
| Flag | Meaning |
|---|---|
-q key=value (repeatable) |
Ransack predicate; wrapped into q[...] via the SDK's transformListParams |
--sort, --page, --limit, --expand, --fields |
passed through to the Admin API conventions from 6.0-admin-api.md |
-d <json> / -d @file / -d - |
request body (inline, file, stdin) |
--store-id |
X-Spree-Store-Id header, only needed when one host serves multiple stores |
--profile, --base-url, --api-key |
credential resolution overrides |
--format json|table |
output rendering (default json) |
Credential resolution and storage
Resolution order (first hit wins): flags → SPREE_BASE_URL/SPREE_API_KEY env → project credentials → profile.
- Project credentials live in
.spree/credentials.jsonin the project directory,0600, gitignored (create-spree-appand spree-starter add.spree/to the scaffolded.gitignore). Written by the auto-mint flow:detectProject()resolves the port → runspree:cli:create_api_key NAME="@spree/cli (auto)" KEY_TYPE=secret SCOPES=read_allthrough Docker (same path as the existingapi-key createcommand) → persist{ baseUrl, token, scopes, mintedAt }. Firstspree api get /productsin a fresh project requires zero setup. - Profiles live in
~/.config/spree/config.json(0600):{ defaultProfile, profiles: { prod: { baseUrl, token } } }.spree auth loginreads the key from an interactive prompt or stdin — never from a flag — and validates it with a test call before saving. The display prefix (first 12 chars) shown byauth statusis computed from the stored token, not persisted separately; the plaintext is never echoed after creation. - OS-keychain storage is an open question (below); v1 is file-based with
0600, matchinggh's fallback behavior.
Core rake task changes (5.5.x patch)
desc 'Create an API key'
task create_api_key: :environment do
name = ENV.fetch('NAME')
key_type = ENV.fetch('KEY_TYPE')
scopes = ENV.fetch('SCOPES', '').split(',').map(&:strip).reject(&:blank?)
store = Spree::Store.default
key = store.api_keys.create!(name: name, key_type: key_type, scopes: scopes)
print key.plaintext_token
end
Unknown scopes are already rejected by the model's validate_known_scopes; the task stays dumb. read_promotions/write_promotions are added to Spree::ApiKey::SCOPES in the same patch (additive, safe — existing keys are unaffected).
Output and errors
- Collections pass through the API's
{data, meta}envelope untouched; single resources print the bare object. Everything isjq-composable. - Exit codes:
0success,1API error (4xx/5xx — the Stripe-style{error: {code, message, details}}payload is printed to stderr),2usage/configuration error (no credential resolvable, bad flags, unreachable host). - A 403 with
code: access_deniedprintsdetails.required_scopeand the remediation command. This is load-bearing for agents: the error text is what the model reads to self-correct.
Relationship to future MCP work
| Lane | Surface | Status after this plan |
|---|---|---|
| Dev/admin agents (Claude Code, Cursor, CI) | spree api + spree-cli skill |
Shipped here |
| Shopper agents (claude.ai, ChatGPT consumers) | Storefront MCP at /api/mcp |
Separate plan, next minor — no CLI substitute exists |
| Merchant copilot on consumer clients | Hosted Admin MCP + OAuth 2.1 | 6.0, rides 6.0-platform-auth; tool catalog informed by observed CLI usage |
| MCP clients that can't shell out | spree mcp stdio wrapper exposing this command group as tools |
Optional, later — the SPREE_BASE_URL/SPREE_API_KEY env contract defined here is already the stdio-MCP credential convention |
agent-skills pairing
One new spree-cli skill in github.com/spree/agent-skills (per that plan's constraints: targets users, not monorepo contributors). It covers: when to reach for spree api vs the TypeScript SDKs, the credential layers, the endpoints → schema → get/post loop, read-before-write habits, and the scope-denial remediation flow. The existing spree-api-v3 skill gets a cross-reference.
Migration Path
All steps are additive; no breaking changes anywhere.
- Core 5.5.x patch (
spree/core) — ✅ shipped (PR #14166):SCOPESenv onspree:cli:create_api_key(fixes secret-key minting),read_promotions/write_promotionsinSpree::ApiKey::SCOPES(plus the broader scope cleanup: dedicatedapi_keys/webhooksscopes,stockcovering inventory, exports gated by the exported resource). Specs for all. @spree/climinor — ✅ done:@spree/admin-sdkdependency;src/config.ts(paired-layer resolution + credential files);src/commands/auth.ts+src/commands/api.ts; helper modules undersrc/api/(params,body,output,ping,spec);--scopesflag onapi-key create;scripts/bundle-spec.mjsslimsadmin.yaml→src/generated/admin-spec.jsonat build time (via theyamlpackage); Changesets entries.- Scaffolding — ✅ partial:
create-spree-appadds.spree/to its.gitignore; the auto-mint flow also writes a self-ignoring.spree/.gitignoreso any project (regardless of scaffold vintage) is covered. Pending: the same.gitignoreline in thespree/spree-startertemplate repo (separate repo PR). - agent-skills — ⏳ open:
spree-cliskill PR tospree/agent-skills. - Docs — ✅ done:
docs/developer/cli/admin-api.mdx(command group + credential layers + agent usage),docs/api-reference/admin-api/endpoints.mdx(generated endpoint index), README + quickstart sections.
As-built surface (beyond the original sketch)
- Commands:
spree api get|post|patch|delete <path>,spree api endpoints(--resource,--search,--format),spree api schema <operation>,spree api status;spree auth login|status|logout|list(logout --projectremoves.spree/credentials.json). - Credential resolution is paired-per-source, not per-field. The API key anchors each layer; host and key resolve together so a saved/minted key is never silently sent to a host from
SPREE_BASE_URLalone. An explicit--base-url/--api-keyflag is the only sanctioned cross-source override. Auto-mint is suppressed when an explicit--base-urltargets a non-project host. - Profile schema persisted at
~/.config/spree/config.json(0600):{ defaultProfile, profiles: { <name>: { baseUrl, token } } }. A corrupt file is backed up toconfig.json.bakrather than silently emptied. - Schema snapshot: a slimmed (examples-stripped) JSON copy of
admin.yamlbundled in the package;spree api schemaresolves$refs inline and prefers exact literal paths over{id}templates. - Exit codes: 0 success, 1 API error (envelope to stderr), 2 usage/configuration error (bad flag, invalid
-q/--page/--limit, no credentials, unreachable host). 403 scope denials print the full mint-and-wire remediation. - Deferred: a true server-vs-snapshot version-skew warning needs an Admin API endpoint exposing the Spree version (none exists yet);
spree api statusnotes the snapshot may lag the live server instead.
Constraints on Current Work
- Do not add per-resource data subcommands to
@spree/cli(spree products list,spree orders show, …). The generic-verb decision is policy; convenience wrappers route throughspree apior don't exist. - Do not start MCP server implementation (storefront, admin, or stdio wrapper) before this ships and has its own plan doc. Future MCP servers wrap
@spree/admin-sdk/ these CLI internals — never fork a parallel tool surface. - Keep regenerating
admin.yamlvia rswag after any Admin API change (bundle exec rake rswag:specs:swaggerize). It was already the rule; the CLI's schema tools now make it load-bearing — a stale spec meansspree api schemalies to agents. - New admin controllers must declare an accurate
scoped_resourceand, if they introduce a new resource family, add the matchingread_*/write_*pair toSpree::ApiKey::SCOPESin the same PR. The CLI surfaces required scopes from the spec; gaps become user-visible immediately.
Open Questions
- OS keychain storage for profile keys (vs
0600files only)? Cross-platform keychain libs for Node add native-dependency weight to a so-far pure-JS CLI;ghships file-fallback and most users live there. Lean: file-only in v1, revisit on demand. - Built-in
--jqfilter (likegh api --jq)? Convenient, but adds a jq-engine dependency; agents and humans can pipe to realjq. Lean: skip in v1. --paginateauto-pagination for collections? Useful for exports, dangerous for context-limited agents. Lean: skip in v1;meta.nextis in the envelope.- Should
spree apialso cover the Store API (--surface store, bundlingstore.yaml) for storefront/checkout testing? Plausible later; out of scope now. Re-scoping existing controllers— resolved during 5.5 RC (2026-06-12): inventory controllers (stock_items,stock_locations,stock_transfers) moved tostock, webhook controllers towebhooks, andapi_keysgot a dedicatedread/write_api_keyspair. See the vocabulary table in5.5-admin-api-key-scopes.md.- Version-skew handling beyond a warning: should
spree api statuscompare bundled-spec version vs server version and offer--spec <path>overrides for edge/pre-release servers?
References
5.5-admin-api-key-scopes.md— the scope vocabulary this CLI's permission UX is built on6.0-admin-api.md— endpoint inventory + conventions (?q,?sort,?expand, flat JSON, prefixed IDs)5.5-agent-skills.md— distribution channel for the companionspree-cliskill6.0-platform-auth.md— the OAuth 2.1 stack that later unlocks consumer-client MCP and a browser-login credential sourcegh apimanual: https://cli.github.com/manual/gh_api — the generic-verb precedent- Stripe CLI auth model (profiles + config file): https://docs.stripe.com/stripe-cli
- Shopify AI Toolkit (CLI-based store management for agents; no official Admin MCP): https://github.com/Shopify/shopify-ai-toolkit
- MCP spec 2026-07-28 release candidate (stateless rework — the churn this plan sidesteps): https://blog.modelcontextprotocol.io/posts/2026-07-28-release-candidate/
- Context-economics findings informing the CLI-first call: GitHub's 93-tool MCP server ≈ 55k tokens; Cursor's 40-tool cap; Datadog/Harness generic-verb redesigns