xmcp 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/dist/cli.js +1 -1
  2. package/dist/index.js +1 -1
  3. package/package.json +2 -3
  4. package/src/auth/api-key.ts +0 -120
  5. package/src/auth/jwt.ts +0 -52
  6. package/src/cli/commands/create/__tests__/create.test.ts +0 -99
  7. package/src/cli/commands/create/index.ts +0 -74
  8. package/src/cli/commands/create/templates/index.ts +0 -4
  9. package/src/cli/commands/create/templates/prompt.ts +0 -30
  10. package/src/cli/commands/create/templates/resource.ts +0 -20
  11. package/src/cli/commands/create/templates/tool.ts +0 -34
  12. package/src/cli/commands/create/templates/widget.ts +0 -33
  13. package/src/cli/utils/naming.ts +0 -39
  14. package/src/cli.ts +0 -125
  15. package/src/client/headers.ts +0 -61
  16. package/src/client/index.ts +0 -180
  17. package/src/client/types.ts +0 -122
  18. package/src/client/utils.ts +0 -133
  19. package/src/cloudflare.ts +0 -6
  20. package/src/compiler/build-telemetry.ts +0 -88
  21. package/src/compiler/client/component-compiler.ts +0 -250
  22. package/src/compiler/client/transpile.ts +0 -21
  23. package/src/compiler/compiler-context.ts +0 -61
  24. package/src/compiler/config/__tests__/config.test.ts +0 -459
  25. package/src/compiler/config/index.ts +0 -62
  26. package/src/compiler/config/injection.ts +0 -210
  27. package/src/compiler/config/schemas/bundler.ts +0 -12
  28. package/src/compiler/config/schemas/experimental/index.ts +0 -22
  29. package/src/compiler/config/schemas/index.ts +0 -20
  30. package/src/compiler/config/schemas/paths.ts +0 -35
  31. package/src/compiler/config/schemas/template.ts +0 -80
  32. package/src/compiler/config/schemas/transport/http.ts +0 -116
  33. package/src/compiler/config/schemas/transport/stdio.ts +0 -31
  34. package/src/compiler/config/schemas/typescript.ts +0 -26
  35. package/src/compiler/config/utils.ts +0 -168
  36. package/src/compiler/generate-env-code.ts +0 -5
  37. package/src/compiler/generate-import-code.ts +0 -187
  38. package/src/compiler/generate-tools-code.ts +0 -174
  39. package/src/compiler/get-bundler-config/get-entries.ts +0 -44
  40. package/src/compiler/get-bundler-config/get-externals.ts +0 -114
  41. package/src/compiler/get-bundler-config/get-injected-variables.ts +0 -46
  42. package/src/compiler/get-bundler-config/index.ts +0 -288
  43. package/src/compiler/get-bundler-config/plugins/index.ts +0 -140
  44. package/src/compiler/get-bundler-config/plugins/types/express.ts +0 -3
  45. package/src/compiler/get-bundler-config/plugins/types/fastify.ts +0 -4
  46. package/src/compiler/get-bundler-config/plugins/types/index.ts +0 -5
  47. package/src/compiler/get-bundler-config/plugins/types/nest.ts +0 -65
  48. package/src/compiler/get-bundler-config/plugins/types/next.ts +0 -52
  49. package/src/compiler/get-bundler-config/resolve-tsconfig-paths.ts +0 -51
  50. package/src/compiler/index.ts +0 -484
  51. package/src/compiler/on-first-build.ts +0 -54
  52. package/src/compiler/parse-xmcp-config.ts +0 -200
  53. package/src/compiler/start-http-server.ts +0 -42
  54. package/src/compiler/utils/__tests__/config-detection.test.ts +0 -307
  55. package/src/compiler/utils/__tests__/path-utils.test.ts +0 -137
  56. package/src/compiler/utils/config-detection.ts +0 -34
  57. package/src/compiler/utils/path-utils.ts +0 -22
  58. package/src/compiler/watcher-recovery.ts +0 -72
  59. package/src/host-bridge.ts +0 -36
  60. package/src/index.ts +0 -94
  61. package/src/platforms/build-cloudflare-output.ts +0 -116
  62. package/src/platforms/build-vercel-output.ts +0 -131
  63. package/src/plugins/index.ts +0 -1
  64. package/src/plugins/x402/index.ts +0 -24
  65. package/src/runtime/adapters/express/index.ts +0 -75
  66. package/src/runtime/adapters/fastify/__tests__/fastify.test.ts +0 -115
  67. package/src/runtime/adapters/fastify/index.ts +0 -78
  68. package/src/runtime/adapters/nestjs/index.ts +0 -16
  69. package/src/runtime/adapters/nestjs/xmcp.controller.ts +0 -34
  70. package/src/runtime/adapters/nestjs/xmcp.guard.ts +0 -101
  71. package/src/runtime/adapters/nestjs/xmcp.oauth.controller.ts +0 -36
  72. package/src/runtime/adapters/nestjs/xmcp.oauth.module.ts +0 -21
  73. package/src/runtime/adapters/nestjs/xmcp.oauth.service.ts +0 -36
  74. package/src/runtime/adapters/nestjs/xmcp.service.ts +0 -96
  75. package/src/runtime/adapters/nestjs/xmcp.utils.ts +0 -11
  76. package/src/runtime/adapters/nextjs/auth.ts +0 -265
  77. package/src/runtime/adapters/nextjs/handler/error-handler.ts +0 -67
  78. package/src/runtime/adapters/nextjs/handler/node-to-web-adapter.ts +0 -143
  79. package/src/runtime/adapters/nextjs/handler/request-converter.ts +0 -74
  80. package/src/runtime/adapters/nextjs/handler/server-lifecycle.ts +0 -69
  81. package/src/runtime/adapters/nextjs/index.ts +0 -121
  82. package/src/runtime/contexts/client-info-context.ts +0 -16
  83. package/src/runtime/contexts/http-request-context.ts +0 -21
  84. package/src/runtime/contexts/http-transport-context.ts +0 -18
  85. package/src/runtime/headers.ts +0 -42
  86. package/src/runtime/middlewares/utils.ts +0 -72
  87. package/src/runtime/platforms/cloudflare/cors.ts +0 -44
  88. package/src/runtime/platforms/cloudflare/middlewares/api-key.ts +0 -102
  89. package/src/runtime/platforms/cloudflare/middlewares/jwt.ts +0 -127
  90. package/src/runtime/platforms/cloudflare/types.ts +0 -23
  91. package/src/runtime/platforms/cloudflare/worker.ts +0 -270
  92. package/src/runtime/templates/home.ts +0 -746
  93. package/src/runtime/transports/http/base-streamable-http.ts +0 -46
  94. package/src/runtime/transports/http/cors/headers.ts +0 -58
  95. package/src/runtime/transports/http/cors/index.ts +0 -34
  96. package/src/runtime/transports/http/index.ts +0 -78
  97. package/src/runtime/transports/http/stateless-streamable-http.ts +0 -353
  98. package/src/runtime/transports/http/web-stateless-http.ts +0 -288
  99. package/src/runtime/transports/stdio/index.ts +0 -109
  100. package/src/runtime/utils/__tests__/client-info.test.ts +0 -146
  101. package/src/runtime/utils/__tests__/tool-extra.test.ts +0 -239
  102. package/src/runtime/utils/client-info.ts +0 -114
  103. package/src/runtime/utils/elicitation.ts +0 -396
  104. package/src/runtime/utils/ext-apps-registry.ts +0 -151
  105. package/src/runtime/utils/mcp-app-protocol.ts +0 -16
  106. package/src/runtime/utils/mcp-app-types.ts +0 -113
  107. package/src/runtime/utils/mcp-host-bridge.ts +0 -473
  108. package/src/runtime/utils/path-to-tool-name.ts +0 -69
  109. package/src/runtime/utils/prompt-loader.ts +0 -151
  110. package/src/runtime/utils/prompts.ts +0 -69
  111. package/src/runtime/utils/react/generate-html.ts +0 -69
  112. package/src/runtime/utils/react/index.ts +0 -6
  113. package/src/runtime/utils/request-tool-names.ts +0 -48
  114. package/src/runtime/utils/resource-loader.ts +0 -151
  115. package/src/runtime/utils/resources.ts +0 -331
  116. package/src/runtime/utils/server.ts +0 -107
  117. package/src/runtime/utils/tool-loader.ts +0 -149
  118. package/src/runtime/utils/tools.ts +0 -183
  119. package/src/runtime/utils/transformers/prompt.ts +0 -120
  120. package/src/runtime/utils/transformers/resource.ts +0 -196
  121. package/src/runtime/utils/transformers/tool.ts +0 -400
  122. package/src/runtime/utils/ui/__tests__/split-meta.test.ts +0 -803
  123. package/src/runtime/utils/ui/flatten-meta.ts +0 -44
  124. package/src/runtime/utils/ui/split-meta.ts +0 -78
  125. package/src/runtime/utils/utils/resource-uri-composer.ts +0 -204
  126. package/src/runtime/utils/validators/index.ts +0 -138
  127. package/src/telemetry/ci-info.ts +0 -6
  128. package/src/telemetry/debug.ts +0 -8
  129. package/src/telemetry/events/definitions.ts +0 -52
  130. package/src/telemetry/events/detached-flush.ts +0 -83
  131. package/src/telemetry/events/post-payload.ts +0 -141
  132. package/src/telemetry/events/tracker.ts +0 -281
  133. package/src/telemetry/index.ts +0 -7
  134. package/src/telemetry/metadata.ts +0 -49
  135. package/src/telemetry/project-id.ts +0 -35
  136. package/src/telemetry/storage.ts +0 -218
  137. package/src/types/adapter.d.ts +0 -5
  138. package/src/types/client-info.ts +0 -20
  139. package/src/types/declarations.ts +0 -37
  140. package/src/types/injected.d.ts +0 -62
  141. package/src/types/middleware.ts +0 -19
  142. package/src/types/prompt.ts +0 -6
  143. package/src/types/resource.ts +0 -15
  144. package/src/types/tool.ts +0 -192
  145. package/src/types/ui-meta.ts +0 -42
  146. package/src/utils/cli-icons.ts +0 -5
  147. package/src/utils/constants.ts +0 -31
  148. package/src/utils/context.ts +0 -105
  149. package/src/utils/detect-package-manager.ts +0 -46
  150. package/src/utils/file-watcher.ts +0 -66
  151. package/src/utils/fs-utils.ts +0 -16
  152. package/src/utils/path-validation.ts +0 -66
  153. package/src/utils/port-utils.ts +0 -43
  154. package/src/utils/spawn-process.ts +0 -49
  155. package/src/utils/subscribable.ts +0 -62
