The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(composio): add direct tool integration module
Steven Enamakelc990bf0739c9
diff --git a/crates/openhuman-core/src/integrations/composio/tools/direct.rs b/crates/openhuman-core/src/integrations/composio/tools/direct.rsindex 2d6d8939a4..a61acc72fb 100644--- a/crates/openhuman-core/src/integrations/composio/tools/direct.rs+++ b/crates/openhuman-core/src/integrations/composio/tools/direct.rs@@ -1,22 +1,22 @@-// Slim host-side HTTP reader for Composio's own v3 API with the user's key.+// Host-side HTTP transport for Composio's own v3 API with the user's key.//-// Composio execution, the OAuth handoff and connection management all run in-// the `tinyconnectors` module (see `module_client`). What remains here are the-// two direct-mode reads whose request parameters the pinned module route does-// not carry: `/connected_accounts?limit=200` and `/tools` with-// `toolkit_versions=latest` (#3932).+// What Composio's direct route sends and how it reshapes the answer is+// `tinyconnectors::client::DirectRoute` (paths, `limit=200`,+// `toolkit_versions=latest` (#3932), repeated `tags=`, blank-id filtering,+// v3-to-envelope translation). This module is only the seam the route needs+// from the host: a `Transport` that carries the key, refuses non-HTTPS bases,+// never follows redirects, and goes out through the host's proxy and TLS+// settings, plus the pre-store API-key probe's client.#[cfg(test)]#[path = "direct_tests.rs"]mod tests;-mod connections;mod construction;-mod discovery;mod http_errors;+mod transport;mod types;-pub use connections::ComposioConnectedAccount;pub use types::DirectComposioClient;// Test-only bridges: the flat `direct_tests.rs` module still expects thesediff --git a/crates/openhuman-core/src/integrations/composio/tools/direct/connections.rs b/crates/openhuman-core/src/integrations/composio/tools/direct/connections.rsdeleted file mode 100644index 119fce5d79..0000000000--- a/crates/openhuman-core/src/integrations/composio/tools/direct/connections.rs+++ /dev/null@@ -1,127 +0,0 @@-//! Connected-account listing for the direct route.--use super::http_errors::response_error;-use super::types::DirectComposioClient;-use anyhow::Context;-use serde::Deserialize;--impl DirectComposioClient {- /// List the user's connected accounts on Composio v3.- ///- /// GET `https://backend.composio.dev/api/v3/connected_accounts` with- /// `x-api-key: <user_key>`. Returns the raw item list; reshaping- /// into [`super::super::super::composio::types::ComposioConnection`]- /// happens at the call site in `composio/client.rs::direct_list_connections`.- ///- /// The v3 envelope is `{ items: [{ id, status, toolkit, created_at, ... }] }`.- /// Toolkit may arrive as either a plain string slug or as a nested- /// object — we tolerate both via [`ComposioConnectedAccount::toolkit_slug`].- /// This matches the same upstream shape drift handled by- /// `de_string_or_object` in `composio/types.rs`.- pub async fn list_connected_accounts(&self) -> anyhow::Result<Vec<ComposioConnectedAccount>> {- let url = format!("{}/connected_accounts", self.base_v3);- self.ensure_request_url(&url)?;-- let resp = self- .client()- .get(&url)- .header("x-api-key", &self.api_key)- // Composio paginates; pull a generous page size so most- // users see their full list in one round trip. If a user has- // > 200 connected accounts (extremely rare for an individual- // tenant) the rest will be missing until we add explicit- // pagination — note for the follow-up.- .query(&[("limit", "200")])- .send()- .await?;-- if !resp.status().is_success() {- let err = response_error(resp).await;- anyhow::bail!("Composio v3 connected_accounts failed: {err}");- }-- let mut body: ComposioConnectedAccountsResponse = resp- .json()- .await- .context("Failed to decode Composio v3 connected_accounts response")?;- // Drop rows with a blank id — serde_default means id can be ""- // if the upstream response is malformed. An empty connectionId- // propagated downstream causes invalid v3 API calls.- body.items.retain(|item| !item.id.trim().is_empty());- tracing::debug!(- count = body.items.len(),- "[composio-direct] list_connected_accounts: fetched connected accounts"- );- Ok(body.items)- }-}--#[derive(Debug, Deserialize)]-struct ComposioConnectedAccountsResponse {- #[serde(default)]- items: Vec<ComposioConnectedAccount>,-}--/// One v3 connected-account row.-///-/// Field shapes follow Composio's v3 docs as of May 2026. `toolkit` may-/// be either a string slug (older payloads) or a nested object with a-/// `slug` field (newer payloads); [`Self::toolkit_slug`] extracts the-/// canonical slug from either shape.-#[derive(Debug, Clone, Deserialize)]-pub struct ComposioConnectedAccount {- #[serde(default)]- pub id: String,- /// `"ACTIVE"`, `"INITIATED"`, `"FAILED"`, … — passed through as-is- /// so the caller's status filter (`ComposioConnection::is_active`)- /// applies uniformly across both backend-proxied and direct paths.- #[serde(default)]- pub status: Option<String>,- /// Composio uses `created_at` (snake_case) at v3. We keep both- /// spellings to tolerate any upstream drift back to `createdAt`.- #[serde(default, alias = "createdAt")]- pub created_at: Option<String>,- /// Toolkit may be a plain string slug or a nested- /// `ComposioToolkitRef`. Extracted via [`Self::toolkit_slug`].- #[serde(default)]- pub(super) toolkit: Option<serde_json::Value>,- /// Older payload shape — a top-level `app_name` string. Used as- /// a fallback when `toolkit` is absent or unparseable.- #[serde(default, rename = "appName", alias = "app_name")]- pub(super) app_name: Option<String>,-}--impl ComposioConnectedAccount {- /// Best-effort extract of the toolkit slug from the- /// possibly-polymorphic `toolkit` field, falling back to- /// `app_name`. Returns `None` only when no recognizable slug- /// representation is present.- pub fn toolkit_slug(&self) -> Option<String> {- if let Some(value) = &self.toolkit {- match value {- serde_json::Value::String(s) => {- let t = s.trim();- if !t.is_empty() {- return Some(t.to_string());- }- }- serde_json::Value::Object(map) => {- for key in ["slug", "id", "name", "key"] {- if let Some(serde_json::Value::String(s)) = map.get(key) {- let t = s.trim();- if !t.is_empty() {- return Some(t.to_string());- }- }- }- }- _ => {}- }- }- self.app_name- .as_deref()- .map(str::trim)- .filter(|s| !s.is_empty())- .map(str::to_string)- }-}diff --git a/crates/openhuman-core/src/integrations/composio/tools/direct/construction.rs b/crates/openhuman-core/src/integrations/composio/tools/direct/construction.rsindex 35ee21b522..d310c8c585 100644--- a/crates/openhuman-core/src/integrations/composio/tools/direct/construction.rs+++ b/crates/openhuman-core/src/integrations/composio/tools/direct/construction.rs@@ -60,7 +60,7 @@ impl DirectComposioClient {/// unit tests can point the direct `/tools` request — including the/// `tags` filter — at a local mock instead of `backend.composio.dev`.///- /// `#[cfg(test)]`-gated on purpose: `list_tool_schemas_v3` attaches the+ /// `#[cfg(test)]`-gated on purpose: the transport attaches the/// `x-api-key` header to whatever `base_v3` holds, so the only way to/// reach the v3 endpoint in production is [`Self::new`], which always/// uses the HTTPS [`COMPOSIO_API_BASE_V3`] const. An injectable base mustdiff --git a/crates/openhuman-core/src/integrations/composio/tools/direct/discovery.rs b/crates/openhuman-core/src/integrations/composio/tools/direct/discovery.rsdeleted file mode 100644index f15a7161e5..0000000000--- a/crates/openhuman-core/src/integrations/composio/tools/direct/discovery.rs+++ /dev/null@@ -1,192 +0,0 @@-//! Tool-schema listing for the direct route: `list_tool_schemas_v3` (the full-//! v3 schema, used by the direct-mode tool catalog) plus the wire types it-//! decodes into.--use super::http_errors::response_error;-use super::types::DirectComposioClient;-use anyhow::Context;-use serde::Deserialize;--impl DirectComposioClient {- /// Build the query-parameter pairs for the Composio v3 `GET /tools`- /// listing used by [`Self::list_tool_schemas_v3`].- ///- /// `toolkits` is sent as a single comma-joined `toolkits=` param (the- /// legacy plural the v3 backend tolerates). `tags` is- /// encoded as **repeated** `tags=` params (`tags=a&tags=b`) — the shape- /// Composio v3 `/tools` documents for tag filtering ("can be specified- /// multiple times"), NOT the comma-joined form the backend proxy uses.- /// Blank entries are trimmed and dropped; an empty `tags` slice yields- /// no `tags` params (treated as no filter).- ///- /// Pure (no I/O) so the param shape is unit-testable without a live- /// HTTP round trip.- pub(super) fn build_list_tool_schemas_v3_query(- toolkits: &[&str],- tags: Option<&[&str]>,- ) -> Vec<(&'static str, String)> {- // #3932: pin toolkit_versions=latest. Without it Composio v3 defaults to- // the 00000000_00 snapshot, which lists zero tools for any toolkit- // published after it (Outlook and every other post-launch toolkit).- let mut params: Vec<(&'static str, String)> = vec![- ("limit", "200".to_string()),- ("toolkit_versions", "latest".to_string()),- ];-- let trimmed: Vec<&str> = toolkits- .iter()- .map(|t| t.trim())- .filter(|t| !t.is_empty())- .collect();- if !trimmed.is_empty() {- params.push(("toolkits", trimmed.join(",")));- }-- if let Some(tags) = tags {- for tag in tags.iter().map(|t| t.trim()).filter(|t| !t.is_empty()) {- params.push(("tags", tag.to_string()));- }- }-- params- }-- /// List v3 tool definitions for one or more toolkits, preserving the- /// raw `input_parameters` JSON schema each action carries.- ///- /// Preserves the full schema so the LLM agent can supply valid arguments- /// without a separate round trip.- ///- /// `toolkits` may contain one or many slugs; when non-empty they are- /// sent as a comma-separated `toolkits=` filter to constrain the v3- /// catalogue scan. Empty filter returns every action across every- /// toolkit on the user's tenant (potentially large; callers should- /// pass a non-empty filter in practice).- ///- /// `tags` narrows the result by Composio action tag (OR semantics —- /// multiple tags broaden the result). This is the direct-mode (BYO- /// key) counterpart to the backend proxy's `tags` query param wired- /// in the connector module's proxy route; without it a self-key user's `composio_list_tools(..., tags)`- /// request would silently drop the tag filter. Blank/empty `tags`- /// are treated as no filter.- pub(crate) async fn list_tool_schemas_v3(- &self,- toolkits: &[&str],- tags: Option<&[&str]>,- ) -> anyhow::Result<Vec<ComposioToolSchemaV3>> {- let url = format!("{}/tools", self.base_v3);- let params = Self::build_list_tool_schemas_v3_query(toolkits, tags);- tracing::debug!(- toolkits = toolkits.len(),- tags = tags.map(<[&str]>::len).unwrap_or(0),- "[composio-direct] list_tool_schemas_v3: GET v3 /tools query built"- );- let req = self- .client()- .get(&url)- .header("x-api-key", &self.api_key)- .query(¶ms);-- let resp = req.send().await?;- if !resp.status().is_success() {- let err = response_error(resp).await;- anyhow::bail!("Composio v3 list_tool_schemas: {err}");- }-- let body: ComposioToolsResponse = resp- .json()- .await- .context("Failed to decode Composio v3 tools response")?;- Ok(body- .items- .into_iter()- .map(ComposioToolSchemaV3::from_v3_tool)- .collect())- }-}--#[derive(Debug, Deserialize)]-pub(super) struct ComposioToolsResponse {- #[serde(default)]- pub(super) items: Vec<ComposioV3Tool>,-}--#[derive(Debug, Clone, Deserialize)]-pub(super) struct ComposioV3Tool {- #[serde(default)]- pub(super) slug: Option<String>,- #[serde(default)]- pub(super) name: Option<String>,- #[serde(default)]- pub(super) description: Option<String>,- #[serde(rename = "appName", default)]- pub(super) app_name: Option<String>,- #[serde(default)]- pub(super) toolkit: Option<ComposioToolkitRef>,- /// JSON schema for the tool parameters. Composio v3 names this- /// `input_parameters`; older payloads use `parameters`. Either- /// shape deserialises into this field, and we re-emit it as- /// `ComposioToolFunction::parameters` so direct-mode users get- /// the same model-callable schema backend mode surfaces.- #[serde(default, alias = "parameters")]- pub(super) input_parameters: Option<serde_json::Value>,- /// JSON schema for the tool's OUTPUT/return value, per Composio v3- /// `/tools`'s `output_parameters` field ("Schema definition of return- /// values from the tool" —- /// <https://docs.composio.dev/reference/api-reference/tools/getTools>).- /// Re-emitted as `ComposioToolFunction::output_parameters` so callers- /// can ground a downstream binding in the tool's real output field- /// names instead of guessing them.- #[serde(default)]- pub(super) output_parameters: Option<serde_json::Value>,-}--#[derive(Debug, Clone, Deserialize)]-pub(super) struct ComposioToolkitRef {- #[serde(default)]- pub(super) slug: Option<String>,- #[serde(default)]- pub(super) name: Option<String>,-}--/// Direct-mode tool definition lifted from Composio v3 `/tools`.-///-/// Carries the `input_parameters` JSON schema so the upstream-/// `composio_list_tools` direct branch can hand the LLM agent a-/// model-callable function shape — same fields backend mode surfaces-/// through `ComposioToolSchema`.-///-/// Kept distinct from `ComposioAction` (legacy flattened shape) so-/// new callers explicitly opt into the schema-preserving variant.-#[derive(Debug, Clone)]-pub struct ComposioToolSchemaV3 {- pub slug: String,- pub description: Option<String>,- pub toolkit_slug: Option<String>,- pub input_parameters: Option<serde_json::Value>,- /// See [`ComposioV3Tool::output_parameters`] — Composio v3's schema for- /// the action's return value, when published.- pub output_parameters: Option<serde_json::Value>,-}--impl ComposioToolSchemaV3 {- fn from_v3_tool(item: ComposioV3Tool) -> Self {- let slug = item- .slug- .clone()- .or_else(|| item.name.clone())- .unwrap_or_default();- let toolkit_slug = item- .toolkit- .as_ref()- .and_then(|t| t.slug.clone().or(t.name.clone()))- .or(item.app_name);- Self {- slug,- description: item.description.or(item.name),- toolkit_slug,- input_parameters: item.input_parameters,- output_parameters: item.output_parameters,- }- }-}diff --git a/crates/openhuman-core/src/integrations/composio/tools/direct/transport.rs b/crates/openhuman-core/src/integrations/composio/tools/direct/transport.rsnew file mode 100644index 0000000000..6a424d9207--- /dev/null+++ b/crates/openhuman-core/src/integrations/composio/tools/direct/transport.rs@@ -0,0 +1,114 @@+//! The host's [`tinyconnectors::client::Transport`] for the direct route.+//!+//! `DirectRoute` owns the paths and the response translation; this owns the+//! wire. It exists (instead of the module's own `ureq` transport) because the+//! host must keep honouring `[proxy]` runtime settings and its TLS roots for+//! Composio traffic, refuse redirects so the `x-api-key` header cannot follow+//! one, and render failures with the exact messages users and the+//! observability classifier already key on.++use std::sync::Arc;++use async_trait::async_trait;+use tinyconnectors::client::{DirectRoute, Transport};+use tinyconnectors::Error as ConnectorError;++use super::http_errors::response_error;+use super::types::DirectComposioClient;++/// Failure label per request path, matching the messages the host has always+/// produced (and the `[composio-direct]` observability anchors match on).+fn failure_label(path: &str) -> &'static str {+ if path.starts_with("/connected_accounts") {+ "Composio v3 connected_accounts failed"+ } else {+ "Composio v3 list_tool_schemas"+ }+}++fn decode_label(path: &str) -> &'static str {+ if path.starts_with("/connected_accounts") {+ "Failed to decode Composio v3 connected_accounts response"+ } else {+ "Failed to decode Composio v3 tools response"+ }+}++fn transport_error(path: &str, message: String) -> ConnectorError {+ ConnectorError::Transport {+ path: path.to_string(),+ message,+ }+}++impl DirectComposioClient {+ /// The module's direct route over this client's transport.+ ///+ /// Built per call: the host's process-wide key gate (`direct_auth`) is what+ /// persists across calls, so the route's own per-instance gate never trips+ /// here by design.+ pub(crate) fn route(self: &Arc<Self>) -> DirectRoute {+ DirectRoute::new(self.clone(), &self.api_key, "default")+ }+}++/// Collapse a route failure into the message the transport produced.+///+/// The route wraps transport failures as `request to <path> failed: <msg>`;+/// users have only ever seen `<msg>`.+pub(crate) fn route_error(error: ConnectorError) -> anyhow::Error {+ match error {+ ConnectorError::Transport { message, .. } => anyhow::anyhow!(message),+ other => anyhow::anyhow!(other.to_string()),+ }+}++#[async_trait]+impl Transport for DirectComposioClient {+ async fn get(&self, path: &str) -> tinyconnectors::Result<serde_json::Value> {+ let url = format!("{}{}", self.base_v3, path);+ self.ensure_request_url(&url)+ .map_err(|e| transport_error(path, format!("{e:#}")))?;+ tracing::debug!(path = %path.split('?').next().unwrap_or(path), "[composio-direct] transport GET");++ let resp = self+ .client()+ .get(&url)+ .header("x-api-key", &self.api_key)+ .send()+ .await+ .map_err(|e| transport_error(path, format!("{:#}", anyhow::Error::from(e))))?;++ if !resp.status().is_success() {+ let err = response_error(resp).await;+ return Err(transport_error(+ path,+ format!("{}: {err}", failure_label(path)),+ ));+ }++ resp.json::<serde_json::Value>().await.map_err(|e| {+ transport_error(path, format!("{}: {e}", decode_label(path)))+ })+ }++ async fn post(+ &self,+ path: &str,+ _body: &serde_json::Value,+ ) -> tinyconnectors::Result<serde_json::Value> {+ Err(transport_error(+ path,+ "the host direct transport serves reads only; writes run in the connector module"+ .to_string(),+ ))+ }++ async fn delete(&self, path: &str) -> tinyconnectors::Result<serde_json::Value> {+ Err(transport_error(+ path,+ "the host direct transport serves reads only; writes run in the connector module"+ .to_string(),+ ))+ }+}diff --git a/crates/openhuman-core/src/integrations/composio/tools/direct/types.rs b/crates/openhuman-core/src/integrations/composio/tools/direct/types.rsindex b2982534d5..f43f75107b 100644--- a/crates/openhuman-core/src/integrations/composio/tools/direct/types.rs+++ b/crates/openhuman-core/src/integrations/composio/tools/direct/types.rs@@ -40,13 +40,13 @@ pub(super) fn is_loopback_http_base(url: &str) -> bool {is_loopback_http_url(&format!("{}/", url.trim_end_matches('/')))}-/// Slim host-side HTTP reader for Composio's own v3 API with the user's key.+/// Host-side HTTP transport for Composio's own v3 API with the user's key.////// Composio execution, the OAuth handoff and connection management all run in-/// the `tinyconnectors` module. This client only serves the two reads whose-/// request parameters the pinned module route does not carry-/// (`/connected_accounts?limit=200`, `/tools?toolkit_versions=latest`) and the-/// pre-store API-key probe.+/// the `tinyconnectors` module. This client carries the direct-route reads+/// (`tinyconnectors::client::DirectRoute` over the `Transport` impl in+/// `transport.rs`) and the pre-store API-key probe through the host's proxy and+/// TLS settings.pub struct DirectComposioClient {pub(super) api_key: String,/// Base URL for Composio v3 endpoints (`{base}/tools`). Production@@ -56,3 +56,12 @@ pub struct DirectComposioClient {pub(super) base_v3: String,pub(super) allow_insecure_loopback: bool,}++// Manual `Debug` (a `Transport` must be `Debug`): never prints the key.+impl std::fmt::Debug for DirectComposioClient {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("DirectComposioClient")+ .field("base_v3", &self.base_v3)+ .finish_non_exhaustive()+ }+}