-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcli-tool-registry.ts
More file actions
838 lines (727 loc) · 34.7 KB
/
cli-tool-registry.ts
File metadata and controls
838 lines (727 loc) · 34.7 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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
/**
* Generic tool registry for creating MCP tools from CLI command definitions
*/
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { CLIExecutionResult, executeCodeQLCommand, executeQLTCommand } from './cli-executor';
import { readDatabaseMetadata, resolveDatabasePath } from './database-resolver';
import { logger } from '../utils/logger';
import { getOrCreateLogDirectory } from './log-directory-manager';
import { buildEnhancedToolSchema } from './param-normalization';
import { resolveQueryPath } from './query-resolver';
import { cacheDatabaseAnalyzeResults, processQueryRunResults } from './result-processor';
import { getUserWorkspaceDir, packageRootDir } from '../utils/package-paths';
import { existsSync, mkdirSync, realpathSync, rmSync, writeFileSync } from 'fs';
import { delimiter, dirname, isAbsolute, join, resolve } from 'path';
import * as yaml from 'js-yaml';
import { createProjectTempDir } from '../utils/temp-dir';
export type { CLIExecutionResult } from './cli-executor';
/**
* Per-database mutex map — serializes concurrent CLI operations that
* acquire an exclusive lock on a CodeQL database (e.g. database analyze).
*/
const databaseLocks = new Map<string, Promise<unknown>>();
/**
* Acquire a serialized slot for the given database path.
* Returns a release function that must be called when the operation completes.
*/
function acquireDatabaseLock(dbPath: string): { ready: Promise<void>; release: () => void } {
const key = dbPath;
const previous = databaseLocks.get(key) ?? Promise.resolve();
let resolveGate!: () => void;
const gate = new Promise<void>(resolve => {
resolveGate = resolve;
});
databaseLocks.set(key, gate);
return {
ready: previous.then(() => {}),
release: () => {
resolveGate();
if (databaseLocks.get(key) === gate) {
databaseLocks.delete(key);
}
},
};
}
export interface CLIToolDefinition {
name: string;
description: string;
command: 'codeql' | 'qlt';
subcommand: string;
inputSchema: Record<string, z.ZodTypeAny>;
examples?: string[];
resultProcessor?: (_result: CLIExecutionResult, _params: Record<string, unknown>) => string;
}
/**
* Default result processor that formats CLI output appropriately
*/
export const defaultCLIResultProcessor = (
result: CLIExecutionResult,
_params: Record<string, unknown>
): string => {
if (!result.success) {
return `Command failed (exit code ${result.exitCode || 'unknown'}):\n${result.error || result.stderr}`;
}
let output = '';
if (result.stdout) {
output += result.stdout;
}
if (result.stderr) {
if (output) {
output += '\n\nWarnings/Info:\n';
}
output += result.stderr;
}
if (!output) {
output = 'Command executed successfully (no output)';
}
return output;
};
/**
* Register a CLI tool with the MCP server.
*
* The raw `inputSchema` shape is wrapped by {@link buildEnhancedToolSchema}
* so that:
* - camelCase / snake_case variants of kebab-case keys are silently
* normalised (e.g. `sourceRoot` → `source-root`);
* - truly unknown properties are rejected with a helpful error that names
* the unrecognized key and, where possible, suggests the correct name.
*/
export function registerCLITool(server: McpServer, definition: CLIToolDefinition): void {
const {
name,
description,
command,
subcommand,
inputSchema,
resultProcessor = defaultCLIResultProcessor
} = definition;
// Build enhanced schema that normalises property-name variants and
// produces actionable error messages for truly unknown keys.
const enhancedSchema = buildEnhancedToolSchema(inputSchema);
server.registerTool(
name,
{
description,
// The enhanced schema is a pre-built ZodEffects (passthrough + transform).
// Using registerTool() instead of tool() because the latter's argument
// parsing rejects ZodEffects as "unrecognized objects". registerTool()
// passes inputSchema directly to getZodSchemaObject(), which correctly
// recognises any Zod schema instance.
inputSchema: enhancedSchema,
},
async (params: Record<string, unknown>) => {
// Track temporary directories for cleanup
const tempDirsToCleanup: string[] = [];
try {
logger.info(`Executing CLI tool: ${name}`, { command, subcommand, params });
// Separate positional arguments from named options
// Extract tool-specific parameters that should not be passed to CLI
// Note: format is extracted for tools that use it internally but not on CLI
// For codeql_bqrs_interpret, codeql_bqrs_decode, codeql_bqrs_info, codeql_generate_query-help, and codeql_database_analyze, format should be passed to CLI
const formatShouldBePassedToCLI = name === 'codeql_bqrs_interpret' || name === 'codeql_bqrs_decode' || name === 'codeql_bqrs_info' || name === 'codeql_generate_query-help' || name === 'codeql_database_analyze' || name === 'codeql_resolve_files';
const extractedParams = formatShouldBePassedToCLI
? {
_positional: params._positional || [],
files: params.files,
file: params.file,
dir: params.dir,
packDir: params.packDir,
tests: params.tests,
query: params.query,
queryName: params.queryName,
queryLanguage: params.queryLanguage,
queryPack: params.queryPack,
sourceFiles: params.sourceFiles,
sourceFunction: params.sourceFunction,
targetFunction: params.targetFunction,
interpretedOutput: params.interpretedOutput,
evaluationFunction: params.evaluationFunction,
evaluationOutput: params.evaluationOutput,
directory: params.directory,
logDir: params.logDir,
qlref: params.qlref
}
: {
_positional: params._positional || [],
files: params.files,
file: params.file,
dir: params.dir,
packDir: params.packDir,
tests: params.tests,
query: params.query,
queryName: params.queryName,
queryLanguage: params.queryLanguage,
queryPack: params.queryPack,
sourceFiles: params.sourceFiles,
sourceFunction: params.sourceFunction,
targetFunction: params.targetFunction,
format: params.format,
interpretedOutput: params.interpretedOutput,
evaluationFunction: params.evaluationFunction,
evaluationOutput: params.evaluationOutput,
directory: params.directory,
logDir: params.logDir,
qlref: params.qlref
};
const {
_positional = [],
files,
file,
dir,
packDir,
tests,
query,
queryName,
queryLanguage: _queryLanguage,
queryPack: _queryPack,
sourceFiles,
sourceFunction,
targetFunction,
format: _format,
interpretedOutput: _interpretedOutput,
evaluationFunction: _evaluationFunction,
evaluationOutput: _evaluationOutput,
directory,
logDir: customLogDir,
qlref,
} = extractedParams;
// Get remaining options (everything not extracted above)
const options = {...params};
Object.keys(extractedParams).forEach(key => delete options[key]);
let positionalArgs = Array.isArray(_positional) ? _positional as string[] : [_positional as string];
// Handle files parameter as positional arguments for certain tools
if (files && Array.isArray(files)) {
positionalArgs = [...positionalArgs, ...files as string[]];
}
// Handle file parameter as positional argument for BQRS tools.
// Check for key presence (not truthiness) so that empty strings
// are caught by the validation below rather than silently skipped.
if (file !== undefined && name.startsWith('codeql_bqrs_')) {
// Defensive coercion: handle file value that is an actual array
// or a JSON-encoded array string (e.g. '["/path/to/file.bqrs"]')
let cleanFile = Array.isArray(file) ? (file.length > 0 ? String(file[0]) : '') : String(file);
if (cleanFile.startsWith('[') && cleanFile.endsWith(']')) {
try {
const parsed = JSON.parse(cleanFile);
if (Array.isArray(parsed) && parsed.length > 0) {
cleanFile = String(parsed[0]);
} else {
cleanFile = '';
}
} catch { /* not valid JSON — use as-is */ }
}
if (!cleanFile.trim()) {
throw new Error('The "file" parameter for BQRS tools must be a non-empty string path to a .bqrs file.');
}
positionalArgs = [...positionalArgs, cleanFile];
}
// Handle qlref parameter as positional argument for resolve qlref tool
if (qlref && name === 'codeql_resolve_qlref') {
positionalArgs = [...positionalArgs, qlref as string];
}
// Handle database parameter as positional argument for resolve database tool
if (options.database && name === 'codeql_resolve_database') {
positionalArgs = [...positionalArgs, resolveDatabasePath(options.database as string)];
delete options.database;
}
// Handle database parameter as positional argument for database create tool
if (options.database && name === 'codeql_database_create') {
positionalArgs = [...positionalArgs, options.database as string];
delete options.database;
}
// Handle database and queries parameters as positional arguments for database analyze tool
if (name === 'codeql_database_analyze') {
if (options.database) {
positionalArgs = [...positionalArgs, resolveDatabasePath(options.database as string)];
delete options.database;
}
if (options.queries) {
positionalArgs = [...positionalArgs, options.queries as string];
delete options.queries;
}
}
// Handle query parameter as positional argument for generate query-help tool
if (query && name === 'codeql_generate_query-help') {
positionalArgs = [...positionalArgs, query as string];
}
// Handle dir parameter as positional argument for pack tools
if (dir && (name === 'codeql_pack_ls')) {
positionalArgs = [...positionalArgs, dir as string];
}
// Handle tool-specific parameters using switch pattern for better maintainability
switch (name) {
case 'codeql_test_accept':
case 'codeql_test_extract':
case 'codeql_test_run':
case 'codeql_resolve_tests':
// Handle tests parameter as positional arguments for test tools.
// Resolve relative paths against the user's effective workspace
// directory. In monorepo layouts this is the repo root; in npm-
// installed layouts it falls back to process.cwd().
if (tests && Array.isArray(tests)) {
const userDir = getUserWorkspaceDir();
positionalArgs = [...positionalArgs, ...(tests as string[]).map(
t => isAbsolute(t) ? t : resolve(userDir, t)
)];
}
break;
case 'codeql_query_run': {
// Resolve database path to absolute path if it's relative
if (options.database && typeof options.database === 'string' && !isAbsolute(options.database)) {
options.database = resolve(getUserWorkspaceDir(), options.database);
logger.info(`Resolved database path to: ${options.database}`);
}
// Auto-resolve multi-language DB root to language subfolder
if (options.database && typeof options.database === 'string') {
options.database = resolveDatabasePath(options.database);
}
// Implement query resolution logic with enhanced results processing
const resolvedQuery = await resolveQueryPath(params, logger);
if (resolvedQuery) {
positionalArgs = [...positionalArgs, resolvedQuery];
// Store the resolved path so processQueryRunResults can reuse it
// without calling resolveQueryPath a second time
params._resolvedQueryPath = resolvedQuery;
} else if (query) {
positionalArgs = [...positionalArgs, query as string];
}
// Handle extensible predicates for tool queries via data extensions.
// Instead of CSV files + --external flags, we create a temporary
// extension pack with a codeql-pack.yml and data extension YAML that
// injects values into the src pack's extensible predicates.
const extensiblePredicates: Record<string, string[]> = {};
if ((queryName === 'PrintAST' || queryName === 'PrintCFG') && sourceFiles) {
const filePaths = (sourceFiles as string).split(',').map((f: string) => f.trim()).filter((f: string) => f.length > 0);
if (filePaths.length > 0) {
extensiblePredicates['selectedSourceFiles'] = filePaths;
}
}
if (sourceFunction) {
const functionNames = (sourceFunction as string).split(',').map((f: string) => f.trim()).filter((f: string) => f.length > 0);
if (functionNames.length > 0) {
extensiblePredicates['sourceFunction'] = functionNames;
}
}
if (targetFunction) {
const functionNames = (targetFunction as string).split(',').map((f: string) => f.trim()).filter((f: string) => f.length > 0);
if (functionNames.length > 0) {
extensiblePredicates['targetFunction'] = functionNames;
}
}
if (Object.keys(extensiblePredicates).length > 0) {
// Derive the target pack name from queryLanguage or query path
let targetPackName: string | undefined;
if (_queryLanguage) {
targetPackName = `advanced-security/ql-mcp-${_queryLanguage}-tools-src`;
} else if (query && typeof query === 'string') {
// Extract language from query path: .../ql/{lang}/tools/src/...
// Normalize backslashes for Windows compatibility
const normalizedQuery = (query as string).replace(/\\/g, '/');
const match = normalizedQuery.match(/\/ql\/([^/]+)\/tools\/src\//);
if (match) {
targetPackName = `advanced-security/ql-mcp-${match[1]}-tools-src`;
}
}
if (targetPackName) {
try {
const extPackDir = createProjectTempDir('codeql-ext-pack-');
tempDirsToCleanup.push(extPackDir);
// Create codeql-pack.yml for the temporary extension pack
const qlpackContent = [
'library: true',
'name: advanced-security/ql-mcp-runtime-extensions',
'version: 0.0.0',
'extensionTargets:',
` ${targetPackName}: "*"`,
'dataExtensions:',
' - "ext/*.model.yml"',
'',
].join('\n');
writeFileSync(join(extPackDir, 'codeql-pack.yml'), qlpackContent, 'utf8');
// Create ext/ directory and data extension YAML
const extDir = join(extPackDir, 'ext');
mkdirSync(extDir, { recursive: true });
// Build the YAML data extensions content using js-yaml for safe serialization
const extensionsData = {
extensions: Object.entries(extensiblePredicates).map(([predName, values]) => ({
addsTo: {
pack: targetPackName,
extensible: predName,
},
data: values.map((val) => [val]),
})),
};
writeFileSync(join(extDir, 'runtime.model.yml'), yaml.dump(extensionsData, { lineWidth: -1, flowLevel: 4 }), 'utf8');
// Add the extension pack directory to --additional-packs so it can be resolved
const existingPacks = options['additional-packs'] as string | undefined;
options['additional-packs'] = existingPacks
? `${existingPacks}${delimiter}${extPackDir}`
: extPackDir;
// Use --model-packs to activate the extension pack for extensible predicates
const modelPacks = options['model-packs'] as string[] | undefined;
const modelPacksArray = Array.isArray(modelPacks) ? modelPacks : [];
modelPacksArray.push('advanced-security/ql-mcp-runtime-extensions@0.0.0');
options['model-packs'] = modelPacksArray;
logger.info(`Created runtime extension pack at ${extPackDir} targeting ${targetPackName} with predicates: ${Object.keys(extensiblePredicates).join(', ')}`);
} catch (err) {
logger.error(`Failed to create runtime extension pack: ${err instanceof Error ? err.message : String(err)}`);
throw err;
}
} else {
logger.warn('Could not determine target pack name for extensible predicates — queryLanguage not set and query path does not match expected pattern');
}
}
break;
}
case 'codeql_bqrs_interpret': {
// Map 'database' to '--source-archive' and '--source-location-prefix'
// for codeql bqrs interpret (only when not explicitly provided).
// Always delete the synthetic 'database' key to prevent it from
// being forwarded as an unsupported CLI flag.
const dbValue = options.database;
delete options.database;
if (dbValue !== undefined) {
const dbStr = String(dbValue).trim();
if (!dbStr) {
throw new Error('The "database" parameter must be a non-empty path to a CodeQL database.');
}
const dbPath = resolveDatabasePath(dbStr);
if (!options['source-archive']) {
const srcZipPath = join(dbPath, 'src.zip');
const srcDirPath = join(dbPath, 'src');
if (existsSync(srcZipPath)) {
options['source-archive'] = srcZipPath;
} else if (existsSync(srcDirPath)) {
options['source-archive'] = srcDirPath;
} else {
throw new Error(
`CodeQL database at "${dbPath}" does not contain a source archive (expected "src.zip" file or "src" directory).`,
);
}
}
// Auto-resolve --source-location-prefix from codeql-database.yml
// (only when not explicitly provided)
if (!options['source-location-prefix']) {
const dbMeta = readDatabaseMetadata(dbPath);
if (dbMeta.sourceLocationPrefix) {
options['source-location-prefix'] = dbMeta.sourceLocationPrefix;
}
}
}
break;
}
case 'codeql_query_compile':
case 'codeql_resolve_metadata':
// Handle query parameter as positional argument for query compilation and metadata tools
if (query) {
positionalArgs = [...positionalArgs, query as string];
}
break;
case 'codeql_resolve_library-path':
// --query is a named flag for resolve library-path, not positional.
// It was extracted from options so we need to restore it.
if (query) {
options.query = query;
}
break;
case 'codeql_resolve_queries':
// Handle directory parameter as positional argument
if (directory) {
positionalArgs = [...positionalArgs, directory as string];
}
break;
case 'codeql_resolve_files':
// Handle dir parameter as positional argument
if (dir) {
positionalArgs = [...positionalArgs, dir as string];
}
break;
default:
// No special parameter handling needed for other tools
break;
}
// Set up logging directory for query/test/analyze runs
let queryLogDir: string | undefined;
if (name === 'codeql_query_run' || name === 'codeql_test_run' || name === 'codeql_database_analyze') {
queryLogDir = getOrCreateLogDirectory(customLogDir as string | undefined);
logger.info(`Using log directory for ${name}: ${queryLogDir}`);
// Create timestamp file to track when query/test run started
const timestampPath = join(queryLogDir, 'timestamp');
writeFileSync(timestampPath, Date.now().toString(), 'utf8');
// Set the --logdir option for CodeQL CLI
options.logdir = queryLogDir;
// Set verbosity to progress+ to generate detailed query.log/test.log
if (!options.verbosity) {
options.verbosity = 'progress+';
}
// Set evaluator-log if not explicitly provided
if (!options['evaluator-log']) {
options['evaluator-log'] = join(queryLogDir, 'evaluator-log.jsonl');
}
// Enable --tuple-counting by default for evaluator logging
if (options['tuple-counting'] === undefined) {
options['tuple-counting'] = true;
}
// For query run, also handle default output
if (name === 'codeql_query_run') {
// If output was not explicitly provided, set it to the log directory
if (!options.output) {
options.output = join(queryLogDir, 'results.bqrs');
}
}
// Ensure the parent directory of --output exists (the CLI will not create it)
if (options.output && typeof options.output === 'string') {
const outputDir = dirname(options.output);
mkdirSync(outputDir, { recursive: true });
}
}
// Extract additionalArgs from options so they are passed as raw CLI
// arguments instead of being transformed into --additionalArgs=value
// by buildCodeQLArgs.
const rawAdditionalArgs = Array.isArray(options.additionalArgs)
? options.additionalArgs as string[]
: [];
delete options.additionalArgs;
// For tools with post-execution processing (query run, test run,
// database analyze), certain CLI flags are set internally and their
// values are read back after execution (e.g. --evaluator-log for log
// summary generation, --output for SARIF interpretation). If a user
// passes these flags via additionalArgs the CLI would receive
// conflicting duplicates and the post-processing would use stale
// values from the options object. Filter them out and log a warning
// directing the user to the corresponding named parameter instead.
const managedFlagNames = new Set([
'evaluator-log',
'logdir',
'output',
'tuple-counting',
'verbosity',
]);
const userAdditionalArgs = queryLogDir
? (() => {
const filteredAdditionalArgs: string[] = [];
for (let i = 0; i < rawAdditionalArgs.length; i += 1) {
const arg = rawAdditionalArgs[i];
const m = arg.match(/^--(?:no-)?([^=]+)(?:=.*)?$/);
if (m && managedFlagNames.has(m[1])) {
logger.warn(
`Ignoring "${arg}" from additionalArgs for ${name}: ` +
'this flag is managed internally. Use the corresponding named parameter instead.'
);
// Always skip the managed flag itself. If it is provided in
// space-separated form (e.g. ["--output", "file.sarif"]),
// also skip the following token as its value so it does not
// become a stray positional argument.
const hasInlineValue = arg.includes('=');
if (!hasInlineValue && i + 1 < rawAdditionalArgs.length) {
i += 1;
}
continue;
}
filteredAdditionalArgs.push(arg);
}
return filteredAdditionalArgs;
})()
: rawAdditionalArgs;
let result: CLIExecutionResult;
if (command === 'codeql') {
// For pack commands, set the working directory to where qlpack.yml is located.
// Resolve to absolute path since the MCP server's cwd may differ from
// the workspace root (especially when launched by VS Code).
let cwd: string | undefined;
if ((name === 'codeql_pack_install' || name === 'codeql_pack_ls') && (dir || packDir)) {
const rawCwd = (dir || packDir) as string;
// Resolve relative paths against the user's effective workspace
// directory rather than a potentially read-only package root.
cwd = isAbsolute(rawCwd) ? rawCwd : resolve(getUserWorkspaceDir(), rawCwd);
}
// Add --additional-packs for commands that need to access local test packs.
// Only set the default examples path when it actually exists on disk
// (it may be absent in npm-installed layouts where ql/javascript/examples/
// is not included in the published package).
const defaultExamplesPath = resolve(packageRootDir, 'ql', 'javascript', 'examples');
const additionalPacksPath = process.env.CODEQL_ADDITIONAL_PACKS
|| (existsSync(defaultExamplesPath) ? defaultExamplesPath : undefined);
if (additionalPacksPath && (name === 'codeql_test_run' || name === 'codeql_query_run' || name === 'codeql_query_compile' || name === 'codeql_database_analyze')) {
const existingAdditionalPacks = options['additional-packs'] as string | undefined;
options['additional-packs'] = existingAdditionalPacks
? `${existingAdditionalPacks}${delimiter}${additionalPacksPath}`
: additionalPacksPath;
}
// Keep test databases for codeql_test_run to allow subsequent query runs
if (name === 'codeql_test_run') {
options['keep-databases'] = true;
}
// Serialize concurrent database_analyze calls to the same database
// to prevent "cache directory is already locked" errors from the CLI.
// Normalize the lock key via realpath to avoid bypassing serialization
// when the same database is referenced through relative paths, symlinks,
// or different casing.
let dbLock: { ready: Promise<void>; release: () => void } | undefined;
if (name === 'codeql_database_analyze') {
// Use the resolved database path from params (set before positionalArgs
// construction) rather than positionalArgs[0], which may include
// _positional values prepended before the database path.
const resolvedDb = typeof params.database === 'string'
? resolveDatabasePath(params.database)
: (positionalArgs.length > 0 ? positionalArgs[0] : undefined);
if (resolvedDb) {
let lockKey = resolve(resolvedDb);
try { lockKey = realpathSync(lockKey); } catch { /* use resolved path if realpath fails */ }
dbLock = acquireDatabaseLock(lockKey);
await dbLock.ready;
}
}
try {
result = await executeCodeQLCommand(subcommand, options, [...positionalArgs, ...userAdditionalArgs], cwd);
} finally {
dbLock?.release();
}
} else if (command === 'qlt') {
result = await executeQLTCommand(subcommand, options, [...positionalArgs, ...userAdditionalArgs]);
} else {
throw new Error(`Unsupported command: ${command}`);
}
// Post-execution processing for codeql_query_run
if (name === 'codeql_query_run' && result.success && queryLogDir) {
// Ensure params has the output path (may have been auto-set in options)
if (!params.output && options.output) {
params.output = options.output;
}
// Process query results: interpretation (SARIF/graphtext/CSV) + auto-caching
result = await processQueryRunResults(result, params, logger);
}
// Post-execution: generate evaluator log summary for query run / database analyze
if ((name === 'codeql_query_run' || name === 'codeql_database_analyze') && result.success && queryLogDir) {
const evalLogPath = options['evaluator-log'] as string | undefined;
if (evalLogPath && existsSync(evalLogPath)) {
try {
const summaryPath = evalLogPath.replace(/\.jsonl$/, '.summary.jsonl');
// codeql generate log-summary takes positional args: <input> [<result>]
const summaryResult = await executeCodeQLCommand(
'generate log-summary',
{ format: 'predicates' },
[evalLogPath, summaryPath]
);
if (summaryResult.success) {
logger.info(`Generated evaluator log summary at ${summaryPath}`);
}
} catch (error) {
logger.warn(`Failed to generate evaluator log summary: ${error}`);
}
}
}
// Post-execution: cache database_analyze results in query results cache
if (name === 'codeql_database_analyze' && result.success && options.output) {
const resolvedDb = typeof params.database === 'string'
? resolveDatabasePath(params.database)
: params.database;
cacheDatabaseAnalyzeResults({ ...params, database: resolvedDb, output: options.output, format: options.format }, logger);
}
// Process the result
const processedResult = resultProcessor(result, params);
return {
content: [{
type: 'text' as const,
text: processedResult
}],
isError: !result.success
};
} catch (error) {
logger.error(`Error in CLI tool ${name}:`, error);
return {
content: [{
type: 'text' as const,
text: `Failed to execute CLI tool: ${error instanceof Error ? error.message : String(error)}`
}],
isError: true
};
} finally {
// Clean up temporary directories
for (const tempDir of tempDirsToCleanup) {
try {
rmSync(tempDir, { recursive: true, force: true });
logger.info(`Cleaned up temporary directory: ${tempDir}`);
} catch (cleanupError) {
logger.error(`Failed to clean up temporary directory ${tempDir}:`, cleanupError);
}
}
}
}
);
}
/**
* Helper function to create common CodeQL input schemas
*/
export const createCodeQLSchemas = {
database: () => z.string().describe('Path to the CodeQL database'),
query: () => z.string().describe('Path to the CodeQL query file (.ql)'),
output: () => z.string().optional().describe('Output file path'),
outputFormat: () => z.enum(['csv', 'json', 'bqrs', 'sarif-latest', 'sarifv2.1.0']).optional()
.describe('Output format for results'),
language: () => z.string().optional().describe('Programming language'),
threads: () => z.number().optional().describe('Number of threads to use'),
ram: () => z.number().optional().describe('Amount of RAM to use (MB)'),
timeout: () => z.number().optional().describe('Timeout in seconds'),
verbose: () => z.boolean().optional().describe('Enable verbose output'),
additionalArgs: () => z.array(z.string()).optional().describe('Additional command-line arguments'),
positionalArgs: () => z.array(z.string()).optional().describe('Positional arguments')
.transform((val) => ({ _positional: val }))
};
/**
* Helper function to create common QLT input schemas
*/
export const createQLTSchemas = {
language: () => z.string().describe('Programming language'),
output: () => z.string().optional().describe('Output directory or file path'),
template: () => z.string().optional().describe('Template to use'),
name: () => z.string().optional().describe('Name for generated query'),
description: () => z.string().optional().describe('Description for generated query'),
verbose: () => z.boolean().optional().describe('Enable verbose output'),
force: () => z.boolean().optional().describe('Force overwrite existing files'),
additionalArgs: () => z.array(z.string()).optional().describe('Additional command-line arguments')
};
/**
* Create a result processor that formats BQRS output specially
*/
export const createBQRSResultProcessor = () => (
result: CLIExecutionResult,
params: Record<string, unknown>
): string => {
if (!result.success) {
return defaultCLIResultProcessor(result, params);
}
// For BQRS commands, provide more context about the output
let output = result.stdout;
if (params.output) {
output += `\n\nResults saved to: ${params.output}`;
}
if (result.stderr) {
output += `\n\nAdditional information:\n${result.stderr}`;
}
return output;
};
/**
* Create a result processor that formats database creation output
*/
export const createDatabaseResultProcessor = () => (
result: CLIExecutionResult,
params: Record<string, unknown>
): string => {
if (!result.success) {
return defaultCLIResultProcessor(result, params);
}
let output = 'Database creation completed successfully';
if (params.database || params._positional) {
const dbPath = params.database || (Array.isArray(params._positional) ? params._positional[0] : params._positional);
output += `\n\nDatabase location: ${dbPath}`;
}
if (result.stdout) {
output += `\n\nOutput:\n${result.stdout}`;
}
if (result.stderr) {
output += `\n\nAdditional information:\n${result.stderr}`;
}
return output;
};