@nestia/core 12.0.0-rc.2 → 12.0.0-rc.3
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/LICENSE +21 -21
- package/MIGRATION.md +138 -169
- package/lib/decorators/NoTransformConfigurationError.js +5 -5
- package/lib/decorators/NoTransformConfigurationError.js.map +1 -1
- package/native/cmd/ttsc-nestia/main.go +11 -11
- package/native/go.mod +32 -32
- package/native/go.sum +54 -54
- package/native/plugin/plan.go +102 -102
- package/native/transform/ast.go +32 -32
- package/native/transform/build.go +388 -380
- package/native/transform/cleanup.go +408 -408
- package/native/transform/contributor.go +97 -97
- package/native/transform/core_querify.go +231 -231
- package/native/transform/core_transform.go +1996 -1996
- package/native/transform/core_websocket.go +115 -115
- package/native/transform/exports.go +13 -13
- package/native/transform/mcp_transform.go +414 -414
- package/native/transform/node_transform.go +357 -357
- package/native/transform/path_rewrite.go +285 -285
- package/native/transform/printer.go +244 -244
- package/native/transform/rewrite.go +668 -668
- package/native/transform/run.go +73 -73
- package/native/transform/transform.go +336 -336
- package/native/transform/typia_fast.go +375 -352
- package/native/transform/typia_replacement.go +24 -24
- package/native/transform.cjs +43 -43
- package/package.json +9 -9
- package/src/adaptors/McpAdaptor.ts +276 -276
- package/src/adaptors/WebSocketAdaptor.ts +429 -429
- package/src/decorators/DynamicModule.ts +44 -44
- package/src/decorators/EncryptedBody.ts +97 -97
- package/src/decorators/EncryptedController.ts +40 -40
- package/src/decorators/EncryptedModule.ts +98 -98
- package/src/decorators/EncryptedRoute.ts +213 -213
- package/src/decorators/HumanRoute.ts +21 -21
- package/src/decorators/McpRoute.ts +154 -154
- package/src/decorators/NoTransformConfigurationError.ts +40 -40
- package/src/decorators/PlainBody.ts +76 -76
- package/src/decorators/SwaggerCustomizer.ts +97 -97
- package/src/decorators/SwaggerExample.ts +180 -180
- package/src/decorators/TypedBody.ts +57 -57
- package/src/decorators/TypedException.ts +147 -147
- package/src/decorators/TypedFormData.ts +187 -187
- package/src/decorators/TypedHeaders.ts +66 -66
- package/src/decorators/TypedParam.ts +77 -77
- package/src/decorators/TypedQuery.ts +234 -234
- package/src/decorators/TypedRoute.ts +198 -198
- package/src/decorators/WebSocketRoute.ts +242 -242
- package/src/decorators/doNotThrowTransformError.ts +5 -5
- package/src/decorators/internal/EncryptedConstant.ts +2 -2
- package/src/decorators/internal/IMcpRouteReflect.ts +40 -40
- package/src/decorators/internal/IWebSocketRouteReflect.ts +23 -23
- package/src/decorators/internal/get_path_and_querify.ts +94 -94
- package/src/decorators/internal/get_path_and_stringify.ts +110 -110
- package/src/decorators/internal/get_text_body.ts +16 -16
- package/src/decorators/internal/headers_to_object.ts +11 -11
- package/src/decorators/internal/is_request_body_undefined.ts +12 -12
- package/src/decorators/internal/load_controller.ts +94 -94
- package/src/decorators/internal/route_error.ts +43 -43
- package/src/decorators/internal/validate_request_body.ts +64 -64
- package/src/decorators/internal/validate_request_form_data.ts +67 -67
- package/src/decorators/internal/validate_request_headers.ts +76 -76
- package/src/decorators/internal/validate_request_query.ts +83 -83
- package/src/index.ts +5 -5
- package/src/module.ts +25 -25
- package/src/options/IRequestBodyValidator.ts +20 -20
- package/src/options/IRequestFormDataProps.ts +27 -27
- package/src/options/IRequestHeadersValidator.ts +22 -22
- package/src/options/IRequestQueryValidator.ts +20 -20
- package/src/options/IResponseBodyQuerifier.ts +25 -25
- package/src/options/IResponseBodyStringifier.ts +30 -30
- package/src/transform.ts +26 -26
- package/src/typings/Creator.ts +3 -3
- package/src/typings/get-function-location.d.ts +7 -7
- package/src/utils/ArrayUtil.ts +7 -7
- package/src/utils/ExceptionManager.ts +115 -115
- package/src/utils/Singleton.ts +16 -16
- package/src/utils/SourceFinder.ts +54 -54
- package/src/utils/VersioningStrategy.ts +27 -27
- package/README.md +0 -93
|
@@ -1,276 +1,276 @@
|
|
|
1
|
-
import {
|
|
2
|
-
BadRequestException,
|
|
3
|
-
HttpException,
|
|
4
|
-
INestApplication,
|
|
5
|
-
} from "@nestjs/common";
|
|
6
|
-
import { NestContainer } from "@nestjs/core";
|
|
7
|
-
|
|
8
|
-
import { IMcpRouteReflect } from "../decorators/internal/IMcpRouteReflect";
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* MCP (Model Context Protocol) adaptor.
|
|
12
|
-
*
|
|
13
|
-
* `McpAdaptor` exposes every method decorated with {@link McpRoute} as an MCP
|
|
14
|
-
* tool, reachable by LLM clients through a stateless Streamable HTTP endpoint.
|
|
15
|
-
*
|
|
16
|
-
* At bootstrap the adaptor walks the {@link NestContainer}, collects every
|
|
17
|
-
* controller method carrying `"nestia/McpRoute"` metadata, and caches a tool
|
|
18
|
-
* registry. A fresh MCP server and transport pair is spun up per incoming HTTP
|
|
19
|
-
* request, following MCP stateless Streamable HTTP mode. This adaptor
|
|
20
|
-
* intentionally does not manage `Mcp-Session-Id` state.
|
|
21
|
-
*
|
|
22
|
-
* Typia-generated JSON Schemas flow through unchanged; the Zod-based high-level
|
|
23
|
-
* registration API of `McpServer` is bypassed by accessing the low-level
|
|
24
|
-
* `.server` handler.
|
|
25
|
-
*
|
|
26
|
-
* Error mapping follows the MCP specification:
|
|
27
|
-
*
|
|
28
|
-
* - Unknown tool name: JSON-RPC `-32601`.
|
|
29
|
-
* - Typia validation failure: JSON-RPC `-32602` with structured diagnostics.
|
|
30
|
-
* - Handler throws {@link HttpException}: success response with `isError: true`,
|
|
31
|
-
* so the LLM can read the message and recover.
|
|
32
|
-
* - Any other throw: JSON-RPC `-32603`.
|
|
33
|
-
*
|
|
34
|
-
* @author wildduck - https://github.com/wildduck2
|
|
35
|
-
* @example
|
|
36
|
-
* ```typescript
|
|
37
|
-
* import core from "@nestia/core";
|
|
38
|
-
* import { NestFactory } from "@nestjs/core";
|
|
39
|
-
*
|
|
40
|
-
* const app = await NestFactory.create(AppModule);
|
|
41
|
-
* await core.McpAdaptor.upgrade(app, { path: "/mcp" });
|
|
42
|
-
* await app.listen(3000);
|
|
43
|
-
* ```;
|
|
44
|
-
*/
|
|
45
|
-
export class McpAdaptor {
|
|
46
|
-
/**
|
|
47
|
-
* Upgrade a running Nest application with a stateless MCP endpoint.
|
|
48
|
-
*
|
|
49
|
-
* Scans the application container for methods decorated with {@link McpRoute},
|
|
50
|
-
* then registers a catch-all HTTP route at the configured path. Each incoming
|
|
51
|
-
* request builds a fresh MCP server + transport on demand, wires the
|
|
52
|
-
* registered tools into it, and delegates handling.
|
|
53
|
-
*
|
|
54
|
-
* Must be called after `NestFactory.create(...)` but before `app.listen(...)`
|
|
55
|
-
* if you want the MCP endpoint to be reachable alongside your regular HTTP
|
|
56
|
-
* routes.
|
|
57
|
-
*
|
|
58
|
-
* @param app Running Nest application instance.
|
|
59
|
-
* @param options Transport and identity overrides.
|
|
60
|
-
*/
|
|
61
|
-
public static async upgrade(
|
|
62
|
-
app: INestApplication,
|
|
63
|
-
options: McpAdaptor.IOptions = {},
|
|
64
|
-
): Promise<void> {
|
|
65
|
-
if ("sessioned" in (options as Record<string, unknown>))
|
|
66
|
-
throw new Error(
|
|
67
|
-
"McpAdaptor.upgrade() supports stateless Streamable HTTP only; sessioned mode is not implemented.",
|
|
68
|
-
);
|
|
69
|
-
|
|
70
|
-
const tools: McpAdaptor.ITool[] = [];
|
|
71
|
-
const container = (app as any).container as NestContainer;
|
|
72
|
-
for (const module of container.getModules().values()) {
|
|
73
|
-
for (const wrapper of module.controllers.values()) {
|
|
74
|
-
const instance = wrapper.instance;
|
|
75
|
-
if (!instance) continue;
|
|
76
|
-
const proto = Object.getPrototypeOf(instance);
|
|
77
|
-
for (const key of Object.getOwnPropertyNames(proto)) {
|
|
78
|
-
if (key === "constructor") continue;
|
|
79
|
-
const method = proto[key];
|
|
80
|
-
if (typeof method !== "function") continue;
|
|
81
|
-
|
|
82
|
-
const meta: IMcpRouteReflect | undefined = Reflect.getMetadata(
|
|
83
|
-
"nestia/McpRoute",
|
|
84
|
-
method,
|
|
85
|
-
);
|
|
86
|
-
if (!meta) continue;
|
|
87
|
-
|
|
88
|
-
const params: IMcpRouteReflect.IArgument[] =
|
|
89
|
-
Reflect.getMetadata("nestia/McpRoute/Parameters", proto, key) ?? [];
|
|
90
|
-
const paramValidator = params.find(
|
|
91
|
-
(p) => p.category === "params",
|
|
92
|
-
)?.validate;
|
|
93
|
-
|
|
94
|
-
tools.push({
|
|
95
|
-
meta,
|
|
96
|
-
source: `${wrapper.metatype?.name ?? proto.constructor?.name ?? "UnknownController"}.${String(key)}`,
|
|
97
|
-
validateArgs: paramValidator,
|
|
98
|
-
handler: async (args) => method.call(instance, args),
|
|
99
|
-
});
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
assertUniqueTools(tools);
|
|
104
|
-
|
|
105
|
-
const serverInfo = options.serverInfo ?? {
|
|
106
|
-
name: "nestia-mcp",
|
|
107
|
-
version: "1.0.0",
|
|
108
|
-
};
|
|
109
|
-
const {
|
|
110
|
-
CallToolRequestSchema,
|
|
111
|
-
ErrorCode,
|
|
112
|
-
ListToolsRequestSchema,
|
|
113
|
-
McpError,
|
|
114
|
-
McpServer,
|
|
115
|
-
StreamableHTTPServerTransport,
|
|
116
|
-
} = await loadMcpSdk();
|
|
117
|
-
|
|
118
|
-
const http = app.getHttpAdapter();
|
|
119
|
-
const route = options.path ?? "/mcp";
|
|
120
|
-
http.all(route, async (req: any, res: any) => {
|
|
121
|
-
// Stateless mode requires a fresh transport per request; sharing one
|
|
122
|
-
// across clients races on internal initialization and request IDs.
|
|
123
|
-
const mcp = new McpServer(serverInfo, {
|
|
124
|
-
capabilities: { tools: {} },
|
|
125
|
-
});
|
|
126
|
-
const server = mcp.server;
|
|
127
|
-
|
|
128
|
-
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
129
|
-
tools: tools.map((t) => ({
|
|
130
|
-
name: t.meta.name,
|
|
131
|
-
title: t.meta.title,
|
|
132
|
-
description: t.meta.description,
|
|
133
|
-
inputSchema: t.meta.inputSchema,
|
|
134
|
-
outputSchema: t.meta.outputSchema,
|
|
135
|
-
annotations: t.meta.annotations,
|
|
136
|
-
})),
|
|
137
|
-
}));
|
|
138
|
-
|
|
139
|
-
server.setRequestHandler(CallToolRequestSchema, async (reqMsg: any) => {
|
|
140
|
-
const tool = tools.find((t) => t.meta.name === reqMsg.params.name);
|
|
141
|
-
if (!tool)
|
|
142
|
-
throw new McpError(
|
|
143
|
-
ErrorCode.MethodNotFound,
|
|
144
|
-
`Tool not found: ${reqMsg.params.name}`,
|
|
145
|
-
);
|
|
146
|
-
|
|
147
|
-
const args = reqMsg.params.arguments ?? {};
|
|
148
|
-
if (tool.validateArgs) {
|
|
149
|
-
const err: Error | null = tool.validateArgs(args);
|
|
150
|
-
if (err !== null) {
|
|
151
|
-
const body =
|
|
152
|
-
err instanceof BadRequestException
|
|
153
|
-
? (err.getResponse() as any)
|
|
154
|
-
: undefined;
|
|
155
|
-
throw new McpError(ErrorCode.InvalidParams, err.message, {
|
|
156
|
-
errors: body?.errors,
|
|
157
|
-
path: body?.path,
|
|
158
|
-
expected: body?.expected,
|
|
159
|
-
value: body?.value,
|
|
160
|
-
reason: body?.reason,
|
|
161
|
-
});
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
try {
|
|
166
|
-
const result = await tool.handler(args);
|
|
167
|
-
if (result === undefined) return { content: [] };
|
|
168
|
-
return {
|
|
169
|
-
content: [
|
|
170
|
-
{
|
|
171
|
-
type: "text" as const,
|
|
172
|
-
text:
|
|
173
|
-
typeof result === "string" ? result : JSON.stringify(result),
|
|
174
|
-
},
|
|
175
|
-
],
|
|
176
|
-
};
|
|
177
|
-
} catch (e) {
|
|
178
|
-
if (e instanceof HttpException) {
|
|
179
|
-
return {
|
|
180
|
-
content: [{ type: "text" as const, text: e.message }],
|
|
181
|
-
isError: true,
|
|
182
|
-
};
|
|
183
|
-
}
|
|
184
|
-
throw new McpError(
|
|
185
|
-
ErrorCode.InternalError,
|
|
186
|
-
e instanceof Error ? e.message : "Internal error",
|
|
187
|
-
);
|
|
188
|
-
}
|
|
189
|
-
});
|
|
190
|
-
|
|
191
|
-
const transport = new StreamableHTTPServerTransport({
|
|
192
|
-
sessionIdGenerator: undefined,
|
|
193
|
-
enableJsonResponse: true,
|
|
194
|
-
});
|
|
195
|
-
try {
|
|
196
|
-
await mcp.connect(transport);
|
|
197
|
-
await transport.handleRequest(req.raw ?? req, res.raw ?? res, req.body);
|
|
198
|
-
} finally {
|
|
199
|
-
await transport.close().catch(() => {});
|
|
200
|
-
await mcp.close().catch(() => {});
|
|
201
|
-
}
|
|
202
|
-
});
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
const assertUniqueTools = (tools: McpAdaptor.ITool[]): void => {
|
|
207
|
-
const dict: Map<string, McpAdaptor.ITool[]> = new Map();
|
|
208
|
-
for (const tool of tools) {
|
|
209
|
-
const array = dict.get(tool.meta.name) ?? [];
|
|
210
|
-
array.push(tool);
|
|
211
|
-
dict.set(tool.meta.name, array);
|
|
212
|
-
}
|
|
213
|
-
const duplicated = Array.from(dict.entries()).filter(
|
|
214
|
-
([, list]) => list.length > 1,
|
|
215
|
-
);
|
|
216
|
-
if (duplicated.length === 0) return;
|
|
217
|
-
throw new Error(
|
|
218
|
-
[
|
|
219
|
-
"Duplicated MCP tool names are not allowed.",
|
|
220
|
-
...duplicated.map(
|
|
221
|
-
([name, list]) =>
|
|
222
|
-
` - ${JSON.stringify(name)}: ${list.map((tool) => tool.source).join(", ")}`,
|
|
223
|
-
),
|
|
224
|
-
].join("\n"),
|
|
225
|
-
);
|
|
226
|
-
};
|
|
227
|
-
|
|
228
|
-
const loadMcpSdk = async () => {
|
|
229
|
-
try {
|
|
230
|
-
const [server, transport, types] = await Promise.all([
|
|
231
|
-
import("@modelcontextprotocol/sdk/server/mcp.js"),
|
|
232
|
-
import("@modelcontextprotocol/sdk/server/streamableHttp.js"),
|
|
233
|
-
import("@modelcontextprotocol/sdk/types.js"),
|
|
234
|
-
]);
|
|
235
|
-
return {
|
|
236
|
-
McpServer: server.McpServer,
|
|
237
|
-
StreamableHTTPServerTransport: transport.StreamableHTTPServerTransport,
|
|
238
|
-
CallToolRequestSchema: types.CallToolRequestSchema,
|
|
239
|
-
ErrorCode: types.ErrorCode,
|
|
240
|
-
ListToolsRequestSchema: types.ListToolsRequestSchema,
|
|
241
|
-
McpError: types.McpError,
|
|
242
|
-
};
|
|
243
|
-
} catch {
|
|
244
|
-
throw new Error(
|
|
245
|
-
"McpAdaptor.upgrade() requires @modelcontextprotocol/sdk. Install it before enabling MCP routes.",
|
|
246
|
-
);
|
|
247
|
-
}
|
|
248
|
-
};
|
|
249
|
-
|
|
250
|
-
export namespace McpAdaptor {
|
|
251
|
-
/** Configuration options for {@link McpAdaptor.upgrade}. */
|
|
252
|
-
export interface IOptions {
|
|
253
|
-
/**
|
|
254
|
-
* HTTP path where the MCP endpoint will be mounted.
|
|
255
|
-
*
|
|
256
|
-
* @default "/mcp"
|
|
257
|
-
*/
|
|
258
|
-
path?: string;
|
|
259
|
-
|
|
260
|
-
/**
|
|
261
|
-
* Identity advertised to MCP clients during the initialize handshake. Shows
|
|
262
|
-
* up in Claude Desktop / Cursor's MCP panel.
|
|
263
|
-
*
|
|
264
|
-
* @default { name: "nestia-mcp", version: "1.0.0" }
|
|
265
|
-
*/
|
|
266
|
-
serverInfo?: { name: string; version: string };
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
/** @internal */
|
|
270
|
-
export interface ITool {
|
|
271
|
-
meta: IMcpRouteReflect;
|
|
272
|
-
source: string;
|
|
273
|
-
handler: (args: unknown) => Promise<unknown>;
|
|
274
|
-
validateArgs?: (input: any) => Error | null;
|
|
275
|
-
}
|
|
276
|
-
}
|
|
1
|
+
import {
|
|
2
|
+
BadRequestException,
|
|
3
|
+
HttpException,
|
|
4
|
+
INestApplication,
|
|
5
|
+
} from "@nestjs/common";
|
|
6
|
+
import { NestContainer } from "@nestjs/core";
|
|
7
|
+
|
|
8
|
+
import { IMcpRouteReflect } from "../decorators/internal/IMcpRouteReflect";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* MCP (Model Context Protocol) adaptor.
|
|
12
|
+
*
|
|
13
|
+
* `McpAdaptor` exposes every method decorated with {@link McpRoute} as an MCP
|
|
14
|
+
* tool, reachable by LLM clients through a stateless Streamable HTTP endpoint.
|
|
15
|
+
*
|
|
16
|
+
* At bootstrap the adaptor walks the {@link NestContainer}, collects every
|
|
17
|
+
* controller method carrying `"nestia/McpRoute"` metadata, and caches a tool
|
|
18
|
+
* registry. A fresh MCP server and transport pair is spun up per incoming HTTP
|
|
19
|
+
* request, following MCP stateless Streamable HTTP mode. This adaptor
|
|
20
|
+
* intentionally does not manage `Mcp-Session-Id` state.
|
|
21
|
+
*
|
|
22
|
+
* Typia-generated JSON Schemas flow through unchanged; the Zod-based high-level
|
|
23
|
+
* registration API of `McpServer` is bypassed by accessing the low-level
|
|
24
|
+
* `.server` handler.
|
|
25
|
+
*
|
|
26
|
+
* Error mapping follows the MCP specification:
|
|
27
|
+
*
|
|
28
|
+
* - Unknown tool name: JSON-RPC `-32601`.
|
|
29
|
+
* - Typia validation failure: JSON-RPC `-32602` with structured diagnostics.
|
|
30
|
+
* - Handler throws {@link HttpException}: success response with `isError: true`,
|
|
31
|
+
* so the LLM can read the message and recover.
|
|
32
|
+
* - Any other throw: JSON-RPC `-32603`.
|
|
33
|
+
*
|
|
34
|
+
* @author wildduck - https://github.com/wildduck2
|
|
35
|
+
* @example
|
|
36
|
+
* ```typescript
|
|
37
|
+
* import core from "@nestia/core";
|
|
38
|
+
* import { NestFactory } from "@nestjs/core";
|
|
39
|
+
*
|
|
40
|
+
* const app = await NestFactory.create(AppModule);
|
|
41
|
+
* await core.McpAdaptor.upgrade(app, { path: "/mcp" });
|
|
42
|
+
* await app.listen(3000);
|
|
43
|
+
* ```;
|
|
44
|
+
*/
|
|
45
|
+
export class McpAdaptor {
|
|
46
|
+
/**
|
|
47
|
+
* Upgrade a running Nest application with a stateless MCP endpoint.
|
|
48
|
+
*
|
|
49
|
+
* Scans the application container for methods decorated with {@link McpRoute},
|
|
50
|
+
* then registers a catch-all HTTP route at the configured path. Each incoming
|
|
51
|
+
* request builds a fresh MCP server + transport on demand, wires the
|
|
52
|
+
* registered tools into it, and delegates handling.
|
|
53
|
+
*
|
|
54
|
+
* Must be called after `NestFactory.create(...)` but before `app.listen(...)`
|
|
55
|
+
* if you want the MCP endpoint to be reachable alongside your regular HTTP
|
|
56
|
+
* routes.
|
|
57
|
+
*
|
|
58
|
+
* @param app Running Nest application instance.
|
|
59
|
+
* @param options Transport and identity overrides.
|
|
60
|
+
*/
|
|
61
|
+
public static async upgrade(
|
|
62
|
+
app: INestApplication,
|
|
63
|
+
options: McpAdaptor.IOptions = {},
|
|
64
|
+
): Promise<void> {
|
|
65
|
+
if ("sessioned" in (options as Record<string, unknown>))
|
|
66
|
+
throw new Error(
|
|
67
|
+
"McpAdaptor.upgrade() supports stateless Streamable HTTP only; sessioned mode is not implemented.",
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
const tools: McpAdaptor.ITool[] = [];
|
|
71
|
+
const container = (app as any).container as NestContainer;
|
|
72
|
+
for (const module of container.getModules().values()) {
|
|
73
|
+
for (const wrapper of module.controllers.values()) {
|
|
74
|
+
const instance = wrapper.instance;
|
|
75
|
+
if (!instance) continue;
|
|
76
|
+
const proto = Object.getPrototypeOf(instance);
|
|
77
|
+
for (const key of Object.getOwnPropertyNames(proto)) {
|
|
78
|
+
if (key === "constructor") continue;
|
|
79
|
+
const method = proto[key];
|
|
80
|
+
if (typeof method !== "function") continue;
|
|
81
|
+
|
|
82
|
+
const meta: IMcpRouteReflect | undefined = Reflect.getMetadata(
|
|
83
|
+
"nestia/McpRoute",
|
|
84
|
+
method,
|
|
85
|
+
);
|
|
86
|
+
if (!meta) continue;
|
|
87
|
+
|
|
88
|
+
const params: IMcpRouteReflect.IArgument[] =
|
|
89
|
+
Reflect.getMetadata("nestia/McpRoute/Parameters", proto, key) ?? [];
|
|
90
|
+
const paramValidator = params.find(
|
|
91
|
+
(p) => p.category === "params",
|
|
92
|
+
)?.validate;
|
|
93
|
+
|
|
94
|
+
tools.push({
|
|
95
|
+
meta,
|
|
96
|
+
source: `${wrapper.metatype?.name ?? proto.constructor?.name ?? "UnknownController"}.${String(key)}`,
|
|
97
|
+
validateArgs: paramValidator,
|
|
98
|
+
handler: async (args) => method.call(instance, args),
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
assertUniqueTools(tools);
|
|
104
|
+
|
|
105
|
+
const serverInfo = options.serverInfo ?? {
|
|
106
|
+
name: "nestia-mcp",
|
|
107
|
+
version: "1.0.0",
|
|
108
|
+
};
|
|
109
|
+
const {
|
|
110
|
+
CallToolRequestSchema,
|
|
111
|
+
ErrorCode,
|
|
112
|
+
ListToolsRequestSchema,
|
|
113
|
+
McpError,
|
|
114
|
+
McpServer,
|
|
115
|
+
StreamableHTTPServerTransport,
|
|
116
|
+
} = await loadMcpSdk();
|
|
117
|
+
|
|
118
|
+
const http = app.getHttpAdapter();
|
|
119
|
+
const route = options.path ?? "/mcp";
|
|
120
|
+
http.all(route, async (req: any, res: any) => {
|
|
121
|
+
// Stateless mode requires a fresh transport per request; sharing one
|
|
122
|
+
// across clients races on internal initialization and request IDs.
|
|
123
|
+
const mcp = new McpServer(serverInfo, {
|
|
124
|
+
capabilities: { tools: {} },
|
|
125
|
+
});
|
|
126
|
+
const server = mcp.server;
|
|
127
|
+
|
|
128
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
129
|
+
tools: tools.map((t) => ({
|
|
130
|
+
name: t.meta.name,
|
|
131
|
+
title: t.meta.title,
|
|
132
|
+
description: t.meta.description,
|
|
133
|
+
inputSchema: t.meta.inputSchema,
|
|
134
|
+
outputSchema: t.meta.outputSchema,
|
|
135
|
+
annotations: t.meta.annotations,
|
|
136
|
+
})),
|
|
137
|
+
}));
|
|
138
|
+
|
|
139
|
+
server.setRequestHandler(CallToolRequestSchema, async (reqMsg: any) => {
|
|
140
|
+
const tool = tools.find((t) => t.meta.name === reqMsg.params.name);
|
|
141
|
+
if (!tool)
|
|
142
|
+
throw new McpError(
|
|
143
|
+
ErrorCode.MethodNotFound,
|
|
144
|
+
`Tool not found: ${reqMsg.params.name}`,
|
|
145
|
+
);
|
|
146
|
+
|
|
147
|
+
const args = reqMsg.params.arguments ?? {};
|
|
148
|
+
if (tool.validateArgs) {
|
|
149
|
+
const err: Error | null = tool.validateArgs(args);
|
|
150
|
+
if (err !== null) {
|
|
151
|
+
const body =
|
|
152
|
+
err instanceof BadRequestException
|
|
153
|
+
? (err.getResponse() as any)
|
|
154
|
+
: undefined;
|
|
155
|
+
throw new McpError(ErrorCode.InvalidParams, err.message, {
|
|
156
|
+
errors: body?.errors,
|
|
157
|
+
path: body?.path,
|
|
158
|
+
expected: body?.expected,
|
|
159
|
+
value: body?.value,
|
|
160
|
+
reason: body?.reason,
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
try {
|
|
166
|
+
const result = await tool.handler(args);
|
|
167
|
+
if (result === undefined) return { content: [] };
|
|
168
|
+
return {
|
|
169
|
+
content: [
|
|
170
|
+
{
|
|
171
|
+
type: "text" as const,
|
|
172
|
+
text:
|
|
173
|
+
typeof result === "string" ? result : JSON.stringify(result),
|
|
174
|
+
},
|
|
175
|
+
],
|
|
176
|
+
};
|
|
177
|
+
} catch (e) {
|
|
178
|
+
if (e instanceof HttpException) {
|
|
179
|
+
return {
|
|
180
|
+
content: [{ type: "text" as const, text: e.message }],
|
|
181
|
+
isError: true,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
throw new McpError(
|
|
185
|
+
ErrorCode.InternalError,
|
|
186
|
+
e instanceof Error ? e.message : "Internal error",
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
const transport = new StreamableHTTPServerTransport({
|
|
192
|
+
sessionIdGenerator: undefined,
|
|
193
|
+
enableJsonResponse: true,
|
|
194
|
+
});
|
|
195
|
+
try {
|
|
196
|
+
await mcp.connect(transport);
|
|
197
|
+
await transport.handleRequest(req.raw ?? req, res.raw ?? res, req.body);
|
|
198
|
+
} finally {
|
|
199
|
+
await transport.close().catch(() => {});
|
|
200
|
+
await mcp.close().catch(() => {});
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const assertUniqueTools = (tools: McpAdaptor.ITool[]): void => {
|
|
207
|
+
const dict: Map<string, McpAdaptor.ITool[]> = new Map();
|
|
208
|
+
for (const tool of tools) {
|
|
209
|
+
const array = dict.get(tool.meta.name) ?? [];
|
|
210
|
+
array.push(tool);
|
|
211
|
+
dict.set(tool.meta.name, array);
|
|
212
|
+
}
|
|
213
|
+
const duplicated = Array.from(dict.entries()).filter(
|
|
214
|
+
([, list]) => list.length > 1,
|
|
215
|
+
);
|
|
216
|
+
if (duplicated.length === 0) return;
|
|
217
|
+
throw new Error(
|
|
218
|
+
[
|
|
219
|
+
"Duplicated MCP tool names are not allowed.",
|
|
220
|
+
...duplicated.map(
|
|
221
|
+
([name, list]) =>
|
|
222
|
+
` - ${JSON.stringify(name)}: ${list.map((tool) => tool.source).join(", ")}`,
|
|
223
|
+
),
|
|
224
|
+
].join("\n"),
|
|
225
|
+
);
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
const loadMcpSdk = async () => {
|
|
229
|
+
try {
|
|
230
|
+
const [server, transport, types] = await Promise.all([
|
|
231
|
+
import("@modelcontextprotocol/sdk/server/mcp.js"),
|
|
232
|
+
import("@modelcontextprotocol/sdk/server/streamableHttp.js"),
|
|
233
|
+
import("@modelcontextprotocol/sdk/types.js"),
|
|
234
|
+
]);
|
|
235
|
+
return {
|
|
236
|
+
McpServer: server.McpServer,
|
|
237
|
+
StreamableHTTPServerTransport: transport.StreamableHTTPServerTransport,
|
|
238
|
+
CallToolRequestSchema: types.CallToolRequestSchema,
|
|
239
|
+
ErrorCode: types.ErrorCode,
|
|
240
|
+
ListToolsRequestSchema: types.ListToolsRequestSchema,
|
|
241
|
+
McpError: types.McpError,
|
|
242
|
+
};
|
|
243
|
+
} catch {
|
|
244
|
+
throw new Error(
|
|
245
|
+
"McpAdaptor.upgrade() requires @modelcontextprotocol/sdk. Install it before enabling MCP routes.",
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
export namespace McpAdaptor {
|
|
251
|
+
/** Configuration options for {@link McpAdaptor.upgrade}. */
|
|
252
|
+
export interface IOptions {
|
|
253
|
+
/**
|
|
254
|
+
* HTTP path where the MCP endpoint will be mounted.
|
|
255
|
+
*
|
|
256
|
+
* @default "/mcp"
|
|
257
|
+
*/
|
|
258
|
+
path?: string;
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Identity advertised to MCP clients during the initialize handshake. Shows
|
|
262
|
+
* up in Claude Desktop / Cursor's MCP panel.
|
|
263
|
+
*
|
|
264
|
+
* @default { name: "nestia-mcp", version: "1.0.0" }
|
|
265
|
+
*/
|
|
266
|
+
serverInfo?: { name: string; version: string };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** @internal */
|
|
270
|
+
export interface ITool {
|
|
271
|
+
meta: IMcpRouteReflect;
|
|
272
|
+
source: string;
|
|
273
|
+
handler: (args: unknown) => Promise<unknown>;
|
|
274
|
+
validateArgs?: (input: any) => Error | null;
|
|
275
|
+
}
|
|
276
|
+
}
|