@modelcontextprotocol/server-everything 0.6.2 → 2.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 (59) hide show
  1. package/README.md +140 -76
  2. package/dist/docs/architecture.md +45 -0
  3. package/dist/docs/extension.md +25 -0
  4. package/dist/docs/features.md +99 -0
  5. package/dist/docs/how-it-works.md +60 -0
  6. package/dist/docs/instructions.md +44 -0
  7. package/dist/docs/startup.md +71 -0
  8. package/dist/docs/structure.md +246 -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 +61 -0
  14. package/dist/prompts/simple.js +23 -0
  15. package/dist/resources/files.js +91 -0
  16. package/dist/resources/index.js +38 -0
  17. package/dist/resources/minted.js +119 -0
  18. package/dist/resources/session.js +62 -0
  19. package/dist/resources/subscriptions.js +66 -0
  20. package/dist/resources/templates.js +167 -0
  21. package/dist/server/context.js +47 -0
  22. package/dist/server/index.js +153 -0
  23. package/dist/server/logging.js +43 -0
  24. package/dist/server/roots.js +49 -0
  25. package/dist/server/tasks.js +295 -0
  26. package/dist/tools/echo.js +35 -0
  27. package/dist/tools/get-annotated-message.js +89 -0
  28. package/dist/tools/get-env.js +34 -0
  29. package/dist/tools/get-header-params.js +95 -0
  30. package/dist/tools/get-resource-links.js +68 -0
  31. package/dist/tools/get-resource-reference.js +81 -0
  32. package/dist/tools/get-roots-list.js +76 -0
  33. package/dist/tools/get-structured-content.js +78 -0
  34. package/dist/tools/get-sum.js +46 -0
  35. package/dist/tools/get-tiny-image.js +47 -0
  36. package/dist/tools/gzip-file-as-resource.js +213 -0
  37. package/dist/tools/index.js +110 -0
  38. package/dist/tools/simulate-research-query.js +216 -0
  39. package/dist/tools/toggle-simulated-logging.js +60 -0
  40. package/dist/tools/toggle-subscriber-updates.js +60 -0
  41. package/dist/tools/trigger-elicitation-request-async.js +122 -0
  42. package/dist/tools/trigger-elicitation-request.js +223 -0
  43. package/dist/tools/trigger-list-changed.js +57 -0
  44. package/dist/tools/trigger-log-messages.js +60 -0
  45. package/dist/tools/trigger-long-running-operation.js +65 -0
  46. package/dist/tools/trigger-multi-step-elicitation.js +125 -0
  47. package/dist/tools/trigger-resource-update.js +52 -0
  48. package/dist/tools/trigger-sampling-request-async.js +110 -0
  49. package/dist/tools/trigger-sampling-request.js +83 -0
  50. package/dist/tools/trigger-url-elicitation.js +206 -0
  51. package/dist/transports/in-memory-event-store.js +44 -0
  52. package/dist/transports/listen.js +36 -0
  53. package/dist/transports/sse.js +112 -0
  54. package/dist/transports/stdio.js +68 -0
  55. package/dist/transports/streamableHttp.js +326 -0
  56. package/dist/version.js +35 -0
  57. package/package.json +39 -13
  58. package/dist/everything.js +0 -361
  59. package/dist/sse.js +0 -24