@@ -1,265 +0,0 @@
1
- import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types";
2
-
3
- /**
4
- * Standard OAuth Protected Resource Metadata path (RFC 9728)
5
- */
6
- const RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
7
-
8
- /**
9
- * OAuth error codes (MCP-specific)
10
- */
11
- const AUTH_ERROR_CODES = {
12
- INVALID_TOKEN: -32001,
13
- INSUFFICIENT_SCOPE: -32002,
14
- } as const;
15
-
16
- /**
17
- * CORS headers for OAuth Protected Resource Metadata endpoint.
18
- * Configured to allow any origin to make the endpoint accessible to web-based MCP clients.
19
- */
20
- const corsHeaders = {
21
- "Access-Control-Allow-Origin": "*",
22
- "Access-Control-Allow-Methods": "GET, OPTIONS",
23
- "Access-Control-Allow-Headers": "*",
24
- "Access-Control-Max-Age": "86400",
25
- };
26
-
27
- /**
28
- * OAuth Protected Resource Metadata interface (RFC 9728).
29
- */
30
- export interface OAuthProtectedResourceMetadata {
31
- resource: string;
32
- authorization_servers: string[];
33
- bearer_methods_supported?: string[];
34
- resource_documentation?: string;
35
- introspection_endpoint?: string;
36
- revocation_endpoint?: string;
37
- [key: string]: unknown;
38
- }
39
-
40
- // Types
41
- export type VerifyToken = (
42
- req: Request,
43
- bearerToken?: string
44
- ) => Promise<
45
- | {
46
- token: string;
47
- clientId: string;
48
- scopes: string[];
49
- expiresAt?: number;
50
- resource?: URL;
51
- extra?: Record<string, unknown>;
52
- }
53
- | undefined
54
- >;
55
-
56
- export type AuthConfig = {
57
- verifyToken: VerifyToken;
58
- required?: boolean;
59
- requiredScopes?: string[];
60
- };
61
-
62
- // Extend Request interface to include auth property
63
- declare global {
64
- interface Request {
65
- auth?: AuthInfo;
66
- }
67
- }
68
-
69
- /**
70
- * Extracts bearer token from Authorization header
71
- */
72
- function extractBearerToken(req: Request): string | undefined {
73
- const authHeader = req.headers.get("Authorization");
74
- const [type, token] = authHeader?.split(" ") || [];
75
- return type?.toLowerCase() === "bearer" ? token : undefined;
76
- }
77
-
78
- /**
79
- * Creates an OAuth authentication error response
80
- */
81
- function createAuthErrorResponse(
82
- req: Request,
83
- errorCode: string,
84
- errorDescription: string,
85
- httpStatus: number,
86
- rpcCode: number
87
- ): Response {
88
- const origin = new URL(req.url).origin;
89
- const resourceMetadataUrl = `${origin}${RESOURCE_METADATA_PATH}`;
90
-
91
- return new Response(
92
- JSON.stringify({
93
- jsonrpc: "2.0",
94
- error: {
95
- code: rpcCode,
96
- message: errorDescription,
97
- },
98
- id: null,
99
- }),
100
- {
101
- status: httpStatus,
102
- headers: {
103
- "WWW-Authenticate": `Bearer error="${errorCode}", error_description="${errorDescription}", resource_metadata="${resourceMetadataUrl}"`,
104
- "Content-Type": "application/json",
105
- },
106
- }
107
- );
108
- }
109
-
110
- /**
111
- * Validates that token has not expired
112
- */
113
- function isTokenExpired(authInfo: AuthInfo): boolean {
114
- return (
115
- authInfo.expiresAt !== undefined && authInfo.expiresAt < Date.now() / 1000
116
- );
117
- }
118
-
119
- /**
120
- * Validates that token has all required scopes
121
- */
122
- function hasRequiredScopes(
123
- authInfo: AuthInfo,
124
- requiredScopes: string[]
125
- ): boolean {
126
- return requiredScopes.every((scope) => authInfo.scopes.includes(scope));
127
- }
128
-
129
- /**
130
- * Wraps an MCP handler with OAuth 2.0 Bearer token authentication.
131
- * Extracts the bearer token from the Authorization header, verifies it,
132
- * and sets it on the request object for use by the handler.
133
- */
134
- export function withAuth(
135
- handler: (request: Request) => Promise<Response>,
136
- config: AuthConfig
137
- ): (request: Request) => Promise<Response> {
138
- return async (req: Request) => {
139
- const { verifyToken, required = false, requiredScopes } = config;
140
-
141
- // Extract bearer token
142
- const bearerToken = extractBearerToken(req);
143
-
144
- // Verify token
145
- let authInfo: AuthInfo | undefined;
146
- try {
147
- authInfo = await verifyToken(req, bearerToken);
148
- } catch (error) {
149
- console.error("[MCP Auth] Error verifying token:", error);
150
- return createAuthErrorResponse(
151
- req,
152
- "invalid_token",
153
- "Invalid token",
154
- 401,
155
- AUTH_ERROR_CODES.INVALID_TOKEN
156
- );
157
- }
158
-
159
- // Check if authentication is required but not provided
160
- if (required && !authInfo) {
161
- return createAuthErrorResponse(
162
- req,
163
- "invalid_token",
164
- "No authorization provided",
165
- 401,
166
- AUTH_ERROR_CODES.INVALID_TOKEN
167
- );
168
- }
169
-
170
- // If no auth info, proceed without it
171
- if (!authInfo) {
172
- return handler(req);
173
- }
174
-
175
- // Validate token expiration
176
- if (isTokenExpired(authInfo)) {
177
- return createAuthErrorResponse(
178
- req,
179
- "invalid_token",
180
- "Token has expired",
181
- 401,
182
- AUTH_ERROR_CODES.INVALID_TOKEN
183
- );
184
- }
185
-
186
- // Validate required scopes
187
- if (
188
- requiredScopes?.length &&
189
- !hasRequiredScopes(authInfo, requiredScopes)
190
- ) {
191
- return createAuthErrorResponse(
192
- req,
193
- "insufficient_scope",
194
- "Insufficient scope",
195
- 403,
196
- AUTH_ERROR_CODES.INSUFFICIENT_SCOPE
197
- );
198
- }
199
-
200
- // Set auth info on the request object
201
- req.auth = authInfo;
202
-
203
- // Call the handler with authenticated request
204
- return handler(req);
205
- };
206
- }
207
-
208
- /**
209
- * Extracts the base resource URL from a well-known endpoint request
210
- */
211
- function extractResourceUrl(req: Request): string {
212
- const resourceUrl = new URL(req.url);
213
-
214
- // Remove the well-known path to get the base resource URL
215
- resourceUrl.pathname = resourceUrl.pathname.replace(
216
- /^\/\.well-known\/[^\/]+/,
217
- ""
218
- );
219
-
220
- // The URL class replaces empty pathname with "/", so we correct that
221
- return resourceUrl.pathname === "/"
222
- ? resourceUrl.toString().replace(/\/$/, "")
223
- : resourceUrl.toString();
224
- }
225
-
226
- /**
227
- * OAuth 2.0 Protected Resource Metadata endpoint handler (RFC 9728).
228
- * Returns a handler that serves protected resource metadata at `/.well-known/oauth-protected-resource`.
229
- *
230
- * @param options - Configuration options
231
- * @param options.authorizationServers - Array of issuer URLs of the OAuth 2.0 Authorization Servers
232
- * @returns A handler function that can be exported as GET in Next.js route handlers
233
- */
234
- export function resourceMetadataHandler(options: {
235
- authorizationServers: string[];
236
- }): (req: Request) => Response {
237
- return (req: Request) => {
238
- const resource = extractResourceUrl(req);
239
- const metadata: OAuthProtectedResourceMetadata = {
240
- resource,
241
- authorization_servers: options.authorizationServers,
242
- };
243
-
244
- return new Response(JSON.stringify(metadata), {
245
- headers: {
246
- ...corsHeaders,
247
- "Cache-Control": "max-age=3600",
248
- "Content-Type": "application/json",
249
- },
250
- });
251
- };
252
- }
253
-
254
- /**
255
- * CORS OPTIONS request handler for OAuth metadata endpoints.
256
- * Necessary for MCP clients that operate in web browsers.
257
- *
258
- * @returns A handler function that can be exported as OPTIONS in Next.js route handlers
259
- */
260
- export function resourceMetadataOptions(req: Request): Response {
261
- return new Response(null, {
262
- status: 200,
263
- headers: corsHeaders,
264
- });
265
- }
@@ -1,67 +0,0 @@
1
- import type { ServerResponse } from "node:http";
2
-
3
- export interface JsonRpcError {
4
- jsonrpc: "2.0";
5
- error: {
6
- code: number;
7
- message: string;
8
- };
9
- id: null;
10
- }
11
-
12
- /**
13
- * Creates a JSON-RPC error response
14
- */
15
- export function createJsonRpcError(
16
- code: number,
17
- message: string
18
- ): JsonRpcError {
19
- return {
20
- jsonrpc: "2.0",
21
- error: { code, message },
22
- id: null,
23
- };
24
- }
25
-
26
- /**
27
- * Sends a JSON-RPC error response via ServerResponse
28
- */
29
- export function sendJsonRpcError(
30
- res: ServerResponse,
31
- code: number,
32
- message: string
33
- ): void {
34
- if (!res.headersSent) {
35
- const statusCode = code >= 400 && code < 600 ? code : 500;
36
- res.writeHead(statusCode, { "Content-Type": "application/json" });
37
- }
38
- res.end(JSON.stringify(createJsonRpcError(code, message)));
39
- }
40
-
41
- /**
42
- * Sends a JSON-RPC internal server error response
43
- */
44
- export function sendInternalServerError(res: ServerResponse): void {
45
- sendJsonRpcError(res, -32603, "Internal server error");
46
- }
47
-
48
- /**
49
- * Creates a Web Response with JSON-RPC error
50
- */
51
- export function createJsonRpcErrorResponse(
52
- code: number,
53
- message: string,
54
- status: number
55
- ): Response {
56
- return new Response(JSON.stringify(createJsonRpcError(code, message)), {
57
- status,
58
- headers: { "Content-Type": "application/json" },
59
- });
60
- }
61
-
62
- /**
63
- * Creates a method not allowed error response
64
- */
65
- export function createMethodNotAllowedResponse(): Response {
66
- return createJsonRpcErrorResponse(-32000, "Method not allowed.", 405);
67
- }
@@ -1,143 +0,0 @@
1
- import type { OutgoingHttpHeaders, ServerResponse } from "node:http";
2
- import { EventEmitter } from "node:events";
3
-
4
- /**
5
- * Node.js ServerResponse to Web Response API.
6
- *
7
- * The MCP transport only uses simple synchronous patterns:
8
- * - res.writeHead(code, headers).end(body)
9
- * - res.writeHead(code).end()
10
- * - res.on('close', ...) and res.on('finish', ...)
11
- *
12
- */
13
- export function nodeToWebAdapter(
14
- signal: AbortSignal,
15
- handler: (res: ServerResponse) => Promise<void> | void
16
- ): Promise<Response> {
17
- return new Promise((resolve) => {
18
- const emitter = new EventEmitter();
19
- let statusCode = 200;
20
- let headers: OutgoingHttpHeaders | undefined;
21
- const bodyChunks: Uint8Array[] = [];
22
- let headersWritten = false;
23
- let resolved = false;
24
- let destroyed = false;
25
-
26
- const appendBodyChunk = (chunk: Buffer | Uint8Array | string) => {
27
- if (typeof chunk === "string") {
28
- bodyChunks.push(Buffer.from(chunk));
29
- return;
30
- }
31
-
32
- bodyChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
33
- };
34
-
35
- // Setup abort signal handling
36
- signal.addEventListener("abort", () => {
37
- emitter.emit("close");
38
- });
39
-
40
- // Create mock response object - use arrow functions to properly capture `this`
41
- const mockResponse = {
42
- writeHead(
43
- code: number,
44
- statusMessageOrHeaders?: string | OutgoingHttpHeaders,
45
- headersArg?: OutgoingHttpHeaders
46
- ) {
47
- statusCode = code;
48
- if (typeof statusMessageOrHeaders === "string") {
49
- headers = headersArg;
50
- } else {
51
- headers = statusMessageOrHeaders;
52
- }
53
- headersWritten = true;
54
- return mockResponse;
55
- },
56
-
57
- write(chunk: Buffer | Uint8Array | string): boolean {
58
- if (!resolved) {
59
- appendBodyChunk(chunk);
60
- }
61
- return true;
62
- },
63
-
64
- end(data?: Buffer | Uint8Array | string) {
65
- if (resolved) {
66
- return mockResponse;
67
- }
68
-
69
- if (data) {
70
- appendBodyChunk(data);
71
- }
72
-
73
- // Ensure headers were written (default to 200 if not)
74
- if (!headersWritten) {
75
- statusCode = 200;
76
- headersWritten = true;
77
- }
78
-
79
- resolved = true;
80
-
81
- // Create Web Response
82
- resolve(
83
- new Response(Buffer.concat(bodyChunks), {
84
- status: statusCode,
85
- headers: headers as Record<string, string>,
86
- })
87
- );
88
-
89
- emitter.emit("finish");
90
- return mockResponse;
91
- },
92
-
93
- on(event: string, listener: (...args: unknown[]) => void) {
94
- emitter.on(event, listener);
95
- return mockResponse;
96
- },
97
-
98
- off(event: string, listener: (...args: unknown[]) => void) {
99
- emitter.off(event, listener);
100
- return mockResponse;
101
- },
102
-
103
- removeListener(event: string, listener: (...args: unknown[]) => void) {
104
- emitter.removeListener(event, listener);
105
- return mockResponse;
106
- },
107
-
108
- destroy(_error?: Error) {
109
- destroyed = true;
110
- emitter.emit("close");
111
- return mockResponse;
112
- },
113
-
114
- get statusCode(): number {
115
- return statusCode;
116
- },
117
-
118
- set statusCode(code: number) {
119
- statusCode = code;
120
- },
121
-
122
- get headersSent(): boolean {
123
- return headersWritten;
124
- },
125
-
126
- get destroyed(): boolean {
127
- return destroyed;
128
- },
129
-
130
- get writable(): boolean {
131
- return !destroyed;
132
- },
133
- } as ServerResponse;
134
-
135
- // Execute handler
136
- Promise.resolve(handler(mockResponse)).catch((error) => {
137
- console.error("Handler error:", error);
138
- if (!resolved) {
139
- resolve(new Response(JSON.stringify({ error: "Internal server error" }), { status: 500 }));
140
- }
141
- });
142
- });
143
- }
@@ -1,74 +0,0 @@
1
- import { type IncomingHttpHeaders, IncomingMessage } from "node:http";
2
- import { Socket } from "node:net";
3
- import { Readable } from "node:stream";
4
- import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types";
5
-
6
- export interface RequestConversionOptions {
7
- method: string;
8
- url: string;
9
- headers: IncomingHttpHeaders;
10
- auth?: AuthInfo;
11
- }
12
-
13
- function toRawHeaders(headers: IncomingHttpHeaders): string[] {
14
- const rawHeaders: string[] = [];
15
-
16
- for (const [key, value] of Object.entries(headers)) {
17
- if (value === undefined) continue;
18
-
19
- if (Array.isArray(value)) {
20
- for (const item of value) {
21
- rawHeaders.push(key, item);
22
- }
23
- continue;
24
- }
25
-
26
- rawHeaders.push(key, value);
27
- }
28
-
29
- return rawHeaders;
30
- }
31
-
32
- /**
33
- * Creates a Node.js IncomingMessage from Web Request options.
34
- * This adapter enables the MCP SDK to work with Web Request objects.
35
- *
36
- * Note: Since we always pass parsedBody to the transport, the stream body
37
- * is never read. The stream methods are only bound for interface compatibility.
38
- */
39
- export function createIncomingMessage(
40
- options: RequestConversionOptions
41
- ): IncomingMessage & { auth?: AuthInfo } {
42
- const { method, url, headers, auth } = options;
43
-
44
- // Create a minimal readable stream for interface compatibility
45
- // The stream is never actually read since we always provide parsedBody
46
- const readable = new Readable();
47
- readable._read = (): void => {};
48
- readable.push(null); // End stream immediately
49
-
50
- // Create IncomingMessage instance
51
- const req = new IncomingMessage(new Socket()) as IncomingMessage & {
52
- auth?: AuthInfo;
53
- };
54
-
55
- // Set request properties
56
- req.method = method;
57
- req.url = url;
58
- req.headers = headers;
59
- req.rawHeaders = toRawHeaders(headers);
60
-
61
- // Set auth if available (can be set by middleware)
62
- if (auth) {
63
- req.auth = auth;
64
- }
65
-
66
- // Bind stream methods for interface compatibility (not actually used)
67
- req.push = readable.push.bind(readable);
68
- req.read = readable.read.bind(readable);
69
- // @ts-expect-error - Required for MCP SDK compatibility
70
- req.on = readable.on.bind(readable);
71
- req.pipe = readable.pipe.bind(readable);
72
-
73
- return req;
74
- }
@@ -1,69 +0,0 @@
1
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp";
2
- import type { ServerResponse } from "node:http";
3
- import { StatelessHttpServerTransport } from "@/runtime/transports/http/stateless-streamable-http";
4
- import {
5
- configureServer,
6
- INJECTED_CONFIG,
7
- loadPrompts,
8
- loadResources,
9
- loadTools,
10
- } from "@/runtime/utils/server";
11
-
12
- export interface ServerLifecycle {
13
- server: McpServer;
14
- transport: StatelessHttpServerTransport;
15
- }
16
-
17
- /**
18
- * Sets up cleanup handlers for server and transport
19
- */
20
- export function setupCleanupHandlers(
21
- res: ServerResponse,
22
- lifecycle: ServerLifecycle
23
- ): void {
24
- const cleanup = () => {
25
- lifecycle.transport.close();
26
- lifecycle.server.close();
27
- };
28
-
29
- // Cleanup when request/connection closes
30
- res.on("close", cleanup);
31
-
32
- // Cleanup on finish
33
- res.on("finish", cleanup);
34
- }
35
-
36
- /**
37
- * Initializes and configures the MCP server with tools, prompts, and resources
38
- */
39
- export async function initializeMcpServer(): Promise<McpServer> {
40
- const toolModulesPromise = loadTools();
41
- const promptModulesPromise = loadPrompts();
42
- const resourceModulesPromise = loadResources();
43
- const [toolModules, promptModules, resourceModules] = await Promise.all([
44
- toolModulesPromise,
45
- promptModulesPromise,
46
- resourceModulesPromise,
47
- ]);
48
-
49
- const { instructions, ...serverInfo } = INJECTED_CONFIG;
50
- const server = new McpServer(serverInfo, { instructions });
51
-
52
- await configureServer(server, toolModules, promptModules, resourceModules);
53
-
54
- return server;
55
- }
56
-
57
- /**
58
- * Creates and connects server lifecycle components
59
- */
60
- export async function createServerLifecycle(
61
- bodySizeLimit: string = "10mb"
62
- ): Promise<ServerLifecycle> {
63
- const server = await initializeMcpServer();
64
- const transport = new StatelessHttpServerTransport(false, bodySizeLimit);
65
-
66
- await server.connect(transport);
67
-
68
- return { server, transport };
69
- }