@sdxc/kit 2026.10.25 → 2026.10.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +28 -15
  2. package/changelog.jsonl +40 -5
  3. package/dist/architecture/graph.d.ts +16 -3
  4. package/dist/architecture/graph.js +37 -19
  5. package/dist/architecture/layers.d.ts +10 -3
  6. package/dist/architecture/layers.js +38 -9
  7. package/dist/commands/destroy.d.ts +1 -1
  8. package/dist/commands/make.d.ts +5 -5
  9. package/dist/commands/make.js +11 -8
  10. package/dist/commands/scaffold.d.ts +1 -1
  11. package/dist/contract.d.ts +3 -3
  12. package/dist/doctor/checks.d.ts +2 -2
  13. package/dist/doctor/checks.js +14 -2
  14. package/dist/doctor/constant-names.d.ts +17 -0
  15. package/dist/doctor/constant-names.js +106 -0
  16. package/dist/doctor/dependencies.d.ts +3 -3
  17. package/dist/doctor/dependencies.js +3 -3
  18. package/dist/doctor/fan-out.d.ts +3 -2
  19. package/dist/doctor/fan-out.js +4 -3
  20. package/dist/doctor/fetch-param.d.ts +15 -0
  21. package/dist/doctor/fetch-param.js +37 -0
  22. package/dist/doctor/files.d.ts +2 -0
  23. package/dist/doctor/files.js +4 -0
  24. package/dist/doctor/local-const.d.ts +15 -0
  25. package/dist/doctor/local-const.js +54 -0
  26. package/dist/doctor/logger.d.ts +15 -0
  27. package/dist/doctor/logger.js +41 -0
  28. package/dist/doctor/orphans.d.ts +3 -3
  29. package/dist/doctor/orphans.js +33 -7
  30. package/dist/doctor/process-env.d.ts +15 -0
  31. package/dist/doctor/process-env.js +39 -0
  32. package/dist/doctor/project.js +17 -13
  33. package/dist/doctor/result-throws.d.ts +5 -4
  34. package/dist/doctor/result-throws.js +6 -5
  35. package/dist/doctor/source-rule.d.ts +35 -0
  36. package/dist/doctor/source-rule.js +52 -0
  37. package/dist/doctor/stack-imports.d.ts +15 -0
  38. package/dist/doctor/stack-imports.js +60 -0
  39. package/dist/doctor/syntax.d.ts +31 -0
  40. package/dist/doctor/syntax.js +56 -0
  41. package/dist/make/binding.d.ts +13 -8
  42. package/dist/make/binding.js +96 -64
  43. package/dist/make/from-model.js +2 -7
  44. package/dist/make/index.js +2 -7
  45. package/dist/package-manager.d.ts +6 -0
  46. package/dist/package-manager.js +25 -2
  47. package/dist/scaffold/index.js +2 -7
  48. package/dist/ui/commands.js +2 -5
  49. package/dist/ui/registry.d.ts +2 -2
  50. package/dist/upgrade/changelog.d.ts +2 -0
  51. package/dist/upgrade/changelog.js +2 -0
  52. package/dist/upgrade/project.d.ts +2 -2
  53. package/dist/upgrade/prompt.d.ts +3 -2
  54. package/dist/upgrade/prompt.js +43 -2
  55. package/package.json +3 -3
  56. package/stubs/scaffold.test-mcp.stub +5 -1
  57. package/templates/app/AGENTS.md +3 -1
  58. package/templates/app/app/commands/db/fresh.ts +20 -13
  59. package/templates/app/app/commands/db/migrate.ts +42 -32
  60. package/templates/app/app/http/controllers/api/openapi.test.ts +29 -0
  61. package/templates/app/app/http/controllers/api/openapi.tsx +8 -2
  62. package/templates/app/app/http/controllers/mcp.test.ts +16 -0
  63. package/templates/app/app/http/middleware/access.ts +6 -3
  64. package/templates/app/app/http/middleware/page.ts +3 -4
  65. package/templates/app/app/initializers/database.test.ts +6 -1
  66. package/templates/app/app/initializers/openapi.ts +5 -4
  67. package/templates/app/app/initializers/router.tsx +3 -4
  68. package/templates/app/app/test/cloudflare-workers.test.ts +27 -0
  69. package/templates/app/app/test/cloudflare-workers.ts +17 -4
  70. package/templates/app/app/test/database.ts +33 -0
  71. package/templates/app/app/test/mcp.ts +96 -0
  72. package/templates/app/resources/layouts/document.tsx +2 -3
