Admin MCP Server
The template ships an admin MCP server in backend/src/mcp-admin/. It is the operations surface for a deployed app: point an AI agent (Claude Desktop, Cursor, Codex, etc.) at it over the Model Context Protocol and the agent can author blog content, look up users and signup numbers, read email queue and campaign stats, queue email sends, check a user's billing entitlement, and list or revoke the OAuth grants its own connectors hold.
MCP (Model Context Protocol) is an open protocol that lets an AI agent call your app's functionality as tools instead of a human clicking through admin UI. A server can expose tools, resources and prompts; this one uses tools only, seventeen of them (see Default Tools).
Architecture
AI Agent (Claude Code, Claude, ChatGPT, Cursor, …)
│ POST /admin/mcp/oauth (Streamable HTTP, stateless)
│ Authorization: Bearer <OAuth access token> - every request
v
McpAdminServiceTransportController
per-IP rate limit, then handleStatelessPost:
verify the token, check its user is still an
admin, then a throwaway McpServer + transport
per request, discarded on close. GET/DELETE → 405
v
McpAdminService oauthTokenSecret + userAllowed + registerTools.
No session store, no per-request state
v
McpAdminToolsService register the tool surface on each per-request
server instance, one mcp-admin-*.tools.ts per
domain: blog, users, email, billing, grants,
plus get_server_info
v
BlogService · UsersService · EmailService · EmailStatsService · BillingService
The MCP and OAuth routes are @ApiExcludeController(), so they never appear in the OpenAPI spec or Swagger UI. They are a parallel surface. The one exception is POST /admin/mcp/oauth/approve, the consent page's Allow, which the frontend calls through its typed client like any other admin route.
Endpoint
All MCP communication goes through one route using stateless Streamable HTTP transport:
| Method | Path | Purpose |
|---|---|---|
POST |
/admin/mcp/oauth |
Send tool calls and JSON-RPC messages |
GET |
/admin/mcp/oauth |
405: no SSE push channel in stateless mode |
DELETE |
/admin/mcp/oauth |
405: no session to tear down |
Authentication
OAuth 2.1, with the app's own sign-in as the consent. There is no shared API key: an agent acts as the admin who approved it, and loses access the moment that person does.
OAuth
An MCP client sends its first request without a token, gets a 401 whose WWW-Authenticate challenge points at the discovery documents, registers itself (POST /admin/mcp/oauth/register) and opens GET /admin/mcp/oauth/authorize in the browser. That checks the request (registered client, redirect URI, a PKCE challenge with code_challenge_method=S256, response_type=code) and redirects to the frontend's consent page, /mcp/authorize, carrying client_id, redirect_uri, code_challenge and state.
The consent page (frontend/app/mcp/authorize/) sends a signed-out visitor to sign in and back, refuses anyone without is_admin, and shows an admin an Allow button. Allow is a Server Action that calls POST /admin/mcp/oauth/approve with the admin's session. SessionGuard identifies the user and McpAdminService.userAllowed admits only an admin, the same rule every MCP call and refresh applies. The backend checks the client, the redirect URI against the ones that client registered, and the PKCE challenge again, since the parameters come back from the browser; then it mints a single-use auth code bound to the admin's user id, valid for five minutes, and returns the client's redirect URL with the code in it. Pending codes live in memory: one user holds at most 10 (the factory's maxAuthCodesPerUser), and approving an eleventh drops that user's oldest, so one account cannot fill the pool; the pool as a whole is capped at maxAuthCodes (default 1000), beyond which approval answers 503.
/token exchanges the code (PKCE S256) for an access token valid for one hour (expires_in: 3600) and a refresh token that trades for a fresh pair. Every token descended from one consent belongs to a family that ends 30 days after that consent: refreshing never extends it, and the last access token expires with it, after which the admin authorizes again. Both tokens carry the admin's user id and are HMAC-SHA256 signed with a key derived from INTERNAL_API_TOKEN (mcp-shared/mcp-oauth.tokens.ts). A refresh token authenticates nothing but the refresh grant.
Every MCP call, code exchange and refresh looks the user up (McpAdminService.userAllowed) and refuses one that no longer exists or no longer has is_admin: the MCP call with a 401, the exchange and refresh with invalid_grant. Taking an admin's rights away, or erasing the account, ends their agents' access on the next call.
Each consent is recorded as a grant in mcp_admin_oauth_grants (mcp-admin/mcp-admin-grants.service.ts) with the approving user, and the refresh token carries its grant id and the client_id it was issued to. A refresh must send that same client_id (OAuth 2.1 §4.3.1; RFC 6749 §6 leaves it optional) and is refused with invalid_grant once the grant is revoked or past its 30-day end. A refresh token stays replayable until then, since nothing marks it used. Revoking a grant takes full effect when its current access token expires, within an hour, because only the user is checked per call, not the grant. Rows past their end are deleted whenever a new consent is recorded.
Registered clients live in mcp_admin_oauth_clients (mcp-admin/mcp-admin-clients.service.ts), so a restart or a deploy keeps every connected client registered. The table keeps the 1,000 most recently used clients. Auth codes live in process memory for their five minutes, so an authorization in flight during a deploy has to be started again.
To revoke one connection, use MCP connections in the backoffice (/backoffice/connections, backed by GET /admin/mcp/grants and POST /admin/mcp/grants/{id}/revoke), or the admin_get_oauth_grants and admin_revoke_oauth_grant tools. The connector has to authorize again. Rotating INTERNAL_API_TOKEN revokes everything at once: every minted token stops verifying.
Client registration is open, so anyone can register a client with a redirect of their own and send you that client's genuine /authorize link; the consent page is on your domain and an admin is signed in. To keep such a client from receiving a code, a redirect_uri is accepted only if it is HTTPS on an allowed origin, or an http or https URL on localhost, 127.0.0.1 or [::1] (any port, for native clients). /register, /authorize and /approve all enforce this. ADMIN_MCP_OAUTH_REDIRECT_ORIGINS sets the allowed origins: comma-separated https://host[:port] values with no path, defaulting to https://claude.ai,https://claude.com,https://chatgpt.com, the sites the browser connectors redirect to and where an attacker cannot read the code. Setting it replaces the defaults, so list those too if you still use them. A connector that redirects to another origin fails to register with invalid_client_metadata until you add its origin. An entry that is not an https origin (claude.ai, https://claude.ai/) refuses boot.
The allowlist narrows who can receive a code but does not remove the risk: the consent page shows only the redirect origin, and an attacker can still start a flow from their own session at an allowed site, so safety then rests on that site binding state to the browser that started it. Approve only a connection you started yourself.
The consent page is served with the frontend's frame-ancestors 'none' and X-Frame-Options: DENY, and the backend's error pages for the flow send the same, so no other site can frame them. Allow is a Server Action, which Next.js accepts only as a same-origin POST, so another site cannot submit it for a signed-in admin.
Boot checks
INTERNAL_API_TOKEN keys the tokens. Boot fails if it is unset, shorter than 32 characters or a placeholder, unless NODE_ENV is development or test, which warn and continue. See What refuses boot. FRONTEND_URL must point at the frontend, since /authorize redirects to the consent page there; a deployment without it refuses to boot.
Agent guidance (initialize instructions)
The MCP initialize result carries an instructions string, the one handshake channel clients are expected to inject into the agent's context. McpAdminService.serverInstructions supplies it: what the server is, its tool domains, and write etiquette (confirm with the human before queueing email, deleting posts or revoking a connection). A server built on mcp-shared that leaves serverInstructions unset falls back to its serverDescription (see mcp-shared/mcp-stateless.ts).
Stateless by design
There are no MCP sessions. Each POST builds a throwaway McpServer + StreamableHTTPServerTransport (sessionIdGenerator: undefined; see mcp-shared/mcp-stateless.ts), handles the one request, and discards both when the response closes. No Mcp-Session-Id is ever issued.
Because no in-memory session map pins you to one backend process, any replica can serve any request, and deploys and restarts are invisible to connected agents. A client that caches session ids across server restarts cannot break, because there is nothing to go stale. There is also no cap, eviction or TTL machinery to tune or to leak.
In exchange there is no server-initiated push (notifications, sampling, elicitation), and the tool registry is rebuilt per request. The default tools are cheap closures, so the rebuild costs microseconds. Add a session layer only once you need push or expensive per-connection setup.
Rate limiting
Every MCP route runs a per-client rate limiter from mcp-shared/mcp-rate-limit.ts before any transport work: 1200 req/min by default on the transport (tunable via MCP_RATE_LIMIT_PER_MIN), and 60 discovery, 10 /register, 30 /authorize and 60 /token requests per minute. A client is an IPv4 address or a whole IPv6 /64, the same as in the global throttler. That throttler (100 req/min per route and IP) also covers these routes, so a transport budget above 100 never binds.
Default Tools
The starter registers seventeen tools. McpAdminToolsService calls one register function per domain, each in its own file in backend/src/mcp-admin/: mcp-admin-blog.tools.ts, mcp-admin-users.tools.ts (users and abandoned deletions), mcp-admin-email.tools.ts, mcp-admin-billing.tools.ts and mcp-admin-grants.tools.ts. Every tool is a thin adapter over an existing domain service.
Blog authoring:
| Tool | Purpose |
|---|---|
admin_get_blog_posts |
Paginated list of all posts (drafts included), with total. |
admin_get_blog_post |
One post by id, full admin detail. |
admin_create_blog_post |
Create a draft (markdown body). |
admin_update_blog_post |
Update fields (set isPublished=true to publish). |
admin_delete_blog_post |
Permanent delete. |
The blog write tools cap body at 30,000 characters because the endpoint's JSON request cap is 32kb; use the backoffice for longer posts. Their other fields take the REST limits from blog.schemas.ts. JSON escapes newlines, quotes and non-ASCII text into more bytes than characters, so a post near the cap can still be refused with a 413.
Operations:
| Tool | Purpose |
|---|---|
admin_get_user |
Look up one user by email address. |
admin_get_users |
Paginated user list, newest first, with the all-time total. |
admin_get_signup_count |
Signup count over the last N days (default 7). |
admin_get_email_stats |
Email queue health: overall totals + success rate, per-campaign stats, daily send volume, recent failures. Same data as the admin email dashboard. |
admin_get_email_campaign |
One campaign's stats by campaign id. |
admin_get_abandoned_deletions |
User-deletion queue rows the worker gave up on. A row may have failed during local erasure, Stripe cleanup, or queue bookkeeping. Inspect lastError before deciding how to recover it. Empty is healthy. |
admin_requeue_abandoned_deletions |
Write: requeue every abandoned deletion after the underlying cause is fixed. The description instructs agents to confirm with the human first. |
admin_get_billing_entitlement |
A user's entitlement (effective plan, paid access, status) by user id or email. With billing dormant (no Stripe config) it reports that state instead of erroring. |
admin_queue_emails |
Write: queue one or more emails (optionally as a campaign) through EmailService.queueBulk. The description instructs agents to confirm with the human first. |
admin_get_oauth_grants |
Paginated active OAuth connections, newest first, with the total: grant id, client name and client_id, created, last refreshed, expires. |
admin_revoke_oauth_grant |
Write: revoke one OAuth connection by grant id and return it. Its access token keeps working until it expires, within an hour. The description instructs agents to confirm with the human first. |
Discovery:
| Tool | Purpose |
|---|---|
get_server_info |
Shared discovery/introspection tool from mcp-shared/server-info-tool.ts: returns a markdown summary of the server's name, purpose, and every other tool safeTool registered, with its description, so an agent can orient itself in one call. |
Ghost users: deleted accounts keep their DB row with PII rewritten (UsersService.ghostDelete). The user tools collapse those rows to { id, deleted: true }, so not even the ghost placeholder values reach agent context.
When MCP creates a post, it's attributed to the seeded MCP admin user (MCP_ADMIN_USER_ID from src/users/user-account.ts, sentinel email [email protected]). The auth-adapter refuses that user's magic-link sign-in by its id, so changing the address does not open a sign-in.
Adding a New Tool
To add a tool, call safeTool(...) in the register function of its domain (backend/src/mcp-admin/mcp-admin-<domain>.tools.ts). For a new domain, add a file with a register<Domain>Tools(server, ...services) function and call it from McpAdminToolsService.registerTools, and add a line for the domain to SERVER_INSTRUCTIONS in mcp-admin.service.ts. get_server_info lists whatever safeTool registered, so there is no list to update. A tool that writes also goes in the writes map in mcp-admin-tools.service.spec.ts with its annotation, because every other tool must be readOnly. safeTool (from mcp-shared/mcp-tools.utils.ts) wraps the raw SDK registration, adds automatic error handling, types the handler's params from the input schema, and takes a ToolAnnotations argument. Use the shared annotation sets (readOnly, creates, updates, deletes) so agents get accurate read-only/destructive hints. Wrap the return payload in textContent(...) for consistent JSON wire shape:
safeTool(
server,
'admin_create_task', // tool name (lowercase + underscores)
'Create Task', // title (human-readable)
'Create a new task', // description (shown to agents)
{ // input schema (Zod raw shape)
title: z.string().describe('Task title'),
assigneeId: z.string().optional().describe('User id to assign to'),
},
creates, // ToolAnnotations: readOnly | creates | updates | deletes
async ({ title, assigneeId }) => {
const task = await tasksService.create({ title, assigneeId });
return textContent(task);
},
);
Tips:
- Lowercase + underscores for tool names.
- Use
.describe()on every zod field. Agents read those descriptions when deciding what to pass. - Pick the annotation set that matches the operation:
readOnlyfor reads,creates/updates/deletesfor writes. They set thereadOnlyHint/destructiveHint/idempotentHintflags agents key off. - Return
textContent(payload). It JSON-encodes the payload into the MCP{ content: [{ type: 'text', text }] }shape. - A paginated list takes
pageShapeas its input schema (spread it to add fields) and converts withtoOffset(params), returning{ items, total }. - Don't add your own try/catch.
safeToolcatches thrown errors and returns anisError: trueresponse, so you can let service exceptions propagate.
If the new tool needs a service the MCP module doesn't already see, import it via McpAdminModule.imports.
Connecting an Agent
Point the client at https://your-backend/admin/mcp/oauth as a Streamable HTTP server with OAuth, for example claude mcp add --transport http crabstack-admin https://your-backend/admin/mcp/oauth in Claude Code. The client opens a browser tab; sign in to the app as an admin and press Allow. There is no key to paste or store.
The first admin is granted with npm run admin:grant -- <email> (see backend/CLAUDE.md); after that, admins grant and revoke from /backoffice/users.
Related
- Architecture - Where MCP fits in the module graph
- Auth Flow - The sign-in the consent page relies on
- Adding a Module - Backend modules whose services MCP tools can call
- Environment Variables -
INTERNAL_API_TOKEN,FRONTEND_URL,ADMIN_MCP_OAUTH_REDIRECT_ORIGINS