-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcodeql-development-mcp-server.js
More file actions
executable file
·8196 lines (8092 loc) · 280 KB
/
codeql-development-mcp-server.js
File metadata and controls
executable file
·8196 lines (8092 loc) · 280 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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
// src/utils/logger.ts
var logger;
var init_logger = __esm({
"src/utils/logger.ts"() {
"use strict";
logger = {
info: (message, ...args) => {
console.error(`[INFO] ${(/* @__PURE__ */ new Date()).toISOString()} ${message}`, ...args);
},
error: (message, ...args) => {
console.error(`[ERROR] ${(/* @__PURE__ */ new Date()).toISOString()} ${message}`, ...args);
},
warn: (message, ...args) => {
console.error(`[WARN] ${(/* @__PURE__ */ new Date()).toISOString()} ${message}`, ...args);
},
debug: (message, ...args) => {
if (process.env.DEBUG) {
console.error(`[DEBUG] ${(/* @__PURE__ */ new Date()).toISOString()} ${message}`, ...args);
}
}
};
}
});
// src/lib/cli-executor.ts
var cli_executor_exports = {};
__export(cli_executor_exports, {
buildCodeQLArgs: () => buildCodeQLArgs,
buildQLTArgs: () => buildQLTArgs,
disableTestCommands: () => disableTestCommands,
enableTestCommands: () => enableTestCommands,
executeCLICommand: () => executeCLICommand,
executeCodeQLCommand: () => executeCodeQLCommand,
executeQLTCommand: () => executeQLTCommand,
getCommandHelp: () => getCommandHelp,
getResolvedCodeQLDir: () => getResolvedCodeQLDir,
resetResolvedCodeQLBinary: () => resetResolvedCodeQLBinary,
resolveCodeQLBinary: () => resolveCodeQLBinary,
sanitizeCLIArgument: () => sanitizeCLIArgument,
sanitizeCLIArguments: () => sanitizeCLIArguments,
validateCodeQLBinaryReachable: () => validateCodeQLBinaryReachable,
validateCommandExists: () => validateCommandExists
});
import { execFile } from "child_process";
import { existsSync } from "fs";
import { basename, delimiter, dirname, isAbsolute } from "path";
import { promisify } from "util";
function enableTestCommands() {
testCommands = /* @__PURE__ */ new Set([
"cat",
"echo",
"ls",
"sh",
"sleep"
]);
}
function disableTestCommands() {
testCommands = null;
}
function isCommandAllowed(command) {
return ALLOWED_COMMANDS.has(command) || testCommands !== null && testCommands.has(command);
}
function resolveCodeQLBinary() {
if (resolvedBinaryResult !== void 0) {
return resolvedBinaryResult;
}
const envPath = process.env.CODEQL_PATH;
if (!envPath) {
resolvedCodeQLDir = null;
resolvedBinaryResult = "codeql";
return resolvedBinaryResult;
}
const base = basename(envPath).toLowerCase();
const validBaseNames = ["codeql", "codeql.exe", "codeql.cmd"];
if (!validBaseNames.includes(base)) {
throw new Error(
`CODEQL_PATH must point to a CodeQL CLI binary (expected basename: codeql), got: ${base}`
);
}
if (!isAbsolute(envPath)) {
throw new Error(
`CODEQL_PATH must be an absolute path, got: ${envPath}`
);
}
if (!existsSync(envPath)) {
throw new Error(
`CODEQL_PATH points to a file that does not exist: ${envPath}`
);
}
resolvedCodeQLDir = dirname(envPath);
resolvedBinaryResult = "codeql";
logger.info(`CodeQL CLI resolved via CODEQL_PATH: ${envPath} (dir: ${resolvedCodeQLDir})`);
return resolvedBinaryResult;
}
function getResolvedCodeQLDir() {
return resolvedCodeQLDir;
}
function resetResolvedCodeQLBinary() {
resolvedCodeQLDir = null;
resolvedBinaryResult = void 0;
}
async function validateCodeQLBinaryReachable() {
const binary2 = resolvedBinaryResult ?? "codeql";
const env = { ...process.env };
if (resolvedCodeQLDir) {
env.PATH = resolvedCodeQLDir + delimiter + (env.PATH || "");
}
try {
const { stdout } = await execFileAsync(binary2, ["version", "--format=terse"], {
env,
timeout: 15e3
});
return stdout.trim();
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
throw new Error(
`CodeQL CLI is not reachable (binary: ${binary2}). Ensure codeql is on PATH or set the CODEQL_PATH environment variable to the absolute path of the CodeQL CLI binary. Details: ${message}`
);
}
}
function sanitizeCLIArgument(arg) {
if (arg.includes("\0")) {
throw new Error(`CLI argument contains null byte: argument rejected for security`);
}
if (DANGEROUS_CONTROL_CHARS.test(arg)) {
throw new Error(`CLI argument contains control characters: argument rejected for security`);
}
return arg;
}
function sanitizeCLIArguments(args) {
return args.map(sanitizeCLIArgument);
}
function getSafeEnvironment(additionalEnv) {
const safeEnv = {};
for (const key of SAFE_ENV_VARS) {
if (process.env[key] !== void 0) {
safeEnv[key] = process.env[key];
}
}
for (const [key, value] of Object.entries(process.env)) {
if (value !== void 0 && SAFE_ENV_PREFIXES.some((prefix) => key.startsWith(prefix))) {
safeEnv[key] = value;
}
}
if (resolvedCodeQLDir && safeEnv.PATH) {
safeEnv.PATH = `${resolvedCodeQLDir}${delimiter}${safeEnv.PATH}`;
} else if (resolvedCodeQLDir) {
safeEnv.PATH = resolvedCodeQLDir;
}
if (additionalEnv) {
Object.assign(safeEnv, additionalEnv);
}
return safeEnv;
}
async function executeCLICommand(options) {
try {
const { command, args, cwd, timeout = 3e5, env } = options;
if (!isCommandAllowed(command)) {
throw new Error(`Command not allowed: ${command}. Only whitelisted commands can be executed.`);
}
if (command.includes(";") || command.includes("|") || command.includes("&") || command.includes("$") || command.includes("`") || command.includes("\n") || command.includes("\r")) {
throw new Error(`Invalid command: contains shell metacharacters: ${command}`);
}
const sanitizedArgs = sanitizeCLIArguments(args);
logger.info(`Executing CLI command: ${command}`, { args: sanitizedArgs, cwd, timeout });
const execOptions = {
cwd,
timeout,
env: getSafeEnvironment(env)
};
const { stdout, stderr } = await execFileAsync(command, sanitizedArgs, execOptions);
return {
stdout,
stderr,
success: true,
exitCode: 0
};
} catch (error) {
logger.error("CLI command execution failed:", error);
const err = error;
const errorMessage = err instanceof Error ? err.message : String(error);
const exitCode = err.code || 1;
return {
stdout: err.stdout || "",
stderr: err.stderr || errorMessage,
success: false,
error: errorMessage,
exitCode
};
}
}
function buildCodeQLArgs(subcommand, options) {
const args = [subcommand];
const singleLetterParams = /* @__PURE__ */ new Set(["t", "o", "v", "q", "h", "J"]);
for (const [key, value] of Object.entries(options)) {
if (value === void 0 || value === null) {
continue;
}
const isSingleLetter = key.length === 1 && singleLetterParams.has(key);
if (typeof value === "boolean") {
if (value) {
args.push(isSingleLetter ? `-${key}` : `--${key}`);
}
} else if (Array.isArray(value)) {
for (const item of value) {
if (isSingleLetter) {
args.push(`-${key}=${String(item)}`);
} else {
args.push(`--${key}=${String(item)}`);
}
}
} else {
if (isSingleLetter) {
args.push(`-${key}=${String(value)}`);
} else {
args.push(`--${key}=${String(value)}`);
}
}
}
return args;
}
function buildQLTArgs(subcommand, options) {
const args = [subcommand];
for (const [key, value] of Object.entries(options)) {
if (value === void 0 || value === null) {
continue;
}
if (typeof value === "boolean") {
if (value) {
args.push(`--${key}`);
}
} else if (Array.isArray(value)) {
for (const item of value) {
args.push(`--${key}`, String(item));
}
} else {
args.push(`--${key}`, String(value));
}
}
return args;
}
async function executeCodeQLCommand(subcommand, options, additionalArgs = [], cwd) {
const args = buildCodeQLArgs(subcommand, options);
args.push(...additionalArgs);
return executeCLICommand({
command: "codeql",
args,
cwd
});
}
async function executeQLTCommand(subcommand, options, additionalArgs = []) {
const args = buildQLTArgs(subcommand, options);
args.push(...additionalArgs);
return executeCLICommand({
command: "qlt",
args
});
}
async function getCommandHelp(command, subcommand) {
const args = subcommand ? [subcommand, "--help"] : ["--help"];
const result = await executeCLICommand({
command,
args
});
return result.stdout || result.stderr || "No help available";
}
async function validateCommandExists(command) {
try {
const result = await executeCLICommand({
command: "which",
args: [command]
});
return result.success;
} catch {
return false;
}
}
var execFileAsync, ALLOWED_COMMANDS, testCommands, SAFE_ENV_VARS, SAFE_ENV_PREFIXES, DANGEROUS_CONTROL_CHARS, resolvedCodeQLDir, resolvedBinaryResult;
var init_cli_executor = __esm({
"src/lib/cli-executor.ts"() {
"use strict";
init_logger();
execFileAsync = promisify(execFile);
ALLOWED_COMMANDS = /* @__PURE__ */ new Set([
"codeql",
"git",
"node",
"npm",
"qlt",
"which"
]);
testCommands = null;
SAFE_ENV_VARS = [
"HOME",
// User home directory
"LANG",
// Locale setting
"LC_ALL",
// Locale setting
"LC_CTYPE",
// Locale setting
"PATH",
// Required to find executables
"SHELL",
// User's shell (Unix)
"TEMP",
// Temporary directory (Windows)
"TERM",
// Terminal type (Unix)
"TMP",
// Temporary directory (Windows)
"TMPDIR",
// Temporary directory (Unix)
"USER",
// Current user (Unix)
"USERNAME"
// Current user (Windows)
];
SAFE_ENV_PREFIXES = [
"CODEQL_",
// CodeQL-specific variables
"NODE_"
// Node.js-specific variables (for npm, etc.)
];
DANGEROUS_CONTROL_CHARS = /[\x01-\x08\x0B\x0C\x0E-\x1F]/;
resolvedCodeQLDir = null;
}
});
// src/utils/package-paths.ts
var package_paths_exports = {};
__export(package_paths_exports, {
getPackageRootDir: () => getPackageRootDir,
getPackageVersion: () => getPackageVersion,
getUserWorkspaceDir: () => getUserWorkspaceDir,
getWorkspaceRootDir: () => getWorkspaceRootDir,
packageRootDir: () => packageRootDir,
resolveToolQueryPackPath: () => resolveToolQueryPackPath,
workspaceRootDir: () => workspaceRootDir
});
import { dirname as dirname3, resolve } from "path";
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
import { fileURLToPath } from "url";
function isRunningFromSource(dir) {
const normalized = dir.replace(/\\/g, "/");
return /\/src(\/[^/]+)?$/.test(normalized);
}
function getPackageRootDir(currentDir = __dirname) {
return isRunningFromSource(currentDir) ? resolve(currentDir, "..", "..") : resolve(currentDir, "..");
}
function getWorkspaceRootDir(packageRoot) {
const pkgRoot = packageRoot ?? getPackageRootDir();
const parentDir = resolve(pkgRoot, "..");
try {
const parentPkgPath = resolve(parentDir, "package.json");
if (existsSync2(parentPkgPath)) {
const parentPkg = JSON.parse(readFileSync2(parentPkgPath, "utf8"));
if (parentPkg.workspaces) {
return parentDir;
}
}
} catch {
}
return pkgRoot;
}
function resolveToolQueryPackPath(language, packageRoot) {
const pkgRoot = packageRoot ?? getPackageRootDir();
return resolve(pkgRoot, "ql", language, "tools", "src");
}
function getPackageVersion() {
if (_cachedVersion !== void 0) return _cachedVersion;
try {
const pkgPath = resolve(getPackageRootDir(), "package.json");
const pkg = JSON.parse(readFileSync2(pkgPath, "utf8"));
_cachedVersion = pkg.version ?? "0.0.0";
} catch {
_cachedVersion = "0.0.0";
}
return _cachedVersion;
}
function getUserWorkspaceDir() {
if (process.env.CODEQL_MCP_WORKSPACE) {
return process.env.CODEQL_MCP_WORKSPACE;
}
if (workspaceRootDir === packageRootDir) {
return process.cwd();
}
return workspaceRootDir;
}
var __filename, __dirname, _cachedVersion, packageRootDir, workspaceRootDir;
var init_package_paths = __esm({
"src/utils/package-paths.ts"() {
"use strict";
__filename = fileURLToPath(import.meta.url);
__dirname = dirname3(__filename);
packageRootDir = getPackageRootDir();
workspaceRootDir = getWorkspaceRootDir(packageRootDir);
}
});
// src/codeql-development-mcp-server.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import { resolve as resolve10 } from "path";
import { pathToFileURL as pathToFileURL3 } from "url";
// src/tools/codeql/bqrs-decode.ts
import { z as z2 } from "zod";
// src/lib/cli-tool-registry.ts
init_cli_executor();
init_logger();
import { z } from "zod";
// src/lib/query-results-evaluator.ts
init_cli_executor();
init_logger();
import { writeFileSync, readFileSync } from "fs";
import { dirname as dirname2, isAbsolute as isAbsolute2 } from "path";
import { mkdirSync } from "fs";
var BUILT_IN_EVALUATORS = {
"json-decode": "JSON format decoder for query results",
"csv-decode": "CSV format decoder for query results",
"mermaid-graph": "Mermaid diagram generator for @kind graph queries (like PrintAST)"
};
async function extractQueryMetadata(queryPath) {
try {
const queryContent = readFileSync(queryPath, "utf-8");
const metadata = {};
const kindMatch = queryContent.match(/@kind\s+([^\s]+)/);
if (kindMatch) metadata.kind = kindMatch[1];
const nameMatch = queryContent.match(/@name\s+(.+)/);
if (nameMatch) metadata.name = nameMatch[1].trim();
const descMatch = queryContent.match(/@description\s+(.+)/);
if (descMatch) metadata.description = descMatch[1].trim();
const idMatch = queryContent.match(/@id\s+(.+)/);
if (idMatch) metadata.id = idMatch[1].trim();
const tagsMatch = queryContent.match(/@tags\s+(.+)/);
if (tagsMatch) {
metadata.tags = tagsMatch[1].split(/\s+/).filter((t) => t.length > 0);
}
return metadata;
} catch (error) {
logger.error("Failed to extract query metadata:", error);
return {};
}
}
async function evaluateWithJsonDecoder(bqrsPath, outputPath) {
try {
const result = await executeCodeQLCommand(
"bqrs decode",
{ format: "json" },
[bqrsPath]
);
if (!result.success) {
return {
success: false,
error: `Failed to decode BQRS file: ${result.stderr || result.error}`
};
}
const defaultOutputPath = outputPath || bqrsPath.replace(".bqrs", ".json");
mkdirSync(dirname2(defaultOutputPath), { recursive: true });
writeFileSync(defaultOutputPath, result.stdout);
return {
success: true,
outputPath: defaultOutputPath,
content: result.stdout
};
} catch (error) {
return {
success: false,
error: `JSON evaluation failed: ${error}`
};
}
}
async function evaluateWithCsvDecoder(bqrsPath, outputPath) {
try {
const result = await executeCodeQLCommand(
"bqrs decode",
{ format: "csv" },
[bqrsPath]
);
if (!result.success) {
return {
success: false,
error: `Failed to decode BQRS file: ${result.stderr || result.error}`
};
}
const defaultOutputPath = outputPath || bqrsPath.replace(".bqrs", ".csv");
mkdirSync(dirname2(defaultOutputPath), { recursive: true });
writeFileSync(defaultOutputPath, result.stdout);
return {
success: true,
outputPath: defaultOutputPath,
content: result.stdout
};
} catch (error) {
return {
success: false,
error: `CSV evaluation failed: ${error}`
};
}
}
async function evaluateWithMermaidGraph(bqrsPath, queryPath, outputPath) {
try {
const metadata = await extractQueryMetadata(queryPath);
if (metadata.kind !== "graph") {
logger.error(`Query is not a graph query (kind: ${metadata.kind}), mermaid-graph evaluation is only for @kind graph queries`);
return {
success: false,
error: `Query is not a graph query (kind: ${metadata.kind}), mermaid-graph evaluation is only for @kind graph queries`
};
}
const jsonResult = await executeCodeQLCommand(
"bqrs decode",
{ format: "json" },
[bqrsPath]
);
if (!jsonResult.success) {
return {
success: false,
error: `Failed to decode BQRS file: ${jsonResult.stderr || jsonResult.error}`
};
}
let queryResults;
try {
queryResults = JSON.parse(jsonResult.stdout);
} catch (parseError) {
return {
success: false,
error: `Failed to parse query results JSON: ${parseError}`
};
}
const mermaidContent = generateMermaidFromGraphResults(queryResults, metadata);
const defaultOutputPath = outputPath || bqrsPath.replace(".bqrs", ".md");
mkdirSync(dirname2(defaultOutputPath), { recursive: true });
writeFileSync(defaultOutputPath, mermaidContent);
return {
success: true,
outputPath: defaultOutputPath,
content: mermaidContent
};
} catch (error) {
return {
success: false,
error: `Mermaid graph evaluation failed: ${error}`
};
}
}
function generateMermaidFromGraphResults(queryResults, metadata) {
const queryName = sanitizeMarkdown(metadata.name || "CodeQL Query Results");
const queryDesc = sanitizeMarkdown(metadata.description || "Graph visualization of CodeQL query results");
let mermaidContent = `# ${queryName}
${queryDesc}
`;
if (!queryResults || typeof queryResults !== "object") {
mermaidContent += "```mermaid\ngraph TD\n A[No Results]\n```\n";
return mermaidContent;
}
const tuples = queryResults.tuples || queryResults;
if (!Array.isArray(tuples) || tuples.length === 0) {
mermaidContent += "```mermaid\ngraph TD\n A[No Graph Data]\n```\n";
return mermaidContent;
}
mermaidContent += "```mermaid\ngraph TD\n";
const nodes = /* @__PURE__ */ new Set();
const edges = /* @__PURE__ */ new Set();
tuples.forEach((tuple, index) => {
if (Array.isArray(tuple) && tuple.length >= 2) {
const source = sanitizeNodeId(tuple[0]?.toString() || `node_${index}_0`);
const target = sanitizeNodeId(tuple[1]?.toString() || `node_${index}_1`);
const label = tuple[2]?.toString() || "";
nodes.add(source);
nodes.add(target);
const edgeId = `${source}_${target}`;
if (!edges.has(edgeId)) {
if (label) {
mermaidContent += ` ${source} -->|${sanitizeLabel(label)}| ${target}
`;
} else {
mermaidContent += ` ${source} --> ${target}
`;
}
edges.add(edgeId);
}
} else if (typeof tuple === "object" && tuple !== null) {
const source = sanitizeNodeId(tuple.source?.toString() || tuple.from?.toString() || `node_${index}_src`);
const target = sanitizeNodeId(tuple.target?.toString() || tuple.to?.toString() || `node_${index}_tgt`);
const label = tuple.label?.toString() || tuple.relation?.toString() || "";
nodes.add(source);
nodes.add(target);
const edgeId = `${source}_${target}`;
if (!edges.has(edgeId)) {
if (label) {
mermaidContent += ` ${source} -->|${sanitizeLabel(label)}| ${target}
`;
} else {
mermaidContent += ` ${source} --> ${target}
`;
}
edges.add(edgeId);
}
}
});
if (edges.size === 0 && nodes.size > 0) {
const nodeArray = Array.from(nodes).slice(0, 10);
nodeArray.forEach((node, index) => {
if (index === 0) {
mermaidContent += ` ${node}[${sanitizeLabel(node)}]
`;
} else {
mermaidContent += ` ${nodeArray[0]} --> ${node}
`;
}
});
}
mermaidContent += "```\n\n";
mermaidContent += `## Query Statistics
`;
mermaidContent += `- Total nodes: ${nodes.size}
`;
mermaidContent += `- Total edges: ${edges.size}
`;
mermaidContent += `- Total tuples processed: ${tuples.length}
`;
return mermaidContent;
}
function sanitizeNodeId(id) {
return id.replace(/[^a-zA-Z0-9_]/g, "_").replace(/^(\d)/, "n$1").substring(0, 50);
}
function sanitizeLabel(label) {
return label.replace(/[|"`<>\n\r\t]/g, "").replace(/\s+/g, " ").trim().substring(0, 30);
}
function sanitizeMarkdown(content) {
return content.replace(/[<>"`]/g, "").replace(/\n/g, " ").replace(/\s+/g, " ").trim().substring(0, 100);
}
async function evaluateQueryResults(bqrsPath, queryPath, evaluationFunction, outputPath) {
try {
const evalFunc = evaluationFunction || "json-decode";
logger.info(`Evaluating query results with function: ${evalFunc}`);
switch (evalFunc) {
case "json-decode":
return await evaluateWithJsonDecoder(bqrsPath, outputPath);
case "csv-decode":
return await evaluateWithCsvDecoder(bqrsPath, outputPath);
case "mermaid-graph":
return await evaluateWithMermaidGraph(bqrsPath, queryPath, outputPath);
default:
if (isAbsolute2(evalFunc)) {
return await evaluateWithCustomScript(bqrsPath, queryPath, evalFunc, outputPath);
} else {
return {
success: false,
error: `Unknown evaluation function: ${evalFunc}. Available built-in functions: ${Object.keys(BUILT_IN_EVALUATORS).join(", ")}`
};
}
}
} catch (error) {
return {
success: false,
error: `Query evaluation failed: ${error}`
};
}
}
async function evaluateWithCustomScript(_bqrsPath, _queryPath, _scriptPath, _outputPath) {
return {
success: false,
error: "Custom evaluation scripts are not yet implemented"
};
}
// src/lib/log-directory-manager.ts
import { mkdirSync as mkdirSync3, existsSync as existsSync3 } from "fs";
import { join as join2, resolve as resolve3 } from "path";
import { randomBytes } from "crypto";
// src/utils/temp-dir.ts
init_package_paths();
import { mkdirSync as mkdirSync2, mkdtempSync } from "fs";
import { isAbsolute as isAbsolute3, join, resolve as resolve2 } from "path";
var PROJECT_TMP_BASE = process.env.CODEQL_MCP_TMP_DIR ? isAbsolute3(process.env.CODEQL_MCP_TMP_DIR) ? process.env.CODEQL_MCP_TMP_DIR : resolve2(process.cwd(), process.env.CODEQL_MCP_TMP_DIR) : join(getPackageRootDir(), ".tmp");
function getProjectTmpBase() {
mkdirSync2(PROJECT_TMP_BASE, { recursive: true });
return PROJECT_TMP_BASE;
}
function createProjectTempDir(prefix) {
const base = getProjectTmpBase();
return mkdtempSync(join(base, prefix));
}
function getProjectTmpDir(name) {
const dir = join(getProjectTmpBase(), name);
mkdirSync2(dir, { recursive: true });
return dir;
}
// src/lib/log-directory-manager.ts
function ensurePathWithinBase(baseDir, targetPath) {
const absBase = resolve3(baseDir);
const absTarget = resolve3(targetPath);
if (!absTarget.startsWith(absBase + "/") && absTarget !== absBase) {
throw new Error(`Provided log directory is outside the allowed base directory: ${absBase}`);
}
return absTarget;
}
function getOrCreateLogDirectory(logDir) {
const baseLogDir = process.env.CODEQL_QUERY_LOG_DIR || getProjectTmpDir("query-logs");
if (logDir) {
const absLogDir = ensurePathWithinBase(baseLogDir, logDir);
if (!existsSync3(absLogDir)) {
mkdirSync3(absLogDir, { recursive: true });
}
return absLogDir;
}
if (!existsSync3(baseLogDir)) {
mkdirSync3(baseLogDir, { recursive: true });
}
const timestamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
const uniqueId = randomBytes(4).toString("hex");
const uniqueLogDir = join2(baseLogDir, `query-run-${timestamp2}-${uniqueId}`);
mkdirSync3(uniqueLogDir, { recursive: true });
return uniqueLogDir;
}
// src/lib/cli-tool-registry.ts
init_package_paths();
import { writeFileSync as writeFileSync2, rmSync, existsSync as existsSync4, mkdirSync as mkdirSync4 } from "fs";
import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute4, join as join3, resolve as resolve4 } from "path";
var defaultCLIResultProcessor = (result, _params) => {
if (!result.success) {
return `Command failed (exit code ${result.exitCode || "unknown"}):
${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;
};
function registerCLITool(server, definition) {
const {
name,
description,
command,
subcommand,
inputSchema,
resultProcessor = defaultCLIResultProcessor
} = definition;
server.tool(
name,
description,
inputSchema,
async (params) => {
const tempDirsToCleanup = [];
try {
logger.info(`Executing CLI tool: ${name}`, { command, subcommand, params });
const formatShouldBePassedToCLI = name === "codeql_bqrs_interpret" || name === "codeql_bqrs_decode" || name === "codeql_generate_query-help" || name === "codeql_database_analyze";
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;
const options = { ...params };
Object.keys(extractedParams).forEach((key) => delete options[key]);
let positionalArgs = Array.isArray(_positional) ? _positional : [_positional];
if (files && Array.isArray(files)) {
positionalArgs = [...positionalArgs, ...files];
}
if (file && name.startsWith("codeql_bqrs_")) {
positionalArgs = [...positionalArgs, file];
}
if (qlref && name === "codeql_resolve_qlref") {
positionalArgs = [...positionalArgs, qlref];
}
if (options.database && name === "codeql_resolve_database") {
positionalArgs = [...positionalArgs, options.database];
delete options.database;
}
if (options.database && name === "codeql_database_create") {
positionalArgs = [...positionalArgs, options.database];
delete options.database;
}
if (name === "codeql_database_analyze") {
if (options.database) {
positionalArgs = [...positionalArgs, options.database];
delete options.database;
}
if (options.queries) {
positionalArgs = [...positionalArgs, options.queries];
delete options.queries;
}
}
if (query && name === "codeql_generate_query-help") {
positionalArgs = [...positionalArgs, query];
}
if (dir && name === "codeql_pack_ls") {
positionalArgs = [...positionalArgs, dir];
}
switch (name) {
case "codeql_test_accept":
case "codeql_test_extract":
case "codeql_test_run":
case "codeql_resolve_tests":
if (tests && Array.isArray(tests)) {
const userDir = getUserWorkspaceDir();
positionalArgs = [...positionalArgs, ...tests.map(
(t) => isAbsolute4(t) ? t : resolve4(userDir, t)
)];
}
break;
case "codeql_query_run": {
if (options.database && typeof options.database === "string" && !isAbsolute4(options.database)) {
options.database = resolve4(getUserWorkspaceDir(), options.database);
logger.info(`Resolved database path to: ${options.database}`);
}
const resolvedQuery = await resolveQueryPath(params, logger);
if (resolvedQuery) {
positionalArgs = [...positionalArgs, resolvedQuery];
} else if (query) {
positionalArgs = [...positionalArgs, query];
}
if (queryName === "PrintAST" && sourceFiles) {
const filePaths = sourceFiles.split(",").map((f) => f.trim());
let tempDir;
let csvPath;
try {
tempDir = createProjectTempDir("codeql-external-");
tempDirsToCleanup.push(tempDir);
csvPath = join3(tempDir, "selectedSourceFiles.csv");
const csvContent = filePaths.join("\n") + "\n";
writeFileSync2(csvPath, csvContent, "utf8");
} catch (err) {
logger.error(`Failed to create external predicate CSV for PrintAST query at path ${csvPath || "[unknown]"}: ${err instanceof Error ? err.message : String(err)}`);
throw err;
}
const currentExternal = options.external || [];
const externalArray = Array.isArray(currentExternal) ? currentExternal : [currentExternal];
externalArray.push(`selectedSourceFiles=${csvPath}`);
options.external = externalArray;
logger.info(`Created external predicate CSV at ${csvPath} for files: ${filePaths.join(", ")}`);
}
if (queryName === "CallGraphFrom" && sourceFunction) {
const functionNames = sourceFunction.split(",").map((f) => f.trim());
let tempDir;
let csvPath;
try {
tempDir = createProjectTempDir("codeql-external-");
tempDirsToCleanup.push(tempDir);
csvPath = join3(tempDir, "sourceFunction.csv");
const csvContent = functionNames.join("\n") + "\n";
writeFileSync2(csvPath, csvContent, "utf8");
} catch (err) {
logger.error(`Failed to create external predicate CSV for CallGraphFrom query at path ${csvPath || "[unknown]"}: ${err instanceof Error ? err.message : String(err)}`);
throw err;
}
const currentExternal = options.external || [];
const externalArray = Array.isArray(currentExternal) ? currentExternal : [currentExternal];
externalArray.push(`sourceFunction=${csvPath}`);
options.external = externalArray;
logger.info(`Created external predicate CSV at ${csvPath} for functions: ${functionNames.join(", ")}`);
}
if (queryName === "CallGraphTo" && targetFunction) {
const functionNames = targetFunction.split(",").map((f) => f.trim());
let tempDir;
let csvPath;
try {
tempDir = createProjectTempDir("codeql-external-");
tempDirsToCleanup.push(tempDir);
csvPath = join3(tempDir, "targetFunction.csv");
const csvContent = functionNames.join("\n") + "\n";
writeFileSync2(csvPath, csvContent, "utf8");
} catch (err) {
logger.error(`Failed to create external predicate CSV for CallGraphTo query at path ${csvPath || "[unknown]"}: ${err instanceof Error ? err.message : String(err)}`);
throw err;
}
const currentExternal = options.external || [];
const externalArray = Array.isArray(currentExternal) ? currentExternal : [currentExternal];
externalArray.push(`targetFunction=${csvPath}`);
options.external = externalArray;
logger.info(`Created external predicate CSV at ${csvPath} for functions: ${functionNames.join(", ")}`);
}
break;
}
case "codeql_query_compile":
case "codeql_resolve_metadata":
if (query) {
positionalArgs = [...positionalArgs, query];
}
break;
case "codeql_resolve_queries":
if (directory) {
positionalArgs = [...positionalArgs, directory];
}
break;
default:
break;
}
let queryLogDir;
if (name === "codeql_query_run" || name === "codeql_test_run") {
queryLogDir = getOrCreateLogDirectory(customLogDir);
logger.info(`Using log directory for ${name}: ${queryLogDir}`);
const timestampPath = join3(queryLogDir, "timestamp");
writeFileSync2(timestampPath, Date.now().toString(), "utf8");
options.logdir = queryLogDir;
if (!options.verbosity) {
options.verbosity = "progress+";
}
if (name === "codeql_query_run") {
if (!options["evaluator-log"]) {
options["evaluator-log"] = join3(queryLogDir, "evaluator-log.jsonl");
}
if (!options.output) {
options.output = join3(queryLogDir, "results.bqrs");
}
}