@akanjs/cli 3.0.0-alpha.100 → 3.0.0-alpha.102

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/.build-stamp CHANGED
@@ -1 +1 @@
1
- 660f8be823b788bf2ecd02a3c5e6ddf5f69299e441b1cb0dd9dbe76b49fbf618
1
+ f85744854c5059c6127e0a720de471b1722191744441237c6816d7c59ec0fc90
@@ -470,7 +470,7 @@ Full contract — credential handshake, room revalidation, socket cleanup scopin
470
470
  - **The guards are also the MCP exposure decision** — see MCP Exposure. An endpoint that names none is not published to agents at all, and a mutation whose only guard is `Public` is refused, so a missing `guards` array now costs visibility as well as authorization.
471
471
  - Resource guards are `Can<Verb><Model>` classes in `srvkit/guards.ts` that `implements Guard` with an `async canPass(context)`. They **fail closed**: no resource named ⇒ `false`; a load that throws ⇒ `logger.warn` then `false`. Admin bypass goes first.
472
472
  - Keep `static name = "User";` on guard classes. `fetch` serializes guard names and the API explorer filters on them; it looks like dead code, and deleting it breaks the UI. Comment it so the next reader knows.
473
- - **Every guard class also declares `static scope: GuardScope`, and it is required with no default.** `"account"` means the verdict reads the caller and nothing about the call, so it can be evaluated with no arguments — which is what lets an MCP listing hide what this caller certainly cannot use. `"resource"` means it needs the call's arguments (`context.getArg()`) and fails closed without them, so it is never evaluated for a listing: the entry stays visible and is stopped at call time. Getting it wrong is not a type error, so the marker is mandatory rather than defaulted — `SignedIn` / `Admin` / role checks are `"account"`, and every `Can<Verb><Model>` is `"resource"`.
473
+ - **Every guard class also declares `static scope: GuardScope`, and it is required with no default.** `"account"` means the verdict reads the caller and nothing about the call, so it can be evaluated with no arguments — which is what lets an MCP listing hide what this caller certainly cannot use. `"resource"` means it needs the call's arguments (`context.getArg()`) and fails closed without them, so it is never evaluated for a listing: the entry stays visible and is stopped at call time. Getting it wrong is not a type error, so the marker is mandatory rather than defaulted — `SignedIn` / `Admin` / role checks are `"account"`, and every `Can<Verb><Model>` is `"resource"`. An `"account"` guard that throws at listing time reached for arguments it does not have: the entry is hidden from every caller and the guard is named once in the log as mismarked. A guard that admits no model at all — `Person` — adds `static agents = false`; the MCP catalogue then refuses every endpoint it guards outright, so the person-only act is absent from the document rather than hidden per caller.
474
474
  - The acting user arrives via `.with(Self)` / `.with(CurrentUserId)` / `.with(Me)`. Never trust a client-supplied id.
475
475
  - Guards ship with the library that owns the model and are imported by its own signals through the package path, so a mounting app inherits authorization and cannot forget it.
476
476
  - Services re-check ownership even when a guard already gated the call — two independent gates.
@@ -617,13 +617,38 @@ it.
617
617
  slice and generated CRUD only, never a named slice or a custom endpoint. It is an opt-**out**, and it is
618
618
  curation, not authorization: HTTP serves the endpoint exactly as before.
619
619
  - **Narrow by cost, and read the boot log first.** MCP forbids a `$ref` across entries, so every entry inlines the
620
- full schema of every model it mentions and the listing is re-sent whole to every agent that connects. A plain
621
- 21-field model costs 12.6KB over eight entries; `mcp: { cru: false }` takes it to 4.7KB. `MCP catalogue: … ·
622
- listing 214KB` plus a per-signal `MCP catalogue cost:` line says where it went.
620
+ schema of every model it mentions and the listing is re-sent whole to every agent that connects. By default a
621
+ response schema names a nested model instead of inlining it (`outputSchema: "shallow"`; `"full"` restores the
622
+ closure, `"none"` drops the schema and keeps the text block) and a request schema asks for a relation's id, which
623
+ is what the wire carries. `MCP catalogue: … · listing 214KB` plus a per-signal `MCP catalogue cost:` line says
624
+ where the rest went; `mcp: { cru: false }` on a model is the next lever. `outputSchema` moves wire bytes and client
625
+ memory only — the model receives names, descriptions and input schemas (measured: 219 tools ≈ 41k tokens either
626
+ way) — so tool count and the input model behind `create*` / `update*` are what cost context. In one line:
627
+ `Person` for an act reserved for a person, `mcp: { cru: false }` for the tools whose input models cost the model
628
+ tokens, `outputSchema` for nothing that reaches the model.
623
629
  - Settings live in the app's `lib/option.ts` — `option.setMcp({ enabled, readOnly, path, version, instructions,
