create-ailk 0.17.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 (36) hide show
  1. package/dist/lib/env-catalog.js +5 -9
  2. package/dist/topology.d.ts +8 -0
  3. package/dist/topology.js +24 -2
  4. package/package.json +1 -1
  5. package/templates/apps/mcp/CLAUDE.md +51 -5
  6. package/templates/apps/mcp/__tests__/app-entry.test.ts +325 -0
  7. package/templates/apps/mcp/__tests__/boot.test.ts +203 -0
  8. package/templates/apps/mcp/__tests__/index.test.ts +86 -47
  9. package/templates/apps/mcp/__tests__/lib/content-adapter.test.ts +5 -6
  10. package/templates/apps/mcp/__tests__/lib/content-root.test.ts +93 -0
  11. package/templates/apps/mcp/__tests__/server.test.ts +63 -6
  12. package/templates/apps/mcp/src/app.ts +32 -0
  13. package/templates/apps/mcp/src/boot.ts +185 -0
  14. package/templates/apps/mcp/src/http-transport.ts +39 -15
  15. package/templates/apps/mcp/src/index.ts +17 -126
  16. package/templates/apps/mcp/src/lib/audit-single-page.ts +7 -6
  17. package/templates/apps/mcp/src/lib/content-adapter.ts +34 -5
  18. package/templates/apps/mcp/src/lib/topology.generated.ts +3 -0
  19. package/templates/apps/mcp/src/server.ts +10 -2
  20. package/templates/apps/mcp/src/serverless-app.ts +88 -0
  21. package/templates/apps/mcp/src/tools/get_business_hours.ts +6 -5
  22. package/templates/apps/mcp/src/tools/get_faq.ts +6 -5
  23. package/templates/apps/mcp/src/tools/get_locations.ts +6 -5
  24. package/templates/apps/mcp/src/tools/get_offerings.ts +6 -5
  25. package/templates/apps/mcp/src/tools/get_pricing.ts +6 -5
  26. package/templates/apps/mcp/src/tools/get_site_info.ts +6 -5
  27. package/templates/apps/mcp/src/tools/list_pages.ts +8 -7
  28. package/templates/apps/mcp/src/tools/read_content.ts +7 -7
  29. package/templates/apps/mcp/src/tools/search_content.ts +6 -5
  30. package/templates/apps/mcp/tsconfig.json +2 -0
  31. package/templates/apps/web/app/.well-known/mcp.json/build-manifest.ts +16 -4
  32. package/templates/apps/web/app/.well-known/mcp.json/route.ts +3 -0
  33. package/templates/apps/web/app/[locale]/(authed)/account/actions.ts +18 -4
  34. package/templates/apps/web/lib/__tests__/site-brand.test.ts +42 -0
  35. package/templates/apps/web/lib/site-brand.tsx +22 -6
  36. package/templates/apps/web/lib/topology.generated.ts +3 -0
@@ -0,0 +1,203 @@
1
+ /**
2
+ * The shared boot module (#8070 D1, D2): `readStatelessEnv` and
3
+ * `httpTransportConfigFromEnv`, which both entrypoints read the environment
4
+ * through.
5
+ *
6
+ * Acceptance criteria verified here (spec docs/specs/8070-spoke-mcp-vercel-backend-spec.md):
7
+ * - AC-1: MCP_HTTP_STATELESS=true selects the stateless transport — a
8
+ * session-less tools/list answers 200 and lists list_pages.
9
+ * - AC-2: each entry's default, and the accepted spellings.
10
+ * - AC-3: a bad value throws naming the variable; a blank per-minute rate
11
+ * falls back to its default rather than disabling the limit.
12
+ *
13
+ * Real sockets on port 0, the pattern of `http-transport.test.ts`.
14
+ */
15
+
16
+ import type { AddressInfo } from "node:net";
17
+
18
+ import type { FastifyInstance } from "fastify";
19
+
20
+ import { httpTransportConfigFromEnv, readStatelessEnv } from "../src/boot.js";
21
+ import { buildHttpTransportApp } from "../src/http-transport.js";
22
+
23
+ const VARS = [
24
+ "MCP_HTTP_STATELESS",
25
+ "MCP_HTTP_PORT",
26
+ "MCP_HTTP_PATH",
27
+ "MCP_RATE_LIMIT_READ_PER_MIN",
28
+ "MCP_RATE_LIMIT_WRITE_PER_MIN",
29
+ "MCP_CORS_WRITE_ALLOWED_ORIGINS",
30
+ "MCP_ABUSE_CAPTURE_LEAD_DAILY_CAP",
31
+ "MCP_ABUSE_START_PURCHASE_DAILY_CAP",
32
+ "MCP_ABUSE_BLOCKED_USER_AGENTS",
33
+ ] as const;
34
+
35
+ const saved: Partial<Record<(typeof VARS)[number], string | undefined>> = {};
36
+
37
+ beforeEach(() => {
38
+ for (const name of VARS) {
39
+ saved[name] = process.env[name];
40
+ delete process.env[name];
41
+ }
42
+ });
43
+
44
+ afterEach(() => {
45
+ for (const name of VARS) {
46
+ const value = saved[name];
47
+ if (value === undefined) delete process.env[name];
48
+ else process.env[name] = value;
49
+ }
50
+ });
51
+
52
+ const TOOLS_LIST = { jsonrpc: "2.0", id: 1, method: "tools/list", params: {} };
53
+
54
+ async function listen(app: FastifyInstance): Promise<number> {
55
+ await app.listen({ host: "127.0.0.1", port: 0 });
56
+ return (app.server.address() as AddressInfo).port;
57
+ }
58
+
59
+ async function postToolsList(port: number): Promise<Response> {
60
+ return fetch(`http://127.0.0.1:${port}/mcp`, {
61
+ method: "POST",
62
+ body: JSON.stringify(TOOLS_LIST),
63
+ headers: {
64
+ "content-type": "application/json",
65
+ accept: "application/json, text/event-stream",
66
+ },
67
+ });
68
+ }
69
+
70
+ /** The app the long-running entry builds, from the environment as it stands. */
71
+ async function appFromEnv(defaultStateless: boolean): Promise<FastifyInstance> {
72
+ const { port: _port, ...config } = httpTransportConfigFromEnv();
73
+ return buildHttpTransportApp({
74
+ ...config,
75
+ stateless: readStatelessEnv(defaultStateless),
76
+ });
77
+ }
78
+
79
+ describe("AC-1 — MCP_HTTP_STATELESS=true selects the stateless transport", () => {
80
+ let app: FastifyInstance | undefined;
81
+
82
+ afterEach(async () => {
83
+ await app?.close();
84
+ app = undefined;
85
+ });
86
+
87
+ it("answers a tools/list with no Mcp-Session-Id with 200, listing list_pages", async () => {
88
+ process.env["MCP_HTTP_STATELESS"] = "true";
89
+ app = await appFromEnv(false);
90
+ const port = await listen(app);
91
+
92
+ const res = await postToolsList(port);
93
+
94
+ expect(res.status).toBe(200);
95
+ const body = (await res.json()) as {
96
+ result?: { tools?: Array<{ name: string }> };
97
+ };
98
+ const names = (body.result?.tools ?? []).map((tool) => tool.name);
99
+ expect(names).toContain("list_pages");
100
+ });
101
+ });
102
+
103
+ describe("AC-2 — each entry's default, and the accepted spellings", () => {
104
+ let app: FastifyInstance | undefined;
105
+
106
+ afterEach(async () => {
107
+ await app?.close();
108
+ app = undefined;
109
+ });
110
+
111
+ it("unset, the long-running default is false — and a session-less tools/list is 400 (today's stateful behaviour)", async () => {
112
+ expect(readStatelessEnv(false)).toBe(false);
113
+
114
+ app = await appFromEnv(false);
115
+ const port = await listen(app);
116
+
117
+ const res = await postToolsList(port);
118
+ expect(res.status).toBe(400);
119
+ });
120
+
121
+ it("unset, the serverless default is true", () => {
122
+ expect(readStatelessEnv(true)).toBe(true);
123
+ });
124
+
125
+ it("an empty value takes the default", () => {
126
+ process.env["MCP_HTTP_STATELESS"] = "";
127
+ expect(readStatelessEnv(true)).toBe(true);
128
+ expect(readStatelessEnv(false)).toBe(false);
129
+ });
130
+
131
+ it.each(["false", "0", "FALSE"])("%s reads as false", (value) => {
132
+ process.env["MCP_HTTP_STATELESS"] = value;
133
+ expect(readStatelessEnv(true)).toBe(false);
134
+ });
135
+
136
+ it.each(["1", "True"])("%s reads as true", (value) => {
137
+ process.env["MCP_HTTP_STATELESS"] = value;
138
+ expect(readStatelessEnv(false)).toBe(true);
139
+ });
140
+
141
+ it("surrounding whitespace is trimmed", () => {
142
+ process.env["MCP_HTTP_STATELESS"] = " true ";
143
+ expect(readStatelessEnv(false)).toBe(true);
144
+ });
145
+ });
146
+
147
+ describe("AC-3 — a bad value fails the boot; a blank rate does not disable the limit", () => {
148
+ it("a value outside the four spellings throws an Error naming MCP_HTTP_STATELESS", () => {
149
+ process.env["MCP_HTTP_STATELESS"] = "yes";
150
+ expect(() => readStatelessEnv(true)).toThrow(Error);
151
+ expect(() => readStatelessEnv(true)).toThrow(/MCP_HTTP_STATELESS/);
152
+ });
153
+
154
+ it("MCP_RATE_LIMIT_READ_PER_MIN='' yields the default 60, never NaN", () => {
155
+ process.env["MCP_RATE_LIMIT_READ_PER_MIN"] = "";
156
+ expect(httpTransportConfigFromEnv().rateLimits.readPerMin).toBe(60);
157
+ });
158
+
159
+ it("MCP_RATE_LIMIT_WRITE_PER_MIN='' yields the default 10, never NaN", () => {
160
+ process.env["MCP_RATE_LIMIT_WRITE_PER_MIN"] = "";
161
+ expect(httpTransportConfigFromEnv().rateLimits.writePerMin).toBe(10);
162
+ });
163
+ });
164
+
165
+ describe("httpTransportConfigFromEnv — today's reading of every other variable", () => {
166
+ it("unset, it returns today's defaults", () => {
167
+ expect(httpTransportConfigFromEnv()).toEqual({
168
+ port: 8080,
169
+ path: "/mcp",
170
+ rateLimits: { readPerMin: 60, writePerMin: 10 },
171
+ cors: { writeAllowedOrigins: [] },
172
+ abuse: {
173
+ captureLeadDailyCapPerIp: 50,
174
+ startPurchaseDailyCapPerIp: 20,
175
+ blockedUserAgents: "",
176
+ },
177
+ });
178
+ });
179
+
180
+ it("set, it reads each variable as src/index.ts did", () => {
181
+ process.env["MCP_HTTP_PORT"] = "9090";
182
+ process.env["MCP_HTTP_PATH"] = "/agents";
183
+ process.env["MCP_RATE_LIMIT_READ_PER_MIN"] = "120";
184
+ process.env["MCP_RATE_LIMIT_WRITE_PER_MIN"] = "5";
185
+ process.env["MCP_CORS_WRITE_ALLOWED_ORIGINS"] =
186
+ "https://a.example, https://b.example";
187
+ process.env["MCP_ABUSE_CAPTURE_LEAD_DAILY_CAP"] = "3";
188
+ process.env["MCP_ABUSE_START_PURCHASE_DAILY_CAP"] = "2";
189
+ process.env["MCP_ABUSE_BLOCKED_USER_AGENTS"] = "BadBot";
190
+
191
+ expect(httpTransportConfigFromEnv()).toEqual({
192
+ port: 9090,
193
+ path: "/agents",
194
+ rateLimits: { readPerMin: 120, writePerMin: 5 },
195
+ cors: { writeAllowedOrigins: ["https://a.example", "https://b.example"] },
196
+ abuse: {
197
+ captureLeadDailyCapPerIp: 3,
198
+ startPurchaseDailyCapPerIp: 2,
199
+ blockedUserAgents: "BadBot",
200
+ },
201
+ });
202
+ });
203
+ });
@@ -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);