-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmcp.rs
More file actions
1241 lines (1120 loc) · 49.5 KB
/
mcp.rs
File metadata and controls
1241 lines (1120 loc) · 49.5 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
use anyhow::{Context, Result};
use log::{debug, error, info, warn};
use rmcp::{
ErrorData as McpError, ServerHandler, ServiceExt, handler::server::tool::ToolRouter,
handler::server::wrapper::Parameters, model::*, tool, tool_handler, tool_router,
transport::stdio,
};
use serde_json::Value;
use std::path::PathBuf;
use crate::ndjson::{self, SAFE_OUTPUT_FILENAME};
use crate::sanitize::{Sanitize, sanitize as sanitize_text};
use crate::tools::{
AddBuildTagParams, AddBuildTagResult,
AddPrCommentParams, AddPrCommentResult,
CommentOnWorkItemParams, CommentOnWorkItemResult,
CreateBranchParams, CreateBranchResult,
CreateGitTagParams, CreateGitTagResult,
CreatePrParams, CreatePrResult, CreateWikiPageParams, CreateWikiPageResult,
CreateWorkItemParams, CreateWorkItemResult,
LinkWorkItemsParams, LinkWorkItemsResult,
ReplyToPrCommentParams, ReplyToPrCommentResult,
ReportIncompleteParams, ReportIncompleteResult,
ResolvePrThreadParams, ResolvePrThreadResult,
UpdateWikiPageParams, UpdateWikiPageResult, MissingDataParams, MissingDataResult,
MissingToolParams, MissingToolResult, NoopParams, NoopResult, QueueBuildParams,
QueueBuildResult, SubmitPrReviewParams, SubmitPrReviewResult, ToolResult,
UpdatePrParams, UpdatePrResult,
UpdateWorkItemParams, UpdateWorkItemResult,
UploadAttachmentParams, UploadAttachmentResult,
anyhow_to_mcp_error,
};
/// Sanitize a title into a safe branch name slug.
/// Only allows alphanumeric characters and dashes, collapses multiple dashes,
/// and limits length to prevent injection attacks.
fn slugify_title(title: &str) -> String {
let slug: String = title
.to_lowercase()
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.collect();
// Collapse multiple dashes and trim leading/trailing dashes
let collapsed: String = slug
.split('-')
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join("-");
// Limit length to 50 chars for reasonable branch names
collapsed.chars().take(50).collect()
}
/// Generate a short random suffix for branch uniqueness
fn generate_short_id() -> String {
use std::time::{SystemTime, UNIX_EPOCH};
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis();
// Take last 6 hex digits of timestamp for short unique suffix
format!("{:06x}", (timestamp & 0xFFFFFF) as u32)
}
// ============================================================================
// SafeOutputs MCP Server
// ============================================================================
/// SafeOutputs is safe to clone for concurrent use: it only contains immutable
/// `PathBuf` fields and a `ToolRouter`. File I/O (NDJSON append) opens files
/// fresh on each call, so no shared mutable state exists between clones.
#[derive(Clone, Debug)]
pub struct SafeOutputs {
bounding_directory: PathBuf,
output_directory: PathBuf,
tool_router: ToolRouter<Self>,
}
#[tool_router]
impl SafeOutputs {
/// Get the full path to the safe output file
fn safe_output_path(&self) -> PathBuf {
self.output_directory.join(SAFE_OUTPUT_FILENAME)
}
/// Read the current contents of the safe output file as NDJSON
async fn read_safe_output_file(&self) -> Result<Vec<Value>> {
ndjson::read_ndjson_file(&self.safe_output_path()).await
}
/// Append a value to the safe output file (NDJSON - just append a line)
async fn write_safe_output_file<T: ToolResult>(&self, value: &T) -> Result<()> {
ndjson::append_to_ndjson_file(&self.safe_output_path(), value).await
}
/// Append a value, but only if we haven't reached the maximum entries for this tool
async fn write_safe_output_file_with_maximum<T: ToolResult>(
&self,
value: &T,
maximum: usize,
) -> Result<bool> {
let array = self.read_safe_output_file().await?;
// Count existing entries for this specific tool using T::NAME
let tool_count = array
.iter()
.filter(|v| v.get("name").and_then(|n| n.as_str()) == Some(T::NAME))
.count();
if tool_count >= maximum {
return Ok(false);
}
self.write_safe_output_file(value).await?;
Ok(true)
}
async fn new(
bounding_directory: impl Into<PathBuf>,
output_directory: impl Into<PathBuf>,
) -> Result<Self> {
let bounding_dir = bounding_directory.into();
let output_dir = output_directory.into();
info!(
"Initializing SafeOutputs MCP server: bounding={}, output={}",
bounding_dir.display(),
output_dir.display()
);
anyhow::ensure!(
bounding_dir.exists() && bounding_dir.is_dir(),
"bounding_directory: {:?} is not a valid path or directory",
bounding_dir
);
anyhow::ensure!(
output_dir.exists() && output_dir.is_dir(),
"output_directory: {:?} is not a valid path or directory",
output_dir
);
// Initialize the safe output file
debug!("Initializing safe output file");
ndjson::init_ndjson_file(&output_dir.join(SAFE_OUTPUT_FILENAME)).await?;
Ok(Self {
bounding_directory: bounding_dir,
output_directory: output_dir,
tool_router: Self::tool_router(),
})
}
/// Generate a git diff patch from a specific directory
/// If `repository` is Some, it's treated as a subdirectory of bounding_directory
/// If `repository` is None or "self", use bounding_directory directly
async fn generate_patch(&self, repository: Option<&str>) -> Result<String, McpError> {
use tokio::process::Command;
// Determine the git directory based on repository
let git_dir = match repository {
Some("self") | None => self.bounding_directory.clone(),
Some(repo_alias) => {
if repo_alias.contains('/')
|| repo_alias.contains('\\')
|| repo_alias.contains("..")
{
return Err(anyhow_to_mcp_error(anyhow::anyhow!(
"Invalid repository alias: {}. Path traversal is not allowed.",
repo_alias
)));
}
let repo_path = self.bounding_directory.join(repo_alias);
let canonical_repo_path = repo_path.canonicalize().map_err(|e| {
anyhow_to_mcp_error(anyhow::anyhow!(
"Failed to canonicalize repository path: {}",
e
))
})?;
let canonical_bounding_dir =
self.bounding_directory.canonicalize().map_err(|e| {
anyhow_to_mcp_error(anyhow::anyhow!(
"Failed to canonicalize bounding directory: {}",
e
))
})?;
if !canonical_repo_path.starts_with(&canonical_bounding_dir) {
return Err(anyhow_to_mcp_error(anyhow::anyhow!(
"Repository path escapes bounding directory: {}",
repo_path.display()
)));
}
if !repo_path.exists() {
return Err(anyhow_to_mcp_error(anyhow::anyhow!(
"Repository directory not found: {}",
repo_path.display()
)));
}
repo_path
}
};
// Run git diff against the target branch to capture all changes
// Try origin/main first (remote tracking), then main, then HEAD as fallback
let diff_targets = ["origin/main", "main", "HEAD"];
let mut last_error = String::new();
let mut diff_output = None;
for target in &diff_targets {
let output = Command::new("git")
.args(["diff", target])
.current_dir(&git_dir)
.output()
.await
.map_err(|e| {
anyhow_to_mcp_error(anyhow::anyhow!("Failed to run git diff: {}", e))
})?;
if output.status.success() {
diff_output = Some(output);
break;
}
last_error = String::from_utf8_lossy(&output.stderr).to_string();
}
let mut patch = if let Some(output) = diff_output {
String::from_utf8_lossy(&output.stdout).to_string()
} else {
return Err(anyhow_to_mcp_error(anyhow::anyhow!(
"git diff failed against all targets (origin/main, main, HEAD): {}",
last_error
)));
};
// Also include untracked files that have been added
let status_output = Command::new("git")
.args(["status", "--porcelain"])
.current_dir(&git_dir)
.output()
.await
.map_err(|e| anyhow_to_mcp_error(anyhow::anyhow!("Failed to run git status: {}", e)))?;
if !status_output.status.success() {
return Err(anyhow_to_mcp_error(anyhow::anyhow!(
"git status failed: {}",
String::from_utf8_lossy(&status_output.stderr)
)));
}
let status = String::from_utf8_lossy(&status_output.stdout);
for line in status.lines() {
if line.starts_with("?? ") {
// Untracked file - generate a diff for it
let file_path = line[3..].trim();
let file_full_path = git_dir.join(file_path);
if file_full_path.is_file() {
if let Ok(content) = tokio::fs::read_to_string(&file_full_path).await {
patch.push_str(&format!("diff --git a/{} b/{}\n", file_path, file_path));
patch.push_str("new file mode 100644\n");
patch.push_str("--- /dev/null\n");
patch.push_str(&format!("+++ b/{}\n", file_path));
let line_count = content.lines().count();
patch.push_str(&format!("@@ -0,0 +1,{} @@\n", line_count));
for line in content.lines() {
patch.push('+');
patch.push_str(line);
patch.push('\n');
}
}
}
}
}
Ok(patch)
}
/// Generate a unique patch filename
fn generate_patch_filename(&self, repository: &str) -> String {
use std::time::{SystemTime, UNIX_EPOCH};
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis();
// Sanitize repository name for filename
let safe_repo = repository.replace(['/', '\\'], "-");
format!("pr-{}-{}.patch", safe_repo, timestamp)
}
#[tool(
description = "Log a transparency message when no significant actions are needed. Use this to confirm workflow completion and provide visibility when analysis is complete but no changes or outputs are required (e.g., 'No issues found', 'All checks passed'). This ensures the workflow produces human-visible output even when no other actions are taken."
)]
async fn noop(&self, params: Parameters<NoopParams>) -> Result<CallToolResult, McpError> {
debug!("Tool called: noop - {:?}", params.0.context);
let mut sanitized = params.0;
sanitized.context = sanitized.context.map(|c| sanitize_text(&c));
let result: NoopResult = sanitized.try_into()?;
let _ = self.write_safe_output_file_with_maximum(&result, 1).await;
Ok(CallToolResult::success(vec![]))
}
#[tool(
name = "missing-tool",
description = "Report that a tool or capability needed to complete the task is not available, or share any information you deem important about missing functionality or limitations. Use this when you cannot accomplish what was requested because the required functionality is missing or access is restricted."
)]
async fn missing_tool(
&self,
params: Parameters<MissingToolParams>,
) -> Result<CallToolResult, McpError> {
warn!("Tool called: missing-tool - '{}'", params.0.tool_name);
debug!("Context: {:?}", params.0.context);
let mut sanitized = params.0;
sanitized.tool_name = sanitize_text(&sanitized.tool_name);
sanitized.context = sanitized.context.map(|c| sanitize_text(&c));
let result: MissingToolResult = sanitized.try_into()?;
let _ = self.write_safe_output_file(&result).await;
Ok(CallToolResult::success(vec![]))
}
#[tool(
name = "missing-data",
description = "Report that data or information needed to complete the task is not available. Use this when you cannot accomplish what was requested because required data, context, or information is missing."
)]
async fn missing_data(
&self,
params: Parameters<MissingDataParams>,
) -> Result<CallToolResult, McpError> {
debug!("Tool called: missing-data - {:?}", params.0.context);
let mut sanitized = params.0;
sanitized.data_type = sanitize_text(&sanitized.data_type);
sanitized.reason = sanitize_text(&sanitized.reason);
sanitized.context = sanitized.context.map(|c| sanitize_text(&c));
let result: MissingDataResult = sanitized.try_into()?;
let _ = self.write_safe_output_file(&result).await;
Ok(CallToolResult::success(vec![]))
}
#[tool(name = "create-work-item", description = "Create an azure devops work item")]
async fn create_work_item(
&self,
params: Parameters<CreateWorkItemParams>,
) -> Result<CallToolResult, McpError> {
info!("Tool called: create-work-item - '{}'", params.0.title);
debug!("Description length: {} chars", params.0.description.len());
// Sanitize untrusted agent-provided text fields (IS-01)
let mut sanitized = params.0;
sanitized.title = sanitize_text(&sanitized.title);
sanitized.description = sanitize_text(&sanitized.description);
let result: CreateWorkItemResult = sanitized.try_into()?;
let _ = self.write_safe_output_file(&result).await;
info!("Work item queued for creation");
Ok(CallToolResult::success(vec![]))
}
#[tool(
name = "comment-on-work-item",
description = "Add a comment to an existing Azure DevOps work item. \
Provide the work item ID and the comment body in markdown. The comment will be \
posted during safe output processing. Target restrictions may apply based on \
pipeline configuration."
)]
async fn comment_on_work_item(
&self,
params: Parameters<CommentOnWorkItemParams>,
) -> Result<CallToolResult, McpError> {
info!(
"Tool called: comment-on-work-item - work item #{}",
params.0.work_item_id
);
debug!("Body length: {} chars", params.0.body.len());
// Sanitize untrusted agent-provided text fields (IS-01)
let mut sanitized = params.0;
sanitized.body = sanitize_text(&sanitized.body);
let result: CommentOnWorkItemResult = sanitized.try_into()?;
self.write_safe_output_file(&result).await
.map_err(|e| anyhow_to_mcp_error(anyhow::anyhow!("Failed to write safe output: {}", e)))?;
info!("Comment queued for work item #{}", result.work_item_id);
Ok(CallToolResult::success(vec![Content::text(format!(
"Comment queued for work item #{}. The comment will be posted during safe output processing.",
result.work_item_id
))]))
}
#[tool(
name = "update-work-item",
description = "Update an existing Azure DevOps work item. Only fields explicitly enabled \
in the pipeline configuration (safe-outputs.update-work-item) may be changed. Updates may be \
further restricted by target (only a specific work item ID) or title-prefix (only work items \
whose current title starts with a configured prefix). Provide the work item ID and only the \
fields you want to update."
)]
async fn update_work_item(
&self,
params: Parameters<UpdateWorkItemParams>,
) -> Result<CallToolResult, McpError> {
info!("Tool called: update-work-item - id={}", params.0.id);
let mut result: UpdateWorkItemResult = params.0.try_into()?;
// Sanitize before persisting to NDJSON (defense-in-depth; Stage 2 sanitizes again)
result.sanitize_fields();
self.write_safe_output_file(&result).await
.map_err(|e| anyhow_to_mcp_error(anyhow::anyhow!("Failed to write safe output: {}", e)))?;
info!("Work item update queued for #{}", result.id);
Ok(CallToolResult::success(vec![Content::text(format!(
"Work item #{} update queued. Changes will be applied during safe output processing.",
result.id
))]))
}
#[tool(
name = "create-pull-request",
description = "Create a new pull request to propose code changes. Use this after making file edits to submit them for review and merging. The PR will be created from the current branch with your committed changes. Use 'self' for the pipeline's own repository, or a repository alias from the checkout list."
)]
async fn create_pr(
&self,
params: Parameters<CreatePrParams>,
) -> Result<CallToolResult, McpError> {
info!("Tool called: create_pr - '{}'", params.0.title);
// Sanitize untrusted agent-provided text fields (IS-01)
let mut sanitized = params.0;
sanitized.title = sanitize_text(&sanitized.title);
sanitized.description = sanitize_text(&sanitized.description);
// Determine repository(default to "self" if not provided)
let repository = sanitized.repository.as_deref().unwrap_or("self");
debug!("Repository: {}", repository);
// Generate the patch from current git changes in the specified repository
debug!("Generating patch for repository: {}", repository);
let patch_content = self.generate_patch(Some(repository)).await?;
if patch_content.trim().is_empty() {
warn!("No changes detected in repository '{}'", repository);
return Err(anyhow_to_mcp_error(anyhow::anyhow!(
"No changes detected in repository '{}'. Make code changes before creating a PR.",
repository
)));
}
debug!("Patch size: {} bytes", patch_content.len());
// Generate a unique filename for the patch (include repo for clarity)
let patch_filename = self.generate_patch_filename(repository);
let patch_path = self.output_directory.join(&patch_filename);
debug!("Patch filename: {}", patch_filename);
// Write the patch file
tokio::fs::write(&patch_path, &patch_content)
.await
.map_err(|e| {
anyhow_to_mcp_error(anyhow::anyhow!("Failed to write patch file: {}", e))
})?;
// Generate source branch name from sanitized title + short unique suffix
let title_slug = slugify_title(&sanitized.title);
let short_id = generate_short_id();
let source_branch = if title_slug.is_empty() {
format!("agent/pr-{}", short_id)
} else {
format!("agent/{}-{}", title_slug, short_id)
};
// Create the result with patch file reference
let result = CreatePrResult::new(
sanitized.title.clone(),
sanitized.description.clone(),
source_branch,
patch_filename,
repository.to_string(),
);
// Write to safe outputs
let _ = self.write_safe_output_file(&result).await;
Ok(CallToolResult::success(vec![Content::text(format!(
"PR request saved for repository '{}'. Patch file: {}. Changes will be pushed and PR created during safe output processing.",
repository, result.patch_file
))]))
}
#[tool(
name = "update-wiki-page",
description = "Create or update an Azure DevOps wiki page with the provided markdown content. \
The page path (e.g. '/Overview/Architecture') and the wiki to write to are determined by the \
pipeline configuration. Use this to publish findings, summaries, documentation, or any other \
structured output that should be visible in the project wiki."
)]
async fn update_wiki_page(
&self,
params: Parameters<UpdateWikiPageParams>,
) -> Result<CallToolResult, McpError> {
info!("Tool called: update-wiki-page - '{}'", params.0.path);
debug!("Content length: {} chars", params.0.content.len());
// Sanitize untrusted agent-provided text fields (IS-01).
// Path: strip control characters to prevent injection into the NDJSON record.
// Content and comment: apply the full sanitization pipeline.
let mut sanitized = params.0;
sanitized.path = sanitized
.path
.chars()
.filter(|c| !c.is_control() || *c == '\t')
.collect();
sanitized.content = sanitize_text(&sanitized.content);
sanitized.comment = sanitized.comment.map(|c| sanitize_text(&c));
let result: UpdateWikiPageResult = sanitized.try_into()?;
let _ = self.write_safe_output_file(&result).await;
info!("Wiki page edit queued: '{}'", result.path);
Ok(CallToolResult::success(vec![Content::text(format!(
"Wiki page edit queued for '{}'. The page will be created or updated during safe output processing.",
result.path
))]))
}
#[tool(
name = "create-wiki-page",
description = "Create a new Azure DevOps wiki page with the provided markdown content. \
The page path (e.g. '/Overview/NewPage') and the wiki to write to are determined by the \
pipeline configuration. The page must not already exist — use update-wiki-page to update \
existing pages. Use this to publish findings, summaries, documentation, or any other \
structured output that should be visible in the project wiki."
)]
async fn create_wiki_page(
&self,
params: Parameters<CreateWikiPageParams>,
) -> Result<CallToolResult, McpError> {
info!("Tool called: create-wiki-page - '{}'", params.0.path);
debug!("Content length: {} chars", params.0.content.len());
// Sanitize untrusted agent-provided text fields (IS-01).
// Path: strip control characters to prevent injection into the NDJSON record.
// Content and comment: apply the full sanitization pipeline.
let mut sanitized = params.0;
sanitized.path = sanitized
.path
.chars()
.filter(|c| !c.is_control() || *c == '\t')
.collect();
sanitized.content = sanitize_text(&sanitized.content);
sanitized.comment = sanitized.comment.map(|c| sanitize_text(&c));
let result: CreateWikiPageResult = sanitized.try_into()?;
let _ = self.write_safe_output_file(&result).await;
info!("Wiki page creation queued: '{}'", result.path);
Ok(CallToolResult::success(vec![Content::text(format!(
"Wiki page creation queued for '{}'. The page will be created during safe output processing.",
result.path
))]))
}
#[tool(
name = "add-pr-comment",
description = "Add a comment thread to an Azure DevOps pull request. Supports both \
general comments and file-specific inline comments with optional line positioning. \
The comment will be posted during safe output processing."
)]
async fn add_pr_comment(
&self,
params: Parameters<AddPrCommentParams>,
) -> Result<CallToolResult, McpError> {
info!(
"Tool called: add-pr-comment - PR #{}",
params.0.pull_request_id
);
debug!("Content length: {} chars", params.0.content.len());
let mut sanitized = params.0;
sanitized.content = sanitize_text(&sanitized.content);
let result: AddPrCommentResult = sanitized.try_into()?;
self.write_safe_output_file(&result).await
.map_err(|e| anyhow_to_mcp_error(anyhow::anyhow!("Failed to write safe output: {}", e)))?;
info!("PR comment queued for PR #{}", result.pull_request_id);
Ok(CallToolResult::success(vec![Content::text(format!(
"Comment queued for PR #{}. The comment will be posted during safe output processing.",
result.pull_request_id
))]))
}
#[tool(
name = "link-work-items",
description = "Create a relationship link between two Azure DevOps work items. \
Supported link types: parent, child, related, predecessor, successor, duplicate, duplicate-of. \
The link will be created during safe output processing."
)]
async fn link_work_items(
&self,
params: Parameters<LinkWorkItemsParams>,
) -> Result<CallToolResult, McpError> {
info!(
"Tool called: link-work-items - {} -> {} ({})",
params.0.source_id, params.0.target_id, params.0.link_type
);
let mut sanitized = params.0;
sanitized.comment = sanitized.comment.map(|c| sanitize_text(&c));
let result: LinkWorkItemsResult = sanitized.try_into()?;
self.write_safe_output_file(&result).await
.map_err(|e| anyhow_to_mcp_error(anyhow::anyhow!("Failed to write safe output: {}", e)))?;
Ok(CallToolResult::success(vec![Content::text(format!(
"Link queued: work item #{} → #{} ({}). The link will be created during safe output processing.",
result.source_id, result.target_id, result.link_type
))]))
}
#[tool(
name = "queue-build",
description = "Trigger an Azure DevOps pipeline/build run. The pipeline must be in the \
allowed-pipelines list configured in the pipeline definition. Optionally specify a branch \
and template parameters."
)]
async fn queue_build(
&self,
params: Parameters<QueueBuildParams>,
) -> Result<CallToolResult, McpError> {
info!(
"Tool called: queue-build - pipeline {}",
params.0.pipeline_id
);
let mut sanitized = params.0;
sanitized.reason = sanitized.reason.map(|r| sanitize_text(&r));
let result: QueueBuildResult = sanitized.try_into()?;
self.write_safe_output_file(&result).await
.map_err(|e| anyhow_to_mcp_error(anyhow::anyhow!("Failed to write safe output: {}", e)))?;
Ok(CallToolResult::success(vec![Content::text(format!(
"Build queued for pipeline {}. The build will be triggered during safe output processing.",
result.pipeline_id
))]))
}
#[tool(
name = "create-git-tag",
description = "Create an annotated git tag on a commit in an Azure DevOps repository. \
The tag will be created during safe output processing."
)]
async fn create_git_tag(
&self,
params: Parameters<CreateGitTagParams>,
) -> Result<CallToolResult, McpError> {
info!("Tool called: create-git-tag - '{}'", params.0.tag_name);
let mut sanitized = params.0;
sanitized.message = sanitized.message.map(|m| sanitize_text(&m));
let result: CreateGitTagResult = sanitized.try_into()?;
self.write_safe_output_file(&result).await
.map_err(|e| anyhow_to_mcp_error(anyhow::anyhow!("Failed to write safe output: {}", e)))?;
Ok(CallToolResult::success(vec![Content::text(format!(
"Git tag '{}' queued. The tag will be created during safe output processing.",
result.tag_name
))]))
}
#[tool(
name = "add-build-tag",
description = "Add a tag to an Azure DevOps build for classification and filtering. \
The tag will be added during safe output processing."
)]
async fn add_build_tag(
&self,
params: Parameters<AddBuildTagParams>,
) -> Result<CallToolResult, McpError> {
info!(
"Tool called: add-build-tag - build {} tag '{}'",
params.0.build_id, params.0.tag
);
let result: AddBuildTagResult = params.0.try_into()?;
self.write_safe_output_file(&result).await
.map_err(|e| anyhow_to_mcp_error(anyhow::anyhow!("Failed to write safe output: {}", e)))?;
Ok(CallToolResult::success(vec![Content::text(format!(
"Build tag '{}' queued for build #{}. The tag will be added during safe output processing.",
result.tag, result.build_id
))]))
}
#[tool(
name = "create-branch",
description = "Create a new branch in an Azure DevOps repository without creating a \
pull request. The branch will be created during safe output processing."
)]
async fn create_branch(
&self,
params: Parameters<CreateBranchParams>,
) -> Result<CallToolResult, McpError> {
info!(
"Tool called: create-branch - '{}'",
params.0.branch_name
);
let result: CreateBranchResult = params.0.try_into()?;
self.write_safe_output_file(&result).await
.map_err(|e| anyhow_to_mcp_error(anyhow::anyhow!("Failed to write safe output: {}", e)))?;
Ok(CallToolResult::success(vec![Content::text(format!(
"Branch '{}' queued for creation. The branch will be created during safe output processing.",
result.branch_name
))]))
}
#[tool(
name = "update-pr",
description = "Update pull request metadata in Azure DevOps. Supports operations: \
add-reviewers, add-labels, set-auto-complete, vote, update-description. \
Changes will be applied during safe output processing."
)]
async fn update_pr(
&self,
params: Parameters<UpdatePrParams>,
) -> Result<CallToolResult, McpError> {
info!(
"Tool called: update-pr - PR #{} operation '{}'",
params.0.pull_request_id, params.0.operation
);
let mut sanitized = params.0;
sanitized.description = sanitized.description.map(|d| sanitize_text(&d));
let result: UpdatePrResult = sanitized.try_into()?;
self.write_safe_output_file(&result).await
.map_err(|e| anyhow_to_mcp_error(anyhow::anyhow!("Failed to write safe output: {}", e)))?;
Ok(CallToolResult::success(vec![Content::text(format!(
"PR #{} '{}' operation queued. Changes will be applied during safe output processing.",
result.pull_request_id, result.operation
))]))
}
#[tool(
name = "upload-attachment",
description = "Upload a file attachment to an Azure DevOps work item. The file will be \
uploaded and linked during safe output processing. File size and type restrictions may apply."
)]
async fn upload_attachment(
&self,
params: Parameters<UploadAttachmentParams>,
) -> Result<CallToolResult, McpError> {
info!(
"Tool called: upload-attachment - work item #{} file '{}'",
params.0.work_item_id, params.0.file_path
);
let mut sanitized = params.0;
sanitized.comment = sanitized.comment.map(|c| sanitize_text(&c));
let result: UploadAttachmentResult = sanitized.try_into()?;
self.write_safe_output_file(&result).await
.map_err(|e| anyhow_to_mcp_error(anyhow::anyhow!("Failed to write safe output: {}", e)))?;
Ok(CallToolResult::success(vec![Content::text(format!(
"Attachment '{}' queued for work item #{}. The file will be uploaded during safe output processing.",
result.file_path, result.work_item_id
))]))
}
#[tool(
name = "submit-pr-review",
description = "Submit a pull request review with a decision (approve, request-changes, \
or comment-only) and an optional body explaining the rationale. The review will be \
submitted during safe output processing. Requires 'allowed-events' to be configured."
)]
async fn submit_pr_review(
&self,
params: Parameters<SubmitPrReviewParams>,
) -> Result<CallToolResult, McpError> {
info!(
"Tool called: submit-pr-review - PR #{} event '{}'",
params.0.pull_request_id, params.0.event
);
let mut sanitized = params.0;
sanitized.body = sanitized.body.map(|b| sanitize_text(&b));
let result: SubmitPrReviewResult = sanitized.try_into()?;
self.write_safe_output_file(&result).await
.map_err(|e| anyhow_to_mcp_error(anyhow::anyhow!("Failed to write safe output: {}", e)))?;
Ok(CallToolResult::success(vec![Content::text(format!(
"PR review '{}' queued for PR #{}. The review will be submitted during safe output processing.",
result.event, result.pull_request_id
))]))
}
#[tool(
name = "reply-to-pr-review-comment",
description = "Reply to an existing review comment thread on an Azure DevOps pull request. \
Provide the PR ID, thread ID, and reply content. The reply will be posted during safe output processing."
)]
async fn reply_to_pr_review_comment(
&self,
params: Parameters<ReplyToPrCommentParams>,
) -> Result<CallToolResult, McpError> {
info!(
"Tool called: reply-to-pr-review-comment - PR #{} thread #{}",
params.0.pull_request_id, params.0.thread_id
);
let mut sanitized = params.0;
sanitized.content = sanitize_text(&sanitized.content);
let result: ReplyToPrCommentResult = sanitized.try_into()?;
self.write_safe_output_file(&result).await
.map_err(|e| anyhow_to_mcp_error(anyhow::anyhow!("Failed to write safe output: {}", e)))?;
Ok(CallToolResult::success(vec![Content::text(format!(
"Reply queued for thread #{} on PR #{}. The reply will be posted during safe output processing.",
result.thread_id, result.pull_request_id
))]))
}
#[tool(
name = "resolve-pr-review-thread",
description = "Resolve or change the status of a review thread on an Azure DevOps pull request. \
Valid statuses: fixed, wont-fix, closed, by-design, active. \
The status change will be applied during safe output processing."
)]
async fn resolve_pr_review_thread(
&self,
params: Parameters<ResolvePrThreadParams>,
) -> Result<CallToolResult, McpError> {
info!(
"Tool called: resolve-pr-review-thread - PR #{} thread #{} → '{}'",
params.0.pull_request_id, params.0.thread_id, params.0.status
);
let result: ResolvePrThreadResult = params.0.try_into()?;
self.write_safe_output_file(&result).await
.map_err(|e| anyhow_to_mcp_error(anyhow::anyhow!("Failed to write safe output: {}", e)))?;
Ok(CallToolResult::success(vec![Content::text(format!(
"Thread #{} status change to '{}' queued for PR #{}. The change will be applied during safe output processing.",
result.thread_id, result.status, result.pull_request_id
))]))
}
#[tool(
name = "report-incomplete",
description = "Signal that the task could not be completed due to infrastructure failure, \
tool errors, or other environmental issues beyond the agent's control. Use this when the \
agent attempted work but couldn't finish (e.g., API timeouts, build failures, resource limits)."
)]
async fn report_incomplete(
&self,
params: Parameters<ReportIncompleteParams>,
) -> Result<CallToolResult, McpError> {
warn!("Tool called: report-incomplete - '{}'", params.0.reason);
let mut sanitized = params.0;
sanitized.reason = sanitize_text(&sanitized.reason);
sanitized.context = sanitized.context.map(|c| sanitize_text(&c));
let result: ReportIncompleteResult = sanitized.try_into()?;
if let Err(e) = self.write_safe_output_file(&result).await {
warn!("Failed to write report-incomplete safe output: {}", e);
}
Ok(CallToolResult::success(vec![]))
}
}
// Implement the server handler
#[tool_handler]
impl ServerHandler for SafeOutputs {
fn get_info(&self) -> ServerInfo {
ServerInfo {
instructions: Some(
"A set of tools that generate SafeOutput compatible results.".into(),
),
capabilities: ServerCapabilities::builder().enable_tools().build(),
..Default::default()
}
}
}
pub async fn run(output_directory: &str, bounding_directory: &str) -> Result<()> {
// Create and run the server with STDIO transport
let service = SafeOutputs::new(bounding_directory, output_directory)
.await?
.serve(stdio())
.await
.inspect_err(|e| {
error!("Error starting MCP server: {}", e);
})?;
service
.waiting()
.await
.map_err(|e| anyhow::anyhow!("MCP exited with error: {:?}", e))?;
Ok(())
}
/// Run SafeOutputs MCP server over HTTP using the Streamable HTTP protocol.
///
/// This is used for MCPG integration: the gateway connects to this server as an
/// HTTP backend and proxies tool calls from the agent.
pub async fn run_http(
output_directory: &str,
bounding_directory: &str,
port: u16,
api_key: Option<&str>,
) -> Result<()> {
use axum::Router;
use rmcp::transport::streamable_http_server::{
StreamableHttpServerConfig, StreamableHttpService,
session::local::LocalSessionManager,
};
use std::sync::Arc;
let bounding = bounding_directory.to_string();
let output = output_directory.to_string();
// Generate or use provided API key.
// In production the pipeline always passes --api-key with a cryptographically
// random value; this fallback covers dev/test invocations.
let api_key = match api_key {
Some(k) => k.to_string(),
None => {
let mut buf = [0u8; 32];
std::fs::File::open("/dev/urandom")
.and_then(|mut f| {
use std::io::Read;
f.read_exact(&mut buf)
})
.context(
"Cannot generate secure API key: /dev/urandom unavailable. \
Pass --api-key explicitly.",
)?;
buf.iter().map(|b| format!("{:02x}", b)).collect()
}
};
info!("Starting SafeOutputs HTTP server on port {}", port);
let config = StreamableHttpServerConfig {
sse_keep_alive: Some(std::time::Duration::from_secs(15)),
stateful_mode: true,
};
let session_manager = Arc::new(LocalSessionManager::default());
// Pre-initialize SafeOutputs once and share via clone.
// The factory closure runs on a Tokio worker thread, so we cannot
// use block_on() inside it — that would panic with "Cannot start
// a runtime from within a runtime".
let safe_outputs_template = SafeOutputs::new(&bounding, &output).await?;
let mcp_service = StreamableHttpService::new(
move || Ok(safe_outputs_template.clone()),
session_manager,
config,
);
// Wrap with API key auth middleware (constant-time comparison to
// prevent timing side-channels from a compromised AWF container).
let expected_key = api_key.clone();
let app = Router::new()
.route("/health", axum::routing::get(|| async { "ok" }))
.route(
"/mcp",
axum::routing::post(axum::routing::any_service(mcp_service.clone()))
.get(axum::routing::any_service(mcp_service.clone()))
.delete(axum::routing::any_service(mcp_service)),
)
.layer(axum::middleware::from_fn(move |req: axum::extract::Request, next: axum::middleware::Next| {
let expected = expected_key.clone();
async move {
// Skip auth for health endpoint
if req.uri().path() == "/health" {
return next.run(req).await;
}
// Constant-time comparison to prevent timing side-channels.
// Length check is non-constant-time but leaking length doesn't
// help brute-force a high-entropy token.
if let Some(auth) = req.headers().get("authorization") {
if let Ok(auth_str) = auth.to_str() {
let expected_header = format!("Bearer {}", expected);
use subtle::ConstantTimeEq;
let expected_bytes = expected_header.as_bytes();
let provided_bytes = auth_str.as_bytes();
if expected_bytes.len() == provided_bytes.len()
&& expected_bytes.ct_eq(provided_bytes).into()
{
return next.run(req).await;
}
}
}
use axum::response::IntoResponse;
(axum::http::StatusCode::UNAUTHORIZED, "Unauthorized").into_response()
}
}));
let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));
let listener = tokio::net::TcpListener::bind(addr).await?;
info!("SafeOutputs HTTP server listening on {}", addr);
// Print port for pipeline capture (key is already known by the caller)
println!("SAFE_OUTPUTS_PORT={}", port);
log::debug!("SafeOutputs API key configured (not printed for security)");
axum::serve(listener, app)
.with_graceful_shutdown(async {
tokio::signal::ctrl_c().await.ok();
info!("SafeOutputs HTTP server shutting down");
})
.await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
async fn create_test_safe_outputs() -> (SafeOutputs, tempfile::TempDir) {
let temp_dir = tempdir().unwrap();
let safe_outputs = SafeOutputs::new(temp_dir.path(), temp_dir.path())
.await
.unwrap();
(safe_outputs, temp_dir)
}
#[test]
fn test_slugify_title_basic() {
assert_eq!(slugify_title("Fix bug in parser"), "fix-bug-in-parser");