Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | from __future__ import annotations |
| 2 | |
| 3 | import logging |
| 4 | import os |
| 5 | import typing as t |
| 6 | import warnings |
| 7 | |
| 8 | import httpx |
| 9 | import typing_extensions as te |
| 10 | from composio_client import Auth, AutoAuth, ProjectAuth, Scope, UserAuth |
| 11 | |
| 12 | from composio import exceptions |
| 13 | from composio.client import DEFAULT_MAX_RETRIES, APIEnvironment, HttpClient |
| 14 | from composio.core.models import ( |
| 15 | AuthConfigs, |
| 16 | ConnectedAccounts, |
| 17 | Keyring, |
| 18 | Logs, |
| 19 | Toolkits, |
| 20 | ToolRouter, |
| 21 | Tools, |
| 22 | Triggers, |
| 23 | Webhooks, |
| 24 | ) |
| 25 | from composio.core.models.base import allow_tracking |
| 26 | from composio.core.models.mcp import MCP |
| 27 | from composio.core.provider import TTool, TToolCollection |
| 28 | from composio.core.provider._openai import ( |
| 29 | OpenAIProvider, |
| 30 | OpenAITool, |
| 31 | OpenAIToolCollection, |
| 32 | ) |
| 33 | from composio.core.provider.base import BaseProvider |
| 34 | from composio.core.types import ToolkitVersionParam |
| 35 | from composio.utils.logging import LogLevel, WithLogger |
| 36 | from composio.utils.toolkit_version import get_toolkit_versions |
| 37 | |
| 38 | _TOOL_ROUTER_DEPRECATION = ( |
| 39 | "`composio.tool_router` is deprecated; use `composio.sessions` instead " |
| 40 | "(or the `composio.create` / `composio.use` shortcuts). It returns the same object." |
| 41 | ) |
| 42 | |
| 43 | |
| 44 | class SDKConfig(te.TypedDict): |
| 45 | environment: te.NotRequired[APIEnvironment] |
| 46 | api_key: te.NotRequired[str] |
| 47 | disable_api_key: te.NotRequired[bool] |
| 48 | user_api_key: te.NotRequired[str] |
| 49 | org_api_key: te.NotRequired[str] |
| 50 | org_id: te.NotRequired[str] |
| 51 | project_id: te.NotRequired[str] |
| 52 | base_url: te.NotRequired[str] |
| 53 | timeout: te.NotRequired[int] |
| 54 | max_retries: te.NotRequired[int] |
| 55 | allow_tracking: te.NotRequired[bool] |
| 56 | file_download_dir: te.NotRequired[str] |
| 57 | toolkit_versions: te.NotRequired[ToolkitVersionParam] |
| 58 | dangerously_allow_auto_upload_download_files: te.NotRequired[bool] |
| 59 | sensitive_file_upload_protection: te.NotRequired[bool] |
| 60 | file_upload_path_deny_segments: te.NotRequired[t.Sequence[str]] |
| 61 | file_upload_dirs: te.NotRequired[t.Union[t.Sequence[str], t.Literal[False]]] |
| 62 | http_client: te.NotRequired[httpx.Client] |
| 63 | logger: te.NotRequired[logging.Logger] |
| 64 | logging_level: te.NotRequired[LogLevel] |
| 65 | |
| 66 | |
| 67 | def _scope( |
| 68 | *, org_id: t.Optional[str], project_id: t.Optional[str] |
| 69 | ) -> t.Optional[Scope]: |
| 70 | """The client ``scope`` for an explicit ``org_id`` / ``project_id`` pair. |
| 71 | |
| 72 | The two nano IDs scope requests together: a user API key without an |
| 73 | explicit scope keeps the API default (the developer project), so a |
| 74 | half-configured scope is rejected instead of silently selecting a project. |
| 75 | The client sends them as ``x-org-id`` / ``x-project-id``. |
| 76 | """ |
| 77 | org_id = org_id or None |
| 78 | project_id = project_id or None |
| 79 | if (org_id is None) != (project_id is None): |
| 80 | raise exceptions.InvalidParams( |
| 81 | "`org_id` and `project_id` scope requests together; pass both " |
| 82 | "(the organization and consumer project nano IDs) or neither" |
| 83 | ) |
| 84 | if org_id is None or project_id is None: |
| 85 | return None |
| 86 | return Scope(organization_id=org_id, project_id=project_id) |
| 87 | |
| 88 | |
| 89 | def _env_key(name: str) -> t.Optional[str]: |
| 90 | """``name`` from the environment, or ``None`` when unset or blank.""" |
| 91 | value = os.environ.get(name) |
| 92 | return value if value and value.strip() else None |
| 93 | |
| 94 | |
| 95 | def _custom_headers() -> t.Optional[t.Dict[str, str]]: |
| 96 | """``COMPOSIO_CUSTOM_HEADERS`` (``name: value`` lines) as default headers. |
| 97 | |
| 98 | The generated client read this variable itself until 2.0.0-rc.18; it now |
| 99 | reads no environment, so the SDK keeps sending what it always sent. |
| 100 | """ |
| 101 | raw = os.environ.get("COMPOSIO_CUSTOM_HEADERS") |
| 102 | if not raw: |
| 103 | return None |
| 104 | parsed: t.Dict[str, str] = {} |
| 105 | for line in raw.split("\n"): |
| 106 | colon = line.find(":") |
| 107 | if colon >= 0: |
| 108 | parsed[line[:colon].strip()] = line[colon + 1 :].strip() |
| 109 | return parsed or None |
| 110 | |
| 111 | |
| 112 | class Composio(t.Generic[TTool, TToolCollection], WithLogger): |
| 113 | """ |
| 114 | Composio SDK for Python. |
| 115 | |
| 116 | Generic parameters: |
| 117 | TTool: The individual tool type returned by the provider (e.g., ChatCompletionToolParam for OpenAI). |
| 118 | TToolCollection: The collection type returned by get_tools (e.g., list[ChatCompletionToolParam]). |
| 119 | |
| 120 | The generic types are automatically inferred from the provider passed to __init__. |
| 121 | When no provider is passed, defaults to OpenAI types. |
| 122 | |
| 123 | Examples: |
| 124 | # Implicit type inference - recommended |
| 125 | composio = Composio(provider=OpenAIProvider()) # Composio[OpenAITool, list[OpenAITool]] |
| 126 | composio = Composio(provider=AnthropicProvider()) # Composio[ToolParam, list[ToolParam]] |
| 127 | composio = Composio() # Composio[OpenAITool, list[OpenAITool]] (default) |
| 128 | |
| 129 | # Custom provider - types are inferred automatically |
| 130 | composio = Composio(provider=MyCustomProvider()) # Composio[MyTool, list[MyTool]] |
| 131 | """ |
| 132 | |
| 133 | tools: "Tools[TTool, TToolCollection]" |
| 134 | |
| 135 | @t.overload |
| 136 | def __init__( |
| 137 | self: "Composio[OpenAITool, OpenAIToolCollection]", |
| 138 | provider: None = None, |
| 139 | **kwargs: te.Unpack[SDKConfig], |
| 140 | ) -> None: |
| 141 | """Initialize with default OpenAI provider.""" |
| 142 | ... |
| 143 | |
| 144 | @t.overload |
| 145 | def __init__( |
| 146 | self, |
| 147 | provider: BaseProvider[TTool, TToolCollection], |
| 148 | **kwargs: te.Unpack[SDKConfig], |
| 149 | ) -> None: |
| 150 | """Initialize with an explicit provider. Types are inferred from the provider.""" |
| 151 | ... |
| 152 | |
| 153 | def __init__( |
| 154 | self, |
| 155 | provider: t.Optional[BaseProvider[t.Any, t.Any]] = None, |
| 156 | **kwargs: te.Unpack[SDKConfig], |
| 157 | ) -> None: |
| 158 | """ |
| 159 | Initialize the Composio SDK. |
| 160 | |
| 161 | :param provider: The provider to use for the SDK. Defaults to OpenAIProvider. |
| 162 | :param environment: The environment to use for the SDK. |
| 163 | :param api_key: The project API key, sent as ``x-api-key``. When the |
| 164 | argument is omitted it falls back to ``COMPOSIO_API_KEY``, as it |
| 165 | always has. Passing ``api_key=None`` explicitly does not fall back |
| 166 | and raises :class:`~composio.exceptions.ApiKeyNotProvidedError`; |
| 167 | use ``disable_api_key=True`` to opt out of project-key |
| 168 | authentication. |
| 169 | :param disable_api_key: Turn project-key authentication off entirely, |
| 170 | including the ``COMPOSIO_API_KEY`` fallback. The SDK then authenticates |
| 171 | with the user API key alone (``user_api_key`` or |
| 172 | ``COMPOSIO_USER_API_KEY``) and sends no ``x-api-key``; requests that |
| 173 | require a project key keep their operation-specific errors. Combining |
| 174 | it with an explicit ``api_key`` is an error. Defaults to ``False``. |
| 175 | :param user_api_key: User API key (``uak_*``) for the organization, consumer, |
| 176 | and user-scoped endpoints reached through ``composio.client``, and for |
| 177 | every session operation when ``disable_api_key=True``. Sent as |
| 178 | ``x-user-api-key`` only on operations whose security scheme accepts it, |
| 179 | never alongside the project key. Falls back to ``COMPOSIO_USER_API_KEY``. |
| 180 | :param org_api_key: Organization API key (``oak_*``) for the organization-owner |
| 181 | endpoints reached through ``composio.client``. Sent as ``x-org-api-key`` only |
| 182 | on operations whose security scheme requires it, never alongside the |
| 183 | project key. Falls back to ``COMPOSIO_ORG_API_KEY``. A project ``api_key`` |
| 184 | is still required. |
| 185 | :param org_id: Organization nano ID that scopes user-key requests, sent as the |
| 186 | ``x-org-id`` header on every request and exported with the session MCP |
| 187 | config. This is the short public identifier the API returns as |
| 188 | ``org_id`` (for example from the consumer project resolve endpoint), not |
| 189 | a UUID. Must be supplied together with ``project_id``; without an |
| 190 | explicit scope a user API key addresses the API default (the developer |
| 191 | project). |
| 192 | :param project_id: Project nano ID that scopes user-key requests, sent as the |
| 193 | ``x-project-id`` header on every request and exported with the session |
| 194 | MCP config. This is the short public identifier the API returns as |
| 195 | ``project_nano_id``, not the project UUID. Must be supplied together |
| 196 | with ``org_id``. |
| 197 | :param base_url: The base URL to use for the SDK. |
| 198 | :param timeout: The timeout to use for the SDK. |
| 199 | :param max_retries: The maximum number of retries to use for the SDK. |
| 200 | :param toolkit_versions: A dictionary mapping toolkit names to specific versions: |
| 201 | - A dictionary mapping toolkit names to specific versions |
| 202 | - A string (e.g., 'latest', '20250906_01') to use the same version for all toolkits |
| 203 | - None or omitted to use 'latest' as default |
| 204 | :param dangerously_allow_auto_upload_download_files: Opt-in for automatic file |
| 205 | upload and download during tool execution. Defaults to False. |
| 206 | :param sensitive_file_upload_protection: When True, block local paths on the built-in sensitive-path denylist before upload. Defaults to True. |
| 207 | :param file_upload_path_deny_segments: Extra path segment names merged with the built-in denylist. |
| 208 | :param file_upload_dirs: Allowlist of directories from which the SDK is allowed |
| 209 | to read local files during **automatic** file upload (the flow gated by |
| 210 | ``dangerously_allow_auto_upload_download_files=True``). |
| 211 | |
| 212 | - ``None`` (default) -> ``[~/.composio/temp]``. |
| 213 | - ``False`` -> reject every local path during auto-upload. URLs and |
| 214 | in-memory bytes still work because they aren't path-checked. |
| 215 | - ``Sequence[str]`` (non-empty) -> use as the allowlist. A file is accepted |
| 216 | iff its symlink-resolved absolute path is inside one of these directories |
| 217 | on a path-component boundary (``/tmp/foo`` allows ``/tmp/foo/bar`` but |
| 218 | NOT ``/tmp/foo-bar``). |
| 219 | - ``[]`` -> behaves like ``False`` (kept as an alias; prefer ``False``). |
| 220 | - Providing a value REPLACES the default. Include ``~/.composio/temp`` in |
| 221 | your list if you want the default staging dir to keep working. |
| 222 | - On Windows, entries are compared case-insensitively. |
| 223 | :param http_client: An ``httpx.Client`` the SDK sends every API request |
| 224 | through (custom transports, proxies, or mocked transports in tests). |
| 225 | :param logger: A ``logging.Logger`` that receives the ``Composio`` |
| 226 | instance's log records and the records the underlying |
| 227 | ``composio_client`` emits (its per-request lifecycle records at |
| 228 | DEBUG). Sensitive values are redacted and long lines truncated |
| 229 | before a record reaches it. Other SDK components still log to the |
| 230 | shared ``composio`` logger, and deprecation notices are raised as |
| 231 | ``ComposioDeprecationWarning`` warnings rather than log records. |
| 232 | Defaults to the shared ``composio`` logger. |
| 233 | :param logging_level: The :class:`composio.utils.logging.LogLevel` applied |
| 234 | to the SDK logger and to the ``composio_client`` logger. Defaults to |
| 235 | ``LogLevel.INFO`` (``COMPOSIO_LOGGING_LEVEL`` overrides the default |
| 236 | when no ``logger`` is passed). |
| 237 | """ |
| 238 | logger = kwargs.get("logger") |
| 239 | logging_level = kwargs.get("logging_level") |
| 240 | WithLogger.__init__(self, logger=logger, logging_level=logging_level) |
| 241 | disable_api_key = kwargs.get("disable_api_key", False) |
| 242 | user_api_key = kwargs.get("user_api_key") or _env_key("COMPOSIO_USER_API_KEY") |
| 243 | org_api_key = kwargs.get("org_api_key") or _env_key("COMPOSIO_ORG_API_KEY") |
| 244 | auth: Auth |
| 245 | if disable_api_key: |
| 246 | if kwargs.get("api_key") is not None: |
| 247 | raise exceptions.InvalidParams( |
| 248 | "`disable_api_key=True` cannot be combined with an explicit " |
| 249 | "`api_key`; pass one or the other" |
| 250 | ) |
| 251 | if not user_api_key: |
| 252 | raise exceptions.UserApiKeyNotProvidedError() |
| 253 | # The user key alone, on every request. An organization key is |
| 254 | # not sent in this mode, as before. |
| 255 | auth = UserAuth(user_api_key) |
| 256 | else: |
| 257 | api_key = kwargs.get("api_key", os.environ.get("COMPOSIO_API_KEY")) |
| 258 | if not api_key: |
| 259 | raise exceptions.ApiKeyNotProvidedError() |
| 260 | # With a user or organization key beside it, the client sends |
| 261 | # exactly one credential per request: the project key wherever the |
| 262 | # operation accepts it, otherwise the first declared scheme a key is |
| 263 | # held for. With the project key alone, that key on every request. |
| 264 | auth = ( |
| 265 | AutoAuth(project=api_key, user=user_api_key, organization=org_api_key) |
| 266 | if user_api_key or org_api_key |
| 267 | else ProjectAuth(api_key) |
| 268 | ) |
| 269 | scope = _scope(org_id=kwargs.get("org_id"), project_id=kwargs.get("project_id")) |
| 270 | |
| 271 | # Each instance gets its own provider so that the execute_tool_fn binding |
| 272 | # performed by Tools.__init__ cannot leak across SDK instances (issue #4369). |
| 273 | actual_provider: BaseProvider[TTool, TToolCollection] = t.cast( |
| 274 | BaseProvider[TTool, TToolCollection], |
| 275 | provider if provider is not None else OpenAIProvider(), |
| 276 | ) |
| 277 | |
| 278 | # Process toolkit versions with environment variable support |
| 279 | toolkit_versions = get_toolkit_versions(kwargs.get("toolkit_versions")) |
| 280 | |
| 281 | allow_tracking.set(kwargs.get("allow_tracking", True)) |
| 282 | self._client = HttpClient( |
| 283 | environment=kwargs.get("environment", "production"), |
| 284 | provider=actual_provider.name, |
| 285 | auth=auth, |
| 286 | scope=scope, |
| 287 | base_url=kwargs.get("base_url") or os.environ.get("COMPOSIO_BASE_URL"), |
| 288 | timeout=kwargs.get("timeout"), |
| 289 | max_retries=kwargs.get("max_retries", DEFAULT_MAX_RETRIES), |
| 290 | default_headers=_custom_headers(), |
| 291 | http_client=kwargs.get("http_client"), |
| 292 | logger=logger, |
| 293 | logging_level=logging_level, |
| 294 | ) |
| 295 | self.provider = actual_provider |
| 296 | sensitive_file_upload_protection: bool = kwargs.get( |
| 297 | "sensitive_file_upload_protection", True |
| 298 | ) |
| 299 | file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = kwargs.get( |
| 300 | "file_upload_path_deny_segments" |
| 301 | ) |
| 302 | file_upload_dirs: t.Union[t.Sequence[str], t.Literal[False], None] = kwargs.get( |
| 303 | "file_upload_dirs" |
| 304 | ) |
| 305 | self.tools = Tools( |
| 306 | client=self._client, |
| 307 | provider=actual_provider, |
| 308 | file_download_dir=kwargs.get("file_download_dir"), |
| 309 | toolkit_versions=toolkit_versions, |
| 310 | dangerously_allow_auto_upload_download_files=kwargs.get( |
| 311 | "dangerously_allow_auto_upload_download_files", False |
| 312 | ), |
| 313 | sensitive_file_upload_protection=sensitive_file_upload_protection, |
| 314 | file_upload_path_deny_segments=file_upload_path_deny_segments, |
| 315 | file_upload_dirs=file_upload_dirs, |
| 316 | ) |
| 317 | |
| 318 | self.toolkits = Toolkits(client=self._client) |
| 319 | self.triggers = Triggers(client=self._client, toolkit_versions=toolkit_versions) |
| 320 | self.auth_configs = AuthConfigs(client=self._client) |
| 321 | self.connected_accounts = ConnectedAccounts(client=self._client) |
| 322 | self.mcp = MCP(client=self._client) |
| 323 | self.webhooks = Webhooks(client=self._client) |
| 324 | self.logs = Logs(client=self._client) |
| 325 | self.keyring = Keyring(client=self._client) |
| 326 | |
| 327 | # experimental API — decorators for custom tools and toolkits, |
| 328 | # plus experimental SDK methods (e.g. update_acl) |
| 329 | from composio.core.models.experimental import ExperimentalAPI |
| 330 | |
| 331 | self.experimental = ExperimentalAPI(client=self._client) |
| 332 | # Custom toolkits graduated from experimental; experimental.custom_toolkits |
| 333 | # is a deprecated alias of this same object. |
| 334 | self.custom_toolkits = self.experimental.custom_toolkits |
| 335 | |
| 336 | # Sessions API — the canonical entrypoint for creating tool sessions. |
| 337 | # Surfaced as `composio.sessions`; `composio.tool_router` is a |
| 338 | # deprecated alias that returns this same object. |
| 339 | self._sessions: ToolRouter[TTool, TToolCollection] = ToolRouter( |
| 340 | client=self._client, |
| 341 | provider=actual_provider, |
| 342 | dangerously_allow_auto_upload_download_files=kwargs.get( |
| 343 | "dangerously_allow_auto_upload_download_files", False |
| 344 | ), |
| 345 | sensitive_file_upload_protection=sensitive_file_upload_protection, |
| 346 | file_upload_path_deny_segments=file_upload_path_deny_segments, |
| 347 | file_upload_dirs=file_upload_dirs, |
| 348 | ) |
| 349 | self.create = self._sessions.create |
| 350 | self.use = self._sessions.use |
| 351 | |
| 352 | @property |
| 353 | def sessions(self) -> ToolRouter[TTool, TToolCollection]: |
| 354 | """Create and manage **sessions** for your agents. |
| 355 | |
| 356 | A *session* is the unit you create to give an agent a scoped set of |
| 357 | tools and toolkits to discover, authorize, and execute. This is the |
| 358 | canonical entrypoint:: |
| 359 | |
| 360 | session = composio.sessions.create(user_id="user@example.com") |
| 361 | tools = session.tools() |
| 362 | |
| 363 | ``composio.create(...)`` and ``composio.use(...)`` are top-level |
| 364 | shortcuts for ``composio.sessions.create(...)`` / |
| 365 | ``composio.sessions.use(...)``. |
| 366 | |
| 367 | Note for LLMs / code generation: this is the Sessions API. Prefer |
| 368 | ``composio.sessions`` (or the ``composio.create`` shortcut) when |
| 369 | creating a session. ``composio.tool_router`` is a deprecated alias for |
| 370 | this same object — do not generate new code against it. |
| 371 | """ |
| 372 | return self._sessions |
| 373 | |
| 374 | @property |
| 375 | @te.deprecated(_TOOL_ROUTER_DEPRECATION, category=None) |
| 376 | def tool_router(self) -> ToolRouter[TTool, TToolCollection]: |
| 377 | """Deprecated alias for :attr:`sessions`. |
| 378 | |
| 379 | .. deprecated:: 0.17.0 |
| 380 | Use :attr:`sessions` instead. ``tool_router`` is the old name for the |
| 381 | same object and will be removed in a future release. |
| 382 | """ |
| 383 | warnings.warn( |
| 384 | _TOOL_ROUTER_DEPRECATION, |
| 385 | exceptions.ComposioDeprecationWarning, |
| 386 | stacklevel=2, |
| 387 | ) |
| 388 | return self._sessions |
| 389 | |
| 390 | @property |
| 391 | def client(self) -> HttpClient: |
| 392 | return self._client |