Anthropic published the Model Context Protocol (MCP) in November 2024. It is an open protocol that lets an AI client (a chat app, an IDE, an agent) call tools and read data from small local or remote “servers”. I wanted to ask questions about my sensor data in plain language, for example “was the garage colder than 5 degrees last night”, without writing a chat UI. An MCP server for the sensor database is a small way to try this.
Since version 1.2 of the official Python SDK (January 2025), the simple decorator API from the FastMCP project is included in the SDK. This makes a server very short.
Setup
I use uv for this. Any virtual environment works.
uv init sensors-mcp
cd sensors-mcp
uv add "mcp[cli]"
The server
My readings are in InfluxDB 2, but to keep the example short, this version reads a small SQLite file with a table readings(sensor TEXT, ts TEXT, value REAL). Replace the queries with your own data source.
# server.py
import sqlite3
import logging
from mcp.server.fastmcp import FastMCP
logging.basicConfig(level=logging.INFO) # logs go to stderr, which is fine
log = logging.getLogger("sensors")
DB = "/home/pi/sensors.db"
mcp = FastMCP("sensors")
def query(sql: str, args: tuple = ()) -> list[tuple]:
with sqlite3.connect(f"file:{DB}?mode=ro", uri=True) as conn:
return conn.execute(sql, args).fetchall()
@mcp.tool()
def list_sensors() -> list[str]:
"""Return the names of all sensors."""
return [r[0] for r in query("SELECT DISTINCT sensor FROM readings ORDER BY sensor")]
@mcp.tool()
def readings(sensor: str, since: str, until: str) -> list[dict]:
"""Return readings for one sensor between two ISO 8601 timestamps (UTC).
Example: since='2025-02-10T00:00:00', until='2025-02-11T00:00:00'.
Returns at most 2000 rows.
"""
rows = query(
"SELECT ts, value FROM readings WHERE sensor = ? AND ts >= ? AND ts < ? "
"ORDER BY ts LIMIT 2000",
(sensor, since, until),
)
log.info("readings(%s) -> %d rows", sensor, len(rows))
return [{"ts": ts, "value": v} for ts, v in rows]
@mcp.tool()
def min_max(sensor: str, since: str, until: str) -> dict:
"""Return min, max and average value for one sensor in a time range (UTC)."""
(mn, mx, avg), = query(
"SELECT MIN(value), MAX(value), AVG(value) FROM readings "
"WHERE sensor = ? AND ts >= ? AND ts < ?",
(sensor, since, until),
)
return {"min": mn, "max": mx, "avg": avg}
if __name__ == "__main__":
mcp.run() # stdio transport by default
The function name becomes the tool name, the type hints become the input schema, and the docstring becomes the description the model reads. The docstring is part of the interface. I first wrote “since: start time” and the model sent things like “last night”. Writing the exact format and an example in the docstring fixed most of that.
The stdout trap
With the stdio transport, the client and server talk JSON-RPC over the process’s stdin and stdout. Anything else you write to stdout breaks the protocol. A forgotten print() for debugging gives confusing errors in the client, often only “server disconnected”.
- Use
logging(it writes to stderr by default) orprint(..., file=sys.stderr). - Watch out for libraries that print to stdout on import.
This took me longer to find than writing the server.
Test with the inspector
The SDK CLI starts the MCP Inspector, a small web UI where you can call each tool by hand:
uv run mcp dev server.py
Open the URL it prints, connect, and try list_sensors. Test the tools here before you connect a real client. When something fails in the chat client, you can not easily see why.
Connect a client
For Claude Desktop, edit claude_desktop_config.json (on macOS it is in ~/Library/Application Support/Claude/):
{
"mcpServers": {
"sensors": {
"command": "uv",
"args": ["--directory", "/Users/me/projects/sensors-mcp", "run", "server.py"]
}
}
}
Restart the app. The tools show up, and the client asks before each tool call. Other MCP clients use a similar JSON block. Use the full path to uv if the app does not find it, because desktop apps on macOS do not always get your shell’s PATH.
My sensor database is on a Pi and the client runs on my laptop. For now I copy the SQLite file with rsync every hour. MCP also has an HTTP transport with Server-Sent Events (SSE) for remote servers, but I have not tried it yet, and I would want authentication in front of it first.
Design notes
- Read-only first. The SQLite connection uses
mode=ro. A tool that only reads cannot break anything. I would think much longer before adding a tool that switches a relay. - Limit result size. A model does not need 50,000 rows. Return aggregates (
min_max) or cap the rows. Large results fill the context and cost money with hosted models. - Few, clear tools. Three tools with good docstrings work better than ten similar ones. The model has to choose.
- Times in UTC, and say so. Models are bad at time zones. Do the conversion in the server if you can.
- A server runs with your user’s permissions. Only install MCP servers from sources you trust, the same as any other program.
The protocol is young and the SDK changes often. Pin the mcp version in pyproject.toml so an update does not break a server that works.