@@ -0,0 +1,49 @@
1
+ // The 2025-era roots sync: after `initialize`, a server whose client supports
2
+ // Roots asks for the list with `roots/list`, and asks again each time the
3
+ // client sends `notifications/roots/list_changed`, reporting each answer to
4
+ // the client as a log message.
5
+ //
6
+ // 2025-era only, and deprecated: the 2026-07-28 revision removes
7
+ // server-to-client requests and `notifications/roots/list_changed`, and
8
+ // deprecates Roots. There a server asks for roots in-band, by returning an
9
+ // `input_required` result from a call, which `get-roots-list` does on both
10
+ // eras (#4852). Nothing is cached: the answer is only reported.
11
+ /** The servers whose `roots/list_changed` handler is installed. */
12
+ const watching = new WeakSet();
13
+ /**
14
+ * Ask the client for its roots and report the answer, and re-ask on each
15
+ * `notifications/roots/list_changed`. Does nothing for a client without Roots.
16
+ * Safe to call more than once: the notification handler is installed once.
17
+ *
18
+ * A failed request is logged to stderr, not thrown, since the caller is a
19
+ * timer with nothing to report the failure to.
20
+ *
21
+ * @param {McpServer} server - The 2025-era server whose client is asked.
22
+ */
23
+ export const syncRoots = async (server) => {
24
+ const clientCapabilities = server.server.getClientCapabilities() || {};
25
+ if (clientCapabilities.roots === undefined)
26
+ return;
27
+ const requestRoots = async () => {
28
+ try {
29
+ const response = await server.server.listRoots();
30
+ await server.sendLoggingMessage({
31
+ level: "info",
32
+ logger: "everything-server",
33
+ data: `Roots updated: ${response.roots.length} root(s) received from client`,
34
+ }, server.server.transport?.sessionId);
35
+ }
36
+ catch (error) {
37
+ console.error(`Failed to request roots from client: ${
38
+ /* v8 ignore start -- the SDK always rejects listRoots() with an Error (ProtocolError or SdkError) */
39
+ error instanceof Error ? error.message : String(error)
40
+ /* v8 ignore stop */
41
+ }`);
42
+ }
43
+ };
44
+ if (!watching.has(server)) {
45
+ watching.add(server);
46
+ server.server.setNotificationHandler("notifications/roots/list_changed", requestRoots);
47
+ }
48
+ await requestRoots();
49
+ };
@@ -0,0 +1,295 @@
1
+ // The server side of the Tasks extension (`io.modelcontextprotocol/tasks`,
2
+ // SEP-2663) on the 2026-07-28 revision (#4852).
3
+ //
4
+ // A tool that runs as a task answers `tools/call` with a task handle
5
+ // (`resultType: "task"`) instead of its result. The client then polls
6
+ // `tasks/get` for the task's status, answers an `input_required` status with
7
+ // `tasks/update`, and may stop the task with `tasks/cancel`; the final result
8
+ // arrives inside the `completed` status. The SDK has no server implementation
9
+ // of the extension (modelcontextprotocol/ext-tasks#30), so this module is one,
10
+ // for the everything server's three task tools.
11
+ //
12
+ // A task outlives the request that created it, and on the 2026-07-28 HTTP
13
+ // path every request is served by a fresh server instance, so tasks live in a
14
+ // process-wide store keyed by the task id. The id is a random UUID the server
15
+ // mints: it is the handle, and knowing it is what lets a client reach the
16
+ // task. Nothing runs in the background. A task's status is worked out from the
17
+ // clock when it is read, so there are no timers to stop; a task past its TTL
18
+ // is dropped the next time the store is touched.
19
+ //
20
+ // The extension is served on 2026-07-28 only. The 2025-11-25 revision had its
21
+ // own, different task methods in the core protocol; they are not served.
22
+ import { randomUUID } from "node:crypto";
23
+ import { CLIENT_CAPABILITIES_META_KEY, MissingRequiredClientCapabilityError, ProtocolError, ProtocolErrorCode, } from "@modelcontextprotocol/server";
24
+ import { z } from "zod";
25
+ /** The extension's identifier, as declared in `capabilities.extensions`. */
26
+ export const TASKS_EXTENSION = "io.modelcontextprotocol/tasks";
27
+ /** Every live task, by id, across every server instance in the process. */
28
+ const tasks = new Map();
29
+ /**
30
+ * The most tasks the process keeps. A task holds its tool's arguments (each
31
+ * task tool bounds their length) and the client's answers (bounded by the
32
+ * transports' request size) until its TTL, so without a cap a burst of calls
33
+ * could exhaust memory first. A live task is kept until its TTL, since the
34
+ * extension lets a server discard one only after that, so at the cap a new
35
+ * task is refused rather than an old one dropped.
36
+ */
37
+ export const MAX_TASKS = 100;
38
+ /**
39
+ * The most bytes of answers, serialized, one `tasks/update` may hand a task.
40
+ * A task keeps its answers until its TTL, and a transport accepts messages
41
+ * far larger than any of these tasks needs (10 MiB on stdio), so with
42
+ * `MAX_TASKS` this bounds what the store holds.
43
+ */
44
+ export const MAX_ANSWER_BYTES = 64 * 1024;
45
+ /** Drop every task past its TTL. */
46
+ function sweep(now) {
47
+ for (const [taskId, task] of tasks) {
48
+ if (task.createdAt + task.ttlMs <= now)
49
+ tasks.delete(taskId);
50
+ }
51
+ }
52
+ /** The task with this id, or a -32602 error naming it as unknown. */
53
+ function find(taskId, now) {
54
+ sweep(now);
55
+ const task = tasks.get(taskId);
56
+ if (!task) {
57
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Unknown task: ${taskId}`);
58
+ }
59
+ return task;
60
+ }
61
+ /** The task's state now, honoring a cancellation. */
62
+ function stateOf(task, now) {
63
+ return task.cancelledAt !== undefined
64
+ ? {
65
+ status: "cancelled",
66
+ statusMessage: "Cancelled by the client",
67
+ since: task.cancelledAt,
68
+ }
69
+ : task.behavior.stateAt(now);
70
+ }
71
+ /** The wire form of a task (the `DetailedTask` of the extension's schema). */
72
+ function describe(task, now) {
73
+ const state = stateOf(task, now);
74
+ return {
75
+ taskId: task.taskId,
76
+ status: state.status,
77
+ ...(state.statusMessage !== undefined && {
78
+ statusMessage: state.statusMessage,
79
+ }),
80
+ createdAt: new Date(task.createdAt).toISOString(),
81
+ lastUpdatedAt: new Date(Math.max(task.createdAt, state.since)).toISOString(),
82
+ ttlMs: task.ttlMs,
83
+ pollIntervalMs: task.pollIntervalMs,
84
+ ...(state.status === "input_required" && {
85
+ inputRequests: state.inputRequests,
86
+ }),
87
+ ...(state.status === "completed" && { result: state.result }),
88
+ };
89
+ }
90
+ /**
91
+ * Store a new task and return the `tools/call` result that hands its handle
92
+ * to the client: the task's fields, with `resultType: "task"`.
93
+ *
94
+ * @param behavior - How the task progresses.
95
+ * @param options - Its time-to-live and the polling interval to suggest.
96
+ */
97
+ export function createTask(behavior, options) {
98
+ const now = Date.now();
99
+ sweep(now);
100
+ if (tasks.size >= MAX_TASKS) {
101
+ return {
102
+ content: [
103
+ {
104
+ type: "text",
105
+ text: `The server is already running ${MAX_TASKS} tasks, its limit. Try again once one has expired.`,
106
+ },
107
+ ],
108
+ isError: true,
109
+ };
110
+ }
111
+ const task = {
112
+ taskId: randomUUID(),
113
+ createdAt: now,
114
+ ...options,
115
+ behavior,
116
+ };
117
+ tasks.set(task.taskId, task);
118
+ // The SDK passes a tool result's `resultType` through to the wire on
119
+ // 2026-07-28, which is how a task handle replaces the tool's result.
120
+ return { content: [], resultType: "task", ...describe(task, now) };
121
+ }
122
+ /**
123
+ * The capabilities the client declared in this request's `_meta` envelope,
124
+ * where a 2026-07-28 client sends them with every request.
125
+ */
126
+ export function clientCapabilitiesOf(ctx) {
127
+ // The SDK's published typing of the envelope has no members, so it is read
128
+ // as the plain JSON object it is.
129
+ const envelope = ctx.mcpReq.envelope;
130
+ const capabilities = isObject(envelope)
131
+ ? envelope[CLIENT_CAPABILITIES_META_KEY]
132
+ : undefined;
133
+ return isObject(capabilities) ? capabilities : undefined;
134
+ }
135
+ /**
136
+ * Whether the client that sent this request supports form-mode elicitation:
137
+ * `elicitation.form`, or an `elicitation` object with neither mode, which the
138
+ * spec reads as form mode (#4985).
139
+ */
140
+ export function clientSupportsFormElicitation(ctx) {
141
+ const elicitation = clientCapabilitiesOf(ctx)?.elicitation;
142
+ return (isObject(elicitation) &&
143
+ (elicitation.form !== undefined || elicitation.url === undefined));
144
+ }
145
+ /**
146
+ * Whether the client that sent this request declared the tasks extension, so
147
+ * it can follow a task handle. A tool may answer with a task only then.
148
+ */
149
+ export function clientSupportsTasks(ctx) {
150
+ const extensions = clientCapabilitiesOf(ctx)?.extensions;
151
+ return isObject(extensions) && extensions[TASKS_EXTENSION] !== undefined;
152
+ }
153
+ function isObject(value) {
154
+ return typeof value === "object" && value !== null && !Array.isArray(value);
155
+ }
156
+ /** The tasks extension, as a client declares it. */
157
+ const TASKS_CAPABILITY = {
158
+ extensions: { [TASKS_EXTENSION]: {} },
159
+ };
160
+ /**
161
+ * What each task tool needs the client to have declared: the tasks
162
+ * extension, to follow the handle, and the capability its task asks for
163
+ * input with. The SDK checks the input requests a tool returns itself, but
164
+ * not the ones a task carries in its status, so they are checked here.
165
+ */
166
+ const TASK_TOOL_REQUIREMENTS = {
167
+ "simulate-research-query": (ctx) => missingTasks(ctx),
168
+ "trigger-sampling-request-async": (ctx) => merged(missingTasks(ctx), clientCapabilitiesOf(ctx)?.sampling === undefined
169
+ ? { sampling: {} }
170
+ : undefined),
171
+ "trigger-elicitation-request-async": (ctx) => merged(missingTasks(ctx), clientSupportsFormElicitation(ctx)
172
+ ? undefined
173
+ : { elicitation: { form: {} } }),
174
+ };
175
+ /** The tasks extension, if this request's client did not declare it. */
176
+ function missingTasks(ctx) {
177
+ return clientSupportsTasks(ctx) ? undefined : TASKS_CAPABILITY;
178
+ }
179
+ /** Both sets of missing capabilities, or undefined when neither is. */
180
+ function merged(a, b) {
181
+ return a || b ? { ...a, ...b } : undefined;
182
+ }
183
+ /** The -32021 error naming the capabilities the client did not declare. */
184
+ function missingCapabilities(requiredCapabilities) {
185
+ return new MissingRequiredClientCapabilityError({ requiredCapabilities }, `Missing required client capability: ${Object.keys(requiredCapabilities).join(", ")}`);
186
+ }
187
+ /**
188
+ * Refuse a call to a task tool from a client that did not declare what the
189
+ * tool needs, with the JSON-RPC error -32021 naming it, as the extension
190
+ * requires: such a client cannot be served without a task handle.
191
+ *
192
+ * `McpServer` reports anything a tool handler throws as an `isError` tool
193
+ * result, so the check cannot live in the tools. Instead it wraps the
194
+ * `tools/call` handler `McpServer` installs, which the SDK then runs behind
195
+ * its own era checks, so the error reaches the client as an error. Call this
196
+ * before the first tool is registered, on a server constructed without a
197
+ * `tools` capability: `McpServer` installs the handler at the first
198
+ * registration then, or in its constructor when `tools` is declared.
199
+ *
200
+ * @param {McpServer} server - The 2026-07-28 server whose task tools to guard.
201
+ */
202
+ export function guardTaskTools(server) {
203
+ const lowLevel = server.server;
204
+ const setRequestHandler = lowLevel.setRequestHandler.bind(lowLevel);
205
+ // The SDK's overloads cannot be restated for a wrapper; this one only
206
+ // inspects the arguments and passes them through unchanged.
207
+ lowLevel.setRequestHandler = ((...args) => {
208
+ const handler = args.at(-1);
209
+ if (args[0] === "tools/call" && typeof handler === "function") {
210
+ args[args.length - 1] = (request, ctx) => {
211
+ const missing = TASK_TOOL_REQUIREMENTS[request.params.name]?.(ctx);
212
+ if (missing)
213
+ throw missingCapabilities(missing);
214
+ return handler(request, ctx);
215
+ };
216
+ }
217
+ return setRequestHandler(...args);
218
+ });
219
+ }
220
+ /** Refuse a tasks/* request from a client without the extension (-32021). */
221
+ function requireTasks(ctx) {
222
+ const missing = missingTasks(ctx);
223
+ if (missing)
224
+ throw missingCapabilities(missing);
225
+ }
226
+ /** Forget every task. For tests. */
227
+ export function clearTasks() {
228
+ tasks.clear();
229
+ }
230
+ const TaskIdParams = z.object({
231
+ taskId: z.string().describe("The task identifier"),
232
+ });
233
+ const TaskResult = z.looseObject({});
234
+ const EmptyResult = z.object({});
235
+ /**
236
+ * Serve the extension's methods on a 2026-07-28 server: `tasks/get`,
237
+ * `tasks/update` and `tasks/cancel`. A request from a client that does not
238
+ * declare the extension is refused with -32021. An unknown or expired task
239
+ * id is refused with -32602 (invalid params). A cancellation is acknowledged
240
+ * whatever the task's status, and changes only a task still running. An update's answers to requests that are not outstanding are
241
+ * ignored. Each input request a task makes has a key of its own, never reused
242
+ * once answered (the extension requires it), so a re-asked request gets a
243
+ * new key.
244
+ *
245
+ * @param {McpServer} server - The 2026-07-28 server to serve them on.
246
+ */
247
+ export function registerTasksExtension(server) {
248
+ server.server.setRequestHandler("tasks/get", { params: TaskIdParams, result: TaskResult }, async ({ taskId }, ctx) => {
249
+ requireTasks(ctx);
250
+ const now = Date.now();
251
+ return describe(find(taskId, now), now);
252
+ });
253
+ server.server.setRequestHandler("tasks/update", { params: TaskIdParams, result: EmptyResult }, async ({ taskId }, ctx) => {
254
+ requireTasks(ctx);
255
+ // The SDK lifts `inputResponses` out of the params of every request
256
+ // (it is a reserved retry field on 2026-07-28) into the context. The
257
+ // extension requires it, so a request without it is malformed.
258
+ const inputResponses = ctx.mcpReq.inputResponses;
259
+ if (inputResponses === undefined) {
260
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Invalid params for tasks/update: inputResponses is required");
261
+ }
262
+ const now = Date.now();
263
+ const task = find(taskId, now);
264
+ const state = stateOf(task, now);
265
+ // Only answers to requests outstanding now are passed on. The rest (a
266
+ // key never issued, one already answered, or any answer to a task not
267
+ // waiting for input) are ignored, as the extension asks, so a client
268
+ // that resends or batches responses is not failed for it.
269
+ const outstanding = state.status === "input_required"
270
+ ? Object.keys(state.inputRequests)
271
+ : [];
272
+ const answered = Object.fromEntries(Object.entries(inputResponses).filter(([key]) => outstanding.includes(key)));
273
+ const size = JSON.stringify(answered).length;
274
+ if (size > MAX_ANSWER_BYTES) {
275
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid params for tasks/update: the answers are ${size} bytes, over the ${MAX_ANSWER_BYTES}-byte limit; the task is unchanged`);
276
+ }
277
+ if (Object.keys(answered).length > 0) {
278
+ task.behavior.receive(answered, now);
279
+ }
280
+ return {};
281
+ });
282
+ server.server.setRequestHandler("tasks/cancel", { params: TaskIdParams, result: EmptyResult }, async ({ taskId }, ctx) => {
283
+ requireTasks(ctx);
284
+ const now = Date.now();
285
+ const task = find(taskId, now);
286
+ // Cancellation is cooperative: the request is acknowledged whatever
287
+ // the task's status, and a task that has already finished stays as it
288
+ // ended.
289
+ const { status } = stateOf(task, now);
290
+ if (status !== "completed" && status !== "cancelled") {
291
+ task.cancelledAt = now;
292
+ }
293
+ return {};
294
+ });
295
+ }
@@ -0,0 +1,35 @@
1
+ import { z } from "zod";
2
+ // Tool input schema
3
+ export const EchoSchema = z.object({
4
+ message: z.string().describe("Message to echo"),
5
+ });
6
+ // Tool configuration
7
+ const name = "echo";
8
+ const config = {
9
+ title: "Echo Tool",
10
+ description: "Echoes back the input string",
11
+ inputSchema: EchoSchema,
12
+ annotations: {
13
+ readOnlyHint: true,
14
+ destructiveHint: false,
15
+ idempotentHint: true,
16
+ openWorldHint: false,
17
+ },
18
+ };
19
+ /**
20
+ * Registers the 'echo' tool.
21
+ *
22
+ * The registered tool validates input arguments using the EchoSchema and
23
+ * returns a response that echoes the message provided in the arguments.
24
+ *
25
+ * @param {McpServer} server - The McpServer instance where the tool will be registered.
26
+ * @returns {void}
27
+ */
28
+ export const registerEchoTool = (server) => {
29
+ server.registerTool(name, config, async (args) => {
30
+ const validatedArgs = EchoSchema.parse(args);
31
+ return {
32
+ content: [{ type: "text", text: `Echo: ${validatedArgs.message}` }],
33
+ };
34
+ });
35
+ };
@@ -0,0 +1,89 @@
1
+ import { z } from "zod";
2
+ import { MCP_TINY_IMAGE } from "./get-tiny-image.js";
3
+ // Tool input schema
4
+ const GetAnnotatedMessageSchema = z.object({
5
+ messageType: z
6
+ .enum(["error", "success", "debug"])
7
+ .describe("Type of message to demonstrate different annotation patterns"),
8
+ includeImage: z
9
+ .boolean()
10
+ .default(false)
11
+ .describe("Whether to include an example image"),
12
+ });
13
+ // Tool configuration
14
+ const name = "get-annotated-message";
15
+ const config = {
16
+ title: "Get Annotated Message Tool",
17
+ description: "Demonstrates how annotations can be used to provide metadata about content.",
18
+ inputSchema: GetAnnotatedMessageSchema,
19
+ annotations: {
20
+ readOnlyHint: true, // This tool only returns data, no side effects
21
+ destructiveHint: false, // Does not delete or modify anything
22
+ idempotentHint: true, // Same input always produces same output
23
+ openWorldHint: false, // Does not interact with external systems
24
+ },
25
+ };
26
+ /**
27
+ * Registers the 'get-annotated-message' tool.
28
+ *
29
+ * The registered tool generates and sends messages with specific types, such as error,
30
+ * success, or debug, carrying associated annotations like priority level and intended
31
+ * audience.
32
+ *
33
+ * The response will have annotations and optionally contain an annotated image.
34
+ *
35
+ * @function
36
+ * @param {McpServer} server - The McpServer instance where the tool will be registered.
37
+ */
38
+ export const registerGetAnnotatedMessageTool = (server) => {
39
+ server.registerTool(name, config, async (args) => {
40
+ const { messageType, includeImage } = GetAnnotatedMessageSchema.parse(args);
41
+ const content = [];
42
+ // Main message with different priorities/audiences based on type
43
+ if (messageType === "error") {
44
+ content.push({
45
+ type: "text",
46
+ text: "Error: Operation failed",
47
+ annotations: {
48
+ priority: 1.0, // Errors are highest priority
49
+ audience: ["user", "assistant"], // Both need to know about errors
50
+ },
51
+ });
52
+ }
53
+ else if (messageType === "success") {
54
+ content.push({
55
+ type: "text",
56
+ text: "Operation completed successfully",
57
+ annotations: {
58
+ priority: 0.7, // Success messages are important but not critical
59
+ audience: ["user"], // Success mainly for user consumption
60
+ },
61
+ });
62
+ /* v8 ignore start -- the input schema's enum admits only error, success and debug, so the debug test is never false */
63
+ }
64
+ else if (messageType === "debug") {
65
+ content.push({
66
+ type: "text",
67
+ text: "Debug: Cache hit ratio 0.95, latency 150ms",
68
+ annotations: {
69
+ priority: 0.3, // Debug info is low priority
70
+ audience: ["assistant"], // Technical details for assistant
71
+ },
72
+ });
73
+ }
74
+ /* v8 ignore stop */
75
+ // Optional image with its own annotations
76
+ if (includeImage) {
77
+ content.push({
78
+ type: "image",
79
+ data: MCP_TINY_IMAGE,
80
+ mimeType: "image/png",
81
+ annotations: {
82
+ priority: 0.5,
83
+ audience: ["user"], // Images primarily for user visualization
84
+ },
85
+ });
86
+ }
87
+ return { content };
88
+ });
89
+ };
@@ -0,0 +1,34 @@
1
+ // Tool configuration
2
+ const name = "get-env";
3
+ const config = {
4
+ title: "Print Environment Tool",
5
+ description: "Returns all environment variables, helpful for debugging MCP server configuration",
6
+ inputSchema: {},
7
+ annotations: {
8
+ readOnlyHint: true,
9
+ destructiveHint: false,
10
+ idempotentHint: true,
11
+ openWorldHint: false,
12
+ },
13
+ };
14
+ /**
15
+ * Registers the 'get-env' tool.
16
+ *
17
+ * The registered tool Retrieves and returns the environment variables
18
+ * of the current process as a JSON-formatted string encapsulated in a text response.
19
+ *
20
+ * @param {McpServer} server - The McpServer instance where the tool will be registered.
21
+ * @returns {void}
22
+ */
23
+ export const registerGetEnvTool = (server) => {
24
+ server.registerTool(name, config, async () => {
25
+ return {
26
+ content: [
27
+ {
28
+ type: "text",
29
+ text: JSON.stringify(process.env, null, 2),
30
+ },
31
+ ],
32
+ };
33
+ });
34
+ };
@@ -0,0 +1,95 @@
1
+ // The `get-header-params` tool: demonstrates two 2026-07-28 tool-definition
2
+ // features (#4852).
3
+ //
4
+ // - Its `inputSchema` and `outputSchema` are plain JSON Schema 2020-12
5
+ // documents (`$schema` named), passed through `fromJsonSchema` rather than
6
+ // built from Zod, and validated by the SDK's JSON Schema validator.
7
+ // - Its `region` argument carries `x-mcp-header: "Region"`. Over Streamable
8
+ // HTTP a 2026-07-28 client mirrors that argument into an
9
+ // `Mcp-Param-Region` request header, so infrastructure in front of the
10
+ // server (a load balancer, a gateway) can route on it without reading the
11
+ // body, and the server rejects a call whose header is missing or disagrees
12
+ // with the body (-32020). The tool reports the header it was sent, which is
13
+ // null on stdio and for a 2025-era client, which mirrors nothing.
14
+ import { fromJsonSchema, } from "@modelcontextprotocol/server";
15
+ /**
16
+ * The keyword that asks a 2026-07-28 client to mirror an argument into the
17
+ * `Mcp-Param-<value>` header (SEP-2243). It is an extension keyword, so the
18
+ * JSON Schema type has no member for it; it is spread into the property.
19
+ */
20
+ const mirroredInHeader = { "x-mcp-header": "Region" };
21
+ /** The input: a region, mirrored into a header, and an optional count. */
22
+ const inputSchema = {
23
+ $schema: "https://json-schema.org/draft/2020-12/schema",
24
+ type: "object",
25
+ properties: {
26
+ region: {
27
+ type: "string",
28
+ description: "A region name, e.g. eu-west. Mirrored into the Mcp-Param-Region HTTP header.",
29
+ ...mirroredInHeader,
30
+ },
31
+ repeat: {
32
+ type: "integer",
33
+ minimum: 1,
34
+ maximum: 3,
35
+ default: 1,
36
+ description: "How many times to repeat the region in the result (1-3)",
37
+ },
38
+ },
39
+ required: ["region"],
40
+ additionalProperties: false,
41
+ };
42
+ /** The output: the region from the body, and the header that carried it. */
43
+ const outputSchema = {
44
+ $schema: "https://json-schema.org/draft/2020-12/schema",
45
+ type: "object",
46
+ properties: {
47
+ region: { type: "string" },
48
+ // Nullable as anyOf with one type per branch, not `type: ["string",
49
+ // "null"]`: some clients map tool schemas onto a dialect that allows a
50
+ // single `type` per property (the OpenAPI subset of Gemini function
51
+ // declarations, for one) and reject or drop the array form.
52
+ regionHeader: {
53
+ anyOf: [{ type: "string" }, { type: "null" }],
54
+ description: "The Mcp-Param-Region header the request carried, if any",
55
+ },
56
+ repeated: { type: "array", items: { type: "string" } },
57
+ },
58
+ required: ["region", "regionHeader", "repeated"],
59
+ additionalProperties: false,
60
+ };
61
+ // Tool configuration
62
+ const name = "get-header-params";
63
+ const config = {
64
+ title: "Get Header Params Tool",
65
+ description: "Returns its region argument and the Mcp-Param-Region HTTP header it arrived in. Demonstrates " +
66
+ "x-mcp-header (a 2026-07-28 Streamable HTTP client mirrors the argument into the header) and " +
67
+ "JSON Schema 2020-12 input and output schemas.",
68
+ inputSchema: fromJsonSchema(inputSchema),
69
+ outputSchema: fromJsonSchema(outputSchema),
70
+ annotations: {
71
+ readOnlyHint: true,
72
+ destructiveHint: false,
73
+ idempotentHint: true,
74
+ openWorldHint: false,
75
+ },
76
+ };
77
+ /**
78
+ * Registers the 'get-header-params' tool.
79
+ *
80
+ * @param {McpServer} server - The McpServer instance where the tool will be registered.
81
+ */
82
+ export const registerGetHeaderParamsTool = (server) => {
83
+ server.registerTool(name, config, async ({ region, repeat }, ctx) => {
84
+ const regionHeader = ctx.http?.req?.headers.get("mcp-param-region") ?? null;
85
+ const structuredContent = {
86
+ region,
87
+ regionHeader,
88
+ repeated: Array.from({ length: repeat ?? 1 }, () => region),
89
+ };
90
+ return {
91
+ content: [{ type: "text", text: JSON.stringify(structuredContent) }],
92
+ structuredContent,
93
+ };
94
+ });
95
+ };
@@ -0,0 +1,68 @@
1
+ import { z } from "zod";
2
+ import { textResource, textResourceUri, blobResourceUri, blobResource, } from "../resources/templates.js";
3
+ // Tool input schema
4
+ const GetResourceLinksSchema = z.object({
5
+ count: z
6
+ .number()
7
+ .min(1)
8
+ .max(10)
9
+ .default(3)
10
+ .describe("Number of resource links to return (1-10)"),
11
+ });
12
+ // Tool configuration
13
+ const name = "get-resource-links";
14
+ const config = {
15
+ title: "Get Resource Links Tool",
16
+ description: "Returns up to ten resource links that reference different types of resources",
17
+ inputSchema: GetResourceLinksSchema,
18
+ annotations: {
19
+ readOnlyHint: true,
20
+ destructiveHint: false,
21
+ idempotentHint: true,
22
+ openWorldHint: false,
23
+ },
24
+ };
25
+ /**
26
+ * Registers the 'get-resource-reference' tool.
27
+ *
28
+ * The registered tool retrieves a specified number of resource links and their metadata.
29
+ * Resource links are dynamically generated as either text or binary blob resources,
30
+ * based on their ID being even or odd.
31
+
32
+ * The response contains a "text" introductory block and multiple "resource_link" blocks.
33
+ *
34
+ * @param {McpServer} server - The McpServer instance where the tool will be registered.
35
+ */
36
+ export const registerGetResourceLinksTool = (server) => {
37
+ server.registerTool(name, config, async (args) => {
38
+ const { count } = GetResourceLinksSchema.parse(args);
39
+ // Add intro text content block
40
+ const content = [];
41
+ content.push({
42
+ type: "text",
43
+ text: `Here are ${count} resource links to resources available in this server:`,
44
+ });
45
+ // Create resource link content blocks
46
+ for (let resourceId = 1; resourceId <= count; resourceId++) {
47
+ // Get resource uri for text or blob resource based on odd/even resourceId
48
+ const isOdd = resourceId % 2 === 0;
49
+ const uri = isOdd
50
+ ? textResourceUri(resourceId)
51
+ : blobResourceUri(resourceId);
52
+ // Get resource based on the resource type
53
+ const resource = isOdd
54
+ ? textResource(uri, resourceId)
55
+ : blobResource(uri, resourceId);
56
+ content.push({
57
+ type: "resource_link",
58
+ uri: resource.uri,
59
+ name: `${isOdd ? "Text" : "Blob"} Resource ${resourceId}`,
60
+ description: `Resource ${resourceId}: ${resource.mimeType === "text/plain"
61
+ ? "plaintext resource"
62
+ : "binary blob resource"}`,
63
+ mimeType: resource.mimeType,
64
+ });
65
+ }
66
+ return { content };
67
+ });
68
+ };