create-ailk 0.43.0 → 0.45.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.
@@ -14,26 +14,30 @@
14
14
  * endpoint when MCP_PUBLIC_HTTP_URL is configured.
15
15
  * Issue #4157 — `name` resolves from SITE_NAME (env → _site.mdx → neutral
16
16
  * default) instead of a hardcoded vendor-brand literal.
17
- * Issue #7136 — the five `feature`-tagged tools are gated on the licence
18
- * features the route passes in (`heldFeatures`), as registration is.
19
17
  * Issue #7396 — `mcpEndpoint` is the configured MCP HTTP host or absent. It
20
18
  * was `${baseUrl}/api/mcp`, a path apps/web does not serve, so every agent
21
19
  * that followed it got a 404.
22
- * Issue #8070 — `unservedTools` drops the tools this topology's MCP server
23
- * does not register (`create_project` on a spoke).
24
20
  * Issue #8057 — `description` resolves from SITE_DESCRIPTION
25
21
  * (`siteIdentity.description` in _site.mdx → neutral default) instead of the
26
22
  * template's own blurb on every site.
27
23
  * Issue #10392 — `authorization` names where an OAuth client signs in to the
28
24
  * workspace tools, when the site pins its issuer and advertises its MCP host.
25
+ * Issue #11951 — `tools` is the site's MCP server's own `tools/list`
26
+ * (`servedTools`), in its order, in place of the catalog gated by the licence
27
+ * (#5971, #7136) and the topology's unserved list (#8070): only the MCP
28
+ * deployment knows which modules it installed. The catalog is a lookup — a
29
+ * name it knows renders as its entry, one it does not from the server's own.
29
30
  */
30
31
 
31
32
  import {
32
33
  getMcpToolCatalog,
33
- type McpCatalogOptions,
34
34
  type McpToolCatalogEntry,
35
35
  } from "@working-theory/metadata";
36
36
 
37
+ import {
38
+ MCP_PROTOCOL_VERSION,
39
+ type ServedMcpTool,
40
+ } from "../../../lib/mcp-served-tools";
37
41
  import { SITE_DESCRIPTION, SITE_NAME } from "../../../lib/site-brand";
38
42
 
39
43
  /**
@@ -111,38 +115,27 @@ export interface BuildMcpManifestOptions {
111
115
  */
112
116
  authIssuer?: string;
113
117
  /**
114
- * Whether this deployment holds the `commerce` add-on licence claim
115
- * (#5971). Add-on-gated tools — today only `start_purchase` — are advertised
116
- * only when it does, so the discovery manifest and the running MCP server
117
- * agree about what this site offers.
118
- *
119
- * Injected rather than resolved here: this builder is PURE (same input →
120
- * same output), a property its own suite asserts. `route.ts` resolves the
121
- * claim and passes it in. Omitted ⇒ false, the fail-closed default.
122
- */
123
- commerceClaimed?: boolean;
124
- /**
125
- * The licence features this deployment holds (#7136). In refuse mode a
126
- * `feature`-tagged tool is advertised only when its feature is held — the
127
- * same gate the MCP server's registration applies. Injected, like
128
- * `commerceClaimed`. Omitted ⇒ none, the fail-closed default.
129
- */
130
- heldFeatures?: readonly string[];
131
- /** Overrides `MCP_FEATURE_GATE_MODE` — a test seam; `route.ts` never
132
- * passes it. */
133
- featureGate?: McpCatalogOptions["featureGate"];
134
- /**
135
- * Tool names this site's MCP server does not serve (#8070 D7) — the
136
- * topology seam's `UNSERVED_MCP_TOOLS`: `create_project` on a spoke, none
137
- * on a hub. Dropped from `tools`, so the manifest never advertises a tool
138
- * the server will not register. Injected, like `commerceClaimed`. Omitted ⇒
139
- * none dropped.
118
+ * The tools the site's MCP server serves — its `tools/list`, in its order
119
+ * (#11951 D4). `route.ts` reads it (`readServedMcpTools`) and passes it in,
120
+ * `[]` when there is no server or the read failed. Injected, like
121
+ * `mcpHttpUrl`, so the builder stays pure.
140
122
  */
141
- unservedTools?: readonly string[];
123
+ servedTools: readonly ServedMcpTool[];
142
124
  }
143
125
 
