@lark-apaas/nestjs-mcp 0.1.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/LICENSE +13 -0
- package/README.md +165 -0
- package/bin/miaoda-mcp.cjs +3 -0
- package/dist/cli.cjs +231618 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/index.cjs +1753 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +360 -0
- package/dist/index.d.ts +360 -0
- package/dist/index.js +1704 -0
- package/dist/index.js.map +1 -0
- package/package.json +73 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/constants.ts","../src/errors.ts","../src/decorators/mcp-tools.decorator.ts","../src/decorators/mcp-tool.decorator.ts","../src/decorators/mcp-ui-resource.decorator.ts","../src/mcp.module.ts","../src/controllers/mcp-manifest.controller.ts","../src/services/mcp-manifest.service.ts","../src/manifest.ts","../src/server-factory.ts","../../../../node_modules/@modelcontextprotocol/ext-apps/dist/src/server/index.js","../src/services/mcp-registry.service.ts","../src/metadata.ts","../src/skill.ts","../src/source-locations.ts","../src/controllers/mcp.controller.ts","../src/services/mcp-server.service.ts","../src/ui-template.ts"],"sourcesContent":["export * from './constants';\nexport type { McpRawShape, McpSchema, Infer, McpUser, McpContext, McpContentBlock, McpToolResult, McpToolUiOptions, McpToolOptions, McpToolsOptions, McpUiResourceOptions, McpToolHandler, McpUiResourceHandler, McpModuleOptions } from './types';\nexport * from './errors';\nexport * from './decorators';\nexport { McpModule } from './mcp.module';\nexport { readMcpUiTemplate } from './ui-template';\n\nexport type { McpCatalog, McpSkill, McpSources, McpSourceLocation } from './types';\n","/**\n * MCP 端点相对应用根的挂载路径。\n *\n * 与 `/__innerapi__/automation/invoke` 同属平台内部端点:不走 `/api/*` 的 CSRF 与响应包装,\n * 由 MCP Gateway 完成凭证校验后以当前用户身份转发到此路径。\n * 应用设置了 `CLIENT_BASE_PATH`(如 `/app/<appId>`)时,完整路径为 `${CLIENT_BASE_PATH}/__innerapi__/mcp`。\n */\nexport const MCP_ENDPOINT_PATH = '/__innerapi__/mcp';\n\n/**\n * Nest 控制器路径(不带前导斜杠,与仓库内其他 `__innerapi__` 控制器写法一致)。\n */\nexport const MCP_CONTROLLER_PATH = '__innerapi__/mcp';\n\n/**\n * 清单文件在用户工程内的相对路径(相对 process.cwd())。\n *\n * 代码是唯一事实来源,清单由 SDK 在开发态启动时以及 `miaoda-mcp validate` 命令导出,\n * 用于离线校验;在线面板通过运行时 manifest 接口读取。\n */\nexport const MCP_MANIFEST_PATH = '.spark/mcp/manifest.json';\n\n/**\n * MCP Apps 单文件 HTML 产物目录(相对 process.cwd()),由构建预设产出 `<entry>.html`。\n */\nexport const MCP_UI_DIST_DIR = 'dist/mcp-ui';\n\n/**\n * MCP Apps 资源 URI 约定前缀。\n */\nexport const MCP_UI_RESOURCE_SCHEME = 'ui://';\n\n/** 类装饰器元数据键:标记一个类为 MCP 工具类 */\nexport const MCP_TOOLS_METADATA_KEY = 'mcp:tools';\n/** 方法装饰器元数据键:标记一个方法为 MCP 工具 */\nexport const MCP_TOOL_METADATA_KEY = 'mcp:tool';\n/** 方法装饰器元数据键:标记一个方法为 MCP Apps 资源 */\nexport const MCP_UI_RESOURCE_METADATA_KEY = 'mcp:ui-resource';\n\n/** 模块配置注入令牌 */\nexport const MCP_MODULE_OPTIONS = Symbol('MCP_MODULE_OPTIONS');\n\n/** 服务端默认名称(可通过模块配置覆盖) */\nexport const MCP_DEFAULT_SERVER_NAME = 'miaoda-app';\n/** 服务端默认版本 */\nexport const MCP_DEFAULT_SERVER_VERSION = '1.0.0';\n\n/** 清单文件格式版本 */\nexport const MCP_MANIFEST_VERSION = 1;\n\n/**\n * 工具名合法字符(MCP 规范 SEP-986):1~128 位,字母、数字、下划线、连字符、点。\n */\nexport const MCP_TOOL_NAME_PATTERN = /^[A-Za-z0-9_.-]{1,128}$/;\n\n/** 应用使用说明:普通 Markdown Resource,不声明 Skills 扩展能力。 */\nexport const MCP_SKILL_PATH = 'server/mcp/SKILL.md';\nexport const MCP_SKILL_URI = 'skill://app/SKILL.md';\n","/**\n * 工具执行期间可预期的业务错误。\n *\n * 在工具方法中抛出该错误时,SDK 会将其转换为 `isError: true` 的工具结果并把 message 原样返回给 Agent,\n * 适合表达“订单不存在”“无权访问”这类需要 Agent 感知并调整策略的失败。\n * 其他未捕获异常会被记录日志,并以通用的失败提示返回,避免泄露内部细节。\n */\nexport class McpToolError extends Error {\n /** 可选的机器可读错误码,会一并放入返回内容 */\n readonly code?: string;\n /** 附加数据,会以 JSON 形式放入返回内容 */\n readonly data?: unknown;\n\n constructor(message: string, options: { code?: string; data?: unknown } = {}) {\n super(message);\n this.name = 'McpToolError';\n this.code = options.code;\n this.data = options.data;\n }\n}\n","import { Injectable, SetMetadata } from '@nestjs/common';\nimport { MCP_TOOLS_METADATA_KEY } from '../constants';\nimport type { McpToolsOptions } from '../types';\n\n/**\n * `@McpTools()` 类装饰器:标记一个类为 MCP 工具类。\n *\n * 自动附加 `@Injectable()`,类内可正常注入业务 Service。\n * 工具类需作为 provider 注册到所属业务模块,应用启动时由 `McpModule` 自动发现,\n * 无需改动 `app.module.ts`。\n *\n * @example\n * ```typescript\n * @McpTools({ prefix: 'order_' })\n * export class OrderMcpTools {\n * constructor(private readonly orders: OrderService) {}\n *\n * @McpTool({ description: '按 ID 查询订单', inputSchema: GetOrderInput, outputSchema: GetOrderOutput })\n * async get(input: Infer<typeof GetOrderInput>, ctx: McpContext): Promise<McpToolResult<typeof GetOrderOutput>> {\n * const order = await this.orders.findById(input.orderId, ctx.user);\n * return { structuredContent: order };\n * }\n * }\n * ```\n */\nexport const McpTools = (options: McpToolsOptions = {}): ClassDecorator => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (target: any) => {\n Injectable()(target);\n SetMetadata(MCP_TOOLS_METADATA_KEY, options)(target);\n return target;\n };\n};\n","import { SetMetadata } from '@nestjs/common';\nimport { MCP_TOOL_METADATA_KEY } from '../constants';\nimport type { McpSchema, McpToolHandler, McpToolOptions } from '../types';\n\n/**\n * `@McpTool()` 方法装饰器:把工具类中的一个方法注册为 MCP 工具。\n *\n * 方法签名约定为 `(input, ctx) => McpToolResult`:\n * - `input` 已按 `inputSchema` 校验并推导类型,可写作 `Infer<typeof InputSchema>`;\n * - `ctx.user` 为网关注入的当前用户身份,与 REST 接口中的 `req.userContext` 一致;\n * - 声明 `outputSchema` 时返回 `{ structuredContent }`,否则返回 `{ content: [...] }`。\n *\n * TypeScript 方法装饰器只能校验、不能改写方法类型,因此入参与返回值类型需在方法签名上显式标注。\n */\nexport function McpTool<\n I extends McpSchema | undefined = undefined,\n O extends McpSchema | undefined = undefined,\n>(options: McpToolOptions<I, O>) {\n return <M extends McpToolHandler<I, O>>(\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<M>,\n ): void => {\n if (typeof propertyKey !== 'string') {\n throw new TypeError('@McpTool() 只能用于具名方法');\n }\n if (!options || typeof options.description !== 'string' || options.description.trim() === '') {\n throw new TypeError(`@McpTool() 于 ${target.constructor.name}.${propertyKey}:description 为必填项`);\n }\n SetMetadata(MCP_TOOL_METADATA_KEY, options)(target, propertyKey, descriptor as PropertyDescriptor);\n };\n}\n","import { SetMetadata } from '@nestjs/common';\nimport { MCP_UI_RESOURCE_METADATA_KEY, MCP_UI_RESOURCE_SCHEME } from '../constants';\nimport type { McpUiResourceHandler, McpUiResourceOptions } from '../types';\n\n/**\n * `@McpUiResource()` 方法装饰器:把方法注册为 MCP Apps 资源(`ui://` 单文件 HTML)。\n *\n * 方法返回完整 HTML 字符串。界面源码放在 `client/mcp-ui/<entry>/` 下(浏览器代码归客户端 tsconfig 管),\n * 由构建预设打包为 `dist/mcp-ui/<entry>.html`,方法内通过 `readMcpUiTemplate('<entry>')` 读取即可。\n *\n * @example\n * ```typescript\n * @McpUiResource({ uri: 'ui://order/detail', title: '订单详情' })\n * orderDetailView() {\n * return readMcpUiTemplate('order-detail');\n * }\n * ```\n */\nexport function McpUiResource(options: McpUiResourceOptions) {\n return <M extends McpUiResourceHandler>(\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<M>,\n ): void => {\n if (typeof propertyKey !== 'string') {\n throw new TypeError('@McpUiResource() 只能用于具名方法');\n }\n if (!options?.uri || !options.uri.startsWith(MCP_UI_RESOURCE_SCHEME)) {\n throw new TypeError(\n `@McpUiResource() 于 ${target.constructor.name}.${propertyKey}:uri 必须以 ${MCP_UI_RESOURCE_SCHEME} 开头`,\n );\n }\n SetMetadata(MCP_UI_RESOURCE_METADATA_KEY, options)(target, propertyKey, descriptor as PropertyDescriptor);\n };\n}\n","import { DynamicModule, Module, Provider } from '@nestjs/common';\nimport { DiscoveryModule } from '@nestjs/core';\nimport { MCP_MODULE_OPTIONS } from './constants';\nimport { McpManifestController } from './controllers/mcp-manifest.controller';\nimport { McpController } from './controllers/mcp.controller';\nimport { McpManifestService } from './services/mcp-manifest.service';\nimport { McpRegistryService } from './services/mcp-registry.service';\nimport { McpServerService } from './services/mcp-server.service';\nimport type { McpModuleOptions } from './types';\n\n/**\n * McpModule\n *\n * 为全栈应用提供 MCP Server 能力:自动发现 `@McpTools()` 类,\n * 在 `/__innerapi__/mcp` 暴露无状态 Streamable HTTP 端点,并导出 `.spark/mcp/manifest.json`。\n *\n * 由 `PlatformModule` 默认引入,业务工程无需手动导入;\n * 需要关闭时传 `PlatformModule.forRoot({ mcp: { enabled: false } })`。\n */\n@Module({})\nexport class McpModule {\n static forRoot(options: McpModuleOptions = {}): DynamicModule {\n const enabled = options.enabled !== false;\n const providers: Provider[] = [\n { provide: MCP_MODULE_OPTIONS, useValue: options },\n McpRegistryService,\n McpServerService,\n McpManifestService,\n ];\n\n return {\n module: McpModule,\n global: true,\n imports: [DiscoveryModule],\n controllers: enabled ? [McpManifestController, McpController] : [],\n providers,\n exports: [McpRegistryService, McpServerService, McpManifestService],\n };\n }\n}\n","import { Controller, Get, Inject, Logger, Res } from '@nestjs/common';\nimport { ApiExcludeController } from '@nestjs/swagger';\nimport type { Response } from 'express';\nimport { McpManifestService } from '../services/mcp-manifest.service';\nimport { McpRegistryService } from '../services/mcp-registry.service';\n\n/** 平台工具目录:只查询当前运行实例,不读取或写入磁盘清单。 */\n@ApiExcludeController()\n@Controller('__innerapi__/mcp/manifest')\nexport class McpManifestController {\n private readonly logger = new Logger(McpManifestController.name);\n\n constructor(\n @Inject(McpManifestService) private readonly manifest: McpManifestService,\n @Inject(McpRegistryService) private readonly registry: McpRegistryService,\n ) {}\n\n @Get()\n async get(@Res() res: Response): Promise<void> {\n res.setHeader('Cache-Control', 'no-store');\n if (!this.registry.isInitialized()) {\n res.status(503).type('application/problem+json').json({\n type: 'about:blank', title: 'Service Unavailable', status: 503,\n });\n return;\n }\n try {\n res.json(await this.manifest.catalog());\n } catch (error) {\n this.logger.error(error instanceof Error ? error.stack : String(error));\n res.status(500).type('application/problem+json').json({\n type: 'about:blank', title: 'Internal Server Error', status: 500,\n });\n }\n }\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Inject, Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';\nimport { MCP_MODULE_OPTIONS, MCP_MANIFEST_PATH } from '../constants';\nimport { buildManifest, writeManifest } from '../manifest';\nimport { McpRegistryService } from './mcp-registry.service';\nimport { readMcpSkill } from '../skill';\nimport { collectSourceLocations } from '../source-locations';\nimport type { McpCatalog, McpSources, McpManifest, McpModuleOptions } from '../types';\n\n/**\n * McpManifestService\n *\n * 把注册表导出为 `.spark/mcp/manifest.json`,用于离线校验和工程交付。\n * 默认仅在非生产环境的应用启动时写入;写入失败只记日志,不影响服务启动。\n */\n@Injectable()\nexport class McpManifestService implements OnApplicationBootstrap {\n private readonly logger = new Logger(McpManifestService.name);\n\n private sources: McpSources = { tools: {}, resources: {} };\n\n constructor(\n @Inject(McpRegistryService) private readonly registry: McpRegistryService,\n @Inject(MCP_MODULE_OPTIONS) private readonly options: McpModuleOptions,\n ) {}\n\n async onApplicationBootstrap(): Promise<void> {\n if (this.options.enabled === false) return;\n // 源码定位只在应用启动时采集,与本轮注册结果一起使用,避免 GET 扫到未生效修改。\n try {\n this.sources = await collectSourceLocations(this.registry.getTools(), this.registry.getResources());\n } catch (error) {\n this.logger.warn(`MCP 源码定位不可用:${error instanceof Error ? error.message : String(error)}`);\n }\n const writeOnBoot = this.options.manifest?.writeOnBoot ?? process.env.NODE_ENV !== 'production';\n if (!writeOnBoot) return;\n try {\n // 空应用不创建文件;曾经注册过能力的应用清理旧清单。\n if (!this.registry.hasAny() && !(await readMcpSkill())) {\n await fs.rm(path.resolve(process.cwd(), this.options.manifest?.path ?? MCP_MANIFEST_PATH), { force: true });\n return;\n }\n const { changed, file } = await this.write();\n if (changed) this.logger.log(`已更新 MCP 清单:${path.relative(process.cwd(), file)}`);\n } catch (error) {\n this.logger.warn(`写入 MCP 清单失败:${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /** 生成清单对象 */\n async build(cwd: string = process.cwd()): Promise<McpManifest> {\n const manifest = await buildManifest({\n skill: await readMcpSkill(cwd),\n tools: this.registry.getTools(),\n resources: this.registry.getResources(),\n options: this.options,\n });\n manifest.sources = { tools: { ...this.sources.tools }, resources: { ...this.sources.resources } };\n if (manifest.skill) manifest.sources.resources[manifest.skill.uri] = { path: manifest.skill.path };\n return manifest;\n }\n\n /** 面板查询不读写派生清单;与本次 MCP 请求使用同一份 Skill 文件读取逻辑。 */\n async catalog(): Promise<McpCatalog> {\n const skill = await readMcpSkill();\n const manifest = await buildManifest({\n tools: this.registry.getTools(), resources: this.registry.getResources(), options: this.options, skill,\n });\n const sources: McpSources = { tools: { ...this.sources.tools }, resources: { ...this.sources.resources } };\n if (skill) sources.resources[skill.uri] = { path: skill.path };\n return {\n version: manifest.version, generatedAt: manifest.generatedAt, endpoint: manifest.endpoint,\n tools: manifest.tools.map(({ source: _source, ...tool }) => tool),\n resources: manifest.resources.map(({ source: _source, ...resource }) => resource),\n skill, sources,\n };\n }\n\n /** 生成并写入清单文件,内容未变化时不落盘 */\n async write(cwd: string = process.cwd()): Promise<{ changed: boolean; file: string; manifest: McpManifest }> {\n const manifest = await this.build(cwd);\n return writeManifest(manifest, { cwd, relativePath: this.options.manifest?.path, fs });\n }\n}\n","import path from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport type { promises as FsPromises } from 'node:fs';\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';\nimport { MCP_ENDPOINT_PATH, MCP_MANIFEST_PATH, MCP_MANIFEST_VERSION } from './constants';\nimport { createMcpServer, resolveServerInfo } from './server-factory';\nimport type { McpManifest, McpModuleOptions, McpSkill, McpToolDefinition, McpUiResourceDefinition } from './types';\n\nexport interface BuildManifestInput {\n tools: McpToolDefinition[];\n resources: McpUiResourceDefinition[];\n options: McpModuleOptions;\n skill?: McpSkill | null;\n}\n\n/**\n * 通过“内存中的 MCP 客户端”读取工具列表生成清单。\n *\n * 这样清单里的 JSON Schema 与真实客户端 `tools/list` 看到的完全一致,避免自行转换 zod 造成偏差。\n */\nexport async function buildManifest(input: BuildManifestInput): Promise<McpManifest> {\n const server = createMcpServer({ tools: input.tools, resources: input.resources, options: input.options, skill: input.skill });\n const client = new Client({ name: 'miaoda-mcp-manifest', version: '1.0.0' });\n const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();\n\n try {\n await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);\n\n const toolSource = new Map(input.tools.map((t) => [t.name, { className: t.className, methodName: t.methodName }]));\n const resourceSource = new Map(\n input.resources.map((r) => [r.options.uri, { className: r.className, methodName: r.methodName }]),\n );\n\n const tools = input.tools.length > 0 ? (await client.listTools()).tools : [];\n const resources = (input.resources.length > 0 || input.skill) ? (await client.listResources()).resources : [];\n\n const manifest: McpManifest = {\n version: MCP_MANIFEST_VERSION,\n generatedAt: new Date().toISOString(),\n endpoint: MCP_ENDPOINT_PATH,\n server: resolveServerInfo(input.options),\n skill: input.skill ? { uri: input.skill.uri, path: input.skill.path } : null,\n tools: tools\n .map((tool) => ({\n ...tool,\n source: toolSource.get(tool.name) ?? { className: '', methodName: '' },\n }))\n .sort((a, b) => a.name.localeCompare(b.name)),\n resources: resources\n .map((resource) => ({\n ...resource,\n source: resourceSource.get(resource.uri),\n }))\n .sort((a, b) => a.uri.localeCompare(b.uri)),\n };\n return manifest;\n } finally {\n await Promise.allSettled([client.close(), server.close()]);\n }\n}\n\n/**\n * 序列化清单:稳定格式,忽略 generatedAt 比较是否变化。\n */\nexport function serializeManifest(manifest: McpManifest): string {\n return `${JSON.stringify(manifest, null, 2)}\\n`;\n}\n\nfunction stripVolatile(json: string): string {\n return json.replace(/\"generatedAt\": \"[^\"]*\"/, '\"generatedAt\": \"\"');\n}\n\nexport interface WriteManifestOptions {\n cwd: string;\n relativePath?: string;\n fs: typeof FsPromises;\n}\n\n/**\n * 写入清单文件;内容(忽略时间戳)未变化时不落盘,避免 watch 模式下反复触发变更。\n */\nexport async function writeManifest(\n manifest: McpManifest,\n { cwd, relativePath = MCP_MANIFEST_PATH, fs }: WriteManifestOptions,\n): Promise<{ changed: boolean; file: string; manifest: McpManifest }> {\n const file = path.resolve(cwd, relativePath);\n const next = serializeManifest(manifest);\n let previous: string | undefined;\n try {\n previous = await fs.readFile(file, 'utf8');\n } catch {\n previous = undefined;\n }\n if (previous !== undefined && stripVolatile(previous) === stripVolatile(next)) {\n return { changed: false, file, manifest };\n }\n await fs.mkdir(path.dirname(file), { recursive: true });\n const temporary = `${file}.${randomUUID()}.tmp`;\n try {\n await fs.writeFile(temporary, next, 'utf8');\n await fs.rename(temporary, file);\n } finally {\n await fs.rm(temporary, { force: true });\n }\n return { changed: true, file, manifest };\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { registerAppResource, registerAppTool, RESOURCE_MIME_TYPE } from '@modelcontextprotocol/ext-apps/server';\nimport { MCP_DEFAULT_SERVER_NAME, MCP_DEFAULT_SERVER_VERSION } from './constants';\nimport { McpToolError } from './errors';\nimport type {\n McpSkill,\n McpContext,\n McpModuleOptions,\n McpSchema,\n McpToolDefinition,\n McpUiResourceDefinition,\n} from './types';\n\n/**\n * 把工具定义装配为 McpServer 时所需的运行时依赖。\n */\nexport interface McpServerFactoryInput {\n tools: McpToolDefinition[];\n resources: McpUiResourceDefinition[];\n options: McpModuleOptions;\n /** 同一次请求的 Skill 正文快照,清单与资源共用。 */\n skill?: McpSkill | null;\n /**\n * 为一次调用构造执行上下文。清单导出等无请求场景可不传,此时调用工具会直接失败。\n */\n createContext?: (extra: any) => McpContext;\n /** 记录未预期异常 */\n onError?: (error: unknown, location: string) => void;\n}\n\n/**\n * 解析服务端名称:模块配置 > SUDA_APP_ID > 默认值。\n */\nexport function resolveServerInfo(options: McpModuleOptions): { name: string; version: string } {\n return {\n name: options.serverName ?? process.env.SUDA_APP_ID ?? MCP_DEFAULT_SERVER_NAME,\n version: options.serverVersion ?? MCP_DEFAULT_SERVER_VERSION,\n };\n}\n\n/**\n * 规范化 schema:未声明的入参视为空对象形状(保证回调签名恒为 `(args, extra)`),\n * 其余原样交给 SDK —— `z.object()` 保留 strict / passthrough / refine 等对象级语义,原始形状由 SDK 包装。\n */\nexport function normalizeSchema(schema: McpSchema | undefined): McpSchema {\n return schema ?? {};\n}\n\n/**\n * 把工具的 `ui` / `meta` 配置合并为 MCP `_meta`。\n */\nexport function buildToolMeta(def: McpToolDefinition): Record<string, unknown> | undefined {\n const { ui, meta } = def.options;\n if (!ui && !meta) return undefined;\n const merged: Record<string, unknown> = { ...(meta ?? {}) };\n if (ui) {\n merged.ui = {\n ...((merged.ui as Record<string, unknown> | undefined) ?? {}),\n resourceUri: ui.resourceUri,\n ...(ui.visibility ? { visibility: ui.visibility } : {}),\n };\n }\n return merged;\n}\n\nconst MISSING_USER_MESSAGE =\n '调用者身份缺失:请求未携带用户信息(x-larkgw-suda-webuser)。请通过 MCP Gateway 或开发服务入口访问,或在模块配置中设置 requireUser: false。';\n\nfunction assertUser(ctx: McpContext, options: McpModuleOptions): void {\n if (options.requireUser === false) return;\n if (!ctx.user?.userId) {\n throw new McpToolError(MISSING_USER_MESSAGE, { code: 'MCP_USER_REQUIRED' });\n }\n}\n\nfunction toErrorResult(error: unknown, location: string, onError?: McpServerFactoryInput['onError']): CallToolResult {\n if (error instanceof McpToolError) {\n const payload: Record<string, unknown> = { message: error.message };\n if (error.code !== undefined) payload.code = error.code;\n if (error.data !== undefined) payload.data = error.data;\n return {\n isError: true,\n content: [{ type: 'text', text: error.code ? `[${error.code}] ${error.message}` : error.message }],\n structuredContent: undefined,\n _meta: { error: payload },\n };\n }\n onError?.(error, location);\n // 细节只进服务端日志:预览沙箱同样对外暴露,不把内部异常信息透给调用方\n return { isError: true, content: [{ type: 'text', text: `工具执行失败(${location}),请查看应用日志` }] };\n}\n\n/**\n * 根据定义创建一个 McpServer 实例。\n *\n * 每个 HTTP 请求都会创建一个新实例(无状态模式),因此这里只做纯装配,不持有任何跨请求状态。\n */\nexport function createMcpServer(input: McpServerFactoryInput): McpServer {\n const { tools, resources, options, createContext, onError } = input;\n const server = new McpServer(resolveServerInfo(options), {\n instructions: options.instructions,\n });\n\n const noContext = (): never => {\n throw new Error('当前 McpServer 实例未绑定请求上下文,不能执行工具');\n };\n\n for (const def of tools) {\n const location = `${def.className}.${def.methodName}`;\n const config = {\n title: def.options.title,\n description: def.options.description,\n inputSchema: normalizeSchema(def.options.inputSchema),\n outputSchema: def.options.outputSchema,\n annotations: def.options.annotations,\n _meta: buildToolMeta(def),\n };\n\n const callback = async (args: Record<string, unknown>, extra: any): Promise<CallToolResult> => {\n try {\n const ctx = createContext ? createContext(extra) : noContext();\n assertUser(ctx, options);\n if (!def.handler) {\n throw new Error(`工具「${def.name}」未绑定实例(${location})`);\n }\n const result = (await def.handler(args ?? {}, ctx)) as CallToolResult;\n if (def.options.outputSchema && result && !result.content) {\n return {\n ...result,\n content: [{ type: 'text', text: JSON.stringify(result.structuredContent ?? null) }],\n };\n }\n return result;\n } catch (error) {\n return toErrorResult(error, location, onError);\n }\n };\n\n if (def.options.ui) {\n registerAppTool(server, def.name, config as any, callback as any);\n } else {\n server.registerTool(def.name, config as any, callback as any);\n }\n }\n\n for (const def of resources) {\n const location = `${def.className}.${def.methodName}`;\n const { uri, title, description, csp, permissions, meta } = def.options;\n const uiMeta: Record<string, unknown> = { ...(meta ?? {}) };\n if (csp) uiMeta.csp = csp;\n if (permissions) uiMeta.permissions = permissions;\n\n registerAppResource(\n server,\n def.name,\n uri,\n {\n title,\n description,\n mimeType: RESOURCE_MIME_TYPE,\n _meta: Object.keys(uiMeta).length > 0 ? { ui: uiMeta } : undefined,\n } as any,\n async (resourceUri: URL, extra: any) => {\n const ctx = createContext ? createContext(extra) : noContext();\n assertUser(ctx, options);\n if (!def.handler) {\n throw new Error(`资源「${uri}」未绑定实例(${location})`);\n }\n const html = await def.handler(ctx);\n return {\n contents: [{ uri: resourceUri.href, mimeType: RESOURCE_MIME_TYPE, text: html }],\n };\n },\n );\n }\n\n if (input.skill) {\n const skill = input.skill;\n server.registerResource('app-skill', skill.uri, {\n title: '应用使用说明',\n description: '应用 MCP 的调用时机、工具选择、调用顺序、约束与失败处理',\n mimeType: 'text/markdown',\n }, async (uri, extra) => {\n const ctx = createContext ? createContext(extra) : noContext();\n assertUser(ctx, options);\n return { contents: [{ uri: uri.href, mimeType: 'text/markdown', text: skill.content }] };\n });\n }\n\n return server;\n}\n","var r=((Z)=>typeof require<\"u\"?require:typeof Proxy<\"u\"?new Proxy(Z,{get:($,J)=>(typeof require<\"u\"?require:$)[J]}):Z)(function(Z){if(typeof require<\"u\")return require.apply(this,arguments);throw Error('Dynamic require of \"'+Z+'\" is not supported')});import{mergeCapabilities as zQ}from\"@modelcontextprotocol/sdk/shared/protocol.js\";import{CallToolRequestSchema as OQ,CallToolResultSchema as IQ,CreateMessageResultSchema as PQ,CreateMessageResultWithToolsSchema as wQ,EmptyResultSchema as HQ,ListResourcesResultSchema as _Q,ListToolsRequestSchema as AQ,PingRequestSchema as EQ,ReadResourceResultSchema as RQ}from\"@modelcontextprotocol/sdk/types.js\";import{Protocol as i}from\"@modelcontextprotocol/sdk/shared/protocol.js\";class F extends i{_registeredMethods=new Set;_eventSlots=new Map;onEventDispatch(Z,$){}_ensureEventSlot(Z){let $=this._eventSlots.get(Z);if(!$){let J=this.eventSchemas[Z];if(!J)throw Error(`Unknown event: ${String(Z)}`);$={listeners:[]},this._eventSlots.set(Z,$);let X=J.shape.method.value;this._registeredMethods.add(X);let V=$;super.setNotificationHandler(J,(D)=>{let L=D.params;this.onEventDispatch(Z,L),V.onHandler?.(L);for(let W of[...V.listeners])W(L)})}return $}setEventHandler(Z,$){let J=this._ensureEventSlot(Z);if(J.onHandler&&$)console.warn(`[MCP Apps] on${String(Z)} handler replaced. Use addEventListener(\"${String(Z)}\", …) to add multiple listeners without replacing.`);J.onHandler=$}getEventHandler(Z){return this._eventSlots.get(Z)?.onHandler}addEventListener(Z,$){this._ensureEventSlot(Z).listeners.push($)}removeEventListener(Z,$){let J=this._eventSlots.get(Z);if(!J)return;let X=J.listeners.indexOf($);if(X!==-1)J.listeners.splice(X,1)}setRequestHandler=(Z,$)=>{this._assertMethodNotRegistered(Z,\"setRequestHandler\"),super.setRequestHandler(Z,$)};setNotificationHandler=(Z,$)=>{this._assertMethodNotRegistered(Z,\"setNotificationHandler\"),super.setNotificationHandler(Z,$)};warnIfRequestHandlerReplaced(Z,$,J){if($&&J)console.warn(`[MCP Apps] ${Z} handler replaced. Previous handler will no longer be called.`)}replaceRequestHandler=(Z,$)=>{let J=Z.shape.method.value;this._registeredMethods.add(J),super.setRequestHandler(Z,$)};_assertMethodNotRegistered(Z,$){let J=Z.shape.method.value;if(this._registeredMethods.has(J))throw Error(`Handler for \"${J}\" already registered (via ${$}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._registeredMethods.add(J)}}import{JSONRPCMessageSchema as n}from\"@modelcontextprotocol/sdk/types.js\";var q=\"2026-01-26\";var z=\"ui/notifications/tool-input-partial\";class N{eventTarget;eventSource;messageListener;constructor(Z=window.parent,$){this.eventTarget=Z;this.eventSource=$;this.messageListener=(J)=>{if($&&J.source!==this.eventSource){console.debug(\"Ignoring message from unknown source\",J);return}let X=n.safeParse(J.data);if(X.success)console.debug(\"Parsed message\",X.data),this.onmessage?.(X.data);else if(J.data?.jsonrpc!==\"2.0\")console.debug(\"Ignoring non-JSON-RPC message\",X.error.message,J);else console.error(\"Failed to parse message\",X.error.message,J),this.onerror?.(Error(\"Invalid JSON-RPC message received: \"+X.error.message))}}async start(){window.addEventListener(\"message\",this.messageListener)}async send(Z,$){if(Z.method!==z)console.debug(\"Sending message\",Z);this.eventTarget.postMessage(Z,\"*\")}async close(){window.removeEventListener(\"message\",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}import{z as Q}from\"zod/v4\";import{ContentBlockSchema as y,CallToolResultSchema as o,EmbeddedResourceSchema as a,ImplementationSchema as g,RequestIdSchema as s,ResourceLinkSchema as t,ToolSchema as e}from\"@modelcontextprotocol/sdk/types.js\";var v=Q.union([Q.literal(\"light\"),Q.literal(\"dark\")]).describe(\"Color theme preference for the host environment.\"),K=Q.union([Q.literal(\"inline\"),Q.literal(\"fullscreen\"),Q.literal(\"pip\")]).describe(\"Display mode for UI presentation.\"),QQ=Q.union([Q.literal(\"--color-background-primary\"),Q.literal(\"--color-background-secondary\"),Q.literal(\"--color-background-tertiary\"),Q.literal(\"--color-background-inverse\"),Q.literal(\"--color-background-ghost\"),Q.literal(\"--color-background-info\"),Q.literal(\"--color-background-danger\"),Q.literal(\"--color-background-success\"),Q.literal(\"--color-background-warning\"),Q.literal(\"--color-background-disabled\"),Q.literal(\"--color-text-primary\"),Q.literal(\"--color-text-secondary\"),Q.literal(\"--color-text-tertiary\"),Q.literal(\"--color-text-inverse\"),Q.literal(\"--color-text-ghost\"),Q.literal(\"--color-text-info\"),Q.literal(\"--color-text-danger\"),Q.literal(\"--color-text-success\"),Q.literal(\"--color-text-warning\"),Q.literal(\"--color-text-disabled\"),Q.literal(\"--color-border-primary\"),Q.literal(\"--color-border-secondary\"),Q.literal(\"--color-border-tertiary\"),Q.literal(\"--color-border-inverse\"),Q.literal(\"--color-border-ghost\"),Q.literal(\"--color-border-info\"),Q.literal(\"--color-border-danger\"),Q.literal(\"--color-border-success\"),Q.literal(\"--color-border-warning\"),Q.literal(\"--color-border-disabled\"),Q.literal(\"--color-ring-primary\"),Q.literal(\"--color-ring-secondary\"),Q.literal(\"--color-ring-inverse\"),Q.literal(\"--color-ring-info\"),Q.literal(\"--color-ring-danger\"),Q.literal(\"--color-ring-success\"),Q.literal(\"--color-ring-warning\"),Q.literal(\"--font-sans\"),Q.literal(\"--font-mono\"),Q.literal(\"--font-weight-normal\"),Q.literal(\"--font-weight-medium\"),Q.literal(\"--font-weight-semibold\"),Q.literal(\"--font-weight-bold\"),Q.literal(\"--font-text-xs-size\"),Q.literal(\"--font-text-sm-size\"),Q.literal(\"--font-text-md-size\"),Q.literal(\"--font-text-lg-size\"),Q.literal(\"--font-heading-xs-size\"),Q.literal(\"--font-heading-sm-size\"),Q.literal(\"--font-heading-md-size\"),Q.literal(\"--font-heading-lg-size\"),Q.literal(\"--font-heading-xl-size\"),Q.literal(\"--font-heading-2xl-size\"),Q.literal(\"--font-heading-3xl-size\"),Q.literal(\"--font-text-xs-line-height\"),Q.literal(\"--font-text-sm-line-height\"),Q.literal(\"--font-text-md-line-height\"),Q.literal(\"--font-text-lg-line-height\"),Q.literal(\"--font-heading-xs-line-height\"),Q.literal(\"--font-heading-sm-line-height\"),Q.literal(\"--font-heading-md-line-height\"),Q.literal(\"--font-heading-lg-line-height\"),Q.literal(\"--font-heading-xl-line-height\"),Q.literal(\"--font-heading-2xl-line-height\"),Q.literal(\"--font-heading-3xl-line-height\"),Q.literal(\"--border-radius-xs\"),Q.literal(\"--border-radius-sm\"),Q.literal(\"--border-radius-md\"),Q.literal(\"--border-radius-lg\"),Q.literal(\"--border-radius-xl\"),Q.literal(\"--border-radius-full\"),Q.literal(\"--border-width-regular\"),Q.literal(\"--shadow-hairline\"),Q.literal(\"--shadow-sm\"),Q.literal(\"--shadow-md\"),Q.literal(\"--shadow-lg\")]).describe(\"CSS variable keys available to MCP apps for theming.\"),ZQ=Q.record(QQ.describe(`Style variables for theming MCP apps.\n\nIndividual style keys are optional - hosts may provide any subset of these values.\nValues are strings containing CSS values (colors, sizes, font stacks, etc.).\n\nNote: This type uses \\`Record<K, string | undefined>\\` rather than \\`Partial<Record<K, string>>\\`\nfor compatibility with Zod schema generation. Both are functionally equivalent for validation.`),Q.union([Q.string(),Q.undefined()]).describe(`Style variables for theming MCP apps.\n\nIndividual style keys are optional - hosts may provide any subset of these values.\nValues are strings containing CSS values (colors, sizes, font stacks, etc.).\n\nNote: This type uses \\`Record<K, string | undefined>\\` rather than \\`Partial<Record<K, string>>\\`\nfor compatibility with Zod schema generation. Both are functionally equivalent for validation.`)).describe(`Style variables for theming MCP apps.\n\nIndividual style keys are optional - hosts may provide any subset of these values.\nValues are strings containing CSS values (colors, sizes, font stacks, etc.).\n\nNote: This type uses \\`Record<K, string | undefined>\\` rather than \\`Partial<Record<K, string>>\\`\nfor compatibility with Zod schema generation. Both are functionally equivalent for validation.`),$Q=Q.object({method:Q.literal(\"ui/open-link\"),params:Q.object({url:Q.string().describe(\"URL to open in the host's browser\")})}),I=Q.object({isError:Q.boolean().optional().describe(\"True if the host failed to open the URL (e.g., due to security policy).\")}).passthrough(),P=Q.object({isError:Q.boolean().optional().describe(\"True if the download failed (e.g., user cancelled or host denied).\")}).passthrough(),w=Q.object({isError:Q.boolean().optional().describe(\"True if the host rejected or failed to deliver the message.\")}).passthrough(),JQ=Q.object({method:Q.literal(\"ui/notifications/sandbox-proxy-ready\"),params:Q.object({})}),Y=Q.object({connectDomains:Q.array(Q.string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).\n\n- Maps to CSP \\`connect-src\\` directive\n- Empty or omitted → no network connections (secure default)`),resourceDomains:Q.array(Q.string()).optional().describe(\"Origins for static resources (images, scripts, stylesheets, fonts, media).\\n\\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\\n- Wildcard subdomains supported: `https://*.example.com`\\n- Empty or omitted → no network resources (secure default)\"),frameDomains:Q.array(Q.string()).optional().describe(\"Origins for nested iframes.\\n\\n- Maps to CSP `frame-src` directive\\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)\"),baseUriDomains:Q.array(Q.string()).optional().describe(\"Allowed base URIs for the document.\\n\\n- Maps to CSP `base-uri` directive\\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)\")}),j=Q.object({camera:Q.object({}).optional().describe(\"Request camera access.\\n\\nMaps to Permission Policy `camera` feature.\"),microphone:Q.object({}).optional().describe(\"Request microphone access.\\n\\nMaps to Permission Policy `microphone` feature.\"),geolocation:Q.object({}).optional().describe(\"Request geolocation access.\\n\\nMaps to Permission Policy `geolocation` feature.\"),clipboardWrite:Q.object({}).optional().describe(\"Request clipboard write access.\\n\\nMaps to Permission Policy `clipboard-write` feature.\")}),XQ=Q.object({method:Q.literal(\"ui/notifications/size-changed\"),params:Q.object({width:Q.number().optional().describe(\"New width in pixels.\"),height:Q.number().optional().describe(\"New height in pixels.\")})}),H=Q.object({method:Q.literal(\"ui/notifications/tool-input\"),params:Q.object({arguments:Q.record(Q.string(),Q.unknown().describe(\"Complete tool call arguments as key-value pairs.\")).optional().describe(\"Complete tool call arguments as key-value pairs.\")})}),_=Q.object({method:Q.literal(\"ui/notifications/tool-input-partial\"),params:Q.object({arguments:Q.record(Q.string(),Q.unknown().describe(\"Partial tool call arguments (incomplete, may change).\")).optional().describe(\"Partial tool call arguments (incomplete, may change).\")})}),A=Q.object({method:Q.literal(\"ui/notifications/tool-cancelled\"),params:Q.object({reason:Q.string().optional().describe('Optional reason for the cancellation (e.g., \"user action\", \"timeout\").')})}),f=Q.object({fonts:Q.string().optional()}),u=Q.object({variables:ZQ.optional().describe(\"CSS variables for theming the app.\"),css:f.optional().describe(\"CSS blocks that apps can inject.\")}),E=Q.object({method:Q.literal(\"ui/resource-teardown\"),params:Q.object({})}),VQ=Q.record(Q.string(),Q.unknown()),O=Q.object({text:Q.object({}).optional().describe(\"Host supports text content blocks.\"),image:Q.object({}).optional().describe(\"Host supports image content blocks.\"),audio:Q.object({}).optional().describe(\"Host supports audio content blocks.\"),resource:Q.object({}).optional().describe(\"Host supports resource content blocks.\"),resourceLink:Q.object({}).optional().describe(\"Host supports resource link content blocks.\"),structuredContent:Q.object({}).optional().describe(\"Host supports structured content.\")}),DQ=Q.object({method:Q.literal(\"ui/notifications/request-teardown\"),params:Q.object({}).optional()}),d=Q.object({experimental:Q.record(Q.string(),Q.record(Q.string(),Q.any()).describe(\"Experimental features keyed by identifier.\")).optional().describe(\"Experimental features keyed by identifier.\"),openLinks:Q.object({}).optional().describe(\"Host supports opening external URLs.\"),downloadFile:Q.object({}).optional().describe(\"Host supports file downloads via ui/download-file.\"),serverTools:Q.object({listChanged:Q.boolean().optional().describe(\"Host supports tools/list_changed notifications.\")}).optional().describe(\"Host can proxy tool calls to the MCP server.\"),serverResources:Q.object({listChanged:Q.boolean().optional().describe(\"Host supports resources/list_changed notifications.\")}).optional().describe(\"Host can proxy resource reads to the MCP server.\"),logging:Q.object({}).optional().describe(\"Host accepts log messages.\"),sandbox:Q.object({permissions:j.optional().describe(\"Permissions granted by the host (camera, microphone, geolocation).\"),csp:Y.optional().describe(\"CSP domains approved by the host.\")}).optional().describe(\"Sandbox configuration applied by the host.\"),updateModelContext:O.optional().describe(\"Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns.\"),message:O.optional().describe(\"Host supports receiving content messages (ui/message) from the view.\"),sampling:Q.object({tools:Q.object({}).optional().describe(\"Host supports tool use via `tools` and `toolChoice` parameters.\")}).optional().describe(\"Host supports LLM sampling (sampling/createMessage) from the view.\\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.\")}),h=Q.object({experimental:Q.record(Q.string(),Q.record(Q.string(),Q.any()).describe(\"Experimental features keyed by identifier.\")).optional().describe(\"Experimental features keyed by identifier.\"),tools:Q.object({listChanged:Q.boolean().optional().describe(\"App supports tools/list_changed notifications.\")}).optional().describe(\"App exposes MCP-style tools that the host can call.\"),availableDisplayModes:Q.array(K).optional().describe(\"Display modes the app supports.\")}),LQ=Q.object({method:Q.literal(\"ui/notifications/initialized\"),params:Q.object({}).optional()}),WQ=Q.object({csp:Y.optional().describe(\"Content Security Policy configuration for UI resources.\"),permissions:j.optional().describe(\"Sandbox permissions requested by the UI resource.\"),domain:Q.string().optional().describe(`Dedicated origin for view sandbox.\n\nUseful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.\n\n**Host-dependent:** The format and validation rules for this field are determined by each host. Servers MUST consult host-specific documentation for the expected domain format. Common patterns include:\n- Hash-based subdomains (e.g., \\`{hash}.claudemcpcontent.com\\`)\n- URL-derived subdomains (e.g., \\`www-example-com.oaiusercontent.com\\`)\n\nIf omitted, host uses default sandbox origin (typically per-conversation).`),prefersBorder:Q.boolean().optional().describe(`Visual boundary preference - true if view prefers a visible border.\n\nBoolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary.\n\n- \\`true\\`: request visible border + background\n- \\`false\\`: request no visible border + background\n- omitted: host decides border`)}),BQ=Q.object({method:Q.literal(\"ui/request-display-mode\"),params:Q.object({mode:K.describe(\"The display mode being requested.\")})}),R=Q.object({mode:K.describe(\"The display mode that was actually set. May differ from requested if not supported.\")}).passthrough(),m=Q.union([Q.literal(\"model\"),Q.literal(\"app\")]).describe(\"Tool visibility scope - who can access the tool.\"),GQ=Q.object({resourceUri:Q.string().optional(),visibility:Q.array(m).optional().describe(`Who can access this tool. Default: [\"model\", \"app\"]\n- \"model\": Tool visible to and callable by the agent\n- \"app\": Tool callable by the app from this server only`),csp:Q.never().optional(),permissions:Q.never().optional()}),dQ=Q.object({mimeTypes:Q.array(Q.string()).optional().describe('Array of supported MIME types for UI resources.\\nMust include `\"text/html;profile=mcp-app\"` for MCP Apps support.')}),KQ=Q.object({method:Q.literal(\"ui/download-file\"),params:Q.object({contents:Q.array(Q.union([a,t])).describe(\"Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.\")})}),NQ=Q.object({method:Q.literal(\"ui/message\"),params:Q.object({role:Q.literal(\"user\").describe('Message role, currently only \"user\" is supported.'),content:Q.array(y).describe(\"Message content blocks (text, image, etc.).\")})}),YQ=Q.object({method:Q.literal(\"ui/notifications/sandbox-resource-ready\"),params:Q.object({html:Q.string().describe(\"HTML content to load into the inner iframe.\"),sandbox:Q.string().optional().describe(\"Optional override for the inner iframe's sandbox attribute.\"),csp:Y.optional().describe(\"CSP configuration from resource metadata.\"),permissions:j.optional().describe(\"Sandbox permissions from resource metadata.\")})}),U=Q.object({method:Q.literal(\"ui/notifications/tool-result\"),params:o.describe(\"Standard MCP tool execution result.\")}),T=Q.object({toolInfo:Q.object({id:s.optional().describe(\"JSON-RPC id of the tools/call request.\"),tool:e.describe(\"Tool definition including name, inputSchema, etc.\")}).optional().describe(\"Metadata of the tool call that instantiated this App.\"),theme:v.optional().describe(\"Current color theme preference.\"),styles:u.optional().describe(\"Style configuration for theming the app.\"),displayMode:K.optional().describe(\"How the UI is currently displayed.\"),availableDisplayModes:Q.array(K).optional().describe(\"Display modes the host supports.\"),containerDimensions:Q.union([Q.object({height:Q.number().describe(\"Fixed container height in pixels.\")}),Q.object({maxHeight:Q.union([Q.number(),Q.undefined()]).optional().describe(\"Maximum container height in pixels.\")})]).and(Q.union([Q.object({width:Q.number().describe(\"Fixed container width in pixels.\")}),Q.object({maxWidth:Q.union([Q.number(),Q.undefined()]).optional().describe(\"Maximum container width in pixels.\")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other\ncontainer holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:Q.string().optional().describe(\"User's language and region preference in BCP 47 format.\"),timeZone:Q.string().optional().describe(\"User's timezone in IANA format.\"),userAgent:Q.string().optional().describe(\"Host application identifier.\"),platform:Q.union([Q.literal(\"web\"),Q.literal(\"desktop\"),Q.literal(\"mobile\")]).optional().describe(\"Platform type for responsive design decisions.\"),deviceCapabilities:Q.object({touch:Q.boolean().optional().describe(\"Whether the device supports touch input.\"),hover:Q.boolean().optional().describe(\"Whether the device supports hover interactions.\")}).optional().describe(\"Device input capabilities.\"),safeAreaInsets:Q.object({top:Q.number().describe(\"Top safe area inset in pixels.\"),right:Q.number().describe(\"Right safe area inset in pixels.\"),bottom:Q.number().describe(\"Bottom safe area inset in pixels.\"),left:Q.number().describe(\"Left safe area inset in pixels.\")}).optional().describe(\"Mobile safe area boundaries in pixels.\")}).passthrough(),k=Q.object({method:Q.literal(\"ui/notifications/host-context-changed\"),params:T.describe(\"Partial context update containing only changed fields.\")}),jQ=Q.object({method:Q.literal(\"ui/update-model-context\"),params:Q.object({content:Q.array(y).optional().describe(\"Context content blocks (text, image, etc.).\"),structuredContent:Q.record(Q.string(),Q.unknown().describe(\"Structured content for machine-readable context data.\")).optional().describe(\"Structured content for machine-readable context data.\")})}),FQ=Q.object({method:Q.literal(\"ui/initialize\"),params:Q.object({appInfo:g.describe(\"App identification (name and version).\"),appCapabilities:h.describe(\"Features and capabilities this app provides.\"),protocolVersion:Q.string().describe(\"Protocol version this app supports.\")})}),M=Q.object({protocolVersion:Q.string().describe('Negotiated protocol version string (e.g., \"2025-11-21\").'),hostInfo:g.describe(\"Host application identification and version.\"),hostCapabilities:d.describe(\"Features and capabilities provided by the host.\"),hostContext:T.describe(\"Rich context about the host environment.\")}).passthrough();var qQ={target:\"draft-2020-12\"};async function x(Z,$){let J=Z[\"~standard\"];if(J.jsonSchema)return J.jsonSchema[$](qQ);if(J.vendor===\"zod\"){let{z:X}=await import(\"zod/v4\");return X.toJSONSchema(Z,{io:$})}throw Error(`Schema (vendor: ${J.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function S(Z,$,J=\"\"){let X=await Z[\"~standard\"].validate($);if(X.issues){let V=X.issues.map((D)=>{let L=D.path?.map((W)=>typeof W===\"object\"?W.key:W).join(\".\");return L?`${L}: ${D.message}`:D.message}).join(\"; \");throw Error(J+V)}return X.value}import{z as UQ}from\"zod/v4\";var C=\"ui/resourceUri\",p=\"text/html;profile=mcp-app\";class c extends F{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(Z){if(this._initializedSent)return;let $=`[ext-apps] App.${Z}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error($);console.warn(`${$}. This will throw in a future release.`)}eventSchemas={toolinput:H,toolinputpartial:_,toolresult:U,toolcancelled:A,hostcontextchanged:k};static ONE_SHOT_EVENTS=new Set([\"toolinput\",\"toolinputpartial\",\"toolresult\",\"toolcancelled\"]);_everHadListener=new Set;_assertHandlerTiming(Z){if(!c.ONE_SHOT_EVENTS.has(Z)||this._everHadListener.has(Z))return;if(this._everHadListener.add(Z),!this._initializedSent)return;let $=`[ext-apps] \"${String(Z)}\" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error($);console.warn($)}setEventHandler(Z,$){if($)this._assertHandlerTiming(Z);super.setEventHandler(Z,$)}addEventListener(Z,$){this._assertHandlerTiming(Z),super.addEventListener(Z,$)}onEventDispatch(Z,$){if(Z===\"hostcontextchanged\")this._hostContext={...this._hostContext,...$}}constructor(Z,$={},J={autoResize:!0}){super(J);this._appInfo=Z;this._capabilities=$;this.options=J;if(!J.allowUnsafeEval)UQ.config({jitless:!0});this.setRequestHandler(EQ,(X)=>{return console.log(\"Received ping:\",X.params),{}}),this.setEventHandler(\"hostcontextchanged\",void 0)}registerCapabilities(Z){if(this.transport)throw Error(\"Cannot register capabilities after transport is established\");this._capabilities=zQ(this._capabilities,Z)}registerTool(Z,$,J){if(this._registeredTools[Z])throw Error(`Tool ${Z} is already registered`);let X=this,V=()=>{if(X._initializedSent&&X._capabilities.tools?.listChanged)X.sendToolListChanged()},D=$.inputSchema!==void 0,L={title:$.title,description:$.description,inputSchema:$.inputSchema,outputSchema:$.outputSchema,annotations:$.annotations,_meta:$._meta,enabled:!0,enable(){this.enabled=!0,V()},disable(){this.enabled=!1,V()},update(W){Object.assign(this,W),V()},remove(){if(X._registeredTools[Z]!==L)return;delete X._registeredTools[Z],V()},handler:async(W,B)=>{if(!L.enabled)throw Error(`Tool ${Z} is disabled`);let G;if(D){let b=L.inputSchema,l=b?await S(b,W??{},`Invalid input for tool ${Z}: `):W??{};G=await J(l,B)}else G=await J(B);if(L.outputSchema&&!G.isError)G.structuredContent=await S(L.outputSchema,G.structuredContent,`Invalid output for tool ${Z}: `);return G}};if(this._registeredTools[Z]=L,!this._capabilities.tools&&!this.transport)this.registerCapabilities({tools:{listChanged:!0}});return this.ensureToolHandlersInitialized(),V(),L}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){if(this._toolHandlersInitialized)return;this._toolHandlersInitialized=!0,this.oncalltool=async(Z,$)=>{let J=this._registeredTools[Z.name];if(!J)throw Error(`Tool ${Z.name} not found`);return J.handler(Z.arguments,$)},this.onlisttools=async(Z,$)=>{return{tools:await Promise.all(Object.entries(this._registeredTools).filter(([X,V])=>V.enabled).map(async([X,V])=>{let D={name:X,title:V.title,description:V.description,inputSchema:V.inputSchema?await x(V.inputSchema,\"input\"):{type:\"object\",properties:{}}};if(V.outputSchema)D.outputSchema=await x(V.outputSchema,\"output\");if(V.annotations)D.annotations=V.annotations;if(V._meta)D._meta=V._meta;return D}))}}}async sendToolListChanged(Z={}){this._assertInitialized(\"sendToolListChanged\"),await this.notification({method:\"notifications/tools/list_changed\",params:Z})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(\"toolinput\")}set ontoolinput(Z){this.setEventHandler(\"toolinput\",Z)}get ontoolinputpartial(){return this.getEventHandler(\"toolinputpartial\")}set ontoolinputpartial(Z){this.setEventHandler(\"toolinputpartial\",Z)}get ontoolresult(){return this.getEventHandler(\"toolresult\")}set ontoolresult(Z){this.setEventHandler(\"toolresult\",Z)}get ontoolcancelled(){return this.getEventHandler(\"toolcancelled\")}set ontoolcancelled(Z){this.setEventHandler(\"toolcancelled\",Z)}get onhostcontextchanged(){return this.getEventHandler(\"hostcontextchanged\")}set onhostcontextchanged(Z){this.setEventHandler(\"hostcontextchanged\",Z)}_onteardown;get onteardown(){return this._onteardown}set onteardown(Z){this.warnIfRequestHandlerReplaced(\"onteardown\",this._onteardown,Z),this._onteardown=Z,this.replaceRequestHandler(E,($,J)=>{if(!this._onteardown)throw Error(\"No onteardown handler set\");return this._onteardown($.params,J)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(Z){this.warnIfRequestHandlerReplaced(\"oncalltool\",this._oncalltool,Z),this._oncalltool=Z,this.replaceRequestHandler(OQ,($,J)=>{if(!this._oncalltool)throw Error(\"No oncalltool handler set\");return this._oncalltool($.params,J)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(Z){this.warnIfRequestHandlerReplaced(\"onlisttools\",this._onlisttools,Z),this._onlisttools=Z,this.replaceRequestHandler(AQ,($,J)=>{if(!this._onlisttools)throw Error(\"No onlisttools handler set\");return this._onlisttools($.params,J)})}assertCapabilityForMethod(Z){switch(Z){case\"sampling/createMessage\":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${Z})`);break}}assertRequestHandlerCapability(Z){switch(Z){case\"tools/call\":case\"tools/list\":if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${Z})`);return;case\"ping\":case\"ui/resource-teardown\":return;default:throw Error(`No handler for method ${Z} registered`)}}assertNotificationCapability(Z){}assertTaskCapability(Z){throw Error(\"Tasks are not supported in MCP Apps\")}assertTaskHandlerCapability(Z){throw Error(\"Task handlers are not supported in MCP Apps\")}async callServerTool(Z,$){if(this._assertInitialized(\"callServerTool\"),typeof Z===\"string\")throw Error(`callServerTool() expects an object as its first argument, but received a string (\"${Z}\"). Did you mean: callServerTool({ name: \"${Z}\", arguments: { ... } })?`);return await this.request({method:\"tools/call\",params:Z},IQ,{onprogress:()=>{},resetTimeoutOnProgress:!0,...$})}async readServerResource(Z,$){return this._assertInitialized(\"readServerResource\"),await this.request({method:\"resources/read\",params:Z},RQ,$)}async listServerResources(Z,$){return this._assertInitialized(\"listServerResources\"),await this.request({method:\"resources/list\",params:Z},_Q,$)}async createSamplingMessage(Z,$){this._assertInitialized(\"createSamplingMessage\");let J=Z.tools?wQ:PQ;return await this.request({method:\"sampling/createMessage\",params:Z},J,$)}sendMessage(Z,$){return this._assertInitialized(\"sendMessage\"),this.request({method:\"ui/message\",params:Z},w,$)}sendLog(Z){return this.notification({method:\"notifications/message\",params:Z})}updateModelContext(Z,$){return this._assertInitialized(\"updateModelContext\"),this.request({method:\"ui/update-model-context\",params:Z},HQ,$)}openLink(Z,$){return this._assertInitialized(\"openLink\"),this.request({method:\"ui/open-link\",params:Z},I,$)}sendOpenLink=this.openLink;downloadFile(Z,$){return this._assertInitialized(\"downloadFile\"),this.request({method:\"ui/download-file\",params:Z},P,$)}requestTeardown(Z={}){return this.notification({method:\"ui/notifications/request-teardown\",params:Z})}requestDisplayMode(Z,$){return this._assertInitialized(\"requestDisplayMode\"),this.request({method:\"ui/request-display-mode\",params:Z},R,$)}sendSizeChanged(Z){return this.notification({method:\"ui/notifications/size-changed\",params:Z})}setupSizeChangedNotifications(){let Z=!1,$=0,J=0,X=()=>{if(Z)return;Z=!0,requestAnimationFrame(()=>{Z=!1;let D=document.documentElement,L=D.style.height;D.style.height=\"max-content\";let W=Math.ceil(D.getBoundingClientRect().height);D.style.height=L;let B=Math.ceil(window.innerWidth);if(B!==$||W!==J)$=B,J=W,this.sendSizeChanged({width:B,height:W})})};X();let V=new ResizeObserver(X);return V.observe(document.documentElement),V.observe(document.body),()=>V.disconnect()}async connect(Z=new N(window.parent,window.parent),$){if(this.transport)throw Error(\"App is already connected. Call close() before connecting again.\");this._initializedSent=!1,await super.connect(Z);try{let J=await this.request({method:\"ui/initialize\",params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:q}},M,$);if(J===void 0)throw Error(`Server sent invalid initialize result: ${J}`);if(this._hostCapabilities=J.hostCapabilities,this._hostInfo=J.hostInfo,this._hostContext=J.hostContext,await this.notification({method:\"ui/notifications/initialized\"}),this._initializedSent=!0,this.options?.autoResize)this.setupSizeChangedNotifications()}catch(J){throw this.close(),J}}}function K3(Z,$,J,X){let V=J._meta,D=V.ui,L=V[C],W=V;if(D?.resourceUri&&!L)W={...V,[C]:D.resourceUri};else if(L&&!D?.resourceUri)W={...V,ui:{...D,resourceUri:L}};return Z.registerTool($,{...J,_meta:W},X)}function N3(Z,$,J,X,V){return Z.registerResource($,J,{mimeType:p,...X},V)}var TQ=\"io.modelcontextprotocol/ui\";function Y3(Z){if(!Z)return;return Z.extensions?.[TQ]}export{K3 as registerAppTool,N3 as registerAppResource,Y3 as getUiCapability,C as RESOURCE_URI_META_KEY,p as RESOURCE_MIME_TYPE,TQ as EXTENSION_ID};\n","import { Inject, Injectable, Logger, OnModuleInit, Scope } from '@nestjs/common';\nimport { DiscoveryService } from '@nestjs/core';\nimport { MCP_MODULE_OPTIONS } from '../constants';\nimport type { McpModuleOptions } from '../types';\nimport { collectFromClass, isMcpToolsClass, mergeAndValidate, type CollectedDefinitions } from '../metadata';\nimport type { McpToolDefinition, McpUiResourceDefinition } from '../types';\n\n/**\n * McpRegistryService\n *\n * 应用启动时扫描所有 provider / controller,收集被 `@McpTools()` 标记的类及其\n * `@McpTool()` / `@McpUiResource()` 方法,形成工具与资源注册表。\n * 定义冲突(重名、非法名、悬空的 ui.resourceUri)会在启动阶段直接抛错,避免带病上线。\n */\n@Injectable()\nexport class McpRegistryService implements OnModuleInit {\n private readonly logger = new Logger(McpRegistryService.name);\n private definitions: CollectedDefinitions = { tools: [], resources: [] };\n private initialized = false;\n\n constructor(\n @Inject(DiscoveryService) private readonly discoveryService: DiscoveryService,\n @Inject(MCP_MODULE_OPTIONS) private readonly options: McpModuleOptions,\n ) {}\n\n onModuleInit(): void {\n // 显式关闭时不做发现,避免定义冲突在「已关闭」的情况下阻断应用启动\n if (this.options.enabled === false) {\n this.initialized = true;\n return;\n }\n this.discover();\n }\n\n /** 全部工具定义(已绑定实例) */\n getTools(): McpToolDefinition[] {\n return this.definitions.tools;\n }\n\n /** 全部 MCP Apps 资源定义(已绑定实例) */\n getResources(): McpUiResourceDefinition[] {\n return this.definitions.resources;\n }\n\n /** 是否至少注册了一个工具或资源 */\n hasAny(): boolean {\n return this.definitions.tools.length > 0 || this.definitions.resources.length > 0;\n }\n\n /** 是否已完成扫描 */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n private discover(): void {\n const wrappers = [...this.discoveryService.getProviders(), ...this.discoveryService.getControllers()];\n const parts: CollectedDefinitions[] = [];\n const seen = new Set<unknown>();\n\n for (const wrapper of wrappers) {\n if (isMcpToolsClass(wrapper.metatype) &&\n (wrapper.scope === Scope.REQUEST || wrapper.scope === Scope.TRANSIENT || !wrapper.isDependencyTreeStatic())) {\n throw new Error(`${wrapper.metatype.name}: MCP 工具必须使用单例及单例依赖,通过 ctx.user 读取请求身份`);\n }\n const { instance } = wrapper;\n if (!instance || typeof instance !== 'object') {\n if (isMcpToolsClass(wrapper.metatype)) {\n this.logger.warn(\n `${wrapper.metatype.name} 标记了 @McpTools() 但没有可用实例(request/transient 作用域或未实例化),已跳过`,\n );\n }\n continue;\n }\n const target = instance.constructor;\n if (!isMcpToolsClass(target) || seen.has(instance)) continue;\n seen.add(instance);\n parts.push(collectFromClass(target, instance));\n }\n\n this.definitions = mergeAndValidate(parts);\n this.initialized = true;\n\n const { tools, resources } = this.definitions;\n if (tools.length === 0 && resources.length === 0) {\n this.logger.debug('未发现 MCP 工具,/__innerapi__/mcp 将返回 404');\n return;\n }\n this.logger.log(\n `已注册 ${tools.length} 个 MCP 工具${resources.length ? `、${resources.length} 个 MCP Apps 资源` : ''}:${tools\n .map((t) => t.name)\n .join(', ')}`,\n );\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport 'reflect-metadata';\nimport {\n MCP_TOOL_METADATA_KEY,\n MCP_TOOL_NAME_PATTERN,\n MCP_TOOLS_METADATA_KEY,\n MCP_UI_RESOURCE_METADATA_KEY,\n MCP_UI_RESOURCE_SCHEME,\n} from './constants';\nimport type {\n McpToolDefinition,\n McpToolOptions,\n McpToolsOptions,\n McpUiResourceDefinition,\n McpUiResourceOptions,\n} from './types';\n\ntype AnyClass = new (...args: any[]) => any;\n\n/**\n * 判断一个类是否被 `@McpTools()` 标记。\n */\nexport function isMcpToolsClass(target: unknown): target is AnyClass {\n return typeof target === 'function' && Reflect.getMetadata(MCP_TOOLS_METADATA_KEY, target) !== undefined;\n}\n\n/**\n * 枚举原型链上的所有方法名(不含 Object.prototype 与 constructor)。\n */\nfunction getAllMethodNames(prototype: object): string[] {\n const names = new Set<string>();\n let current: object | null = prototype;\n while (current && current !== Object.prototype) {\n for (const name of Object.getOwnPropertyNames(current)) {\n if (name === 'constructor') continue;\n const descriptor = Object.getOwnPropertyDescriptor(current, name);\n if (descriptor && typeof descriptor.value === 'function') {\n names.add(name);\n }\n }\n current = Object.getPrototypeOf(current);\n }\n return [...names];\n}\n\nexport interface CollectedDefinitions {\n tools: McpToolDefinition[];\n resources: McpUiResourceDefinition[];\n}\n\n/**\n * 从一个工具类收集工具与资源定义。\n *\n * @param target 被 `@McpTools()` 标记的类\n * @param instance 可选实例;提供时会把方法绑定到实例上作为 handler\n */\nexport function collectFromClass(target: AnyClass, instance?: object): CollectedDefinitions {\n const classOptions = (Reflect.getMetadata(MCP_TOOLS_METADATA_KEY, target) ?? {}) as McpToolsOptions;\n const prototype = target.prototype as Record<string, unknown>;\n const tools: McpToolDefinition[] = [];\n const resources: McpUiResourceDefinition[] = [];\n\n for (const methodName of getAllMethodNames(prototype)) {\n const method = prototype[methodName] as (...args: unknown[]) => unknown;\n const toolOptions = Reflect.getMetadata(MCP_TOOL_METADATA_KEY, method) as McpToolOptions<any, any> | undefined;\n const resourceOptions = Reflect.getMetadata(MCP_UI_RESOURCE_METADATA_KEY, method) as\n | McpUiResourceOptions\n | undefined;\n\n if (toolOptions && resourceOptions) {\n throw new Error(`${target.name}.${methodName} 不能同时标记 @McpTool() 与 @McpUiResource()`);\n }\n\n if (toolOptions) {\n const name = `${classOptions.prefix ?? ''}${toolOptions.name ?? methodName}`;\n tools.push({\n name,\n options: toolOptions,\n className: target.name,\n methodName,\n handler: instance ? (method as any).bind(instance) : undefined,\n });\n } else if (resourceOptions) {\n resources.push({\n name: resourceOptions.name ?? methodName,\n options: resourceOptions,\n className: target.name,\n methodName,\n handler: instance ? (method as any).bind(instance) : undefined,\n });\n }\n }\n\n return { tools, resources };\n}\n\n/**\n * 校验并合并多个类的定义:检查工具名格式、重名、资源 URI 重复以及 `ui.resourceUri` 是否存在。\n * 校验失败时抛出带完整问题列表的错误。\n */\nexport function mergeAndValidate(parts: CollectedDefinitions[]): CollectedDefinitions {\n const tools: McpToolDefinition[] = [];\n const resources: McpUiResourceDefinition[] = [];\n const problems: string[] = [];\n\n const toolNames = new Map<string, string>();\n const resourceUris = new Map<string, string>();\n\n for (const part of parts) {\n for (const tool of part.tools) {\n const location = `${tool.className}.${tool.methodName}`;\n if (!MCP_TOOL_NAME_PATTERN.test(tool.name)) {\n problems.push(`工具名「${tool.name}」不合法(${location}),需匹配 ${MCP_TOOL_NAME_PATTERN}`);\n }\n const existing = toolNames.get(tool.name);\n if (existing) {\n problems.push(`工具名「${tool.name}」重复:${existing} 与 ${location}`);\n } else {\n toolNames.set(tool.name, location);\n }\n tools.push(tool);\n }\n for (const resource of part.resources) {\n const location = `${resource.className}.${resource.methodName}`;\n const uri = resource.options.uri;\n if (!uri.startsWith(MCP_UI_RESOURCE_SCHEME)) {\n problems.push(`资源 URI「${uri}」必须以 ${MCP_UI_RESOURCE_SCHEME} 开头(${location})`);\n }\n const existing = resourceUris.get(uri);\n if (existing) {\n problems.push(`资源 URI「${uri}」重复:${existing} 与 ${location}`);\n } else {\n resourceUris.set(uri, location);\n }\n resources.push(resource);\n }\n }\n\n for (const tool of tools) {\n const resourceUri = tool.options.ui?.resourceUri;\n if (resourceUri && !resourceUris.has(resourceUri)) {\n problems.push(\n `工具「${tool.name}」引用的 ui.resourceUri「${resourceUri}」未找到对应的 @McpUiResource()(${tool.className}.${tool.methodName})`,\n );\n }\n }\n\n if (problems.length > 0) {\n throw new Error(`MCP 定义校验失败:\\n- ${problems.join('\\n- ')}`);\n }\n\n return { tools, resources };\n}\n","import { constants, promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { MCP_SKILL_PATH, MCP_SKILL_URI } from './constants';\nimport type { McpSkill } from './types';\n\n/** 一份工程正文,供 manifest 与 MCP Resource 共用;只读取,不生成或修改。 */\nexport async function readMcpSkill(cwd: string = process.cwd()): Promise<McpSkill | null> {\n const root = await fs.realpath(cwd);\n let file: string;\n try {\n file = await fs.realpath(path.join(root, MCP_SKILL_PATH));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw error;\n }\n const relative = path.relative(root, file);\n if (relative.startsWith('..') || path.isAbsolute(relative)) throw new Error('MCP Skill 必须位于应用工程内');\n if (!(await fs.stat(file)).isFile()) throw new Error('MCP Skill 必须为普通文件');\n // 防止检查后文件被替换为 FIFO 或符号链接,阻塞请求或越出工程。\n const handle = await fs.open(file, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);\n try {\n const stat = await handle.stat();\n const limit = 1024 * 1024;\n if (!stat.isFile() || stat.size > limit) throw new Error('MCP Skill 必须为不超过 1 MiB 的普通文件');\n // 有界读取,避免文件在 stat 后增长导致无界分配。\n const buffer = Buffer.alloc(limit + 1);\n let length = 0;\n while (length < buffer.length) {\n const { bytesRead } = await handle.read(buffer, length, buffer.length - length, null);\n if (bytesRead === 0) break;\n length += bytesRead;\n }\n if (length > limit) throw new Error('MCP Skill 不能超过 1 MiB');\n const content = new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, length));\n return { uri: MCP_SKILL_URI, path: MCP_SKILL_PATH, content };\n } finally {\n await handle.close();\n }\n}\n","import { promises as fs } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport type * as TS from 'typescript';\n\ntype Definition = { name: string; className: string; methodName: string };\ntype SourceLocation = { path: string; line?: number };\ntype SourceLocations = {\n tools: Record<string, SourceLocation>;\n resources: Record<string, SourceLocation>;\n};\n\n// The core package officially re-exports nestjs-mcp; do not follow arbitrary barrels.\nconst sdkEntrypoints = new Set(['@lark-apaas/nestjs-mcp', '@lark-apaas/fullstack-nestjs-core']);\nconst ignored = new Set(['node_modules', 'dist', 'build', 'coverage', '__tests__', '__test__', 'test', 'tests']);\n\nfunction isInside(root: string, file: string): boolean {\n const relative = path.relative(root, file);\n return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);\n}\n\n/**\n * Best-effort development source hints, keyed by tool name / resource URI.\n * Only server TS declarations and client/mcp-ui/<entry>/index.html are eligible.\n * No application modules or handlers are executed. TypeScript is loaded from the\n * consuming project, never required as a production dependency of this package.\n * Custom re-exports, inherited methods and dynamic UI entries are deliberately omitted.\n * Lines describe the current disk source; the caller owns runtime/version matching.\n */\nexport async function collectSourceLocations(\n tools: Array<Definition>,\n resources: Array<Definition & { options: { uri: string } }>,\n cwd = process.cwd(),\n): Promise<SourceLocations> {\n const empty = (): SourceLocations => ({ tools: {}, resources: {} });\n try {\n if (!tools.length && !resources.length) return empty();\n const root = await fs.realpath(cwd);\n const server = path.join(root, 'server');\n // Do not follow source directory symlinks, including the scan root.\n if ((await fs.lstat(server)).isSymbolicLink()) return empty();\n const ts: typeof TS = createRequire(path.join(root, 'package.json'))('typescript');\n const sources = new Map<string, string>();\n const scan = async (directory: string): Promise<void> => {\n for (const item of await fs.readdir(directory, { withFileTypes: true })) {\n if (item.isSymbolicLink() || item.name.startsWith('.') || ignored.has(item.name)) continue;\n const file = path.join(directory, item.name);\n if (item.isDirectory()) await scan(file);\n else if (item.isFile() && /\\.(?:ts|tsx|mts|cts)$/.test(item.name) &&\n !/\\.(?:d|spec|test)\\.(?:ts|tsx|mts|cts)$/.test(item.name)) {\n sources.set(file, await fs.readFile(file, 'utf8'));\n }\n }\n };\n await scan(server);\n if (!sources.size) return empty();\n // An isolated host prevents module resolution from reading dependencies or JS.\n const options: TS.CompilerOptions = { noLib: true, noResolve: true, experimentalDecorators: true };\n const host = ts.createCompilerHost(options);\n host.getSourceFile = (file, languageVersion) => {\n const text = sources.get(file);\n return text === undefined ? undefined : ts.createSourceFile(file, text, languageVersion, true);\n };\n const program = ts.createProgram([...sources.keys()], options, host);\n if (program.getSyntacticDiagnostics().length) return empty();\n const checker = program.getTypeChecker();\n\n // Resolve the local symbol, rather than matching spelling (aliases and shadowing).\n const isSdkReference = (expression: TS.Expression, exported: string): boolean => {\n let identifier: TS.Identifier;\n let namespace = false;\n if (ts.isIdentifier(expression)) identifier = expression;\n else if (ts.isPropertyAccessExpression(expression) && ts.isIdentifier(expression.expression) &&\n expression.name.text === exported) {\n identifier = expression.expression;\n namespace = true;\n } else return false;\n const declarations = checker.getSymbolAtLocation(identifier)?.declarations;\n if (declarations?.length !== 1) return false;\n const declaration = declarations[0];\n let clause: TS.ImportClause;\n if (!namespace && ts.isImportSpecifier(declaration) && !declaration.isTypeOnly &&\n (declaration.propertyName ?? declaration.name).text === exported) {\n clause = declaration.parent.parent;\n } else if (namespace && ts.isNamespaceImport(declaration)) clause = declaration.parent;\n else return false;\n return !clause.isTypeOnly && ts.isStringLiteral(clause.parent.moduleSpecifier) &&\n sdkEntrypoints.has(clause.parent.moduleSpecifier.text);\n };\n const decorated = (node: TS.Node, exported: string): boolean => {\n return ts.canHaveDecorators(node) && !!ts.getDecorators(node)?.some(({ expression }) =>\n ts.isCallExpression(expression) && isSdkReference(expression.expression, exported));\n };\n const classes = new Map<string, TS.ClassDeclaration[]>();\n for (const source of program.getSourceFiles()) {\n const visit = (node: TS.Node): void => {\n // Count even unrecognized classes: their runtime metadata may be inherited\n // or supplied through a custom decorator/barrel we cannot resolve.\n if (ts.isClassDeclaration(node) && node.name) {\n const matches = classes.get(node.name.text) ?? [];\n matches.push(node);\n classes.set(node.name.text, matches);\n }\n ts.forEachChild(node, visit);\n };\n visit(source);\n }\n const methodFor = (definition: Definition, decorator: string): TS.MethodDeclaration | undefined => {\n const matches = classes.get(definition.className);\n if (matches?.length !== 1 || !decorated(matches[0], 'McpTools')) return undefined;\n const methods = matches[0].members.filter((member): member is TS.MethodDeclaration =>\n ts.isMethodDeclaration(member) &&\n (ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)) &&\n member.name.text === definition.methodName);\n if (methods.length !== 1 || !methods[0].body || !decorated(methods[0], decorator)) return undefined;\n return methods[0];\n };\n const result = empty();\n // Duplicate external keys cannot safely be represented by a single location.\n const unique = <T>(items: T[], key: (item: T) => string): T[] => {\n const counts = new Map<string, number>();\n for (const item of items) counts.set(key(item), (counts.get(key(item)) ?? 0) + 1);\n return items.filter(item => counts.get(key(item)) === 1);\n };\n const put = (map: Record<string, SourceLocation>, key: string, value: SourceLocation): void => {\n Object.defineProperty(map, key, { value, enumerable: true, configurable: true, writable: true });\n };\n for (const tool of unique(tools, item => item.name)) {\n const method = methodFor(tool, 'McpTool');\n if (!method) continue;\n const source = method.getSourceFile();\n put(result.tools, tool.name, {\n path: path.relative(root, source.fileName).split(path.sep).join('/'),\n line: source.getLineAndCharacterOfPosition(method.name.getStart(source)).line + 1,\n });\n }\n for (const resource of unique(resources, item => item.options.uri)) {\n const method = methodFor(resource, 'McpUiResource');\n if (!method) continue;\n const calls: TS.CallExpression[] = [];\n const visit = (node: TS.Node): void => {\n // Nested handlers are not evidence that this resource reads their template.\n if (ts.isFunctionLike(node) || ts.isClassLike(node)) return;\n if (ts.isCallExpression(node) && isSdkReference(node.expression, 'readMcpUiTemplate')) calls.push(node);\n ts.forEachChild(node, visit);\n };\n visit(method.body!);\n if (calls.length !== 1 || calls[0].arguments.length !== 1) continue;\n const entry = calls[0].arguments[0];\n if (!(ts.isStringLiteral(entry) || ts.isNoSubstitutionTemplateLiteral(entry)) ||\n !/^[A-Za-z0-9_-]+$/.test(entry.text)) continue;\n const relative = `client/mcp-ui/${entry.text}/index.html`;\n try {\n const file = await fs.realpath(path.join(root, relative));\n // Require the original fixed path: aliases/symlinks must not escape it.\n if (file !== path.join(root, relative) || !isInside(root, file) || !(await fs.stat(file)).isFile()) continue;\n put(result.resources, resource.options.uri, { path: relative });\n } catch { /* Missing UI source is normal in production. */ }\n }\n return result;\n } catch {\n // Source hints must never break discovery, including partial scans / missing TS.\n return empty();\n }\n}\n","import { All, Controller, Inject, Logger, Post, Req, Res } from '@nestjs/common';\nimport { ApiExcludeController } from '@nestjs/swagger';\nimport type { Request, Response } from 'express';\nimport { MCP_CONTROLLER_PATH } from '../constants';\nimport { McpServerService } from '../services/mcp-server.service';\n\n/**\n * McpController\n *\n * `POST /__innerapi__/mcp`:MCP over Streamable HTTP 的唯一端点,请求体为 JSON-RPC。\n * 本期为无状态模式,不提供 SSE 长连接,因此 GET / DELETE 返回 405。\n */\n@ApiExcludeController()\n@Controller(MCP_CONTROLLER_PATH)\nexport class McpController {\n private readonly logger = new Logger(McpController.name);\n\n constructor(\n @Inject(McpServerService) private readonly serverService: McpServerService,\n ) {}\n\n @Post()\n async handlePost(@Req() req: Request, @Res() res: Response): Promise<void> {\n try {\n await this.serverService.handle(req, res);\n } catch (error) {\n this.logger.error(`处理 MCP 请求失败:${error instanceof Error ? error.stack ?? error.message : String(error)}`);\n if (!res.headersSent) {\n res.status(500).json({\n jsonrpc: '2.0',\n error: { code: -32603, message: 'Internal server error' },\n id: null,\n });\n }\n }\n }\n\n /** GET / DELETE 等其他方法:无状态模式不提供 SSE 会话,统一 405 */\n @All()\n handleOthers(@Res() res: Response): void {\n this.methodNotAllowed(res);\n }\n\n private methodNotAllowed(res: Response): void {\n res.setHeader('Allow', 'POST');\n res.status(405).json({\n jsonrpc: '2.0',\n error: { code: -32000, message: 'Method not allowed. 仅支持 POST(无状态 Streamable HTTP)' },\n id: null,\n });\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Inject, Injectable, Logger } from '@nestjs/common';\nimport type { Request, Response } from 'express';\nimport { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\nimport { MCP_MODULE_OPTIONS } from '../constants';\nimport { readMcpSkill } from '../skill';\nimport { createMcpServer } from '../server-factory';\nimport { McpRegistryService } from './mcp-registry.service';\nimport type { McpContext, McpModuleOptions } from '../types';\n\n/**\n * McpServerService\n *\n * 以无状态 Streamable HTTP 方式处理 MCP 请求:每个 HTTP 请求装配一个 McpServer 与\n * 一次性的 transport,工具执行时通过闭包读取该请求的 `req.userContext`,\n * 因而不同用户的调用天然隔离,也不依赖会话存储。\n */\n@Injectable()\nexport class McpServerService {\n private readonly logger = new Logger(McpServerService.name);\n\n constructor(\n @Inject(McpRegistryService) private readonly registry: McpRegistryService,\n @Inject(MCP_MODULE_OPTIONS) private readonly options: McpModuleOptions,\n ) {}\n\n /**\n * 为一次 HTTP 请求构造执行上下文。\n */\n createContext(req: Request, extra: any): McpContext {\n return {\n user: (req as any).userContext ?? {},\n request: req,\n signal: extra?.signal ?? new AbortController().signal,\n requestId: extra?.requestId ?? '',\n extra,\n };\n }\n\n /**\n * 处理一条 MCP over Streamable HTTP 请求(POST)。\n */\n async handle(req: Request, res: Response): Promise<void> {\n const skill = await readMcpSkill();\n if (!this.registry.hasAny() && !skill) {\n res.status(404).json({ jsonrpc: '2.0', error: { code: -32000, message: '当前应用未注册任何 MCP 能力' }, id: null });\n return;\n }\n const server = createMcpServer({\n skill,\n tools: this.registry.getTools(),\n resources: this.registry.getResources(),\n options: this.options,\n createContext: (extra) => this.createContext(req, extra),\n onError: (error, location) => {\n this.logger.error(\n `MCP 工具执行异常(${location}):${error instanceof Error ? error.stack ?? error.message : String(error)}`,\n );\n },\n });\n\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n enableJsonResponse: true,\n });\n\n // 响应结束即释放本次请求的 server 与 transport(server.close 会一并关闭 transport)\n res.on('close', () => {\n server.close().catch((error: unknown) => {\n this.logger.warn(`关闭 McpServer 失败:${error instanceof Error ? error.message : String(error)}`);\n });\n });\n\n await server.connect(transport);\n await transport.handleRequest(req, res, req.body);\n }\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { MCP_UI_DIST_DIR } from './constants';\n\nconst cache = new Map<string, string>();\n\n/**\n * 读取构建预设产出的 MCP Apps 单文件 HTML(`dist/mcp-ui/<entry>.html`)。\n *\n * 生产环境读取一次后缓存;开发环境每次重新读取,配合预设的 watch 构建实现界面热更新。\n *\n * @param entry `client/mcp-ui/<entry>/` 目录名\n * @param cwd 工程根目录,默认 process.cwd()\n */\nexport async function readMcpUiTemplate(entry: string, cwd: string = process.cwd()): Promise<string> {\n if (!/^[A-Za-z0-9_-]+$/.test(entry)) {\n throw new Error(`MCP Apps 界面入口名「${entry}」不合法,仅允许字母、数字、下划线与连字符`);\n }\n const file = path.join(cwd, MCP_UI_DIST_DIR, `${entry}.html`);\n const useCache = process.env.NODE_ENV === 'production';\n if (useCache && cache.has(file)) {\n return cache.get(file) as string;\n }\n let html: string;\n try {\n html = await fs.readFile(file, 'utf8');\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `读取 MCP Apps 界面产物失败:${file}。请确认 client/mcp-ui/${entry}/index.html 存在且已执行构建。原因:${reason}`,\n );\n }\n if (useCache) cache.set(file, html);\n return html;\n}\n\n/** 仅供测试:清空模板缓存 */\nexport function clearMcpUiTemplateCache(): void {\n cache.clear();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;ACOO,IAAMA,oBAAoB;AAK1B,IAAMC,sBAAsB;AAQ5B,IAAMC,oBAAoB;AAK1B,IAAMC,kBAAkB;AAKxB,IAAMC,yBAAyB;AAG/B,IAAMC,yBAAyB;AAE/B,IAAMC,wBAAwB;AAE9B,IAAMC,+BAA+B;AAGrC,IAAMC,qBAAqBC,uBAAO,oBAAA;AAGlC,IAAMC,0BAA0B;AAEhC,IAAMC,6BAA6B;AAGnC,IAAMC,uBAAuB;AAK7B,IAAMC,wBAAwB;AAG9B,IAAMC,iBAAiB;AACvB,IAAMC,gBAAgB;;;AClDtB,IAAMC,eAAN,cAA2BC,MAAAA;EAPlC,OAOkCA;;;;EAEvBC;;EAEAC;EAET,YAAYC,SAAiBC,UAA6C,CAAC,GAAG;AAC5E,UAAMD,OAAAA;AACN,SAAKE,OAAO;AACZ,SAAKJ,OAAOG,QAAQH;AACpB,SAAKC,OAAOE,QAAQF;EACtB;AACF;;;ACnBA,oBAAwC;AAyBjC,IAAMI,WAAW,wBAACC,UAA2B,CAAC,MAAC;AAEpD,SAAO,CAACC,WAAAA;AACNC,kCAAAA,EAAaD,MAAAA;AACbE,mCAAYC,wBAAwBJ,OAAAA,EAASC,MAAAA;AAC7C,WAAOA;EACT;AACF,GAPwB;;;ACzBxB,IAAAI,iBAA4B;AAcrB,SAASC,QAGdC,SAA6B;AAC7B,SAAO,CACLC,QACAC,aACAC,eAAAA;AAEA,QAAI,OAAOD,gBAAgB,UAAU;AACnC,YAAM,IAAIE,UAAU,6DAAA;IACtB;AACA,QAAI,CAACJ,WAAW,OAAOA,QAAQK,gBAAgB,YAAYL,QAAQK,YAAYC,KAAI,MAAO,IAAI;AAC5F,YAAM,IAAIF,UAAU,qBAAgBH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AUC,OAAOH,KAAAA;AAC/D,UAAM,IAAIb,MACR,mEAAsBC,IAAAA,0CAA0BL,KAAAA,uFAAgCkB,MAAAA,EAAQ;EAE5F;AACA,MAAIT,SAAUZ,OAAMwB,IAAIhB,MAAMS,IAAAA;AAC9B,SAAOA;AACT;AApBsBf;","names":["MCP_ENDPOINT_PATH","MCP_CONTROLLER_PATH","MCP_MANIFEST_PATH","MCP_UI_DIST_DIR","MCP_UI_RESOURCE_SCHEME","MCP_TOOLS_METADATA_KEY","MCP_TOOL_METADATA_KEY","MCP_UI_RESOURCE_METADATA_KEY","MCP_MODULE_OPTIONS","Symbol","MCP_DEFAULT_SERVER_NAME","MCP_DEFAULT_SERVER_VERSION","MCP_MANIFEST_VERSION","MCP_TOOL_NAME_PATTERN","MCP_SKILL_PATH","MCP_SKILL_URI","McpToolError","Error","code","data","message","options","name","McpTools","options","target","Injectable","SetMetadata","MCP_TOOLS_METADATA_KEY","import_common","McpTool","options","target","propertyKey","descriptor","TypeError","description","trim","name","SetMetadata","MCP_TOOL_METADATA_KEY","import_common","McpUiResource","options","target","propertyKey","descriptor","TypeError","uri","startsWith","MCP_UI_RESOURCE_SCHEME","name","SetMetadata","MCP_UI_RESOURCE_METADATA_KEY","import_common","import_core","import_common","import_node_fs","import_node_path","import_common","import_protocol","import_types","import_v4","r","Z","require","Proxy","get","$","J","apply","arguments","Error","v","Q","union","literal","describe","K","QQ","ZQ","record","string","undefined","$Q","object","method","params","url","I","isError","boolean","optional","passthrough","P","w","JQ","Y","connectDomains","array","resourceDomains","frameDomains","baseUriDomains","j","camera","microphone","geolocation","clipboardWrite","XQ","width","number","height","H","arguments","unknown","_","A","reason","f","fonts","u","variables","css","E","VQ","O","text","image","audio","resource","resourceLink","structuredContent","DQ","d","experimental","any","openLinks","downloadFile","serverTools","listChanged","serverResources","logging","sandbox","permissions","csp","updateModelContext","message","sampling","tools","h","availableDisplayModes","LQ","WQ","domain","prefersBorder","BQ","mode","R","m","GQ","resourceUri","visibility","never","dQ","mimeTypes","KQ","contents","a","t","NQ","role","content","y","YQ","html","U","o","T","toolInfo","id","s","tool","e","theme","styles","displayMode","containerDimensions","maxHeight","and","maxWidth","locale","timeZone","userAgent","platform","deviceCapabilities","touch","hover","safeAreaInsets","top","right","bottom","left","k","jQ","FQ","appInfo","g","appCapabilities","protocolVersion","M","hostInfo","hostCapabilities","hostContext","C","p","K3","Z","$","J","X","V","_meta","D","ui","L","C","W","resourceUri","registerTool","N3","registerResource","mimeType","p","resolveServerInfo","options","name","serverName","process","env","SUDA_APP_ID","MCP_DEFAULT_SERVER_NAME","version","serverVersion","MCP_DEFAULT_SERVER_VERSION","normalizeSchema","schema","buildToolMeta","def","ui","meta","undefined","merged","resourceUri","visibility","MISSING_USER_MESSAGE","assertUser","ctx","requireUser","user","userId","McpToolError","code","toErrorResult","error","location","onError","payload","message","data","isError","content","type","text","structuredContent","_meta","createMcpServer","input","tools","resources","createContext","server","McpServer","instructions","noContext","Error","className","methodName","config","title","description","inputSchema","outputSchema","annotations","callback","args","extra","handler","result","JSON","stringify","registerAppTool","registerTool","uri","csp","permissions","uiMeta","registerAppResource","mimeType","RESOURCE_MIME_TYPE","Object","keys","length","html","contents","href","skill","registerResource","buildManifest","input","server","createMcpServer","tools","resources","options","skill","client","Client","name","version","clientTransport","serverTransport","InMemoryTransport","createLinkedPair","Promise","all","connect","toolSource","Map","map","t","className","methodName","resourceSource","r","uri","length","listTools","listResources","manifest","MCP_MANIFEST_VERSION","generatedAt","Date","toISOString","endpoint","MCP_ENDPOINT_PATH","resolveServerInfo","path","tool","source","get","sort","a","b","localeCompare","resource","allSettled","close","serializeManifest","JSON","stringify","stripVolatile","json","replace","writeManifest","cwd","relativePath","MCP_MANIFEST_PATH","fs","file","resolve","next","previous","readFile","undefined","changed","mkdir","dirname","recursive","temporary","randomUUID","writeFile","rename","rm","force","import_common","isMcpToolsClass","target","Reflect","getMetadata","MCP_TOOLS_METADATA_KEY","undefined","getAllMethodNames","prototype","names","Set","current","Object","name","getOwnPropertyNames","descriptor","getOwnPropertyDescriptor","value","add","getPrototypeOf","collectFromClass","instance","classOptions","tools","resources","methodName","method","toolOptions","MCP_TOOL_METADATA_KEY","resourceOptions","MCP_UI_RESOURCE_METADATA_KEY","Error","prefix","push","options","className","handler","bind","mergeAndValidate","parts","problems","toolNames","Map","resourceUris","part","tool","location","MCP_TOOL_NAME_PATTERN","test","existing","get","set","resource","uri","startsWith","MCP_UI_RESOURCE_SCHEME","resourceUri","ui","has","length","join","McpRegistryService","logger","Logger","name","definitions","tools","resources","initialized","discoveryService","options","onModuleInit","enabled","discover","getTools","getResources","hasAny","length","isInitialized","wrappers","getProviders","getControllers","parts","seen","Set","wrapper","isMcpToolsClass","metatype","scope","Scope","REQUEST","TRANSIENT","isDependencyTreeStatic","Error","instance","warn","target","has","add","push","collectFromClass","mergeAndValidate","debug","log","map","t","join","import_node_path","readMcpSkill","cwd","process","root","fs","realpath","file","path","join","MCP_SKILL_PATH","error","code","relative","startsWith","isAbsolute","Error","stat","isFile","handle","open","constants","O_RDONLY","O_NONBLOCK","O_NOFOLLOW","limit","size","buffer","Buffer","alloc","length","bytesRead","read","content","TextDecoder","fatal","decode","subarray","uri","MCP_SKILL_URI","close","import_node_fs","import_node_path","sdkEntrypoints","Set","ignored","isInside","root","file","relative","path","startsWith","sep","isAbsolute","collectSourceLocations","tools","resources","cwd","process","empty","length","fs","realpath","server","join","lstat","isSymbolicLink","ts","createRequire","sources","Map","scan","directory","item","readdir","withFileTypes","name","has","isDirectory","isFile","test","set","readFile","size","options","noLib","noResolve","experimentalDecorators","host","createCompilerHost","getSourceFile","languageVersion","text","get","undefined","createSourceFile","program","createProgram","keys","getSyntacticDiagnostics","checker","getTypeChecker","isSdkReference","expression","exported","identifier","namespace","isIdentifier","isPropertyAccessExpression","declarations","getSymbolAtLocation","declaration","clause","isImportSpecifier","isTypeOnly","propertyName","parent","isNamespaceImport","isStringLiteral","moduleSpecifier","decorated","node","canHaveDecorators","getDecorators","some","isCallExpression","classes","source","getSourceFiles","visit","isClassDeclaration","matches","push","forEachChild","methodFor","definition","decorator","className","methods","members","filter","member","isMethodDeclaration","methodName","body","result","unique","items","key","counts","put","map","value","Object","defineProperty","enumerable","configurable","writable","tool","method","fileName","split","line","getLineAndCharacterOfPosition","getStart","resource","uri","calls","isFunctionLike","isClassLike","arguments","entry","isNoSubstitutionTemplateLiteral","stat","McpManifestService","logger","Logger","name","sources","tools","resources","registry","options","onApplicationBootstrap","enabled","collectSourceLocations","getTools","getResources","error","warn","Error","message","String","writeOnBoot","manifest","process","env","NODE_ENV","hasAny","readMcpSkill","fs","rm","path","resolve","cwd","MCP_MANIFEST_PATH","force","changed","file","write","log","relative","build","buildManifest","skill","uri","catalog","version","generatedAt","endpoint","map","source","_source","tool","resource","writeManifest","relativePath","McpManifestController","logger","Logger","name","manifest","registry","get","res","setHeader","isInitialized","status","type","json","title","catalog","error","Error","stack","String","import_common","import_swagger","import_common","McpServerService","logger","Logger","name","registry","options","createContext","req","extra","user","userContext","request","signal","AbortController","requestId","handle","res","skill","readMcpSkill","hasAny","status","json","jsonrpc","error","code","message","id","server","createMcpServer","tools","getTools","resources","getResources","onError","location","Error","stack","String","transport","StreamableHTTPServerTransport","sessionIdGenerator","undefined","enableJsonResponse","on","close","catch","warn","connect","handleRequest","body","McpController","logger","Logger","name","serverService","handlePost","req","res","handle","error","Error","stack","message","String","headersSent","status","json","jsonrpc","code","id","handleOthers","methodNotAllowed","setHeader","McpModule","forRoot","options","enabled","providers","provide","MCP_MODULE_OPTIONS","useValue","McpRegistryService","McpServerService","McpManifestService","module","global","imports","DiscoveryModule","controllers","McpManifestController","McpController","exports","import_node_fs","import_node_path","cache","Map","readMcpUiTemplate","entry","cwd","process","test","Error","file","path","join","MCP_UI_DIST_DIR","useCache","env","NODE_ENV","has","get","html","fs","readFile","error","reason","message","String","set"]}
|