How to Build an MCP Server in Python (SDK v2)

Tutorial thumbnail showing Python code for an MCP server and how it connects an AI client to data
Build an MCP server in Python using the official SDK v2.

Most “build an MCP server in Python” tutorials online were written for version 1 of the official SDK. If you copy them today, the very first line fails with ModuleNotFoundError: No module named 'mcp.server.fastmcp'.

This guide uses the current SDK (v2). We will build a small but real project: a Study Planner MCP server that lets an AI assistant add your assignments, list what is pending and mark things done, all stored in SQLite. Every code block below was run and tested on mcp version 2.3.0 with Python 3.13.

Quick answer: To build an MCP server in Python, install the SDK with pip install "mcp[cli]", create a server with MCPServer("name"), turn normal Python functions into tools using the @mcp.tool() decorator, and start it with mcp.run(). Then connect it to an MCP client such as Claude Desktop, Cursor or VS Code.

What is an MCP Server?

An MCP server is a small program that exposes tools, data and prompt templates to AI applications using the Model Context Protocol (MCP). The AI app (the client) discovers what your server offers and calls it when needed.

Think of it like this: the AI model is smart, but it can’t see your database or run your code. An MCP server gives it a safe, well-defined door into your system.

Diagram of an MCP server between AI clients like Claude Desktop and Cursor and your data, exposing tools, resources and prompts
An MCP server sits between the AI app and your data.

If you are completely new to the protocol, read our beginner explainer on what MCP is and how the Model Context Protocol works first, then come back here to build one.

The three things an MCP server can expose

Building blockWhat it isWho controls itExample in our project
ToolA function the AI can call to do somethingThe model decides when to call itadd_assignment()
ResourceRead-only data identified by a URIThe app or user loads it as contextstudy://subjects
PromptA reusable message templateThe user picks itweekly_plan

What Changed in MCP Python SDK v2

The official MCP Python SDK on GitHub now ships v2 as its stable line, and pip install mcp installs 2.x. It targets the 2026-07-28 revision of the MCP specification.

The change that breaks most old tutorials is a rename:

# Old (v1) - no longer works on v2
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Demo")

# New (v2)
from mcp.server import MCPServer
mcp = MCPServer("Demo")

The decorators you may have seen (@mcp.tool(), @mcp.resource(), @mcp.prompt()) still work the same way. A few other things were renamed too, for example McpError is now MCPError. The full list is in the official v1 to v2 migration guide.

Note: “FastMCP” also exists as a separate, standalone framework (the fastmcp package). That is a different project from the class that used to live inside the official SDK. This guide uses only the official mcp package.

Prerequisites

  • Python 3.10 or newer (the SDK requires it)
  • Basic Python: functions, type hints, docstrings
  • A code editor (VS Code works fine)
  • Optional: Node.js, if you want to use the MCP Inspector for testing
  • Optional: Claude Desktop, Cursor or another MCP client to try it with a real AI

No API key is needed to build or test the server itself.

How to Build an MCP Server in Python: Step by Step

How to build an MCP server in Python in 4 steps: install the SDK, write a tool, test with mcp dev, connect Claude Desktop
The full build process at a glance.

This section shows how to build an MCP server in Python from an empty folder to a working tool inside Claude Desktop. Each step builds on the previous one, so follow them in order.

Step 1: Create the project and install the SDK

Make a folder and a virtual environment, then install the SDK with the CLI extra (it gives you the mcp command for testing).

mkdir study-planner-mcp
cd study-planner-mcp

python -m venv venv
# Windows
venv\Scripts\activate
# macOS / Linux
source venv/bin/activate

pip install "mcp[cli]"

If you use uv, the equivalent is uv add "mcp[cli]".

Check the install:

mcp version

Step 2: Write your first tool (the 6-line server)

Before the full project, here’s the smallest working server. Save it as hello_server.py:

from mcp.server import MCPServer

mcp = MCPServer("hello")

