tokentoll
tokentoll
Erkennen Sie Änderungen der LLM-Kosten im Code-Review. Infracost für LLM-Ausgaben.
Ein CLI-Tool und eine GitHub-Action, die Ihren Code statisch auf LLM-API-Aufrufe analysiert, deren Kosten schätzt und Ihnen die Kostenauswirkungen jeder Änderung in Ihrem Terminal oder als PR-Kommentar anzeigt. Keine Laufzeitabhängigkeiten.
Das Problem
Ein einziger Modellwechsel von gpt-4o-mini zu gpt-4o erhöht die Kosten um das 15-fache.
Ein neuer API-Aufruf in einem kritischen Pfad kann Ihre Rechnung um 10.000 $/Monat erhöhen.
Diese Änderungen verstecken sich im normalen Code-Review.
tokentoll findet LLM-API-Aufrufe in Ihrem Code, schätzt deren Kosten und zeigt Ihnen die Kostenauswirkungen jeder Änderung, bevor sie in die Produktion gelangt.
Related MCP server: CosTrack MCP
Schnellstart
pip install tokentoll
# Scan current directory for LLM API calls and their costs
tokentoll scan .
# Show cost impact of your last commit
tokentoll diff HEAD~1
# Compare two branches
tokentoll diff main..feature-branchGitHub Action
name: LLM Cost Diff
on:
pull_request:
paths:
- "**.py"
permissions:
pull-requests: write
jobs:
cost-diff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: Jwrede/tokentoll@v0.6.1Was es erkennt
SDK | Muster | Status |
OpenAI |
| Unterstützt |
Anthropic |
| Unterstützt |
Google GenAI |
| Unterstützt |
LiteLLM |
| Unterstützt |
LangChain |
| Unterstützt |
Zhipu AI |
| Unterstützt |
JS/TS SDKs | Geplant |
Beispielausgabe
tokentoll scan
LLM API Calls Detected
============================================================
File: src/agents/summarizer.py
Line 42: openai client.chat.completions.create
Model: gpt-4o | Max tokens: 4096
Est. cost/call: $0.03 | Monthly (1000 calls/month per call site): $26.50
Line 78: openai client.chat.completions.create
Model: gpt-4o-mini | Max tokens: 1000
Est. cost/call: $0.000301 | Monthly (1000 calls/month per call site): $0.30
--
Total estimated monthly cost: $26.80
1000 calls/month per call sitetokentoll diff
LLM Cost Diff: main..feature-branch
============================================================
+ ADDED src/agents/rewriter.py:35
openai | Model: gpt-4o
Est. cost/call: $0.03 | Monthly: +$26.50
~ MODIFIED src/agents/summarizer.py:42
openai | Model: gpt-4o -> gpt-4o-mini
Est. cost/call: $0.03 -> $0.000301 | Monthly: -$26.20
--
Monthly cost impact: +$0.30
Added: 1 | Changed: 1 | Removed: 0
1000 calls/month per call siteFunktionsweise
Source Code (.py files)
|
v
+-------------+ +------------------+
| AST Scanner |---->| SDK Detectors |
| (ast.parse) | | OpenAI, Anthropic|
+-------------+ | Google, LiteLLM |
| LangChain |
+------------------+
|
v
+------------------+
| Pricing Engine |
| 2200+ models |
| Auto-cached |
+------------------+
|
+-----------+-----------+
| |
v v
+------------+ +-------------+
| Scan Report| | Diff Engine |
| (costs) | | (old vs new) |
+------------+ +-------------+
| |
v v
+------------+ +-------------+
| Table/JSON | | Table/JSON/ |
| | | PR Comment |
+------------+ +-------------+Analysiert Python-Dateien mithilfe des
ast-Moduls, um LLM-API-Aufrufe zu findenMulti-Pass-Konstanten-Propagierung löst Modellnamen über Variablen,
os.getenv()-Fallbacks, Klassenattribute, Konstruktor-Argumente, Dict-Inhalte und**kwargs-Entpackung aufSucht Preise aus einem lokalen Cache (bezogen von LiteLLM, über 2200 Modelle)
Für den Diff-Modus: Vergleicht Aufrufe zwischen zwei Git-Refs und berechnet die Kostendifferenz
Gibt einen Kostenbericht als Tabelle, JSON oder GitHub-PR-Kommentar aus
CLI-Referenz
tokentoll scan [PATH...] [--format table|json|markdown] [--calls-per-month N] [--config PATH]
tokentoll diff [REF] [--base REF] [--head REF] [--format table|json|markdown|github-comment] [--config PATH]
tokentoll update # Update bundled pricing dataMCP-Server
tokentoll enthält einen MCP-Server (Model Context Protocol), mit dem Claude Code und andere MCP-Hosts die Kostenauswirkungen von LLM-Codeänderungen direkt aus einem Agenten-Gespräch heraus überprüfen können.
Installation
pip install tokentoll[mcp]Registrierung bei Claude Code
claude mcp add --transport stdio tokentoll -- tokentoll-mcpTools
Tool | Beschreibung |
| Findet LLM-API-Aufrufe in einem Verzeichnis und schätzt die monatlichen Kosten. Akzeptiert einen Pfad und optional |
| Vergleicht LLM-Kosten zwischen zwei Git-Refs. Akzeptiert |
Beide Tools geben eine JSON-Ausgabe zurück.
Beispiel-Anwendungsfall
Claude Code kann die Kostenauswirkungen seiner eigenen Änderungen vor dem Commit überprüfen. Zum Beispiel kann der Agent nach dem Wechsel eines Modells von gpt-4o zu gpt-4o-mini das diff-Tool gegen HEAD aufrufen, um die Kostenreduzierung vor dem Erstellen des Commits zu verifizieren.
Preisdaten
Preisdaten sind gebündelt und funktionieren offline. Um auf die neuesten Preise zu aktualisieren:
tokentoll updateDie Preisdaten stammen aus der model_prices_and_context_window.json von LiteLLM und decken über 300 Modelle von OpenAI, Anthropic, Google, AWS Bedrock, Azure und mehr ab.
Dynamische Modell-Standardwerte
Wenn tokentoll auf einen Aufruf stößt, bei dem der Modellname eine Variable ist, die nicht aufgelöst werden kann, wendet es einen sinnvollen SDK-spezifischen Standardwert an, damit Sie dennoch Kostenschätzungen erhalten:
SDK | Standardmodell |
OpenAI |
|
Anthropic |
|
Google GenAI |
|
LiteLLM |
|
LangChain |
|
Zhipu AI |
|
Diese Standardwerte werden in der Scan-Ausgabe als gpt-4o (default) angezeigt. Sie können diese pro Projekt oder pro Pfad mithilfe einer .tokentoll.yml-Konfigurationsdatei überschreiben (siehe unten).
Konfiguration
Erstellen Sie eine .tokentoll.yml in Ihrem Projektstammverzeichnis, um das Verhalten anzupassen. tokentoll findet diese Datei automatisch, indem es vom gescannten Verzeichnis aus nach oben sucht.
# Default model for all dynamic (unresolved) calls
default_model: gpt-4o
# Per-SDK defaults (override the built-in defaults above)
default_models:
openai: gpt-4o-mini
anthropic: claude-haiku-3-20240307
# Assumed calls per month per call site
calls_per_month: 5000
# Skip cost estimation entirely for dynamic (unresolved) models. When true,
# calls whose model name cannot be resolved statically are reported with no
# cost rather than priced against a default. Useful for projects that prefer
# silence over a guess.
skip_dynamic_models: false
# Exclude paths from scanning (prefix match or glob pattern)
exclude:
- tests/
- examples/
- docs/
- "*_test.py"
# Per-path overrides (longest prefix match)
overrides:
- path: src/agents/
default_model: gpt-4o
calls_per_month: 10000
- path: src/azure/
skip_dynamic_models: trueAuflösungsreihenfolge für dynamische Modell-Standardwerte: SDK-spezifische Konfiguration (default_models) > generische Konfiguration (default_model) > integrierte SDK-Standardwerte.
Sie können auch --config path/to/.tokentoll.yml übergeben, um eine bestimmte Konfigurationsdatei zu verwenden.
Tokenschätzung
Standardmäßig schätzt tokentoll die Token-Anzahl mithilfe einer Zeichen/4-Heuristik. Für genauere Schätzungen installieren Sie tiktoken:
pip install tiktokenWenn tiktoken verfügbar ist, verwendet tokentoll die korrekte Tokenizer-Kodierung für jedes Modell. Unbekannte Modelle fallen auf cl100k_base zurück. Tiktoken wird bei Bedarf geladen und Encoder werden zwischengespeichert, sodass kein Start-Performanceverlust entsteht, wenn Sie es nicht benötigen.
Intelligente Variablenauflösung
Echte Codebasen übergeben Modellnamen selten als String-Literale. Die Multi-Pass-Konstanten-Propagierungs-Engine von tokentoll folgt:
DEFAULT_MODEL = os.getenv("MODEL", "gpt-4o")
class Config:
model: str = DEFAULT_MODEL
config = Config()
kwargs = {"model": config.model, "max_tokens": 2000}
client.chat.completions.create(**kwargs)
# tokentoll resolves: model="gpt-4o", max_tokens=2000Variablenzuweisungen (
MODEL = "gpt-4o")os.getenv()/os.environ.get()Fallback-WerteStandardparameter von Funktionen
Standardwerte von Klassenattributen
Konstruktor-Argument-Propagierung
Dict-Literal- und Subskript-Inhalte
**kwargs-Entpackung
Roadmap
Kontextbewusste Aufrufhäufigkeit (geplant): Schätzung der Aufrufe/Monat aus dem umgebenden Code (FastAPI-Routen-Handler = hoher Datenverkehr, Skripte = niedrig, Schleifen = multipliziert), anstatt ein einheitliches Volumen über alle Aufrufstellen hinweg anzunehmen.
JS/TS-Unterstützung (geplant): Erkennung von LLM-Aufrufen in JavaScript- und TypeScript-Dateien.
Kostenwarnungen: Konfigurierbare Schwellenwerte, die CI fehlschlagen lassen, wenn ein PR eine Kostendifferenz überschreitet.
Einschränkungen
Kann Modelle, die zur Laufzeit aus externen Konfigurationsdateien oder Datenbanken geladen werden, nicht auflösen. Diese Aufrufe verwenden SDK-spezifische Standardwerte (konfigurierbar über
.tokentoll.yml).Token-Schätzungen verwenden eine Zeichen/4-Heuristik, sofern nicht tiktoken installiert ist.
Monatliche Schätzungen gehen von einem einheitlichen Aufrufvolumen pro Aufrufstelle aus (konfigurierbar über
--calls-per-month,.tokentoll.ymloder Pfad-spezifische Überschreibungen). Verwenden Sie dieexclude-Option, um Test- und Beispieldateien zu überspringen.Derzeit nur Python (JS/TS-Unterstützung geplant).
Lizenz
MIT
Available Tools
2 toolsdiffA
Compare LLM costs between two git refs.
Shows which LLM call sites were added, removed, or changed between the base and head refs, along with the cost impact of those changes.
Args: base_ref: The base git ref (branch, tag, or commit) to compare from. head_ref: The head git ref to compare to. Defaults to HEAD.
Returns: JSON string with the diff results including cost changes.
| Name | Required | Description | Default |
|---|---|---|---|
| base_ref | Yes | ||
| head_ref | No | HEAD |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden. It indicates a read-like operation (diff) and describes the output, but does not explicitly state side effects or permissions. Adequate but not exhaustive.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is concise, front-loaded with purpose, and includes parameter docs and return type. Every sentence adds value without repetition.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's complexity and the presence of an output schema (not shown), the description adequately covers purpose, parameters, and output format. It could include examples or edge cases but is sufficiently complete for an agent.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 0%, but the description documents both parameters: base_ref as the base git ref and head_ref as the head ref defaulting to HEAD. This adds essential meaning beyond the schema.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool compares LLM costs between two git refs, specifying it shows added, removed, or changed call sites and cost impact. This distinguishes it from the sibling 'scan' tool.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides clear context for when to use the tool (to compare costs between refs) but does not explicitly state when not to use it or mention alternatives. Usage is well implied.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
scanA
Scan a directory for LLM API calls and estimate monthly costs.
Finds all LLM API call sites (OpenAI, Anthropic, etc.) in the given path and produces a cost estimate based on token counts and pricing.
Args: path: Directory or file path to scan. Defaults to current directory. calls_per_month: Assumed monthly call volume per call site. If not provided, the CLI default (1000) is used.
Returns: JSON string with the scan results including call sites and cost estimates.
| Name | Required | Description | Default |
|---|---|---|---|
| path | No | . | |
| calls_per_month | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden. It details the scanning action, cost estimation, and return format. While it doesn't cover every edge case (e.g., recursion depth or error handling), it provides sufficient behavioral insight for a read-only analysis tool.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is concise and well-structured: a lead sentence, then details in Args and Returns sections. Every sentence adds value, and the format is easy to parse.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's simplicity (2 optional params, no annotations), the description covers the core behavior and return type adequately. It could mention recursion or failure modes, but it is sufficient for most use cases.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The schema has 0% description coverage, but the description fully explains both parameters: 'path' (directory/file, default current dir) and 'calls_per_month' (monthly volume, default null implying CLI default of 1000). This adds essential meaning beyond the schema.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool scans a directory for LLM API calls and estimates costs, specifying providers and purpose. This is a specific verb+resource that distinguishes it from the sibling 'diff'.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description clearly indicates when to use the tool (scanning directories for LLM calls and cost estimation). However, it does not explicitly mention when not to use it or provide alternatives, which prevents a top score.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
2 tool updates
v0.1.0- First observed
diff - First observed
scan
TDQS
Scored across 2 tools
The two tools, diff and scan, have clearly distinct purposes: scan finds LLM call sites and estimates costs, while diff compares costs between git refs. No overlap or ambiguity.
Both tool names are single verbs ('diff', 'scan'), which is consistent in style. While not a verb_noun pattern, the naming is uniform and intuitive for the domain.
With only 2 tools, the server is very focused. This can be appropriate for a narrow utility, but it feels thin for a full server. A few more tools (e.g., pricing config) might improve scope.
The tools cover two core operations: scanning and diffing. However, there is no tool for managing pricing configurations or listing assumptions, which could be gaps for advanced use.
Maintenance
Related MCP Connectors
Exact Claude API cost calc with real cache economics, plus a tiktoken-misuse scanner.
Code intelligence for LLMs. Analyze, search, and retrieve code from any public git repository.
AI-powered codebase analysis — call graphs, security, dead code, complexity. 150+ tools.
Codebase intelligence for AI agents — dead code, blast radius, ownership.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceEnables AI cost calculation, comparison, and optimization across major providers like Anthropic, OpenAI, Google, Meta, and Mistral. Supports cost estimation, budget-aware model finding, and token estimation through a simple API and MCP integration.-
- FlicenseNot gradedqualityDmaintenanceEnables AI agents to track LLM costs, enforce budgets, compare models, and estimate expenses through simple tool calls.-
- AlicenseBqualityDmaintenancePredict the cost of an LLM call before you make it, and pick the cheapest model that still does the job, offline, from your editor.732 npmApache 2.0
- AlicenseAqualityDmaintenanceExposes boyter/scc code counting and complexity analysis to LLM agents via read-only tools like counting lines, finding top files, and cost estimation.7BSD 3-Clause