xmcp 0.6.5 → 0.6.7

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 (78) hide show
  1. package/README.md +32 -0
  2. package/dist/cli.js +58 -40
  3. package/dist/compiler/config/index.d.ts +106 -47
  4. package/dist/compiler/config/schemas/template.d.ts +40 -0
  5. package/dist/compiler/config/schemas/transport/http.d.ts +82 -82
  6. package/dist/compiler/config/schemas/transport/stdio.d.ts +5 -0
  7. package/dist/index.d.ts +4 -2
  8. package/dist/index.js +5 -5
  9. package/dist/runtime/adapter-express.js +40 -23
  10. package/dist/runtime/adapter-nestjs.js +40 -23
  11. package/dist/runtime/adapter-nextjs.js +39 -22
  12. package/dist/runtime/contexts/http-request-context.d.ts +3 -1
  13. package/dist/runtime/headers.js +1 -1
  14. package/dist/runtime/http.js +48 -31
  15. package/dist/runtime/stdio.js +19 -13
  16. package/dist/runtime/utils/elicitation.d.ts +4 -0
  17. package/dist/runtime/utils/ext-apps-registry.d.ts +132 -0
  18. package/dist/runtime/utils/path-to-tool-name.d.ts +20 -0
  19. package/dist/runtime/utils/prompt-loader.d.ts +11 -0
  20. package/dist/runtime/utils/prompts.d.ts +8 -0
  21. package/dist/runtime/utils/react/generate-html.d.ts +1 -0
  22. package/dist/runtime/utils/react/index.d.ts +4 -0
  23. package/dist/runtime/utils/resource-loader.d.ts +11 -0
  24. package/dist/runtime/utils/resources.d.ts +4 -0
  25. package/dist/runtime/utils/server.d.ts +35 -0
  26. package/dist/runtime/utils/tool-loader.d.ts +11 -0
  27. package/dist/runtime/utils/tools.d.ts +11 -0
  28. package/dist/runtime/utils/transformers/prompt.d.ts +32 -0
  29. package/dist/runtime/utils/transformers/resource.d.ts +26 -0
  30. package/dist/runtime/utils/transformers/tool.d.ts +30 -0
  31. package/dist/runtime/utils/ui/flatten-meta.d.ts +6 -0
  32. package/dist/runtime/utils/ui/split-meta.d.ts +17 -0
  33. package/dist/runtime/utils/utils/resource-uri-composer.d.ts +60 -0
  34. package/dist/runtime/utils/validators/index.d.ts +13 -0
  35. package/dist/types/client-info.d.ts +12 -0
  36. package/dist/types/tool.d.ts +70 -14
  37. package/dist/utils/context.d.ts +1 -1
  38. package/package.json +9 -1
  39. package/src/client/index.ts +4 -1
  40. package/src/compiler/config/__tests__/config.test.ts +36 -0
  41. package/src/compiler/config/injection.ts +63 -1
  42. package/src/compiler/config/schemas/template.ts +17 -0
  43. package/src/compiler/config/schemas/transport/stdio.ts +1 -0
  44. package/src/compiler/generate-tools-code.ts +24 -6
  45. package/src/compiler/get-bundler-config/get-injected-variables.ts +3 -0
  46. package/src/compiler/get-bundler-config/plugins/index.ts +0 -1
  47. package/src/compiler/index.ts +123 -30
  48. package/src/compiler/start-http-server.ts +11 -4
  49. package/src/compiler/watcher-recovery.ts +72 -0
  50. package/src/index.ts +9 -1
  51. package/src/runtime/adapters/express/index.ts +45 -47
  52. package/src/runtime/adapters/nestjs/xmcp.service.ts +4 -3
  53. package/src/runtime/adapters/nextjs/handler/node-to-web-adapter.ts +40 -6
  54. package/src/runtime/adapters/nextjs/handler/request-converter.ts +20 -0
  55. package/src/runtime/adapters/nextjs/handler/server-lifecycle.ts +8 -5
  56. package/src/runtime/adapters/nextjs/index.ts +41 -25
  57. package/src/runtime/contexts/http-request-context.ts +2 -0
  58. package/src/runtime/headers.ts +37 -2
  59. package/src/runtime/platforms/cloudflare/cors.ts +0 -1
  60. package/src/runtime/platforms/cloudflare/worker.ts +46 -44
  61. package/src/runtime/transports/http/index.ts +0 -4
  62. package/src/runtime/transports/http/stateless-streamable-http.ts +131 -233
  63. package/src/runtime/transports/stdio/index.ts +18 -1
  64. package/src/runtime/utils/__tests__/client-info.test.ts +80 -0
  65. package/src/runtime/utils/__tests__/tool-extra.test.ts +110 -0
  66. package/src/runtime/utils/client-info.ts +71 -0
  67. package/src/runtime/utils/elicitation.ts +396 -0
  68. package/src/runtime/utils/prompt-loader.ts +151 -0
  69. package/src/runtime/utils/resource-loader.ts +151 -0
  70. package/src/runtime/utils/resources.ts +0 -8
  71. package/src/runtime/utils/server.ts +30 -42
  72. package/src/runtime/utils/tool-loader.ts +149 -0
  73. package/src/runtime/utils/tools.ts +31 -9
  74. package/src/runtime/utils/transformers/tool.ts +149 -10
  75. package/src/types/client-info.ts +12 -0
  76. package/src/types/injected.d.ts +62 -0
  77. package/src/types/tool.ts +100 -17
  78. package/src/utils/context.ts +2 -2
