-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathserver.ts
406 lines (378 loc) · 12.4 KB
/
server.ts
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
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import { zodToJsonSchema } from 'zod-to-json-schema';
import { WebApi } from 'azure-devops-node-api';
import { VERSION } from './shared/config';
import { AzureDevOpsConfig } from './shared/types';
import {
AzureDevOpsAuthenticationError,
AzureDevOpsError,
AzureDevOpsResourceNotFoundError,
AzureDevOpsValidationError,
isAzureDevOpsError,
} from './shared/errors';
import { AuthenticationMethod, AzureDevOpsClient } from './shared/auth';
// Import our new feature modules
import {
ListWorkItemsSchema,
GetWorkItemSchema,
CreateWorkItemSchema,
UpdateWorkItemSchema,
ManageWorkItemLinkSchema,
listWorkItems,
getWorkItem,
createWorkItem,
updateWorkItem,
manageWorkItemLink,
} from './features/work-items';
import {
GetProjectSchema,
ListProjectsSchema,
getProject,
listProjects,
} from './features/projects';
import {
GetRepositorySchema,
ListRepositoriesSchema,
getRepository,
listRepositories,
} from './features/repositories';
import {
ListOrganizationsSchema,
listOrganizations,
} from './features/organizations';
// Create a safe console logging function that won't interfere with MCP protocol
function safeLog(message: string) {
process.stderr.write(`${message}\n`);
}
/**
* Create an Azure DevOps MCP Server
*
* @param config The Azure DevOps configuration
* @returns A configured MCP server instance
*/
export function createAzureDevOpsServer(config: AzureDevOpsConfig): Server {
// Validate the configuration
validateConfig(config);
// Initialize the MCP server
const server = new Server(
{
name: 'azure-devops-mcp',
version: VERSION,
},
{
capabilities: {
tools: {},
},
},
);
// Register the ListTools request handler
server.setRequestHandler(ListToolsRequestSchema, () => {
return {
tools: [
// Organization tools
{
name: 'list_organizations',
description:
'List all Azure DevOps organizations accessible to the current authentication',
inputSchema: zodToJsonSchema(ListOrganizationsSchema),
},
// Project tools
{
name: 'list_projects',
description: 'List all projects in an organization',
inputSchema: zodToJsonSchema(ListProjectsSchema),
},
{
name: 'get_project',
description: 'Get details of a specific project',
inputSchema: zodToJsonSchema(GetProjectSchema),
},
// Work item tools
{
name: 'get_work_item',
description: 'Get details of a specific work item',
inputSchema: zodToJsonSchema(GetWorkItemSchema),
},
{
name: 'list_work_items',
description: 'List work items in a project',
inputSchema: zodToJsonSchema(ListWorkItemsSchema),
},
{
name: 'create_work_item',
description: 'Create a new work item',
inputSchema: zodToJsonSchema(CreateWorkItemSchema),
},
{
name: 'update_work_item',
description: 'Update an existing work item',
inputSchema: zodToJsonSchema(UpdateWorkItemSchema),
},
{
name: 'manage_work_item_link',
description: 'Add or remove a link between work items',
inputSchema: zodToJsonSchema(ManageWorkItemLinkSchema),
},
// Repository tools
{
name: 'get_repository',
description: 'Get details of a specific repository',
inputSchema: zodToJsonSchema(GetRepositorySchema),
},
{
name: 'list_repositories',
description: 'List repositories in a project',
inputSchema: zodToJsonSchema(ListRepositoriesSchema),
},
],
};
});
// Register the CallTool request handler
server.setRequestHandler(CallToolRequestSchema, async (request) => {
try {
if (!request.params.arguments) {
throw new AzureDevOpsValidationError('Arguments are required');
}
// Get a connection to Azure DevOps
const connection = await getConnection(config);
switch (request.params.name) {
// Organization tools
case 'list_organizations': {
// Parse arguments but they're not used since this tool doesn't have parameters
ListOrganizationsSchema.parse(request.params.arguments);
const result = await listOrganizations(config);
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
};
}
// Project tools
case 'list_projects': {
const args = ListProjectsSchema.parse(request.params.arguments);
const result = await listProjects(connection, args);
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
};
}
case 'get_project': {
const args = GetProjectSchema.parse(request.params.arguments);
const result = await getProject(connection, args.projectId);
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
};
}
// Work item tools
case 'get_work_item': {
const args = GetWorkItemSchema.parse(request.params.arguments);
const result = await getWorkItem(
connection,
args.workItemId,
args.expand,
);
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
};
}
case 'list_work_items': {
const args = ListWorkItemsSchema.parse(request.params.arguments);
const result = await listWorkItems(connection, args);
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
};
}
case 'create_work_item': {
const args = CreateWorkItemSchema.parse(request.params.arguments);
const result = await createWorkItem(
connection,
args.projectId,
args.workItemType,
{
title: args.title,
description: args.description,
assignedTo: args.assignedTo,
areaPath: args.areaPath,
iterationPath: args.iterationPath,
priority: args.priority,
parentId: args.parentId,
additionalFields: args.additionalFields,
},
);
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
};
}
case 'update_work_item': {
const args = UpdateWorkItemSchema.parse(request.params.arguments);
const result = await updateWorkItem(connection, args.workItemId, {
title: args.title,
description: args.description,
assignedTo: args.assignedTo,
areaPath: args.areaPath,
iterationPath: args.iterationPath,
priority: args.priority,
state: args.state,
additionalFields: args.additionalFields,
});
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
};
}
case 'manage_work_item_link': {
const args = ManageWorkItemLinkSchema.parse(request.params.arguments);
const result = await manageWorkItemLink(connection, args.projectId, {
sourceWorkItemId: args.sourceWorkItemId,
targetWorkItemId: args.targetWorkItemId,
operation: args.operation,
relationType: args.relationType,
newRelationType: args.newRelationType,
comment: args.comment,
});
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
};
}
// Repository tools
case 'get_repository': {
const args = GetRepositorySchema.parse(request.params.arguments);
const result = await getRepository(
connection,
args.projectId,
args.repositoryId,
);
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
};
}
case 'list_repositories': {
const args = ListRepositoriesSchema.parse(request.params.arguments);
const result = await listRepositories(connection, args);
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
};
}
default:
throw new Error(`Unknown tool: ${request.params.name}`);
}
} catch (error) {
safeLog(`Error handling tool call: ${error}`);
// Format the error message
const errorMessage = isAzureDevOpsError(error)
? formatAzureDevOpsError(error)
: `Error: ${error instanceof Error ? error.message : String(error)}`;
return {
content: [{ type: 'text', text: errorMessage }],
};
}
});
return server;
}
/**
* Format an Azure DevOps error for display
*
* @param error The error to format
* @returns Formatted error message
*/
function formatAzureDevOpsError(error: AzureDevOpsError): string {
let message = `Azure DevOps API Error: ${error.message}`;
if (error instanceof AzureDevOpsValidationError) {
message = `Validation Error: ${error.message}`;
} else if (error instanceof AzureDevOpsResourceNotFoundError) {
message = `Not Found: ${error.message}`;
} else if (error instanceof AzureDevOpsAuthenticationError) {
message = `Authentication Failed: ${error.message}`;
}
return message;
}
/**
* Validate the Azure DevOps configuration
*
* @param config The configuration to validate
* @throws {AzureDevOpsValidationError} If the configuration is invalid
*/
function validateConfig(config: AzureDevOpsConfig): void {
if (!config.organizationUrl) {
process.stderr.write(
'ERROR: Organization URL is required but was not provided.\n',
);
process.stderr.write(
`Config: ${JSON.stringify(
{
organizationUrl: config.organizationUrl,
authMethod: config.authMethod,
defaultProject: config.defaultProject,
// Hide PAT for security
personalAccessToken: config.personalAccessToken
? 'REDACTED'
: undefined,
apiVersion: config.apiVersion,
},
null,
2,
)}\n`,
);
throw new AzureDevOpsValidationError('Organization URL is required');
}
// Set default authentication method if not specified
if (!config.authMethod) {
config.authMethod = AuthenticationMethod.PersonalAccessToken;
}
// Validate PAT if using PAT authentication
if (
config.authMethod === AuthenticationMethod.PersonalAccessToken &&
!config.personalAccessToken
) {
throw new AzureDevOpsValidationError(
'Personal Access Token is required for PAT authentication',
);
}
}
/**
* Get an authenticated connection to Azure DevOps
*
* @param config The Azure DevOps configuration
* @returns An authenticated WebApi client
* @throws {AzureDevOpsAuthenticationError} If authentication fails
*/
export async function getConnection(
config: AzureDevOpsConfig,
): Promise<WebApi> {
try {
// Create a client with the appropriate authentication method
const client = new AzureDevOpsClient({
method: config.authMethod || AuthenticationMethod.PersonalAccessToken,
organizationUrl: config.organizationUrl,
personalAccessToken: config.personalAccessToken,
});
// Test the connection by getting the Core API
await client.getCoreApi();
// Return the underlying WebApi client
return await client.getWebApiClient();
} catch (error) {
safeLog(`Connection error details: ${error}`);
throw new AzureDevOpsAuthenticationError(
`Failed to authenticate with Azure DevOps: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
/**
* Test the connection to Azure DevOps
*
* @param config The Azure DevOps configuration
* @returns True if the connection is successful, false otherwise
*/
export async function testConnection(
config: AzureDevOpsConfig,
): Promise<boolean> {
try {
safeLog(`Testing connection to ${config.organizationUrl}...`);
await getConnection(config);
safeLog('Connection successful');
return true;
} catch {
safeLog('Connection test failed:');
return false;
}
}