Skip to main content

AI and machine learning · Advanced · 26 min

Use MCP server tools from your own Claude app

By Padding · Updated 18 Nov 2026
python:3.15-slim · Python 3.15 · anthropic 2.14.0 · mcp 2.3.0 · pytest 9.2.0 · claude-opus-5-5

You will connect a Python app to the stdio clinic-hours MCP server, hand an allowlisted set of its tools to Claude, pass every tool call through to the server with a tested bridge, and know when the API's MCP connector can do the connecting for you.

On this page

An MCP server already describes its tools in a form a model can use: a name, a description and a JSON Schema for the inputs. Claude's Messages API wants almost the same three things. What sits between them is a small piece of your own code, a bridge, that lists the server's tools, decides which ones Claude may see, sends Claude's tool calls to the server and returns the results. Writing that bridge yourself is how you keep control: the model can only call what you expose, and every call goes through one function you can test and log.

You will build it on the Nsoromma Health clinic-hours server from build an MCP server in Python, with its two read-only tools, find_clinics and get_hours, and its SQLite database. You add one tool to it, book_appointment, which changes data, so your app has something it must never show to Claude. By the end you have:

  • an MCP client that starts the server over stdio and lists its tools
  • a converter from MCP tool definitions to Claude tool definitions, with an allowlist and a server prefix on every name
  • a pass-through that runs each tool_use block on the MCP server and turns the answer, or the error, into a tool_result
  • the tool-use loop with a round limit, and a pytest suite that runs it against a local stub of the Messages API and the real MCP server
  • a request that uses the API's MCP connector instead, for servers that are public on the internet, with its limits

Everything except the two live runs works offline and costs nothing, which also means you can re-run it as often as you like on a metered or prepaid connection.

Step 1 · Create the project

Make a throwaway project next to the server's and add the Anthropic SDK, the official MCP Python SDK and pytest, pinned exactly. mcp 2 renamed and reshaped parts of the 1.x API, so code written for one major version does not run on the other:

Bash
mkdir -p ~/mcp-claude-demo
cd ~/mcp-claude-demo
uv init --no-package
uv add "anthropic==2.14.0" "mcp==2.3.0"
uv add --dev "pytest==9.2.0"
mkdir -p tests

Check it worked

Bash
uv run python -c "import anthropic, importlib.metadata as m; print(anthropic.__version__, m.version('mcp'))"

The output is 2.14.0 2.3.0.

Step 2 · Bring in the clinic server and list its tools

Copy the two files you wrote in the server tutorial into this project, and build the database again here so this project has its own copy:

Bash
cp ~/clinic-mcp-demo/seed_db.py ~/clinic-mcp-demo/clinic_server.py .
uv run python seed_db.py

If you no longer have ~/clinic-mcp-demo, work through the database, tools, and resource and prompt steps of that tutorial first. The server opens clinic_hours.db read-only on every query, and clinic_server.py stays exactly as you wrote it.

To show how the bridge keeps a dangerous tool away from the model, the server needs one that changes data. Rather than edit clinic_server.py, create booking_server.py, which imports the same server object, registers book_appointment on it and runs it. Because the database is read-only, bookings go into a list in memory, which the tests will inspect:

Bash
cat > booking_server.py <<'PY'
"""The clinic-hours server from build-an-mcp-server-in-python, plus one tool that changes data."""
from mcp.server.mcpserver.exceptions import ToolError

from clinic_server import ClinicId, Day, query
from clinic_server import mcp as server

BOOKINGS = []  # in memory: clinic_server opens the database read-only


@server.tool()
def book_appointment(clinic_id: ClinicId, day: Day, patient_name: str) -> str:
    """Book an appointment for a patient at a clinic. This changes data."""
    if not query("SELECT 1 FROM clinics WHERE id = ?", (clinic_id,)):
        raise ToolError(f"No clinic with id {clinic_id!r}. Call find_clinics to get valid ids.")
    BOOKINGS.append({"clinic_id": clinic_id, "day": day, "patient_name": patient_name})
    return f"Booked {patient_name} at {clinic_id} on {day}."


