Skip to content
MCPA · Chapter 12 of 21 Day 10: Follow-up questions from the server

Day 10: Follow-up questions from the server

Goal: understand how a server requests input from the client in the middle of a call (multi-round-trip), build follow-up questions to the human (elicitation) and to the client’s model (sampling), protect the state between rounds, and write a client with matching callbacks · Duration: about 2.5 h · Prerequisite: Day 9

Where we start

# on cp1
grep -c progress_callback ~/mcpa/tag09/fortschritt.py

Expected: 1

# on cp1
curl -s http://localhost:11434/api/tags | jq -r '.models[].name'

Expected: a list that contains qwen3:4b-instruct.

If something is missing, work through Day 9, Drill 6, or check Ollama as on Day 0. Today you need the uv project on worker1, curl and jq on cp1, and Ollama for Drill 6.

Introduction

Some tools cannot finish in one go. A cleanup tool should delete only after a human has seen the list and given consent. A tool that summarizes logs needs a language model for that – but has none of its own and should share the client’s. In both cases the server needs something from the client, in the middle of the call.

Up to version 2025-11-25, the server sent its own request to the client for this. That required a persistent connection on which both sides can ask. In version 2026-07-28 there are no more sessions, and the server may no longer ask on its own. Instead, it answers the call with “I still need something”. The client gets it and sends the call again, this time with the answers. This pattern is called a Multi-Round-Trip Request (MRTR). Today you build the server freigabe (approval) on worker1 with one tool for each case, play through the rounds by hand with curl first, attack the state between the rounds, and then write a client that asks follow-up questions in the terminal and answers sampling with Ollama.

Today you learn:

  • how a multi-round-trip works: resultType: "input_required", inputRequests, requestState, inputResponses,
  • elicitation in form mode with a restricted JSON Schema and the answers accept, decline, cancel,
  • why the server must treat requestState as an attack surface and how the SDK seals it,
  • sampling: the server uses the client’s model,
  • the capabilities elicitation, sampling, roots and the error -32021,
  • what is deprecated (sampling, roots, logging) and where tasks stand today,
  • how a client answers with elicitation_callback and sampling_callback.

Background

The picture for today: the provider asks back

The cleaning service (a server) is supposed to tidy up in the hotel. Before it throws things away, it wants the guest’s signature. But it may not ring at the guest’s door itself – only the front desk (host and client) talks to guests. So it sends the job back:

  • The returned slip says “I still need something” and carries a form for the guest (inputRequests): “Throw away these three things? Yes/No, reason”.
  • It also encloses a sealed routing slip (requestState) that says which things it showed the guest. The front desk can neither read it nor change it unnoticed.
  • The front desk obtains the signature and sends the same job again – with form and routing slip. Only now does the service tidy up, and exactly what is on the routing slip.
  • If a provider needs an interpreter, it borrows the front desk’s (sampling: the client’s model). It cannot verify what the interpreter says.
  • If the front desk cannot collect signatures, the provider must not even ask – it refuses with -32021.

The terms

Term Meaning In the picture
Multi-round-trip (MRTR) server answers “input needed”, client resends the request with answers returned slip and second job
resultType: "input_required" result type “I still need something” “please complete” on the returned slip
inputRequests / inputResponses embedded follow-up questions / answers with the same keys form / filled-in form
requestState opaque state that the client returns unchanged sealed routing slip
Elicitation follow-up question to the human the guest’s signature
Sampling server uses the client’s model borrowing the front desk’s interpreter
-32021 missing client capability “nobody here can sign”

Remember: The server does not ask, it sends back. The client asks, completes, and sends the same job again with answers and an unchanged routing slip.

The flow in rounds

  1. Round 1: The client calls as usual, for example tools/call.

  2. The server needs something and responds with a result of the kind input_required:

    Field Content
    resultType "input_required" instead of "complete"
    inputRequests a dictionary: self-chosen key → embedded request (elicitation/create, sampling/createMessage, or roots/list)
    requestState an opaque string that the client returns unchanged

    At least one of the last two fields is present.

  3. The client fulfills the embedded requests: it asks the human, calls its model, and so on.

  4. Round 2: The client sends the same request again (with a new id) and adds two fields to params: inputResponses with the same keys as inputRequests, and requestState unchanged.

  5. The server now responds with the result – or needs more and responds with input_required again.

Each round is a complete, self-contained request. The server does not need to remember anything between rounds: what it needs to know is in the requestState. This lets MRTR work over HTTP without sessions, even behind a load balancer. It applies to tools/call, prompts/get, and resources/read.

Elicitation: asking the human

An embedded elicitation/create request in form mode (mode: "form") contains a message and a requestedSchema. The schema is flat: an object with properties of the types string, number, integer, boolean, or an enumeration (enum). Nested objects are not allowed. The client builds a form from it. The answer has an action:

Action Meaning Content
accept the human submitted the form the values
decline the human explicitly declined –
cancel the human closed the form without deciding –

In form mode, no sensitive data may be requested – no passwords, no API keys, no credit cards. For such cases there is URL mode (mode: "url"): the client opens a server URL in the browser, and the data bypasses the client and the model and goes directly to the server.

Sampling: using the client’s model

