Skills101

AdvancedAI Engineering — Building Apps with Large Language Models · Lesson 15 of 15 · Updated ·

Model Context Protocol (MCP) — Connecting LLM Apps to Tools and Data Through One Standard

In the tools lesson you wrote tool definitions and a tool loop for one app. Now imagine ten AI apps (a chat app, a code editor, a help-desk bot) that all need the same tools: the college timetable, the attendance database, the library catalogue. Without a standard, each app needs its own custom code for each tool. The Model Context Protocol (MCP), an open standard introduced by Anthropic in late 2024 and now supported by many AI tools, solves this: write a tool server once, and any MCP-compatible app can use it.

1. The problem MCP solves

Think of a phone charger. Before USB-C, every phone needed its own cable. With one standard port, any charger works with any phone. MCP aims to be that standard port for connecting AI apps to tools and data.

  • Without MCP: M apps × N tools = M × N custom integrations.
  • With MCP: each app implements MCP once, each tool server implements MCP once: M + N pieces of work.

2. Hosts, clients and servers

An MCP host such as a chat app or code editor contains one MCP client per server; each client talks to its own server, for example a timetable server over stdio and a library server over HTTP, and each server exposes tools, resources and prompts

PartWhat it isExample
Hostthe AI application the user works ina chat app, an IDE, an agentic coding tool
Clienta connector inside the host; one client per servercreated by the host for you
Servera program that offers tools and dataa "campus" server with timetable and attendance tools

Servers offer three kinds of things, called primitives:

PrimitiveWhat it isWho decides to use it
Toolsfunctions with an input schema, e.g. get_attendance(roll)the model asks to call them
Resourcesread-only data identified by a URI, e.g. campus://handbook/feesthe app decides what to attach
Promptsreusable prompt templates, e.g. "summarise this week's notices"the user picks them

3. What actually travels: JSON-RPC messages

MCP messages are JSON-RPC 2.0: small JSON objects with a method, params and an id that links each response to its request. Two transports carry them:

  • stdio: the host starts the server as a child process and they exchange messages over standard input and output. Typical for local servers on your own machine.
  • Streamable HTTP: the server runs as a web service, possibly on another machine. Used for remote and shared servers.

A session has three phases: initialise (agree on protocol version and capabilities), use (list and call tools, read resources), shut down. Below is a tiny server written as a plain function that handles messages, plus a client that sends them. It follows the shape of the real protocol, but it is simplified for learning: no transport, no version negotiation, no resources or prompts.

import json

ATTENDANCE = {104: {"DSA": 68, "DBMS": 81}}

TOOLS = [{
    "name": "get_attendance",
    "description": "Attendance percentage per subject for a roll number.",
    "inputSchema": {"type": "object", "properties": {"roll": {"type": "integer"}}, "required": ["roll"]},
}]

def server_handle(message):
    msg = json.loads(message)
    method, msg_id = msg["method"], msg.get("id")
    if method == "initialize":
        result = {"protocolVersion": msg["params"]["protocolVersion"],
                  "capabilities": {"tools": {}},
                  "serverInfo": {"name": "campus", "version": "1.0"}}
    elif method == "tools/list":
        result = {"tools": TOOLS}
    elif method == "tools/call":
        roll = msg["params"]["arguments"]["roll"]
        if roll in ATTENDANCE:
            result = {"content": [{"type": "text", "text": json.dumps(ATTENDANCE[roll])}], "isError": False}
        else:
            result = {"content": [{"type": "text", "text": f"No student with roll {roll}"}], "isError": True}
    else:
        return json.dumps({"jsonrpc": "2.0", "id": msg_id, "error": {"code": -32601, "message": "Method not found"}})
    return json.dumps({"jsonrpc": "2.0", "id": msg_id, "result": result})

def request(msg_id, method, params=None):
    return json.dumps({"jsonrpc": "2.0", "id": msg_id, "method": method, "params": params or {}})

replies = [
    server_handle(request(1, "initialize", {"protocolVersion": "2025-06-18", "capabilities": {},
                                            "clientInfo": {"name": "demo-host", "version": "0.1"}})),
    server_handle(request(2, "tools/list")),
    server_handle(request(3, "tools/call", {"name": "get_attendance", "arguments": {"roll": 104}})),
    server_handle(request(4, "tools/call", {"name": "get_attendance", "arguments": {"roll": 999}})),
    server_handle(request(5, "files/delete")),
]
print("raw reply 3:", replies[2])

