Use MCP Elicitation in Python to Build a Grouped Report Preview

Build a typed MCP elicitation form in Python, verify the report preview and refusal paths in memory, and add an explicit argument for clients without forms.

Conceptual MCP elicitation form with team selected for report:weekly-01 and the resulting Platform and Product preview.Conceptual MCP elicitation form with team selected for report:weekly-01 and the resulting Platform and Product preview.
Illustrative accepted team choice for report:weekly-01. The typed choice controls the preview. Form and result behavior follow the MCP Python SDK.

Your weekly report tool knows which rows to count. A caller asks for report:weekly-01 and leaves out the grouping. A team summary and a repository summary answer different questions, and either can look plausible if the caller guesses. With MCP elicitation, your Python server can ask for that one choice, receive a typed answer, and return counts that the calling application can verify.

Start with a Python environment that already has the v2 MCP Python SDK, Pydantic, and AnyIO. You’ll put the server and test client in two files and run them in one process. The server counts four hardcoded activity rows. The client checks the question, the allowed answers, and the final structured result. It also exercises a second tool that accepts an explicit grouping for clients without forms. The fixture uses no model, listening port, or external writes. The output shown here is expected from the fixture and documented SDK behavior. SDK v2 overview · SDK in-memory testing

On December 3, 2026, Sourcegraph described a local replay of its Agentic Batch Changes integration in which a native MCP form preserved an optional text field and the client continued after submission. It also reported that a different client returned decline without displaying the form. Those observations motivate two checks in this tutorial. Verify that an accepted answer makes it all the way back to the tool’s result, and make the result clear when the form supplies no answer. Sourcegraph’s account of MCP tool UX

Choose a fixture that exposes the grouping

  1. Use report:weekly-01 as the only valid report ID. Each row represents one activity and supplies its team and repository.
  2. Count the rows by hand along both dimensions. Use those counts as the answer key in the test client.
  3. Require one form field named grouping with the exact values team and repository. Leave the field without a default so the preview depends on an explicit answer.

The four rows, in order, are Platform/api, Platform/web, Product/web, and Platform/api. Grouped by team, the first, second, and fourth rows contribute to Platform and the third contributes to Product. Grouped by repository, the first and fourth contribute to api and the second and third contribute to web. Both views count four activities. The keys and the distribution change with the requested grouping.

Four horizontal bars show team counts of 3 and 1 and repository counts of 2 and 2.Four horizontal bars show team counts of 3 and 1 and repository counts of 2 and 2.
Illustrative report:weekly-01 counts. The same four activity rows give a 3–1 split by team and a 2–2 split by repository.

The repeated Platform/api pair represents two distinct activities. If you turn the fixture into a set of team and repository pairs before counting, the API bucket falls to one and the Platform bucket falls to two. The shared web repository catches a different mistake. If you group repositories inside each team, the two web activities land in different buckets even though the repository view should show a single web count of two. Compare the entire returned dictionary. A total of four alone would let a grouping error pass.

Use the report ID to write the question the person sees. Group report:weekly-01 by team or repository? identifies both the subject and the decision. Literal["team", "repository"] renders as a string enum in the form schema. A flat, one-field Pydantic model fits the SDK’s form mode and lets the client render the choice from the schema. The server already has the report ID and rows. Form answers are exposed to the MCP client, and the spec requires URL mode for interactions involving secrets such as passwords and API keys. SDK elicitation guide · MCP elicitation specification

Decide what the caller can display for each action. A result with status=preview carries the grouping and counts. A result with status=declined or status=cancelled carries the original report ID and null values for grouping and preview. The report ID lets the application associate the outcome with the request that produced it. A future report with zero activity could return a successful preview with an empty dictionary. Using null for decline and cancellation gives the caller a distinct value for the absence of a preview.

Build the resolver and the preview tool

  1. Save the first block as report_server.py. The test client imports the mcp object from this file.
  2. Call preview_weekly when the caller has the report ID and still needs the user’s grouping choice.
  3. Call preview_weekly_explicit when the caller already has the choice. Both tools use the same counting function.
from collections import Counter
from typing import Annotated, Literal

from pydantic import BaseModel, Field

