MRTR: drive input_required manually to keep pending-request UX (#1704) (#1719)
Some checks failed
Run install, format, lint, build, and test on every push / build (push) Has been cancelled
Run install, format, lint, build, and test on every push / publish (push) Has been cancelled
Run install, format, lint, build, and test on every push / publish-github-container-registry (push) Has been cancelled

* MRTR: drive input_required manually to keep pending-request UX (#1704)

Follow-up to #1627/#1705. Instead of letting the SDK auto-fulfil the modern
(2026-07-28) MRTR retry loop, InspectorClient now drives it itself so the
Inspector keeps its pending-request UX, owns the loop, and shows era-accurate
semantics.

Core (core/mcp/inspectorClient.ts):
- Construct the SDK Client with `inputRequired: { autoFulfill: false }`
  (unconditional; a no-op on legacy, which never returns input_required).
- New `requestWithInputRequired()` driver: issues the request with
  `allowInputRequired` + `withInputRequired(schema)`, and while the result is
  `input_required`, fulfils each embedded request through the SAME pending
  sampling/elicitation plumbing, then retries the original call with
  `inputResponses` + the echoed `requestState` on a fresh id, bounded by
  MRTR_MAX_ROUNDS.
- Route tools/call, prompts/get, and resources/read through the driver.
- Embedded roots/list is auto-answered from configured roots (no pending UX);
  decline/cancel is echoed to the server (not treated as an abort); a tool-call
  abort mid-round settles the pending request and surfaces
  ToolCallCancelledError.
- Extract shared `enqueuePendingSample`/`enqueuePendingElicitation` helpers used
  by both the legacy inbound handlers and the driver; add a per-request `origin`
  ("server-request" | "input-required") to the pending wrappers.

Web UI:
- New `MrtrOriginNote` element shows an "input_required — your answer returns as
  a retry" note on a modern MRTR round; legacy panels are unchanged.
- Thread `origin` App -> PendingClientRequestModal -> the sampling/elicitation
  panels (and the inline panels).

Test servers: new MRTR presets (multi-round, roots, sampling, loop, edge-case
param shaping). Integration tests cover the manual round-trip (asserting the
pending UI pauses and the retry carries inputResponses + requestState on a new
id), multi-round, roots auto-answer, sampling, decline-echoed, maxRounds bound,
abort mid-round, and requestState-only/inputRequests-only param shaping.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

* Review: clarify sampling-reject and between-rounds abort comments (#1704)

Address review nits on PR #1719 (comment-only, no behavior change):
- enqueuePendingSample docstring: sampling has no decline/cancel action; the
  panel either sends a result (resolve) or Rejects (reject → fails the call).
  The shared "declined/cancelled resolves" wording was accurate only for the
  elicitation case.
- callToolWithRetries abort comment: note the between-rounds case — when the
  abort lands while an MRTR round awaits an embedded pending request there is no
  in-flight SDK request, so nothing is sent on the wire; the outcome
  (ToolCallCancelledError, no failed-call record) is identical.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

* test-servers: add mrtr-showcase config exercising every MRTR preset (#1704)

A single modern-era streamable-HTTP server (port 3111) bundling all six MRTR
presets — mrtr_confirm, mrtr_two_step, mrtr_sample, mrtr_roots, mrtr_edge,
mrtr_loop — for manual testing of the manual-driving pending-request UX across
single-round, multi-round, sampling, roots, param-shaping, and maxRounds paths.
Document it in the README alongside modern-mrtr-http.json.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cliff Hall 2026-07-17 23:15:19 -04:00 • committed by GitHub
commit 9b2c188d11
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 1131 additions and 96 deletions

View file

@ -42,6 +42,10 @@ type FakeClient = {
* we can drive `callTool` through the URL-elicitation error path without a live
* server. The client is never connected; `callTool` only needs the injected
* `callTool`/`request` methods plus the (connection-independent) helpers.
*
* The tool-call path issues `client.request({ method: "tools/call", … })`
* (through the MRTR driver, #1704), so these fakes drive the error path from
* `request`; `callTool` is left as an unused stub.
*/
function makeClient(fake: FakeClient): InspectorClient {
const client = new InspectorClient(
@ -72,14 +76,14 @@ describe("InspectorClient URL-elicitation error path", () => {
it("surfaces the URL elicitation, then retries the call on accept", async () => {
let attempt = 0;
const fake: FakeClient = {
callTool: vi.fn(async () => {
callTool: vi.fn(),
request: vi.fn(async () => {
attempt += 1;
if (attempt === 1) {
throw new UrlElicitationRequiredError([elicitation]);
}
return okResult;
}),
request: vi.fn(),
};
const client = makeClient(fake);
@ -99,7 +103,7 @@ describe("InspectorClient URL-elicitation error path", () => {
const invocation = await pending;
expect(invocation.success).toBe(true);
expect(fake.callTool).toHaveBeenCalledTimes(2);
expect(fake.request).toHaveBeenCalledTimes(2);
expect(client.getPendingElicitations()).toHaveLength(0);
});
@ -111,14 +115,14 @@ describe("InspectorClient URL-elicitation error path", () => {
};
let attempt = 0;
const fake: FakeClient = {
callTool: vi.fn(async () => {
callTool: vi.fn(),
request: vi.fn(async () => {
attempt += 1;
if (attempt === 1) {
throw new UrlElicitationRequiredError([elicitation, second]);
}
return okResult;
}),
request: vi.fn(),
};
const client = makeClient(fake);
@ -143,15 +147,15 @@ describe("InspectorClient URL-elicitation error path", () => {
const invocation = await pending;
expect(invocation.success).toBe(true);
expect(fake.callTool).toHaveBeenCalledTimes(2);
expect(fake.request).toHaveBeenCalledTimes(2);
});
it("aborts the call (no retry) when the user cancels a required elicitation", async () => {
const fake: FakeClient = {
callTool: vi.fn(async () => {
callTool: vi.fn(),
request: vi.fn(async () => {
throw new UrlElicitationRequiredError([elicitation]);
}),
request: vi.fn(),
};
const client = makeClient(fake);
const failedDispatches = trackFailedDispatches(client);
@ -163,7 +167,7 @@ describe("InspectorClient URL-elicitation error path", () => {
await client.getPendingElicitations()[0].respond({ action: "cancel" });
await expect(pending).rejects.toThrow(/cancelled/i);
expect(fake.callTool).toHaveBeenCalledTimes(1);
expect(fake.request).toHaveBeenCalledTimes(1);
// The abort records exactly one failed history entry — not zero, not a
// duplicate from the generic catch.
expect(failedDispatches()).toBe(1);
@ -172,10 +176,10 @@ describe("InspectorClient URL-elicitation error path", () => {
it("aborts with a loop error when the server re-requests a completed URL", async () => {
// The server keeps returning the same URL after the user completes it.
const fake: FakeClient = {
callTool: vi.fn(async () => {
callTool: vi.fn(),
request: vi.fn(async () => {
throw new UrlElicitationRequiredError([elicitation]);
}),
request: vi.fn(),
};
const client = makeClient(fake);
const failedDispatches = trackFailedDispatches(client);
@ -192,7 +196,7 @@ describe("InspectorClient URL-elicitation error path", () => {
await expect(pending).rejects.toBeInstanceOf(UrlElicitationLoopError);
await expect(pending).rejects.toMatchObject({ url: elicitation.url });
// Only the initial call + one retry ran; the URL was presented just once.
expect(fake.callTool).toHaveBeenCalledTimes(2);
expect(fake.request).toHaveBeenCalledTimes(2);
expect(client.getPendingElicitations()).toHaveLength(0);
// The loop abort records exactly one failed history entry (the accepted
// first round records nothing).
@ -201,10 +205,10 @@ describe("InspectorClient URL-elicitation error path", () => {
it("settles a pending error-path elicitation as cancelled on disconnect (no hang)", async () => {
const fake: FakeClient = {
callTool: vi.fn(async () => {
callTool: vi.fn(),
request: vi.fn(async () => {
throw new UrlElicitationRequiredError([elicitation]);
}),
request: vi.fn(),
};
const client = makeClient(fake);
@ -223,13 +227,13 @@ describe("InspectorClient URL-elicitation error path", () => {
it("rethrows a -32042 error with no elicitations without queuing anything", async () => {
const fake: FakeClient = {
callTool: vi.fn(async () => {
callTool: vi.fn(),
request: vi.fn(async () => {
throw new ProtocolError(
ProtocolErrorCode.UrlElicitationRequired,
"This request requires browser-based authorization.",
);
}),
request: vi.fn(),
};
const client = makeClient(fake);
@ -237,15 +241,15 @@ describe("InspectorClient URL-elicitation error path", () => {
code: ProtocolErrorCode.UrlElicitationRequired,
});
expect(client.getPendingElicitations()).toHaveLength(0);
expect(fake.callTool).toHaveBeenCalledTimes(1);
expect(fake.request).toHaveBeenCalledTimes(1);
});
it("rethrows an ordinary error unchanged", async () => {
const fake: FakeClient = {
callTool: vi.fn(async () => {
callTool: vi.fn(),
request: vi.fn(async () => {
throw new Error("boom");
}),
request: vi.fn(),
};
const client = makeClient(fake);
const failed = vi.fn();

View file

@ -567,12 +567,14 @@ describe("InspectorClient coverage backfill", () => {
it("callTool error path covers general-only, tool-specific-only, and both metadata", async () => {
client = stdioClient();
await client.connect();
// Force the underlying SDK callTool to throw so the dispatchFailedToolCall
// error path runs for each metadata combination.
// Force the underlying SDK request to throw so the dispatchFailedToolCall
// error path runs for each metadata combination. The tool-call path issues
// `client.request({ method: "tools/call", … })` through the MRTR driver
// (#1704), so the throw is injected on `request`.
const c = client as unknown as {
client: { callTool: () => Promise<never> };
client: { request: () => Promise<never> };
};
c.client.callTool = async () => {
c.client.request = async () => {
throw new Error("forced-call-failure");
};

View file

@ -1,6 +1,7 @@
import { describe, it, expect, afterEach } from "vitest";
import { InspectorClient } from "@inspector/core/mcp/inspectorClient.js";
import { createTransportNode } from "@inspector/core/mcp/node/transport.js";
import { ToolCallCancelledError } from "@inspector/core/mcp/toolCallCancelledError.js";
import {
eraToVersionNegotiation,
MODERN_PROTOCOL_VERSION,
@ -11,9 +12,17 @@ import {
createTestServerInfo,
createEchoTool,
createMrtrTool,
createMrtrMultiRoundTool,
createMrtrRootsTool,
createMrtrSamplingTool,
createMrtrLoopTool,
createMrtrEdgeCaseTool,
} from "@modelcontextprotocol/inspector-test-server";
import type { ServerConfig } from "@modelcontextprotocol/inspector-test-server";
import type { ContentBlock } from "@modelcontextprotocol/client";
import type {
ContentBlock,
JSONRPCRequest,
} from "@modelcontextprotocol/client";
/**
* Live coverage of the modern (2026-07-28) connection path (#1700). The bundled
@ -126,25 +135,55 @@ describe("modern-era negotiation (2026-07-28)", () => {
expect("text" in content[0] && content[0].text).toContain("hi");
});
it("completes an MRTR round-trip (input_required elicitation → retry → final result)", async () => {
// The modern (2026-07-28) leg has no server→client requests; a tool that
// needs input returns `input_required` embedding the request, and the client
// fulfils it and retries with a new id. `createMrtrTool` returns
// `inputRequired({ inputRequests: { confirm: elicit(...) } })` on the first
// call and the final result once the answer is echoed back.
// Collect every outbound `tools/call` request frame the transport captured,
// so a test can assert what the MRTR retry actually put on the wire.
function collectToolCallRequests(
connected: InspectorClient,
): JSONRPCRequest[] {
const frames: JSONRPCRequest[] = [];
connected.addEventListener("message", (event) => {
const entry = event.detail;
if (
entry.direction === "request" &&
"method" in entry.message &&
entry.message.method === "tools/call"
) {
frames.push(entry.message as JSONRPCRequest);
}
});
return frames;
}
async function startMrtrServer(
tool: ReturnType<typeof createMrtrTool>,
): Promise<TestServerHttp> {
const started = createTestServerHttp({
serverInfo: createTestServerInfo("modern-mrtr-test", "1.0.0"),
tools: [createMrtrTool()],
tools: [tool],
modern: {},
});
await started.start();
server = started;
return started;
}
it("drives an MRTR round-trip manually (pauses at the pending UI, retries with inputResponses + requestState on a new id)", async () => {
// The modern (2026-07-28) leg has no server→client requests; a tool that
// needs input returns `input_required` embedding the request. With the SDK's
// auto-fulfil disabled, InspectorClient drives the loop itself: it surfaces
// the embedded elicitation through the pending-request UI, then retries the
// original call with the answer.
const started = await startMrtrServer(createMrtrTool());
const connected = await connectWithEra(started.url, "modern");
const toolCallFrames = collectToolCallRequests(connected);
// Auto-fulfil the embedded elicitation the MRTR tool requests, the same way
// the UI's pending-request panel would — which drives the SDK's retry.
// Prove the pending UX actually paused: record that an elicitation was
// surfaced BEFORE we answer it (the manual driver enqueued it), then answer.
let pausedAtPendingUi = false;
connected.addEventListener("newPendingElicitation", (event) => {
pausedAtPendingUi = true;
// The manual driver tags an MRTR round's request "input-required".
expect(event.detail.origin).toBe("input-required");
void event.detail.respond({
action: "accept",
content: { confirm: true },
@ -157,12 +196,213 @@ describe("modern-era negotiation (2026-07-28)", () => {
const result = await connected.callTool(mrtr!, { action: "deploy" });
expect(result.success).toBe(true);
expect(pausedAtPendingUi).toBe(true);
const content = result.result!.content as ContentBlock[];
const text = content[0] && "text" in content[0] ? content[0].text : "";
// The final result is only reachable after the input_required round was
// fulfilled and the original call retried — i.e. the full MRTR loop ran.
expect(text).toContain("MRTR complete");
expect(text).toContain("confirm");
// Two tools/call frames: the original and the retry. The retry has a
// DIFFERENT json-rpc id and carries inputResponses + the echoed requestState.
expect(toolCallFrames.length).toBe(2);
const [original, retry] = toolCallFrames;
expect(retry.id).not.toBe(original.id);
const retryParams = retry.params as {
inputResponses?: Record<string, unknown>;
requestState?: unknown;
};
expect(retryParams.inputResponses?.confirm).toEqual({
action: "accept",
content: { confirm: true },
});
// The original call carries no requestState; the retry echoes the opaque
// server-minted token verbatim (shape: `mrtr:<action>:<n>`).
expect(
(original.params as { requestState?: unknown }).requestState,
).toBeUndefined();
expect(retryParams.requestState).toMatch(/^mrtr:deploy:/);
});
it("drives a multi-round MRTR (two embedded elicitations in sequence, then completes)", async () => {
const started = await startMrtrServer(createMrtrMultiRoundTool());
const connected = await connectWithEra(started.url, "modern");
const seenMessages: string[] = [];
connected.addEventListener("newPendingElicitation", (event) => {
seenMessages.push(event.detail.request.params.message ?? "");
void event.detail.respond({
action: "accept",
content: { value: `answer-${seenMessages.length}` },
});
});
const { tools } = await connected.listTools();
const tool = tools.find((t) => t.name === "mrtr_two_step");
const result = await connected.callTool(tool!, {});
expect(result.success).toBe(true);
// Both rounds surfaced, in order.
expect(seenMessages).toEqual([
"Step 1: enter the first value",
"Step 2: enter the second value",
]);
const content = result.result!.content as ContentBlock[];
const text = content[0] && "text" in content[0] ? content[0].text : "";
expect(text).toContain("MRTR two-step complete");
});
it("auto-answers an embedded roots/list request from configured roots (no pending UI)", async () => {
const started = await startMrtrServer(createMrtrRootsTool());
const connected = new InspectorClient(
{ type: "streamable-http", url: started.url },
{
environment: { transport: createTransportNode },
versionNegotiation: eraToVersionNegotiation("modern"),
roots: [{ uri: "file:///workspace", name: "workspace" }],
},
);
client = connected;
await connected.connect();
let surfacedPending = false;
connected.addEventListener("newPendingElicitation", () => {
surfacedPending = true;
});
connected.addEventListener("newPendingSample", () => {
surfacedPending = true;
});
const { tools } = await connected.listTools();
const tool = tools.find((t) => t.name === "mrtr_roots");
const result = await connected.callTool(tool!, {});
expect(result.success).toBe(true);
// roots is answered silently — nothing pauses at the pending UI.
expect(surfacedPending).toBe(false);
const content = result.result!.content as ContentBlock[];
const text = content[0] && "text" in content[0] ? content[0].text : "";
expect(text).toContain("client reported 1 root");
});
it("surfaces an embedded sampling request through the pending-sample UI", async () => {
const started = await startMrtrServer(createMrtrSamplingTool());
const connected = await connectWithEra(started.url, "modern");
let sampleOrigin: string | undefined;
connected.addEventListener("newPendingSample", (event) => {
sampleOrigin = event.detail.origin;
void event.detail.respond({
model: "test-model",
stopReason: "endTurn",
role: "assistant",
content: { type: "text", text: "hello" },
});
});
const { tools } = await connected.listTools();
const tool = tools.find((t) => t.name === "mrtr_sample");
const result = await connected.callTool(tool!, {});
expect(result.success).toBe(true);
expect(sampleOrigin).toBe("input-required");
const content = result.result!.content as ContentBlock[];
const text = content[0] && "text" in content[0] ? content[0].text : "";
expect(text).toContain("MRTR sample complete");
});
it("echoes a declined elicitation back to the server (decline is not an abort)", async () => {
const started = await startMrtrServer(createMrtrTool());
const connected = await connectWithEra(started.url, "modern");
connected.addEventListener("newPendingElicitation", (event) => {
void event.detail.respond({ action: "decline" });
});
const { tools } = await connected.listTools();
const tool = tools.find((t) => t.name === "mrtr_confirm");
// The tool still completes — the declined result is echoed back, and the
// server returns its final result citing the declined answer.
const result = await connected.callTool(tool!, { action: "deploy" });
expect(result.success).toBe(true);
const content = result.result!.content as ContentBlock[];
const text = content[0] && "text" in content[0] ? content[0].text : "";
expect(text).toContain("MRTR complete");
expect(text).toContain("decline");
});
it("bounds a pathological MRTR that never completes (MRTR_MAX_ROUNDS)", async () => {
const started = await startMrtrServer(createMrtrLoopTool());
const connected = await connectWithEra(started.url, "modern");
// Auto-answer every round; the server never completes, so the driver's cap
// must stop the loop rather than spin forever.
connected.addEventListener("newPendingElicitation", (event) => {
void event.detail.respond({ action: "accept", content: { value: "x" } });
});
const { tools } = await connected.listTools();
const tool = tools.find((t) => t.name === "mrtr_loop");
await expect(connected.callTool(tool!, {})).rejects.toThrow(
/exceeded .* input_required rounds/,
);
});
it("handles requestState-only and inputRequests-only rounds (param shaping)", async () => {
const started = await startMrtrServer(createMrtrEdgeCaseTool());
const connected = await connectWithEra(started.url, "modern");
const toolCallFrames = collectToolCallRequests(connected);
connected.addEventListener("newPendingElicitation", (event) => {
void event.detail.respond({ action: "accept", content: { value: "n" } });
});
const { tools } = await connected.listTools();
const tool = tools.find((t) => t.name === "mrtr_edge");
const result = await connected.callTool(tool!, {});
expect(result.success).toBe(true);
const content = result.result!.content as ContentBlock[];
const text = content[0] && "text" in content[0] ? content[0].text : "";
expect(text).toContain("MRTR edge complete");
// Three rounds: original + two retries.
expect(toolCallFrames.length).toBe(3);
// Round-1 retry carries inputResponses but NO requestState (round 1 minted
// none).
const retry1 = toolCallFrames[1].params as {
inputResponses?: unknown;
requestState?: unknown;
};
expect(retry1.inputResponses).toBeDefined();
expect(retry1.requestState).toBeUndefined();
// Round-2 retry carries requestState and no meaningful inputResponses (round
// 2 was requestState-only; the driver adds none — the modern SDK codec may
// serialize an empty `{}` on the wire).
const retry2 = toolCallFrames[2].params as {
inputResponses?: Record<string, unknown>;
requestState?: unknown;
};
expect(retry2.requestState).toBeDefined();
expect(Object.keys(retry2.inputResponses ?? {})).toHaveLength(0);
});
it("cancels an in-flight MRTR call while its embedded request is pending", async () => {
const started = await startMrtrServer(createMrtrTool());
const connected = await connectWithEra(started.url, "modern");
// Cancel the tool call the moment its embedded elicitation is surfaced,
// instead of answering it.
connected.addEventListener("newPendingElicitation", () => {
connected.cancelToolCall();
});
const { tools } = await connected.listTools();
const tool = tools.find((t) => t.name === "mrtr_confirm");
await expect(
connected.callTool(tool!, { action: "deploy" }),
).rejects.toThrow(ToolCallCancelledError);
// The pending elicitation was removed when the call aborted.
expect(connected.getPendingElicitations()).toHaveLength(0);
});
it("rejects a legacy client against a strict modern-only server", async () => {