@lenne.tech/nest-server 12.9.4 → 12.10.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.
Files changed (145) hide show
  1. package/.claude/rules/configurable-features.md +4 -0
  2. package/.claude/rules/package-management.md +29 -5
  3. package/.claude/rules/role-system.md +12 -0
  4. package/.claude/rules/testing.md +4 -4
  5. package/CLAUDE.md +10 -1
  6. package/FRAMEWORK-API.md +2 -1
  7. package/dist/core/common/decorators/rest-user.decorator.js +4 -0
  8. package/dist/core/common/decorators/rest-user.decorator.js.map +1 -1
  9. package/dist/core/common/filters/http-exception-log.filter.js +3 -0
  10. package/dist/core/common/filters/http-exception-log.filter.js.map +1 -1
  11. package/dist/core/common/helpers/context.helper.js +9 -0
  12. package/dist/core/common/helpers/context.helper.js.map +1 -1
  13. package/dist/core/common/helpers/decorator.helper.js +4 -0
  14. package/dist/core/common/helpers/decorator.helper.js.map +1 -1
  15. package/dist/core/common/helpers/execution-context-request.helper.d.ts +14 -1
  16. package/dist/core/common/helpers/execution-context-request.helper.js +36 -0
  17. package/dist/core/common/helpers/execution-context-request.helper.js.map +1 -1
  18. package/dist/core/common/helpers/graphql-upload.helper.d.ts +8 -0
  19. package/dist/core/common/helpers/graphql-upload.helper.js +206 -0
  20. package/dist/core/common/helpers/graphql-upload.helper.js.map +1 -0
  21. package/dist/core/common/interceptors/translate-response.interceptor.js +4 -0
  22. package/dist/core/common/interceptors/translate-response.interceptor.js.map +1 -1
  23. package/dist/core/common/interfaces/server-options.interface.d.ts +11 -0
  24. package/dist/core/common/middleware/request-context.middleware.js +3 -0
  25. package/dist/core/common/middleware/request-context.middleware.js.map +1 -1
  26. package/dist/core/common/services/request-context.service.d.ts +2 -0
  27. package/dist/core/common/services/request-context.service.js +3 -0
  28. package/dist/core/common/services/request-context.service.js.map +1 -1
  29. package/dist/core/modules/ai/core-ai-mcp.controller.js +4 -2
  30. package/dist/core/modules/ai/core-ai-mcp.controller.js.map +1 -1
  31. package/dist/core/modules/ai/core-ai.constants.d.ts +1 -0
  32. package/dist/core/modules/ai/core-ai.constants.js +1 -0
  33. package/dist/core/modules/ai/core-ai.constants.js.map +1 -1
  34. package/dist/core/modules/ai/core-ai.module.js +2 -0
  35. package/dist/core/modules/ai/core-ai.module.js.map +1 -1
  36. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.d.ts +8 -0
  37. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js +8 -0
  38. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js.map +1 -0
  39. package/dist/core/modules/ai/helpers/ai-verified-user.helper.d.ts +12 -0
  40. package/dist/core/modules/ai/helpers/ai-verified-user.helper.js +23 -0
  41. package/dist/core/modules/ai/helpers/ai-verified-user.helper.js.map +1 -0
  42. package/dist/core/modules/ai/index.d.ts +8 -0
  43. package/dist/core/modules/ai/index.js +8 -0
  44. package/dist/core/modules/ai/index.js.map +1 -1
  45. package/dist/core/modules/ai/interfaces/llm-provider.interface.d.ts +1 -0
  46. package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js +2 -0
  47. package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js.map +1 -1
  48. package/dist/core/modules/ai/providers/ai-egress.helper.d.ts +6 -0
  49. package/dist/core/modules/ai/providers/ai-egress.helper.js +58 -0
  50. package/dist/core/modules/ai/providers/ai-egress.helper.js.map +1 -0
  51. package/dist/core/modules/ai/providers/ai-sdk.packages.d.ts +16 -0
  52. package/dist/core/modules/ai/providers/ai-sdk.packages.js +99 -0
  53. package/dist/core/modules/ai/providers/ai-sdk.packages.js.map +1 -0
  54. package/dist/core/modules/ai/providers/ai-sdk.provider.d.ts +51 -0
  55. package/dist/core/modules/ai/providers/ai-sdk.provider.js +244 -0
  56. package/dist/core/modules/ai/providers/ai-sdk.provider.js.map +1 -0
  57. package/dist/core/modules/ai/providers/llm-provider.factory.d.ts +11 -1
  58. package/dist/core/modules/ai/providers/llm-provider.factory.js +44 -3
  59. package/dist/core/modules/ai/providers/llm-provider.factory.js.map +1 -1
  60. package/dist/core/modules/ai/providers/openai-compatible.provider.js +4 -21
  61. package/dist/core/modules/ai/providers/openai-compatible.provider.js.map +1 -1
  62. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.d.ts +34 -0
  63. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js +130 -0
  64. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js.map +1 -0
  65. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.d.ts +28 -3
  66. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js +141 -15
  67. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js.map +1 -1
  68. package/dist/core/modules/ai/services/core-ai-mcp.service.js +2 -1
  69. package/dist/core/modules/ai/services/core-ai-mcp.service.js.map +1 -1
  70. package/dist/core/modules/ai/services/core-ai.service.js +2 -7
  71. package/dist/core/modules/ai/services/core-ai.service.js.map +1 -1
  72. package/dist/core/modules/ai/tools/ai-tool-result.helper.d.ts +2 -0
  73. package/dist/core/modules/ai/tools/ai-tool-result.helper.js +117 -0
  74. package/dist/core/modules/ai/tools/ai-tool-result.helper.js.map +1 -0
  75. package/dist/core/modules/ai/tools/ai-tool-schema.helper.d.ts +36 -0
  76. package/dist/core/modules/ai/tools/ai-tool-schema.helper.js +81 -0
  77. package/dist/core/modules/ai/tools/ai-tool-schema.helper.js.map +1 -0
  78. package/dist/core/modules/ai/tools/ai-tool.registry.js +2 -1
  79. package/dist/core/modules/ai/tools/ai-tool.registry.js.map +1 -1
  80. package/dist/core/modules/auth/guards/auth.guard.js +10 -2
  81. package/dist/core/modules/auth/guards/auth.guard.js.map +1 -1
  82. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js +4 -1
  83. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js.map +1 -1
  84. package/dist/core/modules/auth/guards/roles.guard.js +11 -1
  85. package/dist/core/modules/auth/guards/roles.guard.js.map +1 -1
  86. package/dist/core/modules/better-auth/better-auth-roles.guard.js +15 -1
  87. package/dist/core/modules/better-auth/better-auth-roles.guard.js.map +1 -1
  88. package/dist/core/modules/better-auth/better-auth.config.js +78 -0
  89. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  90. package/dist/core/modules/tenant/core-tenant.guard.js +9 -1
  91. package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
  92. package/dist/core.module.js +2 -1
  93. package/dist/core.module.js.map +1 -1
  94. package/dist/index.d.ts +1 -0
  95. package/dist/index.js +1 -0
  96. package/dist/index.js.map +1 -1
  97. package/dist/types/graphql-upload.d.ts +34 -2
  98. package/docs/REQUEST-LIFECYCLE.md +46 -9
  99. package/migration-guides/12.9.3-to-12.9.4.md +3 -1
  100. package/migration-guides/12.9.x-to-12.10.x.md +271 -0
  101. package/package.json +46 -21
  102. package/src/core/common/decorators/rest-user.decorator.ts +6 -0
  103. package/src/core/common/filters/http-exception-log.filter.ts +8 -0
  104. package/src/core/common/helpers/context.helper.ts +14 -0
  105. package/src/core/common/helpers/decorator.helper.ts +5 -0
  106. package/src/core/common/helpers/execution-context-request.helper.ts +97 -1
  107. package/src/core/common/helpers/graphql-upload.helper.ts +427 -0
  108. package/src/core/common/interceptors/translate-response.interceptor.ts +8 -0
  109. package/src/core/common/interfaces/server-options.interface.ts +98 -0
  110. package/src/core/common/middleware/request-context.middleware.ts +3 -0
  111. package/src/core/common/services/request-context.service.ts +11 -0
  112. package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +16 -0
  113. package/src/core/modules/ai/README.md +101 -0
  114. package/src/core/modules/ai/core-ai-mcp.controller.ts +7 -2
  115. package/src/core/modules/ai/core-ai.constants.ts +4 -0
  116. package/src/core/modules/ai/core-ai.module.ts +3 -0
  117. package/src/core/modules/ai/decorators/ai-agent-function.decorator.ts +44 -0
  118. package/src/core/modules/ai/helpers/ai-verified-user.helper.ts +47 -0
  119. package/src/core/modules/ai/index.ts +8 -0
  120. package/src/core/modules/ai/interfaces/ai-tool.interface.ts +5 -1
  121. package/src/core/modules/ai/interfaces/llm-provider.interface.ts +6 -0
  122. package/src/core/modules/ai/models/core-ai-mcp-oauth.models.ts +4 -0
  123. package/src/core/modules/ai/providers/ai-egress.helper.ts +98 -0
  124. package/src/core/modules/ai/providers/ai-sdk.packages.ts +153 -0
  125. package/src/core/modules/ai/providers/ai-sdk.provider.ts +383 -0
  126. package/src/core/modules/ai/providers/llm-provider.factory.ts +93 -2
  127. package/src/core/modules/ai/providers/openai-compatible.provider.ts +5 -23
  128. package/src/core/modules/ai/services/core-ai-agent-function.bridge.ts +170 -0
  129. package/src/core/modules/ai/services/core-ai-mcp-oauth.service.ts +240 -20
  130. package/src/core/modules/ai/services/core-ai-mcp.service.ts +3 -1
  131. package/src/core/modules/ai/services/core-ai.service.ts +5 -7
  132. package/src/core/modules/ai/tools/ai-tool-result.helper.ts +153 -0
  133. package/src/core/modules/ai/tools/ai-tool-schema.helper.ts +134 -0
  134. package/src/core/modules/ai/tools/ai-tool.registry.ts +6 -1
  135. package/src/core/modules/auth/guards/auth.guard.ts +19 -2
  136. package/src/core/modules/auth/guards/legacy-auth-rate-limit.guard.ts +9 -2
  137. package/src/core/modules/auth/guards/roles.guard.ts +23 -1
  138. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +11 -0
  139. package/src/core/modules/better-auth/README.md +204 -0
  140. package/src/core/modules/better-auth/better-auth-roles.guard.ts +29 -1
  141. package/src/core/modules/better-auth/better-auth.config.ts +138 -1
  142. package/src/core/modules/tenant/core-tenant.guard.ts +13 -1
  143. package/src/core.module.ts +5 -1
  144. package/src/index.ts +1 -0
  145. package/src/types/graphql-upload.d.ts +34 -2
