@clegra/sdk 0.0.0-stage → 0.1.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +152 -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 +703 -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/CHANGELOG.md ADDED
@@ -0,0 +1,152 @@
1
+ # Changelog
2
+
3
+ Clegra apps (spec 1.0 draft) and the `@clegra/sdk` package. Newest first. Versions before 1.0 are prereleases on the
4
+ npm dist-tag `next`. Entries below «Two scoped packages» keep the names of their time (the unscoped `clegra` package
5
+ and its `clegra/ui`, the `modelapp` package, docs/map): they are history.
6
+
7
+ ## 0.1.0-next.0 (2026-11-17)
8
+
9
+ The first version published to npm (`npm i @clegra/sdk@next zod`).
10
+
11
+ ### Two scoped packages: `@clegra/sdk` and `@clegra/ui`
12
+
13
+ - npm refused the unscoped name, so the package is `@clegra/sdk` in the npm organisation `clegra`. Imports:
14
+ `@clegra/sdk`, `@clegra/sdk/next`, `@clegra/sdk/node`, `@clegra/sdk/testing`, `@clegra/sdk/spec`,
15
+ `@clegra/sdk/clegra.schema.json`, `@clegra/sdk/kinds.json`. The CLI is `npx @clegra/sdk init|check`; its bin is
16
+ still `clegra`. Wire names do not change (`clegra://`, `/.well-known/clegra.json`, `_meta.clegra`, `clegra_*`
17
+ tools, `CLEGRA_*` variables, `clegra.schema.json`, the cookies).
18
+ - The design library left this package: it is `@clegra/ui`, its own package and repository (history kept there),
19
+ with every component public. `@clegra/sdk` has no UI entry and no UI peer dependency (peers: `zod`, optional
20
+ `next`); the generated MCP Apps view is plain HTML. `init --ui` adds `@clegra/ui` (`^0.1.0-next.0`) and its web
21
+ libraries to the app and `@import "@clegra/ui/styles.css"` after Tailwind.
22
+ - `@clegra/sdk/spec/protocol` and `@clegra/sdk/spec/kinds`: the protocol's names and the kinds vocabulary (with
23
+ the key normalisation) for workspace hosts, which until now reached them only by a path into the source. Neither
24
+ imports a Node built-in.
25
+ - `publishConfig.access: public`. The pack check also installs both tarballs in one fresh Next.js app
26
+ (`init --ui`, build, `clegra check`).
27
+
28
+ ### The package in its own repository
29
+
30
+ - The package is its repository's root (published from there with `npm publish --tag next`); the examples
31
+ (`examples/crm`, `examples/warehouse`, `examples/shipments`) are npm workspaces beside it, the docs in `docs/`.
32
+ The tarball ships `docs/spec.md` and `docs/quickstart.md` too. History kept.
33
+ - `clegra/ui`'s palette lives in `ui/brand` (the same values as before).
34
+ - No `"private"` and no approved-tarball step: a prerelease is refused without a dist-tag (npm and `prepack`).
35
+ - `clegra/ui/native/expo-ui-controls` is an entry: `ExpoHost` (Expo UI's `Host` in the app's colour scheme) and the
36
+ layout helpers the native controls share.
37
+
38
+ ### The publisher (spec §2)
39
+
40
+ - Manifest `publisher?: { name, url }` (`defineApp({ publisher })`): who publishes the app, a name and an https
41
+ address. A claim that grants nothing; a store or host may verify it by the address's domain. Well-formedness is a
42
+ manifest rule (`manifest.references`); the JSON Schema has it.
43
+
44
+ ### Pages people use every day, work on a clock, and the app lifecycle (spec §4.1, §4.2, §5.2, §10–§13)
45
+
46
+ - Navigation and page actions: a top-level `nav` (sections of pages), a page's `actions` (global actions drawn as
47
+ forms, prefilled from the page's parameters; the first is the page's primary) and `badge` (a `stat` fragment whose
48
+ value is the count). The generated view draws them too. A host derives filters (enum and date fields) and the
49
+ list-beside-record layout itself.
50
+ - `visibility: "app"` on entities, actions and fragments: their tools are callable by views and the host's own UI,
51
+ never given to a model.
52
+ - Targets: an action offered on an email (`mail.message`) or on a record of a kind in any app (`record:<kind>`), with
53
+ the fields it needs and a template that fills its form.
54
+ - Approve now, act later: `later: { at, window }` on a confirmed write. The confirmation's proof also binds the
55
+ deadline (`until`); the run is stored through the store (`SqlStore` gains a `_later` table: re-run
56
+ `SqlStore.schema()` in a migration), runs once from the reserved `clegra_later` schedule, the person who approved
57
+ as its author, and is refused after its deadline or if its stored arguments no longer match the proof.
58
+ - The installation-level caller (a workspace host's token with no person and exactly the called action's permission),
59
+ `schedules` (a global action every 5–1440 minutes; never an `always` write), declared notification types and
60
+ `to: { permission }`.
61
+ - The app lifecycle: reserved app-only tools `clegra_installation`, `clegra_export` and `clegra_delete`, called by
62
+ a workspace host as the installation when it is enabled, disabled or uninstalled («export, then delete in 30 days»
63
+ or «delete now»).
64
+ - `clegra/testing`: `installationClient`, `.schedule()`, `.runLater()`, `.exportData()`; conformance checks
65
+ `mcp.visibility` and `lifecycle.hidden`; `manifest.references` covers the new rules.
66
+ ### `clegra/ui`: the design library in the package
67
+
68
+ - Clegra's design library is part of `clegra` (it was the separate, unpublished `@clegra/ui`): `clegra/ui/components/*`
69
+ (web and React Native, with the `react-native` and `ios` conditions), `clegra/ui/react/*`, `clegra/ui/react-native/*`,
70
+ `clegra/ui/frame`, `clegra/ui/tokens`, `clegra/ui/hooks/*`, `clegra/ui/primitives`, `clegra/ui/base-ui/*`,
71
+ `clegra/ui/native/{theme,overlay,icons,icon-context}`, `clegra/ui/metro`, and the stylesheets
72
+ `clegra/ui/styles.css` (Tailwind 4 entry; it sources its own components), `theme.css`, `shadcn.css`, `prebuilt.css`.
73
+ - Its UI libraries (React, Base UI, lucide, recharts, … and React Native's) are optional peer dependencies, never
74
+ bundled: an app that only serves MCP installs none of them. `npx clegra init --ui` adds the web ones to a Next.js
75
+ app and imports the stylesheet after Tailwind. Docs: [ui.md](ui.md). The package now ships `NOTICE.md`.
76
+
77
+ ### Renamed to Clegra apps and the `clegra` package
78
+
79
+ - Clegra apps are Clegra's own developer platform, not an open standard: the spec is «Clegra apps — specification»
80
+ (1.0 draft), and nothing in it asks other hosts to implement it. Every app is still a plain, conformant MCP server
81
+ (tools, MCP Apps views, OAuth) that ChatGPT, Claude and any MCP client use, plus a manifest Clegra draws natively.
82
+ - One npm package, `clegra` (was `modelapp`): `clegra`, `clegra/next`, `clegra/node`, `clegra/testing`,
83
+ `clegra/spec`; the CLI is `npx clegra init` and `npx clegra check <url>`.
84
+ - Wire names: manifest `/.well-known/clegra.json`; URIs `clegra://<app>/<entity>/<id>`; `_meta.clegra`, the
85
+ `clegra` token claim and OAuth scope; JWT `typ` `clegra-confirm+jwt`, `clegra-embed+jwt`,
86
+ `clegra-embed-session+jwt`; tools `clegra_resolve`, `clegra_embed`; cookie `__Secure-clegra-embed-<page>`; JSON
87
+ Schema `clegra.schema.json` (`urn:clegra:manifest:1.0`).
88
+ - Next.js: the mount is `app/api/clegra/[...path]` (`/api/clegra`); `withClegra`, `clegraRewrites`,
89
+ `WithClegraOptions`. The SDK's store table is `clegra_store`; environment variables are `CLEGRA_*`
90
+ (`CLEGRA_PUBLIC_URL`, `CLEGRA_ISSUERS`, `CLEGRA_EMBED_SECRET`, `CLEGRA_LOCAL_TOKEN`, `CLEGRA_DEV`,
91
+ `CLEGRA_OAUTH_*`; the pack guard reads `CLEGRA_PUBLISH=approved`).
92
+ - The documentation moved from docs/map to docs/developers; the earlier, larger drafts (docs/map/future) are gone.
93
+ The two reference apps (the CRM and the warehouse) and the repository's scripts follow the new names.
94
+
95
+ ### Kinds in a workspace host: the rules made precise (spec §9; docs/map/kinds.md)
96
+
97
+ - §9.1 names: a host gives a clashing app another name at install time and keeps it (other apps store URIs that carry
98
+ it); it translates URIs both ways on every call and refuses, rather than sends, a URI an app could misread as its own.
99
+ - §9.4 sources: `not-linked` is a source state for an app that signs people in itself when the viewer has not linked
100
+ their account; a reference the viewer can't resolve for that reason reads `no-access`.
101
+ - docs/map/kinds.md: when kinds pay off, third parties' dotted kinds, and the promotion rule (two independent apps, a
102
+ host behaviour that uses it, precise keys, schema.org names; additive only).
103
+
104
+ ### Embedded pages: the sign-in ticket (spec §5.1)
105
+
106
+ - A same-site `url` page is signed in with a ticket, not the app's session cookie (a third-party cookie in a host's
107
+ frame). The host (or the SDK's url-page view, over the MCP Apps bridge) calls `modelapp_embed { page, origin }`
108
+ with the viewer's token: a one-minute HS256 JWT for that page and framing origin, carrying the caller as
109
+ `resolve` named it. The frame POSTs it to `/embed/_ticket` (never in a URL); the app checks `Origin`,
110
+ `Sec-Fetch-Dest: iframe`, signature, page, expiry (5 s skew) and single use (`store.once`), then answers 303 to
111
+ the page with a `Secure; HttpOnly; SameSite=None; Partitioned` cookie for the page's path.
112
+ - `defineApp({ embed: { frameAncestors, secret?, path?, sessionSeconds? } })`, required with a same-site page;
113
+ manifest `embed: { tool, path, frameAncestors }`. Every embed response carries `frame-ancestors` = the declared
114
+ hosts, never `X-Frame-Options`.
115
+ - `modelapp/next`: `embedProxy(app)` (proxy.ts) and `getEmbedCaller(app, page)`; core `app.embed`.
116
+ - Conformance: `embed.frame-ancestors` (public) and `embed.ticket`.
117
+ - Examples: `EMBED_FRAME_ANCESTORS` is gone; the hosts are declared in code; the boards read `getEmbedCaller`.
118
+
119
+ ### The `modelapp` package is built for npm
120
+
121
+ - The tarball ships ESM JavaScript with `.d.ts` files and source maps (`dist/`), not TypeScript source: a
122
+ `next.config` importing `modelapp/next` from `node_modules` now loads (Node refuses `.ts` there). Every entry has
123
+ `types` and `default` conditions; `moduleResolution` `bundler` and `node16` both resolve it. The CLI is
124
+ `dist/spec/src/cli.js` with a `node` shebang; the JSON Schema and `kinds.json` ship next to the code
125
+ (`modelapp/modelapp.schema.json`, `modelapp/kinds.json`).
126
+ - `withModelApp` no longer adds `modelapp` to `transpilePackages`: the package is JavaScript.
127
+ - Not published yet: see [RELEASE.md](RELEASE.md).
128
+
129
+ ### The generated view in hosts (spec §5)
130
+
131
+ - **Clicking a row in ChatGPT looked dead.** The view now finishes `ui/initialize` before any `tools/call`
132
+ and calls over the MCP Apps bridge whenever the host answered it; `window.openai.callTool` is used only by a host
133
+ that refused `ui/initialize`, and an answer without `structuredContent` is an error.
134
+ - The opening result is drawn once. Later `ui/notifications/tool-result` messages (sent for the view's own calls)
135
+ and `openai:set_globals` events (sent for every layout, theme or state change) no longer replace the record the
136
+ person opened or remove the way back. `toolResponseMetadata` is read as ChatGPT gives it (the MCP result
137
+ envelope: `_meta` under `mcp_tool_result`).
138
+ - Every call from the view shows progress at once and its outcome where the person looks: a status line kept at
139
+ the top of the view, with the host's own words when it refuses and a clear message after 30 seconds without an
140
+ answer. Before, a refusal was written below the list, outside an inline frame.
141
+ - Rows are focusable and open with Enter or Space.
142
+ - A change made in the view is told to the model (`ui/update-model-context`, the result's text).
143
+
144
+ ### Records named by their title (spec §6 rule 10, §7)
145
+
146
+ - The text a model reads of a list and of a get carries each record's `title` beside its `uri` (`search` and
147
+ `fetch` already did).
148
+ - Every action tool on a record takes an optional `record_title` beside `id`, and both descriptions tell the model
149
+ to name the record by its title. It is a display hint for a client's own approval prompt: never passed to the
150
+ handler, never shown as the app's; a hint that names another record fails the call with `invalid_input`.
151
+ `record_title` is reserved in an action's `input`.
152
+ - Conformance: new checks `mcp.titles` and `mcp.app-callable`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Clegra
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE.md ADDED
@@ -0,0 +1,25 @@
1
+ # Notices
2
+
3
+ ## Owner and trademark
4
+
5
+ `@clegra/sdk` is licensed under the MIT licence (see `LICENSE`). «Clegra» is a
6
+ trademark, not a company: the legal owner of the software and of the
7
+ trademark is Andrea Zago, ditta individuale (sole proprietorship, Italy).
8
+
9
+ The Clegra name, the logo and the face are not licensed with this package:
10
+ the MIT licence covers the code, not the brand.
11
+
12
+ ## Third-party work
13
+
14
+ `@clegra/sdk` builds on the work of others; their licences apply to their parts.
15
+
16
+ | Work | Licence | Where |
17
+ | --- | --- | --- |
18
+ | MCP TypeScript SDK (`@modelcontextprotocol/server`) | MIT | dependency |
19
+ | Ajv (`ajv`) | MIT | dependency |
20
+ | jose | MIT | dependency |
21
+ | Zod | MIT | peer dependency |
22
+ | Next.js | MIT | optional peer dependency (`@clegra/sdk/next`) |
23
+
24
+ Check each dependency's own licence file for the exact text: this table is a
25
+ summary, verified by hand before each release.
package/README.md CHANGED
@@ -1,3 +1,259 @@
1
- # Temporary Holding Version
1
+ # @clegra/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The package Clegra apps are built with. MIT. You write one typed object, `defineApp({ entities, actions, pages,
4
+ fragments, agents, … })`. It becomes a plain, conformant MCP server (tools, MCP Apps views, OAuth) for ChatGPT, Claude
5
+ and any MCP client, and a JSON manifest Clegra reads to draw the app natively in its workspace. Spec: [docs/spec.md](docs/spec.md).
6
+
7
+ ```sh
8
+ npm i @clegra/sdk zod
9
+ ```
10
+
11
+ ESM JavaScript with its type declarations, Node 20+; `zod` 4 is a peer dependency and `next` (15+) an optional one: an
12
+ app that only serves MCP installs no React and no UI library. Clegra's design system is the separate package
13
+ `@clegra/ui` (below); this one does not depend on it.
14
+ Versions before 1.0 are prereleases on the dist-tag `next` (`npm i @clegra/sdk@next zod`); [docs/RELEASE.md](docs/RELEASE.md)
15
+ says how the tarball is made, checked and published.
16
+
17
+ | Entry | What |
18
+ | --- | --- |
19
+ | `@clegra/sdk` | `defineApp`, `AuthError`, `SqlStore`, `MemoryStore`, types. Framework-agnostic (`app.fetch(request)`) |
20
+ | `@clegra/sdk/next` | `toNextHandlers`, `withClegra`, `clegraRewrites`; `embedProxy`, `getEmbedCaller` for embedded pages (`next` is an optional peer dependency) |
21
+ | `@clegra/sdk/node` | `listen(app)`: the app on Node's own HTTP server |
22
+ | `@clegra/sdk/testing` | `testClient(app)`: JSON-RPC to `app.fetch` with dev tokens; `installationClient(app)` for schedules, later runs and lifecycle tools |
23
+ | `@clegra/sdk/spec` | `checkApp`, `formatReport`: the conformance checks |
24
+ | `@clegra/sdk/spec/protocol`, `@clegra/sdk/spec/kinds` | For workspace hosts: the protocol's names (manifest path, URI scheme, `_meta` key, token claim, reserved tools, embed exchange) and the kinds vocabulary with its key normalisation (`KINDS`, `keyOf`, `normaliseKey`, `kindOfRecord`, …). No Node built-ins: safe in a browser bundle |
25
+ | CLI | `npx @clegra/sdk init [dir] [--ui] [--dry-run]`; `npx @clegra/sdk check <url> [--token …]` (or `CLEGRA_TOKEN`) |
26
+
27
+ ## Next.js: `npx @clegra/sdk init`
28
+
29
+ In an existing App Router app, `npx @clegra/sdk init` writes the three files below and wraps next.config. It also puts a
30
+ random local bearer in `.env.local` (`CLEGRA_LOCAL_TOKEN`), which the generated `resolve` accepts only when
31
+ `NODE_ENV` isn't `production`. It never overwrites a file, prints what it can't edit safely, and `--dry-run` writes
32
+ nothing. Then `npm run dev` and `npx @clegra/sdk check http://localhost:3000 --token <CLEGRA_LOCAL_TOKEN>`.
33
+ See [docs/quickstart.md](docs/quickstart.md).
34
+
35
+ ## Next.js: three files
36
+
37
+ ```ts
38
+ // next.config.ts
39
+ import { withClegra } from "@clegra/sdk/next"
40
+
41
+ export default withClegra({ /* your config: your rewrites, in any shape, are kept */ })
42
+ ```
43
+
44
+ ```ts
45
+ // app/api/clegra/[...path]/route.ts
46
+ import { toNextHandlers } from "@clegra/sdk/next"
47
+ import { app } from "@/clegra"
48
+
49
+ export const { GET, POST, DELETE, OPTIONS } = toNextHandlers(app)
50
+ ```
51
+
52
+ ```ts
53
+ // clegra.ts
54
+ import { defineApp } from "@clegra/sdk"
55
+
56
+ export const app = defineApp({
57
+ name: "crm",
58
+ title: "CRM",
59
+ version: "1.0.0",
60
+ auth: {
61
+ resource: `${process.env.CLEGRA_PUBLIC_URL}/mcp`,
62
+ authorizationServers: [`${process.env.CLEGRA_PUBLIC_URL}/api/auth`],
63
+ resolve: async (token, request, { resource }) => {
64
+ // Verify the token of your own sign-in (signature, expiry, aud === resource), then say who is calling.
65
+ return { installation: "org-id", person: { id: "user-id", name: "Ada" }, permissions: ["deals.view"] }
66
+ },
67
+ },
68
+ // permissions, entities (get/list on any database, scoped by ctx.installation), actions, pages…
69
+ })
70
+ ```
71
+
72
+ - **`withClegra`** adds `beforeFiles` rewrites to the route for `/mcp`, `/.well-known/clegra.json` and the OAuth
73
+ metadata paths (`oauth-protected-resource`, `oauth-authorization-server` and `openid-configuration`, each bare or
74
+ with a path).
75
+ - It keeps the app's own rewrites, in any shape: an array, an object, a sync or async function, or a config
76
+ function.
77
+ - It refuses `basePath` (the well-known paths must be at the root of the host) and `trailingSlash: true` (which
78
+ redirects `/mcp` to `/mcp/`).
79
+ - **`toNextHandlers`** hands `app.fetch` each request at its public address.
80
+ - The mount is taken off (`/api/clegra/mcp` → `/mcp`). A rewritten request arrives with its source path, and
81
+ that path is kept.
82
+ - Responses, SSE included, pass through unbuffered. Nothing is kept between requests, so it runs on serverless.
83
+ - Options: `mount` (default `/api/clegra`, the same value in both functions) and `publicUrl`.
84
+ - Leave defineApp's `path` unset: the mount does that job.
85
+
86
+ ## Embedded pages (`/embed/*`)
87
+
88
+ A page `url: "/embed/board"` is a page of your site that hosts frame. The frame is cross-site, so the viewer is signed
89
+ in with a one-minute, single-use ticket the host asks for (`clegra_embed`) and posts into the frame; the app
90
+ answers with a `Secure; HttpOnly; SameSite=None; Partitioned` cookie for that page's path (spec §5.1).
91
+
92
+ ```ts
93
+ // clegra.ts
94
+ defineApp({ …, embed: { frameAncestors: ["https://app.clegra.com", "https://chatgpt.com"], secret: process.env.CLEGRA_EMBED_SECRET } })
95
+
96
+ // proxy.ts
97
+ export const proxy = embedProxy(app) // POST /embed/_ticket; frame-ancestors on every /embed response
98
+ export const config = { matcher: "/embed/:path*" }
99
+
100
+ // app/embed/board/page.tsx
101
+ const caller = await getEmbedCaller(app, "board") // null: no ticket, expired, or a top-level visit
102
+ ```
103
+
104
+ `app.embed.exchange(request)` and `app.embed.caller(page, request)` are the same, framework-neutral; `app.fetch`
105
+ answers `POST <path>/_ticket` too (`@clegra/sdk/node`).
106
+
107
+ ## Public URL behind proxies and on Vercel
108
+
109
+ The public origin is `publicUrl`, else `CLEGRA_PUBLIC_URL` (an origin only, like `https://crm.example.com`), else
110
+ what the request says (`x-forwarded-host` / `x-forwarded-proto`, else `host`). A client can send those headers, so in
111
+ production set `CLEGRA_PUBLIC_URL` and `auth.resource`. Tokens are only accepted for `auth.resource`. Without
112
+ `auth.resource` in production, every request answers `500 misconfigured`. On Vercel, preview deployments have other
113
+ hosts: give each environment its own value.
114
+
115
+ ## Auth: write `auth.resolve` yourself
116
+
117
+ The app verifies its own access tokens: those its sign-in (better-auth, Clerk, Auth0, WorkOS, …) issues to MCP clients.
118
+
119
+ - `auth.resolve(token, request, { resource })` checks the signature, the expiry and that the audience is exactly
120
+ `resource` (RFC 8707). For a JWT that is `jwtVerify` from `jose` with the issuer's JWKS.
121
+ - It returns `{ installation, person, permissions }` (the tenant comes from the token, never from a parameter). It
122
+ returns null, or throws `AuthError`, to refuse.
123
+ - `auth.authorizationServers` names your authorization server in the protected-resource metadata.
124
+ - `auth.serve(request)` can answer its RFC 8414 metadata at the root.
125
+
126
+ Recipes for better-auth, Clerk, Auth0 and WorkOS: [docs/auth.md](docs/auth.md).
127
+
128
+ Dev sign-in (`auth.dev`) answers loopback callers only. A Next route handler can't know the caller's address:
129
+ `x-forwarded-for` is whatever the client sent. So `toNextHandlers` refuses an app with `auth.dev`. Locally,
130
+ use init's bearer (`CLEGRA_LOCAL_TOKEN`) or your own sign-in, or run the app with `listen` from `@clegra/sdk/node`.
131
+
132
+ ## Kinds and references across apps
133
+
134
+ `kind: "person"` on an entity and `.meta({ as: "email", filter: true })` on a field say what the record is in the
135
+ words every app shares (spec §3.1; the vocabulary is `spec/kinds.json`, written with `npm run schema`). Key filters
136
+ (`email`, `vatID`, `gtin`, `uid`) reach `list` normalised and must be matched exactly. `ref.kind("organization")`
137
+ holds the URI of a record in any app (spec §3.2). Both are optional: apps without them are unchanged.
138
+
139
+ ## Navigation, page actions, schedules, notifications
140
+
141
+ All optional; names are checked by TypeScript and again when the app starts (a wrong one fails with its place named).
142
+
143
+ ```ts
144
+ defineApp({
145
+ …,
146
+ pages: {
147
+ tasks: { title: "Tasks", list: "task", columns: ["title"], actions: ["add_task"], badge: "open_count" },
148
+ board: { title: "Board", dashboard: [{ type: "open_count", params: {} }] },
149
+ },
150
+ nav: [{ section: "Work", pages: ["tasks", "board"] }], // without nav: every non-record page, in order
151
+ schedules: { digest: { action: "send_digest", every: 60 } }, // minutes; a read or a write that isn't confirm: "always"
152
+ notifications: { digest: { label: "Daily digest", permission: "tasks.view", default: false } },
153
+ })
154
+ ```
155
+
156
+ - **Page `actions`**: global actions shown on the page, the first one as its primary. Page params fill in the
157
+ action's inputs that have the same names. The generated view draws them as buttons that open the action's form.
158
+ The page's `view` carries them, and the app's `nav` too.
159
+ - **`badge`**: a `stat` fragment with no required params. Its `value` is the page's count in the navigation.
160
+ - **`visibility: "app"`** on an entity, action or fragment: its tools are for views and the host's own UI only.
161
+ They carry MCP Apps `_meta.ui.visibility: ["app"]`, `search`/`fetch` leave the records out, and agents can't use it.
162
+ - **`schedules`**: the workspace host calls the action as the installation, with no person and
163
+ `_meta.clegra.schedule`. Handlers see `ctx.schedule`.
164
+ - **`ctx.notify({ type, title, to })`**: once the app declares `notifications`, every notification names one of
165
+ them. `to` takes person ids or `{ permission }`. A call with no person must say `to`.
166
+ - **`targets`** on a global action: offered on an email (`mail.message`) or a record of a kind
167
+ (`record:organization`). The input template is filled from the fields the target `needs` (`{subject}`,
168
+ `{from.address}`, `{uri}`, `{title}`).
169
+
170
+ ## Approve now, act later
171
+
172
+ ```ts
173
+ publish: {
174
+ title: "Publish", input: z.object({ text: z.string(), when: z.iso.datetime() }),
175
+ later: { at: "when", window: 60 }, // a write with confirm "always"; window 10–10080 minutes
176
+ run: (input, ctx) => { /* ctx.later: { id, at, until, confirmedAt }; ctx.person: who confirmed it */ },
177
+ }
178
+ ```
179
+
180
+ When the person confirms, the call is stored instead of run. The store keeps the arguments as they were confirmed
181
+ and the host's proof (`until` = `at` + `window`). The answer is `{ data: { later: { id, at, until } } }`.
182
+
183
+ The SDK adds the schedule `clegra_later`, run every 5 minutes. Each due run is claimed once. Its arguments and proof
184
+ are checked again (the proof as of when it was confirmed), and then it runs as its author before `until`. If it can't
185
+ run (expired or refused), the author gets a `clegra_later` notification.
186
+
187
+ - Cancel a run with `ctx.cancelLater(id)`.
188
+ - Without a workspace host, `app.runLater(tenant)` runs the due runs from your own cron.
189
+ - A plain client can't produce a proof. Its confirmation is kept without one.
190
+ - The store needs a `later` part. `MemoryStore` and `SqlStore` have one. `SqlStore.schema()` returns both tables
191
+ (`<table>`, `<table>_later`) and is safe to run again in a new migration.
192
+
193
+ ## Lifecycle
194
+
195
+ ```ts
196
+ lifecycle: {
197
+ installation: (state, ctx) => {}, // "enabled" | "disabled" | "uninstalled"
198
+ export: (ctx) => ({ contentType: "application/json", body: json }), // or null: nothing kept
199
+ delete: (ctx) => ({ counts: { tasks: 12 } }), // idempotent; also after uninstall
200
+ }
201
+ ```
202
+
203
+ These become the app-only tools `clegra_installation`, `clegra_export` (one embedded file with its sha256) and
204
+ `clegra_delete`. Only the installation itself is given them: a workspace host's token with no person. `clegra_delete`
205
+ also removes the tenant's later runs.
206
+
207
+ ```ts
208
+ const host = await installationClient(app) // @clegra/sdk/testing
209
+ await host.schedule("digest"); await host.runLater(); const { file } = await host.exportData()
210
+ ```
211
+
212
+ ## Your own UI: `@clegra/ui`
213
+
214
+ An app's own pages and views can use Clegra's design system, the package `@clegra/ui` (its own repository, version
215
+ and guide): components for React and React Native, the theme (light and dark), tokens and `<ClegraProvider>` (an
216
+ MCP Apps view that takes the host's look). The view `@clegra/sdk` generates is plain HTML and needs none of it.
217
+
218
+ ```sh
219
+ npx @clegra/sdk init --ui && npm install # @clegra/ui and its web libraries into package.json, its stylesheet after Tailwind
220
+ ```
221
+
222
+ ```css
223
+ /* app/globals.css (Tailwind 4); without Tailwind: import "@clegra/ui/prebuilt.css" in the root layout */
224
+ @import "tailwindcss";
225
+ @import "@clegra/ui/styles.css";
226
+ ```
227
+
228
+ ```tsx
229
+ import { Button } from "@clegra/ui/components/button"
230
+ import { ClegraProvider } from "@clegra/ui/frame"
231
+ ```
232
+
233
+ ## This repository
234
+
235
+ The package is the repository's root, so it is published from here (`npm publish --tag next`, [docs/RELEASE.md](docs/RELEASE.md)).
236
+
237
+ | Path | What | In the tarball |
238
+ | --- | --- | --- |
239
+ | `src/` | `@clegra/sdk`, `@clegra/sdk/next`, `@clegra/sdk/node`, `@clegra/sdk/testing` | built, as `dist/src` |
240
+ | `spec/` | `@clegra/sdk/spec` (conformance checks), the CLI (`clegra`: `init`, `check`), the manifest's JSON Schema, `kinds.json` | built, as `dist/spec` |
241
+ | `docs/` | The specification, quickstart, guides, release steps | `docs/spec.md` and `docs/quickstart.md` only |
242
+ | `examples/` | `crm` and `warehouse` (Next.js), `shipments` (Node): npm workspaces of this repository using `@clegra/sdk` as `file:../..` (its TypeScript source, no build step); `examples/deploy.sh` deploys a Next.js example to Vercel | no |
243
+ | `test/` | The real Next.js test (`test/fixture`) | no |
244
+ | `scripts/` | The build, `prepack`/`postpack`, the pack check, the hygiene check, the JSON Schema writer | no |
245
+ | `vendor/` | (git-ignored) the `@clegra/ui` tarball the pack check installs beside this package | no |
246
+
247
+ ```sh
248
+ npm ci # the package's tooling and the examples' dependencies (one lockfile)
249
+ npm run typecheck # src, spec, scripts; typecheck:all adds the examples
250
+ npm test # core, @clegra/sdk/next, clegra init (fixture projects in temp folders), the conformance checks
251
+ npm run test:examples # the three examples' tests (the Next.js ones on an embedded Postgres, PGlite)
252
+ npm run test:next # test/fixture with next dev (port 3942), then next build + next start (3943); clegra check through the rewrites; the embedded page in Chromium (Playwright)
253
+ npm run hygiene # nothing private in any tracked file (scripts/hygiene.mjs)
254
+ npm run build # dist/ (git-ignored): what the tarball ships; npm pack builds it itself
255
+ npm run pack:check # slow: npm pack, the publish guard, a Node-only app (no React), a fresh Next.js app, and one with @clegra/ui too (vendor/)
256
+ ```
257
+
258
+ In the repository the package exports its TypeScript source. `npm pack` and `npm publish` build `dist/` and swap in a
259
+ package.json whose exports point there (scripts/prepack.mjs); scripts/postpack.mjs puts the repository's back.