@nest-mcp/nestjs 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,2262 @@
1
+ import { a as isMcpRuntimeProviderToken, d as MCP_MODULE_OPTIONS, f as MCP_TARGETS_METADATA, i as McpProviderRegistry, l as MCP_HANDLER_METADATA, n as __decorate, o as mcpProviderTokenName, p as McpModuleError, r as __decorateMetadata, s as withMcpCollaborators, t as __decorateParam } from "./decorateParam-DrdHz1Pv.mjs";
2
+ import { n as McpClientService, t as McpClientModule } from "./mcp-client.module-D-EYsz9Y.mjs";
3
+ import { All, ConfigurableModuleBuilder, Controller, Get, Inject, Injectable, Module, Optional, Post, Req, Res, Scope, SetMetadata, VERSION_NEUTRAL, applyDecorators } from "@nestjs/common";
4
+ import { toNodeHandler } from "@modelcontextprotocol/node";
5
+ import { MCP_CORS_ALLOWED_HEADERS, MCP_CORS_EXPOSED_HEADERS, MCP_CORS_METHODS, hardenMcpFetch, resolveMcpHttpSecurity, withMcpNodeBodyLimit } from "@nest-mcp/server/security";
6
+ import { McpGateway, bindMcpGatewayMiddleware, createMcpClientRuntimeUpstream } from "@nest-mcp/gateway";
7
+ import { McpServerRegistry, ResourceTemplate, acceptedContent, completable, createRequestStateCodec, fromJsonSchema, inputRequired, inputResponse } from "@nest-mcp/server";
8
+ import { allowMcpOperation, composeMcpMiddleware, createMcpAuthorizationMiddleware, createMcpLifecycleMiddleware, createMcpOperation, createMcpOperationContext, createMcpPassthroughMiddleware, denyMcpOperation } from "@nest-mcp/core";
9
+ import { ProtocolError, ProtocolErrorCode, fromJsonSchema as fromJsonSchema$1, specTypeSchemas } from "@modelcontextprotocol/server";
10
+ import { DiscoveryModule, DiscoveryService, MetadataScanner, Reflector } from "@nestjs/core";
11
+ import { McpOAuthProxy, McpOAuthSecretKeyring, McpOAuthServer, McpUpstreamAdapter, createMcpClientIdMetadataResolver } from "@nest-mcp/auth";
12
+ import { McpResourceServer, buildOAuthProtectedResourceMetadata, getOAuthProtectedResourceMetadataUrl, oauthMetadataResponse } from "@nest-mcp/server/auth";
13
+ //#region src/mcp-catalog-exposure.ts
14
+ const MCP_CATALOG_SEARCH_TOOL_NAME = "nest-mcp.catalog.search";
15
+ const MCP_CATALOG_SCHEMAS_TOOL_NAME = "nest-mcp.catalog.schemas";
16
+ //#endregion
17
+ //#region src/decorators/mcp-handler.decorators.ts
18
+ function Tool(options) {
19
+ return typedMetadataDecorator(freezeToolDefinition(options));
20
+ }
21
+ function Resource(options) {
22
+ return typedMetadataDecorator(freezeResourceDefinition(options));
23
+ }
24
+ function Prompt(options) {
25
+ return typedMetadataDecorator(freezePromptDefinition(options));
26
+ }
27
+ /** Supplies a default server target for every MCP handler declared by a provider class. */
28
+ function Targets(...serverNames) {
29
+ const normalized = normalizeTargets(serverNames);
30
+ return SetMetadata(MCP_TARGETS_METADATA, normalized);
31
+ }
32
+ function typedMetadataDecorator(definition) {
33
+ const decorator = SetMetadata(MCP_HANDLER_METADATA, definition);
34
+ return (target, propertyKey, descriptor) => {
35
+ decorator(target, propertyKey, descriptor);
36
+ };
37
+ }
38
+ function freezeToolDefinition(options) {
39
+ const { tags, ...sdkOptions } = options;
40
+ const normalizedTags = normalizeTags(tags);
41
+ return Object.freeze({
42
+ kind: "tool",
43
+ options: freezeOptions({
44
+ ...sdkOptions,
45
+ ...normalizedTags === void 0 ? {} : { tags: normalizedTags }
46
+ })
47
+ });
48
+ }
49
+ function freezeResourceDefinition(options) {
50
+ return Object.freeze({
51
+ kind: "resource",
52
+ options: freezeOptions(options)
53
+ });
54
+ }
55
+ function freezePromptDefinition(options) {
56
+ return Object.freeze({
57
+ kind: "prompt",
58
+ options: freezeOptions(options)
59
+ });
60
+ }
61
+ function freezeOptions(options) {
62
+ const servers = options.servers;
63
+ const normalizedServers = servers === void 0 ? void 0 : typeof servers === "string" ? normalizeTargets([servers])[0] : normalizeTargets(servers);
64
+ return Object.freeze({
65
+ ...options,
66
+ ...normalizedServers === void 0 ? {} : { servers: normalizedServers }
67
+ });
68
+ }
69
+ function normalizeTargets(serverNames) {
70
+ if (serverNames.length === 0) throw new TypeError("At least one MCP server target is required.");
71
+ const normalized = serverNames.map((serverName, index) => {
72
+ if (typeof serverName !== "string" || serverName.trim().length === 0) throw new TypeError(`MCP target at index ${String(index)} must be a non-empty string.`);
73
+ return serverName.trim();
74
+ });
75
+ if (new Set(normalized).size !== normalized.length) throw new TypeError("MCP class-level targets must not contain duplicates.");
76
+ return Object.freeze(normalized);
77
+ }
78
+ function normalizeTags(tags) {
79
+ if (tags === void 0) return void 0;
80
+ if (!Array.isArray(tags) || tags.length > 32) throw new TypeError("MCP tool tags must be an array containing at most 32 entries.");
81
+ const normalized = tags.map((tag, index) => {
82
+ if (typeof tag !== "string" || tag.trim().length === 0 || tag.trim().length > 64) throw new TypeError(`MCP tool tag at index ${String(index)} must contain between 1 and 64 characters.`);
83
+ return tag.trim();
84
+ });
85
+ if (new Set(normalized).size !== normalized.length) throw new TypeError("MCP tool tags must not contain duplicates.");
86
+ return Object.freeze(normalized);
87
+ }
88
+ //#endregion
89
+ //#region src/http/node-bridge.ts
90
+ function toNodeRequest(request) {
91
+ const candidate = hasRaw(request) ? request.raw : request;
92
+ if (!isNodeRequest(candidate)) throw new TypeError("Nest MCP HTTP controller requires a Node-compatible HTTP request.");
93
+ return candidate;
94
+ }
95
+ function toNodeResponse(response) {
96
+ const candidate = hasRaw(response) ? response.raw : response;
97
+ if (!isNodeResponse(candidate)) throw new TypeError("Nest MCP HTTP controller requires a Node-compatible HTTP response.");
98
+ return candidate;
99
+ }
100
+ function parsedBodyOf(request) {
101
+ return hasBody(request) ? request.body : void 0;
102
+ }
103
+ function hijackFastifyReply(response, rawResponse) {
104
+ if (!isFastifyReply(response) || response.raw !== rawResponse) return;
105
+ response.hijack();
106
+ }
107
+ function forwardValidatedAuth(request, rawRequest) {
108
+ if (request === rawRequest || !isObject(request) || rawRequest.auth !== void 0) return;
109
+ const auth = Reflect.get(request, "auth");
110
+ if (isAuthInfo(auth)) rawRequest.auth = auth;
111
+ }
112
+ function isAuthInfo(value) {
113
+ if (!isObject(value)) return false;
114
+ const token = Reflect.get(value, "token");
115
+ const clientId = Reflect.get(value, "clientId");
116
+ const scopes = Reflect.get(value, "scopes");
117
+ const expiresAt = Reflect.get(value, "expiresAt");
118
+ const resource = Reflect.get(value, "resource");
119
+ const extra = Reflect.get(value, "extra");
120
+ return typeof token === "string" && typeof clientId === "string" && Array.isArray(scopes) && scopes.every((scope) => typeof scope === "string") && (expiresAt === void 0 || typeof expiresAt === "number") && (resource === void 0 || resource instanceof URL) && (extra === void 0 || isObject(extra));
121
+ }
122
+ function hasRaw(value) {
123
+ return isObject(value) && "raw" in value;
124
+ }
125
+ function hasBody(value) {
126
+ return isObject(value) && "body" in value;
127
+ }
128
+ function isFastifyReply(value) {
129
+ return hasRaw(value) && typeof Reflect.get(value, "hijack") === "function";
130
+ }
131
+ function isNodeRequest(value) {
132
+ return isObject(value) && isObject(Reflect.get(value, "headers")) && typeof Reflect.get(value, Symbol.asyncIterator) === "function";
133
+ }
134
+ function isNodeResponse(value) {
135
+ return isObject(value) && typeof Reflect.get(value, "writeHead") === "function" && typeof Reflect.get(value, "write") === "function" && typeof Reflect.get(value, "end") === "function" && typeof Reflect.get(value, "on") === "function";
136
+ }
137
+ function isObject(value) {
138
+ return typeof value === "object" && value !== null;
139
+ }
140
+ /** Reconstructs the request origin, honoring a terminating proxy's forwarded headers. */
141
+ function nodeRequestUrl(request) {
142
+ const raw = toNodeRequest(request);
143
+ const headers = raw.headers;
144
+ const forwardedProto = headerValue(headers["x-forwarded-proto"]);
145
+ const encrypted = Reflect.get(Reflect.get(raw, "socket") ?? {}, "encrypted") === true;
146
+ const scheme = forwardedProto ?? (encrypted ? "https" : "http");
147
+ const host = headerValue(headers["x-forwarded-host"]) ?? headerValue(headers.host) ?? "localhost";
148
+ return new URL(raw.url ?? "/", `${scheme}://${host}`);
149
+ }
150
+ /** Builds a web `Request` from a Nest request with an explicit body, for hand dispatch. */
151
+ function toWebRequestWithBody(request, body) {
152
+ const raw = toNodeRequest(request);
153
+ const url = nodeRequestUrl(request);
154
+ const headers = new Headers();
155
+ for (const [name, value] of Object.entries(raw.headers)) if (typeof value === "string") headers.set(name, value);
156
+ else if (Array.isArray(value)) headers.set(name, value.join(", "));
157
+ const method = (raw.method ?? "GET").toUpperCase();
158
+ const carriesBody = method !== "GET" && method !== "HEAD" && body !== void 0;
159
+ return new Request(url.href, {
160
+ method,
161
+ headers,
162
+ ...carriesBody ? { body } : {}
163
+ });
164
+ }
165
+ /** Reads a Node request body as text, capped; returns "" when the stream is empty or over cap. */
166
+ async function readNodeBodyText(request, maxBytes) {
167
+ const raw = toNodeRequest(request);
168
+ const chunks = [];
169
+ let total = 0;
170
+ for await (const chunk of raw) {
171
+ const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk instanceof Uint8Array ? Buffer.from(chunk) : void 0;
172
+ if (buffer === void 0) continue;
173
+ total += buffer.byteLength;
174
+ if (total > maxBytes) return "";
175
+ chunks.push(buffer);
176
+ }
177
+ return Buffer.concat(chunks).toString("utf8");
178
+ }
179
+ /** Writes a web `Response` (status, headers, multiple set-cookie, buffered body) to a Node response. */
180
+ async function writeWebResponse(response, nestResponse) {
181
+ const raw = toNodeResponse(nestResponse);
182
+ hijackFastifyReply(nestResponse, raw);
183
+ const headers = {};
184
+ response.headers.forEach((value, key) => {
185
+ if (key.toLowerCase() !== "set-cookie") headers[key] = value;
186
+ });
187
+ const cookies = typeof response.headers.getSetCookie === "function" ? response.headers.getSetCookie() : [];
188
+ if (cookies.length > 0) headers["set-cookie"] = cookies;
189
+ raw.writeHead(response.status, headers);
190
+ const body = response.body === null ? void 0 : Buffer.from(await response.arrayBuffer());
191
+ raw.end(body);
192
+ }
193
+ function headerValue(value) {
194
+ return Array.isArray(value) ? value[0] : value;
195
+ }
196
+ //#endregion
197
+ //#region src/mcp-catalog.runtime.ts
198
+ const MCP_CATALOG_MAX_TOOLS = 1e4;
199
+ const MCP_CATALOG_INPUT_BYTE_LIMIT = 16384;
200
+ const CATALOG_SELECTOR_LIMIT = 64;
201
+ const CATALOG_METADATA_BYTE_LIMIT = 8192;
202
+ const CATALOG_JSON_DEPTH_LIMIT = 16;
203
+ const EMPTY_INPUT_SCHEMA = Object.freeze({
204
+ type: "object",
205
+ properties: Object.freeze({})
206
+ });
207
+ const SEARCH_INPUT_SCHEMA = fromJsonSchema$1({
208
+ type: "object",
209
+ properties: {
210
+ query: {
211
+ type: "string",
212
+ maxLength: 256
213
+ },
214
+ cursor: {
215
+ type: "string",
216
+ maxLength: 512
217
+ },
218
+ limit: {
219
+ type: "integer",
220
+ minimum: 1,
221
+ maximum: 50
222
+ }
223
+ },
224
+ additionalProperties: false
225
+ });
226
+ const SCHEMAS_INPUT_SCHEMA = fromJsonSchema$1({
227
+ type: "object",
228
+ properties: { names: {
229
+ type: "array",
230
+ items: {
231
+ type: "string",
232
+ minLength: 1,
233
+ maxLength: 128
234
+ },
235
+ minItems: 1,
236
+ maxItems: 20,
237
+ uniqueItems: true
238
+ } },
239
+ required: ["names"],
240
+ additionalProperties: false
241
+ });
242
+ const SEARCH_OUTPUT_SCHEMA = fromJsonSchema$1({
243
+ type: "object",
244
+ properties: {
245
+ tools: {
246
+ type: "array",
247
+ items: {
248
+ type: "object",
249
+ properties: {
250
+ name: { type: "string" },
251
+ title: { type: "string" },
252
+ description: { type: "string" },
253
+ tags: {
254
+ type: "array",
255
+ items: { type: "string" }
256
+ }
257
+ },
258
+ required: ["name", "tags"],
259
+ additionalProperties: false
260
+ },
261
+ maxItems: 50
262
+ },
263
+ nextCursor: {
264
+ type: "string",
265
+ maxLength: 512
266
+ }
267
+ },
268
+ required: ["tools"],
269
+ additionalProperties: false
270
+ });
271
+ const SCHEMAS_OUTPUT_SCHEMA = standardSchemaWithJson(specTypeSchemas.ListToolsResult);
272
+ function assertMcpCatalogExposureOptions(options, runtimeName) {
273
+ if (typeof options !== "object" || options === null || typeof options.resolver !== "function") throw catalogError(`MCP catalog exposure for server "${runtimeName}" requires a resolver function.`);
274
+ }
275
+ /** Applies one strategy to only the exact post-visibility registrations owned by this build. */
276
+ async function applyMcpCatalogExposure(server, context, registrations, options, timeoutMs, registerMetaTool) {
277
+ try {
278
+ if (registrations.length > 1e4) throw catalogError(`MCP catalog for server "${context.runtimeName}" exceeds ${String(MCP_CATALOG_MAX_TOOLS)} visible tools.`);
279
+ const entries = Object.freeze(registrations.filter(({ registration }) => registration.enabled).map((registration) => snapshotEntry(registration)));
280
+ const resolverInput = snapshotResolverInput(context, entries);
281
+ const strategy = normalizeStrategy(await resolveWithinDeadline(options.resolver, resolverInput, timeoutMs, context.requestInfo?.signal), context.runtimeName);
282
+ if (strategy.kind === "eager") return;
283
+ const eager = selectEagerEntries(entries, strategy.eager, context.runtimeName);
284
+ if (strategy.kind === "search") {
285
+ applyDeferredMetadata(entries, eager, strategy.deferredMetadata, context.runtimeName);
286
+ return;
287
+ }
288
+ await installLazyCatalog(server, entries, eager, registerMetaTool);
289
+ } catch (cause) {
290
+ if (cause instanceof McpModuleError && cause.code === "INVALID_CATALOG_EXPOSURE") throw cause;
291
+ throw catalogError(`MCP catalog exposure failed closed for server "${context.runtimeName}".`, cause);
292
+ }
293
+ }
294
+ function snapshotEntry(registration) {
295
+ const tool = projectRegisteredTool(registration.name, registration.registration);
296
+ const tags = detachJson(registration.tags, "MCP catalog tags");
297
+ const publicTool = Object.freeze({
298
+ tool,
299
+ tags
300
+ });
301
+ return Object.freeze({
302
+ tool,
303
+ publicTool,
304
+ registration: registration.registration
305
+ });
306
+ }
307
+ function projectRegisteredTool(name, registration) {
308
+ return detachJson({
309
+ name,
310
+ ...registration.title === void 0 ? {} : { title: registration.title },
311
+ ...registration.description === void 0 ? {} : { description: registration.description },
312
+ inputSchema: registration.inputSchema === void 0 ? EMPTY_INPUT_SCHEMA : toInputJsonSchema(registration.inputSchema),
313
+ ...registration.outputSchema === void 0 ? {} : { outputSchema: toOutputJsonSchema(registration.outputSchema) },
314
+ ...registration.annotations === void 0 ? {} : { annotations: registration.annotations },
315
+ ...registration.icons === void 0 ? {} : { icons: registration.icons },
316
+ ...registration.execution === void 0 ? {} : { execution: registration.execution },
317
+ ...registration["_meta"] === void 0 ? {} : { _meta: registration["_meta"] }
318
+ }, `MCP tool "${name}"`);
319
+ }
320
+ function toInputJsonSchema(schema) {
321
+ const converted = schema["~standard"].jsonSchema.input({ target: "draft-2020-12" });
322
+ if (!isPlainRecord$1(converted)) throw catalogError("MCP tool input schema must convert to a JSON Schema object.");
323
+ if (converted.type !== void 0 && converted.type !== "object") throw catalogError("MCP tool input schema must describe an object at its root.");
324
+ return {
325
+ type: "object",
326
+ ...converted
327
+ };
328
+ }
329
+ function toOutputJsonSchema(schema) {
330
+ const converted = schema["~standard"].jsonSchema.output({ target: "draft-2020-12" });
331
+ if (!isPlainRecord$1(converted)) throw catalogError("MCP tool output schema must convert to a JSON Schema object.");
332
+ return {
333
+ ...converted.type === void 0 && isObjectShapedSchema(converted) ? { type: "object" } : {},
334
+ ...converted
335
+ };
336
+ }
337
+ function isObjectShapedSchema(schema) {
338
+ if ("properties" in schema || "patternProperties" in schema || "additionalProperties" in schema || "required" in schema) return true;
339
+ for (const keyword of [
340
+ "oneOf",
341
+ "anyOf",
342
+ "allOf"
343
+ ]) {
344
+ const members = schema[keyword];
345
+ if (Array.isArray(members) && members.length > 0 && members.every((member) => isPlainRecord$1(member) && (member.type === "object" || isObjectShapedSchema(member)))) return true;
346
+ }
347
+ return false;
348
+ }
349
+ function snapshotResolverInput(context, entries) {
350
+ const principal = context.principal === void 0 ? void 0 : Object.freeze({
351
+ ...context.principal,
352
+ scopes: Object.freeze([...context.principal.scopes])
353
+ });
354
+ return Object.freeze({
355
+ runtimeName: context.runtimeName,
356
+ era: context.era,
357
+ ...principal === void 0 ? {} : { principal },
358
+ ...context.requestInfo?.signal === void 0 ? {} : { signal: context.requestInfo.signal },
359
+ tools: Object.freeze(entries.map(({ publicTool }) => publicTool))
360
+ });
361
+ }
362
+ async function resolveWithinDeadline(resolver, input, timeoutMs, signal) {
363
+ const task = Promise.resolve().then(() => resolver(input));
364
+ return new Promise((resolve, reject) => {
365
+ let settled = false;
366
+ const finish = (callback) => {
367
+ if (settled) return;
368
+ settled = true;
369
+ clearTimeout(timer);
370
+ signal?.removeEventListener("abort", onAbort);
371
+ callback();
372
+ };
373
+ const onAbort = () => {
374
+ finish(() => reject(catalogError("MCP catalog exposure resolver was aborted before the build completed.", signal?.reason)));
375
+ };
376
+ const timer = setTimeout(() => {
377
+ finish(() => reject(catalogError(`MCP catalog exposure resolver exceeded its ${String(timeoutMs)}ms deadline.`)));
378
+ }, timeoutMs);
379
+ task.then((value) => finish(() => resolve(value)), (cause) => finish(() => reject(catalogError("MCP catalog exposure resolver threw or rejected.", cause))));
380
+ if (signal?.aborted === true) onAbort();
381
+ else signal?.addEventListener("abort", onAbort, { once: true });
382
+ });
383
+ }
384
+ function normalizeStrategy(value, runtimeName) {
385
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw catalogError(`MCP catalog resolver for server "${runtimeName}" must return a strategy object.`);
386
+ if (value.kind === "eager") return Object.freeze({ kind: "eager" });
387
+ if (value.kind === "search") return Object.freeze({
388
+ kind: "search",
389
+ eager: normalizeSelectors(value.eager),
390
+ deferredMetadata: normalizeDeferredMetadata(value.deferredMetadata)
391
+ });
392
+ if (value.kind === "lazy") return Object.freeze({
393
+ kind: "lazy",
394
+ eager: normalizeSelectors(value.eager)
395
+ });
396
+ throw catalogError(`MCP catalog resolver for server "${runtimeName}" returned an undeclared strategy kind.`);
397
+ }
398
+ function normalizeSelectors(selectors) {
399
+ if (selectors === void 0) return Object.freeze([]);
400
+ if (!Array.isArray(selectors) || selectors.length > CATALOG_SELECTOR_LIMIT) throw catalogError(`MCP catalog eager selectors must contain at most ${String(CATALOG_SELECTOR_LIMIT)} entries.`);
401
+ return Object.freeze(selectors.map((selector, index) => {
402
+ if (typeof selector !== "object" || selector === null) throw catalogError(`MCP catalog selector at index ${String(index)} must be an object.`);
403
+ if (selector.kind === "name") {
404
+ const name = normalizeBoundedString(selector.name, 128, `MCP catalog name selector at index ${String(index)}`);
405
+ return Object.freeze({
406
+ kind: "name",
407
+ name
408
+ });
409
+ }
410
+ if (selector.kind === "tag") {
411
+ const tag = normalizeBoundedString(selector.tag, 64, `MCP catalog tag selector at index ${String(index)}`);
412
+ return Object.freeze({
413
+ kind: "tag",
414
+ tag
415
+ });
416
+ }
417
+ if (selector.kind === "predicate" && typeof selector.predicate === "function") return Object.freeze({
418
+ kind: "predicate",
419
+ predicate: selector.predicate
420
+ });
421
+ throw catalogError(`MCP catalog selector at index ${String(index)} is invalid.`);
422
+ }));
423
+ }
424
+ function normalizeDeferredMetadata(value) {
425
+ const detached = detachJson(value, "MCP search exposure deferredMetadata", CATALOG_METADATA_BYTE_LIMIT);
426
+ if (!isPlainRecord$1(detached) || Object.keys(detached).length === 0) throw catalogError("MCP search exposure deferredMetadata must be a non-empty JSON object.");
427
+ return detached;
428
+ }
429
+ function selectEagerEntries(entries, selectors, runtimeName) {
430
+ const selected = /* @__PURE__ */ new Set();
431
+ for (const entry of entries) for (const selector of selectors) {
432
+ let matches;
433
+ if (selector.kind === "name") matches = entry.tool.name === selector.name;
434
+ else if (selector.kind === "tag") matches = entry.publicTool.tags.includes(selector.tag);
435
+ else {
436
+ let decision;
437
+ try {
438
+ decision = selector.predicate(entry.publicTool);
439
+ } catch (cause) {
440
+ throw catalogError(`MCP catalog predicate selector threw for tool "${entry.tool.name}" on server "${runtimeName}".`, cause);
441
+ }
442
+ if (typeof decision !== "boolean") throw catalogError(`MCP catalog predicate selector returned ${typeof decision} instead of boolean for tool "${entry.tool.name}" on server "${runtimeName}".`);
443
+ matches = decision;
444
+ }
445
+ if (matches) {
446
+ selected.add(entry);
447
+ break;
448
+ }
449
+ }
450
+ return selected;
451
+ }
452
+ function applyDeferredMetadata(entries, eager, metadata, runtimeName) {
453
+ for (const entry of entries) {
454
+ if (eager.has(entry)) continue;
455
+ const existing = entry.tool["_meta"] ?? {};
456
+ for (const key of Object.keys(metadata)) if (Object.hasOwn(existing, key)) throw catalogError(`MCP deferred metadata key "${key}" collides with existing _meta on tool "${entry.tool.name}" for server "${runtimeName}".`);
457
+ const merged = detachJson({
458
+ ...existing,
459
+ ...metadata
460
+ }, `MCP deferred metadata for tool "${entry.tool.name}"`);
461
+ entry.registration.update({ _meta: merged });
462
+ }
463
+ }
464
+ async function installLazyCatalog(server, entries, eager, registerMetaTool) {
465
+ const searchRegistration = registerMetaTool({
466
+ name: MCP_CATALOG_SEARCH_TOOL_NAME,
467
+ title: "Search tool catalog",
468
+ description: "Search the authorized tool catalog using bounded, paginated summaries.",
469
+ inputSchema: SEARCH_INPUT_SCHEMA,
470
+ outputSchema: SEARCH_OUTPUT_SCHEMA,
471
+ handler: async (input) => createSearchResult(entries, input)
472
+ });
473
+ const schemasRegistration = registerMetaTool({
474
+ name: MCP_CATALOG_SCHEMAS_TOOL_NAME,
475
+ title: "Fetch tool schemas",
476
+ description: "Fetch complete definitions for a bounded batch of authorized tools.",
477
+ inputSchema: SCHEMAS_INPUT_SCHEMA,
478
+ outputSchema: SCHEMAS_OUTPUT_SCHEMA,
479
+ handler: async (input) => createSchemasResult(entries, input)
480
+ });
481
+ const listed = [
482
+ ...entries.filter((entry) => eager.has(entry)).map(({ tool }) => tool),
483
+ projectRegisteredTool(MCP_CATALOG_SEARCH_TOOL_NAME, searchRegistration),
484
+ projectRegisteredTool(MCP_CATALOG_SCHEMAS_TOOL_NAME, schemasRegistration)
485
+ ];
486
+ const binding = await cursorBinding("list", listed.map(({ name }) => name));
487
+ server.server.setRequestHandler("tools/list", (request) => {
488
+ const offset = decodeCursor(request.params?.cursor, "list", binding).offset;
489
+ const tools = listed.slice(offset, offset + 50);
490
+ const nextOffset = offset + tools.length;
491
+ return {
492
+ tools,
493
+ ...nextOffset < listed.length ? { nextCursor: encodeCursor({
494
+ v: 1,
495
+ kind: "list",
496
+ offset: nextOffset,
497
+ binding
498
+ }) } : {}
499
+ };
500
+ });
501
+ }
502
+ async function createSearchResult(entries, input) {
503
+ assertInputSize(input, MCP_CATALOG_SEARCH_TOOL_NAME);
504
+ const query = normalizeSearchQuery(input.query);
505
+ const matches = entries.filter((entry) => matchesSearch(entry.publicTool, query));
506
+ const binding = await cursorBinding("search", [query, ...matches.map(({ tool }) => tool.name)]);
507
+ const cursor = decodeCursor(input.cursor, "search", binding);
508
+ const limit = normalizeSearchLimit(input.limit);
509
+ const tools = matches.slice(cursor.offset, cursor.offset + limit).map(({ publicTool }) => summarizeTool(publicTool));
510
+ const nextOffset = cursor.offset + tools.length;
511
+ const structuredContent = {
512
+ tools,
513
+ ...nextOffset < matches.length ? { nextCursor: encodeCursor({
514
+ v: 1,
515
+ kind: "search",
516
+ offset: nextOffset,
517
+ binding
518
+ }) } : {}
519
+ };
520
+ return {
521
+ content: [{
522
+ type: "text",
523
+ text: JSON.stringify(structuredContent)
524
+ }],
525
+ structuredContent
526
+ };
527
+ }
528
+ function createSchemasResult(entries, input) {
529
+ assertInputSize(input, MCP_CATALOG_SCHEMAS_TOOL_NAME);
530
+ if (!Array.isArray(input.names) || input.names.length > 20) throw invalidParams(`names must contain between 1 and ${String(20)} unique tool names.`);
531
+ const byName = new Map(entries.map((entry) => [entry.tool.name, entry.tool]));
532
+ const structuredContent = { tools: input.names.flatMap((name) => {
533
+ const tool = byName.get(name);
534
+ return tool === void 0 ? [] : [tool];
535
+ }) };
536
+ return {
537
+ content: [{
538
+ type: "text",
539
+ text: JSON.stringify(structuredContent)
540
+ }],
541
+ structuredContent
542
+ };
543
+ }
544
+ function summarizeTool(tool) {
545
+ return Object.freeze({
546
+ name: tool.tool.name,
547
+ ...tool.tool.title === void 0 ? {} : { title: tool.tool.title },
548
+ ...tool.tool.description === void 0 ? {} : { description: tool.tool.description },
549
+ tags: tool.tags
550
+ });
551
+ }
552
+ function matchesSearch(tool, query) {
553
+ if (query.length === 0) return true;
554
+ return [
555
+ tool.tool.name,
556
+ tool.tool.title,
557
+ tool.tool.description,
558
+ ...tool.tags
559
+ ].filter((value) => typeof value === "string").some((value) => value.toLowerCase().includes(query));
560
+ }
561
+ function normalizeSearchQuery(value) {
562
+ if (value === void 0) return "";
563
+ if (typeof value !== "string" || value.length > 256) throw invalidParams(`query must contain at most ${String(256)} characters.`);
564
+ return value.trim().toLowerCase();
565
+ }
566
+ function normalizeSearchLimit(value) {
567
+ const limit = value ?? 20;
568
+ if (!Number.isSafeInteger(limit) || limit <= 0 || limit > 50) throw invalidParams(`limit must be an integer between 1 and ${String(50)}.`);
569
+ return limit;
570
+ }
571
+ function encodeCursor(cursor) {
572
+ const bytes = new TextEncoder().encode(JSON.stringify(cursor));
573
+ let binary = "";
574
+ for (const byte of bytes) binary += String.fromCharCode(byte);
575
+ return `v1.${btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "")}`;
576
+ }
577
+ function decodeCursor(value, kind, binding) {
578
+ if (value === void 0) return {
579
+ v: 1,
580
+ kind,
581
+ offset: 0,
582
+ ...binding === void 0 ? {} : { binding }
583
+ };
584
+ if (typeof value !== "string" || value.length > 512 || !value.startsWith("v1.")) throw invalidParams("Invalid MCP catalog cursor.");
585
+ let parsed;
586
+ try {
587
+ const encoded = value.slice(3).replaceAll("-", "+").replaceAll("_", "/");
588
+ const padding = "=".repeat((4 - encoded.length % 4) % 4);
589
+ const binary = atob(encoded + padding);
590
+ const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
591
+ parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
592
+ } catch {
593
+ throw invalidParams("Invalid MCP catalog cursor.");
594
+ }
595
+ if (!isPlainRecord$1(parsed) || !hasExactCursorKeys(parsed, binding !== void 0) || parsed.v !== 1 || parsed.kind !== kind || !Number.isSafeInteger(parsed.offset) || typeof parsed.offset !== "number" || parsed.offset < 0 || parsed.offset > 1e4 || (binding === void 0 ? parsed.binding !== void 0 : parsed.binding !== binding)) throw invalidParams("Invalid MCP catalog cursor.");
596
+ return {
597
+ v: 1,
598
+ kind,
599
+ offset: parsed.offset,
600
+ ...binding === void 0 ? {} : { binding }
601
+ };
602
+ }
603
+ function hasExactCursorKeys(cursor, hasBinding) {
604
+ const expected = hasBinding ? [
605
+ "binding",
606
+ "kind",
607
+ "offset",
608
+ "v"
609
+ ] : [
610
+ "kind",
611
+ "offset",
612
+ "v"
613
+ ];
614
+ const actual = Object.keys(cursor).toSorted();
615
+ return actual.length === expected.length && actual.every((key, index) => key === expected[index]);
616
+ }
617
+ async function cursorBinding(kind, values) {
618
+ return [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify({
619
+ kind,
620
+ values
621
+ }))))].map((byte) => byte.toString(16).padStart(2, "0")).join("");
622
+ }
623
+ function assertInputSize(input, toolName) {
624
+ let serialized;
625
+ try {
626
+ serialized = JSON.stringify(input);
627
+ } catch {
628
+ throw invalidParams(`Input for ${toolName} must be JSON serializable.`);
629
+ }
630
+ if (new TextEncoder().encode(serialized).byteLength > 16384) throw invalidParams(`Input for ${toolName} exceeds ${String(MCP_CATALOG_INPUT_BYTE_LIMIT)} bytes.`);
631
+ }
632
+ function normalizeBoundedString(value, maximum, label) {
633
+ if (typeof value !== "string" || value.trim().length === 0 || value.trim().length > maximum) throw catalogError(`${label} must contain between 1 and ${String(maximum)} characters.`);
634
+ return value.trim();
635
+ }
636
+ function detachJson(value, label, maximumBytes) {
637
+ let clone;
638
+ try {
639
+ clone = structuredClone(value);
640
+ } catch (cause) {
641
+ throw catalogError(`${label} must be safely detachable.`, cause);
642
+ }
643
+ assertJsonSafe(clone, label, 0, /* @__PURE__ */ new Set());
644
+ if (maximumBytes !== void 0) {
645
+ if (new TextEncoder().encode(JSON.stringify(clone)).byteLength > maximumBytes) throw catalogError(`${label} exceeds ${String(maximumBytes)} serialized bytes.`);
646
+ }
647
+ return deepFreeze(clone);
648
+ }
649
+ function assertJsonSafe(value, label, depth, ancestors) {
650
+ if (value === null || typeof value === "string" || typeof value === "boolean") return;
651
+ if (typeof value === "number") {
652
+ if (Number.isFinite(value)) return;
653
+ throw catalogError(`${label} contains a non-finite number.`);
654
+ }
655
+ if (typeof value !== "object") throw catalogError(`${label} contains a non-JSON value.`);
656
+ if (depth >= CATALOG_JSON_DEPTH_LIMIT) throw catalogError(`${label} exceeds the maximum JSON nesting depth.`);
657
+ if (ancestors.has(value)) throw catalogError(`${label} must not contain cycles.`);
658
+ if (!Array.isArray(value) && !isPlainRecord$1(value)) throw catalogError(`${label} must contain only JSON arrays and objects.`);
659
+ ancestors.add(value);
660
+ for (const entry of Array.isArray(value) ? value : Object.values(value)) assertJsonSafe(entry, label, depth + 1, ancestors);
661
+ ancestors.delete(value);
662
+ }
663
+ function deepFreeze(value) {
664
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
665
+ for (const entry of Array.isArray(value) ? value : Object.values(value)) deepFreeze(entry);
666
+ return Object.freeze(value);
667
+ }
668
+ function isPlainRecord$1(value) {
669
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
670
+ const prototype = Object.getPrototypeOf(value);
671
+ return prototype === Object.prototype || prototype === null;
672
+ }
673
+ function standardSchemaWithJson(schema) {
674
+ if (!isStandardSchemaWithJson(schema)) throw new TypeError("Official MCP schema does not expose Standard JSON Schema conversion.");
675
+ return schema;
676
+ }
677
+ function isStandardSchemaWithJson(value) {
678
+ if ((typeof value !== "object" || value === null) && typeof value !== "function") return false;
679
+ const standard = Reflect.get(value, "~standard");
680
+ if (!isPlainRecord$1(standard)) return false;
681
+ const jsonSchema = standard.jsonSchema;
682
+ return isPlainRecord$1(jsonSchema) && typeof jsonSchema.input === "function" && typeof jsonSchema.output === "function" && typeof standard.validate === "function";
683
+ }
684
+ function invalidParams(message) {
685
+ return new ProtocolError(ProtocolErrorCode.InvalidParams, message);
686
+ }
687
+ function catalogError(message, cause) {
688
+ return new McpModuleError("INVALID_CATALOG_EXPOSURE", message, cause === void 0 ? void 0 : { cause });
689
+ }
690
+ //#endregion
691
+ //#region src/discovery/mcp-handler.registry.ts
692
+ const DEFAULT_VISIBILITY_TIMEOUT_MS = 3e4;
693
+ let McpHandlerRegistry = class McpHandlerRegistry {
694
+ providers;
695
+ #handlers = Object.freeze([]);
696
+ #closed = false;
697
+ #serverNames;
698
+ #gatewayNames = /* @__PURE__ */ new Set();
699
+ #catalogRuntimeNames = /* @__PURE__ */ new Set();
700
+ #mutationObservers = /* @__PURE__ */ new Set();
701
+ constructor(providers) {
702
+ this.providers = providers;
703
+ }
704
+ /** Adds one discovered handler. Prefer the typed capability methods for live registration. */
705
+ register(definition, handler, source) {
706
+ this.#append(definition, handler, source, this.#serverNames !== void 0);
707
+ }
708
+ /** Atomically installs a live tool for future per-request server builds. */
709
+ registerTool(options, handler, source = `dynamic tool "${options.name}"`) {
710
+ return this.#registerDynamic({
711
+ kind: "tool",
712
+ options
713
+ }, eraseHandler(handler), source, (next) => eraseHandler(next));
714
+ }
715
+ /** Atomically installs a live prompt for future per-request server builds. */
716
+ registerPrompt(options, handler, source = `dynamic prompt "${options.name}"`) {
717
+ return this.#registerDynamic({
718
+ kind: "prompt",
719
+ options
720
+ }, eraseHandler(handler), source, (next) => eraseHandler(next));
721
+ }
722
+ /** Atomically installs a fixed or templated resource for future server builds. */
723
+ registerResource(options, handler, source = `dynamic resource "${options.name}"`) {
724
+ return this.#registerDynamic({
725
+ kind: "resource",
726
+ options
727
+ }, eraseHandler(handler), source, (next) => eraseHandler(next));
728
+ }
729
+ list() {
730
+ return this.#handlers.map((entry) => Object.freeze({
731
+ kind: entry.definition.kind,
732
+ name: entry.definition.options.name,
733
+ source: entry.source,
734
+ serverNames: Object.freeze([...this.#effectiveTargets(entry.definition)])
735
+ }));
736
+ }
737
+ /** Locks target validation to the runtimes declared by the root module. */
738
+ configureRuntimes(serverNames, gatewayNames = [], catalogRuntimeNames = []) {
739
+ if (this.#serverNames !== void 0) throw new McpModuleError("INVALID_OPTIONS", "MCP handler runtimes are already configured.");
740
+ this.#serverNames = normalizeRuntimeNames(serverNames);
741
+ this.#gatewayNames = new Set(normalizeRuntimeNames(gatewayNames));
742
+ this.#catalogRuntimeNames = new Set(normalizeRuntimeNames(catalogRuntimeNames));
743
+ for (const runtimeName of /* @__PURE__ */ new Set([...this.#gatewayNames, ...this.#catalogRuntimeNames])) if (!this.#serverNames.includes(runtimeName)) throw new McpModuleError("INVALID_OPTIONS", `MCP specialized runtime "${runtimeName}" is not a configured server.`);
744
+ for (const entry of this.#handlers) this.#assertKnownTargets(entry.definition, entry.source);
745
+ for (const runtimeName of this.#serverNames) this.assertNoCollisions(runtimeName);
746
+ }
747
+ /** Observes committed live mutations. The returned unsubscriber is idempotent. */
748
+ onMutation(observer) {
749
+ this.#assertOpen();
750
+ if (typeof observer !== "function") throw new TypeError("MCP capability mutation observer must be a function.");
751
+ this.#mutationObservers.add(observer);
752
+ return () => {
753
+ this.#mutationObservers.delete(observer);
754
+ };
755
+ }
756
+ /** Seals live mutation APIs and releases handler callbacks during application shutdown. */
757
+ close() {
758
+ if (this.#closed) return;
759
+ this.#closed = true;
760
+ this.#handlers = Object.freeze([]);
761
+ this.#mutationObservers.clear();
762
+ }
763
+ assertNoCollisions(runtimeName) {
764
+ const seen = /* @__PURE__ */ new Map();
765
+ for (const entry of this.#handlers) {
766
+ if (!targetsRuntime(entry.definition.options.servers, runtimeName)) continue;
767
+ this.#assertCatalogToolCompatibility(entry.definition, entry.source, runtimeName);
768
+ const key = registrationKey(entry.definition);
769
+ const previous = seen.get(key);
770
+ if (previous !== void 0) throw new McpModuleError("DUPLICATE_HANDLER", `Duplicate MCP ${entry.definition.kind} registration "${key}" for server "${runtimeName}" from ${previous} and ${entry.source}.`);
771
+ seen.set(key, entry.source);
772
+ }
773
+ }
774
+ /** Whether discovery found any decorated handler targeting one runtime. */
775
+ hasHandlersFor(runtimeName) {
776
+ return this.#handlers.some((entry) => targetsRuntime(entry.definition.options.servers, runtimeName));
777
+ }
778
+ asServerFeature(options) {
779
+ const visibilityTimeoutMs = normalizeVisibilityTimeout(options.visibilityTimeoutMs);
780
+ return async (server, context) => {
781
+ const visible = await selectVisibleHandlers(this.#handlers.filter((entry) => targetsRuntime(entry.definition.options.servers, context.runtimeName)), context, visibilityTimeoutMs);
782
+ const catalogRegistrations = [];
783
+ for (const entry of visible) {
784
+ const registration = registerHandler(server, entry, options, context.principal);
785
+ if (registration !== void 0 && entry.definition.kind === "tool") catalogRegistrations.push(Object.freeze({
786
+ name: entry.definition.options.name,
787
+ registration,
788
+ tags: entry.definition.options.tags ?? Object.freeze([])
789
+ }));
790
+ }
791
+ if (options.catalogExposure !== void 0) await applyMcpCatalogExposure(server, context, Object.freeze(catalogRegistrations), options.catalogExposure, visibilityTimeoutMs, (definition) => registerCatalogMetaTool(server, definition, options, context.principal));
792
+ };
793
+ }
794
+ #append(definition, handler, source, notify) {
795
+ this.#assertOpen();
796
+ const normalizedSource = normalizeSource(source);
797
+ const normalizedDefinition = freezeDefinition(definition);
798
+ this.#assertKnownTargets(normalizedDefinition, normalizedSource);
799
+ const entry = Object.freeze({
800
+ id: Symbol(normalizedSource),
801
+ definition: normalizedDefinition,
802
+ handler,
803
+ source: normalizedSource,
804
+ visibility: this.#resolveVisibility(normalizedDefinition, normalizedSource)
805
+ });
806
+ this.#assertNoEntryCollision(entry);
807
+ this.#handlers = Object.freeze([...this.#handlers, entry]);
808
+ if (notify) this.#notify(entry, "registered");
809
+ return entry;
810
+ }
811
+ #registerDynamic(definition, handler, source, eraseReplacement) {
812
+ this.#assertOpen();
813
+ if (this.#serverNames === void 0) throw new McpModuleError("RUNTIME_NOT_READY", "Dynamic MCP capabilities can be registered after application bootstrap configures runtimes.");
814
+ let current = this.#append(definition, handler, source, true);
815
+ let active = true;
816
+ return Object.freeze({
817
+ source: current.source,
818
+ replace: (nextHandler) => {
819
+ this.#assertOpen();
820
+ if (!active) return false;
821
+ const index = this.#handlers.findIndex((entry) => entry.id === current.id);
822
+ if (index === -1) {
823
+ active = false;
824
+ return false;
825
+ }
826
+ const replacement = Object.freeze({
827
+ ...current,
828
+ id: Symbol(current.source),
829
+ handler: eraseReplacement(nextHandler)
830
+ });
831
+ this.#handlers = Object.freeze([
832
+ ...this.#handlers.slice(0, index),
833
+ replacement,
834
+ ...this.#handlers.slice(index + 1)
835
+ ]);
836
+ current = replacement;
837
+ this.#notify(replacement, "replaced");
838
+ return true;
839
+ },
840
+ unregister: () => {
841
+ this.#assertOpen();
842
+ if (!active) return false;
843
+ const next = this.#handlers.filter((entry) => entry.id !== current.id);
844
+ if (next.length === this.#handlers.length) {
845
+ active = false;
846
+ return false;
847
+ }
848
+ this.#handlers = Object.freeze(next);
849
+ active = false;
850
+ this.#notify(current, "unregistered");
851
+ return true;
852
+ }
853
+ });
854
+ }
855
+ #assertOpen() {
856
+ if (!this.#closed) return;
857
+ throw new McpModuleError("RUNTIME_CLOSED", "MCP capabilities cannot be mutated after the Nest runtime begins shutdown.");
858
+ }
859
+ #resolveVisibility(definition, source) {
860
+ const visibility = definition.options.visibility;
861
+ if (visibility === void 0 || typeof visibility === "boolean") return visibility;
862
+ if (!isMcpRuntimeProviderToken(visibility)) throw new McpModuleError("INVALID_VISIBILITY_POLICY", `MCP handler ${source} visibility must be a boolean or collaborator provider token.`);
863
+ try {
864
+ const policy = this.providers.get(visibility);
865
+ if (!isCapabilityVisibilityPolicy(policy)) throw new TypeError("resolved provider does not implement isVisible(context)");
866
+ return policy;
867
+ } catch (cause) {
868
+ throw new McpModuleError("INVALID_VISIBILITY_POLICY", `MCP handler ${source} visibility policy ${mcpProviderTokenName(visibility)} must be a registered singleton collaborator provider.`, { cause });
869
+ }
870
+ }
871
+ #assertKnownTargets(definition, source) {
872
+ if (this.#serverNames === void 0) return;
873
+ for (const target of explicitTargets(definition.options.servers)) if (!this.#serverNames.includes(target)) throw new McpModuleError("UNKNOWN_SERVER_TARGET", `MCP handler ${source} targets unknown server "${target}".`);
874
+ }
875
+ #assertNoEntryCollision(candidate) {
876
+ if (this.#serverNames === void 0) return;
877
+ const candidateTargets = this.#effectiveTargets(candidate.definition);
878
+ for (const gatewayName of candidateTargets) if (this.#gatewayNames.has(gatewayName)) throw new McpModuleError("INVALID_OPTIONS", `MCP gateway server "${gatewayName}" must be dedicated and cannot also host decorated or dynamic tools, prompts, or resources.`);
879
+ for (const runtimeName of candidateTargets) this.#assertCatalogToolCompatibility(candidate.definition, candidate.source, runtimeName);
880
+ const key = registrationKey(candidate.definition);
881
+ for (const entry of this.#handlers) {
882
+ if (registrationKey(entry.definition) !== key) continue;
883
+ const existingTargets = this.#effectiveTargets(entry.definition);
884
+ const collision = candidateTargets.find((target) => existingTargets.includes(target));
885
+ if (collision !== void 0) throw new McpModuleError("DUPLICATE_HANDLER", `Duplicate MCP ${candidate.definition.kind} registration "${key}" for server "${collision}" from ${entry.source} and ${candidate.source}.`);
886
+ }
887
+ }
888
+ #effectiveTargets(definition) {
889
+ return definition.options.servers === void 0 ? this.#serverNames ?? [] : explicitTargets(definition.options.servers);
890
+ }
891
+ #notify(entry, type) {
892
+ const mutation = Object.freeze({
893
+ kind: entry.definition.kind,
894
+ type,
895
+ source: entry.source,
896
+ serverNames: Object.freeze([...this.#effectiveTargets(entry.definition)])
897
+ });
898
+ for (const observer of this.#mutationObservers) try {
899
+ const result = observer(mutation);
900
+ Promise.resolve(result).catch(() => void 0);
901
+ } catch {}
902
+ }
903
+ #assertCatalogToolCompatibility(definition, source, runtimeName) {
904
+ if (definition.kind !== "tool" || !this.#catalogRuntimeNames.has(runtimeName)) return;
905
+ if (definition.options.name.length > 128) throw new McpModuleError("INVALID_CATALOG_EXPOSURE", `MCP tool "${definition.options.name}" from ${source} exceeds the ${String(128)} character catalog name limit on server "${runtimeName}".`);
906
+ if (definition.options.name !== "nest-mcp.catalog.search" && definition.options.name !== "nest-mcp.catalog.schemas") return;
907
+ throw new McpModuleError("DUPLICATE_HANDLER", `MCP tool "${definition.options.name}" from ${source} collides with a reserved catalog meta-tool on server "${runtimeName}".`);
908
+ }
909
+ };
910
+ McpHandlerRegistry = __decorate([Injectable(), __decorateMetadata("design:paramtypes", [typeof McpProviderRegistry === "undefined" ? Object : McpProviderRegistry])], McpHandlerRegistry);
911
+ function isCapabilityVisibilityPolicy(value) {
912
+ return typeof value === "object" && value !== null && typeof Reflect.get(value, "isVisible") === "function";
913
+ }
914
+ async function selectVisibleHandlers(handlers, context, timeoutMs) {
915
+ const policies = /* @__PURE__ */ new Set();
916
+ for (const entry of handlers) if (typeof entry.visibility === "object") policies.add(entry.visibility);
917
+ const byPolicy = await withDeadline(Promise.all([...policies].map(async (policy) => {
918
+ let visible;
919
+ try {
920
+ visible = await policy.isVisible(context);
921
+ } catch (cause) {
922
+ throw visibilityError(policy, context.runtimeName, "threw or rejected", cause);
923
+ }
924
+ if (typeof visible !== "boolean") throw visibilityError(policy, context.runtimeName, `returned ${typeof visible} instead of boolean`);
925
+ return [policy, visible];
926
+ })).then((entries) => new Map(entries)), timeoutMs, context.requestInfo?.signal, `MCP visibility evaluation for server "${context.runtimeName}"`);
927
+ return handlers.filter((entry) => {
928
+ if (entry.visibility === false) return false;
929
+ if (entry.visibility === true || entry.visibility === void 0) return true;
930
+ return byPolicy.get(entry.visibility) === true;
931
+ });
932
+ }
933
+ function visibilityError(policy, runtimeName, detail, cause) {
934
+ return new McpModuleError("INVALID_VISIBILITY_POLICY", `MCP visibility policy ${policy.constructor.name || "<anonymous>"} ${detail} for server "${runtimeName}".`, cause === void 0 ? void 0 : { cause });
935
+ }
936
+ function withDeadline(task, timeoutMs, signal, label) {
937
+ return new Promise((resolve, reject) => {
938
+ let settled = false;
939
+ const finish = (callback) => {
940
+ if (settled) return;
941
+ settled = true;
942
+ clearTimeout(timer);
943
+ signal?.removeEventListener("abort", onAbort);
944
+ callback();
945
+ };
946
+ const onAbort = () => {
947
+ finish(() => reject(signal?.reason ?? new DOMException(`${label} aborted.`, "AbortError")));
948
+ };
949
+ const timer = setTimeout(() => {
950
+ finish(() => reject(new McpModuleError("INVALID_VISIBILITY_POLICY", `${label} exceeded its ${String(timeoutMs)}ms deadline.`)));
951
+ }, timeoutMs);
952
+ task.then((value) => finish(() => resolve(value)), (error) => finish(() => reject(error)));
953
+ if (signal?.aborted === true) onAbort();
954
+ else signal?.addEventListener("abort", onAbort, { once: true });
955
+ });
956
+ }
957
+ function normalizeVisibilityTimeout(value) {
958
+ const timeout = value ?? DEFAULT_VISIBILITY_TIMEOUT_MS;
959
+ if (!Number.isSafeInteger(timeout) || timeout <= 0) throw new McpModuleError("INVALID_OPTIONS", "MCP handlerVisibilityTimeoutMs must be a positive safe integer.");
960
+ return timeout;
961
+ }
962
+ function normalizeRuntimeNames(names) {
963
+ const normalized = names.map((name, index) => {
964
+ if (typeof name !== "string" || name.trim().length === 0) throw new McpModuleError("INVALID_OPTIONS", `MCP runtime name at index ${String(index)} must be a non-empty string.`);
965
+ return name.trim();
966
+ });
967
+ if (new Set(normalized).size !== normalized.length) throw new McpModuleError("INVALID_OPTIONS", "MCP runtime names must be unique.");
968
+ return Object.freeze(normalized);
969
+ }
970
+ function normalizeSource(source) {
971
+ if (typeof source !== "string" || source.trim().length === 0) throw new McpModuleError("INVALID_HANDLER", "MCP handler source must be a non-empty string.");
972
+ return source.trim();
973
+ }
974
+ function explicitTargets(targets) {
975
+ if (targets === void 0) return [];
976
+ return typeof targets === "string" ? [targets] : targets;
977
+ }
978
+ function targetsRuntime(targets, runtimeName) {
979
+ return targets === void 0 || (typeof targets === "string" ? targets === runtimeName : targets.includes(runtimeName));
980
+ }
981
+ function registrationKey(definition) {
982
+ if (definition.kind === "resource" && typeof definition.options.uri === "string") return `${definition.kind}:${definition.options.uri}`;
983
+ return `${definition.kind}:${definition.options.name}`;
984
+ }
985
+ function freezeDefinition(definition) {
986
+ if (typeof definition.options.name !== "string" || definition.options.name.trim().length === 0) throw new McpModuleError("INVALID_HANDLER", `MCP ${definition.kind} name must be a non-empty string.`);
987
+ const targets = definition.options.servers;
988
+ const frozenTargets = targets === void 0 ? {} : { servers: normalizeHandlerTargets(targets) };
989
+ if (definition.kind === "tool") {
990
+ const { tags, annotations, icons, _meta: meta, ...sdkOptions } = definition.options;
991
+ const normalizedTags = normalizeToolTags(tags);
992
+ return Object.freeze({
993
+ kind: "tool",
994
+ options: Object.freeze({
995
+ ...sdkOptions,
996
+ ...frozenTargets,
997
+ ...annotations === void 0 ? {} : { annotations: snapshotDefinitionMetadata(annotations, `MCP tool "${definition.options.name}" annotations`) },
998
+ ...icons === void 0 ? {} : { icons: snapshotDefinitionMetadata(icons, `MCP tool "${definition.options.name}" icons`) },
999
+ ...meta === void 0 ? {} : { _meta: snapshotDefinitionMetadata(meta, `MCP tool "${definition.options.name}" metadata`) },
1000
+ ...normalizedTags === void 0 ? {} : { tags: normalizedTags }
1001
+ })
1002
+ });
1003
+ }
1004
+ if (definition.kind === "prompt") return Object.freeze({
1005
+ kind: "prompt",
1006
+ options: Object.freeze({
1007
+ ...definition.options,
1008
+ ...frozenTargets
1009
+ })
1010
+ });
1011
+ return Object.freeze({
1012
+ kind: "resource",
1013
+ options: Object.freeze({
1014
+ ...definition.options,
1015
+ ...frozenTargets
1016
+ })
1017
+ });
1018
+ }
1019
+ function normalizeToolTags(tags) {
1020
+ if (tags === void 0) return void 0;
1021
+ if (!Array.isArray(tags) || tags.length > 32) throw new McpModuleError("INVALID_OPTIONS", "MCP tool tags must be an array containing at most 32 entries.");
1022
+ const normalized = tags.map((tag, index) => {
1023
+ if (typeof tag !== "string" || tag.trim().length === 0 || tag.trim().length > 64) throw new McpModuleError("INVALID_OPTIONS", `MCP tool tag at index ${String(index)} must contain between 1 and 64 characters.`);
1024
+ return tag.trim();
1025
+ });
1026
+ if (new Set(normalized).size !== normalized.length) throw new McpModuleError("INVALID_OPTIONS", "MCP tool tags must not contain duplicates.");
1027
+ return Object.freeze(normalized);
1028
+ }
1029
+ function snapshotDefinitionMetadata(value, label) {
1030
+ let snapshot;
1031
+ try {
1032
+ snapshot = structuredClone(value);
1033
+ } catch (cause) {
1034
+ throw new McpModuleError("INVALID_OPTIONS", `${label} must be safely detachable.`, { cause });
1035
+ }
1036
+ freezePolicyValue(snapshot);
1037
+ return snapshot;
1038
+ }
1039
+ function normalizeHandlerTargets(targets) {
1040
+ const values = typeof targets === "string" ? [targets] : targets;
1041
+ if (!Array.isArray(values) || values.length === 0) throw new McpModuleError("INVALID_OPTIONS", "MCP handler targets must contain at least one server name.");
1042
+ const normalized = values.map((target, index) => {
1043
+ if (typeof target !== "string" || target.trim().length === 0) throw new McpModuleError("INVALID_OPTIONS", `MCP handler target at index ${String(index)} must be a non-empty string.`);
1044
+ return target.trim();
1045
+ });
1046
+ if (new Set(normalized).size !== normalized.length) throw new McpModuleError("INVALID_OPTIONS", "MCP handler targets must not contain duplicates.");
1047
+ return typeof targets === "string" ? normalized[0] : Object.freeze(normalized);
1048
+ }
1049
+ function eraseHandler(handler) {
1050
+ if (typeof handler !== "function") throw new McpModuleError("INVALID_HANDLER", "Dynamic MCP handler must be callable.");
1051
+ return (...arguments_) => Reflect.apply(handler, void 0, arguments_);
1052
+ }
1053
+ function registerHandler(server, entry, options, principal) {
1054
+ const callback = (...arguments_) => invokeHandler(entry, arguments_, options, principal);
1055
+ if (entry.definition.kind === "tool") {
1056
+ const { name, servers: _servers, visibility: _visibility, tags: _tags, ...config } = entry.definition.options;
1057
+ const registerTool = server.registerTool.bind(server);
1058
+ const registration = Reflect.apply(registerTool, void 0, [
1059
+ name,
1060
+ config,
1061
+ callback
1062
+ ]);
1063
+ if (!isRegisteredTool(registration)) throw new McpModuleError("INVALID_HANDLER", `MCP tool ${entry.source} did not produce an official registration handle.`);
1064
+ return registration;
1065
+ }
1066
+ if (entry.definition.kind === "prompt") {
1067
+ const { name, servers: _servers, visibility: _visibility, ...config } = entry.definition.options;
1068
+ const registerPrompt = server.registerPrompt.bind(server);
1069
+ Reflect.apply(registerPrompt, void 0, [
1070
+ name,
1071
+ config,
1072
+ callback
1073
+ ]);
1074
+ return;
1075
+ }
1076
+ const { name, uri, servers: _servers, visibility: _visibility, ...config } = entry.definition.options;
1077
+ const registerResource = server.registerResource.bind(server);
1078
+ Reflect.apply(registerResource, void 0, [
1079
+ name,
1080
+ uri,
1081
+ config,
1082
+ callback
1083
+ ]);
1084
+ }
1085
+ function isRegisteredTool(value) {
1086
+ return typeof value === "object" && value !== null && "enabled" in value && typeof value.enabled === "boolean" && "update" in value && typeof value.update === "function" && "enable" in value && typeof value.enable === "function" && "disable" in value && typeof value.disable === "function";
1087
+ }
1088
+ function registerCatalogMetaTool(server, definition, options, principal) {
1089
+ const source = `catalog meta-tool "${definition.name}"`;
1090
+ const registration = registerHandler(server, Object.freeze({
1091
+ id: Symbol(source),
1092
+ definition: freezeDefinition({
1093
+ kind: "tool",
1094
+ options: {
1095
+ name: definition.name,
1096
+ title: definition.title,
1097
+ description: definition.description,
1098
+ inputSchema: definition.inputSchema,
1099
+ outputSchema: definition.outputSchema
1100
+ }
1101
+ }),
1102
+ handler: eraseHandler(definition.handler),
1103
+ source,
1104
+ visibility: true
1105
+ }), options, principal);
1106
+ if (registration === void 0) throw new McpModuleError("INVALID_CATALOG_EXPOSURE", `MCP catalog meta-tool "${definition.name}" did not produce a tool registration.`);
1107
+ return registration;
1108
+ }
1109
+ async function invokeHandler(entry, callbackArguments, options, principal) {
1110
+ const sdkContext = callbackArguments.at(-1);
1111
+ if (!isServerContext(sdkContext)) throw new McpModuleError("INVALID_HANDLER", `MCP ${entry.definition.kind} handler ${entry.source} received no official server context.`);
1112
+ const input = Object.freeze({
1113
+ kind: entry.definition.kind,
1114
+ name: entry.definition.options.name,
1115
+ serverName: options.serverName,
1116
+ source: entry.source,
1117
+ arguments: snapshotHandlerArguments(callbackArguments.slice(0, -1))
1118
+ });
1119
+ const requestId = String(sdkContext.mcpReq.id);
1120
+ const context = createMcpOperationContext({
1121
+ operationId: crypto.randomUUID(),
1122
+ role: "server",
1123
+ operation: {
1124
+ name: sdkContext.mcpReq.method,
1125
+ kind: "request",
1126
+ capability: capability(entry.definition.kind),
1127
+ target: options.serverName,
1128
+ attributes: {
1129
+ "mcp.handler.kind": entry.definition.kind,
1130
+ "mcp.handler.name": entry.definition.options.name,
1131
+ "mcp.transport": sdkContext.http?.req === void 0 ? "stdio" : "http"
1132
+ }
1133
+ },
1134
+ signal: sdkContext.mcpReq.signal,
1135
+ requestId,
1136
+ ...sdkContext.sessionId === void 0 ? {} : { sessionId: sdkContext.sessionId },
1137
+ ...principal === void 0 ? {} : { principal }
1138
+ });
1139
+ const operation = createMcpOperation(input, context);
1140
+ const terminal = () => entry.handler(...callbackArguments);
1141
+ const middleware = [];
1142
+ if (options.lifecycleObserver !== void 0) middleware.push(createMcpLifecycleMiddleware(options.lifecycleObserver));
1143
+ if (options.authorization !== void 0) middleware.push(createMcpAuthorizationMiddleware(options.authorization));
1144
+ middleware.push(...options.middleware ?? []);
1145
+ return composeMcpMiddleware(middleware, terminal)(operation);
1146
+ }
1147
+ function snapshotHandlerArguments(values) {
1148
+ return Object.freeze(values.map((value) => {
1149
+ let clone;
1150
+ try {
1151
+ clone = value instanceof URL ? new URL(value.href) : structuredClone(value);
1152
+ } catch (cause) {
1153
+ throw new McpModuleError("INVALID_HANDLER", "Validated MCP handler arguments must be snapshot-safe before authorization.", { cause });
1154
+ }
1155
+ return freezePolicyValue(clone);
1156
+ }));
1157
+ }
1158
+ function freezePolicyValue(value) {
1159
+ if (Array.isArray(value)) {
1160
+ for (const entry of value) freezePolicyValue(entry);
1161
+ return Object.freeze(value);
1162
+ }
1163
+ if (isPlainRecord(value)) {
1164
+ for (const entry of Object.values(value)) freezePolicyValue(entry);
1165
+ return Object.freeze(value);
1166
+ }
1167
+ return value;
1168
+ }
1169
+ function isPlainRecord(value) {
1170
+ if (typeof value !== "object" || value === null) return false;
1171
+ const prototype = Object.getPrototypeOf(value);
1172
+ return prototype === Object.prototype || prototype === null;
1173
+ }
1174
+ function isServerContext(value) {
1175
+ if (typeof value !== "object" || value === null || !("mcpReq" in value)) return false;
1176
+ const request = value.mcpReq;
1177
+ return typeof request === "object" && request !== null && "id" in request && "method" in request && typeof request.method === "string" && "signal" in request && request.signal instanceof AbortSignal;
1178
+ }
1179
+ function capability(kind) {
1180
+ if (kind === "tool") return "tools";
1181
+ if (kind === "resource") return "resources";
1182
+ return "prompts";
1183
+ }
1184
+ //#endregion
1185
+ //#region src/mcp-capabilities.service.ts
1186
+ let McpCapabilitiesService = class McpCapabilitiesService {
1187
+ registry;
1188
+ constructor(registry) {
1189
+ this.registry = registry;
1190
+ }
1191
+ list() {
1192
+ return this.registry.list();
1193
+ }
1194
+ registerTool(options, handler, source) {
1195
+ return this.registry.registerTool(options, handler, source);
1196
+ }
1197
+ registerPrompt(options, handler, source) {
1198
+ return this.registry.registerPrompt(options, handler, source);
1199
+ }
1200
+ registerResource(options, handler, source) {
1201
+ return this.registry.registerResource(options, handler, source);
1202
+ }
1203
+ onMutation(observer) {
1204
+ return this.registry.onMutation(observer);
1205
+ }
1206
+ };
1207
+ McpCapabilitiesService = __decorate([Injectable(), __decorateMetadata("design:paramtypes", [typeof McpHandlerRegistry === "undefined" ? Object : McpHandlerRegistry])], McpCapabilitiesService);
1208
+ //#endregion
1209
+ //#region src/discovery/mcp-handler.explorer.ts
1210
+ let McpHandlerExplorer = class McpHandlerExplorer {
1211
+ discovery;
1212
+ metadataScanner;
1213
+ reflector;
1214
+ registry;
1215
+ #scanned = false;
1216
+ constructor(discovery, metadataScanner, reflector, registry) {
1217
+ this.discovery = discovery;
1218
+ this.metadataScanner = metadataScanner;
1219
+ this.reflector = reflector;
1220
+ this.registry = registry;
1221
+ }
1222
+ assertSingleRoot() {
1223
+ if (this.discovery.getProviders().filter(({ token }) => token === McpHandlerRegistry).length === 1) return;
1224
+ throw new McpModuleError("INVALID_OPTIONS", "McpModule.forRoot() or forRootAsync() must be imported exactly once per Nest application. Configure every inbound MCP server in that shared root and import one McpClientModule when named upstreams are needed.");
1225
+ }
1226
+ scan() {
1227
+ if (this.#scanned) return;
1228
+ this.#scanned = true;
1229
+ for (const wrapper of this.discovery.getProviders()) {
1230
+ const metatype = wrapper.metatype;
1231
+ if (metatype?.prototype === void 0) continue;
1232
+ const classTargets = this.reflector.get(MCP_TARGETS_METADATA, metatype);
1233
+ for (const methodName of this.metadataScanner.getAllMethodNames(metatype.prototype)) {
1234
+ const prototypeMethod = metatype.prototype[methodName];
1235
+ if (typeof prototypeMethod !== "function") continue;
1236
+ const definition = this.reflector.get(MCP_HANDLER_METADATA, prototypeMethod);
1237
+ if (definition === void 0) continue;
1238
+ if (wrapper.scope !== void 0 && wrapper.scope !== Scope.DEFAULT || !wrapper.isDependencyTreeStatic()) throw new McpModuleError("INVALID_SCOPE", `Decorated MCP handler ${metatype.name}.${methodName} must belong to a singleton provider with a static dependency tree.`);
1239
+ const instance = wrapper.instance;
1240
+ if (typeof instance !== "object" || instance === null) throw new McpModuleError("INVALID_SCOPE", `Decorated MCP handler ${metatype.name}.${methodName} must belong to a singleton provider.`);
1241
+ const method = Reflect.get(instance, methodName);
1242
+ if (typeof method !== "function") throw new McpModuleError("INVALID_HANDLER", `Decorated MCP handler ${metatype.name}.${methodName} is not callable.`);
1243
+ this.registry.register(withDefaultTargets(definition, classTargets), (...arguments_) => Reflect.apply(method, instance, arguments_), `${metatype.name}.${methodName}`);
1244
+ }
1245
+ }
1246
+ }
1247
+ };
1248
+ McpHandlerExplorer = __decorate([Injectable(), __decorateMetadata("design:paramtypes", [
1249
+ typeof DiscoveryService === "undefined" ? Object : DiscoveryService,
1250
+ typeof MetadataScanner === "undefined" ? Object : MetadataScanner,
1251
+ typeof Reflector === "undefined" ? Object : Reflector,
1252
+ typeof McpHandlerRegistry === "undefined" ? Object : McpHandlerRegistry
1253
+ ])], McpHandlerExplorer);
1254
+ function withDefaultTargets(definition, classTargets) {
1255
+ if (definition.options.servers !== void 0 || classTargets === void 0) return definition;
1256
+ if (definition.kind === "tool") return Object.freeze({
1257
+ kind: "tool",
1258
+ options: Object.freeze({
1259
+ ...definition.options,
1260
+ servers: classTargets
1261
+ })
1262
+ });
1263
+ if (definition.kind === "prompt") return Object.freeze({
1264
+ kind: "prompt",
1265
+ options: Object.freeze({
1266
+ ...definition.options,
1267
+ servers: classTargets
1268
+ })
1269
+ });
1270
+ return Object.freeze({
1271
+ kind: "resource",
1272
+ options: Object.freeze({
1273
+ ...definition.options,
1274
+ servers: classTargets
1275
+ })
1276
+ });
1277
+ }
1278
+ //#endregion
1279
+ //#region src/server/provider-resolution.ts
1280
+ function requireProvider(providers, token) {
1281
+ const provider = providers.get(token);
1282
+ if (typeof provider !== "object" && typeof provider !== "function" || provider === null) throw new McpModuleError("INVALID_OPTIONS", `MCP server collaborator ${mcpProviderTokenName(token)} must be listed in McpModule collaborators.providers.`);
1283
+ return provider;
1284
+ }
1285
+ function requireMethodProvider(providers, token, methods) {
1286
+ const provider = requireProvider(providers, token);
1287
+ const requiredMethods = Array.isArray(methods) ? methods : [methods];
1288
+ if (requiredMethods.some((method) => typeof Reflect.get(provider, method) !== "function")) throw new McpModuleError("INVALID_OPTIONS", `MCP server collaborator ${mcpProviderTokenName(token)} must implement ${requiredMethods.map((method) => `${String(method)}()`).join(", ")}.`);
1289
+ return provider;
1290
+ }
1291
+ function bindProviderMethod(providers, token, method) {
1292
+ const provider = requireMethodProvider(providers, token, method);
1293
+ return provider[method].bind(provider);
1294
+ }
1295
+ function discardProperties(value, properties) {
1296
+ for (const property of properties) Reflect.deleteProperty(value, property);
1297
+ }
1298
+ //#endregion
1299
+ //#region src/server/mcp-server-options.ts
1300
+ function resolveMcpNestServerOptions(options, providers) {
1301
+ if (options === void 0) return void 0;
1302
+ const { jsonSchemaValidator, requestState, ...data } = options;
1303
+ return {
1304
+ ...data,
1305
+ ...jsonSchemaValidator === void 0 ? {} : { jsonSchemaValidator: requireMethodProvider(providers, jsonSchemaValidator, "getValidator") },
1306
+ ...requestState === void 0 ? {} : { requestState: requestState.verifier === void 0 ? {} : { verify: bindProviderMethod(providers, requestState.verifier, "verify") } }
1307
+ };
1308
+ }
1309
+ function resolveMcpNestServerHttpOptions(options, providers) {
1310
+ if (options === void 0) return void 0;
1311
+ const { eventBus, ...data } = options;
1312
+ discardProperties(data, ["bus", "onerror"]);
1313
+ return {
1314
+ ...data,
1315
+ ...eventBus === void 0 ? {} : { bus: requireMethodProvider(providers, eventBus, ["publish", "subscribe"]) }
1316
+ };
1317
+ }
1318
+ //#endregion
1319
+ //#region src/oauth/mcp-oauth-options.ts
1320
+ /**
1321
+ * Resolves the `oauth` group into a composition function (and, for the proxy,
1322
+ * the `McpOAuthProxy` instance). Returns `undefined` when nothing is configured.
1323
+ */
1324
+ function resolveMcpNestServerOAuth(options, providers, serverName) {
1325
+ if (options === void 0) return void 0;
1326
+ if (options.proxy !== void 0 && options.resource !== void 0) throw new McpModuleError("INVALID_OPTIONS", `MCP server "${serverName}" configures both oauth.proxy and oauth.resource; the proxy already protects the resource. Configure exactly one.`);
1327
+ if (options.proxy !== void 0) return resolveProxy(options, providers, serverName);
1328
+ if (options.resource !== void 0) {
1329
+ const compose = resolveResource(options, providers, serverName);
1330
+ return compose === void 0 ? void 0 : { compose };
1331
+ }
1332
+ }
1333
+ function resolveProxy(options, providers, serverName) {
1334
+ const proxyOptions = options.proxy;
1335
+ if (proxyOptions === void 0) throw new McpModuleError("INVALID_OPTIONS", `MCP server "${serverName}" is missing oauth.proxy.`);
1336
+ if (typeof proxyOptions.issuer !== "string" || proxyOptions.issuer.length === 0) throw new McpModuleError("INVALID_OPTIONS", `MCP server "${serverName}" oauth.proxy.issuer must be a non-empty string.`);
1337
+ const primaryResource = proxyOptions.resources?.[0];
1338
+ if (!Array.isArray(proxyOptions.resources) || proxyOptions.resources.length === 0 || typeof primaryResource !== "string") throw new McpModuleError("INVALID_OPTIONS", `MCP server "${serverName}" oauth.proxy.resources must list at least one resource URL.`);
1339
+ const signingKeys = requireMethodProvider(providers, proxyOptions.signingKeys, "getSigningKeys").getSigningKeys();
1340
+ const masterSecret = requireMethodProvider(providers, proxyOptions.secret, "getMasterSecret").getMasterSecret();
1341
+ const upstreamConfig = requireMethodProvider(providers, proxyOptions.upstream, "getUpstream").getUpstream();
1342
+ const stateStore = requireMethodProvider(providers, proxyOptions.stateStore, "take");
1343
+ const tokenStore = proxyOptions.tokenStore === void 0 ? void 0 : requireMethodProvider(providers, proxyOptions.tokenStore, "take");
1344
+ const clientResolver = proxyOptions.clientResolver === void 0 ? void 0 : requireMethodProvider(providers, proxyOptions.clientResolver, "resolveClient");
1345
+ const consentRenderer = proxyOptions.consent === void 0 ? void 0 : requireMethodProvider(providers, proxyOptions.consent, "render").render;
1346
+ const subjectResolver = proxyOptions.subjectResolver === void 0 ? void 0 : requireMethodProvider(providers, proxyOptions.subjectResolver, "resolveSubject").resolveSubject;
1347
+ const anonymousProvider = proxyOptions.anonymous === void 0 ? void 0 : requireMethodProvider(providers, proxyOptions.anonymous, "permit");
1348
+ const guardedFetch = proxyOptions.fetch === void 0 ? void 0 : requireMethodProvider(providers, proxyOptions.fetch, "fetch").fetch;
1349
+ const cimd = proxyOptions.cimd?.enabled === true ? createMcpClientIdMetadataResolver({
1350
+ ...proxyOptions.cimd.allowedHosts === void 0 ? {} : { allowedHosts: proxyOptions.cimd.allowedHosts },
1351
+ ...proxyOptions.cimd.maxDocumentBytes === void 0 ? {} : { maxDocumentBytes: proxyOptions.cimd.maxDocumentBytes },
1352
+ ...proxyOptions.cimd.fetchTimeoutMs === void 0 ? {} : { fetchTimeoutMs: proxyOptions.cimd.fetchTimeoutMs }
1353
+ }) : void 0;
1354
+ const upstream = new McpUpstreamAdapter({
1355
+ upstream: upstreamConfig,
1356
+ ...guardedFetch === void 0 ? {} : { fetch: guardedFetch }
1357
+ });
1358
+ const proxyConstructorOptions = {
1359
+ issuer: proxyOptions.issuer,
1360
+ resources: proxyOptions.resources,
1361
+ signingKeys,
1362
+ secrets: new McpOAuthSecretKeyring(masterSecret),
1363
+ upstream,
1364
+ stateStore,
1365
+ ...proxyOptions.basePath === void 0 ? {} : { basePath: proxyOptions.basePath },
1366
+ ...proxyOptions.scopesSupported === void 0 ? {} : { scopesSupported: proxyOptions.scopesSupported },
1367
+ ...tokenStore === void 0 ? {} : { tokenStore },
1368
+ ...cimd === void 0 ? {} : { cimd },
1369
+ ...clientResolver === void 0 ? {} : { clientResolver },
1370
+ ...consentRenderer === void 0 ? {} : { consentRenderer },
1371
+ ...subjectResolver === void 0 ? {} : { resolveUpstreamSubject: subjectResolver },
1372
+ ...proxyOptions.ttl === void 0 ? {} : { ttl: proxyOptions.ttl }
1373
+ };
1374
+ const proxy = new McpOAuthProxy(proxyConstructorOptions);
1375
+ const resourceMetadataUrl = new URL("/.well-known/oauth-protected-resource", proxyOptions.issuer).href;
1376
+ const resourceServerOptions = {
1377
+ bearerAuth: {
1378
+ verifier: proxy.verifier,
1379
+ resourceMetadataUrl,
1380
+ ...proxyOptions.requiredScopes === void 0 ? {} : { requiredScopes: [...proxyOptions.requiredScopes] }
1381
+ },
1382
+ metadata: {
1383
+ oauthMetadata: proxy.authorizationServerMetadata,
1384
+ resourceServerUrl: new URL(primaryResource)
1385
+ },
1386
+ ...anonymousProvider === void 0 ? {} : { anonymous: async (request) => anonymousProvider.permit(request) }
1387
+ };
1388
+ const compose = (handler) => new McpOAuthServer(new McpResourceServer(handler, resourceServerOptions), {
1389
+ proxy,
1390
+ ...proxyOptions.basePath === void 0 ? {} : { basePath: proxyOptions.basePath }
1391
+ });
1392
+ return {
1393
+ compose,
1394
+ proxy
1395
+ };
1396
+ }
1397
+ function resolveResource(options, providers, serverName) {
1398
+ const resource = options.resource;
1399
+ if (resource === void 0) return void 0;
1400
+ if (typeof resource.resourceServerUrl !== "string" || resource.resourceServerUrl.length === 0) throw new McpModuleError("INVALID_OPTIONS", `MCP server "${serverName}" oauth.resource.resourceServerUrl must be a non-empty URL string.`);
1401
+ let resourceServerUrl;
1402
+ try {
1403
+ resourceServerUrl = new URL(resource.resourceServerUrl);
1404
+ } catch {
1405
+ throw new McpModuleError("INVALID_OPTIONS", `MCP server "${serverName}" oauth.resource.resourceServerUrl must be a valid URL.`);
1406
+ }
1407
+ const verifier = requireMethodProvider(providers, resource.verifier, "verifyAccessToken");
1408
+ const anonymousProvider = resource.anonymous === void 0 ? void 0 : requireMethodProvider(providers, resource.anonymous, "permit");
1409
+ const resourceServerOptions = {
1410
+ bearerAuth: {
1411
+ verifier,
1412
+ ...resource.requiredScopes === void 0 ? {} : { requiredScopes: [...resource.requiredScopes] }
1413
+ },
1414
+ ...resource.metadata === void 0 ? {} : { metadata: {
1415
+ oauthMetadata: resource.metadata.oauthMetadata,
1416
+ resourceServerUrl,
1417
+ ...resource.metadata.serviceDocumentationUrl === void 0 ? {} : { serviceDocumentationUrl: new URL(resource.metadata.serviceDocumentationUrl) },
1418
+ ...resource.metadata.scopesSupported === void 0 ? {} : { scopesSupported: [...resource.metadata.scopesSupported] },
1419
+ ...resource.metadata.resourceName === void 0 ? {} : { resourceName: resource.metadata.resourceName }
1420
+ } },
1421
+ ...anonymousProvider === void 0 ? {} : { anonymous: async (request) => anonymousProvider.permit(request) }
1422
+ };
1423
+ return (handler) => new McpResourceServer(handler, resourceServerOptions);
1424
+ }
1425
+ //#endregion
1426
+ //#region src/mcp-runtime.service.ts
1427
+ let McpRuntimeService = class McpRuntimeService {
1428
+ options;
1429
+ clientService;
1430
+ servers;
1431
+ explorer;
1432
+ handlerRegistry;
1433
+ capabilities;
1434
+ providers;
1435
+ #ready = false;
1436
+ #gateways = /* @__PURE__ */ new Map();
1437
+ #httpComposers = /* @__PURE__ */ new Map();
1438
+ #oauthProxies = /* @__PURE__ */ new Map();
1439
+ #closeTask;
1440
+ #shutdownError;
1441
+ #unsubscribeCapabilityMutations;
1442
+ constructor(options, clientService, servers, explorer, handlerRegistry, capabilities, providers) {
1443
+ this.options = options;
1444
+ this.clientService = clientService;
1445
+ this.servers = servers;
1446
+ this.explorer = explorer;
1447
+ this.handlerRegistry = handlerRegistry;
1448
+ this.capabilities = capabilities;
1449
+ this.providers = providers;
1450
+ }
1451
+ async onApplicationBootstrap() {
1452
+ try {
1453
+ this.explorer.assertSingleRoot();
1454
+ if (this.options.autoDiscover !== false) this.explorer.scan();
1455
+ const definitions = this.options.servers ?? [];
1456
+ for (const definition of definitions) {
1457
+ if (definition.catalogExposure === void 0) continue;
1458
+ if (typeof definition.catalogExposure !== "object" || definition.catalogExposure === null || definition.catalogExposure.policy === void 0) throw new McpModuleError("INVALID_CATALOG_EXPOSURE", `MCP catalog exposure for server "${definition.name}" requires a policy provider token.`);
1459
+ if (definition.gateway !== void 0) throw new McpModuleError("INVALID_CATALOG_EXPOSURE", `MCP catalog exposure cannot be combined with gateway server "${definition.name}".`);
1460
+ if ((definition.contributors?.length ?? 0) > 0) throw new McpModuleError("INVALID_CATALOG_EXPOSURE", `MCP catalog exposure for server "${definition.name}" cannot safely project tools from custom contributors. Register cataloged tools through decorators or McpCapabilitiesService.`);
1461
+ }
1462
+ this.handlerRegistry.configureRuntimes(definitions.map(({ name }) => name), definitions.flatMap(({ name, gateway }) => gateway === void 0 || gateway.composition === "tools" ? [] : [name]), definitions.flatMap(({ name, catalogExposure }) => catalogExposure === void 0 ? [] : [name]));
1463
+ const oauthRouteOwners = /* @__PURE__ */ new Map();
1464
+ for (const definition of definitions) {
1465
+ const { catalogExposure, contributors: contributorTokens, gateway, handlerAuthorization: handlerAuthorizationToken, handlerLifecycleObserver: handlerLifecycleObserverToken, handlerMiddleware: handlerMiddlewareTokens, handlerVisibilityTimeoutMs, http: httpOptions, lifecycleObserver: lifecycleObserverToken, middleware: middlewareTokens, oauth: oauthOptions, observer: observerToken, onError: errorReporterToken, principalClaims: principalClaimsToken, serverOptions, ...serverDefinition } = definition;
1466
+ Reflect.deleteProperty(serverDefinition, "features");
1467
+ const resolvedOAuth = resolveMcpNestServerOAuth(oauthOptions, this.providers, definition.name);
1468
+ if (resolvedOAuth !== void 0) {
1469
+ this.#httpComposers.set(definition.name, resolvedOAuth.compose);
1470
+ if (resolvedOAuth.proxy !== void 0) {
1471
+ const proxy = resolvedOAuth.proxy;
1472
+ const route = `${proxy.authorizationServerMetadata.issuer}${proxy.basePath}`;
1473
+ const owner = oauthRouteOwners.get(route);
1474
+ if (owner !== void 0) throw new McpModuleError("INVALID_OPTIONS", `MCP servers "${owner}" and "${definition.name}" both expose an OAuth proxy at "${route}". Give each a distinct issuer or oauth.proxy.basePath.`);
1475
+ oauthRouteOwners.set(route, definition.name);
1476
+ this.#oauthProxies.set(definition.name, proxy);
1477
+ }
1478
+ }
1479
+ const resolvedServerOptions = resolveMcpNestServerOptions(serverOptions, this.providers);
1480
+ const resolvedHttpOptions = resolveMcpNestServerHttpOptions(httpOptions, this.providers);
1481
+ const contributors = this.#providerTokenList(contributorTokens, definition.name, "contributors").map((token) => this.#resolveProvider(token, definition.name, "contributor", "contribute"));
1482
+ const catalogPolicy = catalogExposure === void 0 ? void 0 : this.#resolveProvider(catalogExposure.policy, definition.name, "catalog exposure policy", "resolve");
1483
+ const resolvedCatalogExposure = catalogPolicy === void 0 ? void 0 : Object.freeze({ resolver: (input) => catalogPolicy.resolve(input) });
1484
+ if (resolvedCatalogExposure !== void 0) assertMcpCatalogExposureOptions(resolvedCatalogExposure, definition.name);
1485
+ const handlerAuthorization = handlerAuthorizationToken === void 0 ? void 0 : this.#resolveProvider(handlerAuthorizationToken, definition.name, "handler authorization policy", "authorize");
1486
+ const handlerMiddleware = this.#providerTokenList(handlerMiddlewareTokens, definition.name, "handlerMiddleware").map((token) => {
1487
+ const provider = this.#resolveProvider(token, definition.name, "handler middleware", "handle");
1488
+ return provider.handle.bind(provider);
1489
+ });
1490
+ const handlerLifecycleObserver = handlerLifecycleObserverToken === void 0 ? void 0 : this.#resolveProvider(handlerLifecycleObserverToken, definition.name, "handler lifecycle observer", "onEvent");
1491
+ const principalClaimsProvider = principalClaimsToken === void 0 ? void 0 : this.#resolveProvider(principalClaimsToken, definition.name, "principal claims provider", "resolvePrincipalClaims");
1492
+ const middleware = this.#providerTokenList(middlewareTokens, definition.name, "middleware").map((token) => {
1493
+ const provider = this.#resolveProvider(token, definition.name, "server middleware", "handle");
1494
+ return provider.handle.bind(provider);
1495
+ });
1496
+ const lifecycleObserver = lifecycleObserverToken === void 0 ? void 0 : this.#resolveProvider(lifecycleObserverToken, definition.name, "server lifecycle observer", "onEvent");
1497
+ const runtimeObserver = observerToken === void 0 ? void 0 : this.#resolveProvider(observerToken, definition.name, "server runtime observer", "observe");
1498
+ const errorReporter = errorReporterToken === void 0 ? void 0 : this.#resolveProvider(errorReporterToken, definition.name, "server error reporter", "report");
1499
+ if (gateway !== void 0 && gateway.composition !== "tools" && (this.handlerRegistry.hasHandlersFor(definition.name) || contributors.length > 0)) throw new McpModuleError("INVALID_OPTIONS", `MCP gateway server "${definition.name}" must be dedicated and cannot also host decorated or contributed capabilities.`);
1500
+ const discovered = this.handlerRegistry.asServerFeature({
1501
+ serverName: definition.name,
1502
+ ...resolvedCatalogExposure === void 0 ? {} : { catalogExposure: resolvedCatalogExposure },
1503
+ ...handlerAuthorization === void 0 ? {} : { authorization: handlerAuthorization },
1504
+ ...handlerMiddleware.length === 0 ? {} : { middleware: handlerMiddleware },
1505
+ ...handlerLifecycleObserver === void 0 ? {} : { lifecycleObserver: handlerLifecycleObserver },
1506
+ ...handlerVisibilityTimeoutMs === void 0 ? {} : { visibilityTimeoutMs: handlerVisibilityTimeoutMs }
1507
+ });
1508
+ const features = [];
1509
+ if (gateway?.composition === "tools") features.push(this.#createGatewayFeature(definition.name, gateway));
1510
+ if (gateway === void 0 || gateway.composition === "tools") features.push(discovered);
1511
+ if (contributors.length > 0) features.push(async (server, context) => {
1512
+ for (const contributor of contributors) await contributor.contribute(server, context);
1513
+ });
1514
+ if (gateway !== void 0 && gateway.composition !== "tools") features.push(this.#createGatewayFeature(definition.name, gateway));
1515
+ this.servers.register({
1516
+ ...serverDefinition,
1517
+ ...resolvedServerOptions === void 0 ? {} : { serverOptions: resolvedServerOptions },
1518
+ ...resolvedHttpOptions === void 0 ? {} : { http: resolvedHttpOptions },
1519
+ ...principalClaimsProvider === void 0 ? {} : { principalClaims: (authInfo) => principalClaimsProvider.resolvePrincipalClaims(authInfo) },
1520
+ ...middleware.length === 0 ? {} : { middleware },
1521
+ ...lifecycleObserver === void 0 ? {} : { lifecycleObserver },
1522
+ ...runtimeObserver === void 0 ? {} : { observer: (event) => runtimeObserver.observe(event) },
1523
+ ...errorReporter === void 0 ? {} : { onError: (error) => errorReporter.report(error) },
1524
+ ...features.length === 0 ? {} : { features }
1525
+ });
1526
+ }
1527
+ this.#unsubscribeCapabilityMutations = this.handlerRegistry.onMutation(({ kind, serverNames }) => {
1528
+ for (const serverName of serverNames) try {
1529
+ const notifier = this.servers.get(serverName).notify;
1530
+ if (kind === "tool") notifier.toolsChanged();
1531
+ else if (kind === "prompt") notifier.promptsChanged();
1532
+ else notifier.resourcesChanged();
1533
+ } catch {}
1534
+ });
1535
+ this.#ready = true;
1536
+ } catch (bootstrapError) {
1537
+ try {
1538
+ await this.close();
1539
+ } catch (cleanupError) {
1540
+ throw new AggregateError([bootstrapError, cleanupError], "MCP bootstrap failed and its partially initialized runtimes could not close cleanly.", { cause: bootstrapError });
1541
+ }
1542
+ throw bootstrapError;
1543
+ }
1544
+ }
1545
+ /**
1546
+ * Composes the configured OAuth resource-server protection around a runtime's
1547
+ * fetch handler. Returns the runtime untouched when the server has no `oauth`
1548
+ * group, so the HTTP controller's default composition seam is a no-op unless
1549
+ * OAuth is configured.
1550
+ */
1551
+ composeHttpHandler(serverName, runtime) {
1552
+ const composer = this.#httpComposers.get(serverName);
1553
+ return composer === void 0 ? runtime : composer(runtime);
1554
+ }
1555
+ /** The OAuth authorization-server proxy for a server, when `oauth.proxy` is configured. */
1556
+ oauthProxy(serverName) {
1557
+ return this.#oauthProxies.get(serverName);
1558
+ }
1559
+ server(name) {
1560
+ this.#assertReady();
1561
+ return this.servers.get(name);
1562
+ }
1563
+ client(name) {
1564
+ this.#assertReady();
1565
+ return this.clients.requireClient(name);
1566
+ }
1567
+ /** Named client runtime imported through `McpClientModule`. */
1568
+ get clients() {
1569
+ if (this.clientService === void 0) throw new McpModuleError("UNKNOWN_CLIENT", "No McpClientModule is imported by this MCP root.");
1570
+ return this.clientService;
1571
+ }
1572
+ /** Returns the aggregate gateway owned by one configured inbound server. */
1573
+ gateway(serverName) {
1574
+ this.#assertReady();
1575
+ const gateway = this.#gateways.get(serverName);
1576
+ if (gateway === void 0) throw new McpModuleError("UNKNOWN_GATEWAY", `No MCP gateway is configured for server "${serverName}".`);
1577
+ return gateway;
1578
+ }
1579
+ listGateways() {
1580
+ this.#assertReady();
1581
+ return Object.freeze([...this.#gateways.values()]);
1582
+ }
1583
+ isReady() {
1584
+ return this.#ready;
1585
+ }
1586
+ /** Last cleanup failure contained by the Nest lifecycle hook, if any. */
1587
+ get shutdownError() {
1588
+ return this.#shutdownError;
1589
+ }
1590
+ /** Explicit shutdown API. Unlike the Nest hook, this rejects on cleanup failure. */
1591
+ close() {
1592
+ if (this.#closeTask !== void 0) return this.#closeTask;
1593
+ this.#ready = false;
1594
+ this.#closeTask = Promise.resolve().then(() => this.#performClose());
1595
+ return this.#closeTask;
1596
+ }
1597
+ async onModuleDestroy() {
1598
+ try {
1599
+ await this.close();
1600
+ } catch {}
1601
+ }
1602
+ async #performClose() {
1603
+ const errors = [];
1604
+ this.#unsubscribeCapabilityMutations?.();
1605
+ this.#unsubscribeCapabilityMutations = void 0;
1606
+ this.handlerRegistry.close();
1607
+ try {
1608
+ await this.servers.close();
1609
+ } catch (error) {
1610
+ errors.push(error);
1611
+ }
1612
+ const gatewayResults = await Promise.allSettled([...this.#gateways.values()].map(async (gateway) => gateway.close()));
1613
+ for (const result of gatewayResults) if (result.status === "rejected") errors.push(result.reason);
1614
+ if (this.clientService !== void 0) try {
1615
+ await this.clientService.closeFromAggregate();
1616
+ } catch (error) {
1617
+ errors.push(error);
1618
+ }
1619
+ this.#gateways.clear();
1620
+ this.#httpComposers.clear();
1621
+ this.#oauthProxies.clear();
1622
+ if (errors.length > 0) {
1623
+ this.#shutdownError = new AggregateError(errors, "One or more MCP runtimes failed to close.");
1624
+ throw this.#shutdownError;
1625
+ }
1626
+ }
1627
+ #assertReady() {
1628
+ if (!this.#ready) throw new McpModuleError("RUNTIME_NOT_READY", "The MCP runtime is not ready until Nest application bootstrap completes.");
1629
+ }
1630
+ #createGatewayFeature(serverName, options) {
1631
+ const { authorizationContextResolver: authorizationContextResolverToken, composition, discoveryCache: discoveryCacheToken, lifecycleObserver: lifecycleObserverToken, middleware: middlewareTokens, nameCodec: nameCodecToken, onObserverError: observerErrorReporterToken, policy: policyToken, promptNameCodec: promptNameCodecToken, resourceTemplateNameCodec: resourceTemplateNameCodecToken, resourceTemplateUriCodec: resourceTemplateUriCodecToken, resourceUriCodec: resourceUriCodecToken, upstreams: upstreamDefinitions, ...gatewayOptions } = options;
1632
+ const policy = this.#bindGatewayPolicy(this.#resolveProvider(policyToken, serverName, "gateway policy", "authorize"), serverName);
1633
+ const nameCodec = this.#resolveOptionalProvider(nameCodecToken, serverName, "gateway name codec", [
1634
+ "encode",
1635
+ "decode",
1636
+ "tryDecode"
1637
+ ]);
1638
+ const promptNameCodec = this.#resolveOptionalProvider(promptNameCodecToken, serverName, "gateway prompt name codec", [
1639
+ "encode",
1640
+ "decode",
1641
+ "tryDecode"
1642
+ ]);
1643
+ const resourceUriCodec = this.#resolveOptionalProvider(resourceUriCodecToken, serverName, "gateway resource URI codec", [
1644
+ "encode",
1645
+ "decode",
1646
+ "tryDecode"
1647
+ ]);
1648
+ const resourceTemplateUriCodec = this.#resolveOptionalProvider(resourceTemplateUriCodecToken, serverName, "gateway resource-template URI codec", [
1649
+ "encode",
1650
+ "decode",
1651
+ "tryDecode"
1652
+ ]);
1653
+ const resourceTemplateNameCodec = this.#resolveOptionalProvider(resourceTemplateNameCodecToken, serverName, "gateway resource-template name codec", [
1654
+ "encode",
1655
+ "decode",
1656
+ "tryDecode"
1657
+ ]);
1658
+ const discoveryCache = this.#resolveOptionalProvider(discoveryCacheToken, serverName, "gateway discovery cache", [
1659
+ "get",
1660
+ "set",
1661
+ "delete",
1662
+ "clear"
1663
+ ]);
1664
+ const authorizationContextProvider = authorizationContextResolverToken === void 0 ? void 0 : this.#resolveProvider(authorizationContextResolverToken, serverName, "gateway authorization context resolver", "resolveAuthorizationContext");
1665
+ const middleware = this.#providerTokenList(middlewareTokens, serverName, "gateway middleware").map((token) => {
1666
+ const provider = this.#resolveProvider(token, serverName, "gateway middleware", "handle");
1667
+ return bindMcpGatewayMiddleware(provider.handle, provider);
1668
+ });
1669
+ const lifecycleObserver = lifecycleObserverToken === void 0 ? void 0 : this.#resolveProvider(lifecycleObserverToken, serverName, "gateway lifecycle observer", "onEvent");
1670
+ const observerErrorReporter = observerErrorReporterToken === void 0 ? void 0 : this.#resolveProvider(observerErrorReporterToken, serverName, "gateway observer error reporter", "report");
1671
+ if (!Array.isArray(upstreamDefinitions)) throw new McpModuleError("INVALID_OPTIONS", `MCP gateway upstreams for server "${serverName}" must be an array.`);
1672
+ const upstreams = upstreamDefinitions.map((definition) => {
1673
+ if (isProviderGatewayUpstream(definition)) {
1674
+ if (typeof definition.name !== "string" || definition.name.trim().length === 0) throw new McpModuleError("INVALID_OPTIONS", "Nest gateway provider-backed upstream names must be non-empty strings.");
1675
+ const clientProvider = this.#resolveProvider(definition.clientProvider, serverName, `gateway client provider for upstream "${definition.name}"`, "resolveClient");
1676
+ return Object.freeze({
1677
+ name: definition.name,
1678
+ client: clientProvider.resolveClient.bind(clientProvider)
1679
+ });
1680
+ }
1681
+ const normalized = normalizeGatewayUpstream(definition);
1682
+ if (!this.clients.has(normalized.clientName)) throw new McpModuleError("UNKNOWN_CLIENT", `Gateway upstream references unknown MCP client "${normalized.clientName}".`);
1683
+ return createMcpClientRuntimeUpstream(this.clients, normalized.clientName, normalized.gatewayName);
1684
+ });
1685
+ const gateway = new McpGateway({
1686
+ ...gatewayOptions,
1687
+ policy,
1688
+ upstreams,
1689
+ ...nameCodec === void 0 ? {} : { nameCodec },
1690
+ ...promptNameCodec === void 0 ? {} : { promptNameCodec },
1691
+ ...resourceUriCodec === void 0 ? {} : { resourceUriCodec },
1692
+ ...resourceTemplateUriCodec === void 0 ? {} : { resourceTemplateUriCodec },
1693
+ ...resourceTemplateNameCodec === void 0 ? {} : { resourceTemplateNameCodec },
1694
+ ...discoveryCache === void 0 ? {} : { discoveryCache },
1695
+ ...authorizationContextProvider === void 0 ? {} : { authorizationContextResolver: authorizationContextProvider.resolveAuthorizationContext.bind(authorizationContextProvider) },
1696
+ ...middleware.length === 0 ? {} : { middleware },
1697
+ ...lifecycleObserver === void 0 ? {} : { lifecycleObserver },
1698
+ ...observerErrorReporter === void 0 ? {} : { onObserverError: observerErrorReporter.report.bind(observerErrorReporter) }
1699
+ });
1700
+ this.#gateways.set(serverName, gateway);
1701
+ return gateway.asServerFeature({ toolsOnly: composition === "tools" });
1702
+ }
1703
+ #resolveOptionalProvider(token, serverName, role, methods) {
1704
+ return token === void 0 ? void 0 : this.#resolveProviderMethods(token, serverName, role, methods);
1705
+ }
1706
+ #resolveProvider(token, serverName, role, method) {
1707
+ return this.#resolveProviderMethods(token, serverName, role, [method]);
1708
+ }
1709
+ #resolveProviderMethods(token, serverName, role, methods) {
1710
+ try {
1711
+ const provider = this.providers.get(token);
1712
+ if (typeof provider !== "object" && typeof provider !== "function" || provider === null || methods.some((method) => typeof Reflect.get(provider, method) !== "function")) throw new TypeError(`resolved provider does not implement ${methods.map((method) => `${method}()`).join(", ")}`);
1713
+ return provider;
1714
+ } catch (cause) {
1715
+ throw new McpModuleError("INVALID_OPTIONS", `MCP ${role} ${mcpProviderTokenName(token)} for server "${serverName}" must be listed in McpModule collaborators.providers and implement ${methods.map((method) => `${method}()`).join(", ")}.`, { cause });
1716
+ }
1717
+ }
1718
+ #providerTokenList(value, serverName, field) {
1719
+ if (value === void 0) return [];
1720
+ if (Array.isArray(value)) return value;
1721
+ throw new McpModuleError("INVALID_OPTIONS", `MCP server "${serverName}" ${field} must be an array of collaborator provider tokens.`);
1722
+ }
1723
+ #bindGatewayPolicy(policy, serverName) {
1724
+ const { authorizePrompt, authorizeResource, authorizeResourceTemplate } = policy;
1725
+ for (const [name, hook] of [
1726
+ ["authorizePrompt", authorizePrompt],
1727
+ ["authorizeResource", authorizeResource],
1728
+ ["authorizeResourceTemplate", authorizeResourceTemplate]
1729
+ ]) if (hook !== void 0 && typeof hook !== "function") throw new McpModuleError("INVALID_OPTIONS", `MCP gateway policy for server "${serverName}" has a non-callable ${name} hook.`);
1730
+ return Object.freeze({
1731
+ authorize: (operation) => policy.authorize(operation),
1732
+ ...authorizePrompt === void 0 ? {} : { authorizePrompt: (operation) => authorizePrompt.call(policy, operation) },
1733
+ ...authorizeResource === void 0 ? {} : { authorizeResource: (operation) => authorizeResource.call(policy, operation) },
1734
+ ...authorizeResourceTemplate === void 0 ? {} : { authorizeResourceTemplate: (operation) => authorizeResourceTemplate.call(policy, operation) }
1735
+ });
1736
+ }
1737
+ };
1738
+ McpRuntimeService = __decorate([
1739
+ Injectable(),
1740
+ __decorateParam(0, Inject(MCP_MODULE_OPTIONS)),
1741
+ __decorateParam(1, Inject(McpClientService)),
1742
+ __decorateParam(1, Optional()),
1743
+ __decorateMetadata("design:paramtypes", [
1744
+ Object,
1745
+ Object,
1746
+ typeof McpServerRegistry === "undefined" ? Object : McpServerRegistry,
1747
+ typeof McpHandlerExplorer === "undefined" ? Object : McpHandlerExplorer,
1748
+ typeof McpHandlerRegistry === "undefined" ? Object : McpHandlerRegistry,
1749
+ typeof McpCapabilitiesService === "undefined" ? Object : McpCapabilitiesService,
1750
+ typeof McpProviderRegistry === "undefined" ? Object : McpProviderRegistry
1751
+ ])
1752
+ ], McpRuntimeService);
1753
+ function isProviderGatewayUpstream(definition) {
1754
+ return typeof definition === "object" && definition !== null && "clientProvider" in definition;
1755
+ }
1756
+ function normalizeGatewayUpstream(definition) {
1757
+ if (isProviderGatewayUpstream(definition)) throw new McpModuleError("INVALID_OPTIONS", "A provider-backed gateway upstream cannot be normalized as a named client alias.");
1758
+ if (typeof definition !== "string" && (typeof definition !== "object" || definition === null)) throw new McpModuleError("INVALID_OPTIONS", "Nest gateway upstreams must be named client aliases or provider-backed descriptors.");
1759
+ const clientName = typeof definition === "string" ? definition : typeof definition.clientName === "string" ? definition.clientName : "";
1760
+ const gatewayName = typeof definition === "string" ? definition : definition.gatewayName === void 0 ? clientName : typeof definition.gatewayName === "string" ? definition.gatewayName : "";
1761
+ if (clientName.trim().length === 0 || gatewayName.trim().length === 0) throw new McpModuleError("INVALID_OPTIONS", "Nest gateway client and public namespace names must be non-empty strings.");
1762
+ return Object.freeze({
1763
+ clientName,
1764
+ gatewayName
1765
+ });
1766
+ }
1767
+ //#endregion
1768
+ //#region src/mcp-http.controller.ts
1769
+ let McpHttpController = class McpHttpController {
1770
+ runtimeService;
1771
+ constructor(runtimeService) {
1772
+ this.runtimeService = runtimeService;
1773
+ }
1774
+ get mcpServerName() {
1775
+ throw new TypeError("MCP HTTP controller must bind a named server through McpHttpControllerFor().");
1776
+ }
1777
+ #nodeHandler;
1778
+ async handleMcpRequest(request, response) {
1779
+ const intercepted = this.interceptMcpRequest(request, response);
1780
+ if (intercepted !== void 0) return intercepted;
1781
+ const nodeRequest = toNodeRequest(request);
1782
+ const nodeResponse = toNodeResponse(response);
1783
+ forwardValidatedAuth(request, nodeRequest);
1784
+ hijackFastifyReply(response, nodeResponse);
1785
+ await this.#getNodeHandler()(nodeRequest, nodeResponse, parsedBodyOf(request));
1786
+ }
1787
+ /**
1788
+ * Optional Nest-native interception seam before the Node/Web adapter takes ownership.
1789
+ * Returning a value short-circuits MCP dispatch and lets Nest serialize that value;
1790
+ * returning `undefined` delegates to the named MCP runtime.
1791
+ */
1792
+ interceptMcpRequest(_request, _response) {}
1793
+ /**
1794
+ * Override to compose another fetch-shaped facade around the named runtime.
1795
+ * The default applies any configured `oauth` resource-server protection and
1796
+ * otherwise returns the runtime untouched.
1797
+ */
1798
+ createMcpHttpHandler(runtime) {
1799
+ return this.runtimeService.composeHttpHandler(this.mcpServerName, runtime);
1800
+ }
1801
+ /** Override to observe conversion-layer failures handled as HTTP 500 responses. */
1802
+ getNodeAdapterOptions() {}
1803
+ /**
1804
+ * Override to replace the runtime's configured HTTP security posture for
1805
+ * this route. The posture is enforced outside `createMcpHttpHandler()`
1806
+ * composition, so a rejected request never reaches a composed facade.
1807
+ */
1808
+ getHttpSecurityOptions() {}
1809
+ #getNodeHandler() {
1810
+ if (this.#nodeHandler === void 0) {
1811
+ const runtime = this.runtimeService.server(this.mcpServerName);
1812
+ const override = this.getHttpSecurityOptions();
1813
+ const policy = override === void 0 ? runtime.httpSecurity : resolveMcpHttpSecurity(override);
1814
+ const hooks = { onRejected: (status) => runtime.reportRequestRejected(status) };
1815
+ this.#nodeHandler = withMcpNodeBodyLimit(toNodeHandler(hardenMcpFetch(this.createMcpHttpHandler(runtime), policy, hooks), this.getNodeAdapterOptions()), policy, hooks);
1816
+ }
1817
+ return this.#nodeHandler;
1818
+ }
1819
+ };
1820
+ __decorate([
1821
+ All(),
1822
+ __decorateParam(0, Req()),
1823
+ __decorateParam(1, Res({ passthrough: true })),
1824
+ __decorateMetadata("design:type", Function),
1825
+ __decorateMetadata("design:paramtypes", [Object, Object]),
1826
+ __decorateMetadata("design:returntype", Promise)
1827
+ ], McpHttpController.prototype, "handleMcpRequest", null);
1828
+ McpHttpController = __decorate([__decorateParam(0, Inject(McpRuntimeService)), __decorateMetadata("design:paramtypes", [typeof McpRuntimeService === "undefined" ? Object : McpRuntimeService])], McpHttpController);
1829
+ /**
1830
+ * Creates a controller base bound to one named `McpRuntimeService` server.
1831
+ *
1832
+ * @example
1833
+ * ```ts
1834
+ * const ArtifactMcpControllerBase = McpHttpControllerFor("artifact");
1835
+ *
1836
+ * @Controller({ path: "mcp", version: "1" })
1837
+ * @UseGuards(ArtifactGuard)
1838
+ * export class ArtifactMcpController extends ArtifactMcpControllerBase {}
1839
+ * ```
1840
+ *
1841
+ * Override `createMcpHttpHandler()` or `getNodeAdapterOptions()` on the concrete
1842
+ * controller when composition requires additional Nest-injected providers.
1843
+ */
1844
+ function McpHttpControllerFor(serverName) {
1845
+ if (typeof serverName !== "string" || serverName.trim().length === 0) throw new TypeError("MCP HTTP controller server name must be a non-empty string.");
1846
+ class NamedMcpHttpController extends McpHttpController {
1847
+ get mcpServerName() {
1848
+ return serverName;
1849
+ }
1850
+ }
1851
+ return NamedMcpHttpController;
1852
+ }
1853
+ //#endregion
1854
+ //#region src/mcp-cors.ts
1855
+ const DEFAULT_MAX_AGE_SECONDS = 600;
1856
+ /**
1857
+ * CORS options preconfigured for the 2026-07-28 MCP revision, whose
1858
+ * `Mcp-Method`/`Mcp-Name` request headers make every browser MCP POST
1859
+ * CORS-preflighted. Pass the result to `app.enableCors()` when Nest owns CORS
1860
+ * for the whole app; keep exactly one CORS owner per route — with
1861
+ * `app.enableCors()` active, the runtime's built-in `httpSecurity.cors`
1862
+ * preflight handling never runs, so disable one of the two.
1863
+ */
1864
+ function mcpCorsOptions(input) {
1865
+ if (typeof input !== "object" || input === null || !Array.isArray(input.origins)) throw new TypeError("mcpCorsOptions requires an origins array of full browser origins.");
1866
+ const origins = input.origins.map((value, index) => {
1867
+ const failure = `mcpCorsOptions origins[${String(index)}] must be a full origin like "https://app.example.com".`;
1868
+ if (typeof value !== "string" || value.trim().length === 0) throw new TypeError(failure);
1869
+ let parsed;
1870
+ try {
1871
+ parsed = new URL(value);
1872
+ } catch {
1873
+ throw new TypeError(failure);
1874
+ }
1875
+ if (parsed.origin === "null" || parsed.origin !== value.replace(/\/$/, "")) throw new TypeError(failure);
1876
+ return parsed.origin;
1877
+ });
1878
+ const maxAge = input.maxAgeSeconds ?? DEFAULT_MAX_AGE_SECONDS;
1879
+ if (!Number.isInteger(maxAge) || maxAge < 0) throw new TypeError("mcpCorsOptions maxAgeSeconds must be a non-negative integer.");
1880
+ return {
1881
+ origin: origins,
1882
+ methods: [...MCP_CORS_METHODS],
1883
+ allowedHeaders: mergeHeaders(MCP_CORS_ALLOWED_HEADERS, input.additionalAllowedHeaders),
1884
+ exposedHeaders: mergeHeaders(MCP_CORS_EXPOSED_HEADERS, input.additionalExposedHeaders),
1885
+ credentials: input.credentials === true,
1886
+ maxAge
1887
+ };
1888
+ }
1889
+ function mergeHeaders(base, additional) {
1890
+ const merged = new Set(base);
1891
+ for (const header of additional ?? []) {
1892
+ if (typeof header !== "string" || header.trim().length === 0) throw new TypeError("mcpCorsOptions header names must be non-empty strings.");
1893
+ merged.add(header.trim().toLowerCase());
1894
+ }
1895
+ return [...merged];
1896
+ }
1897
+ //#endregion
1898
+ //#region src/oauth/mcp-oauth.controller.ts
1899
+ const MAX_FORM_BODY_BYTES = 65536;
1900
+ let McpOAuthController = class McpOAuthController {
1901
+ runtimeService;
1902
+ constructor(runtimeService) {
1903
+ this.runtimeService = runtimeService;
1904
+ }
1905
+ get mcpServerName() {
1906
+ throw new TypeError("MCP OAuth controller must bind a named server through McpOAuthControllerFor().");
1907
+ }
1908
+ async authorizationServerMetadata(response) {
1909
+ await writeWebResponse(jsonResponse(this.#proxy().authorizationServerMetadata), response);
1910
+ }
1911
+ async jwks(response) {
1912
+ await writeWebResponse(jsonResponse(this.#proxy().jwks()), response);
1913
+ }
1914
+ async protectedResourceMetadata(response) {
1915
+ await writeWebResponse(jsonResponse(this.#proxy().protectedResourceMetadata()), response);
1916
+ }
1917
+ async authorize(request, response) {
1918
+ const webRequest = toWebRequestWithBody(request, void 0);
1919
+ await writeWebResponse(await this.#proxy().authorize(webRequest), response);
1920
+ }
1921
+ async consent(request, response) {
1922
+ const { webRequest, form } = await this.#readForm(request);
1923
+ await writeWebResponse(await this.#proxy().handleConsent(webRequest, form), response);
1924
+ }
1925
+ async callback(request, response) {
1926
+ const webRequest = toWebRequestWithBody(request, void 0);
1927
+ await writeWebResponse(await this.#proxy().handleCallback(webRequest), response);
1928
+ }
1929
+ async token(request, response) {
1930
+ const { webRequest, form } = await this.#readForm(request);
1931
+ await writeWebResponse(await this.#proxy().token(webRequest, form), response);
1932
+ }
1933
+ async #readForm(request) {
1934
+ const parsed = parsedBodyOf(request);
1935
+ const bodyText = parsed === void 0 ? await readNodeBodyText(request, MAX_FORM_BODY_BYTES) : void 0;
1936
+ return {
1937
+ webRequest: toWebRequestWithBody(request, bodyText),
1938
+ form: toSearchParams(parsed, bodyText)
1939
+ };
1940
+ }
1941
+ #proxy() {
1942
+ const proxy = this.runtimeService.oauthProxy(this.mcpServerName);
1943
+ if (proxy === void 0) throw new McpModuleError("INVALID_OPTIONS", `MCP server "${this.mcpServerName}" has no oauth.proxy configured for an OAuth controller.`);
1944
+ return proxy;
1945
+ }
1946
+ };
1947
+ __decorate([
1948
+ Get(".well-known/oauth-authorization-server"),
1949
+ __decorateParam(0, Res({ passthrough: true })),
1950
+ __decorateMetadata("design:type", Function),
1951
+ __decorateMetadata("design:paramtypes", [Object]),
1952
+ __decorateMetadata("design:returntype", Promise)
1953
+ ], McpOAuthController.prototype, "authorizationServerMetadata", null);
1954
+ __decorate([
1955
+ Get(".well-known/jwks.json"),
1956
+ __decorateParam(0, Res({ passthrough: true })),
1957
+ __decorateMetadata("design:type", Function),
1958
+ __decorateMetadata("design:paramtypes", [Object]),
1959
+ __decorateMetadata("design:returntype", Promise)
1960
+ ], McpOAuthController.prototype, "jwks", null);
1961
+ __decorate([
1962
+ Get(".well-known/oauth-protected-resource"),
1963
+ __decorateParam(0, Res({ passthrough: true })),
1964
+ __decorateMetadata("design:type", Function),
1965
+ __decorateMetadata("design:paramtypes", [Object]),
1966
+ __decorateMetadata("design:returntype", Promise)
1967
+ ], McpOAuthController.prototype, "protectedResourceMetadata", null);
1968
+ __decorate([
1969
+ Get("oauth/authorize"),
1970
+ __decorateParam(0, Req()),
1971
+ __decorateParam(1, Res({ passthrough: true })),
1972
+ __decorateMetadata("design:type", Function),
1973
+ __decorateMetadata("design:paramtypes", [Object, Object]),
1974
+ __decorateMetadata("design:returntype", Promise)
1975
+ ], McpOAuthController.prototype, "authorize", null);
1976
+ __decorate([
1977
+ Post("oauth/authorize/consent"),
1978
+ __decorateParam(0, Req()),
1979
+ __decorateParam(1, Res({ passthrough: true })),
1980
+ __decorateMetadata("design:type", Function),
1981
+ __decorateMetadata("design:paramtypes", [Object, Object]),
1982
+ __decorateMetadata("design:returntype", Promise)
1983
+ ], McpOAuthController.prototype, "consent", null);
1984
+ __decorate([
1985
+ Get("oauth/callback"),
1986
+ __decorateParam(0, Req()),
1987
+ __decorateParam(1, Res({ passthrough: true })),
1988
+ __decorateMetadata("design:type", Function),
1989
+ __decorateMetadata("design:paramtypes", [Object, Object]),
1990
+ __decorateMetadata("design:returntype", Promise)
1991
+ ], McpOAuthController.prototype, "callback", null);
1992
+ __decorate([
1993
+ Post("oauth/token"),
1994
+ __decorateParam(0, Req()),
1995
+ __decorateParam(1, Res({ passthrough: true })),
1996
+ __decorateMetadata("design:type", Function),
1997
+ __decorateMetadata("design:paramtypes", [Object, Object]),
1998
+ __decorateMetadata("design:returntype", Promise)
1999
+ ], McpOAuthController.prototype, "token", null);
2000
+ McpOAuthController = __decorate([__decorateParam(0, Inject(McpRuntimeService)), __decorateMetadata("design:paramtypes", [typeof McpRuntimeService === "undefined" ? Object : McpRuntimeService])], McpOAuthController);
2001
+ /**
2002
+ * Creates an OAuth controller base bound to one named `McpRuntimeService`
2003
+ * server whose definition configures `oauth.proxy`.
2004
+ *
2005
+ * @example
2006
+ * ```ts
2007
+ * const AuthControllerBase = McpOAuthControllerFor("artifact");
2008
+ *
2009
+ * @Controller()
2010
+ * export class ArtifactOAuthController extends AuthControllerBase {}
2011
+ * ```
2012
+ */
2013
+ function McpOAuthControllerFor(serverName) {
2014
+ if (typeof serverName !== "string" || serverName.trim().length === 0) throw new TypeError("MCP OAuth controller server name must be a non-empty string.");
2015
+ class NamedMcpOAuthController extends McpOAuthController {
2016
+ get mcpServerName() {
2017
+ return serverName;
2018
+ }
2019
+ }
2020
+ return NamedMcpOAuthController;
2021
+ }
2022
+ function jsonResponse(body) {
2023
+ return new Response(JSON.stringify(body), {
2024
+ status: 200,
2025
+ headers: {
2026
+ "content-type": "application/json",
2027
+ "cache-control": "no-store"
2028
+ }
2029
+ });
2030
+ }
2031
+ function toSearchParams(parsed, bodyText) {
2032
+ if (parsed instanceof URLSearchParams) return parsed;
2033
+ if (typeof parsed === "string") return new URLSearchParams(parsed);
2034
+ if (typeof parsed === "object" && parsed !== null) {
2035
+ const params = new URLSearchParams();
2036
+ for (const [key, value] of Object.entries(parsed)) if (typeof value === "string") params.set(key, value);
2037
+ else if (Array.isArray(value)) {
2038
+ for (const entry of value) if (typeof entry === "string") params.append(key, entry);
2039
+ }
2040
+ return params;
2041
+ }
2042
+ return new URLSearchParams(bodyText ?? "");
2043
+ }
2044
+ //#endregion
2045
+ //#region src/oauth/mcp-oauth.service.ts
2046
+ let McpOAuthService = class McpOAuthService {
2047
+ runtimeService;
2048
+ constructor(runtimeService) {
2049
+ this.runtimeService = runtimeService;
2050
+ }
2051
+ /**
2052
+ * Loads the upstream tokens for the grant referenced by a verified
2053
+ * `AuthInfo` (via its `gid` claim). Returns `undefined` when the server has
2054
+ * no proxy, the token carries no grant id, or the grant has been revoked.
2055
+ */
2056
+ async upstreamTokens(serverName, authInfo) {
2057
+ const proxy = this.runtimeService.oauthProxy(serverName);
2058
+ if (proxy === void 0) return void 0;
2059
+ const grantId = grantIdOf(authInfo);
2060
+ if (grantId === void 0) return void 0;
2061
+ const upstream = await proxy.loadUpstreamTokens(grantId);
2062
+ if (upstream === void 0) return void 0;
2063
+ return {
2064
+ accessToken: upstream.accessToken,
2065
+ ...upstream.refreshToken === void 0 ? {} : { refreshToken: upstream.refreshToken },
2066
+ ...upstream.expiresAt === void 0 ? {} : { expiresAt: upstream.expiresAt }
2067
+ };
2068
+ }
2069
+ };
2070
+ McpOAuthService = __decorate([Injectable(), __decorateMetadata("design:paramtypes", [typeof McpRuntimeService === "undefined" ? Object : McpRuntimeService])], McpOAuthService);
2071
+ function grantIdOf(authInfo) {
2072
+ const claims = authInfo.extra?.["claims"];
2073
+ if (typeof claims !== "object" || claims === null) return void 0;
2074
+ const gid = Reflect.get(claims, "gid");
2075
+ return typeof gid === "string" && gid.length > 0 ? gid : void 0;
2076
+ }
2077
+ //#endregion
2078
+ //#region src/http/mcp-http-routes.ts
2079
+ /** Generates ordinary Nest controllers while retaining the existing protocol/security pipeline. */
2080
+ function withMcpHttpRoutes(definition, routes) {
2081
+ if (routes === void 0) return definition;
2082
+ if (!Array.isArray(routes)) throw invalid("httpRoutes must be an array.");
2083
+ const paths = /* @__PURE__ */ new Set();
2084
+ const controllers = [];
2085
+ for (const input of routes) {
2086
+ if (!input || typeof input.serverName !== "string" || input.serverName.trim().length === 0) throw invalid("Every httpRoutes entry requires a non-empty serverName.");
2087
+ if (input.discovery !== void 0 && (!input.discovery || typeof input.discovery !== "object")) throw invalid("HTTP discovery must be an object.");
2088
+ const route = {
2089
+ serverName: input.serverName,
2090
+ path: claimPath(input.path, paths),
2091
+ ...input.version === void 0 ? {} : { version: Array.isArray(input.version) ? [...input.version] : input.version },
2092
+ decorators: decorators(input.decorators),
2093
+ ...input.discovery === void 0 ? {} : { discovery: {
2094
+ protectedResourcePaths: claimPaths(input.discovery.protectedResourcePaths, paths),
2095
+ authorizationServerPaths: claimPaths(input.discovery.authorizationServerPaths, paths),
2096
+ decorators: decorators(input.discovery.decorators)
2097
+ } }
2098
+ };
2099
+ if (route.discovery !== void 0 && !route.discovery.protectedResourcePaths?.length && !route.discovery.authorizationServerPaths?.length) throw invalid("HTTP discovery requires at least one document path.");
2100
+ controllers.push(httpController(route));
2101
+ for (const kind of ["protectedResource", "authorizationServer"]) {
2102
+ const documentPaths = route.discovery?.[`${kind}Paths`];
2103
+ if (documentPaths?.length) controllers.push(discoveryController(route, kind, documentPaths));
2104
+ }
2105
+ }
2106
+ return {
2107
+ ...definition,
2108
+ controllers: [...definition.controllers ?? [], ...controllers]
2109
+ };
2110
+ }
2111
+ function httpController(route) {
2112
+ const Base = McpHttpControllerFor(route.serverName);
2113
+ let GeneratedMcpHttpController = class GeneratedMcpHttpController extends Base {
2114
+ constructor(runtime, options) {
2115
+ super(runtime);
2116
+ const server = requireServer(options, route.serverName);
2117
+ if (route.discovery !== void 0) discoveryMetadata(server, route);
2118
+ }
2119
+ };
2120
+ GeneratedMcpHttpController = __decorate([
2121
+ Controller({
2122
+ path: route.path,
2123
+ ...route.version === void 0 ? {} : { version: route.version }
2124
+ }),
2125
+ __decorateParam(0, Inject(McpRuntimeService)),
2126
+ __decorateParam(1, Inject(MCP_MODULE_OPTIONS)),
2127
+ __decorateMetadata("design:paramtypes", [typeof McpRuntimeService === "undefined" ? Object : McpRuntimeService, Object])
2128
+ ], GeneratedMcpHttpController);
2129
+ applyDecorators(...route.decorators ?? [])(GeneratedMcpHttpController);
2130
+ return GeneratedMcpHttpController;
2131
+ }
2132
+ function discoveryController(route, kind, paths) {
2133
+ let GeneratedMcpDiscoveryController = class GeneratedMcpDiscoveryController {
2134
+ #metadata;
2135
+ constructor(options) {
2136
+ this.#metadata = discoveryMetadata(requireServer(options, route.serverName), route);
2137
+ }
2138
+ async document(request, response) {
2139
+ const incoming = toWebRequestWithBody(request, void 0);
2140
+ const url = kind === "protectedResource" ? getOAuthProtectedResourceMetadataUrl(this.#metadata.resourceServerUrl) : new URL("/.well-known/oauth-authorization-server", this.#metadata.resourceServerUrl).href;
2141
+ const result = oauthMetadataResponse(new Request(url, {
2142
+ method: incoming.method,
2143
+ headers: incoming.headers
2144
+ }), this.#metadata);
2145
+ if (result === void 0) throw invalid("The SDK did not resolve the discovery document.");
2146
+ await writeWebResponse(result, response);
2147
+ }
2148
+ };
2149
+ __decorate([
2150
+ All([...paths]),
2151
+ __decorateParam(0, Req()),
2152
+ __decorateParam(1, Res({ passthrough: true })),
2153
+ __decorateMetadata("design:type", Function),
2154
+ __decorateMetadata("design:paramtypes", [Object, Object]),
2155
+ __decorateMetadata("design:returntype", Promise)
2156
+ ], GeneratedMcpDiscoveryController.prototype, "document", null);
2157
+ GeneratedMcpDiscoveryController = __decorate([
2158
+ Controller({ version: VERSION_NEUTRAL }),
2159
+ __decorateParam(0, Inject(MCP_MODULE_OPTIONS)),
2160
+ __decorateMetadata("design:paramtypes", [Object])
2161
+ ], GeneratedMcpDiscoveryController);
2162
+ applyDecorators(...route.discovery?.decorators ?? [])(GeneratedMcpDiscoveryController);
2163
+ return GeneratedMcpDiscoveryController;
2164
+ }
2165
+ function requireServer(options, name) {
2166
+ const server = options.servers?.find((candidate) => candidate.name === name);
2167
+ if (server === void 0) throw invalid(`HTTP route references unknown MCP server "${name}".`);
2168
+ return server;
2169
+ }
2170
+ function discoveryMetadata(server, route) {
2171
+ const resource = server.oauth?.resource;
2172
+ const metadata = resource?.metadata;
2173
+ if (resource === void 0 || metadata === void 0) throw invalid(`HTTP discovery for "${server.name}" requires oauth.resource.metadata.`);
2174
+ const options = {
2175
+ resourceServerUrl: new URL(resource.resourceServerUrl),
2176
+ oauthMetadata: structuredClone(metadata.oauthMetadata),
2177
+ ...metadata.resourceName === void 0 ? {} : { resourceName: metadata.resourceName },
2178
+ ...metadata.scopesSupported === void 0 ? {} : { scopesSupported: [...metadata.scopesSupported] },
2179
+ ...metadata.serviceDocumentationUrl === void 0 ? {} : { serviceDocumentationUrl: new URL(metadata.serviceDocumentationUrl) }
2180
+ };
2181
+ buildOAuthProtectedResourceMetadata(options);
2182
+ const expectedPath = new URL(getOAuthProtectedResourceMetadataUrl(options.resourceServerUrl)).pathname.slice(1);
2183
+ const resourcePaths = route.discovery?.protectedResourcePaths;
2184
+ if (resourcePaths?.length && !resourcePaths.includes(expectedPath)) throw invalid(`HTTP discovery for "${server.name}" must include its bearer challenge path "${expectedPath}".`);
2185
+ return options;
2186
+ }
2187
+ function claimPaths(input, paths) {
2188
+ if (input === void 0) return [];
2189
+ if (!Array.isArray(input) || input.length === 0) throw invalid("Discovery document paths must be non-empty arrays.");
2190
+ return input.map((path) => claimPath(path, paths));
2191
+ }
2192
+ function claimPath(input, paths) {
2193
+ if (typeof input !== "string" || !/^\/?[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)*\/?$/u.test(input)) throw invalid("HTTP route paths must be literal paths without queries, fragments, or router patterns.");
2194
+ const path = input.replace(/^\//u, "").replace(/\/$/u, "");
2195
+ if (path.split("/").some((segment) => segment === "." || segment === "..")) throw invalid("HTTP route paths cannot contain dot segments.");
2196
+ const key = path.toLowerCase();
2197
+ if (paths.has(key)) throw invalid(`Duplicate MCP HTTP route path "${path}".`);
2198
+ paths.add(key);
2199
+ return path;
2200
+ }
2201
+ function decorators(input) {
2202
+ if (input === void 0) return [];
2203
+ if (!Array.isArray(input) || input.some((decorator) => typeof decorator !== "function")) throw invalid("HTTP route decorators must be class decorator functions.");
2204
+ return [...input];
2205
+ }
2206
+ function invalid(message) {
2207
+ return new McpModuleError("INVALID_OPTIONS", message);
2208
+ }
2209
+ //#endregion
2210
+ //#region src/mcp.module-definition.ts
2211
+ const { ConfigurableModuleClass, OPTIONS_TYPE, ASYNC_OPTIONS_TYPE } = new ConfigurableModuleBuilder({ optionsInjectionToken: MCP_MODULE_OPTIONS }).setClassMethodName("forRoot").setFactoryMethodName("createMcpOptions").setExtras({
2212
+ isGlobal: false,
2213
+ imports: [],
2214
+ collaborators: {},
2215
+ httpRoutes: []
2216
+ }, (definition, extras) => ({
2217
+ ...withMcpHttpRoutes(withMcpCollaborators({
2218
+ ...definition,
2219
+ imports: [.../* @__PURE__ */ new Set([...definition.imports ?? [], ...extras.imports ?? []])]
2220
+ }, extras.collaborators), extras.httpRoutes),
2221
+ global: extras.isGlobal === true
2222
+ })).build();
2223
+ //#endregion
2224
+ //#region src/mcp.module.ts
2225
+ const MCP_PROVIDERS = [
2226
+ McpServerRegistry,
2227
+ McpHandlerRegistry,
2228
+ McpCapabilitiesService,
2229
+ McpHandlerExplorer,
2230
+ McpRuntimeService,
2231
+ McpOAuthService
2232
+ ];
2233
+ let McpModule = class McpModule extends ConfigurableModuleClass {
2234
+ static forRoot(options = {}) {
2235
+ return super.forRoot(options);
2236
+ }
2237
+ static forRootAsync(options) {
2238
+ return super.forRootAsync(options);
2239
+ }
2240
+ };
2241
+ McpModule = __decorate([Module({
2242
+ imports: [DiscoveryModule],
2243
+ providers: MCP_PROVIDERS,
2244
+ exports: [
2245
+ McpCapabilitiesService,
2246
+ McpRuntimeService,
2247
+ McpOAuthService
2248
+ ]
2249
+ })], McpModule);
2250
+ //#endregion
2251
+ //#region src/mcp-handler.middleware.ts
2252
+ /**
2253
+ * Creates handler middleware that can observe the validated invocation while
2254
+ * preserving the exact SDK result produced by the downstream capability.
2255
+ */
2256
+ function createMcpHandlerPassthroughMiddleware(middleware) {
2257
+ return createMcpPassthroughMiddleware(middleware);
2258
+ }
2259
+ //#endregion
2260
+ export { MCP_CATALOG_SCHEMAS_TOOL_NAME, MCP_CATALOG_SEARCH_TOOL_NAME, McpCapabilitiesService, McpClientModule, McpClientService, McpHttpController, McpHttpControllerFor, McpModule, McpModuleError, McpOAuthController, McpOAuthControllerFor, McpOAuthService, McpRuntimeService, Prompt, Resource, ResourceTemplate, Targets, Tool, acceptedContent, allowMcpOperation, completable, createMcpHandlerPassthroughMiddleware, createRequestStateCodec, denyMcpOperation, fromJsonSchema, inputRequired, inputResponse, mcpCorsOptions };
2261
+
2262
+ //# sourceMappingURL=index.mjs.map