xmcp 0.6.13 → 0.7.1

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 (161) hide show
  1. package/dist/cli.js +8 -8
  2. package/dist/index.js +2 -2
  3. package/dist/runtime/adapter-express.js +2 -2
  4. package/dist/runtime/adapter-fastify.js +2 -2
  5. package/dist/runtime/adapter-nestjs.js +7 -7
  6. package/dist/runtime/adapter-nextjs.js +11 -11
  7. package/dist/runtime/http.js +3 -3
  8. package/dist/runtime/stdio.js +8 -8
  9. package/package.json +10 -11
  10. package/src/auth/api-key.ts +0 -120
  11. package/src/auth/jwt.ts +0 -52
  12. package/src/cli/commands/create/__tests__/create.test.ts +0 -99
  13. package/src/cli/commands/create/index.ts +0 -74
  14. package/src/cli/commands/create/templates/index.ts +0 -4
  15. package/src/cli/commands/create/templates/prompt.ts +0 -30
  16. package/src/cli/commands/create/templates/resource.ts +0 -20
  17. package/src/cli/commands/create/templates/tool.ts +0 -34
  18. package/src/cli/commands/create/templates/widget.ts +0 -33
  19. package/src/cli/utils/naming.ts +0 -39
  20. package/src/cli.ts +0 -125
  21. package/src/client/headers.ts +0 -61
  22. package/src/client/index.ts +0 -180
  23. package/src/client/types.ts +0 -122
  24. package/src/client/utils.ts +0 -133
  25. package/src/cloudflare.ts +0 -6
  26. package/src/compiler/build-telemetry.ts +0 -88
  27. package/src/compiler/client/component-compiler.ts +0 -250
  28. package/src/compiler/client/transpile.ts +0 -21
  29. package/src/compiler/compiler-context.ts +0 -61
  30. package/src/compiler/config/__tests__/config.test.ts +0 -459
  31. package/src/compiler/config/index.ts +0 -62
  32. package/src/compiler/config/injection.ts +0 -210
  33. package/src/compiler/config/schemas/bundler.ts +0 -12
  34. package/src/compiler/config/schemas/experimental/index.ts +0 -22
  35. package/src/compiler/config/schemas/index.ts +0 -20
  36. package/src/compiler/config/schemas/paths.ts +0 -35
  37. package/src/compiler/config/schemas/template.ts +0 -80
  38. package/src/compiler/config/schemas/transport/http.ts +0 -116
  39. package/src/compiler/config/schemas/transport/stdio.ts +0 -31
  40. package/src/compiler/config/schemas/typescript.ts +0 -26
  41. package/src/compiler/config/utils.ts +0 -168
  42. package/src/compiler/generate-env-code.ts +0 -5
  43. package/src/compiler/generate-import-code.ts +0 -187
  44. package/src/compiler/generate-tools-code.ts +0 -174
  45. package/src/compiler/get-bundler-config/get-entries.ts +0 -44
  46. package/src/compiler/get-bundler-config/get-externals.ts +0 -114
  47. package/src/compiler/get-bundler-config/get-injected-variables.ts +0 -46
  48. package/src/compiler/get-bundler-config/index.ts +0 -288
  49. package/src/compiler/get-bundler-config/plugins/index.ts +0 -140
  50. package/src/compiler/get-bundler-config/plugins/types/express.ts +0 -3
  51. package/src/compiler/get-bundler-config/plugins/types/fastify.ts +0 -4
  52. package/src/compiler/get-bundler-config/plugins/types/index.ts +0 -5
  53. package/src/compiler/get-bundler-config/plugins/types/nest.ts +0 -65
  54. package/src/compiler/get-bundler-config/plugins/types/next.ts +0 -52
  55. package/src/compiler/get-bundler-config/resolve-tsconfig-paths.ts +0 -51
  56. package/src/compiler/index.ts +0 -484
  57. package/src/compiler/on-first-build.ts +0 -54
  58. package/src/compiler/parse-xmcp-config.ts +0 -200
  59. package/src/compiler/start-http-server.ts +0 -42
  60. package/src/compiler/utils/__tests__/config-detection.test.ts +0 -307
  61. package/src/compiler/utils/__tests__/path-utils.test.ts +0 -137
  62. package/src/compiler/utils/config-detection.ts +0 -34
  63. package/src/compiler/utils/path-utils.ts +0 -22
  64. package/src/compiler/watcher-recovery.ts +0 -72
  65. package/src/host-bridge.ts +0 -36
  66. package/src/index.ts +0 -94
  67. package/src/platforms/build-cloudflare-output.ts +0 -116
  68. package/src/platforms/build-vercel-output.ts +0 -131
  69. package/src/plugins/index.ts +0 -1
  70. package/src/plugins/x402/index.ts +0 -24
  71. package/src/runtime/adapters/express/index.ts +0 -75
  72. package/src/runtime/adapters/fastify/__tests__/fastify.test.ts +0 -115
  73. package/src/runtime/adapters/fastify/index.ts +0 -78
  74. package/src/runtime/adapters/nestjs/index.ts +0 -16
  75. package/src/runtime/adapters/nestjs/xmcp.controller.ts +0 -34
  76. package/src/runtime/adapters/nestjs/xmcp.guard.ts +0 -101
  77. package/src/runtime/adapters/nestjs/xmcp.oauth.controller.ts +0 -36
  78. package/src/runtime/adapters/nestjs/xmcp.oauth.module.ts +0 -21
  79. package/src/runtime/adapters/nestjs/xmcp.oauth.service.ts +0 -36
  80. package/src/runtime/adapters/nestjs/xmcp.service.ts +0 -96
  81. package/src/runtime/adapters/nestjs/xmcp.utils.ts +0 -11
  82. package/src/runtime/adapters/nextjs/auth.ts +0 -265
  83. package/src/runtime/adapters/nextjs/handler/error-handler.ts +0 -67
  84. package/src/runtime/adapters/nextjs/handler/node-to-web-adapter.ts +0 -143
  85. package/src/runtime/adapters/nextjs/handler/request-converter.ts +0 -74
  86. package/src/runtime/adapters/nextjs/handler/server-lifecycle.ts +0 -69
  87. package/src/runtime/adapters/nextjs/index.ts +0 -82
  88. package/src/runtime/contexts/client-info-context.ts +0 -16
  89. package/src/runtime/contexts/http-request-context.ts +0 -21
  90. package/src/runtime/contexts/http-transport-context.ts +0 -18
  91. package/src/runtime/headers.ts +0 -42
  92. package/src/runtime/middlewares/utils.ts +0 -72
  93. package/src/runtime/platforms/cloudflare/cors.ts +0 -44
  94. package/src/runtime/platforms/cloudflare/middlewares/api-key.ts +0 -102
  95. package/src/runtime/platforms/cloudflare/middlewares/jwt.ts +0 -127
  96. package/src/runtime/platforms/cloudflare/types.ts +0 -23
  97. package/src/runtime/platforms/cloudflare/worker.ts +0 -270
  98. package/src/runtime/templates/home.ts +0 -746
  99. package/src/runtime/transports/http/base-streamable-http.ts +0 -46
  100. package/src/runtime/transports/http/cors/headers.ts +0 -58
  101. package/src/runtime/transports/http/cors/index.ts +0 -34
  102. package/src/runtime/transports/http/index.ts +0 -78
  103. package/src/runtime/transports/http/stateless-streamable-http.ts +0 -311
  104. package/src/runtime/transports/http/web-stateless-http.ts +0 -288
  105. package/src/runtime/transports/stdio/index.ts +0 -109
  106. package/src/runtime/utils/__tests__/client-info.test.ts +0 -146
  107. package/src/runtime/utils/__tests__/tool-extra.test.ts +0 -239
  108. package/src/runtime/utils/client-info.ts +0 -114
  109. package/src/runtime/utils/elicitation.ts +0 -396
  110. package/src/runtime/utils/ext-apps-registry.ts +0 -151
  111. package/src/runtime/utils/mcp-app-protocol.ts +0 -16
  112. package/src/runtime/utils/mcp-app-types.ts +0 -113
  113. package/src/runtime/utils/mcp-host-bridge.ts +0 -473
  114. package/src/runtime/utils/path-to-tool-name.ts +0 -69
  115. package/src/runtime/utils/prompt-loader.ts +0 -151
  116. package/src/runtime/utils/prompts.ts +0 -69
  117. package/src/runtime/utils/react/generate-html.ts +0 -69
  118. package/src/runtime/utils/react/index.ts +0 -6
  119. package/src/runtime/utils/request-tool-names.ts +0 -48
  120. package/src/runtime/utils/resource-loader.ts +0 -151
  121. package/src/runtime/utils/resources.ts +0 -331
  122. package/src/runtime/utils/server.ts +0 -107
  123. package/src/runtime/utils/tool-loader.ts +0 -149
  124. package/src/runtime/utils/tools.ts +0 -183
  125. package/src/runtime/utils/transformers/prompt.ts +0 -120
  126. package/src/runtime/utils/transformers/resource.ts +0 -196
  127. package/src/runtime/utils/transformers/tool.ts +0 -400
  128. package/src/runtime/utils/ui/__tests__/split-meta.test.ts +0 -803
  129. package/src/runtime/utils/ui/flatten-meta.ts +0 -44
  130. package/src/runtime/utils/ui/split-meta.ts +0 -78
  131. package/src/runtime/utils/utils/resource-uri-composer.ts +0 -204
  132. package/src/runtime/utils/validators/index.ts +0 -138
  133. package/src/telemetry/ci-info.ts +0 -6
  134. package/src/telemetry/debug.ts +0 -8
  135. package/src/telemetry/events/definitions.ts +0 -52
  136. package/src/telemetry/events/detached-flush.ts +0 -83
  137. package/src/telemetry/events/post-payload.ts +0 -141
  138. package/src/telemetry/events/tracker.ts +0 -281
  139. package/src/telemetry/index.ts +0 -7
  140. package/src/telemetry/metadata.ts +0 -49
  141. package/src/telemetry/project-id.ts +0 -35
  142. package/src/telemetry/storage.ts +0 -218
  143. package/src/types/adapter.d.ts +0 -5
  144. package/src/types/client-info.ts +0 -20
  145. package/src/types/declarations.ts +0 -37
  146. package/src/types/injected.d.ts +0 -62
  147. package/src/types/middleware.ts +0 -19
  148. package/src/types/prompt.ts +0 -6
  149. package/src/types/resource.ts +0 -15
  150. package/src/types/tool.ts +0 -192
  151. package/src/types/ui-meta.ts +0 -42
  152. package/src/utils/cli-icons.ts +0 -5
  153. package/src/utils/constants.ts +0 -31
  154. package/src/utils/context.ts +0 -105
  155. package/src/utils/detect-package-manager.ts +0 -46
  156. package/src/utils/file-watcher.ts +0 -66
  157. package/src/utils/fs-utils.ts +0 -16
  158. package/src/utils/path-validation.ts +0 -66
  159. package/src/utils/port-utils.ts +0 -43
  160. package/src/utils/spawn-process.ts +0 -49
  161. package/src/utils/subscribable.ts +0 -62