144
- /** MCP HTTP transport version this server implements. */
145
- const MCP_HTTP_VERSION = "2025-03-26";
126
+ /**
127
+ * The builder's lookup table (#11951 D4) — every anonymous-surface entry: a
128
+ * lookup, not a gate. Built once, on first use: its inputs never change.
129
+ */
130
+ let catalogByName: ReadonlyMap<string, McpToolCatalogEntry> | undefined;
131
+ function catalogLookup(): ReadonlyMap<string, McpToolCatalogEntry> {
132
+ catalogByName ??= new Map(
133
+ getMcpToolCatalog({ addons: { commerce: true }, featureGate: "warn" }).map(
134
+ (entry) => [entry.name, entry] as const,
135
+ ),
136
+ );
137
+ return catalogByName;
138
+ }
146
139
 
147
140
  const LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "[::1]"];
148
141
 
@@ -192,12 +185,14 @@ export function buildMcpManifest(opts: BuildMcpManifestOptions): McpManifest {
192
185
  transports.push({
193
186
  type: "http",
194
187
  url: opts.mcpHttpUrl,
195
- version: MCP_HTTP_VERSION,
188
+ // The version the discovery read speaks, so the two cannot drift (#11951 D2).
189
+ version: MCP_PROTOCOL_VERSION,
196
190
  label: "HTTP (Streamable HTTP transport)",
197
191
  });
198
192
  }
199
193
 
200
194
  const authorization = authorizationFor(opts.authIssuer, opts.mcpHttpUrl);
195
+ const catalog = catalogLookup();
201
196
 