@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two numbers."""
    return a + b

if __name__ == "__main__":
    mcp.run()

That’s a complete MCP server. A few things are happening quietly here:

  • The function name becomes the tool name (add)
  • The docstring becomes the description the AI reads to decide when to use it
  • The type hints become the input schema, so the client knows a and b must be integers
  • mcp.run() uses the stdio transport by default, meaning it talks to the client over standard input and output

So write clear docstrings. They are not just comments here, they are instructions for the model.

Step 3: Build the Study Planner server

Now the real project. Create study_server.py:

"""Study Planner MCP server - lets an AI assistant manage your assignments."""
import sqlite3
from datetime import date
from pathlib import Path

from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

DB_PATH = Path(__file__).parent / "study.db"
mcp = MCPServer("study-planner")


def get_db() -> sqlite3.Connection:
    conn = sqlite3.connect(DB_PATH)
    conn.execute(
        """CREATE TABLE IF NOT EXISTS assignments (
               id INTEGER PRIMARY KEY AUTOINCREMENT,
               subject TEXT NOT NULL,
               title TEXT NOT NULL,
               due_date TEXT NOT NULL,
               done INTEGER DEFAULT 0
           )"""
    )
    return conn


@mcp.tool()
def add_assignment(subject: str, title: str, due_date: str) -> str:
    """Add a new assignment. due_date must be in YYYY-MM-DD format."""
    try:
        date.fromisoformat(due_date)
    except ValueError:
        raise ToolError("due_date must look like 2026-12-15 (YYYY-MM-DD)")
    with get_db() as conn:
        cur = conn.execute(
            "INSERT INTO assignments (subject, title, due_date) VALUES (?, ?, ?)",
            (subject, title, due_date),
        )
    return f"Saved assignment #{cur.lastrowid}: {title} ({subject}), due {due_date}"


@mcp.tool()
def list_pending() -> list[dict]:
    """List all assignments that are not done yet, nearest due date first."""
    with get_db() as conn:
        rows = conn.execute(
            "SELECT id, subject, title, due_date FROM assignments "
            "WHERE done = 0 ORDER BY due_date"
        ).fetchall()
    return [
        {"id": r[0], "subject": r[1], "title": r[2], "due_date": r[3]} for r in rows
    ]


@mcp.tool()
def mark_done(assignment_id: int) -> str:
    """Mark an assignment as completed using its id."""
    with get_db() as conn:
        cur = conn.execute(
            "UPDATE assignments SET done = 1 WHERE id = ?", (assignment_id,)
        )
    if cur.rowcount == 0:
        return f"No assignment found with id {assignment_id}"
    return f"Assignment #{assignment_id} marked as done"


@mcp.resource("study://subjects")
def subjects() -> str:
    """All subjects that have at least one assignment."""
    with get_db() as conn:
        rows = conn.execute("SELECT DISTINCT subject FROM assignments").fetchall()
    return "\n".join(r[0] for r in rows) or "No subjects yet"


@mcp.prompt()
def weekly_plan(hours_per_day: int = 2) -> str:
    """Ask the AI to build a study plan from pending assignments."""
    return (
        f"Use the list_pending tool to see my assignments. "
        f"I can study {hours_per_day} hours a day. Make a day-by-day plan "
        f"for this week, finishing the nearest deadlines first."
    )


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

Step 4: Understand what each part does

  • Three tools (add_assignment, list_pending, mark_done): actions the AI can take. Returning a list[dict] gives the client structured data, not just text.
  • One resource (study://subjects): read-only data the app can pull in as context.
  • One prompt (weekly_plan): a ready-made instruction the user can pick from a menu in the client.
  • ToolError: when the AI sends a bad date like “next friday”, the client gets a clear error message it can act on, instead of a raw Python crash.
  • Parameterised SQL (the ? placeholders): the AI’s input never goes straight into the SQL string, which protects you from SQL injection.

Step 5: Test it with a Python client

You don’t need Claude or Cursor to test. The SDK’s Client can connect to your server object directly, in the same process. Create test_client.py:

import asyncio
from mcp import Client
from study_server import mcp


async def main():
    async with Client(mcp) as client:
        tools = await client.list_tools()
        print("Tools:", [t.name for t in tools.tools])

        r = await client.call_tool(
            "add_assignment",
            {"subject": "DBMS", "title": "ER diagram", "due_date": "2026-12-02"},
        )
        print(r.content[0].text)

        r = await client.call_tool("list_pending", {})
        print(r.content[0].text)

        res = await client.read_resource("study://subjects")
        print("Subjects:", res.contents[0].text)


asyncio.run(main())

Run python test_client.py. You should see output similar to this:

Tools: ['add_assignment', 'list_pending', 'mark_done']
Saved assignment #1: ER diagram (DBMS), due 2026-12-02
{
  "id": 1,
  "subject": "DBMS",
  "title": "ER diagram",
  "due_date": "2026-12-02"
}
Subjects: DBMS

The id number depends on how many rows are already in study.db, so don’t worry if yours is different. The text content shows each pending item as JSON; for the full list as structured data, read r.structured_content, which returns {"result": [...]}.

Step 6: Test visually with the MCP Inspector

The MCP Inspector is a browser-based tool for clicking through your server’s tools, resources and prompts. Start it with:

mcp dev study_server.py

It opens a local web page where you can call each tool with your own inputs and see the raw responses. The Inspector is a Node.js app, so you need Node installed for this step.

Step 7: Connect the server to Claude Desktop

The quickest way is the built-in installer:

mcp install study_server.py

Or add it by hand. Open Claude Desktop’s config file:

  • Windows: %APPDATA%\Claude\claude_desktop_config.json
  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json

Add your server under mcpServers. Use the full path to the Python inside your virtual environment, so the mcp package is found:

{
  "mcpServers": {
    "study-planner": {
      "command": "C:\\Users\\you\\study-planner-mcp\\venv\\Scripts\\python.exe",
      "args": ["C:\\Users\\you\\study-planner-mcp\\study_server.py"]
    }
  }
}

Restart Claude Desktop. Now you can type something like “Add my Operating Systems assignment on deadlocks, due 5 December” and the AI will call add_assignment for you. Cursor and VS Code use a very similar JSON format for their MCP settings.

Step 8: Run it over HTTP (optional)

stdio is perfect for local use. If you want other machines or a web app to reach your server, use the Streamable HTTP transport:

mcp run study_server.py --transport streamable-http

By default it listens at http://localhost:8000/mcp. A client then connects with a URL:

async with Client("http://localhost:8000/mcp") as client:
    result = await client.call_tool("list_pending", {})

Don’t expose an HTTP server to the internet without authentication. Anyone who can reach it can call your tools.

stdio vs Streamable HTTP: Which Transport Should You Use?

PointstdioStreamable HTTP
Where it runsOn the same computer as the clientAnywhere reachable over the network
How the client starts itLaunches it as a subprocessConnects to a running URL
Setup effortLowestNeeds a host, port and ideally auth
Best forPersonal tools, desktop apps, learningShared team tools, web apps, deployment
Commandmcp.run()--transport streamable-http

For a college project or a personal tool, start with stdio. Move to HTTP only when you actually need remote access.

Common Errors and How to Fix Them

Error or symptomLikely causeFix
No module named 'mcp.server.fastmcp'Code written for SDK v1Use from mcp.server import MCPServer
ImportError: cannot import name 'McpError'Renamed in v2Use MCPError
Server shows in Claude but tools fail or disconnectA print() statement writing to stdoutIn stdio servers, stdout is the protocol channel. Log to stderr or a file instead
Claude Desktop can’t start the serverWrong Python, or a relative path in the configUse absolute paths to the venv Python and the script
mcp dev fails to openNode.js missingInstall Node.js, or test with the Python client instead
AI never calls your toolVague name or docstringRename the function and describe exactly when to use it

Best Practices for a Good MCP Server

  • Keep each tool focused. One clear job per tool works better than one giant tool with ten options.
  • Write docstrings for the model. Say what the tool does, what format inputs need and what it returns.
  • Validate inputs. The AI can and will send odd values. Check them and raise ToolError with a helpful message.
  • Never trust input in SQL or shell commands. Use parameterised queries, and avoid tools that run arbitrary commands.
  • Be careful with destructive tools. Delete, send or pay actions should be limited, logged, or need confirmation from the user.
  • Return structured data (lists and dicts) when the client may need to work with the result, not just read it.
  • Pin your SDK version in requirements.txt (for example mcp>=2.3,<3) so a future major release doesn’t break your project overnight.

MCP Server Project Ideas for Students

Want to turn this into a final year or mini project? These ideas reuse the exact same pattern you just learned:

Project ideaTools it could exposeLevel
College library assistantsearch_books, issue_book, check_due_dateBeginner
Attendance query serverget_attendance, students_below_75_percentBeginner
Expense tracker for hostel studentsadd_expense, monthly_summaryBeginner
Inventory server for a small shopcheck_stock, low_stock_alert, add_itemIntermediate
Notes search with embeddingssearch_notes, summarise_topicIntermediate
Multi-agent system that shares one MCP serverTools used by a planner and a worker agentAdvanced

To go beyond a single server, see our guides on how to build an AI agent with Python and the top AI agent frameworks to learn in 2026. If you want to keep everything offline and free, pair your server with a local model using Ollama and Python.

For a bigger list of topics, browse our agentic AI projects for final year students and AI project ideas for final year.

Need a Ready-Made AI Project?

If you need a complete, working AI project with source code, project report, synopsis and PPT for your BCA, MCA or B.Tech submission, check out the AI and Python projects on the UpdateGadh Store. A good example is our Multi-Agent Research Assistant in Python. We can also customise a project to match your college’s requirements.

Frequently Asked Questions

What is the difference between FastMCP and MCPServer?

In version 1 of the official MCP Python SDK, the high-level server class was called FastMCP. In v2 it was renamed to MCPServer and moved, so from mcp.server.fastmcp import FastMCP no longer works. Separately, “FastMCP” is also the name of an independent framework with extra production features.

Do I need an API key to build an MCP server?

No. The server is plain Python and runs without any API key. You only need an account or key for the AI client you connect it to, such as Claude Desktop.

Which Python version does the MCP SDK need?

The official MCP Python SDK requires Python 3.10 or newer.

Can I use an MCP server with free or local AI models?

Yes, as long as the client app supports MCP. The server doesn’t care which model is on the other side. Several open-source chat apps and agent frameworks can act as MCP clients for local models.

Is an MCP server the same as a REST API?

Not exactly. A REST API is designed for programs written by developers. An MCP server describes its tools in a standard way that AI applications can discover and call automatically. Many MCP servers actually wrap an existing REST API. Our post on AI agent plugins vs MCP servers covers this in more depth.

Can I build an MCP server as a final year project?

Yes. On its own, a simple server is better suited to a mini project. For a final year project, combine it with a real database, a frontend or dashboard, an AI client or agent, and proper testing and documentation.

Why does my MCP server work in the terminal but not in Claude Desktop?

The usual reasons are relative paths in the config file, the wrong Python interpreter (one without the mcp package installed), or print() statements polluting stdout. Use absolute paths and log to stderr.

Conclusion

Building an MCP server in Python is mostly about writing good, well-described functions. With SDK v2 the pattern is simple: create an MCPServer, decorate your functions as tools, resources and prompts, and call mcp.run().

Start with the Study Planner server above, test it with the Python client, connect it to an AI app, and then swap in your own data. Once you are comfortable, the same skills carry straight into AI agents and multi-agent systems.

Written by Rishabh Saini Founder, UpdateGadh

Rishabh Saini is the founder of UpdateGadh. He has 5 years of experience building PHP, Python, Java, AI and ML projects, and works on projects with the latest and trending technologies. He has helped 2,000+ BCA, MCA and B.Tech students with final year projects. Every project on UpdateGadh is built and tested by him before it is published.

Leave a Reply

Your email address will not be published. Required fields are marked *