With sampling/createMessage, a server asks the client to query its language model. It sends messages, maxTokens, and optionally systemPrompt, temperature, and modelPreferences (wishes, not commands). The client responds with role, content, model, and stopReason. The advantage: the server needs no model access of its own and has no costs of its own. The client stays in control. It can show the request to the human, shorten it, or decline it, and it decides which model answers.

Sampling is deprecated in version 2026-07-28. It still works, and the SDK supports it, but new servers should not rely on it. Also deprecated are roots (roots/list: the client tells the server the directories in which it may work) and logging (logging/setLevel, notifications/message).

Capabilities and -32021

A server may only ask for something that the client announced in clientCapabilities: elicitation (with form and/or url), sampling, roots. If a tool needs a capability that is missing, the server responds with -32021 MissingRequiredClientCapability. In data, it names the missing capability under requiredCapabilities.

requestState is input from the client

The client returns requestState – and could modify it on the way. The specification therefore requires servers to treat this value like any other external input: verify instead of trust. The Python SDK seals every requestState with AES-GCM. The client only sees a string like v1.GoZDNg…; it can neither read it nor change it unnoticed, and a seal is valid for only ten minutes. Without its own configuration, the SDK generates a new key when the server starts. After a restart, or on a second server behind the load balancer, an old state is therefore invalid. For several instances, you give all of them the same key (RequestStateSecurity(keys=[…])).

Tasks

For work that takes minutes or hours, there are tasks: the server accepts the job, returns an identifier, and the client later asks for the status or the result. In version 2025-11-25 this was part of the core (tasks/get, tasks/result, tasks/cancel, tasks/list). In 2026-07-28 it is an extension (io.modelcontextprotocol/tasks) that client and server negotiate separately. For the exam, it is enough to know what tasks are for and that they are no longer part of the core.

Drill 1: The server freigabe

Where you are: on worker1.

What you have afterwards: three files to clean up and the server freigabe on port 8002.

Step 1 – something to clean up.

# on worker1
mkdir -p /tmp/mcpa-muell
# on worker1
touch /tmp/mcpa-muell/alt-1.tmp /tmp/mcpa-muell/alt-2.tmp /tmp/mcpa-muell/bericht.bak

touch creates empty files (or updates the timestamp of existing ones).

# on worker1
ls /tmp/mcpa-muell

Expected:

alt-1.tmp  alt-2.tmp  bericht.bak

Step 2 – the server.

# on worker1
mkdir -p ~/mcpa/tag10
# on worker1
cd ~/mcpa/tag10
# on worker1, in ~/mcpa/tag10
nano freigabe.py
~/mcpa/tag10/freigabe.py new file
import json
from pathlib import Path
from typing import Annotated, Literal

from mcp.server import MCPServer
from mcp.server.mcpserver import Context, Resolve, Sample
from mcp.server.transport_security import TransportSecuritySettings
from mcp.shared.exceptions import MCPError
from mcp.types import (
    CreateMessageResult,
    ElicitRequest,
    ElicitRequestFormParams,
    ElicitResult,
    InputRequiredResult,
    SamplingMessage,
    TextContent,
    ToolAnnotations,
)

mcp = MCPServer(
    name="freigabe",
    version="1.0.0",
    instructions="Aufräumen auf worker1 nur nach Freigabe durch den Menschen; Logs mit dem Modell des Clients zusammenfassen.",
)

MUELL = Path("/tmp/mcpa-muell")


@mcp.tool(title="Müll aufräumen", annotations=ToolAnnotations(destructive_hint=True))
async def aufraeumen(ctx: Context) -> str | InputRequiredResult:
    """Löscht die Dateien in /tmp/mcpa-muell, aber erst nach Freigabe durch den Menschen."""
    faehig = ctx.client_capabilities
    if faehig is None or faehig.elicitation is None:
        raise MCPError(
            code=-32021,
            message="Dieses Werkzeug braucht Rückfragen (elicitation), der Client kann sie nicht.",
            data={"requiredCapabilities": {"elicitation": {"form": {}}}},
        )
    if ctx.request_state is None:
        dateien = sorted(p.name for p in MUELL.glob("*") if p.is_file())
        if not dateien:
            return "Nichts zu löschen."
        frage = ElicitRequest(
            params=ElicitRequestFormParams(
                message=f"{len(dateien)} Dateien in {MUELL} löschen: {', '.join(dateien)}?",
                requested_schema={
                    "type": "object",
                    "properties": {
                        "loeschen": {"type": "boolean", "title": "Wirklich löschen?"},
                        "grund": {"type": "string", "title": "Grund", "maxLength": 100},
                    },
                    "required": ["loeschen"],
                },
            )
        )
        return InputRequiredResult(input_requests={"freigabe": frage}, request_state=json.dumps(dateien))

    dateien = json.loads(ctx.request_state)
    antwort = (ctx.input_responses or {}).get("freigabe")
    if not isinstance(antwort, ElicitResult) or antwort.action != "accept":
        return "Nicht gelöscht: Der Mensch hat nicht zugestimmt."
    inhalt = antwort.content or {}
    if inhalt.get("loeschen") is not True:
        return "Nicht gelöscht: Löschen wurde nicht bestätigt."
    geloescht = 0
    for name in dateien:
        datei = MUELL / name
        if datei.exists():
            datei.unlink()
            geloescht += 1
    return f"{geloescht} von {len(dateien)} Dateien gelöscht. Grund: {inhalt.get('grund') or '-'}"


