An agent over MCP
An assistant is asked where something is, or how long the drive takes. It should answer from data it can cite, say so when the question names more than one place, and keep working when it runs into its key's rate. This page is two complete programs that do that with the oslew MCP server: one on Claude, one on the OpenAI Responses API.
The approach
- Connect to
https://api.oslew.com/mcpwith the key as a bearer token, and read the server's instructions frominitialize. They say how to read an answer, so they belong in the model's system prompt. - List the tools.
tools/listreturns only what the key's plan includes, so the model is never offered a tool that would be refused. - Check each geocode answer before the model acts on it. A tie, an
askor arefusedecision, or a place name that was not found means the agent asks the user rather than answering. - Wait out a 429. It means the agent is going faster than the key's rate, not that anything ran out.
Retry-Aftersays how long.
What a tool answers
A tool's structuredContent is the answer of the HTTP route of the same name. Forgeocode, that is this:
HTTP/1.1 200 OK
content-type: application/json
ratelimit-limit: 100
ratelimit-remaining: 299
ratelimit-reset: 1
{
"query": "Museo Soumaya",
"name": "Museo Soumaya",
"context": null,
"parse": {
"name": "Museo Soumaya",
"method": "passthrough"
},
"context_resolution": null,
"near": null,
"results": [
{
"doc": 348329,
"name": "Museo Soumaya",
"lat": 19.44062110346353,
"lon": -99.20465953606559,
"bbox": [
19.440487037931074,
19.440755168997644,
-99.20478863854248,
-99.20453043361198
],
"precision": "poi",
"precision_m": 6.756173533775122,
"hierarchy": {
"locality": "Miguel Hidalgo",
"region": "CMX",
"country": "MX",
"category": "museum",
"postcode": null,
"street": null
},
"normalized": {
"locality": "Miguel Hidalgo",
"region": "CMX",
"country": "MX",
"formatted": "Museo Soumaya, Miguel Hidalgo, CMX, MX"
},
"components": {
"name": "exact",
"house_number": "missing",
"street": "missing",
"locality": "missing",
"region": "missing",
"postcode": "missing",
"country": "missing"
},
"confidence": 0.5,
"why": {
"tokens": [
"museo",
"soumaya"
],
"matched": 2,
"extra": 0,
"mode": "all",
"tied": false,
"prominence": 5,
"rerank": 87
},
"provenance": {
"name": "overture-places",
"release": "2026-08-19.0",
"license": "CDLA-Permissive-2.0"
},
"attributes": {
"rating": null,
"reviews": 0,
"price": null,
"hours": [
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
]
],
"photo": "https://commons.wikimedia.org/wiki/Special:FilePath/Museo_Soumaya%2C_Ciudad_de_M%C3%A9xico%2C_M%C3%A9xico%2C_2015-07-18%2C_DD_12.JPG",
"provenance": {
"name": "wikidata",
"release": "2026-11-23",
"license": "CC0; images under their Commons licences"
}
}
},
{
"doc": 318314,
"name": "Museo Soumaya",
"lat": 19.33886538628843,
"lon": -99.19254435060174,
"bbox": [
19.338731342470982,
19.33899943010779,
-99.19267344656319,
-99.19241525466357
],
"precision": "poi",
"precision_m": 6.756173533775122,
"hierarchy": {
"locality": "Álvaro Obregón",
"region": "CMX",
"country": "MX",
"category": "museum",
"postcode": null,
"street": null
},
"normalized": {
"locality": "Álvaro Obregón",
"region": "CMX",
"country": "MX",
"formatted": "Museo Soumaya, Álvaro Obregón, CMX, MX"
},
"components": {
"name": "exact",
"house_number": "missing",
"street": "missing",
"locality": "missing",
"region": "missing",
"postcode": "missing",
"country": "missing"
},
"confidence": 0.5,
"why": {
"tokens": [
"museo",
"soumaya"
],
"matched": 2,
"extra": 0,
"mode": "all",
"tied": false,
"prominence": 0,
"rerank": 85
},
"provenance": {
"name": "overture-places",
"release": "2026-08-19.0",
"license": "CDLA-Permissive-2.0"
},
"attributes": null
},
{
"doc": 385507,
"name": "Museo Soumaya - Auguste Rondin",
"lat": 19.53106621771892,
"lon": -99.23296424906052,
"bbox": [
19.530932130179863,
19.531200305259414,
-99.23309336673412,
-99.23283513141011
],
"precision": "poi",
"precision_m": 6.756173533775122,
"hierarchy": {
"locality": "Tlalnepantla de Baz",
"region": null,
"country": "MX",
"category": "museum",
"postcode": null,
"street": null
},
"normalized": {
"locality": "Tlalnepantla de Baz",
"country": "MX",
"formatted": "Museo Soumaya - Auguste Rondin, Tlalnepantla de Baz, MX"
},
"components": {
"name": "exact",
"house_number": "missing",
"street": "missing",
"locality": "missing",
"region": "missing",
"postcode": "missing",
"country": "missing"
},
"confidence": 0.5,
"why": {
"tokens": [
"museo",
"soumaya"
],
"matched": 2,
"extra": 2,
"mode": "all",
"tied": false,
"prominence": 0,
"rerank": 55
},
"provenance": {
"name": "overture-places",
"release": "2026-08-19.0",
"license": "CDLA-Permissive-2.0"
},
"attributes": null
}
],
"mode": "all",
"tied_at_top": 1,
"tie_probe": 32,
"interpolated": false,
"decision": {
"action": "refuse",
"margin": 0.03733337
},
"epoch": 30,
"release": "2026-08-19.0",
"examined": 420,
"postings": 424,
"segments": 2,
"store_requests": 0,
"store_bytes": 0,
"took_us": 12238
}A real response, captured from the service at commit b8f4bde-dirty. Timing fields such as took_us differ on every call.
tied_at_top is 1: no other result shares the top score. That is not enough to act on, anddecision.action says so: it is refuse, because the Museo Soumaya in Miguel Hidalgo and the one in Álvaro Obregón are within 0.04 of each other on the service's margin score, under the 0.12 it takes to pick one. There are two buildings of that name, and the question did not say which. Compare a brand with branches everywhere:
HTTP/1.1 200 OK
content-type: application/json
ratelimit-limit: 100
ratelimit-remaining: 299
ratelimit-reset: 1
{
"query": "OXXO",
"name": "OXXO",
"context": null,
"parse": {
"name": "OXXO",
"method": "passthrough"
},
"context_resolution": null,
"near": null,
"results": [
{
"doc": 19524,
"name": "OXXO",
"lat": 20.612046892212046,
"lon": -105.23387968256127,
"bbox": [
20.611911606339586,
20.612182178088325,
-105.23401122598554,
-105.2337481391495
],
"precision": "poi",
"precision_m": 6.756173533775122,
"hierarchy": {
"locality": "Puerto Vallarta",
"region": null,
"country": "MX",
"category": "convenience_store",
"postcode": null,
"street": null
},
"normalized": {
"locality": "Puerto Vallarta",
"country": "MX",
"formatted": "OXXO, Puerto Vallarta, MX"
},
"components": {
"name": "exact",
"house_number": "missing",
"street": "missing",
"locality": "missing",
"region": "missing",
"postcode": "missing",
"country": "missing"
},
"confidence": 0.99148935,
"why": {
"tokens": [
"oxxo"
],
"matched": 1,
"extra": 0,
"mode": "all",
"tied": true,
"prominence": 0,
"rerank": 75
},
"provenance": {
"name": "overture-places",
"release": "2026-08-19.0",
"license": "CDLA-Permissive-2.0"
},
"attributes": null
},
{
"doc": 20122,
"name": "OXXO",
"lat": 20.610405973859322,
"lon": -105.23397110804532,
"bbox": [
20.61027068832683,
20.610541259395642,
-105.23410265149454,
-105.23383956460859
],
"precision": "poi",
"precision_m": 6.756173533775122,
"hierarchy": {
"locality": "Puerto Vallarta",
"region": null,
"country": "MX",
"category": "convenience_store",
"postcode": null,
"street": null
},
"normalized": {
"locality": "Puerto Vallarta",
"country": "MX",
"formatted": "OXXO, Puerto Vallarta, MX"
},
"components": {
"name": "exact",
"house_number": "missing",
"street": "missing",
"locality": "missing",
"region": "missing",
"postcode": "missing",
"country": "missing"
},
"confidence": 0.99148935,
"why": {
"tokens": [
"oxxo"
],
"matched": 1,
"extra": 0,
"mode": "all",
"tied": true,
"prominence": 0,
"rerank": 75
},
"provenance": {
"name": "overture-places",
"release": "2026-08-19.0",
"license": "CDLA-Permissive-2.0"
},
"attributes": null
},
{
"doc": 20812,
"name": "OXXO",
"lat": 20.62072596660037,
"lon": -105.22510306857126,
"bbox": [
20.620590680172317,
20.620861253032217,
-105.2252346095983,
-105.22497152755672
],
"precision": "poi",
"precision_m": 6.756173533775122,
"hierarchy": {
"locality": "Puerto Vallarta",
"region": null,
"country": "MX",
"category": "convenience_store",
"postcode": null,
"street": null
},
"normalized": {
"locality": "Puerto Vallarta",
"country": "MX",
"formatted": "OXXO, Puerto Vallarta, MX"
},
"components": {
"name": "exact",
"house_number": "missing",
"street": "missing",
"locality": "missing",
"region": "missing",
"postcode": "missing",
"country": "missing"
},
"confidence": 0.99148935,
"why": {
"tokens": [
"oxxo"
],
"matched": 1,
"extra": 0,
"mode": "all",
"tied": true,
"prominence": 0,
"rerank": 75
},
"provenance": {
"name": "overture-places",
"release": "2026-08-19.0",
"license": "CDLA-Permissive-2.0"
},
"attributes": null
}
],
"mode": "all",
"tied_at_top": 16,
"tie_probe": 32,
"interpolated": false,
"decision": {
"action": "refuse",
"margin": 0,
"disambiguation": {
"tied": 16,
"options": [
{
"rank": 1,
"label": "OXXO, Puerto Vallarta, MX",
"country": "MX",
"locality": "Puerto Vallarta"
},
{
"rank": 2,
"label": "OXXO, Puerto Vallarta, MX",
"country": "MX",
"locality": "Puerto Vallarta"
},
{
"rank": 3,
"label": "OXXO, Puerto Vallarta, MX",
"country": "MX",
"locality": "Puerto Vallarta"
},
{
"rank": 4,
"label": "OXXO, Puerto Vallarta, JAL, MX",
"country": "MX",
"locality": "Puerto Vallarta"
},
{
"rank": 5,
"label": "OXXO, Puerto Vallarta, MX",
"country": "MX",
"locality": "Puerto Vallarta"
},
{
"rank": 6,
"label": "Oxxo, Boca de Tomatlán, JAL, MX",
"country": "MX",
"locality": "Boca de Tomatlán"
},
{
"rank": 7,
"label": "oxxo, Pérula, JAL, MX",
"country": "MX",
"locality": "Pérula"
},
{
"rank": 8,
"label": "OXXO, Tomatlán, MX",
"country": "MX",
"locality": "Tomatlán"
}
]
}
},
"epoch": 30,
"release": "2026-08-19.0",
"examined": 98,
"postings": 1736,
"segments": 2,
"store_requests": 0,
"store_bytes": 0,
"took_us": 805
}A real response, captured from the service at commit b8f4bde-dirty. Timing fields such as took_us differ on every call.
tied_at_top is 16 of the 32 candidates the search kept (tie_probe). The first result is one of sixteen equally good answers, and an agent that reports it as the OXXO has guessed. Both programs below treat this as a question for the user. Calibrated confidence does not settle it: each of the sixteen is a confident match to the name, which is exactly the problem.
Both answers carry the same decision.action, refuse, for two different reasons: the top results tie, or the best is too close to the next. It means do not pick one, not that nothing matched. When results tie, decision.disambiguation lists the candidates to put to the user; when they are merely close, there is no list, and the results themselves are the candidates. ask means a detail is missing, named in ask_for; only act means go ahead.
Going faster than the key's rate is answered before any JSON-RPC is read, with the same body and headers as an HTTP route:
HTTP/1.1 429 Too Many Requests
content-type: application/json
ratelimit-limit: 2
ratelimit-remaining: 0
ratelimit-reset: 1
retry-after: 1
{
"error": "address is limited to 2 requests a second, burst 2; try again in 1 s. There is no monthly quota."
}A real response, captured from the service at commit b8f4bde-dirty. Timing fields such as took_us differ on every call.
Claude
Your process holds the MCP session and runs the tools, so it decides what a 429 or a tie means. It speaks Streamable HTTP with httpx, hands Claude the plan's tools, puts the server's instructions in the system prompt, and writes a note in front of any geocode answer that must not be acted on yet, so the model reads the rule next to the evidence. When the agent asks which place you meant, the program waits for your answer.
"""A Claude agent that answers location questions with oslew's MCP tools.
pip install anthropic httpx
export ANTHROPIC_API_KEY=... GEO_API_KEY=...
python agent_claude.py "How long is the drive from Museo Soumaya to the Zocalo?"
Your process holds the MCP session, so it decides what happens on a 429 and
when an answer is too uncertain to act on. Claude sees the server's own
instructions, the tools the key's plan includes, and every tool answer.
"""
import json
import os
import sys
import time
import anthropic
import httpx
MCP_URL = os.environ.get("OSLEW_MCP_URL", "https://api.oslew.com/mcp")
MODEL = "claude-opus-5-5"
class OslewMCP:
"""The MCP messages an agent needs, over Streamable HTTP, with 429 handled."""
def __init__(self, url: str, key: str, max_wait_s: float = 30.0):
self.url = url
self.max_wait_s = max_wait_s
self.session_id: str | None = None
self.next_id = 0
self.http = httpx.Client(
timeout=30.0,
headers={
"Authorization": f"Bearer {key}",
"Accept": "application/json, text/event-stream",
},
)
init = self.request(
"initialize",
{
"protocolVersion": "2025-03-26",
"capabilities": {},
"clientInfo": {"name": "oslew-agent-example", "version": "1"},
},
)
# How to read an answer, in the server's words: ties, fallbacks, licences.
self.instructions: str = init.get("instructions", "")
self.post({"jsonrpc": "2.0", "method": "notifications/initialized"})
def post(self, message: dict) -> httpx.Response:
"""POST one JSON-RPC message, waiting out a 429 as long as Retry-After says."""
waited = 0.0
while True:
headers = {"mcp-session-id": self.session_id} if self.session_id else {}
response = self.http.post(self.url, json=message, headers=headers)
if response.status_code != 429:
break
# Going faster than the key's rate. Nothing was used up; the bucket
# refills, and the service says when there will be room.
wait = float(response.headers.get("retry-after", "1"))
if waited + wait > self.max_wait_s:
response.raise_for_status()
time.sleep(wait)
waited += wait
response.raise_for_status()
self.session_id = response.headers.get("mcp-session-id", self.session_id)
return response
def request(self, method: str, params: dict) -> dict:
self.next_id += 1
response = self.post({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params})
message = read_message(response, self.next_id)
if "error" in message:
# A bad argument, a layer that is not loaded, or a tool outside the
# plan: the service's own sentence, for the agent to relay.
raise ToolRefused(message["error"].get("message", "refused"))
return message["result"]
def tools(self) -> list[dict]:
"""The plan's tools, as Claude tool definitions."""
listed = self.request("tools/list", {})["tools"]
return [
{"name": t["name"], "description": t.get("description", ""), "input_schema": t["inputSchema"]}
for t in listed
]
def call(self, name: str, arguments: dict) -> dict:
return self.request("tools/call", {"name": name, "arguments": arguments})
class ToolRefused(Exception):
pass
def read_message(response: httpx.Response, want_id: int) -> dict:
"""A JSON-RPC answer arrives as JSON or as a server-sent event stream."""
if response.headers.get("content-type", "").startswith("text/event-stream"):
# Events are separated by a blank line; an event's data may span several
# `data:` lines, and the stream opens with an empty priming event.
for event in response.text.replace("\r\n", "\n").split("\n\n"):
data = "\n".join(
line[5:].lstrip() for line in event.split("\n") if line.startswith("data:")
).strip()
if not data:
continue
message = json.loads(data)
if message.get("id") == want_id:
return message
raise RuntimeError("the event stream carried no answer")
return response.json()
def caution(answer: dict) -> str | None:
"""Why a geocode answer must not be acted on yet, or None if it can be."""
decision = answer.get("decision") or {}
tied = answer.get("tied_at_top") or 0
# `refuse` means "do not pick one": the top results tie, or the best is too
# close to the next. The candidates are in `disambiguation`, for the user.
if tied > 1 or decision.get("action") == "refuse":
options = (decision.get("disambiguation") or {}).get("options") or []
labels = "; ".join(o.get("label", "") for o in options[:5])
if not labels:
# Refused without a tie (two close matches, such as two museums of one
# name): there is no disambiguation list, so name the top results.
labels = "; ".join(
", ".join(x for x in (r.get("name"), (r.get("hierarchy") or {}).get("locality")) if x)
for r in (answer.get("results") or [])[:3]
)
why = f"{tied} places tie at the top" if tied > 1 else "the best match is too close to the next one"
return (
f"{why}, so the query does not determine one place. Do not choose one. "
"Ask the user which they mean, or for a street, district or postcode"
+ (f". Candidates: {labels}" if labels else "")
+ "."
)
if decision.get("action") == "ask":
asks = ", ".join(decision.get("ask_for") or []) or "more detail"
return f"decision.action is ask: ask the user for {asks} before using a result."
if (answer.get("context_resolution") or {}).get("fallback"):
return "context_resolution.fallback is true: the place the user named was not found, so say so or ask."
return None
def run_tool(mcp: OslewMCP, name: str, arguments: dict) -> dict:
"""One tool_use, answered as a tool_result block."""
try:
result = mcp.call(name, arguments)
except ToolRefused as refused:
return {"type": "tool_result", "content": str(refused), "is_error": True}
answer = result.get("structuredContent") or {}
text = json.dumps(answer) if answer else "".join(c.get("text", "") for c in result.get("content", []))
note = caution(answer) if name == "geocode" else None
if note:
# Put the rule next to the evidence, so the model reads both together.
text = f"oslew: {note}\n{text}"
return {"type": "tool_result", "content": text, "is_error": bool(result.get("isError"))}
def main() -> None:
question = " ".join(sys.argv[1:]) or "Where is OXXO?"
mcp = OslewMCP(MCP_URL, os.environ["GEO_API_KEY"])
tools = mcp.tools()
system = (
"You answer questions about places and travel using the oslew tools. "
"When a tool answer starts with 'oslew:', follow that note before anything else. "
"Never present one of several tied results as the answer.\n\n"
"What the oslew server says about its tools:\n" + mcp.instructions
)
client = anthropic.Anthropic()
messages: list = [{"role": "user", "content": question}]
while True:
try:
response = client.beta.messages.create(
model=MODEL,
max_tokens=16000,
thinking={"type": "adaptive"},
output_config={"effort": "medium"},
# On a policy decline the API re-runs the turn on a fallback
# model inside the same call, rather than stopping.
betas=["server-side-fallback-2026-07-01"],
fallbacks="default",
system=system,
tools=tools,
messages=messages,
)
except anthropic.RateLimitError:
time.sleep(5)
continue
# Keep every block, thinking included, so the next turn continues this one.
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason == "refusal":
print("The model declined this request.")
return
if response.stop_reason == "tool_use":
results = []
for block in response.content:
if block.type == "tool_use":
results.append({"tool_use_id": block.id, **run_tool(mcp, block.name, block.input)})
messages.append({"role": "user", "content": results})
continue
print("".join(b.text for b in response.content if b.type == "text"))
if response.stop_reason == "max_tokens" or not sys.stdin.isatty():
return
# The agent may have asked which place you meant: answer, or press
# return to stop.
reply = input("\nyou> ").strip()
if not reply:
return
messages.append({"role": "user", "content": reply})
if __name__ == "__main__":
main()It uses the Anthropic Python SDK's beta Messages endpoint for fallbacks, which re-runs a declined turn on a fallback model inside the same call. Set OSLEW_MCP_URL to point it at your own deployment.
OpenAI
The Responses API's mcp tool connects from OpenAI's servers, not from yours, so the endpoint has to be reachable from the internet and the key goes in the tool's headers. The model reads the tool answers itself, so the rules about ties go in its instructions.
"""An OpenAI Responses API agent with oslew as a remote MCP server.
pip install "openai>=3.55"
export OPENAI_API_KEY=... GEO_API_KEY=... OPENAI_MODEL=<a model with remote MCP tools>
python agent_openai.py "Where is OXXO?"
Written against openai 3.55.0. OpenAI's servers call the MCP endpoint, not
your process, so api.oslew.com has to be reachable from the internet and the
key travels in the tool's headers. A 429 comes back as an mcp_call error
without the Retry-After value, so this waits a fixed second and asks again.
"""
import json
import os
import sys
import time
from openai import OpenAI
MCP_URL = os.environ.get("OSLEW_MCP_URL", "https://api.oslew.com/mcp")
MODEL = os.environ["OPENAI_MODEL"]
TOOLS = [
{
"type": "mcp",
"server_label": "oslew",
"server_url": MCP_URL,
"headers": {"Authorization": f"Bearer {os.environ['GEO_API_KEY']}"},
# Every oslew tool is read-only, so there is nothing to approve.
"require_approval": "never",
}
]
INSTRUCTIONS = (
"You answer questions about places and travel using the oslew tools. "
"If a geocode answer has tied_at_top greater than 1, or decision.action is refuse, the query does not "
"determine one place: do not choose one; show the user the candidates in decision.disambiguation and ask "
"which they mean. If decision.action is ask, ask for what ask_for names. "
"If context_resolution.fallback is true, say the place the user named was not found."
)
def rate_limited(response) -> bool:
return any(
item.type == "mcp_call" and item.error is not None and getattr(item.error, "code", None) == 429
for item in response.output
)
def ties(response) -> list[int]:
"""tied_at_top of every geocode call in this turn, for logging and tests."""
found = []
for item in response.output:
if item.type == "mcp_call" and item.name == "geocode" and item.output:
try:
found.append(json.loads(item.output).get("tied_at_top", 0))
except json.JSONDecodeError:
pass
return found
def ask(client: OpenAI, text: str, previous: str | None):
for _ in range(5):
response = client.responses.create(
model=MODEL,
instructions=INSTRUCTIONS,
input=text,
tools=TOOLS,
previous_response_id=previous,
)
if not rate_limited(response):
return response
time.sleep(1)
return response
def main() -> None:
client = OpenAI()
text = " ".join(sys.argv[1:]) or "Where is OXXO?"
previous = None
while True:
response = ask(client, text, previous)
if any(t > 1 for t in ties(response)):
print("(the geocoder returned a tie; the model has been told to ask)")
print(response.output_text)
previous = response.id
if not sys.stdin.isatty():
return
text = input("\nyou> ").strip()
if not text:
return
if __name__ == "__main__":
main()What to watch out for
- Every MCP request takes a token from the Address bucket,
initializeandtools/listincluded, and aroutecall draws on it too. On the free plan, at one request a second, connecting takes most of the burst. See AI agents over MCP. - Give the agent its own key. Every tool is read-only, so the worst a misbehaving agent can do is spend its key's rate, and revoking that key touches nothing else. Seeauthentication.
- Durations are free-flow unless a traffic feed is applied and the call passes
traffic: "live"; each answer'senginesays which. Seelive traffic. - Results carry their licence. An agent that stores what it was told should keep
provenancewith it. See data and licensing.