xmcp 0.6.13 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +8 -8
- package/dist/index.js +2 -2
- package/dist/runtime/adapter-express.js +2 -2
- package/dist/runtime/adapter-fastify.js +2 -2
- package/dist/runtime/adapter-nestjs.js +7 -7
- package/dist/runtime/adapter-nextjs.js +11 -11
- package/dist/runtime/http.js +3 -3
- package/dist/runtime/stdio.js +8 -8
- package/package.json +10 -11
- package/src/auth/api-key.ts +0 -120
- package/src/auth/jwt.ts +0 -52
- package/src/cli/commands/create/__tests__/create.test.ts +0 -99
- package/src/cli/commands/create/index.ts +0 -74
- package/src/cli/commands/create/templates/index.ts +0 -4
- package/src/cli/commands/create/templates/prompt.ts +0 -30
- package/src/cli/commands/create/templates/resource.ts +0 -20
- package/src/cli/commands/create/templates/tool.ts +0 -34
- package/src/cli/commands/create/templates/widget.ts +0 -33
- package/src/cli/utils/naming.ts +0 -39
- package/src/cli.ts +0 -125
- package/src/client/headers.ts +0 -61
- package/src/client/index.ts +0 -180
- package/src/client/types.ts +0 -122
- package/src/client/utils.ts +0 -133
- package/src/cloudflare.ts +0 -6
- package/src/compiler/build-telemetry.ts +0 -88
- package/src/compiler/client/component-compiler.ts +0 -250
- package/src/compiler/client/transpile.ts +0 -21
- package/src/compiler/compiler-context.ts +0 -61
- package/src/compiler/config/__tests__/config.test.ts +0 -459
- package/src/compiler/config/index.ts +0 -62
- package/src/compiler/config/injection.ts +0 -210
- package/src/compiler/config/schemas/bundler.ts +0 -12
- package/src/compiler/config/schemas/experimental/index.ts +0 -22
- package/src/compiler/config/schemas/index.ts +0 -20
- package/src/compiler/config/schemas/paths.ts +0 -35
- package/src/compiler/config/schemas/template.ts +0 -80
- package/src/compiler/config/schemas/transport/http.ts +0 -116
- package/src/compiler/config/schemas/transport/stdio.ts +0 -31
- package/src/compiler/config/schemas/typescript.ts +0 -26
- package/src/compiler/config/utils.ts +0 -168
- package/src/compiler/generate-env-code.ts +0 -5
- package/src/compiler/generate-import-code.ts +0 -187
- package/src/compiler/generate-tools-code.ts +0 -174
- package/src/compiler/get-bundler-config/get-entries.ts +0 -44
- package/src/compiler/get-bundler-config/get-externals.ts +0 -114
- package/src/compiler/get-bundler-config/get-injected-variables.ts +0 -46
- package/src/compiler/get-bundler-config/index.ts +0 -288
- package/src/compiler/get-bundler-config/plugins/index.ts +0 -140
- package/src/compiler/get-bundler-config/plugins/types/express.ts +0 -3
- package/src/compiler/get-bundler-config/plugins/types/fastify.ts +0 -4
- package/src/compiler/get-bundler-config/plugins/types/index.ts +0 -5
- package/src/compiler/get-bundler-config/plugins/types/nest.ts +0 -65
- package/src/compiler/get-bundler-config/plugins/types/next.ts +0 -52
- package/src/compiler/get-bundler-config/resolve-tsconfig-paths.ts +0 -51
- package/src/compiler/index.ts +0 -484
- package/src/compiler/on-first-build.ts +0 -54
- package/src/compiler/parse-xmcp-config.ts +0 -200
- package/src/compiler/start-http-server.ts +0 -42
- package/src/compiler/utils/__tests__/config-detection.test.ts +0 -307
- package/src/compiler/utils/__tests__/path-utils.test.ts +0 -137
- package/src/compiler/utils/config-detection.ts +0 -34
- package/src/compiler/utils/path-utils.ts +0 -22
- package/src/compiler/watcher-recovery.ts +0 -72
- package/src/host-bridge.ts +0 -36
- package/src/index.ts +0 -94
- package/src/platforms/build-cloudflare-output.ts +0 -116
- package/src/platforms/build-vercel-output.ts +0 -131
- package/src/plugins/index.ts +0 -1
- package/src/plugins/x402/index.ts +0 -24
- package/src/runtime/adapters/express/index.ts +0 -75
- package/src/runtime/adapters/fastify/__tests__/fastify.test.ts +0 -115
- package/src/runtime/adapters/fastify/index.ts +0 -78
- package/src/runtime/adapters/nestjs/index.ts +0 -16
- package/src/runtime/adapters/nestjs/xmcp.controller.ts +0 -34
- package/src/runtime/adapters/nestjs/xmcp.guard.ts +0 -101
- package/src/runtime/adapters/nestjs/xmcp.oauth.controller.ts +0 -36
- package/src/runtime/adapters/nestjs/xmcp.oauth.module.ts +0 -21
- package/src/runtime/adapters/nestjs/xmcp.oauth.service.ts +0 -36
- package/src/runtime/adapters/nestjs/xmcp.service.ts +0 -96
- package/src/runtime/adapters/nestjs/xmcp.utils.ts +0 -11
- package/src/runtime/adapters/nextjs/auth.ts +0 -265
- package/src/runtime/adapters/nextjs/handler/error-handler.ts +0 -67
- package/src/runtime/adapters/nextjs/handler/node-to-web-adapter.ts +0 -143
- package/src/runtime/adapters/nextjs/handler/request-converter.ts +0 -74
- package/src/runtime/adapters/nextjs/handler/server-lifecycle.ts +0 -69
- package/src/runtime/adapters/nextjs/index.ts +0 -82
- package/src/runtime/contexts/client-info-context.ts +0 -16
- package/src/runtime/contexts/http-request-context.ts +0 -21
- package/src/runtime/contexts/http-transport-context.ts +0 -18
- package/src/runtime/headers.ts +0 -42
- package/src/runtime/middlewares/utils.ts +0 -72
- package/src/runtime/platforms/cloudflare/cors.ts +0 -44
- package/src/runtime/platforms/cloudflare/middlewares/api-key.ts +0 -102
- package/src/runtime/platforms/cloudflare/middlewares/jwt.ts +0 -127
- package/src/runtime/platforms/cloudflare/types.ts +0 -23
- package/src/runtime/platforms/cloudflare/worker.ts +0 -270
- package/src/runtime/templates/home.ts +0 -746
- package/src/runtime/transports/http/base-streamable-http.ts +0 -46
- package/src/runtime/transports/http/cors/headers.ts +0 -58
- package/src/runtime/transports/http/cors/index.ts +0 -34
- package/src/runtime/transports/http/index.ts +0 -78
- package/src/runtime/transports/http/stateless-streamable-http.ts +0 -311
- package/src/runtime/transports/http/web-stateless-http.ts +0 -288
- package/src/runtime/transports/stdio/index.ts +0 -109
- package/src/runtime/utils/__tests__/client-info.test.ts +0 -146
- package/src/runtime/utils/__tests__/tool-extra.test.ts +0 -239
- package/src/runtime/utils/client-info.ts +0 -114
- package/src/runtime/utils/elicitation.ts +0 -396
- package/src/runtime/utils/ext-apps-registry.ts +0 -151
- package/src/runtime/utils/mcp-app-protocol.ts +0 -16
- package/src/runtime/utils/mcp-app-types.ts +0 -113
- package/src/runtime/utils/mcp-host-bridge.ts +0 -473
- package/src/runtime/utils/path-to-tool-name.ts +0 -69
- package/src/runtime/utils/prompt-loader.ts +0 -151
- package/src/runtime/utils/prompts.ts +0 -69
- package/src/runtime/utils/react/generate-html.ts +0 -69
- package/src/runtime/utils/react/index.ts +0 -6
- package/src/runtime/utils/request-tool-names.ts +0 -48
- package/src/runtime/utils/resource-loader.ts +0 -151
- package/src/runtime/utils/resources.ts +0 -331
- package/src/runtime/utils/server.ts +0 -107
- package/src/runtime/utils/tool-loader.ts +0 -149
- package/src/runtime/utils/tools.ts +0 -183
- package/src/runtime/utils/transformers/prompt.ts +0 -120
- package/src/runtime/utils/transformers/resource.ts +0 -196
- package/src/runtime/utils/transformers/tool.ts +0 -400
- package/src/runtime/utils/ui/__tests__/split-meta.test.ts +0 -803
- package/src/runtime/utils/ui/flatten-meta.ts +0 -44
- package/src/runtime/utils/ui/split-meta.ts +0 -78
- package/src/runtime/utils/utils/resource-uri-composer.ts +0 -204
- package/src/runtime/utils/validators/index.ts +0 -138
- package/src/telemetry/ci-info.ts +0 -6
- package/src/telemetry/debug.ts +0 -8
- package/src/telemetry/events/definitions.ts +0 -52
- package/src/telemetry/events/detached-flush.ts +0 -83
- package/src/telemetry/events/post-payload.ts +0 -141
- package/src/telemetry/events/tracker.ts +0 -281
- package/src/telemetry/index.ts +0 -7
- package/src/telemetry/metadata.ts +0 -49
- package/src/telemetry/project-id.ts +0 -35
- package/src/telemetry/storage.ts +0 -218
- package/src/types/adapter.d.ts +0 -5
- package/src/types/client-info.ts +0 -20
- package/src/types/declarations.ts +0 -37
- package/src/types/injected.d.ts +0 -62
- package/src/types/middleware.ts +0 -19
- package/src/types/prompt.ts +0 -6
- package/src/types/resource.ts +0 -15
- package/src/types/tool.ts +0 -192
- package/src/types/ui-meta.ts +0 -42
- package/src/utils/cli-icons.ts +0 -5
- package/src/utils/constants.ts +0 -31
- package/src/utils/context.ts +0 -105
- package/src/utils/detect-package-manager.ts +0 -46
- package/src/utils/file-watcher.ts +0 -66
- package/src/utils/fs-utils.ts +0 -16
- package/src/utils/path-validation.ts +0 -66
- package/src/utils/port-utils.ts +0 -43
- package/src/utils/spawn-process.ts +0 -49
- 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
|
-
}
|
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
import type { ServerResponse } from "node:http";
|
|
2
|
-
import { nodeToWebAdapter } from "./handler/node-to-web-adapter";
|
|
3
|
-
import {
|
|
4
|
-
createMethodNotAllowedResponse,
|
|
5
|
-
sendInternalServerError,
|
|
6
|
-
} from "./handler/error-handler";
|
|
7
|
-
import {
|
|
8
|
-
createServerLifecycle,
|
|
9
|
-
setupCleanupHandlers,
|
|
10
|
-
} from "./handler/server-lifecycle";
|
|
11
|
-
import { createIncomingMessage } from "./handler/request-converter";
|
|
12
|
-
import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types";
|
|
13
|
-
import { httpRequestContextProvider } from "@/runtime/contexts/http-request-context";
|
|
14
|
-
import { randomUUID } from "node:crypto";
|
|
15
|
-
import {
|
|
16
|
-
setHttpRequestContext,
|
|
17
|
-
} from "@/runtime/contexts/http-request-context";
|
|
18
|
-
import { extractClientInfoFromMessages } from "@/runtime/utils/client-info";
|
|
19
|
-
|
|
20
|
-
const BODY_SIZE_LIMIT = "10mb";
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* Main handler for MCP requests in Next.js runtime.
|
|
24
|
-
* Handles POST requests only, validates, parses, and routes to MCP server.
|
|
25
|
-
*/
|
|
26
|
-
export async function xmcpHandler(request: Request): Promise<Response> {
|
|
27
|
-
// Only handle POST requests
|
|
28
|
-
if (request.method !== "POST") {
|
|
29
|
-
return createMethodNotAllowedResponse();
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
const id = randomUUID();
|
|
33
|
-
const requestHeaders = Object.fromEntries(request.headers.entries());
|
|
34
|
-
|
|
35
|
-
return httpRequestContextProvider(
|
|
36
|
-
{ id, headers: requestHeaders, clientInfo: undefined },
|
|
37
|
-
() => {
|
|
38
|
-
return nodeToWebAdapter(request.signal, async (res: ServerResponse) => {
|
|
39
|
-
try {
|
|
40
|
-
// Initialize server and transport
|
|
41
|
-
const lifecycle = await createServerLifecycle(BODY_SIZE_LIMIT);
|
|
42
|
-
|
|
43
|
-
// Setup cleanup handlers
|
|
44
|
-
setupCleanupHandlers(res, lifecycle);
|
|
45
|
-
|
|
46
|
-
// Parse request body
|
|
47
|
-
const bodyContent = await request.json();
|
|
48
|
-
const clientInfo = extractClientInfoFromMessages(bodyContent);
|
|
49
|
-
setHttpRequestContext({ clientInfo });
|
|
50
|
-
|
|
51
|
-
// Convert Web Request to Node.js IncomingMessage
|
|
52
|
-
const incomingRequest = createIncomingMessage({
|
|
53
|
-
method: request.method,
|
|
54
|
-
url: request.url,
|
|
55
|
-
headers: requestHeaders,
|
|
56
|
-
auth: request.auth,
|
|
57
|
-
});
|
|
58
|
-
|
|
59
|
-
// Handle request through transport
|
|
60
|
-
await lifecycle.transport.handleRequest(
|
|
61
|
-
incomingRequest,
|
|
62
|
-
res,
|
|
63
|
-
bodyContent
|
|
64
|
-
);
|
|
65
|
-
} catch (error) {
|
|
66
|
-
console.error("[Next.js MCP] Error handling MCP request:", error);
|
|
67
|
-
sendInternalServerError(res);
|
|
68
|
-
}
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
);
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
// Re-export auth types and handlers
|
|
75
|
-
export {
|
|
76
|
-
withAuth,
|
|
77
|
-
resourceMetadataHandler,
|
|
78
|
-
resourceMetadataOptions,
|
|
79
|
-
type VerifyToken,
|
|
80
|
-
type AuthConfig,
|
|
81
|
-
type OAuthProtectedResourceMetadata,
|
|
82
|
-
} from "./auth";
|