Skip to content

About

OpenAI-compatible API wrapper around Claude Code CLI. Subscription-covered Claude access for third-party tools.

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Claude Code API

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.

⚠️ This endpoint runs arbitrary commands. Set CCAPI_TOKEN before you start it.

Requests run with Claude Code's built-in tools disabled, but CCAPI_AGENTIC_TEXT=1 brings back claude --print --dangerously-skip-permissions for 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 /health requires a shared secret from the CCAPI_TOKEN environment variable. If it is unset, the service starts and refuses everything with a 401. It also binds 127.0.0.1 by default. Keep both: the token is authorization, the loopback bind is containment. Read SECURITY.md before running it, and do not expose the port.

Quick start

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"

How it works

  1. Checks the shared secret. Authorization: Bearer <token> or X-CCAPI-Token: <token>, compared against CCAPI_TOKEN with hmac.compare_digest. No match, no work: 401, and the subprocess is never spawned.
  2. Receives an OpenAI-format POST /v1/chat/completions.
  3. Flattens the messages array into a single prompt string, piped to the subprocess on stdin (a CLI argument overflows with [Errno 7] Argument list too long on large contexts).
  4. Invokes claude --print --dangerously-skip-permissions --model <model> --output-format json --no-session-persistence, holding an asyncio.Semaphore so no more than CCAPI_MAX_CONCURRENT (default 3) subprocesses run at once.
  5. 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.

Prerequisites

  • claude CLI installed, authenticated, and on the server process's PATH.
  • Python 3.11+ with aiohttp and anthropic. The anthropic SDK 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 answers 401 on 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

Configuration

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.

Authentication

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.

Endpoints

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.

POST /v1/chat/completions

{
  "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.

GET /v1/models

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.

GET /health

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 port is the module-level PORT constant, not the value passed to --port. If you start the server on a non-default port, /health still reports 18782. Trust ss -tlnp over this field.

Models

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.

Running it as a service

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 -f

Confirm 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.

Using it from a client

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 tools with 400 tools_not_supported, and Hermes sends tools on every turn. Fixed by the MCP bridge (#7). If it recurs, ~/.hermes/logs/errors.log names the 400.
  • Images described instead of seen. Check for | images on the → line in journalctl --user -u claude-code-api. If it is missing and tools.vision_tools: Analyzing image appears in ~/.hermes/logs/agent.log, one of the two settings above is missing.
  • Switching models with /model saves to config.yaml (--global). Any claude-* model works through this service now; a model missing from the providers block 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.

Known limitations

  • 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 tools shows those tools to claude as native MCP tools (built-in tools off, the service account's settings and CLAUDE.md not loaded). claude's tool_use blocks come back as OpenAI tool_calls (parallel calls included, real toolu_ ids). The next request's tool results are rendered into the prompt as text, so prior tool turns are not native tool_use blocks.
  • 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.
  • usage counts come from the CLI's own report and are 0 when it does not supply them.
  • Tests stub the CLI. The ci suite 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 fake claude. A real model round trip is still verified by hand, per SOP.md section 4.

Documentation

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.

License

ISC. See LICENSE.

About

OpenAI-compatible API wrapper around Claude Code CLI. Subscription-covered Claude access for third-party tools.

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages