An OpenAI-compatible /v1/chat/completions endpoint in front of the claude CLI.
Point any OpenAI-shaped client at it and inference runs through your existing Claude
Code subscription instead of a metered API key.
Requests run with Claude Code's built-in tools disabled, but
CCAPI_AGENTIC_TEXT=1brings backclaude --print --dangerously-skip-permissionsfor tool-free requests, with Bash, Read, Write, and Edit available and every permission prompt disabled. Treat the request body as an instruction that can execute code as the user running the server.Every route except
GET /healthrequires a shared secret from theCCAPI_TOKENenvironment variable. If it is unset, the service starts and refuses everything with a401. It also binds127.0.0.1by default. Keep both: the token is authorization, the loopback bind is containment. ReadSECURITY.mdbefore running it, and do not expose the port.
pip install aiohttp anthropic
# Mint a secret. Anything guessable defeats the point.
export CCAPI_TOKEN="$(python3 -c 'import secrets;print(secrets.token_urlsafe(32))')"
python3 server.py # 127.0.0.1:18782
# /health needs no token and tells you whether auth is configured.
curl -s http://127.0.0.1:18782/health
# Everything else does.
curl -s http://127.0.0.1:18782/v1/models -H "Authorization: Bearer $CCAPI_TOKEN"- Checks the shared secret.
Authorization: Bearer <token>orX-CCAPI-Token: <token>, compared againstCCAPI_TOKENwithhmac.compare_digest. No match, no work:401, and the subprocess is never spawned. - Receives an OpenAI-format
POST /v1/chat/completions. - Flattens the
messagesarray into a single prompt string, piped to the subprocess on stdin (a CLI argument overflows with[Errno 7] Argument list too longon large contexts). - Invokes
claude --print --dangerously-skip-permissions --model <model> --output-format json --no-session-persistence, holding anasyncio.Semaphoreso no more thanCCAPI_MAX_CONCURRENT(default 3) subprocesses run at once. - Returns an OpenAI-compatible completion object, or chunked SSE if
stream: true.
Every request is one isolated CLI turn (_run_claude_cli): --input-format stream-json, built-in tools off (--tools ""), no user/project settings, CLAUDE.md
or hooks (--setting-sources ""), the caller's system prompt in place of Claude
Code's. Images travel as stream-json image blocks. Caller tools are bridged in as
MCP tools and come back as tool_calls (see Known limitations).
Images used to go to api.anthropic.com directly with the OAuth access token. That
started failing (429 rate_limit_error, measured 2026-10-05) once Anthropic began
billing third-party use of subscription tokens separately, so it was removed.
CCAPI_AGENTIC_TEXT=1 restores the old behaviour for requests without tools:
--output-format json, --dangerously-skip-permissions, Claude Code's own tool loop,
text only. Nothing measured on 2026-10-05 needed it.
claudeCLI installed, authenticated, and on the server process'sPATH.- Python 3.11+ with
aiohttpandanthropic. TheanthropicSDK is required, not optional: it is imported at module scope and is used for hourly model discovery even if you never send an image.pip install aiohttp anthropic
- A value for
CCAPI_TOKEN. Without it the server starts but answers401on everything except/health.
There is one server: server.py. A legacy Node implementation (server.js, Express,
port 3456) was deleted on 2026-08-16. It was never deployed, and it never had the
token gate. See git log -- server.js.
python3 server.py # 127.0.0.1:18782
python3 server.py --port 3456 # different port
python3 server.py --host 0.0.0.0 # DO NOT. See SECURITY.md.
python3 server.py --debug # verbose logging| Setting | Where | Default | Notes |
|---|---|---|---|
CCAPI_TOKEN |
env | unset | The shared secret. Required by every route except GET /health. Unset or blank means everything 401s. Never commit a value. |
| listen port | --port |
18782 |
|
| listen host | --host |
127.0.0.1 |
Leave it. |
CCAPI_MAX_CONCURRENT |
env | 3 |
Concurrent claude subprocesses. |
CCAPI_AGENTIC_TEXT |
env | unset (off) | 1 makes tool-free requests run Claude Code's own Bash/Read/Write loop under --dangerously-skip-permissions again. This is a security setting. |
CLAUDE_API_LOAD_MCP |
env | unset (off) | Only with CCAPI_AGENTIC_TEXT=1: boots the host's MCP servers inside every subprocess. Roughly doubles per-request latency and widens the blast radius. This is a security setting. |
CLAUDE_CODE_MAX_OUTPUT_TOKENS |
env (read by the claude CLI, inherited by every child) |
CLI default | Output ceiling per turn. This service ignores a request's max_tokens, so this is the only output cap on the path. The CLI clamps it to the model's own maximum: with 1000000 set it still sends max_tokens: 128000 for every Claude 5.x model (captured on the wire, 2026-10-06). The maintainer runs 1000000 so the setting never limits below whatever a model allows. |
REQUEST_TIMEOUT |
constant, server.py |
1800 s |
Per-call ceiling. Not an env var. |
QUEUE_TIMEOUT |
constant, server.py |
90 s |
How long a request waits for a semaphore slot before giving up. |
DEFAULT_MODEL |
constant, server.py |
claude-opus-5 |
Used for an unrecognised model name. |
Send the secret as either header. Bearer is preferred, because an OpenAI-compatible
client already sends its configured api_key that way and needs no custom header
plumbing:
curl -H "Authorization: Bearer $CCAPI_TOKEN" ...
curl -H "X-CCAPI-Token: $CCAPI_TOKEN" ...A failure returns 401 in the OpenAI error shape, so clients report it as an auth
problem rather than a generic server error:
{"error": {"message": "Invalid token.", "type": "invalid_request_error", "code": "invalid_api_key"}}If CCAPI_TOKEN is unset the message instead names the variable to set, and
/health reports "auth": "unconfigured". Nothing is served in that state; the
process stays up only so the failure is diagnosable. Full rationale, storage, and
rotation are in SECURITY.md.
POST /v1/chat/completions, GET /v1/models, and GET /health. The two /v1 routes
are also registered without the prefix (/chat/completions, /models) for
clients that do not add it. All four require the token. Only GET /health does
not.
{
"model": "claude-sonnet-4-6",
"messages": [
{ "role": "system", "content": "You are a helpful assistant." },
{ "role": "user", "content": "What is 2+2?" }
],
"stream": false
}Non-streaming returns a standard OpenAI chat completion object. Streaming returns
text/event-stream SSE in OpenAI delta format, terminated with data: [DONE].
Errors return HTTP 500 with {"error": {"message": ..., "type": "server_error"}},
or, mid-stream, an error object emitted as one final SSE frame.
Returns the current model list. The set is seeded from a static list in server.py
and then refreshed from the Anthropic API at most once an hour, so a newly
released model appears without a code change. Discovery failures are logged and
fall back to the static seed.
The only route that needs no token, so nothing sensitive belongs in it.
{
"status": "ok",
"service": "claude-code-api",
"port": 18782,
"auth": "required",
"model_discovery": { "ok": true, "last_success_age_seconds": 120, "stale": false,
"models_served": 12, "last_error": null }
}auth is "required" when CCAPI_TOKEN is set and "unconfigured" when it is not.
It never contains the secret. model_discovery.last_error is truncated, because it is
an arbitrary exception string on an open endpoint; the journal has the full text.
Known wart: the reported
portis the module-levelPORTconstant, not the value passed to--port. If you start the server on a non-default port,/healthstill reports18782. Trustss -tlnpover this field.
DEFAULT_MODEL is claude-opus-5. The static seed set is the Claude 5 family
(claude-opus-5, claude-sonnet-5, claude-fable-5) plus retained 4.x ids
(claude-opus-4-8, claude-opus-4-7, claude-opus-4-6, claude-sonnet-4-6,
claude-haiku-4-5, claude-haiku-4-5-20251001), plus whatever hourly discovery adds.
Aliases are accepted so OpenAI-shaped clients work unmodified:
| You send | You get |
|---|---|
gpt-4, gpt-4-turbo, opus |
claude-opus-5 |
gpt-4o, sonnet |
claude-sonnet-5 |
fable |
claude-fable-5 |
gpt-4o-mini, gpt-3.5-turbo, gpt-3.5-turbo-16k, haiku |
claude-haiku-4-5 |
Provider-prefixed names are accepted too: explicit claude/... and anthropic/...
entries are mapped, and any other prefix/model has the prefix stripped before
lookup. An unrecognised name logs a warning and falls back to DEFAULT_MODEL rather
than erroring.
claude-code-api.service in this repository is a systemd user unit. It must be a
user unit: the subprocess needs the invoking user's HOME, PATH, and
~/.claude/.credentials.json.
# 1. Mint the secret first. The unit reads it from this file, not from a tracked
# Environment= line, because `systemctl show` prints those in the clear.
umask 077
printf 'CCAPI_TOKEN=%s\n' "$(python3 -c 'import secrets;print(secrets.token_urlsafe(32))')" \
> ~/.config/claude-code-api.env
chmod 600 ~/.config/claude-code-api.env
# 2. Then install the unit.
cp claude-code-api.service ~/.config/systemd/user/
systemctl --user daemon-reload
systemctl --user enable --now claude-code-api.service
systemctl --user status claude-code-api.service
journalctl --user -u claude-code-api.service -fConfirm it came up authenticated before pointing a client at it:
curl -s http://127.0.0.1:18782/health | grep -o '"auth": *"[a-z]*"' # want: "required"Adjust the checkout path in ExecStart if you did not clone to
~/clawd/skcapstone-repos/claude-code-api. SOP.md documents the
maintainer's live deployment, including where it currently differs from this file.
Any OpenAI-compatible client works. The maintainer's setup consumes it from
Hermes (Lumina's Telegram runtime) through skgateway (:18780), whose
anthropic backend fronts this service. Hermes never talks to :18782 directly, and
never to api.anthropic.com: direct calls with the subscription token are billed as
third-party usage and fail.
~/.hermes/config.yaml is not under version control, so
examples/hermes-config.yaml is the source of truth
for the keys that touch this service: main model via skgateway, the skgateway
provider, and the two settings native images need (agent.image_input_mode: native
and per-model supports_vision: true under providers; either one alone still
routes images through sk-vision). Merge those keys into your own config; it is not a
complete Hermes config.
The CCAPI_TOKEN is held by skgateway's anthropic backend, not by Hermes.
Things that broke before and how to spot them:
- Every Telegram turn fails with "model provider failed after retries". From
2026-09-17 to 2026-10-04 this service refused any request carrying
toolswith400 tools_not_supported, and Hermes sends tools on every turn. Fixed by the MCP bridge (#7). If it recurs,~/.hermes/logs/errors.lognames the 400. - Images described instead of seen. Check for
| imageson the→line injournalctl --user -u claude-code-api. If it is missing andtools.vision_tools: Analyzing imageappears in~/.hermes/logs/agent.log, one of the two settings above is missing. - Switching models with
/modelsaves toconfig.yaml(--global). Any claude-* model works through this service now; a model missing from theprovidersblock gets images through sk-vision.
To confirm end to end: hermes chat -q "Run 'date' with your terminal tool" should
show a tool call in the session, and hermes chat --image <png> -q "what color?"
should log | images here.
- Authentication is one shared secret. No identities, no scopes, no per-caller audit trail. Anyone holding the token can run anything the service account can run, which is why the loopback bind stays.
- Concurrency is capped, not unlimited. Default 3. Beyond that, requests wait up
to
QUEUE_TIMEOUT(90 s) for a slot and then fail. - Caller tools are served through an MCP bridge, statelessly. A request with
toolsshows those tools to claude as native MCP tools (built-in tools off, the service account's settings and CLAUDE.md not loaded). claude'stool_useblocks come back as OpenAItool_calls(parallel calls included, realtoolu_ids). The next request's tool results are rendered into the prompt as text, so prior tool turns are not nativetool_useblocks. - No cross-request memory. Every call uses
--no-session-persistence. - Streaming is not token-by-token. SSE chunks are word-boundary splits of an already-complete response, so time-to-first-token equals full generation time.
usagecounts come from the CLI's own report and are0when it does not supply them.- Tests stub the CLI. The
cisuite covers the token gate, request translation (transcripts, images, tool names), tool_calls responses (stream and not), text-path isolation, the queue slot, discovery, and stream-json parsing against a fakeclaude. A real model round trip is still verified by hand, perSOP.mdsection 4.
| File | What it covers |
|---|---|
SOP.md |
Architecture, deploy, rollback, troubleshooting, live deployment facts. |
SECURITY.md |
Threat model, credential handling, disclosure. Read before running. |
CONTRIBUTING.md |
How to change it, and how to verify a change without a test suite. |
CHANGELOG.md |
Reconstructed from git history. |
ISC. See LICENSE.