npm package: @grislabs/agentmeter
Description: Cost intelligence for AI agents. Track per-task, per-workflow, per-customer costs.
Latest version: 0.3.0

# agentmeter

[Website](https://grislabs.com) | [npm](https://www.npmjs.com/package/@grislabs/agentmeter)

Cost intelligence for AI agents. Track per-task, per-workflow, per-customer costs across LLM calls, MCP tools, and agent payments.

**The problem:** Your AI agents make 15+ LLM calls, 8 tool calls, and trigger payments per task. Existing tools track per-API-call costs. Nobody tells you "that support ticket cost $2.47 to resolve" or "customer X is costing you $500/mo in agent spend."

## Quick Start

```bash
npm install @grislabs/agentmeter
```

### Option 1: Zero code changes

Add one import at the top of your entry file. That's it — all Anthropic and OpenAI calls are tracked automatically.

```typescript
import "@grislabs/agentmeter/auto";

// Your existing code — completely unchanged
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();
const msg = await client.messages.create({
  model: "claude-sonnet-4-20250514",
  max_tokens: 1024,
  messages: [{ role: "user", content: "Hello" }],
});
// Cost tracked automatically. No wrappers. No callbacks.
```

Or with zero file changes — just set an env var and a CLI flag:

```bash
AGENTMETER_API_KEY=am_live_... node --require @grislabs/agentmeter/register app.js
```

Configure via environment variables:

```bash
AGENTMETER_API_KEY=am_live_...          # required for remote logging
AGENTMETER_ENDPOINT=https://api.agentmeter.dev  # API endpoint
AGENTMETER_LOCAL=true                    # console-only output (no API key needed)
```

### Option 2: Explicit init (more control)

```typescript
import { init } from "@grislabs/agentmeter";

init({
  apiKey: "am_live_...",
  endpoint: "https://api.agentmeter.dev",
});

// All Anthropic/OpenAI calls are auto-tracked from here
```

### Option 3: Workflow tracing (per-task attribution)

For per-task, per-customer cost breakdown:

```typescript
import { trace, extractors } from "@grislabs/agentmeter";

const result = await trace(
  "resolve-ticket",
  { customerId: "cust_123" },
  async (ctx) => {
    const analysis = await ctx.llm(
      anthropic.messages.create({ ... }),
      extractors.anthropic,
    );

    // Tool call with cost (e.g., paid MCP server)
    await ctx.tool("search-kb", searchKB(query), { cost: 0.01, costType: "mcp" });

    // Agent payment (Stripe MPP, x402, etc.)
    await ctx.payment(
      { provider: "stripe_mpp", amount: 0.50, description: "Data lookup" },
      callMPPEndpoint(query),
    );

    return analysis;
  },
);
// Output: resolve-ticket [cust_123]: $2.47 (LLM: $0.80, Tools: $0.17, Payments: $1.50)
```

## Budget Controls

Kill runaway agents before they drain your budget:

```typescript
import { budget } from "@grislabs/agentmeter";

budget("resolve-ticket", {
  perRun: 5.00,
  daily: 500,
  monthly: 10_000,
  onExceeded: "kill",  // "kill" | "alert" | "downgrade-model"
});
```

Budget checks cover **all cost types** — LLM, tools, and payments combined.

## MCP Middleware

Auto-track all MCP tool calls:

```typescript
import { createMCPMiddleware } from "@grislabs/agentmeter/mcp";

const mcpMeter = createMCPMiddleware(mcpClient, {
  defaultCostPerCall: 0.01,
  toolCosts: { "premium-search": 0.10 },
});

await trace("my-workflow", {}, async (ctx) => {
  const client = mcpMeter.wrap(ctx);
  await client.callTool({ name: "search", arguments: { q: "test" } });
});
```

## CLI

```bash
npx agentmeter status       # total spend, top workflows, daily trend
npx agentmeter workflows    # cost percentiles (p50/p95) per workflow
npx agentmeter customers    # cost per customer
```

## What's Tracked

| Cost type | How | Example |
|-----------|-----|---------|
| **LLM inference** | Automatic (via auto-instrumentation) | Anthropic, OpenAI, Google |
| **MCP tool calls** | `cost` param or MCP middleware | Paid MCP servers, API calls |
| **Agent payments** | `ctx.payment()` | Stripe MPP, x402, AP2 |
| **Compute** | `costType: "compute"` | E2B sandbox, GPU time |

All costs roll up into `totalCost` per trace, split into `llmCost`, `toolCost`, and `paymentCost`.

## Supported Providers

- **Anthropic** — all Claude models, with prompt caching support
- **OpenAI** — all GPT and reasoning models
- **Google** — all Gemini models (via manual extractors)
- Custom models via `setCustomPricing()`

## License

MIT