Ask the user in the middle of a call
Unos 32 minutos de lectura, con 6 ejemplos en 9 secciones.
Traducido con IA. Verificado por personas en inglés. Cómo hacemos los libros
Traducido del libro en inglés, edición 2026.11.14. Lee el original
En esta página
- See why a stateless server can't wait for an answer
- Devolver una solicitud de entrada en lugar de un resultado
- Reanudar la llamada con la respuesta
- Ask for structured input with elicitation
- Envía los pasos sensibles a una URL
- Mantén el estado de ida y vuelta a salvo de manipulaciones
- Choose elicitation or a tool argument
- Qué sale mal en producción
- Decisiones que tomó este capítulo
Esta parte aún no está traducida, así que está en inglés.
By the end of this chapter you can make the shop's refund tool stop in the middle of a call, ask the person at the host to confirm a refund, and carry on with the answer, using Model Context Protocol elicitation inside a Multi Round-Trip Request on a server that keeps no call open while it waits. This chapter's claims are true of revision 2026-07-28 of the specification and of mcp 2.3.0, the Python SDK.
At the shop, where refunds come in as tickets for the support team's host, the refund policy requires a support lead to confirm any refund above €150.00 before it's issued. The shop's API enforces that limit by holding such a refund with the status needs_confirmation. In Design tools a model can use, the issue_refund tool passes that hold back to the model and stops there, so a refund the model was right to make waits until someone finds it in the back office.
The person who could confirm the refund is already at the host, reading the conversation. The tool needs a way to put one question to that person in the middle of the call and carry on with the answer. The Model Context Protocol (MCP) has a name for that, elicitation: a structured question that a server sends and the client shows the user. At the pinned revision, the question travels inside a Multi Round-Trip Request, a pattern in which one call can end with a question instead of a result. The server answers the call with an input request instead of a result, and the client calls again with the answer.
Each server example in this chapter runs itself, as the earlier chapters' examples do. Run with no arguments, the file starts a client, and that client launches the same file with --serve over stdio. The shop's API runs on loopback beside them.
Esta parte aún no está traducida, así que está en inglés.
See why a stateless server can't wait for an answer
Before the pinned revision, a server that needed the user's input sent its own request to the client, elicitation/create, and waited for the reply while the tool call stayed open. The pinned revision removed that pattern. The specification says servers MUST send their requests to the client, elicitation/create among them, through the Multi Round-Trip Request pattern. It calls the old pattern a breaking change that is no longer supported (Multi Round-Trip Requests). Elicitation is one of the requests this chapter uses, and it isn't deprecated. The other two, sampling/createMessage and roots/list, are deprecated, and Replace sampling, roots and logging gives their replacements: a direct call to a model provider's API, and tool parameters, resource URIs or server configuration (deprecated features).
The reason is statelessness. At the pinned revision there's no handshake and no session, and each request carries its own version and capabilities in _meta (Carry the version and capabilities on every request). A request that waits on a reply from the client ties one server process to one open connection for as long as a person takes to answer. The specification's aim is a server that can ask for input without a shared storage layer across server instances or stateful load balancing (Multi Round-Trip Requests). The proposal behind the change, SEP-2322, says that Streamable HTTP then depends less on long-lived streams, which cause problems in many environments (SEP-2322).
The Python SDK still offers the old call. ctx.elicit() sends elicitation/create as a request from the server, and on a connection at the pinned revision it fails with NoBackChannelError, an Invalid Request error, because the protocol forbids server-initiated requests there (mcp/shared/transport_context.py, mcp/shared/exceptions.py).
The first attempt at a confirmation is written that way. Its server takes chapter 3's tools from a shared module, lib.confirmations, which holds what this chapter's servers have in common: those tools, the key that protects round-trip state, and a record of answers already used. Its issue_refund calls chapter 3's version, which posts the refund to the shop's API. If the API holds the refund, the tool calls ctx.elicit() and waits. The client has an elicitation callback that plays a scripted user, who would release the refund if asked. The client quotes order O-2289, whose whole refund is above the limit, and calls issue_refund.
1"""The 2025 way to confirm a refund, which fails at revision 2026-07-28: issue_refund calls ctx.elicit() and waits,2but the protocol gives the server no channel back to the client. The printed error code and the count of questions3the user saw show the failure, before anyone is asked."""4import asyncio5import sys67from mcp import Client, MCPError8from mcp.server.mcpserver import Context9from mcp.types import ElicitResult10from pydantic import BaseModel1112from lib import confirmations, loopback, shop_api, shop_tools1314server, held = confirmations.shop_server() # chapter 3's other tools; held is chapter 3's issue_refund15asked = [] # every question that reached the user161718class Release(BaseModel):19 release: bool202122@server.tool(title="Issue a refund", description=shop_tools.DESCRIPTIONS["issue_refund"], annotations=held.annotations)23async def issue_refund(quote_id: confirmations.QuoteId, ctx: Context) -> shop_tools.Refund:24 refund = held.fn(quote_id)25 if refund.status == "needs_confirmation": # ask, and hold the call open until the answer comes back26 answer = await ctx.elicit(f"Refund {refund.amount} on order {refund.order_id}?", Release)27 if answer.action == "accept" and answer.data.release:28 return confirmations.release(refund)29 return refund303132async def say_yes(context, params) -> ElicitResult: # a scripted user, who would release the refund33 asked.append(params.message)34 return ElicitResult(action="accept", content={"release": True})353637async def main() -> None:38 with loopback.serve(shop_api.create_app()) as base_url:39 async with Client(confirmations.launch(__file__, base_url), elicitation_callback=say_yes) as client: # starts this file with --serve40 print("protocol revision:", client.protocol_version)41 quote = (await client.call_tool("quote_refund", {"order_id": "O-2289"})).structured_content42 try:43 await client.call_tool("issue_refund", {"quote_id": quote["quote_id"]})44 except MCPError as error:45 print("error code:", error.error.code)46 print("error message:", error.error.message)47 print("questions the user saw:", len(asked))484950server.run() if "--serve" in sys.argv else asyncio.run(main()) # the client runs this file with --serve; run directly, it starts the client
python refund-needs-confirmation.pyprotocol revision: 2026-07-28
error code: -32600
error message: Cannot send 'elicitation/create': this transport context has no back-channel for server-initiated requests.
questions the user saw: 0
The call failed with JSON-RPC error -32600, Invalid Request, and the message "Cannot send 'elicitation/create': this transport context has no back-channel for server-initiated requests." The scripted user was asked 0 questions. Nobody saw the refund. Because the failure is a protocol error, not a tool result, the model never saw it either (Report failures as tool results). The refund stays held in the shop's API, as it did in chapter 3.
The tool's own logic isn't what failed. It asked the protocol for something the pinned revision doesn't have, a channel from server to client in the middle of a call. Any code that waits inside a tool call for an answer runs into the same wall, whatever SDK it uses.
Working rule: Never wait inside a tool call for something only the client can give you. On a connection at the pinned revision, treat every call to ctx.elicit() or ctx.elicit_url() as a bug, and return an input request instead, as the next section does. Keep the old call only on a server that must also answer 2025-era clients, and only behind a check of ctx.protocol_version (Serve old and new clients through the window).
Devolver una solicitud de entrada en lugar de un resultado
La llamada que falló en la sección anterior necesitaba un canal que el protocolo no tiene. Una Multi Round-Trip Request (solicitud de ida y vuelta múltiple) invierte la pregunta. En lugar de un resultado, el servidor devuelve un InputRequiredResult, cuyo resultType es "input_required", y la llamada termina ahí. Dos campos llevan el resto. inputRequests asocia claves que elige el servidor con las solicitudes que necesita que se respondan, y requestState es una cadena opaca que el cliente debe devolver. El servidor DEBE incluir al menos uno de los dos (Solicitudes de ida y vuelta múltiple; esquema, InputRequiredResult).
Tres reglas limitan qué puede pedir un servidor y cuándo. Solo tools/call, prompts/get y resources/read pueden responder con una solicitud de entrada, y los servidores NO DEBEN enviar una en ninguna otra solicitud. Un servidor NO DEBE incluir una solicitud de elicitation/create a menos que el cliente haya declarado la capacidad elicitation (Solicitudes de ida y vuelta múltiple). Y como todo resultado en la revisión fijada lleva resultType, un cliente trata la ausencia de ese campo, que envía un servidor más antiguo, como "complete", y trata cualquier otro valor no reconocido como inválido (visión general).
issue_refund sigue llamando primero a la versión del capítulo 3, de modo que la API de la tienda decide, con el límite de la política, si un reembolso necesita confirmación, y el servidor nunca repite el límite. Dentro de un mismo proceso del servidor, la herramienta del capítulo 3 devuelve el mismo reembolso para el mismo quote_id cada vez, lo que hace seguro llamarla en cada ronda. Entre procesos, eso no se cumple, como explica Qué sale mal en producción bajo «Registros que solo ve un proceso». Cuando la API retiene el reembolso, la herramienta comprueba que el cliente declaró elicitación en modo formulario y luego construye la solicitud de entrada a mano: un ElicitRequest bajo la clave confirm, cuyo formulario tiene un único campo obligatorio de sí o no, release, y cuyo mensaje indica el importe y el pedido. Su requestState es el ID del reembolso. Cuando llega el reintento, la herramienta comprueba que el estado nombra el reembolso que encontró, y usa el estado como clave de su registro de respuestas.
El servidor pasa request_state_security= a MCPServer, con la política que construye confirmations.state_security(), de modo que varias réplicas puedan compartir después una misma clave. En estos ejemplos esa política es la predeterminada del SDK, una clave creada al iniciarse el proceso. Un cliente declara la elicitación pasando una función de retorno, y llama a la herramienta mediante client.session.call_tool(..., allow_input_required=True), que devuelve la solicitud de entrada en lugar de responderla.
1"""issue_refund answers a held refund with an input request instead of a result, which asks a person to confirm it.2The prose's points rest on the result type line, the one input request under confirm with its message, and the3assert, which fails the run if the SDK doesn't seal the request state."""4import asyncio5import sys67from mcp import Client8from mcp.server.mcpserver import Context9from mcp.server.mcpserver.exceptions import ToolError10from mcp.types import ElicitRequest, ElicitRequestFormParams, InputRequiredResult1112from lib import confirmations, loopback, shop_api, shop_tools1314server, held = confirmations.shop_server() # chapter 3's other tools; held is chapter 3's issue_refund15answered = confirmations.OnceOnly() # the round-trip states already answered, so a replayed answer fails161718@server.tool(title="Issue a refund", description=shop_tools.DESCRIPTIONS["issue_refund"], annotations=held.annotations)19def issue_refund(quote_id: confirmations.QuoteId, ctx: Context) -> shop_tools.Refund | InputRequiredResult:20 refund = held.fn(quote_id) # the same quote_id always gives the same refund21 if refund.status != "needs_confirmation":22 return refund23 answer = (ctx.input_responses or {}).get("confirm") # the answer comes back under the key the tool asked with24 if answer is None or ctx.request_state != refund.refund_id: # first round, or a question never asked25 confirmations.require_elicitation(ctx, "form") # ask only what the client declared it can show26 ask = ElicitRequestFormParams(requested_schema=confirmations.RELEASE_FORM, message=f"Refund {refund.amount} on "27 f"order {refund.order_id}? It is above the policy limit, so a lead must confirm it.")28 return InputRequiredResult(input_requests={"confirm": ElicitRequest(params=ask)},29 request_state=refund.refund_id) # the refund's ID rides in the state the SDK seals30 if answer.action != "accept" or not (answer.content or {}).get("release"):31 raise ToolError(f"Nobody confirmed refund {refund.refund_id}, so the shop's API still holds it.")32 if not answered.claim(ctx.request_state): # sealing can't stop a replay; this record does33 raise ToolError(f"Refund {refund.refund_id} was already confirmed. Don't send the same answer again.")34 return confirmations.release(refund)353637async def main() -> None:38 with loopback.serve(shop_api.create_app()) as base_url:39 async with Client(confirmations.launch(__file__, base_url), # starts this file with --serve over stdio40 elicitation_callback=confirmations.say_yes) as client: # declares elicitation41 quote = (await client.call_tool("quote_refund", {"order_id": "O-2289"})).structured_content42 result = await client.session.call_tool("issue_refund", {"quote_id": quote["quote_id"]},43 allow_input_required=True) # return the input request, not an answer to it44 print("result type:", result.result_type)45 for key, request in result.input_requests.items():46 print(f"input request {key}:", request.method, request.params.mode)47 print("message:", request.params.message)48 # the SDK's sealed-token prefix: a request state that starts with it was sealed on its way out49 assert result.request_state.startswith("v1.")505152server.run() if "--serve" in sys.argv else asyncio.run(main()) # the client runs this file with --serve; run directly, it starts the client
python refund-asks-to-confirm.pyresult type: input_required
input request confirm: elicitation/create form
message: Refund 180.00 on order O-2289? It is above the policy limit, so a lead must confirm it.
La llamada volvió con tipo de resultado input_required, y su única solicitud de entrada es elicitation/create form. El mensaje dice «Refund 180.00 on order O-2289? It is above the policy limit, so a lead must confirm it.». Esa es la pregunta que vería el usuario del host.
La pregunta llega a quien esté frente al host, así que la respuesta es tan fiable como el host. Un accept no demuestra que respondiera un responsable de soporte, ni siquiera que lo hiciera una persona, pues las funciones de retorno programadas de este capítulo responden por código. Los servidores DEBEN además vincular las solicitudes de elicitación a la identidad del cliente y del usuario, añade la especificación (elicitación). Por stdio, como aquí, el usuario es el usuario local del host, que lanzó el servidor, y el servidor no tiene otra identidad a la que vincularla, así que la tienda confía en que el host presente la pregunta a un responsable. Por HTTP, el servidor vincula la pregunta al llamador autenticado, y el sello del SDK ya incluye al llamador de OAuth, de modo que el reintento de otro usuario falla. Un servidor que necesite un responsable también comprueba refunds:write, el ámbito que solo tienen los responsables de soporte, que ya controla issue_refund (Asigna herramientas según lo que permita el token; Traza los límites de confianza).
El requestState que recibió el cliente no es el ID del reembolso que devolvió la herramienta. El ejemplo afirma que la cadena empieza por el prefijo de token v1. del SDK, así que el SDK la selló al salir. MCPServer cifra cada requestState saliente con AES-256-GCM y verifica cada uno que regresa. El sello vincula el estado al método, al nombre de la herramienta, a un resumen de los argumentos, al nombre del servidor y, cuando se usa OAuth, al llamador (mcp/server/request_state.py). La herramienta en sí lee y escribe texto plano, mientras que el cliente recibe un token que no puede leer ni modificar. La especificación dice que los clientes NO DEBEN inspeccionar, analizar, modificar ni hacer suposiciones sobre requestState (Solicitudes de ida y vuelta múltiple), y el sello hace que se cumpla, sea cual sea la intención del cliente.
Tras esta respuesta, nada espera en el servidor. No queda ninguna llamada abierta ni ninguna conexión retenida para el responsable. La API de la tienda sigue reteniendo el reembolso, como antes de que la herramienta preguntara, y si nadie responde nunca, permanece retenido. Para un paso que paga dinero, ese es el valor seguro por defecto.
Entre las rondas, el servidor guarda dos registros, ambos en su propia memoria. El reintento encuentra el reembolso mediante el almacén de cotizaciones del capítulo 3, no mediante el estado, y comprueba la respuesta contra el registro de estados respondidos que explica Mantén a prueba de manipulaciones el estado de la ida y vuelta. Un reintento que llega a otro proceso no encuentra ninguno de los dos registros, y Ejecuta réplicas sin sesiones fijas traslada ambos a un almacenamiento que comparten todas las réplicas.
Regla práctica: Cuando una herramienta no puede terminar sin el usuario, devuelve un InputRequiredResult con una solicitud de entrada por cada pregunta y un requestState que indique lo que debe completar el reintento. Comprueba las capacidades declaradas por el cliente antes de preguntar. Incluye en el estado solo lo que la herramienta necesita para continuar, y deja que el SDK lo selle. Haz cada efecto secundario anterior a la pregunta idempotente o inocuo si nadie responde, porque el cliente puede no volver a llamar nunca.
Reanudar la llamada con la respuesta
La solicitud de entrada de la sección anterior terminó la primera llamada, así que el cliente completa el trabajo enviando de nuevo la misma solicitud. El reintento repite el método, la herramienta y los arguments, añade inputResponses con la clave de las solicitudes de entrada y reenvía requestState exactamente como llegó. La especificación indica que el id de JSON-RPC DEBE ser distinto en el reintento, porque las dos llamadas son solicitudes independientes, y que un requestState NO DEBE usarse para ninguna otra solicitud que envíe el cliente (Multi Round-Trip Requests). Después, el servidor puede terminar o responder con otra solicitud de entrada.
La segunda ronda es donde el sí de un responsable se convierte en un reembolso. La herramienta de la sección anterior lee la respuesta bajo confirm en ctx.input_responses, vuelve a obtener el reembolso con la herramienta del capítulo 3 y comprueba que ctx.request_state contiene el ID de ese reembolso. Solo un accept con release activado hace que pida a la API de la tienda liberar el reembolso retenido, POST /refunds/{refund_id}/confirm, y devolver el reembolso. Cualquier otra cosa deja el reembolso retenido.
El bucle se ejecuta dos veces, una a mano y otra a través del SDK. El archivo lanza el servidor mediante lib.wire, el relé del libro que registra cada mensaje JSON-RPC, y hace de responsable con una respuesta guionizada. Para el pedido O-2289 impulsa el bucle a mano: una llamada y luego un reintento que lleva la respuesta y el estado. Para el pedido O-1145 llama a Client.call_tool, con una función de callback de elicitación que imprime la pregunta y responde que sí.
1"""Finish the refund that refund-asks-to-confirm asks about, by retrying with the answer and the echoed requestState:2first by hand, so both requests show on the wire, then with Client.call_tool, which runs the loop itself. The point3rests on the trace lines, which show two requests each time, with different IDs, and only the retry sending the answer."""4import asyncio5import pathlib67from mcp import Client8from mcp.types import ElicitResult910from lib import confirmations, loopback, shop_api, wire1112LOG = pathlib.Path("refund-confirmed-round-trip.jsonl") # every line the relay copies13YES = ElicitResult(action="accept", content={"release": True}) # the scripted user's answer141516async def say_yes(context, params) -> ElicitResult:17 print("user was asked:", params.message)18 return YES192021async def main() -> None:22 LOG.unlink(missing_ok=True)23 with loopback.serve(shop_api.create_app()) as base_url:24 server = wire.relay(confirmations.launch("refund-asks-to-confirm.py", base_url), log=str(LOG)) # the relay copies each message to LOG25 async with Client(server, elicitation_callback=say_yes) as client:26 quote = (await client.call_tool("quote_refund", {"order_id": "O-2289"})).structured_content27 arguments = {"quote_id": quote["quote_id"]}28 first = await client.session.call_tool("issue_refund", arguments, allow_input_required=True) # the input request, not a result29 # the retry repeats the arguments, adds the answer under the request's key, and echoes the state back30 done = await client.session.call_tool("issue_refund", arguments, input_responses={"confirm": YES},31 request_state=first.request_state, allow_input_required=True)32 print("by hand:", done.structured_content["refund_id"], done.structured_content["status"])33 quote = (await client.call_tool("quote_refund", {"order_id": "O-1145"})).structured_content34 done = await client.call_tool("issue_refund", {"quote_id": quote["quote_id"]})35 print("by Client.call_tool:", done.structured_content["refund_id"], done.structured_content["status"])36 calls, results = [], {} # the issue_refund requests, in order, and each one's resultType37 for direction, message in wire.read_trace(str(LOG)):38 if message.get("method") == "tools/call" and message["params"]["name"] == "issue_refund":39 calls.append(message)40 elif direction == "in" and "result" in message: # a server's response, matched to its request by JSON-RPC id41 results[message["id"]] = message["result"]["resultType"]42 for label, message in zip(["by hand, call", "by hand, retry", "Client.call_tool, call", "Client.call_tool, retry"],43 calls):44 sent = " and ".join(key for key in ("inputResponses", "requestState") if key in message["params"])45 print(f"{label}: id {message['id']}, sends {sent or 'arguments only'}, gets {results[message['id']]}")46 LOG.unlink()4748asyncio.run(main())
python refund-confirmed-round-trip.pyby hand: R-0111 requested
user was asked: Refund 343.49 on order O-1145? It is above the policy limit, so a lead must confirm it.
by Client.call_tool: R-0112 requested
by hand, call: id 4, sends arguments only, gets input_required
by hand, retry: id 5, sends inputResponses and requestState, gets complete
Client.call_tool, call: id 7, sends arguments only, gets input_required
Client.call_tool, retry: id 8, sends inputResponses and requestState, gets complete
Impulsar el bucle a mano funciona, y la traza muestra las dos solicitudes que hay detrás. El reembolso del pedido O-2289 llegó como R-0111 requested, donde requested es el estado de un reembolso liberado, que ya no está retenido. La primera llamada fue id 4, sends arguments only, gets input_required, y el reintento fue id 5, sends inputResponses and requestState, gets complete. Los dos IDs de JSON-RPC son distintos, y solo el reintento lleva la respuesta y el estado.
Client.call_tool ocultó el mismo bucle. Su callback recibió la pregunta "Refund 343.49 on order O-1145? It is above the policy limit, so a lead must confirm it." y respondió que sí, la llamada devolvió R-0112 requested, y quien llamó vio una sola llamada y un resultado. En la red seguían circulando dos solicitudes: id 7, sends arguments only, gets input_required, y después id 8, sends inputResponses and requestState, gets complete. El cliente del SDK envía cada solicitud de entrada al callback correspondiente, reintenta con las respuestas y el estado, y se detiene tras input_required_max_rounds, 10 por defecto, lanzando InputRequiredRoundsExceededError (mcp/client/_input_required.py). Una ronda que lleva solo un requestState, sin preguntas, también es válida. El ejemplo de una ronda así en el esquema se titula load shedding (schema). Para una ronda así, el cliente del SDK espera 50 milisegundos antes de reintentar, duplicando la espera cada vez hasta llegar a 250 milisegundos.
Un reintento repite la solicitud original, así que no es una nueva llamada a la herramienta. En el SDK, el resumen de los argumentos va dentro del estado sellado, por lo que un reintento que cambie los argumentos falla, como muestra Keep round-trip state tamper-proof. Un cliente que quiera argumentos distintos hace otra llamada y recibe otra pregunta.
Regla práctica: Usa Client.call_tool con una función de callback de elicitación en un host, y deja que el SDK ejecute las rondas. Impulsa tú mismo el bucle con client.session.call_tool(..., allow_input_required=True) solo cuando el host deba conservar el estado tras un reinicio o mostrar cada ronda, y entonces repite los argumentos exactamente. En el servidor, lee la respuesta y el estado juntos. Cuando tu servidor siempre envía un estado, trata una respuesta que llegue sin él, o con un estado de otro registro, como una pregunta que nunca se hizo.
Esta parte aún no está traducida, así que está en inglés.
Ask for structured input with elicitation
The confirmation in the previous section asks one yes-or-no question, and elicitation can ask for more. It has two modes (elicitation). In form mode, the server sends a message and a schema, the client renders a form, and the answer returns through the client. In URL mode, the server sends the user to a web page, not a form (the next subsection).
A form's schema is a flat object with primitive properties only: strings, including the formats email, uri, date and date-time; numbers and integers; booleans; and single- or multiple-choice enums. Any of these can carry a default. The user answers accept with the content, decline for an explicit no, or cancel for a dismissed form. Servers MUST handle both refusals. The client MUST show which server is asking, offer decline and cancel, and let the user review a form before it's sent (elicitation; Answer input requests for the user).
The SDK offers a shorter route. A tool parameter declared as Annotated[T, Resolve(fn)] is filled by running fn. When fn returns Elicit(message, Model), the SDK renders the pydantic model as the form, checks the client's capability, returns the input request, and fills it in on the retry. Annotate the parameter as ElicitationResult[Model] and the tool receives all three outcomes to branch on. A plain Model turns decline and cancel into a tool error (mcp/server/mcpserver/resolve.py).
Only the person who opens a returned parcel knows whether the item inside arrived damaged or wrong, and whether it can go back on sale. The policy's reason also decides whether shipping is refunded. The tool record_return asks with a resolver, for the line of KG-1043 on order O-1145. The form has three fields: reason, one of the refund policy's five reasons; restock, a boolean; and an optional free-text note of at most 200 characters. A scripted user accepts, declines, then cancels, and a client without a callback calls last.
1"""record_return asks the person who opened a returned parcel what they found, through a form that a resolver builds2and sends. The point rests on the three answer lines, accept, decline and cancel, and on the error a client without3an elicitation callback gets, which names a missing capability rather than a tool failure."""4import asyncio5from typing import Annotated, Literal67from mcp import Client, MCPError8from mcp.server.mcpserver import AcceptedElicitation, Elicit, ElicitationResult, MCPServer, Resolve9from mcp.types import ElicitResult10from pydantic import BaseModel, Field1112server = MCPServer("shop-returns", version="0.5.0")13Reason = Literal["damaged in transit", "wrong item sent", "missing part", "arrived late", "changed mind"] # the refund policy's five reasons141516class Inspection(BaseModel): # the form: a flat object with primitive fields only17 reason: Reason = Field(description="The refund policy's reason that fits what you found")18 restock: bool = Field(description="The item can go back on sale")19 note: str | None = Field(default=None, max_length=200, description="Anything the refund should say") # a default makes the field optional on the form202122def ask(order_id: str, sku: str) -> Elicit[Inspection]:23 return Elicit(f"You opened the return of {sku} from order {order_id}. What did you find?", Inspection)242526@server.tool(description="Record what a returned item was like when its parcel was opened. The user fills in a form.")27def record_return(order_id: str, sku: str, found: Annotated[ElicitationResult[Inspection], Resolve(ask)]) -> str: # the SDK runs ask(), sends the form as an input request, and fills found in on the retry28 if isinstance(found, AcceptedElicitation):29 return f"Recorded: {found.data.reason}, restock {found.data.restock}."30 return ("The user declined: don't record this return, and don't ask again." if found.action == "decline"31 else "The user closed the form without answering: ask again later.")323334SCRIPT = [ElicitResult(action="accept", content={"reason": "damaged in transit", "restock": False}),35 ElicitResult(action="decline"), ElicitResult(action="cancel")] # the scripted user's three answers36forms = [] # each form the user was shown373839async def scripted_user(context, params) -> ElicitResult:40 forms.append(params.requested_schema)41 return SCRIPT.pop(0)424344async def main() -> None:45 arguments = {"order_id": "O-1145", "sku": "KG-1043"}46 async with Client(server, elicitation_callback=scripted_user) as client:47 for action in ("accept", "decline", "cancel"):48 print(f"{action}:", (await client.call_tool("record_return", arguments)).content[0].text)49 print("form fields:", ", ".join(forms[0]["properties"]))50 print("required:", ", ".join(forms[0]["required"]))51 async with Client(server) as client: # no elicitation_callback, so no elicitation capability52 try:53 await client.call_tool("record_return", arguments)54 except MCPError as error:55 print("client without elicitation:", error.error.code)565758asyncio.run(main())
python elicit-a-refund-reason.pyaccept: Recorded: damaged in transit, restock False.
decline: The user declined: don't record this return, and don't ask again.
cancel: The user closed the form without answering: ask again later.
form fields: reason, restock, note
required: reason, restock
client without elicitation: -32021
The pydantic model gives note a default, so it's the only optional field. The client received the fields reason, restock, note, and only reason, restock are required.
Each string tells the model what to do next. Accept gave "Recorded: damaged in transit, restock False." Decline gave "The user declined: don't record this return, and don't ask again." Cancel gave "The user closed the form without answering: ask again later." A decline stands, and a cancel leaves the question open.
A client without a callback declares no elicitation capability, so the SDK refuses its call with JSON-RPC error -32021, Missing Required Client Capability, before the tool runs (mcp/server/mcpserver/resolve.py). The shop's issue_refund makes the same check by hand.
Working rule: Use form mode for answers only the person at the host can give, and keep each form to the few fields the tool acts on, with enums wherever the answer is one of a known set. Declare forms with a resolver and a pydantic model, and take ElicitationResult when decline and cancel should lead different ways. Build the input request by hand only when you need to control the state yourself.
Envía los pasos sensibles a una URL
La respuesta de un formulario pasa por el cliente y, posiblemente, delante del modelo. Los servidores NO DEBEN usar el modo de formulario para contraseñas, claves de API, tokens de acceso ni credenciales de pago, y DEBEN usar el modo de URL para ellos (elicitation). El modo de URL envía un mensaje y una URL. El cliente NO DEBE obtener la URL ni sus metadatos de antemano, NO DEBE abrirla sin el consentimiento explícito del usuario, y DEBE mostrar la URL completa. La página se abre de forma que ni el cliente ni el modelo puedan ver lo que ocurre en ella. El servidor mantiene los datos personales y las credenciales fuera de la URL, nunca envía una URL que inicie sesión por sí sola al usuario, y DEBE asegurarse de que el usuario que completa el flujo sea el mismo que lo inició.
El modo de URL no es la forma en que un cliente obtiene autorización para un servidor MCP; Encuentra el servidor de autorización a partir del recurso explica eso. Sirve a las necesidades propias del servidor, como un servicio de terceros o un pago. En el modo de URL, accept significa solamente que el usuario ha consentido la interacción, no que la interacción haya terminado (elicitation). La revisión fijada eliminó el campo elicitationId y la notificación notifications/elicitation/complete. El consejo del registro de cambios para un servidor que necesita relacionar un flujo entre reintentos es codificar su propio identificador en requestState (changelog).
El pago llega después de una liberación. pay_refund paga un reembolso liberado, uno con estado requested, de vuelta a la tarjeta del pedido, y el proveedor paga solo bajo la cuenta propia de un responsable (lead) de la cuenta, con sesión iniciada en la página del proveedor. La herramienta genera un ID aleatorio para el flujo, lo coloca en requestState y envía al cliente potencial a https://pay.fernhill.example/connect/ seguido de ese ID, en un dominio reservado que nunca se resuelve. Un conjunto en memoria hace las veces del registro del proveedor de los flujos terminados, y el ejemplo añade este flujo antes de la tercera llamada.
1"""pay_refund sends the support lead to the payment provider's page to connect an account, through URL mode, so the2sign-in stays out of the client. The point rests on the after-accept line, which still asks, and the after-sign-in3line, which completes only once the provider has recorded the flow as finished."""4import asyncio5import secrets67from mcp import Client8from mcp.server.mcpserver import Context, MCPServer9from mcp.types import ElicitRequest, ElicitRequestURLParams, ElicitResult, InputRequiredResult1011from lib import confirmations1213server = MCPServer("shop-payments", version="0.5.0")14finished: set[str] = set() # flows the payment provider reports finished; it would tell the server, not the client151617@server.tool(description="Pay out a released refund through the shop's payment provider, by its refund_id.")18def pay_refund(refund_id: str, ctx: Context) -> str | InputRequiredResult:19 flow = ctx.request_state or secrets.token_urlsafe(16) # the server's own ID for this flow, carried in requestState; 16 random bytes, so it can't be guessed20 if flow in finished:21 return f"Paid {refund_id} through the payment provider"22 answer = (ctx.input_responses or {}).get("connect")23 if answer is not None and answer.action != "accept":24 return f"Not paid: the user didn't connect a payment account. {refund_id} stays released, unpaid."25 confirmations.require_elicitation(ctx, "url")26 ask = ElicitRequestURLParams(url=f"https://pay.fernhill.example/connect/{flow}",27 message="To pay refunds, connect your payment provider account on its own page.")28 return InputRequiredResult(input_requests={"connect": ElicitRequest(params=ask)}, request_state=flow)293031async def main() -> None:32 async with Client(server, elicitation_callback=confirmations.say_yes) as client: # declares form and url33 def call(state=None, answers=None):34 return client.session.call_tool("pay_refund", {"refund_id": "R-0111"}, input_responses=answers,35 request_state=state, allow_input_required=True)36 first = await call()37 request = first.input_requests["connect"].params38 print("first call:", first.result_type, request.mode)39 print("url:", request.url.rsplit("/", 1)[0] + "/…") # cut before the last slash, so the flow's ID isn't printed40 accepted = {"connect": ElicitResult(action="accept")} # the scripted user agrees to open the page41 second = await call(first.request_state, accepted)42 print("after accept:", second.result_type, second.input_requests["connect"].params.mode)43 finished.add(request.url.rsplit("/", 1)[1]) # the flow's ID is what follows the last slash; the provider records it when the lead signs in44 third = await call(second.request_state, accepted)45 print("after sign-in:", third.result_type, third.content[0].text)4647asyncio.run(main())
python elicit-by-url.pyfirst call: input_required url
url: https://pay.fernhill.example/connect/…
after accept: input_required url
after sign-in: complete Paid R-0111 through the payment provider
La primera llamada devolvió input_required url, con la URL https://pay.fernhill.example/connect/…, cortada antes del ID aleatorio. Después de que el usuario simulado aceptara, el reintento seguía devolviendo input_required url, ya que aceptar significaba solamente que el cliente potencial estaba de acuerdo en abrir la página. Una vez que el proveedor registró el inicio de sesión, el siguiente reintento devolvió complete Paid R-0111 through the payment provider.
El ejemplo omite la comprobación de que la persona que inicia sesión es la persona a la que se le pidió. Esa comprobación requiere la identidad del llamador de Obtén un token con PKCE.
Regla práctica: Envía por el modo de URL cualquier dato secreto, y cualquier cosa que inicie la sesión de una persona en otro servicio, nunca por un formulario. Coloca el ID propio del flujo en requestState, trata accept como "el usuario fue a la página", y decide en cada reintento, a partir de los registros propios del servidor, si el flujo ha terminado. Comprueba que la persona que termina un flujo sea la que lo inició.
Mantén el estado de ida y vuelta a salvo de manipulaciones
El reembolso confirmado en Reanuda la llamada con la respuesta dependía de que el cliente devolviera el requestState que había recibido, y nada obliga a un cliente a ser honesto. La especificación trata requestState como una entrada controlada por un atacante, y los servidores DEBEN hacerlo también. Cuando el estado influye en la autorización, en el acceso a recursos o en la lógica de negocio, el servidor DEBE proteger su integridad (por ejemplo, HMAC o AEAD) y rechazar el estado que no supere la comprobación. Para reducir las repeticiones, un servidor DEBERÍA además vincular el estado al usuario autenticado, darle una caducidad corta y asociarlo a la solicitud de la que procede. Nada de eso convierte un estado en de uso único. Un servidor para el que un estado debe usarse como máximo una vez DEBE hacer cumplir esa invariante en el lado del servidor (Solicitudes con múltiples idas y vueltas).
El sellado del SDK cubre la primera parte y le dice al cliente lo mínimo posible. Tanto si el token ha cambiado, haya caducado, pertenezca a otra solicitud o a otro llamador, o use una clave desconocida, el cliente recibe el mismo error JSON-RPC, -32602, "Invalid or expired requestState". La razón real solo se entrega al registro del servidor (mcp/server/request_state.py), de modo que un cliente no aprende nada de un intento fallido. Sin embargo, el sellado no lleva registro de los tokens que ya aceptó, así que la segunda parte recae en el servidor.
Una confirmación repetida supondría una segunda liberación de dinero, por lo que la herramienta debe rechazarla. Esta vez el cliente envía mal el reintento de Reanuda la llamada con la respuesta de tres maneras, luego correctamente y luego correctamente otra vez:
- con un carácter del
requestStatesellado cambiado; - con el sí del líder guionizado pero sin estado, como si respondiera a una pregunta que el servidor nunca envió;
- con el estado correcto pero con el
quote_idde otra cotización; - como un reintento honesto;
- como el mismo reintento honesto, enviado una segunda vez.
1"""Send issue_refund's retry wrongly, then rightly, then again: a changed requestState, an answer with no state, and a2state with other arguments; then an honest retry, and its replay. The seal refuses the changed and the mismatched state,3the tool asks again for the answer with no state, and its own once-only record refuses the replay."""4import asyncio56from mcp import Client, MCPError7from mcp.types import ElicitResult89from lib import confirmations, loopback, shop_api1011YES = ElicitResult(action="accept", content={"release": True}) # the scripted user's answer121314async def retry(client: Client, label: str, quote_id: str, state: str | None) -> None:15 try:16 result = await client.session.call_tool("issue_refund", {"quote_id": quote_id}, input_responses={"confirm": YES},17 request_state=state, allow_input_required=True)18 except MCPError as error:19 print(f"{label}:", error.error.code, error.error.message)20 return21 if result.result_type == "input_required":22 print(f"{label}: input_required, the server asks again")23 elif result.is_error:24 print(f"{label}: tool error,", result.content[0].text)25 else:26 print(f"{label}: refund", result.structured_content["refund_id"], result.structured_content["status"])2728async def main() -> None:29 with loopback.serve(shop_api.create_app()) as base_url:30 async with Client(confirmations.launch("refund-asks-to-confirm.py", base_url),31 elicitation_callback=confirmations.say_yes) as client:32 quotes = [(await client.call_tool("quote_refund", {"order_id": order})).structured_content["quote_id"]33 for order in ("O-2289", "O-1145")]34 first = await client.session.call_tool("issue_refund", {"quote_id": quotes[0]}, allow_input_required=True)35 state = first.request_state36 # swaps the character at index 20 for another, so the seal no longer matches the token37 changed = state[:20] + ("A" if state[20] != "A" else "B") + state[21:]38 await retry(client, "one character changed", quotes[0], changed)39 await retry(client, "answer without state", quotes[0], None)40 await retry(client, "state with other arguments", quotes[1], state)41 await retry(client, "honest retry", quotes[0], state)42 await retry(client, "same retry again", quotes[0], state)434445asyncio.run(main())
python tampered-round-trip-state.pyone character changed: -32602 Invalid or expired requestState
answer without state: input_required, the server asks again
state with other arguments: -32602 Invalid or expired requestState
honest retry: refund R-0111 requested
same retry again: tool error, Error executing tool issue_refund: Refund R-0111 was already confirmed. Don't send the same answer again.
Un token modificado devolvió -32602 Invalid or expired requestState, y los argumentos intercambiados se devolvieron del mismo modo: -32602 Invalid or expired requestState. El SDK registra un motivo distinto para cada caso, seal para el carácter cambiado y request binding para los otros argumentos, y el cliente no recibe ninguno de los dos (mcp/server/request_state.py). Una respuesta sin estado obtuvo input_required, the server asks again. La herramienta trata una respuesta a una pregunta que nunca se hizo como si no hubiera respuesta, y la especificación dice que un servidor al que le falta una respuesta DEBERÍA volver a preguntar en lugar de devolver un error (Solicitudes de múltiples ida y vuelta).
El reintento honesto liberó el reembolso: refund R-0111 requested. Enviado de nuevo, el mismo reintento superó el sellado, porque nada en él había cambiado. En cambio, lo rechazó el registro propio del servidor de estados ya respondidos, con el error de herramienta "tool error, Error executing tool issue_refund: Refund R-0111 was already confirmed. Don't send the same answer again.". Ese registro es confirmations.OnceOnly, un conjunto de estados guardado bajo un bloqueo en la memoria del servidor, y la herramienta lo comprueba antes de pedir a la API de la tienda que libere nada. Detrás, la API responde 409 a una segunda liberación del mismo reembolso, de modo que incluso un servidor que hubiera perdido su registro no podría pagar dos veces.
Regla práctica: Deja que el SDK selle cada requestState, y nunca desactives el sellado para un estado que afecte al dinero, al acceso o a los datos. Mantén el estado pequeño y opaco: un ID, no el registro. Para cualquier paso que deba ocurrir una sola vez, lleva en el servidor tu propio registro de estados respondidos, y compruébalo antes del efecto secundario, no después.
Esta parte aún no está traducida, así que está en inglés.
Choose elicitation or a tool argument
Each question in this chapter could have been a tool argument instead: confirmed: true on issue_refund (Return an input request instead of a result), or reason on record_return (Ask for structured input with elicitation). A tool argument costs no extra round trip and no user interface, but the model fills it in. Elicitation costs a round trip and a person's attention, and only the host's user is meant to answer it. The question to ask, then, is who can know the value.
This is a rule of thumb, not a measurement. If the model can read the value from the conversation, make it an argument. If only the person at the host can give it, elicit it. If it is a secret, or a sign-in to another service, use URL mode.
| What the tool needs | In the shop | Use |
|---|---|---|
| A value in the ticket | the order ID a customer wrote | a tool argument |
| A decision the policy gives a person | releasing a refund above the limit | a form |
| A fact only the person present has | what a returned parcel held | a form |
| A secret or a sign-in | the lead's payment provider account | URL mode |
A confirmed argument on issue_refund would let the model confirm its own refund, a decision the refund policy keeps for a person. The order ID goes the other way. Asking the lead to retype an ID the customer already wrote adds a step and a chance for a typo, and the model can read the ID. When a value could come from either place, take the argument and let the tool check it, as chapter 3's tools check every ID's format.
Elicitation is the server asking the user through the host. It isn't the host's own consent, the step where the host asks the user before a tool with side effects runs, which Ask for consent before side effects builds. The shop's confirmation is the server's own check, and a careful host still asks before it calls issue_refund at all.
Working rule: Make a value a tool argument when the model can know it, and validate it in the tool. Elicit it when only the person can give it, or when the policy says a person must decide, and never accept that kind of value as an argument. Use URL mode for every secret. When you aren't sure, ask who would be at fault if the value were wrong.
Qué sale mal en producción
La confirmación funciona con un solo servidor stdio, un cliente y un responsable que responde al instante. Los responsables reales tardan, los servidores se reinician y los clientes varían, así que el patrón falla de algunas maneras reconocibles.
Estado sellado con una clave que ya no existe. La clave por defecto de MCPServer se genera al arrancar el proceso y vive solo en su memoria (mcp/server/request_state.py). Si el servidor se reinicia entre la pregunta y la respuesta, o el reintento llega a otra réplica, el servidor no puede abrir el estado y la respuesta del responsable falla con -32602. La señal a vigilar es que "Invalid or expired requestState" aumente después de los despliegues o con el número de réplicas. Dale a cada réplica las mismas claves mediante RequestStateSecurity(keys=[...]). confirmations.state_security(), la política de sellado de Devuelve una solicitud de entrada en lugar de un resultado, construye esas claves a partir de SHOP_REQUEST_STATE_KEY. La primera clave sella y todas las claves abren, así que una clave puede rotarse sin perder respuestas (Ejecuta réplicas sin sesiones pegajosas).
Un responsable más lento que la vida útil del estado. Por defecto, el estado del SDK dura 600 segundos por ronda. Un responsable que lee la pregunta, atiende una llamada y responde quince minutos después recibe el mismo -32602, y el registro del servidor dice expired. Configura ttl= con el tiempo más largo que una persona razonablemente necesita, y deja que el host convierta el error en una llamada nueva, que vuelve a preguntar.
Registros que solo ve un proceso. El reintento necesita dos registros de la primera ronda, y ambos viven en la memoria de un solo servidor: el almacén de cotizaciones del capítulo 3, a través del cual el reintento encuentra el reembolso, y confirmations.OnceOnly, el registro de estados respondidos de Mantén el estado de ida y vuelta a salvo de manipulaciones. Detrás de dos réplicas, un reintento que llega a la otra falla con "There is no quote", y una respuesta repetida que llegue allí pasaría la comprobación de un solo uso. Guarda ambos registros en almacenamiento compartido, como hace Ejecuta réplicas sin sesiones pegajosas, y mantén detrás el propio 409 de la API de la tienda.
Una respuesta de alguien que no es responsable. La herramienta libera un reembolso ante cualquier accept que envíe el host, y el host puede responder mediante código. Por stdio, eso es todo lo que puede comprobar un servidor. Por HTTP, vincula cada pregunta al llamador autenticado y comprueba que el token del llamador incluye refunds:write, el ámbito que solo tienen los responsables de soporte (Limita las herramientas según lo que permite el token).
Un cliente que no puede preguntar. Un host cuyo cliente no tiene callback de elicitación no declara la capacidad de elicitación (mcp/client/session.py), y la llamada falla con -32021, Missing Required Client Capability. La comprobación de un resolver se ejecuta antes de la herramienta; una comprobación escrita a mano como la de issue_refund se ejecuta dentro de ella, después de que la herramienta del capítulo 3 ya haya retenido el reembolso (confirmations.require_elicitation). La señal es ese error desde un host y no desde los demás. Un host que atiende a personas debe declarar la elicitación y mostrar las preguntas (Responde a las solicitudes de entrada del usuario). Un servidor cuya herramienta tiene un valor por defecto seguro, como dejar el reembolso retenido, puede devolver ese valor como resultado en lugar de fallar.
Un flujo en modo URL que cambia. La especificación marca el modo URL como una función cuyo diseño puede cambiar en revisiones futuras (elicitación), y la revisión fijada ya ha eliminado dos de sus partes. Mantén el código del modo URL en un solo lugar y compruébalo contra el registro de cambios de cada revisión.
Bucles que nunca terminan. Un flujo en modo URL que el usuario abandona vuelve a preguntar en cada reintento, y el cliente del SDK se detiene después de 10 rondas con InputRequiredRoundsExceededError. Cuenta las rondas de cada flujo en requestState, y después de unas pocas, devuelve un resultado que diga que el paso no está terminado.
Un cliente antiguo en el mismo servidor. Un InputRequiredResult devuelto a un cliente que se conectó con el handshake de 2025 llega como -32603, "Handler returned an invalid result". El SDK comprueba el resultado frente al CallToolResult de 2025, que exige content (mcp/server/runner.py; solicitudes de ida y vuelta de múltiples rondas). Un servidor que atiende ambas versiones comprueba ctx.protocol_version, o usa resolvers, que eligen la ruta correcta para cada conexión (mcp/server/mcpserver/resolve.py). Atiende a clientes antiguos y nuevos durante la ventana cubre ambos casos.
Rechazos que nadie investiga. Cada estado rechazado da al cliente el mismo mensaje, así que el único registro de por qué es el log del servidor, bajo el logger mcp.server.request_state. Conserva ese log, y configura alertas por seal y request binding, que significan que alguien alteró un token, por separado de expired, que normalmente significa una persona lenta.
Regla práctica: Da a las réplicas de un servidor que hace preguntas una clave compartida que pueda rotarse, configura la vida útil del estado según lo que tarda la gente, y traslada el almacén de cotizaciones y todos los registros de un solo uso a almacenamiento compartido, antes de pasar a producción. Vincula cada pregunta al llamador siempre que el transporte lo permita. Después vigila -32602 por su motivo registrado, -32021 por host, y el número de rondas por llamada.
Decisiones que tomó este capítulo
- La API de la tienda decide qué reembolsos necesitan confirmación.
issue_refundllama primero a la versión del capítulo 3 y solo pregunta cuando la API retiene el reembolso, de modo que el límite de la política vive en un solo lugar. - El reembolso se retiene antes de la pregunta, de modo que una pregunta que nadie responde deja el reembolso retenido, como en el capítulo 3.
- La confirmación es una solicitud de entrada construida a mano: una elicitación en modo formulario bajo la clave
confirm, con el ID del reembolso comorequestState, que el reintento comprueba frente al reembolso que encuentra. El formulario del paquete devuelto usa un resolver, donde la comprobación de capacidades del SDK y el renderizado ahorran código. - El SDK sella cada
requestState, bajo claves que un despliegue puede inyectar medianteconfirmations.state_security()oSHOP_REQUEST_STATE_KEY, y en otro caso bajo una clave que vive mientras viva el proceso. - Las respuestas son de una sola vez en el servidor, mediante
confirmations.OnceOnly, comprobadas antes de la liberación, con el 409 de la API detrás. - Una respuesta sin el estado del servidor, o con el estado de otro reembolso, es una pregunta nunca formulada, y la herramienta vuelve a preguntar.
- El servidor no mantiene ninguna llamada abierta, pero conserva dos registros: el almacén de cotizaciones del capítulo 3 y el registro de una sola vez, ambos en memoria aquí y compartidos entre réplicas en el capítulo 6.
- En stdio, el usuario del host es quien confirma. Por HTTP, la pregunta queda vinculada al llamante autenticado, y
refunds:write, el alcance que solo tienen los responsables de soporte, controla la herramienta (Limitar herramientas por lo que permite el token). - Rechazar y cancelar se comportan de forma distinta: un rechazo queda firme, y una cancelación deja la pregunta abierta.
- Los secretos y los inicios de sesión pasan por el modo URL, con el ID del flujo en
requestState, yacceptnunca cuenta como terminado. - La API incorporó dos endpoints,
POST /refunds/{refund_id}/confirmyPOST /refunds/{refund_id}/cancel, que actúan solo sobre un reembolso retenido y responden 409 en otro caso. - Los valores que el modelo puede leer siguen siendo argumentos de la herramienta, y los valores que solo una persona puede dar se solicitan mediante elicitación.
Este capítulo, en esta edición
Edición 2026.11.14Ejemplos verificados el 19 de nov de 2026Superan la prueba 6 de 6 ejemplos ejemplos de este capítulo
Traducido del libro en inglés, edición 2026.11.14.