Velamuvi AIAcademy

Lesson 10 of 39 · Tools

MCP Tools

Connect agents to MCP servers with MCPStdioTool and MCPStreamableHTTPTool, filter and prefix their tools, and use hosted MCP through SupportsMCPTool.

  • 10 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain what an MCP server offers and how an agent uses its tools
  • Run a local MCP server and connect to it with MCPStdioTool
  • Connect to a server over HTTP with MCPStreamableHTTPTool, and filter and prefix its tools
  • Let the provider call an MCP server for you through SupportsMCPTool
  • Recognise the deprecated parts: MCPWebsocketTool, MCPTaskOptions and sampling

Tools that live in another program

So far every tool was a Python function inside your agent's program. The Model Context Protocol (MCP) lets a separate program offer tools to any agent, in any language. Thousands of MCP servers exist, for GitHub, databases, file systems, browsers and more, and one connection gives your agent all of a server's tools.

The protocol is plain JSON messages. Here is the idea in miniature:

Try it yourselfPython
import json

# A tiny MCP-style server: it answers two kinds of JSON requests.
PRICES = {"City E": 35, "Trail X": 50}


def server(request_json):
    request = json.loads(request_json)
    if request["method"] == "tools/list":
        result = {"tools": [{"name": "bike_price", "description": "Daily price of a bike",
                             "inputSchema": {"type": "object", "properties": {"model": {"type": "string"}}}}]}
    else:  # "tools/call"
        model = request["params"]["arguments"]["model"]
        result = {"content": [{"type": "text", "text": f"{model}: {PRICES[model]} EUR a day."}]}
    return json.dumps({"id": request["id"], "result": result})


# The client side: discover the tools, then call one, as an agent framework does.
listing = json.loads(server(json.dumps({"id": 1, "method": "tools/list"})))
print("tools:", [tool["name"] for tool in listing["result"]["tools"]])
call = {"id": 2, "method": "tools/call", "params": {"name": "bike_price", "arguments": {"model": "Trail X"}}}
print(json.loads(server(json.dumps(call)))["result"]["content"][0]["text"])

Agent Framework does the client side for you: it lists the server's tools, turns each one into a normal agent tool, and sends the calls when the model uses them.

A local MCP server

To have something to connect to, here is a small server for Velo, built with the official mcp package (it comes with pip install agent-framework). Save it as velo_mcp_server.py:

import sys

from mcp.server.mcpserver import MCPServer

server = MCPServer("velo-bikes")
PRICES = {"City E": 35, "Trail X": 50, "Kids 20": 15}


@server.tool()
def bike_price(model: str) -> str:
    """Daily rental price of one Velo bike model."""
    if model not in PRICES:
        return f"Unknown model {model}. Models: {', '.join(PRICES)}."
    return f"{model}: {PRICES[model]} EUR a day."


@server.tool()
def list_models() -> str:
    """All bike models that Velo rents out."""
    return ", ".join(PRICES)


if __name__ == "__main__":
    if sys.argv[1:] == ["http"]:
        server.run("streamable-http", host="127.0.0.1", port=8765)   # http://127.0.0.1:8765/mcp
    else:
        server.run()                                                # stdio, the default

Each @server.tool() function becomes an MCP tool; its docstring and type hints become the description and the input schema.

MCPStdioTool: start the server yourself

MCPStdioTool starts the server as a child process. Give it a name, the command to run and its args, then open it with async with: that starts the process, performs the MCP handshake and loads the tools.

import asyncio
import sys

from agent_framework import Agent, MCPStdioTool
from agent_framework.openai import OpenAIChatClient


async def main():
    velo = MCPStdioTool(
        name="velo",
        command=sys.executable,             # the Python that runs this script
        args=["velo_mcp_server.py"],         # the server file, started as a child process
        description="Velo's bike catalogue",
    )
    async with velo:                         # start the server and load its tools
        print("tools:", [function.name for function in velo.functions])
        agent = Agent(
            client=OpenAIChatClient(model="MODEL_NAME"),
            instructions="You are Velo's rental desk in Porto.",
            tools=velo,
        )
        print((await agent.run("How much is a Trail X per day?")).text)


asyncio.run(main())
Output
tools: ['bike_price', 'list_models']
A Trail X costs 50 EUR a day.

Pass the whole MCP tool in tools=; the agent gets every tool it found. Before the connection opens, velo.functions is an empty list, because the tools are only known after the server has listed them. Instead of async with velo: you can also open the agent itself with async with agent:, which connects all of its MCP tools and closes them at the end.

