xmcp 0.6.4 → 0.6.6

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 (41) hide show
  1. package/dist/cli.js +45 -29
  2. package/dist/compiler/config/index.d.ts +59 -0
  3. package/dist/compiler/config/schemas/template.d.ts +40 -0
  4. package/dist/compiler/config/schemas/transport/stdio.d.ts +5 -0
  5. package/dist/index.d.ts +2 -2
  6. package/dist/index.js +4 -4
  7. package/dist/runtime/adapter-express.js +15 -38
  8. package/dist/runtime/adapter-nestjs.js +17 -40
  9. package/dist/runtime/adapter-nextjs.js +16 -39
  10. package/dist/runtime/http.js +23 -46
  11. package/dist/runtime/stdio.js +16 -39
  12. package/dist/types/resource.d.ts +3 -3
  13. package/dist/types/tool.d.ts +4 -4
  14. package/dist/types/ui-meta.d.ts +22 -0
  15. package/package.json +2 -2
  16. package/src/compiler/client/component-compiler.ts +0 -4
  17. package/src/compiler/config/__tests__/config.test.ts +36 -0
  18. package/src/compiler/config/injection.ts +63 -1
  19. package/src/compiler/config/schemas/template.ts +17 -0
  20. package/src/compiler/config/schemas/transport/stdio.ts +1 -0
  21. package/src/compiler/generate-tools-code.ts +21 -1
  22. package/src/compiler/get-bundler-config/get-injected-variables.ts +3 -0
  23. package/src/compiler/index.ts +100 -24
  24. package/src/compiler/on-first-build.ts +34 -50
  25. package/src/compiler/start-http-server.ts +11 -4
  26. package/src/compiler/watcher-recovery.ts +72 -0
  27. package/src/index.ts +2 -1
  28. package/src/runtime/transports/stdio/index.ts +19 -0
  29. package/src/runtime/utils/react/generate-html.ts +0 -32
  30. package/src/runtime/utils/resources.ts +15 -15
  31. package/src/runtime/utils/server.ts +5 -8
  32. package/src/runtime/utils/tools.ts +55 -71
  33. package/src/runtime/utils/transformers/tool.ts +148 -30
  34. package/src/types/resource.ts +3 -3
  35. package/src/types/tool.ts +4 -4
  36. package/src/types/ui-meta.ts +26 -0
  37. package/dist/types/openai-meta.d.ts +0 -173
  38. package/src/runtime/utils/openai/flatten-meta.ts +0 -44
  39. package/src/runtime/utils/openai/split-meta.ts +0 -81
  40. package/src/runtime/utils/openai-resource-registry.ts +0 -58
  41. package/src/types/openai-meta.ts +0 -191
@@ -0,0 +1,72 @@
1
+ import path from "path";
2
+ import fs from "fs";
3
+
4
+ function normalizeSlashes(value: string): string {
5
+ return value.replace(/\\/g, "/");
6
+ }
7
+
8
+ function stripLeadingDotSlash(value: string): string {
9
+ return value.replace(/^\.\//, "");
10
+ }
11
+
12
+ export function toProjectRelativePath(
13
+ filePath: string,
14
+ cwd: string = process.cwd()
15
+ ): string {
16
+ const relativePath = path.isAbsolute(filePath)
17
+ ? path.relative(cwd, filePath)
18
+ : filePath;
19
+
20
+ return stripLeadingDotSlash(normalizeSlashes(relativePath));
21
+ }
22
+
23
+ export function addWatchedPath(
24
+ pathSet: Set<string>,
25
+ filePath: string,
26
+ cwd: string = process.cwd()
27
+ ) {
28
+ pathSet.add(toProjectRelativePath(filePath, cwd));
29
+ }
30
+
31
+ export function removeWatchedPath(
32
+ pathSet: Set<string>,
33
+ filePath: string,
34
+ cwd: string = process.cwd()
35
+ ) {
36
+ const normalizedRawPath = stripLeadingDotSlash(normalizeSlashes(filePath));
37
+ const normalizedRelativePath = toProjectRelativePath(filePath, cwd);
38
+
39
+ const normalizedCandidates = new Set<string>([
40
+ normalizedRawPath,
41
+ normalizedRelativePath,
42
+ ]);
43
+
44
+ for (const currentPath of Array.from(pathSet)) {
45
+ const normalizedCurrentPath = stripLeadingDotSlash(
46
+ normalizeSlashes(currentPath)
47
+ );
48
+
49
+ if (normalizedCandidates.has(normalizedCurrentPath)) {
50
+ pathSet.delete(currentPath);
51
+ }
52
+ }
53
+ }
54
+
55
+ export function pruneMissingWatchedPaths(
56
+ pathSet: Set<string>,
57
+ cwd: string = process.cwd()
58
+ ): boolean {
59
+ let removed = false;
60
+
61
+ for (const currentPath of Array.from(pathSet)) {
62
+ const normalized = stripLeadingDotSlash(normalizeSlashes(currentPath));
63
+ const absolutePath = path.resolve(cwd, normalized);
64
+
65
+ if (!fs.existsSync(absolutePath)) {
66
+ pathSet.delete(currentPath);
67
+ removed = true;
68
+ }
69
+ }
70
+
71
+ return removed;
72
+ }
package/src/index.ts CHANGED
@@ -5,12 +5,13 @@ dotenv.config();
5
5
  export type {
6
6
  ToolMetadata,
7
7
  ToolSchema,
8
+ ToolOutputSchema,
8
9
  ToolExtraArguments,
9
10
  InferSchema,
10
11
  } from "./types/tool";
11
12
  export type { PromptMetadata } from "./types/prompt";
12
13
  export type { ResourceMetadata } from "./types/resource";
13
- export type { OpenAIMetadata, OpenAIToolInvocation } from "./types/openai-meta";
14
+ export type { UIMetadata } from "./types/ui-meta";
14
15
 
15
16
  export type { XmcpConfigInputSchema as XmcpConfig } from "./compiler/config";
16
17
  import "./types/declarations";
@@ -52,6 +52,25 @@ class StdioTransport {
52
52
 
53
53
  // @ts-expect-error: injected by compiler
54
54
  const debug = STDIO_CONFIG.debug || false;
55
+ // @ts-expect-error: injected by compiler
56
+ const silent = STDIO_CONFIG.silent || false;
57
+
58
+ if (silent) {
59
+ // Redirect all console methods to stderr so they don't interfere with
60
+ // the MCP stdio protocol on stdout.
61
+ const stderrConsole = new console.Console(process.stderr, process.stderr);
62
+ const methods = [
63
+ "log", "debug", "info", "warn", "error",
64
+ "dir", "table", "trace", "assert",
65
+ "time", "timeEnd", "timeLog",
66
+ "count", "countReset",
67
+ "group", "groupEnd", "groupCollapsed",
68
+ "clear",
69
+ ] as const;
70
+ for (const method of methods) {
71
+ (console as any)[method] = (stderrConsole as any)[method].bind(stderrConsole);
72
+ }
73
+ }
55
74
 
56
75
  createServer().then((mcpServer) => {
57
76
  const stdioTransport = new StdioTransport(mcpServer, debug);
@@ -1,35 +1,3 @@
1
- export function generateOpenAIHTML(
2
- componentCode: string,
3
- css: string | undefined
4
- ): string {
5
- const styleTag = css ? `<style>${css}</style>` : "";
6
-
7
- return `<!DOCTYPE html>
8
- <html>
9
- <head>
10
- <meta charset="utf-8" />
11
- <meta name="viewport" content="width=device-width, initial-scale=1" />
12
- ${styleTag}
13
- </head>
14
- <body>
15
- <div id="root"></div>
16
-
17
- <script type="module">
18
- const componentSource = ${JSON.stringify(componentCode)};
19
- const blobUrl = URL.createObjectURL(
20
- new Blob([componentSource], { type: "text/javascript" })
21
- );
22
-
23
- await import(blobUrl);
24
-
25
- requestAnimationFrame(() => {
26
- URL.revokeObjectURL(blobUrl);
27
- });
28
- </script>
29
- </body>
30
- </html>`;
31
- }
32
-
33
1
  export function generateUIHTML(
34
2
  componentCode: string,
35
3
  css: string | undefined
@@ -9,9 +9,8 @@ import { ZodRawShape } from "zod/v3";
9
9
  import { transformResourceHandler } from "./transformers/resource";
10
10
  import { composeUriFromPath } from "./utils/resource-uri-composer";
11
11
  import { ResourceMetadata } from "@/types/resource";
12
- import { openAIResourceRegistry } from "./openai-resource-registry";
13
- import { flattenMeta } from "./openai/flatten-meta";
14
- import { generateOpenAIHTML, generateUIHTML } from "./react/generate-html";
12
+ import { flattenMeta } from "./ui/flatten-meta";
13
+ import { generateUIHTML } from "./react/generate-html";
15
14
  import { pathToToolNameMd5, pathToToolNameDjb2 } from "./path-to-tool-name";
16
15
  import { uIResourceRegistry } from "./ext-apps-registry";
17
16
 
@@ -90,13 +89,11 @@ export function addResourcesToServer(
90
89
  server: McpServer,
91
90
  resourcesModules: Map<string, ResourceFile>
92
91
  ): McpServer {
93
- // register auto generated resources from openai tools
94
- const autoGeneratedResources = [
95
- ...openAIResourceRegistry.getAll(),
96
- ...uIResourceRegistry.getAll(),
97
- ];
92
+ const autoGeneratedResources = [...uIResourceRegistry.getAll()];
98
93
 
99
94
  autoGeneratedResources.forEach(([_, autoResource]) => {
95
+ const resourceMimeType =
96
+ autoResource.mimeType || "text/html;profile=mcp-app";
100
97
  // Flatten resource metadata for MCP protocol
101
98
  const flattenedResourceMeta = autoResource?._meta
102
99
  ? flattenMeta(autoResource._meta)
@@ -129,18 +126,14 @@ export function addResourcesToServer(
129
126
  const clientCode = bundle.js;
130
127
  const clientCss = bundle.css;
131
128
 
132
- const isMCPApp =
133
- autoResource.mimeType === "text/html;profile=mcp-app";
134
- const fullHTML = isMCPApp
135
- ? generateUIHTML(clientCode, clientCss)
136
- : generateOpenAIHTML(clientCode, clientCss);
129
+ const fullHTML = generateUIHTML(clientCode, clientCss);
137
130
 
138
131
  return {
139
132
  contents: [
140
133
  {
141
134
  uri: autoResource.uri,
142
135
  text: fullHTML,
143
- mimeType: autoResource.mimeType,
136
+ mimeType: resourceMimeType,
144
137
  _meta: autoResource._meta,
145
138
  },
146
139
  ],
@@ -165,13 +158,14 @@ export function addResourcesToServer(
165
158
  {
166
159
  uri: autoResource.uri,
167
160
  text: response,
161
+ mimeType: resourceMimeType,
162
+ _meta: autoResource._meta,
168
163
  },
169
164
  ],
170
165
  };
171
166
  }
172
167
 
173
168
  // If the tool returns { _meta: ... }, return empty HTML
174
- // (OpenAI handles the rendering)
175
169
  if (
176
170
  response &&
177
171
  typeof response === "object" &&
@@ -183,6 +177,8 @@ export function addResourcesToServer(
183
177
  {
184
178
  uri: autoResource.uri,
185
179
  text: "",
180
+ mimeType: resourceMimeType,
181
+ _meta: autoResource._meta,
186
182
  },
187
183
  ],
188
184
  };
@@ -208,6 +204,8 @@ export function addResourcesToServer(
208
204
  {
209
205
  uri: autoResource.uri,
210
206
  text: textContent.text,
207
+ mimeType: resourceMimeType,
208
+ _meta: autoResource._meta,
211
209
  },
212
210
  ],
213
211
  };
@@ -220,6 +218,8 @@ export function addResourcesToServer(
220
218
  {
221
219
  uri: autoResource.uri,
222
220
  text: "",
221
+ mimeType: resourceMimeType,
222
+ _meta: autoResource._meta,
223
223
  },
224
224
  ],
225
225
  };
@@ -10,11 +10,12 @@ import { UserResourceHandler } from "./transformers/resource";
10
10
  import { ZodRawShape } from "zod/v3";
11
11
  import { addResourcesToServer } from "./resources";
12
12
  import { ResourceMetadata } from "@/types/resource";
13
- import { openAIResourceRegistry } from "./openai-resource-registry";
13
+ import { uIResourceRegistry } from "./ext-apps-registry";
14
14
 
15
15
  export type ToolFile = {
16
16
  metadata: ToolMetadata;
17
17
  schema: ZodRawShape;
18
+ outputSchema?: ZodRawShape;
18
19
  default: UserToolHandler;
19
20
  };
20
21
 
@@ -48,11 +49,8 @@ export const injectedResources = INJECTED_RESOURCES as Record<
48
49
  () => Promise<ResourceFile>
49
50
  >;
50
51
 
51
- export const INJECTED_CONFIG = {
52
- // TODO get from project config
53
- name: "MCP Server",
54
- version: "0.0.1",
55
- } as const satisfies Implementation;
52
+ // @ts-expect-error: injected by compiler
53
+ export const INJECTED_CONFIG = SERVER_INFO as Implementation;
56
54
 
57
55
  /* Loads all modules and injects them into the server */
58
56
  // would be better as a class and use dependency injection perhaps
@@ -62,8 +60,7 @@ export async function configureServer(
62
60
  promptModules: Map<string, PromptFile>,
63
61
  resourceModules: Map<string, ResourceFile>
64
62
  ): Promise<McpServer> {
65
- // Clear the OpenAI resource registry before configuring to prevent stale entries
66
- openAIResourceRegistry.clear();
63
+ uIResourceRegistry.clear();
67
64
 
68
65
  addToolsToServer(server, toolModules);
69
66
  addPromptsToServer(server, promptModules);
@@ -4,14 +4,11 @@ import { ZodRawShape } from "zod/v3";
4
4
  import { ToolFile } from "./server";
5
5
  import { ToolMetadata } from "@/types/tool";
6
6
  import { transformToolHandler } from "./transformers/tool";
7
- import { openAIResourceRegistry } from "./openai-resource-registry";
8
- import { flattenMeta, hasOpenAIMeta } from "./openai/flatten-meta";
9
7
  import { isReactFile } from "./react";
10
- import { splitOpenAIMetaNested } from "./openai/split-meta";
11
8
  import { uIResourceRegistry } from "./ext-apps-registry";
12
- import { hasUIMeta } from "./ui/flatten-meta";
9
+ import { flattenMeta, hasUIMeta } from "./ui/flatten-meta";
13
10
  import { splitUIMetaNested } from "./ui/split-meta";
14
- import { isPaidHandler, getX402Registry } from "xmcp/plugins/x402";
11
+ import { isPaidHandler, getX402Registry } from "@/plugins/x402";
15
12
 
16
13
  /** Validates if a value is a valid Zod schema object */
17
14
  export function isZodRawShape(value: unknown): value is ZodRawShape {
@@ -46,7 +43,7 @@ export function addToolsToServer(
46
43
  description: "No description provided",
47
44
  };
48
45
 
49
- const { default: handler, metadata, schema } = toolModule;
46
+ const { default: handler, metadata, schema, outputSchema } = toolModule;
50
47
 
51
48
  if (typeof metadata === "object" && metadata !== null) {
52
49
  Object.assign(toolConfig, metadata);
@@ -70,6 +67,17 @@ export function addToolsToServer(
70
67
  );
71
68
  }
72
69
 
70
+ let toolOutputSchema: ZodRawShape | undefined;
71
+ if (outputSchema !== undefined && outputSchema !== null) {
72
+ if (isZodRawShape(outputSchema)) {
73
+ toolOutputSchema = outputSchema;
74
+ } else {
75
+ throw new Error(
76
+ `Invalid outputSchema for tool "${toolConfig.name}" at ${path}. Expected Record<string, z.ZodType>`
77
+ );
78
+ }
79
+ }
80
+
73
81
  // Make sure tools has annotations with a title
74
82
  if (toolConfig.annotations === undefined) {
75
83
  toolConfig.annotations = {};
@@ -84,85 +92,53 @@ export function addToolsToServer(
84
92
 
85
93
  const isReact = isReactFile(path);
86
94
 
87
- // Check if this is an OpenAI widget tool
88
- const openaiWidget = hasOpenAIMeta(toolConfig._meta);
89
- const uiWidget = hasUIMeta(toolConfig._meta) || (isReact && !openaiWidget);
95
+ const uiWidget = hasUIMeta(toolConfig._meta) || isReact;
90
96
 
91
97
  let toolSpecificMeta = toolConfig._meta;
92
98
 
93
- if (uiWidget || openaiWidget) {
94
- const openaiResourceUri = `ui://widget/${toolConfig.name}.html`;
99
+ if (uiWidget) {
95
100
  const mcpuiResourceUri = `ui://app/${toolConfig.name}.html`;
96
101
 
97
- // Auto-inject outputTemplate and resourceUri before splitting
98
- if (openaiWidget) {
99
- if (!toolConfig._meta.openai) {
100
- toolConfig._meta.openai = {};
101
- }
102
- if (!toolConfig._meta.openai.outputTemplate) {
103
- toolConfig._meta.openai.outputTemplate = openaiResourceUri;
104
- }
102
+ if (!toolConfig._meta.ui) {
103
+ toolConfig._meta.ui = {};
105
104
  }
106
-
107
- if (uiWidget) {
108
- if (!toolConfig._meta.ui) {
109
- toolConfig._meta.ui = {};
110
- }
111
- if (!toolConfig._meta.ui.resourceUri) {
112
- toolConfig._meta.ui.resourceUri = mcpuiResourceUri;
113
- }
105
+ if (!toolConfig._meta.ui.resourceUri) {
106
+ toolConfig._meta.ui.resourceUri = mcpuiResourceUri;
114
107
  }
115
108
 
116
- // Split metadata only for the widgets that are enabled
117
- if (openaiWidget) {
118
- const openaiSplit = splitOpenAIMetaNested(toolSpecificMeta);
119
- toolSpecificMeta = openaiSplit.toolMeta;
120
-
121
- openAIResourceRegistry.add(toolConfig.name, {
122
- name: toolConfig.name,
123
- uri: openaiResourceUri,
124
- handler,
125
- _meta: openaiSplit.resourceMeta,
126
- toolPath: isReact ? path : undefined,
127
- mimeType: "text/html+skybridge",
128
- });
109
+ const uiSplit = splitUIMetaNested(toolSpecificMeta);
110
+ toolSpecificMeta = uiSplit.toolMeta;
111
+ const resourceSpecificMeta = uiSplit.resourceMeta;
112
+
113
+ // Ensure CSP resource domains includes esm.sh
114
+ resourceSpecificMeta.ui = resourceSpecificMeta.ui || {};
115
+ resourceSpecificMeta.ui.csp = resourceSpecificMeta.ui.csp || {};
116
+ resourceSpecificMeta.ui.csp.resourceDomains =
117
+ resourceSpecificMeta.ui.csp.resourceDomains || [];
118
+
119
+ if (
120
+ !resourceSpecificMeta.ui.csp.resourceDomains.includes(
121
+ "https://esm.sh"
122
+ )
123
+ ) {
124
+ resourceSpecificMeta.ui.csp.resourceDomains.push("https://esm.sh");
129
125
  }
130
126
 
131
- if (uiWidget) {
132
- const uiSplit = splitUIMetaNested(toolSpecificMeta);
133
- toolSpecificMeta = uiSplit.toolMeta;
134
- const resourceSpecificMeta = uiSplit.resourceMeta;
135
-
136
- // Ensure CSP resource domains includes esm.sh
137
- resourceSpecificMeta.ui = resourceSpecificMeta.ui || {};
138
- resourceSpecificMeta.ui.csp = resourceSpecificMeta.ui.csp || {};
139
- resourceSpecificMeta.ui.csp.resourceDomains =
140
- resourceSpecificMeta.ui.csp.resourceDomains || [];
141
-
142
- if (
143
- !resourceSpecificMeta.ui.csp.resourceDomains.includes(
144
- "https://esm.sh"
145
- )
146
- ) {
147
- resourceSpecificMeta.ui.csp.resourceDomains.push("https://esm.sh");
148
- }
149
-
150
- uIResourceRegistry.add(toolConfig.name, {
151
- name: toolConfig.name,
152
- uri: mcpuiResourceUri,
153
- handler,
154
- mimeType: "text/html;profile=mcp-app",
155
- _meta: resourceSpecificMeta,
156
- toolPath: isReact ? path : undefined,
157
- });
158
- }
127
+ uIResourceRegistry.add(toolConfig.name, {
128
+ name: toolConfig.name,
129
+ uri: mcpuiResourceUri,
130
+ handler,
131
+ mimeType: "text/html;profile=mcp-app",
132
+ _meta: resourceSpecificMeta,
133
+ toolPath: isReact ? path : undefined,
134
+ });
159
135
  }
160
136
 
161
137
  const flattenedToolMeta = flattenMeta(toolSpecificMeta);
162
- const meta = openaiWidget || uiWidget ? flattenedToolMeta : undefined;
138
+ const meta = uiWidget ? flattenedToolMeta : undefined;
163
139
  let transformedHandler;
164
140
 
165
- if (isReactFile(path) && (openaiWidget || uiWidget)) {
141
+ if (isReactFile(path) && uiWidget) {
166
142
  transformedHandler = async (args: any, extra: any) => ({
167
143
  content: [{ type: "text", text: "" }],
168
144
  _meta: meta,
@@ -171,7 +147,12 @@ export function addToolsToServer(
171
147
  },
172
148
  });
173
149
  } else {
174
- transformedHandler = transformToolHandler(handler, meta);
150
+ transformedHandler = transformToolHandler(
151
+ handler,
152
+ meta,
153
+ toolOutputSchema,
154
+ toolConfig.name
155
+ );
175
156
  }
176
157
 
177
158
  const toolConfigFormatted = {
@@ -180,6 +161,9 @@ export function addToolsToServer(
180
161
  // Build the object schema using the project's Zod instance to avoid
181
162
  // cross-instance v3 shape issues in tools/list JSON schema generation.
182
163
  inputSchema: z.object(toolSchema),
164
+ outputSchema: toolOutputSchema
165
+ ? z.object(toolOutputSchema).strict()
166
+ : undefined,
183
167
  annotations: toolConfig.annotations,
184
168
  _meta: flattenedToolMeta, // Use flattened metadata for MCP protocol
185
169
  };