@modelcontextprotocol/server-everything 0.6.2 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +121 -72
- package/dist/docs/architecture.md +44 -0
- package/dist/docs/extension.md +23 -0
- package/dist/docs/features.md +105 -0
- package/dist/docs/how-it-works.md +45 -0
- package/dist/docs/instructions.md +37 -0
- package/dist/docs/startup.md +76 -0
- package/dist/docs/structure.md +212 -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 +60 -0
- package/dist/prompts/simple.js +23 -0
- package/dist/resources/files.js +83 -0
- package/dist/resources/index.js +33 -0
- package/dist/resources/session.js +62 -0
- package/dist/resources/subscriptions.js +144 -0
- package/dist/resources/templates.js +166 -0
- package/dist/server/index.js +95 -0
- package/dist/server/logging.js +70 -0
- package/dist/server/roots.js +70 -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-resource-links.js +68 -0
- package/dist/tools/get-resource-reference.js +81 -0
- package/dist/tools/get-roots-list.js +77 -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 +194 -0
- package/dist/tools/index.js +52 -0
- package/dist/tools/simulate-research-query.js +251 -0
- package/dist/tools/toggle-simulated-logging.js +47 -0
- package/dist/tools/toggle-subscriber-updates.js +50 -0
- package/dist/tools/trigger-elicitation-request-async.js +227 -0
- package/dist/tools/trigger-elicitation-request.js +222 -0
- package/dist/tools/trigger-long-running-operation.js +65 -0
- package/dist/tools/trigger-sampling-request-async.js +174 -0
- package/dist/tools/trigger-sampling-request.js +77 -0
- package/dist/tools/trigger-url-elicitation.js +169 -0
- package/dist/transports/in-memory-event-store.js +44 -0
- package/dist/transports/listen.js +36 -0
- package/dist/transports/sse.js +103 -0
- package/dist/transports/stdio.js +48 -0
- package/dist/transports/streamableHttp.js +240 -0
- package/dist/version.js +35 -0
- package/package.json +32 -13
- package/dist/everything.js +0 -361
- package/dist/sse.js +0 -24
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { SubscribeRequestSchema, UnsubscribeRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
|
|
2
|
+
// Track subscriber session id lists by URI
|
|
3
|
+
const subscriptions = new Map();
|
|
4
|
+
// Interval to send notifications to subscribers
|
|
5
|
+
const subsUpdateIntervals = new Map();
|
|
6
|
+
/**
|
|
7
|
+
* Sets up the subscription and unsubscription handlers for the provided server.
|
|
8
|
+
*
|
|
9
|
+
* The function defines two request handlers:
|
|
10
|
+
* 1. A `Subscribe` handler that allows clients to subscribe to specific resource URIs.
|
|
11
|
+
* 2. An `Unsubscribe` handler that allows clients to unsubscribe from specific resource URIs.
|
|
12
|
+
*
|
|
13
|
+
* The `Subscribe` handler performs the following actions:
|
|
14
|
+
* - Extracts the URI and session ID from the request.
|
|
15
|
+
* - Logs a message acknowledging the subscription request.
|
|
16
|
+
* - Updates the internal tracking of subscribers for the given URI.
|
|
17
|
+
*
|
|
18
|
+
* The `Unsubscribe` handler performs the following actions:
|
|
19
|
+
* - Extracts the URI and session ID from the request.
|
|
20
|
+
* - Logs a message acknowledging the unsubscription request.
|
|
21
|
+
* - Removes the subscriber for the specified URI.
|
|
22
|
+
*
|
|
23
|
+
* @param {McpServer} server - The server instance to which subscription handlers will be attached.
|
|
24
|
+
*/
|
|
25
|
+
export const setSubscriptionHandlers = (server) => {
|
|
26
|
+
// Set the subscription handler
|
|
27
|
+
server.server.setRequestHandler(SubscribeRequestSchema, async (request, extra) => {
|
|
28
|
+
// Get the URI to subscribe to
|
|
29
|
+
const { uri } = request.params;
|
|
30
|
+
// Get the session id (can be undefined for stdio)
|
|
31
|
+
const sessionId = extra.sessionId;
|
|
32
|
+
// Acknowledge the subscribe request
|
|
33
|
+
await server.sendLoggingMessage({
|
|
34
|
+
level: "info",
|
|
35
|
+
data: `Received Subscribe Resource request for URI: ${uri} ${sessionId ? `from session ${sessionId}` : ""}`,
|
|
36
|
+
}, sessionId);
|
|
37
|
+
// Get the subscribers for this URI
|
|
38
|
+
const subscribers = subscriptions.has(uri)
|
|
39
|
+
? subscriptions.get(uri)
|
|
40
|
+
: new Set();
|
|
41
|
+
subscribers.add(sessionId);
|
|
42
|
+
subscriptions.set(uri, subscribers);
|
|
43
|
+
return {};
|
|
44
|
+
});
|
|
45
|
+
// Set the unsubscription handler
|
|
46
|
+
server.server.setRequestHandler(UnsubscribeRequestSchema, async (request, extra) => {
|
|
47
|
+
// Get the URI to subscribe to
|
|
48
|
+
const { uri } = request.params;
|
|
49
|
+
// Get the session id (can be undefined for stdio)
|
|
50
|
+
const sessionId = extra.sessionId;
|
|
51
|
+
// Acknowledge the subscribe request
|
|
52
|
+
await server.sendLoggingMessage({
|
|
53
|
+
level: "info",
|
|
54
|
+
data: `Received Unsubscribe Resource request: ${uri} ${sessionId ? `from session ${sessionId}` : ""}`,
|
|
55
|
+
}, sessionId);
|
|
56
|
+
// Remove the subscriber
|
|
57
|
+
if (subscriptions.has(uri)) {
|
|
58
|
+
const subscribers = subscriptions.get(uri);
|
|
59
|
+
if (subscribers.has(sessionId))
|
|
60
|
+
subscribers.delete(sessionId);
|
|
61
|
+
}
|
|
62
|
+
return {};
|
|
63
|
+
});
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Sends simulated resource update notifications to the subscribed client.
|
|
67
|
+
*
|
|
68
|
+
* Iterates the URIs in `subscriptions` and emits a
|
|
69
|
+
* `notifications/resources/updated` notification for each URI the given
|
|
70
|
+
* sessionId is subscribed to.
|
|
71
|
+
*
|
|
72
|
+
* @param {McpServer} server - The server instance used to send notifications.
|
|
73
|
+
* @param {string | undefined} sessionId - The session ID of the client to check for subscriptions.
|
|
74
|
+
* @returns {Promise<void>} Resolves once all applicable notifications are sent.
|
|
75
|
+
*/
|
|
76
|
+
const sendSimulatedResourceUpdates = async (server, sessionId) => {
|
|
77
|
+
// Search all URIs for ones this client is subscribed to
|
|
78
|
+
for (const uri of subscriptions.keys()) {
|
|
79
|
+
const subscribers = subscriptions.get(uri);
|
|
80
|
+
// If this client is subscribed, send the notification
|
|
81
|
+
if (subscribers.has(sessionId)) {
|
|
82
|
+
await server.server.notification({
|
|
83
|
+
method: "notifications/resources/updated",
|
|
84
|
+
params: { uri },
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* Starts the process of simulating resource updates and sending server notifications
|
|
91
|
+
* to the client for the resources they are subscribed to. If the update interval is
|
|
92
|
+
* already active, invoking this function will not start another interval.
|
|
93
|
+
*
|
|
94
|
+
* @param server
|
|
95
|
+
* @param sessionId
|
|
96
|
+
*/
|
|
97
|
+
export const beginSimulatedResourceUpdates = (server, sessionId) => {
|
|
98
|
+
if (!subsUpdateIntervals.has(sessionId)) {
|
|
99
|
+
// Send once immediately, then every 5 seconds. Fire-and-forget: this
|
|
100
|
+
// function is synchronous by contract (its callers start a background
|
|
101
|
+
// simulation), so neither send can be awaited. A send that fails (e.g. the
|
|
102
|
+
// transport closed before the updates were stopped) is logged rather than
|
|
103
|
+
// left to become an unhandled rejection.
|
|
104
|
+
const send = () => sendSimulatedResourceUpdates(server, sessionId).catch((error) => console.error("Simulated resource update failed:", error));
|
|
105
|
+
void send();
|
|
106
|
+
// Set the interval to send later resource update notifications to this client
|
|
107
|
+
subsUpdateIntervals.set(sessionId, setInterval(() => void send(), 5000));
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
/**
|
|
111
|
+
* Stops simulated resource updates for a given session.
|
|
112
|
+
*
|
|
113
|
+
* This function halts any active intervals associated with the provided session ID
|
|
114
|
+
* and removes the session's corresponding entries from resource management collections.
|
|
115
|
+
* Session ID can be undefined for stdio.
|
|
116
|
+
*
|
|
117
|
+
* @param {string} [sessionId]
|
|
118
|
+
*/
|
|
119
|
+
export const stopSimulatedResourceUpdates = (sessionId) => {
|
|
120
|
+
// Remove active intervals
|
|
121
|
+
if (subsUpdateIntervals.has(sessionId)) {
|
|
122
|
+
const subsUpdateInterval = subsUpdateIntervals.get(sessionId);
|
|
123
|
+
clearInterval(subsUpdateInterval);
|
|
124
|
+
subsUpdateIntervals.delete(sessionId);
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
/**
|
|
128
|
+
* Removes a session from every URI's subscriber set, dropping any URI entry
|
|
129
|
+
* that ends up with no remaining subscribers.
|
|
130
|
+
*
|
|
131
|
+
* A session that disconnects without explicitly unsubscribing otherwise stays
|
|
132
|
+
* in `subscriptions` for the life of the process. Call this from the
|
|
133
|
+
* transport's `cleanup(sessionId)` when a session ends.
|
|
134
|
+
*
|
|
135
|
+
* @param {string} [sessionId]
|
|
136
|
+
*/
|
|
137
|
+
export const removeSubscriber = (sessionId) => {
|
|
138
|
+
for (const [uri, subscribers] of subscriptions) {
|
|
139
|
+
subscribers.delete(sessionId);
|
|
140
|
+
if (subscribers.size === 0) {
|
|
141
|
+
subscriptions.delete(uri);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
};
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { ResourceTemplate, } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
+
import { completable } from "@modelcontextprotocol/sdk/server/completable.js";
|
|
4
|
+
// Resource types
|
|
5
|
+
export const RESOURCE_TYPE_TEXT = "Text";
|
|
6
|
+
export const RESOURCE_TYPE_BLOB = "Blob";
|
|
7
|
+
export const RESOURCE_TYPES = [
|
|
8
|
+
RESOURCE_TYPE_TEXT,
|
|
9
|
+
RESOURCE_TYPE_BLOB,
|
|
10
|
+
];
|
|
11
|
+
/**
|
|
12
|
+
* A completer function for resource types.
|
|
13
|
+
*
|
|
14
|
+
* This variable provides functionality to perform autocompletion for the resource types based on user input.
|
|
15
|
+
* It uses a schema description to validate the input and filters through a predefined list of resource types
|
|
16
|
+
* to return suggestions that start with the given input.
|
|
17
|
+
*
|
|
18
|
+
* The input value is expected to be a string representing the type of resource to fetch.
|
|
19
|
+
* The completion logic matches the input against available resource types.
|
|
20
|
+
*/
|
|
21
|
+
export const resourceTypeCompleter = completable(z.string().describe("Type of resource to fetch"), (value) => {
|
|
22
|
+
return RESOURCE_TYPES.filter((t) => t.startsWith(value));
|
|
23
|
+
});
|
|
24
|
+
/**
|
|
25
|
+
* A completer function for resource IDs as strings.
|
|
26
|
+
*
|
|
27
|
+
* The `resourceIdCompleter` accepts a string input representing the ID of a text resource
|
|
28
|
+
* and validates whether the provided value corresponds to an integer resource ID.
|
|
29
|
+
*
|
|
30
|
+
* NOTE: Currently, prompt arguments can only be strings since type is not field of `PromptArgument`
|
|
31
|
+
* Consequently, we must define it as a string and convert the argument to number before using it
|
|
32
|
+
* https://modelcontextprotocol.io/specification/2025-11-25/schema#promptargument
|
|
33
|
+
*
|
|
34
|
+
* If the value is a valid integer, it returns the value within an array.
|
|
35
|
+
* Otherwise, it returns an empty array.
|
|
36
|
+
*
|
|
37
|
+
* The input string is first transformed into a number and checked to ensure it is an integer.
|
|
38
|
+
* This helps validate and suggest appropriate resource IDs.
|
|
39
|
+
*/
|
|
40
|
+
export const resourceIdForPromptCompleter = completable(z.string().describe("ID of the text resource to fetch"), (value) => {
|
|
41
|
+
const resourceId = Number(value);
|
|
42
|
+
return Number.isInteger(resourceId) && resourceId > 0 ? [value] : [];
|
|
43
|
+
});
|
|
44
|
+
/**
|
|
45
|
+
* A callback function that acts as a completer for resource ID values, validating and returning
|
|
46
|
+
* the input value as part of a resource template.
|
|
47
|
+
*
|
|
48
|
+
* @typedef {CompleteResourceTemplateCallback}
|
|
49
|
+
* @param {string} value - The input string value to be evaluated as a resource ID.
|
|
50
|
+
* @returns {string[]} Returns an array containing the input value if it represents a positive
|
|
51
|
+
* integer resource ID, otherwise returns an empty array.
|
|
52
|
+
*/
|
|
53
|
+
export const resourceIdForResourceTemplateCompleter = (value) => {
|
|
54
|
+
const resourceId = Number(value);
|
|
55
|
+
return Number.isInteger(resourceId) && resourceId > 0 ? [value] : [];
|
|
56
|
+
};
|
|
57
|
+
const uriBase = "demo://resource/dynamic";
|
|
58
|
+
const textUriBase = `${uriBase}/text`;
|
|
59
|
+
const blobUriBase = `${uriBase}/blob`;
|
|
60
|
+
const textUriTemplate = `${textUriBase}/{resourceId}`;
|
|
61
|
+
const blobUriTemplate = `${blobUriBase}/{resourceId}`;
|
|
62
|
+
/**
|
|
63
|
+
* Create a dynamic text resource
|
|
64
|
+
* - Exposed for use by embedded resource prompt example
|
|
65
|
+
* @param uri
|
|
66
|
+
* @param resourceId
|
|
67
|
+
*/
|
|
68
|
+
export const textResource = (uri, resourceId) => {
|
|
69
|
+
const timestamp = new Date().toLocaleTimeString();
|
|
70
|
+
return {
|
|
71
|
+
uri: uri.toString(),
|
|
72
|
+
mimeType: "text/plain",
|
|
73
|
+
text: `Resource ${resourceId}: This is a plaintext resource created at ${timestamp}`,
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Create a dynamic blob resource
|
|
78
|
+
* - Exposed for use by embedded resource prompt example
|
|
79
|
+
* @param uri
|
|
80
|
+
* @param resourceId
|
|
81
|
+
*/
|
|
82
|
+
export const blobResource = (uri, resourceId) => {
|
|
83
|
+
const timestamp = new Date().toLocaleTimeString();
|
|
84
|
+
const resourceText = Buffer.from(`Resource ${resourceId}: This is a base64 blob created at ${timestamp}`).toString("base64");
|
|
85
|
+
return {
|
|
86
|
+
uri: uri.toString(),
|
|
87
|
+
mimeType: "application/octet-stream",
|
|
88
|
+
blob: resourceText,
|
|
89
|
+
};
|
|
90
|
+
};
|
|
91
|
+
/**
|
|
92
|
+
* Create a dynamic text resource URI
|
|
93
|
+
* - Exposed for use by embedded resource prompt example
|
|
94
|
+
* @param resourceId
|
|
95
|
+
*/
|
|
96
|
+
export const textResourceUri = (resourceId) => new URL(`${textUriBase}/${resourceId}`);
|
|
97
|
+
/**
|
|
98
|
+
* Create a dynamic blob resource URI
|
|
99
|
+
* - Exposed for use by embedded resource prompt example
|
|
100
|
+
* @param resourceId
|
|
101
|
+
*/
|
|
102
|
+
export const blobResourceUri = (resourceId) => new URL(`${blobUriBase}/${resourceId}`);
|
|
103
|
+
/**
|
|
104
|
+
* Parses the resource identifier from the provided variables and validates
|
|
105
|
+
* that it is a positive integer.
|
|
106
|
+
*
|
|
107
|
+
* The SDK only routes URIs that match the registered template to the
|
|
108
|
+
* resource handler, so by the time we get here the URI prefix is already
|
|
109
|
+
* known to be one of `textUriBase` / `blobUriBase`. Only the resourceId
|
|
110
|
+
* variable still needs validating.
|
|
111
|
+
*
|
|
112
|
+
* @param {URL} uri - The URI of the resource (used in the error message).
|
|
113
|
+
* @param {Record<string, unknown>} variables - Context variables including resourceId.
|
|
114
|
+
* @returns {number} The parsed and validated resource identifier as a positive integer.
|
|
115
|
+
* @throws {Error} If the resourceId is not a finite positive integer.
|
|
116
|
+
*/
|
|
117
|
+
const parseResourceId = (uri, variables) => {
|
|
118
|
+
const idxStr = String(variables.resourceId ?? "");
|
|
119
|
+
const idx = Number(idxStr);
|
|
120
|
+
if (Number.isFinite(idx) && Number.isInteger(idx) && idx > 0) {
|
|
121
|
+
return idx;
|
|
122
|
+
}
|
|
123
|
+
throw new Error(`Unknown resource: ${uri.toString()}`);
|
|
124
|
+
};
|
|
125
|
+
/**
|
|
126
|
+
* Register resource templates with the MCP server.
|
|
127
|
+
* - Text and blob resources, dynamically generated from the URI {resourceId} variable
|
|
128
|
+
* - Any finite positive integer is acceptable for the resourceId variable
|
|
129
|
+
* - List resources method will not return these resources
|
|
130
|
+
* - These are only accessible via template URIs
|
|
131
|
+
* - Both blob and text resources:
|
|
132
|
+
* - have content that is dynamically generated, including a timestamp
|
|
133
|
+
* - have different template URIs
|
|
134
|
+
* - Blob: "demo://resource/dynamic/blob/{resourceId}"
|
|
135
|
+
* - Text: "demo://resource/dynamic/text/{resourceId}"
|
|
136
|
+
*
|
|
137
|
+
* @param server
|
|
138
|
+
*/
|
|
139
|
+
export const registerResourceTemplates = (server) => {
|
|
140
|
+
// Register the text resource template
|
|
141
|
+
server.registerResource("Dynamic Text Resource", new ResourceTemplate(textUriTemplate, {
|
|
142
|
+
list: undefined,
|
|
143
|
+
complete: { resourceId: resourceIdForResourceTemplateCompleter },
|
|
144
|
+
}), {
|
|
145
|
+
mimeType: "text/plain",
|
|
146
|
+
description: "Plaintext dynamic resource fabricated from the {resourceId} variable, which must be an integer.",
|
|
147
|
+
}, async (uri, variables) => {
|
|
148
|
+
const resourceId = parseResourceId(uri, variables);
|
|
149
|
+
return {
|
|
150
|
+
contents: [textResource(uri, resourceId)],
|
|
151
|
+
};
|
|
152
|
+
});
|
|
153
|
+
// Register the blob resource template
|
|
154
|
+
server.registerResource("Dynamic Blob Resource", new ResourceTemplate(blobUriTemplate, {
|
|
155
|
+
list: undefined,
|
|
156
|
+
complete: { resourceId: resourceIdForResourceTemplateCompleter },
|
|
157
|
+
}), {
|
|
158
|
+
mimeType: "application/octet-stream",
|
|
159
|
+
description: "Binary (base64) dynamic resource fabricated from the {resourceId} variable, which must be an integer.",
|
|
160
|
+
}, async (uri, variables) => {
|
|
161
|
+
const resourceId = parseResourceId(uri, variables);
|
|
162
|
+
return {
|
|
163
|
+
contents: [blobResource(uri, resourceId)],
|
|
164
|
+
};
|
|
165
|
+
});
|
|
166
|
+
};
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { InMemoryTaskStore, InMemoryTaskMessageQueue, } from "@modelcontextprotocol/sdk/experimental/tasks";
|
|
3
|
+
import { setSubscriptionHandlers, stopSimulatedResourceUpdates, removeSubscriber, } from "../resources/subscriptions.js";
|
|
4
|
+
import { registerConditionalTools, registerTools } from "../tools/index.js";
|
|
5
|
+
import { registerResources, readInstructions } from "../resources/index.js";
|
|
6
|
+
import { registerPrompts } from "../prompts/index.js";
|
|
7
|
+
import { stopSimulatedLogging } from "./logging.js";
|
|
8
|
+
import { syncRoots } from "./roots.js";
|
|
9
|
+
import { SERVER_VERSION } from "../version.js";
|
|
10
|
+
/**
|
|
11
|
+
* Server Factory
|
|
12
|
+
*
|
|
13
|
+
* This function initializes a `McpServer` with specific capabilities and instructions,
|
|
14
|
+
* registers tools, resources, and prompts, and configures resource subscription handlers.
|
|
15
|
+
*
|
|
16
|
+
* @returns {ServerFactoryResponse} An object containing the server instance, and a `cleanup`
|
|
17
|
+
* function for handling server-side cleanup when a session ends.
|
|
18
|
+
*
|
|
19
|
+
* Properties of the returned object:
|
|
20
|
+
* - `server` {Object}: The initialized server instance.
|
|
21
|
+
* - `cleanup` {Function}: Function to perform cleanup operations for a closing session.
|
|
22
|
+
*/
|
|
23
|
+
export const createServer = () => {
|
|
24
|
+
// Read the server instructions
|
|
25
|
+
const instructions = readInstructions();
|
|
26
|
+
// Create task store and message queue for task support
|
|
27
|
+
const taskStore = new InMemoryTaskStore();
|
|
28
|
+
const taskMessageQueue = new InMemoryTaskMessageQueue();
|
|
29
|
+
let initializeTimeout = null;
|
|
30
|
+
// Create the server
|
|
31
|
+
const server = new McpServer({
|
|
32
|
+
name: "mcp-servers/everything",
|
|
33
|
+
title: "Everything Reference Server",
|
|
34
|
+
version: SERVER_VERSION,
|
|
35
|
+
}, {
|
|
36
|
+
capabilities: {
|
|
37
|
+
tools: {
|
|
38
|
+
listChanged: true,
|
|
39
|
+
},
|
|
40
|
+
prompts: {
|
|
41
|
+
listChanged: true,
|
|
42
|
+
},
|
|
43
|
+
resources: {
|
|
44
|
+
subscribe: true,
|
|
45
|
+
listChanged: true,
|
|
46
|
+
},
|
|
47
|
+
logging: {},
|
|
48
|
+
tasks: {
|
|
49
|
+
list: {},
|
|
50
|
+
cancel: {},
|
|
51
|
+
requests: {
|
|
52
|
+
tools: {
|
|
53
|
+
call: {},
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
instructions,
|
|
59
|
+
taskStore,
|
|
60
|
+
taskMessageQueue,
|
|
61
|
+
});
|
|
62
|
+
// Register the tools
|
|
63
|
+
registerTools(server);
|
|
64
|
+
// Register the resources
|
|
65
|
+
registerResources(server);
|
|
66
|
+
// Register the prompts
|
|
67
|
+
registerPrompts(server);
|
|
68
|
+
// Set resource subscription handlers
|
|
69
|
+
setSubscriptionHandlers(server);
|
|
70
|
+
// Perform post-initialization operations
|
|
71
|
+
server.server.oninitialized = async () => {
|
|
72
|
+
// Register conditional tools now that client capabilities are known.
|
|
73
|
+
// This finishes before the `notifications/initialized` handler finishes.
|
|
74
|
+
registerConditionalTools(server);
|
|
75
|
+
// Sync roots if the client supports them.
|
|
76
|
+
// This is delayed until after the `notifications/initialized` handler finishes,
|
|
77
|
+
// otherwise, the request gets lost.
|
|
78
|
+
const sessionId = server.server.transport?.sessionId;
|
|
79
|
+
initializeTimeout = setTimeout(() => syncRoots(server, sessionId), 350);
|
|
80
|
+
};
|
|
81
|
+
// Return the ServerFactoryResponse
|
|
82
|
+
return {
|
|
83
|
+
server,
|
|
84
|
+
cleanup: (sessionId) => {
|
|
85
|
+
// Stop any simulated logging or resource updates that may have been initiated.
|
|
86
|
+
stopSimulatedLogging(sessionId);
|
|
87
|
+
stopSimulatedResourceUpdates(sessionId);
|
|
88
|
+
removeSubscriber(sessionId);
|
|
89
|
+
// Clean up task store timers
|
|
90
|
+
taskStore.cleanup();
|
|
91
|
+
if (initializeTimeout)
|
|
92
|
+
clearTimeout(initializeTimeout);
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
};
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Map session ID to the interval for sending logging messages to the client
|
|
2
|
+
const logsUpdateIntervals = new Map();
|
|
3
|
+
/**
|
|
4
|
+
* Initiates a simulated logging process by sending random log messages to the client at a
|
|
5
|
+
* fixed interval. Each log message contains a random logging level and optional session ID.
|
|
6
|
+
*
|
|
7
|
+
* @param {McpServer} server - The server instance responsible for handling the logging messages.
|
|
8
|
+
* @param {string | undefined} sessionId - An optional identifier for the session. If provided,
|
|
9
|
+
* the session ID will be appended to log messages.
|
|
10
|
+
*/
|
|
11
|
+
export const beginSimulatedLogging = (server, sessionId) => {
|
|
12
|
+
const maybeAppendSessionId = sessionId ? ` - SessionId ${sessionId}` : "";
|
|
13
|
+
const messages = [
|
|
14
|
+
{ level: "debug", data: `Debug-level message${maybeAppendSessionId}` },
|
|
15
|
+
{ level: "info", data: `Info-level message${maybeAppendSessionId}` },
|
|
16
|
+
{ level: "notice", data: `Notice-level message${maybeAppendSessionId}` },
|
|
17
|
+
{
|
|
18
|
+
level: "warning",
|
|
19
|
+
data: `Warning-level message${maybeAppendSessionId}`,
|
|
20
|
+
},
|
|
21
|
+
{ level: "error", data: `Error-level message${maybeAppendSessionId}` },
|
|
22
|
+
{
|
|
23
|
+
level: "critical",
|
|
24
|
+
data: `Critical-level message${maybeAppendSessionId}`,
|
|
25
|
+
},
|
|
26
|
+
{ level: "alert", data: `Alert level-message${maybeAppendSessionId}` },
|
|
27
|
+
{
|
|
28
|
+
level: "emergency",
|
|
29
|
+
data: `Emergency-level message${maybeAppendSessionId}`,
|
|
30
|
+
},
|
|
31
|
+
];
|
|
32
|
+
/**
|
|
33
|
+
* Send a simulated logging message to the client
|
|
34
|
+
*/
|
|
35
|
+
const sendSimulatedLoggingMessage = async (sessionId) => {
|
|
36
|
+
// By using the `sendLoggingMessage` function to send the message, we
|
|
37
|
+
// ensure that the client's chosen logging level will be respected
|
|
38
|
+
await server.sendLoggingMessage(messages[Math.floor(Math.random() * messages.length)], sessionId);
|
|
39
|
+
};
|
|
40
|
+
// Set the interval to send later logging messages to this client
|
|
41
|
+
/* v8 ignore else -- toggle-simulated-logging tracks the sessions it started and never begins one twice */
|
|
42
|
+
if (!logsUpdateIntervals.has(sessionId)) {
|
|
43
|
+
// Send once immediately, then every 5 seconds. Fire-and-forget: this
|
|
44
|
+
// function is synchronous by contract (it starts a background simulation),
|
|
45
|
+
// so neither send can be awaited. A send that fails (e.g. the transport
|
|
46
|
+
// closed before `stopSimulatedLogging`) is logged rather than left to
|
|
47
|
+
// become an unhandled rejection.
|
|
48
|
+
const send = () => sendSimulatedLoggingMessage(sessionId).catch((error) => console.error("Simulated logging message failed:", error));
|
|
49
|
+
void send();
|
|
50
|
+
// Send a randomly-leveled log message every 5 seconds
|
|
51
|
+
logsUpdateIntervals.set(sessionId, setInterval(() => void send(), 5000));
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Stops the simulated logging process for a given session.
|
|
56
|
+
*
|
|
57
|
+
* This function halts the periodic logging updates associated with the specified
|
|
58
|
+
* session ID by clearing the interval and removing the session's tracking
|
|
59
|
+
* reference. Session ID can be undefined for stdio.
|
|
60
|
+
*
|
|
61
|
+
* @param {string} [sessionId] - The optional unique identifier of the session.
|
|
62
|
+
*/
|
|
63
|
+
export const stopSimulatedLogging = (sessionId) => {
|
|
64
|
+
// Remove active intervals
|
|
65
|
+
if (logsUpdateIntervals.has(sessionId)) {
|
|
66
|
+
const logsUpdateInterval = logsUpdateIntervals.get(sessionId);
|
|
67
|
+
clearInterval(logsUpdateInterval);
|
|
68
|
+
logsUpdateIntervals.delete(sessionId);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { RootsListChangedNotificationSchema, } from "@modelcontextprotocol/sdk/types.js";
|
|
2
|
+
// Track roots by session id
|
|
3
|
+
export const roots = new Map();
|
|
4
|
+
/**
|
|
5
|
+
* Get the latest the client roots list for the session.
|
|
6
|
+
*
|
|
7
|
+
* - Request and cache the roots list for the session if it has not been fetched before.
|
|
8
|
+
* - Return the cached roots list for the session if it exists.
|
|
9
|
+
*
|
|
10
|
+
* When requesting the roots list for a session, it also sets up a `roots/list_changed`
|
|
11
|
+
* notification handler. This ensures that updates are automatically fetched and handled
|
|
12
|
+
* in real-time.
|
|
13
|
+
*
|
|
14
|
+
* This function is idempotent. It should only request roots from the client once per session,
|
|
15
|
+
* returning the cached version thereafter.
|
|
16
|
+
*
|
|
17
|
+
* @param {McpServer} server - An instance of the MCP server used to communicate with the client.
|
|
18
|
+
* @param {string} [sessionId] - An optional session id used to associate the roots list with a specific client session.
|
|
19
|
+
*
|
|
20
|
+
* @throws {Error} In case of a failure to request the roots from the client, an error log message is sent.
|
|
21
|
+
*/
|
|
22
|
+
export const syncRoots = async (server, sessionId) => {
|
|
23
|
+
const clientCapabilities = server.server.getClientCapabilities() || {};
|
|
24
|
+
const clientSupportsRoots = clientCapabilities?.roots !== undefined;
|
|
25
|
+
// Fetch the roots list for this client
|
|
26
|
+
if (clientSupportsRoots) {
|
|
27
|
+
// Function to request the updated roots list from the client
|
|
28
|
+
const requestRoots = async () => {
|
|
29
|
+
try {
|
|
30
|
+
// Request the updated roots list from the client
|
|
31
|
+
const response = await server.server.listRoots();
|
|
32
|
+
/* v8 ignore else -- unreachable: listRoots() validates the reply against ListRootsResultSchema, which requires `roots`, and rejects anything else */
|
|
33
|
+
if (response && "roots" in response) {
|
|
34
|
+
// Store the roots list for this client
|
|
35
|
+
roots.set(sessionId, response.roots);
|
|
36
|
+
// Notify the client of roots received
|
|
37
|
+
await server.sendLoggingMessage({
|
|
38
|
+
level: "info",
|
|
39
|
+
logger: "everything-server",
|
|
40
|
+
data: `Roots updated: ${response?.roots?.length} root(s) received from client`,
|
|
41
|
+
}, sessionId);
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
await server.sendLoggingMessage({
|
|
45
|
+
level: "info",
|
|
46
|
+
logger: "everything-server",
|
|
47
|
+
data: "Client returned no roots set",
|
|
48
|
+
}, sessionId);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
console.error(`Failed to request roots from client ${sessionId}: ${
|
|
53
|
+
/* v8 ignore start -- the SDK always rejects listRoots() with an Error (McpError) */
|
|
54
|
+
error instanceof Error ? error.message : String(error)
|
|
55
|
+
/* v8 ignore stop */
|
|
56
|
+
}`);
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
// If the roots have not been synced for this client,
|
|
60
|
+
// set notification handler and request initial roots
|
|
61
|
+
if (!roots.has(sessionId)) {
|
|
62
|
+
// Set the list changed notification handler
|
|
63
|
+
server.server.setNotificationHandler(RootsListChangedNotificationSchema, requestRoots);
|
|
64
|
+
// Request the initial roots list immediately
|
|
65
|
+
await requestRoots();
|
|
66
|
+
}
|
|
67
|
+
// Return the roots list for this client
|
|
68
|
+
return roots.get(sessionId);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
@@ -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
|
+
};
|