create-ailk 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/lib/env-catalog.js +5 -9
  2. package/dist/spoke-checkout.d.ts +27 -2
  3. package/dist/spoke-checkout.js +207 -4
  4. package/dist/topology.d.ts +8 -0
  5. package/dist/topology.js +29 -5
  6. package/package.json +3 -3
  7. package/templates/apps/mcp/CLAUDE.md +51 -5
  8. package/templates/apps/mcp/__tests__/app-entry.test.ts +325 -0
  9. package/templates/apps/mcp/__tests__/boot.test.ts +203 -0
  10. package/templates/apps/mcp/__tests__/index.test.ts +86 -47
  11. package/templates/apps/mcp/__tests__/lib/content-adapter.test.ts +5 -6
  12. package/templates/apps/mcp/__tests__/lib/content-root.test.ts +93 -0
  13. package/templates/apps/mcp/__tests__/server.test.ts +63 -6
  14. package/templates/apps/mcp/src/app.ts +32 -0
  15. package/templates/apps/mcp/src/boot.ts +185 -0
  16. package/templates/apps/mcp/src/http-transport.ts +39 -15
  17. package/templates/apps/mcp/src/index.ts +17 -126
  18. package/templates/apps/mcp/src/lib/audit-single-page.ts +7 -6
  19. package/templates/apps/mcp/src/lib/content-adapter.ts +34 -5
  20. package/templates/apps/mcp/src/lib/topology.generated.ts +3 -0
  21. package/templates/apps/mcp/src/server.ts +10 -2
  22. package/templates/apps/mcp/src/serverless-app.ts +88 -0
  23. package/templates/apps/mcp/src/tools/get_business_hours.ts +6 -5
  24. package/templates/apps/mcp/src/tools/get_faq.ts +6 -5
  25. package/templates/apps/mcp/src/tools/get_locations.ts +6 -5
  26. package/templates/apps/mcp/src/tools/get_offerings.ts +6 -5
  27. package/templates/apps/mcp/src/tools/get_pricing.ts +6 -5
  28. package/templates/apps/mcp/src/tools/get_site_info.ts +6 -5
  29. package/templates/apps/mcp/src/tools/list_pages.ts +8 -7
  30. package/templates/apps/mcp/src/tools/read_content.ts +7 -7
  31. package/templates/apps/mcp/src/tools/search_content.ts +6 -5
  32. package/templates/apps/mcp/tsconfig.json +2 -0
  33. package/templates/apps/web/app/.well-known/mcp.json/build-manifest.ts +16 -4
  34. package/templates/apps/web/app/.well-known/mcp.json/route.ts +3 -0
  35. package/templates/apps/web/app/[locale]/(authed)/account/actions.ts +18 -4
  36. package/templates/apps/web/app/openapi.json/__tests__/route.test.ts +46 -28
  37. package/templates/apps/web/lib/__tests__/relay.test.ts +13 -7
  38. package/templates/apps/web/lib/__tests__/server-api.test.ts +37 -28
  39. package/templates/apps/web/lib/__tests__/site-brand.test.ts +42 -0
  40. package/templates/apps/web/lib/site-brand.tsx +22 -6
  41. package/templates/apps/web/lib/topology.generated.ts +3 -0
  42. package/versions.json +1 -1
@@ -1,10 +1,16 @@
1
1
  /**
2
2
  * Structural ordering guard for apps/mcp's bootstrap (#5876 spec D4, AC-3;
3
- * #7156 AC-1, AC-2).
3
+ * #7156 AC-1, AC-2; #8070 D2).
4
4
  *
5
- * `apps/mcp/src/index.ts` has real side effects at import time (starts a
6
- * transport, opens a stdio/HTTP listener) — it cannot safely be imported by
7
- * a test. This reads its source text instead, mirroring the existing
5
+ * The boot sequence moved from `src/index.ts` into `bootMcp()` in
6
+ * `src/boot.ts` (#8070), so both entrypoints — `index.ts` (stdio, or HTTP on
7
+ * a port) and `app.ts` (Vercel) — run the same one. The ordering assertions
8
+ * below read `boot.ts`, retargeted from `index.ts`: "before the transport
9
+ * branch" is now "inside `bootMcp()`", and one check on `index.ts` pins that
10
+ * `bootMcp()` itself runs before the transport branch.
11
+ *
12
+ * `index.ts` and `app.ts` await at module level, which ts-jest's CommonJS
13
+ * compile cannot load, so these read source text — the existing
8
14
  * "architectural guard" pattern (`__tests__/read_content.test.ts`).
9
15
  */
10
16
  import { readFileSync } from "node:fs";
@@ -13,26 +19,46 @@ import vm from "node:vm";
13
19
 
