create-stitchkit 0.6.23 → 0.8.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/CHANGELOG.md +58 -0
  2. package/README.md +9 -1
  3. package/UPGRADING.md +93 -17
  4. package/dist/cli.js +82 -57
  5. package/examples/repository/packages/backend/src/surface.snapshot.json +175 -88
  6. package/examples/repository/project.json +0 -1
  7. package/examples/repository/scripts/runtime-smoke.ts +156 -126
  8. package/package.json +7 -4
  9. package/template/README.md +12 -2
  10. package/template/_gitignore +1 -0
  11. package/template/bun.lock +5 -10
  12. package/template/docs/ADDING_A_FEATURE.md +21 -7
  13. package/template/package.json +3 -3
  14. package/template/packages/backend/package.json +0 -1
  15. package/template/packages/backend/src/cli.ts +3 -2
  16. package/template/packages/backend/src/index.ts +6 -3
  17. package/template/packages/backend/src/surface.snapshot.json +90 -50
  18. package/template/packages/backend/src/tools.ts +1 -1
  19. package/template/packages/config/package.json +0 -1
  20. package/template/packages/config/src/app-identity.generated.ts +0 -1
  21. package/template/packages/config/src/declaration.ts +10 -0
  22. package/template/packages/db/package.json +0 -1
  23. package/template/packages/frontend/package.json +1 -2
  24. package/template/packages/shared/package.json +0 -1
  25. package/template/project.json +0 -1
  26. package/template/scripts/acceptance-environment.test.ts +59 -0
  27. package/template/scripts/acceptance-environment.ts +52 -0
  28. package/template/scripts/acceptance-local.ts +8 -28
  29. package/template/scripts/declaration.ts +4 -87
  30. package/template/scripts/env-variables.ts +83 -0
  31. package/template/scripts/runtime-smoke.test.ts +49 -0
  32. package/template/scripts/runtime-smoke.ts +2 -2
  33. package/template/scripts/surface-snapshot.ts +135 -14
  34. package/templates/agent/package.json +2 -2
  35. package/templates/agent/project.json +0 -1
  36. package/templates/agent/src/runtime.ts +1 -1
  37. package/templates/telegram-bot/package.json +1 -1
  38. package/templates/telegram-bot/project.json +0 -1
  39. package/template/.data/board.sqlite +0 -0
  40. package/template/packages/backend/src/surface-manifest.test.ts +0 -237
  41. package/template/packages/backend/src/surface-manifest.ts +0 -220
  42. package/template/scripts/surface-conformance.ts +0 -173
@@ -1,237 +0,0 @@
1
- import { describe, expect, test } from 'bun:test';
2
- import { readFile } from 'node:fs/promises';
3
- import { join } from 'node:path';
4
- import { createContractFactory } from 'stitchkit/contract';
5
- import { generateOpenApiDocument, implement } from 'stitchkit/server';
6
- import { z } from 'zod';
7
- import { discoverCliCommands, discoverMcpTools } from '../../../scripts/surface-conformance';
8
- import {
9
- assertManifestMatchesSnapshot,
10
- assertSurfaceConformance,
11
- buildSurfaceManifest,
12
- } from './surface-manifest';
13
-
14
- const NoteParamsSchema = z.object({ id: z.string() });
15
- const NoteSchema = z.object({ id: z.string() });
16
- // Same address and presence flags as NoteSchema — a different TYPE, for the
17
- // snapshot-digest test. Named here, never inline in a contract (the template's
18
- // own schema-separate-from-contract policy).
19
- const RetypedNoteSchema = z.object({ id: z.number() });
20
- const { defineContract } = createContractFactory<'public'>();
21
-
22
- const service = implement(
23
- defineContract(
24
- { prefix: 'notes', scope: 'public' },
25
- {
26
- read: {
27
- method: 'GET',
28
- path: '/:id',
29
- desc: 'Read a note',
30
- params: NoteParamsSchema,
31
- output: NoteSchema,
32
- expose: ['HTTP', 'MCP', 'AGENT', 'CLI'],
33
- },
34
- },
35
- ),
36
- { read: ({ params }) => ({ id: params.id }) },
37
- );
38
-
39
- describe('surface conformance', () => {
40
- test('derives matching HTTP and MCP discovery identities without calling handlers', () => {
41
- const manifest = buildSurfaceManifest([service]);
42
- const openApi = generateOpenApiDocument({
43
- info: { title: 'Test', version: '1.0.0' },
44
- groups: [{ pathPrefix: '/api', services: [service] }],
45
- });
46
- expect(manifest).toEqual([
47
- {
48
- service: 'notes',
49
- action: 'read',
50
- scope: 'public',
51
- hasInput: false,
52
- hasOutput: true,
53
- inputShape: null,
54
- outputShape: expect.stringMatching(/^[0-9a-f]{16}$/),
55
- http: [{ method: 'GET', path: '/api/notes/{id}' }],
56
- tools: { AGENT: 'read_note', CLI: 'read_note', MCP: 'read_note' },
57
- },
58
- ]);
59
- expect(() =>
60
- assertSurfaceConformance({
61
- manifest,
62
- openApi,
63
- mcpToolNames: ['read_note'],
64
- agentToolNames: ['read_note'],
65
- cliToolNames: ['read_note'],
66
- }),
67
- ).not.toThrow();
68
- });
69
-
70
- test('fails with transport-specific expected and actual diagnostics', () => {
71
- const manifest = buildSurfaceManifest([service]);
72
- expect(() =>
73
- assertSurfaceConformance({
74
- manifest,
75
- openApi: { paths: {} },
76
- mcpToolNames: [],
77
- agentToolNames: [],
78
- cliToolNames: [],
79
- }),
80
- ).toThrow('HTTP/OpenAPI surface mismatch');
81
- expect(() =>
82
- assertSurfaceConformance({
83
- manifest: manifest.map((operation) => ({ ...operation, http: [] })),
84
- openApi: { paths: {} },
85
- mcpToolNames: ['unexpected'],
86
- agentToolNames: ['read_note'],
87
- cliToolNames: ['read_note'],
88
- }),
89
- ).toThrow('MCP discovery surface mismatch');
90
- });
91
-
92
- test('missing Stitchkit metadata is an ERROR unless the standard-document mode is declared', () => {
93
- const manifest = buildSurfaceManifest([service]);
94
- const standardDocument = {
95
- paths: {
96
- '/api/notes/{id}': {
97
- get: { responses: { 200: { description: 'Success' } } },
98
- },
99
- },
100
- };
101
- const names = {
102
- mcpToolNames: ['read_note'],
103
- agentToolNames: ['read_note'],
104
- cliToolNames: ['read_note'],
105
- };
106
- // Without x-stitchkit-* metadata there is nothing to compare. The default
107
- // mode rejects the document; opting out is an explicit decision.
108
- expect(() =>
109
- assertSurfaceConformance({ manifest, openApi: standardDocument, ...names }),
110
- ).toThrow(/no x-stitchkit-\* contract metadata/);
111
- expect(() =>
112
- assertSurfaceConformance({
113
- manifest,
114
- openApi: standardDocument,
115
- ...names,
116
- metadata: 'ignore',
117
- }),
118
- ).not.toThrow();
119
- });
120
-
121
- test('a missing AGENT tool and a missing CLI command each fail conformance', () => {
122
- const manifest = buildSurfaceManifest([service]);
123
- const openApi = generateOpenApiDocument({
124
- info: { title: 'Test', version: '1.0.0' },
125
- groups: [{ pathPrefix: '/api', services: [service] }],
126
- });
127
- expect(() =>
128
- assertSurfaceConformance({
129
- manifest,
130
- openApi,
131
- mcpToolNames: ['read_note'],
132
- agentToolNames: [],
133
- cliToolNames: ['read_note'],
134
- }),
135
- ).toThrow('AGENT mount surface mismatch');
136
- expect(() =>
137
- assertSurfaceConformance({
138
- manifest,
139
- openApi,
140
- mcpToolNames: ['read_note'],
141
- agentToolNames: ['read_note'],
142
- cliToolNames: [],
143
- }),
144
- ).toThrow('CLI manifest surface mismatch');
145
- });
146
-
147
- test('the committed snapshot catches an expose edit that moves BOTH in-process sides together', () => {
148
- // Removing AGENT/CLI from `expose`
149
- // changes the manifest AND the in-process tool lists in lockstep. The
150
- // snapshot is the anchor that does not move with the source.
151
- const snapshot = buildSurfaceManifest([service]);
152
- const narrowed = implement(
153
- defineContract(
154
- { prefix: 'notes', scope: 'public' },
155
- {
156
- read: {
157
- method: 'GET',
158
- path: '/:id',
159
- desc: 'Read a note',
160
- params: NoteParamsSchema,
161
- output: NoteSchema,
162
- expose: ['HTTP', 'MCP'],
163
- },
164
- },
165
- ),
166
- { read: ({ params }) => ({ id: params.id }) },
167
- );
168
- expect(() =>
169
- assertManifestMatchesSnapshot(buildSurfaceManifest([narrowed]), snapshot),
170
- ).toThrow(/diverged from the committed snapshot/);
171
- expect(() =>
172
- assertManifestMatchesSnapshot(buildSurfaceManifest([service]), snapshot),
173
- ).not.toThrow();
174
- });
175
-
176
- test('a schema TYPE change at the same method and path flips the shape digest', () => {
177
- const snapshot = buildSurfaceManifest([service]);
178
- const retyped = implement(
179
- defineContract(
180
- { prefix: 'notes', scope: 'public' },
181
- {
182
- read: {
183
- method: 'GET',
184
- path: '/:id',
185
- desc: 'Read a note',
186
- params: NoteParamsSchema,
187
- // Same address, same presence flags — different output TYPE.
188
- output: RetypedNoteSchema,
189
- expose: ['HTTP', 'MCP', 'AGENT', 'CLI'],
190
- },
191
- },
192
- ),
193
- { read: ({ params }) => ({ id: Number(params.id) }) },
194
- );
195
- expect(() =>
196
- assertManifestMatchesSnapshot(buildSurfaceManifest([retyped]), snapshot),
197
- ).toThrow(/diverged from the committed snapshot/);
198
- });
199
-
200
- test('fails first on duplicate contract identity', () => {
201
- expect(() => buildSurfaceManifest([service, service])).toThrow(
202
- 'Duplicate operation identity notes.read',
203
- );
204
- });
205
-
206
- test('a broken /mcp endpoint rejects discovery — even when zero tools are expected', async () => {
207
- const broken = Bun.serve({
208
- port: 0,
209
- fetch: () => new Response('not the MCP endpoint', { status: 404 }),
210
- });
211
- try {
212
- await expect(discoverMcpTools(`http://127.0.0.1:${broken.port}`, [])).rejects.toThrow();
213
- } finally {
214
- broken.stop(true);
215
- }
216
- });
217
-
218
- test('the CLI surface observed from the SPAWNED process matches the committed snapshot', async () => {
219
- // External observation against the external anchor — neither side is the
220
- // in-process `services` object, so they cannot move together.
221
- const root = join(import.meta.dir, '../../..');
222
- const commands = await discoverCliCommands(root);
223
- const snapshot = SurfaceSnapshotCliSchema.parse(
224
- JSON.parse(
225
- await readFile(join(root, 'packages/backend/src/surface.snapshot.json'), 'utf8'),
226
- ),
227
- );
228
- const expected = snapshot
229
- .flatMap((operation) => (operation.tools.CLI ? [operation.tools.CLI] : []))
230
- .sort();
231
- expect([...commands].sort()).toEqual(expected);
232
- });
233
- });
234
-
235
- const SurfaceSnapshotCliSchema = z.array(
236
- z.object({ tools: z.object({ CLI: z.string().optional() }) }),
237
- );
@@ -1,220 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import type { HttpMethod } from 'stitchkit/contract';
3
- import type { OpenApiDocument, ServiceDef } from 'stitchkit/server';
4
- import { listToolNames } from 'stitchkit/tools';
5
- import { z } from 'zod';
6
-
7
- export interface SurfaceManifestOperation {
8
- service: string;
9
- action: string;
10
- scope: string;
11
- hasInput: boolean;
12
- hasOutput: boolean;
13
- /** Digest of the input JSON Schema — a TYPE change flips it, not just presence. */
14
- inputShape: string | null;
15
- /** Digest of the output JSON Schema. */
16
- outputShape: string | null;
17
- http: Array<{ method: HttpMethod; path: string }>;
18
- tools: Partial<Record<'MCP' | 'AGENT' | 'CLI', string>>;
19
- }
20
-
21
- function schemaShape(schema: z.ZodType | undefined, io: 'input' | 'output'): string | null {
22
- if (!schema) return null;
23
- const document = z.toJSONSchema(schema, { io, unrepresentable: 'any' });
24
- return createHash('sha256').update(JSON.stringify(document)).digest('hex').slice(0, 16);
25
- }
26
-
27
- function joinPath(...parts: Array<string | undefined>): string {
28
- const joined = parts
29
- .filter((part): part is string => Boolean(part))
30
- .map((part) => part.replace(/^\/+|\/+$/g, ''))
31
- .filter(Boolean)
32
- .join('/');
33
- return `/${joined}`;
34
- }
35
-
36
- function operationKey(service: string, action: string): string {
37
- return `${service}\u0000${action}`;
38
- }
39
-
40
- function sorted(values: Iterable<string>): string[] {
41
- return [...values].sort((left, right) => left.localeCompare(right));
42
- }
43
-
44
- function assertSameSet(
45
- label: string,
46
- expectedValues: Iterable<string>,
47
- actualValues: Iterable<string>,
48
- ) {
49
- const expected = sorted(expectedValues);
50
- const actual = sorted(actualValues);
51
- if (
52
- expected.length === actual.length &&
53
- expected.every((value, index) => value === actual[index])
54
- ) {
55
- return;
56
- }
57
- throw new Error(
58
- `${label} surface mismatch\nexpected: ${expected.join(', ') || '(empty)'}\nactual: ${actual.join(', ') || '(empty)'}`,
59
- );
60
- }
61
-
62
- export function buildSurfaceManifest(
63
- services: readonly ServiceDef[],
64
- pathPrefix = '/api',
65
- ): SurfaceManifestOperation[] {
66
- const operations = new Map<string, SurfaceManifestOperation>();
67
- for (const service of services) {
68
- for (const method of Object.values(service.methods)) {
69
- const key = operationKey(service.name, method.key);
70
- if (operations.has(key)) {
71
- throw new Error(`Duplicate operation identity ${service.name}.${method.key}`);
72
- }
73
- operations.set(key, {
74
- service: service.name,
75
- action: method.key,
76
- scope: method.scope ?? service.scope,
77
- hasInput: Boolean(method.inputSchema),
78
- hasOutput: Boolean(method.outputSchema),
79
- inputShape: schemaShape(method.inputSchema, 'input'),
80
- outputShape: schemaShape(method.outputSchema, 'output'),
81
- http:
82
- !method.expose || method.expose.includes('HTTP')
83
- ? [
84
- {
85
- method: method.method,
86
- path: joinPath(pathPrefix, service.prefix, method.path).replace(
87
- /:([^/]+)/g,
88
- '{$1}',
89
- ),
90
- },
91
- ]
92
- : [],
93
- tools: {},
94
- });
95
- }
96
- }
97
- for (const tool of listToolNames({ services })) {
98
- const operation = operations.get(operationKey(tool.service, tool.method));
99
- if (!operation) {
100
- throw new Error(`Tool ${tool.name} has no contract identity`);
101
- }
102
- for (const transport of tool.transports) {
103
- if (transport !== 'HTTP') operation.tools[transport] = tool.name;
104
- }
105
- }
106
- return [...operations.values()].sort(
107
- (left, right) =>
108
- left.service.localeCompare(right.service) || left.action.localeCompare(right.action),
109
- );
110
- }
111
-
112
- /**
113
- * Compare the LIVE manifest against the committed snapshot — the external
114
- * anchor that a source-level change (an `expose` edit, a schema type change, a
115
- * scope change) cannot move along with itself. Regenerate deliberately with
116
- * `bun run surface:snapshot` and review the diff.
117
- */
118
- export function assertManifestMatchesSnapshot(
119
- manifest: readonly SurfaceManifestOperation[],
120
- snapshot: readonly SurfaceManifestOperation[],
121
- ): void {
122
- const actual = JSON.stringify(manifest, null, 2);
123
- const expected = JSON.stringify(snapshot, null, 2);
124
- if (actual !== expected) {
125
- throw new Error(
126
- `Declared surface diverged from the committed snapshot — if the change is intended, regenerate it with "bun run surface:snapshot" and review the diff.\nsnapshot: ${expected}\nactual: ${actual}`,
127
- );
128
- }
129
- }
130
-
131
- export function assertSurfaceConformance({
132
- manifest,
133
- openApi,
134
- mcpToolNames,
135
- agentToolNames,
136
- cliToolNames,
137
- metadata = 'require',
138
- }: {
139
- manifest: readonly SurfaceManifestOperation[];
140
- openApi: Pick<OpenApiDocument, 'paths'>;
141
- mcpToolNames: readonly string[];
142
- agentToolNames: readonly string[];
143
- cliToolNames: readonly string[];
144
- /**
145
- * `'require'` (default) — the OpenAPI document must carry `x-stitchkit-*`
146
- * metadata and it is compared; `'ignore'` — an explicitly declared mode for
147
- * standard documents. A silent skip is not an option.
148
- */
149
- metadata?: 'require' | 'ignore';
150
- }): void {
151
- const openApiOperations = Object.entries(openApi.paths).flatMap(([path, item]) =>
152
- Object.entries(item)
153
- .filter(([method]) => ['get', 'post', 'put', 'patch', 'delete', 'head'].includes(method))
154
- .map(([method, operation]) => ({ method: method.toUpperCase(), path, operation })),
155
- );
156
- assertSameSet(
157
- 'HTTP/OpenAPI',
158
- manifest.flatMap((operation) =>
159
- operation.http.map((entry) => `${entry.method}:${entry.path}`),
160
- ),
161
- openApiOperations.map(({ method, path }) => `${method}:${path}`),
162
- );
163
- const carriesContractMetadata = openApiOperations.some(({ operation }) =>
164
- OpenApiOperationMetadataPresenceSchema.parse(operation),
165
- );
166
- if (metadata === 'require' && openApiOperations.length > 0 && !carriesContractMetadata) {
167
- throw new Error(
168
- 'OpenAPI document carries no x-stitchkit-* contract metadata — pass metadata: "ignore" only for a deliberately standard document',
169
- );
170
- }
171
- if (metadata === 'require' && carriesContractMetadata) {
172
- assertSameSet(
173
- 'HTTP/OpenAPI contract metadata',
174
- manifest.flatMap((operation) =>
175
- operation.http.map(
176
- (entry) =>
177
- `${entry.method}:${entry.path}:${operation.scope}:${operation.hasInput}:${operation.hasOutput}`,
178
- ),
179
- ),
180
- openApiOperations.map(({ method, path, operation }) => {
181
- const metadata = OpenApiOperationMetadataSchema.parse(operation);
182
- return `${method}:${path}:${metadata['x-stitchkit-scope']}:${metadata['x-stitchkit-has-input']}:${metadata['x-stitchkit-has-output']}`;
183
- }),
184
- );
185
- }
186
- assertSameSet(
187
- 'MCP discovery',
188
- manifest.flatMap((operation) => (operation.tools.MCP ? [operation.tools.MCP] : [])),
189
- mcpToolNames,
190
- );
191
- assertSameSet(
192
- 'AGENT mount',
193
- manifest.flatMap((operation) => (operation.tools.AGENT ? [operation.tools.AGENT] : [])),
194
- agentToolNames,
195
- );
196
- assertSameSet(
197
- 'CLI manifest',
198
- manifest.flatMap((operation) => (operation.tools.CLI ? [operation.tools.CLI] : [])),
199
- cliToolNames,
200
- );
201
- }
202
-
203
- const OpenApiOperationMetadataSchema = z.object({
204
- 'x-stitchkit-scope': z.string(),
205
- 'x-stitchkit-has-input': z.boolean(),
206
- 'x-stitchkit-has-output': z.boolean(),
207
- });
208
-
209
- const OpenApiOperationMetadataPresenceSchema = z
210
- .object({
211
- 'x-stitchkit-scope': z.unknown().optional(),
212
- 'x-stitchkit-has-input': z.unknown().optional(),
213
- 'x-stitchkit-has-output': z.unknown().optional(),
214
- })
215
- .transform(
216
- (metadata) =>
217
- metadata['x-stitchkit-scope'] !== undefined ||
218
- metadata['x-stitchkit-has-input'] !== undefined ||
219
- metadata['x-stitchkit-has-output'] !== undefined,
220
- );
@@ -1,173 +0,0 @@
1
- import { readFile } from 'node:fs/promises';
2
- import { join } from 'node:path';
3
- import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
4
- import { mountAgent } from 'stitchkit/tools/agent';
5
- import { z } from 'zod';
6
- import { createSurface } from '../packages/backend/src/surface';
7
- import {
8
- assertManifestMatchesSnapshot,
9
- assertSurfaceConformance,
10
- buildSurfaceManifest,
11
- type SurfaceManifestOperation,
12
- } from '../packages/backend/src/surface-manifest';
13
-
14
- export const SURFACE_SNAPSHOT_PATH = 'packages/backend/src/surface.snapshot.json';
15
-
16
- export interface SurfaceProbe {
17
- name: string;
18
- run: () => Promise<void>;
19
- }
20
-
21
- export function defineSurfaceProbe<TInput, TOutput>({
22
- name,
23
- input,
24
- fixture,
25
- output,
26
- run,
27
- }: {
28
- name: string;
29
- input: z.ZodType<TInput>;
30
- fixture: unknown;
31
- output?: z.ZodType<TOutput>;
32
- run: (input: TInput) => Promise<TOutput>;
33
- }): SurfaceProbe {
34
- return {
35
- name,
36
- run: async () => {
37
- const result = await run(input.parse(fixture));
38
- output?.parse(result);
39
- },
40
- };
41
- }
42
-
43
- interface SurfaceConformanceOptions {
44
- apiOrigin: string;
45
- probes?: readonly SurfaceProbe[];
46
- }
47
-
48
- async function readJson(url: string): Promise<unknown> {
49
- const response = await fetch(url, { signal: AbortSignal.timeout(30_000) });
50
- if (!response.ok) throw new Error(`GET ${url} returned ${response.status}`);
51
- return response.json();
52
- }
53
-
54
- /**
55
- * Observe the CLI surface EXTERNALLY — spawn the real CLI process and parse
56
- * its command table, instead of re-deriving the list from the same in-process
57
- * `services` the manifest was built from (which could only ever agree).
58
- */
59
- export async function discoverCliCommands(root = process.cwd()): Promise<string[]> {
60
- const child = Bun.spawn({
61
- cmd: ['bun', 'packages/backend/src/cli.ts', '--help'],
62
- cwd: root,
63
- stdout: 'pipe',
64
- stderr: 'pipe',
65
- });
66
- const [output, errors, exitCode] = await Promise.all([
67
- new Response(child.stdout).text(),
68
- new Response(child.stderr).text(),
69
- child.exited,
70
- ]);
71
- if (exitCode !== 0) {
72
- throw new Error(`CLI --help exited with ${exitCode}: ${errors || output}`);
73
- }
74
- const lines = output.split('\n');
75
- const start = lines.findIndex((line) => line.trim() === 'Commands:');
76
- if (start === -1) throw new Error('CLI --help output carries no "Commands:" section');
77
- const commands: string[] = [];
78
- for (const line of lines.slice(start + 1)) {
79
- if (!line.startsWith(' ')) break;
80
- const name = line.trim().split(/\s+/)[0];
81
- if (name) commands.push(name);
82
- }
83
- return commands;
84
- }
85
-
86
- export async function discoverMcpTools(
87
- apiOrigin: string,
88
- _manifest: readonly SurfaceManifestOperation[],
89
- ): Promise<string[]> {
90
- const client = new Client(
91
- { name: 'surface-conformance', version: '1.0.0' },
92
- { versionNegotiation: { mode: { pin: '2026-07-28' } } },
93
- );
94
- const transport = new StreamableHTTPClientTransport(new URL(`${apiOrigin}/mcp`));
95
- try {
96
- await client.connect(transport);
97
- // Ask the server what it HAS before asking it to list it. A server exposing
98
- // no MCP tool advertises no `tools` capability, and calling `listTools()`
99
- // anyway makes the vendor client log a debug line — noise printed on every
100
- // green run of a gate whose whole output is one line — to return the empty
101
- // list the capability already stated. The absence is still observed here,
102
- // and a manifest that claims an MCP tool still fails against it.
103
- if (!client.getServerCapabilities()?.tools) return [];
104
- return (await client.listTools()).tools.map((tool) => tool.name);
105
- } finally {
106
- await client.close();
107
- }
108
- }
109
-
110
- export async function runSurfaceConformance({
111
- apiOrigin,
112
- probes = [],
113
- }: SurfaceConformanceOptions): Promise<void> {
114
- const { services, socket } = await createSurface();
115
- try {
116
- const manifest = buildSurfaceManifest(services);
117
- // The committed snapshot is the anchor no source edit can move along with
118
- // itself: removing a transport from `expose` changes the live manifest but
119
- // not the snapshot, so the lane fails until the snapshot is deliberately
120
- // regenerated and reviewed.
121
- const snapshot = SurfaceSnapshotSchema.parse(
122
- JSON.parse(await readFile(join(process.cwd(), SURFACE_SNAPSHOT_PATH), 'utf8')),
123
- );
124
- assertManifestMatchesSnapshot(manifest, snapshot);
125
- const openApi = await readJson(`${apiOrigin}/openapi.json`);
126
- const mcpToolNames = await discoverMcpTools(apiOrigin, manifest);
127
- assertSurfaceConformance({
128
- manifest,
129
- openApi: OpenApiSnapshotSchema.parse(openApi),
130
- mcpToolNames,
131
- // AGENT has no external process to observe — it is anchored by the
132
- // snapshot above; CLI is observed by spawning the real CLI.
133
- agentToolNames: Object.keys(mountAgent(services)),
134
- cliToolNames: await discoverCliCommands(),
135
- });
136
- for (const probe of probes) {
137
- try {
138
- await probe.run();
139
- } catch (cause) {
140
- throw new Error(`Surface probe "${probe.name}" failed`, { cause });
141
- }
142
- }
143
- } finally {
144
- await socket.close();
145
- }
146
- }
147
-
148
- const OpenApiSnapshotSchema = z.object({
149
- paths: z.record(z.string(), z.record(z.string(), z.unknown())),
150
- });
151
-
152
- const SurfaceSnapshotSchema: z.ZodType<SurfaceManifestOperation[]> = z.array(
153
- z.object({
154
- service: z.string(),
155
- action: z.string(),
156
- scope: z.string(),
157
- hasInput: z.boolean(),
158
- hasOutput: z.boolean(),
159
- inputShape: z.string().nullable(),
160
- outputShape: z.string().nullable(),
161
- http: z.array(
162
- z.object({
163
- method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD']),
164
- path: z.string(),
165
- }),
166
- ),
167
- tools: z.object({
168
- MCP: z.string().optional(),
169
- AGENT: z.string().optional(),
170
- CLI: z.string().optional(),
171
- }),
172
- }),
173
- );