xmcp 0.7.0 → 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 (155) hide show
  1. package/dist/cli.js +1 -1
  2. package/dist/index.js +1 -1
  3. package/package.json +2 -3
  4. package/src/auth/api-key.ts +0 -120
  5. package/src/auth/jwt.ts +0 -52
  6. package/src/cli/commands/create/__tests__/create.test.ts +0 -99
  7. package/src/cli/commands/create/index.ts +0 -74
  8. package/src/cli/commands/create/templates/index.ts +0 -4
  9. package/src/cli/commands/create/templates/prompt.ts +0 -30
  10. package/src/cli/commands/create/templates/resource.ts +0 -20
  11. package/src/cli/commands/create/templates/tool.ts +0 -34
  12. package/src/cli/commands/create/templates/widget.ts +0 -33
  13. package/src/cli/utils/naming.ts +0 -39
  14. package/src/cli.ts +0 -125
  15. package/src/client/headers.ts +0 -61
  16. package/src/client/index.ts +0 -180
  17. package/src/client/types.ts +0 -122
  18. package/src/client/utils.ts +0 -133
  19. package/src/cloudflare.ts +0 -6
  20. package/src/compiler/build-telemetry.ts +0 -88
  21. package/src/compiler/client/component-compiler.ts +0 -250
  22. package/src/compiler/client/transpile.ts +0 -21
  23. package/src/compiler/compiler-context.ts +0 -61
  24. package/src/compiler/config/__tests__/config.test.ts +0 -459
  25. package/src/compiler/config/index.ts +0 -62
  26. package/src/compiler/config/injection.ts +0 -210
  27. package/src/compiler/config/schemas/bundler.ts +0 -12
  28. package/src/compiler/config/schemas/experimental/index.ts +0 -22
  29. package/src/compiler/config/schemas/index.ts +0 -20
  30. package/src/compiler/config/schemas/paths.ts +0 -35
  31. package/src/compiler/config/schemas/template.ts +0 -80
  32. package/src/compiler/config/schemas/transport/http.ts +0 -116
  33. package/src/compiler/config/schemas/transport/stdio.ts +0 -31
  34. package/src/compiler/config/schemas/typescript.ts +0 -26
  35. package/src/compiler/config/utils.ts +0 -168
  36. package/src/compiler/generate-env-code.ts +0 -5
  37. package/src/compiler/generate-import-code.ts +0 -187
  38. package/src/compiler/generate-tools-code.ts +0 -174
  39. package/src/compiler/get-bundler-config/get-entries.ts +0 -44
  40. package/src/compiler/get-bundler-config/get-externals.ts +0 -114
  41. package/src/compiler/get-bundler-config/get-injected-variables.ts +0 -46
  42. package/src/compiler/get-bundler-config/index.ts +0 -288
  43. package/src/compiler/get-bundler-config/plugins/index.ts +0 -140
  44. package/src/compiler/get-bundler-config/plugins/types/express.ts +0 -3
  45. package/src/compiler/get-bundler-config/plugins/types/fastify.ts +0 -4
  46. package/src/compiler/get-bundler-config/plugins/types/index.ts +0 -5
  47. package/src/compiler/get-bundler-config/plugins/types/nest.ts +0 -65
  48. package/src/compiler/get-bundler-config/plugins/types/next.ts +0 -52
  49. package/src/compiler/get-bundler-config/resolve-tsconfig-paths.ts +0 -51
  50. package/src/compiler/index.ts +0 -484
  51. package/src/compiler/on-first-build.ts +0 -54
  52. package/src/compiler/parse-xmcp-config.ts +0 -200
  53. package/src/compiler/start-http-server.ts +0 -42
  54. package/src/compiler/utils/__tests__/config-detection.test.ts +0 -307
  55. package/src/compiler/utils/__tests__/path-utils.test.ts +0 -137
  56. package/src/compiler/utils/config-detection.ts +0 -34
  57. package/src/compiler/utils/path-utils.ts +0 -22
  58. package/src/compiler/watcher-recovery.ts +0 -72
  59. package/src/host-bridge.ts +0 -36
  60. package/src/index.ts +0 -94
  61. package/src/platforms/build-cloudflare-output.ts +0 -116
  62. package/src/platforms/build-vercel-output.ts +0 -131
  63. package/src/plugins/index.ts +0 -1
  64. package/src/plugins/x402/index.ts +0 -24
  65. package/src/runtime/adapters/express/index.ts +0 -75
  66. package/src/runtime/adapters/fastify/__tests__/fastify.test.ts +0 -115
  67. package/src/runtime/adapters/fastify/index.ts +0 -78
  68. package/src/runtime/adapters/nestjs/index.ts +0 -16
  69. package/src/runtime/adapters/nestjs/xmcp.controller.ts +0 -34
  70. package/src/runtime/adapters/nestjs/xmcp.guard.ts +0 -101
  71. package/src/runtime/adapters/nestjs/xmcp.oauth.controller.ts +0 -36
  72. package/src/runtime/adapters/nestjs/xmcp.oauth.module.ts +0 -21
  73. package/src/runtime/adapters/nestjs/xmcp.oauth.service.ts +0 -36
  74. package/src/runtime/adapters/nestjs/xmcp.service.ts +0 -96
  75. package/src/runtime/adapters/nestjs/xmcp.utils.ts +0 -11
  76. package/src/runtime/adapters/nextjs/auth.ts +0 -265
  77. package/src/runtime/adapters/nextjs/handler/error-handler.ts +0 -67
  78. package/src/runtime/adapters/nextjs/handler/node-to-web-adapter.ts +0 -143
  79. package/src/runtime/adapters/nextjs/handler/request-converter.ts +0 -74
  80. package/src/runtime/adapters/nextjs/handler/server-lifecycle.ts +0 -69
  81. package/src/runtime/adapters/nextjs/index.ts +0 -121
  82. package/src/runtime/contexts/client-info-context.ts +0 -16
  83. package/src/runtime/contexts/http-request-context.ts +0 -21
  84. package/src/runtime/contexts/http-transport-context.ts +0 -18
  85. package/src/runtime/headers.ts +0 -42
  86. package/src/runtime/middlewares/utils.ts +0 -72
  87. package/src/runtime/platforms/cloudflare/cors.ts +0 -44
  88. package/src/runtime/platforms/cloudflare/middlewares/api-key.ts +0 -102
  89. package/src/runtime/platforms/cloudflare/middlewares/jwt.ts +0 -127
  90. package/src/runtime/platforms/cloudflare/types.ts +0 -23
  91. package/src/runtime/platforms/cloudflare/worker.ts +0 -270
  92. package/src/runtime/templates/home.ts +0 -746
  93. package/src/runtime/transports/http/base-streamable-http.ts +0 -46
  94. package/src/runtime/transports/http/cors/headers.ts +0 -58
  95. package/src/runtime/transports/http/cors/index.ts +0 -34
  96. package/src/runtime/transports/http/index.ts +0 -78
  97. package/src/runtime/transports/http/stateless-streamable-http.ts +0 -353
  98. package/src/runtime/transports/http/web-stateless-http.ts +0 -288
  99. package/src/runtime/transports/stdio/index.ts +0 -109
  100. package/src/runtime/utils/__tests__/client-info.test.ts +0 -146
  101. package/src/runtime/utils/__tests__/tool-extra.test.ts +0 -239
  102. package/src/runtime/utils/client-info.ts +0 -114
  103. package/src/runtime/utils/elicitation.ts +0 -396
  104. package/src/runtime/utils/ext-apps-registry.ts +0 -151
  105. package/src/runtime/utils/mcp-app-protocol.ts +0 -16
  106. package/src/runtime/utils/mcp-app-types.ts +0 -113
  107. package/src/runtime/utils/mcp-host-bridge.ts +0 -473
  108. package/src/runtime/utils/path-to-tool-name.ts +0 -69
  109. package/src/runtime/utils/prompt-loader.ts +0 -151
  110. package/src/runtime/utils/prompts.ts +0 -69
  111. package/src/runtime/utils/react/generate-html.ts +0 -69
  112. package/src/runtime/utils/react/index.ts +0 -6
  113. package/src/runtime/utils/request-tool-names.ts +0 -48
  114. package/src/runtime/utils/resource-loader.ts +0 -151
  115. package/src/runtime/utils/resources.ts +0 -331
  116. package/src/runtime/utils/server.ts +0 -107
  117. package/src/runtime/utils/tool-loader.ts +0 -149
  118. package/src/runtime/utils/tools.ts +0 -183
  119. package/src/runtime/utils/transformers/prompt.ts +0 -120
  120. package/src/runtime/utils/transformers/resource.ts +0 -196
  121. package/src/runtime/utils/transformers/tool.ts +0 -400
  122. package/src/runtime/utils/ui/__tests__/split-meta.test.ts +0 -803
  123. package/src/runtime/utils/ui/flatten-meta.ts +0 -44
  124. package/src/runtime/utils/ui/split-meta.ts +0 -78
  125. package/src/runtime/utils/utils/resource-uri-composer.ts +0 -204
  126. package/src/runtime/utils/validators/index.ts +0 -138
  127. package/src/telemetry/ci-info.ts +0 -6
  128. package/src/telemetry/debug.ts +0 -8
  129. package/src/telemetry/events/definitions.ts +0 -52
  130. package/src/telemetry/events/detached-flush.ts +0 -83
  131. package/src/telemetry/events/post-payload.ts +0 -141
  132. package/src/telemetry/events/tracker.ts +0 -281
  133. package/src/telemetry/index.ts +0 -7
  134. package/src/telemetry/metadata.ts +0 -49
  135. package/src/telemetry/project-id.ts +0 -35
  136. package/src/telemetry/storage.ts +0 -218
  137. package/src/types/adapter.d.ts +0 -5
  138. package/src/types/client-info.ts +0 -20
  139. package/src/types/declarations.ts +0 -37
  140. package/src/types/injected.d.ts +0 -62
  141. package/src/types/middleware.ts +0 -19
  142. package/src/types/prompt.ts +0 -6
  143. package/src/types/resource.ts +0 -15
  144. package/src/types/tool.ts +0 -192
  145. package/src/types/ui-meta.ts +0 -42
  146. package/src/utils/cli-icons.ts +0 -5
  147. package/src/utils/constants.ts +0 -31
  148. package/src/utils/context.ts +0 -105
  149. package/src/utils/detect-package-manager.ts +0 -46
  150. package/src/utils/file-watcher.ts +0 -66
  151. package/src/utils/fs-utils.ts +0 -16
  152. package/src/utils/path-validation.ts +0 -66
  153. package/src/utils/port-utils.ts +0 -43
  154. package/src/utils/spawn-process.ts +0 -49
  155. package/src/utils/subscribable.ts +0 -62
@@ -1,168 +0,0 @@
1
- import type { HttpTransportConfig } from "./schemas";
2
- import {
3
- httpTransportConfigSchema,
4
- stdioTransportConfigSchema,
5
- templateConfigSchema,
6
- typescriptConfigSchema,
7
- corsConfigSchema,
8
- experimentalConfigSchema,
9
- DEFAULT_PATHS,
10
- } from "./schemas";
11
- import type { z } from "zod/v3";
12
- import type { XmcpConfigOutputSchema } from "./index";
13
- import type { CorsConfig } from "./schemas";
14
-
15
- // Resolved types derived from function return types
16
- // This eliminates the need for explicit type definitions
17
- export type ResolvedHttpConfig =
18
- | (Extract<z.output<typeof httpTransportConfigSchema>, object> & {
19
- cors: CorsConfig; // Ensure cors is always present (not optional)
20
- })
21
- | null;
22
-
23
- export function getResolvedHttpConfig(
24
- userConfig: HttpTransportConfig | undefined
25
- ): ResolvedHttpConfig {
26
- if (typeof userConfig === "boolean") {
27
- if (!userConfig) return null;
28
- // When boolean is true, parse an empty object to get defaults from Zod
29
- // The schema transform handles merging all defaults including cors
30
- const parsed = httpTransportConfigSchema.parse({});
31
- // Type guard narrows from boolean | object to object
32
- if (typeof parsed !== "object" || parsed === null) {
33
- return null;
34
- }
35
- return parsed;
36
- }
37
- if (typeof userConfig === "object" && userConfig !== null) {
38
- // The schema transform handles merging defaults for partial configs
39
- const parsed = httpTransportConfigSchema.parse(userConfig);
40
- // Type guard narrows from boolean | object to object
41
- if (typeof parsed !== "object" || parsed === null) {
42
- return null;
43
- }
44
- return parsed;
45
- }
46
- return null;
47
- }
48
-
49
- export function getResolvedCorsConfig(
50
- httpConfig: ResolvedHttpConfig
51
- ): z.output<typeof corsConfigSchema> {
52
- return corsConfigSchema.parse(httpConfig?.cors ?? {});
53
- }
54
-
55
- export type ResolvedPathsConfig = {
56
- tools: string | null;
57
- prompts: string | null;
58
- resources: string | null;
59
- };
60
-
61
- export function getResolvedPathsConfig(
62
- userConfig: XmcpConfigOutputSchema
63
- ): ResolvedPathsConfig {
64
- const userPaths = userConfig?.paths;
65
- if (!userPaths) {
66
- return {
67
- tools: DEFAULT_PATHS.tools,
68
- prompts: DEFAULT_PATHS.prompts,
69
- resources: DEFAULT_PATHS.resources,
70
- };
71
- }
72
-
73
- const resolvedPaths: ResolvedPathsConfig = {
74
- tools: DEFAULT_PATHS.tools,
75
- prompts: DEFAULT_PATHS.prompts,
76
- resources: DEFAULT_PATHS.resources,
77
- };
78
-
79
- // Handle tools path
80
- if (typeof userPaths.tools === "boolean") {
81
- resolvedPaths.tools = userPaths.tools ? DEFAULT_PATHS.tools : null;
82
- } else if (typeof userPaths.tools === "string") {
83
- resolvedPaths.tools = userPaths.tools;
84
- }
85
-
86
- // Handle prompts path
87
- if (typeof userPaths.prompts === "boolean") {
88
- resolvedPaths.prompts = userPaths.prompts ? DEFAULT_PATHS.prompts : null;
89
- } else if (typeof userPaths.prompts === "string") {
90
- resolvedPaths.prompts = userPaths.prompts;
91
- }
92
-
93
- // Handle resources path
94
- if (typeof userPaths.resources === "boolean") {
95
- resolvedPaths.resources = userPaths.resources
96
- ? DEFAULT_PATHS.resources
97
- : null;
98
- } else if (typeof userPaths.resources === "string") {
99
- resolvedPaths.resources = userPaths.resources;
100
- }
101
-
102
- return resolvedPaths;
103
- }
104
-
105
- export type ResolvedStdioConfig = Extract<
106
- z.output<typeof stdioTransportConfigSchema>,
107
- object
108
- > | null;
109
-
110
- export function getResolvedStdioConfig(
111
- userConfig: XmcpConfigOutputSchema
112
- ): ResolvedStdioConfig {
113
- const stdioConfig = userConfig?.stdio;
114
- if (typeof stdioConfig === "boolean") {
115
- if (!stdioConfig) return null;
116
- // When boolean is true, parse an empty object to get defaults from Zod
117
- const parsed = stdioTransportConfigSchema.parse({});
118
- // Type guard: ensure we have an object (not boolean)
119
- if (typeof parsed !== "object" || parsed === null) {
120
- return null;
121
- }
122
- return parsed;
123
- }
124
- if (stdioConfig) {
125
- // Config is already parsed by Zod, but ensure defaults are applied
126
- const parsed = stdioTransportConfigSchema.parse(stdioConfig);
127
- // Type guard: ensure we have an object (not boolean)
128
- if (typeof parsed !== "object" || parsed === null) {
129
- return null;
130
- }
131
- return parsed;
132
- }
133
- // When undefined, parse an empty object to get defaults from Zod
134
- const parsed = stdioTransportConfigSchema.parse({});
135
- // Type guard: ensure we have an object (not boolean)
136
- if (typeof parsed !== "object" || parsed === null) {
137
- return null;
138
- }
139
- return parsed;
140
- }
141
-
142
- export function getResolvedTemplateConfig(
143
- userConfig: XmcpConfigOutputSchema
144
- ): z.output<typeof templateConfigSchema> {
145
- const userTemplate = userConfig?.template;
146
- return templateConfigSchema.parse(userTemplate ?? {});
147
- }
148
-
149
- export type ResolvedExperimentalConfig = Pick<
150
- z.output<typeof experimentalConfigSchema>,
151
- "adapter"
152
- >;
153
-
154
- export function getResolvedExperimentalConfig(
155
- userConfig: XmcpConfigOutputSchema
156
- ): ResolvedExperimentalConfig {
157
- const experimental = userConfig?.experimental;
158
- return {
159
- adapter: experimental?.adapter,
160
- };
161
- }
162
-
163
- export function getResolvedTypescriptConfig(
164
- userConfig: XmcpConfigOutputSchema
165
- ): z.output<typeof typescriptConfigSchema> {
166
- const typescript = userConfig?.typescript;
167
- return typescriptConfigSchema.parse(typescript ?? {});
168
- }
@@ -1,5 +0,0 @@
1
- export function generateEnvCode() {
2
- return `/// <reference types="xmcp" />
3
-
4
- // Do not edit this file`;
5
- }
@@ -1,187 +0,0 @@
1
- import { compilerContext } from "./compiler-context";
2
-
3
- /**
4
- * Generate a valid identifier from a file path for use in variable names.
5
- * Converts paths like "src/tools/hello.ts" to "src_tools_hello_ts"
6
- */
7
- function pathToIdentifier(path: string): string {
8
- return path.replace(/[^a-zA-Z0-9]/g, "_");
9
- }
10
-
11
- export function generateImportCode(): string {
12
- const {
13
- toolPaths,
14
- promptPaths,
15
- resourcePaths,
16
- hasMiddleware,
17
- clientBundles,
18
- platforms,
19
- } = compilerContext.getContext();
20
-
21
- const isCloudflare = platforms?.cloudflare;
22
-
23
- // For Cloudflare, use static imports to avoid code splitting.
24
- // For Node.js, use dynamic imports for lazy loading.
25
- if (isCloudflare) {
26
- return generateStaticImportCode(
27
- toolPaths,
28
- promptPaths,
29
- resourcePaths,
30
- hasMiddleware,
31
- clientBundles
32
- );
33
- }
34
-
35
- return generateDynamicImportCode(
36
- toolPaths,
37
- promptPaths,
38
- resourcePaths,
39
- hasMiddleware,
40
- clientBundles
41
- );
42
- }
43
-
44
- /**
45
- * Generate static imports for Cloudflare Workers.
46
- * This ensures all code is bundled into a single file without code splitting.
47
- */
48
- function generateStaticImportCode(
49
- toolPaths: Set<string>,
50
- promptPaths: Set<string>,
51
- resourcePaths: Set<string>,
52
- hasMiddleware: boolean,
53
- clientBundles?: Map<string, string>
54
- ): string {
55
- // Generate static import statements at the top
56
- const staticImports: string[] = [];
57
- const toolsEntries: string[] = [];
58
- const promptsEntries: string[] = [];
59
- const resourcesEntries: string[] = [];
60
-
61
- Array.from(toolPaths).forEach((p) => {
62
- const path = p.replace(/\\/g, "/");
63
- const relativePath = `../${path}`;
64
- const identifier = pathToIdentifier(path);
65
- staticImports.push(`import * as ${identifier} from "${relativePath}";`);
66
- toolsEntries.push(`"${path}": () => Promise.resolve(${identifier}),`);
67
- });
68
-
69
- Array.from(promptPaths).forEach((p) => {
70
- const path = p.replace(/\\/g, "/");
71
- const relativePath = `../${path}`;
72
- const identifier = pathToIdentifier(path);
73
- staticImports.push(`import * as ${identifier} from "${relativePath}";`);
74
- promptsEntries.push(`"${path}": () => Promise.resolve(${identifier}),`);
75
- });
76
-
77
- Array.from(resourcePaths).forEach((p) => {
78
- const path = p.replace(/\\/g, "/");
79
- const relativePath = `../${path}`;
80
- const identifier = pathToIdentifier(path);
81
- staticImports.push(`import * as ${identifier} from "${relativePath}";`);
82
- resourcesEntries.push(`"${path}": () => Promise.resolve(${identifier}),`);
83
- });
84
-
85
- let middlewareCode = "";
86
- if (hasMiddleware) {
87
- staticImports.push(`import * as _middleware from "../src/middleware.ts";`);
88
- middlewareCode = `export const middleware = () => Promise.resolve(_middleware);`;
89
- }
90
-
91
- // Generate client bundles mapping (empty object if none)
92
- const clientBundlesEntries =
93
- clientBundles && clientBundles.size > 0
94
- ? Array.from(clientBundles)
95
- .map(([toolName, bundlePath]) => ` "${toolName}": "${bundlePath}",`)
96
- .join("\n")
97
- : "";
98
-
99
- return `${staticImports.join("\n")}
100
-
101
- export const tools = {
102
- ${toolsEntries.join("\n")}
103
- };
104
-
105
- export const prompts = {
106
- ${promptsEntries.join("\n")}
107
- };
108
-
109
- export const resources = {
110
- ${resourcesEntries.join("\n")}
111
- };
112
-
113
- export const clientBundles = {
114
- ${clientBundlesEntries}
115
- };
116
-
117
- ${middlewareCode}
118
- `;
119
- }
120
-
121
- /**
122
- * Generate dynamic imports for Node.js environments.
123
- * Uses lazy loading for better startup performance.
124
- */
125
- function generateDynamicImportCode(
126
- toolPaths: Set<string>,
127
- promptPaths: Set<string>,
128
- resourcePaths: Set<string>,
129
- hasMiddleware: boolean,
130
- clientBundles?: Map<string, string>
131
- ): string {
132
- const importToolsCode = Array.from(toolPaths)
133
- .map((p) => {
134
- const path = p.replace(/\\/g, "/");
135
- const relativePath = `../${path}`;
136
- return `"${path}": () => import("${relativePath}"),`;
137
- })
138
- .join("\n");
139
-
140
- const importPromptsCode = Array.from(promptPaths)
141
- .map((p) => {
142
- const path = p.replace(/\\/g, "/");
143
- const relativePath = `../${path}`;
144
- return `"${path}": () => import("${relativePath}"),`;
145
- })
146
- .join("\n");
147
-
148
- const importResourcesCode = Array.from(resourcePaths)
149
- .map((p) => {
150
- const path = p.replace(/\\/g, "/");
151
- const relativePath = `../${path}`;
152
- return `"${path}": () => import("${relativePath}"),`;
153
- })
154
- .join("\n");
155
-
156
- const importMiddlewareCode = hasMiddleware
157
- ? `export const middleware = () => import("../src/middleware.ts");`
158
- : "";
159
-
160
- // Generate client bundles mapping (empty object if none)
161
- const clientBundlesEntries =
162
- clientBundles && clientBundles.size > 0
163
- ? Array.from(clientBundles)
164
- .map(([toolName, bundlePath]) => ` "${toolName}": "${bundlePath}",`)
165
- .join("\n")
166
- : "";
167
-
168
- return `
169
- export const tools = {
170
- ${importToolsCode}
171
- };
172
-
173
- export const prompts = {
174
- ${importPromptsCode}
175
- };
176
-
177
- export const resources = {
178
- ${importResourcesCode}
179
- };
180
-
181
- export const clientBundles = {
182
- ${clientBundlesEntries}
183
- };
184
-
185
- ${importMiddlewareCode}
186
- `;
187
- }
@@ -1,174 +0,0 @@
1
- import { compilerContext } from "./compiler-context";
2
-
3
- // this is an experimental feature
4
- // currently it's only used for the nextjs adapter & is manually generated to resolve the async imports
5
- // this prevents the tools from being an async function that needs to resolve first, instead it just returns the array
6
-
7
- export function generateToolsExportCode(): string {
8
- const { toolPaths } = compilerContext.getContext();
9
-
10
- const importStatements = Array.from(toolPaths)
11
- .map((p, index) => {
12
- const path = p.replace(/\\/g, "/");
13
- const relativePath = `../${path}`;
14
- return `import * as tool${index} from "${relativePath}";`;
15
- })
16
- .join("\n");
17
-
18
- const toolsArray = Array.from(toolPaths)
19
- .map((p, index) => {
20
- const path = p.replace(/\\/g, "/");
21
- const fileName = path.split("/").pop() || path;
22
- const defaultName = fileName.replace(/\.[^/.]+$/, "");
23
-
24
- return `{
25
- path: "${path}",
26
- name: "${defaultName}",
27
- module: tool${index}
28
- }`;
29
- })
30
- .join(",\n ");
31
-
32
- return `import { z } from "zod";
33
-
34
- ${importStatements}
35
-
36
- /**
37
- * Runtime-accessible tools function that works from any context.
38
- * Generated at build time - always up to date with discovered tools.
39
- * @returns {Promise<ToolRegistry>}
40
- */
41
- export async function getTools() {
42
- const toolsData = [
43
- ${toolsArray}
44
- ];
45
-
46
- const registry = {};
47
-
48
- for (const toolData of toolsData) {
49
- const { path, name: defaultName, module } = toolData;
50
- const { default: handler, metadata, schema, outputSchema } = module;
51
-
52
- const toolConfig = {
53
- name: defaultName,
54
- description: "No description provided",
55
- ...((typeof metadata === "object" && metadata !== null) ? metadata : {})
56
- };
57
-
58
- // Determine the actual schema to use
59
- let toolSchema = {};
60
- if (schema && typeof schema === "object" && schema !== null) {
61
- // Basic validation for Zod schema object
62
- const isValidSchema = Object.entries(schema).every(([key, val]) => {
63
- if (typeof key !== "string") return false;
64
- if (typeof val !== "object" || val === null) return false;
65
- if (!("parse" in val) || typeof val.parse !== "function") return false;
66
- return true;
67
- });
68
-
69
- if (isValidSchema) {
70
- toolSchema = schema;
71
- } else {
72
- console.warn(\`Invalid schema for tool "\${toolConfig.name}" at \${path}. Expected Record<string, z.ZodType>\`);
73
- }
74
- }
75
-
76
- let toolOutputSchema = undefined;
77
- if (outputSchema && typeof outputSchema === "object" && outputSchema !== null) {
78
- const isValidOutputSchema = Object.entries(outputSchema).every(([key, val]) => {
79
- if (typeof key !== "string") return false;
80
- if (typeof val !== "object" || val === null) return false;
81
- if (!("parse" in val) || typeof val.parse !== "function") return false;
82
- return true;
83
- });
84
-
85
- if (isValidOutputSchema) {
86
- toolOutputSchema = outputSchema;
87
- } else {
88
- throw new Error(\`Invalid outputSchema for tool "\${toolConfig.name}" at \${path}. Expected Record<string, z.ZodType>\`);
89
- }
90
- }
91
-
92
- // Make sure tools has annotations with a title — shallow copy to avoid mutating shared objects
93
- toolConfig.annotations = { ...(toolConfig.annotations ?? {}) };
94
- if (toolConfig.annotations.title === undefined) {
95
- toolConfig.annotations.title = toolConfig.name;
96
- }
97
-
98
- // Add to registry in the formatted structure
99
- registry[toolConfig.name] = {
100
- description: toolConfig.description,
101
- inputSchema: z.object(toolSchema || {}),
102
- outputSchema: toolOutputSchema
103
- ? z.object(toolOutputSchema).strict()
104
- : undefined,
105
- execute: async (args, extra) => {
106
- const result = await handler(args, extra);
107
- return result;
108
- },
109
- };
110
- }
111
-
112
- return registry;
113
- }
114
-
115
- export const tools = await getTools();`;
116
- }
117
-
118
- export function generateToolsTypesCode(): string {
119
- const { toolPaths } = compilerContext.getContext();
120
-
121
- const toolNames = Array.from(toolPaths).map((p) => {
122
- const path = p.replace(/\\/g, "/");
123
- const fileName = path.split("/").pop() || path;
124
- return fileName.replace(/\.[^/.]+$/, "");
125
- });
126
-
127
- const toolNamesUnion =
128
- toolNames.length > 0
129
- ? toolNames.map((name) => `"${name}"`).join(" | ")
130
- : "never";
131
-
132
- return `import { z } from "zod";
133
-
134
- export interface ToolMetadata {
135
- name: string;
136
- description: string;
137
- annotations?: {
138
- title?: string;
139
- [key: string]: any;
140
- };
141
- [key: string]: any;
142
- }
143
-
144
- export interface ToolItem {
145
- path: string;
146
- name: string;
147
- metadata: ToolMetadata;
148
- schema: Record<string, z.ZodType>;
149
- handler: (args: any) => Promise<any>;
150
- }
151
-
152
- export interface ToolRegistryItem {
153
- description: string;
154
- inputSchema: z.ZodObject<any>;
155
- outputSchema?: z.ZodObject<any>;
156
- execute: (args: any) => Promise<any>;
157
- }
158
-
159
- export type ToolNames = ${toolNamesUnion};
160
-
161
- export type ToolRegistry = {
162
- [k in ToolNames]: ToolRegistryItem;
163
- };
164
-
165
- declare global {
166
- namespace XMCP {
167
- interface Tools extends ToolRegistry {}
168
- }
169
- }
170
-
171
- export declare function getTools(): Promise<ToolRegistry>;
172
- export declare const tools: ToolRegistry;
173
- `;
174
- }
@@ -1,44 +0,0 @@
1
- import { runtimeFolderPath, resolveXmcpSrcPath } from "@/utils/constants";
2
- import { XmcpConfigOutputSchema } from "@/compiler/config";
3
- import path from "path";
4
- import { compilerContext } from "@/compiler/compiler-context";
5
-
6
- /** Get what packages are gonna be built by xmcp */
7
- export function getEntries(
8
- xmcpConfig: XmcpConfigOutputSchema
9
- ): Record<string, string> {
10
- const { platforms } = compilerContext.getContext();
11
-
12
- if (platforms.cloudflare) {
13
- const xmcpSrcPath = resolveXmcpSrcPath();
14
- return {
15
- worker: path.join(xmcpSrcPath, "runtime/platforms/cloudflare/worker.ts"),
16
- };
17
- }
18
-
19
- const entries: Record<string, string> = {};
20
- if (xmcpConfig.stdio) {
21
- entries.stdio = path.join(runtimeFolderPath, "stdio.js");
22
- }
23
- if (xmcpConfig["http"]) {
24
- // non adapter mode
25
- if (!xmcpConfig.experimental?.adapter) {
26
- entries["http"] = path.join(runtimeFolderPath, "http.js");
27
- }
28
-
29
- // adapter mode enabled
30
- if (xmcpConfig.experimental?.adapter === "express") {
31
- entries["adapter"] = path.join(runtimeFolderPath, "adapter-express.js");
32
- }
33
- if (xmcpConfig.experimental?.adapter === "nextjs") {
34
- entries["adapter"] = path.join(runtimeFolderPath, "adapter-nextjs.js");
35
- }
36
- if (xmcpConfig.experimental?.adapter === "nestjs") {
37
- entries["adapter"] = path.join(runtimeFolderPath, "adapter-nestjs.js");
38
- }
39
- if (xmcpConfig.experimental?.adapter === "fastify") {
40
- entries["adapter"] = path.join(runtimeFolderPath, "adapter-fastify.js");
41
- }
42
- }
43
- return entries;
44
- }
@@ -1,114 +0,0 @@
1
- import { getXmcpConfig } from "../compiler-context";
2
- import { builtinModules } from "module";
3
- import { runtimeFiles } from "./plugins";
4
- import { RspackOptions } from "@rspack/core";
5
-
6
- /**
7
- * This function will decide if a file is bundled by xmcp compiler or not.
8
- * We want to avoid building node modules.
9
- * When using Next.js, we want to avoid building tools/*, since the nextjs compiler will handle that code.
10
- */
11
- export function getExternals(): RspackOptions["externals"] {
12
- const xmcpConfig = getXmcpConfig();
13
-
14
- const replacedImports = new Set<string>();
15
-
16
- return [
17
- function (data, callback) {
18
- const { request } = data;
19
-
20
- if (!request) {
21
- return callback();
22
- }
23
-
24
- /**
25
- * Externalize Node.js built-in modules
26
- */
27
- const isBuiltinModule =
28
- builtinModules.includes(request) ||
29
- builtinModules.includes(request.replace(/^node:/, ""));
30
- if (isBuiltinModule) {
31
- return callback(undefined, `commonjs ${request}`);
32
- }
33
-
34
- // Check if request is inside .xmcp folder - if so, bundle it
35
- if (request.includes(".xmcp")) {
36
- return callback();
37
- }
38
-
39
- // Check if request is a runtime file that we've injected - if so, bundle it
40
- // Only include runtime files that are actually injected (conditional loading)
41
- const filesToInclude = [...Object.keys(runtimeFiles), "import-map.js"];
42
- for (const file of filesToInclude) {
43
- if (
44
- request.endsWith(`./${file}`) ||
45
- request.endsWith(`./${file.replace(".js", "")}`)
46
- ) {
47
- return callback();
48
- }
49
- }
50
-
51
- /**
52
- * When using Next.js, we want them to bundle the code for the tool file,
53
- * so just keep the reference for the import as external
54
- */
55
- if (xmcpConfig.experimental?.adapter === "nextjs") {
56
- // Bundle imports from the same folder
57
- if (request.startsWith("./")) {
58
- return callback();
59
- }
60
-
61
- let pathRequest = request;
62
- /**
63
- * Paths are relative to the .xmcp/nextjs-adapter folder,
64
- * but we are building in .xmcp/adapter/index.js, so we need to go up 2 levels
65
- */
66
- if (request.startsWith("../")) {
67
- // Only replace the import if it hasn't been replaced yet
68
- if (!replacedImports.has(request)) {
69
- pathRequest = pathRequest.replace("../", "../../");
70
- replacedImports.add(pathRequest);
71
- }
72
- }
73
-
74
- return callback(undefined, `commonjs ${pathRequest}`);
75
- }
76
-
77
- /**
78
- * When using Fastify, externalize fastify since it should come from
79
- * the user's node_modules
80
- */
81
- if (xmcpConfig.experimental?.adapter === "fastify") {
82
- if (request === "fastify" || request.startsWith("fastify/")) {
83
- return callback(undefined, `commonjs ${request}`);
84
- }
85
- }
86
-
87
- /**
88
- * When using NestJS, externalize NestJS-related packages
89
- * since they should come from the user's node_modules
90
- */
91
- if (xmcpConfig.experimental?.adapter === "nestjs") {
92
- // Externalize NestJS core packages
93
- const nestjsPackages = [
94
- "@nestjs/common",
95
- "@nestjs/core",
96
- "@nestjs/platform-express",
97
- "reflect-metadata",
98
- "rxjs",
99
- ];
100
-
101
- if (
102
- nestjsPackages.some(
103
- (pkg) => request === pkg || request.startsWith(`${pkg}/`)
104
- )
105
- ) {
106
- return callback(undefined, `commonjs ${request}`);
107
- }
108
- }
109
-
110
- // Bundle relative imports and absolute paths
111
- callback();
112
- },
113
- ];
114
- }