Writing Your Own MCP Server: One New Tool, Not the Whole Toolbox

The temptation is to wrap an entire API. The useful version wraps one decision

Contents

The first MCP server I wrote had fourteen tools. It wrapped a home automation API I run, one tool per endpoint: list_devices, get_device_state, set_device_state, list_scenes, run_scene, get_history, and so on down the OpenAPI spec I’d copy-pasted from. It looked thorough. It behaved terribly. The model would call list_devices when it needed get_device_state, invent parameters that didn’t exist, or just give up and tell the user it couldn’t find the right function. I’d built a toolbox. What I needed was a screwdriver.

If you’ve read the general MCP explainer you know the protocol’s shape: a server exposes tools, a client — usually a chat interface — lets a model call them, and the results flow back into the conversation. What that piece doesn’t cover, because it’s a different problem, is how to actually design the tools you expose once you’re the one writing the server. That’s the part almost everyone gets wrong on their first attempt, and it’s the part this post is about.

The one-to-one trap

The mistake is understandable because it’s the path of least resistance. You have an API or a CLI with N operations, so you write N tools, one per operation, with parameters that mirror the underlying call. It feels complete. It maps cleanly onto documentation. It is also close to the worst possible design for a tool a language model has to choose between.

A compact open toolbox holding screwdrivers, bits and pliers in moulded slots.
A small toolbox with a few well-chosen tools, the opposite of wrapping every operation in an API. Photo: Toolset displayed in a toolbox on a dark surface with blue lighting effects by Shixart1985, CC BY 2.0, via Wikimedia Commons.

Two things go wrong. First, tool selection gets harder as the tool count grows, not linearly but combinatorially — the model has to read every tool’s name and description on every turn to decide which one (if any) applies, and thin, overlapping descriptions blur together. get_device_state and list_devices sound like they might do the same thing to a model skimming a schema, even though a human reading the source code knows exactly which one returns what. Second, a one-to-one wrapper pushes the judgment about what to do onto the model, one call at a time, when that judgment is usually better encoded once, in your code, as the actual logic of a coherent action.

Concretely: nobody wants “check whether service X is healthy” translated into a model deciding to call get_service_status, then get_recent_logs, then get_resource_usage, then synthesising an answer from three tool results with three separate chances to misread one of them. They want a check_service_health tool that does all three lookups internally, in code you control and can test, and hands the model one clean structured verdict.

Start from the job, not the API

The reframe that fixed my fourteen-tool mess: don’t ask “what does this API let me do,” ask “what decision does the person actually want made.” A homelab dashboard API has dozens of endpoints. The jobs a user actually asks for are a much shorter list — “is anything down right now,” “restart the thing that’s stuck,” “what changed in the last hour.” Each of those might touch three or four endpoints internally. Each becomes one tool.

This is also why a single-purpose server usually beats a mega-server that wraps an entire product. If you’re building a tool for backup verification, write a server with two or three tools that answer backup questions well, not fifteen that expose every method of the underlying library. A model with a small, sharply-described toolset picks correctly almost every time. A model with a sprawling one picks wrong often enough that you stop trusting it, which defeats the point of building the integration.

A minimal server, one tool

Here’s the shape I use now for a genuinely small MCP server — this one exposes a single tool that reports whether last night’s backup job actually completed, reading a status file a cron job writes after each run:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# server.py — minimal MCP server, one tool
from mcp.server.fastmcp import FastMCP
import json
from datetime import datetime, timezone
from pathlib import Path

mcp = FastMCP("backup-status")

STATUS_FILE = Path("/var/lib/backup-agent/last-run.json")

@mcp.tool()
def check_backup_status() -> dict:
    """Report whether the most recent scheduled backup completed
    successfully, including how long ago it ran and how many bytes
    were transferred. Use this to answer any question about whether
    backups are current, e.g. 'did last night's backup work?' or
    'when did we last back up?'. Takes no arguments.
    """
    if not STATUS_FILE.exists():
        return {
            "status": "unknown",
            "detail": "No status file found — the backup job may never have run.",
        }

    data = json.loads(STATUS_FILE.read_text())
    ran_at = datetime.fromisoformat(data["finished_at"])
    age_hours = (datetime.now(timezone.utc) - ran_at).total_seconds() / 3600

    return {
        "status": "ok" if data["exit_code"] == 0 else "failed",
        "finished_at": data["finished_at"],
        "age_hours": round(age_hours, 1),
        "bytes_transferred": data.get("bytes_transferred"),
        "detail": data.get("message", ""),
    }

