Skip to content

About

Local HTTPS MITM proxy, API translator, and aggregator for Claude, Gemini, and OpenAI clients

Resources

Stars

7 stars

Watchers

0 watching

Forks

Latest commit

 

History

193 Commits

Folders and files

Repository files navigation

Claude Proxy

A local HTTPS MITM proxy, API translator, and aggregator for Claude, Gemini, and OpenAI clients.

crates.io License: MIT

Features

  • Caches Google OAuth tokens locally to speed up execution
  • Blocks unnecessary Vertex AI heat-up calls natively
  • Deduplicates byte-identical concurrent requests so duplicates don't burn upstream tokens
  • Auto-recovers from expired credentials: when Google returns invalid_grant, opens a browser, runs the consent flow, writes a fresh ADC, and resumes the in-flight request transparently (see wiki/auto-reauth.md)
  • Map Local: return a fixed response (inline body or local file) for a configured URL pattern + method instead of forwarding upstream — silence telemetry, neuter update checks, replay fixtures
  • Gemini for opencode: serves the native Gemini API (/v1beta/models…) for opencode's @ai-sdk/google, routing each model to the gemini-cli or antigravity upstream, with login for each (see Gemini models for opencode below and wiki/gemini-providers.md)
  • Anthropic API: serves POST /v1/messages (+ count_tokens) so Claude Code / the Anthropic SDK can drive the same gemini-cli/antigravity models by a provider-prefixed model name; MITM of api.anthropic.com is prefix-gated so normal Claude usage passes through untouched (see Anthropic API below)
  • Gemini Enterprise seat: serves the Antigravity coding plan entitled by a Gemini Enterprise licence, over the businessaicode API as a fourth provider prefix (aicode/<experience>) on both surfaces, borrowing your gemini-cli credential; the licence's project, region and tier are discovered from :fetchLicenses (see wiki/gemini-providers.md)
  • Claude subscription passthrough: serves POST /v1/messages against the real Anthropic API using your Claude Code OAuth credential from the macOS Keychain (or ~/.claude/.credentials.json on Linux) — so any Anthropic-API client can use your Claude subscription without an sk-ant-api… billing key (see Claude subscription passthrough below and wiki/claude-oauth.md)
  • OpenAI aggregator: serves POST /v1/chat/completions and fans it out to multiple OpenAI-compatible backends (configured under [[openai]]), routing by a provider prefix on the model — a near-pure passthrough, no format translation (see OpenAI aggregator below)
  • Cline provider: serves POST /v1/chat/completions against Cline's own API with your Cline account, as a cline/ model prefix — reusing the cline CLI's existing login if you have one, or claude-proxy login cline if you don't; MITM of api.cline.bot is prefix-gated so your real cline CLI passes through untouched (see Cline provider below and wiki/cline.md)
  • CORS: the origin-mode endpoints (http://127.0.0.1:7777/…) answer browser pages on any origin, so a web app at https://example.com or http://localhost:3000 can fetch them directly (a public site also needs Chrome's Local Network Access permission)
  • Content Compression: Runs SmartCrusher on massive tool result JSON arrays or truncates them based on per-provider settings (gemini-cli, antigravity, aicode, opengateway, and vertex for Vertex AI Anthropic endpoints)
  • Transparently routes other traffic via existing Proxies (like Proxyman)

How to use it

Installation

Homebrew (macOS arm64, Linux x86_64)

brew install aeroxy/tap/claude-proxy

Build from source

  1. Build the proxy:

    cargo build --release
  2. Trust the local CA for Node.js and cargo:

    export NODE_EXTRA_CA_CERTS=~/Library/Application\ Support/claude-proxy/ca.crt
    export CARGO_HTTP_CAINFO=~/Library/Application\ Support/claude-proxy/ca.crt
    export HTTPS_PROXY=http://127.0.0.1:7777

    On Linux the CA is at ~/.config/claude-proxy/ca.crt instead; see Running on Linux.

  3. Run the CLI:

    claude

Upgrading from an older build? Delete the old CA and re-import the new one — earlier builds generated a CA cert missing required X.509 extensions (keyCertSign, proper subject DN), which caused strict TLS validators such as cargo to reject it.

rm ~/Library/Application\ Support/claude-proxy/ca.{crt,key}
# Start the proxy once to regenerate, then re-import ca.crt into your trust store.
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain \
  ~/Library/Application\ Support/claude-proxy/ca.crt

Running as a daemon

claude-proxy start                    # daemonize on 7777 (or next free port up to 7786)
claude-proxy --port 7000 start        # pick a starting port
claude-proxy stop                     # SIGTERM all running daemons
claude-proxy --port 7000 stop         # stop a specific instance
claude-proxy restart                  # stop + start (no-op stop if nothing running)
claude-proxy --port 7000 restart      # restart a specific instance

Logs are written to ~/.config/claude-proxy/log/{epoch}.log, one file per start. PID files live at ~/.config/claude-proxy/pids/{port}.pid.

Running on Linux

claude-proxy runs on Linux x86_64 as a single static binary that needs nothing from the system beyond its CA certificates. Install it with Homebrew as above, or cross-compile it on a Mac:

# One-time setup
brew install zig
cargo install cargo-zigbuild
rustup target add x86_64-unknown-linux-musl

make release-linux   # → target/x86_64-unknown-linux-musl/release/claude-proxy (+ a .zip)

Copy the binary to the Linux machine (e.g. into ~/.local/bin/). Everything works as on macOS, with these differences.

The CA lives under ~/.config. It's generated at ~/.config/claude-proxy/ca.{crt,key} (under $XDG_CONFIG_HOME if that's set), not ~/Library/Application Support/claude-proxy/. Wherever this README uses the macOS path, use this one:

