Skip to main content

tokfuse

Fail-closed spend pre-reservation proxy and tool-loop circuit breaker for CLI and MCP AI agents.

# Wrap any OpenAI- or Anthropic-backed agent CLI with a hard $1.50 pre-reserved cap and 3-turn loop fuse
uvx tokfuse --max-usd 1.50 --max-loop 3 -- python run_agent.py
$ uvx tokfuse --max-usd 0.50 --max-loop 3 -- python subagent_swarm.py
[tokfuse] TRIPPED (budget) | Pre-flight reservation $0.1840 for 'claude-sonnet-4-20250514' exceeds session --max-usd $0.5000 ($0.0612 unreserved remaining). | settled=$0.4388 calls=6
$ echo $?
75

Wrap any stdio MCP server (Claude Code, Codex, OpenCode, Cursor, local models) to stop identical or ping-pong tools/call loops and reap orphan server processes on exit:

{
  "mcpServers": {
    "filesystem": {
      "command": "uvx",
      "args": ["tokfuse", "mcp", "--max-repeat", "3", "--max-calls", "80", "--", "npx", "-y", "@modelcontextprotocol/server-filesystem", "."]
    }
  }
}

Why tokfuse Exists

Most agent budget flags (--max-budget-usd, post-turn callbacks, log scrapers) check spend after a response returns:

  1. Parallel subagent overshoot: Five subagents launched concurrently against a $0.50 remaining budget all see $0.50 available, send five $0.25 requests, and settle at $1.25.
  2. Unattended tool loops: Background agents get stuck calling bash({"cmd": "pytest"}) or oscillating read_file <-> grep with identical arguments until rate limits or credit auto-reload trigger.
  3. OAuth / local model blind spot: Subscription-authenticated CLIs do not always expose an HTTP API key path, leaving stdio MCP tool calls unguarded and leaking orphan MCP server processes when terminals close.

tokfuse runs as a zero-dependency Python (>=3.11) process supervisor with two enforcement planes:

  • tokfuse [run] (HTTP/SSE Pre-Reservation Proxy): Binds an ephemeral 127.0.0.1 proxy, injects OPENAI_BASE_URL and ANTHROPIC_BASE_URL into the child process, reserves worst-case cost (estimated_input_tokens + max_tokens) atomically before opening the upstream request, and refunds unused budget once JSON or streaming SSE usage settles.
  • tokfuse mcp (MCP stdio JSON-RPC Fuse): Sits between any MCP host and stdio server, canonicalizes tools/call JSON arguments, blocks A -> A -> A streaks and A <-> B ping-pong loops, and kills the MCP process group cleanly on stdin EOF.

Installation

Run directly without installing via uv:

uvx tokfuse --version
# Or run directly from GitHub before PyPI mirror sync:
uvx --from git+https://github.com/ByKite/tokfuse tokfuse --version

Or install into an isolated tool environment:

uv tool install tokfuse
# or
pip install tokfuse

Zero third-party runtime dependencies; uses only the Python 3.11+ standard library (http.server, http.client, sqlite3, subprocess, ssl).

Usage

1. Cap API Spend & Tool Loops (tokfuse run)

run is the default subcommand when omitted:

# Session cap ($2.00) + persistent UTC daily cap ($10.00 across runs via SQLite WAL)
tokfuse --max-usd 2.00 --daily-usd 10.00 --max-loop 3 --max-wall-sec 600 -- python agent.py

# Machine-readable JSON receipt on stderr for CI pipelines
tokfuse --max-usd 0.75 --json -- pytest tests/evals/

# Custom model pricing ($0.80 / 1M input, $3.20 / 1M output) for private/fine-tuned endpoints
tokfuse --max-usd 5.00 --price-in 0.80 --price-out 3.20 -- ./run_custom_agent.sh

Supported HTTP wire formats:

  • OpenAI Chat Completions (POST /v1/chat/completions, JSON & streaming SSE)
  • OpenAI Responses (POST /v1/responses, JSON & streaming SSE)
  • Anthropic Messages (POST /v1/messages, JSON & streaming SSE, including cache read/creation token rates)

