Sampling
Handle LLM completion requests from servers
MCP servers can request LLM completions from clients during tool execution. This enables servers to delegate AI reasoning to the client, which controls which model is used.
Handler
To support sampling, register a sampling handler when you connect. The handler receives the server’s request (CreateMessageRequestParams) and should return either:
CreateMessageResult (success), or
ErrorData (failure)
Here’s a complete example using Anthropic:
Usage
Enable sampling by passing the handler in ClientCapabilitiesConfig when connecting:
Error handling
When something goes wrong inside your handler, return an ErrorData (don’t raise). The server will receive this as an MCP error response to its sampling request.
Last modified on June 30, 2026