@modelcontextprotocol/server-everything 0.6.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +121 -72
  2. package/dist/docs/architecture.md +44 -0
  3. package/dist/docs/extension.md +23 -0
  4. package/dist/docs/features.md +105 -0
  5. package/dist/docs/how-it-works.md +45 -0
  6. package/dist/docs/instructions.md +37 -0
  7. package/dist/docs/startup.md +76 -0
  8. package/dist/docs/structure.md +212 -0
  9. package/dist/index.js +73 -16
  10. package/dist/prompts/args.js +34 -0
  11. package/dist/prompts/completions.js +52 -0
  12. package/dist/prompts/index.js +15 -0
  13. package/dist/prompts/resource.js +60 -0
  14. package/dist/prompts/simple.js +23 -0
  15. package/dist/resources/files.js +83 -0
  16. package/dist/resources/index.js +33 -0
  17. package/dist/resources/session.js +62 -0
  18. package/dist/resources/subscriptions.js +144 -0
  19. package/dist/resources/templates.js +166 -0
  20. package/dist/server/index.js +95 -0
  21. package/dist/server/logging.js +70 -0
  22. package/dist/server/roots.js +70 -0
  23. package/dist/tools/echo.js +35 -0
  24. package/dist/tools/get-annotated-message.js +89 -0
  25. package/dist/tools/get-env.js +34 -0
  26. package/dist/tools/get-resource-links.js +68 -0
  27. package/dist/tools/get-resource-reference.js +81 -0
  28. package/dist/tools/get-roots-list.js +77 -0
  29. package/dist/tools/get-structured-content.js +78 -0
  30. package/dist/tools/get-sum.js +46 -0
  31. package/dist/tools/get-tiny-image.js +47 -0
  32. package/dist/tools/gzip-file-as-resource.js +194 -0
  33. package/dist/tools/index.js +52 -0
  34. package/dist/tools/simulate-research-query.js +251 -0
  35. package/dist/tools/toggle-simulated-logging.js +47 -0
  36. package/dist/tools/toggle-subscriber-updates.js +50 -0
  37. package/dist/tools/trigger-elicitation-request-async.js +227 -0
  38. package/dist/tools/trigger-elicitation-request.js +222 -0
  39. package/dist/tools/trigger-long-running-operation.js +65 -0
  40. package/dist/tools/trigger-sampling-request-async.js +174 -0
  41. package/dist/tools/trigger-sampling-request.js +77 -0
  42. package/dist/tools/trigger-url-elicitation.js +169 -0
  43. package/dist/transports/in-memory-event-store.js +44 -0
  44. package/dist/transports/listen.js +36 -0
  45. package/dist/transports/sse.js +103 -0
  46. package/dist/transports/stdio.js +48 -0
  47. package/dist/transports/streamableHttp.js +240 -0
  48. package/dist/version.js +35 -0
  49. package/package.json +32 -13
  50. package/dist/everything.js +0 -361
  51. package/dist/sse.js +0 -24
