Skip to Content
DevelopersBuildingMCP server and API tokens

7 min read

MCP server and API tokens

Settings → MCP & API lets AI clients (Claude, ChatGPT, Cursor, VS Code) and scripts work with one store. Two kinds of grant exist, both stored in api_grant (store-scoped, RLS):

KindMade bySecretLifetime
oautha client signing in on the consent pagekmo_… access token + kmr_… refresh tokenaccess 1 h, refresh 30 d, both rotate on refresh
tokenSettings → Create tokenkmc_live_…30 / 90 / 365 days or never

Every grant acts for one member of one store. On each call it is capped twice: by the member’s role, read fresh from the database, and by the grant’s areas (products, orders, customers, inventory, discounts, content, analytics, marketing, online_store, settings, each read or write). Mapping areas to permissions: permissionsForScopes in @commerce/core/api-access. Write never includes refunds, cancels, product or customer deletes, staff or billing: a call that runs at once cannot do those. An MCP client can still ask for them through runAction; they wait in AI approvals and run as the member who approves, even when the member is the owner (the safety floor for AI clients).

Secrets are stored only as SHA-256 hashes. Before a store is known, lookups go through SECURITY DEFINER functions (migration 0130): api_grant_for_access, api_grant_for_refresh, api_auth_code_store, store_id_for_slug.

Endpoints (admin app)

PathWhat
POST /api/mcp/<store slug>MCP, Streamable HTTP, stateless: one JSON-RPC message or batch per POST, JSON reply. GET/DELETE → 405
GET /.well-known/oauth-protected-resource/api/mcp/<slug>RFC 9728 resource metadata
GET /.well-known/oauth-authorization-serverRFC 8414 metadata (issuer = ADMIN_URL)
POST /api/oauth/registerRFC 7591 dynamic registration (20/h per IP). Redirect URIs: https, loopback http, or an app scheme
GET /oauth/authorizeConsent page (signs the member in first via /login?next=)
POST /api/oauth/tokenauthorization_code (PKCE S256 required) and refresh_token
POST /api/oauth/revokeRFC 7009
POST /api/v1/<router>/<procedure>The admin’s oRPC router for access tokens (cookies stripped)
GET /api/mcp/<slug>/download?t=…A file runAction answered with (signed, 10 minutes)

A call without a bearer token gets 401 with WWW-Authenticate: Bearer resource_metadata="…", which is how clients find the sign-in.

Code: packages/api/src/mcp/ (server.ts, oauth.ts, tools.ts, admin-actions.ts, action-catalogue.ts, download-link.ts), packages/core/src/api-access/ (grants, codes, tokens, activity), and admin routes under apps/admin/src/app/{api/mcp,api/oauth,api/v1,.well-known,oauth}.

Tools

tools/list returns the AI assistant’s own tools (services/ai/assistant), filtered to the grant’s permissions:

  • Read tools (READ_TOOL_PERMISSION), plus customerDetails, which answers only while Let clients read customer details is on.
  • Change tools (ACTIONS), listed only while Allow AI clients to make changes is on. A call runs proposeAction with source: 'mcp' and then approveAction at once with the grant’s permissions and the member’s role (grantScope in tools.ts). When the role ticks Needs approval for the action’s permission, approveAction hands it to Approvals instead (needsApprover, see “Role approvals” below). The store-wide Changes need approval switch was retired in migration 0188.

Adding an assistant tool adds it to MCP too; nothing else to wire.

Every other admin action: search, describe, run

Three more tools reach the whole admin router (admin-actions.ts), always listed:

ToolWhat
searchActions({ query, area? })Up to 20 procedures in the grant’s areas: path (orders.fulfil), one line, kind, area
describeAction({ path })Input JSON Schema (from the procedure’s Zod input), output hint, kind, needsApproval (no / always / blocked; a role’s tick still queues a no)
runAction({ path, input })Runs it, or queues it for approval

The catalogue is walked from appRouter at runtime (routerProcedures), so a new procedure is offered without wiring. Its one-line description is the first sentence of the procedure’s JSDoc, collected into action-docs.generated.ts by bun scripts/gen-mcp-action-docs.ts (the mcp-action-docs sweep fails when it is stale); without JSDoc it is derived from the path.

action-catalogue.ts classifies each path. Its explicit tables win; otherwise a name starting with list/get/find/search/count/summary/stats/preview/quote/check/status (or a known read noun such as overview, label, pdf) is a read, a name starting with delete/remove/cancel/refund/uninstall/disconnect/anonymise is sensitive, and the rest are writes:

KindRuns
readat once
writeat once with the member’s role (queued in Approvals when the role ticks Needs approval)
sensitivealways queued for a person in the admin, even for the owner: refunds, store credit, cancellations, deletes and removes, gift card money, payment gateway keys and settings, staff and roles, billing, domains, store export and deletion, MCP & API settings. orders.setStatus to cancelled and products.bulk deleting are sensitive by input
excludednever listed or run: account.*, me, onboarding.*, invitations.*, bugReports.*, creating or revoking tokens, approving, editing, cancelling or undoing AI actions, the AI bar itself, browser hand-offs (Razorpay and Google sign-in, media uploads)

Each router namespace maps to one grant area (NAMESPACE_AREA). Reads need the area, anything else needs it as write; a namespace with no area is excluded (the catalogue test fails until one is added).