export NODE_EXTRA_CA_CERTS="${XDG_CONFIG_HOME:-$HOME/.config}/claude-proxy/ca.crt"
export CARGO_HTTP_CAINFO="${XDG_CONFIG_HOME:-$HOME/.config}/claude-proxy/ca.crt"
export HTTPS_PROXY=http://127.0.0.1:7777

To trust it system-wide (curl, git, Python and other non-Node tools):

# Debian / Ubuntu
sudo cp "${XDG_CONFIG_HOME:-$HOME/.config}/claude-proxy/ca.crt" \
  /usr/local/share/ca-certificates/claude-proxy.crt
sudo update-ca-certificates

# Fedora / RHEL
sudo cp "${XDG_CONFIG_HOME:-$HOME/.config}/claude-proxy/ca.crt" \
  /etc/pki/ca-trust/source/anchors/claude-proxy.crt
sudo update-ca-trust

The config file, logs and PID files are in the same places as on macOS.

Credentials. With no Keychain, the Claude subscription credential is read from ~/.claude/.credentials.json, which is where Claude Code keeps it on Linux. Every other store is in the same place as on macOS:

Credential Location On a new machine
Claude subscription ~/.claude/.credentials.json Sign in to claude there. Don't copy the file: Anthropic rotates the refresh token, so two machines sharing one copy sign each other out.
gemini-cli, antigravity, aicode ~/.config/claude-proxy/auths/, ~/.cli-proxy-api/ Copy the files, or claude-proxy login gemini --no-browser (likewise login antigravity)
Cline ~/.cline/data/settings/providers.json, then ~/.config/claude-proxy/auths/cline-*.json claude-proxy login cline. Don't copy: Cline rotates refresh tokens too.
Vertex (gcloud ADC) ~/.config/gcloud/application_default_credentials.json Copy the file, or claude-proxy login vertex --no-browser

No browser opens on Linux. Pass --no-browser to login and it prints the sign-in URL to open in any browser. For gemini, the sign-in ends on a page showing an authorization code: paste that code into the terminal. For antigravity and vertex, it ends on a redirect to localhost that fails to load: paste that page's URL instead. login cline shows a device code, so it needs neither. The automatic re-authentication on invalid_grant can't open a browser either; it waits 5 minutes and gives up. Run claude-proxy login vertex --no-browser instead.

Remote machines. The proxy only listens on 127.0.0.1. To use one on a server from your laptop, forward the port over SSH and point clients at 127.0.0.1:7777 as usual. For MITM mode, also copy the server's ca.crt to the laptop and trust that.

ssh -N -L 7777:127.0.0.1:7777 <server>

Don't expose the port on a public interface: the proxy ignores incoming API keys and signs every request with your stored credentials, so anyone who can reach it can use your accounts.

Configuration

Config lookup order (first match wins):

  1. --config <path> if provided
  2. ./config.toml in the current working directory
  3. ~/.config/claude-proxy/config.toml

A config file that exists but can't be read or parsed stops startup with the error rather than being skipped, and so does a --config path that doesn't exist.

HTTPS_PROXY is not read for upstream_proxy — it's a client-side var meant to point clients at this proxy, and reading it here would make the proxy chain through itself when HTTPS_PROXY=http://127.0.0.1:7777 is set in the same shell. Configure chained proxies (Proxyman, mitmproxy) explicitly via upstream_proxy = "..." in config.toml.

Listening port

The port defaults to 7777. Set it in config.toml with a top-level port, or override per-invocation with --port. Precedence is --port (CLI) > port (config) > 7777.