14
20
  import * as ts from "typescript";
15
21
 
16
- describe("apps/mcp/src/index.ts — bootstrap ordering", () => {
17
- const src = readFileSync(resolve(__dirname, "../src/index.ts"), "utf-8");
22
+ const indexSrc = readFileSync(resolve(__dirname, "../src/index.ts"), "utf-8");
23
+ const bootSrc = readFileSync(resolve(__dirname, "../src/boot.ts"), "utf-8");
18
24
 
19
- it("awaits initPublicWorkspace()", () => {
20
- expect(src).toMatch(/await initPublicWorkspace\(\)/);
21
- });
25
+ /** The text of `bootMcp()` — from its declaration to its closing brace. */
26
+ function bootBody(): string {
27
+ const start = bootSrc.indexOf("export async function bootMcp(");
28
+ expect(start).toBeGreaterThan(-1);
29
+ const end = bootSrc.indexOf("\n}\n", start);
30
+ expect(end).toBeGreaterThan(start);
31
+ return bootSrc.slice(start, end + 2);
32
+ }
22
33
 
23
- it("awaits initPublicWorkspace() before either transport branch", () => {
24
- const initIdx = src.indexOf("await initPublicWorkspace()");
25
- const transportBranchIdx = src.indexOf('if (transport === "http")');
34
+ describe("apps/mcp/src/index.ts — the shared boot runs before the transport (#8070 D2)", () => {
35
+ it("awaits bootMcp() exactly once, before either transport branch", () => {
36
+ const calls = [...indexSrc.matchAll(/^await bootMcp\(\);$/gm)];
37
+ const transportBranchIdx = indexSrc.indexOf('if (transport === "http")');
26
38
 
27
- expect(initIdx).toBeGreaterThan(-1);
39
+ expect(calls).toHaveLength(1);
28
40
  expect(transportBranchIdx).toBeGreaterThan(-1);
29
- expect(initIdx).toBeLessThan(transportBranchIdx);
41
+ expect(calls[0]!.index!).toBeLessThan(transportBranchIdx);
42
+ });
43
+
44
+ it("the HTTP branch keeps today's stateful default (readStatelessEnv(false))", () => {
45
+ const transportBranchIdx = indexSrc.indexOf('if (transport === "http")');
46
+ const readIdx = indexSrc.indexOf("readStatelessEnv(false)");
47
+
48
+ expect(readIdx).toBeGreaterThan(transportBranchIdx);
49
+ });
50
+ });
51
+
52
+ describe("apps/mcp/src/boot.ts — bootstrap ordering", () => {
53
+ it("awaits initPublicWorkspace()", () => {
54
+ expect(bootBody()).toMatch(/await initPublicWorkspace\(\)/);
30
55
  });
31
56
 
32
57
  it("wraps the await in try/catch — a rejection (DB down at boot) must not crash the whole server (code review, #5876)", () => {
33
- const tryIdx = src.indexOf("try {");
34
- const initIdx = src.indexOf("await initPublicWorkspace()");
35
- const catchIdx = src.indexOf("} catch");
58
+ const body = bootBody();
59
+ const tryIdx = body.indexOf("try {");
60
+ const initIdx = body.indexOf("await initPublicWorkspace()");
61
+ const catchIdx = body.indexOf("} catch");
36
62
 
37
63
  expect(tryIdx).toBeGreaterThan(-1);
38
64
  expect(catchIdx).toBeGreaterThan(-1);
@@ -40,54 +66,65 @@ describe("apps/mcp/src/index.ts — bootstrap ordering", () => {
40
66
  expect(tryIdx).toBeLessThan(initIdx);
41
67
  expect(initIdx).toBeLessThan(catchIdx);
42
68
  });
43
- });
44
69
 
45
- describe("apps/mcp/src/index.ts — the claim refresh loop starts in production (#7156 AC-1)", () => {
46
- const src = readFileSync(resolve(__dirname, "../src/index.ts"), "utf-8");
70
+ it("runs the five boot steps in today's order", () => {
71
+ const body = bootBody();
72
+ const steps = [
73
+ "await initPublicWorkspace()",
74
+ "await registerLicenseKeyStore()",
75
+ "await initMcpCommerceClaim()",
76
+ "startMcpClaimRefresh();",
77
+ "reportUnlicensedProTools();",
78
+ ].map((step) => body.indexOf(step));
79
+
80
+ for (const idx of steps) expect(idx).toBeGreaterThan(-1);
81
+ expect([...steps].sort((a, b) => a - b)).toEqual(steps);
82
+ });
83
+ });
47
84
 
48
- it("starts after the boot read and before the transport branch", () => {
49
- const initIdx = src.indexOf("await initMcpCommerceClaim()");
50
- const callMatches = [...src.matchAll(/^startMcpClaimRefresh\(\);$/gm)];
51
- const transportBranchIdx = src.indexOf('if (transport === "http")');
85
+ describe("apps/mcp/src/boot.ts — the claim refresh loop starts in production (#7156 AC-1)", () => {
86
+ it("starts after the boot read and before bootMcp() returns", () => {
87
+ const body = bootBody();
88
+ const initIdx = body.indexOf("await initMcpCommerceClaim()");
89
+ const callMatches = [...body.matchAll(/^\s*startMcpClaimRefresh\(\);$/gm)];
52
90
 
53
91
  expect(initIdx).toBeGreaterThan(-1);
54
92
  expect(callMatches).toHaveLength(1);
55
- expect(transportBranchIdx).toBeGreaterThan(-1);
56
93
 
57
94
  const callIdx = callMatches[0]!.index!;
58
95
  expect(initIdx).toBeLessThan(callIdx);
59
- expect(callIdx).toBeLessThan(transportBranchIdx);
60
96
  });
61
97
  });
62
98
 
63
- describe("apps/mcp/src/index.ts — the boot warning cannot stop the server (#7156 AC-2, D2)", () => {
64
- const src = readFileSync(resolve(__dirname, "../src/index.ts"), "utf-8");
65
-
99
+ describe("apps/mcp/src/boot.ts — the boot warning cannot stop the server (#7156 AC-2, D2)", () => {
66
100
  /**
67
101
  * The exact behavioural slice AC-2 specifies: from the last `try {` before
68
- * the `reportUnlicensedProTools();` call statement, up to `const transport
69
- * =`. Transpiled and run in a fresh vm context so a real throw from the
70
- * stubbed function proves the guard, not a mock of the guard itself.
102
+ * the `reportUnlicensedProTools();` call statement, up to the end of
103
+ * `bootMcp()`. Transpiled and run in a fresh vm context so a real throw
104
+ * from the stubbed function proves the guard, not a mock of the guard
105
+ * itself.
71
106
  */
72
107
  function guardedSlice(): string {
108
+ const body = bootBody();
73
109
  const callMatches = [
74
- ...src.matchAll(/^\s*reportUnlicensedProTools\(\);$/gm),
110
+ ...body.matchAll(/^\s*reportUnlicensedProTools\(\);$/gm),
75
111
  ];
76
112
  expect(callMatches).toHaveLength(1);
77
113
  const callIdx = callMatches[0]!.index!;
78
- const tryIdx = src.lastIndexOf("try {", callIdx);
79
- const transportIdx = src.indexOf("const transport =");
114
+ const tryIdx = body.lastIndexOf("try {", callIdx);
115
+ // The closing brace of bootMcp() — the last character of `body`.
116
+ const endIdx = body.lastIndexOf("}");
80
117
 
81
118
  expect(tryIdx).toBeGreaterThan(-1);
82
- expect(transportIdx).toBeGreaterThan(callIdx);
119
+ expect(endIdx).toBeGreaterThan(callIdx);
83
120
 
84
- const slice = src.slice(tryIdx, transportIdx);
121
+ const slice = body.slice(tryIdx, endIdx);
85
122
  // The extracted try block must be the one that immediately wraps the
86
123
  // call, not an earlier try{}/await pair (code review, #7156): the two
87
- // other try blocks in this file each await a boot call, so a regressed
88
- // boundary would carry "await" into the slice. Asserting that here
89
- // turns a boundary regression into a clear failure instead of an opaque
90
- // vm ReferenceError from the un-injected awaited function.
124
+ // other try blocks each await a boot call, so a regressed boundary would
125
+ // carry "await" into the slice. Asserting that here turns a boundary
126
+ // regression into a clear failure instead of an opaque vm ReferenceError
127
+ // from the un-injected awaited function.
91
128
  expect(slice).not.toContain("await");
92
129
 
93
130
  return slice;
@@ -137,14 +174,16 @@ describe("apps/mcp/src/index.ts — the boot warning cannot stop the server (#71
137
174
  expect(errorSpy).not.toHaveBeenCalled();
138
175
  });
139
176
 
140
- it("the call statement occurs exactly once, before the transport branch", () => {
141
- const callMatches = [
142
- ...src.matchAll(/^\s*reportUnlicensedProTools\(\);$/gm),
177
+ it("the call statement occurs exactly once, inside bootMcp()", () => {
178
+ const fileMatches = [
179
+ ...bootSrc.matchAll(/^\s*reportUnlicensedProTools\(\);$/gm),
180
+ ];
181
+ const bodyMatches = [
182
+ ...bootBody().matchAll(/^\s*reportUnlicensedProTools\(\);$/gm),
143
183
  ];
144
- const transportBranchIdx = src.indexOf('if (transport === "http")');
145
184
 
146
- expect(callMatches).toHaveLength(1);
147
- expect(callMatches[0]!.index!).toBeLessThan(transportBranchIdx);
185
+ expect(fileMatches).toHaveLength(1);
186
+ expect(bodyMatches).toHaveLength(1);
148
187
  });
149
188
 
150
189
  it("logs to stderr only — the guarded slice never writes stdout", () => {
@@ -10,7 +10,8 @@
10
10
  * adapter itself;
11
11
  * - it forwards the caller's `contentRoot` test-override verbatim;
12
12
  * - it forwards the caller's resolved `locale` as `defaultLocale`;
13
- * - it defaults `contentRoot` to `<cwd>/content` when the caller passes none;
13
+ * - it defaults `contentRoot` to `mcpContentRoot()` when the caller passes
14
+ * none (#8070 D3; the resolver's order is pinned in `content-root.test.ts`);
14
15
  * - its MDX-narrowed twin `getMcpMdxContentAdapter()` (which `read_content`
15
16
  * needs for `getPageSource()`) resolves the same way and raises a named
16
17
  * error rather than a TypeError when the selected adapter is not MDX;
@@ -21,8 +22,6 @@
21
22
  * ALL and returns the fail-closed empty adapter instead.
22
23
  */
23
24
 
24
- import { join } from "node:path";
25
-
26
25
  const mockResolveContentAdapter = jest.fn();
27
26
 
28
27
  jest.mock("@working-theory/content-adapters", () => ({
@@ -36,6 +35,7 @@ import type { ArtifactPrismaClient } from "@working-theory/content-adapters";
36
35
  import {
37
36
  getMcpContentAdapter,
38
37
  getMcpMdxContentAdapter,
38
+ mcpContentRoot,
39
39
  } from "../../src/lib/content-adapter.js";
40
40
  import {
41
41
  __setMcpPublicWorkspaceForTest,
@@ -72,15 +72,14 @@ describe("getMcpContentAdapter", () => {
72
72
  });
73
73
  });
74
74
 
75
- it("defaults contentRoot to <cwd>/content when none is given", () => {
75
+ it("defaults contentRoot to mcpContentRoot() when none is given (#8070 D3)", () => {
76
76
  getMcpContentAdapter();
77
77
 
78
78
  expect(mockResolveContentAdapter).toHaveBeenCalledWith({
79
- contentRoot: join(process.cwd(), "content"),
79
+ contentRoot: mcpContentRoot(),
80
80
  defaultLocale: undefined,
81
81
  });
82
82
  });
83
-
84
83
  it("passes no workspaceId on CONTENT_ADAPTER=mdx — the MDX path stays byte-identical", () => {
85
84
  getMcpContentAdapter({ contentRoot: "/fixtures/content", locale: "en-US" });
86
85
 
@@ -0,0 +1,93 @@
1
+ /**
2
+ * `mcpContentRoot()` — the one content-root resolver (#8070 D3, AC-6).
3
+ *
4
+ * The order, against temp directories:
5
+ * 1. AILK_CONTENT_ROOT when set and non-empty (absolute, or resolved
6
+ * against the working directory);
7
+ * 2. <cwd>/content when it exists (the server started from the repo root);
8
+ * 3. <cwd>/../../content when it exists (the server started from apps/mcp,
9
+ * a Vercel project whose root directory is apps/mcp);
10
+ * 4. else <cwd>/content — today's value, so a missing root keeps today's
11
+ * empty result.
12
+ *
13
+ * The working directory is stubbed through `process.cwd`, never changed.
14
+ */
15
+
16
+ import { mkdirSync, mkdtempSync, realpathSync, rmSync } from "node:fs";
17
+ import { tmpdir } from "node:os";
18
+ import { join } from "node:path";
19
+
20
+ import { mcpContentRoot } from "../../src/lib/content-adapter.js";
21
+
22
+ let base: string;
23
+ let savedRoot: string | undefined;
24
+
25
+ beforeEach(() => {
26
+ base = realpathSync(mkdtempSync(join(tmpdir(), "mcp-content-root-")));
27
+ savedRoot = process.env["AILK_CONTENT_ROOT"];
28
+ delete process.env["AILK_CONTENT_ROOT"];
29
+ });
30
+
31
+ afterEach(() => {
32
+ jest.restoreAllMocks();
33
+ if (savedRoot === undefined) delete process.env["AILK_CONTENT_ROOT"];
34
+ else process.env["AILK_CONTENT_ROOT"] = savedRoot;
35
+ rmSync(base, { recursive: true, force: true });
36
+ });
37
+
38
+ /** Make `dir` (under the temp base) the working directory the resolver sees. */
39
+ function cwdIs(dir: string): string {
40
+ const abs = join(base, dir);
41
+ mkdirSync(abs, { recursive: true });
42
+ jest.spyOn(process, "cwd").mockReturnValue(abs);
43
+ return abs;
44
+ }
45
+
46
+ describe("mcpContentRoot", () => {
47
+ it("AILK_CONTENT_ROOT wins when set — even over an existing <cwd>/content", () => {
48
+ const cwd = cwdIs("repo");
49
+ mkdirSync(join(cwd, "content"));
50
+ const override = join(base, "elsewhere", "content");
51
+ process.env["AILK_CONTENT_ROOT"] = override;
52
+
53
+ expect(mcpContentRoot()).toBe(override);
54
+ });
55
+
56
+ it("a relative AILK_CONTENT_ROOT resolves against the working directory", () => {
57
+ const cwd = cwdIs("repo/apps/mcp");
58
+ process.env["AILK_CONTENT_ROOT"] = "../../content";
59
+
60
+ expect(mcpContentRoot()).toBe(join(cwd, "..", "..", "content"));
61
+ expect(mcpContentRoot()).toBe(join(base, "repo", "content"));
62
+ });
63
+
64
+ it("an empty AILK_CONTENT_ROOT is ignored", () => {
65
+ const cwd = cwdIs("repo");
66
+ mkdirSync(join(cwd, "content"));
67
+ process.env["AILK_CONTENT_ROOT"] = " ";
68
+
69
+ expect(mcpContentRoot()).toBe(join(cwd, "content"));
70
+ });
71
+
72
+ it("else <cwd>/content when it exists", () => {
73
+ const cwd = cwdIs("repo");
74
+ mkdirSync(join(cwd, "content"));
75
+ // A repo-level content two levels up must not win over the local one.
76
+ mkdirSync(join(base, "content"));
77
+
78
+ expect(mcpContentRoot()).toBe(join(cwd, "content"));
79
+ });
80
+
81
+ it("else <cwd>/../../content when it exists", () => {
82
+ cwdIs("repo/apps/mcp");
83
+ mkdirSync(join(base, "repo", "content"));
84
+
85
+ expect(mcpContentRoot()).toBe(join(base, "repo", "content"));
86
+ });
87
+
88
+ it("else <cwd>/content — today's value, when neither exists", () => {
89
+ const cwd = cwdIs("repo/apps/mcp");
90
+
91
+ expect(mcpContentRoot()).toBe(join(cwd, "content"));
92
+ });
93
+ });
@@ -37,6 +37,23 @@ import {
37
37
  reportUnlicensedProTools,
38
38
  } from "../src/server.js";
39
39
 
40
+ // The topology seam's UNSERVED_MCP_TOOLS (#8070 D7), made switchable so one
41
+ // suite can stand in for a hub ([] — the committed seam, and every other
42
+ // case in this file) and a spoke (["create_project"]).
43
+ const mockSeam: { unserved: readonly string[] } = { unserved: [] };
44
+ // eslint-disable-next-line no-restricted-syntax -- the generated topology seam IS the boundary under test (spec 8070 AC-8b mocks its list); every other export passes through from the real module
45
+ jest.mock("../src/lib/topology.generated.js", () => {
46
+ const actual = jest.requireActual("../src/lib/topology.generated.js");
47
+ // A getter defined, not spread: the factory runs before `mockSeam` is
48
+ // initialised, so the list must be read at use, never at mock time.
49
+ const mocked = { ...actual };
50
+ Object.defineProperty(mocked, "UNSERVED_MCP_TOOLS", {
51
+ enumerable: true,
52
+ get: () => mockSeam.unserved,
53
+ });
54
+ return mocked;
55
+ });
56
+
40
57
  describe("createMcpServer", () => {
41
58
  it("creates an McpServer without throwing", () => {
42
59
  expect(() => createMcpServer()).not.toThrow();
@@ -180,6 +197,40 @@ describe("start_purchase registration — gated on the commerce claim (#5971)",
180
197
  });
181
198
  });
182
199
 
200
+ describe("create_project on a spoke — the seam's UNSERVED_MCP_TOOLS (#8070 D7, AC-8b)", () => {
201
+ afterEach(() => {
202
+ mockSeam.unserved = [];
203
+ });
204
+
205
+ it("a spoke's list (['create_project']) keeps it out of registration", () => {
206
+ mockSeam.unserved = ["create_project"];
207
+
208
+ expect(listRegisteredTools().map((t) => t.name)).not.toContain(
209
+ "create_project",
210
+ );
211
+ const server = createMcpServer();
212
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- the SDK exposes no public tool listing; same cast as the suites above
213
+ const tools = (server as any)._registeredTools as Record<string, unknown>;
214
+ expect("create_project" in tools).toBe(false);
215
+ });
216
+
217
+ it("a hub's list ([]) registers it", () => {
218
+ mockSeam.unserved = [];
219
+
220
+ expect(listRegisteredTools().map((t) => t.name)).toContain(
221
+ "create_project",
222
+ );
223
+ });
224
+
225
+ it("withholding it changes nothing else", () => {
226
+ const hub = listRegisteredTools().map((t) => t.name);
227
+ mockSeam.unserved = ["create_project"];
228
+ const spoke = listRegisteredTools().map((t) => t.name);
229
+
230
+ expect(spoke).toEqual(hub.filter((name) => name !== "create_project"));
231
+ });
232
+ });
233
+
183
234
  describe("the five licence-feature tools — one-release warning cycle (#7136)", () => {
184
235
  const FLOW_PAIR = ["get_flow", "submit_flow_step"];
185
236
  const BOOKING_TRIO = [
@@ -311,15 +362,21 @@ describe("the five licence-feature tools — one-release warning cycle (#7136)",
311
362
  expect(consoleWarn).not.toHaveBeenCalled();
312
363
  });
313
364
 
314
- it("index.ts reports after the claim resolves and before either transport starts", () => {
315
- const index = readFileSync(join(__dirname, "../src/index.ts"), "utf8");
316
- const init = index.indexOf("await initMcpCommerceClaim()");
317
- const report = index.indexOf("reportUnlicensedProTools(");
318
- const transport = index.indexOf('if (transport === "http")');
365
+ it("the boot reports after the claim resolves, and index.ts boots before either transport starts", () => {
366
+ // The boot sequence lives in boot.ts's bootMcp() since #8070 D2.
367
+ const boot = readFileSync(join(__dirname, "../src/boot.ts"), "utf8");
368
+ const init = boot.indexOf("await initMcpCommerceClaim()");
369
+ const report = boot.indexOf("reportUnlicensedProTools(");
319
370
 
320
371
  expect(init).toBeGreaterThan(-1);
321
372
  expect(report).toBeGreaterThan(init);
322
- expect(transport).toBeGreaterThan(report);
373
+
374
+ const index = readFileSync(join(__dirname, "../src/index.ts"), "utf8");
375
+ const bootCall = index.indexOf("await bootMcp()");
376
+ const transport = index.indexOf('if (transport === "http")');
377
+
378
+ expect(bootCall).toBeGreaterThan(-1);
379
+ expect(transport).toBeGreaterThan(bootCall);
323
380
  });
324
381
 
325
382
  it("server.ts never writes to stdout — the stdio transport's JSON-RPC channel", () => {
@@ -0,0 +1,32 @@
1
+ /**
2
+ * @working-theory/mcp — the Vercel entry (#8070 D2).
3
+ *
4
+ * A Vercel project whose root directory is `apps/mcp` detects this file
5
+ * (`src/app` precedes `src/index` in its Node-backend search, and the chosen
6
+ * file must import the framework), builds it, and calls the default export —
7
+ * the `serverlessHandler(app)` request function, which Vercel's Node runtime
8
+ * accepts where a bare Fastify instance is not a shape it runs.
9
+ * It never listens; the module-level `await` runs once per instance, so a
10
+ * warm instance reuses the booted app.
11
+ *
12
+ * Run locally, use `src/index.ts` (stdio, or HTTP on MCP_HTTP_PORT) instead.
13
+ * Everything testable lives in `serverless-app.ts`.
14
+ */
15
+
16
+ import Fastify from "fastify";
17
+
18
+ import { bootMcp } from "./boot.js";
19
+ import {
20
+ configureServerlessApp,
21
+ SERVERLESS_FASTIFY_OPTIONS,
22
+ serverlessHandler,
23
+ } from "./serverless-app.js";
24
+
25
+ /** Read statically by Vercel's Node builder; caps one request (S8070-03). */
26
+ export const config = { maxDuration: 30 };
27
+
28
+ await bootMcp();
29
+ const app = Fastify(SERVERLESS_FASTIFY_OPTIONS);
30
+ await configureServerlessApp(app);
31
+ await app.ready();
32
+ export default serverlessHandler(app);
@@ -0,0 +1,185 @@
1
+ /**
2
+ * The boot sequence and the HTTP env→config reader both entrypoints share
3
+ * (#8070 D1, D2).
4
+ *
5
+ * `src/index.ts` (stdio, or HTTP on `MCP_HTTP_PORT`) and `src/app.ts` (the
6
+ * Vercel entry) each call {@link bootMcp} before they build a transport, and
7
+ * read the HTTP configuration through {@link httpTransportConfigFromEnv} and
8
+ * {@link readStatelessEnv}. One copy of each, so the two entries cannot drift.
9
+ *
10
+ * Nothing here loads Fastify: the HTTP transport's config type is imported as
11
+ * a type only, so the stdio entry still never loads the HTTP stack.
12
+ */
13
+
14
+ import {
15
+ DEFAULT_CAPTURE_LEAD_DAILY_CAP,
16
+ DEFAULT_START_PURCHASE_DAILY_CAP,
17
+ readPositiveIntEnv,
18
+ } from "./abuse/index.js";
19
+ import type { HttpTransportConfig } from "./http-transport.js";
20
+ import {
21
+ initMcpCommerceClaim,
22
+ startMcpClaimRefresh,
23
+ } from "./lib/commerce-claim.js";
24
+ import {
25
+ initPublicWorkspace,
26
+ registerLicenseKeyStore,
27
+ } from "./lib/topology.generated.js";
28
+
29
+ /**
30
+ * Runs the boot sequence, in order: the workspace resolution, the licence-key
31
+ * store, the commerce claim, the claim re-read loop and the one-release
32
+ * licence warning. Each step that can fail is guarded so one failure never
33
+ * takes the other tools down.
34
+ */
35
+ export async function bootMcp(): Promise<void> {
36
+ // Resolves the MCP server's own workspace ONCE, before any transport is
37
+ // built — a no-op unless CONTENT_ADAPTER=database (#5876 spec D4/D6).
38
+ // This is the one `await` that covers every transport:
39
+ // `getMcpContentAdapter()` (content-adapter.ts) stays synchronous and reads
40
+ // the memoised result.
41
+ //
42
+ // A REJECTION here (a transient DB error — unreachable at boot, a migration
43
+ // in progress, a bad DATABASE_URL) is caught rather than left to crash the
44
+ // process: every OTHER tool (lead capture, scheduling, …) has nothing to do
45
+ // with the content adapter and must keep serving. The module's un-resolved
46
+ // `{ kind: "not-required" }` state is left in place on a caught failure —
47
+ // the SAME fail-closed shape an ambiguous workspace count already produces
48
+ // (D5) — so content tools serve their empty/not-found shape rather than the
49
+ // whole server going dark over one adapter's connectivity.
50
+ try {
51
+ await initPublicWorkspace();
52
+ } catch (err) {
53
+ console.error(
54
+ "[mcp] initPublicWorkspace() failed — content tools will serve their " +
55
+ "fail-closed empty shape under CONTENT_ADAPTER=database until this " +
56
+ "resolves; every other tool is unaffected:",
57
+ err,
58
+ );
59
+ }
60
+
61
+ // Registers the renewed licence key's durable home (#6677 DD-6) BEFORE the
62
+ // commerce claim below memoises the licence: with a database, the key a
63
+ // sibling app renewed lives in one SiteSetting row, and the claim must read
64
+ // it. Never throws; without DATABASE_URL the file store stays in place.
65
+ await registerLicenseKeyStore();
66
+
67
+ // Resolves the deployment's `commerce` add-on claim at boot, before any
68
+ // transport is built — the sibling of the workspace resolution above and
69
+ // the same #5876 idiom (#5971 spec D2). Without this await the memoised
70
+ // claim is never resolved and `start_purchase` is invisible on a KEYED
71
+ // site too. The same single licence read now also resolves the licence
72
+ // features the deployment holds, which gate the five `feature`-tagged
73
+ // tools (#7136). The re-read loop below runs every `MCP_CLAIM_REFRESH_MS`
74
+ // thereafter (#7156), so the server's origin agrees with the manifest
75
+ // route's origin response within that bound; the route answers
76
+ // `cache-control: public, max-age=86400`, so a downstream cache may serve
77
+ // an older manifest for up to 24 hours.
78
+ //
79
+ // A REJECTION is caught for the same reason: a licence read that fails
80
+ // must not take the other 19 tools down. `initMcpCommerceClaim()` already
81
+ // resolves to the fail-closed "unclaimed" internally, so this catch is
82
+ // belt-and-braces for anything thrown outside its own try.
83
+ try {
84
+ await initMcpCommerceClaim();
85
+ } catch (err) {
86
+ console.error(
87
+ "[mcp] initMcpCommerceClaim() failed — start_purchase stays unregistered " +
88
+ "(fail-closed) until this resolves; every other tool is unaffected:",
89
+ err,
90
+ );
91
+ }
92
+
93
+ // Starts the bounded re-read (#7156 spec D1), after the boot read resolves
94
+ // so the first re-read never races it. Never throws; the timer is unref'd.
95
+ startMcpClaimRefresh();
96
+
97
+ // The one-release warning cycle (#7136): once per process, whichever
98
+ // transport follows, one stderr line per tool served without its licence
99
+ // feature. After the claim resolves, or it would warn for every tool.
100
+ //
101
+ // A throw here must not stop the server (#7156 spec D2, L1) — only the call
102
+ // is guarded, not the import: if `./server.js` fails to load, every
103
+ // transport loads it again and the server could not start anyway.
104
+ const { reportUnlicensedProTools } = await import("./server.js");
105
+ try {
106
+ reportUnlicensedProTools();
107
+ } catch (err) {
108
+ console.error(
109
+ "[mcp] reportUnlicensedProTools() failed — the licence boot warning was " +
110
+ "not written; every tool is served as registered:",
111
+ err,
112
+ );
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Whether the HTTP transport runs stateless, from `MCP_HTTP_STATELESS`
118
+ * (#8070 D1). Trimmed and case-insensitive: `true`/`1` → on, `false`/`0` →
119
+ * off, unset or empty → `defaultValue`. Anything else throws, so a typo fails
120
+ * the boot rather than silently picking a mode.
121
+ *
122
+ * Each entry passes its own default: `src/index.ts` passes `false` (today's
123
+ * stateful server, unchanged); the Vercel entry passes `true`, because a
124
+ * stateful transport keeps its sessions in one instance's memory and cannot
125
+ * work across the instances a serverless host runs.
126
+ */
127
+ export function readStatelessEnv(defaultValue: boolean): boolean {
128
+ // A literal read, so create-ailk's declared-env scan finds it (#7874).
129
+ const raw = process.env["MCP_HTTP_STATELESS"];
130
+ const value = (raw ?? "").trim().toLowerCase();
131
+ if (value === "") return defaultValue;
132
+ if (value === "true" || value === "1") return true;
133
+ if (value === "false" || value === "0") return false;
134
+ throw new Error(
135
+ `MCP_HTTP_STATELESS must be one of true, false, 1 or 0 (got "${raw}")`,
136
+ );
137
+ }
138
+
139
+ /**
140
+ * The HTTP transport's configuration, read from the environment as
141
+ * `src/index.ts` has always read it — with one change: the two per-minute
142
+ * rates go through {@link readPositiveIntEnv}, as the daily caps already do,
143
+ * so a blank or non-numeric value falls back to its default instead of
144
+ * yielding `NaN` and silently disabling the limit (#8070 S8070-06).
145
+ *
146
+ * Every variable is optional; the defaults are shown in
147
+ * `apps/mcp/.env.example`. Stateless mode is not read here: each entry reads
148
+ * it through {@link readStatelessEnv} with its own default.
149
+ */
150
+ export function httpTransportConfigFromEnv(): HttpTransportConfig & {
151
+ port: number;
152
+ } {
153
+ const port = parseInt(process.env["MCP_HTTP_PORT"] ?? "8080", 10);
154
+ const path = process.env["MCP_HTTP_PATH"] ?? "/mcp";
155
+ const readPerMin = readPositiveIntEnv("MCP_RATE_LIMIT_READ_PER_MIN", 60);
156
+ const writePerMin = readPositiveIntEnv("MCP_RATE_LIMIT_WRITE_PER_MIN", 10);
157
+ const writeOriginsRaw = process.env["MCP_CORS_WRITE_ALLOWED_ORIGINS"] ?? "";
158
+ const writeAllowedOrigins = writeOriginsRaw
159
+ ? writeOriginsRaw.split(",").map((o) => o.trim())
160
+ : [];
161
+ // Both caps go through readPositiveIntEnv rather than a bare parseInt: a
162
+ // BLANK env var would otherwise yield NaN and silently disable the cap
163
+ // (#5971 security review round 2).
164
+ const captureLeadDailyCapPerIp = readPositiveIntEnv(
165
+ "MCP_ABUSE_CAPTURE_LEAD_DAILY_CAP",
166
+ DEFAULT_CAPTURE_LEAD_DAILY_CAP,
167
+ );
168
+ const startPurchaseDailyCapPerIp = readPositiveIntEnv(
169
+ "MCP_ABUSE_START_PURCHASE_DAILY_CAP",
170
+ DEFAULT_START_PURCHASE_DAILY_CAP,
171
+ );
172
+ const blockedUserAgents = process.env["MCP_ABUSE_BLOCKED_USER_AGENTS"] ?? "";
173
+
174
+ return {
175
+ port,
176
+ path,
177
+ rateLimits: { readPerMin, writePerMin },
178
+ cors: { writeAllowedOrigins },
179
+ abuse: {
180
+ captureLeadDailyCapPerIp,
181
+ startPurchaseDailyCapPerIp,
182
+ blockedUserAgents,
183
+ },
184
+ };
185
+ }