@modelcontextprotocol/server-everything 0.6.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +121 -72
  2. package/dist/docs/architecture.md +44 -0
  3. package/dist/docs/extension.md +23 -0
  4. package/dist/docs/features.md +105 -0
  5. package/dist/docs/how-it-works.md +45 -0
  6. package/dist/docs/instructions.md +37 -0
  7. package/dist/docs/startup.md +76 -0
  8. package/dist/docs/structure.md +212 -0
  9. package/dist/index.js +73 -16
  10. package/dist/prompts/args.js +34 -0
  11. package/dist/prompts/completions.js +52 -0
  12. package/dist/prompts/index.js +15 -0
  13. package/dist/prompts/resource.js +60 -0
  14. package/dist/prompts/simple.js +23 -0
  15. package/dist/resources/files.js +83 -0
  16. package/dist/resources/index.js +33 -0
  17. package/dist/resources/session.js +62 -0
  18. package/dist/resources/subscriptions.js +144 -0
  19. package/dist/resources/templates.js +166 -0
  20. package/dist/server/index.js +95 -0
  21. package/dist/server/logging.js +70 -0
  22. package/dist/server/roots.js +70 -0
  23. package/dist/tools/echo.js +35 -0
  24. package/dist/tools/get-annotated-message.js +89 -0
  25. package/dist/tools/get-env.js +34 -0
  26. package/dist/tools/get-resource-links.js +68 -0
  27. package/dist/tools/get-resource-reference.js +81 -0
  28. package/dist/tools/get-roots-list.js +77 -0
  29. package/dist/tools/get-structured-content.js +78 -0
  30. package/dist/tools/get-sum.js +46 -0
  31. package/dist/tools/get-tiny-image.js +47 -0
  32. package/dist/tools/gzip-file-as-resource.js +194 -0
  33. package/dist/tools/index.js +52 -0
  34. package/dist/tools/simulate-research-query.js +251 -0
  35. package/dist/tools/toggle-simulated-logging.js +47 -0
  36. package/dist/tools/toggle-subscriber-updates.js +50 -0
  37. package/dist/tools/trigger-elicitation-request-async.js +227 -0
  38. package/dist/tools/trigger-elicitation-request.js +222 -0
  39. package/dist/tools/trigger-long-running-operation.js +65 -0
  40. package/dist/tools/trigger-sampling-request-async.js +174 -0
  41. package/dist/tools/trigger-sampling-request.js +77 -0
  42. package/dist/tools/trigger-url-elicitation.js +169 -0
  43. package/dist/transports/in-memory-event-store.js +44 -0
  44. package/dist/transports/listen.js +36 -0
  45. package/dist/transports/sse.js +103 -0
  46. package/dist/transports/stdio.js +48 -0
  47. package/dist/transports/streamableHttp.js +240 -0
  48. package/dist/version.js +35 -0
  49. package/package.json +32 -13
  50. package/dist/everything.js +0 -361
  51. package/dist/sse.js +0 -24
