Model Context Protocol (MCP)

Learn the Model Context Protocol: what MCP is, how clients and servers communicate, the three server features (tools, resources and prompts), and how MCP connects agents to external systems in a standard way.

30 minIntermediateCode Examples

The Core Idea: MCP is an open protocol that standardizes how AI applications connect to tools, data and prompts. An MCP client talks to MCP servers using simple JSON messages, so any compatible app can use any compatible server without custom integration code.

  1. Beginner: MCP Fundamentals

Before MCP, connecting an AI application to a new tool or data source meant writing a custom integration for each pair. With N applications and M tools, that is up to N × M integrations. MCP replaces this with one standard: each application speaks MCP once, and each tool exposes MCP once.

Analogy: Think of USB. Instead of a different cable for every device and computer, one standard port connects them all.

Without a standardWith MCP
Custom integration per app and toolOne protocol both sides understand
Work is repeated by every teamA server is written once and reused
Hard to swap toolsPlug in a different server

MCP was introduced by Anthropic as an open standard and is now supported by many AI applications and tool providers. The protocol keeps evolving, so check the official specification for current details.

  1. Beginner: MCP Clients and Servers

PartRoleExample
HostThe AI application the user interacts withA chat app or an IDE with an agent
MCP clientA connection inside the host that talks to one serverThe code that sends requests
MCP serverA program that exposes capabilitiesA server for files, a database or a calendar

Messages use JSON-RPC 2.0: a request has an id, a method and parameters, and the server replies with a result or an error. They travel over a transport: a local process using standard input and output (stdio), or HTTP for remote servers.

In the code: The client and server in the example exchange real JSON-RPC messages in memory, with no network.

  1. Medium: Tools

Tools are actions the model can request, exactly like the function calling you already know. The server describes each tool with a name, a description and a JSON schema for its arguments. The client lists them with tools/list and runs one with tools/call.

MessagePurpose
tools/listDiscover available tools and their schemas
tools/callRun a tool with arguments and get content back

In the code: The agent asked the server for its tools, found get_weather, and called it for Delhi to receive 33C, sunny.

Security: A tool is still code that can act. The host should show or confirm risky calls, and servers should expose only the minimum.

  1. Medium: Resources and Prompts

Besides tools, a server can offer two other kinds of capability:

FeatureWhat it isWho controls itExample
ResourcesData the application can read, identified by a URIUsually the applicationA file, a database record, a document
PromptsReusable prompt templates with argumentsUsually the userA summarize template for selected text

Resources use resources/list and resources/read. Prompts use prompts/list and prompts/get. In the code, the client read a todo file as a resource and fetched a summarize prompt filled with an argument.

Tools vs. resources
Use a tool when the model should do something or compute something. Use a resource when it should read data that already exists.

  1. Advanced: Connecting Agents to External Systems

1
Connect: The client starts or opens a server and sends initialize. Both sides share which features they support.
2
Discover: List tools, resources and prompts.
3
Use: Add the tools to the agent's tool list. Read resources into context when needed.
4
Handle errors: Servers return errors, such as method not found, that the client must handle.
5
Secure: Authenticate remote servers, limit permissions and require confirmation for risky tools.

Trust: Only connect to servers you trust. A malicious or compromised server can return harmful text or tool descriptions. Treat everything a server sends as untrusted data, as the security lesson explains.

Why it matters for agents: Instead of writing a new integration per tool, an agent can discover and use whatever MCP servers are connected, which makes tool sets easy to extend.

  1. Visual Explanation: One MCP Conversation and Three Server Features

The figure walks through the messages in the code, then summarizes the three things an MCP server can offer.

Part 1 · One ConversationMessages in the code
Connectinitialize
Client says hello
↓
Server returns its name and features
↓
demo-server ready
Discover and usetools/list, tools/call
Server lists get_weather
↓
Client calls it with city = Delhi
↓
33C, sunny
Readresources and prompts
Reads todo.txt as a resource
↓
Fetches the summarize prompt
↓
Data and a ready prompt
Part 2 · The Three Server FeaturesWhat a server can offer
Tools
Actions
The model asks, the client runs.
Resources
Data
Read by URI.
Prompts
Templates
Reusable and parameterized.
Errors
JSON-RPC
Unknown method returns -32601.
Click to see why MCP removes N times M integrationsCompare ▼
With 5 apps and 20 tools you would need up to 100 custom connectors. With MCP, 5 apps speak the protocol and 20 tools expose it, which is 25 pieces of work, and any app can use any tool.

Part 1 shows the sequence: connect, discover and use, then read. Part 2 shows tools, resources, prompts and errors. Open the bar to see the arithmetic behind the integration problem.

  1. Python Implementation: A Tiny MCP Server and Client