@@ -4,15 +4,33 @@
4
4
  * on the empty tables.
5
5
  */
6
6
 
7
+ import type { AnyCommandContext, CommandResult } from "@sdxc/cli";
8
+
7
9
  import { createCommand, failure, success } from "@sdxc/cli";
8
10
  import { openDatabase } from "@sdxc/cloudflare-mocks/sqlite";
9
11
  import { isFailure } from "@sdxc/result";
10
12
 
13
+ import type { MigrationDatabase } from "~/app/services/migrations";
14
+
11
15
  import commandset from "~/app/commands";
12
16
  import { LOCAL_DATABASE_FILE, PROJECT_ROOT } from "~/app/initializers/local-database";
13
17
  import { runCommand } from "~/app/services/commands";
14
18
  import { applyMigrations, dropTables, readMigrations } from "~/app/services/migrations";
15
19
 
20
+ /** Empties `database` and applies the chain to it, printing each table dropped and migration applied. */
21
+ async function rebuild(
22
+ ctx: AnyCommandContext,
23
+ database: MigrationDatabase,
24
+ ): Promise<CommandResult> {
25
+ let dropped = dropTables(database);
26
+ if (isFailure(dropped)) return dropped;
27
+ ctx.stdout(`Dropped ${dropped.data.length} ${dropped.data.length === 1 ? "table" : "tables"}\n`);
28
+ let applied = applyMigrations(database, await readMigrations(PROJECT_ROOT));
29
+ if (isFailure(applied)) return applied;
30
+ ctx.stdout(applied.data.map((name) => `Applied ${name}\n`).join(""));
31
+ return success();
32
+ }
33
+
16
34
  /** Refuses `--remote`: emptying production has no undo. */
