esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • Book a callContact
  • Download ResumeContact
Let’s talk

I’ll build the agent for it.

AI engineering / Advanced / 03.05

Building an MCP Client

Connect to a server, list its tools, hand them to a model, run the ask, call, answer loop, and stay safe when things go wrong.

14 min readFree

The app that plugs in

The last lesson, Building an MCP Server, ended with a promise: next, building an MCP client, letting your app use any server. Here it is.

A server sits and waits. Nothing happens until something asks. That something is the client. If the server is a shop, the client is the shopper who asks what is for sale and buys what the model decides it needs.

By the end you will know how a tool list becomes something a model understands, how the ask, call, answer loop runs, and what to do when a tool fails, hangs or is risky. You will run a small client of your own.

Key words

Client
The part of your app that talks to one MCP server. It sends requests and reads the answers.
Tool definition
A server's description of one tool: its name, what it does, and what inputs it takes.
Function calling
A way for a model to answer with "please run this function with these inputs" instead of plain text. Your code runs it and sends the result back.
Tool loop
The cycle of: the model asks for a tool, your code runs it, the result goes back to the model, repeat until the model answers in words.
Timeout
A limit on how long you wait. If no answer comes in time, you stop waiting.

What a client does

The official quickstart opens with its goal: "In this tutorial, you'll learn how to build an LLM-powered chatbot client that connects to MCP servers."

The Specification overview calls clients connectors inside the host, the app the person uses. A client does not think. The model thinks. The client connects to one server, asks what tools it has, carries the model's requests across, and brings answers back.

The MCP Python SDK has this client side built in. Its README says you can use it to "Build MCP clients that connect to any MCP server", and that it speaks every standard transport: stdio, Streamable HTTP, and SSE. A transport is the road the messages travel on.

Connecting: two ways to say hello

A client first connects. The protocol changed recently, so know both versions. The MCP lesson showed this too.

  1. 1

    Revision 2025-11-25 and older

    The client opens with an "initialize" request. The specification says that request carries the protocol version the client supports, its capabilities and information about itself. After the server answers, the client sends a "notifications/initialized" notification.

  2. 2

    Revision 2026-07-28 (the latest)

    The Versioning and compatibility page says: "There is no negotiation handshake. Every request carries its protocol version, and the server accepts or rejects each request independently". The version rides in a field called _meta on every request. The page calls this kind "modern" and the old kind "legacy", and says a modern client cannot talk to a legacy-only server.

The Tools page names three _meta fields: protocol version, client information and client capabilities. Every request must include the required ones. On the Versioning page, a server that does not know the version asked for must answer with an UnsupportedProtocolVersionError listing the versions it does support, and the client should pick one and retry.

The old way is a phone call that starts with "hello, can you hear me?". The new way is a letter with your return address on every page, so no greeting is needed. The code below uses the older hello, as the MCP lesson did, so the steps are easy to see.

Tip

Check which revision your server speaks before you build.

Listing tools and translating them

After connecting, the client asks "tools/list". Each tool in the answer has a name, a description and an inputSchema, a written description of the inputs it expects. A model needs the same three things in order to ask for a tool.

The Function Calling lesson showed that each model vendor has its own way to describe a function. MCP is one agreed shape on the server side, the model has its own on its side, and the client translates between them.

  1. 1

    Ask

    Send tools/list and read the list from the answer.

  2. 2

    Translate

    For each tool, copy the name, the description and the input schema into the shape your model expects. The official quickstart does exactly this: it builds a list of entries with "name", "description" and "input_schema" and hands the list to the model on every call.

  3. 3

    Keep a map

    Remember which server each tool came from.

One detail: tool names should be unique inside one server, but a client joining several servers can meet two tools with the same name. The Tools page suggests "prefixing tool names with a server identifier".

The loop

