AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The Clerk CLI is a powerful tool for interacting with Clerk's Backend and Platform APIs. It streamlines development workflows by handling authentication, environment key management, and instance configuration without requiring manual HTTP requests. It is designed to be used in both local development and automated environments, providing a structured way to manage users, organizations, and security settings.
What it does
- Manages user, organization, and session data via the Backend API.
- Handles instance configuration, including social providers and security settings.
- Automates environment key synchronization and local webhook testing.
- Provides diagnostic tools to verify project linking and CLI health.
- Supports secure impersonation for testing and debugging user flows.
- Enables platform-level management of applications and billing.
When to use it
- When you need to perform administrative tasks like listing or modifying users.
- When setting up or verifying environment variables for a Clerk-integrated project.
- When auditing or hardening the security configuration of a Clerk instance.
- When debugging API interactions or testing webhooks in a local environment.
- When you need to perform bulk operations or scripted management of Clerk resources.
Advantages
- Reduces manual effort by automating authentication and key resolution.
- Provides a consistent, structured interface for both Backend and Platform APIs.
- Includes safety features like dry-run modes for destructive operations.
- Integrates seamlessly into CI/CD pipelines and automated agent workflows.
- Offers built-in diagnostic commands to quickly resolve configuration issues.
Usage examples
- “List the first 50 users in my Clerk instance.”
- The agent runs 'clerk users list --json --limit 50' and processes the output to display the requested user information.
- “Check if my project is correctly linked to Clerk.”
- The agent executes 'clerk doctor --json' to verify the project's link status and overall health, reporting any issues found.
- “Pull the latest environment keys for my project.”
- The agent runs 'clerk env pull' to update the local .env.local file with the current project keys.
- “Dry-run a patch to my instance configuration.”
- The agent executes 'clerk config patch --dry-run' with the specified changes to preview the impact before applying them.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/clerk/clerk-cli/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip clerk-cli.zip -d .agents/skills
Documentation by Clerk
Clerk CLI
The clerk binary is a pre-authenticated gateway to Clerk's Backend API and Platform API, plus project-level tooling (auth, linking, env pulls, instance config). When the user asks anything that touches a Clerk resource, reach for clerk first instead of hand-rolling curl.
For setup or init requests, use the clerk-setup skill as the source of truth. Its package-runner, accountless, migration, and init-first guidance takes precedence over the general operational prerequisites below.
This skill targets clerk
latest. Ifclerk --versiondisagrees with the latest available CLI, refresh it withclerk update, or invoke the latest through a package runner such asbunx clerk@latest. The binary is always the source of truth, so runclerk <command> --helpto verify anything this skill claims.
Execution environment (prefer the host, understand the sandbox warning)
Most AI coding agents default to running shell commands in a sandbox where the user's home directory, OS keychain, browser launch, localhost callback binding, or network access may be blocked. The Clerk CLI depends on all of those host capabilities:
OS credential store:
clerk auth loginstores the OAuth token in the system keychain. A sandbox without keychain access reports "not logged in" even when the host is authenticated.Home-directory Clerk state: saved config, cached metadata, and fallback credentials live under the user's Clerk config/data directories.
Linked project metadata: resolved from the repo's git remote plus Clerk config. Sandboxes with stripped repo state or blocked home-dir reads can misreport "not linked".
Local
.env*files: publishable and secret keys materialized byclerk env pull.Outbound network access to Clerk: every Backend and Platform API call.
Browser + localhost OAuth callback:
clerk auth loginneeds both.
In agent mode, the CLI now does a best-effort warn-once check at the host-sensitive library boundaries. When it detects that host-only Clerk state or system capabilities are unavailable, it emits:
Host-only Clerk state or system capabilities may be unavailable in agent mode. This may be a sandboxed run.
Re-run this command on the host shell before trusting auth, link, env, or API failures.Treat that warning as authoritative. The command may continue, but any auth, link, env, config, API, browser, or OAuth callback failure from that invocation is untrusted until you rerun the same command on the host.
Prefer these commands on the user's host shell, not in a sandbox:
clerk doctor, clerk whoami, clerk auth login, clerk link, clerk env pull,
clerk apps ..., clerk config ..., clerk api ....
If a command was accidentally run in a sandbox and it reports Not logged in,
auth_required, not linked, missing env, keychain/file permission errors,
or network failures, do not treat the result as authoritative. Rerun it on
the host before acting on it or reporting it to the user.
Invoking the CLI
Before running any clerk command, figure out which binary to invoke and bind that choice for the rest of the session:
# 1. Prefer a globally installed binary when it matches the skill's target version.
command -v clerk >/dev/null 2>&1 && clerk --versionIf that prints latest or any version you trust, use bare clerk for the rest of the session.
Otherwise fall back to a package runner, in this order (matches the CLI's own preferredRunner logic, which prefers the runner that matches the project's lockfile):
| Project package manager | Invocation |
|---|---|
bun (bun.lock*) | bunx clerk@latest |
npm (package-lock.json) | npx -y clerk@latest |
pnpm (pnpm-lock.yaml) | pnpm dlx clerk@latest |
yarn >= 2 (yarn.lock) | yarn dlx clerk@latest |
Yarn Classic (v1) has no dlx; treat those projects as "no preferred runner" and fall back to the first runner from the list above that's on PATH.
The published npm package is clerk, not @clerk/cli. Never teach npm install -g clerk as the primary path. If the global CLI is stale or behaves differently from this skill, either upgrade the global install or fall back to the latest runner form above.
Prerequisites (run at session start for non-setup operations)
Except when following clerk-setup, verify the CLI is authenticated, linked, and healthy before running other Clerk commands in a session:
clerk --version # confirm the binary is on PATH
clerk doctor --json # structured health check; exit 1 if anything failedAlways run clerk doctor --json first. It catches the common setup failures (not logged in, project not linked, missing keys, stale CLI version) up front, so later commands don't fail with confusing errors. In agent mode it also includes a Host execution check that warns when Clerk's host-side config / credential directories are not writable, which is the canonical signal that the current invocation is likely sandboxed.
Each result has name, status (pass/warn/fail), message, optional detail, optional remedy (how to fix it), and optional fix (label for auto-fixable issues). Parse that and act on it, or surface it to the user. If Host execution warns, rerun the command on the host before trusting any auth/link/env/API failures from the same sandboxed run. Rerun clerk doctor --json whenever a later command starts misbehaving.
If clerk --version reports a newer CLI than this skill covers, trust clerk <command> --help first and refresh this skill bundle from its source. The reverse also applies: --accountless and the accountless JSON keys ship in CLI 3.3+ — on an older CLI, use the --keyless alias or upgrade.
Accountless setup
clerk init does not require clerk auth login: on a framework with accountless support, an unauthenticated bootstrap with no --app, or an unauthenticated agent run with no --app or existing project link, mints an unclaimed accountless app with temporary development keys — no account, no browser, no flag. (A signed-out human re-running it in an existing project gets the login flow instead — --accountless forces the temporary-keys path.) Most instance commands then work on that key alone.
Two things to know before you use it: the accountless path follows whatever sk_ key is local — sk_live_ included, claimed or not — so pass --app <id> when you mean a real app; and clerk open returns a credential-equivalent claim URL, never safe to paste into a log or PR.
Which commands need an account, and the full rules: auth.md.
The mental model
| Layer | What it does | Commands |
|---|---|---|
| Session / project | Auth, link a repo to a Clerk app, pull env keys | auth login, link, unlink, whoami, env pull, doctor |
| Instance config | Manage the configuration (social providers, session lifetimes, etc.) for a specific instance | config pull, config schema, config patch, config put |
| Backend API (default) | Runtime data: users, orgs, sessions, invitations, JWT templates, webhooks | clerk api <path> |
Platform API (--platform) | Account-level: applications, instances, billing | clerk api --platform <path> |
Frontend API (--fapi) | The instance's public client-facing API (what clerk-js calls) | clerk api --fapi <path> |
A project is "linked" to an application via clerk link. Once linked, most commands auto-resolve the target app and dev instance from the repo's git remote. To target something else, pass --app <id> and/or --instance dev|prod|<instance_id>. See references/auth.md for the full resolution order.
Discover endpoints - don't memorize them
The CLI ships with the Clerk OpenAPI catalog. Always discover endpoints dynamically instead of guessing paths:
clerk api ls # list every Backend API endpoint
clerk api ls users # filter by keyword (matches path, summary, tag, operationId)
clerk api ls --platform apps # list Platform API endpointsUse this before clerk api <path>. If you don't see the endpoint you expected, it probably isn't exposed.
The clerk api command (the workhorse)
clerk api makes authenticated HTTP calls. It auto-resolves keys, auto-detects method from body presence, supports stdin, and can preview mutations with --dry-run.
# GET requests
clerk api /users # list users
clerk api /users/user_abc123 # fetch one
clerk api /users?limit=5&order_by=-created_at # query params work inline
# Mutating requests
clerk api /users -d '{"email_address":["[email protected]"]}' # POST (auto-detected from body)
clerk api /users/user_abc123 -X PATCH -d '{"first_name":"A"}'
clerk api /users/user_abc123 -X DELETE
# Body from file or stdin
clerk api /users --file payload.json
cat payload.json | clerk api /users
# Always preview mutations first
clerk api /users/user_abc123 -X DELETE --dry-run
clerk api /users/user_abc123 -X DELETE --yes # skip confirmation once you've verified
# Target a specific app/instance
clerk api /users --app app_abc123 --instance prod
# Include response headers when debugging
clerk api /users --include
# Platform API (account-level, not tenant data)
clerk api /v1/platform/applications --platform
# Frontend API (the instance's public client-facing API — what clerk-js calls.
# Unauthenticated; --fapi and --platform cannot be combined, --secret-key is ignored)
clerk api --fapi /environmentIn human mode, clerk api with no arguments opens an interactive request builder; in agent mode it prints usage guidance and exits 0 — always pass an endpoint (or ls) explicitly from scripts.
For instance config, prefer the dedicated clerk config ... commands over raw Platform API /config paths. They handle dry-run, diffing, and confirmation more cleanly than the raw endpoint form.
Always --dry-run a mutation before running it for real. Then re-run without --dry-run (add --yes if you're sure). In agent mode, interactive confirmation is bypassed, so --dry-run is the only safety net for destructive calls.
JSON bodies must be valid JSON. The CLI validates and rejects malformed payloads.
Endpoint paths may be given with or without /v1/ prefix - both work for Backend API calls. The CLI normalizes.
See references/recipes.md for concrete patterns: listing/filtering users, creating orgs, impersonation sessions, etc.
Inspecting large outputs (do not flood your context)
users list, apps list, config pull, and most clerk api GETs return payloads that can be many kilobytes or megabytes. Production tenants commonly have thousands of users; an instance config can be hundreds of fields deep. Reading those responses into the conversation costs context window for no benefit. Save the response to a file first, then query just what you need with jq:
# 1. Persist the response. Use --limit 250 to maximize page size for users list.
clerk users list --json --limit 250 > /tmp/users.json
clerk apps list --json > /tmp/apps.json
clerk api /users/user_abc123 > /tmp/user.json
# 2. Inspect only what you need.
jq '.data | length' /tmp/users.json # current page size
jq '.hasMore' /tmp/users.json # are more pages available?
jq '.data[0] | keys' /tmp/users.json # discover the user shape once
jq '.data[] | {id, email_addresses}' /tmp/users.json # project to a few fields
jq '[.data[] | select(.banned)] | length' /tmp/users.json # aggregate without reading rowsIf jq is not available, fall back to Python or Node - both can stream the file without printing it whole:
python3 -c 'import json; d=json.load(open("/tmp/users.json")); print(len(d["data"]), d["hasMore"])'
node -e 'const d=require("/tmp/users.json"); console.log(d.data.length, d.hasMore)'cat / head the file only when you genuinely need to see the raw structure for one-off debugging. When walking pages, write each page to its own file (e.g. page-${offset}.json) so individual pages stay independently inspectable.
Commands
Read the command catalog when choosing a subcommand or flag. Confirm unfamiliar syntax with clerk <command> --help.
Agent-mode behavior (important)
The CLI auto-detects agent mode when stdout is not a TTY, or when --mode agent / CLERK_MODE=agent is set. In agent mode:
Interactive prompts are disabled. Commands that would normally show pickers (
linkwithout--app,unlinkwithout--yes,userswithout a subcommand) either auto-resolve or exit with a usage error.clerk apiwith no args prints usage guidance and exits 0; pass an endpoint (orls) explicitly. Always pass explicit flags in scripted calls:--yes, and--appfor an app the person named that's already in the account.Host-sensitive operations emit a sandbox warning once per invocation. Home-directory Clerk state, keychain access, networked Clerk calls, browser launch, and localhost OAuth callback setup can trigger the warning shown above. If it appears, rerun the same command on the host before trusting the result.
If your harness does not clearly present as agent mode, force it. Use
--mode agentorCLERK_MODE=agentwhen you want the CLI's non-interactive behavior and sandbox warning path to apply deterministically.linksupports deterministic agent flows. In agent mode,clerk link --app <id>links directly. Without--app, newer CLIs signed in to an account first claim the appclerk initcreated in this folder; otherwise the CLI tries silent key-based autolink, and if it cannot determine the app unambiguously, it exits with a usage error.If a Clerk CLI command returns an error with code
not_linked, follow When the folder isn't linked. It covers sandbox checks, unclaimed apps, competing claim files, and older CLIs. Do not assumeclerk linkis the next step.For
init, followclerk-setup. It owns framework-support, accountless, app-linking, migration, and login-order guidance so setup instructions have one source of truth.--freshis destructive. It replaces the temporary app and overwrites the env keys and.clerk/keyless.jsonbreadcrumb with no prompt, orphaning the previous app and its users. Never pass it just to re-runinit.A few commands require
--yesin agent mode.unlink,security fix(unless--dry-run), anddisable orgswhile organization billing is on exit with a usage error without it.updatewithout--yesprints a hint and exits0without updating.Every other confirmation is skipped in agent mode.
config patch/put,apimutations,users create, andenable/disableexecute with no prompt and no error. Passing--yesis harmless but changes nothing. Do not treat it as a safety gate ---dry-runis the real one.Before
security fix, tell the user what changes. Several fixes add a CAPTCHA, verification, second-factor, or passkey step, or force a password reset; findings with acustomFlowsnote break custom sign-in flows until they are updated.mfaandpasswordless-authare product decisions: ask which--factors/--strategyrather than picking. See Audit and harden security.impersonaterequires the[user]positional in agent mode. If a search term matches multiple users, it exits2listing candidate user IDs — retry with a specificuser_...ID. Output is a JSON object ({url, id, userId, actor, ...}); surfaceurlto the user and captureid— it is the only chance to record the revoke handle.webhooks listenis long-running. Run it in the background. In agent mode (or with--json) it emits NDJSON: onereadyline ({type:"ready", relay_url, forward_to}), then oneeventline per delivery — each event line can be fed back toclerk webhooks verify --delivery.doctor --fixis ignored. Parsedoctor --jsonoutput'sremedyfield and act on it yourself.apps listandapps createdefault to JSON when piped.usersdefaults to JSON when piped, likeapps.clerk users listandclerk users createemit JSON in agent mode. Bareclerk users(no subcommand) is a usage error in agent mode - passlist,create, oropenexplicitly.clerk users openrequires theuser-idpositional in agent mode and prints a JSON descriptor instead of launching a browser.deploy --domainneeds a domain the user owns, anddeploy statusis the gate. Ask the user for the domain before runningclerk deploy --domain <domain>. When the wizard is needed (Apple's private key, or the user prefers it), have the user runclerk deployin a separate terminal from the project directory, never through your session or Claude Code's!shell escape. Verify withclerk deploy status --mode agent.deployhas no--appflag: to deploy a specific app, link the folder first withclerk link --app <id>. See Deploy to production.--input-json <json|@file|->expands JSON into flags on any command (e.g.clerk init --input-json '{"framework":"next","yes":true}'). Stdin needs the explicit-marker (echo '{"yes":true}' | clerk init --input-json -); bare piped stdin is not auto-detected, so shell loops and self-reading commands (cat body.json | clerk api …) are untouched. Place--input-jsonafter the leaf subcommand. Full rules in references/agent-mode.md.
Full matrix and sandbox details in references/agent-mode.md.
Output format and errors
JSON output:
--jsononapps listanddoctor. Forclerk api, the response body is the raw API JSON, so pipe intojqfreely.Exit codes:
0success,1runtime error,2usage/validation error.doctorreturns1if any check failed.Error format: User-facing errors print a single line to stderr and set a non-zero exit code. Use
--verbosefor stack traces when debugging.
Safety rules for autonomous use
Discover before acting:
clerk api ls <keyword>beforeclerk api <path>.Preview mutations:
--dry-runon everyconfig patch,config put,security fix,api -X POST/PATCH/PUT/DELETE.Target explicitly in production: pass
--instance prodrather than relying on defaults, and confirm with the user before any production mutation.Never commit secrets:
env pullwrites to.env.local(which should be gitignored). Don't paste secret keys into code or chat.Use
doctor --jsonto diagnose before assuming the CLI is broken.Confirm before impersonating in production:
clerk impersonatebypasses the user's MFA and may count against the impersonation quota.
References
references/auth.md - auth flow, key resolution order, host-vs-sandbox behavior,
--app/--instancetargeting, Backend vs Platform API.references/recipes.md - copy-pasteable recipes for common Clerk tasks.
references/agent-mode.md - agent-mode behavior matrix, sandbox warning semantics, exit codes, error format.
references/commands.md - command catalog with each command's purpose and key flags.
Files
- ATTRIBUTION.mdAdded by AutoGineer753 B
- SKILL.md20.8 KiB
- references/agent-mode.md40.5 KiB
- references/auth.md14.0 KiB
- references/commands.md19.1 KiB
- references/recipes.md11.7 KiB
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Python, Needs Node.js
Security
What our scanner noticed· Low risk
- Instructions that use the network
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Clerk
- Publisher
- Clerk (Official)
- Source
- clerk/skills · skills/clerk-cli · commit c5d2c0d
- Licence
- MIT License (redistribution allowed)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Clerk.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download clerk-cli.zip