xmcp 0.6.9 → 0.6.11

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 (32) hide show
  1. package/README.md +0 -32
  2. package/dist/cli.js +27 -24
  3. package/dist/compiler/config/index.d.ts +11 -11
  4. package/dist/compiler/config/schemas/experimental/index.d.ts +4 -4
  5. package/dist/compiler/config/schemas/transport/http.d.ts +13 -13
  6. package/dist/index.js +5 -5
  7. package/dist/runtime/adapter-express.js +16 -16
  8. package/dist/runtime/adapter-fastify.js +488 -0
  9. package/dist/runtime/adapter-nestjs.js +16 -16
  10. package/dist/runtime/adapter-nextjs.js +14 -14
  11. package/dist/runtime/http.js +24 -24
  12. package/dist/runtime/stdio.js +17 -17
  13. package/dist/runtime/utils/client-info.d.ts +8 -0
  14. package/dist/types/client-info.d.ts +1 -0
  15. package/package.json +4 -2
  16. package/src/compiler/config/__tests__/config.test.ts +56 -0
  17. package/src/compiler/config/schemas/experimental/index.ts +6 -1
  18. package/src/compiler/config/schemas/transport/http.ts +5 -0
  19. package/src/compiler/get-bundler-config/get-entries.ts +3 -0
  20. package/src/compiler/get-bundler-config/get-externals.ts +10 -0
  21. package/src/compiler/get-bundler-config/plugins/index.ts +8 -3
  22. package/src/compiler/get-bundler-config/plugins/types/fastify.ts +4 -0
  23. package/src/compiler/get-bundler-config/plugins/types/index.ts +1 -0
  24. package/src/runtime/adapters/fastify/__tests__/fastify.test.ts +115 -0
  25. package/src/runtime/adapters/fastify/index.ts +78 -0
  26. package/src/runtime/transports/http/cors/index.ts +4 -2
  27. package/src/runtime/utils/__tests__/client-info.test.ts +47 -0
  28. package/src/runtime/utils/__tests__/tool-extra.test.ts +91 -1
  29. package/src/runtime/utils/client-info.ts +36 -0
  30. package/src/runtime/utils/transformers/tool.ts +5 -1
  31. package/src/telemetry/events/definitions.ts +2 -0
  32. package/src/types/client-info.ts +8 -0
