Skip to content
ImagineWorld

Sampling

node_idnode-book_learn-model-context-protocol-with-python_chapter-09-sampling
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num9
chapter_titleSampling
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

One of the most powerful features of MCP is sampling. What does that mean, first of all? Well, let’s take a look at the definition of the word and deduce from there. Merriam-Webster defines sampling as follows:

“the action or process of taking samples of something for analysis”

Okay, so we need a sample, and we end up analyzing said sample, understood. With this definition in mind, let’s talk about it in the context of MCP. In MCP, sampling means the server is sending a sampling request, a sample for analysis, to the client. Why does the server do that? It’s simple; the server needs the client’s help with some things. Because the client is the one with the LLM (even though a server can have an LLM sometimes), the server delegates tasks to the client, where an LLM can help.

Makes sense so far, right? But I bet you’re asking why a server would do that.

In this chapter, we’ll do the following:

  • Understand the topic of sampling and when to use it
  • Build a server implementation using sampling and consume it with VS Code
  • Connect the server implementation to a client implementation for the occasions when we want to integrate this functionality into our app.

The chapter covers the following topics:

  • Why sampling?
  • Implementing sampling

As we said at the beginning, the server wants to delegate some problems to the client and, specifically, to the client’s LLM. So, what problems can an LLM help with that the server can’t? There are lots of examples if you think about it: generating product descriptions, abstracts, tags, and more.

Let’s look into the sample flow first so we understand how the interaction happens at a high level.

When performing sampling, the following participants are involved:

  • User: The user is usually involved in two places, as the originator of the initial action, and even as the human in the loop, accepting or modifying the sample request.
  • Server: The server is the participant sending out a sample request. This request is usually sent out from a server feature, such as a tool call, reading of a resource, or a request from a prompt template.
  • Client: The client’s job is to receive the sample request and show it to the user, so the user can decide what to do with it. A user treats a sampling request as a recommendation for what to do. If the request asks for a specific model, number of tokens, and so on, then this is something the user can take under advisement, and either accept or change to their liking.
  • LLM: The LLM on the client plays the part of completing the sampling request and takes a prompt originating from the server, and produces a response using its generative capabilities.

Here’s a diagram depicting the overall flow:

Figure 9.1 – Sampling flow

It’s worth clarifying that a sampling request doesn’t happen for no reason, but rather, there’s an initial action that ends up triggering it. For example, the user wants to create a product, or needs help with a blog post, and so on, and that in turn leads to the server delegating part of that task back to the client.

Let’s look at some specific scenarios next to understand it better.

We’ve mentioned some scenarios briefly up to this point, but let’s discuss them in detail.

The act of writing a blog post is a good case, as there are aspects of it that definitely fall on the user, such as writing a draft. However, there are parts of it when an LLM does a better job, such as summarizing it for an abstract or even generating keywords (thank you, Kent Dodds, for the inspiration for this use case):

  1. The user submits a draft blog post to the server.
  2. The server stores the draft but asks for help with producing tags, so a sample request is sent.
  3. The client uses its LLM to analyze the draft and produce a response.

A common task for someone working in a back office as part of e-commerce is the management of products. Usually, you start off registering the product by title and capture other properties that might make sense. However, writing a compelling description might be a time-consuming task and something an LLM does better than a human. Here’s how this use case could look as a sampling scenario:

  1. The admin user, via the client, adds a new product with a title and keywords.
  2. The server asks the client for help with creating a compelling product description with keywords as context.
  3. The client produces such a description, and the server updates the product with a better description.

Many times, when playing games, you encounter characters in the game you want to have a conversation with; some of these characters are known as NPCs or non-player characters. Usually, these characters are limited in what they can say, as this is how they’re programmed. This limitation takes away from the gaming experience, and this is where an LLM can step in and do a better job. See the following flow for how this could work:

  1. The user asks to talk to a character.
  2. The server retrieves character information such as name, description, motive, clues, and so on, and sends it as a sample request.
  3. The client retrieves the character information from the prompt request and uses that as a system message to produce a nice conversation response.

Now that we understand more about suitable scenarios, let’s discuss what the actual messages look like, as it’s important to understand what is being sent back and forth. More importantly, it’s important to understand what information you can configure upon sending a sample request to a client.

If you’re using an SDK, you will almost never encounter a JSON-RPC, but what is interesting to know is what can be sent as part of a sampling request, so you know what type of guidance you can send to the client. Let’s have a look at the following message:

Request

{
"jsonrpc": "2.0",
"id": 1,
"method": "sampling/createMessage",
"params": {
"messages": [
{
"role": "user",
"content": {
"type": "text",
"text": "Write a compelling description of this product:
tomato, here's some keywords: red, vegetable, fresh"
}
}
],
"modelPreferences": {
"hints": [
{
"name": "claude-3-sonnet"
}
],
"intelligencePriority": 0.8,
"speedPriority": 0.5
},
"systemPrompt": "You're a professional writing assistant and
tend to want to write descriptions in a poetic way",
"maxTokens": 100
}
}

In the preceding message, the following are of special interest:

  • messages: Here’s where you’re sending the messages that get fed to the LLM.
  • modelPreferences: This property is just a preference for which model should ideally be used. The user is the one ultimately deciding, but this should be seen as a recommendation. Also, make note of other properties we can set, such as intelligencePriority and speedPriority.
  • systemPrompt: This is an important one, as this is the personality of the LLM and can greatly affect the outcome of the message.
  • maxTokens: This property decides how many tokens will be used for this task.

Now that we have had a good look at what the server is sending to the client, let’s look at what the client sends back:

Response

{
"jsonrpc": "2.0",
"id": 1,
"result": {
"role": "assistant",
"content": {
"type": "text",
"text": "The capital of France is Paris."
},
"model": "claude-3-sonnet-20240307",
"stopReason": "endTurn"
}
}

Here, we can see how the LLM response comes back in the content property, and it also lets us know which model was ultimately used, among other details.

Now, we’ve come to the extra exciting part of this chapter, namely, how to implement sampling.

We’ll cover the following parts of the implementation:

  • Server side: How to add this to the MCP server
  • Client side: How to enable it and what the code looks like, both to receive a request and send a response

To implement sampling on the server side, we need to consider when the sampling request should take place. Usually, a sampling request doesn’t happen out of nowhere, but it happens in the context of an action. Imagine the following scenario. A user working in the back office of an e-commerce site adds new products for sale. They need help with the description, and it should be as compelling as possible. For the description, they will therefore use the help of a client and its LLM. Here’s how it will play out:

  1. The user’s client calls a tool on the server that asks to create a new product.
  2. The server’s tool then dispatches a sample request with instructions on what to do, which is a prompt.
  3. The client then takes said prompt from the sample request, calls their LLM, and returns the answer:
    from mcp.server.fastmcp import Context, FastMCP
    from mcp.server.session import ServerSession
    from mcp.types import SamplingMessage, TextContent
    from uuid import uuid4
    mcp = FastMCP(name="Sampling Example")
    products = []
    @mcp.tool()
    async def create_product(product_name: str, keywords: str,
    ctx: Context[ServerSession, None]) -> str:
    """Create a product and generate a product
    description using LLM sampling."""
    # 1. A new product is being created
    product = { "id": uuid4(), "name": product_name, "description": "" }
    prompt = f"Create a product description about {keywords}"
    # 2. Creates a sampling message and passes the prompt as the payload
    result = await ctx.session.create_message(
    messages=[
    SamplingMessage(
    role="user",
    content=TextContent(type="text", text=prompt),
    )
    ],
    max_tokens=100,
    )
    product["description"] = result.content.text
    products.append(product)
    # return the complete product
    return product

In steps 1 and 2 in the preceding code, note the use of the ctx (context) object, calling session.create_message, and passing in SamplingMessage, which has a user value, and messages being populated with the prompt you’re sending to the client:

result = await ctx.session.create_message(
messages=[
SamplingMessage(
role="user",
content=TextContent(type="text", text=prompt),
)
],
max_tokens=100,
)
if __name__ == "__main__":
print("Starting server…")
mcp.run()

Also, take note of the fact that we’re waiting for the client here to come back to us before we return. Once the client’s message comes back, we assign the result to the product description and, finally, return the product:

product["description"] = result.content.text
products.append(product)
# return the complete product
return product

Let’s test this out in VS Code. Ensure you do the following:

  1. Create a server entry in mcp.json like so:
    "sample-server": {
    "command": "python",
    "args": ["path/to/server/sample-server.py"]
    }

Make sure the server is running by clicking the Start Server link at the top of the server entry.

  1. You also need to select which models are allowed to be used with sampling. To make the selection, open the Extension view and notice the MCP Servers – installed section at the bottom. Click the gear icon and Configure Model Access for the installed server, and select the allowed models for sampling, such as Claude Sonnet.
  2. Open the GitHub Copilot Chat window in VS Code and ensure the Agent mode is selected in the chat (select the icon for it at the top or run the Chat: Open Chat command in the command palette). Now, type the following prompt:
    "create product called tomato with keywords red and vegetable and delicious"

You should see a dialog asking for your permission to run that, once allowed, produces a tooling response from create_product. Here’s what happened under the hood:

  1. The prompt was parsed. Here’s what was sent to the tool:
    {
    "keywords": "red, vegetable, delicious",
    "product_name": "tomato"
    }
  2. The create_product tool was invoked.
  3. The sample request was sent to the client. Because the client in VS Code has its own LLM, it produces a response to the sample request like so:

Figure 9.2 – Sampling in VS Code

Let’s have a look at the generated description:

Introducing our **Red Garden Medley**—a vibrant selection of the freshest, most delicious red vegetables nature has to offer! Each hand-picked assortment features juicy tomatoes, crisp red bell peppers, and sweet red radishes, bursting with flavor and color. Perfect for salads, roasting, or snacking, these vegetables not only brighten your plate but also deliver a powerhouse of vitamins and antioxidants. Enjoy the taste of freshness with every bite—delicious, nutritious, and naturally red!

Wouldn’t you buy that tomato?:)

Okay, that’s great. We got sampling to work on an MCP server, and VS Code was acting as a client, ensuring that it worked. How do we actually build a client for this in a scenario where we want to integrate this into a real solution? That’s a great question and something we will cover in the next section.

First off, you need to let the server know that you support sampling as a feature. To do that, you need to pass the configuration when creating the client instance, like so:

{
"capabilities": {
"sampling": {}
}
}

Okay, what do we need to know? For one, sampling is outside of your normal flow of calling tools, resources, and prompts. What does that mean, you wonder. Well, let’s see how we listen for incoming sampling requests:

async def run():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write,
sampling_callback=handle_sampling_message) as session:
await session.initialize()
# call tools, resource and prompts and read responses

This code shows how we normally connect to an MCP server and initialize the process so we can later call tools or whatever we want to do. There’s a difference, though: note sampling_callback=handle_sampling_message. This is important as this allows us to listen for incoming messages.

Let’s look at handle_sampling_message next:

async def call_llm(prompt: str, system_prompt: str) -> str:
client = OpenAI(
base_url="https://models.github.ai/inference",
api_key=os.environ["GITHUB_TOKEN"],
)
response = client.chat.completions.create(
messages=[
{
"role": "system",
"content": system_prompt,
},
{
"role": "user",
"content": prompt,
}
],
model="openai/gpt-4o-mini",
temperature=1,
max_tokens=200,
top_p=1
)
return response.choices[0].message.content
async def handle_sampling_message(
context: RequestContext[ClientSession, None], params:
types.CreateMessageRequestParams
) -> types.CreateMessageResult:
print(f"Sampling request: {params.messages}")
# 1. parse out the incoming prompt
message = params.messages[0].content.text
# 2. call the llm to get a response on our prompt query
response = await call_llm(message, "You're a helpful assistant,
keep to the topic, don't make things up too much but
definitely create a compelling product description")
# 3. create the sample response
return types.CreateMessageResult(
role="assistant",
content=types.TextContent(
type="text",
text=response,
),
model="gpt-3.5-turbo",
stopReason="endTurn",
)

There are three things in the preceding code we should make a note of:

  • In step 1, here’s how we parse out the incoming product message (our assignment, if you will). This is what we will send to the LLM to get a response from. In this case, our response should be a product description.
  • In step 2, we call the LLM to get a response.
  • Lastly, we construct a sample response that gets sent back to the MCP server.

A helper function calls GitHub Models with a prompt and a system message, and parses out the LLM response.

That’s it, if you test running the client at this point: https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter09/code/python/README.md

You should see a response similar to the following:

[08/16/25 19:31:40] INFO Processing request of type CallToolRequest server.py:624
Sampling request: [SamplingMessage(role='user', content=TextContent(type='text', text='Create a product description about paprika described by as red, juicy, vegetable', annotations=None, meta=None))]
[08/16/25 19:31:43] INFO Processing request of type ListToolsRequest server.py:624
result: {"id": 1, "name": "paprika", "description": "**Product Description: Paprika \u2013 The Vibrant Touch of Flavor**\n\nElevate your culinary creations with our premium Paprika, a stunning red spice derived from the most luscious, juicy peppers. This vibrant addition is more than just a seasoning; it\u2019s a burst of color and taste that brings warmth and depth to every dish.\n\nOur Paprika is sourced from high-quality, sun-ripened vegetables, meticulously harvested at their peak to ensure maximum flavor. With its rich, sweet notes and subtle smokiness, this natural spice delivers a delightful punch that enhances everything from savory stews and roasted meats to vibrant vegetable dishes and sauces.\n\nNot only is our Paprika a feast for the eyes with its brilliant red hue, but it's also packed with antioxidants and vitamins, making it a nutritious choice for health-conscious cooks. Whether you sprinkle it onto a beloved family recipe or use it to create something intentionally new, our Paprika is versatile enough to brighten any meal.\n\nTransform everyday cooking into an extraordinary experience with the irresistible"}
INFO Processing request of type CallToolRequest server.py:624
result: {
"id": 1,
"name": "paprika",
"description": "**Product Description: Paprika – The Vibrant Touch of Flavor**\n\nElevate your culinary creations with our premium Paprika, a stunning red spice derived from the most luscious, juicy peppers. This vibrant addition is more than just a seasoning; it's a burst of color and taste that brings warmth and depth to every dish.\n\nOur Paprika is sourced from high-quality, sun-ripened vegetables, meticulously harvested at their peak to ensure maximum flavor. With its rich, sweet notes and subtle smokiness, this natural spice delivers a delightful punch that enhances everything from savory stews and roasted meats to vibrant vegetable dishes and sauces.\n\nNot only is our Paprika a feast for the eyes with its brilliant red hue, but it's also packed with antioxidants and vitamins, making it a nutritious choice for health-conscious cooks. Whether you sprinkle it onto a beloved family recipe or use it to create something intentionally new, our Paprika is versatile enough to brighten any meal.\n\nTransform everyday cooking into an extraordinary experience with the irresistible"
}

The client does two things:

  • It calls the create_product tool with a product name and keyword, and it ends up producing a product with an LLM-generated description like so:
    Product Description: Paprika – The Vibrant Touch of Flavor**\n\nElevate your culinary creations with our premium Paprika, a stunning red spice derived from the most luscious, juicy peppers. This vibrant addition is more than just a seasoning; it's a burst of color and taste that brings warmth and depth to every dish.\n\nOur Paprika is sourced from high-quality, sun-ripened vegetables, meticulously harvested at their peak to ensure maximum flavor. With its rich, sweet notes and subtle smokiness, this natural spice delivers a delightful punch that enhances everything from savory stews and roasted meats to vibrant vegetable dishes and sauces.\n\nNot only is our Paprika a feast for the eyes with its brilliant red hue, but it's also packed with antioxidants and vitamins, making it a nutritious choice for health-conscious cooks. Whether you sprinkle it onto a beloved family recipe or use it to create something intentionally new, our Paprika is versatile enough to brighten any meal.\n\nTransform everyday cooking into an extraordinary experience with the irresistible

Doesn’t that sound like paprika you would buy? Imagine sending this to an LLM and asking it to generate a photo (optional homework). What an image that would be.

  • It calls the get_products tool, which lists the newly added product.

As you can see, this is a great way to delegate tasks to the client that it’s better equipped to handle.

The idea with the meaning of the word sampling is to analyze a small sample. In the context of MCP, this is about delegation and how the server delegates part of its work to the client.

A scenario is usually started by a user, such as authoring a blog post or wanting to create a product in a back office solution. The server ends up creating a sampling request and sends that to the client as part of a task it needs help with. The client is then able to respond to said request using an LLM response.

It should also be stated that the sample request contains recommendations on model, token usage, system prompt, and much more, and that it should involve a human who either accepts these recommendations or changes them to their liking.

This is a great functionality, where an LLM on the client can be called in to help.

In our next chapter, we’ll dive into yet another powerful feature of MCP, namely, elicitation, which is about improving the user experience by setting up a flow where the user is asked to pick another choice or provide more information to help the server do its job better.

In this assignment, we’ll take all our knowledge of adding sampling implementations to the client and server and apply it to a fun area, namely, a mystery game, and the conversational part. The idea is to create a character that’s interesting to talk to over pre-programmed responses.

Here’s how it should work:

  • User: Talk to character N
  • Server: Retrieve character info
  • Server: Send sampling request with character info
  • Client: Receive sampling request and produce a response using the LLM
  • Server: Store response for caching and logging

To help you, imagine that a character is defined in a JSON file like so:

[
{
"id": "1",
"name": "Monsieur Lestrange",
"description": "a 600 year old vampire",
"personality": "very polite and will tell you a great deal of what
it's like paying the electricity bill of a 1200 year old castle
with bad insulation. In fact, he's quite boring and would rather
talk about that over what you would expect like vampire hunters,
stakes etc"
}
]

You can access the solution at https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter09/solution/README.md.

What’s the reason for using sampling?

  • A: You want to sample a smaller piece of information from a large dataset
  • B: The server needs help with a generative AI-type task, and the client can use its LLM to generate a response
  • C: The client needs the server’s help with a task

What party initiates the sampling request?

  • A: Either of them
  • B: The client
  • C: The server

You can access the solution at https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter09/solution/solution-quiz.md.