MCP Budget
by Nawfel1235
README.md
# MCP SpendShield
Node.js/TypeScript cost tracking and daily budget enforcement for MCP tool handlers. Tracks explicit USD costs and token usage, estimates missing usage, and applies global, per-tool, and per-client daily limits.
## Install
```bash
npm install mcp-spendshield
```
## Quick start
```ts
import { createMCPSpendShield } from "mcp-spendshield";
const spend = createMCPSpendShield({
maxDailyUsd: 25,
maxPerToolUsd: { deep_research: 5, image_generation: 8 },
maxPerClientUsd: 10,
mode: "block",
estimatedUsdPerToken: 0.000002,
});
const budgetedSearch = spend.wrapToolHandler(
async (args: { query: string }) => providerSearch(args.query),
"deep_research",
);
// Register budgetedSearch as the MCP tool handler.
const snapshot = spend.status();
console.log(snapshot);
```
The wrapper reads `cost_usd`, `total_cost_usd`, or `cost` from the result, then token usage from a `usage` object. When usage is missing it calls `costEstimator`, or estimates from serialized result length. Client identity is derived from the Bearer token or `context.clientId`, then SHA-256 hashed. Supply `clientIdResolver` when your transport has a trusted client identity.
## Configuration
| Option | Default | Description |
| --- | ---: | --- |
| `maxDailyUsd` | unset | Global daily USD ceiling. |
| `maxPerToolUsd` | `{}` | Daily ceiling by tool name. |
| `maxPerClientUsd` | unset | Daily ceiling per client. |
| `mode` | `warn` | `warn` logs and allows; `block` withholds the result and throws. |
| `estimatedUsdPerToken` | `0.000001` | Fallback token price. |
| `costEstimator` | unset | Custom function returning estimated USD cost. |
| `clientIdResolver` | automatic | Resolve a trusted client identifier from handler context. |
| `logger` | console | Structured budget event callback. |
**Operational note:** costs are measured after a tool returns. Block mode withholds the result after execution; it cannot undo side effects or guarantee a pre-execution spend cap. Counters are in-memory and process-local, reset at UTC midnight, and do not coordinate across replicas. Use provider-side quotas for hard spending limits.
## API
- `createMCPSpendShield(options)` / `new MCPSpendShield(options)`
- `spend.wrapToolHandler(handler, toolName)`
- `spend.status()` / `spend.reset()`
- `CostTracker`, `BudgetExceededError`
## Development
```bash
npm install
npm test
npm pack --dry-run
```
Node.js 20+ · TypeScript · MIT
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues