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,473 +0,0 @@
1
- import {
2
- HOST_CONTEXT_CHANGED_METHOD,
3
- HOST_CONTEXT_CHANGED_METHOD_LEGACY,
4
- LOG_MESSAGE_METHOD,
5
- OPEN_LINK_METHOD,
6
- OPEN_LINK_METHOD_LEGACY,
7
- REQUEST_DISPLAY_MODE_METHOD,
8
- REQUEST_DISPLAY_MODE_METHOD_LEGACY,
9
- RESOURCES_READ_METHOD,
10
- SIZE_CHANGED_METHOD,
11
- UI_MESSAGE_METHOD,
12
- UPDATE_MODEL_CONTEXT_METHOD,
13
- } from "./mcp-app-protocol";
14
- import type {
15
- McpHostCallToolParams,
16
- McpHostCapabilities,
17
- McpHostContainerDimensions,
18
- McpHostContext,
19
- McpHostMessageResult,
20
- McpHostModelContextResult,
21
- McpHostOpenLinkParams,
22
- McpHostReadResourceResult,
23
- McpHostRequestDisplayModeParams,
24
- McpHostRequestDisplayModeResult,
25
- McpHostSendMessageParams,
26
- McpHostToolResult,
27
- McpUiDisplayMode,
28
- McpHostUpdateModelContextParams,
29
- } from "./mcp-app-types";
30
-
31
- export * from "./mcp-app-protocol";
32
- export type * from "./mcp-app-types";
33
-
34
- export interface McpHostBridgeState {
35
- isConnected: boolean;
36
- hostContext: McpHostContext | null;
37
- hostCapabilities: McpHostCapabilities | null;
38
- }
39
-
40
- export interface McpHostBridge {
41
- callTool: (
42
- name: McpHostCallToolParams["name"],
43
- args?: McpHostCallToolParams["arguments"]
44
- ) => Promise<McpHostToolResult>;
45
- requestDisplayMode: (
46
- mode: McpUiDisplayMode
47
- ) => Promise<McpHostRequestDisplayModeResult>;
48
- openLink: (url: McpHostOpenLinkParams["url"]) => Promise<void>;
49
- readResource: (uri: string) => Promise<McpHostReadResourceResult>;
50
- sendMessage: (params: McpHostSendMessageParams) => Promise<McpHostMessageResult>;
51
- updateModelContext: (
52
- params: McpHostUpdateModelContextParams
53
- ) => Promise<McpHostModelContextResult>;
54
- logMessage: (params: McpHostSendMessageParams) => Promise<void>;
55
- notifySizeChanged: (
56
- params: McpHostContainerDimensions
57
- ) => Promise<void>;
58
- getState: () => McpHostBridgeState;
59
- getHostContext: () => McpHostContext | null;
60
- getHostCapabilities: () => McpHostCapabilities | null;
61
- isConnected: () => boolean;
62
- subscribe: (listener: (state: McpHostBridgeState) => void) => () => void;
63
- dispose: () => void;
64
- }
65
-
66
- interface PendingRequest {
67
- resolve: (value: unknown) => void;
68
- reject: (error: Error) => void;
69
- timeoutId: ReturnType<typeof setTimeout>;
70
- }
71
-
72
- interface MessageEventLike {
73
- source: unknown;
74
- data: unknown;
75
- }
76
-
77
- interface MessageTargetLike {
78
- postMessage: (message: unknown, targetOrigin: string) => void;
79
- }
80
-
81
- interface WindowLike extends MessageTargetLike {
82
- parent: MessageTargetLike;
83
- open?: (url: string, target?: string, features?: string) => unknown;
84
- addEventListener: (
85
- type: "message",
86
- listener: (event: MessageEventLike) => void
87
- ) => void;
88
- removeEventListener: (
89
- type: "message",
90
- listener: (event: MessageEventLike) => void
91
- ) => void;
92
- }
93
-
94
- export interface CreateMcpHostBridgeOptions {
95
- targetWindow?: WindowLike;
96
- requestTimeoutMs?: number;
97
- connectionTimeoutMs?: number;
98
- }
99
-
100
- function getDefaultWindow(): WindowLike | null {
101
- if (typeof window === "undefined") {
102
- return null;
103
- }
104
- return window as unknown as WindowLike;
105
- }
106
-
107
- function isRecord(value: unknown): value is Record<string, unknown> {
108
- return !!value && typeof value === "object";
109
- }
110
-
111
- function toErrorMessage(error: unknown, fallback: string): string {
112
- if (error instanceof Error && error.message) {
113
- return error.message;
114
- }
115
- return fallback;
116
- }
117
-
118
- function mergeHostContext(
119
- current: McpHostContext | null,
120
- incoming: McpHostContext
121
- ): McpHostContext {
122
- const merged: McpHostContext = {
123
- ...(current ?? {}),
124
- ...incoming,
125
- };
126
-
127
- if (current?.safeAreaInsets || incoming.safeAreaInsets) {
128
- merged.safeAreaInsets = {
129
- ...(current?.safeAreaInsets ?? {}),
130
- ...(incoming.safeAreaInsets ?? {}),
131
- };
132
- }
133
-
134
- if (current?.containerDimensions || incoming.containerDimensions) {
135
- merged.containerDimensions = {
136
- ...(current?.containerDimensions ?? {}),
137
- ...(incoming.containerDimensions ?? {}),
138
- };
139
- }
140
-
141
- if (current?.styles || incoming.styles) {
142
- merged.styles = {
143
- ...(current?.styles ?? {}),
144
- ...(incoming.styles ?? {}),
145
- variables:
146
- current?.styles?.variables || incoming.styles?.variables
147
- ? {
148
- ...(current?.styles?.variables ?? {}),
149
- ...(incoming.styles?.variables ?? {}),
150
- }
151
- : undefined,
152
- css:
153
- current?.styles?.css || incoming.styles?.css
154
- ? {
155
- ...(current?.styles?.css ?? {}),
156
- ...(incoming.styles?.css ?? {}),
157
- }
158
- : undefined,
159
- };
160
- }
161
-
162
- return merged;
163
- }
164
-
165
- export function createMcpHostBridge(
166
- options: CreateMcpHostBridgeOptions = {}
167
- ): McpHostBridge {
168
- const targetWindow = options.targetWindow ?? getDefaultWindow();
169
- const requestTimeoutMs = options.requestTimeoutMs ?? 15_000;
170
- const connectionTimeoutMs = options.connectionTimeoutMs ?? 2_000;
171
-
172
- let nextId = 100;
173
- let disposed = false;
174
- let hasObservedHostTraffic = false;
175
- let state: McpHostBridgeState = {
176
- isConnected: !!targetWindow && targetWindow.parent !== targetWindow,
177
- hostContext: null,
178
- hostCapabilities: null,
179
- };
180
-
181
- const listeners = new Set<(state: McpHostBridgeState) => void>();
182
- const pending = new Map<number, PendingRequest>();
183
-
184
- const emit = () => {
185
- for (const listener of listeners) {
186
- listener(state);
187
- }
188
- };
189
-
190
- const setState = (nextState: McpHostBridgeState) => {
191
- if (
192
- nextState.isConnected === state.isConnected &&
193
- nextState.hostContext === state.hostContext &&
194
- nextState.hostCapabilities === state.hostCapabilities
195
- ) {
196
- return;
197
- }
198
- state = nextState;
199
- emit();
200
- };
201
-
202
- const rejectPending = (message: string) => {
203
- for (const [id, request] of pending.entries()) {
204
- clearTimeout(request.timeoutId);
205
- request.reject(new Error(message));
206
- pending.delete(id);
207
- }
208
- };
209
-
210
- const applyHostUpdate = (incoming: {
211
- hostContext?: McpHostContext;
212
- hostCapabilities?: McpHostCapabilities;
213
- }) => {
214
- const nextContext = incoming.hostContext
215
- ? mergeHostContext(state.hostContext, incoming.hostContext)
216
- : state.hostContext;
217
- const nextCapabilities = incoming.hostCapabilities
218
- ? {
219
- ...(state.hostCapabilities ?? {}),
220
- ...incoming.hostCapabilities,
221
- }
222
- : state.hostCapabilities;
223
-
224
- setState({
225
- isConnected: true,
226
- hostContext: nextContext,
227
- hostCapabilities: nextCapabilities,
228
- });
229
- };
230
-
231
- const handleMessage = (event: MessageEventLike) => {
232
- if (!targetWindow || event.source !== targetWindow.parent) return;
233
- if (!isRecord(event.data)) return;
234
-
235
- hasObservedHostTraffic = true;
236
- if (!state.isConnected) {
237
- setState({ ...state, isConnected: true });
238
- }
239
-
240
- const data = event.data;
241
-
242
- if ("id" in data && data.id != null && typeof data.id === "number") {
243
- const request = pending.get(data.id);
244
- if (request) {
245
- clearTimeout(request.timeoutId);
246
- pending.delete(data.id);
247
- if (isRecord(data.error)) {
248
- request.reject(
249
- new Error(
250
- typeof data.error.message === "string"
251
- ? data.error.message
252
- : "MCP request failed"
253
- )
254
- );
255
- } else {
256
- request.resolve(data.result);
257
- }
258
- }
259
- }
260
-
261
- if (data.id === 1 && isRecord(data.result)) {
262
- applyHostUpdate({
263
- hostContext: isRecord(data.result.hostContext)
264
- ? (data.result.hostContext as McpHostContext)
265
- : undefined,
266
- hostCapabilities: isRecord(data.result.hostCapabilities)
267
- ? (data.result.hostCapabilities as McpHostCapabilities)
268
- : undefined,
269
- });
270
- }
271
-
272
- if (
273
- data.method === HOST_CONTEXT_CHANGED_METHOD &&
274
- isRecord(data.params)
275
- ) {
276
- applyHostUpdate({
277
- hostContext: data.params as McpHostContext,
278
- });
279
- }
280
-
281
- if (
282
- data.method === HOST_CONTEXT_CHANGED_METHOD_LEGACY &&
283
- isRecord(data.params) &&
284
- isRecord(data.params.hostContext)
285
- ) {
286
- applyHostUpdate({
287
- hostContext: data.params.hostContext as McpHostContext,
288
- });
289
- }
290
- };
291
-
292
- if (targetWindow) {
293
- targetWindow.addEventListener("message", handleMessage);
294
-
295
- if (targetWindow.parent !== targetWindow) {
296
- setTimeout(() => {
297
- if (disposed || hasObservedHostTraffic || state.hostContext) return;
298
- setState({ ...state, isConnected: false });
299
- }, connectionTimeoutMs);
300
- }
301
- }
302
-
303
- const ensureWindow = (): WindowLike => {
304
- if (disposed) {
305
- throw new Error("MCP host bridge has been disposed");
306
- }
307
- if (!targetWindow) {
308
- throw new Error("MCP host bridge requires a browser window");
309
- }
310
- return targetWindow;
311
- };
312
-
313
- const sendNotification = (method: string, params: unknown) => {
314
- const activeWindow = ensureWindow();
315
- activeWindow.parent.postMessage(
316
- {
317
- jsonrpc: "2.0",
318
- method,
319
- params,
320
- },
321
- "*"
322
- );
323
- };
324
-
325
- const sendRequest = (
326
- method: string,
327
- params: Record<string, unknown> = {}
328
- ): Promise<unknown> => {
329
- const activeWindow = ensureWindow();
330
-
331
- return new Promise((resolve, reject) => {
332
- const id = nextId++;
333
- const timeoutId = setTimeout(() => {
334
- if (!pending.has(id)) return;
335
- pending.delete(id);
336
- reject(new Error(`MCP request timed out: ${method}`));
337
- }, requestTimeoutMs);
338
-
339
- pending.set(id, { resolve, reject, timeoutId });
340
-
341
- activeWindow.parent.postMessage(
342
- {
343
- jsonrpc: "2.0",
344
- id,
345
- method,
346
- params,
347
- },
348
- "*"
349
- );
350
- });
351
- };
352
-
353
- const sendRequestWithFallback = async (
354
- methods: string[],
355
- params: Record<string, unknown>
356
- ) => {
357
- let lastError: unknown;
358
-
359
- for (const method of methods) {
360
- try {
361
- return await sendRequest(method, params);
362
- } catch (error) {
363
- lastError = error;
364
- const message = toErrorMessage(error, "MCP request failed");
365
- if (!/method not found|unknown method/i.test(message)) {
366
- throw error;
367
- }
368
- }
369
- }
370
-
371
- throw lastError instanceof Error
372
- ? lastError
373
- : new Error("MCP request failed");
374
- };
375
-
376
- const fallbackOpen = async (url: string) => {
377
- if (targetWindow?.open) {
378
- targetWindow.open(url, "_blank", "noopener,noreferrer");
379
- return;
380
- }
381
- throw new Error("Unable to open link without a browser window");
382
- };
383
-
384
- return {
385
- callTool(name, args) {
386
- return sendRequest("tools/call", {
387
- name,
388
- arguments: args ?? {},
389
- }) as Promise<McpHostToolResult>;
390
- },
391
-
392
- requestDisplayMode(mode) {
393
- return sendRequestWithFallback(
394
- [REQUEST_DISPLAY_MODE_METHOD, REQUEST_DISPLAY_MODE_METHOD_LEGACY],
395
- { mode }
396
- ) as Promise<McpHostRequestDisplayModeResult>;
397
- },
398
-
399
- async openLink(url) {
400
- try {
401
- await sendRequestWithFallback(
402
- [OPEN_LINK_METHOD, OPEN_LINK_METHOD_LEGACY],
403
- { url }
404
- );
405
- } catch (error) {
406
- const canFallback = !state.isConnected || !targetWindow;
407
- if (canFallback) {
408
- await fallbackOpen(url);
409
- return;
410
- }
411
- throw new Error(toErrorMessage(error, "Failed to open link"));
412
- }
413
- },
414
-
415
- readResource(uri) {
416
- return sendRequest(RESOURCES_READ_METHOD, {
417
- uri,
418
- }) as Promise<McpHostReadResourceResult>;
419
- },
420
-
421
- sendMessage(params) {
422
- return sendRequest(UI_MESSAGE_METHOD, params) as Promise<McpHostMessageResult>;
423
- },
424
-
425
- updateModelContext(params) {
426
- return sendRequest(
427
- UPDATE_MODEL_CONTEXT_METHOD,
428
- params
429
- ) as Promise<McpHostModelContextResult>;
430
- },
431
-
432
- async logMessage(params) {
433
- sendNotification(LOG_MESSAGE_METHOD, params);
434
- },
435
-
436
- async notifySizeChanged(params) {
437
- sendNotification(SIZE_CHANGED_METHOD, params);
438
- },
439
-
440
- getState() {
441
- return state;
442
- },
443
-
444
- getHostContext() {
445
- return state.hostContext;
446
- },
447
-
448
- getHostCapabilities() {
449
- return state.hostCapabilities;
450
- },
451
-
452
- isConnected() {
453
- return state.isConnected;
454
- },
455
-
456
- subscribe(listener) {
457
- listeners.add(listener);
458
- return () => {
459
- listeners.delete(listener);
460
- };
461
- },
462
-
463
- dispose() {
464
- if (disposed) return;
465
- disposed = true;
466
- if (targetWindow) {
467
- targetWindow.removeEventListener("message", handleMessage);
468
- }
469
- rejectPending("MCP host bridge has been disposed");
470
- listeners.clear();
471
- },
472
- };
473
- }
@@ -1,69 +0,0 @@
1
- /**
2
- * Normalize a path and generate a base name for tool identification.
3
- */
4
- function normalizeAndGetBaseName(path: string): {
5
- normalizedPath: string;
6
- baseName: string;
7
- } {
8
- // Normalize path (handle both / and \ separators)
9
- const normalizedPath = path.replace(/\\/g, "/");
10
-
11
- if (!normalizedPath) {
12
- throw new Error("Invalid tool path: path is empty");
13
- }
14
-
15
- // Remove file extension
16
- const withoutExtension = normalizedPath.replace(/\.[^/.]+$/, "");
17
-
18
- // Replace / with _
19
- const baseName = withoutExtension.replace(/\//g, "_");
20
-
21
- return { normalizedPath, baseName };
22
- }
23
-
24
- /**
25
- * Web-compatible pathToToolName using djb2 hash.
26
- * Used for Cloudflare Workers where node:crypto is not available.
27
- */
28
- export function pathToToolNameDjb2(path: string): string {
29
- const { normalizedPath, baseName } = normalizeAndGetBaseName(path);
30
-
31
- // djb2 hash algorithm - deterministic and works everywhere
32
- let hash = 5381;
33
- for (let i = 0; i < normalizedPath.length; i++) {
34
- hash = (Math.imul(hash, 33) + normalizedPath.charCodeAt(i)) >>> 0;
35
- }
36
- const hashStr = hash.toString(16).slice(0, 6).padStart(6, "0");
37
-
38
- return `${baseName}_${hashStr}`;
39
- }
40
-
41
- /**
42
- * Node.js pathToToolName using MD5 hash.
43
- * Used for backwards compatibility with existing Node.js deployments.
44
- *
45
- * Note: For Cloudflare builds, crypto is resolved to an empty module
46
- * via bundler fallback config. This is safe because pathToToolNameDjb2
47
- * is used instead in Cloudflare Workers.
48
- */
49
- export function pathToToolNameMd5(path: string): string {
50
- const { normalizedPath, baseName } = normalizeAndGetBaseName(path);
51
-
52
- // Use 'crypto' (not 'node:crypto') for bundler compatibility
53
- // eslint-disable-next-line @typescript-eslint/no-require-imports
54
- const crypto = require("crypto");
55
- const hash = crypto
56
- .createHash("md5")
57
- .update(normalizedPath)
58
- .digest("hex")
59
- .slice(0, 6);
60
-
61
- return `${baseName}_${hash}`;
62
- }
63
-
64
- /**
65
- * Default export for backwards compatibility.
66
- * In Cloudflare Workers, use pathToToolNameDjb2 directly.
67
- * In Node.js, this uses MD5 for backwards compatibility.
68
- */
69
- export const pathToToolName = pathToToolNameMd5;
@@ -1,151 +0,0 @@
1
- import type { PromptFile } from "./server";
2
-
3
- const EMPTY_PROMPT_FILE_MESSAGE = "File is empty.";
4
- const MISSING_DEFAULT_EXPORT_MESSAGE =
5
- "File does not export a default prompt handler.";
6
- const INVALID_DEFAULT_EXPORT_MESSAGE =
7
- "Default export must be a prompt handler function.";
8
-
9
- type PromptLoadIssue = {
10
- path: string;
11
- message: string;
12
- };
13
-
14
- function createPromptLoadIssue(path: string): PromptLoadIssue {
15
- return {
16
- path,
17
- message: EMPTY_PROMPT_FILE_MESSAGE,
18
- };
19
- }
20
-
21
- function createInvalidPromptImplementationError(path: string): Error {
22
- return new Error(
23
- `[xmcp] Invalid prompt file: ${path}\n -> ${INVALID_DEFAULT_EXPORT_MESSAGE}`
24
- );
25
- }
26
-
27
- function classifyPromptModule(
28
- promptModule: unknown,
29
- path: string
30
- ): "empty" | "missing-default" | "valid" {
31
- if (typeof promptModule !== "object" || promptModule === null) {
32
- throw createInvalidPromptImplementationError(path);
33
- }
34
-
35
- const moduleRecord = promptModule 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 createInvalidPromptImplementationError(path);
57
- }
58
-
59
- return "valid";
60
- }
61
-
62
- function toPromptFile(promptModule: unknown): PromptFile {
63
- return promptModule as PromptFile;
64
- }
65
-
66
- export async function loadPromptModules(
67
- loaders: Record<string, () => Promise<unknown>>
68
- ) {
69
- const promptModules = new Map<string, PromptFile>();
70
- const skippedPrompts: PromptLoadIssue[] = [];
71
-
72
- const results = await Promise.all(
73
- Object.entries(loaders).map(async ([path, loadPrompt]) => {
74
- const promptModule = await loadPrompt();
75
- const classification = classifyPromptModule(promptModule, path);
76
-
77
- if (classification === "empty") {
78
- return {
79
- skipped: true as const,
80
- issue: createPromptLoadIssue(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
- promptModule: toPromptFile(promptModule),
98
- };
99
- })
100
- );
101
-
102
- for (const result of results) {
103
- if (result.skipped) {
104
- skippedPrompts.push(result.issue);
105
- continue;
106
- }
107
-
108
- promptModules.set(result.path, result.promptModule);
109
- }
110
-
111
- return {
112
- promptModules,
113
- skippedPrompts,
114
- };
115
- }
116
-
117
- function createPromptLoadIssueReporter(
118
- logger: Pick<Console, "warn"> = console
119
- ) {
120
- let lastReportedSummaryKey = "";
121
-
122
- return (skippedPrompts: PromptLoadIssue[]) => {
123
- const summaryKey = skippedPrompts
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 (skippedPrompts.length === 0) {
135
- return;
136
- }
137
-
138
- skippedPrompts.forEach(({ path, message }) => {
139
- logger.warn(
140
- `[xmcp] Failed to load prompt file: ${path}\n -> ${message}`
141
- );
142
- });
143
-
144
- const count = skippedPrompts.length;
145
- logger.warn(
146
- `[xmcp] ${count} prompt${count === 1 ? "" : "s"} skipped due to empty files or missing default exports`
147
- );
148
- };
149
- }
150
-
151
- export const reportPromptLoadIssues = createPromptLoadIssueReporter();