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,196 +0,0 @@
1
- import {
2
- ReadResourceResult,
3
- ServerRequest,
4
- ServerNotification,
5
- } from "@modelcontextprotocol/sdk/types";
6
- import { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol";
7
- import { ZodRawShape } from "zod/v3";
8
- import {
9
- composeUriFromPath,
10
- ResourceInfo,
11
- } from "../utils/resource-uri-composer";
12
-
13
- /**
14
- * Type for the original resource handler that users write
15
- */
16
- export type UserResourceHandler = (
17
- args: ZodRawShape,
18
- extra?: RequestHandlerExtra<ServerRequest, ServerNotification>
19
- ) => ReadResourceResult | string | Promise<ReadResourceResult | string>;
20
-
21
- /**
22
- * Type for the transformed handler that the MCP server expects (direct resources)
23
- */
24
- export type McpResourceHandler = (
25
- uri: URL,
26
- extra: RequestHandlerExtra<ServerRequest, ServerNotification>
27
- ) => ReadResourceResult | Promise<ReadResourceResult>;
28
-
29
- /**
30
- * Transforms a user's resource handler into an MCP-compatible handler.
31
- *
32
- * This function:
33
- * 1. Extracts parameters from the URI based on the resource file path
34
- * 2. Passes the parameters to the user's handler
35
- * 3. Transforms string responses into the required ReadResourceResult format
36
- * 4. Ensures the URI is included in the response content
37
- *
38
- * @param handler - The user's resource handler function
39
- * @param filePath - The resource file path (used to extract URI template and parameters)
40
- * @returns A transformed handler compatible with McpServer.registerResource
41
- * @throws Error if the handler returns an invalid response type
42
- */
43
- export function transformResourceHandler(
44
- handler: UserResourceHandler,
45
- filePath: string,
46
- schema: ZodRawShape = {}
47
- ): McpResourceHandler {
48
- const resourceInfo = composeUriFromPath(filePath);
49
-
50
- if (!resourceInfo) {
51
- throw new Error(
52
- `Invalid resource file path: ${filePath}. Must follow (scheme)/path/[param] convention.`
53
- );
54
- }
55
-
56
- return async (
57
- uri: URL,
58
- extra: RequestHandlerExtra<ServerRequest, ServerNotification>
59
- ): Promise<ReadResourceResult> => {
60
- // extract and validate parameters from the actual URI using the template and schema
61
- const parameters = extractParametersFromUri(uri.href, resourceInfo, schema);
62
-
63
- let response = handler(parameters, extra);
64
-
65
- // only await if it's actually a promise
66
- if (response instanceof Promise) {
67
- response = await response;
68
- }
69
-
70
- // transform string response to ReadResourceResult
71
- if (typeof response === "string") {
72
- return {
73
- contents: [
74
- {
75
- uri: uri.href,
76
- text: response,
77
- },
78
- ],
79
- };
80
- }
81
-
82
- // validate response format
83
- if (
84
- !response ||
85
- typeof response !== "object" ||
86
- !Array.isArray(response.contents)
87
- ) {
88
- const responseType = response === null ? "null" : typeof response;
89
- const responseValue =
90
- response === undefined
91
- ? "undefined"
92
- : response === null
93
- ? "null"
94
- : typeof response === "object"
95
- ? JSON.stringify(response, null, 2)
96
- : String(response);
97
-
98
- throw new Error(
99
- `Resource handler must return a ReadResourceResult or string. ` +
100
- `Got ${responseType}: ${responseValue}\n\n` +
101
- `Expected ReadResourceResult format:\n` +
102
- `{\n` +
103
- ` contents: [\n` +
104
- ` { uri: "resource://uri", text: "content here" },\n` +
105
- ` { uri: "resource://uri", mimeType: "application/json", text: "json content" },\n` +
106
- ` { uri: "resource://uri", blob: base64data }\n` +
107
- ` ]\n` +
108
- `}`
109
- );
110
- }
111
-
112
- // ensure all content items have the URI set
113
- response.contents.forEach((content) => {
114
- if (!content.uri) {
115
- content.uri = uri.href;
116
- }
117
- });
118
-
119
- return response;
120
- };
121
- }
122
-
123
- /**
124
- * Extract and validate parameters from a concrete URI using the resource template info
125
- *
126
- * @param uri - The actual URI string being requested
127
- * @param resourceInfo - The resource template information
128
- * @param schema - The user's Zod schema for validation
129
- * @returns Object with validated parameter names and values
130
- * @throws Error if parameter validation fails
131
- */
132
- function extractParametersFromUri(
133
- uri: string,
134
- resourceInfo: ResourceInfo,
135
- schema: ZodRawShape
136
- ): Record<string, any> {
137
- const extractedValues: Record<string, string> = {};
138
- const validatedParameters: Record<string, any> = {};
139
-
140
- if (resourceInfo.parameters.length === 0) {
141
- // direct resource, no parameters to extract
142
- return validatedParameters;
143
- }
144
-
145
- // for template resources, extract parameter values from the URI
146
- // example:
147
- // Template: users://{userId}/profile
148
- // Actual URI: users://123/profile
149
- // Extract: { userId: "123" }
150
-
151
- const templatePath = resourceInfo.uriTemplate.split("://")[1] || "";
152
- const actualPath = uri.split("://")[1] || "";
153
-
154
- const templateParts = templatePath.split("/");
155
- const actualParts = actualPath.split("/");
156
-
157
- // match template parts with actual parts to extract parameter values
158
- for (let i = 0; i < templateParts.length && i < actualParts.length; i++) {
159
- const templatePart = templateParts[i];
160
- const actualPart = actualParts[i];
161
-
162
- // check if this template part is a parameter (e.g., {userId})
163
- const paramMatch = templatePart.match(/^\{(.+)\}$/);
164
- if (paramMatch) {
165
- const paramName = paramMatch[1];
166
- extractedValues[paramName] = actualPart; // extract actual value
167
- }
168
- }
169
-
170
- // validate extracted parameters against the user's schema
171
- for (const paramName of resourceInfo.parameters) {
172
- const paramValue = extractedValues[paramName];
173
- const paramSchema = schema[paramName];
174
-
175
- if (paramValue === undefined) {
176
- throw new Error(`Missing required parameter: ${paramName}`);
177
- }
178
-
179
- if (!paramSchema) {
180
- // no schema defined for this parameter, pass through as string to prevent breaking
181
- validatedParameters[paramName] = paramValue;
182
- continue;
183
- }
184
-
185
- try {
186
- validatedParameters[paramName] = paramSchema.parse(paramValue);
187
- } catch (error) {
188
- throw new Error(
189
- `Invalid parameter "${paramName}": ${paramValue}. ` +
190
- `Validation error: ${error instanceof Error ? error.message : String(error)}`
191
- );
192
- }
193
- }
194
-
195
- return validatedParameters;
196
- }
@@ -1,400 +0,0 @@
1
- import {
2
- CallToolResult,
3
- ServerRequest,
4
- ServerNotification,
5
- } from "@modelcontextprotocol/sdk/types";
6
- import { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol";
7
- import { ZodRawShape } from "zod/v3";
8
- import type { ToolExtraArguments } from "@/types/tool";
9
- import { getHttpRequestContext } from "@/runtime/contexts/http-request-context";
10
- import { getClientInfoContext } from "@/runtime/contexts/client-info-context";
11
- import { extractClientInfoFromHeaders } from "@/runtime/utils/client-info";
12
- import { elicitFromTool } from "../elicitation";
13
- import { validateContent } from "../validators";
14
-
15
- function validateAgainstOutputSchema(
16
- data: Record<string, unknown>,
17
- outputSchema: ZodRawShape,
18
- toolName: string,
19
- errorPrefix: string
20
- ): void {
21
- if (data === null || typeof data !== "object" || Array.isArray(data)) {
22
- throw new Error(
23
- `Tool "${toolName}" ${errorPrefix}: expected a plain object.`
24
- );
25
- }
26
-
27
- const outputKeys = new Set(Object.keys(outputSchema));
28
- const extraKeys = Object.keys(data).filter((key) => !outputKeys.has(key));
29
- if (extraKeys.length > 0) {
30
- throw new Error(
31
- `Tool "${toolName}" ${errorPrefix}: unrecognized key(s): ${extraKeys.join(", ")}`
32
- );
33
- }
34
-
35
- for (const [fieldName, fieldSchema] of Object.entries(outputSchema)) {
36
- try {
37
- fieldSchema.parse((data as any)[fieldName]);
38
- } catch (error: any) {
39
- throw new Error(
40
- `Tool "${toolName}" ${errorPrefix}: ${error?.message ?? `invalid field "${fieldName}"`}`
41
- );
42
- }
43
- }
44
- }
45
-
46
- /**
47
- * Type for the original tool handler that users write
48
- */
49
- export type UserToolResponse =
50
- | CallToolResult
51
- | string
52
- | number
53
- | Record<string, unknown>;
54
-
55
- export type UserToolHandler = (
56
- args: ZodRawShape,
57
- extra: ToolExtraArguments
58
- ) => UserToolResponse | Promise<UserToolResponse>;
59
-
60
- /**
61
- * Type for the transformed handler that the MCP server expects
62
- */
63
- export type McpToolHandler = (
64
- args: ZodRawShape,
65
- extra: RequestHandlerExtra<ServerRequest, ServerNotification>
66
- ) => CallToolResult | Promise<CallToolResult>;
67
-
68
- function hasUIMeta(meta?: Record<string, any>): boolean {
69
- return !!(
70
- meta &&
71
- typeof meta === "object" &&
72
- Object.keys(meta).some((key) => key.startsWith("ui/"))
73
- );
74
- }
75
-
76
- function createToolExtraArguments(
77
- extra: RequestHandlerExtra<ServerRequest, ServerNotification>
78
- ): ToolExtraArguments {
79
- let clientInfo = undefined;
80
-
81
- try {
82
- const httpRequestContext = getHttpRequestContext();
83
- clientInfo =
84
- httpRequestContext.clientInfo ??
85
- extractClientInfoFromHeaders(httpRequestContext.headers);
86
- } catch {
87
- // no HTTP request context available (for example, stdio transport)
88
- }
89
-
90
- if (!clientInfo) {
91
- try {
92
- clientInfo = getClientInfoContext().clientInfo;
93
- } catch {
94
- // no client info context available
95
- }
96
- }
97
-
98
- return {
99
- ...(extra as ToolExtraArguments),
100
- clientInfo,
101
- elicit: (request, options) =>
102
- elicitFromTool(extra as ToolExtraArguments, request, options),
103
- };
104
- }
105
-
106
- /**
107
- * Transforms a user's tool handler into an MCP-compatible handler.
108
- *
109
- * This function:
110
- * 1. Passes through both args and extra parameters to the user's handler
111
- * 2. Transforms string/number responses into the required CallToolResult format
112
- * 3. Allows returning `content`, `structuredContent`, or both
113
- * 4. Allows returning only `_meta` (without `content`) when it contains widget metadata
114
- * 5. Auto-wraps HTML strings with widget metadata if provided
115
- * 6. Validates that the response is a proper CallToolResult and throws a descriptive error if not
116
- *
117
- * @param handler - The user's tool handler function
118
- * @param meta - Optional metadata to attach to responses (for MCP app widgets)
119
- * @returns A transformed handler compatible with McpServer.registerTool
120
- * @throws Error if the handler returns an invalid response type
121
- */
122
- export function transformToolHandler(
123
- handler: UserToolHandler,
124
- meta?: Record<string, any>,
125
- outputSchema?: ZodRawShape,
126
- toolName = "unknown-tool"
127
- ): McpToolHandler {
128
- return async (
129
- args: ZodRawShape,
130
- extra: RequestHandlerExtra<ServerRequest, ServerNotification>
131
- ): Promise<CallToolResult> => {
132
- const toolExtra = createToolExtraArguments(extra);
133
- let response: any = handler(args, toolExtra);
134
-
135
- // only await if it's actually a promise
136
- if (response instanceof Promise) {
137
- response = await response;
138
- }
139
-
140
- if (typeof response === "string" || typeof response === "number") {
141
- if (outputSchema) {
142
- const outputSchemaEntries = Object.entries(outputSchema);
143
- if (outputSchemaEntries.length === 1) {
144
- const [fieldName, fieldSchema] = outputSchemaEntries[0];
145
- try {
146
- fieldSchema.parse(response);
147
- return {
148
- content: [
149
- {
150
- type: "text",
151
- text: typeof response === "number" ? `${response}` : response,
152
- },
153
- ],
154
- structuredContent: {
155
- [fieldName]: response,
156
- },
157
- };
158
- } catch {
159
- // Backward compatible fallback: keep content-only when primitive
160
- // output does not match outputSchema.
161
- }
162
- }
163
- }
164
-
165
- // Check if we have widget metadata to attach
166
- const hasWidgetMeta = hasUIMeta(meta);
167
-
168
- if (hasWidgetMeta) {
169
- // For widget tools, return empty text content with metadata
170
- // The actual HTML is served by the auto-generated resource
171
- return {
172
- content: [
173
- {
174
- type: "text",
175
- text: "",
176
- },
177
- ],
178
- structuredContent: {
179
- args,
180
- },
181
- _meta: meta,
182
- };
183
- }
184
-
185
- // Regular string/number response
186
- return {
187
- content: [
188
- {
189
- type: "text",
190
- text: typeof response === "number" ? `${response}` : response,
191
- },
192
- ],
193
- };
194
- }
195
-
196
- // With outputSchema declared, allow returning a plain object as shorthand
197
- // for `{ structuredContent: ... }`.
198
- if (
199
- outputSchema &&
200
- response &&
201
- typeof response === "object" &&
202
- !Array.isArray(response) &&
203
- !("structuredContent" in response) &&
204
- !("content" in response && Array.isArray((response as any).content)) &&
205
- !("_meta" in response) &&
206
- !("isError" in response)
207
- ) {
208
- // Validate the response against outputSchema before wrapping.
209
- validateAgainstOutputSchema(
210
- response as Record<string, unknown>,
211
- outputSchema,
212
- toolName,
213
- "returned data that does not match outputSchema"
214
- );
215
- response = {
216
- structuredContent: response,
217
- };
218
- }
219
-
220
- // Check if response has _meta but no content (special case for widget metadata)
221
- if (
222
- response &&
223
- typeof response === "object" &&
224
- "_meta" in response &&
225
- !("content" in response) &&
226
- !("structuredContent" in response)
227
- ) {
228
- const meta = (response as any)._meta;
229
-
230
- if (hasUIMeta(meta)) {
231
- // Transform to include empty text content with the _meta
232
- return {
233
- content: [
234
- {
235
- type: "text",
236
- text: "",
237
- },
238
- ],
239
- _meta: meta,
240
- };
241
- }
242
- }
243
-
244
- // validate response is an object
245
- if (!response || typeof response !== "object") {
246
- const responseType = response === null ? "null" : typeof response;
247
- const responseValue =
248
- response === undefined
249
- ? "undefined"
250
- : response === null
251
- ? "null"
252
- : typeof response === "object"
253
- ? JSON.stringify(response, null, 2)
254
- : String(response);
255
-
256
- throw new Error(
257
- `Tool handler must return a CallToolResult, string, or number. ` +
258
- `Got ${responseType}: ${responseValue}\n\n` +
259
- `Expected CallToolResult format:\n` +
260
- `{\n` +
261
- ` content: [\n` +
262
- ` { type: "text", text: "your text here" },\n` +
263
- ` { type: "image", data: "base64data", mimeType: "image/jpeg" },\n` +
264
- ` { type: "audio", data: "base64data", mimeType: "audio/mpeg" },\n` +
265
- ` { type: "resource_link", name: "resource name", uri: "resource://uri" }\n` +
266
- ` // All content types support an optional "_meta" object property\n` +
267
- ` ]\n` +
268
- `}\n\n` +
269
- `Or with structured content:\n` +
270
- `{\n` +
271
- ` structuredContent: { your: "data" }\n` +
272
- `}\n\n` +
273
- `Or both for backwards compatibility:\n` +
274
- `{\n` +
275
- ` content: [{ type: "text", text: "fallback" }],\n` +
276
- ` structuredContent: { your: "data" }\n` +
277
- `}\n\n` +
278
- `Or for widget metadata only:\n` +
279
- `{\n` +
280
- ` _meta: {\n` +
281
- ` "ui/...": ...\n` +
282
- ` }\n` +
283
- `}`
284
- );
285
- }
286
-
287
- // Check if response has at least one of: content or structuredContent
288
- let hasContent = "content" in response && Array.isArray(response.content);
289
- const hasStructuredContent = "structuredContent" in response;
290
- const isError = "isError" in response && (response as any).isError === true;
291
-
292
- if (!hasContent && !hasStructuredContent && !isError) {
293
- const responseValue = JSON.stringify(response, null, 2);
294
-
295
- throw new Error(
296
- `Tool handler must return at least 'content' or 'structuredContent'. ` +
297
- `Got: ${responseValue}\n\n` +
298
- `Expected CallToolResult format:\n` +
299
- `{\n` +
300
- ` content: [\n` +
301
- ` { type: "text", text: "your text here" },\n` +
302
- ` { type: "image", data: "base64data", mimeType: "image/jpeg" },\n` +
303
- ` { type: "audio", data: "base64data", mimeType: "audio/mpeg" },\n` +
304
- ` { type: "resource_link", name: "resource name", uri: "resource://uri" }\n` +
305
- ` ]\n` +
306
- `}\n\n` +
307
- `Or with structured content:\n` +
308
- `{\n` +
309
- ` structuredContent: { your: "data" }\n` +
310
- `}\n\n` +
311
- `Or both for backwards compatibility:\n` +
312
- `{\n` +
313
- ` content: [{ type: "text", text: "fallback" }],\n` +
314
- ` structuredContent: { your: "data" }\n` +
315
- `}`
316
- );
317
- }
318
-
319
- // Auto-generate fallback content for isError responses without content
320
- if (isError && !hasContent && !hasStructuredContent) {
321
- const { isError: _, ...rest } = response as Record<string, unknown>;
322
- const errorText =
323
- Object.keys(rest).length > 0
324
- ? `Tool execution failed: ${JSON.stringify(rest)}`
325
- : "Tool execution failed";
326
- response.content = [{ type: "text", text: errorText }];
327
- hasContent = true;
328
- }
329
-
330
- // Validate structuredContent against outputSchema if present.
331
- if (outputSchema && hasStructuredContent && !isError) {
332
- validateAgainstOutputSchema(
333
- (response as any).structuredContent as Record<string, unknown>,
334
- outputSchema,
335
- toolName,
336
- "returned structuredContent that does not match outputSchema"
337
- );
338
- }
339
-
340
- // Auto-generate text fallback for clients that only render content.
341
- if (!hasContent && hasStructuredContent) {
342
- response.content = [
343
- {
344
- type: "text",
345
- text: JSON.stringify((response as any).structuredContent),
346
- },
347
- ];
348
- hasContent = true;
349
- }
350
-
351
- // validate each content item if content is present
352
- if (hasContent) {
353
- for (let i = 0; i < response.content.length; i++) {
354
- const contentItem = response.content[i];
355
- const validationResult = validateContent(contentItem);
356
- if (!validationResult.valid) {
357
- throw new Error(
358
- `Invalid content item at index ${i}: ${validationResult.error}\n\n` +
359
- `Content item: ${JSON.stringify(contentItem, null, 2)}\n\n` +
360
- `Expected content formats:\n` +
361
- `- Text: { type: "text", text: "your text here" }\n` +
362
- `- Image: { type: "image", data: "base64data", mimeType: "image/jpeg" }\n` +
363
- `- Audio: { type: "audio", data: "base64data", mimeType: "audio/mpeg" }\n` +
364
- `- Resource: { type: "resource_link", name: "name", uri: "uri" }\n` +
365
- `All content types support an optional "_meta" object property`
366
- );
367
- }
368
- }
369
- }
370
-
371
- // validate structuredContent if present
372
- if (hasStructuredContent) {
373
- const structuredContent = (response as any).structuredContent;
374
-
375
- if (
376
- structuredContent === null ||
377
- typeof structuredContent !== "object" ||
378
- Array.isArray(structuredContent)
379
- ) {
380
- const structuredType = Array.isArray(structuredContent)
381
- ? "array"
382
- : typeof structuredContent;
383
-
384
- throw new Error(
385
- `'structuredContent' must be a plain object (not an array or primitive). ` +
386
- `Got ${structuredType}: ${JSON.stringify(structuredContent, null, 2)}\n\n` +
387
- `Expected format:\n` +
388
- `{\n` +
389
- ` structuredContent: {\n` +
390
- ` key: "value",\n` +
391
- ` nested: { data: "here" }\n` +
392
- ` }\n` +
393
- `}`
394
- );
395
- }
396
- }
397
-
398
- return response as CallToolResult;
399
- };
400
- }