The official MCP Python SDK exposes Python functions to an AI client. Use it when an assistant should follow a calculation or query rule you already own. You do not need a server simply to ask an assistant to write Python, or when an existing tool already handles the job.
This example builds a quote calculator with SDK 2.3.0, connects it over stdio and checks both successful results and errors. A useful connection must let the assistant see why a request failed, as well as return the right total.
Install the SDK and CLI
With uv and Codex CLI or Claude Code installed, open PowerShell in a new project:
uv venv --python 3.12 .venv
uv pip install --python .venv\Scripts\python.exe "mcp[cli]==2.3.0"
$mcpCli = (Resolve-Path .venv\Scripts\mcp.exe).Path
$server = Join-Path (Get-Location).Path server.py
The cli extra installs the mcp run launcher. This guide uses the 2.x MCPServer API, rather than an older bundled FastMCP import or the separate fastmcp package.
Write a tool with explicit calculation rules
Save this as server.py. Prices use integer cents so the example can reject a fractional-cent discount instead of quietly choosing a rounding rule:
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp.types import ToolAnnotations
mcp = MCPServer("Order quote")
@mcp.tool(annotations=ToolAnnotations(
read_only_hint=True, destructive_hint=False,
idempotent_hint=True, open_world_hint=False,
))
def quote_order(unit_price_cents: int, quantity: int, discount_percent: int = 0) -> dict[str, int]:
"""Calculate a quote in integer cents; discount must divide the gross amount exactly."""
if unit_price_cents < 0:
raise ToolError("unit_price_cents must be non-negative")
if quantity < 1:
raise ToolError("quantity must be at least 1")
if not 0 <= discount_percent <= 100:
raise ToolError("discount_percent must be between 0 and 100")
gross = unit_price_cents * quantity
if gross * discount_percent % 100:
raise ToolError("discount produces a fractional cent; choose an explicit rounding rule")
discount = gross * discount_percent // 100
return {"gross_cents": gross, "discount_cents": discount, "net_cents": gross - discount}
Type hints describe the arguments and returned data. The function checks the business rules. ToolError supplies an expected, client-visible failure message.
The CLI loads this module and starts the server. It needs no second startup call at the bottom of the file, and the module writes no debugging text to the stdio protocol stream.
Connect an AI client
Codex CLI
In the same PowerShell session:
codex mcp add mcp-python-sdk -- $mcpCli run $server --transport stdio
codex mcp list
Check the executable and module paths in the list. Open a fresh Codex conversation, request quote_order explicitly and inspect its actual tool response.
Claude Code
claude mcp add mcp-python-sdk --scope project --transport stdio -- $mcpCli run $server --transport stdio
claude mcp list
Our health check returned ✓ Connected. The client starts a local stdio subprocess; this setup needs no HTTP port.
For Cursor, follow its MCP guide with the launcher described in the SDK documentation.
Three jobs for the tool
Calculate using the shared function
Call quote_order with unit_price_cents=12000, quantity=2 and
discount_percent=0. Report the returned gross_cents, discount_cents and
net_cents. Do not replace the call with mental arithmetic.
The actual result is 24000 gross cents, zero discount and 24000 net cents. Keeping the formula in Python gives different conversations the same implementation to call.
Compare a discounted quote
Call quote_order for the same unit price and quantity with discount_percent=10.
Compare the returned values with the zero-discount result. Do not edit files.
The tool returns gross_cents=24000, discount_cents=2400 and net_cents=21600. Separate output fields make the deduction easy to check.
Check whether failures are actionable
Call quote_order with unit_price_cents=12000, quantity=0, discount_percent=0.
Then call unit_price_cents=1, quantity=1, discount_percent=10.
Report the actual error text from each call without inventing extra detail.
Both calls fail deliberately. The first includes quantity must be at least 1; the second includes discount produces a fractional cent; choose an explicit rounding rule. The assistant receives enough information to explain or correct the input.
Common errors
Only “Error executing tool quote_order” reaches the client
Our initial implementation raised ValueError; the client received that generic message without the calculation-specific detail. Switching expected business failures to ToolError produced the full explanations above. Reserve client-visible errors for information the caller should see, rather than exposing arbitrary internal exceptions.
quantity must be at least 1
The connection is working: the function rejected the input. Supply a positive quantity. If zero has a valid meaning in your application, change the rule and its tests before exposing that behavior to clients.
discount produces a fractional cent
This example rejects discounts that cannot be represented in whole cents. Ten percent of a one-cent gross amount triggers it. Decide how your application rounds before implementing that policy; silently dropping the remainder would introduce a different rule.
Scope, costs and alternatives
The example calculates values without checking inventory, taking payment or writing orders. Its annotations describe deterministic, read-only behavior with no external access. Annotations do not restrict what arbitrary Python code can do; new file or service access still needs appropriate permissions and validation.
The SDK is MIT-licensed and does not include a model or a separate model API charge. Client and model usage are separate. This walkthrough covers stdio; use the official documentation for HTTP serving, authentication and deployment.
If you already have FastAPI endpoints, consider an API adapter. For a framework with more application-level features, see FastMCP. Use MCP Inspector to examine tools and protocol errors.
FAQ
Is the MCP Python SDK the same as FastMCP?
The official SDK and standalone FastMCP are separate packages. This guide pins mcp[cli]==2.3.0 and uses MCPServer. Match package names, versions and imports before applying an older example.
Do I need a model API key to build this server?
The local server only runs a Python function and needs no model key. Codex or Claude Code supplies the model and chooses when to call the tool. A function that connects to another service would need that service's own configuration.
Why is there no mcp.run() at the bottom of server.py?
The mcp run server.py --transport stdio launcher loads the object named mcp and starts the transport. Importing the definition alone does not establish a client connection. Keep one startup mechanism for this example.
Why test invalid input as well as the correct total?
Successful arithmetic only checks the normal path. Zero quantities, out-of-range discounts and fractional cents require deliberate behavior. These tests also exposed the generic exception message, which became actionable after the change to ToolError.
References
What we tested
On 2026-11-16: Windows, Python 3.12, mcp[cli] 2.3.0 and Codex CLI 0.169.0. Codex made two quote calls and two invalid-input calls; we compared ValueError with ToolError responses. Claude Code add/list reported Connected. Cursor, HTTP, remote deployment, external databases and payment flows were not tested.