Something went wrong. Try again.
mirror of github.com/PrefectHQ/fastmcp
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879# /// script# dependencies = ["anthropic", "fastmcp", "rich"]# ///"""Simple Text Sampling
Demonstrates the basic MCP sampling flow where a server tool requestsan LLM completion from the client.
Run: uv run examples/sampling/text.py"""
import asyncio
from rich.console import Consolefrom rich.panel import Panel
from fastmcp import Client, Context, FastMCPfrom fastmcp.client.sampling import SamplingMessage, SamplingParamsfrom fastmcp.client.sampling.handlers.anthropic import AnthropicSamplingHandler
console = Console()
# Create a wrapper handler that logs when the LLM is calledclass LoggingAnthropicHandler(AnthropicSamplingHandler): async def __call__( self, messages: list[SamplingMessage], params: SamplingParams, context ): # type: ignore[override] console.print(" [bold blue]SAMPLING[/] Calling Claude API...") result = await super().__call__(messages, params, context) console.print(" [bold blue]SAMPLING[/] Response received") return result
# Create the MCP servermcp = FastMCP("Haiku Generator")
@mcp.toolasync def write_haiku(topic: str, ctx: Context) -> str: """Write a haiku about any topic.""" console.print( f" [bold cyan]SERVER[/] Tool 'write_haiku' called with topic: {topic}" )
result = await ctx.sample( messages=f"Write a haiku about: {topic}", system_prompt="You are a poet. Write only the haiku, nothing else.", max_tokens=100, )
console.print(" [bold cyan]SERVER[/] Returning haiku to client") return result.text or ""
async def main(): console.print(Panel.fit("[bold]MCP Sampling Flow Demo[/]", subtitle="text.py")) console.print()
# Create the sampling handler handler = LoggingAnthropicHandler(default_model="claude-sonnet-4-5")
# Connect client to server with the sampling handler async with Client(mcp, sampling_handler=handler) as client: console.print("[bold green]CLIENT[/] Calling tool 'write_haiku'...") console.print()
result = await client.call_tool("write_haiku", {"topic": "Python programming"})
console.print() console.print("[bold green]CLIENT[/] Received result:") console.print(Panel(result.data, title="Haiku", border_style="green")) # type: ignore[arg-type]
if __name__ == "__main__": asyncio.run(main())