AI Agents10 min read

Connect an AI Agent to APIs: Tools, Auth, Retries and MCP

How to wire an LLM agent to real APIs: JSON Schema tool definitions, the tool-call loop, secrets, pagination, rate limits, safe retries and MCP servers.

By AI Agents DirectoryLast checked
Rows of server racks with network cables in a data centre

An agent becomes useful when it can read and change data in other systems: open a ticket, look up an order, list the issues in a repository. The model never makes those HTTP calls itself. It returns a structured request naming a tool and its arguments, your code runs the request, and the result goes back to the model. This guide covers that loop end to end, plus the parts that usually break in production: credentials, pagination, rate limits, bad arguments and duplicate writes. The examples use the Claude API tool use docs, the OpenAI function calling guide and the Model Context Protocol specification.

How the tool-call loop works

Both major APIs follow the same shape. OpenAI’s guide breaks it into five steps: send tools with the prompt, receive a tool call, run your code, send the output back, and get either a final answer or more tool calls. Anthropic describes the same round trip with different field names.

ConceptClaude Messages APIOpenAI Responses API
Tool definitionname, description, input_schemafunction with name, description, parameters
Signal that tools are neededstop_reason: "tool_use"function_call items in the output
The calltool_use block with id, name, inputcall_id, name, JSON-encoded arguments
Your replytool_result block with tool_use_idfunction_call_output item with call_id
Signalling a failureis_error: true on the resultPut the error in the output string

Two Claude formatting rules catch people out. The tool results must sit in the user message that comes straight after the assistant’s tool call, and inside that message every tool_result block has to come before any text. Breaking either rule returns an error. Also expect more than one call per turn: OpenAI’s guide says a response can hold zero, one or several calls, so loop over all of them.

Define tools with JSON Schema

Every tool’s inputs are described with a JSON Schema object. The useful keywords are few: type and properties for the shape, required for mandatory fields, enum to pin a value to a fixed list, and additionalProperties: false to reject keys you did not declare (the JSON Schema reference notes that extra properties are allowed by default).

The description matters more than the schema. Anthropic calls detailed descriptions “by far the most important factor in tool performance” and suggests at least three or four sentences per tool, covering what it does, when to use it and when not to, what each parameter means, and what it leaves out. Other advice from both vendors that pays off with real APIs:

  • Prefix tool names with the service, such as github_list_issues or slack_send_message, so the model can tell similar tools apart.
  • Use enums to rule out invalid states. OpenAI’s example is a toggle_light(on, off) function that allows nonsense combinations.
  • Return only the fields the model needs and stable identifiers like slugs or UUIDs. A raw 200-field API response wastes context.
  • Keep the tool list short. OpenAI suggests staying under roughly 20 functions at the start of a turn and calls that a soft guide.

A working loop

The example below gives Claude one read-only tool that lists GitHub issues, following the pattern in Anthropic’s handle-tool-calls page. It turns on strict tool use, handles pagination inside the tool, and returns failures with is_error so the model can react. Model IDs come from Anthropic’s models overview.

import json, os, re
import anthropic, requests

client = anthropic.Anthropic()
GH = {"Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}",
      "Accept": "application/vnd.github+json"}

tools = [{
    "name": "github_list_issues",
    "description": (
        "Lists issues in one GitHub repository. Use it when the user asks about "
        "bugs, open work or issue counts for a named repo. Returns number, title, "
        "state and URL for up to 200 issues; it does not return comments or bodies."
    ),
    "strict": True,
    "input_schema": {
        "type": "object",
        "properties": {
            "repo": {"type": "string", "description": "owner/name, e.g. octocat/Spoon-Knife"},
            "state": {"type": "string", "enum": ["open", "closed", "all"]},
        },
        "required": ["repo", "state"],
        "additionalProperties": False,
    },
}]

def github_list_issues(repo: str, state: str) -> list[dict]:
    if not re.fullmatch(r"[\w.-]+/[\w.-]+", repo):
        raise ValueError("repo must look like owner/name")
    url, params, items = f"https://api.github.com/repos/{repo}/issues", {"state": state, "per_page": 100}, []
    while url and len(items) < 200:
        r = requests.get(url, headers=GH, params=params, timeout=30)
        if r.status_code in (403, 429) and ("retry-after" in r.headers
                                            or r.headers.get("x-ratelimit-remaining") == "0"):
            wait = r.headers.get("retry-after") or r.headers.get("x-ratelimit-reset")
            raise RuntimeError(f"GitHub rate limit hit. Do not retry before: {wait}")
        r.raise_for_status()
        items += [{"number": i["number"], "title": i["title"], "state": i["state"],
                   "url": i["html_url"]} for i in r.json()]
        url, params = r.links.get("next", {}).get("url"), None  # follow the link header
    return items[:200]

HANDLERS = {"github_list_issues": github_list_issues}

def run(prompt: str, max_turns: int = 8):
    messages = [{"role": "user", "content": prompt}]
    for _ in range(max_turns):
        resp = client.messages.create(model="claude-opus-5-5", max_tokens=2048,
                                      tools=tools, messages=messages)
        messages.append({"role": "assistant", "content": resp.content})
        if resp.stop_reason != "tool_use":
            return resp
        results = []
        for block in resp.content:
            if block.type != "tool_use":
                continue
            try:
                out = HANDLERS[block.name](**block.input)
                results.append({"type": "tool_result", "tool_use_id": block.id,
                                "content": json.dumps(out)})
            except Exception as e:
                results.append({"type": "tool_result", "tool_use_id": block.id,
                                "content": f"{type(e).__name__}: {e}", "is_error": True})
        messages.append({"role": "user", "content": results})
    raise RuntimeError("tool loop did not finish")

