Skip to main content
Glama

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

npm install mcp-spendshield

Related MCP server: Expense-Tracker-MCP-Server

Quick start

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

npm install
npm test
npm pack --dry-run

Node.js 20+ · TypeScript · MIT

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers