Skip to content
ImagineWorld

Elicitation

node_idnode-book_learn-model-context-protocol-with-python_chapter-10-elicitation
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num10
chapter_titleElicitation
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Elicitation means the process of getting or producing something, especially information or a reaction.

Why does that matter for MCP then? The official docs have the following to say:

The Model Context Protocol (MCP) provides a standardized way for servers to request additional information from users through the client during interactions. This flow allows clients to maintain control over user interactions and data sharing while enabling servers to gather necessary information dynamically.

So, what does that mean? It means, for some reason, the server finds it needs to involve the client additionally to ask the user for more information. Now the purpose is clearer, right?

Okay, imagine the following: as a user, you’re trying to book a holiday trip, and the date you searched for isn’t available. There’s a way to improve that situation through using elicitation – namely, instead of just saying as a server that said trip isn’t available, you make an effort to ask additional questions and perhaps suggest dates around this date that are available. Now you’ll see, hopefully, how this could be a very useful technique in lots of contexts, to increase the chance of something being sold or booked, and so on.

In this chapter, we’ll learn how to do the following:

  • Explain what elicitation is
  • Learn when to use it
  • Build an elicitation integration

The chapter covers the following topics:

  • Why elicitation?
  • Implementing elicitation
  • Elicitation flow
  • JSON-RPC messages
  • Implementing the server-side functionality
  • Testing elicitation with VS Code

Okay, we’ve already tried describing, at the beginning of this chapter, what situations might motivate the use of elicitation in MCP, but let’s try to summarize some main motivating factors:

  • Task complexity: For some tasks, it’s simply not possible to provide all the information needed up front. This might be scenarios where the user needs to make selections through a workflow. For example, the user might need to make multiple choices as they purchase a ticket to the movies. They start with wanting to book a certain film on a given day, but then need to be asked whether they need a premium seat or other customizations available. Or, take a scenario such as booking a train ticket, where you need to make choices such as a ticket with a numbered seat, whether the ticket is physical or an e-ticket, and so on. You could ask for all this information up front, but it might make for a tedious user experience, and it might be better to start off asking for less input.
  • Increase the conversion rate on a website: Another angle is for companies to ensure they have a better conversion rate, meaning that more users on the website become actual customers. For example, if a user wants a red sweater and you don’t have it in stock at the moment, then you might want to ask the user if they’re okay with a different color or want to sign up on a waitlist to order it automatically when it comes in. This type of behavior is more likely to improve your sales as a company.
  • Improved user experience: As a logical conclusion of the preceding angle, the overall user experience is likely to improve if the user can be met with something else than just a no, and instead be faced with reasonable choices.

All in all, elicitation can be a great way to improve your app. Let’s try to look at the implementation side of things next.

So, we want to use elicitation – great. But first, there’s a set of guidelines we should know about. Here’s what the official docs have to say:

For trust, safety, and security:

  • Servers must not use elicitation to request sensitive information

Applications should:

  • Provide a UI that makes it clear which server is requesting information
  • Allow users to review and modify their responses before sending
  • Respect user privacy and provide clear decline and cancel options

In general, what happens during elicitation is that the server decides it doesn’t have enough information to complete a call to a tool, resource, or prompt.

What’s important to understand is that this happens as a two-step process:

  1. The server asks the client if it’s okay to initiate an elicitation request towards the user.
  2. The client asks the user to submit information.

The user can both accept or decline in both 1) and 2); see the following sequence diagram explaining this process. To hopefully make it easier to understand, we’ve chosen a trip-booking process:

Figure 10.1 – JSON-RPC messages

Figure 10.1 – JSON-RPC messages

Now that we’ve explained the overall flow, let’s see what the JSON-RPC messages look like.

Like with most MCP features, there are specific messages in JSON-RPC that need to be sent and received:

Request message

{
"jsonrpc": "2.0",
"id": 1,
"method": "elicitation/create",
"params": {
"message": "Please provide your GitHub username",
"requestedSchema": {
"type": "object",
"properties": {
"name": {
"type": "string"
}
},
"required": ["name"]
}
}
}

In the preceding message, we can see how message contains the payload for what we’re asking for – a user choice to be made or some explanation of what we’re asking for. requestedSchema is a schema that defines what information you need as a server, so here it’s important you specify both the name of what you need, its type, and any other rules you want to impose. See this example schema, where the server asks for name, email, and age. For each parameter, we specify both type and description, and in some places, we specify format and even validation rules, such as you should be at least 18 years of age:

"requestedSchema": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Your full name"
},
"email": {
"type": "string",
"format": "email",
"description": "Your email address"
},
"age": {
"type": "number",
"minimum": 18,
"description": "Your age"
}
},
"required": ["name", "email"]
}

Let’s have a look at a response. Specifically, this is an accept -type response where the user has agreed to submit the information requested of them.

Response message

{
"jsonrpc": "2.0",
"id": 2,
"result": {
"action": "accept",
"content": {
"name": "Monalisa Octocat",
"email": "[email protected]",
"age": 30
}
}
}

