◆ AI All-in-One

Level 2 Agentic Coding · Building with AI

Model Context Protocol

MCP is an open standard for plugging tools and data into AI applications. Write a tool server once and it works in any MCP-capable app, from chat assistants to code editors. This chapter explains hosts, clients and servers, the three things a server can offer, and builds a small server in Python.

Level
●●●●● Easy
Reading
11 min
To learn it well
1 hour to read, an afternoon to build a server
↗ Plan a path here

Read first

Tool Use and Function Calling

This leads to

Extending Your Agent: Skills, Hooks, MCP and Subagents
The full path from zero — 7 concepts before this one
  1. What Is AI?
  2. Python for AI
  3. How Machines Learn
  4. Large Language Models, Explained Simply
  5. Using LLM APIs
  6. Structured Output and JSON
  7. Tool Use and Function Calling
  8. Model Context Protocol

Read them roughly in this order. See it on the concept map →

Why it matters

The Tool Use and Function Calling chapter showed how to give a model your own functions. Tool definitions there are written inside one application, in one provider's format. Now imagine you want your company's issue tracker available in Claude Desktop, in ChatGPT, in your code editor's assistant and in an internal agent. Without a standard you write four integrations. With ten AI applications and a hundred data sources, the world needs 10 × 100 = 1,000 custom connectors.

The Model Context Protocol (MCP) fixes this the way USB fixed peripherals. It is an open standard, introduced by Anthropic in November 2024, that defines how an AI application discovers and uses tools and data offered by a separate program. Each data source implements MCP once (an MCP server), and each AI application implements it once (an MCP host). Then 10 + 100 = 110 implementations replace 1,000. By 2025 MCP was supported by the major assistants and many code editors, and thousands of servers existed for services like GitHub, Slack, databases, browsers and file systems. In December 2025 Anthropic donated the protocol to the Agentic AI Foundation, a fund under the Linux Foundation co-founded with Block and OpenAI.

For you as a builder, MCP means two things. You can give your app or agent a large catalogue of ready-made tools by connecting to existing servers. And you can expose your system to every MCP-capable AI app by writing one small server.

The intuition

Think of a hotel concierge (the host application) who can call many specialist services: a restaurant, a taxi firm, a theatre box office. For each service the concierge keeps one dedicated phone line (a client). Every service answers the phone the same way. "Here's what I can do for you" (a list of capabilities), then "Done, here's your result" (a structured reply). The concierge doesn't need to know how the restaurant's kitchen works, only the shared phone protocol.

The guest is the user. The concierge's brain, deciding which service to ring and what to ask, is the model.

MCP host assistant app, IDE or your own agent Model + conversation sees tools as ordinary tool schemas MCP client 1 MCP client 2 MCP client 3 one client per server stdio subprocess pipes stdio JSON-RPC messages Streamable HTTP over the internet, OAuth Filesystem server local process on your machine tools · resources Database server local process tools · resources · prompts Issue-tracker server remote service at a URL tools · prompts MCP servers each offers some of: tools (model calls them) resources (app attaches them) prompts (user picks them)
Fig. 1 MCP architecture. The host application (an assistant, an IDE or your own agent) runs one MCP client per server. Local servers are launched as subprocesses and talk over stdio; remote servers are reached over Streamable HTTP. Each server can offer tools, resources and prompts.

Key idea MCP standardises the connection between AI applications and tools, not the model. A server describes its tools once; any MCP host can list them, hand them to its model as tool schemas, and run the calls the model makes. It is the tool-call loop with a universal plug.

How it works

Three participants

  • The MCP host is the AI application the user works in: Claude Desktop, Claude Code, ChatGPT, VS Code, or your own agent. It owns the model and the conversation.
  • An MCP client is a component inside the host that keeps a connection to one server. A host connected to three servers runs three clients.
  • An MCP server is a program that offers capabilities: a GitHub server, a Postgres server, the notes server we build below. It can run on your laptop or on a remote machine.

The model never talks to servers directly. The host decides which servers are connected, which tools the model may see, and whether a call needs the user's approval.

Three things a server can offer

MCP defines three server primitives, which differ in who decides to use them:

Primitive What it is Who triggers it Example
Tools Functions the model can call The model search_notes(query), create_issue(title, body)
Resources Read-only data, each with a URI The application or user notes://groceries, a file, a database schema
Prompts Reusable prompt templates with arguments The user, e.g. as a slash command "Summarise my notes as {style}"

Tools are by far the most used, and they map one-to-one onto the tool schemas from Tool Use and Function Calling: a name, a description and a JSON Schema for the inputs. An MCP resource is context the application can attach to the conversation, like opening a file in a chat. An MCP prompt is a template a user picks from a menu. The protocol also lets a server ask the user a question mid-task (elicitation), for example to confirm a deletion.

Messages: JSON-RPC 2.0

Under the hood every MCP message is JSON-RPC: a small, long-established standard for remote procedure calls in JSON. A request has a method, params and an id, and the reply carries the same id. Listing tools is a tools/list request. Calling one looks like this:

{"jsonrpc": "2.0", "id": 3, "method": "tools/call",
 "params": {"name": "search_notes", "arguments": {"query": "flour"}}}

