---
title: "How to Build an MCP Server in Python (Step-by-Step, 2026)"
description: "Build a working MCP server with the official Python SDK: two tools (web search and read page) in about 30 lines, tested with the SDK client, then connected to Claude Code and Claude Desktop, plus HTTP transport and debugging tips."
category: "guides"
url: https://keirolabs.cloud/blog/how-to-build-mcp-server
published: 2026-11-24
updated: 2026-11-24
---

# How to build an MCP server in Python: a web search server, step by step

## The 60-second version

**An MCP server is a small program that exposes tools to AI apps over the Model Context Protocol.** Write it once, and Claude Desktop, Claude Code, IDEs and agent frameworks can all use its tools. With the official Python SDK, a working server is about 30 lines. This guide builds a **web search MCP server** with two tools, `web_search` and `read_page`, and every step was run and tested.

| Step | What you do |
|---|---|
| 1. Install | `pip install mcp requests` |
| 2. Write | Decorate Python functions with `@mcp.tool()` |
| 3. Run | `mcp.run()` (stdio) or `mcp.run(transport="streamable-http")` |
| 4. Test | List tools and call them from an MCP client |
| 5. Connect | `claude mcp add ...` for Claude Code, or a JSON config for Claude Desktop |

We tested this with the `mcp` Python SDK version 1.26.0.

## What is an MCP server?

**MCP (Model Context Protocol) is an open standard for connecting AI applications to tools and data.** Anthropic introduced it and has since donated it to the Linux Foundation's Agentic AI Foundation. An MCP server can offer three kinds of things:

- **Tools:** functions the model can call (search, query a database, create a ticket). This is what most servers are for.
- **Resources:** data the app can read (files, records).
- **Prompts:** reusable prompt templates.

**And it talks over one of two transports:** **stdio,** where the client launches your server as a local process (the simplest, and the default), or **Streamable HTTP,** where your server runs as a web service that remote clients connect to.

## Step 1: install the SDK

```bash
pip install mcp requests
```

`mcp` is the official Python SDK; it includes **FastMCP,** a high-level API that turns typed Python functions into MCP tools. `requests` is for calling the search API.

## Step 2: write the server

**Each tool is a typed function with a docstring.** FastMCP reads the type hints to build the input schema and uses the docstring as the tool's description, which is what the model reads to decide when to call it:

```python
# server.py: a web search MCP server backed by Keirolabs.
import os, requests
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("keiro-search")
API = "https://api.keirolabs.cloud/api/v2"

def _post(path: str, body: dict) -> dict:
    r = requests.post(f"{API}/{path}", json=body, timeout=60,
                      headers={"Authorization": f"Bearer {os.environ['KEIRO_API_KEY']}"})
    r.raise_for_status()
    return r.json()

@mcp.tool()
def web_search(query: str, count: int = 8) -> str:
    """Search the live web. Returns numbered results with title, URL and snippet.
    Use for anything recent or anything you are not sure about. Keep queries to 2-10 words."""
    results = _post("search/lite", {"query": query, "count": max(1, min(count, 20))})["results"]
    return "\n\n".join(f"[{i+1}] {r['title']}\n{r['url']}\n{r.get('snippet', '')}"
                       for i, r in enumerate(results)) or "No results."

@mcp.tool()
def read_page(url: str) -> str:
    """Fetch a web page and return its main content as markdown. Use after web_search, on the 1-3 most relevant URLs."""
    page = _post("extract", {"url": url})["results"][0]
    if page.get("error"):
        return f"Could not read {url}: {page['error']}"
    return page["content"][:20000]   # cap what goes into the model's context

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

**Design choices that matter:**

- **Two tools, not ten.** Search to find, read to go deep. Every tool's definition is sent to the model on every request.
- **Return compact text,** not raw JSON. Numbered results with URLs are easy for the model to cite.
- **Clamp arguments** (`count`) and **cap output size** (`[:20000]`) instead of trusting the model.
- **Return errors as text** so the model can try another URL instead of failing.
- **Keep secrets in environment variables,** never in tool arguments.

## Step 3: test it before connecting it to anything

**Test with the SDK's own client.** This launches the server over stdio, lists its tools and calls both:

```python
# test_server.py
import asyncio, os, sys
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def main():
    params = StdioServerParameters(command=sys.executable, args=["server.py"], env=dict(os.environ))
    async with stdio_client(params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            tools = (await session.list_tools()).tools
            print("TOOLS:", [(t.name, list(t.inputSchema["properties"])) for t in tools])
            out = await session.call_tool("web_search", {"query": "latest stable Python version", "count": 3})
            text = out.content[0].text
            print(text[:300])
            page = await session.call_tool("read_page", {"url": text.split("\n")[1]})
            print(len(page.content[0].text), "chars")

asyncio.run(main())
```

**What we got:**

```text
TOOLS: [('web_search', ['query', 'count']), ('read_page', ['url'])]
[1] The official home of the Python Programming Language
https://www.python.org/downloads/
Download the latest version for Windows. ... Or get the standalone installer for Python 3.15.2.
...
6583 chars
```

**The schema came straight from the type hints:** `query` and `count` for search, `url` for reading. The page came back as clean markdown starting with "# Download Python". You can also inspect a server interactively with the MCP Inspector (`npx @modelcontextprotocol/inspector python3 server.py`).

## Step 4: connect it to Claude Code and Claude Desktop

**Claude Code,** one command:

```bash
claude mcp add keiro-search -e KEIRO_API_KEY=your-key -- python3 /absolute/path/to/server.py
```

**Claude Desktop:** add the server to `claude_desktop_config.json` (Settings → Developer → Edit Config), then restart the app:

```json
{
  "mcpServers": {
    "keiro-search": {
      "command": "python3",
      "args": ["/absolute/path/to/server.py"],
      "env": {"KEIRO_API_KEY": "your-key"}
    }
  }
}
```

**Use absolute paths.** The client launches your server from its own working directory, so relative paths and virtual environments that aren't activated are the most common reasons a server "doesn't show up". Point `command` at the Python inside your virtual environment if `mcp` is installed there.

## Step 5 (optional): run it over HTTP

**For a server that remote clients or teammates connect to,** change one line:

```python
mcp.run(transport="streamable-http")   # serves at http://localhost:8000/mcp by default
```

Clients then connect by URL, for example `claude mcp add --transport http keiro-search https://your-host/mcp`. **Before exposing it publicly, add authentication.** Anyone who can reach the URL can spend your API credits.

## Debugging an MCP server

- **Never print to stdout in a stdio server.** Stdout carries the protocol messages; a stray `print()` corrupts them. Log to stderr instead.
- **"Tool not found" or no tools listed:** run the test client above first, to separate server bugs from client config bugs.
- **Works in the terminal, fails in the app:** usually a missing environment variable or a relative path.
- **The model never calls your tool:** improve the docstring. Say *when* to use the tool, not just what it does ([LLM tools](/blog/llm-tools)).
- **Huge responses:** cap output; a full web page can blow up the context window ([context engineering for search agents](/blog/context-engineering-web-search-agents)).

## Ready-made instead of built?

**If you just want web search in Claude or your IDE,** there are existing web search MCP servers, including Keirolabs' own ([best MCP servers for web search and scraping](/blog/best-mcp-servers-web-search-scraping-2026), [MCP web search guide](/blog/mcp-model-context-protocol-web-search-2026-guide)). **Build your own when** you want to combine search with your own tools and data, control exactly what the model sees, or ship a server for your product.

New Keirolabs accounts get up to 2,000 free credits with no card, enough to run this server for a long while ([get a key](https://platform.keirolabs.cloud/register)).
