-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathtools.rs
More file actions
1704 lines (1479 loc) · 60.2 KB
/
tools.rs
File metadata and controls
1704 lines (1479 loc) · 60.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
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
use std::borrow::Cow;
use std::sync::Arc;
use std::time::Instant;
use anyhow::Result;
use rmcp::model::{CallToolRequestParam, CallToolResult, Content, Tool};
use rmcp::{Peer, RoleServer};
use serde_json::{json, Value};
use tracing::{debug, error, info, instrument, warn};
use wassette::LifecycleManager;
use crate::components::{
extract_args_from_request, get_component_tools, handle_component_call, handle_list_components,
handle_load_component, handle_unload_component,
};
/// The list of components that Wassette knows about
const COMPONENT_LIST: &str = include_str!("../../../component-registry.json");
/// Handles a request to list available tools.
#[instrument(skip(lifecycle_manager))]
pub async fn handle_tools_list(
lifecycle_manager: &LifecycleManager,
disable_builtin_tools: bool,
) -> Result<Value> {
debug!("Handling tools list request");
let mut tools = get_component_tools(lifecycle_manager).await?;
if !disable_builtin_tools {
tools.extend(get_builtin_tools());
}
debug!(num_tools = %tools.len(), "Retrieved tools");
let response = rmcp::model::ListToolsResult {
tools,
next_cursor: None,
};
Ok(serde_json::to_value(response)?)
}
/// Check if a tool name is a builtin tool
fn is_builtin_tool(name: &str) -> bool {
matches!(
name,
"load-component"
| "unload-component"
| "list-components"
| "get-policy"
| "grant-storage-permission"
| "grant-network-permission"
| "grant-environment-variable-permission"
| "revoke-storage-permission"
| "revoke-network-permission"
| "revoke-environment-variable-permission"
| "search-components"
| "reset-permission"
)
}
/// Sanitize tool arguments for logging by limiting string length and removing sensitive data
fn sanitize_args_for_logging(args: &Option<serde_json::Map<String, Value>>) -> String {
const MAX_ARG_LENGTH: usize = 200;
const MAX_TOTAL_LENGTH: usize = 1000;
match args {
None => "{}".to_string(),
Some(map) => {
let mut sanitized = serde_json::Map::new();
let mut total_length = 0;
for (key, value) in map {
// Skip potentially sensitive keys
if key.to_lowercase().contains("password")
|| key.to_lowercase().contains("secret")
|| key.to_lowercase().contains("token")
|| key.to_lowercase().contains("key")
{
sanitized.insert(key.clone(), json!("<redacted>"));
continue;
}
// Truncate long string values
let sanitized_value = match value {
Value::String(s) if s.len() > MAX_ARG_LENGTH => {
json!(format!("{}... ({} chars)", &s[..MAX_ARG_LENGTH], s.len()))
}
_ => value.clone(),
};
// Check if adding this key-value pair would exceed the total length before insertion
// The +20 accounts for JSON overhead (quotes, colons, commas, braces)
if total_length + key.len() + 20 > MAX_TOTAL_LENGTH {
sanitized.insert("...".to_string(), json!("(truncated)"));
break;
}
sanitized.insert(key.clone(), sanitized_value);
total_length += key.len() + 20;
}
serde_json::to_string(&sanitized).unwrap_or_else(|_| "{}".to_string())
}
}
}
/// Handles a tool call request.
#[instrument(skip_all, fields(method_name = %req.name))]
pub async fn handle_tools_call(
req: CallToolRequestParam,
lifecycle_manager: &LifecycleManager,
server_peer: Peer<RoleServer>,
disable_builtin_tools: bool,
) -> Result<Value> {
let start_time = Instant::now();
let tool_name = req.name.to_string();
let sanitized_args = sanitize_args_for_logging(&req.arguments);
debug!(
tool_name = %tool_name,
arguments = %sanitized_args,
"Tool invocation started"
);
let result = if disable_builtin_tools && is_builtin_tool(req.name.as_ref()) {
// When builtin tools are disabled, reject calls to builtin tools
warn!(
tool_name = %tool_name,
"Tool invocation rejected: built-in tools are disabled"
);
Err(anyhow::anyhow!("Built-in tools are disabled"))
} else {
// Handle builtin tools (if enabled) or component calls
match req.name.as_ref() {
"load-component" if !disable_builtin_tools => {
handle_load_component(&req, lifecycle_manager, server_peer).await
}
"unload-component" if !disable_builtin_tools => {
handle_unload_component(&req, lifecycle_manager, server_peer).await
}
"list-components" if !disable_builtin_tools => {
handle_list_components(lifecycle_manager).await
}
"get-policy" if !disable_builtin_tools => {
handle_get_policy(&req, lifecycle_manager).await
}
"grant-storage-permission" if !disable_builtin_tools => {
handle_grant_storage_permission(&req, lifecycle_manager).await
}
"grant-network-permission" if !disable_builtin_tools => {
handle_grant_network_permission(&req, lifecycle_manager).await
}
"grant-environment-variable-permission" if !disable_builtin_tools => {
handle_grant_environment_variable_permission(&req, lifecycle_manager).await
}
"revoke-storage-permission" if !disable_builtin_tools => {
handle_revoke_storage_permission(&req, lifecycle_manager).await
}
"revoke-network-permission" if !disable_builtin_tools => {
handle_revoke_network_permission(&req, lifecycle_manager).await
}
"revoke-environment-variable-permission" if !disable_builtin_tools => {
handle_revoke_environment_variable_permission(&req, lifecycle_manager).await
}
"search-components" if !disable_builtin_tools => {
handle_search_component(&req, lifecycle_manager).await
}
"reset-permission" if !disable_builtin_tools => {
handle_reset_permission(&req, lifecycle_manager).await
}
_ => handle_component_call(&req, lifecycle_manager).await,
}
};
let duration = start_time.elapsed();
match &result {
Ok(_) => {
debug!(
tool_name = %tool_name,
duration_ms = %duration.as_millis(),
outcome = "success",
"Tool invocation completed successfully"
);
}
Err(e) => {
error!(
tool_name = %tool_name,
duration_ms = %duration.as_millis(),
outcome = "error",
error = %e,
"Tool invocation failed"
);
}
}
match result {
Ok(result) => Ok(serde_json::to_value(result)?),
Err(e) => {
let error_text = format!("Error: {e}");
let contents = vec![Content::text(error_text)];
let error_result = CallToolResult {
content: Some(contents),
structured_content: None,
is_error: Some(true),
};
Ok(serde_json::to_value(error_result)?)
}
}
}
fn get_builtin_tools() -> Vec<Tool> {
debug!("Getting builtin tools");
vec![
Tool {
name: Cow::Borrowed("load-component"),
description: Some(Cow::Borrowed(
"Dynamically loads a new tool or component from either the filesystem or OCI registries. Optionally, you can specify which tools to load from the component.",
)),
input_schema: Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Path to the component (file://, oci://, or https://)"
},
"tools": {
"type": "array",
"items": {"type": "string"},
"description": "Optional array of tool names to load from the component. If not specified, all tools will be loaded."
}
},
"required": ["path"]
}))
.unwrap_or_default(),
),
output_schema: None,
annotations: None,
},
Tool {
name: Cow::Borrowed("unload-component"),
description: Some(Cow::Borrowed(
"Unloads a tool or component.",
)),
input_schema: Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {
"id": {"type": "string"}
},
"required": ["id"]
}))
.unwrap_or_default(),
),
output_schema: None,
annotations: None,
},
Tool {
name: Cow::Borrowed("list-components"),
description: Some(Cow::Borrowed(
"Lists all currently loaded components or tools.",
)),
input_schema: Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {},
"required": []
}))
.unwrap_or_default(),
),
output_schema: None,
annotations: None,
},
Tool {
name: Cow::Borrowed("get-policy"),
description: Some(Cow::Borrowed(
"Gets the policy information for a specific component",
)),
input_schema: Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {
"component_id": {
"type": "string",
"description": "ID of the component to get policy for"
}
},
"required": ["component_id"]
}))
.unwrap_or_default(),
),
output_schema: None,
annotations: None,
},
Tool {
name: Cow::Borrowed("grant-storage-permission"),
description: Some(Cow::Borrowed(
"Grants storage access permission to a component, allowing it to read from and/or write to specific storage locations."
)),
input_schema: Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {
"component_id": {
"type": "string",
"description": "ID of the component to grant storage permission to"
},
"details": {
"type": "object",
"properties": {
"uri": {
"type": "string",
"description": "URI of the storage resource to grant access to. e.g. fs:///tmp/test"
},
"access": {
"type": "array",
"items": {
"type": "string",
"enum": ["read", "write"]
},
"description": "Access type for the storage resource, this must be an array of strings with values 'read' or 'write'"
}
},
"required": ["uri", "access"],
"additionalProperties": false
}
},
"required": ["component_id", "details"]
}))
.unwrap_or_default(),
),
output_schema: None,
annotations: None,
},
Tool {
name: Cow::Borrowed("grant-network-permission"),
description: Some(Cow::Borrowed(
"Grants network access permission to a component, allowing it to make network requests to specific hosts."
)),
input_schema: Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {
"component_id": {
"type": "string",
"description": "ID of the component to grant network permission to"
},
"details": {
"type": "object",
"properties": {
"host": {
"type": "string",
"description": "Host to grant network access to"
}
},
"required": ["host"],
"additionalProperties": false
}
},
"required": ["component_id", "details"]
}))
.unwrap_or_default(),
),
output_schema: None,
annotations: None,
},
Tool {
name: Cow::Borrowed("grant-environment-variable-permission"),
description: Some(Cow::Borrowed(
"Grants environment variable access permission to a component, allowing it to access specific environment variables."
)),
input_schema: Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {
"component_id": {
"type": "string",
"description": "ID of the component to grant environment variable permission to"
},
"details": {
"type": "object",
"properties": {
"key": {
"type": "string",
"description": "Environment variable key to grant access to"
}
},
"required": ["key"],
"additionalProperties": false
}
},
"required": ["component_id", "details"]
}))
.unwrap_or_default(),
),
output_schema: None,
annotations: None,
},
Tool {
name: Cow::Borrowed("revoke-storage-permission"),
description: Some(Cow::Borrowed(
"Revokes all storage access permissions from a component for the specified URI path, removing both read and write access to that location."
)),
input_schema: Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {
"component_id": {
"type": "string",
"description": "ID of the component to revoke storage permission from"
},
"details": {
"type": "object",
"properties": {
"uri": {
"type": "string",
"description": "URI of the storage resource to revoke all access from. e.g. fs:///tmp/test"
}
},
"required": ["uri"],
"additionalProperties": false
}
},
"required": ["component_id", "details"]
}))
.unwrap_or_default(),
),
output_schema: None,
annotations: None,
},
Tool {
name: Cow::Borrowed("revoke-network-permission"),
description: Some(Cow::Borrowed(
"Revokes network access permission from a component, removing its ability to make network requests to specific hosts."
)),
input_schema: Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {
"component_id": {
"type": "string",
"description": "ID of the component to revoke network permission from"
},
"details": {
"type": "object",
"properties": {
"host": {
"type": "string",
"description": "Host to revoke network access from"
}
},
"required": ["host"],
"additionalProperties": false
}
},
"required": ["component_id", "details"]
}))
.unwrap_or_default(),
),
output_schema: None,
annotations: None,
},
Tool {
name: Cow::Borrowed("revoke-environment-variable-permission"),
description: Some(Cow::Borrowed(
"Revokes environment variable access permission from a component, removing its ability to access specific environment variables."
)),
input_schema: Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {
"component_id": {
"type": "string",
"description": "ID of the component to revoke environment variable permission from"
},
"details": {
"type": "object",
"properties": {
"key": {
"type": "string",
"description": "Environment variable key to revoke access from"
}
},
"required": ["key"],
"additionalProperties": false
}
},
"required": ["component_id", "details"]
}))
.unwrap_or_default(),
),
output_schema: None,
annotations: None,
},
Tool {
name: Cow::Borrowed("reset-permission"),
description: Some(Cow::Borrowed(
"Resets all permissions for a component, removing all granted permissions and returning it to the default state."
)),
input_schema: Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {
"component_id": {
"type": "string",
"description": "ID of the component to reset permissions for"
}
},
"required": ["component_id"]
}))
.unwrap_or_default(),
),
output_schema: None,
annotations: None,
},
Tool {
name: Cow::Borrowed("search-components"),
description: Some(Cow::Borrowed(
"Lists all known components that can be fetched and loaded. Optionally filter by a search query.",
)),
input_schema: Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Optional search query to filter components by name, description, or URI"
}
},
"required": []
}))
.unwrap_or_default(),
),
output_schema: None,
annotations: None,
},
]
}
/// Calculate a relevance score for a component based on query terms
/// Higher scores indicate better matches
fn calculate_relevance_score(component: &Value, query_terms: &[String]) -> u32 {
let name = component["name"].as_str().unwrap_or("").to_lowercase();
let description = component["description"]
.as_str()
.unwrap_or("")
.to_lowercase();
let uri = component["uri"].as_str().unwrap_or("").to_lowercase();
let mut score = 0u32;
for term in query_terms {
// Exact name match gets highest score
if name == term.as_str() {
score += 100;
} else if name.starts_with(term) {
score += 50;
} else if name.contains(term) {
score += 20;
}
// Description matches get medium score
if description.starts_with(term) {
score += 15;
} else if description.contains(term) {
score += 10;
}
// URI matches get lower score
if uri.contains(term) {
score += 5;
}
}
score
}
#[instrument(skip(_lifecycle_manager))]
pub(crate) async fn handle_search_component(
req: &CallToolRequestParam,
_lifecycle_manager: &LifecycleManager,
) -> Result<CallToolResult> {
let args = extract_args_from_request(req)?;
// Extract the optional query parameter
let query = args.get("query").and_then(|v| v.as_str());
// Parse the component list
let components_value: Value = serde_json::from_str(COMPONENT_LIST)?;
let all_components = components_value
.as_array()
.ok_or_else(|| anyhow::anyhow!("Component registry is not an array"))?;
// Filter and rank components based on query
let filtered_components: Vec<Value> = if let Some(q) = query {
// Split query into words for multi-term matching
let query_terms: Vec<String> = q
.split_whitespace()
.map(|term| term.to_lowercase())
.collect();
if query_terms.is_empty() {
all_components.to_vec()
} else {
// Calculate relevance scores and filter out non-matches
let mut scored_components: Vec<(u32, &Value)> = all_components
.iter()
.map(|component| {
let score = calculate_relevance_score(component, &query_terms);
(score, component)
})
.filter(|(score, _)| *score > 0)
.collect();
// Sort by relevance score (descending)
scored_components.sort_by(|a, b| b.0.cmp(&a.0));
// Extract components in ranked order
scored_components
.into_iter()
.map(|(_, component)| (*component).clone())
.collect()
}
} else {
all_components.to_vec()
};
let status_text = serde_json::to_string(&json!({
"status": "Component list found",
"components": filtered_components,
}))?;
let contents = vec![Content::text(status_text)];
Ok(CallToolResult {
content: Some(contents),
structured_content: None,
is_error: None,
})
}
#[instrument(skip(lifecycle_manager))]
pub async fn handle_get_policy(
req: &CallToolRequestParam,
lifecycle_manager: &LifecycleManager,
) -> Result<CallToolResult> {
let args = extract_args_from_request(req)?;
let component_id = args
.get("component_id")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow::anyhow!("Missing required argument: 'component_id'"))?;
info!("Getting policy for component {}", component_id);
// Ensure the component is available (compile lazily if needed)
lifecycle_manager
.ensure_component_loaded(component_id)
.await
.map_err(|e| anyhow::anyhow!("Component not found: {} ({})", component_id, e))?;
let policy_info = lifecycle_manager.get_policy_info(component_id).await;
let status_text = if let Some(info) = policy_info {
serde_json::to_string(&json!({
"status": "policy found",
"component_id": component_id,
"policy_info": {
"policy_id": info.policy_id,
"source_uri": info.source_uri,
"local_path": info.local_path,
"created_at": info.created_at.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default().as_secs()
}
}))?
} else {
serde_json::to_string(&json!({
"status": "no policy found",
"component_id": component_id
}))?
};
let contents = vec![Content::text(status_text)];
Ok(CallToolResult {
content: Some(contents),
structured_content: None,
is_error: None,
})
}
/// Generic helper for handling grant permission requests
async fn handle_grant_permission_generic(
req: &CallToolRequestParam,
lifecycle_manager: &LifecycleManager,
permission_type: &str,
permission_display_name: &str,
) -> Result<CallToolResult> {
let args = extract_args_from_request(req)?;
let component_id = args
.get("component_id")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow::anyhow!("Missing required argument: 'component_id'"))?;
let details = args
.get("details")
.ok_or_else(|| anyhow::anyhow!("Missing required argument: 'details'"))?;
info!(
"Granting {} permission to component {}",
permission_display_name, component_id
);
// Ensure component is loaded (lazy compile)
lifecycle_manager
.ensure_component_loaded(component_id)
.await
.map_err(|e| anyhow::anyhow!("Component not found: {} ({})", component_id, e))?;
let result = lifecycle_manager
.grant_permission(component_id, permission_type, details)
.await;
match result {
Ok(()) => {
let status_text = serde_json::to_string(&json!({
"status": "permission granted successfully",
"component_id": component_id,
"permission_type": permission_display_name,
"details": details
}))?;
let contents = vec![Content::text(status_text)];
Ok(CallToolResult {
content: Some(contents),
structured_content: None,
is_error: None,
})
}
Err(e) => {
error!(
"Failed to grant {} permission: {}",
permission_display_name, e
);
Err(anyhow::anyhow!(
"Failed to grant {} permission to component {}: {}",
permission_display_name,
component_id,
e
))
}
}
}
#[instrument(skip(lifecycle_manager))]
pub async fn handle_grant_storage_permission(
req: &CallToolRequestParam,
lifecycle_manager: &LifecycleManager,
) -> Result<CallToolResult> {
handle_grant_permission_generic(req, lifecycle_manager, "storage", "storage").await
}
#[instrument(skip(lifecycle_manager))]
pub async fn handle_grant_network_permission(
req: &CallToolRequestParam,
lifecycle_manager: &LifecycleManager,
) -> Result<CallToolResult> {
handle_grant_permission_generic(req, lifecycle_manager, "network", "network").await
}
#[instrument(skip(lifecycle_manager))]
pub async fn handle_grant_environment_variable_permission(
req: &CallToolRequestParam,
lifecycle_manager: &LifecycleManager,
) -> Result<CallToolResult> {
handle_grant_permission_generic(
req,
lifecycle_manager,
"environment",
"environment variable",
)
.await
}
#[instrument(skip(lifecycle_manager))]
pub async fn handle_grant_memory_permission(
req: &CallToolRequestParam,
lifecycle_manager: &LifecycleManager,
) -> Result<CallToolResult> {
handle_grant_permission_generic(req, lifecycle_manager, "resource", "memory").await
}
/// Generic helper for handling revoke permission requests
async fn handle_revoke_permission_generic(
req: &CallToolRequestParam,
lifecycle_manager: &LifecycleManager,
permission_type: &str,
permission_display_name: &str,
) -> Result<CallToolResult> {
let args = extract_args_from_request(req)?;
let component_id = args
.get("component_id")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow::anyhow!("Missing required argument: 'component_id'"))?;
let details = args
.get("details")
.ok_or_else(|| anyhow::anyhow!("Missing required argument: 'details'"))?;
info!(
"Revoking {} permission from component {}",
permission_display_name, component_id
);
lifecycle_manager
.ensure_component_loaded(component_id)
.await
.map_err(|e| anyhow::anyhow!("Component not found: {} ({})", component_id, e))?;
let result = lifecycle_manager
.revoke_permission(component_id, permission_type, details)
.await;
match result {
Ok(()) => {
let status_text = serde_json::to_string(&json!({
"status": "permission revoked",
"component_id": component_id,
"permission_type": permission_display_name,
"details": details
}))?;
let contents = vec![Content::text(status_text)];
Ok(CallToolResult {
content: Some(contents),
structured_content: None,
is_error: None,
})
}
Err(e) => {
error!(
"Failed to revoke {} permission: {}",
permission_display_name, e
);
Err(anyhow::anyhow!(
"Failed to revoke {} permission from component {}: {}",
permission_display_name,
component_id,
e
))
}
}
}
#[instrument(skip(lifecycle_manager))]
pub async fn handle_revoke_storage_permission(
req: &CallToolRequestParam,
lifecycle_manager: &LifecycleManager,
) -> Result<CallToolResult> {
let args = extract_args_from_request(req)?;
let component_id = args
.get("component_id")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow::anyhow!("Missing required argument: 'component_id'"))?;
let details = args
.get("details")
.ok_or_else(|| anyhow::anyhow!("Missing required argument: 'details'"))?;
let uri = details
.get("uri")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow::anyhow!("Missing 'uri' field in details"))?;
info!(
"Revoking all storage permissions for URI {} from component {}",
uri, component_id
);
lifecycle_manager
.ensure_component_loaded(component_id)
.await
.map_err(|e| anyhow::anyhow!("Component not found: {} ({})", component_id, e))?;
let result = lifecycle_manager
.revoke_storage_permission_by_uri(component_id, uri)
.await;
match result {
Ok(()) => {
let status_text = serde_json::to_string(&json!({
"status": "permission revoked successfully",
"component_id": component_id,
"uri": uri,
"message": "All access (read and write) to the specified URI has been revoked"
}))?;
let contents = vec![Content::text(status_text)];
Ok(CallToolResult {
content: Some(contents),
structured_content: None,
is_error: None,
})
}
Err(e) => {
error!("Failed to revoke storage permission: {}", e);
Err(anyhow::anyhow!(
"Failed to revoke storage permission from component {}: {}",
component_id,
e
))
}
}
}
#[instrument(skip(lifecycle_manager))]
pub async fn handle_revoke_network_permission(
req: &CallToolRequestParam,
lifecycle_manager: &LifecycleManager,
) -> Result<CallToolResult> {
handle_revoke_permission_generic(req, lifecycle_manager, "network", "network").await
}
#[instrument(skip(lifecycle_manager))]
pub async fn handle_revoke_environment_variable_permission(
req: &CallToolRequestParam,
lifecycle_manager: &LifecycleManager,
) -> Result<CallToolResult> {
handle_revoke_permission_generic(
req,
lifecycle_manager,
"environment",
"environment variable",
)
.await
}
#[instrument(skip(lifecycle_manager))]
pub async fn handle_reset_permission(
req: &CallToolRequestParam,
lifecycle_manager: &LifecycleManager,
) -> Result<CallToolResult> {
let args = extract_args_from_request(req)?;
let component_id = args
.get("component_id")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow::anyhow!("Missing required argument: 'component_id'"))?;
info!("Resetting all permissions for component {}", component_id);
lifecycle_manager
.ensure_component_loaded(component_id)
.await
.map_err(|e| anyhow::anyhow!("Component not found: {} ({})", component_id, e))?;
let result = lifecycle_manager.reset_permission(component_id).await;
match result {
Ok(()) => {
let status_text = serde_json::to_string(&json!({
"status": "permissions reset successfully",
"component_id": component_id
}))?;
let contents = vec![Content::text(status_text)];
Ok(CallToolResult {
content: Some(contents),
structured_content: None,
is_error: None,
})
}
Err(e) => {
error!("Failed to reset permissions: {}", e);
Err(anyhow::anyhow!(
"Failed to reset permissions for component {}: {}",
component_id,
e
))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]