Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
2cf436c
feat(all): add scaffolding for deps
wildduck2 Apr 18, 2026
c13f2b8
feat(core): add @McpRoute decorator and McpAdaptor runtime (#1350)
wildduck2 Apr 18, 2026
6b6ac05
feat(sdk): extend analyzer and generator for MCP routes (#1350)
wildduck2 Apr 18, 2026
8d4b312
test(mcp): add MCP feature test suite (#1350)
wildduck2 Apr 18, 2026
90bed54
style(mcp): apply nestia prettier config to MCP files
wildduck2 Apr 18, 2026
1f4f57f
feat(mcp): derive tool description and title from JSDoc comments
wildduck2 Apr 18, 2026
7b3f54f
fix(website): fix nextra version to avoid its bug
samchon May 4, 2026
46c5209
Merge pull request #1456 from samchon/fix/nextra
samchon May 4, 2026
96b015a
feat(core): narrow public McpRoute API to string overload
wildduck2 May 7, 2026
eed6061
feat(core): enforce MCP schema constraints at compile time
wildduck2 May 7, 2026
a22fd46
test(sdk): add compile-fail features for MCP schema constraints
wildduck2 May 7, 2026
3122777
docs(mcp): polish JSDoc across MCP feature files
wildduck2 May 7, 2026
8ffe09c
fix(sdk): register tsconfig-paths when paths exist without baseUrl (#…
Neschadin May 13, 2026
9c5967d
chore: release v11.2.1
samchon May 13, 2026
421ccd9
Keep MCP routes compatible with current master
samchon Jun 11, 2026
54e5388
Keep MCP route contracts stateless and deterministic
samchon Jun 11, 2026
caf32b8
Preserve public McpRoute usage through SDK generation
samchon Jun 11, 2026
151aca3
Align MCP transformer comments with spell check
samchon Jun 11, 2026
9b3af0a
Merge pull request #1454 from wildduck2/feat/mcp-route
samchon Jun 11, 2026
a8d04f1
chore: release v11.3.0
samchon Jun 11, 2026
cbaf6f0
feat(migrate): build the SDK/NestJS generator on @ttsc/factory
samchon Jun 18, 2026
bbc9209
chore(migrate): drop typescript from runtime dependencies
samchon Jun 18, 2026
798298c
fix(migrate): @ttsc/factory ^0.15.8 + clean blank-line spacer
samchon Jun 18, 2026
588ef43
chore(migrate): bump @ttsc/factory to ^0.15.9
samchon Jun 18, 2026
02ade1a
chore(migrate): bump @ttsc/factory to ^0.15.10
samchon Jun 18, 2026
bfefd47
Merge pull request #1505 from samchon/feat/migrate-ttsc-factory
samchon Jun 18, 2026
d721f08
chore(deps): bump ws from 7.5.10 to 7.5.11
dependabot[bot] Jun 18, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion benchmark/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"private": true,
"name": "@samchon/nestia-benchmark",
"version": "11.2.0",
"version": "11.3.0",
"description": "Benchmark Nestia",
"main": "lib/index.js",
"scripts": {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"private": true,
"name": "@nestia/station",
"version": "11.2.0",
"version": "11.3.0",
"description": "Nestia station",
"scripts": {
"build": "pnpm --filter=./packages/* -r build",
Expand Down
2 changes: 1 addition & 1 deletion packages/benchmark/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@nestia/benchmark",
"version": "11.2.0",
"version": "11.3.0",
"description": "NestJS Performance Benchmark Program",
"main": "src/index.ts",
"exports": {
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "nestia",
"version": "11.2.0",
"version": "11.3.0",
"description": "Nestia CLI tool",
"main": "src/index.ts",
"bin": {
Expand Down
7 changes: 4 additions & 3 deletions packages/core/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@nestia/core",
"version": "11.2.0",
"version": "11.3.0",
"description": "Super-fast validation decorators of NestJS",
"main": "src/index.ts",
"exports": {
Expand Down Expand Up @@ -52,7 +52,7 @@
"rxjs": ">=6.0.3",
"tgrid": "^1.1.0",
"typia": "catalog:samchon",
"ws": "^7.5.3"
"ws": "^7.5.11"
},
"peerDependencies": {
"@nestia/fetcher": "workspace:^",
Expand All @@ -63,6 +63,7 @@
"typia": "catalog:samchon"
},
"devDependencies": {
"@modelcontextprotocol/sdk": "catalog:modelcontextprotocol",
"@nestjs/common": "catalog:nestjs",
"@nestjs/core": "catalog:nestjs",
"@nestjs/platform-express": "catalog:nestjs",
Expand Down Expand Up @@ -104,4 +105,4 @@
"./package.json": "./package.json"
}
}
}
}
276 changes: 276 additions & 0 deletions packages/core/src/adaptors/McpAdaptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,276 @@
import {
BadRequestException,
HttpException,
INestApplication,
} from "@nestjs/common";
import { NestContainer } from "@nestjs/core";

import { IMcpRouteReflect } from "../decorators/internal/IMcpRouteReflect";

/**
* MCP (Model Context Protocol) adaptor.
*
* `McpAdaptor` exposes every method decorated with {@link McpRoute} as an MCP
* tool, reachable by LLM clients through a stateless Streamable HTTP endpoint.
*
* At bootstrap the adaptor walks the {@link NestContainer}, collects every
* controller method carrying `"nestia/McpRoute"` metadata, and caches a tool
* registry. A fresh MCP server and transport pair is spun up per incoming HTTP
* request, following MCP stateless Streamable HTTP mode. This adaptor
* intentionally does not manage `Mcp-Session-Id` state.
*
* Typia-generated JSON Schemas flow through unchanged; the Zod-based high-level
* registration API of `McpServer` is bypassed by accessing the low-level
* `.server` handler.
*
* Error mapping follows the MCP specification:
*
* - Unknown tool name: JSON-RPC `-32601`.
* - Typia validation failure: JSON-RPC `-32602` with structured diagnostics.
* - Handler throws {@link HttpException}: success response with `isError: true`,
* so the LLM can read the message and recover.
* - Any other throw: JSON-RPC `-32603`.
*
* @author wildduck - https://github.com/wildduck2
* @example
* ```typescript
* import core from "@nestia/core";
* import { NestFactory } from "@nestjs/core";
*
* const app = await NestFactory.create(AppModule);
* await core.McpAdaptor.upgrade(app, { path: "/mcp" });
* await app.listen(3000);
* ```;
*/
export class McpAdaptor {
/**
* Upgrade a running Nest application with a stateless MCP endpoint.
*
* Scans the application container for methods decorated with {@link McpRoute},
* then registers a catch-all HTTP route at the configured path. Each incoming
* request builds a fresh MCP server + transport on demand, wires the
* registered tools into it, and delegates handling.
*
* Must be called after `NestFactory.create(...)` but before `app.listen(...)`
* if you want the MCP endpoint to be reachable alongside your regular HTTP
* routes.
*
* @param app Running Nest application instance.
* @param options Transport and identity overrides.
*/
public static async upgrade(
app: INestApplication,
options: McpAdaptor.IOptions = {},
): Promise<void> {
if ("sessioned" in (options as Record<string, unknown>))
throw new Error(
"McpAdaptor.upgrade() supports stateless Streamable HTTP only; sessioned mode is not implemented.",
);

const tools: McpAdaptor.ITool[] = [];
const container = (app as any).container as NestContainer;
for (const module of container.getModules().values()) {
for (const wrapper of module.controllers.values()) {
const instance = wrapper.instance;
if (!instance) continue;
const proto = Object.getPrototypeOf(instance);
for (const key of Object.getOwnPropertyNames(proto)) {
if (key === "constructor") continue;
const method = proto[key];
if (typeof method !== "function") continue;

const meta: IMcpRouteReflect | undefined = Reflect.getMetadata(
"nestia/McpRoute",
method,
);
if (!meta) continue;

const params: IMcpRouteReflect.IArgument[] =
Reflect.getMetadata("nestia/McpRoute/Parameters", proto, key) ?? [];
const paramValidator = params.find(
(p) => p.category === "params",
)?.validate;

tools.push({
meta,
source: `${wrapper.metatype?.name ?? proto.constructor?.name ?? "UnknownController"}.${String(key)}`,
validateArgs: paramValidator,
handler: async (args) => method.call(instance, args),
});
}
}
}
assertUniqueTools(tools);

const serverInfo = options.serverInfo ?? {
name: "nestia-mcp",
version: "1.0.0",
};
const {
CallToolRequestSchema,
ErrorCode,
ListToolsRequestSchema,
McpError,
McpServer,
StreamableHTTPServerTransport,
} = await loadMcpSdk();

const http = app.getHttpAdapter();
const route = options.path ?? "/mcp";
http.all(route, async (req: any, res: any) => {
// Stateless mode requires a fresh transport per request; sharing one
// across clients races on internal initialization and request IDs.
const mcp = new McpServer(serverInfo, {
capabilities: { tools: {} },
});
const server = mcp.server;

server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: tools.map((t) => ({
name: t.meta.name,
title: t.meta.title,
description: t.meta.description,
inputSchema: t.meta.inputSchema,
outputSchema: t.meta.outputSchema,
annotations: t.meta.annotations,
})),
}));

server.setRequestHandler(CallToolRequestSchema, async (reqMsg) => {
const tool = tools.find((t) => t.meta.name === reqMsg.params.name);
if (!tool)
throw new McpError(
ErrorCode.MethodNotFound,
`Tool not found: ${reqMsg.params.name}`,
);

const args = reqMsg.params.arguments ?? {};
if (tool.validateArgs) {
const err: Error | null = tool.validateArgs(args);
if (err !== null) {
const body =
err instanceof BadRequestException
? (err.getResponse() as any)
: undefined;
throw new McpError(ErrorCode.InvalidParams, err.message, {
errors: body?.errors,
path: body?.path,
expected: body?.expected,
value: body?.value,
reason: body?.reason,
});
}
}

try {
const result = await tool.handler(args);
if (result === undefined) return { content: [] };
return {
content: [
{
type: "text" as const,
text:
typeof result === "string" ? result : JSON.stringify(result),
},
],
};
} catch (e) {
if (e instanceof HttpException) {
return {
content: [{ type: "text" as const, text: e.message }],
isError: true,
};
}
throw new McpError(
ErrorCode.InternalError,
e instanceof Error ? e.message : "Internal error",
);
}
});

const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined,
enableJsonResponse: true,
});
try {
await mcp.connect(transport);
await transport.handleRequest(req.raw ?? req, res.raw ?? res, req.body);
} finally {
await transport.close().catch(() => {});
await mcp.close().catch(() => {});
}
});
}
}

