@protobase/cli 0.57.6 → 0.58.1

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.
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.57.6";
2
+ var version = "0.58.1";
3
3
  //#endregion
4
4
  export { version };
@@ -15,6 +15,7 @@ const conventionModules = (projectDir) => {
15
15
  "auth/mailer.ts",
16
16
  "config/roles.ts",
17
17
  "assistant/tools.ts",
18
+ "mcp/tools.ts",
18
19
  "audit/queue.ts",
19
20
  "webhooks/owner-roles.ts",
20
21
  "notifications/store.ts",
@@ -90,30 +90,30 @@ const projectRoles = async (config) => {
90
90
  const module = await lastModule(config, "config/roles.ts");
91
91
  return module && (module.roles ?? module.default);
92
92
  };
93
- /**
94
- * The assistant's own tools: the default export of every config folder's assistant/tools.ts, the extensions' first, each
95
- * name once; none while the assistant is off.
96
- */
97
- const projectAssistantTools = async (config) => {
98
- if (config.assistant === false) return [];
93
+ /** The default export of every config folder's `file`, a list of tools, the extensions' first, each name once. */
94
+ const projectTools = async (config, file, kind) => {
99
95
  const found = config.sources.flatMap(({ files, label }) => {
100
- const load = files.module("assistant/tools.ts");
96
+ const load = files.module(file);
101
97
  return load ? [load().then((module) => module.default.map((tool) => ({
102
98
  tool,
103
99
  label
104
100
  })))] : [];
105
101
  });
106
102
  const tools = (await Promise.all(found)).flat();
107
- checkUnique("The assistant tool", tools.map(({ tool, label }) => ({
103
+ checkUnique(kind, tools.map(({ tool, label }) => ({
108
104
  name: tool.name,
109
105
  value: tool,
110
106
  label
111
107
  })));
112
108
  return tools.map(({ tool }) => tool);
113
109
  };
110
+ /** The dock assistant's own tools, of every config folder's assistant/tools.ts; none while the assistant is off. */
111
+ const projectAssistantTools = async (config) => config.assistant === false ? [] : projectTools(config, "assistant/tools.ts", "The assistant tool");
112
+ /** The MCP endpoint's own tools, of every config folder's mcp/tools.ts; none without `auth.mcp` or with `mcpEndpoint: false`. */
113
+ const projectMcpTools = async (config) => !config.auth || !config.auth.mcp || config.mcpEndpoint === false ? [] : projectTools(config, "mcp/tools.ts", "The MCP tool");
114
114
  /**
115
- * The API's options, from the config's top-level keys, with what the conventions find: the roles, write hooks and
116
- * assistant tools, the audit queue of audit/queue.ts and the error hook of hooks/error.ts.
115
+ * The API's options, from the config's top-level keys, with what the conventions find: the roles, write hooks,
116
+ * assistant and MCP tools, the audit queue of audit/queue.ts and the error hook of hooks/error.ts.
117
117
  */
118
118
  const projectOptions = async (config) => {
119
119
  const { apiPath, mcpEndpoint, runtimeUpdates, remoteResources, locale, apiKeys, statementTimeoutMs, scanGuard, defaultAccess, rowPermissions, errorReporting, assistant, cors, maps, plugins } = config;
@@ -134,9 +134,10 @@ const projectOptions = async (config) => {
134
134
  runtime: runtimeUpdates,
135
135
  sources: remoteResources
136
136
  };
137
- const [roles, tools, audit, onUnhandledError] = await Promise.all([
137
+ const [roles, tools, mcpTools, audit, onUnhandledError] = await Promise.all([
138
138
  projectRoles(config),
139
139
  projectAssistantTools(config),
140
+ projectMcpTools(config),
140
141
  lastDefault(config, "audit/queue.ts"),
141
142
  lastDefault(config, "hooks/error.ts")
142
143
  ]);
@@ -150,6 +151,10 @@ const projectOptions = async (config) => {
150
151
  ...options.assistant || {},
151
152
  tools
152
153
  } },
154
+ ...mcpTools.length > 0 && { mcp: {
155
+ ...options.mcp || {},
156
+ tools: mcpTools
157
+ } },
153
158
  ...audit && { audit },
154
159
  ...onUnhandledError && { onUnhandledError }
155
160
  };
@@ -198,4 +203,4 @@ const projectNotifications = async (config) => {
198
203
  });
199
204
  };
200
205
  //#endregion
201
- export { lastModule, mergedModule, projectAssistantTools, projectFiles, projectFunctions, projectJobs, projectNotifications, projectOptions, projectResources, projectRoles, projectWebhooks, projectWriteHooks };
206
+ export { lastModule, mergedModule, projectAssistantTools, projectFiles, projectFunctions, projectJobs, projectMcpTools, projectNotifications, projectOptions, projectResources, projectRoles, projectWebhooks, projectWriteHooks };
@@ -3,16 +3,17 @@ import { checkJobsSchema, startJobs } from "@protobase/server";
3
3
  const store = globalThis;
4
4
  /**
5
5
  * Runs the project's jobs in the dev server: started on the first load, once the jobs schema checks out, with the app's
6
- * own mailer when it has one, and given the reloaded definitions on every load after it, so an edited job runs its new
7
- * code from the next job on. A mailer added or changed later is the jobs' from the next start.
6
+ * own mailer when it has one, and given the reloaded definitions and the rebuilt app's `decryptField` on every load
7
+ * after it, so an edited job runs its new code from the next job on. A mailer added or changed later is the jobs' from the next start.
8
8
  */
9
- const devJobs = async (db, definitions, mailer) => {
10
- if (store.__protobaseJobs) return store.__protobaseJobs.update(definitions);
9
+ const devJobs = async (db, definitions, decryptField, mailer) => {
10
+ if (store.__protobaseJobs) return store.__protobaseJobs.update(definitions, decryptField);
11
11
  if (definitions.length === 0) return;
12
12
  await checkJobsSchema(db);
13
13
  store.__protobaseJobs = await startJobs({
14
14
  db,
15
15
  jobs: definitions,
16
+ decryptField,
16
17
  ...mailer && { mailer },
17
18
  onError: (error) => console.error(error)
18
19
  });
package/dist/dev/entry.js CHANGED
@@ -49,7 +49,7 @@ const ui = {
49
49
  icons: projectIcons(projectDir)
50
50
  };
51
51
  const { admin, jobs } = projectAdmin(project, db, ui, reporter, upgradeWebSocket);
52
- await devJobs(db, jobs, project.mailer);
52
+ await devJobs(db, jobs, admin.decryptField, project.mailer);
53
53
  devRealtimePrune(admin);
54
54
  var entry_default = withDevServiceWorker(new Hono(), Boolean(project.notifications)).route("/", admin);
55
55
  /** Whether the auth store has a user yet, for the banner's sign-in line; undefined without one. */
@@ -48,6 +48,7 @@ const startServe = async ({ config, env, openDb = (url) => openAppDatabase(pg, u
48
48
  db,
49
49
  jobs: definitions,
50
50
  work: env.runJobs,
51
+ decryptField: admin.decryptField,
51
52
  ...project.mailer && { mailer: project.mailer },
52
53
  onError: (error) => console.error(error)
53
54
  }) : void 0;
@@ -29,13 +29,14 @@ const startWorker = async ({ config, databaseUrl, openDb = (url) => openAppDatab
29
29
  return isCaptured(model) || model.comments || Object.values(model.fields).some((field) => field.ai);
30
30
  });
31
31
  if (project.jobs.length === 0 && !builtIn) throw new Error("The bundle has no jobs: name their module in protobase.config.ts as `jobs`, or give a resource events, history, comments or an AI field");
32
- const { jobs: definitions } = projectAdmin(project, db);
32
+ const { admin, jobs: definitions } = projectAdmin(project, db);
33
33
  await checkJobsSchema(db);
34
34
  return {
35
35
  definitions,
36
36
  runtime: await startJobs({
37
37
  db,
38
38
  jobs: definitions,
39
+ decryptField: admin.decryptField,
39
40
  ...project.mailer && { mailer: project.mailer },
40
41
  onError: (error) => console.error(error)
41
42
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.57.6",
3
+ "version": "0.58.1",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -42,12 +42,12 @@
42
42
  "dependencies": {
43
43
  "@better-auth/core": "^1.7.12",
44
44
  "@hono/node-server": "^2.1.3",
45
- "@protobase/config": "0.57.6",
46
- "@protobase/layout": "0.57.6",
47
- "@protobase/query": "0.57.6",
48
- "@protobase/schema": "0.57.6",
49
- "@protobase/server": "0.57.6",
50
- "@protobase/ui": "0.57.6",
45
+ "@protobase/config": "0.58.1",
46
+ "@protobase/layout": "0.58.1",
47
+ "@protobase/query": "0.58.1",
48
+ "@protobase/schema": "0.58.1",
49
+ "@protobase/server": "0.58.1",
50
+ "@protobase/ui": "0.58.1",
51
51
  "@react-email/render": "^2.1.0",
52
52
  "@scalar/hono-api-reference": "^0.12.10",
53
53
  "@tailwindcss/vite": "^4.3.3",
@@ -104,7 +104,7 @@ Reference:
104
104
  - When changing the user menu → read [User menu](references/reference/user-menu.md)
105
105
  - When adding tabs along the bottom of a phone → read [Bottom bar](references/reference/bottom-bar.md)
106
106
  - When configuring the chat beside the admin → read [Assistant](references/reference/assistant.md)
107
- - When letting AI clients read the app's data over MCP, or building an MCP server of your own → read [MCP](references/reference/mcp.md)
107
+ - When letting AI clients read the app's data over MCP, adding MCP tools of the app's own (`mcp/tools.ts`), or building an MCP server of your own → read [MCP](references/reference/mcp.md)
108
108
  - When looking for a command or its options → read [CLI](references/reference/cli.md)
109
109
  - When asking how Protobase is versioned and which bundles a runtime runs → read [Versioning](references/reference/versioning.md)
110
110
  - When looking for an export of `@protobase/schema` → read the [API reference](https://docs.protobase.net/api/schema/)
@@ -19,4 +19,5 @@ Fields and actions filled by a model, the assistant beside the admin, and MCP.
19
19
  - [MCP comments](../reference/mcp.md#comments): AI clients read a record's comments, and with MCP writes on add one after the person approves it.
20
20
  - [MCP batch writes](../reference/mcp.md#batch-writes): When MCP writes are on, AI clients make many creates, updates and deletes across resources in one transaction, after the person approves the batch.
21
21
  - [Connected apps](../reference/auth.md#oauth-for-mcp-clients): People allow an AI client to sign in, and disconnect it later.
22
+ - [MCP tools of your own](../reference/mcp.md#the-apps-own-tools) (beta): `mcp/tools.ts` adds your own tools to the MCP endpoint, which AI clients call as the signed-in person, each change after the person approves it; for now a tool keeps its results small and catches its own refusals.
22
23
  - [MCP address](../reference/mcp.md#connecting-a-client): Signed-in people find the app's MCP address on their account page, copy it or add it to Claude in one click.
@@ -14,7 +14,7 @@ Develop, build and run an app, on servers, in containers and on phones.
14
14
  - [Encryption commands](../reference/cli.md#encryption-status): Report and fix plaintext or old-key values of encrypted fields.
15
15
  - [One bundle](../reference/cli.md#build): `protobase build` writes one folder with everything the app needs, without a database or secrets. It fails on a view that filters, sorts or searches by a field its resource does not allow.
16
16
  - [Source maps](../reference/cli.md#source-maps): The bundle and plugins can carry source maps with debug ids, for an error tracker to read browser stack frames.
17
- - [Extensions](../reference/cli.md#extensions): A host adds its own tools and widgets to every app it builds.
17
+ - [Extensions](../reference/cli.md#extensions): A host adds its own widgets, dock assistant tools (`assistant/tools.ts`) and MCP tools (`mcp/tools.ts`) to every app it builds.
18
18
  - [Native packages](../reference/cli.md#native-packages): npm packages with native add-ons are bundled for Linux.
19
19
  - [Serve runtime](../reference/cli.md#serve): Runs a bundle, set by environment variables, with a health check, startup checks, jobs and a clean shutdown.
20
20
  - [Migrations at update time](../guides/deploy.md#migrations): The bundle carries the project's migrations, and the runtime applies them in one transaction before the new version serves.
@@ -21,6 +21,7 @@ Describe the tables of an existing Postgres database as resources, with their fi
21
21
  - [Recent strong sign-in](../reference/data-config.md#recent-strong-sign-in): A sensitive field can ask for a passkey or a second step in the last minutes before it is revealed. The record page asks the person to confirm it's them, then shows it.
22
22
  - [Computed reveals](../reference/data-config.md#computed-reveals) (beta): A secret kept elsewhere, or built from several values, is revealed like a sensitive field, with the same access, audit and recent sign-in check, but made when it is asked for.
23
23
  - [Encrypted fields](../reference/data-config.md#encrypted-fields): A sensitive text field is encrypted with the app's own key before it is stored, so dumps, backups and SQL readers see only ciphertext. A command encrypts the values a column already holds.
24
+ - [Encrypted fields in jobs and functions](../reference/data-config.md#reading-in-jobs-and-functions) (beta): A job or an API function reads an encrypted value the app must use itself, such as a share's password, and each read is audited like a reveal.
24
25
  - [Encryption key rotation](../reference/data-config.md#the-key): The encryption key can be replaced without downtime. CLI commands re-encrypt stored values and report what is left.
25
26
  - [Schema API reference](../reference/data-config.md#schema-api-reference): Every builder, option and type of `@protobase/schema` has a doc comment, shown in your editor and in the generated API reference, and the types the builders return are exported for helpers of your own.
26
27
  - [Extending a config](../reference/cli.md#extending-a-config): A project can merge other configs and UI configs into its own. A name defined twice is an error, never a silent override.
@@ -50,6 +50,7 @@ The second argument of a handler (`c.env` in a [Hono app](#hono-apps)):
50
50
  | `records` | The app's resources, acting as the caller: `list`, `get`, `create`, `update`, `delete`, `softDeleteField`. |
51
51
  | `db` | The Kysely instance itself. It skips every access rule, row filter and tenant scope. |
52
52
  | `caller()` | Resolves to `{ session, records }`. Public functions use it to ask for a caller when they need one. |
53
+ | `decryptField(resource, key, field)` | An [encrypted field](../reference/data-config.md#reading-in-jobs-and-functions)'s value, skipping access rules like `db`; each read is audited, naming the function and the caller. |
53
54
  | `acceptWebSocket(events)` | Answers a WebSocket upgrade with a socket; return its response. See [WebSockets](#websockets). |
54
55
  | `name` | The function's name. |
55
56
 
@@ -123,8 +123,9 @@ Before answering, the server publishes an audit event to the app's audit queue,
123
123
  type AuditEvent = {
124
124
  type: 'field.revealed'
125
125
  at: string // ISO 8601
126
- actor: { id: string | number; roles: string[] }
127
- tenant?: string | number // the caller's organization, for tenant-scoped resources
126
+ actor?: { id: string | number; roles: string[] } // absent when a job read the value
127
+ reader?: { job: string } | { function: string } // who read it with decryptField; absent for a reveal
128
+ tenant?: string | number // the caller's organization (the record's for decryptField), for tenant-scoped resources
128
129
  resource: string
129
130
  recordKey: string // as in the record's URL
130
131
  field: string
@@ -132,6 +133,8 @@ type AuditEvent = {
132
133
  }
133
134
  ```
134
135
 
136
+ A job or API function that reads an encrypted field with [`decryptField`](data-config.md#reading-in-jobs-and-functions) publishes the same event, with `reader` set and, for a job, no `actor` or `origin` headers.
137
+
135
138
  With [organizations](auth.md#organizations), someone with a global role switching into an organization they are not a member of publishes `{ type: 'organization.entered', at, actor, organization, origin }` first, where `actor.roles` are their global roles; a failed publish refuses the switch. `AuditEvent` is the union of the two.
136
139
 
137
140
  ### Audit events
@@ -66,7 +66,7 @@ Making the query role needs `CREATEROLE` once, for the role that applies the mig
66
66
 
67
67
  ### The app's own tools
68
68
 
69
- `assistant/tools.ts` adds tools of the app's own, which the built-in backend offers after its two: its default export is an array of tools, found by that path when the app starts. A tool is `defineTool({ name, description, parameters, run })` from `@protobase/server`: `parameters` is the JSON Schema of its arguments, and `run(args, context)` returns the text the model reads. A name must be 1 to 64 letters, digits, `_` or `-`, and a name taken twice stops the server at startup. A backend elsewhere has its own tools, so the file does nothing there, nor with `assistant: false`. A tool's `annotations` are MCP's tool hints (`readOnlyHint`, `destructiveHint`, ...), which the dock ignores; the same tools can be offered over the app's [MCP endpoint](mcp.md#building-on-it).
69
+ `assistant/tools.ts` adds tools of the app's own, which the built-in backend offers after its two: its default export is an array of tools, found by that path when the app starts. A tool is `defineTool({ name, description, parameters, run })` from `@protobase/server`: `parameters` is the JSON Schema of its arguments, and `run(args, context)` returns the text the model reads. A name must be 1 to 64 letters, digits, `_` or `-`, and a name taken twice stops the server at startup. A backend elsewhere has its own tools, so the file does nothing there, nor with `assistant: false`. A tool's `annotations` are MCP's tool hints (`readOnlyHint`, `destructiveHint`, ...), which the dock ignores. The file serves the dock only, not the app's MCP endpoint: tools for AI clients over MCP go in `mcp/tools.ts`, which can export these too (see [The app's own tools](mcp.md#the-apps-own-tools) on MCP).
70
70
 
71
71
  `context` holds the user's `session`, `locale` (the language they read, `'en'` or `'nl'`, for the texts a tool shows them such as its approvals; set over MCP, absent in the dock), `show(part)` to add a part to the answer, `approve(request)` for an approval card, `conversation` (the dock's, absent over MCP), `resources()` (the resources the user may read, restricted to their fields, with their views), and `records`: `list(resource, params)` with the REST API's list parameters, `aggregate(resource, { group_by, filter?, limit?, label? })` with its counts per value as `:aggregate` gives them, `get(resource, key)`, `create(resource, data)`, `update(resource, key, data, { etag? })` (without an ETag it updates any version), `delete(resource, key, { etag? })` (soft on a resource with `.softDelete()`) and `softDeleteField(resource)` (the field a delete sets, or `undefined` when a delete removes the record) on the app's resources **as the user**, through their access rules, tenant scope, validation and write hooks, as in the REST API. `get`, `create`, `update` and `delete` each answer `{ record, etag }`, and `list` a page of records. `batch(operations)` runs the operations of a REST [batch write](api.md#batch-writes) in one transaction and answers its `results`; a refusal or a missing record rejects with an `HttpProblem`, whose `detail` a tool can return to the model as text.
72
72
 
@@ -187,10 +187,10 @@ By default the bundle runs on Node and on Bun. `--bun` makes it a bundle for Bun
187
187
 
188
188
  ### Extensions
189
189
 
190
- `--extend <dir>` (repeatable) adds an extension to the bundle without touching the project's files: a folder with a `protobase.config.ts`, a `protobase.ui.tsx` or both. Its config and the code its paths find go into the config module beside the project's, merged before the project's own when the bundle is served, in the order given (see [Extensions](config.md#extensions)). Its `protobase.ui.tsx` becomes one more [plugin](plugins.md) of the bundle, in `public/plugins/<name>/`, named by its `package.json`'s `name`, else its folder's. A host adds its own assistant tools and widgets to every app it builds this way; to add React code to apps without building them, serve a plugin instead.
190
+ `--extend <dir>` (repeatable) adds an extension to the bundle without touching the project's files: a folder with a `protobase.config.ts`, a `protobase.ui.tsx` or both. Its config and the code its paths find go into the config module beside the project's, merged before the project's own when the bundle is served, in the order given (see [Extensions](config.md#extensions)). Its `protobase.ui.tsx` becomes one more [plugin](plugins.md) of the bundle, in `public/plugins/<name>/`, named by its `package.json`'s `name`, else its folder's. A host adds its own widgets, dock assistant tools (`assistant/tools.ts`) and MCP tools (`mcp/tools.ts`) to every app it builds this way; to add React code to apps without building them, serve a plugin instead.
191
191
 
192
192
  - The extension's imports of `@protobase/*` resolve from the project, so it runs on the app's own versions; `react`, `react-dom` and `@protobase/ui` are the app's at runtime, as for every plugin. Everything else it imports resolves from its own folder and is built into its plugin, with a stylesheet of the classes its files use.
193
- - A component, action handler or field type that the extension and the project both define fails the build, naming both. To find them, the build loads the merged UI configs once in Node: only browser code, which needs no secrets. Its server code does not run at build time, so an assistant tool both define fails when the bundle is served, naming both.
193
+ - A component, action handler or field type that the extension and the project both define fails the build, naming both. To find them, the build loads the merged UI configs once in Node: only browser code, which needs no secrets. Its server code does not run at build time, so an assistant or MCP tool both define fails when the bundle is served, naming both.
194
194
  - An error names an extension by its folder. Two extensions whose plugins would have one name fail the build.
195
195
 
196
196
  ### The manifest
@@ -115,9 +115,9 @@ export default defineConfig({ writeHooks: ['queue-sent-invoice'] })
115
115
  ## mcpEndpoint
116
116
 
117
117
  - **Type:** `{ sql?: boolean; writes?: boolean | { resources?: string[]; rolesWithoutApproval?: string[] } } | false`
118
- - **Default:** the read tools only: `list_resources`, `describe_resource`, `list_records`, `count_records` and `get_record`
118
+ - **Default:** the read tools only: `list_resources`, `describe_resource`, `list_records`, `count_records` and `get_record`, then the tools of `mcp/tools.ts`
119
119
 
120
- The MCP endpoint's tools; [`auth.mcp`](sign-in.md#authmcp) turns the endpoint on. `sql: true` also offers admins and the `ai` role `run_read_only_query`, which reads the whole database outside the access rules. `writes: true` offers `create_record`, `update_record`, `delete_record` and `batch_write` through the REST API's rules, each approved by the person in their client; `writes.resources` limits them to the resources named, and `writes.rolesWithoutApproval` lets holders of those roles, such as a service account, write without the approval. `false` is for a host that serves its own MCP endpoint at `auth.mcp.path`, in front of this app. See [MCP](../mcp.md#the-tools).
120
+ The MCP endpoint's tools; [`auth.mcp`](sign-in.md#authmcp) turns the endpoint on. `sql: true` also offers admins and the `ai` role `run_read_only_query`, which reads the whole database outside the access rules. `writes: true` offers `create_record`, `update_record`, `delete_record` and `batch_write` through the REST API's rules, each approved by the person in their client; `writes.resources` limits them to the resources named, and `writes.rolesWithoutApproval` lets holders of those roles, such as a service account, write without the approval. `false` is for a host that serves its own MCP endpoint at `auth.mcp.path`, in front of this app. See [MCP](../mcp.md#the-tools). The app's own tools are the default export of `mcp/tools.ts`, an array of `defineTool(...)`, offered after these; with [extensions](../config.md#extensions), the extensions' come first. See [The app's own tools](../mcp.md#the-apps-own-tools).
121
121
 
122
122
  ```ts
123
123
  export default defineConfig({ auth: { mcp: true }, mcpEndpoint: { writes: { resources: ['tasks'] } } })
@@ -137,6 +137,7 @@ The other files belong to an option, and are described with it:
137
137
  | `hooks/<name>.ts` | [`writeHooks`](config/api.md#writehooks) |
138
138
  | `hooks/error.ts`, `audit/queue.ts` | [Code of the API](config/api.md#code-of-the-api) |
139
139
  | `assistant/tools.ts` | [`assistant`](config/admin-app.md#assistant) |
140
+ | `mcp/tools.ts` | [`mcpEndpoint`](config/api.md#mcpendpoint) |
140
141
  | `jobs/<name>.ts` | [`jobs`](config/jobs-and-events.md#jobs) |
141
142
  | `webhooks/owner-roles.ts` | [`webhooks`](config/jobs-and-events.md#webhooks) |
142
143
  | `notifications/store.ts`, `notifications/history-store.ts`, `notifications/senders.ts` | [`notifications`](config/jobs-and-events.md#notifications) |
@@ -159,6 +160,7 @@ export default defineUi({ extends: [tasksUi] })
159
160
  | resources, views and pages of `config/` | all kept | an error naming both folders |
160
161
  | user menu | at most one among all folders | an error |
161
162
  | assistant tools of `assistant/tools.ts` | the extensions' first, in order, then the app's | an error naming the tool and both folders |
163
+ | MCP tools of `mcp/tools.ts` | the extensions' first, in order, then the app's | an error naming the tool and both folders |
162
164
  | `jobs`, functions, file providers (`files.providers`) | all kept, by name | an error naming the name and both folders |
163
165
  | `files.trustedHosts` | all kept | |
164
166
  | the other keys of `files` | each the app's own; otherwise the last config that sets it | |
@@ -255,7 +255,7 @@ resource('apps')
255
255
 
256
256
  ## Encrypted fields
257
257
 
258
- An encrypted field is a [sensitive field](#sensitive-fields) whose value the server encrypts before it reaches the database, so a dump, a backup, a replica, a realtime subscriber or anyone running SQL sees only ciphertext. Only its reveal decrypts it, for a caller who may read the record and the field, and every reveal is audited. Every API write encrypts it: the record form, REST, batches, imports, [public forms](forms.md) and `records` in [API functions](../guides/api-functions.md). The [Supabase-compatible REST API](supabase-rest.md#encrypted-fields) refuses to write or filter it.
258
+ An encrypted field is a [sensitive field](#sensitive-fields) whose value the server encrypts before it reaches the database, so a dump, a backup, a replica, a realtime subscriber or anyone running SQL sees only ciphertext. Only its reveal decrypts it, for a caller who may read the record and the field, and your own [jobs and functions](#reading-in-jobs-and-functions) on the server; every read is audited. Every API write encrypts it: the record form, REST, batches, imports, [public forms](forms.md) and `records` in [API functions](../guides/api-functions.md). The [Supabase-compatible REST API](supabase-rest.md#encrypted-fields) refuses to write or filter it.
259
259
 
260
260
  ```ts
261
261
  api_key: f.text().encrypted().access({ read: roles.can('keys.read') }),
@@ -275,6 +275,18 @@ When you change a `.sensitive()` field to `.encrypted()`, change every rule, val
275
275
 
276
276
  No other field of the resource may be over the column, as its own or as a relation's column, and another resource over the same table must leave the column out, or declare it `.encrypted()` too with the same `.table()`, tenant and key; the server does not start otherwise. A resource over a view of the table cannot be checked, so leave the column out of the view itself, not only out of the resource.
277
277
 
278
+ ### Reading in jobs and functions
279
+
280
+ A value the app must use itself, such as the password of a backup share, is read on the server with `decryptField(resource, key, field)` of a [job's](jobs.md) context and of a protected [API function's](../guides/api-functions.md#the-context):
281
+
282
+ ```ts
283
+ const password = await context.decryptField('backup_targets', target.id, 'password')
284
+ ```
285
+
286
+ It returns the cleartext, or `null` when the field is empty. Like the context's `db`, it skips access rules, row filters and tenant scope, and reads only live records. `key` is the record's key, or its parts in the order of a composite key. A resource that is unknown, a field that does not exist or is not `.encrypted()`, and a record that does not exist are errors that name them, as is a value that does not decrypt.
287
+
288
+ Every read publishes a `field.revealed` [audit event](api.md#sensitive-fields-and-audit), whose `reader` names the job (`{ job }`, with no `actor`) or the function (`{ function }`, with its caller as `actor`), and the value is only returned once the event is published: when publishing fails, so does the read. A public function has no `decryptField`, since anyone may call it: enqueue a job that reads the value instead. No HTTP request reaches it.
289
+
278
290
  ### The key
279
291
 
280
292
  The app's key is `PROTOBASE_ENCRYPTION_KEY`: 32 random bytes in base64, such as the output of `openssl rand -base64 32`. It is its own: never the app's `secret` (`PROTOBASE_SECRET`) or an API key, nor derived from one, so rotating those loses nothing. Keep it apart from the database's backups, since whoever holds both reads every value. The server does not start with an encrypted field and no key, or a key that is not 32 bytes in base64.
@@ -53,7 +53,7 @@ export default (async ({ invoiceId }, { db }) => {
53
53
  | its name | Letters, digits, `_`, `-`, `.` and `/`; the file `jobs/<name>.ts` holds what it does. |
54
54
  | `description` | What the job does, for the people who read the config. |
55
55
  | `arguments` | Its arguments by name, each a [field type](data-config.md#field-types) such as `'integer'` or `'bigint'`, or the type with options: `{ type: 'enum', values: ['day', 'week'] }`, `{ type: 'text', min: 1 }`, `{ type: 'integer', optional: true }`, `{ type: 'decimal', precision: 8, scale: 2 }`. Each value is checked as a field of that type checks it, when the job is enqueued and again before it runs, and no other argument is taken. A payload refused at run time fails the job for good. The same is JSON in a `protobase.config.json`. |
56
- | the default export of `jobs/<name>.ts` | `(payload, { db, job, signal, mail, sendNotification })`, typed with `JobRun<Payload>` from `@protobase/server`, its payload `JobPayload<typeof config, '<name>'>` (see [Typed names and payloads](#typed-names-and-payloads)): the work. `db` is the app's pool: the enqueuer's transaction has committed by then. `job` holds its `id`, `name`, `attempt`, `maxAttempts` and `startedOn`, when this try took it. `signal` aborts when the try times out or the worker shuts down. `mail` sends mail, see [Mail](#mail). `sendNotification` sends a notification, see [Sending](notifications.md#sending); inside a transaction of `db`, a try that throws in it queues nothing. It is `undefined` in an app without [`notifications`](config/jobs-and-events.md#notifications). |
56
+ | the default export of `jobs/<name>.ts` | `(payload, { db, job, signal, decryptField, mail, sendNotification })`, typed with `JobRun<Payload>` from `@protobase/server`, its payload `JobPayload<typeof config, '<name>'>` (see [Typed names and payloads](#typed-names-and-payloads)): the work. `db` is the app's pool: the enqueuer's transaction has committed by then. `job` holds its `id`, `name`, `attempt`, `maxAttempts` and `startedOn`, when this try took it. `signal` aborts when the try times out or the worker shuts down. `decryptField(resource, key, field)` reads an encrypted field's value, audited, see [Reading in jobs and functions](data-config.md#reading-in-jobs-and-functions). `mail` sends mail, see [Mail](#mail). `sendNotification` sends a notification, see [Sending](notifications.md#sending); inside a transaction of `db`, a try that throws in it queues nothing. It is `undefined` in an app without [`notifications`](config/jobs-and-events.md#notifications). |
57
57
  | `maxAttempts` | Tries before the job is kept as failed; default 10. |
58
58
  | `retryDelay`, `maxRetryDelay` | The wait before the first retry, doubling with each one (with some jitter), and its ceiling; default `2s` and `1 hour`. Milliseconds or text such as `30 seconds`. |
59
59
  | `timeout` | How long one try may run before it counts as failed; default `15 minutes`. |
@@ -2,7 +2,7 @@
2
2
 
3
3
  # MCP
4
4
 
5
- The app's MCP endpoint, through which a person's AI client lists resources, finds and reads records and their comments, and, when turned on, creates and updates them with that person's access and approval.
5
+ The app's MCP endpoint, through which a person's AI client lists resources, finds and reads records and their comments, and, when turned on, creates and updates them with that person's access and approval, besides the app's own tools.
6
6
 
7
7
  An app can serve an MCP endpoint: a person adds its address to an AI client that speaks MCP, such as a chat assistant or a code editor, signs in on the app and allows the client. The client then works with that person's access: it lists the resources and fields they may read, finds records with the API's filters, sorting and pages, and reads one record.
8
8
 
@@ -160,6 +160,70 @@ The person approves the batch once, in their language, seeing each write in it n
160
160
 
161
161
  A batch is checked before the person is asked: an operation other than a create, update or delete, a field an operation does not take, an update without an ETag or more than 500 operations come back as `{ "error": "invalid-argument", "message": ... }` naming the operation, and with writes limited to some resources an operation on any other refuses the whole batch. An update does not set the field a soft delete sets, as `update_record` does not: a delete goes through a delete operation. A refusal while it runs, such as an operation the person may not do or a stale ETag, comes back with the REST batch's `operation` (its index), `op` and `resource`. Either way nothing is written.
162
162
 
163
+ ## The app's own tools
164
+
165
+ `mcp/tools.ts` adds tools of the app's own, offered after the built-in ones to everyone signed in, whatever `mcpEndpoint.writes` says. Its default export is an array of `defineTool(...)` from `@protobase/server`, the same shape as the [assistant's own tools](assistant.md#the-apps-own-tools): a `name` of 1 to 64 letters, digits, `_` or `-`, a `description` the client's model reads, `parameters`, the JSON Schema of its arguments, which the endpoint checks each call against, `annotations`, MCP's tool hints such as `readOnlyHint`, and `run(args, context)`, which returns the text the client reads. The file is found when the app starts, under `protobase dev` and `protobase serve` alike, and only with `auth.mcp` on; with `mcpEndpoint: false` it offers nothing.
166
+
167
+ `context` holds the caller's `session`, the `locale` they read, `approve(request)`, `resources()`, the resources they may read, and `records`, the app's records **as that person**: their role's access rules, tenant, hidden fields, `validate` and write hooks apply, as in the REST API and the built-in tools. Its methods are the assistant's, listed [there](assistant.md#the-apps-own-tools); a refusal rejects with an `HttpProblem`. `show` does nothing over MCP, and there is no `conversation`.
168
+
169
+ A tool that reads:
170
+
171
+ ```ts
172
+ // mcp/tools.ts
173
+ import { defineTool, HttpProblem } from '@protobase/server'
174
+
175
+ const openTasks = defineTool({
176
+ name: 'open_tasks',
177
+ description: "The person's open tasks, newest first: id, title and due date.",
178
+ parameters: { type: 'object', properties: { limit: { type: 'integer', minimum: 1, maximum: 50 } } },
179
+ annotations: { readOnlyHint: true },
180
+ run: async (args, { records }) => {
181
+ const page = await records.list('tasks', { filter: 'status = "open"', order_by: 'created_at desc', page_size: Number(args.limit ?? 10), fields: ['id', 'title', 'due_on'] }).catch((error: unknown) => {
182
+ if (error instanceof HttpProblem) return { error: error.slug, message: error.message }
183
+ throw error
184
+ })
185
+ return JSON.stringify(page)
186
+ },
187
+ })
188
+ ```
189
+
190
+ A tool that changes data asks first, through `approve`, before it changes anything:
191
+
192
+ ```ts
193
+ const closeTask = defineTool({
194
+ name: 'close_task',
195
+ description: 'Marks one task done.',
196
+ parameters: { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'] },
197
+ annotations: { readOnlyHint: false },
198
+ run: async (args, { approve, records }) => {
199
+ const { record, etag } = await records.get('tasks', Number(args.id))
200
+ const answer = await approve({ title: `Close task #${args.id} "${record.title}"?`, fields: [{ label: 'Status', value: 'Done' }], approveLabel: 'Close' })
201
+ if (answer !== 'approved') return JSON.stringify({ closed: false })
202
+ await records.update('tasks', Number(args.id), { status: 'done' }, { etag })
203
+ return JSON.stringify({ closed: true })
204
+ },
205
+ })
206
+
207
+ export default [openTasks, closeTask]
208
+ ```
209
+
210
+ `approve` asks the person through MCP's form elicitation, as the [built-in writes](#writes) do: the client calls the tool again from the start with their answer, so everything before `approve` runs twice and must change nothing. It resolves with `'approved'` only when they approve; declining resolves otherwise, and a client that cannot ask gets the call refused with a message saying so, before anything after `approve` runs. An approval holds once, for the same call with the same arguments, by the same person in the same app, organization and client. A user holding one of [`rolesWithoutApproval`](#writes-without-approval) is approved at once, for these tools too. **A tool that never calls `approve` writes unasked**: whatever it does through `records`, the person's access rules still limit, but nobody is asked first.
211
+
212
+ With [extensions](config.md#extensions), each folder's `mcp/tools.ts` adds its tools, the extensions' first, in order, then the app's. A name two of them use, or one of the built-in tools' names, such as `get_record` or `create_record`, even one the config leaves off, stops the server at startup, naming it.
213
+
214
+ `assistant/tools.ts` stays the dock's: it offers nothing over MCP, since the dock serves only the `admin` and `ai` roles while MCP serves everyone signed in. To offer the dock's tools over MCP too, on purpose, export them from `mcp/tools.ts` as well:
215
+
216
+ ```ts
217
+ // mcp/tools.ts
218
+ import assistantTools from '../assistant/tools'
219
+
220
+ export default [...assistantTools]
221
+ ```
222
+
223
+ A host calling `createAdmin` itself passes the tools as `options.mcp.tools`; the JSON config's `mcpEndpoint` takes none.
224
+
225
+ <gap>An app's own MCP tool cannot have its result kept within a size budget, nor its refusals turned into `{ error, message }`, because neither is implemented for tools outside the built-in ones.</gap> Until then a tool keeps its own results small and catches its own refusals, as `open_tasks` above does; anything else it throws reaches the client as "The server failed to answer.".
226
+
163
227
  ## Browsers and hosts
164
228
 
165
229
  A client in a browser may call the endpoint from any origin: it sends its token, never cookies. A request addressed to another host than that of the app's [`url`](config/app.md#url) is refused, against DNS rebinding.
@@ -172,7 +236,7 @@ The endpoint serves each request on its own, without an MCP session: a `GET` or
172
236
 
173
237
  - `mcpHandler({ authenticate, resource, scope, server })`: the endpoint as a fetch handler. It checks the host, admits a valid token (`mcpGate`) and serves the request with the server that `server(session, request)` builds for its caller; `request` is the HTTP request, such as for the language the person reads.
174
238
  - `mcpServer({ info, instructions, tools, context, report, rolesWithoutApproval, approvals })`: an MCP server named by `info`, its `name`, `version` and `icons`, such as `mcpIcons(origin, icons)`, the app's icons on `origin`, and offering [assistant tools](assistant.md#the-apps-own-tools), each with its JSON Schema and its `annotations`, MCP's tool hints. `context` is the tools' context without `approve`, with the `locale` its approvals are asked in (English when absent): each call gets its own, which asks the client's user, or approves at once when the session's user holds one of `rolesWithoutApproval`. `approvals` is `mcpApprovals()`, built once and passed to every server the endpoint builds: it keeps the approvals asked for until they are answered or expire. `instructions` is what it tells clients when they connect, by default `mcpInstructions`, the advice on reading records above.
175
- - `mcpTools({ db, sql, writes, commented })`: the default tools for a session; `writes` is `true`, `false` or `{ resources, rolesWithoutApproval }`, and `commented` names the resources with comments.
239
+ - `mcpTools({ db, sql, writes, commented, own })`: the endpoint's tools for a session; `writes` is `true`, `false` or `{ resources, rolesWithoutApproval }`, `commented` names the resources with comments, and `own` are [the app's own tools](#the-apps-own-tools), offered after the rest.
176
240
  - `readRecordTools()`, or `listResourcesTool()`, `describeResourceTool()`, `listRecordsTool()` and `getRecordTool()`: the read tools alone; `readOnlyQueryTool(db)` is `run_read_only_query`, and `readWriteQueryTool(db)` proposes one write statement that the user approves before it runs.
177
241
  - `commentTools({ commented }, writes)`, or `listCommentsTool({ commented })` and `addCommentTool({ commented, resources })`: the comment tools on the resources named in `commented`, which call the context's `comments`, and `add_comment` only when `writes` is not `false`.
178
242
  - `writeRecordTools({ resources })`, or `createRecordTool(...)`, `updateRecordTool(...)` and `deleteRecordTool(...)`: the single write tools alone, on the listed resources or, without `resources`, on any; `batchWriteTool({ resources })` is `batch_write` alone.