Model Context Protocol (MCP)
Expose your own tools through an MCP server and connect a client to it.
By Invicly Tech, , in AI Engineering with Python. About 11 minutes to read.
In short
The Model Context Protocol is an open standard for connecting AI applications to tools and data. You write an MCP server once, and any MCP-compatible client can discover and use its tools and resources.
Think of it like this: MCP is like a USB port for AI apps: one plug shape for many devices.
Explained simply
Before MCP, every AI app needed its own custom code to talk to each tool: one integration for GitHub in one chat app, another for the same GitHub in a different editor. The Model Context Protocol (MCP) is an open standard that replaces this with one shared way of connecting.
There are three roles. The host is the AI app the user works in, like a chat app or a code editor. Inside it, an MCP client manages the connection to one server. The MCP server is a small program that offers capabilities: tools the model can call, resources it can read, and prompt templates.
Write a server once, and any MCP-compatible host can discover its tools, read their descriptions and schemas, and call them. The model still only requests calls; the host runs them through the client.
A server is real code running with real permissions. Installing one is like installing any program, so only use servers you trust, and give them the least access they need.
Press Play on a diagram to walk through it one step at a time.
- Host app to MCP client: Start connection1Start connection
- MCP client to MCP server: initialize2initialize
- MCP client to MCP server: tools/list3tools/list
- MCP server to MCP client: Tool names and schemas4Tool names and schemas
- Host app to MCP client: Model wants a tool5Model wants a tool
- MCP client to MCP server: tools/call with arguments6tools/call with arguments
- MCP server to MCP client: Tool result7Tool result
- Tools
- Functions the model can call
- Resources
- Readable files or records
- Prompts
- Reusable prompt templates
- 1Host app
Chat app or editor the user sees
- 2Model
Decides which tools to request
- 3MCP clients
One per connected server
- 4Transport
stdio locally, Streamable HTTP remotely
- 5MCP servers
Tools, resources, prompts
- 6Real systems
Files, databases, APIs
In depth
Under the hood: JSON-RPC and a handshake
MCP messages are JSON-RPC 2.0: small JSON objects with a method name, parameters and an ID, plus notifications that need no reply. Every session starts with a handshake. The client sends initialize with the protocol version it speaks and its capabilities. The server replies with its own version and capabilities, for example that it offers tools and resources. The client then sends an initialized notification, and normal work begins.
After that, the client discovers what is available with methods such as tools/list, resources/list and prompts/list, and uses them with tools/call, resources/read and prompts/get. A tool result contains content items (usually text) and an isError flag, so tool failures go back to the model as readable results instead of protocol errors.
Servers can also send notifications, for instance that their tool list changed, so the client knows to fetch it again.
- MCP client to MCP server: initialize: version, capabilities1initialize: version, capabilities
- MCP server to MCP client: Server version and capabilities2Server version and capabilities
- MCP client to MCP server: notifications/initialized3notifications/initialized
- MCP client to MCP server: tools/list4tools/list
- MCP server to MCP client: Tools with input schemas5Tools with input schemas
Tools, resources and prompts: who is in control
The three server features differ in who decides to use them. Tools are model-controlled: the model sees their descriptions and chooses when to call them, so they suit actions and live lookups such as create_issue or search_orders. Resources are application-controlled: the host decides which ones to attach as context, often when the user picks a file or record. Each resource has a URI such as file:///notes/todo.md, and servers can offer URI templates for families of resources. Prompts are user-controlled: reusable templates the user selects, often shown as slash commands.
Clients can offer features to servers too. With sampling, a server asks the host's model to generate text. Roots tell a server which folders it may work in. Elicitation lets a server ask the user for missing input. Support varies by host, so check before relying on them.
- Chosen by the model
- Actions and live lookups
- Called with tools/call
- Chosen by the host app
- Files, records, docs by URI
- Read with resources/read
- Chosen by the user
- Reusable templates
- Fetched with prompts/get
Transports: stdio and Streamable HTTP
A transport is how the JSON-RPC messages travel. With stdio, the host starts your server as a child process and they talk over its standard input and output. It is simple and needs no network or ports, which makes it the usual choice for local tools on the user's machine.
One rule catches many beginners: in a stdio server, never print normal output to stdout. Stdout is the protocol channel, so a stray print corrupts the messages. Log to stderr instead.
For remote servers, MCP uses Streamable HTTP: the client sends JSON-RPC over HTTP POST to one endpoint, and the server can reply with plain JSON or stream several messages back. It replaced an older HTTP plus SSE transport. Remote servers serve many users, so they need real authentication; the specification builds on OAuth for this.
- stdio: local, one user, no port
- Streamable HTTP: remote, many users, needs auth
- In stdio servers, log to stderr, never stdout
Building, testing and trusting servers
With the official Python SDK, FastMCP turns ordinary functions into MCP features. The function name becomes the tool name, type hints become the input schema, and the docstring becomes the description, so write docstrings as carefully as tool descriptions. Use @mcp.resource with a URI for read-only data and @mcp.prompt for templates.
Test before connecting a real host. The MCP Inspector (run with npx @modelcontextprotocol/inspector) is a web tool that connects to your server, lists its features and lets you call tools by hand.
For trust, remember a server runs with the permissions of whoever starts it. Review third-party servers before installing, pin versions, and prefer servers that limit themselves to specific folders or scopes. Tool annotations such as readOnlyHint or destructiveHint help hosts warn users, but they are hints from the server, not enforcement.
Learn it in 3 short steps
About 40m each. Track them with a timer in your plan.
- 1Learn MCP concepts: servers, tools, resources~40m
- 2Build a small MCP server~40m
- 3Connect a client to your server~40m
Key points
- MCP separates hosts and clients from servers that provide capabilities.
- Servers commonly run locally over stdio or remotely over HTTP.
- One server works with any compatible client, avoiding custom integrations.
- Treat third-party servers as code you run: review permissions and trust.
Key terms
Tap a card to flip it. 0/5 known
Examples
# pip install mcp
from mcp.server.fastmcp import FastMCP
mcp = FastMCP('notes')
@mcp.tool()
def add_note(text: str) -> str:
"""Save a short note."""
with open('notes.txt', 'a') as f:
f.write(text + '\n')
return 'saved'
if __name__ == '__main__':
mcp.run() # stdio transport by defaultA tiny MCP server exposing one tool with the Python SDK.
Adding a resource and a prompt to a FastMCP server
You already have a notes server with an add_note tool. Now you want the host to be able to read notes as context and offer a ready-made prompt. Step 1: a resource with a URI template notes://{name} returns one note's text; the host decides when to attach it. Step 2: a prompt named summarise_notes builds a request the user can pick, often shown as a slash command. Step 3: run it, then open the MCP Inspector to list resources and prompts and try them by hand before connecting a real host.
from pathlib import Path
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("notes")
NOTES = Path("notes")
@mcp.resource("notes://{name}")
def read_note(name: str) -> str:
"""Return the text of one note."""
return (NOTES / f"{Path(name).name}.txt").read_text()
@mcp.prompt()
def summarise_notes(topic: str) -> str:
return f"Summarise my notes about {topic} in five bullet points."
if __name__ == "__main__":
mcp.run()Connecting your own Python client over stdio
You want to call your server from a script, for example in a test. Step 1: describe how to start the server process with StdioServerParameters. Step 2: stdio_client starts it and gives you read and write streams. Step 3: ClientSession runs the protocol; call initialize first, which performs the handshake. Step 4: list the tools and call one with a dictionary of arguments. The result holds content items, usually text, that you would pass back to a model as a tool result.
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
params = StdioServerParameters(command="python", args=["server.py"])
async def main():
async with stdio_client(params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
tools = await session.list_tools()
print([t.name for t in tools.tools])
result = await session.call_tool("add_note", {"text": "buy milk"})
print(result.content)
asyncio.run(main())Quick reference
- pip install mcp gives the official Python SDK; FastMCP lives in mcp.server.fastmcp
- Roles: host (the app), client (one per server), server (offers tools, resources, prompts)
- Tools are chosen by the model, resources by the host app, prompts by the user
- Session start: initialize, then notifications/initialized, then tools/list
- stdio for local servers; Streamable HTTP for remote ones, with proper auth
- In a stdio server, write logs to stderr; stdout carries the protocol
- Test servers with: npx @modelcontextprotocol/inspector
- Docstrings and type hints become the tool description and schema the model sees
Common mistakes
- Installing untrusted MCP servers with broad file or network access.
- Writing vague tool docstrings, which become the descriptions models rely on.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Create a FastMCP server called calc with one tool add(a: int, b: int) that returns the sum. Run it and list its tools in the MCP Inspector.
- Exercise 2medium
Add a tool read_file(name) to a server that may only read .txt files inside one docs folder. Reject any path that tries to escape it, such as ../secrets.txt.
- Exercise 3hard
Write a client script that connects to a server over stdio, lists its tools, and prints each tool's name, description and required arguments.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is MCP only for one AI provider?
- No. MCP is an open standard with SDKs in several languages, and many hosts from different companies support it.
- What is the difference between MCP and normal tool calling?
- Tool calling is how a model requests a function inside one app. MCP standardises how apps discover and connect to tools from separate servers, so the same server works in many apps.
- Are MCP servers safe to install?
- Only as safe as their code and permissions. Treat them like any program you run: use trusted sources, review what they access and limit their scope.
- Should I use stdio or HTTP for my MCP server?
- Use stdio for tools that run locally for one user. Use Streamable HTTP when the server is shared or hosted remotely, and add authentication.