How to build an MCP server

Expose tools, resources, and prompts to any AI host by building an MCP server in Python or TypeScript — over stdio for local use, or Streamable HTTP for remote.

, updated

An MCP server is the standard way to expose tools, data, and prompts to any AI host — Claude Code, Claude Desktop, Cursor, VS Code, or your own agent. You write the server once, and every MCP-aware host can call it. You don’t need an SDK for each editor, and the host’s model sees your tools like any built-in capability.

How that call flows from the model down to your code:

┌──────────────────────────── MCP Host (Claude Code, IDE, app) ────────────────────────────┐
│                                                                                          │
│    user  ⇄  LLM  ⇄  MCP client                                                           │
│                       │                                                                  │
└───────────────────────┼──────────────────────────────────────────────────────────────────┘
                        │  JSON-RPC over stdio or Streamable HTTP
              ┌─────────▼──────────┐
              │   your MCP server  │   ← the code in this guide
              └────────────────────┘

For the full protocol view (transports, lifecycle, reverse calls), see MCP Flow Architecture.

The three things a server exposes

You declare The host does with it Who triggers it
Tools — functions the model can call Lists them in the model’s context; runs them on request The model
Resources — files, records, or API results addressable by URI (notes://today) Lets the app or user browse and attach them The app / user
Prompts — reusable, parameterized prompt templates Shows them in a slash-menu for the user The user

Decorators in the SDKs map straight onto these: @mcp.tool(), @mcp.resource(...), @mcp.prompt() in Python, and registerTool / registerResource / registerPrompt in TypeScript.

Option 1: Python (official SDK)

Requires Python 3.11+. Install the official MCP package:

pip install "mcp[cli]"

The [cli] extra adds the mcp command used for dev tooling below.

Write the server

Create server.py. Type hints become the JSON Schema the host shows the model, and docstrings become tool descriptions:

from mcp.server import MCPServer

mcp = MCPServer("demo-tools")


@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b


@mcp.tool()
def list_files(path: str = ".") -> list[str]:
    """List the files in a directory."""
    from pathlib import Path
    return sorted(p.name for p in Path(path).iterdir())


@mcp.resource("notes://{name}")
def note(name: str) -> str:
    """Return a note by name."""
    return f"Contents of the '{name}' note..."


@mcp.prompt()
def review(code: str) -> str:
    """Ask the host model to review a code snippet."""
    return f"Review this code for bugs and security issues:\n\n{code}"


if __name__ == "__main__":
    mcp.run()  # stdio transport by default

Test it with the MCP Inspector

mcp dev server.py

This launches your server as a subprocess (the same way a real host does) and opens the MCP Inspector in your browser. Go to Tools, and you’ll find add rendered as a form with two required integer fields — built automatically from your type hints. Call it with a=1, b=2 and you get 3 back. Resources and Prompts tabs exercise the other two primitives.

Connect it to a host

# registers it with Claude Desktop for you
mcp install server.py --name "Demo Tools" --env DEBUG=some-value

Or edit the config file directly (see the connection guide):

{
  "mcpServers": {
    "demo-tools": {
      "command": "python",
      "args": ["/absolute/path/to/server.py"],
      "env": {}
    }
  }
}

Other hosts (Claude Code, Cursor, VS Code) take the same command + args launch line in their own config files or CLIs.

Serve it remotely

For anything you deploy — multiple users, web apps, servers behind your API — swap the transport:

if __name__ == "__main__":
    mcp.run(transport="streamable-http", port=3001)

That’s it — the SDK stands up a Starlette app and your MCP endpoint lives at http://127.0.0.1:3001/mcp. For a hosted deployment, front it with real authentication (the spec’s authorization layer is OAuth 2.1) and TLS from your proxy.

Option 2: TypeScript (official SDK)

Requires a current LTS Node.js:

npm install @modelcontextprotocol/sdk zod

Write the server

Create src/index.ts and add "type": "module" to package.json. Field schemas are declared with Zod; the SDK turns them into JSON Schema for the host:

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({ name: "demo-tools", version: "1.0.0" });

server.registerTool(
  "add",
  {
    title: "Add Numbers",
    description: "Add two numbers together.",
    inputSchema: { a: z.number(), b: z.number() },
  },
  async ({ a, b }) => ({
    content: [{ type: "text", text: String(a + b) }],
  }),
);

server.registerTool(
  "list_files",
  {
    title: "List Files",
    description: "List the files in a directory.",
    inputSchema: { path: z.string().default(".") },
  },
  async ({ path }) => {
    const fs = await import("node:fs/promises");
    const entries = await fs.readdir(path);
    return { content: [{ type: "text", text: entries.join("\n") }] };
  },
);

const transport = new StdioServerTransport();
await server.connect(transport);

For a remote server, switch to StreamableHTTPServerTransport from @modelcontextprotocol/sdk/server/streamableHttp.js and mount the handler in an HTTP app — the SDK server docs show stateless and stateful patterns.

Test and connect

Run the Inspector without any host install:

npx @modelcontextprotocol/inspector node dist/index.js

Or point a host at your build output the same way hosts run published servers:

{
  "mcpServers": {
    "demo-tools": {
      "command": "node",
      "args": ["/absolute/path/to/dist/index.js"]
    }
  }
}

Design tips

  • Descriptions are the model’s documentation. The model picks a tool based on its name and description — be specific (“Fetch the current weather radar for a US city”, not “get data”).
  • Few, focused tools beat many overlapping ones. Three tools the model can tell apart beat ten it has to guess between.
  • Return readable errors as results. Wrap expected failures in a result with isError: true (TypeScript) or raise-and-describe (Python SDK turns exceptions into tool results) so the model can read the message and retry on its own.
  • Never write to stdout on stdio. Stdout is the protocol wire — log to stderr or a file instead. The Python SDK already diverts plain print() to stderr while serving.
  • Use absolute paths and pass config via env. The host spawns your process with its own cwd and environment; nothing from your shell is inherited unless the config entry lists it.
  • Model-controlled tools, user-controlled prompts. Ask for anything risky through a prompt or an elicitation instead of letting the model fire it silently.

Further reading