@clegra/sdk 0.0.0-stage → 0.1.0-next.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.
Files changed (81) hide show
  1. package/CHANGELOG.md +158 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE.md +25 -0
  4. package/README.md +258 -2
  5. package/dist/spec/kinds.json +211 -0
  6. package/dist/spec/schema/clegra.schema.json +1249 -0
  7. package/dist/spec/src/cli.d.ts +2 -0
  8. package/dist/spec/src/cli.js +21 -0
  9. package/dist/spec/src/cli.js.map +1 -0
  10. package/dist/spec/src/conformance.d.ts +34 -0
  11. package/dist/spec/src/conformance.js +704 -0
  12. package/dist/spec/src/conformance.js.map +1 -0
  13. package/dist/spec/src/init/index.d.ts +31 -0
  14. package/dist/spec/src/init/index.js +151 -0
  15. package/dist/spec/src/init/index.js.map +1 -0
  16. package/dist/spec/src/init/next-config.d.ts +19 -0
  17. package/dist/spec/src/init/next-config.js +77 -0
  18. package/dist/spec/src/init/next-config.js.map +1 -0
  19. package/dist/spec/src/init/project.d.ts +44 -0
  20. package/dist/spec/src/init/project.js +141 -0
  21. package/dist/spec/src/init/project.js.map +1 -0
  22. package/dist/spec/src/init/templates.d.ts +20 -0
  23. package/dist/spec/src/init/templates.js +166 -0
  24. package/dist/spec/src/init/templates.js.map +1 -0
  25. package/dist/spec/src/init/ui.d.ts +30 -0
  26. package/dist/spec/src/init/ui.js +82 -0
  27. package/dist/spec/src/init/ui.js.map +1 -0
  28. package/dist/spec/src/kinds.d.ts +89 -0
  29. package/dist/spec/src/kinds.js +319 -0
  30. package/dist/spec/src/kinds.js.map +1 -0
  31. package/dist/spec/src/protocol.d.ts +50 -0
  32. package/dist/spec/src/protocol.js +52 -0
  33. package/dist/spec/src/protocol.js.map +1 -0
  34. package/dist/spec/src/rules.d.ts +132 -0
  35. package/dist/spec/src/rules.js +282 -0
  36. package/dist/spec/src/rules.js.map +1 -0
  37. package/dist/src/auth.d.ts +371 -0
  38. package/dist/src/auth.js +964 -0
  39. package/dist/src/auth.js.map +1 -0
  40. package/dist/src/define.d.ts +249 -0
  41. package/dist/src/define.js +83 -0
  42. package/dist/src/define.js.map +1 -0
  43. package/dist/src/embed.d.ts +98 -0
  44. package/dist/src/embed.js +256 -0
  45. package/dist/src/embed.js.map +1 -0
  46. package/dist/src/index.d.ts +11 -0
  47. package/dist/src/index.js +11 -0
  48. package/dist/src/index.js.map +1 -0
  49. package/dist/src/labels.d.ts +10 -0
  50. package/dist/src/labels.js +22 -0
  51. package/dist/src/labels.js.map +1 -0
  52. package/dist/src/manifest.d.ts +499 -0
  53. package/dist/src/manifest.js +188 -0
  54. package/dist/src/manifest.js.map +1 -0
  55. package/dist/src/meaning.d.ts +64 -0
  56. package/dist/src/meaning.js +116 -0
  57. package/dist/src/meaning.js.map +1 -0
  58. package/dist/src/next/index.d.ts +101 -0
  59. package/dist/src/next/index.js +187 -0
  60. package/dist/src/next/index.js.map +1 -0
  61. package/dist/src/node.d.ts +14 -0
  62. package/dist/src/node.js +64 -0
  63. package/dist/src/node.js.map +1 -0
  64. package/dist/src/server.d.ts +229 -0
  65. package/dist/src/server.js +2256 -0
  66. package/dist/src/server.js.map +1 -0
  67. package/dist/src/store.d.ts +129 -0
  68. package/dist/src/store.js +213 -0
  69. package/dist/src/store.js.map +1 -0
  70. package/dist/src/testing.d.ts +133 -0
  71. package/dist/src/testing.js +81 -0
  72. package/dist/src/testing.js.map +1 -0
  73. package/dist/src/types.d.ts +352 -0
  74. package/dist/src/types.js +2 -0
  75. package/dist/src/types.js.map +1 -0
  76. package/dist/src/view.d.ts +35 -0
  77. package/dist/src/view.js +442 -0
  78. package/dist/src/view.js.map +1 -0
  79. package/docs/quickstart.md +350 -0
  80. package/docs/spec.md +997 -0
  81. package/package.json +89 -4
