Sub topic 10
Turning MCP tools into LLM tool definitions
This chapter covers how to convert the tool descriptions an MCP server returns into the tool format an LLM API expects. It assumes you can read async Python, know what JSON Schema is, and have called an LLM API with tool calling before. It also assumes you have a working client session from the previous chapters, one that can call initialize() and list_tools().
Why a mapping step exists
An MCP server describes each tool in a standard shape. An LLM API describes tools in its own shape. Your host application sits between the two, so it has to translate.
The translation is small because both sides use JSON Schema for the arguments. An MCP tool has a name, an optional description, and an inputSchema field. That field is already a JSON Schema object. An LLM API wants nearly the same information, wrapped in different field names.
The mapping step still matters for three reasons:
- The wrapper differs between providers, so you need one place that knows the difference.
- The model sees only the name, description and schema. The quality of these three fields decides whether the model picks the right tool.
- You often need to change names, trim descriptions, or drop tools before the model sees them.
What the server gives you
A call to session.list_tools() returns an object with a tools list. Each item is a Tool with these fields that matter here:
| MCP field | Meaning | Required |
|---|---|---|
| `name` | Identifier used when calling the tool | Yes |
| `description` | Natural language text for the model | No |
| `inputSchema` | JSON Schema object describing the arguments | Yes |
| `outputSchema` | Optional JSON Schema for structured results | No |
| `annotations` | Optional hints such as read-only or destructive | No |
Only the first three are needed for the mapping. The annotations field is useful for approval logic, which a later chapter covers. Treat annotations as hints from the server, not as guarantees.
The description can be missing, so your code must handle None. For the add tool from the minimal server, the SDK builds the schema from the type hints. It looks like this:
{
"properties": {
"a": {"title": "A", "type": "integer"},
"b": {"title": "B", "type": "integer"}
},
"required": ["a", "b"],
"title": "addArguments",
"type": "object"
}The top level is an object with properties and required. This is the shape LLM APIs expect for tool arguments.
The basic mapping
For the Anthropic Messages API, a tool is a dictionary with name, description and input_schema. The conversion renames one field and supplies a default for the description.
def to_llm_tools(mcp_tools):
return [
{
"name": t.name,
"description": t.description or "",
"input_schema": t.inputSchema,
}
for t in mcp_tools
]You call it with the list from the session:
listed = await session.list_tools()
tools = to_llm_tools(listed.tools)Other providers wrap the same schema differently. The table below shows the common patterns. Check your provider's current documentation, because field names change.
| Provider style | Wrapper around the schema |
|---|---|
| Anthropic Messages | Flat dict with `input_schema` |
| OpenAI Chat Completions | `{"type": "function", "function": {"name", "description", "parameters"}}` |
If you support several providers, keep one function per provider and let the rest of your loop work with MCP Tool objects.
Pagination
list_tools() can return a page of results with a nextCursor value. A server with many tools may split its list. If your host ignores the cursor, the model never sees the later tools, and nothing reports an error.
This helper collects every page:
async def list_all_tools(session):
tools = []
cursor = None
while True:
page = await session.list_tools(cursor=cursor)
tools.extend(page.tools)
cursor = page.nextCursor
if cursor is None:
return toolsMost small servers return one page, so the bug often stays hidden until a server grows.
Keeping the mapping honest
Name rules
LLM APIs restrict tool names. A common rule is letters, digits, underscores and hyphens, with a length limit such as 64 characters. MCP tool names are more permissive in practice, since servers are written by many people. A name with a dot or a space can cause a request error from the model API.
A simple defence is to sanitize names and keep a lookup table to the original:
import re
def to_llm_tools_safe(mcp_tools):
tools = []
lookup = {}
for t in mcp_tools:
safe = re.sub(r"[^a-zA-Z0-9_-]", "_", t.name)[:64]
if safe in lookup:
raise ValueError(f"Tool name collision after sanitizing: {safe}")
lookup[safe] = t.name
tools.append(
{
"name": safe,
"description": t.description or "",
"input_schema": t.inputSchema,
}
)
return tools, lookupWhen the model calls safe, you look up the original name and send that to the server:
original_name = lookup[block.name]
result = await session.call_tool(original_name, block.input)The same lookup idea solves collisions between several servers. A later chapter builds on it with a server prefix.
Schema features the provider may not accept
The MCP specification lets a server send any valid JSON Schema. Providers support only a subset of it. Features that commonly cause trouble:
$refand$defs, which appear when a tool takes a nested model.anyOfandoneOf, which appear for optional or union types.- Very deep nesting, or very large enums.
- Keywords such as
formatorpattern, which some providers reject in strict modes.
When a request fails with a schema error, find out which tool caused it. Send the tools one at a time, or log each schema before the call. Then decide whether to simplify the schema in the host, fix the server, or drop the tool.
Description quality
The model reads the description to decide when to call the tool. A description like "Do the thing" gives it nothing to work with. You usually can't change a third-party server, but you can wrap or override its descriptions in the host:
OVERRIDES = {
"add": "Add two integers and return their sum. Use for exact arithmetic.",
}
def apply_overrides(tools):
for tool in tools:
if tool["name"] in OVERRIDES:
tool["description"] = OVERRIDES[tool["name"]]
return toolsDescriptions are also an input channel from the server. A malicious server can put instructions in a description. Treat descriptions from servers you don't control as untrusted text. The security chapter returns to this.
Filtering what the model sees
You do not have to expose every tool. Each tool costs input tokens on every request, and a long list makes selection less accurate. An allowlist is the simplest filter:
ALLOWED = {"add", "read_file", "search_docs"}
def filter_tools(mcp_tools):
return [t for t in mcp_tools if t.name in ALLOWED]An allowlist also applies least privilege. A tool the model never sees is a tool it cannot call. Filter before mapping, and enforce the same list again when executing a call, so a model that invents a tool name is stopped.
def check_allowed(name):
if name not in ALLOWED:
raise PermissionError(f"Tool not allowed: {name}")Tools can change
A server can announce that its tool list changed, if it declared the listChanged capability for tools during initialization. The client then receives a notifications/tools/list_changed message. The simplest safe approach for a short script is to call list_tools() at the start of each turn, as the agent loop in the next chapter does. A long-running host should refresh when the notification arrives and cache the mapped list between turns.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| API rejects the request with an invalid tool name | Name has a dot, space or is too long | Sanitize names and keep a lookup |
| API rejects a schema | Unsupported keyword such as `$ref` | Log per-tool schemas, simplify or drop the tool |
| Model never uses a tool that exists | Missing page of tools, or vague description | Follow `nextCursor`, improve the description |
| `TypeError` on `description` | Description is `None` | Use `t.description or ""` |
| Model calls a tool name you don't recognise | Tool list changed or the model invented a name | Look up names and return an error result |
Exercises
Exercise
A server returns a tool named files.read. The model API only accepts names made of letters, digits, underscores and hyphens. Using the approach in this chapter, what name does the model see, and what must the host do when the model calls it?
Show answer
The model sees files_read. The host keeps a lookup from the sanitized name to the original, so when the model calls files_read it looks up files.read and passes that original name to session.call_tool. It should also raise an error if two tools sanitize to the same name.
Exercise
Your host lists tools from a server and the model never uses the last few tools, even when they fit the request. The server has about 120 tools. What is the most likely cause, and how do you fix it?
Show answer
The server paginates its tool list and the host read only the first page. Fix it by following nextCursor in a loop until it is None, as the list_all_tools helper does.