xmcp 0.6.7 → 0.6.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/cli.js +36 -15
  2. package/dist/compiler/config/index.d.ts +7 -0
  3. package/dist/compiler/config/schemas/template.d.ts +5 -0
  4. package/dist/host-bridge.d.ts +4 -0
  5. package/dist/host-bridge.js +1 -0
  6. package/dist/index.d.ts +4 -0
  7. package/dist/index.js +5 -5
  8. package/dist/runtime/adapter-express.js +21 -19
  9. package/dist/runtime/adapter-nestjs.js +21 -19
  10. package/dist/runtime/adapter-nextjs.js +21 -19
  11. package/dist/runtime/contexts/client-info-context.d.ts +8 -0
  12. package/dist/runtime/http.js +26 -24
  13. package/dist/runtime/stdio.js +32 -30
  14. package/dist/runtime/utils/mcp-app-protocol.d.ts +14 -0
  15. package/dist/runtime/utils/mcp-app-types.d.ts +103 -0
  16. package/dist/runtime/utils/mcp-host-bridge.d.ts +43 -0
  17. package/dist/runtime/utils/server.d.ts +3 -1
  18. package/dist/types/ui-meta.d.ts +15 -0
  19. package/package.json +12 -1
  20. package/src/compiler/client/component-compiler.ts +26 -5
  21. package/src/compiler/config/injection.ts +1 -0
  22. package/src/compiler/config/schemas/template.ts +13 -0
  23. package/src/compiler/get-bundler-config/index.ts +1 -0
  24. package/src/host-bridge.ts +36 -0
  25. package/src/index.ts +36 -0
  26. package/src/runtime/adapters/nextjs/handler/server-lifecycle.ts +2 -1
  27. package/src/runtime/contexts/client-info-context.ts +16 -0
  28. package/src/runtime/transports/http/stateless-streamable-http.ts +11 -89
  29. package/src/runtime/transports/stdio/index.ts +40 -7
  30. package/src/runtime/utils/__tests__/client-info.test.ts +19 -0
  31. package/src/runtime/utils/__tests__/tool-extra.test.ts +39 -0
  32. package/src/runtime/utils/client-info.ts +7 -0
  33. package/src/runtime/utils/mcp-app-protocol.ts +16 -0
  34. package/src/runtime/utils/mcp-app-types.ts +113 -0
  35. package/src/runtime/utils/mcp-host-bridge.ts +473 -0
  36. package/src/runtime/utils/react/generate-html.ts +12 -4
  37. package/src/runtime/utils/server.ts +3 -2
  38. package/src/runtime/utils/transformers/tool.ts +10 -1
  39. package/src/runtime/utils/ui/__tests__/split-meta.test.ts +42 -0
  40. package/src/runtime/utils/ui/split-meta.ts +4 -1
  41. package/src/types/ui-meta.ts +17 -1
