argentor-builtins 1.4.7

50+ built-in skills (web search, crypto, file ops, security, data processing) for Argentor
Documentation
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
//! HTTP-based skills for querying the XcapitSFF backend.
//!
//! Provides five skills that interact with the XcapitSFF REST API:
//!
//! - [`XcapitSearchSkill`] — Full-text search across entities.
//! - [`XcapitLeadInfoSkill`] — Retrieve lead details by ID.
//! - [`XcapitTicketInfoSkill`] — Retrieve ticket details by ID.
//! - [`XcapitKbSearchSkill`] — Search the knowledge base for a ticket's subject/description.
//! - [`XcapitCustomer360Skill`] — Retrieve the 360-degree customer view.
//!
//! All skills share a single `reqwest::Client` with a 10-second timeout and
//! target the base URL configured via the `XCAPITSFF_URL` environment variable
//! (defaults to `http://localhost:8000`).

use argentor_core::{ArgentorResult, ToolCall, ToolResult};
use argentor_security::{Capability, PermissionSet};
use argentor_skills::skill::{Skill, SkillDescriptor};
use argentor_skills::SkillRegistry;
use async_trait::async_trait;
use std::sync::Arc;
use std::time::Duration;
use tracing::info;

/// Default base URL used when the `XCAPITSFF_URL` environment variable is not set.
const DEFAULT_BASE_URL: &str = "http://localhost:8000";

/// Build a shared `reqwest::Client` with a 10-second timeout.
///
/// # Panics
///
/// Panics if the TLS backend cannot be initialized (fundamentally broken
/// environment with no recovery path).
fn build_xcapitsff_client() -> reqwest::Client {
    #[allow(clippy::expect_used)]
    reqwest::Client::builder()
        .timeout(Duration::from_secs(10))
        .build()
        .expect("Failed to create HTTP client -- TLS backend unavailable")
}

/// Resolve the XcapitSFF base URL from the environment or a provided override.
///
/// Priority: `base_url` parameter > `XCAPITSFF_URL` env var > [`DEFAULT_BASE_URL`].
fn resolve_base_url(base_url: &str) -> String {
    if !base_url.is_empty() {
        return base_url.trim_end_matches('/').to_string();
    }
    std::env::var("XCAPITSFF_URL")
        .unwrap_or_else(|_| DEFAULT_BASE_URL.to_string())
        .trim_end_matches('/')
        .to_string()
}

/// Extract the host portion from a base URL for capability declarations.
fn host_from_url(base_url: &str) -> String {
    reqwest::Url::parse(base_url)
        .ok()
        .and_then(|u| u.host_str().map(String::from))
        .unwrap_or_else(|| "localhost".to_string())
}

// ---------------------------------------------------------------------------
// XcapitSearchSkill
// ---------------------------------------------------------------------------

/// Full-text search across XcapitSFF entities.
///
/// Issues a GET request to `/api/v1/search/?q={query}` and returns the JSON
/// response body.
pub struct XcapitSearchSkill {
    /// Skill metadata.
    descriptor: SkillDescriptor,
    /// Shared HTTP client.
    client: reqwest::Client,
    /// Resolved base URL (no trailing slash).
    base_url: String,
}

impl XcapitSearchSkill {
    /// Create a new `XcapitSearchSkill`.
    ///
    /// `base_url` overrides `XCAPITSFF_URL`; pass `""` to use the env/default.
    pub fn new(base_url: &str, client: reqwest::Client) -> Self {
        let base = resolve_base_url(base_url);
        let host = host_from_url(&base);
        Self {
            descriptor: SkillDescriptor {
                name: "xcapitsff_search".to_string(),
                description: "Search across XcapitSFF entities by query string.".to_string(),
                parameters_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "query": {
                            "type": "string",
                            "description": "The search query string"
                        }
                    },
                    "required": ["query"]
                }),
                required_capabilities: vec![Capability::NetworkAccess {
                    allowed_hosts: vec![host],
                }],
                requires_approval: false,
            },
            client,
            base_url: base,
        }
    }
}

#[async_trait]
impl Skill for XcapitSearchSkill {
    fn descriptor(&self) -> &SkillDescriptor {
        &self.descriptor
    }

    fn validate_arguments(
        &self,
        call: &ToolCall,
        _permissions: &PermissionSet,
    ) -> ArgentorResult<()> {
        let query = call.arguments.get("query").and_then(|v| v.as_str());
        if query.is_none() || query.is_some_and(str::is_empty) {
            return Err(argentor_core::ArgentorError::Skill(
                "Missing or empty 'query' parameter".to_string(),
            ));
        }
        Ok(())
    }

    async fn execute(&self, call: ToolCall) -> ArgentorResult<ToolResult> {
        let query = call.arguments["query"]
            .as_str()
            .unwrap_or_default()
            .to_string();

        if query.is_empty() {
            return Ok(ToolResult::error(
                &call.id,
                "Missing or empty 'query' parameter",
            ));
        }

        let mut parsed = reqwest::Url::parse(&format!("{}/api/v1/search/", self.base_url))
            .map_err(|e| argentor_core::ArgentorError::Skill(format!("Invalid base URL: {e}")))?;
        parsed.query_pairs_mut().append_pair("q", &query);
        let url = parsed.to_string();
        info!(skill = "xcapitsff_search", url = %url, "XcapitSFF search");

        match self.client.get(&url).send().await {
            Ok(resp) => {
                let status = resp.status().as_u16();
                let body = resp.text().await.unwrap_or_default();
                if (200..400).contains(&status) {
                    Ok(ToolResult::success(&call.id, body))
                } else {
                    Ok(ToolResult::error(
                        &call.id,
                        format!("HTTP {status}: {body}"),
                    ))
                }
            }
            Err(e) => Ok(ToolResult::error(&call.id, format!("Request failed: {e}"))),
        }
    }
}

// ---------------------------------------------------------------------------
// XcapitLeadInfoSkill
// ---------------------------------------------------------------------------

/// Retrieve lead details by ID from XcapitSFF.
///
/// Issues a GET request to `/api/v1/leads/{lead_id}`.
pub struct XcapitLeadInfoSkill {
    /// Skill metadata.
    descriptor: SkillDescriptor,
    /// Shared HTTP client.
    client: reqwest::Client,
    /// Resolved base URL (no trailing slash).
    base_url: String,
}

impl XcapitLeadInfoSkill {
    /// Create a new `XcapitLeadInfoSkill`.
    pub fn new(base_url: &str, client: reqwest::Client) -> Self {
        let base = resolve_base_url(base_url);
        let host = host_from_url(&base);
        Self {
            descriptor: SkillDescriptor {
                name: "xcapitsff_lead_info".to_string(),
                description: "Retrieve lead details by ID from XcapitSFF.".to_string(),
                parameters_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "lead_id": {
                            "type": "integer",
                            "description": "The lead ID to retrieve"
                        }
                    },
                    "required": ["lead_id"]
                }),
                required_capabilities: vec![Capability::NetworkAccess {
                    allowed_hosts: vec![host],
                }],
                requires_approval: false,
            },
            client,
            base_url: base,
        }
    }
}

#[async_trait]
impl Skill for XcapitLeadInfoSkill {
    fn descriptor(&self) -> &SkillDescriptor {
        &self.descriptor
    }

    fn validate_arguments(
        &self,
        call: &ToolCall,
        _permissions: &PermissionSet,
    ) -> ArgentorResult<()> {
        let lead_id = call.arguments.get("lead_id");
        if lead_id.is_none() || !lead_id.is_some_and(|v| v.is_i64() || v.is_u64()) {
            return Err(argentor_core::ArgentorError::Skill(
                "Missing or non-integer 'lead_id' parameter".to_string(),
            ));
        }
        Ok(())
    }

    async fn execute(&self, call: ToolCall) -> ArgentorResult<ToolResult> {
        let lead_id = match call.arguments["lead_id"].as_i64() {
            Some(id) => id,
            None => {
                return Ok(ToolResult::error(
                    &call.id,
                    "Missing or non-integer 'lead_id' parameter",
                ));
            }
        };

        let url = format!("{}/api/v1/leads/{}", self.base_url, lead_id);
        info!(skill = "xcapitsff_lead_info", url = %url, "XcapitSFF lead info");

        match self.client.get(&url).send().await {
            Ok(resp) => {
                let status = resp.status().as_u16();
                let body = resp.text().await.unwrap_or_default();
                if (200..400).contains(&status) {
                    Ok(ToolResult::success(&call.id, body))
                } else {
                    Ok(ToolResult::error(
                        &call.id,
                        format!("HTTP {status}: {body}"),
                    ))
                }
            }
            Err(e) => Ok(ToolResult::error(&call.id, format!("Request failed: {e}"))),
        }
    }
}

// ---------------------------------------------------------------------------
// XcapitTicketInfoSkill
// ---------------------------------------------------------------------------

/// Retrieve ticket details by ID from XcapitSFF.
///
/// Issues a GET request to `/api/v1/tickets/{ticket_id}`.
pub struct XcapitTicketInfoSkill {
    /// Skill metadata.
    descriptor: SkillDescriptor,
    /// Shared HTTP client.
    client: reqwest::Client,
    /// Resolved base URL (no trailing slash).
    base_url: String,
}

impl XcapitTicketInfoSkill {
    /// Create a new `XcapitTicketInfoSkill`.
    pub fn new(base_url: &str, client: reqwest::Client) -> Self {
        let base = resolve_base_url(base_url);
        let host = host_from_url(&base);
        Self {
            descriptor: SkillDescriptor {
                name: "xcapitsff_ticket_info".to_string(),
                description: "Retrieve ticket details by ID from XcapitSFF.".to_string(),
                parameters_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "ticket_id": {
                            "type": "integer",
                            "description": "The ticket ID to retrieve"
                        }
                    },
                    "required": ["ticket_id"]
                }),
                required_capabilities: vec![Capability::NetworkAccess {
                    allowed_hosts: vec![host],
                }],
                requires_approval: false,
            },
            client,
            base_url: base,
        }
    }
}

#[async_trait]
impl Skill for XcapitTicketInfoSkill {
    fn descriptor(&self) -> &SkillDescriptor {
        &self.descriptor
    }

    fn validate_arguments(
        &self,
        call: &ToolCall,
        _permissions: &PermissionSet,
    ) -> ArgentorResult<()> {
        let ticket_id = call.arguments.get("ticket_id");
        if ticket_id.is_none() || !ticket_id.is_some_and(|v| v.is_i64() || v.is_u64()) {
            return Err(argentor_core::ArgentorError::Skill(
                "Missing or non-integer 'ticket_id' parameter".to_string(),
            ));
        }
        Ok(())
    }

    async fn execute(&self, call: ToolCall) -> ArgentorResult<ToolResult> {
        let ticket_id = match call.arguments["ticket_id"].as_i64() {
            Some(id) => id,
            None => {
                return Ok(ToolResult::error(
                    &call.id,
                    "Missing or non-integer 'ticket_id' parameter",
                ));
            }
        };

        let url = format!("{}/api/v1/tickets/{}", self.base_url, ticket_id);
        info!(skill = "xcapitsff_ticket_info", url = %url, "XcapitSFF ticket info");

        match self.client.get(&url).send().await {
            Ok(resp) => {
                let status = resp.status().as_u16();
                let body = resp.text().await.unwrap_or_default();
                if (200..400).contains(&status) {
                    Ok(ToolResult::success(&call.id, body))
                } else {
                    Ok(ToolResult::error(
                        &call.id,
                        format!("HTTP {status}: {body}"),
                    ))
                }
            }
            Err(e) => Ok(ToolResult::error(&call.id, format!("Request failed: {e}"))),
        }
    }
}

