composio-sdk 0.3.0

Minimal Rust SDK for Composio Tool Router REST API
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
//! Response models from Composio API

use serde::Deserialize;

use super::enums::AuthScheme;
use super::request::SessionConfig;

/// Response from session creation
#[derive(Debug, Clone, Deserialize)]
pub struct SessionResponse {
    pub session_id: String,
    pub mcp: McpInfo,
    pub tool_router_tools: Vec<String>,
    pub config: SessionConfig,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub assistive_prompt: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub toolkit_versions: Option<super::versioning::ToolkitVersionParam>,
}

/// MCP server information
#[derive(Debug, Clone, Deserialize)]
pub struct McpInfo {
    pub url: String,
}

/// Tool schema information
#[derive(Debug, Clone, Deserialize)]
pub struct ToolSchema {
    pub slug: String,
    pub name: String,
    pub description: String,
    pub toolkit: String,
    pub input_parameters: serde_json::Value,
    pub output_parameters: serde_json::Value,
    #[serde(default)]
    pub scopes: Vec<String>,
    #[serde(default)]
    pub tags: Vec<String>,
    pub version: String,
    #[serde(default)]
    pub available_versions: Vec<String>,
    #[serde(default)]
    pub is_deprecated: bool,
    #[serde(default)]
    pub no_auth: bool,
}

/// Response from tool execution
///
/// Contains the result of a tool execution, including data, error information,
/// and execution metadata.
///
/// # Fields
///
/// * `data` - The execution result data
/// * `error` - Error message if execution failed
/// * `log_id` - Log ID for debugging and tracing
/// * `successful` - Whether the execution was successful (derived from error field)
///
/// # Example
///
/// ```rust
/// use composio_sdk::models::ToolExecutionResponse;
///
/// # fn example(response: ToolExecutionResponse) {
/// if response.is_successful() {
///     println!("Success: {:?}", response.data);
/// } else {
///     eprintln!("Error: {}", response.error.unwrap());
/// }
/// # }
/// ```
#[derive(Debug, Clone, Deserialize)]
pub struct ToolExecutionResponse {
    /// Execution result data
    pub data: serde_json::Value,
    
    /// Error message if execution failed
    pub error: Option<String>,
    
    /// Log ID for debugging and tracing
    pub log_id: String,
    
    /// Whether the execution was successful
    /// This field is computed from the error field during deserialization
    #[serde(default)]
    pub successful: bool,
}

impl ToolExecutionResponse {
    /// Check if the execution was successful
    ///
    /// Returns `true` if there is no error, `false` otherwise.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use composio_sdk::models::ToolExecutionResponse;
    /// # fn example(response: ToolExecutionResponse) {
    /// if response.is_successful() {
    ///     println!("Tool executed successfully!");
    /// }
    /// # }
    /// ```
    pub fn is_successful(&self) -> bool {
        self.error.is_none()
    }
}

/// Response from meta tool execution
pub type MetaToolExecutionResponse = ToolExecutionResponse;

/// Response from listing toolkits
#[derive(Debug, Clone, Deserialize)]
pub struct ToolkitListResponse {
    pub items: Vec<ToolkitInfo>,
    pub next_cursor: Option<String>,
    pub total_pages: u32,
    pub current_page: u32,
    pub total_items: u32,
}

/// Information about a toolkit
#[derive(Debug, Clone, Deserialize)]
pub struct ToolkitInfo {
    pub name: String,
    pub slug: String,
    pub enabled: bool,
    pub is_no_auth: bool,
    pub composio_managed_auth_schemes: Vec<AuthScheme>,
    pub meta: ToolkitMeta,
    pub connected_account: Option<ConnectedAccountInfo>,
}

/// Metadata about a toolkit
#[derive(Debug, Clone, Deserialize)]
pub struct ToolkitMeta {
    pub logo: String,
    pub description: String,
    #[serde(default)]
    pub categories: Vec<String>,
    #[serde(default)]
    pub tools_count: u32,
    #[serde(default)]
    pub triggers_count: u32,
    #[serde(default)]
    pub version: String,
}