if __name__ == "__main__":
    server.run()  # stdio by default
PY

A production server would write bookings to their own table through a separate read-write connection; the in-memory list keeps this tutorial about the client.

Now the client side. mcp.Client takes a StdioServerParameters, starts the command as a child process, and talks MCP over its standard input and output. Create list_tools.py:

Bash
cat > list_tools.py <<'PY'
"""Start the clinic server over stdio and print the tools it offers."""
import asyncio
import json
import sys

from mcp import Client, StdioServerParameters

SERVER = StdioServerParameters(command=sys.executable, args=["booking_server.py"])


async def main():
    async with Client(SERVER) as mcp:
        listing = await mcp.list_tools()
        for tool in listing.tools:
            print(tool.name, json.dumps(tool.input_schema.get("required", [])))


asyncio.run(main())
PY
uv run list_tools.py | tee /tmp/list-tools.txt

sys.executable is the Python running the client, so the server starts inside the same project environment with the same mcp version.

Check it worked

Three lines, one per tool, in the order the server registered them, with the inputs each one requires:

Text
find_clinics ["city"]
get_hours ["clinic_id", "day"]
book_appointment ["clinic_id", "day", "patient_name"]

The server process exits when the async with block ends.

Step 3 · Turn MCP tools into Claude tool definitions

Create mcp_bridge.py, the module the rest of the tutorial builds on. Its first three functions handle the tool list:

  • list_all_tools follows next_cursor, because a server may return its tools in pages.
  • to_claude_tools keeps only the tools named in allow, copies the description and schema, and prefixes each name with the server name and two underscores. Two servers can both have a search tool; clinic__search and files__search cannot collide. The name is checked against the Messages API's pattern, letters, digits, _ and -, at most 128 characters.
  • to_claude_tools also fails if the allowlist names a tool the server does not have, so a renamed tool breaks loudly instead of silently disappearing.

It is an allowlist, not a denylist, on purpose. If the server's owner adds a cancel_all_appointments tool next month, a denylist would hand it to Claude without anyone deciding to; an allowlist ignores it until you add it.

The last two functions handle calls, and are explained in the next step:

Bash
cat > mcp_bridge.py <<'PY'
"""Turn MCP tools into Claude tool definitions, and Claude's tool calls into MCP calls."""
import json
import re

from mcp import MCPError

SEP = "__"  # clinic__get_hours: server name, two underscores, tool name
NAME_OK = re.compile(r"^[a-zA-Z0-9_-]{1,128}$")  # the Messages API's rule for tool names


async def list_all_tools(mcp):
    """Every tool on the server, following next_cursor when the list comes in pages."""
    tools, cursor = [], None
    while True:
        page = await mcp.list_tools(cursor=cursor)
        tools.extend(page.tools)
        cursor = page.next_cursor
        if not cursor:
            return tools


def to_claude_tools(server_name, mcp_tools, allow):
    """Claude tool definitions for the allowed MCP tools only."""
    offered = {tool.name for tool in mcp_tools}
    missing = set(allow) - offered
    if missing:
        raise ValueError(f"allowed tools not on the {server_name} server: {sorted(missing)}")
    definitions = []
    for tool in sorted(mcp_tools, key=lambda t: t.name):
        if tool.name not in allow:
            continue  # the model never hears about it
        name = f"{server_name}{SEP}{tool.name}"
        if not NAME_OK.match(name):
            raise ValueError(f"{name!r} is not a valid Claude tool name")
        definitions.append(
            {
                "name": name,
                "description": tool.description or f"The {tool.name} tool on {server_name}.",
                "input_schema": tool.input_schema,
            }
        )
    return definitions


def text_of(result):
    """Turn an MCP CallToolResult into text for a tool_result block."""
    if result.structured_content is not None:
        return json.dumps(result.structured_content)  # one line of JSON, as the output schema describes
    parts = []
    for item in result.content:
        if item.type == "text":
            parts.append(item.text)
        else:
            parts.append(f"[{item.type} content left out]")
    return "\n".join(parts) or "(the tool returned nothing)"