@@ -185,6 +185,7 @@ JWT-based authentication for existing projects:
185
185
  | **REST Endpoints** | `GET /ai/status` (public, `{ mcp }`; the route does not exist while the module is off, so it answers 404 — 12.3.1), `POST /ai/prompt`, `POST /ai/stream` (SSE); `GET/POST/PUT/DELETE /ai/connections*`, `/ai/connections/available`, `/ai/connections/select`, `/ai/connections/preferences*`, `/ai/conversations*`, `/ai/interactions*`, `/ai/budget-limits*`, `GET /ai/usage` |
186
186
  | **GraphQL Endpoints** | `aiPrompt`, `aiAvailableConnections`, `aiSetUserConnection`, connection/preference/conversation/interaction/budget queries + mutations, `aiUsage` |
187
187
  | **MCP Server** | Streamable HTTP at `POST/GET/DELETE /ai/mcp` (Bearer auth; with `ai.mcp.stateless` (12.3.0+) a server and transport per POST, no session, GET / DELETE 405, so any replica answers; `tools/call` runs the admin's tool policies, `authorize()` and the elicitation confirmation (12.3.0+) — refused for tools needing confirmation in stateless mode); a user the controller resolves itself (the OAuth access token, which only this controller accepts, after the guards ran without a user) gets `req.user` and the tenant the header names from an active membership only, through `CoreTenantGuard.resolveMembershipContext()` (11.43.3); with `ai.mcp.oauth` an OAuth 2.1 router (`/.well-known/*`, `/authorize`, `/token`, `/register`) that `CoreAiMcpOAuthInitializer` mounts during `app.init()` — an Express router behind the Nest middleware and routes, ahead of Nest's not-found handler, so guards and interceptors do not run for it; `/authorize` answers with a built-in consent page (the Better-Auth session from the middleware is the user; Allow is a CSRF-bound POST); `ai.mcp.roles` / an overridden `mayUseMcp()` (12.8.6+) decide who may use MCP at all, checked on every `/ai/mcp` request whatever the credential (403), on the consent route (refusal notice, 403) and on `/token` (`invalid_grant`); a project's own notice on the consent route goes through `sendConsentNotice()`, which applies the same security headers |
188
+ | **NestJS AI interop (12.10.0)** | `providerType: 'nestjs-ai'` connections call a model registered in `@nestjs/ai`'s `AiModule.forRoot({ models })` through the AI SDK, wrapped in `@nestjs/resilience` retries + timeout; `LlmProviderFactory.registerAiSdkModel()` runs database-managed connections on an AI SDK model a project builds (with a `fetch` held to `ai.allowedBaseUrlHosts`). Native tools go to the model WITHOUT `execute`, so the AI SDK returns the calls and the module's gates run them. `ai.agentFunctions` offers `@AgentFunction()` methods as tools: the module's gates first, then `@nestjs/ai`'s pipeline with the run's HTTP request (`RequestContext.getRequest()`) as caller. `CoreAiMcpOAuthService.createMcpTokenVerifier()` lets a project's `@nestjs/mcp` endpoint accept the MCP OAuth access tokens issued for it — tokens are bound to their resource (RFC 8707: `resource` at `/authorize` and `/token`, `aud` in the token; `/ai/mcp` refuses one for another resource, tokens from before 12.10.0 are valid at `/ai/mcp` only, an unknown resource is `invalid_target`). The 0.x packages are optional peers, loaded lazily and refused outside their tested range (`AI_SDK_TESTED_RANGES`) |
188
189
  | **Permission Model** | `S_EVERYONE` for `GET /ai/status` only (no user data, no request input; API tokens refused as on every route without `@ApiTokenScopes()`); `S_USER` for prompt/conversations/available/usage; `ADMIN` for connections/preferences/interactions/budgets; encrypted API keys never leave the server (`securityCheck` + `secretFields`); a prompt continues only the caller's own conversation — a foreign or unknown `conversationId` counts as none, admins included (`CoreAiService.scopeConversation()`, 12.3.0) |
189
190
 
190
191
  ### Email & Templates
@@ -219,7 +220,7 @@ JWT-based authentication for existing projects:
219
220
  | **Subscription re-check** | Since 11.42.3 that context is not trusted for the life of the socket. Every connection a `CoreModule` `onConnect` accepts is registered (`registerWsConnection()`) and checked again — at once on an invalidation (tenant guard, role change, password reset, Better-Auth deleting the session), otherwise before the next operation or event once `graphQl.subscriptionRevalidationMs` (30 s) has passed. The check re-runs the handshake's authentication and the tenant resolution; a connection whose rights changed is closed with 4403 (retried by the graphql-ws client, which then reconnects with its current rights) and the event that triggered the check is dropped. Before, a removed membership, a deactivated tenant, a withdrawn role or a revoked session kept receiving events on an open socket until the client reconnected. See `.claude/rules/role-system.md` → "Open WebSockets" |
220
221
  | **Complexity Analysis** | Query cost calculation to prevent DoS attacks |
221
222
  | **Enum Registration** | `registerEnum()` helper for GraphQL enum types |
222
- | **Upload Support** | `graphqlUploadExpress()` for multipart file uploads |
223
+ | **Upload Support** | `graphqlUploadExpress()` for multipart file uploads, with the framework's `processGraphQlUploadRequest` (graphql-upload's parser with the GHSA-5vm7-vc2x-p3w2 and GHSA-qwwm-252j-9whw fixes, since 12.10.0) |
223
224
 
