Sub topic 16
Tool integration standards and agent frameworks
This chapter assumes you can write a tool-calling agent loop by hand, as in the earlier chapters. You should know how a tool is described with a JSON schema and how run_tool returns errors as text. Here you will see why tool definitions are being standardized, what the Model Context Protocol (MCP) does, and how to decide between a framework and your own loop.
The integration problem
Every model provider describes tools in a slightly different JSON shape. Every agent also needs tools from many places, such as a database, a ticket system, or a file store. Without a standard, you write one adapter per provider and one per tool source. With 4 providers and 10 tool sources, that is up to 40 adapters.
Two layers of standard reduce this work:
- Provider function-calling formats describe tools to one model API.
- Tool protocols such as MCP describe how an agent application finds and calls tools that live in a separate process.
Provider formats differ in small ways
The core idea is the same everywhere: a name, a description, and a JSON schema for the arguments. The wrapper differs.
| Where | Wrapper | Schema field |
|---|---|---|
| OpenAI-style chat APIs | `{"type": "function", "function": {...}}` | `parameters` |
| Anthropic Messages API | flat object | `input_schema` |
| MCP `tools/list` | flat object | `inputSchema` |
A common design is to keep one internal definition and convert it at the edge. The code below does this. It also shows a minimal tool server that answers MCP-style requests.
import json
TOOLS = {}
def tool(name: str, description: str, parameters: dict):
def register(fn):
TOOLS[name] = {"fn": fn, "description": description, "schema": parameters}
return fn
return register
@tool(
"get_weather",
"Get the current temperature in Celsius for a city.",
{
"type": "object",
"properties": {"city": {"type": "string", "description": "City name, for example Oslo"}},
"required": ["city"],
},
)
def get_weather(city: str) -> str:
return json.dumps({"city": city, "temp_c": 18})
def to_openai() -> list:
return [
{"type": "function",
"function": {"name": n, "description": t["description"], "parameters": t["schema"]}}
for n, t in TOOLS.items()
]
def to_anthropic() -> list:
return [
{"name": n, "description": t["description"], "input_schema": t["schema"]}
for n, t in TOOLS.items()
]
def handle_request(request: dict) -> dict:
"""Answer a JSON-RPC request the way an MCP server answers tools/list and tools/call."""
method = request.get("method")
rid = request.get("id")
if method == "tools/list":
tools = [
{"name": n, "description": t["description"], "inputSchema": t["schema"]}
for n, t in TOOLS.items()
]
return {"jsonrpc": "2.0", "id": rid, "result": {"tools": tools}}
if method == "tools/call":
params = request.get("params", {})
name = params.get("name")
if name not in TOOLS:
return {"jsonrpc": "2.0", "id": rid,
"error": {"code": -32602, "message": f"unknown tool: {name}"}}
try:
text = TOOLS[name]["fn"](**params.get("arguments", {}))
result = {"content": [{"type": "text", "text": text}], "isError": False}
except Exception as exc:
result = {"content": [{"type": "text", "text": str(exc)}], "isError": True}
return {"jsonrpc": "2.0", "id": rid, "result": result}
return {"jsonrpc": "2.0", "id": rid,
"error": {"code": -32601, "message": f"method not found: {method}"}}
print(json.dumps(to_openai()[0]["function"]["name"]))
print(json.dumps(to_anthropic()[0]["input_schema"]["required"]))
call = {"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": {"name": "get_weather", "arguments": {"city": "Oslo"}}}
print(json.dumps(handle_request(call)))This is a teaching sketch. A real MCP server also performs an initialize handshake, declares its capabilities, and runs over a transport. Use an official SDK for that rather than writing it yourself.
What MCP standardizes
MCP is an open protocol that connects an AI application to external capabilities. It uses JSON-RPC 2.0 messages. It has three roles:
- Host: the application the user runs, such as an IDE or chat app. It owns the model and the agent loop.
- Client: a connector inside the host. Each client keeps one connection to one server.
- Server: a separate program that exposes capabilities.
Servers can expose three kinds of capability. Tools are actions the model can request. Resources are data the application can read. Prompts are reusable templates. Tools are the part that matters most for agents.
MCP supports two main transports. With stdio, the host launches the server as a child process and exchanges messages over standard input and output. This suits local tools. With HTTP (streamable HTTP), the server runs remotely, which suits shared services and needs authentication.
The host still runs the agent loop. MCP only changes where run_tool finds its tools. In the loop from earlier chapters, you would replace the TOOLS lookup with a request to the right client.
Gotchas with protocol tools
- Trust. A server's tool names and descriptions go into the model's context. A malicious or compromised server can write descriptions that try to steer the model. Treat third-party servers like third-party code and review what they expose.
- Tool overload. Connecting five servers can add dozens of schemas to every request. That costs tokens and makes the model pick the wrong tool more often. Filter to the tools a given agent needs.
- Name collisions. Two servers may both define
search. Prefix names by server, such asgithub_search. - Errors. Two failure levels exist. A JSON-RPC
errormeans the request itself was bad.isError: trueinside a result means the tool ran and failed. Pass the second kind to the model as text so it can recover, as yourrun_tooldid. - Permissions still apply. A standard connection does not make an action safe. Keep the guardrails and approval checks in the host, before the call is forwarded.
Frameworks: what they give you
An agent framework packages the pieces you have built by hand: the loop, tool registration, message history, retries, tracing hooks, and often multi-agent patterns. Examples include LangChain and LangGraph, the OpenAI Agents SDK, and Google's ADK. Names and APIs change quickly, so check current documentation before you commit.
| Choose | When |
|---|---|
| Your own loop | The task is simple, you need full control of each request, or you want few dependencies. |
| A framework | You need state persistence, human-approval pauses, tracing, or several coordinated agents, and you do not want to rebuild them. |
Costs of a framework:
- Hidden prompts. Some frameworks add their own instructions or reformat messages. When behavior is wrong, you must find out what was actually sent.
- Abstraction churn. Breaking changes between versions are common in this field.
- Debugging depth. A stack trace may pass through several layers before it reaches your tool.
A practical rule: write the loop by hand once, as you did here, so that you can read a framework's source and understand it. Then adopt a framework only for features you can name. Keep your tool functions plain Python with schemas, so you can move them between a framework, MCP, or your own loop.
Exercise
Your agent connects to two MCP servers. Both expose a tool named search. The model keeps calling the wrong one, and each request now carries 40 tool schemas. Name two changes that address both problems.
Show answer
Prefix tool names by server (for example docs_search and tickets_search) so the names are distinct and descriptive. Then filter the tool list so each agent or task only receives the tools it needs. This removes the collision and shrinks the schema payload, which lowers token cost and the chance of a wrong choice.
Exercise
In the handle_request sketch, a tool raises a ValueError. Does the server return a JSON-RPC error or a result, and why?
Show answer
It returns a result with isError: true and the message as text content. The request was valid and the tool did run, so this is a tool failure, not a protocol failure. Returning it as a result lets the model read the message and try a corrected call.