@kirrosh/zond 0.9.4 → 0.11.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kirrosh/zond",
3
- "version": "0.9.4",
3
+ "version": "0.11.0",
4
4
  "description": "API testing platform — define tests in YAML, run from CLI or WebUI, generate from OpenAPI specs",
5
5
  "license": "MIT",
6
6
  "module": "index.ts",
@@ -12,3 +12,4 @@ export { compressEndpointsWithSchemas, buildGenerationGuide } from "./guide-buil
12
12
  export type { GuideOptions } from "./guide-builder.ts";
13
13
  export type { EndpointWarning, WarningCode } from "./endpoint-warnings.ts";
14
14
  export type { EndpointInfo, ResponseInfo, GenerateOptions, SecuritySchemeInfo, CrudGroup } from "./types.ts";
15
+ export { generateSuites, generateStep, detectCrudGroups, generateCrudSuite } from "./suite-generator.ts";
@@ -34,6 +34,7 @@ export interface RawStep {
34
34
 
35
35
  export interface RawSuite {
36
36
  name: string;
37
+ tags?: string[];
37
38
  folder?: string;
38
39
  fileStem?: string;
39
40
  base_url?: string;
@@ -48,6 +49,9 @@ export interface RawSuite {
48
49
  export function serializeSuite(suite: RawSuite): string {
49
50
  const lines: string[] = [];
50
51
  lines.push(`name: ${yamlScalar(suite.name)}`);
52
+ if (suite.tags && suite.tags.length > 0) {
53
+ lines.push(`tags: [${suite.tags.join(", ")}]`);
54
+ }
51
55
  if (suite.base_url) {
52
56
  lines.push(`base_url: ${yamlScalar(suite.base_url)}`);
53
57
  }
@@ -0,0 +1,388 @@
1
+ import type { OpenAPIV3 } from "openapi-types";
2
+ import type { EndpointInfo, SecuritySchemeInfo, CrudGroup } from "./types.ts";
3
+ import type { RawSuite, RawStep } from "./serializer.ts";
4
+ import { generateFromSchema } from "./data-factory.ts";
5
+ import { groupEndpointsByTag } from "./chunker.ts";
6
+
7
+ // ──────────────────────────────────────────────
8
+ // Helpers
9
+ // ──────────────────────────────────────────────
10
+
11
+ /** Convert OpenAPI path params {param} to test interpolation {{param}} */
12
+ function convertPath(path: string): string {
13
+ return path.replace(/\{([^}]+)\}/g, "{{$1}}");
14
+ }
15
+
16
+ function slugify(s: string): string {
17
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
18
+ }
19
+
20
+ function escapeRegex(s: string): string {
21
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
22
+ }
23
+
24
+ function getExpectedStatus(ep: EndpointInfo): number {
25
+ const success = ep.responses.find(r => r.statusCode >= 200 && r.statusCode < 300);
26
+ if (success) return success.statusCode;
27
+ if (ep.responses.length > 0) return ep.responses[0].statusCode;
28
+ return 200;
29
+ }
30
+
31
+ function getSuccessSchema(ep: EndpointInfo): OpenAPIV3.SchemaObject | undefined {
32
+ return ep.responses.find(r => r.statusCode >= 200 && r.statusCode < 300)?.schema;
33
+ }
34
+
35
+ function getBodyAssertions(ep: EndpointInfo): Record<string, Record<string, string>> | undefined {
36
+ const schema = getSuccessSchema(ep);
37
+ if (!schema) return undefined;
38
+
39
+ if (schema.type === "array") {
40
+ return { _body: { type: "array" } };
41
+ }
42
+
43
+ if (schema.properties) {
44
+ const assertions: Record<string, Record<string, string>> = {};
45
+ const props = Object.keys(schema.properties).slice(0, 5);
46
+ for (const prop of props) {
47
+ assertions[prop] = { exists: "true" };
48
+ }
49
+ return Object.keys(assertions).length > 0 ? assertions : undefined;
50
+ }
51
+
52
+ return undefined;
53
+ }
54
+
55
+ function getAuthHeaders(
56
+ ep: EndpointInfo,
57
+ schemes: SecuritySchemeInfo[],
58
+ ): Record<string, string> | undefined {
59
+ if (ep.security.length === 0) return undefined;
60
+
61
+ for (const secName of ep.security) {
62
+ const scheme = schemes.find(s => s.name === secName);
63
+ if (!scheme) continue;
64
+
65
+ if (scheme.type === "http" && scheme.scheme === "bearer") {
66
+ return { Authorization: "Bearer {{auth_token}}" };
67
+ }
68
+ if (scheme.type === "apiKey" && scheme.in === "header" && scheme.apiKeyName) {
69
+ return { [scheme.apiKeyName]: "{{api_key}}" };
70
+ }
71
+ }
72
+
73
+ return undefined;
74
+ }
75
+
76
+ function getRequiredQueryParams(ep: EndpointInfo): Record<string, unknown> | undefined {
77
+ const queryParams = ep.parameters.filter(p => p.in === "query" && p.required);
78
+ if (queryParams.length === 0) return undefined;
79
+
80
+ const query: Record<string, unknown> = {};
81
+ for (const p of queryParams) {
82
+ if (p.schema) {
83
+ query[p.name] = generateFromSchema(p.schema as OpenAPIV3.SchemaObject, p.name);
84
+ } else {
85
+ query[p.name] = "{{$randomString}}";
86
+ }
87
+ }
88
+ return query;
89
+ }
90
+
91
+ /** Check if all endpoints share the same auth headers → suite-level */
92
+ function getSuiteHeaders(
93
+ endpoints: EndpointInfo[],
94
+ schemes: SecuritySchemeInfo[],
95
+ ): Record<string, string> | undefined {
96
+ if (endpoints.length === 0) return undefined;
97
+
98
+ const headerSets = endpoints.map(ep => getAuthHeaders(ep, schemes));
99
+ const first = headerSets[0];
100
+ if (!first) return undefined;
101
+
102
+ const firstJson = JSON.stringify(first);
103
+ const allSame = headerSets.every(h => JSON.stringify(h) === firstJson);
104
+ return allSame ? first : undefined;
105
+ }
106
+
107
+ /** Find the best field to capture from POST response (for CRUD chains) */
108
+ function getCaptureField(ep: EndpointInfo): string {
109
+ const schema = getSuccessSchema(ep);
110
+ if (schema?.properties) {
111
+ if ("id" in schema.properties) return "id";
112
+ for (const [name, propSchema] of Object.entries(schema.properties)) {
113
+ const s = propSchema as OpenAPIV3.SchemaObject;
114
+ if (s.type === "integer" || s.format === "uuid") return name;
115
+ }
116
+ }
117
+ return "id";
118
+ }
119
+
120
+ // ──────────────────────────────────────────────
121
+ // Public API
122
+ // ──────────────────────────────────────────────
123
+
124
+ /** Generate a single test step from an EndpointInfo */
125
+ export function generateStep(
126
+ ep: EndpointInfo,
127
+ securitySchemes: SecuritySchemeInfo[],
128
+ ): RawStep {
129
+ const method = ep.method.toUpperCase();
130
+ const name = ep.operationId ?? ep.summary ?? `${method} ${ep.path}`;
131
+ const path = convertPath(ep.path);
132
+
133
+ const step: RawStep = {
134
+ name,
135
+ [method]: path,
136
+ expect: {
137
+ status: getExpectedStatus(ep),
138
+ },
139
+ };
140
+
141
+ const authHeaders = getAuthHeaders(ep, securitySchemes);
142
+ if (authHeaders) {
143
+ step.headers = authHeaders;
144
+ }
145
+
146
+ if (["POST", "PUT", "PATCH"].includes(method) && ep.requestBodySchema) {
147
+ step.json = generateFromSchema(ep.requestBodySchema);
148
+ }
149
+
150
+ const query = getRequiredQueryParams(ep);
151
+ if (query) {
152
+ step.query = query;
153
+ }
154
+
155
+ const body = getBodyAssertions(ep);
156
+ if (body) {
157
+ step.expect.body = body;
158
+ }
159
+
160
+ return step;
161
+ }
162
+
163
+ /** Detect CRUD groups from a list of endpoints */
164
+ export function detectCrudGroups(endpoints: EndpointInfo[]): CrudGroup[] {
165
+ const groups: CrudGroup[] = [];
166
+ const postEndpoints = endpoints.filter(ep => ep.method.toUpperCase() === "POST" && !ep.deprecated);
167
+
168
+ for (const createEp of postEndpoints) {
169
+ const basePath = createEp.path;
170
+
171
+ // Find item endpoints: basePath/{param}
172
+ const itemPattern = new RegExp(`^${escapeRegex(basePath)}/\\{([^}]+)\\}$`);
173
+ const itemEndpoints = endpoints.filter(ep => !ep.deprecated && itemPattern.test(ep.path));
174
+
175
+ if (itemEndpoints.length === 0) continue;
176
+
177
+ const itemPath = itemEndpoints[0].path;
178
+ const idMatch = itemPath.match(/\{([^}]+)\}$/);
179
+ if (!idMatch) continue;
180
+ const idParam = idMatch[1];
181
+
182
+ const read = itemEndpoints.find(ep => ep.method.toUpperCase() === "GET");
183
+ if (!read) continue; // Minimum: POST + GET/{id}
184
+
185
+ const update = itemEndpoints.find(ep => ["PUT", "PATCH"].includes(ep.method.toUpperCase()));
186
+ const del = itemEndpoints.find(ep => ep.method.toUpperCase() === "DELETE");
187
+ const list = endpoints.find(ep => ep.method.toUpperCase() === "GET" && ep.path === basePath && !ep.deprecated);
188
+
189
+ const resource = basePath.split("/").filter(Boolean).pop() ?? "resource";
190
+
191
+ groups.push({
192
+ resource,
193
+ basePath,
194
+ itemPath,
195
+ idParam,
196
+ create: createEp,
197
+ list,
198
+ read,
199
+ update,
200
+ delete: del,
201
+ });
202
+ }
203
+
204
+ return groups;
205
+ }
206
+
207
+ /** Generate a CRUD chain suite from a CrudGroup */
208
+ export function generateCrudSuite(
209
+ group: CrudGroup,
210
+ securitySchemes: SecuritySchemeInfo[],
211
+ ): RawSuite {
212
+ const captureField = group.create ? getCaptureField(group.create) : "id";
213
+ const captureVar = `${group.resource.replace(/s$/, "")}_id`;
214
+ const tests: RawStep[] = [];
215
+
216
+ const allEps = [group.create, group.list, group.read, group.update, group.delete].filter(Boolean) as EndpointInfo[];
217
+ const suiteHeaders = getSuiteHeaders(allEps, securitySchemes);
218
+
219
+ // 1. Create
220
+ if (group.create) {
221
+ const step = generateStep(group.create, securitySchemes);
222
+ if (!step.expect.body) step.expect.body = {};
223
+ step.expect.body[captureField] = { capture: captureVar };
224
+ if (suiteHeaders) delete (step as any).headers;
225
+ tests.push(step);
226
+ }
227
+
228
+ // 2. Read created
229
+ if (group.read) {
230
+ const step: RawStep = {
231
+ name: group.read.operationId ?? `Read created ${group.resource.replace(/s$/, "")}`,
232
+ GET: convertPath(group.itemPath).replace(`{{${group.idParam}}}`, `{{${captureVar}}}`),
233
+ expect: {
234
+ status: getExpectedStatus(group.read),
235
+ body: getBodyAssertions(group.read),
236
+ },
237
+ };
238
+ tests.push(step);
239
+ }
240
+
241
+ // 3. Update
242
+ if (group.update) {
243
+ const method = group.update.method.toUpperCase();
244
+ const step: RawStep = {
245
+ name: group.update.operationId ?? `Update ${group.resource.replace(/s$/, "")}`,
246
+ [method]: convertPath(group.itemPath).replace(`{{${group.idParam}}}`, `{{${captureVar}}}`),
247
+ expect: {
248
+ status: getExpectedStatus(group.update),
249
+ },
250
+ };
251
+ if (group.update.requestBodySchema) {
252
+ step.json = generateFromSchema(group.update.requestBodySchema);
253
+ }
254
+ tests.push(step);
255
+ }
256
+
257
+ // 4. Delete
258
+ if (group.delete) {
259
+ const step: RawStep = {
260
+ name: group.delete.operationId ?? `Delete ${group.resource.replace(/s$/, "")}`,
261
+ DELETE: convertPath(group.itemPath).replace(`{{${group.idParam}}}`, `{{${captureVar}}}`),
262
+ expect: {
263
+ status: getExpectedStatus(group.delete),
264
+ },
265
+ };
266
+ tests.push(step);
267
+
268
+ // 5. Verify deleted
269
+ if (group.read) {
270
+ tests.push({
271
+ name: `Verify ${group.resource.replace(/s$/, "")} deleted`,
272
+ GET: convertPath(group.itemPath).replace(`{{${group.idParam}}}`, `{{${captureVar}}}`),
273
+ expect: {
274
+ status: 404,
275
+ },
276
+ });
277
+ }
278
+ }
279
+
280
+ const suite: RawSuite = {
281
+ name: `${group.resource}-crud`,
282
+ tags: ["crud"],
283
+ fileStem: `crud-${slugify(group.resource)}`,
284
+ base_url: "{{base_url}}",
285
+ tests,
286
+ };
287
+
288
+ if (suiteHeaders) {
289
+ suite.headers = suiteHeaders;
290
+ }
291
+
292
+ return suite;
293
+ }
294
+
295
+ /** Main entry point: generate all suites from endpoints */
296
+ export function generateSuites(opts: {
297
+ endpoints: EndpointInfo[];
298
+ securitySchemes: SecuritySchemeInfo[];
299
+ }): RawSuite[] {
300
+ const { endpoints, securitySchemes } = opts;
301
+
302
+ // Filter deprecated
303
+ const active = endpoints.filter(ep => !ep.deprecated);
304
+
305
+ // 1. Detect CRUD groups
306
+ const crudGroups = detectCrudGroups(active);
307
+
308
+ // Collect endpoints consumed by CRUD groups
309
+ const crudEndpointKeys = new Set<string>();
310
+ for (const g of crudGroups) {
311
+ if (g.create) crudEndpointKeys.add(`${g.create.method.toUpperCase()} ${g.create.path}`);
312
+ if (g.list) crudEndpointKeys.add(`${g.list.method.toUpperCase()} ${g.list.path}`);
313
+ if (g.read) crudEndpointKeys.add(`${g.read.method.toUpperCase()} ${g.read.path}`);
314
+ if (g.update) crudEndpointKeys.add(`${g.update.method.toUpperCase()} ${g.update.path}`);
315
+ if (g.delete) crudEndpointKeys.add(`${g.delete.method.toUpperCase()} ${g.delete.path}`);
316
+ }
317
+
318
+ // Remaining endpoints (not in any CRUD group)
319
+ const remaining = active.filter(ep => !crudEndpointKeys.has(`${ep.method.toUpperCase()} ${ep.path}`));
320
+
321
+ const suites: RawSuite[] = [];
322
+
323
+ // 2. Group remaining by tag → smoke + smoke-unsafe
324
+ const byTag = groupEndpointsByTag(remaining);
325
+
326
+ for (const [tag, tagEndpoints] of byTag) {
327
+ const tagSlug = slugify(tag) || "api";
328
+
329
+ // GET endpoints → smoke suite
330
+ const getEndpoints = tagEndpoints.filter(ep => ep.method.toUpperCase() === "GET");
331
+ if (getEndpoints.length > 0) {
332
+ const tests = getEndpoints.map(ep => generateStep(ep, securitySchemes));
333
+ const headers = getSuiteHeaders(getEndpoints, securitySchemes);
334
+
335
+ const suite: RawSuite = {
336
+ name: `${tagSlug}-smoke`,
337
+ tags: ["smoke"],
338
+ fileStem: `smoke-${tagSlug}`,
339
+ base_url: "{{base_url}}",
340
+ tests,
341
+ };
342
+
343
+ if (headers) {
344
+ suite.headers = headers;
345
+ for (const t of tests) {
346
+ if (t.headers && JSON.stringify(t.headers) === JSON.stringify(headers)) {
347
+ delete (t as any).headers;
348
+ }
349
+ }
350
+ }
351
+
352
+ suites.push(suite);
353
+ }
354
+
355
+ // Non-GET endpoints → smoke-unsafe suite
356
+ const unsafeEndpoints = tagEndpoints.filter(ep => ep.method.toUpperCase() !== "GET");
357
+ if (unsafeEndpoints.length > 0) {
358
+ const tests = unsafeEndpoints.map(ep => generateStep(ep, securitySchemes));
359
+ const headers = getSuiteHeaders(unsafeEndpoints, securitySchemes);
360
+
361
+ const suite: RawSuite = {
362
+ name: `${tagSlug}-smoke-unsafe`,
363
+ tags: ["smoke", "unsafe"],
364
+ fileStem: `smoke-${tagSlug}-unsafe`,
365
+ base_url: "{{base_url}}",
366
+ tests,
367
+ };
368
+
369
+ if (headers) {
370
+ suite.headers = headers;
371
+ for (const t of tests) {
372
+ if (t.headers && JSON.stringify(t.headers) === JSON.stringify(headers)) {
373
+ delete (t as any).headers;
374
+ }
375
+ }
376
+ }
377
+
378
+ suites.push(suite);
379
+ }
380
+ }
381
+
382
+ // 3. CRUD suites
383
+ for (const group of crudGroups) {
384
+ suites.push(generateCrudSuite(group, securitySchemes));
385
+ }
386
+
387
+ return suites;
388
+ }
@@ -57,7 +57,9 @@ export const TOOL_DESCRIPTIONS = {
57
57
  "and return a focused test generation guide. For large APIs returns a chunking plan — " +
58
58
  "call again with tag parameter for each chunk. Use testsDir param to only generate for uncovered endpoints. " +
59
59
  "After generating YAML, use save_test_suites to save files, then run_tests to verify. " +
60
- "Includes YAML format cheatsheet by default; pass includeFormat: false for subsequent tag chunks to save tokens.",
60
+ "Includes YAML format cheatsheet by default; pass includeFormat: false for subsequent tag chunks to save tokens. " +
61
+ "Use mode: 'generate' to auto-generate and save deterministic YAML test files (smoke + CRUD) without LLM. " +
62
+ "Default mode is 'generate'; use mode: 'guide' for the text-based generation guide.",
61
63
 
62
64
  ci_init:
63
65
  "Generate a CI/CD workflow file for running API tests automatically on push, PR, and schedule. " +
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { join } from "node:path";
2
3
  import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
4
  import {
4
5
  readOpenApiSpec,
@@ -6,10 +7,13 @@ import {
6
7
  extractSecuritySchemes,
7
8
  scanCoveredEndpoints,
8
9
  filterUncoveredEndpoints,
10
+ serializeSuite,
11
+ generateSuites,
9
12
  } from "../../core/generator/index.ts";
10
13
  import { compressEndpointsWithSchemas, buildGenerationGuide } from "../../core/generator/guide-builder.ts";
11
14
  import { planChunks, filterByTag } from "../../core/generator/chunker.ts";
12
15
  import { TOOL_DESCRIPTIONS } from "../descriptions.js";
16
+ import { validateAndSave } from "./save-test-suite.ts";
13
17
 
14
18
  export function registerGenerateAndSaveTool(server: McpServer) {
15
19
  server.registerTool("generate_and_save", {
@@ -22,8 +26,11 @@ export function registerGenerateAndSaveTool(server: McpServer) {
22
26
  testsDir: z.optional(z.string()).describe("Path to existing tests directory — filters to uncovered endpoints only"),
23
27
  overwrite: z.optional(z.boolean()).describe("Hint for save_test_suites overwrite behavior (default: false)"),
24
28
  includeFormat: z.optional(z.boolean()).describe("Include YAML format reference (default: true, set false for subsequent tag chunks)"),
29
+ mode: z.optional(z.enum(["generate", "guide"])).describe(
30
+ "'generate' creates and saves YAML test files deterministically (default), 'guide' returns text for LLM-crafted tests"
31
+ ),
25
32
  },
26
- }, async ({ specPath, outputDir, tag, methodFilter, testsDir, overwrite, includeFormat }) => {
33
+ }, async ({ specPath, outputDir, tag, methodFilter, testsDir, overwrite, includeFormat, mode }) => {
27
34
  try {
28
35
  const doc = await readOpenApiSpec(specPath);
29
36
  let endpoints = extractEndpoints(doc);
@@ -31,6 +38,7 @@ export function registerGenerateAndSaveTool(server: McpServer) {
31
38
  const baseUrl = ((doc as any).servers?.[0]?.url) as string | undefined;
32
39
  const title = (doc as any).info?.title as string | undefined;
33
40
  const effectiveOutputDir = outputDir ?? "./tests/";
41
+ const effectiveMode = mode ?? "generate";
34
42
 
35
43
  // Apply method filter
36
44
  if (methodFilter && methodFilter.length > 0) {
@@ -83,8 +91,11 @@ export function registerGenerateAndSaveTool(server: McpServer) {
83
91
  instruction:
84
92
  `This API has ${plan.totalEndpoints} endpoints across ${plan.chunks.length} tags. ` +
85
93
  `Call generate_and_save with tag parameter for each chunk sequentially. ` +
86
- `Pass includeFormat: false for subsequent chunks to save tokens. ` +
87
- `Example: generate_and_save(specPath: '${specPath}', tag: '${plan.chunks[0].tag}')`,
94
+ (effectiveMode === "guide"
95
+ ? `Pass includeFormat: false for subsequent chunks to save tokens. `
96
+ : "") +
97
+ `Example: generate_and_save(specPath: '${specPath}', tag: '${plan.chunks[0].tag}'` +
98
+ (effectiveMode === "guide" ? `, mode: 'guide'` : "") + `)`,
88
99
  };
89
100
  if (coverageInfo) {
90
101
  result.coverage = coverageInfo;
@@ -94,7 +105,49 @@ export function registerGenerateAndSaveTool(server: McpServer) {
94
105
  };
95
106
  }
96
107
 
97
- // Guide mode: small API or specific tag
108
+ // ── Generate mode: deterministic YAML generation ──
109
+ if (effectiveMode === "generate") {
110
+ const suites = generateSuites({ endpoints, securitySchemes });
111
+
112
+ const files: Array<{
113
+ saved: boolean;
114
+ filePath: string;
115
+ tests: number;
116
+ error?: string;
117
+ }> = [];
118
+
119
+ for (const suite of suites) {
120
+ const yaml = serializeSuite(suite);
121
+ const fileName = (suite.fileStem ?? suite.name) + ".yaml";
122
+ const filePath = join(effectiveOutputDir, fileName);
123
+
124
+ const result = await validateAndSave(filePath, yaml, overwrite ?? false);
125
+ files.push({
126
+ saved: result.saved,
127
+ filePath: result.filePath ?? filePath,
128
+ tests: suite.tests.length,
129
+ ...(result.error ? { error: result.error } : {}),
130
+ });
131
+ }
132
+
133
+ const response: Record<string, unknown> = {
134
+ mode: "generate",
135
+ suitesGenerated: suites.length,
136
+ files,
137
+ hint: files.some(f => !f.saved)
138
+ ? "Some files were not saved (already exist?). Use overwrite: true to replace."
139
+ : "Files saved. Run run_tests to verify. Use mode: 'guide' for LLM-crafted tests with more detail.",
140
+ };
141
+ if (coverageInfo) {
142
+ response.coverage = coverageInfo;
143
+ }
144
+
145
+ return {
146
+ content: [{ type: "text" as const, text: JSON.stringify(response, null, 2) }],
147
+ };
148
+ }
149
+
150
+ // ── Guide mode: text-based generation guide ──
98
151
  const coverageHeader = coverageInfo
99
152
  ? `## Coverage: ${coverageInfo.covered}/${coverageInfo.total} endpoints covered (${coverageInfo.percentage}%). Generating tests for ${endpoints.length} uncovered endpoints:`
100
153
  : undefined;