Skip to main content
Sampling lets a tool ask the connected client’s LLM for a completion during tool execution. Use it when the server needs model judgment but should not own an LLM provider integration. This guide focuses on when to use sampling and how to keep tools resilient. Use the Tool context API reference for exact overloads, options, progress behavior, defaults, and return shapes.

Use sampling when the client should provide the model

Sampling is useful when the connected client already has the right model, credentials, policy, or user context. Good fits: Do not use sampling for deterministic server logic, authorization decisions, or work that must succeed in clients without sampling support.

Check client support

Only call ctx.sample() when the client advertises the sampling capability. Provide a deterministic fallback.
The fallback should still give the user a useful result, even if it is less capable than the sampled path.

Keep prompts narrow

Sampling works best when the prompt asks for one clear output. Put server-side data into the prompt and ask for a bounded result.
Avoid asking the sampled model to make hidden business decisions. If the tool changes state, keep the state-changing logic on the server and use sampling only for language or analysis.

Use full control when needed

Use the full request form when the tool needs a system prompt, multiple messages, or model preferences.
Keep exact option tuning in the API reference. The guide-level choice is simple: use a string prompt for ordinary completions, and use the full request object when the message structure matters.

Report long-running progress

Sampling can take time. If the client supplied a progress token, mcp-use can report progress while waiting. For custom progress handling or intervals, see the Tool context API reference. For long non-sampling work, use ctx.reportProgress directly:
Use Notifications for broader server-to-client notification workflows.

Handle sampling failures

Sampling can fail when the client rejects the request, disconnects, times out, or returns content your tool does not expect.
Return a fallback result when the tool can still complete. Return an error only when sampling is required for correctness.

Test sampling locally

Run a server with a sampling tool and call it from a client that supports sampling, such as the Inspector.
In the Inspector, call the sampling tool, approve the sampling request, and verify both the sampled path and the fallback path.

Next steps

Tool context API reference

Look up ctx.sample() overloads, options, progress behavior, and return shapes.

Elicitation

Ask the user for input during tool execution.

Notifications

Send status, progress, and custom notifications to connected clients.

Client sampling

Configure sampling support in a TypeScript MCP client.