Build Your Own MCP Server and Connect It to Claude
- An MCP server is a program that exposes tools (functions) that Claude can call. With the official Python SDK (
mcp), you build one just by adding@mcp.tool()to a function. - For use only on your own computer, run it over stdio; for use by several people or in the Claude app, run it over Streamable HTTP (a public HTTPS address).
- Connect it to Claude Code with
claude mcp add, and to the Claude app as a custom connector (a remote server URL). A local stdio server can’t be used in the Claude app chat (claude.ai). - The text a server returns is input the model reads. The basics are read-only tools first, input validation, secrets in environment variables, and never expose it publicly without authentication.
- The examples follow the official documentation, and we verified the syntax on 2026-10-11. We also confirmed the server’s behavior by calling it directly on our own machine.
What you’ll be able to do after this tutorial
Section titled “What you’ll be able to do after this tutorial”- Build an MCP server with two inventory lookup tools using the official SDK, and test calling them.
- Attach the same server to Claude Code with
claude mcp addand check its status with/mcp. - Know the steps and requirements for connecting a server you run over HTTP as a custom connector in the Claude app.
- Apply the security principles to follow when building an MCP server (least privilege, prompt injection, secrets).
Concepts to know first
Section titled “Concepts to know first”| Term | Meaning |
|---|---|
| MCP | Model Context Protocol. An open standard that connects AI apps to external tools and data. For an easy introduction, see 20. Connectors (MCP). |
| MCP server | A program that exposes tools, resources, and prompts. This tutorial covers only tools. |
| Host and client | An AI app such as Claude Code or the Claude app is the host, and the client inside it connects to a server one-to-one. |
| stdio | A way for the host to run the server as a child process on its own computer and talk to it over standard input and output. |
| Streamable HTTP | A way where the server is up at a URL (default path /mcp) and several clients connect to it. It’s the approach used for remote servers. |
| Custom connector | A feature in the Claude app where you enter a remote MCP server’s URL to connect it. We covered the concept in C7. |
Where can you connect it?
Section titled “Where can you connect it?”| Connect to | Server type | Where the server lives |
|---|---|---|
| Claude Code (terminal) | stdio or HTTP | Your computer or remote |
Claude Desktop local config (claude_desktop_config.json) |
stdio | Your computer (not used in Cowork or claude.ai) |
| Claude app custom connector (claude.ai, Desktop, Cowork) | HTTP | The public internet, reachable from Anthropic’s cloud |
Step by step
Section titled “Step by step”-
Working folder and installing the SDK
You need Python 3.11 or later (per the official SDK docs and README, as of 2026-10-19). Create a virtual environment and install the official SDK. The
cliextra also installs themcp devcommand for development.Terminal window mkdir inventory-mcp && cd inventory-mcppython3 -m venv .venvsource .venv/bin/activatepip install "mcp[cli]"If you use
uv,uv add "mcp[cli]"gives the same result. -
Build the server: two read-only tools
Create
server.py. It’s an inventory lookup server. In real life it would read a database or an internal API, but the example uses fake data in memory."""Inventory lookup MCP server (a read-only example)."""import sysfrom mcp.server import MCPServerfrom mcp.server.mcpserver.exceptions import ToolErrorfrom mcp.types import ToolAnnotationsmcp = MCPServer("inventory")# In real life this would read a database or an internal API, but the example uses in-memory data.STOCK = {"KB-100": {"name": "Wireless keyboard", "qty": 42, "location": "A-1"},"MS-200": {"name": "Wireless mouse", "qty": 0, "location": "A-2"},"MN-300": {"name": "27-inch monitor", "qty": 7, "location": "B-1"},}@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))def get_stock(sku: str) -> str:"""Look up the stock quantity and storage location by SKU code (e.g. KB-100)."""print(f"get_stock called: {sku!r}", file=sys.stderr) # Logs go to stderritem = STOCK.get(sku.strip().upper())if item is None:raise ToolError(f"Unknown SKU: {sku}")return f"{item['name']}: {item['qty']} units (location {item['location']})"@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))def search_items(keyword: str, max_results: int = 5) -> list[dict]:"""Find items whose product name contains the keyword, and return their SKU and quantity."""max_results = max(1, min(max_results, 20)) # Enforce the cap in codehits = [{"sku": sku, "name": v["name"], "qty": v["qty"]}for sku, v in STOCK.items()if keyword.lower() in v["name"].lower()]return hits[:max_results]if __name__ == "__main__":mcp.run() # The default is stdioHere’s what to notice in the code.
- Type hints are the schema.
sku: strandmax_results: int = 5produce the JSON schema, and the SDK also validates input for you. The docstring is the tool description the model sees. The more specific you make the description, the better Claude calls it. readOnlyHint=Trueis only a hint. It tells the client “this tool only reads,” but the MCP spec says not to trust annotations like this unless the server is trusted. You have to keep things safe in code.- Raise expected failures as
ToolError. The message in aToolErroris passed to the model as is, so Claude can retry with a different SKU. For a regular exception (ValueErrorand the like), the model gets only “Error executing tool …” and the original text stays in the server log only. We ran it ourselves to confirm the difference between the two. - Write logs to stderr. In a stdio server, standard output (stdout) is the protocol channel. If you
print()to stdout, communication breaks.
Check the syntax.
Terminal window python3 -m py_compile server.py && echo Syntax OK - Type hints are the schema.
-
Call it directly before connecting
If you check the server by itself before attaching it to Claude, you can separate problems. Create
test_server.pyusing the SDK’s in-memory client.import asynciofrom mcp import Clientfrom server import mcpasync def main() -> None:async with Client(mcp) as client:tools = await client.list_tools()print([t.name for t in tools.tools])ok = await client.call_tool("get_stock", {"sku": "kb-100"})print(ok.content[0].text)found = await client.call_tool("search_items", {"keyword": "wireless"})print(found.structured_content)bad = await client.call_tool("get_stock", {"sku": "zz"})print(bad.is_error, bad.content[0].text)asyncio.run(main())Terminal window python test_server.pyIf you see the tool list,
Wireless keyboard: 42 units (location A-1), the search results, and on the last lineTrue Error executing tool get_stock: Unknown SKU: zz, it’s working. If you’d like to click through the tools on a browser screen, you can open the MCP Inspector withmcp dev server.py(per the official README). -
Connect to Claude Code (stdio)
In
claude mcp add, what comes before--is Claude Code’s options, and what comes after is the command that runs the server. Write the server’s run path as an absolute path.Terminal window claude mcp add inventory -- "$PWD/.venv/bin/python" "$PWD/server.py"claude mcp listIf you see
inventory: … - Connected, it worked. Open a session and check the status with/mcp, or just ask.Copy and paste this promptUsing the inventory server, tell me the stock for KB-100, and pick out the products with “wireless” in the name that have a stock of 0.
Claude asks for approval before it calls a tool. Server tools are referenced in permission rules and hooks in the form
mcp__servername__toolname, such asmcp__inventory__get_stock.Screen guide: The /mcp screen showing the inventory server as ConnectedView in the Claude Code docs ↗
Choose a scope like this. There’s a detailed explanation in C14.
Scope Option Stored in Used for local (default) --scope local~/.claude.jsonJust you, in this project project --scope projectThe project’s .mcp.jsonSharing with your team through git user --scope user~/.claude.jsonAll your projects For a server that needs secrets, pass them with
--env KEY=valueor use${VAR}environment variable expansion in.mcp.json. Don’t write the value itself in a file and commit it.{"mcpServers": {"inventory": {"type": "stdio","command": "${CLAUDE_PROJECT_DIR:-.}/.venv/bin/python","args": ["${CLAUDE_PROJECT_DIR:-.}/server.py"],"env": { "INVENTORY_API_TOKEN": "${INVENTORY_API_TOKEN}" }}}} -
Run it over HTTP (for remote servers and the Claude app)
Run the same server in the mode where you connect to it by URL. Create one more file.
from server import mcpmcp.run(transport="streamable-http", host="127.0.0.1", port=8000)Save it as
serve_http.pyand runpython serve_http.py, and you can connect athttp://127.0.0.1:8000/mcp. We ran it ourselves and checked it with Claude Code.Terminal window claude mcp add --transport http inventory-http http://127.0.0.1:8000/mcpclaude mcp listYou want to see
Connected. If you turn off the server, it changes toFailed to connect. -
Connect to the Claude app as a custom connector
A custom connector in the Claude app reaches your server from Anthropic’s cloud, not from your device. So there are requirements.
- The server must be reachable over HTTPS from the public internet. A server on
127.0.0.1, an internal network, or behind a VPN won’t work. - To keep a private server behind a firewall, you have to allow Anthropic’s IP ranges (the list of ranges is at platform.claude.com/docs/en/api/ip-addresses).
- Write the server address including the MCP path, like
https://your-domain/mcp.
Once the requirements are met, here’s what to do on a Pro/Max personal account (per the support center docs of 2026-10-11; the on-screen wording may change).
- In Customize > Connectors, click + Add > Add custom connector
- Enter a name and the server URL, then click Continue
- Check the authentication settings. Choose from Sign in now, Sign in when needed, and No sign in. You can also use OAuth or request headers (fixed credentials).
- Click Add, then turn it on from + > Connectors in the chat window.
On Team/Enterprise, an Owner (or Primary Owner) adds it under Organization settings > Connectors with Add > Custom > Web, and members click Connect in Customize > Connectors. To edit one, you remove it and add it again. The Free plan allows up to 1 custom connector.
Screen guide: The Add custom connector dialog (name, server URL, choosing authentication)View in the Anthropic Help Center ↗
Adding a custom connector in the Claude app (Pro/Max) - Customize > ConnectorsClick + Add and choose Add custom connector
- Add dialogEnter a name and the server URL (https://your-domain/mcp), then click Continue
- Authentication settingsChoose from Sign in now / Sign in when needed / No sign in
- Add dialogClick Add→ You can turn it on from + > Connectors in the chat window
This is a simplified flow. See the official help page for the actual screens.
- The server must be reachable over HTTPS from the public internet. A server on
-
If you build the same server in TypeScript (for reference)
With the TypeScript SDK v2 it looks like this. You need Node.js 20 or later, and you must turn on ESM with
npm pkg set type=module.Terminal window npm init -y && npm pkg set type=modulenpm install @modelcontextprotocol/server zod tsximport { McpServer } from '@modelcontextprotocol/server';import { serveStdio } from '@modelcontextprotocol/server/stdio';import * as z from 'zod/v4';const STOCK: Record<string, { name: string; qty: number; location: string }> = {'KB-100': { name: 'Wireless keyboard', qty: 42, location: 'A-1' },'MS-200': { name: 'Wireless mouse', qty: 0, location: 'A-2' }};function createServer(): McpServer {const server = new McpServer({ name: 'inventory', version: '1.0.0' });server.registerTool('get_stock',{description: 'Look up the stock quantity and storage location by SKU code (e.g. KB-100).',inputSchema: z.object({ sku: z.string().max(20).describe('SKU code') }),annotations: { readOnlyHint: true }},async ({ sku }) => {const item = STOCK[sku.trim().toUpperCase()];if (!item) {return { content: [{ type: 'text', text: `Unknown SKU: ${sku}` }], isError: true };}return { content: [{ type: 'text', text: `${item.name}: ${item.qty} units (location ${item.location})` }] };});return server;}void serveStdio(createServer);console.error('inventory MCP server running on stdio'); // Logs go to stderrRun it with
npx tsx server.ts, and attach it to Claude Code withclaude mcp add inventory -- npx tsx /absolute/path/server.ts. We launched this code directly withtsxand checked the responses toinitializeand the tool call.
Quick reference
Section titled “Quick reference”claude mcp commands
Section titled “claude mcp commands”| What you want to do | Command |
|---|---|
| Add a local stdio server | claude mcp add <name> -- <command> [args...] |
| Add with environment variables | claude mcp add --env KEY=value --transport stdio <name> -- <command> |
| Add a remote HTTP server | claude mcp add --transport http <name> <URL> |
| Attach a header (token) | --header "Authorization: Bearer ..." (be careful not to leave the token in your shell history) |
| List and status | claude mcp list |
| Server details | claude mcp get <name> |
| Remove | claude mcp remove <name> (also deletes a stored OAuth token) |
| Status, auth, and reconnecting within a session | /mcp |
| Add with JSON | claude mcp add-json <name> '<json>' |
The SSE transport is deprecated. Use HTTP for new servers.
Tool result size limits (Claude Code)
Section titled “Tool result size limits (Claude Code)”| Item | Behavior |
|---|---|
| Over 10,000 tokens | A warning is shown |
MAX_MCP_OUTPUT_TOKENS |
Maximum output tokens, default 25,000 |
| Text result over 50,000 characters | Saved to a file and replaced with a file reference |
| HTTP/SSE response body over 16 MB | The request fails. Split it up on the server (pagination) |
Server security checklist
Section titled “Server security checklist”| Item | What to do |
|---|---|
| Least privilege | Start with read-only tools. Add write and delete tools only when truly necessary, with a narrow scope. Make the database account and tokens the server uses read-only too. |
| Input validation | Limit types, lengths, and ranges in code (for example, the max_results cap). Input the model produces is untrusted input. When building file paths, SQL, or shell commands, don’t just concatenate it. |
| Prompt injection | Text a tool returns (email, web pages, ticket bodies) may contain hidden instructions like “ignore your previous instructions.” Don’t put a tool that fetches outside text on the same server as write tools. |
| Secrets | Don’t write them directly in code or .mcp.json; receive them through environment variables. Don’t put tokens or personal data in tool results or logs. |
| Output size | Limit how much you return at once. Large results grow both tokens (cost) and context. |
| Authentication | Add authentication to a server you expose over HTTP. A shared token gives everyone the same permissions. According to the official MCP security docs (as of 2026-10-12), a server should accept only tokens issued to itself, and the spec forbids token passthrough, where a received token is handed straight to another API. Start OAuth scopes with a minimal range like read. |
| Local HTTP servers | Other processes on the same PC can reach them. The official security docs say to use stdio for local servers, or for HTTP, to use an auth token or IPC with restricted access. |
| Don’t rely on hints | Annotations like readOnlyHint are hints. Block real permissions with server code and credentials. |
| Logs | A stdio server writes only to stderr. Don’t leave sensitive values in logs. |
Common sticking points
Section titled “Common sticking points”ImportError: cannot import name 'FastMCP' or MCPServer can’t be found
Section titled “ImportError: cannot import name 'FastMCP' or MCPServer can’t be found”- Cause: Older tutorials use
FastMCP, and the current SDK v2 usesMCPServer. It happens when the installedmcpversion differs from the text. - Fix: Check the version with
pip show mcp, and remember that the code in this tutorial is for v2. With the virtual environment activated, try reinstalling withpip install "mcp[cli]".
claude mcp list shows Failed to connect
Section titled “claude mcp list shows Failed to connect”- Cause: With stdio, it’s often that the server run command is wrong (a relative path, or a
pythonoutside the virtual environment) or the server died while starting. With HTTP, the server isn’t running or the address or port is different. - Fix: Run the same command directly in a terminal and look at the error. Use an absolute path, then
claude mcp removeandclaude mcp addagain. For HTTP, if you seeECONNREFUSED, start the server first.
A stdio server hangs right after connecting or sends back garbled responses
Section titled “A stdio server hangs right after connecting or sends back garbled responses”- Cause: If the server prints
print()logs to standard output (stdout), they get mixed in with protocol messages. - Fix: Switch all logs to
sys.stderr(console.errorin TypeScript).
Claude doesn’t call my tool
Section titled “Claude doesn’t call my tool”- Cause: The tool name and description may be vague, the server may not be connected, or you may have declined at the approval step.
- Fix: Check the connection status in
/mcp, and rewrite the docstring concretely in the form “what it does + an input example.” Try putting the server name in your request (for example, “Using the inventory server, …”).
I added a custom connector but it won’t connect
Section titled “I added a custom connector but it won’t connect”- Cause: The server isn’t reachable from the public internet (local, internal network, VPN), or the authentication method doesn’t match the server. The connection goes out from Anthropic’s cloud, not your device.
- Fix: Check that
https://your-domain/mcpopens from an external network, and for a private server, allow Anthropic’s IP ranges. Match the authentication setting to the method the server requires (OAuth, header, or none). To edit a connector, remove it and add it again.
A .mcp.json server is stuck at Pending approval
Section titled “A .mcp.json server is stuck at Pending approval”- Cause: A project-scope server needs approval the first time you use it. In a folder you haven’t trusted, the repository can’t approve itself.
- Fix: Open interactive
claudeand approve it. To reset your approval choices, useclaude mcp reset-project-choices.
Practical tips
Section titled “Practical tips”- Few tools, specific descriptions. With many tools, Claude has a harder time choosing and uses more context. Make each tool do one thing.
- The model reads error messages. Write “what went wrong and how to retry” in the
ToolError. Leave out server internals such as internal paths or SQL. - Build it with local stdio first, and move to HTTP when you need to. You only change the transport in
mcp.run()and keep the same tool code. - Look at what already exists before building your own. For a service that already has an official connector or a public server, the cost of building a new one may be higher. But Anthropic doesn’t verify third-party servers, so read the code and permissions before you use one.
- When you hand it out to a team, put it in a plugin. A plugin distributes skills and MCP servers (
.mcp.json) as one bundle. See 6. Package skills and plugins and deploy to your team.
What to read next
Section titled “What to read next”- 6. Package skills and plugins and deploy to your team — bundling servers and skills into a plugin for team distribution
- 1. Build a work bot with tool use — how to define and call tools yourself through the API
- C7. Connectors — how to use ready-made connectors, and their security
- C14. Claude Code core features — MCP scopes, permission modes, and hooks
Sources
Last verified: Oct 26, 2026
- MCP Python SDK (README) github.com
- MCP Python SDK docs py.sdk.modelcontextprotocol.io
- MCP TypeScript SDK (README, v2) github.com
- MCP TypeScript SDK: Build your first server github.com
- Connect Claude Code to tools via MCP code.claude.com
- Get started with custom connectors using remote MCP support.claude.com
- MCP Security Best Practices modelcontextprotocol.io
Prices, limits, and menu names change often. Before making an important decision, check the official pages above for the latest details.
Finished this tutorial?
Progress is saved only in this browser and never sent anywhere.