MCP · Lesson 100 of 120
Rate Limits and Abuse
Protect your server.
An agent stuck in a loop can call a tool hundreds of times a minute. So can an attacker. A rate limit caps how often a tool can run, and protects your server and your bills.

- Looping agents
- Attackers
- Cap the calls
A simple rate limit
We keep the times of recent calls. Calls older than ten seconds are dropped. If five calls remain, the tool refuses with a clear error. Then we call it seven times, and print whether each call failed. Run it. Five calls succeed, and the last two are refused.
rate_limit.pypython
import time
from collections import deque
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from tester import call
mcp = MCPServer("northwind")
recent = deque()
@mcp.tool()
def order_status(order_id: int) -> str:
"""Look up an order. Limited to 5 calls every 10 seconds."""
while recent and time.time() - recent[0] > 10:
recent.popleft()
if len(recent) >= 5:
raise ToolError("Rate limit reached, try again in a few seconds")
recent.append(time.time())
return "shipped"
print([call(mcp, "order_status", {"order_id": 1042}).is_error for _ in range(7)])Output
[False, False, False, False, False, True, True]
Also uses tester.py
import asyncio
from mcp import Client
def call(server, tool, args=None, **options):
async def go():
async with Client(server, **options) as client:
return await client.call_tool(tool, args or {})
return asyncio.run(go())
def tools(server):
async def go():
async with Client(server) as client:
return (await client.list_tools()).tools
return asyncio.run(go())In production
Limit per user, not just per server. Keep counts in a shared store, like Redis, when running many copies. Set limits at the gateway too. And alert when limits are hit often.
| key | value |
|---|---|
| Per | user |
| Shared store | many copies |
| Gateway | another layer |
| Alerts | often hit |
Summary
Rate limits stop runaway agents and abuse. Limit per user, in a shared store. Next, auditing.
Key takeaways- Window of calls
- ToolError
- Per user
Next up: Auditing — log every call