@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,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@clegra/sdk/next`: a Clegra app (a `defineApp` object) inside a Next.js app.
|
|
3
|
+
*
|
|
4
|
+
* - `toNextHandlers(app)` → the route handlers of `app/api/clegra/[...path]/route.ts`.
|
|
5
|
+
* - `withClegra(nextConfig)` → the rewrites that put MCP and the manifest where hosts and clients look for
|
|
6
|
+
* them: `/mcp` and `/.well-known/…` at the root of the site, served by that one route.
|
|
7
|
+
*
|
|
8
|
+
* - `embedProxy(app)` → proxy.ts for the embedded pages (`/embed/*`, spec §5.1): the ticket exchange and the
|
|
9
|
+
* `frame-ancestors` of every embed response. `getEmbedCaller(app, page)` → who looks at an embedded page.
|
|
10
|
+
*
|
|
11
|
+
* Only types are imported from the core: next.config loads this module and stays light. `next` is an optional
|
|
12
|
+
* peer dependency: types here, and `next/server` / `next/headers` loaded only when the proxy or a page runs.
|
|
13
|
+
*/
|
|
14
|
+
/** Where the catch-all route lives by default (`app/api/clegra/[...path]/route.ts`). */
|
|
15
|
+
export const DEFAULT_MOUNT = "/api/clegra";
|
|
16
|
+
/** The paths rewritten to the route: MCP, the manifest and the OAuth metadata (RFC 9728, RFC 8414, OpenID discovery). */
|
|
17
|
+
const PUBLIC_PATHS = [
|
|
18
|
+
"/mcp",
|
|
19
|
+
// MANIFEST_PATH (a test keeps the two equal; not imported so that next.config does not load the SDK).
|
|
20
|
+
"/.well-known/clegra.json",
|
|
21
|
+
"/.well-known/oauth-protected-resource/:path*",
|
|
22
|
+
"/.well-known/oauth-authorization-server/:path*",
|
|
23
|
+
"/.well-known/openid-configuration/:path*",
|
|
24
|
+
];
|
|
25
|
+
function mountOf(mount) {
|
|
26
|
+
const m = (mount ?? DEFAULT_MOUNT).replace(/\/+$/, "");
|
|
27
|
+
if (!/^(\/[A-Za-z0-9._~-]+)+$/.test(m))
|
|
28
|
+
throw new Error(`@clegra/sdk/next: mount "${mount}" must be a URL path like /api/clegra`);
|
|
29
|
+
return m;
|
|
30
|
+
}
|
|
31
|
+
function publicOrigin(value, where) {
|
|
32
|
+
if (value === undefined || value === "")
|
|
33
|
+
return null;
|
|
34
|
+
let url;
|
|
35
|
+
try {
|
|
36
|
+
url = new URL(value);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
throw new Error(`@clegra/sdk/next: ${where} "${value}" is not a URL`);
|
|
40
|
+
}
|
|
41
|
+
if (!/^https?:$/.test(url.protocol) || (url.pathname !== "/" && url.pathname !== "") || url.search || url.hash || url.username || url.password) {
|
|
42
|
+
throw new Error(`@clegra/sdk/next: ${where} "${value}" must be an origin only, like https://crm.example.com (no path, query or credentials)`);
|
|
43
|
+
}
|
|
44
|
+
return url;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The route handlers for `app/api/clegra/[...path]/route.ts`:
|
|
48
|
+
*
|
|
49
|
+
* ```ts
|
|
50
|
+
* export const { GET, POST, DELETE, OPTIONS } = toNextHandlers(app)
|
|
51
|
+
* ```
|
|
52
|
+
*
|
|
53
|
+
* Each request reaches `app.fetch` at its PUBLIC address: the mount taken off (`/api/clegra/mcp` → `/mcp`),
|
|
54
|
+
* the origin `publicUrl` when given. Responses (JSON or an SSE stream) are returned as they are, never buffered.
|
|
55
|
+
* Nothing is kept between requests (MCP is stateless): it runs on serverless as on one server.
|
|
56
|
+
*
|
|
57
|
+
* Dev sign-in (`auth.dev`) is refused: it answers loopback callers only, and a Next route handler can't know the
|
|
58
|
+
* peer's address (`x-forwarded-for` is whatever the client sent). Sign people in with the app's own auth
|
|
59
|
+
* (`auth.resolve`), or run the app with `listen` from `@clegra/sdk/node` while developing.
|
|
60
|
+
*/
|
|
61
|
+
export function toNextHandlers(app, options = {}) {
|
|
62
|
+
const mount = mountOf(options.mount);
|
|
63
|
+
const fixedOrigin = options.publicUrl !== undefined ? publicOrigin(options.publicUrl, "publicUrl") : publicOrigin(process.env.CLEGRA_PUBLIC_URL, "CLEGRA_PUBLIC_URL");
|
|
64
|
+
if (app.devMode) {
|
|
65
|
+
throw new Error("@clegra/sdk/next: auth.dev can't run inside Next.js — dev sign-in answers loopback callers only and a route handler can't know the caller's address. Use the app's own sign-in (auth.resolve) or run the app with listen() from @clegra/sdk/node.");
|
|
66
|
+
}
|
|
67
|
+
const mcpPath = app.manifest().mcp.url;
|
|
68
|
+
if (mcpPath !== "/mcp") {
|
|
69
|
+
throw new Error(`@clegra/sdk/next: the app serves MCP at ${mcpPath}; with Next.js leave defineApp's \`path\` unset — the route's mount (${mount}) is taken off and withClegra puts MCP at /mcp`);
|
|
70
|
+
}
|
|
71
|
+
const handle = async (request) => {
|
|
72
|
+
const url = new URL(request.url);
|
|
73
|
+
let path = url.pathname;
|
|
74
|
+
if (path === mount || path.startsWith(`${mount}/`))
|
|
75
|
+
path = path.slice(mount.length) || "/";
|
|
76
|
+
else if (path !== "/mcp" && !path.startsWith("/.well-known/")) {
|
|
77
|
+
// The route file is somewhere else than `mount` says: a configuration error, said instead of guessed around.
|
|
78
|
+
return new Response(JSON.stringify({ error: "misconfigured", error_description: `@clegra/sdk/next: request for ${path} reached the clegra route, but its mount is ${mount} (set the same mount in toNextHandlers and withClegra)` }), {
|
|
79
|
+
status: 500,
|
|
80
|
+
headers: { "content-type": "application/json" },
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
const headers = publicHeaders(request.headers, fixedOrigin);
|
|
84
|
+
const origin = fixedOrigin ? fixedOrigin.origin : url.origin;
|
|
85
|
+
const hasBody = request.method !== "GET" && request.method !== "HEAD" && request.body !== null;
|
|
86
|
+
const init = { method: request.method, headers, signal: request.signal, ...(hasBody ? { body: request.body, duplex: "half" } : {}) };
|
|
87
|
+
const response = await app.fetch(new Request(new URL(path + url.search, origin), init), { remoteAddress: null });
|
|
88
|
+
if (!(response.headers.get("content-type") ?? "").startsWith("text/event-stream"))
|
|
89
|
+
return response;
|
|
90
|
+
// An SSE stream: no compression or other transform may hold it back (`next start` compresses responses).
|
|
91
|
+
const streamed = new Headers(response.headers);
|
|
92
|
+
const cache = streamed.get("cache-control");
|
|
93
|
+
if (!cache?.includes("no-transform"))
|
|
94
|
+
streamed.set("cache-control", cache ? `${cache}, no-transform` : "no-cache, no-transform");
|
|
95
|
+
streamed.set("x-accel-buffering", "no");
|
|
96
|
+
return new Response(response.body, { status: response.status, statusText: response.statusText, headers: streamed });
|
|
97
|
+
};
|
|
98
|
+
return { GET: handle, POST: handle, DELETE: handle, OPTIONS: handle };
|
|
99
|
+
}
|
|
100
|
+
/** The request's headers, with the configured public origin in place of whatever came in (the core reads x-forwarded-* first). */
|
|
101
|
+
function publicHeaders(given, fixedOrigin) {
|
|
102
|
+
const headers = new Headers(given);
|
|
103
|
+
if (fixedOrigin) {
|
|
104
|
+
headers.set("x-forwarded-host", fixedOrigin.host);
|
|
105
|
+
headers.set("x-forwarded-proto", fixedOrigin.protocol.slice(0, -1));
|
|
106
|
+
headers.set("host", fixedOrigin.host);
|
|
107
|
+
}
|
|
108
|
+
return headers;
|
|
109
|
+
}
|
|
110
|
+
const embedOf = async (source, where) => {
|
|
111
|
+
const app = typeof source === "function" ? await source() : source;
|
|
112
|
+
if (!app.embed)
|
|
113
|
+
throw new Error(`${where}: the app declares no \`embed\` (defineApp({ embed: { frameAncestors, … } }), spec §5.1)`);
|
|
114
|
+
return app.embed;
|
|
115
|
+
};
|
|
116
|
+
/**
|
|
117
|
+
* proxy.ts for the embedded pages (spec §5.1), with the matcher on the embed path:
|
|
118
|
+
*
|
|
119
|
+
* ```ts
|
|
120
|
+
* export const proxy = embedProxy(app)
|
|
121
|
+
* export const config = { matcher: "/embed/:path*" }
|
|
122
|
+
* ```
|
|
123
|
+
*
|
|
124
|
+
* `POST /embed/_ticket` exchanges a host's ticket for the page's partitioned session cookie and redirects (303) to
|
|
125
|
+
* the page; every other embed request goes on to the page with `Content-Security-Policy: frame-ancestors <the
|
|
126
|
+
* declared hosts>` and `Referrer-Policy: no-referrer`. Options: `publicUrl` as in `toNextHandlers`.
|
|
127
|
+
*/
|
|
128
|
+
export function embedProxy(source, options = {}) {
|
|
129
|
+
const fixedOrigin = options.publicUrl !== undefined ? publicOrigin(options.publicUrl, "publicUrl") : publicOrigin(process.env.CLEGRA_PUBLIC_URL, "CLEGRA_PUBLIC_URL");
|
|
130
|
+
return async (request) => {
|
|
131
|
+
const embed = await embedOf(source, "embedProxy");
|
|
132
|
+
const { pathname } = new URL(request.url);
|
|
133
|
+
if (pathname === embed.exchangePath) {
|
|
134
|
+
const hasBody = request.method !== "GET" && request.method !== "HEAD" && request.body !== null;
|
|
135
|
+
const init = { method: request.method, headers: publicHeaders(request.headers, fixedOrigin), ...(hasBody ? { body: request.body, duplex: "half" } : {}) };
|
|
136
|
+
return embed.exchange(new Request(request.url, init));
|
|
137
|
+
}
|
|
138
|
+
const { NextResponse } = await import("next/server");
|
|
139
|
+
const response = NextResponse.next();
|
|
140
|
+
if (pathname === embed.path || pathname.startsWith(`${embed.path}/`))
|
|
141
|
+
for (const [k, v] of Object.entries(embed.headers()))
|
|
142
|
+
response.headers.set(k, v);
|
|
143
|
+
return response;
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Who looks at the embedded page `page` (its name in defineApp's `pages`), in a server component, route handler or
|
|
148
|
+
* server function of that page: the caller its ticket was issued to, from the page's session cookie; null without one
|
|
149
|
+
* (opened outside a host's frame, expired, or a top-level visit). Scope everything by `caller.installation`.
|
|
150
|
+
*/
|
|
151
|
+
export async function getEmbedCaller(source, page, options = {}) {
|
|
152
|
+
const fixedOrigin = options.publicUrl !== undefined ? publicOrigin(options.publicUrl, "publicUrl") : publicOrigin(process.env.CLEGRA_PUBLIC_URL, "CLEGRA_PUBLIC_URL");
|
|
153
|
+
// The request first: it makes the page dynamic before the app (its database, its auth) is touched, never at build time.
|
|
154
|
+
const { headers } = await import("next/headers");
|
|
155
|
+
const given = publicHeaders(new Headers(await headers()), fixedOrigin);
|
|
156
|
+
const embed = await embedOf(source, "getEmbedCaller");
|
|
157
|
+
return embed.caller(page, new Request(`http://${given.get("host") ?? "localhost"}${embed.path}`, { headers: given }));
|
|
158
|
+
}
|
|
159
|
+
/** The rewrites `withClegra` adds (in `beforeFiles`, so no page or public file can shadow them). */
|
|
160
|
+
export function clegraRewrites(options = {}) {
|
|
161
|
+
const mount = mountOf(options.mount);
|
|
162
|
+
return PUBLIC_PATHS.map((source) => ({ source, destination: `${mount}${source}` }));
|
|
163
|
+
}
|
|
164
|
+
function withConfig(config, options) {
|
|
165
|
+
if (config.basePath)
|
|
166
|
+
throw new Error(`withClegra: basePath "${config.basePath}" is not supported — /mcp and /.well-known/… must be at the root of the host (RFC 8615, RFC 9728)`);
|
|
167
|
+
if (config.trailingSlash)
|
|
168
|
+
throw new Error("withClegra: trailingSlash: true redirects /mcp to /mcp/, and MCP clients use the exact address of the protected resource; turn it off");
|
|
169
|
+
const ours = clegraRewrites(options);
|
|
170
|
+
const theirs = config.rewrites;
|
|
171
|
+
if (theirs !== undefined && typeof theirs !== "function")
|
|
172
|
+
throw new Error("withClegra: next.config `rewrites` must be a function (sync or async)");
|
|
173
|
+
const rewrites = async () => {
|
|
174
|
+
const given = theirs ? await theirs() : [];
|
|
175
|
+
if (Array.isArray(given))
|
|
176
|
+
return { beforeFiles: ours, afterFiles: given, fallback: [] };
|
|
177
|
+
return { beforeFiles: [...ours, ...(given.beforeFiles ?? [])], afterFiles: given.afterFiles ?? [], fallback: given.fallback ?? [] };
|
|
178
|
+
};
|
|
179
|
+
return { ...config, rewrites: rewrites };
|
|
180
|
+
}
|
|
181
|
+
export function withClegra(config, options = {}) {
|
|
182
|
+
mountOf(options.mount);
|
|
183
|
+
if (typeof config === "function")
|
|
184
|
+
return async (phase, context) => withConfig(await config(phase, context), options);
|
|
185
|
+
return withConfig(config, options);
|
|
186
|
+
}
|
|
187
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/next/index.ts"],"names":[],"mappings":"AAIA;;;;;;;;;;;;GAYG;AAEH,wFAAwF;AACxF,MAAM,CAAC,MAAM,aAAa,GAAG,aAAa,CAAA;AAE1C,yHAAyH;AACzH,MAAM,YAAY,GAAG;IACnB,MAAM;IACN,sGAAsG;IACtG,0BAA0B;IAC1B,8CAA8C;IAC9C,gDAAgD;IAChD,0CAA0C;CAClC,CAAA;AAgBV,SAAS,OAAO,CAAC,KAAyB;IACxC,MAAM,CAAC,GAAG,CAAC,KAAK,IAAI,aAAa,CA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AK,EAAE,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAA;IACpH,OAAO,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AACpC,CAAC","sourcesContent":["import type { App } from \"../define\"\nimport type { EmbedCaller } from \"../embed\"\nimport type { NextConfig } from \"next\"\n\n/**\n * `@clegra/sdk/next`: a Clegra app (a `defineApp` object) inside a Next.js app.\n *\n * - `toNextHandlers(app)` → the route handlers of `app/api/clegra/[...path]/route.ts`.\n * - `withClegra(nextConfig)` → the rewrites that put MCP and the manifest where hosts and clients look for\n * them: `/mcp` and `/.well-known/…` at the root of the site, served by that one route.\n *\n * - `embedProxy(app)` → proxy.ts for the embedded pages (`/embed/*`, spec §5.1): the ticket exchange and the\n * `frame-ancestors` of every embed response. `getEmbedCaller(app, page)` → who looks at an embedded page.\n *\n * Only types are imported from the core: next.config loads this module and stays light. `next` is an optional\n * peer dependency: types here, and `next/server` / `next/headers` loaded only when the proxy or a page runs.\n */\n\n/** Where the catch-all route lives by default (`app/api/clegra/[...path]/route.ts`). */\nexport const DEFAULT_MOUNT = \"/api/clegra\"\n\n/** The paths rewritten to the route: MCP, the manifest and the OAuth metadata (RFC 9728, RFC 8414, OpenID discovery). */\nconst PUBLIC_PATHS = [\n \"/mcp\",\n // MANIFEST_PATH (a test keeps the two equal; not imported so that next.config does not load the SDK).\n \"/.well-known/clegra.json\",\n \"/.well-known/oauth-protected-resource/:path*\",\n \"/.well-known/oauth-authorization-server/:path*\",\n \"/.well-known/openid-configuration/:path*\",\n] as const\n\nexport type NextHandlerOptions = {\n /** Where the catch-all route is mounted (default `/api/clegra`): the same value as in `withClegra`. */\n mount?: string\n /**\n * The site's public origin (`https://crm.example.com`), when the request alone can't say it (a proxy that\n * rewrites the host). Default: the `CLEGRA_PUBLIC_URL` environment variable; without either, the origin is\n * what the request says (`x-forwarded-host` / `x-forwarded-proto`, else `host`).\n */\n publicUrl?: string\n}\n\nexport type NextRouteHandler = (request: Request) => Promise<Response>\nexport type NextHandlers = { GET: NextRouteHandler; POST: NextRouteHandler; DELETE: NextRouteHandler; OPTIONS: NextRouteHandler }\n\nfunction mountOf(mount: string | undefined): string {\n const m = (mount ?? DEFAULT_MOUNT).replace(/\\/+$/, \"\")\n if (!/^(\\/[A-Za-z0-9._~-]+)+$/.test(m)) throw new Error(`@clegra/sdk/next: mount \"${mount}\" must be a URL path like /api/clegra`)\n return m\n}\n\nfunction publicOrigin(value: string | undefined, where: string): URL | null {\n if (value === undefined || value === \"\") return null\n let url: URL\n try {\n url = new URL(value)\n } catch {\n throw new Error(`@clegra/sdk/next: ${where} \"${value}\" is not a URL`)\n }\n if (!/^https?:$/.test(url.protocol) || (url.pathname !== \"/\" && url.pathname !== \"\") || url.search || url.hash || url.username || url.password) {\n throw new Error(`@clegra/sdk/next: ${where} \"${value}\" must be an origin only, like https://crm.example.com (no path, query or credentials)`)\n }\n return url\n}\n\n/**\n * The route handlers for `app/api/clegra/[...path]/route.ts`:\n *\n * ```ts\n * export const { GET, POST, DELETE, OPTIONS } = toNextHandlers(app)\n * ```\n *\n * Each request reaches `app.fetch` at its PUBLIC address: the mount taken off (`/api/clegra/mcp` → `/mcp`),\n * the origin `publicUrl` when given. Responses (JSON or an SSE stream) are returned as they are, never buffered.\n * Nothing is kept between requests (MCP is stateless): it runs on serverless as on one server.\n *\n * Dev sign-in (`auth.dev`) is refused: it answers loopback callers only, and a Next route handler can't know the\n * peer's address (`x-forwarded-for` is whatever the client sent). Sign people in with the app's own auth\n * (`auth.resolve`), or run the app with `listen` from `@clegra/sdk/node` while developing.\n */\nexport function toNextHandlers(app: App, options: NextHandlerOptions = {}): NextHandlers {\n const mount = mountOf(options.mount)\n const fixedOrigin = options.publicUrl !== undefined ? publicOrigin(options.publicUrl, \"publicUrl\") : publicOrigin(process.env.CLEGRA_PUBLIC_URL, \"CLEGRA_PUBLIC_URL\")\n if (app.devMode) {\n throw new Error(\n \"@clegra/sdk/next: auth.dev can't run inside Next.js — dev sign-in answers loopback callers only and a route handler can't know the caller's address. Use the app's own sign-in (auth.resolve) or run the app with listen() from @clegra/sdk/node.\",\n )\n }\n const mcpPath = app.manifest().mcp.url\n if (mcpPath !== \"/mcp\") {\n throw new Error(`@clegra/sdk/next: the app serves MCP at ${mcpPath}; with Next.js leave defineApp's \\`path\\` unset — the route's mount (${mount}) is taken off and withClegra puts MCP at /mcp`)\n }\n\n const handle: NextRouteHandler = async (request) => {\n const url = new URL(request.url)\n let path = url.pathname\n if (path === mount || path.startsWith(`${mount}/`)) path = path.slice(mount.length) || \"/\"\n else if (path !== \"/mcp\" && !path.startsWith(\"/.well-known/\")) {\n // The route file is somewhere else than `mount` says: a configuration error, said instead of guessed around.\n return new Response(JSON.stringify({ error: \"misconfigured\", error_description: `@clegra/sdk/next: request for ${path} reached the clegra route, but its mount is ${mount} (set the same mount in toNextHandlers and withClegra)` }), {\n status: 500,\n headers: { \"content-type\": \"application/json\" },\n })\n }\n const headers = publicHeaders(request.headers, fixedOrigin)\n const origin = fixedOrigin ? fixedOrigin.origin : url.origin\n const hasBody = request.method !== \"GET\" && request.method !== \"HEAD\" && request.body !== null\n const init: RequestInit & { duplex?: \"half\" } = { method: request.method, headers, signal: request.signal, ...(hasBody ? { body: request.body, duplex: \"half\" } : {}) }\n const response = await app.fetch(new Request(new URL(path + url.search, origin), init), { remoteAddress: null })\n if (!(response.headers.get(\"content-type\") ?? \"\").startsWith(\"text/event-stream\")) return response\n // An SSE stream: no compression or other transform may hold it back (`next start` compresses responses).\n const streamed = new Headers(response.headers)\n const cache = streamed.get(\"cache-control\")\n if (!cache?.includes(\"no-transform\")) streamed.set(\"cache-control\", cache ? `${cache}, no-transform` : \"no-cache, no-transform\")\n streamed.set(\"x-accel-buffering\", \"no\")\n return new Response(response.body, { status: response.status, statusText: response.statusText, headers: streamed })\n }\n return { GET: handle, POST: handle, DELETE: handle, OPTIONS: handle }\n}\n\n/** The request's headers, with the configured public origin in place of whatever came in (the core reads x-forwarded-* first). */\nfunction publicHeaders(given: Headers, fixedOrigin: URL | null): Headers {\n const headers = new Headers(given)\n if (fixedOrigin) {\n headers.set(\"x-forwarded-host\", fixedOrigin.host)\n headers.set(\"x-forwarded-proto\", fixedOrigin.protocol.slice(0, -1))\n headers.set(\"host\", fixedOrigin.host)\n }\n return headers\n}\n\n// ------------------------------------------------------------ embedded pages (spec §5.1)\n\n/** The app, or how to get it (an app made on first use, as the examples do). */\nexport type AppSource = App | (() => App | Promise<App>)\n\nconst embedOf = async (source: AppSource, where: string) => {\n const app = typeof source === \"function\" ? await source() : source\n if (!app.embed) throw new Error(`${where}: the app declares no \\`embed\\` (defineApp({ embed: { frameAncestors, … } }), spec §5.1)`)\n return app.embed\n}\n\n/**\n * proxy.ts for the embedded pages (spec §5.1), with the matcher on the embed path:\n *\n * ```ts\n * export const proxy = embedProxy(app)\n * export const config = { matcher: \"/embed/:path*\" }\n * ```\n *\n * `POST /embed/_ticket` exchanges a host's ticket for the page's partitioned session cookie and redirects (303) to\n * the page; every other embed request goes on to the page with `Content-Security-Policy: frame-ancestors <the\n * declared hosts>` and `Referrer-Policy: no-referrer`. Options: `publicUrl` as in `toNextHandlers`.\n */\nexport function embedProxy(source: AppSource, options: { publicUrl?: string } = {}): (request: Request) => Promise<Response> {\n const fixedOrigin = options.publicUrl !== undefined ? publicOrigin(options.publicUrl, \"publicUrl\") : publicOrigin(process.env.CLEGRA_PUBLIC_URL, \"CLEGRA_PUBLIC_URL\")\n return async (request) => {\n const embed = await embedOf(source, \"embedProxy\")\n const { pathname } = new URL(request.url)\n if (pathname === embed.exchangePath) {\n const hasBody = request.method !== \"GET\" && request.method !== \"HEAD\" && request.body !== null\n const init: RequestInit & { duplex?: \"half\" } = { method: request.method, headers: publicHeaders(request.headers, fixedOrigin), ...(hasBody ? { body: request.body, duplex: \"half\" } : {}) }\n return embed.exchange(new Request(request.url, init))\n }\n const { NextResponse } = await import(\"next/server\")\n const response = NextResponse.next()\n if (pathname === embed.path || pathname.startsWith(`${embed.path}/`)) for (const [k, v] of Object.entries(embed.headers())) response.headers.set(k, v)\n return response\n }\n}\n\n/**\n * Who looks at the embedded page `page` (its name in defineApp's `pages`), in a server component, route handler or\n * server function of that page: the caller its ticket was issued to, from the page's session cookie; null without one\n * (opened outside a host's frame, expired, or a top-level visit). Scope everything by `caller.installation`.\n */\nexport async function getEmbedCaller(source: AppSource, page: string, options: { publicUrl?: string } = {}): Promise<EmbedCaller | null> {\n const fixedOrigin = options.publicUrl !== undefined ? publicOrigin(options.publicUrl, \"publicUrl\") : publicOrigin(process.env.CLEGRA_PUBLIC_URL, \"CLEGRA_PUBLIC_URL\")\n // The request first: it makes the page dynamic before the app (its database, its auth) is touched, never at build time.\n const { headers } = await import(\"next/headers\")\n const given = publicHeaders(new Headers(await headers()), fixedOrigin)\n const embed = await embedOf(source, \"getEmbedCaller\")\n return embed.caller(page, new Request(`http://${given.get(\"host\") ?? \"localhost\"}${embed.path}`, { headers: given }))\n}\n\n// ------------------------------------------------------------ next.config\n\ntype Rewrite = { source: string; destination: string; basePath?: false; locale?: false; has?: unknown[]; missing?: unknown[] }\ntype Rewrites = Rewrite[] | { beforeFiles?: Rewrite[]; afterFiles?: Rewrite[]; fallback?: Rewrite[] }\ntype ConfigFunction = (phase: string, context: { defaultConfig: NextConfig }) => NextConfig | Promise<NextConfig>\n\nexport type WithClegraOptions = {\n /** Where the catch-all route is mounted (default `/api/clegra`): the same value as in `toNextHandlers`. */\n mount?: string\n}\n\n/** The rewrites `withClegra` adds (in `beforeFiles`, so no page or public file can shadow them). */\nexport function clegraRewrites(options: WithClegraOptions = {}): Rewrite[] {\n const mount = mountOf(options.mount)\n return PUBLIC_PATHS.map((source) => ({ source, destination: `${mount}${source}` }))\n}\n\nfunction withConfig(config: NextConfig, options: WithClegraOptions): NextConfig {\n if (config.basePath) throw new Error(`withClegra: basePath \"${config.basePath}\" is not supported — /mcp and /.well-known/… must be at the root of the host (RFC 8615, RFC 9728)`)\n if (config.trailingSlash) throw new Error(\"withClegra: trailingSlash: true redirects /mcp to /mcp/, and MCP clients use the exact address of the protected resource; turn it off\")\n const ours = clegraRewrites(options)\n const theirs = config.rewrites as (() => Rewrites | Promise<Rewrites>) | undefined\n if (theirs !== undefined && typeof theirs !== \"function\") throw new Error(\"withClegra: next.config `rewrites` must be a function (sync or async)\")\n const rewrites = async () => {\n const given = theirs ? await theirs() : []\n if (Array.isArray(given)) return { beforeFiles: ours, afterFiles: given, fallback: [] }\n return { beforeFiles: [...ours, ...(given.beforeFiles ?? [])], afterFiles: given.afterFiles ?? [], fallback: given.fallback ?? [] }\n }\n return { ...config, rewrites: rewrites as NextConfig[\"rewrites\"] }\n}\n\n/**\n * next.config: adds the rewrites for `/mcp`, `/.well-known/clegra.json` and the OAuth metadata paths to the\n * clegra route (before the app's own, merged with them in any shape: array, object, sync or async function). The rest\n * of the config is kept as it is. Takes the config object or a config function.\n */\nexport function withClegra(config: NextConfig, options?: WithClegraOptions): NextConfig\nexport function withClegra(config: ConfigFunction, options?: WithClegraOptions): ConfigFunction\nexport function withClegra(config: NextConfig | ConfigFunction, options: WithClegraOptions = {}): NextConfig | ConfigFunction {\n mountOf(options.mount)\n if (typeof config === \"function\") return async (phase, context) => withConfig(await config(phase, context), options)\n return withConfig(config, options)\n}\n"]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { App } from "./define.js";
|
|
2
|
+
/**
|
|
3
|
+
* `@clegra/sdk/node`: an app on Node's own HTTP server, for a standalone
|
|
4
|
+
* app or local tools. A web app serves `app.fetch` from its framework instead
|
|
5
|
+
* (`@clegra/sdk/next`); the core itself never opens a socket.
|
|
6
|
+
*/
|
|
7
|
+
export declare function listen(app: App, options?: {
|
|
8
|
+
port?: number;
|
|
9
|
+
host?: string;
|
|
10
|
+
log?: boolean;
|
|
11
|
+
}): Promise<{
|
|
12
|
+
url: string;
|
|
13
|
+
close: () => Promise<void>;
|
|
14
|
+
}>;
|
package/dist/src/node.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { createServer } from "node:http";
|
|
2
|
+
import { PROTOCOL_ID } from "../spec/src/protocol.js";
|
|
3
|
+
import { isLoopback } from "./auth.js";
|
|
4
|
+
/**
|
|
5
|
+
* `@clegra/sdk/node`: an app on Node's own HTTP server, for a standalone
|
|
6
|
+
* app or local tools. A web app serves `app.fetch` from its framework instead
|
|
7
|
+
* (`@clegra/sdk/next`); the core itself never opens a socket.
|
|
8
|
+
*/
|
|
9
|
+
export async function listen(app, options = {}) {
|
|
10
|
+
const port = options.port ?? 3000;
|
|
11
|
+
const host = options.host ?? "127.0.0.1";
|
|
12
|
+
if (app.devMode && !isLoopback(host))
|
|
13
|
+
throw new Error(`auth.dev works only on a loopback address, not ${host}`);
|
|
14
|
+
const { devCode } = await app.start();
|
|
15
|
+
const http = createServer(async (req, res) => {
|
|
16
|
+
const started = Date.now();
|
|
17
|
+
try {
|
|
18
|
+
const response = await app.fetch(await toRequest(req), { remoteAddress: req.socket.remoteAddress ?? null });
|
|
19
|
+
const headers = {};
|
|
20
|
+
response.headers.forEach((v, k) => (headers[k] = v));
|
|
21
|
+
res.writeHead(response.status, headers);
|
|
22
|
+
if (response.body) {
|
|
23
|
+
const reader = response.body.getReader();
|
|
24
|
+
for (let r = await reader.read(); !r.done; r = await reader.read())
|
|
25
|
+
res.write(r.value);
|
|
26
|
+
}
|
|
27
|
+
res.end();
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
console.error(`[${PROTOCOL_ID} http]`, error);
|
|
31
|
+
if (!res.headersSent)
|
|
32
|
+
res.writeHead(500).end();
|
|
33
|
+
else
|
|
34
|
+
res.end();
|
|
35
|
+
}
|
|
36
|
+
finally {
|
|
37
|
+
if (options.log !== false)
|
|
38
|
+
console.log(`${new Date().toISOString()} ${req.method} ${req.url} ${res.statusCode} ${Date.now() - started}ms`);
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
await new Promise((resolve, reject) => {
|
|
42
|
+
http.once("error", reject);
|
|
43
|
+
http.listen(port, host, resolve);
|
|
44
|
+
});
|
|
45
|
+
const address = http.address();
|
|
46
|
+
const url = `http://${host}:${typeof address === "object" && address ? address.port : port}`;
|
|
47
|
+
const base = app.manifest().mcp.url;
|
|
48
|
+
console.log(`${app.name} — MCP ${url}${base} · manifest ${url}/.well-known/clegra.json`);
|
|
49
|
+
if (devCode)
|
|
50
|
+
console.log(`DEV AUTH ON (never in production) — sign-in code: ${devCode}`);
|
|
51
|
+
return { url, close: () => new Promise((resolve) => http.close(() => resolve())) };
|
|
52
|
+
}
|
|
53
|
+
async function toRequest(req) {
|
|
54
|
+
const chunks = [];
|
|
55
|
+
for await (const chunk of req)
|
|
56
|
+
chunks.push(chunk);
|
|
57
|
+
const headers = new Headers();
|
|
58
|
+
for (const [k, v] of Object.entries(req.headers))
|
|
59
|
+
if (v !== undefined)
|
|
60
|
+
headers.set(k, Array.isArray(v) ? v.join(", ") : v);
|
|
61
|
+
const body = chunks.length && req.method !== "GET" && req.method !== "HEAD" ? Buffer.concat(chunks) : undefined;
|
|
62
|
+
return new Request(`http://${req.headers.host ?? "localhost"}${req.url}`, { method: req.method, headers, ...(body ? { body } : {}) });
|
|
63
|
+
}
|
|
64
|
+
//# sourceMappingURL=node.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node.js","sourceRoot":"","sources":["../../src/node.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAwB,MAAM,WAAW,CAAA;AAE9D,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAElD,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAA;AAGnC;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,MAAM,CAAC,GAAQ,EAAE,UAA2D,EAAE;IAClG,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,IAAI,CAAA;IACjC,MAAM,IA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n\nimport { PROTOCOL_ID } from \"../spec/src/protocol\"\n\nimport { isLoopback } from \"./auth\"\nimport type { App } from \"./define\"\n\n/**\n * `@clegra/sdk/node`: an app on Node's own HTTP server, for a standalone\n * app or local tools. A web app serves `app.fetch` from its framework instead\n * (`@clegra/sdk/next`); the core itself never opens a socket.\n */\nexport async function listen(app: App, options: { port?: number; host?: string; log?: boolean } = {}): Promise<{ url: string; close: () => Promise<void> }> {\n const port = options.port ?? 3000\n const host = options.host ?? \"127.0.0.1\"\n if (app.devMode && !isLoopback(host)) throw new Error(`auth.dev works only on a loopback address, not ${host}`)\n const { devCode } = await app.start()\n const http = createServer(async (req, res) => {\n const started = Date.now()\n try {\n const response = await app.fetch(await toRequest(req), { remoteAddress: req.socket.remoteAddress ?? null })\n const headers: Record<string, string> = {}\n response.headers.forEach((v, k) => (headers[k] = v))\n res.writeHead(response.status, headers)\n if (response.body) {\n const reader = response.body.getReader()\n for (let r = await reader.read(); !r.done; r = await reader.read()) res.write(r.value)\n }\n res.end()\n } catch (error) {\n console.error(`[${PROTOCOL_ID} http]`, error)\n if (!res.headersSent) res.writeHead(500).end()\n else res.end()\n } finally {\n if (options.log !== false) console.log(`${new Date().toISOString()} ${req.method} ${req.url} ${res.statusCode} ${Date.now() - started}ms`)\n }\n })\n await new Promise<void>((resolve, reject) => {\n http.once(\"error\", reject)\n http.listen(port, host, resolve)\n })\n const address = http.address()\n const url = `http://${host}:${typeof address === \"object\" && address ? address.port : port}`\n const base = app.manifest().mcp.url\n console.log(`${app.name} — MCP ${url}${base} · manifest ${url}/.well-known/clegra.json`)\n if (devCode) console.log(`DEV AUTH ON (never in production) — sign-in code: ${devCode}`)\n return { url, close: () => new Promise((resolve) => http.close(() => resolve())) }\n}\n\nasync function toRequest(req: IncomingMessage): Promise<Request> {\n const chunks: Buffer[] = []\n for await (const chunk of req) chunks.push(chunk as Buffer)\n const headers = new Headers()\n for (const [k, v] of Object.entries(req.headers)) if (v !== undefined) headers.set(k, Array.isArray(v) ? v.join(\", \") : v)\n const body = chunks.length && req.method !== \"GET\" && req.method !== \"HEAD\" ? Buffer.concat(chunks) : undefined\n return new Request(`http://${req.headers.host ?? \"localhost\"}${req.url}`, { method: req.method, headers, ...(body ? { body } : {}) })\n}\n"]}
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { McpServer, type Icon } from "@modelcontextprotocol/server";
|
|
2
|
+
import { META_KEY } from "../spec/src/protocol.js";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { type AuthOptions, type Caller, type Person, type RequestTrust } from "./auth.js";
|
|
5
|
+
import { type EmbedCaller, type EmbedOptions } from "./embed.js";
|
|
6
|
+
import { type Manifest } from "./manifest.js";
|
|
7
|
+
import { type Label } from "./labels.js";
|
|
8
|
+
import { type IdempotencyStore, type LaterOutcome } from "./store.js";
|
|
9
|
+
import type { ActionConfig, ActionHandle, ActionHandler, AgentConfig, Context, EntityConfig, EntityHandle, FragmentConfig, FragmentInstance, KindConfig, LifecycleConfig, NavSection, NotificationTypeConfig, PageConfig, PermissionConfig, Publisher, ScheduleConfig, SettingConfig, Template } from "./types.js";
|
|
10
|
+
/**
|
|
11
|
+
* THE CLEGRA APP SERVER, v1 (docs/spec.md): an MCP server
|
|
12
|
+
* (official SDK, Streamable HTTP, stateless) whose declarations — entities,
|
|
13
|
+
* actions, pages, fragments, agents, permissions, settings — become plain MCP
|
|
14
|
+
* tools and MCP Apps views for any host, and a manifest hosts read to mount
|
|
15
|
+
* the app natively. Internal: authors use defineApp (define.ts).
|
|
16
|
+
*
|
|
17
|
+
* Every request builds a fresh McpServer for its caller: the tools a caller
|
|
18
|
+
* may not use are not listed, titles are in the caller's language, and every
|
|
19
|
+
* handler closes over the verified caller. Permissions, field permissions,
|
|
20
|
+
* exposure to plain clients, confirmations and idempotency are enforced
|
|
21
|
+
* here, on every surface (tools, search, fetch, the resolver, dashboards),
|
|
22
|
+
* before any handler.
|
|
23
|
+
*/
|
|
24
|
+
/** What a request brings beside its caller: whether dev tokens count (a loopback caller), and each call's arguments as received. */
|
|
25
|
+
export type RequestInfo = {
|
|
26
|
+
trust: RequestTrust;
|
|
27
|
+
received: ReadonlyMap<string | number, unknown>;
|
|
28
|
+
/** The public origin the request reached (what a same-site `url` page is resolved against), when known. */
|
|
29
|
+
origin?: string;
|
|
30
|
+
};
|
|
31
|
+
/** The issuer name of callers named by the app's own `auth.resolve`. */
|
|
32
|
+
export declare const OWN_ISSUER = "app";
|
|
33
|
+
export type ServerOptions = {
|
|
34
|
+
/** The app id: lowercase letters, digits, `-`; 2–40 characters. */
|
|
35
|
+
name: string;
|
|
36
|
+
title: Label;
|
|
37
|
+
version: string;
|
|
38
|
+
description?: Label;
|
|
39
|
+
icons?: Icon[];
|
|
40
|
+
/**
|
|
41
|
+
* Who publishes the app (spec §2): a name and the publisher's web address (https). A claim, granting nothing: a
|
|
42
|
+
* store or host may verify it against the address's domain and show it as verified.
|
|
43
|
+
*/
|
|
44
|
+
publisher?: Publisher;
|
|
45
|
+
/** The locale of bare-string labels (default `en`). */
|
|
46
|
+
locale?: string;
|
|
47
|
+
auth?: AuthOptions;
|
|
48
|
+
/**
|
|
49
|
+
* Where the app's own routes live on its public address (default none): MCP at `<path>/mcp`, `<path>/health`.
|
|
50
|
+
* The manifest and the OAuth metadata stay where their standards put them, under `/.well-known/` at the root.
|
|
51
|
+
*/
|
|
52
|
+
path?: string;
|
|
53
|
+
/** MCP `instructions` for models. */
|
|
54
|
+
instructions?: string;
|
|
55
|
+
websiteUrl?: string;
|
|
56
|
+
/** Where write results and used token ids are kept (default: in memory; several instances share one). */
|
|
57
|
+
store?: IdempotencyStore;
|
|
58
|
+
/** Escape hatch: the raw McpServer of each request, to add hand-written tools, resources or views. */
|
|
59
|
+
mcp?: (server: McpServer, caller: Caller | null) => void;
|
|
60
|
+
/** The names of people of the installation by their ids (the values of `person` fields): what a host shows in place of an id. */
|
|
61
|
+
people?: PeopleResolver;
|
|
62
|
+
/** Pages on the app's own site framed by hosts (spec §5.1): who may frame them, the ticket's signing secret. Required with a same-site `url` page. */
|
|
63
|
+
embed?: EmbedOptions;
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* The app's embedded pages (spec §5.1), for the route in front of them (`@clegra/sdk/next`'s `embedProxy`, or any
|
|
67
|
+
* server): the ticket exchange, the headers of every embed response, and the caller of a page from its cookie.
|
|
68
|
+
*/
|
|
69
|
+
export type AppEmbed = {
|
|
70
|
+
/** Where the embed pages live (`/embed`). */
|
|
71
|
+
readonly path: string;
|
|
72
|
+
/** Where tickets are posted (`/embed/_ticket`). */
|
|
73
|
+
readonly exchangePath: string;
|
|
74
|
+
/** The headers every embed response carries: `Content-Security-Policy: frame-ancestors <declared hosts>`, `Referrer-Policy: no-referrer`. */
|
|
75
|
+
headers(): Record<string, string>;
|
|
76
|
+
/** `POST <path>/_ticket`: the ticket for the page's session cookie and a 303 to the page; a refusal page otherwise. */
|
|
77
|
+
exchange(request: Request): Promise<Response>;
|
|
78
|
+
/** The caller of the embed page `page` for this request (its session cookie), or null. */
|
|
79
|
+
caller(page: string, request: Request): Promise<EmbedCaller | null>;
|
|
80
|
+
};
|
|
81
|
+
/** Names by person id, for the ids it knows (spec §3, «People»). An id it leaves out is shown as an unknown person, never as the id. */
|
|
82
|
+
export type PeopleResolver = (ids: string[], ctx: Context) => Record<string, string> | Promise<Record<string, string>>;
|
|
83
|
+
/** The one `_meta` key of the host protocol (spec §7): `{ call, confirmation, settings }` on requests, `{ notifications, untrusted, l10n }` on results. */
|
|
84
|
+
export { META_KEY };
|
|
85
|
+
export type ErrorCode = "unauthorized" | "permission_denied" | "not_found" | "invalid_input" | "confirmation_required" | "conflict" | "internal";
|
|
86
|
+
/** A failure a handler may throw on purpose: it reaches the caller as `{ error: { code, message } }`. */
|
|
87
|
+
export declare class AppError extends Error {
|
|
88
|
+
readonly code: ErrorCode;
|
|
89
|
+
readonly details?: Record<string, unknown> | undefined;
|
|
90
|
+
constructor(code: ErrorCode, message: string, details?: Record<string, unknown> | undefined);
|
|
91
|
+
}
|
|
92
|
+
/** A notification as a result carries it (`_meta.clegra.notifications`): its texts in the caller's language, its recipients said. */
|
|
93
|
+
export type SentNotification = {
|
|
94
|
+
type?: string;
|
|
95
|
+
title: string;
|
|
96
|
+
body?: string;
|
|
97
|
+
uri?: string;
|
|
98
|
+
to: string[] | {
|
|
99
|
+
permission: string;
|
|
100
|
+
};
|
|
101
|
+
};
|
|
102
|
+
/** What one pass over the due later runs did: each run's outcome, and the notifications for the host to deliver. */
|
|
103
|
+
export type LaterReport = {
|
|
104
|
+
runs: {
|
|
105
|
+
id: string;
|
|
106
|
+
tool: string;
|
|
107
|
+
at: string;
|
|
108
|
+
status: LaterOutcome["status"];
|
|
109
|
+
message: string;
|
|
110
|
+
}[];
|
|
111
|
+
notifications: SentNotification[];
|
|
112
|
+
};
|
|
113
|
+
/** The fixed hint on the tools of an entity with cross-app references (spec §3.2): how a model opens such a record. */
|
|
114
|
+
export declare const CROSS_INPUT_HINT = "An input that takes a record of another app takes its URI (clegra://<app>/<entity>/<id>), as that app's search or lists give it.";
|
|
115
|
+
export declare const CROSS_APP_HINT = "A record of another app appears as { uri, kind }: the app the URI names opens it with its fetch tool.";
|
|
116
|
+
/**
|
|
117
|
+
* Text written by outsiders, as a model reads it (spec §7): inside
|
|
118
|
+
* `<untrusted>`, with `&`, `<` and `>` (and their full-width and small
|
|
119
|
+
* forms) escaped as XML text, so nothing in it is a tag: it can't close or
|
|
120
|
+
* open the wrapper, plainly, nested or already encoded.
|
|
121
|
+
*/
|
|
122
|
+
export declare const untrustedText: (value: string) => string;
|
|
123
|
+
/**
|
|
124
|
+
* The key of a record action's display hint (spec §6 rule 10): the record's title as the model read it, for a client's
|
|
125
|
+
* own approval prompt. Never trusted: the app names the record from `id`; a hint that names another record stops the call.
|
|
126
|
+
*/
|
|
127
|
+
export declare const RECORD_TITLE_PARAM = "record_title";
|
|
128
|
+
export declare class AppServer {
|
|
129
|
+
#private;
|
|
130
|
+
readonly name: string;
|
|
131
|
+
readonly options: ServerOptions;
|
|
132
|
+
readonly locale: string;
|
|
133
|
+
constructor(options: ServerOptions);
|
|
134
|
+
/** The embedded pages' side for the route in front of them: null when the app declares no `embed`. */
|
|
135
|
+
get embed(): AppEmbed | null;
|
|
136
|
+
/** The namespaced kinds this app defines (spec §3.1), before any entity that uses them. */
|
|
137
|
+
defineKinds(kinds: Record<string, KindConfig>): void;
|
|
138
|
+
/** An entity (spec §4): a Zod object with `.meta()` meaning, and its reads. */
|
|
139
|
+
registerEntity<S extends z.ZodObject>(name: string, config: EntityConfig<S>): EntityHandle<S>;
|
|
140
|
+
/** An action (spec §5), on an entity's records or global. */
|
|
141
|
+
registerAction<I extends z.ZodObject = z.ZodObject<{}>, E extends EntityHandle | undefined = undefined>(name: string, config: ActionConfig<I, E>, handler: ActionHandler<I, E>): ActionHandle;
|
|
142
|
+
/** A page (spec §6). Every entity has a `record` page by default; registering one with its name replaces it. */
|
|
143
|
+
registerPage<P extends z.ZodObject = z.ZodObject<{}>>(name: string, config: PageConfig<P>): {
|
|
144
|
+
readonly kind: "page";
|
|
145
|
+
readonly name: string;
|
|
146
|
+
};
|
|
147
|
+
/** A fragment type (spec §7): params, live data, a native template or an MCP Apps view. */
|
|
148
|
+
registerFragment<P extends z.ZodObject, T extends Template>(type: string, config: FragmentConfig<P, T>): {
|
|
149
|
+
readonly kind: "fragment";
|
|
150
|
+
readonly type: string;
|
|
151
|
+
};
|
|
152
|
+
/** An agent (spec §8): run by the host's model, with these tools. */
|
|
153
|
+
registerAgent(name: string, config: AgentConfig): void;
|
|
154
|
+
/** A permission (spec §8): `group.verb`. Returns its id. */
|
|
155
|
+
registerPermission(id: string, config: PermissionConfig): string;
|
|
156
|
+
/** The navigation: sections of pages (their references are checked with the manifest). */
|
|
157
|
+
registerNav(sections: NavSection[]): void;
|
|
158
|
+
/** A schedule: a global action the workspace host runs as the installation every `every` minutes. */
|
|
159
|
+
registerSchedule(name: string, config: ScheduleConfig): void;
|
|
160
|
+
/** A notification type the app's notifications name (`ctx.notify({ type })`). */
|
|
161
|
+
registerNotificationType(type: string, config: NotificationTypeConfig): void;
|
|
162
|
+
/** What the app does when the workspace host tells it of its installation, asks for its data, or asks it to delete them. */
|
|
163
|
+
registerLifecycle(config: LifecycleConfig): void;
|
|
164
|
+
/** A setting an administrator fills per installation (spec §2): text, number or boolean, never a secret. */
|
|
165
|
+
registerSetting(id: string, config: SettingConfig): void;
|
|
166
|
+
/** `clegra://<app>/<type>/<key>` (spec §4, §7). */
|
|
167
|
+
uri(type: string | EntityHandle, key: string): string;
|
|
168
|
+
/** A fragment instance's URI: the record id for record cards, base64url of the sorted params' JSON otherwise. */
|
|
169
|
+
fragmentUri(instance: FragmentInstance): string;
|
|
170
|
+
/** A URI of this app read back: its type and key, or null. */
|
|
171
|
+
parseUri(uri: string): {
|
|
172
|
+
type: string;
|
|
173
|
+
key: string;
|
|
174
|
+
params: Record<string, unknown>;
|
|
175
|
+
} | null;
|
|
176
|
+
/**
|
|
177
|
+
* Runs the tenant's due later runs now, as `clegra_later` does when the workspace host calls it: for an app whose
|
|
178
|
+
* callers are its own (no workspace host runs its schedules), from the app's own cron. `settings`: what handlers
|
|
179
|
+
* see as `ctx.settings`. The notifications in the report are the app's to deliver.
|
|
180
|
+
*/
|
|
181
|
+
runLater(tenant: string, options?: {
|
|
182
|
+
settings?: Record<string, unknown>;
|
|
183
|
+
locale?: string;
|
|
184
|
+
}): Promise<LaterReport>;
|
|
185
|
+
/** A fresh McpServer for one request, for this caller (null: manifest and views only). `request`: what `fetch` knows of the HTTP request. */
|
|
186
|
+
createMcpServer(caller: Caller | null, era?: "legacy" | "modern", request?: RequestInfo): McpServer;
|
|
187
|
+
/** The manifest (spec §2), built from the definition: pure JSON. Throws on references that don't hold. */
|
|
188
|
+
manifest(): Manifest;
|
|
189
|
+
/**
|
|
190
|
+
* A dev access token (tests, local hosts). `host: "workspace"` makes the SDK ask for confirmation proofs.
|
|
191
|
+
* `person: null` with `host: "workspace"`: the installation-level caller (schedules, later runs, lifecycle tools).
|
|
192
|
+
*/
|
|
193
|
+
devToken(input?: {
|
|
194
|
+
person?: string | Person | null;
|
|
195
|
+
permissions?: string[] | "all";
|
|
196
|
+
host?: "workspace" | "plain";
|
|
197
|
+
installation?: string;
|
|
198
|
+
locale?: string;
|
|
199
|
+
}): Promise<string>;
|
|
200
|
+
/**
|
|
201
|
+
* A dev confirmation proof for one call (what a workspace host signs after «Confirm»). For an action with `later`
|
|
202
|
+
* it carries the run's deadline (`until`, from the arguments' `at` and the action's window) unless `until` is given.
|
|
203
|
+
*/
|
|
204
|
+
devConfirmation(input: {
|
|
205
|
+
tool: string;
|
|
206
|
+
args: Record<string, unknown>;
|
|
207
|
+
call: string;
|
|
208
|
+
person?: string;
|
|
209
|
+
installation?: string;
|
|
210
|
+
until?: number;
|
|
211
|
+
}): Promise<string>;
|
|
212
|
+
/**
|
|
213
|
+
* Readiness for serving (`listen` in `@clegra/sdk/node`, a framework adapter): the manifest is built and
|
|
214
|
+
* checked, the dev authority started. Returns the dev sign-in code when dev sign-in is on.
|
|
215
|
+
*/
|
|
216
|
+
start(): Promise<{
|
|
217
|
+
devCode: string | null;
|
|
218
|
+
}>;
|
|
219
|
+
/**
|
|
220
|
+
* One HTTP request (Fetch API): MCP at `<path>/mcp`, the manifest, OAuth metadata, the dev authority, `<path>/health`.
|
|
221
|
+
* `info.remoteAddress`: the address the request came from. Dev sign-in and dev tokens count only when it is
|
|
222
|
+
* a loopback address, checked on every request (`listen` passes the socket's; without it dev mode stays shut).
|
|
223
|
+
*/
|
|
224
|
+
fetch(request: Request, info?: {
|
|
225
|
+
remoteAddress?: string | null;
|
|
226
|
+
}): Promise<Response>;
|
|
227
|
+
/** Whether dev sign-in is on (it then answers loopback callers only). */
|
|
228
|
+
get devMode(): boolean;
|
|
229
|
+
}
|