@appweaver/skill 0.0.0-stage → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,393 @@
1
+ # Mailer
2
+
3
+ The mailer module sends transactional emails. Its driver `SmtpMailer` (provider `smtp`) of `@appweaver/nodemailer` uses
4
+ Nodemailer over SMTP and is selected when the package is installed. The `JsonMailer` of core (provider `json`, selected
5
+ by name only) writes the emails into the log at `debug` (the `mailer` logger) instead of sending them, for development
6
+ and tests. Without a driver, or with `MAILER_PROVIDER=none`, no `Mailer` and no `EmailService` are defined, and the
7
+ email features are unavailable: the email verification and password reset routes are not registered, and the `Email`
8
+ 2FA method is not offered.
9
+
10
+ ## Injecting Mailer
11
+
12
+ Mailer is an optional infrastructure. Inject it with `required: false` to avoid errors when no mailer is selected.
13
+
14
+ ```ts
15
+ import { inject } from '@appweaver/core';
16
+ import { Mailer } from '@appweaver/common';
17
+
18
+ const mailer = inject(Mailer, false); // undefined if not registered
19
+ ```
20
+
21
+ ---
22
+
23
+ #### `mailer.sendEmail(data)`
24
+
25
+ Sends an email. Returns `true` on success.
26
+
27
+ | Field | Type | Required | Description |
28
+ | ----------------- | ------------------------- | -------- | --------------------------------------------------------------------------- |
29
+ | `to` | `string \| string[]` | Yes | Recipient addresses, i.e. `jane@example.com` or `"Jane" <jane@example.com>` |
30
+ | `subject` | `string` | Yes | Email subject line |
31
+ | `text` | `string` | Yes | Plain-text body |
32
+ | `html` | `string` | No | HTML body (falls back to the escaped `text`) |
33
+ | `from` | `string \| EmailSender` | No | Sender, the config by default, see [the sender](#the-sender) |
34
+ | `cc`, `bcc` | `string \| string[]` | No | Copy recipients |
35
+ | `replyTo` | `string` | No | Reply-to address |
36
+ | `headers` | `Record<string, string>` | No | Additional headers |
37
+ | `attachments` | `EmailAttachment[]` | No | Attached files, the same shape for every mailer (below) |
38
+ | `providerOptions` | `Record<string, unknown>` | No | Options of the driver, i.e. passed to `sendMail` by `smtp` |
39
+
40
+ The sender, recipients, headers, attachments and `providerOptions` form the `EmailEnvelope` type, shared by `Email` and
41
+ `TemplateEmail`. An `EmailAttachment` is `{ filename, content, contentType?, encoding? }`, where `content` is a
42
+ `string` or a `Buffer` and `encoding` is `'base64'` or `'utf8'` for a string. An email sent through the queue of
43
+ `EmailService` keeps binary content as a `base64` string with `encoding: 'base64'`.
44
+
45
+ ```ts
46
+ await mailer.sendEmail({
47
+ to: 'alice@example.com',
48
+ subject: 'Welcome!',
49
+ text: 'Thanks for signing up.',
50
+ html: '<p>Thanks for <strong>signing up</strong>.</p>'
51
+ });
52
+ ```
53
+
54
+ **With attachments:**
55
+
56
+ ```ts
57
+ await mailer.sendEmail({
58
+ to: ['bob@example.com', 'carol@example.com'],
59
+ replyTo: 'billing@example.com',
60
+ subject: 'Your invoice',
61
+ text: 'Please find your invoice attached.',
62
+ attachments: [
63
+ {
64
+ filename: 'invoice.pdf',
65
+ content: pdf.toString('base64'),
66
+ encoding: 'base64',
67
+ contentType: 'application/pdf'
68
+ }
69
+ ]
70
+ });
71
+ ```
72
+
73
+ ### The sender
74
+
75
+ The `mailer.senderName` and `mailer.senderAddress` config is the default sender, used by the account emails. `from`
76
+ overrides it with an address string, or with `{ name?, address? }` whose missing parts come from the config. An
77
+ enabled mailer requires `mailer.senderAddress`, without it the application fails to start with `CONFIGURATION_INVALID`.
78
+ `npm create @appweaver` and `weaver module add mailer` set it only in the `test` environment (`no-reply@example.com`,
79
+ for the `json` mailer of the tests), so set it in `config` before the first start.
80
+
81
+ Keep the address on a domain the mailer may send from, otherwise the provider or DMARC rejects it, and put a user's own
82
+ address in `replyTo`:
83
+
84
+ ```ts
85
+ await emailService.sendEmail({
86
+ to,
87
+ from: { name: `${agent.name} via Helpdesk` },
88
+ replyTo: agent.email,
89
+ subject,
90
+ text
91
+ });
92
+ ```
93
+
94
+ ---
95
+
96
+ #### `mailer.checkHealth()`
97
+
98
+ Verifies that the mail transport is reachable (`transporter.verify()` for SMTP). Returns a `HealthCheckResult`.
99
+
100
+ ---
101
+
102
+ #### A driver of another provider
103
+
104
+ A driver of another service (Postmark, SES, ...) extends `Mailer` (`sendEmail`, `checkHealth`), completes the email
105
+ with `completeEmail` of `@appweaver/core` (the sender and the HTML body), and throws a `MailerError`
106
+ (`MAILER_SEND_FAILED` with its `provider` name, and the `status` and `providerCode` of the service) when the service
107
+ rejects an email. `npm create @appweaver module <package> -- --contract mailer` scaffolds it as a module package
108
+ tested with `testMailerContract`, see [modules](./modules.md#creating-a-module-package).
109
+
110
+ ---
111
+
112
+ ## Configuration
113
+
114
+ | Key | Type | Default | Description |
115
+ | ----------------------- | -------- | ------------- | ------------------------------------------------------------------------------------------------------ |
116
+ | `MAILER_PROVIDER` | `string` | `'auto'` | `auto` (`smtp` with `@appweaver/nodemailer`, otherwise none), `smtp`, `json`, `none`, or a module path |
117
+ | `MAILER_SENDER_NAME` | `string` | — | Display name of the default sender, the bare address without one |
118
+ | `MAILER_SENDER_ADDRESS` | `string` | — | Address of the default sender, required by an enabled mailer to start |
119
+ | `MAILER_SMTP_HOST` | `string` | `'127.0.0.1'` | SMTP server hostname |
120
+ | `MAILER_SMTP_PORT` | `int` | `587` | SMTP server port |
121
+ | `MAILER_SMTP_SECURE` | `bool` | `false` | Use TLS (`true` for port 465) |
122
+ | `MAILER_SMTP_USER` | `string` | — | SMTP authentication username |
123
+ | `MAILER_SMTP_PASSWORD` | `string` | — | SMTP authentication password |
124
+
125
+ **`appweaver.json` example:**
126
+
127
+ ```json
128
+ {
129
+ "config": {
130
+ "mailer": {
131
+ "senderName": "My App",
132
+ "senderAddress": "no-reply@myapp.com",
133
+ "smtp": {
134
+ "host": "smtp.mailgun.org",
135
+ "port": 587,
136
+ "user": "postmaster@mg.myapp.com"
137
+ }
138
+ }
139
+ }
140
+ }
141
+ ```
142
+
143
+ Keep the password in the gitignored `.env` as `MAILER_SMTP_PASSWORD`.
144
+
145
+ **Use `JsonMailer` in the tests:**
146
+
147
+ ```json
148
+ {
149
+ "environments": {
150
+ "test": {
151
+ "mailer": {
152
+ "provider": "json"
153
+ }
154
+ }
155
+ }
156
+ }
157
+ ```
158
+
159
+ ---
160
+
161
+ ## Real-world example
162
+
163
+ ```ts
164
+ import { inject } from '@appweaver/core';
165
+ import { Mailer } from '@appweaver/common';
166
+
167
+ export class AuthService {
168
+ private readonly _mailer = inject(Mailer, false);
169
+
170
+ async sendPasswordReset(email: string, token: string): Promise<void> {
171
+ if (!this._mailer) return; // mailer not configured, skip silently
172
+
173
+ await this._mailer.sendEmail({
174
+ to: email,
175
+ subject: 'Reset your password',
176
+ text: `Use this token to reset your password: ${token}`,
177
+ html: `<p>Use this token to reset your password: <strong>${token}</strong></p>`
178
+ });
179
+ }
180
+ }
181
+ ```
182
+
183
+ ---
184
+
185
+ ## EmailService
186
+
187
+ `EmailService` is a higher-level wrapper around `Mailer` that routes all emails through the `Queue` infrastructure. This
188
+ decouples the caller from the SMTP transport, provides retry semantics, and avoids blocking the request thread on email
189
+ delivery.
190
+
191
+ Inject it like any other service. It is defined whenever a `Mailer` and a `Queue` are, so inject it with
192
+ `required: false` in code that must also run without a mailer.
193
+
194
+ ```ts
195
+ import { EmailService, inject } from '@appweaver/core';
196
+ ```
197
+
198
+ Every send method takes an `Email` built by the caller or a [`TemplateEmail`](#template-emails) (one with a
199
+ `template` field), which it renders from the templates of the application before queueing it.
200
+
201
+ ---
202
+
203
+ #### `emailService.sendEmail(email)`
204
+
205
+ Fire-and-forget. Adds the email to the queue and returns immediately — delivery happens asynchronously.
206
+
207
+ ```ts
208
+ await emailService.sendEmail({
209
+ to: 'alice@example.com',
210
+ subject: 'Welcome!',
211
+ text: 'Thanks for signing up.',
212
+ html: '<p>Thanks for <strong>signing up</strong>.</p>'
213
+ });
214
+ ```
215
+
216
+ ---
217
+
218
+ #### `emailService.sendEmailAndWait(email)`
219
+
220
+ Queues the email and resolves only once delivery succeeds, or rejects if it fails. Use this when you need a delivery
221
+ confirmation before proceeding (e.g., before returning a 200 to the client).
222
+
223
+ Returns `true` on success.
224
+
225
+ ```ts
226
+ const sent = await emailService.sendEmailAndWait({
227
+ to: 'bob@example.com',
228
+ subject: 'Your invoice',
229
+ text: 'Please find your invoice attached.',
230
+ attachments: [
231
+ {
232
+ filename: 'invoice.pdf',
233
+ content: pdf.toString('base64'),
234
+ encoding: 'base64'
235
+ }
236
+ ]
237
+ });
238
+ ```
239
+
240
+ ---
241
+
242
+ A failed send fails the job with `MAILER_SEND_FAILED`: a `MailerError` of the driver is kept, any other error is
243
+ wrapped in one naming the selected provider (`details.provider`, i.e. `smtp`) and the subject. `sendEmailAndWait`
244
+ sends the job with an ID of its own and receives its result through the `PubSub` (`queue:email:results`), so it
245
+ resolves on whichever instance the worker sending the email runs, once the email is sent or its last retry failed,
246
+ rejecting with the `MailerError` of the job.
247
+
248
+ ---
249
+
250
+ #### `emailService.sendEmailBulk(emails)`
251
+
252
+ Queues all emails at once without waiting for any to finish. Prefer this when sending a large batch and delivery
253
+ confirmation is not required. The template emails are rendered first, and one that fails to render is logged as an
254
+ error and left out, the others are still queued.
255
+
256
+ ```ts
257
+ await emailService.sendEmailBulk(
258
+ users.map((u) => ({
259
+ to: u.email,
260
+ subject: 'New feature announcement',
261
+ text: `Hi ${u.name}, we just shipped something new...`
262
+ }))
263
+ );
264
+ ```
265
+
266
+ ---
267
+
268
+ #### `emailService.sendEmailBulkAndWait(emails)`
269
+
270
+ Queues all emails and waits for every delivery attempt to settle. Returns an array of
271
+ `{ success: boolean; error?: Error }` in the same order as the input — failed deliveries do not reject the whole call,
272
+ and neither does a template email that fails to render, reported as a failed result while the others are still sent.
273
+
274
+ ```ts
275
+ const results = await emailService.sendEmailBulkAndWait(emails);
276
+
277
+ for (const [i, result] of results.entries()) {
278
+ if (!result.success) {
279
+ logger.error(result.error, `Failed to deliver email to ${emails[i].to}`);
280
+ }
281
+ }
282
+ ```
283
+
284
+ ---
285
+
286
+ #### Template emails
287
+
288
+ A `TemplateEmail` passed to any send method is rendered from the templates of the [template engine](./templates.md) in
289
+ the given locale. The `template` is a name without the format, its templates render the parts of the email:
290
+
291
+ | Template | Renders | Required |
292
+ | -------------------- | ------------------- | ------------------------------------------- |
293
+ | `<template>.html` | The HTML body | No, the escaped text body when missing |
294
+ | `<template>.txt` | The plain text body | No, derived from the HTML body when missing |
295
+ | `<template>.subject` | The subject | Unless `subject` is given |
296
+
297
+ | Field | Type | Required | Description |
298
+ | ---------- | -------------------- | -------- | ------------------------------------------------------------- |
299
+ | `to` | `string \| string[]` | Yes | Recipient addresses |
300
+ | `template` | `string` | Yes | Template name without the format, i.e. `emails/order-shipped` |
301
+ | `data` | `object` | No | The data the templates render |
302
+ | `locale` | `string` | No | The locale to render in, `LOCALE_DEFAULT` by default |
303
+ | `subject` | `string` | No | Used instead of the `.subject` template |
304
+
305
+ The other fields of the `EmailEnvelope` (`from`, `cc`, `bcc`, `replyTo`, `headers`, `attachments`, `providerOptions`)
306
+ are passed on to the rendered email.
307
+
308
+ ```text
309
+ templates/emails/
310
+ ├── order-shipped.html.hbs
311
+ ├── order-shipped.txt.hbs # optional, i.e. for a table laid out as text
312
+ └── order-shipped.subject.hbs # {{t "emails.orderShipped.subject" number=order.number}}
313
+ ```
314
+
315
+ ```ts
316
+ await emailService.sendEmail({
317
+ to: customer.email,
318
+ template: 'emails/order-shipped',
319
+ data: { order, trackingUrl },
320
+ locale: customer.language // decided by the application
321
+ });
322
+ ```
323
+
324
+ `emailService.renderTemplateEmail(email)` returns the rendered `Email` without sending it, i.e. to check it in a test.
325
+ An email needs one of the body templates, without both or without a subject it rejects with `TEMPLATE_NOT_FOUND`, and
326
+ without a loaded template engine with `CONFIGURATION_INVALID`.
327
+
328
+ ### Account emails
329
+
330
+ The account routes send their emails from the templates of the application, always in `LOCALE_DEFAULT`. To send one
331
+ in another locale, call the services directly: `sendEmailVerification` and `sendResetPassword` of `AccountService` take
332
+ the locale as their last argument, `sendChallenge` of `TwoFactorService` as its `locale` option. The framework ships no
333
+ templates of its own:
334
+
335
+ | Template | Data |
336
+ | --------------------------- | ---------------------------------------------- |
337
+ | `emails/verify-email` | `email`, `link` |
338
+ | `emails/password-reset` | `email`, `link` |
339
+ | `emails/two-factor-code` | `email`, `code`, `purpose`, `expiresInMinutes` |
340
+ | `emails/recovery-code-used` | `email` |
341
+
342
+ An email is rendered when its `.html` or `.txt` template exists, with the translated `emails.<email>.subject` key when
343
+ it has no `.subject` template. Without a template, or without the `@appweaver/handlebars` package, it is sent as plain
344
+ text built from the `emails.*` translations, which the framework defines in English and `locales/<locale>.json`
345
+ overrides.
346
+
347
+ A project scaffolded with the `mailer`, `templates` and `locales` modules starts with the `.html` and `.subject`
348
+ templates of all three emails in `templates/emails/`, sharing the `layouts/email.html` layout and the
349
+ `partials/email-button.html` partial, and with their English keys in `locales/en.json`. Their plain text is derived from
350
+ the HTML, add a `.txt` template only for a text that should read differently. Edit them freely, or delete them to send
351
+ the plain text. Without the `locales` module, the templates hold the English texts themselves and there is no `locales/`
352
+ directory; without the `templates` module, the emails are sent as plain text of `locales/en.json`. The `emails` keys are
353
+ added to `locales/en.json` with the mailer only, whichever of the two modules is added first. Removing the `mailer`
354
+ module (`weaver module remove mailer`) deletes these templates and the `emails` keys still holding their English text,
355
+ and without `@appweaver/nodemailer` no mailer is selected. See [templates.md](./templates.md).
356
+
357
+ ---
358
+
359
+ ### Real-world example — post-registration flow
360
+
361
+ ```ts
362
+ import { EmailService, inject } from '@appweaver/core';
363
+
364
+ export class RegistrationService {
365
+ private readonly _emailService = inject(EmailService);
366
+
367
+ async register(user: { email: string; name: string }): Promise<void> {
368
+ // ... persist user to DB ...
369
+
370
+ // Send welcome email and wait for confirmation before returning
371
+ await this._emailService.sendEmailAndWait({
372
+ to: user.email,
373
+ subject: 'Welcome to MyApp!',
374
+ text: `Hi ${user.name}, your account is ready.`,
375
+ html: `<p>Hi <strong>${user.name}</strong>, your account is ready.</p>`
376
+ });
377
+ }
378
+
379
+ async notifyAdmins(
380
+ admins: { email: string }[],
381
+ message: string
382
+ ): Promise<void> {
383
+ // Blast all admin notifications without blocking
384
+ await this._emailService.sendEmailBulk(
385
+ admins.map((a) => ({
386
+ to: a.email,
387
+ subject: 'Admin notification',
388
+ text: message
389
+ }))
390
+ );
391
+ }
392
+ }
393
+ ```
@@ -0,0 +1,245 @@
1
+ # MCP server
2
+
3
+ `@appweaver/mcp` exposes the application to AI agents (Claude, Cursor, ...) over the Model Context Protocol: the
4
+ resource actions a model opts into and the custom tools of `createMcpTool`. Nothing is exposed unless declared, every
5
+ tool runs as the authenticated user so the resource policies apply, and destructive tools need two opt-ins.
6
+
7
+ ```sh
8
+ npm install @appweaver/mcp # or: weaver module add mcp
9
+ ```
10
+
11
+ ## Endpoint and authentication
12
+
13
+ `POST /mcp` (`mcp.routePrefix`, i.e. `/api/mcp` to put it under the API) is the Streamable HTTP transport without
14
+ sessions: a JSON-RPC message (`initialize`, `ping`, `tools/list`, `tools/call`) answered with its JSON response, `202`
15
+ for a notification, `405` for `GET` and `DELETE`. A request authenticates with the strategies of `mcp.auth` (JWT and API
16
+ keys by default); without credentials it is refused with `401` unless `mcp.anonymousEnabled`, which shows only the
17
+ `public` tools. A browser `Origin` not in `mcp.allowedOrigins` is refused with `MCP_ORIGIN_DENIED`.
18
+
19
+ The server speaks the protocol versions `2026-07-28`, `2025-11-25`, `2025-06-18` and `2025-03-26`. An older client
20
+ negotiates one with `initialize`; a stateless client of `2026-07-28` skips it and sends the version with every request,
21
+ in the `MCP-Protocol-Version` header or the `io.modelcontextprotocol/protocolVersion` key of the `_meta` of its params.
22
+ An unsupported version is refused (`400` for the header, a JSON-RPC `-32602` error for the `_meta`), its `data` listing
23
+ the supported versions.
24
+
25
+ ```sh
26
+ claude mcp add --transport http my-api http://localhost:3000/mcp --header "X-Api-Key: <key>"
27
+ ```
28
+
29
+ `tools/list` returns only the tools the user may call.
30
+
31
+ ## OAuth sign-in of the MCP clients
32
+
33
+ Opt-in with `mcp.oauth2.enabled`: an MCP client given only the endpoint URL signs its user in by itself (the MCP
34
+ authorization spec), the application acting as the authorization server:
35
+
36
+ 1. A request without credentials gets `401` with `WWW-Authenticate: Bearer resource_metadata="..."`, the protected
37
+ resource metadata (RFC 9728) at `/.well-known/oauth-protected-resource/mcp`, naming `app.hostname` as the issuer
38
+ of `/.well-known/oauth-authorization-server` (RFC 8414).
39
+ 2. `POST /oauth/register` (RFC 7591) registers a public client of HTTPS or loopback redirect URIs, stored nowhere: the
40
+ `client_id` holds them, signed with the JWT secret or private key.
41
+ 3. `GET /oauth/authorize` (code flow, PKCE `S256`, `resource` checked) shows a page naming the client and its
42
+ redirect host, with a link per OAuth2 provider of `security.oauth2` (`mcp.oauth2.providers` picks them), signing
43
+ in through `/auth/login/<provider>` like the API, and with `mcp.oauth2.passwordEnabled` a form signing in with the
44
+ email and password (see [below](#password-sign-in)). Back at `/oauth/callback`, the user confirms the password of
45
+ an existing account the provider account links to, then passes 2FA when required, on the forms of
46
+ `POST /oauth/sign-in`.
47
+ 4. `POST /oauth/token` exchanges the code, then the refresh token, for the JWTs of the API login. A refresh token is
48
+ used once, like on `POST /auth/refresh` (see [security](./security.md#token-lifetimes-and-refresh-rotation)): a
49
+ replayed or revoked one, or one of a user who has to pass 2FA or enrol a method now, answers `invalid_grant`, and
50
+ the client authorizes again.
51
+
52
+ ```json
53
+ {
54
+ "app": {
55
+ "hostname": "https://api.example.com"
56
+ },
57
+ "mcp": {
58
+ "oauth2": {
59
+ "enabled": true
60
+ }
61
+ },
62
+ "security": {
63
+ "oauth2": {
64
+ "google": {
65
+ "enabled": true,
66
+ "clientId": "...",
67
+ "clientSecret": "..."
68
+ }
69
+ }
70
+ }
71
+ }
72
+ ```
73
+
74
+ - `security.allowedRedirectHosts` must allow the host of `app.hostname`, and `mcp.auth` keep `jwt` (the default).
75
+ - The tokens are valid for the whole API, like the login's, and a logout revokes them.
76
+ - With `mcp.anonymousEnabled` there is no `401`, so no client starts the sign-in.
77
+
78
+ ### Password sign-in
79
+
80
+ `mcp.oauth2.passwordEnabled` adds an email and password form to the sign-in page, below the provider links or alone
81
+ without a provider, for the users without a provider account. It posts to `POST /oauth/sign-in`, signs in with
82
+ `AuthService.login` like `POST /auth/login`, then asks for the 2FA code when the user must pass it.
83
+
84
+ - It is counted with the logins of the API by `checkLoginRateLimit` of `@appweaver/web`: 12 sign-ins of an IP address
85
+ per minute across both, not 12 more ([security.md](./security.md#auth-routes)). A wrong password or the limit shows
86
+ the page again with the error (`401`, `429` with `Retry-After`, `503` while the store fails) and a new state.
87
+ - It needs `formsEnabled`, and is left out with a warning while the login requires a bot check (`login` in the
88
+ `authRoutes` of `security.recaptcha` or `security.turnstile`), since the page cannot run the widget.
89
+ - The page shows the client and the host of its redirect URI: since any client may register, a link of an
90
+ impersonating client is told apart only by that host, as with the providers.
91
+
92
+ ### Sign-in pages
93
+
94
+ The pages are `mcp/sign-in`, `mcp/password`, `mcp/two-factor` and `mcp/error`, never cached nor framed. A wrong
95
+ password of an account to link sends the user back to the client to start again (`access_denied`), like
96
+ `/auth/exchange-token`. `POST /oauth/sign-in` has a secure rate limit, failing with `503` while its store fails. The 2FA
97
+ form
98
+ verifies a code of the default method of the user, sends a new code, or switches to another method of the user or to
99
+ a recovery code; a wrong code is retried until `maxAttempts`, then the client gets `access_denied`.
100
+
101
+ Each page renders the `mcp/<page>.html` template of the template engine when the application has one, otherwise a
102
+ plain HTML page, in the locale of `Accept-Language`. The texts are the `mcp.*` translations, defined in English by the
103
+ framework and overridden by `locales/<locale>.json`, the provider names included (`mcp.signIn.providers.google`, a
104
+ provider without one shown by its name). A project with the `mcp` and `templates` modules starts with the
105
+ four templates and their `layouts/page.html` layout, in the card style of the email layout.
106
+
107
+ | Page | Data |
108
+ | ------------ | ----------------------------------------------------------------------------------------------------------- |
109
+ | `sign-in` | `client`, `host`, `providers` (`{ name, label, url }`), `error`, and `action`, `state` of the password form |
110
+ | `password` | `action`, `state` (posted back as `state`), `error` |
111
+ | `two-factor` | `action`, `state`, `error`, `hint`, `methods` (`{ value, label, selected }`) |
112
+ | `error` | `message` |
113
+
114
+ The forms post `state`, with `username` and `password` (the password form), `password`, or `code`, `method` and
115
+ `action` (`verify` or `resend`).
116
+
117
+ `mcp.oauth2.formsEnabled: false` removes the forms (`POST /oauth/sign-in` answers `404`) and refuses the users who
118
+ must confirm a password or pass 2FA with `access_denied`. The consent page of `/oauth/authorize` always shows.
119
+
120
+ ## Resource tools
121
+
122
+ Opt a model in with the `mcp` key of `createRoutes`, like `events`:
123
+
124
+ ```ts
125
+ export default createRoutes({
126
+ modelName: 'post',
127
+ defaults: { roles: ['editor'] }, // the API routes, and the tools by default
128
+ delete: { roles: ['admin'] },
129
+ mcp: {
130
+ description: 'The articles of the blog.',
131
+ actions: ['find', 'query', 'aggregate', 'create', 'delete'],
132
+ exclude: ['internalNote'], // fields left out of the results, filters and sorts
133
+ maxLimit: 20, // default: mcp.maxLimit
134
+ cache: 10_000 // TTL in ms with mcp.cache.enabled, or false
135
+ }
136
+ });
137
+ ```
138
+
139
+ A tool has the access of its API route (`public`, `roles`, `permissions`, from the route or the `defaults`), so the
140
+ agents of a user can do what the user can do through the API. The `mcp` config overrides it for every action
141
+ (`mcp: { public: true, ... }`) or for one (`{ action: 'delete', roles: ['admin'] }`), the action first. The API route
142
+ may be excluded, the tool still runs. The resource events of `@appweaver/realtime` default the same way to the access
143
+ of the `find` route.
144
+
145
+ | Tool | Arguments | Kind |
146
+ | ---------------- | ---------------------------------------------------- | ----------- |
147
+ | `post_find` | `{ id }` | read-only |
148
+ | `post_query` | `{ filter?, sort?, page?, size?, cursor? }` | read-only |
149
+ | `post_aggregate` | `{ select, filter?, dateField?, from?, to?, step? }` | read-only |
150
+ | `post_create` | the create body of the model | write |
151
+ | `post_update` | `{ id, data }` | destructive |
152
+ | `post_delete` | `{ id }` | destructive |
153
+
154
+ - The tool names are the snake case of the model and the action (`blog_post_query`).
155
+ - The query filter covers the visible scalar fields: a value, or the operators `_eq`, `_ne`, `_gt`, `_gte`, `_lt`,
156
+ `_lte`, `_in`, `_exists` (and `_contains`, `_starts`, `_ends`, `_ilike` on texts), combined with `_or`. The sort is
157
+ `{ field: 'asc' | 'desc' }`.
158
+ - The results are projected onto the response schema of the model, its relations included (no hidden fields, i.e. no
159
+ password hash of an author), and the `exclude` fields are left out of the results, the filter, the sort and the
160
+ aggregations.
161
+ - The string formats of the arguments are checked (`date-time`, `email`, `uuid`, ...), a date with its time zone, i.e.
162
+ `2026-11-19T14:37:00Z` or `2026-11-19T15:37:00+01:00`.
163
+ - The schemas are published as plain JSON Schema, the model references inlined.
164
+
165
+ ## Custom tools
166
+
167
+ ```ts
168
+ export const refundOrder = createMcpTool({
169
+ name: 'refundOrder',
170
+ description: 'Refunds a paid order',
171
+ input: Type.Object({ orderId: Type.Integer(), reason: Type.String() }),
172
+ output: Type.Object({ refundId: Type.String() }), // optional
173
+ roles: ['support'], // or public / permissions
174
+ destructive: true, // or readOnly: true
175
+ handler: ({ orderId, reason }, { user, signal }) =>
176
+ refunds.refund(orderId, reason)
177
+ });
178
+
179
+ createMcpTool({ ...getOrder, roles: ['support'] }); // an AI tool of createAiTool (parameters, execute)
180
+ ```
181
+
182
+ The arguments are validated against `input` (defaults filled in) before the handler runs. A text result is returned
183
+ as text, any other value as JSON text and `structuredContent` (an array or a scalar as `{ result }`).
184
+
185
+ ## Caching
186
+
187
+ Opt-in with `mcp.cache.enabled` (and `cache.enabled`): the successful results of the read-only tools are cached per
188
+ tool, arguments and user (and API key) for `mcp.cache.ttl` ms (default `5000`).
189
+
190
+ - `find`, `query` and `aggregate` resource tools: evicted when their model or an included model changes. The `cache`
191
+ of the `mcp` config sets their TTL, `false` turns it off.
192
+ - Custom tools: `readOnly: true` with `cache: true | <ms>`, evicted on a change of the `cacheRelations` models.
193
+ `cache` without `readOnly` fails with `CONFIGURATION_INVALID`.
194
+
195
+ ```ts
196
+ createMcpTool({
197
+ name: 'topPosts',
198
+ readOnly: true,
199
+ cache: 30_000,
200
+ cacheRelations: ['Post'],
201
+ handler: () => top()
202
+ });
203
+ ```
204
+
205
+ ## Rate limiting
206
+
207
+ Opt-in with `mcp.rateLimit.enabled`: each authenticated user makes at most `mcp.rateLimit.max` tool calls (default
208
+ `60`) per `mcp.rateLimit.window` ms (default `60000`), counted in the `Memory` provider (shared across instances with
209
+ `redis`). Past it a call returns `isError: true` with `MCP_RATE_LIMITED` and `{ limit, retryAfter }` (seconds).
210
+ Anonymous calls are not counted; the server's `rateLimit` still applies to every request.
211
+
212
+ ## Destructive tools
213
+
214
+ `update`, `delete` and every tool marked `destructive` need both:
215
+
216
+ 1. listing the action (or `destructive: true` on the tool), and
217
+ 2. `mcp.destructiveEnabled: true` (default `false`).
218
+
219
+ Until then they are hidden, with a warning logged once. Every tool also carries the `readOnlyHint` and
220
+ `destructiveHint` annotations, so clients can ask the user before running it.
221
+
222
+ ## Errors and limits
223
+
224
+ A failed call returns `isError: true` with `{ code, message, details }` of an Appweaver error (`MCP_INPUT_INVALID`
225
+ for invalid arguments, `RESOURCE_NOT_FOUND`, ...); any other error is logged and returned as `INTERNAL_ERROR`. A
226
+ result over `mcp.maxResultSize` fails with `MCP_RESULT_TOO_LARGE`. An unknown tool, or one the user may not call, is
227
+ the JSON-RPC error `-32602`.
228
+
229
+ ## Logging, telemetry, testing
230
+
231
+ Every call is logged at the info level (`mcp.logCalls`): the tool, the user, the duration and the outcome. Every call
232
+ is a `tools/call <tool>` server span (`mcp.method.name`, `gen_ai.tool.name`) with the `mcp.server.operation.duration`
233
+ metric (`telemetry.instrumentations.mcp`).
234
+
235
+ ```ts
236
+ const mcp = createMcpClient((request) => app.server.inject(request), {
237
+ headers: { 'x-api-key': key }
238
+ });
239
+ const tools = await mcp.listTools();
240
+ const { structuredContent, isError } = await mcp.callTool('post_find', {
241
+ id: 1
242
+ });
243
+ ```
244
+
245
+ `createMcpClient` of `@appweaver/testing` sends the JSON-RPC requests through `inject`, as the user of the headers.