Skip to main content
Glama
KitsuneTech1

Token Guardian MCP

by KitsuneTech1

Token Guardian MCP

Token Guardian — это локальный MCP-сервер только для чтения, предназначенный для выявления неэффективного использования токенов в Claude Code и Codex, не снижая при этом их производительность.

Он выполняет две задачи:

  • Сообщает, какие агенты, модели и сессии обрабатывают больше всего токенов.

  • Рекомендует самую дешевую безопасную модель и уровень усилий для конкретной задачи.

Также включает команду route-task для пробного запуска, предназначенную для тестирования маршрутизации на основе промпта до регистрации MCP где-либо.

Жесткая граница безопасности

Token Guardian не может изменять настройки модели, уровни усилий, ограничения контекста, сжатие, регистрацию MCP или запущенные сессии. У него нет учетных данных модели, и он не совершает платных вызовов API.

Инструмент использования вызывает ccusage с флагами --offline и --no-cost. Заголовки Codex являются необязательными метаданными, читаемыми через sqlite3 -readonly. Каждый инструмент MCP помечен как доступный только для чтения, неразрушающий, идемпотентный и замкнутый.

Related MCP server: token-pilot

Инструменты

token_guardian_usage_snapshot

Считывает от одного до тридцати дней локального использования и возвращает:

  • Итоги по агенту и модели

  • Доли кэшированного чтения, вывода и frontier-моделей

  • Крупнейшие сессии

  • Точные дубликаты заголовков работ Codex

  • Быстрые выигрыши, подтвержденные данными

Обработанные токены являются диагностикой рабочей нагрузки. Они не эквивалентны счетчику подписки, особенно когда доминирует кэшированный ввод.

token_guardian_recommend_route

Принимает клиент, задачу, риск и текущий размер контекста. Возвращает модель, уровень усилий, причины и опциональный frontier-валидатор.

Политика закрывается при ошибке. Работа, связанная с безопасностью, архитектурой, производством, разрушительными действиями, высоким риском, критическими задачами или неоднозначными ситуациями, остается на frontier-модели. Дешевые модели обрабатывают ограниченную механическую работу. Сбалансированные модели обрабатывают обычное кодирование и отладку, при необходимости с проверкой frontier.

Тестирование маршрутизации на основе промпта

Соберите проект, затем запустите маршрутизатор из любой папки:

node ./dist/route-cli.js --client codex --prompt "Implement a bounded TypeScript parser with tests." --cwd .

Рабочая папка не обязательно должна быть репозиторием. Маршрутизатор в первую очередь использует промпт. Он проверяет до 256 имен в текущей папке на наличие необязательных маркеров проекта, не открывая содержимое файлов и не сканируя подпапки.

Команда только выводит рекомендацию и команду запуска в рамках сессии. Она не выполняет эту команду, не изменяет конфигурацию, не регистрирует MCP и не взаимодействует с активной сессией. Расплывчатые продолжения промптов, такие как yeah, test that, остаются на frontier-маршруте, поскольку их реальный контекст отсутствует.

Локальные требования

  • Node.js 24 или новее

  • ccusage в PATH

  • sqlite3 в PATH для необязательных заголовков потоков Codex

Сборка и тестирование

npm install
npm test
npm run typecheck
npm run build

Запустите собранный stdio-сервер:

node dist/index.js

Проверьте его без регистрации в живом клиенте:

npx @modelcontextprotocol/inspector node dist/index.js

Статус регистрации

Эта первая сборка намеренно не зарегистрирована в Claude, Codex или общем шлюзе Kitsune. Регистрация и любой перезапуск клиента являются отдельным изменением после принятия изолированного сервера.

Лицензия

MIT. См. LICENSE.

Available Tools

2 tools
token_guardian_recommend_routeRecommend Model RouteA
Read-onlyIdempotent

Recommend a conservative Claude, Codex, or local model and effort for one task. Returns advice only and never switches the active client.

ParametersJSON Schema
NameRequiredDescriptionDefault
riskNonormal
clientYesClient that will perform the task.
task_kindNoExplicit task class. Omit only when genuinely unknown.
task_summaryYesShort description of the actual work.
current_modelNo
context_tokensNo
current_effortNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
tierYes
modelYes
clientYes
effortYes
actionsYes
reasonsYes
validatorNo
confidenceYes
advisoryOnlyYes

TDQS

