composio_sdk/lib.rs
1//! # Composio Rust SDK
2//!
3//! A minimal, type-safe Rust SDK for the Composio Tool Router REST API.
4//!
5//! This SDK enables ZeroClaw and other Rust applications to interact with external services
6//! through Composio's Tool Router API, providing session management, tool execution,
7//! and authentication handling with a minimal memory footprint (~2 MB).
8//!
9//! ## Features
10//!
11//! - **Session Management**: Create and manage Tool Router sessions for users
12//! - **Tool Execution**: Execute tools and meta tools with automatic retry logic
13//! - **Type Safety**: Comprehensive type definitions for all API requests and responses
14//! - **Error Handling**: Detailed error types with actionable error messages
15//! - **Async/Await**: Built on tokio for efficient async operations
16//! - **Memory Efficient**: Minimal memory footprint suitable for resource-constrained environments
17//!
18//! ## Quick Start
19//!
20//! ```no_run
21//! use composio_sdk::{ComposioClient, MetaToolSlug};
22//! use serde_json::json;
23//!
24//! #[tokio::main]
25//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
26//! // Initialize client with API key
27//! let client = ComposioClient::builder()
28//! .api_key(std::env::var("COMPOSIO_API_KEY")?)
29//! .build()?;
30//!
31//! // Create a session for a user
32//! let session = client
33//! .create_session("user_123")
34//! .toolkits(vec!["github", "gmail"])
35//! .manage_connections(true)
36//! .send()
37//! .await?;
38//!
39//! println!("Session ID: {}", session.session_id());
40//! println!("MCP URL: {}", session.mcp_url());
41//!
42//! // Execute a tool
43//! let result = session
44//! .execute_tool(
45//! "GITHUB_CREATE_ISSUE",
46//! json!({
47//! "owner": "composio",
48//! "repo": "composio",
49//! "title": "Test issue",
50//! "body": "Created via Rust SDK"
51//! })
52//! )
53//! .await?;
54//!
55//! println!("Result: {:?}", result.data);
56//!
57//! // Execute a meta tool
58//! let search_result = session
59//! .execute_meta_tool(
60//! MetaToolSlug::ComposioSearchTools,
61//! json!({
62//! "query": "create a GitHub issue"
63//! })
64//! )
65//! .await?;
66//!
67//! println!("Search result: {:?}", search_result.data);
68//!
69//! Ok(())
70//! }
71//! ```
72//!
73//! ## Session Configuration
74//!
75//! Sessions can be configured with various options:
76//!
77//! ```no_run
78//! # use composio_sdk::ComposioClient;
79//! # async fn example(client: ComposioClient) -> Result<(), Box<dyn std::error::Error>> {
80//! let session = client
81//! .create_session("user_123")
82//! .toolkits(vec!["github", "gmail"]) // Enable specific toolkits
83//! .disable_toolkits(vec!["exa", "firecrawl"]) // Or disable specific toolkits
84//! .auth_config("github", "ac_custom_config") // Use custom auth config
85//! .connected_account("gmail", "ca_work_email") // Select specific account
86//! .manage_connections(true) // Enable in-chat auth
87//! .send()
88//! .await?;
89//! # Ok(())
90//! # }
91//! ```
92//!
93//! ## Error Handling
94//!
95//! The SDK provides comprehensive error handling:
96//!
97//! ```no_run
98//! # use composio_sdk::{ComposioClient, ComposioError};
99//! # use serde_json::json;
100//! # async fn example(client: ComposioClient) -> Result<(), Box<dyn std::error::Error>> {
101//! # let session = client.create_session("user_123").send().await?;
102//! match session.execute_tool("INVALID_TOOL", json!({})).await {
103//! Ok(result) => println!("Success: {:?}", result),
104//! Err(ComposioError::ApiError { status, message, suggested_fix, .. }) => {
105//! eprintln!("API error ({}): {}", status, message);
106//! if let Some(fix) = suggested_fix {
107//! eprintln!("Suggested fix: {}", fix);
108//! }
109//! }
110//! Err(ComposioError::NetworkError(e)) => {
111//! eprintln!("Network error: {}", e);
112//! }
113//! Err(e) => {
114//! eprintln!("Other error: {}", e);
115//! }
116//! }
117//! # Ok(())
118//! # }
119//! ```
120//!
121//! ## Configuration
122//!
123//! Customize SDK behavior with [`ComposioConfig`]:
124//!
125//! ```no_run
126//! use composio_sdk::ComposioClient;
127//! use std::time::Duration;
128//!
129//! let client = ComposioClient::builder()
130//! .api_key("your-api-key")
131//! .base_url("https://backend.composio.dev/api/v3")
132//! .timeout(Duration::from_secs(60))
133//! .max_retries(5)
134//! .build()?;
135//! # Ok::<(), composio_sdk::ComposioError>(())
136//! ```
137
138// ============================================================================
139// Module Declarations
140// ============================================================================
141
142/// Client implementation for the Composio API
143pub mod client;
144
145/// Configuration types for the SDK
146pub mod config;
147
148/// Error types and error handling utilities
149pub mod error;
150
151/// Data models for API requests and responses
152pub mod models;
153
154/// Retry logic and exponential backoff utilities
155pub mod retry;
156
157/// Session management and tool execution
158pub mod session;
159
160/// Wizard instruction generation from Composio Skills
161pub mod wizard;
162
163/// Skills integration for copying and managing Composio Skills
164pub mod skills_integration;
165
166/// Meta tools - Native Rust implementations
167pub mod meta_tools;
168
169/// Utility functions for the SDK
170pub mod utils;
171
172/// Provider system for framework-specific tool formatting
173pub mod providers;
174
175// ============================================================================
176// SDK Metadata
177// ============================================================================
178
179/// SDK version from Cargo.toml
180pub const VERSION: &str = env!("CARGO_PKG_VERSION");
181
182/// SDK name
183pub const NAME: &str = env!("CARGO_PKG_NAME");
184
185/// Get SDK version information
186///
187/// # Examples
188///
189/// ```rust
190/// use composio_sdk;
191///
192/// println!("Using Composio SDK v{}", composio_sdk::VERSION);
193/// ```
194pub fn version() -> &'static str {
195 VERSION
196}
197
198// ============================================================================
199// Core Client and Configuration
200// ============================================================================
201
202/// Main client for interacting with the Composio API
203pub use client::ComposioClient;
204
205/// Builder for constructing a [`ComposioClient`] with custom configuration
206pub use client::ComposioClientBuilder;
207
208/// Configuration for the Composio SDK
209pub use config::ComposioConfig;
210
211// ============================================================================
212// Provider System
213// ============================================================================
214
215/// Provider trait for framework-specific tool formatting
216///
217/// See the [`providers`] module documentation for detailed usage examples.
218pub use providers::Provider;
219
220/// OpenAI provider for Chat Completions API
221pub use providers::OpenAIProvider;
222
223/// Anthropic provider for Claude API
224pub use providers::AnthropicProvider;
225
226// ============================================================================
227// Logging Utilities
228// ============================================================================
229
230/// Logging utilities for the SDK
231///
232/// This module provides logging configuration with verbosity control,
233/// message truncation, and environment-based setup.
234///
235/// See the [`utils::logging`] module documentation for detailed usage examples.
236pub use utils::logging::{
237 setup as setup_logging, setup_from_env as setup_logging_from_env,
238 get_verbosity, set_verbosity, truncate_message, LogLevel, Verbosity, WithLogger,
239 ENV_COMPOSIO_LOGGING_LEVEL, ENV_COMPOSIO_LOG_VERBOSITY,
240};
241
242// ============================================================================
243// Session Management
244// ============================================================================
245
246/// A Tool Router session for a specific user
247pub use session::Session;
248
249/// Builder for constructing a session with custom configuration
250pub use session::SessionBuilder;
251
252// ============================================================================
253// Error Types
254// ============================================================================
255
256/// Main error type for the SDK
257pub use error::ComposioError;
258
259/// Detailed error information from API error responses
260pub use error::ErrorDetail;
261
262// ============================================================================
263// Request Models
264// ============================================================================
265
266/// Configuration for creating a Tool Router session
267pub use models::SessionConfig;
268
269/// Toolkit filter for enabling or disabling specific toolkits
270pub use models::ToolkitFilter;
271
272/// Configuration for per-toolkit tool filtering
273pub use models::ToolsConfig;
274
275/// Tool filter for a specific toolkit
276pub use models::ToolFilter;
277
278/// Configuration for tag-based tool filtering
279pub use models::TagsConfig;
280
281/// Configuration for workbench execution
282pub use models::WorkbenchConfig;
283
284/// Request to execute a tool
285pub use models::ToolExecutionRequest;
286
287/// Request to execute a meta tool
288pub use models::MetaToolExecutionRequest;
289
290/// Request to create an authentication link
291pub use models::LinkRequest;
292
293/// Parameters for creating an authentication configuration
294pub use models::AuthConfigCreateParams;
295
296/// Authentication configuration data
297pub use models::AuthConfigData;
298
299/// Parameters for listing authentication configurations
300pub use models::AuthConfigListParams;
301
302/// Parameters for updating an authentication configuration
303pub use models::AuthConfigUpdateParams;
304
305/// Parameters for creating a connected account
306pub use models::ConnectedAccountCreateParams;
307
308/// Reference to an authentication configuration
309pub use models::AuthConfigReference;
310
311/// Connection data for creating a connected account
312pub use models::ConnectionData;
313
314/// Parameters for listing connected accounts
315pub use models::ConnectedAccountListParams;
316
317/// Parameters for executing a proxy request
318pub use models::ToolProxyParams;
319
320// ============================================================================
321// Response Models
322// ============================================================================
323
324/// Response from session creation
325pub use models::SessionResponse;
326
327/// MCP server information
328pub use models::McpInfo;
329
330/// Tool schema information
331pub use models::ToolSchema;
332
333/// Response from tool execution
334pub use models::ToolExecutionResponse;
335
336/// Response from meta tool execution
337pub use models::MetaToolExecutionResponse;
338
339/// Response from listing toolkits
340pub use models::ToolkitListResponse;
341
342/// Information about a toolkit
343pub use models::ToolkitInfo;
344
345/// Metadata about a toolkit
346pub use models::ToolkitMeta;
347
348/// Information about a connected account
349pub use models::ConnectedAccountInfo;
350
351/// Response from creating an auth link
352pub use models::LinkResponse;
353
354/// Error response from API
355pub use models::ErrorResponse;
356
357/// Response from creating an authentication configuration
358pub use models::AuthConfigCreateResponse;
359
360/// Response from listing authentication configurations
361pub use models::AuthConfigListResponse;
362
363/// Response from retrieving a single authentication configuration
364pub use models::AuthConfigRetrieveResponse;
365
366/// Information about an authentication configuration
367pub use models::AuthConfigInfo;
368
369/// Response from creating a connected account
370pub use models::ConnectedAccountCreateResponse;
371
372/// Response from listing connected accounts
373pub use models::ConnectedAccountListResponse;
374
375/// Detailed information about a connected account
376pub use models::ConnectedAccountDetail;
377
378/// Response from retrieving a single connected account
379pub use models::ConnectedAccountRetrieveResponse;
380
381/// Response from updating connected account status
382pub use models::ConnectedAccountUpdateStatusResponse;
383
384/// Response from a proxy request
385pub use models::ToolProxyResponse;
386
387/// Response from creating or updating a trigger instance
388pub use models::TriggerInstanceUpsertResponse;
389
390// ============================================================================
391// Enums
392// ============================================================================
393
394/// Meta tool slugs for the 5 core Composio meta tools
395pub use models::MetaToolSlug;
396
397/// Tag types for filtering tools by behavior hints
398pub use models::TagType;
399
400/// Authentication schemes supported by toolkits
401pub use models::AuthScheme;
402
403// ============================================================================
404// Versioning Types
405// ============================================================================
406
407/// Toolkit version type
408pub use models::ToolkitVersion;
409
410/// Map of toolkit versions
411pub use models::ToolkitVersions;
412
413/// Toolkit version parameter for configuration
414pub use models::ToolkitVersionParam;
415
416/// Constant for "latest" version
417pub use models::TOOLKIT_LATEST_VERSION;
418
419// ============================================================================
420// Webhook Events
421// ============================================================================
422
423/// Webhook event types and utilities
424///
425/// This module provides strongly-typed definitions for webhook events,
426/// enabling type-safe handling of events like connection expiration.
427///
428/// See the [`models::webhook_events`] module documentation for detailed usage examples.
429pub use models::webhook_events::{
430 ConnectionExpiredEvent, ConnectionState, ConnectionStatus,
431 SingleConnectedAccountDetailedResponse, WebhookConnectionMetadata, WebhookEvent,
432 WebhookEventType, is_connection_expired_event,
433};
434
435// ============================================================================
436// Tool Modifiers
437// ============================================================================
438
439/// Tool modifier traits and utilities
440///
441/// This module provides functionality to modify tool schemas, execution parameters,
442/// and execution responses. Modifiers allow you to customize tool behavior without
443/// changing the underlying tool definitions.
444///
445/// See the [`models::modifiers`] module documentation for detailed usage examples.
446pub use models::modifiers::{
447 AfterExecute, BeforeExecute, SchemaModifier, BeforeExecuteMeta, AfterExecuteMeta,
448 Modifier, Modifiers, ToolExecuteParams, CustomAuthParams, CustomConnectionData,
449};
450
451// ============================================================================
452// Custom Tools
453// ============================================================================
454
455/// Custom tools functionality
456///
457/// This module provides functionality for creating and managing custom tools.
458/// Custom tools can be simple tools without authentication or toolkit-based
459/// tools with authentication and proxy execution.
460///
461/// See the [`models::custom_tools`] module documentation for detailed usage examples.
462pub use models::custom_tools::{
463 CustomTool, CustomToolsRegistry, ExecuteRequestFn,
464};
465
466// ============================================================================
467// Triggers
468// ============================================================================
469
470/// Trigger event types and utilities
471///
472/// This module provides functionality to manage triggers in Composio.
473/// Triggers are event listeners that notify your application when specific
474/// events occur in connected services.
475///
476/// See the [`models::triggers`] module documentation for detailed usage examples.
477pub use models::triggers::{
478 TriggerEvent, TriggerMetadata, TriggerConnectedAccount,
479 TriggerType, TriggerInstance, WebhookVersion,
480};
481
482// ============================================================================
483// Connected Accounts
484// ============================================================================
485
486/// Connected accounts management
487///
488/// This module provides functionality to manage connected accounts,
489/// which represent user connections to external services through Composio.
490///
491/// See the [`models::connected_accounts`] module documentation for detailed usage examples.
492pub use models::connected_accounts::{
493 ConnectionRequest, ConnectionStatus as ConnectedAccountStatus,
494 AuthScheme as ConnectedAccountAuthScheme, AUTH_SCHEME as auth_scheme,
495};
496
497// ============================================================================
498// Wizard Module (Skills Integration)
499// ============================================================================
500
501/// Wizard instruction generation utilities
502///
503/// This module provides tools for extracting Composio Skills content and
504/// generating wizard instructions for AI agents based on official best practices.
505///
506/// See the [`wizard`] module documentation for detailed usage examples.
507pub use wizard::{
508 Impact, InstructionValidator, Rule, SkillsExtractor, ValidationResult,
509 WizardInstructionGenerator,
510};
511
512// ============================================================================
513// Skills Integration Module
514// ============================================================================
515
516/// Skills integration error types and utilities
517///
518/// This module provides error handling for Skills integration operations,
519/// including file I/O errors, YAML parsing errors, validation failures,
520/// and security violations.
521///
522/// See the [`skills_integration`] module documentation for detailed usage examples.
523pub use skills_integration::{SkillsCopyResult, SkillsError, SkillsValidation};