Python MCP Server Generator

Python MCP Server Generator

Builds a new Python MCP server with the official SDK: a uv project, typed tools, in-memory tests and client configuration.

Skill files2 files

references/

SKILL.md152 lines
1
---
2
name: python-mcp-server-generator
3
description: 'Use this skill when the user wants to create a new Model Context Protocol (MCP) server in Python. Also use it to expose Python functions, an API, or a database to AI clients as MCP tools. The skill makes a uv project with the MCP Python SDK v2 (MCPServer), typed tools, in-memory tests, and client configuration. Do not use it for an MCP client or for a server in another language.'
4
compatibility: 'Requires uv, Python 3.10 or later, and network access to install packages. The MCP Inspector also requires Node.js.'
5
---
6
7
# Python MCP Server Generator
8
9
Create a Model Context Protocol (MCP) server in Python with the official [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) v2. SDK v2 supports the MCP specification revision [2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28). The same server also serves clients that use earlier revisions.
10
11
## Workflow
12
13
Copy this checklist and track your progress:
14
15
- [ ] Step 1: Create the project.
16
- [ ] Step 2: Write the server.
17
- [ ] Step 3: Write the tests.
18
- [ ] Step 4: Run the tests until they pass.
19
- [ ] Step 5: Configure the client.
20
21
### Step 1: Create the project
22
23
Run these commands:
24
25
```bash
26
uv init --app --no-package project-name
27
cd project-name
28
uv add "mcp[cli]>=2,<3"
29
uv add --dev pytest
30
```
31
32
Then delete `main.py`. The server goes in `server.py`.
33
34
- Without `--no-package`, uv makes a `src/` package layout, and the tests cannot import `server.py`.
35
- `uv init` makes the `.gitignore` file. Do not write a different one.
36
37
### Step 2: Write the server
38
39
Start from this template:
40
41
```python
42
from mcp.server import MCPServer
43
from mcp.server.mcpserver.exceptions import ToolError
44
45
mcp = MCPServer("Demo", version="0.1.0")
46
47
48
@mcp.tool()
49
def divide(a: float, b: float) -> float:
50
"""Divide a by b."""
51
if b == 0:
52
raise ToolError("b must not be zero.")
53
return a / b
54
55
56
if __name__ == "__main__":
57
mcp.run() # stdio is the default transport
58
```
59
60
Then change the template for the request of the user:
61
62
1. Replace `divide` with the tools that the user needs.
63
2. Give each tool full type hints and a docstring. The SDK makes the input schema from the type hints. The docstring becomes the tool description.
64
3. Return a Pydantic model or a `TypedDict` when the client needs machine-readable data. The SDK makes the output schema from the return type.
65
4. Use `async def` for I/O. The SDK runs a sync tool on a worker thread.
66
5. Mark a read-only tool with `@mcp.tool(annotations=ToolAnnotations(read_only_hint=True))` (from `mcp.types`). Use `destructive_hint=True` for a destructive tool.
67
6. Add resources (`@mcp.resource("users://{user_id}")`) and prompts (`@mcp.prompt()`) only when the user asks for them.
68
69
Use stdio by default. Read [references/streamable-http.md](references/streamable-http.md) only when the user asks for a remote server or an HTTP server.
70
71
### Step 3: Write the tests
72
73
Put `test_server.py` next to `server.py`. Write a test for each tool and for each `ToolError`:
74
75
```python
76
import pytest
77
78
from mcp import Client
79
80
from server import mcp
81
82
83
@pytest.mark.anyio
84
async def test_divide():
85
async with Client(mcp) as client:
86
result = await client.call_tool("divide", {"a": 6, "b": 3})
87
assert result.structured_content == {"result": 2.0}
88
89
90
@pytest.mark.anyio
91
async def test_divide_by_zero():
92
async with Client(mcp) as client:
93
result = await client.call_tool("divide", {"a": 1, "b": 0})
94
assert result.is_error
95
assert "must not be zero" in result.content[0].text
96
```
97
98
- The in-memory `Client` needs no subprocess and no port. It connects with the 2026-07-28 revision.
99
- The `mcp` package installs `anyio`, which supplies the `anyio` marker. Do not add `pytest-asyncio`.
100
101
### Step 4: Run the tests until they pass
102
103
1. Run `uv run pytest`.
104
2. If a test fails, read the error. Fix the server or the test.
105
3. Run `uv run pytest` again.
106
4. Continue only when all tests pass.
107
108
### Step 5: Configure the client
109
110
For VS Code, write `.vscode/mcp.json`:
111
112
```json
113
{
114
"servers": {
115
"demo": {
116
"type": "stdio",
117
"command": "uv",
118
"args": ["--directory", "/absolute/path/to/project", "run", "server.py"]
119
}
120
}
121
}
122
```
123
124
For Claude Desktop, run `uv run mcp install server.py`.
125
126
Tell the user these commands:
127
128
- `uv run server.py` starts the stdio server. The server waits for a host on stdin and prints nothing.
129
- `uv run mcp dev server.py` opens the MCP Inspector. The Inspector needs Node.js.
130
131
## Gotchas
132
133
SDK v2 and the 2026-07-28 revision changed many SDK v1 patterns. Do not copy SDK v1 examples.
134
135
- SDK v2 removed `FastMCP` and `mcp.server.fastmcp`. Import the server class with `from mcp.server import MCPServer`.
136
- Import `Context`, `Image`, `Audio`, `Resolve`, `Elicit`, `ElicitationResult`, `AcceptedElicitation`, `Message`, `UserMessage`, and `AssistantMessage` from `mcp.server.mcpserver`.
137
- Give the server name as the first `MCPServer` argument. Give all other constructor arguments as keyword arguments. Their positional order changed in SDK v2.
138
- Set `version`. If you do not set it, the server reports an empty version.
139
- Give the transport options (`transport`, `host`, `port`, `json_response`, `stateless_http`, `transport_security`) to `run()`, not to `MCPServer(...)`.
140
- The SDK v2 types use snake_case fields, for example `read_only_hint`, `structured_content`, and `is_error`.
141
- Raise `ToolError` for an error that the model must read. For other exceptions, the model gets only a generic error message.
142
- Do not raise `MCPError` for a tool failure. The client gets a protocol error, not a tool result with `is_error`. Many hosts do not show this error to the model.
143
- In a stdio server, stdout is the protocol channel. Do not call `print()`. Log to stderr with the `logging` module.
144
- Do not use `ctx.elicit()`. It fails on a 2026-07-28 connection. For user input during a tool call, annotate a parameter with `Resolve(fn)`. Return `Elicit(message, Model)` from `fn`.
145
- Send list change notifications with `await ctx.notify_tools_changed()`. A 2026-07-28 connection drops `ctx.session.send_tool_list_changed()`.
146
- For stdio and HTTP, the lifespan runs one time, when the server starts. Each in-memory `Client(mcp)` in a test runs the lifespan again. Read its object with `ctx.request_context.lifespan_context`.
147
- The 2026-07-28 revision deprecates these features ([SEP-2577](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577)). Do not add them to a new server:
148
- **Sampling** (`ctx.session.create_message()`): Call the LLM provider API directly.
149
- **Protocol logging** (`ctx.log()`, `ctx.info()`, and similar methods): Use the standard `logging` module.
150
- **Roots** (`ctx.session.list_roots()`): Get paths from tool parameters, resource URIs, or the server configuration.
151
- The 2026-07-28 revision has no SSE transport. Use Streamable HTTP.
152

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…