MCP Server Example and Template for TypeScript and Python
A minimal MCP server example in TypeScript or Python is four files: a package manifest, one source file that registers tools and connects a stdio transport, and a README with the host config. The first section below is a complete, runnable two-tool server (add, count_words) tested on 2026-10-19.
After the example is the exact template MCP Server Generator produces, in TypeScript and Python, with what each part does and how to extend it.
Two more tested examples follow it: a server with a resource and a prompt, and the same tools over Streamable HTTP instead of stdio.
Both versions were run on 2026-10-17 (@modelcontextprotocol/sdk 1.32.1 on Node 20, mcp 2.3.0 on Python 3.13) using the exact host configs from their READMEs, and answered tools/list and tools/call correctly.
| TypeScript | Python | |
|---|---|---|
| SDK package | @modelcontextprotocol/sdk (+ Zod) | mcp (>=2.0) |
| Entry file | src/index.ts | server.py |
| Run command | node --import tsx src/index.ts | python server.py (or .venv/bin/python) |
Host config command | Absolute path to tsx or node | Absolute path to python / venv |
MCP server example (TypeScript and Python)
This MCP server example exposes two real tools, add and count_words, with no placeholders, so you can see a full request and response before you write your own. Both versions use the official SDKs and the stdio transport that Claude Desktop and Cursor launch.
MCP server example in TypeScript (Node.js)
src/index.ts
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: "example-server", version: "1.0.0" });
server.registerTool(
"add",
{
description: "Add two numbers and return the sum",
inputSchema: { a: z.number().describe("First number"), b: z.number().describe("Second number") },
},
async ({ a, b }) => ({
content: [{ type: "text", text: String(a + b) }],
})
);
server.registerTool(
"count_words",
{
description: "Count the words in a piece of text",
inputSchema: { text: z.string().describe("Text to count") },
},
async ({ text }) => {
const words = text.trim().split(/\s+/).filter(Boolean).length;
return { content: [{ type: "text", text: `${words} words` }] };
}
);
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("example-server running on stdio");
npm install @modelcontextprotocol/sdk@^1.32.1 zod@^3.25.76
npm install -D tsx typescript @types/node
node --import tsx src/index.ts
Use "type": "module" in package.json (the top-level await needs ES modules). inputSchema here is a plain object of Zod fields; the template further down passes a z.object(...). Both were run with SDK 1.32.1.
Simple MCP server example in Python
server.py
from typing import Annotated
from pydantic import Field
from mcp.server import MCPServer
mcp = MCPServer("example-server", version="1.0.0")
@mcp.tool()
def add(
a: Annotated[float, Field(description="First number")],
b: Annotated[float, Field(description="Second number")],
) -> str:
"""Add two numbers and return the sum"""
return str(a + b)
@mcp.tool()
def count_words(text: Annotated[str, Field(description="Text to count")]) -> str:
"""Count the words in a piece of text"""
return f"{len(text.split())} words"
if __name__ == "__main__":
mcp.run()
pip install "mcp>=2.0.0"
python server.py
Annotated[..., Field(description=...)] puts a description on each parameter in the input schema; plain type hints (a: float) work too, without descriptions. pydantic is installed with mcp.
What the example returns
Trimmed tools/list result from the TypeScript server:
{"tools":[
{"name":"add","description":"Add two numbers and return the sum",
"inputSchema":{"type":"object","properties":{
"a":{"type":"number","description":"First number"},
"b":{"type":"number","description":"Second number"}},
"required":["a","b"]}},
{"name":"count_words","description":"Count the words in a piece of text",
"inputSchema":{"type":"object","properties":{
"text":{"type":"string","description":"Text to count"}},
"required":["text"]}}
]}
tools/call add {"a":2,"b":3}returned5in TypeScript and5.0in Python (the Python parameters are floats).tools/call count_words {"text":"hello MCP server world"}returned4 wordsin both.- Calling
addwith a string foraand nobreturned a result withisError: trueand a validation message in both, so the model sees what went wrong.
Python only: outputSchema and structuredContent
The Python server's tools/list has one thing the TypeScript one above does not: each tool also gets an outputSchema, because MCPServer reads the -> str return annotation.
"outputSchema": {"type": "object",
"properties": {"result": {"type": "string", "title": "Result"}},
"required": ["result"], "title": "addOutput"}
Every result then carries "structuredContent": {"result": "5.0"} next to the usual text content. Hosts that only read text are unaffected. If you want plain text tools (for example, to make a Python and a TypeScript server answer tools/list identically in a test), write @mcp.tool(structured_output=False); with that change outputSchema and structuredContent both disappear. Checked on 2026-10-27 with mcp 2.3.0. The Python MCP server generator page shows the same behaviour for the generated get_weather tool, and the tool schema generator can draft an explicit outputSchema for either language.
Tested on 2026-10-19 over stdio JSON-RPC (initialize, tools/list, tools/call) with @modelcontextprotocol/sdk 1.32.1 and Zod 3.25.76 on Node 20.19.2 (via tsx and compiled with tsc), and mcp 2.3.0 on Python 3.13.5. To run the same checks yourself, see how to test an MCP server; to add it to a host, see connect an MCP server to Claude Desktop and Cursor.
Need an example for your own tools instead? Describe them in the MCP Server Generator form (or wrap a private REST API with the tested handlers in build an MCP server for an internal API), or, if you already have an OpenAPI or Swagger spec, generate a server with real HTTP calls in the OpenAPI to MCP converter. The step-by-step version of this is how to build an MCP server.
TypeScript template
weather-helper/
├── package.json
├── tsconfig.json # ES2022, NodeNext, strict, outDir dist
├── src/index.ts
└── README.md
src/index.ts
#!/usr/bin/env node
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: "weather-helper",
version: "1.0.0",
});
server.registerTool(
"get_weather",
{
description: "Get current weather for a city",
inputSchema: z.object({
city: z.string().describe("City name, e.g. San Francisco")
}),
},
async ({ city }) => {
// TODO: replace this placeholder with real logic for get_weather
const text = "[get_weather] " + "city=" + JSON.stringify(city);
return {
content: [{ type: "text", text }],
};
}
);
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("weather-helper MCP server running on stdio");
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
#!/usr/bin/env nodesurvivestsc, so the compileddist/index.jsworks as the package'sbinafternpm run build.McpServerholds the server name and version the host displays.registerTool(name, {description, inputSchema}, handler): the Zod object becomes the JSON Schema the model sees;.describe()text is passed to the model as the parameter description.- The handler returns
{ content: [{ type: "text", text }] }. Replace theTODOwith your logic. StdioServerTransporttalks JSON-RPC over stdin/stdout. That is why the startup message usesconsole.error: anything printed to stdout corrupts the protocol.
package.json (trimmed)
{
"name": "weather-helper",
"type": "module",
"bin": { "weather-helper": "./dist/index.js" },
"scripts": {
"start": "node --import tsx src/index.ts",
"build": "tsc -p tsconfig.json",
"start:dist": "node dist/index.js"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.32.1",
"zod": "^3.25.76"
},
"devDependencies": {
"@types/node": "^22.10.2",
"tsx": "^4.19.2",
"typescript": "^5.7.2"
},
"engines": { "node": ">=18" }
}
Python template
weather-helper/
├── server.py
├── requirements.txt # mcp>=2.0.0
├── pyproject.toml # requires-python >=3.10
└── README.md
server.py
"""Example MCP server with a weather lookup tool"""
from mcp.server import MCPServer
mcp = MCPServer("weather-helper", version="1.0.0")
@mcp.tool()
def get_weather(city: str) -> str:
"""Get current weather for a city
Args:
city: City name, e.g. San Francisco
"""
# TODO: replace this placeholder with real logic for get_weather
return "[get_weather] " + "city=" + repr(city)
if __name__ == "__main__":
mcp.run()
MCPServeris the high-level server inmcp2.x (it was calledFastMCPin 1.x). Passingversion="1.0.0"makes the host see a real version; without itserverInfo.versionis empty.@mcp.tool()turns a function into a tool. Type hints (str,float,bool) become the input schema, and the docstring becomes the description.mcp.run()defaults to stdio, which is what Claude Desktop and Cursor launch.
Add a tool with an optional parameter
This is the code the generator writes when you add a second tool and untick required on days. Paste it above main() / if __name__:
TypeScript
server.registerTool(
"get_forecast",
{
description: "Get a multi-day forecast for a city",
inputSchema: z.object({
city: z.string().describe("City name"),
days: z.number().describe("Number of days (1-7)").optional(),
}),
},
async ({ city, days }) => {
// TODO: call your forecast API here
const text = "[get_forecast] city=" + JSON.stringify(city) + ", days=" + JSON.stringify(days);
return { content: [{ type: "text", text }] };
}
);
Python
@mcp.tool()
def get_forecast(city: str, days: float = 0.0) -> str:
"""Get a multi-day forecast for a city
Args:
city: City name
days: Number of days (1-7)
"""
# TODO: call your forecast API here
return "[get_forecast] city=" + repr(city) + ", days=" + repr(days)
Optional parameters get .optional() in Zod and a default value in Python. Keep each tool task-shaped (one clear job, a verb in the name) rather than one tool per endpoint; models choose between a handful of well-described tools more reliably.
Run and test it
# TypeScript
npm install
npx @modelcontextprotocol/inspector npm start
# Python
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
npx @modelcontextprotocol/inspector .venv/bin/python server.py
The MCP Inspector launches your server the same way a host does and lets you list and call tools before you touch any host config. For CLI checks, failure-path tests and a CI smoke script, see how to test an MCP server. When it works there, connect the server to Claude Desktop or Cursor.
MCP server example with a resource and a prompt
Tools are only one of the three things an MCP server can offer. In the MCP specification, tools are called by the model, resources are read-only data identified by a URI that the host or user attaches as context, and prompts are message templates the user picks explicitly. This example adds one of each of the last two to a server: a style guide resource and a release-notes prompt with one required argument.
TypeScript: registerResource and registerPrompt
src/resources-prompts.ts
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: "example-server", version: "1.0.0" });
const STYLE_GUIDE = "# Release notes style\n- One line per change.\n- Start with a verb: Add, Fix, Remove.\n- Dates as YYYY-MM-DD.";
// A resource: read-only context the host or user can attach.
server.registerResource(
"style-guide",
"docs://style-guide",
{ title: "Release notes style guide", description: "House rules for release notes", mimeType: "text/markdown" },
async (uri) => ({
contents: [{ uri: uri.href, mimeType: "text/markdown", text: STYLE_GUIDE }],
})
);
// A prompt: a reusable message template the user picks from the host's menu.
server.registerPrompt(
"release-notes",
{
title: "Draft release notes",
description: "Turn a list of changes into release notes",
argsSchema: { changes: z.string().describe("One change per line") },
},
({ changes }) => ({
messages: [
{
role: "user",
content: { type: "text", text: `Write release notes for these changes.\n\n${STYLE_GUIDE}\n\nChanges:\n${changes}` },
},
],
})
);
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("example-server running on stdio");
registerResource(name, uri, metadata, read) returns contents with the URI it was asked for. registerPrompt takes an argsSchema of Zod string fields, which become the prompt's arguments; the callback returns the messages the host inserts into the conversation. Same package.json and install commands as the first example.
Python: @mcp.resource and @mcp.prompt
resources_prompts.py
from typing import Annotated
from pydantic import Field
from mcp.server import MCPServer
mcp = MCPServer("example-server", version="1.0.0")
STYLE_GUIDE = "# Release notes style\n- One line per change.\n- Start with a verb: Add, Fix, Remove.\n- Dates as YYYY-MM-DD."
@mcp.resource(
"docs://style-guide",
name="style-guide",
title="Release notes style guide",
description="House rules for release notes",
mime_type="text/markdown",
)
def style_guide() -> str:
return STYLE_GUIDE
@mcp.prompt(name="release-notes", title="Draft release notes")
def release_notes(changes: Annotated[str, Field(description="One change per line")]) -> str:
"""Turn a list of changes into release notes"""
return f"Write release notes for these changes.\n\n{STYLE_GUIDE}\n\nChanges:\n{changes}"
if __name__ == "__main__":
mcp.run()
A prompt function that returns a string becomes a single user message. Function parameters become prompt arguments, and the docstring becomes the prompt description.
What a client sees
initializeadvertisesresourcesandpromptscapabilities (the TypeScript server has notoolscapability because it registers no tools).resources/listreturns{"name":"style-guide","title":"Release notes style guide","uri":"docs://style-guide","description":"House rules for release notes","mimeType":"text/markdown"}from both servers, andresources/readreturns the Markdown text.prompts/listreturnsrelease-noteswith one argument,{"name":"changes","description":"One change per line","required":true}.prompts/getwithchangesreturns oneusermessage containing the style guide and the changes. Withoutchanges, both servers answer with an error instead of a half-filled prompt.
Hosts surface these differently. In Claude Code, MCP prompts appear as slash commands named after the server and prompt (here /mcp__example-server__release-notes). Some hosts only use tools, so check your host before you move logic out of a tool. The MCP Inspector has Resources and Prompts tabs to try both; see how to test an MCP server.
MCP server example over Streamable HTTP
The examples above use stdio: the host starts the server as a child process. A Streamable HTTP server runs on its own and hosts connect to a URL such as http://127.0.0.1:3000/mcp. Use it when one running server should serve several clients, or when the host only accepts remote URLs. These versions are stateless: every request gets a fresh server, so there are no session IDs to track. To skip the hand edits, the remote MCP server generator writes this setup from a form, with a Dockerfile and a Host allowlist.
TypeScript: StreamableHTTPServerTransport with Express
src/http.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js";
import type { Request, Response } from "express";
import { z } from "zod";
function buildServer() {
const server = new McpServer({ name: "example-server", version: "1.0.0" });
server.registerTool(
"add",
{
description: "Add two numbers and return the sum",
inputSchema: { a: z.number().describe("First number"), b: z.number().describe("Second number") },
},
async ({ a, b }) => ({ content: [{ type: "text", text: String(a + b) }] })
);
return server;
}
// Binds to 127.0.0.1 and rejects foreign Host headers (DNS rebinding protection).
const app = createMcpExpressApp();
// Stateless: a fresh server and transport for every POST, no session IDs.
app.post("/mcp", async (req: Request, res: Response) => {
const server = buildServer();
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
res.on("close", () => {
transport.close();
server.close();
});
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
});
app.listen(3000, "127.0.0.1", () => {
console.error("example-server on http://127.0.0.1:3000/mcp");
});
npm install @modelcontextprotocol/sdk@^1.32.1 zod@^3.25.76 express@^5
npm install -D tsx typescript @types/node @types/express
node --import tsx src/http.ts
createMcpExpressApp() from the SDK adds the JSON body parser and, because it binds to 127.0.0.1, rejects requests whose Host header is not a localhost name (DNS rebinding protection). Express is a dependency of the SDK, but install it yourself because your code imports it.
Python: mcp.run(transport="streamable-http")
http_server.py
from typing import Annotated
from pydantic import Field
from mcp.server import MCPServer
mcp = MCPServer("example-server", version="1.0.0")
@mcp.tool()
def add(
a: Annotated[float, Field(description="First number")],
b: Annotated[float, Field(description="Second number")],
) -> str:
"""Add two numbers and return the sum"""
return str(a + b)
if __name__ == "__main__":
# Serves http://127.0.0.1:8000/mcp
mcp.run(transport="streamable-http", stateless_http=True)
The add tool is the same as in the stdio example; only the last line changes. The server listens on 127.0.0.1:8000 at /mcp and also checks the Host header.
Connect a host to the HTTP server
// Cursor: ~/.cursor/mcp.json
{ "mcpServers": { "example-server": { "url": "http://127.0.0.1:3000/mcp" } } }
// VS Code: .vscode/mcp.json
{ "servers": { "example-server": { "type": "http", "url": "http://127.0.0.1:3000/mcp" } } }
# Claude Code
claude mcp add --transport http example-server http://127.0.0.1:3000/mcp
# Codex: ~/.codex/config.toml
[mcp_servers.example-server]
url = "http://127.0.0.1:3000/mcp"
Use port 8000 for the Python server. Claude Desktop's config file only launches local commands, so add a URL there through Settings > Connectors or the mcp-remote bridge; the MCP config generator writes any of these entries for you, and the connect guide lists the file locations. These examples have no authentication, so keep them on localhost. To share one server with a team behind a token, see Streamable HTTP with a shared token.
Tested on 2026-10-23 with @modelcontextprotocol/sdk 1.32.1 (Express 5.3.0) on Node 20.19.2, run through tsx and compiled with tsc, and mcp 2.3.0 on Python 3.13.5. The official TypeScript SDK client connected to each server, listed tools and called add(2, 3) (result 5, and 5.0 in Python); a request with a foreign Host header got HTTP 403 from the TypeScript server and 421 from the Python server. The resource and prompt servers above were checked with the same client over stdio.
What the template does not include
- Real handler logic: tools echo their arguments until you replace the
TODOs - Resources, prompts, auth, or an HTTP transport (add resources and prompts and Streamable HTTP by hand as shown above)
- Parameter types beyond string, number and boolean (edit the Zod schema or type hints for arrays, enums or objects)
Generate this template with your own tools
Name your tools and parameters in the form; the ZIP has the same structure as above. No OpenAPI needed.
FAQ
Is this an official MCP server template?
No. It is generated by MCP Server Generator, but it uses the official SDKs: @modelcontextprotocol/sdk for TypeScript and the mcp package for Python.
Why does the Python template use MCPServer instead of FastMCP?
In version 2 of the mcp Python package, FastMCP was renamed to MCPServer and is imported from mcp.server. The template pins mcp>=2.0.0, so it uses the new name. On mcp 1.x you would write from mcp.server.fastmcp import FastMCP instead.
Do I need to compile the TypeScript template?
No. npm start runs src/index.ts directly through tsx. npm run build compiles to dist/ with tsc if you prefer plain Node in production.
Can the template run as a remote HTTP server?
Not as generated. It uses the stdio transport, which is what Claude Desktop and Cursor launch locally. To serve it over Streamable HTTP, replace the transport code as in the HTTP example on this page: StreamableHTTPServerTransport with Express in TypeScript, or mcp.run(transport="streamable-http") in Python. Both were tested with the official SDK client.
How do I get the template with my own tool names?
Fill in the form on the MCP Server Generator homepage and download the ZIP. Tool names, descriptions and typed parameters are written into the code for you.
What is a simple MCP server example in Python?
The Python example on this page is a complete one: MCPServer("example-server") from mcp 2.x, two functions decorated with @mcp.tool() (add and count_words), and mcp.run() for stdio. Install it with pip install "mcp>=2.0.0" and run python server.py. On mcp 1.x, import FastMCP from mcp.server.fastmcp instead.
Is there an MCP server example in TypeScript or Node.js?
Yes. The TypeScript example uses McpServer and StdioServerTransport from @modelcontextprotocol/sdk with Zod input schemas, registers add and count_words, and runs on Node with tsx or after compiling with tsc. It was tested with SDK 1.32.1 on Node 20.
Where can I find more MCP server examples on GitHub?
The official modelcontextprotocol/servers repository holds the reference servers maintained by the MCP steering group, such as Everything, Fetch, Filesystem, Git, Memory, Sequential Thinking and Time. Published third-party servers are listed in the MCP Registry. The template on this page is also on GitHub at wuzzheng/mcp-server-template.
Is there a weather MCP server example?
The template on this page is a weather-helper server with a get_weather(city) tool whose handler is a placeholder: replace the TODO with a call to the weather API you use. The official MCP documentation's build a server tutorial also builds a weather server and connects it to Claude for Desktop.
What is the difference between MCP tools, resources and prompts?
Tools are functions the model decides to call, with a JSON Schema for their input. Resources are read-only data identified by a URI that the host or user attaches as context. Prompts are message templates with arguments that the user picks explicitly. A server can offer any mix of the three; the resource and prompt example shows the last two.
How do I add a resource or a prompt to an MCP server?
In TypeScript, call server.registerResource(name, uri, metadata, readCallback) and server.registerPrompt(name, { description, argsSchema }, callback) on the McpServer. In Python, decorate functions with @mcp.resource("docs://style-guide") and @mcp.prompt(). The server then advertises the resources and prompts capabilities automatically.