A First Server with an Official SDK
Build a small issue-tracker server with the official Python SDK (mcp 2.x): typed tools whose return types become output schemas and structured content, a resource and a resource template, tool errors the model can read, and a read-only SQL tool whose limits live in the database rather than in a string check.
Contentsand lesson path
On this page
- Why it matters
- The task: an issue tracker in SQLite
- Step 1: Put the SQL limits in the database layer
- Step 2: Typed tools, a resource and a template
- Step 3: Call it the way a host would
- Check your understanding
- Apply it
- Review prompt
Lessons of Building MCP Servers
- A First Server with an Official SDK Worked example · 20 min
- Designing Tools for Agents, Not for APIs Concept · 15 min
- Lab: Wrap a REST API as an MCP Server Lab · 30 min
- Contract Tests and the Inspector Lab · 20 min
- Remote Deployment with OAuth Authorization Worked example · 25 min
- Check: Server Design Review Knowledge check · 8 questions
What you will learn
- Implement an MCP server with an official SDK that exposes tools with input and output schemas, plus at least one resource.
Prerequisites: MCP Fundamentals
01. Why it matters
In Reading the Wire you followed a tool call as raw JSON-RPC. Writing that by hand for every server is slow and easy to get wrong: each tool needs an input schema, results need the right shape, errors must go down the right path, and since revision 2026-07-28 of the specification every request carries its own protocol version and client capabilities in _meta instead of a one-off initialize handshake. An official SDK does that work, so your code is ordinary functions with type hints.
The MCP project (the modelcontextprotocol organisation on GitHub) maintains the official SDKs. This lesson uses the Python package mcp 2.3.0 (October 2026), which implements 2026-07-28. Its PyPI page declares Python 3.10 or newer, but 3.10 reached end of life in October 2026 and the size cap below needs 3.11, so use Python 3.12 or later (tested with 3.12.13). The TypeScript SDK 2.x ships as @modelcontextprotocol/server and @modelcontextprotocol/client. Two version traps are worth knowing now:
- In mcp 1.x the high-level class was
FastMCPinmcp.server.fastmcp. Version 2 renamed itMCPServer, imported withfrom mcp.server import MCPServer; the old import fails on 2.x. Pinmcp<2only if you must keep old code running. - Schemas the SDK generates follow JSON Schema 2020-12, the dialect MCP assumes when a schema has no
$schemakey. Older tutorials that say "Draft-07" describe an earlier default.
02. The task: an issue tracker in SQLite
You will expose a small SQLite issue database to an agent with four capabilities:
- a tool
get_issuethat returns one issue as typed data, with an output schema; - a tool
query_issuesfor ad-hoc questions in read-only SQL; - a static resource
schema://issuesdescribing the columns; - a resource template
issues://{number}, so a host can attach any issue as context without the server listing every one.
Create a folder issues-server, a virtual environment and the database. The seed script also adds a table called api_keys, which stands in for data the agent must never read.
mkdir issues-server && cd issues-server
python3 -m venv .venv && source .venv/bin/activate
python -m pip install "mcp==2.3.0""""Create tracker.db: an issues table the agent may read, a table it must not."""
import sqlite3
import sys
ISSUES = [
(101, "Login fails with SSO", "open", "auth", "maya", "2026-10-02"),
(102, "Export to CSV drops accents", "open", "export", "li", "2026-10-05"),
(103, "Dark mode contrast too low", "closed", "ui", "maya", "2026-09-28"),
(104, "Rate limit too strict on search", "open", "api", "sam", "2026-10-11"),
]
db = sqlite3.connect(sys.argv[1] if len(sys.argv) > 1 else "tracker.db")
db.executescript("""
DROP TABLE IF EXISTS issues;
DROP TABLE IF EXISTS api_keys;
CREATE TABLE issues (
number INTEGER PRIMARY KEY, title TEXT NOT NULL, state TEXT NOT NULL,
label TEXT NOT NULL, assignee TEXT, opened TEXT NOT NULL);
CREATE TABLE api_keys (service TEXT, secret TEXT);
""")
db.executemany("INSERT INTO issues VALUES (?, ?, ?, ?, ?, ?)", ISSUES)
db.execute("INSERT INTO api_keys VALUES ('billing', 'sk_live_do_not_leak')")
db.commit()
db.close()
print("created tracker.db with", len(ISSUES), "issues")python seed_db.pycreated tracker.db with 4 issues03. Step 1: Put the SQL limits in the database layer
A tool that runs model-written SQL is powerful and risky. A common first attempt checks that the text starts with SELECT. That check is not a security boundary: SELECT title FROM issues UNION SELECT secret FROM api_keys starts with SELECT, so does SELECT sql FROM sqlite_master, and a query that joins a table to itself fourteen times also starts with SELECT and runs for minutes. Loading every row with fetchall() can also exhaust memory.
Put the limits where the database enforces them:
- Read-only connection. The URI
file:...?mode=romakes SQLite refuse every write. It also fails when the file is missing, instead of quietly creating an empty database. - Authoriser allowlist.
set_authorizeris called for each table and column a statement touches while it is compiled. AllowSELECT, functions and reads of theissuestable, and deny everything else: other tables,sqlite_master,ATTACH,PRAGMA. Two functions are denied by name,zeroblobandrandomblob, because one call such aszeroblob(1000000000)allocates about 1 GB in a single step, before the work budget can stop it. Plain common table expressions such asWITH o AS (SELECT ... FROM issues) SELECT ...still work, because SQLite asks the authoriser only about the tables they read;WITH RECURSIVEis refused, because the allowlist does not includeSQLITE_RECURSIVE. A CTE that readsapi_keysis refused like any other read of that table, andtest_cte_rulespins all three cases. - Work budget.
set_progress_handlerruns every 1,000 virtual-machine steps; returning non-zero interrupts the query. - Size cap. On Python 3.11 and later,
setlimit(SQLITE_LIMIT_LENGTH, ...)makes SQLite stop a query with a "string or blob too big" error when it builds a value over 1 MB, for example with nestedreplacecalls. - Row cap.
fetchmany(51)reads at most one row more than the 50 returned, which is enough to report truncation.
On a server database such as PostgreSQL the same ideas map to a role with SELECT on specific views only, a statement_timeout, and a row limit in the query.
"""Run model-written SQL with database-level limits (stdlib only)."""
import sqlite3
from contextlib import closing
ALLOWED_TABLES = {"issues"}
MAX_ROWS = 50
MAX_TICKS = 20_000 # one tick per 1,000 SQLite VM steps: about 2e7 steps
MAX_VALUE_BYTES = 1_000_000 # largest string or blob one query may build
DENIED_FUNCTIONS = {"zeroblob", "randomblob"} # build huge blobs in one step
class QueryRejected(Exception):
"""The query broke a rule; the message is safe to show the model."""
def _authorizer(action, arg1, arg2, db_name, trigger):
if action == sqlite3.SQLITE_SELECT:
return sqlite3.SQLITE_OK
if action == sqlite3.SQLITE_FUNCTION: # arg2 is the function name
denied = arg2.lower() in DENIED_FUNCTIONS
return sqlite3.SQLITE_DENY if denied else sqlite3.SQLITE_OK
if action == sqlite3.SQLITE_READ and arg1 in ALLOWED_TABLES:
return sqlite3.SQLITE_OK
return sqlite3.SQLITE_DENY # writes, ATTACH, PRAGMA, WITH RECURSIVE, other tables
def run_readonly(db_path: str, sql: str) -> dict:
uri = f"file:{db_path}?mode=ro" # read-only: the file must exist
with closing(sqlite3.connect(uri, uri=True)) as conn:
conn.set_authorizer(_authorizer)
if hasattr(conn, "setlimit"): # Python 3.11 and later
conn.setlimit(sqlite3.SQLITE_LIMIT_LENGTH, MAX_VALUE_BYTES)
ticks = 0
def budget() -> int:
nonlocal ticks
ticks += 1
return 1 if ticks > MAX_TICKS else 0 # non-zero aborts the query
conn.set_progress_handler(budget, 1_000)
try:
cur = conn.execute(sql)
rows = cur.fetchmany(MAX_ROWS + 1)
except sqlite3.DatabaseError as exc:
raise QueryRejected(f"Query refused: {exc}") from None
columns = [d[0] for d in cur.description or []]
return {
"columns": columns,
"rows": [list(r) for r in rows[:MAX_ROWS]],
"truncated": len(rows) > MAX_ROWS,
}Security code needs tests that attack it. Each test below tries something the agent must not be able to do and expects a refusal; two tests check that honest queries, including a plain CTE, still work.
import os
import sqlite3
import subprocess
import sys
import tempfile
import unittest
from readonly_sql import QueryRejected, run_readonly
class ReadOnlySqlTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.mkdtemp()
cls.db = os.path.join(cls.tmp, "tracker.db")
subprocess.run([sys.executable, "seed_db.py", cls.db], check=True,
capture_output=True)
def test_select_on_allowed_table_works(self):
out = run_readonly(self.db, "SELECT number, title FROM issues "
"WHERE state = 'open' ORDER BY number")
self.assertEqual(out["columns"], ["number", "title"])
self.assertEqual(len(out["rows"]), 3)
def test_other_table_is_denied(self):
with self.assertRaises(QueryRejected):
run_readonly(self.db, "SELECT secret FROM api_keys")
def test_select_prefix_does_not_unlock_secrets(self):
sql = "SELECT title FROM issues UNION SELECT secret FROM api_keys"
with self.assertRaises(QueryRejected):
run_readonly(self.db, sql)
def test_schema_table_is_denied(self):
with self.assertRaises(QueryRejected):
run_readonly(self.db, "SELECT sql FROM sqlite_master")
def test_writes_are_denied(self):
for sql in ("DELETE FROM issues",
"UPDATE issues SET state = 'closed'",
"WITH x AS (SELECT 1) DELETE FROM issues",
"ATTACH DATABASE 'other.db' AS o",
"PRAGMA writable_schema = 1"):
with self.subTest(sql=sql), self.assertRaises(QueryRejected):
run_readonly(self.db, sql)
self.assertEqual(len(run_readonly(self.db, "SELECT * FROM issues")["rows"]), 4)
def test_cte_rules(self):
plain = "WITH o AS (SELECT number FROM issues WHERE state = 'open') " \
"SELECT count(*) FROM o"
self.assertEqual(run_readonly(self.db, plain)["rows"], [[3]])
for sql in ("WITH k AS (SELECT secret FROM api_keys) SELECT * FROM k",
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 "
"FROM n WHERE i < 3) SELECT i FROM n"):
with self.subTest(sql=sql), self.assertRaises(QueryRejected):
run_readonly(self.db, sql)
def test_huge_values_are_refused(self):
for sql in ("SELECT length(zeroblob(1000000000))",
"SELECT length(RANDOMBLOB(1000000000))"):
with self.subTest(sql=sql), self.assertRaises(QueryRejected):
run_readonly(self.db, sql)
def test_runaway_query_is_interrupted(self):
tables = ", ".join(f"issues t{i}" for i in range(14)) # 4**14 rows
sql = f"SELECT count(*) FROM {tables}"
with self.assertRaises(QueryRejected) as ctx:
run_readonly(self.db, sql)
self.assertIn("interrupted", str(ctx.exception))
def test_missing_file_is_an_error_not_a_new_db(self):
missing = os.path.join(self.tmp, "nope.db")
with self.assertRaises(sqlite3.OperationalError):
run_readonly(missing, "SELECT 1")
self.assertFalse(os.path.exists(missing))
if __name__ == "__main__":
unittest.main(verbosity=2)python -m unittest test_readonly_sql.........
----------------------------------------------------------------------
Ran 9 tests in 0.902s
OK04. Step 2: Typed tools, a resource and a template
Now the server. Read it once, then look at the notes below it.
"""Issue tracker MCP server on the official Python SDK (mcp 2.x)."""
import json
import logging
import os
import sqlite3
from contextlib import closing
from typing import Annotated
from pydantic import BaseModel, Field
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ResourceNotFoundError, ToolError
from readonly_sql import QueryRejected, run_readonly
DB_PATH = os.environ["ISSUES_DB"] # absolute path, set in the host config
log = logging.getLogger("issues") # MCPServer sends log records to stderr
mcp = MCPServer("issues", version="0.1.0")
class Issue(BaseModel):
number: int
title: str
state: str = Field(description="open or closed")
label: str
assignee: str | None
class QueryResult(BaseModel):
columns: list[str]
rows: list[list[str | int | float | None]]
truncated: bool = Field(description="True if more than 50 rows matched")
def _load(number: int) -> Issue | None:
uri = f"file:{DB_PATH}?mode=ro"
with closing(sqlite3.connect(uri, uri=True)) as conn:
row = conn.execute(
"SELECT number, title, state, label, assignee FROM issues "
"WHERE number = ?", (number,)).fetchone()
if row is None:
return None
return Issue(**dict(zip(Issue.model_fields, row)))
@mcp.tool()
def get_issue(number: Annotated[int, Field(ge=1)]) -> Issue:
"""Fetch one issue by its number, for example 101."""
issue = _load(number)
if issue is None:
raise ToolError(f"No issue #{number}. Use query_issues to find numbers.")
return issue
@mcp.tool()
def query_issues(sql: str) -> QueryResult:
"""Run one read-only SQLite SELECT over the `issues` table.
Columns: number, title, state, label, assignee, opened (YYYY-MM-DD).
At most 50 rows come back. Other tables and WITH RECURSIVE are refused.
"""
log.info("query_issues called") # never log the SQL text or results
try:
return QueryResult(**run_readonly(DB_PATH, sql))
except QueryRejected as exc:
raise ToolError(str(exc)) from None
@mcp.resource("schema://issues")
def issues_schema() -> str:
"""Column list of the issues table, for writing queries."""
return "issues(number INTEGER, title TEXT, state TEXT, label TEXT, " \
"assignee TEXT, opened TEXT)"
@mcp.resource("issues://{number}", mime_type="application/json")
def issue_resource(number: int) -> str:
"""One issue as JSON, addressed by its number."""
issue = _load(number)
if issue is None:
raise ResourceNotFoundError(f"No issue #{number}")
return json.dumps(issue.model_dump())
if __name__ == "__main__":
mcp.run() # stdioWhat the SDK builds from this file:
- Input schema. The parameters and their hints become the tool's
inputSchema.Annotated[int, Field(ge=1)]adds"minimum": 1, and the SDK rejects a bad argument before your function runs, as a tool error the model can read. - Output schema and structured content. Because
get_issuereturns the Pydantic modelIssue, the tool definition carries anoutputSchema, and each result carriesstructuredContent(the object, field for field) plus the same JSON as a text block. The specification asks servers that declare an output schema to return conforming structured results, and recommends the text copy for clients that only read text. A return type such asintorlist[...]is wrapped as{"result": ...}. - Tool errors.
raise ToolError(...)produces a result withisError: trueand your message, which the model can act on. Returning a dict such as{"error": ...}would look like a success to the host. Unexpected exceptions also becomeisError: true, but the SDK keeps their text out of the result and logs the traceback instead. - Resources.
schema://issuesis a fixed resource.issues://{number}is a template (RFC 6570 URI template syntax): it appears inresources/templates/list, and any matching URI is resolved when read. A missing issue raisesResourceNotFoundError, which becomes JSON-RPC error-32602with the URI indata. - Configuration and logs. The database path comes from
ISSUES_DB, an absolute path set by whoever launches the server; hosts start stdio servers in a working directory you do not control. Logs go to stderr throughlogging, and the tool logs that it was called, not the SQL or the rows, which may hold personal data.
05. Step 3: Call it the way a host would
The SDK's Client can connect to a server object in memory, with no subprocess and no port. That makes it the quickest way to see exactly what a host receives. The script lists the tools, calls them, and reads the template.
"""Talk to the server in memory with the SDK's own Client."""
import asyncio
import json
import textwrap
from mcp import Client
from issues_server import mcp
def show(label: str, value: object) -> None:
text = value if isinstance(value, str) else json.dumps(value)
print(textwrap.fill(f"{label} {text}", 80, subsequent_indent=" "))
async def main() -> None:
async with Client(mcp) as client:
tools = (await client.list_tools()).tools
show("tools:", [t.name for t in tools])
show("input schema:", tools[0].input_schema["properties"])
show("output required:", tools[0].output_schema["required"])
ok = await client.call_tool("get_issue", {"number": 101})
show("structuredContent:", ok.structured_content)
show("text block:", " ".join(ok.content[0].text.split()))
miss = await client.call_tool("get_issue", {"number": 999})
show(f"isError={miss.is_error}:", miss.content[0].text)
bad = await client.call_tool(
"query_issues", {"sql": "SELECT secret FROM api_keys"})
show(f"isError={bad.is_error}:", bad.content[0].text)
templates = (await client.list_resource_templates()).resource_templates
show("template:", templates[0].uri_template)
page = await client.read_resource("issues://103")
show("issues://103 ->", page.contents[0].text)
asyncio.run(main())ISSUES_DB=$PWD/tracker.db python try_server.py 2>server.errtools: ["get_issue", "query_issues"]
input schema: {"number": {"minimum": 1, "title": "Number", "type": "integer"}}
output required: ["number", "title", "state", "label", "assignee"]
structuredContent: {"number": 101, "title": "Login fails with SSO", "state":
"open", "label": "auth", "assignee": "maya"}
text block: { "number": 101, "title": "Login fails with SSO", "state": "open",
"label": "auth", "assignee": "maya" }
isError=True: Error executing tool get_issue: No issue #999. Use query_issues to
find numbers.
isError=True: Error executing tool query_issues: Query refused: access to
api_keys.secret is prohibited
template: issues://{number}
issues://103 -> {"number": 103, "title": "Dark mode contrast too low", "state":
"closed", "label": "ui", "assignee": "maya"}The output shows each idea at work: the minimum in the input schema, the required fields of the output schema, structuredContent with its text copy, two different isError results with messages that say what to do next, and the template resolving issues://103. The file server.err holds the server's log lines, which never touched stdout.
To use the server from a desktop host, register the launch command with absolute paths. The shape below is the common mcpServers format; check your host's documentation for the file location.
{
"mcpServers": {
"issues": {
"command": "/home/you/issues-server/.venv/bin/python",
"args": ["/home/you/issues-server/issues_server.py"],
"env": { "ISSUES_DB": "/home/you/issues-server/tracker.db" }
}
}
}Older guides insist on PYTHONUNBUFFERED=1 for Python stdio servers. The SDK writes and flushes each message itself, so it is not needed here. It only helps hand-written servers that print to stdout and forget to flush: when stdout is a pipe, Python buffers it in blocks, so a reply can sit in the buffer until it fills.
06. Check your understanding
07. Apply it
Start the skill project: an issue-tracker server that you will grow over this skill. Add a tool list_labels that returns a typed model, so it has an output schema. Then add a resource template labels://{name} that returns the open issues for one label, and raise ResourceNotFoundError for unknown labels. Extend try_server.py to call both, and add one attack test to test_readonly_sql.py that you expect to fail before you fix it, for example a query against a view you create later. Lesson 3 wraps a REST API instead of a database, and lesson 4 turns scripts like try_server.py into contract tests.
08. Review prompt
Without looking back, explain to a colleague: where a Python SDK tool gets its input schema and its output schema; what a client receives when the tool succeeds, when it raises ToolError, and when it crashes; the difference between a resource and a resource template; and the five limits that make a read-only SQL tool safe enough to expose, with an attack each one stops.
References
- MCP docs: Build an MCP server
- MCP specification 2026-07-28: Tools (output schema, structured content, errors)
- MCP specification 2026-07-28: Resources and resource templates
- MCP Python SDK: Structured output
- MCP Python SDK: Handling errors
- MCP Python SDK: Migration guide (v1 to v2)
- Python docs: sqlite3 (set_authorizer, set_progress_handler)
- SQLite: Compile-time authorization callbacks
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.