624
- allowedOrigins, pageSize, language, auth })`, **not `main.ts`**. Each field has an `AKAN_MCP_*` env spelling.
625
- `AKAN_MCP_READONLY=true` is the read-only-deployment valve, not the exposure switch; `AKAN_MCP=false` takes the
626
- whole surface off.
630
+ allowedOrigins, pageSize, language, outputSchema, rateLimit, auth })`, or `setMcp((env) => …)` for one derived from the server env, **not
631
+ `main.ts`**. Each field has an `AKAN_MCP_*` env spelling. `AKAN_MCP_READONLY=true` is the read-only-deployment
632
+ valve, not the exposure switch; `AKAN_MCP=false` takes the whole surface off. Every call that executes an
633
+ endpoint is rate-limited per caller (120 a minute, 8 in flight, per process; 429 + `Retry-After`) — `rateLimit`
634
+ / `AKAN_MCP_RATE_LIMIT` tunes or disables it.
635
+ - **Authentication is the same server.** An app mounting `libs/shared` serves the OAuth 2.1 authorization server
636
+ beside `/mcp` — `/.well-known/oauth-authorization-server`, `/oauth/authorize`, `/oauth/token`, `/oauth/register`
637
+ (RFC 7591; Cursor's `cursor://` redirect admitted) plus the consent page `libs/shared/page/oauth/consent` — and
638
+ names itself as the issuer, so `/mcp` demands a bearer token, verifies its signature, and refuses one carrying no
639
+ `aud`. A token is the app's own access JWT plus `aud`/`iss`/`client_id`, so `AccountMiddleware` and the guards
640
+ judge it unchanged; there is no scope. Per-app knobs live in `env.server.*` under `oauth` (`consentPath` and
641
+ `signinPath` with the basePath, `clients`, `dynamicRegistration`, `allowedRedirectSchemes`, `clientIdMetadata`,
642
+ `enabled`). `/mcp` reads the `Authorization` header only — a cookie is dropped at the door — and `JWT_SECRET` is
643
+ mandatory outside `local`, because the derived fallback is forgeable from three public names. A grant is revoked
644
+ whole — `POST /oauth/revoke` (RFC 7009) by the client, `fetch.revokeOAuthConnection(sessionId)` by the account's
645
+ owner, `fetch.listOAuthConnections()` to see them — and a revoked access token is refused at its next call.
646
+ - **A person may, a model may not.** An agent's token names its `client_id` and `aud`; a browser session has
647
+ neither, and `context.origin` is `"mcp"` for a call through the MCP endpoint. `guards: [Every, Person]` refuses a
648
+ model and, because `Person` declares `static agents = false`, takes the entry out of the MCP catalogue document
649
+ itself (named in the boot log like `mcp: false`); `.with(AgentCall)` hands an endpoint the same verdict as a
650
+ boolean to narrow what the call sets in motion; `isAgentCall(context)` is the function behind both
651
+ (`@libs/shared/srvkit`). Never sniff `aud` through a cast.
627
652
  - **The refusals are fail-closed**: a declared `mcp: false`, an endpoint with no `guards`, a mutation with no real
628
653
  guard, `pubsub` and `message`, an `Any` or `Upload` return, a file upload, a required `Any` argument, and the
629
654
  generated `light<Model>` read. A `prompt` also refuses a list argument and any `Any` argument. **Every refusal
@@ -746,10 +771,11 @@ shape, so `cascade` never means "related" — it means one of exactly these:
746
771
  forms: a relation, an id with `ref`, or a polymorphic id with `refPath`. An array, a Map, `ref` together with
747
772
  `refPath`, and a field naming no owner each fail the class build.
748
773
  - **A `refPath` must name an `enumOf` field** — a free-form owner type is unknowable at build time. The one
749
- exception is opt-in and priced: `polymorphic: "any"` alongside `cascade: "removeWith"` takes a free-form
750
- `String` type field holding the owner's refName, and sweeps for children on **every** model's removal. The
751
- sweep is one indexed probe, but a single wildcard edge turns every cascade in the app back to one document at
752
- a time; the boot log names the edges in one `info` line.
774
+ exception is opt-in and priced: `cascade: "removeWithAny"` takes a free-form `String` type field holding the
775
+ owner's refName, and sweeps for children on **every** model's removal. The sweep is one indexed probe, but a
776
+ single wildcard edge turns every cascade in the app back to one document at a time; the boot log names the
777
+ edges in one `info` line. The action carries its own `refPath` in the option type, so the widening cannot be
778
+ declared apart from the direction it widens.
753
779
  - **A cascade goes through the target's service, never its model** — that path is what runs the target's
754
780
  `_postRemove`, where a module puts the side effect the removal has to carry.
755
781
  - **Nothing checks whether another document still references the same target.** `File` in particular is deduped by
@@ -14,7 +14,17 @@
14
14
  ],