async def call_through(mcp, server_name, block, exposed):
    """Run one tool_use block on the MCP server and return the matching tool_result block."""
    prefix = server_name + SEP
    if block.name not in exposed or not block.name.startswith(prefix):
        return {
            "type": "tool_result",
            "tool_use_id": block.id,
            "content": f"Tool {block.name} is not available.",
            "is_error": True,
        }
    try:
        result = await mcp.call_tool(block.name.removeprefix(prefix), block.input)
    except MCPError as err:  # a protocol error, such as the server going away
        return {"type": "tool_result", "tool_use_id": block.id, "content": f"MCP error: {err}", "is_error": True}
    return {
        "type": "tool_result",
        "tool_use_id": block.id,
        "content": text_of(result),
        "is_error": result.is_error,
    }
PY

Then a short script to look at what Claude will receive. Create preview_tools.py:

Bash
cat > preview_tools.py <<'PY'
"""Print the Claude tool definitions the bridge builds from the clinic server."""
import asyncio
import json
import sys

from mcp import Client, StdioServerParameters

from mcp_bridge import list_all_tools, to_claude_tools

SERVER = StdioServerParameters(command=sys.executable, args=["booking_server.py"])


async def main():
    async with Client(SERVER) as mcp:
        tools = to_claude_tools("clinic", await list_all_tools(mcp), {"find_clinics", "get_hours"})
    print(json.dumps(tools[1], indent=2))
    print([tool["name"] for tool in tools])


asyncio.run(main())
PY
uv run preview_tools.py | tee /tmp/preview.txt

Check it worked

The script prints the definition for clinic__get_hours: its name, the docstring from clinic_server.py as description, and an input_schema whose required list is ["clinic_id", "day"], with the pattern on clinic_id and the enum of seven days that your type hints produced. The last line is ['clinic__find_clinics', 'clinic__get_hours']: book_appointment is on the server but not in the list.

The schema also carries title keys that MCPServer added. The API accepts them, so the bridge passes the schema through untouched rather than trying to clean it.

Step 4 · Pass tool calls through to the MCP session

When Claude replies with a tool_use block, call_through in mcp_bridge.py does four things:

  • refuses any name that is not in the exposed set, without asking the server. A model can still name a tool it was never given, and text inside a tool result can try to talk it into one, so the check sits in code, not in the prompt.
  • strips the clinic__ prefix and calls the tool on the server with Claude's input.
  • turns the MCP result into text with text_of. get_hours and find_clinics return pydantic models, so the result carries structured_content, and the bridge sends that as one line of JSON. Without it, the bridge joins the text items; MCP results can hold images, audio or links to resources too, and it says what it left out rather than dropping it silently.
  • copies the server's is_error flag onto the tool_result, so Claude learns the call failed and can try again. An MCPError, a protocol problem such as the server going away, becomes an error result as well, instead of crashing the loop.

Try it with three made-up tool_use blocks and no model at all. Create try_calls.py:

Bash
cat > try_calls.py <<'PY'
"""Send three made-up tool_use blocks through the bridge, without Claude."""
import asyncio
import sys
from types import SimpleNamespace

from mcp import Client, StdioServerParameters

from mcp_bridge import call_through

SERVER = StdioServerParameters(command=sys.executable, args=["booking_server.py"])
EXPOSED = {"clinic__find_clinics", "clinic__get_hours"}
BLOCKS = [
    SimpleNamespace(id="toolu_1", name="clinic__get_hours", input={"clinic_id": "kumasi-asokwa", "day": "saturday"}),
    SimpleNamespace(id="toolu_2", name="clinic__get_hours", input={"clinic_id": "accra-osu", "day": "monday"}),
    SimpleNamespace(id="toolu_3", name="clinic__book_appointment",
                    input={"clinic_id": "kumasi-asokwa", "day": "monday", "patient_name": "Ama"}),
]


async def main():
    async with Client(SERVER) as mcp:
        for block in BLOCKS:
            result = await call_through(mcp, "clinic", block, EXPOSED)
            print(result["tool_use_id"], result["is_error"], result["content"])