and the server answers:

{"jsonrpc": "2.0", "id": 3,
 "result": {"content": [{"type": "text", "text": "groceries"}],
            "structuredContent": {"result": ["groceries"]}}}

The other main methods follow the same naming pattern: resources/list, resources/read, prompts/list and prompts/get. In the current protocol revision (dated 2026-07-28) every request also carries the protocol version and the client's capabilities in a _meta field, and a client can send server/discover to ask a server what it supports. Earlier revisions began each connection with an initialize handshake instead. The SDKs handle these details, so you rarely write raw JSON-RPC.

How MCP plugs into the tool-call loop

Here is the whole path from a user's question to an answer, with MCP in the middle:

  1. Connect. The host starts its clients. Each one connects to its server and learns what it offers.
  2. List. Each client calls tools/list. The host merges all the tools into one list.
  3. Ask the model. The host sends the user's message plus those tools, converted to its provider's schema format, to the model.
  4. Model calls a tool. The model replies with a tool_use block for search_notes.
  5. Route. The host finds which client owns search_notes (after asking the user's permission, if required) and sends tools/call to that server.
  6. Return. The server runs the function and returns the result. The host puts it into a tool_result block and calls the model again.
Model Host + MCP client e.g. Claude Desktop MCP server notes_server.py 1 connect, discover 2 tools/list search_notes, add_note + schemas once per connection 3 question + tools "Which notes mention flour?" 4 tool_use search_notes {query: "flour"} 5 tools/call after user approval, if required 6 result ["groceries"] tool_result final answer: "Your groceries note."
Fig. 2 One question answered through MCP. Steps 1 and 2 happen once per connection; steps 3 to 6 are the ordinary tool-call loop, with the host forwarding the model's tool call to the right server.

Steps 3, 4 and 6 are exactly the loop from Tool Use and Function Calling. MCP adds only the discovery (steps 1 and 2) and a standard way to carry out step 5.

Transports: stdio and Streamable HTTP

The transport is how the bytes travel. MCP defines two:

  • stdio transport. The host launches the server as a local subprocess and they exchange JSON-RPC messages over the process's standard input and standard output. It's simple and fast, and the server runs with your local permissions. Most desktop setups use it.
  • Streamable HTTP. The server is a web service at a URL such as https://example.com/mcp. The client sends messages as HTTP POST requests, and the server can stream responses back. This is the transport for remote, shared servers, and it supports normal web authentication (MCP recommends OAuth).

The same server code can usually run with either transport. You choose with one argument.

In code

We'll build a small notes server with the official Python SDK, mcp (written against version 2.3; pip install "mcp[cli]" or uv add "mcp[cli]", Python 3.10+). It offers two tools, one resource and one prompt. Type hints and docstrings become the JSON Schemas and descriptions automatically.

# notes_server.py
from mcp.server import MCPServer

mcp = MCPServer("notes")
NOTES = {"groceries": "eggs, flour, milk", "ideas": "an MCP server for my notes"}

@mcp.tool()
def search_notes(query: str) -> list[str]:
    """Return the titles of notes whose text contains the query (case-insensitive)."""
    q = query.lower()
    return [title for title, text in NOTES.items() if q in text.lower()]

@mcp.tool()
def add_note(title: str, text: str) -> str:
    """Create or overwrite a note."""
    NOTES[title] = text
    return f"saved '{title}' ({len(text)} characters)"

@mcp.resource("notes://{title}")
def read_note(title: str) -> str:
    """The full text of one note."""
    return NOTES.get(title, "no such note")

@mcp.prompt()
def summarise_notes(style: str = "bullet points") -> str:
    """Ask the model to summarise every note."""
    return f"Summarise all my notes as {style}. Use the search_notes tool first."

if __name__ == "__main__":
    mcp.run(transport="stdio")       # or transport="streamable-http" to serve on a URL

Versions 1.x of the SDK called this class FastMCP (from mcp.server.fastmcp import FastMCP). The decorators are the same, so older tutorials still translate directly.

The same package includes a client. This script launches the server as a subprocess over stdio, lists its tools, converts them into Anthropic tool schemas, and calls a tool and a resource. It runs as written with notes_server.py in the same folder:

import asyncio, sys
from mcp import Client, StdioServerParameters

server = StdioServerParameters(command=sys.executable, args=["notes_server.py"])

async def main():
    async with Client(server) as client:                 # launches the server process
        listing = await client.list_tools()
        claude_tools = [{"name": t.name, "description": t.description,
                         "input_schema": t.input_schema} for t in listing.tools]
        print(claude_tools[0])
        result = await client.call_tool("search_notes", {"query": "flour"})
        print(result.structured_content)
        note = await client.read_resource("notes://groceries")
        print(note.contents[0].text)

asyncio.run(main())
# {'name': 'search_notes', 'description': 'Return the titles of notes whose text contains
#   the query (case-insensitive).', 'input_schema': {'type': 'object', 'properties':
#   {'query': {'title': 'Query', 'type': 'string'}}, 'required': ['query'], ...}}
# {'result': ['groceries']}
# eggs, flour, milk

claude_tools is ready to pass as tools= to the Messages API. When the model returns a tool_use block, you forward it with client.call_tool(block.name, block.input) and send the result back as a tool_result. That is a complete MCP host in miniature. (The Anthropic SDK also has helpers that do this conversion, and its API can connect to remote MCP servers directly.)

To try the server interactively, open it in the MCP Inspector, a web UI for listing and calling a server's tools: uv run mcp dev notes_server.py. To use it from Claude Desktop, add it to the app's claude_desktop_config.json and restart the app:

{
  "mcpServers": {
    "notes": {
      "command": "uv",
      "args": ["--directory", "/ABSOLUTE/PATH/TO/notes", "run", "notes_server.py"]
    }
  }
}

Common pitfalls

  • Printing to stdout in a stdio server. Standard output is the protocol channel. A stray print("debug") corrupts the JSON-RPC stream and the connection dies with a confusing error. Log to standard error with Python's logging module instead.
  • Relative paths in configuration. Desktop hosts launch servers from their own working directory. Use absolute paths, and sometimes the full path to uv or python.
  • Too many tools. Each connected server adds its tool descriptions to every model request. Ten servers with fifteen tools each is 150 schemas, thousands of tokens, and a model that picks the wrong tool more often. Connect only what a task needs.
  • Poor descriptions. An MCP tool's docstring is its prompt. All the Tool Use and Function Calling advice applies: say what it does, when to use it, and what it returns.
  • Huge results. Return compact text or structured data, not whole databases. Paginate.

Watch out An MCP server is code that runs with real permissions, and its tool descriptions and results go straight into your model's context. A malicious or compromised server can hide instructions in a tool description ("tool poisoning") or in its results (prompt injection), or quietly overreach with your credentials. Install servers only from sources you trust, pin their versions, give each one the narrowest access it needs, and keep human approval switched on for tools that write, delete, send or spend.

Where it leads

  • Agents gain new abilities simply by connecting servers. Coding agents commonly use MCP servers for browsers, issue trackers and documentation.
  • AI Coding Assistants and Agents such as Claude Code, Cursor and VS Code's agent mode are popular MCP hosts.
  • Context Engineering and Memory matters more as servers multiply. Some hosts load tool descriptions only on demand to save context.
  • Building AI Products: remote MCP servers with OAuth are becoming a standard way for software companies to offer their product to AI assistants.

A bit of history

Before MCP, each AI application had its own plug-in system. ChatGPT plug-ins (2023) used OpenAPI descriptions, and every framework had its own tool wrappers. Anthropic released MCP as an open specification with Python and TypeScript SDKs on 25 November 2024. It took inspiration from the Language Server Protocol, which does a similar job of standardising connections between code editors and language tools, and it used JSON-RPC as its message format. Adoption was quick. OpenAI added MCP support to its Agents SDK in March 2025, followed by other major assistants and many code editors. Spec revisions through 2025 replaced the original HTTP-plus-SSE transport with Streamable HTTP, added OAuth-based authorisation, structured tool output and elicitation. In December 2025 the protocol moved to the vendor-neutral Agentic AI Foundation under the Linux Foundation. The 2026-07-28 revision made each request self-describing ("stateless"), so remote servers became easier to scale.

Try it

  1. Add a delete_note(title) tool to the server. Run the stdio client and confirm that list_tools() now shows three tools.
  2. Write a tiny host: take claude_tools from the client script, pass them to the Anthropic Messages API, and forward each tool_use block to client.call_tool. Ask "Which of my notes mention flour?"
  3. Run the server with transport="streamable-http" and connect with Client("http://localhost:8000/mcp"). What changes in your client code, and what stays the same?

Hint for 3: only the argument to Client changes. Everything after the connection is identical, which is the point of a transport layer.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Your company has 10 AI apps and 100 data sources. Roughly how many integrations does MCP need, compared with custom connectors for every pair?

  2. A host application is connected to three MCP servers. How many MCP clients does it run?

  3. You want a read-only database schema that the user or app can attach to a conversation, not something the model calls. Which MCP primitive fits?

  4. Your stdio MCP server dies with a confusing error after you added print("debug"). Why?

  5. You connect ten MCP servers with fifteen tools each to your assistant. What problem should you expect?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Docs

Model Context Protocol

MCP project · Intermediate · Free

The specification, guides and SDKs for connecting AI models to tools and data.

Tool

MCP Python SDK

MCP project · Intermediate · Free

The official Python package for writing MCP servers (the MCPServer class, formerly FastMCP) and clients, with the mcp command-line tool.

Docs

MCP Specification

MCP project · Advanced · Free

The authoritative, versioned description of the protocol: messages, primitives, transports, authorisation and security considerations.

Tool

MCP Inspector

MCP project · Beginner · Free

A browser-based tool for connecting to any MCP server, listing its tools, resources and prompts, and calling them by hand while you develop.

Tool

MCP reference servers

MCP project · Intermediate · Free

Reference server implementations (filesystem, git, fetch, memory and more) and links to community servers. Good code to learn from.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/building/mcp.md