---
title: "How to build an MCP server: a Python and TypeScript tutorial"
description: "Learn how to build an MCP server with the official Python and TypeScript SDKs: tools, resources, transports, testing, client config, and production security."
summary: "This tutorial builds a working MCP server on the official Python SDK v2 that wraps a public API with typed tools and a resource, then shows the TypeScript version. It covers stdio and Streamable HTTP, testing with an in-memory client and the MCP Inspector, host config, and remote server security."
type: "guide"
canonical_url: "https://theaiengineering.com/articles/how-to-build-an-mcp-server"
markdown_url: "https://theaiengineering.com/articles/how-to-build-an-mcp-server.md"
topic: "Model Context Protocol"
author: "The AI Engineering Editors"
publisher: "The AI Engineering"
published: "2026-11-06"
updated: "2026-11-11"
keywords: ["how to build an mcp server","mcp server tutorial","build mcp server python","mcp server python sdk","mcp server python fastmcp","how to build an mcp server in typescript","how to build an mcp server for an api","build mcp server from scratch"]
citation: "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"
---

# How to build an MCP server: a Python and TypeScript tutorial

## TL;DR

- An MCP server exposes tools (called by the model), resources (attached by the host application), and prompts (chosen by the user) to any MCP-compatible host over JSON-RPC 2.0.
- The official Python SDK, the mcp package, reached version 2 on July 28, 2026; its high-level class, called FastMCP in v1, is now MCPServer, and it builds each tool's JSON Schema from type hints.
- The official TypeScript SDK v2 ships as @modelcontextprotocol/server and @modelcontextprotocol/client and declares tool inputs with Zod v4 or another Standard Schema library.
- Use stdio for a server that runs on the user's machine and Streamable HTTP for a remote one; under the 2026-07-28 specification both are stateless, with no initialize handshake.
- A remote MCP server that uses authorization acts as an OAuth 2.1 resource server: it publishes Protected Resource Metadata, accepts only tokens issued for itself, and validates, rate limits, and logs tool calls.