224
225
  ### Development & Operations
225
226
 
@@ -370,6 +371,7 @@ The following diagram shows the exact order of execution from HTTP request to re
370
371
  | |
371
372
  | 3. graphqlUploadExpress() [GraphQL only] |
372
373
  | - Handles multipart file uploads |
374
+ | - processGraphQlUploadRequest: bad map path -> 400 |
373
375
  +----------------------------+----------------------------+
374
376
  |
375
377
  +----------------------------v----------------------------+
@@ -605,7 +607,7 @@ configure(consumer: MiddlewareConsumer) {
605
607
  consumer.apply(RequestContextMiddleware).forRoutes('*');
606
608
  consumer.apply(StringCookiesMiddleware).forRoutes('*');
607
609
  consumer.apply(SecurityHeadersMiddleware).forRoutes('*');
608
- consumer.apply(graphqlUploadExpress()).forRoutes('graphql');
610
+ consumer.apply(graphqlUploadExpress({ processRequest: processGraphQlUploadRequest })).forRoutes('graphql');
609
611
  }
610
612
  ```
611
613
 
@@ -761,6 +763,15 @@ session cookie riding along can never turn a token request into a session reques
761
763
 
762
764
  Only for GraphQL routes. Handles multipart file upload requests according to the [GraphQL multipart request specification](https://github.com/jaydenseric/graphql-multipart-request-spec).
763
765
 
766
+ It runs before every guard, so whatever it parses comes from an anonymous client. Since 12.10.0 `CoreModule` passes
767
+ the framework's `processGraphQlUploadRequest` (`common/helpers/graphql-upload.helper.ts`) instead of graphql-upload's
768
+ own `processRequest`: graphql-upload 17.1.0's parser with both hunks of the fix in graphql-upload 18.0.2 (which needs
769
+ graphql 17). A `map` path with a `__proto__` key, or one that goes through an already placed upload, is answered with
770
+ 400 "Invalid object path" (GHSA-5vm7-vc2x-p3w2 — before, `{"1":["variables.file"],"2":["variables.file.reject"]}`
771
+ without file fields made the parser throw an uncaught `TypeError` and the process exit), and a second file field with
772
+ the name of an already resolved upload is ignored (GHSA-qwwm-252j-9whw — before, its temporary file leaked). A project
773
+ that registers `graphqlUploadExpress()` itself passes `{ processRequest: processGraphQlUploadRequest }` too.
774
+
764
775
  > **NestJS docs:** [Middleware](https://docs.nestjs.com/middleware)
765
776
 
766
777
  ---
@@ -1690,13 +1701,39 @@ export class UserService extends CoreUserService<User> {
1690
1701
 
1691
1702
  ### Guard Context Detection
1692
1703
 
1693
- Guards handle both REST and GraphQL contexts:
1694
-
1695
- ```typescript
1696
- // Inside RolesGuard
1697
- const gqlContext = GqlExecutionContext.create(context).getContext();
1698
- const request = gqlContext?.req || context.switchToHttp().getRequest();
1699
- ```
1704
+ Guards, interceptors and the `@CurrentUser()` decorator resolve the request through ONE helper,
1705
+ `resolveGuardRequest()` (`common/helpers/execution-context-request.helper.ts`), for every transport:
1706
+
1707
+ | Context type | Request a guard decides on |
1708
+ |--------------|----------------------------|
1709
+ | `http` | `context.switchToHttp().getRequest()` |
1710
+ | `graphql` (HTTP) | `GqlExecutionContext.create(context).getContext().req` |
1711
+ | `graphql` (WebSocket subscription) | the graphql-ws context `CoreModule`'s `onConnect` recorded the user on |
1712
+ | `ai` (`@nestjs/ai` agent function, 12.10.0) | `args[1].request` — the HTTP request the call runs in (`caller.request`) |
1713
+ | `mcp` (`@nestjs/mcp` tool / resource / prompt, 12.10.0) | `args[1].request`; without `request.user`, the user `createMcpTokenVerifier()` verified |
1714
+
1715
+ ### Agent function and MCP calls (`'ai'` / `'mcp'`, 12.10.0)
1716
+
1717
+ `@nestjs/ai` and `@nestjs/mcp` wrap their methods with Nest's `ExternalContextCreator`, so every GLOBAL guard,
1718
+ interceptor, pipe and filter of the application runs around them — the framework's included, in any project that
1719
+ installs either package. Their arguments are `[input, call]`: index 0 is what the MODEL or the MCP CLIENT wrote, index 1
1720
+ the call object the package built from server code.
1721
+
1722
+ | Layer | On `'ai'` / `'mcp'` |
1723
+ |-------|---------------------|
1724
+ | `RolesGuard`, `BetterAuthRolesGuard`, `AuthGuard()`, `CoreTenantGuard`, API-token enforcement, legacy rate limit | decide on `call.request` exactly as over HTTP, tenant context included — never on index 0. Before 12.10.0 the HTTP fallback returned index 0, so tool arguments `{ "user": { "roles": ["admin"] } }` were the authenticated caller |
1725
+ | Request-less caller (`caller: { user, scopes }`, a durable run, MCP over stdio) | **anonymous**: `caller.user` is data nothing authenticated. Public methods (`S_EVERYONE`, no `@Roles()`) run, every other one is refused with 401 — by every guard, the tenant guard included ("no request" is never permission) |
1726
+ | `CheckResponseInterceptor`, `CheckSecurityInterceptor` (`getContextData()`) | filter the result for `call.request.user` (anonymous without a request) — `@Restricted` fields and secret fields never reach the model |
1727
+ | `ResponseModelInterceptor` | unchanged (no HTTP access) |
1728
+ | `TranslateResponseInterceptor` | passes the result through (it shapes responses for a reader's language) |
1729
+ | `HttpExceptionLogFilter`, `MongooseCastErrorFilter` | return nothing, so the package tells the model / client the exception's message — they never touch an HTTP response there |
1730
+ | `@CurrentUser()`, `@RESTUser()` | `call.request.user` |
1731
+
1732
+ The AI module's own tool results (chat loop and `/ai/mcp` `tools/call`) pass `sanitizeToolResultForModel()`:
1733
+ `securityCheck(user)` on every model instance at any depth (inside arrays and plain wrappers such as `{ success, data }`),
1734
+ then every secret field (`security.secretFields` and the framework defaults, also under their SQL column names) leaves
1735
+ the result — a Mongoose document through its stripped `toJSON()`. An MCP OAuth user is shaped like a middleware user
1736
+ (`toVerifiedAiUser()`: `hasRole()`, `_authenticatedViaBetterAuth`), so role guards and `securityCheck()` work with it.
1700
1737
 
1701
1738
  > **NestJS docs:** [REST Controllers](https://docs.nestjs.com/controllers), [GraphQL Resolvers](https://docs.nestjs.com/graphql/resolvers)
1702
1739
 
@@ -108,7 +108,9 @@ needs no authentication, and every application with GraphQL subscriptions accept
108
108
  exact-pins at 8.22.1. nest-server's own `overrides:` do not reach your install (`docs/security-overrides.md`), so put the
109
109
  entry into your project's `pnpm-workspace.yaml` and run `pnpm install`. A nest-server-starter based project already has
110
110
  an 8.x entry, `'ws@>=8.0.0 <8.22.1': 8.22.1`: **replace** it, do not only raise its target — its key does not match
111
- the exact `8.22.1` that `@nestjs/graphql` requests, so the vulnerable copy would stay. The 7.x entry stays as it is.
111
+ the exact `8.22.1` that `@nestjs/graphql` requests, so the vulnerable copy would stay. Its 7.x entry
112
+ `'ws@>=7.0.0 <7.5.13': 7.5.13` is a pre-emptive floor for projects that add `subscriptions-transport-ws`; 7.5.13 is
113
+ covered by the same advisory (patched 7.5.14), so raise it to `'ws@>=7.0.0 <7.5.14': '7.5.14'` as well.
112
114
 
113
115
  ```yaml
