|
| 1 | +""" |
| 2 | +Test the elicitation feature using stdio transport. |
| 3 | +""" |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +from mcp.server.fastmcp import Context, FastMCP |
| 8 | +from mcp.shared.memory import create_connected_server_and_client_session |
| 9 | +from mcp.types import ElicitResult, TextContent |
| 10 | + |
| 11 | + |
| 12 | +@pytest.mark.anyio |
| 13 | +async def test_stdio_elicitation(): |
| 14 | + """Test the elicitation feature using stdio transport.""" |
| 15 | + |
| 16 | + # Create a FastMCP server with a tool that uses elicitation |
| 17 | + mcp = FastMCP(name="StdioElicitationServer") |
| 18 | + |
| 19 | + @mcp.tool(description="A tool that uses elicitation") |
| 20 | + async def ask_user(prompt: str, ctx: Context) -> str: |
| 21 | + schema = { |
| 22 | + "type": "object", |
| 23 | + "properties": { |
| 24 | + "answer": {"type": "string"}, |
| 25 | + }, |
| 26 | + "required": ["answer"], |
| 27 | + } |
| 28 | + |
| 29 | + response = await ctx.elicit( |
| 30 | + message=f"Tool wants to ask: {prompt}", |
| 31 | + requestedSchema=schema, |
| 32 | + ) |
| 33 | + return f"User answered: {response['answer']}" |
| 34 | + |
| 35 | + # Create a custom handler for elicitation requests |
| 36 | + async def elicitation_callback(context, params): |
| 37 | + # Verify the elicitation parameters |
| 38 | + if params.message == "Tool wants to ask: What is your name?": |
| 39 | + return ElicitResult(response={"answer": "Test User"}) |
| 40 | + else: |
| 41 | + raise ValueError(f"Unexpected elicitation message: {params.message}") |
| 42 | + |
| 43 | + # Use memory-based session to test with stdio transport |
| 44 | + async with create_connected_server_and_client_session( |
| 45 | + mcp._mcp_server, elicitation_callback=elicitation_callback |
| 46 | + ) as client_session: |
| 47 | + # First initialize the session |
| 48 | + result = await client_session.initialize() |
| 49 | + assert result.serverInfo.name == "StdioElicitationServer" |
| 50 | + |
| 51 | + # Call the tool that uses elicitation |
| 52 | + tool_result = await client_session.call_tool( |
| 53 | + "ask_user", {"prompt": "What is your name?"} |
| 54 | + ) |
| 55 | + |
| 56 | + # Verify the result |
| 57 | + assert len(tool_result.content) == 1 |
| 58 | + assert isinstance(tool_result.content[0], TextContent) |
| 59 | + assert tool_result.content[0].text == "User answered: Test User" |
0 commit comments