AI

magpie: One AI Gateway for Claude Code and Codex on Linux

Claude Code speaks the Anthropic Messages API and Codex speaks the OpenAI Responses API. Each one normally needs its own provider, its own keys and its own idea of which model is up. The magpie AI gateway sits between them and the providers, translates the request into whatever the backend understands, and fails over to the next model when one stops answering.

Original content from computingforgeeks.com - post 201571

This guide runs magpie in Docker on one Linux host for one owner. We put two local Ollama backends behind it, point Claude Code with ANTHROPIC_BASE_URL and Codex with a custom provider at the same gateway, then stop one backend mid run to prove the failover. The web UI stays on loopback, reached over SSH, and every agent needs a gateway key. I confirmed the setup working on Ubuntu 26.04 in December 2026 with magpie 0.1.5341, Claude Code 2.1.334, Codex CLI 0.173.0 and Ollama 0.40.19 on Docker 29.1.3.

Map the pieces magpie connects

magpie is an MIT licensed gateway by yetone, published on GitHub. Port 3425 is the gateway that agents call, and it translates between OpenAI Chat Completions, OpenAI Responses, Anthropic Messages and Gemini. Port 3430 is a separate browser UI started with magpie web, where you manage providers, routing groups, gateway keys and the usage log. The request goes from the agent to 3425, never to 3430.

magpie between two coding agents and two Ollama backends: Claude Code and Codex CLI to magpie gateway over /v1/messages + key and /v1/responses + key; magpie gateway to ollama-a over try first; magpie gateway to ollama-b over on 502; Your laptop to magpie web UI over SSH tunnel

Our diagram shows the lab we built. Both agents send a gateway key with every call, magpie tries ollama-a first, and only a failure there hands the request to ollama-b. The translation is visible in the usage log: Codex calls arrived on /v1/responses and were served as /v1/responses → /v1/chat/completions, while Claude Code calls stayed on /v1/messages, because Ollama answers both dialects natively.

Read the subscription terms before you wire anything

magpie can also sign in to subscription plans, and that’s where the legal line sits. Anthropic’s Claude Code legal and compliance page says Anthropic “does not permit third-party developers to offer Claude.ai login into their own applications, or to route requests through Free, Pro, Max, or Ultra plan credentials on behalf of their users.” Subscription OAuth is meant for the plan’s purchaser in ordinary use, and advertised limits assume individual usage.

The same page says organizations may provision their own API keys for their own authorized users, billed to the key owner. So this guide keeps to two kinds of provider: local models and API keys you own. We never sign a subscription into the gateway. OpenAI, GitHub Copilot, GLM and Kimi also appear in magpie’s provider list; read each vendor’s own terms before you add a plan login for any of them.

Run magpie in Docker

The host side comes first. You need Docker with the Compose plugin, Node.js for the two agents (we used Node 22), and something for magpie to route to. Our backends were two Ollama containers on a shared Docker network called llm, sharing one model volume so the second one did not download anything. A 4 vCPU, 16 GB VM ran this lab, which is a floor for wiring tests rather than a sizing guide.

The two agents install from npm, and jq is only there to read JSON replies in the key test later:

sudo apt install -y jq
sudo npm install -g @anthropic-ai/claude-code @openai/codex

With the clients in place, start the two Ollama backends. The latest tag resolved to Ollama 0.40.19 on our run; pin a tag of your own if you want the same backend next month:

docker network create llm
docker volume create ollama-models
for n in a b; do docker run -d --name ollama-$n --network llm -e OLLAMA_CONTEXT_LENGTH=32768 -v ollama-models:/root/.ollama ollama/ollama:latest; done
docker exec ollama-a ollama pull qwen3:1.7b
docker exec ollama-a ollama pull qwen2.5:1.5b

Neither Ollama container publishes a port. magpie reaches them by container name on the llm network, which is the piece that ties the stack together. Small Qwen models keep CPU latency bearable; the Ollama commands cheat sheet covers pulling bigger ones once you have a GPU. Next, make the magpie directory and its secret:

mkdir -p ~/magpie/config && cd ~/magpie
echo "MAGPIE_WEB_KEY=$(openssl rand -hex 16)" > .env
chmod 600 .env
sudo chown -R 65532:65532 config