@@ -0,0 +1,34 @@
1
+ // Tool configuration
2
+ const name = "get-env";
3
+ const config = {
4
+ title: "Print Environment Tool",
5
+ description: "Returns all environment variables, helpful for debugging MCP server configuration",
6
+ inputSchema: {},
7
+ annotations: {
8
+ readOnlyHint: true,
9
+ destructiveHint: false,
10
+ idempotentHint: true,
11
+ openWorldHint: false,
12
+ },
13
+ };
14
+ /**
15
+ * Registers the 'get-env' tool.
16
+ *
17
+ * The registered tool Retrieves and returns the environment variables
18
+ * of the current process as a JSON-formatted string encapsulated in a text response.
19
+ *
20
+ * @param {McpServer} server - The McpServer instance where the tool will be registered.
21
+ * @returns {void}
22
+ */
23
+ export const registerGetEnvTool = (server) => {
24
+ server.registerTool(name, config, async () => {
25
+ return {
26
+ content: [
27
+ {
28
+ type: "text",
29
+ text: JSON.stringify(process.env, null, 2),
30
+ },
31
+ ],
32
+ };
33
+ });
34
+ };
@@ -0,0 +1,68 @@
1
+ import { z } from "zod";
2
+ import { textResource, textResourceUri, blobResourceUri, blobResource, } from "../resources/templates.js";
3
+ // Tool input schema
4
+ const GetResourceLinksSchema = z.object({
5
+ count: z
6
+ .number()
7
+ .min(1)
8
+ .max(10)
9
+ .default(3)
10
+ .describe("Number of resource links to return (1-10)"),
11
+ });
12
+ // Tool configuration
13
+ const name = "get-resource-links";
14
+ const config = {
15
+ title: "Get Resource Links Tool",
16
+ description: "Returns up to ten resource links that reference different types of resources",
17
+ inputSchema: GetResourceLinksSchema,
18
+ annotations: {
19
+ readOnlyHint: true,
20
+ destructiveHint: false,
21
+ idempotentHint: true,
22
+ openWorldHint: false,
23
+ },
24
+ };
25
+ /**
26
+ * Registers the 'get-resource-reference' tool.
27
+ *
28
+ * The registered tool retrieves a specified number of resource links and their metadata.
29
+ * Resource links are dynamically generated as either text or binary blob resources,
30
+ * based on their ID being even or odd.
31
+
32
+ * The response contains a "text" introductory block and multiple "resource_link" blocks.
33
+ *
34
+ * @param {McpServer} server - The McpServer instance where the tool will be registered.
35
+ */
36
+ export const registerGetResourceLinksTool = (server) => {
37
+ server.registerTool(name, config, async (args) => {
38
+ const { count } = GetResourceLinksSchema.parse(args);
39
+ // Add intro text content block
40
+ const content = [];
41
+ content.push({
42
+ type: "text",
43
+ text: `Here are ${count} resource links to resources available in this server:`,
44
+ });
45
+ // Create resource link content blocks
46
+ for (let resourceId = 1; resourceId <= count; resourceId++) {
47
+ // Get resource uri for text or blob resource based on odd/even resourceId
48
+ const isOdd = resourceId % 2 === 0;
49
+ const uri = isOdd
50
+ ? textResourceUri(resourceId)
51
+ : blobResourceUri(resourceId);
52
+ // Get resource based on the resource type
53
+ const resource = isOdd
54
+ ? textResource(uri, resourceId)
55
+ : blobResource(uri, resourceId);
56
+ content.push({
57
+ type: "resource_link",
58
+ uri: resource.uri,
59
+ name: `${isOdd ? "Text" : "Blob"} Resource ${resourceId}`,
60
+ description: `Resource ${resourceId}: ${resource.mimeType === "text/plain"
61
+ ? "plaintext resource"
62
+ : "binary blob resource"}`,
63
+ mimeType: resource.mimeType,
64
+ });
65
+ }
66
+ return { content };
67
+ });
68
+ };
@@ -0,0 +1,81 @@
1
+ import { z } from "zod";
2
+ import { textResource, textResourceUri, blobResourceUri, blobResource, RESOURCE_TYPE_BLOB, RESOURCE_TYPE_TEXT, RESOURCE_TYPES, } from "../resources/templates.js";
3
+ // Tool input schema
4
+ const GetResourceReferenceSchema = z.object({
5
+ resourceType: z
6
+ .enum([RESOURCE_TYPE_TEXT, RESOURCE_TYPE_BLOB])
7
+ .default(RESOURCE_TYPE_TEXT),
8
+ resourceId: z
9
+ .number()
10
+ .default(1)
11
+ .describe("ID of the text resource to fetch"),
12
+ });
13
+ // Tool configuration
14
+ const name = "get-resource-reference";
15
+ const config = {
16
+ title: "Get Resource Reference Tool",
17
+ description: "Returns a resource reference that can be used by MCP clients",
18
+ inputSchema: GetResourceReferenceSchema,
19
+ annotations: {
20
+ readOnlyHint: true,
21
+ destructiveHint: false,
22
+ idempotentHint: true,
23
+ openWorldHint: false,
24
+ },
25
+ };
26
+ /**
27
+ * Registers the 'get-resource-reference' tool.
28
+ *
29
+ * The registered tool validates and processes arguments for retrieving a resource
30
+ * reference. Supported resource types include predefined `RESOURCE_TYPE_TEXT` and
31
+ * `RESOURCE_TYPE_BLOB`. The retrieved resource's reference will include the resource
32
+ * ID, type, and its associated URI.
33
+ *
34
+ * The tool performs the following operations:
35
+ * 1. Validates the `resourceType` argument to ensure it matches a supported type.
36
+ * 2. Validates the `resourceId` argument to ensure it is a finite positive integer.
37
+ * 3. Constructs a URI for the resource based on its type (text or blob).
38
+ * 4. Retrieves the resource and returns it in a content block.
39
+ *
40
+ * @param {McpServer} server - The McpServer instance where the tool will be registered.
41
+ */
42
+ export const registerGetResourceReferenceTool = (server) => {
43
+ server.registerTool(name, config, async (args) => {
44
+ // Validate resource type argument
45
+ const { resourceType } = args;
46
+ /* v8 ignore next -- unreachable: the input schema's enum rejects any other resourceType before the handler runs */
47
+ if (!RESOURCE_TYPES.includes(resourceType)) {
48
+ throw new Error(`Invalid resourceType: ${args?.resourceType}. Must be ${RESOURCE_TYPE_TEXT} or ${RESOURCE_TYPE_BLOB}.`);
49
+ }
50
+ // Validate resourceId argument
51
+ const resourceId = Number(args?.resourceId);
52
+ if (!Number.isFinite(resourceId) ||
53
+ !Number.isInteger(resourceId) ||
54
+ resourceId < 1) {
55
+ throw new Error(`Invalid resourceId: ${args?.resourceId}. Must be a finite positive integer.`);
56
+ }
57
+ // Get resource based on the resource type
58
+ const uri = resourceType === RESOURCE_TYPE_TEXT
59
+ ? textResourceUri(resourceId)
60
+ : blobResourceUri(resourceId);
61
+ const resource = resourceType === RESOURCE_TYPE_TEXT
62
+ ? textResource(uri, resourceId)
63
+ : blobResource(uri, resourceId);
64
+ return {
65
+ content: [
66
+ {
67
+ type: "text",
68
+ text: `Returning resource reference for Resource ${resourceId}:`,
69
+ },
70
+ {
71
+ type: "resource",
72
+ resource: resource,
73
+ },
74
+ {
75
+ type: "text",
76
+ text: `You can access this resource using the URI: ${resource.uri}`,
77
+ },
78
+ ],
79
+ };
80
+ });
81
+ };
@@ -0,0 +1,77 @@
1
+ import { syncRoots } from "../server/roots.js";
2
+ // Tool configuration
3
+ const name = "get-roots-list";
4
+ const config = {
5
+ title: "Get Roots List Tool",
6
+ description: "Lists the current MCP roots provided by the client. Demonstrates the roots protocol capability even though this server doesn't access files.",
7
+ inputSchema: {},
8
+ annotations: {
9
+ readOnlyHint: true,
10
+ destructiveHint: false,
11
+ idempotentHint: true,
12
+ openWorldHint: false,
13
+ },
14
+ };
15
+ /**
16
+ * Registers the 'get-roots-list' tool.
17
+ *
18
+ * If the client does not support the roots capability, the tool is not registered.
19
+ *
20
+ * The registered tool interacts with the MCP roots capability, which enables the server to access
21
+ * information about the client's workspace directories or file system roots.
22
+ *
23
+ * When supported, the server automatically retrieves and formats the current list of roots from the
24
+ * client upon connection and whenever the client sends a `roots/list_changed` notification.
25
+ *
26
+ * Therefore, this tool displays the roots that the server currently knows about for the connected
27
+ * client. If for some reason the server never got the initial roots list, the tool will request the
28
+ * list from the client again.
29
+ *
30
+ * @param {McpServer} server - The McpServer instance where the tool will be registered.
31
+ */
32
+ export const registerGetRootsListTool = (server) => {
33
+ // Does client support roots?
34
+ const clientCapabilities = server.server.getClientCapabilities() || {};
35
+ const clientSupportsRoots = clientCapabilities.roots !== undefined;
36
+ // If so, register tool
37
+ if (clientSupportsRoots) {
38
+ server.registerTool(name, config, async (args, extra) => {
39
+ // Get the current rootsFetch the current roots list from the client if need be
40
+ const currentRoots = await syncRoots(server, extra.sessionId);
41
+ // Respond if client supports roots but doesn't have any configured
42
+ if (clientSupportsRoots &&
43
+ (!currentRoots || currentRoots.length === 0)) {
44
+ return {
45
+ content: [
46
+ {
47
+ type: "text",
48
+ text: "The client supports roots but no roots are currently configured.\n\n" +
49
+ "This could mean:\n" +
50
+ "1. The client hasn't provided any roots yet\n" +
51
+ "2. The client provided an empty roots list\n" +
52
+ "3. The roots configuration is still being loaded",
53
+ },
54
+ ],
55
+ };
56
+ }
57
+ // Create formatted response if there is a list of roots
58
+ const rootsList = currentRoots
59
+ ? currentRoots
60
+ .map((root, index) => {
61
+ return `${index + 1}. ${root.name || "Unnamed Root"}\n URI: ${root.uri}`;
62
+ })
63
+ .join("\n\n")
64
+ : "No roots found";
65
+ return {
66
+ content: [
67
+ {
68
+ type: "text",
69
+ text: `Current MCP Roots (${currentRoots.length} total):\n\n${rootsList}\n\n` +
70
+ "Note: This server demonstrates the roots protocol capability but doesn't actually access files. " +
71
+ "The roots are provided by the MCP client and can be used by servers that need file system access.",
72
+ },
73
+ ],
74
+ };
75
+ });
76
+ }
77
+ };
@@ -0,0 +1,78 @@
1
+ import { z } from "zod";
2
+ // Tool input schema
3
+ const GetStructuredContentInputSchema = {
4
+ location: z
5
+ .enum(["New York", "Chicago", "Los Angeles"])
6
+ .describe("Choose city"),
7
+ };
8
+ // Tool output schema
9
+ const GetStructuredContentOutputSchema = z.object({
10
+ temperature: z.number().describe("Temperature in celsius"),
11
+ conditions: z.string().describe("Weather conditions description"),
12
+ humidity: z.number().describe("Humidity percentage"),
13
+ });
14
+ // Tool configuration
15
+ const name = "get-structured-content";
16
+ const config = {
17
+ title: "Get Structured Content Tool",
18
+ description: "Returns structured content along with an output schema for client data validation",
19
+ inputSchema: GetStructuredContentInputSchema,
20
+ outputSchema: GetStructuredContentOutputSchema,
21
+ annotations: {
22
+ readOnlyHint: true,
23
+ destructiveHint: false,
24
+ idempotentHint: true,
25
+ openWorldHint: false,
26
+ },
27
+ };
28
+ /**
29
+ * Registers the 'get-structured-content' tool.
30
+ *
31
+ * The registered tool processes incoming arguments using a predefined input schema,
32
+ * generates structured content with weather information including temperature,
33
+ * conditions, and humidity, and returns both backward-compatible content blocks
34
+ * and structured content in the response.
35
+ *
36
+ * The response contains:
37
+ * - `content`: An array of content blocks, presented as JSON stringified objects.
38
+ * - `structuredContent`: A JSON structured representation of the weather data.
39
+ *
40
+ * @param {McpServer} server - The McpServer instance where the tool will be registered.
41
+ */
42
+ export const registerGetStructuredContentTool = (server) => {
43
+ server.registerTool(name, config, async (args) => {
44
+ // Get simulated weather for the chosen city
45
+ let weather;
46
+ switch (args.location) {
47
+ case "New York":
48
+ weather = {
49
+ temperature: 33,
50
+ conditions: "Cloudy",
51
+ humidity: 82,
52
+ };
53
+ break;
54
+ case "Chicago":
55
+ weather = {
56
+ temperature: 36,
57
+ conditions: "Light rain / drizzle",
58
+ humidity: 82,
59
+ };
60
+ break;
61
+ case "Los Angeles":
62
+ weather = {
63
+ temperature: 73,
64
+ conditions: "Sunny / Clear",
65
+ humidity: 48,
66
+ };
67
+ break;
68
+ }
69
+ const backwardCompatibleContentBlock = {
70
+ type: "text",
71
+ text: JSON.stringify(weather),
72
+ };
73
+ return {
74
+ content: [backwardCompatibleContentBlock],
75
+ structuredContent: weather,
76
+ };
77
+ });
78
+ };
@@ -0,0 +1,46 @@
1
+ import { z } from "zod";
2
+ // Tool input schema
3
+ const GetSumSchema = z.object({
4
+ a: z.number().describe("First number"),
5
+ b: z.number().describe("Second number"),
6
+ });
7
+ // Tool configuration
8
+ const name = "get-sum";
9
+ const config = {
10
+ title: "Get Sum Tool",
11
+ description: "Returns the sum of two numbers",
12
+ inputSchema: GetSumSchema,
13
+ annotations: {
14
+ readOnlyHint: true,
15
+ destructiveHint: false,
16
+ idempotentHint: true,
17
+ openWorldHint: false,
18
+ },
19
+ };
20
+ /**
21
+ * Registers the 'get-sum' tool.
22
+ **
23
+ * The registered tool processes input arguments, validates them using a predefined schema,
24
+ * calculates the sum of two numeric values, and returns the result in a content block.
25
+ *
26
+ * Expects input arguments to conform to a specific schema that includes two numeric properties, `a` and `b`.
27
+ * Validation is performed to ensure the input adheres to the expected structure before calculating the sum.
28
+ *
29
+ * The result is returned as a Promise resolving to an object containing the computed sum in a text format.
30
+ *
31
+ * @param {McpServer} server - The McpServer instance where the tool will be registered.
32
+ */
33
+ export const registerGetSumTool = (server) => {
34
+ server.registerTool(name, config, async (args) => {
35
+ const validatedArgs = GetSumSchema.parse(args);
36
+ const sum = validatedArgs.a + validatedArgs.b;
37
+ return {
38
+ content: [
39
+ {
40
+ type: "text",
41
+ text: `The sum of ${validatedArgs.a} and ${validatedArgs.b} is ${sum}.`,
42
+ },
43
+ ],
44
+ };
45
+ });
46
+ };
@@ -0,0 +1,47 @@
1
+ // A tiny encoded MCP logo image
2
+ export const MCP_TINY_IMAGE = "iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAKsGlDQ1BJQ0MgUHJvZmlsZQAASImVlwdUU+kSgOfe9JDQEiIgJfQmSCeAlBBaAAXpYCMkAUKJMRBU7MriClZURLCs6KqIgo0idizYFsWC3QVZBNR1sWDDlXeBQ9jdd9575805c+a7c+efmf+e/z9nLgCdKZDJMlF1gCxpjjwyyI8dn5DIJvUABRiY0kBdIMyWcSMiwgCTUft3+dgGyJC9YzuU69/f/1fREImzhQBIBMbJomxhFsbHMe0TyuQ5ALg9mN9kbo5siK9gzJRjDWL8ZIhTR7hviJOHGY8fjomO5GGsDUCmCQTyVACaKeZn5wpTsTw0f4ztpSKJFGPsGbyzsmaLMMbqgiUWI8N4KD8n+S95Uv+WM1mZUyBIVfLIXoaF7C/JlmUK5v+fn+N/S1amYrSGOaa0NHlwJGaxvpAHGbNDlSxNnhI+yhLRcPwwpymCY0ZZmM1LHGWRwD9UuTZzStgop0gC+co8OfzoURZnB0SNsnx2pLJWipzHHWWBfKyuIiNG6U8T85X589Ki40Y5VxI7ZZSzM6JCx2J4S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msXq+TaLPZ0AXgMRF2vMEqlQoJTSYTpNNpApvNZliv1/+BHDaZTAi2Wq1A3Ig0xmMej7+RcZjdbodUKkWAaDQK+GHjHPnImB88JrZIJAKFQgH2+z2BOczhcMiwRCIBgUAA+NN5BP6mj2DYff35gk6nA61WCzBn2JxO5wPM7/fLz4vD0E+OECfn8xl/0Gw2KbLxeAyLxQIsFgt8p75pDSO7h/HbpUWpewCike9WLpfB7XaDy+WCYrFI/slk8i0MnRRAUt46hPMI4vE4+Hw+ec7t9/44VgWigEeby+UgFArJWjUYOqhWG6x50rpcSfR6PVUfNOgEVRlTX0HhrZBKz4MZjUYWi8VoA+lc9H/VaRZYjBKrtXR8tlwumcFgeMWRbZpA9ORQWfVm8A/FsrLaxebd5wAAAABJRU5ErkJggg==";
3
+ // Tool configuration
4
+ const name = "get-tiny-image";
5
+ const config = {
6
+ title: "Get Tiny Image Tool",
7
+ description: "Returns a tiny MCP logo image.",
8
+ inputSchema: {},
9
+ annotations: {
10
+ readOnlyHint: true,
11
+ destructiveHint: false,
12
+ idempotentHint: true,
13
+ openWorldHint: false,
14
+ },
15
+ };
16
+ /**
17
+ * Registers the "get-tiny-image" tool.
18
+ *
19
+ * The registered tool returns a response containing a small image alongside some
20
+ * descriptive text.
21
+ *
22
+ * The response structure includes textual content before and after the image.
23
+ * The image is served as a PNG data type and represents the default MCP tiny image.
24
+ *
25
+ * @param server - The McpServer instance where the tool will be registered.
26
+ */
27
+ export const registerGetTinyImageTool = (server) => {
28
+ server.registerTool(name, config, async () => {
29
+ return {
30
+ content: [
31
+ {
32
+ type: "text",
33
+ text: "Here's the image you requested:",
34
+ },
35
+ {
36
+ type: "image",
37
+ data: MCP_TINY_IMAGE,
38
+ mimeType: "image/png",
39
+ },
40
+ {
41
+ type: "text",
42
+ text: "The image above is the MCP logo.",
43
+ },
44
+ ],
45
+ };
46
+ });
47
+ };
@@ -0,0 +1,194 @@
1
+ import { z } from "zod";
2
+ import { gzipSync } from "node:zlib";
3
+ import { getSessionResourceURI, registerSessionResource, } from "../resources/session.js";
4
+ // Maximum input file size - 10 MB default
5
+ const GZIP_MAX_FETCH_SIZE = Number(process.env.GZIP_MAX_FETCH_SIZE ?? String(10 * 1024 * 1024));
6
+ // Maximum fetch time - 30 seconds default.
7
+ const GZIP_MAX_FETCH_TIME_MILLIS = Number(process.env.GZIP_MAX_FETCH_TIME_MILLIS ?? String(30 * 1000));
8
+ // Comma-separated list of allowed domains. Empty means all domains are allowed.
9
+ const GZIP_ALLOWED_DOMAINS = (process.env.GZIP_ALLOWED_DOMAINS ?? "")
10
+ .split(",")
11
+ .map((d) => d.trim().toLowerCase())
12
+ .filter((d) => d.length > 0);
13
+ // Tool input schema
14
+ const GZipFileAsResourceSchema = z.object({
15
+ name: z.string().describe("Name of the output file").default("README.md.gz"),
16
+ data: z
17
+ .url()
18
+ .describe("URL or data URI of the file content to compress")
19
+ .default("https://raw.githubusercontent.com/modelcontextprotocol/servers/refs/heads/main/README.md"),
20
+ outputType: z
21
+ .enum(["resourceLink", "resource"])
22
+ .default("resourceLink")
23
+ .describe("How the resulting gzipped file should be returned. 'resourceLink' returns a link to a resource that can be read later, 'resource' returns a full resource object."),
24
+ });
25
+ // Tool configuration
26
+ const name = "gzip-file-as-resource";
27
+ const config = {
28
+ title: "GZip File as Resource Tool",
29
+ description: "Compresses a single file using gzip compression. Depending upon the selected output type, returns either the compressed data as a gzipped resource or a resource link, allowing it to be downloaded in a subsequent request during the current session.",
30
+ inputSchema: GZipFileAsResourceSchema,
31
+ annotations: {
32
+ readOnlyHint: false,
33
+ destructiveHint: false,
34
+ idempotentHint: true,
35
+ openWorldHint: true,
36
+ },
37
+ };
38
+ /**
39
+ * Registers the `gzip-file-as-resource` tool.
40
+ *
41
+ * The registered tool compresses input data using gzip, and makes the resulting file accessible
42
+ * as a resource for the duration of the session.
43
+ *
44
+ * The tool supports two output types:
45
+ * - "resource": Returns the resource directly, including its URI, MIME type, and base64-encoded content.
46
+ * - "resourceLink": Returns a link to access the resource later.
47
+ *
48
+ * If an unrecognized `outputType` is provided, the tool throws an error.
49
+ *
50
+ * @param {McpServer} server - The McpServer instance where the tool will be registered.
51
+ * @throws {Error} Throws an error if an unknown output type is specified.
52
+ */
53
+ export const registerGZipFileAsResourceTool = (server) => {
54
+ server.registerTool(name, config, async (args) => {
55
+ const { name, data: dataUri, outputType, } = GZipFileAsResourceSchema.parse(args);
56
+ // Validate data uri
57
+ const url = validateDataURI(dataUri);
58
+ // Fetch the data
59
+ const response = await fetchSafely(url, {
60
+ maxBytes: GZIP_MAX_FETCH_SIZE,
61
+ timeoutMillis: GZIP_MAX_FETCH_TIME_MILLIS,
62
+ });
63
+ // Compress the data using gzip
64
+ const inputBuffer = Buffer.from(response);
65
+ const compressedBuffer = gzipSync(inputBuffer);
66
+ // Create resource
67
+ const uri = getSessionResourceURI(name);
68
+ const blob = compressedBuffer.toString("base64");
69
+ const mimeType = "application/gzip";
70
+ const resource = { uri, name, mimeType };
71
+ // Register resource, get resource link in return
72
+ const resourceLink = registerSessionResource(server, resource, "blob", blob);
73
+ // Return the resource or a resource link that can be used to access this resource later
74
+ if (outputType === "resource") {
75
+ return {
76
+ content: [
77
+ {
78
+ type: "resource",
79
+ resource: { uri, mimeType, blob },
80
+ },
81
+ ],
82
+ };
83
+ }
84
+ else if (outputType === "resourceLink") {
85
+ return {
86
+ content: [resourceLink],
87
+ };
88
+ }
89
+ else {
90
+ /* v8 ignore next -- unreachable: the input schema's enum admits only resource and resourceLink */
91
+ throw new Error(`Unknown outputType: ${outputType}`);
92
+ }
93
+ });
94
+ };
95
+ /**
96
+ * Validates a given data URI to ensure it follows the appropriate protocols and rules.
97
+ *
98
+ * @param {string} dataUri - The data URI to validate. Must be an HTTP, HTTPS, or data protocol URL. If a domain is provided, it must match the allowed domains list if applicable.
99
+ * @return {URL} The validated and parsed URL object.
100
+ * @throws {Error} If the data URI does not use a supported protocol or does not meet allowed domains criteria.
101
+ */
102
+ function validateDataURI(dataUri) {
103
+ // Validate Inputs
104
+ const url = new URL(dataUri);
105
+ try {
106
+ if (url.protocol !== "http:" &&
107
+ url.protocol !== "https:" &&
108
+ url.protocol !== "data:") {
109
+ throw new Error(`Unsupported URL protocol for ${dataUri}. Only http, https, and data URLs are supported.`);
110
+ }
111
+ if (GZIP_ALLOWED_DOMAINS.length > 0 &&
112
+ (url.protocol === "http:" || url.protocol === "https:")) {
113
+ const domain = url.hostname;
114
+ const domainAllowed = GZIP_ALLOWED_DOMAINS.some((allowedDomain) => {
115
+ return domain === allowedDomain || domain.endsWith(`.${allowedDomain}`);
116
+ });
117
+ if (!domainAllowed) {
118
+ throw new Error(`Domain ${domain} is not in the allowed domains list.`);
119
+ }
120
+ }
121
+ }
122
+ catch (error) {
123
+ throw new Error(`Error processing file ${dataUri}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
124
+ }
125
+ return url;
126
+ }
127
+ /**
128
+ * Fetches data safely from a given URL while ensuring constraints on maximum byte size and timeout duration.
129
+ *
130
+ * @param {URL} url The URL to fetch data from.
131
+ * @param {Object} options An object containing options for the fetch operation.
132
+ * @param {number} options.maxBytes The maximum allowed size (in bytes) of the response. If the response exceeds this size, the operation will be aborted.
133
+ * @param {number} options.timeoutMillis The timeout duration (in milliseconds) for the fetch operation. If the fetch takes longer, it will be aborted.
134
+ * @return {Promise<ArrayBuffer>} A promise that resolves with the response as an ArrayBuffer if successful.
135
+ * @throws {Error} Throws an error if the response size exceeds the defined limit, the fetch times out, or the response is otherwise invalid.
136
+ */
137
+ async function fetchSafely(url, { maxBytes, timeoutMillis }) {
138
+ const controller = new AbortController();
139
+ const timeout = setTimeout(() => controller.abort(`Fetching ${url} took more than ${timeoutMillis} ms and was aborted.`), timeoutMillis);
140
+ try {
141
+ // Fetch the data
142
+ const response = await fetch(url, { signal: controller.signal });
143
+ if (!response.body) {
144
+ throw new Error("No response body");
145
+ }
146
+ // Note: we can't trust the Content-Length header: a malicious or clumsy server could return much more data than advertised.
147
+ // We check it here for early bail-out, but we still need to monitor actual bytes read below.
148
+ const contentLengthHeader = response.headers.get("content-length");
149
+ if (contentLengthHeader != null) {
150
+ const contentLength = parseInt(contentLengthHeader, 10);
151
+ if (contentLength > maxBytes) {
152
+ throw new Error(`Content-Length for ${url} exceeds max of ${maxBytes}: ${contentLength}`);
153
+ }
154
+ }
155
+ // Read the fetched data from the response body
156
+ const reader = response.body.getReader();
157
+ const chunks = [];
158
+ let totalSize = 0;
159
+ // Read chunks until done
160
+ try {
161
+ while (true) {
162
+ const { done, value } = await reader.read();
163
+ if (done)
164
+ break;
165
+ totalSize += value.length;
166
+ if (totalSize > maxBytes) {
167
+ // Not awaited: cancel() adopts the source's promise and may never
168
+ // settle, and we are about to throw anyway. Swallow its rejection so
169
+ // it cannot surface as an unhandled one; the thrown size error is
170
+ // the failure this path reports.
171
+ reader.cancel().catch(
172
+ /* v8 ignore next -- only runs if cancelling the source fails, which nothing here can provoke */
173
+ () => { });
174
+ throw new Error(`Response from ${url} exceeds ${maxBytes} bytes`);
175
+ }
176
+ chunks.push(value);
177
+ }
178
+ }
179
+ finally {
180
+ reader.releaseLock();
181
+ }
182
+ // Combine chunks into a single buffer
183
+ const buffer = new Uint8Array(totalSize);
184
+ let offset = 0;
185
+ for (const chunk of chunks) {
186
+ buffer.set(chunk, offset);
187
+ offset += chunk.length;
188
+ }
189
+ return buffer.buffer;
190
+ }
191
+ finally {
192
+ clearTimeout(timeout);
193
+ }
194
+ }