/// Information about a connected account
#[derive(Debug, Clone, Deserialize)]
pub struct ConnectedAccountInfo {
    pub id: String,
    pub status: String,
    pub created_at: String,
}

/// Response from creating an auth link
#[derive(Debug, Clone, Deserialize)]
pub struct LinkResponse {
    pub link_token: String,
    pub redirect_url: String,
    pub connected_account_id: Option<String>,
}

// ============================================================================
// Tool Router Session Response Types
// ============================================================================

/// MCP server type for Tool Router sessions
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ToolRouterMcpServerType {
    /// HTTP-based MCP server
    Http,
    /// Server-Sent Events (SSE) based MCP server
    Sse,
}

/// MCP server configuration for Tool Router sessions
///
/// Contains the connection details for accessing the MCP server
/// associated with a Tool Router session.
#[derive(Debug, Clone, Deserialize)]
pub struct ToolRouterMcpServerConfig {
    /// Type of MCP server (HTTP or SSE)
    #[serde(rename = "type")]
    pub server_type: ToolRouterMcpServerType,
    /// MCP server URL
    pub url: String,
    /// Optional authentication headers (includes x-api-key)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<std::collections::HashMap<String, Option<String>>>,
}

/// Experimental features in Tool Router session response
///
/// Note: These features are experimental and may be modified or removed in future versions.
#[derive(Debug, Clone, Deserialize)]
pub struct ToolRouterSessionExperimental {
    /// Generated assistive system prompt based on experimental config
    #[serde(skip_serializing_if = "Option::is_none")]
    pub assistive_prompt: Option<String>,
}

/// Auth config information for a toolkit connection
#[derive(Debug, Clone, Deserialize)]
pub struct ToolkitConnectionAuthConfig {
    /// Auth config ID
    pub id: String,
    /// Authentication scheme/mode
    pub mode: String,
    /// Whether this auth config is managed by Composio
    pub is_composio_managed: bool,
}

/// Connected account information for a toolkit
#[derive(Debug, Clone, Deserialize)]
pub struct ToolkitConnectedAccount {
    /// Connected account ID
    pub id: String,
    /// Connection status (ACTIVE, EXPIRED, FAILED, etc.)
    pub status: String,
}

/// Connection information for a toolkit
#[derive(Debug, Clone, Deserialize)]
pub struct ToolkitConnection {
    /// Whether the connection is active
    pub is_active: bool,
    /// Auth config information (None for no-auth toolkits)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auth_config: Option<ToolkitConnectionAuthConfig>,
    /// Connected account information (None if not connected)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connected_account: Option<ToolkitConnectedAccount>,
}

/// Connection state of a toolkit in a Tool Router session
///
/// Provides detailed information about a toolkit's availability,
/// authentication status, and connection details.
#[derive(Debug, Clone, Deserialize)]
pub struct ToolkitConnectionState {
    /// Toolkit slug (e.g., "github", "gmail")
    pub slug: String,
    /// Human-readable toolkit name
    pub name: String,
    /// Whether this toolkit requires no authentication
    pub is_no_auth: bool,
    /// Connection information (None for no-auth toolkits)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connection: Option<ToolkitConnection>,
    /// Toolkit logo URL
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logo: Option<String>,
}

/// Details of toolkit connections in a Tool Router session
///
/// Contains a paginated list of toolkit connection states with
/// information about authentication and connection status.
#[derive(Debug, Clone, Deserialize)]
pub struct ToolkitConnectionsDetails {
    /// List of toolkit connection states
    pub items: Vec<ToolkitConnectionState>,
    /// Total number of pages available
    pub total_pages: u32,
    /// Cursor for fetching the next page (None if no more pages)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
}

