# AI API Cost Firewall & Rate Limiter (Token Guard) (`neon_innovation_lab/mcp-rate-limiter`) Actor

Protect OpenAI, Anthropic, and Groq API budgets from runaway loops and token spend spikes. Sliding-window rate limiter and automatic circuit breaker.

- **URL**: https://apify.com/neon\_innovation\_lab/mcp-rate-limiter.md
- **Developed by:** [Neon Innovation Lab](https://apify.com/neon_innovation_lab) (community)
- **Categories:**
- **Stats:** 2 total users, 1 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$1.00 / 1,000 api request routeds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## MCP Rate Limiter & Circuit Breaker | AI Agent Token & Cost Firewall

[![Model Context Protocol](https://img.shields.io/badge/MCP-Rate_Limiter-blue.svg)](https://modelcontextprotocol.io)
[![Circuit Breaker](https://img.shields.io/badge/Circuit_Breaker-Sliding_Window-red.svg)](https://neoninnovationlab.com/tools/mcp-gateway-hub)
[![Cost Protection](https://img.shields.io/badge/FinOps-Cost_Spike_Guard-brightgreen.svg)](https://neoninnovationlab.com/upgrade)

Autonomous AI agents can be relentless. When an LLM model gets trapped in an infinite retry loop, hallucinates tool parameters, or triggers recursive subagents, it can hammer expensive third-party APIs (Stripe, Twilio, OpenAI, Snowflake) with thousands of calls per minute—racking up catastrophic bills and crashing mission-critical databases.

**MCP Rate Limiter & Circuit Breaker** operates as an inline protective firewall between your agent runtime (**Claude Desktop**, **Cursor**, **LangGraph**, **CrewAI**) and your **Model Context Protocol (MCP)** servers. It enforces sliding-window request throttling, token cost budgets, and automatic circuit breaking with zero code changes required on your downstream tools.

***

### 🛡️ Core Protection Features

1. **Sliding-Window Rate Limiting**: Enforces strict burst and sustained request thresholds per minute or hour.
2. **Automated Circuit Breaker Pattern**:
   - **CLOSED (Normal Operation)**: Requests pass through with sub-millisecond overhead.
   - **OPEN (Tripped)**: If error rates exceed threshold (e.g. 5 consecutive 5xx errors or rate limit breached), the gateway trips open, immediately returning a structured backoff message to the LLM without touching your backend.
   - **HALF-OPEN (Recovery)**: Automatically probes the downstream service after a configurable cooldown period before restoring full traffic.
3. **Runaway Loop Detection**: Detects duplicate tool arguments called in rapid succession and halts execution before credit card depletion occurs.
4. **Context-Window Overflow Protection**: Prevents 100KB+ database responses from filling the LLM context and triggering massive inference billing spikes.

***

### 🌍 Global Enterprise & Regional Compliance (GEO Targeting)

#### 🇺🇸 North America (Silicon Valley, New York, Seattle, Austin)

- **FinOps & Cloud Cost Governance**: Protects AI engineering budgets from unmonitored agent experiments and runaway loop billing spikes.
- **SLA & API Quota Protection**: Prevents internal developer agents from consuming shared external API quotas (e.g., Salesforce, Google Workspace, GitHub Enterprise).

#### 🇪🇺 Europe & 🇬🇧 United Kingdom (London, Berlin, Paris, Amsterdam)

- **System Stability & Reliability (EU AI Act Article 15)**: Meets mandatory technical resilience standards requiring automated failsafes against cascading software failures.
- **Fair Resource Allocation**: Ensures shared European multi-tenant microservices remain responsive under high concurrent agent usage.

#### 🌏 Asia-Pacific & 🇮🇳 India (Singapore, Tokyo, Sydney, Bengaluru, Hyderabad)

- **High-Concurrency Agent Clusters**: Regulates throughput for large offshore QA and developer teams running parallel agentic IDEs.
- **Bandwidth & Compute Optimization**: Smooths traffic spikes hitting latency-sensitive regional infrastructure.

***

### 🚀 Quick Setup & Integration

#### 1. Claude Desktop (`claude_desktop_config.json`)

Connect Claude to your rate-limited proxy endpoint:

```json
{
  "mcpServers": {
    "neon-rate-limited-mcp": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-sse",
        "https://<YOUR_APIFY_CONTAINER_URL>/sse"
      ]
    }
  }
}
```

#### 2. Cursor IDE Integration

In Cursor Settings -> **Features** -> **MCP Servers**:

1. Click **+ Add New MCP Server**.
2. Name: `Rate-Limited MCP Proxy`.
3. Type: `sse`.
4. URL: `https://<YOUR_APIFY_CONTAINER_URL>/sse`.

***

### ⚙️ Input Configuration

| Parameter | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `targetMcpUrl` | `String` | **Required** | The target downstream MCP server SSE URL to protect. |
| `rateLimitRequests` | `Integer` | `60` | Maximum allowed tool call requests within the sliding window. |
| `rateLimitWindowSeconds` | `Integer` | `60` | Duration of the rate limit window in seconds (default: 1 minute). |

***

### 📊 Live Enterprise Console & Zero-Trust Gateways

For automated PII Data Loss Prevention (DLP), threat firewalls, and W3C OpenTelemetry tracing, visit:
**<https://neoninnovationlab.com/tools/mcp-gateway-hub>**

# Actor input Schema

## `TARGET_MCP_URL` (type: `string`):

The upstream MCP server URL to protect.

## `RATE_LIMIT_REQUESTS` (type: `integer`):

Number of allowed requests.

## `RATE_LIMIT_WINDOW_SECONDS` (type: `integer`):

Time window for rate limiting.

## Actor input object example

```json
{
  "TARGET_MCP_URL": "https://your-upstream-mcp-server.com",
  "RATE_LIMIT_REQUESTS": 50,
  "RATE_LIMIT_WINDOW_SECONDS": 60
}
```

# Actor output Schema

## `proxy_endpoint` (type: `string`):

Connect your AI agent or MCP client to this protected proxy URL.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "TARGET_MCP_URL": "https://your-upstream-mcp-server.com"
};

// Run the Actor and wait for it to finish
const run = await client.actor("neon_innovation_lab/mcp-rate-limiter").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "TARGET_MCP_URL": "https://your-upstream-mcp-server.com" }

# Run the Actor and wait for it to finish
run = client.actor("neon_innovation_lab/mcp-rate-limiter").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "TARGET_MCP_URL": "https://your-upstream-mcp-server.com"
}' |
apify call neon_innovation_lab/mcp-rate-limiter --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,neon_innovation_lab/mcp-rate-limiter"
        }
    }
}

```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/Co21aDjtxSr6gOr1Q/builds/gIiKXTrl7JzP6BXEa/openapi.json