if __name__ == "__main__":
    mcp.run(transport="stdio")

That’s the whole server. One tool, no parameters because there’s nothing to disambiguate, a docstring that spells out the exact questions it answers and when to reach for it, and a return value that’s already a clean structured dict rather than a wall of log text the model has to parse itself. FastMCP (part of the official Python SDK) handles the protocol plumbing — capability negotiation, JSON-RPC framing, schema generation from the type hints — so the tool itself is the only code that matters.

Notice what isn’t here: no list_backup_jobs, no get_backup_config, no trigger_backup. If those become genuinely useful later, they’re separate tools with their own sharp descriptions, added because a real question came up that this one tool can’t answer — the API happening to expose them is beside the point.

The description is the interface

The docstring above is doing more work than the function body. A language model never sees your source code, your comments, or your variable names. It sees the tool’s name, its description, and its parameter schema — that’s the entire interface it reasons about when deciding whether and how to call the tool. Write the description like you’re briefing a competent colleague who has never seen this system: state exactly what the tool returns, list the kinds of user questions it answers, and if there’s a gotcha (“age_hours can be negative if the server clock is wrong”), say so there rather than hoping the model infers it.

I’ve fixed more “the model isn’t calling my tool” bugs by rewriting the docstring than by touching the code. A tool named check_backup_status with a one-line description (“checks backup status”) gets ignored far more often than the same tool with a description that spells out the actual phrasing a user might use to ask for it.

Testing before you wire it in

Don’t debug tool selection inside a full chat client — too many moving parts, and you can’t easily see the raw request/response. The MCP Inspector, a small local web UI bundled with the SDK tooling, connects directly to your server over stdio and lets you call each tool by hand, inspect the exact JSON schema it published, and see the raw result before any model touches it:

1
npx @modelcontextprotocol/inspector python server.py

That single command starts your server as a subprocess, opens a browser tab, and lists every tool it discovered. Call check_backup_status from the UI first. If it returns sane JSON there but the model still won’t invoke it once wired into a client, the problem is almost always the description, not the code — which is a much faster thing to iterate on than you’d think, since it’s just prose.

Error handling that a model can act on

The other half of a tool a model actually uses well is what happens when things go wrong. Raising a raw exception, or returning a Python traceback as a string, gives the model nothing to do except apologise to the user. Return a structured error instead — a status field the model can read, plus a plain-language detail it can relay or act on:

1
2
3
4
5
6
7
8
    try:
        data = json.loads(STATUS_FILE.read_text())
    except json.JSONDecodeError:
        return {
            "status": "error",
            "detail": "Status file exists but isn't valid JSON — "
                      "the backup agent may have crashed mid-write.",
        }

That distinction — file missing versus file corrupt versus job actually failed — is exactly the kind of judgment worth encoding once in your code rather than leaving the model to guess from an ambiguous error string.

Keep write access narrow, on purpose

Everything above describes a read-only tool, deliberately. The moment you write a tool that changes state — restarts a service, deletes a file, sends a message — the calculus changes, and it’s worth being conservative. Scope each write tool to the single narrowest action it needs to perform rather than a generic run_command tool that accepts arbitrary strings; a model with a restart_backup_agent tool can only restart the backup agent, while a model with shell access can do anything a user’s account can do. If a write action is destructive or hard to undo, make the tool return a confirmation payload first and require a second explicit call to execute, rather than trusting a model’s read of a vague instruction to do the right irreversible thing on the first try. Genericise any real endpoint or hostname in your own code before you ever paste a “here’s my working example” snippet anywhere public — a tool description that leaks your actual infrastructure layout is a description that helps an attacker as much as it helps the model.

Transport: stdio is usually the right default

