Spaces:
Sleeping
Sleeping
Jeremiah Lowin commited on
Commit ·
815bac1
1
Parent(s): 1f71f65
Provide a response type to client
Browse filesFiles changed (10)
- CLAUDE.md+6-1
- docs/clients/elicitation.mdxAdded+119
- docs/docs.json+1
- docs/servers/context.mdx+111
- src/fastmcp/client/elicitation.py+21-7
- src/fastmcp/server/context.py+4-4
- src/fastmcp/server/elicitation.py+34-2
- src/fastmcp/utilities/json_schema_type.py+9-7
- tests/client/test_elicitation.py+133-192
- tests/utilities/test_json_schema_type.py+85-1
1234528 unmodified lines34353637# FastMCP Development Guidelines## Testing and Investigation### In-Memory Transport - Always Preferred28 unmodified lines- You must always run pre-commit if you open a PR, because it is run as part of a required check.- When opening PRs, apply labels appropriately for bugs/breaking changes/enhancements/features. Generally, improvements are enhancements (not features) unless told otherwise.- NEVER modify files in docs/python-sdk/**, as they are auto-generated.- Use # type: ignore[attr-defined] in unit tests when accessing an MCP result of indeterminate type instead of asserting its type1234567891028 unmodified lines39404142# FastMCP Development Guidelines## Documentation- Documentation uses the Mintlify framework- Files must be present in docs.json to be included in the documentation## Testing and Investigation### In-Memory Transport - Always Preferred28 unmodified lines- You must always run pre-commit if you open a PR, because it is run as part of a required check.- When opening PRs, apply labels appropriately for bugs/breaking changes/enhancements/features. Generally, improvements are enhancements (not features) unless told otherwise.- NEVER modify files in docs/python-sdk/**, as they are auto-generated.- Use # type: ignore[attr-defined] in unit tests when accessing an MCP result of indeterminate type instead of asserting its type
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119---title: User ElicitationsidebarTitle: Elicitationdescription: Handle server-initiated user input requests with structured schemas.icon: user-check---
import { VersionBadge } from "/snippets/version-badge.mdx";
<VersionBadge version="2.10.0" />
## What is Elicitation?
Elicitation allows MCP servers to request structured input from users during tool execution. Instead of requiring all inputs upfront, servers can interactively ask users for information as needed - like prompting for missing parameters, requesting clarification, or gathering additional context.
For example, a file management tool might ask "Which directory should I create?" or a data analysis tool might request "What date range should I analyze?"
## How FastMCP Makes Elicitation Easy
FastMCP's client provides a helpful abstraction layer that:
- **Converts JSON schemas to Python types**: The raw MCP protocol uses JSON schemas, but FastMCP automatically converts these to Python dataclasses- **Provides structured constructors**: Instead of manually building dictionaries that match the schema, you get dataclass constructors that ensure correct structure- **Handles type conversion**: FastMCP takes care of converting between JSON representations and Python objects- **Runtime introspection**: You can inspect the generated dataclass fields to understand the expected structure
When you implement an elicitation handler, FastMCP gives you a dataclass type that matches the server's schema, making it easy to create properly structured responses without having to manually parse JSON schemas.
## Elicitation Handler
Provide an `elicitation_handler` function when creating the client. FastMCP automatically converts the server's JSON schema into a Python dataclass type, making it easy to construct the response:
```pythonfrom fastmcp import Clientfrom fastmcp.client.elicitation import ElicitResult
async def elicitation_handler(message: str, response_type: type, params, context) -> ElicitResult: # Present the message to the user and collect input user_input = input(f"{message}: ") # Create response using the provided dataclass type # FastMCP converted the JSON schema to this Python type for you response_data = response_type(value=user_input) return ElicitResult(action="accept", content=response_data)
client = Client( "my_mcp_server.py", elicitation_handler=elicitation_handler,)```
### Handler Parameters
The elicitation handler receives four parameters:
<Card icon="code" title="Elicitation Handler Parameters"><ResponseField name="message" type="str"> The prompt message to display to the user</ResponseField>
<ResponseField name="response_type" type="type"> A Python dataclass type that FastMCP created from the server's JSON schema. Use this to construct your response with proper typing and IDE support.</ResponseField>
<ResponseField name="params" type="ElicitRequestParams"> The original MCP elicitation request parameters, including the raw JSON schema in `params.requestedSchema` if you need it</ResponseField>
<ResponseField name="context" type="RequestContext"> Request context containing metadata about the elicitation request</ResponseField></Card>
### Response Actions
The handler must return an `ElicitResult` object that includes both an action and (when accepted) the user's input:
<Card icon="code" title="ElicitResult Structure"><ResponseField name="action" type="Literal['accept', 'decline', 'cancel']"> How the user responded to the elicitation request</ResponseField>
<ResponseField name="content" type="dataclass instance | dict | None"> The user's input data (required for "accept", omitted for "decline"/"cancel")</ResponseField></Card>
**Action Types:**- **`accept`**: User provided valid input - include their data in the `content` field- **`decline`**: User chose not to provide the requested information - omit `content` - **`cancel`**: User cancelled the entire operation - omit `content`
## Basic Example
```pythonfrom fastmcp import Clientfrom fastmcp.client.elicitation import ElicitResult
async def basic_elicitation_handler(message: str, response_type: type, params, context) -> ElicitResult: print(f"Server asks: {message}") # Simple text input for demonstration user_response = input("Your response: ") if not user_response: return ElicitResult(action="decline") # Use the response_type dataclass to create a properly structured response # FastMCP handles the conversion from JSON schema to Python type return ElicitResult(action="accept", content=response_type(value=user_response))
client = Client( "my_mcp_server.py", elicitation_handler=basic_elicitation_handler)```
105 unmodified lines106107108109110111105 unmodified lines"group": "Advanced Features","icon": "stars","pages": ["clients/logging","clients/progress","clients/sampling",105 unmodified lines106107108109110111112105 unmodified lines"group": "Advanced Features","icon": "stars","pages": ["clients/elicitation","clients/logging","clients/progress","clients/sampling",
15 unmodified lines161718192021253 unmodified lines27527627727827928015 unmodified lines- **Progress Reporting**: Update the client on the progress of long-running operations- **Resource Access**: Read data from resources registered with the server- **LLM Sampling**: Request the client's LLM to generate text based on provided messages- **Request Information**: Access metadata about the current request- **Server Access**: When needed, access the underlying FastMCP server instance253 unmodified linesSee [Client Sampling](/clients/client#llm-sampling) for more details on how clients handle these requests.### Component Changes<VersionBadge version="2.9.1" />15 unmodified lines16171819202122253 unmodified lines27627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039115 unmodified lines- **Progress Reporting**: Update the client on the progress of long-running operations- **Resource Access**: Read data from resources registered with the server- **LLM Sampling**: Request the client's LLM to generate text based on provided messages- **User Elicitation**: Request structured input from users during tool execution- **Request Information**: Access metadata about the current request- **Server Access**: When needed, access the underlying FastMCP server instance253 unmodified linesSee [Client Sampling](/clients/client#llm-sampling) for more details on how clients handle these requests.### User Elicitation<VersionBadge version="2.10.0" />Request structured input from users during tool execution. This allows tools to interactively ask for missing parameters, clarification, or additional context as needed.```pythonfrom dataclasses import dataclass@dataclassclass UserInfo:name: strage: int@mcp.toolasync def collect_user_info(ctx: Context) -> str:"""Collect user information through interactive prompts."""# Request structured user informationresult = await ctx.elicit(message="Please provide your information",response_type=UserInfo)if result.action == "accept":user = result.datareturn f"Hello {user.name}, you are {user.age} years old"elif result.action == "decline":return "Information not provided"else: # cancelreturn "Operation cancelled"```**Method signature:**- **`ctx.elicit(message: str, response_type: type = str) -> ElicitationResult`**- `message`: The prompt message to display to the user- `response_type`: The Python type defining the expected response structure (dataclass, primitive type, etc.)- Returns an `ElicitationResult` with `action` ("accept", "decline", "cancel") and `data` (when accepted)**Supported Response Types:**- **Primitive types**: `str`, `int`, `float`, `bool`- **Literal types**: `Literal["option1", "option2"]` for constrained choices- **Enum types**: Python enums for predefined options- **Dataclass types**: Custom structured data with multiple fields```pythonfrom typing import Literalfrom enum import Enumclass Priority(Enum):LOW = "low"MEDIUM = "medium"HIGH = "high"@dataclassclass TaskInfo:title: strpriority: Priorityurgent: bool@mcp.toolasync def create_task(ctx: Context) -> str:"""Create a task with user-provided details."""# Multiple elicitation calls for different information# Simple string inputtitle_result = await ctx.elicit("What's the task title?", response_type=str)if title_result.action != "accept":return "Task creation cancelled"# Enum selectionpriority_result = await ctx.elicit("What's the priority?", response_type=Priority)if priority_result.action != "accept":return "Task creation cancelled"# Boolean choiceurgent_result = await ctx.elicit("Is this urgent?", response_type=bool)if urgent_result.action != "accept":return "Task creation cancelled"return f"Created task: {title_result.data} (Priority: {priority_result.data.value}, Urgent: {urgent_result.data})"```**Pattern Matching Support:**FastMCP provides typed result classes for pattern matching:```pythonfrom fastmcp.server.elicitation import (AcceptedElicitation,DeclinedElicitation,CancelledElicitation)@mcp.toolasync def pattern_example(ctx: Context) -> str:result = await ctx.elicit("Enter your name:", response_type=str)match result:case AcceptedElicitation(data=name):return f"Hello {name}!"case DeclinedElicitation():return "No name provided"case CancelledElicitation():return "Operation cancelled"```Elicitation requires the client to provide an elicitation handler. If the client doesn't support elicitation, the request will fail. See [Client Elicitation](/clients/elicitation) for details on implementing client-side handlers.### Component Changes<VersionBadge version="2.9.1" />
1234567891011121314151617181920212223243 unmodified lines282930313233343536373839from __future__ import annotationsfrom collections.abc import Awaitable, Callablefrom typing import Any, TypeAliasimport mcp.typesfrom mcp import ClientSessionfrom mcp.client.session import ElicitationFnTfrom mcp.shared.context import LifespanContextT, RequestContextfrom mcp.types import ElicitRequestParams, ElicitResult__all__ = ["ElicitRequestParams", "ElicitResult", "ElicitationHandler"]ElicitationHandler: TypeAlias = Callable[[str, # messagedict[str, Any], # requested_schemaRequestContext[ClientSession, LifespanContextT],],Awaitable[ElicitResult],]3 unmodified linesasync def _elicitation_handler(context: RequestContext[ClientSession, LifespanContextT],params: ElicitRequestParams,) -> ElicitResult | mcp.types.ErrorData:try:result = await elicitation_handler(params.message, params.requestedSchema, context)return resultexcept Exception as e:return mcp.types.ErrorData(code=mcp.types.INTERNAL_ERROR,12345678910111213141516171819202122232425262728293031323334353 unmodified lines394041424344454647484950515253from __future__ import annotationsfrom collections.abc import Awaitable, Callablefrom typing import Any, Generic, TypeAlias, TypeVarimport mcp.typesfrom mcp import ClientSessionfrom mcp.client.session import ElicitationFnTfrom mcp.shared.context import LifespanContextT, RequestContextfrom mcp.types import ElicitRequestParamsfrom mcp.types import ElicitResult as MCPElicitResultfrom pydantic_core import to_jsonable_pythonfrom fastmcp.utilities.json_schema_type import json_schema_to_type__all__ = ["ElicitRequestParams", "ElicitResult", "ElicitationHandler"]T = TypeVar("T")class ElicitResult(MCPElicitResult, Generic[T]):content: T | None = NoneElicitationHandler: TypeAlias = Callable[[str, # messagetype[T], # a class for creating a structured responseElicitRequestParams,RequestContext[ClientSession, LifespanContextT],],Awaitable[ElicitResult[T | dict[str, Any]]],]3 unmodified linesasync def _elicitation_handler(context: RequestContext[ClientSession, LifespanContextT],params: ElicitRequestParams,) -> MCPElicitResult | mcp.types.ErrorData:try:response_type = json_schema_to_type(params.requestedSchema)result = await elicitation_handler(params.message, response_type, params, context)content = to_jsonable_python(result.content)return MCPElicitResult(**result.model_dump() | {"content": content})except Exception as e:return mcp.types.ErrorData(code=mcp.types.INTERNAL_ERROR,
29 unmodified lines30313233343536302 unmodified lines3393403413423433443456 unmodified lines35235335435535635735835936036129 unmodified linesAcceptedElicitation,CancelledElicitation,DeclinedElicitation,PrimitiveElicitationType,get_elicitation_schema,)from fastmcp.server.server import FastMCP302 unmodified linesresponse_type = str # type: ignoreif response_type in {bool, int, float, str}:response_type = PrimitiveElicitationType[response_type] # type: ignorerequested_schema = get_elicitation_schema(response_type) # type: ignore6 unmodified linesif result.action == "accept" and result.content:type_adapter = get_cached_typeadapter(response_type)validated_data = cast(T | PrimitiveElicitationType[T],type_adapter.validate_python(result.content),)if isinstance(validated_data, PrimitiveElicitationType):return AcceptedElicitation[T](data=validated_data.value)else:return AcceptedElicitation[T](data=validated_data)29 unmodified lines30313233343536302 unmodified lines3393403413423433443456 unmodified lines35235335435535635735835936036129 unmodified linesAcceptedElicitation,CancelledElicitation,DeclinedElicitation,ScalarElicitationType,get_elicitation_schema,)from fastmcp.server.server import FastMCP302 unmodified linesresponse_type = str # type: ignoreif response_type in {bool, int, float, str}:response_type = ScalarElicitationType[response_type] # type: ignorerequested_schema = get_elicitation_schema(response_type) # type: ignore6 unmodified linesif result.action == "accept" and result.content:type_adapter = get_cached_typeadapter(response_type)validated_data = cast(T | ScalarElicitationType[T],type_adapter.validate_python(result.content),)if isinstance(validated_data, ScalarElicitationType):return AcceptedElicitation[T](data=validated_data.value)else:return AcceptedElicitation[T](data=validated_data)
17 unmodified lines1819202122232410 unmodified lines3536373839404120 unmodified lines62636465666730 unmodified lines989910010110210310410510610717 unmodified lines"CancelledElicitation","DeclinedElicitation","get_elicitation_schema","PrimitiveElicitationType",]logger = get_logger(__name__)10 unmodified lines@dataclassclass PrimitiveElicitationType(Generic[T]):value: T20 unmodified lines- Must be an object schema- Must only contain primitive field types (string, number, integer, boolean)- Must be flat (no nested objects or arrays of objects)- Only primitive types and their nullable variants are allowedArgs:30 unmodified lineselif prop_schema.get("nullable", False):continue # Nullable with no other type is fine# Handle union types (oneOf/anyOf)if "oneOf" in prop_schema or "anyOf" in prop_schema:union_schemas = prop_schema.get("oneOf", []) + prop_schema.get("anyOf", [])for union_schema in union_schemas:union_type = union_schema.get("type")if union_type not in ALLOWED_TYPES:raise TypeError(17 unmodified lines1819202122232410 unmodified lines3536373839404120 unmodified lines6263646566676830 unmodified lines9910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813917 unmodified lines"CancelledElicitation","DeclinedElicitation","get_elicitation_schema","ScalarElicitationType",]logger = get_logger(__name__)10 unmodified lines@dataclassclass ScalarElicitationType(Generic[T]):value: T20 unmodified lines- Must be an object schema- Must only contain primitive field types (string, number, integer, boolean)- Must be flat (no nested objects or arrays of objects)- Allows const fields (for Literal types) and enum fields (for Enum types)- Only primitive types and their nullable variants are allowedArgs:30 unmodified lineselif prop_schema.get("nullable", False):continue # Nullable with no other type is fine# Handle const fields (Literal types)if "const" in prop_schema:continue # const fields are allowed regardless of type# Handle enum fields (Enum types)if "enum" in prop_schema:continue # enum fields are allowed regardless of type# Handle references to definitions (like Enum types)if "$ref" in prop_schema:# Get the referenced definitionref_path = prop_schema["$ref"]if ref_path.startswith("#/$defs/"):def_name = ref_path[8:] # Remove "#/$defs/" prefixref_def = schema.get("$defs", {}).get(def_name, {})# If the referenced definition has an enum, it's allowedif "enum" in ref_def:continue# If the referenced definition has a type that's allowed, it's allowedref_type = ref_def.get("type")if ref_type in ALLOWED_TYPES:continue# If we can't determine what the ref points to, reject it for safetyraise TypeError(f"Elicitation schema field '{prop_name}' contains a reference '{ref_path}' ""that could not be validated. Only references to enum types or primitive types are allowed.")# Handle union types (oneOf/anyOf)if "oneOf" in prop_schema or "anyOf" in prop_schema:union_schemas = prop_schema.get("oneOf", []) + prop_schema.get("anyOf", [])for union_schema in union_schemas:# Allow const and enum in unionsif "const" in union_schema or "enum" in union_schema:continueunion_type = union_schema.get("type")if union_type not in ALLOWED_TYPES:raise TypeError(
40 unmodified lines41424344454647206 unmodified lines254255256257258259260261137 unmodified lines39940040140240340440540640740840941041141241340 unmodified linesfrom copy import deepcopyfrom dataclasses import MISSING, field, make_dataclassfrom datetime import datetimefrom enum import Enumfrom typing import (Annotated,Any,206 unmodified linesdef _create_enum(name: str, values: list[Any]) -> type:"""Create enum type from list of values."""if all(isinstance(v, str) for v in values):return Enum(name, {v.upper(): v for v in values}) # type: ignore[return-value]return Literal[tuple(values)] # type: ignore[return-value]137 unmodified linesdef _sanitize_name(name: str) -> str:"""Convert string to valid Python identifier."""# Step 1: replace everything except [0-9a-zA-Z_] with underscorescleaned = re.sub(r"[^0-9a-zA-Z_]", "_", name)# Step 2: deduplicate underscorescleaned = re.sub(r"__+", "_", cleaned)# Step 3: if the first char of original name isn't a letter, prepend field_if not name or not re.match(r"[a-zA-Z]", name[0]):cleaned = f"field_{cleaned}"# Step 4: deduplicate again and strip trailing underscorescleaned = re.sub(r"__+", "_", cleaned).strip("_")return cleaned40 unmodified lines414243444546206 unmodified lines253254255256257258259137 unmodified lines39739839940040140240340440540640740840941041141241341441540 unmodified linesfrom copy import deepcopyfrom dataclasses import MISSING, field, make_dataclassfrom datetime import datetimefrom typing import (Annotated,Any,206 unmodified linesdef _create_enum(name: str, values: list[Any]) -> type:"""Create enum type from list of values."""# Always return Literal for enum fields to preserve the literal naturereturn Literal[tuple(values)] # type: ignore[return-value]137 unmodified linesdef _sanitize_name(name: str) -> str:"""Convert string to valid Python identifier."""original_name = name# Step 1: replace everything except [0-9a-zA-Z_] with underscorescleaned = re.sub(r"[^0-9a-zA-Z_]", "_", name)# Step 2: deduplicate underscorescleaned = re.sub(r"__+", "_", cleaned)# Step 3: if the first char of original name isn't a letter or underscore, prepend field_if not name or not re.match(r"[a-zA-Z_]", name[0]):cleaned = f"field_{cleaned}"# Step 4: deduplicate againcleaned = re.sub(r"__+", "_", cleaned)# Step 5: only strip trailing underscores if they weren't in the original nameif not original_name.endswith("_"):cleaned = cleaned.rstrip("_")return cleaned
1234567891011121314151633 unmodified lines5051525354555657585 unmodified lines6465666768697018 unmodified lines8990919293949515 unmodified lines1111121131141151161171181191 unmodified line12112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416510 unmodified lines17617717817918018118212 unmodified lines19519619719819920020120220320420520620720820913 unmodified lines22322422522622722822923 unmodified lines25325425525625725825926026126226326426526626726826927027127227327427527627727827928019 unmodified lines30030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844912 unmodified lines46246346446546646746817 unmodified lines48648748848949049149217 unmodified lines510511512513514515516from dataclasses import dataclassimport pytestfrom mcp.types import ElicitResultfrom fastmcp import Context, FastMCPfrom fastmcp.client.client import Clientfrom fastmcp.exceptions import ToolErrorfrom fastmcp.server.elicitation import (AcceptedElicitation,CancelledElicitation,DeclinedElicitation,)@pytest.fixture33 unmodified linesasync def test_elicitation_accept_content(fastmcp_server):"""Test basic elicitation functionality."""async def elicitation_handler(message, schema, ctx):# Mock user providing their namereturn ElicitResult(action="accept", content={"name": "Alice"})async with Client(fastmcp_server, elicitation_handler=elicitation_handler5 unmodified linesasync def test_elicitation_decline(fastmcp_server):"""Test that elicitation handler receives correct parameters."""async def elicitation_handler(message, schema, ctx):return ElicitResult(action="decline")async with Client(18 unmodified linesreturn f"Your favorite color is {result.data}!"return "No color provided"async def elicitation_handler(message, schema, ctx):# Mock user providing their favorite color as string in content dictreturn ElicitResult(action="accept", content={"value": "blue"})15 unmodified lines)return "done"async def elicitation_handler(message, schema, ctx):captured_params["message"] = messagecaptured_params["schema"] = schemacaptured_params["ctx"] = ctxreturn ElicitResult(action="accept", content={"value": 42})1 unmodified lineawait client.call_tool("test_tool", {})assert captured_params["message"] == "Test message"assert captured_params["schema"] == {"properties": {"value": {"title": "Value", "type": "integer"}},"required": ["value"],"title": "PrimitiveElicitationType","type": "object",}assert captured_params["ctx"] is not Noneasync def test_elicitation_default_string_schema():"""Test elicitation with default string schema."""mcp = FastMCP("TestServer")@mcp.toolasync def ask_for_input(context: Context) -> str:result = await context.elicit(message="Please provide some input"# No schema provided - should default to string)if result.action == "accept":return f"You said: {result.data}"return "No input provided"async def elicitation_handler(message, schema, ctx):# Verify default schema is wrapped string objectexpected_schema = {"properties": {"value": {"title": "Value", "type": "string"}},"required": ["value"],"title": "PrimitiveElicitationType","type": "object",}assert schema == expected_schemareturn ElicitResult(action="accept", content={"value": "Hello world!"})async with Client(mcp, elicitation_handler=elicitation_handler) as client:result = await client.call_tool("ask_for_input", {})assert result.data == "You said: Hello world!"async def test_elicitation_cancel_action():"""Test user canceling elicitation request."""mcp = FastMCP("TestServer")10 unmodified lineselse:return "No response provided"async def elicitation_handler(message, schema, ctx):return ElicitResult(action="cancel")async with Client(mcp, elicitation_handler=elicitation_handler) as client:12 unmodified linesreturn f"You are {result.data} years old"return "No age provided"async def elicitation_handler(message, schema, ctx):expected_schema = {"properties": {"value": {"title": "Value", "type": "integer"}},"required": ["value"],"title": "PrimitiveElicitationType","type": "object",}assert schema == expected_schemareturn ElicitResult(action="accept", content={"value": 25})async with Client(mcp, elicitation_handler=elicitation_handler) as client:result = await client.call_tool("get_age", {})13 unmodified linesexcept Exception as e:return f"Error: {str(e)}"async def elicitation_handler(message, schema, ctx):raise ValueError("Handler failed!")async with Client(mcp, elicitation_handler=elicitation_handler) as client:23 unmodified linescall_count = 0async def elicitation_handler(message, schema, ctx):nonlocal call_countcall_count += 1if call_count == 1:assert "name" in message.lower()expected_schema = {"properties": {"value": {"title": "Value", "type": "string"}},"required": ["value"],"title": "PrimitiveElicitationType","type": "object",}assert schema == expected_schemareturn ElicitResult(action="accept", content={"value": "Bob"})elif call_count == 2:assert "age" in message.lower()expected_schema = {"properties": {"value": {"title": "Value", "type": "integer"}},"required": ["value"],"title": "PrimitiveElicitationType","type": "object",}assert schema == expected_schemareturn ElicitResult(action="accept", content={"value": 25})else:raise ValueError("Unexpected call")19 unmodified linesmessage="Please provide your information", response_type=UserInfo)if result.action == "accept":user = result.datareturn f"User: {user.name}, age: {user.age}"return "No user info provided"async def elicitation_handler(message, schema, ctx):# Verify the schema has the dataclass fieldsassert schema["type"] == "object"assert "name" in schema["properties"]assert "age" in schema["properties"]assert schema["properties"]["name"]["type"] == "string"assert schema["properties"]["age"]["type"] == "integer"return ElicitResult(action="accept", content={"name": "Alice", "age": 30})async with Client(mcp, elicitation_handler=elicitation_handler) as client:result = await client.call_tool("get_user_info", {})assert result.data == "User: Alice, age: 30"async def test_primitive_type_string():"""Test elicitation with string primitive type."""mcp = FastMCP("TestServer")@mcp.toolasync def test_string(context: Context) -> str:result = await context.elicit("Enter text:", response_type=str)assert result.action == "accept"return f"Got: {result.data}"async def elicitation_handler(message, schema, ctx):assert schema["properties"]["value"]["type"] == "string"return ElicitResult(action="accept", content={"value": "hello"})async with Client(mcp, elicitation_handler=elicitation_handler) as client:result = await client.call_tool("test_string", {})assert result.data == "Got: hello"async def test_primitive_type_int():"""Test elicitation with integer primitive type."""mcp = FastMCP("TestServer")@mcp.toolasync def test_int(context: Context) -> str:result = await context.elicit("Enter number:", response_type=int)assert result.action == "accept"return f"Got: {result.data}"async def elicitation_handler(message, schema, ctx):assert schema["properties"]["value"]["type"] == "integer"return ElicitResult(action="accept", content={"value": 42})async with Client(mcp, elicitation_handler=elicitation_handler) as client:result = await client.call_tool("test_int", {})assert result.data == "Got: 42"async def test_primitive_type_float():"""Test elicitation with float primitive type."""mcp = FastMCP("TestServer")@mcp.toolasync def test_float(context: Context) -> str:result = await context.elicit("Enter decimal:", response_type=float)assert result.action == "accept"return f"Got: {result.data}"async def elicitation_handler(message, schema, ctx):assert schema["properties"]["value"]["type"] == "number"return ElicitResult(action="accept", content={"value": 3.14})async with Client(mcp, elicitation_handler=elicitation_handler) as client:result = await client.call_tool("test_float", {})assert result.data == "Got: 3.14"async def test_primitive_type_bool():"""Test elicitation with boolean primitive type."""mcp = FastMCP("TestServer")@mcp.toolasync def test_bool(context: Context) -> str:result = await context.elicit("Enter true/false:", response_type=bool)assert result.action == "accept"return f"Got: {result.data}"async def elicitation_handler(message, schema, ctx):assert schema["properties"]["value"]["type"] == "boolean"return ElicitResult(action="accept", content={"value": True})async with Client(mcp, elicitation_handler=elicitation_handler) as client:result = await client.call_tool("test_bool", {})assert result.data == "Got: True"async def test_schema_validation_rejects_non_object():"""Test that non-object schemas are rejected."""from fastmcp.server.elicitation import validate_elicitation_json_schemawith pytest.raises(TypeError, match="must be an object schema"):validate_elicitation_json_schema({"type": "string"})async def test_schema_validation_rejects_empty_object():"""Test that object schemas without properties are rejected."""from fastmcp.server.elicitation import validate_elicitation_json_schemawith pytest.raises(TypeError, match="must have at least one property"):validate_elicitation_json_schema({"type": "object"})async def test_schema_validation_rejects_nested_objects():"""Test that nested object schemas are rejected."""from fastmcp.server.elicitation import validate_elicitation_json_schemawith pytest.raises(TypeError, match="has type 'object' which is not a primitive type"):validate_elicitation_json_schema({"type": "object","properties": {"user": {"type": "object","properties": {"name": {"type": "string"}},}},})async def test_schema_validation_rejects_arrays():"""Test that array schemas are rejected."""from fastmcp.server.elicitation import validate_elicitation_json_schemawith pytest.raises(TypeError, match="has type 'array' which is not a primitive type"):validate_elicitation_json_schema({"type": "object","properties": {"users": {"type": "array", "items": {"type": "string"}}},})async def test_pattern_matching_accept():12 unmodified linescase CancelledElicitation():return "Cancelled"async def elicitation_handler(message, schema, ctx):return ElicitResult(action="accept", content={"value": "Alice"})async with Client(mcp, elicitation_handler=elicitation_handler) as client:17 unmodified linescase CancelledElicitation():return "Cancelled"async def elicitation_handler(message, schema, ctx):return ElicitResult(action="decline")async with Client(mcp, elicitation_handler=elicitation_handler) as client:17 unmodified linescase CancelledElicitation():return "Cancelled"async def elicitation_handler(message, schema, ctx):return ElicitResult(action="cancel")async with Client(mcp, elicitation_handler=elicitation_handler) as client:1234567891011121314151617181933 unmodified lines5354555657585960615 unmodified lines6768697071727318 unmodified lines9293949596979815 unmodified lines1141151161171181191201211221231 unmodified line12512612712812913013113213313413513613713813914010 unmodified lines15115215315415515615712 unmodified lines17017117217317417517617713 unmodified lines19119219319419519619723 unmodified lines22122222322422522622722822923023123219 unmodified lines25225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939012 unmodified lines40340440540640740840917 unmodified lines42742842943043143243317 unmodified lines451452453454455456457from dataclasses import asdict, dataclassfrom enum import Enumfrom typing import Literalimport pytestfrom fastmcp import Context, FastMCPfrom fastmcp.client.client import Clientfrom fastmcp.client.elicitation import ElicitResultfrom fastmcp.exceptions import ToolErrorfrom fastmcp.server.elicitation import (AcceptedElicitation,CancelledElicitation,DeclinedElicitation,)from fastmcp.utilities.types import TypeAdapter@pytest.fixture33 unmodified linesasync def test_elicitation_accept_content(fastmcp_server):"""Test basic elicitation functionality."""async def elicitation_handler(message, response_type, params, ctx):# Mock user providing their namereturn ElicitResult(action="accept", content=response_type(name="Alice"))async with Client(fastmcp_server, elicitation_handler=elicitation_handler5 unmodified linesasync def test_elicitation_decline(fastmcp_server):"""Test that elicitation handler receives correct parameters."""async def elicitation_handler(message, response_type, params, ctx):return ElicitResult(action="decline")async with Client(18 unmodified linesreturn f"Your favorite color is {result.data}!"return "No color provided"async def elicitation_handler(message, response_type, params, ctx):# Mock user providing their favorite color as string in content dictreturn ElicitResult(action="accept", content={"value": "blue"})15 unmodified lines)return "done"async def elicitation_handler(message, response_type, params, ctx):captured_params["message"] = messagecaptured_params["response_type"] = str(response_type)captured_params["params"] = paramscaptured_params["ctx"] = ctxreturn ElicitResult(action="accept", content={"value": 42})1 unmodified lineawait client.call_tool("test_tool", {})assert captured_params["message"] == "Test message"assert "ScalarElicitationType" in str(captured_params["response_type"])assert captured_params["params"].requestedSchema == {"properties": {"value": {"title": "Value", "type": "integer"}},"required": ["value"],"title": "ScalarElicitationType","type": "object",}assert captured_params["ctx"] is not Noneasync def test_elicitation_cancel_action():"""Test user canceling elicitation request."""mcp = FastMCP("TestServer")10 unmodified lineselse:return "No response provided"async def elicitation_handler(message, response_type, params, ctx):return ElicitResult(action="cancel")async with Client(mcp, elicitation_handler=elicitation_handler) as client:12 unmodified linesreturn f"You are {result.data} years old"return "No age provided"async def elicitation_handler(message, response_type, params, ctx):return ElicitResult(action="accept", content=response_type(value=25))async with Client(mcp, elicitation_handler=elicitation_handler) as client:result = await client.call_tool("get_age", {})13 unmodified linesexcept Exception as e:return f"Error: {str(e)}"async def elicitation_handler(message, response_type, params, ctx):raise ValueError("Handler failed!")async with Client(mcp, elicitation_handler=elicitation_handler) as client:23 unmodified linescall_count = 0async def elicitation_handler(message, response_type, params, ctx):nonlocal call_countcall_count += 1if call_count == 1:return ElicitResult(action="accept", content={"value": "Bob"})elif call_count == 2:return ElicitResult(action="accept", content={"value": 25})else:raise ValueError("Unexpected call")19 unmodified linesmessage="Please provide your information", response_type=UserInfo)if result.action == "accept":return f"User: {result.data.name}, age: {result.data.age}"return "No user info provided"async def elicitation_handler(message, response_type, params, ctx):# Verify we get the dataclass typeassert (TypeAdapter(response_type).json_schema()== TypeAdapter(UserInfo).json_schema())# Verify the schema has the dataclass fields (available in params)schema = params.requestedSchemaassert schema["type"] == "object"assert "name" in schema["properties"]assert "age" in schema["properties"]assert schema["properties"]["name"]["type"] == "string"assert schema["properties"]["age"]["type"] == "integer"return ElicitResult(action="accept", content=UserInfo(name="Alice", age=30))async with Client(mcp, elicitation_handler=elicitation_handler) as client:result = await client.call_tool("get_user_info", {})assert result.data == "User: Alice, age: 30"async def test_all_primitive_field_types():class DataEnum(Enum):X = "x"Y = "y"@dataclassclass Data:integer: intfloat_: floatnumber: int | floatboolean: boolstring: strconstant: Literal["x"]union: Literal["x"] | Literal["y"]choice: Literal["x", "y"]enum: DataEnummcp = FastMCP("TestServer")@mcp.toolasync def get_data(context: Context) -> Data:result = await context.elicit(message="Enter data", response_type=Data)return result.data # type: ignore[attr-defined]async def elicitation_handler(message, response_type, params, ctx):return ElicitResult(action="accept",content=Data(integer=1,float_=1.0,number=1.0,boolean=True,string="hello",constant="x",union="x",choice="x",enum=DataEnum.X,),)async with Client(mcp, elicitation_handler=elicitation_handler) as client:result = await client.call_tool("get_data", {})# Now all literal/enum fields should be preserved as stringsresult_data = asdict(result.data)result_data_enum = result_data.pop("enum")assert result_data_enum == "x" # Should be a string now, not an enumassert result_data == {"integer": 1,"float_": 1.0,"number": 1.0,"boolean": True,"string": "hello","constant": "x","union": "x","choice": "x",}class TestValidation:async def test_schema_validation_rejects_non_object(self):"""Test that non-object schemas are rejected."""from fastmcp.server.elicitation import validate_elicitation_json_schemawith pytest.raises(TypeError, match="must be an object schema"):validate_elicitation_json_schema({"type": "string"})async def test_schema_validation_rejects_empty_object(self):"""Test that object schemas without properties are rejected."""from fastmcp.server.elicitation import validate_elicitation_json_schemawith pytest.raises(TypeError, match="must have at least one property"):validate_elicitation_json_schema({"type": "object"})async def test_schema_validation_rejects_nested_objects(self):"""Test that nested object schemas are rejected."""from fastmcp.server.elicitation import validate_elicitation_json_schemawith pytest.raises(TypeError, match="has type 'object' which is not a primitive type"):validate_elicitation_json_schema({"type": "object","properties": {"user": {"type": "object","properties": {"name": {"type": "string"}},}},})async def test_schema_validation_rejects_arrays(self):"""Test that array schemas are rejected."""from fastmcp.server.elicitation import validate_elicitation_json_schemawith pytest.raises(TypeError, match="has type 'array' which is not a primitive type"):validate_elicitation_json_schema({"type": "object","properties": {"users": {"type": "array", "items": {"type": "string"}}},})async def test_pattern_matching_accept():12 unmodified linescase CancelledElicitation():return "Cancelled"async def elicitation_handler(message, response_type, params, ctx):return ElicitResult(action="accept", content={"value": "Alice"})async with Client(mcp, elicitation_handler=elicitation_handler) as client:17 unmodified linescase CancelledElicitation():return "Cancelled"async def elicitation_handler(message, response_type, params, ctx):return ElicitResult(action="decline")async with Client(mcp, elicitation_handler=elicitation_handler) as client:17 unmodified linescase CancelledElicitation():return "Cancelled"async def elicitation_handler(message, response_type, params, ctx):return ElicitResult(action="cancel")async with Client(mcp, elicitation_handler=elicitation_handler) as client:
12345100 unmodified lines106107108109110111274 unmodified lines386387388389390391from datetime import datetimefrom typing import Any, Unionimport pytestfrom pydantic import AnyUrl, BaseModel, TypeAdapter, ValidationError100 unmodified linesvalidator.validate_python(False)class TestStringConstraints:"""Test suite for string constraint validation."""274 unmodified lineswith pytest.raises(ValidationError):validator.validate_python({"user": {"age": 30}})class TestDefaultValues:"""Test suite for default value handling."""1234567100 unmodified lines108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172274 unmodified lines447448449450451452453454455456457458459460461462463464465466467468469470471472473474475from dataclasses import dataclassfrom datetime import datetimefrom enum import Enumfrom typing import Any, Literal, Unionimport pytestfrom pydantic import AnyUrl, BaseModel, TypeAdapter, ValidationError100 unmodified linesvalidator.validate_python(False)class TestConstrainedTypes:def test_constant(self):validator = TypeAdapter(Literal["x"])schema = validator.json_schema()type_ = json_schema_to_type(schema)assert type_ == Literal["x"]assert TypeAdapter(type_).validate_python("x") == "x"with pytest.raises(ValidationError):TypeAdapter(type_).validate_python("y")def test_union_constants(self):validator = TypeAdapter(Literal["x"] | Literal["y"])schema = validator.json_schema()type_ = json_schema_to_type(schema)assert type_ == Literal["x"] | Literal["y"]assert TypeAdapter(type_).validate_python("x") == "x"assert TypeAdapter(type_).validate_python("y") == "y"with pytest.raises(ValidationError):TypeAdapter(type_).validate_python("z")def test_enum_str(self):class MyEnum(Enum):X = "x"Y = "y"validator = TypeAdapter(MyEnum)schema = validator.json_schema()type_ = json_schema_to_type(schema)assert type_ == Literal["x", "y"]assert TypeAdapter(type_).validate_python("x") == "x"assert TypeAdapter(type_).validate_python("y") == "y"with pytest.raises(ValidationError):TypeAdapter(type_).validate_python("z")def test_enum_int(self):class MyEnum(Enum):X = 1Y = 2validator = TypeAdapter(MyEnum)schema = validator.json_schema()type_ = json_schema_to_type(schema)assert type_ == Literal[1, 2]assert TypeAdapter(type_).validate_python(1) == 1assert TypeAdapter(type_).validate_python(2) == 2with pytest.raises(ValidationError):TypeAdapter(type_).validate_python(3)def test_choice(self):validator = TypeAdapter(Literal["x", "y"])schema = validator.json_schema()type_ = json_schema_to_type(schema)assert type_ == Literal["x", "y"]assert TypeAdapter(type_).validate_python("x") == "x"assert TypeAdapter(type_).validate_python("y") == "y"with pytest.raises(ValidationError):TypeAdapter(type_).validate_python("z")class TestStringConstraints:"""Test suite for string constraint validation."""274 unmodified lineswith pytest.raises(ValidationError):validator.validate_python({"user": {"age": 30}})def test_object_with_underscore_names(self):@dataclassclass Data:x: intx_: int_x: intschema = TypeAdapter(Data).json_schema()assert schema == {"title": "Data","type": "object","properties": {"x": {"type": "integer", "title": "X"},"x_": {"type": "integer", "title": "X"},"_x": {"type": "integer", "title": "X"},},"required": ["x", "x_", "_x"],}object = json_schema_to_type(schema)object_schema = TypeAdapter(object).json_schema()assert object_schema == schemaclass TestDefaultValues:"""Test suite for default value handling."""
CLAUDE.md+6-1
docs/clients/elicitation.mdxAdded+119
docs/docs.json+1
docs/servers/context.mdx+111
src/fastmcp/client/elicitation.py+21-7
src/fastmcp/server/context.py+4-4
src/fastmcp/server/elicitation.py+34-2
src/fastmcp/utilities/json_schema_type.py+9-7
tests/client/test_elicitation.py+133-192
tests/utilities/test_json_schema_type.py+85-1