Skip to main content

Session

Struct Session 

Source
pub struct Session { /* private fields */ }
Expand description

Represents a Tool Router session

A session provides scoped access to tools and toolkits for a specific user. It maintains a reference to the client for making API calls and stores session metadata including available tools and toolkit version configuration.

§Example

use composio_sdk::ComposioClient;

let client = ComposioClient::builder()
    .api_key("your-api-key")
    .build()?;

let session = client
    .create_session("user_123")
    .toolkits(vec!["github", "gmail"])
    .send()
    .await?;

println!("Session ID: {}", session.session_id());
println!("MCP URL: {}", session.mcp_url());
println!("Available tools: {}", session.tools().len());

Implementations§

Source§

impl Session

Source

pub fn session_id(&self) -> &str

Get the session ID

Returns the unique identifier for this session. This ID is used for all session-scoped API operations.

§Example
let session = client.create_session("user_123").send().await?;
println!("Session ID: {}", session.session_id());
Source

pub fn mcp_url(&self) -> &str

Get the MCP URL

Returns the Model Context Protocol (MCP) server URL for this session. This URL can be used to connect MCP-compatible clients to access the session’s tools.

§Example
let session = client.create_session("user_123").send().await?;
println!("MCP URL: {}", session.mcp_url());
Source

pub fn tools(&self) -> &[String]

Get the available tool slugs

Returns a slice of tool slugs available in this session. These are the meta tools (COMPOSIO_SEARCH_TOOLS, COMPOSIO_MULTI_EXECUTE_TOOL, etc.) that can be used with this session.

§Example
let session = client.create_session("user_123").send().await?;
 
for tool_slug in session.tools() {
    println!("Tool: {}", tool_slug);
}
Source

pub async fn execute_tool( &self, tool_slug: impl Into<String>, arguments: Value, ) -> Result<ToolExecutionResponse, ComposioError>

Execute a tool within this session

Executes a specific tool with the provided arguments. The tool must be available in this session (either through enabled toolkits or via COMPOSIO_SEARCH_TOOLS).

§Arguments
  • tool_slug - The tool identifier (e.g., “GITHUB_CREATE_ISSUE”)
  • arguments - JSON value containing the tool’s input parameters
§Returns

Returns a ToolExecutionResponse containing:

  • data: The tool’s output data
  • error: Optional error message if execution failed
  • log_id: Unique identifier for this execution (for debugging)
§Errors

Returns an error if:

  • The tool is not found or not available in this session
  • The user doesn’t have a connected account for the toolkit
  • The arguments are invalid or missing required fields
  • Network error occurs
  • API returns an error response
§Example
use composio_sdk::ComposioClient;
use serde_json::json;

let client = ComposioClient::builder()
    .api_key("your-api-key")
    .build()?;

let session = client
    .create_session("user_123")
    .toolkits(vec!["github"])
    .send()
    .await?;

let result = session
    .execute_tool(
        "GITHUB_CREATE_ISSUE",
        json!({
            "owner": "composio",
            "repo": "composio",
            "title": "Test issue",
            "body": "Created via Rust SDK"
        })
    )
    .await?;

println!("Result: {:?}", result.data);
println!("Log ID: {}", result.log_id);

if let Some(error) = result.error {
    eprintln!("Tool execution error: {}", error);
}
Source

pub async fn execute_meta_tool( &self, slug: MetaToolSlug, arguments: Value, ) -> Result<MetaToolExecutionResponse, ComposioError>

Execute a meta tool within this session

Meta tools are special tools provided by Composio for runtime tool discovery, connection management, and advanced operations:

  • COMPOSIO_SEARCH_TOOLS: Discover relevant tools across 1000+ apps
  • COMPOSIO_MULTI_EXECUTE_TOOL: Execute up to 20 tools in parallel
  • COMPOSIO_MANAGE_CONNECTIONS: Handle OAuth and API key authentication
  • COMPOSIO_REMOTE_WORKBENCH: Run Python code in persistent sandbox
  • COMPOSIO_REMOTE_BASH_TOOL: Execute bash commands for file/data processing