const assertUniqueTools = (tools: McpAdaptor.ITool[]): void => {
const dict: Map<string, McpAdaptor.ITool[]> = new Map();
for (const tool of tools) {
const array = dict.get(tool.meta.name) ?? [];
array.push(tool);
dict.set(tool.meta.name, array);
}
const duplicated = Array.from(dict.entries()).filter(
([, list]) => list.length > 1,
);
if (duplicated.length === 0) return;
throw new Error(
[
"Duplicated MCP tool names are not allowed.",
...duplicated.map(
([name, list]) =>
` - ${JSON.stringify(name)}: ${list.map((tool) => tool.source).join(", ")}`,
),
].join("\n"),
);
};

const loadMcpSdk = async () => {
try {
const [server, transport, types] = await Promise.all([
import("@modelcontextprotocol/sdk/server/mcp.js"),
import("@modelcontextprotocol/sdk/server/streamableHttp.js"),
import("@modelcontextprotocol/sdk/types.js"),
]);
return {
McpServer: server.McpServer,
StreamableHTTPServerTransport: transport.StreamableHTTPServerTransport,
CallToolRequestSchema: types.CallToolRequestSchema,
ErrorCode: types.ErrorCode,
ListToolsRequestSchema: types.ListToolsRequestSchema,
McpError: types.McpError,
};
} catch {
throw new Error(
"McpAdaptor.upgrade() requires @modelcontextprotocol/sdk. Install it before enabling MCP routes.",
);
}
};

export namespace McpAdaptor {
/** Configuration options for {@link McpAdaptor.upgrade}. */
export interface IOptions {
/**
* HTTP path where the MCP endpoint will be mounted.
*
* @default "/mcp"
*/
path?: string;

/**
* Identity advertised to MCP clients during the initialize handshake. Shows
* up in Claude Desktop / Cursor's MCP panel.
*
* @default { name: "nestia-mcp", version: "1.0.0" }
*/
serverInfo?: { name: string; version: string };
}

/** @internal */
export interface ITool {
meta: IMcpRouteReflect;
source: string;
handler: (args: unknown) => Promise<unknown>;
validateArgs?: (input: any) => Error | null;
}
}
Loading
Loading