// ---------------------------------------------------------------------------
// XcapitKbSearchSkill
// ---------------------------------------------------------------------------

/// Search the XcapitSFF knowledge base for articles matching a ticket's
/// subject and description.
///
/// Issues a GET request to
/// `/api/v1/knowledge/for-ticket?subject={subject}&description={description}`.
pub struct XcapitKbSearchSkill {
    /// Skill metadata.
    descriptor: SkillDescriptor,
    /// Shared HTTP client.
    client: reqwest::Client,
    /// Resolved base URL (no trailing slash).
    base_url: String,
}

impl XcapitKbSearchSkill {
    /// Create a new `XcapitKbSearchSkill`.
    pub fn new(base_url: &str, client: reqwest::Client) -> Self {
        let base = resolve_base_url(base_url);
        let host = host_from_url(&base);
        Self {
            descriptor: SkillDescriptor {
                name: "xcapitsff_kb_search".to_string(),
                description: "Search the knowledge base for articles matching a ticket subject and description.".to_string(),
                parameters_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "subject": {
                            "type": "string",
                            "description": "The ticket subject to search for"
                        },
                        "description": {
                            "type": "string",
                            "description": "The ticket description to search for"
                        }
                    },
                    "required": ["subject", "description"]
                }),
                required_capabilities: vec![Capability::NetworkAccess {
                    allowed_hosts: vec![host],
                }],
                requires_approval: false,
            },
            client,
            base_url: base,
        }
    }
}

#[async_trait]
impl Skill for XcapitKbSearchSkill {
    fn descriptor(&self) -> &SkillDescriptor {
        &self.descriptor
    }

    fn validate_arguments(
        &self,
        call: &ToolCall,
        _permissions: &PermissionSet,
    ) -> ArgentorResult<()> {
        let subject = call.arguments.get("subject").and_then(|v| v.as_str());
        let description = call.arguments.get("description").and_then(|v| v.as_str());

        if subject.is_none() || subject.is_some_and(str::is_empty) {
            return Err(argentor_core::ArgentorError::Skill(
                "Missing or empty 'subject' parameter".to_string(),
            ));
        }
        if description.is_none() || description.is_some_and(str::is_empty) {
            return Err(argentor_core::ArgentorError::Skill(
                "Missing or empty 'description' parameter".to_string(),
            ));
        }
        Ok(())
    }

    async fn execute(&self, call: ToolCall) -> ArgentorResult<ToolResult> {
        let subject = call.arguments["subject"]
            .as_str()
            .unwrap_or_default()
            .to_string();
        let description = call.arguments["description"]
            .as_str()
            .unwrap_or_default()
            .to_string();

        if subject.is_empty() {
            return Ok(ToolResult::error(
                &call.id,
                "Missing or empty 'subject' parameter",
            ));
        }
        if description.is_empty() {
            return Ok(ToolResult::error(
                &call.id,
                "Missing or empty 'description' parameter",
            ));
        }

        let mut parsed =
            reqwest::Url::parse(&format!("{}/api/v1/knowledge/for-ticket", self.base_url))
                .map_err(|e| {
                    argentor_core::ArgentorError::Skill(format!("Invalid base URL: {e}"))
                })?;
        parsed
            .query_pairs_mut()
            .append_pair("subject", &subject)
            .append_pair("description", &description);
        let url = parsed.to_string();
        info!(skill = "xcapitsff_kb_search", url = %url, "XcapitSFF KB search");

        match self.client.get(&url).send().await {
            Ok(resp) => {
                let status = resp.status().as_u16();
                let body = resp.text().await.unwrap_or_default();
                if (200..400).contains(&status) {
                    Ok(ToolResult::success(&call.id, body))
                } else {
                    Ok(ToolResult::error(
                        &call.id,
                        format!("HTTP {status}: {body}"),
                    ))
                }
            }
            Err(e) => Ok(ToolResult::error(&call.id, format!("Request failed: {e}"))),
        }
    }
}

// ---------------------------------------------------------------------------
// XcapitCustomer360Skill
// ---------------------------------------------------------------------------

/// Retrieve a 360-degree customer view from XcapitSFF.
///
/// Issues a GET request to `/api/v1/customers/{customer_id}/360`.
pub struct XcapitCustomer360Skill {
    /// Skill metadata.
    descriptor: SkillDescriptor,
    /// Shared HTTP client.
    client: reqwest::Client,
    /// Resolved base URL (no trailing slash).
    base_url: String,
}

impl XcapitCustomer360Skill {
    /// Create a new `XcapitCustomer360Skill`.
    pub fn new(base_url: &str, client: reqwest::Client) -> Self {
        let base = resolve_base_url(base_url);
        let host = host_from_url(&base);
        Self {
            descriptor: SkillDescriptor {
                name: "xcapitsff_customer360".to_string(),
                description: "Retrieve the 360-degree customer view by customer ID from XcapitSFF."
                    .to_string(),
                parameters_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "customer_id": {
                            "type": "integer",
                            "description": "The customer ID to retrieve the 360 view for"
                        }
                    },
                    "required": ["customer_id"]
                }),
                required_capabilities: vec![Capability::NetworkAccess {
                    allowed_hosts: vec![host],
                }],
                requires_approval: false,
            },
            client,
            base_url: base,
        }
    }
}

#[async_trait]
impl Skill for XcapitCustomer360Skill {
    fn descriptor(&self) -> &SkillDescriptor {
        &self.descriptor
    }

    fn validate_arguments(
        &self,
        call: &ToolCall,
        _permissions: &PermissionSet,
    ) -> ArgentorResult<()> {
        let customer_id = call.arguments.get("customer_id");
        if customer_id.is_none() || !customer_id.is_some_and(|v| v.is_i64() || v.is_u64()) {
            return Err(argentor_core::ArgentorError::Skill(
                "Missing or non-integer 'customer_id' parameter".to_string(),
            ));
        }
        Ok(())
    }

    async fn execute(&self, call: ToolCall) -> ArgentorResult<ToolResult> {
        let customer_id = match call.arguments["customer_id"].as_i64() {
            Some(id) => id,
            None => {
                return Ok(ToolResult::error(
                    &call.id,
                    "Missing or non-integer 'customer_id' parameter",
                ));
            }
        };

        let url = format!("{}/api/v1/customers/{}/360", self.base_url, customer_id);
        info!(skill = "xcapitsff_customer360", url = %url, "XcapitSFF customer 360");

        match self.client.get(&url).send().await {
            Ok(resp) => {
                let status = resp.status().as_u16();
                let body = resp.text().await.unwrap_or_default();
                if (200..400).contains(&status) {
                    Ok(ToolResult::success(&call.id, body))
                } else {
                    Ok(ToolResult::error(
                        &call.id,
                        format!("HTTP {status}: {body}"),
                    ))
                }
            }
            Err(e) => Ok(ToolResult::error(&call.id, format!("Request failed: {e}"))),
        }
    }
}

// ---------------------------------------------------------------------------
// Registration helper
// ---------------------------------------------------------------------------

