> ## Documentation Index
> Fetch the complete documentation index at: https://lava.so/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Manage AI Spend & API Keys

> Create scoped API keys with spend limits for agents and developer tools

Spend keys are scoped API keys that work as drop-in replacements for provider API keys. Use them to give agents, team members, or developer tools access to AI models with built-in spend limits, model restrictions, and rate controls.

<Info>
  **Start here:** [Authenticate an Agent](/agents/authenticate) explains when to use MCP session auth versus the SDK login flow.
</Info>

## MCP flow

The Lava MCP server auto-manages a spend key for gateway access. When you call `login`, a spend key is provisioned automatically for the MCP session.

* `login` to authenticate — auto-provisions a spend key for `prompt` and `call` access
* `prompt` or `call` to route traffic, spending against the auto-provisioned key
* `search` to discover available providers before routing

To create spend keys with custom limits, model restrictions, or expiration — use the SDK code below.

## SDK flow

If you are writing code directly, use the examples below with `@lavapayments/nodejs`.

## How Spend Keys Work

A spend key is an OpenAI-compatible API key that routes through Lava's gateway. Any tool that accepts an OpenAI API key can use a Lava spend key instead. You control which models are allowed, how much can be spent, and how fast requests can be made.

## Create a Spend Key

```typescript theme={null}
import { Lava } from '@lavapayments/nodejs';

const lava = new Lava(process.env.LAVA_SECRET_KEY);

const spendKey = await lava.spendKeys.create({
  name: 'Agent - Production',
  allowed_providers: ['openai', 'anthropic'],
  allowed_models: ['gpt-4o-mini', 'claude-sonnet-4-20250514'],
  spend_limit: {
    amount: '50.00',
    cycle: 'monthly'
  },
  rate_limit: {
    rpm: 60
  }
});

// Save this immediately - the full key is only shown once
console.log('Spend key:', spendKey.key);
console.log('Key ID:', spendKey.spend_key_id);
```

<Warning>
  The full key value is only returned when you create or rotate a spend key. Store it securely right away.
</Warning>

### Spend key options

| Parameter           | Options                                    | Description                                                 |
| ------------------- | ------------------------------------------ | ----------------------------------------------------------- |
| `allowed_providers` | Array of provider names, or `null` for all | Restrict which providers can be used                        |
| `allowed_models`    | Array of model IDs, or `null` for all      | Restrict which models can be used                           |
| `request_shape`     | `openai`, `anthropic`                      | Request format (default: `openai`)                          |
| `spend_limit`       | `{ amount, cycle }`                        | Max spend per cycle (`daily`, `weekly`, `monthly`, `total`) |
| `request_limit`     | `{ count, cycle }`                         | Max requests per cycle                                      |
| `rate_limit`        | `{ rpm, burst? }`                          | Requests per minute, with optional burst allowance          |
| `expires_at`        | ISO 8601 date, or `null`                   | Auto-expire the key after a date                            |
| `status`            | `active`, `paused`                         | Pause a key without revoking it                             |

## Use a Spend Key

Spend keys work anywhere an OpenAI API key is accepted. Point the tool at Lava's base URL and use the spend key as the API key.

### With the OpenAI SDK

```typescript theme={null}
import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: spendKey.key,
  baseURL: 'https://api.lava.so/v1'
});

const completion = await openai.chat.completions.create({
  model: 'gpt-4o-mini',
  messages: [{ role: 'user', content: 'Hello!' }]
});
```

### With the Anthropic SDK

For Anthropic-shaped requests, create the key with `request_shape: 'anthropic'`:

```typescript theme={null}
const anthropicKey = await lava.spendKeys.create({
  name: 'Agent - Anthropic',
  request_shape: 'anthropic',
  allowed_providers: ['anthropic'],
  spend_limit: { amount: '100.00', cycle: 'monthly' }
});
```

```typescript theme={null}
import Anthropic from '@anthropic-ai/sdk';

const anthropic = new Anthropic({
  apiKey: anthropicKey.key,
  baseURL: 'https://api.lava.so'  // No /v1 — Anthropic SDK appends it
});

const message = await anthropic.messages.create({
  model: 'claude-sonnet-4-20250514',
  max_tokens: 1024,
  messages: [{ role: 'user', content: 'Hello!' }]
});
```

## Update a Spend Key

Change restrictions on an existing key without rotating the key itself:

```typescript theme={null}
await lava.spendKeys.update(spendKey.spend_key_id, {
  allowed_models: ['gpt-4o-mini'],  // Restrict to a cheaper model
  spend_limit: { amount: '100.00', cycle: 'monthly' }  // Increase limit
});
```

## Rotate a Key

Generate a new key value for the same spend key. The old key stops working immediately:

```typescript theme={null}
const rotated = await lava.spendKeys.rotate(spendKey.spend_key_id);
console.log('New key:', rotated.key);  // Full key, shown once
```

## Monitor Spend

Check current spend and usage for a key:

```typescript theme={null}
const keys = await lava.spendKeys.list();

for (const key of keys.data) {
  console.log(`${key.name}: $${key.current_spend} spent (limit: $${key.spend_limit?.amount ?? 'none'})`);
  console.log(`  ${key.current_requests} requests, last used: ${key.last_used_at ?? 'never'}`);
}
```

## Revoke a Key

Permanently disable a spend key:

```typescript theme={null}
await lava.spendKeys.revoke(spendKey.spend_key_id);
```

## What's Next?

<CardGroup cols={2}>
  <Card title="Spend Key Setup Guides" icon="wrench" href="/guides/spend-key-setup-guides">
    Step-by-step setup for Cursor, Claude Code, Vercel AI SDK, and more
  </Card>

  <Card title="AI Spend Overview" icon="chart-line" href="/guides/ai-spend-keys">
    How AI Spend works, dashboard features, and team management
  </Card>

  <Card title="Route Traffic" icon="route" href="/agents/route-traffic">
    Forward requests through the gateway with usage tracking
  </Card>

  <Card title="SDK Reference" icon="code" href="/sdk/nodejs">
    Full spend key API documentation
  </Card>
</CardGroup>
