Learn › Local AI Agents: Hermes 3 and the Model Context Protocol › Discovering Tools: Connecting Python to MCP

Discovering Tools: Connecting Python to MCP

Advanced 🕐 12 min Lesson 9 of 12
What you'll learn
  • Use the MCP Python SDK to open a stdio client connection to a server and call session.list_tools()
  • Write mcp_tool_to_hermes() to translate an MCP tool definition to the format Hermes expects in its tools block
  • Build a tool registry that maps each tool name to its server session for routing tool calls
  • Call session.call_tool() with parsed arguments and extract the text result from the content blocks

What This Lesson Builds

At the end of Lesson 8, you can call Hermes 3 with a hand-written tool definition in the system prompt and get a tool call back. This lesson replaces the hand-written part: instead of writing the tools block yourself, your Python code queries the actual MCP servers and builds the system prompt dynamically from their live tool listings.

By the end of this lesson you will have two functions:

  • connect_servers() — opens MCP client connections to all configured servers and returns them along with their tool listings
  • build_system_prompt(all_tools) — formats the tool list into the Hermes system prompt string

These become the foundation of the agent loop in Lesson 10.

The MCP Python Client

The official MCP Python SDK provides the client. Install it if it was not already pulled in by FastMCP:

uv add mcp

The key classes are ClientSession for the connection and either stdio_client or streamable_http_client for the transport. For local servers over stdio:

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

server_params = StdioServerParameters(
    command="python",
    args=["notes_server.py"],
)

async with stdio_client(server_params) as (read, write):
    async with ClientSession(read, write) as session:
        await session.initialize()
        tools_result = await session.list_tools()
        for tool in tools_result.tools:
            print(tool.name, "-", tool.description)

The stdio_client context manager spawns the server process and provides the read/write streams. ClientSession wraps them in the MCP protocol. session.initialize() performs the handshake and capability discovery. After that, session.list_tools() returns the full tool listing from the server.

The MCP SDK is async — it uses Python's asyncio. The agent code must run inside an async context. If you are new to async Python, the key rule is: functions that call await must themselves be declared async def, and you start the top-level async context with asyncio.run(main()).

Connecting to Multiple Servers

The agent connects to three servers: notes, filesystem, and fetch. Create a configuration structure that describes each server and a function that connects to all of them:

import asyncio
import json
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

SERVERS = [
    {
        "name": "notes",
        "params": StdioServerParameters(command="python", args=["notes_server.py"]),
    },
    {
        "name": "filesystem",
        "params": StdioServerParameters(
            command="npx",
            args=["-y", "@modelcontextprotocol/server-filesystem", "./workspace"],
        ),
    },
    {
        "name": "fetch",
        "params": StdioServerParameters(
            command="npx",
            args=["-y", "@modelcontextprotocol/server-fetch"],
        ),
    },
]


async def connect_servers():
    """Connect to all MCP servers and return sessions with their tool listings."""
    connections = []
    for server_cfg in SERVERS:
        transport = await stdio_client(server_cfg["params"]).__aenter__()
        read, write = transport
        session = ClientSession(read, write)
        await session.__aenter__()
        await session.initialize()
        tools_result = await session.list_tools()
        connections.append({
            "name": server_cfg["name"],
            "session": session,
            "tools": tools_result.tools,
        })
        print(f"Connected to {server_cfg['name']}: {len(tools_result.tools)} tools")
    return connections

Note: managing multiple context managers manually with __aenter__/__aexit__ is verbose. Lesson 10 wraps this in a cleaner pattern using AsyncExitStack. For now, this explicit form makes the lifecycle visible.

Translating MCP Tool Schemas to the Hermes Format

MCP's tool schema uses inputSchema as the parameter field name. Hermes expects parameters inside a function wrapper. The translation is straightforward:

def mcp_tool_to_hermes(tool) -> dict:
    """Convert an MCP tool definition to the Hermes function calling format."""
    return {
        "type": "function",
        "function": {
            "name": tool.name,
            "description": tool.description or "",
            "parameters": tool.inputSchema,
        }
    }


def build_system_prompt(connections: list) -> str:
    """Build the Hermes tool-calling system prompt from MCP tool listings."""
    all_tools = []
    for conn in connections:
        for tool in conn["tools"]:
            all_tools.append(mcp_tool_to_hermes(tool))

    tools_json = json.dumps(all_tools, indent=2)

    return f"""You are a function calling AI model. You are provided with function signatures within <tools></tools> XML tags. You may call one or more functions to assist with the user query. Do not make assumptions about what values to plug into functions.

<tools>
{tools_json}
</tools>

For each function call return a JSON object with function name and arguments within <tool_call></tool_call> XML tags as follows:
<tool_call>
{{"name": "function_name", "arguments": {{"arg1": "value1"}}}}
</tool_call>

If no tool is relevant, respond in natural language."""

Building a Tool Registry

To route a tool call back to the right server, you need a registry that maps tool names to their server sessions:

def build_tool_registry(connections: list) -> dict:
    """Map each tool name to the session that provides it."""
    registry = {}
    for conn in connections:
        for tool in conn["tools"]:
            if tool.name in registry:
                # Two servers expose the same tool name — prefix to disambiguate
                print(f"Warning: tool name collision on {tool.name!r}, "
                      f"prefixing with server name")
                registry[f"{conn['name']}_{tool.name}"] = conn["session"]
            else:
                registry[tool.name] = conn["session"]
    return registry

When the agent parses a <tool_call> response from Hermes, it looks up the tool name in this registry to find the session, then calls session.call_tool(name, arguments) on that session.

Calling a Tool via MCP

Once you have the session and the parsed arguments from the Hermes response, calling the tool is one line:

result = await session.call_tool(tool_name, arguments=tool_args)
tool_output = result.content[0].text if result.content else "No output"

The result object has a content list of content blocks. For text tools, the first block's text field holds the string output. If result.isError is True, the content holds the error message — you inject this back into the conversation the same way as a successful result, letting Hermes read the error and decide how to recover.

Testing the Bridge

Write a small test script that connects to the notes server and calls add_note programmatically:

async def test():
    connections = await connect_servers()
    system_prompt = build_system_prompt(connections)
    print("System prompt length:", len(system_prompt), "characters")
    print("First 300 chars:", system_prompt[:300])

    # Direct tool call test (no LLM yet)
    registry = build_tool_registry(connections)
    session = registry["add_note"]
    result = await session.call_tool("add_note", arguments={
        "title": "Test note",
        "content": "This was created by the bridge test script."
    })
    print("Tool result:", result.content[0].text)

asyncio.run(test())

Run this and confirm: the connection prints the tool count for each server, the system prompt is generated, and the direct tool call succeeds. With this working, Lesson 10 adds Hermes 3 inference to complete the loop.

Key takeaways
  • The MCP Python SDK is async — all client calls use await and the top-level entry point is asyncio.run(main())
  • mcp_tool_to_hermes() does one mapping: inputSchema becomes parameters inside a function wrapper — the content is identical, only the key names differ
  • Build the tool registry before the first LLM call — it maps tool names to sessions so the agent can route each tool_call to the right server without searching all sessions
  • If result.isError is True, inject the error message back as a tool_response turn anyway — Hermes reads the error and can retry with corrected arguments
Learn more every week Get 5 hand-picked prompts + new AI tools every Monday. Free.