# Build an MCP Server in Python (with a Chart Tool)

> How to build an MCP (Model Context Protocol) server in Python with the official mcp package. Decorate functions with @server.tool(), return a Matplotlib chart as an Image, test with a client, and connect to Claude.

Source: https://www.pythoncharts.com/ai/mcp-server-python/ | Published: 2026-12-06 | Author: Alex Scott | Category: AI | Tags: mcp, model context protocol, llm, claude, tool use, matplotlib, pandas

To build an MCP (Model Context Protocol) server in Python, create an `MCPServer` from the official [`mcp`](https://pypi.org/project/mcp/) package, decorate ordinary functions with `@server.tool()`, and call `server.run()`. The type hints become the tool's input schema and the docstring becomes its description, so an AI app such as Claude can discover the tools and call them. No API key is involved, because the server never calls a model itself.

This post uses `mcp` 2.3.0. In `mcp` 1.x the class was `FastMCP` in `mcp.server.fastmcp`; in 2.x it is `MCPServer` in `mcp.server.mcpserver`, and importing the old path raises a `ModuleNotFoundError` that points to the migration guide.

## Quick Example

The server below wraps a simulated bakery orders table (one row per product per day, seeded so the numbers repeat) in two tools: one returns the best sellers as data, and one returns a Matplotlib bar chart as an image.

```python
import io

import matplotlib
import numpy as np
import pandas as pd
from mcp.server.mcpserver import Image, MCPServer
from mcp.server.mcpserver.exceptions import ToolError

matplotlib.use("Agg")  # no window: the server has no screen
import matplotlib.pyplot as plt

# Simulated orders for a small bakery: one row per product per day
rng = np.random.default_rng(31)
days = pd.date_range("2026-01-01", "2026-11-30", name="date")
menu = {"Sourdough": (4.50, 60), "Croissant": (3.20, 85), "Bagel": (2.60, 70), "Cinnamon roll": (3.80, 40)}
frames = []
for product, (price, base) in menu.items():
    season = 1 + 0.25 * np.sin(2 * np.pi * (days.day_of_year.to_numpy() - 80) / 365)
    units = rng.poisson(base * season * np.where(days.day_of_week >= 5, 1.4, 1.0))
    frames.append(pd.DataFrame({"date": days, "product": product, "units": units,
                                "revenue": (units * price).round(2)}))
orders = pd.concat(frames, ignore_index=True)

server = MCPServer("bakery-sales")

@server.tool()
def top_products(n: int = 3, since: str = "2026-01-01") -> list[dict]:
    """Best-selling products by revenue, from the `since` date (YYYY-MM-DD) onward."""
    recent = orders[orders["date"] >= since]
    totals = recent.groupby("product")["revenue"].sum().nlargest(n).round(2)
    return [{"product": p, "revenue": float(r)} for p, r in totals.items()]

@server.tool()
def monthly_revenue_chart(product: str | None = None) -> Image:
    """Bar chart of revenue per month, for one product or for all of them."""
    data = orders if product is None else orders[orders["product"] == product]
    if data.empty:
        raise ToolError(f"Unknown product {product!r}. Choose from {sorted(menu)}")
    monthly = data.groupby(data["date"].dt.to_period("M"))["revenue"].sum()
    fig, ax = plt.subplots(figsize=(7, 3.6))
    ax.bar(monthly.index.strftime("%b"), monthly.to_numpy(), color="#b5651d")
    ax.set(title=f"{product or 'All products'}: revenue by month (USD)")
    ax.spines[["top", "right"]].set_visible(False)
    buffer = io.BytesIO()
    fig.savefig(buffer, format="png", dpi=150, bbox_inches="tight")
    plt.close(fig)
    return Image(data=buffer.getvalue(), format="png")
```

Save that as `server.py` and add two lines at the bottom, which start the server over standard input and output (the `stdio` transport):

```python
if __name__ == "__main__":
    server.run()
```

Running `python server.py` now sits and waits, because it is waiting for an MCP client to talk to it. That is correct. The next section shows how to talk to it.

## How do I test an MCP server without an AI app?

Use the `Client` that ships with the package. Passing the server object itself connects them in memory, with no subprocess, which makes a quick check in a notebook or a test. `client.call_tool()` takes the tool name and a dictionary of arguments:

```python
import asyncio

from mcp import Client

async def call(tool, arguments):
    async with Client(server) as client:
        return await client.call_tool(tool, arguments)

result = asyncio.run(call("top_products", {"n": 2, "since": "2026-10-01"}))
print(result.structured_content)
print(result.is_error)
```

```text
{'result': [{'product': 'Croissant', 'revenue': 15856.0}, {'product': 'Sourdough', 'revenue': 15201.0}]}
False
```

The return value is a `CallToolResult`. A tool that returns a plain value also fills `structured_content` (a dictionary under the key `result`, built from the return type hint), and the same data is in `result.content` as text. In a Jupyter notebook, skip `asyncio.run()` and write `await call(...)` directly.

To test the real thing, start `server.py` as a subprocess with the same client. This is exactly what an AI app does:

```python
import sys

from mcp import Client, StdioServerParameters

params = StdioServerParameters(command=sys.executable, args=["server.py"])

async def main():
    async with Client(params) as client:
        tools = await client.list_tools()
        print([tool.name for tool in tools.tools])

asyncio.run(main())
```

```text
['top_products', 'monthly_revenue_chart']
```

## How do I return a Matplotlib chart from an MCP tool?

Return an `mcp.server.mcpserver.Image`, built from the PNG bytes of a saved figure. The client receives it as an `ImageContent` block with a `mime_type` of `image/png` and the bytes base64-encoded in `data`, and apps like Claude display it in the conversation. The chart tool above takes an optional `product`, so the same function draws both charts here:

```python
import base64

for product in [None, "Cinnamon roll"]:
    result = asyncio.run(call("monthly_revenue_chart", {"product": product}))
    image = result.content[0]
    print(product, image.type, image.mime_type, len(base64.b64decode(image.data)), "bytes")
```

```text
None image image/png 24052 bytes
Cinnamon roll image image/png 22070 bytes
```

![Bar chart of bakery revenue by month for all products, rising from January to a July peak and falling toward November](https://www.pythoncharts.com/ai/mcp-server-python/images/mcp-chart-all.png)

![Bar chart of cinnamon roll revenue by month, peaking in June](https://www.pythoncharts.com/ai/mcp-server-python/images/mcp-chart-cinnamon-roll.png)

All products together peak in July ($37,278) and are lowest in November ($23,350). Cinnamon rolls peak a month earlier, in June ($6,566), which is the kind of detail an AI app can only surface if you give it a tool that takes a `product` argument.

Two details matter for any server that draws charts. Call `matplotlib.use("Agg")` before importing `pyplot`, since the server has no display. And call `plt.close(fig)` after saving, because a long-running server would otherwise keep every figure in memory.

## How do the type hints and docstrings become the tool schema?

The client never sees your Python. It sees a name, a description and a JSON Schema for the arguments, all generated from the function. `list_tools()` shows them:

```python
async def list_tools():
    async with Client(server) as client:
        return (await client.list_tools()).tools

tool = asyncio.run(list_tools())[0]
print(tool.name, "-", tool.description)
print(tool.input_schema["properties"])
print("required:", tool.input_schema.get("required"))
```

```text
top_products - Best-selling products by revenue, from the `since` date (YYYY-MM-DD) onward.
{'n': {'default': 3, 'title': 'N', 'type': 'integer'}, 'since': {'default': '2026-01-01', 'title': 'Since', 'type': 'string'}}
required: None
```

A model decides whether to call a tool, and with which arguments, from exactly this text. So name tools after what they do (`top_products`, not `query1`), say in the docstring what the arguments mean and what format dates take, and give arguments defaults when a sensible one exists. Arguments are validated with Pydantic before your function runs.

## What happens when a tool fails?

An exception inside a tool does not crash the server. The call comes back with `is_error` set to `True`, and what the model sees depends on the exception. Raise `ToolError` (from `mcp.server.mcpserver.exceptions`) for a failure you expect, and your message reaches the model (after an `Error executing tool <name>:` prefix), which can read it and retry:

```python
result = asyncio.run(call("monthly_revenue_chart", {"product": "Muffin"}))
print(result.is_error)
print(result.content[0].text)
```

```text
True
Error executing tool monthly_revenue_chart: Unknown product 'Muffin'. Choose from ['Bagel', 'Cinnamon roll', 'Croissant', 'Sourdough']
```

That is why the chart tool's message lists the valid products: the model sees it and can call the tool again with a correct name. Any other exception, such as a `ValueError` or `KeyError`, is treated as a crash. The server logs the traceback, and the model only sees `Error executing tool monthly_revenue_chart`, which gives it nothing to fix. A missing required argument or a value of the wrong type is rejected before your function is called, with a message naming the field.

## How do I add resources and prompts?

MCP servers offer three things: tools (functions the model calls), resources (data the app can read by URI) and prompts (reusable message templates the user picks). Resources and prompts use their own decorators:

```python
@server.resource("bakery://products")
def products() -> list[str]:
    """The products on the menu."""
    return sorted(menu)

@server.prompt()
def monthly_review(month: str) -> str:
    """Ask for a written review of one month."""
    return (f"Use the bakery-sales tools to review {month}. Name the best seller, "
            "chart the revenue by month, and say what changed from the month before.")

async def read_extras():
    async with Client(server) as client:
        resource = await client.read_resource("bakery://products")
        prompt = await client.get_prompt("monthly_review", {"month": "October"})
        return resource.contents[0].text, prompt.messages[0].content.text

text, message = asyncio.run(read_extras())
print(text)
print(message)
```

```text
[
  "Bagel",
  "Cinnamon roll",
  "Croissant",
  "Sourdough"
]
Use the bakery-sales tools to review October. Name the best seller, chart the revenue by month, and say what changed from the month before.
```

Add these above the `if __name__` lines in `server.py`. The decorated functions still behave as normal Python functions, so you can unit test them directly.

## How do I connect the server to Claude?

An MCP client launches the server as a subprocess, so it needs a command that works from anywhere. Use an absolute path to `server.py`, and give the command every package the server imports. With Claude Code, add it from a terminal:

```bash
claude mcp add bakery -- uv run --with mcp --with pandas --with matplotlib python /absolute/path/to/server.py
```

Claude Desktop and other apps that read a JSON config use the same command split into `command` and `args` (in `claude_desktop_config.json`, under `mcpServers`):

```json
{
  "mcpServers": {
    "bakery": {
      "command": "uv",
      "args": ["run", "--with", "mcp", "--with", "pandas", "--with", "matplotlib",
               "python", "/absolute/path/to/server.py"]
    }
  }
}
```

Restart the app, then ask something that needs the data: "Which product had the highest revenue since October, and can you chart it by month?" The model picks `top_products` and `monthly_revenue_chart` by their descriptions, calls them, and writes the answer around what they return.

## Which transport should I use?

`server.run()` defaults to `"stdio"`. The other options on `run()` are `"sse"` and `"streamable-http"`:

| | `stdio` | `streamable-http` |
|---|---|---|
| How it runs | The app launches it as a subprocess | You run it as a web server, the app connects by URL |
| Good for | Local tools on your own machine | A shared server, or one on another machine |
| Setup | A command and a path | A host, a port and, for anything public, authentication |
| Call it with | `server.run()` | `server.run("streamable-http")` |

Start with `stdio`. Move to `streamable-http` when several people or apps need the same server.

## Practical Tips

- **Never `print()` in a `stdio` server.** Standard output carries the protocol, so a stray `print` corrupts the messages. Log to standard error with `logging` or `print(..., file=sys.stderr)`.
- **Raise `ToolError` for expected failures.** Its message goes to the model. Other exceptions are hidden from it.
- **Keep tools small and well named.** A model picks between tools from their names and docstrings, so five clear tools work better than one that takes a "mode" argument.
- **Return summaries, not whole tables.** Everything a tool returns goes into the model's context. Send the top rows or the aggregate and let the model ask for more.
- **Treat arguments as untrusted.** The model fills them in, and a user can influence it. Validate paths and dates, and never pass a model-written string to `eval()` or a shell.
- **Pin the version.** The 1.x to 2.x change renamed the main class, so `pip install mcp==2.3.0` keeps examples like these working.

## Similar Topics

- [Generate Charts from a DataFrame with an LLM](https://www.pythoncharts.com/ai/llm-generate-charts-from-dataframe/)
- [Run Local LLMs with Ollama in Python](https://www.pythoncharts.com/ai/run-local-llms-ollama-python/)
- [Build a Simple RAG Pipeline in Python](https://www.pythoncharts.com/ai/simple-rag-pipeline-python/)
- [AI in Python: A Guide to Local LLMs, Embeddings, RAG and MCP](https://www.pythoncharts.com/ai/ai-python-guide/)
