AGENTIC AI · MCP GUIDE
Build Your First MCP Server in Python (Tested With the Current SDK)
In this guide
MCP, the Model Context Protocol, is an open standard that lets an AI application connect to tools and data through one common interface. To build your first MCP server in Python, install the mcp package, create an MCPServer, mark ordinary Python functions with @mcp.tool(), and run it. In the current 2.x SDK the class is MCPServer; older tutorials that import FastMCP from mcp.server.fastmcp fail on a fresh install. The full server below was run against a real MCP client for this guide, and all four checks passed.
Most AI demos stop at a chat window. A working AI system has to read a file, look up a record or call an internal service, and every team used to wire those connections by hand for each model and each application. MCP replaces that repeated work with a shared contract. You write the tool once, and any application that speaks MCP can use it.
This guide is for developers who know basic Python and want a working example rather than a definition. You will build a small server, run it, call it from a client you write yourself, and learn what changed in the newest SDK. It also covers the mistakes that cost beginners the most time. If you are weighing a structured course after this, the AI Engineer course covers MCP in its live sessions.
What is MCP and what problem does it solve?
MCP defines how an AI application, called the client or host, talks to a program that offers capabilities, called the server. The application can ask the server what it offers and then use those things on the model’s behalf. The protocol is open, so a server you write is not tied to one model or one vendor.
Think of a USB socket. Before a common socket, every device needed its own cable. With one, you plug in what you need. MCP does the same job for connecting models to tools and data. The server describes each capability in a standard way, including its name, what it does and what inputs it takes, so the model can decide when to use it.
Two points are worth keeping in mind from the start. First, the server runs your code, not the model’s. The model asks, and your function decides what actually happens. Second, because your code runs, you are responsible for what it is allowed to do. We return to that in the section on safety.
The three things a server can offer
An MCP server exposes three kinds of capability. Knowing the difference stops you from putting everything in the wrong place.
| Building block | What it is | Who decides to use it | Example |
|---|---|---|---|
| Tool | A function the model can call to do something or compute something | The model, during a conversation | Add two numbers, look up an order |
| Resource | Read-only data the application can load as context | The application or user | A list of course names, a file |
| Prompt | A reusable instruction template | The user | A “summarise this ticket” template |
This guide builds two tools and one resource. Prompts follow the same pattern and are easy to add once these work.
Set up your environment
You need Python 3.10 or newer and a clean virtual environment. The examples in this guide were run on Python 3.12 with mcp version 2.3.0. Create the environment, then install the package:
python -m venv .venv
.venv\Scripts\activate # on macOS or Linux: source .venv/bin/activate
pip install mcp
Check which version you got with pip show mcp. The version matters here, because the API changed between the 1.x and 2.x releases. If you are following older code that must keep working, you can pin the earlier line with pip install "mcp<2".
Write the server
Create a file called server.py. It defines a small “course helper” with two tools and one resource:
from mcp.server.mcpserver import MCPServer
mcp = MCPServer("course-helper")
COURSES = {
"ai-engineer": "AI Engineer: 2 months, live, two pieces of work every week.",
"ai-testing": "AI Testing: test chatbots, RAG search and AI agents.",
}
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two whole numbers."""
return a + b
@mcp.tool()
def course_summary(slug: str) -> str:
"""Return a one-line summary for a course slug."""
return COURSES.get(slug, f"No course called {slug!r}.")
@mcp.resource("courses://list")
def course_list() -> str:
"""List every course slug this server knows."""
return "\n".join(sorted(COURSES))
if __name__ == "__main__":
mcp.run()
Three details do most of the work. The type hints (a: int) become the input schema the model sees, so write them accurately. The docstring becomes the tool’s description, which is how the model decides when to call it, so write it for the model as well as for people. And mcp.run() starts the server over standard input and output, the simplest way for a local application to launch and talk to it.
What changed in the 2.x SDK
If you copy a tutorial written a year ago, you will most likely see this line:
from mcp.server.fastmcp import FastMCP
On a fresh install of version 2.3.0, that import fails with an error saying mcp.server.fastmcp no longer exists. The message explains that in the 2.x line FastMCP was renamed MCPServer, and that other APIs changed too. The fix has two parts. For new code, import MCPServer from mcp.server.mcpserver as shown above. For old code you do not want to migrate yet, pin mcp<2. The SDK’s migration guide, linked in the sources, lists the other differences.
This is a good habit for any fast-moving library. When a tutorial fails on a clean install, check the installed version against the version the tutorial used before assuming you made a mistake.
Test it with a real client
Do not trust a server you have only read. Write a client that starts it, lists its tools and calls them. Save this as client.py in the same folder:
import asyncio, sys
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def main():
params = StdioServerParameters(command=sys.executable, args=["server.py"])
async with stdio_client(params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
tools = await session.list_tools()
print("tools:", [t.name for t in tools.tools])
print("add:", (await session.call_tool("add", {"a": 2, "b": 3})).content[0].text)
print("summary:", (await session.call_tool("course_summary", {"slug": "ai-testing"})).content[0].text)
print("missing:", (await session.call_tool("course_summary", {"slug": "x"})).content[0].text)
res = await session.read_resource("courses://list")
print("resource:", res.contents[0].text.replace("\n", ","))
asyncio.run(main())
Run python client.py. The output from our run was:
tools: ['add', 'course_summary']
add: 5
summary: AI Testing: test chatbots, RAG search and AI agents.
missing: No course called 'x'.
resource: ai-engineer,ai-testing
Notice command=sys.executable. The client starts the server as a separate process, and a bare python can resolve to a different interpreter than the one running the client, one that does not have the package installed. Passing the exact interpreter that is running the client avoids that class of problem.
How to debug a server that will not start
With standard input and output, the protocol messages travel on the same channel as normal output. That has a practical rule: never use print() inside a stdio server to log things, because the text mixes with the protocol and breaks the conversation. Write logs to standard error or to a file instead.
When the client reports “Connection closed”, the server process has usually crashed on start. Run it by itself with python server.py and read the error. When we tested an older tutorial’s code against the 2.x SDK, the client reported only “Connection closed”, and running the server alone showed the real cause, the failed FastMCP import described above. Reproducing the failure outside the client is the fastest way to see the real cause.
Design tools a model can use well
A tool that works in a test can still fail in a conversation. These habits make the difference:
- One job per tool. A tool called
do_everythinggives the model too many ways to go wrong. Several small, clearly named tools are easier to choose between. - Accurate types and short descriptions. The model sees only the name, the description and the input schema. If the description is vague, the tool is called at the wrong time.
- Return plain, useful errors. Our
course_summaryreturns “No course called 'x'.” rather than raising an exception, so the model can recover and try again. - Keep outputs small. Return what the model needs, not a whole database table. Large outputs waste context and slow every later step.
Safety: your code runs, so limit what it can do
A tool is a way for a model to cause something to happen on your machine or in your systems. Treat the model’s input as untrusted. Check arguments before using them, and never build a shell command or a database query by joining strings from the model.
Give each tool the least permission it needs. A tool that reads one folder should not be able to read the whole disk. A tool that looks up orders should not be able to change them. If an action cannot be undone, such as sending a message or deleting a record, build in a confirmation step that a person approves. The guide on why AI agents fail in production covers the wider set of checks that keep these systems safe.
Connect the server to an application
Once the server passes your own client test, you can point an MCP-aware application at it. The details differ from application to application, so follow that application’s own documentation for adding a local server. In general you tell it the command that starts the server, for example the path to your Python interpreter and to server.py, and it launches the process and lists your tools.
We have not tested every application, so check the documentation of the one you use. Whatever the application, use absolute paths in the configuration, because the application may start the server from a different working directory than your terminal.
Where to go next
Your first server uses standard input and output, which suits tools running on one machine. To share a server across a team you would serve it over the network instead, which the protocol supports through an HTTP-based transport. That brings authentication and deployment questions, so build the local version first and get the tool design right.
Good next exercises: wrap a real API of your own, such as a ticket system or a spreadsheet, as two or three tools; add a second resource; and write an automated test using the client pattern above so every change is checked. If you want to build this under the guidance of a mentor, with reviewed work at each stage, see the AI Engineer course, which also covers retrieval, evaluation and deployment.
Keep a record of what you tested
Because the SDK changed between major versions, write down the versions you tested with: the Python version, the mcp version and the date. A one-line note at the top of your README saves the next person, who may be you in six months, from the same confusing failure. Add the client script to your repository as well, so anyone can confirm in seconds that the server still starts and that each tool still answers.
A short checklist before you share a server
- It starts cleanly with
python server.pyand the client test passes. - Every tool has a clear name, an accurate type hint and a one-line description.
- Errors come back as readable messages, not crashes.
- Nothing prints to standard output except protocol messages.
- Each tool has only the permissions it needs, and irreversible actions need approval.
- The README states the SDK version you tested against.
Frequently asked questions about MCP servers
What does MCP stand for?
MCP stands for Model Context Protocol. It is an open standard for connecting AI applications to tools and data through one common interface, so a server written once can work with many applications.
Why does from mcp.server.fastmcp import FastMCP fail?
In the 2.x release of the Python SDK, FastMCP was renamed MCPServer and moved to mcp.server.mcpserver. Either update the import, or pin an earlier version with pip install "mcp<2" if you need old code to keep running.
Do I need an API key or a paid model to build an MCP server?
No. The server and the test client in this guide use no model and no key. A model only enters when you connect the server to an application that has one.
What is the difference between a tool and a resource?
A tool is a function the model can call to do or compute something. A resource is read-only data the application loads as context. Use a tool when something must happen, and a resource when you are simply offering information to read.
Can I write an MCP server in a language other than Python?
Yes. The protocol is language-neutral, and there are official software development kits for several languages. This guide uses Python because it is the most common starting point for AI engineers.
How do I learn MCP with mentor feedback?
MCP is part of the BuildAI Careers AI Engineer course, which is 2 months at ₹34,999 including taxes. Check the course page for the current batch and terms.
Build it with mentor feedback
Reading a guide shows you the shape of a server. Building several, with someone reviewing your tool design and your safety choices, is what makes the skill reliable. Look at the AI Engineer course for the full path. New Batch every 2 weeks. Enquire now.
Sources and review date
Reviewed on 8 November 2026. The server, client and output shown above were run on Python 3.12 with mcp 2.3.0; the code is original learning material.