Running at once calls the procedure with call() and apiPrincipal on the context, the same path /api/v1 takes: the role ∩ the grant’s areas is enforced by scopeFor, and logTokenCall writes the Activity row with the procedure path. Input over 32,000 characters is refused; answers over 20,000 characters are cut with a note; a call has 30 seconds. A procedure that returns a File (labels, invoices, CSV exports) answers with a signed download link instead: HMAC over grant, store, path and input with the settings secret, valid 10 minutes; opening it re-checks the grant (principalForGrant) and re-runs the read.

Queued calls become a runAdminAction in ai_action (services/ai/assistant/actions/admin-action.ts, not offered as a tool of its own). Its card shows the action’s name, what it does and every input value as a row. Approve runs the procedure with the approver’s own request context (ActionEnv.api), so the procedure’s middleware checks the approver’s role; a FORBIDDEN refusal is returned to the approver and leaves the action waiting (ApproverNotAllowed), any other error marks it failed with that message. ai.approveAction, reviseAction and cancelAction are open to any member with a role (APPROVE_PERMISSIONS). An assistant proposal is the asker’s alone; an MCP one may be approved by the asker, the owner or a member with the action’s permission (for runAdminAction, whose permission only the procedure knows, any member may try to approve and the procedure decides; editing or cancelling it for someone else is the owner’s). Proposals expire after ASSISTANT_LIMITS.proposalTtlMinutes (24 hours); expired ones read as expired and are refused with a message saying so. approvedBy and result.by record the approver; when the connecting member confirms their own client’s sensitive action, result.confirmedAi is set (the view’s confirmedAi), so it reads as confirming the AI rather than an approval.

Role approvals

A role may tick Needs approval on any change permission (role_approval, migration 0188; only the owner edits ticks, staff.saveRoleApprovals). Defaults for new stores and roles: DEFAULT_APPROVAL_PERMISSIONS in @commerce/core/permissions (refund, cancel, product and customer delete, discounts, payments.manage, billing, staff invite and manage). Payment keys and payouts moved from settings.manage to payments.manage (granted to every role that had settings.manage; settings.manage is not ticked).

The queue lives in one place, storeProcedureWith (procedures/store.ts). For a procedure behind one can(permission) that the member’s role ticks (mustAsk; never the owner), a call the catalogue classifies as write or sensitive (approvalKind, which also classifies admin-only namespaces such as staff) is stored as a runAdminAction row with needsApprover, permission and source admin / mcp / api, and the caller gets an APPROVAL_QUEUED error (data.approvalId). The admin’s API client rewrites its message to “Sent for approval” (apps/admin/src/lib/api-client.ts), so every page’s existing error display says so. MCP’s runAction turns it into a “Waiting for approval” answer.

Who approves (canApprove in procedures/approval-rules.ts): the owner, or a member with approvals.manage who holds the permission and whose role does not tick it; never the asker (openFor), who may only withdraw. Approving replays the call as the approver with approvalReplay set, so a tick on the approver’s side cannot queue it twice. Queued rows expire after APPROVAL_TTL_DAYS (7). approvals.waiting / mine / counts back Settings → Approvals and its nav count; opening Your requests marks decided outcomes seen.

A grant some inputs need on top of the procedure’s own is named on the procedure too: can(permissions.ORDERS_WRITE, (input) => ...) (AlsoNeeds, procedures/also-needs.ts). The middleware refuses the call without it and holds it when the role ticks it, exactly like the main permission: orders.setStatus to cancelled also needs orders.cancel, a cancel or edit that refunds orders.refund, products.bulk deleting products.delete, and so on. Never check a change grant inside the handler (scope.can(...)): the tick would be skipped there, which is how the orders table’s cancel ran at once while the order page’s waited (#1409). The handler-grants sweep enforces it.

Gaps, by design:

  • Reads are never queued, nor canAny / canDetached procedures by their own list (no single permission to tick; an also grant is held), nor a server-side call() without a path.
  • People-only paths (catalogue exclusions: browser hand-offs, tokens, deciding approvals) and file uploads cannot wait: a ticked one is refused with FORBIDDEN.

The token API

/api/v1 sets context.apiPrincipal. Then:

  • protectedProcedure (session-only: account, sign-in, store picking) refuses tokens.
  • can / canAny / canDetached run as the token’s member. scopeFor intersects the role with principal.permissions, and refuses procedures that name no permission.
  • Each successful call is logged (logTokenCall): changes one by one; reads folded to one row per procedure per 10 minutes.
  • The route refuses (403) excluded catalogue paths and sensitive ones in the settings area (apiTokenRefusal): a token has no approval step, so payment keys, domains, store deletion and MCP settings need a person.

Example:

curl -X POST https://admin.koomerce.app/api/v1/products/list \ -H "Authorization: Bearer kmc_live_…" -H "content-type: application/json" \ -d '{"json":{"page":1}}'

Limits and retention

  • API_RATE_LIMIT: 120 requests/min per grant (Redis store), on both MCP and /api/v1.
  • api_activity keeps 90 days. The worker’s daily {api}-activity-prune job deletes older rows (stores_with_old_api_activity).

Tests

packages/api/test/mcp.test.ts covers:

  • registration, PKCE and refresh rotation
  • the tool list and settings switches
  • approvals and blocked reads
  • token capping and session-only refusal
  • expiry, revoke and cross-store refusal

mcp-action-catalogue.test.ts covers the classification, exclusions and that every namespace has an area; mcp-actions.test.ts covers search and describe, grant and role refusals, approval routing (role ticks, sensitive always, even for the owner), approval running as the approver, activity rows, file links and truncation.

Was this helpful?
Last updated on