SyntaxPilot
Courses/AI: Zero to Agents/Lesson 29

AI: Zero to Agents · Lesson 29 of 40 · 11 min

MCP: plugging agents into tools

queued

These are the notes for AI episode 29. In episode 28 you gave a model tools, but those tools lived inside one app. Here you'll see why copying tools between apps breaks, count the N×M connectors problem, and invent the fix: MCP, the Model Context Protocol. You'll write a toy MCP-style server that answers JSON-RPC requests (tools/list, tools/call), tell protocol errors from tool errors (isError), add the initialize handshake, and connect one client to any server. Every Python example runs as-is in the SyntaxPilot compiler; outputs and errors are real (Python 3.13). The servers are toys that use the same message shapes as the MCP specification.

Real-life example: the hostel charger drawer

In a hostel room In AI apps
Five phones, each wanting its own charger many AI apps, each needing its own connectors
A drawer of tangled cables, one per phone one custom connector per app × service pair
Everyone moves to one port: USB-C everyone agrees on one protocol: MCP
Your phone the host (the AI app)
The USB-C port, one per cable a client (one connection to one server)
Any charger built to the standard a server (offers tools, data, prompts)

Problem 1: too many connectors

Three AI apps each need four services. If every app writes its own connector for every service:

apps = ["chai bot", "desk assistant", "code editor"]
services = ["prices", "calendar", "UPI payments", "files"]

connectors = [(a, s) for a in apps for s in services]
print("custom connectors to write:", len(connectors))

apps, services = 10, 100        # a real company
print("at scale:", apps * services)

Output:

custom connectors to write: 12
at scale: 1000

Anthropic described this as an "N×M" data integration problem: N apps times M data sources, every pair wired by hand.

Problem 2: copying a tool into another app fails

price_tool = {"name": "price",                 # written for app A
              "description": "Total price in rupees.",
              "input_schema": {"type": "object"}}

def app_b_load(tool):        # app B expects its own format
    return tool["name"], tool["parameters"]

print("App A uses:", price_tool["name"])
print("App B loads:", app_b_load(price_tool))

Output:

App A uses: price
Traceback (most recent call last):
  File "/tmp/tmpgpgyv4zy/main.py", line 9, in <module>
    print("App B loads:", app_b_load(price_tool))
                          ~~~~~~~~~~^^^^^^^^^^^^
  File "/tmp/tmpgpgyv4zy/main.py", line 6, in app_b_load
    return tool["name"], tool["parameters"]
                         ~~~~^^^^^^^^^^^^^^
KeyError: 'parameters'

App A calls the schema input_schema; app B, built by another team, expects parameters. With no shared format, every tool must be rewritten for every app.

The fix: one agreed message format

A protocol is an agreed set of messages. MCP uses JSON-RPC 2.0: every request has jsonrpc, an id, a method and params; every reply carries the same id and either a result or an error. A server only has to answer two tool requests:

  • tools/list: what tools do you have? (discovery)
  • tools/call: run this tool with these arguments.
import json
PRICES = {"chai": 15, "samosa": 20}
TOOLS = [{"name": "price", "description": "Total price in rupees.",
          "inputSchema": {"type": "object",
                          "properties": {"item": {"type": "string"},
                                         "qty": {"type": "integer"}},
                          "required": ["item", "qty"]}}]

def server(raw):                     # the chai shop's MCP-style server
    req = json.loads(raw)
    if req["method"] == "tools/list":
        result = {"tools": TOOLS}
    elif req["method"] == "tools/call":
        a = req["params"]["arguments"]
        total = PRICES[a["item"]] * a["qty"]
        result = {"content": [{"type": "text", "text": str(total)}]}
    return json.dumps({"jsonrpc": "2.0", "id": req["id"], "result": result})

def client(id, method, params={}):   # ANY app can send these
    raw = json.dumps({"jsonrpc": "2.0", "id": id,
                      "method": method, "params": params})
    return json.loads(server(raw))["result"]

print([t["name"] for t in client(1, "tools/list")["tools"]])
print(client(2, "tools/call", {"name": "price",
             "arguments": {"item": "chai", "qty": 2}}))

Output:

['price']
{'content': [{'type': 'text', 'text': '30'}]}

The app learned the tool at run time, so adding a tool to the server needs no change in the app.

The real messages (from the MCP specification)

A tools/call request:

{"jsonrpc": "2.0", "id": 2, "method": "tools/call",
 "params": {"name": "get_weather", "arguments": {"location": "New York"}}}

and its reply:

{"jsonrpc": "2.0", "id": 2,
 "result": {"content": [{"type": "text", "text": "Current weather in New York: ..."}],
            "isError": false}}

