FastMCP · Chapter 6 of 6
FastMCP and FastAPI sharing one SQLite database
13 min study · Examples checked with FastMCP 4.2 and MCP Python SDK 2.3 on Python 3.14 ·
A server’s Python dictionary disappears when the process stops. Copying business logic into separate MCP and REST handlers also creates two places for rules to drift. This chapter stores a small public catalog in SQLite and exposes the same lookup through both interfaces, with startup and shutdown owned by the application lifecycle.
Keep storage independent of the adapters
The repository owns SQL, connection cleanup, and row conversion. MCP and FastAPI translate their requests into calls to that repository. Neither interface calls the other over HTTP, so the application avoids an unnecessary network hop and duplicate validation machinery inside one process.
This example is deliberately read-only and contains only public sample lessons. It does not expose drafts or publishing tools. Use the previous chapter’s identity and authorization design before adding protected operations. A shared service does not automatically make every public REST operation suitable as an agent-facing tool.
Install fastmcp==4.2.0, fastapi==0.163.0, and uvicorn==0.54.0 in the example’s environment. Create repository.py:
from contextlib import closing
import sqlite3
class CatalogRepository:
def __init__(self, database_path: str):
self.database_path = database_path
def initialize(self) -> None:
with closing(sqlite3.connect(self.database_path)) as connection:
with connection:
connection.execute(
"CREATE TABLE IF NOT EXISTS lessons ("
"id INTEGER PRIMARY KEY, title TEXT NOT NULL, minutes INTEGER NOT NULL)"
)
connection.executemany(
"INSERT OR IGNORE INTO lessons (id, title, minutes) VALUES (?, ?, ?)",
[(1, "Python functions", 12), (2, "Django forms", 15)],
)
def get_lesson(self, lesson_id: int) -> dict | None:
with closing(sqlite3.connect(self.database_path)) as connection:
connection.row_factory = sqlite3.Row
row = connection.execute(
"SELECT id, title, minutes FROM lessons WHERE id = ?", (lesson_id,)
).fetchone()
return dict(row) if row is not None else None
Each operation opens and closes its own connection in the thread that uses it. The transaction context controls commit and rollback; closing() makes connection cleanup explicit because SQLite’s connection context manager alone does not close the connection. Parameters are bound separately instead of interpolated into SQL.
The seed insert is idempotent for these fixed primary keys and does not overwrite existing records. This initialization is a teaching convenience. A deployed evolving schema needs a reviewed migration strategy, and importing an application module should not silently migrate a production database.
Wire the server lifecycle and interfaces
Create app.py:
import asyncio
from contextlib import asynccontextmanager
import os
from fastapi import FastAPI, HTTPException, Path
from fastmcp import FastMCP
from fastmcp.exceptions import ToolError
from pydantic import Field
from typing import Annotated
from repository import CatalogRepository
def create_app(database_path: str) -> FastAPI:
repository = CatalogRepository(database_path)
@asynccontextmanager
async def lifespan(server):
await asyncio.to_thread(repository.initialize)
yield
mcp = FastMCP("Persistent public catalog", lifespan=lifespan, mask_error_details=True)
@mcp.tool(annotations={"readOnlyHint": True})
async def get_lesson(lesson_id: Annotated[int, Field(ge=1)]) -> dict:
"""Read a public lesson from the durable catalog by identifier."""
lesson = await asyncio.to_thread(repository.get_lesson, lesson_id)
if lesson is None:
raise ToolError("Lesson not found")
return lesson
mcp_app = mcp.http_app(path="/")
api = FastAPI(lifespan=mcp_app.lifespan)
api.mount("/mcp", mcp_app)
@api.get("/lessons/{lesson_id}")
def read_lesson(lesson_id: Annotated[int, Path(ge=1)]):
lesson = repository.get_lesson(lesson_id)
if lesson is None:
raise HTTPException(status_code=404, detail="Lesson not found")
return lesson
return api
app = create_app(os.environ.get("CATALOG_DB", "catalog.db"))
Run uvicorn app:app --host 127.0.0.1 --port 8000 from this directory. Startup initializes the configured SQLite file. REST is available at /lessons/1, and MCP is mounted at /mcp/. The mount prefix and the inner path="/" combine into that endpoint; they should not accidentally produce /mcp/mcp.
FastAPI must run the MCP application’s lifespan. A mounted ASGI application’s startup is not automatically equivalent to running all of its nested lifecycle hooks. The explicit lifespan connection starts and stops the MCP transport machinery and the catalog initialization together. See the FastAPI integration guide.
Keep blocking I/O out of async handlers
The REST handler uses def, so FastAPI’s synchronous handler integration runs its blocking repository call appropriately. The MCP handler uses async def and explicitly moves SQLite work to a thread. Writing async def around a blocking database call would otherwise block the event loop during that call.
Each thread creates its own SQLite connection, so the repository does not share a connection across unrelated threads. For larger workloads, use an appropriate database, driver, and connection-pool strategy. Thread offloading does not make SQLite a distributed database or remove transaction design requirements.
Compare the two public contracts
Create client.py for the running HTTP service:
import asyncio
from fastmcp import Client
async def main():
async with Client("http://127.0.0.1:8000/mcp/", timeout=10) as client:
result = await client.call_tool("get_lesson", {"lesson_id": 1})
assert result.data["title"] == "Python functions"
print(result.data)
if __name__ == "__main__":
asyncio.run(main())
The REST operation represents a resource URL and returns HTTP 404 for a missing row. The MCP operation has a tool name, argument schema, and protocol-level error behavior. Both ask the same repository for the same record, but their public errors need not have identical envelopes.
Automatic OpenAPI conversion can bootstrap an MCP interface, but exposing every endpoint can produce an unwieldy or inappropriate tool surface. Select domain operations intentionally, with compact results and clear descriptions. In Django, the same separation can use an application service and ORM repository; preserve Django’s initialization and sync/async boundaries rather than importing views as generic tools.
Practice
Read a lesson through both interfaces, stop the service, and confirm the database file remains. Change a title in a temporary database using a parameterized update, restart with that file, and check both interfaces return the new title. Verify a missing identifier produces an appropriate failure through each adapter.
Answer check: committed storage outlives the application, seed initialization does not replace the edited title, and both adapters agree on the stored record. Imports alone do not create the database; application startup does.
Summary
Share domain logic and storage while keeping each interface’s contract explicit. Correct lifecycle wiring, connection ownership, and persistence behavior matter as much as the tool decorator.