@lark-apaas/nestjs-mcp 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1753 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/index.ts
32
+ var src_exports = {};
33
+ __export(src_exports, {
34
+ MCP_CONTROLLER_PATH: () => MCP_CONTROLLER_PATH,
35
+ MCP_DEFAULT_SERVER_NAME: () => MCP_DEFAULT_SERVER_NAME,
36
+ MCP_DEFAULT_SERVER_VERSION: () => MCP_DEFAULT_SERVER_VERSION,
37
+ MCP_ENDPOINT_PATH: () => MCP_ENDPOINT_PATH,
38
+ MCP_MANIFEST_PATH: () => MCP_MANIFEST_PATH,
39
+ MCP_MANIFEST_VERSION: () => MCP_MANIFEST_VERSION,
40
+ MCP_MODULE_OPTIONS: () => MCP_MODULE_OPTIONS,
41
+ MCP_SKILL_PATH: () => MCP_SKILL_PATH,
42
+ MCP_SKILL_URI: () => MCP_SKILL_URI,
43
+ MCP_TOOLS_METADATA_KEY: () => MCP_TOOLS_METADATA_KEY,
44
+ MCP_TOOL_METADATA_KEY: () => MCP_TOOL_METADATA_KEY,
45
+ MCP_TOOL_NAME_PATTERN: () => MCP_TOOL_NAME_PATTERN,
46
+ MCP_UI_DIST_DIR: () => MCP_UI_DIST_DIR,
47
+ MCP_UI_RESOURCE_METADATA_KEY: () => MCP_UI_RESOURCE_METADATA_KEY,
48
+ MCP_UI_RESOURCE_SCHEME: () => MCP_UI_RESOURCE_SCHEME,
49
+ McpModule: () => McpModule,
50
+ McpTool: () => McpTool,
51
+ McpToolError: () => McpToolError,
52
+ McpTools: () => McpTools,
53
+ McpUiResource: () => McpUiResource,
54
+ readMcpUiTemplate: () => readMcpUiTemplate
55
+ });
56
+ module.exports = __toCommonJS(src_exports);
57
+
58
+ // src/constants.ts
59
+ var MCP_ENDPOINT_PATH = "/__innerapi__/mcp";
60
+ var MCP_CONTROLLER_PATH = "__innerapi__/mcp";
61
+ var MCP_MANIFEST_PATH = ".spark/mcp/manifest.json";
62
+ var MCP_UI_DIST_DIR = "dist/mcp-ui";
63
+ var MCP_UI_RESOURCE_SCHEME = "ui://";
64
+ var MCP_TOOLS_METADATA_KEY = "mcp:tools";
65
+ var MCP_TOOL_METADATA_KEY = "mcp:tool";
66
+ var MCP_UI_RESOURCE_METADATA_KEY = "mcp:ui-resource";
67
+ var MCP_MODULE_OPTIONS = /* @__PURE__ */ Symbol("MCP_MODULE_OPTIONS");
68
+ var MCP_DEFAULT_SERVER_NAME = "miaoda-app";
69
+ var MCP_DEFAULT_SERVER_VERSION = "1.0.0";
70
+ var MCP_MANIFEST_VERSION = 1;
71
+ var MCP_TOOL_NAME_PATTERN = /^[A-Za-z0-9_.-]{1,128}$/;
72
+ var MCP_SKILL_PATH = "server/mcp/SKILL.md";
73
+ var MCP_SKILL_URI = "skill://app/SKILL.md";
74
+
75
+ // src/errors.ts
76
+ var McpToolError = class extends Error {
77
+ static {
78
+ __name(this, "McpToolError");
79
+ }
80
+ /** 可选的机器可读错误码,会一并放入返回内容 */
81
+ code;
82
+ /** 附加数据,会以 JSON 形式放入返回内容 */
83
+ data;
84
+ constructor(message, options = {}) {
85
+ super(message);
86
+ this.name = "McpToolError";
87
+ this.code = options.code;
88
+ this.data = options.data;
89
+ }
90
+ };
91
+
92
+ // src/decorators/mcp-tools.decorator.ts
93
+ var import_common = require("@nestjs/common");
94
+ var McpTools = /* @__PURE__ */ __name((options = {}) => {
95
+ return (target) => {
96
+ (0, import_common.Injectable)()(target);
97
+ (0, import_common.SetMetadata)(MCP_TOOLS_METADATA_KEY, options)(target);
98
+ return target;
99
+ };
100
+ }, "McpTools");
101
+
102
+ // src/decorators/mcp-tool.decorator.ts
103
+ var import_common2 = require("@nestjs/common");
104
+ function McpTool(options) {
105
+ return (target, propertyKey, descriptor) => {
106
+ if (typeof propertyKey !== "string") {
107
+ throw new TypeError("@McpTool() \u53EA\u80FD\u7528\u4E8E\u5177\u540D\u65B9\u6CD5");
108
+ }
109
+ if (!options || typeof options.description !== "string" || options.description.trim() === "") {
110
+ throw new TypeError(`@McpTool() \u4E8E ${target.constructor.name}.${propertyKey}\uFF1Adescription \u4E3A\u5FC5\u586B\u9879`);
111
+ }
112
+ (0, import_common2.SetMetadata)(MCP_TOOL_METADATA_KEY, options)(target, propertyKey, descriptor);
113
+ };
114
+ }
115
+ __name(McpTool, "McpTool");
116
+
117
+ // src/decorators/mcp-ui-resource.decorator.ts
118
+ var import_common3 = require("@nestjs/common");
119
+ function McpUiResource(options) {
120
+ return (target, propertyKey, descriptor) => {
121
+ if (typeof propertyKey !== "string") {
122
+ throw new TypeError("@McpUiResource() \u53EA\u80FD\u7528\u4E8E\u5177\u540D\u65B9\u6CD5");
123
+ }
124
+ if (!options?.uri || !options.uri.startsWith(MCP_UI_RESOURCE_SCHEME)) {
125
+ throw new TypeError(`@McpUiResource() \u4E8E ${target.constructor.name}.${propertyKey}\uFF1Auri \u5FC5\u987B\u4EE5 ${MCP_UI_RESOURCE_SCHEME} \u5F00\u5934`);
126
+ }
127
+ (0, import_common3.SetMetadata)(MCP_UI_RESOURCE_METADATA_KEY, options)(target, propertyKey, descriptor);
128
+ };
129
+ }
130
+ __name(McpUiResource, "McpUiResource");
131
+
132
+ // src/mcp.module.ts
133
+ var import_common9 = require("@nestjs/common");
134
+ var import_core2 = require("@nestjs/core");
135
+
136
+ // src/controllers/mcp-manifest.controller.ts
137
+ var import_common6 = require("@nestjs/common");
138
+ var import_swagger = require("@nestjs/swagger");
139
+
140
+ // src/services/mcp-manifest.service.ts
141
+ var import_node_fs3 = require("fs");
142
+ var import_node_path4 = __toESM(require("path"), 1);
143
+ var import_common5 = require("@nestjs/common");
144
+
145
+ // src/manifest.ts
146
+ var import_node_path = __toESM(require("path"), 1);
147
+ var import_node_crypto = require("crypto");
148
+ var import_client = require("@modelcontextprotocol/sdk/client/index.js");
149
+ var import_inMemory = require("@modelcontextprotocol/sdk/inMemory.js");
150
+
151
+ // src/server-factory.ts
152
+ var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
153
+
154
+ // ../../../node_modules/@modelcontextprotocol/ext-apps/dist/src/server/index.js
155
+ var import_protocol = require("@modelcontextprotocol/sdk/shared/protocol.js");
156
+ var import_types = require("@modelcontextprotocol/sdk/types.js");
157
+ var import_protocol2 = require("@modelcontextprotocol/sdk/shared/protocol.js");
158
+ var import_types2 = require("@modelcontextprotocol/sdk/types.js");
159
+ var import_v4 = require("zod/v4");
160
+ var import_types3 = require("@modelcontextprotocol/sdk/types.js");
161
+ var import_v42 = require("zod/v4");
162
+ var r = ((Z) => typeof require < "u" ? require : typeof Proxy < "u" ? new Proxy(Z, {
163
+ get: /* @__PURE__ */ __name(($, J) => (typeof require < "u" ? require : $)[J], "get")
164
+ }) : Z)(function(Z) {
165
+ if (typeof require < "u") return require.apply(this, arguments);
166
+ throw Error('Dynamic require of "' + Z + '" is not supported');
167
+ });
168
+ var v = import_v4.z.union([
169
+ import_v4.z.literal("light"),
170
+ import_v4.z.literal("dark")
171
+ ]).describe("Color theme preference for the host environment.");
172
+ var K = import_v4.z.union([
173
+ import_v4.z.literal("inline"),
174
+ import_v4.z.literal("fullscreen"),
175
+ import_v4.z.literal("pip")
176
+ ]).describe("Display mode for UI presentation.");
177
+ var QQ = import_v4.z.union([
178
+ import_v4.z.literal("--color-background-primary"),
179
+ import_v4.z.literal("--color-background-secondary"),
180
+ import_v4.z.literal("--color-background-tertiary"),
181
+ import_v4.z.literal("--color-background-inverse"),
182
+ import_v4.z.literal("--color-background-ghost"),
183
+ import_v4.z.literal("--color-background-info"),
184
+ import_v4.z.literal("--color-background-danger"),
185
+ import_v4.z.literal("--color-background-success"),
186
+ import_v4.z.literal("--color-background-warning"),
187
+ import_v4.z.literal("--color-background-disabled"),
188
+ import_v4.z.literal("--color-text-primary"),
189
+ import_v4.z.literal("--color-text-secondary"),
190
+ import_v4.z.literal("--color-text-tertiary"),
191
+ import_v4.z.literal("--color-text-inverse"),
192
+ import_v4.z.literal("--color-text-ghost"),
193
+ import_v4.z.literal("--color-text-info"),
194
+ import_v4.z.literal("--color-text-danger"),
195
+ import_v4.z.literal("--color-text-success"),
196
+ import_v4.z.literal("--color-text-warning"),
197
+ import_v4.z.literal("--color-text-disabled"),
198
+ import_v4.z.literal("--color-border-primary"),
199
+ import_v4.z.literal("--color-border-secondary"),
200
+ import_v4.z.literal("--color-border-tertiary"),
201
+ import_v4.z.literal("--color-border-inverse"),
202
+ import_v4.z.literal("--color-border-ghost"),
203
+ import_v4.z.literal("--color-border-info"),
204
+ import_v4.z.literal("--color-border-danger"),
205
+ import_v4.z.literal("--color-border-success"),
206
+ import_v4.z.literal("--color-border-warning"),
207
+ import_v4.z.literal("--color-border-disabled"),
208
+ import_v4.z.literal("--color-ring-primary"),
209
+ import_v4.z.literal("--color-ring-secondary"),
210
+ import_v4.z.literal("--color-ring-inverse"),
211
+ import_v4.z.literal("--color-ring-info"),
212
+ import_v4.z.literal("--color-ring-danger"),
213
+ import_v4.z.literal("--color-ring-success"),
214
+ import_v4.z.literal("--color-ring-warning"),
215
+ import_v4.z.literal("--font-sans"),
216
+ import_v4.z.literal("--font-mono"),
217
+ import_v4.z.literal("--font-weight-normal"),
218
+ import_v4.z.literal("--font-weight-medium"),
219
+ import_v4.z.literal("--font-weight-semibold"),
220
+ import_v4.z.literal("--font-weight-bold"),
221
+ import_v4.z.literal("--font-text-xs-size"),
222
+ import_v4.z.literal("--font-text-sm-size"),
223
+ import_v4.z.literal("--font-text-md-size"),
224
+ import_v4.z.literal("--font-text-lg-size"),
225
+ import_v4.z.literal("--font-heading-xs-size"),
226
+ import_v4.z.literal("--font-heading-sm-size"),
227
+ import_v4.z.literal("--font-heading-md-size"),
228
+ import_v4.z.literal("--font-heading-lg-size"),
229
+ import_v4.z.literal("--font-heading-xl-size"),
230
+ import_v4.z.literal("--font-heading-2xl-size"),
231
+ import_v4.z.literal("--font-heading-3xl-size"),
232
+ import_v4.z.literal("--font-text-xs-line-height"),
233
+ import_v4.z.literal("--font-text-sm-line-height"),
234
+ import_v4.z.literal("--font-text-md-line-height"),
235
+ import_v4.z.literal("--font-text-lg-line-height"),
236
+ import_v4.z.literal("--font-heading-xs-line-height"),
237
+ import_v4.z.literal("--font-heading-sm-line-height"),
238
+ import_v4.z.literal("--font-heading-md-line-height"),
239
+ import_v4.z.literal("--font-heading-lg-line-height"),
240
+ import_v4.z.literal("--font-heading-xl-line-height"),
241
+ import_v4.z.literal("--font-heading-2xl-line-height"),
242
+ import_v4.z.literal("--font-heading-3xl-line-height"),
243
+ import_v4.z.literal("--border-radius-xs"),
244
+ import_v4.z.literal("--border-radius-sm"),
245
+ import_v4.z.literal("--border-radius-md"),
246
+ import_v4.z.literal("--border-radius-lg"),
247
+ import_v4.z.literal("--border-radius-xl"),
248
+ import_v4.z.literal("--border-radius-full"),
249
+ import_v4.z.literal("--border-width-regular"),
250
+ import_v4.z.literal("--shadow-hairline"),
251
+ import_v4.z.literal("--shadow-sm"),
252
+ import_v4.z.literal("--shadow-md"),
253
+ import_v4.z.literal("--shadow-lg")
254
+ ]).describe("CSS variable keys available to MCP apps for theming.");
255
+ var ZQ = import_v4.z.record(QQ.describe(`Style variables for theming MCP apps.
256
+
257
+ Individual style keys are optional - hosts may provide any subset of these values.
258
+ Values are strings containing CSS values (colors, sizes, font stacks, etc.).
259
+
260
+ Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
261
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`), import_v4.z.union([
262
+ import_v4.z.string(),
263
+ import_v4.z.undefined()
264
+ ]).describe(`Style variables for theming MCP apps.
265
+
266
+ Individual style keys are optional - hosts may provide any subset of these values.
267
+ Values are strings containing CSS values (colors, sizes, font stacks, etc.).
268
+
269
+ Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
270
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`)).describe(`Style variables for theming MCP apps.
271
+
272
+ Individual style keys are optional - hosts may provide any subset of these values.
273
+ Values are strings containing CSS values (colors, sizes, font stacks, etc.).
274
+
275
+ Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
276
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`);
277
+ var $Q = import_v4.z.object({
278
+ method: import_v4.z.literal("ui/open-link"),
279
+ params: import_v4.z.object({
280
+ url: import_v4.z.string().describe("URL to open in the host's browser")
281
+ })
282
+ });
283
+ var I = import_v4.z.object({
284
+ isError: import_v4.z.boolean().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")
285
+ }).passthrough();
286
+ var P = import_v4.z.object({
287
+ isError: import_v4.z.boolean().optional().describe("True if the download failed (e.g., user cancelled or host denied).")
288
+ }).passthrough();
289
+ var w = import_v4.z.object({
290
+ isError: import_v4.z.boolean().optional().describe("True if the host rejected or failed to deliver the message.")
291
+ }).passthrough();
292
+ var JQ = import_v4.z.object({
293
+ method: import_v4.z.literal("ui/notifications/sandbox-proxy-ready"),
294
+ params: import_v4.z.object({})
295
+ });
296
+ var Y = import_v4.z.object({
297
+ connectDomains: import_v4.z.array(import_v4.z.string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
298
+
299
+ - Maps to CSP \`connect-src\` directive
300
+ - Empty or omitted \u2192 no network connections (secure default)`),
301
+ resourceDomains: import_v4.z.array(import_v4.z.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 \u2192 no network resources (secure default)"),
302
+ frameDomains: import_v4.z.array(import_v4.z.string()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted \u2192 no nested iframes allowed (`frame-src 'none'`)"),
303
+ baseUriDomains: import_v4.z.array(import_v4.z.string()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted \u2192 only same origin allowed (`base-uri 'self'`)")
304
+ });
305
+ var j = import_v4.z.object({
306
+ camera: import_v4.z.object({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),
307
+ microphone: import_v4.z.object({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),
308
+ geolocation: import_v4.z.object({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),
309
+ clipboardWrite: import_v4.z.object({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")
310
+ });
311
+ var XQ = import_v4.z.object({
312
+ method: import_v4.z.literal("ui/notifications/size-changed"),
313
+ params: import_v4.z.object({
314
+ width: import_v4.z.number().optional().describe("New width in pixels."),
315
+ height: import_v4.z.number().optional().describe("New height in pixels.")
316
+ })
317
+ });
318
+ var H = import_v4.z.object({
319
+ method: import_v4.z.literal("ui/notifications/tool-input"),
320
+ params: import_v4.z.object({
321
+ arguments: import_v4.z.record(import_v4.z.string(), import_v4.z.unknown().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")
322
+ })
323
+ });
324
+ var _ = import_v4.z.object({
325
+ method: import_v4.z.literal("ui/notifications/tool-input-partial"),
326
+ params: import_v4.z.object({
327
+ arguments: import_v4.z.record(import_v4.z.string(), import_v4.z.unknown().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")
328
+ })
329
+ });
330
+ var A = import_v4.z.object({
331
+ method: import_v4.z.literal("ui/notifications/tool-cancelled"),
332
+ params: import_v4.z.object({
333
+ reason: import_v4.z.string().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')
334
+ })
335
+ });
336
+ var f = import_v4.z.object({
337
+ fonts: import_v4.z.string().optional()
338
+ });
339
+ var u = import_v4.z.object({
340
+ variables: ZQ.optional().describe("CSS variables for theming the app."),
341
+ css: f.optional().describe("CSS blocks that apps can inject.")
342
+ });
343
+ var E = import_v4.z.object({
344
+ method: import_v4.z.literal("ui/resource-teardown"),
345
+ params: import_v4.z.object({})
346
+ });
347
+ var VQ = import_v4.z.record(import_v4.z.string(), import_v4.z.unknown());
348
+ var O = import_v4.z.object({
349
+ text: import_v4.z.object({}).optional().describe("Host supports text content blocks."),
350
+ image: import_v4.z.object({}).optional().describe("Host supports image content blocks."),
351
+ audio: import_v4.z.object({}).optional().describe("Host supports audio content blocks."),
352
+ resource: import_v4.z.object({}).optional().describe("Host supports resource content blocks."),
353
+ resourceLink: import_v4.z.object({}).optional().describe("Host supports resource link content blocks."),
354
+ structuredContent: import_v4.z.object({}).optional().describe("Host supports structured content.")
355
+ });
356
+ var DQ = import_v4.z.object({
357
+ method: import_v4.z.literal("ui/notifications/request-teardown"),
358
+ params: import_v4.z.object({}).optional()
359
+ });
360
+ var d = import_v4.z.object({
361
+ experimental: import_v4.z.record(import_v4.z.string(), import_v4.z.record(import_v4.z.string(), import_v4.z.any()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),
362
+ openLinks: import_v4.z.object({}).optional().describe("Host supports opening external URLs."),
363
+ downloadFile: import_v4.z.object({}).optional().describe("Host supports file downloads via ui/download-file."),
364
+ serverTools: import_v4.z.object({
365
+ listChanged: import_v4.z.boolean().optional().describe("Host supports tools/list_changed notifications.")
366
+ }).optional().describe("Host can proxy tool calls to the MCP server."),
367
+ serverResources: import_v4.z.object({
368
+ listChanged: import_v4.z.boolean().optional().describe("Host supports resources/list_changed notifications.")
369
+ }).optional().describe("Host can proxy resource reads to the MCP server."),
370
+ logging: import_v4.z.object({}).optional().describe("Host accepts log messages."),
371
+ sandbox: import_v4.z.object({
372
+ permissions: j.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),
373
+ csp: Y.optional().describe("CSP domains approved by the host.")
374
+ }).optional().describe("Sandbox configuration applied by the host."),
375
+ updateModelContext: O.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),
376
+ message: O.optional().describe("Host supports receiving content messages (ui/message) from the view."),
377
+ sampling: import_v4.z.object({
378
+ tools: import_v4.z.object({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")
379
+ }).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")
380
+ });
381
+ var h = import_v4.z.object({
382
+ experimental: import_v4.z.record(import_v4.z.string(), import_v4.z.record(import_v4.z.string(), import_v4.z.any()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),
383
+ tools: import_v4.z.object({
384
+ listChanged: import_v4.z.boolean().optional().describe("App supports tools/list_changed notifications.")
385
+ }).optional().describe("App exposes MCP-style tools that the host can call."),
386
+ availableDisplayModes: import_v4.z.array(K).optional().describe("Display modes the app supports.")
387
+ });
388
+ var LQ = import_v4.z.object({
389
+ method: import_v4.z.literal("ui/notifications/initialized"),
390
+ params: import_v4.z.object({}).optional()
391
+ });
392
+ var WQ = import_v4.z.object({
393
+ csp: Y.optional().describe("Content Security Policy configuration for UI resources."),
394
+ permissions: j.optional().describe("Sandbox permissions requested by the UI resource."),
395
+ domain: import_v4.z.string().optional().describe(`Dedicated origin for view sandbox.
396
+
397
+ Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.
398
+
399
+ **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:
400
+ - Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`)
401
+ - URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`)
402
+
403
+ If omitted, host uses default sandbox origin (typically per-conversation).`),
404
+ prefersBorder: import_v4.z.boolean().optional().describe(`Visual boundary preference - true if view prefers a visible border.
405
+
406
+ Boolean 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.
407
+
408
+ - \`true\`: request visible border + background
409
+ - \`false\`: request no visible border + background
410
+ - omitted: host decides border`)
411
+ });
412
+ var BQ = import_v4.z.object({
413
+ method: import_v4.z.literal("ui/request-display-mode"),
414
+ params: import_v4.z.object({
415
+ mode: K.describe("The display mode being requested.")
416
+ })
417
+ });
418
+ var R = import_v4.z.object({
419
+ mode: K.describe("The display mode that was actually set. May differ from requested if not supported.")
420
+ }).passthrough();
421
+ var m = import_v4.z.union([
422
+ import_v4.z.literal("model"),
423
+ import_v4.z.literal("app")
424
+ ]).describe("Tool visibility scope - who can access the tool.");
425
+ var GQ = import_v4.z.object({
426
+ resourceUri: import_v4.z.string().optional(),
427
+ visibility: import_v4.z.array(m).optional().describe(`Who can access this tool. Default: ["model", "app"]
428
+ - "model": Tool visible to and callable by the agent
429
+ - "app": Tool callable by the app from this server only`),
430
+ csp: import_v4.z.never().optional(),
431
+ permissions: import_v4.z.never().optional()
432
+ });
433
+ var dQ = import_v4.z.object({
434
+ mimeTypes: import_v4.z.array(import_v4.z.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')
435
+ });
436
+ var KQ = import_v4.z.object({
437
+ method: import_v4.z.literal("ui/download-file"),
438
+ params: import_v4.z.object({
439
+ contents: import_v4.z.array(import_v4.z.union([
440
+ import_types3.EmbeddedResourceSchema,
441
+ import_types3.ResourceLinkSchema
442
+ ])).describe("Resource contents to download \u2014 embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")
443
+ })
444
+ });
445
+ var NQ = import_v4.z.object({
446
+ method: import_v4.z.literal("ui/message"),
447
+ params: import_v4.z.object({
448
+ role: import_v4.z.literal("user").describe('Message role, currently only "user" is supported.'),
449
+ content: import_v4.z.array(import_types3.ContentBlockSchema).describe("Message content blocks (text, image, etc.).")
450
+ })
451
+ });
452
+ var YQ = import_v4.z.object({
453
+ method: import_v4.z.literal("ui/notifications/sandbox-resource-ready"),
454
+ params: import_v4.z.object({
455
+ html: import_v4.z.string().describe("HTML content to load into the inner iframe."),
456
+ sandbox: import_v4.z.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),
457
+ csp: Y.optional().describe("CSP configuration from resource metadata."),
458
+ permissions: j.optional().describe("Sandbox permissions from resource metadata.")
459
+ })
460
+ });
461
+ var U = import_v4.z.object({
462
+ method: import_v4.z.literal("ui/notifications/tool-result"),
463
+ params: import_types3.CallToolResultSchema.describe("Standard MCP tool execution result.")
464
+ });
465
+ var T = import_v4.z.object({
466
+ toolInfo: import_v4.z.object({
467
+ id: import_types3.RequestIdSchema.optional().describe("JSON-RPC id of the tools/call request."),
468
+ tool: import_types3.ToolSchema.describe("Tool definition including name, inputSchema, etc.")
469
+ }).optional().describe("Metadata of the tool call that instantiated this App."),
470
+ theme: v.optional().describe("Current color theme preference."),
471
+ styles: u.optional().describe("Style configuration for theming the app."),
472
+ displayMode: K.optional().describe("How the UI is currently displayed."),
473
+ availableDisplayModes: import_v4.z.array(K).optional().describe("Display modes the host supports."),
474
+ containerDimensions: import_v4.z.union([
475
+ import_v4.z.object({
476
+ height: import_v4.z.number().describe("Fixed container height in pixels.")
477
+ }),
478
+ import_v4.z.object({
479
+ maxHeight: import_v4.z.union([
480
+ import_v4.z.number(),
481
+ import_v4.z.undefined()
482
+ ]).optional().describe("Maximum container height in pixels.")
483
+ })
484
+ ]).and(import_v4.z.union([
485
+ import_v4.z.object({
486
+ width: import_v4.z.number().describe("Fixed container width in pixels.")
487
+ }),
488
+ import_v4.z.object({
489
+ maxWidth: import_v4.z.union([
490
+ import_v4.z.number(),
491
+ import_v4.z.undefined()
492
+ ]).optional().describe("Maximum container width in pixels.")
493
+ })
494
+ ])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
495
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),
496
+ locale: import_v4.z.string().optional().describe("User's language and region preference in BCP 47 format."),
497
+ timeZone: import_v4.z.string().optional().describe("User's timezone in IANA format."),
498
+ userAgent: import_v4.z.string().optional().describe("Host application identifier."),
499
+ platform: import_v4.z.union([
500
+ import_v4.z.literal("web"),
501
+ import_v4.z.literal("desktop"),
502
+ import_v4.z.literal("mobile")
503
+ ]).optional().describe("Platform type for responsive design decisions."),
504
+ deviceCapabilities: import_v4.z.object({
505
+ touch: import_v4.z.boolean().optional().describe("Whether the device supports touch input."),
506
+ hover: import_v4.z.boolean().optional().describe("Whether the device supports hover interactions.")
507
+ }).optional().describe("Device input capabilities."),
508
+ safeAreaInsets: import_v4.z.object({
509
+ top: import_v4.z.number().describe("Top safe area inset in pixels."),
510
+ right: import_v4.z.number().describe("Right safe area inset in pixels."),
511
+ bottom: import_v4.z.number().describe("Bottom safe area inset in pixels."),
512
+ left: import_v4.z.number().describe("Left safe area inset in pixels.")
513
+ }).optional().describe("Mobile safe area boundaries in pixels.")
514
+ }).passthrough();
515
+ var k = import_v4.z.object({
516
+ method: import_v4.z.literal("ui/notifications/host-context-changed"),
517
+ params: T.describe("Partial context update containing only changed fields.")
518
+ });
519
+ var jQ = import_v4.z.object({
520
+ method: import_v4.z.literal("ui/update-model-context"),
521
+ params: import_v4.z.object({
522
+ content: import_v4.z.array(import_types3.ContentBlockSchema).optional().describe("Context content blocks (text, image, etc.)."),
523
+ structuredContent: import_v4.z.record(import_v4.z.string(), import_v4.z.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")
524
+ })
525
+ });
526
+ var FQ = import_v4.z.object({
527
+ method: import_v4.z.literal("ui/initialize"),
528
+ params: import_v4.z.object({
529
+ appInfo: import_types3.ImplementationSchema.describe("App identification (name and version)."),
530
+ appCapabilities: h.describe("Features and capabilities this app provides."),
531
+ protocolVersion: import_v4.z.string().describe("Protocol version this app supports.")
532
+ })
533
+ });
534
+ var M = import_v4.z.object({
535
+ protocolVersion: import_v4.z.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),
536
+ hostInfo: import_types3.ImplementationSchema.describe("Host application identification and version."),
537
+ hostCapabilities: d.describe("Features and capabilities provided by the host."),
538
+ hostContext: T.describe("Rich context about the host environment.")
539
+ }).passthrough();
540
+ var C = "ui/resourceUri";
541
+ var p = "text/html;profile=mcp-app";
542
+ function K3(Z, $, J, X) {
543
+ let V = J._meta, D = V.ui, L = V[C], W = V;
544
+ if (D?.resourceUri && !L) W = {
545
+ ...V,
546
+ [C]: D.resourceUri
547
+ };
548
+ else if (L && !D?.resourceUri) W = {
549
+ ...V,
550
+ ui: {
551
+ ...D,
552
+ resourceUri: L
553
+ }
554
+ };
555
+ return Z.registerTool($, {
556
+ ...J,
557
+ _meta: W
558
+ }, X);
559
+ }
560
+ __name(K3, "K3");
561
+ function N3(Z, $, J, X, V) {
562
+ return Z.registerResource($, J, {
563
+ mimeType: p,
564
+ ...X
565
+ }, V);
566
+ }
567
+ __name(N3, "N3");
568
+
569
+ // src/server-factory.ts
570
+ function resolveServerInfo(options) {
571
+ return {
572
+ name: options.serverName ?? process.env.SUDA_APP_ID ?? MCP_DEFAULT_SERVER_NAME,
573
+ version: options.serverVersion ?? MCP_DEFAULT_SERVER_VERSION
574
+ };
575
+ }
576
+ __name(resolveServerInfo, "resolveServerInfo");
577
+ function normalizeSchema(schema) {
578
+ return schema ?? {};
579
+ }
580
+ __name(normalizeSchema, "normalizeSchema");
581
+ function buildToolMeta(def) {
582
+ const { ui, meta } = def.options;
583
+ if (!ui && !meta) return void 0;
584
+ const merged = {
585
+ ...meta ?? {}
586
+ };
587
+ if (ui) {
588
+ merged.ui = {
589
+ ...merged.ui ?? {},
590
+ resourceUri: ui.resourceUri,
591
+ ...ui.visibility ? {
592
+ visibility: ui.visibility
593
+ } : {}
594
+ };
595
+ }
596
+ return merged;
597
+ }
598
+ __name(buildToolMeta, "buildToolMeta");
599
+ var MISSING_USER_MESSAGE = "\u8C03\u7528\u8005\u8EAB\u4EFD\u7F3A\u5931\uFF1A\u8BF7\u6C42\u672A\u643A\u5E26\u7528\u6237\u4FE1\u606F\uFF08x-larkgw-suda-webuser\uFF09\u3002\u8BF7\u901A\u8FC7 MCP Gateway \u6216\u5F00\u53D1\u670D\u52A1\u5165\u53E3\u8BBF\u95EE\uFF0C\u6216\u5728\u6A21\u5757\u914D\u7F6E\u4E2D\u8BBE\u7F6E requireUser: false\u3002";
600
+ function assertUser(ctx, options) {
601
+ if (options.requireUser === false) return;
602
+ if (!ctx.user?.userId) {
603
+ throw new McpToolError(MISSING_USER_MESSAGE, {
604
+ code: "MCP_USER_REQUIRED"
605
+ });
606
+ }
607
+ }
608
+ __name(assertUser, "assertUser");
609
+ function toErrorResult(error, location, onError) {
610
+ if (error instanceof McpToolError) {
611
+ const payload = {
612
+ message: error.message
613
+ };
614
+ if (error.code !== void 0) payload.code = error.code;
615
+ if (error.data !== void 0) payload.data = error.data;
616
+ return {
617
+ isError: true,
618
+ content: [
619
+ {
620
+ type: "text",
621
+ text: error.code ? `[${error.code}] ${error.message}` : error.message
622
+ }
623
+ ],
624
+ structuredContent: void 0,
625
+ _meta: {
626
+ error: payload
627
+ }
628
+ };
629
+ }
630
+ onError?.(error, location);
631
+ return {
632
+ isError: true,
633
+ content: [
634
+ {
635
+ type: "text",
636
+ text: `\u5DE5\u5177\u6267\u884C\u5931\u8D25\uFF08${location}\uFF09\uFF0C\u8BF7\u67E5\u770B\u5E94\u7528\u65E5\u5FD7`
637
+ }
638
+ ]
639
+ };
640
+ }
641
+ __name(toErrorResult, "toErrorResult");
642
+ function createMcpServer(input) {
643
+ const { tools, resources, options, createContext, onError } = input;
644
+ const server = new import_mcp.McpServer(resolveServerInfo(options), {
645
+ instructions: options.instructions
646
+ });
647
+ const noContext = /* @__PURE__ */ __name(() => {
648
+ throw new Error("\u5F53\u524D McpServer \u5B9E\u4F8B\u672A\u7ED1\u5B9A\u8BF7\u6C42\u4E0A\u4E0B\u6587\uFF0C\u4E0D\u80FD\u6267\u884C\u5DE5\u5177");
649
+ }, "noContext");
650
+ for (const def of tools) {
651
+ const location = `${def.className}.${def.methodName}`;
652
+ const config = {
653
+ title: def.options.title,
654
+ description: def.options.description,
655
+ inputSchema: normalizeSchema(def.options.inputSchema),
656
+ outputSchema: def.options.outputSchema,
657
+ annotations: def.options.annotations,
658
+ _meta: buildToolMeta(def)
659
+ };
660
+ const callback = /* @__PURE__ */ __name(async (args, extra) => {
661
+ try {
662
+ const ctx = createContext ? createContext(extra) : noContext();
663
+ assertUser(ctx, options);
664
+ if (!def.handler) {
665
+ throw new Error(`\u5DE5\u5177\u300C${def.name}\u300D\u672A\u7ED1\u5B9A\u5B9E\u4F8B\uFF08${location}\uFF09`);
666
+ }
667
+ const result = await def.handler(args ?? {}, ctx);
668
+ if (def.options.outputSchema && result && !result.content) {
669
+ return {
670
+ ...result,
671
+ content: [
672
+ {
673
+ type: "text",
674
+ text: JSON.stringify(result.structuredContent ?? null)
675
+ }
676
+ ]
677
+ };
678
+ }
679
+ return result;
680
+ } catch (error) {
681
+ return toErrorResult(error, location, onError);
682
+ }
683
+ }, "callback");
684
+ if (def.options.ui) {
685
+ K3(server, def.name, config, callback);
686
+ } else {
687
+ server.registerTool(def.name, config, callback);
688
+ }
689
+ }
690
+ for (const def of resources) {
691
+ const location = `${def.className}.${def.methodName}`;
692
+ const { uri, title, description, csp, permissions, meta } = def.options;
693
+ const uiMeta = {
694
+ ...meta ?? {}
695
+ };
696
+ if (csp) uiMeta.csp = csp;
697
+ if (permissions) uiMeta.permissions = permissions;
698
+ N3(server, def.name, uri, {
699
+ title,
700
+ description,
701
+ mimeType: p,
702
+ _meta: Object.keys(uiMeta).length > 0 ? {
703
+ ui: uiMeta
704
+ } : void 0
705
+ }, async (resourceUri, extra) => {
706
+ const ctx = createContext ? createContext(extra) : noContext();
707
+ assertUser(ctx, options);
708
+ if (!def.handler) {
709
+ throw new Error(`\u8D44\u6E90\u300C${uri}\u300D\u672A\u7ED1\u5B9A\u5B9E\u4F8B\uFF08${location}\uFF09`);
710
+ }
711
+ const html = await def.handler(ctx);
712
+ return {
713
+ contents: [
714
+ {
715
+ uri: resourceUri.href,
716
+ mimeType: p,
717
+ text: html
718
+ }
719
+ ]
720
+ };
721
+ });
722
+ }
723
+ if (input.skill) {
724
+ const skill = input.skill;
725
+ server.registerResource("app-skill", skill.uri, {
726
+ title: "\u5E94\u7528\u4F7F\u7528\u8BF4\u660E",
727
+ description: "\u5E94\u7528 MCP \u7684\u8C03\u7528\u65F6\u673A\u3001\u5DE5\u5177\u9009\u62E9\u3001\u8C03\u7528\u987A\u5E8F\u3001\u7EA6\u675F\u4E0E\u5931\u8D25\u5904\u7406",
728
+ mimeType: "text/markdown"
729
+ }, async (uri, extra) => {
730
+ const ctx = createContext ? createContext(extra) : noContext();
731
+ assertUser(ctx, options);
732
+ return {
733
+ contents: [
734
+ {
735
+ uri: uri.href,
736
+ mimeType: "text/markdown",
737
+ text: skill.content
738
+ }
739
+ ]
740
+ };
741
+ });
742
+ }
743
+ return server;
744
+ }
745
+ __name(createMcpServer, "createMcpServer");
746
+
747
+ // src/manifest.ts
748
+ async function buildManifest(input) {
749
+ const server = createMcpServer({
750
+ tools: input.tools,
751
+ resources: input.resources,
752
+ options: input.options,
753
+ skill: input.skill
754
+ });
755
+ const client = new import_client.Client({
756
+ name: "miaoda-mcp-manifest",
757
+ version: "1.0.0"
758
+ });
759
+ const [clientTransport, serverTransport] = import_inMemory.InMemoryTransport.createLinkedPair();
760
+ try {
761
+ await Promise.all([
762
+ server.connect(serverTransport),
763
+ client.connect(clientTransport)
764
+ ]);
765
+ const toolSource = new Map(input.tools.map((t2) => [
766
+ t2.name,
767
+ {
768
+ className: t2.className,
769
+ methodName: t2.methodName
770
+ }
771
+ ]));
772
+ const resourceSource = new Map(input.resources.map((r2) => [
773
+ r2.options.uri,
774
+ {
775
+ className: r2.className,
776
+ methodName: r2.methodName
777
+ }
778
+ ]));
779
+ const tools = input.tools.length > 0 ? (await client.listTools()).tools : [];
780
+ const resources = input.resources.length > 0 || input.skill ? (await client.listResources()).resources : [];
781
+ const manifest = {
782
+ version: MCP_MANIFEST_VERSION,
783
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
784
+ endpoint: MCP_ENDPOINT_PATH,
785
+ server: resolveServerInfo(input.options),
786
+ skill: input.skill ? {
787
+ uri: input.skill.uri,
788
+ path: input.skill.path
789
+ } : null,
790
+ tools: tools.map((tool) => ({
791
+ ...tool,
792
+ source: toolSource.get(tool.name) ?? {
793
+ className: "",
794
+ methodName: ""
795
+ }
796
+ })).sort((a2, b) => a2.name.localeCompare(b.name)),
797
+ resources: resources.map((resource) => ({
798
+ ...resource,
799
+ source: resourceSource.get(resource.uri)
800
+ })).sort((a2, b) => a2.uri.localeCompare(b.uri))
801
+ };
802
+ return manifest;
803
+ } finally {
804
+ await Promise.allSettled([
805
+ client.close(),
806
+ server.close()
807
+ ]);
808
+ }
809
+ }
810
+ __name(buildManifest, "buildManifest");
811
+ function serializeManifest(manifest) {
812
+ return `${JSON.stringify(manifest, null, 2)}
813
+ `;
814
+ }
815
+ __name(serializeManifest, "serializeManifest");
816
+ function stripVolatile(json) {
817
+ return json.replace(/"generatedAt": "[^"]*"/, '"generatedAt": ""');
818
+ }
819
+ __name(stripVolatile, "stripVolatile");
820
+ async function writeManifest(manifest, { cwd, relativePath = MCP_MANIFEST_PATH, fs: fs5 }) {
821
+ const file = import_node_path.default.resolve(cwd, relativePath);
822
+ const next = serializeManifest(manifest);
823
+ let previous;
824
+ try {
825
+ previous = await fs5.readFile(file, "utf8");
826
+ } catch {
827
+ previous = void 0;
828
+ }
829
+ if (previous !== void 0 && stripVolatile(previous) === stripVolatile(next)) {
830
+ return {
831
+ changed: false,
832
+ file,
833
+ manifest
834
+ };
835
+ }
836
+ await fs5.mkdir(import_node_path.default.dirname(file), {
837
+ recursive: true
838
+ });
839
+ const temporary = `${file}.${(0, import_node_crypto.randomUUID)()}.tmp`;
840
+ try {
841
+ await fs5.writeFile(temporary, next, "utf8");
842
+ await fs5.rename(temporary, file);
843
+ } finally {
844
+ await fs5.rm(temporary, {
845
+ force: true
846
+ });
847
+ }
848
+ return {
849
+ changed: true,
850
+ file,
851
+ manifest
852
+ };
853
+ }
854
+ __name(writeManifest, "writeManifest");
855
+
856
+ // src/services/mcp-registry.service.ts
857
+ var import_common4 = require("@nestjs/common");
858
+ var import_core = require("@nestjs/core");
859
+
860
+ // src/metadata.ts
861
+ var import_reflect_metadata = require("reflect-metadata");
862
+ function isMcpToolsClass(target) {
863
+ return typeof target === "function" && Reflect.getMetadata(MCP_TOOLS_METADATA_KEY, target) !== void 0;
864
+ }
865
+ __name(isMcpToolsClass, "isMcpToolsClass");
866
+ function getAllMethodNames(prototype) {
867
+ const names = /* @__PURE__ */ new Set();
868
+ let current = prototype;
869
+ while (current && current !== Object.prototype) {
870
+ for (const name of Object.getOwnPropertyNames(current)) {
871
+ if (name === "constructor") continue;
872
+ const descriptor = Object.getOwnPropertyDescriptor(current, name);
873
+ if (descriptor && typeof descriptor.value === "function") {
874
+ names.add(name);
875
+ }
876
+ }
877
+ current = Object.getPrototypeOf(current);
878
+ }
879
+ return [
880
+ ...names
881
+ ];
882
+ }
883
+ __name(getAllMethodNames, "getAllMethodNames");
884
+ function collectFromClass(target, instance) {
885
+ const classOptions = Reflect.getMetadata(MCP_TOOLS_METADATA_KEY, target) ?? {};
886
+ const prototype = target.prototype;
887
+ const tools = [];
888
+ const resources = [];
889
+ for (const methodName of getAllMethodNames(prototype)) {
890
+ const method = prototype[methodName];
891
+ const toolOptions = Reflect.getMetadata(MCP_TOOL_METADATA_KEY, method);
892
+ const resourceOptions = Reflect.getMetadata(MCP_UI_RESOURCE_METADATA_KEY, method);
893
+ if (toolOptions && resourceOptions) {
894
+ throw new Error(`${target.name}.${methodName} \u4E0D\u80FD\u540C\u65F6\u6807\u8BB0 @McpTool() \u4E0E @McpUiResource()`);
895
+ }
896
+ if (toolOptions) {
897
+ const name = `${classOptions.prefix ?? ""}${toolOptions.name ?? methodName}`;
898
+ tools.push({
899
+ name,
900
+ options: toolOptions,
901
+ className: target.name,
902
+ methodName,
903
+ handler: instance ? method.bind(instance) : void 0
904
+ });
905
+ } else if (resourceOptions) {
906
+ resources.push({
907
+ name: resourceOptions.name ?? methodName,
908
+ options: resourceOptions,
909
+ className: target.name,
910
+ methodName,
911
+ handler: instance ? method.bind(instance) : void 0
912
+ });
913
+ }
914
+ }
915
+ return {
916
+ tools,
917
+ resources
918
+ };
919
+ }
920
+ __name(collectFromClass, "collectFromClass");
921
+ function mergeAndValidate(parts) {
922
+ const tools = [];
923
+ const resources = [];
924
+ const problems = [];
925
+ const toolNames = /* @__PURE__ */ new Map();
926
+ const resourceUris = /* @__PURE__ */ new Map();
927
+ for (const part of parts) {
928
+ for (const tool of part.tools) {
929
+ const location = `${tool.className}.${tool.methodName}`;
930
+ if (!MCP_TOOL_NAME_PATTERN.test(tool.name)) {
931
+ problems.push(`\u5DE5\u5177\u540D\u300C${tool.name}\u300D\u4E0D\u5408\u6CD5\uFF08${location}\uFF09\uFF0C\u9700\u5339\u914D ${MCP_TOOL_NAME_PATTERN}`);
932
+ }
933
+ const existing = toolNames.get(tool.name);
934
+ if (existing) {
935
+ problems.push(`\u5DE5\u5177\u540D\u300C${tool.name}\u300D\u91CD\u590D\uFF1A${existing} \u4E0E ${location}`);
936
+ } else {
937
+ toolNames.set(tool.name, location);
938
+ }
939
+ tools.push(tool);
940
+ }
941
+ for (const resource of part.resources) {
942
+ const location = `${resource.className}.${resource.methodName}`;
943
+ const uri = resource.options.uri;
944
+ if (!uri.startsWith(MCP_UI_RESOURCE_SCHEME)) {
945
+ problems.push(`\u8D44\u6E90 URI\u300C${uri}\u300D\u5FC5\u987B\u4EE5 ${MCP_UI_RESOURCE_SCHEME} \u5F00\u5934\uFF08${location}\uFF09`);
946
+ }
947
+ const existing = resourceUris.get(uri);
948
+ if (existing) {
949
+ problems.push(`\u8D44\u6E90 URI\u300C${uri}\u300D\u91CD\u590D\uFF1A${existing} \u4E0E ${location}`);
950
+ } else {
951
+ resourceUris.set(uri, location);
952
+ }
953
+ resources.push(resource);
954
+ }
955
+ }
956
+ for (const tool of tools) {
957
+ const resourceUri = tool.options.ui?.resourceUri;
958
+ if (resourceUri && !resourceUris.has(resourceUri)) {
959
+ problems.push(`\u5DE5\u5177\u300C${tool.name}\u300D\u5F15\u7528\u7684 ui.resourceUri\u300C${resourceUri}\u300D\u672A\u627E\u5230\u5BF9\u5E94\u7684 @McpUiResource()\uFF08${tool.className}.${tool.methodName}\uFF09`);
960
+ }
961
+ }
962
+ if (problems.length > 0) {
963
+ throw new Error(`MCP \u5B9A\u4E49\u6821\u9A8C\u5931\u8D25\uFF1A
964
+ - ${problems.join("\n- ")}`);
965
+ }
966
+ return {
967
+ tools,
968
+ resources
969
+ };
970
+ }
971
+ __name(mergeAndValidate, "mergeAndValidate");
972
+
973
+ // src/services/mcp-registry.service.ts
974
+ function _ts_decorate(decorators, target, key, desc) {
975
+ var c = arguments.length, r2 = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
976
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r2 = Reflect.decorate(decorators, target, key, desc);
977
+ else for (var i2 = decorators.length - 1; i2 >= 0; i2--) if (d2 = decorators[i2]) r2 = (c < 3 ? d2(r2) : c > 3 ? d2(target, key, r2) : d2(target, key)) || r2;
978
+ return c > 3 && r2 && Object.defineProperty(target, key, r2), r2;
979
+ }
980
+ __name(_ts_decorate, "_ts_decorate");
981
+ function _ts_metadata(k2, v2) {
982
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k2, v2);
983
+ }
984
+ __name(_ts_metadata, "_ts_metadata");
985
+ function _ts_param(paramIndex, decorator) {
986
+ return function(target, key) {
987
+ decorator(target, key, paramIndex);
988
+ };
989
+ }
990
+ __name(_ts_param, "_ts_param");
991
+ var McpRegistryService = class _McpRegistryService {
992
+ static {
993
+ __name(this, "McpRegistryService");
994
+ }
995
+ discoveryService;
996
+ options;
997
+ logger = new import_common4.Logger(_McpRegistryService.name);
998
+ definitions = {
999
+ tools: [],
1000
+ resources: []
1001
+ };
1002
+ initialized = false;
1003
+ constructor(discoveryService, options) {
1004
+ this.discoveryService = discoveryService;
1005
+ this.options = options;
1006
+ }
1007
+ onModuleInit() {
1008
+ if (this.options.enabled === false) {
1009
+ this.initialized = true;
1010
+ return;
1011
+ }
1012
+ this.discover();
1013
+ }
1014
+ /** 全部工具定义(已绑定实例) */
1015
+ getTools() {
1016
+ return this.definitions.tools;
1017
+ }
1018
+ /** 全部 MCP Apps 资源定义(已绑定实例) */
1019
+ getResources() {
1020
+ return this.definitions.resources;
1021
+ }
1022
+ /** 是否至少注册了一个工具或资源 */
1023
+ hasAny() {
1024
+ return this.definitions.tools.length > 0 || this.definitions.resources.length > 0;
1025
+ }
1026
+ /** 是否已完成扫描 */
1027
+ isInitialized() {
1028
+ return this.initialized;
1029
+ }
1030
+ discover() {
1031
+ const wrappers = [
1032
+ ...this.discoveryService.getProviders(),
1033
+ ...this.discoveryService.getControllers()
1034
+ ];
1035
+ const parts = [];
1036
+ const seen = /* @__PURE__ */ new Set();
1037
+ for (const wrapper of wrappers) {
1038
+ if (isMcpToolsClass(wrapper.metatype) && (wrapper.scope === import_common4.Scope.REQUEST || wrapper.scope === import_common4.Scope.TRANSIENT || !wrapper.isDependencyTreeStatic())) {
1039
+ throw new Error(`${wrapper.metatype.name}: MCP \u5DE5\u5177\u5FC5\u987B\u4F7F\u7528\u5355\u4F8B\u53CA\u5355\u4F8B\u4F9D\u8D56\uFF0C\u901A\u8FC7 ctx.user \u8BFB\u53D6\u8BF7\u6C42\u8EAB\u4EFD`);
1040
+ }
1041
+ const { instance } = wrapper;
1042
+ if (!instance || typeof instance !== "object") {
1043
+ if (isMcpToolsClass(wrapper.metatype)) {
1044
+ this.logger.warn(`${wrapper.metatype.name} \u6807\u8BB0\u4E86 @McpTools() \u4F46\u6CA1\u6709\u53EF\u7528\u5B9E\u4F8B\uFF08request/transient \u4F5C\u7528\u57DF\u6216\u672A\u5B9E\u4F8B\u5316\uFF09\uFF0C\u5DF2\u8DF3\u8FC7`);
1045
+ }
1046
+ continue;
1047
+ }
1048
+ const target = instance.constructor;
1049
+ if (!isMcpToolsClass(target) || seen.has(instance)) continue;
1050
+ seen.add(instance);
1051
+ parts.push(collectFromClass(target, instance));
1052
+ }
1053
+ this.definitions = mergeAndValidate(parts);
1054
+ this.initialized = true;
1055
+ const { tools, resources } = this.definitions;
1056
+ if (tools.length === 0 && resources.length === 0) {
1057
+ this.logger.debug("\u672A\u53D1\u73B0 MCP \u5DE5\u5177\uFF0C/__innerapi__/mcp \u5C06\u8FD4\u56DE 404");
1058
+ return;
1059
+ }
1060
+ this.logger.log(`\u5DF2\u6CE8\u518C ${tools.length} \u4E2A MCP \u5DE5\u5177${resources.length ? `\u3001${resources.length} \u4E2A MCP Apps \u8D44\u6E90` : ""}\uFF1A${tools.map((t2) => t2.name).join(", ")}`);
1061
+ }
1062
+ };
1063
+ McpRegistryService = _ts_decorate([
1064
+ (0, import_common4.Injectable)(),
1065
+ _ts_param(0, (0, import_common4.Inject)(import_core.DiscoveryService)),
1066
+ _ts_param(1, (0, import_common4.Inject)(MCP_MODULE_OPTIONS)),
1067
+ _ts_metadata("design:type", Function),
1068
+ _ts_metadata("design:paramtypes", [
1069
+ typeof import_core.DiscoveryService === "undefined" ? Object : import_core.DiscoveryService,
1070
+ typeof McpModuleOptions === "undefined" ? Object : McpModuleOptions
1071
+ ])
1072
+ ], McpRegistryService);
1073
+
1074
+ // src/skill.ts
1075
+ var import_node_fs = require("fs");
1076
+ var import_node_path2 = __toESM(require("path"), 1);
1077
+ async function readMcpSkill(cwd = process.cwd()) {
1078
+ const root = await import_node_fs.promises.realpath(cwd);
1079
+ let file;
1080
+ try {
1081
+ file = await import_node_fs.promises.realpath(import_node_path2.default.join(root, MCP_SKILL_PATH));
1082
+ } catch (error) {
1083
+ if (error.code === "ENOENT") return null;
1084
+ throw error;
1085
+ }
1086
+ const relative = import_node_path2.default.relative(root, file);
1087
+ if (relative.startsWith("..") || import_node_path2.default.isAbsolute(relative)) throw new Error("MCP Skill \u5FC5\u987B\u4F4D\u4E8E\u5E94\u7528\u5DE5\u7A0B\u5185");
1088
+ if (!(await import_node_fs.promises.stat(file)).isFile()) throw new Error("MCP Skill \u5FC5\u987B\u4E3A\u666E\u901A\u6587\u4EF6");
1089
+ const handle = await import_node_fs.promises.open(file, import_node_fs.constants.O_RDONLY | import_node_fs.constants.O_NONBLOCK | import_node_fs.constants.O_NOFOLLOW);
1090
+ try {
1091
+ const stat = await handle.stat();
1092
+ const limit = 1024 * 1024;
1093
+ if (!stat.isFile() || stat.size > limit) throw new Error("MCP Skill \u5FC5\u987B\u4E3A\u4E0D\u8D85\u8FC7 1 MiB \u7684\u666E\u901A\u6587\u4EF6");
1094
+ const buffer = Buffer.alloc(limit + 1);
1095
+ let length = 0;
1096
+ while (length < buffer.length) {
1097
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, null);
1098
+ if (bytesRead === 0) break;
1099
+ length += bytesRead;
1100
+ }
1101
+ if (length > limit) throw new Error("MCP Skill \u4E0D\u80FD\u8D85\u8FC7 1 MiB");
1102
+ const content = new TextDecoder("utf-8", {
1103
+ fatal: true
1104
+ }).decode(buffer.subarray(0, length));
1105
+ return {
1106
+ uri: MCP_SKILL_URI,
1107
+ path: MCP_SKILL_PATH,
1108
+ content
1109
+ };
1110
+ } finally {
1111
+ await handle.close();
1112
+ }
1113
+ }
1114
+ __name(readMcpSkill, "readMcpSkill");
1115
+
1116
+ // src/source-locations.ts
1117
+ var import_node_fs2 = require("fs");
1118
+ var import_node_module = require("module");
1119
+ var import_node_path3 = __toESM(require("path"), 1);
1120
+ var sdkEntrypoints = /* @__PURE__ */ new Set([
1121
+ "@lark-apaas/nestjs-mcp",
1122
+ "@lark-apaas/fullstack-nestjs-core"
1123
+ ]);
1124
+ var ignored = /* @__PURE__ */ new Set([
1125
+ "node_modules",
1126
+ "dist",
1127
+ "build",
1128
+ "coverage",
1129
+ "__tests__",
1130
+ "__test__",
1131
+ "test",
1132
+ "tests"
1133
+ ]);
1134
+ function isInside(root, file) {
1135
+ const relative = import_node_path3.default.relative(root, file);
1136
+ return relative !== ".." && !relative.startsWith(`..${import_node_path3.default.sep}`) && !import_node_path3.default.isAbsolute(relative);
1137
+ }
1138
+ __name(isInside, "isInside");
1139
+ async function collectSourceLocations(tools, resources, cwd = process.cwd()) {
1140
+ const empty = /* @__PURE__ */ __name(() => ({
1141
+ tools: {},
1142
+ resources: {}
1143
+ }), "empty");
1144
+ try {
1145
+ if (!tools.length && !resources.length) return empty();
1146
+ const root = await import_node_fs2.promises.realpath(cwd);
1147
+ const server = import_node_path3.default.join(root, "server");
1148
+ if ((await import_node_fs2.promises.lstat(server)).isSymbolicLink()) return empty();
1149
+ const ts = (0, import_node_module.createRequire)(import_node_path3.default.join(root, "package.json"))("typescript");
1150
+ const sources = /* @__PURE__ */ new Map();
1151
+ const scan = /* @__PURE__ */ __name(async (directory) => {
1152
+ for (const item of await import_node_fs2.promises.readdir(directory, {
1153
+ withFileTypes: true
1154
+ })) {
1155
+ if (item.isSymbolicLink() || item.name.startsWith(".") || ignored.has(item.name)) continue;
1156
+ const file = import_node_path3.default.join(directory, item.name);
1157
+ if (item.isDirectory()) await scan(file);
1158
+ else if (item.isFile() && /\.(?:ts|tsx|mts|cts)$/.test(item.name) && !/\.(?:d|spec|test)\.(?:ts|tsx|mts|cts)$/.test(item.name)) {
1159
+ sources.set(file, await import_node_fs2.promises.readFile(file, "utf8"));
1160
+ }
1161
+ }
1162
+ }, "scan");
1163
+ await scan(server);
1164
+ if (!sources.size) return empty();
1165
+ const options = {
1166
+ noLib: true,
1167
+ noResolve: true,
1168
+ experimentalDecorators: true
1169
+ };
1170
+ const host = ts.createCompilerHost(options);
1171
+ host.getSourceFile = (file, languageVersion) => {
1172
+ const text = sources.get(file);
1173
+ return text === void 0 ? void 0 : ts.createSourceFile(file, text, languageVersion, true);
1174
+ };
1175
+ const program = ts.createProgram([
1176
+ ...sources.keys()
1177
+ ], options, host);
1178
+ if (program.getSyntacticDiagnostics().length) return empty();
1179
+ const checker = program.getTypeChecker();
1180
+ const isSdkReference = /* @__PURE__ */ __name((expression, exported) => {
1181
+ let identifier;
1182
+ let namespace = false;
1183
+ if (ts.isIdentifier(expression)) identifier = expression;
1184
+ else if (ts.isPropertyAccessExpression(expression) && ts.isIdentifier(expression.expression) && expression.name.text === exported) {
1185
+ identifier = expression.expression;
1186
+ namespace = true;
1187
+ } else return false;
1188
+ const declarations = checker.getSymbolAtLocation(identifier)?.declarations;
1189
+ if (declarations?.length !== 1) return false;
1190
+ const declaration = declarations[0];
1191
+ let clause;
1192
+ if (!namespace && ts.isImportSpecifier(declaration) && !declaration.isTypeOnly && (declaration.propertyName ?? declaration.name).text === exported) {
1193
+ clause = declaration.parent.parent;
1194
+ } else if (namespace && ts.isNamespaceImport(declaration)) clause = declaration.parent;
1195
+ else return false;
1196
+ return !clause.isTypeOnly && ts.isStringLiteral(clause.parent.moduleSpecifier) && sdkEntrypoints.has(clause.parent.moduleSpecifier.text);
1197
+ }, "isSdkReference");
1198
+ const decorated = /* @__PURE__ */ __name((node, exported) => {
1199
+ return ts.canHaveDecorators(node) && !!ts.getDecorators(node)?.some(({ expression }) => ts.isCallExpression(expression) && isSdkReference(expression.expression, exported));
1200
+ }, "decorated");
1201
+ const classes = /* @__PURE__ */ new Map();
1202
+ for (const source of program.getSourceFiles()) {
1203
+ const visit = /* @__PURE__ */ __name((node) => {
1204
+ if (ts.isClassDeclaration(node) && node.name) {
1205
+ const matches = classes.get(node.name.text) ?? [];
1206
+ matches.push(node);
1207
+ classes.set(node.name.text, matches);
1208
+ }
1209
+ ts.forEachChild(node, visit);
1210
+ }, "visit");
1211
+ visit(source);
1212
+ }
1213
+ const methodFor = /* @__PURE__ */ __name((definition, decorator) => {
1214
+ const matches = classes.get(definition.className);
1215
+ if (matches?.length !== 1 || !decorated(matches[0], "McpTools")) return void 0;
1216
+ const methods = matches[0].members.filter((member) => ts.isMethodDeclaration(member) && (ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)) && member.name.text === definition.methodName);
1217
+ if (methods.length !== 1 || !methods[0].body || !decorated(methods[0], decorator)) return void 0;
1218
+ return methods[0];
1219
+ }, "methodFor");
1220
+ const result = empty();
1221
+ const unique = /* @__PURE__ */ __name((items, key) => {
1222
+ const counts = /* @__PURE__ */ new Map();
1223
+ for (const item of items) counts.set(key(item), (counts.get(key(item)) ?? 0) + 1);
1224
+ return items.filter((item) => counts.get(key(item)) === 1);
1225
+ }, "unique");
1226
+ const put = /* @__PURE__ */ __name((map, key, value) => {
1227
+ Object.defineProperty(map, key, {
1228
+ value,
1229
+ enumerable: true,
1230
+ configurable: true,
1231
+ writable: true
1232
+ });
1233
+ }, "put");
1234
+ for (const tool of unique(tools, (item) => item.name)) {
1235
+ const method = methodFor(tool, "McpTool");
1236
+ if (!method) continue;
1237
+ const source = method.getSourceFile();
1238
+ put(result.tools, tool.name, {
1239
+ path: import_node_path3.default.relative(root, source.fileName).split(import_node_path3.default.sep).join("/"),
1240
+ line: source.getLineAndCharacterOfPosition(method.name.getStart(source)).line + 1
1241
+ });
1242
+ }
1243
+ for (const resource of unique(resources, (item) => item.options.uri)) {
1244
+ const method = methodFor(resource, "McpUiResource");
1245
+ if (!method) continue;
1246
+ const calls = [];
1247
+ const visit = /* @__PURE__ */ __name((node) => {
1248
+ if (ts.isFunctionLike(node) || ts.isClassLike(node)) return;
1249
+ if (ts.isCallExpression(node) && isSdkReference(node.expression, "readMcpUiTemplate")) calls.push(node);
1250
+ ts.forEachChild(node, visit);
1251
+ }, "visit");
1252
+ visit(method.body);
1253
+ if (calls.length !== 1 || calls[0].arguments.length !== 1) continue;
1254
+ const entry = calls[0].arguments[0];
1255
+ if (!(ts.isStringLiteral(entry) || ts.isNoSubstitutionTemplateLiteral(entry)) || !/^[A-Za-z0-9_-]+$/.test(entry.text)) continue;
1256
+ const relative = `client/mcp-ui/${entry.text}/index.html`;
1257
+ try {
1258
+ const file = await import_node_fs2.promises.realpath(import_node_path3.default.join(root, relative));
1259
+ if (file !== import_node_path3.default.join(root, relative) || !isInside(root, file) || !(await import_node_fs2.promises.stat(file)).isFile()) continue;
1260
+ put(result.resources, resource.options.uri, {
1261
+ path: relative
1262
+ });
1263
+ } catch {
1264
+ }
1265
+ }
1266
+ return result;
1267
+ } catch {
1268
+ return empty();
1269
+ }
1270
+ }
1271
+ __name(collectSourceLocations, "collectSourceLocations");
1272
+
1273
+ // src/services/mcp-manifest.service.ts
1274
+ function _ts_decorate2(decorators, target, key, desc) {
1275
+ var c = arguments.length, r2 = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
1276
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r2 = Reflect.decorate(decorators, target, key, desc);
1277
+ else for (var i2 = decorators.length - 1; i2 >= 0; i2--) if (d2 = decorators[i2]) r2 = (c < 3 ? d2(r2) : c > 3 ? d2(target, key, r2) : d2(target, key)) || r2;
1278
+ return c > 3 && r2 && Object.defineProperty(target, key, r2), r2;
1279
+ }
1280
+ __name(_ts_decorate2, "_ts_decorate");
1281
+ function _ts_metadata2(k2, v2) {
1282
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k2, v2);
1283
+ }
1284
+ __name(_ts_metadata2, "_ts_metadata");
1285
+ function _ts_param2(paramIndex, decorator) {
1286
+ return function(target, key) {
1287
+ decorator(target, key, paramIndex);
1288
+ };
1289
+ }
1290
+ __name(_ts_param2, "_ts_param");
1291
+ var McpManifestService = class _McpManifestService {
1292
+ static {
1293
+ __name(this, "McpManifestService");
1294
+ }
1295
+ registry;
1296
+ options;
1297
+ logger = new import_common5.Logger(_McpManifestService.name);
1298
+ sources = {
1299
+ tools: {},
1300
+ resources: {}
1301
+ };
1302
+ constructor(registry, options) {
1303
+ this.registry = registry;
1304
+ this.options = options;
1305
+ }
1306
+ async onApplicationBootstrap() {
1307
+ if (this.options.enabled === false) return;
1308
+ try {
1309
+ this.sources = await collectSourceLocations(this.registry.getTools(), this.registry.getResources());
1310
+ } catch (error) {
1311
+ this.logger.warn(`MCP \u6E90\u7801\u5B9A\u4F4D\u4E0D\u53EF\u7528\uFF1A${error instanceof Error ? error.message : String(error)}`);
1312
+ }
1313
+ const writeOnBoot = this.options.manifest?.writeOnBoot ?? process.env.NODE_ENV !== "production";
1314
+ if (!writeOnBoot) return;
1315
+ try {
1316
+ if (!this.registry.hasAny() && !await readMcpSkill()) {
1317
+ await import_node_fs3.promises.rm(import_node_path4.default.resolve(process.cwd(), this.options.manifest?.path ?? MCP_MANIFEST_PATH), {
1318
+ force: true
1319
+ });
1320
+ return;
1321
+ }
1322
+ const { changed, file } = await this.write();
1323
+ if (changed) this.logger.log(`\u5DF2\u66F4\u65B0 MCP \u6E05\u5355\uFF1A${import_node_path4.default.relative(process.cwd(), file)}`);
1324
+ } catch (error) {
1325
+ this.logger.warn(`\u5199\u5165 MCP \u6E05\u5355\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`);
1326
+ }
1327
+ }
1328
+ /** 生成清单对象 */
1329
+ async build(cwd = process.cwd()) {
1330
+ const manifest = await buildManifest({
1331
+ skill: await readMcpSkill(cwd),
1332
+ tools: this.registry.getTools(),
1333
+ resources: this.registry.getResources(),
1334
+ options: this.options
1335
+ });
1336
+ manifest.sources = {
1337
+ tools: {
1338
+ ...this.sources.tools
1339
+ },
1340
+ resources: {
1341
+ ...this.sources.resources
1342
+ }
1343
+ };
1344
+ if (manifest.skill) manifest.sources.resources[manifest.skill.uri] = {
1345
+ path: manifest.skill.path
1346
+ };
1347
+ return manifest;
1348
+ }
1349
+ /** 面板查询不读写派生清单;与本次 MCP 请求使用同一份 Skill 文件读取逻辑。 */
1350
+ async catalog() {
1351
+ const skill = await readMcpSkill();
1352
+ const manifest = await buildManifest({
1353
+ tools: this.registry.getTools(),
1354
+ resources: this.registry.getResources(),
1355
+ options: this.options,
1356
+ skill
1357
+ });
1358
+ const sources = {
1359
+ tools: {
1360
+ ...this.sources.tools
1361
+ },
1362
+ resources: {
1363
+ ...this.sources.resources
1364
+ }
1365
+ };
1366
+ if (skill) sources.resources[skill.uri] = {
1367
+ path: skill.path
1368
+ };
1369
+ return {
1370
+ version: manifest.version,
1371
+ generatedAt: manifest.generatedAt,
1372
+ endpoint: manifest.endpoint,
1373
+ tools: manifest.tools.map(({ source: _source, ...tool }) => tool),
1374
+ resources: manifest.resources.map(({ source: _source, ...resource }) => resource),
1375
+ skill,
1376
+ sources
1377
+ };
1378
+ }
1379
+ /** 生成并写入清单文件,内容未变化时不落盘 */
1380
+ async write(cwd = process.cwd()) {
1381
+ const manifest = await this.build(cwd);
1382
+ return writeManifest(manifest, {
1383
+ cwd,
1384
+ relativePath: this.options.manifest?.path,
1385
+ fs: import_node_fs3.promises
1386
+ });
1387
+ }
1388
+ };
1389
+ McpManifestService = _ts_decorate2([
1390
+ (0, import_common5.Injectable)(),
1391
+ _ts_param2(0, (0, import_common5.Inject)(McpRegistryService)),
1392
+ _ts_param2(1, (0, import_common5.Inject)(MCP_MODULE_OPTIONS)),
1393
+ _ts_metadata2("design:type", Function),
1394
+ _ts_metadata2("design:paramtypes", [
1395
+ typeof McpRegistryService === "undefined" ? Object : McpRegistryService,
1396
+ typeof McpModuleOptions === "undefined" ? Object : McpModuleOptions
1397
+ ])
1398
+ ], McpManifestService);
1399
+
1400
+ // src/controllers/mcp-manifest.controller.ts
1401
+ function _ts_decorate3(decorators, target, key, desc) {
1402
+ var c = arguments.length, r2 = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
1403
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r2 = Reflect.decorate(decorators, target, key, desc);
1404
+ else for (var i2 = decorators.length - 1; i2 >= 0; i2--) if (d2 = decorators[i2]) r2 = (c < 3 ? d2(r2) : c > 3 ? d2(target, key, r2) : d2(target, key)) || r2;
1405
+ return c > 3 && r2 && Object.defineProperty(target, key, r2), r2;
1406
+ }
1407
+ __name(_ts_decorate3, "_ts_decorate");
1408
+ function _ts_metadata3(k2, v2) {
1409
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k2, v2);
1410
+ }
1411
+ __name(_ts_metadata3, "_ts_metadata");
1412
+ function _ts_param3(paramIndex, decorator) {
1413
+ return function(target, key) {
1414
+ decorator(target, key, paramIndex);
1415
+ };
1416
+ }
1417
+ __name(_ts_param3, "_ts_param");
1418
+ var McpManifestController = class _McpManifestController {
1419
+ static {
1420
+ __name(this, "McpManifestController");
1421
+ }
1422
+ manifest;
1423
+ registry;
1424
+ logger = new import_common6.Logger(_McpManifestController.name);
1425
+ constructor(manifest, registry) {
1426
+ this.manifest = manifest;
1427
+ this.registry = registry;
1428
+ }
1429
+ async get(res) {
1430
+ res.setHeader("Cache-Control", "no-store");
1431
+ if (!this.registry.isInitialized()) {
1432
+ res.status(503).type("application/problem+json").json({
1433
+ type: "about:blank",
1434
+ title: "Service Unavailable",
1435
+ status: 503
1436
+ });
1437
+ return;
1438
+ }
1439
+ try {
1440
+ res.json(await this.manifest.catalog());
1441
+ } catch (error) {
1442
+ this.logger.error(error instanceof Error ? error.stack : String(error));
1443
+ res.status(500).type("application/problem+json").json({
1444
+ type: "about:blank",
1445
+ title: "Internal Server Error",
1446
+ status: 500
1447
+ });
1448
+ }
1449
+ }
1450
+ };
1451
+ _ts_decorate3([
1452
+ (0, import_common6.Get)(),
1453
+ _ts_param3(0, (0, import_common6.Res)()),
1454
+ _ts_metadata3("design:type", Function),
1455
+ _ts_metadata3("design:paramtypes", [
1456
+ typeof Response === "undefined" ? Object : Response
1457
+ ]),
1458
+ _ts_metadata3("design:returntype", Promise)
1459
+ ], McpManifestController.prototype, "get", null);
1460
+ McpManifestController = _ts_decorate3([
1461
+ (0, import_swagger.ApiExcludeController)(),
1462
+ (0, import_common6.Controller)("__innerapi__/mcp/manifest"),
1463
+ _ts_param3(0, (0, import_common6.Inject)(McpManifestService)),
1464
+ _ts_param3(1, (0, import_common6.Inject)(McpRegistryService)),
1465
+ _ts_metadata3("design:type", Function),
1466
+ _ts_metadata3("design:paramtypes", [
1467
+ typeof McpManifestService === "undefined" ? Object : McpManifestService,
1468
+ typeof McpRegistryService === "undefined" ? Object : McpRegistryService
1469
+ ])
1470
+ ], McpManifestController);
1471
+
1472
+ // src/controllers/mcp.controller.ts
1473
+ var import_common8 = require("@nestjs/common");
1474
+ var import_swagger2 = require("@nestjs/swagger");
1475
+
1476
+ // src/services/mcp-server.service.ts
1477
+ var import_common7 = require("@nestjs/common");
1478
+ var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
1479
+ function _ts_decorate4(decorators, target, key, desc) {
1480
+ var c = arguments.length, r2 = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
1481
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r2 = Reflect.decorate(decorators, target, key, desc);
1482
+ else for (var i2 = decorators.length - 1; i2 >= 0; i2--) if (d2 = decorators[i2]) r2 = (c < 3 ? d2(r2) : c > 3 ? d2(target, key, r2) : d2(target, key)) || r2;
1483
+ return c > 3 && r2 && Object.defineProperty(target, key, r2), r2;
1484
+ }
1485
+ __name(_ts_decorate4, "_ts_decorate");
1486
+ function _ts_metadata4(k2, v2) {
1487
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k2, v2);
1488
+ }
1489
+ __name(_ts_metadata4, "_ts_metadata");
1490
+ function _ts_param4(paramIndex, decorator) {
1491
+ return function(target, key) {
1492
+ decorator(target, key, paramIndex);
1493
+ };
1494
+ }
1495
+ __name(_ts_param4, "_ts_param");
1496
+ var McpServerService = class _McpServerService {
1497
+ static {
1498
+ __name(this, "McpServerService");
1499
+ }
1500
+ registry;
1501
+ options;
1502
+ logger = new import_common7.Logger(_McpServerService.name);
1503
+ constructor(registry, options) {
1504
+ this.registry = registry;
1505
+ this.options = options;
1506
+ }
1507
+ /**
1508
+ * 为一次 HTTP 请求构造执行上下文。
1509
+ */
1510
+ createContext(req, extra) {
1511
+ return {
1512
+ user: req.userContext ?? {},
1513
+ request: req,
1514
+ signal: extra?.signal ?? new AbortController().signal,
1515
+ requestId: extra?.requestId ?? "",
1516
+ extra
1517
+ };
1518
+ }
1519
+ /**
1520
+ * 处理一条 MCP over Streamable HTTP 请求(POST)。
1521
+ */
1522
+ async handle(req, res) {
1523
+ const skill = await readMcpSkill();
1524
+ if (!this.registry.hasAny() && !skill) {
1525
+ res.status(404).json({
1526
+ jsonrpc: "2.0",
1527
+ error: {
1528
+ code: -32e3,
1529
+ message: "\u5F53\u524D\u5E94\u7528\u672A\u6CE8\u518C\u4EFB\u4F55 MCP \u80FD\u529B"
1530
+ },
1531
+ id: null
1532
+ });
1533
+ return;
1534
+ }
1535
+ const server = createMcpServer({
1536
+ skill,
1537
+ tools: this.registry.getTools(),
1538
+ resources: this.registry.getResources(),
1539
+ options: this.options,
1540
+ createContext: /* @__PURE__ */ __name((extra) => this.createContext(req, extra), "createContext"),
1541
+ onError: /* @__PURE__ */ __name((error, location) => {
1542
+ this.logger.error(`MCP \u5DE5\u5177\u6267\u884C\u5F02\u5E38\uFF08${location}\uFF09\uFF1A${error instanceof Error ? error.stack ?? error.message : String(error)}`);
1543
+ }, "onError")
1544
+ });
1545
+ const transport = new import_streamableHttp.StreamableHTTPServerTransport({
1546
+ sessionIdGenerator: void 0,
1547
+ enableJsonResponse: true
1548
+ });
1549
+ res.on("close", () => {
1550
+ server.close().catch((error) => {
1551
+ this.logger.warn(`\u5173\u95ED McpServer \u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`);
1552
+ });
1553
+ });
1554
+ await server.connect(transport);
1555
+ await transport.handleRequest(req, res, req.body);
1556
+ }
1557
+ };
1558
+ McpServerService = _ts_decorate4([
1559
+ (0, import_common7.Injectable)(),
1560
+ _ts_param4(0, (0, import_common7.Inject)(McpRegistryService)),
1561
+ _ts_param4(1, (0, import_common7.Inject)(MCP_MODULE_OPTIONS)),
1562
+ _ts_metadata4("design:type", Function),
1563
+ _ts_metadata4("design:paramtypes", [
1564
+ typeof McpRegistryService === "undefined" ? Object : McpRegistryService,
1565
+ typeof McpModuleOptions === "undefined" ? Object : McpModuleOptions
1566
+ ])
1567
+ ], McpServerService);
1568
+
1569
+ // src/controllers/mcp.controller.ts
1570
+ function _ts_decorate5(decorators, target, key, desc) {
1571
+ var c = arguments.length, r2 = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
1572
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r2 = Reflect.decorate(decorators, target, key, desc);
1573
+ else for (var i2 = decorators.length - 1; i2 >= 0; i2--) if (d2 = decorators[i2]) r2 = (c < 3 ? d2(r2) : c > 3 ? d2(target, key, r2) : d2(target, key)) || r2;
1574
+ return c > 3 && r2 && Object.defineProperty(target, key, r2), r2;
1575
+ }
1576
+ __name(_ts_decorate5, "_ts_decorate");
1577
+ function _ts_metadata5(k2, v2) {
1578
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k2, v2);
1579
+ }
1580
+ __name(_ts_metadata5, "_ts_metadata");
1581
+ function _ts_param5(paramIndex, decorator) {
1582
+ return function(target, key) {
1583
+ decorator(target, key, paramIndex);
1584
+ };
1585
+ }
1586
+ __name(_ts_param5, "_ts_param");
1587
+ var McpController = class _McpController {
1588
+ static {
1589
+ __name(this, "McpController");
1590
+ }
1591
+ serverService;
1592
+ logger = new import_common8.Logger(_McpController.name);
1593
+ constructor(serverService) {
1594
+ this.serverService = serverService;
1595
+ }
1596
+ async handlePost(req, res) {
1597
+ try {
1598
+ await this.serverService.handle(req, res);
1599
+ } catch (error) {
1600
+ this.logger.error(`\u5904\u7406 MCP \u8BF7\u6C42\u5931\u8D25\uFF1A${error instanceof Error ? error.stack ?? error.message : String(error)}`);
1601
+ if (!res.headersSent) {
1602
+ res.status(500).json({
1603
+ jsonrpc: "2.0",
1604
+ error: {
1605
+ code: -32603,
1606
+ message: "Internal server error"
1607
+ },
1608
+ id: null
1609
+ });
1610
+ }
1611
+ }
1612
+ }
1613
+ /** GET / DELETE 等其他方法:无状态模式不提供 SSE 会话,统一 405 */
1614
+ handleOthers(res) {
1615
+ this.methodNotAllowed(res);
1616
+ }
1617
+ methodNotAllowed(res) {
1618
+ res.setHeader("Allow", "POST");
1619
+ res.status(405).json({
1620
+ jsonrpc: "2.0",
1621
+ error: {
1622
+ code: -32e3,
1623
+ message: "Method not allowed. \u4EC5\u652F\u6301 POST\uFF08\u65E0\u72B6\u6001 Streamable HTTP\uFF09"
1624
+ },
1625
+ id: null
1626
+ });
1627
+ }
1628
+ };
1629
+ _ts_decorate5([
1630
+ (0, import_common8.Post)(),
1631
+ _ts_param5(0, (0, import_common8.Req)()),
1632
+ _ts_param5(1, (0, import_common8.Res)()),
1633
+ _ts_metadata5("design:type", Function),
1634
+ _ts_metadata5("design:paramtypes", [
1635
+ typeof Request === "undefined" ? Object : Request,
1636
+ typeof Response === "undefined" ? Object : Response
1637
+ ]),
1638
+ _ts_metadata5("design:returntype", Promise)
1639
+ ], McpController.prototype, "handlePost", null);
1640
+ _ts_decorate5([
1641
+ (0, import_common8.All)(),
1642
+ _ts_param5(0, (0, import_common8.Res)()),
1643
+ _ts_metadata5("design:type", Function),
1644
+ _ts_metadata5("design:paramtypes", [
1645
+ typeof Response === "undefined" ? Object : Response
1646
+ ]),
1647
+ _ts_metadata5("design:returntype", void 0)
1648
+ ], McpController.prototype, "handleOthers", null);
1649
+ McpController = _ts_decorate5([
1650
+ (0, import_swagger2.ApiExcludeController)(),
1651
+ (0, import_common8.Controller)(MCP_CONTROLLER_PATH),
1652
+ _ts_param5(0, (0, import_common8.Inject)(McpServerService)),
1653
+ _ts_metadata5("design:type", Function),
1654
+ _ts_metadata5("design:paramtypes", [
1655
+ typeof McpServerService === "undefined" ? Object : McpServerService
1656
+ ])
1657
+ ], McpController);
1658
+
1659
+ // src/mcp.module.ts
1660
+ function _ts_decorate6(decorators, target, key, desc) {
1661
+ var c = arguments.length, r2 = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
1662
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r2 = Reflect.decorate(decorators, target, key, desc);
1663
+ else for (var i2 = decorators.length - 1; i2 >= 0; i2--) if (d2 = decorators[i2]) r2 = (c < 3 ? d2(r2) : c > 3 ? d2(target, key, r2) : d2(target, key)) || r2;
1664
+ return c > 3 && r2 && Object.defineProperty(target, key, r2), r2;
1665
+ }
1666
+ __name(_ts_decorate6, "_ts_decorate");
1667
+ var McpModule = class _McpModule {
1668
+ static {
1669
+ __name(this, "McpModule");
1670
+ }
1671
+ static forRoot(options = {}) {
1672
+ const enabled = options.enabled !== false;
1673
+ const providers = [
1674
+ {
1675
+ provide: MCP_MODULE_OPTIONS,
1676
+ useValue: options
1677
+ },
1678
+ McpRegistryService,
1679
+ McpServerService,
1680
+ McpManifestService
1681
+ ];
1682
+ return {
1683
+ module: _McpModule,
1684
+ global: true,
1685
+ imports: [
1686
+ import_core2.DiscoveryModule
1687
+ ],
1688
+ controllers: enabled ? [
1689
+ McpManifestController,
1690
+ McpController
1691
+ ] : [],
1692
+ providers,
1693
+ exports: [
1694
+ McpRegistryService,
1695
+ McpServerService,
1696
+ McpManifestService
1697
+ ]
1698
+ };
1699
+ }
1700
+ };
1701
+ McpModule = _ts_decorate6([
1702
+ (0, import_common9.Module)({})
1703
+ ], McpModule);
1704
+
1705
+ // src/ui-template.ts
1706
+ var import_node_fs4 = require("fs");
1707
+ var import_node_path5 = __toESM(require("path"), 1);
1708
+ var cache = /* @__PURE__ */ new Map();
1709
+ async function readMcpUiTemplate(entry, cwd = process.cwd()) {
1710
+ if (!/^[A-Za-z0-9_-]+$/.test(entry)) {
1711
+ throw new Error(`MCP Apps \u754C\u9762\u5165\u53E3\u540D\u300C${entry}\u300D\u4E0D\u5408\u6CD5\uFF0C\u4EC5\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u4E0E\u8FDE\u5B57\u7B26`);
1712
+ }
1713
+ const file = import_node_path5.default.join(cwd, MCP_UI_DIST_DIR, `${entry}.html`);
1714
+ const useCache = process.env.NODE_ENV === "production";
1715
+ if (useCache && cache.has(file)) {
1716
+ return cache.get(file);
1717
+ }
1718
+ let html;
1719
+ try {
1720
+ html = await import_node_fs4.promises.readFile(file, "utf8");
1721
+ } catch (error) {
1722
+ const reason = error instanceof Error ? error.message : String(error);
1723
+ throw new Error(`\u8BFB\u53D6 MCP Apps \u754C\u9762\u4EA7\u7269\u5931\u8D25\uFF1A${file}\u3002\u8BF7\u786E\u8BA4 client/mcp-ui/${entry}/index.html \u5B58\u5728\u4E14\u5DF2\u6267\u884C\u6784\u5EFA\u3002\u539F\u56E0\uFF1A${reason}`);
1724
+ }
1725
+ if (useCache) cache.set(file, html);
1726
+ return html;
1727
+ }
1728
+ __name(readMcpUiTemplate, "readMcpUiTemplate");
1729
+ // Annotate the CommonJS export names for ESM import in node:
1730
+ 0 && (module.exports = {
1731
+ MCP_CONTROLLER_PATH,
1732
+ MCP_DEFAULT_SERVER_NAME,
1733
+ MCP_DEFAULT_SERVER_VERSION,
1734
+ MCP_ENDPOINT_PATH,
1735
+ MCP_MANIFEST_PATH,
1736
+ MCP_MANIFEST_VERSION,
1737
+ MCP_MODULE_OPTIONS,
1738
+ MCP_SKILL_PATH,
1739
+ MCP_SKILL_URI,
1740
+ MCP_TOOLS_METADATA_KEY,
1741
+ MCP_TOOL_METADATA_KEY,
1742
+ MCP_TOOL_NAME_PATTERN,
1743
+ MCP_UI_DIST_DIR,
1744
+ MCP_UI_RESOURCE_METADATA_KEY,
1745
+ MCP_UI_RESOURCE_SCHEME,
1746
+ McpModule,
1747
+ McpTool,
1748
+ McpToolError,
1749
+ McpTools,
1750
+ McpUiResource,
1751
+ readMcpUiTemplate
1752
+ });
1753
+ //# sourceMappingURL=index.cjs.map