@silkweave/nestjs 1.12.0 → 2.2.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/build/index.d.mts CHANGED
@@ -1,13 +1,89 @@
1
- import { CanActivate, DynamicModule, INestApplication, MiddlewareConsumer, NestModule, Type } from "@nestjs/common";
1
+ import { CanActivate, DynamicModule, MiddlewareConsumer, NestModule, Type } from "@nestjs/common";
2
+ import { ApplicationConfig, DiscoveryService, HttpAdapterHost, MetadataScanner, ModuleRef, Reflector } from "@nestjs/core";
3
+ import { Action, SilkweaveContext, SilkweaveOptions } from "@silkweave/core";
4
+ import { z } from "zod/v4";
2
5
  import { AuthConfig } from "@silkweave/auth";
3
- import { Action as Action$1, ActionKind, HttpMethod, SilkweaveContext, SilkweaveOptions } from "@silkweave/core";
4
- import z$1 from "zod/v4";
5
- import { InferTrpcRouter } from "@silkweave/trpc";
6
- import { TypegenFormat } from "@silkweave/typegen";
7
- import { DiscoveryService, HttpAdapterHost, MetadataScanner, ModuleRef, Reflector } from "@nestjs/core";
8
6
  import { CorsOptions } from "cors";
9
- import { OpenAPIObject } from "@nestjs/swagger";
10
7
 
8
+ //#region src/lib/reflect/schema.d.ts
9
+ /**
10
+ * A transport-neutral description of a single input field. Every metadata
11
+ * source (swagger decorators, class-validator, an OpenAPI document, TypeScript
12
+ * `design:type`) is mapped to this shape, the shapes are merged by precedence,
13
+ * and the result is converted to Zod once. Keeping a single intermediate keeps
14
+ * the per-source mappers small and the Zod construction in one place.
15
+ */
16
+ interface FieldDesc {
17
+ type?: 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object' | 'unknown';
18
+ required?: boolean;
19
+ description?: string;
20
+ enum?: (string | number)[];
21
+ items?: FieldDesc;
22
+ min?: number;
23
+ max?: number;
24
+ minLength?: number;
25
+ maxLength?: number;
26
+ format?: string;
27
+ default?: unknown;
28
+ }
29
+ /** Merge `over` onto `base` - defined keys of `over` win. */
30
+ declare function mergeField(base: FieldDesc, over: FieldDesc): FieldDesc;
31
+ /** Convert a merged {@link FieldDesc} to a Zod schema. */
32
+ declare function fieldToZod(d: FieldDesc): z.ZodType;
33
+ /** Normalise a TS-enum object or an array literal to a flat value list. */
34
+ declare function normalizeEnum(value: unknown): (string | number)[] | undefined;
35
+ /** Map a swagger/`design:type` type token (constructor, `[Type]`, or string) to a base type. */
36
+ declare function typeTokenToBase(type: unknown): FieldDesc['type'] | undefined;
37
+ /** From the constructor TypeScript emits via `emitDecoratorMetadata`. */
38
+ declare function designTypeToField(ctor: unknown): FieldDesc;
39
+ /** From an `@ApiParam`/`@ApiQuery` entry stored under `swagger/apiParameters`. */
40
+ declare function swaggerParamToField(p: Record<string, any>): FieldDesc;
41
+ /** From an `@ApiProperty` options object stored under `swagger/apiModelProperties`. */
42
+ declare function apiPropertyToField(o: Record<string, any>): FieldDesc;
43
+ /** From an array of `class-validator` validation-metadata entries for one property. */
44
+ declare function classValidatorToField(metas: Array<{
45
+ type?: string;
46
+ name?: string;
47
+ constraints?: unknown[];
48
+ }>): FieldDesc;
49
+ /** From an OpenAPI Schema Object (used by both the doc and `@ApiParam({ schema })`). */
50
+ declare function openapiSchemaToField(schema: Record<string, any>): FieldDesc;
51
+ /**
52
+ * Reflect a whole-DTO class (`@Body() dto: CreateDto`) into per-property
53
+ * {@link FieldDesc}s. Property names are the union of `@ApiProperty` and
54
+ * `class-validator` decorated fields; each field merges `design:type` (base),
55
+ * then `class-validator` constraints, then `@ApiProperty` (highest). Properties
56
+ * default to required unless a source marks them optional.
57
+ */
58
+ declare function reflectDtoFields(dtoType: any): Record<string, FieldDesc>;
59
+ //#endregion
60
+ //#region src/lib/reflect/openapi.d.ts
61
+ /**
62
+ * A minimal view of an OpenAPI document - the subset we read. Matches the shape
63
+ * `SwaggerModule.createDocument()` returns, but typed loosely so callers can
64
+ * pass any compatible object without a hard `@nestjs/swagger` dependency.
65
+ */
66
+ interface OpenApiDocument {
67
+ paths?: Record<string, Record<string, any>>;
68
+ components?: {
69
+ schemas?: Record<string, any>;
70
+ };
71
+ }
72
+ interface OpenApiLookup {
73
+ doc: OpenApiDocument;
74
+ /** `${METHOD} ${path}` → operation object. */
75
+ operations: Map<string, any>;
76
+ }
77
+ /** Index a document's operations by `${METHOD} ${path}` for fast matching. */
78
+ declare function buildOpenApiLookup(doc: OpenApiDocument): OpenApiLookup;
79
+ /**
80
+ * Resolve the per-field descriptors for a route from an ingested OpenAPI
81
+ * document. Merges `parameters` (path/query/header) and the JSON request-body
82
+ * schema's properties into a single field map. Returns `{}` when the operation
83
+ * isn't found - callers fall back to decorator reflection.
84
+ */
85
+ declare function openApiFields(lookup: OpenApiLookup, method: string, openapiPath: string): Record<string, FieldDesc>;
86
+ //#endregion
11
87
  //#region src/lib/types.d.ts
