-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathworkflow-prompts.ts
More file actions
1153 lines (1035 loc) · 36.9 KB
/
workflow-prompts.ts
File metadata and controls
1153 lines (1035 loc) · 36.9 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
/**
* MCP Server workflow prompts for CodeQL development
*
* All prompt content is loaded from .prompt.md files in this directory.
* This file only handles prompt registration and parameter processing.
*/
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { basename, isAbsolute, normalize, relative, resolve, sep } from 'path';
import { existsSync } from 'fs';
import { loadPromptTemplate, processPromptTemplate } from './prompt-loader';
import { getUserWorkspaceDir } from '../utils/package-paths';
import { logger } from '../utils/logger';
/** Supported CodeQL languages for tools queries */
export const SUPPORTED_LANGUAGES = [
'actions',
'cpp',
'csharp',
'go',
'java',
'javascript',
'python',
'ruby',
'swift'
] as const;
// ────────────────────────────────────────────────────────────────────────────
// File-path resolution for prompt parameters
// ────────────────────────────────────────────────────────────────────────────
/**
* Result of resolving a user-supplied file path in a prompt parameter.
*
* `resolvedPath` is always set (to the best-effort absolute path).
* `warning` is set only when the path is problematic — the caller should
* embed it in the prompt response so the user sees a clear message.
*/
export interface PromptFilePathResult {
resolvedPath: string;
warning?: string;
}
/**
* Resolve a user-supplied file path for a prompt parameter.
*
* Relative paths are resolved against `workspaceRoot` (which defaults to
* `getUserWorkspaceDir()`). The function never throws — it returns a
* `warning` string when the path is empty, contains traversal sequences, or
* does not exist on disk.
*
* @param filePath - The raw path value from the prompt parameter.
* @param workspaceRoot - Directory to resolve relative paths against.
* @returns An object with the resolved absolute path and an optional warning.
*/
export function resolvePromptFilePath(
filePath: string,
workspaceRoot?: string,
): PromptFilePathResult {
if (!filePath || filePath.trim() === '') {
return {
resolvedPath: filePath ?? '',
warning: '⚠ **File path is empty.** Please provide a valid file path.',
};
}
const effectiveRoot = workspaceRoot ?? getUserWorkspaceDir();
// Normalise first to collapse any . or .. segments.
const normalizedPath = normalize(filePath);
// Resolve to absolute path.
const absolutePath = isAbsolute(normalizedPath)
? normalizedPath
: resolve(effectiveRoot, normalizedPath);
// Verify the resolved path stays within the workspace root.
// This catches path traversal (e.g. "../../etc/passwd") after full
// resolution rather than relying on a fragile substring check.
const rel = relative(effectiveRoot, absolutePath);
if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
return {
resolvedPath: absolutePath,
warning: `⚠ **File path** \`${filePath}\` **resolves outside the workspace root.** Resolved to: \`${absolutePath}\``,
};
}
// Check existence on disk (advisory only — the resolved path is always
// returned so that downstream tools can attempt the operation themselves
// and surface their own errors).
if (!existsSync(absolutePath)) {
return {
resolvedPath: absolutePath,
warning: `⚠ **File path** \`${filePath}\` **does not exist.** Resolved to: \`${absolutePath}\``,
};
}
return { resolvedPath: absolutePath };
}
// ────────────────────────────────────────────────────────────────────────────
// Exported parameter schemas for each workflow prompt.
//
// Extracting the schemas makes it easy to unit-test required vs optional
// validation independently of the MCP server registration.
//
// **Convention for VS Code UX consistency**:
// Every prompt MUST expose at least one parameter – even if all parameters
// are optional – so that VS Code always displays the parameter input dialog
// and allows the user to customize the prompt before Copilot Chat processes
// it. The `description` field on each Zod schema member doubles as the
// placeholder text shown in the VS Code input box.
// ────────────────────────────────────────────────────────────────────────────
/**
* Schema for test_driven_development prompt parameters.
*
* - `language` is **required** – the TDD workflow is language-specific.
* - `queryName` is optional – defaults to '[QueryName]' if omitted.
*/
export const testDrivenDevelopmentSchema = z.object({
language: z
.enum(SUPPORTED_LANGUAGES)
.describe('Programming language for the query'),
queryName: z
.string()
.optional()
.describe('Name of the query to develop'),
});
/**
* Schema for tools_query_workflow prompt parameters.
*
* - `language` and `database` are **required**.
* - `sourceFiles`, `sourceFunction`, `targetFunction` are optional context.
*/
export const toolsQueryWorkflowSchema = z.object({
database: z
.string()
.describe('Path to the CodeQL database'),
language: z
.enum(SUPPORTED_LANGUAGES)
.describe('Programming language for the tools queries'),
sourceFiles: z
.string()
.optional()
.describe('Comma-separated source file names for PrintAST (e.g., "main.js,utils.js")'),
sourceFunction: z
.string()
.optional()
.describe('Function name for PrintCFG or CallGraphFrom (e.g., "processData")'),
targetFunction: z
.string()
.optional()
.describe('Function name for CallGraphTo (e.g., "validate")'),
});
/**
* Schema for workshop_creation_workflow prompt parameters.
* Uses z.coerce.number() for numStages to handle string inputs from VSCode slash commands.
*
* - `queryPath` and `language` are **required**.
* - `workshopName` and `numStages` are optional.
*/
export const workshopCreationWorkflowSchema = z.object({
queryPath: z
.string()
.describe('Path to the production-grade CodeQL query (.ql or .qlref)'),
language: z
.enum(SUPPORTED_LANGUAGES)
.describe('Programming language of the query'),
workshopName: z
.string()
.optional()
.describe('Name for the workshop directory'),
numStages: z
.coerce.number()
.optional()
.describe('Number of incremental stages (default: 4-8)'),
});
/**
* Schema for ql_tdd_basic prompt parameters.
*
* - `language` is **required** – TDD workflows are language-specific.
* - `queryName` is optional.
*/
export const qlTddBasicSchema = z.object({
language: z
.enum(SUPPORTED_LANGUAGES)
.describe('Programming language for the query'),
queryName: z
.string()
.optional()
.describe('Name of the query to develop'),
});
/**
* Schema for ql_tdd_advanced prompt parameters.
*
* - `language` is **required** – TDD workflows are language-specific.
* - `database` and `queryName` are optional.
*/
export const qlTddAdvancedSchema = z.object({
database: z
.string()
.optional()
.describe('Path to the CodeQL database for analysis'),
language: z
.enum(SUPPORTED_LANGUAGES)
.describe('Programming language for the query'),
queryName: z
.string()
.optional()
.describe('Name of the query to develop'),
});
/**
* Schema for sarif_rank_false_positives / sarif_rank_true_positives.
*
* - `sarifPath` is **required** – the prompt needs a SARIF file to analyze.
* - `queryId` is optional – narrows analysis to a specific rule.
*/
export const sarifRankSchema = z.object({
queryId: z
.string()
.optional()
.describe('CodeQL query/rule identifier'),
sarifPath: z
.string()
.describe('Path to the SARIF file to analyze'),
});
/**
* Schema for run_query_and_summarize_false_positives prompt parameters.
*
* - `queryPath` is **required** – the prompt needs a query to analyze.
*/
export const describeFalsePositivesSchema = z.object({
queryPath: z
.string()
.describe('Path to the CodeQL query file'),
});
/**
* Schema for explain_codeql_query prompt parameters.
*
* - `queryPath` and `language` are **required**.
* - `databasePath` is optional – a database may also be derived from tests.
*/
export const explainCodeqlQuerySchema = z.object({
databasePath: z
.string()
.optional()
.describe('Path to a CodeQL database for profiling'),
language: z
.enum(SUPPORTED_LANGUAGES)
.describe('Programming language of the query'),
queryPath: z
.string()
.describe('Path to the CodeQL query file (.ql or .qlref)'),
});
/**
* Schema for document_codeql_query prompt parameters.
*
* - `queryPath` and `language` are **required**.
*/
export const documentCodeqlQuerySchema = z.object({
language: z
.enum(SUPPORTED_LANGUAGES)
.describe('Programming language of the query'),
queryPath: z
.string()
.describe('Path to the CodeQL query file (.ql or .qlref)'),
});
/**
* Schema for check_for_duplicated_code prompt parameters.
*
* - `queryPath` is **required** – the file to audit.
* - `workspaceUri` is optional – if omitted the agent will derive it from the
* pack root containing the query.
*/
export const checkForDuplicatedCodeSchema = z.object({
queryPath: z
.string()
.describe('Path to the .ql or .qll file to audit for duplicated definitions'),
workspaceUri: z
.string()
.optional()
.describe('Pack root directory containing codeql-pack.yml (for LSP resolution)'),
});
/**
* Schema for find_overlapping_queries prompt parameters.
*
* - `queryDescription` is **required** – describes the new query's purpose.
* - `language` is **required** – the target CodeQL language.
* - `packRoot` is optional – directory containing `codeql-pack.yml` for the
* pack that will own the new query.
*/
export const findOverlappingQueriesSchema = z.object({
queryDescription: z
.string()
.describe(
'Description of the new query\'s purpose and target constructs '
+ '(e.g. "detect placement-new on types with non-trivial destructors")'
),
language: z
.enum(SUPPORTED_LANGUAGES)
.describe('Target language for the new query (e.g. cpp, java, python)'),
packRoot: z
.string()
.optional()
.describe('Directory containing codeql-pack.yml for the pack that will own the new query'),
});
/**
* Schema for ql_lsp_iterative_development prompt parameters.
*
* - `language` and `queryPath` are **required** – LSP tools need both.
* - `workspaceUri` is optional – defaults to the pack root.
*/
export const qlLspIterativeDevelopmentSchema = z.object({
language: z
.enum(SUPPORTED_LANGUAGES)
.describe('Programming language for the query'),
queryPath: z
.string()
.describe('Path to the query file being developed'),
workspaceUri: z
.string()
.optional()
.describe('Workspace URI for LSP dependency resolution'),
});
// ────────────────────────────────────────────────────────────────────────────
// Error-recovery utilities for prompt handlers
// ────────────────────────────────────────────────────────────────────────────
/**
* Prompt result shape returned by every workflow prompt handler.
*/
interface PromptResult {
messages: Array<{
role: 'user';
content: { type: 'text'; text: string };
}>;
}
/**
* Create a permissive copy of a Zod schema shape for MCP registration.
*
* The MCP SDK validates prompt arguments against the registered schema
* **before** invoking the handler. If validation fails, the SDK throws a
* raw `McpError(-32602)` with a cryptic JSON dump that is poor UX when
* surfaced as a VS Code slash-command error.
*
* This function converts every `z.enum()` field in the shape to a
* `z.string()` (preserving `.describe()` and `.optional()` modifiers) so
* that the SDK never rejects user input at the protocol layer. The strict
* enum validation then happens inside `createSafePromptHandler()`, which
* can return a user-friendly inline error instead of throwing.
*
* All non-enum field types are passed through unchanged.
*/
export function toPermissiveShape(
shape: Record<string, z.ZodTypeAny>,
): Record<string, z.ZodTypeAny> {
const permissive: Record<string, z.ZodTypeAny> = {};
for (const [key, zodType] of Object.entries(shape)) {
permissive[key] = widenZodType(zodType);
}
return permissive;
}
/**
* Widen a single Zod type for permissive registration:
*
* - Replace z.enum() with z.string() (so any string value passes SDK
* validation; the handler validates the enum via createSafePromptHandler)
* - Preserve optional/required status and .describe() metadata so
* VS Code correctly marks fields in the slash-command input dialog.
*/
function widenZodType(zodType: z.ZodTypeAny): z.ZodTypeAny {
// Unwrap ZodOptional → widen inner → re-wrap (only if inner changed)
if (zodType instanceof z.ZodOptional) {
const inner = zodType.unwrap();
const widenedInner = widenZodType(inner);
if (widenedInner === inner) return zodType; // no change needed
const result = widenedInner.optional();
const desc = zodType.description;
return desc ? result.describe(desc) : result;
}
// Replace ZodEnum with ZodString, preserving description
if (zodType instanceof z.ZodEnum) {
const desc = zodType.description;
const replacement = z.string();
return desc ? replacement.describe(desc) : replacement;
}
// All other types (string, number, coerce, etc.) pass through unchanged
return zodType;
}
/**
* Format a Zod validation error into a user-friendly markdown message.
*
* Extracts the relevant details from ZodError issues and presents them
* as actionable guidance rather than raw JSON.
*/
export function formatValidationError(
promptName: string,
error: z.ZodError,
): string {
const lines = [
`⚠ **Invalid input for \`${promptName}\`**`,
'',
];
for (const issue of error.issues) {
const field = issue.path.length > 0 ? issue.path.join('.') : 'input';
if (issue.code === 'invalid_enum_value' && 'options' in issue) {
const opts = (issue.options as string[]).join(', ');
lines.push(
`- **\`${field}\`**: received \`${String(issue.received)}\` — ` +
`must be one of: ${opts}`,
);
} else if (issue.code === 'invalid_type') {
lines.push(
`- **\`${field}\`**: expected ${issue.expected}, received ${issue.received}`,
);
} else {
lines.push(`- **\`${field}\`**: ${issue.message}`);
}
}
lines.push(
'',
'Please correct the input and try again.',
);
return lines.join('\n');
}
/**
* Wrap a prompt handler with early validation and exception recovery.
*
* 1. Validates `rawArgs` against the **strict** Zod schema (with enums).
* 2. On validation failure → returns a user-friendly inline error message.
* 3. On unexpected handler exception → catches and returns inline error.
* 4. On success → returns the handler's result normally.
*
* This ensures slash-command users never see raw MCP protocol errors.
*/
export function createSafePromptHandler<T extends z.ZodObject<z.ZodRawShape>>(
promptName: string,
strictSchema: T,
handler: (_args: z.infer<T>) => Promise<PromptResult>,
): (_rawArgs: Record<string, unknown>) => Promise<PromptResult> {
return async (rawArgs: Record<string, unknown>): Promise<PromptResult> => {
// Step 1: Validate with the strict schema
const parseResult = strictSchema.safeParse(rawArgs);
if (!parseResult.success) {
const errorText = formatValidationError(promptName, parseResult.error);
logger.warn(`Prompt ${promptName} validation failed: ${parseResult.error.message}`);
return {
messages: [{
role: 'user',
content: { type: 'text', text: errorText },
}],
};
}
// Step 2: Call the handler with validated args, catching exceptions
try {
return await handler(parseResult.data);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
logger.error(`Prompt ${promptName} handler error: ${msg}`);
return {
messages: [{
role: 'user',
content: {
type: 'text',
text: `⚠ **Error in \`${promptName}\`**: ${msg}\n\nPlease check your inputs and try again.`,
},
}],
};
}
};
}
// ────────────────────────────────────────────────────────────────────────────
// Prompt names (exported for testing)
// ────────────────────────────────────────────────────────────────────────────
/** Names of every workflow prompt registered with the MCP server. */
export const WORKFLOW_PROMPT_NAMES = [
'check_for_duplicated_code',
'document_codeql_query',
'explain_codeql_query',
'find_overlapping_queries',
'ql_lsp_iterative_development',
'ql_tdd_advanced',
'ql_tdd_basic',
'run_query_and_summarize_false_positives',
'sarif_rank_false_positives',
'sarif_rank_true_positives',
'test_driven_development',
'tools_query_workflow',
'workshop_creation_workflow',
] as const;
/**
* Register MCP workflow prompts
*
* Each prompt loads its content from a corresponding .prompt.md file
* and processes any parameter substitutions.
*
* **UX note**: Every prompt schema is passed to `server.prompt()` so that
* VS Code always displays the parameter-input quick-pick before the prompt
* is sent to Copilot Chat. This lets users review and customise the values.
*/
export function registerWorkflowPrompts(server: McpServer): void {
// Test-Driven Development Prompt
server.prompt(
'test_driven_development',
'Test-driven development workflow for CodeQL queries using MCP tools',
toPermissiveShape(testDrivenDevelopmentSchema.shape),
createSafePromptHandler(
'test_driven_development',
testDrivenDevelopmentSchema,
async ({ language, queryName }) => {
const template = loadPromptTemplate('ql-tdd-basic.prompt.md');
const content = processPromptTemplate(template, {
language,
queryName: queryName || '[QueryName]'
});
return {
messages: [
{
role: 'user',
content: {
type: 'text',
text: `## Context\n\n- **Language**: ${language}\n${queryName ? `- **Query Name**: ${queryName}\n` : ''}\n${content}`
}
}
]
};
},
),
);
// Tools Query Workflow Prompt
server.prompt(
'tools_query_workflow',
'Guide for using built-in tools queries (PrintAST, PrintCFG, CallGraphFrom, CallGraphTo) to understand code structure',
toPermissiveShape(toolsQueryWorkflowSchema.shape),
createSafePromptHandler(
'tools_query_workflow',
toolsQueryWorkflowSchema,
async ({ language, database, sourceFiles, sourceFunction, targetFunction }) => {
const template = loadPromptTemplate('tools-query-workflow.prompt.md');
const warnings: string[] = [];
const dbResult = resolvePromptFilePath(database);
const resolvedDatabase = dbResult.resolvedPath;
if (dbResult.warning) warnings.push(dbResult.warning);
const content = processPromptTemplate(template, {
language,
database: resolvedDatabase
});
const contextSection = buildToolsQueryContext(
language,
resolvedDatabase,
sourceFiles,
sourceFunction,
targetFunction
);
const warningSection = warnings.length > 0
? warnings.join('\n') + '\n\n'
: '';
return {
messages: [
{
role: 'user',
content: {
type: 'text',
text: warningSection + contextSection + content
}
}
]
};
},
),
);
// Workshop Creation Workflow Prompt
server.prompt(
'workshop_creation_workflow',
'Guide for creating CodeQL query development workshops from production-grade queries',
toPermissiveShape(workshopCreationWorkflowSchema.shape),
createSafePromptHandler(
'workshop_creation_workflow',
workshopCreationWorkflowSchema,
async ({ queryPath, language, workshopName, numStages }) => {
const template = loadPromptTemplate('workshop-creation-workflow.prompt.md');
const warnings: string[] = [];
const qpResult = resolvePromptFilePath(queryPath);
const resolvedQueryPath = qpResult.resolvedPath;
if (qpResult.warning) warnings.push(qpResult.warning);
const derivedName =
workshopName ||
basename(resolvedQueryPath)
.replace(/\.(ql|qlref)$/, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-') ||
'codeql-workshop';
const contextSection = buildWorkshopContext(
resolvedQueryPath,
language,
derivedName,
numStages
);
const warningSection = warnings.length > 0
? warnings.join('\n') + '\n\n'
: '';
return {
messages: [
{
role: 'user',
content: {
type: 'text',
text: warningSection + contextSection + template
}
}
]
};
},
),
);
// TDD Basic Prompt - Test-Driven Development Checklist
server.prompt(
'ql_tdd_basic',
'Test-driven CodeQL query development checklist - write tests first, implement query, iterate until tests pass',
toPermissiveShape(qlTddBasicSchema.shape),
createSafePromptHandler(
'ql_tdd_basic',
qlTddBasicSchema,
async ({ language, queryName }) => {
const template = loadPromptTemplate('ql-tdd-basic.prompt.md');
let contextSection = '## Your Development Context\n\n';
contextSection += `- **Language**: ${language}\n`;
if (queryName) {
contextSection += `- **Query Name**: ${queryName}\n`;
}
contextSection += '\n';
return {
messages: [
{
role: 'user',
content: {
type: 'text',
text: contextSection + template
}
}
]
};
},
),
);
// TDD Advanced Prompt - Advanced Techniques with AST/CFG/CallGraph
server.prompt(
'ql_tdd_advanced',
'Advanced test-driven CodeQL development with AST visualization, control flow, and call graph analysis',
toPermissiveShape(qlTddAdvancedSchema.shape),
createSafePromptHandler(
'ql_tdd_advanced',
qlTddAdvancedSchema,
async ({ language, queryName, database }) => {
const template = loadPromptTemplate('ql-tdd-advanced.prompt.md');
const warnings: string[] = [];
let resolvedDatabase = database;
if (database) {
const dbResult = resolvePromptFilePath(database);
resolvedDatabase = dbResult.resolvedPath;
if (dbResult.warning) warnings.push(dbResult.warning);
}
let contextSection = '## Your Development Context\n\n';
contextSection += `- **Language**: ${language}\n`;
if (queryName) {
contextSection += `- **Query Name**: ${queryName}\n`;
}
if (resolvedDatabase) {
contextSection += `- **Database**: ${resolvedDatabase}\n`;
}
contextSection += '\n';
const warningSection = warnings.length > 0
? warnings.join('\n') + '\n\n'
: '';
return {
messages: [
{
role: 'user',
content: {
type: 'text',
text: warningSection + contextSection + template
}
}
]
};
},
),
);
// SARIF Rank False Positives Prompt
server.prompt(
'sarif_rank_false_positives',
'Analyze SARIF results to identify likely false positives in CodeQL query results',
toPermissiveShape(sarifRankSchema.shape),
createSafePromptHandler(
'sarif_rank_false_positives',
sarifRankSchema,
async ({ queryId, sarifPath }) => {
const template = loadPromptTemplate('sarif-rank-false-positives.prompt.md');
const warnings: string[] = [];
const spResult = resolvePromptFilePath(sarifPath);
const resolvedSarifPath = spResult.resolvedPath;
if (spResult.warning) warnings.push(spResult.warning);
let contextSection = '## Analysis Context\n\n';
if (queryId) {
contextSection += `- **Query ID**: ${queryId}\n`;
}
contextSection += `- **SARIF File**: ${resolvedSarifPath}\n`;
contextSection += '\n';
const warningSection = warnings.length > 0
? warnings.join('\n') + '\n\n'
: '';
return {
messages: [
{
role: 'user',
content: {
type: 'text',
text: warningSection + contextSection + template
}
}
]
};
},
),
);
// SARIF Rank True Positives Prompt
server.prompt(
'sarif_rank_true_positives',
'Analyze SARIF results to identify likely true positives in CodeQL query results',
toPermissiveShape(sarifRankSchema.shape),
createSafePromptHandler(
'sarif_rank_true_positives',
sarifRankSchema,
async ({ queryId, sarifPath }) => {
const template = loadPromptTemplate('sarif-rank-true-positives.prompt.md');
const warnings: string[] = [];
const spResult = resolvePromptFilePath(sarifPath);
const resolvedSarifPath = spResult.resolvedPath;
if (spResult.warning) warnings.push(spResult.warning);
let contextSection = '## Analysis Context\n\n';
if (queryId) {
contextSection += `- **Query ID**: ${queryId}\n`;
}
contextSection += `- **SARIF File**: ${resolvedSarifPath}\n`;
contextSection += '\n';
const warningSection = warnings.length > 0
? warnings.join('\n') + '\n\n'
: '';
return {
messages: [
{
role: 'user',
content: {
type: 'text',
text: warningSection + contextSection + template
}
}
]
};
},
),
);
// Run a query and describe its false positives
server.prompt(
'run_query_and_summarize_false_positives',
'Help a user figure out where their query may need improvement to have a lower false positive rate',
toPermissiveShape(describeFalsePositivesSchema.shape),
createSafePromptHandler(
'run_query_and_summarize_false_positives',
describeFalsePositivesSchema,
async ({ queryPath }) => {
const template = loadPromptTemplate('run-query-and-summarize-false-positives.prompt.md');
const warnings: string[] = [];
const qpResult = resolvePromptFilePath(queryPath);
const resolvedQueryPath = qpResult.resolvedPath;
if (qpResult.warning) warnings.push(qpResult.warning);
const contextSection = `## Analysis Context\n\n- **Query Path**: ${resolvedQueryPath}\n\n`;
const warningSection = warnings.length > 0
? warnings.join('\n') + '\n\n'
: '';
return {
messages: [
{
role: 'user',
content: {
type: 'text',
text: warningSection + contextSection + template
}
}
]
};
},
),
);
// Explain CodeQL Query Prompt (for workshop learning content)
server.prompt(
'explain_codeql_query',
'Generate detailed explanation of a CodeQL query for workshop learning content - uses MCP tools to gather context and produces both verbal explanations and mermaid evaluation diagrams',
toPermissiveShape(explainCodeqlQuerySchema.shape),
createSafePromptHandler(
'explain_codeql_query',
explainCodeqlQuerySchema,
async ({ queryPath, language, databasePath }) => {
const template = loadPromptTemplate('explain-codeql-query.prompt.md');
const warnings: string[] = [];
const qpResult = resolvePromptFilePath(queryPath);
const resolvedQueryPath = qpResult.resolvedPath;
if (qpResult.warning) warnings.push(qpResult.warning);
let resolvedDatabasePath = databasePath;
if (databasePath) {
const dbResult = resolvePromptFilePath(databasePath);
resolvedDatabasePath = dbResult.resolvedPath;
if (dbResult.warning) warnings.push(dbResult.warning);
}
let contextSection = '## Query to Explain\n\n';
contextSection += `- **Query Path**: ${resolvedQueryPath}\n`;
contextSection += `- **Language**: ${language}\n`;
if (resolvedDatabasePath) {
contextSection += `- **Database Path**: ${resolvedDatabasePath}\n`;
}
contextSection += '\n';
const warningSection = warnings.length > 0
? warnings.join('\n') + '\n\n'
: '';
return {
messages: [
{
role: 'user',
content: {
type: 'text',
text: warningSection + contextSection + template
}
}
]
};
},
),
);
// Document CodeQL Query Prompt
server.prompt(
'document_codeql_query',
'Create or update documentation for a CodeQL query - generates standardized markdown documentation as a sibling file to the query',
toPermissiveShape(documentCodeqlQuerySchema.shape),
createSafePromptHandler(
'document_codeql_query',
documentCodeqlQuerySchema,
async ({ queryPath, language }) => {
const template = loadPromptTemplate('document-codeql-query.prompt.md');
const warnings: string[] = [];
const qpResult = resolvePromptFilePath(queryPath);
const resolvedQueryPath = qpResult.resolvedPath;
if (qpResult.warning) warnings.push(qpResult.warning);
const contextSection = `## Query to Document
- **Query Path**: ${resolvedQueryPath}
- **Language**: ${language}
`;
const warningSection = warnings.length > 0
? warnings.join('\n') + '\n\n'
: '';
return {
messages: [
{
role: 'user',
content: {
type: 'text',
text: warningSection + contextSection + template
}
}
]
};
},
),
);
// Check for Duplicated Code Prompt
server.prompt(
'check_for_duplicated_code',
'Check a .ql or .qll file for classes, predicates, and modules that duplicate definitions already available in the standard CodeQL libraries or shared project .qll files',
checkForDuplicatedCodeSchema.shape,
async ({ queryPath, workspaceUri }) => {
const template = loadPromptTemplate('check-for-duplicated-code.prompt.md');
const contextSection = `## File to Audit
- **Query Path**: ${queryPath}
${workspaceUri ? `- **Workspace URI**: ${workspaceUri}
` : ''}
`;
return {
messages: [
{
role: 'user',
content: {
type: 'text',
text: contextSection + template,
},
},
],
};
}
);
// Find Overlapping Queries Prompt
server.prompt(
'find_overlapping_queries',
'Discover existing .ql query files and .qll library files whose content may overlap with a new query design, identifying reusable classes, predicates, and modules',
findOverlappingQueriesSchema.shape,
async ({ queryDescription, language, packRoot }) => {
const template = loadPromptTemplate('find-overlapping-queries.prompt.md');
const contextSection =
`## New Query Context
`
+ `- **Query Description**: ${queryDescription}
`
+ `- **Language**: ${language}
`
+ (packRoot ? `- **Pack Root**: ${packRoot}
` : '');