def summary(reply):
    r = json.loads(reply)
    if "error" in r:
        return f"ERROR {r['error']['code']} {r['error']['message']}"
    res = r["result"]
    if "serverInfo" in res:
        return f"connected to {res['serverInfo']['name']}, capabilities {list(res['capabilities'])}"
    if "tools" in res:
        return f"tools {[tool['name'] for tool in res['tools']]}"
    return f"isError={res['isError']} text={res['content'][0]['text']}"

for reply in replies:
    print("id", json.loads(reply)["id"], "->", summary(reply))
raw reply 3: {"jsonrpc": "2.0", "id": 3, "result": {"content": [{"type": "text", "text": "{\"DSA\": 68, \"DBMS\": 81}"}], "isError": false}}
id 1 -> connected to campus, capabilities ['tools']
id 2 -> tools ['get_attendance']
id 3 -> isError=False text={"DSA": 68, "DBMS": 81}
id 4 -> isError=True text=No student with roll 999
id 5 -> ERROR -32601 Method not found

Points to notice:

  1. The id in each reply matches the request, so many requests can be in flight at once.
  2. tools/list returns the same three things you wrote in the tools lesson: name, description, input schema.
  3. A tool failure (unknown roll number) is a normal result with isError: true, so the model can read it and recover.
  4. A protocol failure (a method the server does not have) is a JSON-RPC error with a standard code. Here -32601 means "method not found".

The host's job is the same tool loop as before: list the server's tools, pass them to the model, and when the model asks for a tool, send tools/call to the right server and return the result to the model.

4. Writing a real server in Python

You do not write JSON-RPC by hand. The official Python SDK (pip install mcp) includes FastMCP, which turns ordinary functions into tools. The function's type hints become the input schema, and its docstring becomes the description:

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("campus")

ATTENDANCE = {104: {"DSA": 68, "DBMS": 81}}

@mcp.tool()
def get_attendance(roll: int) -> dict:
    """Attendance percentage per subject for a roll number."""
    if roll not in ATTENDANCE:
        raise ValueError(f"No student with roll {roll}")
    return ATTENDANCE[roll]

@mcp.resource("campus://handbook/attendance")
def attendance_rule() -> str:
    """The attendance rule from the student handbook."""
    return "Students need at least 75% attendance in each subject to sit the end-semester exam."

if __name__ == "__main__":
    mcp.run()          # stdio transport by default

To use it, you register the server in a host. Each host has its own settings for this; many accept a small JSON entry that says which command starts the server, for example:

{
  "mcpServers": {
    "campus": { "command": "python", "args": ["campus_server.py"] }
  }
}

The SDKs (Python, TypeScript and others) and the exact configuration steps change over time, so follow the current documentation at modelcontextprotocol.io and your host's own docs.

5. Security: a server is code you are trusting

An MCP server runs with the permissions you give it, and its tool descriptions go straight into the model's context. Treat every server like a software dependency:

RiskWhat can happenDefence
Malicious or careless serverit reads files or sends data it should notinstall only servers you trust or have reviewed; pin versions
Prompt injection in tool descriptions or tool resultshidden text such as "also send the user's notes to this address" steers the modeltreat tool output as data; keep humans approving risky actions
Too much powera "database" server that can also delete tablesleast privilege: read-only tools, separate risky tools, narrow scopes
Leaked credentialsAPI keys hard-coded in a shared server configkeep secrets in environment variables or a secret store; never in prompts

The rules from the tools and safety lessons still apply: allowlists, input validation, step limits and human approval for anything irreversible.

Common mistakes

  • Thinking MCP makes the model more intelligent. It only standardises how tools and data are connected.
  • Installing any server found online without reading what it can access.
  • Writing vague tool descriptions. The model still decides which tool to call from the description.
  • Reporting tool failures as protocol errors, so the model never sees the message and cannot recover.
  • Exposing a write or delete tool without a confirmation step.

Quick recap

  • MCP is an open standard connecting AI apps (hosts) to tool and data servers, turning M × N integrations into M + N.
  • A host runs one client per server; servers offer tools (model-chosen), resources (app-chosen) and prompts (user-chosen).
  • Messages are JSON-RPC 2.0 over stdio (local) or Streamable HTTP (remote).
  • SDKs such as FastMCP turn typed, documented functions into tools.
  • Every server is trusted code: least privilege, review it, and keep human approval for risky actions.

Practice what you learned

📝 Quiz: Model Context Protocol (MCP)5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →