MCP servers and clients · Chapter 1 of 16

Why MCP

By the end of this chapter you can explain what problem the Model Context Protocol solves, name the three parts of every MCP setup (host, client, server), and connect to a real MCP server from Python, list its tools and call one. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: The protocol
  • 4 tasks
  • Python
  • Free chapter

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.

Why you need this

Bazaar Bhai runs 40 kirana stores across Jaipur, from Malviya Nagar to Amer. Every evening each store counts its shelves, and the counts land in one SQLite database, next to the prices, the suppliers and the purchase orders. Rajat, the owner, has caught the AI bug: he wants an assistant he can ask "how much masoor dal is left at Vaishali Nagar?", Gopal's store managers want a WhatsApp bot, and the suppliers want a portal that tells them what to deliver.

A model cannot answer any of that on its own. It knows what text usually says, not what is on Bazaar Bhai's shelves. Ask the lab model (it answers inside your lab, with the same API as OpenAI's) with nothing else in the request:

$ lab ask "Can a customer return a packet of atta after two weeks at Bazaar Bhai?"
Sure. You can return any product within 30 days with the bill for a full refund.

Confident, and wrong: the store policy says 7 days. Every AI app needs Bazaar Bhai's data put in front of the model, and each app is being built by a different team. Simran, the senior engineer, has seen where that goes. This chapter makes you feel it in code, then shows the way out.

The lesson

One question, many shapes

Every app starts with the same question: how many units of a product does a store have? It is one SQL query:

>>> stock_level("BB02", "P017")      # Masoor Dal 1 kg, Vaishali Nagar
46
>>> stock_level("BB03", "P044")      # Mansarovar does not carry it
>>>

The trouble starts when an app wants it. Rajat's assistant is built on OpenAI's API, which takes a tool description: a name, a sentence saying what it does, and a JSON schema of its parameters. The model reads the description and, when a question needs it, asks for the tool by name with arguments. Here is one for prices, offered with a question:

PRICE_TOOL = {
    "type": "function",
    "function": {
        "name": "price_of",
        "description": "Bazaar Bhai's selling price and the MRP of one product.",
        "parameters": {
            "type": "object",
            "properties": {"product_id": {"type": "string"}},
            "required": ["product_id"],
        },
    },
}
Function(arguments='{"product_id":"P017"}', name='price_of')

The model did not run anything. It asked; the app must run price_of and send the result back. Gopal's WhatsApp bot wants something else entirely: a function that takes a text command and returns a reply. The suppliers' portal, built by an agency, wants a dictionary in and a dictionary out with its own key names. Three apps, three wrappers around one query, and each wrapper belongs to whichever team owns that app.

N times M

Now count. Bazaar Bhai's data lives in several places: stock, prices, suppliers and orders in SQLite, sales in a CSV export, the policy in a Markdown file. Rajat's list (/workspace/data/integrations.json) already has five apps. Without a standard, every app needs its own integration with every source it uses: with 3 apps and 4 sources, that can be 12 pieces of glue, each written, tested, secured and kept up to date separately. Add a sixth app and you write its glue for every source again; change the stock table and you fix it in every app.

This is the problem the Model Context Protocol (MCP) was created for, by Anthropic in late 2024, and since adopted across the industry. It is the same move USB made for devices: agree on one plug. Each data source is exposed once, as an MCP server. Each app speaks MCP once, as a client. Any client can then use any server, so 3 apps and 4 sources need 3 + 4 = 7 pieces, and a sixth app costs one, not four.

What MCP standardises

MCP is a protocol, not a library: a set of agreed messages, so that a server written in Python works with a client written in TypeScript. It fixes:

  • The messages: JSON-RPC 2.0 requests, responses and notifications (chapter 2 writes them by hand).
  • The transports: stdio, where the client starts the server as a subprocess and they talk over its stdin and stdout, for local servers; and streamable HTTP, for servers running as a service (chapter 12).
  • Discovery: a client asks a server what it offers (tools/list) and gets names, descriptions and JSON schemas, so nothing is hard-coded.
  • The building blocks: tools (functions the model can ask to run), resources (data the app can read, like a price list) and prompts (reusable templates a user can pick).
  • Versions: each side says which protocol version it speaks. The current one is dated 2026-07-28; older clients connect with a handshake (chapter 3).

Here is what actually crosses a server's stdin and stdout when a client calls stock_level, one JSON message per line (an older client, after its handshake):

-> {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"stock_level","arguments":{"store_id":"BB02","product_id":"P017"}}}
<- {"jsonrpc":"2.0","id":2,"result":{"content":[{"text":"{\n  \"store_id\": \"BB02\",\n  \"product_id\": \"P017\",\n  \"units\": 46\n}","type":"text"}],"isError":false,"structuredContent":{"store_id":"BB02","product_id":"P017","units":46}}}

The result carries the answer twice: as text, which any model can read, and as structuredContent, which code can use without parsing.

