@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.
- package/README.md +140 -76
- package/dist/docs/architecture.md +45 -0
- package/dist/docs/extension.md +25 -0
- package/dist/docs/features.md +99 -0
- package/dist/docs/how-it-works.md +60 -0
- package/dist/docs/instructions.md +44 -0
- package/dist/docs/startup.md +71 -0
- package/dist/docs/structure.md +246 -0
- package/dist/index.js +73 -16
- package/dist/prompts/args.js +34 -0
- package/dist/prompts/completions.js +52 -0
- package/dist/prompts/index.js +15 -0
- package/dist/prompts/resource.js +61 -0
- package/dist/prompts/simple.js +23 -0
- package/dist/resources/files.js +91 -0
- package/dist/resources/index.js +38 -0
- package/dist/resources/minted.js +119 -0
- package/dist/resources/session.js +62 -0
- package/dist/resources/subscriptions.js +66 -0
- package/dist/resources/templates.js +167 -0
- package/dist/server/context.js +47 -0
- package/dist/server/index.js +153 -0
- package/dist/server/logging.js +43 -0
- package/dist/server/roots.js +49 -0
- package/dist/server/tasks.js +295 -0
- package/dist/tools/echo.js +35 -0
- package/dist/tools/get-annotated-message.js +89 -0
- package/dist/tools/get-env.js +34 -0
- package/dist/tools/get-header-params.js +95 -0
- package/dist/tools/get-resource-links.js +68 -0
- package/dist/tools/get-resource-reference.js +81 -0
- package/dist/tools/get-roots-list.js +76 -0
- package/dist/tools/get-structured-content.js +78 -0
- package/dist/tools/get-sum.js +46 -0
- package/dist/tools/get-tiny-image.js +47 -0
- package/dist/tools/gzip-file-as-resource.js +213 -0
- package/dist/tools/index.js +110 -0
- package/dist/tools/simulate-research-query.js +216 -0
- package/dist/tools/toggle-simulated-logging.js +60 -0
- package/dist/tools/toggle-subscriber-updates.js +60 -0
- package/dist/tools/trigger-elicitation-request-async.js +122 -0
- package/dist/tools/trigger-elicitation-request.js +223 -0
- package/dist/tools/trigger-list-changed.js +57 -0
- package/dist/tools/trigger-log-messages.js +60 -0
- package/dist/tools/trigger-long-running-operation.js +65 -0
- package/dist/tools/trigger-multi-step-elicitation.js +125 -0
- package/dist/tools/trigger-resource-update.js +52 -0
- package/dist/tools/trigger-sampling-request-async.js +110 -0
- package/dist/tools/trigger-sampling-request.js +83 -0
- package/dist/tools/trigger-url-elicitation.js +206 -0
- package/dist/transports/in-memory-event-store.js +44 -0
- package/dist/transports/listen.js +36 -0
- package/dist/transports/sse.js +112 -0
- package/dist/transports/stdio.js +68 -0
- package/dist/transports/streamableHttp.js +326 -0
- package/dist/version.js +35 -0
- package/package.json +39 -13
- package/dist/everything.js +0 -361
- package/dist/sse.js +0 -24
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Resources a tool creates for a 2026-07-28 client to read later, served from
|
|
2
|
+
// handles the server mints (#4852).
|
|
3
|
+
//
|
|
4
|
+
// On a 2025-era connection, `gzip-file-as-resource` registers the resource it
|
|
5
|
+
// creates on the server instance serving the client's connection or session
|
|
6
|
+
// (resources/session.ts), and the resource lasts as long as that instance.
|
|
7
|
+
// The 2026-07-28 revision has no sessions, and on its HTTP path every request
|
|
8
|
+
// is served by a fresh instance, so a resource registered on one would be gone
|
|
9
|
+
// before the client could read it. Instead the resource is stored here, under a
|
|
10
|
+
// URI that embeds a random id the server mints, and every 2026-07-28 instance
|
|
11
|
+
// serves the store through one resource template. The id is the handle: a
|
|
12
|
+
// client can read a minted resource only if it was given the URI. Each one
|
|
13
|
+
// expires after ten minutes; an expired or unknown URI reads as not found
|
|
14
|
+
// (-32602).
|
|
15
|
+
import { randomUUID } from "node:crypto";
|
|
16
|
+
import { ResourceNotFoundError, ResourceTemplate, } from "@modelcontextprotocol/server";
|
|
17
|
+
/** How long a minted resource stays readable, in milliseconds. */
|
|
18
|
+
export const MINTED_RESOURCE_TTL_MS = 10 * 60_000;
|
|
19
|
+
/**
|
|
20
|
+
* The most minted resources the process keeps, and the most bytes of content
|
|
21
|
+
* across them. Each one may be as large as the gzip tool's fetch limit, so
|
|
22
|
+
* without a budget a burst of calls could exhaust memory before the TTL frees
|
|
23
|
+
* anything; past it, the oldest are dropped first.
|
|
24
|
+
*/
|
|
25
|
+
export const MAX_MINTED_RESOURCES = 100;
|
|
26
|
+
export const MAX_MINTED_BYTES = 64 * 1024 * 1024;
|
|
27
|
+
/** The URI template every minted resource matches. */
|
|
28
|
+
const mintedUriTemplate = "demo://resource/minted/{id}/{name}";
|
|
29
|
+
/** Every live minted resource, by URI, across every server instance. */
|
|
30
|
+
const minted = new Map();
|
|
31
|
+
/** Drop every minted resource past its expiry. */
|
|
32
|
+
function sweep(now) {
|
|
33
|
+
for (const [uri, resource] of minted) {
|
|
34
|
+
if (resource.expiresAt <= now)
|
|
35
|
+
minted.delete(uri);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Drop the oldest minted resources (the map keeps insertion order) until one
|
|
40
|
+
* more of `bytes` fits both budgets.
|
|
41
|
+
*/
|
|
42
|
+
function makeRoom(bytes) {
|
|
43
|
+
let total = bytes;
|
|
44
|
+
for (const [uri, resource] of minted)
|
|
45
|
+
total += sizeOf(uri, resource);
|
|
46
|
+
for (const [uri, resource] of minted) {
|
|
47
|
+
if (minted.size < MAX_MINTED_RESOURCES && total <= MAX_MINTED_BYTES)
|
|
48
|
+
break;
|
|
49
|
+
minted.delete(uri);
|
|
50
|
+
total -= sizeOf(uri, resource);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** What a stored resource counts against the budget: everything it keeps. */
|
|
54
|
+
function sizeOf(uri, resource) {
|
|
55
|
+
return uri.length + resource.name.length + resource.blob.length;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Store a blob resource under a freshly minted URI, and return a link to it.
|
|
59
|
+
* Throws for a blob larger than `MAX_MINTED_BYTES`.
|
|
60
|
+
*
|
|
61
|
+
* @param name - The resource's name, the last segment of its URI.
|
|
62
|
+
* @param mimeType - Its MIME type.
|
|
63
|
+
* @param blob - Its content, base64-encoded.
|
|
64
|
+
*/
|
|
65
|
+
export function mintBlobResource(name, mimeType, blob) {
|
|
66
|
+
// One resource larger than the whole budget is refused outright, rather
|
|
67
|
+
// than evicting everything else and still exceeding the budget.
|
|
68
|
+
const uri = `demo://resource/minted/${randomUUID()}/${encodeURIComponent(name)}`;
|
|
69
|
+
const size = uri.length + name.length + blob.length;
|
|
70
|
+
if (size > MAX_MINTED_BYTES) {
|
|
71
|
+
throw new Error(`Cannot keep ${name} for later reading: its ${size} bytes exceed the ${MAX_MINTED_BYTES}-byte limit for minted resources`);
|
|
72
|
+
}
|
|
73
|
+
const now = Date.now();
|
|
74
|
+
sweep(now);
|
|
75
|
+
makeRoom(size);
|
|
76
|
+
minted.set(uri, {
|
|
77
|
+
name,
|
|
78
|
+
mimeType,
|
|
79
|
+
blob,
|
|
80
|
+
expiresAt: now + MINTED_RESOURCE_TTL_MS,
|
|
81
|
+
});
|
|
82
|
+
return {
|
|
83
|
+
type: "resource_link",
|
|
84
|
+
uri,
|
|
85
|
+
name,
|
|
86
|
+
mimeType,
|
|
87
|
+
description: `Created by a tool call; readable for ${MINTED_RESOURCE_TTL_MS / 60_000} minutes at this URI`,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Register the template that serves minted resources, on a 2026-07-28
|
|
92
|
+
* server. It lists nothing: a minted resource is reached by the URI a tool
|
|
93
|
+
* returned.
|
|
94
|
+
*
|
|
95
|
+
* @param server - The 2026-07-28 server to serve them on.
|
|
96
|
+
*/
|
|
97
|
+
export function registerMintedResources(server) {
|
|
98
|
+
server.registerResource("Minted Resource", new ResourceTemplate(mintedUriTemplate, { list: undefined }), {
|
|
99
|
+
description: "A resource a tool created for this client, such as gzip-file-as-resource's output. Readable for ten minutes at the URI the tool returned.",
|
|
100
|
+
}, async (uri) => {
|
|
101
|
+
sweep(Date.now());
|
|
102
|
+
const resource = minted.get(uri.toString());
|
|
103
|
+
if (!resource)
|
|
104
|
+
throw new ResourceNotFoundError(uri.toString());
|
|
105
|
+
return {
|
|
106
|
+
contents: [
|
|
107
|
+
{
|
|
108
|
+
uri: uri.toString(),
|
|
109
|
+
mimeType: resource.mimeType,
|
|
110
|
+
blob: resource.blob,
|
|
111
|
+
},
|
|
112
|
+
],
|
|
113
|
+
};
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
/** Forget every minted resource. For tests. */
|
|
117
|
+
export function clearMintedResources() {
|
|
118
|
+
minted.clear();
|
|
119
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tracks registered session resources per server, by URI, to allow updating/removing on
|
|
3
|
+
* re-registration. This prevents "Resource already registered" errors when a tool creates
|
|
4
|
+
* a resource with the same URI multiple times during a session, without touching another
|
|
5
|
+
* session's server that registered the same URI (#4808).
|
|
6
|
+
*/
|
|
7
|
+
const registeredResources = new WeakMap();
|
|
8
|
+
/**
|
|
9
|
+
* Generates a session-scoped resource URI string based on the provided resource name.
|
|
10
|
+
*
|
|
11
|
+
* @param {string} name - The name of the resource to create a URI for.
|
|
12
|
+
* @returns {string} The formatted session resource URI.
|
|
13
|
+
*/
|
|
14
|
+
export const getSessionResourceURI = (name) => {
|
|
15
|
+
return `demo://resource/session/${name}`;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Registers a session-scoped resource with the provided server and returns a resource link.
|
|
19
|
+
*
|
|
20
|
+
* The registered resource is available during the life of the session only; it is not otherwise persisted.
|
|
21
|
+
*
|
|
22
|
+
* @param {McpServer} server - The server instance responsible for handling the resource registration.
|
|
23
|
+
* @param {Resource} resource - The resource object containing metadata such as URI, name, description, and mimeType.
|
|
24
|
+
* @param {"text"|"blob"} type
|
|
25
|
+
* @param payload
|
|
26
|
+
* @returns {ResourceLink} An object representing the resource link, with associated metadata.
|
|
27
|
+
*/
|
|
28
|
+
export const registerSessionResource = (server, resource, type, payload) => {
|
|
29
|
+
// Destructure resource
|
|
30
|
+
const { uri, name, mimeType, description, title, annotations, icons, _meta } = resource;
|
|
31
|
+
// Prepare the resource content to return
|
|
32
|
+
// See https://modelcontextprotocol.io/specification/2025-11-25/server/resources#resource-contents
|
|
33
|
+
const resourceContent = type === "text"
|
|
34
|
+
? {
|
|
35
|
+
uri: uri.toString(),
|
|
36
|
+
mimeType,
|
|
37
|
+
text: payload,
|
|
38
|
+
}
|
|
39
|
+
: {
|
|
40
|
+
uri: uri.toString(),
|
|
41
|
+
mimeType,
|
|
42
|
+
blob: payload,
|
|
43
|
+
};
|
|
44
|
+
const serverResources = registeredResources.get(server) ?? new Map();
|
|
45
|
+
registeredResources.set(server, serverResources);
|
|
46
|
+
// Check if a resource with this URI is already registered on this server and remove it
|
|
47
|
+
const resourceKey = uri.toString();
|
|
48
|
+
const existingResource = serverResources.get(resourceKey);
|
|
49
|
+
if (existingResource) {
|
|
50
|
+
existingResource.remove();
|
|
51
|
+
serverResources.delete(resourceKey);
|
|
52
|
+
}
|
|
53
|
+
// Register file resource
|
|
54
|
+
const registeredResource = server.registerResource(name, uri, { mimeType, description, title, annotations, icons, _meta }, async () => {
|
|
55
|
+
return {
|
|
56
|
+
contents: [resourceContent],
|
|
57
|
+
};
|
|
58
|
+
});
|
|
59
|
+
// Track the registered resource for potential future removal
|
|
60
|
+
serverResources.set(resourceKey, registeredResource);
|
|
61
|
+
return { type: "resource_link", ...resource };
|
|
62
|
+
};
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// 2025-era per-resource subscriptions, and the simulated updates
|
|
2
|
+
// `toggle-subscriber-updates` sends for them.
|
|
3
|
+
//
|
|
4
|
+
// `resources/subscribe` and `resources/unsubscribe` exist only on the 2025
|
|
5
|
+
// protocol era. A 2026-07-28 client names the resources it wants updates for
|
|
6
|
+
// in its `subscriptions/listen` filter instead, and the serving entry
|
|
7
|
+
// delivers each `notifications/resources/updated` only to a stream that asked
|
|
8
|
+
// for it (`trigger-resource-update` shows that). The subscribed set belongs to
|
|
9
|
+
// the server instance serving the client's connection or session, so no
|
|
10
|
+
// session map is needed (#4852).
|
|
11
|
+
/**
|
|
12
|
+
* Install the `resources/subscribe` and `resources/unsubscribe` handlers on a
|
|
13
|
+
* 2025-era server, recording each subscription in `subscribed`.
|
|
14
|
+
*
|
|
15
|
+
* Each handler acknowledges the request with an info-level log message, then
|
|
16
|
+
* adds the URI to, or removes it from, the set.
|
|
17
|
+
*
|
|
18
|
+
* @param {McpServer} server - The server instance to which subscription handlers will be attached.
|
|
19
|
+
* @param {Set<string>} subscribed - The URIs this server's client has subscribed to.
|
|
20
|
+
*/
|
|
21
|
+
export const setSubscriptionHandlers = (server, subscribed) => {
|
|
22
|
+
server.server.setRequestHandler("resources/subscribe", async (request) => {
|
|
23
|
+
const { uri } = request.params;
|
|
24
|
+
await server.sendLoggingMessage({
|
|
25
|
+
level: "info",
|
|
26
|
+
data: `Received Subscribe Resource request for URI: ${uri}`,
|
|
27
|
+
}, server.server.transport?.sessionId);
|
|
28
|
+
subscribed.add(uri);
|
|
29
|
+
return {};
|
|
30
|
+
});
|
|
31
|
+
server.server.setRequestHandler("resources/unsubscribe", async (request) => {
|
|
32
|
+
const { uri } = request.params;
|
|
33
|
+
await server.sendLoggingMessage({
|
|
34
|
+
level: "info",
|
|
35
|
+
data: `Received Unsubscribe Resource request: ${uri}`,
|
|
36
|
+
}, server.server.transport?.sessionId);
|
|
37
|
+
subscribed.delete(uri);
|
|
38
|
+
return {};
|
|
39
|
+
});
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Start sending `server`'s client a `notifications/resources/updated` for each
|
|
43
|
+
* resource it has subscribed to, now and then every five seconds.
|
|
44
|
+
*
|
|
45
|
+
* @param {McpServer} server - The server whose client receives the updates.
|
|
46
|
+
* @param {Set<string>} subscribed - The URIs that client has subscribed to.
|
|
47
|
+
* @returns {() => void} Stops the updates.
|
|
48
|
+
*/
|
|
49
|
+
export const beginSimulatedResourceUpdates = (server, subscribed) => {
|
|
50
|
+
// Fire-and-forget: this runs on a timer with no caller to await it. A send
|
|
51
|
+
// that fails (e.g. the transport closed before the updates were stopped) is
|
|
52
|
+
// logged rather than left to become an unhandled rejection.
|
|
53
|
+
const send = async () => {
|
|
54
|
+
try {
|
|
55
|
+
for (const uri of [...subscribed]) {
|
|
56
|
+
await server.server.sendResourceUpdated({ uri });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
console.error("Simulated resource update failed:", error);
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
void send();
|
|
64
|
+
const interval = setInterval(() => void send(), 5000);
|
|
65
|
+
return () => clearInterval(interval);
|
|
66
|
+
};
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { ResourceNotFoundError, ResourceTemplate, completable, } from "@modelcontextprotocol/server";
|
|
3
|
+
// Resource types
|
|
4
|
+
export const RESOURCE_TYPE_TEXT = "Text";
|
|
5
|
+
export const RESOURCE_TYPE_BLOB = "Blob";
|
|
6
|
+
export const RESOURCE_TYPES = [
|
|
7
|
+
RESOURCE_TYPE_TEXT,
|
|
8
|
+
RESOURCE_TYPE_BLOB,
|
|
9
|
+
];
|
|
10
|
+
/**
|
|
11
|
+
* A completer function for resource types.
|
|
12
|
+
*
|
|
13
|
+
* This variable provides functionality to perform autocompletion for the resource types based on user input.
|
|
14
|
+
* It uses a schema description to validate the input and filters through a predefined list of resource types
|
|
15
|
+
* to return suggestions that start with the given input.
|
|
16
|
+
*
|
|
17
|
+
* The input value is expected to be a string representing the type of resource to fetch.
|
|
18
|
+
* The completion logic matches the input against available resource types.
|
|
19
|
+
*/
|
|
20
|
+
export const resourceTypeCompleter = completable(z.string().describe("Type of resource to fetch"), (value) => {
|
|
21
|
+
return RESOURCE_TYPES.filter((t) => t.startsWith(value));
|
|
22
|
+
});
|
|
23
|
+
/**
|
|
24
|
+
* A completer function for resource IDs as strings.
|
|
25
|
+
*
|
|
26
|
+
* The `resourceIdCompleter` accepts a string input representing the ID of a text resource
|
|
27
|
+
* and validates whether the provided value corresponds to an integer resource ID.
|
|
28
|
+
*
|
|
29
|
+
* NOTE: Currently, prompt arguments can only be strings since type is not field of `PromptArgument`
|
|
30
|
+
* Consequently, we must define it as a string and convert the argument to number before using it
|
|
31
|
+
* https://modelcontextprotocol.io/specification/2025-11-25/schema#promptargument
|
|
32
|
+
*
|
|
33
|
+
* If the value is a valid integer, it returns the value within an array.
|
|
34
|
+
* Otherwise, it returns an empty array.
|
|
35
|
+
*
|
|
36
|
+
* The input string is first transformed into a number and checked to ensure it is an integer.
|
|
37
|
+
* This helps validate and suggest appropriate resource IDs.
|
|
38
|
+
*/
|
|
39
|
+
export const resourceIdForPromptCompleter = completable(z.string().describe("ID of the text resource to fetch"), (value) => {
|
|
40
|
+
const resourceId = Number(value);
|
|
41
|
+
return Number.isInteger(resourceId) && resourceId > 0 ? [value] : [];
|
|
42
|
+
});
|
|
43
|
+
/**
|
|
44
|
+
* A callback function that acts as a completer for resource ID values, validating and returning
|
|
45
|
+
* the input value as part of a resource template.
|
|
46
|
+
*
|
|
47
|
+
* @typedef {CompleteResourceTemplateCallback}
|
|
48
|
+
* @param {string} value - The input string value to be evaluated as a resource ID.
|
|
49
|
+
* @returns {string[]} Returns an array containing the input value if it represents a positive
|
|
50
|
+
* integer resource ID, otherwise returns an empty array.
|
|
51
|
+
*/
|
|
52
|
+
export const resourceIdForResourceTemplateCompleter = (value) => {
|
|
53
|
+
const resourceId = Number(value);
|
|
54
|
+
return Number.isInteger(resourceId) && resourceId > 0 ? [value] : [];
|
|
55
|
+
};
|
|
56
|
+
const uriBase = "demo://resource/dynamic";
|
|
57
|
+
const textUriBase = `${uriBase}/text`;
|
|
58
|
+
const blobUriBase = `${uriBase}/blob`;
|
|
59
|
+
const textUriTemplate = `${textUriBase}/{resourceId}`;
|
|
60
|
+
const blobUriTemplate = `${blobUriBase}/{resourceId}`;
|
|
61
|
+
/**
|
|
62
|
+
* Create a dynamic text resource
|
|
63
|
+
* - Exposed for use by embedded resource prompt example
|
|
64
|
+
* @param uri
|
|
65
|
+
* @param resourceId
|
|
66
|
+
*/
|
|
67
|
+
export const textResource = (uri, resourceId) => {
|
|
68
|
+
const timestamp = new Date().toLocaleTimeString();
|
|
69
|
+
return {
|
|
70
|
+
uri: uri.toString(),
|
|
71
|
+
mimeType: "text/plain",
|
|
72
|
+
text: `Resource ${resourceId}: This is a plaintext resource created at ${timestamp}`,
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* Create a dynamic blob resource
|
|
77
|
+
* - Exposed for use by embedded resource prompt example
|
|
78
|
+
* @param uri
|
|
79
|
+
* @param resourceId
|
|
80
|
+
*/
|
|
81
|
+
export const blobResource = (uri, resourceId) => {
|
|
82
|
+
const timestamp = new Date().toLocaleTimeString();
|
|
83
|
+
const resourceText = Buffer.from(`Resource ${resourceId}: This is a base64 blob created at ${timestamp}`).toString("base64");
|
|
84
|
+
return {
|
|
85
|
+
uri: uri.toString(),
|
|
86
|
+
mimeType: "application/octet-stream",
|
|
87
|
+
blob: resourceText,
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* Create a dynamic text resource URI
|
|
92
|
+
* - Exposed for use by embedded resource prompt example
|
|
93
|
+
* @param resourceId
|
|
94
|
+
*/
|
|
95
|
+
export const textResourceUri = (resourceId) => new URL(`${textUriBase}/${resourceId}`);
|
|
96
|
+
/**
|
|
97
|
+
* Create a dynamic blob resource URI
|
|
98
|
+
* - Exposed for use by embedded resource prompt example
|
|
99
|
+
* @param resourceId
|
|
100
|
+
*/
|
|
101
|
+
export const blobResourceUri = (resourceId) => new URL(`${blobUriBase}/${resourceId}`);
|
|
102
|
+
/**
|
|
103
|
+
* Parses the resource identifier from the provided variables and validates
|
|
104
|
+
* that it is a positive integer.
|
|
105
|
+
*
|
|
106
|
+
* The SDK only routes URIs that match the registered template to the
|
|
107
|
+
* resource handler, so by the time we get here the URI prefix is already
|
|
108
|
+
* known to be one of `textUriBase` / `blobUriBase`. Only the resourceId
|
|
109
|
+
* variable still needs validating.
|
|
110
|
+
*
|
|
111
|
+
* @param {URL} uri - The URI of the resource (used in the error message).
|
|
112
|
+
* @param {Record<string, unknown>} variables - Context variables including resourceId.
|
|
113
|
+
* @returns {number} The parsed and validated resource identifier as a positive integer.
|
|
114
|
+
* @throws {ResourceNotFoundError} If the resourceId is not a finite positive
|
|
115
|
+
* integer: no such resource exists, which the protocol reports as -32602
|
|
116
|
+
* with the URI in the error's data (#4852).
|
|
117
|
+
*/
|
|
118
|
+
const parseResourceId = (uri, variables) => {
|
|
119
|
+
const idxStr = String(variables.resourceId ?? "");
|
|
120
|
+
const idx = Number(idxStr);
|
|
121
|
+
if (Number.isFinite(idx) && Number.isInteger(idx) && idx > 0) {
|
|
122
|
+
return idx;
|
|
123
|
+
}
|
|
124
|
+
throw new ResourceNotFoundError(uri.toString());
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* Register resource templates with the MCP server.
|
|
128
|
+
* - Text and blob resources, dynamically generated from the URI {resourceId} variable
|
|
129
|
+
* - Any finite positive integer is acceptable for the resourceId variable
|
|
130
|
+
* - List resources method will not return these resources
|
|
131
|
+
* - These are only accessible via template URIs
|
|
132
|
+
* - Both blob and text resources:
|
|
133
|
+
* - have content that is dynamically generated, including a timestamp
|
|
134
|
+
* - have different template URIs
|
|
135
|
+
* - Blob: "demo://resource/dynamic/blob/{resourceId}"
|
|
136
|
+
* - Text: "demo://resource/dynamic/text/{resourceId}"
|
|
137
|
+
*
|
|
138
|
+
* @param server
|
|
139
|
+
*/
|
|
140
|
+
export const registerResourceTemplates = (server) => {
|
|
141
|
+
// Register the text resource template
|
|
142
|
+
server.registerResource("Dynamic Text Resource", new ResourceTemplate(textUriTemplate, {
|
|
143
|
+
list: undefined,
|
|
144
|
+
complete: { resourceId: resourceIdForResourceTemplateCompleter },
|
|
145
|
+
}), {
|
|
146
|
+
mimeType: "text/plain",
|
|
147
|
+
description: "Plaintext dynamic resource fabricated from the {resourceId} variable, which must be an integer.",
|
|
148
|
+
}, async (uri, variables) => {
|
|
149
|
+
const resourceId = parseResourceId(uri, variables);
|
|
150
|
+
return {
|
|
151
|
+
contents: [textResource(uri, resourceId)],
|
|
152
|
+
};
|
|
153
|
+
});
|
|
154
|
+
// Register the blob resource template
|
|
155
|
+
server.registerResource("Dynamic Blob Resource", new ResourceTemplate(blobUriTemplate, {
|
|
156
|
+
list: undefined,
|
|
157
|
+
complete: { resourceId: resourceIdForResourceTemplateCompleter },
|
|
158
|
+
}), {
|
|
159
|
+
mimeType: "application/octet-stream",
|
|
160
|
+
description: "Binary (base64) dynamic resource fabricated from the {resourceId} variable, which must be an integer.",
|
|
161
|
+
}, async (uri, variables) => {
|
|
162
|
+
const resourceId = parseResourceId(uri, variables);
|
|
163
|
+
return {
|
|
164
|
+
contents: [blobResource(uri, resourceId)],
|
|
165
|
+
};
|
|
166
|
+
});
|
|
167
|
+
};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// The per-instance context the server factory hands to the features that
|
|
2
|
+
// need more than the `McpServer` itself (#4852).
|
|
3
|
+
//
|
|
4
|
+
// Before the 2026-07-28 revision, features that kept state across calls
|
|
5
|
+
// (simulated logging, resource subscriptions, the roots cache, the URL
|
|
6
|
+
// elicitation error path) held it in module-level maps keyed by the
|
|
7
|
+
// transport's session id. The 2026-07-28 revision has no sessions, so that
|
|
8
|
+
// state now lives here, on the server instance the factory built: one per
|
|
9
|
+
// stdio connection, one per 2025-era Streamable HTTP session, and one per
|
|
10
|
+
// request on the 2026-07-28 HTTP path, where nothing survives between
|
|
11
|
+
// requests unless the server mints a handle for it (as the tasks store does).
|
|
12
|
+
//
|
|
13
|
+
// The context also carries the protocol era the instance serves, because a
|
|
14
|
+
// few features differ by era, and the publisher that announces list and
|
|
15
|
+
// resource changes, because where a change notification goes differs by
|
|
16
|
+
// transport: on stdio and on a 2025-era session the instance sends it
|
|
17
|
+
// itself, while on the 2026-07-28 HTTP path the instance lives for one
|
|
18
|
+
// request and the change goes out on the handler's subscription bus.
|
|
19
|
+
/**
|
|
20
|
+
* A publisher that sends each change from `server` itself. On a 2025-era
|
|
21
|
+
* connection the notification goes to the client unsolicited; on a
|
|
22
|
+
* 2026-07-28 stdio connection `serveStdio` routes it onto the open
|
|
23
|
+
* `subscriptions/listen` streams that asked for it.
|
|
24
|
+
*
|
|
25
|
+
* `resourceUpdated` is sent only for a URI `isSubscribed` accepts: a 2025-era
|
|
26
|
+
* client subscribes per resource, and on 2026-07-28 the listen router does
|
|
27
|
+
* the filtering, so the server passes `() => true` there.
|
|
28
|
+
*/
|
|
29
|
+
export function instancePublisher(server, isSubscribed) {
|
|
30
|
+
const report = (error) => console.error("Change notification failed:", error);
|
|
31
|
+
// The low-level sends return their promise; McpServer's own helpers start
|
|
32
|
+
// the same send and drop it, so a failed one would go unhandled.
|
|
33
|
+
const send = (notify) => {
|
|
34
|
+
if (server.isConnected())
|
|
35
|
+
notify().catch(report);
|
|
36
|
+
};
|
|
37
|
+
return {
|
|
38
|
+
toolsChanged: () => send(() => server.server.sendToolListChanged()),
|
|
39
|
+
promptsChanged: () => send(() => server.server.sendPromptListChanged()),
|
|
40
|
+
resourcesChanged: () => send(() => server.server.sendResourceListChanged()),
|
|
41
|
+
resourceUpdated: (uri) => {
|
|
42
|
+
if (isSubscribed(uri)) {
|
|
43
|
+
server.server.sendResourceUpdated({ uri }).catch(report);
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// The everything server's factory: builds one fully registered `McpServer`
|
|
2
|
+
// for the protocol era it is asked to serve (#4852).
|
|
3
|
+
//
|
|
4
|
+
// One factory backs every transport and both eras. `serveStdio` calls it once
|
|
5
|
+
// per stdio connection; the Streamable HTTP transport calls it once per
|
|
6
|
+
// 2025-era session and once per 2026-07-28 request; the SSE transport once
|
|
7
|
+
// per (2025-era) connection. Everything that must outlive a single call lives
|
|
8
|
+
// on the instance it builds, in the context below, never in a map keyed by a
|
|
9
|
+
// session id: the 2026-07-28 revision has no sessions.
|
|
10
|
+
//
|
|
11
|
+
// What differs by era is wired here, in one place:
|
|
12
|
+
// - 2025-era: the client's capabilities arrive in `initialize`, so the tools
|
|
13
|
+
// that need a client capability are registered once it has initialized, and
|
|
14
|
+
// the roots list is synced then. The features the 2026-07-28 revision
|
|
15
|
+
// removes (`logging/setLevel`-paced simulated logging, `resources/subscribe`
|
|
16
|
+
// timed updates) are registered here only, labelled deprecated.
|
|
17
|
+
// - 2026-07-28: there is no `initialize`, and each request carries the
|
|
18
|
+
// client's capabilities in its `_meta`, so the capability-gated tools are
|
|
19
|
+
// registered up front and the SDK refuses an embedded request the client
|
|
20
|
+
// did not declare (-32021). The tasks extension is served here only.
|
|
21
|
+
import { createRequestStateCodec, McpServer, } from "@modelcontextprotocol/server";
|
|
22
|
+
import { setSubscriptionHandlers } from "../resources/subscriptions.js";
|
|
23
|
+
import { registerConditionalTools, registerLegacyTools, registerModernTools, registerTools, } from "../tools/index.js";
|
|
24
|
+
import { registerResources, readInstructions } from "../resources/index.js";
|
|
25
|
+
import { registerPrompts } from "../prompts/index.js";
|
|
26
|
+
import { guardTaskTools, registerTasksExtension, TASKS_EXTENSION, } from "./tasks.js";
|
|
27
|
+
import { syncRoots } from "./roots.js";
|
|
28
|
+
import { instancePublisher, } from "./context.js";
|
|
29
|
+
import { SERVER_VERSION } from "../version.js";
|
|
30
|
+
/**
|
|
31
|
+
* The process-wide `requestState` codec. The key is per process: on the
|
|
32
|
+
* 2026-07-28 HTTP path a later round may be served by a fresh instance, so
|
|
33
|
+
* the key cannot belong to one. A deployment of several processes would load
|
|
34
|
+
* a shared secret here instead.
|
|
35
|
+
*/
|
|
36
|
+
export const roundStateCodec = createRequestStateCodec({
|
|
37
|
+
key: crypto.getRandomValues(new Uint8Array(32)),
|
|
38
|
+
ttlSeconds: 600,
|
|
39
|
+
});
|
|
40
|
+
/**
|
|
41
|
+
* Cache hints for the 2026-07-28 cacheable results (`ttlMs` / `cacheScope`).
|
|
42
|
+
* The lists are the same for every client and change only with a
|
|
43
|
+
* `list_changed` notification, so a shared cache may hold them for a minute;
|
|
44
|
+
* `server/discover` changes only when the server is upgraded. 2025-era
|
|
45
|
+
* responses never carry these fields. A static document resource sets a
|
|
46
|
+
* longer hint of its own (resources/files.ts).
|
|
47
|
+
*/
|
|
48
|
+
export const CACHE_HINTS = {
|
|
49
|
+
"server/discover": { ttlMs: 5 * 60_000, cacheScope: "public" },
|
|
50
|
+
"tools/list": { ttlMs: 60_000, cacheScope: "public" },
|
|
51
|
+
"prompts/list": { ttlMs: 60_000, cacheScope: "public" },
|
|
52
|
+
"resources/list": { ttlMs: 60_000, cacheScope: "public" },
|
|
53
|
+
"resources/templates/list": { ttlMs: 60_000, cacheScope: "public" },
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Server Factory
|
|
57
|
+
*
|
|
58
|
+
* Initializes a `McpServer` with its capabilities and instructions, and
|
|
59
|
+
* registers the tools, resources and prompts for the era it serves.
|
|
60
|
+
*
|
|
61
|
+
* @param {ServerOptions} options - The era to serve and where its change
|
|
62
|
+
* notifications go.
|
|
63
|
+
* @returns {ServerFactoryResponse} The server instance, and a `cleanup`
|
|
64
|
+
* function that ends its per-connection work when the connection closes.
|
|
65
|
+
*/
|
|
66
|
+
export const createServer = (options = {}) => {
|
|
67
|
+
const era = options.era ?? "legacy";
|
|
68
|
+
// Read the server instructions
|
|
69
|
+
const instructions = readInstructions();
|
|
70
|
+
const cleanups = [];
|
|
71
|
+
let initializeTimeout = null;
|
|
72
|
+
// Create the server
|
|
73
|
+
const server = new McpServer({
|
|
74
|
+
name: "mcp-servers/everything",
|
|
75
|
+
title: "Everything Reference Server",
|
|
76
|
+
version: SERVER_VERSION,
|
|
77
|
+
}, {
|
|
78
|
+
capabilities: {
|
|
79
|
+
// `tools: { listChanged: true }` is advertised by the first
|
|
80
|
+
// registerTool. Declaring it here would install McpServer's
|
|
81
|
+
// tools/call handler in the constructor, before guardTaskTools can
|
|
82
|
+
// wrap it.
|
|
83
|
+
prompts: {
|
|
84
|
+
listChanged: true,
|
|
85
|
+
},
|
|
86
|
+
resources: {
|
|
87
|
+
subscribe: true,
|
|
88
|
+
listChanged: true,
|
|
89
|
+
},
|
|
90
|
+
// Deprecated as of 2026-07-28 (SEP-2577), and still served on both
|
|
91
|
+
// eras: 2025-era clients set the level with `logging/setLevel`,
|
|
92
|
+
// 2026-07-28 clients per request in `_meta`.
|
|
93
|
+
logging: {},
|
|
94
|
+
// The tasks extension (`io.modelcontextprotocol/tasks`) is
|
|
95
|
+
// advertised on 2026-07-28 only, where it is served.
|
|
96
|
+
...(era === "modern" && { extensions: { [TASKS_EXTENSION]: {} } }),
|
|
97
|
+
},
|
|
98
|
+
instructions,
|
|
99
|
+
cacheHints: CACHE_HINTS,
|
|
100
|
+
requestState: { verify: roundStateCodec.verify },
|
|
101
|
+
});
|
|
102
|
+
// Resources a 2025-era client has subscribed to on this instance. On
|
|
103
|
+
// 2026-07-28 the client names them in its subscriptions/listen filter and
|
|
104
|
+
// the serving entry delivers only what it asked for.
|
|
105
|
+
const subscribed = new Set();
|
|
106
|
+
const context = {
|
|
107
|
+
era,
|
|
108
|
+
subscribed,
|
|
109
|
+
publish: options.publish ??
|
|
110
|
+
instancePublisher(server, (uri) => era === "modern" ? true : subscribed.has(uri)),
|
|
111
|
+
onCleanup: (fn) => cleanups.push(fn),
|
|
112
|
+
};
|
|
113
|
+
// A task tool refuses, with -32021, a client that has not declared what it
|
|
114
|
+
// needs; this wraps the tools/call handler the first registration installs.
|
|
115
|
+
if (era === "modern")
|
|
116
|
+
guardTaskTools(server);
|
|
117
|
+
// Register the tools, resources and prompts every era gets
|
|
118
|
+
registerTools(server, context);
|
|
119
|
+
registerResources(server, context);
|
|
120
|
+
registerPrompts(server);
|
|
121
|
+
if (era === "modern") {
|
|
122
|
+
// Each request carries the client's capabilities, so the tools that need
|
|
123
|
+
// one are registered up front, along with the tasks extension.
|
|
124
|
+
registerModernTools(server, context);
|
|
125
|
+
registerTasksExtension(server);
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
registerLegacyTools(server, context);
|
|
129
|
+
setSubscriptionHandlers(server, context.subscribed);
|
|
130
|
+
// Perform post-initialization operations
|
|
131
|
+
server.server.oninitialized = async () => {
|
|
132
|
+
// Register conditional tools now that client capabilities are known.
|
|
133
|
+
// This finishes before the `notifications/initialized` handler finishes.
|
|
134
|
+
registerConditionalTools(server, context);
|
|
135
|
+
// Sync roots if the client supports them.
|
|
136
|
+
// This is delayed until after the `notifications/initialized` handler finishes,
|
|
137
|
+
// otherwise, the request gets lost.
|
|
138
|
+
initializeTimeout = setTimeout(() => syncRoots(server), 350);
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
// Return the ServerFactoryResponse
|
|
142
|
+
return {
|
|
143
|
+
server,
|
|
144
|
+
cleanup: () => {
|
|
145
|
+
// Stop any simulated logging or resource updates that may have been initiated.
|
|
146
|
+
for (const fn of cleanups.splice(0))
|
|
147
|
+
fn();
|
|
148
|
+
subscribed.clear();
|
|
149
|
+
if (initializeTimeout)
|
|
150
|
+
clearTimeout(initializeTimeout);
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Simulated logging for `toggle-simulated-logging`: a timer that sends a
|
|
2
|
+
// random-leveled `notifications/message` every five seconds, filtered by the
|
|
3
|
+
// level the client set with `logging/setLevel`.
|
|
4
|
+
//
|
|
5
|
+
// This is 2025-era behavior. The 2026-07-28 revision removes
|
|
6
|
+
// `logging/setLevel` and unsolicited log messages: a log message is sent only
|
|
7
|
+
// during a request, at the level that request names in its `_meta`
|
|
8
|
+
// (`trigger-log-messages` shows that). Logging itself is deprecated as of
|
|
9
|
+
// 2026-07-28 (SEP-2577). The timer belongs to one server instance, the one
|
|
10
|
+
// serving the client's connection or session, so no session map is needed
|
|
11
|
+
// (#4852).
|
|
12
|
+
/** One message per logging level, from least to most severe. */
|
|
13
|
+
const MESSAGES = [
|
|
14
|
+
{ level: "debug", data: "Debug-level message" },
|
|
15
|
+
{ level: "info", data: "Info-level message" },
|
|
16
|
+
{ level: "notice", data: "Notice-level message" },
|
|
17
|
+
{ level: "warning", data: "Warning-level message" },
|
|
18
|
+
{ level: "error", data: "Error-level message" },
|
|
19
|
+
{ level: "critical", data: "Critical-level message" },
|
|
20
|
+
{ level: "alert", data: "Alert level-message" },
|
|
21
|
+
{ level: "emergency", data: "Emergency-level message" },
|
|
22
|
+
];
|
|
23
|
+
/**
|
|
24
|
+
* Start sending `server`'s client a random-leveled log message now and then
|
|
25
|
+
* every five seconds. The SDK drops a message below the level the client set.
|
|
26
|
+
*
|
|
27
|
+
* @param {McpServer} server - The server whose client receives the messages.
|
|
28
|
+
* @returns {() => void} Stops the messages.
|
|
29
|
+
*/
|
|
30
|
+
export const beginSimulatedLogging = (server) => {
|
|
31
|
+
// Fire-and-forget: this runs on a timer with no caller to await it. A send
|
|
32
|
+
// that fails (e.g. the transport closed before logging was stopped) is
|
|
33
|
+
// logged rather than left to become an unhandled rejection.
|
|
34
|
+
const send = () => server
|
|
35
|
+
.sendLoggingMessage(MESSAGES[Math.floor(Math.random() * MESSAGES.length)],
|
|
36
|
+
// The SDK keeps the level the client set per transport session, so
|
|
37
|
+
// the filter is looked up by this connection's session id.
|
|
38
|
+
server.server.transport?.sessionId)
|
|
39
|
+
.catch((error) => console.error("Simulated logging message failed:", error));
|
|
40
|
+
void send();
|
|
41
|
+
const interval = setInterval(() => void send(), 5000);
|
|
42
|
+
return () => clearInterval(interval);
|
|
43
|
+
};
|