AI
Building an MCP server that coding tools can call
What a Model Context Protocol server is, and how to expose your own tools through one.
The Model Context Protocol (MCP) is a standard way for an AI application to discover and call tools that another program exposes. The application (Claude Code, Cursor, an editor) is the host. It creates one client per server, and the two sides exchange JSON-RPC 2.0 messages. A local server usually talks over stdio: the host starts it as a subprocess, writes requests to its stdin and reads replies from its stdout. A remote one uses the Streamable HTTP transport.
For tools, two requests matter. tools/list returns the tools, each with a name, a description and a JSON Schema for its inputs. tools/call runs one tool by name with arguments. The host gives the list to the model, the model decides when to call something, and the result goes back into the conversation. Servers can also expose resources and prompts, but this post is only about tools.
The server I'll walk through is the one in my postgres-query-doctor project, which measures fixes for slow Postgres queries on a sandbox database. The file, src/query_doctor/mcp_server.py, is 89 lines long, because the official Python SDK does the protocol work.
Three tools, one per layer
describe_query(query)returns theEXPLAIN ANALYZEplan and, for each table the query reads, the row count, column statistics and existing indexes.try_fix(query, indexes, rewrite)builds the proposed indexes, times the query (or a rewrite) against the original, compares the rows, and rolls everything back.diagnose(query)runs the project's own agent, which proposes fixes and proves them in the same lab, using its own model.
A coding agent can already read code and write SQL. What it can't do is see what the database knows about a query, or measure whether its idea helped. The first tool gives it the evidence and the second lets it test its own fix. The third is for a caller that would rather hand over the whole job. There is no general "run this SQL and return the rows" tool and no tool that leaves an index behind. Each tool is one complete task.
The server also sets an instructions string, which a client may show to the model, for example in the system prompt. Mine says which tool to use first and what the lab guarantees.
Types become the schema, the docstring becomes the description
@server.tool(annotations=LAB_TOOL)
def try_fix(query: str, indexes: list[str] | None = None, rewrite: str | None = None) -> str:
"""Measure a fix for a slow query on the sandbox, then undo it.
Builds the indexes, times the query (or the rewrite) against the original over several runs,
and checks the rows are identical. A fix only counts as faster when every run with it beats
every run without it and it saves at least 1 ms. Everything is rolled back afterwards.
Args:
query: The slow query.
indexes: CREATE INDEX statements to try.
rewrite: A rewritten version of the query to compare against the original.
"""
with lab_lock, failures_for_the_caller(), connect() as conn:
return report.comparison(lab.try_fix(conn, query, indexes or [], rewrite))The SDK builds the tool definition from this function. The function name is the tool name. The type hints become the input schema: query is a required string, and the other two are optional because they have defaults. Arguments are validated against that schema before the function runs, so an argument of the wrong type comes back as an error the model can read, without any code from me.
The docstring becomes the description, whole. The SDK does not split the Args block into per-parameter schema descriptions, so the model reads those notes as part of the description. To put them inside the schema, the SDK's route is Annotated with a pydantic Field(description=...).
The docstring also states the rule for "faster": every run beats every run, and at least 1 ms saved (MIN_SAVING_MS in lab.py). A model that knows the rule can read the verdict correctly.
Every tool returns a str. For try_fix and diagnose it is the plain-text report from report.py that the command line prints too. This sample is the command-line output in the README, which says its timings are from an Apple M2 laptop:
Before 45.2 ms median (43.7-46.1 ms over 5 runs), 10 rows
Seq Scan on votes; Seq Scan on posts
After 5.2 ms median (5.1-5.7 ms over 5 runs), 10 rows
Bitmap Heap Scan on posts; ...; Index Scan on votes using votes_post_id_idx
Index posts_owner_user_id_idx: 2.8 MB, built in 61 ms
Index votes_post_id_idx: 11.4 MB, built in 201 ms
Results identical: same rows in the same order
Verdict faster, 8.7x (every run with the fix beat every run without it)Because the return type is str, the SDK also sends the same text as structured content, wrapped as {"result": "..."}. I didn't design a JSON shape for the output. The reader is a model, and labelled lines that end in a verdict are something it can act on.
Annotations
# Every change is rolled back, so from the caller's side nothing is modified.
LAB_TOOL = ToolAnnotations(read_only_hint=True, destructive_hint=False, open_world_hint=False)
# ...
@server.tool(annotations=ToolAnnotations(read_only_hint=True, open_world_hint=True))
def diagnose(query: str) -> str:
# ...Annotations are hints about a tool's behaviour. A client can use them to decide, for example, whether to ask the user before a call. The defaults in the specification assume the worst: readOnlyHint is false, destructiveHint is true and openWorldHint is true.
try_fix does create indexes, but inside a transaction that is always rolled back, so I mark it read-only. That is a judgment call. The README still says to point the server at a sandbox copy, because a trial index blocks writes to its table while it is measured. diagnose sets open_world_hint=True because it calls an external model API. The specification says destructiveHint is meaningful only when readOnlyHint is false, so by the letter of the spec that field on LAB_TOOL adds nothing.
The specification also says clients must treat annotations as untrusted unless they come from a trusted server. The real protection is in lab.py: the rolled-back transaction, a statement timeout, and prepared statements so that one call can't carry a second statement.
Failures the model can act on
@contextmanager
def failures_for_the_caller() -> Generator[None]:
"""Failures the calling agent can act on (bad SQL, a timeout, a missing API key) become tool
errors it can read. Anything else stays a crash, with its details kept on the server."""
try:
yield
except (psycopg.Error, ValueError, AgentRunError, UserError) as error:
raise ToolError(str(error).strip()) from errorMCP has two error channels. A protocol error is a JSON-RPC error. The specification's examples include an unknown tool and a malformed request. A tool execution error is a normal result with isError: true and the message in its content. The specification says clients should pass those to the model so it can correct itself.
In the Python SDK, raising ToolError produces the second kind: the model gets my message after an "Error executing tool try_fix:" prefix. Any other exception also comes back with isError: true, but the text is only "Error executing tool" plus the tool's name, and the traceback goes to the server log.
So this context manager is an allowlist. Database errors, ValueError (which the lab raises on purpose, for example when a statement is not a CREATE INDEX) and the agent library's errors have messages the model can use. Everything else is treated as a bug in my code. The list goes by exception type, so a ValueError raised by accident would get through too. A test in tests/test_mcp.py passes DROP TABLE items as an index and asserts that the result is an error containing "not a CREATE INDEX statement".
Connecting it to a client
query-doctor mcp calls server.run(), which uses stdio when no transport is given. For Claude Code:
claude mcp add query-doctor -- uv run --directory /path/to/postgres-query-doctor query-doctor mcpCursor and other clients take the same command in their config file:
{
"mcpServers": {
"query-doctor": {
"command": "uv",
"args": ["run", "--directory", "/path/to/postgres-query-doctor", "query-doctor", "mcp"]
}
}
}The server reads DATABASE_URL and the API keys from the project's .env. The SDK handles each request in its own task and runs plain def tools in worker threads, so two calls can overlap. Every tool body takes lab_lock, a threading.Lock, so measurements run one at a time and don't distort each other's timings.
What I'd carry over to another server
- Expose what the model lacks, as whole tasks. Three tools were enough here.
- Write the description for the model: what the tool does, what its result means, what it costs. The
diagnosedocstring says it takes from about ten seconds to a minute and calls another model. - Return text that ends in a conclusion and, where there is one, a next step. One verdict in
report.pyends with "Run VACUUM on the table and try again." - Raise errors, don't return them, and choose which exception types the model gets to read.
- Set annotations honestly, and enforce safety in code.
- Test through the protocol. The tests use the SDK's in-memory
Client(mcp_server.server)to list and call the tools, with no subprocess.