Ask the user in the middle of a call
Cerca de 37 minutos min de leitura, com 6 exemplos em 9 seções.
Traduzido com IA. Verificado por pessoas em inglês. Como fazemos os livros
Traduzido do livro em inglês, edição 2026.11.14. Leia o original
Nesta página
- See why a stateless server can't wait for an answer
- Retornar uma solicitação de entrada em vez de um resultado
- Retomar a chamada com a resposta
- Ask for structured input with elicitation
- Envie etapas sensíveis para uma URL
- Mantenha o estado de ida e volta à prova de adulteração
- Choose elicitation or a tool argument
- O que dá errado em produção
- Decisões que este capítulo tomou
Esta parte ainda não foi traduzida, por isso está em 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 ainda não foi traduzida, por isso está em 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).
Retornar uma solicitação de entrada em vez de um resultado
A chamada que falhou na seção anterior precisava de um canal que o protocolo não tem. Uma Multi Round-Trip Request inverte a direção da pergunta. Em vez de um resultado, o servidor retorna um InputRequiredResult, cujo resultType é "input_required", e a chamada termina aí. Dois campos carregam o restante. inputRequests mapeia chaves escolhidas pelo servidor para os requests que ele precisa que sejam respondidos, e requestState é uma string opaca que o cliente deve devolver. O servidor DEVE incluir pelo menos um dos dois (Multi Round-Trip Requests; schema, InputRequiredResult).
Três regras limitam o que um servidor pode pedir, e quando. Somente tools/call, prompts/get e resources/read podem responder com uma solicitação de entrada, e os servidores NÃO DEVEM enviar uma em qualquer outra requisição. Um servidor NÃO DEVE incluir uma requisição elicitation/create a menos que o cliente tenha declarado a capacidade elicitation (Multi Round-Trip Requests). E, como todo resultado na revisão fixada carrega resultType, um cliente trata a ausência desse campo, que um servidor mais antigo envia, como "complete", e trata qualquer outro valor não reconhecido como inválido (overview).
issue_refund ainda chama a versão do capítulo 3 primeiro, de modo que a API da loja decide, com o limite da política, se um reembolso precisa de confirmação, e o servidor nunca repete o limite. Dentro de um mesmo processo do servidor, a ferramenta do capítulo 3 retorna o mesmo reembolso para o mesmo quote_id a cada vez, o que torna seguro chamá-la em cada rodada. Entre processos, isso não vale, como O que dá errado em produção explica na seção "Registros que só um processo enxerga". Quando a API mantém o reembolso, a ferramenta verifica se o cliente declarou elicitação em modo formulário e então constrói a solicitação de entrada manualmente: uma ElicitRequest sob a chave confirm, cujo formulário é um único campo obrigatório de sim ou não, release, e cuja mensagem nomeia o valor e o pedido. Seu requestState é o ID do reembolso. Quando a nova tentativa chega, a ferramenta verifica se o estado nomeia o reembolso que ela encontrou, e usa o estado como chave do seu registro de respostas.
O servidor passa request_state_security= para MCPServer, com a política que confirmations.state_security() constrói, para que várias réplicas possam, depois, compartilhar uma mesma chave. Nestes exemplos, essa política é o padrão do SDK, uma chave criada quando o processo inicia. Um cliente declara elicitação passando um callback, e chama a ferramenta por meio de client.session.call_tool(..., allow_input_required=True), que devolve a solicitação de entrada em vez de respondê-la.
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.
A chamada retornou com tipo de resultado input_required, e sua única solicitação de entrada é elicitation/create form. A mensagem diz "Refund 180.00 on order O-2289? It is above the policy limit, so a lead must confirm it." Essa é a pergunta que o usuário do host veria.
A pergunta vai para quem está sentado no host, então a resposta só é tão confiável quanto o host. Um accept não mostra que um líder de suporte respondeu, nem que uma pessoa respondeu, já que os callbacks roteirizados deste capítulo respondem por código. Os servidores também DEVEM vincular as requisições de elicitação à identidade do cliente e do usuário, acrescenta a especificação (elicitation). Sobre stdio, como aqui, o usuário é o usuário local do host, que iniciou o servidor, e o servidor não tem outra identidade à qual vincular, então a loja confia no host para encaminhar a pergunta a um líder. Sobre HTTP, o servidor vincula a pergunta ao chamador autenticado, e o selo do SDK já inclui o chamador OAuth, de modo que a nova tentativa de outro usuário falha. Um servidor que precisa de um líder também verifica a presença de refunds:write, o escopo que apenas líderes de suporte possuem, que já controla issue_refund (Definir o escopo das ferramentas pelo que o token permite; Desenhar as fronteiras de confiança).
O requestState que o cliente recebeu não é o ID do reembolso que a ferramenta retornou. O exemplo afirma que a string começa com o prefixo de token v1. do SDK, então o SDK o selou na saída. MCPServer criptografa cada requestState que sai com AES-256-GCM e verifica cada um que volta. O selo vincula-o ao método, ao nome da ferramenta, a um digest dos argumentos, ao nome do servidor e, quando OAuth está em uso, ao chamador (mcp/server/request_state.py). A própria ferramenta lê e escreve texto simples, enquanto o cliente recebe um token que não consegue ler nem alterar. A especificação diz que os clientes NÃO DEVEM inspecionar, analisar, modificar nem fazer suposições sobre requestState (Multi Round-Trip Requests), e o selo faz com que isso valha independentemente do que um cliente pretenda.
Depois desta resposta, nada aguarda no servidor. Nenhuma chamada permanece aberta, e nenhuma conexão fica retida para o líder. A API da loja ainda mantém o reembolso, como fazia antes de a ferramenta perguntar, e, se ninguém jamais responder, ele continua retido. Para um passo que paga dinheiro, esse é o padrão seguro.
Entre as rodadas, o servidor mantém dois registros, ambos em sua própria memória. A nova tentativa encontra o reembolso pelo armazenamento de cotações do capítulo 3, não pelo estado, e confere a resposta com o registro de estados respondidos que Mantenha o estado da ida e volta à prova de adulteração explica. Uma nova tentativa que chega a outro processo não encontra nenhum dos dois registros, e Execute réplicas sem sessões fixas move ambos para um armazenamento que todas as réplicas compartilham.
Regra prática: Quando uma ferramenta não consegue terminar sem o usuário, retorne um InputRequiredResult com uma solicitação de entrada por pergunta e um requestState que diga o que a nova tentativa deve concluir. Verifique as capacidades declaradas pelo cliente antes de perguntar. Coloque no estado apenas o que a ferramenta precisa para continuar, e deixe o SDK selá-lo. Torne idempotente ou inofensivo todo efeito colateral anterior à pergunta, pois o cliente pode nunca mais chamar.
Retomar a chamada com a resposta
A solicitação de entrada apresentada em a seção anterior encerrou a primeira chamada, então o cliente conclui o trabalho enviando a mesma solicitação novamente. A nova tentativa repete o método, a ferramenta e o arguments, acrescenta inputResponses, indexado com as mesmas chaves das solicitações de entrada, e devolve o requestState exatamente como foi recebido. A especificação diz que o id do JSON-RPC DEVE ser diferente na nova tentativa, porque as duas chamadas são solicitações independentes, e que um requestState NÃO DEVE ser usado em nenhuma outra solicitação enviada pelo cliente (Requisições de ida e volta em múltiplas rodadas). Em seguida, o servidor pode concluir ou responder com outra solicitação de entrada.
A segunda rodada é o ponto em que o sim de um líder vira um reembolso. A ferramenta da seção anterior lê a resposta sob confirm em ctx.input_responses, obtém o reembolso novamente com a ferramenta do capítulo 3 e verifica se ctx.request_state contém o ID desse reembolso. Somente um accept com release definido faz a ferramenta pedir à API da loja que libere o reembolso retido, POST /refunds/{refund_id}/confirm, e devolva o reembolso. Qualquer outra resposta deixa o reembolso retido.
O laço é executado duas vezes, uma à mão e outra pelo SDK. O arquivo inicia o servidor por meio de lib.wire, o repasse do livro que registra cada mensagem JSON-RPC, e faz o papel do líder com uma resposta roteirizada. Para o pedido O-2289, ele conduz o laço à mão: uma chamada e, em seguida, uma nova tentativa que leva a resposta e o estado. Para o pedido O-1145, ele chama Client.call_tool, com um callback de elicitação que imprime a pergunta e responde sim.
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
Conduzir o laço à mão funciona, e o rastro mostra as duas solicitações por trás dele. O reembolso do pedido O-2289 voltou como R-0111 requested, em que requested é o status de um reembolso liberado, que deixou de estar retido. A primeira chamada foi id 4, sends arguments only, gets input_required, e a nova tentativa foi id 5, sends inputResponses and requestState, gets complete. Os dois IDs do JSON-RPC diferem, e somente a nova tentativa carrega a resposta e o estado.
Client.call_tool ocultou o mesmo laço. Seu callback foi questionado com "Refund 343.49 on order O-1145? It is above the policy limit, so a lead must confirm it." e respondeu sim, a chamada devolveu R-0112 requested, e quem chamou viu uma chamada e um resultado. O canal ainda transportava duas solicitações: id 7, sends arguments only, gets input_required, depois id 8, sends inputResponses and requestState, gets complete. O cliente do SDK envia cada solicitação de entrada ao callback correspondente, repete a tentativa com as respostas e o estado, e para após input_required_max_rounds, 10 por padrão, levantando InputRequiredRoundsExceededError (mcp/client/_input_required.py). Uma rodada que traz apenas um requestState, sem perguntas, também é válida. O exemplo do esquema para uma dessas rodadas tem o título load shedding (esquema). Nessa rodada, o cliente do SDK espera 50 milissegundos antes de tentar de novo, dobrando a espera a cada vez, até o limite de 250 milissegundos.
Uma nova tentativa repete a solicitação original, então não é uma chamada de ferramenta nova. No SDK, o resumo criptográfico dos argumentos fica dentro do estado selado, de modo que uma nova tentativa que os altere falha, como mostra Mantenha o estado de ida e volta à prova de adulteração. Um cliente que queira argumentos diferentes faz outra chamada e recebe outra pergunta.
Regra prática: Use Client.call_tool com um callback de elicitação em um host e deixe o SDK executar as rodadas. Conduza o laço você mesmo com client.session.call_tool(..., allow_input_required=True) somente quando o host precisar manter o estado após uma reinicialização ou mostrar cada rodada, e então repita os argumentos exatamente. No servidor, leia a resposta e o estado juntos. Quando seu servidor sempre enviar um estado, trate uma resposta que chegue sem ele, ou com um estado de outro registro, como uma pergunta nunca feita.
Esta parte ainda não foi traduzida, por isso está em 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.
Envie etapas sensíveis para uma URL
A resposta de um formulário passa pelo cliente e, possivelmente, diante do modelo. Servidores NÃO DEVEM usar o modo de formulário para senhas, chaves de API, tokens de acesso ou credenciais de pagamento, e DEVEM usar o modo URL para elas (elicitação). O modo URL envia uma mensagem e uma URL. O cliente NÃO DEVE buscar a URL nem os seus metadados antecipadamente, NÃO DEVE abri-la sem o consentimento explícito do usuário, e DEVE mostrar a URL completa. A página é aberta de modo que nem o cliente nem o modelo possam ver o que acontece nela. O servidor mantém dados pessoais e credenciais fora da URL, nunca envia uma URL que autentique o usuário por si só, e DEVE garantir que o usuário que concluir o fluxo seja aquele que o iniciou.
O modo URL não é a forma como um cliente obtém autorização em um servidor MCP; Encontre o servidor de autorização a partir do recurso trata disso. Ele atende às necessidades do próprio servidor, como um serviço de terceiros ou um pagamento. No modo URL, accept significa apenas que o usuário consentiu com a interação, não que a interação foi concluída (elicitação). A revisão fixada removeu o campo elicitationId e a notificação notifications/elicitation/complete. O conselho do registro de alterações para um servidor que precisa relacionar um fluxo entre novas tentativas é codificar o seu próprio identificador em requestState (registro de alterações).
O pagamento vem depois da liberação. pay_refund devolve ao cartão do pedido um reembolso liberado, com status requested, e o provedor paga somente sob a conta própria de um lead, autenticado na página do provedor. A ferramenta cria um ID aleatório para o fluxo, coloca-o em requestState e envia o lead para https://pay.fernhill.example/connect/ seguido desse ID, em um domínio reservado que nunca resolve. Um conjunto em memória faz o papel do registro do provedor sobre os fluxos concluídos, e o exemplo adiciona este fluxo antes da terceira chamada.
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
A primeira chamada retornou input_required url, com a URL https://pay.fernhill.example/connect/…, truncada antes do ID aleatório. Depois que o usuário simulado aceitou, a nova tentativa ainda retornou input_required url, pois aceitar significava apenas que o lead concordou em abrir a página. Quando o provedor registrou a autenticação, a tentativa seguinte devolveu complete Paid R-0111 through the payment provider.
O exemplo omite a verificação de que a pessoa que se autentica é a que foi solicitada. Essa verificação exige a identidade de quem faz a chamada, obtida em Obtenha um token com PKCE.
Regra prática: Envie qualquer dado secreto, e qualquer coisa que autentique uma pessoa em outro serviço, pelo modo URL, nunca por um formulário. Coloque o ID próprio do fluxo em requestState, trate accept como "o usuário foi à página", e decida em cada nova tentativa, com base nos registros do próprio servidor, se o fluxo foi concluído. Verifique se a pessoa que conclui um fluxo é a mesma que o iniciou.
Mantenha o estado de ida e volta à prova de adulteração
O reembolso confirmado em Retome a chamada com a resposta depende de o cliente devolver o requestState que recebeu, e nada obriga um cliente a ser honesto. A especificação trata o requestState como entrada controlada pelo atacante, e os servidores DEVEM fazer o mesmo. Quando o estado influencia autorização, acesso a recursos ou lógica de negócio, o servidor DEVE proteger sua integridade (por exemplo, HMAC ou AEAD) e rejeitar o estado que não passar na verificação. Para reduzir reenvios indevidos (replays), um servidor DEVERIA também vincular o estado ao usuário autenticado, dar a ele uma validade curta e amarrá-lo à requisição de onde veio. Nada disso torna um estado de uso único. Um servidor para o qual um estado deve ser usado no máximo uma vez DEVE impor essa invariante do lado do servidor (Requisições de múltiplas rodadas).
O selo do SDK cobre a primeira parte e informa ao cliente o mínimo possível. Se o token mudou, expirou, pertence a outra requisição ou chamador, ou usa uma chave desconhecida, o cliente recebe o mesmo erro JSON-RPC, -32602, "Invalid or expired requestState". O motivo real vai apenas para o log do servidor (mcp/server/request_state.py), de modo que o cliente não aprende nada com uma tentativa falha. Porém, o selo não guarda registro dos tokens que já aceitou, então a segunda parte cabe ao servidor.
Uma confirmação repetida significaria uma segunda liberação de dinheiro, então a ferramenta precisa recusá-la. Desta vez, o cliente envia a repetição de Retome a chamada com a resposta de forma errada de três maneiras, depois de forma correta e depois de forma correta outra vez:
- com um caractere do
requestStateselado alterado; - com o "sim" do protagonista roteirizado, mas sem estado, como se respondesse a uma pergunta que o servidor nunca enviou;
- com o estado correto, mas com o
quote_idde outra cotação; - como uma repetição honesta;
- como a mesma repetição honesta, enviada uma 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.
Um token alterado voltou como -32602 Invalid or expired requestState, e os argumentos trocados voltaram do mesmo modo: -32602 Invalid or expired requestState. O SDK registra um motivo diferente para cada caso, seal para o caractere alterado e request binding para os outros argumentos, e o cliente não recebe nenhum dos dois (mcp/server/request_state.py). Uma resposta sem estado recebeu input_required, the server asks again. A ferramenta trata uma resposta a uma pergunta que nunca foi feita como ausência de resposta, e a especificação diz que um servidor que não recebeu uma resposta DEVERIA perguntar de novo, em vez de devolver um erro (Requisições de múltiplas rodadas).
O reenvio honesto liberou o reembolso: refund R-0111 requested. Enviado de novo, o mesmo reenvio passou pelo selo, porque nada nele havia mudado. O registro próprio do servidor, com os estados já respondidos, o recusou, com o erro da ferramenta "tool error, Error executing tool issue_refund: Refund R-0111 was already confirmed. Don't send the same answer again.". Esse registro é confirmations.OnceOnly, um conjunto de estados mantido sob um lock na memória do servidor, e a ferramenta o consulta antes de pedir à API da loja que libere qualquer valor. Por trás dele, a API responde 409 a uma segunda liberação do mesmo reembolso, de modo que mesmo um servidor que tivesse perdido seu registro não conseguiria pagar duas vezes.
Regra prática: Deixe o selo do SDK proteger todo requestState, e nunca desative o selo para estado que toque dinheiro, acesso ou dados. Mantenha o estado pequeno e opaco: um ID, e não o registro. Para qualquer passo que deve acontecer uma única vez, mantenha no servidor seu próprio registro de estados respondidos, e consulte-o antes do efeito colateral, não depois.
Esta parte ainda não foi traduzida, por isso está em 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.
O que dá errado em produção
A confirmação funciona com um servidor stdio, um cliente e um responsável simulado por script, que responde na hora. Responsáveis reais levam tempo, servidores reiniciam e clientes variam, por isso o padrão falha de algumas formas reconhecíveis.
Estado selado por uma chave que morreu. A chave padrão de MCPServer é criada quando o processo inicia e vive apenas na memória dele (mcp/server/request_state.py). Se o servidor reiniciar entre a pergunta e a resposta, ou se a nova tentativa chegar a outra réplica, o servidor não consegue abrir o estado, e a resposta do responsável falha com -32602. O sinal a observar é "Invalid or expired requestState" aumentar após implantações ou conforme o número de réplicas. Dê a todas as réplicas as mesmas chaves por meio de RequestStateSecurity(keys=[...]). confirmations.state_security(), a política de selagem de Retornar uma solicitação de entrada em vez de um resultado, constrói essas chaves a partir de SHOP_REQUEST_STATE_KEY. A primeira chave sela e todas as chaves abrem, de modo que uma chave pode ser rotacionada sem descartar respostas (Executar réplicas sem sessões fixas).
Um responsável mais lento que o tempo de vida do estado. O estado do SDK dura 600 segundos por rodada, por padrão. Um responsável que lê a pergunta, atende uma ligação e responde quinze minutos depois recebe o mesmo -32602, e o log do servidor diz expired. Defina ttl= como o maior tempo que uma pessoa razoavelmente leva, e deixe o host transformar o erro em uma nova chamada, que pergunta de novo.
Registros que só um processo enxerga. A nova tentativa precisa de dois registros da primeira rodada, e ambos vivem na memória de um único servidor: o armazenamento de cotações do capítulo 3, pelo qual a nova tentativa encontra o reembolso, e confirmations.OnceOnly, o registro das respostas já dadas de Mantenha o estado de ida e volta à prova de adulteração. Atrás de duas réplicas, uma nova tentativa que chegue à outra falha com "There is no quote", e uma resposta reproduzida que chegue a ela passaria pela verificação de uso único. Mantenha os dois registros em armazenamento compartilhado, como faz Executar réplicas sem sessões fixas, e mantenha por trás deles o próprio 409 da API da loja.
Uma resposta de alguém que não é responsável. A ferramenta libera um reembolso a qualquer accept que o host envie, e o host pode responder por código. Pelo stdio, é até onde o servidor consegue verificar. Por HTTP, vincule cada pergunta ao chamador autenticado e verifique se o token do chamador traz refunds:write, o escopo que só os responsáveis de suporte têm (Delimite as ferramentas pelo que o token permite).
Um cliente que não consegue perguntar. Um host cujo cliente não tem callback de elicitação não declara a capacidade de elicitação (mcp/client/session.py), e a chamada falha com -32021, Missing Required Client Capability. A verificação de um resolver roda antes da ferramenta; uma verificação feita à mão, como a de issue_refund, roda dentro dela, depois que a ferramenta do capítulo 3 já reteve o reembolso (confirmations.require_elicitation). O sinal é esse erro aparecer em um host e não nos outros. Um host que atende pessoas deve declarar elicitação e mostrar as perguntas (Responda às solicitações de entrada do usuário). Um servidor cuja ferramenta tenha um padrão seguro, como manter o reembolso retido, pode devolver esse padrão como resultado em vez de falhar.
Um fluxo em modo URL que muda. A especificação marca o modo URL como um recurso cujo design pode mudar em revisões futuras (elicitação), e a revisão fixada já removeu duas de suas partes. Mantenha o código do modo URL em um só lugar e confira-o contra o changelog de cada revisão.
Laços que nunca terminam. Um fluxo em modo URL que o usuário abandona pergunta de novo a cada nova tentativa, e o cliente do SDK para após 10 rodadas com InputRequiredRoundsExceededError. Conte as rodadas de cada fluxo em requestState e, depois de algumas, devolva um resultado informando que a etapa não foi concluída.
Um cliente antigo no mesmo servidor. Um InputRequiredResult devolvido a um cliente que se conectou com o handshake de 2025 chega a ele como -32603, "Handler returned an invalid result". O SDK verifica o resultado contra o CallToolResult de 2025, que exige content (mcp/server/runner.py; requisições de múltiplas idas e voltas). Um servidor que atende aos dois verifica ctx.protocol_version, ou usa resolvers, que escolhem o caminho certo para cada conexão (mcp/server/mcpserver/resolve.py). Atenda clientes antigos e novos durante a janela trata dos dois casos.
Rejeições que ninguém investiga. Cada estado rejeitado dá ao cliente a mesma mensagem, de modo que o único registro do motivo é o log do servidor, sob o logger mcp.server.request_state. Envie esse log para um sistema central, e configure alertas separados para seal e request binding, que indicam que alguém alterou um token, e para expired, que geralmente indica uma pessoa lenta.
Regra prática: Dê às réplicas de um servidor que faz perguntas uma chave compartilhada que possa ser rotacionada, defina o tempo de vida do estado conforme o tempo que as pessoas levam, e mova o armazenamento de cotações e todos os registros de uso único para armazenamento compartilhado antes de ir para produção. Vincule cada pergunta ao chamador sempre que o transporte oferecer essa possibilidade. Depois, acompanhe o -32602 pelo motivo registrado, o -32021 por host e o número de rodadas por chamada.
Decisões que este capítulo tomou
- A API da loja decide quais reembolsos precisam de confirmação.
issue_refundchama primeiro a versão do capítulo 3 e pergunta somente quando a API retém o reembolso, para que o limite da política fique em um só lugar. - O reembolso é retido antes da pergunta, de modo que uma pergunta que ninguém responde deixa o reembolso retido, como no capítulo 3.
- A confirmação é uma solicitação de entrada montada manualmente: uma elicitação em modo formulário sob a chave
confirm, com o ID do reembolso comorequestState, que a nova tentativa verifica contra o reembolso encontrado. O formulário de encomenda devolvida usa um resolvedor, em que a verificação de capacidade e a renderização do SDK economizam código. - O SDK sela cada
requestState, sob chaves que uma implantação pode injetar por meio deconfirmations.state_security()ouSHOP_REQUEST_STATE_KEY, e, caso contrário, sob uma chave que dura enquanto o processo estiver em execução. - As respostas são únicas no servidor, por meio de
confirmations.OnceOnly, verificadas antes da liberação, com o 409 da API como garantia adicional. - Uma resposta sem o estado do servidor, ou com o estado de outro reembolso, equivale a uma pergunta nunca feita, e a ferramenta pergunta novamente.
- O servidor não mantém nenhuma chamada aberta, mas guarda dois registros: o armazenamento de cotações do capítulo 3 e o registro de resposta única, ambos em memória aqui e compartilhados entre réplicas no capítulo 6.
- Em stdio, quem confirma é o usuário do host. Por HTTP, a pergunta fica vinculada ao chamador autenticado, e
refunds:write, o escopo que apenas líderes de suporte possuem, controla o acesso à ferramenta (Defina o escopo das ferramentas de acordo com o que o token permite). - Recusar e cancelar levam a caminhos diferentes: uma recusa é definitiva, e um cancelamento deixa a pergunta em aberto.
- Segredos e logins passam pelo modo URL, com o ID do fluxo em
requestState, eacceptnunca conta como concluído. - A API ganhou dois endpoints,
POST /refunds/{refund_id}/confirmePOST /refunds/{refund_id}/cancel, que agem somente sobre um reembolso retido e respondem 409 nos demais casos. - Valores que o modelo pode ler continuam como argumentos da ferramenta, e valores que só uma pessoa pode fornecer são obtidos por elicitação.
Este capítulo, nesta edição
Edição 2026.11.14Exemplos aprovados em 19 de nov de 20266 de 6 exemplos exemplos deste capítulo passam
Traduzido do livro em inglês, edição 2026.11.14.