---
title: "Production guardrails for AI agents: spend caps, X-Max-Price & idempotency | FeedMCP"
description: "Three built-in guardrails in FeedMCP to prevent autonomous AI agents from overspending or double-billing on retries."
canonical: "https://feedmcp.com/guides/ai-agent-cost-control/"
---
<p class="crumbs"><a href="/guides/">Guides</a></p>

# Production guardrails for AI agents: spend caps, X-Max-Price & idempotency

When autonomous agents call paid APIs, two failure modes matter most: runaway pagination loops and duplicate charges on retry. FeedMCP enforces three hard guardrails at the API gateway.

## Endpoints used

| Endpoint | Path | Price |
| --- | --- | --- |
| [Douyin trending list](/apis/douyin/trends/list/) | `GET /v1/douyin/trends/list` | $0.002 |
| [TikTok video comments](/apis/tiktok/videos/comments/list/) | `GET /v1/tiktok/videos/comments/list` | $0.002 |
| [Xiaohongshu note comments](/apis/xiaohongshu/notes/comments/list/) | `GET /v1/xiaohongshu/notes/comments/list` | $0.02 |

## Steps

### 1. Layer 1: Per-agent API keys with hard spend caps

Issue one key per agent in the [console](/console/keys/) with a dollar cap; hitting it returns `key_spend_cap_reached` cleanly.

### 2. Layer 2: Per-call `X-Max-Price` / `max_price`

Refuses accidental calls to higher-priced endpoints before touching any upstream provider (`price_above_max`, free).

### 3. Layer 3: `Idempotency-Key` on retries

Retrying a timed-out request with the same key guarantees a single charge within 24 hours (`Idempotent-Replayed: true`).

## Complete code

```python
import os, time, uuid, requests

def safe_call(path: str, params: dict, max_price: str = "0.02", retries: int = 2):
    idem_key = str(uuid.uuid4())
    for attempt in range(retries + 1):
        r = requests.get(
            f"https://api.feedmcp.com{path}",
            params=params,
            headers={
                "Authorization": f"Bearer {os.environ['FEEDMCP_API_KEY']}",
                "X-Max-Price": max_price,
                "Idempotency-Key": idem_key,
            },
            timeout=30,
        )
        body = r.json()
        if body.get("code") == "ok":
            return body
        # 严格遵循服务端 retry 建议：no / after_fix 立即停，不要盲目死循环
        if body.get("retry") not in ("yes", "once", "same_key"):
            raise RuntimeError(f"Stop: {body.get('code')} - {body.get('message')}")
        time.sleep(body.get("retry_after_seconds") or (attempt + 1) * 2)
    raise RuntimeError("Retries exhausted")
```

## Cost estimate

Every error includes `charged: false` and an explicit `retry` enum so agents stay deterministic. See [Billing](/docs/billing/) and [Errors](/docs/errors/).

## Questions

### How much does it cost to run this guide?

Every error includes `charged: false` and an explicit `retry` enum so agents stay deterministic. See [Billing](/docs/billing/) and [Errors](/docs/errors/).

### Can I do this without writing code?

Yes. Install the [FeedMCP MCP server](/mcp/) in Claude, Cursor or Cherry Studio and run the same workflow in plain language.

## More guides

- [Python guide: search Xiaohongshu notes and export comments to CSV](/guides/xiaohongshu-api-python/)
- [Python guide: Douyin trending, video comments and Xingtu creator rates](/guides/douyin-api-python/)
- [Python guide: fetch WeChat Official Account articles, stats and comments](/guides/wechat-mp-articles-python/)
- [Extract video transcripts from YouTube, TikTok, Instagram, X & Meta Ads for LLMs](/guides/tiktok-youtube-transcripts-ai/)
- [Monitor competitor ads across Meta, Google, LinkedIn & TikTok in one script](/guides/competitor-ad-library-monitor/)
- [Mine product pain points across TikTok, Reddit, Xiaohongshu & Douyin with MCP](/guides/social-comment-pain-point-mining/)
- [Low-cost X (Twitter) monitoring with per-item pricing ($0.0003/item)](/guides/x-twitter-pay-per-item-guide/)

---

HTML version: https://feedmcp.com/guides/ai-agent-cost-control/