/// Register all five XcapitSFF skills into the given registry.
///
/// A single `reqwest::Client` with a 10-second timeout is shared across all
/// skills. `base_url` overrides the `XCAPITSFF_URL` env var; pass `""` to
/// use the environment variable or the default (`http://localhost:8000`).
pub fn register_xcapitsff_skills(registry: &SkillRegistry, base_url: &str) {
    let client = build_xcapitsff_client();
    registry.register(Arc::new(XcapitSearchSkill::new(base_url, client.clone())));
    registry.register(Arc::new(XcapitLeadInfoSkill::new(base_url, client.clone())));
    registry.register(Arc::new(XcapitTicketInfoSkill::new(
        base_url,
        client.clone(),
    )));
    registry.register(Arc::new(XcapitKbSearchSkill::new(base_url, client.clone())));
    registry.register(Arc::new(XcapitCustomer360Skill::new(base_url, client)));
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use argentor_security::PermissionSet;
    use wiremock::matchers::{method, path, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    /// Helper: create a ToolCall with the given name and arguments.
    fn make_call(name: &str, args: serde_json::Value) -> ToolCall {
        ToolCall {
            id: format!("test_{name}"),
            name: name.to_string(),
            arguments: args,
        }
    }

    // -- Descriptor name tests -----------------------------------------------

    #[test]
    fn test_search_descriptor_name() {
        let client = build_xcapitsff_client();
        let skill = XcapitSearchSkill::new("http://example.com", client);
        assert_eq!(skill.descriptor().name, "xcapitsff_search");
    }

    #[test]
    fn test_lead_info_descriptor_name() {
        let client = build_xcapitsff_client();
        let skill = XcapitLeadInfoSkill::new("http://example.com", client);
        assert_eq!(skill.descriptor().name, "xcapitsff_lead_info");
    }

    #[test]
    fn test_ticket_info_descriptor_name() {
        let client = build_xcapitsff_client();
        let skill = XcapitTicketInfoSkill::new("http://example.com", client);
        assert_eq!(skill.descriptor().name, "xcapitsff_ticket_info");
    }

    #[test]
    fn test_kb_search_descriptor_name() {
        let client = build_xcapitsff_client();
        let skill = XcapitKbSearchSkill::new("http://example.com", client);
        assert_eq!(skill.descriptor().name, "xcapitsff_kb_search");
    }

    #[test]
    fn test_customer360_descriptor_name() {
        let client = build_xcapitsff_client();
        let skill = XcapitCustomer360Skill::new("http://example.com", client);
        assert_eq!(skill.descriptor().name, "xcapitsff_customer360");
    }

    // -- Descriptor capability tests -----------------------------------------

    #[test]
    fn test_descriptor_capabilities_contain_host() {
        let client = build_xcapitsff_client();
        let skill = XcapitSearchSkill::new("http://my-backend:9000", client);
        let caps = &skill.descriptor().required_capabilities;
        assert_eq!(caps.len(), 1);
        match &caps[0] {
            Capability::NetworkAccess { allowed_hosts } => {
                assert_eq!(allowed_hosts, &["my-backend".to_string()]);
            }
            other => panic!("Expected NetworkAccess, got {other:?}"),
        }
    }

    // -- Parameter validation tests ------------------------------------------

    #[test]
    fn test_search_validate_missing_query() {
        let client = build_xcapitsff_client();
        let skill = XcapitSearchSkill::new("http://x", client);
        let call = make_call("xcapitsff_search", serde_json::json!({}));
        let perms = PermissionSet::new();
        assert!(skill.validate_arguments(&call, &perms).is_err());
    }

    #[test]
    fn test_search_validate_empty_query() {
        let client = build_xcapitsff_client();
        let skill = XcapitSearchSkill::new("http://x", client);
        let call = make_call("xcapitsff_search", serde_json::json!({"query": ""}));
        let perms = PermissionSet::new();
        assert!(skill.validate_arguments(&call, &perms).is_err());
    }

    #[test]
    fn test_lead_validate_missing_id() {
        let client = build_xcapitsff_client();
        let skill = XcapitLeadInfoSkill::new("http://x", client);
        let call = make_call("xcapitsff_lead_info", serde_json::json!({}));
        let perms = PermissionSet::new();
        assert!(skill.validate_arguments(&call, &perms).is_err());
    }

    #[test]
    fn test_lead_validate_non_integer_id() {
        let client = build_xcapitsff_client();
        let skill = XcapitLeadInfoSkill::new("http://x", client);
        let call = make_call("xcapitsff_lead_info", serde_json::json!({"lead_id": "abc"}));
        let perms = PermissionSet::new();
        assert!(skill.validate_arguments(&call, &perms).is_err());
    }

    #[test]
    fn test_ticket_validate_missing_id() {
        let client = build_xcapitsff_client();
        let skill = XcapitTicketInfoSkill::new("http://x", client);
        let call = make_call("xcapitsff_ticket_info", serde_json::json!({}));
        let perms = PermissionSet::new();
        assert!(skill.validate_arguments(&call, &perms).is_err());
    }

    #[test]
    fn test_customer360_validate_missing_id() {
        let client = build_xcapitsff_client();
        let skill = XcapitCustomer360Skill::new("http://x", client);
        let call = make_call("xcapitsff_customer360", serde_json::json!({}));
        let perms = PermissionSet::new();
        assert!(skill.validate_arguments(&call, &perms).is_err());
    }

    #[test]
    fn test_kb_validate_missing_subject() {
        let client = build_xcapitsff_client();
        let skill = XcapitKbSearchSkill::new("http://x", client);
        let call = make_call(
            "xcapitsff_kb_search",
            serde_json::json!({"description": "desc"}),
        );
        let perms = PermissionSet::new();
        assert!(skill.validate_arguments(&call, &perms).is_err());
    }

    #[test]
    fn test_kb_validate_missing_description() {
        let client = build_xcapitsff_client();
        let skill = XcapitKbSearchSkill::new("http://x", client);
        let call = make_call(
            "xcapitsff_kb_search",
            serde_json::json!({"subject": "subj"}),
        );
        let perms = PermissionSet::new();
        assert!(skill.validate_arguments(&call, &perms).is_err());
    }

    // -- Execute with mock server tests --------------------------------------

    #[tokio::test]
    async fn test_search_execute_success() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v1/search/"))
            .and(query_param("q", "test query"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"results": []})),
            )
            .mount(&server)
            .await;

        let client = build_xcapitsff_client();
        let skill = XcapitSearchSkill::new(&server.uri(), client);
        let call = make_call(
            "xcapitsff_search",
            serde_json::json!({"query": "test query"}),
        );
        let result = skill.execute(call).await.unwrap();
        assert!(
            !result.is_error,
            "Expected success, got: {}",
            result.content
        );
        assert!(result.content.contains("results"));
    }

    #[tokio::test]
    async fn test_lead_info_execute_success() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v1/leads/42"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"id": 42, "name": "John Doe"})),
            )
            .mount(&server)
            .await;

        let client = build_xcapitsff_client();
        let skill = XcapitLeadInfoSkill::new(&server.uri(), client);
        let call = make_call("xcapitsff_lead_info", serde_json::json!({"lead_id": 42}));
        let result = skill.execute(call).await.unwrap();
        assert!(
            !result.is_error,
            "Expected success, got: {}",
            result.content
        );
        assert!(result.content.contains("John Doe"));
    }

    #[tokio::test]
    async fn test_ticket_info_execute_success() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v1/tickets/99"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"id": 99, "status": "open"})),
            )
            .mount(&server)
            .await;

        let client = build_xcapitsff_client();
        let skill = XcapitTicketInfoSkill::new(&server.uri(), client);
        let call = make_call(
            "xcapitsff_ticket_info",
            serde_json::json!({"ticket_id": 99}),
        );
        let result = skill.execute(call).await.unwrap();
        assert!(
            !result.is_error,
            "Expected success, got: {}",
            result.content
        );
        assert!(result.content.contains("open"));
    }

    #[tokio::test]
    async fn test_kb_search_execute_success() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v1/knowledge/for-ticket"))
            .and(query_param("subject", "login issue"))
            .and(query_param("description", "cannot login"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"articles": [{"title": "Reset password"}]})),
            )
            .mount(&server)
            .await;

        let client = build_xcapitsff_client();
        let skill = XcapitKbSearchSkill::new(&server.uri(), client);
        let call = make_call(
            "xcapitsff_kb_search",
            serde_json::json!({"subject": "login issue", "description": "cannot login"}),
        );
        let result = skill.execute(call).await.unwrap();
        assert!(
            !result.is_error,
            "Expected success, got: {}",
            result.content
        );
        assert!(result.content.contains("Reset password"));
    }

    #[tokio::test]
    async fn test_customer360_execute_success() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v1/customers/7/360"))
            .respond_with(ResponseTemplate::new(200).set_body_json(
                serde_json::json!({"customer_id": 7, "name": "Acme Corp", "tickets": 3}),
            ))
            .mount(&server)
            .await;

        let client = build_xcapitsff_client();
        let skill = XcapitCustomer360Skill::new(&server.uri(), client);
        let call = make_call(
            "xcapitsff_customer360",
            serde_json::json!({"customer_id": 7}),
        );
        let result = skill.execute(call).await.unwrap();
        assert!(
            !result.is_error,
            "Expected success, got: {}",
            result.content
        );
        assert!(result.content.contains("Acme Corp"));
    }

    #[tokio::test]
    async fn test_execute_returns_error_on_404() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v1/leads/999"))
            .respond_with(ResponseTemplate::new(404).set_body_string("not found"))
            .mount(&server)
            .await;

        let client = build_xcapitsff_client();
        let skill = XcapitLeadInfoSkill::new(&server.uri(), client);
        let call = make_call("xcapitsff_lead_info", serde_json::json!({"lead_id": 999}));
        let result = skill.execute(call).await.unwrap();
        assert!(result.is_error, "Expected error on 404");
        assert!(result.content.contains("404"));
    }

    #[tokio::test]
    async fn test_execute_returns_error_on_500() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v1/tickets/1"))
            .respond_with(ResponseTemplate::new(500).set_body_string("internal server error"))
            .mount(&server)
            .await;

        let client = build_xcapitsff_client();
        let skill = XcapitTicketInfoSkill::new(&server.uri(), client);
        let call = make_call("xcapitsff_ticket_info", serde_json::json!({"ticket_id": 1}));
        let result = skill.execute(call).await.unwrap();
        assert!(result.is_error, "Expected error on 500");
        assert!(result.content.contains("500"));
    }

    #[tokio::test]
    async fn test_search_execute_empty_query_returns_error() {
        let client = build_xcapitsff_client();
        let skill = XcapitSearchSkill::new("http://unused", client);
        let call = make_call("xcapitsff_search", serde_json::json!({"query": ""}));
        let result = skill.execute(call).await.unwrap();
        assert!(result.is_error);
        assert!(result.content.contains("query"));
    }

    // -- Registration test ---------------------------------------------------

    #[test]
    fn test_register_xcapitsff_skills_registers_all_five() {
        let registry = SkillRegistry::new();
        register_xcapitsff_skills(&registry, "http://test-backend:8000");
        assert!(registry.get("xcapitsff_search").is_some());
        assert!(registry.get("xcapitsff_lead_info").is_some());
        assert!(registry.get("xcapitsff_ticket_info").is_some());
        assert!(registry.get("xcapitsff_kb_search").is_some());
        assert!(registry.get("xcapitsff_customer360").is_some());
    }

    // -- Base URL resolution tests -------------------------------------------

    #[test]
    fn test_resolve_base_url_uses_provided() {
        let url = resolve_base_url("http://custom:9000/");
        assert_eq!(url, "http://custom:9000");
    }

    #[test]
    fn test_resolve_base_url_strips_trailing_slash() {
        let url = resolve_base_url("http://example.com/");
        assert_eq!(url, "http://example.com");
    }

    #[test]
    fn test_host_from_url_extracts_host() {
        assert_eq!(host_from_url("http://my-host:8000"), "my-host");
        assert_eq!(
            host_from_url("https://api.example.com/path"),
            "api.example.com"
        );
    }
}