@@ -0,0 +1,8 @@
1
+ import type { JsonRpcMessage } from "@/runtime/transports/http/base-streamable-http";
2
+ import type { HttpHeaders } from "@/runtime/contexts/http-request-context";
3
+ import type { McpClientInfo } from "@/types/client-info";
4
+ import type { Implementation } from "@modelcontextprotocol/sdk/types";
5
+ export declare const mapImplementationToClientInfo: (implementation: Implementation | undefined) => McpClientInfo | undefined;
6
+ export declare const extractClientInfoFromMessage: (message: JsonRpcMessage | undefined) => McpClientInfo | undefined;
7
+ export declare const extractClientInfoFromMessages: (payload: unknown) => McpClientInfo | undefined;
8
+ export declare const extractClientInfoFromHeaders: (headers: HttpHeaders) => McpClientInfo | undefined;
@@ -1,3 +1,4 @@
1
+ export declare const CLIENT_INFO_HEADER_NAMES: readonly ["x-mcp-client-name", "x-mcp-client-version", "x-mcp-client-title", "x-mcp-client-website-url", "x-mcp-client-description"];
1
2
  export interface McpClientInfo {
2
3
  /** MCP client implementation name from initialize.params.clientInfo.name */
3
4
  name: string;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "xmcp",
3
3
  "description": "The MCP framework",
4
- "version": "0.6.9",
4
+ "version": "0.6.11",
5
5
  "author": {
6
6
  "name": "xmcp",
7
7
  "email": "support@xmcp.dev",
@@ -84,7 +84,8 @@
84
84
  "dev": "cross-env NODE_ENV=development tsx --watch --tsconfig ./bundler.tsconfig.json ./bundler/index.ts",
85
85
  "build": "cross-env NODE_ENV=production tsx --tsconfig ./bundler.tsconfig.json ./bundler/index.ts",
86
86
  "analyze": "cross-env GENERATE_STATS=true pnpm build && pnpm tsx scripts/analyze-rspack-stats.ts",
87
- "test:config": "node --import tsx --test src/compiler/config/__tests__/*.test.ts"
87
+ "test:config": "node --import tsx --test src/compiler/config/__tests__/*.test.ts",
88
+ "test:adapters": "node --import tsx --test src/runtime/adapters/fastify/__tests__/*.test.ts"
88
89
  },
89
90
  "dependencies": {
90
91
  "@modelcontextprotocol/sdk": "^1.26.0",
@@ -114,6 +115,7 @@
114
115
  "del": "^7.1.0",
115
116
  "dotenv": "^16.6.1",
116
117
  "express": "^4.22.1",
118
+ "fastify": "^5.0.0",
117
119
  "fs-extra": "^11.3.2",
118
120
  "glob": "^11.1.0",
119
121
  "is-docker": "^4.0.0",
@@ -71,10 +71,45 @@ describe("Config System - Zod Defaults", () => {
71
71
  const corsConfig = getResolvedCorsConfig(httpConfig);
72
72
  assert.equal(corsConfig.origin, "*");
73
73
  assert.deepEqual(corsConfig.methods, ["GET", "POST"]);
74
+ assert.deepEqual(corsConfig.allowedHeaders, [
75
+ "Content-Type",
76
+ "Authorization",
77
+ "mcp-session-id",
78
+ "mcp-protocol-version",
79
+ "x-mcp-client-name",
80
+ "x-mcp-client-version",
81
+ "x-mcp-client-title",
82
+ "x-mcp-client-website-url",
83
+ "x-mcp-client-description",
84
+ ]);
74
85
  assert.equal(corsConfig.credentials, false);
75
86
  assert.equal(corsConfig.maxAge, 86400);
76
87
  }
77
88
  });
89
+
90
+ it("should preserve client info headers when merging CORS allowedHeaders arrays", () => {
91
+ const httpConfig = getResolvedHttpConfig({
92
+ cors: {
93
+ allowedHeaders: ["Content-Type", "Authorization"],
94
+ },
95
+ });
96
+ assert.notEqual(httpConfig, null);
97
+
98
+ if (httpConfig) {
99
+ const corsConfig = getResolvedCorsConfig(httpConfig);
100
+ assert.deepEqual(corsConfig.allowedHeaders, [
101
+ "Content-Type",
102
+ "Authorization",
103
+ "mcp-session-id",
104
+ "mcp-protocol-version",
105
+ "x-mcp-client-name",
106
+ "x-mcp-client-version",
107
+ "x-mcp-client-title",
108
+ "x-mcp-client-website-url",
109
+ "x-mcp-client-description",
110
+ ]);
111
+ }
112
+ });
78
113
  });
79
114
 
80
115
  describe("Config System - Boolean Transformations", () => {
@@ -169,6 +204,27 @@ describe("Config System - Resolution Functions", () => {
169
204
 
170
205
  assert.equal(resolved.adapter, "express");
171
206
  });
207
+
208
+ it("should resolve fastify adapter", () => {
209
+ const config = configSchema.parse({
210
+ experimental: {
211
+ adapter: "fastify",
212
+ },
213
+ });
214
+ const resolved = getResolvedExperimentalConfig(config);
215
+
216
+ assert.equal(resolved.adapter, "fastify");
217
+ });
218
+
219
+ it("should reject unknown adapter values", () => {
220
+ assert.throws(() => {
221
+ configSchema.parse({
222
+ experimental: {
223
+ adapter: "unknown-framework",
224
+ },
225
+ });
226
+ });
227
+ });
172
228
  });
173
229
 
