tap-mcp 0.6.0

Model Context Protocol server for TAP Node functionality
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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
//! Customer and connection tools for TAP MCP

use super::schema;
use super::{default_limit, error_text_response, success_text_response, ToolHandler};
use crate::error::{Error, Result};
use crate::mcp::protocol::{CallToolResult, Tool};
use crate::tap_integration::TapIntegration;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use tap_msg::message::TapMessage;
use tap_node::customer::CustomerManager;
use tap_node::storage::models::{Customer, SchemaType};
use tracing::{debug, error};

/// Tool for listing customers (parties that an agent acts for)
pub struct ListCustomersTool {
    tap_integration: Arc<TapIntegration>,
}

/// Parameters for listing customers
#[derive(Debug, Deserialize)]
struct ListCustomersParams {
    agent_did: String,
    #[serde(default = "default_limit")]
    limit: u32,
    #[serde(default)]
    offset: u32,
}

/// Response for listing customers
#[derive(Debug, Serialize)]
struct ListCustomersResponse {
    customers: Vec<CustomerInfo>,
    total: usize,
}

#[derive(Debug, Serialize)]
struct CustomerInfo {
    #[serde(rename = "@id")]
    id: String,
    metadata: HashMap<String, serde_json::Value>,
    transaction_count: usize,
    transaction_ids: Vec<String>,
}

impl ListCustomersTool {
    pub fn new(tap_integration: Arc<TapIntegration>) -> Self {
        Self { tap_integration }
    }

    fn tap_integration(&self) -> &TapIntegration {
        &self.tap_integration
    }
}

#[async_trait::async_trait]
impl ToolHandler for ListCustomersTool {
    async fn handle(&self, arguments: Option<Value>) -> Result<CallToolResult> {
        let params: ListCustomersParams = match arguments {
            Some(args) => serde_json::from_value(args)
                .map_err(|e| Error::invalid_parameter(format!("Invalid parameters: {}", e)))?,
            None => {
                return Ok(error_text_response(
                    "Missing required parameters".to_string(),
                ))
            }
        };

        debug!(
            "Listing customers for agent {} with limit={}, offset={}",
            params.agent_did, params.limit, params.offset
        );

        // Get storage for the agent
        let storage = match self
            .tap_integration()
            .storage_for_agent(&params.agent_did)
            .await
        {
            Ok(storage) => storage,
            Err(e) => {
                error!(
                    "Failed to get storage for agent {}: {}",
                    params.agent_did, e
                );
                return Ok(error_text_response(format!(
                    "Failed to get storage for agent {}: {}",
                    params.agent_did, e
                )));
            }
        };

        // Get all customers for this agent from the database
        let all_customers = match storage.list_customers(&params.agent_did, 1000, 0).await {
            Ok(customers) => customers,
            Err(e) => {
                error!("Failed to list customers: {}", e);
                return Ok(error_text_response(format!(
                    "Failed to list customers: {}",
                    e
                )));
            }
        };

        // Convert database customers to our response format
        let mut customers: Vec<CustomerInfo> = Vec::new();

        for customer in all_customers {
            // Convert customer metadata from profile
            let mut metadata = HashMap::new();

            if let Some(profile) = customer.profile.as_object() {
                // Copy all profile fields as metadata
                for (key, value) in profile {
                    if key != "@context" && key != "@type" && key != "identifier" {
                        metadata.insert(key.clone(), value.clone());
                    }
                }
            }

            // Add specific fields if they exist
            if let Some(given_name) = &customer.given_name {
                metadata.insert(
                    "givenName".to_string(),
                    serde_json::Value::String(given_name.clone()),
                );
            }
            if let Some(family_name) = &customer.family_name {
                metadata.insert(
                    "familyName".to_string(),
                    serde_json::Value::String(family_name.clone()),
                );
            }
            if let Some(display_name) = &customer.display_name {
                metadata.insert(
                    "name".to_string(),
                    serde_json::Value::String(display_name.clone()),
                );
            }
            if let Some(country) = &customer.address_country {
                metadata.insert(
                    "addressCountry".to_string(),
                    serde_json::Value::String(country.clone()),
                );
            }
            if let Some(locality) = &customer.address_locality {
                metadata.insert(
                    "addressLocality".to_string(),
                    serde_json::Value::String(locality.clone()),
                );
            }
            if let Some(postal_code) = &customer.postal_code {
                metadata.insert(
                    "postalCode".to_string(),
                    serde_json::Value::String(postal_code.clone()),
                );
            }

            // Get transaction count for this customer
            // We'll need to search through transactions to find where this customer is involved
            let mut transaction_ids = Vec::new();
            if let Ok(transactions) = storage.list_transactions(1000, 0).await {
                for transaction in transactions {
                    if let Ok(tap_message) =
                        serde_json::from_value::<TapMessage>(transaction.message_json.clone())
                    {
                        // Check if this customer is involved in the transaction
                        let mut is_involved = false;

                        if let TapMessage::Transfer(ref transfer) = tap_message {
                            // Check if customer is originator
                            if let Some(originator) = &transfer.originator {
                                if originator.id == customer.id {
                                    is_involved = true;
                                }
                            }
                            // Check if customer is beneficiary
                            if let Some(ref beneficiary) = transfer.beneficiary {
                                if beneficiary.id == customer.id {
                                    is_involved = true;
                                }
                            }
                            // Check if any agent acts for this customer
                            for agent in &transfer.agents {
                                if agent.for_parties().contains(&customer.id) {
                                    is_involved = true;
                                }
                            }
                        }

                        if is_involved {
                            transaction_ids.push(transaction.reference_id);
                        }
                    }
                }
            }

            customers.push(CustomerInfo {
                id: customer.id,
                metadata,
                transaction_count: transaction_ids.len(),
                transaction_ids,
            });
        }

        let total = customers.len();

        // Apply pagination - customers are already in a Vec
        customers.sort_by(|a, b| a.id.cmp(&b.id));

        let paginated_customers: Vec<CustomerInfo> = customers
            .into_iter()
            .skip(params.offset as usize)
            .take(params.limit as usize)
            .collect();

        let response = ListCustomersResponse {
            customers: paginated_customers,
            total,
        };

        let response_json = serde_json::to_string_pretty(&response)
            .map_err(|e| Error::tool_execution(format!("Failed to serialize response: {}", e)))?;

        Ok(success_text_response(response_json))
    }