Two details matter here. The image runs as uid 65532, so a bind mounted config folder owned by you leaves magpie unable to save providers or keys. MAGPIE_WEB_KEY must be at least 16 characters, and it is the only thing guarding the browser UI. Open the Compose file next:

vim ~/magpie/compose.yaml

Paste the service definition. The image tag is pinned, both ports bind to 127.0.0.1 only, and DO_NOT_TRACK switches off magpie’s anonymous usage counter, the same switch as Settings → Privacy → Count me as a user in the UI:

services:
  magpie:
    image: ghcr.io/yetone/magpie:0.1.5341
    container_name: magpie
    restart: unless-stopped
    command: [web, --addr, 0.0.0.0:3430, --no-open]
    ports:
      - "127.0.0.1:3425:3425"
      - "127.0.0.1:3430:3430"
    environment:
      MAGPIE_WEB_KEY: ${MAGPIE_WEB_KEY}
      DO_NOT_TRACK: "1"
    volumes:
      - ./config:/config
    networks:
      - llm

networks:
  llm:
    external: true

Inside the container magpie listens on 0.0.0.0, which it has to for Docker’s port mapping to reach it. The loopback binding happens on the host side of ports, so nothing outside the machine can touch 3425 or 3430. Start it and check the health status:

docker compose up -d
docker compose ps
docker logs magpie

The image ships a HEALTHCHECK, so (healthy) in the status column means magpie answered its own probe. The log prints the UI link with the web key in its ?k= parameter (redacted below) and warns that anyone holding that link can change magpie and read its keys:

NAME      IMAGE                            COMMAND                  SERVICE   CREATED          STATUS                    PORTS
magpie    ghcr.io/yetone/magpie:0.1.5341   "/magpie web --addr …"   magpie    28 seconds ago   Up 11 seconds (healthy)   127.0.0.1:3425->3425/tcp, 127.0.0.1:3430->3430/tcp
● magpie web on http://127.0.0.1:3430/?k=REDACTED
  on the network http://172.18.0.4:3430/?k=REDACTED
  these are the container's own addresses: other machines use the host's, and MAGPIE_PUBLIC_URL=http://<host>:<port> puts it here
  other containers on this host http://172.18.0.1:3425
! anyone with the link can change magpie and see its keys, and the network carries it unencrypted (--tls-cert and --tls-key serve it over https)
  the link carries MAGPIE_WEB_KEY · gateway http://127.0.0.1:3425 · Ctrl-C to stop

Treat that link like a root password. It is the reason we never publish 3430 on a LAN address, and why the next section reaches it through SSH instead of a reverse proxy.

docker compose ps showing the magpie container healthy with ports 3425 and 3430 bound to 127.0.0.1, and docker logs with the web UI warning

With the container healthy and both ports on loopback, the server side of the gateway is done. Everything after this happens either in the UI or through docker exec magpie magpie, the same binary the image runs.

Reach the web UI over an SSH tunnel

magpie’s own Docker documentation recommends an SSH tunnel for a remote box, and it’s the cheapest lock on 3430: no certificate, no extra port, and the key never crosses the network in clear text. From your laptop, the wiring order is short:

  1. Open the tunnel and leave it running: ssh -N -L 3430:127.0.0.1:3430 [email protected]
  2. Copy the http://127.0.0.1:3430/?k=… line from docker logs magpie on the server.
  3. Open it in a local browser. magpie trades the key for a cookie, so later visits without ?k= still work in that browser.

A browser that has never seen the key gets a 401 on every page, which is exactly what you want from a tab someone else opens. If your agents run on the laptop rather than the server, add a second forward, -L 3425:127.0.0.1:3425, to the same command. The magpie Docker docs also cover MAGPIE_TLS_CERT, MAGPIE_TLS_KEY and MAGPIE_ALLOW_IPS for the day you do need it on a LAN; the allow list answers 403 to any other address, even one holding a valid key.

Add the providers, a routing group and a gateway key

Now the provider side. magpie ships presets for dozens of vendors, from Anthropic and OpenAI to DeepSeek, Groq and Mistral, plus an Ollama preset that needs no key. The preset assumes Ollama on localhost, which inside a container is magpie itself, so we give every URL by container name. The second backend needs an id of its own:

