60e0ffc959
Upgrade checks / Notify on failure (push) Has been cancelled
Upgrade checks / Close issue on success (push) Has been cancelled
Schema Crash Test / Real-world schema crash test (232K schemas) (push) Has been cancelled
Run static analysis / static_analysis (push) Has been cancelled
Tests / Tests: Python 3.10 on ubuntu-latest (push) Has been cancelled
Tests / Tests: Python 3.13 on ubuntu-latest (push) Has been cancelled
Tests / Tests: Python 3.10 on windows-latest (push) Has been cancelled
Tests / Tests with lowest-direct dependencies (push) Has been cancelled
Tests / MCP conformance tests (push) Has been cancelled
Tests / Integration tests (push) Has been cancelled
Tests / Package install smoke (push) Has been cancelled
Upgrade checks / Static analysis (push) Has been cancelled
Upgrade checks / Tests: Python 3.10 on ubuntu-latest (push) Has been cancelled
Upgrade checks / Tests: Python 3.13 on ubuntu-latest (push) Has been cancelled
Upgrade checks / Tests: Python 3.10 on windows-latest (push) Has been cancelled
Upgrade checks / Integration tests (push) Has been cancelled
Update MCPServerConfig Schema / update-config-schema (push) Has been cancelled
Update SDK Documentation / update-sdk-docs (push) Has been cancelled
1.3 KiB
1.3 KiB
Sampling Examples
These examples demonstrate FastMCP's sampling API, which allows server tools to request LLM completions from the client.
Prerequisites
pip install fastmcp[anthropic]
export ANTHROPIC_API_KEY=your-key
Or run directly with uv:
uv run examples/sampling/text.py
Examples
Simple Text Sampling (text.py)
Basic sampling flow where a server tool requests an LLM completion:
uv run examples/sampling/text.py
Structured Output (structured_output.py)
Uses result_type to get validated Pydantic models from the LLM:
uv run examples/sampling/structured_output.py
Tool Use (tool_use.py)
Gives the LLM tools to use during sampling (calculator, time, dice):
uv run examples/sampling/tool_use.py
Server Fallback (server_fallback.py)
Configures a fallback sampling handler on the server, enabling sampling even when clients don't support it:
uv run examples/sampling/server_fallback.py
Using OpenAI Instead
To use OpenAI instead of Anthropic, change the handler:
from fastmcp.client.sampling.handlers.openai import OpenAISamplingHandler
handler = OpenAISamplingHandler(default_model="gpt-4o-mini")
And install with pip install fastmcp[openai].