@@ -0,0 +1,2256 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { createMcpHandler, inputRequired, inputResponse, McpServer } from "@modelcontextprotocol/server";
4
+ import { entityKindProblems, keyOf, kindNameProblem, kindDefinitionProblems, kindOfRecord, kindSentence, kindsOf, normaliseKey } from "../spec/src/kinds.js";
5
+ import { DELETE_TOOL, EMBED_TOOL, EXPORT_TOOL, INSTALLATION_TOOL, INSTALLATION_TOOLS, LATER_TOOL, META_KEY, OAUTH_SCOPE, PROTOCOL_ID, RESOLVE_TOOL, URI_SCHEME, uriPrefix } from "../spec/src/protocol.js";
6
+ import { LIMITS, manifestRuleProblems } from "../spec/src/rules.js";
7
+ import { z } from "zod";
8
+ import { argsHash, AuthError, canonicalJson, DEV_ISSUER, DevAuthority, INSTALLATION, isLoopback, laterDeadline, signConfirmation, tenantOf, TokenVerifier } from "./auth.js";
9
+ import { EmbedAuthority, EmbedError } from "./embed.js";
10
+ import { MANIFEST_PATH, manifestUri, SPEC_VERSION } from "./manifest.js";
11
+ import { isLabel, labelMap, localize } from "./labels.js";
12
+ import { fieldsOf, jsonSchemaOf, kindRef, localRef, plainSchema } from "./meaning.js";
13
+ import { MemoryStore } from "./store.js";
14
+ import { MCP_APP_MIME_TYPE, urlPageHtml, viewHtml } from "./view.js";
15
+ /** The issuer name of callers named by the app's own `auth.resolve`. */
16
+ export const OWN_ISSUER = "app";
17
+ /** The one `_meta` key of the host protocol (spec §7): `{ call, confirmation, settings }` on requests, `{ notifications, untrusted, l10n }` on results. */
18
+ export { META_KEY };
19
+ const hostMeta = (meta) => {
20
+ const m = meta?.[META_KEY];
21
+ return m && typeof m === "object" && !Array.isArray(m) ? m : {};
22
+ };
23
+ /** A failure a handler may throw on purpose: it reaches the caller as `{ error: { code, message } }`. */
24
+ export class AppError extends Error {
25
+ code;
26
+ details;
27
+ constructor(code, message, details) {
28
+ super(message);
29
+ this.code = code;
30
+ this.details = details;
31
+ this.name = "AppError";
32
+ }
33
+ }
34
+ const NAME = /^[a-z][a-z0-9-]{1,39}$/;
35
+ const IDENT = /^[a-z][a-z0-9_]{0,39}$/;
36
+ const PERMISSION = /^[a-z][a-z0-9_-]{0,39}\.[a-z][a-z0-9_-]{0,39}$/;
37
+ const RESERVED_PARAMS = new Set(["query", "sort", "dir", "cursor", "limit", "id"]);
38
+ const RESERVED_TOOLS = new Set(["search", "fetch", RESOLVE_TOOL, EMBED_TOOL, ...INSTALLATION_TOOLS]);
39
+ /** How far in the past a later run's `at` may be when it is confirmed, and how far ahead. */
40
+ const LATER_PAST_MS = 5 * 60_000;
41
+ const LATER_AHEAD_MS = 366 * 24 * 3600_000;
42
+ /** Later runs taken per pass. */
43
+ const LATER_BATCH = 25;
44
+ /** The largest export a host takes. */
45
+ const EXPORT_MAX_BYTES = 512 * 1024 * 1024;
46
+ /** The words of the SDK's own notification when a later run did not run, per language (the app's locale when the caller's is missing). */
47
+ const DID_NOT_RUN = { en: (t) => `«${t}» did not run`, it: (t) => `«${t}» non è stata eseguita` };
48
+ /** The SDK's notification type for later runs that did not run. */
49
+ const LATER_NOTIFICATION = { label: { en: "Scheduled actions that did not run", it: "Azioni programmate non eseguite" }, description: { en: "An action you confirmed for later expired or was refused.", it: "Un'azione confermata per dopo è scaduta o è stata rifiutata." }, default: true };
50
+ /** The `_meta` of a tool only views and the host's own UI call: never a model's (MCP Apps visibility, ChatGPT). */
51
+ const APP_ONLY_META = { ui: { visibility: ["app"] }, "openai/visibility": "private", "openai/widgetAccessible": true };
52
+ /** The fixed hint on the tools of an entity with cross-app references (spec §3.2): how a model opens such a record. */
53
+ export const CROSS_INPUT_HINT = "An input that takes a record of another app takes its URI (clegra://<app>/<entity>/<id>), as that app's search or lists give it.";
54
+ export const CROSS_APP_HINT = "A record of another app appears as { uri, kind }: the app the URI names opens it with its fetch tool.";
55
+ /** JSON Schema formats of key properties (spec §6: a key filter carries `format` where JSON Schema has one). */
56
+ const KEY_FORMATS = { email: "email" };
57
+ /** A field as the kind rules read it (spec/src/kinds.ts): its meaning, and an array's item type. */
58
+ function kindField(f) {
59
+ const items = f.schema.items;
60
+ const itemType = f.type === "array" && items && typeof items.type === "string" ? items.type : undefined;
61
+ return { name: f.name, type: f.type, required: f.required, ...(f.enum ? { enum: f.enum } : {}), ...(f.permission ? { permission: f.permission } : {}), ...(f.as !== undefined ? { as: f.as } : {}), ...(f.filter ? { filter: true } : {}), ...(f.currency ? { currency: f.currency } : {}), ...(itemType ? { itemType } : {}) };
62
+ }
63
+ const b64url = (s) => Buffer.from(s, "utf8").toString("base64url");
64
+ const unb64url = (s) => Buffer.from(s, "base64url").toString("utf8");
65
+ const sortedJson = canonicalJson;
66
+ // ------------------------------------------------------------ untrusted text
67
+ const XML = { "&": "&amp;", "<": "&lt;", ">": "&gt;", "\uFF1C": "&lt;", "\uFF1E": "&gt;", "\uFE64": "&lt;", "\uFE65": "&gt;" };
68
+ /**
69
+ * Text written by outsiders, as a model reads it (spec §7): inside
70
+ * `<untrusted>`, with `&`, `<` and `>` (and their full-width and small
71
+ * forms) escaped as XML text, so nothing in it is a tag: it can't close or
72
+ * open the wrapper, plainly, nested or already encoded.
73
+ */
74
+ export const untrustedText = (value) => `<untrusted>${value.replace(/[&<>\uFF1C\uFF1E\uFE64\uFE65]/g, (c) => XML[c])}</untrusted>`;
75
+ /**
76
+ * The key of a record action's display hint (spec §6 rule 10): the record's title as the model read it, for a client's
77
+ * own approval prompt. Never trusted: the app names the record from `id`; a hint that names another record stops the call.
78
+ */
79
+ export const RECORD_TITLE_PARAM = "record_title";
80
+ /** A title compared as a person reads it: the untrusted wrapper and its escapes undone, case, width, quotes and spaces ignored. */
81
+ const comparableTitle = (value) => value
82
+ .replace(/<\/?untrusted>/g, "")
83
+ .replace(/&lt;/g, "<")
84
+ .replace(/&gt;/g, ">")
85
+ .replace(/&amp;/g, "&")
86
+ .normalize("NFKC")
87
+ .toLowerCase()
88
+ .replace(/\s+/g, " ")
89
+ .trim()
90
+ .replace(/^["'«»“”‘’]+|["'«»“”‘’]+$/g, "")
91
+ .trim();
92
+ const pointerKey = (k) => k.replace(/~/g, "~0").replace(/\//g, "~1");
93
+ /** Every string inside `value` (at any depth) wrapped as untrusted, its JSON pointer noted. `skip`: keys left as they are. */
94
+ function markAll(value, pointer, pointers, skip) {
95
+ if (typeof value === "string") {
96
+ pointers.push(pointer);
97
+ return untrustedText(value);
98
+ }
99
+ if (Array.isArray(value))
100
+ return value.map((v, i) => markAll(v, `${pointer}/${i}`, pointers, skip));
101
+ if (value && typeof value === "object")
102
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, skip?.has(k) ? v : markAll(v, `${pointer}/${pointerKey(k)}`, pointers, skip)]));
103
+ return value;
104
+ }
105
+ /** A template's keys that are never free text. */
106
+ const TEMPLATE_KEYS = new Set(["uri", "kind", "format", "currency"]);
107
+ const text = (t) => [{ type: "text", text: t }];
108
+ const shownLabels = new AsyncLocalStorage();
109
+ /**
110
+ * A label in `locale`; inside a tool call, its other locales are noted too, so the call's view can draw it
111
+ * in the reader's language (MCP Apps `hostContext.locale`), whatever language the token named.
112
+ */
113
+ function say(label, locale, fallback) {
114
+ const shown = localize(label, locale, fallback);
115
+ const notes = shownLabels.getStore();
116
+ if (notes && label && typeof label === "object" && shown) {
117
+ for (const [l, value] of Object.entries(label)) {
118
+ if (typeof value !== "string" || value === shown)
119
+ continue;
120
+ let d = notes.get(l);
121
+ if (!d)
122
+ notes.set(l, (d = {}));
123
+ d[shown] ??= value;
124
+ }
125
+ }
126
+ return shown;
127
+ }
128
+ /** The labels a call showed, beside its result (`_meta.clegra.l10n`), for its view only: a model never reads `_meta`. */
129
+ function withL10n(result, notes) {
130
+ if (!notes.size)
131
+ return result;
132
+ const meta = (result._meta ?? {});
133
+ const own = (meta[META_KEY] && typeof meta[META_KEY] === "object" ? meta[META_KEY] : {});
134
+ return { ...result, _meta: { ...meta, [META_KEY]: { ...own, l10n: Object.fromEntries(notes) } } };
135
+ }
136
+ /**
137
+ * A tool's input as it is listed (the same JSON Schema), left for the SDK's own handler to check: an action's
138
+ * input is validated there (#runAction), so what is wrong is said field by field, in the caller's language,
139
+ * as a tool error a view and a model can read, not as a protocol error in English.
140
+ */
141
+ function listedOnly(schema, title) {
142
+ const std = schema["~standard"];
143
+ // Listed as plain JSON Schema: the meaning keys (`label`, `ref`, `currency`, …) are the manifest's, a plain client gets each field's `title`.
144
+ const listed = () => {
145
+ const raw = jsonSchemaOf(schema, "input");
146
+ const plain = plainSchema(raw);
147
+ for (const [k, p] of Object.entries(raw.properties ?? {}))
148
+ if (isLabel(p.label) && plain.properties?.[k])
149
+ plain.properties[k].title = title(p.label);
150
+ return plain;
151
+ };
152
+ return { "~standard": { ...std, validate: (value) => ({ value }), jsonSchema: { input: listed, output: listed } } };
153
+ }
154
+ /** Whether the client of this request can answer an elicitation (MCP 2026-07-28: capabilities ride every request). */
155
+ function elicits(ctx) {
156
+ const caps = ctx.mcpReq.envelope?.["io.modelcontextprotocol/clientCapabilities"];
157
+ return Boolean(caps?.elicitation);
158
+ }
159
+ function failure(code, message, details) {
160
+ return { isError: true, content: text(message), structuredContent: { error: { code, message, ...details } } };
161
+ }
162
+ export class AppServer {
163
+ name;
164
+ options;
165
+ locale;
166
+ #verifier;
167
+ #dev;
168
+ #store;
169
+ #entities = new Map();
170
+ #actions = new Map();
171
+ #pages = new Map();
172
+ #fragments = new Map();
173
+ #agents = new Map();
174
+ #permissions = new Map();
175
+ #settings = new Map();
176
+ #schedules = new Map();
177
+ #notificationTypes = new Map();
178
+ #nav = null;
179
+ #lifecycle = {};
180
+ #kinds = {};
181
+ #manifest = null;
182
+ #devReady = null;
183
+ #path;
184
+ #embed;
185
+ #warnedStore = false;
186
+ #handler = createMcpHandler((ctx) => {
187
+ const extra = ctx.authInfo?.extra;
188
+ return this.createMcpServer(extra?.caller ?? null, ctx.era, extra?.request);
189
+ }, {
190
+ legacy: "stateless",
191
+ onerror: (e) => console.error(`[${PROTOCOL_ID}]`, e.message),
192
+ });
193
+ constructor(options) {
194
+ if (!NAME.test(options.name))
195
+ throw new Error(`name "${options.name}": lowercase letters, digits and -, 2 to 40 characters (it is the app id)`);
196
+ this.name = options.name;
197
+ this.options = options;
198
+ this.locale = options.locale ?? "en";
199
+ const auth = options.auth ?? {};
200
+ if (auth.dev && process.env.NODE_ENV === "production")
201
+ throw new Error("auth.dev is for development: it is refused when NODE_ENV is production");
202
+ if (auth.anonymous && process.env.NODE_ENV === "production")
203
+ throw new Error("auth.anonymous is for local demos: it is refused when NODE_ENV is production");
204
+ const path = (options.path ?? "").replace(/\/+$/, "");
205
+ if (path && !/^(\/[A-Za-z0-9._~-]+)+$/.test(path))
206
+ throw new Error(`path "${options.path}": a URL path like /api/clegra`);
207
+ this.#path = path;
208
+ this.#store = options.store ?? new MemoryStore();
209
+ this.#verifier = new TokenVerifier(auth, (key, ttlMs) => this.#store.once(key, ttlMs));
210
+ this.#dev = auth.dev ? new DevAuthority(auth.dev === true ? {} : auth.dev, { name: this.name, title: localize(options.title, this.locale, this.locale), allPermissions: () => [...this.#permissions.keys()] }) : null;
211
+ if (this.#dev)
212
+ this.#verifier.useDev(this.#dev);
213
+ this.#embed = options.embed ? new EmbedAuthority(options.embed, this.#store, () => this.#embedPages()) : null;
214
+ }
215
+ // ------------------------------------------------------------ embedded pages (spec §5.1)
216
+ /** The same-site `url` pages: the ones a ticket opens. */
217
+ #embedPages() {
218
+ return [...this.#pages.values()].flatMap((p) => (p.config.kind === "custom" && "url" in p.config && p.config.url.startsWith("/") ? [{ name: p.name, path: p.config.url.split(/[?#]/)[0] }] : []));
219
+ }
220
+ /** The app's origin for tickets and sessions: its configured public address, else the one the request reached. */
221
+ #appOrigin(requestOrigin) {
222
+ const resource = this.options.auth?.resource;
223
+ return resource ? new URL(resource).origin : requestOrigin;
224
+ }
225
+ /** The embedded pages' side for the route in front of them: null when the app declares no `embed`. */
226
+ get embed() {
227
+ const e = this.#embed;
228
+ if (!e)
229
+ return null;
230
+ return {
231
+ path: e.path,
232
+ exchangePath: e.exchangePath,
233
+ headers: () => e.headers(),
234
+ exchange: async (request) => {
235
+ const problem = this.#productionProblem();
236
+ if (problem)
237
+ return e.refusal(new EmbedError(500, "misconfigured", problem));
238
+ return e.exchange(request, this.#appOrigin(this.#origin(request)));
239
+ },
240
+ caller: async (page, request) => {
241
+ const header = request.headers.get("cookie") ?? "";
242
+ const name = e.cookieName(page);
243
+ const value = header.split(/;\s*/).find((c) => c.startsWith(`${name}=`))?.slice(name.length + 1);
244
+ return e.session(page, value, request.headers.get("sec-fetch-dest"), this.#appOrigin(this.#origin(request)));
245
+ },
246
+ };
247
+ }
248
+ // ------------------------------------------------------------ registration
249
+ #taken(name) {
250
+ if (this.#entities.has(name) || this.#fragments.has(name))
251
+ throw new Error(`"${name}" is already an entity or a fragment type (they share one namespace)`);
252
+ }
253
+ #changed() {
254
+ this.#manifest = null;
255
+ }
256
+ #toolNames = new Set();
257
+ #claimTools(...names) {
258
+ for (const n of names) {
259
+ if (!/^[a-zA-Z0-9_.-]{1,64}$/.test(n))
260
+ throw new Error(`tool name "${n}": letters, digits, _ . -; at most 64`);
261
+ if (this.#toolNames.has(n) || RESERVED_TOOLS.has(n))
262
+ throw new Error(`tool name "${n}" is taken or reserved`);
263
+ this.#toolNames.add(n);
264
+ }
265
+ }
266
+ /** The namespaced kinds this app defines (spec §3.1), before any entity that uses them. */
267
+ defineKinds(kinds) {
268
+ if (this.#entities.size)
269
+ throw new Error("kinds: define them before the entities");
270
+ const problems = kindDefinitionProblems(kinds);
271
+ if (problems.length)
272
+ throw new Error(problems.join("; "));
273
+ this.#kinds = { ...kinds };
274
+ this.#changed();
275
+ }
276
+ /** An entity (spec §4): a Zod object with `.meta()` meaning, and its reads. */
277
+ registerEntity(name, config) {
278
+ if (!IDENT.test(name))
279
+ throw new Error(`entity "${name}": lowercase letters, digits and _, starting with a letter`);
280
+ this.#taken(name);
281
+ const fields = fieldsOf(name, config.schema);
282
+ for (const f of fields)
283
+ if ((f.filter || f.sort) && RESERVED_PARAMS.has(f.name) && f.name !== "id")
284
+ throw new Error(`entity "${name}": field "${f.name}" can't be a filter or sort (reserved parameter name)`);
285
+ // Kinds (spec §3.1): what `as` says must hold for the entity's kind, or the definition fails here, not at a host.
286
+ const own = this.#kinds;
287
+ const problems = entityKindProblems(`entity "${name}"`, config.kind, fields.map(kindField), own);
288
+ if (problems.length)
289
+ throw new Error(problems.join("; "));
290
+ const keys = new Map();
291
+ for (const f of fields) {
292
+ const how = f.as ? keyOf(f.as, kindsOf(config.kind), own) : null;
293
+ if (how)
294
+ keys.set(f.name, { property: f.as, how });
295
+ }
296
+ const handle = { kind: "entity", name, schema: config.schema, fields, uri: (id) => this.uri(name, id) };
297
+ const plain = config.expose?.plain !== false;
298
+ const tools = { list: { name: config.expose?.list ?? `${name}_list`, plain }, get: { name: config.expose?.get ?? `${name}_get`, plain } };
299
+ this.#claimTools(tools.list.name, tools.get.name);
300
+ this.#entities.set(name, { name, config: config, fields, handle: handle, tools, keys });
301
+ this.#changed();
302
+ return handle;
303
+ }
304
+ /** An action (spec §5), on an entity's records or global. */
305
+ registerAction(name, config, handler) {
306
+ if (!IDENT.test(name))
307
+ throw new Error(`action "${name}": lowercase letters, digits and _`);
308
+ const entity = config.entity ? this.#entities.get(config.entity.name) : undefined;
309
+ if (config.entity && !entity)
310
+ throw new Error(`action "${name}": entity "${config.entity.name}" is not registered here`);
311
+ const tool = config.expose?.tool ?? (entity ? `${entity.name}_${name}` : name);
312
+ if (this.#actions.has(tool))
313
+ throw new Error(`action "${name}": its tool name "${tool}" is taken`);
314
+ this.#claimTools(tool);
315
+ const input = (config.input ?? z.object({}));
316
+ if (entity && "id" in input.shape)
317
+ throw new Error(`action "${name}": "id" is the record's id, given by the SDK; don't declare it in input`);
318
+ if (entity && RECORD_TITLE_PARAM in input.shape)
319
+ throw new Error(`action "${name}": "${RECORD_TITLE_PARAM}" is the record's title hint, given by the SDK; don't declare it in input`);
320
+ const write = config.readOnly !== true;
321
+ const confirm = write ? (config.confirm ?? "always") : "never";
322
+ // Writes reach plain MCP clients only when the developer opts in (spec §6).
323
+ const plain = config.expose?.plain ?? !write;
324
+ if (config.later && !this.#store.later)
325
+ throw new Error(`action "${name}": later keeps the confirmed call in the store, and this store has no later part (MemoryStore and SqlStore have one)`);
326
+ const later = config.later ? { at: String(config.later.at), window: config.later.window ?? LIMITS.laterWindow.default } : undefined;
327
+ this.#actions.set(tool, { name, tool, ...(entity ? { entity } : {}), config: config, input, handler: handler, write, confirm, plain, ...(later ? { later } : {}) });
328
+ this.#changed();
329
+ return { kind: "action", name, tool };
330
+ }
331
+ /** A page (spec §6). Every entity has a `record` page by default; registering one with its name replaces it. */
332
+ registerPage(name, config) {
333
+ if (!IDENT.test(name))
334
+ throw new Error(`page "${name}": lowercase letters, digits and _`);
335
+ if (this.#pages.has(name) && !this.#pages.get(name).derived)
336
+ throw new Error(`page "${name}" is registered twice`);
337
+ if ((config.kind === "list" || config.kind === "record") && !this.#entities.has(config.entity.name))
338
+ throw new Error(`page "${name}": entity "${config.entity.name}" is not registered here`);
339
+ if (config.kind === "list") {
340
+ const fields = this.#entities.get(config.entity.name).fields;
341
+ for (const c of config.columns)
342
+ if (!fields.some((f) => f.name === c))
343
+ throw new Error(`page "${name}": column "${c}" is not a field of ${config.entity.name}`);
344
+ if (config.params && !config.query)
345
+ throw new Error(`page "${name}": with params, give query(params) too`);
346
+ }
347
+ if (config.kind === "custom" && "url" in config && !/^https:\/\//.test(config.url) && !/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?\//.test(config.url) && !/^\/(?!\/)[^\s\\]*$/.test(config.url))
348
+ throw new Error(`page "${name}": url must be https, or a path on the app's own site (/embed/…)`);
349
+ if (config.kind === "custom" && "url" in config && config.url.startsWith("/")) {
350
+ if (!this.#embed)
351
+ throw new Error(`page "${name}": a page on the app's own site (${config.url}) is framed by hosts on other sites, so it needs \`embed\` in defineApp (frameAncestors and a signing secret, spec §5.1)`);
352
+ const path = config.url.split(/[?#]/)[0];
353
+ if (!path.startsWith(`${this.#embed.path}/`) || path === this.#embed.exchangePath || !/^(\/[a-z0-9][a-z0-9._~-]*)+$/.test(path))
354
+ throw new Error(`page "${name}": url ${config.url} must be a page under ${this.#embed.path}/ (embed.path)`);
355
+ if (config.url !== path)
356
+ throw new Error(`page "${name}": url ${config.url}: a same-site embed page is a path without query or fragment`);
357
+ }
358
+ const tool = config.kind === "record" ? this.#entities.get(config.entity.name).tools.get : { name: config.expose?.tool ?? `open_${name}`, plain: config.expose?.plain !== false };
359
+ if (config.kind !== "record")
360
+ this.#claimTools(tool.name);
361
+ this.#pages.set(name, { name, config: config, tool });
362
+ this.#changed();
363
+ return { kind: "page", name };
364
+ }
365
+ /** A fragment type (spec §7): params, live data, a native template or an MCP Apps view. */
366
+ registerFragment(type, config) {
367
+ if (!IDENT.test(type))
368
+ throw new Error(`fragment "${type}": lowercase letters, digits and _`);
369
+ this.#taken(type);
370
+ if (!config.template && !config.view)
371
+ throw new Error(`fragment "${type}": give a template or a view`);
372
+ const tool = { name: config.expose?.tool ?? `show_${type}`, plain: config.expose?.plain !== false };
373
+ this.#claimTools(tool.name);
374
+ this.#fragments.set(type, { type, config: config, tool });
375
+ this.#changed();
376
+ return { kind: "fragment", type };
377
+ }
378
+ /** An agent (spec §8): run by the host's model, with these tools. */
379
+ registerAgent(name, config) {
380
+ if (!IDENT.test(name))
381
+ throw new Error(`agent "${name}": lowercase letters, digits and _`);
382
+ if (!config.tools.length)
383
+ throw new Error(`agent "${name}": give it at least one tool`);
384
+ this.#agents.set(name, config);
385
+ this.#changed();
386
+ }
387
+ /** A permission (spec §8): `group.verb`. Returns its id. */
388
+ registerPermission(id, config) {
389
+ if (!PERMISSION.test(id))
390
+ throw new Error(`permission "${id}": group.verb, lowercase`);
391
+ this.#permissions.set(id, config);
392
+ this.#changed();
393
+ return id;
394
+ }
395
+ /** The navigation: sections of pages (their references are checked with the manifest). */
396
+ registerNav(sections) {
397
+ this.#nav = sections.map((s) => ({ ...s, pages: [...s.pages] }));
398
+ this.#changed();
399
+ }
400
+ /** A schedule: a global action the workspace host runs as the installation every `every` minutes. */
401
+ registerSchedule(name, config) {
402
+ if (name === LATER_TOOL)
403
+ throw new Error(`schedule "${name}" is reserved (the SDK runs later actions with it)`);
404
+ if (this.#schedules.has(name))
405
+ throw new Error(`schedule "${name}" is registered twice`);
406
+ this.#schedules.set(name, { action: config.action, every: config.every, maxSeconds: config.maxSeconds ?? LIMITS.scheduleSeconds.default });
407
+ this.#changed();
408
+ }
409
+ /** A notification type the app's notifications name (`ctx.notify({ type })`). */
410
+ registerNotificationType(type, config) {
411
+ if (type === LATER_TOOL)
412
+ throw new Error(`notification "${type}" is reserved (the SDK tells a later run's author with it)`);
413
+ if (!IDENT.test(type))
414
+ throw new Error(`notification "${type}": lowercase letters, digits and _, starting with a letter`);
415
+ this.#notificationTypes.set(type, config);
416
+ this.#changed();
417
+ }
418
+ /** What the app does when the workspace host tells it of its installation, asks for its data, or asks it to delete them. */
419
+ registerLifecycle(config) {
420
+ for (const [k, v] of Object.entries(config)) {
421
+ if (!["installation", "export", "delete"].includes(k))
422
+ throw new Error(`lifecycle: "${k}" is not installation, export or delete`);
423
+ if (v !== undefined && typeof v !== "function")
424
+ throw new Error(`lifecycle.${k}: a function`);
425
+ }
426
+ this.#lifecycle = { ...config };
427
+ this.#changed();
428
+ }
429
+ /** A setting an administrator fills per installation (spec §2): text, number or boolean, never a secret. */
430
+ registerSetting(id, config) {
431
+ if (!/^[a-z][a-z0-9_]{1,39}$/.test(id))
432
+ throw new Error(`setting "${id}": lowercase letters, digits and _, starting with a letter, 2 to 40 characters`);
433
+ if (!["text", "number", "boolean"].includes(config.type))
434
+ throw new Error(`setting "${id}": type is text, number or boolean`);
435
+ if (config.default !== undefined && typeof config.default !== (config.type === "text" ? "string" : config.type))
436
+ throw new Error(`setting "${id}": the default must be a ${config.type}`);
437
+ this.#settings.set(id, config);
438
+ this.#changed();
439
+ }
440
+ // ------------------------------------------------------------ URIs
441
+ /** `clegra://<app>/<type>/<key>` (spec §4, §7). */
442
+ uri(type, key) {
443
+ return `${uriPrefix(this.name)}/${typeof type === "string" ? type : type.name}/${encodeURIComponent(key)}`;
444
+ }
445
+ /** A fragment instance's URI: the record id for record cards, base64url of the sorted params' JSON otherwise. */
446
+ fragmentUri(instance) {
447
+ if (this.#entities.has(instance.type))
448
+ return this.uri(instance.type, String(instance.params.id ?? ""));
449
+ return this.uri(instance.type, b64url(sortedJson(instance.params)));
450
+ }
451
+ /** A URI of this app read back: its type and key, or null. */
452
+ parseUri(uri) {
453
+ const m = new RegExp(`^${URI_SCHEME}://([^/]+)/([^/?#]+)/([^/?#]+)$`).exec(uri);
454
+ if (!m || m[1] !== this.name)
455
+ return null;
456
+ const type = m[2];
457
+ let key;
458
+ try {
459
+ key = decodeURIComponent(m[3]);
460
+ }
461
+ catch {
462
+ return null;
463
+ }
464
+ if (this.#entities.has(type))
465
+ return { type, key, params: { id: key } };
466
+ if (this.#fragments.has(type)) {
467
+ try {
468
+ const params = JSON.parse(unb64url(key));
469
+ if (params && typeof params === "object" && !Array.isArray(params))
470
+ return { type, key, params: params };
471
+ }
472
+ catch { }
473
+ }
474
+ return null;
475
+ }
476
+ // ------------------------------------------------------------ callers and contexts
477
+ #allPermissions() {
478
+ return [...this.#permissions.keys()];
479
+ }
480
+ /** The actions with `later`. */
481
+ #laterActions() {
482
+ return [...this.#actions.values()].filter((a) => a.later);
483
+ }
484
+ /** Every schedule, the SDK's own `clegra_later` included when an action has later. */
485
+ #allSchedules() {
486
+ const out = [...this.#schedules.entries()].map(([name, s]) => {
487
+ const action = this.#actions.get(s.action.tool);
488
+ return { name, ...(action ? { action } : {}), tool: s.action.tool, every: s.every, maxSeconds: s.maxSeconds };
489
+ });
490
+ if (this.#laterActions().length)
491
+ out.push({ name: LATER_TOOL, tool: LATER_TOOL, every: LIMITS.laterEvery, maxSeconds: LIMITS.scheduleSeconds.default });
492
+ return out;
493
+ }
494
+ /** Whether the caller is the installation itself: a workspace host's token without a person (schedules, later runs, lifecycle). */
495
+ #isInstallation(caller) {
496
+ return caller.host === "workspace" && !caller.person;
497
+ }
498
+ /**
499
+ * Why a call's `_meta.clegra.schedule` is refused, or null: it names one of the app's schedules, of this very tool,
500
+ * and comes from the installation-level caller (a workspace host, no person). A call without it is not a schedule's.
501
+ */
502
+ #scheduleProblem(tool, caller, meta) {
503
+ const name = hostMeta(meta).schedule;
504
+ if (name === undefined)
505
+ return null;
506
+ if (!this.#isInstallation(caller))
507
+ return "a schedule's run comes from a workspace host as the installation, with no person";
508
+ const s = typeof name === "string" ? this.#allSchedules().find((x) => x.name === name) : undefined;
509
+ if (!s)
510
+ return `"${String(name)}" is not a schedule of this app`;
511
+ if (s.tool !== tool)
512
+ return `schedule "${s.name}" runs ${s.tool}, not ${tool}`;
513
+ return null;
514
+ }
515
+ /** A notification as `ctx.notify` takes it, checked: a declared type (or none when none is declared), recipients said when there is no person. */
516
+ #checkNotification(n, caller) {
517
+ if (!n || typeof n !== "object")
518
+ throw new Error("ctx.notify: give { title, … }");
519
+ const types = [...this.#notificationTypes.keys()];
520
+ if (types.length && (typeof n.type !== "string" || !this.#notificationTypes.has(n.type)))
521
+ throw new Error(`ctx.notify: type ${n.type === undefined ? "is missing" : `"${String(n.type)}" is not declared`}: this app's notification types are ${types.join(", ")}`);
522
+ if (!types.length && n.type !== undefined)
523
+ throw new Error(`ctx.notify: type "${String(n.type)}": this app declares no notification types (declare them in notifications, or leave type out)`);
524
+ const to = n.to;
525
+ if (to === undefined) {
526
+ if (!caller.person)
527
+ throw new Error("ctx.notify: this call has no person (a schedule, the installation itself): say who receives it in to");
528
+ }
529
+ else if (Array.isArray(to)) {
530
+ if (!to.every((id) => typeof id === "string" && id))
531
+ throw new Error("ctx.notify: to is a list of person ids");
532
+ }
533
+ else if (!to || typeof to !== "object" || typeof to.permission !== "string" || !this.#permissions.has(to.permission))
534
+ throw new Error(`ctx.notify: to is person ids or { permission } naming a declared permission${to && typeof to === "object" && "permission" in to ? ` ("${String(to.permission)}" is not one)` : ""}`);
535
+ }
536
+ /** Notifications as a result carries them, in the caller's language; `to` said (default: the person of `caller`). */
537
+ #sent(notes, caller, ctx) {
538
+ return notes.map((n) => ({
539
+ ...(n.type !== undefined ? { type: n.type } : {}),
540
+ title: ctx.t(n.title),
541
+ ...(n.body !== undefined ? { body: ctx.t(n.body) } : {}),
542
+ ...(n.uri !== undefined ? { uri: n.uri } : {}),
543
+ to: n.to ?? (caller.person ? [caller.person.id] : []),
544
+ }));
545
+ }
546
+ #notificationsMeta(sent) {
547
+ return sent.length ? { _meta: { [META_KEY]: { notifications: sent } } } : {};
548
+ }
549
+ #context(caller, meta, notes, run) {
550
+ const locale = caller.locale ?? this.locale;
551
+ const host = hostMeta(meta);
552
+ // Settings are the installation's, set by its administrator: only its workspace host says them (also when it runs a later run). A plain client gets the defaults.
553
+ const sent = ((caller.host === "workspace" || run) && host.settings && typeof host.settings === "object" && !Array.isArray(host.settings) ? host.settings : {});
554
+ const settings = {};
555
+ for (const [id, s] of this.#settings) {
556
+ const v = sent[id];
557
+ const ok = s.type === "number" ? typeof v === "number" : s.type === "boolean" ? typeof v === "boolean" : typeof v === "string";
558
+ settings[id] = ok ? v : s.default;
559
+ }
560
+ const call = run ? run.call : typeof host.call === "string" ? host.call : null;
561
+ const schedule = run ? LATER_TOOL : typeof host.schedule === "string" && this.#isInstallation(caller) && this.#allSchedules().some((x) => x.name === host.schedule) ? host.schedule : null;
562
+ return {
563
+ app: this.name,
564
+ installation: caller.installation,
565
+ person: caller.person,
566
+ permissions: caller.permissions,
567
+ can: (p) => caller.permissions.has(p),
568
+ locale,
569
+ host: caller.host,
570
+ settings,
571
+ call,
572
+ schedule,
573
+ later: run?.later ?? null,
574
+ cancelLater: async (id) => (this.#store.later ? this.#store.later.cancel(String(id), caller.installation) : false),
575
+ t: (label) => say(label, locale, this.locale),
576
+ notify: (n) => {
577
+ this.#checkNotification(n, caller);
578
+ notes.push(n);
579
+ },
580
+ uri: (entity, id) => this.uri(entity, id),
581
+ };
582
+ }
583
+ #t(caller, label) {
584
+ return say(label, caller?.locale ?? this.locale, this.locale);
585
+ }
586
+ #visibleFields(entity, caller) {
587
+ return entity.fields.filter((f) => !f.permission || caller.permissions.has(f.permission));
588
+ }
589
+ /** Whether this caller reaches the entity at all, on any surface: its permission, and for a plain client its exposure. */
590
+ #canSee(entity, caller) {
591
+ if (entity.config.permission && !caller.permissions.has(entity.config.permission))
592
+ return false;
593
+ return caller.host !== "plain" || entity.tools.get.plain;
594
+ }
595
+ /** The same for a fragment type. */
596
+ #canShow(f, caller) {
597
+ if (f.config.permission && !caller.permissions.has(f.config.permission))
598
+ return false;
599
+ return caller.host !== "plain" || f.tool.plain;
600
+ }
601
+ /** Whether a URI inside a fragment's data points to something this caller reaches (a URI of another app is not ours to judge). */
602
+ #uriVisible(uri, caller) {
603
+ if (typeof uri !== "string")
604
+ return true;
605
+ const parsed = this.parseUri(uri);
606
+ const entity = parsed ? this.#entities.get(parsed.type) : undefined;
607
+ return !entity || this.#canSee(entity, caller);
608
+ }
609
+ #mayUse(action, caller) {
610
+ if (action.config.permission && !caller.permissions.has(action.config.permission))
611
+ return false;
612
+ if (action.entity && !this.#canSee(action.entity, caller))
613
+ return false;
614
+ if (caller.host === "plain" && !action.plain)
615
+ return false;
616
+ return true;
617
+ }
618
+ /** A row with only the fields this caller may see. */
619
+ #strip(entity, row, caller) {
620
+ const out = {};
621
+ for (const f of this.#visibleFields(entity, caller))
622
+ if (row[f.name] !== undefined)
623
+ out[f.name] = row[f.name];
624
+ return out;
625
+ }
626
+ /** What the view and hosts need to draw a field, in the caller's language. */
627
+ #column(f, caller) {
628
+ return {
629
+ name: f.name,
630
+ label: this.#t(caller, f.label ?? f.name),
631
+ type: f.type,
632
+ ...(f.role ? { role: f.role } : {}),
633
+ ...(f.enum ? { enum: f.enum } : {}),
634
+ ...(f.labels ? { labels: Object.fromEntries(Object.entries(f.labels).map(([k, v]) => [k, this.#t(caller, v)])) } : f.enum ? { labels: Object.fromEntries(f.enum.map((v) => [v, v])) } : {}),
635
+ ...(f.tones ? { tones: f.tones } : {}),
636
+ ...(f.currency ? { currency: f.currency } : {}),
637
+ ...(f.ref ? { ref: f.ref } : {}),
638
+ ...(f.sort ? { sort: true } : {}),
639
+ };
640
+ }
641
+ #actionInfo(a, caller) {
642
+ // The form's labels in the caller's language (plainSchema keeps only bare-string labels).
643
+ const raw = jsonSchemaOf(a.input, "input");
644
+ const input = plainSchema(raw);
645
+ for (const [k, p] of Object.entries(raw.properties ?? {})) {
646
+ const shown = input.properties?.[k];
647
+ if (!shown)
648
+ continue;
649
+ if (isLabel(p.label))
650
+ shown.title = this.#t(caller, p.label);
651
+ if (typeof p.currency === "string")
652
+ shown.currency = p.currency;
653
+ if (p.labels && typeof p.labels === "object")
654
+ shown.labels = Object.fromEntries(Object.entries(p.labels).filter(([, l]) => isLabel(l)).map(([v, l]) => [v, this.#t(caller, l)]));
655
+ // An input that holds another record's id: the form offers a picker over that entity's list (its tool, the field that names a record), never a box for a raw id.
656
+ const target = typeof p.ref === "string" ? this.#entities.get(p.ref) : undefined;
657
+ if (target && this.#canSee(target, caller) && (caller.host !== "plain" || target.tools.list.plain)) {
658
+ const title = this.#visibleFields(target, caller).find((f) => f.role === "title");
659
+ shown.ref = { entity: target.name, tool: target.tools.list.name, title: title?.name ?? "id", search: this.#visibleFields(target, caller).some((f) => f.search) };
660
+ }
661
+ // A record of any app (spec §3.2): the host's picker gives the URI; the generated view takes it as text.
662
+ const kind = kindRef(p);
663
+ if (kind)
664
+ shown.ref = { kind };
665
+ }
666
+ return { tool: a.tool, title: this.#t(caller, a.config.title), confirm: a.confirm, input };
667
+ }
668
+ /**
669
+ * An input that failed its schema, said field by field in the caller's language (Zod's own locales):
670
+ * `error.fields` maps each input key to what is wrong with it, the message names the fields by their labels.
671
+ */
672
+ #invalid(schema, error, caller) {
673
+ const raw = jsonSchemaOf(schema, "input");
674
+ const fields = {};
675
+ for (const issue of error.issues) {
676
+ const key = issue.path.map(String).join(".") || "_";
677
+ fields[key] ??= issue.message;
678
+ }
679
+ const label = (key) => {
680
+ const l = raw.properties?.[key.split(".")[0]]?.label;
681
+ return isLabel(l) ? this.#t(caller, l) : key;
682
+ };
683
+ const message = Object.entries(fields).map(([k, m]) => (k === "_" ? m : `${label(k)}: ${m}`)).join("; ");
684
+ return failure("invalid_input", message, { fields });
685
+ }
686
+ /** An input's label in the caller's language (its key when it has none). */
687
+ #fieldLabel(schema, key, caller) {
688
+ const l = jsonSchemaOf(schema, "input").properties?.[key]?.label;
689
+ return isLabel(l) ? this.#t(caller, l) : key;
690
+ }
691
+ /** Zod's messages in the caller's language, when Zod has it (else English). */
692
+ #zodLocale(caller) {
693
+ const lang = (caller.locale ?? this.locale).split("-")[0].toLowerCase();
694
+ const make = z.locales[lang];
695
+ return typeof make === "function" ? { error: make().localeError } : {};
696
+ }
697
+ /**
698
+ * An action's input as a person reads it before confirming (label → value): referenced records by their titles,
699
+ * dates, numbers and money in the caller's language. What can't be named stays as sent.
700
+ */
701
+ async #shownInput(a, received, caller, ctx) {
702
+ const raw = jsonSchemaOf(a.input, "input");
703
+ const locale = caller.locale ?? this.locale;
704
+ const out = [];
705
+ for (const [k, v] of Object.entries(received)) {
706
+ // The model's title hint is never shown as the app's: the record is named from its id.
707
+ if (v === undefined || v === null || v === "" || (a.entity && k === RECORD_TITLE_PARAM))
708
+ continue;
709
+ const p = raw.properties?.[k] ?? {};
710
+ let label = isLabel(p.label) ? this.#t(caller, p.label) : k;
711
+ let value = typeof v === "string" ? v : JSON.stringify(v);
712
+ const target = k === "id" && a.entity ? a.entity : typeof p.ref === "string" ? this.#entities.get(p.ref) : undefined;
713
+ if (k === "id" && a.entity)
714
+ label = this.#t(caller, a.entity.config.label);
715
+ try {
716
+ if (target && typeof v === "string" && this.#canSee(target, caller)) {
717
+ const row = await target.config.get(v, ctx);
718
+ if (row)
719
+ value = this.#recordCard(target, this.#strip(target, row, caller), caller).title;
720
+ }
721
+ else if (typeof v === "number")
722
+ value = typeof p.currency === "string" ? new Intl.NumberFormat(locale, { style: "currency", currency: p.currency }).format(v) : new Intl.NumberFormat(locale).format(v);
723
+ else if (typeof v === "string" && p.format === "date" && /^\d{4}-\d{2}-\d{2}$/.test(v))
724
+ value = new Intl.DateTimeFormat(locale, { dateStyle: "medium" }).format(new Date(`${v}T12:00:00`));
725
+ else if (typeof v === "boolean")
726
+ value = v ? "✓" : "—";
727
+ else if (typeof v === "string" && p.labels && isLabel(p.labels[v]))
728
+ value = this.#t(caller, p.labels[v]);
729
+ }
730
+ catch { }
731
+ out.push({ label, value });
732
+ }
733
+ return out;
734
+ }
735
+ #recordActions(entity, caller) {
736
+ return [...this.#actions.values()].filter((a) => a.entity === entity && this.#mayUse(a, caller)).map((a) => this.#actionInfo(a, caller));
737
+ }
738
+ /** A row as a model reads it: its untrusted fields (strings at any depth) wrapped, their JSON pointers under `base` noted for `_meta`. */
739
+ #markRow(entity, row, base, pointers) {
740
+ const copy = { ...row };
741
+ for (const f of entity.fields)
742
+ if (f.untrusted && copy[f.name] !== undefined)
743
+ copy[f.name] = markAll(copy[f.name], `${base}/${pointerKey(f.name)}`, pointers);
744
+ return copy;
745
+ }
746
+ /** A record card's title and subtitle the same way. */
747
+ #markCard(entity, card, base, pointers) {
748
+ const untrusted = (role) => entity.fields.some((f) => f.role === role && f.untrusted);
749
+ const out = { ...card };
750
+ if (untrusted("title"))
751
+ out.title = markAll(card.title, `${base}/title`, pointers);
752
+ if (card.subtitle !== undefined && untrusted("subtitle"))
753
+ out.subtitle = markAll(card.subtitle, `${base}/subtitle`, pointers);
754
+ return out;
755
+ }
756
+ /** A resolved fragment's data as a model reads it (a record's untrusted fields; every text of a fragment declared `untrusted`). */
757
+ #markResolved(r, base, pointers) {
758
+ if (r.state !== "ok" || !r.data || typeof r.data !== "object")
759
+ return r.data;
760
+ const entity = this.#entities.get(r.fragment.type);
761
+ if (entity)
762
+ return this.#markRow(entity, r.data, `${base}/data`, pointers);
763
+ return this.#fragments.get(r.fragment.type)?.config.untrusted ? markAll(r.data, `${base}/data`, pointers, TEMPLATE_KEYS) : r.data;
764
+ }
765
+ #marks(pointers) {
766
+ return pointers.length ? { _meta: { [META_KEY]: { untrusted: pointers } } } : {};
767
+ }
768
+ // ------------------------------------------------------------ reads
769
+ #queryOf(entity, caller, args, base) {
770
+ const visible = this.#visibleFields(entity, caller);
771
+ const filters = { ...(base?.filters ?? {}) };
772
+ for (const f of visible)
773
+ if (f.filter && args[f.name] !== undefined)
774
+ filters[f.name] = args[f.name];
775
+ for (const k of Object.keys(filters)) {
776
+ const f = visible.find((x) => x.name === k);
777
+ if (!f || !f.filter)
778
+ throw new AppError("invalid_input", `"${k}" can't be filtered on`);
779
+ }
780
+ // A key filter is exact on the normalised value (spec §3.1 rule 5): the handler gets it normalised (an email lower-cased).
781
+ for (const [k, key] of entity.keys) {
782
+ const f = filters[k];
783
+ if (f === undefined)
784
+ continue;
785
+ const norm = (v) => {
786
+ if (typeof v !== "string")
787
+ throw new AppError("invalid_input", `"${k}" is an exact ${key.property}: give a string`);
788
+ const n = normaliseKey(v, key.how);
789
+ if (n === null)
790
+ throw new AppError("invalid_input", `"${k}": ${JSON.stringify(v)} is not a ${key.property}`);
791
+ return n;
792
+ };
793
+ if (f !== null && typeof f === "object" && "in" in f && Array.isArray(f.in))
794
+ filters[k] = { in: f.in.map(norm) };
795
+ else if (f !== null && typeof f === "object")
796
+ throw new AppError("invalid_input", `"${k}" is an exact ${key.property}: give a value or { in: [...] }, not a range`);
797
+ else
798
+ filters[k] = norm(f);
799
+ }
800
+ const sortField = typeof args.sort === "string" ? args.sort : base?.sort?.field;
801
+ if (sortField !== undefined && !visible.some((f) => f.name === sortField && f.sort))
802
+ throw new AppError("invalid_input", `"${sortField}" can't be sorted by`);
803
+ const limit = typeof args.limit === "number" ? Math.max(1, Math.min(100, Math.floor(args.limit))) : 25;
804
+ const textQuery = typeof args.query === "string" && args.query.trim() ? args.query.trim() : base?.text;
805
+ // Text is searched only in the search fields the caller may see: a hidden field must not answer by matching.
806
+ const textFields = visible.filter((f) => f.search).map((f) => f.name);
807
+ if (textQuery && !textFields.length)
808
+ throw new AppError("invalid_input", `${entity.name} can't be searched by text`);
809
+ return {
810
+ filters,
811
+ ...(textQuery ? { text: textQuery, textFields } : {}),
812
+ ...(sortField ? { sort: { field: sortField, dir: args.dir === "desc" || (args.dir === undefined && base?.sort?.dir === "desc") ? "desc" : "asc" } } : {}),
813
+ ...(typeof args.cursor === "string" ? { cursor: args.cursor } : {}),
814
+ limit,
815
+ };
816
+ }
817
+ async #list(entity, caller, ctx, query) {
818
+ const result = await entity.config.list(query, ctx);
819
+ this.#exact(entity, query, (result.rows ?? []));
820
+ const rows = (result.rows ?? []).slice(0, query.limit).map((r) => this.#strip(entity, r, caller));
821
+ return { rows, ...(result.next ? { next: result.next } : {}), ...(typeof result.total === "number" ? { total: result.total } : {}) };
822
+ }
823
+ /**
824
+ * A handler that answered an exact key filter with a row that doesn't hold the value (spec §3.1 rule 5) fails
825
+ * the call, clearly: a host matches records by these filters, and a wrong row would be a wrong match.
826
+ */
827
+ #exact(entity, query, rows) {
828
+ for (const [k, key] of entity.keys) {
829
+ const f = query.filters[k];
830
+ if (f === undefined)
831
+ continue;
832
+ const wanted = typeof f === "string" ? [f] : f && typeof f === "object" && "in" in f ? f.in.map(String) : [];
833
+ for (const row of rows) {
834
+ const values = Array.isArray(row[k]) ? row[k] : [row[k]];
835
+ if (values.some((v) => typeof v === "string" && wanted.includes(normaliseKey(v, key.how) ?? "\u0000")))
836
+ continue;
837
+ const why = `${entity.tools.list.name}: the app's list returned ${entity.name} ${String(row.id)}, whose ${k} doesn't hold the exact ${key.property} asked for (${wanted.join(", ")}). A key filter is exact on the normalised value (spec §3.1).`;
838
+ console.error(`[${PROTOCOL_ID}] ${why}`);
839
+ throw new AppError("internal", why);
840
+ }
841
+ }
842
+ }
843
+ /**
844
+ * Titles of the records a list's ref fields point to (field → id → title), as this caller may see them.
845
+ * `pointers`: the titles that are outsiders' text are noted there (under `/refs`), like any untrusted value.
846
+ */
847
+ async #refs(entity, rows, caller, ctx, pointers) {
848
+ const out = {};
849
+ await Promise.all(this.#visibleFields(entity, caller).map(async (f) => {
850
+ // Same-app references only: a record of another app is the host's to name, for each viewer (spec §3.2).
851
+ const local = localRef(f);
852
+ const target = local ? this.#entities.get(local) : undefined;
853
+ if (!target || !this.#canSee(target, caller))
854
+ return;
855
+ const ids = [...new Set(rows.map((r) => r[f.name]).filter((v) => typeof v === "string"))].slice(0, 50);
856
+ const titles = {};
857
+ await Promise.all(ids.map(async (id) => {
858
+ const row = await target.config.get(id, ctx);
859
+ if (row)
860
+ titles[id] = this.#recordCard(target, this.#strip(target, row, caller), caller).title;
861
+ }));
862
+ out[f.name] = titles;
863
+ }));
864
+ Object.assign(out, await this.#personRefs(entity, rows, caller, ctx));
865
+ // In declaration order, whatever finished first.
866
+ const ordered = {};
867
+ for (const f of entity.fields) {
868
+ if (!out[f.name])
869
+ continue;
870
+ ordered[f.name] = out[f.name];
871
+ if (pointers && localRef(f) && this.#untrustedTitle(this.#entities.get(localRef(f))))
872
+ for (const id of Object.keys(ordered[f.name]))
873
+ pointers.push(`/refs/${pointerKey(f.name)}/${pointerKey(id)}`);
874
+ }
875
+ return ordered;
876
+ }
877
+ /** Whether this app names people: it declares `people`, or its dev sign-in knows its test people. */
878
+ #namesPeople() {
879
+ return Boolean(this.options.people || this.#dev);
880
+ }
881
+ /**
882
+ * The names of the people a list's `person` fields hold (field → id → name), when the app names people:
883
+ * the caller's own name from the token, the dev sign-in's test people, then the app's `people`. An id none
884
+ * of them knows is left out (a host shows an unknown person, never the id). Without a way to name people
885
+ * nothing is sent: the field's values are the names themselves.
886
+ */
887
+ async #personRefs(entity, rows, caller, ctx) {
888
+ const fields = this.#visibleFields(entity, caller).filter((f) => f.role === "person" && !f.ref);
889
+ if (!fields.length || !this.#namesPeople())
890
+ return {};
891
+ const ids = [...new Set(rows.flatMap((r) => fields.map((f) => r[f.name])).filter((v) => typeof v === "string" && v !== ""))].slice(0, 200);
892
+ const names = {};
893
+ if (caller.person?.name)
894
+ names[caller.person.id] = caller.person.name;
895
+ for (const p of this.#dev?.people ?? [])
896
+ if (p.name)
897
+ names[p.id] ??= p.name;
898
+ const unknown = ids.filter((id) => !names[id]);
899
+ if (unknown.length && this.options.people) {
900
+ try {
901
+ const found = await this.options.people(unknown, ctx);
902
+ for (const id of unknown)
903
+ if (typeof found?.[id] === "string" && found[id])
904
+ names[id] = found[id];
905
+ }
906
+ catch (error) {
907
+ console.error(`[${PROTOCOL_ID}] people`, error);
908
+ }
909
+ }
910
+ const out = {};
911
+ for (const f of fields) {
912
+ const own = {};
913
+ for (const r of rows) {
914
+ const id = r[f.name];
915
+ if (typeof id === "string" && names[id])
916
+ own[id] = names[id];
917
+ }
918
+ out[f.name] = own;
919
+ }
920
+ return out;
921
+ }
922
+ #untrustedTitle(entity) {
923
+ return entity.fields.some((f) => f.role === "title" && f.untrusted);
924
+ }
925
+ /** A record's title as a model reads it beside its URI (spec §6 rule 10): what it names the record by (an outsider's title wrapped). */
926
+ #modelTitle(entity, row, caller) {
927
+ const title = this.#recordCard(entity, row, caller).title;
928
+ return this.#untrustedTitle(entity) ? untrustedText(title) : title;
929
+ }
930
+ /** A row as a model reads it, with the records it references named: `{ id, title }` in place of a bare id (an outsider's title wrapped). */
931
+ #named(entity, row, refs) {
932
+ const out = { ...row };
933
+ for (const f of entity.fields) {
934
+ const id = out[f.name];
935
+ // A record of another app: its URI and kind, never a title (the app has none, and keeps none: spec §3.2).
936
+ const kind = kindRef(f);
937
+ if (kind) {
938
+ if (typeof id === "string")
939
+ out[f.name] = { uri: id, kind };
940
+ continue;
941
+ }
942
+ const title = typeof id === "string" ? refs[f.name]?.[id] : undefined;
943
+ if (title === undefined)
944
+ continue;
945
+ // A person by name; a referenced record by its title (an outsider's title wrapped).
946
+ if (localRef(f))
947
+ out[f.name] = { id, title: this.#untrustedTitle(this.#entities.get(localRef(f))) ? untrustedText(title) : title };
948
+ else if (f.role === "person")
949
+ out[f.name] = { id, name: title };
950
+ }
951
+ return out;
952
+ }
953
+ #listFiltersShape(entity, caller) {
954
+ const shape = {};
955
+ for (const f of this.#visibleFields(entity, caller)) {
956
+ if (!f.filter)
957
+ continue;
958
+ // Descriptions are in the app's locale, the same for every caller (spec §6 rule 2); a field with `as` names its property.
959
+ const label = say(f.label ?? f.name, this.locale, this.locale);
960
+ const key = entity.keys.get(f.name);
961
+ if (key) {
962
+ // A key is matched exactly (spec §3.1 rule 5): a value or a set of values, never a range.
963
+ const value = KEY_FORMATS[key.property] ? z.string().meta({ format: KEY_FORMATS[key.property] }) : z.string();
964
+ shape[f.name] = z.union([value, z.object({ in: z.array(value) })]).optional().describe(`${label}: exact ${key.property}; a value or { in: [...] }`);
965
+ continue;
966
+ }
967
+ const value = f.enum ? z.enum(f.enum) : f.type === "number" || f.type === "integer" ? z.number() : f.type === "boolean" ? z.boolean() : z.string();
968
+ shape[f.name] = z
969
+ .union([value, z.object({ in: z.array(value) }), z.object({ gte: value.optional(), lte: value.optional() })])
970
+ .optional()
971
+ .describe(`${label}${f.as ? ` (${f.as})` : ""}: a value, { in: [...] }, or a range { gte, lte }`);
972
+ }
973
+ if (this.#visibleFields(entity, caller).some((f) => f.search))
974
+ shape.query = z.string().max(200).optional().describe("Text to search for");
975
+ const sortable = this.#visibleFields(entity, caller).filter((f) => f.sort).map((f) => f.name);
976
+ if (sortable.length) {
977
+ shape.sort = z.enum(sortable).optional().describe("Field to sort by");
978
+ shape.dir = z.enum(["asc", "desc"]).optional();
979
+ }
980
+ return shape;
981
+ }
982
+ #recordCard(entity, row, caller) {
983
+ const role = (r) => entity.fields.find((f) => f.role === r && (!f.permission || caller.permissions.has(f.permission)));
984
+ const title = role("title");
985
+ const subtitle = role("subtitle");
986
+ const status = role("status");
987
+ const statusValue = status ? row[status.name] : undefined;
988
+ return {
989
+ title: String(title ? (row[title.name] ?? "") : row.id),
990
+ ...(subtitle && row[subtitle.name] != null ? { subtitle: String(row[subtitle.name]) } : {}),
991
+ ...(status && statusValue != null ? { status: this.#t(caller, status.labels?.[String(statusValue)] ?? String(statusValue)) } : {}),
992
+ };
993
+ }
994
+ /** One fragment instance as this caller may see it now. */
995
+ async #resolve(instance, caller, ctx) {
996
+ const uri = this.fragmentUri(instance);
997
+ const fragment = { app: this.name, type: instance.type, params: instance.params };
998
+ const entity = this.#entities.get(instance.type);
999
+ if (entity) {
1000
+ if (!this.#canSee(entity, caller))
1001
+ return { fragment, uri, state: "no-access" };
1002
+ const row = await entity.config.get(String(instance.params.id ?? ""), ctx);
1003
+ if (!row)
1004
+ return { fragment, uri, state: "gone" };
1005
+ const data = this.#strip(entity, row, caller);
1006
+ return {
1007
+ fragment,
1008
+ uri,
1009
+ state: "ok",
1010
+ template: "record",
1011
+ ...this.#recordCard(entity, data, caller),
1012
+ data,
1013
+ // The titles of the records it references (field → id → title), as this caller may see them: a host shows those, never the ids.
1014
+ refs: await this.#refs(entity, [data], caller, ctx),
1015
+ view: { kind: "record", tool: entity.tools.get.name, fields: this.#visibleFields(entity, caller).map((f) => this.#column(f, caller)), actions: this.#recordActions(entity, caller) },
1016
+ };
1017
+ }
1018
+ const f = this.#fragments.get(instance.type);
1019
+ if (!f)
1020
+ return { fragment, uri, state: "gone" };
1021
+ if (!this.#canShow(f, caller))
1022
+ return { fragment, uri, state: "no-access" };
1023
+ const parsed = f.config.params.safeParse(instance.params);
1024
+ if (!parsed.success)
1025
+ return { fragment, uri, state: "gone" };
1026
+ let data = (await f.config.data(parsed.data, ctx));
1027
+ if (!data)
1028
+ return { fragment, uri, state: "gone" };
1029
+ // What a template links to is shown only to who reaches it: a card of a record out of reach is no access, such items leave a list.
1030
+ if (f.config.template === "card" && !this.#uriVisible(data.uri, caller))
1031
+ return { fragment, uri, state: "no-access" };
1032
+ if (f.config.template === "list" && Array.isArray(data.items))
1033
+ data = { ...data, items: data.items.filter((i) => this.#uriVisible(i?.uri, caller)) };
1034
+ const actions = (f.config.actions ?? []).map((h) => this.#actions.get(h.tool)).filter((a) => Boolean(a && this.#mayUse(a, caller))).map((a) => this.#actionInfo(a, caller));
1035
+ return { fragment, uri, state: "ok", template: f.config.template ?? "view", title: this.#t(caller, f.config.title), data, ...(actions.length ? { actions } : {}) };
1036
+ }
1037
+ // ------------------------------------------------------------ calls
1038
+ /**
1039
+ * Runs one action call: permission, input, record, idempotency, confirmation, handler (spec §7).
1040
+ * `raw`: the call's arguments as they were received; the proof and the idempotency check cover those, never the parsed or defaulted input.
1041
+ */
1042
+ async #runAction(a, caller, args, mctx, request, raw) {
1043
+ const meta = (mctx?.mcpReq._meta ?? undefined);
1044
+ const notes = [];
1045
+ const ctx = this.#context(caller, meta, notes);
1046
+ if (!this.#mayUse(a, caller))
1047
+ return failure("permission_denied", `You may not use ${this.#t(caller, a.config.title)}.`);
1048
+ const { id, [RECORD_TITLE_PARAM]: hint, ...rest } = args;
1049
+ const parsed = a.input.safeParse(a.entity ? rest : args, this.#zodLocale(caller));
1050
+ if (!parsed.success)
1051
+ return this.#invalid(a.input, parsed.error, caller);
1052
+ let record;
1053
+ if (a.entity) {
1054
+ if (typeof id !== "string" || !id)
1055
+ return failure("invalid_input", "id: the record's id is required");
1056
+ if (hint !== undefined && typeof hint !== "string")
1057
+ return failure("invalid_input", `${RECORD_TITLE_PARAM}: a string`, { fields: { [RECORD_TITLE_PARAM]: "a string" } });
1058
+ const row = await a.entity.config.get(id, ctx);
1059
+ if (!row)
1060
+ return failure("not_found", `${this.#t(caller, a.entity.config.label)} ${id} doesn't exist.`);
1061
+ record = row;
1062
+ // The hint is what a client's own approval prompt may have shown the person: one that names another record stops
1063
+ // the call (the person approved something else). It never changes what runs, and is never shown as the app's.
1064
+ const titleField = a.entity.fields.find((f) => f.role === "title" && (!f.permission || caller.permissions.has(f.permission)));
1065
+ const real = titleField ? record[titleField.name] : undefined;
1066
+ if (typeof hint === "string" && hint.trim() && real !== undefined && real !== null && comparableTitle(hint) !== comparableTitle(String(real))) {
1067
+ const label = this.#t(caller, a.entity.config.label).toLowerCase();
1068
+ const why = `${RECORD_TITLE_PARAM} doesn't match the ${label} with id ${id}: read it again (${a.entity.tools.get.name}) and name the one the person means`;
1069
+ return failure("invalid_input", why, { fields: { [RECORD_TITLE_PARAM]: why } });
1070
+ }
1071
+ }
1072
+ const received = (raw && typeof raw === "object" && !Array.isArray(raw) ? raw : args);
1073
+ // A later action: when it runs is checked before anyone is asked to confirm it, and the deadline the proof must carry follows from it.
1074
+ // (A call id already answered gives its answer back first, whatever the time is now.)
1075
+ let until;
1076
+ let laterRefused = null;
1077
+ if (a.later) {
1078
+ const at = received[a.later.at];
1079
+ const atMs = typeof at === "string" ? Date.parse(at) : NaN;
1080
+ const now = Date.now();
1081
+ const why = !Number.isFinite(atMs) ? "a date and time" : atMs < now - LATER_PAST_MS ? "a time that has not passed" : atMs > now + LATER_AHEAD_MS ? "at most a year ahead" : null;
1082
+ if (why)
1083
+ laterRefused = failure("invalid_input", `${this.#fieldLabel(a.input, a.later.at, caller)}: ${why}`, { fields: { [a.later.at]: why } });
1084
+ else
1085
+ until = laterDeadline(at, a.later.window);
1086
+ }
1087
+ // Per caller: a stored answer is only ever given back to who made the call.
1088
+ const key = a.write && ctx.call ? `${caller.installation}:${caller.issuer}:${caller.subject}:${a.tool}:${ctx.call}` : null;
1089
+ const hash = canonicalJson(received);
1090
+ if (key) {
1091
+ // One atomic step: two requests with the same call id can't both run.
1092
+ const existing = await this.#store.begin(key, hash, 120_000);
1093
+ if (existing) {
1094
+ if (existing.args !== hash)
1095
+ return failure("conflict", "This call id was already used with other arguments.");
1096
+ if (existing.result === undefined)
1097
+ return failure("conflict", "This call is still running: ask again for its result.", { pending: true });
1098
+ return existing.result;
1099
+ }
1100
+ }
1101
+ let kept = false;
1102
+ try {
1103
+ if (laterRefused)
1104
+ return laterRefused;
1105
+ let proven = null;
1106
+ if (a.write && a.confirm === "always" && caller.host === "workspace") {
1107
+ const proof = hostMeta(meta).confirmation;
1108
+ const checked = typeof proof === "string" ? await this.#verifier.checkConfirmation(proof, { issuer: caller.issuer, subject: caller.subject, installation: caller.installationId, tool: a.tool, args: received, call: ctx.call, ...(until !== undefined ? { until } : {}) }, request.trust) : { ok: false, why: "no proof" };
1109
+ if (checked.ok)
1110
+ proven = { proof: proof, iat: checked.iat };
1111
+ const why = checked.ok ? null : checked.why;
1112
+ if (why) {
1113
+ const card = a.entity && record ? this.#recordCard(a.entity, this.#strip(a.entity, record, caller), caller) : null;
1114
+ return failure("confirmation_required", `${this.#t(caller, a.config.title)} needs the person's confirmation (${why}).`, {
1115
+ confirm: { tool: a.tool, title: this.#t(caller, a.config.title), ...(a.entity && record ? { record: { uri: this.uri(a.entity.name, String(record.id)), ...card } } : {}), input: received, ...(a.later && until !== undefined ? { later: { at: received[a.later.at], until } } : {}) },
1116
+ });
1117
+ }
1118
+ }
1119
+ // A plain client that can elicit (MCP 2026-07-28 input requests) is asked to confirm an `always` write; others rely on the tool's destructiveHint.
1120
+ if (a.write && a.confirm === "always" && caller.host === "plain" && mctx && elicits(mctx)) {
1121
+ const answer = inputResponse(mctx.mcpReq.inputResponses, "confirm");
1122
+ if (answer.kind !== "elicit") {
1123
+ const lines = (await this.#shownInput(a, received, caller, ctx)).map((l) => `${l.label}: ${l.value}`).join("; ");
1124
+ return inputRequired({ inputRequests: { confirm: inputRequired.elicit({ message: `${this.#t(caller, a.config.title)}${lines ? ` (${lines})` : ""}?`, requestedSchema: z.object({ confirm: z.boolean() }) }) } });
1125
+ }
1126
+ if (answer.action !== "accept" || answer.content?.confirm !== true)
1127
+ return failure("confirmation_required", "Not confirmed.");
1128
+ }
1129
+ // Confirmed now, run later: the call is kept as received, with its proof, and runs when it is due (clegra_later).
1130
+ if (a.later && until !== undefined) {
1131
+ const at = received[a.later.at];
1132
+ const run = {
1133
+ id: randomUUID(),
1134
+ tenant: caller.installation,
1135
+ tool: a.tool,
1136
+ args: received,
1137
+ argsHash: argsHash(received),
1138
+ at,
1139
+ until,
1140
+ author: caller.person ? { id: caller.person.id, name: caller.person.name } : null,
1141
+ permissions: [a.config.permission, a.entity?.config.permission].filter((x) => typeof x === "string" && caller.permissions.has(x)),
1142
+ proof: proven?.proof ?? null,
1143
+ issuer: caller.issuer,
1144
+ subject: caller.subject,
1145
+ installation: caller.installationId,
1146
+ call: ctx.call,
1147
+ confirmedAt: proven?.iat ?? Math.floor(Date.now() / 1000),
1148
+ };
1149
+ await this.#store.later.add(run);
1150
+ const message = `Scheduled for ${at}.`;
1151
+ const result = { content: text(message), structuredContent: { ok: true, message, data: { later: { id: run.id, at, until } } } };
1152
+ if (key) {
1153
+ await this.#store.finish(key, { args: hash, result }, 24 * 3600_000);
1154
+ kept = true;
1155
+ }
1156
+ return result;
1157
+ }
1158
+ let out;
1159
+ try {
1160
+ out = await a.handler(parsed.data, ctx, record);
1161
+ }
1162
+ catch (error) {
1163
+ if (error instanceof AppError)
1164
+ return failure(error.code, error.message, error.details);
1165
+ console.error(`[${PROTOCOL_ID}] ${a.tool}`, error);
1166
+ return failure("internal", "The action failed.");
1167
+ }
1168
+ const recordUri = out?.record ? (out.record.startsWith(`${URI_SCHEME}://`) ? out.record : a.entity ? this.uri(a.entity.name, out.record) : out.record) : undefined;
1169
+ const message = out?.message ?? "Done.";
1170
+ const result = {
1171
+ content: text(message),
1172
+ structuredContent: { ok: true, message, ...(recordUri ? { record: recordUri } : {}), ...(out?.data ? { data: out.data } : {}) },
1173
+ ...this.#notificationsMeta(this.#sent(notes, caller, ctx)),
1174
+ };
1175
+ if (key) {
1176
+ await this.#store.finish(key, { args: hash, result }, 24 * 3600_000);
1177
+ kept = true;
1178
+ }
1179
+ return result;
1180
+ }
1181
+ finally {
1182
+ // Refused or failed: nothing is kept, the same call id can be tried again.
1183
+ if (key && !kept)
1184
+ await this.#store.abandon(key);
1185
+ }
1186
+ }
1187
+ // ------------------------------------------------------------ later runs
1188
+ /**
1189
+ * One pass over a tenant's due later runs: each is claimed (once: a claimed run is never given again), checked
1190
+ * against what the person confirmed, and run as its author. `meta`: the request's (`_meta.clegra.settings`).
1191
+ */
1192
+ async #runDue(tenant, meta, trust, locale) {
1193
+ const report = { runs: [], notifications: [] };
1194
+ const store = this.#store.later;
1195
+ if (!store)
1196
+ return report;
1197
+ for (const due of await store.due(tenant, new Date(), LATER_BATCH)) {
1198
+ const run = await store.claim(due.id, tenant);
1199
+ if (!run)
1200
+ continue; // another pass took it
1201
+ let done;
1202
+ try {
1203
+ done = await this.#runOne(run, meta, trust);
1204
+ }
1205
+ catch (error) {
1206
+ console.error(`[${PROTOCOL_ID}] ${LATER_TOOL} ${run.tool} ${run.id}`, error);
1207
+ done = { outcome: { status: "failed", message: "The action failed." }, notes: [] };
1208
+ }
1209
+ await store.finish(run.id, done.outcome);
1210
+ report.runs.push({ id: run.id, tool: run.tool, at: run.at, ...done.outcome });
1211
+ report.notifications.push(...done.notes);
1212
+ if ((done.outcome.status === "expired" || done.outcome.status === "refused") && run.author)
1213
+ report.notifications.push(this.#didNotRun(run, done.outcome, locale));
1214
+ }
1215
+ return report;
1216
+ }
1217
+ /** One claimed later run: refused unless it is exactly what was confirmed (arguments, time, proof as of its confirmation), expired after its deadline, else run. */
1218
+ async #runOne(run, meta, trust) {
1219
+ const refused = (message) => ({ outcome: { status: "refused", message }, notes: [] });
1220
+ const failed = (message, notes = []) => ({ outcome: { status: "failed", message }, notes });
1221
+ const a = this.#actions.get(run.tool);
1222
+ if (!a?.later)
1223
+ return refused(`${run.tool} is not an action that runs later`);
1224
+ if (argsHash(run.args) !== run.argsHash)
1225
+ return refused("its arguments are not the ones confirmed");
1226
+ const at = run.args[a.later.at];
1227
+ if (typeof at !== "string" || at !== run.at)
1228
+ return refused("its time is not the one confirmed");
1229
+ if (!(Date.parse(at) <= Date.now()))
1230
+ return refused("it is not due yet");
1231
+ if (run.proof) {
1232
+ // The host's proof, verified as of when the person confirmed it: its signature, and that it covers exactly these arguments, this call and this deadline.
1233
+ const checked = await this.#verifier.checkConfirmation(run.proof, { issuer: run.issuer, subject: run.subject, installation: run.installation, tool: run.tool, args: run.args, call: run.call, until: run.until }, trust, new Date(run.confirmedAt * 1000));
1234
+ if (!checked.ok)
1235
+ return refused(checked.why);
1236
+ if (checked.iat !== run.confirmedAt)
1237
+ return refused("the proof is not the one kept");
1238
+ }
1239
+ if (Math.floor(Date.now() / 1000) > run.until)
1240
+ return { outcome: { status: "expired", message: `its deadline passed (${new Date(run.until * 1000).toISOString()})` }, notes: [] };
1241
+ const caller = { installation: run.tenant, installationId: run.installation, person: run.author, permissions: new Set(run.permissions), host: run.proof ? "workspace" : "plain", issuer: run.issuer, subject: run.subject };
1242
+ if (!this.#mayUse(a, caller))
1243
+ return refused("its author may not use it");
1244
+ const notes = [];
1245
+ const ctx = this.#context(caller, meta, notes, { later: { id: run.id, at: run.at, until: run.until, confirmedAt: run.confirmedAt }, call: run.call });
1246
+ const { id, [RECORD_TITLE_PARAM]: _hint, ...rest } = run.args;
1247
+ const parsed = a.input.safeParse(a.entity ? rest : run.args);
1248
+ if (!parsed.success)
1249
+ return failed(`its arguments no longer fit the action: ${parsed.error.issues.map((i) => `${i.path.join(".") || "_"}: ${i.message}`).join("; ")}`);
1250
+ let record;
1251
+ if (a.entity) {
1252
+ const row = await a.entity.config.get(String(id ?? ""), ctx);
1253
+ if (!row)
1254
+ return failed(`${this.#t(caller, a.entity.config.label)} ${String(id)} doesn't exist.`);
1255
+ record = row;
1256
+ }
1257
+ let out;
1258
+ try {
1259
+ out = await a.handler(parsed.data, ctx, record);
1260
+ }
1261
+ catch (error) {
1262
+ if (error instanceof AppError)
1263
+ return failed(error.message, this.#sent(notes, caller, ctx));
1264
+ console.error(`[${PROTOCOL_ID}] ${LATER_TOOL} ${a.tool}`, error);
1265
+ return failed("The action failed.");
1266
+ }
1267
+ return { outcome: { status: "done", message: out?.message ?? "Done." }, notes: this.#sent(notes, caller, ctx) };
1268
+ }
1269
+ /** What the author of a later run that did not run is told. */
1270
+ #didNotRun(run, outcome, locale) {
1271
+ const a = this.#actions.get(run.tool);
1272
+ const lang = (locale ?? this.locale).split("-")[0].toLowerCase();
1273
+ const title = a ? say(a.config.title, locale ?? this.locale, this.locale) : run.tool;
1274
+ return { type: LATER_TOOL, title: (DID_NOT_RUN[lang] ?? DID_NOT_RUN.en)(title), body: outcome.message, to: [run.author.id] };
1275
+ }
1276
+ /**
1277
+ * Runs the tenant's due later runs now, as `clegra_later` does when the workspace host calls it: for an app whose
1278
+ * callers are its own (no workspace host runs its schedules), from the app's own cron. `settings`: what handlers
1279
+ * see as `ctx.settings`. The notifications in the report are the app's to deliver.
1280
+ */
1281
+ async runLater(tenant, options = {}) {
1282
+ if (!this.#store.later)
1283
+ throw new Error("runLater: the store has no later part");
1284
+ return this.#runDue(tenant, options.settings ? { [META_KEY]: { settings: options.settings } } : undefined, { dev: Boolean(this.#dev), requestResource: null }, options.locale);
1285
+ }
1286
+ // ------------------------------------------------------------ the MCP server
1287
+ #viewUri() {
1288
+ return `ui://${this.name}/view`;
1289
+ }
1290
+ #pageViewUri(page) {
1291
+ return `ui://${this.name}/pages/${page}`;
1292
+ }
1293
+ #entityViewUri(entity) {
1294
+ return `ui://${this.name}/entities/${entity}`;
1295
+ }
1296
+ #fragmentViewUri(type) {
1297
+ return `ui://${this.name}/fragments/${type}`;
1298
+ }
1299
+ /** A tool's view; `appOnly`: the tool of an app-only item, which no model is given (MCP Apps `visibility: ["app"]`, ChatGPT `openai/visibility: private`). */
1300
+ #ui(resourceUri, appOnly = false) {
1301
+ return { ui: { resourceUri, visibility: appOnly ? ["app"] : ["model", "app"] }, "ui/resourceUri": resourceUri, "openai/outputTemplate": resourceUri, "openai/widgetAccessible": true, ...(appOnly ? { "openai/visibility": "private" } : {}) };
1302
+ }
1303
+ /** A tool without a view of its own that views call (a record's actions): callable from a view in MCP Apps hosts (`ui.visibility` with "app") and in ChatGPT (`openai/widgetAccessible`). Without it a host refuses the view's call. */
1304
+ #callable(appOnly = false) {
1305
+ return appOnly ? APP_ONLY_META : { ui: { visibility: ["model", "app"] }, "openai/widgetAccessible": true };
1306
+ }
1307
+ /** Whether this caller may open a page (its tool's gates: exposure, permission, its list's entity). */
1308
+ #canOpen(p, caller) {
1309
+ const c = p.config;
1310
+ if (c.kind === "record" || (caller.host === "plain" && !p.tool.plain))
1311
+ return false;
1312
+ if (c.permission && !caller.permissions.has(c.permission))
1313
+ return false;
1314
+ return c.kind !== "list" || this.#canSee(this.#entities.get(c.entity.name), caller);
1315
+ }
1316
+ /**
1317
+ * The navigation as this caller may use it (`view.nav` of a page): sections in the reader's language, each page
1318
+ * with its title, the tool that opens it and its badge's tool. Without declared `nav`: every non-record page, one section.
1319
+ */
1320
+ #navFor(caller) {
1321
+ const sections = this.#nav ?? [{ pages: [...this.#pages.values()].filter((p) => p.config.kind !== "record").map((p) => p.name) }];
1322
+ return sections
1323
+ .map((s) => ({
1324
+ ...(s.section !== undefined ? { section: this.#t(caller, s.section) } : {}),
1325
+ pages: s.pages.flatMap((name) => {
1326
+ const p = this.#pages.get(name);
1327
+ if (!p || !this.#canOpen(p, caller) || p.config.kind === "record")
1328
+ return [];
1329
+ const badge = p.config.badge ? this.#fragments.get(p.config.badge) : undefined;
1330
+ return [{ name, title: this.#t(caller, p.config.title), tool: p.tool.name, ...(badge && this.#canShow(badge, caller) ? { badge: badge.tool.name } : {}) }];
1331
+ }),
1332
+ }))
1333
+ .filter((s) => s.pages.length);
1334
+ }
1335
+ /** A page's actions as this caller may use them (like a record's), each with its inputs prefilled from the page's params of the same name. */
1336
+ #pageActions(c, caller, params) {
1337
+ if (c.kind === "record")
1338
+ return [];
1339
+ return (c.actions ?? []).flatMap((h) => {
1340
+ const a = this.#actions.get(h.tool);
1341
+ if (!a || !this.#mayUse(a, caller))
1342
+ return [];
1343
+ const info = this.#actionInfo(a, caller);
1344
+ const props = info.input.properties ?? {};
1345
+ const prefill = Object.fromEntries(Object.entries(params).filter(([k, v]) => Object.hasOwn(props, k) && v !== undefined && v !== null && v !== ""));
1346
+ return [{ ...info, ...(Object.keys(prefill).length ? { prefill } : {}) }];
1347
+ });
1348
+ }
1349
+ /** What every page's `view` carries beside its kind and title: its actions and the app's navigation (the page itself named). */
1350
+ #pageExtras(p, caller, params) {
1351
+ const actions = this.#pageActions(p.config, caller, params);
1352
+ const nav = this.#navFor(caller);
1353
+ return { page: p.name, ...(actions.length ? { actions } : {}), ...(nav.length ? { nav } : {}) };
1354
+ }
1355
+ #allPages() {
1356
+ const pages = [...this.#pages.values()];
1357
+ for (const e of this.#entities.values())
1358
+ if (!this.#pages.has(e.name))
1359
+ pages.push({ name: e.name, config: { kind: "record", entity: e.handle }, derived: true, tool: e.tools.get });
1360
+ return pages;
1361
+ }
1362
+ #pageParams(page, caller) {
1363
+ const c = page.config;
1364
+ if (c.kind === "record")
1365
+ return z.object({ id: z.string() });
1366
+ if (c.params)
1367
+ return c.params;
1368
+ if (c.kind === "list") {
1369
+ const e = this.#entities.get(c.entity.name);
1370
+ return z.strictObject(this.#listFiltersShape(e, caller));
1371
+ }
1372
+ return z.object({});
1373
+ }
1374
+ /** A fresh McpServer for one request, for this caller (null: manifest and views only). `request`: what `fetch` knows of the HTTP request. */
1375
+ createMcpServer(caller, era = "legacy", request = { trust: { dev: Boolean(this.#dev), requestResource: null }, received: new Map() }) {
1376
+ void era;
1377
+ const o = this.options;
1378
+ // Tool names, titles and descriptions are in the app's own locale: stable for every caller (spec §6). Data labels follow the caller.
1379
+ const t = (l) => say(l, this.locale, this.locale);
1380
+ const s = new McpServer({ name: o.name, version: o.version, title: t(o.title), ...(o.description ? { description: t(o.description) } : {}), ...(o.icons ? { icons: o.icons } : {}), ...(o.websiteUrl ? { websiteUrl: o.websiteUrl } : {}) }, { ...(o.instructions ? { instructions: o.instructions } : {}) });
1381
+ // Resources: the manifest, the SDK's view, page, entity and fragment views.
1382
+ s.registerResource("manifest", manifestUri(this.name), { mimeType: "application/json", description: "The app's manifest (what hosts read to mount the app)" }, async () => ({
1383
+ contents: [{ uri: manifestUri(this.name), mimeType: "application/json", text: JSON.stringify(this.manifest()) }],
1384
+ }));
1385
+ const view = (uri, title, html, src) => {
1386
+ const csp = src && "url" in src ? { frameDomains: [new URL(src.url).origin] } : src && "csp" in src && src.csp ? src.csp : {};
1387
+ const ui = { csp, ...(src && "prefersBorder" in src && src.prefersBorder !== undefined ? { prefersBorder: src.prefersBorder } : {}) };
1388
+ s.registerResource(title, uri, { mimeType: MCP_APP_MIME_TYPE, _meta: { ui } }, async () => ({ contents: [{ uri, mimeType: MCP_APP_MIME_TYPE, text: await html(), _meta: { ui } }] }));
1389
+ };
1390
+ view(this.#viewUri(), `${t(o.title)} view`, () => viewHtml(t(o.title)));
1391
+ // A page on the app's own site (`/embed/…`) is framed at the address the request reached (or the configured one).
1392
+ const origin = request.origin ?? (o.auth?.resource ? new URL(o.auth.resource).origin : null);
1393
+ const absolute = (url) => (url.startsWith("/") ? (origin ? new URL(url, origin).href : null) : url);
1394
+ for (const p of this.#allPages()) {
1395
+ const c = p.config;
1396
+ if (c.kind !== "custom" && c.view)
1397
+ view(this.#pageViewUri(p.name), t(c.title ?? p.name), () => (typeof c.view.html === "function" ? c.view.html() : c.view.html), c.view);
1398
+ else if (c.kind === "dashboard")
1399
+ view(this.#pageViewUri(p.name), t(c.title), () => viewHtml(t(c.title), { tool: p.tool.name }));
1400
+ if (c.kind === "custom" && "url" in c) {
1401
+ const url = absolute(c.url);
1402
+ // A same-site page signs the viewer in with a ticket (spec §5.1); a page on another site is framed as it is.
1403
+ if (url)
1404
+ view(this.#pageViewUri(p.name), t(c.title), () => urlPageHtml(t(c.title), url, c.url.startsWith("/") ? { tool: EMBED_TOOL, page: p.name } : null), { url });
1405
+ }
1406
+ if (c.kind === "custom" && "view" in c)
1407
+ view(this.#pageViewUri(p.name), t(c.title), () => (typeof c.view.html === "function" ? c.view.html() : c.view.html), c.view);
1408
+ }
1409
+ for (const e of this.#entities.values())
1410
+ if (e.config.view)
1411
+ view(this.#entityViewUri(e.name), t(e.config.label), () => (typeof e.config.view.html === "function" ? e.config.view.html() : e.config.view.html), e.config.view);
1412
+ for (const f of this.#fragments.values())
1413
+ if (f.config.view)
1414
+ view(this.#fragmentViewUri(f.type), t(f.config.title), () => (typeof f.config.view.html === "function" ? f.config.view.html() : f.config.view.html), f.config.view);
1415
+ if (!caller) {
1416
+ this.options.mcp?.(s, null);
1417
+ return s;
1418
+ }
1419
+ const plainCaller = caller.host === "plain";
1420
+ const reg = s.registerTool.bind(s);
1421
+ const guard = (name, fn) => async (args, ctx) => {
1422
+ const notes = new Map();
1423
+ // A schedule's run is the installation's, of that schedule's own tool: anything else naming a schedule is refused.
1424
+ const scheduleWhy = this.#scheduleProblem(name, caller, ctx.mcpReq._meta);
1425
+ if (scheduleWhy)
1426
+ return failure("permission_denied", `Not a run of this schedule: ${scheduleWhy}.`);
1427
+ try {
1428
+ return withL10n(await shownLabels.run(notes, () => fn(args ?? {}, ctx)), notes);
1429
+ }
1430
+ catch (error) {
1431
+ if (error instanceof AppError)
1432
+ return failure(error.code, error.message, error.details);
1433
+ console.error(`[${PROTOCOL_ID}] ${name}`, error);
1434
+ return failure("internal", "The call failed.");
1435
+ }
1436
+ };
1437
+ const ctxOf = (ctx) => this.#context(caller, ctx.mcpReq._meta, []);
1438
+ const read = { readOnlyHint: true, idempotentHint: true, destructiveHint: false, openWorldHint: false };
1439
+ // Entities: list and get.
1440
+ for (const e of this.#entities.values()) {
1441
+ if (!this.#canSee(e, caller) || (plainCaller && !e.tools.list.plain))
1442
+ continue;
1443
+ const label = t(e.config.label);
1444
+ const plural = t(e.config.plural ?? e.config.label);
1445
+ const columns = () => this.#visibleFields(e, caller).filter((f) => f.name !== "id" && (f.role || f.filter)).slice(0, 6).map((f) => this.#column(f, caller));
1446
+ // What the entity is, for every client: the kind's fixed sentence ends both descriptions; hosts read `_meta.clegra` (spec §6).
1447
+ // The kind's sentence is always last (spec §6 rule 8); the cross-app hint (spec §3.2) before it.
1448
+ const kindText = `${e.fields.some((f) => kindRef(f)) ? ` ${CROSS_APP_HINT}` : ""}${e.config.kind !== undefined ? ` ${kindSentence(e.config.kind)}` : ""}`;
1449
+ const entityMeta = { [META_KEY]: { entity: e.name, ...(e.config.kind !== undefined ? { kind: e.config.kind } : {}) } };
1450
+ const appOnlyEntity = e.config.visibility === "app";
1451
+ reg(e.tools.list.name, {
1452
+ title: plural,
1453
+ description: `${t(e.config.description) || plural}. Lists ${plural.toLowerCase()} with filters, sort and paging (pass \`cursor\` from the previous result's \`next\`).${kindText}`,
1454
+ inputSchema: z.strictObject({ ...this.#listFiltersShape(e, caller), cursor: z.string().optional(), limit: z.number().int().min(1).max(100).optional() }),
1455
+ annotations: { title: plural, ...read },
1456
+ _meta: { ...this.#ui(this.#viewUri(), appOnlyEntity), ...entityMeta },
1457
+ }, guard(e.tools.list.name, async (args, mctx) => {
1458
+ const ctx = ctxOf(mctx);
1459
+ const query = this.#queryOf(e, caller, args);
1460
+ const out = await this.#list(e, caller, ctx, query);
1461
+ const uris = out.rows.map((r) => this.uri(e.name, String(r.id)));
1462
+ const pointers = [];
1463
+ const marked = out.rows.map((r, i) => this.#markRow(e, r, `/rows/${i}`, pointers));
1464
+ const refs = await this.#refs(e, out.rows, caller, ctx, pointers);
1465
+ return {
1466
+ content: text(JSON.stringify({ rows: marked.map((r, i) => ({ uri: uris[i], title: this.#modelTitle(e, out.rows[i], caller), ...this.#named(e, r, refs) })), ...(out.next ? { next: out.next } : {}), ...(out.total !== undefined ? { total: out.total } : {}) })),
1467
+ structuredContent: { entity: e.name, ...out, uris, refs, view: { kind: "list", title: this.#t(caller, e.config.plural ?? e.config.label), columns: columns(), tool: e.tools.list.name, args, getTool: e.tools.get.name, ...(query.sort ? { sort: query.sort } : {}) } },
1468
+ ...this.#marks(pointers),
1469
+ };
1470
+ }));
1471
+ reg(e.tools.get.name, {
1472
+ title: label,
1473
+ description: `One ${label.toLowerCase()} by id, with the actions available on it.${kindText}`,
1474
+ inputSchema: z.object({ id: z.string().describe(`The ${label.toLowerCase()}'s id`) }),
1475
+ annotations: { title: label, ...read },
1476
+ _meta: { ...this.#ui(e.config.view ? this.#entityViewUri(e.name) : this.#viewUri(), appOnlyEntity), ...entityMeta },
1477
+ }, guard(e.tools.get.name, async (args, mctx) => {
1478
+ const ctx = ctxOf(mctx);
1479
+ const row = await e.config.get(String(args.id), ctx);
1480
+ if (!row)
1481
+ return failure("not_found", `${label} ${String(args.id)} doesn't exist.`);
1482
+ const record = this.#strip(e, row, caller);
1483
+ const pointers = [];
1484
+ const marked = this.#markRow(e, record, "/record", pointers);
1485
+ const uri = this.uri(e.name, String(record.id));
1486
+ const refs = await this.#refs(e, [record], caller, ctx, pointers);
1487
+ return {
1488
+ content: text(JSON.stringify({ uri, title: this.#modelTitle(e, record, caller), ...this.#named(e, marked, refs) })),
1489
+ structuredContent: { entity: e.name, uri, record, refs, view: { kind: "record", title: this.#t(caller, e.config.label), tool: e.tools.get.name, fields: this.#visibleFields(e, caller).map((f) => this.#column(f, caller)), actions: this.#recordActions(e, caller) } },
1490
+ ...this.#marks(pointers),
1491
+ };
1492
+ }));
1493
+ }
1494
+ // search and fetch (ChatGPT's conventions), over searchable entities.
1495
+ // App-only entities are never a model's: search and fetch leave their records out.
1496
+ const searchable = [...this.#entities.values()].filter((e) => e.config.visibility !== "app" && this.#canSee(e, caller) && this.#visibleFields(e, caller).some((f) => f.search));
1497
+ // The kinds search can be limited to (spec §6): those of the searchable entities.
1498
+ const searchKinds = [...new Set(searchable.flatMap((e) => kindsOf(e.config.kind)))];
1499
+ if (searchable.length) {
1500
+ reg("search", {
1501
+ title: t({ en: "Search", it: "Cerca" }),
1502
+ description: `Searches ${searchable.map((e) => t(e.config.plural ?? e.config.label)).join(", ")} by text. Returns ids (URIs) to pass to fetch.${searchKinds.length ? ` \`kind\` limits it to records of one kind; each result says its kind.` : ""}`,
1503
+ inputSchema: z.object({
1504
+ query: z.string().min(1).max(200),
1505
+ ...(searchKinds.length ? { kind: z.enum(searchKinds).optional().describe("Only records of this kind") } : {}),
1506
+ limit: z.number().int().min(1).max(50).optional(),
1507
+ }),
1508
+ annotations: { ...read },
1509
+ _meta: this.#ui(this.#viewUri()),
1510
+ }, guard("search", async (args, mctx) => {
1511
+ const ctx = ctxOf(mctx);
1512
+ const limit = typeof args.limit === "number" ? args.limit : 10;
1513
+ const only = typeof args.kind === "string" ? args.kind : undefined;
1514
+ const results = [];
1515
+ const forModel = [];
1516
+ const pointers = [];
1517
+ for (const e of searchable) {
1518
+ if (only && !kindsOf(e.config.kind).includes(only))
1519
+ continue;
1520
+ const out = await this.#list(e, caller, ctx, this.#queryOf(e, caller, { query: String(args.query), limit }));
1521
+ for (const row of out.rows) {
1522
+ // One kind per record: the record's own (its `by` field has no permission, so the caller sees it).
1523
+ const kind = kindOfRecord(e.config.kind, row);
1524
+ if (only && kind !== only)
1525
+ continue;
1526
+ const uri = this.uri(e.name, String(row.id));
1527
+ const card = this.#recordCard(e, row, caller);
1528
+ const marked = this.#markCard(e, card, `/results/${results.length}`, pointers);
1529
+ results.push({ id: uri, entity: e.name, entityLabel: this.#t(caller, e.config.label), ...(kind ? { kind } : {}), ...card, url: uri });
1530
+ forModel.push({ id: uri, title: marked.title, url: uri, ...(kind ? { kind } : {}) });
1531
+ }
1532
+ }
1533
+ return { content: text(JSON.stringify({ results: forModel })), structuredContent: { results, view: { kind: "search" } }, ...this.#marks(pointers) };
1534
+ }));
1535
+ reg("fetch", {
1536
+ title: t({ en: "Fetch", it: "Apri" }),
1537
+ description: "One record by its id (a URI from search or a list), with all fields the caller may see.",
1538
+ inputSchema: z.object({ id: z.string().describe("The record's URI") }),
1539
+ annotations: { ...read },
1540
+ _meta: this.#ui(this.#viewUri()),
1541
+ }, guard("fetch", async (args, mctx) => {
1542
+ const ctx = ctxOf(mctx);
1543
+ const parsed = this.parseUri(String(args.id));
1544
+ const hidden = parsed && (this.#entities.get(parsed.type)?.config.visibility === "app" || this.#fragments.get(parsed.type)?.config.visibility === "app");
1545
+ if (!parsed || hidden)
1546
+ return failure("not_found", "Unknown id.");
1547
+ const r = await this.#resolve({ type: parsed.type, params: parsed.params }, caller, ctx);
1548
+ if (r.state !== "ok")
1549
+ return failure(r.state === "no-access" ? "permission_denied" : "not_found", r.state === "no-access" ? "No access." : "Not found.");
1550
+ const entity = this.#entities.get(parsed.type);
1551
+ const record = r.data;
1552
+ const pointers = [];
1553
+ const refs = entity ? await this.#refs(entity, [record], caller, ctx, pointers) : {};
1554
+ const marked = entity ? this.#named(entity, this.#markRow(entity, record, "/record", pointers), refs) : this.#markResolved(r, "", pointers);
1555
+ const title = "title" in r ? r.title : "";
1556
+ const kind = entity ? kindOfRecord(entity.config.kind, record) : null;
1557
+ return {
1558
+ content: text(JSON.stringify({ id: r.uri, title: entity ? this.#markCard(entity, { title }, "", []).title : title, text: JSON.stringify(marked), url: r.uri, metadata: { type: parsed.type, ...(kind ? { kind } : {}) } })),
1559
+ structuredContent: entity ? { entity: entity.name, uri: r.uri, record, refs, view: r.template === "record" ? { ...("view" in r ? r.view : {}), title: this.#t(caller, entity.config.label) } : undefined } : { ...r, view: { kind: "fragment", title } },
1560
+ ...this.#marks(pointers),
1561
+ };
1562
+ }));
1563
+ }
1564
+ // Embed tickets (spec §5.1): for hosts and the app's own url-page views, hidden from models.
1565
+ const embed = this.#embed;
1566
+ if (embed) {
1567
+ const pages = new Map(this.#embedPages().map((e) => [e.name, e]));
1568
+ reg(EMBED_TOOL, {
1569
+ title: "Embed ticket",
1570
+ description: "For hosts and the app's views: a one-minute, single-use ticket that signs the viewer in to one of the app's embedded pages, framed by a document of the given origin.",
1571
+ inputSchema: z.object({ page: z.string().describe("The page's name (manifest pages with a same-site url)"), origin: z.string().describe("The origin of the document that frames the page and posts the ticket") }),
1572
+ annotations: { title: "Embed ticket", readOnlyHint: true, idempotentHint: false, destructiveHint: false, openWorldHint: false },
1573
+ _meta: { ui: { visibility: ["app"] }, "openai/visibility": "private", "openai/widgetAccessible": true },
1574
+ }, guard(EMBED_TOOL, async (args) => {
1575
+ const name = String(args.page);
1576
+ const page = this.#pages.get(name);
1577
+ // The same gates as the page's own tool (open_<page>): a page the caller can't open has no ticket either.
1578
+ if (!page || !pages.has(name) || (plainCaller && !page.tool.plain))
1579
+ return failure("not_found", `No embedded page "${name}".`);
1580
+ if (page.config.permission && !caller.permissions.has(page.config.permission))
1581
+ return failure("permission_denied", `You may not open ${this.#t(caller, page.config.title)}.`);
1582
+ try {
1583
+ const appOrigin = this.#appOrigin(request.origin ?? "");
1584
+ if (!appOrigin)
1585
+ return failure("internal", "The app's public origin is unknown (set auth.resource).");
1586
+ const ticket = await embed.issue(caller, name, String(args.origin), appOrigin);
1587
+ return { content: text(`A ticket for «${this.#t(caller, page.config.title)}», valid until ${ticket.expiresAt}.`), structuredContent: ticket };
1588
+ }
1589
+ catch (error) {
1590
+ if (!(error instanceof EmbedError))
1591
+ throw error;
1592
+ if (error.code === "misconfigured") {
1593
+ console.error(`[${PROTOCOL_ID}] ${error.message}`);
1594
+ return failure("internal", "The app can't issue embed tickets (misconfigured).");
1595
+ }
1596
+ return failure(error.code === "not_found" ? "not_found" : error.status === 403 ? "permission_denied" : "invalid_input", error.message, error.code === "wrong_origin" ? { fields: { origin: error.message } } : undefined);
1597
+ }
1598
+ }));
1599
+ }
1600
+ // The resolver hosts use for cards (hidden from models).
1601
+ reg(RESOLVE_TOOL, {
1602
+ title: "Resolve",
1603
+ description: "For hosts: fragment and record URIs resolved for the viewer.",
1604
+ inputSchema: z.object({ uris: z.array(z.string()).max(50), want: z.enum(["reference", "fragment", "snapshot"]).optional() }),
1605
+ annotations: { ...read },
1606
+ _meta: { ui: { visibility: ["app"] }, "openai/visibility": "private", "openai/widgetAccessible": true },
1607
+ }, guard(RESOLVE_TOOL, async (args, mctx) => {
1608
+ const ctx = ctxOf(mctx);
1609
+ const results = [];
1610
+ const pointers = [];
1611
+ // Every URI is read at once (one slow record doesn't hold the others); the answer keeps the order asked.
1612
+ const uris = args.uris;
1613
+ const resolved = await Promise.all(uris.map((uri) => {
1614
+ const parsed = this.parseUri(uri);
1615
+ return parsed ? this.#resolve({ type: parsed.type, params: parsed.params }, caller, ctx).then((r) => ({ parsed, r })) : null;
1616
+ }));
1617
+ for (const [i, uri] of uris.entries()) {
1618
+ const found = resolved[i];
1619
+ if (!found) {
1620
+ // Another app's URI is not this app's to answer (spec §6): not_found, never a guess. This app's unknown type or record: gone.
1621
+ results.push({ uri, state: uri.startsWith(`${uriPrefix(this.name)}/`) ? "gone" : "not_found" });
1622
+ continue;
1623
+ }
1624
+ const { parsed, r } = found;
1625
+ if (r.state !== "ok")
1626
+ results.push({ uri, state: r.state });
1627
+ else {
1628
+ // For the host: which values are outsiders' text (it wraps them before a model reads them).
1629
+ const at = `/results/${results.length}`;
1630
+ const entity = this.#entities.get(parsed.type);
1631
+ if (entity && "title" in r)
1632
+ this.#markCard(entity, { title: String(r.title), ...("subtitle" in r && typeof r.subtitle === "string" ? { subtitle: r.subtitle } : {}) }, at, pointers);
1633
+ if (args.want !== "reference")
1634
+ this.#markResolved(r, at, pointers);
1635
+ const { fragment: _f, view, ...rest } = r;
1636
+ const actions = view?.actions ? { actions: view.actions.map((a) => a.tool) } : "actions" in rest && Array.isArray(rest.actions) ? { actions: rest.actions.map((a) => a.tool) } : {};
1637
+ results.push(args.want === "reference" ? { uri, state: "ok", title: "title" in rest ? rest.title : "", ...("subtitle" in rest ? { subtitle: rest.subtitle } : {}), ...("status" in rest ? { status: rest.status } : {}) } : { ...rest, ...actions, uri });
1638
+ }
1639
+ }
1640
+ return { content: text(`${results.length} resolved`), structuredContent: { results }, ...this.#marks(pointers) };
1641
+ }));
1642
+ // Actions.
1643
+ for (const a of this.#actions.values()) {
1644
+ if (!this.#mayUse(a, caller))
1645
+ continue;
1646
+ const title = t(a.config.title);
1647
+ // An action on a record: the id, and the record's title as a display hint, so a client's own approval prompt can
1648
+ // name the record the person approves (spec §6 rule 10). Descriptions in the app's locale, like every tool's.
1649
+ const one = a.entity ? t(a.entity.config.label).toLowerCase() : "";
1650
+ const input = a.entity
1651
+ ? z.object({
1652
+ id: z.string().describe(`The ${one}'s id, from a list, search or get result. When you describe this action or ask the person to approve it, name the ${one} by its title, never by this id`),
1653
+ [RECORD_TITLE_PARAM]: z.string().max(300).optional().describe(`The ${one}'s title as the list, search or get result gave it, so the person sees which ${one} they approve. Display only: the app names the ${one} from its id, and refuses the call if this names another one`),
1654
+ ...a.input.shape,
1655
+ })
1656
+ : a.input;
1657
+ const crossInput = Object.values((jsonSchemaOf(a.input, "input").properties ?? {})).some((p) => kindRef(p));
1658
+ reg(a.tool, {
1659
+ title,
1660
+ description: `${t(a.config.description) || title}${a.write ? (a.confirm === "always" ? " (a change; the person confirms it first)" : " (a change)") : ""}.${a.entity ? ` On one ${one}: its \`id\`, and its title in \`${RECORD_TITLE_PARAM}\`.` : ""}${crossInput ? ` ${CROSS_INPUT_HINT}` : ""}`,
1661
+ inputSchema: listedOnly(input, t),
1662
+ annotations: { title, readOnlyHint: !a.write, destructiveHint: a.write && a.confirm === "always", idempotentHint: !a.write, openWorldHint: false },
1663
+ _meta: this.#callable(a.config.visibility === "app"),
1664
+ }, guard(a.tool, (args, mctx) => this.#runAction(a, caller, args, mctx, request, request.received.get(mctx.mcpReq.id))));
1665
+ }
1666
+ // Pages: open_<page> (record pages are <entity>_get).
1667
+ for (const p of this.#allPages()) {
1668
+ const c = p.config;
1669
+ if (c.kind === "record" || !this.#canOpen(p, caller))
1670
+ continue;
1671
+ const title = t(c.title);
1672
+ const params = this.#pageParams(p, caller);
1673
+ const shape = c.kind === "list" ? { ...params.shape, cursor: z.string().optional(), limit: z.number().int().min(1).max(100).optional() } : params.shape;
1674
+ const resource = c.kind === "list" && !c.view ? this.#viewUri() : this.#pageViewUri(p.name);
1675
+ reg(p.tool.name, {
1676
+ title,
1677
+ description: `Opens the page «${title}»${t(c.description) ? `: ${t(c.description)}` : ""}. Its parameters set the state it opens in.`,
1678
+ inputSchema: c.kind === "list" && !c.params ? z.strictObject(shape) : z.object(shape),
1679
+ annotations: { title, ...read },
1680
+ _meta: this.#ui(resource),
1681
+ }, guard(p.tool.name, async (args, mctx) => {
1682
+ const ctx = ctxOf(mctx);
1683
+ const { cursor, limit, ...rest } = args;
1684
+ const parsed = params.safeParse(rest, this.#zodLocale(caller));
1685
+ if (!parsed.success)
1686
+ return this.#invalid(params, parsed.error, caller);
1687
+ const pageParams = parsed.data;
1688
+ if (c.kind === "list") {
1689
+ const e = this.#entities.get(c.entity.name);
1690
+ const query = this.#queryOf(e, caller, { ...(c.query ? {} : pageParams), cursor, limit }, c.query ? c.query(pageParams) : undefined);
1691
+ const out = await this.#list(e, caller, ctx, query);
1692
+ const visible = new Set(this.#visibleFields(e, caller).map((f) => f.name));
1693
+ // A page with parameters of its own decides its order itself (query): its columns are not sortable from outside.
1694
+ const columns = c.columns.filter((n) => visible.has(n)).map((n) => this.#column(e.fields.find((f) => f.name === n), caller)).map(({ sort, ...col }) => (sort && !c.params ? { ...col, sort } : col));
1695
+ const pointers = [];
1696
+ const marked = out.rows.map((r, i) => this.#markRow(e, r, `/rows/${i}`, pointers));
1697
+ const refs = await this.#refs(e, out.rows, caller, ctx, pointers);
1698
+ return {
1699
+ content: text(JSON.stringify({ page: p.name, rows: marked.map((r) => this.#named(e, r, refs)), ...(out.next ? { next: out.next } : {}) })),
1700
+ structuredContent: { page: p.name, entity: e.name, params: pageParams, ...out, uris: out.rows.map((r) => this.uri(e.name, String(r.id))), refs, view: { kind: "list", title: this.#t(caller, c.title), columns, tool: p.tool.name, args: pageParams, getTool: e.tools.get.name, ...(query.sort && !c.params ? { sort: query.sort } : {}), ...this.#pageExtras(p, caller, pageParams) } },
1701
+ ...this.#marks(pointers),
1702
+ };
1703
+ }
1704
+ if (c.kind === "dashboard") {
1705
+ const instances = typeof c.fragments === "function" ? await c.fragments(pageParams, ctx) : c.fragments;
1706
+ const fragments = [];
1707
+ for (const i of instances)
1708
+ fragments.push({ ...(await this.#resolve(i, caller, ctx)), ...(i.size ? { size: i.size } : {}) });
1709
+ const pointers = [];
1710
+ return {
1711
+ content: text(JSON.stringify({ page: p.name, fragments: fragments.map((f, i) => ({ uri: f.uri, state: f.state, ...("data" in f ? { data: this.#markResolved(f, `/fragments/${i}`, pointers) } : {}) })) })),
1712
+ structuredContent: { page: p.name, params: pageParams, fragments, view: { kind: "dashboard", title: this.#t(caller, c.title), tool: p.tool.name, args: pageParams, ...this.#pageExtras(p, caller, pageParams) } },
1713
+ ...this.#marks(pointers),
1714
+ };
1715
+ }
1716
+ return { content: text(`Opened ${title}.`), structuredContent: { page: p.name, params: pageParams, view: { kind: "custom", title: this.#t(caller, c.title), ...this.#pageExtras(p, caller, pageParams) } } };
1717
+ }));
1718
+ }
1719
+ // Custom fragment types: show_<type>.
1720
+ for (const f of this.#fragments.values()) {
1721
+ if (!this.#canShow(f, caller))
1722
+ continue;
1723
+ const title = t(f.config.title);
1724
+ reg(f.tool.name, {
1725
+ title,
1726
+ description: `${t(f.config.description).replace(/[.\s]*$/, "")}. Shows it as a live fragment; don't repeat its data in full.`,
1727
+ inputSchema: f.config.params,
1728
+ annotations: { title, ...read },
1729
+ _meta: this.#ui(f.config.view ? this.#fragmentViewUri(f.type) : this.#viewUri(), f.config.visibility === "app"),
1730
+ }, guard(f.tool.name, async (args, mctx) => {
1731
+ const r = await this.#resolve({ type: f.type, params: args }, caller, ctxOf(mctx));
1732
+ if (r.state !== "ok")
1733
+ return failure(r.state === "no-access" ? "permission_denied" : "not_found", r.state === "no-access" ? "No access." : "Not available.");
1734
+ const pointers = [];
1735
+ return { content: text(JSON.stringify({ uri: r.uri, data: this.#markResolved(r, "", pointers) })), structuredContent: { ...r, view: { kind: "fragment", title: this.#t(caller, f.config.title) } }, ...this.#marks(pointers) };
1736
+ }));
1737
+ }
1738
+ // The installation's own tools: listed only to the installation-level caller (a workspace host, no person).
1739
+ if (this.#isInstallation(caller))
1740
+ this.#installationTools(caller, reg, guard, request);
1741
+ this.options.mcp?.(s, caller);
1742
+ return s;
1743
+ }
1744
+ /** `clegra_later` (when an action has later) and the lifecycle tools the app implements, for the installation-level caller. */
1745
+ #installationTools(caller, reg, guard, request) {
1746
+ const write = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };
1747
+ const meta = (mctx) => mctx.mcpReq._meta;
1748
+ /** A lifecycle handler's context, its notifications kept for the result. */
1749
+ const run = async (mctx, fn) => {
1750
+ const notes = [];
1751
+ const ctx = this.#context(caller, meta(mctx), notes);
1752
+ const result = await fn(ctx);
1753
+ const sent = this.#notificationsMeta(this.#sent(notes, caller, ctx));
1754
+ return { ...result, ...sent };
1755
+ };
1756
+ if (this.#laterActions().length) {
1757
+ reg(LATER_TOOL, {
1758
+ title: "Run due later actions",
1759
+ description: "For the workspace host, as the installation (its schedule clegra_later): runs the actions people confirmed for later whose time has come.",
1760
+ inputSchema: z.object({}),
1761
+ annotations: { title: "Run due later actions", ...write },
1762
+ _meta: APP_ONLY_META,
1763
+ }, guard(LATER_TOOL, async (_args, mctx) => {
1764
+ const report = await this.#runDue(caller.installation, meta(mctx), request.trust, caller.locale);
1765
+ const count = (status) => report.runs.filter((r) => r.status === status).length;
1766
+ return {
1767
+ content: text(`${report.runs.length} due: ${count("done")} done, ${count("failed")} failed, ${count("expired")} expired, ${count("refused")} refused.`),
1768
+ structuredContent: { runs: report.runs },
1769
+ ...this.#notificationsMeta(report.notifications),
1770
+ };
1771
+ }));
1772
+ }
1773
+ const life = this.#lifecycle;
1774
+ if (life.installation) {
1775
+ const handler = life.installation;
1776
+ reg(INSTALLATION_TOOL, {
1777
+ title: "Installation changed",
1778
+ description: "For the workspace host, as the installation: the administrator enabled, disabled or uninstalled the app.",
1779
+ inputSchema: z.object({ state: z.enum(["enabled", "disabled", "uninstalled"]) }),
1780
+ annotations: { title: "Installation changed", ...write, idempotentHint: true },
1781
+ _meta: APP_ONLY_META,
1782
+ }, guard(INSTALLATION_TOOL, (args, mctx) => run(mctx, async (ctx) => {
1783
+ await handler(args.state, ctx);
1784
+ return { content: text(`The installation is ${String(args.state)}.`), structuredContent: { ok: true } };
1785
+ })));
1786
+ }
1787
+ if (life.export) {
1788
+ const handler = life.export;
1789
+ reg(EXPORT_TOOL, {
1790
+ title: "Export",
1791
+ description: "For the workspace host, as the installation: everything the app keeps for it, as one file (an embedded resource).",
1792
+ inputSchema: z.object({}),
1793
+ annotations: { title: "Export", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
1794
+ _meta: APP_ONLY_META,
1795
+ }, guard(EXPORT_TOOL, (_args, mctx) => run(mctx, async (ctx) => {
1796
+ const file = await handler(ctx);
1797
+ if (!file)
1798
+ return { content: text("The app keeps nothing for this installation."), structuredContent: { empty: true } };
1799
+ return this.#exportResult(file);
1800
+ })));
1801
+ }
1802
+ if (life.delete) {
1803
+ const handler = life.delete;
1804
+ reg(DELETE_TOOL, {
1805
+ title: "Delete",
1806
+ description: "For the workspace host, as the installation: deletes everything the app keeps for it. Asking again answers the same.",
1807
+ inputSchema: z.object({}),
1808
+ annotations: { title: "Delete", readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
1809
+ _meta: APP_ONLY_META,
1810
+ }, guard(DELETE_TOOL, (_args, mctx) => run(mctx, async (ctx) => {
1811
+ const out = await handler(ctx);
1812
+ // The later runs the SDK keeps for the tenant are its data too.
1813
+ const later = this.#store.later ? await this.#store.later.clear(caller.installation) : 0;
1814
+ const counts = { ...(out && out.counts ? out.counts : {}), ...(later ? { later_runs: later } : {}) };
1815
+ return { content: text("Deleted."), structuredContent: { deleted: true, ...(Object.keys(counts).length ? { counts } : {}) } };
1816
+ })));
1817
+ }
1818
+ }
1819
+ /** An export as the host takes it: the file's facts, and the file itself as one embedded resource (base64). */
1820
+ #exportResult(file) {
1821
+ const EXT = { "application/json": ".json", "text/csv": ".csv", "application/zip": ".zip", "text/plain": ".txt", "application/x-ndjson": ".ndjson" };
1822
+ if (typeof file.contentType !== "string" || !/^[\w.+-]+\/[\w.+-]+(\s*;.*)?$/.test(file.contentType))
1823
+ throw new Error(`lifecycle.export: contentType "${String(file.contentType)}" is not a media type`);
1824
+ const name = file.name ?? `${this.name}-export${EXT[file.contentType.split(";")[0].trim()] ?? ""}`;
1825
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(name))
1826
+ throw new Error(`lifecycle.export: name "${name}": letters, digits, . _ -, at most 128`);
1827
+ const bytes = typeof file.body === "string" ? Buffer.from(file.body, "utf8") : Buffer.from(file.body.buffer, file.body.byteOffset, file.body.byteLength);
1828
+ if (bytes.byteLength > EXPORT_MAX_BYTES)
1829
+ throw new Error(`lifecycle.export: ${bytes.byteLength} bytes; an export is at most ${EXPORT_MAX_BYTES} bytes`);
1830
+ const sha256 = createHash("sha256").update(bytes).digest("hex");
1831
+ return {
1832
+ content: [
1833
+ { type: "text", text: `Export ${name}: ${bytes.byteLength} bytes.` },
1834
+ { type: "resource", resource: { uri: `${uriPrefix(this.name)}/export/${encodeURIComponent(name)}`, mimeType: file.contentType, blob: bytes.toString("base64") } },
1835
+ ],
1836
+ structuredContent: { name, contentType: file.contentType, bytes: bytes.byteLength, sha256 },
1837
+ };
1838
+ }
1839
+ // ------------------------------------------------------------ the manifest
1840
+ /** The manifest (spec §2), built from the definition: pure JSON. Throws on references that don't hold. */
1841
+ manifest() {
1842
+ if (this.#manifest)
1843
+ return this.#manifest;
1844
+ const L = (l) => labelMap(l, this.locale);
1845
+ const perm = (p, where) => {
1846
+ if (p && !this.#permissions.has(p))
1847
+ throw new Error(`${where}: permission "${p}" is not registered`);
1848
+ return p ? { permission: p } : {};
1849
+ };
1850
+ // An action's input for hosts that draw its form: the plain JSON Schema, each property with its `label` map.
1851
+ const labelled = (schema) => {
1852
+ const raw = jsonSchemaOf(schema, "input");
1853
+ const plain = plainSchema(raw);
1854
+ for (const [k, p] of Object.entries(raw.properties ?? {})) {
1855
+ const shown = plain.properties?.[k];
1856
+ if (!shown)
1857
+ continue;
1858
+ if (isLabel(p.label))
1859
+ shown.label = L(p.label);
1860
+ // What a host needs to draw the field and to show its value before a confirmation: the entity an id belongs to, a number's currency.
1861
+ if (typeof p.ref === "string") {
1862
+ if (!this.#entities.has(p.ref))
1863
+ throw new Error(`an action's input "${k}": ref "${p.ref}" is not an entity`);
1864
+ shown.ref = p.ref;
1865
+ }
1866
+ const kind = kindRef(p);
1867
+ if (kind !== undefined) {
1868
+ if (kindNameProblem(kind))
1869
+ throw new Error(`an action's input "${k}": ref: ${kindNameProblem(kind)}`);
1870
+ shown.ref = { kind };
1871
+ }
1872
+ if (typeof p.currency === "string")
1873
+ shown.currency = p.currency;
1874
+ if (p.labels && typeof p.labels === "object")
1875
+ shown.labels = Object.fromEntries(Object.entries(p.labels).filter(([, l]) => isLabel(l)).map(([v, l]) => [v, L(l)]));
1876
+ }
1877
+ return plain;
1878
+ };
1879
+ const entities = [...this.#entities.values()].map((e) => {
1880
+ for (const f of e.fields) {
1881
+ if (localRef(f) && !this.#entities.has(localRef(f)))
1882
+ throw new Error(`entity "${e.name}", field "${f.name}": ref "${f.ref}" is not an entity`);
1883
+ perm(f.permission, `entity "${e.name}", field "${f.name}"`);
1884
+ }
1885
+ const fields = e.fields.map((f) => ({
1886
+ name: f.name,
1887
+ type: f.type,
1888
+ required: f.required,
1889
+ ...(f.enum ? { enum: f.enum } : {}),
1890
+ ...(f.role ? { role: f.role } : {}),
1891
+ label: L(f.label ?? f.name),
1892
+ ...(f.as !== undefined ? { as: f.as } : {}),
1893
+ ...(f.ref ? { ref: f.ref } : {}),
1894
+ ...(f.permission ? { permission: f.permission } : {}),
1895
+ ...(f.filter ? { filter: true } : {}),
1896
+ ...(f.sort ? { sort: true } : {}),
1897
+ ...(f.search ? { search: true } : {}),
1898
+ ...(f.labels ? { labels: Object.fromEntries(Object.entries(f.labels).map(([k, v]) => [k, L(v)])) } : {}),
1899
+ ...(f.tones ? { tones: f.tones } : {}),
1900
+ ...(f.currency ? { currency: f.currency } : {}),
1901
+ ...(f.untrusted ? { untrusted: true } : {}),
1902
+ }));
1903
+ return {
1904
+ name: e.name,
1905
+ label: L(e.config.label),
1906
+ plural: L(e.config.plural ?? e.config.label),
1907
+ ...(e.config.description ? { description: L(e.config.description) } : {}),
1908
+ ...(e.config.icon ? { icon: e.config.icon } : {}),
1909
+ ...(e.config.kind !== undefined ? { kind: e.config.kind } : {}),
1910
+ ...perm(e.config.permission, `entity "${e.name}"`),
1911
+ schema: plainSchema(jsonSchemaOf(e.config.schema)),
1912
+ fields,
1913
+ tools: { list: e.tools.list, get: e.tools.get },
1914
+ searchable: e.fields.some((f) => f.search),
1915
+ ...(e.config.visibility === "app" ? { visibility: "app" } : {}),
1916
+ };
1917
+ });
1918
+ const actions = [...this.#actions.values()].map((a) => ({
1919
+ name: a.name,
1920
+ tool: { name: a.tool, plain: a.plain },
1921
+ ...(a.entity ? { entity: a.entity.name } : {}),
1922
+ title: L(a.config.title),
1923
+ ...(a.config.description ? { description: L(a.config.description) } : {}),
1924
+ ...(a.config.icon ? { icon: a.config.icon } : {}),
1925
+ input: labelled(a.input),
1926
+ readOnly: !a.write,
1927
+ confirm: a.confirm,
1928
+ ...perm(a.config.permission, `action "${a.name}"`),
1929
+ ...(a.config.visibility === "app" ? { visibility: "app" } : {}),
1930
+ ...(a.config.targets?.length ? { targets: a.config.targets.map((x) => ({ target: x.target, needs: [...x.needs], ...(x.input ? { input: JSON.parse(JSON.stringify(x.input)) } : {}), ...(x.label !== undefined ? { label: L(x.label) } : {}) })) } : {}),
1931
+ ...(a.later ? { later: { at: a.later.at, window: a.later.window } } : {}),
1932
+ }));
1933
+ const everyone = { installation: "manifest", installationId: "manifest", person: null, permissions: new Set(this.#permissions.keys()), host: "workspace", issuer: "", subject: "" };
1934
+ const pages = this.#allPages().map((p) => {
1935
+ const c = p.config;
1936
+ const { actions: pageActions, badge: pageBadge } = c;
1937
+ const base = {
1938
+ name: p.name,
1939
+ kind: c.kind,
1940
+ ...(c.kind !== "record" || c.title ? { title: L(c.kind === "record" ? (c.title ?? this.#entities.get(c.entity.name).config.label) : c.title) } : { title: L(this.#entities.get(c.entity.name).config.label) }),
1941
+ ...(c.icon ? { icon: c.icon } : c.kind === "record" || c.kind === "list" ? (this.#entities.get(c.entity.name).config.icon ? { icon: this.#entities.get(c.entity.name).config.icon } : {}) : {}),
1942
+ ...perm(c.permission, `page "${p.name}"`),
1943
+ params: plainSchema(jsonSchemaOf(this.#pageParams(p, everyone), "input")),
1944
+ // Also on a record page, where the rules refuse them (a definition error, not a silent drop).
1945
+ ...(pageActions?.length ? { actions: pageActions.map((h) => this.#actions.get(h.tool)?.name ?? h.name) } : {}),
1946
+ ...(pageBadge !== undefined ? { badge: pageBadge } : {}),
1947
+ };
1948
+ const override = c.kind !== "custom" && c.view ? { view: this.#pageViewUri(p.name) } : {};
1949
+ if (c.kind === "list")
1950
+ return { ...base, entity: c.entity.name, columns: c.columns, tool: p.tool, ...override };
1951
+ if (c.kind === "record") {
1952
+ for (const s of c.sections ?? [])
1953
+ for (const f of s.fields)
1954
+ if (!c.entity.fields.some((x) => x.name === f))
1955
+ throw new Error(`page "${p.name}": field "${f}" is not a field of ${c.entity.name}`);
1956
+ return { ...base, entity: c.entity.name, tool: p.tool, ...override, ...(c.sections ? { sections: c.sections.map((s) => ({ title: L(s.title), fields: s.fields })) } : {}), ...(p.derived ? { derived: true } : {}) };
1957
+ }
1958
+ if (c.kind === "dashboard")
1959
+ return { ...base, tool: p.tool, view: this.#pageViewUri(p.name) };
1960
+ return { ...base, tool: p.tool, view: this.#pageViewUri(p.name), ...("url" in c ? { url: c.url } : {}) };
1961
+ });
1962
+ const fragments = [
1963
+ ...[...this.#entities.values()].map((e) => ({ type: e.name, title: L(e.config.label), entity: e.name, template: "record", params: { type: "object", properties: { id: { type: "string" } }, required: ["id"] }, tool: e.tools.get, ...(e.config.view ? { view: this.#entityViewUri(e.name) } : {}), ...perm(e.config.permission, `entity "${e.name}"`) })),
1964
+ ...[...this.#fragments.values()].map((f) => {
1965
+ for (const h of f.config.actions ?? [])
1966
+ if (!this.#actions.has(h.tool))
1967
+ throw new Error(`fragment "${f.type}": action ${h.tool} is not registered`);
1968
+ return {
1969
+ type: f.type,
1970
+ title: L(f.config.title),
1971
+ description: L(f.config.description),
1972
+ ...(f.config.icon ? { icon: f.config.icon } : {}),
1973
+ params: plainSchema(jsonSchemaOf(f.config.params, "input")),
1974
+ ...(f.config.template ? { template: f.config.template } : {}),
1975
+ ...(f.config.view ? { view: this.#fragmentViewUri(f.type) } : {}),
1976
+ tool: f.tool,
1977
+ ...perm(f.config.permission, `fragment "${f.type}"`),
1978
+ ...(f.config.actions?.length ? { actions: f.config.actions.map((h) => h.name) } : {}),
1979
+ ...(f.config.size ? { size: f.config.size } : {}),
1980
+ ...(f.config.untrusted ? { untrusted: true } : {}),
1981
+ ...(f.config.visibility === "app" ? { visibility: "app" } : {}),
1982
+ };
1983
+ }),
1984
+ ];
1985
+ const agents = [...this.#agents.entries()].map(([name, a]) => {
1986
+ // An agent's tools: entities (their reads) and actions, by name; or tool names as they are.
1987
+ const tools = a.tools.flatMap((x) => {
1988
+ const n = typeof x === "string" ? x : x.kind === "entity" ? x.name : x.name;
1989
+ const entity = this.#entities.get(n);
1990
+ if (entity)
1991
+ return [entity.tools.list.name, entity.tools.get.name];
1992
+ const action = [...this.#actions.values()].find((y) => y.name === n || y.tool === n);
1993
+ if (action)
1994
+ return [action.tool];
1995
+ if (this.#toolNames.has(n) || n === "search" || n === "fetch")
1996
+ return [n];
1997
+ throw new Error(`agent "${name}": "${n}" is not an entity, action or tool of this app`);
1998
+ });
1999
+ return { name, title: L(a.title), description: L(a.description), instructions: a.instructions, tools, tier: a.tier ?? "standard", ...(a.starters?.length ? { starters: a.starters.map((s) => L(s)) } : {}) };
2000
+ });
2001
+ const auth = this.options.auth ?? {};
2002
+ const types = [...this.#notificationTypes.entries(), ...(this.#laterActions().length ? [[LATER_TOOL, LATER_NOTIFICATION]] : [])];
2003
+ const notifications = types.map(([type, n]) => ({ type, label: L(n.label), ...(n.description !== undefined ? { description: L(n.description) } : {}), default: n.default !== false, ...perm(n.permission, `notification "${type}"`) }));
2004
+ const lifecycle = {
2005
+ ...(this.#lifecycle.installation ? { installation: INSTALLATION_TOOL } : {}),
2006
+ ...(this.#lifecycle.export ? { export: EXPORT_TOOL } : {}),
2007
+ ...(this.#lifecycle.delete ? { delete: DELETE_TOOL } : {}),
2008
+ };
2009
+ this.#manifest = {
2010
+ specVersion: SPEC_VERSION,
2011
+ name: this.name,
2012
+ title: L(this.options.title),
2013
+ version: this.options.version,
2014
+ ...(this.options.description ? { description: L(this.options.description) } : {}),
2015
+ ...(this.options.icons ? { icons: this.options.icons } : {}),
2016
+ ...(this.options.publisher ? { publisher: { name: this.options.publisher.name, url: this.options.publisher.url } } : {}),
2017
+ locale: this.locale,
2018
+ mcp: { url: `${this.#path}/mcp` },
2019
+ // The server's own address is what its tokens are for (never a name an app could claim): a host installs the app from it or not at all.
2020
+ auth: { ...(auth.resource ? { resource: auth.resource } : {}), authorizationServers: auth.authorizationServers ?? (auth.issuers ?? []).map((i) => i.issuer) },
2021
+ view: this.#viewUri(),
2022
+ resolveTool: RESOLVE_TOOL,
2023
+ ...(this.#embed ? { embed: { tool: { name: EMBED_TOOL, plain: true }, path: this.#embed.path, frameAncestors: [...this.#embed.frameAncestors] } } : {}),
2024
+ ...([...this.#entities.values()].some((e) => e.fields.some((f) => f.search)) ? { searchTool: "search" } : {}),
2025
+ ...(Object.keys(this.#kinds).length ? { kinds: Object.fromEntries(Object.entries(this.#kinds).map(([k, d]) => [k, { label: L(d.label), properties: d.properties }])) } : {}),
2026
+ entities,
2027
+ actions,
2028
+ pages,
2029
+ fragments,
2030
+ agents,
2031
+ permissions: [...this.#permissions.entries()].map(([id, p]) => ({ id, label: L(p.label), ...(p.description ? { description: L(p.description) } : {}), default: p.default === true })),
2032
+ settings: [...this.#settings.entries()].map(([id, s]) => ({
2033
+ id,
2034
+ label: L(s.label),
2035
+ ...(s.description ? { description: L(s.description) } : {}),
2036
+ type: s.type,
2037
+ required: s.required === true,
2038
+ ...(s.default !== undefined ? { default: s.default } : {}),
2039
+ })),
2040
+ ...(this.#nav ? { nav: this.#nav.map((s) => ({ ...(s.section !== undefined ? { section: L(s.section) } : {}), pages: [...s.pages] })) } : {}),
2041
+ ...(this.#allSchedules().length ? { schedules: this.#allSchedules().map((s) => ({ name: s.name, ...(s.name !== LATER_TOOL ? { action: s.action?.name ?? s.tool } : {}), tool: s.tool, every: s.every, maxSeconds: s.maxSeconds })) } : {}),
2042
+ ...(notifications.length ? { notifications } : {}),
2043
+ ...(Object.keys(lifecycle).length ? { lifecycle } : {}),
2044
+ };
2045
+ // The rules beyond the schema (spec/src/rules.ts, the same the conformance checks run): a wrong name fails here, at definition time.
2046
+ const problems = manifestRuleProblems(this.#manifest);
2047
+ if (problems.length) {
2048
+ this.#manifest = null;
2049
+ throw new Error(problems.join("; "));
2050
+ }
2051
+ return this.#manifest;
2052
+ }
2053
+ // ------------------------------------------------------------ dev helpers
2054
+ async #devStarted() {
2055
+ if (!this.#dev)
2056
+ throw new Error("auth.dev is off");
2057
+ this.#devReady ??= this.#dev.start();
2058
+ await this.#devReady;
2059
+ return this.#dev;
2060
+ }
2061
+ /**
2062
+ * A dev access token (tests, local hosts). `host: "workspace"` makes the SDK ask for confirmation proofs.
2063
+ * `person: null` with `host: "workspace"`: the installation-level caller (schedules, later runs, lifecycle tools).
2064
+ */
2065
+ async devToken(input = {}) {
2066
+ const dev = await this.#devStarted();
2067
+ return dev.token({ ...input, audience: DEV_ISSUER });
2068
+ }
2069
+ /**
2070
+ * A dev confirmation proof for one call (what a workspace host signs after «Confirm»). For an action with `later`
2071
+ * it carries the run's deadline (`until`, from the arguments' `at` and the action's window) unless `until` is given.
2072
+ */
2073
+ async devConfirmation(input) {
2074
+ const dev = await this.#devStarted();
2075
+ const sub = input.person ?? dev.people[0].id;
2076
+ const later = this.#actions.get(input.tool)?.later;
2077
+ const until = input.until ?? (later && typeof input.args[later.at] === "string" ? laterDeadline(input.args[later.at], later.window) : undefined);
2078
+ return signConfirmation(dev.key, { iss: DEV_ISSUER, aud: DEV_ISSUER, sub, installation: input.installation ?? dev.installation, tool: input.tool, args: input.args, call: input.call, ...(until !== undefined && Number.isFinite(until) ? { until } : {}) });
2079
+ }
2080
+ // ------------------------------------------------------------ HTTP
2081
+ #origin(request) {
2082
+ const url = new URL(request.url);
2083
+ const proto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim() || url.protocol.replace(":", "");
2084
+ const host = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || request.headers.get("host") || url.host;
2085
+ return `${proto}://${host}`;
2086
+ }
2087
+ async #caller(request, resource, trust) {
2088
+ const auth = this.options.auth ?? {};
2089
+ const bearer = /^Bearer\s+(.+)$/i.exec(request.headers.get("authorization") ?? "")?.[1]?.trim();
2090
+ const metadata = `${new URL(resource).origin}/.well-known/oauth-protected-resource${new URL(resource).pathname}`;
2091
+ const challenge = (reason) => new Response(JSON.stringify({ error: "invalid_token", error_description: reason }), {
2092
+ status: 401,
2093
+ headers: { "content-type": "application/json", "www-authenticate": `Bearer resource_metadata="${metadata}", error="invalid_token", error_description="${reason.replace(/"/g, "'")}"`, ...CORS },
2094
+ });
2095
+ if (!bearer) {
2096
+ if (auth.anonymous) {
2097
+ const a = auth.anonymous;
2098
+ return { installation: tenantOf(a.installation, "anonymous"), installationId: a.installation, person: a.person ?? null, permissions: new Set(a.permissions === "all" ? this.#allPermissions() : a.permissions), ...(a.locale ? { locale: a.locale } : {}), host: "plain", issuer: "anonymous", subject: a.person?.id ?? "anonymous" };
2099
+ }
2100
+ return challenge("sign in first");
2101
+ }
2102
+ if (trust.dev)
2103
+ await this.#devStarted();
2104
+ try {
2105
+ // A workspace host's token (or a dev token) is the SDK's to verify; any other is the app's own.
2106
+ if (auth.resolve && !this.#verifier.knows(bearer))
2107
+ return this.#resolved(await auth.resolve(bearer, request, { resource }));
2108
+ return await this.#verifier.verify(bearer, trust);
2109
+ }
2110
+ catch (error) {
2111
+ if (!(error instanceof AuthError))
2112
+ console.error(`[${PROTOCOL_ID}] auth`, error);
2113
+ return challenge(error instanceof AuthError ? error.message : "invalid token");
2114
+ }
2115
+ }
2116
+ /** A caller the app's own `auth.resolve` named, checked: its tenant is the app's, never one of a host's. */
2117
+ #resolved(r) {
2118
+ if (!r)
2119
+ throw new AuthError("not a token of this app");
2120
+ if (typeof r.installation !== "string" || !INSTALLATION.test(r.installation))
2121
+ throw new AuthError("auth.resolve: installation must match [A-Za-z0-9._:-]{1,128}");
2122
+ const person = r.person && typeof r.person.id === "string" && r.person.id ? { id: r.person.id, name: String(r.person.name ?? "") } : null;
2123
+ const known = new Set(this.#allPermissions());
2124
+ const permissions = r.permissions === "all" ? known : new Set([...(r.permissions ?? [])].filter((p) => known.has(p)));
2125
+ return { installation: r.installation, installationId: r.installation, person, permissions, ...(r.locale ? { locale: r.locale } : {}), host: "plain", issuer: OWN_ISSUER, subject: r.subject ?? person?.id ?? "anonymous" };
2126
+ }
2127
+ /** The app's own path of a request (its `path` taken off), or null when the request is outside it. */
2128
+ #local(pathname) {
2129
+ const base = this.#path;
2130
+ if (pathname.startsWith("/.well-known/"))
2131
+ return pathname;
2132
+ if (!base)
2133
+ return pathname;
2134
+ if (pathname === base)
2135
+ return "/";
2136
+ return pathname.startsWith(`${base}/`) ? pathname.slice(base.length) : null;
2137
+ }
2138
+ /**
2139
+ * Readiness for serving (`listen` in `@clegra/sdk/node`, a framework adapter): the manifest is built and
2140
+ * checked, the dev authority started. Returns the dev sign-in code when dev sign-in is on.
2141
+ */
2142
+ async start() {
2143
+ this.manifest();
2144
+ if (this.#dev)
2145
+ await this.#devStarted();
2146
+ const auth = this.options.auth ?? {};
2147
+ if (!this.#dev && !auth.issuers?.length && !auth.resolve && !auth.anonymous)
2148
+ console.warn(`[${PROTOCOL_ID}] nobody can sign in: give auth.resolve (the app's own tokens) or auth.issuers (workspace hosts), or turn on auth.dev while developing`);
2149
+ return { devCode: this.#dev?.code ?? null };
2150
+ }
2151
+ /** What is wrong with this configuration for production, said on every request instead of guessed around (no fallback). */
2152
+ #productionProblem() {
2153
+ if (process.env.NODE_ENV !== "production")
2154
+ return null;
2155
+ const auth = this.options.auth ?? {};
2156
+ if ((auth.resolve || auth.issuers?.length) && !auth.resource)
2157
+ return "auth.resource is required in production: this server's public MCP address (https://…/mcp), the only audience its tokens are accepted for";
2158
+ return null;
2159
+ }
2160
+ /**
2161
+ * One HTTP request (Fetch API): MCP at `<path>/mcp`, the manifest, OAuth metadata, the dev authority, `<path>/health`.
2162
+ * `info.remoteAddress`: the address the request came from. Dev sign-in and dev tokens count only when it is
2163
+ * a loopback address, checked on every request (`listen` passes the socket's; without it dev mode stays shut).
2164
+ */
2165
+ async fetch(request, info = {}) {
2166
+ const url = new URL(request.url);
2167
+ const origin = this.#origin(request);
2168
+ const auth = this.options.auth ?? {};
2169
+ const json = (body, status = 200, headers = {}) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...CORS, ...headers } });
2170
+ const problem = this.#productionProblem();
2171
+ if (problem)
2172
+ return json({ error: "misconfigured", error_description: problem }, 500);
2173
+ const base = this.#path;
2174
+ // The embed ticket exchange (spec §5.1), for a server that hands every request here (@clegra/sdk/node); Next's proxy
2175
+ // answers it before the route (embedProxy).
2176
+ if (this.#embed && url.pathname === this.#embed.exchangePath)
2177
+ return this.embed.exchange(request);
2178
+ const devHere = Boolean(this.#dev) && isLoopback(info.remoteAddress);
2179
+ // In dev the server is whatever address the caller reached it by (a tunnel); otherwise only its configured one.
2180
+ const requestResource = `${origin}${base}/mcp`;
2181
+ const resource = devHere ? requestResource : (auth.resource ?? requestResource);
2182
+ const trust = { dev: devHere, requestResource: devHere ? requestResource : null };
2183
+ // Preflight: the headers the browser asks for are allowed as asked (MCP 2026-07-28 clients send mcp-method, mcp-name, Mcp-Param-*; no cookies are ever used).
2184
+ if (request.method === "OPTIONS") {
2185
+ const asked = request.headers.get("access-control-request-headers");
2186
+ return new Response(null, { status: 204, headers: { ...CORS, ...(asked && /^[\w\-, ]{1,2000}$/.test(asked) ? { "access-control-allow-headers": asked } : {}), "access-control-max-age": "600", vary: "access-control-request-headers" } });
2187
+ }
2188
+ const path = this.#local(url.pathname);
2189
+ const notHere = () => new Response(`${localize(this.options.title, this.locale, this.locale)}: MCP at ${base}/mcp, manifest at ${MANIFEST_PATH}`, { status: 404, headers: { "content-type": "text/plain; charset=utf-8" } });
2190
+ if (path === null)
2191
+ return notHere();
2192
+ if (path === MANIFEST_PATH)
2193
+ return json(this.manifest(), 200, { "cache-control": "public, max-age=30" });
2194
+ if (path === "/" && request.method === "GET" && (request.headers.get("accept") ?? "").includes("application/json"))
2195
+ return json({ name: this.name, manifest: MANIFEST_PATH, mcp: `${base}/mcp` });
2196
+ if (path === "/health")
2197
+ return json({ ok: true, name: this.name, version: this.options.version });
2198
+ if (path === "/.well-known/oauth-protected-resource" || path === `/.well-known/oauth-protected-resource${base}/mcp`) {
2199
+ // Where a client signs a person in. With dev sign-in on it is this server alone: trusted issuers that are hosts sign their own tokens, a client has nothing to ask them.
2200
+ const servers = auth.authorizationServers ?? (devHere ? [`${origin}${base}`] : (auth.issuers ?? []).map((i) => i.issuer));
2201
+ return json({ resource, authorization_servers: servers, bearer_methods_supported: ["header"], scopes_supported: [OAUTH_SCOPE], resource_name: localize(this.options.title, this.locale, this.locale) });
2202
+ }
2203
+ if (auth.serve) {
2204
+ const answered = await auth.serve(request);
2205
+ if (answered)
2206
+ return answered;
2207
+ }
2208
+ if (devHere) {
2209
+ const dev = await this.#devStarted();
2210
+ // The dev authority's paths are the app's own (under `path`), its metadata also at the RFC 8414 address for an issuer with a path.
2211
+ const devPath = base && path.startsWith("/.well-known/") && path.endsWith(base) ? path.slice(0, -base.length) : path;
2212
+ const local = devPath === url.pathname ? request : new Request(new URL(devPath + url.search, url.origin), request);
2213
+ const answered = await dev.handle(local, `${origin}${base}`, resource);
2214
+ if (answered)
2215
+ return answered;
2216
+ }
2217
+ if (path !== "/mcp")
2218
+ return notHere();
2219
+ const caller = await this.#caller(request, resource, trust);
2220
+ if (caller instanceof Response)
2221
+ return caller;
2222
+ if (!this.options.store && !this.#warnedStore && process.env.NODE_ENV === "production") {
2223
+ this.#warnedStore = true;
2224
+ console.warn(`[${PROTOCOL_ID}] store: idempotency and one-time tokens are kept in memory; on serverless or several instances give a shared store (SqlStore)`);
2225
+ }
2226
+ // Each call's arguments as received (the MCP SDK hands tools the parsed ones): what a confirmation proof and the idempotency check cover.
2227
+ const received = new Map();
2228
+ if (request.method === "POST") {
2229
+ try {
2230
+ const body = JSON.parse(await request.clone().text());
2231
+ for (const m of Array.isArray(body) ? body : [body]) {
2232
+ const message = m;
2233
+ if (message && message.method === "tools/call" && (typeof message.id === "string" || typeof message.id === "number"))
2234
+ received.set(message.id, message.params?.arguments ?? {});
2235
+ }
2236
+ }
2237
+ catch { }
2238
+ }
2239
+ const response = await this.#handler.fetch(request, { authInfo: { token: "verified", clientId: caller.issuer, scopes: [], extra: { caller, request: { trust, received, origin } } } });
2240
+ const headers = new Headers(response.headers);
2241
+ for (const [k, v] of Object.entries(CORS))
2242
+ headers.set(k, v);
2243
+ return new Response(response.body, { status: response.status, headers });
2244
+ }
2245
+ /** Whether dev sign-in is on (it then answers loopback callers only). */
2246
+ get devMode() {
2247
+ return Boolean(this.#dev);
2248
+ }
2249
+ }
2250
+ const CORS = {
2251
+ "access-control-allow-origin": "*",
2252
+ "access-control-allow-methods": "GET, POST, DELETE, OPTIONS",
2253
+ "access-control-allow-headers": "authorization, content-type, mcp-session-id, mcp-protocol-version, last-event-id",
2254
+ "access-control-expose-headers": "www-authenticate, mcp-session-id",
2255
+ };
2256
+ //# sourceMappingURL=server.js.map