§Arguments
  • slug - The meta tool identifier (MetaToolSlug enum)
  • arguments - JSON value containing the meta tool’s input parameters
§Returns

Returns a MetaToolExecutionResponse containing:

  • data: The meta tool’s output data
  • error: Optional error message if execution failed
  • log_id: Unique identifier for this execution (for debugging)
§Errors

Returns an error if:

  • The arguments are invalid or missing required fields
  • Network error occurs
  • API returns an error response
§Example
use composio_sdk::{ComposioClient, MetaToolSlug};
use serde_json::json;

let client = ComposioClient::builder()
    .api_key("your-api-key")
    .build()?;

let session = client
    .create_session("user_123")
    .toolkits(vec!["github"])
    .send()
    .await?;

// Search for tools
let search_result = session
    .execute_meta_tool(
        MetaToolSlug::ComposioSearchTools,
        json!({
            "query": "create a GitHub issue"
        })
    )
    .await?;

println!("Search result: {:?}", search_result.data);

// Multi-execute tools
let multi_result = session
    .execute_meta_tool(
        MetaToolSlug::ComposioMultiExecuteTool,
        json!({
            "tools": [
                {
                    "tool_slug": "GITHUB_GET_REPOS",
                    "arguments": {"owner": "composio"}
                },
                {
                    "tool_slug": "GITHUB_GET_ISSUES",
                    "arguments": {"owner": "composio", "repo": "composio"}
                }
            ]
        })
    )
    .await?;

println!("Multi-execute result: {:?}", multi_result.data);
Source

pub fn list_toolkits(&self) -> ToolkitListBuilder<'_>

List available toolkits in this session

Returns a builder for listing toolkits with optional filtering. The builder allows you to configure pagination, search, and filtering options before executing the request.

§Example
let session = client.create_session("user_123").send().await?;

// List all toolkits
let toolkits = session.list_toolkits().send().await?;

// List only connected toolkits
let connected = session.list_toolkits()
    .is_connected(true)
    .send()
    .await?;

// Search for specific toolkits
let github_toolkits = session.list_toolkits()
    .search("github")
    .send()
    .await?;
Source

pub async fn get_meta_tools(&self) -> Result<Vec<ToolSchema>, ComposioError>

Get meta tools schemas for this session

Retrieves the complete schemas for all meta tools available in this session. Meta tools include:

  • COMPOSIO_SEARCH_TOOLS: Discover relevant tools across 1000+ apps
  • COMPOSIO_MULTI_EXECUTE_TOOL: Execute up to 20 tools in parallel
  • COMPOSIO_MANAGE_CONNECTIONS: Handle OAuth and API key authentication
  • COMPOSIO_REMOTE_WORKBENCH: Run Python code in persistent sandbox
  • COMPOSIO_REMOTE_BASH_TOOL: Execute bash commands for file/data processing

The returned schemas include detailed information about input parameters, output parameters, descriptions, and other metadata needed to use the tools.

§Returns

Returns a vector of ToolSchema objects, each containing:

  • slug: Tool identifier (e.g., “COMPOSIO_SEARCH_TOOLS”)
  • name: Human-readable name
  • description: Detailed functionality explanation
  • input_parameters: JSON schema of required inputs
  • output_parameters: JSON schema of return values
  • version: Current version
  • Other metadata fields
§Errors

Returns an error if:

  • Network error occurs
  • API returns an error response
  • Response cannot be parsed
§Example
use composio_sdk::ComposioClient;

let client = ComposioClient::builder()
    .api_key("your-api-key")
    .build()?;

let session = client
    .create_session("user_123")
    .send()
    .await?;

// Get all meta tool schemas
let meta_tools = session.get_meta_tools().await?;

