Every AI integration project starts the same way: a client with an LLM-powered app, a mess of internal systems behind it, and a custom glue layer of REST endpoints, prompt snippets and JSON-parsing prayers connecting the two. That glue layer is where integrations go to die — every client re-invents it, every model vendor’s tool-calling format is slightly different, and every schema change breaks a prompt somewhere downstream.
The Model Context Protocol (MCP) is the industry’s attempt to delete that glue layer. Anthropic introduced it in November 2024, OpenAI adopted it in March 2025, Google DeepMind followed, and in December 2025 Anthropic donated the protocol to the Agentic AI Foundation under the Linux Foundation (Wikipedia). It is no longer “a Claude thing” — it’s the closest thing the agent ecosystem has to a universal socket, and GitHub currently indexes about 44,000 repositories with the mcp-server topic (GitHub search, checked 16 Nov 2026). There’s even an official registry at registry.modelcontextprotocol.io, live since September 2025, that catalogs published servers.
Here’s the part most people miss: if you run a business — or build software for businesses — an MCP server is now a distribution channel. ChatGPT, Claude, Gemini-based agents and IDE assistants can all plug into it. Publish a server that exposes your inventory, your booking system, or your ledger, and every MCP-capable AI client on your customer’s machine becomes a frontend you didn’t have to build.
This post is a working engineer’s tour, not a hello world. We’ll build a complete MCP server on the official Python SDK v2 (current release: 2.3.0, 2 Oct 2026 — GitHub releases, which changed the API significantly from the FastMCP-era tutorials you’ll find online), test it end-to-end with a real client over both transports, cover the error-handling discipline that separates production servers from demo code, and then run the numbers on what tool schemas actually cost you in tokens.
Everything below was executed and verified on this machine before publishing: mcp==2.3.0, Python 3.14, SQLite stdlib. No API keys needed anywhere.
The case for MCP over a bespoke REST+prompt layer
A bespoke integration has three failure modes. First, the model has to guess the API: you stuff endpoint docs into a prompt, the model hallucinates a parameter name, and you burn a repair loop on it. Second, every client needs new glue: your ChatGPT action, your Claude integration and your IDE agent each speak a different tool format. Third, schema drift is silent: you rename a field, nothing crashes, and every downstream prompt that referenced the old name starts producing garbage.
MCP fixes all three with one move: the server declares its tools with typed schemas, the protocol transports them, and any conforming client absorbs them automatically. The model doesn’t guess — it reads the schema. The client doesn’t re-implement — it speaks MCP. And the schema is generated from the same Python type hints that validate the arguments, so drift becomes impossible rather than improbable.
The counter-argument is real, though, and we’ll measure it later: every tool you expose costs tokens in every conversation, whether or not the model uses it. MCP is not free. It’s a trade.
The server: a working-capital desk in 120 lines
The demo domain matters if you want to sell this. “Weather server” teaches nothing. We’ll build a working-capital tracker: a small business’s accounts-receivable ledger, exposed as tools so a user can ask their AI client things like “which invoices are more than 60 days overdue and what’s the total?” — and the model answers by calling real code against a real SQLite database, not by hallucinating a spreadsheet.
"""
Working-Capital MCP Server
Run: python server.py (stdio, for Claude Desktop etc.)
python server.py --http (Streamable HTTP on 127.0.0.1:8000)
"""
import argparse
import json
import pathlib
import sqlite3
from contextlib import asynccontextmanager
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
DB = pathlib.Path(__file__).parent / "ledger.db"
def get_db() -> sqlite3.Connection:
conn = sqlite3.connect(DB)
conn.row_factory = sqlite3.Row
return conn
async def lifespan(server: MCPServer):
conn = get_db()
try:
total = conn.execute(
"SELECT COALESCE(SUM(amount_cents),0) FROM invoices WHERE status='open'"
).fetchone()[0]
yield {"open_receivables_usd": total / 100.0}
finally:
conn.close()
mcp = MCPServer(
"working-capital",
instructions=(
"Tools for querying a small business accounts-receivable ledger. "
"All amounts are USD. Use aging_report before chasing anyone."
),
lifespan=lifespan,
)
@mcp.tool()
def list_invoices(status: str = "open", customer: str | None = None) -> str:
"""List invoices, optionally filtered by status (open|paid|all) and customer name."""
if status not in ("open", "paid", "all"):
raise ToolError(f"status must be open|paid|all, got: {status!r}")
q = "SELECT id, customer, amount_cents, due_date, status FROM invoices WHERE 1=1"
params: list = []
if status != "all":
q += " AND status=?"
params.append(status)
if customer:
q += " AND customer LIKE ?"
params.append(f"%{customer}%")
q += " ORDER BY due_date"
rows = get_db().execute(q, params).fetchall()
return json.dumps(
[{"id": r[0], "customer": r[1], "amount_usd": r[2] / 100.0,
"due": r[3], "status": r[4]} for r in rows], indent=2)
@mcp.tool()
def aging_report() -> str:
"""Receivables bucketed by days overdue: current, 1-30, 31-60, 61-90, 90+."""
conn = get_db()
rows = conn.execute(
"""
SELECT CASE
WHEN julianday('now') - julianday(due_date) <= 0 THEN 'current'
WHEN julianday('now') - julianday(due_date) <= 30 THEN '1-30'
WHEN julianday('now') - julianday(due_date) <= 60 THEN '31-60'
WHEN julianday('now') - julianday(due_date) <= 90 THEN '61-90'
ELSE '90+'
END AS bucket,
COUNT(*) AS n, SUM(amount_cents) AS cents
FROM invoices WHERE status='open'
GROUP BY bucket
"""
).fetchall()
return json.dumps(
{r[0]: {"count": r[1], "amount_usd": r[2] / 100.0} for r in rows}, indent=2)
@mcp.tool()
def record_payment(invoice_id: int, amount_cents: int) -> str:
"""Record a payment against an invoice. Marks it paid when fully settled."""
if amount_cents <= 0:
raise ToolError("amount_cents must be positive")
conn = get_db()
cur = conn.execute("SELECT amount_cents, status FROM invoices WHERE id=?", (invoice_id,))
row = cur.fetchone()
if row is None:
raise ToolError(f"invoice {invoice_id} not found")
if row["status"] == "paid":
raise ToolError(f"invoice {invoice_id} is already paid")
if amount_cents > row["amount_cents"]:
raise ToolError(
f"payment {amount_cents} exceeds open balance {row['amount_cents']}")
remaining = row["amount_cents"] - amount_cents
conn.execute(
"UPDATE invoices SET amount_cents=?, status=? WHERE id=?",
(remaining, "paid" if remaining == 0 else "open", invoice_id))
conn.commit()
return json.dumps({"invoice_id": invoice_id,
"remaining_usd": remaining / 100.0,
"status": "paid" if remaining == 0 else "partial"})
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--http", action="store_true",
help="serve Streamable HTTP on 127.0.0.1:8000 instead of stdio")
args = parser.parse_args()
if args.http:
import uvicorn
uvicorn.run(mcp.streamable_http_app(), host="127.0.0.1", port=8000, log_level="warning")
else:
mcp.run()
Things worth noticing, because this is where the v2 SDK does real work for you:
The schema is the signature. status: str = "open" and customer: str | None = None become a JSON Schema the client absorbs automatically. The docstring becomes the tool description the model reads to decide when to call it. Write both like the model is a new hire on their first day, because functionally it is.
lifespan is your startup/teardown hook. It runs once when the server boots, and whatever it yields is carried as context. Ours computes open receivables once at startup instead of on every call. Note the @asynccontextmanager decorator — forgetting it produces a confusing 'async_generator' object does not support the asynchronous context manager protocol crash at first connect (ask me how I know; it was the only bug in the entire build).
instructions is a system prompt fragment. Clients surface it to the model alongside your tools. One sentence of “how to use this server well” is worth more than any amount of clever tool naming.
Error handling: the difference between a tool and a liability
This is the section most MCP tutorials skip, and it’s the one your clients will feel.
When a model calls record_payment with a bad argument, one of two things can happen. If your tool raises a generic exception, the SDK classifies it as a crash: the model sees only the generic string Error executing tool record_payment, your server logs a full traceback at ERROR level, and the model — blind to the actual reason — will often retry the exact same call. If your tool raises ToolError, the SDK classifies it as anticipated: the message you wrote (“payment 99999999 exceeds open balance 1850000”) is delivered to the model, and the server logs it at INFO with no traceback noise.
Why does the distinction matter economically? Because a model that can read the failure can correct it in the next turn. “Exceeds open balance 1850000” tells the model exactly what to do: re-ask the user or lower the amount. A generic crash string forces the model to flail. Every flailing turn is another round trip, more tokens, and a worse answer. Error messages are prompt engineering, delivered at exactly the moment the model needs them.
The SDK docs say it directly: raise ToolError from a tool for any failure you saw coming (exceptions.py). Everything else is treated as a crash. Design your tools so that every foreseeable bad input — validation, not-found, state conflicts like double-payment — is an anticipated error with a message written for the model, not for a human developer.
Proof: the full end-to-end test
We don’t publish untested code. This is the actual test harness — a real MCP client that launches the server over stdio, discovers the tools, exercises the happy path and all three error paths, and asserts on the results. This file, plus the server above, exit 0 as a pair:
"""End-to-end test: real MCP client over stdio against server.py."""
import asyncio
from mcp import Client
from mcp.client.stdio import StdioServerParameters
async def main():
params = StdioServerParameters(
command="venv/bin/python", args=["server.py"], cwd=".")
async with Client(params) as client:
listing = await client.list_tools()
names = sorted(t.name for t in listing.tools)
print("TOOLS:", names)
assert names == ["aging_report", "list_invoices", "record_payment"], names
inv = await client.call_tool("list_invoices", {"status": "open"})
print("LIST_INVOICES:", inv.structured_content)
aging = await client.call_tool("aging_report", {})
print("AGING:", aging.structured_content)
pay = await client.call_tool("record_payment",
{"invoice_id": 1, "amount_cents": 250000})
print("PAY_FULL:", pay.structured_content)
r = await client.call_tool("list_invoices", {"status": "yolo"})
assert r.is_error, "expected is_error for bad status"
print("BAD_STATUS:", r.content[0].text[:70])
r2 = await client.call_tool("record_payment",
{"invoice_id": 2, "amount_cents": 99999999})
assert r2.is_error, "expected is_error for overpay"
print("OVERPAY:", r2.content[0].text[:70])
r3 = await client.call_tool("record_payment",
{"invoice_id": 999, "amount_cents": 100})
assert r3.is_error, "expected is_error for missing invoice"
print("MISSING:", r3.content[0].text[:70])
asyncio.run(main())
print("E2E STDIO TEST: ALL ASSERTIONS PASSED")
Verified output from the run on this machine (test exit code: 0):
TOOLS: ['aging_report', 'list_invoices', 'record_payment']
LIST_INVOICES: {'result': '[\n {\n "id": 5,
"customer": "Bengkel Motor Pak De",
"amount_usd": 3100.0, ...
AGING: {'result': '{\n "1-30": {"count": 1, "amount_usd": 18500.0},
"31-60": {"count": 1, "amount_usd": 2500.0}, ...
PAY_FULL: {'result': '{"invoice_id": 1, "remaining_usd": 0.0, "status": "paid"}'}
BAD_STATUS: Error executing tool list_invoices: status must be open|paid|all, got: 'yolo'
OVERPAY: Error executing tool record_payment: payment 99999999 exceeds open bal[ance...]
MISSING: Error executing tool record_payment: invoice 999 not found
E2E STDIO TEST: ALL ASSERTIONS PASSED
Note what the client never did: write a line of protocol code, construct a JSON-RPC envelope, or handle a schema. The Client object launches the server, negotiates the protocol version, and hands back typed Python. That’s the entire selling point of the protocol in one file.
The second transport: Streamable HTTP
stdio is for desktop clients that spawn your server as a subprocess. The transport you actually deploy is Streamable HTTP — same server, one flag:
python server.py --http
# MCPServer listening on http://127.0.0.1:8000/mcp
And the same client works with only the address changed — a URL means Streamable HTTP:
async with Client("http://127.0.0.1:8000/mcp") as client:
listing = await client.list_tools()
aging = await client.call_tool("aging_report", {})
We ran this too (test exit code: 0): the HTTP client discovered the same three tools and pulled the same aging report. For production you’d put this behind a reverse proxy with TLS and — before exposing it to anyone but yourself — authentication. The v2 MCPServer constructor takes auth_server_provider and token_verifier parameters for OAuth, which is its own article; the two-line summary is do not deploy an unauthenticated MCP server on a public IP, because tools are write-capable and the internet scans ports continuously.
The token tax: what your tool shelf costs per conversation
Now the math that should drive every MCP design decision. Tool definitions are injected into the model’s context at the start of every conversation. I captured the raw tools/list payload from our server over HTTP and measured it:
- 3 tools = 1,433 bytes of JSON ≈ 400 tokens
- Average cost per tool (schema + description + envelope share) ≈ 472 bytes ≈ 130 tokens
Extrapolating linearly (same envelope, measured per-tool average):
- 10 tools ≈ 1,300 tokens
- 30 tools ≈ 3,950 tokens
- 100 tools ≈ 13,100 tokens
- 200 tools ≈ 26,200 tokens
Is 200 tools realistic? Yes — this is the documented failure mode of big MCP deployments; community writeups have measured similar overhead on 200-tool setups (Yaw Terminal). Price it out at GPT-4o’s $2.50 per million input tokens (OpenAI pricing via Inworld): 26,239 tokens injected into every single conversation is about $65.60 per 1,000 conversations before the model has answered a single question. With prompt caching at a 90% cache-hit rate (cached input bills at half price on OpenAI’s rate card), that drops to roughly $36 per 1,000 — real money either way, for shelf-ware the user mostly never invokes.
Two design rules fall out of this, and both are testable:
- Few, fat tools beat many thin ones.
aging_reportanswers five questions the model could have asked as five separate tools. Every collapsed tool is 130 tokens back in every conversation forever. - Descriptions are the highest-leverage tokens you’ll write. Seventy characters that tell the model when to call a tool prevent both missed calls and wrong calls. Spend more effort on the docstring than on the implementation.
There’s a third lever at the protocol level — the 2026-07-28 spec version added tool annotations and pagination support for exactly this reason (MCP spec) — but client support varies, so design your server to be small enough not to need it.
Where this makes money
Three concrete sales angles, in rising order of ambition:
1. The integration itself. Businesses with an LLM subscription and four internal systems will pay roughly $1,000–$5,000 for a tested MCP server that makes their data speakable to their AI client — two to five developer-days at typical integration rates ($60–120/hr, so the math checks: 2×8×$60 = $960 on the floor, 5×8×$120 = $4,800 at the top) with the SDK shown above. The error-handling discipline in this post is most of what they’re actually paying for; a demo-grade server takes an afternoon and then falls over the first time a model sends a bad argument.
2. The maintained server. An MCP server is a long-lived surface over a moving backend. Schema changes, auth rotation, new tools per the client’s roadmap — a monthly retainer to keep a revenue-adjacent integration healthy is an easier sell than the build itself.
3. The distribution play. If you run a product, publishing an MCP server to the official registry puts your product inside every MCP-capable AI client your users already run. The registry preview has been live since September 2025 (MCP blog) and the ecosystem is early enough that category ownership is still available in most verticals.
One honest warning to close: the v2 Python SDK landed in October 2026 and broke from the v1 FastMCP API, so most tutorials currently online are stale. When you hire this out or copy from a gist, the first question is “which SDK version did you run it against?” — and the first proof is a test like the one above, with a real client, exiting zero.
Building an MCP integration against real internal systems — with auth, tests and the error discipline that survives contact with a live model — is most of what we do. If you want a custom version of the server in this post wired to your own data, email [email protected].