12
88
  /**
13
89
  * Context passed to a Nest Silkweave adapter when `SilkweaveModule` wires it
@@ -24,7 +100,7 @@ interface NestAdapterRegisterContext {
24
100
  /** Per-adapter context - already forked with `{ adapter: adapter.name, ...userContext }`. */
25
101
  baseContext: SilkweaveContext;
26
102
  /** Actions filtered to those enabled on this adapter. */
27
- actions: Action$1[];
103
+ actions: Action[];
28
104
  }
29
105
  /**
30
106
  * A Silkweave Nest adapter. Each transport (REST, tRPC, MCP) implements this
@@ -35,18 +111,13 @@ interface NestAdapterRegisterContext {
35
111
  */
36
112
  interface NestSilkweaveAdapter {
37
113
  /** Adapter discriminator - set on the silkweave context as `ctx.get('adapter')`. */
38
- readonly name: 'rest' | 'trpc' | 'mcp' | 'typegen';
39
- /**
40
- * URL prefix the adapter mounts on (e.g. `'/api'`). Surfaced for introspection
41
- * tooling such as `addSilkweaveActions()` (OpenAPI/Swagger), which reads it to
42
- * keep generated docs aligned with the live routes.
43
- */
114
+ readonly name: 'mcp';
115
+ /** URL prefix the adapter mounts on (e.g. `'/mcp'`). Surfaced for introspection. */
44
116
  readonly basePath?: string;
45
117
  /**
46
118
  * When `true`, the adapter receives every discovered action regardless of
47
- * each action's `transports` allowlist / `isEnabled` gate. Used by
48
- * non-runtime adapters like `typegen()` that emit types for the entire
49
- * action surface.
119
+ * each action's `isEnabled` gate. Reserved for non-runtime adapters that need
120
+ * the entire action surface.
50
121
  */
51
122
  readonly allActions?: boolean;
52
123
  /** Register this adapter's routes on Nest's HTTP server. */
@@ -55,10 +126,30 @@ interface NestSilkweaveAdapter {
55
126
  interface SilkweaveModuleOptions {
56
127
  /** Identity for the silkweave instance - surfaced to MCP clients, OpenAPI, etc. */
57
128
  silkweave: SilkweaveOptions;
58
- /** Adapters to mount. Examples: `rest()`, `trpc()`, `mcp()`. */
129
+ /** Adapters to mount. Currently `mcp()`. */
59
130
  adapters: NestSilkweaveAdapter[];
60
131
  /** Initial context keys merged into every adapter's `baseContext`. */
61
132
  context?: Record<string, unknown>;
133
+ /**
134
+ * Optional OpenAPI document (e.g. from `SwaggerModule.createDocument(app, cfg)`)
135
+ * used as an authoritative source when reflecting `@Mcp` tool input schemas.
136
+ * Matched to each method by HTTP verb + path; falls back to decorator
137
+ * reflection when an operation or field isn't present.
138
+ */
139
+ openapi?: OpenApiDocument;
140
+ /**
141
+ * Opt-in allow-list of app-global guard classes (registered via
142
+ * `app.useGlobalGuards()` or `{ provide: APP_GUARD, useClass }`) to run on
143
+ * every MCP tool call, before each method/class `@UseGuards`. Listed by
144
+ * class - a blanket "run all globals" is deliberately not offered, since
145
+ * unrelated globals (e.g. a `ThrottlerGuard` that needs a writable response)
146
+ * would misbehave over MCP. Empty/omitted ⇒ no global guards run.
147
+ *
148
+ * Note: over MCP the request stand-in is headers-only (`params`/`query` are
149
+ * empty), so per-session or IP-derived guard logic won't apply; header-based
150
+ * authentication still works.
151
+ */
152
+ globalGuards?: Type<CanActivate>[];
62
153
  }
63
154
  declare const SILKWEAVE_MODULE_OPTIONS = "__silkweave_module_options__";
64
155
  //#endregion
@@ -91,221 +182,120 @@ interface McpAdapterOptions {
91
182
  */
92
183
  declare function mcp(options?: McpAdapterOptions): NestSilkweaveAdapter;
93
184
  //#endregion
94
- //#region src/adapter/rest.d.ts
95
- interface RestAdapterOptions {
96
- /** URL prefix joined to each action's path. e.g. `'/api'` → `POST /api/users/list`. Default: `'/api'`. */
97
- basePath?: string;
98
- /** Optional bearer-token auth applied to every REST action. */
99
- auth?: AuthConfig;
100
- }
101
- /**
102
- * REST adapter for `@silkweave/nestjs`. Registers each discovered `@Action`
103
- * as an individual route on Nest's HTTP adapter:
104
- *
105
- * - HTTP verb comes from `method`, else `GET` for `kind: 'query'`, else `POST`.
106
- * - Path comes from `path` (joined to `basePath`, may contain `:param`
107
- * placeholders), else `${basePath}/${actionName-with-slashes}`.
108
- * - Input is merged from the request body, the `queryParams` query-string
109
- * fields, and any `:param` path placeholders (see `resolveActionInput`).
110
- *
111
- * Routes show up in Nest's `RoutesResolver` logger. They are registered
112
- * directly on the HTTP adapter (not as Nest controllers), so `@nestjs/swagger`'s
113
- * controller scanner does not see them - use `addSilkweaveActions()` to add them
114
- * to the OpenAPI document. Works on `@nestjs/platform-express` out of the box.
115
- * For `@nestjs/platform-fastify`, register `@fastify/express` first.
116
- */
117
- declare function rest(options?: RestAdapterOptions): NestSilkweaveAdapter;
118
- //#endregion
119
- //#region src/adapter/trpc.d.ts
120
- interface TrpcAdapterOptions {
121
- /** URL prefix at which the tRPC handler is mounted. Default `'/trpc'`. */
122
- basePath?: string;
123
- /** Optional bearer-token auth applied to every tRPC procedure. */
124
- auth?: AuthConfig;
125
- }
185
+ //#region src/lib/metadata.d.ts
186
+ /** Reflect-metadata key carrying `@Mcp` options on a controller method. */
187
+ declare const MCP_METADATA = "__silkweave_mcp__";
126
188
  /**
127
- * tRPC adapter for `@silkweave/nestjs`. Builds a tRPC router from discovered
128
- * `@Action` methods and mounts the resulting express middleware at
129
- * `basePath` on Nest's HTTP adapter.
130
- *
131
- * Action names with dots (e.g. `users.list` from `@Actions('users')`) collapse
132
- * to camelCase procedure keys (`usersList`).
133
- *
134
- * Works on `@nestjs/platform-express`. On `@nestjs/platform-fastify`, register
135
- * `@fastify/express` first so Nest can serve Express-style middleware.
189
+ * Options for the `@Mcp()` method decorator. Every field is optional - an empty
190
+ * `@Mcp()` exposes the decorated controller route as an MCP tool with its name,
191
+ * description, and input schema fully reflected from the method's route
192
+ * (`@Get`/`@Post`/...), parameter decorators (`@Param`/`@Query`/`@Body`), and
193
+ * any `@nestjs/swagger` (`@ApiOperation`/`@ApiParam`/`@ApiProperty`) or
194
+ * `class-validator` metadata it carries.
136
195
  */
137
- declare function trpc(options?: TrpcAdapterOptions): NestSilkweaveAdapter;
138
- //#endregion
139
- //#region src/adapter/typegen.d.ts
140
- interface TypegenAdapterOptions {
141
- /** Output file path for the generated `.d.ts` file. Resolved against `process.cwd()`. Parent directories are created automatically. */
142
- path: string;
196
+ interface McpMetadata {
143
197
  /**
144
- * What to emit (default `'all'`):
145
- * - `'interfaces'` - `{Name}Input` / `{Name}Output` interfaces per action
146
- * - `'trpc-router'` - `AppRouter` type alias for `createTRPCClient<AppRouter>()`
147
- * - `'all'` - both
198
+ * MCP tool name override. When unset it is derived from the controller class
199
+ * and method name (e.g. `ChannelsController.findOne` `ChannelsFindOne`).
148
200
  */
149
- format?: TypegenFormat;
201
+ name?: string;
150
202
  /**
151
- * Whether to write the file at all. Default: `process.env.NODE_ENV !== 'production'`.
152
- * Server processes generally shouldn't write to disk in production deploys -
153
- * leave it on the default unless you know you want otherwise.
203
+ * Tool description override. When unset it falls back to the method's
204
+ * `@ApiOperation({ summary | description })`, then a generated default.
154
205
  */
155
- enabled?: boolean;
156
- }
157
- /**
158
- * Typegen adapter for `@silkweave/nestjs`. Discovers every `@Action`-decorated
159
- * method (regardless of `transports` filtering) and writes a single `.d.ts`
160
- * file with REST input/output interfaces and/or a tRPC `AppRouter` type alias.
161
- *
162
- * Designed for the monorepo pattern where the server (this app) is the source
163
- * of truth for types and consumer apps import from `path` - e.g.
164
- * `path: '../app/src/types/silkweave.ts'`.
165
- */
166
- declare function typegen(options: TypegenAdapterOptions): NestSilkweaveAdapter;
167
- //#endregion
168
- //#region src/lib/metadata.d.ts
169
- declare const ACTION_METADATA = "__silkweave_action__";
170
- declare const ACTIONS_METADATA = "__silkweave_actions__";
171
- type Transport = 'rest' | 'trpc' | 'mcp';
172
- interface ActionMetadata<I extends object = object, O extends object = object, C = unknown> {
173
- /** Action name. Defaults to the kebab-cased method name. */
174
- name?: string;
175
- /** Human-readable description. Becomes the MCP tool description and REST OpenAPI summary. */
176
- description: string;
177
- /** Zod object schema for the action's input. */
178
- input: z$1.ZodType<I> & {
179
- shape: Record<string, z$1.ZodTypeAny>;
180
- };
181
- /** Optional Zod object schema for the action's output (used by tRPC type inference). */
182
- output?: z$1.ZodType<O> & {
183
- shape: Record<string, z$1.ZodTypeAny>;
184
- };
206
+ description?: string;
185
207
  /**
186
- * Zod schema for individual chunks yielded by a streaming (async-generator)
187
- * action method. Required when the decorated method is an `async function*`.
188
- * Mirrors `Action.chunk` in @silkweave/core; typegen/trpc use it to expose
189
- * the action as a tRPC subscription.
208
+ * Zod raw-shape override merged over the reflected input fields (override
209
+ * wins per field). The escape hatch for shapes reflection can't express
210
+ * losslessly - discriminated unions, custom validators, `@Transform`, etc.
190
211
  */
191
- chunk?: z$1.ZodType<C>;
192
- /** `'query'` (GET in REST, `.query()` in tRPC) or `'mutation'` (POST in REST, `.mutation()` in tRPC). Default: `'mutation'`. */
193
- kind?: ActionKind;
194
- /** HTTP verb for the REST route. Defaults to `POST` (or `GET` when `kind` is `'query'`). Overrides the `kind`-derived default. */
195
- method?: HttpMethod;
196
- /** REST route path, optionally with `:param` placeholders (e.g. `'spaces/:spaceId/users'`). Each placeholder must be a key of `input`. Defaults to the action name with dots as slashes. */
197
- path?: string;
198
- /** Input fields read from the URL query string instead of the request body (e.g. `['offset', 'limit']`). Each must be a key of `input`. */
199
- queryParams?: (keyof I)[];
200
- /** Allowlist of transports that should expose this action. Default: all registered transports. */
201
- transports?: Transport[];
202
- /** Dynamic enable check (in addition to `transports`). AND-combined with the transports filter. */
203
- isEnabled?: (context: SilkweaveContext) => boolean;
204
- /** Custom MCP `CallToolResult` formatter. See `@silkweave/mcp`'s `smartToolResult`. */
205
- toolResult?: Action$1<I, O>['toolResult'];
206
- /** CLI positional-argument keys (unused for HTTP-only adapters, kept for parity with `createAction`). */
207
- args?: (keyof I)[];
208
- /** Custom MCP tool name override. If unset, derived from action name as PascalCase. */
209
- mcpToolName?: string;
210
- }
211
- interface ActionsClassMetadata {
212
- /** Prefix joined to the method-level action name with a dot. e.g. `Actions('users')` + method `list` → `users.list`. */
213
- prefix?: string;
214
- /** Class-level transports allowlist. Method-level `transports` overrides; otherwise inherits this. */
215
- transports?: Transport[];
216
- }
217
- interface ResultToolResult<O extends object = object> {
218
- toolResult?: Action$1<object, O>['toolResult'];
212
+ input?: Record<string, z.ZodType>;
213
+ /**
214
+ * Whether to apply the controller method's parameter-bound pipes
215
+ * (`@Param('id', ParseIntPipe)`) when re-binding the call. Default `'apply'`.
216
+ * Global/`ValidationPipe`, interceptors, and exception filters never run -
217
+ * the method is invoked directly, not through Nest's HTTP request pipeline.
218
+ */
219
+ pipes?: 'apply' | 'skip';
219
220
  }
220
- type AnyActionMetadata = ActionMetadata<object, object> & ResultToolResult<object>;
221
- declare const ACTION_RESPONSE_KEY = "__silkweave_response__";
222
221
  //#endregion
223
- //#region src/decorator/action.d.ts
222
+ //#region src/decorator/mcp.d.ts
224
223
  /**
225
- * Method decorator that registers a Silkweave action.
224
+ * Method decorator that exposes an existing NestJS controller route as an MCP
225
+ * tool. It is **additive** - the route keeps serving HTTP exactly as before;
226
+ * `@Mcp()` just opts the method into MCP discovery.
226
227
  *
227
- * The decorated method becomes an Action and is exposed via every adapter
228
- * configured on `SilkweaveModule` (REST/tRPC/MCP), unless `transports` is
229
- * provided to restrict it.
228
+ * The tool's name, description, and input schema are reflected from the
229
+ * method's own metadata:
230
+ * - **fields** from the parameter decorators (`@Param`/`@Query`/`@Body`) - a
231
+ * `@Param('id')` becomes an `id` field; a whole-DTO `@Body() dto: CreateDto`
232
+ * is flattened to its properties,
233
+ * - **types/constraints/descriptions** from `@nestjs/swagger`
234
+ * (`@ApiParam`/`@ApiQuery`/`@ApiProperty`/`@ApiOperation`) and, when present,
235
+ * `class-validator` decorators on the DTOs,
236
+ * - optionally refined by an OpenAPI document passed to `SilkweaveModule`.
230
237
  *
231
- * The method receives `(input, context)` where `input` is the parsed Zod input
232
- * and `context` is the `SilkweaveContext` (with `logger`, `request`, optional
233
- * `auth`). The class instance is a normal Nest provider, so other services can
234
- * be injected via the constructor.
238
+ * On a tool call the input is split back into the method's positional arguments
239
+ * and the method is invoked directly (with `@UseGuards` guards applied first).
235
240
  *
236
241
  * @example
237
242
  * ```ts
238
- * @Injectable()
239
- * @Actions('users')
240
- * export class UserActions {
241
- * constructor(private db: DbService) {}
242
- *
243
- * @Action({
244
- * description: 'List users',
245
- * input: z.object({ limit: z.number().optional() }),
246
- * kind: 'query'
247
- * })
248
- * list(input: { limit?: number }, ctx: SilkweaveContext) {
249
- * return this.db.listUsers(input.limit)
243
+ * @Controller('sessions/:sessionId/channels')
244
+ * export class ChannelsController {
245
+ * @Get(':channelId')
246
+ * @ApiOperation({ summary: 'Get a specific channel by ID' })
247
+ * @ApiParam({ name: 'sessionId', description: 'Session ID' })
248
+ * @ApiParam({ name: 'channelId', description: 'Channel ID' })
249
+ * @Mcp()
250
+ * findOne(@Param('sessionId') sessionId: string, @Param('channelId') channelId: string) {
251
+ * return this.service.get(sessionId, channelId)
250
252
  * }
251
253
  * }
252
254
  * ```
253
255
  */
254
- declare function Action<I extends object = object, O extends object = object, C = unknown>(options: ActionMetadata<I, O, C>): MethodDecorator;
255
- //#endregion
256
- //#region src/decorator/actions.d.ts
257
- /**
258
- * Class decorator that groups a provider's `@Action` methods under a common
259
- * prefix. The prefix is joined to each method's action name with a dot
260
- * (e.g. `@Actions('users')` + method `list` → action name `users.list`).
261
- *
262
- * The class itself remains a normal Nest provider - add `@Injectable()`
263
- * separately so it can be resolved by the DI container.
264
- *
265
- * Accepts either a prefix string (shorthand) or a full options object:
266
- * ```ts
267
- * @Actions('users')
268
- * @Actions({ prefix: 'users', transports: ['rest', 'trpc'] })
269
- * ```
270
- */
271
- declare function Actions(prefixOrOptions?: string | ActionsClassMetadata): ClassDecorator;
256
+ declare function Mcp(options?: McpMetadata): MethodDecorator;
272
257
  //#endregion
273
- //#region src/lib/discovery.d.ts
274
- declare class ActionDiscovery {
258
+ //#region src/lib/controllerDiscovery.d.ts
259
+ declare class ControllerDiscovery {
275
260
  private readonly discovery;
276
261
  private readonly scanner;
277
262
  private readonly reflector;
278
263
  private readonly moduleRef;
279
- constructor(discovery: DiscoveryService, scanner: MetadataScanner, reflector: Reflector, moduleRef: ModuleRef);
264
+ private readonly appConfig;
265
+ constructor(discovery: DiscoveryService, scanner: MetadataScanner, reflector: Reflector, moduleRef: ModuleRef, appConfig: ApplicationConfig);
280
266
  /**
281
- * Walk every Nest provider, find methods annotated with `@Action`, and build
282
- * a list of core `Action` objects ready to feed into `silkweave().actions()`.
283
- *
284
- * Action invocation is wrapped to (a) run `@UseGuards` guards declared on the
285
- * method or its class against the incoming request (read from
286
- * `ctx.get('request')`, populated by REST/tRPC and by MCP-over-HTTP from the
287
- * SDK's `extra.requestInfo`) and (b) bind `this` to the resolved Nest provider
288
- * so DI-injected dependencies remain available.
267
+ * Walk every Nest provider/controller, find methods annotated with `@Mcp`,
268
+ * and build a core `Action` per method whose input schema is reflected from
269
+ * the route + parameter decorators (+ optional OpenAPI document) and whose
270
+ * `run` re-binds the validated input back into the method's positional
271
+ * arguments (with `@UseGuards` guards - and any opted-in `globalGuards` -
272
+ * applied first).
289
273
  */
290
- discover(): Action$1[];
274
+ discover(openapi?: OpenApiDocument, globalGuards?: Type<CanActivate>[]): Action[];
291
275
  private toAction;
276
+ /** Build the merged Zod input shape and the per-argument re-bind plan. */
277
+ private buildInput;
292
278
  }
293
279
  //#endregion
294
- //#region src/lib/filter.d.ts
280
+ //#region src/lib/guards.d.ts
281
+ type GuardRef = Type<CanActivate> | CanActivate;
295
282
  /**
296
- * Compile a `transports` allowlist + optional user `isEnabled` into a single
297
- * `(ctx) => boolean` callback compatible with `Action.isEnabled`.
283
+ * Collect the app's global guards that match an opt-in allow-list of classes.
284
+ *
285
+ * Reads both registration styles Nest exposes via `ApplicationConfig`:
286
+ * `useGlobalGuards(new X())` instances (`getGlobalGuards()`) and
287
+ * `{ provide: APP_GUARD, useClass }` DI guards (`getGlobalRequestGuards()`,
288
+ * which yields `InstanceWrapper`s - we read `.instance` off each).
298
289
  *
299
- * - If `transports` is omitted, the action runs on every adapter.
300
- * - If `transports` is set, the action is gated on `ctx.get<string>('adapter')`
301
- * matching one of the listed transports. Each adapter in `@silkweave/nestjs`
302
- * forks its context with `{ adapter: 'rest' | 'trpc' | 'mcp' }`.
303
- * - If both `transports` and `userIsEnabled` are set, they are AND-combined.
290
+ * The allow-list is intentionally explicit-by-class: a blanket "run every
291
+ * global" would also fire unrelated globals (e.g. a `ThrottlerGuard` that
292
+ * assumes a writable response) on every tool call. An empty allow-list runs
293
+ * no globals, preserving the prior behavior.
294
+ *
295
+ * Call this at tool-call time, not at discovery time: `APP_GUARD` instances
296
+ * aren't populated until `app.init()` finishes.
304
297
  */
305
- declare function buildIsEnabled(transports: Transport[] | undefined, userIsEnabled: ((ctx: SilkweaveContext) => boolean) | undefined): ((ctx: SilkweaveContext) => boolean) | undefined;
306
- //#endregion
307
- //#region src/lib/guards.d.ts
308
- type GuardRef = Type<CanActivate> | CanActivate;
298
+ declare function collectGlobalGuards(appConfig: ApplicationConfig, allowList: Type<CanActivate>[]): CanActivate[];
309
299
  /**
310
300
  * Read `@UseGuards(...)` metadata for both the method and its class and merge
311
301
  * the two lists. Method-level guards run AFTER class-level guards (matching
@@ -327,33 +317,69 @@ declare function collectGuards(reflector: Reflector, classRef: Type<unknown>, ha
327
317
  */
328
318
  declare function runGuards(guards: GuardRef[], moduleRef: ModuleRef, reflector: Reflector, classRef: Type<unknown>, handler: (...args: unknown[]) => unknown, request: unknown, response: unknown, contextType?: 'http' | 'rpc'): Promise<void>;
329
319
  //#endregion
330
- //#region src/lib/openapi.d.ts
331
- interface ActionPathsOptions {
332
- /** URL prefix the `rest()` adapter mounts on. Default `'/api'`. */
333
- basePath?: string;
334
- /** OpenAPI tag the actions are grouped under. Default `'Actions'`. */
335
- tag?: string;
320
+ //#region src/lib/rebind.d.ts
321
+ /**
322
+ * Instruction for reconstructing one positional handler argument from the flat
323
+ * MCP tool input. Built at discovery time, consumed by {@link invokeRebound}.
324
+ */
325
+ type Binding = {
326
+ kind: 'value';
327
+ field: string;
328
+ source: 'path' | 'query' | 'body';
329
+ metatype?: unknown;
330
+ pipes?: unknown[];
331
+ } | {
332
+ kind: 'object';
333
+ source: 'query' | 'body';
334
+ fields: string[];
335
+ metatype?: unknown;
336
+ pipes?: unknown[];
337
+ } | {
338
+ kind: 'params';
339
+ fields: string[];
340
+ } | {
341
+ kind: 'request';
342
+ } | {
343
+ kind: 'response';
344
+ } | {
345
+ kind: 'headers';
346
+ data?: string;
347
+ } | {
348
+ kind: 'ip';
349
+ } | {
350
+ kind: 'host';
351
+ data?: string;
352
+ } | {
353
+ kind: 'missing';
354
+ };
355
+ interface RequestLike {
356
+ headers?: Record<string, unknown>;
357
+ ip?: unknown;
358
+ hosts?: Record<string, unknown>;
336
359
  }
337
360
  /**
338
- * Build an OpenAPI `paths` fragment for a set of Silkweave actions, mirroring
339
- * exactly how the `rest()` adapter routes them: the same HTTP verb (`method` ??
340
- * `kind`), the same `path`/`name`-derived route, and the same path/query/body
341
- * field split (`pathParamNames` + `queryParams`). Schemas are inlined from the
342
- * Zod input/output via `z.toJSONSchema`; no shared components are emitted.
361
+ * Reconstruct the controller method's positional arguments from the validated
362
+ * tool `input` (and the request stand-in for `@Req`/`@Headers`/...), then call
363
+ * it. `applyParamPipes` controls whether parameter-bound pipes run.
343
364
  */
344
- declare function buildActionPaths(actions: Action$1[], options?: ActionPathsOptions): Record<string, Record<string, unknown>>;
365
+ declare function invokeRebound(method: (...args: any[]) => any, instance: object, input: Record<string, unknown>, bindings: Binding[], request: RequestLike | undefined, applyParamPipes: boolean): Promise<unknown>;
366
+ /** Map a non-input parameter slot (`@Req`/`@Headers`/`@Ip`/...) to its runtime binding. */
367
+ declare function specialBinding(paramtype: number, data: string | undefined): Binding | null;
345
368
  //#endregion
346
369
  //#region src/lib/silkweave.module.d.ts
347
370
  /**
348
371
  * Root module for `@silkweave/nestjs`.
349
372
  *
350
- * Discovers every `@Action`-decorated method via `DiscoveryService` and
351
- * registers the configured adapters (`rest()`, `trpc()`, `mcp()`) directly on
352
- * Nest's HTTP adapter inside `configure()`. Because `configure()` runs during
353
- * `registerModules` - before Nest's `registerRouter()` step - Silkweave's
354
- * routes always sit ahead of every controller in the Express stack. There is
355
- * no slot middleware, no race with Nest's 404 catch-all, and every route
356
- * shows up in Nest's `RoutesResolver` logger.
373
+ * Discovers every `@Mcp`-decorated **controller method** via `DiscoveryService`,
374
+ * reflects each into a Silkweave action (input schema from the route + parameter
375
+ * decorators + optional OpenAPI document; invocation by re-binding the validated
376
+ * input back into the method), and registers the configured adapter(s) - `mcp()` -
377
+ * directly on Nest's HTTP adapter inside `configure()`.
378
+ *
379
+ * Because `configure()` runs during `registerModules` - before Nest's
380
+ * `registerRouter()` step - Silkweave's routes always sit ahead of every
381
+ * controller in the Express stack. The controllers keep serving HTTP exactly as
382
+ * before; `@Mcp` is purely additive.
357
383
  *
358
384
  * @example
359
385
  * ```ts
@@ -361,13 +387,10 @@ declare function buildActionPaths(actions: Action$1[], options?: ActionPathsOpti
361
387
  * imports: [
362
388
  * SilkweaveModule.forRoot({
363
389
  * silkweave: { name: 'app', description: 'My App', version: '1.0.0' },
364
- * adapters: [
365
- * rest({ basePath: '/api' }),
366
- * trpc({ basePath: '/trpc' }),
367
- * mcp({ basePath: '/mcp' })
368
- * ]
390
+ * adapters: [mcp({ basePath: '/mcp' })]
369
391
  * })
370
- * ]
392
+ * ],
393
+ * controllers: [ChannelsController]
371
394
  * })
372
395
  * export class AppModule {}
373
396
  * ```
@@ -376,50 +399,10 @@ declare class SilkweaveModule implements NestModule {
376
399
  private readonly options;
377
400
  private readonly discovery;
378
401
  private readonly httpAdapterHost;
379
- constructor(options: SilkweaveModuleOptions, discovery: ActionDiscovery, httpAdapterHost: HttpAdapterHost);
402
+ constructor(options: SilkweaveModuleOptions, discovery: ControllerDiscovery, httpAdapterHost: HttpAdapterHost);
380
403
  static forRoot(options: SilkweaveModuleOptions): DynamicModule;
381
404
  configure(_consumer: MiddlewareConsumer): void;
382
405
  }
383
406
  //#endregion
384
- //#region src/lib/swagger.d.ts
385
- interface SilkweaveSwaggerOptions {
386
- /**
387
- * URL prefix the `rest()` adapter mounts on. Defaults to the configured
388
- * `rest()` adapter's `basePath`, falling back to `'/api'`.
389
- */
390
- basePath?: string;
391
- /** OpenAPI tag the actions are grouped under. Default `'Actions'`. */
392
- tag?: string;
393
- /**
394
- * Include actions that are *not* enabled on the REST transport (gated out via
395
- * `transports` / `isEnabled`). Default `false` - the document mirrors the
396
- * routes the `rest()` adapter actually registers.
397
- */
398
- includeDisabled?: boolean;
399
- }
400
- /**
401
- * Merge every REST-exposed Silkweave `@Action` into a NestJS Swagger
402
- * `OpenAPIObject`.
403
- *
404
- * `@nestjs/swagger` builds its document by scanning **controllers**, but
405
- * Silkweave registers action routes directly on the HTTP adapter (so they sit
406
- * ahead of controllers in the request pipeline) - which means the scanner never
407
- * sees them. This helper closes that gap: it discovers the actions through the
408
- * same `ActionDiscovery` provider the `rest()` adapter uses, builds OpenAPI
409
- * paths with the same routing logic (`buildActionPaths`), and merges them into
410
- * the document. The result stays in sync with the live routes without any
411
- * dynamic controllers.
412
- *
413
- * Call it between `SwaggerModule.createDocument()` and `SwaggerModule.setup()`:
414
- *
415
- * @example
416
- * ```ts
417
- * const document = SwaggerModule.createDocument(app, config)
418
- * addSilkweaveActions(app, document)
419
- * SwaggerModule.setup('api/docs', app, document)
420
- * ```
421
- */
422
- declare function addSilkweaveActions(app: INestApplication, document: OpenAPIObject, options?: SilkweaveSwaggerOptions): OpenAPIObject;
423
- //#endregion
424
- export { ACTIONS_METADATA, ACTION_METADATA, ACTION_RESPONSE_KEY, Action, ActionDiscovery, ActionMetadata, ActionPathsOptions, Actions, type ActionsClassMetadata, AnyActionMetadata, type InferTrpcRouter, McpAdapterOptions, NestAdapterRegisterContext, NestSilkweaveAdapter, RestAdapterOptions, ResultToolResult, SILKWEAVE_MODULE_OPTIONS, SilkweaveModule, SilkweaveModuleOptions, SilkweaveSwaggerOptions, type Transport, TrpcAdapterOptions, TypegenAdapterOptions, addSilkweaveActions, buildActionPaths, buildIsEnabled, collectGuards, mcp, rest, runGuards, trpc, typegen };
407
+ export { Binding, ControllerDiscovery, FieldDesc, MCP_METADATA, Mcp, McpAdapterOptions, McpMetadata, NestAdapterRegisterContext, NestSilkweaveAdapter, OpenApiDocument, OpenApiLookup, SILKWEAVE_MODULE_OPTIONS, SilkweaveModule, SilkweaveModuleOptions, apiPropertyToField, buildOpenApiLookup, classValidatorToField, collectGlobalGuards, collectGuards, designTypeToField, fieldToZod, invokeRebound, mcp, mergeField, normalizeEnum, openApiFields, openapiSchemaToField, reflectDtoFields, runGuards, specialBinding, swaggerParamToField, typeTokenToBase };
425
408
  //# sourceMappingURL=index.d.mts.map