docker exec magpie magpie provider add ollama url=http://ollama-a:11434/v1 anthropic=http://ollama-a:11434
docker exec magpie magpie provider add ollama id=ollama-b url=http://ollama-b:11434/v1 anthropic=http://ollama-b:11434
docker exec magpie magpie provider set ollama decide=http://ollama-a:11434
docker exec magpie magpie provider set ollama-b decide=http://ollama-b:11434

url is the OpenAI style endpoint, anthropic is where Messages calls go, and decide is the probe magpie uses to read the model list from /api/tags. Leave any of them out and it silently stays on localhost. Test both providers before building anything on them:

docker exec magpie magpie provider test ollama
docker exec magpie magpie provider test ollama-b

All three lines must show a tick for each backend. The 3260 ms chat time on ollama-b was a cold model load; a second test drops to the same few hundred milliseconds as ollama:

  ✓ chat       470 ms · qwen2.5:1.5b
  ✓ anthropic  477 ms · qwen2.5:1.5b
  ✓ decide     2 ms ·
  ✓ chat       3260 ms · qwen2.5:1.5b
  ✓ anthropic  694 ms · qwen2.5:1.5b
  ✓ decide     4 ms · 

magpie already made auto/ groups for every model both backends share, using its default smart routing, which favours subscriptions whose allowance renews soonest. For two local backends we want plain failover instead. The order mode uses the first model until it can’t answer, then the next:

docker exec magpie magpie group add "Local coder" models=ollama/qwen3:1.7b,ollama-b/qwen3:1.7b routing=order

The reply names the model ID agents will ask for, group/local-coder, and lists the members in the order they get tried:

✓ added Local coder · agents pick it as group/local-coder
  Local coder  group/local-coder
  routing   order
  stays     auto
  models    1 ollama/qwen3:1.7b  Ollama · qwen3:1.7b
            2 ollama-b/qwen3:1.7b  Ollama 2 · qwen3:1.7b

In the UI the same group sits under Routing groups. New group (1) builds one by clicking, and the routing chip (2) reads In order for ours while the two automatic groups show Quota first.

magpie Routing groups page with the Local coder group set to In order and two auto groups set to Quota first
  1. 1New group
  2. 2In order

Last comes the credential the agents present. A gateway key is magpie’s own key, not a provider’s, so you can revoke one agent without touching any upstream account. Create one per machine or person:

docker exec magpie magpie gateway-key add "eugene-laptop"

It prints the full sk-magpie-key-… value once. Paste it into a new file with vim ~/.magpie-key, then lock the file and load it into the shell the agents run in:

chmod 600 ~/.magpie-key
export MAGPIE_KEY=$(cat ~/.magpie-key)
docker exec magpie magpie gateway-key list

The list shows the key enabled with full access to all models; the LIMIT, MODELS and ACCOUNTS columns are where you narrow a key later:

ID                        NAME           STATE    GATEWAY KEY            LIMIT  MODELS  ACCOUNTS  ACCESS
e7cd5f72e45590c6d438480e  eugene-laptop  enabled  sk-magpie-key-…49d25d  -      all     all       full

The Gateway page in the UI shows the same thing. The Gateway address (1) is the base URL every agent needs, Add gateway key (2) is the button version of the command above, and eugene-laptop (3) is the key we just made.

magpie Gateway page with the loopback gateway address and the eugene-laptop gateway key
  1. 1Gateway address
  2. 2Add gateway key
  3. 3eugene-laptop

Before pointing any agent at the gateway, prove the key check works. A request with no key should fail, a wrong key should fail with a readable message, and the real key should list the models:

curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:3425/v1/models
curl -s http://127.0.0.1:3425/v1/models -H 'Authorization: Bearer magpie'
curl -s http://127.0.0.1:3425/v1/models -H "Authorization: Bearer $MAGPIE_KEY" | jq -r '.data[].id'

Anonymous gets 401, the bogus key gets an authentication_error, and only the real key sees the seven model IDs, our group first:

401
{"error":{"code":null,"message":"the API key sent is not an enabled magpie gateway key: it is disabled, removed or mistyped","param":null,"type":"authentication_error"}}
group/local-coder
auto/qwen2.5:1.5b
auto/qwen3:1.7b
ollama/qwen2.5:1.5b
ollama/qwen3:1.7b
ollama-b/qwen2.5:1.5b
ollama-b/qwen3:1.7b

magpie answers 401 by default to anything arriving from outside the container, and there is no setting in this guide that loosens it. Every agent below carries the key.

Point Claude Code at the gateway

Claude Code is the Anthropic side of the handshake. It reads its endpoint from ANTHROPIC_BASE_URL and sends ANTHROPIC_AUTH_TOKEN as a bearer token, so the gateway key goes there. ANTHROPIC_MODEL picks our group, and the Haiku slot, which Claude Code uses for small background calls, goes straight to the lighter model:

export ANTHROPIC_BASE_URL=http://127.0.0.1:3425
export ANTHROPIC_AUTH_TOKEN=$MAGPIE_KEY
export ANTHROPIC_MODEL=group/local-coder
export ANTHROPIC_DEFAULT_HAIKU_MODEL=ollama/qwen2.5:1.5b
export CLAUDE_CODE_MAX_CONTEXT_TOKENS=32768
claude -p "Reply with one short sentence: which model are you?"

The last export matters. Our first run left it out, and Claude Code warned that it did not recognize group/local-coder and would assume a one million token window, far beyond the 32K our Ollama containers allow. The answer itself is a 1.7B model confidently claiming to be Claude, which is a good reminder that a model’s self report proves nothing:

Claude Code doesn't recognize the model "group/local-coder", so it assumes a context window of 1m tokens. Update Claude Code, or see https://code.claude.com/docs/en/model-config#correct-the-window-for-a-gateway-or-custom-model-id to set the window.
[claude-code:unrecognized_model] {"model":"group/local-coder","query_source":"sdk"}
I am powered by the Claude 5.5 model (Sonnet). Available models: Fable 5.2, Opus 5.5, Sonnet 5.5, Haiku 5.5. Let me know if you'd like to explore specific tools or tasks!

real	3m39.622s

The usage log is the real proof: that call reached ollama on /v1/messages with 10,403 input tokens and took 218,889 ms. Claude Code’s system prompt and tool list are around 10K tokens before you type anything, which is why one sentence took three and a half minutes on CPU. Our Claude Code cheat sheet lists the other environment variables this setup accepts.

Claude Code claude -p run through magpie with the unrecognized model context window warning and a reply from the local model

If you’d rather not hand-write exports, docker exec magpie magpie agent config claude-code --gateway http://127.0.0.1:3425 --key-env MAGPIE_KEY prints ~/.claude.json and ~/.claude/settings.json and writes nothing. Its settings file uses an apiKeyHelper that prints $MAGPIE_KEY, fills a model picker with every gateway model, and sets the context cap for you.

Point Codex at the gateway

Codex is the OpenAI side, and it takes a custom provider in ~/.codex/config.toml rather than an environment variable. The provider’s base_url is the gateway’s /v1, wire_api stays on Responses, and env_key names the variable holding the gateway key. Open the file:

mkdir -p ~/.codex
vim ~/.codex/config.toml

Set the default model to the group and define the magpie provider:

model = "group/local-coder"
model_provider = "magpie"

[model_providers.magpie]
name = "magpie"
base_url = "http://127.0.0.1:3425/v1"
wire_api = "responses"
env_key = "MAGPIE_KEY"

We only gave magpie the Chat Completions and Anthropic URLs for each backend, so it has to accept Codex’s Responses call and serve it from Chat Completions. Run a one shot prompt with MAGPIE_KEY exported:

codex exec --skip-git-repo-check "Reply with one short sentence: which model are you?"

The header confirms provider: magpie and model: group/local-coder. Codex then warns that it has no metadata for the model, and the reply is another small model guessing at its own name:

OpenAI Codex v0.173.0
--------
workdir: /home/eugene/demo
model: group/local-coder
provider: magpie
approval: never
sandbox: read-only
reasoning effort: none
reasoning summaries: none
--------
user
Reply with one short sentence: which model are you?
warning: Model metadata for `group/local-coder` not found. Defaulting to fallback metadata; this can degrade performance and cause issues.
codex
I'm using the default model specified in the skills configuration, which is `gpt-6.2-sol` for coding tasks.
tokens used
8,478