Hosts, clients and servers

Three words, used precisely from now on:

  • The host is the AI application the user talks to: Rajat's assistant, Claude Desktop, an IDE, an agent you write. It holds the conversation and calls the model.
  • A client lives inside the host and holds one connection to one server. A host that uses three servers runs three clients.
  • A server is a program that exposes tools, resources and prompts: your bazaar-stock, a GitHub server, a file system server.

The model never speaks MCP. The host lists the server's tools, turns them into tool descriptions the model understands, and runs the calls the model asks for through its client (chapter 9 builds exactly that).

Your first MCP client

This chapter's folder has stock_server.py, a finished MCP server with one tool. Run it alone and it waits in silence: it talks to whichever client started it. lab tools stock_server.py starts it and lists its tools:

stock_level  Units of one product in one store, from the evening stock count.
    store_id: string
    product_id: string

The official Python SDK, the mcp package (version 2), has a Client that does the same from your code. You tell it how to start the server, and it starts it, agrees on a protocol version and hands you a connected client:

import asyncio, sys
from mcp import Client, StdioServerParameters

async def main():
    server = StdioServerParameters(command=sys.executable, args=["stock_server.py"])
    async with Client(server) as client:
        tools = await client.list_tools()
        print([tool.name for tool in tools.tools])

asyncio.run(main())
['stock_level']
  • sys.executable is the Python running your file, so the server runs with the same packages.
  • Everything is async: a client waits on another process. async with starts the server and stops it when the block ends.
  • await client.call_tool(name, arguments) calls a tool. Its result has .content (the text parts) and .structured_content (the dictionary).

What MCP does not do

It does not make the model smarter, and it does not replace your database: the server still runs the same SQL. It does not decide who may do what either. A purchase-order tool exposed to every client is a risk, and Nisha, who looks after security, will have questions (chapter 13).

Your turn

Write the stock lookup in task 1, then wire it into the three apps in apps.py in task 2, and notice how much of task 2 is glue. Task 3 reaches the same stock through the MCP server with no glue at all. The interview question counts Bazaar Bhai's real integrations: watch for the app that lists a source twice and the source nobody needs.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    stock.py: one question, one function

    Every app Rajat wants asks the same question first. In stock.py, write stock_level(store_id, product_id): it looks up the pair in the stock table of /workspace/data/bazaar.db and returns the quantity as an int.

    It returns None when the store does not carry the product, or the store does not exist.

    For example, stock_level("BB02", "P017") returns 46.

  2. Task 2

    three_apps.py: three apps, three integrations

    Read apps.py: three teams' apps, each wanting stock_level in its own shape. In three_apps.py, import stock_level from stock.py and write:

    OWNER_TOOL, a tool description in OpenAI's format: type function, a function named stock_level with a description, and parameters with two required string properties, store_id and product_id.

    manager_command(text), which takes a message like /stock BB07 P013 and returns BB07 P013: 18 units, or BB07 P013: not stocked when the store does not carry the product.

    supplier_lookup(request), which takes {"store": "BB07", "sku": "P013"} and returns {"store": "BB07", "sku": "P013", "units": 18}, with 0 units when the store does not carry the product.

    When run, it prints what each app returns, one per line: owner_assistant with OWNER_TOOL, stock_level and the question How many units of P020 are left at BB03?; managers_bot with /stock BB21 P044; supplier_portal with store BB33 and sku P101.

  3. Task 3

    first_client.py: the same stock, over MCP

    stock_server.py offers stock_level once, as an MCP server. In first_client.py, use the mcp package's Client to start it over stdio (with sys.executable) and print three lines:

    Connected to <server name> (protocol <version>), with the name and protocol version the client received;

    one line per tool the server lists: its name, a colon, a space and its description;

    the result of calling stock_level for store BB12 and product P027, as BB12 P027: 17 units, taken from the result's structured content.

    Do not open the database in this file.

  4. Task 4 · interview question

    Interview: count.py, N times M

    /workspace/data/integrations.json lists Bazaar Bhai's apps and the sources each one needs. In count.py, write integrations(data), which returns a tuple: the number of integrations without MCP (one per app and source it needs), the number of clients with MCP (one per app that needs something) and the number of servers (one per source that something needs).

    A source listed twice by one app counts once. When run, it reads the file and prints two lines, for example:

    Without MCP: 12 integrations

    With MCP: 3 clients + 4 servers = 7

What you will learn

  • The integration problem: why N apps and M data sources become N times M pieces of glue code.
  • What MCP standardises: one protocol for exposing tools, data and prompts to any AI app.
  • Hosts, clients and servers: who does what.
  • Your first MCP client, with the official mcp package.

More in The protocol

Build "Why MCP" yourself

Bazaar Bhai, a chain of 40 kirana stores in Jaipur, exposes its stock and orders once, to every AI tool. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.