# ~/.config/claude-proxy/config.toml
port = 7000

Using a custom CA

If you already manage a CA (e.g. one signed by a corporate root already in your trust store), you can point the proxy at it instead of using the auto-generated one. The proxy needs both the cert and the private key to sign leaf certs for each intercepted host — a public cert alone (.cer file) is not sufficient.

# ~/.config/claude-proxy/config.toml
upstream_proxy = "http://127.0.0.1:9090"  # optional

# Both must be set together. PEM format. Tilde expansion supported.
ca_cert_path = "~/.certs/my-ca.crt"
ca_key_path  = "~/.certs/my-ca.key"

If only one of the two fields is set, the proxy will exit with an error at startup.

Skipping interception

Hosts listed in no_mitm_hosts are never intercepted: their CONNECT is relayed as an opaque TCP tunnel, so the client's TLS session runs end to end with the real server and no proxy feature (Map Local included) applies to them. * and ? wildcards work as in Map Local. The tunnel dials the host directly rather than through upstream_proxy. Like port and upstream_proxy, it is a top-level key, so it must sit above the first [table] in the file.

# ~/.config/claude-proxy/config.toml
no_mitm_hosts = ["mcp-proxy.anthropic.com"]

Map Local

Make the proxy return a fixed response for a URL match — useful for silencing telemetry, blocking update checks, or replaying canned fixtures without sending upstream traffic. Each [[map_local]] rule needs a url (with * and ? wildcards allowed) and may pin a method. The body comes from one of: an inline body string, a file path on disk, or neither (empty body). When the body is a file, the proxy reads it live on every matching request, so editing the file is reflected immediately without restarting the proxy.

When several rules could match the same request, the most specific one wins (more literal characters in url outranks a fuzzier pattern; rules that pin a method outrank any-method rules). Content-Type defaults intelligently: explicit content_type wins, otherwise it's derived from the file extension for file-backed rules, or application/json for non-empty inline bodies, or omitted entirely for empty responses. The proxy always adds X-Map-Local: true (and X-Map-Local-Source: <path> for file-backed rules) so you can tell mocked responses from real ones.

# Datadog log intake — return 202 with an empty JSON object so the client thinks it succeeded.
[[map_local]]
url    = "https://*.datadoghq.com/api/v2/logs"
method = "POST"
status = 202
body   = "{}"

# Plain HTTP works too — useful for internal telemetry endpoints.
[[map_local]]
url    = "http://192.168.0.1/x/y/z"
method = "POST"
body   = "{}"

# Anthropic event-logging batches — pretend the server accepted everything.
[[map_local]]
url    = "https://api.anthropic.com/api/event_logging/v2/batch"
method = "POST"
body   = '{"accepted_count":100,"rejected_count":0}'

# Claude Code update check — return 200 with no body and no Content-Type header.
[[map_local]]
url    = "https://downloads.claude.ai/claude-code-releases/latest"
method = "GET"

# File-backed rule. Edit the file at any time — next matching request sees the change.
# Content-Type is auto-derived from the extension (.json -> application/json).
[[map_local]]
url    = "https://api.anthropic.com/v1/messages"
method = "POST"
file   = "~/dev/mocks/messages.json"
[map_local.headers]
"x-mock-source" = "fixture"

If a rule's file is missing or unreadable at request time the proxy returns 502 with X-Map-Local-Error: file-unreadable and a body explaining the path that failed — loud failure beats a silent passthrough that hides "why isn't my mock working?".

Full reference (specificity tiebreaker, Content-Type defaulting matrix, plain-HTTP support, error envelope, regression-test recipes): see wiki/map-local.md.

Gemini models for opencode (@ai-sdk/google)

