Tutorial
MCP Server Python Tutorial: Build a Read-Only Tool
Build an MCP server in Python with a read-only lookup tool. Run a real client, inspect structured results and test malformed inputs step by step.
An MCP server in Python can give an AI application a useful capability without giving it a way to change records. In this tutorial, we build one small tool that looks up a fictional service code. Then we call it through a real MCP client, inspect the returned data and test the inputs it should reject.
The result is a working local example you can understand from end to end. It has three fictional records, one lookup function and no database. You do not need a model subscription or an API key to run the protocol checks.
Quick answer
Model Context Protocol, usually called MCP, defines how a client discovers and calls tools exposed by a server. Our server publishes lookup_service. Its input is an exact code such as SVC-101, and its output says whether the record was found.
The client starts the server as a local subprocess and talks to it over standard input and output. The test checks the connection and the response, rather than importing a function and assuming that proves the protocol works. This tutorial verifies that local MCP exchange. It does not test whether a particular AI application chooses the right tool during a conversation.
If tool calling is new to you, start with building an AI agent in Python. That guide explains the model and tool loop. Here, we give a small capability a consistent interface that an MCP client can discover.
What we are building
The directory contains three invented service records: account access, delivery questions and return guidance. Each has an exact code, a display name, a fictional team and an availability label. These are tutorial fixtures, not real contacts or business records.
The tool cannot accept a file path, run a command, modify an entry or search your whole computer. An unknown but correctly formatted code returns not-found. A malformed code produces a tool error. That distinction helps a caller decide whether it needs a different identifier or needs to fix its request.

