inspector/core/mcp/elicitationCreateMessage.ts
Cliff Hall 9b2c188d11
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) (#1719)
* 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>
2026-07-17 23:15:19 -04:00

125 lines
4.3 KiB
TypeScript

import type { ElicitRequest, ElicitResult } from "@modelcontextprotocol/client";
import { RELATED_TASK_META_KEY } from "@modelcontextprotocol/client";
import type { PendingRequestOrigin } from "./types.js";
export type { ElicitRequest, ElicitResult };
/**
* Data shape of a pending elicitation request tracked by the InspectorClient.
* v2's state/screen layer consumes this interface; the runtime class below
* (ElicitationCreateMessage) implements it.
*/
export interface InspectorPendingElicitation {
id: string;
timestamp: Date;
request: ElicitRequest;
taskId?: string;
origin: PendingRequestOrigin;
}
/**
* Represents a pending elicitation request from the server
*/
export class ElicitationCreateMessage {
public readonly id: string;
public readonly timestamp: Date;
public readonly request: ElicitRequest;
public readonly taskId?: string;
/**
* How this request reached the Inspector — a legacy server→client request or
* a modern MRTR `input_required` round. Drives era-accurate copy in the
* pending-request UI. Defaults to `"server-request"` so existing call sites
* (and stories) keep the legacy semantics unchanged.
*/
public readonly origin: PendingRequestOrigin;
private resolvePromise?: (result: ElicitResult) => void;
/**
* Rejects the originating call with an error. Set for task-augmented elicit
* (so the server's `tasks/result` receives the error on decline) and for
* MRTR-driven elicitations (so a genuine failure aborts the tool call).
*/
private rejectCallback?: (error: Error) => void;
private onRemove: (id: string) => void;
constructor(
request: ElicitRequest,
resolve: (result: ElicitResult) => void,
onRemove: (id: string) => void,
reject?: (error: Error) => void,
origin: PendingRequestOrigin = "server-request",
) {
this.onRemove = onRemove;
this.id = `elicitation-${crypto.randomUUID()}`;
this.timestamp = new Date();
this.request = request;
// Extract taskId from request params metadata if present
const relatedTask = request.params?._meta?.[RELATED_TASK_META_KEY];
this.taskId = relatedTask?.taskId;
this.origin = origin;
this.resolvePromise = resolve;
this.rejectCallback = reject;
}
/**
* Reject the elicitation (e.g. when user declines). Only has effect when this
* request was task-augmented; then the server's tasks/result will receive the error.
*/
reject(error: Error): void {
if (this.rejectCallback) {
this.rejectCallback(error);
this.rejectCallback = undefined;
}
}
/**
* Respond to the elicitation request with a result
*/
async respond(result: ElicitResult): Promise<void> {
if (!this.resolvePromise) {
throw new Error("Request already resolved");
}
this.resolvePromise(result);
this.resolvePromise = undefined;
// Remove from pending list after responding
this.remove();
}
/**
* Resolve this elicitation as accepted, but only if it is still pending.
*
* Used by the URL-mode `notifications/elicitation/complete` handler to
* auto-advance an open URL elicitation when the server signals the
* out-of-band flow finished. It is a no-op once the user has already
* responded — that guard (plus the modal's own once-guard) keeps `respond()`
* from throwing its "already resolved" error on a race between the manual
* "I've completed it" click and the server's completion notification.
*/
completeIfPending(): void {
if (this.resolvePromise) {
void this.respond({ action: "accept" });
}
}
/**
* Settle a still-pending elicitation as cancelled, without removing it from
* the queue. Used by `disconnect()` teardown so an awaiting caller — notably
* the error-path `awaitUrlElicitation` that blocks `callTool` — doesn't hang
* forever when the pending queue is dropped wholesale. No-op once already
* resolved; deliberately does not call `onRemove` (the caller clears the
* queue itself, so we must not splice it mid-iteration).
*/
cancel(): void {
if (this.resolvePromise) {
this.resolvePromise({ action: "cancel" });
this.resolvePromise = undefined;
}
this.rejectCallback = undefined;
}
/**
* Remove this pending elicitation from the list
*/
remove(): void {
this.onRemove(this.id);
}
}