mcp-expose 1.0.0
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/CHANGELOG.md +39 -0
- package/LICENSE +21 -0
- package/README.md +708 -0
- package/dist/adonisjs/index.cjs +708 -0
- package/dist/adonisjs/index.cjs.map +1 -0
- package/dist/adonisjs/index.d.cts +68 -0
- package/dist/adonisjs/index.d.ts +68 -0
- package/dist/adonisjs/index.js +684 -0
- package/dist/adonisjs/index.js.map +1 -0
- package/dist/express/index.cjs +789 -0
- package/dist/express/index.cjs.map +1 -0
- package/dist/express/index.d.cts +61 -0
- package/dist/express/index.d.ts +61 -0
- package/dist/express/index.js +763 -0
- package/dist/express/index.js.map +1 -0
- package/dist/fastify/index.cjs +660 -0
- package/dist/fastify/index.cjs.map +1 -0
- package/dist/fastify/index.d.cts +42 -0
- package/dist/fastify/index.d.ts +42 -0
- package/dist/fastify/index.js +635 -0
- package/dist/fastify/index.js.map +1 -0
- package/dist/hono/index.cjs +656 -0
- package/dist/hono/index.cjs.map +1 -0
- package/dist/hono/index.d.cts +44 -0
- package/dist/hono/index.d.ts +44 -0
- package/dist/hono/index.js +630 -0
- package/dist/hono/index.js.map +1 -0
- package/dist/index.cjs +720 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +81 -0
- package/dist/index.d.ts +81 -0
- package/dist/index.js +686 -0
- package/dist/index.js.map +1 -0
- package/dist/koa/index.cjs +739 -0
- package/dist/koa/index.cjs.map +1 -0
- package/dist/koa/index.d.cts +68 -0
- package/dist/koa/index.d.ts +68 -0
- package/dist/koa/index.js +709 -0
- package/dist/koa/index.js.map +1 -0
- package/dist/nestjs/index.cjs +1117 -0
- package/dist/nestjs/index.cjs.map +1 -0
- package/dist/nestjs/index.d.cts +104 -0
- package/dist/nestjs/index.d.ts +104 -0
- package/dist/nestjs/index.js +1079 -0
- package/dist/nestjs/index.js.map +1 -0
- package/dist/server-fzkb-wJo.d.cts +194 -0
- package/dist/server-fzkb-wJo.d.ts +194 -0
- package/package.json +225 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/nestjs/index.ts","../../src/core/dispatch.ts","../../src/core/node.ts","../../src/core/schema.ts","../../src/core/route-tool.ts","../../src/core/server.ts","../../src/nestjs/dto-schema.ts"],"sourcesContent":["import {\n All,\n Controller,\n Inject,\n Injectable,\n Module,\n Req,\n Res,\n SetMetadata,\n UseGuards,\n VERSION_NEUTRAL,\n type CanActivate,\n type DynamicModule,\n type Type,\n} from '@nestjs/common';\nimport { ApplicationConfig, DiscoveryModule, DiscoveryService } from '@nestjs/core';\nimport type { IncomingMessage } from 'node:http';\nimport { createFetchDispatcher } from '../core/dispatch.js';\nimport { loopbackBaseUrl, normalizeHeaders } from '../core/node.js';\nimport { createRouteTool, joinPaths, sanitizeToolName } from '../core/route-tool.js';\nimport { McpServer } from '../core/server.js';\nimport type { JsonSchema, McpServerOptions, McpToolDefinition, RouteToolOptions, ToolContext } from '../core/types.js';\nimport { dtoToJsonSchema, primitiveSchema, type ClassValidatorStorage } from './dto-schema.js';\n\nexport { dtoToJsonSchema } from './dto-schema.js';\n\n// Nest's metadata keys (stable across Nest 8 – 12).\nconst PATH_METADATA = 'path';\nconst METHOD_METADATA = 'method';\nconst ROUTE_ARGS_METADATA = '__routeArguments__';\nconst VERSION_METADATA = '__version__';\nconst REQUEST_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'ALL', 'OPTIONS', 'HEAD'];\nconst PARAMTYPE_BODY = 3;\nconst PARAMTYPE_QUERY = 4;\nconst PARAMTYPE_PARAM = 5;\n\nexport const MCP_TOOL_METADATA = 'mcp-expose:tool';\nexport const MCP_MODULE_OPTIONS = Symbol('MCP_MODULE_OPTIONS');\n\ndeclare const Reflect: {\n getMetadata(key: unknown, target: object, prop?: string | symbol): any;\n};\n\n/**\n * Expose a controller method as an MCP tool.\n *\n * @Get(':id')\n * @McpTool({ description: 'Get a user by id' })\n * findOne(@Param('id') id: string) { ... }\n *\n * The input schema is derived from `@Param()`, `@Query()` and `@Body()` DTOs\n * (class-validator rules and @ApiProperty descriptions), unless you pass\n * `input` / `body` / `query` / `params` yourself.\n */\nexport function McpTool(options: RouteToolOptions = {}): MethodDecorator {\n return SetMetadata(MCP_TOOL_METADATA, options);\n}\n\nexport interface McpModuleOptions extends McpServerOptions {\n /**\n * Path of the MCP endpoint. @default 'mcp'\n * The app's global prefix applies to it unless you exclude it.\n */\n path?: string;\n /** Guards for the MCP endpoint itself, e.g. `[JwtAuthGuard]`. Global guards apply too. */\n guards?: (Type<CanActivate> | CanActivate)[];\n /**\n * Base URL for internal calls. Defaults to loopback on the port the MCP\n * request arrived on.\n */\n baseUrl?: string;\n /**\n * Prefix added to every tool route. Normally not needed: the app's global\n * prefix and URI versioning are detected automatically.\n */\n pathPrefix?: string;\n /** Extra hand-written tools (see `defineTool`). */\n tools?: McpToolDefinition[];\n /**\n * class-validator's metadata storage, used to turn DTOs into JSON Schema.\n * Loaded automatically from `class-validator` when installed.\n */\n classValidatorStorage?: ClassValidatorStorage;\n}\n\nexport interface McpModuleAsyncOptions extends Pick<McpModuleOptions, 'path' | 'guards'> {\n /** Modules that export the providers listed in `inject`. */\n imports?: NonNullable<DynamicModule['imports']>;\n /** Providers passed to `useFactory`. */\n inject?: (string | symbol | Function)[];\n /** Returns the remaining options (everything except `path` and `guards`). */\n useFactory: (\n ...args: any[]\n ) => Omit<McpModuleOptions, 'path' | 'guards'> | Promise<Omit<McpModuleOptions, 'path' | 'guards'>>;\n}\n\ninterface ControllerWrapper {\n metatype?: Function | null;\n instance?: object;\n}\n\n/** Holds the MCP server and discovers `@McpTool()` handlers. Inject it to add tools at runtime. */\nexport class McpService {\n readonly server: McpServer;\n\n constructor(\n private readonly discovery: DiscoveryService,\n private readonly appConfig: ApplicationConfig,\n private readonly options: McpModuleOptions,\n ) {\n this.server = new McpServer(options);\n for (const t of options.tools ?? []) this.server.addTool(t);\n const dispatch = createFetchDispatcher({\n baseUrl: options.baseUrl ?? ((ctx) => loopbackBaseUrl(ctx.raw as IncomingMessage)),\n });\n this.server.onLoad(async () => {\n const storage = options.classValidatorStorage ?? (await loadClassValidator());\n for (const t of this.discover(storage)) {\n this.server.addTool(createRouteTool(t.route, t.options, dispatch, options));\n }\n });\n }\n\n private globalPrefix(): string {\n return this.appConfig.getGlobalPrefix?.() ?? '';\n }\n\n private versionSegment(controller: Function, handler: Function): string | undefined {\n const versioning = (\n this.appConfig as {\n getVersioning?(): { type: number; prefix?: string | false; defaultVersion?: unknown } | undefined;\n }\n ).getVersioning?.();\n if (!versioning || versioning.type !== 0 /* VersioningType.URI */) return undefined;\n let version =\n Reflect.getMetadata(VERSION_METADATA, handler) ??\n Reflect.getMetadata(VERSION_METADATA, controller) ??\n versioning.defaultVersion;\n if (Array.isArray(version)) version = version[0];\n if (version === undefined || typeof version === 'symbol') return undefined;\n const prefix = versioning.prefix === false ? '' : (versioning.prefix ?? 'v');\n return `${prefix}${String(version)}`;\n }\n\n private discover(storage: ClassValidatorStorage | undefined) {\n const found: { route: { method: string; path: string }; options: RouteToolOptions }[] = [];\n for (const wrapper of this.discovery.getControllers() as ControllerWrapper[]) {\n const controller = wrapper.metatype;\n if (!controller?.prototype) continue;\n const proto = controller.prototype;\n const ctrlPaths = toArray(Reflect.getMetadata(PATH_METADATA, controller) ?? '/');\n const ctrlName = controller.name.replace(/Controller$/, '');\n\n for (const key of Object.getOwnPropertyNames(proto)) {\n if (key === 'constructor') continue;\n const handler = Object.getOwnPropertyDescriptor(proto, key)?.value;\n if (typeof handler !== 'function') continue;\n const meta: RouteToolOptions | undefined = Reflect.getMetadata(MCP_TOOL_METADATA, handler);\n if (!meta) continue;\n const method = REQUEST_METHODS[Reflect.getMetadata(METHOD_METADATA, handler) as number] ?? 'GET';\n const methodPath = toArray(Reflect.getMetadata(PATH_METADATA, handler) ?? '/')[0] as string;\n const path = joinPaths(\n this.globalPrefix(),\n this.versionSegment(controller, handler),\n this.options.pathPrefix,\n ctrlPaths[0] as string,\n methodPath,\n );\n found.push({\n route: { method: method === 'ALL' ? 'POST' : method, path },\n options: {\n name: sanitizeToolName(`${toSnake(ctrlName)}_${toSnake(key)}`),\n ...describeArgs(controller, key, storage),\n ...meta,\n },\n });\n }\n }\n return found;\n }\n}\n\n/** Derive params/query/body schemas from the handler's decorated arguments. */\nfunction describeArgs(controller: Function, key: string, storage: ClassValidatorStorage | undefined): RouteToolOptions {\n const args: Record<string, { index: number; data?: unknown }> =\n Reflect.getMetadata(ROUTE_ARGS_METADATA, controller, key) ?? {};\n const types: unknown[] = Reflect.getMetadata('design:paramtypes', controller.prototype, key) ?? [];\n const params: JsonSchema = { type: 'object', properties: {} };\n const query: JsonSchema = { type: 'object', properties: {}, required: [] };\n let body: JsonSchema | undefined;\n\n const schemaFor = (t: unknown): JsonSchema =>\n primitiveSchema(t) ?? (typeof t === 'function' ? dtoToJsonSchema(t, storage) : {});\n\n for (const [k, arg] of Object.entries(args)) {\n const paramtype = Number(k.split(':')[0]);\n const t = types[arg.index];\n const field = typeof arg.data === 'string' ? arg.data : undefined;\n if (paramtype === PARAMTYPE_PARAM && field) {\n params.properties![field] = primitiveSchema(t) ?? { type: 'string' };\n } else if (paramtype === PARAMTYPE_QUERY) {\n if (field) query.properties![field] = primitiveSchema(t) ?? { type: 'string' };\n else Object.assign(query, mergeObject(query, schemaFor(t)));\n } else if (paramtype === PARAMTYPE_BODY) {\n if (field) {\n body ??= { type: 'object', properties: {}, required: [] };\n body.properties![field] = schemaFor(t);\n (body.required as string[]).push(field);\n } else {\n body = mergeObject(body, schemaFor(t));\n }\n }\n }\n const out: RouteToolOptions = { params };\n if (Object.keys(query.properties!).length) out.query = query;\n if (body) out.body = body;\n return out;\n}\n\nfunction mergeObject(a: JsonSchema | undefined, b: JsonSchema): JsonSchema {\n if (!a) return b;\n return {\n type: 'object',\n properties: { ...a.properties, ...b.properties },\n required: [...(a.required ?? []), ...(b.required ?? [])],\n };\n}\n\nasync function loadClassValidator(): Promise<ClassValidatorStorage | undefined> {\n try {\n const cv = (await import('class-validator')) as { getMetadataStorage?: () => ClassValidatorStorage };\n return cv.getMetadataStorage?.();\n } catch {\n return undefined;\n }\n}\n\nfunction toArray<T>(v: T | T[]): T[] {\n return Array.isArray(v) ? v : [v];\n}\n\nfunction toSnake(s: string): string {\n return s\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[-\\s]+/g, '_')\n .toLowerCase();\n}\n\n// Decorators are applied by hand so this package builds without\n// `experimentalDecorators` / `emitDecoratorMetadata`.\nInjectable()(McpService);\nInject(DiscoveryService)(McpService, undefined as never, 0);\nInject(ApplicationConfig)(McpService, undefined as never, 1);\nInject(MCP_MODULE_OPTIONS)(McpService, undefined as never, 2);\n\ninterface AnyReq {\n method: string;\n headers: Record<string, string | string[] | undefined>;\n body?: unknown;\n ip?: string;\n raw?: IncomingMessage;\n socket?: unknown;\n}\ninterface AnyRes {\n // Express\n status?(code: number): AnyRes;\n set?(headers: Record<string, string>): AnyRes;\n // Fastify\n code?(code: number): AnyRes;\n headers?(headers: Record<string, string>): AnyRes;\n send(body?: unknown): unknown;\n end?(body?: unknown): unknown;\n}\n\nfunction createMcpController(options: Pick<McpModuleOptions, 'path' | 'guards'>): Type<unknown> {\n class McpController {\n constructor(readonly mcp: McpService) {}\n\n async handle(req: AnyReq, res: AnyRes) {\n const nodeReq = (req.raw ?? req) as IncomingMessage;\n const headers = normalizeHeaders(req.headers);\n const ctx: ToolContext = { headers, clientIp: req.ip, raw: nodeReq };\n const out = await this.mcp.server.handleHttp({ method: req.method, headers, body: req.body }, ctx);\n if (typeof res.code === 'function') {\n res.code(out.status).headers!(out.headers).send(out.body);\n } else {\n res.status!(out.status).set!(out.headers);\n if (out.body === undefined) res.end!();\n else res.send(out.body);\n }\n }\n }\n const proto = McpController.prototype;\n const descriptor = Object.getOwnPropertyDescriptor(proto, 'handle')!;\n // Version-neutral so URI versioning never moves the endpoint to /v1/mcp.\n Controller({ path: options.path ?? 'mcp', version: VERSION_NEUTRAL })(McpController);\n Inject(McpService)(McpController, undefined as never, 0);\n All()(proto, 'handle', descriptor);\n Req()(proto, 'handle', 0);\n Res()(proto, 'handle', 1);\n if (options.guards?.length) UseGuards(...options.guards)(McpController);\n return McpController;\n}\n\n/**\n * Adds an MCP endpoint to a NestJS app (Express or Fastify platform):\n *\n * @Module({ imports: [McpModule.forRoot({ name: 'shop-api' })] })\n *\n * Remember to exclude the MCP path from your global prefix if you want it at\n * `/mcp`: `app.setGlobalPrefix('api', { exclude: ['mcp'] })`.\n */\nexport class McpModule {\n static forRoot(options: McpModuleOptions): DynamicModule {\n return {\n module: McpModule,\n global: true,\n imports: [DiscoveryModule],\n controllers: [createMcpController(options)],\n providers: [{ provide: MCP_MODULE_OPTIONS, useValue: options }, McpService],\n exports: [McpService],\n };\n }\n\n /**\n * Resolve the options from other providers, e.g. `ConfigService`:\n *\n * McpModule.forRootAsync({\n * imports: [ConfigModule],\n * inject: [ConfigService],\n * useFactory: (config: ConfigService) => ({ name: config.get('APP_NAME') }),\n * })\n *\n * `path` and `guards` define the MCP controller, so they are passed directly.\n */\n static forRootAsync(options: McpModuleAsyncOptions): DynamicModule {\n return {\n module: McpModule,\n global: true,\n imports: [DiscoveryModule, ...(options.imports ?? [])],\n controllers: [createMcpController(options)],\n providers: [\n {\n provide: MCP_MODULE_OPTIONS,\n inject: options.inject ?? [],\n useFactory: async (...args: unknown[]) => ({\n ...(await options.useFactory(...args)),\n ...(options.path ? { path: options.path } : {}),\n }),\n },\n McpService,\n ],\n exports: [McpService],\n };\n }\n}\nModule({})(McpModule);\n","import type { Dispatcher, RouteRequest, ToolContext } from './types.js';\n\nexport function buildUrl(base: string, req: Pick<RouteRequest, 'path' | 'query'>): string {\n const url = new URL(base.replace(/\\/+$/, '') + req.path);\n for (const [k, v] of Object.entries(req.query)) {\n for (const item of Array.isArray(v) ? v : [v]) url.searchParams.append(k, item);\n }\n return url.toString();\n}\n\nexport interface FetchDispatcherOptions {\n /**\n * Base URL of the API, e.g. `http://127.0.0.1:3000` or `https://api.example.com/v1`.\n * A function lets adapters resolve it per call (e.g. from the local port).\n */\n baseUrl: string | ((ctx: ToolContext) => string);\n /** Custom fetch implementation. Defaults to the global `fetch`. */\n fetch?: typeof fetch;\n /** Per-request timeout in ms. @default 30_000 */\n timeoutMs?: number;\n}\n\n/**\n * Dispatches tool calls as real HTTP requests. Used for loopback calls into the\n * host app (Express, Koa, NestJS) and for standalone gateways in front of any API.\n */\nexport function createFetchDispatcher(opts: FetchDispatcherOptions): Dispatcher {\n const doFetch = opts.fetch ?? fetch;\n return async (req, ctx) => {\n const base = typeof opts.baseUrl === 'function' ? opts.baseUrl(ctx) : opts.baseUrl;\n const res = await doFetch(buildUrl(base, req), {\n method: req.method,\n headers: req.headers,\n body:\n req.body === undefined || req.method === 'GET' || req.method === 'HEAD' ? undefined : JSON.stringify(req.body),\n signal: AbortSignal.timeout(opts.timeoutMs ?? 30_000),\n });\n const headers: Record<string, string> = {};\n res.headers.forEach((v, k) => (headers[k] = v));\n return { status: res.status, headers, body: await res.text() };\n };\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { McpHttpResponse } from './server.js';\n\n/** Flatten Node's IncomingHttpHeaders into lower-cased single strings. */\nexport function normalizeHeaders(headers: Record<string, string | string[] | undefined>): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(headers)) {\n if (v === undefined) continue;\n out[k.toLowerCase()] = Array.isArray(v) ? v.join(', ') : String(v);\n }\n return out;\n}\n\n/** Read and return the raw body of a Node request (for frameworks without a JSON body parser). */\nexport function readRawBody(req: IncomingMessage, limit = 4 * 1024 * 1024): Promise<string> {\n return new Promise((resolve, reject) => {\n let size = 0;\n const chunks: Buffer[] = [];\n req.on('data', (c: Buffer) => {\n size += c.length;\n if (size > limit) {\n reject(new Error('Request body too large'));\n req.destroy();\n } else chunks.push(c);\n });\n req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));\n req.on('error', reject);\n });\n}\n\n/** Base URL that reaches the same server the MCP request arrived on. */\nexport function loopbackBaseUrl(req: IncomingMessage): string {\n const socket = req.socket as IncomingMessage['socket'] & {\n encrypted?: boolean;\n server?: { address(): { address: string } | string | null };\n };\n const port = socket.localPort;\n const encrypted = socket.encrypted;\n // Prefer the address the server is bound to: when it listens on all\n // interfaces this yields 127.0.0.1, so internal calls come from loopback\n // (which `trust proxy: 'loopback'` style settings rely on).\n const bound = socket.server?.address();\n let host = (typeof bound === 'object' && bound?.address) || socket.localAddress || '127.0.0.1';\n if (host.startsWith('::ffff:')) host = host.slice(7);\n if (host === '::' || host === '0.0.0.0') host = '127.0.0.1';\n if (host.includes(':')) host = `[${host}]`;\n return `${encrypted ? 'https' : 'http'}://${host}:${port}`;\n}\n\nexport function writeNodeResponse(res: ServerResponse, out: McpHttpResponse): void {\n res.statusCode = out.status;\n for (const [k, v] of Object.entries(out.headers)) res.setHeader(k, v);\n res.end(out.body);\n}\n","import type { JsonSchema, McpToolDefinition, SchemaLike } from './types.js';\n\ninterface StandardSchemaV1 {\n '~standard': {\n validate?: (value: unknown) => unknown;\n jsonSchema?: { input?: (opts: { target: string }) => unknown };\n };\n}\n\nfunction isStandard(s: unknown): s is StandardSchemaV1 {\n return typeof s === 'object' && s !== null && '~standard' in s;\n}\n\n/** Convert any supported schema flavour into a plain JSON Schema object. */\nexport function toJsonSchema(schema: SchemaLike | undefined): JsonSchema | undefined {\n if (schema === undefined || schema === null) return undefined;\n let out: unknown;\n if (isStandard(schema) && typeof schema['~standard'].jsonSchema?.input === 'function') {\n out = schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' });\n } else if (typeof (schema as { toJSONSchema?: unknown }).toJSONSchema === 'function') {\n out = (schema as { toJSONSchema(): unknown }).toJSONSchema();\n } else if (isStandard(schema)) {\n throw new Error(\n 'mcp-expose: this schema library does not support JSON Schema export. Pass a plain JSON Schema instead.',\n );\n } else {\n out = schema;\n }\n const { $schema: _ignored, ...rest } = out as JsonSchema;\n return rest;\n}\n\n/** Build a validator from a Standard Schema, if the input is one. */\nexport function toValidator(schema: SchemaLike | undefined): McpToolDefinition['validate'] {\n if (!isStandard(schema) || typeof schema['~standard'].validate !== 'function') return undefined;\n const validate = schema['~standard'].validate;\n return async (value) => {\n const result = (await validate(value)) as {\n value?: unknown;\n issues?: { message: string; path?: (PropertyKey | { key: PropertyKey })[] }[];\n };\n if (!result.issues) return { ok: true, value: result.value };\n const message = result.issues\n .map((i) => {\n const path = (i.path ?? []).map((p) => (typeof p === 'object' ? String(p.key) : String(p))).join('.');\n return path ? `${path}: ${i.message}` : i.message;\n })\n .join('; ');\n return { ok: false, message };\n };\n}\n\n/** Very small structural check used when no Standard Schema validator exists. */\nexport function checkRequired(schema: JsonSchema, args: Record<string, unknown>): string | undefined {\n const missing = (schema.required ?? []).filter((k) => args[k] === undefined);\n return missing.length ? `Missing required argument(s): ${missing.join(', ')}` : undefined;\n}\n","import { checkRequired, toJsonSchema, toValidator } from './schema.js';\nimport type {\n Dispatcher,\n JsonSchema,\n McpServerOptions,\n McpToolDefinition,\n RouteResponse,\n RouteSpec,\n RouteToolOptions,\n ToolAnnotations,\n ToolContext,\n ToolResult,\n} from './types.js';\n\nexport const DEFAULT_FORWARD_HEADERS = ['authorization', 'cookie', 'x-api-key', 'accept-language'];\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH']);\nconst PARAM_RE = /:([A-Za-z0-9_]+)\\??|\\{([A-Za-z0-9_]+)\\}/g;\n\n/** Names of the path parameters in a route path (`/a/:id/{slug}` -> ['id', 'slug']). */\nexport function pathParams(path: string): string[] {\n return [...path.matchAll(PARAM_RE)].map((m) => (m[1] ?? m[2]) as string);\n}\n\n/**\n * Encode one path-parameter value. Rejects empty, `.` and `..` values: after URL\n * normalisation they would change which route is called (e.g. `/orders/../admin`),\n * letting an agent reach routes that were never exposed as tools.\n */\nfunction encodeSegment(name: string, value: unknown): string {\n const raw = String(value);\n if (raw === '' || raw === '.' || raw === '..') {\n throw new Error(`Invalid value for path parameter \"${name}\": ${JSON.stringify(raw)}`);\n }\n return encodeURIComponent(raw);\n}\n\n/** Replace path placeholders with URL-encoded values. Missing optional params drop their segment. */\nexport function interpolatePath(path: string, values: Record<string, unknown>): string {\n return path\n .replace(/\\/:([A-Za-z0-9_]+)\\?/g, (_, k: string) =>\n values[k] === undefined ? '' : `/${encodeSegment(k, values[k])}`,\n )\n .replace(PARAM_RE, (_, a?: string, b?: string) => {\n const k = (a ?? b) as string;\n return encodeSegment(k, values[k]);\n });\n}\n\n/** Join path segments, normalising slashes. */\nexport function joinPaths(...parts: (string | undefined)[]): string {\n const joined = parts\n .filter((p): p is string => !!p && p !== '/')\n .map((p) => p.replace(/^\\/+|\\/+$/g, ''))\n .filter(Boolean)\n .join('/');\n return `/${joined}`;\n}\n\n/** `GET /users/:id/orders` -> `get_users_by_id_orders` */\nexport function toolNameFromRoute(method: string, path: string): string {\n const segments = path\n .split('/')\n .filter(Boolean)\n .map((s) => {\n const m = /^(?::([A-Za-z0-9_]+)\\??|\\{([A-Za-z0-9_]+)\\})$/.exec(s);\n return m ? `by_${m[1] ?? m[2]}` : s;\n });\n return sanitizeToolName([method.toLowerCase(), ...segments].join('_'));\n}\n\nexport function sanitizeToolName(name: string): string {\n return name\n .replace(/[^A-Za-z0-9_-]+/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_|_$/g, '')\n .slice(0, 64);\n}\n\nfunction defaultAnnotations(method: string): ToolAnnotations {\n switch (method) {\n case 'GET':\n case 'HEAD':\n return { readOnlyHint: true, openWorldHint: false };\n case 'DELETE':\n return { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false };\n case 'PUT':\n return { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false };\n default:\n return { readOnlyHint: false, destructiveHint: false, openWorldHint: false };\n }\n}\n\ninterface ArgMapping {\n params: string[];\n query: Set<string>;\n body: Set<string>;\n /** Body schema is not an object: the whole body is passed under the `body` key. */\n wholeBody: boolean;\n bodyMethod: boolean;\n}\n\n/**\n * Build the flat input schema an agent sees, and remember which argument goes\n * to the path, query string or body when the tool is called.\n */\nexport function buildInputSchema(\n route: RouteSpec,\n opts: RouteToolOptions,\n): { schema: JsonSchema; mapping: ArgMapping } {\n const method = route.method.toUpperCase();\n const params = pathParams(route.path);\n const mapping: ArgMapping = {\n params,\n query: new Set(),\n body: new Set(),\n wholeBody: false,\n bodyMethod: BODY_METHODS.has(method),\n };\n\n if (opts.input) {\n const schema = toJsonSchema(opts.input) as JsonSchema;\n return { schema: { type: 'object', ...schema }, mapping };\n }\n\n const properties: Record<string, JsonSchema> = {};\n const required = new Set<string>();\n\n const paramSchema = toJsonSchema(opts.params);\n for (const p of params) {\n properties[p] = paramSchema?.properties?.[p] ?? { type: 'string', description: `Path parameter \"${p}\"` };\n if (!route.path.includes(`:${p}?`)) required.add(p);\n }\n\n const querySchema = toJsonSchema(opts.query);\n for (const [k, v] of Object.entries(querySchema?.properties ?? {})) {\n properties[k] = v;\n mapping.query.add(k);\n }\n for (const k of querySchema?.required ?? []) required.add(k);\n\n const bodySchema = toJsonSchema(opts.body);\n if (bodySchema) {\n if (bodySchema.properties && (bodySchema.type === undefined || bodySchema.type === 'object')) {\n for (const [k, v] of Object.entries(bodySchema.properties)) {\n properties[k] = v;\n mapping.body.add(k);\n }\n for (const k of bodySchema.required ?? []) required.add(k);\n } else {\n properties.body = bodySchema;\n required.add('body');\n mapping.wholeBody = true;\n }\n }\n\n const schema: JsonSchema = { type: 'object', properties };\n if (required.size) schema.required = [...required];\n return { schema, mapping };\n}\n\nfunction splitArgs(args: Record<string, unknown>, mapping: ArgMapping) {\n const pathValues: Record<string, unknown> = {};\n const query: Record<string, string | string[]> = {};\n let body: Record<string, unknown> | unknown | undefined;\n\n for (const [k, v] of Object.entries(args)) {\n if (v === undefined) continue;\n if (mapping.params.includes(k)) {\n pathValues[k] = v;\n } else if (mapping.wholeBody && k === 'body') {\n body = v;\n } else if (mapping.query.has(k) || (!mapping.body.has(k) && !mapping.bodyMethod)) {\n query[k] = Array.isArray(v) ? v.map(String) : typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v);\n } else {\n body = { ...((body as Record<string, unknown>) ?? {}), [k]: v };\n }\n }\n if (body === undefined && mapping.bodyMethod) body = {};\n return { pathValues, query, body };\n}\n\nexport function responseToResult(res: RouteResponse, maxChars: number): ToolResult {\n let text = res.body;\n if (text.length > maxChars) text = `${text.slice(0, maxChars)}\\n…[truncated ${text.length - maxChars} chars]`;\n const isError = res.status >= 400;\n const result: ToolResult = {\n content: [{ type: 'text', text: isError ? `HTTP ${res.status}\\n${text}` : text || `HTTP ${res.status}` }],\n };\n if (isError) {\n result.isError = true;\n return result;\n }\n if ((res.headers['content-type'] ?? '').includes('json') && text === res.body) {\n try {\n const parsed = JSON.parse(res.body);\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) result.structuredContent = parsed;\n } catch {\n /* not JSON after all */\n }\n }\n return result;\n}\n\nexport function pickForwardHeaders(ctx: ToolContext, names: string[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (const name of names) {\n const v = ctx.headers[name.toLowerCase()];\n if (v !== undefined) out[name.toLowerCase()] = v;\n }\n return out;\n}\n\n/**\n * Turn an HTTP route + options into an MCP tool whose handler calls the route\n * through `dispatch`, so auth guards, validation and rate limits all still apply.\n */\nexport function createRouteTool(\n route: RouteSpec,\n opts: RouteToolOptions,\n dispatch: Dispatcher,\n serverOpts: Pick<McpServerOptions, 'forwardHeaders' | 'maxResponseChars'> = {},\n): McpToolDefinition {\n const method = route.method.toUpperCase();\n const name = sanitizeToolName(opts.name ?? toolNameFromRoute(method, route.path));\n const { schema, mapping } = buildInputSchema(route, opts);\n const forward = serverOpts.forwardHeaders ?? DEFAULT_FORWARD_HEADERS;\n const maxChars = serverOpts.maxResponseChars ?? 100_000;\n\n return {\n name,\n title: opts.title,\n description: opts.description ?? `${method} ${route.path}`,\n inputSchema: schema,\n annotations: { ...defaultAnnotations(method), ...opts.annotations },\n validate: toValidator(opts.input),\n async handler(args, ctx) {\n const missing = opts.input ? undefined : checkRequired(schema, args);\n if (missing) return { isError: true, content: [{ type: 'text', text: missing }] };\n\n const { pathValues, query, body } = splitArgs(args, mapping);\n const headers: Record<string, string> = {\n accept: 'application/json',\n ...pickForwardHeaders(ctx, forward),\n ...opts.headers,\n 'x-mcp-tool': name,\n };\n if (ctx.clientIp) headers['x-forwarded-for'] = ctx.clientIp;\n if (body !== undefined) headers['content-type'] = 'application/json';\n\n let path: string;\n try {\n path = interpolatePath(route.path, pathValues);\n } catch (err) {\n return { isError: true, content: [{ type: 'text', text: (err as Error).message }] };\n }\n const res = await dispatch({ method, path, query, body, headers }, ctx);\n return responseToResult(res, maxChars);\n },\n };\n}\n","import type { McpServerOptions, McpToolDefinition, ToolContext, ToolResult } from './types.js';\n\nexport const SUPPORTED_PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];\nexport const LATEST_PROTOCOL_VERSION = SUPPORTED_PROTOCOL_VERSIONS[0] as string;\n\ntype JsonRpcId = string | number | null;\ninterface JsonRpcRequest {\n jsonrpc: '2.0';\n id?: JsonRpcId;\n method: string;\n params?: Record<string, unknown>;\n}\nexport interface JsonRpcResponse {\n jsonrpc: '2.0';\n id: JsonRpcId;\n result?: unknown;\n error?: { code: number; message: string; data?: unknown };\n}\n\nconst PARSE_ERROR = -32700;\nconst INVALID_REQUEST = -32600;\nconst METHOD_NOT_FOUND = -32601;\nconst INVALID_PARAMS = -32602;\n\nconst ok = (id: JsonRpcId, result: unknown): JsonRpcResponse => ({ jsonrpc: '2.0', id, result });\nconst fail = (id: JsonRpcId, code: number, message: string): JsonRpcResponse => ({\n jsonrpc: '2.0',\n id,\n error: { code, message },\n});\n\n/** Minimal HTTP request/response shapes, so each adapter can bridge its own framework. */\nexport interface McpHttpRequest {\n method: string;\n headers: Record<string, string>;\n /** Parsed JSON body, or the raw string. */\n body: unknown;\n}\nexport interface McpHttpResponse {\n status: number;\n headers: Record<string, string>;\n body?: string;\n}\n\n/**\n * A stateless MCP server speaking the Streamable HTTP transport (JSON responses).\n * Holds the tool registry and answers JSON-RPC messages.\n */\nexport class McpServer {\n private readonly tools = new Map<string, McpToolDefinition>();\n private loaders: (() => void | Promise<void>)[] = [];\n\n constructor(readonly options: McpServerOptions) {}\n\n /** Register a tool. Throws on duplicate names. */\n addTool(tool: McpToolDefinition): this {\n if (this.tools.has(tool.name)) {\n throw new Error(`mcp-expose: duplicate tool name \"${tool.name}\". Set an explicit \\`name\\`.`);\n }\n this.tools.set(tool.name, tool);\n return this;\n }\n\n /** Register a function that adds tools lazily, right before the first MCP request is served. */\n onLoad(loader: () => void | Promise<void>): this {\n this.loaders.push(loader);\n return this;\n }\n\n async listTools(): Promise<McpToolDefinition[]> {\n await this.load();\n return [...this.tools.values()];\n }\n\n private async load() {\n if (!this.loaders.length) return;\n const loaders = this.loaders;\n this.loaders = [];\n for (const l of loaders) await l();\n }\n\n /** Handle one JSON-RPC message (or a batch). Returns null when no response is due. */\n async handleMessage(message: unknown, ctx: ToolContext): Promise<JsonRpcResponse | JsonRpcResponse[] | null> {\n if (Array.isArray(message)) {\n const results = (await Promise.all(message.map((m) => this.handleOne(m, ctx)))).filter(\n (r): r is JsonRpcResponse => r !== null,\n );\n return results.length ? results : null;\n }\n return this.handleOne(message, ctx);\n }\n\n private async handleOne(message: unknown, ctx: ToolContext): Promise<JsonRpcResponse | null> {\n const msg = message as Partial<JsonRpcRequest>;\n if (!msg || typeof msg !== 'object' || msg.jsonrpc !== '2.0') {\n return fail(null, INVALID_REQUEST, 'Invalid JSON-RPC message');\n }\n // Responses from the client or notifications: acknowledge, no reply.\n if (typeof msg.method !== 'string' || msg.id === undefined) return null;\n const id = msg.id;\n const params = msg.params ?? {};\n\n await this.load();\n switch (msg.method) {\n case 'initialize': {\n const requested = params.protocolVersion as string | undefined;\n const protocolVersion =\n requested && SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : LATEST_PROTOCOL_VERSION;\n return ok(id, {\n protocolVersion,\n capabilities: { tools: { listChanged: false } },\n serverInfo: { name: this.options.name, version: this.options.version ?? '1.0.0' },\n ...(this.options.instructions ? { instructions: this.options.instructions } : {}),\n });\n }\n case 'ping':\n return ok(id, {});\n case 'tools/list':\n return ok(id, {\n tools: [...this.tools.values()].map((t) => ({\n name: t.name,\n ...(t.title ? { title: t.title } : {}),\n description: t.description,\n inputSchema: t.inputSchema,\n ...(t.annotations ? { annotations: t.annotations } : {}),\n })),\n });\n case 'tools/call': {\n const tool = this.tools.get(params.name as string);\n if (!tool) return fail(id, INVALID_PARAMS, `Unknown tool: ${String(params.name)}`);\n return ok(id, await this.callTool(tool, (params.arguments ?? {}) as Record<string, unknown>, ctx));\n }\n case 'resources/list':\n return ok(id, { resources: [] });\n case 'prompts/list':\n return ok(id, { prompts: [] });\n default:\n return fail(id, METHOD_NOT_FOUND, `Method not found: ${msg.method}`);\n }\n }\n\n private async callTool(\n tool: McpToolDefinition,\n args: Record<string, unknown>,\n ctx: ToolContext,\n ): Promise<ToolResult> {\n try {\n if (tool.validate) {\n const v = await tool.validate(args);\n if (!v.ok) return { isError: true, content: [{ type: 'text', text: `Invalid arguments: ${v.message}` }] };\n args = v.value as Record<string, unknown>;\n }\n return await tool.handler(args, ctx);\n } catch (err) {\n // Tool failures are reported in-band so the model can react to them.\n return { isError: true, content: [{ type: 'text', text: `Tool error: ${(err as Error).message}` }] };\n }\n }\n\n /** Check the Origin header (DNS rebinding protection). */\n isOriginAllowed(origin: string | undefined): boolean {\n if (!origin) return true;\n const allowed = this.options.allowedOrigins;\n if (allowed === '*') return true;\n return (allowed ?? []).includes(origin);\n }\n\n /**\n * Framework-neutral Streamable HTTP handler. Adapters convert their request\n * into McpHttpRequest, call this, and write the McpHttpResponse back.\n */\n async handleHttp(req: McpHttpRequest, ctx: ToolContext): Promise<McpHttpResponse> {\n const json = { 'content-type': 'application/json' };\n if (!this.isOriginAllowed(req.headers.origin)) {\n return { status: 403, headers: json, body: JSON.stringify(fail(null, INVALID_REQUEST, 'Origin not allowed')) };\n }\n if (req.method.toUpperCase() !== 'POST') {\n // Stateless server: no standalone SSE stream and no sessions to delete.\n return { status: 405, headers: { allow: 'POST' } };\n }\n let body = req.body;\n if (typeof body === 'string' || body instanceof Uint8Array) {\n try {\n body = JSON.parse(typeof body === 'string' ? body : new TextDecoder().decode(body));\n } catch {\n return { status: 400, headers: json, body: JSON.stringify(fail(null, PARSE_ERROR, 'Parse error')) };\n }\n }\n const response = await this.handleMessage(body, ctx);\n if (response === null) return { status: 202, headers: {} };\n return { status: 200, headers: json, body: JSON.stringify(response) };\n }\n}\n","import type { JsonSchema } from '../core/types.js';\n\ninterface ValidationMetadata {\n type: string;\n name?: string;\n propertyName: string;\n constraints?: unknown[];\n each?: boolean;\n}\n\nexport interface ClassValidatorStorage {\n getTargetValidationMetadatas(\n target: Function,\n targetSchema: string,\n always: boolean,\n strictGroups: boolean,\n ): ValidationMetadata[];\n}\n\ndeclare const Reflect: { getMetadata?(key: string, target: object, prop?: string | symbol): unknown };\n\nconst PRIMITIVES = new Map<unknown, JsonSchema>([\n [String, { type: 'string' }],\n [Number, { type: 'number' }],\n [Boolean, { type: 'boolean' }],\n [Date, { type: 'string', format: 'date-time' }],\n [Array, { type: 'array' }],\n [Object, { type: 'object' }],\n]);\n\nexport function primitiveSchema(type: unknown): JsonSchema | undefined {\n const s = PRIMITIVES.get(type);\n return s ? { ...s } : undefined;\n}\n\n/** Apply one class-validator rule to a (property or `items`) schema. */\nfunction applyRule(s: JsonSchema, name: string, c: unknown[] = []): void {\n switch (name) {\n case 'isString':\n s.type = 'string';\n break;\n case 'isNumber':\n case 'isNumberString':\n s.type = name === 'isNumber' ? 'number' : 'string';\n break;\n case 'isInt':\n s.type = 'integer';\n break;\n case 'isBoolean':\n s.type = 'boolean';\n break;\n case 'isDate':\n case 'isDateString':\n case 'isISO8601':\n s.type = 'string';\n s.format = 'date-time';\n break;\n case 'isEmail':\n s.type = 'string';\n s.format = 'email';\n break;\n case 'isUrl':\n s.type = 'string';\n s.format = 'uri';\n break;\n case 'isUUID':\n s.type = 'string';\n s.format = 'uuid';\n break;\n case 'isPositive':\n s.exclusiveMinimum = 0;\n break;\n case 'isNegative':\n s.exclusiveMaximum = 0;\n break;\n case 'min':\n s.minimum = c[0];\n break;\n case 'max':\n s.maximum = c[0];\n break;\n case 'minLength':\n s.minLength = c[0];\n break;\n case 'maxLength':\n s.maxLength = c[0];\n break;\n case 'length':\n s.minLength = c[0];\n if (c[1] !== undefined) s.maxLength = c[1];\n break;\n case 'matches':\n if (c[0] instanceof RegExp) s.pattern = c[0].source;\n break;\n case 'isIn':\n s.enum = c[0] as unknown[];\n break;\n case 'isEnum':\n s.enum = (c[1] as unknown[]) ?? Object.values(c[0] as object);\n break;\n case 'isNotEmpty':\n if (s.type === 'string') s.minLength = Math.max(1, Number(s.minLength ?? 0));\n break;\n case 'isArray':\n s.type = 'array';\n break;\n case 'arrayMinSize':\n s.minItems = c[0];\n break;\n case 'arrayMaxSize':\n s.maxItems = c[0];\n break;\n case 'isObject':\n s.type = 'object';\n break;\n }\n}\n\n/**\n * Derive a JSON Schema from a class-validator DTO. Only used to *describe* the\n * tool to the agent: the real validation still happens in your ValidationPipe.\n */\nexport function dtoToJsonSchema(dto: Function, storage: ClassValidatorStorage | undefined, depth = 0): JsonSchema {\n const schema: JsonSchema = { type: 'object', properties: {} };\n if (!storage || depth > 5) return schema;\n const metas = storage.getTargetValidationMetadatas(dto, '', true, false);\n const properties: Record<string, JsonSchema> = {};\n const optional = new Set<string>();\n\n for (const m of metas) {\n const prop = (properties[m.propertyName] ??= initial(dto, m.propertyName));\n if (m.type === 'conditionalValidation' && m.name === 'isOptional') {\n optional.add(m.propertyName);\n } else if (m.type === 'nestedValidation') {\n const nestedType = Reflect.getMetadata?.('design:type', dto.prototype, m.propertyName);\n if (typeof nestedType === 'function' && !PRIMITIVES.has(nestedType)) {\n Object.assign(prop, dtoToJsonSchema(nestedType, storage, depth + 1));\n }\n } else if (m.type === 'customValidation' && m.name) {\n if (m.each) {\n prop.type = 'array';\n const items = (prop.items ??= {}) as JsonSchema;\n applyRule(items, m.name, m.constraints);\n } else {\n applyRule(prop, m.name, m.constraints);\n }\n }\n }\n\n schema.properties = properties;\n const required = Object.keys(properties).filter((p) => !optional.has(p));\n if (required.length) schema.required = required;\n return schema;\n}\n\nfunction initial(dto: Function, prop: string): JsonSchema {\n const designType = Reflect.getMetadata?.('design:type', dto.prototype, prop);\n const s: JsonSchema = primitiveSchema(designType) ?? {};\n // Pick up @nestjs/swagger @ApiProperty() descriptions/examples when present.\n const api = Reflect.getMetadata?.('swagger/apiModelProperties', dto.prototype, prop) as\n { description?: string; example?: unknown; enum?: unknown } | undefined;\n if (api?.description) s.description = api.description;\n if (api?.example !== undefined) s.examples = [api.example];\n if (Array.isArray(api?.enum)) s.enum = api.enum;\n return s;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;oBAcO;AACP,kBAAqE;;;ACb9D,SAASA,SAASC,MAAcC,KAAyC;AAC9E,QAAMC,MAAM,IAAIC,IAAIH,KAAKI,QAAQ,QAAQ,EAAA,IAAMH,IAAII,IAAI;AACvD,aAAW,CAACC,GAAGC,CAAAA,KAAMC,OAAOC,QAAQR,IAAIS,KAAK,GAAG;AAC9C,eAAWC,QAAQC,MAAMC,QAAQN,CAAAA,IAAKA,IAAI;MAACA;MAAIL,KAAIY,aAAaC,OAAOT,GAAGK,IAAAA;EAC5E;AACA,SAAOT,IAAIc,SAAQ;AACrB;AANgBjB;AAwBT,SAASkB,sBAAsBC,MAA4B;AAChE,QAAMC,UAAUD,KAAKE,SAASA;AAC9B,SAAO,OAAOnB,KAAKoB,QAAAA;AACjB,UAAMrB,OAAO,OAAOkB,KAAKI,YAAY,aAAaJ,KAAKI,QAAQD,GAAAA,IAAOH,KAAKI;AAC3E,UAAMC,MAAM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AAMlE,QAAQ2I,WAAU,GAAIzE,IAAAA;YAChC,GAAIlE,QAAQ2D,OAAO;cAAEA,MAAM3D,QAAQ2D;YAAK,IAAI,CAAC;UAC/C,IAHY;QAId;QACAzD;;MAEFsI,SAAS;QAACtI;;IACZ;EACF;AACF;IACA0I,sBAAO,CAAC,CAAA,EAAGd,SAAAA;","names":["buildUrl","base","req","url","URL","replace","path","k","v","Object","entries","query","item","Array","isArray","searchParams","append","toString","createFetchDispatcher","opts","doFetch","fetch","ctx","baseUrl","res","method","headers","body","undefined","JSON","stringify","signal","AbortSignal","timeout","timeoutMs","forEach","status","text","normalizeHeaders","headers","out","k","v","Object","entries","undefined","toLowerCase","Array","isArray","join","String","loopbackBaseUrl","req","socket","port","localPort","encrypted","bound","server","address","host","localAddress","startsWith","slice","includes","isStandard","s","toJsonSchema","schema","undefined","out","jsonSchema","input","target","toJSONSchema","Error","$schema","_ignored","rest","toValidator","validate","value","result","issues","ok","message","map","i","path","p","String","key","join","checkRequired","args","missing","required","filter","k","length","DEFAULT_FORWARD_HEADERS","BODY_METHODS","Set","PARAM_RE","pathParams","path","matchAll","map","m","encodeSegment","name","value","raw","String","Error","JSON","stringify","encodeURIComponent","interpolatePath","values","replace","_","k","undefined","a","b","joinPaths","parts","joined","filter","p","Boolean","join","toolNameFromRoute","method","segments","split","s","exec","sanitizeToolName","toLowerCase","slice","defaultAnnotations","readOnlyHint","openWorldHint","destructiveHint","idempotentHint","buildInputSchema","route","opts","toUpperCase","params","mapping","query","body","wholeBody","bodyMethod","has","input","schema","toJsonSchema","type","properties","required","paramSchema","description","includes","add","querySchema","v","Object","entries","bodySchema","size","splitArgs","args","pathValues","Array","isArray","responseToResult","res","maxChars","text","length","isError","status","result","content","headers","parsed","parse","structuredContent","pickForwardHeaders","ctx","names","out","createRouteTool","dispatch","serverOpts","forward","forwardHeaders","maxResponseChars","title","inputSchema","annotations","validate","toValidator","handler","missing","checkRequired","accept","clientIp","err","message","SUPPORTED_PROTOCOL_VERSIONS","LATEST_PROTOCOL_VERSION","PARSE_ERROR","INVALID_REQUEST","METHOD_NOT_FOUND","INVALID_PARAMS","ok","id","result","jsonrpc","fail","code","message","error","McpServer","tools","Map","loaders","options","addTool","tool","has","name","Error","set","onLoad","loader","push","listTools","load","values","length","l","handleMessage","ctx","Array","isArray","results","Promise","all","map","m","handleOne","filter","r","msg","method","undefined","params","requested","protocolVersion","includes","capabilities","listChanged","serverInfo","version","instructions","t","title","description","inputSchema","annotations","get","String","callTool","arguments","resources","prompts","args","validate","v","isError","content","type","text","value","handler","err","isOriginAllowed","origin","allowed","allowedOrigins","handleHttp","req","json","headers","status","body","JSON","stringify","toUpperCase","allow","Uint8Array","parse","TextDecoder","decode","response","PRIMITIVES","Map","String","type","Number","Boolean","Date","format","Array","Object","primitiveSchema","s","get","undefined","applyRule","name","c","exclusiveMinimum","exclusiveMaximum","minimum","maximum","minLength","maxLength","RegExp","pattern","source","enum","values","Math","max","minItems","maxItems","dtoToJsonSchema","dto","storage","depth","schema","properties","metas","getTargetValidationMetadatas","optional","Set","m","prop","propertyName","initial","add","nestedType","Reflect","getMetadata","prototype","has","assign","each","items","constraints","required","keys","filter","p","length","designType","api","description","example","examples","isArray","PATH_METADATA","METHOD_METADATA","ROUTE_ARGS_METADATA","VERSION_METADATA","REQUEST_METHODS","PARAMTYPE_BODY","PARAMTYPE_QUERY","PARAMTYPE_PARAM","MCP_TOOL_METADATA","MCP_MODULE_OPTIONS","Symbol","McpTool","options","SetMetadata","McpService","server","discovery","appConfig","McpServer","t","tools","addTool","dispatch","createFetchDispatcher","baseUrl","ctx","loopbackBaseUrl","raw","onLoad","storage","classValidatorStorage","loadClassValidator","discover","createRouteTool","route","globalPrefix","getGlobalPrefix","versionSegment","controller","handler","versioning","getVersioning","type","undefined","version","Reflect","getMetadata","defaultVersion","Array","isArray","prefix","String","found","wrapper","getControllers","metatype","prototype","proto","ctrlPaths","toArray","ctrlName","name","replace","key","Object","getOwnPropertyNames","getOwnPropertyDescriptor","value","meta","method","methodPath","path","joinPaths","pathPrefix","push","sanitizeToolName","toSnake","describeArgs","args","types","params","properties","query","required","body","schemaFor","primitiveSchema","dtoToJsonSchema","k","arg","entries","paramtype","Number","split","index","field","data","assign","mergeObject","out","keys","length","a","b","cv","getMetadataStorage","v","s","toLowerCase","Injectable","Inject","DiscoveryService","ApplicationConfig","createMcpController","McpController","mcp","handle","req","res","nodeReq","headers","normalizeHeaders","clientIp","ip","handleHttp","code","status","send","set","end","descriptor","Controller","VERSION_NEUTRAL","All","Req","Res","guards","UseGuards","McpModule","forRoot","module","global","imports","DiscoveryModule","controllers","providers","provide","useValue","exports","forRootAsync","inject","useFactory","Module"]}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { Type, CanActivate, DynamicModule } from '@nestjs/common';
|
|
2
|
+
import { DiscoveryService, ApplicationConfig } from '@nestjs/core';
|
|
3
|
+
import { J as JsonSchema, M as McpServerOptions, a as McpToolDefinition, b as McpServer, R as RouteToolOptions } from '../server-fzkb-wJo.cjs';
|
|
4
|
+
|
|
5
|
+
interface ValidationMetadata {
|
|
6
|
+
type: string;
|
|
7
|
+
name?: string;
|
|
8
|
+
propertyName: string;
|
|
9
|
+
constraints?: unknown[];
|
|
10
|
+
each?: boolean;
|
|
11
|
+
}
|
|
12
|
+
interface ClassValidatorStorage {
|
|
13
|
+
getTargetValidationMetadatas(target: Function, targetSchema: string, always: boolean, strictGroups: boolean): ValidationMetadata[];
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Derive a JSON Schema from a class-validator DTO. Only used to *describe* the
|
|
17
|
+
* tool to the agent: the real validation still happens in your ValidationPipe.
|
|
18
|
+
*/
|
|
19
|
+
declare function dtoToJsonSchema(dto: Function, storage: ClassValidatorStorage | undefined, depth?: number): JsonSchema;
|
|
20
|
+
|
|
21
|
+
declare const MCP_TOOL_METADATA = "mcp-expose:tool";
|
|
22
|
+
declare const MCP_MODULE_OPTIONS: unique symbol;
|
|
23
|
+
/**
|
|
24
|
+
* Expose a controller method as an MCP tool.
|
|
25
|
+
*
|
|
26
|
+
* @Get(':id')
|
|
27
|
+
* @McpTool({ description: 'Get a user by id' })
|
|
28
|
+
* findOne(@Param('id') id: string) { ... }
|
|
29
|
+
*
|
|
30
|
+
* The input schema is derived from `@Param()`, `@Query()` and `@Body()` DTOs
|
|
31
|
+
* (class-validator rules and @ApiProperty descriptions), unless you pass
|
|
32
|
+
* `input` / `body` / `query` / `params` yourself.
|
|
33
|
+
*/
|
|
34
|
+
declare function McpTool(options?: RouteToolOptions): MethodDecorator;
|
|
35
|
+
interface McpModuleOptions extends McpServerOptions {
|
|
36
|
+
/**
|
|
37
|
+
* Path of the MCP endpoint. @default 'mcp'
|
|
38
|
+
* The app's global prefix applies to it unless you exclude it.
|
|
39
|
+
*/
|
|
40
|
+
path?: string;
|
|
41
|
+
/** Guards for the MCP endpoint itself, e.g. `[JwtAuthGuard]`. Global guards apply too. */
|
|
42
|
+
guards?: (Type<CanActivate> | CanActivate)[];
|
|
43
|
+
/**
|
|
44
|
+
* Base URL for internal calls. Defaults to loopback on the port the MCP
|
|
45
|
+
* request arrived on.
|
|
46
|
+
*/
|
|
47
|
+
baseUrl?: string;
|
|
48
|
+
/**
|
|
49
|
+
* Prefix added to every tool route. Normally not needed: the app's global
|
|
50
|
+
* prefix and URI versioning are detected automatically.
|
|
51
|
+
*/
|
|
52
|
+
pathPrefix?: string;
|
|
53
|
+
/** Extra hand-written tools (see `defineTool`). */
|
|
54
|
+
tools?: McpToolDefinition[];
|
|
55
|
+
/**
|
|
56
|
+
* class-validator's metadata storage, used to turn DTOs into JSON Schema.
|
|
57
|
+
* Loaded automatically from `class-validator` when installed.
|
|
58
|
+
*/
|
|
59
|
+
classValidatorStorage?: ClassValidatorStorage;
|
|
60
|
+
}
|
|
61
|
+
interface McpModuleAsyncOptions extends Pick<McpModuleOptions, 'path' | 'guards'> {
|
|
62
|
+
/** Modules that export the providers listed in `inject`. */
|
|
63
|
+
imports?: NonNullable<DynamicModule['imports']>;
|
|
64
|
+
/** Providers passed to `useFactory`. */
|
|
65
|
+
inject?: (string | symbol | Function)[];
|
|
66
|
+
/** Returns the remaining options (everything except `path` and `guards`). */
|
|
67
|
+
useFactory: (...args: any[]) => Omit<McpModuleOptions, 'path' | 'guards'> | Promise<Omit<McpModuleOptions, 'path' | 'guards'>>;
|
|
68
|
+
}
|
|
69
|
+
/** Holds the MCP server and discovers `@McpTool()` handlers. Inject it to add tools at runtime. */
|
|
70
|
+
declare class McpService {
|
|
71
|
+
private readonly discovery;
|
|
72
|
+
private readonly appConfig;
|
|
73
|
+
private readonly options;
|
|
74
|
+
readonly server: McpServer;
|
|
75
|
+
constructor(discovery: DiscoveryService, appConfig: ApplicationConfig, options: McpModuleOptions);
|
|
76
|
+
private globalPrefix;
|
|
77
|
+
private versionSegment;
|
|
78
|
+
private discover;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Adds an MCP endpoint to a NestJS app (Express or Fastify platform):
|
|
82
|
+
*
|
|
83
|
+
* @Module({ imports: [McpModule.forRoot({ name: 'shop-api' })] })
|
|
84
|
+
*
|
|
85
|
+
* Remember to exclude the MCP path from your global prefix if you want it at
|
|
86
|
+
* `/mcp`: `app.setGlobalPrefix('api', { exclude: ['mcp'] })`.
|
|
87
|
+
*/
|
|
88
|
+
declare class McpModule {
|
|
89
|
+
static forRoot(options: McpModuleOptions): DynamicModule;
|
|
90
|
+
/**
|
|
91
|
+
* Resolve the options from other providers, e.g. `ConfigService`:
|
|
92
|
+
*
|
|
93
|
+
* McpModule.forRootAsync({
|
|
94
|
+
* imports: [ConfigModule],
|
|
95
|
+
* inject: [ConfigService],
|
|
96
|
+
* useFactory: (config: ConfigService) => ({ name: config.get('APP_NAME') }),
|
|
97
|
+
* })
|
|
98
|
+
*
|
|
99
|
+
* `path` and `guards` define the MCP controller, so they are passed directly.
|
|
100
|
+
*/
|
|
101
|
+
static forRootAsync(options: McpModuleAsyncOptions): DynamicModule;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export { MCP_MODULE_OPTIONS, MCP_TOOL_METADATA, McpModule, type McpModuleAsyncOptions, type McpModuleOptions, McpService, McpTool, dtoToJsonSchema };
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { Type, CanActivate, DynamicModule } from '@nestjs/common';
|
|
2
|
+
import { DiscoveryService, ApplicationConfig } from '@nestjs/core';
|
|
3
|
+
import { J as JsonSchema, M as McpServerOptions, a as McpToolDefinition, b as McpServer, R as RouteToolOptions } from '../server-fzkb-wJo.js';
|
|
4
|
+
|
|
5
|
+
interface ValidationMetadata {
|
|
6
|
+
type: string;
|
|
7
|
+
name?: string;
|
|
8
|
+
propertyName: string;
|
|
9
|
+
constraints?: unknown[];
|
|
10
|
+
each?: boolean;
|
|
11
|
+
}
|
|
12
|
+
interface ClassValidatorStorage {
|
|
13
|
+
getTargetValidationMetadatas(target: Function, targetSchema: string, always: boolean, strictGroups: boolean): ValidationMetadata[];
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Derive a JSON Schema from a class-validator DTO. Only used to *describe* the
|
|
17
|
+
* tool to the agent: the real validation still happens in your ValidationPipe.
|
|
18
|
+
*/
|
|
19
|
+
declare function dtoToJsonSchema(dto: Function, storage: ClassValidatorStorage | undefined, depth?: number): JsonSchema;
|
|
20
|
+
|
|
21
|
+
declare const MCP_TOOL_METADATA = "mcp-expose:tool";
|
|
22
|
+
declare const MCP_MODULE_OPTIONS: unique symbol;
|
|
23
|
+
/**
|
|
24
|
+
* Expose a controller method as an MCP tool.
|
|
25
|
+
*
|
|
26
|
+
* @Get(':id')
|
|
27
|
+
* @McpTool({ description: 'Get a user by id' })
|
|
28
|
+
* findOne(@Param('id') id: string) { ... }
|
|
29
|
+
*
|
|
30
|
+
* The input schema is derived from `@Param()`, `@Query()` and `@Body()` DTOs
|
|
31
|
+
* (class-validator rules and @ApiProperty descriptions), unless you pass
|
|
32
|
+
* `input` / `body` / `query` / `params` yourself.
|
|
33
|
+
*/
|
|
34
|
+
declare function McpTool(options?: RouteToolOptions): MethodDecorator;
|
|
35
|
+
interface McpModuleOptions extends McpServerOptions {
|
|
36
|
+
/**
|
|
37
|
+
* Path of the MCP endpoint. @default 'mcp'
|
|
38
|
+
* The app's global prefix applies to it unless you exclude it.
|
|
39
|
+
*/
|
|
40
|
+
path?: string;
|
|
41
|
+
/** Guards for the MCP endpoint itself, e.g. `[JwtAuthGuard]`. Global guards apply too. */
|
|
42
|
+
guards?: (Type<CanActivate> | CanActivate)[];
|
|
43
|
+
/**
|
|
44
|
+
* Base URL for internal calls. Defaults to loopback on the port the MCP
|
|
45
|
+
* request arrived on.
|
|
46
|
+
*/
|
|
47
|
+
baseUrl?: string;
|
|
48
|
+
/**
|
|
49
|
+
* Prefix added to every tool route. Normally not needed: the app's global
|
|
50
|
+
* prefix and URI versioning are detected automatically.
|
|
51
|
+
*/
|
|
52
|
+
pathPrefix?: string;
|
|
53
|
+
/** Extra hand-written tools (see `defineTool`). */
|
|
54
|
+
tools?: McpToolDefinition[];
|
|
55
|
+
/**
|
|
56
|
+
* class-validator's metadata storage, used to turn DTOs into JSON Schema.
|
|
57
|
+
* Loaded automatically from `class-validator` when installed.
|
|
58
|
+
*/
|
|
59
|
+
classValidatorStorage?: ClassValidatorStorage;
|
|
60
|
+
}
|
|
61
|
+
interface McpModuleAsyncOptions extends Pick<McpModuleOptions, 'path' | 'guards'> {
|
|
62
|
+
/** Modules that export the providers listed in `inject`. */
|
|
63
|
+
imports?: NonNullable<DynamicModule['imports']>;
|
|
64
|
+
/** Providers passed to `useFactory`. */
|
|
65
|
+
inject?: (string | symbol | Function)[];
|
|
66
|
+
/** Returns the remaining options (everything except `path` and `guards`). */
|
|
67
|
+
useFactory: (...args: any[]) => Omit<McpModuleOptions, 'path' | 'guards'> | Promise<Omit<McpModuleOptions, 'path' | 'guards'>>;
|
|
68
|
+
}
|
|
69
|
+
/** Holds the MCP server and discovers `@McpTool()` handlers. Inject it to add tools at runtime. */
|
|
70
|
+
declare class McpService {
|
|
71
|
+
private readonly discovery;
|
|
72
|
+
private readonly appConfig;
|
|
73
|
+
private readonly options;
|
|
74
|
+
readonly server: McpServer;
|
|
75
|
+
constructor(discovery: DiscoveryService, appConfig: ApplicationConfig, options: McpModuleOptions);
|
|
76
|
+
private globalPrefix;
|
|
77
|
+
private versionSegment;
|
|
78
|
+
private discover;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Adds an MCP endpoint to a NestJS app (Express or Fastify platform):
|
|
82
|
+
*
|
|
83
|
+
* @Module({ imports: [McpModule.forRoot({ name: 'shop-api' })] })
|
|
84
|
+
*
|
|
85
|
+
* Remember to exclude the MCP path from your global prefix if you want it at
|
|
86
|
+
* `/mcp`: `app.setGlobalPrefix('api', { exclude: ['mcp'] })`.
|
|
87
|
+
*/
|
|
88
|
+
declare class McpModule {
|
|
89
|
+
static forRoot(options: McpModuleOptions): DynamicModule;
|
|
90
|
+
/**
|
|
91
|
+
* Resolve the options from other providers, e.g. `ConfigService`:
|
|
92
|
+
*
|
|
93
|
+
* McpModule.forRootAsync({
|
|
94
|
+
* imports: [ConfigModule],
|
|
95
|
+
* inject: [ConfigService],
|
|
96
|
+
* useFactory: (config: ConfigService) => ({ name: config.get('APP_NAME') }),
|
|
97
|
+
* })
|
|
98
|
+
*
|
|
99
|
+
* `path` and `guards` define the MCP controller, so they are passed directly.
|
|
100
|
+
*/
|
|
101
|
+
static forRootAsync(options: McpModuleAsyncOptions): DynamicModule;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export { MCP_MODULE_OPTIONS, MCP_TOOL_METADATA, McpModule, type McpModuleAsyncOptions, type McpModuleOptions, McpService, McpTool, dtoToJsonSchema };
|