A3.6/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare readOnlyHint=true, idempotentHint=true, and destructiveHint=false. The description adds valuable behavioral context: 'Returns advice only and never switches the active client', confirming the tool's side-effect-free nature. No contradiction with annotations. The description could mention error handling or latency but is sufficient given the strong annotation coverage.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two sentences, front-loaded with the key action, and contains no filler. Every word adds value: 'conservative' qualifies the recommendation, 'one task' sets scope, and 'never switches' clarifies behavior. Ideal conciseness.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (7 parameters, output schema exists, good annotations), the description covers the core workflow but leaves out context like the meaning of 'conservative', 'effort', or how the recommendation relates to the input parameters. The output schema might fill gaps, but the description could be more helpful for understanding the tool's role in a multi-step workflow.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is only 43% (3 of 7 parameters have descriptions). The description adds no parameter-specific information; it only states the overall purpose. Parameters like 'risk', 'current_effort', and 'context_tokens' remain undocumented, and the description does not compensate for the low coverage. The agent must rely on the incomplete schema, which is insufficient.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb 'recommend', the resource ('model and effort'), and the scope ('for one task'). It also distinguishes from the sibling tool 'token_guardian_usage_snapshot' by emphasizing that it returns advice only and does not change state, making the purpose specific and unambiguous.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no explicit guidance on when to use this tool versus the sibling 'token_guardian_usage_snapshot'. It states that it returns advice only, implying safe usage, but does not mention when to choose recommendations over usage snapshots or any prerequisites or exclusions. This leaves the agent without clear direction on invocation context.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

token_guardian_usage_snapshotToken Usage SnapshotA
Read-onlyIdempotent

Read local Claude Code and Codex usage, identify large contexts and expensive routing, and return evidence-backed quick wins. Never changes settings or sessions.

ParametersJSON Schema
NameRequiredDescriptionDefault
daysNo
agentNoall
top_sessionsNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
caveatYes
totalsYes
windowYes
byAgentYes
byModelYes
metricsYes
quickWinsYes
topSessionsYes
duplicateCodexWorkYes

TDQS

A4/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare readOnlyHint, idempotentHint, and destructiveHint as safe. The description reinforces this by stating 'Never changes settings or sessions.' It adds value by describing what the tool does with the data (identify, return quick wins), which goes beyond the annotations' safety profile.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two efficient sentences that pack in the tool's purpose, outcomes, and safety guarantee. Every word serves a purpose with no redundancy or filler.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The description is adequate for a read-only snapshot tool with an output schema and sensible defaults, but it fails to mention the tunable parameters (days, agent, top_sessions) that control the snapshot scope. The sibling tool is not contrasted, leaving the agent to infer the relationship.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate, but it does not mention the three parameters (days, agent, top_sessions) or their roles. The parameter names are somewhat self-explanatory, but the description adds no additional meaning beyond the schema's type and default constraints.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool reads usage data, identifies large contexts and expensive routing, and returns quick wins. It uses a specific verb ('Read') and resource ('local Claude Code and Codex usage'), and distinguishes from the sibling tool 'token_guardian_recommend_route' by focusing on analysis rather than recommendations.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly states it never changes settings or sessions, implying it is safe for inspection. It contrasts with the sibling by focusing on analysis and quick wins, but does not provide explicit 'when to use vs when not to use' guidance. The context is clear enough for an agent to infer appropriate usage.

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.

  1. 2 tool updatesv0.1.0
    • First observedtoken_guardian_recommend_route
    • First observedtoken_guardian_usage_snapshot

TDQS

A3.7/5.0

Scored across 2 tools

Disambiguation5/5

Each tool serves a distinct, non-overlapping purpose: one provides a usage snapshot with improvement suggestions, the other recommends a routing choice for a task. There is no ambiguity between them.

Naming Consistency5/5

Both tool names follow a consistent 'token_guardian_<verb>_<noun>' pattern using snake_case, with descriptive verbs ('usage_snapshot', 'recommend_route') that clearly indicate their function.

Tool Count3/5

With only 2 tools, the server feels minimal for a domain that might benefit from additional diagnostics (e.g., cost breakdown, model listing) or configuration advice. The count is on the low end of acceptable for a focused utility.

Completeness2/5

The server explicitly avoids any action tools, being read-only. It covers snapshot analysis and routing recommendations but lacks tools for detailed queries (e.g., by time period, by model) or applying any changes, leaving notable gaps for hands-on usage optimization.

Maintenance

ActivityStale
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers