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,107 +0,0 @@
1
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp";
2
- import { Implementation } from "@modelcontextprotocol/sdk/types";
3
- import { addToolsToServer } from "./tools";
4
- import { addPromptsToServer, PromptArgsRawShape } from "./prompts";
5
- import { ToolMetadata } from "@/types/tool";
6
- import { PromptMetadata } from "@/types/prompt";
7
- import { UserToolHandler } from "./transformers/tool";
8
- import { UserPromptHandler } from "./transformers/prompt";
9
- import { UserResourceHandler } from "./transformers/resource";
10
- import { ZodRawShape } from "zod/v3";
11
- import { addResourcesToServer } from "./resources";
12
- import { ResourceMetadata } from "@/types/resource";
13
- import { uIResourceRegistry } from "./ext-apps-registry";
14
- import { loadPromptModules, reportPromptLoadIssues } from "./prompt-loader";
15
- import {
16
- loadResourceModules,
17
- reportResourceLoadIssues,
18
- } from "./resource-loader";
19
- import { loadToolModules, reportToolLoadIssues } from "./tool-loader";
20
-
21
- export type ToolFile = {
22
- metadata: ToolMetadata;
23
- schema: ZodRawShape;
24
- outputSchema?: ZodRawShape;
25
- default: UserToolHandler;
26
- };
27
-
28
- export type PromptFile = {
29
- metadata: PromptMetadata;
30
- schema: PromptArgsRawShape;
31
- default: UserPromptHandler;
32
- };
33
-
34
- export type ResourceFile = {
35
- metadata: ResourceMetadata;
36
- schema: ZodRawShape;
37
- default: UserResourceHandler;
38
- };
39
-
40
- export const injectedTools = INJECTED_TOOLS as Record<
41
- string,
42
- () => Promise<ToolFile>
43
- >;
44
-
45
- export const injectedPrompts = INJECTED_PROMPTS as Record<
46
- string,
47
- () => Promise<PromptFile>
48
- >;
49
-
50
- export const injectedResources = INJECTED_RESOURCES as Record<
51
- string,
52
- () => Promise<ResourceFile>
53
- >;
54
-
55
- export const INJECTED_CONFIG = SERVER_INFO as Implementation & { instructions?: string };
56
-
57
- /* Loads all modules and injects them into the server */
58
- // would be better as a class and use dependency injection perhaps
59
- export async function configureServer(
60
- server: McpServer,
61
- toolModules: Map<string, ToolFile>,
62
- promptModules: Map<string, PromptFile>,
63
- resourceModules: Map<string, ResourceFile>
64
- ): Promise<McpServer> {
65
- uIResourceRegistry.clear();
66
-
67
- addToolsToServer(server, toolModules);
68
- addPromptsToServer(server, promptModules);
69
- addResourcesToServer(server, resourceModules);
70
- return server;
71
- }
72
-
73
- export async function loadTools() {
74
- const { toolModules, skippedTools } = await loadToolModules(injectedTools);
75
- reportToolLoadIssues(skippedTools);
76
- return toolModules;
77
- }
78
-
79
- export async function loadPrompts() {
80
- const { promptModules, skippedPrompts } = await loadPromptModules(
81
- injectedPrompts
82
- );
83
- reportPromptLoadIssues(skippedPrompts);
84
- return promptModules;
85
- }
86
-
87
- export async function loadResources() {
88
- const { resourceModules, skippedResources } = await loadResourceModules(
89
- injectedResources
90
- );
91
- reportResourceLoadIssues(skippedResources);
92
- return resourceModules;
93
- }
94
-
95
- export async function createServer() {
96
- const { instructions, ...serverInfo } = INJECTED_CONFIG;
97
- const server = new McpServer(serverInfo, { instructions });
98
- const toolModulesPromise = loadTools();
99
- const promptModulesPromise = loadPrompts();
100
- const resourceModulesPromise = loadResources();
101
- const [toolModules, promptModules, resourceModules] = await Promise.all([
102
- toolModulesPromise,
103
- promptModulesPromise,
104
- resourceModulesPromise,
105
- ]);
106
- return configureServer(server, toolModules, promptModules, resourceModules);
107
- }
@@ -1,149 +0,0 @@
1
- import type { ToolFile } from "./server";
2
-
3
- const EMPTY_TOOL_FILE_MESSAGE = "File is empty.";
4
- const MISSING_DEFAULT_EXPORT_MESSAGE =
5
- "File does not export a default tool handler.";
6
- const INVALID_DEFAULT_EXPORT_MESSAGE =
7
- "Default export must be a tool handler function.";
8
-
9
- type ToolLoadIssue = {
10
- path: string;
11
- message: string;
12
- };
13
-
14
- function createToolLoadIssue(path: string): ToolLoadIssue {
15
- return {
16
- path,
17
- message: EMPTY_TOOL_FILE_MESSAGE,
18
- };
19
- }
20
-
21
- function createInvalidToolImplementationError(path: string): Error {
22
- return new Error(
23
- `[xmcp] Invalid tool file: ${path}\n -> ${INVALID_DEFAULT_EXPORT_MESSAGE}`
24
- );
25
- }
26
-
27
- function classifyToolModule(
28
- toolModule: unknown,
29
- path: string
30
- ): "empty" | "missing-default" | "valid" {
31
- if (typeof toolModule !== "object" || toolModule === null) {
32
- throw createInvalidToolImplementationError(path);
33
- }
34
-
35
- const moduleRecord = toolModule 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 createInvalidToolImplementationError(path);
57
- }
58
-
59
- return "valid";
60
- }
61
-
62
- function toToolFile(toolModule: unknown): ToolFile {
63
- return toolModule as ToolFile;
64
- }
65
-
66
- export async function loadToolModules(
67
- loaders: Record<string, () => Promise<unknown>>
68
- ) {
69
- const toolModules = new Map<string, ToolFile>();
70
- const skippedTools: ToolLoadIssue[] = [];
71
-
72
- const results = await Promise.all(
73
- Object.entries(loaders).map(async ([path, loadTool]) => {
74
- const toolModule = await loadTool();
75
- const classification = classifyToolModule(toolModule, path);
76
-
77
- if (classification === "empty") {
78
- return {
79
- skipped: true as const,
80
- issue: createToolLoadIssue(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
- toolModule: toToolFile(toolModule),
98
- };
99
- })
100
- );
101
-
102
- for (const result of results) {
103
- if (result.skipped) {
104
- skippedTools.push(result.issue);
105
- continue;
106
- }
107
-
108
- toolModules.set(result.path, result.toolModule);
109
- }
110
-
111
- return {
112
- toolModules,
113
- skippedTools,
114
- };
115
- }
116
-
117
- function createToolLoadIssueReporter(
118
- logger: Pick<Console, "warn"> = console
119
- ) {
120
- let lastReportedSummaryKey = "";
121
-
122
- return (skippedTools: ToolLoadIssue[]) => {
123
- const summaryKey = skippedTools
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 (skippedTools.length === 0) {
135
- return;
136
- }
137
-
138
- skippedTools.forEach(({ path, message }) => {
139
- logger.warn(`[xmcp] Failed to load tool file: ${path}\n -> ${message}`);
140
- });
141
-
142
- const count = skippedTools.length;
143
- logger.warn(
144
- `[xmcp] ${count} tool${count === 1 ? "" : "s"} skipped due to empty files or missing default exports`
145
- );
146
- };
147
- }
148
-
149
- export const reportToolLoadIssues = createToolLoadIssueReporter();
@@ -1,183 +0,0 @@
1
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp";
2
- import { z } from "zod";
3
- import { ZodRawShape } from "zod/v3";
4
- import { ToolFile } from "./server";
5
- import { ToolMetadata } from "@/types/tool";
6
- import { transformToolHandler } from "./transformers/tool";
7
- import { isReactFile } from "./react";
8
- import { uIResourceRegistry } from "./ext-apps-registry";
9
- import { flattenMeta, hasUIMeta } from "./ui/flatten-meta";
10
- import { splitUIMetaNested } from "./ui/split-meta";
11
- import { isPaidHandler, getX402Registry } from "@/plugins/x402";
12
-
13
- /** Validates if a value is a valid Zod schema object */
14
- export function isZodRawShape(value: unknown): value is ZodRawShape {
15
- if (typeof value !== "object" || value === null) {
16
- return false;
17
- }
18
-
19
- const obj = value as Record<string, unknown>;
20
- return Object.entries(obj).every(([key, val]) => {
21
- if (typeof key !== "string") return false;
22
- if (typeof val !== "object" || val === null) return false;
23
- if (!("parse" in val) || typeof val.parse !== "function") return false;
24
- return true;
25
- });
26
- }
27
-
28
- export function pathToName(path: string): string {
29
- const fileName = path.split("/").pop() || path;
30
- return fileName.replace(/\.[^/.]+$/, "");
31
- }
32
-
33
- /** Ensures toolConfig has its own annotations object with a title */
34
- export function ensureAnnotations(toolConfig: Pick<ToolMetadata, "name" | "annotations">): void {
35
- toolConfig.annotations = { ...(toolConfig.annotations ?? {}) };
36
- if (toolConfig.annotations.title === undefined) {
37
- toolConfig.annotations.title = toolConfig.name;
38
- }
39
- }
40
-
41
- /** Loads tools and injects them into the server */
42
- export function addToolsToServer(
43
- server: McpServer,
44
- toolModules: Map<string, ToolFile>
45
- ): McpServer {
46
- toolModules.forEach((toolModule, path) => {
47
- const defaultName = pathToName(path);
48
-
49
- const toolConfig: ToolMetadata = {
50
- name: defaultName,
51
- description: "No description provided",
52
- };
53
-
54
- const { default: handler, metadata, schema, outputSchema } = toolModule;
55
-
56
- if (typeof metadata === "object" && metadata !== null) {
57
- Object.assign(toolConfig, metadata);
58
- }
59
-
60
- // Register paid tools in x402 registry if plugin is installed
61
- if (isPaidHandler(handler)) {
62
- const registry = getX402Registry();
63
- if (registry) {
64
- registry.set(toolConfig.name, handler.__x402);
65
- }
66
- }
67
-
68
- // Determine the actual schema to use
69
- let toolSchema: ZodRawShape = {};
70
- if (isZodRawShape(schema)) {
71
- toolSchema = schema;
72
- } else if (schema !== undefined && schema !== null) {
73
- console.warn(
74
- `Invalid schema for tool "${toolConfig.name}" at ${path}. Expected Record<string, z.ZodType>`
75
- );
76
- }
77
-
78
- let toolOutputSchema: ZodRawShape | undefined;
79
- if (outputSchema !== undefined && outputSchema !== null) {
80
- if (isZodRawShape(outputSchema)) {
81
- toolOutputSchema = outputSchema;
82
- } else {
83
- throw new Error(
84
- `Invalid outputSchema for tool "${toolConfig.name}" at ${path}. Expected Record<string, z.ZodType>`
85
- );
86
- }
87
- }
88
-
89
- // Make sure tools has annotations with a title
90
- ensureAnnotations(toolConfig);
91
-
92
- if (toolConfig._meta === undefined) {
93
- toolConfig._meta = {};
94
- }
95
-
96
- const isReact = isReactFile(path);
97
-
98
- const uiWidget = hasUIMeta(toolConfig._meta) || isReact;
99
-
100
- let toolSpecificMeta = toolConfig._meta;
101
-
102
- if (uiWidget) {
103
- const mcpuiResourceUri = `ui://app/${toolConfig.name}.html`;
104
-
105
- if (!toolConfig._meta.ui) {
106
- toolConfig._meta.ui = {};
107
- }
108
- if (!toolConfig._meta.ui.resourceUri) {
109
- toolConfig._meta.ui.resourceUri = mcpuiResourceUri;
110
- }
111
-
112
- const uiSplit = splitUIMetaNested(toolSpecificMeta);
113
- toolSpecificMeta = uiSplit.toolMeta;
114
- const resourceSpecificMeta = uiSplit.resourceMeta;
115
-
116
- // Ensure CSP resource domains includes esm.sh
117
- resourceSpecificMeta.ui = resourceSpecificMeta.ui || {};
118
- resourceSpecificMeta.ui.csp = resourceSpecificMeta.ui.csp || {};
119
- resourceSpecificMeta.ui.csp.resourceDomains =
120
- resourceSpecificMeta.ui.csp.resourceDomains || [];
121
-
122
- if (
123
- !resourceSpecificMeta.ui.csp.resourceDomains.includes(
124
- "https://esm.sh"
125
- )
126
- ) {
127
- resourceSpecificMeta.ui.csp.resourceDomains.push("https://esm.sh");
128
- }
129
-
130
- uIResourceRegistry.add(toolConfig.name, {
131
- name: toolConfig.name,
132
- uri: mcpuiResourceUri,
133
- handler,
134
- mimeType: "text/html;profile=mcp-app",
135
- _meta: resourceSpecificMeta,
136
- toolPath: isReact ? path : undefined,
137
- });
138
- }
139
-
140
- const flattenedToolMeta = flattenMeta(toolSpecificMeta);
141
- const meta = uiWidget ? flattenedToolMeta : undefined;
142
- let transformedHandler;
143
-
144
- if (isReactFile(path) && uiWidget) {
145
- transformedHandler = async (args: any, extra: any) => ({
146
- content: [{ type: "text", text: "" }],
147
- _meta: meta,
148
- structuredContent: {
149
- args,
150
- },
151
- });
152
- } else {
153
- transformedHandler = transformToolHandler(
154
- handler,
155
- meta,
156
- toolOutputSchema,
157
- toolConfig.name
158
- );
159
- }
160
-
161
- const toolConfigFormatted = {
162
- title: toolConfig.annotations?.title,
163
- description: toolConfig.description,
164
- // Build the object schema using the project's Zod instance to avoid
165
- // cross-instance v3 shape issues in tools/list JSON schema generation.
166
- inputSchema: z.object(toolSchema),
167
- outputSchema: toolOutputSchema
168
- ? z.object(toolOutputSchema).strict()
169
- : undefined,
170
- annotations: toolConfig.annotations,
171
- _meta: flattenedToolMeta, // Use flattened metadata for MCP protocol
172
- };
173
-
174
- // server as any prevents infinite type recursion
175
- (server as any).registerTool(
176
- toolConfig.name,
177
- toolConfigFormatted,
178
- transformedHandler
179
- );
180
- });
181
-
182
- return server;
183
- }
@@ -1,120 +0,0 @@
1
- import {
2
- GetPromptResult,
3
- ServerRequest,
4
- ServerNotification,
5
- } from "@modelcontextprotocol/sdk/types";
6
- import { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol";
7
- import { PromptArgsRawShape } from "../prompts";
8
- import { contentValidators, validateContent } from "../validators";
9
-
10
- /**
11
- * Type for content that users can return from prompt handlers
12
- */
13
- export type PromptContent = GetPromptResult["messages"][number]["content"];
14
- // could be exporting this for typing the prompt handler and make sure return type is type safe
15
-
16
- /**
17
- * Type for the original prompt handler that users write
18
- * The extra parameter is optional for backward compatibility
19
- * Users can only return content objects, strings, or numbers - not full message arrays
20
- */
21
- export type UserPromptHandler = (
22
- args: PromptArgsRawShape,
23
- extra?: RequestHandlerExtra<ServerRequest, ServerNotification>
24
- ) => PromptContent | string | number | Promise<PromptContent | string | number>;
25
-
26
- /**
27
- * Type for the transformed handler that the MCP server expects
28
- */
29
- export type McpPromptHandler = (
30
- args: PromptArgsRawShape,
31
- extra: RequestHandlerExtra<ServerRequest, ServerNotification>
32
- ) => GetPromptResult | Promise<GetPromptResult>;
33
-
34
- /**
35
- * Transforms a user's prompt handler into an MCP-compatible handler.
36
- *
37
- * This function:
38
- * 1. Passes through both args and extra parameters to the user's handler
39
- * 2. Transforms string/number/content responses into a single message GetPromptResult format
40
- * 3. Always creates exactly one message with the specified role
41
- * 4. Validates that the response is valid and throws a descriptive error if not
42
- *
43
- * @param handler - The user's prompt handler function
44
- * @param role - The role to assign to the message ("user" or "assistant")
45
- * @returns A transformed handler compatible with McpServer.registerPrompt
46
- * @throws Error if the handler returns an invalid response type
47
- */
48
- export function transformPromptHandler(
49
- handler: UserPromptHandler,
50
- role: "user" | "assistant" = "assistant"
51
- ): McpPromptHandler {
52
- return async (
53
- args: PromptArgsRawShape,
54
- extra: RequestHandlerExtra<ServerRequest, ServerNotification>
55
- ): Promise<GetPromptResult> => {
56
- let response = handler(args, extra);
57
-
58
- // only await if it's actually a promise
59
- if (response instanceof Promise) {
60
- response = await response;
61
- }
62
-
63
- let content: GetPromptResult["messages"][number]["content"];
64
-
65
- // transform string/number responses to text content
66
- if (typeof response === "string" || typeof response === "number") {
67
- content = {
68
- type: "text",
69
- text: typeof response === "number" ? `${response}` : response,
70
- };
71
- } else {
72
- // validate content object responses
73
- const validationResult = validateContent(response);
74
- if (validationResult.valid) {
75
- content = response as PromptContent;
76
- } else {
77
- const responseType = response === null ? "null" : typeof response;
78
- const responseValue =
79
- response === undefined
80
- ? "undefined"
81
- : response === null
82
- ? "null"
83
- : typeof response === "object"
84
- ? JSON.stringify(response, null, 2)
85
- : String(response);
86
-
87
- throw new Error(
88
- `Prompt handler must return a PromptContent object, string, or number. ` +
89
- `Got ${responseType}: ${responseValue}\n\n` +
90
- `Validation error: ${validationResult.error}\n\n` +
91
- `Expected formats:\n` +
92
- `- String: "your text here"\n` +
93
- `- Number: 42\n` +
94
- `- Text content: { type: "text", text: "your text here" }\n` +
95
- `- Image content: { type: "image", data: "base64data", mimeType: "image/jpeg" }\n` +
96
- `- Audio content: { type: "audio", data: "base64data", mimeType: "audio/mpeg" }\n` +
97
- `- Resource link: { type: "resource_link", name: "resource name", uri: "resource://uri" }\n` +
98
- `- All content types support an optional "_meta" object property`
99
- );
100
- }
101
- }
102
-
103
- // validate the role
104
- if (role !== "user" && role !== "assistant") {
105
- throw new Error(`Invalid role: ${role}`);
106
- }
107
-
108
- // final result with single message
109
- const result = {
110
- messages: [
111
- {
112
- role,
113
- content,
114
- },
115
- ],
116
- };
117
-
118
- return result;
119
- };
120
- }