Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Provide a response type to client

Jeremiah Lowin3805ac9b44fd
diff --git a/CLAUDE.md b/CLAUDE.md
index 18c7a4ffc..c47c2e3eb 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,5 +1,10 @@
# 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 Preferred
@@ -34,4 +39,4 @@ async with Client(transport=StreamableHttpTransport(server_url)) as client:
- 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
\ No newline at end of file
+- Use # type: ignore[attr-defined] in unit tests when accessing an MCP result of indeterminate type instead of asserting its type
diff --git a/docs/clients/elicitation.mdx b/docs/clients/elicitation.mdx
new file mode 100644
index 000000000..907a60314
--- /dev/null
+++ b/docs/clients/elicitation.mdx
@@ -0,0 +1,119 @@
+---
+title: User Elicitation
+sidebarTitle: Elicitation
+description: 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:
+
+```python
+from fastmcp import Client
+from 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
+
+```python
+from fastmcp import Client
+from 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
+)
+```
+
+
diff --git a/docs/docs.json b/docs/docs.json
index e3526069e..852c86ea9 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -106,6 +106,7 @@
"group": "Advanced Features",
"icon": "stars",
"pages": [
+ "clients/elicitation",
"clients/logging",
"clients/progress",
"clients/sampling",
diff --git a/docs/servers/context.mdx b/docs/servers/context.mdx
index 31f833c7c..a29f84ddd 100644
--- a/docs/servers/context.mdx
+++ b/docs/servers/context.mdx
@@ -16,6 +16,7 @@ The `Context` object provides a clean interface to access MCP features within yo
- **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 instance
@@ -275,6 +276,116 @@ async def generate_example(concept: str, ctx: Context) -> str:
See [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.
+
+```python
+from dataclasses import dataclass
+
+@dataclass
+class UserInfo:
+ name: str
+ age: int
+
+async def collect_user_info(ctx: Context) -> str:
+ """Collect user information through interactive prompts."""
+ # Request structured user information
+ result = await ctx.elicit(
+ message="Please provide your information",
+ response_type=UserInfo
+ )
+
+ if result.action == "accept":
+ user = result.data
+ return f"Hello {user.name}, you are {user.age} years old"
+ elif result.action == "decline":
+ return "Information not provided"
+ else: # cancel
+ return "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
+
+```python
+from typing import Literal
+from enum import Enum
+
+class Priority(Enum):
+ LOW = "low"
+ MEDIUM = "medium"
+ HIGH = "high"
+
+@dataclass
+class TaskInfo:
+ title: str
+ priority: Priority
+ urgent: bool
+
+async def create_task(ctx: Context) -> str:
+ """Create a task with user-provided details."""
+ # Multiple elicitation calls for different information
+
+ # Simple string input
+ title_result = await ctx.elicit("What's the task title?", response_type=str)
+ if title_result.action != "accept":
+ return "Task creation cancelled"
+
+ # Enum selection
+ priority_result = await ctx.elicit("What's the priority?", response_type=Priority)
+ if priority_result.action != "accept":
+ return "Task creation cancelled"
+
+ # Boolean choice
+ urgent_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:
+
+```python
+from fastmcp.server.elicitation import (
+ AcceptedElicitation,
+ DeclinedElicitation,
+ CancelledElicitation
+)
+
+async 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" />
diff --git a/src/fastmcp/client/elicitation.py b/src/fastmcp/client/elicitation.py
index 0bfe06356..b5d8df873 100644
--- a/src/fastmcp/client/elicitation.py
+++ b/src/fastmcp/client/elicitation.py
@@ -1,24 +1,35 @@
from __future__ import annotations
from collections.abc import Awaitable, Callable
-from typing import Any, TypeAlias
+from typing import Any, Generic, TypeAlias, TypeVar
import mcp.types
from mcp import ClientSession
from mcp.client.session import ElicitationFnT
from mcp.shared.context import LifespanContextT, RequestContext
-from mcp.types import ElicitRequestParams, ElicitResult
+from mcp.types import ElicitRequestParams
+from mcp.types import ElicitResult as MCPElicitResult
+from pydantic_core import to_jsonable_python
+
+from 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 = None
+
ElicitationHandler: TypeAlias = Callable[
[
str, # message
- dict[str, Any], # requested_schema
+ type[T], # a class for creating a structured response
+ ElicitRequestParams,
RequestContext[ClientSession, LifespanContextT],
],
- Awaitable[ElicitResult],
+ Awaitable[ElicitResult[T | dict[str, Any]]],
]
@@ -28,12 +39,15 @@ def create_elicitation_callback(
async def _elicitation_handler(
context: RequestContext[ClientSession, LifespanContextT],
params: ElicitRequestParams,
- ) -> ElicitResult | mcp.types.ErrorData:
+ ) -> MCPElicitResult | mcp.types.ErrorData:
try:
+ response_type = json_schema_to_type(params.requestedSchema)
+
result = await elicitation_handler(
- params.message, params.requestedSchema, context
+ params.message, response_type, params, context
)
- return result
+ 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,
diff --git a/src/fastmcp/server/context.py b/src/fastmcp/server/context.py
index dc6f4edb5..a3302c818 100644
--- a/src/fastmcp/server/context.py
+++ b/src/fastmcp/server/context.py
@@ -30,7 +30,7 @@ from fastmcp.server.elicitation import (
AcceptedElicitation,
CancelledElicitation,
DeclinedElicitation,
- PrimitiveElicitationType,
+ ScalarElicitationType,
get_elicitation_schema,
)
from fastmcp.server.server import FastMCP
@@ -339,7 +339,7 @@ class Context:
response_type = str # type: ignore
if response_type in {bool, int, float, str}:
- response_type = PrimitiveElicitationType[response_type] # type: ignore
+ response_type = ScalarElicitationType[response_type] # type: ignore
requested_schema = get_elicitation_schema(response_type) # type: ignore
@@ -352,10 +352,10 @@ class Context:
if result.action == "accept" and result.content:
type_adapter = get_cached_typeadapter(response_type)
validated_data = cast(
- T | PrimitiveElicitationType[T],
+ T | ScalarElicitationType[T],
type_adapter.validate_python(result.content),
)
- if isinstance(validated_data, PrimitiveElicitationType):
+ if isinstance(validated_data, ScalarElicitationType):
return AcceptedElicitation[T](data=validated_data.value)
else:
return AcceptedElicitation[T](data=validated_data)
diff --git a/src/fastmcp/server/elicitation.py b/src/fastmcp/server/elicitation.py
index 08693e5c6..499613380 100644
--- a/src/fastmcp/server/elicitation.py
+++ b/src/fastmcp/server/elicitation.py
@@ -18,7 +18,7 @@ __all__ = [
"CancelledElicitation",
"DeclinedElicitation",
"get_elicitation_schema",
- "PrimitiveElicitationType",
+ "ScalarElicitationType",
]
logger = get_logger(__name__)
@@ -35,7 +35,7 @@ class AcceptedElicitation(BaseModel, Generic[T]):
@dataclass
-class PrimitiveElicitationType(Generic[T]):
+class ScalarElicitationType(Generic[T]):
value: T
@@ -62,6 +62,7 @@ def validate_elicitation_json_schema(schema: dict[str, Any]) -> None:
- 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 allowed
Args:
@@ -98,10 +99,41 @@ def validate_elicitation_json_schema(schema: dict[str, Any]) -> None:
elif 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 definition
+ ref_path = prop_schema["$ref"]
+ if ref_path.startswith("#/$defs/"):
+ def_name = ref_path[8:] # Remove "#/$defs/" prefix
+ ref_def = schema.get("$defs", {}).get(def_name, {})
+ # If the referenced definition has an enum, it's allowed
+ if "enum" in ref_def:
+ continue
+ # If the referenced definition has a type that's allowed, it's allowed
+ ref_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 safety
+ raise 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 unions
+ if "const" in union_schema or "enum" in union_schema:
+ continue
union_type = union_schema.get("type")
if union_type not in ALLOWED_TYPES:
raise TypeError(
diff --git a/src/fastmcp/utilities/json_schema_type.py b/src/fastmcp/utilities/json_schema_type.py
index 1160c6334..ff5ab4102 100644
--- a/src/fastmcp/utilities/json_schema_type.py
+++ b/src/fastmcp/utilities/json_schema_type.py
@@ -41,7 +41,6 @@ from collections.abc import Callable, Mapping
from copy import deepcopy
from dataclasses import MISSING, field, make_dataclass
from datetime import datetime
-from enum import Enum
from typing import (
Annotated,
Any,
@@ -254,8 +253,7 @@ def _create_numeric_type(
def _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]
+ # Always return Literal for enum fields to preserve the literal nature
return Literal[tuple(values)] # type: ignore[return-value]
@@ -399,15 +397,19 @@ def _schema_to_type(
def _sanitize_name(name: str) -> str:
"""Convert string to valid Python identifier."""
+ original_name = name
# Step 1: replace everything except [0-9a-zA-Z_] with underscores
cleaned = re.sub(r"[^0-9a-zA-Z_]", "_", name)
# Step 2: deduplicate underscores
cleaned = 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]):
+ # 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 again and strip trailing underscores
- cleaned = re.sub(r"__+", "_", cleaned).strip("_")
+ # Step 4: deduplicate again
+ cleaned = re.sub(r"__+", "_", cleaned)
+ # Step 5: only strip trailing underscores if they weren't in the original name
+ if not original_name.endswith("_"):
+ cleaned = cleaned.rstrip("_")
return cleaned
diff --git a/tests/client/test_elicitation.py b/tests/client/test_elicitation.py
index b792fde69..d79cfbdca 100644
--- a/tests/client/test_elicitation.py
+++ b/tests/client/test_elicitation.py
@@ -1,16 +1,19 @@
-from dataclasses import dataclass
+from dataclasses import asdict, dataclass
+from enum import Enum
+from typing import Literal
import pytest
-from mcp.types import ElicitResult
from fastmcp import Context, FastMCP
from fastmcp.client.client import Client
+from fastmcp.client.elicitation import ElicitResult
from fastmcp.exceptions import ToolError
from fastmcp.server.elicitation import (
AcceptedElicitation,
CancelledElicitation,
DeclinedElicitation,
)
+from fastmcp.utilities.types import TypeAdapter
@pytest.fixture
@@ -50,9 +53,9 @@ async def test_elicitation_with_no_handler(fastmcp_server):
async def test_elicitation_accept_content(fastmcp_server):
"""Test basic elicitation functionality."""
- async def elicitation_handler(message, schema, ctx):
+ async def elicitation_handler(message, response_type, params, ctx):
# Mock user providing their name
- return ElicitResult(action="accept", content={"name": "Alice"})
+ return ElicitResult(action="accept", content=response_type(name="Alice"))
async with Client(
fastmcp_server, elicitation_handler=elicitation_handler
@@ -64,7 +67,7 @@ async def test_elicitation_accept_content(fastmcp_server):
async def test_elicitation_decline(fastmcp_server):
"""Test that elicitation handler receives correct parameters."""
- async def elicitation_handler(message, schema, ctx):
+ async def elicitation_handler(message, response_type, params, ctx):
return ElicitResult(action="decline")
async with Client(
@@ -89,7 +92,7 @@ async def test_default_response_type(fastmcp_server):
return f"Your favorite color is {result.data}!"
return "No color provided"
- async def elicitation_handler(message, schema, ctx):
+ async def elicitation_handler(message, response_type, params, ctx):
# Mock user providing their favorite color as string in content dict
return ElicitResult(action="accept", content={"value": "blue"})
@@ -111,9 +114,10 @@ async def test_elicitation_handler_parameters():
)
return "done"
- async def elicitation_handler(message, schema, ctx):
+ async def elicitation_handler(message, response_type, params, ctx):
captured_params["message"] = message
- captured_params["schema"] = schema
+ captured_params["response_type"] = str(response_type)
+ captured_params["params"] = params
captured_params["ctx"] = ctx
return ElicitResult(action="accept", content={"value": 42})
@@ -121,45 +125,16 @@ async def test_elicitation_handler_parameters():
await client.call_tool("test_tool", {})
assert captured_params["message"] == "Test message"
- assert captured_params["schema"] == {
+ assert "ScalarElicitationType" in str(captured_params["response_type"])
+ assert captured_params["params"].requestedSchema == {
"properties": {"value": {"title": "Value", "type": "integer"}},
"required": ["value"],
- "title": "PrimitiveElicitationType",
+ "title": "ScalarElicitationType",
"type": "object",
}
assert captured_params["ctx"] is not None
-async def test_elicitation_default_string_schema():
- """Test elicitation with default string schema."""
- mcp = FastMCP("TestServer")
-
- @mcp.tool
- async 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 object
- expected_schema = {
- "properties": {"value": {"title": "Value", "type": "string"}},
- "required": ["value"],
- "title": "PrimitiveElicitationType",
- "type": "object",
- }
- assert schema == expected_schema
- return 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")
@@ -176,7 +151,7 @@ async def test_elicitation_cancel_action():
else:
return "No response provided"
- async def elicitation_handler(message, schema, ctx):
+ async def elicitation_handler(message, response_type, params, ctx):
return ElicitResult(action="cancel")
async with Client(mcp, elicitation_handler=elicitation_handler) as client:
@@ -195,15 +170,8 @@ async def test_elicitation_number_schema():
return 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_schema
- return ElicitResult(action="accept", content={"value": 25})
+ 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", {})
@@ -223,7 +191,7 @@ async def test_elicitation_handler_error():
except Exception as e:
return f"Error: {str(e)}"
- async def elicitation_handler(message, schema, ctx):
+ async def elicitation_handler(message, response_type, params, ctx):
raise ValueError("Handler failed!")
async with Client(mcp, elicitation_handler=elicitation_handler) as client:
@@ -253,28 +221,12 @@ async def test_elicitation_multiple_calls():
call_count = 0
- async def elicitation_handler(message, schema, ctx):
+ async def elicitation_handler(message, response_type, params, ctx):
nonlocal call_count
call_count += 1
if 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_schema
return 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_schema
return ElicitResult(action="accept", content={"value": 25})
else:
raise ValueError("Unexpected call")
@@ -300,150 +252,139 @@ async def test_dataclass_response_type():
message="Please provide your information", response_type=UserInfo
)
if result.action == "accept":
- user = result.data
- return f"User: {user.name}, age: {user.age}"
+ return f"User: {result.data.name}, age: {result.data.age}"
return "No user info provided"
- async def elicitation_handler(message, schema, ctx):
- # Verify the schema has the dataclass fields
+ async def elicitation_handler(message, response_type, params, ctx):
+ # Verify we get the dataclass type
+ assert (
+ TypeAdapter(response_type).json_schema()
+ == TypeAdapter(UserInfo).json_schema()
+ )
+
+ # Verify the schema has the dataclass fields (available in params)
+ schema = params.requestedSchema
assert 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})
+ 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_primitive_type_string():
- """Test elicitation with string primitive type."""
- mcp = FastMCP("TestServer")
-
- @mcp.tool
- async 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.tool
- async 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.tool
- async 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_all_primitive_field_types():
+ class DataEnum(Enum):
+ X = "x"
+ Y = "y"
+ @dataclass
+ class Data:
+ integer: int
+ float_: float
+ number: int | float
+ boolean: bool
+ string: str
+ constant: Literal["x"]
+ union: Literal["x"] | Literal["y"]
+ choice: Literal["x", "y"]
+ enum: DataEnum
-async def test_primitive_type_bool():
- """Test elicitation with boolean primitive type."""
mcp = FastMCP("TestServer")
@mcp.tool
- async 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_schema
-
- with 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_schema
-
- with 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_schema
-
- with 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 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 strings
+ result_data = asdict(result.data)
+ result_data_enum = result_data.pop("enum")
+ assert result_data_enum == "x" # Should be a string now, not an enum
+ assert result_data == {
+ "integer": 1,
+ "float_": 1.0,
+ "number": 1.0,
+ "boolean": True,
+ "string": "hello",
+ "constant": "x",
+ "union": "x",
+ "choice": "x",
+ }
-async def test_schema_validation_rejects_arrays():
- """Test that array schemas are rejected."""
- from fastmcp.server.elicitation import validate_elicitation_json_schema
- with 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"}}},
- }
- )
+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_schema
+
+ with 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_schema
+
+ with 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_schema
+
+ with 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_schema
+
+ with 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():
@@ -462,7 +403,7 @@ async def test_pattern_matching_accept():
case CancelledElicitation():
return "Cancelled"
- async def elicitation_handler(message, schema, ctx):
+ 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:
@@ -486,7 +427,7 @@ async def test_pattern_matching_decline():
case CancelledElicitation():
return "Cancelled"
- async def elicitation_handler(message, schema, ctx):
+ async def elicitation_handler(message, response_type, params, ctx):
return ElicitResult(action="decline")
async with Client(mcp, elicitation_handler=elicitation_handler) as client:
@@ -510,7 +451,7 @@ async def test_pattern_matching_cancel():
case CancelledElicitation():
return "Cancelled"
- async def elicitation_handler(message, schema, ctx):
+ async def elicitation_handler(message, response_type, params, ctx):
return ElicitResult(action="cancel")
async with Client(mcp, elicitation_handler=elicitation_handler) as client:
diff --git a/tests/utilities/test_json_schema_type.py b/tests/utilities/test_json_schema_type.py
index 866facbce..ca8cd11b6 100644
--- a/tests/utilities/test_json_schema_type.py
+++ b/tests/utilities/test_json_schema_type.py
@@ -1,5 +1,7 @@
+from dataclasses import dataclass
from datetime import datetime
-from typing import Any, Union
+from enum import Enum
+from typing import Any, Literal, Union
import pytest
from pydantic import AnyUrl, BaseModel, TypeAdapter, ValidationError
@@ -106,6 +108,65 @@ class TestSimpleTypes:
validator.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 = 1
+ Y = 2
+
+ validator = TypeAdapter(MyEnum)
+ schema = validator.json_schema()
+ type_ = json_schema_to_type(schema)
+ assert type_ == Literal[1, 2]
+ assert TypeAdapter(type_).validate_python(1) == 1
+ assert TypeAdapter(type_).validate_python(2) == 2
+ with 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."""
@@ -386,6 +447,29 @@ class TestObjectTypes:
with pytest.raises(ValidationError):
validator.validate_python({"user": {"age": 30}})
+ def test_object_with_underscore_names(self):
+ @dataclass
+ class Data:
+ x: int
+ x_: int
+ _x: int
+
+ schema = 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 == schema
+
class TestDefaultValues:
"""Test suite for default value handling."""