alpha

Instructs a coding assistant how to build Model Context Protocol servers with the Python SDK v2: setup, tools, resources, prompts, transports and tests.
description: 'Instructions for building Model Context Protocol (MCP) servers using the Python SDK v2'
applyTo: '**/*.py, **/pyproject.toml, **/requirements.txt'
These instructions apply to the [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) v2 and the MCP specification revision [2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28).
uv init --app --no-package mcp-server-demo and uv add "mcp[cli]>=2,<3".mcp.server: from mcp.server import MCPServer.FastMCP or mcp.server.fastmcp. SDK v2 removed this import path.Context, Image, Audio, Resolve, Elicit, and the prompt message classes from mcp.server.mcpserver.@mcp.tool(), @mcp.resource(), and @mcp.prompt() decorators for registration.mcp.run() or mcp.run(transport="stdio").mcp.run(transport="streamable-http"), or mount mcp.streamable_http_app() in Starlette or FastAPI.host, port, json_response, stateless_http, transport_security) to run(), not to MCPServer(...).streamable_http_app(). This method has no port option.MCPServer argument. Give all other constructor arguments as keyword arguments.version on MCPServer. If you do not set it, the server reports an empty version.read_only_hint, structured_content, and is_error.ctx: Context parameter to a tool, resource, or prompt to get the request context.await ctx.report_progress(progress, total, message).Resolve(fn) parameter. Return Elicit(message, Model) from fn. This works with clients of all protocol revisions.ctx.elicit(). It fails on a 2026-07-28 connection.logging module. Protocol logging (ctx.info() and similar methods) is deprecated.ctx.session.create_message()). It is deprecated. Call the LLM provider API directly.ctx.session.list_roots()). It is deprecated. Get paths from tool parameters or the server configuration.Icon(src="https://...", mime_type="image/png") from mcp.types. Server, tools, resources, and prompts accept icons=[...].Image class to return images: return Image(data=png_bytes, format="png") or return Image(path=file_path).@mcp.resource("greeting://{name}").@mcp.completion() decorator.Client(mcp) runs it again.ctx.request_context.lifespan_context. Use Context[AppContext] for a typed result.ToolError (from mcp.server.mcpserver.exceptions) for an error that the model must read.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.await ctx.notify_tools_changed(). Do not use ctx.session.send_tool_list_changed(). A 2026-07-28 connection drops it.stateless_http=True changes only how the server serves clients of earlier revisions.json_response=True sends one JSON body for each request. In this mode, the server cannot send progress notifications during the request.uv run mcp dev server.py (MCP Inspector) or uv run mcp install server.py (Claude Desktop).async with Client(mcp) as client: (from mcp import Client).Mount("/path", app=mcp.streamable_http_app()). The lifespan of the host app must enter mcp.session_manager.run() for each server.Mcp-* request headers. Expose the Mcp-Session-Id response header.transport_security, the SDK checks the Host and Origin headers only when the host is 127.0.0.1, localhost, or ::1. For all other hosts, set transport_security=TransportSecuritySettings(allowed_hosts=[...], allowed_origins=[...]) (from mcp.server.transport_security).request_state_security=RequestStateSecurity(keys=[...]) on MCPServer.Server class (from mcp.server) only when MCPServer does not give sufficient control.Field descriptions.print() in a stdio server, because stdout is the protocol channel.from mcp.server import MCPServer
mcp = MCPServer("My Server", version="0.1.0")
@mcp.tool()
def calculate(a: int, b: int, op: str) -> int:
"""Perform calculation"""
if op == "add":
return a + b
return a - b
if __name__ == "__main__":
mcp.run() # stdio by default
from mcp.server import MCPServer
mcp = MCPServer("My HTTP Server", version="0.1.0")
@mcp.tool()
def hello(name: str = "World") -> str:
"""Greet someone"""
return f"Hello, {name}!"
if __name__ == "__main__":
mcp.run(transport="streamable-http", host="127.0.0.1", port=8000)
from pydantic import BaseModel, Field
class WeatherData(BaseModel):
temperature: float = Field(description="Temperature in Celsius")
condition: str
humidity: float
@mcp.tool()
def get_weather(city: str) -> WeatherData:
"""Get weather for a city"""
return WeatherData(
temperature=22.5,
condition="sunny",
humidity=65.0
)
@mcp.resource("users://{user_id}")
def get_user(user_id: str) -> str:
"""Get user profile data"""
return f"User {user_id} profile data"
import logging
from mcp.server.mcpserver import Context
logger = logging.getLogger(__name__)
@mcp.tool()
async def process_data(data: str, ctx: Context) -> str:
"""Process data with progress reports"""
logger.info("Processing: %s", data)
await ctx.report_progress(0.5, 1.0, "Halfway done")
return f"Processed: {data}"
from typing import Annotated
from pydantic import BaseModel
from mcp.server.mcpserver import AcceptedElicitation, Elicit, ElicitationResult, Resolve
class Quantity(BaseModel):
copies: int
async def ask_quantity() -> Elicit[Quantity]:
"""Ask the user how many copies to reserve."""
return Elicit("How many copies?", Quantity)
@mcp.tool()
async def reserve(
title: str,
quantity: Annotated[ElicitationResult[Quantity], Resolve(ask_quantity)],
) -> str:
"""Reserve copies of a book"""
if isinstance(quantity, AcceptedElicitation):
return f"Reserved {quantity.data.copies} of {title!r}."
return "Nothing reserved."
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass
from mcp.server import MCPServer
from mcp.server.mcpserver import Context
@dataclass
class AppContext:
db: Database # Your database client
@asynccontextmanager
async def app_lifespan(server: MCPServer) -> AsyncIterator[AppContext]:
db = await Database.connect()
try:
yield AppContext(db=db)
finally:
await db.disconnect()
mcp = MCPServer("My App", version="0.1.0", lifespan=app_lifespan)
@mcp.tool()
def query(sql: str, ctx: Context[AppContext]) -> str:
"""Query database"""
db = ctx.request_context.lifespan_context.db
return db.execute(sql)
from mcp.server.mcpserver import AssistantMessage, Message, UserMessage
@mcp.prompt(title="Code Review")
def review_code(code: str) -> list[Message]:
"""Create code review prompt"""
return [
UserMessage("Review this code:"),
UserMessage(code),
AssistantMessage("I'll review the code for you.")
]
from mcp.server.mcpserver.exceptions import ToolError
@mcp.tool()
async def risky_operation(input: str) -> str:
"""Operation that might fail"""
if not input:
raise ToolError("Input must not be empty.")
result = await perform_operation(input) # Your operation
return f"Success: {result}"
import pytest
from mcp import Client
from server import mcp # The HTTP Server example
@pytest.mark.anyio
async def test_hello():
async with Client(mcp) as client:
result = await client.call_tool("hello", {"name": "MCP"})
assert result.structured_content == {"result": "Hello, MCP!"}
© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com


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
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

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
Loading reviews…
Loading comments…