An MCP server in Python lets Claude Code call your own functions as tools: check disk space, read a log, query an internal API. You write plain Python functions, the MCP Python SDK turns them into tools with a JSON schema, and Claude Code starts the server over stdio. The goal here is a small, read-only server that gives Claude useful diagnostics without giving it a shell.
You will build a server-health MCP server with two tools, test it with raw JSON-RPC, register it with claude mcp add, and call it from a non-interactive claude -p run. The code targets version 2 of the SDK, where FastMCP was renamed to MCPServer, so most v1 examples online no longer run as-is.
Tested on: Ubuntu 24.04.5 LTS, Python 3.11.18, MCP Python SDK (mcp) 2.3.0, Claude Code 2.1.332, jq 1.7.
The Problem
Out of the box, Claude Code has no tools for your own systems except Bash. Check what MCP servers are configured:
claude mcp list
No MCP servers configured. Use `claude mcp add` to add a server.
Without a server, the only way for Claude to answer “how full is the disk?” is to run shell commands. That works, but you either approve every command by hand or you allow Bash, which allows everything. A dedicated MCP server exposes exactly the operations you choose, with typed arguments and nothing else.
Prerequisites
- Python 3.10 or newer (the
mcp2.x package requires>=3.10) with thevenvmodule. - Claude Code installed and logged in.
jq, only for reading the test output.- Optional: How to Block Dangerous Commands with Claude Code Hooks, if you also let Claude run Bash.
Step 1: Create the Project and Install the MCP SDK
Create a directory with its own virtual environment. Pin the major version, because the 1.x and 2.x APIs differ.
mkdir ~/mcp-server-health && cd ~/mcp-server-health
python3 -m venv .venv
.venv/bin/pip install "mcp>=2,<3"
.venv/bin/python -c "import importlib.metadata as m; print(m.version('mcp'))"
2.3.0
Step 2: Write the MCP Server in Python
Save this as server.py:
"""server-health: a read-only MCP server for Linux diagnostics."""
import shutil
from collections import deque
from pathlib import Path
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp.types import ToolAnnotations
mcp = MCPServer("server-health", version="1.0.0")
# Only these files can be read. No paths from the model.
LOGS = {
"dpkg": Path("/var/log/dpkg.log"),
"apt": Path("/var/log/apt/history.log"),
}
READ_ONLY = ToolAnnotations(readOnlyHint=True, openWorldHint=False)
@mcp.tool(annotations=READ_ONLY)
def disk_usage(mount: str = "/") -> dict:
"""Disk usage of a mount point, in GB and percent used."""
_, used, free = shutil.disk_usage(mount)
gb = 1024 ** 3
return {
"mount": mount,
"used_gb": round(used / gb, 1),
"free_gb": round(free / gb, 1),
"used_percent": round(used / (used + free) * 100, 1), # same as df
}
@mcp.tool(annotations=READ_ONLY)
def tail_log(name: str, lines: int = 20) -> str:
"""Last lines of an allowlisted log file. Names: dpkg, apt."""
if name not in LOGS:
raise ToolError(f"unknown log {name!r}; allowed: {', '.join(LOGS)}")
lines = max(1, min(lines, 200))
with LOGS[name].open(errors="replace") as f:
return "".join(deque(f, maxlen=lines))
if __name__ == "__main__":
mcp.run() # stdio transport (default)
Key points:
MCPServeris the high-level server class in SDK 2.x (it wasFastMCPin 1.x). The name and version are what the client sees in the handshake.@mcp.tool()registers a function as a tool. The function name becomes the tool name, the docstring becomes the description Claude reads, and the type hints become the JSON input schema. Write the docstring for the model: say what the tool returns and which values are valid.- No paths from the model.
tail_logaccepts a short name and maps it to a file through theLOGSallowlist. Claude can never ask for/etc/shadowor../../.linesis clamped to 1-200 so a single call cannot dump a huge file. ToolErroris for failures you expect. Its message goes back to the model withisError: true. Any other exception is treated as a crash: the model only seesError executing tool tail_logand the traceback goes to the server log on stderr.readOnlyHint=Truetells the client that the tool does not modify anything. It is a hint, not enforcement: the code itself must be read-only.used_percentis calculated asused / (used + free), the same waydfreportsUse%, so reserved blocks do not distort the number.mcp.run()without arguments uses the stdio transport: Claude Code starts the process and talks to it over stdin/stdout.
Step 3: Test the Server with Raw JSON-RPC
Before involving Claude, talk to the server directly. MCP over stdio is newline-delimited JSON-RPC 2.0: an initialize request, an initialized notification, then normal requests. Save this as requests.jsonl:
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"manual-test","version":"0"}}}
{"jsonrpc":"2.0","method":"notifications/initialized"}
{"jsonrpc":"2.0","id":2,"method":"tools/list"}
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"disk_usage","arguments":{"mount":"/"}}}
{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"tail_log","arguments":{"name":"/etc/shadow"}}}
Pipe it into the server. The sleep 1 keeps stdin open long enough for the replies; jq keeps only the interesting fields:
(cat requests.jsonl; sleep 1) | .venv/bin/python server.py 2>/dev/null \
| jq -c '{id} + (.result | {serverInfo, tools: [.tools[]?.name], content, isError} | with_entries(select(.value != null and .value != [])))'
{"id":1,"serverInfo":{"name":"server-health","version":"1.0.0"}}
{"id":2,"tools":["disk_usage","tail_log"]}
{"id":3,"content":[{"text":"{\n \"mount\": \"/\",\n \"used_gb\": 8.9,\n \"free_gb\": 59.9,\n \"used_percent\": 12.9\n}","type":"text"}],"isError":false}
{"id":4,"content":[{"text":"Error executing tool tail_log: unknown log '/etc/shadow'; allowed: dpkg, apt","type":"text"}],"isError":true}
What to check:
id 2lists both tools. To see the generated input schemas, run the same pipe withjq .instead.id 3returns the dict as JSON text, with the same percentage thatdf -h /shows.id 4is the allowlist at work: an error the model can read, no file content.- Synchronous tools run on worker threads in SDK 2.x, so responses can arrive in a different order than the requests. Match them by
id, not by line.
Step 4: Register the Server with Claude Code
Add the server with absolute paths to the virtual environment’s Python and to the script. Everything after -- is the command that starts the server:
cd ~/mcp-server-health
claude mcp add server-health -- "$HOME/mcp-server-health/.venv/bin/python" "$HOME/mcp-server-health/server.py"
Added stdio MCP server server-health with command: /root/mcp-server-health/.venv/bin/python /root/mcp-server-health/server.py to local config
File modified: /root/.claude.json [project: /root/mcp-server-health]
The default scope is local: the server is available to you, in this project directory only. Check that Claude Code can start it and complete the handshake:
claude mcp list
Checking MCP server health…
server-health: /root/mcp-server-health/.venv/bin/python /root/mcp-server-health/server.py - √ Connected
To share the server with a team, use --scope project instead. Claude Code then writes a .mcp.json file that you commit, and each user approves the server the first time they run claude in the project (until then claude mcp list shows ⏸ Pending approval). In that case avoid user-specific absolute paths in the command.
Verification
MCP tools are named mcp__<server>__<tool>. In a non-interactive run there is nobody to answer a permission prompt, so pre-approve exactly the tool the run needs with --allowedTools.
Case 1: Claude answers from the tool
claude -p "How full is the root filesystem? Use the server-health MCP tools. Answer in one sentence." \
--allowedTools "mcp__server-health__disk_usage"
The root filesystem is about 12.9% full, with 8.9 GB used and 59.9 GB free.
Case 2: Allowlisted log and a refused path
claude -p "Show the last 3 lines of the apt log using the server-health tools. Then try to read the log named /etc/shadow and report what happened. Be brief." \
--allowedTools "mcp__server-health__tail_log"
**Last 3 lines of the apt log:**
```
Commandline: apt-get -q -y -o DPkg::Lock::Timeout=120 --no-install-recommends install tigervnc-scraping-server python3-pil xterm fonts-jetbrains-mono librsvg2-common
Install: fonts-jetbrains-mono:amd64 (2.304+ds-4), tigervnc-common:amd64 (1.13.1+dfsg-2build2, automatic), ...
End-Date: 2026-11-21 05:14:59
```
**`/etc/shadow` request:** The tool refused it with `unknown log '/etc/shadow'; allowed: dpkg, apt`. It only reads logs on its allowlist and won't take an arbitrary file path, so no data came back.
(The Install: line is shortened here.) Claude read the allowed log, and the attempt to read an arbitrary file failed inside your code, not because of a prompt someone had to click. The exact wording of Claude’s answers will vary between runs; the numbers and the error text come from the server.
Troubleshooting
ModuleNotFoundError: No module named 'mcp.server.fastmcp'→ you are running v1 example code on SDK 2.x. Replacefrom mcp.server.fastmcp import FastMCPwithfrom mcp.server.mcpserver import MCPServerand check the migration guide, or pin"mcp<2"for old code.× Failed to connect — CONNECTION_CLOSED: Connection closedinclaude mcp list→ the process exited at startup. The usual cause is a command likepython3 server.pythat uses the system Python, wheremcpis not installed. Use the absolute path to.venv/bin/python, then run that exact command by hand to see the error.⏸ Pending approval (run `claude` to approve)→ the server was added with--scope project. Startclaudeinteractively in the project and approve it once.- The model only sees
Error executing tool …→ your code raised a plain exception. RaiseToolErrorfor expected failures so the message reaches the model; read the traceback for real crashes on stderr. - Claude uses Bash instead of your tool → improve the docstring (what it returns, valid values), and name the server in the prompt as in the examples above.
Conclusion
A Python MCP server is a few typed functions behind MCPServer: test it with raw JSON-RPC, register it with claude mcp add, and allow only the tools a run needs. Keeping the tools narrow and read-only gives Claude real information about your system without a general shell, the same least-privilege idea as in How to Restrict WordPress Application Passwords to Specific Users.
References
- Claude Code Docs: Connect Claude Code to tools via MCP
- MCP Python SDK: Migration guide to v2
- PyPI: mcp
- Model Context Protocol
Entrepreneur | Full-stack developer | Founder of MediSign Ltd. I have over 15 years of professional experience designing and developing web applications. I am also very experienced in managing web projects.
