-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcache-tools.ts
More file actions
257 lines (235 loc) · 11.2 KB
/
cache-tools.ts
File metadata and controls
257 lines (235 loc) · 11.2 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
/**
* Query Results Cache Tools — LLM-facing tools for cached query result
* lookup, retrieval (with subset selection), clearing, and comparison.
*
* Enabled by default alongside annotation tools.
*/
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { sessionDataManager } from '../lib/session-data-manager';
import { logger } from '../utils/logger';
/**
* Register all query results cache tools with the MCP server.
*/
export function registerCacheTools(server: McpServer): void {
registerQueryResultsCacheLookupTool(server);
registerQueryResultsCacheRetrieveTool(server);
registerQueryResultsCacheClearTool(server);
registerQueryResultsCacheCompareTool(server);
logger.info('Registered query results cache tools');
}
// ---------------------------------------------------------------------------
// query_results_cache_lookup
// ---------------------------------------------------------------------------
function registerQueryResultsCacheLookupTool(server: McpServer): void {
server.tool(
'query_results_cache_lookup',
'Check whether cached query results exist for given parameters. Returns metadata about the cached entry without the full content.',
{
cacheKey: z.string().optional().describe('Look up by exact cache key (if known).'),
queryName: z.string().optional().describe('Query name to search for (e.g. "PrintAST", "CallGraphFrom").'),
ruleId: z.string().optional().describe('Filter by CodeQL query @id (e.g. "js/sql-injection"). The @id is the most reliable identifier.'),
databasePath: z.string().optional().describe('Database path to search for.'),
language: z.string().optional().describe('Filter by language (e.g. "cpp", "javascript").'),
limit: z.number().int().positive().max(500).optional().describe('Maximum number of cache entries to return when listing by filter (default: 50, max: 500).'),
},
async ({ cacheKey, queryName, ruleId, databasePath, language, limit }) => {
const store = sessionDataManager.getStore();
// Exact lookup by cache key
if (cacheKey) {
const meta = store.getCacheEntryMeta(cacheKey);
if (meta) {
return { content: [{ type: 'text' as const, text: JSON.stringify({ cached: true, ...meta }, null, 2) }] };
}
return { content: [{ type: 'text' as const, text: JSON.stringify({ cached: false, cacheKey }) }] };
}
// List matching entries
const entries = store.listCacheEntries({ queryName, ruleId, databasePath, language, limit: limit ?? 50 });
if (entries.length === 0) {
return { content: [{ type: 'text' as const, text: JSON.stringify({ cached: false, queryName, ruleId, databasePath, language }) }] };
}
return {
content: [{
type: 'text' as const,
text: JSON.stringify({ cached: true, count: entries.length, entries }, null, 2),
}],
};
},
);
}
// ---------------------------------------------------------------------------
// query_results_cache_retrieve
// ---------------------------------------------------------------------------
function registerQueryResultsCacheRetrieveTool(server: McpServer): void {
server.tool(
'query_results_cache_retrieve',
'Retrieve cached query results with optional subset selection. Supports line ranges (for graphtext/CSV) and SARIF result indices and file filtering to return only the relevant portion.',
{
cacheKey: z.string().describe('The cache key of the result to retrieve.'),
lineRange: z
.object({
start: z.number().int().min(1).describe('First line to include (1-indexed, inclusive).'),
end: z.number().int().min(1).describe('Last line to include (1-indexed, inclusive).'),
})
.refine(({ start, end }) => start <= end, { message: 'lineRange.start must be <= lineRange.end' })
.optional()
.describe('Line range {start, end} (1-indexed, inclusive). For graphtext/CSV output only.'),
resultIndices: z
.object({
start: z.number().int().min(0).describe('First SARIF result index to include (0-indexed, inclusive).'),
end: z.number().int().min(0).describe('Last SARIF result index to include (0-indexed, inclusive).'),
})
.refine(({ start, end }) => start <= end, { message: 'resultIndices.start must be <= resultIndices.end' })
.optional()
.describe('SARIF result index range {start, end} (0-indexed, inclusive). For SARIF output only.'),
fileFilter: z.string().optional().describe('For SARIF: only include results whose file path contains this string.'),
maxLines: z.number().int().positive().optional().describe('Maximum number of lines to return for line-based formats (default: 500).'),
maxResults: z.number().int().positive().optional().describe('Maximum number of SARIF results to return (default: 100).'),
},
async ({ cacheKey, lineRange, resultIndices, fileFilter, maxLines, maxResults }) => {
const store = sessionDataManager.getStore();
const meta = store.getCacheEntryMeta(cacheKey);
if (!meta) {
return { content: [{ type: 'text' as const, text: `No cached result found for key: ${cacheKey}` }] };
}
// SARIF format: always use the SARIF-aware subset retrieval so that
// maxResults is applied and result-level filters (indices, file path) work correctly.
const isSarif = meta.outputFormat.includes('sarif');
if (isSarif) {
const subset = store.getCacheSarifSubset(cacheKey, {
resultIndices: resultIndices ? [resultIndices.start, resultIndices.end] : undefined,
fileFilter,
maxResults,
});
if (!subset) {
return { content: [{ type: 'text' as const, text: `Cached content not available for key: ${cacheKey}` }] };
}
let parsedResults: unknown;
try {
parsedResults = JSON.parse(subset.content);
} catch {
// getCacheSarifSubset fell back to plain-text content; return it as-is.
return {
content: [{
type: 'text' as const,
text: subset.content,
}],
};
}
return {
content: [{
type: 'text' as const,
text: JSON.stringify({
totalResults: subset.totalResults,
returnedResults: subset.returnedResults,
truncated: subset.truncated,
sarifSubset: parsedResults,
}, null, 2),
}],
};
}
// Line-based subset for graphtext, CSV, or any other text format.
const subset = store.getCacheContentSubset(cacheKey, {
lineRange: lineRange ? [lineRange.start, lineRange.end] : undefined,
maxLines: maxLines ?? 500,
});
if (!subset) {
return { content: [{ type: 'text' as const, text: `Cached content not available for key: ${cacheKey}` }] };
}
return {
content: [{
type: 'text' as const,
text: JSON.stringify({
totalLines: subset.totalLines,
returnedLines: subset.returnedLines,
truncated: subset.truncated,
}) + '\n\n' + subset.content,
}],
};
},
);
}
// ---------------------------------------------------------------------------
// query_results_cache_clear
// ---------------------------------------------------------------------------
function registerQueryResultsCacheClearTool(server: McpServer): void {
server.tool(
'query_results_cache_clear',
'Clear cached query results by cache key, query name, database path, or clear all.',
{
cacheKey: z.string().optional().describe('Clear a specific cache entry.'),
queryName: z.string().optional().describe('Clear all entries for this query name.'),
ruleId: z.string().optional().describe('Clear all entries for this CodeQL query @id.'),
databasePath: z.string().optional().describe('Clear all entries for this database.'),
all: z.boolean().optional().describe('Clear the entire query results cache.'),
},
async ({ cacheKey, queryName, ruleId, databasePath, all }) => {
if (!cacheKey && !queryName && !ruleId && !databasePath && !all) {
return { content: [{ type: 'text' as const, text: 'At least one filter (cacheKey, queryName, ruleId, databasePath, or all) is required.' }] };
}
const store = sessionDataManager.getStore();
const cleared = store.clearCacheEntries({ cacheKey, queryName, ruleId, databasePath, all: all ?? false });
return { content: [{ type: 'text' as const, text: `Cleared ${cleared} cached query result(s).` }] };
},
);
}
// ---------------------------------------------------------------------------
// query_results_cache_compare
// ---------------------------------------------------------------------------
function registerQueryResultsCacheCompareTool(server: McpServer): void {
server.tool(
'query_results_cache_compare',
'Compare cached query results across multiple databases for the same query. Useful for MRVA-style cross-repository analysis.',
{
queryName: z.string().optional().describe('The query name to compare across databases.'),
ruleId: z.string().optional().describe('The CodeQL query @id to compare across databases (preferred over queryName).'),
language: z.string().optional().describe('Filter by language.'),
},
async ({ queryName, ruleId, language }) => {
if (!queryName && !ruleId) {
return { content: [{ type: 'text' as const, text: 'Either queryName or ruleId is required.' }] };
}
const store = sessionDataManager.getStore();
const entries = store.listCacheEntries({ queryName, ruleId, language });
if (entries.length === 0) {
const identifier = ruleId ?? queryName;
return { content: [{ type: 'text' as const, text: `No cached results found for "${identifier}".` }] };
}
// Group by database
const byDatabase = new Map<string, typeof entries>();
for (const entry of entries) {
const key = entry.databasePath;
if (!byDatabase.has(key)) byDatabase.set(key, []);
byDatabase.get(key)!.push(entry);
}
const comparison = Array.from(byDatabase.entries()).map(([db, dbEntries]) => {
// Use the latest entry's result count (entries are sorted by createdAt DESC).
// When multiple cache entries exist for the same ruleId on the same database
// (e.g. one from query_run and another from database_analyze decomposition),
// the latest entry is the most representative.
const latestEntry = dbEntries[0];
const resultCount = latestEntry.resultCount ?? 0;
return {
database: db,
languages: [...new Set(dbEntries.map(e => e.language))],
formats: [...new Set(dbEntries.map(e => e.outputFormat))],
resultCount,
totalResultCount: resultCount,
cachedRuns: dbEntries.length,
latestCachedAt: dbEntries[0].createdAt,
};
});
return {
content: [{
type: 'text' as const,
text: JSON.stringify({
queryName: queryName ?? null,
ruleId: ruleId ?? null,
databases: comparison.length,
comparison,
}, null, 2),
}],
};
},
);
}