@@ -1,69 +0,0 @@
1
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp";
2
- import { ZodOptional, ZodType, ZodTypeDef, ZodRawShape } from "zod/v3";
3
- import { PromptFile } from "./server";
4
- import { isZodRawShape, pathToName } from "./tools";
5
- import { transformPromptHandler } from "./transformers/prompt";
6
-
7
- interface PromptMetadata {
8
- name: string;
9
- title: string;
10
- description: string;
11
- role?: string;
12
- }
13
-
14
- export type PromptArgsRawShape = {
15
- [k: string]:
16
- | ZodType<string, ZodTypeDef, string>
17
- | ZodOptional<ZodType<string, ZodTypeDef, string>>;
18
- };
19
-
20
- /** Loads prompts and injects them into the server */
21
- export function addPromptsToServer(
22
- server: McpServer,
23
- promptModules: Map<string, PromptFile>
24
- ): McpServer {
25
- promptModules.forEach((promptModule, path) => {
26
- const defaultName = pathToName(path);
27
-
28
- const promptConfig: PromptMetadata = {
29
- name: defaultName,
30
- title: defaultName,
31
- description: "No description provided",
32
- };
33
- let promptSchema: ZodRawShape = {};
34
-
35
- const { default: handler, metadata, schema } = promptModule;
36
-
37
- if (typeof metadata === "object" && metadata !== null) {
38
- Object.assign(promptConfig, metadata);
39
- }
40
-
41
- // Transform the user's handler into an MCP-compatible handler
42
- const transformedHandler = transformPromptHandler(
43
- handler,
44
- (promptConfig.role as "user" | "assistant") || "assistant"
45
- );
46
-
47
- // Validate and ensure schema is properly typed
48
- if (isZodRawShape(schema)) {
49
- Object.assign(promptSchema, schema);
50
- } else if (schema !== undefined && schema !== null) {
51
- console.warn(
52
- `Invalid schema for prompt "${promptConfig.name}" at ${path}. Expected Record<string, z.ZodType>`
53
- );
54
- }
55
-
56
- // server as any prevents infinite type recursion
57
- (server as any).registerPrompt(
58
- promptConfig.name,
59
- {
60
- title: promptConfig.title,
61
- description: promptConfig.description,
62
- argsSchema: schema,
63
- },
64
- transformedHandler
65
- );
66
- });
67
-
68
- return server;
69
- }
@@ -1,69 +0,0 @@
1
- import {
2
- INITIALIZE_METHOD,
3
- INITIALIZED_METHOD,
4
- MCP_APPS_PROTOCOL_VERSION,
5
- } from "../mcp-app-protocol";
6
-
7
- export function generateUIHTML(
8
- componentCode: string,
9
- css: string | undefined
10
- ): string {
11
- const renderScript = `
12
- <script type="module">
13
- const componentSource = ${JSON.stringify(componentCode)};
14
- const blobUrl = URL.createObjectURL(
15
- new Blob([componentSource], { type: "text/javascript" })
16
- );
17
-
18
- await import(blobUrl);
19
-
20
- let nextId = 1;
21
-
22
- window.parent.postMessage({
23
- jsonrpc: "2.0",
24
- id: nextId++,
25
- method: ${JSON.stringify(INITIALIZE_METHOD)},
26
- params: {
27
- appCapabilities: {
28
- availableDisplayModes: ["inline", "fullscreen", "pip"]
29
- },
30
- appInfo: { name: "xmcp React Widget", version: "1.0.0" },
31
- protocolVersion: ${JSON.stringify(MCP_APPS_PROTOCOL_VERSION)}
32
- }
33
- }, "*");
34
-
35
- window.addEventListener("message", (event) => {
36
- const data = event.data;
37
-
38
- if (event.source !== window.parent) return;
39
-
40
- // handshake ack
41
- if (data?.result?.hostContext && data?.id === 1) {
42
- window.parent.postMessage({
43
- jsonrpc: "2.0",
44
- method: ${JSON.stringify(INITIALIZED_METHOD)},
45
- params: {}
46
- }, "*");
47
- }
48
- });
49
-
50
- requestAnimationFrame(() => {
51
- URL.revokeObjectURL(blobUrl);
52
- });
53
- </script>`;
54
-
55
- const styleTag = css ? `<style>${css}</style>` : "";
56
-
57
- return `<!DOCTYPE html>
58
- <html>
59
- <head>
60
- <meta charset="utf-8">
61
- <meta name="viewport" content="width=device-width, initial-scale=1">
62
- ${styleTag}
63
- </head>
64
- <body>
65
- <div id="root"></div>
66
- ${renderScript}
67
- </body>
68
- </html>`;
69
- }
@@ -1,6 +0,0 @@
1
- /**
2
- * Check if a file path is a React component (.tsx file)
3
- */
4
- export function isReactFile(filePath: string): boolean {
5
- return filePath.endsWith(".tsx");
6
- }
@@ -1,48 +0,0 @@
1
- import type { Request } from "express";
2
- import type { JsonRpcMessage } from "@/runtime/transports/http/base-streamable-http";
3
-
4
- export function extractToolNamesFromRequest(request: Request): string[] {
5
- if (request?.body === undefined || request.body === null) {
6
- return [];
7
- }
8
-
9
- const messages: JsonRpcMessage[] = Array.isArray(request.body)
10
- ? request.body
11
- : [request.body];
12
-
13
- const toolNames: string[] = [];
14
-
15
- for (const message of messages) {
16
- if (
17
- typeof message === "object" &&
18
- message !== null &&
19
- "method" in message &&
20
- message.method === "tools/call"
21
- ) {
22
- const params = message.params;
23
-
24
- if (
25
- params &&
26
- typeof params === "object" &&
27
- "name" in params &&
28
- typeof (params as { name?: unknown }).name === "string"
29
- ) {
30
- toolNames.push((params as { name: string }).name);
31
- }
32
- }
33
- }
34
-
35
- return toolNames;
36
- }
37
-
38
- export function storeToolNamesOnRequestHeaders(
39
- request: Request,
40
- toolNames: string[]
41
- ): void {
42
- if (toolNames.length === 0) {
43
- return;
44
- }
45
-
46
- request.headers["x-mcp-tool-name"] = toolNames[0];
47
- request.headers["x-mcp-tool-names"] = toolNames.join(",");
48
- }
@@ -1,151 +0,0 @@
1
- import type { ResourceFile } from "./server";
2
-
3
- const EMPTY_RESOURCE_FILE_MESSAGE = "File is empty.";
4
- const MISSING_DEFAULT_EXPORT_MESSAGE =
5
- "File does not export a default resource handler.";
6
- const INVALID_DEFAULT_EXPORT_MESSAGE =
7
- "Default export must be a resource handler function.";
8
-
9
- type ResourceLoadIssue = {
10
- path: string;
11
- message: string;
12
- };
13
-
14
- function createResourceLoadIssue(path: string): ResourceLoadIssue {
15
- return {
16
- path,
17
- message: EMPTY_RESOURCE_FILE_MESSAGE,
18
- };
19
- }
20
-
21
- function createInvalidResourceImplementationError(path: string): Error {
22
- return new Error(
23
- `[xmcp] Invalid resource file: ${path}\n -> ${INVALID_DEFAULT_EXPORT_MESSAGE}`
24
- );
25
- }
26
-
27
- function classifyResourceModule(
28
- resourceModule: unknown,
29
- path: string
30
- ): "empty" | "missing-default" | "valid" {
31
- if (typeof resourceModule !== "object" || resourceModule === null) {
32
- throw createInvalidResourceImplementationError(path);
33
- }
34
-
35
- const moduleRecord = resourceModule as Record<string, unknown>;
36
- const keys = Object.keys(moduleRecord);
37
- const defaultExport = moduleRecord.default;
38
- const nonInteropKeys = keys.filter((key) => key !== "__esModule");
39
-
40
- if (
41
- keys.length === 0 ||
42
- (nonInteropKeys.length === 1 &&
43
- nonInteropKeys[0] === "default" &&
44
- typeof defaultExport === "object" &&
45
- defaultExport !== null &&
46
- Object.keys(defaultExport as Record<string, unknown>).length === 0)
47
- ) {
48
- return "empty";
49
- }
50
-
51
- if (!("default" in moduleRecord) || moduleRecord.default === undefined) {
52
- return "missing-default";
53
- }
54
-
55
- if (typeof moduleRecord.default !== "function") {
56
- throw createInvalidResourceImplementationError(path);
57
- }
58
-
59
- return "valid";
60
- }
61
-
62
- function toResourceFile(resourceModule: unknown): ResourceFile {
63
- return resourceModule as ResourceFile;
64
- }
65
-
66
- export async function loadResourceModules(
67
- loaders: Record<string, () => Promise<unknown>>
68
- ) {
69
- const resourceModules = new Map<string, ResourceFile>();
70
- const skippedResources: ResourceLoadIssue[] = [];
71
-
72
- const results = await Promise.all(
73
- Object.entries(loaders).map(async ([path, loadResource]) => {
74
- const resourceModule = await loadResource();
75
- const classification = classifyResourceModule(resourceModule, path);
76
-
77
- if (classification === "empty") {
78
- return {
79
- skipped: true as const,
80
- issue: createResourceLoadIssue(path),
81
- };
82
- }
83
-
84
- if (classification === "missing-default") {
85
- return {
86
- skipped: true as const,
87
- issue: {
88
- path,
89
- message: MISSING_DEFAULT_EXPORT_MESSAGE,
90
- },
91
- };
92
- }
93
-
94
- return {
95
- skipped: false as const,
96
- path,
97
- resourceModule: toResourceFile(resourceModule),
98
- };
99
- })
100
- );
101
-
102
- for (const result of results) {
103
- if (result.skipped) {
104
- skippedResources.push(result.issue);
105
- continue;
106
- }
107
-
108
- resourceModules.set(result.path, result.resourceModule);
109
- }
110
-
111
- return {
112
- resourceModules,
113
- skippedResources,
114
- };
115
- }
116
-
117
- function createResourceLoadIssueReporter(
118
- logger: Pick<Console, "warn"> = console
119
- ) {
120
- let lastReportedSummaryKey = "";
121
-
122
- return (skippedResources: ResourceLoadIssue[]) => {
123
- const summaryKey = skippedResources
124
- .map(({ path, message }) => `${path}:${message}`)
125
- .sort()
126
- .join("|");
127
-
128
- if (summaryKey === lastReportedSummaryKey) {
129
- return;
130
- }
131
-
132
- lastReportedSummaryKey = summaryKey;
133
-
134
- if (skippedResources.length === 0) {
135
- return;
136
- }
137
-
138
- skippedResources.forEach(({ path, message }) => {
139
- logger.warn(
140
- `[xmcp] Failed to load resource file: ${path}\n -> ${message}`
141
- );
142
- });
143
-
144
- const count = skippedResources.length;
145
- logger.warn(
146
- `[xmcp] ${count} resource${count === 1 ? "" : "s"} skipped due to empty files or missing default exports`
147
- );
148
- };
149
- }
150
-
151
- export const reportResourceLoadIssues = createResourceLoadIssueReporter();
@@ -1,331 +0,0 @@
1
- import {
2
- McpServer,
3
- ResourceTemplate,
4
- } from "@modelcontextprotocol/sdk/server/mcp";
5
- import { ReadResourceResult } from "@modelcontextprotocol/sdk/types";
6
- import { ResourceFile } from "./server";
7
- import { isZodRawShape, pathToName } from "./tools";
8
- import { ZodRawShape } from "zod/v3";
9
- import { transformResourceHandler } from "./transformers/resource";
10
- import { composeUriFromPath } from "./utils/resource-uri-composer";
11
- import { ResourceMetadata } from "@/types/resource";
12
- import { flattenMeta } from "./ui/flatten-meta";
13
- import { generateUIHTML } from "./react/generate-html";
14
- import { pathToToolNameMd5, pathToToolNameDjb2 } from "./path-to-tool-name";
15
- import { uIResourceRegistry } from "./ext-apps-registry";
16
-
17
- /**
18
- * Get the appropriate pathToToolName function based on runtime environment.
19
- * - For Cloudflare (INJECTED_CLIENT_BUNDLES defined): Use djb2 hash
20
- * - For Node.js: Use MD5 hash (backwards compatible)
21
- */
22
- function pathToToolName(path: string): string {
23
- // Cloudflare mode: use djb2 hash (bundles were named with djb2 at compile time)
24
- if (IS_CLOUDFLARE) {
25
- return pathToToolNameDjb2(path);
26
- }
27
- // Node.js mode: use MD5 hash (backwards compatible)
28
- return pathToToolNameMd5(path);
29
- }
30
-
31
- /**
32
- * Get a client bundle by name.
33
- * For Cloudflare Workers, bundles are injected at compile time.
34
- * For Node.js, bundles are read from the filesystem at runtime.
35
- */
36
- function getClientBundle(
37
- bundleName: string
38
- ): { js: string; css?: string } | null {
39
- // Cloudflare mode: use injected bundles
40
- if (INJECTED_CLIENT_BUNDLES) {
41
- return INJECTED_CLIENT_BUNDLES[bundleName] || null;
42
- }
43
-
44
- // Node.js mode: read from filesystem
45
- if (!IS_CLOUDFLARE) {
46
- try {
47
- // Dynamic import to avoid bundling fs in Cloudflare
48
- const fs = require("fs");
49
- const path = require("path");
50
-
51
- const searchRoots = [
52
- path.join(process.cwd(), "dist", "client"),
53
- path.join(process.cwd(), "client"),
54
- ];
55
-
56
- for (const root of searchRoots) {
57
- const jsCandidate = path.join(root, `${bundleName}.bundle.js`);
58
- const cssCandidate = path.join(root, `${bundleName}.bundle.css`);
59
-
60
- if (fs.existsSync(jsCandidate)) {
61
- const js = fs.readFileSync(jsCandidate, "utf-8");
62
- let css: string | undefined;
63
-
64
- if (fs.existsSync(cssCandidate)) {
65
- css = fs.readFileSync(cssCandidate, "utf-8");
66
- }
67
-
68
- return { js, css };
69
- }
70
- }
71
- } catch {
72
- // fs not available or file not found
73
- }
74
- }
75
-
76
- return null;
77
- }
78
-
79
- /** Loads resources and injects them into the server */
80
- export function addResourcesToServer(
81
- server: McpServer,
82
- resourcesModules: Map<string, ResourceFile>
83
- ): McpServer {
84
- const autoGeneratedResources = [...uIResourceRegistry.getAll()];
85
-
86
- autoGeneratedResources.forEach(([_, autoResource]) => {
87
- const resourceMimeType =
88
- autoResource.mimeType || "text/html;profile=mcp-app";
89
- // Flatten resource metadata for MCP protocol
90
- const flattenedResourceMeta = autoResource?._meta
91
- ? flattenMeta(autoResource._meta)
92
- : undefined;
93
- const resourceConfig: ResourceMetadata = {
94
- name: autoResource.name,
95
- description: `Auto-generated resource for ${autoResource.name} tool`,
96
- mimeType: autoResource.mimeType,
97
- _meta: flattenedResourceMeta,
98
- };
99
-
100
- // Transform the handler to serve HTML from the tool handler
101
- const transformedHandler = async (
102
- uri: URL,
103
- extra: any
104
- ): Promise<ReadResourceResult> => {
105
- if (autoResource.mimeType && autoResource.toolPath) {
106
- try {
107
- const bundleName = pathToToolName(autoResource.toolPath);
108
- const bundle = getClientBundle(bundleName);
109
-
110
- if (!bundle) {
111
- throw new Error(
112
- `React client bundle not found for "${autoResource.name}" (bundle: "${bundleName}").\n` +
113
- `React tool bundles are generated automatically when you run "xmcp build" (or "xmcp dev").\n` +
114
- `Please re-run the build so the framework can regenerate the bundle.`
115
- );
116
- }
117
-
118
- const clientCode = bundle.js;
119
- const clientCss = bundle.css;
120
-
121
- const fullHTML = generateUIHTML(clientCode, clientCss);
122
-
123
- return {
124
- contents: [
125
- {
126
- uri: autoResource.uri,
127
- text: fullHTML,
128
- mimeType: resourceMimeType,
129
- _meta: autoResource._meta,
130
- },
131
- ],
132
- };
133
- } catch (error) {
134
- console.error(`React failed for ${autoResource.name}:`, error);
135
- throw error;
136
- }
137
- }
138
-
139
- // NON-React PATH: Original behavior (backward compatible)
140
- // Call the original tool handler to get the HTML content
141
- let response = autoResource.handler({}, extra);
142
- if (response instanceof Promise) {
143
- response = await response;
144
- }
145
-
146
- // If the tool returns a string (HTML), serve it directly
147
- if (typeof response === "string") {
148
- return {
149
- contents: [
150
- {
151
- uri: autoResource.uri,
152
- text: response,
153
- mimeType: resourceMimeType,
154
- _meta: autoResource._meta,
155
- },
156
- ],
157
- };
158
- }
159
-
160
- // If the tool returns { _meta: ... }, return empty HTML
161
- if (
162
- response &&
163
- typeof response === "object" &&
164
- "_meta" in response &&
165
- !("content" in response)
166
- ) {
167
- return {
168
- contents: [
169
- {
170
- uri: autoResource.uri,
171
- text: "",
172
- mimeType: resourceMimeType,
173
- _meta: autoResource._meta,
174
- },
175
- ],
176
- };
177
- }
178
-
179
- // If the tool returns CallToolResult with content array
180
- if (
181
- response &&
182
- typeof response === "object" &&
183
- "content" in response &&
184
- Array.isArray(response.content)
185
- ) {
186
- const textContent = response.content.find(
187
- (item: any) => item.type === "text"
188
- );
189
- if (
190
- textContent &&
191
- textContent.type === "text" &&
192
- typeof textContent.text === "string"
193
- ) {
194
- return {
195
- contents: [
196
- {
197
- uri: autoResource.uri,
198
- text: textContent.text,
199
- mimeType: resourceMimeType,
200
- _meta: autoResource._meta,
201
- },
202
- ],
203
- };
204
- }
205
- }
206
-
207
- // Fallback: return empty HTML
208
- return {
209
- contents: [
210
- {
211
- uri: autoResource.uri,
212
- text: "",
213
- mimeType: resourceMimeType,
214
- _meta: autoResource._meta,
215
- },
216
- ],
217
- };
218
- };
219
-
220
- // Register as a direct resource
221
- server.registerResource(
222
- autoResource.name,
223
- autoResource.uri,
224
- resourceConfig,
225
- transformedHandler
226
- );
227
- });
228
-
229
- // Then, register manual resources as before
230
- resourcesModules.forEach((resourceModule, path) => {
231
- const defaultName = pathToName(path);
232
-
233
- const resourceConfig: ResourceMetadata = {
234
- name: defaultName,
235
- description: "No description provided",
236
- };
237
-
238
- const { default: handler, metadata, schema } = resourceModule;
239
-
240
- if (typeof metadata === "object" && metadata !== null) {
241
- Object.assign(resourceConfig, metadata);
242
- }
243
-
244
- let resourceSchema: ZodRawShape = {};
245
- if (isZodRawShape(schema)) {
246
- resourceSchema = schema;
247
- } else if (schema !== undefined && schema !== null) {
248
- console.warn(
249
- `Invalid schema for resource "${resourceConfig.name}" at ${path}. Expected Record<string, z.ZodType>`
250
- );
251
- }
252
-
253
- const resourceInfo = composeUriFromPath(path);
254
-
255
- if (!resourceInfo) {
256
- console.warn(
257
- `Skipping resource "${resourceConfig.name}" at ${path}: Invalid file path format`
258
- );
259
- return;
260
- }
261
-
262
- // Construct URI based on mimeType
263
- let uri = resourceInfo.uriTemplate;
264
- if (resourceConfig.mimeType && resourceConfig.mimeType.includes("html")) {
265
- // Add .html extension if mimeType contains "html"
266
- uri = uri.endsWith(".html") ? uri : `${uri}.html`;
267
- }
268
-
269
- const transformedHandler = transformResourceHandler(
270
- handler,
271
- path,
272
- resourceSchema
273
- );
274
-
275
- if (resourceInfo.type === "direct") {
276
- // register as a direct resource (static composed URI)
277
- server.registerResource(
278
- resourceConfig.name as string,
279
- uri,
280
- resourceConfig,
281
- transformedHandler
282
- );
283
- } else {
284
- // register as a resource template (dynamic URI with parameters)
285
- const resourceTemplate = new ResourceTemplate(uri, {
286
- list: undefined,
287
- });
288
-
289
- // create template callback that directly uses variables instead of re-parsing URI
290
- // this is a wrapper over the transformed handler
291
- // would be nice to have a modelling layer + assertion to handle this
292
- const templateCallback = async (uri: URL, variables: any, extra: any) => {
293
- // validate parameters against schema
294
- const validatedParams: Record<string, any> = {};
295
- for (const paramName of resourceInfo.parameters) {
296
- const paramValue = variables[paramName];
297
- const paramSchema = resourceSchema[paramName];
298
-
299
- if (paramValue === undefined) {
300
- // throw a nice hint error
301
- throw new Error(
302
- `Missing required parameter: ${paramName}. Available variables: ${Object.keys(variables)}`
303
- );
304
- }
305
-
306
- if (paramSchema) {
307
- validatedParams[paramName] = paramSchema.parse(paramValue);
308
- } else {
309
- validatedParams[paramName] = paramValue;
310
- }
311
- }
312
-
313
- let response = handler(validatedParams, extra);
314
- if (response instanceof Promise) response = await response;
315
-
316
- return typeof response === "string"
317
- ? { contents: [{ uri: uri.href, text: response }] }
318
- : response;
319
- };
320
-
321
- server.registerResource(
322
- resourceConfig.name as string,
323
- resourceTemplate,
324
- resourceConfig,
325
- templateCallback
326
- );
327
- }
328
- });
329
-
330
- return server;
331
- }