202
197
  return {
203
198
  schemaVersion: "1",
@@ -206,14 +201,22 @@ export function buildMcpManifest(opts: BuildMcpManifestOptions): McpManifest {
206
201
  // Spread conditional to satisfy exactOptionalPropertyTypes: the key is
207
202
  // absent, not undefined, when no MCP HTTP host is configured.
208
203
  ...(opts.mcpHttpUrl ? { mcpEndpoint: opts.mcpHttpUrl } : {}),
209
- tools: getMcpToolCatalog({
210
- addons: { commerce: opts.commerceClaimed === true },
211
- features: opts.heldFeatures ?? [],
212
- ...(opts.featureGate ? { featureGate: opts.featureGate } : {}),
213
- }).filter((tool) => !(opts.unservedTools ?? []).includes(tool.name)),
204
+ // A served name the catalog knows renders as its entry; one it does not
205
+ // (an MCP deployment newer than this site) in the server's own words,
206
+ // `outputSchema: {}` — the schema that admits anything, since the server
207
+ // publishes none (#11951 D4).
208
+ tools: opts.servedTools.map(
209
+ (tool) =>
210
+ catalog.get(tool.name) ?? {
211
+ name: tool.name,
212
+ description: tool.description ?? "",
213
+ inputSchema: tool.inputSchema,
214
+ outputSchema: {},
215
+ },
216
+ ),
214
217
  transport: {
215
218
  type: "http",
216
- version: MCP_HTTP_VERSION,
219
+ version: MCP_PROTOCOL_VERSION,
217
220
  },
218
221
  transports,
219
222
  ailk: { version: opts.ailkVersion },
@@ -7,18 +7,18 @@
7
7
  * The endpoint is advertised only when MCP_PUBLIC_HTTP_URL configures one
8
8
  * (#7396) — apps/web serves no MCP endpoint itself.
9
9
  *
10
- * Assembly — no fetch(). The catalog is read in-process from
11
- * @working-theory/metadata; the AILK version is read from this app's
12
- * package.json; the `commerce` add-on claim is read locally through
13
- * `checkLicense()` (#5971) so an add-on-gated tool is advertised on exactly
14
- * the deployments whose MCP server registers it. Without that, a KEYED site
15
- * would register `start_purchase` while hiding it from its own manifest —
16
- * the surface disagreement `apps/mcp/__tests__/catalog-drift.test.ts` exists
17
- * to make impossible. The same single read also yields the licence features
18
- * the deployment holds (#7136), which gate the five `feature`-tagged tools
19
- * here exactly as they gate registration on the MCP server. `create_project`
20
- * is always left out: this manifest describes the HTTP surface, and the MCP
21
- * server serves that tool over stdio only (#9965 D13, #8584).
10
+ * The tools are the MCP server's own (#11951). The route asks the server at
11
+ * MCP_PUBLIC_HTTP_URL for its `tools/list` (`lib/mcp-served-tools.ts`, one
12
+ * answer per URL per instance for 60 s) and lists exactly that, in its order.
13
+ * Only the MCP deployment knows which module packages it installed, so the
14
+ * licence, commerce-claim and topology gates this route once copied from its
15
+ * registration rule (#5971, #7136, #8070) drifted by construction: the
16
+ * server applies them itself. `create_project` is absent because the HTTP
17
+ * transport never lists it (#9965 D13). When the server cannot be read the
18
+ * manifest lists no tools — never a guess — and answers `no-store`; with no
19
+ * MCP_PUBLIC_HTTP_URL there is no server to ask, and it lists none. The
20
+ * catalog in @working-theory/metadata only supplies each known tool's entry;
21
+ * the AILK version is read from this app's package.json.
22
22
  *
23
23
  * Mirrors /.well-known/ai-plugin.json conventions: Response.json with a
24
24
  * conservative cache-control header.
@@ -30,12 +30,8 @@
30
30
 
31
31
  import { siteDiscoverable } from "@working-theory/api-client";
32
32
 
33
- import { UNSERVED_MCP_TOOLS } from "../../../lib/topology.generated";
33
+ import { readServedMcpTools } from "../../../lib/mcp-served-tools";
34
34
  import packageJson from "../../../package.json";
35
- import {
36
- COMMERCE_FEATURE,
37
- resolveLicenceFeatures,
38
- } from "../../../src/lib/commerce-claim";
39
35
 
40
36
  import { buildMcpManifest } from "./build-manifest";
41
37
 
@@ -57,7 +53,8 @@ export function OPTIONS(): Response {
57
53
  }
58
54
 
59
55
  export async function GET(): Promise<Response> {
60
- // #10510 D4 — hidden by the owner: 404, never cached, before the licence read.
56
+ // #10510 D4 — hidden by the owner: 404, never cached, before the MCP server
57
+ // is asked (#11951).
61
58
  if (!(await siteDiscoverable())) {
62
59
  return new Response(null, {
63
60
  status: 404,
@@ -71,18 +68,12 @@ export async function GET(): Promise<Response> {
71
68
  const mcpHttpUrlEnv = process.env["MCP_PUBLIC_HTTP_URL"];
72
69
  // With it, the site's pinned issuer turns on the OAuth metadata (#10392).
73
70
  const authIssuerEnv = process.env["BETTER_AUTH_URL"];
74
- const heldFeatures = await resolveLicenceFeatures();
71
+ // #11951 D4 — the server's own tools/list; `null` is a failed read.
72
+ const served = mcpHttpUrlEnv ? await readServedMcpTools(mcpHttpUrlEnv) : [];
75
73
 
76
74
  const manifest = buildMcpManifest({
77
75
  ailkVersion: packageJson.version,
78
- commerceClaimed: heldFeatures.includes(COMMERCE_FEATURE),
79
- heldFeatures,
80
- // The tools this topology's MCP server does not register (#8070 D7) —
81
- // and create_project, which the HTTP transport never serves (#9965 D13).
82
- unservedTools: [
83
- ...UNSERVED_MCP_TOOLS.filter((name) => name !== "create_project"),
84
- "create_project",
85
- ],
76
+ servedTools: served ?? [],
86
77
  // Spread conditional to satisfy exactOptionalPropertyTypes: omit the key
87
78
  // entirely when the env var is not set rather than passing undefined.
88
79
  ...(mcpHttpUrlEnv ? { mcpHttpUrl: mcpHttpUrlEnv } : {}),
@@ -92,7 +83,8 @@ export async function GET(): Promise<Response> {
92
83
  return Response.json(manifest, {
93
84
  status: 200,
94
85
  headers: {
95
- "cache-control": "public, max-age=86400",
86
+ // A failed read is a passing state no client should keep (#11951 D4).
87
+ "cache-control": served === null ? "no-store" : "public, max-age=86400",
96
88
  ...CORS_HEADERS,
97
89
  },
98
90
  });
@@ -0,0 +1,238 @@
1
+ /**
2
+ * A `node:http` stub of the MCP server's anonymous `/mcp` route (#11951 §5),
3
+ * answering the way the SDK's Streamable HTTP transport answered the spec's
4
+ * probe in each mode:
5
+ *
6
+ * - `stateless` — JSON bodies, no session; a bare `tools/list` is accepted.
7
+ * - `stateful` — `text/event-stream` bodies, an `Mcp-Session-Id` on
8
+ * `initialize`, 400 for any other POST without it; `DELETE` with it answers
9
+ * 200, or 400 when it carries a `content-type` (Fastify's empty-JSON-body
10
+ * refusal).
11
+ *
12
+ * Like the server's abuse guard it refuses a `user-agent` other than
13
+ * `MCP_DISCOVERY_USER_AGENT` with `403 {"error":"blocked user agent"}`; like
14
+ * the transport it answers 406 to an `accept` missing either type and 415 to
15
+ * a POST that is not `application/json`. `tools/list` can be served in pages,
16
+ * and `override` can answer any request with a fixed status, a raw body, or
17
+ * no answer at all. Every request is recorded. The stub follows the server,
18
+ * never the other way round.
19
+ */
20
+
21
+ import {
22
+ createServer,
23
+ type IncomingHttpHeaders,
24
+ type IncomingMessage,
25
+ type ServerResponse,
26
+ } from "node:http";
27
+ import type { AddressInfo } from "node:net";
28
+
29
+ import { MCP_DISCOVERY_USER_AGENT } from "../../mcp-served-tools";
30
+
31
+ export interface StubTool {
32
+ name: string;
33
+ description?: string;
34
+ inputSchema: Record<string, unknown>;
35
+ }
36
+
37
+ export interface RecordedRequest {
38
+ method: string;
39
+ /** The JSON-RPC `method` and `id`, when the body carried them. */
40
+ rpcMethod?: string;
41
+ rpcId?: unknown;
42
+ params?: Record<string, unknown>;
43
+ headers: IncomingHttpHeaders;
44
+ }
45
+
46
+ /** What `override` may answer in place of the stub's own reply. */
47
+ export type StubOverride =
48
+ | { status: number; contentType?: string; body?: string }
49
+ | "hang";
50
+
51
+ export interface McpStubOptions {
52
+ mode: "stateless" | "stateful";
53
+ tools: readonly StubTool[];
54
+ /** Serve `tools/list` this many entries a page, `nextCursor` on all but the last. */
55
+ pageSize?: number;
56
+ override?: (request: RecordedRequest) => StubOverride | undefined;
57
+ }
58
+
59
+ export interface McpStub {
60
+ /** The stub's `/mcp` URL. */
61
+ url: string;
62
+ requests: RecordedRequest[];
63
+ close(): Promise<void>;
64
+ }
65
+
66
+ const SESSION_ID = "stub-session-1";
67
+ const PROTOCOL_VERSION = "2025-03-26";
68
+
69
+ function readBody(req: IncomingMessage): Promise<string> {
70
+ return new Promise((resolve, reject) => {
71
+ let data = "";
72
+ req.setEncoding("utf8");
73
+ req.on("data", (chunk: string) => {
74
+ data += chunk;
75
+ });
76
+ req.on("end", () => resolve(data));
77
+ req.on("error", reject);
78
+ });
79
+ }
80
+
81
+ function parseRpc(
82
+ raw: string,
83
+ ): { id?: unknown; method?: string; params?: Record<string, unknown> } | null {
84
+ try {
85
+ const value: unknown = JSON.parse(raw);
86
+ return typeof value === "object" && value !== null && !Array.isArray(value)
87
+ ? (value as { id?: unknown; method?: string; params?: Record<string, unknown> })
88
+ : null;
89
+ } catch {
90
+ return null;
91
+ }
92
+ }
93
+
94
+ export async function startMcpStub(options: McpStubOptions): Promise<McpStub> {
95
+ const requests: RecordedRequest[] = [];
96
+
97
+ function send(
98
+ res: ServerResponse,
99
+ status: number,
100
+ message: unknown,
101
+ extraHeaders: Record<string, string> = {},
102
+ ): void {
103
+ if (options.mode === "stateful") {
104
+ res.writeHead(status, { "content-type": "text/event-stream", ...extraHeaders });
105
+ res.end(`event: message\ndata: ${JSON.stringify(message)}\n\n`);
106
+ return;
107
+ }
108
+ res.writeHead(status, { "content-type": "application/json", ...extraHeaders });
109
+ res.end(JSON.stringify(message));
110
+ }
111
+
112
+ function plain(res: ServerResponse, status: number, body = ""): void {
113
+ res.writeHead(status, body ? { "content-type": "application/json" } : {});
114
+ res.end(body);
115
+ }
116
+
117
+ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
118
+ const raw = await readBody(req);
119
+ const rpc = req.method === "POST" ? parseRpc(raw) : null;
120
+ const recorded: RecordedRequest = {
121
+ method: req.method ?? "",
122
+ ...(typeof rpc?.method === "string" ? { rpcMethod: rpc.method } : {}),
123
+ ...(rpc && "id" in rpc ? { rpcId: rpc.id } : {}),
124
+ ...(rpc?.params ? { params: rpc.params } : {}),
125
+ headers: req.headers,
126
+ };
127
+ requests.push(recorded);
128
+
129
+ const forced = options.override?.(recorded);
130
+ if (forced === "hang") return;
131
+ if (forced) {
132
+ res.writeHead(forced.status, forced.contentType ? { "content-type": forced.contentType } : {});
133
+ res.end(forced.body ?? "");
134
+ return;
135
+ }
136
+
137
+ if (req.headers["user-agent"] !== MCP_DISCOVERY_USER_AGENT) {
138
+ plain(res, 403, JSON.stringify({ error: "blocked user agent" }));
139
+ return;
140
+ }
141
+ const accept = req.headers["accept"] ?? "";
142
+ if (!accept.includes("application/json") || !accept.includes("text/event-stream")) {
143
+ plain(res, 406);
144
+ return;
145
+ }
146
+ const session = req.headers["mcp-session-id"];
147
+
148
+ if (req.method === "DELETE") {
149
+ if (options.mode !== "stateful" || session !== SESSION_ID) plain(res, 400);
150
+ else if (req.headers["content-type"] !== undefined) plain(res, 400);
151
+ else plain(res, 200);
152
+ return;
153
+ }
154
+ if (req.method !== "POST") {
155
+ plain(res, 405);
156
+ return;
157
+ }
158
+ if (req.headers["content-type"] !== "application/json") {
159
+ plain(res, 415);
160
+ return;
161
+ }
162
+ if (rpc === null || typeof rpc.method !== "string") {
163
+ plain(res, 400);
164
+ return;
165
+ }
166
+
167
+ if (rpc.method === "initialize") {
168
+ send(
169
+ res,
170
+ 200,
171
+ {
172
+ jsonrpc: "2.0",
173
+ id: rpc.id,
174
+ result: {
175
+ protocolVersion: PROTOCOL_VERSION,
176
+ capabilities: { tools: { listChanged: true } },
177
+ serverInfo: { name: "mcp-stub", version: "0.0.0" },
178
+ },
179
+ },
180
+ options.mode === "stateful" ? { "mcp-session-id": SESSION_ID } : {},
181
+ );
182
+ return;
183
+ }
184
+ if (options.mode === "stateful" && session !== SESSION_ID) {
185
+ plain(res, 400);
186
+ return;
187
+ }
188
+ if (rpc.method === "notifications/initialized") {
189
+ plain(res, 202);
190
+ return;
191
+ }
192
+ if (rpc.method === "tools/list") {
193
+ const size = options.pageSize ?? options.tools.length;
194
+ const cursor = rpc.params?.["cursor"];
195
+ const start = typeof cursor === "string" ? Number(cursor) : 0;
196
+ const page = options.tools.slice(start, start + size);
197
+ const next = start + size < options.tools.length ? String(start + size) : undefined;
198
+ send(res, 200, {
199
+ jsonrpc: "2.0",
200
+ id: rpc.id,
201
+ result: { tools: page, ...(next ? { nextCursor: next } : {}) },
202
+ });
203
+ return;
204
+ }
205
+ send(res, 200, {
206
+ jsonrpc: "2.0",
207
+ id: rpc.id,
208
+ error: { code: -32601, message: "Method not found" },
209
+ });
210
+ }
211
+
212
+ const server = createServer((req, res) => {
213
+ handle(req, res).catch(() => {
214
+ if (!res.headersSent) plain(res, 500);
215
+ });
216
+ });
217
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
218
+ const { port } = server.address() as AddressInfo;
219
+
220
+ return {
221
+ url: `http://127.0.0.1:${port}/mcp`,
222
+ requests,
223
+ close: () =>
224
+ new Promise<void>((resolve) => {
225
+ server.closeAllConnections();
226
+ server.close(() => resolve());
227
+ }),
228
+ };
229
+ }
230
+
231
+ /** A URL on a port bound and then closed: every connection is refused. */
232
+ export async function refusedUrl(): Promise<string> {
233
+ const server = createServer();
234
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
235
+ const { port } = server.address() as AddressInfo;
236
+ await new Promise<void>((resolve) => server.close(() => resolve()));
237
+ return `http://127.0.0.1:${port}/mcp`;
238
+ }