This is the heart of any client. The model does not run tools. It asks, and your code does the work.

  1. 1

    Send the question and the tools

    Give the model the user's message and the translated tool list.

  2. 2

    Read the reply

    If the model answers in words, you are done. If it asks for a tool, take its tool name and inputs.

  3. 3

    Check with the user

    If the call is risky, show it and wait for a yes.

  4. 4

    Call the server

    Send tools/call with the name and inputs. Read the content in the answer.

  5. 5

    Send the result back

    Add it to the conversation as a tool result, and ask the model again. Go to step 2.

Notice the limit. A model can keep asking for tools. The quickstart sets a cap, MAX_TOOL_TURNS, and its text says the loop runs "until Claude answers without one or MAX_TOOL_TURNS is reached, at which point the client reports that it stopped". A cap stops a confused model from running up a bill.

The official client, in short

Here is the start of the official Python quickstart's query function, copied as published. It lists the server's tools and changes them into the model's format. It needs the vendor's key and network, so it is shown without output and was not run here.

Text
# From the Build an MCP client quickstart (Python tab), shown without its output (not run here)
async def process_query(client: Client, query: str) -> str:
    """Process a query using Claude and available tools"""
    messages = [
        {
            "role": "user",
            "content": query
        }
    ]

    tool_list = await client.list_tools()
    available_tools = [{
        "name": tool.name,
        "description": tool.description,
        "input_schema": tool.input_schema
    } for tool in tool_list.tools]

The quickstart says Client "is the single object your program talks to the server through". It also says that entering the async with block "launches the server and agrees a protocol version with it", so the real SDK does the hello for you.

Build a tiny client yourself

Now a version you can run for free, with only the Python standard library. server is a stand-in for an MCP server: a plain function that answers requests. McpClient is the client. fake_model is a stand-in for a language model.

Be clear about what is fake. fake_model always asks for the double tool with 4, then repeats the answer back. It is a stand-in so the code runs free. A real model is slower, costs money for every token it reads and writes, can give a different answer each run, and can fail or refuse. The stand-in server copies the message shapes and skips most of the rules.

The code runs three small stories: connect and list tools, run one question through the loop, and meet trouble.

Python
import json

TOOLS = [{
    "name": "double",
    "description": "Double a number",
    "inputSchema": {"type": "object", "properties": {"n": {"type": "number"}}, "required": ["n"]},
}]

def server(request):
    """Stand-in for an MCP server: answers one request, no network."""
    if "id" not in request:
        return None  # a notification gets no reply
    method, params = request["method"], request.get("params", {})
    if method == "initialize":
        result = {"protocolVersion": "2025-11-25", "capabilities": {"tools": {}}}
    elif method == "tools/list":
        result = {"tools": TOOLS}
    elif method == "tools/call" and params["name"] == "double":
        n = params["arguments"].get("n")
        if isinstance(n, (int, float)):
            result = {"content": [{"type": "text", "text": str(n * 2)}], "isError": False}
        else:
            result = {"content": [{"type": "text", "text": "n must be a number"}], "isError": True}
    elif method == "tools/call" and params["name"] == "slow":
        raise TimeoutError("no answer in time")
    else:
        return {"jsonrpc": "2.0", "id": request["id"], "error": {"code": -32601, "message": "Method not found"}}
    return {"jsonrpc": "2.0", "id": request["id"], "result": result}

class McpClient:
    def __init__(self, transport):
        self.transport, self.next_id = transport, 0

    def send(self, method, params=None, notify=False):
        message = {"jsonrpc": "2.0", "method": method, "params": params or {}}
        if not notify:
            self.next_id += 1
            message["id"] = self.next_id
        print("  client ->", json.dumps(message))
        try:
            reply = self.transport(message)
        except TimeoutError:  # a real client sets a timer; here the stand-in raises
            print("  client: gave up waiting, no reply")
            return {"result": {"content": [{"type": "text", "text": "tool timed out"}], "isError": True}}
        if reply:
            print("  server ->", json.dumps(reply))
        return reply

    def connect(self):
        self.send("initialize", {"protocolVersion": "2025-11-25", "capabilities": {}})
        self.send("notifications/initialized", notify=True)

    def list_tools(self):
        return self.send("tools/list")["result"]["tools"]

    def call_tool(self, name, arguments, ask_user):
        if not ask_user(name, arguments):
            return {"content": [{"type": "text", "text": "the user said no"}], "isError": True}
        return self.send("tools/call", {"name": name, "arguments": arguments})["result"]