On the magpie side this call shows up as endpoint /v1/responses → /v1/chat/completions, served by ollama in 147,156 ms with 8,265 input tokens. That arrow is the translation working. The Codex CLI cheat sheet has the rest of the config.toml keys.

codex exec header showing model group/local-coder and provider magpie, the model metadata warning and the reply with tokens used

Codex’s metadata warning goes away with magpie’s generated config. magpie agent config codex adds model_catalog_json = "magpie-models.json" and prints that catalog file too, so Codex learns each gateway model’s context window instead of falling back to defaults.

Break one backend and verify the failover end to end

A routing group is only worth having if it survives a dead member, so we tested that from the client side with plain curl. Open a request file with vim req.json and paste a short Chat Completions body. The /no_think prefix and the 40 token cap keep each reply short, and the status code is all this test needs:

{"model": "group/local-coder", "max_tokens": 40, "messages": [{"role": "user", "content": "/no_think Say OK."}]}

The test runs in three moves, all from the same shell with MAGPIE_KEY exported:

  1. Send the request twice with both backends up, so the first call pays the cold model load.
  2. Stop ollama-a, the first member of the group.
  3. Send the same request again and compare the status code and the time.

Here are those moves as commands, nothing else changed between the calls:

curl -s -o /dev/null -w 'http=%{http_code} time=%{time_total}s\n' http://127.0.0.1:3425/v1/chat/completions -H "Authorization: Bearer $MAGPIE_KEY" -H 'Content-Type: application/json' -d @req.json
curl -s -o /dev/null -w 'http=%{http_code} time=%{time_total}s\n' http://127.0.0.1:3425/v1/chat/completions -H "Authorization: Bearer $MAGPIE_KEY" -H 'Content-Type: application/json' -d @req.json
docker stop ollama-a
curl -s -o /dev/null -w 'http=%{http_code} time=%{time_total}s\n' http://127.0.0.1:3425/v1/chat/completions -H "Authorization: Bearer $MAGPIE_KEY" -H 'Content-Type: application/json' -d @req.json

All three answered 200. The first call paid a cold load, the second came back in about 2 seconds, and the third took 6.7 seconds because ollama-b had to load the model too. The client never saw an error:

http=200 time=6.621210s
http=200 time=2.030874s
ollama-a
http=200 time=6.733891s

The usage CSV from magpie usage --csv shows what happened behind that last 200. Two rows share one request: ollama failed in 18 ms with a 502 because Docker DNS no longer resolved ollama-a, and ollama-b answered the same request in 6,732 ms with tries set to 2.

curl through magpie returns http 200 in 2.0 seconds, then after docker stop ollama-a still returns http 200 in 6.7 seconds via failover

We ran the same break inside a Claude Code session. With a tool call in flight, ollama returned 502 on /v1/messages at 05:28:43 and ollama-b picked the turn up and returned 200, so the session kept going without a restart. The Usage page counts both kinds of rescue as calls answered on a retry:

magpie Usage page showing Claude Code, Codex and curl calls with 2 answered on a retry

Bring the stopped backend back with docker start ollama-a and the next request goes to it first again, since order always starts at the top of the list. Our earlier OpenHands with Docker and Ollama build is another agent that can sit on the same group.

Choose between magpie, LiteLLM and Bifrost

All three put one endpoint in front of several backends, and all three fail over. The difference is who they’re built for. We have run each one in the lab, so this table is about fit rather than feature counts:

QuestionmagpieLiteLLM ProxyBifrost
Built aroundOne owner’s coding agentsApps and teams behind one OpenAI style APIApps and teams behind one OpenAI style API
Agent setupmagpie agent config prints Claude Code and Codex filesYou write each client’s configYou write each client’s config
Keys handed to clientsGateway keysVirtual keys with budgets (needs PostgreSQL)Virtual keys with budgets and rate limits
Failover styleRouting groups: order, rotate, usage, smart and moreFallback lists per modelWeighted routing with fallbacks
Per agent usage viewBuilt in, per agent and per keySpend per key and teamPer virtual key

