@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
package/docs/spec.md ADDED
@@ -0,0 +1,997 @@
1
+ # Clegra apps — specification
2
+
3
+ > Version 1.0, draft (2026-11-16). Normative; MUST, SHOULD and MAY as in RFC 2119.
4
+ > Clegra apps are Clegra's own developer platform: apps that Clegra draws natively
5
+ > in its workspace and that are, at the same time, plain MCP servers that ChatGPT,
6
+ > Claude and any MCP client use as they are. The package `@clegra/sdk` builds them; this
7
+ > page is the contract they meet. The wire name is `clegra` (manifest path, URI
8
+ > scheme, `_meta` key, token claim, OAuth scope, resolve tool).
9
+ > Anything not on this page is not part of 1.0.
10
+
11
+ ## 1. What it is
12
+
13
+ An **app** is described once, as one definition: entities, actions, pages,
14
+ fragments, agents, permissions, settings, and optionally its navigation,
15
+ schedules, notification types and lifecycle. The definition has two halves:
16
+
17
+ - the **manifest**: pure JSON, no code. The *workspace host* (Clegra: the
18
+ node of the company or person that installed the app; «host» below) reads it
19
+ with one fetch and draws the app natively: pages in its navigation, records
20
+ as cards, actions behind a confirmation, agents.
21
+ - the **handlers** (`get`, `list`, `run`, `data`), reached through a **plain
22
+ MCP server** generated from the same definition: tools with correct
23
+ annotations and MCP Apps `ui://` views. ChatGPT, Claude and any MCP client
24
+ use it as they use any MCP server.
25
+
26
+ **No MCP extension is required or announced.** An MCP client never needs the
27
+ manifest; the workspace host needs nothing beyond the manifest and MCP. Every
28
+ feature on this page degrades to plain MCP: what ChatGPT, Claude and other
29
+ clients see of each one is in §6.1.
30
+
31
+ ## 2. The manifest
32
+
33
+ Served at `GET /.well-known/clegra.json` (no authentication) and as one
34
+ MCP resource, `clegra://<name>` (`application/json`); the two MUST be identical.
35
+ JSON Schema: [`spec/schema/clegra.schema.json`](../spec/schema/clegra.schema.json).
36
+
37
+ | Key | Content |
38
+ |---|---|
39
+ | `specVersion` | `"1.0"` |
40
+ | `name`, `title`, `version`, `description?`, `icons?`, `locale` | Identity. `name` is the app id: `[a-z][a-z0-9-]{1,39}` |
41
+ | `publisher?` | `{ name, url }`: who publishes the app. `name` is the publisher's own name (1–100 characters, no spaces around it, no control characters), `url` its web address, an absolute `https` URL without credentials (at most 300 characters). A claim: it grants nothing. A store or host may verify it against the domain of `url` and show the app's publisher as verified; an unverified publisher is never shown as verified |
42
+ | `mcp` | `{ url }`: the MCP endpoint (Streamable HTTP), relative to the manifest (`/mcp`, or under the app's path, `/api/clegra/mcp`). The manifest and the OAuth metadata are always under `/.well-known/` at the root |
43
+ | `auth` | `{ resource?, authorizationServers }` (§7). `resource` is the app's own public MCP address: the only token audience it accepts |
44
+ | `view` | The generated `ui://` view that draws lists, records, dashboards, fragments |
45
+ | `resolveTool`, `searchTool?` | Tools a host uses to resolve URIs and to search |
46
+ | `embed?` | `{ tool, path, frameAncestors }`: the app's own pages that hosts frame (§5.1). Present exactly when a page has a same-site `url` |
47
+ | `kinds?` | Definitions of the namespaced kinds this app uses (§3.1) |
48
+ | `entities`, `actions`, `pages`, `fragments`, `agents` | §3–§5 |
49
+ | `permissions` | `{ id, label, description?, default }`; ids are `group.verb` |
50
+ | `settings` | `{ id, label, description?, type: text\|number\|boolean, required, default? }` (`id`: `[a-z][a-z0-9_]{1,39}`): values an administrator sets per installation; the workspace host sends them with every call (§7). Never secrets: those stay in the app's own configuration |
51
+ | `nav?` | `[{ section?, pages }]`: the app's navigation (§5.2) |
52
+ | `schedules?` | `[{ name, action?, tool, every, maxSeconds }]`: actions the workspace host runs as the installation (§11) |
53
+ | `notifications?` | `[{ type, label, description?, default, permission? }]`: the notification types the app sends (§12) |
54
+ | `lifecycle?` | `{ installation?, export?, delete? }`: the reserved lifecycle tools the app implements (§13) |
55
+
56
+ **Labels** are always maps per locale (`{ "en": "Deal", "it": "Trattativa" }`);
57
+ a host picks the person's locale, then `locale`, then the first entry.
58
+ Identifiers are never translated. **Tool refs** are `{ name, plain }`: the MCP
59
+ tool, and whether it is listed to plain MCP clients.
60
+ **Agents** are `{ name, title, description, instructions, tools, tier:
61
+ fast|standard|strong, starters? }`: the host's model runs them with those tools.
62
+ **Reserved names**: the tools `clegra_later`, `clegra_installation`,
63
+ `clegra_export` and `clegra_delete` are the installation's (§10); no entity,
64
+ action, page or fragment tool takes them. The schedule and notification type
65
+ `clegra_later` are the SDK's (§4.2). Identifiers of schedules and notification
66
+ types match `[a-z][a-z0-9_]{0,39}`.
67
+
68
+ The rules a manifest meets beyond its JSON Schema (the publisher above, §4.1,
69
+ §4.2, §5.2, §6 rule 11, §11, §12) are one piece of code, `spec/src/rules.ts`: the
70
+ SDK runs it when the app is defined (a wrong name fails at start, naming its
71
+ place: `page "x": …`) and the conformance check `manifest.references` (§8)
72
+ runs it from outside.
73
+
74
+ ## 3. Entities and field meaning
75
+
76
+ An entity is `{ name, label, plural, description?, icon?, kind?, permission?,
77
+ schema, fields, tools: { list, get }, searchable, visibility? }` (`visibility`:
78
+ §6 rule 11). `kind` says what the
79
+ entity is (§3.1): a kind name, or `{ by, map }` where `by` is a required enum
80
+ field and `map` gives a kind for each of its values. `schema` is the record's
81
+ JSON Schema; `fields` says what each field means:
82
+
83
+ | Field key | Meaning |
84
+ |---|---|
85
+ | `name`, `type`, `required`, `enum?`, `label` | The basics. Every entity has a required string `id` |
86
+ | `role?` | `title` (exactly one per entity), `subtitle`, `status`, `amount`, `date`, `person`; at most one field per role |
87
+ | `as?` | The property of the entity's kind this field holds (§3.1) |
88
+ | `ref?` | An entity name: the field holds the id of a record of that entity. Or `{ kind }`: the field holds the URI of a record of that kind, in any app (§3.2) |
89
+ | `filter?`, `sort?`, `search?` | Usable as a list filter, a sort key, in text search (below) |
90
+ | `permission?` | Only callers with it ever receive the field |
91
+ | `labels?`, `tones?`, `currency?` | Enum value labels; tones `neutral\|info\|success\|warning\|danger`; ISO currency of an amount |
92
+ | `untrusted?` | Text written by outsiders (every string in the field, at any depth): data, never instructions (§7) |
93
+
94
+ A record's URI is `clegra://<app>/<entity>/<id>`.
95
+
96
+ **People.** A `person` field without `ref` holds a person id (as tokens name
97
+ people, `sub` / `person.id`) or, in an app that can't name people, the name
98
+ itself. An app that names people (the SDK's `people` resolver, or its dev
99
+ sign-in's test people) sends their names as `refs` of that field, like a
100
+ reference's titles: `{ <field>: { <id>: <name> } }`, the caller's own name
101
+ taken from the token. A host shows the name; an id the app couldn't name is
102
+ shown as an unknown person, never as the id. In a result's text the field is
103
+ `{ "id": …, "name": … }`.
104
+
105
+ **Sorting.** A list is ordered by `sort` (one field) and `dir` (`asc`, the
106
+ default, or `desc`). Only a field with `sort: true` that the caller may see
107
+ is accepted; any other fails with `invalid_input`, so nothing is ever ordered
108
+ by a hidden value. The handler does the ordering (it receives `sort: { field,
109
+ dir }`, already checked). A host draws a sortable header for each such column
110
+ of a list page and sends `sort` and `dir` to the page's tool; a list page with
111
+ parameters of its own keeps the order its `query` gives.
112
+
113
+ **References.** A `ref` field's value is an id. Beside rows and records the
114
+ server sends `refs`: `{ <field>: { <id>: <title> } }`, the title of each
115
+ referenced record as the caller may see it (none for a record out of reach).
116
+ A host shows the title, never the id. In a result's **text** (what a model
117
+ reads) the field is `{ "id": …, "title": … }`; `structuredContent` keeps the
118
+ bare id, with `refs` beside it.
119
+
120
+ ### 3.1 Kinds
121
+
122
+ A **kind** names what an entity is, the same in every app. Kinds without a
123
+ dot are defined by this specification and published, with their properties,
124
+ as [`spec/kinds.json`](../spec/kinds.json).
125
+ Property names are schema.org's, verbatim (JSCalendar's where schema.org has
126
+ none: `due`, `uid`):
127
+
128
+ | `kind` | Properties (`as`) | Keys |
129
+ |---|---|---|
130
+ | `person` | `givenName`, `familyName`, `email`†, `telephone`†, `jobTitle`, `worksFor`, `address`, `image` | `email` |
131
+ | `organization` | `legalName`, `email`†, `telephone`†, `url`, `address`, `vatID`, `taxID` | `vatID` |
132
+ | `event` | `startDate` (required), `endDate`, `location`, `attendee`†, `organizer`, `uid` | `uid` |
133
+ | `task` | `due`, `startDate`, `completed`, `assignee` | — |
134
+ | `document` | `url`, `encodingFormat`, `author`, `contentSize` | — |
135
+ | `product` | `sku`, `gtin`, `brand`, `price` | `gtin` |
136
+ | `order` | `orderNumber`, `orderDate`, `customer`, `totalPrice` | — |
137
+
138
+ † multi-valued: an array field, or several fields with the same `as`. Any
139
+ entity, with or without a kind, MAY mark the **universal** properties `url`
140
+ (the record in the app's own pages), `dateCreated` and `dateModified`; on a
141
+ kind that defines `url` itself (organization: its website; document: the
142
+ document) the kind's meaning applies. `message`, `place`, `invoice` and
143
+ `project` are reserved: no app may use them as kinds.
144
+
145
+ A property has a type, and the field holding it a matching one: `string`
146
+ and `date` (rule 4) a string field; `number` a number or integer; `boolean`
147
+ a boolean; `address` a string or an object; `money` a number or integer
148
+ whose field names its `currency`. A multi-valued property also matches an
149
+ array of those.
150
+
151
+ A kind with a dot is a third party's, named reverse-DNS under a domain it
152
+ controls (`com.acme.shipment`: lowercase segments of letters, digits and
153
+ `-`). A manifest MAY define it in `kinds`: `{ <kind>: { label, properties: {
154
+ <name>: { type, many?, key? } } } }`, names `[a-z][A-Za-z0-9]*`, a key always
155
+ of type `string` and compared exactly. Hosts match namespaced kinds by exact
156
+ name. An entity whose namespaced kind the manifest doesn't define may mark
157
+ only the universal properties.
158
+
159
+ 1. An entity has at most one kind per record. Its `title` field is the kind's
160
+ `name`; no `as` is needed for it. With `{ by, map }`, `by` is a required
161
+ enum field without `permission` (a record's kind is seen with the record),
162
+ and `map` names a kind for each of its values and for no other value.
163
+ 2. `as` MUST name a property of the entity's kind (of any mapped kind, with
164
+ `{ by, map }`) or a universal property. The field's type MUST match the
165
+ property's. A property not marked many MUST be on at most one field.
166
+ 3. An entity MUST have the properties its kind requires (`event`:
167
+ `startDate`). All others are optional. An app MUST NOT use `as` for a value
168
+ that only resembles the property. Fields without `as` are the app's own and
169
+ mean what they meant before.
170
+ 4. Values: `email` an addr-spec; `telephone` SHOULD be E.164; `vatID` the
171
+ country prefix and the number, no spaces; `gtin` 8, 12, 13 or 14 digits;
172
+ dates RFC 3339 (a date alone on an event means all day); `address` a string
173
+ or a schema.org `PostalAddress` object; `price` and `totalPrice` are
174
+ numbers whose field has `currency`.
175
+ 5. A field whose `as` is a **key** of its kind (`email`, `vatID`, `gtin`,
176
+ `uid`, and a namespaced kind's `key` properties) MUST have `filter: true`.
177
+ That filter is exact on the normalised value: `email` lower-cased, `vatID`
178
+ upper-cased without spaces, `gtin` its digits (spaces and `-` removed; any
179
+ other character is `invalid_input`), `uid` and namespaced keys as they are.
180
+ It takes a value or `{ in: [...] }`, never a range, and on a multi-valued
181
+ field it matches any of the values. The server normalises the filter
182
+ before the handler, and a list that answers a key filter with a record not
183
+ holding the value fails with `internal`.
184
+ 6. Kinds add no permission and remove none: `permission` on the entity and
185
+ its fields applies unchanged (a key filter on a field the caller may not see
186
+ fails with `invalid_input`, as any filter does).
187
+ 7. A host MUST treat an entity whose kind it does not know as an entity
188
+ without a kind. Within one `specVersion`, kinds and properties are only
189
+ added. `taxID` is a property, not a key, until a country-qualified form is
190
+ defined.
191
+
192
+ Kinds pay off when several apps of one workspace hold the same kind of thing
193
+ (pickers, references and search across apps, matching by key). An app's own
194
+ records (a deal, a ticket, a quote line) have no kind; none is invented for
195
+ them.
196
+
197
+ ### 3.2 References across apps
198
+
199
+ A field with `ref: { kind }` holds a record URI, `clegra://<app>/<entity>/<id>`
200
+ (`<app>` the name the app has in the workspace, §9): a record of that kind in
201
+ any app, this one included. Syntactically valid means: `<app>` matches
202
+ `[a-z][a-z0-9-]{1,39}`, `<entity>` `[a-z][a-z0-9_]{0,39}`, and `<id>` is one
203
+ or more characters without `/`, `?`, `#` or white space (an id that has them
204
+ is percent-encoded). The app stores the URI and nothing else of the
205
+ record (a title would be a copy that outlives permissions). It MUST accept any
206
+ syntactically valid record URI, MUST NOT call the other app, and sends no
207
+ `refs` entry for the field: the host resolves it for each viewer (§9). In a
208
+ result's text the field is `{ "uri": …, "kind": … }`, and the descriptions of
209
+ the entity's tools say, in a fixed sentence before the kind's, that the app
210
+ the URI names opens it with its `fetch` tool. An action input property MAY
211
+ carry the same `ref` (§4); its tool's description says it takes the URI.
212
+
213
+ A workspace host that relays a result to the app's view MAY add
214
+ `_meta.clegra.resolved`: `{ <uri>: { state, title? } }`, `state` being
215
+ `ok` (with the title) or one of the states of §9 rule 3. The generated view shows the title for `ok` and the state
216
+ otherwise; without it (a plain host) it shows the app and entity the URI
217
+ names, never a title.
218
+
219
+ ## 4. Actions
220
+
221
+ `{ name, entity?, title, description?, icon?, input, readOnly, confirm,
222
+ permission?, tool, visibility?, targets?, later? }`. With `entity` the action
223
+ works on one record and its tool takes `id` plus `input`; without, it is
224
+ global. `visibility`: §6 rule 11; `targets`: §4.1; `later`: §4.2. `confirm` is `always`
225
+ (the default for writes), `optional` or `never` (always, for reads). A result
226
+ is `{ ok: true, message, record?, data? }`.
227
+
228
+ `input` is a JSON Schema (`required`, `minLength`, `minimum`, `format: date`,
229
+ `enum` and the like are what a form checks). Its properties MAY carry, beside
230
+ `label`: `ref` (the entity whose record id the property holds: a form draws
231
+ a picker over that entity's list, showing titles, never a box for an id; or
232
+ `{ kind }`: the property holds a record URI of that kind in any app, §3.2,
233
+ and a workspace host draws its picker over every app of the workspace with
234
+ that kind),
235
+ `currency` (a number is money) and `labels` (an enum's values by label map).
236
+ A host uses the same keys to show a value before a confirmation: a record by
237
+ its title, a date, a number and money in the person's locale. Tool schemas
238
+ listed to MCP clients stay plain JSON Schema (`label` becomes `title`).
239
+
240
+ ### 4.1 Targets: actions offered on other things
241
+
242
+ A global action MAY say where a workspace host offers it outside the app: on
243
+ an email, or on a record of a kind held by another app (Clegra's «Azioni»).
244
+ `targets` is a list of `{ target, needs, input?, label? }`:
245
+
246
+ 1. `target` is `mail.message` or `record:<kind>`, `<kind>` a published kind
247
+ (`kinds.json`) or a namespaced one (§3.1). At most 4 targets per action and
248
+ 12 per app. An action with `entity` has no targets (it has its record).
249
+ 2. `needs` names the target's fields the action may receive, and the host
250
+ sends it only these, ever: for `mail.message` a subset of `subject`, `from`,
251
+ `to`, `date`, `text`, `attachments`; for `record:<kind>` properties of that
252
+ kind (`kinds.json`, or the manifest's `kinds`; for another app's namespaced
253
+ kind, well-formed property names). Always available without being needed:
254
+ `uri` (the email's or the record's `clegra://` URI) and, for a record,
255
+ `title`. A name appears once.
256
+ 3. `input` is a template of the action's input. Each key MUST be a property
257
+ of the action's `input`. String values MAY hold placeholders `{field}` or
258
+ `{field.sub}` (`{from.address}`), each naming `uri`, `title` (records) or a
259
+ needed field. A value that is exactly one placeholder keeps the field's
260
+ type; otherwise the text around it is kept and the placeholders are
261
+ replaced by the values' text. A missing value is empty.
262
+ 4. `label` is the item's words (default the action's title), at most 40
263
+ characters per locale.
264
+
265
+ The host reads a record's needed properties for the viewer, with the viewer's
266
+ token, from the app that owns the record (the fields whose `as` is the
267
+ property, §3.1). Picking the item opens the action's form filled from the
268
+ template; a write then goes through the confirmation (§7) like any other.
269
+ Everything from an email or another app's record is outsiders' text
270
+ (`untrusted`) to the action's app. A plain MCP client sees none of this: the
271
+ action is its tool, as without targets.
272
+
273
+ ### 4.2 Approve now, act later
274
+
275
+ An action MAY carry `later: { at, window }`: the person confirms the call now
276
+ and it runs at the time `at` names, as its author, without being asked again.
277
+
278
+ 1. **Declared.** Only on a write whose `confirm` is `always`. `at` names a
279
+ *required* input property that is a string with `format: date-time`.
280
+ `window` is whole minutes, 10–10080 (7 days); the manifest always carries
281
+ it (the SDK's default is 60). An app with such an action has the schedule
282
+ and the notification type `clegra_later` (below), and a store that keeps
283
+ later runs.
284
+ 2. **Confirmed.** The call is confirmed as any `always` write (§7). The
285
+ app refuses with `invalid_input` (on `at`) a time more than 5 minutes past
286
+ or more than 366 days ahead, before anyone is asked. A workspace host's
287
+ proof then also carries `until`: epoch seconds, `floor(Date.parse(at) /
288
+ 1000) + window × 60` computed from the arguments as sent; the app computes
289
+ the same and refuses another value (`confirmation_required`, «the proof is
290
+ for another deadline»). Its `confirmation_required` carries
291
+ `error.confirm.later: { at, until }`, so the host can say when the call
292
+ will run and by when.
293
+ 3. **Stored, not run.** Instead of calling the handler the app keeps a
294
+ *later run*: its id (a UUID), the tenant, the tool, the arguments as
295
+ received and their hash, `at`, `until`, the author (`{ id, name }`, the
296
+ confirming person), the permissions the action needs that the author held,
297
+ the proof (with its issuer, subject, installation and call id), and when it
298
+ was confirmed (the proof's `iat`). It answers `{ ok: true, message:
299
+ "Scheduled for <at>.", data: { later: { id, at, until } } }`; a repeated
300
+ call id answers the same (idempotency, §7).
301
+ 4. **Run once.** The tool `clegra_later` (input `{}`, only for the
302
+ installation-level caller, §10) takes the caller's tenant's runs that are
303
+ due (`at` ≤ now) and *claims* each atomically: a claimed run is never given
304
+ to anyone again, whatever happens next. For each it checks that the
305
+ arguments' hash and `at` are still the confirmed ones, that the stored
306
+ proof verifies against the issuer's keys *as of its confirmation time*,
307
+ covers these arguments, this call and this `until`, and has that `iat`, and
308
+ that the author may still use the action with the stored permissions
309
+ (otherwise `refused`). After `until` the run is `expired`. Otherwise the
310
+ handler runs with the stored input re-parsed (a record action reads its
311
+ record again), `ctx.person` = the author, `ctx.permissions` = the stored
312
+ ones, `ctx.later = { id, at, until, confirmedAt }`, `ctx.schedule =
313
+ "clegra_later"` and the settings the host sent with this call. The
314
+ outcome is kept: `done`, `failed`, `expired` or `refused`, with a message.
315
+ The result is `{ runs: [{ id, tool, at, status, message }] }`, and its
316
+ notifications (the handlers', the author by default) go out as any result's
317
+ (§12). An `expired` or `refused` run tells its author with the type
318
+ `clegra_later` (title: the action's title and «did not run»).
319
+ 5. **Cancelled.** A handler of the same tenant MAY cancel a pending run by
320
+ its id (`ctx.cancelLater(id)`: false when there is none, or it already ran
321
+ or started).
322
+ 6. **Scheduled.** The SDK adds the schedule `{ name: "clegra_later", tool:
323
+ "clegra_later", every: 5 }` (no `action`) and the notification type
324
+ `clegra_later` («Scheduled actions that did not run», `default: true`),
325
+ exactly when an action has `later`; no app declares them itself.
326
+ 7. **Plain clients.** A client that is not a workspace host can't produce a
327
+ proof. There a later action is an `always` write (elicitation where the
328
+ client supports it, else the client's own approval, guided by
329
+ `destructiveHint`, §7), and its run is stored with the caller as author and
330
+ no proof (`proof: null`): the caller's token was verified when the call was
331
+ confirmed. A run made with the app's own tokens belongs to the app's own
332
+ tenant, which no workspace host runs: the app runs its tenants' due runs
333
+ from its own cron (the SDK's `app.runLater(tenant)`; the notifications it
334
+ returns are the app's to deliver).
335
+
336
+ ## 5. Pages and fragments
337
+
338
+ A **page** is `{ name, kind, title, icon?, permission?, params, tool,
339
+ actions?, badge?, … }` (`actions`, `badge`: §5.2):
340
+
341
+ | `kind` | Extra keys | Drawn |
342
+ |---|---|---|
343
+ | `list` | `entity`, `columns` | Natively, from the list tool's rows |
344
+ | `record` | `entity`, `sections?` | Natively. Every entity has one (`derived: true` unless declared) |
345
+ | `dashboard` | `view` | Fragments on a grid |
346
+ | `custom` | `view`, or `view` + `url` | The developer's MCP Apps document, or their site in an isolated frame. `url` is https, or a path on the app's own site (`/embed/pipeline`), resolved against the app's public origin |
347
+
348
+ A **fragment** is a small live piece of the app shown in answers and on
349
+ dashboards: `{ type, title, description?, params, template?, view?, tool,
350
+ permission?, actions?, size?, untrusted?, visibility? }` (`visibility`: §6
351
+ rule 11). Templates are `record` (one per
352
+ entity, `params { id }`), `card`, `stat`, `list`, `chart`; a fragment without
353
+ a template has only a `view`. A fragment instance's URI is
354
+ `clegra://<app>/<type>/<base64url of its params, keys sorted>`.
355
+ `untrusted: true` says the fragment's texts are outsiders' (records' names):
356
+ they are marked like an untrusted field (§7).
357
+
358
+ Template data, which a workspace host draws natively:
359
+
360
+ | Template | Data |
361
+ |---|---|
362
+ | `card` | `{ title, subtitle?, status?, fields: [{ label, value }], uri? }` |
363
+ | `stat` | `{ label, value, format?: number\|money\|percent, currency?, hint? }` |
364
+ | `list` | `{ items: [{ title, subtitle?, status?, uri? }] }` |
365
+ | `chart` | `{ kind: bar\|line\|pie, points: [{ label, value }], format?: number\|money, currency? }` |
366
+
367
+ A `uri` is a record of the app: the item opens it. An item (or a card) whose
368
+ `uri` is a record the caller can't reach is not sent.
369
+
370
+ **Views** are MCP Apps documents (`ui://<app>/…`, `text/html;profile=mcp-app`).
371
+ Any generated view MAY be overridden per entity, page or fragment; the
372
+ manifest then names the override in `view`. A host MAY still draw natively.
373
+
374
+ The generated view sorts a list by its sortable columns, opens records,
375
+ draws an action's form from its `input` (required fields marked, each field
376
+ checked before sending, a `ref` as a picker) and shows under each field what
377
+ the server says is wrong with it (`error.fields`, §7). It asks nothing more
378
+ before a write: confirming is the host's (§7).
379
+
380
+ The generated view and the host (MCP Apps, `2026-01-26`):
381
+
382
+ - It sends `ui/initialize`, then `ui/notifications/initialized`, and makes
383
+ no `tools/call` before the host answered. A host that answers is called
384
+ over that bridge (ChatGPT included). Only a host that refuses
385
+ `ui/initialize` and offers `window.openai.callTool` is called through it,
386
+ and an answer without the result's `structuredContent` is an error.
387
+ - It draws the result of the call that opened it once: from
388
+ `ui/notifications/tool-result`, or from `window.openai.toolOutput` (its
389
+ `_meta` from `toolResponseMetadata`, the MCP result envelope) when that is
390
+ there first. Later tool-result notifications (hosts send them for the
391
+ view's own calls too) and `openai:set_globals` events never replace what
392
+ the person opened since; a new locale draws the same screen again.
393
+ - Every click that calls a tool shows progress at once, then the result, or
394
+ what the app or the host said (a host's refusal in its own words, a host
395
+ that doesn't answer within 30 seconds), where the person is looking: a
396
+ status line kept at the top of the view. A click is never silent.
397
+ - A record's action sends `id` and the record's title as `record_title`
398
+ (§6 rule 10). After a change made in the view it sends
399
+ `ui/update-model-context` with the result's text, so the model knows in
400
+ its next turn.
401
+
402
+ ### 5.1 Embedded pages: the sign-in ticket
403
+
404
+ A `custom` page whose `url` is a path on the app's own site (an *embed
405
+ page*) is framed by hosts on other sites, where the app's own session cookie
406
+ is a third-party cookie that browsers block. The viewer is signed in to it
407
+ with a ticket instead:
408
+
409
+ 1. **Declared.** An app with an embed page MUST have `embed` in its manifest:
410
+ `tool` (`clegra_embed`), `path` (default `/embed`; every embed page is
411
+ under it) and `frameAncestors`, the hosts that may frame embed pages, as
412
+ CSP sources: `https://host[:port]`, `https://*.host`, `'self'`; outside
413
+ production `http://localhost` and `http://127.0.0.1` (port or `:*`).
414
+ 2. **Asked for.** The host, holding the viewer's token for the app, calls
415
+ `clegra_embed { page, origin }`: `origin` is the origin of the document
416
+ that will frame the page and post the ticket. The tool is listed to every
417
+ caller with `_meta.ui.visibility: ["app"]` (hidden from models). It MUST
418
+ refuse a page the caller can't open (the page's permission, `plain`), an
419
+ origin that is opaque (`null`), not a serialized origin, or not matched by
420
+ `frameAncestors`. It answers `{ page, action, field, ticket, expiresAt }`.
421
+ 3. **The ticket** is a JWT (`typ: clegra-embed+jwt`, HMAC with a key only
422
+ the app holds), `iss` the app's origin, `aud` the page's absolute URL,
423
+ `origin`, `jti`, `iat`, `exp` at most 60 seconds after `iat`, and the
424
+ caller as the app named it (`clegra: { installation, person,
425
+ permissions, locale?, host }`), nothing more.
426
+ 4. **Posted, never in a URL.** The framing document submits a form with
427
+ `method="post"`, `action` = `<app origin><path>/_ticket`, `target` = the
428
+ frame, the ticket in the field `field`. So the ticket is never in an
429
+ address bar, the history, a server's access log or a `Referer`, and the
430
+ browser itself states the poster's `Origin`.
431
+ 5. **Exchanged once.** The app MUST refuse (a 4xx, no cookie) a request that
432
+ is not a POST, whose `Sec-Fetch-Dest` is not `iframe`, whose `Origin` is
433
+ not the ticket's `origin` or no longer matched by `frameAncestors`, and a
434
+ ticket that is tampered, of another app, for a page that isn't one of its
435
+ embed pages, expired, issued more than 5 seconds in the future, living
436
+ longer than 60 seconds, or already used (its `jti` kept, atomically,
437
+ until it expires: shared by every instance). Otherwise it answers `303` to
438
+ the page (absolute, from the ticket: never from the request) with
439
+ `Referrer-Policy: no-referrer`, `Cache-Control: no-store` and a session
440
+ cookie: `Secure; HttpOnly; SameSite=None; Partitioned` (CHIPS: kept under
441
+ the host's top-level site only), `Path` = the page's path, no `Domain`, a
442
+ short `Max-Age` (default 10 minutes, at most an hour), holding the
443
+ ticket's caller signed with another key than tickets.
444
+ 6. **Read by the page.** The page's caller is the session's (scope by its
445
+ `installation`, as a handler's `ctx`). The session counts only for its own
446
+ page and never for a top-level navigation (`Sec-Fetch-Dest: document`).
447
+ 7. **Framing.** Every response under `path` (the pages, the exchange and its
448
+ refusals) MUST carry `Content-Security-Policy: frame-ancestors` with
449
+ exactly the declared sources, and no `X-Frame-Options`. Every frame up to
450
+ the top must match one, so a host whose view runs in an opaque sandbox
451
+ frames embed pages from its own document, not from inside that view.
452
+
453
+ The SDK's view of an embed page (`ui://<app>/pages/<page>`) does steps 2 and 4
454
+ over the MCP Apps bridge, with its own `location.origin`; a host that draws
455
+ natively does them itself. A page on another site (`https://…`) is framed as
456
+ it is, with no ticket.
457
+
458
+ ### 5.2 Navigation, page actions and badges
459
+
460
+ 1. **Navigation.** `nav` is a list of sections `{ section?, pages }`, in
461
+ order: `section` a label (absent: ungrouped), `pages` one or more page
462
+ names. Every page named exists, is not a `record` page, and appears at most
463
+ once over all sections. Without `nav` a host shows every non-record page,
464
+ ungrouped, in declaration order. With `nav`, a page not named is not in the
465
+ navigation, and is still reachable (links, page actions, record pages).
466
+ 2. **Page actions.** A page's `actions` names up to 8 *global* actions (no
467
+ `entity`), in order; the first is the page's **primary**. A `record` page
468
+ has none (its record's actions are there). The page's params prefill the
469
+ action's inputs of the same name. A host draws the primary prominently and
470
+ the others in a menu; each opens the action's form drawn from its `input`
471
+ (§4), prefilled, and a read's form shows its result. A write goes through
472
+ the confirmation (§7).
473
+ 3. **Badge.** A page's `badge` names a fragment type with `template: "stat"`
474
+ whose params have no required key (not on a `record` page). The page's
475
+ count in the navigation is the fragment's `data.value` (a number), called
476
+ as the viewer with params `{}`. A badge the viewer can't show is not drawn.
477
+ 4. **In the view.** A page's result carries what the generated view needs to
478
+ draw the same thing in any MCP Apps host: `structuredContent.view.actions`
479
+ (`[{ tool, title, confirm, input, prefill? }]`, only the actions this caller
480
+ may use) and `view.nav` (`[{ section?, pages: [{ name, title, tool, badge? }]
481
+ }]`, `badge` the stat fragment's tool, only the pages this caller may open).
482
+
483
+ **Host guidance** (non-normative; nothing in the manifest): Clegra derives a
484
+ list page's filters from the fields' meaning: an `enum` field with `filter` is
485
+ a choice, the first date field with `filter` (`format: date` or `date-time`)
486
+ a period sent as `{ gte, lte }` (a date-time as the bounds of the days in the
487
+ workspace's time zone). A list page whose entity has a record page is drawn
488
+ with the record beside the list.
489
+
490
+ ## 6. The generated MCP server
491
+
492
+ Streamable HTTP at `mcp.url`. Tools, in this order of derivation:
493
+
494
+ | Tool | From | Kind |
495
+ |---|---|---|
496
+ | `<entity>_list`, `<entity>_get` | each entity (filters, `query`, `sort`, `dir`, `cursor`, `limit` ≤ 100, default 25) | read |
497
+ | `search`, `fetch` | entities with a `search` field; `search` takes an optional `kind` (an enum of the searchable entities' kinds) and each result carries `kind` when its entity has one; `fetch` carries it in `metadata` | read |
498
+ | `clegra_resolve` | always: `{ uris, want? }` → each URI's state `ok \| gone \| no-access \| not_found` and data, for hosts; hidden from models. `not_found`: a URI that is not this app's (a host MUST send an app only its own URIs); `gone`: this app's record or type that doesn't exist | read |
499
+ | `<entity>_<action>` or `<action>` | each action | read or write |
500
+ | `open_<page>` | each page except `record` pages (those are `<entity>_get`) | read |
501
+ | `show_<fragment>` | each non-record fragment | read |
502
+ | `clegra_later` | an action with `later` (§4.2) | write; only for the installation (§10) |
503
+ | `clegra_installation`, `clegra_export`, `clegra_delete` | `lifecycle` (§13) | write, read, write; only for the installation (§10) |
504
+
505
+ Rules:
506
+
507
+ 1. Names match `[a-zA-Z0-9_.-]{1,64}`, are unique, and MAY be renamed by the developer; the manifest carries the actual names.
508
+ 2. Names, titles and descriptions are in the app's `locale` and identical for every caller and every call. Data labels follow the caller's locale.
509
+ 3. Reads carry `readOnlyHint: true`. Writes carry `readOnlyHint: false` and `destructiveHint: true` exactly when `confirm` is `always`.
510
+ 4. A write is listed to plain MCP clients only when the developer opted in (`plain: true`). An entity, page or fragment MAY be hidden from them (`plain: false`).
511
+ 5. A tool the caller lacks the permission for is not listed.
512
+ 6. Tools with a view name it in `_meta.ui.resourceUri`; the data to draw is the result's `structuredContent`. Every tool a view calls (lists, records, actions, pages) carries `_meta.ui.visibility` with `"app"` (ChatGPT also reads `openai/widgetAccessible: true`); a host refuses a view's call to any other tool.
513
+ 7. Hand-written tools, resources and views MAY be added to the same server; they are outside the manifest.
514
+ 8. Entity tools (`<entity>_list`, `<entity>_get`) carry `_meta.clegra: { entity, kind? }`, `kind` as in the manifest. With a kind, their description ends with one fixed sentence: `Kind: person.`; with `{ by, map }`, the kinds in the map's order and the field: `Kind: organization or person (by type).`
515
+ 9. A list filter on a field with `as` names the property in its description (`Company (worksFor): …`); a key filter says it is exact (`Email: exact email; a value or { in: [...] }`) and carries `format` where JSON Schema has one (`email`).
516
+ 10. **Records are named by their title.** In the text a model reads, every record of a list, a get, `search` and `fetch` carries its `title` beside its `uri` (an outsider's title wrapped, §7). A tool of an action on a record takes `id` (required) and `record_title` (optional string, at most 300 characters): the record's title as the model read it, so a client that writes its own approval prompt from the arguments can name the record the person approves. Both descriptions tell the model to name the record by its title, never by its id. `record_title` is a display hint and never trusted: the app names the record from `id` in everything it shows or confirms, never passes the hint to the handler, and refuses the call with `invalid_input` (`fields.record_title`) when the hint names another record (compared without the untrusted wrapper, case, width, quotes and extra spaces). `record_title` is reserved: an action's `input` can't declare it.
517
+ 11. **App-only items.** An entity, action or fragment with `visibility: "app"` is for views and the host's own UI, never for a model. Its tools (the entity's list and get, the action's, the fragment's show tool) carry `_meta.ui.visibility: ["app"]` (no `"model"`), `openai/visibility: "private"` and `openai/widgetAccessible: true`. `search` and `fetch` leave its records out (`fetch` answers `not_found`), and no agent of the app may use it (a definition error). A host MUST NOT give such a tool to any model, its own agents included; views and the host's UI still call it. App-only is not access control: a client that ignores `_meta.ui.visibility` lists the tool like any other, so what a client must not call stays behind a permission or `plain: false`.
518
+ 12. **The installation's tools** (`clegra_later`, `clegra_installation`, `clegra_export`, `clegra_delete`) carry the same app-only `_meta` and are listed only to the installation-level caller (§10): never to a plain client, never to a person.
519
+
520
+ ### 6.1 What plain MCP clients see
521
+
522
+ ChatGPT, Claude and any MCP client use the app as a plain MCP server. Of each
523
+ feature they see:
524
+
525
+ | Feature | A plain MCP client |
526
+ |---|---|
527
+ | Navigation, page actions, badges (§5.2) | The `open_<page>` tools as before. The generated view (MCP Apps hosts, ChatGPT included) draws the navigation, the badges and the page actions from the page's `view`, each action opening its form |
528
+ | `visibility: "app"` (§6 rule 11) | The tools are listed with `_meta.ui.visibility: ["app"]`: a host that follows MCP Apps keeps them from its model and lets views call them; `search` and `fetch` never return their records |
529
+ | Targets (§4.1) | Nothing: the action is its own tool, as without targets |
530
+ | `later` (§4.2) | An `always` write (elicitation, or the client's own approval guided by `destructiveHint`) answered «Scheduled for …»; it runs from the app's own cron (`app.runLater`) |
531
+ | Schedules (§11) | The scheduled action's tool, as any action. A call naming a schedule is refused |
532
+ | Notifications (§12) | Nothing: `_meta.clegra.notifications` is ignored |
533
+ | Lifecycle (§13), `clegra_later` | Nothing: the tools are never listed to them |
534
+
535
+ ## 7. Enforcement
536
+
537
+ All of it happens in the server, on every surface (tools, `search`, `fetch`,
538
+ the resolver, dashboards, views), before any handler runs.
539
+
540
+ **Authorization is MCP's.** OAuth bearer tokens, protected-resource metadata
541
+ (RFC 9728), a `401` with `WWW-Authenticate: Bearer resource_metadata=…`.
542
+ There is no second sign-in. An app accepts two kinds of token:
543
+
544
+ 1. **Its own** (a web app with its own users): issued by the app's own
545
+ authorization server to an MCP client (ChatGPT, Claude, Clegra connect the
546
+ same way, as OAuth clients; each person links their account of the app
547
+ once). The app verifies them itself and names the caller (below, «The
548
+ app's own tokens»). No `clegra` claim is involved.
549
+ 2. **A workspace host's** (in-house apps a company installs into its own
550
+ host): the trusted-issuer mode, with the `clegra` claim. The rest of this
551
+ list is about these.
552
+
553
+ - A workspace host's token is a JWT with `typ: at+jwt`, `exp` and `sub`, from an issuer the
554
+ app trusts, with one claim, `clegra: { installation, person?,
555
+ permissions?, locale?, host?: "workspace" | "plain" }`. `installation`
556
+ matches `[A-Za-z0-9._:-]{1,128}`.
557
+ - **Audience** (RFC 8707): `aud` MUST be the app's own public MCP address,
558
+ `auth.resource`. An app never accepts its name, or another address, as an
559
+ audience. A host signs `aud` = the MCP address it installed the app from,
560
+ never a value read from the manifest, and MUST refuse to install an app
561
+ whose `auth.resource` is not that address (an app on an internal address is
562
+ configured with that same address, or it is not installed). So a token
563
+ signed for one app is useless at any other, whatever the other claims.
564
+ - **Tenant**: the installation is bound to its issuer. Handlers receive
565
+ `<installation>@<issuer>` and MUST scope every read and write by it; two
566
+ issuers can't reach each other's data by naming the same installation.
567
+ - **A workspace host's token** (`host: "workspace"`) is for one request: it
568
+ MUST carry `jti` and `iat`, live 60 seconds at most, and is accepted once.
569
+ - A call without a `person` has the permissions its token lists, like any
570
+ other: none unless the token says so. A workspace host's call for the
571
+ installation itself is defined in §10.
572
+
573
+ **The app's own tokens.** The app verifies each one (signature, expiry, and
574
+ `aud` = `auth.resource`, RFC 8707: a token issued for another resource is
575
+ refused) and maps it to a caller: `{ installation, person, permissions,
576
+ locale? }`. The SDK hook is `auth.resolve(token, request, { resource })`; it
577
+ returns null for a token that is not the app's (a `401` follows) or throws
578
+ with the reason.
579
+
580
+ - `installation` is the app's own tenant (an organization, a workspace, an
581
+ account), taken from the verified token or the session behind it, never
582
+ from a request parameter. It matches `[A-Za-z0-9._:-]{1,128}`: no `@`, so it
583
+ can never equal a workspace host's `<installation>@<issuer>`.
584
+ - `permissions` come from the app's own roles; ids the manifest does not
585
+ declare are dropped. The caller is a plain host (`host: "plain"`).
586
+ - A token that is a JWT from a configured issuer (or the development
587
+ authority) is never handed to `auth.resolve`.
588
+ - The protected-resource metadata names the app's authorization server
589
+ (`auth.authorizationServers`). Paths the authorization server needs outside
590
+ its own mount (RFC 8414 metadata under `/.well-known/`) MAY be answered by
591
+ the same routes (`auth.serve`).
592
+ - In production `auth.resource` is required with `resolve` or `issuers`:
593
+ without it every request fails with a clear `500 misconfigured`, never with
594
+ an address guessed from request headers.
595
+
596
+ **Clegra and third-party apps.** Clegra connects to an app it does not host
597
+ exactly as ChatGPT does: as an OAuth client with a Client ID Metadata
598
+ Document, the person signs in to the app and consents once, and Clegra keeps
599
+ the refresh token on the person's behalf. It then also reads the manifest to
600
+ draw the app natively. Confirmations to such an app follow MCP (annotations
601
+ and elicitation, below); a workspace host's proof applies only to tokens of
602
+ the trusted-issuer mode.
603
+
604
+ **Permissions and visibility**
605
+
606
+ - Entity, action, page, fragment and field permissions are checked on every call.
607
+ - A field the caller may not see is absent from rows, records, cards, filters
608
+ and sorts, and text search looks only in the search fields the caller may
609
+ see (handlers receive them as `textFields`).
610
+ - What is hidden from plain clients (`plain: false`) is hidden from them
611
+ everywhere: its tools are not listed, and `fetch`, the resolver, reference
612
+ titles, dashboards and record actions answer `no-access` for it.
613
+
614
+ **Confirmation** of a write whose `confirm` is `always`:
615
+
616
+ - a workspace host shows the person the exact values, then sends a proof: a
617
+ JWT (`typ: clegra-confirm+jwt`, 5 minutes at most) signed by the token's
618
+ issuer for the same audience and subject, with `installation`, `tool`,
619
+ `call` (the call id) and `args`: the base64url SHA-256 of the canonical
620
+ JSON (keys sorted at every depth) of the arguments **as sent**, before any
621
+ parsing or default; for an action with `later`, also `until` (§4.2).
622
+ Without a valid proof the call fails with `confirmation_required` and
623
+ `error.confirm` describes what to show (`{ tool, title, record?, input,
624
+ later? }`);
625
+ - a plain client that supports MCP elicitation is asked to confirm, with the
626
+ values as a person reads them (labels, titles of referenced records);
627
+ - a plain client that can't elicit: the client's own approval applies, guided
628
+ by the tool's annotations (`destructiveHint`); the server runs the call.
629
+
630
+ What a person confirms names the record by the title the app reads from `id`
631
+ (`error.confirm.record`, the elicitation's text), never by the model's
632
+ `record_title`, and a host MUST NOT show that hint as the app's. A client's own
633
+ approval prompt is written from the arguments: there the hint is the only
634
+ title, and a hint that names another record stops the call (§6 rule 10), so
635
+ the person can't approve one record and change another.
636
+
637
+ **Decision (1.0): confirmations follow MCP.** A host that confirms on its own
638
+ (ChatGPT, Claude) decides from the annotations; a client that supports
639
+ elicitation is asked through it; a workspace host proves the person's
640
+ confirmation. An app's views add no confirmation of their own: a second
641
+ dialog inside a view would ask twice in hosts that already ask, and would be
642
+ the only safeguard nowhere. A developer who wants a write never to run
643
+ without a confirmation the app can verify keeps it off plain clients, which
644
+ is the default.
645
+
646
+ **Idempotency**: a write with a call id runs once per caller, installation
647
+ and tool, also when the same call arrives twice at the same moment. A repeat
648
+ returns the first result; the same id with other arguments (as sent) fails
649
+ with `conflict`; a repeat while the first still runs fails with `conflict`
650
+ and `error.pending: true`.
651
+
652
+ **Host metadata**: one key, `_meta.clegra`.
653
+
654
+ - Requests MAY carry `{ call, confirmation, settings, schedule }`. `settings`
655
+ are the installation's values (§2) and count only from a workspace host;
656
+ any other caller gets the defaults. `schedule` names the schedule this call
657
+ is a run of (§11); it counts only from the installation-level caller (§10),
658
+ and any other call carrying it is refused.
659
+ - Results MAY carry `{ notifications, untrusted, l10n }`:
660
+ - `notifications`: `[{ type?, title, body?, uri?, to }]` (§12). `to` is
661
+ either the ids of people (as the token named them; default the caller's
662
+ person) or `{ permission }`: everyone of the installation who holds that
663
+ declared permission. A workspace host delivers them; a plain client
664
+ ignores them.
665
+ - `untrusted`: JSON pointers into `structuredContent` to every value that
666
+ is outsiders' text. In the result's text those values are wrapped in
667
+ `<untrusted>…</untrusted>` with `&`, `<`, `>` (and their full-width and
668
+ small forms) escaped as XML text, so nothing inside is a tag. A host that
669
+ gives a model `structuredContent` wraps the pointed values the same way.
670
+ - `l10n`: `{ <locale>: { <label as shown>: <the same label in that locale> } }`
671
+ for the app's labels the result shows (titles, columns, enum values,
672
+ actions, inputs, the handler's own `t` texts). A view draws them in the
673
+ reader's language (MCP Apps `hostContext.locale`, ChatGPT's
674
+ `window.openai.locale`), else English, else as shown. For views only: a
675
+ model never reads `_meta`.
676
+
677
+ **Errors**: `isError: true` and `structuredContent.error = { code, message }`,
678
+ `code` one of `unauthorized`, `permission_denied`, `not_found`,
679
+ `invalid_input`, `confirmation_required`, `conflict`, `internal`.
680
+ An action's `invalid_input` also carries `fields`: `{ <input key>: <what is
681
+ wrong> }`, in the caller's locale where the server has it; `message` names
682
+ the fields by their labels. It is a tool error, never a protocol error, so a
683
+ view and a model can both read it.
684
+
685
+ **Development sign-in** (SDK): off unless enabled, refused in production,
686
+ answered only to callers on a loopback address (checked on every request);
687
+ the sign-in code allows five wrong attempts.
688
+
689
+ ### Client registration (development sign-in)
690
+
691
+ The development authorization server knows a client in two ways:
692
+
693
+ - **A Client ID Metadata Document** (what current MCP clients use, MCP
694
+ authorization 2025-11-25): the `client_id` is the https URL of a JSON
695
+ document that describes the client. The server metadata says
696
+ `client_id_metadata_document_supported: true`.
697
+ - **Dynamic Client Registration** (RFC 7591) at `registration_endpoint`, kept
698
+ for clients that don't send a metadata document yet. Any client is
699
+ registered; its redirect addresses are not checked.
700
+
701
+ For a URL `client_id`:
702
+
703
+ - The URL is https, has a path, and has no fragment, user name, password or
704
+ `.`/`..` segment. A query is accepted.
705
+ - The document is a JSON object whose `client_id` is that URL, the same
706
+ string, with a non-empty `redirect_uris`. `client_name` is shown on the
707
+ sign-in page. There is never a `client_secret`; `token_endpoint_auth_method`
708
+ is `none` or absent (a public client) or `private_key_jwt` (RFC 7523, as the
709
+ MCP authorization spec allows for metadata-document clients). Client secrets
710
+ are refused.
711
+ - A `private_key_jwt` client names its keys with exactly one of `jwks_uri`
712
+ (fetched with the same protections as the document, kept 5 minutes; an
713
+ unknown `kid` fetches it again, at most every 10 seconds) or inline `jwks`
714
+ (public keys only), and may name `token_endpoint_auth_signing_alg`: `RS256`
715
+ (default), `ES256` or `PS256`; never `none` or HMAC. At the token endpoint,
716
+ on both grants, it MUST send `client_assertion_type`
717
+ `urn:ietf:params:oauth:client-assertion-type:jwt-bearer` and a
718
+ `client_assertion` signed with that algorithm, with `iss` = `sub` = its
719
+ `client_id`, `aud` the token endpoint or the issuer, `exp` at most 5 minutes
720
+ ahead (30 seconds of clock skew), and a `jti` used once. Otherwise the answer
721
+ is `401 invalid_client`. The metadata lists
722
+ `token_endpoint_auth_methods_supported: ["none", "private_key_jwt"]` and
723
+ `token_endpoint_auth_signing_alg_values_supported`.
724
+ - `redirect_uri` MUST be one of `redirect_uris`, exactly. One exception
725
+ (RFC 8252): for `http://127.0.0.1`, `http://localhost` and `http://[::1]`
726
+ the port may differ. A request that fails any of these gets an error page;
727
+ it is never redirected.
728
+ - At the token endpoint `client_id` is required and MUST be the one the code
729
+ was issued to.
730
+ - Fetching the document: nothing is requested unless the host is public. IP
731
+ literals and names that are loopback, private, link-local, carrier-grade
732
+ NAT, unique-local, multicast or unspecified are refused (also as
733
+ IPv4-mapped IPv6, and `localhost`, `*.localhost`, `*.local`, `*.internal`),
734
+ and so is a name when any address it resolves to is one of those. Redirects
735
+ are not followed. The answer must be `200`, JSON, at most 64 KB, within 5
736
+ seconds. It is kept as `Cache-Control` says (`max-age` between a minute and
737
+ a day, five minutes by default, not at all with `no-store`); a failure is
738
+ kept 30 seconds.
739
+ - A known limit: the addresses are checked, then the request resolves the
740
+ name again, so DNS rebinding is not excluded. The connection is not pinned
741
+ to the checked address. This is a development server; a production one
742
+ should pin it.
743
+
744
+ ### Production: an app with its own authorization server
745
+
746
+ The SDK is not an authorization server outside development, and ships none:
747
+ an app uses an existing one (better-auth's MCP plugin, Clerk, WorkOS, Auth0, …)
748
+ and verifies its tokens in `auth.resolve` (recipes, non-normative: [auth.md](auth.md)). For MCP clients
749
+ (ChatGPT, Claude, others) to connect to an app that signs people in itself,
750
+ its authorization server needs:
751
+
752
+ - OAuth 2.1 authorization code with PKCE `S256`.
753
+ - Metadata (RFC 8414, or OpenID Connect discovery) with
754
+ `code_challenge_methods_supported`. Clients refuse a server that does not
755
+ list it.
756
+ - Protected-resource metadata (RFC 9728). The SDK serves it;
757
+ `auth.authorizationServers` names the authorization server (default: the
758
+ issuers of `auth.issuers`).
759
+ - The `resource` parameter (RFC 8707): the token's `aud` MUST be the app's
760
+ `auth.resource`.
761
+ - Client registration, in this order of preference:
762
+ 1. Client ID Metadata Documents: `client_id_metadata_document_supported:
763
+ true`, the document fetched with the protections above (and the
764
+ connection pinned), `redirect_uri` matched exactly, no secrets;
765
+ `private_key_jwt` for clients that sign with a key pair (ChatGPT does).
766
+ 2. Dynamic Client Registration (RFC 7591), optional, for clients that
767
+ don't send a metadata document yet.
768
+ 3. Clients registered by hand, where the server can do neither.
769
+ - Tokens the app can verify, in `auth.resolve` (any format the app's
770
+ authorization server issues, audience-bound to `auth.resource`).
771
+ - State shared by every instance: on serverless or several instances, the
772
+ store of write results and one-time token ids (§7, idempotency) is shared
773
+ (`SqlStore` in the app's Postgres, or another atomic store), never memory.
774
+ - No key files: keys and secrets come from the environment.
775
+
776
+ A workspace host's token, in the trusted-issuer mode, is a signed JWT whose
777
+ header has `typ: at+jwt`, with `iss` exactly one of `auth.issuers`, `aud` =
778
+ `auth.resource`, `exp`, `sub`, and the `clegra` claim with a valid
779
+ `installation` (above). The signature is checked against the issuer's key
780
+ set: `<issuer>/.well-known/jwks.json`, or the issuer's `jwksUri`. Clocks may
781
+ differ by 30 seconds. Opaque tokens are not accepted in this mode.
782
+
783
+ ## 8. Conformance
784
+
785
+ [`spec`](../spec) checks any app from outside,
786
+ over HTTP, whatever it is built with:
787
+
788
+ ```sh
789
+ npx @clegra/sdk check https://crm.example.com --token <a plain caller's bearer>
790
+ ```
791
+
792
+ | Check | Passes when |
793
+ |---|---|
794
+ | `manifest.served` | `GET /.well-known/clegra.json` answers 200 with JSON |
795
+ | `manifest.schema` | the manifest validates against the JSON Schema |
796
+ | `manifest.references` | names refer to things the manifest declares; tool names are unique and valid, none reserved; the publisher is well-formed (§2); navigation, page actions, badges, app-only items, targets, `later`, schedules and notification types meet their rules (§4.1, §4.2, §5.2, §6 rule 11, §11, §12) |
797
+ | `auth.mcp` | without a token the endpoint answers 401 and points to protected-resource metadata, whose `resource` is the address the app was reached at (or the manifest's `auth.resource`) |
798
+ | `mcp.initialize` | `initialize` succeeds with no extension |
799
+ | `mcp.tools` | tools match the manifest: names, `readOnlyHint`, `destructiveHint`; nothing hidden is listed |
800
+ | `mcp.deterministic` | `tools/list` is the same on every call |
801
+ | `mcp.sort` | a list tool offers to sort only by fields the manifest declares sortable, and refuses any other key |
802
+ | `mcp.views` | every view a tool names is served as an MCP Apps document |
803
+ | `mcp.titles` | each row of a list's text carries its `uri` and `title`, and the record's text from its get tool the same title; every action tool on a record takes a required string `id` and an optional string `record_title` |
804
+ | `mcp.app-callable` | the tools a view calls (lists, records, actions, pages) don't leave `"app"` out of `_meta.ui.visibility` |
805
+ | `mcp.visibility` | the tools of app-only entities, actions and fragments carry `_meta.ui.visibility: ["app"]`, without `"model"`; `search` finds no record of an app-only entity |
806
+ | `lifecycle.hidden` | `clegra_later`, `clegra_installation`, `clegra_export` and `clegra_delete` are not listed to a plain caller |
807
+ | `mcp.manifest` | the manifest is one MCP resource, identical to the file |
808
+ | `kinds.known` | every unprefixed kind is in `kinds.json` for the `specVersion`; every dotted kind is well-formed |
809
+ | `kinds.properties` | every `as` belongs to the entity's kind (or is universal) with a matching type; single-valued properties appear once; required ones exist; keys are filters; `kinds` definitions are well-formed |
810
+ | `kinds.keys` | listing with a key value taken from a returned record, in another letter case where case doesn't count, returns that record and only records holding that value |
811
+ | `kinds.values` | sampled records: `email`, `vatID`, `gtin`, dates, `address` and numbers have the stated form |
812
+ | `kinds.tools` | entity tools carry the kind in the description and in `_meta.clegra`; `search` offers `kind`, keeps to it, and names each result's kind |
813
+ | `refs.cross` | a `ref: { kind }` field's values are record URIs; its text form is `{ uri, kind }`; no `refs` title is sent for it; such an action input is a string |
814
+ | `resolve.foreign` | the resolver answers `not_found` for another app's URI |
815
+ | `embed.frame-ancestors` | (public) an app with same-site pages declares `embed`; each embed page and `GET <path>/_ticket` (refused) answer with `frame-ancestors` exactly the declared sources, no `X-Frame-Options` |
816
+ | `embed.ticket` | a ticket for a declared origin is a ≤ 60 s JWT for the page with a `jti`; an undeclared origin gets none; posted from another `Origin`, a second time, or by a top-level page it is refused; posted right it answers 303 to the page with `Referrer-Policy: no-referrer` and a `Secure; HttpOnly; SameSite=None; Partitioned` cookie scoped to the page's path |
817
+
818
+ The `kinds.*` checks are skipped, not failed, for an app that declares no
819
+ kinds (and `kinds.keys` when no listed record holds a key value to try);
820
+ `refs.cross` for an app without references to other apps; the `embed.*`
821
+ checks for an app without same-site pages; `mcp.visibility` for an app
822
+ without app-only items; `lifecycle.hidden` for an app without lifecycle tools
823
+ or later runs.
824
+
825
+ An app is conformant when every check passes with a token. Without a token
826
+ only the public checks run: the report says «Incomplete», never «Conformant».
827
+
828
+ ## 9. Workspace hosts: across apps
829
+
830
+ What a workspace host does when it draws several apps together. None of it
831
+ needs anything from an app beyond §2–§7.
832
+
833
+ 1. **Names.** An app is the connection an administrator installed (its
834
+ address, public or local); there is no global app id. A host MUST NOT hold
835
+ two apps with the same `name` in one workspace: when an app's `name` is
836
+ taken, the administrator gives it another name there at install time, and
837
+ the host uses that name in the workspace's record URIs and translates them
838
+ to and from the app's own `name` in every call. Record URIs are therefore
839
+ scoped to the workspace and resolved by its host. The name is kept for the
840
+ installation's life (other apps store URIs that carry it). When another app
841
+ of the workspace is named as a renamed app's own `name`, the host MUST NOT
842
+ send the renamed app a URI of that other app (it would read as its own):
843
+ it refuses the call instead. (A public directory of
844
+ apps may give them globally unique, publisher-verified names; that is a
845
+ listing, outside this specification.)
846
+ 2. **Caller.** Every call a host makes to list, search, match or resolve
847
+ across apps MUST be made for the viewer, with the viewer's token for that
848
+ app. A host MUST NOT show a person data obtained with another caller's
849
+ token, and MUST NOT keep a copy of records beyond the response it is drawing.
850
+ 3. **Resolving.** For a cross-app reference the host calls the owning app's
851
+ resolver and shows the title, or one of `no-access`, `not-linked` (the app
852
+ signs people in itself and the viewer has not linked their account: the
853
+ host offers to link it), `gone`, `unreachable` (a timeout or an error),
854
+ `unknown-app` (no app of that name in the workspace), each distinguishable
855
+ to the person. It MUST NOT show a title
856
+ from an earlier response in place of a failed one.
857
+ 4. **Fan-out.** A federated list calls every source in parallel with a time
858
+ limit per source. The result MUST name every source with its state (`ok`,
859
+ `timeout`, `error`, `no-access`, `not-linked`) and MUST be marked partial
860
+ unless all are `ok`. A total is shown only when every source gave one. A
861
+ host MUST NOT substitute other data for a failed source.
862
+ 5. **Order.** A merged order across sources is allowed only by a property
863
+ every included source declares sortable; otherwise results are grouped by
864
+ source in each source's own order.
865
+ 6. **Matching.** Two records are *matched* only when they have the same kind
866
+ and an equal normalised key (§3.1 rule 5), found by the key's exact filter.
867
+ A host MUST NOT match on names or any non-key value, MUST NOT store matches,
868
+ MUST NOT present matched records as one record, and MUST show each one's
869
+ source.
870
+ 7. **Links.** A host MAY store a person's statement that two records are, or
871
+ are not, the same thing: the two URIs, who, when — no field values. A link
872
+ belongs to the workspace (anyone may benefit from it) and is shown only to a
873
+ viewer for whom both URIs resolve `ok`.
874
+ 8. **Models.** What a host gives a model from these calls keeps `untrusted`
875
+ marks (§7) and names the source of every record.
876
+
877
+ ## 10. The installation-level caller
878
+
879
+ Some calls are made by a workspace host for the installation itself, with
880
+ nobody at the screen: schedules (§11), later runs (§4.2) and the lifecycle
881
+ (§13). The **installation-level caller** is exactly:
882
+
883
+ 1. **The token.** A workspace host's token in the trusted-issuer mode (§7:
884
+ `host: "workspace"`, one request, `jti`), whose `clegra` claim has **no
885
+ `person`**, with `sub` = `installation:<installation>` and `permissions` =
886
+ exactly the permission the called action declares (an empty list when it
887
+ declares none, and for the reserved tools; never more).
888
+ 2. **What it may call.** (a) A schedule's tool, with `_meta.clegra.schedule`
889
+ = that schedule's name; (b) `clegra_later`; (c) the lifecycle tools. The
890
+ app refuses with `permission_denied` a `schedule` that names no schedule of
891
+ the app, names a schedule of another tool, or comes from any other caller
892
+ (a person, a plain client). A person-less workspace call to any other tool
893
+ is not refused for being one: it has the permissions its token lists, as
894
+ §7 says (a host uses that for its administrators' checks).
895
+ 3. **No confirmation.** None is ever shown or proven: a scheduled action is
896
+ never `confirm: "always"` (§11), an `optional` write runs, and a later run
897
+ carries the proof made when the person confirmed it.
898
+ 4. **What handlers see.** `ctx.person` is null (in a later run: the run's
899
+ author), `ctx.schedule` the schedule's name (`clegra_later` in a later
900
+ run; null in any other call), `ctx.permissions` as the token lists them,
901
+ `ctx.settings` as the host sent them.
902
+ 5. **Results.** Notifications in its results are delivered by the host as
903
+ any (§12); each says `to`, since there is no person to default to.
904
+
905
+ Only a workspace host in the trusted-issuer mode can be this caller. An app
906
+ that signs its callers in itself (its own tokens, §7) is never called as the
907
+ installation: a host that connects to it as an OAuth client runs no
908
+ schedules and no lifecycle tools there, and the app runs its own cron.
909
+
910
+ ## 11. Schedules
911
+
912
+ `schedules` lists `{ name, action?, tool, every, maxSeconds }`: actions the
913
+ workspace host runs as the installation (§10).
914
+
915
+ 1. `name` is an identifier; at most 10 schedules besides the SDK's own
916
+ `clegra_later` (§4.2), which has no `action`, `tool: "clegra_later"` and
917
+ `every: 5`.
918
+ 2. `action` is a global action whose input accepts `{}` (no required
919
+ property), and `tool` is its tool. The action is a read, or a write whose
920
+ `confirm` is `never` or `optional`. A write with `confirm: "always"` is
921
+ never scheduled: nobody is there to confirm it. The only way to run a
922
+ confirmed write afterwards is `later` (§4.2).
923
+ 3. `every` is whole minutes, 5–1440; `maxSeconds` whole seconds, 1–300 (the
924
+ SDK's default is 60).
925
+ 4. A run is `tools/call` of `tool` with `{}` and `_meta.clegra.schedule` =
926
+ `name`, by the installation-level caller (§10), with the installation's
927
+ `settings`.
928
+
929
+ A host runs a schedule at most once every `every` minutes per installation
930
+ (claimed in its own database, so two of its processes never run it twice),
931
+ within `maxSeconds`, and only while the installation is enabled. It keeps a
932
+ log of the runs (ok or failed, with the message).
933
+
934
+ ## 12. Notifications
935
+
936
+ A result's `_meta.clegra.notifications` (§7) asks the workspace host to tell
937
+ people of the installation something: `{ type?, title, body?, uri?, to }`,
938
+ `title` and `body` in the caller's language, `uri` a record of the app.
939
+
940
+ 1. **Types.** `notifications` in the manifest lists the types an app sends:
941
+ `{ type, label, description?, default, permission? }`. People turn a type
942
+ off (or on) per app. `default: false` keeps it off for a person until they
943
+ turn it on. With `permission` (a declared one) only its holders receive it,
944
+ checked by the host on top of `to`.
945
+ 2. **Typed or untyped.** An app that declares types names one of them in
946
+ every notification it sends (the SDK refuses any other: a programming
947
+ error). An app that declares none sends untyped notifications, which the
948
+ host files under one type of its own per app. The SDK's `clegra_later`
949
+ (§4.2) does not count as a declared type: it never makes the app's other
950
+ notifications typed.
951
+ 3. **Recipients.** `to` is a list of person ids, or `{ permission }`: everyone
952
+ of the installation who holds that declared permission. Without `to` the
953
+ SDK sends the caller's person; a call without a person (§10) MUST say `to`.
954
+ 4. **Reserved.** `clegra_later` is the SDK's type for later runs that did not
955
+ run (`default: true`); an app declares it only through `later`.
956
+
957
+ ## 13. The app lifecycle
958
+
959
+ An app MAY be told of its installation's changes and give or delete the
960
+ tenant's data, through three reserved app-only tools that it names in
961
+ `lifecycle` (`{ installation?: "clegra_installation", export?: "clegra_export",
962
+ delete?: "clegra_delete" }`, each optional). Only the installation-level
963
+ caller (§10) is given them (§6 rule 12).
964
+
965
+ - **`clegra_installation`** `{ state: "enabled" | "disabled" | "uninstalled" }`
966
+ → `{ ok: true }`. The host calls it after an administrator enables,
967
+ disables or uninstalls the app. A failure never blocks the administrator's
968
+ change; the host shows it.
969
+ - **`clegra_export`** `{}` → the tenant's data as one file:
970
+ `structuredContent` `{ name, contentType, bytes, sha256 }` (`sha256` the
971
+ lowercase hex SHA-256 of the file's bytes; `name` matches
972
+ `[A-Za-z0-9][A-Za-z0-9._-]{0,127}`), and among its `content` one MCP
973
+ embedded resource `{ type: "resource", resource: { uri:
974
+ "clegra://<app>/export/<name>", mimeType, blob } }` holding the file
975
+ (base64). `{ empty: true }` when the app keeps nothing for the tenant. At
976
+ most 512 MiB; a host refuses more, and a file whose size or hash doesn't
977
+ match.
978
+ - **`clegra_delete`** `{}` → `{ deleted: true, counts? }` (`counts`: what was
979
+ deleted, by name; the SDK adds `later_runs`): everything the app keeps for
980
+ the tenant, its later runs included. Idempotent: asking again is never an
981
+ error and answers `deleted: true` again (`counts` then say what that call
982
+ deleted).
983
+
984
+ `clegra_export` and `clegra_delete` MUST keep working after `uninstalled`:
985
+ that is when they are needed.
986
+
987
+ **Host guidance** (non-normative). On uninstall Clegra asks the administrator
988
+ to choose: «Export, then delete in 30 days» (the export is made now and kept
989
+ 30 days for download; `clegra_delete` is called after 30 days) or «Delete
990
+ now» (`clegra_delete` now, no export). Without `clegra_export` the choice
991
+ reads «Delete in 30 days» or «Delete now»; without `clegra_delete` the host
992
+ offers the export only, and says the data stay on the app's server. A failed
993
+ export stops the uninstall; a failed delete is retried, with backoff, and
994
+ shown to the administrators. An app without any of these tools is
995
+ uninstalled, enabled and disabled on the host alone, and the host tells the
996
+ administrator in so many words that the app is not told and its data stay on
997
+ its server.