tbcontracts-mcp
Provides observability integration by emitting OpenTelemetry spans and gen_ai.client.token.usage counters for spend recording, allowing token usage metrics to be exported to compatible backends.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@tbcontracts-mcpreallocate spare tokens from low-priority agents to researcher"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
tbcontracts-mcp
An MCP (Model Context Protocol) server that exposes
token-budget-contracts
as tools, so any MCP-aware client (Claude Code, Claude Desktop, Cursor,
etc.) can manage token budgets across a multi-agent LLM system.
What this actually does
Multi-agent orchestrators (a planner spawning a researcher, a writer, a critic, ...) burn tokens unevenly. A high-priority agent can starve mid-task while a low-priority agent sits on unused budget. This server's one job is answering, in real time: given these agents' priorities and current spend, how should the remaining budget move right now?
It does this by wrapping token-budget-contracts'
priority-weighted Reallocator: spare budget flows from idle or
lower-priority agents to whichever agent is actually starved, never
below a donor's protected minimum reserve, and never "uphill" from a
more important agent to a less important one.
This is not a cost-tracking dashboard or a network gateway. See Honest scope below.
Related MCP server: spiderswitch
Install
pip install tbcontracts-mcpThis pulls in token-budget-contracts>=0.3.0 and opentelemetry-api as
dependencies. Requires Python 3.10+ (see Why not Python 3.9).
Tools
Tool | What it does |
| Register an agent with a priority weight and initial token budget. |
| Record raw input/output tokens an agent consumed for a task. Automatically triggers priority-weighted reallocation if the agent goes over budget. |
| Look up one agent's current remaining budget, priority, and reserve. |
| The core tool. Given an agent that needs more tokens right now, runs the real priority-weighted borrowing logic and returns a concrete plan: which agents gave up how much, which agent received it, and why each donor was eligible. |
| Full current state of every registered agent, as structured JSON. |
Every tool takes a strict, typed JSON input schema and returns structured
JSON ({"success": true/false, ...}) - never free text - so a calling
agent or orchestrator can parse the result programmatically.
Error handling
Unknown agent IDs, invalid input, and budget-exceeded conditions all come back as a structured error, never a stack trace:
{
"success": false,
"error": {
"type": "unknown_agent",
"message": "Agent 'ghost' was never registered. Call register_agent first.",
"agent_id": "ghost",
"known_agents": ["critic", "researcher"]
}
}Error type is one of unknown_agent, invalid_input, budget_exceeded,
tbcontracts_error, or internal_error. A bad tool call never crashes
the server process - the MCP client keeps working.
Quick start (as a library, for testing)
from tbcontracts_mcp import server
server.register_agent(agent_id="researcher", priority=3, max_tokens=4000)
server.register_agent(agent_id="critic", priority=1, max_tokens=2000)
server.record_spend(agent_id="researcher", input_tokens=3800, output_tokens=100)
# -> over budget by 400 tokens; automatically borrows from critic
plan = server.request_reallocation(agent_id="researcher", tokens_needed=1000)
print(plan)Normally you won't call these functions directly - an MCP client calls them as tools over stdio. See the client configs below.
Using it from an MCP client
The server runs over stdio and needs no network setup - just point your
client at the tbcontracts-mcp command.
Claude Code
claude mcp add tbcontracts -- tbcontracts-mcpOr add it directly to .mcp.json:
{
"mcpServers": {
"tbcontracts": {
"command": "tbcontracts-mcp"
}
}
}Claude Desktop
Add to claude_desktop_config.json:
{
"mcpServers": {
"tbcontracts": {
"command": "tbcontracts-mcp"
}
}
}Cursor
Add to .cursor/mcp.json:
{
"mcpServers": {
"tbcontracts": {
"command": "tbcontracts-mcp"
}
}
}Any of these can equally run it via python -m tbcontracts_mcp instead of
the console script, e.g. if you've installed it into a specific venv:
{
"mcpServers": {
"tbcontracts": {
"command": "/path/to/venv/bin/python",
"args": ["-m", "tbcontracts_mcp"]
}
}
}Observability
Spend recorded through record_spend is emitted two ways, both additive
to your existing observability stack rather than replacing it:
The underlying library's own OTel spans.
token-budget-contractsalready instruments every governance decision (registration, spend, reallocation) as an OpenTelemetry span when telemetry is enabled. This server wiresrecord_spendstraight through that existing hook rather than building a parallel tracer - setTBCONTRACTS_MCP_OTEL=1in the server's environment to turn it on (uses the global OTel tracer provider; configure your exporter the usual OTel way).A
gen_ai.client.token.usagecounter, following the emerging OpenTelemetrygen_ai.*semantic conventions, emitted viaopentelemetry-apifor everyrecord_spendcall. This tracks raw input/output token counts per agent, not pre-computed dollar cost - pricing tables change constantly and a token counter shouldn't be coupled to one. Attach whatever OTelMeterProvider/exporter you like in the process that launches this server; if none is configured, this is a no-op.
Honest scope
tbcontracts-mcp is the allocation-decision layer for one thing:
priority-weighted budget reallocation between agents you've already told
it about. It is meant to be composed with other tools, not to replace
them. Specifically, it does not:
do cross-provider cost tracking. It emits raw token counters, not dollar costs, and has no notion of a pricing table for OpenAI, Anthropic, or anyone else.
do network-level rate limiting or gateway routing. It doesn't sit in the request path between your app and an LLM provider, and it can't throttle or route calls. Tools like Bifrost, MuleSoft, or Solo.io's gateways already do that well - use one of those alongside this.
replace an observability platform. It emits spans/counters you can send to Grafana, Datadog, Honeycomb, etc., but it isn't a dashboard, storage backend, or alerting system itself.
What it does do: given the agents you've registered and their current spend, decide - and actually execute - how unused budget should move between them right now, based on priority.
Why not Python 3.9?
token-budget-contracts itself supports Python 3.9+, but the official
mcp Python SDK this server depends on has never supported Python 3.9
(it requires 3.10+ on every released version). This package therefore
requires Python 3.10+, even though the library it wraps does not.
Development
git clone https://github.com/swaranshu-borgaonkar/tbcontracts-mcp
cd tbcontracts-mcp
pip install -e ".[dev]"
pytest -vLicense
MIT for the code in this package. token-budget-contracts, which this
server wraps, implements the governance model described in a pending
U.S. provisional patent application (see its own README for details). If
you plan to use this commercially at scale, consult your own counsel.
Available Tools
5 toolsget_budget_snapshotA
Return the full current state of every registered agent - priority, allocated budget, consumed tokens, remaining budget, and min_reserve - as structured JSON. Use this for a system-wide view before deciding whether a reallocation is needed, or to let an orchestrator/human inspect overall budget health across all agents at once.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full disclosure burden. It communicates a read-only aggregate behavior via 'Return' and 'snapshot', details the output as structured JSON, and explains the system-wide scope. It stops short of explicitly stating 'does not modify any state' or discussing failures, but for a zero-parameter getter the behavioral disclosure is solid.
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?
Two sentences, each earning its place: the first states output scope and fields, the second states exactly when the tool should be used. The most important information is front-loaded in the first sentence, and there is no redundant wording.
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?
For a zero-parameter, read-only aggregation tool with no output schema, the description is complete: it specifies the returned fields, the format, the scope, and primary usage scenarios. An agent can invoke this correctly without additional context.
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 tool has no parameters, so the schema already fully covers this dimension. The description adds no parameter-specific meaning but also does not need to; 0-parameter tools get a baseline score of 4 since there is nothing to clarify.
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 states a specific verb and resource: 'Return the full current state of every registered agent' and enumerates the exact fields (priority, allocated budget, consumed tokens, remaining budget, and min_reserve). It is clearly differentiated from siblings by emphasizing the system-wide, all-agents scope, unlike get_remaining_budget presumably, making the purpose unmistakable.
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 gives concrete usage contexts: 'before deciding whether a reallocation is needed' and 'to let an orchestrator/human inspect overall budget health across all agents at once.' It clearly implies a system-wide monitoring role, though it does not explicitly name when not to use it or mention alternative sibling tools by name.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
get_remaining_budgetA
Return a single agent's current remaining token budget, along with its allocated total, consumed total, priority, and protected minimum reserve. Use this to check whether an agent is close to starved before deciding whether to request a reallocation.
| Name | Required | Description | Default |
|---|---|---|---|
| agent_id | Yes | The registered agent to look up. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden. The verbs 'Return' and 'check' clearly imply a read-only operation, and the description discloses the returned fields and the concept of 'close to starved.' However, it does not explicitly state that it has no side effects, require no special permissions, or describe error behavior—though these are partially implied by the tool name and usage.
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 two sentences with no filler. The first sentence front-loads the function and output fields; the second provides a directly actionable use case. Every sentence earns its place.
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?
The tool has one parameter, no output schema, and no annotations. The description compensates by listing all returned fields (remaining budget, allocated, consumed, priority, protected minimum reserve) and the context for use. An agent has enough information to call the tool and interpret the result.
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 description coverage is 100% because agent_id is described as 'The registered agent to look up.' The description adds only the notion of 'single agent,' which reinforces the semantics already present in the schema but does not add meaningful new meaning beyond it. Baseline 3 is appropriate.
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 states a specific verb and resource: 'Return a single agent's current remaining token budget' along with the exact fields returned. It distinguishes from siblings by emphasizing 'single agent' (vs. get_budget_snapshot) and by connecting to the reallocation workflow (vs. request_reallocation).
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 gives a clear use case: 'Use this to check whether an agent is close to starved before deciding whether to request a reallocation.' It implies when this tool is appropriate relative to request_reallocation, but it does not explicitly mention when not to use it or name the alternative get_budget_snapshot.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
record_spendA
Record tokens actually consumed by a registered agent for a task, as raw input/output token counts (not dollar cost). If this pushes the agent over its remaining budget, the library automatically attempts priority-weighted reallocation to cover the shortfall from eligible donor agents before failing. The response reports whether reallocation was triggered and, if so, exactly which donor agents gave up how many tokens. Fails with a structured budget_exceeded error if no combination of donors can cover the shortfall - it never silently overspends.
| Name | Required | Description | Default |
|---|---|---|---|
| task | No | Free-text label for what this spend was for, e.g. the task name. | |
| agent_id | Yes | The registered agent the spend belongs to. | |
| confidence | No | Optional 0-1 confidence score for the result this spend produced. Feeds the agent's confidence gate for its next spend request. | |
| input_tokens | No | Number of prompt/input tokens consumed by this call. | |
| output_tokens | No | Number of completion/output tokens consumed by this call. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden of behavioral disclosure, and it does so thoroughly. It reveals automatic priority-weighted reallocation, donor agent involvement, response contents, structured budget_exceeded errors, and the guarantee that it never silently overspends.
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 front-loaded with the tool's core purpose and every sentence adds unique value: purpose, reallocation behavior, response shape, and failure mode. It is detailed enough to be actionable without being padded or redundant.
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?
Despite having no output schema and no annotations, the description covers the operation, side effects, return behavior, and error semantics. An agent has everything it needs to decide when to call this tool and what to expect from the call.
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 input schema has 100% coverage, so the baseline is 3. The description adds meaningful semantic context by emphasizing that input_tokens and output_tokens are raw token counts rather than dollar costs, which prevents a common misinterpretation that the schema alone does not explicitly guard against.
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 states the specific action ('record tokens actually consumed'), the resource (a registered agent for a task), and the exact unit (raw input/output token counts, not dollar cost). It clearly differentiates this from sibling tools like request_reallocation by explaining that record_spend is the recording action and reallocation happens automatically as a consequence.
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 makes it clear this is the tool to call when reporting actual token consumption for a completed task, and it explains the reallocation behavior that may follow. It does not explicitly mention when to use request_reallocation directly or what conditions would favor that sibling, so the guidance stops short of naming exclusions.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
register_agentA
Register a new agent in the budget system with a priority weight and an initial token budget. Call this once per agent before recording spend or requesting reallocation for it. Priority is relative: higher priority agents can pull spare budget from equal-or-lower priority agents during reallocation, but budget never flows from a higher-priority agent to a lower-priority one. Re-registering an existing agent_id resets its contract and ledger entry.
| Name | Required | Description | Default |
|---|---|---|---|
| agent_id | Yes | Unique identifier for the agent, e.g. 'researcher' or 'writer'. | |
| priority | No | Relative importance; higher number = more important. During reallocation, this agent may only receive tokens from donor agents whose priority is <= this value. | |
| max_tokens | No | Initial token budget allocated to this agent. | |
| min_reserve | No | Minimum tokens this agent must always retain, even when it is eligible to donate during someone else's reallocation. Defaults to 10% of max_tokens if omitted. | |
| confidence_threshold | No | Optional 0-1 confidence threshold. Once a recorded spend for this agent reports a confidence at or above this value, further spend requests are blocked by the confidence gate. Omit to disable. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden of behavioral disclosure, and it does well: it explains the relative priority semantics (higher priority pulls from equal-or-lower, never the reverse) and explicitly discloses that re-registering resets the contract and ledger entry — a destructive repeat-call consequence. No contradiction with annotations since none exist.
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?
Three dense sentences, front-loaded with the primary purpose in the first sentence. The priority semantics and reset behavior earn their place and there is no fluff. Slightly dense but well structured for the information conveyed.
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?
For a registration tool with no output schema, the description covers the prerequisite relationship to siblings, the priority flow rules, and the reset-on-reregister consequence — everything an agent needs to call it correctly. Minor gap: no mention of expected return value or success indication, but acceptable without an output schema.
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 100%, so the baseline is 3. The description mentions 'priority weight' and 'initial token budget', mapping to priority and max_tokens, but adds nothing beyond what the schema already documents for each parameter. The schema itself carries the parameter detail.
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 opening sentence 'Register a new agent in the budget system with a priority weight and an initial token budget' uses a specific verb (register) with a specific resource (agent in budget system) and the key fields. It distinguishes itself from siblings by framing registration as a prerequisite to record_spend and request_reallocation, so an agent can tell it apart from the other four tools.
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 gives explicit sequencing guidance: 'Call this once per agent before recording spend or requesting reallocation for it.' This tells the agent when to use the tool relative to its siblings. It doesn't explicitly state when NOT to use it (e.g., to inspect budget one should use get_budget_snapshot), but the prerequisite framing provides clear enough context.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
request_reallocationA
The core allocation-decision tool. Given an agent that needs additional tokens right now, run the library's priority-weighted borrowing logic to pull spare budget from eligible donor agents - starting with the lowest-priority, most-idle ones - and apply it for real. A donor is only eligible if its priority is <= the needy agent's priority (budget never flows from a more important agent to a less important one) and it never gives up tokens below its own protected min_reserve. Returns a concrete plan: which agents gave up how many tokens, which agent received them, why each donor was eligible, and how much of the requested amount could not be covered (if any). This performs a real reallocation against the live ledger, not a dry-run simulation - call get_remaining_budget first if you only want to inspect state without moving tokens.
| Name | Required | Description | Default |
|---|---|---|---|
| agent_id | Yes | The agent that needs additional budget right now. | |
| tokens_needed | Yes | How many additional tokens this agent needs beyond what it currently has remaining. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
There are no annotations, so the description carries the full behavioral burden. It clearly discloses that this performs a real reallocation against the live ledger, is not a dry-run simulation, enforces priority-based eligibility, protects min_reserve, and may only partially cover the requested amount. This is rich, actionable behavioral context.
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 dense but every sentence earns its place: core action, eligibility rules, return plan, and the critical real-vs-dry-run caveat are all included. It is front-loaded with the purpose and keeps the alternative routing at the end.
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 there is no output schema, the description compensates by specifying the return plan contents: which donors gave up tokens, which agent received them, why each donor was eligible, and how much could not be covered. With safety, side effects, and when-not-to-use all covered, nothing essential is missing for correct invocation.
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 description coverage is 100%, so the schema already explains both agent_id and tokens_needed. The description adds minimal new parameter-level meaning beyond restating the need for additional tokens and the requested amount, so the baseline of 3 is appropriate.
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 identifies the tool as the core allocation-decision tool that runs priority-weighted borrowing logic to move tokens from eligible donor agents to a needy agent. It also explicitly distinguishes itself from the inspection-only sibling get_remaining_budget, so an agent can tell them apart immediately.
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 states exactly when to use it: when an agent needs additional tokens right now and a real reallocation is desired. It explicitly names the alternative for the non-mutating case, saying to call get_remaining_budget first if you only want to inspect state without moving tokens.
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.
5 tool updates
v0.1.0- First observed
get_budget_snapshot - First observed
get_remaining_budget - First observed
record_spend - First observed
register_agent - First observed
request_reallocation
TDQS
Scored across 5 tools
Each tool maps to a distinct action: registration, spend recording, single-agent read, system-wide read, and reallocation. Although record_spend can trigger reallocation as a side effect, the descriptions clearly separate that automatic behavior from the explicit request_reallocation decision tool.
All tool names follow a consistent snake_case verb_noun pattern: register_agent, record_spend, get_remaining_budget, get_budget_snapshot, request_reallocation. The verb and noun choices are predictable and match each tool's purpose.
Five tools is well-scoped for a narrow budget-management domain. Each tool earns its place, covering registration, spending, inspection, and reallocation without redundancy or bloat.
The core lifecycle is covered: register agents, record spend, inspect individual and global state, and manually reallocate budget. Minor gaps include no explicit unregister/agent removal or direct priority adjustment without re-registering/resetting, but these are workable limitations rather than blocking dead ends.
Maintenance
Related MCP Connectors
Agent Cost Allocator MCP — multi-tenant LLM cost attribution for chargeback billing. Companion to
Hosted MCP server for LLM cost estimation, model comparison, and budget-aware routing.
Agent Token Budget MCP — hard per-session token + spend cap with signed budget-exhausted
MCP server for building and testing AI agents with multi-model experimentation and insights.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceAn MCP server that reduces token usage by lazily loading skills and tools only when needed, and routing repetitive subtasks to ML backends instead of the LLM.-
- AlicenseNot gradedqualityBmaintenanceMCP server that enables agents to dynamically switch between multiple AI models (OpenAI, Anthropic, Google, etc.) with unified protocol-driven configuration and capability discovery.Apache 2.0
- AlicenseNot gradedqualityCmaintenanceBudget management and cost tracking MCP server for autonomous agents, enabling budget creation, cost recording, spending projections, and alert rules.MIT
- FlicenseNot gradedqualityCmaintenanceToken-optimized multi-agent orchestration MCP server that owns session state, compacts context between agent hops, routes work to smaller models when safe, and reports estimated token savings.1-