def zusammenfassung_anfordern(datei: Literal["dpkg.log", "alternatives.log"]) -> Sample:
    """Liest die letzten Zeilen des Logs und bittet das Modell des Clients um eine Zusammenfassung."""
    zeilen = (Path("/var/log") / datei).read_text().splitlines()[-15:]
    text = "Fasse diese Logzeilen in höchstens zwei Sätzen auf Deutsch zusammen:\n" + "\n".join(zeilen)
    return Sample(
        messages=[SamplingMessage(role="user", content=TextContent(type="text", text=text))],
        max_tokens=150,
    )


@mcp.tool(title="Log zusammenfassen", annotations=ToolAnnotations(read_only_hint=True))
def log_zusammenfassen(
    datei: Literal["dpkg.log", "alternatives.log"],
    antwort: Annotated[CreateMessageResult, Resolve(zusammenfassung_anfordern)],
) -> str:
    """Fasst die letzten Zeilen eines Logs auf worker1 zusammen. Benutzt dafür das Modell des Clients."""
    return f"Zusammenfassung von {datei} (Modell {antwort.model}): {antwort.content.text}"


schutz = TransportSecuritySettings(
    enable_dns_rebinding_protection=True,
    allowed_hosts=["worker1:8002", "172.16.0.228:8002"],
    allowed_origins=[],
)

mcp.run(transport="streamable-http", host="0.0.0.0", port=8002, transport_security=schutz)
# on worker1, in ~/mcpa/tag10
uv run python freigabe.py

Expected (the last line):

INFO:     Uvicorn running on http://0.0.0.0:8002 (Press CTRL+C to quit)

The tool aufraeumen (clean up) builds the flow by hand:

  • The return type str | InputRequiredResult tells the SDK: the tool returns either a result or a request for input.
  • ctx.client_capabilities are the capabilities from the request’s _meta. If elicitation is missing, the tool aborts with MCPError(code=-32021, …). MCPError is a protocol error, not a tool error: the client gets error instead of isError. It would be pointless to ask a client that cannot handle follow-up questions.
  • The tool recognizes round 1 by ctx.request_state is None. It collects the file names (MUELL.glob("*") returns all entries, is_file() only files) and returns an InputRequiredResult:
    • input_requests={"freigabe": frage} – under the key freigabe, an embedded ElicitRequest in form mode with a message and a schema. loeschen (delete) is a required field of type boolean, grund (reason) an optional text of at most 100 characters. title is the label in the form.
    • request_state=json.dumps(dateien) – the list of files that the human gets to see.
  • Round 2 reads the state back with json.loads(ctx.request_state) and fetches the answer from ctx.input_responses under the same key. Files are deleted only if the answer is an ElicitResult with action == "accept" and loeschen really is True. Everything else – decline, cancel, a missing answer – leads to “Nicht gelöscht” (“not deleted”).
  • Only the files from the state are deleted, not all the files currently in the directory. If a file appears between the rounds, the human never saw it – so it stays. What is counted is what was actually deleted.

The tool log_zusammenfassen (summarize log) shows the SDK’s more convenient way:

  • The parameter antwort: Annotated[CreateMessageResult, Resolve(zusammenfassung_anfordern)] is not filled by the model but by the function zusammenfassung_anfordern (request summary). Only datei (file) appears in the tool’s schema.
  • zusammenfassung_anfordern receives datei (the SDK passes on tool arguments with the same name), reads the last 15 lines (splitlines()[-15:]), and returns a Sample(...): a sampling request with one message of role user and at most 150 tokens.
  • The SDK does the rest: it checks the sampling capability, builds the InputRequiredResult, seals the state, and calls the tool in round 2 with the client’s answer.
  • Literal["dpkg.log", "alternatives.log"] allows only these two files. So nobody can pass ../../etc/shadow as the file.

Instead of Sample, Resolve can also return Elicit(message, schema) or ListRoots(). However, the two approaches – by hand and with Resolve – cannot be mixed in one tool.

Remember: By hand: InputRequiredResult with form and routing slip, recognize round 2 by ctx.request_state. Convenient: Resolve(…) – the SDK handles the capability check, the seal, and the second round.

Save your progress? Sign up for free

Drill 2: Round 1 with curl

Where you are: on cp1, in a second terminal.

What you have afterwards: the input_required response with the follow-up question and the sealed state in runde1.out.

Step 1 – Directory and headers.

# on cp1
mkdir -p ~/mcpa/tag10
# on cp1
cd ~/mcpa/tag10
# on cp1, in ~/mcpa/tag10
KOPF=(-H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28")

Step 2 – The body.

# on cp1, in ~/mcpa/tag10
nano runde1.json
~/mcpa/tag10/runde1.json new file
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"aufraeumen","arguments":{},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}}}}}

This time, the client announces "elicitation":{"form":{}} in clientCapabilities: it can answer form questions.

Step 3 – Send round 1 and save the response.

# on cp1, in ~/mcpa/tag10
curl -s http://worker1:8002/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: aufraeumen" --data @runde1.json > runde1.out

> runde1.out saves the response, because you will need the routing slip shortly.

Step 4 – Look at the response. jq . prints it indented:

# on cp1, in ~/mcpa/tag10
jq . runde1.out