114
116
  overrides:
@@ -0,0 +1,271 @@
1
+ # Migration Guide: 12.9.x → 12.10.x
2
+
3
+ > **This minor contains breaking changes** (see "Breaking Changes"): secret fields no longer reach the model, the client
4
+ > or an MCP client through an AI tool result; a failed OAuth sign-in without its own error URL lands on the app's login
5
+ > page instead of Better-Auth's error page; a `socialProviders.<name>.scope` that is neither a string nor a list is
6
+ > ignored. The MAJOR digit follows NestJS, so a breaking change ships as a minor here — read this guide before updating.
7
+
8
+ ## Overview
9
+
10
+ | Category | Details |
11
+ |----------|---------|
12
+ | **Breaking Changes** | (1) Failed OAuth sign-ins without their own error URL, and `GET /iam/error`, now land on `<appUrl>/auth/login?error=<code>` (`betterAuth.errorUrl`, `false` restores Better-Auth's page). (2) A `socialProviders.<name>.scope` that is neither a string nor a list is ignored with an error at boot. (3) AI tool results lose every secret field (`password`, `verificationToken`, `passwordResetToken`, `passwordResetTokenExpiresAt`, `refreshTokens`, `tempTokens`, `apiKeyEncrypted`, `security.secretFields`, each also as its SQL column) — in the chat loop, in `actions[].result` and in `/ai/mcp` `tools/call` |
13
+ | **Security fixes** | GraphQL multipart uploads: one anonymous request to `/graphql` could crash the process (graphql-upload GHSA-5vm7-vc2x-p3w2, high), and duplicate file fields leaked temporary files (GHSA-qwwm-252j-9whw, medium) — fixed by the framework's own parser, no action needed (see "Security: GraphQL multipart uploads"). MCP OAuth tokens are bound to their resource (RFC 8707). With `@nestjs/ai` or `@nestjs/mcp` installed, the framework's global guards decided agent function / MCP tool calls on the tool ARGUMENTS (`switchToHttp()` is index 0 there): `{ "user": { "roles": ["admin"] } }` in a model's tool call was the authenticated caller. Now the request the call runs in decides; a request-less caller is anonymous |
14
+ | **New Features** | Social provider options reach Better-Auth (`tenantId`, `scope`, `prompt`, `mapProfileToUser`, …), `scope` from an environment variable, `betterAuth.errorUrl`; AI SDK transport (`providerType: 'nestjs-ai'`, `LlmProviderFactory.registerAiSdkModel()`), `@AgentFunction()` methods as AI tools (`ai.agentFunctions`, `@AiAgentFunction()`), Standard Schema tool parameters, `CoreAiMcpOAuthService.createMcpTokenVerifier()` for a `@nestjs/mcp` endpoint, `RequestContext.getRequest()`, `LlmCompletionOptions.abortSignal` |
15
+ | **Bugfixes** | `HttpExceptionLogFilter` no longer throws on non-HTTP transports (the model read "Internal server error" for every refusal of an agent function) |
16
+ | **Migration Effort** | ~5 minutes: check that the app has `/auth/login` (or set `betterAuth.errorUrl`), and that no AI tool returns a secret-named field on purpose |
17
+
18
+ ## Quick Migration
19
+
20
+ ```bash
21
+ pnpm add @lenne.tech/nest-server@12.10.x
22
+ pnpm run update # only if you use the starter's update script
23
+ pnpm run build
24
+ pnpm test
25
+ ```
26
+
27
+ No new dependency is required. `ai`, `@nestjs/ai` and `@nestjs/resilience` are new **optional** peers — install them
28
+ only for the integrations below.
29
+
30
+ ## Security: GraphQL multipart uploads (graphql-upload GHSA-5vm7-vc2x-p3w2, GHSA-qwwm-252j-9whw)
31
+
32
+ **No action needed** unless the project registers `graphqlUploadExpress()` itself (below).
33
+
34
+ `CoreModule` registers graphql-upload's `graphqlUploadExpress()` for `/graphql`, in front of every guard. Up to 12.9.x
35
+ it ran graphql-upload's own `processRequest`, which accepted any object path in the multipart `map` field:
36
+
37
+ - **GHSA-5vm7-vc2x-p3w2 (high):** a path into an upload placed by an earlier entry replaced one of its methods. A
38
+ request with `map={"1":["variables.file"],"2":["variables.file.reject"]}` and no file fields made the parser throw
39
+ `TypeError: upload.reject is not a function` outside any request — an uncaught exception, on which the process
40
+ exits (`installProcessDiagnostics()` exits 1, as Node does without it). **One anonymous request took the server
41
+ down.** A path with a `__proto__` key let a client-supplied object pass the `GraphQLUpload` scalar's check.
42
+ - **GHSA-qwwm-252j-9whw (medium):** a second file field with the name of an already resolved upload created another
43
+ temporary file and dropped the reference to the first, which was never deleted — temporary files and file
44
+ descriptors leaked per request.
45
+
46
+ graphql-upload fixed both in 18.0.2, which requires graphql 17; this framework runs graphql 16. 12.10.0 therefore
47
+ ships `processGraphQlUploadRequest` (`common/helpers/graphql-upload.helper.ts`): graphql-upload 17.1.0's parser with
48
+ both upstream fixes, and `CoreModule` passes it to `graphqlUploadExpress()`. Such a `map` path is answered with 400
49
+ "Invalid object path", a duplicate file field is ignored. graphql-upload stays at 17.1.0 for its scalar and middleware.
50
+
51
+ **A project that registers `graphqlUploadExpress()` itself** (its own route, its own limits) passes the framework's
52
+ parser — graphql-upload's default is the vulnerable one:
53
+
54
+ ```typescript
55
+ import { processGraphQlUploadRequest } from '@lenne.tech/nest-server';
56
+ import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.mjs';
57
+
58
+ consumer
59
+ .apply(graphqlUploadExpress({ maxFiles: 10, maxFileSize: 10_000_000, processRequest: processGraphQlUploadRequest }))
60
+ .forRoutes('graphql');
61
+ ```
62
+
63
+ Find such registrations with `grep -rn "graphqlUploadExpress(" src/`. A project that calls graphql-upload's
64
+ `processRequest` directly switches to `processGraphQlUploadRequest` (same signature and options).
65
+
66
+ **Behaviour change:** a GraphQL variable literally named `__proto__` that receives a file is refused with 400 (input
67
+ object fields cannot use that name; names starting with `__` are reserved).
68
+
69
+ ## What's New in 12.10.x
70
+
71
+ ### 0. Social sign-in: provider options and the error page (Better-Auth)
72
+
73
+ - **Provider options reach Better-Auth.** Until 12.9.4 `buildSocialProviders()` handed a provider only `clientId`,
74
+ `clientSecret` and `disableSignUp`; `tenantId`, `scope` and every other option were dropped without a word (a Microsoft
75
+ sign-in ran against `common` with Better-Auth's default scopes). Every option on `betterAuth.socialProviders.<name>`
76
+ except `enabled` is now passed on; the computed `clientId` / `clientSecret` / `disableSignUp` are written last, so a
77
+ string `disableSignUp` from `NEST_SERVER_CONFIG` still cannot open a closed registration.
78
+ - **`scope` from an environment variable works.** `NSC__…__SCOPE=openid,profile,email` is split on commas or spaces.
79
+ - **`betterAuth.errorUrl`** (`string | false`, default `<appUrl>/auth/login`; a path is resolved against the app URL)
80
+ becomes Better-Auth's `onAPIError.errorURL`. `options.onAPIError` is merged; its own `errorURL` wins.
81
+
82
+ ```typescript
83
+ betterAuth: {
84
+ errorUrl: '/auth/login', // default; false keeps Better-Auth's page on the API host
85
+ socialProviders: {
86
+ microsoft: { clientId, clientSecret, tenantId: '<tenant-id>', scope: 'openid,profile,email' },
87
+ },
88
+ },
89
+ ```
90
+
91
+ A login page maps the `error` query code to its own text and never renders `error_description` — anyone can set it
92
+ through a link to `/iam/error`. Details: [Better-Auth README](../src/core/modules/better-auth/README.md), "Social
93
+ providers".
94
+
95
+ ### 1. Global guards on `@nestjs/ai` and `@nestjs/mcp` calls
96
+
97
+ `@nestjs/ai` (`@AgentFunction()`) and `@nestjs/mcp` (`@Tool()`, `@Resource()`, `@Prompt()`) run every global guard,
98
+ interceptor and filter around their methods with the context types `'ai'` / `'mcp'`. The framework now resolves the
99
+ request of such a call from the call object (`caller.request`, `McpContext.request`):
100
+
101
+ - `@Roles()` on an agent function or MCP tool is decided against the request's user exactly as over HTTP, tenant
102
+ header included.
103
+ - A **request-less** caller — `caller: { user, scopes }` (a queue job), a durable run, MCP over stdio — is
104
+ **anonymous**: public methods run, every other one is refused with 401. To run a role-gated agent function from a job,
105
+ authenticate there and pass a request (`caller: { request }`).
106
+ - `@Restricted` and secret-field filtering apply to the result for the request's user.
107
+
108
+ Nothing to do unless you relied on the old behaviour (which read the tool arguments).
109
+
110
+ ### 2. AI SDK transport
111
+
112
+ ```typescript
113
+ // A model of @nestjs/ai's AiModule.forRoot({ models }): create a connection with
114
+ // providerType 'nestjs-ai', model 'default' (the registered name), baseUrl 'nestjs-ai:default'.
115
+
116
+ // Or any AI SDK provider for database-managed connections:
117
+ await llmProviderFactory.registerAiSdkModel('anthropic', (connection, { fetch }) =>
118
+ createAnthropic({ apiKey: connection.apiKey, fetch })(connection.model),
119
+ );
120
+ ```
121
+
122
+ Requires `ai` (`>=7.0.0 <8`); `nestjs-ai` additionally `@nestjs/ai` (`>=0.0.2 <0.0.3`) and `@nestjs/resilience`
123
+ (`>=0.0.3 <0.0.4`). Outside these ranges the call / boot fails with `AiSdkPackageError` naming the range. Hand the
124
+ provider the `fetch` from the builder context, or `ai.allowedBaseUrlHosts` does not cover it.
125
+
126
+ ### 3. Agent functions as AI tools
127
+
128
+ ```typescript
129
+ // config.env.ts
130
+ ai: { agentFunctions: true }, // or { include: ['cancel_booking'] } / { exclude: [...] }
131
+
132
+ // on the method
133
+ @AgentFunction({ name: 'cancel_booking', description: 'Cancel a booking', inputSchema: z.object({ id: z.string() }) })
134
+ @AiAgentFunction({ destructive: true })
135
+ @Roles(RoleEnum.S_USER)
136
+ cancel({ id }: { id: string }) { ... }
137
+ ```
138
+
139
+ The AI module's gates run first (role filter, policies and grants, `authorize()`, confirmation, plan mode, budgets),
140
+ then `@nestjs/ai`'s pipeline with the run's HTTP request. Roles default to the method's `@Roles()`, else `S_USER`.
141
+
142
+ ### 4. Standard Schema tool parameters
143
+
144
+ ```typescript
145
+ readonly parameters = z.object({ id: z.string() }) as any; // Zod 4.2+, ArkType, Valibot via toStandardJsonSchema()
146
+ ```
147
+
148
+ The registry stores the JSON Schema and validates the arguments before `authorize()` and `execute()`.
149
+
150
+ ### 5. A `@nestjs/mcp` endpoint with the framework's MCP OAuth server
151
+
152
+ `CoreAiMcpOAuthService.createMcpTokenVerifier({ resource })` returns a verifier for `McpModule`'s `auth.verifier`
153
+ (module README → "Your own `@nestjs/mcp` endpoint").
154
+
155
+ ### 6. MCP OAuth tokens are bound to their resource (RFC 8707)
156
+
157
+ The authorization server honours `resource` at `/authorize` and `/token` (code and refresh grant) and binds it into the
158
+ code, the refresh token and the access token (`aud`). `/ai/mcp` accepts only tokens for itself, a
159
+ `createMcpTokenVerifier()` only tokens for its `resource`; an unknown `resource` is `invalid_target`. Nothing changes for
160
+ today's clients: one that names no `resource` gets a token for `/ai/mcp`, and tokens and refresh tokens issued before
161
+ 12.10.0 stay valid at `/ai/mcp` (a refresh binds them to it). **SQL projects:** the tables of the MCP OAuth codes and refresh
162
+ tokens (collections `aiMcpOAuthCodes` / `aiMcpOAuthRefreshTokens` on MongoDB) gain a nullable `resource` column, which the boot adds as the owner role (`ownerUrl`);
163
+ without an owner connection add it with a migration.
164
+
165
+ ### 7. Dependencies
166
+
167
+ 12.10.0 declares NestJS 12.5.1. `pnpm run update` raises these pins where a nest-server-starter based project already
168
+ declares them:
169
+
170
+ | Package | From | To |
171
+ |---|---|---|
172
+ | `@nestjs/common`, `@nestjs/core`, `@nestjs/platform-express`, `@nestjs/testing` | 12.5.0 | 12.5.1 |
173
+ | `@nestjs/terminus` | 12.1.0 | 12.2.0 |
174
+ | `graphql-subscriptions` | 3.0.0 | 3.1.0 |
175
+ | `js-sha256` | 1.0.0 | 1.1.0 |
176
+ | `nodemailer` | 10.5.0 | 10.6.0 |
177
+ | `mongoose` (MongoDB projects) | 9.12.1 | 9.12.2 |
178
+
179
+ Where declared, also the optional peers `bullmq` 6.7.7, `@aws-sdk/*` 3.1171.0 and `ai` 7.0.176, and `vitest` /
180
+ `@vitest/coverage-v8` 5.1.1. `js-sha256` 1.1.0 now hashes multi-byte typed arrays (`Uint16Array`, `Float32Array`, …) by
181
+ their bytes, as Node's `crypto` does; string input — what the framework hashes — gives the same digests as before.
182
+
183
+ New direct `dependencies` for the multipart parser (see "Security: GraphQL multipart uploads"): `busboy` 1.6.0,
184
+ `fs-capacitor` 8.0.0, `http-errors` 2.0.1 and `object-path` 0.11.8 — the versions graphql-upload 17.1.0 already
185
+ installed, so an npm-mode project gets no new package. A vendor-mode project declares them (the core imports them
186
+ directly).
187
+
188
+ ## Breaking Changes
189
+
190
+ ### Failed OAuth sign-ins land on the app's login page
191
+
192
+ **Before:** a failed OAuth sign-in without an error URL of its own (state expired after ten minutes, missing or tampered;
193
+ a flow started without `errorCallbackURL`) and every `GET /iam/error` showed Better-Auth's English error page on the API
194
+ host.
195
+
196
+ **After:** they land on `<appUrl>/auth/login?error=<code>`.
197
+
198
+ **Action:** make sure the app has an `/auth/login` route that reads `error`, or set `betterAuth.errorUrl` to another
199
+ page (an absolute URL or a path). A project that customized Better-Auth's page
200
+ (`options.onAPIError.customizeDefaultErrorPage`) sets `betterAuth.errorUrl: false`. An explicit
201
+ `options.onAPIError.errorURL` still wins.
202
+
203
+ ### A `scope` that is neither a string nor a list is ignored
204
+
205
+ **Before:** an object (indexed `NSC__…__SCOPE__0` variables) made every `/iam/sign-in/social` throw a `TypeError`.
206
+
207
+ **After:** it is dropped with one error at boot, and the provider asks for its default scopes — with
208
+ `disableDefaultScope: true` for none, which the provider refuses.
209
+
210
+ **Action:** write one comma-separated `NSC__…__SCOPE` variable.
211
+
212
+ ### Secret fields leave AI tool results
213
+
214
+ **Before:** `CoreAiService.sanitizeResult()` ran `securityCheck()` on model instances only, and `/ai/mcp` sent
215
+ `JSON.stringify(result)`. A tool returning a lean document or a plain object handed its secret fields to the model, to
216
+ `actions[].result` and to the MCP client.
217
+
218
+ **After:** both paths use `sanitizeToolResultForModel()`: `securityCheck(user)` on every model instance at any depth —
219
+ also inside the `{ success, data }` wrapper, which `/ai/mcp` never looked into — then every field named in
220
+ `security.secretFields` or the framework defaults (also as SQL column, `password_reset_token`) is removed, at any depth.
221
+ A Mongoose document is replaced by its stripped `toJSON()`; a class instance becomes a plain copy of its own enumerable
222
+ fields (what `JSON.stringify` read anyway). An MCP OAuth user now carries `hasRole()` (string or array, as Better-Auth
223
+ users do) and `_authenticatedViaBetterAuth`, so a `securityCheck()` calling `user.hasRole()` works on that path.
224
+
225
+ **Action:** if a tool returns a field with such a name ON PURPOSE (it should not — the model and the client read it),
226
+ rename it. Over `/ai/mcp`, a result now loses what its models' `securityCheck()` hides from the caller, as it already did
227
+ in the chat. An override of `sanitizeResult()` keeps working.
228
+
229
+ ## Compatibility Notes
230
+
231
+ | Pattern | Status |
232
+ |---------|--------|
233
+ | `LlmProviderFactory` subclass with its own constructor | Compatible — the new `ModuleRef` parameter is optional |
234
+ | Builder registered under `'nestjs-ai'` by the project | Compatible — `registerBuilder()` replaces the built-in one |
235
+ | Override of `OpenAiCompatibleProvider.resolveAllowedBaseUrlHosts()` / `normaliseHostEntry()` | Compatible — same contract; the default bodies now delegate to `ai-egress.helper` |
236
+ | `/ai/mcp` and the MCP OAuth server | Unchanged — still `@modelcontextprotocol/sdk` 1.x (see below) |
237
+ | Projects without `ai` / `@nestjs/ai` / `@nestjs/mcp` | Unchanged — nothing new is loaded |
238
+ | Vendor mode | The core names `ai`, `@nestjs/ai` and `@nestjs/resilience` in literal `import()` calls: the project declares them (the lt CLI adds them) |
239
+ | Vendor mode, GraphQL uploads | The core imports `busboy`, `fs-capacitor`, `http-errors` and `object-path` itself (`common/helpers/graphql-upload.helper.ts`): add them to `dependencies` at the versions in §7 — a pnpm project does not see graphql-upload's own copies |
240
+ | `graphqlUploadExpress()` registered by the project | Pass `processRequest: processGraphQlUploadRequest` (see "Security: GraphQL multipart uploads") |
241
+
242
+ **Why `/ai/mcp` stays on MCP SDK v1:** `@modelcontextprotocol/server` 2.x ships no OAuth authorization-server router
243
+ (only resource-server helpers), and `@nestjs/mcp` serves every request statelessly — no sessions, no server-initiated
244
+ elicitation for 2025 clients, which the clients in use today need for the confirmation of destructive tools. A migration
245
+ that keeps every current behaviour is a release of its own.
246
+
247
+ ## Troubleshooting
248
+
249
+ | Symptom | Cause | Fix |
250
+ |---------|-------|-----|
251
+ | `AiSdkPackageError: @nestjs/ai@0.0.3 is installed, but … tested with >=0.0.2 <0.0.3` | an untested 0.x release | install a version in the range, or update `@lenne.tech/nest-server` |
252
+ | `ai.agentFunctions is set, but the application imports no AiModule.forRoot()` | the bridge needs `@nestjs/ai`'s module | import `AiModule.forRoot({ models })` or remove `ai.agentFunctions` |
253
+ | An agent function is missing from the tools | it requires `scopes` | remove `scopes`, gate it with `@Roles()` |
254
+ | A role-gated agent function answers 401 from a queue job | request-less callers are anonymous | authenticate in the job and pass `caller: { request }` |
255
+ | A `@nestjs/mcp` tool answers 401 with an MCP OAuth token | the verifier refused it (expired, `ai.mcp.roles`, unknown user) | check `ai.mcp.roles`; obtain a new token |
256
+ | A file upload answers 400 `Invalid object path for the ‘map’ multipart field …` | the `map` names a path into another upload or with a `__proto__` key | send each file at its own variable path (`variables.files.0`, `variables.files.1`) |
257
+ | Vendor mode: `Cannot find package 'busboy'` (or `fs-capacitor`, `http-errors`, `object-path`) at start | the core imports them since 12.10.0 | add them to `dependencies` (§7) |
258
+
259
+ ## Module Documentation
260
+
261
+ - [Better-Auth README](../src/core/modules/better-auth/README.md) — "Social providers", OAuth error URL
262
+ - [Better-Auth INTEGRATION-CHECKLIST](../src/core/modules/better-auth/INTEGRATION-CHECKLIST.md) — "Social provider with its own options"
263
+ - [AI module README](../src/core/modules/ai/README.md) — "NestJS AI and the AI SDK", "Your own `@nestjs/mcp` endpoint"
264
+ - [AI INTEGRATION-CHECKLIST](../src/core/modules/ai/INTEGRATION-CHECKLIST.md) — "NestJS AI / AI SDK"
265
+ - [Request lifecycle](../docs/REQUEST-LIFECYCLE.md) — "Agent function and MCP calls"
266
+
267
+ ## References
268
+
269
+ - `@nestjs/ai`: https://www.npmjs.com/package/@nestjs/ai
270
+ - `@nestjs/mcp`: https://www.npmjs.com/package/@nestjs/mcp
271
+ - AI SDK: https://ai-sdk.dev
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "12.9.4",
3
+ "version": "12.10.0",
4
4
  "type": "module",
5
5
  "description": "Server framework in TypeScript on top of NestJS: GraphQL and REST APIs on MongoDB, PostgreSQL, MySQL or MariaDB, with authentication, field-level permissions, multi-tenancy, offline sync and an AI assistant.",
6
6
  "keywords": [
@@ -100,26 +100,27 @@
100
100
  "node": ">= 22.15",
101
101
  "pnpm": "^11.0.0"
102
102
  },
103
- "packageManager": "pnpm@11.28.10+sha512.672216f06e15c109b85471d49d3fbed17e6f03ead258df08c2bf5b4a5c33321ebfbf59476bce81325efada16ace0ac78548fd0bfcd7a51369e939182a3dd50e4",
103
+ "packageManager": "pnpm@11.28.13+sha512.d5caa9cdcd6067ac2902f9f44daa00b1288a73babf1e98f4f375b3a7583b1894b4d49f7527da8f5e1530198bb10e03adba321a1f015429dc2946ce8a7a9a8c65",
104
104
  "dependencies": {
105
105
  "@apollo/server": "5.5.1",
106
106
  "@as-integrations/express5": "1.1.2",
107
107
  "@getbrevo/brevo": "6.2.0",
108
108
  "@modelcontextprotocol/sdk": "1.32.2",
109
109
  "@nestjs/apollo": "14.2.1",
110
- "@nestjs/common": "12.5.0",
111
- "@nestjs/core": "12.5.0",
110
+ "@nestjs/common": "12.5.1",
111
+ "@nestjs/core": "12.5.1",
112
112
  "@nestjs/graphql": "14.2.1",
113
113
  "@nestjs/jwt": "12.0.5",
114
114
  "@nestjs/passport": "12.0.2",
115
- "@nestjs/platform-express": "12.5.0",
115
+ "@nestjs/platform-express": "12.5.1",
116
116
  "@nestjs/schedule": "12.0.4",
117
117
  "@nestjs/swagger": "12.1.2",
118
- "@nestjs/terminus": "12.1.0",
118
+ "@nestjs/terminus": "12.2.0",
119
119
  "@tus/file-store": "2.1.2",
120
120
  "@tus/server": "2.4.7",
121
121
  "@types/supertest": "7.2.1",
122
122
  "bcrypt": "6.0.0",
123
+ "busboy": "1.6.0",
123
124
  "class-transformer": "0.5.1",
124
125
  "class-validator": "0.15.1",
125
126
  "compression": "1.8.2",
@@ -128,18 +129,21 @@
128
129
  "dotenv": "18.0.10",
129
130
  "ejs": "7.0.2",
130
131
  "express": "5.3.0",
132
+ "fs-capacitor": "8.0.0",
131
133
  "graphql": "16.15.0",
132
134
  "graphql-query-complexity": "2.0.0",
133
- "graphql-subscriptions": "3.0.0",
135
+ "graphql-subscriptions": "3.1.0",
134
136
  "graphql-upload": "17.1.0",
135
137
  "graphql-ws": "6.4.1",
138
+ "http-errors": "2.0.1",
136
139
  "jose": "6.2.17",
137
- "js-sha256": "1.0.0",
140
+ "js-sha256": "1.1.0",
138
141
  "json-to-graphql-query": "2.3.0",
139
142
  "lodash": "4.18.1",
140
143
  "multer": "2.5.0",
141
144
  "node-mailjet": "6.0.11",
142
- "nodemailer": "10.5.0",
145
+ "nodemailer": "10.6.0",
146
+ "object-path": "0.11.8",
143
147
  "passport": "0.7.0",
144
148
  "passport-jwt": "4.0.1",
145
149
  "reflect-metadata": "0.2.2",
@@ -157,9 +161,12 @@
157
161
  "@aws-sdk/s3-request-presigner": ">=3.1045.0 <4",
158
162
  "@better-auth/core": ">=1.7.16 <1.8.0",
159
163
  "@better-auth/passkey": ">=1.7.16 <1.8.0",
164
+ "@nestjs/ai": ">=0.0.2 <0.0.3",
160
165
  "@nestjs/mongoose": ">=12.0.0 <13",
166
+ "@nestjs/resilience": ">=0.0.3 <0.0.4",
161
167
  "@swc/core": ">=1.10.0 <2",
162
168
  "@tus/s3-store": ">=2.0.5 <3",
169
+ "ai": ">=7.0.0 <8",
163
170
  "better-auth": ">=1.7.16 <1.8.0",
164
171
  "bullmq": ">=5.16.0 <7",
165
172
  "drizzle-orm": "1.0.0-rc.5",
@@ -187,15 +194,24 @@
187
194
  "@better-auth/passkey": {
188
195
  "optional": false
189
196
  },
197
+ "@nestjs/ai": {
198
+ "optional": true
199
+ },
190
200
  "@nestjs/mongoose": {
191
201
  "optional": true
192
202
  },
203
+ "@nestjs/resilience": {
204
+ "optional": true
205
+ },
193
206
  "@swc/core": {
194
207
  "optional": true
195
208
  },
196
209
  "@tus/s3-store": {
197
210
  "optional": true
198
211
  },
212
+ "ai": {
213
+ "optional": true
214
+ },
199
215
  "better-auth": {
200
216
  "optional": false
201
217
  },
@@ -228,54 +244,63 @@
228
244
  }
229
245
  },
230
246
  "devDependencies": {
231
- "@aws-sdk/client-s3": "3.1168.0",
232
- "@aws-sdk/lib-storage": "3.1168.0",
233
- "@aws-sdk/s3-request-presigner": "3.1168.0",
247
+ "@aws-sdk/client-s3": "3.1171.0",
248
+ "@aws-sdk/lib-storage": "3.1171.0",
249
+ "@aws-sdk/s3-request-presigner": "3.1171.0",
234
250
  "@better-auth/core": "1.7.23",
235
251
  "@better-auth/passkey": "1.7.23",
236
252
  "@compodoc/compodoc": "2.0.0",
253
+ "@modelcontextprotocol/server": "2.4.0",
254
+ "@nestjs/ai": "0.0.2",
237
255
  "@nestjs/cli": "12.0.13",
256
+ "@nestjs/mcp": "0.0.4",
238
257
  "@nestjs/mongoose": "12.0.1",
258
+ "@nestjs/resilience": "0.0.3",
239
259
  "@nestjs/schematics": "12.0.13",
240
- "@nestjs/testing": "12.5.0",
260
+ "@nestjs/testing": "12.5.1",
241
261
  "@swc/cli": "0.8.2",
242
262
  "@swc/core": "1.16.22",
243
263
  "@tus/s3-store": "2.1.0",
264
+ "@types/busboy": "1.5.5",
244
265
  "@types/compression": "1.8.1",
245
266
  "@types/cookie-parser": "1.4.10",
246
267
  "@types/ejs": "3.1.5",
247
268
  "@types/express": "5.0.6",
269
+ "@types/http-errors": "2.0.5",
248
270
  "@types/lodash": "4.17.27",
249
271
  "@types/multer": "2.3.0",
250
272
  "@types/node": "26.6.6",
273
+ "@types/object-path": "0.11.4",
251
274
  "@types/passport": "1.0.17",
252
275
  "@types/pg": "8.23.1",
253
- "@vitest/coverage-v8": "5.1.0",
276
+ "@vitest/coverage-v8": "5.1.1",
277
+ "ai": "7.0.176",
254
278
  "better-auth": "1.7.23",
255
- "bullmq": "6.7.6",
279
+ "bullmq": "6.7.7",
256
280
  "cross-env": "10.1.0",
257
281
  "drizzle-orm": "1.0.0-rc.5",
258
282
  "ioredis": "6.0.0",
259
283
  "kysely": "0.29.9",
260
284
  "mongodb": "7.8.0",
261
- "mongoose": "9.12.1",
285
+ "mongoose": "9.12.2",
262
286
  "mysql2": "3.24.6",
263
287
  "nodemon": "3.1.14",
264
288
  "otpauth": "9.6.0",
265
- "oxfmt": "0.78.0",
266
- "oxlint": "1.93.0",
289
+ "oxfmt": "0.79.0",
290
+ "oxlint": "1.94.0",
267
291
  "oxlint-tsgolint": "7.0.2007",
268
292
  "pg": "8.23.1",
269
- "playwright-core": "1.65.0",
293
+ "playwright-core": "1.65.1",
270
294
  "rimraf": "6.1.4",
271
- "smtp-server": "3.21.4",
295
+ "smtp-server": "3.21.6",
272
296
  "tsx": "4.23.15",
273
297
  "tus-js-client": "4.3.1",
274
298
  "typeorm": "1.1.3",
275
299
  "typescript": "6.0.3",
276
300
  "unplugin-swc": "2.0.0",
277
301
  "vite": "8.3.8",
278
- "vitest": "5.1.0"
302
+ "vitest": "5.1.1",
303
+ "zod": "4.6.7"
279
304
  },
280
305
  "main": "dist/index.js",
281
306
  "types": "dist/index.d.ts",
@@ -1,9 +1,15 @@
1
1
  import { createParamDecorator, ExecutionContext } from '@nestjs/common';
2
2
 
3
+ import { isAgentCallContext, resolveAgentCallRequest } from '../helpers/execution-context-request.helper.js';
4
+
3
5
  /**
4
6
  * User decorator for REST request
5
7
  */
6
8
  export const RESTUser = createParamDecorator((data: unknown, ctx: ExecutionContext) => {
9
+ // An agent function / MCP call: the request's user, never one in the call's arguments (nestjs-ai plan §1)
10
+ if (isAgentCallContext(ctx)) {
11
+ return resolveAgentCallRequest(ctx)?.user;
12
+ }
7
13
  const request = ctx.switchToHttp().getRequest();
8
14
  return request.user;
9
15
  });
@@ -37,6 +37,14 @@ export class HttpExceptionLogFilter implements ExceptionFilter {
37
37
  return exception;
38
38
  }
39
39
 
40
+ // Any transport without an HTTP response of its own — an agent function call (`'ai'`) or an MCP call (`'mcp'`),
41
+ // whose second argument is the CALL, not a response (nestjs-ai plan §1). Returning nothing hands the exception
42
+ // back to the caller's handler, which tells the model or MCP client its message. Writing to `switchToHttp()`
43
+ // there threw a TypeError instead, and the model read "Internal server error" for every 401 / 403 / 404.
44
+ if (type !== 'http') {
45
+ return undefined;
46
+ }
47
+
40
48
  // REST
41
49
  const ctx = host.switchToHttp();
42
50
  const res = ctx.getResponse<Response>();
@@ -2,6 +2,8 @@ import { ExecutionContext } from '@nestjs/common';
2
2
  import { GqlExecutionContext } from '@nestjs/graphql';
3
3
  import { Request as RequestType } from 'express';
4
4
 
5
+ import { isAgentCallContext, resolveAgentCallRequest } from './execution-context-request.helper.js';
6
+
5
7
  /**
6
8
  * Helper for context processing
7
9
  * @deprecated use functions directly
@@ -33,6 +35,18 @@ export function getContextData(context: ExecutionContext): {
33
35
  return { args: null, currentUser: null, request: null };
34
36
  }
35
37
 
38
+ // An agent function / MCP call (nestjs-ai plan §1): the user is the one of the request the call runs in — never a
39
+ // `user` in the call's arguments, which the model or the MCP client wrote. A request-less call has no user, so the
40
+ // interceptors filter its result for an anonymous caller (the strictest view).
41
+ if (isAgentCallContext(context)) {
42
+ const agentRequest = resolveAgentCallRequest(context);
43
+ return {
44
+ args: context.getArgByIndex(0),
45
+ currentUser: agentRequest?.user,
46
+ request: (agentRequest ?? null) as RequestType,
47
+ };
48
+ }
49
+
36
50
  // Init data
37
51
  let user: { [key: string]: any };
38
52
  let rawContext: any = null;