from mcp.server import MCPServer
from mcp.server.mcpserver import (
    AcceptedElicitation,
    Elicit,
    ElicitationResult,
    Resolve,
)

mcp = MCPServer("Weekly report preview")

ReportId = Literal["report:weekly-01"]
Grouping = Literal["team", "repository"]

ROWS = (
    ("Platform", "api"),
    ("Platform", "web"),
    ("Product", "web"),
    ("Platform", "api"),
)


class GroupingChoice(BaseModel):
    grouping: Grouping = Field(description="Count activity by team or repository.")


class PreviewResult(BaseModel):
    report_id: ReportId
    status: Literal["preview", "declined", "cancelled"]
    grouping: Grouping | None
    preview: dict[str, int] | None


async def ask_grouping(report_id: ReportId) -> Elicit[GroupingChoice]:
    return Elicit(f"Group {report_id} by team or repository?", GroupingChoice)


def build_preview(report_id: ReportId, grouping: Grouping) -> PreviewResult:
    column = 0 if grouping == "team" else 1
    counts = Counter(row[column] for row in ROWS)
    return PreviewResult(
        report_id=report_id,
        status="preview",
        grouping=grouping,
        preview=dict(sorted(counts.items())),
    )


@mcp.tool()
async def preview_weekly(
    report_id: ReportId,
    answer: Annotated[ElicitationResult[GroupingChoice], Resolve(ask_grouping)],
) -> PreviewResult:
    """Ask for a grouping and preview counts from the weekly activity fixture."""
    if isinstance(answer, AcceptedElicitation):
        return build_preview(report_id, answer.data.grouping)

    return PreviewResult(
        report_id=report_id,
        status="declined" if answer.action == "decline" else "cancelled",
        grouping=None,
        preview=None,
    )


@mcp.tool()
async def preview_weekly_explicit(report_id: ReportId, grouping: Grouping) -> PreviewResult:
    """Preview counts using a grouping the caller already obtained from the user."""
    return build_preview(report_id, grouping)

report_id is an ordinary tool argument. The SDK matches it to the resolver’s parameter by name and passes the validated value. The answer parameter lives in the dependency declaration and stays out of the tool input schema. A client discovering preview_weekly supplies report_id. A client handling the returned form supplies grouping through the elicitation response. If you rename the tool argument, rename the resolver parameter too. The SDK analyzes the dependency signature during registration, so a mismatch can fail before the client connects. SDK dependency resolution

The ElicitationResult[GroupingChoice] wrapper gives the tool all three form actions. AcceptedElicitation carries the validated answer and opens the only interactive path to build_preview. The remaining actions are decline and cancel. With an unwrapped GroupingChoice dependency, the SDK would abort the tool on either action. This tutorial uses the wrapper so the application can distinguish explicit refusal from dismissal in a normal tool result. The latter is a form action. Cancellation of the enclosing MCP request is a separate operation. SDK elicitation guide · MCP response actions

build_preview selects a column and adds one count per row. Sorting makes the output easier to read, while dictionary equality in the test is independent of key order. Both entry points return PreviewResult, which lets the SDK derive the output schema and expose the model’s fields directly in structured_content. The SDK also serializes the object for content. The harness tests the structured fields because those are what an application can use to decide whether to display a preview and what labels to display. SDK structured output

The form schema and result schema change for different reasons. Adding a third grouping would change the allowed input, the field the helper selects, and the expected counts. Changing how the client displays an existing grouping can leave the form schema alone. Keep the output field grouping alongside the counts so a client can retain the meaning of a stored preview. A dictionary containing web and api happens to be recognizable in this fixture, but callers should be able to read the dimension directly from the result.

Run the in-memory client and check the result

  1. Save the next block as check_report.py next to report_server.py.
  2. In the Python environment with the v2 SDK, run python check_report.py from that directory. Leave assertions enabled.
  3. Compare the confirmation lines with the expected transcript. If the script stops, use the last confirmation and the failing assertion to locate the failing case.
import anyio

from mcp import Client, MCPError
from mcp.client import ClientRequestContext
from mcp.types import ElicitRequestFormParams, ElicitRequestParams, ElicitResult

from report_server import mcp

REPORT = {"report_id": "report:weekly-01"}
TEAM = {
    **REPORT,
    "status": "preview",
    "grouping": "team",
    "preview": {"Platform": 3, "Product": 1},
}
REPOSITORY = {
    **REPORT,
    "status": "preview",
    "grouping": "repository",
    "preview": {"api": 2, "web": 2},
}


async def check_form(reply: ElicitResult, expected: dict) -> None:
    questions: list[str] = []

    async def answer(
        context: ClientRequestContext, params: ElicitRequestParams
    ) -> ElicitResult:
        assert isinstance(params, ElicitRequestFormParams), params
        questions.append(params.message)
        schema = params.requested_schema
        assert set(schema["properties"]) == {"grouping"}, schema
        assert "grouping" in schema["required"], schema
        field = schema["properties"]["grouping"]
        assert set(field["enum"]) == {"team", "repository"}, field
        assert "default" not in field, field
        return reply

    async with Client(mcp, elicitation_callback=answer) as client:
        assert client.protocol_version == "2026-07-28", client.protocol_version
        result = await client.call_tool("preview_weekly", REPORT)
        assert not result.is_error, result.content
        assert result.structured_content == expected, result.structured_content
        assert questions == ["Group report:weekly-01 by team or repository?"], questions

    print(f"{reply.action}: {expected['grouping'] or 'no preview'}")


async def main() -> None:
    await check_form(ElicitResult(action="accept", content={"grouping": "team"}), TEAM)
    await check_form(
        ElicitResult(action="accept", content={"grouping": "repository"}), REPOSITORY
    )
    await check_form(
        ElicitResult(action="decline"),
        {**REPORT, "status": "declined", "grouping": None, "preview": None},
    )
    await check_form(
        ElicitResult(action="cancel"),
        {**REPORT, "status": "cancelled", "grouping": None, "preview": None},
    )

    async with Client(mcp) as client:
        assert client.protocol_version == "2026-07-28", client.protocol_version
        try:
            await client.call_tool("preview_weekly", REPORT)
        except MCPError as error:
            assert error.error.code == -32021, error.error
            print(f"missing form capability: {error.error.code}")
        else:
            raise AssertionError("The call should fail without a form callback")

        result = await client.call_tool(
            "preview_weekly_explicit", {**REPORT, "grouping": "repository"}
        )
        assert not result.is_error, result.content
        assert result.structured_content == REPOSITORY, result.structured_content
        print("explicit repository: api=2, web=2")

        result = await client.call_tool(
            "preview_weekly_explicit", {**REPORT, "grouping": "owner"}
        )
        assert result.is_error, result
        assert result.structured_content is None, result.structured_content
        print("invalid explicit grouping: tool error")


if __name__ == "__main__":
    anyio.run(main)

The example callback checks the same form parameters a UI would receive and returns a predetermined action. The isinstance check narrows the callback’s parameters to form mode before the code reads requested_schema. A host that displays a form uses those parameters to render the question and lets the person review and submit their answer. Passing elicitation_callback=answer declares capability in the SDK. The harness opens a separate client without that keyword to exercise a caller that cannot answer the form. SDK client callbacks · MCP elicitation specification

The following table gives illustrative expected observations. REPORT is the {"report_id": "report:weekly-01"} dictionary in the script. In the last three cases the client stays connected while the tool name or argument changes. This lets you compare the capability failure with explicit calls under the same client setup.

Input Action Expected result
Case report:weekly-01 with grouping omitted and the callback choosing team Call preview_weekly with REPORT and return ElicitResult(action="accept", content={"grouping": "team"}). The callback receives one form. The final result has status=preview, grouping=team, and preview={"Platform": 3, "Product": 1}.
Case report:weekly-01 with grouping omitted and the callback choosing repository Call preview_weekly with REPORT and return ElicitResult(action="accept", content={"grouping": "repository"}). The callback receives one form. The final result has status=preview, grouping=repository, and preview={"api": 2, "web": 2}.
Case report:weekly-01 with a declined form Call preview_weekly with REPORT and return ElicitResult(action="decline"). The result has status=declined, grouping=null, and preview=null, with no tool error.
Case report:weekly-01 with a dismissed form Call preview_weekly with REPORT and return ElicitResult(action="cancel"). The result has status=cancelled, grouping=null, and preview=null, with no tool error.
Case report:weekly-01 with no client callback Open Client(mcp) and call preview_weekly with REPORT. The capability check raises MCPError with code -32021 before the caller receives any tool result.
Case report:weekly-01 with no callback and repository supplied by the user Call preview_weekly_explicit with {**REPORT, "grouping": "repository"}. The structured result equals the accepted repository case, including both counts and the grouping.
Case report:weekly-01 with no callback and invalid grouping owner Call preview_weekly_explicit with {**REPORT, "grouping": "owner"}. The returned tool result has is_error=True and structured_content is None.

