@lark-apaas/nestjs-mcp 0.1.1 → 0.1.2

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.
@@ -1 +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/request-log.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/revision.ts","../src/services/mcp-revision.service.ts","../src/development-revision.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, McpNamedSkill, McpSources, McpSourceLocation } from './types';\n\nexport { MCP_APP_REVISION_META_KEY, MCP_APP_REVISION_MISMATCH } from './revision';\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 * 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/** 平台 manifest 接口响应结构版本 */\nexport const MCP_MANIFEST_VERSION = 3;\n\n/**\n * 工具名合法字符(MCP 规范 SEP-986):1~128 位,字母、数字、下划线、连字符、点。\n */\nexport const MCP_TOOL_NAME_PATTERN = /^[A-Za-z0-9_.-]{1,128}$/;\n\n\n/** 多 Skill 的固定源码目录。 */\nexport const MCP_SKILLS_PATH = 'server/mcp/skills';\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 字符串。界面源码放在 `server/mcp/ui/<entry>/` 下(浏览器代码使用 UI 独立 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 { McpRevisionService } from './services/mcp-revision.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 端点,并通过 `GET /__innerapi__/mcp/manifest` 提供实时能力目录。\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 McpRevisionService,\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, Req, Res } from '@nestjs/common';\nimport { ApiExcludeController } from '@nestjs/swagger';\nimport type { Request, Response } from 'express';\nimport { McpRequestLog } from '../request-log';\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 constructor(\n @Inject(McpManifestService) private readonly manifest: McpManifestService,\n @Inject(McpRegistryService) private readonly registry: McpRegistryService,\n ) {}\n\n @Get()\n async get(@Req() req: Request, @Res() res: Response): Promise<void> {\n const log = new McpRequestLog(req, res, 'manifest');\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 log.exception(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 { AsyncResource } from 'node:async_hooks';\nimport { Logger } from '@nestjs/common';\nimport type { Request, Response } from 'express';\nimport { isJSONRPCErrorResponse, isJSONRPCResultResponse, type JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';\n\n/** 与框架平台日志共用上报链路;source_type 是 Observable 消费的字段。 */\nexport const MCP_LOG_ATTRIBUTES = { source_type: 'platform', paas_attributes_module: 'mcp' } as const;\n\nfunction record(value: unknown): Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown> : {};\n}\n\nfunction label(value: unknown): string | undefined {\n return typeof value === 'string' ? value.slice(0, 256) : undefined;\n}\n\n/** 每个 HTTP 请求独立记录;只摘取诊断字段,不保存请求参数或响应正文。 */\nexport class McpRequestLog {\n private readonly logger = new Logger('McpRequest');\n private readonly started = performance.now();\n private readonly fields: Record<string, unknown>;\n private failed = false;\n private reported = false;\n\n constructor(req: Request, res: Response, operation = 'rpc') {\n const body = operation === 'rpc' ? record(req.body) : {};\n const params = record(body.params);\n this.fields = {\n operation,\n http_method: req.method,\n mcp_method: label(body.method),\n rpc_id: typeof body.id === 'number' ? body.id : label(body.id),\n };\n if (body.method === 'tools/call') this.fields.tool_name = label(params.name);\n if (body.method === 'prompts/get') this.fields.prompt_name = label(params.name);\n // URI 可能包含查询凭证;不记录 query、fragment 或 userinfo。\n if (body.method === 'resources/read' && typeof params.uri === 'string') {\n try {\n const uri = new URL(params.uri);\n uri.username = ''; uri.password = ''; uri.search = ''; uri.hash = '';\n this.fields.resource_uri = label(uri.href);\n } catch { /* 非法 URI 交给 MCP 校验,不输出原始输入 */ }\n }\n // socket close 等事件可能在请求异步上下文之外触发,显式保留 trace / 用户上下文。\n res.once('finish', AsyncResource.bind(() => this.complete(res, false)));\n res.once('close', AsyncResource.bind(() => this.complete(res, !res.writableFinished)));\n }\n\n /** SDK 发出的协议结果;HTTP 200 也可能包含工具失败或 JSON-RPC 错误。 */\n response(message: JSONRPCMessage): void {\n if (isJSONRPCErrorResponse(message)) {\n this.failed = true;\n this.fields.error_code = message.error.code;\n this.fields.business_error_code = label(record(message.error.data).code);\n } else if (isJSONRPCResultResponse(message) && message.result.isError === true) {\n this.failed = true;\n this.fields.is_error = true;\n this.fields.business_error_code = label(record(record(message.result._meta).error).code);\n }\n }\n\n /** 未预期异常保留服务端诊断;不向 MCP 响应增加内部信息。 */\n exception(error: unknown, location?: string): void {\n this.failed = true;\n this.fields.location = location;\n this.fields.error_message = error instanceof Error ? error.message : 'Non-Error exception';\n if (error instanceof Error) this.fields.stack = error.stack;\n }\n\n private complete(res: Response, aborted: boolean): void {\n if (this.reported) return;\n this.reported = true;\n const fields = {\n ...this.fields,\n http_status: res.statusCode,\n status: aborted ? 'aborted' : this.failed || res.statusCode >= 400 ? 'failed' : 'success',\n duration_ms: Math.round(performance.now() - this.started),\n };\n // 日志后端异常不能影响协议响应或产生未处理异常。\n try {\n const level = fields.status === 'failed' ? 'error' : fields.status === 'aborted' ? 'warn' : 'log';\n this.logger[level](JSON.stringify(fields), { ...fields, ...MCP_LOG_ATTRIBUTES });\n } catch { /* 日志基础设施不可用时保留业务行为 */ }\n }\n}\n","import { Inject, Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';\nimport { MCP_LOG_ATTRIBUTES } from '../request-log';\nimport { MCP_MODULE_OPTIONS } from '../constants';\nimport { buildManifest } from '../manifest';\nimport { McpRegistryService } from './mcp-registry.service';\nimport { readMcpSkills } from '../skill';\nimport { collectSourceLocations } from '../source-locations';\nimport type { McpCatalog, McpSources, McpModuleOptions } from '../types';\n\n/**\n * McpManifestService\n *\n * 为平台提供运行时能力目录;工具与资源来自注册表,Skill 正文按请求读取。\n * 启动时只采集源码定位,不读写离线清单。\n */\n@Injectable()\nexport class McpManifestService implements OnApplicationBootstrap {\n private readonly logger = new Logger(McpManifestService.name);\n\n private sources: McpSources = { tools: {}, resources: {}, prompts: {} };\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)}`, MCP_LOG_ATTRIBUTES);\n }\n }\n\n /** 面板查询不读写派生清单;与本次 MCP 请求使用同一份 Skill 文件读取逻辑。 */\n async catalog(): Promise<McpCatalog> {\n const skills = await readMcpSkills();\n const manifest = await buildManifest({\n tools: this.registry.getTools(), resources: this.registry.getResources(), options: this.options, skills,\n });\n const sources: McpSources = { tools: { ...this.sources.tools }, resources: { ...this.sources.resources }, prompts: {} };\n for (const skill of skills) sources.prompts[skill.name] = { path: skill.path };\n return { ...manifest, sources };\n }\n}\n","import { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';\nimport { MCP_ENDPOINT_PATH, MCP_MANIFEST_VERSION } from './constants';\nimport { createMcpServer } from './server-factory';\nimport type { McpCatalog, McpModuleOptions, McpNamedSkill, McpToolDefinition, McpUiResourceDefinition } from './types';\n\nexport interface BuildManifestInput {\n tools: McpToolDefinition[];\n resources: McpUiResourceDefinition[];\n options: McpModuleOptions;\n skills?: McpNamedSkill[];\n}\n\n/**\n * 通过“内存中的 MCP 客户端”读取工具列表生成清单。\n *\n * 这样清单里的 JSON Schema 与真实客户端 `tools/list` 看到的完全一致,避免自行转换 zod 造成偏差。\n */\nexport async function buildManifest(input: BuildManifestInput): Promise<Omit<McpCatalog, 'sources'>> {\n const skills = input.skills ?? [];\n const server = createMcpServer({ tools: input.tools, resources: input.resources, options: input.options, skills });\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 tools = input.tools.length > 0 ? (await client.listTools()).tools : [];\n const resources = (input.resources.length > 0) ? (await client.listResources()).resources : [];\n\n const prompts = skills.length ? (await client.listPrompts()).prompts : [];\n return {\n version: MCP_MANIFEST_VERSION,\n generatedAt: new Date().toISOString(),\n endpoint: MCP_ENDPOINT_PATH,\n tools: tools.sort((a, b) => a.name.localeCompare(b.name)),\n resources: resources.sort((a, b) => a.uri.localeCompare(b.uri)),\n prompts,\n skills,\n };\n } finally {\n await Promise.allSettled([client.close(), server.close()]);\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { ErrorCode, GetPromptRequestSchema, ListPromptsRequestSchema, McpError, 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 McpNamedSkill,\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 skills?: McpNamedSkill[];\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 try {\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 } catch (error) {\n if (!(error instanceof McpToolError)) onError?.(error, location);\n throw error;\n }\n },\n );\n }\n\n const skills = input.skills ?? [];\n const names = new Set<string>();\n for (const skill of skills) {\n if (names.has(skill.name)) throw new Error('MCP Prompt name 重复');\n names.add(skill.name);\n // SKILL.md 的 frontmatter 是定义元数据,消息只包含 Markdown 正文。\n const text = skill.content.replace(/^---\\r?\\n[\\s\\S]*?\\r?\\n---(?:\\r?\\n|$)/, '');\n server.registerPrompt(skill.name, { description: skill.description }, async (extra) => {\n const ctx = createContext ? createContext(extra) : noContext();\n assertUser(ctx, options);\n return { description: skill.description, messages: [{ role: 'user', content: { type: 'text', text } }] };\n });\n }\n\n // 官方 SDK 注册时默认声明 listChanged;无状态 JSON 传输不提供主动通知。\n server.server.registerCapabilities({\n ...(tools.length ? { tools: { listChanged: false } } : {}),\n ...(resources.length ? { resources: { listChanged: false } } : {}),\n prompts: { listChanged: false },\n });\n // 文件可在两次请求之间增删。空列表也必须可发现,避免删除最后一份后变成方法不存在。\n if (!skills.length) {\n server.server.setRequestHandler(ListPromptsRequestSchema, () => ({ prompts: [] }));\n server.server.setRequestHandler(GetPromptRequestSchema, ({ params }) => {\n throw new McpError(ErrorCode.InvalidParams, `Prompt ${params.name} not found`);\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_LOG_ATTRIBUTES } from '../request-log';\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 作用域或未实例化),已跳过`, MCP_LOG_ATTRIBUTES,\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', MCP_LOG_ATTRIBUTES);\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(', ')}`, MCP_LOG_ATTRIBUTES,\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 { parseDocument } from 'yaml';\nimport { MCP_SKILLS_PATH } from './constants';\nimport type { McpNamedSkill } from './types';\n\nconst FILE_LIMIT = 1024 * 1024;\nconst TOTAL_LIMIT = 8 * FILE_LIMIT;\nconst COUNT_LIMIT = 100;\nconst NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/** 检查每个路径分量,拒绝链接;缺失是正常状态,其他错误不伪装成空列表。 */\nasync function checkedPath(root: string, relative: string): Promise<string | null> {\n let file = root;\n for (const part of relative.split('/')) {\n if (!part || part === '.' || part === '..') throw new Error('MCP Skill 必须位于应用工程内');\n file = path.join(file, part);\n try {\n const stat = await fs.lstat(file);\n if (stat.isSymbolicLink()) throw new Error('MCP Skill 必须位于应用工程内,不允许符号链接');\n const resolved = await fs.realpath(file);\n if (resolved !== file) throw new Error('MCP Skill 必须位于应用工程内,不允许路径重定向');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw error;\n }\n }\n return file;\n}\n\nasync function readFile(file: string): Promise<{ content: string; bytes: number }> {\n if (!(await fs.stat(file)).isFile()) throw new Error('MCP Skill 必须为普通文件');\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 if (!stat.isFile() || stat.size > FILE_LIMIT) throw new Error('MCP Skill 必须为不超过 1 MiB 的普通文件');\n const buffer = Buffer.alloc(FILE_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 > FILE_LIMIT) throw new Error('MCP Skill 不能超过 1 MiB');\n return { content: new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, length)), bytes: length };\n } finally { await handle.close(); }\n}\n\nfunction metadata(content: string): { name: string; description: string } {\n const match = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---(?:\\r?\\n|$)/.exec(content);\n if (!match) throw new Error('MCP Skill 缺少完整 YAML frontmatter');\n const doc = parseDocument(match[1], { uniqueKeys: true, schema: 'core' });\n if (doc.errors.length || doc.warnings.length) throw new Error('MCP Skill frontmatter YAML 无效');\n const value: unknown = doc.toJS({ maxAliasCount: 0 });\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('MCP Skill frontmatter 必须为对象');\n const { name, description } = value as Record<string, unknown>;\n if (typeof name !== 'string' || (!NAME.test(name) || name.length > 64) || typeof description !== 'string' || !description.trim() || description.length > 1024) {\n throw new Error('MCP Skill frontmatter 必须含有效 name 和非空 description');\n }\n return { name, description };\n}\n\n/** 同一请求的唯一磁盘快照;只读取 SKILL.md,不遍历附件或执行脚本。 */\nexport async function readMcpSkills(cwd: string = process.cwd()): Promise<McpNamedSkill[]> {\n const root = await fs.realpath(cwd);\n const candidates: Array<{ file: string; relative: string }> = [];\n const directory = await checkedPath(root, MCP_SKILLS_PATH);\n if (directory) {\n if (!(await fs.stat(directory)).isDirectory()) throw new Error('MCP Skills 路径必须为目录');\n for (const item of (await fs.readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {\n if (item.isSymbolicLink()) throw new Error('MCP Skill 必须位于应用工程内,不允许符号链接');\n if (!item.isDirectory()) continue;\n const relative = `${MCP_SKILLS_PATH}/${item.name}/SKILL.md`;\n const file = await checkedPath(root, relative);\n if (!file) continue;\n if (!NAME.test(item.name) || item.name.length > 64) throw new Error('MCP Skill 目录名须为1–64位小写字母、数字及单连字符,不能首尾连字符');\n candidates.push({ file, relative });\n if (candidates.length > COUNT_LIMIT) throw new Error('MCP Skill 最多 100 份');\n }\n }\n const skills: McpNamedSkill[] = [];\n const names = new Set<string>();\n let total = 0;\n for (const candidate of candidates) {\n const { content, bytes } = await readFile(candidate.file);\n total += bytes;\n if (total > TOTAL_LIMIT) throw new Error('MCP Skill 总正文不能超过 8 MiB');\n const meta = metadata(content);\n if (names.has(meta.name)) throw new Error('MCP Skill name 重复');\n names.add(meta.name);\n skills.push({ ...meta, path: candidate.relative, content });\n }\n return skills;\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 prompts: 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 server/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: {}, prompts: {} });\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 (file === path.join(server, 'mcp', 'ui') || file === path.join(server, 'mcp', 'skills')) continue;\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 = `server/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, Post, Req, Res } from '@nestjs/common';\nimport { ApiExcludeController } from '@nestjs/swagger';\nimport type { Request, Response } from 'express';\nimport { MCP_CONTROLLER_PATH } from '../constants';\nimport { McpRequestLog } from '../request-log';\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 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 {\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(@Req() req: Request, @Res() res: Response): void {\n new McpRequestLog(req, res);\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 { MCP_LOG_ATTRIBUTES, McpRequestLog } from '../request-log';\nimport { isJSONRPCResultResponse, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { assertAppRevision, MCP_APP_REVISION_META_KEY, withUiSnapshot } from '../revision';\nimport { McpRevisionService } from './mcp-revision.service';\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 @Inject(McpRevisionService) private readonly revisions: McpRevisionService,\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 log = new McpRequestLog(req, res);\n try {\n await this.handleRequest(req, res, log);\n } catch (error) {\n log.exception(error);\n throw error;\n }\n }\n\n private async handleRequest(req: Request, res: Response, log: McpRequestLog): Promise<void> {\n const snapshot = await this.revisions.capture();\n if (!snapshot || (!this.registry.hasAny() && !snapshot.skills.length)) {\n res.status(404).json({ jsonrpc: '2.0', error: { code: -32000, message: '当前应用未注册任何 MCP 能力' }, id: null });\n return;\n }\n const { skills, revision } = snapshot;\n const server = createMcpServer({\n skills,\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) => log.exception(error, location),\n });\n\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n enableJsonResponse: true,\n });\n\n const send = transport.send.bind(transport);\n transport.send = (message, options) => {\n log.response(message);\n if (!isJSONRPCResultResponse(message)) return send(message, options);\n const meta = { ...message.result._meta };\n // 扩展保留键只由当前应用快照决定,缺少构建标识时不能透出业务提供的值。\n delete meta[MCP_APP_REVISION_META_KEY];\n if (revision !== undefined) meta[MCP_APP_REVISION_META_KEY] = revision;\n return send({ ...message, result: { ...message.result, _meta: meta } }, options);\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)}`, MCP_LOG_ATTRIBUTES);\n });\n });\n\n await server.connect(transport);\n // transport 已校验 HTTP 与 JSON-RPC 格式;在 SDK 分派/执行业务处理前拒绝过期请求。\n const onmessage = transport.onmessage!;\n transport.onmessage = (message, extra) => {\n if ('method' in message && 'id' in message &&\n ['tools/call', 'resources/read', 'prompts/get'].includes(message.method)) {\n try { assertAppRevision(message.params?._meta, revision); } catch (error) {\n if (!(error instanceof McpError)) throw error;\n void transport.send({\n jsonrpc: '2.0', id: message.id,\n error: { code: error.code, message: error.message, data: error.data },\n }, { relatedRequestId: message.id }).catch((error: Error) => transport.onerror?.(error));\n return;\n }\n }\n onmessage(message, extra);\n };\n await withUiSnapshot(snapshot.ui, () => transport.handleRequest(req, res, req.body));\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport { createHash } from 'node:crypto';\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { MCP_UI_DIST_DIR } from './constants';\n\n/** 妙搭扩展:响应中的实际修订,以及请求中期望调用的修订。 */\nexport const MCP_APP_REVISION_META_KEY = 'com.feishu.miaoda/appRevision';\nexport const MCP_APP_REVISION_MISMATCH = 'MCP_APP_REVISION_MISMATCH';\n\nexport function revisionHash(value: unknown): string {\n return createHash('sha256').update(JSON.stringify(value)).digest('hex');\n}\n\nexport function assertAppRevision(meta: unknown, actual: string | undefined): void {\n if (!meta || typeof meta !== 'object' || !Object.prototype.hasOwnProperty.call(meta, MCP_APP_REVISION_META_KEY)) return;\n const expected = (meta as Record<string, unknown>)[MCP_APP_REVISION_META_KEY];\n if (typeof expected !== 'string' || !expected || expected.length > 256) {\n throw new McpError(ErrorCode.InvalidParams, 'appRevision 必须为 1–256 字符的字符串');\n }\n if (actual === undefined) {\n throw new McpError(-32000, '当前运行环境缺少发布版本标识,请检查平台环境或配置 appBuildId', { code: 'MCP_APP_REVISION_UNAVAILABLE' });\n }\n if (expected !== actual) {\n throw new McpError(-32000, '应用已更新,请重新调试;本次操作未执行', {\n code: MCP_APP_REVISION_MISMATCH, expectedRevision: expected, actualRevision: actual,\n });\n }\n}\n\nexport interface UiSnapshot { root: string; files: ReadonlyMap<string, string>; fingerprint: string }\nconst uiContext = new AsyncLocalStorage<UiSnapshot>();\n\n/** 保持资源内容与当前请求的修订标识一致,不能在 handler 中重新读到下一版 HTML。 */\nexport function withUiSnapshot<T>(snapshot: UiSnapshot, callback: () => T): T {\n return uiContext.run(snapshot, callback);\n}\n\nexport async function snapshotUiTemplate(entry: string, cwd: string): Promise<{ html: string } | undefined> {\n const snapshot = uiContext.getStore();\n if (!snapshot || await fs.realpath(cwd) !== snapshot.root) return undefined;\n const html = snapshot.files.get(`${entry}.html`);\n if (html === undefined) throw new Error(`当前 MCP 修订中不存在 UI 产物:${entry}.html`);\n return { html };\n}\n\n/** 只扫描已构建的单文件 UI;未变化的文件复用内容,绝不执行业务资源 handler。 */\nexport class UiSnapshotReader {\n private cache = new Map<string, { signature: string; html: string; hash: string }>();\n private inFlight = new Map<string, Promise<UiSnapshot>>();\n\n async read(cwd: string): Promise<UiSnapshot> {\n const root = await fs.realpath(cwd);\n const existing = this.inFlight.get(root);\n if (existing) return existing;\n const pending = this.readWithRetry(root).finally(() => { this.inFlight.delete(root); });\n this.inFlight.set(root, pending);\n return pending;\n }\n\n private async readWithRetry(root: string): Promise<UiSnapshot> {\n // watch 删除入口可能发生于 readdir/stat/read 之间;最多重试两次完整扫描。\n for (let attempt = 0; ; attempt++) {\n try { return await this.readSnapshot(root); } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || attempt >= 2) throw error;\n }\n }\n }\n\n private async readSnapshot(root: string): Promise<UiSnapshot> {\n const dir = path.join(root, MCP_UI_DIST_DIR);\n let names: string[];\n try { names = await fs.readdir(dir); } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n names = [];\n }\n const files = new Map<string, string>();\n const next = new Map<string, { signature: string; html: string; hash: string }>();\n for (const name of names.filter((name) => /^[A-Za-z0-9_-]+\\.html$/.test(name)).sort()) {\n const file = path.join(dir, name);\n const stat = await fs.lstat(file, { bigint: true });\n if (!stat.isFile()) throw new Error(`MCP UI 产物必须为普通文件:${name}`);\n const signature = `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;\n let cached = this.cache.get(file);\n if (cached?.signature !== signature) {\n // 指纹最终基于实际读出的字节。rename 发生于 stat/read 之间时下一次 stat 会刷新缓存。\n const html = await fs.readFile(file, 'utf8');\n cached = { signature, html, hash: revisionHash(html) };\n }\n next.set(file, cached);\n files.set(name, cached.html);\n }\n this.cache = next;\n return { root, files, fingerprint: revisionHash([...next].map(([file, value]) => [path.basename(file), value.hash])) };\n }\n}\n","import { Inject, Injectable, Logger, type OnApplicationBootstrap } from '@nestjs/common';\nimport { MCP_LOG_ATTRIBUTES } from '../request-log';\nimport { developmentBuildId } from '../development-revision';\nimport { MCP_MODULE_OPTIONS } from '../constants';\nimport { readMcpSkills } from '../skill';\nimport { revisionHash, UiSnapshotReader } from '../revision';\nimport { McpRegistryService } from './mcp-registry.service';\nimport type { McpNamedSkill, McpModuleOptions } from '../types';\n\nexport class McpRevisionState {\n private readonly ui = new UiSnapshotReader();\n private readonly base: Promise<string | undefined>;\n\n constructor(readonly cwd: string, production: boolean, buildId?: string, entrypoint = process.argv[1], captureDevelopmentBuild = true) {\n // 开发态必须在服务初始化时固定已编译代码,不能等首次请求才读取可能已变化的磁盘。\n let base = buildId;\n if (base === undefined && production) {\n const functionId = process.env._FAAS_FUNC_ID;\n const revision = process.env._FAAS_REVISION_NUMBER;\n // veFaaS 已发布 revision 不可变;0/负数不是可用于绑定的发布版本。\n if (functionId && revision && /^[1-9]\\d*$/.test(revision)) {\n base = JSON.stringify(['vefaas', functionId, revision]);\n }\n }\n if (base === undefined && !production && captureDevelopmentBuild) {\n try { base = developmentBuildId(cwd, entrypoint); } catch (error) {\n new Logger(McpRevisionState.name).warn(\n `MCP 版本指纹不可用:${error instanceof Error ? error.message : String(error)}。请检查编译产物或配置 appBuildId。`, MCP_LOG_ATTRIBUTES,\n );\n }\n }\n this.base = Promise.resolve(base);\n }\n\n private async getBase(): Promise<string | undefined> {\n const configured = await this.base;\n if (configured !== undefined) {\n if (!configured.trim() || configured.length > 256) throw new Error('MCP appBuildId 必须为 1–256 字符的字符串');\n return configured;\n }\n return undefined;\n }\n\n async capture(skillsSnapshot?: McpNamedSkill[]) {\n const [base, ui, skills] = await Promise.all([\n this.getBase(), this.ui.read(this.cwd), skillsSnapshot ?? readMcpSkills(this.cwd),\n ]);\n const revision = base === undefined ? undefined : revisionHash([\n base, ui.fingerprint, skills.map(({ name, description, content }) => [name, description, content]),\n ]);\n return { revision, ui, skills };\n }\n}\n\n/** 应用级单例;HTTP 请求创建 McpServer 时不能重新扫描后端编译产物。 */\n@Injectable()\nexport class McpRevisionService implements OnApplicationBootstrap {\n private state?: McpRevisionState;\n\n constructor(\n @Inject(MCP_MODULE_OPTIONS) private readonly options: McpModuleOptions,\n @Inject(McpRegistryService) private readonly registry: McpRegistryService,\n ) {}\n\n async onApplicationBootstrap(): Promise<void> {\n if (this.options.enabled === false) return;\n if (this.registry.hasAny()) {\n this.initialize(true);\n return;\n }\n try {\n if ((await readMcpSkills()).length) this.initialize(true);\n } catch (error) {\n // 文件错误由目录/协议请求返回;不能阻断未使用 MCP 的主应用启动。\n new Logger(McpRevisionService.name).warn(\n `MCP Skill 初始化读取失败:${error instanceof Error ? error.message : String(error)}`, MCP_LOG_ATTRIBUTES,\n );\n }\n }\n\n private initialize(atStartup: boolean): McpRevisionState {\n return this.state ??= new McpRevisionState(\n process.cwd(), process.env.NODE_ENV === 'production', this.options.appBuildId,\n process.argv[1], atStartup,\n );\n }\n\n async capture() {\n if (this.options.enabled === false) return undefined;\n if (this.state) return this.state.capture();\n // 启动后新增 Skill 可被发现,但开发态不能用此时磁盘上的代码冒充已加载版本。\n const skills = await readMcpSkills();\n if (!this.registry.hasAny() && !skills.length) return undefined;\n return this.initialize(false).capture(skills);\n }\n}\n","import { createHash } from 'node:crypto';\nimport { existsSync, lstatSync, readFileSync, readdirSync, realpathSync } from 'node:fs';\nimport path from 'node:path';\n\nconst CODE_FILE = /\\.(?:[cm]?js|json|node)$/;\nconst IGNORED_PATHS = new Set(['dist/client', 'dist/mcp-ui', 'dist/server/mcp/ui', 'dist/mcp/ui', 'dist/server/dist/client']);\n\n/**\n * 固定本轮启动的编译产物快照,不在请求时读取正在被编译器改写的后端文件。\n * 只识别实际 Node 入口所在的 dist;ts-node/自定义输出目录须显式提供 appBuildId。\n */\nexport function developmentBuildId(cwd: string, entrypoint: string | undefined): string | undefined {\n if (!entrypoint) return undefined;\n const root = realpathSync(cwd);\n const entry = path.resolve(cwd, entrypoint);\n // Nest CLI 可启动 `node dist/server/main`(省略 .js)。\n const executable = [entry, `${entry}.js`, `${entry}.cjs`, `${entry}.mjs`]\n .find(file => existsSync(file) && lstatSync(file).isFile());\n if (!executable) return undefined;\n const relative = path.relative(root, realpathSync(executable)).split(path.sep).join('/');\n if (!/^dist\\/(?:server\\/)?main\\.[cm]?js$/.test(relative)) return undefined;\n\n const files: string[] = [];\n function scan(dir: string): void {\n if (!existsSync(path.join(root, dir))) return;\n for (const name of readdirSync(path.join(root, dir)).sort()) {\n const file = path.posix.join(dir, name);\n if (IGNORED_PATHS.has(file) || name === 'node_modules' || name === '.git') continue;\n const stat = lstatSync(path.join(root, file));\n // 不把 UI 源码的偶然编译产物当作后端代码;UI 由单独的运行快照负责。\n if (stat.isDirectory()) scan(file);\n else if (stat.isFile() && CODE_FILE.test(name)) files.push(file);\n else if (stat.isSymbolicLink()) throw new Error(`MCP 开发编译产物不能包含符号链接:${file}`);\n }\n }\n if (relative.startsWith('dist/server/')) {\n scan('dist/server'); scan('dist/shared');\n } else {\n scan('dist');\n }\n // 锁定依赖配置,安装不同版本依赖并重启时也应失效;不依赖目录时间戳。\n for (const file of ['dist/package.json', 'package.json', 'package-lock.json', 'npm-shrinkwrap.json', 'pnpm-lock.yaml', 'yarn.lock']) {\n if (existsSync(path.join(root, file))) files.push(file);\n }\n const hash = createHash('sha256').update(JSON.stringify(['miaoda-mcp-dev-build-v1', relative]));\n for (const file of [...new Set(files)].sort()) {\n const digest = createHash('sha256').update(readFileSync(path.join(root, file))).digest('hex');\n hash.update(JSON.stringify([file, digest]));\n }\n return hash.digest('hex');\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { MCP_UI_DIST_DIR } from './constants';\nimport { snapshotUiTemplate } from './revision';\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 `server/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 snapshot = await snapshotUiTemplate(entry, cwd);\n if (snapshot) return snapshot.html;\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}。请确认 server/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;AAK5B,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;AAI9B,IAAMC,kBAAkB;;;AC1CxB,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;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BsBR;","names":["MCP_ENDPOINT_PATH","MCP_CONTROLLER_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_SKILLS_PATH","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_common","MCP_LOG_ATTRIBUTES","source_type","paas_attributes_module","record","value","Array","isArray","label","slice","undefined","McpRequestLog","logger","Logger","started","performance","now","fields","failed","reported","req","res","operation","body","params","http_method","method","mcp_method","rpc_id","id","tool_name","name","prompt_name","uri","URL","username","password","search","hash","resource_uri","href","once","AsyncResource","bind","complete","writableFinished","response","message","isJSONRPCErrorResponse","error_code","error","code","business_error_code","data","isJSONRPCResultResponse","result","isError","is_error","_meta","exception","location","error_message","Error","stack","aborted","http_status","statusCode","status","duration_ms","Math","round","level","JSON","stringify","import_common","import_types","import_types","import_protocol","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","skills","names","Set","skill","has","add","replace","registerPrompt","messages","role","registerCapabilities","listChanged","prompts","setRequestHandler","ListPromptsRequestSchema","GetPromptRequestSchema","params","McpError","ErrorCode","InvalidParams","buildManifest","input","skills","server","createMcpServer","tools","resources","options","client","Client","name","version","clientTransport","serverTransport","InMemoryTransport","createLinkedPair","Promise","all","connect","length","listTools","listResources","prompts","listPrompts","MCP_MANIFEST_VERSION","generatedAt","Date","toISOString","endpoint","MCP_ENDPOINT_PATH","sort","a","b","localeCompare","uri","allSettled","close","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","MCP_LOG_ATTRIBUTES","target","has","add","push","collectFromClass","mergeAndValidate","debug","log","map","t","join","FILE_LIMIT","TOTAL_LIMIT","COUNT_LIMIT","NAME","checkedPath","root","relative","file","part","split","Error","path","join","stat","fs","lstat","isSymbolicLink","resolved","realpath","error","code","readFile","isFile","handle","open","constants","O_RDONLY","O_NONBLOCK","O_NOFOLLOW","size","buffer","Buffer","alloc","length","bytesRead","read","content","TextDecoder","fatal","decode","subarray","bytes","close","metadata","match","exec","doc","parseDocument","uniqueKeys","schema","errors","warnings","value","toJS","maxAliasCount","Array","isArray","name","description","test","trim","readMcpSkills","cwd","process","candidates","directory","MCP_SKILLS_PATH","isDirectory","item","readdir","withFileTypes","sort","a","b","localeCompare","push","skills","names","Set","total","candidate","meta","has","add","import_node_fs","import_node_path","sdkEntrypoints","Set","ignored","isInside","root","file","relative","path","startsWith","sep","isAbsolute","collectSourceLocations","tools","resources","cwd","process","empty","prompts","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","prompts","registry","options","onApplicationBootstrap","enabled","collectSourceLocations","getTools","getResources","error","warn","Error","message","String","MCP_LOG_ATTRIBUTES","catalog","skills","readMcpSkills","manifest","buildManifest","skill","path","McpManifestController","manifest","registry","get","req","res","log","McpRequestLog","setHeader","isInitialized","status","type","json","title","catalog","error","exception","import_common","import_swagger","import_common","import_types","import_node_async_hooks","import_node_fs","import_node_path","import_types","MCP_APP_REVISION_META_KEY","MCP_APP_REVISION_MISMATCH","revisionHash","value","createHash","update","JSON","stringify","digest","assertAppRevision","meta","actual","Object","prototype","hasOwnProperty","call","expected","length","McpError","ErrorCode","InvalidParams","undefined","code","expectedRevision","actualRevision","uiContext","AsyncLocalStorage","withUiSnapshot","snapshot","callback","run","snapshotUiTemplate","entry","cwd","getStore","fs","realpath","root","html","files","get","Error","UiSnapshotReader","cache","Map","inFlight","read","existing","pending","readWithRetry","finally","delete","set","attempt","readSnapshot","error","dir","path","join","MCP_UI_DIST_DIR","names","readdir","next","name","filter","test","sort","file","stat","lstat","bigint","isFile","signature","dev","ino","size","mtimeNs","ctimeNs","cached","readFile","hash","fingerprint","map","basename","import_common","import_node_crypto","import_node_fs","import_node_path","CODE_FILE","IGNORED_PATHS","Set","developmentBuildId","cwd","entrypoint","undefined","root","realpathSync","entry","path","resolve","executable","find","file","existsSync","lstatSync","isFile","relative","split","sep","join","test","files","scan","dir","name","readdirSync","sort","posix","has","stat","isDirectory","push","isSymbolicLink","Error","startsWith","hash","createHash","update","JSON","stringify","digest","readFileSync","McpRevisionState","ui","UiSnapshotReader","base","cwd","production","buildId","entrypoint","process","argv","captureDevelopmentBuild","undefined","functionId","env","_FAAS_FUNC_ID","revision","_FAAS_REVISION_NUMBER","test","JSON","stringify","developmentBuildId","error","Logger","name","warn","Error","message","String","MCP_LOG_ATTRIBUTES","Promise","resolve","getBase","configured","trim","length","capture","skillsSnapshot","skills","all","read","readMcpSkills","revisionHash","fingerprint","map","description","content","McpRevisionService","state","options","registry","onApplicationBootstrap","enabled","hasAny","initialize","atStartup","NODE_ENV","appBuildId","McpServerService","logger","Logger","name","registry","options","revisions","createContext","req","extra","user","userContext","request","signal","AbortController","requestId","handle","res","log","McpRequestLog","handleRequest","error","exception","snapshot","capture","hasAny","skills","length","status","json","jsonrpc","code","message","id","revision","server","createMcpServer","tools","getTools","resources","getResources","onError","location","transport","StreamableHTTPServerTransport","sessionIdGenerator","undefined","enableJsonResponse","send","bind","response","isJSONRPCResultResponse","meta","result","_meta","MCP_APP_REVISION_META_KEY","on","close","catch","warn","Error","String","MCP_LOG_ATTRIBUTES","connect","onmessage","includes","method","assertAppRevision","params","McpError","data","relatedRequestId","onerror","withUiSnapshot","ui","body","McpController","serverService","handlePost","req","res","handle","headersSent","status","json","jsonrpc","error","code","message","id","handleOthers","McpRequestLog","methodNotAllowed","setHeader","McpModule","forRoot","options","enabled","providers","provide","MCP_MODULE_OPTIONS","useValue","McpRegistryService","McpServerService","McpRevisionService","McpManifestService","module","global","imports","DiscoveryModule","controllers","McpManifestController","McpController","exports","import_node_fs","import_node_path","cache","Map","readMcpUiTemplate","entry","cwd","process","test","Error","snapshot","snapshotUiTemplate","html","file","path","join","MCP_UI_DIST_DIR","useCache","env","NODE_ENV","has","get","fs","readFile","error","reason","message","String","set"]}
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/request-log.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/revision.ts","../src/services/mcp-revision.service.ts","../src/development-revision.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, McpNamedSkill, McpSources, McpSourceLocation } from './types';\n\nexport { MCP_APP_REVISION_META_KEY, MCP_APP_REVISION_MISMATCH } from './revision';\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 * 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/** 平台 manifest 接口响应结构版本 */\nexport const MCP_MANIFEST_VERSION = 3;\n\n/**\n * 工具名合法字符(MCP 规范 SEP-986):1~128 位,字母、数字、下划线、连字符、点。\n */\nexport const MCP_TOOL_NAME_PATTERN = /^[A-Za-z0-9_.-]{1,128}$/;\n\n\n/** 多 Skill 的固定源码目录。 */\nexport const MCP_SKILLS_PATH = 'server/mcp/skills';\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 字符串。界面源码放在 `server/mcp/ui/<entry>/` 下(浏览器代码使用 UI 独立 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 { McpRevisionService } from './services/mcp-revision.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 端点,并通过 `GET /__innerapi__/mcp/manifest` 提供实时能力目录。\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 McpRevisionService,\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, Req, Res } from '@nestjs/common';\nimport { ApiExcludeController } from '@nestjs/swagger';\nimport type { Request, Response } from 'express';\nimport { McpRequestLog } from '../request-log';\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 constructor(\n @Inject(McpManifestService) private readonly manifest: McpManifestService,\n @Inject(McpRegistryService) private readonly registry: McpRegistryService,\n ) {}\n\n @Get()\n async get(@Req() req: Request, @Res() res: Response): Promise<void> {\n const log = new McpRequestLog(req, res, 'manifest');\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 log.exception(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 { AsyncResource } from 'node:async_hooks';\nimport { Logger } from '@nestjs/common';\nimport type { Request, Response } from 'express';\nimport { isJSONRPCErrorResponse, isJSONRPCResultResponse, type JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';\n\n/** 与框架平台日志共用上报链路;source_type 是 Observable 消费的字段。 */\nexport const MCP_LOG_ATTRIBUTES = { source_type: 'platform', paas_attributes_module: 'mcp' } as const;\n\nfunction record(value: unknown): Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown> : {};\n}\n\nfunction label(value: unknown): string | undefined {\n return typeof value === 'string' ? value.slice(0, 256) : undefined;\n}\n\n/** 每个 HTTP 请求独立记录;只摘取诊断字段,不保存请求参数或响应正文。 */\nexport class McpRequestLog {\n private readonly logger = new Logger('McpRequest');\n private readonly started = performance.now();\n private readonly fields: Record<string, unknown>;\n private failed = false;\n private reported = false;\n\n constructor(req: Request, res: Response, operation = 'rpc') {\n const body = operation === 'rpc' ? record(req.body) : {};\n const params = record(body.params);\n this.fields = {\n operation,\n http_method: req.method,\n mcp_method: label(body.method),\n rpc_id: typeof body.id === 'number' ? body.id : label(body.id),\n };\n if (body.method === 'tools/call') this.fields.tool_name = label(params.name);\n if (body.method === 'prompts/get') this.fields.prompt_name = label(params.name);\n // URI 可能包含查询凭证;不记录 query、fragment 或 userinfo。\n if (body.method === 'resources/read' && typeof params.uri === 'string') {\n try {\n const uri = new URL(params.uri);\n uri.username = ''; uri.password = ''; uri.search = ''; uri.hash = '';\n this.fields.resource_uri = label(uri.href);\n } catch { /* 非法 URI 交给 MCP 校验,不输出原始输入 */ }\n }\n // socket close 等事件可能在请求异步上下文之外触发,显式保留 trace / 用户上下文。\n res.once('finish', AsyncResource.bind(() => this.complete(res, false)));\n res.once('close', AsyncResource.bind(() => this.complete(res, !res.writableFinished)));\n }\n\n /** SDK 发出的协议结果;HTTP 200 也可能包含工具失败或 JSON-RPC 错误。 */\n response(message: JSONRPCMessage): void {\n if (isJSONRPCErrorResponse(message)) {\n this.failed = true;\n this.fields.error_code = message.error.code;\n this.fields.business_error_code = label(record(message.error.data).code);\n } else if (isJSONRPCResultResponse(message) && message.result.isError === true) {\n this.failed = true;\n this.fields.is_error = true;\n this.fields.business_error_code = label(record(record(message.result._meta).error).code);\n }\n }\n\n /** 未预期异常保留服务端诊断;不向 MCP 响应增加内部信息。 */\n exception(error: unknown, location?: string): void {\n this.failed = true;\n this.fields.location = location;\n this.fields.error_message = error instanceof Error ? error.message : 'Non-Error exception';\n if (error instanceof Error) this.fields.stack = error.stack;\n }\n\n private complete(res: Response, aborted: boolean): void {\n if (this.reported) return;\n this.reported = true;\n const fields = {\n ...this.fields,\n http_status: res.statusCode,\n status: aborted ? 'aborted' : this.failed || res.statusCode >= 400 ? 'failed' : 'success',\n duration_ms: Math.round(performance.now() - this.started),\n };\n // 日志后端异常不能影响协议响应或产生未处理异常。\n try {\n const level = fields.status === 'failed' ? 'error' : fields.status === 'aborted' ? 'warn' : 'log';\n this.logger[level](JSON.stringify(fields), { ...fields, ...MCP_LOG_ATTRIBUTES });\n } catch { /* 日志基础设施不可用时保留业务行为 */ }\n }\n}\n","import { Inject, Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';\nimport { MCP_LOG_ATTRIBUTES } from '../request-log';\nimport { MCP_MODULE_OPTIONS } from '../constants';\nimport { buildManifest } from '../manifest';\nimport { McpRegistryService } from './mcp-registry.service';\nimport { readMcpSkills } from '../skill';\nimport { collectSourceLocations } from '../source-locations';\nimport type { McpCatalog, McpSources, McpModuleOptions } from '../types';\n\n/**\n * McpManifestService\n *\n * 为平台提供运行时能力目录;工具与资源来自注册表,Skill 正文按请求读取。\n * 启动时只采集源码定位,不读写离线清单。\n */\n@Injectable()\nexport class McpManifestService implements OnApplicationBootstrap {\n private readonly logger = new Logger(McpManifestService.name);\n\n private sources: McpSources = { tools: {}, resources: {}, prompts: {} };\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)}`, MCP_LOG_ATTRIBUTES);\n }\n }\n\n /** 面板查询不读写派生清单;与本次 MCP 请求使用同一份 Skill 文件读取逻辑。 */\n async catalog(): Promise<McpCatalog> {\n const skills = await readMcpSkills();\n const manifest = await buildManifest({\n tools: this.registry.getTools(), resources: this.registry.getResources(), options: this.options, skills,\n });\n const sources: McpSources = { tools: { ...this.sources.tools }, resources: { ...this.sources.resources }, prompts: {} };\n for (const skill of skills) sources.prompts[skill.name] = { path: skill.path };\n return { ...manifest, sources };\n }\n}\n","import { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';\nimport { MCP_ENDPOINT_PATH, MCP_MANIFEST_VERSION } from './constants';\nimport { createMcpServer, resolveServerInfo } from './server-factory';\nimport type { McpCatalog, McpModuleOptions, McpNamedSkill, McpToolDefinition, McpUiResourceDefinition } from './types';\n\nexport interface BuildManifestInput {\n tools: McpToolDefinition[];\n resources: McpUiResourceDefinition[];\n options: McpModuleOptions;\n skills?: McpNamedSkill[];\n}\n\n/**\n * 通过“内存中的 MCP 客户端”读取工具列表生成清单。\n *\n * 这样清单里的 JSON Schema 与真实客户端 `tools/list` 看到的完全一致,避免自行转换 zod 造成偏差。\n */\nexport async function buildManifest(input: BuildManifestInput): Promise<Omit<McpCatalog, 'sources'>> {\n const skills = input.skills ?? [];\n const server = createMcpServer({ tools: input.tools, resources: input.resources, options: input.options, skills });\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 tools = input.tools.length > 0 ? (await client.listTools()).tools : [];\n const resources = (input.resources.length > 0) ? (await client.listResources()).resources : [];\n\n const prompts = skills.length ? (await client.listPrompts()).prompts : [];\n return {\n version: MCP_MANIFEST_VERSION,\n generatedAt: new Date().toISOString(),\n endpoint: MCP_ENDPOINT_PATH,\n serverInfo: { name: resolveServerInfo(input.options).name },\n tools: tools.sort((a, b) => a.name.localeCompare(b.name)),\n resources: resources.sort((a, b) => a.uri.localeCompare(b.uri)),\n prompts,\n skills,\n };\n } finally {\n await Promise.allSettled([client.close(), server.close()]);\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { ErrorCode, GetPromptRequestSchema, ListPromptsRequestSchema, McpError, 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 McpNamedSkill,\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 skills?: McpNamedSkill[];\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 try {\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 } catch (error) {\n if (!(error instanceof McpToolError)) onError?.(error, location);\n throw error;\n }\n },\n );\n }\n\n const skills = input.skills ?? [];\n const names = new Set<string>();\n for (const skill of skills) {\n if (names.has(skill.name)) throw new Error('MCP Prompt name 重复');\n names.add(skill.name);\n // SKILL.md 的 frontmatter 是定义元数据,消息只包含 Markdown 正文。\n const text = skill.content.replace(/^---\\r?\\n[\\s\\S]*?\\r?\\n---(?:\\r?\\n|$)/, '');\n server.registerPrompt(skill.name, { description: skill.description }, async (extra) => {\n const ctx = createContext ? createContext(extra) : noContext();\n assertUser(ctx, options);\n return { description: skill.description, messages: [{ role: 'user', content: { type: 'text', text } }] };\n });\n }\n\n // 官方 SDK 注册时默认声明 listChanged;无状态 JSON 传输不提供主动通知。\n server.server.registerCapabilities({\n ...(tools.length ? { tools: { listChanged: false } } : {}),\n ...(resources.length ? { resources: { listChanged: false } } : {}),\n prompts: { listChanged: false },\n });\n // 文件可在两次请求之间增删。空列表也必须可发现,避免删除最后一份后变成方法不存在。\n if (!skills.length) {\n server.server.setRequestHandler(ListPromptsRequestSchema, () => ({ prompts: [] }));\n server.server.setRequestHandler(GetPromptRequestSchema, ({ params }) => {\n throw new McpError(ErrorCode.InvalidParams, `Prompt ${params.name} not found`);\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_LOG_ATTRIBUTES } from '../request-log';\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 作用域或未实例化),已跳过`, MCP_LOG_ATTRIBUTES,\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', MCP_LOG_ATTRIBUTES);\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(', ')}`, MCP_LOG_ATTRIBUTES,\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 { parseDocument } from 'yaml';\nimport { MCP_SKILLS_PATH } from './constants';\nimport type { McpNamedSkill } from './types';\n\nconst FILE_LIMIT = 1024 * 1024;\nconst TOTAL_LIMIT = 8 * FILE_LIMIT;\nconst COUNT_LIMIT = 100;\nconst NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/** 检查每个路径分量,拒绝链接;缺失是正常状态,其他错误不伪装成空列表。 */\nasync function checkedPath(root: string, relative: string): Promise<string | null> {\n let file = root;\n for (const part of relative.split('/')) {\n if (!part || part === '.' || part === '..') throw new Error('MCP Skill 必须位于应用工程内');\n file = path.join(file, part);\n try {\n const stat = await fs.lstat(file);\n if (stat.isSymbolicLink()) throw new Error('MCP Skill 必须位于应用工程内,不允许符号链接');\n const resolved = await fs.realpath(file);\n if (resolved !== file) throw new Error('MCP Skill 必须位于应用工程内,不允许路径重定向');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw error;\n }\n }\n return file;\n}\n\nasync function readFile(file: string): Promise<{ content: string; bytes: number }> {\n if (!(await fs.stat(file)).isFile()) throw new Error('MCP Skill 必须为普通文件');\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 if (!stat.isFile() || stat.size > FILE_LIMIT) throw new Error('MCP Skill 必须为不超过 1 MiB 的普通文件');\n const buffer = Buffer.alloc(FILE_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 > FILE_LIMIT) throw new Error('MCP Skill 不能超过 1 MiB');\n return { content: new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, length)), bytes: length };\n } finally { await handle.close(); }\n}\n\nfunction metadata(content: string): { name: string; description: string } {\n const match = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---(?:\\r?\\n|$)/.exec(content);\n if (!match) throw new Error('MCP Skill 缺少完整 YAML frontmatter');\n const doc = parseDocument(match[1], { uniqueKeys: true, schema: 'core' });\n if (doc.errors.length || doc.warnings.length) throw new Error('MCP Skill frontmatter YAML 无效');\n const value: unknown = doc.toJS({ maxAliasCount: 0 });\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('MCP Skill frontmatter 必须为对象');\n const { name, description } = value as Record<string, unknown>;\n if (typeof name !== 'string' || (!NAME.test(name) || name.length > 64) || typeof description !== 'string' || !description.trim() || description.length > 1024) {\n throw new Error('MCP Skill frontmatter 必须含有效 name 和非空 description');\n }\n return { name, description };\n}\n\n/** 同一请求的唯一磁盘快照;只读取 SKILL.md,不遍历附件或执行脚本。 */\nexport async function readMcpSkills(cwd: string = process.cwd()): Promise<McpNamedSkill[]> {\n const root = await fs.realpath(cwd);\n const candidates: Array<{ file: string; relative: string }> = [];\n const directory = await checkedPath(root, MCP_SKILLS_PATH);\n if (directory) {\n if (!(await fs.stat(directory)).isDirectory()) throw new Error('MCP Skills 路径必须为目录');\n for (const item of (await fs.readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {\n if (item.isSymbolicLink()) throw new Error('MCP Skill 必须位于应用工程内,不允许符号链接');\n if (!item.isDirectory()) continue;\n const relative = `${MCP_SKILLS_PATH}/${item.name}/SKILL.md`;\n const file = await checkedPath(root, relative);\n if (!file) continue;\n if (!NAME.test(item.name) || item.name.length > 64) throw new Error('MCP Skill 目录名须为1–64位小写字母、数字及单连字符,不能首尾连字符');\n candidates.push({ file, relative });\n if (candidates.length > COUNT_LIMIT) throw new Error('MCP Skill 最多 100 份');\n }\n }\n const skills: McpNamedSkill[] = [];\n const names = new Set<string>();\n let total = 0;\n for (const candidate of candidates) {\n const { content, bytes } = await readFile(candidate.file);\n total += bytes;\n if (total > TOTAL_LIMIT) throw new Error('MCP Skill 总正文不能超过 8 MiB');\n const meta = metadata(content);\n if (names.has(meta.name)) throw new Error('MCP Skill name 重复');\n names.add(meta.name);\n skills.push({ ...meta, path: candidate.relative, content });\n }\n return skills;\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 prompts: 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 server/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: {}, prompts: {} });\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 (file === path.join(server, 'mcp', 'ui') || file === path.join(server, 'mcp', 'skills')) continue;\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 = `server/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, Post, Req, Res } from '@nestjs/common';\nimport { ApiExcludeController } from '@nestjs/swagger';\nimport type { Request, Response } from 'express';\nimport { MCP_CONTROLLER_PATH } from '../constants';\nimport { McpRequestLog } from '../request-log';\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 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 {\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(@Req() req: Request, @Res() res: Response): void {\n new McpRequestLog(req, res);\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 { MCP_LOG_ATTRIBUTES, McpRequestLog } from '../request-log';\nimport { isJSONRPCResultResponse, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { assertAppRevision, MCP_APP_REVISION_META_KEY, withUiSnapshot } from '../revision';\nimport { McpRevisionService } from './mcp-revision.service';\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 @Inject(McpRevisionService) private readonly revisions: McpRevisionService,\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 log = new McpRequestLog(req, res);\n try {\n await this.handleRequest(req, res, log);\n } catch (error) {\n log.exception(error);\n throw error;\n }\n }\n\n private async handleRequest(req: Request, res: Response, log: McpRequestLog): Promise<void> {\n const snapshot = await this.revisions.capture();\n if (!snapshot || (!this.registry.hasAny() && !snapshot.skills.length)) {\n res.status(404).json({ jsonrpc: '2.0', error: { code: -32000, message: '当前应用未注册任何 MCP 能力' }, id: null });\n return;\n }\n const { skills, revision } = snapshot;\n const server = createMcpServer({\n skills,\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) => log.exception(error, location),\n });\n\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n enableJsonResponse: true,\n });\n\n const send = transport.send.bind(transport);\n transport.send = (message, options) => {\n log.response(message);\n if (!isJSONRPCResultResponse(message)) return send(message, options);\n const meta = { ...message.result._meta };\n // 扩展保留键只由当前应用快照决定,缺少构建标识时不能透出业务提供的值。\n delete meta[MCP_APP_REVISION_META_KEY];\n if (revision !== undefined) meta[MCP_APP_REVISION_META_KEY] = revision;\n return send({ ...message, result: { ...message.result, _meta: meta } }, options);\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)}`, MCP_LOG_ATTRIBUTES);\n });\n });\n\n await server.connect(transport);\n // transport 已校验 HTTP 与 JSON-RPC 格式;在 SDK 分派/执行业务处理前拒绝过期请求。\n const onmessage = transport.onmessage!;\n transport.onmessage = (message, extra) => {\n if ('method' in message && 'id' in message &&\n ['tools/call', 'resources/read', 'prompts/get'].includes(message.method)) {\n try { assertAppRevision(message.params?._meta, revision); } catch (error) {\n if (!(error instanceof McpError)) throw error;\n void transport.send({\n jsonrpc: '2.0', id: message.id,\n error: { code: error.code, message: error.message, data: error.data },\n }, { relatedRequestId: message.id }).catch((error: Error) => transport.onerror?.(error));\n return;\n }\n }\n onmessage(message, extra);\n };\n await withUiSnapshot(snapshot.ui, () => transport.handleRequest(req, res, req.body));\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport { createHash } from 'node:crypto';\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { MCP_UI_DIST_DIR } from './constants';\n\n/** 妙搭扩展:响应中的实际修订,以及请求中期望调用的修订。 */\nexport const MCP_APP_REVISION_META_KEY = 'com.feishu.miaoda/appRevision';\nexport const MCP_APP_REVISION_MISMATCH = 'MCP_APP_REVISION_MISMATCH';\n\nexport function revisionHash(value: unknown): string {\n return createHash('sha256').update(JSON.stringify(value)).digest('hex');\n}\n\nexport function assertAppRevision(meta: unknown, actual: string | undefined): void {\n if (!meta || typeof meta !== 'object' || !Object.prototype.hasOwnProperty.call(meta, MCP_APP_REVISION_META_KEY)) return;\n const expected = (meta as Record<string, unknown>)[MCP_APP_REVISION_META_KEY];\n if (typeof expected !== 'string' || !expected || expected.length > 256) {\n throw new McpError(ErrorCode.InvalidParams, 'appRevision 必须为 1–256 字符的字符串');\n }\n if (actual === undefined) {\n throw new McpError(-32000, '当前运行环境缺少发布版本标识,请检查平台环境或配置 appBuildId', { code: 'MCP_APP_REVISION_UNAVAILABLE' });\n }\n if (expected !== actual) {\n throw new McpError(-32000, '应用已更新,请重新调试;本次操作未执行', {\n code: MCP_APP_REVISION_MISMATCH, expectedRevision: expected, actualRevision: actual,\n });\n }\n}\n\nexport interface UiSnapshot { root: string; files: ReadonlyMap<string, string>; fingerprint: string }\nconst uiContext = new AsyncLocalStorage<UiSnapshot>();\n\n/** 保持资源内容与当前请求的修订标识一致,不能在 handler 中重新读到下一版 HTML。 */\nexport function withUiSnapshot<T>(snapshot: UiSnapshot, callback: () => T): T {\n return uiContext.run(snapshot, callback);\n}\n\nexport async function snapshotUiTemplate(entry: string, cwd: string): Promise<{ html: string } | undefined> {\n const snapshot = uiContext.getStore();\n if (!snapshot || await fs.realpath(cwd) !== snapshot.root) return undefined;\n const html = snapshot.files.get(`${entry}.html`);\n if (html === undefined) throw new Error(`当前 MCP 修订中不存在 UI 产物:${entry}.html`);\n return { html };\n}\n\n/** 只扫描已构建的单文件 UI;未变化的文件复用内容,绝不执行业务资源 handler。 */\nexport class UiSnapshotReader {\n private cache = new Map<string, { signature: string; html: string; hash: string }>();\n private inFlight = new Map<string, Promise<UiSnapshot>>();\n\n async read(cwd: string): Promise<UiSnapshot> {\n const root = await fs.realpath(cwd);\n const existing = this.inFlight.get(root);\n if (existing) return existing;\n const pending = this.readWithRetry(root).finally(() => { this.inFlight.delete(root); });\n this.inFlight.set(root, pending);\n return pending;\n }\n\n private async readWithRetry(root: string): Promise<UiSnapshot> {\n // watch 删除入口可能发生于 readdir/stat/read 之间;最多重试两次完整扫描。\n for (let attempt = 0; ; attempt++) {\n try { return await this.readSnapshot(root); } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || attempt >= 2) throw error;\n }\n }\n }\n\n private async readSnapshot(root: string): Promise<UiSnapshot> {\n const dir = path.join(root, MCP_UI_DIST_DIR);\n let names: string[];\n try { names = await fs.readdir(dir); } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n names = [];\n }\n const files = new Map<string, string>();\n const next = new Map<string, { signature: string; html: string; hash: string }>();\n for (const name of names.filter((name) => /^[A-Za-z0-9_-]+\\.html$/.test(name)).sort()) {\n const file = path.join(dir, name);\n const stat = await fs.lstat(file, { bigint: true });\n if (!stat.isFile()) throw new Error(`MCP UI 产物必须为普通文件:${name}`);\n const signature = `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;\n let cached = this.cache.get(file);\n if (cached?.signature !== signature) {\n // 指纹最终基于实际读出的字节。rename 发生于 stat/read 之间时下一次 stat 会刷新缓存。\n const html = await fs.readFile(file, 'utf8');\n cached = { signature, html, hash: revisionHash(html) };\n }\n next.set(file, cached);\n files.set(name, cached.html);\n }\n this.cache = next;\n return { root, files, fingerprint: revisionHash([...next].map(([file, value]) => [path.basename(file), value.hash])) };\n }\n}\n","import { Inject, Injectable, Logger, type OnApplicationBootstrap } from '@nestjs/common';\nimport { MCP_LOG_ATTRIBUTES } from '../request-log';\nimport { developmentBuildId } from '../development-revision';\nimport { MCP_MODULE_OPTIONS } from '../constants';\nimport { readMcpSkills } from '../skill';\nimport { revisionHash, UiSnapshotReader } from '../revision';\nimport { McpRegistryService } from './mcp-registry.service';\nimport type { McpNamedSkill, McpModuleOptions } from '../types';\n\nexport class McpRevisionState {\n private readonly ui = new UiSnapshotReader();\n private readonly base: Promise<string | undefined>;\n\n constructor(readonly cwd: string, production: boolean, buildId?: string, entrypoint = process.argv[1], captureDevelopmentBuild = true) {\n // 开发态必须在服务初始化时固定已编译代码,不能等首次请求才读取可能已变化的磁盘。\n let base = buildId;\n if (base === undefined && production) {\n const functionId = process.env._FAAS_FUNC_ID;\n const revision = process.env._FAAS_REVISION_NUMBER;\n // veFaaS 已发布 revision 不可变;0/负数不是可用于绑定的发布版本。\n if (functionId && revision && /^[1-9]\\d*$/.test(revision)) {\n base = JSON.stringify(['vefaas', functionId, revision]);\n }\n }\n if (base === undefined && !production && captureDevelopmentBuild) {\n try { base = developmentBuildId(cwd, entrypoint); } catch (error) {\n new Logger(McpRevisionState.name).warn(\n `MCP 版本指纹不可用:${error instanceof Error ? error.message : String(error)}。请检查编译产物或配置 appBuildId。`, MCP_LOG_ATTRIBUTES,\n );\n }\n }\n this.base = Promise.resolve(base);\n }\n\n private async getBase(): Promise<string | undefined> {\n const configured = await this.base;\n if (configured !== undefined) {\n if (!configured.trim() || configured.length > 256) throw new Error('MCP appBuildId 必须为 1–256 字符的字符串');\n return configured;\n }\n return undefined;\n }\n\n async capture(skillsSnapshot?: McpNamedSkill[]) {\n const [base, ui, skills] = await Promise.all([\n this.getBase(), this.ui.read(this.cwd), skillsSnapshot ?? readMcpSkills(this.cwd),\n ]);\n const revision = base === undefined ? undefined : revisionHash([\n base, ui.fingerprint, skills.map(({ name, description, content }) => [name, description, content]),\n ]);\n return { revision, ui, skills };\n }\n}\n\n/** 应用级单例;HTTP 请求创建 McpServer 时不能重新扫描后端编译产物。 */\n@Injectable()\nexport class McpRevisionService implements OnApplicationBootstrap {\n private state?: McpRevisionState;\n\n constructor(\n @Inject(MCP_MODULE_OPTIONS) private readonly options: McpModuleOptions,\n @Inject(McpRegistryService) private readonly registry: McpRegistryService,\n ) {}\n\n async onApplicationBootstrap(): Promise<void> {\n if (this.options.enabled === false) return;\n if (this.registry.hasAny()) {\n this.initialize(true);\n return;\n }\n try {\n if ((await readMcpSkills()).length) this.initialize(true);\n } catch (error) {\n // 文件错误由目录/协议请求返回;不能阻断未使用 MCP 的主应用启动。\n new Logger(McpRevisionService.name).warn(\n `MCP Skill 初始化读取失败:${error instanceof Error ? error.message : String(error)}`, MCP_LOG_ATTRIBUTES,\n );\n }\n }\n\n private initialize(atStartup: boolean): McpRevisionState {\n return this.state ??= new McpRevisionState(\n process.cwd(), process.env.NODE_ENV === 'production', this.options.appBuildId,\n process.argv[1], atStartup,\n );\n }\n\n async capture() {\n if (this.options.enabled === false) return undefined;\n if (this.state) return this.state.capture();\n // 启动后新增 Skill 可被发现,但开发态不能用此时磁盘上的代码冒充已加载版本。\n const skills = await readMcpSkills();\n if (!this.registry.hasAny() && !skills.length) return undefined;\n return this.initialize(false).capture(skills);\n }\n}\n","import { createHash } from 'node:crypto';\nimport { existsSync, lstatSync, readFileSync, readdirSync, realpathSync } from 'node:fs';\nimport path from 'node:path';\n\nconst CODE_FILE = /\\.(?:[cm]?js|json|node)$/;\nconst IGNORED_PATHS = new Set(['dist/client', 'dist/mcp-ui', 'dist/server/mcp/ui', 'dist/mcp/ui', 'dist/server/dist/client']);\n\n/**\n * 固定本轮启动的编译产物快照,不在请求时读取正在被编译器改写的后端文件。\n * 只识别实际 Node 入口所在的 dist;ts-node/自定义输出目录须显式提供 appBuildId。\n */\nexport function developmentBuildId(cwd: string, entrypoint: string | undefined): string | undefined {\n if (!entrypoint) return undefined;\n const root = realpathSync(cwd);\n const entry = path.resolve(cwd, entrypoint);\n // Nest CLI 可启动 `node dist/server/main`(省略 .js)。\n const executable = [entry, `${entry}.js`, `${entry}.cjs`, `${entry}.mjs`]\n .find(file => existsSync(file) && lstatSync(file).isFile());\n if (!executable) return undefined;\n const relative = path.relative(root, realpathSync(executable)).split(path.sep).join('/');\n if (!/^dist\\/(?:server\\/)?main\\.[cm]?js$/.test(relative)) return undefined;\n\n const files: string[] = [];\n function scan(dir: string): void {\n if (!existsSync(path.join(root, dir))) return;\n for (const name of readdirSync(path.join(root, dir)).sort()) {\n const file = path.posix.join(dir, name);\n if (IGNORED_PATHS.has(file) || name === 'node_modules' || name === '.git') continue;\n const stat = lstatSync(path.join(root, file));\n // 不把 UI 源码的偶然编译产物当作后端代码;UI 由单独的运行快照负责。\n if (stat.isDirectory()) scan(file);\n else if (stat.isFile() && CODE_FILE.test(name)) files.push(file);\n else if (stat.isSymbolicLink()) throw new Error(`MCP 开发编译产物不能包含符号链接:${file}`);\n }\n }\n if (relative.startsWith('dist/server/')) {\n scan('dist/server'); scan('dist/shared');\n } else {\n scan('dist');\n }\n // 锁定依赖配置,安装不同版本依赖并重启时也应失效;不依赖目录时间戳。\n for (const file of ['dist/package.json', 'package.json', 'package-lock.json', 'npm-shrinkwrap.json', 'pnpm-lock.yaml', 'yarn.lock']) {\n if (existsSync(path.join(root, file))) files.push(file);\n }\n const hash = createHash('sha256').update(JSON.stringify(['miaoda-mcp-dev-build-v1', relative]));\n for (const file of [...new Set(files)].sort()) {\n const digest = createHash('sha256').update(readFileSync(path.join(root, file))).digest('hex');\n hash.update(JSON.stringify([file, digest]));\n }\n return hash.digest('hex');\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { MCP_UI_DIST_DIR } from './constants';\nimport { snapshotUiTemplate } from './revision';\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 `server/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 snapshot = await snapshotUiTemplate(entry, cwd);\n if (snapshot) return snapshot.html;\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}。请确认 server/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;AAK5B,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;AAI9B,IAAMC,kBAAkB;;;AC1CxB,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,S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AUf,OAAM0B,IAAIf,MAAMD,IAAAA;AAC9B,SAAOA;AACT;AAtBsBR;","names":["MCP_ENDPOINT_PATH","MCP_CONTROLLER_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_SKILLS_PATH","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_common","MCP_LOG_ATTRIBUTES","source_type","paas_attributes_module","record","value","Array","isArray","label","slice","undefined","McpRequestLog","logger","Logger","started","performance","now","fields","failed","reported","req","res","operation","body","params","http_method","method","mcp_method","rpc_id","id","tool_name","name","prompt_name","uri","URL","username","password","search","hash","resource_uri","href","once","AsyncResource","bind","complete","writableFinished","response","message","isJSONRPCErrorResponse","error_code","error","code","business_error_code","data","isJSONRPCResultResponse","result","isError","is_error","_meta","exception","location","error_message","Error","stack","aborted","http_status","statusCode","status","duration_ms","Math","round","level","JSON","stringify","import_common","import_types","import_types","import_protocol","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","skills","names","Set","skill","has","add","replace","registerPrompt","messages","role","registerCapabilities","listChanged","prompts","setRequestHandler","ListPromptsRequestSchema","GetPromptRequestSchema","params","McpError","ErrorCode","InvalidParams","buildManifest","input","skills","server","createMcpServer","tools","resources","options","client","Client","name","version","clientTransport","serverTransport","InMemoryTransport","createLinkedPair","Promise","all","connect","length","listTools","listResources","prompts","listPrompts","MCP_MANIFEST_VERSION","generatedAt","Date","toISOString","endpoint","MCP_ENDPOINT_PATH","serverInfo","resolveServerInfo","sort","a","b","localeCompare","uri","allSettled","close","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","MCP_LOG_ATTRIBUTES","target","has","add","push","collectFromClass","mergeAndValidate","debug","log","map","t","join","FILE_LIMIT","TOTAL_LIMIT","COUNT_LIMIT","NAME","checkedPath","root","relative","file","part","split","Error","path","join","stat","fs","lstat","isSymbolicLink","resolved","realpath","error","code","readFile","isFile","handle","open","constants","O_RDONLY","O_NONBLOCK","O_NOFOLLOW","size","buffer","Buffer","alloc","length","bytesRead","read","content","TextDecoder","fatal","decode","subarray","bytes","close","metadata","match","exec","doc","parseDocument","uniqueKeys","schema","errors","warnings","value","toJS","maxAliasCount","Array","isArray","name","description","test","trim","readMcpSkills","cwd","process","candidates","directory","MCP_SKILLS_PATH","isDirectory","item","readdir","withFileTypes","sort","a","b","localeCompare","push","skills","names","Set","total","candidate","meta","has","add","import_node_fs","import_node_path","sdkEntrypoints","Set","ignored","isInside","root","file","relative","path","startsWith","sep","isAbsolute","collectSourceLocations","tools","resources","cwd","process","empty","prompts","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","prompts","registry","options","onApplicationBootstrap","enabled","collectSourceLocations","getTools","getResources","error","warn","Error","message","String","MCP_LOG_ATTRIBUTES","catalog","skills","readMcpSkills","manifest","buildManifest","skill","path","McpManifestController","manifest","registry","get","req","res","log","McpRequestLog","setHeader","isInitialized","status","type","json","title","catalog","error","exception","import_common","import_swagger","import_common","import_types","import_node_async_hooks","import_node_fs","import_node_path","import_types","MCP_APP_REVISION_META_KEY","MCP_APP_REVISION_MISMATCH","revisionHash","value","createHash","update","JSON","stringify","digest","assertAppRevision","meta","actual","Object","prototype","hasOwnProperty","call","expected","length","McpError","ErrorCode","InvalidParams","undefined","code","expectedRevision","actualRevision","uiContext","AsyncLocalStorage","withUiSnapshot","snapshot","callback","run","snapshotUiTemplate","entry","cwd","getStore","fs","realpath","root","html","files","get","Error","UiSnapshotReader","cache","Map","inFlight","read","existing","pending","readWithRetry","finally","delete","set","attempt","readSnapshot","error","dir","path","join","MCP_UI_DIST_DIR","names","readdir","next","name","filter","test","sort","file","stat","lstat","bigint","isFile","signature","dev","ino","size","mtimeNs","ctimeNs","cached","readFile","hash","fingerprint","map","basename","import_common","import_node_crypto","import_node_fs","import_node_path","CODE_FILE","IGNORED_PATHS","Set","developmentBuildId","cwd","entrypoint","undefined","root","realpathSync","entry","path","resolve","executable","find","file","existsSync","lstatSync","isFile","relative","split","sep","join","test","files","scan","dir","name","readdirSync","sort","posix","has","stat","isDirectory","push","isSymbolicLink","Error","startsWith","hash","createHash","update","JSON","stringify","digest","readFileSync","McpRevisionState","ui","UiSnapshotReader","base","cwd","production","buildId","entrypoint","process","argv","captureDevelopmentBuild","undefined","functionId","env","_FAAS_FUNC_ID","revision","_FAAS_REVISION_NUMBER","test","JSON","stringify","developmentBuildId","error","Logger","name","warn","Error","message","String","MCP_LOG_ATTRIBUTES","Promise","resolve","getBase","configured","trim","length","capture","skillsSnapshot","skills","all","read","readMcpSkills","revisionHash","fingerprint","map","description","content","McpRevisionService","state","options","registry","onApplicationBootstrap","enabled","hasAny","initialize","atStartup","NODE_ENV","appBuildId","McpServerService","logger","Logger","name","registry","options","revisions","createContext","req","extra","user","userContext","request","signal","AbortController","requestId","handle","res","log","McpRequestLog","handleRequest","error","exception","snapshot","capture","hasAny","skills","length","status","json","jsonrpc","code","message","id","revision","server","createMcpServer","tools","getTools","resources","getResources","onError","location","transport","StreamableHTTPServerTransport","sessionIdGenerator","undefined","enableJsonResponse","send","bind","response","isJSONRPCResultResponse","meta","result","_meta","MCP_APP_REVISION_META_KEY","on","close","catch","warn","Error","String","MCP_LOG_ATTRIBUTES","connect","onmessage","includes","method","assertAppRevision","params","McpError","data","relatedRequestId","onerror","withUiSnapshot","ui","body","McpController","serverService","handlePost","req","res","handle","headersSent","status","json","jsonrpc","error","code","message","id","handleOthers","McpRequestLog","methodNotAllowed","setHeader","McpModule","forRoot","options","enabled","providers","provide","MCP_MODULE_OPTIONS","useValue","McpRegistryService","McpServerService","McpRevisionService","McpManifestService","module","global","imports","DiscoveryModule","controllers","McpManifestController","McpController","exports","import_node_fs","import_node_path","cache","Map","readMcpUiTemplate","entry","cwd","process","test","Error","snapshot","snapshotUiTemplate","html","file","path","join","MCP_UI_DIST_DIR","useCache","env","NODE_ENV","has","get","fs","readFile","error","reason","message","String","set"]}