asyncio.run(main())
PY
uv run try_calls.py | tee /tmp/try-calls.txt

Check it worked

The script prints these three lines:

Text
toolu_1 False {"clinic_id": "kumasi-asokwa", "clinic_name": "Nsoromma Health Asokwa", "day": "saturday", "is_open": true, "opens": "09:00", "closes": "13:00"}
toolu_2 True Error executing tool get_hours: No clinic with id 'accra-osu'. Call find_clinics to get valid ids.
toolu_3 True Tool clinic__book_appointment is not available.

The first call worked. The second reached the server, which answered with the ToolError text you wrote in the server tutorial, prefixed by the SDK, so the model knows to call find_clinics. The third never left your process. Mixed in with them, the server's log lines, such as get_hours kumasi-asokwa saturday and the failed call, arrive on standard error, which is where your logs should pick them up.

Step 5 · Run the tool-use loop

Create clinic_assistant.py. ask lists the tools, converts them, and runs the loop from let Claude call your Python functions with tool use: send the request, append Claude's reply unchanged, run every tool_use block through the bridge, return all the results in one user message, and stop after four rounds. Points specific to this model and this SDK:

  • max_tokens is 4000. Opus 5.5 always thinks before it answers, and thinking counts towards the limit.
  • The assistant's content goes back as it came, thinking blocks included. The API needs them during tool use.
  • tool_choice is left at its default, auto. Opus 5.5 returns a 400 error for a forced tool choice.
  • mcp.Client runs on an anyio task group. An exception that escapes its async with block arrives wrapped in an ExceptionGroup, so main handles NoAnswer inside the block.
Bash
cat > clinic_assistant.py <<'PY'
"""Answer clinic questions with Claude, using tools from the clinic MCP server."""
import asyncio
import sys
from pathlib import Path

import anthropic
from mcp import Client, StdioServerParameters

from mcp_bridge import call_through, list_all_tools, to_claude_tools

MODEL = "claude-opus-5-5"
MAX_TOKENS = 4000  # thinking counts towards this
MAX_ROUNDS = 4
SERVER_NAME = "clinic"
ALLOWED = {"find_clinics", "get_hours"}  # book_appointment stays hidden
SYSTEM = "You answer questions about Nsoromma Health clinic opening hours. Use the tools; do not guess hours."
SERVER = StdioServerParameters(
    command=sys.executable,
    args=[str(Path(__file__).with_name("booking_server.py"))],
)


class NoAnswer(Exception):
    """Claude stopped without a usable answer."""


async def ask(question, claude, mcp):
    tools = to_claude_tools(SERVER_NAME, await list_all_tools(mcp), ALLOWED)
    exposed = {tool["name"] for tool in tools}
    messages = [{"role": "user", "content": question}]
    for _ in range(MAX_ROUNDS):
        reply = await claude.messages.create(
            model=MODEL, max_tokens=MAX_TOKENS, system=SYSTEM, tools=tools, messages=messages
        )
        messages.append({"role": "assistant", "content": reply.content})
        if reply.stop_reason != "tool_use":
            text = "".join(b.text for b in reply.content if b.type == "text").strip()
            if not text:
                raise NoAnswer(f"no text in the reply, stop_reason {reply.stop_reason}")
            return text
        results = [
            await call_through(mcp, SERVER_NAME, block, exposed)
            for block in reply.content
            if block.type == "tool_use"
        ]
        messages.append({"role": "user", "content": results})
    raise NoAnswer(f"no answer after {MAX_ROUNDS} rounds")


async def main(question):
    claude = anthropic.AsyncAnthropic()  # reads ANTHROPIC_API_KEY (and ANTHROPIC_BASE_URL)
    async with Client(SERVER) as mcp:
        try:
            print(await ask(question, claude, mcp))
        except NoAnswer as err:
            # Handled inside the block: anything raised out of it arrives wrapped in an ExceptionGroup.
            print(f"No answer: {err}", file=sys.stderr)


if __name__ == "__main__":
    asyncio.run(main(sys.argv[1]))