We keep the example narrow because a short tool is easier to inspect. If the first version mixes lookup, web search and record changes, it becomes much harder to tell which permission or decision caused a problem.
Download and prerequisites
Download the complete MCP lookup example. It includes the server, the client, the tests, installation requirements and the actual result captured from the local client run.
Use Python 3.10 or newer. This example was checked on Windows with Python 3.13 and the official mcp package pinned to 2.3.0. The pin describes the version we tested, not a promise that every later version has the same interface. See the official Python SDK repository and package release page before changing versions.
Extract the download into its own folder. Run the following commands from that folder in PowerShell:
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements.txt
.\.venv\Scripts\python.exe check_client.py
.\.venv\Scripts\python.exe -m unittest -v
On macOS or Linux, use .venv/bin/python in place of .\.venv\Scripts\python.exe. Calling the environment’s interpreter directly also avoids depending on shell activation settings. Installation needs network access to download packages. Once installed, this particular example makes no external service requests.
Step 1: define the result before exposing the tool
The tool returns three fields: status, code and service. A found result contains a service object. A not found result keeps service as null. That makes a missing record explicit instead of returning a vague sentence that another piece of code must interpret.
We use TypedDict to describe the result fields while returning ordinary Python dictionaries. The complete server below includes these types. A generic dict return annotation alone did not provide structured results in our initial test, so the declared shape is part of the working example.
Consistent output matters when a tool becomes one step in a larger workflow. A caller should not have to guess whether an empty message means a missing record, an error or a successful lookup with no details. For a related pattern, read structured JSON with schemas and Pydantic.
Step 2: write the complete server
Save this as directory_server.py. The download contains the same file.
import re
from types import MappingProxyType
from typing import Annotated, Literal
from typing_extensions import TypedDict
from mcp.server import MCPServer
from mcp.types import ToolAnnotations
from pydantic import Field
class ServiceRecord(TypedDict):
name: str
team: str
availability: str
class LookupResult(TypedDict):
status: Literal["found", "not-found"]
code: str
service: ServiceRecord | None
mcp = MCPServer("Fictional service directory")
# Tuple values and a read-only mapping keep this example's records immutable.
DIRECTORY = MappingProxyType({
"SVC-101": ("Account access", "Fictional help desk", "Weekdays"),
"SVC-202": ("Delivery questions", "Fictional shipping desk", "Weekdays"),
"SVC-303": ("Return guidance", "Fictional returns desk", "Weekdays"),
})
@mcp.tool(annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False))
def lookup_service(
code: Annotated[str, Field(strict=True, min_length=7, max_length=7, pattern=r"^SVC-[0-9]{3}$")],
) -> LookupResult:
"""Look up one exact fictional service code. No search, record updates or external requests."""
# Also validate direct Python calls, which bypass SDK argument validation.
if type(code) is not str or re.fullmatch(r"SVC-[0-9]{3}", code) is None:
raise ValueError("Use an exact code such as SVC-101")
record = DIRECTORY.get(code)
if record is None:
return {"status": "not-found", "code": code, "service": None}
name, team, availability = record
return {
"status": "found",
"code": code,
"service": {"name": name, "team": team, "availability": availability},
}
if __name__ == "__main__":
mcp.run(transport="stdio")
The records are stored in a mapping proxy with tuple values. The lookup creates a fresh response dictionary, so changing a returned response does not alter the stored directory. This makes the local data boundary visible in the implementation, rather than relying on the function’s name.
The input constraint requires a seven character string with the exact format SVC- followed by three digits. It does not trim spaces or silently rewrite lowercase codes. If your real directory needs different conventions, decide those rules before loosening the format.
The function also checks its input directly. That matters because an ordinary Python caller can bypass SDK argument validation by calling the function itself. We test both paths rather than assuming the protocol layer is always present.
The decorator includes a read-only hint and a closed world hint. They describe intended behavior to a client. They do not restrict the operating system permissions of the server process. The implementation still needs to match the description. The SDK tools guide explains the decorator, schemas and annotations.
Step 3: connect through a real client
Save this as check_client.py:
import asyncio
import json
from pathlib import Path
import sys
from mcp import Client
from mcp.client.stdio import StdioServerParameters
async def main():
server = StdioServerParameters(
command=sys.executable,
args=[str(Path(__file__).with_name("directory_server.py"))],
)
async with Client(server) as client:
tools = await client.list_tools()
assert [tool.name for tool in tools.tools] == ["lookup_service"]
tool = tools.tools[0]
assert tool.annotations.read_only_hint is True
cases = [
("known", {"code": "SVC-101"}),
("unknown", {"code": "SVC-999"}),
("malformed", {"code": "../private.txt"}),
]
results = []
for name, arguments in cases:
result = await client.call_tool("lookup_service", arguments)
results.append({"case": name, "is_error": result.is_error,
"data": result.structured_content})
assert results[0]["data"]["status"] == "found"
assert results[1]["data"]["status"] == "not-found"
assert results[2]["is_error"] is True
report = {"protocol": client.protocol_version, "input_schema": tool.input_schema,
"results": results}
Path(__file__).with_name("verified-results.json").write_text(
json.dumps(report, indent=2) + "\n", encoding="utf-8")
print(json.dumps(report, indent=2))
if __name__ == "__main__":
asyncio.run(main())
The client uses the same Python interpreter that is running the checker. This keeps the subprocess in the environment where we installed the SDK. It locates the server relative to the client file, so a directory name containing spaces does not need to be assembled into a shell command.
Entering the asynchronous client context opens the connection. The client lists the tools, checks that the expected lookup exists and sends three requests. Leaving the context closes the connection and ends the subprocess. No separate terminal server or open network port is required for this example.
We inspect structured_content for successful lookups and is_error for the malformed request. Those are the fields exposed by the tested SDK client. The client documentation describes result handling, while the transport guide covers local subprocess connections.
Step 4: inspect the three outcomes
Run the client command again and open verified-results.json. The file records the negotiated protocol, the actual input schema and the three responses. It is produced by the connection you just ran, not a manually invented screenshot of a successful integration.
| Request | Expected result | Meaning |
|---|---|---|
SVC-101 |
found, with Account access |
The directory contains the exact code |
SVC-999 |
not-found, with no service |
The code is valid but the directory has no matching record |
../private.txt |
Tool error | The request is outside the accepted code format |

