composio-sdk 0.2.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
//! MCP (Model Context Protocol) module for Composio SDK.
//!
//! This module provides MCP server operations for creating, managing, and generating
//! MCP server instances for users.
//!
//! # Overview
//!
//! MCP servers provide connection points for AI assistants to access applications.
//! This module allows you to:
//! - Create MCP server configurations with specific toolkits
//! - List and filter existing MCP servers
//! - Update MCP server configurations
//! - Delete MCP servers
//! - Generate user-specific MCP server URLs
//!
//! # Example
//!
//! ```rust,no_run
//! use composio_sdk::{Composio, models::mcp::MCPToolkitConfig};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let composio = Composio::builder()
//!     .api_key("your-api-key")
//!     .build()?;
//!
//! // Create an MCP server
//! let server = composio.mcp().create(
//!     "my-mcp-server",
//!     vec!["github".to_string(), "slack".to_string()],
//!     None,
//!     None,
//! ).await?;
//!
//! // Generate a user-specific URL
//! let instance = composio.mcp().generate(
//!     "user_123",
//!     &server.id,
//!     None,
//! ).await?;
//!
//! println!("MCP URL: {}", instance.url);
//! # Ok(())
//! # }
//! ```

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

// ============================================================================
// Data Types (matching TypeScript/Python specification)
// ============================================================================

/// MCP toolkit configuration
///
/// Specifies a toolkit and optionally an auth config to use for the MCP server.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPToolkitConfig {
    /// Toolkit slug (e.g., "github", "slack")
    pub toolkit: String,
    
    /// Optional auth config ID to use for this toolkit
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auth_config_id: Option<String>,
}

impl MCPToolkitConfig {
    /// Create a new toolkit configuration
    pub fn new(toolkit: impl Into<String>) -> Self {
        Self {
            toolkit: toolkit.into(),
            auth_config_id: None,
        }
    }

    /// Set the auth config ID
    pub fn with_auth_config(mut self, auth_config_id: impl Into<String>) -> Self {
        self.auth_config_id = Some(auth_config_id.into());
        self
    }
}

impl From<String> for MCPToolkitConfig {
    fn from(toolkit: String) -> Self {
        Self::new(toolkit)
    }
}

impl From<&str> for MCPToolkitConfig {
    fn from(toolkit: &str) -> Self {
        Self::new(toolkit)
    }
}

/// MCP Server Instance data structure
///
/// Represents a user-specific MCP server instance with connection details.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPServerInstance {
    /// Server instance ID
    pub id: String,
    
    /// Human-readable server name
    pub name: String,
    
    /// Server type (typically "streamable_http")
    #[serde(rename = "type")]
    pub server_type: String,
    
    /// User-specific connection URL
    pub url: String,
    
    /// Associated user ID
    pub user_id: String,
    
    /// Available tools for the user
    pub allowed_tools: Vec<String>,
    
    /// Associated auth configurations
    pub auth_configs: Vec<String>,
}

/// Complete MCP server information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPItem {
    /// Unique server identifier
    pub id: String,
    
    /// Human-readable server name
    pub name: String,
    
    /// Array of enabled tool identifiers
    pub allowed_tools: Vec<String>,
    
    /// Array of auth configuration IDs
    pub auth_config_ids: Vec<String>,
    
    /// Array of toolkit names
    pub toolkits: Vec<String>,
    
    /// Setup commands for different clients
    pub commands: HashMap<String, String>,
    
    /// Server connection URL
    pub mcp_url: String,
    
    /// Map of toolkit icons
    pub toolkit_icons: HashMap<String, String>,
    
    /// Number of active instances
    pub server_instance_count: i32,
    
    /// Creation timestamp
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<String>,
    
    /// Last update timestamp
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<String>,
}

/// Paginated list response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPListResponse {
    /// Array of MCP server objects
    pub items: Vec<MCPItem>,
    
    /// Current page number
    pub current_page: i32,
    
    /// Total number of pages
    pub total_pages: i32,
}

/// Response from creating an MCP server
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPCreateResponse {
    /// Server ID
    pub id: String,
    
    /// Server name
    pub name: String,
    
    /// Allowed tools
    pub allowed_tools: Vec<String>,
    
    /// Auth config IDs
    pub auth_config_ids: Vec<String>,
    
    /// Toolkits
    pub toolkits: Vec<String>,
    
    /// MCP URL
    pub mcp_url: String,
    
    /// Creation timestamp
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<String>,
}

/// Response from updating an MCP server
pub type MCPUpdateResponse = MCPCreateResponse;

/// Response from deleting an MCP server
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPDeleteResponse {
    /// Server ID that was deleted
    pub id: String,
    
    /// Whether the deletion was successful
    pub deleted: bool,
}

/// Response from generating MCP URLs
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPGenerateUrlResponse {
    /// Array of user-specific URLs
    pub user_ids_url: Vec<String>,
}

// ============================================================================
// Request Types
// ============================================================================

/// Parameters for creating an MCP server
#[derive(Debug, Clone, Serialize)]
pub struct MCPCreateParams {
    /// Server name
    pub name: String,
    
    /// Toolkit slugs
    pub toolkits: Vec<String>,
    
    /// Auth config IDs
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auth_config_ids: Option<Vec<String>>,
    
    /// Custom tools (allowed tools)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub custom_tools: Option<Vec<String>>,
    
