Skip to content

Commit 25e5f3a

Browse files
cliffhallevalstateclaude
authored
fix(everything): prevent URL elicitation error-path infinite loop (#4285)
* url elicitation * single tool for normal and error path * Address review feedback on URL elicitation tool - Remove src/everything/pnpm-lock.yaml (monorepo uses npm workspaces) - Drop redundant TriggerUrlElicitationSchema.parse(args) in the handler; destructure directly from args like the other tools, since the SDK validates against the registered schema before invoking the handler - Add explicit accept/decline/cancel messaging in the request path, mirroring trigger-elicitation-request.ts - Clarify the registerTool count comment in registrations.test.ts (task-based tools register via registerToolTask, counted separately) - Add tests covering the no-url / undefined-capability registration guards, the randomUUID() elicitationId fallback, and the decline/cancel response paths (100% coverage of the tool) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Add tool annotations to trigger-url-elicitation Match the annotations block on sibling elicitation tools and the CLAUDE.md guidance. Uses openWorldHint: true since the tool drives an external browser flow. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(everything): prevent URL elicitation error-path infinite loop The trigger-url-elicitation tool's error path (errorPath=true) threw UrlElicitationRequiredError (-32042) carrying the same URL that failed and re-threw it on every retry, so clients looped (and tripped their own loop detection). - Point the prerequisite elicitation at a different URL (https://modelcontextprotocol.io) than the failing request. - Track issued prerequisites by the inputs a client resends on retry (session + url + caller-supplied elicitationId); a plain retry is then recognized, ignores errorPath, and proceeds via the request path instead of re-throwing the prerequisite. - Update tests and docs accordingly. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(everything): address review on URL elicitation error path - Replace raw NUL byte delimiters in errorPathKey with the \u0000 escape sequence so the source stays plain text and the diff is reviewable (same collision-proof delimiter at runtime). - Add a one-shot test reset helper + beforeEach so the suite is robust to the module-level marker state regardless of order. - Use a dedicated prerequisite message instead of reusing the caller's. - Document the unbounded-growth tradeoff as a demo simplification and note the one-shot marker semantics in docs/features.md. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: evalstate <1936278+evalstate@users.noreply.github.com> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent f5054df commit 25e5f3a

4 files changed

Lines changed: 158 additions & 20 deletions

File tree

‎src/everything/__tests__/tools.test.ts‎

Lines changed: 80 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { describe, it, expect, vi } from 'vitest';
1+
import { describe, it, expect, vi, beforeEach } from 'vitest';
22
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
33
import { registerEchoTool, EchoSchema } from '../tools/echo.js';
44
import { registerGetSumTool } from '../tools/get-sum.js';
@@ -13,7 +13,10 @@ import { registerToggleSimulatedLoggingTool } from '../tools/toggle-simulated-lo
1313
import { registerToggleSubscriberUpdatesTool } from '../tools/toggle-subscriber-updates.js';
1414
import { registerTriggerSamplingRequestTool } from '../tools/trigger-sampling-request.js';
1515
import { registerTriggerElicitationRequestTool } from '../tools/trigger-elicitation-request.js';
16-
import { registerTriggerUrlElicitationTool } from '../tools/trigger-url-elicitation.js';
16+
import {
17+
registerTriggerUrlElicitationTool,
18+
__resetIssuedErrorPathElicitations,
19+
} from '../tools/trigger-url-elicitation.js';
1720
import { registerGetRootsListTool } from '../tools/get-roots-list.js';
1821
import { registerGZipFileAsResourceTool } from '../tools/gzip-file-as-resource.js';
1922

@@ -708,6 +711,12 @@ describe('Tools', () => {
708711
});
709712

710713
describe('trigger-url-elicitation', () => {
714+
// The error-path marker is module-level state shared across cases; reset it
715+
// so tests are independent of order and of each other's leftover keys.
716+
beforeEach(() => {
717+
__resetIssuedErrorPathElicitations();
718+
});
719+
711720
it('should not register when client does not support URL elicitation', () => {
712721
const handlers: Map<string, Function> = new Map();
713722
const mockServer = {
@@ -913,7 +922,7 @@ describe('Tools', () => {
913922
);
914923
});
915924

916-
it('should throw MCP error -32042 with required URL elicitation data when errorPath is true', async () => {
925+
it('should throw MCP error -32042 with a prerequisite elicitation pointing at a different URL when errorPath is true', async () => {
917926
const handlers: Map<string, Function> = new Map();
918927
const mockServer = {
919928
registerTool: vi.fn((name: string, config: any, handler: Function) => {
@@ -928,7 +937,7 @@ describe('Tools', () => {
928937

929938
const handler = handlers.get('trigger-url-elicitation')!;
930939

931-
expect.assertions(2);
940+
expect.assertions(5);
932941

933942
try {
934943
await handler(
@@ -942,13 +951,74 @@ describe('Tools', () => {
942951
);
943952
} catch (error: any) {
944953
expect(error.code).toBe(-32042);
945-
expect(error.data.elicitations[0]).toEqual({
946-
mode: 'url',
947-
url: 'https://example.com/connect',
948-
message: 'Authorization is required to continue.',
949-
elicitationId: 'elicitation-xyz',
950-
});
954+
const prerequisite = error.data.elicitations[0];
955+
expect(prerequisite.mode).toBe('url');
956+
// The prerequisite must NOT reuse the failing URL, otherwise the client
957+
// would complete it, retry, hit the same error, and loop forever.
958+
expect(prerequisite.url).toBe('https://modelcontextprotocol.io');
959+
expect(prerequisite.url).not.toBe('https://example.com/connect');
960+
// It carries its own elicitation id for the prerequisite itself.
961+
expect(typeof prerequisite.elicitationId).toBe('string');
962+
}
963+
});
964+
965+
it('should ignore errorPath and take the request path when the same call is retried after the prerequisite', async () => {
966+
const handlers: Map<string, Function> = new Map();
967+
const mockSendRequest = vi.fn().mockResolvedValue({ action: 'accept' });
968+
969+
const mockServer = {
970+
registerTool: vi.fn((name: string, config: any, handler: Function) => {
971+
handlers.set(name, handler);
972+
}),
973+
server: {
974+
getClientCapabilities: vi.fn(() => ({ elicitation: { url: {} } })),
975+
},
976+
} as unknown as McpServer;
977+
978+
registerTriggerUrlElicitationTool(mockServer);
979+
980+
const handler = handlers.get('trigger-url-elicitation')!;
981+
// A real client retries with the *same* arguments and does not echo the
982+
// prerequisite's elicitationId. Note these args omit elicitationId, so the
983+
// correlation must rely on stable inputs (session + url), not a per-call
984+
// random id.
985+
const args = {
986+
url: 'https://example.com/connect',
987+
message: 'Authorization is required to continue.',
988+
errorPath: true,
989+
};
990+
const extra = { sessionId: 'session-1', sendRequest: mockSendRequest };
991+
992+
// First call: error path issues the prerequisite and throws -32042.
993+
let prerequisiteUrl: string | undefined;
994+
try {
995+
await handler(args, extra);
996+
throw new Error('expected first call to throw');
997+
} catch (error: any) {
998+
expect(error.code).toBe(-32042);
999+
prerequisiteUrl = error.data.elicitations[0].url;
1000+
expect(prerequisiteUrl).toBe('https://modelcontextprotocol.io');
1001+
expect(mockSendRequest).not.toHaveBeenCalled();
9511002
}
1003+
1004+
// Plain retry with identical arguments: errorPath is ignored and the call
1005+
// proceeds via the request path instead of throwing the prerequisite again.
1006+
const result = await handler({ ...args }, extra);
1007+
1008+
expect(mockSendRequest).toHaveBeenCalledWith(
1009+
expect.objectContaining({
1010+
method: 'elicitation/create',
1011+
params: expect.objectContaining({
1012+
mode: 'url',
1013+
url: 'https://example.com/connect',
1014+
}),
1015+
}),
1016+
expect.anything(),
1017+
expect.anything()
1018+
);
1019+
expect(result.content[0].text).toContain(
1020+
'✅ User completed the URL elicitation flow.'
1021+
);
9521022
});
9531023
});
9541024

‎src/everything/docs/features.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
- `toggle-simulated-logging` (tools/toggle-simulated-logging.ts): Starts or stops simulated, random‑leveled logging for the invoking session. Respects the client’s selected minimum logging level.
2424
- `toggle-subscriber-updates` (tools/toggle-subscriber-updates.ts): Starts or stops simulated resource update notifications for URIs the invoking session has subscribed to.
2525
- `trigger-elicitation-request` (tools/trigger-elicitation-request.ts): Issues an `elicitation/create` request using form-mode fields (strings, numbers, booleans, enums, and format validation) and returns the resulting action/content.
26-
- `trigger-url-elicitation` (tools/trigger-url-elicitation.ts): Issues an `elicitation/create` request in URL mode (`mode: "url"`) with an `elicitationId`, or throws MCP error `-32042` (`UrlElicitationRequiredError`) when `errorPath=true`. Requires client capability `elicitation.url`.
26+
- `trigger-url-elicitation` (tools/trigger-url-elicitation.ts): Issues an `elicitation/create` request in URL mode (`mode: "url"`) with an `elicitationId`, or throws MCP error `-32042` (`UrlElicitationRequiredError`) when `errorPath=true`. On the error path the prerequisite elicitation it returns points at a different URL than the failing request (`https://modelcontextprotocol.io`); when the client satisfies it and retries the same call, the retry ignores `errorPath` and proceeds via the request path, so the client does not loop on the same error. The retry marker is one-shot per `(session, url, elicitationId)`: it is cleared on the recognized retry, so re-running the error path with identical arguments without an intervening prerequisite is treated as a retry and proceeds. Requires client capability `elicitation.url`.
2727
- `trigger-sampling-request` (tools/trigger-sampling-request.ts): Issues a `sampling/createMessage` request to the client/LLM using provided `prompt` and optional generation controls; returns the LLM's response payload.
2828
- `simulate-research-query` (tools/simulate-research-query.ts): Demonstrates MCP Tasks (SEP-1686) with a simulated multi-stage research operation. Accepts `topic` and `ambiguous` parameters. Returns a task that progresses through stages with status updates. If `ambiguous` is true and client supports elicitation, sends an elicitation request directly to gather clarification before completing.
2929
- `trigger-sampling-request-async` (tools/trigger-sampling-request-async.ts): Demonstrates bidirectional tasks where the server sends a sampling request that the client executes as a background task. Server polls for status and retrieves the LLM result when complete. Requires client to support `tasks.requests.sampling.createMessage`.

‎src/everything/docs/structure.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ src/everything
156156
- `trigger-elicitation-request.ts`
157157
- Registers a `trigger-elicitation-request` tool that sends an `elicitation/create` request to the client/LLM and returns the elicitation result.
158158
- `trigger-url-elicitation.ts`
159-
- Registers a `trigger-url-elicitation` tool that either sends an out-of-band URL-mode `elicitation/create` request (`mode: "url"`) including an `elicitationId` (request path) or throws `UrlElicitationRequiredError` (`-32042`) for client-handled URL elicitation (error path).
159+
- Registers a `trigger-url-elicitation` tool that either sends an out-of-band URL-mode `elicitation/create` request (`mode: "url"`) including an `elicitationId` (request path) or throws `UrlElicitationRequiredError` (`-32042`) for client-handled URL elicitation (error path). On the error path the carried prerequisite elicitation points at a different URL than the failing one (`https://modelcontextprotocol.io`), and when the client satisfies it and retries the same call, the retry ignores `errorPath` and proceeds via the request path — so the client does not loop on the same error.
160160
- `trigger-elicitation-request-async.ts`
161161
- Registers a `trigger-elicitation-request-async` tool that demonstrates bidirectional MCP tasks for elicitation. Sends an elicitation request with task metadata, then polls the client's `tasks/get` endpoint for completion status before fetching the final result.
162162
- `trigger-sampling-request.ts`

‎src/everything/tools/trigger-url-elicitation.ts‎

Lines changed: 76 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,9 @@ const TriggerUrlElicitationSchema = z.object({
2626
"Controls which elicitation mechanism is used. " +
2727
"When false (default), sends an elicitation/create request (request path). " +
2828
"When true, throws a UrlElicitationRequiredError (MCP error code -32042) so the client handles " +
29-
"the URL elicitation via the error path rather than waiting for a response."
29+
"the URL elicitation via the error path rather than waiting for a response. " +
30+
"To clear the error, satisfy the prerequisite and retry this call with the same arguments; the " +
31+
"retry ignores errorPath and proceeds, so the client does not loop on the same error."
3032
),
3133
});
3234

@@ -48,6 +50,32 @@ const config = {
4850
},
4951
};
5052

53+
/**
54+
* Tracks requests for which an error-path prerequisite has already been issued,
55+
* keyed by the stable inputs a client resends when it retries the original tool
56+
* call (session + URL + caller-supplied elicitationId).
57+
*
58+
* When the client satisfies the prerequisite and retries the same call, the
59+
* matching entry lets us recognize the retry, ignore `errorPath`, and proceed
60+
* via the request path instead of re-throwing `UrlElicitationRequiredError` —
61+
* which would otherwise loop forever (throw -> client satisfies prerequisite ->
62+
* retry -> throw -> ...).
63+
*
64+
* Demo simplification: entries are only removed on a recognized retry, so a
65+
* client that triggers the error path and never retries leaves its key behind.
66+
* That is acceptable for this reference server; a production implementation
67+
* serving many long-lived sessions should evict entries (e.g. a
68+
* `Map<string, timestamp>` with TTL-based cleanup).
69+
*/
70+
const issuedErrorPathElicitations = new Set<string>();
71+
72+
/**
73+
* Test-only helper to reset the module-level error-path state between cases.
74+
* Not part of the tool's public behavior.
75+
*/
76+
export const __resetIssuedErrorPathElicitations = () =>
77+
issuedErrorPathElicitations.clear();
78+
5179
/**
5280
* Registers the 'trigger-url-elicitation' tool.
5381
*
@@ -56,8 +84,11 @@ const config = {
5684
*
5785
* Depending on the `errorPath` argument it either:
5886
* - Sends an `elicitation/create` request and awaits the result (request path), or
59-
* - Throws a `UrlElicitationRequiredError` (MCP error -32042) for the client to
60-
* handle via the error path.
87+
* - Throws a `UrlElicitationRequiredError` (MCP error -32042) carrying a
88+
* prerequisite elicitation for the client to handle (error path). When the
89+
* client satisfies the prerequisite and retries the same call, the retry
90+
* ignores `errorPath` and proceeds via the request path, so the client does
91+
* not loop on the same error.
6192
*
6293
* @param {McpServer} server - The McpServer instance where the tool will be registered.
6394
*/
@@ -85,6 +116,16 @@ export const registerTriggerUrlElicitationTool = (server: McpServer) => {
85116
} = args;
86117

87118
const elicitationId = requestedElicitationId ?? randomUUID();
119+
const sessionId = extra.sessionId ?? "default";
120+
121+
// Key the one-shot error-path marker on inputs the client resends
122+
// verbatim when it retries the original tool call. A real client retries
123+
// with the *same* arguments and does NOT echo the prerequisite's
124+
// (server-generated) elicitationId, so we must key on stable inputs:
125+
// the session, the requested URL, and the caller-supplied elicitationId
126+
// (if any). Keying on the resolved/random elicitationId would change on
127+
// every call and never match, re-throwing the prerequisite forever.
128+
const errorPathKey = `${sessionId}\u0000${url}\u0000${requestedElicitationId ?? ""}`;
88129

89130
const elicitationParams: ElicitRequestURLParams = {
90131
mode: "url",
@@ -93,12 +134,39 @@ export const registerTriggerUrlElicitationTool = (server: McpServer) => {
93134
elicitationId,
94135
};
95136

96-
// Error path: throw UrlElicitationRequiredError (-32042) for the client to handle
137+
// Error path: signal the client via UrlElicitationRequiredError (-32042)
138+
// so it handles a prerequisite URL elicitation before this request can
139+
// proceed. Two things keep the client from looping forever:
140+
//
141+
// 1. The prerequisite points at a *different* URL than the one that
142+
// failed. Reusing the original `url` would make the client complete
143+
// the prerequisite, retry, and hit the same -32042 error endlessly.
144+
// 2. We remember that we issued a prerequisite for this request. When
145+
// the client satisfies it and retries the same call, we recognize
146+
// the retry, *ignore* errorPath, and fall through to the request
147+
// path. Without this, the retry would re-enter the error path and
148+
// re-request the prerequisite URL — another loop.
97149
if (errorPath) {
98-
throw new UrlElicitationRequiredError(
99-
[elicitationParams],
100-
"This request requires browser-based authorization."
101-
);
150+
if (issuedErrorPathElicitations.has(errorPathKey)) {
151+
// Retry of a satisfied prerequisite: clear the one-shot marker and
152+
// ignore errorPath, falling through to the request path below.
153+
issuedErrorPathElicitations.delete(errorPathKey);
154+
} else {
155+
// Originating call: record that we issued a prerequisite for this
156+
// request, then signal the client via -32042.
157+
issuedErrorPathElicitations.add(errorPathKey);
158+
const prerequisiteElicitation: ElicitRequestURLParams = {
159+
mode: "url",
160+
url: "https://modelcontextprotocol.io",
161+
message:
162+
"Open this link to satisfy the prerequisite, then retry the request.",
163+
elicitationId: randomUUID(),
164+
};
165+
throw new UrlElicitationRequiredError(
166+
[prerequisiteElicitation],
167+
"This request requires browser-based authorization."
168+
);
169+
}
102170
}
103171

104172
// Request path: send elicitation/create and await the user's response

0 commit comments

Comments
 (0)