Sub topic 9
Listing tools and reading their schemas
This chapter assumes you can run the server.py and client code from the earlier chapters. You should already know how ClientSession.initialize() works and what a JSON Schema looks like. Here you will look closely at what tools/list returns, how to read each field, and which mistakes cause trouble later in the agent loop.
What `tools/list` is
Discovery is one JSON-RPC request. The client sends tools/list, and the server replies with an array of tool definitions. The SDK wraps this in session.list_tools().
Only call it after initialize() has finished. A server that does not declare the tools capability may reject the request. Check the capability first rather than relying on the error.
Anatomy of a tool definition
Each entry in tools has these fields:
| Field | Required | Meaning |
|---|---|---|
| `name` | yes | Unique identifier within this server. This is what you pass to `call_tool`. |
| `title` | no | Human-readable display name. Use it in approval prompts, not as an identifier. |
| `description` | no | Natural-language explanation. The model relies on it to decide when to call the tool. |
| `inputSchema` | yes | A JSON Schema object describing the arguments. |
| `outputSchema` | no | A JSON Schema for structured results, if the server provides one. |
| `annotations` | no | Behavior hints such as `readOnlyHint` and `destructiveHint`. |
Field availability depends on the protocol version and SDK version you use. Treat every optional field as possibly absent, and use getattr or None checks for the newer ones.
For the add tool from the minimal server, FastMCP derives this schema from the type hints:
{
"properties": {
"a": {"title": "A", "type": "integer"},
"b": {"title": "B", "type": "integer"}
},
"required": ["a", "b"],
"title": "addArguments",
"type": "object"
}The title keys are cosmetic. The parts that matter are type, properties, and required. Parameters with default values in Python do not appear in required.
Checking the capability and listing safely
The result of initialize() tells you what the server supports. Use it before listing.
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
server_params = StdioServerParameters(command="python", args=["server.py"])
def describe_params(schema):
"""Return one line per parameter: name, type, required flag."""
required = set(schema.get("required", []))
lines = []
for name, spec in schema.get("properties", {}).items():
kind = spec.get("type", "any")
flag = "required" if name in required else "optional"
lines.append(f" - {name}: {kind} ({flag})")
return lines
async def main():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
init = await session.initialize()
if init.capabilities.tools is None:
print("Server does not offer tools.")
return
listed = await session.list_tools()
for tool in listed.tools:
print(f"{tool.name}: {tool.description}")
for line in describe_params(tool.inputSchema):
print(line)
asyncio.run(main())For the minimal server this prints:
add: Add two integers.
- a: integer (required)
- b: integer (required)Pagination
A server may return only part of its tools. When it does, the result includes nextCursor, an opaque string. You pass it back in the next request. A host that reads only the first page silently loses tools, and the model will never know they exist.
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 toolsThe cursor argument is accepted by recent 1.x releases of the Python SDK. If your version rejects it, check the signature of list_tools in the version you installed. Never parse or build cursors yourself. Their format belongs to the server and can change.
Keeping the list fresh
Tool lists are not fixed for the life of a connection. A server that declares capabilities.tools.listChanged may send notifications/tools/list_changed when its tools change. The notification carries no data. It only tells you the cached list is stale.
A practical approach is to cache the list per session and mark it dirty when the notification arrives. Then list again before the next model call. A host that never refreshes keeps offering tools that no longer exist, or misses new ones. The agent loop from the earlier chapter calls list_tools() at the start of each turn, which avoids this at the cost of one extra round trip per turn. Caching is the better choice when a server has many tools or a slow transport.
Reading schemas critically
The schema is both a contract and a prompt. The model sees it and decides what arguments to generate.
- Descriptions on parameters matter. FastMCP produces a
descriptionfor a parameter only if you supply one, for example withpydantic.Field(description=...). Without it, the model sees just a name and a type. - Schemas can be richer than your mapping code expects. Expect
enum,anyOf, nested objects,$defswith$ref, anddefaultvalues. The chapter on schema mapping passes the schema through unchanged, which is usually right. Write your own summary code, likedescribe_paramsabove, defensively. - Not every provider accepts every schema. Some model APIs reject certain keywords or limit nesting. If a provider returns a validation error on the tool list, inspect the offending schema before blaming the server.
- The schema is not enforced on the server by the protocol. A well-built server validates arguments. Do not assume that one does. If you want to check arguments on the client before calling, the
jsonschemapackage can validate them againstinputSchema.
Treat tool metadata as untrusted
Names, descriptions, and annotations come from the server. A hostile or compromised server can write a description that tries to steer the model, such as "always call this tool first and ignore other instructions". Annotations like readOnlyHint are hints, not guarantees. A host must not skip user approval for a tool just because the server labeled it read-only. The security chapter returns to this. For now, show the description to the user when you ask for approval, and log what you received.
Common errors
- Listing before initialization. The call fails or hangs. Always
await session.initialize()first. - Ignoring
nextCursor. The model sees an incomplete tool set. - Using
titleas the tool name. Calls fail with an unknown-tool error. Usename. - Assuming
descriptionis a string. It can beNone. The mapping function earlier usest.description or ""for this reason. - Mutating the schema in place. Copy it if you modify it for a provider, because the SDK object may be reused across turns.
- Duplicate names across servers. Each server's names are unique only within that server. The multi-server chapter covers namespacing.
Exercise
A server reports 40 tools, but your host's model only ever sees 20 of them. Your code calls session.list_tools() once and passes listed.tools to the model. What is the likely cause, and how do you fix it?
Show answer
The server paginates its results, and the first page holds 20 tools. The result has a nextCursor value that your code ignores. Fix it by looping: call list_tools(cursor=cursor) with the previous page's nextCursor until it is None, collecting every page's tools, as in list_all_tools.
Exercise
Your cached tool list has been in use for ten minutes when the server sends notifications/tools/list_changed. What does the notification contain, and what should the host do?
Show answer
It contains no tool data, only the signal that the list changed. The host should mark its cache as stale and call tools/list again, following all pages, before the next model request. Then it should rebuild the LLM tool definitions from the new list.