-
Notifications
You must be signed in to change notification settings - Fork 2k
Add support for Elicitation #625
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
6597f30
Elicitation
dsp-ant 40470d6
add elicitation test using create_client_server_memory_streams
ihrpr 427a634
field rename
ihrpr 3a2d915
adjust types after the spec revision
ihrpr a75afd4
add ElicitationResult to fastMCP
ihrpr 4603e89
add readme
ihrpr 653c057
add validation for primitive types
ihrpr d4ae036
cleanup
ihrpr 67bfd9a
format
ihrpr 51b5ee8
Update
dsp-ant File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -31,6 +31,8 @@ | |
- [Images](#images) | ||
- [Context](#context) | ||
- [Completions](#completions) | ||
- [Elicitation](#elicitation) | ||
- [Authentication](#authentication) | ||
- [Running Your Server](#running-your-server) | ||
- [Development Mode](#development-mode) | ||
- [Claude Desktop Integration](#claude-desktop-integration) | ||
|
@@ -74,7 +76,7 @@ The Model Context Protocol allows applications to provide context for LLMs in a | |
|
||
### Adding MCP to your python project | ||
|
||
We recommend using [uv](https://docs.astral.sh/uv/) to manage your Python projects. | ||
We recommend using [uv](https://docs.astral.sh/uv/) to manage your Python projects. | ||
|
||
If you haven't created a uv-managed project yet, create one: | ||
|
||
|
@@ -372,6 +374,50 @@ async def handle_completion( | |
return Completion(values=filtered) | ||
return None | ||
``` | ||
### Elicitation | ||
|
||
Request additional information from users during tool execution: | ||
|
||
```python | ||
from mcp.server.fastmcp import FastMCP, Context | ||
from mcp.server.elicitation import ( | ||
AcceptedElicitation, | ||
DeclinedElicitation, | ||
CancelledElicitation, | ||
) | ||
from pydantic import BaseModel, Field | ||
|
||
mcp = FastMCP("Booking System") | ||
|
||
|
||
@mcp.tool() | ||
async def book_table(date: str, party_size: int, ctx: Context) -> str: | ||
"""Book a table with confirmation""" | ||
|
||
# Schema must only contain primitive types (str, int, float, bool) | ||
class ConfirmBooking(BaseModel): | ||
confirm: bool = Field(description="Confirm booking?") | ||
notes: str = Field(default="", description="Special requests") | ||
|
||
result = await ctx.elicit( | ||
message=f"Confirm booking for {party_size} on {date}?", schema=ConfirmBooking | ||
) | ||
|
||
match result: | ||
case AcceptedElicitation(data=data): | ||
if data.confirm: | ||
return f"Booked! Notes: {data.notes or 'None'}" | ||
return "Booking cancelled" | ||
case DeclinedElicitation(): | ||
return "Booking declined" | ||
case CancelledElicitation(): | ||
return "Booking cancelled" | ||
``` | ||
|
||
The `elicit()` method returns an `ElicitationResult` with: | ||
- `action`: "accept", "decline", or "cancel" | ||
- `data`: The validated response (only when accepted) | ||
- `validation_error`: Any validation error message | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think this should just bubble. |
||
|
||
### Authentication | ||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
"""Elicitation utilities for MCP servers.""" | ||
|
||
from __future__ import annotations | ||
|
||
import types | ||
from typing import Generic, Literal, TypeVar, Union, get_args, get_origin | ||
|
||
from pydantic import BaseModel | ||
from pydantic.fields import FieldInfo | ||
|
||
from mcp.server.session import ServerSession | ||
from mcp.types import RequestId | ||
|
||
ElicitSchemaModelT = TypeVar("ElicitSchemaModelT", bound=BaseModel) | ||
|
||
|
||
class AcceptedElicitation(BaseModel, Generic[ElicitSchemaModelT]): | ||
"""Result when user accepts the elicitation.""" | ||
|
||
action: Literal["accept"] = "accept" | ||
data: ElicitSchemaModelT | ||
|
||
|
||
class DeclinedElicitation(BaseModel): | ||
"""Result when user declines the elicitation.""" | ||
|
||
action: Literal["decline"] = "decline" | ||
|
||
|
||
class CancelledElicitation(BaseModel): | ||
"""Result when user cancels the elicitation.""" | ||
|
||
action: Literal["cancel"] = "cancel" | ||
|
||
|
||
ElicitationResult = AcceptedElicitation[ElicitSchemaModelT] | DeclinedElicitation | CancelledElicitation | ||
|
||
|
||
# Primitive types allowed in elicitation schemas | ||
_ELICITATION_PRIMITIVE_TYPES = (str, int, float, bool) | ||
|
||
|
||
def _validate_elicitation_schema(schema: type[BaseModel]) -> None: | ||
"""Validate that a Pydantic model only contains primitive field types.""" | ||
for field_name, field_info in schema.model_fields.items(): | ||
if not _is_primitive_field(field_info): | ||
raise TypeError( | ||
f"Elicitation schema field '{field_name}' must be a primitive type " | ||
f"{_ELICITATION_PRIMITIVE_TYPES} or Optional of these types. " | ||
f"Complex types like lists, dicts, or nested models are not allowed." | ||
) | ||
|
||
|
||
def _is_primitive_field(field_info: FieldInfo) -> bool: | ||
"""Check if a field is a primitive type allowed in elicitation schemas.""" | ||
annotation = field_info.annotation | ||
|
||
# Handle None type | ||
if annotation is types.NoneType: | ||
return True | ||
|
||
# Handle basic primitive types | ||
if annotation in _ELICITATION_PRIMITIVE_TYPES: | ||
return True | ||
|
||
# Handle Union types | ||
origin = get_origin(annotation) | ||
if origin is Union or origin is types.UnionType: | ||
args = get_args(annotation) | ||
# All args must be primitive types or None | ||
return all(arg is types.NoneType or arg in _ELICITATION_PRIMITIVE_TYPES for arg in args) | ||
|
||
return False | ||
|
||
|
||
async def elicit_with_validation( | ||
session: ServerSession, | ||
message: str, | ||
schema: type[ElicitSchemaModelT], | ||
related_request_id: RequestId | None = None, | ||
) -> ElicitationResult[ElicitSchemaModelT]: | ||
"""Elicit information from the client/user with schema validation. | ||
|
||
This method can be used to interactively ask for additional information from the | ||
client within a tool's execution. The client might display the message to the | ||
user and collect a response according to the provided schema. Or in case a | ||
client is an agent, it might decide how to handle the elicitation -- either by asking | ||
the user or automatically generating a response. | ||
""" | ||
# Validate that schema only contains primitive types and fail loudly if not | ||
_validate_elicitation_schema(schema) | ||
|
||
json_schema = schema.model_json_schema() | ||
|
||
result = await session.elicit( | ||
message=message, | ||
requestedSchema=json_schema, | ||
related_request_id=related_request_id, | ||
) | ||
|
||
if result.action == "accept" and result.content: | ||
# Validate and parse the content using the schema | ||
validated_data = schema.model_validate(result.content) | ||
return AcceptedElicitation(data=validated_data) | ||
elif result.action == "decline": | ||
return DeclinedElicitation() | ||
elif result.action == "cancel": | ||
return CancelledElicitation() | ||
else: | ||
# This should never happen, but handle it just in case | ||
raise ValueError(f"Unexpected elicitation action: {result.action}") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it gives us a better API and user experience if
ctx.elicit(schema=SchemaT)
always return an instance ofSchemaT
, or an exception.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
My comment implies that an exception would be raised if user rejects.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
then the problem will be how to distinguish between cancel and reject?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Wouldn't this imply that we use exceptions for control flow? We should reserve exceptions for handling exceptional circumstances. I don't think decline fits into this.
I do prefer having a return value that indicates if it was accepted,declined,etc.