17
35
  export default createCommand(commandset.db.fresh, async (ctx) => {
18
36
  if (ctx.flags.remote) {
@@ -20,18 +38,7 @@ export default createCommand(commandset.db.fresh, async (ctx) => {
20
38
  }
21
39
 
22
40
  let database = openDatabase(LOCAL_DATABASE_FILE);
23
- try {
24
- let dropped = dropTables(database);
25
- if (isFailure(dropped)) return dropped;
26
- ctx.stdout(
27
- `Dropped ${dropped.data.length} ${dropped.data.length === 1 ? "table" : "tables"}\n`,
28
- );
29
- let applied = applyMigrations(database, await readMigrations(PROJECT_ROOT));
30
- if (isFailure(applied)) return applied;
31
- ctx.stdout(applied.data.map((name) => `Applied ${name}\n`).join(""));
32
- } finally {
33
- database.close();
34
- }
35
-
41
+ let rebuilt = await rebuild(ctx, database).finally(() => database.close());
42
+ if (isFailure(rebuilt)) return rebuilt;
36
43
  return ctx.flags.seed ? runCommand(ctx, ["db", "seed"]) : success();
37
44
  });
@@ -4,7 +4,7 @@
4
4
  * against the production database. Safe to run twice: an applied migration is skipped.
5
5
  */
6
6
 
7
- import type { AnyCommandContext } from "@sdxc/cli";
7
+ import type { AnyCommandContext, CommandResult } from "@sdxc/cli";
8
8
  import type { Result } from "@sdxc/result";
9
9
 
10
10
  import { createCommand, success } from "@sdxc/cli";
@@ -28,6 +28,14 @@ const REMOTE_PENDING = s.array(s.object({ Name: s.string() }));
28
28
  // oxlint-disable-next-line no-control-regex -- matching the ESC that starts a color sequence
29
29
  const ANSI = /\u001B\[[0-9;]*m/g;
30
30
 
31
+ /** The migration names `cf d1 migrations list` printed as JSON, or `null` for any other output. */
32
+ function listedNames(printed: string): string[] | null {
33
+ let json = wrap(() => JSON.parse(printed.replace(ANSI, "")) as unknown);
34
+ if (isFailure(json)) return null;
35
+ let parsed = s.parseSafe(REMOTE_PENDING, json.data);
36
+ return parsed.success ? parsed.value.map((row) => row.Name) : null;
37
+ }
38
+
31
39
  /** The migrations the production database lacks, as `cf d1 migrations list` reports them. */
32
40
  async function remotePending(ctx: AnyCommandContext): Promise<Result<string[], Error>> {
33
41
  let listed = await ctx.exec(
@@ -35,43 +43,35 @@ async function remotePending(ctx: AnyCommandContext): Promise<Result<string[], E
35
43
  { cwd: PROJECT_ROOT, stdio: "collect" },
36
44
  );
37
45
  if (isFailure(listed)) return listed;
38
- let printed = listed.data.stdout;
39
- let json = wrap(() => JSON.parse(printed.replace(ANSI, "")) as unknown);
40
- let parsed = isFailure(json) ? undefined : s.parseSafe(REMOTE_PENDING, json.data);
41
- if (parsed === undefined || !parsed.success) {
42
- return failure(new Error(`cf d1 migrations list printed ${printed.trim()}`));
43
- }
44
- return success(parsed.value.map((row) => row.Name));
46
+ let names = listedNames(listed.data.stdout);
47
+ return names === null
48
+ ? failure(new Error(`cf d1 migrations list printed ${listed.data.stdout.trim()}`))
49
+ : success(names);
45
50
  }
46
51
 
47
- /**
48
- * With `--pending`, prints one migration name per line and applies nothing; an up-to-date
49
- * database prints nothing. `sdxc deploy` reads that list to show what production will run.
50
- */
51
- export default createCommand(commandset.db.migrate, async (ctx) => {
52
- if (ctx.flags.remote) {
53
- if (ctx.flags.pending) {
54
- let pending = await remotePending(ctx);
55
- if (isFailure(pending)) return pending;
56
- ctx.stdout(pending.data.map((name) => `${name}\n`).join(""));
57
- return success();
58
- }
59
- let applied = await ctx.exec(
60
- ["cf", "d1", "migrations", "apply", DATABASE_ID, "--dir", MIGRATIONS_DIRECTORY],
61
- { cwd: PROJECT_ROOT },
62
- );
63
- return isFailure(applied) ? applied : success();
52
+ /** Applies, or with `pending` lists, the migrations the production database lacks, through `cf`. */
53
+ async function migrateRemote(ctx: AnyCommandContext, pending: boolean): Promise<CommandResult> {
54
+ if (pending) {
55
+ let names = await remotePending(ctx);
56
+ if (isFailure(names)) return names;
57
+ ctx.stdout(names.data.map((name) => `${name}\n`).join(""));
58
+ return success();
64
59
  }
60
+ let applied = await ctx.exec(
61
+ ["cf", "d1", "migrations", "apply", DATABASE_ID, "--dir", MIGRATIONS_DIRECTORY],
62
+ { cwd: PROJECT_ROOT },
63
+ );
64
+ return isFailure(applied) ? applied : success();
65
+ }
65
66
 
67
+ /** Applies, or with `pending` lists, the migrations the local SQLite file lacks. */
68
+ async function migrateLocal(ctx: AnyCommandContext, pending: boolean): Promise<CommandResult> {
66
69
  let database = openDatabase(LOCAL_DATABASE_FILE);
67
70
  try {
68
71
  let migrations = await readMigrations(PROJECT_ROOT);
69
- if (ctx.flags.pending) {
70
- ctx.stdout(
71
- pendingMigrations(database, migrations)
72
- .map((migration) => `${migration.name}\n`)
73
- .join(""),
74
- );
72
+ if (pending) {
73
+ let names = pendingMigrations(database, migrations).map((migration) => migration.name);
74
+ ctx.stdout(names.map((name) => `${name}\n`).join(""));
75
75
  return success();
76
76
  }
77
77
  let applied = applyMigrations(database, migrations);
@@ -85,4 +85,14 @@ export default createCommand(commandset.db.migrate, async (ctx) => {
85
85
  } finally {
86
86
  database.close();
87
87
  }
88
- });
88
+ }
89
+
90
+ /**
91
+ * With `--pending`, prints one migration name per line and applies nothing; an up-to-date
92
+ * database prints nothing. `sdxc deploy` reads that list to show what production will run.
93
+ */
94
+ export default createCommand(commandset.db.migrate, (ctx) =>
95
+ ctx.flags.remote
96
+ ? migrateRemote(ctx, ctx.flags.pending === true)
97
+ : migrateLocal(ctx, ctx.flags.pending === true),
98
+ );
@@ -0,0 +1,29 @@
1
+ /**
2
+ * `/api/openapi.json`, fetched through the app's router: one document naming the published
3
+ * origin, which a client revalidates by its `ETag`.
4
+ */
5
+
6
+ import { describe, expect, test } from "vitest";
7
+
8
+ import { createWebRouter } from "~/app/initializers/router";
9
+ import { SITE_URL } from "~/config/constants";
10
+
11
+ describe("openapi", () => {
12
+ test("names SITE_URL as the server whatever origin the request reached", async () => {
13
+ let response = await createWebRouter().fetch("http://localhost:5173/api/openapi.json");
14
+
15
+ let document = (await response.json()) as { servers: Array<{ url: string }> };
16
+ expect(document.servers).toEqual([{ url: SITE_URL }]);
17
+ });
18
+
19
+ test("answers a request carrying the document's ETag with 304", async () => {
20
+ let router = createWebRouter();
21
+ let first = await router.fetch("https://example.com/api/openapi.json");
22
+
23
+ let second = await router.fetch("https://example.com/api/openapi.json", {
24
+ headers: { "If-None-Match": first.headers.get("ETag") ?? "" },
25
+ });
26
+
27
+ expect(second.status).toBe(304);
28
+ });
29
+ });
@@ -10,8 +10,14 @@ import api from "~/app/http/middleware/api";
10
10
  import { createApiDocument } from "~/app/initializers/openapi";
11
11
  import routes from "~/routes/api";
12
12
 
13
+ /**
14
+ * Builds the document on the first request and serves that build, with its `ETag`, to every
15
+ * later one for the life of the Worker.
16
+ */
17
+ const serveDocument = openapiHandler(() => createApiDocument().build());
18
+
13
19
  export default createAction(routes.api.openapi, {
14
20
  middleware: api,
15
- /** GET /api/openapi.json, naming the origin the request reached as the API's server. */
16
- handler: (ctx) => openapiHandler(() => createApiDocument(ctx.url.origin).build())(ctx),
21
+ /** GET /api/openapi.json, as JSON or YAML by `Accept` or `?format=`. */
22
+ handler: (ctx) => serveDocument(ctx),
17
23
  });
@@ -0,0 +1,16 @@
1
+ /**
2
+ * `/mcp`, called through the app's router the way an MCP client calls it, with `callTool` from
3
+ * `app/test/mcp.ts`.
4
+ */
5
+
6
+ import { describe, expect, test } from "vitest";
7
+
8
+ import { callTool } from "~/app/test/mcp";
9
+
10
+ describe("mcp", () => {
11
+ test("answers a call to a tool the server does not offer with an error", async () => {
12
+ let call = await callTool("missing", {});
13
+
14
+ expect(call.isError).toBe(true);
15
+ });
16
+ });
@@ -5,6 +5,7 @@
5
5
  */
6
6
 
7
7
  import { access } from "@sdxc/authz/middleware/router";
8
+ import * as s from "remix/data-schema";
8
9
  import { Session } from "remix/session";
9
10
 
10
11
  import type { Actor } from "~/app/policies/policy";
@@ -15,14 +16,16 @@ import policy from "~/app/policies/policy";
15
16
  /** The session key a sign-in stores the visitor under, and `signedIn` reads back. */
16
17
  export const ACTOR_KEY = "actor";
17
18
 
19
+ /** The shape a signed-in visitor is stored in; any other value reads as a guest. */
20
+ const STORED_ACTOR = s.object({ id: s.string() });
21
+
18
22
  /**
19
23
  * The signed-in visitor the session holds, or `undefined` for a guest. A request without a
20
24
  * session, or one whose stored value has no string `id`, reads as a guest.
21
25
  */
22
26
  export function signedIn(session: Session | undefined): Actor | undefined {
23
- let value: unknown = session?.get(ACTOR_KEY);
24
- if (typeof value !== "object" || value === null || !("id" in value)) return undefined;
25
- return typeof value.id === "string" ? { id: value.id } : undefined;
27
+ let stored = s.parseSafe(STORED_ACTOR, session?.get(ACTOR_KEY));
28
+ return stored.success ? { id: stored.value.id } : undefined;
26
29
  }
27
30
 
28
31
  /** The roles the session's visitor holds: `member` once signed in, none for a guest. */
@@ -1,8 +1,7 @@
1
1
  /**
2
- * The middleware every page declares: the parsed form body, the cross-origin check a
3
- * cookie-backed form relies on, the visitor's session, access and language, the honeypot every
4
- * form submission must pass, the security headers, and the document's assets and renderer. A
5
- * page controller passes it as its `middleware`, so only requests that render a document pay.
2
+ * The chain every page controller passes as its `middleware`: form body, cross-origin check,
3
+ * session, access, language, honeypot, security headers, and the document's assets and
4
+ * renderer, so only requests that render a document pay for them.
6
5
  */
7
6
 
8
7
  import { assets } from "@sdxc/assets-middleware";
@@ -1,11 +1,12 @@
1
1
  /**
2
2
  * The database the router and the job dispatcher publish as `ctx.db`, run against the
3
- * in-memory D1 stand-in tests receive as the `DB` binding.
3
+ * in-memory D1 stand-in tests receive as the `DB` binding, and the migration chain applied to it.
4
4
  */
5
5
 
6
6
  import { describe, expect, test } from "vitest";
7
7
 
8
8
  import { openDatabase } from "~/app/initializers/database";
9
+ import { migrate } from "~/app/test/database";
9
10
 
10
11
  describe("openDatabase", () => {
11
12
  test("runs SQL through the DB binding", async () => {
@@ -15,4 +16,8 @@ describe("openDatabase", () => {
15
16
 
16
17
  expect(result.rows).toEqual([{ answer: 42 }]);
17
18
  });
19
+
20
+ test("takes every migration in database/migrations/ on an empty binding", async () => {
21
+ await expect(migrate()).resolves.toBeUndefined();
22
+ });
18
23
  });
@@ -5,17 +5,18 @@
5
5
 
6
6
  import { createDocument } from "@sdxc/openapi";
7
7
 
8
+ import { SITE_URL } from "~/config/constants";
8
9
  import problems from "~/config/problems";
9
10
  import { HEALTH } from "~/routes/api";
10
11
 
11
12
  /**
12
- * Starts the document for the origin the API is served from, which OpenAPI requires as an
13
- * absolute server URL; `build()` assembles it, failing on a contract it cannot express.
13
+ * Starts the document with `SITE_URL`, the origin the app is published at, as its server, since
14
+ * OpenAPI requires an absolute one; `build()` assembles it, failing on a contract it cannot express.
14
15
  */
15
- export function createApiDocument(origin: string) {
16
+ export function createApiDocument() {
16
17
  return createDocument({
17
18
  info: { title: "App API", version: "1.0.0" },
18
- servers: [{ url: origin }],
19
+ servers: [{ url: SITE_URL }],
19
20
  problems,
20
21
  }).add(HEALTH);
21
22
  }
@@ -49,10 +49,9 @@ declare module "remix/router" {
49
49
  }
50
50
 
51
51
  /**
52
- * Builds the router the Worker forwards each request to. Its middleware is what pages and
53
- * endpoints both need, written inline so {@link AppContext} reads what each one publishes; a
54
- * controller adds its contract's chain, `app/http/middleware/page.ts` or `api.ts`, itself.
55
- * While developing, `/_emails` previews every mapped email in every supported language.
52
+ * Builds the router the Worker forwards each request to, with the middleware pages and
53
+ * endpoints share written inline so {@link AppContext} reads what each publishes; a controller
54
+ * adds `page.ts` or `api.ts` itself. While developing, `/_emails` previews every mapped email.
56
55
  */
57
56
  export function createWebRouter() {
58
57
  let router = createRouter({
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The `cloudflare:workers` stand-in Vitest resolves: a Durable Object class extends its
3
+ * `DurableObject` and runs against a mock state, as the Worker runtime would construct it.
4
+ */
5
+
6
+ import { createDurableObjectState } from "@sdxc/cloudflare-mocks";
7
+ import { DurableObject, env } from "cloudflare:workers";
8
+ import { describe, expect, test } from "vitest";
9
+
10
+ /** A counter in the shape `sdxc make do` writes, with storage of its own. */
11
+ class CounterDO extends DurableObject<Cloudflare.Env> {
12
+ /** Counts one more and answers the total. */
13
+ async increment(): Promise<number> {
14
+ let count = ((await this.ctx.storage.get<number>("count")) ?? 0) + 1;
15
+ await this.ctx.storage.put("count", count);
16
+ return count;
17
+ }
18
+ }
19
+
20
+ describe("DurableObject", () => {
21
+ test("lets a class extending it run against a mock state", async () => {
22
+ let counter = new CounterDO(createDurableObjectState(), env);
23
+
24
+ expect(await counter.increment()).toBe(1);
25
+ expect(await counter.increment()).toBe(2);
26
+ });
27
+ });
@@ -1,8 +1,7 @@
1
1
  /**
2
- * The `cloudflare:workers` module under Vitest, which imports the app's modules in Node, outside
3
- * the Worker runtime. It carries the development secrets `.env.example` lists, so a module that
4
- * reads `env` at import loads the same way it does under `bun dev`. Its bindings are in-memory
5
- * stand-ins that behave like Cloudflare's, so a test reads and writes real SQL through `DB`.
2
+ * The `cloudflare:workers` module under Vitest, which runs the app's modules in Node: the
3
+ * development secrets `.env.example` lists, so a module reading `env` at import loads as under
4
+ * `bun dev`, and in-memory bindings that behave like Cloudflare's, so `DB` runs real SQL.
6
5
  */
7
6
 
8
7
  import {
@@ -25,3 +24,17 @@ export const env = {
25
24
  TURNSTILE_SITE_KEY: "1x00000000000000000000AA",
26
25
  TURNSTILE_SECRET_KEY: "1x0000000000000000000000000000000AA",
27
26
  } as Partial<Cloudflare.Env> as Cloudflare.Env;
27
+
28
+ /**
29
+ * The base class a Durable Object extends, holding the state and `env` it is constructed with,
30
+ * so a test builds one with `createDurableObjectState()` from `@sdxc/cloudflare-mocks`.
31
+ */
32
+ export class DurableObject<Env = Cloudflare.Env> {
33
+ ctx: DurableObjectState;
34
+ env: Env;
35
+
36
+ constructor(ctx: DurableObjectState, env: Env) {
37
+ this.ctx = ctx;
38
+ this.env = env;
39
+ }
40
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The database a test reads and writes: the in-memory `DB` binding with every migration in
3
+ * `database/migrations/` applied in name order, as `sdxc run db migrate` applies them, and
4
+ * factories that write through the app's own models.
5
+ *
6
+ * @see {@link https://sdxc.dev/docs/operations-and-testing/test-data}
7
+ */
8
+
9
+ import { createFactories } from "@sdxc/data-model/testing";
10
+ import { env } from "cloudflare:workers";
11
+
12
+ import { openDatabase } from "~/app/initializers/database";
13
+ import registry from "~/app/models";
14
+
15
+ /** Every migration's SQL by path, bundled by Vite, so a test reads them without the file system. */
16
+ const MIGRATIONS = import.meta.glob<string>("/database/migrations/*.sql", {
17
+ query: "?raw",
18
+ import: "default",
19
+ eager: true,
20
+ });
21
+
22
+ /**
23
+ * Applies every migration to the `DB` binding. Each test file starts with an empty binding, so a
24
+ * file runs this once, in `beforeAll`.
25
+ */
26
+ export async function migrate(): Promise<void> {
27
+ for (let path of Object.keys(MIGRATIONS).sort()) await env.DB.exec(MIGRATIONS[path] ?? "");
28
+ }
29
+
30
+ /** Factories writing through the app's models over the `DB` binding, with values that repeat run to run. */
31
+ export function factories() {
32
+ return createFactories(registry.bind({ db: openDatabase() }), { seed: 1 });
33
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Calls the app's MCP tools the way a client does: a JSON-RPC `tools/call` posted to `/mcp`. A
3
+ * guest's call goes through the app's router, running every middleware a real call runs; a
4
+ * member's goes through a router binding that principal, which the API grants nobody yet.
5
+ *
6
+ * @see {@link https://sdxc.dev/docs/operations-and-testing/mcp-server}
7
+ */
8
+
9
+ import { access } from "@sdxc/authz/middleware/router";
10
+ import { models } from "@sdxc/data-model/router";
11
+ import { database } from "@sdxc/database-middleware";
12
+ import { LATEST_PROTOCOL_VERSION, MetaKey } from "@sdxc/mcp";
13
+ import { createRouter } from "remix/router";
14
+
15
+ import { openDatabase } from "~/app/initializers/database";
16
+ import mcp from "~/app/initializers/mcp";
17
+ import { createWebRouter } from "~/app/initializers/router";
18
+ import registry from "~/app/models";
19
+ import abilities from "~/app/policies/abilities";
20
+ import policy from "~/app/policies/policy";
21
+ import routes from "~/routes/api";
22
+
23
+ /** Who a call is made as: a guest, as the API binds every caller, or a signed-in member. */
24
+ export type Caller = "guest" | "member";
25
+
26
+ /** What a call answered: its text, and whether the tool, or the protocol, reported a failure. */
27
+ export interface ToolCall {
28
+ text: string;
29
+ isError: boolean;
30
+ }
31
+
32
+ /** The JSON-RPC response to a `tools/call`. */
33
+ interface CallResponse {
34
+ result?: { content?: Array<{ text?: string }>; isError?: boolean };
35
+ error?: { message?: string };
36
+ }
37
+
38
+ /**
39
+ * A router answering `/mcp` over the app's database and models as a member, the principal the
40
+ * API binds once it authenticates its callers.
41
+ */
42
+ function createMemberRouter() {
43
+ let router = createRouter({
44
+ middleware: [
45
+ database(openDatabase()),
46
+ models(registry, (ctx) => ({ db: ctx.db })),
47
+ access(policy, { roles: ["member"], facts: { actor: { id: "1" } }, load: [abilities] }),
48
+ ],
49
+ });
50
+ router.map(routes.mcp, (ctx) => mcp.fetch(ctx));
51
+ return router;
52
+ }
53
+
54
+ /**
55
+ * Calls the tool `name` with `args` as `caller`. A protocol error, such as arguments the tool's
56
+ * schema refuses or a forbidden call, answers its message as a failure.
57
+ */
58
+ export async function callTool(
59
+ name: string,
60
+ args: Record<string, unknown>,
61
+ caller: Caller = "guest",
62
+ ): Promise<ToolCall> {
63
+ let router = caller === "member" ? createMemberRouter() : createWebRouter();
64
+ let response = await router.fetch(
65
+ new Request(new URL(routes.mcp.href(), "https://example.com"), {
66
+ method: "POST",
67
+ headers: {
68
+ "Content-Type": "application/json",
69
+ "MCP-Protocol-Version": LATEST_PROTOCOL_VERSION,
70
+ "Mcp-Method": "tools/call",
71
+ "Mcp-Name": name,
72
+ },
73
+ body: JSON.stringify({
74
+ jsonrpc: "2.0",
75
+ id: 1,
76
+ method: "tools/call",
77
+ params: {
78
+ name,
79
+ arguments: args,
80
+ _meta: {
81
+ [MetaKey.ProtocolVersion]: LATEST_PROTOCOL_VERSION,
82
+ [MetaKey.ClientInfo]: { name: "test", version: "1.0.0" },
83
+ [MetaKey.ClientCapabilities]: {},
84
+ },
85
+ },
86
+ }),
87
+ }),
88
+ );
89
+ return readCall((await response.json()) as CallResponse);
90
+ }
91
+
92
+ /** What a `tools/call` response says, with a protocol error read as the call's failure. */
93
+ function readCall(body: CallResponse): ToolCall {
94
+ if (body.error !== undefined) return { text: body.error.message ?? "", isError: true };
95
+ return { text: body.result?.content?.[0]?.text ?? "", isError: body.result?.isError === true };
96
+ }
@@ -1,8 +1,7 @@
1
1
  /**
2
2
  * The HTML document every page renders inside: the head tags, the page's title, description,
3
- * canonical link and link-preview tags, and the
4
- * stylesheets imported below in cascade order. The client entry is linked only by a page
5
- * that carries an island.
3
+ * canonical link and link-preview tags, and the stylesheets imported below in cascade order.
4
+ * The client entry is linked only by a page that carries an island.
6
5
  */
7
6
 
8
7
  import type { DocumentAssets } from "@sdxc/assets-middleware";