@@ -5,19 +5,55 @@ import {
5
5
  } from "@modelcontextprotocol/sdk/types";
6
6
  import { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol";
7
7
  import { ZodRawShape } from "zod/v3";
8
+ import type { ToolExtraArguments } from "@/types/tool";
9
+ import { getHttpRequestContext } from "@/runtime/contexts/http-request-context";
10
+ import { elicitFromTool } from "../elicitation";
8
11
  import { validateContent } from "../validators";
9
12
 
13
+ function validateAgainstOutputSchema(
14
+ data: Record<string, unknown>,
15
+ outputSchema: ZodRawShape,
16
+ toolName: string,
17
+ errorPrefix: string
18
+ ): void {
19
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
20
+ throw new Error(
21
+ `Tool "${toolName}" ${errorPrefix}: expected a plain object.`
22
+ );
23
+ }
24
+
25
+ const outputKeys = new Set(Object.keys(outputSchema));
26
+ const extraKeys = Object.keys(data).filter((key) => !outputKeys.has(key));
27
+ if (extraKeys.length > 0) {
28
+ throw new Error(
29
+ `Tool "${toolName}" ${errorPrefix}: unrecognized key(s): ${extraKeys.join(", ")}`
30
+ );
31
+ }
32
+
33
+ for (const [fieldName, fieldSchema] of Object.entries(outputSchema)) {
34
+ try {
35
+ fieldSchema.parse((data as any)[fieldName]);
36
+ } catch (error: any) {
37
+ throw new Error(
38
+ `Tool "${toolName}" ${errorPrefix}: ${error?.message ?? `invalid field "${fieldName}"`}`
39
+ );
40
+ }
41
+ }
42
+ }
43
+
10
44
  /**
11
45
  * Type for the original tool handler that users write
12
46
  */
13
- export type UserToolHandler = (
14
- args: ZodRawShape,
15
- extra: RequestHandlerExtra<ServerRequest, ServerNotification>
16
- ) =>
47
+ export type UserToolResponse =
17
48
  | CallToolResult
18
49
  | string
19
50
  | number
20
- | Promise<CallToolResult | string | number>;
51
+ | Record<string, unknown>;
52
+
53
+ export type UserToolHandler = (
54
+ args: ZodRawShape,
55
+ extra: ToolExtraArguments
56
+ ) => UserToolResponse | Promise<UserToolResponse>;
21
57
 
