How to build an MCP server: a Python and TypeScript tutorial
An MCP server is a program that exposes tools, resources, and prompts to AI applications through the Model Context Protocol, so any compatible host can discover and call them without custom integration code. This guide shows how to build an MCP server end to end: a small Python server on the official SDK that wraps a public API, the same tool in TypeScript, tests with an in-memory client and the MCP Inspector, host configuration, and the controls a remote server needs before production traffic. For the protocol's architecture, start with what the Model Context Protocol is.
What does an MCP server expose?#
An MCP server exposes three primitives, and they differ by who decides to use them. Tools are functions the model calls, resources are data the host application attaches as context, and prompts are templates the user picks. Most servers that wrap an API are mainly tools, with a resource or two for reference data.
| Primitive | Controlled by | Client discovers it with | In this guide's server |
|---|---|---|---|
| Tools | The model | tools/list, then tools/call |
get_package, check_vulnerabilities |
| Resources | The host application | resources/list, resources/templates/list |
pypi://{name}/readme |
| Prompts | The user | prompts/list, then prompts/get |
None |
Build an MCP server when more than one AI application needs the same capability, or when you own a system that other teams' agents should reach through one reviewed interface. If a single application calls a single model, functions defined inside that application through plain tool calling are simpler. The server never talks to the model directly: the host lists your tools, passes them to its model, and forwards the model's calls back to you.
Choose a transport: stdio or Streamable HTTP#
Choose stdio when the server runs on the same machine as the host, which launches it as a subprocess and talks over stdin and stdout. Choose Streamable HTTP when the server is deployed for many users: each JSON-RPC message is an HTTP POST to one endpoint. The server code stays the same; only the run call changes.
| stdio | Streamable HTTP | |
|---|---|---|
| Who starts the server | The host, as a child process | You, as a web service |
| Wire format | Newline-delimited JSON-RPC on stdin and stdout | One POST endpoint, such as /mcp; replies as JSON or a per-request SSE stream |
| Clients per process | Usually one | Many |
| Credentials | Environment variables | OAuth 2.1 bearer tokens |
| Main hazard | Any non-protocol output on stdout breaks the stream | DNS rebinding, token misuse, abuse at scale |
| Typical use | Local files, CLIs, a user's own API key | Shared SaaS integrations, internal platforms |
The current specification, revision 2026-07-28, made both transports stateless. The initialize handshake and protocol-level sessions are gone: every request carries its protocol version and client capabilities in _meta, and every server must answer server/discover. Streamable HTTP also mirrors the method and tool name into Mcp-Method and Mcp-Name headers so gateways can route without parsing bodies. For server authors, any replica can answer any request, and state that spans calls must travel as an explicit handle in tool arguments. The older HTTP+SSE transport is deprecated, so do not build on it.
Set up the Python SDK#
The official Python SDK is the mcp package on PyPI, which requires Python 3.10 or later. Version 2, released on July 28, 2026, alongside the 2026-07-28 specification, renamed the high-level FastMCP class to MCPServer and removed the old import path, so v1 tutorials that import mcp.server.fastmcp no longer run unchanged.
Install it with pip install "mcp[cli]" or uv add "mcp[cli]". The cli extra adds the mcp command: mcp dev opens a server in the MCP Inspector, mcp run starts it, and mcp install registers it with Claude Desktop. The SDK depends on the httpx2 HTTP client, so the example below uses it without another install. According to the v2 release notes, one v2 server answers both 2025-11-25 and 2026-07-28 clients with no configuration, so older hosts keep working.
The name FastMCP still causes confusion. The standalone FastMCP project says its version 1.0 was incorporated into the official SDK in 2024; today it is a separate framework maintained by Prefect and installed with pip install fastmcp, with its own API. This guide uses the official SDK. The MCP platforms directory lists FastMCP alongside registries, hosting services, and gateways.
Build the server: tools, schemas, and a resource#
The example server wraps two read-only endpoints of PyPI's JSON API, which needs no API key. It exposes two tools, one that returns a package's latest version and one that lists known advisories for a release, plus a resource template that serves a project's README. Type hints become the schemas clients see.
from typing import Annotated
import httpx2
from pydantic import BaseModel, Field
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp.types import ToolAnnotations
mcp = MCPServer("pypi")
READ_ONLY = ToolAnnotations(read_only_hint=True, open_world_hint=True)
PackageName = Annotated[str, Field(
pattern=r"^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$",
description="Exact PyPI project name, for example 'requests'.",
)]
Version = Annotated[str, Field(
pattern=r"^[0-9][A-Za-z0-9.+!-]{0,63}$",
description="Exact release, for example '2.31.0'.",
)]
class Package(BaseModel):
name: str
version: str = Field(description="Latest released version.")
summary: str | None
requires_python: str | None
class Advisory(BaseModel):
id: str
fixed_in: list[str] = Field(description="Fixed releases, if any.")
async def fetch(path: str) -> dict:
async with httpx2.AsyncClient(timeout=10.0) as client:
r = await client.get(f"https://pypi.org/pypi/{path}/json")
if r.status_code == 404:
raise ToolError(f"No PyPI project or release at '{path}'.")
if r.status_code != 200:
raise ToolError(f"PyPI returned {r.status_code}; retry later.")
return r.json()
@mcp.tool(annotations=READ_ONLY)
async def get_package(name: PackageName) -> Package:
"""Get the latest version and Python range of a PyPI package.
Use it before recommending a package or pinning a version."""
return Package.model_validate((await fetch(name))["info"])
@mcp.tool(annotations=READ_ONLY)
async def check_vulnerabilities(
name: PackageName, version: Version
) -> list[Advisory]:
"""List known security advisories for one release of a package.
An empty list means PyPI knows of none, not that it is safe."""
data = await fetch(f"{name}/{version}")
return [Advisory(id=v["id"], fixed_in=v["fixed_in"])
for v in data.get("vulnerabilities", [])
if not v.get("withdrawn")]
@mcp.resource("pypi://{name}/readme", mime_type="text/markdown")
async def readme(name: str) -> str:
"""The project's long description, usually its README."""
return (await fetch(name))["info"]["description"] or ""
if __name__ == "__main__":
mcp.run() # stdio; mcp.run(transport="streamable-http") for HTTPEach decorator is the whole registration. The SDK reads everything else from the function:
- Name and description. The function name becomes the tool name, and the docstring becomes the description the model reads. The second sentence of each docstring tells the model when to call the tool and how to read an empty result.
- Input schema.
Annotated[str, Field(pattern=...)]becomes a JSON Schema property with apatternand adescription. The SDK validates arguments before the function runs, so a name such as../adminnever reaches the URL, and the model receives the validation message as a tool error it can correct. - Output schema. Returning a Pydantic model publishes an
outputSchemaand fillsstructuredContentnext to a JSON text copy incontent; a list is wrapped as{"result": [...]}. This is server data for the host, unrelated to structured outputs from a model. - Errors.
ToolErrorreturns a result withisError: trueand your message, which the model can act on. Returning an error string instead would look like success. Any other exception also returnsisError: true, but with a generic message, while the traceback stays in the server log. - Annotations.
read_only_hintandopen_world_hinthelp hosts decide whether to ask the user before a call. They are hints, not enforcement, and the specification tells clients to treat them as untrusted unless the server is trusted. - Resource.
pypi://{name}/readmeis a template the host reads withresources/read. The SDK's default resource security rejects..segments, absolute paths, and null bytes in template values.
check_vulnerabilities calls the release endpoint, /pypi/<name>/<version>/json, because the project endpoint reports vulnerabilities only for the latest release. Wrapping an API this way, as a few task-shaped tools rather than one tool per endpoint, is the core of building an MCP server for an API.
The same server in TypeScript#
The official TypeScript SDK v2 ships as @modelcontextprotocol/server and @modelcontextprotocol/client, replacing v1's single @modelcontextprotocol/sdk package, which still receives fixes on a separate branch. Tool inputs are declared with Zod v4 or another Standard Schema library, and the SDK derives JSON Schema from them. It runs on Node.js, Bun, and Deno.
import { McpServer } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
import * as z from 'zod/v4';
const Package = z.object({
name: z.string(),
version: z.string(),
summary: z.string().nullable(),
requires_python: z.string().nullable(),
});
const PackageName = z
.string()
.regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/)
.describe("Exact PyPI project name, for example 'requests'.");
function createServer(): McpServer {
const server = new McpServer({ name: 'pypi', version: '1.0.0' });
server.registerTool(
'get_package',
{
description:
'Get the latest version and Python range of a PyPI package.',
inputSchema: z.object({ name: PackageName }),
outputSchema: Package,
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ name }) => {
const res = await fetch(`https://pypi.org/pypi/${name}/json`, {
signal: AbortSignal.timeout(10_000),
});
// A thrown error reaches the model as a result with isError: true
if (!res.ok) throw new Error(`PyPI returned ${res.status}.`);
const out = Package.parse((await res.json()).info);
return {
content: [{ type: 'text', text: JSON.stringify(out) }],
structuredContent: out,
};
},
);
return server;
}
void serveStdio(createServer);Install the dependencies with npm install @modelcontextprotocol/server zod; the server package requires Node.js 20 or later. serveStdio takes a factory and replaces v1's StdioServerTransport and connect() wiring. The SDK catches a thrown error and returns it as an isError: true result, and it validates structuredContent against outputSchema before the result leaves the server. For remote deployment, the TypeScript SDK publishes thin adapters for Express, Fastify, Hono, and Node's http module.
Test your MCP server#
Test an MCP server at two levels. In code, the SDK's own client connects to the server object in memory, with no subprocess or port, so listing and calling tools works in ordinary unit tests. Interactively, the MCP Inspector launches the server, renders forms from each tool's input schema, and shows the raw JSON-RPC traffic.
import anyio
from mcp import Client
from server import mcp
async def main() -> None:
async with Client(mcp) as client: # in memory, no subprocess
names = [t.name for t in (await client.list_tools()).tools]
assert names == ["get_package", "check_vulnerabilities"]
pkg = await client.call_tool("get_package", {"name": "mcp"})
print(pkg.structured_content["version"]) # 2.3.0 on 2026-11-06
args = {"name": "requests", "version": "2.31.0"}
adv = await client.call_tool("check_vulnerabilities", args)
print(adv.structured_content["result"][0])
# {'id': 'GHSA-9wx4-h78v-vm56', 'fixed_in': ['2.32.0']}
bad = await client.call_tool("get_package", {"name": "../x"})
assert bad.is_error # the schema rejects it before any request
doc = await client.read_resource("pypi://mcp/readme")
assert doc.contents[0].text.startswith("# MCP Python SDK")
anyio.run(main)The same Client class tests the real transports. Passing StdioServerParameters(command="python", args=["server.py"]) launches the server as a subprocess, and passing a URL such as http://127.0.0.1:8000/mcp connects over Streamable HTTP. We ran all three against the server above with mcp 2.3.0, and each connection reported protocol version 2026-07-28. The TypeScript server passed the equivalent checks with the TypeScript client.
For interactive work, mcp dev server.py opens the MCP Inspector, which requires Node.js 22.19.0 or later. Its CLI mode suits CI: npx @modelcontextprotocol/inspector --cli python server.py --method tools/list prints the tool definitions, --method tools/call with --tool-name and --tool-arg calls one, and a call that returns isError: true exits with code 5. Adding --strict to tools/list fails the run when a tool schema has portability errors that some clients would reject.
Connect it to a client#
Desktop hosts and IDEs connect to a local server through a JSON config file that names the server and the command that launches it. Claude Desktop, Claude Code's project .mcp.json, and the portable .mcp.json format that VS Code reads all use an mcpServers object whose entries hold a command, its args, and an optional env.
{
"mcpServers": {
"pypi": {
"command": "uv",
"args": [
"run", "--with", "mcp[cli]",
"mcp", "run", "/absolute/path/to/server.py"
]
}
}
}For Claude Desktop, this goes in claude_desktop_config.json, under ~/Library/Application Support/Claude/ on macOS and %APPDATA%\Claude\ on Windows; mcp install server.py writes the entry for you. VS Code's own .vscode/mcp.json uses a servers key instead and adds "type": "stdio" to each entry. Clients that accept remote entries in these files, such as Claude Code and VS Code, take "type": "http" and a url, such as https://mcp.example.com/mcp, instead of a command. The AI coding tools directory lists more hosts, and our guide to AI coding agents covers how they use MCP.
Three mistakes cause most connection failures. A relative path breaks because the host launches the server from its own working directory. A host keeps its old config until it restarts, and Claude Desktop must be fully quit. And on stdio, any print() to stdout corrupts the protocol stream, so log to stderr. The host also passes a minimal environment, so put API keys in env rather than relying on your shell.
Production concerns for remote MCP servers#
A remote MCP server is a network-facing service that runs code on behalf of a model, so it needs the controls of any API plus a few specific to MCP. The specification's tools page requires servers to validate all tool inputs, implement access controls, rate limit tool invocations, and sanitize tool outputs.
Authorization#
Authorization is optional in MCP and defined only for HTTP. A server that adopts it acts as an OAuth 2.1 resource server under the authorization specification: it must publish Protected Resource Metadata (RFC 9728), answer invalid or expired tokens with HTTP 401, and validate that each token was issued for this server as its audience (RFC 8707). It must not accept or pass through tokens issued for other services. To call an upstream API for the user, the server needs its own credential for that API, never the client's MCP token.
In the Python SDK, you implement a TokenVerifier that checks a JWT signature or calls your authorization server's introspection endpoint, then pass it to MCPServer with auth=AuthSettings(issuer_url=..., resource_server_url=..., required_scopes=[...]). The SDK serves the metadata document at /.well-known/oauth-protected-resource/mcp, returns the 401 with a WWW-Authenticate header that points to it, and exposes the caller's identity and scopes to handlers through get_access_token(). None of this applies to stdio, where the security boundary is the process that launched the server.
Least privilege and input validation#
Give each tool the narrowest access its task needs. The specification's security guidance recommends a minimal initial scope set, step-up authorization through targeted scope challenges in WWW-Authenticate when a privileged tool is first called, and no wildcard scopes. Back read-only tools with read-only upstream credentials. Schemas catch malformed input, but ownership and business rules still need checks in code on every call, and a state handle such as a cart ID must be bound to the authenticated user rather than treated as proof of access.
Tool poisoning and prompt injection#
Tool descriptions and results go straight into the model's context, which makes them an injection channel. Invariant Labs named tool poisoning in April 2025, showing a malicious add tool whose hidden description told an agent in Cursor to read ~/.ssh/id_rsa and send it in a tool argument. It also described rug pulls, a tool poisoning variant in which a server changes a tool's description after the user approved it.
As a server author, keep descriptions short and factual, version every change to them, and never build them from untrusted data. Treat your outputs as a second channel: the README this guide's resource returns is written by each package's author, so it can carry prompt injection. Truncate and label third-party text, and let hosts apply guardrails to results.
Transport hardening, rate limits, and logging#
The remaining controls are operational, and most take a few lines of configuration:
- Origin and Host checks. Streamable HTTP servers must validate
Originto block DNS rebinding; our server returned 403 for a foreign origin. The Python SDK accepts only localhostHostheaders until you passtransport_security=TransportSecuritySettings(allowed_hosts=[...], allowed_origins=[...]). - Limits. Rate limit per token and per tool, set timeouts on upstream calls, and cap result sizes. The Python SDK rejects request bodies over 4 MiB by default.
- Logging. Log tool name, caller, redacted arguments, latency, and
isErrorfor every call, to stderr on stdio. MCP-level logging such asctx.info()is deprecated in SDK v2, so use the language's logging library and feed the records into LLM observability. - Gateways. Many servers behind one AI gateway or MCP gateway, such as Bifrost, get central authentication, tool allowlists, and audit logs; what an AI gateway is explains the pattern.
MCP tool design checklist#
Good MCP tools are few, specific, and predictable. Before shipping a server, check each tool against the list below, which combines the specification's naming rules with lessons from building this example. The tool calling guide covers general tool design for models in more depth.
- Names follow the specification. Use 1 to 128 characters from ASCII letters, digits, underscores, hyphens, and dots, unique within the server. Hosts that aggregate servers may prefix names to avoid collisions.
- Descriptions say when to use the tool, what an empty result means, and any limits, in a sentence or two.
- One task per tool. Shape tools around what a user wants done, not around each API endpoint.
- Every input is constrained with types, enums, patterns, or bounds, so bad calls fail before your code runs.
- Results are compact and typed. Return an output schema, resolve opaque IDs to readable names, and paginate long lists.
- Errors are actionable. Raise tool errors with a message the model can fix; reserve protocol errors for requests no model can repair.
- Annotations are honest. Mark read-only, destructive, idempotent, and open-world behavior correctly, and put writes in separate tools so hosts can require approval.
- The tool list is stable. Return tools in a deterministic order, which the 2026-07-28 changelog recommends for client caching and prompt cache hits.
- State is explicit. Pass cross-call state as a handle, bound to the caller, with its expiry stated in the description.
- Tests run in CI with the in-memory client and the Inspector's
--strictschema check.
Where to go next#
With a server built and tested, the next step is the agent that calls your tools. Our guide to building an AI agent covers the loop on the other side, and A2A vs MCP explains when agents should talk to each other instead of to tools. The MCP topic hub collects every guide on the protocol.
Frequently asked questions
Is FastMCP the same as the official MCP Python SDK?
- Not anymore. FastMCP 1.0 was incorporated into the official Python SDK in 2024, and the SDK's high-level server class was named FastMCP until version 2. In v2, released July 28, 2026, that class is MCPServer, imported from mcp.server. A separate FastMCP framework, maintained by Prefect and published on PyPI as fastmcp, continues as an independent project with its own API.
How do I build an MCP server in TypeScript?
- Install @modelcontextprotocol/server and zod, create an McpServer, and register each tool with registerTool, passing a description, a Zod inputSchema, and an async handler. The SDK converts the Zod schema to JSON Schema and rejects invalid arguments before the handler runs. Serve it locally with serveStdio from @modelcontextprotocol/server/stdio, or over HTTP through one of the SDK's framework adapters.
How do I turn an existing API into an MCP server?
- Write a thin server that wraps the API with a few task-shaped tools rather than one tool per endpoint. Give each tool a description that says when to use it, constrain inputs with types and patterns, return compact structured results, and convert API failures into tool errors the model can act on. Read-only data that supplies context, such as documentation, fits better as a resource.
How do I test an MCP server?
- Test it in code with the SDK's client. In Python, Client(mcp) connects to the server object in memory, so unit tests need no subprocess or port. For interactive checks, run the MCP Inspector, which lists tools, renders input forms from their schemas, and shows the JSON-RPC traffic. Its --cli mode lists and calls tools from a script and returns a nonzero exit code when a call fails.
Should an MCP server use stdio or Streamable HTTP?
- Use stdio when the server runs on the same machine as the host, such as a tool that reads local files or calls an API with the user's own key. Use Streamable HTTP when the server must be shared, deployed centrally, or reached by clients on other machines. HTTP servers must validate the Origin header and usually need OAuth-based authorization.
Do MCP servers need authentication?
- Remote servers that touch private data do. Authorization is optional in the MCP specification, but an HTTP server that implements it must behave as an OAuth 2.1 resource server: publish Protected Resource Metadata, return 401 for missing or invalid tokens, and accept only tokens issued for itself. Stdio servers should not use that flow and should read credentials from their environment instead.
Terms in this guide
Cite this guide
The AI Engineering Editors. "How to build an MCP server: a Python and TypeScript tutorial." The AI Engineering, updated Nov 11, 2026. https://theaiengineering.com/articles/how-to-build-an-mcp-server
- Title
- How to build an MCP server: a Python and TypeScript tutorial
- Author
- The AI Engineering Editors
- Publisher
- The AI Engineering
- Published
- Updated