An [MCP server](https://theaiengineering.com/glossary/mcp-server) is a program that exposes tools, resources, and prompts to AI applications through the [Model Context Protocol](https://theaiengineering.com/glossary/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](https://theaiengineering.com/articles/what-is-model-context-protocol).

## 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](https://theaiengineering.com/glossary/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](https://theaiengineering.com/glossary/mcp-transport) when the server is deployed for many users: each [JSON-RPC](https://theaiengineering.com/glossary/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](https://modelcontextprotocol.io/specification/2026-07-28/basic/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.

**Figure 1: One server, two transports. The code is identical; the launch, credentials, and trust boundary differ.**

The same server file runs two ways: a local host launches it over stdio with an API key from its environment, and a remote client reaches it over Streamable HTTP with an OAuth token.

Components:

- **Local host**: Desktop app or IDE
- **Authorization server**: Issues audience-bound tokens
- **Remote client**: Agent on another machine
- **server.py over stdio**: Child process of the host API key from env
- **server.py over HTTP**: POST /mcp, one endpoint Verifies bearer tokens
- **Upstream API**: PyPI JSON API in this guide

Groups:

- User's machine: Local host, server.py over stdio
- Network: Authorization server, Remote client, server.py over HTTP

Connections:

- Local host → server.py over stdio: stdin / stdout
- Remote client → server.py over HTTP: POST over HTTPS
- Remote client → Authorization server: OAuth
- server.py over stdio → Upstream API
- server.py over HTTP → Upstream API

## 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](https://py.sdk.modelcontextprotocol.io/whats-new/), 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](https://theaiengineering.com/platforms/mcp-platforms) 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.

```python
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 HTTP
```

Each 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](https://theaiengineering.com/glossary/json-schema) property with a `pattern` and a `description`. The SDK validates arguments before the function runs, so a name such as `../admin` never 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 `outputSchema` and fills `structuredContent` next to a JSON text copy in `content`; a list is wrapped as `{"result": [...]}`. This is server data for the host, unrelated to structured outputs from a model.
- **Errors.** `ToolError` returns a result with `isError: true` and your message, which the model can act on. Returning an error string instead would look like success. Any other exception also returns `isError: true`, but with a generic message, while the traceback stays in the server log.
- **Annotations.** `read_only_hint` and `open_world_hint` help hosts decide whether to [ask the user before a call](https://theaiengineering.com/glossary/human-in-the-loop). They are hints, not enforcement, and the specification tells clients to treat them as untrusted unless the server is trusted.
- **Resource.** `pypi://{name}/readme` is a template the host reads with `resources/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.

```typescript
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](https://github.com/modelcontextprotocol/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.

```python
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](https://modelcontextprotocol.io/docs/tools/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`.

```json
{
  "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](https://theaiengineering.com/platforms/ai-coding-tools) lists more hosts, and our guide to [AI coding agents](https://theaiengineering.com/articles/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](https://modelcontextprotocol.io/specification/2026-07-28/server/tools) 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](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization): 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.

**Figure 2: An authorized tools/call over Streamable HTTP, from the first 401 to the tool result.**

A client calls a protected MCP server without a token, gets a 401, obtains an audience-bound token from the authorization server, and retries; the server checks it before calling PyPI.

Steps:

1. MCP client → MCP server: POST /mcp, no token
2. MCP server → MCP client: 401 + resource_metadata
3. MCP client → Auth server: authorize: PKCE + resource
4. Auth server → MCP client: token for this server
5. MCP client → MCP server: tools/call + Bearer token
6. MCP server → MCP server: check audience, scopes, input
7. MCP server → MCP server: call PyPI, own credential
8. MCP server → MCP client: content + structuredContent

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](https://invariantlabs.ai/blog/mcp-security-notification) 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](https://theaiengineering.com/glossary/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](https://theaiengineering.com/glossary/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 `Origin` to block DNS rebinding; our server returned 403 for a foreign origin. The Python SDK accepts only localhost `Host` headers until you pass `transport_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 `isError` for every call, to stderr on stdio. MCP-level logging such as `ctx.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](https://theaiengineering.com/glossary/ai-gateway) or [MCP gateway](https://theaiengineering.com/glossary/mcp-gateway), such as Bifrost, get central authentication, tool allowlists, and audit logs; [what an AI gateway is](https://theaiengineering.com/articles/what-is-an-ai-gateway) 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](https://theaiengineering.com/articles/tool-calling) 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 `--strict` schema 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](https://theaiengineering.com/articles/how-to-build-an-ai-agent) covers the loop on the other side, and [A2A vs MCP](https://theaiengineering.com/articles/a2a-vs-mcp) explains when agents should talk to each other instead of to tools. The [MCP topic hub](https://theaiengineering.com/topics/mcp) 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

- [MCP server](https://theaiengineering.com/glossary/mcp-server): An MCP server is a program that exposes tools, resources, and prompts to AI applications through the Model Context Protocol, running locally over stdio or remotely over Streamable HTTP.
- [Model Context Protocol (MCP)](https://theaiengineering.com/glossary/model-context-protocol): Model Context Protocol (MCP) is an open protocol, introduced by Anthropic in November 2024, that standardizes how AI applications connect to external tools, data sources, and prompts through MCP servers.
- [Tool calling](https://theaiengineering.com/glossary/tool-calling): Tool calling is an LLM capability in which the model, given a list of tool definitions, outputs a structured request naming a tool and its arguments, which the application executes and returns.
- [Structured outputs](https://theaiengineering.com/glossary/structured-outputs): Structured outputs is an LLM API feature that constrains generation so the model's response always conforms to a developer-supplied JSON Schema, producing output that code can parse without retries.
- [Prompt injection](https://theaiengineering.com/glossary/prompt-injection): Prompt injection is an attack in which text supplied to a large language model, typed by a user or hidden in content the model reads, alters the application's intended behavior or output.
- [Guardrails](https://theaiengineering.com/glossary/guardrails): Guardrails are programmatic checks placed around a large language model that validate, filter, or block inputs, outputs, and tool calls so an AI application stays within its safety, security, and policy limits.
- [LLM observability](https://theaiengineering.com/glossary/llm-observability): LLM observability is the practice of instrumenting LLM applications to record each request's prompts, responses, tool calls, token usage, latency, cost, and quality scores as traces that teams can search and analyze.
- [AI gateway](https://theaiengineering.com/glossary/ai-gateway): An AI gateway is a proxy layer between applications and model providers that exposes one API for many models and centralizes routing, failover, access control, cost tracking, caching, and logging.
- [MCP transport](https://theaiengineering.com/glossary/mcp-transport): An MCP transport is the binding that carries Model Context Protocol messages between a client and a server; the specification defines stdio for local subprocesses and Streamable HTTP for remote servers.
- [JSON-RPC](https://theaiengineering.com/glossary/json-rpc): JSON-RPC is a lightweight, transport-agnostic remote procedure call protocol that encodes method calls, results, and errors as JSON objects; version 2.0 is the message format of MCP and A2A.
- [JSON Schema](https://theaiengineering.com/glossary/json-schema): JSON Schema is a declarative vocabulary, itself written in JSON, for describing the structure of JSON data; LLM APIs and MCP use it to define tool arguments and constrain model output.
- [Human-in-the-loop](https://theaiengineering.com/glossary/human-in-the-loop): Human-in-the-loop (HITL) is an agent design in which the run pauses at defined checkpoints, such as before a sensitive tool call, so a person can approve, edit, or reject the action.
- [Rate limiting](https://theaiengineering.com/glossary/rate-limiting): Rate limiting is the enforcement of a maximum number of requests or tokens a client may send to an API within a time window, with excess requests rejected, usually with HTTP 429.
- [Tool poisoning](https://theaiengineering.com/glossary/tool-poisoning): Tool poisoning is an attack in which a malicious or compromised MCP server hides instructions in a tool's description or schema, which the model reads as trusted context and may follow.
- [MCP gateway](https://theaiengineering.com/glossary/mcp-gateway): An MCP gateway is a proxy that sits between MCP hosts and many MCP servers, exposing them through one endpoint and centralizing authentication, tool access policy, and audit logging.

## Related guides

- [What is the Model Context Protocol (MCP)? How it works](https://theaiengineering.com/articles/what-is-model-context-protocol): The Model Context Protocol (MCP) is an open standard for connecting AI apps to tools and data. Learn its architecture, transports, tool calls, and security.
- [A2A protocol vs MCP: differences and when to use each](https://theaiengineering.com/articles/a2a-vs-mcp): A2A protocol vs MCP: A2A connects AI agents to other agents, and MCP connects an agent to tools and data. Compare agent cards, tasks, transports, and security.
- [What is tool calling? How LLM function calling works](https://theaiengineering.com/articles/tool-calling): Tool calling lets an LLM request actions from your code through structured calls. Learn the request loop, parallel calls, structured outputs, security, and MCP.
- [How to build an AI agent: a step-by-step guide in Python](https://theaiengineering.com/articles/how-to-build-an-ai-agent): Learn how to build an AI agent from scratch in Python: when you need one, tool schemas, the agent loop, stop conditions, guardrails, evals, and tracing.

Part of the [Model Context Protocol](https://theaiengineering.com/topics/mcp) topic hub.

## 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: 2026-11-06
- Updated: 2026-11-11
- URL: https://theaiengineering.com/articles/how-to-build-an-mcp-server
- Markdown: https://theaiengineering.com/articles/how-to-build-an-mcp-server.md

To cite one section, link to its anchor:

- [What does an MCP server expose?](https://theaiengineering.com/articles/how-to-build-an-mcp-server#what-does-an-mcp-server-expose)
- [Choose a transport: stdio or Streamable HTTP](https://theaiengineering.com/articles/how-to-build-an-mcp-server#choose-a-transport-stdio-or-streamable-http)
- [Set up the Python SDK](https://theaiengineering.com/articles/how-to-build-an-mcp-server#set-up-the-python-sdk)
- [Build the server: tools, schemas, and a resource](https://theaiengineering.com/articles/how-to-build-an-mcp-server#build-the-server-tools-schemas-and-a-resource)
- [The same server in TypeScript](https://theaiengineering.com/articles/how-to-build-an-mcp-server#the-same-server-in-typescript)
- [Test your MCP server](https://theaiengineering.com/articles/how-to-build-an-mcp-server#test-your-mcp-server)
- [Connect it to a client](https://theaiengineering.com/articles/how-to-build-an-mcp-server#connect-it-to-a-client)
- [Production concerns for remote MCP servers](https://theaiengineering.com/articles/how-to-build-an-mcp-server#production-concerns-for-remote-mcp-servers)
- [MCP tool design checklist](https://theaiengineering.com/articles/how-to-build-an-mcp-server#mcp-tool-design-checklist)
- [Where to go next](https://theaiengineering.com/articles/how-to-build-an-mcp-server#where-to-go-next)
- [Frequently asked questions](https://theaiengineering.com/articles/how-to-build-an-mcp-server#faq)
