Skip to content

Integrating Tools into Agents: From API to MCP

Overview

Tool integration is a critical step in agent development: I explore methods for connecting external functions via function-calling, REST API, and MCP, as well as reliability and security concerns.

Why Agents Need Tools

Without tools, an agent is limited to text generation. Tools enable it to perform actions: querying databases, calling APIs, sending messages. This transforms an LLM into an executor.

Function Calling

The simplest approach is to describe functions in JSON Schema and pass them to the model. The model returns a structured call that is executed in code.

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get weather",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string"}
                },
                "required": ["city"]
            }
        }
    }
]
response = llm.chat(messages, tools=tools)
if response.tool_calls:
    for call in response.tool_calls:
        result = execute_function(call)

For more details, see function-calling and tool-calling-deep-dive.

REST API as a Tool

If the tool is an external service, the agent calls it via HTTP. Proper error handling and timeouts are crucial.

import requests

def call_api(url, payload):
    try:
        resp = requests.post(url, json=payload, timeout=10)
        resp.raise_for_status()
        return resp.json()
    except requests.exceptions.Timeout:
        return {"error": "timeout"}
    except requests.exceptions.HTTPError as e:
        return {"error": f"http {e.response.status_code}"}

MCP: Standardization

MCP is a protocol that standardizes access to tools. The agent connects to an MCP server and receives a list of available tools without hard-coding them into the code.

graph LR
    A[Agent] -->|MCP| B[MCP-client]
    B --> C[MCP-server 1]
    B --> D[MCP-server 2]
    C --> E[API 1]
    D --> F[API 2]

Example connection via Python SDK:

from mcp import ClientSession, StdioServerParameters

session = await ClientSession(server_params)
await session.initialize()
tools = await session.list_tools()

Error Handling and Retries

Tools can fail. I add exponential backoff retries and return a clear error message to the agent so it can adjust its action.

import time

def call_with_retry(func, max_retries=3):
    for attempt in range(max_retries):
        try:
            return func()
        except Exception as e:
            if attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)

Security

Tools are a vector for attacks. Necessary measures include: