@hexagen-monaco/sync 0.5.2 → 0.7.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 (148) hide show
  1. package/dist/cli.js +1610 -620
  2. package/dist/cli.js.map +1 -1
  3. package/dist/config.d.ts +24 -0
  4. package/dist/config.d.ts.map +1 -1
  5. package/dist/domain/types.d.ts +8 -1
  6. package/dist/domain/types.d.ts.map +1 -1
  7. package/dist/fs-utils.d.ts +17 -4
  8. package/dist/fs-utils.d.ts.map +1 -1
  9. package/dist/generators/apps-framework-templates.d.ts +2 -1
  10. package/dist/generators/apps-framework-templates.d.ts.map +1 -1
  11. package/dist/generators/apps.d.ts.map +1 -1
  12. package/dist/generators/architecture-files.d.ts.map +1 -1
  13. package/dist/generators/barrels/recursive.d.ts +2 -3
  14. package/dist/generators/barrels/recursive.d.ts.map +1 -1
  15. package/dist/generators/barrels.d.ts +2 -3
  16. package/dist/generators/barrels.d.ts.map +1 -1
  17. package/dist/generators/cross-context.d.ts +5 -0
  18. package/dist/generators/cross-context.d.ts.map +1 -0
  19. package/dist/generators/eslint.d.ts +3 -1
  20. package/dist/generators/eslint.d.ts.map +1 -1
  21. package/dist/generators/layer-folders.d.ts +18 -6
  22. package/dist/generators/layer-folders.d.ts.map +1 -1
  23. package/dist/generators/package-json.d.ts +2 -3
  24. package/dist/generators/package-json.d.ts.map +1 -1
  25. package/dist/generators/port-analyzer.d.ts +38 -4
  26. package/dist/generators/port-analyzer.d.ts.map +1 -1
  27. package/dist/generators/reap.d.ts +7 -3
  28. package/dist/generators/reap.d.ts.map +1 -1
  29. package/dist/generators/root-file-templates.d.ts +4 -4
  30. package/dist/generators/root-file-templates.d.ts.map +1 -1
  31. package/dist/generators/root-files.d.ts.map +1 -1
  32. package/dist/generators/shared-kernel.d.ts +23 -0
  33. package/dist/generators/shared-kernel.d.ts.map +1 -0
  34. package/dist/generators/stubs.d.ts +13 -0
  35. package/dist/generators/stubs.d.ts.map +1 -1
  36. package/dist/generators/tsconfig.d.ts.map +1 -1
  37. package/dist/index.js +1441 -470
  38. package/dist/index.js.map +1 -1
  39. package/dist/journal.d.ts +64 -0
  40. package/dist/journal.d.ts.map +1 -0
  41. package/dist/migration-report.d.ts +13 -2
  42. package/dist/migration-report.d.ts.map +1 -1
  43. package/dist/results.d.ts +66 -0
  44. package/dist/results.d.ts.map +1 -1
  45. package/dist/scope-filter.d.ts +35 -0
  46. package/dist/scope-filter.d.ts.map +1 -0
  47. package/dist/sync-engine-helpers.d.ts.map +1 -1
  48. package/dist/sync-engine.d.ts +13 -1
  49. package/dist/sync-engine.d.ts.map +1 -1
  50. package/dist/templates/adobe-creative-production/manifest.json +2 -0
  51. package/dist/templates/adobe-express/manifest.json +2 -0
  52. package/dist/templates/adobe-firefly-composite/manifest.json +2 -0
  53. package/dist/templates/adobe-firefly-content-tagging/manifest.json +2 -0
  54. package/dist/templates/adobe-firefly-core/manifest.json +2 -0
  55. package/dist/templates/adobe-firefly-custom-models/manifest.json +2 -0
  56. package/dist/templates/adobe-firefly-generate/manifest.json +2 -0
  57. package/dist/templates/adobe-firefly-media/manifest.json +2 -0
  58. package/dist/templates/adobe-firefly-storage-azure/manifest.json +2 -0
  59. package/dist/templates/adobe-firefly-storage-gcs/manifest.json +2 -0
  60. package/dist/templates/adobe-firefly-storage-s3/manifest.json +2 -0
  61. package/dist/templates/adobe-firefly-upscale/manifest.json +2 -0
  62. package/dist/templates/adobe-illustrator/manifest.json +2 -0
  63. package/dist/templates/adobe-ims-spa/manifest.json +2 -0
  64. package/dist/templates/adobe-indesign/manifest.json +2 -0
  65. package/dist/templates/adobe-lightroom/manifest.json +2 -0
  66. package/dist/templates/adobe-photoshop/manifest.json +2 -0
  67. package/dist/templates/adobe-substance-3d/manifest.json +2 -0
  68. package/dist/templates/auth-mock/manifest.json +2 -0
  69. package/dist/templates/bedrock-agentcore-runtime/manifest.json +10 -2
  70. package/dist/templates/bedrock-agentcore-services/manifest.json +38 -9
  71. package/dist/templates/better-auth/manifest.json +2 -0
  72. package/dist/templates/bullmq/manifest.json +2 -0
  73. package/dist/templates/ci-github-actions/README.md +7 -0
  74. package/dist/templates/ci-github-actions/files/.github/dependabot.yml +16 -4
  75. package/dist/templates/ci-github-actions/files/.github/workflows/ci.yml +7 -3
  76. package/dist/templates/ci-github-actions/files/.github/workflows/preview.yml +20 -2
  77. package/dist/templates/ci-github-actions/manifest.json +26 -6
  78. package/dist/templates/clerk/manifest.json +2 -0
  79. package/dist/templates/design-system/manifest.json +14 -3
  80. package/dist/templates/docker/manifest.json +2 -0
  81. package/dist/templates/error-handling/manifest.json +2 -0
  82. package/dist/templates/eslint-no-console/manifest.json +2 -0
  83. package/dist/templates/github-oauth/manifest.json +2 -0
  84. package/dist/templates/google-oauth/manifest.json +2 -0
  85. package/dist/templates/langgraph/manifest.json +62 -15
  86. package/dist/templates/llm-adapter/manifest.json +2 -0
  87. package/dist/templates/magic-link/manifest.json +2 -0
  88. package/dist/templates/mcp-server/README.md +49 -0
  89. package/dist/templates/mcp-server/files/.env.mcp.example +6 -0
  90. package/dist/templates/mcp-server/files/.mcp.json.example +8 -0
  91. package/dist/templates/mcp-server/files/bin/cli.ts +15 -0
  92. package/dist/templates/mcp-server/files/src/infrastructure/mcp/prompts/example.prompt.ts +32 -0
  93. package/dist/templates/mcp-server/files/src/infrastructure/mcp/registry/register-all.ts +11 -0
  94. package/dist/templates/mcp-server/files/src/infrastructure/mcp/registry/tool-registry.test.ts +67 -0
  95. package/dist/templates/mcp-server/files/src/infrastructure/mcp/registry/tool-registry.ts +45 -0
  96. package/dist/templates/mcp-server/files/src/infrastructure/mcp/resources/example.resource.ts +28 -0
  97. package/dist/templates/mcp-server/files/src/infrastructure/mcp/sdk.ts +41 -0
  98. package/dist/templates/mcp-server/files/src/infrastructure/mcp/server.ts +52 -0
  99. package/dist/templates/mcp-server/files/src/infrastructure/mcp/tools/example.tool.test.ts +31 -0
  100. package/dist/templates/mcp-server/files/src/infrastructure/mcp/tools/example.tool.ts +74 -0
  101. package/dist/templates/mcp-server/files/src/infrastructure/mcp/transport/register-transports.ts +15 -0
  102. package/dist/templates/mcp-server/files/src/infrastructure/mcp/transport/stdio.ts +14 -0
  103. package/dist/templates/mcp-server/manifest.json +68 -0
  104. package/dist/templates/mcp-server-http/README.md +98 -0
  105. package/dist/templates/mcp-server-http/files/.env.mcp-http.example +22 -0
  106. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/auth/bearer.test.ts +54 -0
  107. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/auth/bearer.ts +49 -0
  108. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/auth/oauth.test.ts +50 -0
  109. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/auth/oauth.ts +53 -0
  110. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/guard.test.ts +75 -0
  111. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/guard.ts +26 -0
  112. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/transport/http.ts +94 -0
  113. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/transport/register-transports.ts +15 -0
  114. package/dist/templates/mcp-server-http/manifest.json +56 -0
  115. package/dist/templates/microsoft-entra/manifest.json +2 -0
  116. package/dist/templates/nextauth/manifest.json +2 -0
  117. package/dist/templates/observability/manifest.json +10 -2
  118. package/dist/templates/rate-limiting/manifest.json +2 -0
  119. package/dist/templates/shared-types/manifest.json +2 -0
  120. package/dist/templates/supabase/manifest.json +2 -0
  121. package/dist/templates/supabase-auth/manifest.json +2 -0
  122. package/dist/toolchain-version.d.ts +14 -0
  123. package/dist/toolchain-version.d.ts.map +1 -0
  124. package/dist/types/manifest/apps.d.ts +12 -1
  125. package/dist/types/manifest/apps.d.ts.map +1 -1
  126. package/package.json +1 -1
  127. package/dist/application/use-cases/stub-generation.use-case.d.ts +0 -23
  128. package/dist/application/use-cases/stub-generation.use-case.d.ts.map +0 -1
  129. package/dist/generators/migration-assistant.d.ts +0 -7
  130. package/dist/generators/migration-assistant.d.ts.map +0 -1
  131. package/dist/generators/migration-audit.d.ts +0 -28
  132. package/dist/generators/migration-audit.d.ts.map +0 -1
  133. package/dist/generators/migration-stubs.d.ts +0 -7
  134. package/dist/generators/migration-stubs.d.ts.map +0 -1
  135. package/dist/generators/test-generator.d.ts +0 -7
  136. package/dist/generators/test-generator.d.ts.map +0 -1
  137. package/dist/generators/test-templates/data-builder.d.ts +0 -2
  138. package/dist/generators/test-templates/data-builder.d.ts.map +0 -1
  139. package/dist/generators/test-templates/enhanced-test-double.d.ts +0 -2
  140. package/dist/generators/test-templates/enhanced-test-double.d.ts.map +0 -1
  141. package/dist/generators/test-templates/index.d.ts +0 -5
  142. package/dist/generators/test-templates/index.d.ts.map +0 -1
  143. package/dist/generators/test-templates/integration-test.d.ts +0 -2
  144. package/dist/generators/test-templates/integration-test.d.ts.map +0 -1
  145. package/dist/generators/test-templates/unit-test.d.ts +0 -2
  146. package/dist/generators/test-templates/unit-test.d.ts.map +0 -1
  147. package/dist/generators/wiring.d.ts +0 -20
  148. package/dist/generators/wiring.d.ts.map +0 -1
@@ -0,0 +1,28 @@
1
+ // @hexagen-server-only
2
+ /**
3
+ * Example MCP resource (read-only) — exposes data a client can fetch by URI.
4
+ * Resources mirror the tool pattern: validate, call a *read* use-case, return
5
+ * its content. A worked stub: wire it onto the server from your composition root
6
+ * and replace the body with a real read use-case.
7
+ */
8
+ import type { McpServerLike } from "../sdk.js";
9
+
10
+ type ResourceCapableServer = McpServerLike & {
11
+ registerResource?: (
12
+ name: string,
13
+ uri: string,
14
+ handler: () => Promise<{ contents: Array<{ uri: string; text: string }> }>,
15
+ ) => void;
16
+ };
17
+
18
+ export function registerExampleResource(server: McpServerLike): void {
19
+ (server as ResourceCapableServer).registerResource?.(
20
+ "example",
21
+ "example://info",
22
+ async () => ({
23
+ contents: [
24
+ { uri: "example://info", text: "Replace with a read use-case." },
25
+ ],
26
+ }),
27
+ );
28
+ }
@@ -0,0 +1,41 @@
1
+ // @hexagen-server-only — loads the MCP SDK; must never reach a client bundle (ADR-0037).
2
+ /**
3
+ * Dynamic-import wrapper for `@modelcontextprotocol/sdk` (ADR-0010).
4
+ *
5
+ * The SDK ships `node:`-scheme imports that break webpack when imported
6
+ * statically into a client-bundled app, so it is loaded at runtime via
7
+ * `import()` instead. A side benefit: a missing SDK fails *here*, with a clear
8
+ * install hint, rather than breaking the build.
9
+ *
10
+ * Install it: `npm install @modelcontextprotocol/sdk zod`
11
+ */
12
+
13
+ // The SDK is loaded at runtime, so its types aren't statically available here;
14
+ // the composition root treats the returned values structurally.
15
+ export interface LoadedSdk {
16
+ McpServer: new (info: { name: string; version: string }) => McpServerLike;
17
+ }
18
+
19
+ export interface McpServerLike {
20
+ registerTool(
21
+ name: string,
22
+ config: { description: string; inputSchema: Record<string, unknown> },
23
+ handler: (input: Record<string, unknown>) => Promise<unknown>,
24
+ ): void;
25
+ connect(transport: unknown): Promise<void>;
26
+ }
27
+
28
+ let cached: Promise<LoadedSdk> | null = null;
29
+
30
+ export function loadSdk(): Promise<LoadedSdk> {
31
+ cached ??= import("@modelcontextprotocol/sdk/server/mcp.js")
32
+ .then((mod) => ({ McpServer: mod.McpServer as LoadedSdk["McpServer"] }))
33
+ .catch((cause: unknown) => {
34
+ cached = null;
35
+ throw new Error(
36
+ "Failed to load @modelcontextprotocol/sdk. Install it: `npm install @modelcontextprotocol/sdk zod`.",
37
+ { cause },
38
+ );
39
+ });
40
+ return cached;
41
+ }
@@ -0,0 +1,52 @@
1
+ // @hexagen-server-only — composition root; holds privileged use-cases (ADR-0037).
2
+ import { loadSdk } from "./sdk.js";
3
+ import { applyTools } from "./registry/tool-registry.js";
4
+
5
+ /**
6
+ * Builds a transport instance on demand. A **factory**, not an instance, so an
7
+ * addon (e.g. `mcp-server-http`) can register a fully-configured transport
8
+ * without this composition root knowing its options — and without depending on
9
+ * when it is constructed.
10
+ */
11
+ export type TransportFactory = () => Promise<unknown>;
12
+
13
+ const transportFactories = new Map<string, TransportFactory>();
14
+
15
+ /**
16
+ * Register a transport under an `MCP_TRANSPORT` value. The base registers
17
+ * `stdio`; the `mcp-server-http` addon registers `streamable-http` — each from
18
+ * its own file via `transport/register-transports.ts`, so neither edits this file.
19
+ */
20
+ export function registerTransport(
21
+ name: string,
22
+ factory: TransportFactory,
23
+ ): void {
24
+ transportFactories.set(name, factory);
25
+ }
26
+
27
+ /**
28
+ * Compose and start the MCP server: load the SDK (dynamic import, ADR-0010),
29
+ * build the server, wire the registered tools, then connect the transport
30
+ * selected by `MCP_TRANSPORT` (default `stdio`). `register-all.ts` and
31
+ * `register-transports.ts` must be imported first (see `bin/cli.ts`) so the
32
+ * registries are populated.
33
+ */
34
+ export async function startServer(): Promise<void> {
35
+ const { McpServer } = await loadSdk();
36
+ const server = new McpServer({
37
+ name: process.env.MCP_SERVER_NAME || "{server_name}",
38
+ version: "0.1.0",
39
+ });
40
+
41
+ applyTools(server);
42
+
43
+ const transportName = process.env.MCP_TRANSPORT || "stdio";
44
+ const factory = transportFactories.get(transportName);
45
+ if (!factory) {
46
+ const known = [...transportFactories.keys()].join(", ") || "(none)";
47
+ throw new Error(
48
+ `No MCP transport registered for MCP_TRANSPORT="${transportName}". Registered: ${known}.`,
49
+ );
50
+ }
51
+ await server.connect(await factory());
52
+ }
@@ -0,0 +1,31 @@
1
+ // @hexagen-server-only
2
+ import { describe, it } from "node:test";
3
+ import assert from "node:assert/strict";
4
+
5
+ import { exampleTool } from "./example.tool.js";
6
+
7
+ describe("exampleTool", () => {
8
+ it("maps a successful Result to MCP text content", async () => {
9
+ const res = await exampleTool.handler({ name: "Ada" });
10
+ assert.equal(res.isError, undefined);
11
+ assert.match(res.content[0].text, /Ada/);
12
+ });
13
+
14
+ it("maps a use-case failure to an MCP error (isError: true)", async () => {
15
+ const res = await exampleTool.handler({ name: "" });
16
+ assert.equal(res.isError, true);
17
+ assert.match(res.content[0].text, /must not be empty/);
18
+ });
19
+
20
+ it("rejects an invalid input shape with an MCP error", async () => {
21
+ const res = await exampleTool.handler({ name: 123 });
22
+ assert.equal(res.isError, true);
23
+ assert.match(res.content[0].text, /Invalid input/);
24
+ });
25
+
26
+ it("dry_run validates without performing the action", async () => {
27
+ const res = await exampleTool.handler({ name: "Ada", dry_run: true });
28
+ assert.equal(res.isError, undefined);
29
+ assert.match(res.content[0].text, /dry-run/);
30
+ });
31
+ });
@@ -0,0 +1,74 @@
1
+ // @hexagen-server-only
2
+ /**
3
+ * Worked example: an MCP tool is an INBOUND ADAPTER over an existing use-case —
4
+ * validate input, call the use-case, map its `Result` to an MCP response. No
5
+ * business logic lives here; the hexagon is untouched. Copy this file to add a
6
+ * real tool, then register it in `registry/register-all.ts`.
7
+ *
8
+ * Two patterns to keep when you copy it:
9
+ * 1. **Explicit `Result` -> MCP mapping, including the error path** (`isError:
10
+ * true`). If the error path is glossed over here, every tool copied from it
11
+ * will gloss over it too.
12
+ * 2. **`dry_run`** for any tool that mutates state (ADR-0010 #5): validate and
13
+ * report what *would* happen, change nothing.
14
+ */
15
+ import { z } from "zod";
16
+ import type { RegisteredTool, ToolResult } from "../registry/tool-registry.js";
17
+
18
+ // A discriminated Result — your real use-cases already return one of these.
19
+ // Replace `greetUseCase` with a call into your application layer.
20
+ type Result<T> = { ok: true; value: T } | { ok: false; error: string };
21
+
22
+ async function greetUseCase(input: {
23
+ name: string;
24
+ dryRun: boolean;
25
+ }): Promise<Result<string>> {
26
+ if (input.name.trim() === "") {
27
+ return { ok: false, error: "name must not be empty" };
28
+ }
29
+ if (input.dryRun) {
30
+ return { ok: true, value: `[dry-run] would greet ${input.name}` };
31
+ }
32
+ return { ok: true, value: `Hello, ${input.name}, from {server_name}!` };
33
+ }
34
+
35
+ const InputSchema = {
36
+ name: z.string().describe("Who to greet"),
37
+ dry_run: z
38
+ .boolean()
39
+ .optional()
40
+ .describe("Validate and report the action without performing it"),
41
+ };
42
+
43
+ export const exampleTool: RegisteredTool = {
44
+ name: "greet",
45
+ description: "Example tool — greets a name. Replace with a real use-case.",
46
+ inputSchema: InputSchema,
47
+ handler: async (raw): Promise<ToolResult> => {
48
+ // 1. Validate the untrusted input at the boundary.
49
+ const parsed = z.object(InputSchema).safeParse(raw);
50
+ if (!parsed.success) {
51
+ return {
52
+ content: [
53
+ { type: "text", text: `Invalid input: ${parsed.error.message}` },
54
+ ],
55
+ isError: true,
56
+ };
57
+ }
58
+
59
+ // 2. Call the use-case.
60
+ const result = await greetUseCase({
61
+ name: parsed.data.name,
62
+ dryRun: parsed.data.dry_run ?? false,
63
+ });
64
+
65
+ // 3. Map the Result to an MCP response — BOTH branches, explicitly.
66
+ if (!result.ok) {
67
+ return {
68
+ content: [{ type: "text", text: `Error: ${result.error}` }],
69
+ isError: true,
70
+ };
71
+ }
72
+ return { content: [{ type: "text", text: result.value }] };
73
+ },
74
+ };
@@ -0,0 +1,15 @@
1
+ // @hexagen-server-only
2
+ /**
3
+ * Static transport registrations. The base registers `stdio`. An addon adds a
4
+ * transport here with one import + one `registerTransport(...)` line — e.g. the
5
+ * `mcp-server-http` addon appends:
6
+ *
7
+ * import { createHttpTransport } from "./http.js";
8
+ * registerTransport("streamable-http", createHttpTransport);
9
+ *
10
+ * so the composition root (`server.ts`) never needs to be rewritten.
11
+ */
12
+ import { registerTransport } from "../server.js";
13
+ import { createStdioTransport } from "./stdio.js";
14
+
15
+ registerTransport("stdio", createStdioTransport);
@@ -0,0 +1,14 @@
1
+ // @hexagen-server-only
2
+ import type { TransportFactory } from "../server.js";
3
+
4
+ /**
5
+ * stdio transport factory — the secure local default: the server runs as a
6
+ * subprocess of a trusted client (Claude Desktop/Code, an IDE), with no network
7
+ * surface. The SDK transport is dynamically imported (ADR-0010).
8
+ */
9
+ export const createStdioTransport: TransportFactory = async () => {
10
+ const { StdioServerTransport } = await import(
11
+ "@modelcontextprotocol/sdk/server/stdio.js"
12
+ );
13
+ return new StdioServerTransport();
14
+ };
@@ -0,0 +1,68 @@
1
+ {
2
+ "id": "mcp-server",
3
+ "name": "MCP Server (stdio)",
4
+ "description": "Expose the project's application use-cases as MCP tools over stdio — an inbound adapter with a static tool registry, a transport-factory seam, and a dynamic SDK import (ADR-0010).",
5
+ "provides": "platform.mcp",
6
+ "scope": "project",
7
+ "version": "1.0.0",
8
+ "requires": ["env-setup"],
9
+ "conflicts": [],
10
+ "branch": "feature/generator-template-mcp-server",
11
+ "questions": [
12
+ {
13
+ "id": "server_name",
14
+ "type": "text",
15
+ "prompt": "MCP server name advertised to clients?",
16
+ "default": "{projectName}"
17
+ },
18
+ {
19
+ "id": "resources",
20
+ "type": "boolean",
21
+ "prompt": "Scaffold MCP resources (read-only)?",
22
+ "default": false
23
+ },
24
+ {
25
+ "id": "prompts",
26
+ "type": "boolean",
27
+ "prompt": "Scaffold reusable MCP prompts?",
28
+ "default": false
29
+ }
30
+ ],
31
+ "envVars": ["MCP_SERVER_NAME", "MCP_TRANSPORT"],
32
+ "outputs": [
33
+ "src/infrastructure/mcp/sdk.ts",
34
+ "src/infrastructure/mcp/server.ts",
35
+ "src/infrastructure/mcp/transport/stdio.ts",
36
+ "src/infrastructure/mcp/transport/register-transports.ts",
37
+ "src/infrastructure/mcp/registry/tool-registry.ts",
38
+ "src/infrastructure/mcp/registry/register-all.ts",
39
+ "src/infrastructure/mcp/tools/example.tool.ts",
40
+ "src/infrastructure/mcp/tools/example.tool.test.ts",
41
+ "src/infrastructure/mcp/registry/tool-registry.test.ts",
42
+ "bin/cli.ts",
43
+ ".mcp.json.example",
44
+ ".env.mcp.example",
45
+ {
46
+ "path": "src/infrastructure/mcp/resources/example.resource.ts",
47
+ "when": {
48
+ "answer": "resources",
49
+ "equals": true
50
+ }
51
+ },
52
+ {
53
+ "path": "src/infrastructure/mcp/prompts/example.prompt.ts",
54
+ "when": {
55
+ "answer": "prompts",
56
+ "equals": true
57
+ }
58
+ }
59
+ ],
60
+ "checklist": [
61
+ "Install the SDK (there is no manifest deps field — this is the only channel): npm install @modelcontextprotocol/sdk",
62
+ "Set MCP_SERVER_NAME in .env (defaults to the project name).",
63
+ "Add a tool: copy src/infrastructure/mcp/tools/example.tool.ts, wrap your use-case, then add one import + registerTool(...) line in registry/register-all.ts.",
64
+ "Point your MCP client at the server using .mcp.json.example — it runs: npx tsx bin/cli.ts (.ts isn't executable by node directly; use tsx, or build and run node dist/bin/cli.js).",
65
+ "Verify with the inspector: npx @modelcontextprotocol/inspector npx tsx bin/cli.ts",
66
+ "For remote/HTTP access, install the mcp-server-http addon (always authenticated)."
67
+ ]
68
+ }
@@ -0,0 +1,98 @@
1
+ # Template: `mcp-server-http` (author / agent guide)
2
+
3
+ > Not emitted. This documents how the template is built so a future agent can
4
+ > extend it without re-deriving the design. The user-facing install steps live
5
+ > in `manifest.json`'s `checklist`.
6
+
7
+ HTTP-transport + auth addon for [`mcp-server`](../mcp-server/README.md). Splitting
8
+ HTTP out of the base does two things: it keeps the auth/transport prompt noise
9
+ out of stdio installs, and it makes the network transport **always
10
+ authenticated** — the unsafe `auth=none` combination is structurally excluded
11
+ (no such option) rather than rejected at prompt time.
12
+
13
+ ## Why this is a factory addon, not a `server.ts` rewrite
14
+
15
+ `docs/planning/generator-templates/18-mcp-server.md` (Template 2) predates the
16
+ base and describes re-emitting `server.ts` with an HTTP branch. **It is stale.**
17
+ The base shipped with the `registerTransport(factory)` seam its own Risk #4
18
+ asked for, so this addon uses the seam:
19
+
20
+ - **`server.ts` is untouched.** `startServer()` already dispatches on
21
+ `MCP_TRANSPORT` via the transport-factory registry.
22
+ - **`transport/register-transports.ts` is re-emitted** with both `stdio` and
23
+ `streamable-http` registrations — the seam's documented extension point. It is
24
+ a 3-line declarative file, so the overwrite's blast radius is minimal; a
25
+ user-edited copy is preserved as `.hexagen-update`.
26
+ - **The startup guard runs inside `createHttpTransport()`** (lazy), not in the
27
+ composition root — so stdio deployments pay nothing and importing the module
28
+ in a test never trips it.
29
+
30
+ ## Auth wiring (the `{auth}` interpolation)
31
+
32
+ `auth` is a select (`bearer` | `oauth`, no `none`). Only the chosen
33
+ implementation is emitted (gated outputs), and `http.ts` imports it via the
34
+ reserved-var seam: the source line
35
+
36
+ ```ts
37
+ import { authenticate } from "../auth/{auth}.js";
38
+ ```
39
+
40
+ interpolates to `../auth/bearer.js` or `../auth/oauth.js`. This is
41
+ install-time-fixed by design: only the selected strategy ships, so the unused
42
+ one is never a bundle/attack surface. `MCP_AUTH_MODE` does not switch the auth
43
+ _implementation_ (that is fixed at install via the gated file) — but it IS read
44
+ at startup by `guard.ts` (unset/`none` over HTTP → refuse to start). Changing the
45
+ actual mechanism means re-installing; if a runtime switch is ever required,
46
+ promote to a runtime auth registry mirroring the transport seam (the gated-file
47
+ structure does not block that).
48
+
49
+ Both `bearer.ts` and `oauth.ts` export `authenticate(req): Promise<boolean>`.
50
+ `bearer` does a constant-time token compare against `MCP_BEARER_TOKEN`. `oauth`
51
+ is a **fail-closed scaffold**: it denies all requests until you wire JWKS
52
+ verification (the `jose` snippet is in the file). A scaffold that returned `true`
53
+ would be dangerously misleading, so the default is deny.
54
+
55
+ Each module also exports **`assertConfigured()`**, called once at startup from the
56
+ HTTP factory (`http.ts`), which throws if the chosen mode's secret
57
+ (`MCP_BEARER_TOKEN` / `MCP_OAUTH_ISSUER_URL`) is unset — turning a silent
58
+ deny-all into a loud startup error. (The manifest's `envVars` intentionally lists
59
+ only the always-required `MCP_TRANSPORT`/`MCP_HTTP_PORT`/`MCP_AUTH_MODE`; the
60
+ secrets are conditional on `auth`, so listing both would make
61
+ `validate-templates` flag the unused mode's secret. A schema for conditional env
62
+ vars would be the proper static fix — an engine follow-up, not this addon.)
63
+
64
+ ## Deliberate deviations from the planning doc
65
+
66
+ - **`server.ts` is not re-emitted** (seam, above).
67
+ - **`MCP_ALLOWED_TOOLS` is documented but NOT enforced.** Tool-level
68
+ allowlisting filters tool dispatch, which lives in the base tool registry and
69
+ applies to every transport — it does not belong in a transport addon. The env
70
+ var is reserved with a loud "not yet enforced" note; enforcing it is a base
71
+ follow-up.
72
+
73
+ ## Files
74
+
75
+ | Output | Notes |
76
+ | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
77
+ | `transport/http.ts` | StreamableHTTP factory (`StreamableHTTPServerTransport`, dynamic import, stateless); guards, then authenticates each request before `handleRequest` |
78
+ | `transport/register-transports.ts` | **re-emit** — registers stdio + streamable-http |
79
+ | `guard.ts` | `assertSafeTransport` — refuses streamable-http without an auth mode |
80
+ | `auth/bearer.ts` / `auth/oauth.ts` | gated on `auth`; `http.ts` imports the chosen one via `{auth}` |
81
+ | `*.test.ts` (guard, bearer, oauth) | `node:test`; pattern-gated behind `--with-tests` (`99-gap-analysis.md`) |
82
+ | `.env.mcp-http.example` | `MCP_HTTP_PORT`/`MCP_AUTH_MODE` seeded from the answers |
83
+
84
+ ## SDK
85
+
86
+ `@modelcontextprotocol/sdk` **v1** — `server/streamableHttp.js` →
87
+ `StreamableHTTPServerTransport` (verified against the installed `1.29.0`, not
88
+ external docs; the repo's own server is stdio-only so there was no in-repo
89
+ ground truth for the HTTP subpath). Dynamically imported per ADR-0010.
90
+
91
+ ## Verify
92
+
93
+ ```bash
94
+ # emit shape (this repo)
95
+ yarn --cwd packages/template-engine test
96
+ # runtime (a generated project, SDK installed)
97
+ MCP_TRANSPORT=streamable-http MCP_AUTH_MODE=bearer MCP_BEARER_TOKEN=dev npx tsx bin/cli.ts
98
+ ```
@@ -0,0 +1,22 @@
1
+ # ─────────────────────────────────────────────────────────────────────────────
2
+ # MCP server — HTTP transport (added by mcp-server-http)
3
+ # Overrides the stdio defaults in .env.mcp.example. The server REFUSES TO START
4
+ # with streamable-http unless MCP_AUTH_MODE is bearer|oauth (see guard.ts).
5
+ # ─────────────────────────────────────────────────────────────────────────────
6
+ MCP_TRANSPORT=streamable-http
7
+ MCP_HTTP_PORT={http_port}
8
+
9
+ # Auth mode (chosen at install): bearer | oauth — there is no "none", HTTP is
10
+ # always authenticated.
11
+ MCP_AUTH_MODE={auth}
12
+
13
+ # bearer: the shared secret clients send as `Authorization: Bearer <token>`.
14
+ MCP_BEARER_TOKEN=
15
+
16
+ # oauth: your OAuth issuer base URL; wire token verification in auth/oauth.ts.
17
+ MCP_OAUTH_ISSUER_URL=
18
+
19
+ # Reserved — NOT YET ENFORCED. A comma-separated tool allowlist. Tool-level
20
+ # allowlisting is a cross-transport concern slated for the base tool registry;
21
+ # do not rely on this for access control in this version.
22
+ MCP_ALLOWED_TOOLS=
@@ -0,0 +1,54 @@
1
+ import { describe, it, afterEach } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import type { IncomingMessage } from "node:http";
4
+ import { authenticate, assertConfigured } from "./bearer.js";
5
+
6
+ function reqWith(authorization?: string): IncomingMessage {
7
+ return {
8
+ headers: authorization ? { authorization } : {},
9
+ } as IncomingMessage;
10
+ }
11
+
12
+ describe("bearer authenticate", () => {
13
+ const original = process.env.MCP_BEARER_TOKEN;
14
+ afterEach(() => {
15
+ if (original === undefined) delete process.env.MCP_BEARER_TOKEN;
16
+ else process.env.MCP_BEARER_TOKEN = original;
17
+ });
18
+
19
+ it("denies when MCP_BEARER_TOKEN is unset (fail closed)", async () => {
20
+ delete process.env.MCP_BEARER_TOKEN;
21
+ assert.equal(await authenticate(reqWith("Bearer anything")), false);
22
+ });
23
+
24
+ it("denies a missing, prefix-less, or wrong token", async () => {
25
+ process.env.MCP_BEARER_TOKEN = "s3cret";
26
+ assert.equal(await authenticate(reqWith(undefined)), false);
27
+ assert.equal(await authenticate(reqWith("s3cret")), false); // no "Bearer " prefix
28
+ assert.equal(await authenticate(reqWith("Bearer wrong")), false);
29
+ });
30
+
31
+ it("allows the correct token (scheme is case-insensitive, RFC 7235)", async () => {
32
+ process.env.MCP_BEARER_TOKEN = "s3cret";
33
+ assert.equal(await authenticate(reqWith("Bearer s3cret")), true);
34
+ assert.equal(await authenticate(reqWith("bearer s3cret")), true);
35
+ });
36
+ });
37
+
38
+ describe("bearer assertConfigured", () => {
39
+ const original = process.env.MCP_BEARER_TOKEN;
40
+ afterEach(() => {
41
+ if (original === undefined) delete process.env.MCP_BEARER_TOKEN;
42
+ else process.env.MCP_BEARER_TOKEN = original;
43
+ });
44
+
45
+ it("throws at startup when MCP_BEARER_TOKEN is unset", () => {
46
+ delete process.env.MCP_BEARER_TOKEN;
47
+ assert.throws(() => assertConfigured(), /MCP_BEARER_TOKEN/);
48
+ });
49
+
50
+ it("passes when MCP_BEARER_TOKEN is set", () => {
51
+ process.env.MCP_BEARER_TOKEN = "s3cret";
52
+ assert.doesNotThrow(() => assertConfigured());
53
+ });
54
+ });
@@ -0,0 +1,49 @@
1
+ // @hexagen-server-only
2
+ import { timingSafeEqual } from "node:crypto";
3
+ import type { IncomingMessage } from "node:http";
4
+
5
+ /**
6
+ * Bearer-token authentication for the HTTP transport. Compares the
7
+ * `Authorization: Bearer <token>` header against `MCP_BEARER_TOKEN` with a
8
+ * constant-time comparison. Fail-closed: denies when the env token is unset, so
9
+ * a misconfigured deployment rejects every request rather than allowing them.
10
+ */
11
+ export async function authenticate(req: IncomingMessage): Promise<boolean> {
12
+ const expected = process.env.MCP_BEARER_TOKEN;
13
+ if (!expected) return false; // fail closed — no token configured = deny all
14
+
15
+ const header = req.headers.authorization;
16
+ const value = Array.isArray(header) ? header[0] : header;
17
+ // RFC 7235 §2.1: the auth-scheme name is case-insensitive ("Bearer"/"bearer"/…).
18
+ if (!value || !/^Bearer /i.test(value)) return false;
19
+
20
+ const provided = value.slice(7).trim(); // "Bearer ".length === 7
21
+ return constantTimeEqual(provided, expected);
22
+ }
23
+
24
+ /**
25
+ * Startup configuration check (called once from the HTTP transport factory): the
26
+ * bearer transport is unusable without a token — an unset token fail-closes and
27
+ * silently denies every request. Throw at startup so a missing secret is a loud,
28
+ * immediate error rather than a confusing wall of 401s.
29
+ */
30
+ export function assertConfigured(): void {
31
+ if (!process.env.MCP_BEARER_TOKEN) {
32
+ throw new Error(
33
+ "Refusing to start: MCP_AUTH_MODE=bearer requires MCP_BEARER_TOKEN to be set " +
34
+ "(an unset token denies every request).",
35
+ );
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Length-checked constant-time string compare. `timingSafeEqual` throws on a
41
+ * length mismatch, so the length guard runs first (token length is not
42
+ * meaningfully secret); equal-length tokens are then compared without an
43
+ * early-exit timing side channel.
44
+ */
45
+ function constantTimeEqual(a: string, b: string): boolean {
46
+ const aBuf = Buffer.from(a, "utf8");
47
+ const bBuf = Buffer.from(b, "utf8");
48
+ return aBuf.length === bBuf.length && timingSafeEqual(aBuf, bBuf);
49
+ }
@@ -0,0 +1,50 @@
1
+ import { describe, it, afterEach } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import type { IncomingMessage } from "node:http";
4
+ import { authenticate, assertConfigured } from "./oauth.js";
5
+
6
+ function reqWith(authorization?: string): IncomingMessage {
7
+ return {
8
+ headers: authorization ? { authorization } : {},
9
+ } as IncomingMessage;
10
+ }
11
+
12
+ describe("oauth authenticate (scaffold — fail closed)", () => {
13
+ const original = process.env.MCP_OAUTH_ISSUER_URL;
14
+ afterEach(() => {
15
+ if (original === undefined) delete process.env.MCP_OAUTH_ISSUER_URL;
16
+ else process.env.MCP_OAUTH_ISSUER_URL = original;
17
+ });
18
+
19
+ it("denies when the issuer URL is unset", async () => {
20
+ delete process.env.MCP_OAUTH_ISSUER_URL;
21
+ assert.equal(await authenticate(reqWith("Bearer token")), false);
22
+ });
23
+
24
+ it("denies until real verification is wired (fail-closed default)", async () => {
25
+ // The scaffold returns false even for a well-formed bearer until you
26
+ // implement issuer verification — see auth/oauth.ts. This test documents
27
+ // that contract; replace it once verification lands.
28
+ process.env.MCP_OAUTH_ISSUER_URL = "https://issuer.example.com";
29
+ assert.equal(await authenticate(reqWith("Bearer token")), false);
30
+ assert.equal(await authenticate(reqWith(undefined)), false);
31
+ });
32
+ });
33
+
34
+ describe("oauth assertConfigured", () => {
35
+ const original = process.env.MCP_OAUTH_ISSUER_URL;
36
+ afterEach(() => {
37
+ if (original === undefined) delete process.env.MCP_OAUTH_ISSUER_URL;
38
+ else process.env.MCP_OAUTH_ISSUER_URL = original;
39
+ });
40
+
41
+ it("throws at startup when MCP_OAUTH_ISSUER_URL is unset", () => {
42
+ delete process.env.MCP_OAUTH_ISSUER_URL;
43
+ assert.throws(() => assertConfigured(), /MCP_OAUTH_ISSUER_URL/);
44
+ });
45
+
46
+ it("passes when MCP_OAUTH_ISSUER_URL is set", () => {
47
+ process.env.MCP_OAUTH_ISSUER_URL = "https://issuer.example.com";
48
+ assert.doesNotThrow(() => assertConfigured());
49
+ });
50
+ });
@@ -0,0 +1,53 @@
1
+ // @hexagen-server-only
2
+ import type { IncomingMessage } from "node:http";
3
+
4
+ /**
5
+ * OAuth resource-server authentication for the HTTP transport (SCAFFOLD).
6
+ *
7
+ * Validate the incoming bearer token as an access token issued by your OAuth
8
+ * provider (`MCP_OAUTH_ISSUER_URL`): verify the JWT signature against the
9
+ * issuer's JWKS, then check the audience and any required scopes. This is left
10
+ * as a deliberate scaffold because the issuer, audience, and scope policy are
11
+ * project-specific.
12
+ *
13
+ * Fail-closed: returns false until you wire real verification — an unconfigured
14
+ * OAuth deployment denies every request rather than allowing them.
15
+ *
16
+ * Recommended verifier — `jose` (`npm i jose`):
17
+ *
18
+ * import { createRemoteJWKSet, jwtVerify } from "jose";
19
+ * const JWKS = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`));
20
+ * const { payload } = await jwtVerify(token, JWKS, {
21
+ * issuer,
22
+ * audience: "<your-mcp-server-audience>",
23
+ * });
24
+ * return hasRequiredScopes(payload.scope);
25
+ */
26
+ export async function authenticate(req: IncomingMessage): Promise<boolean> {
27
+ const issuer = process.env.MCP_OAUTH_ISSUER_URL;
28
+ if (!issuer) return false; // fail closed — issuer unset = deny all
29
+
30
+ const header = req.headers.authorization;
31
+ const value = Array.isArray(header) ? header[0] : header;
32
+ // RFC 7235 §2.1: the auth-scheme name is case-insensitive.
33
+ if (!value || !/^Bearer /i.test(value)) return false;
34
+
35
+ // const token = value.slice(7).trim(); // "Bearer ".length === 7
36
+ // TODO: verify `token` against the issuer JWKS (see the jose snippet above)
37
+ // and return true only for a valid token carrying the required scopes.
38
+ return false; // <- replace with real verification; fail-closed until then
39
+ }
40
+
41
+ /**
42
+ * Startup configuration check (called once from the HTTP transport factory):
43
+ * OAuth verification needs the issuer URL. Throw at startup so a missing issuer
44
+ * is a loud error rather than a silent deny-all. (Even when configured, this
45
+ * scaffold denies until you implement verification above.)
46
+ */
47
+ export function assertConfigured(): void {
48
+ if (!process.env.MCP_OAUTH_ISSUER_URL) {
49
+ throw new Error(
50
+ "Refusing to start: MCP_AUTH_MODE=oauth requires MCP_OAUTH_ISSUER_URL to be set.",
51
+ );
52
+ }
53
+ }