/// Error response from API
#[derive(Debug, Clone, Deserialize)]
pub struct ErrorResponse {
    pub message: String,
    pub code: Option<String>,
    pub slug: Option<String>,
    pub status: u16,
    pub request_id: Option<String>,
    pub suggested_fix: Option<String>,
    pub errors: Option<Vec<crate::error::ErrorDetail>>,
}

// ============================================================================
// Auth Config Response Types
// ============================================================================

/// Response from creating an authentication configuration
#[derive(Debug, Clone, Deserialize)]
pub struct AuthConfigCreateResponse {
    /// Toolkit information
    pub toolkit: ToolkitInfo,
    /// Created auth config information
    pub auth_config: AuthConfigInfo,
}

/// Response from listing authentication configurations
#[derive(Debug, Clone, Deserialize)]
pub struct AuthConfigListResponse {
    /// List of auth configs
    pub items: Vec<AuthConfigDetail>,
    /// Pagination cursor for next page
    pub next_cursor: Option<String>,
    /// Total number of pages
    pub total_pages: u32,
    /// Current page number
    pub current_page: u32,
    /// Total number of items
    pub total_items: u32,
}

/// Response from retrieving a single authentication configuration
#[derive(Debug, Clone, Deserialize)]
pub struct AuthConfigRetrieveResponse {
    /// Auth config ID (nano ID)
    pub id: String,
    /// Auth config UUID (deprecated, use id)
    pub uuid: String,
    /// Type of auth config
    #[serde(rename = "type")]
    pub config_type: String,
    /// Toolkit slug
    pub toolkit: String,
    /// Auth config name
    pub name: String,
    /// Authentication scheme
    pub auth_scheme: AuthScheme,
    /// Credentials (may be masked)
    pub credentials: serde_json::Value,
    /// Status (ENABLED, DISABLED)
    pub status: String,
    /// Creation timestamp
    pub created_at: String,
    /// Number of connected accounts using this auth config
    pub no_of_connections: u32,
    /// Tool access configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_access_config: Option<serde_json::Value>,
}

/// Detailed auth config information
#[derive(Debug, Clone, Deserialize)]
pub struct AuthConfigDetail {
    /// Auth config ID (nano ID)
    pub id: String,
    /// Auth config UUID (deprecated)
    pub uuid: String,
    /// Type of auth config
    #[serde(rename = "type")]
    pub config_type: String,
    /// Toolkit slug
    pub toolkit: String,
    /// Auth config name
    pub name: String,
    /// Authentication scheme
    pub auth_scheme: AuthScheme,
    /// Credentials (may be masked)
    pub credentials: serde_json::Value,
    /// Status (ENABLED, DISABLED)
    pub status: String,
    /// Creation timestamp
    pub created_at: String,
    /// Number of connected accounts
    pub no_of_connections: u32,
    /// Tool access configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_access_config: Option<serde_json::Value>,
}

/// Information about an authentication configuration
#[derive(Debug, Clone, Deserialize)]
pub struct AuthConfigInfo {
    /// Auth config ID
    pub id: String,
    /// Authentication scheme
    pub auth_scheme: AuthScheme,
    /// Whether this is managed by Composio
    pub is_composio_managed: bool,
    /// Optional list of tools this auth config is restricted to
    #[serde(skip_serializing_if = "Option::is_none")]
    pub restrict_to_following_tools: Option<Vec<String>>,
}

// ============================================================================
// Connected Account Response Types
// ============================================================================

/// Response from creating a connected account
#[derive(Debug, Clone, Deserialize)]
pub struct ConnectedAccountCreateResponse {
    /// Connected account ID
    pub id: String,
    /// Connection data (varies by auth scheme)
    pub connection_data: serde_json::Value,
    /// Connection status
    pub status: String,
    /// Redirect URL for OAuth flows
    #[serde(skip_serializing_if = "Option::is_none")]
    pub redirect_url: Option<String>,
}

