Spaces:
Running
Running
File size: 23,286 Bytes
815bac1 d325152 baead56 dbf9272 fb12cad baead56 815bac1 1f71f65 baead56 dbf9272 baead56 815bac1 baead56 1f71f65 a922f59 1f71f65 baead56 815bac1 baead56 815bac1 baead56 a922f59 1f71f65 baead56 815bac1 baead56 a922f59 1f71f65 baead56 815bac1 baead56 815bac1 baead56 815bac1 baead56 815bac1 baead56 815bac1 baead56 1f71f65 baead56 fb12cad dbf9272 d325152 dbf9272 fb12cad baead56 fb12cad baead56 fb12cad baead56 fb12cad dbf9272 fb12cad baead56 815bac1 baead56 1f71f65 baead56 815bac1 baead56 1f71f65 baead56 fb12cad baead56 fb12cad baead56 fb12cad baead56 815bac1 fb12cad 815bac1 baead56 815bac1 baead56 1f71f65 baead56 815bac1 baead56 815bac1 baead56 815bac1 baead56 815bac1 baead56 815bac1 baead56 fb12cad 670f900 fb12cad 670f900 fb12cad 670f900 fb12cad a922f59 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 | from dataclasses import asdict, dataclass
from enum import Enum
from typing import Literal
import pytest
from mcp.types import ElicitRequestParams
from pydantic import BaseModel
from typing_extensions import TypedDict
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,
validate_elicitation_json_schema,
)
from fastmcp.utilities.types import TypeAdapter
@pytest.fixture
def fastmcp_server():
mcp = FastMCP("TestServer")
@dataclass
class Person:
name: str
@mcp.tool
async def ask_for_name(context: Context) -> str:
result = await context.elicit(
message="What is your name?",
response_type=Person,
)
if result.action == "accept":
return f"Hello, {result.data.name}!"
else:
return "No name provided."
@mcp.tool
def simple_test() -> str:
return "Hello!"
return mcp
async def test_elicitation_with_no_handler(fastmcp_server):
"""Test that elicitation works without a handler."""
async with Client(fastmcp_server) as client:
with pytest.raises(ToolError, match="Elicitation not supported"):
await client.call_tool("ask_for_name")
async def test_elicitation_accept_content(fastmcp_server):
"""Test basic elicitation functionality."""
async def elicitation_handler(message, response_type, params, ctx):
# Mock user providing their name
return ElicitResult(action="accept", content=response_type(name="Alice"))
async with Client(
fastmcp_server, elicitation_handler=elicitation_handler
) as client:
result = await client.call_tool("ask_for_name")
assert result.data == "Hello, Alice!"
async 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(
fastmcp_server, elicitation_handler=elicitation_handler
) as client:
result = await client.call_tool("ask_for_name")
assert result.data == "No name provided."
async def test_elicitation_handler_parameters():
"""Test that elicitation handler receives correct parameters."""
mcp = FastMCP("TestServer")
captured_params = {}
@mcp.tool
async def test_tool(context: Context) -> str:
await context.elicit(
message="Test message",
response_type=int,
)
return "done"
async def elicitation_handler(message, response_type, params, ctx):
captured_params["message"] = message
captured_params["response_type"] = str(response_type)
captured_params["params"] = params
captured_params["ctx"] = ctx
return ElicitResult(action="accept", content={"value": 42})
async with Client(mcp, elicitation_handler=elicitation_handler) as client:
await 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 None
async def test_elicitation_cancel_action():
"""Test user canceling elicitation request."""
mcp = FastMCP("TestServer")
@mcp.tool
async def ask_for_optional_info(context: Context) -> str:
result = await context.elicit(
message="Optional: What's your age?", response_type=int
)
if result.action == "cancel":
return "Request was canceled"
elif result.action == "accept":
return f"Age: {result.data}"
else:
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:
result = await client.call_tool("ask_for_optional_info", {})
assert result.data == "Request was canceled"
class TestScalarResponseTypes:
async def test_elicitation_no_response(self):
"""Test elicitation with no response type."""
mcp = FastMCP("TestServer")
@mcp.tool
async def my_tool(context: Context) -> None:
result = await context.elicit(message="", response_type=None)
return result.data # type: ignore[attr-defined]
async def elicitation_handler(
message, response_type, params: ElicitRequestParams, ctx
):
assert params.requestedSchema == {"type": "object", "properties": {}}
assert response_type is None
return ElicitResult(action="accept")
async with Client(mcp, elicitation_handler=elicitation_handler) as client:
result = await client.call_tool("my_tool", {})
assert result.data is None
async def test_elicitation_empty_response(self):
"""Test elicitation with empty response type."""
mcp = FastMCP("TestServer")
@mcp.tool
async def my_tool(context: Context) -> None:
result = await context.elicit(message="", response_type=None)
return result.data # type: ignore[attr-defined]
async def elicitation_handler(
message, response_type, params: ElicitRequestParams, ctx
):
return ElicitResult(action="accept", content={})
async with Client(mcp, elicitation_handler=elicitation_handler) as client:
result = await client.call_tool("my_tool", {})
assert result.data is None
async def test_elicitation_response_when_no_response_requested(self):
"""Test elicitation with no response type."""
mcp = FastMCP("TestServer")
@mcp.tool
async def my_tool(context: Context) -> None:
result = await context.elicit(message="", response_type=None)
return result.data # type: ignore[attr-defined]
async def elicitation_handler(message, response_type, params, ctx):
return ElicitResult(action="accept", content={"value": "hello"})
async with Client(mcp, elicitation_handler=elicitation_handler) as client:
with pytest.raises(
ToolError, match="Elicitation expected an empty response"
):
await client.call_tool("my_tool", {})
async def test_elicitation_str_response(self):
"""Test elicitation with string schema."""
mcp = FastMCP("TestServer")
@mcp.tool
async def my_tool(context: Context) -> str:
result = await context.elicit(message="", response_type=str)
return result.data # type: ignore[attr-defined]
async def elicitation_handler(message, response_type, params, ctx):
return ElicitResult(action="accept", content={"value": "hello"})
async with Client(mcp, elicitation_handler=elicitation_handler) as client:
result = await client.call_tool("my_tool", {})
assert result.data == "hello"
async def test_elicitation_int_response(self):
"""Test elicitation with number schema."""
mcp = FastMCP("TestServer")
@mcp.tool
async def my_tool(context: Context) -> int:
result = await context.elicit(message="", response_type=int)
return result.data # type: ignore[attr-defined]
async def elicitation_handler(message, response_type, params, ctx):
return ElicitResult(action="accept", content={"value": 42})
async with Client(mcp, elicitation_handler=elicitation_handler) as client:
result = await client.call_tool("my_tool", {})
assert result.data == 42
async def test_elicitation_float_response(self):
"""Test elicitation with number schema."""
mcp = FastMCP("TestServer")
@mcp.tool
async def my_tool(context: Context) -> float:
result = await context.elicit(message="", response_type=float)
return result.data # type: ignore[attr-defined]
async def elicitation_handler(message, response_type, params, ctx):
return ElicitResult(action="accept", content={"value": 3.14})
async with Client(mcp, elicitation_handler=elicitation_handler) as client:
result = await client.call_tool("my_tool", {})
assert result.data == 3.14
async def test_elicitation_bool_response(self):
"""Test elicitation with boolean schema."""
mcp = FastMCP("TestServer")
@mcp.tool
async def my_tool(context: Context) -> bool:
result = await context.elicit(message="", response_type=bool)
return result.data # type: ignore[attr-defined]
async def elicitation_handler(message, response_type, params, ctx):
return ElicitResult(action="accept", content={"value": True})
async with Client(mcp, elicitation_handler=elicitation_handler) as client:
result = await client.call_tool("my_tool", {})
assert result.data is True
async def test_elicitation_literal_response(self):
"""Test elicitation with literal schema."""
mcp = FastMCP("TestServer")
@mcp.tool
async def my_tool(context: Context) -> Literal["x", "y"]:
result = await context.elicit(message="", response_type=Literal["x", "y"]) # type: ignore
return result.data # type: ignore[attr-defined]
async def elicitation_handler(message, response_type, params, ctx):
return ElicitResult(action="accept", content={"value": "x"})
async with Client(mcp, elicitation_handler=elicitation_handler) as client:
result = await client.call_tool("my_tool", {})
assert result.data == "x"
async def test_elicitation_enum_response(self):
"""Test elicitation with enum schema."""
mcp = FastMCP("TestServer")
class ResponseEnum(Enum):
X = "x"
Y = "y"
@mcp.tool
async def my_tool(context: Context) -> ResponseEnum:
result = await context.elicit(message="", response_type=ResponseEnum)
return result.data # type: ignore[attr-defined]
async def elicitation_handler(message, response_type, params, ctx):
return ElicitResult(action="accept", content={"value": "x"})
async with Client(mcp, elicitation_handler=elicitation_handler) as client:
result = await client.call_tool("my_tool", {})
assert result.data == "x"
async def test_elicitation_list_of_strings_response(self):
"""Test elicitation with list schema."""
mcp = FastMCP("TestServer")
@mcp.tool
async def my_tool(context: Context) -> str:
result = await context.elicit(message="", response_type=["x", "y"])
return result.data # type: ignore[attr-defined]
async def elicitation_handler(message, response_type, params, ctx):
return ElicitResult(action="accept", content={"value": "x"})
async with Client(mcp, elicitation_handler=elicitation_handler) as client:
result = await client.call_tool("my_tool", {})
assert result.data == "x"
async def test_elicitation_handler_error():
"""Test error handling in elicitation handler."""
mcp = FastMCP("TestServer")
@mcp.tool
async def failing_elicit(context: Context) -> str:
try:
result = await context.elicit(message="This will fail", response_type=str)
assert result.action == "accept"
return f"Got: {result.data}"
except 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:
result = await client.call_tool("failing_elicit", {})
assert "Error:" in result.data
async def test_elicitation_multiple_calls():
"""Test multiple elicitation calls in sequence."""
mcp = FastMCP("TestServer")
@mcp.tool
async def multi_step_form(context: Context) -> str:
# First question
name_result = await context.elicit(
message="What's your name?", response_type=str
)
if name_result.action != "accept":
return "Form abandoned"
# Second question
age_result = await context.elicit(message="What's your age?", response_type=int)
if age_result.action != "accept":
return f"Hello {name_result.data}, form incomplete"
return f"Hello {name_result.data}, you are {age_result.data} years old"
call_count = 0
async def elicitation_handler(message, response_type, params, ctx):
nonlocal call_count
call_count += 1
if 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")
async with Client(mcp, elicitation_handler=elicitation_handler) as client:
result = await client.call_tool("multi_step_form", {})
assert result.data == "Hello Bob, you are 25 years old"
assert call_count == 2
@dataclass
class UserInfo:
name: str
age: int
class UserInfoTypedDict(TypedDict):
name: str
age: int
class UserInfoPydantic(BaseModel):
name: str
age: int
@pytest.mark.parametrize(
"structured_type", [UserInfo, UserInfoTypedDict, UserInfoPydantic]
)
async def test_structured_response_type(
structured_type: type[UserInfo | UserInfoTypedDict | UserInfoPydantic],
):
"""Test elicitation with dataclass response type."""
mcp = FastMCP("TestServer")
@mcp.tool
async def get_user_info(context: Context) -> str:
result = await context.elicit(
message="Please provide your information", response_type=structured_type
)
if result.action == "accept":
if isinstance(result.data, dict):
return f"User: {result.data['name']}, age: {result.data['age']}"
else:
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 type
assert (
TypeAdapter(response_type).json_schema()
== TypeAdapter(structured_type).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=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"
@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
mcp = FastMCP("TestServer")
@mcp.tool
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",
}
class TestValidation:
async def test_schema_validation_rejects_non_object(self):
"""Test that non-object schemas are rejected."""
with pytest.raises(TypeError, match="must be an object schema"):
validate_elicitation_json_schema({"type": "string"})
async def test_schema_validation_rejects_nested_objects(self):
"""Test that nested object schemas are rejected."""
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."""
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 TestPatternMatching:
async def test_pattern_matching_accept(self):
"""Test pattern matching with AcceptedElicitation."""
mcp = FastMCP("TestServer")
@mcp.tool
async def pattern_match_tool(context: Context) -> str:
result = await context.elicit("Enter your name:", response_type=str)
match result:
case AcceptedElicitation(data=name):
return f"Hello {name}!"
case DeclinedElicitation():
return "You declined"
case CancelledElicitation():
return "Cancelled"
case _:
return "Unknown result"
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:
result = await client.call_tool("pattern_match_tool", {})
assert result.data == "Hello Alice!"
async def test_pattern_matching_decline(self):
"""Test pattern matching with DeclinedElicitation."""
mcp = FastMCP("TestServer")
@mcp.tool
async def pattern_match_tool(context: Context) -> str:
result = await context.elicit("Enter your name:", response_type=str)
match result:
case AcceptedElicitation(data=name):
return f"Hello {name}!"
case DeclinedElicitation():
return "You declined"
case CancelledElicitation():
return "Cancelled"
case _:
return "Unknown result"
async def elicitation_handler(message, response_type, params, ctx):
return ElicitResult(action="decline")
async with Client(mcp, elicitation_handler=elicitation_handler) as client:
result = await client.call_tool("pattern_match_tool", {})
assert result.data == "You declined"
async def test_pattern_matching_cancel(self):
"""Test pattern matching with CancelledElicitation."""
mcp = FastMCP("TestServer")
@mcp.tool
async def pattern_match_tool(context: Context) -> str:
result = await context.elicit("Enter your name:", response_type=str)
match result:
case AcceptedElicitation(data=name):
return f"Hello {name}!"
case DeclinedElicitation():
return "You declined"
case CancelledElicitation():
return "Cancelled"
case _:
return "Unknown result"
async def elicitation_handler(message, response_type, params, ctx):
return ElicitResult(action="cancel")
async with Client(mcp, elicitation_handler=elicitation_handler) as client:
result = await client.call_tool("pattern_match_tool", {})
assert result.data == "Cancelled"
async def test_elicitation_implicit_acceptance(fastmcp_server):
"""Test that elicitation handler can return data directly without ElicitResult wrapper."""
async def elicitation_handler(message, response_type, params, ctx):
# Return data directly without wrapping in ElicitResult
# This should be treated as implicit acceptance
return response_type(name="Bob")
async with Client(
fastmcp_server, elicitation_handler=elicitation_handler
) as client:
result = await client.call_tool("ask_for_name")
assert result.data == "Hello, Bob!"
async def test_elicitation_implicit_acceptance_must_be_dict(fastmcp_server):
"""Test that elicitation handler can return data directly without ElicitResult wrapper."""
async def elicitation_handler(message, response_type, params, ctx):
# Return data directly without wrapping in ElicitResult
# This should be treated as implicit acceptance
return "Bob"
async with Client(
fastmcp_server, elicitation_handler=elicitation_handler
) as client:
with pytest.raises(
ToolError,
match="Elicitation responses must be serializable as a JSON object",
):
await client.call_tool("ask_for_name")
|