This script implements a small MCP-style server and client that exchange JSON-RPC 2.0 messages in memory. It covers initialize, tools/list, tools/call, resources/list, resources/read, prompts/get and an error for an unknown method. It follows the shape of the protocol but is a teaching sketch, not the official SDK.

mcp_demo.pyPython 3.10+ · standard library only
import json # A tiny MCP-style server and client talking JSON-RPC 2.0 (in memory, no network)class Server:    def __init__(self):        self.tools = {"get_weather": {            "description": "Get the current weather for a city",            "inputSchema": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},            "fn": lambda args: {"Paris": "18C, cloudy", "Delhi": "33C, sunny"}.get(args["city"], "unknown city")}}        self.resources = {"file:///notes/todo.txt": "buy milk\nfinish lesson"}        self.prompts = {"summarize": "Summarize this in one sentence: {text}"}     def handle(self, request):        method, params, rid = request["method"], request.get("params", {}), request["id"]        if method == "initialize":            result = {"protocolVersion": "2024-11-05", "capabilities": {"tools": {}, "resources": {}, "prompts": {}},                      "serverInfo": {"name": "demo-server", "version": "0.1"}}        elif method == "tools/list":            result = {"tools": [{"name": n, "description": t["description"], "inputSchema": t["inputSchema"]} for n, t in self.tools.items()]}        elif method == "tools/call":            text = self.tools[params["name"]]["fn"](params["arguments"])            result = {"content": [{"type": "text", "text": text}], "isError": False}        elif method == "resources/list":            result = {"resources": [{"uri": uri, "name": uri.split("/")[-1]} for uri in self.resources]}        elif method == "resources/read":            result = {"contents": [{"uri": params["uri"], "text": self.resources[params["uri"]]}]}        elif method == "prompts/get":            text = self.prompts[params["name"]].format(**params["arguments"])            result = {"messages": [{"role": "user", "content": {"type": "text", "text": text}}]}        else:            return {"jsonrpc": "2.0", "id": rid, "error": {"code": -32601, "message": "Method not found"}}        return {"jsonrpc": "2.0", "id": rid, "result": result} class Client:    def __init__(self, server):        self.server, self.next_id = server, 1     def request(self, method, params=None):        message = {"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params or {}}        self.next_id += 1        return self.server.handle(json.loads(json.dumps(message)))      # sent as JSON, as on a real transport client = Client(Server())print("initialize ->", client.request("initialize")["result"]["serverInfo"])tools = client.request("tools/list")["result"]["tools"]print("tools/list ->", [t["name"] for t in tools])print("tools/call ->", client.request("tools/call", {"name": "get_weather", "arguments": {"city": "Delhi"}})["result"]["content"][0]["text"])print("resources/list ->", [r["name"] for r in client.request("resources/list")["result"]["resources"]])print("resources/read ->", client.request("resources/read", {"uri": "file:///notes/todo.txt"})["result"]["contents"][0]["text"].replace("\n", " | "))print("prompts/get ->", client.request("prompts/get", {"name": "summarize", "arguments": {"text": "MCP connects agents to tools"}})["result"]["messages"][0]["content"]["text"])print("unknown method ->", client.request("tools/delete")["error"])
EXPECTED OUTPUT (your numbers may differ slightly)
initialize -> {'name': 'demo-server', 'version': '0.1'}
tools/list -> ['get_weather']
tools/call -> 33C, sunny
resources/list -> ['todo.txt']
resources/read -> buy milk | finish lesson
prompts/get -> Summarize this in one sentence: MCP connects agents to tools
unknown method -> {'code': -32601, 'message': 'Method not found'}

Every line of output is the result of one JSON-RPC request. The unknown method returns a standard error code instead of crashing. For real projects, use an official MCP SDK, which also handles transports, capability negotiation and authentication.

Knowledge Check

Question 1: What problem does MCP mainly solve?
Question 2: Which MCP feature should you use for reading existing data such as a file?

Key Points

✓MCP is an open protocol that standardizes how AI apps connect to tools, data and prompts.
✓A host contains MCP clients, and each client talks to one MCP server.
✓Messages are JSON-RPC 2.0 over stdio for local servers or HTTP for remote ones.
✓Tools are actions, resources are readable data and prompts are reusable templates.
✓Use tools/list and tools/call, resources/list and resources/read, prompts/list and prompts/get.
✓Only connect to trusted servers, limit permissions and treat server output as untrusted.

The Big Picture

MCP in One Line

One protocol → servers expose tools, resources and prompts → any compatible agent can use them

MCP makes tool ecosystems reusable, but trust and security remain your responsibility.

Up Next: Connecting to many tools and servers expands what an agent can be tricked into doing. In Agent Security you will study prompt injection, tool security and safe execution.