Repository navigation
Expand file tree
/
Copy pathsearch.ts
More file actions
274 lines (236 loc) · 10.4 KB
/
Copy pathsearch.ts
File metadata and controls
274 lines (236 loc) · 10.4 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { WebApi } from "azure-devops-node-api";
import { IGitApi } from "azure-devops-node-api/GitApi.js";
import { GitItem, VersionControlRecursionType } from "azure-devops-node-api/interfaces/GitInterfaces.js";
import { z } from "zod";
import { apiVersion } from "../utils.js";
import { orgName } from "../index.js";
import { createExternalContentResponse } from "../shared/content-safety.js";
const SEARCH_TOOLS = {
search_code: "search_code",
search_wiki: "search_wiki",
search_workitem: "search_workitem",
};
function configureSearchTools(server: McpServer, tokenProvider: () => Promise<string>, connectionProvider: () => Promise<WebApi>, userAgentProvider: () => string) {
server.tool(
SEARCH_TOOLS.search_code,
"Search Azure DevOps Repositories for a given search text",
{
searchText: z.string().describe("Keywords to search for in code repositories"),
project: z
.union([z.string().transform((value) => [value]), z.array(z.string())])
.optional()
.describe("Filter by projects"),
repository: z.array(z.string()).optional().describe("Filter by repositories"),
path: z.array(z.string()).optional().describe("Filter by paths"),
branch: z.array(z.string()).optional().describe("Filter by branches"),
includeFacets: z.boolean().default(false).describe("Include facets in the search results"),
skip: z.coerce.number().default(0).describe("Number of results to skip"),
top: z.coerce.number().default(5).describe("Maximum number of results to return"),
},
async ({ searchText, project, repository, path, branch, includeFacets, skip, top }) => {
const accessToken = await tokenProvider();
const connection = await connectionProvider();
const url = `https://almsearch.dev.azure.com/${orgName}/_apis/search/codesearchresults?api-version=${apiVersion}`;
const requestBody: Record<string, unknown> = {
searchText,
includeFacets,
$skip: skip,
$top: top,
};
const filters: Record<string, string[]> = {};
if (project && project.length > 0) filters.Project = project;
if (repository && repository.length > 0) filters.Repository = repository;
if (path && path.length > 0) filters.Path = path;
if (branch && branch.length > 0) filters.Branch = branch;
if (Object.keys(filters).length > 0) {
requestBody.filters = filters;
}
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${accessToken}`,
"User-Agent": userAgentProvider(),
},
body: JSON.stringify(requestBody),
});
if (!response.ok) {
throw new Error(`Azure DevOps Code Search API error: ${response.status} ${response.statusText}`);
}
const resultText = await response.text();
const resultJson = JSON.parse(resultText) as { results?: SearchResult[] };
const gitApi = await connection.getGitApi();
const combinedResults = await fetchCombinedResults(resultJson.results ?? [], gitApi);
return createExternalContentResponse(resultText + JSON.stringify(combinedResults), "code search results");
}
);
server.tool(
SEARCH_TOOLS.search_wiki,
"Search Azure DevOps Wiki for a given search text. Results include the repository path and a wiki-relative pagePath that can be used with the wiki tool.",
{
searchText: z.string().describe("Keywords to search for wiki pages"),
project: z.array(z.string()).optional().describe("Filter by projects"),
wiki: z.array(z.string()).optional().describe("Filter by wiki names"),
includeFacets: z.boolean().default(false).describe("Include facets in the search results"),
skip: z.coerce.number().default(0).describe("Number of results to skip"),
top: z.coerce.number().default(10).describe("Maximum number of results to return"),
},
async ({ searchText, project, wiki, includeFacets, skip, top }) => {
const accessToken = await tokenProvider();
const url = `https://almsearch.dev.azure.com/${orgName}/_apis/search/wikisearchresults?api-version=${apiVersion}`;
const requestBody: Record<string, unknown> = {
searchText,
includeFacets,
$skip: skip,
$top: top,
};
const filters: Record<string, string[]> = {};
if (project && project.length > 0) filters.Project = project;
if (wiki && wiki.length > 0) filters.Wiki = wiki;
if (Object.keys(filters).length > 0) {
requestBody.filters = filters;
}
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${accessToken}`,
"User-Agent": userAgentProvider(),
},
body: JSON.stringify(requestBody),
});
if (!response.ok) {
throw new Error(`Azure DevOps Wiki Search API error: ${response.status} ${response.statusText}`);
}
const result = (await response.json()) as WikiSearchResponse;
const results = result.results?.map(addWikiPagePath);
const enrichedResult = results ? { ...result, results } : result;
return createExternalContentResponse(JSON.stringify(enrichedResult), "wiki search results");
}
);
server.tool(
SEARCH_TOOLS.search_workitem,
"Get Azure DevOps Work Item search results for a given search text",
{
searchText: z.string().describe("Search text to find in work items"),
project: z.array(z.string()).optional().describe("Filter by projects"),
areaPath: z.array(z.string()).optional().describe("Filter by area paths"),
workItemType: z.array(z.string()).optional().describe("Filter by work item types"),
state: z.array(z.string()).optional().describe("Filter by work item states"),
assignedTo: z.array(z.string()).optional().describe("Filter by assigned to users"),
includeFacets: z.boolean().default(false).describe("Include facets in the search results"),
skip: z.coerce.number().default(0).describe("Number of results to skip for pagination"),
top: z.coerce.number().default(10).describe("Number of results to return"),
},
async ({ searchText, project, areaPath, workItemType, state, assignedTo, includeFacets, skip, top }) => {
const accessToken = await tokenProvider();
const url = `https://almsearch.dev.azure.com/${orgName}/_apis/search/workitemsearchresults?api-version=${apiVersion}`;
const requestBody: Record<string, unknown> = {
searchText,
includeFacets,
$skip: skip,
$top: top,
};
const filters: Record<string, unknown> = {};
if (project && project.length > 0) filters["System.TeamProject"] = project;
if (areaPath && areaPath.length > 0) filters["System.AreaPath"] = areaPath;
if (workItemType && workItemType.length > 0) filters["System.WorkItemType"] = workItemType;
if (state && state.length > 0) filters["System.State"] = state;
if (assignedTo && assignedTo.length > 0) filters["System.AssignedTo"] = assignedTo;
if (Object.keys(filters).length > 0) {
requestBody.filters = filters;
}
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${accessToken}`,
"User-Agent": userAgentProvider(),
},
body: JSON.stringify(requestBody),
});
if (!response.ok) {
throw new Error(`Azure DevOps Work Item Search API error: ${response.status} ${response.statusText}`);
}
const result = await response.text();
return createExternalContentResponse(result, "work item search results");
}
);
}
interface SearchResult {
project?: { id?: string };
repository?: { id?: string };
path?: string;
versions?: { changeId?: string }[];
[key: string]: unknown;
}
interface WikiSearchResult {
path?: string;
pagePath?: string;
wiki?: {
mappedPath?: string;
[key: string]: unknown;
};
[key: string]: unknown;
}
interface WikiSearchResponse {
results?: WikiSearchResult[];
[key: string]: unknown;
}
type CombinedResult = { gitItem: GitItem } | { error: string };
function addWikiPagePath(result: WikiSearchResult): WikiSearchResult {
if (result.pagePath || !result.path || !result.wiki?.mappedPath) {
return result;
}
const mappedPath = result.wiki.mappedPath === "/" ? "" : result.wiki.mappedPath.replace(/\/+$/, "");
if (mappedPath && result.path !== mappedPath && !result.path.startsWith(`${mappedPath}/`)) {
return result;
}
const relativePath = decodeURIComponent(result.path.slice(mappedPath.length).replace(/\.md$/i, ""));
const pagePath = relativePath.startsWith("/") ? relativePath : `/${relativePath}`;
return { ...result, pagePath };
}
async function fetchCombinedResults(topSearchResults: SearchResult[], gitApi: IGitApi): Promise<CombinedResult[]> {
const combinedResults: CombinedResult[] = [];
for (const searchResult of topSearchResults) {
try {
const projectId = searchResult.project?.id;
const repositoryId = searchResult.repository?.id;
const filePath = searchResult.path;
const changeId = Array.isArray(searchResult.versions) && searchResult.versions.length > 0 ? searchResult.versions[0].changeId : undefined;
if (!projectId || !repositoryId || !filePath || !changeId) {
combinedResults.push({
error: `Missing projectId, repositoryId, filePath, or changeId in the result: ${JSON.stringify(searchResult)}`,
});
continue;
}
const versionDescriptor = { version: changeId, versionType: 2, versionOptions: 0 };
const item = await gitApi.getItem(
repositoryId,
filePath,
projectId,
undefined,
VersionControlRecursionType.None,
true, // includeContentMetadata
false, // latestProcessedChange
false, // download
versionDescriptor,
true, // includeContent
true, // resolveLfs
true // sanitize
);
combinedResults.push({
gitItem: item,
});
} catch (err) {
combinedResults.push({
error: err instanceof Error ? err.message : String(err),
});
}
}
return combinedResults;
}
export { SEARCH_TOOLS, configureSearchTools };