22
58
  /**
23
59
  * Type for the transformed handler that the MCP server expects
@@ -35,6 +71,25 @@ function hasUIMeta(meta?: Record<string, any>): boolean {
35
71
  );
36
72
  }
37
73
 
74
+ function createToolExtraArguments(
75
+ extra: RequestHandlerExtra<ServerRequest, ServerNotification>
76
+ ): ToolExtraArguments {
77
+ let clientInfo = undefined;
78
+
79
+ try {
80
+ clientInfo = getHttpRequestContext().clientInfo;
81
+ } catch {
82
+ // no request context available (for example, stdio transport)
83
+ }
84
+
85
+ return {
86
+ ...(extra as ToolExtraArguments),
87
+ clientInfo,
88
+ elicit: (request, options) =>
89
+ elicitFromTool(extra as ToolExtraArguments, request, options),
90
+ };
91
+ }
92
+
38
93
  /**
39
94
  * Transforms a user's tool handler into an MCP-compatible handler.
40
95
  *
@@ -53,13 +108,16 @@ function hasUIMeta(meta?: Record<string, any>): boolean {
53
108
  */
54
109
  export function transformToolHandler(
55
110
  handler: UserToolHandler,
56
- meta?: Record<string, any>
111
+ meta?: Record<string, any>,
112
+ outputSchema?: ZodRawShape,
113
+ toolName = "unknown-tool"
57
114
  ): McpToolHandler {
58
115
  return async (
59
116
  args: ZodRawShape,
60
117
  extra: RequestHandlerExtra<ServerRequest, ServerNotification>
61
118
  ): Promise<CallToolResult> => {
62
- let response = handler(args, extra);
119
+ const toolExtra = createToolExtraArguments(extra);
120
+ let response: any = handler(args, toolExtra);
63
121
 
64
122
  // only await if it's actually a promise
65
123
  if (response instanceof Promise) {
@@ -67,6 +125,30 @@ export function transformToolHandler(
67
125
  }
68
126
 
69
127
  if (typeof response === "string" || typeof response === "number") {
128
+ if (outputSchema) {
129
+ const outputSchemaEntries = Object.entries(outputSchema);
130
+ if (outputSchemaEntries.length === 1) {
131
+ const [fieldName, fieldSchema] = outputSchemaEntries[0];
132
+ try {
133
+ fieldSchema.parse(response);
134
+ return {
135
+ content: [
136
+ {
137
+ type: "text",
138
+ text: typeof response === "number" ? `${response}` : response,
139
+ },
140
+ ],
141
+ structuredContent: {
142
+ [fieldName]: response,
143
+ },
144
+ };
145
+ } catch {
146
+ // Backward compatible fallback: keep content-only when primitive
147
+ // output does not match outputSchema.
148
+ }
149
+ }
150
+ }
151
+
70
152
  // Check if we have widget metadata to attach
71
153
  const hasWidgetMeta = hasUIMeta(meta);
72
154
 
@@ -98,6 +180,30 @@ export function transformToolHandler(
98
180
  };
99
181
  }
100
182
 
183
+ // With outputSchema declared, allow returning a plain object as shorthand
184
+ // for `{ structuredContent: ... }`.
185
+ if (
186
+ outputSchema &&
187
+ response &&
188
+ typeof response === "object" &&
189
+ !Array.isArray(response) &&
190
+ !("structuredContent" in response) &&
191
+ !("content" in response && Array.isArray((response as any).content)) &&
192
+ !("_meta" in response) &&
193
+ !("isError" in response)
194
+ ) {
195
+ // Validate the response against outputSchema before wrapping.
196
+ validateAgainstOutputSchema(
197
+ response as Record<string, unknown>,
198
+ outputSchema,
199
+ toolName,
200
+ "returned data that does not match outputSchema"
201
+ );
202
+ response = {
203
+ structuredContent: response,
204
+ };
205
+ }
206
+
101
207
  // Check if response has _meta but no content (special case for widget metadata)
102
208
  if (
103
209
  response &&
@@ -166,10 +272,11 @@ export function transformToolHandler(
166
272
  }
167
273
 
168
274
  // Check if response has at least one of: content or structuredContent
169
- const hasContent = "content" in response && Array.isArray(response.content);
275
+ let hasContent = "content" in response && Array.isArray(response.content);
170
276
  const hasStructuredContent = "structuredContent" in response;
277
+ const isError = "isError" in response && (response as any).isError === true;
171
278
 
172
- if (!hasContent && !hasStructuredContent) {
279
+ if (!hasContent && !hasStructuredContent && !isError) {
173
280
  const responseValue = JSON.stringify(response, null, 2);
174
281
 
175
282
  throw new Error(
@@ -196,6 +303,38 @@ export function transformToolHandler(
196
303
  );
197
304
  }
198
305
 
306
+ // Auto-generate fallback content for isError responses without content
307
+ if (isError && !hasContent && !hasStructuredContent) {
308
+ const { isError: _, ...rest } = response as Record<string, unknown>;
309
+ const errorText =
310
+ Object.keys(rest).length > 0
311
+ ? `Tool execution failed: ${JSON.stringify(rest)}`
312
+ : "Tool execution failed";
313
+ response.content = [{ type: "text", text: errorText }];
314
+ hasContent = true;
315
+ }
316
+
317
+ // Validate structuredContent against outputSchema if present.
318
+ if (outputSchema && hasStructuredContent && !isError) {
319
+ validateAgainstOutputSchema(
320
+ (response as any).structuredContent as Record<string, unknown>,
321
+ outputSchema,
322
+ toolName,
323
+ "returned structuredContent that does not match outputSchema"
324
+ );
325
+ }
326
+
327
+ // Auto-generate text fallback for clients that only render content.
328
+ if (!hasContent && hasStructuredContent) {
329
+ response.content = [
330
+ {
331
+ type: "text",
332
+ text: JSON.stringify((response as any).structuredContent),
333
+ },
334
+ ];
335
+ hasContent = true;
336
+ }
337
+
199
338
  // validate each content item if content is present
200
339
  if (hasContent) {
201
340
  for (let i = 0; i < response.content.length; i++) {
@@ -243,6 +382,6 @@ export function transformToolHandler(
243
382
  }
244
383
  }
245
384
 
246
- return response;
385
+ return response as CallToolResult;
247
386
  };
248
387
  }
@@ -0,0 +1,12 @@
1
+ export interface McpClientInfo {
2
+ /** MCP client implementation name from initialize.params.clientInfo.name */
3
+ name: string;
4
+ /** MCP client implementation version from initialize.params.clientInfo.version */
5
+ version: string;
6
+ /** Optional human-friendly title from initialize.params.clientInfo.title */
7
+ title?: string;
8
+ /** Optional website URL from initialize.params.clientInfo.websiteUrl */
9
+ websiteUrl?: string;
10
+ /** Optional description from initialize.params.clientInfo.description */
11
+ description?: string;
12
+ }
@@ -0,0 +1,62 @@
1
+ // ─── ProvidePlugin (module exports wired from .xmcp/import-map.js) ────────────
2
+
3
+ declare const INJECTED_TOOLS: Record<
4
+ string,
5
+ () => Promise<import("../runtime/utils/server").ToolFile>
6
+ >;
7
+
8
+ declare const INJECTED_PROMPTS: Record<
9
+ string,
10
+ () => Promise<import("../runtime/utils/server").PromptFile>
11
+ >;
12
+
13
+ declare const INJECTED_RESOURCES: Record<
14
+ string,
15
+ () => Promise<import("../runtime/utils/server").ResourceFile>
16
+ >;
17
+
18
+ declare const INJECTED_MIDDLEWARE:
19
+ | (() => Promise<{
20
+ default?:
21
+ | import("./middleware").Middleware
22
+ | import("./middleware").Middleware[]
23
+ | import("./middleware").WebMiddleware
24
+ | import("./middleware").WebMiddleware[];
25
+ }>)
26
+ | undefined;
27
+
28
+ // ─── DefinePlugin — config objects ────────────────────────────────────────────
29
+
30
+ declare const HTTP_CONFIG: Omit<
31
+ NonNullable<import("../compiler/config").ResolvedHttpConfig>,
32
+ "cors"
33
+ >;
34
+
35
+ declare const HTTP_CORS_CONFIG: import("../compiler/config").CorsConfig;
36
+
37
+ declare const TEMPLATE_CONFIG: import("../compiler/config").TemplateConfig;
38
+
39
+ declare const STDIO_CONFIG: { debug: boolean; silent: boolean };
40
+
41
+ declare const SERVER_INFO: import("@modelcontextprotocol/sdk/types").Implementation;
42
+
43
+ // ─── DefinePlugin — individual CORS vars (legacy Express adapter) ──────────────
44
+
45
+ declare const HTTP_CORS_ORIGIN: string;
46
+ declare const HTTP_CORS_METHODS: string;
47
+ declare const HTTP_CORS_ALLOWED_HEADERS: string;
48
+ declare const HTTP_CORS_EXPOSED_HEADERS: string;
49
+ declare const HTTP_CORS_CREDENTIALS: boolean;
50
+ declare const HTTP_CORS_MAX_AGE: number;
51
+ declare const HTTP_DEBUG: boolean;
52
+ declare const HTTP_BODY_SIZE_LIMIT: string;
53
+
54
+ // ─── DefinePlugin — runtime flags ─────────────────────────────────────────────
55
+
56
+ declare const IS_CLOUDFLARE: boolean;
57
+
58
+ declare const INJECTED_CLIENT_BUNDLES:
59
+ | Record<string, { js: string; css?: string }>
60
+ | undefined;
61
+
62
+ declare const RUNTIME_FILES: Record<string, string>;
package/src/types/tool.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { z } from "zod/v3";
2
2
  import type { ZodType as ZodTypeV4, infer as inferV4 } from "zod";
3
+ import type { ElicitResult as McpElicitResult } from "@modelcontextprotocol/sdk/types";
3
4
  import { UIMetadata } from "./ui-meta";
5
+ import type { McpClientInfo } from "./client-info";
4
6
 
5
7
  export interface ToolAnnotations {
6
8
  /** Human-readable title for the tool */
@@ -31,10 +33,95 @@ export interface ToolMetadata {
31
33
  }
32
34
 
33
35
  type CompatibleZodType = z.ZodTypeAny | ZodTypeV4<unknown>;
36
+ type InferCompatibleZodType<T extends CompatibleZodType> =
37
+ T extends z.ZodTypeAny
38
+ ? z.infer<T>
39
+ : T extends ZodTypeV4<unknown>
40
+ ? inferV4<T>
41
+ : never;
34
42
 
35
43
  export type ToolSchema = Record<string, CompatibleZodType>;
44
+ export type ToolOutputSchema = Record<string, CompatibleZodType>;
45
+ export type ElicitResult = McpElicitResult;
46
+
47
+ export interface ToolRequestOptions {
48
+ /** Progress notification callback */
49
+ onprogress?: (progress: any) => void;
50
+ /** Abort signal for cancelling the request */
51
+ signal?: AbortSignal;
52
+ /** Request timeout in milliseconds */
53
+ timeout?: number;
54
+ /** Whether receiving progress notifications resets the timeout */
55
+ resetTimeoutOnProgress?: boolean;
56
+ /** Maximum total time to wait for a response */
57
+ maxTotalTimeout?: number;
58
+ /** Additional transport-specific options */
59
+ [key: string]: unknown;
60
+ }
61
+
62
+ type ElicitStringFormat = "date" | "uri" | "email" | "date-time";
63
+
64
+ interface ElicitFieldBase {
65
+ title?: string;
66
+ description?: string;
67
+ }
68
+
69
+ export interface ElicitStringField extends ElicitFieldBase {
70
+ type: "string";
71
+ minLength?: number;
72
+ maxLength?: number;
73
+ format?: ElicitStringFormat;
74
+ default?: string;
75
+ }
76
+
77
+ export interface ElicitEnumField extends ElicitFieldBase {
78
+ type: "string";
79
+ enum: string[];
80
+ enumNames?: string[];
81
+ default?: string;
82
+ }
83
+
84
+ export interface ElicitBooleanField extends ElicitFieldBase {
85
+ type: "boolean";
86
+ default?: boolean;
87
+ }
36
88
 
37
- // The ToolExtraArguments type is equivalent to Parameters<ToolCallback<undefined>>[0] from @modelcontextprotocol/sdk but fully resolved to avoid external type dependencies.
89
+ export interface ElicitNumberField extends ElicitFieldBase {
90
+ type: "number" | "integer";
91
+ minimum?: number;
92
+ maximum?: number;
93
+ default?: number;
94
+ }
95
+
96
+ export type ElicitFormField =
97
+ | ElicitStringField
98
+ | ElicitEnumField
99
+ | ElicitBooleanField
100
+ | ElicitNumberField;
101
+
102
+ export interface ElicitFormSchema {
103
+ type: "object";
104
+ properties: Record<string, ElicitFormField>;
105
+ required?: string[];
106
+ }
107
+
108
+ export interface ElicitFormRequest {
109
+ mode?: "form";
110
+ message: string;
111
+ requestedSchema: ElicitFormSchema;
112
+ }
113
+
114
+ export interface ElicitUrlRequest {
115
+ mode: "url";
116
+ message: string;
117
+ url: string;
118
+ elicitationId: string;
119
+ }
120
+
121
+ export type ElicitRequest = ElicitFormRequest | ElicitUrlRequest;
122
+
123
+ // The ToolExtraArguments type is based on Parameters<ToolCallback<undefined>>[0]
124
+ // from @modelcontextprotocol/sdk, with xmcp-specific extensions.
38
125
  /**
39
126
  * Extra arguments passed to MCP tool functions.
40
127
  */
@@ -76,28 +163,24 @@ export interface ToolExtraArguments {
76
163
  headers: Record<string, string | string[] | undefined>;
77
164
  };
78
165
 
166
+ /** MCP client metadata from initialize.params.clientInfo, when available */
167
+ clientInfo?: McpClientInfo;
168
+
79
169
  /** Sends a notification that relates to the current request being handled */
80
170
  sendNotification: (notification: any) => Promise<void>;
81
171
 
82
172
  /** Sends a request that relates to the current request being handled */
83
- sendRequest: <U extends z.ZodType<object>>(
173
+ sendRequest: <U extends CompatibleZodType>(
84
174
  request: any,
85
175
  resultSchema: U,
86
- options?: {
87
- /** Progress notification callback */
88
- onprogress?: (progress: any) => void;
89
- /** Abort signal for cancelling the request */
90
- signal?: AbortSignal;
91
- /** Request timeout in milliseconds */
92
- timeout?: number;
93
- /** Whether receiving progress notifications resets the timeout */
94
- resetTimeoutOnProgress?: boolean;
95
- /** Maximum total time to wait for a response */
96
- maxTotalTimeout?: number;
97
- /** Additional transport-specific options */
98
- [key: string]: unknown;
99
- }
100
- ) => Promise<z.infer<U>>;
176
+ options?: ToolRequestOptions
177
+ ) => Promise<InferCompatibleZodType<U>>;
178
+
179
+ /** Requests user input from the connected client */
180
+ elicit: (
181
+ request: ElicitRequest,
182
+ options?: ToolRequestOptions
183
+ ) => Promise<ElicitResult>;
101
184
  }
102
185
 
103
186
  export type InferSchema<T extends Record<string, unknown>> = {
@@ -8,7 +8,7 @@ type SetContext<T extends DefaultContext> = (data: Partial<T>) => void;
8
8
 
9
9
  export interface Context<T extends DefaultContext> {
10
10
  /** Run a callback with a specific context. */
11
- provider: (initialValue: T, callback: () => void) => void;
11
+ provider: <R>(initialValue: T, callback: () => R) => R;
12
12
  /** Get the context. */
13
13
  getContext: GetContext<T>;
14
14
  /** Partially update the context. */
@@ -88,7 +88,7 @@ export function createContext<T extends Object>({
88
88
  Object.assign(store, data);
89
89
  };
90
90
 
91
- const provider = (initialValue: T, callback: () => void) => {
91
+ const provider = <R>(initialValue: T, callback: () => R): R => {
92
92
  fallbackStoreWrapper.current = initialValue;
93
93
  return context.run(initialValue, callback);
94
94
  };