-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtestPlanTools.ts
More file actions
673 lines (620 loc) · 23.4 KB
/
testPlanTools.ts
File metadata and controls
673 lines (620 loc) · 23.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
/*
* Copyright (c) 2024 Provar Limited.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.md file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
/* eslint-disable camelcase */
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { z } from 'zod';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import type { ServerConfig } from '../server.js';
import { assertPathAllowed, PathPolicyError } from '../security/pathPolicy.js';
import { makeError, makeRequestId } from '../schemas/common.js';
import { log } from '../logging/logger.js';
// ── Helpers ───────────────────────────────────────────────────────────────────
/**
* Try to extract testCaseId from testcase XML content.
* Looks for registryId, id, or guid attributes on the root element.
*/
function extractTestCaseId(xmlContent: string): string | null {
for (const attr of ['registryId', 'id', 'guid']) {
const match = new RegExp(`${attr}="([^"]+)"`).exec(xmlContent);
if (match) return match[1];
}
return null;
}
/** Normalize path separators to forward slashes. */
function toForwardSlashes(p: string): string {
return p.replace(/\\/g, '/');
}
/** Build a .testinstance XML string. */
function buildTestInstanceXml(guid: string, testCaseId: string, testCasePath: string): string {
return [
'<?xml version="1.0" encoding="UTF-8" standalone="no"?>',
`<testPlanInstance guid="${guid}" testCaseId="${testCaseId}" testCasePath="${testCasePath}">`,
' <planSettings/>',
' <planFeatures/>',
'</testPlanInstance>',
].join('\n');
}
/** Build a .planitem XML string. */
function buildPlanItemXml(guid: string): string {
return [
'<?xml version="1.0" encoding="UTF-8" standalone="no"?>',
`<testPlan guid="${guid}">`,
' <planSettings/>',
' <planFeatures/>',
'</testPlan>',
].join('\n');
}
// ── provar_testplan_create ────────────────────────────────────────────────────
export function registerTestPlanCreate(server: McpServer, config: ServerConfig): void {
server.registerTool(
'provar_testplan_create',
{
title: 'Create Test Plan',
description: [
'Create a new Provar test plan: makes the plans/{plan_name}/ directory and writes the root .planitem file.',
'Use this before provar_testplan_create-suite or provar_testplan_add-instance, which both require the plan to already exist.',
'Returns the guid assigned to the new plan, the plan directory path, and the .planitem path written.',
].join(' '),
inputSchema: {
project_path: z
.string()
.describe('Absolute path to the Provar project root (must contain a .testproject file)'),
plan_name: z.string().describe('Name of the new test plan (becomes the directory name under plans/)'),
overwrite: z
.boolean()
.optional()
.default(false)
.describe('Overwrite the .planitem file if the plan directory already exists (default: false)'),
dry_run: z
.boolean()
.optional()
.default(false)
.describe('Return what would be created without writing to disk (default: false)'),
},
},
({ project_path, plan_name, overwrite, dry_run }) => {
const requestId = makeRequestId();
log('info', 'provar_testplan_create', { requestId, project_path, plan_name });
try {
assertPathAllowed(project_path, config.allowedPaths);
const projectRoot = path.resolve(project_path);
const testProjectFiles = fs.existsSync(projectRoot)
? fs.readdirSync(projectRoot).filter((f) => f.endsWith('.testproject'))
: [];
if (testProjectFiles.length === 0) {
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(
makeError('NOT_A_PROJECT', `No .testproject file found in ${projectRoot}`, requestId)
),
},
],
};
}
if (!/^[A-Za-z0-9][\w\- ]*$/.test(plan_name)) {
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(
makeError(
'INVALID_PLAN_NAME',
`plan_name must start with a letter or digit and contain only letters, digits, underscores, hyphens, or spaces: "${plan_name}"`,
requestId
)
),
},
],
};
}
const planDir = path.join(projectRoot, 'plans', plan_name);
assertPathAllowed(planDir, config.allowedPaths);
const planItemPath = path.join(planDir, '.planitem');
if (!overwrite && fs.existsSync(planItemPath)) {
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(
makeError(
'PLAN_EXISTS',
`Plan already exists: ${planItemPath}. Set overwrite: true to replace the .planitem file.`,
requestId
)
),
},
],
};
}
const guid = randomUUID();
const xmlContent = buildPlanItemXml(guid);
if (!dry_run) {
fs.mkdirSync(planDir, { recursive: true });
fs.writeFileSync(planItemPath, xmlContent, 'utf-8');
}
const response = {
requestId,
plan_dir: planDir,
planitem_path: planItemPath,
guid,
dry_run: dry_run ?? false,
created: !dry_run,
next_steps: dry_run
? 'Review the plan structure, then call provar_testplan_create with dry_run=false to write to disk.'
: `Plan created at ${planDir}. Use provar_testplan_create-suite to add suites, then provar_testplan_add-instance to wire test cases into the plan.`,
};
return {
content: [{ type: 'text' as const, text: JSON.stringify(response) }],
structuredContent: response,
};
} catch (err: unknown) {
const error = err as Error & { code?: string };
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(
makeError(
error instanceof PathPolicyError ? error.code : error.code ?? 'CREATE_PLAN_ERROR',
error.message,
requestId
)
),
},
],
};
}
}
);
}
// ── provar_testplan_add-instance ──────────────────────────────────────────────
export function registerTestPlanAddInstance(server: McpServer, config: ServerConfig): void {
server.registerTool(
'provar_testplan_add-instance',
{
title: 'Add Test Plan Instance',
description: [
'Add a .testinstance file to an existing Provar test plan suite directory.',
'The plan directory and suite directory must already exist.',
'test_case_path is relative to the project root (e.g. "tests/MyTest.testcase").',
'suite_path is the path within the plan (e.g. "MySuite" or "MySuite/SubSuite").',
'Returns the guid assigned to the new instance and the path where it was written.',
].join(' '),
inputSchema: {
project_path: z.string().describe('Absolute path to the Provar project root'),
test_case_path: z
.string()
.describe('Path to the .testcase file, relative to project root (e.g. "tests/MyTest.testcase")'),
plan_name: z.string().describe('Name of the test plan (directory under plans/)'),
suite_path: z
.string()
.optional()
.describe('Path within the plan to place the instance (e.g. "MySuite" or "MySuite/SubSuite")'),
overwrite: z
.boolean()
.optional()
.default(false)
.describe('Overwrite the .testinstance file if it already exists (default: false)'),
dry_run: z
.boolean()
.optional()
.default(false)
.describe('Return what would be written without writing to disk (default: false)'),
},
},
({ project_path, test_case_path, plan_name, suite_path, overwrite, dry_run }) => {
const requestId = makeRequestId();
log('info', 'provar_testplan_add-instance', { requestId, project_path, test_case_path, plan_name });
try {
assertPathAllowed(project_path, config.allowedPaths);
const projectRoot = path.resolve(project_path);
// Verify .testproject exists
const testProjectFiles = fs.existsSync(projectRoot)
? fs.readdirSync(projectRoot).filter((f) => f.endsWith('.testproject'))
: [];
if (testProjectFiles.length === 0) {
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(
makeError('NOT_A_PROJECT', `No .testproject file found in ${projectRoot}`, requestId)
),
},
],
};
}
// Resolve testcase absolute path — normalize backslashes so Windows-style paths work on macOS/Linux.
// Check for '..' before path.join() normalizes them away; otherwise traversal goes undetected
// when allowedPaths is empty (unrestricted mode). Then enforce containment on the resolved path.
const normalizedTestCasePath = toForwardSlashes(test_case_path);
if (normalizedTestCasePath.split('/').some((seg) => seg === '..')) {
throw new PathPolicyError('PATH_TRAVERSAL', `Path traversal detected in test_case_path: ${test_case_path}`);
}
const absoluteTestCasePath = path.join(projectRoot, normalizedTestCasePath);
assertPathAllowed(absoluteTestCasePath, config.allowedPaths);
if (!fs.existsSync(absoluteTestCasePath)) {
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(
makeError('FILE_NOT_FOUND', `Test case not found: ${absoluteTestCasePath}`, requestId)
),
},
],
};
}
if (!normalizedTestCasePath.endsWith('.testcase')) {
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(makeError('INVALID_PATH', 'test_case_path must end with .testcase', requestId)),
},
],
};
}
// Read testcase XML and extract testCaseId
const testCaseXml = fs.readFileSync(absoluteTestCasePath, 'utf-8');
const testCaseId = extractTestCaseId(testCaseXml);
if (!testCaseId) {
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(
makeError(
'NO_TEST_CASE_ID',
`Cannot extract registryId, id, or guid from ${absoluteTestCasePath}`,
requestId
)
),
},
],
};
}
// Determine instance directory
const instanceDirParts = ['plans', plan_name];
if (suite_path) instanceDirParts.push(...suite_path.split('/').filter(Boolean));
const instanceDir = path.join(projectRoot, ...instanceDirParts);
if (!fs.existsSync(instanceDir)) {
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(
makeError(
'DIR_NOT_FOUND',
`Suite directory does not exist: ${instanceDir}. Create it with provar_testplan_create-suite first.`,
requestId
)
),
},
],
};
}
// Determine filename and full path
const instanceFileName = path.basename(normalizedTestCasePath, '.testcase') + '.testinstance';
const instanceFilePath = path.join(instanceDir, instanceFileName);
if (!overwrite && fs.existsSync(instanceFilePath)) {
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(
makeError(
'FILE_EXISTS',
`Instance file already exists: ${instanceFilePath}. Set overwrite: true to replace it.`,
requestId
)
),
},
],
};
}
// Build XML
const guid = randomUUID();
const xmlContent = buildTestInstanceXml(guid, testCaseId, normalizedTestCasePath);
if (!dry_run) {
fs.writeFileSync(instanceFilePath, xmlContent, 'utf-8');
}
const response = {
requestId,
instance_path: instanceFilePath,
guid,
test_case_id: testCaseId,
test_case_path: normalizedTestCasePath,
dry_run: dry_run ?? false,
written: !dry_run,
};
return {
content: [{ type: 'text' as const, text: JSON.stringify(response) }],
structuredContent: response,
};
} catch (err: unknown) {
const error = err as Error & { code?: string };
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(
makeError(
error instanceof PathPolicyError ? error.code : error.code ?? 'ADD_INSTANCE_ERROR',
error.message,
requestId
)
),
},
],
};
}
}
);
}
// ── provar_testplan_create-suite ──────────────────────────────────────────────
export function registerTestPlanCreateSuite(server: McpServer, config: ServerConfig): void {
server.registerTool(
'provar_testplan_create-suite',
{
title: 'Create Test Plan Suite',
description: [
'Create a new suite directory inside a Provar test plan.',
'The plan directory must already exist with a .planitem file at its root.',
'Writes a new .planitem file into the created suite directory.',
'Returns the guid assigned to the new suite.',
].join(' '),
inputSchema: {
project_path: z.string().describe('Absolute path to the Provar project root'),
plan_name: z.string().describe('Name of the test plan (directory under plans/)'),
suite_name: z.string().describe('Name of the new suite directory to create'),
parent_suite_path: z
.string()
.optional()
.describe('Path of the parent suite within the plan (e.g. "MySuite"). Omit to create at plan root.'),
dry_run: z
.boolean()
.optional()
.default(false)
.describe('Return what would be created without writing to disk (default: false)'),
},
},
({ project_path, plan_name, suite_name, parent_suite_path, dry_run }) => {
const requestId = makeRequestId();
log('info', 'provar_testplan_create-suite', { requestId, project_path, plan_name, suite_name });
try {
assertPathAllowed(project_path, config.allowedPaths);
const projectRoot = path.resolve(project_path);
// Verify .testproject exists
const testProjectFiles = fs.existsSync(projectRoot)
? fs.readdirSync(projectRoot).filter((f) => f.endsWith('.testproject'))
: [];
if (testProjectFiles.length === 0) {
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(
makeError('NOT_A_PROJECT', `No .testproject file found in ${projectRoot}`, requestId)
),
},
],
};
}
// Verify plan directory exists
const planDir = path.join(projectRoot, 'plans', plan_name);
if (!fs.existsSync(planDir)) {
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(
makeError('DIR_NOT_FOUND', `Plan directory does not exist: ${planDir}`, requestId)
),
},
],
};
}
// Verify plan .planitem exists
const planItemPath = path.join(planDir, '.planitem');
if (!fs.existsSync(planItemPath)) {
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(
makeError('FILE_NOT_FOUND', `Plan .planitem file does not exist: ${planItemPath}`, requestId)
),
},
],
};
}
// Determine suite directory
const suiteDirParts = [planDir];
if (parent_suite_path) suiteDirParts.push(...parent_suite_path.split('/').filter(Boolean));
suiteDirParts.push(suite_name);
const suiteDir = path.join(...suiteDirParts);
if (fs.existsSync(suiteDir)) {
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(makeError('DIR_EXISTS', `Suite directory already exists: ${suiteDir}`, requestId)),
},
],
};
}
const guid = randomUUID();
const xmlContent = buildPlanItemXml(guid);
const newPlanItemPath = path.join(suiteDir, '.planitem');
if (!dry_run) {
fs.mkdirSync(suiteDir, { recursive: true });
fs.writeFileSync(newPlanItemPath, xmlContent, 'utf-8');
}
const response = {
requestId,
suite_dir: suiteDir,
planitem_path: newPlanItemPath,
guid,
dry_run: dry_run ?? false,
created: !dry_run,
};
return {
content: [{ type: 'text' as const, text: JSON.stringify(response) }],
structuredContent: response,
};
} catch (err: unknown) {
const error = err as Error & { code?: string };
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(
makeError(
error instanceof PathPolicyError ? error.code : error.code ?? 'CREATE_SUITE_ERROR',
error.message,
requestId
)
),
},
],
};
}
}
);
}
// ── provar_testplan_remove-instance ──────────────────────────────────────────
export function registerTestPlanRemoveInstance(server: McpServer, config: ServerConfig): void {
server.registerTool(
'provar_testplan_remove-instance',
{
title: 'Remove Test Plan Instance',
description: [
'Remove a .testinstance file from a Provar test plan.',
'instance_path is relative to the project root.',
'Returns the path of the removed file.',
].join(' '),
inputSchema: {
project_path: z.string().describe('Absolute path to the Provar project root'),
instance_path: z.string().describe('Path to the .testinstance file, relative to project root'),
dry_run: z
.boolean()
.optional()
.default(false)
.describe('Return what would be removed without deleting (default: false)'),
},
},
({ project_path, instance_path, dry_run }) => {
const requestId = makeRequestId();
log('info', 'provar_testplan_remove-instance', { requestId, project_path, instance_path });
try {
assertPathAllowed(project_path, config.allowedPaths);
const projectRoot = path.resolve(project_path);
const absolutePath = path.join(projectRoot, instance_path);
// Assert no traversal outside project root
const resolvedProjectRoot = path.resolve(projectRoot);
const resolvedAbsolute = path.resolve(absolutePath);
if (!resolvedAbsolute.startsWith(resolvedProjectRoot + path.sep) && resolvedAbsolute !== resolvedProjectRoot) {
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(
makeError('PATH_TRAVERSAL', `Path traversal detected: ${instance_path}`, requestId)
),
},
],
};
}
// Must end with .testinstance
if (!instance_path.endsWith('.testinstance')) {
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(makeError('INVALID_PATH', 'instance_path must end with .testinstance', requestId)),
},
],
};
}
// File must exist
if (!fs.existsSync(absolutePath)) {
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(
makeError('FILE_NOT_FOUND', `Instance file not found: ${absolutePath}`, requestId)
),
},
],
};
}
if (!dry_run) {
fs.unlinkSync(absolutePath);
}
const response = {
requestId,
removed_path: absolutePath,
dry_run: dry_run ?? false,
removed: !dry_run,
};
return {
content: [{ type: 'text' as const, text: JSON.stringify(response) }],
structuredContent: response,
};
} catch (err: unknown) {
const error = err as Error & { code?: string };
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(
makeError(
error instanceof PathPolicyError ? error.code : error.code ?? 'REMOVE_INSTANCE_ERROR',
error.message,
requestId
)
),
},
],
};
}
}
);
}
// ── Convenience re-export ─────────────────────────────────────────────────────
export function registerAllTestPlanTools(server: McpServer, config: ServerConfig): void {
registerTestPlanCreate(server, config);
registerTestPlanAddInstance(server, config);
registerTestPlanCreateSuite(server, config);
registerTestPlanRemoveInstance(server, config);
}