π The fast, Pythonic way to build MCP servers and clients.
Relay task elicitation through standard MCP protocol
Chris Guidry361eb08f429c
diff --git a/examples/task_elicitation.py b/examples/task_elicitation.pynew file mode 100644index 000000000..51f7b046a--- /dev/null+++ b/examples/task_elicitation.py@@ -0,0 +1,82 @@+"""+Background task elicitation demo.++A background task (Docket) that pauses mid-execution to ask the user a+question, waits for the answer, then resumes and finishes.++Works with both in-memory and Redis backends:++ # In-memory (single process, no Redis needed)+ FASTMCP_DOCKET_URL=memory:// uv run python examples/task_elicitation.py++ # Redis (distributed, needs a worker running separately)+ # Terminal 1: docker compose -f examples/tasks/docker-compose.yml up -d+ # Terminal 2: FASTMCP_DOCKET_URL=redis://localhost:24242/0 \+ # uv run fastmcp tasks worker examples/task_elicitation.py+ # Terminal 3: FASTMCP_DOCKET_URL=redis://localhost:24242/0 \+ # uv run python examples/task_elicitation.py++Requires the `docket` extra (included in dev dependencies).+"""++import asyncio+from dataclasses import dataclass++from mcp.types import TextContent++from fastmcp import Context, FastMCP+from fastmcp.client import Client+from fastmcp.server.elicitation import AcceptedElicitation++mcp = FastMCP("Task Elicitation Demo")+++@dataclass+class DinnerPrefs:+ cuisine: str+ vegetarian: bool++[email protected](task=True)+async def plan_dinner(ctx: Context) -> str:+ """Plan a dinner menu, asking the user what they're in the mood for."""++ await ctx.report_progress(0, 2, "Asking what you'd like...")++ result = await ctx.elicit(+ "What kind of dinner are you in the mood for?",+ response_type=DinnerPrefs,+ )++ if not isinstance(result, AcceptedElicitation):+ return "Dinner cancelled!"++ prefs = result.data+ await ctx.report_progress(1, 2, "Planning your menu...")+ await asyncio.sleep(1)+ await ctx.report_progress(2, 2, "Done!")++ veg = "vegetarian " if prefs.vegetarian else ""+ return f"Tonight's menu: a lovely {veg}{prefs.cuisine} dinner!"+++async def handle_elicitation(message, response_type, params, context):+ """Handle elicitation requests from background tasks."""+ print(f" Server asks: {message}")+ print(" Responding with: cuisine=Thai, vegetarian=True")+ return DinnerPrefs(cuisine="Thai", vegetarian=True)+++async def main():+ async with Client(mcp, elicitation_handler=handle_elicitation) as client:+ print("Starting background task...")+ task = await client.call_tool("plan_dinner", {}, task=True)+ print(f" task_id = {task.task_id}\n")++ result = await task.result()+ assert isinstance(result.content[0], TextContent)+ print(f"\nResult: {result.content[0].text}")+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/src/fastmcp/server/context.py b/src/fastmcp/server/context.pyindex a39817e58..d65e87c43 100644--- a/src/fastmcp/server/context.py+++ b/src/fastmcp/server/context.py@@ -1133,7 +1133,7 @@ class Context:return await elicit_for_task(task_id=self._task_id, # type: ignore[arg-type]- session=self.session,+ session=self._session,message=message,schema=schema,fastmcp=self.fastmcp,diff --git a/src/fastmcp/server/tasks/elicitation.py b/src/fastmcp/server/tasks/elicitation.pyindex 299382df6..1a85da9f8 100644--- a/src/fastmcp/server/tasks/elicitation.py+++ b/src/fastmcp/server/tasks/elicitation.py@@ -41,7 +41,7 @@ ELICIT_TTL_SECONDS = 3600async def elicit_for_task(task_id: str,- session: ServerSession,+ session: ServerSession | None,message: str,schema: dict[str, Any],fastmcp: FastMCP,diff --git a/src/fastmcp/server/tasks/notifications.py b/src/fastmcp/server/tasks/notifications.pyindex 2c65e31e1..c47f8e484 100644--- a/src/fastmcp/server/tasks/notifications.py+++ b/src/fastmcp/server/tasks/notifications.py@@ -117,7 +117,9 @@ async def notification_subscriber_loop(try:# Reconstruct and send MCP notification- await _send_mcp_notification(session, notification_dict)+ await _send_mcp_notification(+ session, notification_dict, session_id, docket+ )logger.debug("Delivered notification to session %s (attempt %d)",session_id,@@ -159,12 +161,20 @@ async def notification_subscriber_loop(async def _send_mcp_notification(session: ServerSession,notification_dict: dict[str, Any],+ session_id: str,+ docket: Docket,) -> None:"""Reconstruct MCP notification from dict and send to session.+ For input_required notifications with elicitation metadata, also sends+ a standard elicitation/create request to the client and relays the+ response back to the worker via Redis.+Args:session: MCP ServerSessionnotification_dict: Notification as dict (method, params, _meta)+ session_id: Session identifier (for elicitation relay)+ docket: Docket instance (for elicitation relay)"""method = notification_dict.get("method", "notifications/tasks/status")if method != "notifications/tasks/status":@@ -181,6 +191,97 @@ async def _send_mcp_notification(await session.send_notification(server_notification)+ # If this is an input_required notification with elicitation metadata,+ # relay the elicitation to the client via standard elicitation/create+ params = notification_dict.get("params", {})+ if params.get("status") == "input_required":+ meta = notification_dict.get("_meta", {})+ related_task = meta.get("modelcontextprotocol.io/related-task", {})+ elicitation = related_task.get("elicitation")+ if elicitation:+ task_id = params["taskId"]+ asyncio.create_task( # noqa: RUF006+ _relay_elicitation(session, session_id, task_id, elicitation, docket),+ name=f"elicitation-relay-{task_id[:8]}",+ )+++async def _relay_elicitation(+ session: ServerSession,+ session_id: str,+ task_id: str,+ elicitation: dict[str, Any],+ docket: Docket,+) -> None:+ """Relay elicitation from a background task worker to the client.++ Sends a standard elicitation/create request to the client session, then+ pushes the response to Redis so the blocked worker can resume.++ Args:+ session: MCP ServerSession+ session_id: Session identifier+ task_id: Background task ID+ elicitation: Elicitation metadata (message, requestedSchema)+ docket: Docket instance for Redis access+ """+ from fastmcp.server.tasks.elicitation import (+ ELICIT_RESPONSE_KEY,+ ELICIT_STATUS_KEY,+ ELICIT_TTL_SECONDS,+ )++ try:+ result = await session.elicit(+ message=elicitation["message"],+ requestedSchema=elicitation["requestedSchema"],+ )++ response_key = docket.key(+ ELICIT_RESPONSE_KEY.format(session_id=session_id, task_id=task_id)+ )+ status_key = docket.key(+ ELICIT_STATUS_KEY.format(session_id=session_id, task_id=task_id)+ )++ response = {+ "action": result.action,+ "content": result.content,+ }++ async with docket.redis() as redis:+ await redis.lpush( # type: ignore[invalid-await]+ response_key, json.dumps(response)+ )+ await redis.expire(response_key, ELICIT_TTL_SECONDS)+ await redis.set(status_key, "responded", ex=ELICIT_TTL_SECONDS)++ logger.debug(+ "Relayed elicitation response for task %s (action=%s)",+ task_id,+ result.action,+ )+ except Exception as e:+ logger.warning("Failed to relay elicitation for task %s: %s", task_id, e)+ # Push a cancel response so the worker's BLPOP doesn't block forever+ try:+ response_key = docket.key(+ ELICIT_RESPONSE_KEY.format(session_id=session_id, task_id=task_id)+ )+ cancel = {"action": "cancel", "content": None}+ async with docket.redis() as redis:+ await redis.lpush( # type: ignore[invalid-await]+ response_key, json.dumps(cancel)+ )+ await redis.expire(response_key, ELICIT_TTL_SECONDS)+ except Exception as cancel_error:+ logger.warning(+ "Failed to push cancel response for task %s "+ "(worker may block until TTL): %s",+ task_id,+ cancel_error,+ )+# =============================================================================# Subscriber Managementdiff --git a/tests/server/tasks/test_context_background_task.py b/tests/server/tasks/test_context_background_task.pyindex 219a7ae21..2b5a1efa9 100644--- a/tests/server/tasks/test_context_background_task.py+++ b/tests/server/tasks/test_context_background_task.py@@ -13,6 +13,7 @@ from mcp import ServerSessionfrom fastmcp import FastMCPfrom fastmcp.client import Client+from fastmcp.client.elicitation import ElicitResultfrom fastmcp.server.context import Contextfrom fastmcp.server.elicitation import AcceptedElicitation, DeclinedElicitationfrom fastmcp.server.tasks.elicitation import handle_task_input@@ -227,67 +228,31 @@ class TestBackgroundTaskIntegration:assert captured["is_background"] is Trueasync def test_elicit_accept_flow(self):- """E2E: tool elicits input, client accepts, tool receives value.-- Flow:- 1. Tool calls ctx.elicit("name?", str) β blocks waiting for input- 2. Client polls handle_task_input(action="accept", content={"value":"Bob"})- 3. Tool resumes with AcceptedElicitation(data="Bob")- """+ """E2E: tool elicits input, client accepts via elicitation_handler."""mcp = FastMCP("elicit-accept-test")- elicit_started = asyncio.Event()- captured: dict[str, str | None] = {"task_id": None, "session_id": None}@mcp.tool(task=True)async def ask_name(ctx: Context) -> str:- captured["task_id"] = ctx.task_id- captured["session_id"] = ctx.session_id- elicit_started.set()-result = await ctx.elicit("What is your name?", str)if isinstance(result, AcceptedElicitation):return f"Hello, {result.data}!"return "No name provided"- async with Client(mcp) as client:- task = await client.call_tool("ask_name", {}, task=True)- await asyncio.wait_for(elicit_started.wait(), timeout=5.0)-- assert captured["task_id"] is not None- assert captured["session_id"] is not None-- # Poll until the "waiting" status is stored in Redis- success = False- for _ in range(40):- success = await handle_task_input(- task_id=captured["task_id"],- session_id=captured["session_id"],- action="accept",- content={"value": "Bob"},- fastmcp=mcp,- )- if success:- break- await asyncio.sleep(0.05)-- assert success is True, "handle_task_input should succeed within 2s"+ async def handler(message, response_type, params, ctx):+ return ElicitResult(action="accept", content={"value": "Bob"})+ async with Client(mcp, elicitation_handler=handler) as client:+ task = await client.call_tool("ask_name", {}, task=True)await task.wait(timeout=10.0)result = await task.result()assert result.data == "Hello, Bob!"async def test_elicit_decline_flow(self):- """E2E: tool elicits input, client declines, tool gets DeclinedElicitation."""+ """E2E: tool elicits input, client declines via elicitation_handler."""mcp = FastMCP("elicit-decline-test")- elicit_started = asyncio.Event()- captured: dict[str, str | None] = {"task_id": None, "session_id": None}@mcp.tool(task=True)async def optional_input(ctx: Context) -> str:- captured["task_id"] = ctx.task_id- captured["session_id"] = ctx.session_id- elicit_started.set()-result = await ctx.elicit("Want to provide a name?", str)if isinstance(result, DeclinedElicitation):return "User declined"@@ -295,34 +260,17 @@ class TestBackgroundTaskIntegration:return f"Got: {result.data}"return "Cancelled"- async with Client(mcp) as client:- task = await client.call_tool("optional_input", {}, task=True)- await asyncio.wait_for(elicit_started.wait(), timeout=5.0)-- assert captured["task_id"] is not None- assert captured["session_id"] is not None-- success = False- for _ in range(40):- success = await handle_task_input(- task_id=captured["task_id"],- session_id=captured["session_id"],- action="decline",- content=None,- fastmcp=mcp,- )- if success:- break- await asyncio.sleep(0.05)-- assert success is True+ async def handler(message, response_type, params, ctx):+ return ElicitResult(action="decline")+ async with Client(mcp, elicitation_handler=handler) as client:+ task = await client.call_tool("optional_input", {}, task=True)await task.wait(timeout=10.0)result = await task.result()assert result.data == "User declined"async def test_elicit_with_pydantic_model(self):- """E2E: tool elicits structured Pydantic input, data round-trips correctly."""+ """E2E: tool elicits structured Pydantic input via elicitation_handler."""from pydantic import BaseModelclass UserInfo(BaseModel):@@ -330,43 +278,20 @@ class TestBackgroundTaskIntegration:age: intmcp = FastMCP("elicit-pydantic-test")- elicit_started = asyncio.Event()- captured: dict[str, str | None] = {"task_id": None, "session_id": None}@mcp.tool(task=True)async def get_user_info(ctx: Context) -> str:- captured["task_id"] = ctx.task_id- captured["session_id"] = ctx.session_id- elicit_started.set()-result = await ctx.elicit("Provide user info", UserInfo)if isinstance(result, AcceptedElicitation):assert isinstance(result.data, UserInfo)return f"{result.data.name} is {result.data.age}"return "No info"- async with Client(mcp) as client:- task = await client.call_tool("get_user_info", {}, task=True)- await asyncio.wait_for(elicit_started.wait(), timeout=5.0)-- assert captured["task_id"] is not None- assert captured["session_id"] is not None-- success = False- for _ in range(40):- success = await handle_task_input(- task_id=captured["task_id"],- session_id=captured["session_id"],- action="accept",- content={"name": "Alice", "age": 30},- fastmcp=mcp,- )- if success:- break- await asyncio.sleep(0.05)-- assert success is True+ async def handler(message, response_type, params, ctx):+ return ElicitResult(action="accept", content={"name": "Alice", "age": 30})+ async with Client(mcp, elicitation_handler=handler) as client:+ task = await client.call_tool("get_user_info", {}, task=True)await task.wait(timeout=10.0)result = await task.result()assert result.data == "Alice is 30"diff --git a/tests/server/tasks/test_notifications.py b/tests/server/tasks/test_notifications.pyindex 07b2b7f3b..34b169bb5 100644--- a/tests/server/tasks/test_notifications.py+++ b/tests/server/tasks/test_notifications.py@@ -7,14 +7,14 @@ No mocking of Redis, sessions, or Docket internals.import asyncio-import mcp.types+import mcp.types as mcp_typesfrom fastmcp import FastMCPfrom fastmcp.client import Client+from fastmcp.client.elicitation import ElicitResultfrom fastmcp.client.messages import MessageHandlerfrom fastmcp.server.context import Contextfrom fastmcp.server.elicitation import AcceptedElicitation-from fastmcp.server.tasks.elicitation import handle_task_inputfrom fastmcp.server.tasks.notifications import (get_subscriber_count,)@@ -25,12 +25,12 @@ class NotificationCaptureHandler(MessageHandler):def __init__(self) -> None:super().__init__()- self.notifications: list[mcp.types.ServerNotification] = []+ self.notifications: list[mcp_types.ServerNotification] = []- async def on_notification(self, message: mcp.types.ServerNotification) -> None:+ async def on_notification(self, message: mcp_types.ServerNotification) -> None:self.notifications.append(message)- def for_method(self, method: str) -> list[mcp.types.ServerNotification]:+ def for_method(self, method: str) -> list[mcp_types.ServerNotification]:return [notificationfor notification in self.notifications@@ -41,58 +41,60 @@ class NotificationCaptureHandler(MessageHandler):class TestNotificationIntegration:"""Integration tests for the notification queue using real Docket memory backend.- The elicitation flow implicitly validates the full notification pipeline:- 1. Tool calls ctx.elicit() β stores request in Redis β pushes notification- 2. Subscriber picks up notification β sends MCP notification to client- 3. Client calls handle_task_input() β LPUSH response β BLPOP wakes tool+ The elicitation flow validates the full notification pipeline:+ 1. Tool calls ctx.elicit() -> stores request in Redis -> pushes notification+ 2. Subscriber picks up notification -> sends MCP notification to client+ 3. Subscriber relays elicitation/create to client -> handler responds+ 4. Relay pushes response to Redis -> BLPOP wakes tool"""async def test_notification_delivered_during_elicitation(self):- """Full E2E: notification queue delivers input_required metadata to client."""+ """Full E2E: notification queue delivers input_required metadata to client.++ The elicitation relay handles the response via the client's+ elicitation_handler. We verify both the notification metadata+ structure and the end-to-end elicitation flow.+ """mcp = FastMCP("notification-test")notification_handler = NotificationCaptureHandler()- elicit_started = asyncio.Event()- captured: dict[str, str | None] = {"task_id": None, "session_id": None}@mcp.tool(task=True)async def elicit_tool(ctx: Context) -> str:- captured["task_id"] = ctx.task_id- captured["session_id"] = ctx.session_id- elicit_started.set()-result = await ctx.elicit("Enter value", str)if isinstance(result, AcceptedElicitation):return f"got: {result.data}"return "no value"- async with Client(mcp, message_handler=notification_handler) as client:+ async def elicitation_handler(message, response_type, params, ctx):+ return ElicitResult(action="accept", content={"value": "hello"})++ async with Client(+ mcp,+ message_handler=notification_handler,+ elicitation_handler=elicitation_handler,+ ) as client:task = await client.call_tool("elicit_tool", {}, task=True)- await asyncio.wait_for(elicit_started.wait(), timeout=5.0)- assert captured["task_id"] is not None- assert captured["session_id"] is not None+ await task.wait(timeout=10.0)+ result = await task.result()+ assert result.data == "got: hello"- notification: mcp.types.ServerNotification | None = None- for _ in range(40):- candidates = notification_handler.for_method(- "notifications/tasks/status"+ # Verify the input_required notification was delivered with metadata+ notification: mcp_types.ServerNotification | None = None+ candidates = notification_handler.for_method("notifications/tasks/status")+ for candidate in reversed(candidates):+ candidate_meta = getattr(candidate.root, "_meta", None)+ related_task = (+ candidate_meta.get("modelcontextprotocol.io/related-task")+ if isinstance(candidate_meta, dict)+ else None)- for candidate in reversed(candidates):- candidate_meta = getattr(candidate.root, "_meta", None)- related_task = (- candidate_meta.get("modelcontextprotocol.io/related-task")- if isinstance(candidate_meta, dict)- else None- )- if (- isinstance(related_task, dict)- and related_task.get("status") == "input_required"- ):- notification = candidate- break- if notification is not None:+ if (+ isinstance(related_task, dict)+ and related_task.get("status") == "input_required"+ ):+ notification = candidatebreak- await asyncio.sleep(0.05)assert notification is not None, "expected notifications/tasks/status"task_meta = getattr(notification.root, "_meta", None)@@ -100,7 +102,7 @@ class TestNotificationIntegration:related_task = task_meta.get("modelcontextprotocol.io/related-task")assert isinstance(related_task, dict)- assert related_task.get("taskId") == captured["task_id"]+ assert related_task.get("taskId") == task.task_idassert related_task.get("status") == "input_required"elicitation = related_task.get("elicitation")@@ -109,25 +111,6 @@ class TestNotificationIntegration:assert isinstance(elicitation.get("requestId"), str)assert isinstance(elicitation.get("requestedSchema"), dict)- success = False- for _ in range(40):- success = await handle_task_input(- task_id=captured["task_id"],- session_id=captured["session_id"],- action="accept",- content={"value": "hello"},- fastmcp=mcp,- )- if success:- break- await asyncio.sleep(0.05)-- assert success is True-- await task.wait(timeout=10.0)- result = await task.result()- assert result.data == "got: hello"-async def test_subscriber_started_and_cleaned_up(self):"""Subscriber starts during background task and stops when client disconnects."""mcp = FastMCP("subscriber-test")diff --git a/tests/server/tasks/test_task_elicitation_relay.py b/tests/server/tasks/test_task_elicitation_relay.pynew file mode 100644index 000000000..42362edd2--- /dev/null+++ b/tests/server/tasks/test_task_elicitation_relay.py@@ -0,0 +1,191 @@+"""Tests for background task elicitation relay (notifications.py).++The relay bridges distributed background tasks to clients via the standard+MCP elicitation/create protocol. When a worker calls ctx.elicit(), the+notification subscriber detects the input_required notification and sends+an elicitation/create request to the client session. The client's+elicitation_handler fires, and the relay pushes the response to Redis+for the blocked worker.++These tests use Client(mcp) with the real memory:// Docket backend.+"""++import asyncio+from dataclasses import dataclass++from pydantic import BaseModel++from fastmcp import FastMCP+from fastmcp.client import Client+from fastmcp.client.elicitation import ElicitResult+from fastmcp.server.context import Context+from fastmcp.server.elicitation import (+ AcceptedElicitation,+ CancelledElicitation,+ DeclinedElicitation,+)+++class TestElicitationRelay:+ """E2E tests for elicitation flowing through the standard MCP protocol."""++ async def test_accept_via_elicitation_handler(self):+ """Tool elicits, client handler accepts, tool gets the value."""+ mcp = FastMCP("relay-accept")++ @mcp.tool(task=True)+ async def ask_name(ctx: Context) -> str:+ result = await ctx.elicit("What is your name?", str)+ if isinstance(result, AcceptedElicitation):+ return f"Hello, {result.data}!"+ return "No name"++ async def handler(message, response_type, params, ctx):+ assert message == "What is your name?"+ return ElicitResult(action="accept", content={"value": "Alice"})++ async with Client(mcp, elicitation_handler=handler) as client:+ task = await client.call_tool("ask_name", {}, task=True)+ result = await task.result()+ assert result.data == "Hello, Alice!"++ async def test_decline_via_elicitation_handler(self):+ """Tool elicits, client handler declines, tool gets DeclinedElicitation."""+ mcp = FastMCP("relay-decline")++ @mcp.tool(task=True)+ async def optional_input(ctx: Context) -> str:+ result = await ctx.elicit("Provide a name?", str)+ if isinstance(result, DeclinedElicitation):+ return "User declined"+ if isinstance(result, AcceptedElicitation):+ return f"Got: {result.data}"+ return "Cancelled"++ async def handler(message, response_type, params, ctx):+ return ElicitResult(action="decline")++ async with Client(mcp, elicitation_handler=handler) as client:+ task = await client.call_tool("optional_input", {}, task=True)+ result = await task.result()+ assert result.data == "User declined"++ async def test_cancel_via_elicitation_handler(self):+ """Tool elicits, client handler cancels, tool gets CancelledElicitation."""+ mcp = FastMCP("relay-cancel")++ @mcp.tool(task=True)+ async def cancellable(ctx: Context) -> str:+ result = await ctx.elicit("Input?", str)+ if isinstance(result, CancelledElicitation):+ return "Cancelled"+ return "Not cancelled"++ async def handler(message, response_type, params, ctx):+ return ElicitResult(action="cancel")++ async with Client(mcp, elicitation_handler=handler) as client:+ task = await client.call_tool("cancellable", {}, task=True)+ result = await task.result()+ assert result.data == "Cancelled"++ async def test_dataclass_round_trips_through_relay(self):+ """Structured dataclass type round-trips through the relay."""+ mcp = FastMCP("relay-dataclass")++ @dataclass+ class UserInfo:+ name: str+ age: int++ @mcp.tool(task=True)+ async def get_user(ctx: Context) -> str:+ result = await ctx.elicit("Provide user info", UserInfo)+ if isinstance(result, AcceptedElicitation):+ assert isinstance(result.data, UserInfo)+ return f"{result.data.name} is {result.data.age}"+ return "No info"++ async def handler(message, response_type, params, ctx):+ return ElicitResult(action="accept", content={"name": "Bob", "age": 30})++ async with Client(mcp, elicitation_handler=handler) as client:+ task = await client.call_tool("get_user", {}, task=True)+ result = await task.result()+ assert result.data == "Bob is 30"++ async def test_pydantic_model_round_trips_through_relay(self):+ """Structured Pydantic model round-trips through the relay."""+ mcp = FastMCP("relay-pydantic")++ class Config(BaseModel):+ host: str+ port: int++ @mcp.tool(task=True)+ async def get_config(ctx: Context) -> str:+ result = await ctx.elicit("Server config?", Config)+ if isinstance(result, AcceptedElicitation):+ assert isinstance(result.data, Config)+ return f"{result.data.host}:{result.data.port}"+ return "No config"++ async def handler(message, response_type, params, ctx):+ return ElicitResult(+ action="accept", content={"host": "localhost", "port": 8080}+ )++ async with Client(mcp, elicitation_handler=handler) as client:+ task = await client.call_tool("get_config", {}, task=True)+ result = await task.result()+ assert result.data == "localhost:8080"++ async def test_multiple_sequential_elicitations(self):+ """Tool calls ctx.elicit() twice, both go through the relay."""+ mcp = FastMCP("relay-multi")++ @mcp.tool(task=True)+ async def two_questions(ctx: Context) -> str:+ r1 = await ctx.elicit("First name?", str)+ r2 = await ctx.elicit("Last name?", str)+ if isinstance(r1, AcceptedElicitation) and isinstance(+ r2, AcceptedElicitation+ ):+ return f"{r1.data} {r2.data}"+ return "Incomplete"++ call_count = 0++ async def handler(message, response_type, params, ctx):+ nonlocal call_count+ call_count += 1+ if call_count == 1:+ assert message == "First name?"+ return ElicitResult(action="accept", content={"value": "Jane"})+ else:+ assert message == "Last name?"+ return ElicitResult(action="accept", content={"value": "Doe"})++ async with Client(mcp, elicitation_handler=handler) as client:+ task = await client.call_tool("two_questions", {}, task=True)+ result = await task.result()+ assert result.data == "Jane Doe"+ assert call_count == 2++ async def test_no_elicitation_handler_returns_cancel(self):+ """Without an elicitation_handler, the relay fails and task gets cancel."""+ mcp = FastMCP("relay-no-handler")++ @mcp.tool(task=True)+ async def needs_input(ctx: Context) -> str:+ result = await ctx.elicit("Input?", str)+ if isinstance(result, CancelledElicitation):+ return "Cancelled as expected"+ if isinstance(result, AcceptedElicitation):+ return f"Got: {result.data}"+ return "Other"++ async with Client(mcp) as client:+ task = await client.call_tool("needs_input", {}, task=True)+ result = await asyncio.wait_for(task.result(), timeout=15.0)+ assert result.data == "Cancelled as expected"