174
230
  describe("Config System - Injection Functions", () => {
@@ -3,7 +3,12 @@ import { z } from "zod/v3";
3
3
  // ------------------------------------------------------------
4
4
  // Adapter config schema (perhaps a separate file but it's small yet)
5
5
  // ------------------------------------------------------------
6
- export const adapterConfigSchema = z.enum(["express", "nextjs", "nestjs"]);
6
+ export const adapterConfigSchema = z.enum([
7
+ "express",
8
+ "nextjs",
9
+ "nestjs",
10
+ "fastify",
11
+ ]);
7
12
 
8
13
  export type AdapterConfig = z.infer<typeof adapterConfigSchema>;
9
14
 
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod/v3";
2
+ import { CLIENT_INFO_HEADER_NAMES } from "@/types/client-info";
2
3
 
3
4
  // ------------------------------------------------------------
4
5
  // Cors config schema
@@ -14,6 +15,7 @@ const corsConfigBaseSchema = z.object({
14
15
  "Authorization",
15
16
  "mcp-session-id",
16
17
  "mcp-protocol-version",
18
+ ...CLIENT_INFO_HEADER_NAMES,
17
19
  ]),
18
20
  exposedHeaders: z
19
21
  .union([z.string(), z.array(z.string())])
@@ -40,6 +42,9 @@ export const corsConfigSchema = corsConfigBaseSchema
40
42
  const headers = new Set(result.allowedHeaders);
41
43
  headers.add("mcp-session-id");
42
44
  headers.add("mcp-protocol-version");
45
+ for (const clientInfoHeaderName of CLIENT_INFO_HEADER_NAMES) {
46
+ headers.add(clientInfoHeaderName);
47
+ }
43
48
  result.allowedHeaders = Array.from(headers);
44
49
  }
45
50
  if (Array.isArray(result.exposedHeaders)) {
@@ -36,6 +36,9 @@ export function getEntries(
36
36
  if (xmcpConfig.experimental?.adapter === "nestjs") {
37
37
  entries["adapter"] = path.join(runtimeFolderPath, "adapter-nestjs.js");
38
38
  }
39
+ if (xmcpConfig.experimental?.adapter === "fastify") {
40
+ entries["adapter"] = path.join(runtimeFolderPath, "adapter-fastify.js");
41
+ }
39
42
  }
40
43
  return entries;
41
44
  }
@@ -74,6 +74,16 @@ export function getExternals(): RspackOptions["externals"] {
74
74
  return callback(undefined, `commonjs ${pathRequest}`);
75
75
  }
76
76
 
77
+ /**
78
+ * When using Fastify, externalize fastify since it should come from
79
+ * the user's node_modules
80
+ */
81
+ if (xmcpConfig.experimental?.adapter === "fastify") {
82
+ if (request === "fastify" || request.startsWith("fastify/")) {
83
+ return callback(undefined, `commonjs ${request}`);
84
+ }
85
+ }
86
+
77
87
  /**
78
88
  * When using NestJS, externalize NestJS-related packages
79
89
  * since they should come from the user's node_modules
@@ -6,6 +6,7 @@ import { XmcpConfigOutputSchema } from "@/compiler/config";
6
6
  import { getXmcpConfig } from "@/compiler/compiler-context";
7
7
  import {
8
8
  expressTypeDefinition,
9
+ fastifyTypeDefinition,
9
10
  nestJsTypeDefinition,
10
11
  nextJsTypeDefinition,
11
12
  } from "./types";
@@ -70,6 +71,8 @@ function getNeededRuntimeFiles(xmcpConfig: XmcpConfigOutputSchema): string[] {
70
71
  neededFiles.push("adapter-nextjs.js");
71
72
  } else if (xmcpConfig.experimental?.adapter === "nestjs") {
72
73
  neededFiles.push("adapter-nestjs.js");
74
+ } else if (xmcpConfig.experimental?.adapter === "fastify") {
75
+ neededFiles.push("adapter-fastify.js");
73
76
  } else {
74
77
  neededFiles.push("http.js");
75
78
  }
@@ -117,12 +120,14 @@ export class CreateTypeDefinitionPlugin {
117
120
  // Manually type the .xmcp/adapter/index.js file using a .xmcp/adapter/index.d.ts file
118
121
  if (xmcpConfig.experimental?.adapter) {
119
122
  let typeDefinitionContent = "";
120
- if (xmcpConfig.experimental?.adapter == "nextjs") {
123
+ if (xmcpConfig.experimental?.adapter === "nextjs") {
121
124
  typeDefinitionContent = nextJsTypeDefinition;
122
- } else if (xmcpConfig.experimental?.adapter == "express") {
125
+ } else if (xmcpConfig.experimental?.adapter === "express") {
123
126
  typeDefinitionContent = expressTypeDefinition;
124
- } else if (xmcpConfig.experimental?.adapter == "nestjs") {
127
+ } else if (xmcpConfig.experimental?.adapter === "nestjs") {
125
128
  typeDefinitionContent = nestJsTypeDefinition;
129
+ } else if (xmcpConfig.experimental?.adapter === "fastify") {
130
+ typeDefinitionContent = fastifyTypeDefinition;
126
131
  }
127
132
  fs.writeFileSync(
128
133
  path.join(adapterOutputPath, "index.d.ts"),
@@ -0,0 +1,4 @@
1
+ export const fastifyTypeDefinition = `
2
+ import type { FastifyRequest, FastifyReply } from 'fastify';
3
+ export declare function xmcpHandler(request: FastifyRequest, reply: FastifyReply): Promise<void>;
4
+ `;
@@ -2,3 +2,4 @@
2
2
  export { nextJsTypeDefinition } from "./next";
3
3
  export { expressTypeDefinition } from "./express";
4
4
  export { nestJsTypeDefinition } from "./nest";
5
+ export { fastifyTypeDefinition } from "./fastify";
@@ -0,0 +1,115 @@
1
+ import { describe, it, before } from "node:test";
2
+ import assert from "node:assert";
3
+ import Fastify from "fastify";
4
+
5
+ // All DefinePlugin globals must be set before the adapter and server modules are
6
+ // loaded. HTTP_CONFIG and HTTP_CORS_CONFIG are captured at module evaluation
7
+ // time inside the adapter; INJECTED_* and SERVER_INFO are captured in
8
+ // utils/server.ts. The modules are loaded via dynamic import() inside before(),
9
+ // which runs after this synchronous initialisation.
10
+ const g = globalThis as Record<string, unknown>;
11
+ g["HTTP_CONFIG"] = {
12
+ port: 3001,
13
+ host: "127.0.0.1",
14
+ bodySizeLimit: 10 * 1024 * 1024,
15
+ endpoint: "/mcp",
16
+ debug: false,
17
+ };
18
+ g["HTTP_CORS_CONFIG"] = {
19
+ origin: "*",
20
+ methods: ["GET", "POST"],
21
+ credentials: false,
22
+ maxAge: 86400,
23
+ };
24
+ g["INJECTED_TOOLS"] = {};
25
+ g["INJECTED_PROMPTS"] = {};
26
+ g["INJECTED_RESOURCES"] = {};
27
+ g["SERVER_INFO"] = { name: "test-server", version: "0.0.0" };
28
+
29
+ const HEADERS = {
30
+ "content-type": "application/json",
31
+ accept: "text/event-stream, application/json",
32
+ };
33
+
34
+ describe("Fastify adapter", () => {
35
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
36
+ let xmcpHandler!: (req: any, reply: any) => Promise<void>;
37
+ let injectedTools!: Record<string, () => Promise<unknown>>;
38
+
39
+ before(async () => {
40
+ // Dynamically import AFTER globals are set so module-level initialisers see
41
+ // the correct values.
42
+ ({ xmcpHandler } = (await import("../index")) as {
43
+ xmcpHandler: typeof xmcpHandler;
44
+ });
45
+ ({ injectedTools } = (await import("../../../utils/server")) as {
46
+ injectedTools: Record<string, () => Promise<unknown>>;
47
+ });
48
+ });
49
+
50
+ it("handles an initialize request successfully", async () => {
51
+ const app = Fastify();
52
+ app.post("/mcp", xmcpHandler);
53
+
54
+ const response = await app.inject({
55
+ method: "POST",
56
+ url: "/mcp",
57
+ headers: HEADERS,
58
+ payload: {
59
+ jsonrpc: "2.0",
60
+ id: 1,
61
+ method: "initialize",
62
+ params: {
63
+ protocolVersion: "2025-03-26",
64
+ capabilities: {},
65
+ clientInfo: { name: "test", version: "1.0.0" },
66
+ },
67
+ },
68
+ });
69
+
70
+ assert.strictEqual(response.statusCode, 200);
71
+ assert.ok(
72
+ response.body.includes('"serverInfo"'),
73
+ 'response body must contain "serverInfo"'
74
+ );
75
+ assert.ok(
76
+ response.body.includes("test-server"),
77
+ "response body must contain the server name"
78
+ );
79
+ });
80
+
81
+ it("writes a 500 JSON-RPC error to reply.raw when createServer throws", async () => {
82
+ // Inject a broken loader into the live injectedTools object so that the next
83
+ // loadToolModules() call rejects, propagating up through createServer() and
84
+ // into the catch block inside xmcpHandler. This works because injectedTools
85
+ // is the same object reference that was captured from INJECTED_TOOLS above —
86
+ // adding a key here is visible to loadTools() on the next invocation.
87
+ injectedTools["__test_error__"] = async () => {
88
+ throw new Error("forced load failure");
89
+ };
90
+
91
+ try {
92
+ const app = Fastify();
93
+ app.post("/mcp", xmcpHandler);
94
+
95
+ const response = await app.inject({
96
+ method: "POST",
97
+ url: "/mcp",
98
+ headers: HEADERS,
99
+ payload: { jsonrpc: "2.0", id: 1, method: "tools/list" },
100
+ });
101
+
102
+ // After reply.hijack() the catch block writes directly to reply.raw.
103
+ assert.strictEqual(response.statusCode, 500);
104
+ const body = JSON.parse(response.body) as {
105
+ jsonrpc: string;
106
+ error: { code: number; message: string };
107
+ id: unknown;
108
+ };
109
+ assert.strictEqual(body.jsonrpc, "2.0");
110
+ assert.strictEqual(body.error.code, -32603);
111
+ } finally {
112
+ delete injectedTools["__test_error__"];
113
+ }
114
+ });
115
+ });
@@ -0,0 +1,78 @@
1
+ import type { FastifyRequest, FastifyReply } from "fastify";
2
+ import { createServer } from "@/runtime/utils/server";
3
+ import { StatelessHttpServerTransport } from "@/runtime/transports/http/stateless-streamable-http";
4
+ import { setHeaders } from "@/runtime/transports/http/cors";
5
+ import { httpRequestContextProvider } from "@/runtime/contexts/http-request-context";
6
+ import { randomUUID } from "node:crypto";
7
+ import { extractClientInfoFromMessages } from "@/runtime/utils/client-info";
8
+ import type { CorsConfig } from "@/compiler/config";
9
+
10
+ const httpConfig = HTTP_CONFIG as {
11
+ port: number;
12
+ host: string;
13
+ bodySizeLimit: number;
14
+ endpoint: string;
15
+ debug: boolean;
16
+ };
17
+ const corsConfig = HTTP_CORS_CONFIG as CorsConfig;
18
+
19
+ export async function xmcpHandler(
20
+ request: FastifyRequest,
21
+ reply: FastifyReply
22
+ ): Promise<void> {
23
+ return new Promise<void>((resolve) => {
24
+ const id = randomUUID();
25
+ const clientInfo = extractClientInfoFromMessages(request.body);
26
+
27
+ httpRequestContextProvider(
28
+ { id, headers: request.headers, clientInfo },
29
+ async () => {
30
+ try {
31
+ // Claim the raw stream before any await so Fastify never attempts its
32
+ // own finalisation after the transport has already written to reply.raw.
33
+ // This MUST remain the first statement in the try block — after hijack,
34
+ // any throw is caught here and written directly to reply.raw, with no
35
+ // risk of Fastify also sending a response.
36
+ reply.hijack();
37
+
38
+ setHeaders(reply.raw, corsConfig, request.headers.origin);
39
+
40
+ const server = await createServer();
41
+ const transport = new StatelessHttpServerTransport(
42
+ httpConfig.debug,
43
+ httpConfig.bodySizeLimit.toString()
44
+ );
45
+
46
+ // Release transport + server when the connection closes (normal
47
+ // completion or client abort). Without this, warm containers leak
48
+ // instances per request.
49
+ reply.raw.on("close", () => {
50
+ transport.close();
51
+ server.close();
52
+ });
53
+
54
+ await server.connect(transport);
55
+
56
+ // The transport writes directly to reply.raw via Node's ServerResponse
57
+ // API. request.raw has already had its body consumed by Fastify, so
58
+ // we pass request.body as parsedBody rather than re-reading the stream.
59
+ await transport.handleRequest(request.raw, reply.raw, request.body);
60
+ resolve();
61
+ } catch (error) {
62
+ console.error("[HTTP-server] Error handling MCP request:", error);
63
+ if (!reply.raw.headersSent) {
64
+ reply.raw.writeHead(500, { "content-type": "application/json" });
65
+ reply.raw.end(
66
+ JSON.stringify({
67
+ jsonrpc: "2.0",
68
+ error: { code: -32603, message: "Internal server error" },
69
+ id: null,
70
+ })
71
+ );
72
+ }
73
+ resolve();
74
+ }
75
+ }
76
+ );
77
+ });
78
+ }
@@ -1,12 +1,14 @@
1
1
  import { CorsConfig } from "@/compiler/config";
2
+ import { ServerResponse } from "http";
2
3
  import { Request, Response, NextFunction, RequestHandler } from "express";
3
4
  import { buildCorsHeaders } from "./headers";
4
5
 
5
6
  /**
6
- * Sets CORS headers on the response based on the provided configuration
7
+ * Sets CORS headers on the response based on the provided configuration.
8
+ * Accepts any Node ServerResponse (or Express Response, which extends it).
7
9
  */
8
10
  export function setHeaders(
9
- res: Response,
11
+ res: ServerResponse,
10
12
  config: CorsConfig,
11
13
  origin?: string
12
14
  ): void {
@@ -1,6 +1,7 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert";
3
3
  import {
4
+ extractClientInfoFromHeaders,
4
5
  extractClientInfoFromMessage,
5
6
  extractClientInfoFromMessages,
6
7
  mapImplementationToClientInfo,
@@ -97,3 +98,49 @@ test("mapImplementationToClientInfo maps SDK implementation shape", () => {
97
98
  description: "CLI coding agent",
98
99
  });
99
100
  });
101
+
102
+ test("extractClientInfoFromHeaders extracts required and optional fields", () => {
103
+ const result = extractClientInfoFromHeaders({
104
+ "x-mcp-client-name": "cursor",
105
+ "x-mcp-client-version": "0.50.1",
106
+ "x-mcp-client-title": "Cursor",
107
+ "x-mcp-client-website-url": "https://cursor.com",
108
+ "x-mcp-client-description": "AI code editor",
109
+ });
110
+
111
+ assert.deepStrictEqual(result, {
112
+ name: "cursor",
113
+ version: "0.50.1",
114
+ title: "Cursor",
115
+ websiteUrl: "https://cursor.com",
116
+ description: "AI code editor",
117
+ });
118
+ });
119
+
120
+ test("extractClientInfoFromHeaders handles case-insensitive header names", () => {
121
+ const result = extractClientInfoFromHeaders({
122
+ "X-MCP-Client-Name": "claude-code",
123
+ "X-MCP-Client-Version": "2.1.0",
124
+ });
125
+
126
+ assert.deepStrictEqual(result, {
127
+ name: "claude-code",
128
+ version: "2.1.0",
129
+ });
130
+ });
131
+
132
+ test("extractClientInfoFromHeaders returns undefined without name and version", () => {
133
+ assert.strictEqual(
134
+ extractClientInfoFromHeaders({
135
+ "x-mcp-client-name": "cursor",
136
+ }),
137
+ undefined
138
+ );
139
+
140
+ assert.strictEqual(
141
+ extractClientInfoFromHeaders({
142
+ "x-mcp-client-version": "0.50.1",
143
+ }),
144
+ undefined
145
+ );
146
+ });
@@ -75,7 +75,97 @@ test("transformToolHandler forwards clientInfo through tool extra arguments", as
75
75
  });
