Build an MCP Server in Python Step by Step (stdio)
👋 In plain words: In this lesson you build a real MCP server for a small test-case store: Claude can search test cases, read one, and add a new one. You go one step at a time, from an empty folder to a tested server that Claude Code or any other MCP host can use.
Building an MCP server in Python takes surprisingly little code with the official SDK. In this lesson you will install the mcp package, create a server with three tools, a resource and a prompt, write tool descriptions Claude can use, return helpful errors instead of crashes, run the server over stdio from a client process, and cover it with pytest tests that run in-process.
🔑 Key terms
- MCPServer: the high-level server class in the Python
mcpSDK (version 2.x). It turns decorated functions into MCP tools, resources and prompts. - ToolError: an exception you raise on purpose; its message is sent to the model as an error result.
- StdioServerParameters: how a client describes the command that starts a stdio server.
🪜 The steps at a glance
- Create the project and install the SDK.
- Write the data layer.
- Add tools with good descriptions.
- Add a resource and a prompt.
- Return helpful errors.
- Run it over stdio from a client.
- Test it with pytest.
🪜 Step 1: Create the project
⌨️ Terminal
mkdir testcase-mcp
cd testcase-mcp
python -m venv .venv
.venv\Scripts\activate
pip install mcp pytest
This course was built with mcp 2.3.0. Older tutorials import FastMCP from mcp.server.fastmcp; in the 2.x SDK the class is MCPServer in mcp.server.mcpserver.
🪜 Step 2: Write the data layer
Keep business logic in plain Python, separate from MCP. Here a dictionary stands in for your test management tool:
📄 store.py
TEST_CASES = {
"TC-101": {"title": "Login with valid credentials", "area": "auth", "priority": "high"},
"TC-102": {"title": "Login locked after 5 failed attempts", "area": "auth", "priority": "high"},
"TC-201": {"title": "Apply a 10% coupon at checkout", "area": "checkout", "priority": "medium"},
}
def search(area: str) -> list[dict]:
return [{"id": k, **v} for k, v in TEST_CASES.items() if v["area"] == area]
def add(title: str, area: str, priority: str) -> str:
new_id = f"TC-{max(int(k[3:]) for k in TEST_CASES) + 1}"
TEST_CASES[new_id] = {"title": title, "area": area, "priority": priority}
return new_id
🪜 Step 3: Add tools with good descriptions
Each tool is a typed function. The SDK builds the input schema from the type hints and uses the docstring as the description, so write the docstring for Claude (Lesson 24):
📄 server.py
from typing import Literal, TypedDict
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
import store
mcp = MCPServer("testcases", instructions="Search, read and add manual test cases.")
Area = Literal["auth", "checkout", "search"]
class TestCase(TypedDict):
id: str
title: str
area: str
priority: str
class NewCase(TypedDict):
id: str
@mcp.tool()
def search_test_cases(area: Area) -> list[TestCase]:
"""List test cases for one product area. Use this before adding a case, to avoid duplicates.
area: one of auth, checkout, search.
"""
return store.search(area)
@mcp.tool()
def get_test_case(case_id: str) -> TestCase:
"""Get one test case by ID. case_id looks like TC-101 (TC- followed by digits)."""
if case_id not in store.TEST_CASES:
raise ToolError(f"No test case {case_id}. Use search_test_cases to find valid IDs.")
return {"id": case_id, **store.TEST_CASES[case_id]}
@mcp.tool()
def add_test_case(title: str, area: Area, priority: Literal["high", "medium", "low"]) -> NewCase:
"""Add a new test case and return its new ID. title is a short imperative sentence."""
if len(title) < 10:
raise ToolError("title is too short: describe the behaviour, e.g. 'Reject an expired coupon'.")
return {"id": store.add(title, area, priority)}
@mcp.resource("testcases://areas/{area}")
def area_summary(area: str) -> str:
"""Plain-text list of the test cases in one area."""
return "\n".join(f"{c['id']}: {c['title']} [{c['priority']}]" for c in store.search(area))
@mcp.prompt()
def review_coverage(area: str) -> str:
"""Ask Claude to review test coverage for an area."""
return f"Review the test cases in area '{area}'. List missing negative and boundary cases."
if __name__ == "__main__":
mcp.run()
Literal[...]becomes anenumin the schema, so Claude can only send allowed areas and priorities.- Typed return values (
TypedDictor a Pydantic model) give each tool an output schema, and clients receive the result asstructured_content. With a baredictreturn type, the SDK publishes no output schema and sends the result only as JSON text, a detail our own pytest suite caught while building this lesson. - Descriptions say when to use each tool (“before adding a case”) and the format of IDs.
🪜 Step 4: Check the schema Claude will see
📄 show_schema.py
import asyncio
import json
from mcp import Client
from server import mcp
async def main():
async with Client(mcp) as client:
for tool in (await client.list_tools()).tools:
print(tool.name, json.dumps(tool.input_schema["properties"]))
asyncio.run(main())⌨️ Terminal
python show_schema.py🖥️ Output
search_test_cases {"area": {"enum": ["auth", "checkout", "search"], "title": "Area", "type": "string"}}
get_test_case {"case_id": {"title": "Case Id", "type": "string"}}
add_test_case {"title": {"title": "Title", "type": "string"}, "area": {"enum": ["auth", "checkout", "search"], "title": "Area", "type": "string"}, "priority": {"enum": ["high", "medium", "low"], "title": "Priority", "type": "string"}}
Always look at the generated schema once. It is the contract Claude works from.
🪜 Step 5: Return helpful errors
Compare what the model receives for a deliberate ToolError with an unexpected crash:
📄 errors_demo.py
import asyncio
from mcp import Client
from server import mcp
async def main():
async with Client(mcp) as client:
r = await client.call_tool("get_test_case", {"case_id": "TC-999"})
print("deliberate:", r.is_error, "|", r.content[0].text)
r = await client.call_tool("add_test_case", {"title": "Short", "area": "auth", "priority": "low"})
print("validation:", r.is_error, "|", r.content[0].text)
asyncio.run(main())⌨️ Terminal
python errors_demo.py🖥️ Output
deliberate: True | Error executing tool get_test_case: No test case TC-999. Use search_test_cases to find valid IDs.
validation: True | Error executing tool add_test_case: title is too short: describe the behaviour, e.g. 'Reject an expired coupon'.
Tool 'get_test_case' failed: 'Error executing tool get_test_case: No test case TC-999. Use search_test_cases to find valid IDs.'
Tool 'add_test_case' failed: "Error executing tool add_test_case: title is too short: describe the behaviour, e.g. 'Reject an expired coupon'."
- A
ToolErrormessage reaches the model as an error result it can act on (“use search_test_cases to find valid IDs”). - Any other exception is reported as a generic “Error executing tool …” and its details stay on the server, which protects internals but gives the model nothing to work with. Raise
ToolErrorfor every failure you can anticipate.
🪜 Step 6: Run it over stdio from a client
A host such as Claude Code starts the server as a subprocess. This client does the same, so you can test the real transport:
📄 stdio_client.py
import asyncio
import sys
from mcp import Client, StdioServerParameters
async def main():
params = StdioServerParameters(command=sys.executable, args=["server.py"])
async with Client(params) as client:
result = await client.call_tool("search_test_cases", {"area": "auth"})
for case in result.structured_content["result"]:
print(case["id"], "-", case["title"])
added = await client.call_tool("add_test_case", {"title": "Reject an expired coupon code",
"area": "checkout", "priority": "medium"})
print("added:", added.structured_content)
asyncio.run(main())⌨️ Terminal
python stdio_client.py🖥️ Output
TC-101 - Login with valid credentials
TC-102 - Login locked after 5 failed attempts
added: {'id': 'TC-202'}
mcp dev server.py (it uses Node.js to run the Inspector). Lesson 30 covers debugging in detail.🪜 Step 7: Test it with pytest
In-process tests are fast and need no subprocess:
📄 test_server.py
import asyncio
import pytest
from mcp import Client
import store
from server import mcp
def call(tool, args):
async def go():
async with Client(mcp) as client:
return await client.call_tool(tool, args)
return asyncio.run(go())
def test_search_returns_only_requested_area():
result = call("search_test_cases", {"area": "auth"})
assert {c["area"] for c in result.structured_content["result"]} == {"auth"}
def test_unknown_case_is_a_helpful_error():
result = call("get_test_case", {"case_id": "TC-999"})
assert result.is_error and "search_test_cases" in result.content[0].text
def test_add_creates_new_id():
before = len(store.TEST_CASES)
result = call("add_test_case", {"title": "Search with an empty query", "area": "search", "priority": "low"})
assert result.structured_content["id"].startswith("TC-") and len(store.TEST_CASES) == before + 1
@pytest.mark.parametrize("area", ["billing", ""])
def test_invalid_area_is_rejected(area):
assert call("search_test_cases", {"area": area}).is_error
⌨️ Terminal
pytest -q -p no:cacheprovider test_server.py🖥️ Output
..... [100%]
5 passed in 0.42s
🌍 Real-world example: Ravi’s test-case server
Ravi built this server for his team’s test management tool. The first version raised Python KeyErrors, and Claude Code kept retrying with the same wrong ID. After switching to ToolError messages that named the search tool, Claude looked up the right ID on the next turn. The in-process pytest suite now runs on every commit in under a second.
🧪 Practice Questions
Question 1. An MCP tool raises KeyError for an unknown ID. Claude Code receives only “Error executing tool get_test_case” and keeps retrying the same ID. What is the best fix?
- A. Return None instead
- B. Raise a ToolError with a message that explains the problem and how to find valid IDs
- C. Print the error to stdout
- D. Remove the tool
Show answer
Answer: B. Deliberate ToolError messages reach the model; unexpected exceptions are reduced to a generic message. A clear message lets Claude recover.
Question 2. How does the Python MCP SDK build a tool’s input schema?
- A. From the function’s type hints; the docstring becomes the description
- B. From a YAML file next to the server
- C. Claude infers it at run time
- D. From the first call’s arguments
Show answer
Answer: A. Type hints (including Literal for enums) define the schema, and the docstring is the description Claude reads.
Question 3. Which two are good practices when writing an MCP server? (Choose 2.)
- A. Keep business logic in plain modules and test tools in-process with pytest
- B. Use print() for debug output in stdio servers
- C. Use Literal types for fields with a fixed set of values
- D. Return full stack traces to help the model
Show answer
Answer: A and C. Separation and in-process tests make servers reliable; Literal types constrain inputs. Stdout prints corrupt stdio, and stack traces leak internals.
Question 4. A tutorial imports FastMCP from mcp.server.fastmcp, but the import fails with mcp 2.3.0. What should you use?
- A. Downgrade Python
- B. MCPServer from mcp.server.mcpserver
- C. The Anthropic SDK’s Tool Runner
- D. A raw HTTP server
Show answer
Answer: B. In the 2.x Python SDK the high-level server class is MCPServer.
📝 Assignment
- Task 1: Build the server and add a tool
update_priority(case_id, priority)with aToolErrorfor unknown IDs.
✅ Done when: a test covers both the success and the error path. - Task 2: Replace
store.pywith a small SQLite database (Python’ssqlite3module).
✅ Done when: all existing tests still pass. - Stretch: Add a tool
find_duplicates(title)that returns existing cases with similar titles, and updateadd_test_case‘s description to call it first.
✅ Done when: adding “Login with valid username and password” reports TC-101 as a likely duplicate.
❓ Frequently Asked Questions
🤔 How do I create an MCP server in Python?
Install mcp, create MCPServer("name"), decorate functions with @mcp.tool(), @mcp.resource(uri) and @mcp.prompt(), and call mcp.run() for stdio.
🤔 How do I test an MCP server?
Connect mcp.Client to the server object in-process for fast pytest tests, and run a stdio client against server.py to test the real transport.
🤔 How should an MCP tool report errors?
Raise ToolError with a clear message for expected problems. The client receives an error result (is_error) that the model can read.
🤔 What is the MCP Inspector?
A browser-based tool for exploring an MCP server’s tools, resources and prompts by hand. The Python SDK can launch it with mcp dev server.py.
🏁 Summary
MCPServerplus decorators turns typed Python functions into MCP tools, resources and prompts.- Write docstrings for Claude and use
Literaltypes for fixed values. - Raise
ToolErrorfor expected failures; unexpected exceptions become generic errors. mcp.run()serves over stdio; test the transport with a stdio client.- Test tools in-process with pytest on every commit.
Next, continue with Remote MCP Server over HTTP with Authentication in Python.
Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.