for tool in meta_tools {
    println!("Tool: {}", tool.slug);
    println!("  Name: {}", tool.name);
    println!("  Description: {}", tool.description);
    println!("  Version: {}", tool.version);
    println!("  Input schema: {}", tool.input_parameters);
    println!("  Output schema: {}", tool.output_parameters);
    println!();
}
Source

pub async fn get_provider_tools<P>( &self, provider: &P, ) -> Result<P::ToolCollection, ComposioError>
where P: Provider,

Get meta tools formatted for a specific provider

This method retrieves meta tools and converts them to the format expected by a specific AI framework (OpenAI, Anthropic, etc.) using the provider system.

§Type Parameters
  • P - The provider type that implements the Provider trait
§Arguments
  • provider - The provider instance to use for conversion
§Returns

Returns the provider’s tool collection type (e.g., Vec<ChatCompletionToolParam> for OpenAI)

§Errors

Returns an error if:

  • Network error occurs
  • API returns an error response
  • Response cannot be parsed
§Example
use composio_sdk::{ComposioClient, providers::OpenAIProvider};

let client = ComposioClient::builder()
    .api_key("your-api-key")
    .build()?;

let session = client
    .create_session("user_123")
    .toolkits(vec!["github"])
    .send()
    .await?;

// Get tools in OpenAI format
let provider = OpenAIProvider::new();
let openai_tools = session.get_provider_tools(&provider).await?;

// Use with OpenAI API
// let response = openai_client.chat().completions().create(
//     ChatCompletionRequest {
//         model: "gpt-4",
//         messages: vec![...],
//         tools: Some(openai_tools),
//         ...
//     }
// ).await?;
§Example with Anthropic
use composio_sdk::{ComposioClient, providers::AnthropicProvider};

let client = ComposioClient::builder()
    .api_key("your-api-key")
    .build()?;

let session = client
    .create_session("user_123")
    .send()
    .await?;

// Get tools in Anthropic format
let provider = AnthropicProvider::new();
let anthropic_tools = session.get_provider_tools(&provider).await?;

// Use with Anthropic API
// let response = anthropic_client.messages().create(
//     MessageRequest {
//         model: "claude-3-5-sonnet-20241022",
//         messages: vec![...],
//         tools: Some(anthropic_tools),
//         ...
//     }
// ).await?;

Create an authentication link for a toolkit

Generates a Connect Link URL that users can visit to authenticate with a specific toolkit (e.g., GitHub, Gmail, Slack). This is used for both in-chat authentication and manual authentication flows.

§Arguments
  • toolkit - The toolkit slug to create an auth link for (e.g., “github”, “gmail”)
  • callback_url - Optional URL to redirect to after authentication completes. Query parameters status and connected_account_id will be appended.
§Returns

Returns a LinkResponse containing:

  • link_token: Token identifying this auth link session
  • redirect_url: URL for the user to visit to complete authentication
  • connected_account_id: Optional ID if account already exists
§Errors

Returns an error if:

  • Toolkit slug is invalid or not found (400 Bad Request)
  • Connected account already exists for this toolkit (400 Bad Request)
  • Network error occurs
  • API returns an error response
  • Response cannot be parsed
§Example
use composio_sdk::ComposioClient;

let client = ComposioClient::builder()
    .api_key("your-api-key")
    .build()?;

let session = client
    .create_session("user_123")
    .send()
    .await?;

// Create auth link without callback
let link = session.create_auth_link("github", None).await?;
println!("Visit: {}", link.redirect_url);

// Create auth link with callback
let link = session.create_auth_link(
    "gmail",
    Some("https://example.com/callback".to_string())
).await?;
println!("Link token: {}", link.link_token);
println!("Redirect URL: {}", link.redirect_url);
§See Also

Trait Implementations§

Source§

impl Clone for Session

Source§

fn clone(&self) -> Session

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Session

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more