A tools/list reply gives each tool's name, an optional title, a description and an inputSchema (JSON Schema, as in episode 28).

 User ──► Host (AI app + model)
             ├── Client 1 ──► Server: chai prices   (tools: price)
             └── Client 2 ──► Server: calendar      (tools: free_slots)

The model never talks to a server directly: the host gives the model the tool list, the model picks a tool, and the client sends tools/call.

Problem 3: two kinds of errors

PRICES = {"chai": 15, "samosa": 20}

def server(req):
    if req["method"] != "tools/call":
        return {"error": {"code": -32601, "message": "Method not found"}}
    p = req["params"]
    if p["name"] != "price":                       # protocol error
        return {"error": {"code": -32602,
                          "message": f"Unknown tool: {p['name']}"}}
    item = p["arguments"]["item"]
    if item not in PRICES:                         # the tool itself failed
        return {"result": {"isError": True, "content": [{"type": "text",
                "text": f"'{item}' is not on the menu: {list(PRICES)}"}]}}
    return {"result": {"isError": False, "content": [{"type": "text",
            "text": str(PRICES[item] * p["arguments"]["qty"])}]}}

for name, item in [("price", "chai"), ("prize", "chai"), ("price", "pizza")]:
    req = {"jsonrpc": "2.0", "id": 1, "method": "tools/call",
           "params": {"name": name, "arguments": {"item": item, "qty": 2}}}
    r = server(req)
    if "error" in r: print(f"{name} {item}: protocol error", r["error"])
    else: print(f"{name} {item}: isError={r['result']['isError']},",
                r["result"]["content"][0]["text"])

Output:

price chai: isError=False, 30
prize chai: protocol error {'code': -32602, 'message': 'Unknown tool: prize'}
price pizza: isError=True, 'pizza' is not on the menu: ['chai', 'samosa']
Kind When Who reads it Shape
Protocol error the request itself is broken: unknown tool, invalid arguments the app JSON-RPC error, e.g. code -32602, Unknown tool: prize
Tool execution error the tool ran but failed: API down, item not on the menu the model a normal result with isError: true

An isError result goes back to the model like any tool result, so it can read the message and try again (samosa instead of pizza).

Problem 4: say hello first (the handshake)

Apps and servers are updated by different people. Before anything else, the client sends initialize with the protocol version it speaks and its capabilities; the server replies with its own version, capabilities and serverInfo; then the client sends the notification notifications/initialized. Only then does normal work start.

SUPPORTED = ["2025-06-18", "2025-03-26"]
ready = False

def server(req):
    global ready
    if req["method"] == "initialize":
        want = req["params"]["protocolVersion"]
        if want not in SUPPORTED:
            return {"error": {"code": -32602,
                    "message": "Unsupported protocol version",
                    "data": {"supported": SUPPORTED, "requested": want}}}
        ready = True
        return {"result": {"protocolVersion": want,
                "capabilities": {"tools": {}},
                "serverInfo": {"name": "chai-shop", "version": "1.0.0"}}}
    if not ready:
        return {"error": {"code": -32002, "message": "Not initialized"}}
    return {"result": {"tools": ["price"]}}

def show(n, r):
    print(n, r["error"]["message"] if "error" in r
          else r["result"].get("protocolVersion", r["result"]))

show(1, server({"method": "tools/list"}))
show(2, server({"method": "initialize", "params": {"protocolVersion": "1.0.0"}}))
show(3, server({"method": "initialize",
                "params": {"protocolVersion": "2025-06-18"}}))
show(4, server({"method": "tools/list"}))

Output:

1 Not initialized
2 Unsupported protocol version
3 2025-06-18
4 {'tools': ['price']}

(The toy's "Not initialized" refusal is our own rule; the spec says clients should not send requests other than pings before the server has answered initialize. The Unsupported protocol version error with code -32602 is the spec's own example.)

The payoff: one client, any server

def chai_server(method, params={}):          # server 1: prices
    if method == "tools/list": return [{"name": "price"}]
    return {"chai": 15, "samosa": 20}[params["item"]] * params["qty"]

def calendar_server(method, params={}):      # server 2: bookings
    if method == "tools/list": return [{"name": "free_slots"}]
    return ["7 pm", "9 pm"]

def connect(server):          # ONE client function for EVERY server
    tools = [t["name"] for t in server("tools/list")]
    print("found tools:", tools)
    return tools

for srv, args in [(chai_server, {"item": "samosa", "qty": 3}),
                  (calendar_server, {"day": "Saturday"})]:
    tool = connect(srv)[0]
    print(" ", tool, "->", srv("tools/call", args))