PY

To run it without a key, use a stub of the Messages API: a cut-down version of the one in test Claude API code offline that plays a model. On a first request it asks for clinic__get_hours for Asokwa on Saturday; once it receives tool results, it answers with a sentence that quotes them. Tests can queue other tool calls. It also answers the MCP connector request used in the last step. Create stub_messages.py:

Bash
cat > stub_messages.py <<'PY'
"""A local stand-in for the Messages API that plays a scripted tool-using model."""
import json
import sys
import threading
from collections import deque
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

THINKING = {"type": "thinking", "thinking": "", "signature": "stub-signature"}
ASOKWA_SATURDAY = {"clinic_id": "kumasi-asokwa", "day": "saturday"}


def message(n, content, stop_reason):
    return {
        "id": f"msg_stub_{n}",
        "type": "message",
        "role": "assistant",
        "model": "claude-opus-5-5",
        "content": [THINKING, *content],
        "stop_reason": stop_reason,
        "stop_sequence": None,
        "usage": {"input_tokens": 300, "output_tokens": 120},
    }


class StubAPI:
    def __init__(self, port=0):
        self.queued = deque()  # each item: a list of (tool name, input) calls for one turn
        self.received = []  # every request body, in order
        stub = self

        class Handler(BaseHTTPRequestHandler):
            def do_POST(self):
                body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
                stub.received.append({"headers": {k.lower(): v for k, v in self.headers.items()}, "body": body})
                self.reply(stub.answer(body))

            def reply(self, payload):
                data = json.dumps(payload).encode()
                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.send_header("Content-Length", str(len(data)))
                self.end_headers()
                self.wfile.write(data)

            def log_message(self, format, *args):
                pass

        self.server = ThreadingHTTPServer(("127.0.0.1", port), Handler)

    def answer(self, body):
        n = len(self.received)
        if "mcp_servers" in body:  # the MCP connector: the API calls the server itself
            server = body["mcp_servers"][0]["name"]
            return message(n, [
                {"type": "mcp_tool_use", "id": "mcptoolu_stub_1", "name": "get_hours",
                 "server_name": server, "input": ASOKWA_SATURDAY},
                {"type": "mcp_tool_result", "tool_use_id": "mcptoolu_stub_1", "is_error": False,
                 "content": [{"type": "text", "text": '{"is_open": true, "opens": "09:00", "closes": "13:00"}'}]},
                {"type": "text", "text": "Stub reply: Asokwa is open 09:00-13:00 on Saturday."},
            ], "end_turn")
        last = body["messages"][-1]["content"]
        if isinstance(last, list) and any(b.get("type") == "tool_result" for b in last) and not self.queued:
            seen = " | ".join(b["content"] for b in last if b.get("type") == "tool_result")
            return message(n, [{"type": "text", "text": f"Stub reply. Tool results: {seen}"}], "end_turn")
        default = [("clinic__get_hours", ASOKWA_SATURDAY)]
        calls = self.queued.popleft() if self.queued else default
        blocks = [
            {"type": "tool_use", "id": f"toolu_stub_{n}_{i}", "name": name, "input": args}
            for i, (name, args) in enumerate(calls)
        ]
        return message(n, blocks, "tool_use")

    @property
    def base_url(self):
        host, port = self.server.server_address[:2]
        return f"http://{host}:{port}"

    def start(self):
        threading.Thread(target=self.server.serve_forever, daemon=True).start()
        return self

    def stop(self):
        self.server.shutdown()
        self.server.server_close()


if __name__ == "__main__":
    stub = StubAPI(port=int(sys.argv[1]) if len(sys.argv) > 1 else 8811)
    print(f"Stub Messages API on {stub.base_url}", flush=True)
    stub.server.serve_forever()
PY

Start the stub in a second terminal and leave it running:

Bash
cd ~/mcp-claude-demo
uv run stub_messages.py 8811

Back in the first terminal, ask a question. stub-key is not a key; the stub ignores it, but the SDK will not send a request without one:

Bash
ANTHROPIC_BASE_URL=http://127.0.0.1:8811 ANTHROPIC_API_KEY=stub-key uv run clinic_assistant.py "When is the Asokwa clinic open on Saturday?" | tee /tmp/answer.txt

Check it worked

The output is Stub reply. Tool results: followed by the Asokwa Saturday JSON from the last step, with "opens": "09:00", "closes": "13:00". That JSON went the whole way round: the stub asked for a tool, your bridge called the real MCP server over stdio, the server read clinic_hours.db, and the answer came back to the stub as a tool_result. Stop the stub with Ctrl+C in the second terminal.

Step 6 · Test the bridge with pytest

The tests start their own stub on a free port, so nothing needs to run in the second terminal. They connect to the clinic server in-process, by passing the MCPServer object to Client instead of a command, which is faster and lets a test read the BOOKINGS list. One test still goes over stdio, to prove the real transport works. Create tests/conftest.py:

Bash
cat > tests/conftest.py <<'PY'
import sys
from pathlib import Path

import anthropic
import pytest

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

import booking_server  # noqa: E402
from stub_messages import StubAPI  # noqa: E402


@pytest.fixture
def stub():
    server = StubAPI().start()
    yield server
    server.stop()


@pytest.fixture
def claude(stub):
    # "stub-key" is not a real key; the stub never checks it.
    return anthropic.AsyncAnthropic(api_key="stub-key", base_url=stub.base_url, max_retries=0)


@pytest.fixture(autouse=True)
def no_bookings():
    booking_server.BOOKINGS.clear()
    yield
PY

Now the tests. Each one says what it proves in its name; the hidden-tool test is the one to keep an eye on, because it checks that a refused call never reaches the server:

Bash
cat > tests/test_bridge.py <<'PY'
import asyncio
import json

import pytest
from mcp import Client

import booking_server
import clinic_assistant
from clinic_assistant import NoAnswer, ask
from mcp_bridge import list_all_tools, to_claude_tools

ASOKWA_SATURDAY = {"clinic_id": "kumasi-asokwa", "day": "saturday"}


def run(question, claude, server=booking_server.server):
    """Ask one question with the clinic server connected in-process."""
    async def go():
        async with Client(server) as mcp:
            try:
                return await ask(question, claude, mcp)
            except NoAnswer as err:
                return err  # returned, not raised, so it is not wrapped in an ExceptionGroup
    result = asyncio.run(go())
    if isinstance(result, NoAnswer):
        raise result
    return result


def tool_results(request):
    return [b for b in request["body"]["messages"][-1]["content"] if b["type"] == "tool_result"]


def test_model_sees_only_allowed_tools(stub, claude):
    run("When is Asokwa open on Saturday?", claude)
    names = [tool["name"] for tool in stub.received[0]["body"]["tools"]]
    assert names == ["clinic__find_clinics", "clinic__get_hours"]


def test_mcp_result_reaches_claude(stub, claude):
    answer = run("When is Asokwa open on Saturday?", claude)
    assert len(stub.received) == 2
    [result] = tool_results(stub.received[1])
    assert result["is_error"] is False
    hours = json.loads(result["content"])
    assert (hours["is_open"], hours["opens"], hours["closes"]) == (True, "09:00", "13:00")
    assert "13:00" in answer


def test_hidden_tool_is_refused(stub, claude):
    stub.queued.append([("clinic__book_appointment", {**ASOKWA_SATURDAY, "patient_name": "Ama"})])
    run("Book me in at Asokwa on Saturday", claude)
    [result] = tool_results(stub.received[1])
    assert result["is_error"] is True
    assert "not available" in result["content"]
    assert booking_server.BOOKINGS == []  # the server was never asked


def test_tool_error_is_passed_back(stub, claude):
    stub.queued.append([("clinic__get_hours", {"clinic_id": "accra-osu", "day": "monday"})])
    run("Is Accra Osu open on Monday?", claude)
    [result] = tool_results(stub.received[1])
    assert result["is_error"] is True
    assert "No clinic with id 'accra-osu'" in result["content"]
    assert "Call find_clinics" in result["content"]