def to_function_schema(tool):
    """MCP tool definition -> a generic function-calling entry."""
    return {"type": "function", "function": {"name": tool["name"],
            "description": tool["description"], "parameters": tool["inputSchema"]}}

def fake_model(messages, tools):
    """Stand-in model: always asks for double(4), then reads the answer back."""
    if messages[-1]["role"] == "user":
        return {"role": "assistant", "tool_calls": [{"id": "call_1", "name": "double", "arguments": {"n": 4}}]}
    return {"role": "assistant", "content": "Double 4 is " + messages[-1]["content"]}

def ask_user(name, arguments):
    print("  ask user: run", name, "with", json.dumps(arguments), "? -> yes")
    return True

print("1. connect and list tools")
client = McpClient(server)
client.connect()
tools = [to_function_schema(t) for t in client.list_tools()]
print("  function schema:", json.dumps(tools))

print("2. run one question")
messages = [{"role": "user", "content": "What is double 4?"}]
for turn in range(5):  # a cap, so the loop cannot run forever
    reply = fake_model(messages, tools)
    print("  model ->", json.dumps(reply))
    messages.append(reply)
    if "tool_calls" not in reply:
        break
    for call in reply["tool_calls"]:
        result = client.call_tool(call["name"], call["arguments"], ask_user)
        text = " ".join(part["text"] for part in result["content"])
        messages.append({"role": "tool", "tool_call_id": call["id"], "content": text})
print("  final answer:", messages[-1]["content"])

print("3. bad input, a timeout, and a user who says no")
print("  result:", client.call_tool("double", {"n": "four"}, ask_user)["content"][0]["text"])
print("  result:", client.call_tool("slow", {}, ask_user)["content"][0]["text"])
print("  result:", client.call_tool("double", {"n": 1}, lambda name, arguments: False)["content"][0]["text"])

Output

1. connect and list tools
  client -> {"jsonrpc": "2.0", "method": "initialize", "params": {"protocolVersion": "2025-11-25", "capabilities": {}}, "id": 1}
  server -> {"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-11-25", "capabilities": {"tools": {}}}}
  client -> {"jsonrpc": "2.0", "method": "notifications/initialized", "params": {}}
  client -> {"jsonrpc": "2.0", "method": "tools/list", "params": {}, "id": 2}
  server -> {"jsonrpc": "2.0", "id": 2, "result": {"tools": [{"name": "double", "description": "Double a number", "inputSchema": {"type": "object", "properties": {"n": {"type": "number"}}, "required": ["n"]}}]}}
  function schema: [{"type": "function", "function": {"name": "double", "description": "Double a number", "parameters": {"type": "object", "properties": {"n": {"type": "number"}}, "required": ["n"]}}}]
2. run one question
  model -> {"role": "assistant", "tool_calls": [{"id": "call_1", "name": "double", "arguments": {"n": 4}}]}
  ask user: run double with {"n": 4} ? -> yes
  client -> {"jsonrpc": "2.0", "method": "tools/call", "params": {"name": "double", "arguments": {"n": 4}}, "id": 3}
  server -> {"jsonrpc": "2.0", "id": 3, "result": {"content": [{"type": "text", "text": "8"}], "isError": false}}
  model -> {"role": "assistant", "content": "Double 4 is 8"}
  final answer: Double 4 is 8