It’s actually possible for the user to say, “I don’t want to provide this information”. If that happens, then a reject type message is sent as a response instead, and looks like so:

Reject message

{
"sonrpc": "2.0",
"id": 2,
"result": {
"action": "decline"
}
}

Here, it’s clear that the user declines to submit the requested information.

A third type of response is cancellation. It’s very similar to decline, but it’s more like the user dismisses the elicitation dialog by typing Escape, clicking to close a dialog, so it’s more like the user ignores interacting, rather than saying an explicit No.

We’ve mentioned the general request schema and an example. However, there are quite a few supported types, and it’s important to know they exist so you use them correctly. These types are presented to the user as part of the elicitation process, and it means the user either uses a drop list, a text input field, or some other UI element to provide the information.

  • string: This one is about asking for a string. You can add quite a few checks. Here’s what the schema looks like:
    {
    "type": "string",
    "title": "Display Name",
    "description": "Description text",
    "minLength": 3,
    "maxLength": 50,
    "pattern": "^[A-Za-z]+$",
    "format": "email"
    }

Here, you can see that you can limit both minLength and maxLength and even set patterns, which can be highly useful in case you’re asking for a specific allowed structure, such as an address, telephone number, social security number, and so on.

  • number: This one is slightly less complex, but by setting a minimum and maximum value, it helps the user understand what’s allowed and not. See this schema:
    {
    "type": "number", // or "integer"
    "title": "Display Name",
    "description": "Description text",
    "minimum": 0,
    "maximum": 100
    }

See the minimum and maximum values, which you can specify.

  • boolean: For this type, the idea is to get the user to answer yes or no. You can also specify whether there should be a default value:
    {
    "type": "boolean",
    "title": "Display Name",
    "description": "Description text",
    "default": false
    }
  • enum: This one should be thought of as a list of options, which can be useful if you want the user to choose between trips on different dates, for example:
    {
    "type": "string",
    "title": "Display Name",
    "description": "Description text",
    "enum": ["option1", "option2", "option3"],
    "enumNames": ["Option 1", "Option 2", "Option 3"]
    }

With that in mind, let’s see if we can use several of these types, as we will show the implementation parts in the next section.

Implementing the server-side functionality

Section titled “Implementing the server-side functionality”

Let’s start with the server. What we need to know is that a server feature, tool, resource, or prompt should run its course, and if it detects that more information is needed, it should produce an elicitation message.

First, let’s see how we produce such a message. First, we have an if that checks whether a message should be produced. If so, we call elicit on the context object while providing a message and a schema to abide by:

class BookingPreferences(BaseModel):
"""Schema for collecting user preferences."""
checkAlternative: bool = Field(description="Would you like
to check another date?")
alternativeDate: str = Field(
default="2024-12-26",
description="Alternative date (YYYY-MM-DD)",
)
def is_available_date -> bool:
pass
@mcp.tool()
def book_table(date: str,ctx: Context[ServerSession, None]) -> str:
# 1. Check if data is available
if not is_available_date(date):
result = await ctx.elicit(
message=(f"No trips available on {date}. Would you
like to try another date?"),
schema=BookingPreferences,
)

Then there should be a check to see what the user and the client responded with:

if result.action == "accept" and result.data:
if result.data.checkAlternative:
return f"[SUCCESS] Booked for {result.data.alternativeDate}"
return "[CANCELLED] No booking made"
return "[CANCELLED] Booking cancelled"

Here, you can see how we investigate the action property to see if the user accepted the primary action and submitted additional data. If so, we start parsing out what was selected. If it wasn’t accepted, then we respond with a cancellation message.

Now, let’s see it all together:

from pydantic import BaseModel, Field
from mcp.server.fastmcp import Context, FastMCP
from mcp.server.session import ServerSession
mcp = FastMCP(name="Elicitation Example")
class BookingPreferences(BaseModel):
"""Schema for collecting user preferences."""
checkAlternative: bool = Field(description="Would you like
to check another date?")
alternativeDate: str = Field(
default="2024-12-26",
description="Alternative date (YYYY-MM-DD)",
)
@mcp.tool()
async def book_trip(date: str, ctx: Context[ServerSession, None]) -> str:
"""Book a trip with date availability check."""
# Check if date is available
if not is_available_date(date):
# Date unavailable – ask user for alternative
result = await ctx.elicit(
message=(f"No trips available on {date}. Would you
like to try another date?"),
schema=BookingPreferences,
)
if result.action == "accept" and result.data:
if result.data.checkAlternative:
return f"[SUCCESS] Booked for
{result.data.alternativeDate}"
return "[CANCELLED] No booking made"
return "[CANCELLED] Booking cancelled"
# Date available
return f"[SUCCESS] Booked for {date}"

Now, let’s move on to testing elicitation features with VS Code.

To test elicitation features with VS Code, you will need to add the MCP server as an entry to the mcp.json file like so:

"server": {
"type": "sse",
"url": "http://localhost:8000/sse"
}

Then, ensure you’re in Agent mode before you type the following prompt:

Book trip on 2025-02-01

You should see the following play out in the user interface:

  1. Typing a prompt and tool invocation: Here, you type your request to book a trip, and the system recognizes it as a tool invocation. You need to approve the tool invocation for it to proceed:

Figure 10.2 – Typing a prompt and seeing a tool invocation

Figure 10.2 – Typing a prompt and seeing a tool invocation

  1. Approving the tool invocation: Once you approve the tool invocation, you should see the interface telling you the selected data is busy, and you’ll be asked to respond, meaning now it will take you into crafting an elicitation response:

Figure 10.3 – Approving the tool invocation

Figure 10.3 – Approving the tool invocation

  1. Crafting an elicitation response: Now you will need to craft a response based on the user’s input and the system’s requirements. This involves using the elicitation schema you defined earlier to gather any additional information needed. Here’s how that looks in the user interface. In the following screenshot, you’re asked whether you want to respond or not. If you choose true, it will continue to ask you for another date; if not, it will stop the elicitation process:

Figure 10.4 – Crafting an elicitation response

Figure 10.4 – Crafting an elicitation response

  1. Responding to the elicitation: Once you’ve selected to continue, you need to fill in the alternate date like so:

Figure 10.5 – Responding to the elicitation

Figure 10.5 – Responding to the elicitation

  1. The final result: Because you’ve now submitted an alternative date, the server will check to see if this response is okay. In the following screenshot, you can see that that’s the case and you receive a confirmation for your booking:

Figure 10.6 – The final result

Figure 10.6 – The final result

That completes elicitation on the server side.

Great – now we have a good understanding of the server side of things, and even how to test it with VS Code. Let’s proceed to implement the client side.

Normally, when writing a client, you deal with a ClientSession object. This allows you to manage the connection to the server. In addition to read_stream and write_stream, you can also pass elicitation_callback to handle any elicitation events:

async with ClientSession(
read_stream,
write_stream,
elicitation_callback=elicitation_callback_handler) as session:

Let’s have a look at elicitation_callback_handler:

async def elicitation_callback_handler(context:
RequestContext[ClientSession, None], params: ElicitRequestParams):
print(f"[CLIENT] Received elicitation data: {params.message}")

As you can see, this handler takes two parameters: the request context and the elicitation request parameters. What we need to do at this point is to create a client response that gets sent back to the server. There are three possible responses you can send back to the server:

  • accept: This means we want the elicitation process to continue. If we give such a response, we should also conform to the input schema set out by the server. For example, the following answer would conform:
    return ElicitResult(action="accept", content={
    "checkAlternative": True,
    "alternativeDate": "2025-01-01"
    }) # should book 1 jan instead of initial 2nd Jan

Here, you see how we first set the action property to accept and set content to a payload, with the schema taking checkAlternative and alternativeDate. Note also how we hardcode the response. In a more production-like app, the value assigned to alternativeDate should come as the result of asking the user for input.

  • decline: This means we want to stop the elicitation process. We can send a response like this:
    return ElicitResult(action="decline")

Here, we don’t set content at all, which makes it clear that we are not providing any additional information or context for the decline. This decline response happens very early on in the process. This could be likened to a user simply saying no without providing further details.

  • accept: The user accepts to respond but then declines to provide an alternative date:
    # 1. refuses no select other date
    return ElicitResult(action="accept", content={
    "checkAlternative": False
    }) # should say no booking made, WORKS -->

This decline happens a bit later in the process, after the user has been presented with the option to select an alternative date.

Let’s try to show it all in this sequence diagram:

Figure 10.7 – Flow for implementing elicitation in the client in Python

Figure 10.7 – Flow for implementing elicitation in the client in Python

As you can see, generally, there are a few permutations to keep track of where the user can cancel at different stages, but the key is to ensure that the client is able to handle these different scenarios gracefully.

In this chapter, we’ve covered the elicitation process in detail, including how it is initiated and the different scenarios in which it can occur. We’ve also explored the various responses that can be sent back to the server during this process. Elicitation is when the system actively seeks to gather more information from the user in order to fulfill a request or clarify intent.

We’ve also seen how the user can accept as well as abort at different stages of the process.

Finally, elicitation can be a powerful tool for improving user interactions and ensuring that the system is able to meet user needs effectively.

In the next chapter, we’ll explore how to secure your MCP server and client using various authentication methods such as Basic Auth, JWT, and OAuth2.1.

So far, you’ve seen code that handles a booking scenario. Now your task is to implement a scenario where the user finishes a booking process but is asked whether they want to be a member or not to receive a discount for future bookings. Use the code at https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter10/code/README.md.

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

An elicitation process is technically initiated when:

  • A: The server determines that it needs more information from the user to complete a request.
  • B: The user provides input that requires further clarification or details.
  • C: The system needs to confirm user intent before proceeding.

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