    fn get_definition(&self) -> Tool {
        Tool {
            name: "tap_list_customers".to_string(),
            description: "Lists customers (parties) that a specific agent acts on behalf of. Includes metadata about each party and transaction history.".to_string(),
            input_schema: schema::list_customers_schema(),
        }
    }
}

/// Tool for listing connections (counterparties with transaction history)
pub struct ListConnectionsTool {
    tap_integration: Arc<TapIntegration>,
}

/// Parameters for listing connections
#[derive(Debug, Deserialize)]
struct ListConnectionsParams {
    party_id: String,
    #[serde(default = "default_limit")]
    limit: u32,
    #[serde(default)]
    offset: u32,
}

/// Response for listing connections
#[derive(Debug, Serialize)]
struct ListConnectionsResponse {
    connections: Vec<ConnectionInfo>,
    total: usize,
}

#[derive(Debug, Serialize)]
struct ConnectionInfo {
    #[serde(rename = "@id")]
    id: String,
    metadata: HashMap<String, serde_json::Value>,
    transaction_count: usize,
    transaction_ids: Vec<String>,
    roles: Vec<String>, // Roles this counterparty has played
}

impl ListConnectionsTool {
    pub fn new(tap_integration: Arc<TapIntegration>) -> Self {
        Self { tap_integration }
    }

    fn tap_integration(&self) -> &TapIntegration {
        &self.tap_integration
    }
}

