@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,246 @@
1
+ # Everything Server - Project Structure
2
+
3
+ **[Architecture](architecture.md)
4
+ | Project Structure
5
+ | [Startup Process](startup.md)
6
+ | [Server Features](features.md)
7
+ | [Extension Points](extension.md)
8
+ | [How It Works](how-it-works.md)**
9
+
10
+ ```
11
+ src/everything
12
+ ├── index.ts
13
+ ├── AGENTS.md
14
+ ├── package.json
15
+ ├── docs
16
+ │ ├── architecture.md
17
+ │ ├── extension.md
18
+ │ ├── features.md
19
+ │ ├── how-it-works.md
20
+ │ ├── instructions.md
21
+ │ ├── startup.md
22
+ │ └── structure.md
23
+ ├── prompts
24
+ │ ├── index.ts
25
+ │ ├── args.ts
26
+ │ ├── completions.ts
27
+ │ ├── simple.ts
28
+ │ └── resource.ts
29
+ ├── resources
30
+ │ ├── index.ts
31
+ │ ├── files.ts
32
+ │ ├── minted.ts
33
+ │ ├── session.ts
34
+ │ ├── subscriptions.ts
35
+ │ └── templates.ts
36
+ ├── server
37
+ │ ├── index.ts
38
+ │ ├── context.ts
39
+ │ ├── logging.ts
40
+ │ ├── roots.ts
41
+ │ └── tasks.ts
42
+ ├── tools
43
+ │ ├── index.ts
44
+ │ ├── echo.ts
45
+ │ ├── get-annotated-message.ts
46
+ │ ├── get-env.ts
47
+ │ ├── get-header-params.ts
48
+ │ ├── get-resource-links.ts
49
+ │ ├── get-resource-reference.ts
50
+ │ ├── get-roots-list.ts
51
+ │ ├── get-structured-content.ts
52
+ │ ├── get-sum.ts
53
+ │ ├── get-tiny-image.ts
54
+ │ ├── gzip-file-as-resource.ts
55
+ │ ├── simulate-research-query.ts
56
+ │ ├── toggle-simulated-logging.ts
57
+ │ ├── toggle-subscriber-updates.ts
58
+ │ ├── trigger-elicitation-request-async.ts
59
+ │ ├── trigger-elicitation-request.ts
60
+ │ ├── trigger-list-changed.ts
61
+ │ ├── trigger-log-messages.ts
62
+ │ ├── trigger-long-running-operation.ts
63
+ │ ├── trigger-multi-step-elicitation.ts
64
+ │ ├── trigger-resource-update.ts
65
+ │ ├── trigger-sampling-request-async.ts
66
+ │ ├── trigger-sampling-request.ts
67
+ │ └── trigger-url-elicitation.ts
68
+ └── transports
69
+ ├── in-memory-event-store.ts
70
+ ├── listen.ts
71
+ ├── sse.ts
72
+ ├── stdio.ts
73
+ └── streamableHttp.ts
74
+ ```
75
+
76
+ # Project Contents
77
+
78
+ ## `src/everything`:
79
+
80
+ ### `index.ts`
81
+
82
+ - CLI entry point that selects and runs a specific transport module based on the first CLI argument: `stdio`, `sse`, or `streamableHttp`.
83
+
84
+ ### `AGENTS.md`
85
+
86
+ - Directions for Agents/LLMs explaining coding guidelines and how to appropriately extend the server.
87
+
88
+ ### `package.json`
89
+
90
+ - Package metadata and scripts:
91
+ - `build`: TypeScript compile to `dist/`, copies `docs/` into `dist/` and marks the compiled entry scripts as executable.
92
+ - `start:stdio`, `start:sse`, `start:streamableHttp`: Run built transports from `dist/`.
93
+ - Declares dependencies on the TypeScript SDK v2 packages (`@modelcontextprotocol/server`, `@modelcontextprotocol/node`, `@modelcontextprotocol/server-legacy`), `express`, `cors`, `zod`, etc.
94
+
95
+ ### `docs/`
96
+
97
+ - `architecture.md`
98
+ - Describes the server architecture, including transport layers, session initialization, and primitive registration.
99
+ - `extension.md`
100
+ - Explains how to extend the server with new tools, prompts, resources, or transports.
101
+ - `features.md`
102
+ - A comprehensive reference listing all implemented prompts, resources, tools, and protocol behaviors.
103
+ - `how-it-works.md`
104
+ - Explains how SSE and Streamable HTTP transports are set up and how sessions are managed.
105
+ - `instructions.md`
106
+ - Human‑readable instructions intended to be passed to the client/LLM as guidance on server use. Loaded by the server at startup and returned in the initialize exchange.
107
+ - `startup.md`
108
+ - Describes the server startup sequence, environment checks, and initialization.
109
+ - `structure.md`
110
+ - This document.
111
+
112
+ ### `prompts/`
113
+
114
+ - `index.ts`
115
+ - `registerPrompts(server)` orchestrator; delegates to prompt factory/registration methods from in individual prompt files.
116
+ - `simple.ts`
117
+ - Registers `simple-prompt`: a prompt with no arguments that returns a single user message.
118
+ - `args.ts`
119
+ - Registers `args-prompt`: a prompt with two arguments (`city` required, `state` optional) used to compose a message.
120
+ - `completions.ts`
121
+ - Registers `completable-prompt`: a prompt whose arguments support server-driven completions using the SDK’s `completable(...)` helper (e.g., completing `department` and context-aware `name`).
122
+ - `resource.ts`
123
+ - Exposes `registerEmbeddedResourcePrompt(server)` which registers `resource-prompt` — a prompt that accepts `resourceType` ("Text" or "Blob") and `resourceId` (integer), and embeds a dynamically generated resource of the requested type within the returned messages. Internally reuses helpers from `resources/templates.ts`.
124
+
125
+ ### `resources/`
126
+
127
+ - `index.ts`
128
+ - `registerResources(server, context)` orchestrator; delegates to resource factory/registration methods from individual resource files, adding the minted-resource template on 2026-07-28.
129
+ - `templates.ts`
130
+ - Registers two dynamic, template‑driven resources using `ResourceTemplate`:
131
+ - Text: `demo://resource/dynamic/text/{index}` (MIME: `text/plain`)
132
+ - Blob: `demo://resource/dynamic/blob/{index}` (MIME: `application/octet-stream`, Base64 payload)
133
+ - The `{index}` path variable must be a finite positive integer; any other is not found (`-32602`). Content is generated on demand with a timestamp.
134
+ - Exposes helpers `textResource(uri, index)`, `textResourceUri(index)`, `blobResource(uri, index)`, and `blobResourceUri(index)` so other modules can construct and embed dynamic resources directly (e.g., from prompts).
135
+ - `files.ts`
136
+ - Registers static file-based resources for each file in the `docs/` folder.
137
+ - URIs follow the pattern: `demo://resource/static/document/<filename>`.
138
+ - Serves markdown files as `text/markdown`, `.txt` as `text/plain`, `.json` as `application/json`, others default to `text/plain`.
139
+ - Gives each a one-hour public cache hint for 2026-07-28 reads.
140
+ - `minted.ts`
141
+ - 2026-07-28: stores resources tools create under server-minted URIs (`demo://resource/minted/<id>/<name>`) for ten minutes, process-wide, and serves them through one template.
142
+ - `session.ts`
143
+ - 2025 era: registers resources tools create on the session's server instance (`demo://resource/session/<name>`).
144
+ - `subscriptions.ts`
145
+ - 2025 era: the `resources/subscribe` and `resources/unsubscribe` handlers, and the timed updates `toggle-subscriber-updates` drives.
146
+
147
+ ### `server/`
148
+
149
+ - `index.ts`
150
+ - Server factory that creates an `McpServer` for a protocol era (`createServer({ era, publish })`) with declared capabilities, cache hints and the `requestState` verifier, loads server instructions, and registers tools, prompts, and resources for that era.
151
+ - On the 2025 era, sets resource subscription handlers via `setSubscriptionHandlers(server, subscribed)` and registers the capability-gated tools after `initialize`.
152
+ - Exposes `{ server, cleanup }` to the chosen transport. Cleanup stops any running intervals in the server when the connection ends.
153
+ - `context.ts`
154
+ - The per-instance context features receive: the era, the change publisher, the 2025-era subscriptions and a cleanup registry.
155
+ - `logging.ts`
156
+ - Implements simulated logging (2025 era). Periodically sends randomized log messages at various levels to the connected client. Started/stopped on demand via a dedicated tool.
157
+ - `roots.ts`
158
+ - 2025 era: syncs the client's roots after `initialize` and on `roots/list_changed`, reporting each answer as a log message.
159
+ - `tasks.ts`
160
+ - 2026-07-28: the server side of the tasks extension (`tasks/get`, `tasks/update`, `tasks/cancel`) and the process-wide task store the task tools create tasks in.
161
+
162
+ ### `tools/`
163
+
164
+ - `index.ts`
165
+ - Registration orchestrators, by era: `registerTools(server, context)` (both), `registerLegacyTools` and `registerConditionalTools` (2025 era), `registerModernTools` (2026-07-28). Each delegates to the registration methods in individual tool files.
166
+ - `echo.ts`
167
+ - Registers an `echo` tool that takes a message and returns `Echo: {message}`.
168
+ - `get-annotated-message.ts`
169
+ - Registers a `get-annotated-message` tool which demonstrates content-level annotations. Emits a primary `text` message with content `annotations` (`priority`, `audience`) that vary by `messageType` (`"error" | "success" | "debug"`), and optionally includes an annotated `image` (tiny PNG) when `includeImage` is true. All tools in this server include tool-level annotations (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`).
170
+ - `get-env.ts`
171
+ - Registers a `get-env` tool that returns the current process environment variables as formatted JSON text; useful for debugging configuration.
172
+ - `get-header-params.ts`
173
+ - Registers a `get-header-params` tool with JSON Schema 2020-12 input and output schemas whose `region` argument carries `x-mcp-header`; returns the argument and the `Mcp-Param-Region` header it arrived in.
174
+ - `get-resource-links.ts`
175
+ - Registers a `get-resource-links` tool that returns an intro `text` block followed by multiple `resource_link` items.
176
+ - `get-resource-reference.ts`
177
+ - Registers a `get-resource-reference` tool that returns a reference for a selected dynamic resource.
178
+ - `get-roots-list.ts`
179
+ - Registers a `get-roots-list` tool that asks the client for its roots with a multi-round-trip request and lists them.
180
+ - `gzip-file-as-resource.ts`
181
+ - Registers a `gzip-file-as-resource` tool that fetches content from a URL or data URI, compresses it, and then either:
182
+ - returns a `resource_link` (default) to a resource it can read later, or
183
+ - returns an inline `resource` with the gzipped data.
184
+ - The linked resource is a per-session resource at `demo://resource/session/<name>` (`resources/session.ts`) for a 2025-era client, and a minted one at `demo://resource/minted/<id>/<name>` (`resources/minted.ts`) for a 2026-07-28 client, with `mimeType: application/gzip`.
185
+ - Environment controls:
186
+ - `GZIP_MAX_FETCH_SIZE` (bytes, default 10 MiB)
187
+ - `GZIP_MAX_FETCH_TIME_MILLIS` (ms, default 30000)
188
+ - `GZIP_ALLOWED_DOMAINS` (comma-separated allowlist; empty means all domains allowed)
189
+ - `simulate-research-query.ts`
190
+ - 2026-07-28: registers a `simulate-research-query` tool that runs as a task on the tasks extension, through four timed stages, pausing at `input_required` for a clarification on an ambiguous topic.
191
+ - `trigger-elicitation-request.ts`
192
+ - Registers a `trigger-elicitation-request` tool that asks for a form with a multi-round-trip request and returns the elicitation result.
193
+ - `trigger-elicitation-request-async.ts`
194
+ - 2026-07-28: registers a `trigger-elicitation-request-async` tool that runs as a task waiting in `input_required` for a form elicitation.
195
+ - `trigger-list-changed.ts`
196
+ - Registers a `trigger-list-changed` tool that publishes a tools, prompts or resources list change.
197
+ - `trigger-log-messages.ts`
198
+ - Registers a `trigger-log-messages` tool that sends one log message per level, filtered by the request's or session's log level.
199
+ - `trigger-multi-step-elicitation.ts`
200
+ - Registers a `trigger-multi-step-elicitation` tool that asks two questions in sequence, carrying the first answer in a signed `requestState`.
201
+ - `trigger-resource-update.ts`
202
+ - Registers a `trigger-resource-update` tool that publishes a `notifications/resources/updated` for a URI.
203
+ - `trigger-sampling-request-async.ts`
204
+ - 2026-07-28: registers a `trigger-sampling-request-async` tool that runs as a task waiting in `input_required` for a sampling request.
205
+ - `trigger-url-elicitation.ts`
206
+ - On 2026-07-28, registers a `trigger-url-elicitation` tool that returns its URL elicitation in-band (`input_required`). On the 2025 era, it 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.
207
+ - `trigger-sampling-request.ts`
208
+ - Registers a `trigger-sampling-request` tool that asks the client's LLM for a completion with a multi-round-trip request and returns the sampling result.
209
+ - `get-structured-content.ts`
210
+ - Registers a `get-structured-content` tool that demonstrates structuredContent block responses.
211
+ - `get-sum.ts`
212
+ - Registers a `get-sum` tool with a Zod input schema that sums two numbers `a` and `b` and returns the result.
213
+ - `get-tiny-image.ts`
214
+ - Registers a `get-tiny-image` tool, which returns a tiny PNG MCP logo as an `image` content item, along with surrounding descriptive `text` items.
215
+ - `trigger-long-running-operation.ts`
216
+ - Registers a `trigger-long-running-operation` tool that simulates a long-running task over a specified `duration` (seconds) and number of `steps`; emits `notifications/progress` updates when the client supplies a `progressToken`.
217
+ - `toggle-simulated-logging.ts`
218
+ - 2025 era: registers a `toggle-simulated-logging` tool, which starts or stops simulated logging for the connection.
219
+ - `toggle-subscriber-updates.ts`
220
+ - 2025 era: registers a `toggle-subscriber-updates` tool, which starts or stops simulated resource subscription updates for the connection.
221
+
222
+ ### `transports/`
223
+
224
+ - `in-memory-event-store.ts`
225
+ - `InMemoryEventStore`: the Streamable HTTP transport's event store for resumability. Replays only the events of the stream a `Last-Event-ID` belongs to, and reports an unknown event ID as having no stream, so the SDK refuses the resume.
226
+ - `listen.ts`
227
+ - `listenOrExit(app, port, listeningMessage)`: binds an Express app to its port for both HTTP transports.
228
+ - Prints the listening message only once the port is bound; on a bind failure (such as a port already in use) prints why and exits non-zero.
229
+ - `stdio.ts`
230
+ - Serves `createServer({ era })` over a `StdioServerTransport` with the SDK's `serveStdio`, which picks the connection's era from the client's first message.
231
+ - Runs each instance's `cleanup()` when it closes, and handles `SIGINT` to close cleanly.
232
+ - `sse.ts`
233
+ - Deprecated; 2025-era clients only. Warns on start.
234
+ - Express server exposing:
235
+ - `GET /sse` to establish an SSE connection per session.
236
+ - `POST /message` for client messages.
237
+ - Manages multiple connected clients via a transport map.
238
+ - Starts an `SSEServerTransport` (from the frozen `@modelcontextprotocol/server-legacy/sse` bridge), created the server via `createServer()`, and connects it to a new transport.
239
+ - On server disconnect, calls `cleanup()` to remove any live intervals.
240
+ - `streamableHttp.ts`
241
+ - Express server exposing a single `/mcp` endpoint for both protocol eras.
242
+ - 2026-07-28: a session-less POST carrying the per-request envelope (classified by the SDK's `isLegacyRequest`) is served by `createMcpHandler`, a fresh server per request, publishing change notifications on the handler's bus.
243
+ - 2025 era: POST (JSON‑RPC), GET (SSE stream), and DELETE (session termination) using `NodeStreamableHTTPServerTransport` from `@modelcontextprotocol/node`.
244
+ - Uses an `InMemoryEventStore` for resumable sessions and tracks transports by `sessionId`.
245
+ - Answers a request for an unknown or ended `Mcp-Session-Id` with `404 Not Found`, and closes every open session on `SIGINT`.
246
+ - Connects a fresh server instance on initialization POST and reuses the transport for subsequent requests.
package/dist/index.js CHANGED
@@ -1,18 +1,75 @@
1
1
  #!/usr/bin/env node
2
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
- import { createServer } from "./everything.js";
4
- async function main() {
5
- const transport = new StdioServerTransport();
6
- const { server, cleanup } = createServer();
7
- await server.connect(transport);
8
- // Cleanup on exit
9
- process.on("SIGINT", async () => {
10
- await cleanup();
11
- await server.close();
12
- process.exit(0);
13
- });
2
+ // The `mcp-server-everything` launcher: picks a transport from the first
3
+ // command-line argument (default `stdio`) and starts it.
4
+ //
5
+ // `run()` is exported and the start-up is guarded by `isEntryPoint()` (#4854),
6
+ // so a test can import this module and drive each branch in-process without
7
+ // the import itself starting a server on the test runner's stdio. Each
8
+ // transport module is still imported dynamically, so only the requested one
9
+ // initializes.
10
+ import { realpathSync } from "node:fs";
11
+ import { fileURLToPath } from "node:url";
12
+ /**
13
+ * Start the transport named `scriptName`, or print the usage and exit 1 for an
14
+ * unknown name.
15
+ */
16
+ export async function run(scriptName) {
17
+ try {
18
+ // Dynamically import only the requested module to prevent all modules from initializing
19
+ switch (scriptName) {
20
+ case "stdio": {
21
+ // Import and run the default server
22
+ const { startStdioServer } = await import("./transports/stdio.js");
23
+ await startStdioServer();
24
+ break;
25
+ }
26
+ case "sse": {
27
+ // Import and run the SSE server
28
+ const { startSseServer } = await import("./transports/sse.js");
29
+ startSseServer();
30
+ break;
31
+ }
32
+ case "streamableHttp": {
33
+ // Import and run the streamable HTTP server
34
+ const { startStreamableHttpServer } = await import("./transports/streamableHttp.js");
35
+ startStreamableHttpServer();
36
+ break;
37
+ }
38
+ default:
39
+ console.error(`-`.repeat(53));
40
+ console.error(` Everything Server Launcher`);
41
+ console.error(` Usage: node ./index.js [stdio|sse|streamableHttp]`);
42
+ console.error(` Default transport: stdio`);
43
+ console.error(`-`.repeat(53));
44
+ console.error(`Unknown transport: ${scriptName}`);
45
+ console.log("Available transports:");
46
+ console.log("- stdio");
47
+ console.log("- sse");
48
+ console.log("- streamableHttp");
49
+ process.exit(1);
50
+ }
51
+ }
52
+ catch (error) {
53
+ console.error("Error running script:", error);
54
+ process.exit(1);
55
+ }
56
+ }
57
+ /**
58
+ * Whether the module at `moduleUrl` is the script node was started with
59
+ * (`argv1`). Both sides are resolved through symlinks, because the npm `bin`
60
+ * shim that `npx` runs is a symlink to `dist/index.js`.
61
+ */
62
+ export function isEntryPoint(argv1, moduleUrl) {
63
+ if (!argv1)
64
+ return false;
65
+ try {
66
+ return realpathSync(argv1) === realpathSync(fileURLToPath(moduleUrl));
67
+ }
68
+ catch {
69
+ return false;
70
+ }
71
+ }
72
+ /* v8 ignore next -- true only when node runs this file as the binary; the boot smoke (scripts/smoke-servers.mjs) covers that path */
73
+ if (isEntryPoint(process.argv[1], import.meta.url)) {
74
+ await run(process.argv[2] || "stdio");
14
75
  }
15
- main().catch((error) => {
16
- console.error("Server error:", error);
17
- process.exit(1);
18
- });
@@ -0,0 +1,34 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Register a prompt with arguments
4
+ * - Two arguments, one required and one optional
5
+ * - Combines argument values in the returned prompt
6
+ *
7
+ * @param server
8
+ */
9
+ export const registerArgumentsPrompt = (server) => {
10
+ // Prompt arguments
11
+ const promptArgsSchema = z.object({
12
+ city: z.string().describe("Name of the city"),
13
+ state: z.string().describe("Name of the state").optional(),
14
+ });
15
+ // Register the prompt
16
+ server.registerPrompt("args-prompt", {
17
+ title: "Arguments Prompt",
18
+ description: "A prompt with two arguments, one required and one optional",
19
+ argsSchema: promptArgsSchema,
20
+ }, (args) => {
21
+ const location = `${args?.city}${args?.state ? `, ${args?.state}` : ""}`;
22
+ return {
23
+ messages: [
24
+ {
25
+ role: "user",
26
+ content: {
27
+ type: "text",
28
+ text: `What's weather in ${location}?`,
29
+ },
30
+ },
31
+ ],
32
+ };
33
+ });
34
+ };
@@ -0,0 +1,52 @@
1
+ import { z } from "zod";
2
+ import { completable } from "@modelcontextprotocol/server";
3
+ /**
4
+ * Register a prompt with completable arguments
5
+ * - Two required arguments, both with completion handlers
6
+ * - First argument value will be included in context for second argument
7
+ * - Allows second argument to depend on the first argument value
8
+ *
9
+ * @param server
10
+ */
11
+ export const registerPromptWithCompletions = (server) => {
12
+ // Prompt arguments
13
+ const promptArgsSchema = z.object({
14
+ department: completable(z.string().describe("Choose the department."), (value) => {
15
+ return ["Engineering", "Sales", "Marketing", "Support"].filter((d) => d.startsWith(value));
16
+ }),
17
+ name: completable(z
18
+ .string()
19
+ .describe("Choose a team member to lead the selected department."), (value, context) => {
20
+ const department = context?.arguments?.["department"];
21
+ if (department === "Engineering") {
22
+ return ["Alice", "Bob", "Charlie"].filter((n) => n.startsWith(value));
23
+ }
24
+ else if (department === "Sales") {
25
+ return ["David", "Eve", "Frank"].filter((n) => n.startsWith(value));
26
+ }
27
+ else if (department === "Marketing") {
28
+ return ["Grace", "Henry", "Iris"].filter((n) => n.startsWith(value));
29
+ }
30
+ else if (department === "Support") {
31
+ return ["John", "Kim", "Lee"].filter((n) => n.startsWith(value));
32
+ }
33
+ return [];
34
+ }),
35
+ });
36
+ // Register the prompt
37
+ server.registerPrompt("completable-prompt", {
38
+ title: "Team Management",
39
+ description: "First argument choice narrows values for second argument.",
40
+ argsSchema: promptArgsSchema,
41
+ }, ({ department, name }) => ({
42
+ messages: [
43
+ {
44
+ role: "user",
45
+ content: {
46
+ type: "text",
47
+ text: `Please promote ${name} to the head of the ${department} team.`,
48
+ },
49
+ },
50
+ ],
51
+ }));
52
+ };
@@ -0,0 +1,15 @@
1
+ import { registerSimplePrompt } from "./simple.js";
2
+ import { registerArgumentsPrompt } from "./args.js";
3
+ import { registerPromptWithCompletions } from "./completions.js";
4
+ import { registerEmbeddedResourcePrompt } from "./resource.js";
5
+ /**
6
+ * Register the prompts with the MCP server.
7
+ *
8
+ * @param server
9
+ */
10
+ export const registerPrompts = (server) => {
11
+ registerSimplePrompt(server);
12
+ registerArgumentsPrompt(server);
13
+ registerPromptWithCompletions(server);
14
+ registerEmbeddedResourcePrompt(server);
15
+ };
@@ -0,0 +1,61 @@
1
+ import { z } from "zod";
2
+ import { resourceTypeCompleter, resourceIdForPromptCompleter, } from "../resources/templates.js";
3
+ import { textResource, textResourceUri, blobResourceUri, blobResource, RESOURCE_TYPE_BLOB, RESOURCE_TYPE_TEXT, RESOURCE_TYPES, } from "../resources/templates.js";
4
+ /**
5
+ * Register a prompt with an embedded resource reference
6
+ * - Takes a resource type and id
7
+ * - Returns the corresponding dynamically created resource
8
+ *
9
+ * @param server
10
+ */
11
+ export const registerEmbeddedResourcePrompt = (server) => {
12
+ // Prompt arguments
13
+ const promptArgsSchema = z.object({
14
+ resourceType: resourceTypeCompleter,
15
+ resourceId: resourceIdForPromptCompleter,
16
+ });
17
+ // Register the prompt
18
+ server.registerPrompt("resource-prompt", {
19
+ title: "Resource Prompt",
20
+ description: "A prompt that includes an embedded resource reference",
21
+ argsSchema: promptArgsSchema,
22
+ }, (args) => {
23
+ // Validate resource type argument
24
+ const resourceType = args.resourceType;
25
+ if (!RESOURCE_TYPES.includes(resourceType)) {
26
+ throw new Error(`Invalid resourceType: ${args?.resourceType}. Must be ${RESOURCE_TYPE_TEXT} or ${RESOURCE_TYPE_BLOB}.`);
27
+ }
28
+ // Validate resourceId argument
29
+ const resourceId = Number(args?.resourceId);
30
+ if (!Number.isFinite(resourceId) ||
31
+ !Number.isInteger(resourceId) ||
32
+ resourceId < 1) {
33
+ throw new Error(`Invalid resourceId: ${args?.resourceId}. Must be a finite positive integer.`);
34
+ }
35
+ // Get resource based on the resource type
36
+ const uri = resourceType === RESOURCE_TYPE_TEXT
37
+ ? textResourceUri(resourceId)
38
+ : blobResourceUri(resourceId);
39
+ const resource = resourceType === RESOURCE_TYPE_TEXT
40
+ ? textResource(uri, resourceId)
41
+ : blobResource(uri, resourceId);
42
+ return {
43
+ messages: [
44
+ {
45
+ role: "user",
46
+ content: {
47
+ type: "text",
48
+ text: `This prompt includes the ${resourceType} resource with id: ${resourceId}. Please analyze the following resource:`,
49
+ },
50
+ },
51
+ {
52
+ role: "user",
53
+ content: {
54
+ type: "resource",
55
+ resource: resource,
56
+ },
57
+ },
58
+ ],
59
+ };
60
+ });
61
+ };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Register a simple prompt with no arguments
3
+ * - Returns the fixed text of the prompt with no modifications
4
+ *
5
+ * @param server
6
+ */
7
+ export const registerSimplePrompt = (server) => {
8
+ // Register the prompt
9
+ server.registerPrompt("simple-prompt", {
10
+ title: "Simple Prompt",
11
+ description: "A prompt with no arguments",
12
+ }, () => ({
13
+ messages: [
14
+ {
15
+ role: "user",
16
+ content: {
17
+ type: "text",
18
+ text: "This is a simple prompt without arguments.",
19
+ },
20
+ },
21
+ ],
22
+ }));
23
+ };
@@ -0,0 +1,91 @@
1
+ import { dirname, join } from "path";
2
+ import { fileURLToPath } from "url";
3
+ import { readdirSync, readFileSync, statSync } from "fs";
4
+ /** How long a client or shared cache may keep a static document. */
5
+ export const STATIC_DOCUMENT_CACHE_HINT = {
6
+ ttlMs: 60 * 60_000,
7
+ cacheScope: "public",
8
+ };
9
+ /**
10
+ * Register static file resources
11
+ * - Each file in src/everything/docs is exposed as an individual static resource
12
+ * - URIs follow the pattern: "demo://static/docs/<filename>"
13
+ * - Markdown (.md) files are served as mime type "text/markdown"
14
+ * - Text (.txt) files are served as mime type "text/plain"
15
+ * - JSON (.json) files are served as mime type "application/json"
16
+ *
17
+ * @param server
18
+ */
19
+ export const registerFileResources = (server) => {
20
+ // Read the entries in the docs directory
21
+ const __filename = fileURLToPath(import.meta.url);
22
+ const __dirname = dirname(__filename);
23
+ const docsDir = join(__dirname, "..", "docs");
24
+ let entries;
25
+ try {
26
+ entries = readdirSync(docsDir);
27
+ }
28
+ catch {
29
+ // If docs/ folder is missing or unreadable, just skip registration
30
+ return;
31
+ }
32
+ // Register each file as a static resource
33
+ for (const name of entries) {
34
+ // Only process files, not directories
35
+ const fullPath = join(docsDir, name);
36
+ try {
37
+ const st = statSync(fullPath);
38
+ if (!st.isFile())
39
+ continue;
40
+ }
41
+ catch {
42
+ continue;
43
+ }
44
+ // Prepare file resource info
45
+ const uri = `demo://resource/static/document/${encodeURIComponent(name)}`;
46
+ const mimeType = getMimeType(name);
47
+ const description = `Static document file exposed from /docs: ${name}`;
48
+ // Register file resource
49
+ server.registerResource(name, uri,
50
+ // A static document changes only when the server is upgraded, so any
51
+ // cache may keep it for an hour (2026-07-28 clients only; #4852).
52
+ { mimeType, description, cacheHint: STATIC_DOCUMENT_CACHE_HINT }, async (uri) => {
53
+ const text = readFileSafe(fullPath);
54
+ return {
55
+ contents: [
56
+ {
57
+ uri: uri.toString(),
58
+ mimeType,
59
+ text,
60
+ },
61
+ ],
62
+ };
63
+ });
64
+ }
65
+ };
66
+ /**
67
+ * Get the mimetype based on filename
68
+ * @param fileName
69
+ */
70
+ function getMimeType(fileName) {
71
+ const lower = fileName.toLowerCase();
72
+ if (lower.endsWith(".md") || lower.endsWith(".markdown"))
73
+ return "text/markdown";
74
+ if (lower.endsWith(".txt"))
75
+ return "text/plain";
76
+ if (lower.endsWith(".json"))
77
+ return "application/json";
78
+ return "text/plain";
79
+ }
80
+ /**
81
+ * Read a file or return an error message if it fails
82
+ * @param path
83
+ */
84
+ function readFileSafe(path) {
85
+ try {
86
+ return readFileSync(path, "utf-8");
87
+ }
88
+ catch (e) {
89
+ return `Error reading file: ${path}. ${e}`;
90
+ }
91
+ }
@@ -0,0 +1,38 @@
1
+ import { registerResourceTemplates } from "./templates.js";
2
+ import { registerFileResources } from "./files.js";
3
+ import { registerMintedResources } from "./minted.js";
4
+ import { fileURLToPath } from "url";
5
+ import { dirname, join } from "path";
6
+ import { readFileSync } from "fs";
7
+ /**
8
+ * Register the resources with the MCP server. A 2026-07-28 server also serves
9
+ * the resources tools mint for later reading (see minted.ts).
10
+ * @param server
11
+ * @param context
12
+ */
13
+ export const registerResources = (server, context) => {
14
+ registerResourceTemplates(server);
15
+ registerFileResources(server);
16
+ if (context.era === "modern")
17
+ registerMintedResources(server);
18
+ };
19
+ /**
20
+ * Reads the server instructions from the corresponding markdown file.
21
+ * Attempts to load the content of the file located in the `docs` directory.
22
+ * If the file cannot be loaded, an error message is returned instead.
23
+ *
24
+ * @return {string} The content of the server instructions file, or an error message if reading fails.
25
+ */
26
+ export function readInstructions() {
27
+ const __filename = fileURLToPath(import.meta.url);
28
+ const __dirname = dirname(__filename);
29
+ const filePath = join(__dirname, "..", "docs", "instructions.md");
30
+ let instructions;
31
+ try {
32
+ instructions = readFileSync(filePath, "utf-8");
33
+ }
34
+ catch (e) {
35
+ instructions = "Server instructions not loaded: " + e;
36
+ }
37
+ return instructions;
38
+ }