def test_parallel_calls_answered_in_one_message(stub, claude):
    stub.queued.append([
        ("clinic__get_hours", ASOKWA_SATURDAY),
        ("clinic__get_hours", {"clinic_id": "kumasi-bantama", "day": "saturday"}),
    ])
    run("Is Asokwa or Bantama open on Saturday?", claude)
    results = [json.loads(r["content"]) for r in tool_results(stub.received[1])]
    assert [(r["clinic_id"], r["is_open"]) for r in results] == [
        ("kumasi-asokwa", True),
        ("kumasi-bantama", False),
    ]


def test_round_cap_stops_a_runaway_loop(stub, claude):
    for _ in range(clinic_assistant.MAX_ROUNDS):
        stub.queued.append([("clinic__find_clinics", {"city": "Kumasi"})])
    with pytest.raises(NoAnswer, match="after 4 rounds"):
        run("Keep going", claude)
    assert len(stub.received) == clinic_assistant.MAX_ROUNDS


def test_allowlist_must_match_the_server():
    async def go():
        async with Client(booking_server.server) as mcp:
            return await list_all_tools(mcp)
    tools = asyncio.run(go())
    with pytest.raises(ValueError, match="delete_everything"):
        to_claude_tools("clinic", tools, {"get_hours", "delete_everything"})


def test_real_stdio_server(stub, claude):
    async def go():
        async with Client(clinic_assistant.SERVER) as mcp:
            return await ask("When is Asokwa open on Saturday?", claude, mcp)
    assert '"closes": "13:00"' in asyncio.run(go())
PY
uv run pytest -q tests/test_bridge.py

Check it worked

pytest prints 8 passed. To see the most important test catch a bug, open mcp_bridge.py, change if block.name not in exposed or not block.name.startswith(prefix): to if not block.name.startswith(prefix):, and run the file again. test_hidden_tool_is_refused fails: the call now reaches the server, which books Ama's appointment with a tool Claude was never given. Put the line back.

Step 7 · Ask Claude a real question

The tests prove the plumbing. Only a real request shows what the model does with your tools. Load the key you stored in call an LLM API from Python and ask something that needs both read-only tools. This makes up to four billed requests to Opus 5.5:

Bash
cd ~/mcp-claude-demo
uv run --env-file ~/.config/llm-demo/env clinic_assistant.py "Which clinics in Kumasi are open on Saturday morning, and until when?"

Check it worked

You get a short answer saying that Nsoromma Health Asokwa is open from 09:00 to 13:00 and that Bantama is closed on Saturday. The wording varies from run to run. Check the hours against clinic_hours.db yourself before you trust the pattern: the answer is only as good as the tool results, and a model can still misread them. If you later expose book_appointment, make your app show the booking to a person and wait for them to confirm before call_through sends it.

Treat what comes back from any MCP server as untrusted text. A tool description or result can carry instructions aimed at the model; see secure the MCP servers you build and install and defend an LLM app against prompt injection.

Step 8 · Let the API connect to a public MCP server

If a server is already on the internet over HTTPS, the Messages API can be its MCP client for you. You send an mcp_servers list with the server's URL and an mcp_toolset entry in tools, plus the mcp-client-2025-11-20 beta header. The API lists the tools, Claude calls them, and the reply holds mcp_tool_use and mcp_tool_result blocks next to the text, all in one request. Your code runs no loop.

The same allowlist idea applies: default_config switches every tool off, and configs switches on the two read-only ones. Create connector.py. It reads the server URL, and a bearer token if the server needs one, from the environment, so neither ends up in your code:

Bash
cat > connector.py <<'PY'
"""Let the Messages API call a public MCP server for you (MCP connector, beta)."""
import os

import anthropic