The example above ends with mcp.run(transport="stdio"), and for a server you’re running locally — spawned by a desktop chat client as a subprocess, talking over standard input and output — that’s the right call. It needs no port, no auth story, and no network exposure to get wrong. The alternative, an HTTP or SSE transport, only earns its complexity when the server has to run somewhere other than the same machine as the client: a shared box multiple people’s clients connect to, or a server you want reachable from a phone. The moment you flip to HTTP you’ve also taken on everything that comes with running a network service — binding it to a private address rather than 0.0.0.0, putting it behind a reverse proxy with its own auth rather than trusting the protocol layer, and never assuming a client-supplied identity claim is enough on its own. Most homelab MCP servers never need to leave stdio, and starting there instead of reaching for HTTP by default avoids a whole category of exposure you didn’t need.

Adding a second tool, responsibly

Once the read-only tool earns its keep, a second one sometimes genuinely is warranted — the next specific job someone actually asked for, rather than a mirror of every remaining endpoint. Say the backup status tool proves itself, and the obvious next question is “just run it again now.” The naive version is a trigger_backup tool that fires immediately on a single call. The safer version splits the action into a proposal and a confirmation, so the model can’t cause an unplanned multi-hour backup run purely because it misread an ambiguous prompt:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
@mcp.tool()
def request_backup_run(reason: str) -> dict:
    """Propose starting an out-of-schedule backup run. Does NOT start
    it — returns a confirmation token that must be passed to
    confirm_backup_run within 5 minutes to actually trigger it. Use
    this whenever a user asks to back up now, outside the schedule.
    """
    token = _issue_confirmation_token(reason)
    return {"status": "pending_confirmation", "token": token,
            "detail": "Call confirm_backup_run with this token to proceed."}

@mcp.tool()
def confirm_backup_run(token: str) -> dict:
    """Actually start the backup run previously proposed by
    request_backup_run, using the token it returned. Fails if the
    token is missing, expired, or already used.
    """
    if not _valid_token(token):
        return {"status": "error", "detail": "Token invalid or expired."}
    _start_backup_job()
    return {"status": "started"}

That pattern — propose, then confirm with a short-lived token — costs one extra tool and one extra round trip, and in exchange makes it structurally hard for a single misread instruction to trigger a real, disruptive action. It’s a small tax worth paying on any tool that isn’t purely read-only, and it scales better than trying to write a bulletproof natural-language check into the first tool’s docstring.

Troubleshooting the usual failures

Three problems account for nearly every “my MCP server isn’t working” report I’ve either hit myself or helped someone else through.

The tool exists but the model never calls it. Almost always a description problem, not a code problem — the Inspector will show you the tool is registered and callable, which rules out the plumbing. Rewrite the docstring to state plainly what questions it answers, in the words a user would actually use to ask.

The server starts, then the client shows no tools at all. Usually a transport mismatch: the client is configured to connect over HTTP to a server that’s running stdio, or vice versa, or the client’s config points at the wrong working directory so the subprocess never actually launches. Check the client’s own logs, not just your server’s — most clients log a connection failure clearly if you know where to look.

The tool is called with the wrong arguments. The schema is too permissive, usually because a parameter that should be a constrained enum was left as a bare string. Tighten the type — status: Literal["ok", "failed", "unknown"] instead of status: str — and the model has far less room to invent a value that doesn’t match what your code expects downstream.

Who this is for

If you’re integrating one system you already run — a backup job, a monitoring dashboard, a home automation hub — writing a small, purpose-built MCP server with two or three sharply-scoped tools takes an afternoon and genuinely improves how well a model can help you operate that system. If you’re tempted to wrap an entire third-party API surface one-to-one because the documentation makes it look easy, resist it; you’ll get a toolbox nobody reaches into correctly. Write the tool for the question you actually ask, not the endpoint that happens to exist, and add a second one only when a second real question shows up. The local RAG pattern taught the same lesson from the other direction — narrow, well-described access beats a firehose of raw data every time a model has to reason about what it’s looking at.

Smarc
Written by Smarc

Founder and editor of Aside House. A lifelong tinkerer who self-hosts far more than is sensible, hardens Linux boxes for fun, and prods the latest AI tools to see what they can really do. The how-to guides here are the notes Smarc wishes had existed the first time round.

Smarc is the editor of Aside House. The homelab, the hardware and the opinions are real; the guides are drafted with AI assistance. Infrastructure details are genericised on purpose.