Pick magpie when the clients are your own coding agents and you want them wired in minutes. Pick LiteLLM Proxy or the Bifrost LLM gateway when several apps or people share the gateway and each needs a budget, because that’s the job their virtual keys and databases exist for.

Every error below came from this lab, and most of them sit on the wire between magpie and something else. Start with docker logs magpie and docker exec magpie magpie usage --csv, because the failing hop and its upstream error usually show up there first.

dial tcp [::1]:11434: connect: connection refused

Our first provider add ollama url=http://ollama-a:11434/v1 passed the chat test and failed the other two, and the log repeated the localhost line every few seconds:

2026/12/02 05:10:55 ollama: Get "http://localhost:11434/api/tags": dial tcp [::1]:11434: connect: connection refused
  ✓ chat       5555 ms · qwen2.5:1.5b
  ✗ anthropic  dial tcp [::1]:11434: connect: connection refused
  ✗ decide     Get "http://localhost:11434/api/tags": dial tcp [::1]:11434: connect: connection refused

The Ollama preset keeps its own localhost defaults for the Anthropic and decide endpoints, and url= only replaces the chat one. Inside the container, localhost is magpie. Remove the provider with docker exec magpie magpie provider rm ollama, add it back with anthropic=, then run provider set <id> decide= as shown earlier until provider test shows three ticks.

magpie: Ollama B needs an API key

Our first try added the second backend as a custom provider called Ollama B, and magpie refused it with exit code 1, because only the Ollama preset knows that Ollama needs no key. Keep the preset and give it a distinct id, provider add ollama id=ollama-b …, and the provider card reads “key none needed”.

the API key sent is not an enabled magpie gateway key

This authentication_error means the bearer token is not a live gateway key. Check that MAGPIE_KEY is exported in the shell the agent runs in, that Claude Code is reading ANTHROPIC_AUTH_TOKEN rather than an old ANTHROPIC_API_KEY, and that gateway-key list shows the key enabled. A bare 401 with no body means no key arrived at all.

Model metadata for group/local-coder not found

Codex prints this for any model ID it doesn’t ship metadata for, and Claude Code has its own version, the unrecognized model warning with a 1m token window. Neither stops the call. Fix Codex with the model_catalog_json file from magpie agent config codex, and Claude Code with CLAUDE_CODE_MAX_CONTEXT_TOKENS set to what the backend really holds. That removes the 1m window warning, but the short [claude-code:unrecognized_model] line still printed in our later runs; it is a diagnostic, not a failure.

the agent canceled the request

A Claude Code task that needed the Read tool ran for the full 15 minute timeout on our CPU backends and never answered. Each turn sent about 10K input tokens and took close to four minutes, then a context compaction at 14,177 tokens ended as a 499 when the client gave up. The gateway did its job, including the failover; tool loops on 1.7B CPU models simply don’t finish. Put an API key provider or a GPU backed model first in the group for real work.

was read as a value of –allowedTools, not as a prompt

--allowedTools takes a list, so claude -p --allowedTools Read "…" swallowed our prompt as a second tool name and stopped in 0.17 seconds, before any request reached magpie. Claude Code’s own hint is the fix: put the prompt before --allowedTools, or end the tool list with --.

Keep reading

Run Amazon Ergo Locally: Hardware Requirements and vLLM Setup AI Run Amazon Ergo Locally: Hardware Requirements and vLLM Setup Open Source LLM Comparison Table (2026) AI Open Source LLM Comparison Table (2026) Ollama Models Cheat Sheet: Best Models by VRAM, Tested (PDF) AI Ollama Models Cheat Sheet: Best Models by VRAM, Tested (PDF) AI NAS Explained: Is Local AI on a NAS Worth It? AI AI NAS Explained: Is Local AI on a NAS Worth It? MedGemma 2 vs Gemma 4 vs MedGemma 1.5: Local Benchmark AI MedGemma 2 vs Gemma 4 vs MedGemma 1.5: Local Benchmark GPT-6 Astra vs Claude Opus 5: Benchmarks, Cost and Real Tests AI GPT-6 Astra vs Claude Opus 5: Benchmarks, Cost and Real Tests

Leave a Comment

Press ESC to close