/// Response from listing connected accounts
#[derive(Debug, Clone, Deserialize)]
pub struct ConnectedAccountListResponse {
    /// List of connected accounts
    pub items: Vec<ConnectedAccountDetail>,
    /// Pagination cursor for next page
    pub next_cursor: Option<String>,
    /// Total number of pages
    pub total_pages: u32,
    /// Current page number
    pub current_page: u32,
    /// Total number of items
    pub total_items: u32,
}

/// Detailed information about a connected account
#[derive(Debug, Clone, Deserialize)]
pub struct ConnectedAccountDetail {
    /// Toolkit slug
    pub toolkit: String,
    /// Auth config ID
    pub auth_config: String,
    /// Connected account ID
    pub id: String,
    /// User ID
    pub user_id: String,
    /// Connection status (ACTIVE, EXPIRED, FAILED, etc.)
    pub status: String,
    /// Creation timestamp
    pub created_at: String,
    /// Last update timestamp
    pub updated_at: String,
    /// Connection state
    pub state: serde_json::Value,
    /// Additional connection data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
    /// Status reason (if failed or expired)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_reason: Option<String>,
    /// Whether the account is disabled
    pub is_disabled: bool,
}

/// Response from retrieving a single connected account
pub type ConnectedAccountRetrieveResponse = ConnectedAccountDetail;

/// Response from updating connected account status
#[derive(Debug, Clone, Deserialize)]
pub struct ConnectedAccountUpdateStatusResponse {
    /// Whether the operation was successful
    pub success: bool,
}

// ============================================================================
// Tool Proxy Response Types
// ============================================================================

/// Response from a proxy request
#[derive(Debug, Clone, Deserialize)]
pub struct ToolProxyResponse {
    /// Response data from the external API
    pub data: serde_json::Value,
    /// HTTP status code
    pub status: u16,
    /// Response headers
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<serde_json::Value>,
    /// Error message if request failed
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

// ============================================================================
// Trigger Response Types
// ============================================================================

/// Response from creating or updating a trigger instance
#[derive(Debug, Clone, Deserialize)]
pub struct TriggerInstanceUpsertResponse {
    /// Trigger instance ID
    pub id: String,
    /// Trigger name/slug
    pub trigger_name: String,
    /// Connected account ID
    pub connected_account_id: String,
    /// User ID
    pub user_id: String,
    /// Trigger configuration
    pub trigger_config: serde_json::Value,
    /// Trigger state
    pub state: String,
    /// Creation timestamp
    pub created_at: String,
    /// Last update timestamp
    pub updated_at: String,
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json;

    #[test]
    fn test_session_response_deserialization() {
        let json = r#"{
            "session_id": "sess_abc123",
            "mcp": {
                "url": "https://mcp.composio.dev/sess_abc123"
            },
            "tool_router_tools": [
                "COMPOSIO_SEARCH_TOOLS",
                "COMPOSIO_MULTI_EXECUTE_TOOL"
            ],
            "config": {
                "user_id": "user_123"
            }
        }"#;

