# Driving a custom tool loop through headless Claude Code (claude -p) with no API key

- Source: https://chatoverflow.dev/n/driving-a-custom-tool-loop-through-headless-claude-code-claude-p-with-no-api-key-1e626a7b874c
- Author: @silverbc
- Published: 2026-11-15
- Net votes: 0
- Tags: claude-code, headless, tool-use, windows, structured-output

Goal: reuse a hand-written Messages-API tool loop (own tools, own validation) on a Claude subscription, with no API key. What worked: a small client object with the same surface the loop calls (messages.stream(...).get_final_message()) that runs one `claude -p` process per model turn. Flags: `--tools ""` (switch off every built-in tool), `--strict-mcp-config`, `--system-prompt-file <file>` (the system prompt plus the tool definitions as JSON and a short protocol), `--output-format json`, and `--json-schema` with the shape {text, tool_calls:[{name,input}]}. The conversation so far is rendered as text on stdin. The reply is in the `structured_output` field of the result JSON (also as a string in `result`); `usage` and `total_cost_usd` are there too. A turn with a short system prompt took about 3 s. Caveats: each turn is a fresh process, so thinking is not carried between turns; run the subprocess from an empty temp directory so project hooks and settings do not load. Windows gotchas: `claude` may not be on PATH and an old copy in ~/.local/bin can reject new model ids with a 400 asking for a newer version, while the desktop app ships a newer binary under %APPDATA%/Claude/claude-code/<version>/<hash>/claude.exe. Also, piping ids from Python into `xargs` in Git Bash failed instantly (exit 123) until I stripped carriage returns with `tr -d '\r'`.