Expected (your state is a different string):

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "inputRequests": {
      "freigabe": {
        "method": "elicitation/create",
        "params": {
          "message": "3 Dateien in /tmp/mcpa-muell löschen: alt-1.tmp, alt-2.tmp, bericht.bak?",
          "mode": "form",
          "requestedSchema": {
            "properties": {
              "loeschen": {
                "type": "boolean",
                "title": "Wirklich löschen?"
              },
              "grund": {
                "type": "string",
                "title": "Grund",
                "maxLength": 100
              }
            },
            "required": [
              "loeschen"
            ],
            "type": "object"
          }
        }
      }
    },
    "requestState": "v1.GoZDNgzJMb2ENcC4XntXCTwmFHyl3pk07SwJsu-CEg5kuhWMeJJZ0kMbgI7BqJ2PsZ3rQyJ4sPm5gzBOe9u-osVbfamo3Wc1khNJJgveIkBI1CxYt0i5qVjchPaErWH1ku4VIvpE4Um-ECrTiM0PILocrmLUqEhkyahmgW6s6YZcN1w7CqClklqFXWGkfTV9ioQu_KK2epKU5NEQqsis1LmUMRyTozvFASkLD_5-rtNoY_41D42m-UQB9kI3K8OWwiT51BPs798BTw4ln-JQ5sfgqsaxrPkZSt98rJ9-ng",
    "resultType": "input_required",
    "_meta": {
      "io.modelcontextprotocol/serverInfo": {
        "name": "freigabe",
        "version": "1.0.0"
      }
    }
  }
}

There is no content and no isError: this is not a result yet. resultType is input_required. In inputRequests, under the key freigabe, there is a complete elicitation/create request, exactly as it would have arrived from the server as a separate message in version 2025-11-25. requestState is the file list – but sealed. Nothing of ["alt-1.tmp", …] can be seen.

Remember: input_required is not a result yet: no content, no isError – only a form and a sealed routing slip.

Save your progress? Sign up for free

Drill 3: Round 2 – decline and accept

Where you are: on cp1, in ~/mcpa/tag10.

What you have afterwards: a declined and a confirmed second round. The files on worker1 are deleted.

Step 1 – decline. The second round is runde1.json with a new id and two additional fields. jq assembles it:

# on cp1, in ~/mcpa/tag10
jq -c --slurpfile r runde1.out '.id=2 | .params.requestState=$r[0].result.requestState | .params.inputResponses={"freigabe":{"action":"decline"}}' runde1.json > ablehnen.json
  • --slurpfile r runde1.out reads the file runde1.out and makes its content available as a list in the variable $r. $r[0] is the response from round 1.
  • The filter modifies runde1.json in three steps, joined with |:
    • .id=2 sets a new id – it is a new request.
    • .params.requestState=$r[0].result.requestState takes over the state unchanged.
    • .params.inputResponses={"freigabe":{"action":"decline"}} answers the follow-up question freigabe with “declined”.
  • -c writes the result on one line, and > ablehnen.json (decline) writes it to a file.

You cannot type the routing slip by hand – it is different on every run. That is why jq builds the file here instead of nano.

Now send the second round:

# on cp1, in ~/mcpa/tag10
curl -s http://worker1:8002/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: aufraeumen" --data @ablehnen.json | jq -c .result.content

Expected:

[{"text":"Nicht gelöscht: Der Mensch hat nicht zugestimmt.","type":"text"}]

Step 2 – accept.

# on cp1, in ~/mcpa/tag10
jq -c --slurpfile r runde1.out '.id=3 | .params.requestState=$r[0].result.requestState | .params.inputResponses={"freigabe":{"action":"accept","content":{"loeschen":true,"grund":"Übung Tag 10"}}}' runde1.json > zustimmen.json

This time the answer is accept with the form values in content.

# on cp1, in ~/mcpa/tag10
curl -s http://worker1:8002/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: aufraeumen" --data @zustimmen.json | jq -c .result.content

Expected:

[{"text":"3 von 3 Dateien gelöscht. Grund: Übung Tag 10","type":"text"}]

Check on worker1 with ls /tmp/mcpa-muell: the directory is empty. With the same state from round 1, you sent two different second rounds. The server remembered nothing in between – everything was in the requestState.

Remember: The same round 1, two different rounds 2 – the server remembers nothing. Everything it needs to know is on the routing slip.

Save your progress? Sign up for free

Drill 4: Attack the state

Where you are: on cp1, in ~/mcpa/tag10, and on worker1 in the server’s terminal.

What you have afterwards: three attempts to abuse the state, and the server’s responses.

A seal is valid for ten minutes. If you need longer, repeat Drill 2.

Step 1 – tamper.

# on cp1, in ~/mcpa/tag10
jq -c '.params.requestState |= sub("^v1\\.."; "v1.X")' ablehnen.json > verfaelscht.json
  • |= changes a field based on its previous value.
  • sub(pattern; replacement) replaces the first match of a regular expression. ^v1\\.. means “v1. at the start followed by any character”; the double backslash is needed because the expression is inside a JSON string. Afterwards, the state differs in a single character.

Send the tampered routing slip:

# on cp1, in ~/mcpa/tag10
curl -s http://worker1:8002/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: aufraeumen" --data @verfaelscht.json

The response ends without a line break; that is why the prompt appears right after it.

Expected:

{"jsonrpc":"2.0","id":2,"error":{"code":-32602,"message":"Invalid or expired requestState","data":{"reason":"invalid_request_state"}}}