server = {"type": "url", "url": os.environ["CLINIC_MCP_URL"], "name": "clinic"}
if os.environ.get("CLINIC_MCP_TOKEN"):
    server["authorization_token"] = os.environ["CLINIC_MCP_TOKEN"]

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY
reply = client.beta.messages.create(
    model="claude-opus-5-5",
    max_tokens=4000,
    betas=["mcp-client-2025-11-20"],
    mcp_servers=[server],
    tools=[
        {
            "type": "mcp_toolset",
            "mcp_server_name": "clinic",
            "default_config": {"enabled": False},  # allowlist: everything off ...
            "configs": {  # ... then switch on the read-only tools
                "find_clinics": {"enabled": True},
                "get_hours": {"enabled": True},
            },
        }
    ],
    messages=[{"role": "user", "content": "When is the Asokwa clinic open on Saturday?"}],
)
for block in reply.content:
    if block.type == "mcp_tool_use":
        print(f"called {block.server_name}.{block.name} with {block.input}")
    elif block.type == "mcp_tool_result":
        print("tool error" if block.is_error else "tool result received")
    elif block.type == "text":
        print(block.text)
print("stop_reason:", reply.stop_reason)
PY

Test the request it builds against the stub, which answers with the block shapes the connector documentation shows:

Bash
cat > tests/test_connector.py <<'PY'
import os
import subprocess
import sys
from pathlib import Path

CONNECTOR = Path(__file__).resolve().parent.parent / "connector.py"


def test_connector_request_shape(stub):
    env = {
        **os.environ,
        "ANTHROPIC_BASE_URL": stub.base_url,
        "ANTHROPIC_API_KEY": "stub-key",
        "CLINIC_MCP_URL": "https://clinic.example.com/mcp",
    }
    env.pop("CLINIC_MCP_TOKEN", None)
    out = subprocess.run([sys.executable, CONNECTOR], env=env, capture_output=True, text=True, check=True).stdout

    [request] = stub.received
    assert "mcp-client-2025-11-20" in request["headers"]["anthropic-beta"]
    body = request["body"]
    assert body["mcp_servers"] == [{"type": "url", "url": "https://clinic.example.com/mcp", "name": "clinic"}]
    [toolset] = body["tools"]
    assert toolset["default_config"] == {"enabled": False}
    assert sorted(toolset["configs"]) == ["find_clinics", "get_hours"]
    assert "called clinic.get_hours" in out
    assert "stop_reason: end_turn" in out
PY
uv run pytest -q

To run it for real you need an MCP server reachable over HTTPS, such as the clinic server moved to Streamable HTTP with a token check in serve an MCP server over HTTP with authentication. Put CLINIC_MCP_TOKEN=... in the same private env file as your API key, never on the command line, and replace the URL with your server's:

Bash
cd ~/mcp-claude-demo
CLINIC_MCP_URL=https://mcp.example.com/mcp uv run --env-file ~/.config/llm-demo/env connector.py

Know the connector's limits before you choose it:

  • Only MCP tools work through it. Resources and prompts, such as the server's clinics://directory and plan_visit, do not.
  • The server must be public over HTTP, with Streamable HTTP or SSE, and the URL must start with https://. A local stdio server, like the one in this tutorial, cannot be connected directly.
  • For OAuth-protected servers you get the access token and refresh it yourself, then pass it as authorization_token.
  • Each server in mcp_servers must be used by exactly one mcp_toolset. A tool name in configs that the server does not have is only logged as a warning, so a typo in an allowlist switches nothing on, and a typo in a denylist leaves a tool switched on.
  • Data sent through the connector is not covered by zero data retention arrangements.
  • The newer mcp-client-2026-09-15 beta header adds pinning of a server's tool list, so a server changing its tools mid-conversation does not change what Claude sees.

Keep the client-side bridge for local servers, private networks, resources and prompts, or when you want each call to pass through your own checks and logs. The Anthropic SDK also ships helpers for this side (anthropic[mcp], with async_mcp_tool for its tool runner); a bridge you write yourself is where the allowlist, the prefix and the refusals live in one place you can test.

Check it worked

pytest prints 9 passed: the eight bridge tests and the connector request test, which checks the beta header, the mcp_servers entry and the allowlist. With a public MCP server and your API key, the script prints something like called clinic.get_hours with {'clinic_id': 'kumasi-asokwa', 'day': 'saturday'}, then tool result received, Claude's answer and the stop reason.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.