The script is designed to print this sequence as each case passes. These lines are illustrative expected output.

accept: team
accept: repository
decline: no preview
cancel: no preview
missing form capability: -32021
explicit repository: api=2, web=2
invalid explicit grouping: tool error

Keep the exception check inside async with so the expected capability failure can be caught directly as MCPError. If an unexpected exception escapes the client’s context manager, AnyIO can wrap it in an ExceptionGroup. Read the underlying exception in that traceback. The SDK also documents an Elicitation not supported error on paths where a question reaches a client without a callback and skips the up-front capability check. The fixture targets the resolver path and checks the more specific -32021 code. SDK troubleshooting

For a dashboard or other caller that renders this preview, start with whether the call raised. A raised protocol error leaves the caller without a tool result. If the call returns, inspect is_error before accessing the result fields. An invalid explicit argument produces error content at this level. With a successful tool result, inspect status. Only preview means there are groups to display. If the page still shows an earlier preview when the current form is dismissed, keep the display associated with the earlier call so the user can tell where those counts came from. SDK troubleshooting · SDK structured output

Use the first failure to narrow the repair. An assertion inside answer points to the form before the counting function runs. If the callback supplies team and the final result contains repository keys, check the grouping passed into the helper and the column it selects. If the keys are right and the count is wrong, compare the rows and check for deduplication. If everything matches except the recorded questions, inspect the interaction even though the arithmetic passed. A correct preview can still follow an unnecessary second prompt.

Trace what happens between the call and the preview

  1. Check client.protocol_version after entering the client context. This harness expects 2026-07-28.
  2. Follow the accepted team case from the original report ID to the returned form and then to the retry carrying the answer.
  3. Verify the one recorded callback and the complete final result together. The screenshot shows the SDK fields that carry the exchange.

On the first request, ask_grouping returns Elicit because the interactive tool needs a choice. The SDK returns an InputRequiredResult with the form request in input_requests. The high-level Client dispatches the request to elicitation_callback. After the callback returns, the SDK retries the original tool with the same arguments, adding the answer in input_responses and echoing the server’s opaque request_state. The server verifies the state and resolves the dependency using the matching answer. The client receives an ordinary CallToolResult. Your Python code awaits one logical call across the two request legs in this example. SDK multi-round-trip requests

Client and server lanes show the original call, the returned form, the retry carrying answer and state, and the final preview.Client and server lanes show the original call, the returned form, the retry carrying answer and state, and the final preview.
Illustrative successful MCP 2026-07-28 exchange. The SDK routes the returned question to the callback and retries the same tool with the answer and state.

Opening of the MCP Python SDK’s Multi-round-trip requests documentation.
MCP Python SDK documentation for multi-round-trip requests. · Original source

The resolver can run again during the retry. It rebuilds the same question from the validated report ID and the same form model. The SDK matches the recorded answer to that rendered question and gives the tool the validated grouping. The counting logic lives in the tool body, after resolution. Tracing entry into the resolver and tracing receipt of a form in the callback will therefore tell you different things. For the accepted team case, a repeated resolver entry is consistent with the exchange, while a second callback within the same call_tool deserves investigation. SDK dependency resolution · SDK multi-round-trip requests

If you started with an older example using await ctx.elicit(...) inside the tool body, check the reported protocol version before changing the callback. That call relies on the older request channel. On the protocol version this harness checks, the SDK returns the question in a response and the client answers it on the next request. Moving the question to Resolve(ask_grouping) selects the supported mechanism while retaining the elicitation callback on the client. SDK troubleshooting · MCP Goes Stateless

