|
| 1 | +"""Multi-round MRTR with request_state accumulation. |
| 2 | +
|
| 3 | +This is the ADO-custom-rules example from the SEP, translated. Resolving |
| 4 | +a work item triggers cascading required fields: |
| 5 | +
|
| 6 | + Rule 1: State → "Resolved" requires a Resolution field |
| 7 | + Rule 2: Resolution = "Duplicate" requires a "Duplicate Of" link |
| 8 | +
|
| 9 | +The server learns Rule 2 is needed only after the user answers Rule 1. |
| 10 | +Two rounds of elicitation. The Rule 1 answer must survive across rounds |
| 11 | +*without server-side storage* — that's what ``request_state`` is for. |
| 12 | +
|
| 13 | +Key point: ``input_responses`` carries only the *latest* round's answers. |
| 14 | +Round 2's retry has ``{"duplicate_of": ...}`` but NOT ``{"resolution": ...}``. |
| 15 | +Anything the server needs to keep must be encoded in ``request_state``, |
| 16 | +which the client echoes verbatim. |
| 17 | +
|
| 18 | +Run against the in-memory client: |
| 19 | +
|
| 20 | + uv run python -m mrtr_options.basic_multiround |
| 21 | +""" |
| 22 | + |
| 23 | +from __future__ import annotations |
| 24 | + |
| 25 | +import base64 |
| 26 | +import json |
| 27 | +from typing import Any |
| 28 | + |
| 29 | +import anyio |
| 30 | + |
| 31 | +from mcp import types |
| 32 | +from mcp.client import Client |
| 33 | +from mcp.client.context import ClientRequestContext |
| 34 | +from mcp.server import Server, ServerRequestContext |
| 35 | + |
| 36 | + |
| 37 | +def encode_state(state: dict[str, Any]) -> str: |
| 38 | + """Serialize state for the round trip through the client. |
| 39 | +
|
| 40 | + Plain base64-JSON here. A production server handling sensitive data |
| 41 | + MUST sign this — the client is an untrusted intermediary and could |
| 42 | + forge or replay state otherwise. See SEP-2322 §Security Implications. |
| 43 | + """ |
| 44 | + return base64.b64encode(json.dumps(state).encode()).decode() |
| 45 | + |
| 46 | + |
| 47 | +def decode_state(blob: str | None) -> dict[str, Any]: |
| 48 | + if not blob: |
| 49 | + return {} |
| 50 | + return json.loads(base64.b64decode(blob)) |
| 51 | + |
| 52 | + |
| 53 | +def ask(message: str, field: str) -> types.ElicitRequest: |
| 54 | + """Build a form-mode elicitation for a single string field.""" |
| 55 | + return types.ElicitRequest( |
| 56 | + params=types.ElicitRequestFormParams( |
| 57 | + message=message, |
| 58 | + requested_schema={ |
| 59 | + "type": "object", |
| 60 | + "properties": {field: {"type": "string"}}, |
| 61 | + "required": [field], |
| 62 | + }, |
| 63 | + ) |
| 64 | + ) |
| 65 | + |
| 66 | + |
| 67 | +async def on_list_tools( |
| 68 | + ctx: ServerRequestContext, params: types.PaginatedRequestParams | None |
| 69 | +) -> types.ListToolsResult: |
| 70 | + return types.ListToolsResult( |
| 71 | + tools=[ |
| 72 | + types.Tool( |
| 73 | + name="resolve_work_item", |
| 74 | + description="Resolve a work item. May need cascading follow-up fields.", |
| 75 | + input_schema={ |
| 76 | + "type": "object", |
| 77 | + "properties": {"work_item_id": {"type": "integer"}}, |
| 78 | + "required": ["work_item_id"], |
| 79 | + }, |
| 80 | + ) |
| 81 | + ] |
| 82 | + ) |
| 83 | + |
| 84 | + |
| 85 | +async def on_call_tool( |
| 86 | + ctx: ServerRequestContext, params: types.CallToolRequestParams |
| 87 | +) -> types.CallToolResult | types.IncompleteResult: |
| 88 | + args = params.arguments or {} |
| 89 | + work_item_id = args.get("work_item_id", 0) |
| 90 | + responses = params.input_responses or {} |
| 91 | + state = decode_state(params.request_state) |
| 92 | + |
| 93 | + # ─────────────────────────────────────────────────────────────────────── |
| 94 | + # Round 1: State → Resolved triggers Rule 1 (require Resolution). |
| 95 | + # |
| 96 | + # If we don't yet have the resolution — neither in this round's |
| 97 | + # input_responses nor in accumulated state — ask for it. |
| 98 | + # ─────────────────────────────────────────────────────────────────────── |
| 99 | + resolution = state.get("resolution") |
| 100 | + if not resolution: |
| 101 | + resp = responses.get("resolution") |
| 102 | + if not resp or resp.get("action") != "accept": |
| 103 | + return types.IncompleteResult( |
| 104 | + input_requests={ |
| 105 | + "resolution": ask( |
| 106 | + f"Resolving #{work_item_id} requires a resolution. Fixed, Won't Fix, Duplicate, or By Design?", |
| 107 | + "resolution", |
| 108 | + ) |
| 109 | + }, |
| 110 | + # No state yet — the original tool arguments are re-sent on |
| 111 | + # retry, so we don't need to encode anything for round 1. |
| 112 | + ) |
| 113 | + resolution = resp["content"]["resolution"] |
| 114 | + |
| 115 | + # ─────────────────────────────────────────────────────────────────────── |
| 116 | + # Round 2: Resolution = "Duplicate" triggers Rule 2 (require link). |
| 117 | + # |
| 118 | + # If the resolution is Duplicate and we don't yet have the link, ask |
| 119 | + # for it — but encode the already-gathered resolution in request_state |
| 120 | + # so it survives the round trip regardless of which server instance |
| 121 | + # handles the next retry. |
| 122 | + # ─────────────────────────────────────────────────────────────────────── |
| 123 | + if resolution == "Duplicate": |
| 124 | + resp = responses.get("duplicate_of") |
| 125 | + if not resp or resp.get("action") != "accept": |
| 126 | + return types.IncompleteResult( |
| 127 | + input_requests={"duplicate_of": ask("Which work item is the original?", "duplicate_of")}, |
| 128 | + request_state=encode_state({"resolution": resolution}), |
| 129 | + ) |
| 130 | + dup = resp["content"]["duplicate_of"] |
| 131 | + text = f"#{work_item_id} resolved as Duplicate of #{dup}." |
| 132 | + else: |
| 133 | + text = f"#{work_item_id} resolved as {resolution}." |
| 134 | + |
| 135 | + return types.CallToolResult(content=[types.TextContent(text=text)]) |
| 136 | + |
| 137 | + |
| 138 | +server = Server("mrtr-multiround", on_list_tools=on_list_tools, on_call_tool=on_call_tool) |
| 139 | + |
| 140 | + |
| 141 | +# ─── Demo driver ───────────────────────────────────────────────────────────── |
| 142 | + |
| 143 | + |
| 144 | +ANSWERS = { |
| 145 | + "resolution": "Duplicate", |
| 146 | + "duplicate_of": "4301", |
| 147 | +} |
| 148 | + |
| 149 | + |
| 150 | +async def elicitation_callback(context: ClientRequestContext, params: types.ElicitRequestParams) -> types.ElicitResult: |
| 151 | + assert isinstance(params, types.ElicitRequestFormParams) |
| 152 | + print(f"[client] server asks: {params.message}") |
| 153 | + # Pick the field name from the schema and answer from our table. |
| 154 | + field = next(iter(params.requested_schema["properties"])) |
| 155 | + answer = ANSWERS[field] |
| 156 | + print(f"[client] answering {field}={answer}") |
| 157 | + return types.ElicitResult(action="accept", content={field: answer}) |
| 158 | + |
| 159 | + |
| 160 | +async def main() -> None: |
| 161 | + async with Client(server, elicitation_callback=elicitation_callback) as client: |
| 162 | + result = await client.call_tool("resolve_work_item", {"work_item_id": 4522}) |
| 163 | + print(f"[client] final: {result.content[0].text}") # type: ignore[union-attr] |
| 164 | + |
| 165 | + |
| 166 | +if __name__ == "__main__": |
| 167 | + anyio.run(main) |
0 commit comments