3. bad input, a timeout, and a user who says no
  ask user: run double with {"n": "four"} ? -> yes
  client -> {"jsonrpc": "2.0", "method": "tools/call", "params": {"name": "double", "arguments": {"n": "four"}}, "id": 4}
  server -> {"jsonrpc": "2.0", "id": 4, "result": {"content": [{"type": "text", "text": "n must be a number"}], "isError": true}}
  result: n must be a number
  ask user: run slow with {} ? -> yes
  client -> {"jsonrpc": "2.0", "method": "tools/call", "params": {"name": "slow", "arguments": {}}, "id": 5}
  client: gave up waiting, no reply
  result: tool timed out
  result: the user said no

Reading the output

Story one shows the old hello: an initialize request, its answer, then a notification with no reply. Then tools/list returns one tool, and the client changes it into a function schema. Look closely: inputSchema became "parameters". Everything else was copied. That one rename is the whole translation here.

Story two is the loop. The stand-in model asked for double with 4. The client asked the user first (it printed "ask user"), then sent tools/call. The server answered with a content list holding the text 8. The client turned that into a tool message, called the model again, and the model said "Double 4 is 8". The model ran twice.

When things go wrong

Tools fail and servers hang. The Tools page names two kinds of error, and they need different handling.

  • Protocol errors

    A problem with the request itself: an unknown tool, a malformed request, or a server error. They come back as a standard JSON-RPC error. The page says clients may give these to the model, though they are less likely to lead to a fix.

  • Tool execution errors

    The tool ran and failed: an API failure, input in the wrong format, a business rule. They come back as a normal result with isError set to true. The page says clients should give these to the model so it can correct itself.

  • Silence

    No answer at all. The specification says to set a timeout on every request.

In story three, the input n was the word "four", so the stand-in server sent back isError true and "n must be a number". The client passed that text on. A real model could read it and try again with a number. The quickstart does the same: its notes say passing the error flag on "lets Claude read the message and try something else".

Quick check

A tool returns isError true with "date must be in the future". What should your client do?

Timeouts

A timeout is like not standing at a bus stop for ever. The Lifecycle page of specification 2025-11-25 says implementations should set timeouts on all sent requests, "to prevent hung connections and resource exhaustion". When no answer arrives in time, the sender should send a cancellation notification for that request and stop waiting. The Tools page also lists "Implement timeouts for tool calls" as something clients should do.

In the code, the stand-in raises a TimeoutError for a tool called slow. The client catches it and turns the failure into a tool result. A real client would run a real timer and send the cancellation. The point is the shape: a stuck tool becomes a message the model can read, not a frozen app.

Asking the user first

Some tools only read. Others send email, spend money or delete files. The client is the last gate before the server acts.

The Tools page says there should always be a human in the loop with the ability to deny tool invocations. Under security, it says clients should prompt for user confirmation on sensitive operations, show tool inputs to the user before calling the server to avoid malicious or accidental data exfiltration, validate tool results before passing them to the model, and log tool usage. (Exfiltration means data being quietly sent out.)

The page also says clients must treat tool annotations, the hints a server attaches to describe its tools, as untrusted unless they come from trusted servers. A server saying "harmless" is not a reason to skip the question.

  1. 1

    Show what will happen

    The tool name and its exact inputs, in words a person understands.

  2. 2

    Wait for a clear yes

    No yes means no. In story three, the last call passes a function that always says no, and the client answers "the user said no" without sending anything.

  3. 3

    Tell the model

    A refusal is a result too. Send it back so the model can pick another route.

What to remember

  • Connect, list, carry

    Open the line, translate tool definitions for the model, and move messages between model and server.

  • A capped loop

    Model asks, client calls, result goes back. Stop after a set number of turns.

  • Plan for trouble

    Hand tool errors to the model, set timeouts, ask the user before risk.

Quick check

In the loop, who actually runs the tool?

Next: connecting to MCP servers, local and remote.

Sources

How is this lesson?

Last updated on 16 November 2026

Learn with me

Every lesson is free. I add new ones as I learn. Have a question, or want help with your own work? Book a short call.