@@ -0,0 +1,52 @@
1
+ import { registerGetAnnotatedMessageTool } from "./get-annotated-message.js";
2
+ import { registerEchoTool } from "./echo.js";
3
+ import { registerGetEnvTool } from "./get-env.js";
4
+ import { registerGetResourceLinksTool } from "./get-resource-links.js";
5
+ import { registerGetResourceReferenceTool } from "./get-resource-reference.js";
6
+ import { registerGetRootsListTool } from "./get-roots-list.js";
7
+ import { registerGetStructuredContentTool } from "./get-structured-content.js";
8
+ import { registerGetSumTool } from "./get-sum.js";
9
+ import { registerGetTinyImageTool } from "./get-tiny-image.js";
10
+ import { registerGZipFileAsResourceTool } from "./gzip-file-as-resource.js";
11
+ import { registerToggleSimulatedLoggingTool } from "./toggle-simulated-logging.js";
12
+ import { registerToggleSubscriberUpdatesTool } from "./toggle-subscriber-updates.js";
13
+ import { registerTriggerElicitationRequestTool } from "./trigger-elicitation-request.js";
14
+ import { registerTriggerLongRunningOperationTool } from "./trigger-long-running-operation.js";
15
+ import { registerTriggerSamplingRequestTool } from "./trigger-sampling-request.js";
16
+ import { registerTriggerSamplingRequestAsyncTool } from "./trigger-sampling-request-async.js";
17
+ import { registerTriggerElicitationRequestAsyncTool } from "./trigger-elicitation-request-async.js";
18
+ import { registerSimulateResearchQueryTool } from "./simulate-research-query.js";
19
+ import { registerTriggerUrlElicitationTool } from "./trigger-url-elicitation.js";
20
+ /**
21
+ * Register the tools with the MCP server.
22
+ * @param server
23
+ */
24
+ export const registerTools = (server) => {
25
+ registerEchoTool(server);
26
+ registerGetAnnotatedMessageTool(server);
27
+ registerGetEnvTool(server);
28
+ registerGetResourceLinksTool(server);
29
+ registerGetResourceReferenceTool(server);
30
+ registerGetStructuredContentTool(server);
31
+ registerGetSumTool(server);
32
+ registerGetTinyImageTool(server);
33
+ registerGZipFileAsResourceTool(server);
34
+ registerToggleSimulatedLoggingTool(server);
35
+ registerToggleSubscriberUpdatesTool(server);
36
+ registerTriggerLongRunningOperationTool(server);
37
+ };
38
+ /**
39
+ * Register the tools that are conditional upon client capabilities.
40
+ * These must be registered conditionally, after initialization.
41
+ */
42
+ export const registerConditionalTools = (server) => {
43
+ registerGetRootsListTool(server);
44
+ registerTriggerElicitationRequestTool(server);
45
+ registerTriggerUrlElicitationTool(server);
46
+ registerTriggerSamplingRequestTool(server);
47
+ // Task-based research tool (uses experimental tasks API)
48
+ registerSimulateResearchQueryTool(server);
49
+ // Bidirectional task tools - server sends requests that client executes as tasks
50
+ registerTriggerSamplingRequestAsyncTool(server);
51
+ registerTriggerElicitationRequestAsyncTool(server);
52
+ };
@@ -0,0 +1,251 @@
1
+ import { z } from "zod";
2
+ import { ElicitResultSchema, } from "@modelcontextprotocol/sdk/types.js";
3
+ // Tool input schema
4
+ const SimulateResearchQuerySchema = z.object({
5
+ topic: z.string().describe("The research topic to investigate"),
6
+ ambiguous: z
7
+ .boolean()
8
+ .default(false)
9
+ .describe("Simulate an ambiguous query that requires clarification (triggers input_required status)"),
10
+ });
11
+ // Research stages
12
+ const STAGES = [
13
+ "Gathering sources",
14
+ "Analyzing content",
15
+ "Synthesizing findings",
16
+ "Generating report",
17
+ ];
18
+ // Duration per stage in milliseconds
19
+ const STAGE_DURATION = 1000;
20
+ // Map to store research state per task
21
+ const researchStates = new Map();
22
+ /**
23
+ * Runs the background research process.
24
+ * Updates task status as it progresses through stages.
25
+ * If clarification is needed, sends elicitation via sendRequest with relatedTask,
26
+ * which queues the request in the task message queue. The SDK delivers it through
27
+ * the tasks/result stream when the client calls tasks/result (per spec input_required flow).
28
+ * This works on all transports (STDIO, SSE, Streamable HTTP).
29
+ */
30
+ async function runResearchProcess(taskId, args, taskStore,
31
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
32
+ sendRequest) {
33
+ const state = researchStates.get(taskId);
34
+ /* v8 ignore next -- createTask stores the state immediately before starting this process */
35
+ if (!state)
36
+ return;
37
+ // Process each stage
38
+ for (let i = state.currentStage; i < STAGES.length; i++) {
39
+ state.currentStage = i;
40
+ // Check if task was cancelled externally
41
+ if (state.completed)
42
+ return;
43
+ // Update status message for current stage
44
+ await taskStore.updateTaskStatus(taskId, "working", `${STAGES[i]}...`);
45
+ // At synthesis stage (index 2), check if clarification is needed
46
+ if (i === 2 && state.ambiguous && !state.clarification) {
47
+ // Update status to show we're requesting input (spec SHOULD)
48
+ await taskStore.updateTaskStatus(taskId, "input_required", `Found multiple interpretations for "${state.topic}". Requesting clarification...`);
49
+ try {
50
+ // relatedTask queues elicitation via task message queue → delivered through tasks/result on all transports
51
+ const elicitResult = await sendRequest({
52
+ method: "elicitation/create",
53
+ params: {
54
+ message: `The research query "${state.topic}" could have multiple interpretations. Please clarify what you're looking for:`,
55
+ requestedSchema: {
56
+ type: "object",
57
+ properties: {
58
+ interpretation: {
59
+ type: "string",
60
+ title: "Clarification",
61
+ description: "Which interpretation of the topic do you mean?",
62
+ oneOf: getInterpretationsForTopic(state.topic),
63
+ },
64
+ },
65
+ required: ["interpretation"],
66
+ },
67
+ },
68
+ }, ElicitResultSchema, { relatedTask: { taskId } });
69
+ // Process elicitation response
70
+ if (elicitResult.action === "accept" && elicitResult.content) {
71
+ state.clarification =
72
+ elicitResult.content
73
+ .interpretation || "User accepted without selection";
74
+ }
75
+ else if (elicitResult.action === "decline") {
76
+ state.clarification = "User declined - using default interpretation";
77
+ }
78
+ else {
79
+ state.clarification = "User cancelled - using default interpretation";
80
+ }
81
+ }
82
+ catch (error) {
83
+ // Elicitation failed - use default interpretation and continue
84
+ console.warn(`Elicitation failed for task ${taskId}:`, error instanceof Error ? error.message : String(error));
85
+ state.clarification = "technical (default - elicitation unavailable)";
86
+ }
87
+ // Resume with working status (spec SHOULD)
88
+ await taskStore.updateTaskStatus(taskId, "working", `Continuing with interpretation: "${state.clarification}"...`);
89
+ // Continue processing (no return - just keep going through the loop)
90
+ }
91
+ // Simulate work for this stage
92
+ await new Promise((resolve) => setTimeout(resolve, STAGE_DURATION));
93
+ }
94
+ // All stages complete - generate result
95
+ state.completed = true;
96
+ const result = generateResearchReport(state);
97
+ state.result = result;
98
+ await taskStore.storeTaskResult(taskId, "completed", result);
99
+ }
100
+ /**
101
+ * Generates the final research report with educational content about tasks.
102
+ */
103
+ function generateResearchReport(state) {
104
+ const topic = state.clarification
105
+ ? `${state.topic} (${state.clarification})`
106
+ : state.topic;
107
+ const report = `# Research Report: ${topic}
108
+
109
+ ## Research Parameters
110
+ - **Topic**: ${state.topic}
111
+ ${state.clarification ? `- **Clarification**: ${state.clarification}` : ""}
112
+
113
+ ## Synthesis
114
+ This research query was processed through ${STAGES.length} stages:
115
+ ${STAGES.map((s, i) => `- Stage ${i + 1}: ${s} ✓`).join("\n")}
116
+
117
+ ---
118
+
119
+ ## About This Demo (SEP-1686: Tasks)
120
+
121
+ This tool demonstrates MCP's task-based execution pattern for long-running operations:
122
+
123
+ **Task Lifecycle Demonstrated:**
124
+ 1. \`tools/call\` with \`task\` parameter → Server returns \`CreateTaskResult\` (not the final result)
125
+ 2. Client polls \`tasks/get\` → Server returns current status and \`statusMessage\`
126
+ 3. Status progressed: \`working\` → ${state.clarification ? `\`input_required\` → \`working\` → ` : ""}\`completed\`
127
+ 4. Client calls \`tasks/result\` → Server returns this final result
128
+
129
+ ${state.clarification
130
+ ? `**Elicitation Flow:**
131
+ When the query was ambiguous, the server sent an \`elicitation/create\` request
132
+ to the client. The task status changed to \`input_required\` while awaiting user input.
133
+ ${state.clarification.includes("unavailable")
134
+ ? `**Note:** Elicitation failed and a default interpretation was used.`
135
+ : `After receiving clarification ("${state.clarification}"), the task resumed processing and completed.`}
136
+ `
137
+ : ""}
138
+ **Key Concepts:**
139
+ - Tasks enable "call now, fetch later" patterns
140
+ - \`statusMessage\` provides human-readable progress updates
141
+ - Tasks have TTL (time-to-live) for automatic cleanup
142
+ - \`pollInterval\` suggests how often to check status
143
+ - Elicitation requests use \`relatedTask\` to queue via tasks/result (works on all transports)
144
+
145
+ *This is a simulated research report from the Everything MCP Server.*
146
+ `;
147
+ return {
148
+ content: [
149
+ {
150
+ type: "text",
151
+ text: report,
152
+ },
153
+ ],
154
+ };
155
+ }
156
+ /**
157
+ * Registers the 'simulate-research-query' tool as a task-based tool.
158
+ *
159
+ * This tool demonstrates the MCP Tasks feature (SEP-1686) with a real-world scenario:
160
+ * a research tool that gathers and synthesizes information from multiple sources.
161
+ * If the query is ambiguous, it pauses to ask for clarification before completing.
162
+ *
163
+ * @param {McpServer} server - The McpServer instance where the tool will be registered.
164
+ */
165
+ export const registerSimulateResearchQueryTool = (server) => {
166
+ // Check if client supports elicitation (needed for input_required flow)
167
+ const clientCapabilities = server.server.getClientCapabilities() || {};
168
+ const clientSupportsElicitation = clientCapabilities.elicitation !== undefined;
169
+ server.experimental.tasks.registerToolTask("simulate-research-query", {
170
+ title: "Simulate Research Query",
171
+ description: "Simulates a deep research operation that gathers, analyzes, and synthesizes information. " +
172
+ "Demonstrates MCP task-based operations with progress through multiple stages. " +
173
+ "If 'ambiguous' is true and client supports elicitation, sends an elicitation request for clarification.",
174
+ inputSchema: SimulateResearchQuerySchema,
175
+ execution: { taskSupport: "required" },
176
+ annotations: {
177
+ readOnlyHint: false,
178
+ destructiveHint: false,
179
+ idempotentHint: false,
180
+ openWorldHint: false,
181
+ },
182
+ }, {
183
+ /**
184
+ * Creates a new research task and starts background processing.
185
+ */
186
+ createTask: async (args, extra) => {
187
+ const validatedArgs = SimulateResearchQuerySchema.parse(args);
188
+ // Create the task in the store
189
+ const task = await extra.taskStore.createTask({
190
+ ttl: 300000, // 5 minutes
191
+ pollInterval: 1000,
192
+ });
193
+ // Initialize research state
194
+ const state = {
195
+ topic: validatedArgs.topic,
196
+ ambiguous: validatedArgs.ambiguous && clientSupportsElicitation,
197
+ currentStage: 0,
198
+ completed: false,
199
+ };
200
+ researchStates.set(task.taskId, state);
201
+ // Start background research (don't await - runs asynchronously)
202
+ // Pass sendRequest for elicitation (queued via task message queue, works on all transports)
203
+ runResearchProcess(task.taskId, validatedArgs, extra.taskStore, extra.sendRequest).catch((error) => {
204
+ console.error(`Research task ${task.taskId} failed:`, error);
205
+ extra.taskStore
206
+ .updateTaskStatus(task.taskId, "failed", String(error))
207
+ .catch(console.error);
208
+ });
209
+ return { task };
210
+ },
211
+ /* v8 ignore start -- SDK 1.x never calls a tool task's getTask/getTaskResult: tasks/get and tasks/result are answered from the task store (Protocol), so these handlers are unreachable over the wire */
212
+ /**
213
+ * Returns the current status of the research task.
214
+ */
215
+ getTask: async (args, extra) => {
216
+ return await extra.taskStore.getTask(extra.taskId);
217
+ },
218
+ /**
219
+ * Returns the task result.
220
+ * Elicitation is now handled directly in the background process.
221
+ */
222
+ getTaskResult: async (args, extra) => {
223
+ // Return the stored result
224
+ const result = await extra.taskStore.getTaskResult(extra.taskId);
225
+ // Clean up state
226
+ researchStates.delete(extra.taskId);
227
+ return result;
228
+ },
229
+ /* v8 ignore stop */
230
+ });
231
+ };
232
+ /**
233
+ * Returns contextual interpretation options based on the topic.
234
+ */
235
+ function getInterpretationsForTopic(topic) {
236
+ const lowerTopic = topic.toLowerCase();
237
+ // Example: contextual interpretations for "python"
238
+ if (lowerTopic.includes("python")) {
239
+ return [
240
+ { const: "programming", title: "Python programming language" },
241
+ { const: "snake", title: "Python snake species" },
242
+ { const: "comedy", title: "Monty Python comedy group" },
243
+ ];
244
+ }
245
+ // Default generic interpretations
246
+ return [
247
+ { const: "technical", title: "Technical/scientific perspective" },
248
+ { const: "historical", title: "Historical perspective" },
249
+ { const: "current", title: "Current events/news perspective" },
250
+ ];
251
+ }
@@ -0,0 +1,47 @@
1
+ import { beginSimulatedLogging, stopSimulatedLogging, } from "../server/logging.js";
2
+ // Tool configuration
3
+ const name = "toggle-simulated-logging";
4
+ const config = {
5
+ title: "Toggle Simulated Logging",
6
+ description: "Toggles simulated, random-leveled logging on or off.",
7
+ inputSchema: {},
8
+ annotations: {
9
+ readOnlyHint: false,
10
+ destructiveHint: false,
11
+ idempotentHint: false,
12
+ openWorldHint: false,
13
+ },
14
+ };
15
+ // Track enabled clients by session id
16
+ const clients = new Set();
17
+ /**
18
+ * Registers the `toggle-simulated-logging` tool.
19
+ *
20
+ * The registered tool enables or disables the sending of periodic, random-leveled
21
+ * logging messages the connected client.
22
+ *
23
+ * When invoked, it either starts or stops simulated logging based on the session's
24
+ * current state. If logging for the specified session is active, it will be stopped;
25
+ * if it is inactive, logging will be started.
26
+ *
27
+ * @param {McpServer} server - The McpServer instance where the tool will be registered.
28
+ */
29
+ export const registerToggleSimulatedLoggingTool = (server) => {
30
+ server.registerTool(name, config, async (_args, extra) => {
31
+ const sessionId = extra?.sessionId;
32
+ let response;
33
+ if (clients.has(sessionId)) {
34
+ stopSimulatedLogging(sessionId);
35
+ clients.delete(sessionId);
36
+ response = `Stopped simulated logging for session ${sessionId}`;
37
+ }
38
+ else {
39
+ beginSimulatedLogging(server, sessionId);
40
+ clients.add(sessionId);
41
+ response = `Started simulated, random-leveled logging for session ${sessionId} at a 5 second pace. Client's selected logging level will be respected. If an interval elapses and the message to be sent is below the selected level, it will not be sent. Thus at higher chosen logging levels, messages should arrive further apart. `;
42
+ }
43
+ return {
44
+ content: [{ type: "text", text: `${response}` }],
45
+ };
46
+ });
47
+ };
@@ -0,0 +1,50 @@
1
+ import { beginSimulatedResourceUpdates, stopSimulatedResourceUpdates, } from "../resources/subscriptions.js";
2
+ // Tool configuration
3
+ const name = "toggle-subscriber-updates";
4
+ const config = {
5
+ title: "Toggle Subscriber Updates",
6
+ description: "Toggles simulated resource subscription updates on or off.",
7
+ inputSchema: {},
8
+ annotations: {
9
+ readOnlyHint: false,
10
+ destructiveHint: false,
11
+ idempotentHint: false,
12
+ openWorldHint: false,
13
+ },
14
+ };
15
+ // Track enabled clients by session id
16
+ const clients = new Set();
17
+ /**
18
+ * Registers the `toggle-subscriber-updates` tool.
19
+ *
20
+ * The registered tool enables or disables the sending of periodic, simulated resource
21
+ * update messages the connected client for any subscriptions they have made.
22
+ *
23
+ * When invoked, it either starts or stops simulated resource updates based on the session's
24
+ * current state. If simulated updates for the specified session is active, it will be stopped;
25
+ * if it is inactive, simulated updates will be started.
26
+ *
27
+ * The response provides feedback indicating whether simulated updates were started or stopped,
28
+ * including the session ID.
29
+ *
30
+ * @param {McpServer} server - The McpServer instance where the tool will be registered.
31
+ */
32
+ export const registerToggleSubscriberUpdatesTool = (server) => {
33
+ server.registerTool(name, config, async (_args, extra) => {
34
+ const sessionId = extra?.sessionId;
35
+ let response;
36
+ if (clients.has(sessionId)) {
37
+ stopSimulatedResourceUpdates(sessionId);
38
+ clients.delete(sessionId);
39
+ response = `Stopped simulated resource updates for session ${sessionId}`;
40
+ }
41
+ else {
42
+ beginSimulatedResourceUpdates(server, sessionId);
43
+ clients.add(sessionId);
44
+ response = `Started simulated resource updated notifications for session ${sessionId} at a 5 second pace. Client will receive updates for any resources the it is subscribed to.`;
45
+ }
46
+ return {
47
+ content: [{ type: "text", text: `${response}` }],
48
+ };
49
+ });
50
+ };
@@ -0,0 +1,227 @@
1
+ import { z } from "zod";
2
+ // Tool configuration
3
+ const name = "trigger-elicitation-request-async";
4
+ const config = {
5
+ title: "Trigger Async Elicitation Request Tool",
6
+ description: "Trigger an async elicitation request that the CLIENT executes as a background task. " +
7
+ "Demonstrates bidirectional MCP tasks where the server sends an elicitation request and " +
8
+ "the client handles user input asynchronously, allowing the server to poll for completion.",
9
+ inputSchema: {},
10
+ annotations: {
11
+ readOnlyHint: false,
12
+ destructiveHint: false,
13
+ idempotentHint: false,
14
+ openWorldHint: false,
15
+ },
16
+ };
17
+ // Poll interval in milliseconds
18
+ const POLL_INTERVAL = 1000;
19
+ // Time-to-live requested for the client's task (10 minutes for user input)
20
+ const TASK_TTL = 600000;
21
+ // Stop polling this long before the TTL runs out, so the last tasks/get
22
+ // reaches the client while it still holds the task
23
+ const TTL_SAFETY_MARGIN = 5000;
24
+ /**
25
+ * Registers the 'trigger-elicitation-request-async' tool.
26
+ *
27
+ * This tool demonstrates bidirectional MCP tasks for elicitation:
28
+ * - Server sends elicitation request to client with task metadata
29
+ * - Client creates a task and returns CreateTaskResult
30
+ * - Client prompts user for input (task status: input_required)
31
+ * - Server polls client's tasks/get endpoint for status
32
+ * - Server fetches final result from client's tasks/result endpoint
33
+ *
34
+ * @param {McpServer} server - The McpServer instance where the tool will be registered.
35
+ */
36
+ export const registerTriggerElicitationRequestAsyncTool = (server) => {
37
+ // Check client capabilities
38
+ const clientCapabilities = server.server.getClientCapabilities() || {};
39
+ // Client must support form-mode elicitation AND tasks.requests.elicitation.
40
+ // The request is form mode, so a URL-only client cannot answer it (#4985):
41
+ // form mode is `elicitation.form`, or `elicitation` with neither mode.
42
+ const elicitation = clientCapabilities.elicitation;
43
+ const clientSupportsElicitation = elicitation !== undefined &&
44
+ (elicitation.form !== undefined || elicitation.url === undefined);
45
+ const clientTasksCapability = clientCapabilities.tasks;
46
+ const clientSupportsAsyncElicitation = clientTasksCapability?.requests?.elicitation?.create !== undefined;
47
+ if (clientSupportsElicitation && clientSupportsAsyncElicitation) {
48
+ server.registerTool(name, config, async (args, extra) => {
49
+ // Polling must end before the client may expire the task. The client
50
+ // starts the TTL when it creates the task, after this point, so a
51
+ // deadline measured from here is conservative. performance.now() is
52
+ // monotonic, so a wall-clock adjustment cannot stretch the deadline.
53
+ const pollDeadline = performance.now() + TASK_TTL - TTL_SAFETY_MARGIN;
54
+ // Create the elicitation request WITH task metadata
55
+ // Using z.any() schema to avoid complex type matching with _meta
56
+ const request = {
57
+ method: "elicitation/create",
58
+ params: {
59
+ task: {
60
+ ttl: TASK_TTL, // 10 minutes (user input may take a while)
61
+ },
62
+ message: "Please provide inputs for the following fields (async task demo):",
63
+ requestedSchema: {
64
+ type: "object",
65
+ properties: {
66
+ name: {
67
+ title: "Your Name",
68
+ type: "string",
69
+ description: "Your full name",
70
+ },
71
+ favoriteColor: {
72
+ title: "Favorite Color",
73
+ type: "string",
74
+ description: "What is your favorite color?",
75
+ enum: ["Red", "Blue", "Green", "Yellow", "Purple"],
76
+ },
77
+ agreeToTerms: {
78
+ title: "Terms Agreement",
79
+ type: "boolean",
80
+ description: "Do you agree to the terms and conditions?",
81
+ },
82
+ },
83
+ required: ["name"],
84
+ },
85
+ },
86
+ };
87
+ // Send the elicitation request
88
+ // Client may return either:
89
+ // - ElicitResult (synchronous execution)
90
+ // - CreateTaskResult (task-based execution with { task } object)
91
+ const elicitResponse = await extra.sendRequest(request, z.union([
92
+ // CreateTaskResult - client created a task
93
+ z.object({
94
+ task: z.object({
95
+ taskId: z.string(),
96
+ status: z.string(),
97
+ pollInterval: z.number().optional(),
98
+ statusMessage: z.string().optional(),
99
+ }),
100
+ }),
101
+ // ElicitResult - synchronous execution
102
+ z.object({
103
+ action: z.string(),
104
+ content: z.any().optional(),
105
+ }),
106
+ ]));
107
+ // Check if client returned CreateTaskResult (has task object)
108
+ const isTaskResult = "task" in elicitResponse && elicitResponse.task;
109
+ if (!isTaskResult) {
110
+ // Client executed synchronously - return the direct response
111
+ return {
112
+ content: [
113
+ {
114
+ type: "text",
115
+ text: `[SYNC] Client executed synchronously:\n${JSON.stringify(elicitResponse, null, 2)}`,
116
+ },
117
+ ],
118
+ };
119
+ }
120
+ const taskId = elicitResponse.task.taskId;
121
+ const statusMessages = [];
122
+ statusMessages.push(`Task created: ${taskId}`);
123
+ // Poll for task completion
124
+ let attempts = 0;
125
+ let taskStatus = elicitResponse.task.status;
126
+ // A task that is already finished when created is never polled, so
127
+ // its status message has to come from the CreateTaskResult
128
+ let taskStatusMessage = elicitResponse.task.statusMessage;
129
+ let timedOut = false;
130
+ while (taskStatus !== "completed" &&
131
+ taskStatus !== "failed" &&
132
+ taskStatus !== "cancelled") {
133
+ // Wait before polling
134
+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL));
135
+ // Give up rather than poll past the TTL the task was created with.
136
+ // Checked after the wait, so a timer that fires late cannot slip a
137
+ // poll in after the deadline.
138
+ if (performance.now() > pollDeadline) {
139
+ timedOut = true;
140
+ break;
141
+ }
142
+ attempts++;
143
+ // Get task status from client
144
+ const pollResult = await extra.sendRequest({
145
+ method: "tasks/get",
146
+ params: { taskId },
147
+ }, z.looseObject({
148
+ status: z.string(),
149
+ statusMessage: z.string().optional(),
150
+ }));
151
+ taskStatus = pollResult.status;
152
+ taskStatusMessage = pollResult.statusMessage;
153
+ // Only log status changes or every 10 polls to avoid spam
154
+ if (attempts === 1 ||
155
+ attempts % 10 === 0 ||
156
+ taskStatus !== "input_required") {
157
+ statusMessages.push(`Poll ${attempts}: ${taskStatus}${taskStatusMessage ? ` - ${taskStatusMessage}` : ""}`);
158
+ }
159
+ }
160
+ // Check for timeout
161
+ if (timedOut) {
162
+ return {
163
+ content: [
164
+ {
165
+ type: "text",
166
+ text: `[TIMEOUT] Task timed out after ${attempts} poll attempts, before its ${TASK_TTL / 60000}-minute TTL expired\n\nProgress:\n${statusMessages.join("\n")}`,
167
+ },
168
+ ],
169
+ };
170
+ }
171
+ // Check for failure/cancellation
172
+ if (taskStatus === "failed" || taskStatus === "cancelled") {
173
+ return {
174
+ content: [
175
+ {
176
+ type: "text",
177
+ text: `[${taskStatus.toUpperCase()}] ${taskStatusMessage || "No message"}\n\nProgress:\n${statusMessages.join("\n")}`,
178
+ },
179
+ ],
180
+ };
181
+ }
182
+ // Fetch the final result
183
+ const result = await extra.sendRequest({
184
+ method: "tasks/result",
185
+ params: { taskId },
186
+ }, z.any());
187
+ // Format the elicitation result
188
+ const content = [];
189
+ if (result.action === "accept" && result.content) {
190
+ content.push({
191
+ type: "text",
192
+ text: `[COMPLETED] User provided the requested information!`,
193
+ });
194
+ const userData = result.content;
195
+ const lines = [];
196
+ if (userData.name)
197
+ lines.push(`- Name: ${userData.name}`);
198
+ if (userData.favoriteColor)
199
+ lines.push(`- Favorite Color: ${userData.favoriteColor}`);
200
+ if (userData.agreeToTerms !== undefined)
201
+ lines.push(`- Agreed to terms: ${userData.agreeToTerms}`);
202
+ content.push({
203
+ type: "text",
204
+ text: `User inputs:\n${lines.join("\n")}`,
205
+ });
206
+ }
207
+ else if (result.action === "decline") {
208
+ content.push({
209
+ type: "text",
210
+ text: `[DECLINED] User declined to provide the requested information.`,
211
+ });
212
+ }
213
+ else if (result.action === "cancel") {
214
+ content.push({
215
+ type: "text",
216
+ text: `[CANCELLED] User cancelled the elicitation dialog.`,
217
+ });
218
+ }
219
+ // Include progress and raw result for debugging
220
+ content.push({
221
+ type: "text",
222
+ text: `\nProgress:\n${statusMessages.join("\n")}\n\nRaw result: ${JSON.stringify(result, null, 2)}`,
223
+ });
224
+ return { content };
225
+ });
226
+ }
227
+ };