Many published servers run through npx or uvx, for example MCPStdioTool(name="files", command="npx", args=["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]).

MCPStreamableHTTPTool: a server at a URL

A server that runs on its own, perhaps on another machine, speaks streamable HTTP. Start the same server with python velo_mcp_server.py http, then connect with MCPStreamableHTTPTool:

import asyncio

from agent_framework import Agent, MCPStreamableHTTPTool
from agent_framework.openai import OpenAIChatClient


async def main():
    # Start the server first, in another terminal: python velo_mcp_server.py http
    velo = MCPStreamableHTTPTool(
        name="velo",
        url="http://127.0.0.1:8765/mcp",
        allowed_tools=["bike_price"],        # the agent only gets this tool
        tool_name_prefix="velo",             # tool names become velo_...
    )
    async with velo:
        print("tools:", [function.name for function in velo.functions])
        agent = Agent(
            client=OpenAIChatClient(model="MODEL_NAME"),
            instructions="You are Velo's rental desk in Porto.",
            tools=velo,
        )
        print((await agent.run("How much is a City E per day?")).text)


asyncio.run(main())
Output
tools: ['velo_bike_price']
A City E costs 35 EUR a day.

Two options matter for every server, whatever the transport:

  • allowed_tools keeps only the tools you name. A big server may offer dozens of tools, and every tool you expose costs tokens and gives the model one more way to go wrong.
  • tool_name_prefix puts a prefix in front of each name, so two servers that both have a search tool don't clash.

approval_mode works as in the tool approval lesson: "always_require", "never_require", or a dictionary with always_require_approval and never_require_approval lists of tool names. For a remote server you often need static_headers= too, for example {"Authorization": "Bearer ..."} with a key from an environment variable.

Hosted MCP: let the provider call the server

Some providers can call a public MCP server themselves, on their own machines. Clients that can do this match the SupportsMCPTool protocol and offer get_mcp_tool():

from agent_framework import Agent, SupportsMCPTool
from agent_framework.openai import OpenAIChatClient

client = OpenAIChatClient(model="MODEL_NAME")
print("can host MCP:", isinstance(client, SupportsMCPTool))

learn = client.get_mcp_tool(
    name="microsoft_learn",
    url="https://learn.microsoft.com/api/mcp",   # OpenAI's servers call this URL, not your code
    approval_mode="never_require",
)
agent = Agent(client=client, instructions="Answer questions about Microsoft products.", tools=[learn])
print(learn)
Output
can host MCP: True
{'type': 'mcp', 'server_label': 'microsoft_learn', 'server_url': 'https://learn.microsoft.com/api/mcp', 'require_approval': 'never'}

The result is just a tool description for the provider. Your program never connects to the server, so this only works for servers the provider can reach on the internet, not for one on your laptop.

Deprecated parts to recognise

MCP itself is still changing, and three names in Agent Framework are left over from older versions:

  • MCPWebsocketTool: WebSocket was never part of the MCP specification and was removed in MCP v2. Creating one prints a DeprecationWarning, and connecting fails (see below). Use MCPStreamableHTTPTool.
  • MCPTaskOptions: MCP Tasks were removed during the move to MCP SDK 2.x. The class only exists so old imports still work, and it warns: MCP Tasks support was removed during the MCP SDK 2.x migration. MCPTaskOptions is retained only for import compatibility.
  • Sampling: a server may ask to borrow your model to write text. The MCP specification of 2026-07-28 deprecated sampling, but it's still supported. Agent Framework refuses every sampling request unless you pass the model as client= and a SamplingApprovalCallback, a function that receives the request and returns True to allow it:
import sys

from agent_framework import MCPStdioTool
from agent_framework.openai import OpenAIChatClient


def approve_sampling(params) -> bool:
    # Runs before the server may use your model. Return False to refuse.
    return params.max_tokens <= 500


writer = MCPStdioTool(
    name="writer",
    command=sys.executable,
    args=["writer_server.py"],
    client=OpenAIChatClient(model="MODEL_NAME"),   # the model the server may borrow
    sampling_approval_callback=approve_sampling,
)

Without a callback, the request is refused and the agent logs Denying MCP sampling request from 'writer': no 'sampling_approval_callback' configured.

Common mistakes

Practice exercise

Write the filter that allowed_tools and tool_name_prefix apply to a server's tools: keep only the allowed ones, then add the prefix.

Your solutionPython
server_tools = ["bike_price", "list_models", "delete_booking", "refund"]


def expose(tools, allowed_tools=None, prefix=None):
    # Keep only the tools named in allowed_tools (all tools when it is None),
    # then put the prefix and an underscore in front of each name when a prefix is given.
    return list(tools)


print(expose(server_tools))
print(expose(server_tools, allowed_tools=["bike_price", "list_models"]))
print(expose(server_tools, allowed_tools=["bike_price"], prefix="velo"))
Knowledge check

What does MCPStdioTool do when you open it with async with?

Summary

  • An MCP server offers tools to any agent; Agent Framework lists them and turns them into normal agent tools.
  • MCPStdioTool starts a local server as a child process; MCPStreamableHTTPTool connects to a server at a URL. Open them with async with.
  • allowed_tools, tool_name_prefix, approval_mode and headers control what the agent gets and how it connects.
  • Clients that match SupportsMCPTool offer get_mcp_tool(), so the provider calls a public server for you.
  • MCPWebsocketTool and MCPTaskOptions are deprecated, and sampling needs a SamplingApprovalCallback.

Next: Agents as Tools.

Finished reading? Tick it off to track your progress.