apps, services = 10, 100
print("custom:", apps * services, "| one standard:", apps + services)

Output:

found tools: ['price']
  price -> 60
found tools: ['free_slots']
  free_slots -> ['7 pm', '9 pm']
custom: 1000 | one standard: 110

Each app implements the protocol once and each service ships one server: N + M (110) instead of N × M (1,000). You just invented MCP.

Tools, resources and prompts

Feature What it is Who decides to use it Example
Tools functions the model can call the model ("model-controlled") price, free_slots
Resources data the app can read the app the menu file
Prompts ready-made templates the user "Summarise today's orders"

During initialize, the server lists which of these capabilities it supports.

Transports: how messages travel

  • stdio: the host starts the server as a program on your machine; messages go through its standard input and output. Good for local things like your files.
  • HTTP: the server runs online, e.g. a company's calendar service.

The JSON-RPC messages are the same either way.

From one company's idea to a shared standard

Date Event
25 Nov 2024 Anthropic introduces MCP (it reuses ideas from the Language Server Protocol)
March 2025 OpenAI adopts MCP, including in the ChatGPT desktop app
9 Dec 2025 Anthropic donates MCP to the new Agentic AI Foundation under the Linux Foundation, co-founded by Anthropic, Block and OpenAI
By Dec 2025 10,000+ active public MCP servers; used by ChatGPT, Cursor, Gemini, Microsoft Copilot and VS Code

Stay safe

  • Tool descriptions go straight into the model's input. In April 2025, Invariant Labs described tool poisoning: malicious instructions hidden in a tool description that the model reads but the user never sees.
  • Install only servers you trust.
  • The spec says there should always be a human in the loop who can deny tool invocations, with confirmation prompts for sensitive operations.
  • Servers must validate all tool inputs (episode 28).

Glossary

Term Meaning Example from this episode
N×M problem every app needs a custom connector for every service 10 apps × 100 services = 1,000
Protocol an agreed format for messages between programs USB-C for software
MCP Model Context Protocol: an open standard connecting AI apps to tools and data introduced 25 Nov 2024
Host the AI application that contains the model a chatbot, a code editor
Client one connection from the host to one server connect(server)
Server a program that offers tools, resources or prompts chai_server
JSON-RPC 2.0 a remote procedure call format written in JSON {"jsonrpc": "2.0", "id": 1, "method": ...}
Request id links a reply to its request "id": 2
Method the name of what you're asking for "tools/call"
tools/list asks a server which tools it has (discovery) returns price
tools/call asks a server to run a tool {"name": "price", "arguments": {...}}
inputSchema the tool's JSON Schema for its arguments {"type": "object", ...}
Content block one piece of a result: text, image, ... {"type": "text", "text": "30"}
Protocol error a JSON-RPC error for a broken request -32602 Unknown tool: prize
isError flag on a result when the tool itself failed pizza not on the menu
initialize the first request: version + capabilities (the handshake) "protocolVersion": "2025-06-18"
Capabilities the optional features each side supports {"tools": {}}
notifications/initialized the client's "ready" message after the handshake sent once
Resource data a server lets the app read the menu file
Prompt (MCP) a ready-made template offered by a server "Summarise today's orders"
Transport how messages travel stdio, HTTP
stdio standard input/output of a local program a local files server
Tool poisoning hidden instructions inside a tool description a malicious server
Human in the loop a person who can approve or deny actions a confirm dialog

Common mistakes

Mistake What you see Why Fix
Each app with its own tool format KeyError: 'parameters' no shared standard speak one protocol: MCP
Calling a tool that doesn't exist -32602 Unknown tool: prize broken request (protocol error) only use names from tools/list
Treating a tool failure as a crash the agent stops tool errors are normal results return isError: true; let the model retry
Skipping the handshake Not initialized / Unsupported protocol version no agreed version send initialize first
Installing any server you find hidden instructions reach the model tool poisoning trusted servers only; human approval

Mini project: a mini MCP router

Write a server with three tools (menu, price, book_table), the initialize handshake, tools/list, tools/call, protocol errors for unknown tools and isError results for bad arguments. Then write one connect() client that lists and calls every tool.

Practice

1. Add a menu tool to the chai server, and make price return isError when qty is 0.

Solution
PRICES = {"chai": 15, "samosa": 20}
TOOLS = [{"name": "price", "description": "Total price in rupees."},
         {"name": "menu", "description": "List the items on the menu."}]