#[async_trait::async_trait]
impl ToolHandler for ListConnectionsTool {
    async fn handle(&self, arguments: Option<Value>) -> Result<CallToolResult> {
        let params: ListConnectionsParams = match arguments {
            Some(args) => serde_json::from_value(args)
                .map_err(|e| Error::invalid_parameter(format!("Invalid parameters: {}", e)))?,
            None => {
                return Ok(error_text_response(
                    "Missing required parameters".to_string(),
                ))
            }
        };

        debug!(
            "Listing connections for party {} with limit={}, offset={}",
            params.party_id, params.limit, params.offset
        );

        // We need to search across all agent storages to find transactions involving this party
        let agent_infos = match self.tap_integration().list_agents().await {
            Ok(agents) => agents,
            Err(e) => {
                error!("Failed to list agents: {}", e);
                return Ok(error_text_response(format!("Failed to list agents: {}", e)));
            }
        };

        let mut connections: HashMap<String, ConnectionInfo> = HashMap::new();

        // Search through each agent's storage
        for agent_info in agent_infos {
            let storage = match self
                .tap_integration()
                .storage_for_agent(&agent_info.id)
                .await
            {
                Ok(storage) => storage,
                Err(e) => {
                    debug!("Failed to get storage for agent {}: {}", agent_info.id, e);
                    continue;
                }
            };

            let transactions = match storage.list_transactions(1000, 0).await {
                Ok(transactions) => transactions,
                Err(e) => {
                    debug!(
                        "Failed to get transactions for agent {}: {}",
                        agent_info.id, e
                    );
                    continue;
                }
            };

            // Process each transaction
            for transaction in transactions {
                if let Ok(TapMessage::Transfer(ref transfer)) =
                    serde_json::from_value::<TapMessage>(transaction.message_json.clone())
                {
                    let mut party_is_involved = false;
                    let mut counterparties = HashSet::new();

                    // Check if our party is the originator
                    if let Some(originator) = &transfer.originator {
                        if originator.id == params.party_id {
                            party_is_involved = true;
                            // Add beneficiary as counterparty
                            if let Some(ref beneficiary) = transfer.beneficiary {
                                counterparties.insert(beneficiary.id.clone());
                            }
                        }
                    }

                    // Check if our party is the beneficiary
                    if let Some(ref beneficiary) = transfer.beneficiary {
                        if beneficiary.id == params.party_id {
                            party_is_involved = true;
                            // Add originator as counterparty
                            if let Some(originator) = &transfer.originator {
                                counterparties.insert(originator.id.clone());
                            }
                        }
                    }

                    // Check if our party is represented by any agent
                    for agent in &transfer.agents {
                        if agent.for_parties().contains(&params.party_id) {
                            party_is_involved = true;
                            // Add other parties represented by other agents as counterparties
                            for other_agent in &transfer.agents {
                                if other_agent.id != agent.id {
                                    for other_party in other_agent.for_parties() {
                                        if other_party != &params.party_id {
                                            counterparties.insert(other_party.clone());
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // If this party is involved, record the counterparties
                    if party_is_involved {
                        for counterparty_id in counterparties {
                            let connection = connections
                                .entry(counterparty_id.clone())
                                .or_insert_with(|| ConnectionInfo {
                                    id: counterparty_id.clone(),
                                    metadata: HashMap::new(),
                                    transaction_count: 0,
                                    transaction_ids: Vec::new(),
                                    roles: Vec::new(),
                                });
                            connection.transaction_count += 1;
                            connection
                                .transaction_ids
                                .push(transaction.reference_id.clone());

                            // Determine role of counterparty
                            if let Some(originator) = &transfer.originator {
                                if counterparty_id == originator.id
                                    && !connection.roles.contains(&"originator".to_string())
                                {
                                    connection.roles.push("originator".to_string());
                                }
                            }
                            if let Some(ref beneficiary) = transfer.beneficiary {
                                if counterparty_id == beneficiary.id
                                    && !connection.roles.contains(&"beneficiary".to_string())
                                {
                                    connection.roles.push("beneficiary".to_string());
                                }
                            }

                            // Add metadata from party objects
                            if let Some(originator) = &transfer.originator {
                                if counterparty_id == originator.id {
                                    for (key, value) in &originator.metadata {
                                        connection.metadata.insert(key.clone(), value.clone());
                                    }
                                }
                            }
                            if let Some(ref beneficiary) = transfer.beneficiary {
                                if counterparty_id == beneficiary.id {
                                    for (key, value) in &beneficiary.metadata {
                                        connection.metadata.insert(key.clone(), value.clone());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        let total = connections.len();

        // Apply pagination and sort by ID for consistent ordering
        let mut connection_list: Vec<ConnectionInfo> = connections.into_values().collect();
        connection_list.sort_by(|a, b| a.id.cmp(&b.id));

        let paginated_connections: Vec<ConnectionInfo> = connection_list
            .into_iter()
            .skip(params.offset as usize)
            .take(params.limit as usize)
            .collect();

        let response = ListConnectionsResponse {
            connections: paginated_connections,
            total,
        };

        let response_json = serde_json::to_string_pretty(&response)
            .map_err(|e| Error::tool_execution(format!("Failed to serialize response: {}", e)))?;

        Ok(success_text_response(response_json))
    }

    fn get_definition(&self) -> Tool {
        Tool {
            name: "tap_list_connections".to_string(),
            description: "Lists all counterparties (connections) of a specific party. Includes metadata about each counterparty and transaction history.".to_string(),
            input_schema: schema::list_connections_schema(),
        }
    }
}

/// Tool for getting customer details including IVMS101 data
pub struct GetCustomerDetailsTool {
    tap_integration: Arc<TapIntegration>,
}

/// Parameters for getting customer details
#[derive(Debug, Deserialize)]
struct GetCustomerDetailsParams {
    agent_did: String,
    customer_id: String,
}

/// Response for getting customer details
#[derive(Debug, Serialize)]
struct GetCustomerDetailsResponse {
    customer: Option<serde_json::Value>,
    ivms101_data: Option<serde_json::Value>,
}

impl GetCustomerDetailsTool {
    pub fn new(tap_integration: Arc<TapIntegration>) -> Self {
        Self { tap_integration }
    }

    fn tap_integration(&self) -> &TapIntegration {
        &self.tap_integration
    }
}

#[async_trait::async_trait]
impl ToolHandler for GetCustomerDetailsTool {
    async fn handle(&self, arguments: Option<Value>) -> Result<CallToolResult> {
        let params: GetCustomerDetailsParams = match arguments {
            Some(args) => serde_json::from_value(args)
                .map_err(|e| Error::invalid_parameter(format!("Invalid parameters: {}", e)))?,
            None => {
                return Ok(error_text_response(
                    "Missing required parameters".to_string(),
                ))
            }
        };

        debug!(
            "Getting customer details for customer {} via agent {}",
            params.customer_id, params.agent_did
        );

        // Get storage for the agent
        let storage = match self
            .tap_integration()
            .storage_for_agent(&params.agent_did)
            .await
        {
            Ok(storage) => storage,
            Err(e) => {
                error!(
                    "Failed to get storage for agent {}: {}",
                    params.agent_did, e
                );
                return Ok(error_text_response(format!(
                    "Failed to get storage for agent {}: {}",
                    params.agent_did, e
                )));
            }
        };

        // Get customer data
        let customer = match storage.get_customer(&params.customer_id).await {
            Ok(customer) => customer,
            Err(e) => {
                debug!("Failed to get customer {}: {}", params.customer_id, e);
                None
            }
        };

        let response = if let Some(customer) = customer {
            // Convert customer to JSON value
            let customer_json = serde_json::to_value(&customer).map_err(|e| {
                Error::tool_execution(format!("Failed to serialize customer: {}", e))
            })?;

            let profile = customer_json.get("profile").cloned();
            let ivms101 = customer_json.get("ivms101_data").cloned();

            GetCustomerDetailsResponse {
                customer: Some(profile.unwrap_or(customer_json)),
                ivms101_data: ivms101,
            }
        } else {
            GetCustomerDetailsResponse {
                customer: None,
                ivms101_data: None,
            }
        };

        let response_json = serde_json::to_string_pretty(&response)
            .map_err(|e| Error::tool_execution(format!("Failed to serialize response: {}", e)))?;

        Ok(success_text_response(response_json))
    }

    fn get_definition(&self) -> Tool {
        Tool {
            name: "tap_get_customer_details".to_string(),
            description: "Gets detailed information about a specific customer including their profile and IVMS101 data if available.".to_string(),
            input_schema: schema::get_customer_details_schema(),
        }
    }
}

/// Tool for generating IVMS101 data for a customer
pub struct GenerateIvms101Tool {
    tap_integration: Arc<TapIntegration>,
}

/// Parameters for generating IVMS101
#[derive(Debug, Deserialize)]
struct GenerateIvms101Params {
    agent_did: String,
    customer_id: String,
}

impl GenerateIvms101Tool {
    pub fn new(tap_integration: Arc<TapIntegration>) -> Self {
        Self { tap_integration }
    }

    fn tap_integration(&self) -> &TapIntegration {
        &self.tap_integration
    }
}

#[async_trait::async_trait]
impl ToolHandler for GenerateIvms101Tool {
    async fn handle(&self, arguments: Option<Value>) -> Result<CallToolResult> {
        let params: GenerateIvms101Params = match arguments {
            Some(args) => serde_json::from_value(args)
                .map_err(|e| Error::invalid_parameter(format!("Invalid parameters: {}", e)))?,
            None => {
                return Ok(error_text_response(
                    "Missing required parameters".to_string(),
                ))
            }
        };

        debug!(
            "Generating IVMS101 data for customer {} via agent {}",
            params.customer_id, params.agent_did
        );

        // Get storage for the agent
        let storage = match self
            .tap_integration()
            .storage_for_agent(&params.agent_did)
            .await
        {
            Ok(storage) => storage,
            Err(e) => {
                error!(
                    "Failed to get storage for agent {}: {}",
                    params.agent_did, e
                );
                return Ok(error_text_response(format!(
                    "Failed to get storage for agent {}: {}",
                    params.agent_did, e
                )));
            }
        };

        // Create customer manager
        let customer_manager = CustomerManager::new(storage);

        // Generate IVMS101 data
        match customer_manager
            .generate_ivms101_data(&params.customer_id)
            .await
        {
            Ok(ivms_data) => {
                let response_json = serde_json::to_string_pretty(&ivms_data).map_err(|e| {
                    Error::tool_execution(format!("Failed to serialize IVMS101 data: {}", e))
                })?;
                Ok(success_text_response(response_json))
            }
            Err(e) => {
                error!("Failed to generate IVMS101 data: {}", e);
                Ok(error_text_response(format!(
                    "Failed to generate IVMS101 data: {}",
                    e
                )))
            }
        }
    }

    fn get_definition(&self) -> Tool {
        Tool {
            name: "tap_generate_ivms101".to_string(),
            description: "Generates IVMS101 compliant data for a customer based on their stored profile information.".to_string(),
            input_schema: schema::generate_ivms101_schema(),
        }
    }
}

/// Tool for updating customer profile
pub struct UpdateCustomerProfileTool {
    tap_integration: Arc<TapIntegration>,
}

/// Parameters for updating customer profile
#[derive(Debug, Deserialize)]
struct UpdateCustomerProfileParams {
    agent_did: String,
    customer_id: String,
    profile_data: Value,
}

impl UpdateCustomerProfileTool {
    pub fn new(tap_integration: Arc<TapIntegration>) -> Self {
        Self { tap_integration }
    }

    fn tap_integration(&self) -> &TapIntegration {
        &self.tap_integration
    }
}

#[async_trait::async_trait]
impl ToolHandler for UpdateCustomerProfileTool {
    async fn handle(&self, arguments: Option<Value>) -> Result<CallToolResult> {
        let params: UpdateCustomerProfileParams = match arguments {
            Some(args) => serde_json::from_value(args)
                .map_err(|e| Error::invalid_parameter(format!("Invalid parameters: {}", e)))?,
            None => {
                return Ok(error_text_response(
                    "Missing required parameters".to_string(),
                ))
            }
        };

        debug!(
            "Updating profile for customer {} via agent {}",
            params.customer_id, params.agent_did
        );

        // Get storage for the agent
        let storage = match self
            .tap_integration()
            .storage_for_agent(&params.agent_did)
            .await
        {
            Ok(storage) => storage,
            Err(e) => {
                error!(
                    "Failed to get storage for agent {}: {}",
                    params.agent_did, e
                );
                return Ok(error_text_response(format!(
                    "Failed to get storage for agent {}: {}",
                    params.agent_did, e
                )));
            }
        };

        // Create customer manager
        let customer_manager = CustomerManager::new(storage);

        // Update customer profile
        match customer_manager
            .update_customer_profile(&params.customer_id, params.profile_data)
            .await
        {
            Ok(_) => Ok(success_text_response(format!(
                "Successfully updated profile for customer {}",
                params.customer_id
            ))),
            Err(e) => {
                error!("Failed to update customer profile: {}", e);
                Ok(error_text_response(format!(
                    "Failed to update customer profile: {}",
                    e
                )))
            }
        }
    }

    fn get_definition(&self) -> Tool {
        Tool {
            name: "tap_update_customer_profile".to_string(),
            description: "Updates the schema.org profile data for a customer. The profile_data should be a JSON object with schema.org fields.".to_string(),
            input_schema: schema::update_customer_profile_schema(),
        }
    }
}

/// Tool for creating a new customer
pub struct CreateCustomerTool {
    tap_integration: Arc<TapIntegration>,
}

/// Parameters for creating a customer
#[derive(Debug, Deserialize)]
struct CreateCustomerParams {
    agent_did: String,
    customer_id: String,
    profile_data: Value,
}

impl CreateCustomerTool {
    pub fn new(tap_integration: Arc<TapIntegration>) -> Self {
        Self { tap_integration }
    }

    fn tap_integration(&self) -> &TapIntegration {
        &self.tap_integration
    }
}

#[async_trait::async_trait]
impl ToolHandler for CreateCustomerTool {
    async fn handle(&self, arguments: Option<Value>) -> Result<CallToolResult> {
        let params: CreateCustomerParams = match arguments {
            Some(args) => serde_json::from_value(args)
                .map_err(|e| Error::invalid_parameter(format!("Invalid parameters: {}", e)))?,
            None => {
                return Ok(error_text_response(
                    "Missing required parameters".to_string(),
                ))
            }
        };

        debug!(
            "Creating customer {} via agent {}",
            params.customer_id, params.agent_did
        );

        // Get storage for the agent
        let storage = match self
            .tap_integration()
            .storage_for_agent(&params.agent_did)
            .await
        {
            Ok(storage) => storage,
            Err(e) => {
                error!(
                    "Failed to get storage for agent {}: {}",
                    params.agent_did, e
                );
                return Ok(error_text_response(format!(
                    "Failed to get storage for agent {}: {}",
                    params.agent_did, e
                )));
            }
        };

        // Create customer manager
        let customer_manager = CustomerManager::new(storage.clone());

        // Check if customer already exists
        let existing = match storage.get_customer(&params.customer_id).await {
            Ok(existing) => existing,
            Err(e) => {
                error!("Failed to check existing customer: {}", e);
                return Ok(error_text_response(format!(
                    "Failed to check existing customer: {}",
                    e
                )));
            }
        };

        if existing.is_none() {
            // Create new customer
            let display_name = params
                .profile_data
                .get("givenName")
                .and_then(|v| v.as_str())
                .map(|given| {
                    if let Some(family) = params
                        .profile_data
                        .get("familyName")
                        .and_then(|v| v.as_str())
                    {
                        format!("{} {}", given, family)
                    } else {
                        given.to_string()
                    }
                });

            // Create customer profile from schema.org data
            let mut profile = json!({
                "@context": "https://schema.org",
                "@type": "Person",
                "identifier": params.customer_id.clone(),
            });

            // Merge provided profile data
            if let Value::Object(profile_obj) = &mut profile {
                if let Value::Object(data_obj) = &params.profile_data {
                    for (key, value) in data_obj {
                        profile_obj.insert(key.clone(), value.clone());
                    }
                }
            }

            // Determine schema type based on provided data
            let schema_type = if params.profile_data.get("@type").and_then(|v| v.as_str())
                == Some("Organization")
            {
                SchemaType::Organization
            } else {
                SchemaType::Person
            };

            // Create Customer struct
            let customer = Customer {
                id: params.customer_id.clone(),
                agent_did: params.agent_did.clone(),
                schema_type,
                given_name: params
                    .profile_data
                    .get("givenName")
                    .and_then(|v| v.as_str())
                    .map(String::from),
                family_name: params
                    .profile_data
                    .get("familyName")
                    .and_then(|v| v.as_str())
                    .map(String::from),
                display_name,
                legal_name: params
                    .profile_data
                    .get("legalName")
                    .and_then(|v| v.as_str())
                    .map(String::from),
                lei_code: params
                    .profile_data
                    .get("leiCode")
                    .and_then(|v| v.as_str())
                    .map(String::from),
                mcc_code: params
                    .profile_data
                    .get("mccCode")
                    .and_then(|v| v.as_str())
                    .map(String::from),
                address_country: params
                    .profile_data
                    .get("addressCountry")
                    .and_then(|v| v.as_str())
                    .map(String::from),
                address_locality: params
                    .profile_data
                    .get("addressLocality")
                    .and_then(|v| v.as_str())
                    .map(String::from),
                postal_code: params
                    .profile_data
                    .get("postalCode")
                    .and_then(|v| v.as_str())
                    .map(String::from),
                street_address: params
                    .profile_data
                    .get("streetAddress")
                    .and_then(|v| v.as_str())
                    .map(String::from),
                profile,
                ivms101_data: None,
                verified_at: None,
                created_at: chrono::Utc::now().to_rfc3339(),
                updated_at: chrono::Utc::now().to_rfc3339(),
            };

            // Create the customer
            match storage.upsert_customer(&customer).await {
                Ok(_) => {
                    debug!("Created new customer {}", params.customer_id);
                    Ok(success_text_response(format!(
                        "Successfully created customer {}",
                        params.customer_id
                    )))
                }
                Err(e) => {
                    error!("Failed to create customer: {}", e);
                    Ok(error_text_response(format!(
                        "Failed to create customer: {}",
                        e
                    )))
                }
            }
        } else {
            // Update existing customer
            match customer_manager
                .update_customer_profile(&params.customer_id, params.profile_data)
                .await
            {
                Ok(_) => Ok(success_text_response(format!(
                    "Successfully updated existing customer {}",
                    params.customer_id
                ))),
                Err(e) => {
                    error!("Failed to update customer: {}", e);
                    Ok(error_text_response(format!(
                        "Failed to update customer: {}",
                        e
                    )))
                }
            }
        }
    }

    fn get_definition(&self) -> Tool {
        Tool {
            name: "tap_create_customer".to_string(),
            description: "Creates a new customer profile for an agent. The customer_id should be a DID or unique identifier. The profile_data should be a JSON object with schema.org fields (e.g., givenName, familyName, addressCountry). If a customer with the same ID already exists, their profile will be updated.".to_string(),
            input_schema: schema::create_customer_schema(),
        }
    }
}

/// Tool for updating customer from IVMS101 data
pub struct UpdateCustomerFromIvms101Tool {
    tap_integration: Arc<TapIntegration>,
}

/// Parameters for updating customer from IVMS101
#[derive(Debug, Deserialize)]
struct UpdateCustomerFromIvms101Params {
    agent_did: String,
    customer_id: String,
    ivms101_data: Value,
}

impl UpdateCustomerFromIvms101Tool {
    pub fn new(tap_integration: Arc<TapIntegration>) -> Self {
        Self { tap_integration }
    }

    fn tap_integration(&self) -> &TapIntegration {
        &self.tap_integration
    }
}

#[async_trait::async_trait]
impl ToolHandler for UpdateCustomerFromIvms101Tool {
    async fn handle(&self, arguments: Option<Value>) -> Result<CallToolResult> {
        let params: UpdateCustomerFromIvms101Params = match arguments {
            Some(args) => serde_json::from_value(args)
                .map_err(|e| Error::invalid_parameter(format!("Invalid parameters: {}", e)))?,
            None => {
                return Ok(error_text_response(
                    "Missing required parameters".to_string(),
                ))
            }
        };

        debug!(
            "Updating customer {} from IVMS101 data via agent {}",
            params.customer_id, params.agent_did
        );

        // Get storage for the agent
        let storage = match self
            .tap_integration()
            .storage_for_agent(&params.agent_did)
            .await
        {
            Ok(storage) => storage,
            Err(e) => {
                error!(
                    "Failed to get storage for agent {}: {}",
                    params.agent_did, e
                );
                return Ok(error_text_response(format!(
                    "Failed to get storage for agent {}: {}",
                    params.agent_did, e
                )));
            }
        };

        // Create customer manager
        let customer_manager = CustomerManager::new(storage);

        // Update customer from IVMS101 data
        match customer_manager
            .update_customer_from_ivms101(&params.customer_id, &params.ivms101_data)
            .await
        {
            Ok(_) => Ok(success_text_response(format!(
                "Successfully updated customer {} from IVMS101 data",
                params.customer_id
            ))),
            Err(e) => {
                error!("Failed to update customer from IVMS101: {}", e);
                Ok(error_text_response(format!(
                    "Failed to update customer from IVMS101: {}",
                    e
                )))
            }
        }
    }

    fn get_definition(&self) -> Tool {
        Tool {
            name: "tap_update_customer_from_ivms101".to_string(),
            description: "Updates a customer's profile using IVMS101 data. This extracts name, address and other fields from IVMS101 format.".to_string(),
            input_schema: schema::update_customer_from_ivms101_schema(),
        }
    }
}