15
15
  "update": {
16
16
  "filePath": "./mcpRule.instruction.md",
17
- "contents": ["exposure rule", "configuration", "declaring endpoints", "refusals and wire behaviour", "prompts"],
17
+ "contents": [
18
+ "exposure rule",
19
+ "configuration",
20
+ "declaring endpoints",
21
+ "refusals and wire behaviour",
22
+ "prompts",
23
+ "rolling out to an app",
24
+ "choosing what to open",
25
+ "writing instructions",
26
+ "verifying an app"
27
+ ],
18
28
  "rules": [
19
29
  "Use current Akan APIs only",
20
30
  "State the rule before the reason, and keep the reason to one clause",
@@ -1,7 +1,8 @@
1
1
  # Akan MCP Exposure Guideline
2
2
 
3
3
  ## Purpose
4
- Use this when writing a `*.signal.ts`, configuring `option.setMcp(...)`, or debugging a tool an agent cannot see.
4
+ Use this when writing a `*.signal.ts`, configuring `option.setMcp(...)`, debugging a tool an agent cannot see, or
5
+ opening an app's service to agents end to end — the rollout checklist and the exposure design rules are at the end.
5
6
  The always-loaded convention set carries the short version; this is the full contract.
6
7
 
7
8
  ## Exposure Rule
@@ -42,17 +43,21 @@ export class FileSlice extends slice(srv.file, {
42
43
  the guard rules keep out.
43
44
  - **Reach for it by cost, not by taste.** Every entry inlines the schema of every model it mentions, so a plain
44
45
  21-field model with one named slice costs 12.6KB across its eight entries. `mcp: { cru: false }` on that model
45
- takes it to 4.7KB — the write entries carry both the input *and* the full model, and are 63% of it.
46
+ takes it to 4.7KB — the write entries carry both the input *and* the full model, and are 63% of it. Those figures
47
+ are for `outputSchema: "full"`; the default names nested models instead of inlining them (below). Measured on a
48
+ fully open 347-tool catalogue: 1194KB before, 532KB under the default, 194KB under `"none"`, and 1046KB even under
49
+ `"full"` — the id and nullable savings apply in every mode — before any endpoint was curated.
46
50
 
47
51
  ## Configuration
48
52
  Settings live in the app's `lib/option.ts` — `option.setMcp({ … })`, taking `enabled`, `readOnly`, `path`,
49
- `version`, `instructions`, `allowedOrigins`, `pageSize`, `language`, `legacyTextBlock`, and `auth`. **Not `main.ts`**: the gateway
53
+ `version`, `instructions`, `allowedOrigins`, `pageSize`, `language`, `legacyTextBlock`, `outputSchema`, `rateLimit`, and `auth`. **Not `main.ts`**: the gateway
50
54
  there only spawns children, and `option.ts` is the app-authored file `server.ts` already hands to the process that
51
55
  mounts `/mcp`. Every lib's option is read in mount order with the app's last, so an app tightens what a library
52
56
  declared without restating it. Each field also has an env spelling (`AKAN_MCP`, `AKAN_MCP_READONLY`,
53
57
  `AKAN_MCP_PATH`, `AKAN_MCP_VERSION`, `AKAN_MCP_INSTRUCTIONS`, `AKAN_MCP_ALLOWED_ORIGINS`, `AKAN_MCP_PAGE_SIZE`,
54
- `AKAN_MCP_LANGUAGE`, `AKAN_MCP_LEGACY_TEXT`, `AKAN_MCP_AUTH_SERVERS`, `AKAN_MCP_SCOPES`, `AKAN_MCP_RESOURCE`) for a
55
- deployment that configures what the source does not, which the option overrides.
58
+ `AKAN_MCP_LANGUAGE`, `AKAN_MCP_LEGACY_TEXT`, `AKAN_MCP_OUTPUT_SCHEMA`, `AKAN_MCP_RATE_LIMIT`, `AKAN_MCP_CONCURRENT`,
59
+ `AKAN_MCP_AUTH_SERVERS`, `AKAN_MCP_SCOPES`, `AKAN_MCP_RESOURCE`) for a deployment that configures what the source does
60
+ not, which the option overrides.
56
61
  The two booleans answer to `AKAN_PUBLIC_MCP` / `AKAN_PUBLIC_MCP_READONLY` too, the same pairing `AKAN_OPENAPI`
57
62
  has, and a value written in code wins over the env of the same name — an explicit `undefined` is not a value.
58
63
  `AKAN_MCP_PATH` is normalized to a leading `/`, because the route key and the OAuth metadata path are both built by
@@ -142,20 +147,50 @@ export class TaskEndpoint extends endpoint(srv.task, ({ mutation, prompt }) => (
142
147
  `AKAN_MCP_LEGACY_TEXT=false` — leaves a one-line pointer in the text block instead, for a deployment whose
143
148
  clients read the structured half. A scalar return is unaffected: it has no structured half to point at, so it
144
149
  ships as the value itself either way.
150
+ - **A request schema asks for a relation's id, and a response schema names a nested model.** `serialize` sends a
151
+ relation field as its id and the server never converts an object back, so publishing the related model's shape
152
+ asked an agent for what the document layer cannot take. On the response side every entry inlines the transitive
153
+ closure of every model it mentions (a `$ref` may not cross entries), and on an open catalogue 83% of the bytes
154
+ were the same schemas repeated — so a nested database model is published as `{ type: "object", description:
155
+ "<ModelName>" }` and the returned model keeps every field of its own; an embedded scalar stays inline. Measured,
156
+ that took a 347-tool listing from 1194KB to 532KB, and one user's paged `tools/list` to 320KB.
157
+ `option.setMcp({ outputSchema: "full" })` (`AKAN_MCP_OUTPUT_SCHEMA`) restores the closure; `"none"` publishes no
158
+ `outputSchema` at all — results still ship as `structuredContent`, and the text block stays on whatever
159
+ `legacyTextBlock` said, because a client validates structured content only against a declared schema. Inside a
160
+ `$defs` an id carries no `pattern` and nullability rides in `type: [T, "null"]` (an enum lists `null` too); a
161
+ top-level argument keeps the spellings the OpenAPI document uses. **Know which bytes reach the model.** The
162
+ provider tool definition a client builds from a listing carries the name, the description and the input schema —
163
+ the Anthropic and OpenAI tool formats have no field for an output schema — so `outputSchema` is a wire and
164
+ client-memory cost, and the model's context is spent on names, descriptions, input schemas and the number of
165
+ tools. Curate those (`mcp: false`, `mcp: { cru: false }`, `readOnly`) to cut context; pick `outputSchema` for the
166
+ transfer.
167
+ Measured on a 219-tool user listing: the wire carried 366KB, the client reported ≈41.6k tokens for it, and the
168
+ server's own count of names + descriptions + input schemas was 95KB — the same 41k at 2.4 characters per token.
169
+ So `outputSchema` (`full` / `shallow` / `none`) moves wire bytes and client memory and **not one model token**;
170
+ do not tune it expecting a context win. What does cost context: the tool count, and the input model inlined
171
+ behind every `create*` / `update*` (22 such tools were 8.7k of those 41k; the heaviest single tool was
172
+ `updateUser` at ~900 tokens) — `mcp: { cru: false }` on a model whose writes an agent has no business with is
173
+ the lever that pays. A custom mutation whose arguments are plain ids is cheap (nine contract tools, 1.2k). In
174
+ one line: `Person` for an act reserved for a person, `mcp: { cru: false }` for the tools whose input models cost
175
+ the model tokens, and `outputSchema` for nothing that reaches the model at all.
145
176
  - A refused endpoint answers the *same* "unknown tool" as one that does not exist. Never make that
146
- message more helpful — the difference is what enumerates your private surface. A guard's refusal is generalized
147
- the same way: the caller reads `You are not permitted to perform this action.`, never `Access denied by guard:
148
- Admin`, which names your authorization structure to the one caller barred from it. A domain `Err` resolves
149
- through the dictionary first and keeps its own words.
177
+ message more helpful — the difference is what enumerates your private surface. Every 401 and 403 is generalized
178
+ the same way, the framework's `Access denied by guard: Admin` and an app's `No authentication with roles: admin`
179
+ alike: the caller reads `You are not permitted to perform this action.`, because either sentence names your
180
+ authorization structure to the one caller barred from it. A domain `Err` at any other status resolves through
181
+ the dictionary and keeps its own words, placeholders filled.
150
182
  - The `readOnly` / `destructive` / `idempotent` hints a client renders are derived from the endpoint type and key
151
183
  and are not configurable. Clients are told to distrust hints; they are never a gate.
152
184
  - **`AKAN_MCP_READONLY=true` is the read-only-deployment valve, not the exposure switch.** It drops every mutation
153
185
  whatever it declared, and reports each one in the boot log like any other refusal.
154
186
  - OAuth resource metadata is published at `/.well-known/oauth-protected-resource` (and at that path plus the mount
155
- path, the spelling most clients try first). `AKAN_MCP_AUTH_SERVERS`, `AKAN_MCP_SCOPES`, and `AKAN_MCP_RESOURCE`
156
- configure it; `insufficient_scope` is enforced only once `AKAN_MCP_SCOPES` is set. A token carrying no `aud` at
157
- all is refused once `AKAN_MCP_AUTH_SERVERS` names an issuer — that issuer mints tokens for its other resources
158
- too — and accepted while none is named, because a first-party Akan token is bound by app and environment.
187
+ path, the spelling most clients try first). `auth.authorizationServers` / `AKAN_MCP_AUTH_SERVERS`,
188
+ `auth.scopes` / `AKAN_MCP_SCOPES`, `auth.resource` / `AKAN_MCP_RESOURCE` and `auth.verify` configure it;
189
+ `insufficient_scope` is enforced only once scopes are declared. Naming an issuer changes three things at once: a
190
+ request with no credential is answered 401 from `initialize` on (an MCP client starts its OAuth flow on nothing
191
+ else), a token carrying no `aud` is refused (that issuer mints for its other resources too), and the challenge
192
+ carries no `error` code (RFC 6750 §3.1 reserves it for a credential that was presented). A server naming no
193
+ issuer keeps anonymous access and accepts a first-party token, which is bound by app and environment instead.
159
194
  - **The boot log names every published entry with no dictionary `.desc()`.** An agent picks a tool by its
160
195
  description, so a missing one is a broken tool. What the framework generates has no text of its own and borrows
161
196
  the model's: the generated list reads the `.of()` label, and the base CRUD tools append the model's `.desc()` to
@@ -163,9 +198,19 @@ export class TaskEndpoint extends endpoint(srv.task, ({ mutation, prompt }) => (
163
198
  `akan quality scan` rule for this any more: a source scanner found the exposure only as an `mcp:` literal, and
164
199
  with exposure derived from the guards the resolved catalogue is the only place that can answer.
165
200
  - A browser-hosted client needs `allowedOrigins` **and** the CORS answer the server sends back for those origins.
166
- Every other MCP client sends no `Origin` at all, and the one that does is matched against the forwarded host so
167
- a proxy does not turn each call into a 403 — which is only as trustworthy as an edge that *overwrites* that
168
- header. `AKAN_MCP_RESOURCE` pins the resource identifier where you cannot guarantee it.
201
+ Every other MCP client sends no `Origin` at all, and the one that does is matched against the server's public
202
+ origin: the configured `auth.resource`'s when there is one (`libs/shared` derives it from the issuer, so a mounted
203
+ app is always pinned), and only otherwise the forwarded host — which is as trustworthy as an edge that
204
+ *overwrites* that header. The same origin names the `resource_metadata` URL in every 401 challenge.
205
+ `AKAN_MCP_RESOURCE` is the pin for an app that mounts no authorization server.
206
+ - **Every call that executes an endpoint is rate-limited per caller** — `tools/call`, `resources/read` and
207
+ `prompts/get`, never a listing. A caller is the bearer's session (`sid`), so one connector counts as one however
208
+ many connections it opens; a credential-less caller is the address the proxy recorded, and callers with none share
209
+ one bucket. Defaults are 120 calls a minute and 8 in flight, counted per process (N replicas grant N budgets); past
210
+ either the answer is HTTP 429 with JSON-RPC `-32010` and a `Retry-After`, and an unknown tool name is counted like
211
+ any other call. `option.setMcp({ rateLimit: { calls, windowMs, concurrent } })`, `rateLimit: false` to turn it off;
212
+ `AKAN_MCP_RATE_LIMIT=<calls>` or `<calls>/<seconds>` (`off` disables) and `AKAN_MCP_CONCURRENT`. The boot log says
213
+ which is in force, and warns when it is off.
169
214
  - **A `resources/read` uri that does not decode** — a stray `%` — is `Unknown resource`, not a server failure.
170
215
  - **A caller's own mistake is reported as one** and never as a server failure: an argument that is missing,
171
216
  unparseable or **undeclared** comes back as `isError` naming it — `additionalProperties: false` travels in the
@@ -181,9 +226,13 @@ export class TaskEndpoint extends endpoint(srv.task, ({ mutation, prompt }) => (
181
226
  body names one), and one that leaves a mirror out is refused just like one that contradicts the body: a gateway
182
227
  rule keyed on a header never fires for the request that omitted it. Legacy requests are not checked. Capabilities
183
228
  are derived from the catalogue, so a server with no prompts does not advertise `prompts`.
184
- - **An expired or wrongly-audienced bearer token is refused up front**, so an agent is told to authenticate rather
185
- than that the tool does not exist. Its **signature is not checked** — that needs your app's own secret — so a
186
- token signed wrong, like an opaque one, still degrades to an anonymous caller.
229
+ - **An expired, wrongly-audienced or unverifiable bearer token is refused up front**, so an agent is told to
230
+ authenticate rather than that the tool does not exist. The signature is checked through `auth.verify`, which the
231
+ module that mints the tokens supplies (`libs/shared` does, from the app's signing secret); without a verifier the
232
+ claims are read unverified and a token signed wrong, like an opaque one, degrades to an anonymous caller.
233
+ - **`/mcp` reads the `Authorization` header and nothing else.** The `cookie` header is deleted from the request
234
+ before the account middleware runs, so a same-site page cannot drive `tools/call` on the visitor's ambient session
235
+ — the request class `CrossSiteGuard` shields every mutation from, which this route never passes through.
187
236
  - **Resource URIs**: `akan://<model>/{id}`, `akan://<model>/list` for the model's own list, and
188
237
  `akan://<model>/list/<sliceKey>` for a slice's. The root list takes no third segment on purpose — any token
189
238
  there is one a slice could also be named. **Those three are the whole set**, so only the generated reads that
@@ -192,6 +241,78 @@ export class TaskEndpoint extends endpoint(srv.task, ({ mutation, prompt }) => (
192
241
  - **The catalogue is one language**, `en` unless `language` says otherwise: it is built once at boot and cached by
193
242
  clients, so there is no `Accept-Language` negotiation.
194
243
 
244
+ ## Authentication — The Authorization Server Is The Same Process
245
+
246
+ `libs/shared/lib/_oauth` is an OAuth 2.1 authorization server (RFC 8414 metadata, PKCE `S256` only, RFC 7591
247
+ registration, Client ID Metadata Documents, RFC 9207 `iss`) served by the app that serves `/mcp`. Its `option.ts`
248
+ names the issuer and hands `McpAuth` a verifier, so mounting the lib is all an app does; the protocol engine it
249
+ delegates to lives in `akanjs/server` (`OAuthAuthorize`, `OAuthToken`, `OAuthRegistration`, `OAuthClientIdMetadata`,
250
+ `OAuthPkce`, `OAuthRedirect`, `OAuthMetadata`, `OAuthErrors`) and is unit-tested without a container.
251
+
252
+ - **Endpoints, at the origin's root:** `GET /.well-known/oauth-authorization-server`, `GET /oauth/authorize`,
253
+ `POST /oauth/token` (form-encoded), `POST /oauth/register`, `POST /oauth/revoke` (RFC 7009, form-encoded, the
254
+ same client authentication as the token endpoint). The consent step is `libs/shared/page/oauth/consent`
255
+ — a server-rendered page whose two forms post to `/api/approveOAuthConsent/<requestId>` and
256
+ `/api/denyOAuthConsent/<requestId>` and follow the 302 back to the client. The account's own controls are
257
+ `fetch.listOAuthConnections()` (one entry per live grant: `sessionId`, `clientId`, `clientName`, `userAgent`,
258
+ `createdAt`, `expiresAt`, `isCurrent`) and `fetch.revokeOAuthConnection(sessionId)`; the app renders the
259
+ connected-apps page, the lib supplies the two endpoints and the `oauth.connectedApps` / `disconnect` /
260
+ `noConnectedApps` / `currentConnection` translations. All of it is `mcp: false`.
261
+ - **Revocation closes a grant, not a token.** A refresh token or an access token both name one grant (the access
262
+ token carries the lineage as `sid`); revoking either closes the refresh lineage and denylists the lineage id for
263
+ an access token's lifetime, so a stateless token dies early — `/mcp` answers 401 `invalid_token` and
264
+ `AccountMiddleware` treats it as anonymous, at the next call. `/oauth/revoke` answers an empty 200 whether the token
265
+ was live, unknown, or another client's (RFC 7009 §2.2 — it must not double as a token oracle); only a failed client
266
+ authentication is 401. Changing a password still revokes every session, browser ones included; disconnecting an
267
+ app revokes that one.
268
+ - **A person may, a model may not.** The one honest marker of "a model is driving this call" is on the token: an
269
+ access token minted here names its `client_id` and the MCP resource as `aud`, and a browser session carries
270
+ neither; `SerAccount` declares those claims, so nothing casts to read them. Read it three ways, all in
271
+ `@libs/shared/srvkit`: `.with(AgentCall)` hands the endpoint a boolean (drop `sendEmails` on an agent's say-so);
272
+ `guards: [Every, Person]` refuses a model outright and, being `account`-scoped, hides the entry from every MCP
273
+ listing (signing, paying, anything the page treats as a deliberate act); `isAgentCall(context)` inside a guard or
274
+ service. All three read `context.origin === "mcp"` first — a field on `SignalContext`, never the trace, which can
275
+ be absent — and the token second, so an agent's token used over plain HTTP is still an agent. `Person` also
276
+ declares **`static agents = false`**, the guard-level marker the catalogue reads: an endpoint it guards is refused
277
+ from the document itself (named in the boot log like `mcp: false`, with the guards' `static name`s — the explorer's
278
+ filter labels, which need not be the class names), not merely
279
+ hidden per caller at listing time — so the boot count, the size line and every agent's listing agree, and no
280
+ second flag is needed. Any guard that admits no model may declare the marker; a listing still evaluates
281
+ `account`-scoped guards per caller, so the two mechanisms compose.
282
+ - **The flow:** `POST /mcp` with no token → 401 with `resource_metadata` → the client reads the PRM, then the AS
283
+ metadata, registers (or uses a pre-registered / URL `client_id`), opens `/oauth/authorize` in a browser → the
284
+ server parks the request and redirects to the consent page (via `signinPath?redirect=` when anonymous) → the user
285
+ allows → `redirect_uri?code&state&iss` → the client posts the code and its PKCE verifier to `/oauth/token` → an
286
+ access token (1h, `aud` = the MCP resource, `iss`, `client_id`, `sub`, and the account's `self`/`me`) plus a
287
+ rotating refresh token (30d; reuse revokes the family). The token is the app's own access JWT, so
288
+ `AccountMiddleware` and every guard read it exactly as a browser session; nothing is scoped.
289
+ - **Invariants:** an authorization request lives ten minutes, binds to the first signed-in account that opens it,
290
+ and is decided once; a code lives sixty seconds and is consumed on first exchange even if that exchange fails; a
291
+ redirect URI must be registered and match exactly, loopback ports excepted (RFC 8252 §7.3); a refresh token is
292
+ bound to the client it was issued to. A `client_id` that is an HTTPS URL with a path is fetched as a metadata
293
+ document: the name is judged first (no address literal, no reserved suffix, no port), then resolved, and refused
294
+ when any address is private, loopback, link-local, CGNAT or multicast — the rebinding window between lookup and
295
+ fetch is what the deployment's egress policy still owns.
296
+ - **Per-app configuration** goes in `env.server.*` under `oauth`: `consentPath` and `signinPath` (with the basePath
297
+ when the app has one — `/office/oauth/consent`), `clients` (pre-registered, with an optional `clientSecret`),
298
+ `dynamicRegistration` (on by default: Claude Code and claude.ai register themselves), `allowedRedirectSchemes`
299
+ (`["cursor"]` by default, for Cursor's desktop callback), `accessTokenSeconds` (3600, also how long a revoked
300
+ access token can outlive its grant), `clientIdMetadata: { enabled, refusePrivateAddresses }` (both on; `enabled:
301
+ false` turns Client ID Metadata Documents off and the metadata stops advertising them — Claude Code then registers
302
+ dynamically instead), `issuer` and `resource` (only when a tunnel or an edge makes the derived origin wrong),
303
+ `enabled: false` to take the server and the `/mcp` credential requirement away together. The signin page must
304
+ honour `?redirect=` to return the user to the consent page.
305
+ - **Clients:** Claude Code — `claude mcp add --transport http <name> <origin>/mcp` and nothing else; it registers,
306
+ opens the browser to `http://localhost:<port>/callback`, refreshes on 401. claude.ai — a custom connector by URL
307
+ (needs public HTTPS; DCR or the Advanced-settings client id/secret; callback
308
+ `https://claude.ai/api/mcp/auth_callback`). Cursor — the URL alone (DCR with a `cursor://` redirect), or a
309
+ pre-registered client in `mcp.json` `auth` with `http://localhost:8787/callback` /
310
+ `https://www.cursor.com/agents/mcp/oauth/callback` registered. A first-party browser token no longer opens `/mcp`
311
+ once the issuer is named; `--header "Authorization: Bearer …"` needs a token minted with `aud`.
312
+ - **`JWT_SECRET`** (or `security.jwtSecret`) is required outside `local`; the boot refuses without it, because the
313
+ derived fallback is seeded from the app, environment and repo names and forges an admin token for anyone who
314
+ knows them. `AKAN_ALLOW_DERIVED_JWT_SECRET=1` accepts that risk explicitly.
315
+
195
316
  ## `prompt()`
196
317
  **`prompt()`** is invoked by the *user* — a client renders it as a slash command — not chosen by the model. `exec`
197
318
  returns `PromptMessage[]`, or a bare string that is wrapped into one user message; build them with `Msg.user` /
@@ -215,3 +336,103 @@ over the ask.
215
336
  frames down included, and is a no-op when nobody is streaming — so the same code runs unchanged over HTTP, a
216
337
  websocket, and in tests. `McpProgress.streaming` says whether anyone is reading, for a report whose message
217
338
  costs something to assemble.
339
+
340
+ ## Rolling MCP Out To An App
341
+
342
+ The goal of exposing a service over MCP is that a person uses it through an agent instead of through the page:
343
+ one browser consent (the app's own sign-in included), then an hour-long access token and a thirty-day rotating
344
+ refresh token stand in for every later sign-in. The token is the app's own access JWT, so what an agent may do is
345
+ exactly what that person may do over HTTP — nothing is widened and nothing is scoped. Do these in order; steps 2
346
+ and 3 are the ones whose omission shows up as a 404 or a doubled basePath on the consent page.
347
+
348
+ 1. **Mount the lib that carries the authorization server** (`libs/shared`) and confirm `lib/_oauth`,
349
+ `page/oauth/consent` and `srvkit/oauthServer.ts` are present. Its `option.ts` declares `auth` for `setMcp`, and
350
+ `setMcp` merges field by field in mount order with the app last — the app never restates `auth`.
351
+ 2. **`akan.config.ts`: `syncPageLibs: true`** (or the lib's name in an array). `akan sync <app>` links the consent
352
+ route under every basePath the app declares; the link folder is generated and never committed.
353
+ 3. **`env.server.*` → `oauth`.** `consentPath` / `signinPath` carry the basePath the browser sees
354
+ (`/office/oauth/consent`, `/office/signin`) and are omitted for an app without one. The server hands the
355
+ sign-in page `?redirect=` as the app's router names the route — basePath removed — because `router.push` puts
356
+ the locale and basePath back; the app adds nothing. `issuer` (`AKAN_MCP_AUTH_SERVERS` for the resource side)
357
+ only behind a tunnel or an edge that renames the host, `resource` (`AKAN_MCP_RESOURCE`) only when `path` moved
358
+ off `/mcp`, `clients` + `dynamicRegistration: false` only for a deployment that closes registration.
359
+ 4. **The sign-in page honours `?redirect=`** by passing it unchanged to the password and SSO controls — a
360
+ router-space path, never prefixed by hand. Accepting it needs only `startsWith("/") && !startsWith("//")`.
361
+ 5. **`lib/option.ts`: `option.setMcp({ instructions, legacyTextBlock: false })`** (`AKAN_MCP_INSTRUCTIONS`,
362
+ `AKAN_MCP_LEGACY_TEXT`). Leave `readOnly` (`AKAN_MCP_READONLY`) off when the point is to let people *use* the
363
+ service; it is the valve for a deployment that must not write, not the way to curate.
364
+ 6. **`JWT_SECRET`** (or `security.jwtSecret`) in every deployment outside `local`; the boot refuses without it.
365
+ 7. **Read the boot log** — `MCP catalogue: tools=… · listing …KB`, the `MCP catalogue cost:` line, one `warn` per
366
+ refusal, and the list of published entries with no `.desc()`. A tool missing from it is missing everywhere.
367
+ 8. **Connect once per app** — `claude mcp add --transport http <name> <issuer>/mcp`; a second entry for the same
368
+ server with a pre-registered client tests a registration mode, it does not add anything a user needs.
369
+
370
+ ## Choosing What To Open
371
+
372
+ One rule: **an endpoint is open to an agent when the same person could do the same thing from the page, under
373
+ the same guards.** What stays closed is closed because no agent has a reason to call it, not because of who may
374
+ — and that is the only thing `mcp: false` says.
375
+
376
+ | Endpoint | Decision |
377
+ |---|---|
378
+ | Domain read slices (`inOrg`, `inProject`, `inSelf`, `byStatuses`) | Open. A named slice publishes only when it declares its **own** `guards`; the `slice()` map reaches the root slice and the generated CRUD, never a named slice. A search slice only on data that may be enumerated. |
379
+ | The root slice and generated CRUD | Published by default; `root:` is `Admin`, so a user token never lists it. Take the cost line first: `mcp: { cru: false }` keeps the reads and drops the writes of a model whose write entries are most of its bytes; `mcp: false` for an internal or sensitive model. |
380
+ | Domain mutations (`startTask`, `completeTicket`) | Open when a person would ask an agent to do it for them; a resource guard is mandatory. An act that cannot be undone — signing, paying, sending, removing — either stays off or says so in its `.desc()`: MCP has no approval card. |
381
+ | Steps of a UI state machine (`requestPhoneCodeForSignin`, `setPasswordInPrepareUser`, a prepare-user flow) | `mcp: false`. Perfectly guarded, and only ever called by mistake. |
382
+ | Authentication, SSO, and the OAuth protocol endpoints | Already `mcp: false` where they are declared. |
383
+ | File upload, an `Any` / `Upload` return, a required `Any` argument, `pubsub` / `message`, `light<Model>` | Refused by the framework; nothing to write. |
384
+ | Admin-only endpoints | Leave the `Admin` guard; an account-scope guard hides the entry from every caller it refuses. |
385
+ | An act only a person may take (signing, paying, sending to a customer) | `guards: [Every, Person]` refuses every agent and, because `Person` declares `static agents = false`, takes the entry out of the catalogue document — no `mcp: false` needed, the HTTP route untouched. When a person and a model may both call but not to the same effect, keep the guards and take `.with(AgentCall)` to narrow what the call sets in motion. |
386
+
387
+ - **Scope is what makes hiding possible.** `static scope: "account"` (a role check) is evaluated with no arguments
388
+ and filters the listing per caller; `"resource"` (`Can<Verb><Model>`, ownership) needs `context.getArg()`, stays
389
+ listed, and stops the call. Marking a resource guard `"account"` would make the listing lie — the marker has no
390
+ default for that reason.
391
+ - **Identity comes from the internal args** (`.with(Self)`, `.with(Account)`, `.with(Me)`), never from an id the
392
+ client sent, and the service re-checks ownership behind the guard.
393
+ - **An admin who signs in on the consent page mints an admin token.** A connector created under an admin account
394
+ passes `Admin` guards; treat that as an operational decision, and read the request's subject type when in doubt.
395
+ - **Return what answers the question.** A count-or-summary endpoint taking an id beats a document; a nullable model
396
+ return publishes no `outputSchema`, so prefer a non-null return plus an `Err`. Bulky page-only fields are
397
+ `field.visual`. Narrow a list with a named filter slice, never with the root list's raw `query`.
398
+
399
+ ## Writing `instructions`
400
+
401
+ `*.abstract.md` and `<Agent.Guide>` never reach an MCP client. Exactly three texts do: `instructions`, every
402
+ published entry's `.desc()`, and a `prompt()`. All three are English, whatever the users speak — the reader is a
403
+ model, and the catalogue is built once in one `language` and cached by clients.
404
+
405
+ - **`instructions` is the workflow.** Five to eight sentences, in this order: what the app is and what its nouns
406
+ mean; **which tool to call first** and which ids the rest take; how a name becomes an id; what a write confirms
407
+ before it runs and which writes cannot be undone; what this server does *not* do and where that is done instead.
408
+
409
+ ```ts
410
+ instructions: [
411
+ "Operations tools for a back-office that runs consulting projects.",
412
+ "An org is one company; a project belongs to an org; a ticket is one unit of work on a project.",
413
+ "Start from orgInSelf, then projectInOrg and ticketInProject; every other tool takes the ids those return.",
414
+ "Prefer ticketStatusInProject for 'how is it going' and ticketInProject only when the user asks for detail.",
415
+ "createTicket, startTicket and completeTicket write on the caller's behalf: confirm the project and title first.",
416
+ "Nothing here signs, invoices or uploads a file; those are deliberate acts on the record's own page.",
417
+ ].join(" "),
418
+ ```
419
+ - **`.desc()` is the reason to pick one tool** — what it returns and when to use it, two clauses. An id argument's
420
+ `.desc()` names the tool that returns it (`From projectInOrg`). The generated CRUD borrows the model's `.of()`
421
+ label and `.desc()`, which is the only text those entries can carry.
422
+ - **`prompt()` is a workflow the user invokes** as a slash command, not one the model chooses — a weekly report,
423
+ an onboarding check. Put the ask in `Msg.user` at a high `priority` and the attachments in `Msg.resource` masked
424
+ by their `Light` model at a low one.
425
+
426
+ ## Verifying An App
427
+
428
+ - `akan lint <app>`, `akan typecheck <app>`, `akan sync <app>`, then the boot log above.
429
+ - The lib's own suites run wherever it is mounted: the OAuth signal test (metadata, registration, both `authorize`
430
+ redirects, code exchange, `/mcp` with the minted token and the refusal of a first-party or forged one, refresh
431
+ rotation) and the refresh-session and option unit tests.
432
+ - **One exposure test per app**, in a `lib/<model>.signal.test.ts`: list `tools/list` with a user token and pin the
433
+ names with `toEqual`, and assert the curated and admin-only ones with `not.toContain`. Exposure is derived from
434
+ the guards, so a guard change fails this test first — which is the point. The framework's own pattern is
435
+ `pkgs/akanjs/server/mcp/mcp.integration.test.ts`.
436
+ - Live: connect a client, consent, call a tool, `claude mcp logout`, authenticate again. `AKAN_PUBLIC_LOG_LEVEL=debug`
437
+ prints one `OAuth token request grant_type=… client_id=…` line per token call; two refreshes in the same second
438
+ both answering 200 is the grace window working, not a fault.
@@ -133,11 +133,13 @@ shape, so `cascade` never means "related" — it means one of exactly these:
133
133
  `refPath`. An array, a Map, `ref` together with `refPath`, and a field naming no owner each fail the class build.
134
134
  - **A `refPath` must name an `enumOf` field** — a free-form owner type is unknowable at build time, so every
135
135
  model's removal would have to sweep the polymorphic table on the chance it is the owner.
136
- - **`polymorphic: "any"` buys that sweep on purpose**, for the one shape an enum cannot express: a child whose
137
- owner is any model in the app, named by a free-form `String` holding the owner's refName.
136
+ - **`cascade: "removeWithAny"` buys that sweep on purpose**, for the one shape an enum cannot express: a child
137
+ whose owner is any model in the app, named by a free-form `String` holding the owner's refName. It is a third
138
+ action rather than a flag beside `removeWith`, because the widening and the direction are one decision — the
139
+ option type pairs the action with the `refPath` it reads the owner off, so neither can be declared alone.
138
140
 
139
141
  ```ts
140
- parent: field(ID, { refPath: "parentType", cascade: "removeWith", polymorphic: "any" }),
142
+ parent: field(ID, { refPath: "parentType", cascade: "removeWithAny" }),
141
143
  parentType: field(String), // holds the owner's refName
142
144
  ```
143
145
 
@@ -148,11 +150,12 @@ shape, so `cascade` never means "related" — it means one of exactly these:
148
150
  `info` line naming the edges — that line is the answer to "why does this app remove everything per document".
149
151
  The opt-in is what keeps an app that declared none on the fast path.
150
152
 
151
- Refused at the class build: `polymorphic: "any"` on a `refPath` that already names an `enumOf` (the enum names
152
- the candidates and indexes better — keep one), a `typeKey` that is not a `String` (the sweep matches a refName
153
- against that column, and a column that cannot hold one silently finds nothing), and the option anywhere other
154
- than a `cascade: "removeWith"` field with a `refPath`. A wildcard owner is also exempt from the mount check
155
- that a monomorphic owner fails at boot — it names no module to mount.
153
+ Refused at the class build: `removeWithAny` on a `refPath` that already names an `enumOf` (the enum names the
154
+ candidates and indexes better — use `removeWith`), a `typeKey` that is not a `String` (the sweep matches a
155
+ refName against that column, and a column that cannot hold one silently finds nothing), and the action with no
156
+ `refPath` at all — that last one is a typecheck error at the call site, and the class build keeps the same
157
+ refusal for the macro and bundled paths that reach it untyped. A wildcard owner is also exempt from the mount
158
+ check that a monomorphic owner fails at boot — it names no module to mount.
156
159
  - **A cascade goes through the target's service, never its model** — that path is what runs the target's
157
160
  `_postRemove`, where a module puts the side effect the removal has to carry.
158
161
  - **Bulk is decided at boot, per target model, for both directions.** A target with no `remove` schema hook, no
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akanjs/cli",
3
- "version": "3.0.0-alpha.100",
3
+ "version": "3.0.0-alpha.102",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -33,7 +33,7 @@
33
33
  "@langchain/openai": "^1.4.6",
34
34
  "@tailwindcss/node": "^4.3.0",
35
35
  "@trapezedev/project": "^7.1.4",
36
- "akanjs": "3.0.0-alpha.100",
36
+ "akanjs": "3.0.0-alpha.102",
37
37
  "chalk": "^5.6.2",
38
38
  "commander": "^14.0.3",
39
39
  "dayjs": "^1.11.20",