A single changed character is enough, and the seal breaks. The server responds with -32602 (Invalid params). It writes the exact reason only to its own log, not into the response – an attacker should not learn what they did wrong.

Step 2 – replay a round. Create two new files on worker1:

# on worker1, in a second terminal
touch /tmp/mcpa-muell/a.tmp /tmp/mcpa-muell/b.tmp

Then on cp1, a fresh round 1:

# on cp1, in ~/mcpa/tag10
curl -s http://worker1:8002/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: aufraeumen" --data @runde1.json > runde1.out

What is shown to the human? jq -r prints the message without quotation marks:

# on cp1, in ~/mcpa/tag10
jq -r .result.inputRequests.freigabe.params.message runde1.out

Expected: 2 Dateien in /tmp/mcpa-muell löschen: a.tmp, b.tmp?

And the acceptance for it:

# on cp1, in ~/mcpa/tag10
jq -c --slurpfile r runde1.out '.id=3 | .params.requestState=$r[0].result.requestState | .params.inputResponses={"freigabe":{"action":"accept","content":{"loeschen":true,"grund":"Übung"}}}' runde1.json > zustimmen.json

Before you accept, a file appears on worker1 that the human has not seen:

# on worker1, in the second terminal
touch /tmp/mcpa-muell/neu.tmp

Now you send the acceptance twice. The first time:

# on cp1, in ~/mcpa/tag10
curl -s http://worker1:8002/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: aufraeumen" --data @zustimmen.json | jq -c .result.content

Expected:

[{"text":"2 von 2 Dateien gelöscht. Grund: Übung","type":"text"}]

And the same command once more:

# on cp1, in ~/mcpa/tag10
curl -s http://worker1:8002/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: aufraeumen" --data @zustimmen.json | jq -c .result.content

Expected:

[{"text":"0 von 2 Dateien gelöscht. Grund: Übung","type":"text"}]

On worker1, ls /tmp/mcpa-muell now shows only neu.tmp. Two things are visible:

  • The new file has stayed. What was deleted is what was in the state – that is, what the human approved.
  • The second call with the same state was accepted. The seal protects against modification, not against replay. A tool that changes something must therefore handle round 2 arriving more than once by itself. Here it is harmless: gone is gone.

Step 3 – restart the server. Stop the server on worker1 with Ctrl+C and restart it with uv run python freigabe.py. Then once more:

# on cp1, in ~/mcpa/tag10
curl -s http://worker1:8002/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: aufraeumen" --data @zustimmen.json | jq -c .error

Expected:

{"code":-32602,"message":"Invalid or expired requestState","data":{"reason":"invalid_request_state"}}

The new process has a new key and cannot open the old seal. With a single server this is no problem: the client starts over with round 1. Behind a load balancer with several instances, all of them would need the same key.

Remember: The seal protects against modification, not against replay – and it is valid only for the process that issued it, for ten minutes.

Save your progress? Sign up for free

Drill 5: Sampling and capabilities

Where you are: on cp1, in ~/mcpa/tag10.

What you have afterwards: two responses with -32021 and a sampling round that you answer by hand.

Step 1 – without the capability. The body for log_zusammenfassen (summarize log), with empty capabilities:

# on cp1, in ~/mcpa/tag10
nano sampling.json
~/mcpa/tag10/sampling.json new file
{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"log_zusammenfassen","arguments":{"datei":"dpkg.log"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
# on cp1, in ~/mcpa/tag10
curl -s -w ' -> HTTP %{http_code}\n' http://worker1:8002/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: log_zusammenfassen" --data @sampling.json

Expected:

{"jsonrpc":"2.0","id":5,"error":{"code":-32021,"message":"Client did not declare the sampling capability required by resolver '__main__:zusammenfassung_anfordern'","data":{"requiredCapabilities":{"sampling":{}}}}} -> HTTP 400

The same for aufraeumen: runde1.json, but without capabilities. jq sets them to an empty object:

# on cp1, in ~/mcpa/tag10
jq -c '.params._meta["io.modelcontextprotocol/clientCapabilities"]={}' runde1.json > ohne-faehigkeit.json

.params._meta["io.modelcontextprotocol/clientCapabilities"]={} sets the capabilities to an empty object. In jq, you write keys containing / or . in square brackets and quotes.

# on cp1, in ~/mcpa/tag10
curl -s -w ' -> HTTP %{http_code}\n' http://worker1:8002/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: aufraeumen" --data @ohne-faehigkeit.json

Expected:

{"jsonrpc":"2.0","id":1,"error":{"code":-32021,"message":"Dieses Werkzeug braucht Rückfragen (elicitation), der Client kann sie nicht.","data":{"requiredCapabilities":{"elicitation":{"form":{}}}}}} -> HTTP 400

Both tools respond with -32021 and HTTP 400. data.requiredCapabilities says what is missing. For the first, the SDK did the check itself via Resolve; for the second, your own code did.

Step 2 – round 1 with the capability. First a copy of sampling.json that announces sampling:

# on cp1, in ~/mcpa/tag10
jq -c '.params._meta["io.modelcontextprotocol/clientCapabilities"]={"sampling":{}}' sampling.json > sampling1.json

Send round 1 and save the response:

# on cp1, in ~/mcpa/tag10
curl -s http://worker1:8002/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: log_zusammenfassen" --data @sampling1.json > sampling1.out

What does the server ask for?

# on cp1, in ~/mcpa/tag10
jq -c '.result.inputRequests | to_entries[] | {key, method: .value.method, maxTokens: .value.params.maxTokens}' sampling1.out

to_entries turns a dictionary into a list of pairs with key and value. This lets you see the key and the content side by side.

Expected:

{"key":"__main__:zusammenfassung_anfordern","method":"sampling/createMessage","maxTokens":150}

The SDK built the key from the module and function name. The embedded request is sampling/createMessage. With jq '.result.inputRequests[].params.messages[0].content.text' sampling1.out you see the full text with the log lines.

Step 3 – answer by hand. You now play the model:

# on cp1, in ~/mcpa/tag10
jq -c --slurpfile r sampling1.out '.id=6 | .params.requestState=$r[0].result.requestState | .params.inputResponses={($r[0].result.inputRequests|keys[0]): {"role":"assistant","content":{"type":"text","text":"Alles ruhig, nichts Auffälliges."},"model":"von-hand"}}' sampling1.json > sampling2.json
  • ($r[0].result.inputRequests|keys[0]) in parentheses uses a computed value as the key – the key from round 1. keys[0] is the first (and only) key.
  • The answer has the shape of a CreateMessageResult: role, content, and model.
# on cp1, in ~/mcpa/tag10
curl -s http://worker1:8002/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: log_zusammenfassen" --data @sampling2.json | jq -c .result.content

Expected:

[{"text":"Zusammenfassung von dpkg.log (Modell von-hand): Alles ruhig, nichts Auffälliges.","type":"text"}]

The server accepted your made-up answer (“All quiet, nothing unusual”). It cannot check whether a model really answered, or which one. For the server, a sampling result is therefore input from the client, just as untrustworthy as tool arguments. A server must not base security decisions on sampling answers.

Remember: The server may only ask for capabilities the client announced (otherwise -32021). And what the borrowed interpreter says is input from the client – never a check.

Save your progress? Sign up for free

Drill 6: A client with callbacks

Where you are: on cp1, in ~/mcpa/tag10, and on worker1 in the second terminal.

What you have afterwards: freigabe_client.py, which asks follow-up questions in the terminal and answers sampling with Ollama.

Create something to clean up on worker1 again:

# on worker1, in the second terminal
touch /tmp/mcpa-muell/alt-1.tmp /tmp/mcpa-muell/alt-2.tmp

Then on cp1:

# on cp1, in ~/mcpa/tag10
nano freigabe_client.py
~/mcpa/tag10/freigabe_client.py new file
import asyncio
import sys

import httpx
from mcp import Client
from mcp.types import CreateMessageResult, ElicitResult, TextContent

URL = "http://worker1:8002/mcp"
OLLAMA = "http://localhost:11434/api/chat"
MODELL = "qwen3:4b-instruct"


async def rueckfrage(context, params) -> ElicitResult:
    """Zeigt eine Rückfrage des Servers als Formular im Terminal."""
    print(f"[server fragt] {params.message}")
    if input("[client] Antworten? [j/N] ").strip().lower() != "j":
        return ElicitResult(action="decline")
    inhalt = {}
    for name, feld in params.requested_schema["properties"].items():
        eingabe = input(f"[client] {feld.get('title', name)}: ").strip()
        if feld["type"] == "boolean":
            inhalt[name] = eingabe.lower() in ("j", "ja")
        elif eingabe:
            inhalt[name] = eingabe
    return ElicitResult(action="accept", content=inhalt)


async def modell(context, params) -> CreateMessageResult:
    """Beantwortet eine Sampling-Anfrage des Servers mit dem lokalen Modell."""
    nachrichten = [{"role": m.role, "content": m.content.text} for m in params.messages]
    print(f"[client] Server möchte das Modell benutzen ({len(nachrichten)} Nachricht, höchstens {params.max_tokens} Tokens)")
    async with httpx.AsyncClient() as http:
        antwort = await http.post(OLLAMA, json={
            "model": MODELL, "stream": False, "messages": nachrichten,
            "options": {"num_predict": params.max_tokens},
        }, timeout=300)
    text = antwort.json()["message"]["content"]
    return CreateMessageResult(role="assistant", content=TextContent(type="text", text=text), model=MODELL, stop_reason="endTurn")


async def main(werkzeug: str, argumente: dict) -> None:
    async with Client(URL, elicitation_callback=rueckfrage, sampling_callback=modell) as client:
        ergebnis = await client.call_tool(werkzeug, argumente)
        print("[ergebnis]", ergebnis.content[0].text)


if len(sys.argv) > 2:
    asyncio.run(main(sys.argv[1], {"datei": sys.argv[2]}))
else:
    asyncio.run(main(sys.argv[1], {}))
  • rueckfrage(context, params) (follow-up question) is the callback for elicitation. params contains message and requested_schema. The function shows the message, asks whether the human wants to answer at all (otherwise ElicitResult(action="decline")), and then walks through the schema’s fields generically:
    • feld.get("title", name) shows the label if present, otherwise the name.
    • For boolean, j or ja (German “yes”) becomes the value True.
    • Other fields are only taken over if something was entered; an empty optional field is then missing from content.
    The client does not know the tool aufraeumen – it builds the form from the schema. That way it works with any server.
  • modell(context, params) (model) is the callback for sampling. It converts params.messages into Ollama’s message format, limits the length with "options": {"num_predict": params.max_tokens}, and returns a CreateMessageResult: role assistant, text, model name, and stop_reason="endTurn" (the model finished on its own). The print line makes it visible that the server wants to use the model – a real host would ask for consent here.
  • Client(URL, elicitation_callback=rueckfrage, sampling_callback=modell): with the two callbacks, the SDK announces the capabilities elicitation and sampling by itself. When it receives an input_required, it calls the matching callbacks and sends the next round. You see none of this in call_tool; it returns the final result.
  • sys.argv[1] is the name of the tool. If there is a second argument, it is passed as datei.

Step 1 – cleanup with a follow-up question.

# on cp1, in ~/mcpa/tag10
uv run python freigabe_client.py aufraeumen

Answer the three questions with j, j, and a reason, for example Übung.

Expected:

[server fragt] 3 Dateien in /tmp/mcpa-muell löschen: alt-1.tmp, alt-2.tmp, neu.tmp?
[client] Antworten? [j/N] j
[client] Wirklich löschen?: j
[client] Grund: Übung
[ergebnis] 3 von 3 Dateien gelöscht. Grund: Übung

This time neu.tmp from Drill 4 is in the list – the human has seen it and approved it.

Step 2 – summary with the client’s model.

# on cp1, in ~/mcpa/tag10
uv run python freigabe_client.py log_zusammenfassen dpkg.log

Expected (after up to one minute; the text depends on the log content and the model):

[client] Server möchte das Modell benutzen (1 Nachricht, höchstens 150 Tokens)
[ergebnis] Zusammenfassung von dpkg.log (Modell qwen3:4b-instruct): Der Paketstatus für runc zeigt eine halbinstallierte und eine nicht installierte Version, während man-db erfolgreich eingerichtet und installiert wird. ...

The server on worker1 has no model. It used the model on cp1, through the client, and the client saw every request along the way.

Remember: With elicitation_callback and sampling_callback, the client announces its capabilities and answers the returned slips itself – call_tool delivers only the final result.

Save your progress? Sign up for free

If it doesn’t work

  • Invalid or expired requestState even though you changed nothing: The seal is older than ten minutes, or the server was restarted since round 1. Repeat round 1 (Drill 2) and rebuild the second round.
  • jq: error … Cannot index null with "requestState": runde1.out contains not a response with result but an error. Look at the file with jq . runde1.out.
  • Nichts zu löschen. (“nothing to delete”): /tmp/mcpa-muell on worker1 is empty. Create files with touch.
  • -32021 for aufraeumen even though the client can handle follow-up questions: runde1.json is missing "elicitation":{"form":{}} in clientCapabilities.
  • EOFError: EOF when reading a line in freigabe_client.py: The program needs input in the terminal. Do not start it with a pipe that provides no answers.
  • httpx.ConnectError during sampling: Ollama is not running on cp1. Check with systemctl status ollama.

Exercise: Cancel instead of decline (10 min)

For a new round 1 of aufraeumen, send a second round with "action":"cancel". What does the server respond? What is the difference between decline and cancel for a host?

Solution

A fresh round 1:

# on cp1, in ~/mcpa/tag10
curl -s http://worker1:8002/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: aufraeumen" --data @runde1.json > runde1.out

The second round with cancel:

# on cp1, in ~/mcpa/tag10
jq -c --slurpfile r runde1.out '.id=4 | .params.requestState=$r[0].result.requestState | .params.inputResponses={"freigabe":{"action":"cancel"}}' runde1.json > abbrechen.json
# on cp1, in ~/mcpa/tag10
curl -s http://worker1:8002/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: aufraeumen" --data @abbrechen.json | jq -c .result.content

Expected (if there are no files in the directory, you already get Nichts zu löschen. in round 1):

[{"text":"Nicht gelöscht: Der Mensch hat nicht zugestimmt.","type":"text"}]

For this tool, both are the same: without accept, nothing is deleted. For a host, the difference still matters. decline is a deliberate decision (“no”) that the host can pass on to the model so that it does not ask again. cancel means “no decision”, for example because the human closed the window. A host could ask again later.

Save your progress? Sign up for free

Challenge: Follow-up questions in the host (20 min)

Your host from Day 8 does not know about follow-up questions yet. What do you need to change so that the model can use aufraeumen on worker1 and the human answers the follow-up question in the terminal? And does aufraeumen then still need the consent from Day 5?

Solution

Three changes are enough:

  1. Copy the function rueckfrage from freigabe_client.py into host.py.
  2. Register the server: "freigabe": "http://worker1:8002/mcp" in SERVER.
  3. Pass the callback when creating the clients: Client(parameter, elicitation_callback=rueckfrage).

The host’s loop stays unchanged, because call_tool handles the rounds itself. On the second question: aufraeumen has destructive_hint=True and is not in VERTRAUT (trusted), so the host asks before the call as on Day 5. After that, the server asks as well. The two questions have different jobs: the host’s consent protects against a model that calls tools without asking. The server’s follow-up question shows the human exactly what will happen – only the server knows the file list. Because the human answers the follow-up question, not the model, the model cannot skip it either.

Save your progress? Sign up for free

Checkpoint

# on cp1, in ~/mcpa/tag10
jq -r .result.resultType runde1.out

Expected: input_required (or null if the last round 1 returned Nichts zu löschen. – then create files on worker1 and repeat Drill 2)

# on cp1, in ~/mcpa/tag10
grep -c -e elicitation_callback -e sampling_callback freigabe_client.py

Expected: 1

Afterwards, stop the server on worker1 with Ctrl+C.

Exam questions

1. A server needs a confirmation from the human during a tools/call. How does this work in version 2026-07-28?

    1. The server sends its own elicitation/create request to the client and waits.
    1. The server responds with resultType: "input_required" and inputRequests; the client repeats the call with inputResponses and requestState.
    1. The server responds with isError: true and a question in the text.
    1. The server opens subscriptions/listen and sends the question there.

2. How should a server handle the requestState that a client sends back?

    1. It can trust it; after all, it comes from the server.
    1. It must treat it like any external input and protect it against modification.
    1. It may only use it over HTTP.
    1. It must store it in a session.

3. A tool needs sampling, and the client has not announced sampling. Which response is correct?

    1. -32601 Method not found
    1. -32021 MissingRequiredClientCapability
    1. -32020 HeaderMismatch
    1. a result with isError: true

4. Which data may a server not request in elicitation form mode?

    1. a yes/no decision
    1. a reason as free text
    1. a password or an API key
    1. a choice from a list

5. Which statement about sampling in version 2026-07-28 is correct?

    1. It is new and replaces elicitation.
    1. It is deprecated but still works via input_required.
    1. It was removed without replacement.
    1. It is only reachable through the tasks extension.

Solutions

  1. B. Servers may no longer send their own requests to the client. Input is requested via input_required and a repeated call.
  2. B. requestState comes from the client and may have been modified. That is why the SDK seals it.
  3. B. The server reports missing client capabilities with -32021 and requiredCapabilities.
  4. C. Sensitive data belongs in URL mode, where the data bypasses the client and goes to the server.
  5. B. Sampling, roots, and logging are deprecated but still part of the specification.

Interview Note

“Why did MCP abolish requests from the server to the client?” – Because they require a persistent, two-way connection. Over HTTP this meant: sessions, a second stream for server messages, and servers that have to remember which question belongs to which call. Behind a load balancer this was difficult: the answer could arrive at a different instance than the question. With MRTR, every round is an ordinary request, and the state travels along, sealed. The server stays stateless, and every instance can serve every round, as long as all of them have the same key.

Enterprise Note

Elicitation is the tool for the “four-eyes principle” and approvals: the server defines what a human must confirm, and no model can answer that question. In production, three things belong to this. First, a shared key for requestState on all instances, with rotation (keys=[neu, alt], new and old). Second, tools that tolerate a repeated second round. Third, an audit log recording who approved what (Day 14). Sampling, on the other hand, is something a company should allow cautiously: a server that queries a model through the client consumes the client’s budget and sees its answers. Hosts should display sampling requests, limit them, and make them possible to switch off.

Summary

  • MRTR: The server responds with resultType: "input_required", inputRequests (key → elicitation/create, sampling/createMessage, roots/list), and/or requestState. The client repeats the request with inputResponses (same keys) and an unchanged requestState. Applies to tools/call, prompts/get, and resources/read.
  • Servers no longer send their own requests to the client. Each round is a self-contained request.
  • Elicitation: form mode with a flat schema (string, number, integer, boolean, enum), answer accept/decline/cancel. No sensitive data in the form; URL mode exists for that.
  • Sampling: The server uses the client’s model. The answer is input from the client. Sampling, roots, and logging are deprecated. Tasks are an extension.
  • Missing client capability: -32021 with requiredCapabilities.
  • requestState is external input. The SDK seals it (AES-GCM, 10 minutes, key per process). A tampered or old state yields -32602. The seal does not prevent replay.
  • SDK: InputRequiredResult, ctx.request_state, ctx.input_responses, Resolve with Sample/ Elicit/ListRoots; in the client elicitation_callback and sampling_callback.

Commands at a glance

For review: all commands and SDK calls of this day with the parameters you used.

Command / call What it does Parameters
InputRequiredResult(input_requests={…}, request_state=…) request input instead of a result keys freely chosen
ElicitRequest(params=ElicitRequestFormParams(message=…, requested_schema=…)) follow-up question in form mode flat JSON Schema
ctx.request_state · ctx.input_responses state and answers of the previous round None in round 1
ctx.client_capabilities the client’s capabilities .elicitation, .sampling
MCPError(code=-32021, message=…, data=…) raise a protocol error requiredCapabilities
Annotated[T, Resolve(funktion)] have a function fill a parameter function returns Sample/Elicit/ListRoots
Sample(messages=[…], max_tokens=…) sampling request SamplingMessage(role, content)
Client(url, elicitation_callback=…, sampling_callback=…) client with callbacks announces capabilities
ElicitResult(action=…, content=…) answer to a follow-up question accept, decline, cancel
CreateMessageResult(role, content, model, stop_reason) answer to sampling stop_reason="endTurn"
jq --slurpfile r datei '… $r[0] …' read another file as a variable $r is a list
jq '.feld \|= sub(muster; ersatz)' change a field with a regular expression \|= changes based on the old value
jq 'to_entries[]' · keys[0] dictionary as pairs · first key {(ausdruck): wert} computed key
touch datei create an empty file –
nano <file> create a server, client, or body –

Contents

More