Sub topic 12
What clients offer servers: sampling, roots, and elicitation
This chapter assumes you know the host, client, and server roles, the JSON-RPC message shapes, and the initialization handshake from earlier chapters. You should also be able to read short Python programs.
Most of MCP flows from client to server. The client lists tools, reads resources, and fetches prompts. Three features run the other way. The server sends a request, and the client answers it. These are sampling, roots, and elicitation. Each one lets a server use something only the client side has: a language model, knowledge of the user's workspace, or the user themselves.
Why servers need to ask the client
A server is usually a small program with narrow logic. It often lacks three things.
- A model. The server has no API key and should not need one.
- Context about where the user is working, such as which folders are in scope.
- A way to talk to the person. It runs as a subprocess or a remote service, with no screen.
The client can supply all three, and the host controls them. Because the request passes through the host, the host can apply its own policies: approval prompts, model choice, and cost limits.
The negotiation rule
All three features are optional. A client declares the ones it supports in the capabilities object of its initialize request:
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-06-18",
"capabilities": {
"sampling": {},
"roots": {"listChanged": true},
"elicitation": {}
},
"clientInfo": {"name": "example-client", "version": "1.0.0"}
}
}A server must send a request only for a feature the client declared. If elicitation is missing from the capabilities, the server must not send elicitation/create. Well-written servers check what the client declared and fall back, for example by returning an error message from the tool.
Sampling: the server borrows the client's model
With sampling, a server asks the client to run a model completion. The server never sees the host's API credentials, and the host decides which model answers.
The method is sampling/createMessage. The request carries the conversation and some preferences:
{
"jsonrpc": "2.0",
"id": 7,
"method": "sampling/createMessage",
"params": {
"messages": [
{"role": "user", "content": {"type": "text", "text": "Summarize in one sentence: ..."}}
],
"systemPrompt": "You are a concise editor.",
"modelPreferences": {
"hints": [{"name": "claude"}],
"costPriority": 0.8,
"speedPriority": 0.5,
"intelligencePriority": 0.3
},
"maxTokens": 100
}
}Note what is a preference and what is a command.
hintsare substrings of model names the server would like. The client may map them to an equivalent model it has.- The three priorities are numbers from 0 to 1. They express relative importance and are not guarantees.
maxTokensis required.systemPrompt,temperature,stopSequences, andincludeContextare optional.
The client may modify or reject the request. The specification recommends a human in the loop: the user can review the prompt before it goes to the model, and review the completion before it returns to the server.
The result contains the role, the content, the model that actually answered, and a stop reason:
{
"jsonrpc": "2.0",
"id": 7,
"result": {
"role": "assistant",
"model": "example-model-1",
"stopReason": "endTurn",
"content": {"type": "text", "text": "The report shows sales rose in Q3."}
}
}Roots: the server learns where it may work
A root is a URI that tells a server which part of the world is relevant. In the current specification, roots are file:// URIs, usually project folders. Roots are guidance about scope. They are not a sandbox, because the protocol does not stop a server process from reading other paths. Real isolation needs operating-system controls.
The client declares "roots": {"listChanged": true}. The server then sends roots/list and gets:
{
"jsonrpc": "2.0",
"id": 3,
"result": {
"roots": [
{"uri": "file:///home/user/project", "name": "project"}
]
}
}The name is optional and only a display label. If the user opens a different folder, a client that set listChanged sends this notification, which has no id and expects no reply:
{"jsonrpc": "2.0", "method": "notifications/roots/list_changed"}The server should then call roots/list again. A server that caches roots and ignores this notification will keep working in a stale directory.
Elicitation: the server asks the user
Elicitation lets a server request structured input from the user in the middle of an operation. Before this feature, a server that needed a missing argument had to fail and hope the model would retry with the value filled in.
The method is elicitation/create. The request has a message for the user and a requestedSchema:
{
"jsonrpc": "2.0",
"id": 9,
"method": "elicitation/create",
"params": {
"message": "A summary already exists. Replace it?",
"requestedSchema": {
"type": "object",
"properties": {
"overwrite": {"type": "boolean", "description": "Replace the existing summary"}
},
"required": ["overwrite"]
}
}
}The schema is deliberately limited to a flat object whose properties are strings (with optional formats), numbers, integers, booleans, or enums. Nested objects and arrays are not allowed. This keeps the form simple for any host to render.
The user has three choices, and the result's action field reports which one:
| `action` | Meaning | `content` present? |
|---|---|---|
| `accept` | The user submitted the form. | Yes, matching the schema |
| `decline` | The user explicitly refused. | No |
| `cancel` | The user dismissed the form without choosing. | No |
A server must handle all three. Treating cancel as accept with defaults is a common error.
Comparing the three features
| Feature | Method | Declared as | Server gets | Main risk |
|---|---|---|---|---|
| Sampling | `sampling/createMessage` | `sampling` | A model completion | Cost and prompt injection |
| Roots | `roots/list` | `roots` | A list of `file://` scopes | Treating scope as security |
| Elicitation | `elicitation/create` | `elicitation` | Structured user input | Phishing for secrets |
A working example
The server below uses the official Python SDK. Its summarize tool first elicits a confirmation, then samples a summary, then logs the client's roots. It assumes a client that declared all three capabilities. Save it as server.py.
from pydantic import BaseModel, Field
from mcp.server.fastmcp import Context, FastMCP
from mcp.types import SamplingMessage, TextContent
mcp = FastMCP("summarizer")
class Confirm(BaseModel):
overwrite: bool = Field(description="Replace the existing summary?")
@mcp.tool()
async def summarize(text: str, ctx: Context) -> str:
"""Summarize text using the client's model."""
roots = await ctx.session.list_roots()
await ctx.info(f"Client roots: {[str(r.uri) for r in roots.roots]}")
answer = await ctx.elicit(
message="A summary already exists. Replace it?", schema=Confirm
)
if answer.action != "accept" or not answer.data.overwrite:
return "Kept the existing summary."
result = await ctx.session.create_message(
messages=[
SamplingMessage(
role="user",
content=TextContent(type="text", text=f"Summarize in one sentence:\n\n{text}"),
)
],
max_tokens=100,
)
if result.content.type == "text":
return result.content.text
return "The model returned non-text content."
if __name__ == "__main__":
mcp.run(transport="stdio")The client supplies one callback for each feature. The SDK registers the matching capability when you pass a callback. This client answers with fixed values so you can run it without a model:
import asyncio
from mcp import ClientSession, StdioServerParameters, types
from mcp.client.stdio import stdio_client
async def handle_sampling(context, params: types.CreateMessageRequestParams):
# A real host shows params.messages to the user and calls its own model here.
return types.CreateMessageResult(
role="assistant",
content=types.TextContent(type="text", text="Stub summary."),
model="stub-model",
stopReason="endTurn",
)
async def handle_elicitation(context, params: types.ElicitRequestParams):
print("Server asks:", params.message)
return types.ElicitResult(action="accept", content={"overwrite": True})
async def handle_roots(context):
return types.ListRootsResult(
roots=[types.Root(uri="file:///home/user/project", name="project")]
)
async def main():
params = StdioServerParameters(command="python", args=["server.py"])
async with stdio_client(params) as (read, write):
async with ClientSession(
read,
write,
sampling_callback=handle_sampling,
elicitation_callback=handle_elicitation,
list_roots_callback=handle_roots,
) as session:
await session.initialize()
result = await session.call_tool("summarize", {"text": "Sales rose in Q3."})
print(result.content)
asyncio.run(main())Running it prints the elicitation message, then the stub summary. Change action="accept" to "decline" and the tool returns "Kept the existing summary." That shows the server handling a refusal.
Common errors
- Sending a request the client did not declare. The request fails. Check the negotiated capabilities first.
- Assuming roots are enforced. A root narrows what a cooperative server does. It does not restrict a malicious one.
- Ignoring
roots/list_changed. The server keeps using folders the user has closed. - Blocking on elicitation in a client with no UI. Headless clients should not declare
elicitation. - Hard-coding a model in sampling. Use
hintsand priorities, because the client picks the model. - Treating
declineandcancelas errors. Both are normal outcomes that your tool should handle.
Exercise
A server wants to ask the user for a deployment region while a tool is running. The client's initialize request declared only sampling and roots. What should the server do, and which three action values must it handle if the client had declared elicitation?
Show answer
The server must not send elicitation/create, because the client did not declare that capability. It should fall back, for example by returning a tool result that says a region argument is required, or by using a default and saying so. If elicitation had been declared, the server must handle accept (with content), decline (explicit refusal), and cancel (dismissed without choosing).
Exercise
Why is it wrong to treat a root such as file:///home/user/project as a security boundary, and what should a client do when the user switches to a different project folder?
Show answer
Roots are scope guidance that a cooperative server follows. The protocol does not stop a server process from opening other paths, so real isolation needs OS-level controls such as containers or permissions. When the folder changes, a client that declared roots.listChanged sends notifications/roots/list_changed, and the server should call roots/list again.