@nest-mcp/nestjs 0.0.0-stage → 2.0.0-alpha.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/README.md CHANGED
@@ -1,3 +1,769 @@
1
- # Temporary Holding Version
1
+ # @nest-mcp/nestjs
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ NestJS 12 integration for the official Model Context Protocol TypeScript SDK v2.
4
+
5
+ The package root is intentionally Nest-focused. Import framework-neutral runtime, transport,
6
+ gateway, authentication, and observability APIs from their owning `@nest-mcp/*` packages.
7
+ Install Zod 4.2 or newer alongside the package when using the recommended schema authoring style
8
+ below.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ pnpm add @nest-mcp/nestjs @modelcontextprotocol/client@2 @modelcontextprotocol/core@2 @modelcontextprotocol/node@2 @modelcontextprotocol/server@2 @nestjs/common@12 @nestjs/core@12 reflect-metadata rxjs zod@^4.4.3
14
+ ```
15
+
16
+ ```ts
17
+ import { Injectable, Module } from "@nestjs/common";
18
+ import { McpClientModule, McpModule, Tool } from "@nest-mcp/nestjs";
19
+ import { z } from "zod/v4";
20
+
21
+ const artifactReadInput = z.object({ id: z.string() });
22
+
23
+ @Injectable()
24
+ class ArtifactTools {
25
+ @Tool({
26
+ name: "artifact.read",
27
+ inputSchema: artifactReadInput,
28
+ })
29
+ read({ id }: z.output<typeof artifactReadInput>) {
30
+ return { content: [{ type: "text" as const, text: id }] };
31
+ }
32
+ }
33
+
34
+ @Module({
35
+ imports: [
36
+ McpModule.forRoot({
37
+ imports: [
38
+ McpClientModule.forRoot({
39
+ servers: [
40
+ {
41
+ name: "knowledge",
42
+ transport: { kind: "http", url: "https://mcp.example.com/mcp" },
43
+ },
44
+ ],
45
+ bootstrap: {
46
+ connectAll: true,
47
+ },
48
+ }),
49
+ ],
50
+ servers: [
51
+ {
52
+ name: "artifact",
53
+ serverInfo: { name: "artifact", version: "1.0.0" },
54
+ },
55
+ ],
56
+ }),
57
+ ],
58
+ providers: [ArtifactTools],
59
+ })
60
+ export class AppModule {}
61
+ ```
62
+
63
+ Zod 4.2 or newer is the recommended authoring experience, while the public contract remains the
64
+ official `StandardSchemaWithJSON` interface so ArkType, Valibot, and other compatible schemas still
65
+ work. A DTO class that carries a Standard Schema can be reused as `MyDto.schema` when its carried
66
+ schema also implements Standard JSON Schema conversion, as Zod 4.2+ does. The DTO class itself is
67
+ an HTTP metadata carrier rather than an MCP schema.
68
+
69
+ Configure upstream clients asynchronously with normal Nest imports and injection, then import that
70
+ configured client module through the MCP server root:
71
+
72
+ ```ts
73
+ McpModule.forRoot({
74
+ imports: [
75
+ McpClientModule.forRootAsync({
76
+ imports: [RuntimeConfigModule],
77
+ inject: [RuntimeConfigService],
78
+ useFactory: (config: RuntimeConfigService) => ({
79
+ servers: config.mcpServers(),
80
+ bootstrap: {
81
+ connectAll: true,
82
+ },
83
+ }),
84
+ }),
85
+ ],
86
+ });
87
+ ```
88
+
89
+ Use `McpModule.forRootAsync()` separately when inbound server definitions are asynchronous.
90
+ `McpModule` and `McpClientModule` are both local by default. Import the MCP server root exactly once
91
+ per Nest application because decorator discovery is application-wide. Configure the client module
92
+ independently and include it in `McpModule`'s `imports` when gateways or `McpRuntimeService` need its
93
+ named upstreams. Set `isGlobal: true` on either module only when application-wide injection is
94
+ intentional.
95
+
96
+ After Nest application bootstrap, inject `McpRuntimeService`. Mount
97
+ `runtime.server("artifact").toNodeHandler()` at the desired route, access the named upstream with
98
+ `runtime.client("knowledge")`, or use `runtime.clients` for registry operations. The module closes
99
+ inbound server handlers before upstream clients during Nest shutdown. For Nest-native routing,
100
+ guards, interceptors, prefixes, and versioning, declare `httpRoutes` below.
101
+
102
+ For an outbound-only agent host, import `McpClientModule` directly and inject `McpClientService`:
103
+
104
+ ```ts
105
+ import { Injectable, Module } from "@nestjs/common";
106
+ import { McpClientModule, McpClientService } from "@nest-mcp/nestjs/client";
107
+
108
+ @Injectable()
109
+ class KnowledgeAgent {
110
+ constructor(private readonly clients: McpClientService) {}
111
+
112
+ listTools() {
113
+ return this.clients.listTools("knowledge");
114
+ }
115
+ }
116
+
117
+ @Module({
118
+ imports: [
119
+ McpClientModule.forRoot({
120
+ servers: upstreamServers,
121
+ bootstrap: {
122
+ connectAll: true,
123
+ },
124
+ }),
125
+ ],
126
+ providers: [KnowledgeAgent],
127
+ })
128
+ export class AgentHostModule {}
129
+ ```
130
+
131
+ `McpClientService` extends the framework-neutral `McpClientRuntime`, so it exposes the same typed
132
+ registry and protocol operations while adding Nest bootstrap and shutdown ownership. Client
133
+ factories, transports, authentication, middleware, observers, and resolvers are referenced by
134
+ provider token and registered under `McpClientModule`'s `collaborators`; the module resolves and
135
+ binds them before constructing the runtime. The dedicated `@nest-mcp/nestjs/client` entrypoint does not
136
+ load inbound server, gateway, or OAuth implementation code. Outside Nest, continue constructing
137
+ `McpClientRuntime` directly from `@nest-mcp/client`.
138
+
139
+ For dynamic, already-admitted client generations, use the dedicated manager entrypoint:
140
+
141
+ ```ts
142
+ import { Module } from "@nestjs/common";
143
+ import { McpManagerModule } from "@nest-mcp/nestjs/manager";
144
+
145
+ const GENERATION_RESOLVER = Symbol("GENERATION_RESOLVER");
146
+ const LIFECYCLE_OBSERVER = Symbol("LIFECYCLE_OBSERVER");
147
+
148
+ @Module({
149
+ imports: [
150
+ McpManagerModule.forRoot({
151
+ generationResolver: GENERATION_RESOLVER,
152
+ observer: LIFECYCLE_OBSERVER,
153
+ maxConnections: 16,
154
+ collaborators: {
155
+ providers: [
156
+ { provide: GENERATION_RESOLVER, useExisting: AdmittedGenerationResolver },
157
+ { provide: LIFECYCLE_OBSERVER, useExisting: RuntimeMetricsObserver },
158
+ ],
159
+ },
160
+ }),
161
+ ],
162
+ })
163
+ export class ManagedUpstreamsModule {}
164
+ ```
165
+
166
+ Inject `McpManagerService` from `@nest-mcp/nestjs/manager`; it extends the framework-neutral
167
+ `McpRuntimeManager` from `@nest-mcp/manager` and closes deterministically during Nest module
168
+ shutdown. `forRootAsync()` supports normal imported configuration providers. Generation resolution
169
+ and lifecycle observation are provider-token seams. An optional `clock` token must implement
170
+ `now()`, and `listenerErrorReporter` must implement `report(error, event)`; raw callbacks do not live
171
+ in Nest module options. Records, endpoint admission, credentials, and durable reconciliation remain
172
+ application responsibilities.
173
+
174
+ The client adapter resolves these provider-token seams:
175
+
176
+ | Client option | Provider contract |
177
+ | --------------------------------------------- | ------------------------------------------------------ |
178
+ | `runtime.clientFactory` | `createClient` |
179
+ | `runtime.transportFactory` / server factory | `createTransport` |
180
+ | `runtime.middleware[]` | `handle` |
181
+ | `runtime.observer` | `onEvent` |
182
+ | `runtime.lifecycle.clock` / `runtime.clock` | `now` |
183
+ | `runtime.lifecycle.errorReporter` | `report` |
184
+ | `runtime.principalResolver` | `resolvePrincipal` |
185
+ | `runtime.attributesResolver` | `resolveAttributes` |
186
+ | `runtime.operationIdFactory` | `createOperationId` |
187
+ | `servers[].configureClient` | `configure` |
188
+ | `servers[].clientOptions.jsonSchemaValidator` | `getValidator` |
189
+ | `servers[].clientOptions.responseCacheStore` | `get`, `set`, `delete`, `evict`, `clear` |
190
+ | `servers[].connectOptions.progressObserver` | `onProgress` |
191
+ | HTTP `authProvider` | `token`, or the complete `OAuthClientProvider` methods |
192
+ | HTTP `fetch` / `middleware[]` / reconnection | `fetch` / `handle` / `schedule` |
193
+ | HTTP `requestInit` / stdio `stderrStream` | provider-owned value |
194
+
195
+ Static connect configuration intentionally excludes `AbortSignal`; pass cancellation to an
196
+ imperative client operation instead. Passive URL, timeout, retry, stdio mode, and environment data
197
+ stays inline.
198
+
199
+ Decorated singleton providers with static dependency trees are compiled once. The official SDK
200
+ still creates a fresh cheap server instance for every modern HTTP request. `@Tool`, `@Prompt`, and
201
+ `@Resource` preserve the official callback types: a schema-incompatible
202
+ method signature is rejected by TypeScript before reflective discovery runs.
203
+
204
+ ## Feature modules and server targeting
205
+
206
+ Keep handler providers and their dependencies in feature modules while configuring the shared
207
+ runtime once with `forRoot()`:
208
+
209
+ ```ts
210
+ import { Injectable, Module } from "@nestjs/common";
211
+ import { Targets, Tool } from "@nest-mcp/nestjs";
212
+
213
+ @Injectable()
214
+ @Targets("artifact", "backoffice")
215
+ class ArtifactTools {
216
+ @Tool({ name: "artifact.read" })
217
+ read() {
218
+ return { content: [{ type: "text" as const, text: "read" }] };
219
+ }
220
+
221
+ // Method targets replace, rather than merge with, the class defaults.
222
+ @Tool({ name: "artifact.delete", servers: "backoffice" })
223
+ remove() {
224
+ return { content: [{ type: "text" as const, text: "removed" }] };
225
+ }
226
+ }
227
+
228
+ @Module({
229
+ imports: [ArtifactStoreModule],
230
+ providers: [ArtifactTools],
231
+ exports: [ArtifactTools],
232
+ })
233
+ export class ArtifactMcpFeatureModule {}
234
+ ```
235
+
236
+ Use ordinary Nest modules for imports, providers, and explicit exports; discovery scans registered
237
+ providers across the application. `@Targets()` supplies class defaults; a decorator's own
238
+ `servers` value replaces that default for the method. When neither is present, the capability
239
+ targets every configured server, so explicitly target local servers when a dedicated gateway is
240
+ configured. Empty, duplicate, unknown, and gateway targets are rejected.
241
+
242
+ ### Injectable low-level contributors
243
+
244
+ When a capability cannot be expressed through decorators or `McpCapabilitiesService`, register a
245
+ singleton contributor provider explicitly:
246
+
247
+ ```ts
248
+ import { Injectable, Module } from "@nestjs/common";
249
+ import { McpModule, type McpServerContributor } from "@nest-mcp/nestjs";
250
+
251
+ @Injectable()
252
+ class HealthContributor implements McpServerContributor {
253
+ contribute: McpServerContributor["contribute"] = (server) => {
254
+ server.registerTool("health.check", {}, async () => ({
255
+ content: [{ type: "text", text: "ok" }],
256
+ }));
257
+ };
258
+ }
259
+
260
+ @Module({
261
+ imports: [
262
+ McpModule.forRoot({
263
+ collaborators: { providers: [HealthContributor] },
264
+ servers: [
265
+ {
266
+ name: "operations",
267
+ serverInfo: { name: "operations", version: "1.0.0" },
268
+ contributors: [HealthContributor],
269
+ },
270
+ ],
271
+ }),
272
+ ],
273
+ })
274
+ export class OperationsMcpModule {}
275
+ ```
276
+
277
+ Contributors are the Nest boundary for low-level official SDK registration; raw server feature
278
+ callbacks remain in `@nest-mcp/server`. Contributors must use the default singleton scope and
279
+ cannot share a dedicated gateway or catalog-projected server.
280
+
281
+ All callback-bearing Nest server settings are provider tokens resolved once during bootstrap:
282
+
283
+ | Server option | Required provider method(s) |
284
+ | ------------------------------------- | --------------------------- |
285
+ | `serverOptions.jsonSchemaValidator` | `getValidator` |
286
+ | `serverOptions.requestState.verifier` | `verify` |
287
+ | `http.eventBus` | `publish`, `subscribe` |
288
+ | `principalClaims` | `resolvePrincipalClaims` |
289
+ | `middleware[]` | `handle` |
290
+ | `lifecycleObserver` | `onEvent` |
291
+ | `observer` | `observe` |
292
+ | `onError` | `report` |
293
+ | `handlerAuthorization` | `authorize` |
294
+ | `handlerMiddleware[]` | `handle` |
295
+ | `handlerLifecycleObserver` | `onEvent` |
296
+ | `contributors[]` | `contribute` |
297
+ | `catalogExposure.policy` | `resolve` |
298
+
299
+ The declarative Nest gateway follows the same rule:
300
+
301
+ | Gateway option | Required provider method(s) |
302
+ | -------------------------------------- | ----------------------------------------------------------------------------------------- |
303
+ | `gateway.upstreams[].clientProvider` | `resolveClient` |
304
+ | `gateway.policy` | `authorize`; optional `authorizePrompt`, `authorizeResource`, `authorizeResourceTemplate` |
305
+ | `gateway.nameCodec` | `encode`, `decode`, `tryDecode` |
306
+ | `gateway.promptNameCodec` | `encode`, `decode`, `tryDecode` |
307
+ | `gateway.resourceUriCodec` | `encode`, `decode`, `tryDecode` |
308
+ | `gateway.resourceTemplateUriCodec` | `encode`, `decode`, `tryDecode` |
309
+ | `gateway.resourceTemplateNameCodec` | `encode`, `decode`, `tryDecode` |
310
+ | `gateway.discoveryCache` | `get`, `set`, `delete`, `clear` |
311
+ | `gateway.authorizationContextResolver` | `resolveAuthorizationContext` |
312
+ | `gateway.middleware[]` | `handle` |
313
+ | `gateway.lifecycleObserver` | `onEvent` |
314
+ | `gateway.onObserverError` | `report` |
315
+
316
+ Use a class token, string token, symbol token, or abstract-class token registered under
317
+ `McpModule`'s `collaborators.providers`. Use `collaborators.imports` for modules that supply their
318
+ dependencies; imported providers can be exposed through `useExisting`. This explicit child-module
319
+ ownership prevents an identically named private provider elsewhere in the application from being
320
+ selected and keeps collaborator initialization/teardown ordered around the runtimes they serve.
321
+ Collaborators must use the default singleton scope with a static dependency tree; bootstrap fails
322
+ before serving traffic when a token is missing, scoped, or does not implement its required method.
323
+ The Nest option names make token ownership explicit: `http.eventBus` maps to the official handler's
324
+ `bus`, and `serverOptions.requestState.verifier` supplies its `verify` callback. Passive data such as
325
+ timeouts, limits, cache hints, and other scalar server or gateway settings remains inline. When
326
+ constructing `McpServerRuntime` or `McpGateway` outside Nest, pass the raw callback-bearing options
327
+ defined by `@nest-mcp/server` and `@nest-mcp/gateway` instead.
328
+
329
+ ## Per-request capability visibility
330
+
331
+ Visibility controls which capabilities are installed on a freshly built server; it does not
332
+ authorize invocation:
333
+
334
+ ```ts
335
+ import { Injectable } from "@nestjs/common";
336
+ import {
337
+ Tool,
338
+ type McpCapabilityVisibilityPolicy,
339
+ type McpServerBuildContext,
340
+ } from "@nest-mcp/nestjs";
341
+
342
+ @Injectable()
343
+ class ArtifactVisibility implements McpCapabilityVisibilityPolicy {
344
+ isVisible(context: Readonly<McpServerBuildContext>): boolean {
345
+ return context.principal?.tenantId === "artifact-team";
346
+ }
347
+ }
348
+
349
+ @Injectable()
350
+ class InternalArtifactTools {
351
+ @Tool({
352
+ name: "artifact.internal",
353
+ visibility: ArtifactVisibility,
354
+ })
355
+ internalArtifact() {
356
+ return { content: [{ type: "text" as const, text: "internal" }] };
357
+ }
358
+ }
359
+ ```
360
+
361
+ Register policy classes as default-scope singleton `McpModule` collaborators.
362
+ Each policy is evaluated once per fresh server build and shared by every capability that references
363
+ it. Static `true`/`false` visibility is also supported. A missing or non-singleton provider,
364
+ exception, rejection, non-boolean result, request abort, or deadline aborts the server build
365
+ fail-closed. The visibility wave defaults to 30 seconds and is configured per server with
366
+ `handlerVisibilityTimeoutMs`.
367
+
368
+ Always use `handlerAuthorization` independently for call-time access decisions. Hiding a tool,
369
+ prompt, or resource from discovery is not an authorization boundary.
370
+
371
+ ## Authorization-safe tool catalogs
372
+
373
+ `McpNestServerDefinition.catalogExposure` is an opt-in projection applied after the complete
374
+ per-request visibility wave:
375
+
376
+ - `eager` lists every currently visible tool normally.
377
+ - `search` keeps selected tools eager and merges application-supplied deferred metadata into the
378
+ other visible definitions. No vendor metadata is added unless this strategy is configured.
379
+ - `lazy` keeps selected tools eager and adds the bounded `nest-mcp.catalog.search` and
380
+ `nest-mcp.catalog.schemas` tools. Search results are cursor-paginated against the exact ordered
381
+ visible snapshot; schema fetches accept a bounded name batch and return official MCP `Tool`
382
+ definitions.
383
+
384
+ Eager selectors can match an exact name, a normalized `ToolOptions.tags` value, or a readonly
385
+ predicate. Dynamic strategy selection belongs to a singleton `McpCatalogExposurePolicy` provider;
386
+ its `resolve()` input contains frozen public tool projections plus the token-free principal,
387
+ runtime name, protocol era, and abort signal. It never exposes decorated callbacks, visibility
388
+ providers, raw requests, or bearer credentials.
389
+
390
+ ```ts
391
+ import { Injectable } from "@nestjs/common";
392
+ import type {
393
+ McpCatalogExposurePolicy,
394
+ McpCatalogExposureStrategy,
395
+ McpNestCatalogExposureOptions,
396
+ } from "@nest-mcp/nestjs";
397
+
398
+ @Injectable()
399
+ class ArtifactCatalogPolicy implements McpCatalogExposurePolicy {
400
+ resolve: McpCatalogExposurePolicy["resolve"] = (input): McpCatalogExposureStrategy => {
401
+ return input.principal?.scopes.includes("tools:discover-all")
402
+ ? { kind: "eager" }
403
+ : {
404
+ kind: "lazy",
405
+ eager: [{ kind: "tag", tag: "essential" }],
406
+ };
407
+ };
408
+ }
409
+
410
+ const catalogExposure = {
411
+ policy: ArtifactCatalogPolicy,
412
+ } satisfies McpNestCatalogExposureOptions;
413
+ ```
414
+
415
+ Register `ArtifactCatalogPolicy` under `McpModule`'s `collaborators.providers` and assign
416
+ `catalogExposure` to the server definition.
417
+
418
+ Each lazy meta-tool closes over the exact visible snapshot belonging to that fresh server build.
419
+ Unknown and hidden names are indistinguishable to schema fetches, concurrent builds do not share
420
+ catalog state, and list/search cursors are rejected if reused after the ordered visible snapshot
421
+ changes. Deferred tools plus both meta-tools still enter the normal
422
+ `handlerAuthorization` pipeline when called. Lazy meta-tool names are reserved on every
423
+ catalog-enabled runtime. Catalog exposure cannot share a runtime with a gateway or custom
424
+ `contributors`: the SDK exposes no public tool-enumeration seam for safely projecting those
425
+ registrations, so bootstrap rejects that composition instead of silently dropping tools.
426
+
427
+ ## Live capability registration
428
+
429
+ After application bootstrap, inject the public capability service:
430
+
431
+ ```ts
432
+ import { McpCapabilitiesService } from "@nest-mcp/nestjs";
433
+
434
+ const capabilities = app.get(McpCapabilitiesService);
435
+
436
+ const refresh = capabilities.registerTool(
437
+ { name: "artifact.refresh", servers: "artifact" },
438
+ async () => ({ content: [{ type: "text" as const, text: "refreshed" }] }),
439
+ );
440
+
441
+ refresh.replace(async () => ({
442
+ content: [{ type: "text" as const, text: "refreshed-v2" }],
443
+ }));
444
+ refresh.unregister();
445
+ ```
446
+
447
+ `McpRuntimeService.capabilities` references the same service for runtime-oriented code.
448
+
449
+ `registerTool()`, `registerPrompt()`, and `registerResource()` use the same targeting, visibility,
450
+ collision, and callback types as decorators. A registration handle atomically replaces only its
451
+ callback or unregisters that exact entry; either operation returns `false` once the handle is no
452
+ longer active. Mutations use copy-on-write snapshots: a server build keeps the capabilities it
453
+ started with, while later builds see the new snapshot. Successful register, replace, and unregister
454
+ operations publish the matching tools, prompts, or resources list-change notification to every
455
+ targeted runtime.
456
+
457
+ Once runtime shutdown begins, the service is sealed: new registrations and active-handle
458
+ `replace()`/`unregister()` calls throw `McpModuleError` with code `RUNTIME_CLOSED`.
459
+
460
+ ## Validated handler pipeline
461
+
462
+ Each Nest server definition can apply policy around its decorated callbacks:
463
+
464
+ ```ts
465
+ import { Injectable, Module } from "@nestjs/common";
466
+ import {
467
+ McpModule,
468
+ allowMcpOperation,
469
+ denyMcpOperation,
470
+ type McpHandlerAuthorizationPolicy,
471
+ } from "@nest-mcp/nestjs";
472
+
473
+ @Injectable()
474
+ class ArtifactHandlerPolicy implements McpHandlerAuthorizationPolicy {
475
+ authorize: McpHandlerAuthorizationPolicy["authorize"] = (operation) => {
476
+ return operation.context.principal?.scopes.includes("artifacts:read") === true
477
+ ? allowMcpOperation({ policy: "artifact-scopes-v1" })
478
+ : denyMcpOperation("The required artifact scope is missing.");
479
+ };
480
+ }
481
+
482
+ @Module({
483
+ imports: [
484
+ McpModule.forRoot({
485
+ collaborators: {
486
+ providers: [
487
+ ArtifactHandlerPolicy,
488
+ DeadlineMiddleware,
489
+ AuditMiddleware,
490
+ ArtifactLifecycleObserver,
491
+ ],
492
+ },
493
+ servers: [
494
+ {
495
+ name: "artifact",
496
+ serverInfo: { name: "artifact", version: "1.0.0" },
497
+ handlerAuthorization: ArtifactHandlerPolicy,
498
+ handlerMiddleware: [DeadlineMiddleware, AuditMiddleware],
499
+ handlerLifecycleObserver: ArtifactLifecycleObserver,
500
+ },
501
+ ],
502
+ }),
503
+ ],
504
+ })
505
+ export class ArtifactMcpModule {}
506
+ ```
507
+
508
+ The official SDK first validates arguments and resolves the registered tool, resource, or prompt.
509
+ Nest MCP then creates `McpHandlerInvocationInput` from that trusted callback definition and the
510
+ official server context. The pipeline runs in this order:
511
+
512
+ 1. `handlerLifecycleObserver` surrounds the complete invocation and records denials.
513
+ 2. `handlerAuthorization` runs before all custom handler middleware and cannot be bypassed by a
514
+ short-circuiting middleware.
515
+ 3. `handlerMiddleware` applies application policy.
516
+ 4. The decorated provider method runs.
517
+
518
+ Transforming handler middleware is typed to the official tool, prompt, and resource result union.
519
+ For logging, tracing, and other concerns that must preserve the exact downstream result, use
520
+ `createMcpHandlerPassthroughMiddleware()`; its continuation is result-opaque and mandatory.
521
+
522
+ This handler pipeline works for HTTP and stdio. Callback arguments and results are absent from
523
+ lifecycle events, and an authenticated HTTP principal is projected without its bearer token or
524
+ arbitrary token metadata.
525
+
526
+ A server's injectable `middleware` providers are intentionally different: they surround a complete
527
+ HTTP exchange before official dispatch and do not run for stdio. Use them for exchange-level
528
+ concerns, not as the sole authorization seam for individual capabilities. A raw Node handler
529
+ mounted beside Nest routes also does not automatically execute Nest guards or interceptors.
530
+
531
+ ## Declarative Nest HTTP routes
532
+
533
+ Declare `httpRoutes` on `McpModule.forRoot()` or `forRootAsync()` to serve a named runtime without
534
+ writing a controller:
535
+
536
+ ```ts
537
+ McpModule.forRootAsync({
538
+ httpRoutes: [
539
+ {
540
+ serverName: "artifact",
541
+ path: "mcp",
542
+ decorators: [UseGuards(ArtifactRouteGuard)],
543
+ discovery: {
544
+ protectedResourcePaths: [".well-known/oauth-protected-resource/mcp"],
545
+ authorizationServerPaths: [".well-known/oauth-authorization-server/api/auth"],
546
+ decorators: [PublicRoute()],
547
+ },
548
+ },
549
+ ],
550
+ imports: [RuntimeConfigModule],
551
+ inject: [RuntimeConfigService],
552
+ collaborators: { providers: [ArtifactRouteGuard, ArtifactTokenVerifier] },
553
+ useFactory: (config: RuntimeConfigService) => ({
554
+ servers: [
555
+ {
556
+ name: "artifact",
557
+ serverInfo: { name: "artifact", version: "1.0.0" },
558
+ oauth: {
559
+ resource: {
560
+ resourceServerUrl: config.mcpUrl, // e.g. https://example.com/mcp
561
+ verifier: ArtifactTokenVerifier,
562
+ requiredScopes: ["mcp:invoke"],
563
+ metadata: { oauthMetadata: config.authorizationServerMetadata },
564
+ },
565
+ },
566
+ },
567
+ ],
568
+ }),
569
+ });
570
+ ```
571
+
572
+ `PublicRoute`, the guard, verifier, and configuration service above are application-owned. Register
573
+ providers required by route decorators in `collaborators.providers` or export them from imported
574
+ modules. Routing metadata is static: with `forRootAsync()`, put `httpRoutes` beside `useFactory`,
575
+ not in its result. Omitting `httpRoutes` registers no controllers.
576
+
577
+ Each entry creates ordinary Nest controllers using the existing MCP handler. Express and Fastify
578
+ retain Nest guards, interceptors, global prefixes, and optional `version`. The named server still
579
+ owns bearer authentication, `httpSecurity`, and capability authorization. Class `decorators` let
580
+ applications attach their existing route metadata without creating wrapper classes. Manual
581
+ `McpHttpControllerFor()` controllers and direct Node handlers remain available when needed.
582
+
583
+ Optional `discovery` serves official SDK metadata from that server's `oauth.resource.metadata`.
584
+ It does not implement authorization, consent, or token issuance. Discovery has its own decorators;
585
+ transport decorators are not copied to it. Set application public-route metadata here when global
586
+ guards otherwise require a login. Discovery is version-neutral, including when Nest has a default
587
+ version. If the application sets a global prefix, exclude the declared well-known paths using
588
+ `app.setGlobalPrefix(prefix, { exclude: paths })` so clients can find them at the origin root.
589
+
590
+ When declaring protected-resource discovery, include the exact path advertised by the resource
591
+ URL's bearer challenge: for `https://example.com/api/v1/mcp`, use
592
+ `.well-known/oauth-protected-resource/api/v1/mcp`. Additional aliases are optional. Supply
593
+ authorization-server discovery paths appropriate for the configured issuer. The SDK handles GET,
594
+ HEAD, OPTIONS, and unsupported methods. Discovery for `oauth.proxy` continues to use the explicit
595
+ proxy controller factory.
596
+
597
+ Paths must be non-empty literal paths without router patterns, dot segments, queries, or fragments.
598
+ Leading and trailing slashes are normalized; paths must be unique across all declared MCP and
599
+ discovery routes, ignoring case. Do not register a manual controller at the same path. Unknown
600
+ server names or discovery without resource metadata fail during Nest module initialization.
601
+
602
+ ## Custom Nest HTTP controller
603
+
604
+ Bind a named runtime to a normal Nest controller when MCP should participate in the application's
605
+ HTTP route pipeline:
606
+
607
+ ```ts
608
+ import { Controller, Injectable, Module, UseGuards } from "@nestjs/common";
609
+ import type { AuthInfo, OAuthTokenVerifier } from "@modelcontextprotocol/server";
610
+ import { McpHttpControllerFor, McpModule, McpRuntimeService } from "@nest-mcp/nestjs";
611
+ import type { McpServerRuntime } from "@nest-mcp/server";
612
+ import { McpResourceServer } from "@nest-mcp/server/auth";
613
+ import { McpValidatedServer } from "@nest-mcp/server/security";
614
+
615
+ @Injectable()
616
+ class ArtifactTokenVerifier implements OAuthTokenVerifier {
617
+ verifyAccessToken(token: string): Promise<AuthInfo> {
618
+ return verifyArtifactAccessToken(token);
619
+ }
620
+ }
621
+
622
+ const ArtifactMcpControllerBase = McpHttpControllerFor("artifact");
623
+
624
+ @Controller({ path: "mcp", version: "1" })
625
+ @UseGuards(ArtifactRouteGuard)
626
+ class ArtifactMcpController extends ArtifactMcpControllerBase {
627
+ constructor(
628
+ runtimeService: McpRuntimeService,
629
+ private readonly verifier: ArtifactTokenVerifier,
630
+ ) {
631
+ super(runtimeService);
632
+ }
633
+
634
+ protected override createMcpHttpHandler(runtime: McpServerRuntime) {
635
+ return new McpValidatedServer(
636
+ new McpResourceServer(runtime, {
637
+ bearerAuth: { verifier: this.verifier, requiredScopes: ["mcp:invoke"] },
638
+ }),
639
+ requestValidationOptions,
640
+ );
641
+ }
642
+ }
643
+
644
+ @Module({
645
+ imports: [McpModule.forRoot(runtimeOptions)],
646
+ controllers: [ArtifactMcpController],
647
+ providers: [ArtifactTokenVerifier],
648
+ })
649
+ export class AppModule {}
650
+ ```
651
+
652
+ The inherited catch-all route works with Express and Fastify and preserves Nest global prefixes,
653
+ versioning, guards, and interceptors while leaving HTTP method semantics to the MCP handler. Prefer
654
+ Nest guards for application route policy. `McpHttpControllerFor()` accepts only the named runtime;
655
+ the concrete controller composes framework-neutral `McpResourceServer` and `McpValidatedServer`
656
+ facades by overriding `createMcpHttpHandler()` with Nest-injected collaborators. Override
657
+ `getNodeAdapterOptions()` to observe failures in the Node/Web conversion layer through an injected
658
+ reporter.
659
+
660
+ The route inherits the runtime's HTTP security posture (`httpSecurity` on the server definition):
661
+ routable browser origins are denied by default, MCP CORS preflights are answered, and bodies are
662
+ capped at 1 MiB. Override `getHttpSecurityOptions()` on the concrete controller to replace the
663
+ posture for one route — it is enforced outside `createMcpHttpHandler()` composition, so rejected
664
+ requests never reach a composed facade. When Nest owns CORS app-wide instead, pass
665
+ `mcpCorsOptions({ origins: ["https://app.example.com"] })` to `app.enableCors()` and set
666
+ `httpSecurity: { cors: false }` so each route keeps a single CORS owner.
667
+
668
+ For a Nest-native request-level short circuit, override `interceptMcpRequest()`. Returning a value
669
+ lets Nest serialize it through the normal response pipeline; returning `undefined` delegates to MCP.
670
+ Capability calls still use `handlerAuthorization`, `handlerMiddleware`, and
671
+ `handlerLifecycleObserver`, which work identically over HTTP and stdio. A full per-capability Nest
672
+ RPC lane (request-scoped providers, parameter pipes, and exception filters) is intentionally not
673
+ emulated through private Nest internals in this release.
674
+
675
+ ## Agent gateways and observability
676
+
677
+ The Nest server's declarative `gateway` option installs a policy-enforced aggregate backed by the
678
+ module-owned clients. It projects tools, prompts, concrete resources, resource templates, and
679
+ completion while keeping downstream and upstream credentials separate. Import
680
+ `@nest-mcp/gateway` directly only when building a framework-neutral gateway.
681
+ `McpRuntimeService.clients` provides the Nest-owned named client runtime for application services
682
+ and agent orchestration.
683
+
684
+ For the common case, declare the gateway directly on a Nest server. Its upstreams resolve against
685
+ the same module-owned client registry and unknown client names fail during bootstrap:
686
+
687
+ ```ts
688
+ McpModule.forRoot({
689
+ imports: [
690
+ McpClientModule.forRoot({
691
+ servers: upstreamServers,
692
+ bootstrap: {
693
+ connectAll: true,
694
+ },
695
+ }),
696
+ ],
697
+ collaborators: { providers: [AgentGatewayPolicy] },
698
+ servers: [
699
+ {
700
+ name: "agent-gateway",
701
+ serverInfo: { name: "agent-gateway", version: "1.0.0" },
702
+ gateway: {
703
+ upstreams: ["artifact-storage", { clientName: "knowledge", gatewayName: "kb" }],
704
+ policy: AgentGatewayPolicy,
705
+ },
706
+ },
707
+ ],
708
+ });
709
+ ```
710
+
711
+ `AgentGatewayPolicy` is a default-scope provider implementing `McpGatewayPolicy`; register it under
712
+ `McpModule`'s `collaborators.providers`. The gateway resolves that token once during bootstrap. The
713
+ same applies to configured name/URI codecs, the discovery cache, authorization-context resolver,
714
+ middleware, lifecycle observer, and observer-error reporter: the `gateway` definition contains their
715
+ tokens, while `collaborators.providers` owns their singleton implementations. Numeric limits and
716
+ other passive gateway data stay inline. Raw implementations remain valid when constructing
717
+ `McpGateway` directly from `@nest-mcp/gateway`.
718
+
719
+ Gateway servers are dedicated. Do not target the same server with `@Tool`, `@Prompt`,
720
+ or `@Resource`, or configure a `contributor` that owns projected capability handlers/list-change
721
+ semantics. Nest rejects decorated or contributed handler mixing during bootstrap; the
722
+ framework-neutral gateway rejects other handler ownership with `CAPABILITY_CONFLICT` when the
723
+ per-request SDK server is built.
724
+
725
+ Because an omitted decorator target means every configured server, modules
726
+ that define a gateway alongside local servers should explicitly set `servers` on each decorated
727
+ handler. This keeps the dedicated gateway out of the handler's target set.
728
+
729
+ The string and `{ clientName }` forms deliberately treat each named `McpClientRuntime` connection
730
+ as an upstream service identity; they never forward the downstream bearer token. The same
731
+ declarative `upstreams` array can instead contain `{ name, clientProvider: ProviderToken }` when an
732
+ application needs authorization-aware token exchange or a tenant/user-owned connection. Register
733
+ an `McpGatewayClientProvider` under that token; its `resolveClient()` method receives the verified
734
+ downstream request context and must perform an audience-checked exchange or select an already
735
+ isolated client rather than forwarding the bearer token unchanged. Framework-neutral callers can
736
+ still pass a complete raw upstream directly to `McpGateway` from `@nest-mcp/gateway`.
737
+
738
+ After bootstrap, `McpRuntimeService.gateway(serverName)` returns the gateway owned by that inbound
739
+ server, including `invalidateDiscovery()`. `listGateways()` provides a frozen operational snapshot.
740
+ Application shutdown closes inbound server handlers, then their gateways, then upstream client
741
+ connections. Gateway shutdown cancels accepted work before client ownership is released.
742
+ Nest lifecycle cleanup contains errors so adapter disposal can finish; `shutdownError` retains the aggregate,
743
+ while an explicit `runtime.close()` rejects when the host wants strict cleanup handling.
744
+ Call `app.enableShutdownHooks()` when process signals should invoke this lifecycle. Bootstrap failure rolls
745
+ back any client/server runtimes that were already initialized.
746
+
747
+ Resource templates and prompt/template completion are projected by the gateway. Transparent
748
+ `input_required` relaying and notification bridging remain explicit future layers because they
749
+ require sealed route-bound state and long-lived, authorization-partitioned subscription
750
+ coordination.
751
+
752
+ `@nest-mcp/observability` provides bounded structured-log and metrics observers plus tracing
753
+ middleware. Import it directly, then adapt its observers behind injectable server or client
754
+ collaborator tokens. Client observers are referenced from `McpClientModule`'s `runtime.observer`
755
+ option. The default attribute projection excludes principals, payloads, request/session identifiers,
756
+ error messages, stacks, and credentials.
757
+
758
+ For HTTP bearer authentication and protected-resource metadata, construct `McpResourceServer` from
759
+ `@nest-mcp/server/auth` around the mounted runtime. OAuth authentication establishes identity;
760
+ `handlerAuthorization` still decides whether that identity may invoke a specific capability.
761
+
762
+ ### Native tools with a gateway
763
+
764
+ Set `gateway.composition: "tools"` on a server to expose its decorated or dynamic
765
+ local handlers alongside gateway tools on the same authenticated transport. The
766
+ gateway installs only tools and retains its own authorization policy; local
767
+ handlers keep `handlerAuthorization`. Local prompts and resources remain local.
768
+ Gateway tool names must be distinct from local names: duplicate SDK registrations
769
+ fail instead of shadowing either tool. The default gateway mode remains dedicated.