If you do not need control over each turn, the Python SDK’s tool runner (in beta) builds the schema from a function decorated with @beta_tool, runs the loop for you, and turns exceptions into is_error results. Anthropic recommends the manual loop when you need human approval, custom logging or conditional execution.

Auth and secrets

The model should never see or produce a credential. In the loop above, the token lives in an environment variable and is attached by the tool function. Apply the same rule to anything your code already knows: OpenAI’s guide says not to make the model fill arguments you already have, giving the example of a submit_refund() that takes no order ID because the application supplies it. Scope each token to what the tool does. A read-only tool should run on a read-only credential, so a confused or manipulated model cannot do more than read.

For MCP servers the spec splits auth by transport. Authorization is optional; a server on stdio should read credentials from its environment, while HTTP servers should follow the spec’s OAuth 2.1 flow, in which the server acts as a resource server. The rules worth knowing even if a library handles them: access tokens must not go in the URL query string, servers must check that a token was issued for them specifically, and a server must not accept or forward tokens meant for some other service. Our Gmail and Drive guide shows OAuth scopes for a real pair of Google APIs.

Pagination, rate limits and retries

Handle these inside the tool, not in the model. GitHub’s REST API is a good reference case:

  • Pagination comes through a link header with rel="next". Most endpoints cap per_page at 100, and a larger value is quietly reduced rather than rejected, so never assume one page holds everything.
  • Rate limits show up as x-ratelimit-remaining and x-ratelimit-reset headers. Going over returns 403 or 429; GitHub says not to retry before the reset time, or before the retry-after seconds if that header is present.
  • Pacing writes: GitHub suggests sending requests one after another rather than in parallel, and waiting at least a second between bulk POST, PATCH, PUT or DELETE calls.

HTTP’s 429 status is defined in RFC 6585, which says the server “MAY include a Retry-After header indicating how long” to wait. When a limit does reach the model, make the message useful. Anthropic’s example of a good error is “Rate limit exceeded. Retry after 60 seconds.” rather than a bare “failed”.

Validate what the model sends

Without strict mode, models can send a string where you expected a number or leave out a required field. With strict: true, Claude’s tool inputs are constrained to your schema; Anthropic’s example is a passengers field that comes back as 2, not "two". OpenAI recommends always enabling strict mode, which requires additionalProperties: false on every object and every property listed as required, with optional fields expressed by allowing null.

Schema conformance is not authorization. The schema can say repo is a string; only your code can say whether this user may read that repo. The MCP spec puts it bluntly: servers must validate all tool inputs, enforce access controls, rate limit calls and sanitise outputs. Two more reasons to check values:

  • Anthropic notes that Claude Sonnet may guess a missing required value (it filled in New York for a weather question with no city), while Opus models are more likely to ask.
  • API responses are untrusted input. A ticket body or web page can contain text written to steer the model. Anthropic advises keeping such content inside tool_result blocks rather than the system prompt.

Idempotency for write actions

Agents retry. Claude will typically retry an invalid call two or three times, a network timeout leaves you unsure whether a POST landed, and the model may call the same tool again on a later turn. For any tool that creates or changes something, make repeats harmless.

Stripe’s API shows the standard pattern. The client sends a unique Idempotency-Key header on POST requests, ideally a V4 UUID of up to 255 characters, and Stripe returns the saved result for a repeat with the same key instead of acting twice. Keys are kept for at least 24 hours, and reusing a key with different parameters is rejected. Stripe also warns that a 500 response leaves the outcome unknown, so look up the object before retrying with a new key.

In agent code, generate the key from the logical operation (for example, the ticket and action), not per model call, and store it so a restart reuses it. For actions with real consequences, the MCP spec says clients should ask the user to confirm and show the tool inputs before calling the server.

Expose the API as an MCP server

Once more than one agent or app needs the same API, wrap it in an MCP server instead of copying tool definitions around. The official Python SDK (MIT licence, Python 3.11 or later) derives the input schema from type hints:

from typing import Literal
from mcp.server import MCPServer
from github_tools import github_list_issues  # the function from the loop above

mcp = MCPServer("GitHub issues")

@mcp.tool()
def list_issues(repo: str, state: Literal["open", "closed", "all"] = "open") -> list[dict]:
    """List issues in a GitHub repository (owner/name). Read-only."""
    return github_list_issues(repo, state)

Test it with uv run mcp dev server.py in the MCP Inspector, and serve it over HTTP with uv run mcp run server.py --transport streamable-http. The spec asks for tool names of 1 to 128 characters using letters, digits, underscores, hyphens and dots. It separates protocol errors (unknown tool, malformed request) from tool execution errors, which go back in the result with isError: true so the model can correct itself.

To use a remote server from Claude without writing a client, Anthropic’s MCP connector (beta) takes the server URL and an optional OAuth token in mcp_servers. It only supports MCP tools, the server must be reachable over HTTPS, and you handle the OAuth flow and token refresh yourself. Ready-made servers such as the AWS MCP Server follow the same protocol; more are in our agent frameworks hub.

Honest limits

None of this makes the model’s choices correct. Strict mode guarantees shape, not judgement, and descriptions steer tool choice without guaranteeing it. Keep write tools few and narrow, log every call, and put a person in front of anything irreversible. If you are building a customer-facing flow on top of these tools, our guide to drafting support replies with an LLM covers the review step and evaluation.

#Tool use#Function calling#Model Context Protocol#Claude API#API integration
AI

Written by AI Agents Directory

Editorial team

Facts in this guide are checked against official documentation and repositories, which are linked in the article.