forked from modelcontextprotocol/conformance
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
503 lines (457 loc) · 16 KB
/
index.ts
File metadata and controls
503 lines (457 loc) · 16 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
#!/usr/bin/env node
import { Command } from 'commander';
import { ZodError } from 'zod';
import {
runConformanceTest,
printClientResults,
runServerConformanceTest,
printServerResults,
printServerSummary,
runInteractiveMode
} from './runner';
import {
listScenarios,
listClientScenarios,
listActiveClientScenarios,
listPendingClientScenarios,
listAuthScenarios,
listMetadataScenarios,
listCoreScenarios,
listExtensionScenarios,
listBackcompatScenarios,
listDraftScenarios,
listScenariosForSpec,
listClientScenariosForSpec,
getScenarioSpecVersions,
ALL_SPEC_VERSIONS
} from './scenarios';
import type { SpecVersion } from './scenarios';
import { ConformanceCheck } from './types';
import { ClientOptionsSchema, ServerOptionsSchema } from './schemas';
import {
loadExpectedFailures,
evaluateBaseline,
printBaselineResults
} from './expected-failures';
import { createTierCheckCommand } from './tier-check';
import packageJson from '../package.json';
function resolveSpecVersion(value: string): SpecVersion {
if (ALL_SPEC_VERSIONS.includes(value as SpecVersion)) {
return value as SpecVersion;
}
console.error(`Unknown spec version: ${value}`);
console.error(`Valid versions: ${ALL_SPEC_VERSIONS.join(', ')}`);
process.exit(1);
}
// Note on naming: `command` refers to which CLI command is calling this.
// The `client` command tests Scenario objects (which test clients),
// and the `server` command tests ClientScenario objects (which test servers).
// This matches the inverted naming in scenarios/index.ts.
function filterScenariosBySpecVersion(
allScenarios: string[],
version: SpecVersion,
command: 'client' | 'server'
): string[] {
const versionScenarios =
command === 'client'
? listScenariosForSpec(version)
: listClientScenariosForSpec(version);
const allowed = new Set(versionScenarios);
return allScenarios.filter((s) => allowed.has(s));
}
const program = new Command();
program
.name('conformance')
.description('MCP Conformance Test Suite')
.version(packageJson.version);
// Client command - tests a client implementation against scenarios
program
.command('client')
.description(
'Run conformance tests against a client implementation or start interactive mode'
)
.option('--command <command>', 'Command to run the client')
.option('--scenario <scenario>', 'Scenario to test')
.option('--suite <suite>', 'Run a suite of tests in parallel (e.g., "auth")')
.option('--timeout <ms>', 'Timeout in milliseconds', '30000')
.option(
'--expected-failures <path>',
'Path to YAML file listing expected failures (baseline)'
)
.option('-o, --output-dir <path>', 'Save results to this directory')
.option(
'--spec-version <version>',
'Filter scenarios by spec version (cumulative for date versions)'
)
.option('--verbose', 'Show verbose output')
.action(async (options) => {
try {
const timeout = parseInt(options.timeout, 10);
const verbose = options.verbose ?? false;
const outputDir = options.outputDir;
const specVersionFilter = options.specVersion
? resolveSpecVersion(options.specVersion)
: undefined;
// Handle suite mode
if (options.suite) {
if (!options.command) {
console.error('--command is required when using --suite');
process.exit(1);
}
const suites: Record<string, () => string[]> = {
all: listScenarios,
core: listCoreScenarios,
extensions: listExtensionScenarios,
backcompat: listBackcompatScenarios,
auth: listAuthScenarios,
metadata: listMetadataScenarios,
draft: listDraftScenarios,
'sep-835': () =>
listAuthScenarios().filter((name) => name.startsWith('auth/scope-'))
};
const suiteName = options.suite.toLowerCase();
if (!suites[suiteName]) {
console.error(`Unknown suite: ${suiteName}`);
console.error(`Available suites: ${Object.keys(suites).join(', ')}`);
process.exit(1);
}
let scenarios = suites[suiteName]();
if (specVersionFilter) {
scenarios = filterScenariosBySpecVersion(
scenarios,
specVersionFilter,
'client'
);
}
console.log(
`Running ${suiteName} suite (${scenarios.length} scenarios) in parallel...\n`
);
const results = await Promise.all(
scenarios.map(async (scenarioName) => {
try {
const result = await runConformanceTest(
options.command,
scenarioName,
timeout,
outputDir
);
return {
scenario: scenarioName,
checks: result.checks,
error: null
};
} catch (error) {
return {
scenario: scenarioName,
checks: [
{
id: scenarioName,
name: scenarioName,
description: 'Failed to run scenario',
status: 'FAILURE' as const,
timestamp: new Date().toISOString(),
errorMessage:
error instanceof Error ? error.message : String(error)
}
],
error
};
}
})
);
console.log('\n=== SUITE SUMMARY ===\n');
let totalPassed = 0;
let totalFailed = 0;
let totalWarnings = 0;
for (const result of results) {
const passed = result.checks.filter(
(c) => c.status === 'SUCCESS'
).length;
const failed = result.checks.filter(
(c) => c.status === 'FAILURE'
).length;
const warnings = result.checks.filter(
(c) => c.status === 'WARNING'
).length;
totalPassed += passed;
totalFailed += failed;
totalWarnings += warnings;
const status = failed === 0 && warnings === 0 ? '✓' : '✗';
const warningStr = warnings > 0 ? `, ${warnings} warnings` : '';
console.log(
`${status} ${result.scenario}: ${passed} passed, ${failed} failed${warningStr}`
);
if (verbose && failed > 0) {
result.checks
.filter((c) => c.status === 'FAILURE')
.forEach((c) => {
console.log(
` - ${c.name}: ${c.errorMessage || c.description}`
);
});
}
}
console.log(
`\nTotal: ${totalPassed} passed, ${totalFailed} failed, ${totalWarnings} warnings`
);
if (options.expectedFailures) {
const expectedFailuresConfig = await loadExpectedFailures(
options.expectedFailures
);
const baselineScenarios = expectedFailuresConfig.client ?? [];
const baselineResult = evaluateBaseline(results, baselineScenarios);
printBaselineResults(baselineResult);
process.exit(baselineResult.exitCode);
}
process.exit(totalFailed > 0 || totalWarnings > 0 ? 1 : 0);
}
// Require either --scenario or --suite
if (!options.scenario) {
console.error('Either --scenario or --suite is required');
console.error('\nAvailable client scenarios:');
listScenarios().forEach((s) => console.error(` - ${s}`));
console.error(
'\nAvailable suites: all, core, extensions, backcompat, auth, metadata, draft, sep-835'
);
process.exit(1);
}
// Validate options with Zod for single scenario mode
const validated = ClientOptionsSchema.parse(options);
// If no command provided, run in interactive mode
if (!validated.command) {
await runInteractiveMode(validated.scenario, verbose, outputDir);
process.exit(0);
}
// Otherwise run conformance test
const result = await runConformanceTest(
validated.command,
validated.scenario,
timeout,
outputDir
);
const { overallFailure } = printClientResults(
result.checks,
verbose,
result.clientOutput,
result.allowClientError
);
if (options.expectedFailures) {
const expectedFailuresConfig = await loadExpectedFailures(
options.expectedFailures
);
const baselineScenarios = expectedFailuresConfig.client ?? [];
const baselineResult = evaluateBaseline(
[{ scenario: validated.scenario, checks: result.checks }],
baselineScenarios
);
printBaselineResults(baselineResult);
process.exit(baselineResult.exitCode);
}
process.exit(overallFailure ? 1 : 0);
} catch (error) {
if (error instanceof ZodError) {
console.error('Validation error:');
error.errors.forEach((err) => {
console.error(` ${err.path.join('.')}: ${err.message}`);
});
console.error('\nAvailable client scenarios:');
listScenarios().forEach((s) => console.error(` - ${s}`));
process.exit(1);
}
console.error('Client test error:', error);
process.exit(1);
}
});
// Server command - tests a server implementation
program
.command('server')
.description('Run conformance tests against a server implementation')
.requiredOption('--url <url>', 'URL of the server to test')
.option(
'--scenario <scenario>',
'Scenario to test (defaults to active suite if not specified)'
)
.option(
'--suite <suite>',
'Suite to run: "active" (default, excludes pending), "all", or "pending"',
'active'
)
.option(
'--expected-failures <path>',
'Path to YAML file listing expected failures (baseline)'
)
.option('-o, --output-dir <path>', 'Save results to this directory')
.option(
'--spec-version <version>',
'Filter scenarios by spec version (cumulative for date versions)'
)
.option('--verbose', 'Show verbose output (JSON instead of pretty print)')
.action(async (options) => {
try {
// Validate options with Zod
const validated = ServerOptionsSchema.parse(options);
const verbose = options.verbose ?? false;
const outputDir = options.outputDir;
const specVersionFilter = options.specVersion
? resolveSpecVersion(options.specVersion)
: undefined;
// If a single scenario is specified, run just that one
if (validated.scenario) {
const result = await runServerConformanceTest(
validated.url,
validated.scenario,
outputDir
);
const { failed } = printServerResults(
result.checks,
result.scenarioDescription,
verbose
);
if (options.expectedFailures) {
const expectedFailuresConfig = await loadExpectedFailures(
options.expectedFailures
);
const baselineScenarios = expectedFailuresConfig.server ?? [];
const baselineResult = evaluateBaseline(
[{ scenario: validated.scenario!, checks: result.checks }],
baselineScenarios
);
printBaselineResults(baselineResult);
process.exit(baselineResult.exitCode);
}
process.exit(failed > 0 ? 1 : 0);
} else {
// Run scenarios based on suite
const suite = options.suite?.toLowerCase() || 'active';
let scenarios: string[];
if (suite === 'all') {
scenarios = listClientScenarios();
} else if (suite === 'active' || suite === 'core') {
// 'core' is an alias for 'active' - tier 1 requirements
scenarios = listActiveClientScenarios();
} else if (suite === 'pending') {
scenarios = listPendingClientScenarios();
} else {
console.error(`Unknown suite: ${suite}`);
console.error('Available suites: active, all, core, pending');
process.exit(1);
}
if (specVersionFilter) {
scenarios = filterScenariosBySpecVersion(
scenarios,
specVersionFilter,
'server'
);
}
console.log(
`Running ${suite} suite (${scenarios.length} scenarios) against ${validated.url}\n`
);
const allResults: { scenario: string; checks: ConformanceCheck[] }[] =
[];
for (const scenarioName of scenarios) {
console.log(`\n=== Running scenario: ${scenarioName} ===`);
try {
const result = await runServerConformanceTest(
validated.url,
scenarioName,
outputDir
);
allResults.push({ scenario: scenarioName, checks: result.checks });
} catch (error) {
console.error(`Failed to run scenario ${scenarioName}:`, error);
allResults.push({
scenario: scenarioName,
checks: [
{
id: scenarioName,
name: scenarioName,
description: 'Failed to run scenario',
status: 'FAILURE',
timestamp: new Date().toISOString(),
errorMessage:
error instanceof Error ? error.message : String(error)
}
]
});
}
}
const { totalFailed } = printServerSummary(allResults);
if (options.expectedFailures) {
const expectedFailuresConfig = await loadExpectedFailures(
options.expectedFailures
);
const baselineScenarios = expectedFailuresConfig.server ?? [];
const baselineResult = evaluateBaseline(
allResults,
baselineScenarios
);
printBaselineResults(baselineResult);
process.exit(baselineResult.exitCode);
}
process.exit(totalFailed > 0 ? 1 : 0);
}
} catch (error) {
if (error instanceof ZodError) {
console.error('Validation error:');
error.errors.forEach((err) => {
console.error(` ${err.path.join('.')}: ${err.message}`);
});
console.error('\nAvailable server scenarios:');
listClientScenarios().forEach((s) => console.error(` - ${s}`));
process.exit(1);
}
console.error('Server test error:', error);
process.exit(1);
}
});
// Tier check command
program.addCommand(createTierCheckCommand());
// List scenarios command
program
.command('list')
.description('List available test scenarios')
.option('--client', 'List client scenarios')
.option('--server', 'List server scenarios')
.option(
'--spec-version <version>',
'Filter scenarios by spec version (cumulative for date versions)'
)
.action((options) => {
const specVersionFilter = options.specVersion
? resolveSpecVersion(options.specVersion)
: undefined;
if (options.server || (!options.client && !options.server)) {
console.log('Server scenarios (test against a server):');
let serverScenarios = listClientScenarios();
if (specVersionFilter) {
serverScenarios = filterScenariosBySpecVersion(
serverScenarios,
specVersionFilter,
'server'
);
}
serverScenarios.forEach((s) => {
const v = getScenarioSpecVersions(s);
console.log(` - ${s}${v ? ` [${v}]` : ''}`);
});
}
if (options.client || (!options.client && !options.server)) {
if (options.server || (!options.client && !options.server)) {
console.log('');
}
console.log('Client scenarios (test against a client):');
let clientScenarioNames = listScenarios();
if (specVersionFilter) {
clientScenarioNames = filterScenariosBySpecVersion(
clientScenarioNames,
specVersionFilter,
'client'
);
}
clientScenarioNames.forEach((s) => {
const v = getScenarioSpecVersions(s);
console.log(` - ${s}${v ? ` [${v}]` : ''}`);
});
}
});
program.parse();