@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.
- package/CHANGELOG.md +158 -0
- package/LICENSE +21 -0
- package/NOTICE.md +25 -0
- package/README.md +258 -2
- package/dist/spec/kinds.json +211 -0
- package/dist/spec/schema/clegra.schema.json +1249 -0
- package/dist/spec/src/cli.d.ts +2 -0
- package/dist/spec/src/cli.js +21 -0
- package/dist/spec/src/cli.js.map +1 -0
- package/dist/spec/src/conformance.d.ts +34 -0
- package/dist/spec/src/conformance.js +704 -0
- package/dist/spec/src/conformance.js.map +1 -0
- package/dist/spec/src/init/index.d.ts +31 -0
- package/dist/spec/src/init/index.js +151 -0
- package/dist/spec/src/init/index.js.map +1 -0
- package/dist/spec/src/init/next-config.d.ts +19 -0
- package/dist/spec/src/init/next-config.js +77 -0
- package/dist/spec/src/init/next-config.js.map +1 -0
- package/dist/spec/src/init/project.d.ts +44 -0
- package/dist/spec/src/init/project.js +141 -0
- package/dist/spec/src/init/project.js.map +1 -0
- package/dist/spec/src/init/templates.d.ts +20 -0
- package/dist/spec/src/init/templates.js +166 -0
- package/dist/spec/src/init/templates.js.map +1 -0
- package/dist/spec/src/init/ui.d.ts +30 -0
- package/dist/spec/src/init/ui.js +82 -0
- package/dist/spec/src/init/ui.js.map +1 -0
- package/dist/spec/src/kinds.d.ts +89 -0
- package/dist/spec/src/kinds.js +319 -0
- package/dist/spec/src/kinds.js.map +1 -0
- package/dist/spec/src/protocol.d.ts +50 -0
- package/dist/spec/src/protocol.js +52 -0
- package/dist/spec/src/protocol.js.map +1 -0
- package/dist/spec/src/rules.d.ts +132 -0
- package/dist/spec/src/rules.js +282 -0
- package/dist/spec/src/rules.js.map +1 -0
- package/dist/src/auth.d.ts +371 -0
- package/dist/src/auth.js +964 -0
- package/dist/src/auth.js.map +1 -0
- package/dist/src/define.d.ts +249 -0
- package/dist/src/define.js +83 -0
- package/dist/src/define.js.map +1 -0
- package/dist/src/embed.d.ts +98 -0
- package/dist/src/embed.js +256 -0
- package/dist/src/embed.js.map +1 -0
- package/dist/src/index.d.ts +11 -0
- package/dist/src/index.js +11 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/labels.d.ts +10 -0
- package/dist/src/labels.js +22 -0
- package/dist/src/labels.js.map +1 -0
- package/dist/src/manifest.d.ts +499 -0
- package/dist/src/manifest.js +188 -0
- package/dist/src/manifest.js.map +1 -0
- package/dist/src/meaning.d.ts +64 -0
- package/dist/src/meaning.js +116 -0
- package/dist/src/meaning.js.map +1 -0
- package/dist/src/next/index.d.ts +101 -0
- package/dist/src/next/index.js +187 -0
- package/dist/src/next/index.js.map +1 -0
- package/dist/src/node.d.ts +14 -0
- package/dist/src/node.js +64 -0
- package/dist/src/node.js.map +1 -0
- package/dist/src/server.d.ts +229 -0
- package/dist/src/server.js +2256 -0
- package/dist/src/server.js.map +1 -0
- package/dist/src/store.d.ts +129 -0
- package/dist/src/store.js +213 -0
- package/dist/src/store.js.map +1 -0
- package/dist/src/testing.d.ts +133 -0
- package/dist/src/testing.js +81 -0
- package/dist/src/testing.js.map +1 -0
- package/dist/src/types.d.ts +352 -0
- package/dist/src/types.js +2 -0
- package/dist/src/types.js.map +1 -0
- package/dist/src/view.d.ts +35 -0
- package/dist/src/view.js +442 -0
- package/dist/src/view.js.map +1 -0
- package/docs/quickstart.md +350 -0
- package/docs/spec.md +997 -0
- package/package.json +89 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"view.js","sourceRoot":"","sources":["../../src/view.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAE5D,MAAM,CAAC,MAAM,iBAAiB,GAAG,2BAA2B,CAAA;AAC5D,MAAM,CAAC,MAAM,yBAAyB,GAAG,YAAY,CAAA;AAErD,MAAM,KAAK,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8Bb,CAAA;AAED,MAAM,MAAM,GAAG;;;;;;;;;;;;;;;+DAegD,yBAAyB,wBAAwB,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wHA+BH,WAAW;;;yFAG1C,QAAQ;;gEAEjC,QAAQ,yDAAyD,QAAQ;;;;;;;;kBAQvH,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;8GAwDiF,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4WAwEmP,WAAW;;;;;;;;qCAQlV,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;+OA+G+L,QAAQ;;;;;;;;;;;;;CAatP,CAAA;AAED,2GAA2G;AAC3G,MAAM,UAAU,QAAQ,CAAC,KAAa,EAAE,OAAgE,IAAI;IAC1G,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;IAC9D,OAAO,8HAA8H,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,kBAAkB,KAAK,kJAAkJ,MAAM,CAAC,OAAO,CAAC,UAAU,EAAE,QAAQ,CAAC,yBAAyB,CAAA;AACvY,CAAC;AAED,MAAM,eAAe,GAAG;;;;;;;;;;;;;;;;;;;;;;;;+DAwBuC,yBAAyB,wBAAwB,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4B1H,CAAA;AAED;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CAAC,KAAa,EAAE,GAAW,EAAE,KAA4C;IAClG,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;IACpE,MAAM,IAAI,GAAG,GAAG,WAAW,OAAO,CAAA;IAClC,OAAO,8HAA8H,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,+cAA+c,IAAI,4GAA4G,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,sBAAsB,eAAe,CAAC,OAAO,CAAC,UAAU,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,yBAAyB,CAAA;AACr1B,CAAC","sourcesContent":["/**\n * THE SDK'S MCP APPS VIEW (spec §5): one HTML document that draws every\n * derived result (a list, a record, a fragment, a dashboard) for hosts that\n * show MCP Apps views: ChatGPT, Claude, and a workspace host's frames.\n *\n * It speaks the MCP Apps bridge (JSON-RPC 2.0 over postMessage:\n * `ui/initialize` then `ui/notifications/initialized`, `tools/call`,\n * `ui/notifications/tool-result`, `ui/notifications/size-changed`,\n * `ui/update-model-context`). ChatGPT implements the same bridge and also\n * injects `window.openai`: the view draws its first result from\n * `window.openai.toolOutput` when that is there first, but calls tools over the\n * standard bridge; `window.openai.callTool` is used only by a host that did not\n * answer `ui/initialize`. Data arrives as the tool result's `structuredContent`;\n * a page opened with no tool call (`boot`) asks for its own data. No network\n * access: the host relays every call, with its permissions and confirmations.\n * A click always shows something: progress at once, then the record, or what\n * the host or the app said, in a status line at the top of the view.\n */\n\nimport { META_KEY, PROTOCOL_ID } from \"../spec/src/protocol\"\n\nexport const MCP_APP_MIME_TYPE = \"text/html;profile=mcp-app\"\nexport const MCP_APPS_PROTOCOL_VERSION = \"2026-01-26\"\n\nconst STYLE = `\n:root{color-scheme:light dark;--bg:var(--color-background-primary,#fff);--bg2:var(--color-background-secondary,#f5f5f7);--fg:var(--color-text-primary,#1d1d1f);--fg2:var(--color-text-secondary,#6e6e73);--line:var(--color-border-primary,#e5e5ea);--accent:var(--color-text-info,#0a66d8);--r:var(--border-radius-md,10px);font-family:var(--font-sans,system-ui,-apple-system,sans-serif)}\n@media (prefers-color-scheme:dark){:root{--bg:var(--color-background-primary,#1c1c1e);--bg2:var(--color-background-secondary,#2c2c2e);--fg:var(--color-text-primary,#f5f5f7);--fg2:var(--color-text-secondary,#a1a1a6);--line:var(--color-border-primary,#3a3a3c)}}\nhtml[data-theme=dark]{--bg:var(--color-background-primary,#1c1c1e);--bg2:var(--color-background-secondary,#2c2c2e);--fg:var(--color-text-primary,#f5f5f7);--fg2:var(--color-text-secondary,#a1a1a6);--line:var(--color-border-primary,#3a3a3c)}\nhtml[data-theme=light]{--bg:var(--color-background-primary,#fff);--bg2:var(--color-background-secondary,#f5f5f7);--fg:var(--color-text-primary,#1d1d1f);--fg2:var(--color-text-secondary,#6e6e73);--line:var(--color-border-primary,#e5e5ea)}\n*{box-sizing:border-box}body{margin:0;background:transparent;color:var(--fg);font-size:14px;line-height:1.4}\n#root{padding:12px}h2{font-size:16px;margin:0 0 10px}h3{font-size:14px;margin:0 0 6px}\n.muted{color:var(--fg2)}.box{background:var(--bg);border:1px solid var(--line);border-radius:var(--r);padding:12px}\ntable{width:100%;border-collapse:collapse}th,td{text-align:left;padding:7px 8px;border-bottom:1px solid var(--line);vertical-align:top}th{font-weight:600;color:var(--fg2);font-size:12px}\ntr.link{cursor:pointer}tr.link:hover td{background:var(--bg2)}td.num{text-align:right;font-variant-numeric:tabular-nums}\n.badge{display:inline-block;padding:1px 8px;border-radius:999px;font-size:12px;background:var(--bg2)}\n.t-success{background:#d9f5df;color:#11622a}.t-danger{background:#fde0e0;color:#8a1414}.t-warning{background:#fff1cc;color:#7a4d00}.t-info{background:#dcebff;color:#0b4a99}\n@media (prefers-color-scheme:dark){.t-success{background:#123d20;color:#9be3ae}.t-danger{background:#4a1616;color:#ffb3b3}.t-warning{background:#4a3a10;color:#ffd98a}.t-info{background:#14304f;color:#a9cfff}}\nhtml[data-theme=dark]{color-scheme:dark}html[data-theme=light]{color-scheme:light}\nhtml[data-theme=dark] .t-success{background:#123d20;color:#9be3ae}html[data-theme=dark] .t-danger{background:#4a1616;color:#ffb3b3}html[data-theme=dark] .t-warning{background:#4a3a10;color:#ffd98a}html[data-theme=dark] .t-info{background:#14304f;color:#a9cfff}\nhtml[data-theme=light] .t-success{background:#d9f5df;color:#11622a}html[data-theme=light] .t-danger{background:#fde0e0;color:#8a1414}html[data-theme=light] .t-warning{background:#fff1cc;color:#7a4d00}html[data-theme=light] .t-info{background:#dcebff;color:#0b4a99}\ndl{display:grid;grid-template-columns:minmax(90px,max-content) 1fr;gap:6px 14px;margin:8px 0}dt{color:var(--fg2)}dd{margin:0}\n.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:10px}\n.stat{font-size:26px;font-weight:600;font-variant-numeric:tabular-nums}\nbutton{font:inherit;border:1px solid var(--line);background:var(--bg2);color:var(--fg);border-radius:8px;padding:5px 12px;cursor:pointer}button.back{margin:0 0 8px;background:transparent;border-color:transparent;color:var(--fg2);padding:2px 4px}button.primary{background:var(--fg);color:var(--bg);border-color:var(--fg)}\n.row{display:flex;gap:8px;flex-wrap:wrap;align-items:center}.actions{margin-top:10px}\nform.act{margin-top:8px;display:grid;gap:6px}input,select,textarea{font:inherit;padding:6px;border:1px solid var(--line);border-radius:6px;background:var(--bg);color:var(--fg)}\n.bar{display:grid;grid-template-columns:minmax(70px,max-content) 1fr max-content;gap:6px 10px;align-items:center}.bar i{display:block;height:10px;background:var(--accent);border-radius:4px}\n.msg{margin-top:8px;font-size:13px}.err{color:#c62828}\nth.sort{cursor:pointer;user-select:none;white-space:nowrap}th.sort:hover{color:var(--fg)}th.sort:focus-visible{outline:2px solid var(--accent);outline-offset:-2px}\n.req{color:#c62828}.ferr{color:#c62828;font-size:12px;min-height:0}.bad{border-color:#c62828}form.act label{display:block}\n#status{position:sticky;top:0;z-index:2;margin:12px 12px 0;padding:7px 10px;border-radius:8px;font-size:13px;background:var(--bg2);color:var(--fg2);border:1px solid var(--line)}#status[hidden]{display:none}#status.error{color:#c62828;border-color:#c62828}\ntr.link:focus-visible td{outline:2px solid var(--accent);outline-offset:-2px}tr[aria-busy=true] td{opacity:.55}\nnav.nav{display:grid;gap:4px;margin:0 0 10px}.navlabel{font-size:12px;margin-right:2px}button.navitem{padding:3px 10px;font-size:13px}button.navitem[aria-current=page]{border-color:var(--fg);font-weight:600}button.navitem[aria-busy=true]{opacity:.55}\n.count{margin-left:6px;font-size:12px;color:var(--fg2);font-variant-numeric:tabular-nums}.pageacts{margin:0 0 10px}\n`\n\nconst SCRIPT = `\n(() => {\n const BOOT = __BOOT__;\n const root = document.getElementById(\"root\"); const statusLine = document.getElementById(\"status\");\n // shown: a result is on screen (the first one the host gave, or the view's own boot call).\n let nextId = 1; const pending = new Map(); let shown = false; let locale = navigator.language || \"en\";\n const post = (m) => window.parent.postMessage(m, \"*\");\n // A host that never answers (it refused the call without saying so) is an error the person sees, not a dead click.\n const request = (method, params, wait) => new Promise((resolve, reject) => { const id = nextId++; pending.set(id, { resolve, reject }); post({ jsonrpc: \"2.0\", id, method, params }); if (wait) setTimeout(() => { if (pending.delete(id)) reject(new Error(tr(\"noAnswer\", method + (params && params.name ? \" \" + params.name : \"\")))); }, wait); });\n const notify = (method, params) => post({ jsonrpc: \"2.0\", method, params });\n const esc = (s) => String(s ?? \"\").replace(/[&<>\"']/g, (c) => ({ \"&\": \"&\", \"<\": \"<\", \">\": \">\", '\"': \""\", \"'\": \"'\" })[c]);\n // The bridge this host speaks: \"mcp\" once it answered ui/initialize (the standard, ChatGPT included), \"openai\" for a\n // host that only injects window.openai. Every call waits for the handshake: a host takes no tools/call before it.\n let bridge = null;\n const openaiCalls = () => Boolean(window.openai && typeof window.openai.callTool === \"function\");\n const ready = request(\"ui/initialize\", { protocolVersion: \"${MCP_APPS_PROTOCOL_VERSION}\", appInfo: { name: \"${PROTOCOL_ID}-view\", version: \"1.0.0\" }, appCapabilities: {} }, 10000).then(\n (r) => { bridge = \"mcp\"; applyContext(r && r.hostContext); notify(\"ui/notifications/initialized\", {}); resize(); },\n (e) => { if (openaiCalls()) { bridge = \"openai\"; return; } throw new Error(tr(\"noBridge\") + \" (\" + String((e && e.message) || e) + \")\"); });\n ready.catch(() => {});\n const within = (p, what) => new Promise((resolve, reject) => { const t = setTimeout(() => reject(new Error(tr(\"noAnswer\", what))), 30000); p.then((v) => { clearTimeout(t); resolve(v); }, (e) => { clearTimeout(t); reject(e); }); });\n // A refusal says who refused and why (the host's own words), never a dead click.\n const callTool = async (name, args) => {\n await ready;\n if (bridge === \"mcp\") {\n try { return await request(\"tools/call\", { name, arguments: args }, 30000); }\n catch (e) { const why = String((e && e.message) || e); throw new Error(why.startsWith(tr(\"noAnswer\", \"\")) ? why : tr(\"refused\", name) + \" \" + why); }\n }\n let r;\n try { r = await within(Promise.resolve(window.openai.callTool(name, args)), name); }\n catch (e) { const why = String((e && e.message) || e); throw new Error(why.startsWith(tr(\"noAnswer\", \"\")) ? why : tr(\"refused\", name) + \" \" + why); }\n if (r === undefined || r === null || typeof r !== \"object\") throw new Error(tr(\"refused\", name));\n if (!r.structuredContent && !r.isError) throw new Error(tr(\"noData\", name));\n return r;\n };\n // What the view is doing or what went wrong, at the top where the person is looking (sticky while scrolling).\n const notice = (text, kind) => { statusLine.hidden = !text; statusLine.textContent = text || \"\"; statusLine.className = kind || \"\"; statusLine.setAttribute(\"role\", kind === \"error\" ? \"alert\" : \"status\"); resize(); };\n const fail = (e) => { const text = String((e && e.message) || e || \"Failed\"); if (!shown) { notice(null); root.innerHTML = '<div class=\"box err\">' + esc(text) + \"</div>\"; resize(); } else notice(text, \"error\"); };\n // The view's own few words (what the app's labels don't cover), in the host's language when the view has it.\n const STR = {\n en: { pages: \"Pages\", dateTime: \"Enter a date and time\", opening: \"Opening…\", working: \"Working…\", refused: \"The host refused the call ({n}).\", noAnswer: \"The host did not answer ({n}).\", noData: \"The host returned no data for the view ({n}).\", noBridge: \"This host does not connect the view to the app\", required: \"Required\", tooShort: \"At least {n} characters\", tooLong: \"At most {n} characters\", min: \"At least {n}\", max: \"At most {n}\", date: \"Enter a date\", number: \"Enter a number\", search: \"Search…\", choose: \"Choose…\", none: \"No results\", done: \"Done.\", noAccess: \"No access\", notAvailable: \"Not available\", sortBy: \"Sort by {n}\", unknownPerson: \"Unknown person\", refGone: \"Deleted\", refUnreachable: \"App not answering\", refUnknownApp: \"App not in this workspace\", recordUri: \"A record URI: clegra://app/entity/id\" },\n it: { pages: \"Pagine\", dateTime: \"Inserisci data e ora\", opening: \"Apertura…\", working: \"In corso…\", refused: \"L'host ha rifiutato la chiamata ({n}).\", noAnswer: \"L'host non ha risposto ({n}).\", noData: \"L'host non ha restituito dati per la vista ({n}).\", noBridge: \"Questo host non collega la vista all'app\", required: \"Obbligatorio\", tooShort: \"Almeno {n} caratteri\", tooLong: \"Al massimo {n} caratteri\", min: \"Almeno {n}\", max: \"Al massimo {n}\", date: \"Inserisci una data\", number: \"Inserisci un numero\", search: \"Cerca…\", choose: \"Scegli…\", none: \"Nessun risultato\", done: \"Fatto.\", noAccess: \"Nessun accesso\", notAvailable: \"Non disponibile\", sortBy: \"Ordina per {n}\", unknownPerson: \"Persona sconosciuta\", refGone: \"Eliminato\", refUnreachable: \"L'app non risponde\", refUnknownApp: \"App non presente in questo spazio\", recordUri: \"L'URI di un record: clegra://app/entità/id\" },\n es: { pages: \"Páginas\", dateTime: \"Introduce fecha y hora\", opening: \"Abriendo…\", working: \"En curso…\", refused: \"El host rechazó la llamada ({n}).\", noAnswer: \"El host no respondió ({n}).\", noData: \"El host no devolvió datos para la vista ({n}).\", noBridge: \"Este host no conecta la vista con la app\", required: \"Obligatorio\", tooShort: \"Al menos {n} caracteres\", tooLong: \"Como máximo {n} caracteres\", min: \"Al menos {n}\", max: \"Como máximo {n}\", date: \"Introduce una fecha\", number: \"Introduce un número\", search: \"Buscar…\", choose: \"Elige…\", none: \"Sin resultados\", done: \"Hecho.\", noAccess: \"Sin acceso\", notAvailable: \"No disponible\", sortBy: \"Ordenar por {n}\", unknownPerson: \"Persona desconocida\", refGone: \"Eliminado\", refUnreachable: \"La app no responde\", refUnknownApp: \"App que no está en este espacio\", recordUri: \"La URI de un registro: clegra://app/entidad/id\" },\n fr: { pages: \"Pages\", dateTime: \"Saisissez une date et une heure\", opening: \"Ouverture…\", working: \"En cours…\", refused: \"L'hôte a refusé l'appel ({n}).\", noAnswer: \"L'hôte n'a pas répondu ({n}).\", noData: \"L'hôte n'a renvoyé aucune donnée pour la vue ({n}).\", noBridge: \"Cet hôte ne relie pas la vue à l'app\", required: \"Obligatoire\", tooShort: \"Au moins {n} caractères\", tooLong: \"Au plus {n} caractères\", min: \"Au moins {n}\", max: \"Au plus {n}\", date: \"Saisissez une date\", number: \"Saisissez un nombre\", search: \"Rechercher…\", choose: \"Choisir…\", none: \"Aucun résultat\", done: \"Fait.\", noAccess: \"Pas d'accès\", notAvailable: \"Non disponible\", sortBy: \"Trier par {n}\", unknownPerson: \"Personne inconnue\", refGone: \"Supprimé\", refUnreachable: \"L'app ne répond pas\", refUnknownApp: \"App absente de cet espace\", recordUri: \"L'URI d'un enregistrement : clegra://app/entité/id\" },\n de: { pages: \"Seiten\", dateTime: \"Datum und Uhrzeit eingeben\", opening: \"Wird geöffnet…\", working: \"Wird ausgeführt…\", refused: \"Der Host hat den Aufruf abgelehnt ({n}).\", noAnswer: \"Der Host hat nicht geantwortet ({n}).\", noData: \"Der Host hat keine Daten für die Ansicht geliefert ({n}).\", noBridge: \"Dieser Host verbindet die Ansicht nicht mit der App\", required: \"Erforderlich\", tooShort: \"Mindestens {n} Zeichen\", tooLong: \"Höchstens {n} Zeichen\", min: \"Mindestens {n}\", max: \"Höchstens {n}\", date: \"Datum eingeben\", number: \"Zahl eingeben\", search: \"Suchen…\", choose: \"Auswählen…\", none: \"Keine Ergebnisse\", done: \"Erledigt.\", noAccess: \"Kein Zugriff\", notAvailable: \"Nicht verfügbar\", sortBy: \"Sortieren nach {n}\", unknownPerson: \"Unbekannte Person\", refGone: \"Gelöscht\", refUnreachable: \"App antwortet nicht\", refUnknownApp: \"App nicht in diesem Arbeitsbereich\", recordUri: \"Die URI eines Datensatzes: clegra://app/entität/id\" },\n };\n const tr = (k, n) => String((STR[String(locale).split(\"-\")[0].toLowerCase()] || STR.en)[k] || STR.en[k]).replace(\"{n}\", n === undefined ? \"\" : n);\n // The app's labels in the reader's language (hostContext.locale): each call sends its labels' other locales (_meta.${PROTOCOL_ID}.l10n); English when the app lacks the reader's.\n let l10n = {};\n const L = (s) => { if (typeof s !== \"string\") return s; const lang = String(locale).split(\"-\")[0].toLowerCase(); const d = l10n[locale] || l10n[lang] || l10n.en; const out = d && d[s]; return typeof out === \"string\" ? out : s; };\n // Records of other apps, as the workspace host resolved them for this viewer (_meta.${META_KEY}.resolved: uri → { state, title? }, spec §3.2).\n let resolved = {};\n const learn = (r) => { const m = r && ((r._meta && r._meta[\"${META_KEY}\"]) || (r.result && r.result._meta && r.result._meta[\"${META_KEY}\"])); if (m && m.resolved && typeof m.resolved === \"object\") resolved = Object.assign({}, resolved, m.resolved); const add = m && m.l10n; if (!add || typeof add !== \"object\") return; for (const [k, d] of Object.entries(add)) if (d && typeof d === \"object\") l10n[k] = Object.assign(l10n[k] || {}, d); };\n let refs = {};\n const STATE_WORD = { \"no-access\": \"noAccess\", gone: \"refGone\", unreachable: \"refUnreachable\", \"unknown-app\": \"refUnknownApp\" };\n // A record of another app: its title or its state as the host says it; without the host's word, the app and entity the URI names, never a title.\n const crossRef = (v) => {\n const r = resolved[v];\n if (r && r.state === \"ok\" && typeof r.title === \"string\") return esc(r.title);\n if (r && STATE_WORD[r.state]) return '<span class=\"muted\" title=\"' + esc(v) + '\">' + esc(tr(STATE_WORD[r.state])) + \"</span>\";\n const m = /^${PROTOCOL_ID}:\\\\/\\\\/([^/]+)\\\\/([^/]+)\\\\//.exec(String(v));\n return '<span class=\"muted\" title=\"' + esc(v) + '\">' + esc(m ? m[1] + \" · \" + m[2] : v) + \"</span>\";\n };\n const fmt = (v, col) => {\n if (col && col.ref && typeof col.ref === \"object\" && col.ref.kind && typeof v === \"string\" && v) return crossRef(v);\n if (col && col.ref && refs[col.name] && refs[col.name][v]) return esc(refs[col.name][v]);\n // A person by name; one the app can't name is an unknown person, never the bare id.\n if (col && col.role === \"person\" && !col.ref && refs[col.name] && v !== null && v !== undefined && v !== \"\") return refs[col.name][v] ? esc(refs[col.name][v]) : '<span class=\"muted\">' + esc(tr(\"unknownPerson\")) + \"</span>\";\n if (v === null || v === undefined || v === \"\") return '<span class=\"muted\">—</span>';\n if (col && col.role === \"amount\" && typeof v === \"number\") { try { return esc(new Intl.NumberFormat(locale, { style: \"currency\", currency: col.currency || \"EUR\" }).format(v)); } catch { return esc(v); } }\n if (col && col.role === \"date\" && typeof v === \"string\" && /^\\\\d{4}-\\\\d{2}-\\\\d{2}/.test(v)) { try { return esc(new Intl.DateTimeFormat(locale, { dateStyle: \"medium\" }).format(new Date(v.length === 10 ? v + \"T12:00:00\" : v))); } catch { return esc(v); } }\n if (col && col.enum && col.labels) { const label = L(col.labels[v] ?? v); const tone = col.tones && col.tones[v]; return col.role === \"status\" ? '<span class=\"badge ' + (tone ? \"t-\" + tone : \"\") + '\">' + esc(label) + \"</span>\" : esc(label); }\n if (typeof v === \"number\") return esc(new Intl.NumberFormat(locale).format(v));\n if (typeof v === \"boolean\") return v ? \"✓\" : \"—\";\n if (typeof v === \"object\") return esc(JSON.stringify(v));\n return esc(v);\n };\n const resize = () => notify(\"ui/notifications/size-changed\", { width: document.documentElement.scrollWidth, height: Math.ceil(document.body.getBoundingClientRect().height) });\n const say = (el, text, error) => { let m = el.querySelector(\":scope > .msg\"); if (!m) { m = document.createElement(\"div\"); m.className = \"msg\"; el.appendChild(m); } m.className = \"msg\" + (error ? \" err\" : \"\"); m.textContent = text; m.hidden = !text; resize(); if (text && m.scrollIntoView) m.scrollIntoView({ block: \"nearest\" }); };\n const resultOf = (r) => { learn(r); return (r && r.structuredContent) || (r && r.result && r.result.structuredContent) || r || {}; };\n const errorOf = (r) => { const s = resultOf(r); return (r && r.isError) ? L((s.error && s.error.message) || (r.content && r.content[0] && r.content[0].text) || \"Failed\") : null; };\n\n function actionForm(container, action, record, recordTitle) {\n const schema = action.input || {};\n const props = schema.properties || {};\n const required = new Set(Array.isArray(schema.required) ? schema.required : []);\n const keys = Object.keys(props).filter((k) => k !== \"id\");\n // What is wrong with each field, said under it; true when something was said.\n const showErrors = (form, errs) => { let any = false; form.querySelectorAll(\"[data-err]\").forEach((d) => { const m = errs[d.dataset.err]; d.textContent = m || \"\"; const el = form.elements[d.dataset.err]; if (el && el.classList) { el.classList.toggle(\"bad\", Boolean(m)); el.setAttribute(\"aria-invalid\", m ? \"true\" : \"false\"); } if (m) any = true; }); resize(); return any; };\n const run = async (args, form) => {\n const button = form && form.querySelector(\"button.primary\"); if (button) button.disabled = true;\n say(container, tr(\"working\"));\n try {\n // record_title: what the host's own approval prompt can show beside the id; the app never trusts it (it names the record itself).\n const r = await callTool(action.tool, Object.assign({}, record ? { id: record.id } : {}, record && recordTitle ? { record_title: recordTitle } : {}, args)); const e = errorOf(r);\n if (e) { const fields = resultOf(r).error && resultOf(r).error.fields; if (form && fields && showErrors(form, fields)) { say(container, \"\"); return; } return say(container, e, true); }\n if (form) form.remove();\n const s = resultOf(r); say(container, L(s.message) || tr(\"done\")); tellModel(action, r, s);\n if (lastCall && (s.record || !record)) { try { await reload(); } catch (e) { return fail(e); } const box = root.querySelector(\".box\"); if (box) say(box, L(s.message) || tr(\"done\")); }\n }\n catch (e) { say(container, String(e && e.message || e), true); }\n finally { if (button) button.disabled = false; }\n };\n if (!keys.length) return run({}, null);\n const open = container.querySelector(\":scope > form.act\"); if (open) open.remove();\n const f = document.createElement(\"form\"); f.className = \"act\"; f.noValidate = true;\n f.innerHTML = keys.map((k) => { const p = props[k]; const must = required.has(k);\n const label = esc(L(p.title) || k) + (p.currency ? \" (\" + esc(p.currency) + \")\" : \"\") + (must ? ' <span class=\"req\" title=\"' + esc(tr(\"required\")) + '\">*</span>' : \"\");\n const attrs = ' name=\"' + esc(k) + '\"' + (must ? ' aria-required=\"true\"' : \"\");\n const err = '<div class=\"ferr\" data-err=\"' + esc(k) + '\" role=\"alert\"></div>';\n // Another record's id: a picker over that entity's list (searched by text when it can be), showing titles.\n if (p.ref && p.ref.tool) return \"<label>\" + label + \"<br>\" + (p.ref.search ? '<input type=\"search\" data-ref-search=\"' + esc(k) + '\" placeholder=\"' + esc(tr(\"search\")) + '\" aria-label=\"' + esc(tr(\"search\")) + '\"> ' : \"\") + \"<select\" + attrs + ' data-ref=\"' + esc(k) + '\"><option value=\"\">' + esc(tr(\"choose\")) + \"</option></select></label>\" + err;\n if (Array.isArray(p.enum)) return \"<label>\" + label + \"<br><select\" + attrs + \">\" + (must ? \"\" : '<option value=\"\">—</option>') + p.enum.map((v) => '<option value=\"' + esc(v) + '\">' + esc(L((p.labels && p.labels[v]) || v)) + \"</option>\").join(\"\") + \"</select></label>\" + err;\n if (p.type === \"boolean\") return '<label><input type=\"checkbox\" name=\"' + esc(k) + '\"> ' + esc(L(p.title) || k) + \"</label>\";\n const num = p.type === \"number\" || p.type === \"integer\";\n // A record of another app: its URI (a workspace host offers its own picker over every app of the kind).\n if (p.ref && p.ref.kind) return \"<label>\" + label + \"<br><input\" + attrs + ' type=\"text\" placeholder=\"${PROTOCOL_ID}://…\" spellcheck=\"false\"></label>' + err;\n return \"<label>\" + label + \"<br><input\" + attrs + ' type=\"' + (num ? \"number\" : p.format === \"date\" ? \"date\" : p.format === \"date-time\" ? \"datetime-local\" : \"text\") + '\"' + (num && p.type === \"number\" ? ' step=\"any\"' : \"\") + (typeof p.minimum === \"number\" ? ' min=\"' + p.minimum + '\"' : \"\") + (typeof p.maximum === \"number\" ? ' max=\"' + p.maximum + '\"' : \"\") + (typeof p.maxLength === \"number\" ? ' maxlength=\"' + p.maxLength + '\"' : \"\") + \"></label>\" + err; }).join(\"\") + '<div class=\"row\"><button class=\"primary\" type=\"button\">' + esc(L(action.title)) + \"</button></div>\";\n // The latest ask per field wins: an earlier, slower answer (the first full list) never replaces what was searched after it.\n const asked = {};\n const loadRef = async (k, q) => {\n const p = props[k]; const sel = f.elements[k]; if (!sel) return; const keep = sel.value || sel.dataset.prefill || \"\"; const turn = asked[k] = (asked[k] || 0) + 1;\n try { const r = await callTool(p.ref.tool, Object.assign({ limit: 25 }, q ? { query: q } : {})); if (turn !== asked[k] || errorOf(r)) return; const rows = resultOf(r).rows || [];\n sel.innerHTML = '<option value=\"\">' + esc(tr(rows.length ? \"choose\" : \"none\")) + \"</option>\" + rows.map((row) => '<option value=\"' + esc(row.id) + '\">' + esc(row[p.ref.title] === undefined || row[p.ref.title] === null ? row.id : row[p.ref.title]) + \"</option>\").join(\"\");\n if (keep && rows.some((row) => row.id === keep)) sel.value = keep; else if (q && rows.length === 1) sel.value = rows[0].id; resize(); } catch {}\n };\n const check = (k, el) => { const p = props[k]; if (p.type === \"boolean\") return null; const v = el.value;\n if (v === \"\") return required.has(k) ? tr(\"required\") : null;\n if (p.type === \"number\" || p.type === \"integer\") { const n = Number(v); if (!Number.isFinite(n) || (p.type === \"integer\" && !Number.isInteger(n))) return tr(\"number\"); if (typeof p.minimum === \"number\" && n < p.minimum) return tr(\"min\", fmt(p.minimum)); if (typeof p.maximum === \"number\" && n > p.maximum) return tr(\"max\", fmt(p.maximum)); return null; }\n if (p.format === \"date\" && !/^\\\\d{4}-\\\\d{2}-\\\\d{2}$/.test(v)) return tr(\"date\");\n if (p.format === \"date-time\" && !Number.isFinite(Date.parse(v))) return tr(\"dateTime\");\n if (p.ref && p.ref.kind && typeof p.pattern === \"string\" && !new RegExp(p.pattern).test(v)) return tr(\"recordUri\");\n if (typeof p.minLength === \"number\" && v.length < p.minLength) return tr(\"tooShort\", p.minLength);\n if (typeof p.maxLength === \"number\" && v.length > p.maxLength) return tr(\"tooLong\", p.maxLength);\n return null; };\n // A click, not a form submission: views run in a sandbox without allow-forms.\n f.onsubmit = (e) => e.preventDefault();\n f.querySelector(\"button.primary\").onclick = () => {\n const args = {}; const errs = {};\n for (const k of keys) { const el = f.elements[k]; const p = props[k]; if (!el) continue; const bad = check(k, el); if (bad) errs[k] = bad; if (p.type === \"boolean\") args[k] = el.checked; else if (el.value !== \"\") args[k] = (p.type === \"number\" || p.type === \"integer\") ? Number(el.value) : p.format === \"date-time\" ? new Date(el.value).toISOString() : el.value; }\n if (showErrors(f, errs)) { const first = f.querySelector(\".bad\"); if (first && first.focus) first.focus(); return; }\n run(args, f);\n };\n // A page action's inputs start from the page's params of the same name (prefill); a picker keeps its value until its options arrive.\n const pre = action.prefill || {};\n for (const k of keys) { const v = pre[k]; const el = f.elements[k]; if (v === undefined || v === null || !el) continue;\n if (props[k].type === \"boolean\") el.checked = Boolean(v); else if (props[k].ref && props[k].ref.tool) el.dataset.prefill = String(v);\n else if (props[k].format === \"date-time\") { const d = new Date(String(v)); if (Number.isFinite(d.getTime())) el.value = new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 16); }\n else el.value = String(v); }\n container.appendChild(f);\n for (const k of keys) if (props[k].ref && props[k].ref.tool) { loadRef(k, \"\"); const box = f.querySelector('[data-ref-search=\"' + k + '\"]'); let timer; if (box) box.oninput = () => { clearTimeout(timer); timer = setTimeout(() => loadRef(k, box.value.trim()), 250); }; }\n resize();\n }\n function actionsBar(el, actions, record, recordTitle) {\n if (!actions || !actions.length) return;\n const bar = document.createElement(\"div\"); bar.className = \"row actions\";\n for (const a of actions) { const b = document.createElement(\"button\"); b.textContent = L(a.title); b.onclick = () => actionForm(el, a, record, recordTitle); bar.appendChild(b); }\n el.appendChild(bar);\n }\n // A page's own actions (view.actions), at its top: the first is its primary; each opens its form, prefilled from the page's params.\n function pageActions(v) {\n if (!v.actions || !v.actions.length) return null;\n const el = document.createElement(\"div\"); el.className = \"pageacts\";\n const bar = document.createElement(\"div\"); bar.className = \"row\";\n v.actions.forEach((a, i) => { const b = document.createElement(\"button\"); if (i === 0) b.className = \"primary\"; b.textContent = L(a.title); b.onclick = () => actionForm(el, a, null, \"\"); bar.appendChild(b); });\n el.appendChild(bar);\n return el;\n }\n // The app's navigation (view.nav): its sections as a compact menu; a page opens through its own tool (open_<page>), a badge shows its count.\n const badges = {};\n function navBar(v) {\n const sections = (v.nav || []).filter((x) => x && Array.isArray(x.pages) && x.pages.length);\n if (sections.reduce((n, x) => n + x.pages.length, 0) < 2) return;\n const nav = document.createElement(\"nav\"); nav.className = \"nav\"; nav.setAttribute(\"aria-label\", tr(\"pages\"));\n for (const sec of sections) {\n const g = document.createElement(\"div\"); g.className = \"row\";\n if (sec.section) { const h = document.createElement(\"span\"); h.className = \"muted navlabel\"; h.textContent = L(sec.section); g.appendChild(h); }\n for (const pg of sec.pages) {\n const b = document.createElement(\"button\"); b.className = \"navitem\"; b.textContent = L(pg.title);\n if (pg.name === v.page) b.setAttribute(\"aria-current\", \"page\");\n if (pg.badge) { const c = document.createElement(\"span\"); c.className = \"count\"; c.dataset.badge = pg.badge; if (badges[pg.badge] !== undefined) c.textContent = badges[pg.badge]; b.appendChild(c); }\n b.onclick = () => open(pg.tool, {}, b, true);\n g.appendChild(b);\n }\n nav.appendChild(g);\n }\n root.appendChild(nav);\n const tools = [...new Set([...nav.querySelectorAll(\"[data-badge]\")].map((c) => c.dataset.badge))];\n for (const tool of tools) callTool(tool, {}).then((r) => { if (errorOf(r)) return; const d = resultOf(r).data; if (!d || typeof d.value !== \"number\") return; badges[tool] = new Intl.NumberFormat(locale).format(d.value); nav.querySelectorAll('[data-badge=\"' + tool + '\"]').forEach((c) => { c.textContent = badges[tool]; }); resize(); }, (e) => console.warn(\"[${PROTOCOL_ID}] badge \" + tool, e));\n }\n // A change made in the view, told to the model for its next turn (MCP Apps ui/update-model-context: the host keeps the\n // last one). The text is the app's own result text, as the model would have read it from the call.\n const tellModel = (action, r, s) => {\n if (bridge !== \"mcp\") return;\n const said = (r && Array.isArray(r.content) && r.content[0] && typeof r.content[0].text === \"string\") ? r.content[0].text : String(s.message || \"\");\n request(\"ui/update-model-context\", { content: [{ type: \"text\", text: \"The person used «\" + L(action.title) + \"» (\" + action.tool + \") in the app's view: \" + said }], structuredContent: { tool: action.tool, result: s } }, 10000)\n .catch((e) => console.warn(\"[${PROTOCOL_ID}] the host did not take the model context\", e));\n };\n let lastCall = null; let last = null;\n // Where «back» returns: the lists and searches a record was opened from, each with the call that draws it again.\n const trail = [];\n const reload = async () => { if (!lastCall) return; const r = await callTool(lastCall.name, lastCall.args); const e = errorOf(r); if (e) throw new Error(e); render(resultOf(r)); };\n // fresh: a page opened from the navigation starts a new trail («back» returns within a page, not across pages).\n const open = async (name, args, el, fresh) => {\n const from = { s: last, call: lastCall };\n if (el) el.setAttribute(\"aria-busy\", \"true\");\n notice(tr(\"opening\"), \"busy\");\n try { const r = await callTool(name, args); const e = errorOf(r); if (e) return fail(e); const s = resultOf(r); if (!s || !s.view) return fail(tr(\"noData\", name)); if (fresh) trail.length = 0; else if (from.s) trail.push(from); lastCall = { name, args }; notice(null); render(s); }\n catch (e) { fail(e); }\n finally { if (el) el.removeAttribute(\"aria-busy\"); }\n };\n const backBar = () => {\n if (!trail.length) return;\n const prev = trail[trail.length - 1];\n const b = document.createElement(\"button\"); b.className = \"back\"; b.textContent = \"‹ \" + L((prev.s.view && prev.s.view.title) || \"\");\n b.onclick = async () => { trail.pop(); lastCall = prev.call; notice(null); if (prev.call) { try { await reload(); return; } catch {} } render(prev.s); };\n b.dataset.back = \"1\";\n root.appendChild(b);\n };\n\n function recordBox(view, record) {\n const el = document.createElement(\"div\"); el.className = \"box\";\n const title = view.fields.find((f) => f.role === \"title\");\n const named = record[title ? title.name : \"id\"];\n el.innerHTML = \"<h2>\" + esc(named) + \"</h2><dl>\" + view.fields.filter((f) => f.name !== \"id\" && f.role !== \"title\" && record[f.name] !== undefined).map((f) => \"<dt>\" + esc(L(f.label)) + \"</dt><dd>\" + fmt(record[f.name], f) + \"</dd>\").join(\"\") + \"</dl>\";\n actionsBar(el, view.actions, record, named === undefined || named === null ? \"\" : String(named));\n return el;\n }\n function fragmentBox(fr) {\n const el = document.createElement(\"div\"); el.className = \"box\";\n const d = fr.data || {};\n if (fr.state && fr.state !== \"ok\") { el.innerHTML = '<span class=\"muted\">' + esc(tr(fr.state === \"no-access\" ? \"noAccess\" : \"notAvailable\")) + \"</span>\"; return el; }\n if (fr.template === \"record\" && fr.view) return recordBox(fr.view, fr.data);\n let h = fr.title ? \"<h3>\" + esc(L(fr.title)) + \"</h3>\" : \"\";\n if (fr.template === \"stat\") { const v = typeof d.value === \"number\" ? (d.format === \"money\" ? new Intl.NumberFormat(locale, { style: \"currency\", currency: d.currency || \"EUR\" }).format(d.value) : d.format === \"percent\" ? new Intl.NumberFormat(locale, { style: \"percent\" }).format(d.value) : new Intl.NumberFormat(locale).format(d.value)) : d.value; h += '<div class=\"muted\">' + esc(L(d.label)) + '</div><div class=\"stat\">' + esc(v) + \"</div>\" + (d.hint ? '<div class=\"muted\">' + esc(L(d.hint)) + \"</div>\" : \"\"); }\n else if (fr.template === \"card\") h += \"<h2>\" + esc(d.title) + \"</h2>\" + (d.subtitle ? '<div class=\"muted\">' + esc(d.subtitle) + \"</div>\" : \"\") + (d.status ? '<span class=\"badge\">' + esc(L(d.status)) + \"</span>\" : \"\") + \"<dl>\" + (d.fields || []).map((f) => \"<dt>\" + esc(L(f.label)) + \"</dt><dd>\" + esc(f.value) + \"</dd>\").join(\"\") + \"</dl>\";\n else if (fr.template === \"list\") h += (d.items || []).map((i) => \"<div style='padding:6px 0;border-bottom:1px solid var(--line)'><b>\" + esc(i.title) + \"</b>\" + (i.status ? ' <span class=\"badge\">' + esc(L(i.status)) + \"</span>\" : \"\") + (i.subtitle ? '<div class=\"muted\">' + esc(i.subtitle) + \"</div>\" : \"\") + \"</div>\").join(\"\") || '<span class=\"muted\">—</span>';\n else if (fr.template === \"chart\") { const pts = d.points || []; const max = Math.max(1, ...pts.map((p) => Math.abs(Number(p.value) || 0))); h += '<div class=\"bar\">' + pts.map((p) => \"<span>\" + esc(L(p.label)) + '</span><i style=\"width:' + Math.round((Math.abs(Number(p.value) || 0) / max) * 100) + '%\"></i><span class=\"muted\">' + esc(d.format === \"money\" ? new Intl.NumberFormat(locale, { style: \"currency\", currency: d.currency || \"EUR\", maximumFractionDigits: 0 }).format(p.value) : p.value) + \"</span>\").join(\"\") + \"</div>\"; }\n else h += \"<pre>\" + esc(JSON.stringify(d, null, 2)) + \"</pre>\";\n el.innerHTML = h;\n actionsBar(el, fr.actions, null);\n return el;\n }\n function render(s) {\n shown = true; last = s;\n refs = (s && s.refs) || {};\n const v = s && s.view;\n root.innerHTML = \"\";\n if (s && s.error) { root.innerHTML = '<div class=\"box err\">' + esc(L(s.error.message) || s.error.code) + \"</div>\"; return resize(); }\n if (!v) { root.innerHTML = '<div class=\"box muted\">' + esc(JSON.stringify(s)) + \"</div>\"; return resize(); }\n if (v.kind === \"list\") {\n navBar(v);\n const box = document.createElement(\"div\"); box.className = \"box\";\n const cols = v.columns;\n box.innerHTML = \"<h2>\" + esc(L(v.title)) + (typeof s.total === \"number\" ? ' <span class=\"muted\">· ' + esc(s.total) + \"</span>\" : \"\") + \"</h2>\" +\n \"<table><thead><tr>\" + cols.map((c) => { const on = v.sort && v.sort.field === c.name ? v.sort.dir : null;\n // A sortable column's header sorts by it: first ascending, again descending. The app checks the field (and refuses one the caller may not see).\n return c.sort && v.tool ? '<th class=\"sort\" tabindex=\"0\" role=\"columnheader\" data-sort=\"' + esc(c.name) + '\" aria-sort=\"' + (on === \"asc\" ? \"ascending\" : on === \"desc\" ? \"descending\" : \"none\") + '\" title=\"' + esc(tr(\"sortBy\", L(c.label))) + '\">' + esc(L(c.label)) + (on ? (on === \"asc\" ? \" ▲\" : \" ▼\") : \"\") + \"</th>\" : \"<th>\" + esc(L(c.label)) + \"</th>\"; }).join(\"\") + \"</tr></thead><tbody>\" +\n (s.rows || []).map((r, i) => '<tr class=\"link\" tabindex=\"0\" data-i=\"' + i + '\">' + cols.map((c) => \"<td\" + (c.role === \"amount\" || c.type === \"number\" ? ' class=\"num\"' : \"\") + \">\" + fmt(r[c.name], c) + \"</td>\").join(\"\") + \"</tr>\").join(\"\") +\n \"</tbody></table>\" + ((s.rows || []).length ? \"\" : '<p class=\"muted\">—</p>');\n if (v.tool && !lastCall) lastCall = { name: v.tool, args: v.args || {} };\n const acts = pageActions(v); if (acts) box.insertBefore(acts, box.querySelector(\"table\"));\n box.querySelectorAll(\"tr.link\").forEach((row) => { const go = () => open(v.getTool, { id: s.rows[Number(row.dataset.i)].id }, row); row.onclick = go; row.onkeydown = (e) => { if (e.key === \"Enter\" || e.key === \" \") { e.preventDefault(); go(); } }; });\n box.querySelectorAll(\"th.sort\").forEach((th) => { const go = async () => { const field = th.dataset.sort; const args = Object.assign({}, v.args || {}, { sort: field, dir: v.sort && v.sort.field === field && v.sort.dir === \"asc\" ? \"desc\" : \"asc\" }); delete args.cursor;\n notice(tr(\"opening\"), \"busy\"); try { const r = await callTool(v.tool, args); const e = errorOf(r); if (e) return fail(e); lastCall = { name: v.tool, args }; notice(null); render(resultOf(r)); } catch (e) { fail(e); } };\n th.onclick = go; th.onkeydown = (e) => { if (e.key === \"Enter\" || e.key === \" \") { e.preventDefault(); go(); } }; });\n if (s.next && v.tool) { const more = document.createElement(\"button\"); more.textContent = \"…\"; more.style.marginTop = \"8px\"; more.onclick = async () => { notice(tr(\"opening\"), \"busy\"); try { const r = await callTool(v.tool, Object.assign({}, v.args || {}, { cursor: s.next })); const e = errorOf(r); if (e) return fail(e); notice(null); render(resultOf(r)); } catch (e) { fail(e); } }; box.appendChild(more); }\n root.appendChild(box);\n } else if (v.kind === \"record\") {\n if (v.tool && s.record && s.record.id !== undefined) lastCall = { name: v.tool, args: { id: s.record.id } };\n backBar();\n root.appendChild(recordBox(v, s.record));\n } else if (v.kind === \"fragment\") {\n root.appendChild(fragmentBox(Object.assign({ title: v.title }, s)));\n } else if (v.kind === \"dashboard\") {\n if (v.tool && !lastCall) lastCall = { name: v.tool, args: v.args || {} };\n navBar(v);\n const h = document.createElement(\"h2\"); h.textContent = L(v.title); root.appendChild(h);\n const acts = pageActions(v); if (acts) root.appendChild(acts);\n const g = document.createElement(\"div\"); g.className = \"grid\"; for (const fr of s.fragments || []) g.appendChild(fragmentBox(fr)); root.appendChild(g);\n } else if (v.kind === \"search\") {\n const box = document.createElement(\"div\"); box.className = \"box\";\n box.innerHTML = (s.results || []).map((r, i) => \"<div class='hit' data-i='\" + i + \"' style='padding:6px 0;border-bottom:1px solid var(--line);cursor:pointer'><b>\" + esc(r.title) + \"</b> <span class='muted'>\" + esc(L(r.entityLabel || \"\")) + \"</span>\" + (r.status ? ' <span class=\"badge\">' + esc(L(r.status)) + \"</span>\" : \"\") + (r.subtitle ? \"<div class='muted'>\" + esc(r.subtitle) + \"</div>\" : \"\") + \"</div>\").join(\"\") || '<span class=\"muted\">—</span>';\n box.querySelectorAll(\".hit\").forEach((el) => el.onclick = () => open(\"fetch\", { id: s.results[Number(el.dataset.i)].id }, el));\n root.appendChild(box);\n }\n resize();\n }\n const applyContext = (ctx) => { if (!ctx) return; if (ctx.theme) document.documentElement.dataset.theme = ctx.theme; if (ctx.locale) locale = ctx.locale; const vars = ctx.styles && ctx.styles.variables; if (vars) for (const [k, v] of Object.entries(vars)) if (v) document.documentElement.style.setProperty(k, v); };\n window.addEventListener(\"message\", (e) => {\n if (e.source !== window.parent) return;\n const m = e.data; if (!m || m.jsonrpc !== \"2.0\") return;\n if (m.id !== undefined && pending.has(m.id) && !m.method) { const p = pending.get(m.id); pending.delete(m.id); return m.error ? p.reject(new Error(m.error.message || \"error\")) : p.resolve(m.result); }\n // The result of the call that opened the view, once. Hosts send tool-result again for the view's own calls (MCP Apps,\n // interactive phase) and may repeat it: the view already drew those from the call's answer, and the person's place\n // (a record opened from the list, the way back) is never replaced by an older result.\n if (m.method === \"ui/notifications/tool-result\") { if (shown) return; const s = resultOf(m.params); if ((s && s.view) || !BOOT) render(s); return; }\n // A new language: everything is drawn again in it, the app's labels from the locales its results sent (the data stay as they are: asking again would answer in the token's language).\n if (m.method === \"ui/notifications/host-context-changed\") { const before = locale; applyContext(m.params); if (locale !== before && last) render(last); return; }\n if (m.method === \"ui/resource-teardown\" && m.id !== undefined) post({ jsonrpc: \"2.0\", id: m.id, result: {} });\n });\n const boot = async () => {\n if (BOOT && !shown) { lastCall = { name: BOOT.tool, args: BOOT.args || {} }; try { const r = await callTool(BOOT.tool, BOOT.args || {}); const e = errorOf(r); if (e) { root.innerHTML = '<div class=\"box err\">' + esc(e) + \"</div>\"; resize(); } else render(resultOf(r)); } catch (e) { root.innerHTML = '<div class=\"box err\">' + esc(e.message || e) + \"</div>\"; resize(); } }\n };\n // ChatGPT's window.openai: the opening result (toolOutput = structuredContent) and its _meta apart (toolResponseMetadata:\n // the MCP result envelope, the _meta under mcp_tool_result / call_tool_result), its locale. openai:set_globals carries\n // only what changed (layout, theme, widget state…): it never replaces what the person opened since.\n const openaiMeta = (m) => { if (!m || typeof m !== \"object\") return null; for (const c of [m, m._meta, m.mcp_tool_result && m.mcp_tool_result._meta, m.call_tool_result && m.call_tool_result._meta]) if (c && typeof c === \"object\" && c[\"${META_KEY}\"]) return c; return null; };\n const fromOpenai = (g) => {\n if (!g || typeof g !== \"object\") return;\n const before = locale; if (typeof g.locale === \"string\" && g.locale) locale = g.locale;\n const meta = openaiMeta(g.toolResponseMetadata); if (meta) learn({ _meta: meta });\n if (!shown && g.toolOutput && typeof g.toolOutput === \"object\") return render(g.toolOutput);\n if (shown && (locale !== before || meta) && last) render(last);\n };\n if (window.openai) fromOpenai(window.openai);\n window.addEventListener(\"openai:set_globals\", (e) => fromOpenai(e && e.detail && e.detail.globals));\n ready.then(() => setTimeout(boot, 250), (e) => { if (!shown) fail(e); });\n new ResizeObserver(resize).observe(document.body);\n})();\n`\n\n/** The view document; `boot` names the tool a page calls for its own data when no tool result opens it. */\nexport function viewHtml(title: string, boot: { tool: string; args?: Record<string, unknown> } | null = null): string {\n const bootJson = JSON.stringify(boot).replace(/</g, \"\\\\u003c\")\n return `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>${title.replace(/[<&]/g, \"\")}</title><style>${STYLE}</style></head><body><div id=\"status\" role=\"status\" aria-live=\"polite\" hidden></div><div id=\"root\"><div class=\"box muted\">…</div></div><script>${SCRIPT.replace(\"__BOOT__\", bootJson)}</script></body></html>`\n}\n\nconst URL_PAGE_SCRIPT = `\n(() => {\n const PAGE = __PAGE__;\n const frame = document.getElementById(\"page\"); const statusLine = document.getElementById(\"status\");\n let locale = navigator.language || \"en\";\n const STR = {\n en: { signingIn: \"Signing in…\", notOpened: \"The page did not open: this host may not let the view sign in to an embedded page.\", noBridge: \"This host does not connect the view to the app\", noAnswer: \"The host did not answer ({n}).\", refused: \"The host refused the call ({n}).\" },\n it: { signingIn: \"Accesso in corso…\", notOpened: \"La pagina non si è aperta: questo host potrebbe non permettere alla vista di accedere a una pagina incorporata.\", noBridge: \"Questo host non collega la vista all'app\", noAnswer: \"L'host non ha risposto ({n}).\", refused: \"L'host ha rifiutato la chiamata ({n}).\" },\n es: { signingIn: \"Iniciando sesión…\", notOpened: \"La página no se abrió: puede que este host no permita a la vista iniciar sesión en una página incrustada.\", noBridge: \"Este host no conecta la vista con la app\", noAnswer: \"El host no respondió ({n}).\", refused: \"El host rechazó la llamada ({n}).\" },\n fr: { signingIn: \"Connexion…\", notOpened: \"La page ne s'est pas ouverte : cet hôte ne permet peut-être pas à la vue de se connecter à une page intégrée.\", noBridge: \"Cet hôte ne relie pas la vue à l'app\", noAnswer: \"L'hôte n'a pas répondu ({n}).\", refused: \"L'hôte a refusé l'appel ({n}).\" },\n de: { signingIn: \"Anmeldung…\", notOpened: \"Die Seite wurde nicht geöffnet: Dieser Host erlaubt der Ansicht vielleicht nicht, sich bei einer eingebetteten Seite anzumelden.\", noBridge: \"Dieser Host verbindet die Ansicht nicht mit der App\", noAnswer: \"Der Host hat nicht geantwortet ({n}).\", refused: \"Der Host hat den Aufruf abgelehnt ({n}).\" },\n };\n const tr = (k, n) => String((STR[String(locale).split(\"-\")[0].toLowerCase()] || STR.en)[k]).replace(\"{n}\", n === undefined ? \"\" : n);\n const notice = (text, error) => { statusLine.hidden = !text; statusLine.textContent = text || \"\"; statusLine.className = error ? \"error\" : \"\"; statusLine.setAttribute(\"role\", error ? \"alert\" : \"status\"); };\n let nextId = 1; const pending = new Map();\n const post = (m) => window.parent.postMessage(m, \"*\");\n const request = (method, params, wait) => new Promise((resolve, reject) => { const id = nextId++; pending.set(id, { resolve, reject }); post({ jsonrpc: \"2.0\", id, method, params }); setTimeout(() => { if (pending.delete(id)) reject(new Error(tr(\"noAnswer\", method + (params && params.name ? \" \" + params.name : \"\")))); }, wait); });\n window.addEventListener(\"message\", (e) => {\n if (e.source !== window.parent) return;\n const m = e.data; if (!m || m.jsonrpc !== \"2.0\") return;\n if (m.id !== undefined && !m.method && pending.has(m.id)) { const p = pending.get(m.id); pending.delete(m.id); return m.error ? p.reject(new Error(m.error.message || \"error\")) : p.resolve(m.result); }\n if (m.method === \"ui/resource-teardown\" && m.id !== undefined) post({ jsonrpc: \"2.0\", id: m.id, result: {} });\n });\n let bridge = null;\n const ready = request(\"ui/initialize\", { protocolVersion: \"${MCP_APPS_PROTOCOL_VERSION}\", appInfo: { name: \"${PROTOCOL_ID}-url-page\", version: \"1.0.0\" }, appCapabilities: {} }, 10000).then(\n (r) => { bridge = \"mcp\"; if (r && r.hostContext && r.hostContext.locale) locale = r.hostContext.locale; post({ jsonrpc: \"2.0\", method: \"ui/notifications/initialized\", params: {} }); post({ jsonrpc: \"2.0\", method: \"ui/notifications/size-changed\", params: { height: 720 } }); },\n (e) => { if (window.openai && typeof window.openai.callTool === \"function\") { bridge = \"openai\"; if (window.openai.locale) locale = window.openai.locale; return; } throw new Error(tr(\"noBridge\") + \" (\" + String((e && e.message) || e) + \")\"); });\n // The ticket (spec §5.1), asked for the viewer over the host's bridge, as the view's other calls.\n const callTool = async (name, args) => {\n await ready;\n let r;\n try { r = bridge === \"mcp\" ? await request(\"tools/call\", { name, arguments: args }, 30000) : await window.openai.callTool(name, args); }\n catch (e) { const why = String((e && e.message) || e); throw new Error(why.startsWith(tr(\"noAnswer\", \"\")) ? why : tr(\"refused\", name) + \" \" + why); }\n const s = r && r.structuredContent;\n if (!r || r.isError || !s) throw new Error((s && s.error && s.error.message) || (r && r.content && r.content[0] && r.content[0].text) || tr(\"refused\", name));\n return s;\n };\n const open = async () => {\n if (!PAGE.embed) { frame.src = PAGE.url; return; }\n notice(tr(\"signingIn\"));\n // location.origin is this document's: the one that posts the ticket, so the one the ticket is for.\n const t = await callTool(PAGE.embed.tool, { page: PAGE.embed.page, origin: location.origin });\n // A form posted into the frame: the ticket never sits in a URL, the history or a Referer.\n const form = document.createElement(\"form\"); form.method = \"post\"; form.action = t.action; form.target = frame.name; form.hidden = true;\n const field = document.createElement(\"input\"); field.type = \"hidden\"; field.name = t.field; field.value = t.ticket; form.appendChild(field);\n document.body.appendChild(form);\n const late = setTimeout(() => notice(tr(\"notOpened\"), true), 20000);\n frame.addEventListener(\"load\", () => { clearTimeout(late); notice(null); }, { once: true });\n form.submit(); form.remove();\n };\n ready.then(open).catch((e) => notice(String((e && e.message) || e), true));\n})();\n`\n\n/**\n * A custom page whose content is a site: an iframe in the view, the site's origin allowed as a frame (MCP Apps CSP\n * `frameDomains`). A page on the app's own site (`embed`) is opened signed in: the view asks the app for a ticket\n * (`clegra_embed`, for this document's origin) over the host's bridge and posts it into the frame (spec §5.1).\n * A page on another site is framed as it is.\n */\nexport function urlPageHtml(title: string, url: string, embed: { tool: string; page: string } | null): string {\n const page = JSON.stringify({ url, embed }).replace(/</g, \"\\\\u003c\")\n const name = `${PROTOCOL_ID}-page`\n return `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>${title.replace(/[<&]/g, \"\")}</title><style>html,body{margin:0;height:100%;font:13px system-ui,sans-serif}iframe{border:0;width:100%;height:100vh;display:block}#status{position:fixed;top:8px;left:8px;right:8px;padding:6px 10px;border-radius:8px;background:#f5f5f7;color:#6e6e73;border:1px solid #e5e5ea}#status[hidden]{display:none}#status.error{color:#c62828;border-color:#c62828}</style></head><body><div id=\"status\" role=\"status\" aria-live=\"polite\" hidden></div><iframe id=\"page\" name=\"${name}\" sandbox=\"allow-scripts allow-forms allow-same-origin allow-popups\" referrerpolicy=\"no-referrer\" title=\"${title.replace(/\"/g, \"\")}\"></iframe><script>${URL_PAGE_SCRIPT.replace(\"__PAGE__\", () => page)}</script></body></html>`\n}\n"]}
|
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
# Quickstart
|
|
2
|
+
|
|
3
|
+
> A Clegra app is an app that Clegra draws natively and that is also a plain MCP server for ChatGPT, Claude and any
|
|
4
|
+
> MCP client. One package, `@clegra/sdk` (ESM JavaScript with its
|
|
5
|
+
> types, Node 20+; `npm i @clegra/sdk@next zod`). Its design library is the separate package `@clegra/ui` (optional). For a Next.js app that already has data and a sign-in: **five
|
|
6
|
+
> minutes to see it, a day to ship it.**
|
|
7
|
+
|
|
8
|
+
## Next.js in 5 minutes
|
|
9
|
+
|
|
10
|
+
In an existing Next.js App Router app (`app/` or `src/app/`):
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm i @clegra/sdk zod # before the first release: npm i ./clegra-0.1.0.tgz zod (the tarball of `npm pack`)
|
|
14
|
+
npx @clegra/sdk init # --dry-run prints what it would do; --ui adds @clegra/ui, Clegra's design system
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
```text
|
|
18
|
+
clegra init: Next.js 16.4.6, App Router in app/, TypeScript, alias @/*, next.config.ts
|
|
19
|
+
|
|
20
|
+
create clegra.ts (app "acme-tasks": sample tasks, one action, one page; TODOs for your data and sign-in)
|
|
21
|
+
create app/api/clegra/[...path]/route.ts (imports { app } from "@/clegra")
|
|
22
|
+
edit next.config.ts (wrapped the exported config with withClegra)
|
|
23
|
+
create .env.local (CLEGRA_LOCAL_TOKEN: a random local bearer, refused in production)
|
|
24
|
+
|
|
25
|
+
Next:
|
|
26
|
+
1. npm run dev (then http://localhost:3000/.well-known/clegra.json is the manifest, http://localhost:3000/mcp the MCP server)
|
|
27
|
+
2. npx @clegra/sdk check http://localhost:3000 --token <the token>
|
|
28
|
+
3. MCP Inspector: npx @modelcontextprotocol/inspector, Streamable HTTP, http://localhost:3000/mcp, header Authorization: Bearer <the token>
|
|
29
|
+
4. A day to ship: …
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
What it writes:
|
|
33
|
+
|
|
34
|
+
- **`clegra.ts`**: a working `defineApp` with one entity (`task`) on sample data kept in the file, scoped by
|
|
35
|
+
`ctx.installation`, one confirmed action (`complete`) and one list page. Two `TODO`s mark where your database and
|
|
36
|
+
your sign-in go.
|
|
37
|
+
- **`app/api/clegra/[...path]/route.ts`**: `export const { GET, POST, DELETE, OPTIONS } = toNextHandlers(app)`.
|
|
38
|
+
- **`next.config`** wrapped in `withClegra(…)`. It adds rewrites for `/mcp`, `/.well-known/clegra.json` and the
|
|
39
|
+
OAuth metadata paths. init edits the file only when the edit is certain (one
|
|
40
|
+
`export default <expression>` line). Otherwise it prints the edit for you to make.
|
|
41
|
+
- **`.env.local`**: `CLEGRA_LOCAL_TOKEN`, a random bearer.
|
|
42
|
+
|
|
43
|
+
init never overwrites a file. Running it twice only prints `skip`s. It warns about what would get in the way: a
|
|
44
|
+
`proxy.ts` (or `middleware.ts`) that would block `/mcp`, `basePath` or `trailingSlash: true` (which `withClegra`
|
|
45
|
+
refuses), a `.gitignore` that doesn't cover `.env.local`, and missing `@clegra/sdk`/`zod`.
|
|
46
|
+
|
|
47
|
+
Then:
|
|
48
|
+
|
|
49
|
+
```sh
|
|
50
|
+
npm run dev
|
|
51
|
+
npx @clegra/sdk check http://localhost:3000 --token <CLEGRA_LOCAL_TOKEN>
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
- **The MCP Inspector**: `npx @modelcontextprotocol/inspector`, transport Streamable HTTP, URL
|
|
55
|
+
`http://localhost:3000/mcp`, header `Authorization: Bearer <CLEGRA_LOCAL_TOKEN>`. You see `task_list`,
|
|
56
|
+
`task_get`, `task_complete`, `search`, `fetch`, `open_tasks` and `clegra_resolve`.
|
|
57
|
+
- **`clegra check`** runs every check. All of them pass but one: `auth.mcp — protected-resource metadata names no
|
|
58
|
+
authorization server`. That is the honest state of a fresh app. MCP clients can't sign anyone in until
|
|
59
|
+
`authorizationServers` names your sign-in, which is the first job of day one.
|
|
60
|
+
|
|
61
|
+
**The local bearer, and why it is safe.** The generated `resolve` accepts `CLEGRA_LOCAL_TOKEN` only when
|
|
62
|
+
`NODE_ENV` is not `production`. `next build`, `next start` and every deployment (Vercel previews included) set
|
|
63
|
+
`production`, and then the bearer is refused whatever the environment holds. In production without
|
|
64
|
+
`CLEGRA_PUBLIC_URL`, every request gets a `500 misconfigured` that names the missing setting. The token is random
|
|
65
|
+
per project and lives in `.env.local`, which Next's `.gitignore` keeps out of git. The SDK's own dev sign-in
|
|
66
|
+
(`auth.dev`, a sign-in page for test people) does **not** exist under Next: it trusts only loopback callers, and a
|
|
67
|
+
route handler can't know the caller's address, so `toNextHandlers` refuses it. `auth.anonymous` (no token at all) is
|
|
68
|
+
not used either. It has no production guard, and with it nobody ever gets a `401`.
|
|
69
|
+
|
|
70
|
+
## A day to ship
|
|
71
|
+
|
|
72
|
+
Work through the TODOs in `clegra.ts`:
|
|
73
|
+
|
|
74
|
+
1. **Your data in `get`, `list` and `run`.** Call the functions your pages already use, with `ctx.installation` as
|
|
75
|
+
the tenant. [Your data layer](#your-data-layer) below shows a `list` over SQL.
|
|
76
|
+
2. **Your sign-in in `auth.resolve` and `auth.authorizationServers`.** Your auth library is the OAuth authorization
|
|
77
|
+
server. `resolve` verifies its access tokens and names the caller. Recipes for better-auth, Clerk, Auth0 and
|
|
78
|
+
WorkOS are in [auth.md](auth.md). Keep the `localCaller` line if you like; it never answers in production.
|
|
79
|
+
3. **The public address.** Set `CLEGRA_PUBLIC_URL=https://app.example.com` (an origin only) in each environment.
|
|
80
|
+
`auth.resource` is then `https://app.example.com/mcp`, the only audience tokens are accepted for. Without it,
|
|
81
|
+
production answers `500 misconfigured`. A client can send `x-forwarded-host`, so never rely on it. On Vercel,
|
|
82
|
+
previews have other hosts: give each environment its own value.
|
|
83
|
+
4. **A shared store.** On serverless or with several instances, use
|
|
84
|
+
`store: new SqlStore((text, params) => pool.query(text, params))`. It keeps write results (idempotency) and
|
|
85
|
+
one-time token ids in your Postgres (and the runs of `later` actions, below). `SqlStore.schema()` gives its
|
|
86
|
+
tables (`clegra_store`, `clegra_store_later`) for a migration, `CREATE … IF NOT EXISTS`: run it as a migration,
|
|
87
|
+
never at startup, and again in a new migration when you upgrade.
|
|
88
|
+
5. **`clegra check` in CI.** Get a token for a test user through the real OAuth flow, then run
|
|
89
|
+
`CLEGRA_TOKEN=… npx @clegra/sdk check https://preview.example.com`. The exit code is 0 when conformant, 1 when a
|
|
90
|
+
check failed, and 3 when there was no token (only the public checks ran).
|
|
91
|
+
6. **Connect Claude and ChatGPT.** They need https: your deployment, or `cloudflared tunnel --url
|
|
92
|
+
http://localhost:3000` locally. Note that a tunnel's host is not `CLEGRA_PUBLIC_URL`, and your authorization
|
|
93
|
+
server must also be reachable there. Add `https://app.example.com/mcp` as a connector and sign in with your own
|
|
94
|
+
sign-in. Lists, records and dashboards show as MCP Apps views. Clients identify themselves with a Client ID
|
|
95
|
+
Metadata Document, so your authorization server must support CIMD (see [auth.md](auth.md)).
|
|
96
|
+
7. **Embedded pages.** A page `{ title, url: "/embed/stock" }` frames a real page of your app inside hosts. The
|
|
97
|
+
frame is cross-site there, so your session cookie never reaches it: the host signs the viewer in with a
|
|
98
|
+
one-minute ticket instead (spec §5.1). Three pieces:
|
|
99
|
+
- `embed: { frameAncestors: ["https://app.clegra.com", "https://chatgpt.com", …], secret }` in `defineApp`
|
|
100
|
+
(`secret` default `CLEGRA_EMBED_SECRET`, 32+ characters; the hosts that may frame `/embed/*`);
|
|
101
|
+
- `proxy.ts`: `export const proxy = embedProxy(app)` with `export const config = { matcher: "/embed/:path*" }`
|
|
102
|
+
(the ticket exchange at `POST /embed/_ticket`, `frame-ancestors` on every embed response);
|
|
103
|
+
- in the page: `const caller = await getEmbedCaller(app, "stock")` (null: show "open it from the app"), then
|
|
104
|
+
scope by `caller.installation`, check `caller.can(…)`. Give `/embed/*` a bare layout.
|
|
105
|
+
|
|
106
|
+
What needs https: every remote MCP client (Claude, ChatGPT), and any authorization server they reach. What doesn't:
|
|
107
|
+
the Inspector, `clegra check` and workspace hosts on your machine.
|
|
108
|
+
|
|
109
|
+
## Without Next.js: one file, `listen`
|
|
110
|
+
|
|
111
|
+
The same object runs on Node's own HTTP server. There, the SDK's dev sign-in works, because the socket tells it
|
|
112
|
+
the caller's address:
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
// app.ts
|
|
116
|
+
import { AppError, defineApp } from "@clegra/sdk"
|
|
117
|
+
import { z } from "zod"
|
|
118
|
+
|
|
119
|
+
type Note = { id: string; title: string; status: "open" | "done" }
|
|
120
|
+
const notes = new Map<string, Map<string, Note>>() // one map per installation
|
|
121
|
+
const notesOf = (installation: string) => {
|
|
122
|
+
if (!notes.has(installation)) notes.set(installation, new Map([["n1", { id: "n1", title: "Call Ada", status: "open" }]]))
|
|
123
|
+
return notes.get(installation)!
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export default defineApp({
|
|
127
|
+
name: "notes",
|
|
128
|
+
title: { en: "Notes", it: "Note" },
|
|
129
|
+
version: "1.0.0",
|
|
130
|
+
auth: { dev: true }, // local sign-in page: loopback callers only, refused in production
|
|
131
|
+
|
|
132
|
+
permissions: { "notes.edit": { label: "Edit notes", default: true } },
|
|
133
|
+
|
|
134
|
+
entities: {
|
|
135
|
+
note: {
|
|
136
|
+
label: "Note",
|
|
137
|
+
plural: "Notes",
|
|
138
|
+
schema: z.object({
|
|
139
|
+
id: z.string(),
|
|
140
|
+
title: z.string().meta({ role: "title", label: "Title", search: true }),
|
|
141
|
+
status: z.enum(["open", "done"]).meta({ role: "status", label: "Status", filter: true }),
|
|
142
|
+
}),
|
|
143
|
+
get: (id, ctx) => notesOf(ctx.installation).get(id) ?? null,
|
|
144
|
+
list: (q, ctx) => {
|
|
145
|
+
let rows = [...notesOf(ctx.installation).values()]
|
|
146
|
+
if (typeof q.filters.status === "string") rows = rows.filter((n) => n.status === q.filters.status)
|
|
147
|
+
// q.textFields: the search fields this caller may see; search in those only
|
|
148
|
+
if (q.text) rows = rows.filter((n) => (q.textFields ?? []).some((f) => String(n[f as "title"] ?? "").toLowerCase().includes(q.text!.toLowerCase())))
|
|
149
|
+
return { rows, total: rows.length }
|
|
150
|
+
},
|
|
151
|
+
},
|
|
152
|
+
},
|
|
153
|
+
|
|
154
|
+
actions: {
|
|
155
|
+
close: {
|
|
156
|
+
on: "note", // a record action: `note` below is the typed record
|
|
157
|
+
title: "Close",
|
|
158
|
+
input: z.object({}), // always given; z.object({}) for none
|
|
159
|
+
permission: "notes.edit",
|
|
160
|
+
expose: { plain: true }, // writes reach ChatGPT/Claude only when you opt in
|
|
161
|
+
run: (_input, ctx, note) => {
|
|
162
|
+
if (note.status === "done") throw new AppError("conflict", "Already closed.")
|
|
163
|
+
notesOf(ctx.installation).set(note.id, { ...note, status: "done" })
|
|
164
|
+
return { message: `${note.title} closed.`, record: note.id }
|
|
165
|
+
},
|
|
166
|
+
},
|
|
167
|
+
},
|
|
168
|
+
|
|
169
|
+
fragments: {
|
|
170
|
+
open_count: {
|
|
171
|
+
title: "Open notes",
|
|
172
|
+
description: "How many notes are open",
|
|
173
|
+
params: z.object({}), // always given too
|
|
174
|
+
template: "stat",
|
|
175
|
+
data: (_p, ctx) => ({ label: "open", value: [...notesOf(ctx.installation).values()].filter((n) => n.status === "open").length }),
|
|
176
|
+
},
|
|
177
|
+
},
|
|
178
|
+
|
|
179
|
+
pages: {
|
|
180
|
+
notes: { title: "Notes", list: "note", columns: ["title", "status"] },
|
|
181
|
+
home: { title: "Home", dashboard: [{ type: "open_count", params: {} }] },
|
|
182
|
+
},
|
|
183
|
+
|
|
184
|
+
agents: {
|
|
185
|
+
helper: { title: "Helper", description: "Finds and closes notes", instructions: "Help with notes.", uses: ["note", "close"] },
|
|
186
|
+
},
|
|
187
|
+
})
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
// main.ts
|
|
192
|
+
import { listen } from "@clegra/sdk/node"
|
|
193
|
+
import app from "./app"
|
|
194
|
+
await listen(app, { port: 3920 }) // MCP at /mcp, manifest at /.well-known/clegra.json
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
`npx tsx main.ts` prints the dev sign-in code. A wrong name anywhere (a permission, an entity, an action) fails
|
|
198
|
+
here, at start, not at the first call. In the Inspector (`http://127.0.0.1:3920/mcp`) sign in with the code. A
|
|
199
|
+
client identifies itself with a Client ID Metadata Document or registers dynamically; in dev both work with nothing
|
|
200
|
+
to set up.
|
|
201
|
+
|
|
202
|
+
Three things you get by saying them in the schema:
|
|
203
|
+
|
|
204
|
+
- **Sorting**: `.meta({ sort: true })` on a field makes its column sortable in every host (a header to click, `sort`
|
|
205
|
+
and `dir` on the list tool). Your `list` gets `q.sort = { field, dir }`, already checked: order by it.
|
|
206
|
+
- **References**: `ref("folder")` in an entity or in an action's `input`. Lists and records show the folder's title,
|
|
207
|
+
forms offer a picker over folders, a model reads `{ id, title }`. You only ever handle the id.
|
|
208
|
+
- **Forms**: an action's `input` is its form. Required fields are marked, `min`, `max` and dates are checked before
|
|
209
|
+
sending, and what your schema refuses comes back per field (`error.fields`) in the caller's language. Add
|
|
210
|
+
`.meta({ label, currency, labels })` for the words and the money.
|
|
211
|
+
|
|
212
|
+
## Pages people use every day
|
|
213
|
+
|
|
214
|
+
The same app, with what makes it a place to work in rather than a list (all optional; [spec §5.2, §4.2, §11–§13](spec.md)):
|
|
215
|
+
|
|
216
|
+
```ts
|
|
217
|
+
actions: {
|
|
218
|
+
add: {
|
|
219
|
+
title: "New note",
|
|
220
|
+
input: z.object({ title: z.string() }),
|
|
221
|
+
permission: "notes.edit",
|
|
222
|
+
run: (input, ctx) => {
|
|
223
|
+
const id = crypto.randomUUID()
|
|
224
|
+
notesOf(ctx.installation).set(id, { id, title: input.title, status: "open" })
|
|
225
|
+
return { message: `${input.title} added.`, record: id }
|
|
226
|
+
},
|
|
227
|
+
},
|
|
228
|
+
remind: { // run by a schedule: no required input, not confirm "always"
|
|
229
|
+
title: "Remind about open notes",
|
|
230
|
+
input: z.object({}),
|
|
231
|
+
readOnly: true,
|
|
232
|
+
run: (_input, ctx) => {
|
|
233
|
+
const open = [...notesOf(ctx.installation).values()].filter((n) => n.status === "open").length
|
|
234
|
+
if (open) ctx.notify({ type: "reminder", title: `${open} notes are open`, to: { permission: "notes.edit" } }) // no person in a schedule: say `to`
|
|
235
|
+
return { message: `${open} open.` }
|
|
236
|
+
},
|
|
237
|
+
},
|
|
238
|
+
archive_on: { // «approve now, act later»: confirmed now, runs at `when`
|
|
239
|
+
title: "Archive the done notes",
|
|
240
|
+
input: z.object({ when: z.iso.datetime() }),
|
|
241
|
+
permission: "notes.edit",
|
|
242
|
+
later: { at: "when", window: 60 },
|
|
243
|
+
run: (_input, ctx) => {
|
|
244
|
+
for (const n of notesOf(ctx.installation).values()) if (n.status === "done") notesOf(ctx.installation).delete(n.id)
|
|
245
|
+
return { message: "Archived." }
|
|
246
|
+
},
|
|
247
|
+
},
|
|
248
|
+
},
|
|
249
|
+
pages: {
|
|
250
|
+
notes: { title: "Notes", list: "note", columns: ["title", "status"], actions: ["add"], badge: "open_count" },
|
|
251
|
+
home: { title: "Home", dashboard: [{ type: "open_count", params: {} }] },
|
|
252
|
+
},
|
|
253
|
+
nav: [{ section: "Notes", pages: ["home", "notes"] }],
|
|
254
|
+
schedules: { morning: { action: "remind", every: 1440 } },
|
|
255
|
+
notifications: { reminder: { label: "Open notes reminder" } },
|
|
256
|
+
lifecycle: {
|
|
257
|
+
export: (ctx) => ({ contentType: "application/json", body: JSON.stringify([...notesOf(ctx.installation).values()]) }),
|
|
258
|
+
delete: (ctx) => {
|
|
259
|
+
const n = notesOf(ctx.installation).size
|
|
260
|
+
notes.delete(ctx.installation)
|
|
261
|
+
return { counts: { notes: n } }
|
|
262
|
+
},
|
|
263
|
+
},
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
- **Page actions and badges**: «New note» is the notes page's primary button, opening its form; the open count shows
|
|
267
|
+
next to «Notes» in the navigation. ChatGPT and Claude see the same in the generated view.
|
|
268
|
+
- **Schedules** run as the installation, with nobody at the screen: Clegra calls `remind` once a day. A write that
|
|
269
|
+
needs a confirmation can't be scheduled; that is what `later` is for.
|
|
270
|
+
- **Later**: the person confirms «Archive the done notes at 18:00» once; the SDK keeps the confirmed call and runs it
|
|
271
|
+
at that time, as them, or tells them it did not run. It needs a store with later runs (`MemoryStore`, the default,
|
|
272
|
+
or `SqlStore`).
|
|
273
|
+
- **Lifecycle**: when an administrator uninstalls the app, Clegra offers to export the data and delete them in 30
|
|
274
|
+
days, or to delete them now.
|
|
275
|
+
|
|
276
|
+
## Test it
|
|
277
|
+
|
|
278
|
+
```ts
|
|
279
|
+
import { installationClient, testClient } from "@clegra/sdk/testing"
|
|
280
|
+
import app from "./app"
|
|
281
|
+
|
|
282
|
+
const plain = await testClient(app, { permissions: "all" }) // as ChatGPT would call
|
|
283
|
+
await plain.call("note_list", { status: "open" })
|
|
284
|
+
const host = await testClient(app, { permissions: "all", host: "workspace" })
|
|
285
|
+
await host.confirmed("note_close", { id: "n1" }) // call id + confirmation proof
|
|
286
|
+
await host.confirmed("archive_on", { when: "2026-12-01T17:00:00Z" }) // stored: { data: { later: { id, at, until } } }
|
|
287
|
+
|
|
288
|
+
const installation = await installationClient(app) // the installation itself: no person
|
|
289
|
+
await installation.schedule("morning") // as the host runs the schedule
|
|
290
|
+
await installation.runLater() // the due later runs
|
|
291
|
+
const { file } = await installation.exportData() // clegra_export, read back
|
|
292
|
+
await installation.call("clegra_delete")
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
`testClient` signs with dev tokens, so it needs `auth: { dev: true }` on the app it tests. Alternatively, pass
|
|
296
|
+
`token` with a bearer your own `resolve` accepts, which is how the Next examples test their real auth. Then run the conformance checks ([spec §8](spec.md#8-conformance)):
|
|
297
|
+
`npx @clegra/sdk check <url> --token <bearer>`.
|
|
298
|
+
|
|
299
|
+
## Your data layer
|
|
300
|
+
|
|
301
|
+
Your data layer is yours: any database, ORM or API. The SDK guarantees three things without knowing it:
|
|
302
|
+
|
|
303
|
+
- The tenant (`ctx.installation`) and the person come from the verified caller, never from parameters.
|
|
304
|
+
- Filters, sort, text and cursor reach `list` already checked against the fields' meaning and the caller's field
|
|
305
|
+
permissions.
|
|
306
|
+
- Fields the caller may not see are stripped from what your handler returns.
|
|
307
|
+
|
|
308
|
+
A list handler over SQL:
|
|
309
|
+
|
|
310
|
+
```ts
|
|
311
|
+
list: async (q, ctx) => {
|
|
312
|
+
const where = ["org_id = $1"], params: unknown[] = [ctx.installation] // the tenant, always
|
|
313
|
+
if (typeof q.filters.status === "string") where.push(`status = $${params.push(q.filters.status)}`)
|
|
314
|
+
if (q.text) where.push(`(${(q.textFields ?? []).map((f) => `${f} ILIKE $${params.push(`%${q.text}%`)}`).join(" OR ")})`)
|
|
315
|
+
const order = q.sort ? `${q.sort.field} ${q.sort.dir}` : "id" // q.sort.field is a declared sortable field
|
|
316
|
+
const offset = Number(q.cursor ?? 0)
|
|
317
|
+
const { rows } = await db.query(`SELECT * FROM notes WHERE ${where.join(" AND ")} ORDER BY ${order} LIMIT ${q.limit + 1} OFFSET ${offset}`, params)
|
|
318
|
+
return { rows: rows.slice(0, q.limit), ...(rows.length > q.limit ? { next: String(offset + q.limit) } : {}) }
|
|
319
|
+
},
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
## Kinds, when other apps hold the same things
|
|
323
|
+
|
|
324
|
+
If your entities are people, companies, events, tasks, documents, products or orders, say so: `kind: "person"` on
|
|
325
|
+
the entity and `.meta({ as: "email", filter: true })` on the field that holds it. Hosts then show one picker, one
|
|
326
|
+
search and one «People» page over every app that has people, and find the same person in another app by the exact
|
|
327
|
+
email. Your `list` receives a key filter normalised (`q.filters.email` lower-cased): compare it exactly.
|
|
328
|
+
|
|
329
|
+
```ts
|
|
330
|
+
if (typeof q.filters.email === "string") where.push(`lower(email) = $${params.push(q.filters.email)}`)
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
A field that points at a record of *another* app is `ref.kind("organization")`: it holds the URI and nothing else.
|
|
334
|
+
Skip kinds for your own domain records (deals, tickets), and when a workspace will have one app per kind they add
|
|
335
|
+
nothing. Details: [AI guide](ai-guide.md#kinds-the-same-kind-of-thing-across-apps-optional), [spec §3.1](spec.md#31-kinds).
|
|
336
|
+
|
|
337
|
+
## Three rules, three escape hatches
|
|
338
|
+
|
|
339
|
+
- `input` (actions) and `params` (fragments) are always given: `z.object({})` for none.
|
|
340
|
+
- `on: "<entity>"` makes a record action; without it the action is global and `run` gets `(input, ctx)`.
|
|
341
|
+
- Every handler scopes its data by `ctx.installation`.
|
|
342
|
+
|
|
343
|
+
- `mcp: (server, caller) => { … }` hands you the raw `McpServer` of each request for hand-written tools, resources
|
|
344
|
+
and views.
|
|
345
|
+
- `view: { html }` on an entity, a page or a fragment replaces the generated view. A page that is only
|
|
346
|
+
`{ title, view }` or `{ title, url }` is fully yours.
|
|
347
|
+
- `expose: { plain, tool }` (entities: `{ plain, list, get }`) decides what plain MCP clients see and what the tools
|
|
348
|
+
are called.
|
|
349
|
+
|
|
350
|
+
Next: [auth.md](auth.md), the [examples](examples/crm.md), the [spec](spec.md), the [AI guide](ai-guide.md).
|