    /// Whether to use Composio managed auth
    #[serde(skip_serializing_if = "Option::is_none")]
    pub managed_auth_via_composio: Option<bool>,
}

/// Parameters for updating an MCP server
#[derive(Debug, Clone, Serialize)]
pub struct MCPUpdateParams {
    /// Optional new name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    
    /// Optional toolkit slugs
    #[serde(skip_serializing_if = "Option::is_none")]
    pub toolkits: Option<Vec<String>>,
    
    /// Optional auth config IDs
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auth_config_ids: Option<Vec<String>>,
    
    /// Optional custom tools
    #[serde(skip_serializing_if = "Option::is_none")]
    pub custom_tools: Option<Vec<String>>,
    
    /// Optional managed auth flag
    #[serde(skip_serializing_if = "Option::is_none")]
    pub managed_auth_via_composio: Option<bool>,
}

/// Parameters for listing MCP servers
#[derive(Debug, Clone, Default, Serialize)]
pub struct MCPListParams {
    /// Page number for pagination
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page_no: Option<i32>,
    
    /// Maximum items per page
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<i32>,
    
    /// Filter by toolkit name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub toolkits: Option<String>,
    
    /// Filter by auth configuration ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auth_config_ids: Option<String>,
    
    /// Filter by server name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    
    /// Order by field
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_by: Option<String>,
    
    /// Order direction
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_direction: Option<String>,
}

/// Parameters for generating MCP URLs
#[derive(Debug, Clone, Serialize)]
pub struct MCPGenerateUrlParams {
    /// MCP server ID
    pub mcp_server_id: String,
    
    /// User IDs to generate URLs for
    pub user_ids: Vec<String>,
    
    /// Whether to use Composio managed auth
    #[serde(skip_serializing_if = "Option::is_none")]
    pub managed_auth_by_composio: Option<bool>,
}

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

    #[test]
    fn test_mcp_toolkit_config_new() {
        let config = MCPToolkitConfig::new("github");
        assert_eq!(config.toolkit, "github");
        assert!(config.auth_config_id.is_none());
    }

    #[test]
    fn test_mcp_toolkit_config_with_auth() {
        let config = MCPToolkitConfig::new("github")
            .with_auth_config("ac_123");
        
        assert_eq!(config.toolkit, "github");
        assert_eq!(config.auth_config_id, Some("ac_123".to_string()));
    }

    #[test]
    fn test_mcp_toolkit_config_from_string() {
        let config: MCPToolkitConfig = "slack".into();
        assert_eq!(config.toolkit, "slack");
        assert!(config.auth_config_id.is_none());
    }

    #[test]
    fn test_mcp_server_instance_serialization() {
        let instance = MCPServerInstance {
            id: "mcp_123".to_string(),
            name: "Test Server".to_string(),
            server_type: "streamable_http".to_string(),
            url: "https://mcp.composio.dev/test".to_string(),
            user_id: "user_123".to_string(),
            allowed_tools: vec!["GITHUB_CREATE_ISSUE".to_string()],
            auth_configs: vec!["ac_123".to_string()],
        };

        let json = serde_json::to_string(&instance).unwrap();
        assert!(json.contains("mcp_123"));
        assert!(json.contains("Test Server"));
        assert!(json.contains("streamable_http"));
    }

    #[test]
    fn test_mcp_server_instance_deserialization() {
        let json = r#"{
            "id": "mcp_456",
            "name": "My Server",
            "type": "streamable_http",
            "url": "https://mcp.url",
            "user_id": "user_456",
            "allowed_tools": ["SLACK_SEND_MESSAGE"],
            "auth_configs": ["ac_456"]
        }"#;

        let instance: MCPServerInstance = serde_json::from_str(json).unwrap();
        assert_eq!(instance.id, "mcp_456");
        assert_eq!(instance.name, "My Server");
        assert_eq!(instance.server_type, "streamable_http");
        assert_eq!(instance.url, "https://mcp.url");
        assert_eq!(instance.user_id, "user_456");
        assert_eq!(instance.allowed_tools.len(), 1);
        assert_eq!(instance.auth_configs.len(), 1);
    }

    #[test]
    fn test_mcp_list_params_default() {
        let params = MCPListParams::default();
        assert!(params.page_no.is_none());
        assert!(params.limit.is_none());
        assert!(params.toolkits.is_none());
        assert!(params.auth_config_ids.is_none());
        assert!(params.name.is_none());
    }

    #[test]
    fn test_mcp_create_params_serialization() {
        let params = MCPCreateParams {
            name: "Test Server".to_string(),
            toolkits: vec!["github".to_string()],
            auth_config_ids: Some(vec!["ac_123".to_string()]),
            custom_tools: Some(vec!["GITHUB_CREATE_ISSUE".to_string()]),
            managed_auth_via_composio: Some(true),
        };

        let json = serde_json::to_string(&params).unwrap();
        assert!(json.contains("Test Server"));
        assert!(json.contains("github"));
        assert!(json.contains("ac_123"));
    }

    #[test]
    fn test_mcp_delete_response_deserialization() {
        let json = r#"{
            "id": "mcp_789",
            "deleted": true
        }"#;

        let response: MCPDeleteResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.id, "mcp_789");
        assert!(response.deleted);
    }
}