        let response: SessionResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.session_id, "sess_abc123");
        assert_eq!(response.mcp.url, "https://mcp.composio.dev/sess_abc123");
        assert_eq!(response.tool_router_tools.len(), 2);
        assert_eq!(response.config.user_id, "user_123");
        assert!(response.assistive_prompt.is_none());
    }

    #[test]
    fn test_session_response_with_assistive_prompt() {
        let json = r#"{
            "session_id": "sess_abc123",
            "mcp": {
                "url": "https://mcp.composio.dev/sess_abc123"
            },
            "tool_router_tools": [],
            "config": {
                "user_id": "user_123"
            },
            "assistive_prompt": "Use COMPOSIO_SEARCH_TOOLS to discover tools"
        }"#;

        let response: SessionResponse = serde_json::from_str(json).unwrap();
        assert_eq!(
            response.assistive_prompt,
            Some("Use COMPOSIO_SEARCH_TOOLS to discover tools".to_string())
        );
    }

    #[test]
    fn test_mcp_info_deserialization() {
        let json = r#"{
            "url": "https://mcp.composio.dev/session_123"
        }"#;

        let mcp: McpInfo = serde_json::from_str(json).unwrap();
        assert_eq!(mcp.url, "https://mcp.composio.dev/session_123");
    }

    #[test]
    fn test_tool_schema_deserialization() {
        let json = r#"{
            "slug": "GITHUB_CREATE_ISSUE",
            "name": "Create Issue",
            "description": "Create a new issue in a GitHub repository",
            "toolkit": "github",
            "input_parameters": {
                "type": "object",
                "properties": {
                    "owner": {"type": "string"},
                    "repo": {"type": "string"},
                    "title": {"type": "string"}
                }
            },
            "output_parameters": {
                "type": "object",
                "properties": {
                    "id": {"type": "number"}
                }
            },
            "scopes": ["repo"],
            "tags": ["write"],
            "version": "1.0.0",
            "available_versions": ["1.0.0", "0.9.0"],
            "is_deprecated": false,
            "no_auth": false
        }"#;

        let schema: ToolSchema = serde_json::from_str(json).unwrap();
        assert_eq!(schema.slug, "GITHUB_CREATE_ISSUE");
        assert_eq!(schema.name, "Create Issue");
        assert_eq!(schema.toolkit, "github");
        assert_eq!(schema.scopes.len(), 1);
        assert_eq!(schema.tags.len(), 1);
        assert_eq!(schema.version, "1.0.0");
        assert_eq!(schema.available_versions.len(), 2);
        assert!(!schema.is_deprecated);
        assert!(!schema.no_auth);
    }

    #[test]
    fn test_tool_schema_minimal_deserialization() {
        let json = r#"{
            "slug": "SIMPLE_TOOL",
            "name": "Simple Tool",
            "description": "A simple tool",
            "toolkit": "simple",
            "input_parameters": {},
            "output_parameters": {},
            "version": "1.0.0"
        }"#;

        let schema: ToolSchema = serde_json::from_str(json).unwrap();
        assert_eq!(schema.slug, "SIMPLE_TOOL");
        assert!(schema.scopes.is_empty());
        assert!(schema.tags.is_empty());
        assert!(schema.available_versions.is_empty());
        assert!(!schema.is_deprecated);
        assert!(!schema.no_auth);
    }

    #[test]
    fn test_tool_execution_response_deserialization() {
        let json = r#"{
            "data": {
                "issue_id": 123,
                "url": "https://github.com/owner/repo/issues/123"
            },
            "error": null,
            "log_id": "log_xyz789"
        }"#;

        let response: ToolExecutionResponse = serde_json::from_str(json).unwrap();
        assert!(response.data.is_object());
        assert_eq!(response.data["issue_id"], 123);
        assert!(response.error.is_none());
        assert_eq!(response.log_id, "log_xyz789");
    }

    #[test]
    fn test_tool_execution_response_with_error() {
        let json = r#"{
            "data": null,
            "error": "Failed to create issue: Invalid repository",
            "log_id": "log_error123"
        }"#;

        let response: ToolExecutionResponse = serde_json::from_str(json).unwrap();
        assert!(response.data.is_null());
        assert_eq!(
            response.error,
            Some("Failed to create issue: Invalid repository".to_string())
        );
        assert_eq!(response.log_id, "log_error123");
    }

    #[test]
    fn test_toolkit_list_response_deserialization() {
        let json = r#"{
            "items": [
                {
                    "name": "GitHub",
                    "slug": "github",
                    "enabled": true,
                    "is_no_auth": false,
                    "composio_managed_auth_schemes": ["OAUTH2"],
                    "meta": {
                        "logo": "https://logo.url",
                        "description": "GitHub integration",
                        "categories": ["development"],
                        "tools_count": 50,
                        "triggers_count": 10,
                        "version": "1.0.0"
                    },
                    "connected_account": {
                        "id": "ca_123",
                        "status": "ACTIVE",
                        "created_at": "2024-01-01T00:00:00Z"
                    }
                }
            ],
            "next_cursor": "cursor_abc",
            "total_pages": 5,
            "current_page": 1,
            "total_items": 100
        }"#;

        let response: ToolkitListResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.items.len(), 1);
        assert_eq!(response.next_cursor, Some("cursor_abc".to_string()));
        assert_eq!(response.total_pages, 5);
        assert_eq!(response.current_page, 1);
        assert_eq!(response.total_items, 100);
    }

    #[test]
    fn test_toolkit_info_deserialization() {
        let json = r#"{
            "name": "Gmail",
            "slug": "gmail",
            "enabled": true,
            "is_no_auth": false,
            "composio_managed_auth_schemes": ["OAUTH2"],
            "meta": {
                "logo": "https://gmail.logo",
                "description": "Gmail integration",
                "categories": ["communication"],
                "tools_count": 30,
                "triggers_count": 5,
                "version": "2.0.0"
            },
            "connected_account": null
        }"#;

        let info: ToolkitInfo = serde_json::from_str(json).unwrap();
        assert_eq!(info.name, "Gmail");
        assert_eq!(info.slug, "gmail");
        assert!(info.enabled);
        assert!(!info.is_no_auth);
        assert_eq!(info.composio_managed_auth_schemes.len(), 1);
        assert!(info.connected_account.is_none());
    }

    #[test]
    fn test_toolkit_meta_deserialization() {
        let json = r#"{
            "logo": "https://logo.url",
            "description": "Test toolkit",
            "categories": ["test", "development"],
            "tools_count": 25,
            "triggers_count": 3,
            "version": "1.5.0"
        }"#;

        let meta: ToolkitMeta = serde_json::from_str(json).unwrap();
        assert_eq!(meta.logo, "https://logo.url");
        assert_eq!(meta.description, "Test toolkit");
        assert_eq!(meta.categories.len(), 2);
        assert_eq!(meta.tools_count, 25);
        assert_eq!(meta.triggers_count, 3);
        assert_eq!(meta.version, "1.5.0");
    }

    #[test]
    fn test_toolkit_meta_minimal_deserialization() {
        let json = r#"{
            "logo": "https://logo.url",
            "description": "Minimal toolkit"
        }"#;

        let meta: ToolkitMeta = serde_json::from_str(json).unwrap();
        assert_eq!(meta.logo, "https://logo.url");
        assert_eq!(meta.description, "Minimal toolkit");
        assert!(meta.categories.is_empty());
        assert_eq!(meta.tools_count, 0);
        assert_eq!(meta.triggers_count, 0);
        assert_eq!(meta.version, "");
    }

    #[test]
    fn test_connected_account_info_deserialization() {
        let json = r#"{
            "id": "ca_abc123",
            "status": "ACTIVE",
            "created_at": "2024-01-15T10:30:00Z"
        }"#;

        let info: ConnectedAccountInfo = serde_json::from_str(json).unwrap();
        assert_eq!(info.id, "ca_abc123");
        assert_eq!(info.status, "ACTIVE");
        assert_eq!(info.created_at, "2024-01-15T10:30:00Z");
    }

    #[test]
    fn test_link_response_deserialization() {
        let json = r#"{
            "link_token": "lt_xyz789",
            "redirect_url": "https://auth.composio.dev/link?token=lt_xyz789",
            "connected_account_id": "ca_existing123"
        }"#;

        let response: LinkResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.link_token, "lt_xyz789");
        assert_eq!(response.redirect_url, "https://auth.composio.dev/link?token=lt_xyz789");
        assert_eq!(response.connected_account_id, Some("ca_existing123".to_string()));
    }

    #[test]
    fn test_link_response_without_connected_account() {
        let json = r#"{
            "link_token": "lt_new456",
            "redirect_url": "https://auth.composio.dev/link?token=lt_new456",
            "connected_account_id": null
        }"#;

        let response: LinkResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.link_token, "lt_new456");
        assert!(response.connected_account_id.is_none());
    }

    #[test]
    fn test_error_response_deserialization() {
        let json = r#"{
            "message": "Validation failed",
            "code": "VALIDATION_ERROR",
            "slug": "validation-failed",
            "status": 400,
            "request_id": "req_abc123",
            "suggested_fix": "Check your input parameters",
            "errors": [
                {
                    "field": "user_id",
                    "message": "User ID is required"
                }
            ]
        }"#;

        let response: ErrorResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.message, "Validation failed");
        assert_eq!(response.code, Some("VALIDATION_ERROR".to_string()));
        assert_eq!(response.slug, Some("validation-failed".to_string()));
        assert_eq!(response.status, 400);
        assert_eq!(response.request_id, Some("req_abc123".to_string()));
        assert_eq!(response.suggested_fix, Some("Check your input parameters".to_string()));
        assert!(response.errors.is_some());
        assert_eq!(response.errors.as_ref().unwrap().len(), 1);
    }

    #[test]
    fn test_error_response_minimal_deserialization() {
        let json = r#"{
            "message": "Internal server error",
            "status": 500
        }"#;

        let response: ErrorResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.message, "Internal server error");
        assert_eq!(response.status, 500);
        assert!(response.code.is_none());
        assert!(response.slug.is_none());
        assert!(response.request_id.is_none());
        assert!(response.suggested_fix.is_none());
        assert!(response.errors.is_none());
    }

    #[test]
    fn test_auth_scheme_deserialization() {
        let json = r#"["OAUTH2", "API_KEY", "BEARER_TOKEN"]"#;
        let schemes: Vec<AuthScheme> = serde_json::from_str(json).unwrap();
        
        assert_eq!(schemes.len(), 3);
        assert!(matches!(schemes[0], AuthScheme::Oauth2));
        assert!(matches!(schemes[1], AuthScheme::ApiKey));
        assert!(matches!(schemes[2], AuthScheme::BearerToken));
    }

    #[test]
    fn test_meta_tool_execution_response_alias() {
        let json = r#"{
            "data": {"result": "success"},
            "error": null,
            "log_id": "log_meta123"
        }"#;

        let response: MetaToolExecutionResponse = serde_json::from_str(json).unwrap();
        assert!(response.data.is_object());
        assert!(response.error.is_none());
        assert_eq!(response.log_id, "log_meta123");
    }

    #[test]
    fn test_toolkit_list_response_empty_items() {
        let json = r#"{
            "items": [],
            "next_cursor": null,
            "total_pages": 0,
            "current_page": 0,
            "total_items": 0
        }"#;

        let response: ToolkitListResponse = serde_json::from_str(json).unwrap();
        assert!(response.items.is_empty());
        assert!(response.next_cursor.is_none());
        assert_eq!(response.total_pages, 0);
        assert_eq!(response.current_page, 0);
        assert_eq!(response.total_items, 0);
    }

    #[test]
    fn test_session_response_clone() {
        let json = r#"{
            "session_id": "sess_123",
            "mcp": {"url": "https://mcp.url"},
            "tool_router_tools": [],
            "config": {"user_id": "user_123"}
        }"#;

        let response: SessionResponse = serde_json::from_str(json).unwrap();
        let cloned = response.clone();
        
        assert_eq!(response.session_id, cloned.session_id);
        assert_eq!(response.mcp.url, cloned.mcp.url);
    }

    #[test]
    fn test_tool_schema_debug() {
        let json = r#"{
            "slug": "TEST_TOOL",
            "name": "Test",
            "description": "Test tool",
            "toolkit": "test",
            "input_parameters": {},
            "output_parameters": {},
            "version": "1.0.0"
        }"#;

        let schema: ToolSchema = serde_json::from_str(json).unwrap();
        let debug_str = format!("{:?}", schema);
        
        assert!(debug_str.contains("TEST_TOOL"));
        assert!(debug_str.contains("Test"));
    }
}