def server(req):
    if req["method"] == "tools/list":
        return {"result": {"tools": TOOLS}}
    name, args = req["params"]["name"], req["params"]["arguments"]
    if name == "menu":
        text = ", ".join(PRICES)
    elif name == "price":
        if args["qty"] < 1:
            return {"result": {"isError": True, "content": [
                {"type": "text", "text": "qty must be at least 1"}]}}
        text = str(PRICES[args["item"]] * args["qty"])
    else:
        return {"error": {"code": -32602, "message": f"Unknown tool: {name}"}}
    return {"result": {"isError": False, "content": [{"type": "text", "text": text}]}}

call = lambda n, a: server({"method": "tools/call", "params": {"name": n, "arguments": a}})
print([t["name"] for t in server({"method": "tools/list"})["result"]["tools"]])
print(call("menu", {}))
print(call("price", {"item": "chai", "qty": 0}))

Output:

['price', 'menu']
{'result': {'isError': False, 'content': [{'type': 'text', 'text': 'chai, samosa'}]}}
{'result': {'isError': True, 'content': [{'type': 'text', 'text': 'qty must be at least 1'}]}}

2. Write a third server, weather, and connect all three with one connect().

Solution
def chai_server(method, params={}):
    if method == "tools/list": return [{"name": "price"}]
    return {"chai": 15, "samosa": 20}[params["item"]] * params["qty"]

def calendar_server(method, params={}):
    if method == "tools/list": return [{"name": "free_slots"}]
    return ["7 pm", "9 pm"]

def weather_server(method, params={}):
    if method == "tools/list": return [{"name": "forecast"}]
    return f"{params['city']}: 31 C, clear"      # toy data

def connect(server):
    return [t["name"] for t in server("tools/list")]

calls = [(chai_server, {"item": "chai", "qty": 2}),
         (calendar_server, {"day": "Saturday"}),
         (weather_server, {"city": "Pune"})]
for srv, args in calls:
    tool = connect(srv)[0]
    print(tool, "->", srv("tools/call", args))

Output:

price -> 30
free_slots -> ['7 pm', '9 pm']
forecast -> Pune: 31 C, clear

3. Five AI apps and twenty services all speak MCP. How many integrations?

Answer

5 clients + 20 servers = 25, instead of 5 × 20 = 100 custom connectors.

Quick quiz 1

tools/call for price with item: "pizza": price exists, but pizza isn't on the menu. What comes back?

Answer

B: a result with isError: true. The request was valid; the tool itself failed, and the message goes back to the model.

Quick quiz 2

5 apps, 20 services, everyone speaks MCP. How many integrations?

Answer

B: 25 (N + M).

Interview questions

  1. What problem does MCP solve? The N×M integration problem: without a standard, every AI app needs a custom connector for every tool or data source. With MCP, each app implements a client once and each service ships one server.
  2. Host vs client vs server? The host is the AI app with the model; it runs one client per server connection; a server exposes tools, resources and prompts.
  3. What message format does MCP use? JSON-RPC 2.0: requests with jsonrpc, id, method, params; replies with the same id and a result or an error.
  4. Protocol error vs isError? Protocol errors (unknown tool, invalid arguments) are JSON-RPC errors for the app; tool execution errors are results with isError: true that the model can read and recover from.
  5. What happens during initialization? The client sends initialize with its protocol version and capabilities, the server answers with its version, capabilities and info, then the client sends notifications/initialized.
  6. Tools vs resources vs prompts? Tools are model-controlled functions; resources are data the app reads; prompts are templates a user picks.
  7. Main security risks? Untrusted servers and tool poisoning (hidden instructions in descriptions). Use trusted servers, keep a human in the loop, validate inputs.

Summary

  • N apps × M services = too many custom connectors.
  • MCP is one protocol: hosts run clients that talk to servers.
  • Messages are JSON-RPC 2.0: tools/list to discover, tools/call to run.
  • Protocol errors for broken requests; isError: true for tool failures the model can fix.
  • initialize first: agree on a version and capabilities.
  • Servers offer tools, resources, prompts over stdio or HTTP.
  • Trust carefully: tool poisoning exists; keep a human in the loop.

Next: episode 30, Memory: how an agent remembers you tomorrow.

Sources: Wikipedia, "Model Context Protocol" (en.wikipedia.org/wiki/Model_Context_Protocol); MCP specification 2025-03-26, "Lifecycle" (modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle); MCP specification 2025-06-18, "Tools" (modelcontextprotocol.io/specification/2025-06-18/server/tools); Anthropic, "Donating the Model Context Protocol and establishing the Agentic AI Foundation", 9 Dec 2025 (anthropic.com/news/donating-the-model-context-protocol-and-establishing-of-the-agentic-ai-foundation).