@@ -0,0 +1,14 @@
1
+ export declare const MCP_APPS_PROTOCOL_VERSION = "2026-01-26";
2
+ export declare const INITIALIZE_METHOD = "ui/initialize";
3
+ export declare const INITIALIZED_METHOD = "ui/notifications/initialized";
4
+ export declare const REQUEST_DISPLAY_MODE_METHOD = "ui/request-display-mode";
5
+ export declare const REQUEST_DISPLAY_MODE_METHOD_LEGACY = "ui/requestDisplayMode";
6
+ export declare const OPEN_LINK_METHOD = "ui/open-link";
7
+ export declare const OPEN_LINK_METHOD_LEGACY = "ui/openLink";
8
+ export declare const UPDATE_MODEL_CONTEXT_METHOD = "ui/update-model-context";
9
+ export declare const UI_MESSAGE_METHOD = "ui/message";
10
+ export declare const LOG_MESSAGE_METHOD = "notifications/message";
11
+ export declare const RESOURCES_READ_METHOD = "resources/read";
12
+ export declare const HOST_CONTEXT_CHANGED_METHOD = "ui/notifications/host-context-changed";
13
+ export declare const HOST_CONTEXT_CHANGED_METHOD_LEGACY = "ui/hostContextChanged";
14
+ export declare const SIZE_CHANGED_METHOD = "ui/notifications/size-changed";
@@ -0,0 +1,103 @@
1
+ export type McpUiDisplayMode = "inline" | "fullscreen" | "pip";
2
+ export interface McpHostCallToolParams {
3
+ name: string;
4
+ arguments?: Record<string, unknown>;
5
+ }
6
+ export interface McpHostOpenLinkParams {
7
+ url: string;
8
+ }
9
+ export interface McpHostRequestDisplayModeParams {
10
+ mode: McpUiDisplayMode;
11
+ }
12
+ export interface McpHostRequestDisplayModeResult {
13
+ mode: McpUiDisplayMode | string;
14
+ }
15
+ export interface McpHostSendMessageParams {
16
+ role?: string;
17
+ content: unknown;
18
+ [key: string]: unknown;
19
+ }
20
+ export interface McpHostUpdateModelContextParams {
21
+ content?: unknown;
22
+ role?: string;
23
+ [key: string]: unknown;
24
+ }
25
+ export interface McpHostToolContentItem {
26
+ type: string;
27
+ text?: string;
28
+ [key: string]: unknown;
29
+ }
30
+ export interface McpHostToolResult {
31
+ content?: McpHostToolContentItem[];
32
+ structuredContent?: unknown;
33
+ isError?: boolean;
34
+ [key: string]: unknown;
35
+ }
36
+ export interface McpHostResourceContentItem {
37
+ uri?: string;
38
+ mimeType?: string;
39
+ text?: string;
40
+ blob?: string;
41
+ [key: string]: unknown;
42
+ }
43
+ export interface McpHostReadResourceResult {
44
+ contents?: McpHostResourceContentItem[];
45
+ [key: string]: unknown;
46
+ }
47
+ export interface McpHostMessageResult {
48
+ role?: string;
49
+ content?: unknown;
50
+ [key: string]: unknown;
51
+ }
52
+ export interface McpHostModelContextResult {
53
+ ok?: boolean;
54
+ [key: string]: unknown;
55
+ }
56
+ export interface McpHostContainerDimensions {
57
+ width?: number;
58
+ height?: number;
59
+ }
60
+ export interface McpHostStyleContext {
61
+ variables?: Record<string, string>;
62
+ css?: {
63
+ fonts?: string[];
64
+ [key: string]: unknown;
65
+ };
66
+ [key: string]: unknown;
67
+ }
68
+ export interface McpHostContext {
69
+ theme?: string;
70
+ displayMode?: McpUiDisplayMode | string;
71
+ locale?: string;
72
+ timeZone?: string;
73
+ platform?: string;
74
+ availableDisplayModes?: McpUiDisplayMode[];
75
+ containerDimensions?: McpHostContainerDimensions;
76
+ safeAreaInsets?: {
77
+ top?: number;
78
+ right?: number;
79
+ bottom?: number;
80
+ left?: number;
81
+ };
82
+ toolInfo?: Record<string, unknown>;
83
+ deviceCapabilities?: Record<string, unknown>;
84
+ styles?: McpHostStyleContext;
85
+ [key: string]: unknown;
86
+ }
87
+ export interface McpHostCapabilities {
88
+ serverTools?: {
89
+ listChanged?: boolean;
90
+ call?: boolean;
91
+ };
92
+ serverResources?: {
93
+ listChanged?: boolean;
94
+ read?: boolean;
95
+ };
96
+ openLinks?: boolean;
97
+ updateModelContext?: boolean | string[];
98
+ message?: boolean;
99
+ logging?: boolean;
100
+ downloadFile?: boolean;
101
+ sandbox?: Record<string, unknown>;
102
+ [key: string]: unknown;
103
+ }
@@ -0,0 +1,43 @@
1
+ import type { McpHostCallToolParams, McpHostCapabilities, McpHostContainerDimensions, McpHostContext, McpHostMessageResult, McpHostModelContextResult, McpHostOpenLinkParams, McpHostReadResourceResult, McpHostRequestDisplayModeResult, McpHostSendMessageParams, McpHostToolResult, McpUiDisplayMode, McpHostUpdateModelContextParams } from "./mcp-app-types";
2
+ export * from "./mcp-app-protocol";
3
+ export type * from "./mcp-app-types";
4
+ export interface McpHostBridgeState {
5
+ isConnected: boolean;
6
+ hostContext: McpHostContext | null;
7
+ hostCapabilities: McpHostCapabilities | null;
8
+ }
9
+ export interface McpHostBridge {
10
+ callTool: (name: McpHostCallToolParams["name"], args?: McpHostCallToolParams["arguments"]) => Promise<McpHostToolResult>;
11
+ requestDisplayMode: (mode: McpUiDisplayMode) => Promise<McpHostRequestDisplayModeResult>;
12
+ openLink: (url: McpHostOpenLinkParams["url"]) => Promise<void>;
13
+ readResource: (uri: string) => Promise<McpHostReadResourceResult>;
14
+ sendMessage: (params: McpHostSendMessageParams) => Promise<McpHostMessageResult>;
15
+ updateModelContext: (params: McpHostUpdateModelContextParams) => Promise<McpHostModelContextResult>;
16
+ logMessage: (params: McpHostSendMessageParams) => Promise<void>;
17
+ notifySizeChanged: (params: McpHostContainerDimensions) => Promise<void>;
18
+ getState: () => McpHostBridgeState;
19
+ getHostContext: () => McpHostContext | null;
20
+ getHostCapabilities: () => McpHostCapabilities | null;
21
+ isConnected: () => boolean;
22
+ subscribe: (listener: (state: McpHostBridgeState) => void) => () => void;
23
+ dispose: () => void;
24
+ }
25
+ interface MessageEventLike {
26
+ source: unknown;
27
+ data: unknown;
28
+ }
29
+ interface MessageTargetLike {
30
+ postMessage: (message: unknown, targetOrigin: string) => void;
31
+ }
32
+ interface WindowLike extends MessageTargetLike {
33
+ parent: MessageTargetLike;
34
+ open?: (url: string, target?: string, features?: string) => unknown;
35
+ addEventListener: (type: "message", listener: (event: MessageEventLike) => void) => void;
36
+ removeEventListener: (type: "message", listener: (event: MessageEventLike) => void) => void;
37
+ }
38
+ export interface CreateMcpHostBridgeOptions {
39
+ targetWindow?: WindowLike;
40
+ requestTimeoutMs?: number;
41
+ connectionTimeoutMs?: number;
42
+ }
43
+ export declare function createMcpHostBridge(options?: CreateMcpHostBridgeOptions): McpHostBridge;
@@ -27,7 +27,9 @@ export type ResourceFile = {
27
27
  export declare const injectedTools: Record<string, () => Promise<ToolFile>>;
28
28
  export declare const injectedPrompts: Record<string, () => Promise<PromptFile>>;
29
29
  export declare const injectedResources: Record<string, () => Promise<ResourceFile>>;
30
- export declare const INJECTED_CONFIG: Implementation;
30
+ export declare const INJECTED_CONFIG: Implementation & {
31
+ instructions?: string;
32
+ };
31
33
  export declare function configureServer(server: McpServer, toolModules: Map<string, ToolFile>, promptModules: Map<string, PromptFile>, resourceModules: Map<string, ResourceFile>): Promise<McpServer>;
32
34
  export declare function loadTools(): Promise<Map<string, ToolFile>>;
33
35
  export declare function loadPrompts(): Promise<Map<string, PromptFile>>;
@@ -4,12 +4,27 @@ export interface UIMetadata {
4
4
  * Auto-generated as `ui://app/{toolName}.html` when omitted.
5
5
  */
6
6
  resourceUri?: string;
7
+ /**
8
+ * Visibility hint for how prominently hosts should surface the widget entry point.
9
+ */
10
+ visibility?: Array<"model" | "app">;
7
11
  /**
8
12
  * Content Security Policy configuration for widget resources.
9
13
  */
10
14
  csp?: {
11
15
  connectDomains?: string[];
12
16
  resourceDomains?: string[];
17
+ frameDomains?: string[];
18
+ baseUriDomains?: string[];
19
+ };
20
+ /**
21
+ * Browser permission hints requested by the widget iframe.
22
+ */
23
+ permissions?: {
24
+ camera?: Record<string, never>;
25
+ microphone?: Record<string, never>;
26
+ geolocation?: Record<string, never>;
27
+ clipboardWrite?: Record<string, never>;
13
28
  };
14
29
  /**
15
30
  * Optional dedicated origin for this widget.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "xmcp",
3
3
  "description": "The MCP framework",
4
- "version": "0.6.7",
4
+ "version": "0.6.9",
5
5
  "author": {
6
6
  "name": "xmcp",
7
7
  "email": "support@xmcp.dev",
@@ -40,9 +40,16 @@
40
40
  "exports": {
41
41
  ".": {
42
42
  "types": "./dist/index.d.ts",
43
+ "import": "./dist/index.js",
43
44
  "require": "./dist/index.js",
44
45
  "default": "./dist/index.js"
45
46
  },
47
+ "./host-bridge": {
48
+ "types": "./dist/host-bridge.d.ts",
49
+ "import": "./dist/host-bridge.js",
50
+ "require": "./dist/host-bridge.js",
51
+ "default": "./dist/host-bridge.js"
52
+ },
46
53
  "./headers": {
47
54
  "types": "./dist/runtime/headers.d.ts",
48
55
  "require": "./dist/runtime/headers.js",
@@ -50,6 +57,7 @@
50
57
  },
51
58
  "./cloudflare": {
52
59
  "types": "./dist/cloudflare.d.ts",
60
+ "import": "./dist/cloudflare.js",
53
61
  "require": "./dist/cloudflare.js",
54
62
  "default": "./dist/cloudflare.js"
55
63
  },
@@ -57,6 +65,9 @@
57
65
  },
58
66
  "typesVersions": {
59
67
  "*": {
68
+ "host-bridge": [
69
+ "dist/host-bridge.d.ts"
70
+ ],
60
71
  "headers": [
61
72
  "dist/runtime/headers.d.ts"
62
73
  ],
@@ -125,12 +125,33 @@ export class ClientComponentCompiler {
125
125
  root.render(React.createElement(Component, props));
126
126
  }
127
127
 
128
+ render({});
129
+
128
130
  window.addEventListener("message", (event) => {
129
131
  if (event.source !== window.parent && event.source !== null) return;
130
-
131
- if (event.data?.method === "ui/notifications/tool-input") {
132
- render(event.data.params?.arguments ?? {});
133
- }
132
+ const method = event.data?.method;
133
+ const isInputNotification =
134
+ method === "ui/notifications/tool-input" ||
135
+ method === "tool-input" ||
136
+ method === "mcp-apps:tool-input" ||
137
+ method === "ui/notifications/tool-input-partial";
138
+
139
+ const isResultNotification = method === "ui/notifications/tool-result";
140
+
141
+ if (!isInputNotification && !isResultNotification) return;
142
+
143
+ const args = isResultNotification
144
+ ? event.data?.params?.structuredContent?.args ??
145
+ event.data?.params?.arguments ??
146
+ event.data?.params?.input ??
147
+ event.data?.arguments ??
148
+ {}
149
+ : event.data?.params?.arguments ??
150
+ event.data?.params?.input ??
151
+ event.data?.arguments ??
152
+ {};
153
+
154
+ render(args);
134
155
  });
135
156
  `;
136
157
  }
@@ -221,7 +242,7 @@ export class ClientComponentCompiler {
221
242
  concatenateModules: true,
222
243
  moduleIds: "deterministic",
223
244
  },
224
- cache: true,
245
+ cache: false,
225
246
  };
226
247
  }
227
248
  }
@@ -164,6 +164,7 @@ export function injectServerInfoVariables(userConfig: XmcpConfigOutputSchema) {
164
164
  version,
165
165
  description: templateConfig.description,
166
166
  icons,
167
+ instructions: templateConfig.instructions,
167
168
  };
168
169
 
169
170
  return {
@@ -29,6 +29,19 @@ const templateConfigBaseSchema = z.object({
29
29
  })
30
30
  )
31
31
  .optional(),
32
+ /**
33
+ * Instructions describing how to use the server and its features.
34
+ *
35
+ * This is sent in the MCP `initialize` response and can be used by clients
36
+ * to improve the LLM's understanding of available tools, resources, etc.
37
+ *
38
+ * Instructions should focus on cross-tool relationships, workflow patterns,
39
+ * and constraints, but should not duplicate information already in tool descriptions.
40
+ *
41
+ * @example
42
+ * instructions: "Use tool-a before tool-b. Always check resources first."
43
+ */
44
+ instructions: z.string().optional(),
32
45
  /**
33
46
  * Custom home page content for the `/` endpoint.
34
47
  *
@@ -121,6 +121,7 @@ export function getRspackConfig(
121
121
  output: {
122
122
  filename: outputFilename,
123
123
  path: outputPath,
124
+ globalObject: "globalThis",
124
125
  ...(isCloudflare
125
126
  ? {
126
127
  library: { type: "module" },
@@ -0,0 +1,36 @@
1
+ export { createMcpHostBridge } from "./runtime/utils/mcp-host-bridge";
2
+ export type {
3
+ McpHostBridge,
4
+ McpHostBridgeState,
5
+ CreateMcpHostBridgeOptions,
6
+ } from "./runtime/utils/mcp-host-bridge";
7
+ export type {
8
+ McpHostCallToolParams,
9
+ McpHostContext,
10
+ McpHostCapabilities,
11
+ McpHostContainerDimensions,
12
+ McpHostOpenLinkParams,
13
+ McpHostReadResourceResult,
14
+ McpHostRequestDisplayModeParams,
15
+ McpHostRequestDisplayModeResult,
16
+ McpHostSendMessageParams,
17
+ McpHostMessageResult,
18
+ McpHostModelContextResult,
19
+ McpHostToolContentItem,
20
+ McpHostToolResult,
21
+ McpUiDisplayMode,
22
+ McpHostUpdateModelContextParams,
23
+ } from "./runtime/utils/mcp-app-types";
24
+ export {
25
+ MCP_APPS_PROTOCOL_VERSION,
26
+ INITIALIZE_METHOD,
27
+ INITIALIZED_METHOD,
28
+ REQUEST_DISPLAY_MODE_METHOD,
29
+ OPEN_LINK_METHOD,
30
+ UPDATE_MODEL_CONTEXT_METHOD,
31
+ UI_MESSAGE_METHOD,
32
+ LOG_MESSAGE_METHOD,
33
+ RESOURCES_READ_METHOD,
34
+ HOST_CONTEXT_CHANGED_METHOD,
35
+ SIZE_CHANGED_METHOD,
36
+ } from "./runtime/utils/mcp-app-protocol";
package/src/index.ts CHANGED
@@ -56,3 +56,39 @@ export type {
56
56
  export { isEnvHeader, headersToRecord } from "./client/headers";
57
57
 
58
58
  export { extractToolNamesFromRequest } from "./runtime/utils/request-tool-names";
59
+ export { createMcpHostBridge } from "./runtime/utils/mcp-host-bridge";
60
+ export type {
61
+ McpHostBridge,
62
+ McpHostBridgeState,
63
+ CreateMcpHostBridgeOptions,
64
+ } from "./runtime/utils/mcp-host-bridge";
65
+ export type {
66
+ McpHostCallToolParams,
67
+ McpHostContext,
68
+ McpHostCapabilities,
69
+ McpHostContainerDimensions,
70
+ McpHostOpenLinkParams,
71
+ McpHostReadResourceResult,
72
+ McpHostRequestDisplayModeParams,
73
+ McpHostRequestDisplayModeResult,
74
+ McpHostSendMessageParams,
75
+ McpHostMessageResult,
76
+ McpHostModelContextResult,
77
+ McpHostToolContentItem,
78
+ McpHostToolResult,
79
+ McpUiDisplayMode,
80
+ McpHostUpdateModelContextParams,
81
+ } from "./runtime/utils/mcp-app-types";
82
+ export {
83
+ MCP_APPS_PROTOCOL_VERSION,
84
+ INITIALIZE_METHOD,
85
+ INITIALIZED_METHOD,
86
+ REQUEST_DISPLAY_MODE_METHOD,
87
+ OPEN_LINK_METHOD,
88
+ UPDATE_MODEL_CONTEXT_METHOD,
89
+ UI_MESSAGE_METHOD,
90
+ LOG_MESSAGE_METHOD,
91
+ RESOURCES_READ_METHOD,
92
+ HOST_CONTEXT_CHANGED_METHOD,
93
+ SIZE_CHANGED_METHOD,
94
+ } from "./runtime/utils/mcp-app-protocol";
@@ -46,7 +46,8 @@ export async function initializeMcpServer(): Promise<McpServer> {
46
46
  resourceModulesPromise,
47
47
  ]);
48
48
 
49
- const server = new McpServer(INJECTED_CONFIG);
49
+ const { instructions, ...serverInfo } = INJECTED_CONFIG;
50
+ const server = new McpServer(serverInfo, { instructions });
50
51
 
51
52
  await configureServer(server, toolModules, promptModules, resourceModules);
52
53
 
@@ -0,0 +1,16 @@
1
+ import type { McpClientInfo } from "@/types/client-info";
2
+ import { createContext } from "../../utils/context";
3
+
4
+ export interface ClientInfoContext {
5
+ clientInfo?: McpClientInfo;
6
+ }
7
+
8
+ export const clientInfoContext = createContext<ClientInfoContext>({
9
+ name: "client-info-context",
10
+ });
11
+
12
+ export const setClientInfoContext = clientInfoContext.setContext;
13
+
14
+ export const getClientInfoContext = clientInfoContext.getContext;
15
+
16
+ export const clientInfoContextProvider = clientInfoContext.provider;
@@ -1,6 +1,5 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp";
2
2
  import { StreamableHTTPServerTransport as SdkStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp";
3
- import { isInitializeRequest } from "@modelcontextprotocol/sdk/types";
4
3
  import express, {
5
4
  Express,
6
5
  Request,
@@ -32,13 +31,6 @@ import {
32
31
  import { CorsConfig, corsConfigSchema } from "@/compiler/config/schemas";
33
32
  import { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types";
34
33
  import { extractClientInfoFromMessages } from "@/runtime/utils/client-info";
35
- import type { McpClientInfo } from "@/types/client-info";
36
-
37
- interface SessionLifecycle {
38
- server: McpServer;
39
- transport: SdkStreamableHTTPServerTransport;
40
- clientInfo?: McpClientInfo;
41
- }
42
34
 
43
35
  // Global type declarations for tool name context
44
36
  declare global {
@@ -110,7 +102,6 @@ export class StatelessStreamableHTTPTransport {
110
102
  private createServerFn: () => Promise<McpServer>;
111
103
  private corsConfig: CorsConfig;
112
104
  private providers: Provider[] | undefined;
113
- private sessions = new Map<string, SessionLifecycle>();
114
105
 
115
106
  constructor(
116
107
  createServerFn: () => Promise<McpServer>,
@@ -175,7 +166,7 @@ export class StatelessStreamableHTTPTransport {
175
166
  res.status(200).json({
176
167
  status: "ok",
177
168
  transport: "streamable-http",
178
- mode: "session",
169
+ mode: "stateless",
179
170
  });
180
171
  });
181
172
 
@@ -260,56 +251,25 @@ export class StatelessStreamableHTTPTransport {
260
251
  ): Promise<void> {
261
252
  try {
262
253
  const requestClientInfo = extractClientInfoFromMessages(req.body);
263
- const sessionId = this.getSessionId(req);
264
- let lifecycle = sessionId ? this.sessions.get(sessionId) : undefined;
265
- let clientInfo = requestClientInfo;
254
+ const server = await this.createServerFn();
255
+ const transport = new StatelessHttpServerTransport(
256
+ this.debug,
257
+ this.options.bodySizeLimit || "10mb"
258
+ );
266
259
 
267
260
  res.on("finish", () => {
268
261
  global.__XMCP_CURRENT_TOOL_NAME = undefined;
269
262
  });
270
263
  res.on("close", () => {
264
+ void transport.close();
265
+ void server.close();
271
266
  global.__XMCP_CURRENT_TOOL_NAME = undefined;
272
267
  });
273
268
 
274
- if (!lifecycle) {
275
- if (
276
- sessionId ||
277
- req.method !== "POST" ||
278
- !isInitializeRequest(req.body)
279
- ) {
280
- res.status(400).json({
281
- jsonrpc: "2.0",
282
- error: {
283
- code: -32000,
284
- message: "Bad Request: No valid session ID provided",
285
- },
286
- id: null,
287
- });
288
- return;
289
- }
290
-
291
- lifecycle = await this.createSessionLifecycle();
292
- }
293
-
294
- if (!clientInfo) {
295
- clientInfo = lifecycle.clientInfo;
296
- }
297
-
298
- setHttpRequestContext({ clientInfo });
299
-
300
- await lifecycle.transport.handleRequest(req, res, req.body);
269
+ setHttpRequestContext({ clientInfo: requestClientInfo });
301
270
 
302
- if (!sessionId && lifecycle.transport.sessionId) {
303
- this.sessions.set(lifecycle.transport.sessionId, {
304
- ...lifecycle,
305
- clientInfo,
306
- });
307
- } else if (sessionId && lifecycle.transport.sessionId) {
308
- this.sessions.set(lifecycle.transport.sessionId, {
309
- ...lifecycle,
310
- clientInfo,
311
- });
312
- }
271
+ await server.connect(transport);
272
+ await transport.handleRequest(req, res, req.body);
313
273
  } catch (error) {
314
274
  console.error("[HTTP-server] Error handling MCP request:", error);
315
275
  if (!res.headersSent) {
@@ -325,37 +285,6 @@ export class StatelessStreamableHTTPTransport {
325
285
  }
326
286
  }
327
287
 
328
- private getSessionId(req: Request): string | undefined {
329
- const header = req.headers["mcp-session-id"];
330
-
331
- if (Array.isArray(header)) {
332
- return header[0];
333
- }
334
-
335
- return typeof header === "string" && header.length > 0 ? header : undefined;
336
- }
337
-
338
- private async createSessionLifecycle(): Promise<SessionLifecycle> {
339
- const server = await this.createServerFn();
340
- const transport = new SdkStreamableHTTPServerTransport({
341
- sessionIdGenerator: () => randomUUID(),
342
- });
343
-
344
- transport.onclose = () => {
345
- const sessionId = transport.sessionId;
346
-
347
- if (sessionId) {
348
- this.sessions.delete(sessionId);
349
- }
350
-
351
- void server.close();
352
- };
353
-
354
- await server.connect(transport);
355
-
356
- return { server, transport };
357
- }
358
-
359
288
  public async start(): Promise<void> {
360
289
  const host = this.options.host || "127.0.0.1";
361
290
  const port = await findAvailablePort(this.port, host);
@@ -376,13 +305,6 @@ export class StatelessStreamableHTTPTransport {
376
305
 
377
306
  public shutdown(): void {
378
307
  this.log("Shutting down server");
379
-
380
- for (const { server, transport } of this.sessions.values()) {
381
- void transport.close();
382
- void server.close();
383
- }
384
-
385
- this.sessions.clear();
386
308
  this.server.close();
387
309
  process.exit(0);
388
310
  }
@@ -2,6 +2,11 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
3
  import { createServer } from "../../utils/server";
4
4
  import dotenv from "dotenv";
5
+ import {
6
+ clientInfoContextProvider,
7
+ setClientInfoContext,
8
+ } from "@/runtime/contexts/client-info-context";
9
+ import { mapImplementationToClientInfo } from "@/runtime/utils/client-info";
5
10
  dotenv.config();
6
11
 
7
12
  class StdioTransport {
@@ -17,6 +22,18 @@ class StdioTransport {
17
22
 
18
23
  public start(): void {
19
24
  try {
25
+ this.mcpServer.server.oninitialized = () => {
26
+ const implementation = this.mcpServer.server.getClientVersion();
27
+ const clientInfo = mapImplementationToClientInfo(implementation);
28
+ setClientInfoContext({ clientInfo });
29
+
30
+ if (this.debug && clientInfo) {
31
+ console.log(
32
+ `[STDIO] MCP client initialized: ${clientInfo.name}@${clientInfo.version}`
33
+ );
34
+ }
35
+ };
36
+
20
37
  this.mcpServer.connect(this.transport);
21
38
  if (this.debug) {
22
39
  console.log("[STDIO] MCP Server running with STDIO transport");
@@ -58,19 +75,35 @@ if (silent) {
58
75
  // the MCP stdio protocol on stdout.
59
76
  const stderrConsole = new console.Console(process.stderr, process.stderr);
60
77
  const methods = [
61
- "log", "debug", "info", "warn", "error",
62
- "dir", "table", "trace", "assert",
63
- "time", "timeEnd", "timeLog",
64
- "count", "countReset",
65
- "group", "groupEnd", "groupCollapsed",
78
+ "log",
79
+ "debug",
80
+ "info",
81
+ "warn",
82
+ "error",
83
+ "dir",
84
+ "table",
85
+ "trace",
86
+ "assert",
87
+ "time",
88
+ "timeEnd",
89
+ "timeLog",
90
+ "count",
91
+ "countReset",
92
+ "group",
93
+ "groupEnd",
94
+ "groupCollapsed",
66
95
  "clear",
67
96
  ] as const;
68
97
  for (const method of methods) {
69
- (console as any)[method] = (stderrConsole as any)[method].bind(stderrConsole);
98
+ (console as any)[method] = (stderrConsole as any)[method].bind(
99
+ stderrConsole
100
+ );
70
101
  }
71
102
  }
72
103
 
73
104
  createServer().then((mcpServer) => {
74
105
  const stdioTransport = new StdioTransport(mcpServer, debug);
75
- stdioTransport.start();
106
+ clientInfoContextProvider({ clientInfo: undefined }, () => {
107
+ stdioTransport.start();
108
+ });
76
109
  });