The proxy serves the native Gemini API and routes each model by its provider prefix: gemini-cli and antigravity on Google Cloud Code Assist, plus aicode for a Gemini Enterprise seat on its own upstream — the first two the same way CLIProxyAPI does. Credential files are compatible: anything in ~/.cli-proxy-api/ is read as-is, and login writes new ones to ~/.config/claude-proxy/auths/.

  1. Sign in (opens a browser, or use --no-browser for headless/remote):

    claude-proxy login gemini            # Google account (Code Assist) → gemini-cli provider
    claude-proxy login gemini --project my-gcp-project   # skip project auto-discovery
    claude-proxy login antigravity       # antigravity account
    claude-proxy login vertex            # Google Cloud ADC → vertex provider

    Headless / Remote SSH Server (--no-browser): Add --no-browser to any login command to complete sign-in without a local browser:

    claude-proxy login gemini --no-browser
    claude-proxy login antigravity --no-browser
    claude-proxy login vertex --no-browser

    For gemini, this uses an out-of-band auth flow (via codeassist.google.com/authcode) where you copy and paste a clean code. For antigravity and vertex, this displays the authorization URL; open it locally, authorize, and since no server is running locally, your browser will fail to load localhost — simply copy the full failed redirect URL (carrying ?code=...) from the browser's address bar and paste it back into your terminal.

  2. Point opencode at the proxy. Either transport works:

    • Origin (simplest, no CA): set the Google provider baseURL to http://127.0.0.1:7777/v1beta and any dummy API key.
    • MITM (no opencode config): keep the default Google endpoint and run opencode with HTTPS_PROXY=http://127.0.0.1:7777 and NODE_EXTRA_CA_CERTS=~/Library/Application\ Support/claude-proxy/ca.crt.
  3. Pick a model by provider prefix. The provider is the first segment of the model name: gemini-cli/<model>, antigravity/<model> or aicode/<experience> — e.g. gemini-cli/gemini-2.5-pro, gemini-cli/gemini-2.5-flash, antigravity/claude-sonnet-4-6, antigravity/gemini-3-pro-high, aicode/gemini-3.7-flash-high (the last needs an [aicode] config table; it reuses the gemini-cli login rather than adding one of its own). The part after the prefix is sent upstream as-is, so any model your account can serve works (not just catalogued ones). GET /v1beta/models lists the known models (provider-prefixed) for the providers you have credentials for. Streaming (:streamGenerateContent) and :countTokens are supported.

Optional config.toml knobs:

[settings]
# Defaults to ["~/.config/claude-proxy/auths", "~/.cli-proxy-api"] when omitted.
auth_dirs = ["~/.config/claude-proxy/auths", "~/.cli-proxy-api"]

Full reference (endpoints, prefix routing, request/response envelope, credential formats, login flow internals): see wiki/gemini-providers.md.

Anthropic API (/v1/messages) for Claude Code & the Anthropic SDK

The same gemini-cli / antigravity backends are also exposed through the Anthropic Messages API, so any Anthropic-API client can drive Gemini (and antigravity's claude-*) models. Sign in once with claude-proxy login … as above, then:

  • Origin (simplest, no CA): point your client's base URL at http://127.0.0.1:7777 (e.g. ANTHROPIC_BASE_URL=http://127.0.0.1:7777 for Claude Code) and use any dummy API key.
  • MITM (no client config): run the client with HTTPS_PROXY=http://127.0.0.1:7777 and NODE_EXTRA_CA_CERTS=~/Library/Application\ Support/claude-proxy/ca.crt. Interception of api.anthropic.com is gated on the provider prefix — requests whose model is not gemini-cli/… or antigravity/… pass straight through to the real Anthropic API, so normal Claude usage is unaffected.

Set the request model to a provider-prefixed name (e.g. gemini-cli/gemini-2.5-pro, antigravity/claude-sonnet-4-6). POST /v1/messages (streaming and non-streaming) and POST /v1/messages/count_tokens are supported.

curl -s http://127.0.0.1:7777/v1/messages -H 'content-type: application/json' \
  -d '{"model":"gemini-cli/gemini-2.5-pro","max_tokens":1024,
       "messages":[{"role":"user","content":"hi"}]}'

Claude subscription passthrough (/v1/messages from your Keychain)

Serves POST /v1/messages (+ count_tokens) against the real Anthropic API using the Claude Code OAuth credential already in your macOS Keychain (on Linux, ~/.claude/.credentials.json), so any Anthropic-API client can drive your Claude subscription without an sk-ant-api… billing key. No translation — Anthropic in, Anthropic out.

Enable it with a single line in config.toml (every field has a working default):

# ~/.config/claude-proxy/config.toml
[claude_oauth]

Sign in once with the claude CLI so the credential exists, then:

  • Origin (simplest, no CA): ANTHROPIC_BASE_URL=http://127.0.0.1:7777 with any dummy API key. Plain real model names work (claude-opus-5), as does the explicit claude-oauth/claude-opus-5.
  • MITM: HTTPS_PROXY=http://127.0.0.1:7777. Only models prefixed claude-oauth/ are routed here — an unprefixed model on api.anthropic.com is your real claude CLI using its own credential, and is forwarded to the real API on the normal path, which still applies the transcript-healing scrubs (empty text and unsigned thinking blocks left behind by a provider-backed turn) to bodies that carry them.
curl -s http://127.0.0.1:7777/v1/messages -H 'content-type: application/json' \
  -d '{"model":"claude-opus-5","max_tokens":64,
       "system":"You are a pirate.",
       "messages":[{"role":"user","content":"hi"}]}'