76
76
  });
77
77
 
78
- test("transformToolHandler leaves clientInfo undefined when request has no initialize metadata", async () => {
78
+ test("transformToolHandler prefers initialize clientInfo over request headers", async () => {
79
+ const transformedHandler = transformToolHandler((_args, extra) => {
80
+ return {
81
+ structuredContent: {
82
+ clientInfoName: extra.clientInfo?.name,
83
+ clientInfoVersion: extra.clientInfo?.version,
84
+ },
85
+ };
86
+ });
87
+
88
+ const result = await new Promise<UserToolResponse>((resolve, reject) => {
89
+ httpRequestContextProvider(
90
+ {
91
+ id: "request-id-headers-precedence",
92
+ headers: {
93
+ "x-mcp-client-name": "header-client",
94
+ "x-mcp-client-version": "9.9.9",
95
+ },
96
+ clientInfo: {
97
+ name: "initialize-client",
98
+ version: "1.0.0",
99
+ },
100
+ },
101
+ () => {
102
+ invokeHandler(transformedHandler, "rpc-headers-precedence")
103
+ .then(resolve)
104
+ .catch(reject);
105
+ }
106
+ );
107
+ });
108
+
109
+ assert.deepStrictEqual(result, {
110
+ structuredContent: {
111
+ clientInfoName: "initialize-client",
112
+ clientInfoVersion: "1.0.0",
113
+ },
114
+ content: [
115
+ {
116
+ type: "text",
117
+ text: '{"clientInfoName":"initialize-client","clientInfoVersion":"1.0.0"}',
118
+ },
119
+ ],
120
+ });
121
+ });
122
+
123
+ test("transformToolHandler uses request headers as HTTP clientInfo fallback", async () => {
124
+ const transformedHandler = transformToolHandler((_args, extra) => {
125
+ return {
126
+ structuredContent: {
127
+ clientInfoName: extra.clientInfo?.name,
128
+ clientInfoVersion: extra.clientInfo?.version,
129
+ clientInfoTitle: extra.clientInfo?.title,
130
+ },
131
+ };
132
+ });
133
+
134
+ const result = await new Promise<UserToolResponse>((resolve, reject) => {
135
+ httpRequestContextProvider(
136
+ {
137
+ id: "request-id-headers",
138
+ headers: {
139
+ "X-MCP-Client-Name": "cursor",
140
+ "X-MCP-Client-Version": "0.50.1",
141
+ "X-MCP-Client-Title": "Cursor",
142
+ },
143
+ clientInfo: undefined,
144
+ },
145
+ () => {
146
+ invokeHandler(transformedHandler, "rpc-headers")
147
+ .then(resolve)
148
+ .catch(reject);
149
+ }
150
+ );
151
+ });
152
+
153
+ assert.deepStrictEqual(result, {
154
+ structuredContent: {
155
+ clientInfoName: "cursor",
156
+ clientInfoVersion: "0.50.1",
157
+ clientInfoTitle: "Cursor",
158
+ },
159
+ content: [
160
+ {
161
+ type: "text",
162
+ text: '{"clientInfoName":"cursor","clientInfoVersion":"0.50.1","clientInfoTitle":"Cursor"}',
163
+ },
164
+ ],
165
+ });
166
+ });
167
+
168
+ test("transformToolHandler leaves clientInfo undefined when request has no client metadata", async () => {
79
169
  const transformedHandler = transformToolHandler((_args, extra) => {
80
170
  return {
81
171
  structuredContent: {
@@ -1,4 +1,5 @@
1
1
  import type { JsonRpcMessage } from "@/runtime/transports/http/base-streamable-http";
2
+ import type { HttpHeaders } from "@/runtime/contexts/http-request-context";
2
3
  import type { McpClientInfo } from "@/types/client-info";
3
4
  import type { Implementation } from "@modelcontextprotocol/sdk/types";
4
5
 
@@ -76,3 +77,38 @@ export const extractClientInfoFromMessages = (
76
77
 
77
78
  return undefined;
78
79
  };
80
+
81
+ const getHeaderValue = (
82
+ headers: HttpHeaders,
83
+ headerName: string
84
+ ): string | undefined => {
85
+ const normalizedHeaderName = headerName.toLowerCase();
86
+
87
+ for (const [key, value] of Object.entries(headers)) {
88
+ if (key.toLowerCase() !== normalizedHeaderName) {
89
+ continue;
90
+ }
91
+
92
+ const headerValue = Array.isArray(value) ? value[0] : value;
93
+ if (typeof headerValue !== "string") {
94
+ return undefined;
95
+ }
96
+
97
+ const trimmedValue = headerValue.trim();
98
+ return trimmedValue.length > 0 ? trimmedValue : undefined;
99
+ }
100
+
101
+ return undefined;
102
+ };
103
+
104
+ export const extractClientInfoFromHeaders = (
105
+ headers: HttpHeaders
106
+ ): McpClientInfo | undefined => {
107
+ return parseClientInfoCandidate({
108
+ name: getHeaderValue(headers, "x-mcp-client-name"),
109
+ version: getHeaderValue(headers, "x-mcp-client-version"),
110
+ title: getHeaderValue(headers, "x-mcp-client-title"),
111
+ websiteUrl: getHeaderValue(headers, "x-mcp-client-website-url"),
112
+ description: getHeaderValue(headers, "x-mcp-client-description"),
113
+ });
114
+ };
@@ -8,6 +8,7 @@ import { ZodRawShape } from "zod/v3";
8
8
  import type { ToolExtraArguments } from "@/types/tool";
9
9
  import { getHttpRequestContext } from "@/runtime/contexts/http-request-context";
10
10
  import { getClientInfoContext } from "@/runtime/contexts/client-info-context";
11
+ import { extractClientInfoFromHeaders } from "@/runtime/utils/client-info";
11
12
  import { elicitFromTool } from "../elicitation";
12
13
  import { validateContent } from "../validators";
13
14
 
@@ -78,7 +79,10 @@ function createToolExtraArguments(
78
79
  let clientInfo = undefined;
79
80
 
80
81
  try {
81
- clientInfo = getHttpRequestContext().clientInfo;
82
+ const httpRequestContext = getHttpRequestContext();
83
+ clientInfo =
84
+ httpRequestContext.clientInfo ??
85
+ extractClientInfoFromHeaders(httpRequestContext.headers);
82
86
  } catch {
83
87
  // no HTTP request context available (for example, stdio transport)
84
88
  }
@@ -23,6 +23,8 @@ export enum AdapterType {
23
23
  NONE = "none",
24
24
  EXPRESS = "express",
25
25
  NEXTJS = "nextjs",
26
+ NESTJS = "nestjs",
27
+ FASTIFY = "fastify",
26
28
  }
27
29
 
28
30
  type EventPayload = {