Integrating External APIs through MCP
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
Most MCP servers you'll write are wrappers: the model needs something that lives behind someone else's HTTP API. The wrapper is where the real engineering happens. It hides the API key, turns a sprawling API into one or two clear tools, keeps results small and converts every failure into a message the model can use. This lesson builds one for a carrier's parcel-tracking API and tests every failure path without touching the network.
What you'll learn
- Designing a tool around the question, not the API.
- Keeping keys and URLs inside the server.
- Mapping timeouts, 404s, rate limits and server errors to useful messages.
- Testing an HTTP-backed server with a fake transport.
Before you start
Design the tool, not the API
A carrier's API might have forty endpoints. The model needs to answer "where is the parcel?". So the tool takes a tracking number and returns a status and the latest few events. That's all. It doesn't return the delivery address, which would be personal data the model has no reason to see, and it doesn't expose "create shipment" or "cancel parcel" at all. Whatever you don't expose can't be misused, whether by a confused model or a hostile email.
The server
"""An MCP server that wraps a (pretend) carrier tracking REST API. The model gets one clean tool;
the API key, the URL and every HTTP detail stay inside the server."""
import logging
import os
import re
import sys
from typing import TypedDict
import httpx
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp_types import ToolAnnotations
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
log = logging.getLogger("carrier")
TRACKING = re.compile(r"^[A-Z0-9]{6,30}$")
MAX_EVENTS = 5
mcp = MCPServer("carrier")
class Parcel(TypedDict):
tracking_number: str
status: str
events: list[str]
def make_client() -> httpx.Client:
"""Read configuration from the environment at call time. Never hard-code a key, never log it."""
base = os.environ.get("CARRIER_API_BASE", "https://api.carrier.example")
key = os.environ.get("CARRIER_API_KEY", "")
return httpx.Client(base_url=base, timeout=httpx.Timeout(8.0, connect=3.0),
headers={"Authorization": f"Bearer {key}", "User-Agent": "shop-mcp/1.0"})
@mcp.tool(title="Track a parcel", annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True))
def track_parcel(tracking_number: str) -> Parcel:
"""Get the current status and the latest few events for a parcel, by tracking number (letters and digits).
Use after lookup_order has given you a tracking number. Does not return the delivery address."""
number = tracking_number.strip().upper()
if not TRACKING.match(number):
raise ToolError("Tracking numbers are 6 to 30 letters and digits. Check the number and try again.")
try:
with make_client() as client:
resp = client.get(f"/v1/parcels/{number}")
except httpx.TimeoutException:
raise ToolError("The carrier service did not answer in time. Try again later or tell the customer tracking is unavailable.") from None
except httpx.HTTPError as e:
log.warning("carrier request failed: %s", type(e).__name__) # type only: URLs and headers can hold secrets
raise ToolError("The carrier service could not be reached. Tell the customer tracking is unavailable.") from None
if resp.status_code == 404:
raise ToolError(f"The carrier has no parcel {number}. Check the tracking number.")
if resp.status_code == 429:
wait = resp.headers.get("Retry-After", "a minute")
raise ToolError(f"The carrier is rate limiting requests. Try again after {wait} seconds, or say tracking is unavailable.")
if resp.status_code >= 500:
raise ToolError("The carrier service is having problems. Tell the customer tracking is unavailable for now.")
if resp.status_code != 200:
log.warning("carrier returned %s", resp.status_code)
raise ToolError("The carrier service refused the request. Tell the customer tracking is unavailable.")
try:
data = resp.json()
events = [f"{e['time']} {e['description']}" for e in data.get("events", [])][:MAX_EVENTS]
return {"tracking_number": number, "status": str(data["status"]), "events": events}
except (ValueError, KeyError, TypeError):
raise ToolError("The carrier sent an answer this tool could not read. Tell the customer tracking is unavailable.") from None
if __name__ == "__main__":
mcp.run(transport="stdio")
Walk through the decisions:
- Configuration from the environment, read at call time.
CARRIER_API_BASE and CARRIER_API_KEY never appear in code or tool output. The example hostname is a placeholder. We tested that the key from the environment ends up in the request header.
- Validate before you call out. The tracking number must be 6 to 30 letters and digits. A value like
../../etc/passwd is refused before any request is made, and a test checks that no request was sent.
- Timeouts are set. Eight seconds overall, three to connect. Without them, one slow carrier can hang the whole agent.
- Each failure gets its own message, written for the model: not found, rate limited (with the
Retry-After value when given), service trouble, refused, unreadable response. Each tells the model what to say to the customer.
- Network errors are logged by type only. A full exception can contain URLs and headers. The message to the model never mentions internal host names, and a test checks that.
- The response is parsed defensively. A 200 with HTML, or JSON missing
status, becomes a clear error rather than a crash.
- Results are trimmed. At most five events, and only the fields we chose, so the carrier adding new fields later can't leak more.
- The annotation says it reaches outside.
openWorldHint=True says it interacts with an external system; readOnlyHint=True says it doesn't change anything.
Testing without a network
The httpx library has a MockTransport that returns responses you define. Our tests swap the server's make_client function for one that uses it:
def serve(handler):
cs.make_client = lambda: httpx.Client(base_url="https://api.test", transport=httpx.MockTransport(handler))
@pytest.mark.parametrize("response,needle", [
(httpx.Response(404), "no parcel"),
(httpx.Response(429, headers={"Retry-After": "30"}), "after 30 seconds"),
(httpx.Response(503), "having problems"),
(httpx.Response(403), "refused"),
(httpx.Response(200, text="<html>not json</html>"), "could not read"),
(httpx.Response(200, json={"events": []}), "could not read"),
])
def test_http_failures_become_helpful_tool_errors(response, needle):
serve(lambda req: response)
r = call({"tracking_number": "JD0146"})
assert r.is_error and needle in r.content[0].text
Other tests cover a successful call (with nine events trimmed to five and a secret field not reaching the result), a read timeout, a connection error whose internal host name must not appear in the message, and the bad-number case above. Everything passes without a network connection or a real key.
Using more than one server
An agent can connect to several servers at once. The shop server returns the tracking number from lookup_order, then the model calls track_parcel on the carrier server with it. The bridge's server prefix (shop__, carrier__) keeps names unique. Each server has its own allow list in your policy, and neither server knows the other exists.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A customer asks where a parcel is. The agent calls the shop server for the order, gets a tracking number, then calls the carrier server. One afternoon the carrier's service is down. The wrapper returns "having problems; tell the customer tracking is unavailable for now", the agent writes an honest reply that the status can't be checked right now, and a person can follow up. Without the wrapper, the model would have seen an unhandled error or a raw HTML error page, and may have guessed.
Mistakes to avoid
- Exposing one tool per endpoint instead of one per question.
- No timeouts on outbound calls.
- Putting the API key or full URL in an error message or a log line.
- Returning the whole upstream response.
- Retrying blindly inside the tool. Report a rate limit and let the caller decide.
Security notes
Everything the model passes becomes part of a request to a third party, so validate it. Never let a model-supplied value choose the host or the path beyond a validated identifier. That's how a tool turns into a server-side request forgery hole. Keep the key scoped to read-only tracking if the carrier offers that, and rotate it like any other secret.
Cost and speed
Each call waits on someone else's service. Set short timeouts, keep results small, and consider a short cache keyed on the tracking number when the same parcel is checked repeatedly. Check the carrier's rate limits and pricing, which this lesson doesn't assume.
Key takeaways
- Wrap the question, not the API, and expose as little as possible.
- Keep keys and URLs in the server; set timeouts; validate before calling out.
- Give every failure a message that tells the model what to do.
- Test every path with a fake transport.
Lesson recap: design the tool around the question and give every failure a useful message.
Quick quiz
- Why return only five events and chosen fields?
- Why validate the tracking number before the request?
- Why log only the exception type for a network error?
- What should a 429 response turn into?
- How do the tests avoid a real network?
Answers and explanations
- To keep results small and prevent extra upstream fields, such as an address, from reaching the model.
- To stop a crafted value, such as a path traversal string, from becoming part of an outbound request.
- Full exceptions can contain URLs, headers or hostnames that shouldn't appear in logs or model-visible messages.
- A message saying the carrier is rate limiting, with the retry time if it was given, and a suggestion to say tracking is unavailable.
- They replace the HTTP client with one that uses
httpx.MockTransport and returns scripted responses.
Official references and further reading
Related tutorials