The path looking input is useful because it tests a common misunderstanding: a lookup argument should not become a file path just because a caller supplies one. Our tool has no file reading branch. It treats the supplied value as an identifier and rejects values that do not meet its format.
The SDK may print an argument rejection message to the error stream during the malformed case. That is expected here. The important check is that the client receives a tool error and that the known record still works.
Step 5: test more than the happy path
The download’s test_directory.py contains three test methods. One starts a real stdio subprocess and checks the returned service. Another uses an in-process MCP client to exercise known codes, a missing record and invalid requests. The third checks direct calls and the immutable directory boundary.
The invalid cases include a missing argument, a number, a boolean, lowercase text, a newline, a path and an excessively long value. These represent different ways a caller can leave the contract. They should not turn into a plausible looking record through accidental conversion.
We also compare the directory before and after the protocol calls. Changing a returned response is tested separately. Together, these checks support a specific claim: the sample lookup retains its stored records under the tested operations. They are not proof that any arbitrary MCP server is read-only or isolated.
Keep those fixtures when you change the tool. If a future request adds search by name, introduce a separate input contract and a test for ambiguous matches. Do not quietly make an exact lookup start guessing which service the caller meant.
Step 6: connect to an AI application deliberately
After the Python client works, you can decide whether to connect the server to an AI host that supports local MCP processes. Configuration depends on the application. Use its current documentation for the server command, arguments and applicable permission controls. This article does not claim that a Claude, ChatGPT or Copilot host connection was tested.
The command needs to point to the environment’s Python executable, and the argument needs to point to directory_server.py. Use absolute paths in a host configuration so the host’s working directory cannot change which file runs. Do not substitute a downloaded server from an unknown source into the command just because it exposes a similar tool name.
When testing a host, first ask for the known fictional code. Then ask for an unknown code and a request outside the directory’s purpose. Inspect the tool call, its arguments and the result shown to the model. A polished answer alone does not establish that the expected tool ran.
If the host invents an answer for a missing record, the server can still be working correctly. That is a host or model behavior to evaluate separately. Preserve the actual tool result so you can tell a lookup failure from an answer that ignored the lookup.
Troubleshooting the local connection
If Python cannot import mcp, check the interpreter in your command. Installing the package in one environment and launching the server in another is an easy way to get an import error. The supplied client uses sys.executable to keep its child process aligned with its own environment.
If the server starts but the connection fails, inspect the error output. Standard output carries the protocol messages. Adding ordinary print() debugging to the server can interfere with that stream. Put debugging on standard error or use the SDK’s logging mechanisms. The client program can print its own report because it is not the server’s protocol stream.
If structured results are missing, check the return type and installed SDK version. The download uses explicit result types rather than an untyped dictionary annotation. If you change the result shape, change the types, client expectations and tests together.
If a valid looking code is rejected, inspect the exact string. Spaces, different capitalization and trailing newlines are intentionally rejected. Decide whether normalization belongs in your real contract before adding it. Do not remove the format rule just to make a single test pass.
What read-only does and does not establish
Our sample lookup contains no mutation operation, external request or file access. Its input is small and its records are fictional. Those properties make it a useful starting point, but they do not turn the subprocess into a sandbox.
A real server runs with the permissions of its process. Replacing the code, adding a database connection or reading local files changes the review needed. Also consider what a lookup reveals. Reading a private customer record can disclose information even if the tool never changes that record.
Keep authorization separate from identifier validation. A valid service code tells you what was requested, not whether a person may see it. If you add real data, establish the allowed users, fields and access checks before exposing it to a host. A read-only annotation does not supply that policy.
Start with the smallest capability that answers a useful question. Give it a clear contract, make missing results explicit and preserve the tests that demonstrate its boundary. That leaves you with a tool people can inspect rather than a broad capability whose behavior depends on a vague prompt.
FAQ
How do you get started with an MCP server in Python?
Download the complete MCP lookup example, extract it into its own folder and make sure you have Python 3.10 or newer. From that folder, create a virtual environment, install requirements.txt, then run check_client.py and the unit tests with the environment’s interpreter. Installation needs network access, but once installed this particular example makes no external service requests.
What does an MCP Python tool return for unknown or malformed input?
A valid code such as SVC-101 returns found with a service object. A correctly formatted code that isn’t in the directory, such as SVC-999, returns not-found with service set to null. A malformed value such as ../private.txt produces a tool error, and that distinction helps a caller decide whether it needs a different identifier or needs to fix its request.
Is a read-only MCP tool really read-only?
Not automatically. The read-only and closed world hints only describe intended behavior to a client, and they don’t restrict what the server process can do at the operating system level. A real server runs with the access of its process, so replacing the code, adding a database connection or reading local files changes the review needed, and a lookup can still disclose a private record. The tests in this tutorial support a specific claim about the sample lookup under the tested operations, not that any arbitrary MCP server is read-only or isolated.
Which Python and mcp package versions does this tutorial use?
Use Python 3.10 or newer. The example was checked on Windows with Python 3.13 and the official mcp package pinned to 2.3.0. That pin describes the version tested, not a promise that every later version has the same interface, so check the official Python SDK repository and package release page before changing versions.
How can you test an MCP server without an AI app?
The supplied check_client.py starts the server as a local subprocess over standard input and output, lists the tools and sends a known, an unknown and a malformed request. The download’s test_directory.py adds three test methods, one of which starts a real stdio subprocess. These checks verify the local MCP exchange. They don’t test whether a particular AI application chooses the right tool during a conversation.
Can you connect this MCP server to Claude, ChatGPT or Copilot?
This article doesn’t claim that a Claude, ChatGPT or Copilot host connection was tested. If you try one, follow that application’s current documentation for the server command and arguments, and use absolute paths so the host’s working directory can’t change which file runs. Ask for the known fictional code first, then an unknown code, and inspect the tool call and result, because a polished answer alone doesn’t show that the expected tool ran.
Where to go next
Use the Python tool calling tutorial to understand the conversation loop around a tool. Use the RAG citation checker when returned information needs evidence people can inspect. If you later compare hosts or models, keep the same fixtures and follow the task based model testing guide.