The in-memory transport makes this a check of the server and client APIs and the result they exchange. The diagram explains the protocol behind the high-level call. If your host behaves differently, correlate its tool invocations with the form events before changing this fixture. The local callback is controlled by the harness. The host’s rendering, its delivery of the person’s action, and any decision it makes to start a new call belong to the host integration. SDK in-memory testing · SDK multi-round-trip requests

Diagnose repeated questions and recover with an explicit grouping

Observation Where to look What to change or verify
The callback receives multiple forms during one call_tool Compare the exact messages and schemas across rounds. Derive the message from report_id and keep the schema fixed across the exchange.
The callback never runs and MCPError carries -32021 Check whether the client declared form support by registering the callback. Register a callback on a client that can present the form. If the user has supplied the choice elsewhere, use preview_weekly_explicit.
The retry reports Invalid or expired requestState Inspect the server log for the reason. Compare the retry’s tool name and arguments with the original and check whether the server restarted. Start a fresh call when the old state is unusable. Use the explicit tool when the grouping is already known.
The tool returns declined or cancelled Read status and confirm preview is null. End this interaction. If the user later supplies a grouping and requests the preview, begin a fresh explicit call.

For a duplicate prompt within one call, compare the first and second callback payloads. A timestamp embedded in Group report:weekly-01 by team or repository? could change on resumption. A schema changed between rounds can also invalidate the match to the recorded answer. Both cases make the SDK ask again. The high-level client bounds the retry loop, so the last exception can report exhaustion while the first differing question points to the cause. Remove the volatile input or restore the stable schema, then rerun the accepted team case and look for one callback followed by the exact team counts. SDK dependency resolution · SDK multi-round-trip requests

If repeated forms have identical text and the harness passes, count the host’s top-level tool invocations. A second call_tool after a terminal result begins a new interaction. The harness creates a fresh list of questions for each case, so the assertion catches repetition within one call. When debugging a host, record each call boundary and terminal result. For example, a decline followed immediately by a second invocation of preview_weekly points to how the host handles status=declined. The remedy belongs at the caller’s decision to issue another call. Replaying agent sessions to diagnose behavior

A state verification error calls for a different inspection. The SDK binds the token to the originating tool name and arguments and uses a process-local key by default. A restart between legs can invalidate an otherwise unchanged retry. If your client manages the rounds itself, echo the state as returned and keep the original arguments. Putting the newly obtained grouping into the original call’s arguments changes the request the token was issued for. Read the server log to distinguish that mismatch from expiry or a change of process. SDK multi-round-trip requests · SDK troubleshooting

To rehearse recovery, suppose a host cannot show the form and the person says in chat, “Group the weekly report by repository.” Start a new preview_weekly_explicit call with report_id set to report:weekly-01 and grouping set to repository. The seventh line is the invalid-argument check, so look for explicit repository: api=2, web=2 immediately before it in the local transcript. At the application boundary, compare structured_content with REPOSITORY. That confirms the same output as accepting the repository option in the form, with the web activities from both teams counted together.

If the caller still has only a report ID, leave the preview absent until the person chooses. A decline or dismissal ends that interaction. The explicit tool provides another way to carry a choice the person actually supplies. In this fixture there are no external writes to reverse. To roll back the interactive path in a test host, route preview requests through preview_weekly_explicit after the caller has both values. Recheck the valid repository case and the invalid owner case to verify the input boundary after the change.

Once the local checks pass, run the same fixture in the host you intend to support. Start with the explicit repository call. If it succeeds and the interactive call fails, inspect the form capability and callback path. If the host finds neither tool, check discovery and the server object it is running. If a call hangs, inspect the host’s time limits. After a reconnect, invoke the tool again and compare the result with the fixture. A visible tool name only confirms what the host is displaying at that moment. Inspect an MCP connection and tool call · Diagnose MCP startup and call timeouts · Verify a tool call after an OpenCode reconnect

Sources

Many assistants.
One place to remember.

Bring your AI sessions, context, and usage together with Automater.

Meet Automater