Your own system prompt is preserved verbatim — the proxy prepends the two system blocks a real claude-cli sends (Anthropic only honors an OAuth credential when the request looks like Claude Code) and yours follows them. Tokens are refreshed automatically and merged back into the Keychain item (or that file), leaving your MCP logins and other keys intact.

Note this uses a subscription credential from a client that isn't Claude Code, which is outside Anthropic's intended use of it. See wiki/claude-oauth.md for the full disguise, config, and verification steps.

OpenAI aggregator (/v1/chat/completions)

Serves the OpenAI Chat Completions API and fans it out to one or more OpenAI-compatible backends. There is no format translation — OpenAI in, OpenAI out; the proxy only picks the backend, rewrites the model, and pipes the response through (streaming included).

Configure each backend under [[openai]] in config.toml:

# ~/.config/claude-proxy/config.toml
[[openai]]
name = "opengateway"                       # the provider prefix
base_url = "https://opengateway.example/v1" # POSTed to {base_url}/chat/completions
api_key = "sk-..."                          # optional; if omitted, your client's
                                            # Authorization header is forwarded instead
  [openai.headers]                          # optional extra upstream headers
  X-Title = "claude-proxy"

[[openai]]
name = "openrouter"
base_url = "https://openrouter.ai/api/v1"
api_key = "sk-or-v1-..."

Origin mode only — point your OpenAI client at the proxy (OPENAI_BASE_URL=http://127.0.0.1:7777), no CA trust needed. There is no MITM of api.openai.com.

The request model is <provider>/<upstream-model>: the first /-segment selects the [[openai]] provider; everything after it is forwarded verbatim as the upstream model. So opengateway/minimax/minimax-m3 routes to opengateway and asks it for minimax/minimax-m3.

curl -s http://127.0.0.1:7777/v1/chat/completions -H 'content-type: application/json' \
  -d '{"model":"opengateway/minimax/minimax-m3",
       "messages":[{"role":"user","content":"hi"}]}'

Cline provider (/v1/chat/completions)

Serves the OpenAI Chat Completions API against Cline's own API (api.cline.bot) using your Cline account, so any OpenAI-compatible client can spend a Cline subscription without holding a Cline key. No format translation — OpenAI in, OpenAI out. The proxy supplies the credential (refreshing it as needed), sends the header set a real cline CLI sends, and unwraps Cline's {"data":…,"success":true} response envelope so SDKs can parse it.

Nothing to configure: the cline/ prefix is always routable, like gemini-cli/ and antigravity/. A [cline] table is only for overrides (see config.example.toml).

Signing in. If you already use the cline CLI, there is nothing to do — the proxy reads its providers.json. Otherwise:

claude-proxy login cline        # WorkOS device flow: type the printed code in your browser

Refreshed tokens are written back to whichever store they came from, merged in place so the rest of the CLI's config survives. Turn that off with write_back = false if you'd rather keep them in memory only.

Routing. Prefix the model with cline/:

curl -s http://127.0.0.1:7777/v1/chat/completions -H 'content-type: application/json' \
  -d '{"model":"cline/anthropic/claude-haiku-4.5",
       "messages":[{"role":"user","content":"hi"}]}'

In origin mode (OPENAI_BASE_URL=http://127.0.0.1:7777) you can opt into bare model names too — [cline] serve_unprefixed = true — and Cline then serves any model no configured [[openai]] provider claims. It's off by default so the always-on surface can't spend your Cline account on a request that didn't ask for it. Over MITM of api.cline.bot only the explicit cline/ prefix is served, so your real cline CLI keeps talking to its own API with its own credential.

Model list. GET /v1/models answers with Cline's catalog, every id prefixed so you can paste one straight back into a request (shown with the default cline prefix — if you set [cline] prefix, substitute yours in the filter):

curl -s http://127.0.0.1:7777/v1/models | jq -r '.data[].id' | grep '^cline/anthropic/' | head -3
# cline/anthropic/claude-fable-5.1
# cline/anthropic/claude-fable-5.1:batch
# cline/anthropic/claude-opus-5

Origin mode only, and it needs no credit: Cline's catalog is public, so listing never touches your account. With no Cline login on the machine it's a 404 rather than a list of models you couldn't call.

This listing is Cline's catalog only — models from [[openai]] providers are not included, since those backends are a pure passthrough with no catalog of their own.

Details, including the credential stores, the refresh rules and the response-envelope handling: wiki/cline.md.

About

Local HTTPS MITM proxy, API translator, and aggregator for Claude, Gemini, and OpenAI clients

Resources

Stars

7 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages