Introduction
Your application already has orders, documents, or appointments behind a FastAPI backend. An AI assistant could help customers use that information, but giving a model unrestricted access to your API would expose far more capability than most tasks require.
Model Context Protocol, or MCP, provides a standard interface through which an AI application can discover and call tools. In a FastAPI product, it can act as an additional adapter over existing application services. Authentication, customer isolation, validation, and the final business decision still belong to your backend.
This tutorial is for Python developers who know FastAPI, typed request models, and basic authentication concepts. The example was tested with Python 3.12.14, mcp 2.3.0, FastAPI 0.156.2, and Pydantic 2.14.1, using the 2026-07-28 MCP protocol. It exposes one read-only order lookup and uses local demonstration tokens. It is not a complete production OAuth deployment.
The July 2026 MCP specification release changed the protocol's request lifecycle. Use documentation matching your installed SDK and intended clients rather than combining initialization examples from older releases with current request envelopes.
Decide Whether You Need MCP
MCP is useful when multiple MCP-capable hosts should discover and use a focused set of product capabilities. If one private assistant already calls two internal functions, ordinary function calling against those application services may be sufficient.
Adding MCP does not automatically make your backend safer, improve the model's reasoning, or replace your mobile app's REST API. It introduces another integration contract that needs tests, versioning, monitoring, and an owner.
| Interface | Typical consumer | Responsibility |
|---|---|---|
| REST endpoint | Your mobile app or web dashboard | Stable application requests and responses |
| MCP tool | An AI host acting for an authorized caller | A discoverable, constrained task with a typed result |
| Application service | Both adapters | Business rules and authorized access to records |
| Database or external provider | Application service | Persistence or an explicitly scoped integration |
Share the application service rather than copying authorization logic into every adapter. If your service checks order ownership for REST but your MCP tool queries the table directly, the new interface can bypass the rule that protected the original application.
For the underlying API structure, see the FastAPI guide. This article concentrates on the agent-facing boundary.
Design Tools Around Customer Tasks
Start with a tool such as get_order_status. It should answer one question, accept a constrained identifier, and return only the fields needed for that answer.
Avoid starting with run_sql, a general HTTP proxy, or a tool that accepts an arbitrary operation name. Those interfaces make the model responsible for understanding much more of your system and make permissions harder to review.
A good tool description explains what the tool does, what the caller must supply, and whether it changes anything. Its output should distinguish a real result from a failure. A returned string saying “database unavailable” can be mistaken for a successful answer if the tool reports success around it.
The MCP Python SDK error guide describes ToolError for a failed tool execution. Use safe, actionable error messages and keep internal exception details out of the model-visible response.
In our example, an unavailable order gets the same message whether it does not exist or belongs to another customer. That avoids confirming another customer's order identifiers through different error messages.
Build an Authenticated Local Example
Create a directory containing server.py, then install the versions used here in a virtual environment:
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install "mcp==2.3.0" "fastapi==0.156.2" "pydantic==2.14.1" "uvicorn==0.54.0"
The example has two customer namespaces, North and South. Its token verifier maps local test credentials to a server-controlled tenant claim. The model never supplies that claim as a tool argument.
The verifier is deliberately limited to local experimentation: it has no sign-in flow, token expiry policy, or external identity-provider integration. The auth.example.com value is a placeholder, not a functioning authorization server. Keep the application bound to loopback while using this verifier.
"""Local-only read tool fixture. Replace token verification before deployment."""
import os
import secrets
from contextlib import asynccontextmanager
from typing import Annotated
from fastapi import FastAPI
from mcp.server import MCPServer
from mcp.server.auth.middleware.auth_context import get_access_token
from mcp.server.auth.provider import AccessToken, TokenVerifier
from mcp.server.auth.settings import AuthSettings
from mcp.server.mcpserver.exceptions import ToolError
from mcp.types import ToolAnnotations
from pydantic import AnyHttpUrl, BaseModel, Field
RESOURCE = "http://127.0.0.1:8000/mcp"
class LocalTokenVerifier(TokenVerifier):
async def verify_token(self, token: str) -> AccessToken | None:
for tenant, variable in [("north", "NORTH_DEMO_TOKEN"), ("south", "SOUTH_DEMO_TOKEN")]:
expected = os.environ.get(variable)
if expected and secrets.compare_digest(token, expected):
return AccessToken(
token=token, client_id="local-demo", subject=f"{tenant}-user",
scopes=["orders:read"], resource=RESOURCE,
claims={"tenant_id": tenant},
)
return None
mcp = MCPServer(
"Order support",
token_verifier=LocalTokenVerifier(),
auth=AuthSettings(
issuer_url=AnyHttpUrl("https://auth.example.com"),
resource_server_url=AnyHttpUrl(RESOURCE),
required_scopes=["orders:read"],
validate_token_resource=True,
),
)
class OrderSummary(BaseModel):
order_id: str
status: str
ORDERS = {
("north", "order-100"): OrderSummary(order_id="order-100", status="processing"),
("south", "order-200"): OrderSummary(order_id="order-200", status="shipped"),
}
@mcp.tool(annotations=ToolAnnotations(read_only_hint=True))
def get_order_status(
order_id: Annotated[str, Field(pattern=r"^order-[0-9]{1,10}$")],
) -> OrderSummary:
"""Read an order status visible to the signed-in customer. Does not change orders."""
token = get_access_token()
if token is None or "orders:read" not in token.scopes:
raise ToolError("Order access is unavailable.")
tenant = (token.claims or {}).get("tenant_id")
if not isinstance(tenant, str):
raise ToolError("Order access is unavailable.")
order = ORDERS.get((tenant, order_id))
if order is None:
raise ToolError("Order unavailable for this account.")
return order
mcp_app = mcp.streamable_http_app(json_response=True, stateless_http=True)
@asynccontextmanager
async def lifespan(app: FastAPI):
async with mcp.session_manager.run():
yield
app = FastAPI(lifespan=lifespan)
@app.get("/health")
def health():
return {"status": "ok"}
# Keep the root mount last so it does not swallow the FastAPI routes.
app.mount("/", mcp_app)
The SDK's ASGI integration guide explains why the parent application must manage the mounted MCP application's lifespan. Here the MCP app is created first, and FastAPI starts its manager in lifespan. The root mount comes after /health so it does not intercept that route.
With this mounting arrangement, the public MCP endpoint is /mcp. Mounting the default MCP app at /mcp instead would add another path prefix; inspect the resulting route rather than assuming its address.
The read_only_hint annotation describes the tool to clients. It is not an authorization check. The actual restrictions are in token validation and the tenant-scoped lookup.
Try the Tool Over HTTP
Set a local credential and start the server. This example value is for a loopback demonstration only:
export NORTH_DEMO_TOKEN='north-local-demo-only'
uvicorn server:app --host 127.0.0.1 --port 8000
In a separate terminal, send a request for North's fixture order:
curl http://127.0.0.1:8000/mcp \
-H 'Authorization: Bearer north-local-demo-only' \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-H 'MCP-Protocol-Version: 2026-07-28' \
-H 'Mcp-Method: tools/call' \
-H 'Mcp-Name: get_order_status' \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "get_order_status",
"arguments": {"order_id": "order-100"},
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {}
}
}
}'
The result's structuredContent contains order_id and status. Change the argument to order-200 while keeping North's credential. The tool should return an error, because that order belongs to South. Remove the authorization header and the HTTP layer should reject the request before the tool runs.
This request demonstrates the current protocol envelope explicitly. In an application integration, use a compatible MCP client SDK rather than reproducing the protocol in every feature. Test the actual hosts you intend to support; a passing local request does not establish compatibility with every existing client.
Replace the Demonstration Verifier Before Deployment
The production identity provider should establish who the caller is. Your MCP resource server verifies the token, including its intended resource or audience, issuer, expiry, and required scopes. Do not accept a decoded JWT merely because it contains a plausible tenant identifier.
The SDK's authorization documentation describes the token verifier and protected-resource metadata. Configure that flow for your identity provider and your actual public MCP URL. The local dictionary-style verifier above demonstrates the boundary, not the implementation of production identity.
Resolve the customer account from verified identity and server-side membership. In a multi-organization app, selecting an organization does not itself prove membership. Check that membership before running the tool, and apply any per-user restrictions inside the organization.
The MCP security guidance also rejects token passthrough. A token intended for an unrelated service should not become authorization for your MCP endpoint or be forwarded indiscriminately to downstream systems. Keep delegated credentials limited to their intended resource and permissions.
For the database version of this example, constrain the query with the authorized tenant before retrieving the record. Returning all orders and filtering them later creates unnecessary opportunities for data to enter logs, traces, or model context.
Introduce Write Tools with a Separate Approval Step
A read tool is a useful first integration because it has fewer business consequences. A tool that cancels an order, schedules a message, or issues a refund needs a more explicit flow.
I would separate preparation from execution:
- A preparation tool checks the current record and returns a proposed operation with its effect, revision, and expiry.
- The application shows that operation to the authorized person through a trusted confirmation surface.
- The backend records approval bound to that person and the exact proposed operation.
- A commit tool checks the approval, current permissions, record revision, and idempotency key before performing the change.
A model-generated approved: true field is not evidence that a person approved anything. Similarly, a generic “yes” in a conversation should not approve a different amount or recipient after the draft changes.
Make the final operation retry-safe. If an upstream provider accepts the change but your request times out, the next attempt must reconcile the previous result rather than issue the change again. Keep the idempotency record in durable storage and scope it to the user and operation.
For work that outlasts a short request, return a job identifier and expose progress through a deliberate contract. The reliable AI document-processing guide explains durable jobs, retries, and recovery boundaries. Moving a long operation into an in-memory task does not provide those guarantees.
Treat Tool Content as Data
A tool may retrieve a document that contains instructions such as “ignore previous rules” or “send this information elsewhere.” That document is customer or external content, not an authorization policy.
Keep model instructions separate from retrieved content, return bounded results, and prevent the model from choosing arbitrary network destinations or database queries. If a feature needs remote URLs, validate the destinations and redirects in the service that fetches them. Restrict outbound access where the environment permits it.
Prompt instructions can help an assistant behave sensibly, but server checks are what prevent an unauthorized action. Test a malicious instruction inside an otherwise legitimate document and verify that it cannot widen the caller's permissions.
Retrieval also needs scope. An agent that uses RAG should search only the documents that caller is allowed to see, before the results enter the model context. The RAG architecture guide explains the retrieval pipeline; apply the same access policy to search and subsequent document reads.
Test the Boundary, Not Just the Function
Calling get_order_status directly is insufficient to test this integration. It skips the mounted route, request metadata, authentication middleware, and application lifespan.
The accompanying example was exercised through FastAPI's ASGI test client with the real MCP route. Seven checks passed:
| Check | Expected result |
|---|---|
| FastAPI health route | Still reachable after mounting MCP |
| Missing credential | HTTP 401 |
| Incorrect credential | HTTP 401 |
| North reading North's order | Structured status result |
| North reading South's or a missing order | Matching tool errors |
| South reading South's order | South's own status result |
| Malformed order identifier | Validation error |
These tests use local fixtures and the pinned protocol. They do not verify a real identity provider, proxy, database, model, or public deployment. The SDK testing guide also provides an in-process client for narrower tool tests; use both levels when they exercise different failure modes.
Before production, add expired-token and wrong-audience tests, a valid token with insufficient scope, revoked membership, concurrent users, and the host's discovery flow. Write tools also need duplicate-request, changed-approval, and interrupted-execution tests.
A model evaluation is another layer. Give the assistant realistic questions and inspect whether it chooses the right tool, supplies valid arguments, handles a denied result correctly, and avoids reporting a change that never happened.
Make the Integration Operable
Record enough context to explain an operation: request identifier, authorized principal, tool name, outcome, duration, and relevant domain-operation identifier. Do not log raw access tokens. Avoid recording complete tool arguments or results by default when they contain private information.
Apply timeouts and limits at the service boundary. Cap expensive queries, returned records, concurrent calls, and downstream requests per customer. A tool that the model can call repeatedly can create substantial load even when each individual call looks reasonable.
Configure HTTPS, the deployed hostname and origin allowlists, and proxy behavior for the SDK transport. An ordinary mobile API CORS configuration is not proof that an MCP browser client can send the required headers. Test the deployed path through the same proxy customers will use.
Keep a way to disable an individual tool without disabling the whole product. For a first pilot, enable one read workflow for a small group, inspect failures, and agree on the conditions for adding writes. Measure successful customer tasks as well as protocol-level success.
Conclusion
MCP gives an AI host a standard way to reach product capabilities. FastAPI and your application services remain responsible for what those capabilities are allowed to do.
- Start with a narrow tool and a small structured result.
- Derive customer identity from verified credentials, not model arguments.
- Share authorization and business rules with existing application interfaces.
- Test the real MCP route as well as the underlying function.
- Add consequential writes only with explicit approval and durable retry handling.
Connecting an AI assistant to your existing product? I help teams define useful backend tools, their permission boundaries, and a rollout they can test and operate. Book a meeting to discuss your first MCP integration.
See the project work
Explore the decisions, scope, and validation behind selected mobile and AI projects.
Explore case studies