Existing OPENAI_BASE_URL and ANTHROPIC_BASE_URL values in your shell (such as OpenRouter, LiteLLM, or a corporate gateway) are preserved as the upstream target automatically. API keys stay in pass-through headers and are never written to logs or SQLite.

2. Guard Any stdio MCP Server (tokfuse mcp)

tokfuse mcp --max-repeat 3 --max-calls 100 --max-wall-sec 900 -- uvx mcp-server-git

By default, when an agent repeats the exact same (tool_name, canonical_json_args) call --max-repeat times (or alternates A <-> B --max-repeat times), tokfuse mcp returns a spec-compliant MCP CallToolResult with isError: true instructing the model to stop retrying without crashing your editor session. If the agent ignores the warning repeatedly (or --hard-kill is set), tokfuse mcp terminates the server process group with exit code 76.

3. Inspect or Reset Daily Spend (tokfuse status / reset)

tokfuse status
tokfuse status --json
tokfuse reset          # clears today's UTC row
tokfuse reset --all    # clears all historical rows

By default, --daily-usd stores aggregated UTC day totals in $XDG_CACHE_HOME/tokfuse/ledger.sqlite (or ~/.cache/tokfuse/ledger.sqlite, overridable via --ledger or TOKFUSE_LEDGER_PATH).

Exit Codes

Exit Code Meaning
0 (or child code) Wrapped command exited normally without tripping any fuse
2 Invalid CLI flags or missing target command
75 Budget fuse tripped (--max-usd, --daily-usd, or unpriced model in fail-closed mode)
76 Loop / call-count fuse tripped (--max-loop, --max-repeat, or --max-calls)
124 Wall-clock timeout tripped (--max-wall-sec)

Key Flags (tokfuse run)

Flag Default Description
--max-usd FLOAT unset Hard session USD cap enforced via atomic pre-flight reservation
--daily-usd FLOAT unset Hard UTC daily USD cap shared across concurrent processes (SQLite WAL)
--max-loop INT 3 Trip on N consecutive identical or A <-> B ping-pong tool-call turns (0 disables)
--max-calls INT unset Hard cap on total LLM generation calls in the session
--max-wall-sec FLOAT unset Kill child process group after N seconds (exit 124)
--default-max-tokens INT 4096 Output token cap reserved when a request omits max_tokens
--price-in / --price-out built-in table Custom USD per 1,000,000 input/output tokens
--allow-unknown-model false Use $5/$20 per 1M fallback instead of failing closed on unknown model IDs
--json false Emit structured JSON summary receipt to stderr on exit

Development

uv sync --dev
uv run ruff check .
uv run pytest -v

License

MIT

Metadata

Release files for tokfuse 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tokfuse 0.1.0
File Size Uploaded Provenance Actions
tokfuse-0.1.0.tar.gz 31.9 kB Without provenance Details for tokfuse-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for tokfuse 0.1.0
File Interpreter ABI Platform Actions
tokfuse-0.1.0-py3-none-any.whl Python 3 none any Details for tokfuse-0.1.0-py3-none-any.whl

Total release size: 57.4 kB

Release files / tokfuse-0.1.0.tar.gz

Download URL tokfuse-0.1.0.tar.gz
Size 31.9 kB
Tags Source
SHA-256 checksum
How to use checksums
d78f73724e3b40fd3d5151ee177eb2b9c2a16f79d828519ff163c7613f34889c
BLAKE2b-256 checksum
How to use checksums
b80992b13321a270523241bacbfa9205733dc2df58c6d59ec3eac0b6d357b1f5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.1 {"installer":{"name":"uv","version":"0.13.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / tokfuse-0.1.0-py3-none-any.whl

Download URL tokfuse-0.1.0-py3-none-any.whl
Size 25.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
81fa6672fcc36962dab83417f5722a38d55b71f9c16ccd518f71e9821f235bba
BLAKE2b-256 checksum
How to use checksums
29d108ee7d2e53696b8fe73c07a8ce8d2d7b2d978480158065fa84a564e412d9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.1 {"installer":{"name":"uv","version":"0.13.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for tokfuse 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page