Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Worked example · 20 min · revision 3

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

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 FastMCP in mcp.server.fastmcp. Version 2 renamed it MCPServer, imported with from mcp.server import MCPServer; the old import fails on 2.x. Pin mcp<2 only 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 $schema key. 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:

  1. a tool get_issue that returns one issue as typed data, with an output schema;
  2. a tool query_issues for ad-hoc questions in read-only SQL;
  3. a static resource schema://issues describing the columns;
  4. 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.

Terminal
mkdir issues-server && cd issues-server
python3 -m venv .venv && source .venv/bin/activate
python -m pip install "mcp==2.3.0"
Python · issues-server/seed_db.py
"""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")
Terminal
python seed_db.py
Expected output
created tracker.db with 4 issues

03. 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=ro makes SQLite refuse every write. It also fails when the file is missing, instead of quietly creating an empty database.
  • Authoriser allowlist. set_authorizer is called for each table and column a statement touches while it is compiled. Allow SELECT, functions and reads of the issues table, and deny everything else: other tables, sqlite_master, ATTACH, PRAGMA. Two functions are denied by name, zeroblob and randomblob, because one call such as zeroblob(1000000000) allocates about 1 GB in a single step, before the work budget can stop it. Plain common table expressions such as WITH o AS (SELECT ... FROM issues) SELECT ... still work, because SQLite asks the authoriser only about the tables they read; WITH RECURSIVE is refused, because the allowlist does not include SQLITE_RECURSIVE. A CTE that reads api_keys is refused like any other read of that table, and test_cte_rules pins all three cases.
  • Work budget. set_progress_handler runs 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 nested replace calls.
  • 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.

Python · issues-server/readonly_sql.py
"""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.

Python · issues-server/test_readonly_sql.py
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)
Terminal
python -m unittest test_readonly_sql
Illustrative output (the run time on the Ran line differs on every machine)
.........
----------------------------------------------------------------------
Ran 9 tests in 0.902s

OK

04. Step 2: Typed tools, a resource and a template

Now the server. Read it once, then look at the notes below it.

Python · issues-server/issues_server.py
"""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()  # stdio

What 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_issue returns the Pydantic model Issue, the tool definition carries an outputSchema, and each result carries structuredContent (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 as int or list[...] is wrapped as {"result": ...}.
  • Tool errors. raise ToolError(...) produces a result with isError: true and 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 become isError: true, but the SDK keeps their text out of the result and logs the traceback instead.
  • Resources. schema://issues is a fixed resource. issues://{number} is a template (RFC 6570 URI template syntax): it appears in resources/templates/list, and any matching URI is resolved when read. A missing issue raises ResourceNotFoundError, which becomes JSON-RPC error -32602 with the URI in data.
  • 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 through logging, 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.

Python · issues-server/try_server.py
"""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())
Terminal
ISSUES_DB=$PWD/tracker.db python try_server.py 2>server.err
Expected output
tools: ["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.

JSON · host configuration (paths are examples)
{
  "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

Practice check · 3 questions

First server with the SDK

Answer from what you built in this lesson.

Q1. An earlier `issues_server.py` opened `file:tracker.db?mode=ro` by a relative path. It worked when you started it inside `issues-server`. Registered in a desktop host, every call fails with `unable to open database file`. What is the likely cause?
Q2. Your query tool accepts any SQL that starts with `SELECT`. Which request still reads the `api_keys` table?
Q3. `try_server.py` gets `isError=True` back from `get_issue` for issue 999. What does `client.read_resource("issues://999")` give the client instead?
Practice only: not graded, not saved, not evidence.

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

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check