Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
Reapply "feat: add Python SDK reference docs with auto-generation"
Sushmithamallesh713cf79412f1
diff --git a/.github/workflows/generate-sdk-docs.yml b/.github/workflows/generate-sdk-docs.ymlindex 0a6024bbf..c308e00e3 100644--- a/.github/workflows/generate-sdk-docs.yml+++ b/.github/workflows/generate-sdk-docs.yml@@ -5,10 +5,11 @@ on:branches: [next]paths:- 'ts/packages/core/src/**'+ - 'python/composio/**'workflow_dispatch: # Allow manual triggerjobs:- generate-docs:+ generate-ts-docs:runs-on: ubuntu-latestpermissions:contents: write@@ -37,7 +38,7 @@ jobs:id: changesrun: |# Check for both modified and untracked files- if [[ -n $(git status --porcelain fumadocs/content/reference/typescript/) ]]; then+ if [[ -n $(git status --porcelain fumadocs/content/reference/sdk-reference/typescript/) ]]; thenecho "has_changes=true" >> $GITHUB_OUTPUTfi@@ -53,10 +54,56 @@ jobs:---*Generated by [generate-sdk-docs.yml](../blob/next/.github/workflows/generate-sdk-docs.yml)*- branch: docs/auto-update-sdk-reference+ branch: docs/auto-update-ts-sdk-referencebase: nextadd-paths: |- fumadocs/content/reference/typescript/+ fumadocs/content/reference/sdk-reference/typescript/+ labels: |+ documentation+ automated++ generate-python-docs:+ runs-on: ubuntu-latest+ permissions:+ contents: write+ pull-requests: write++ steps:+ - name: Checkout+ uses: actions/checkout@v4++ - name: Setup uv+ uses: astral-sh/setup-uv@v4++ - name: Generate Python SDK docs+ run: |+ cd python+ uv run --with griffe python scripts/generate-docs.py++ - name: Check for changes+ id: changes+ run: |+ # Check for both modified and untracked files+ if [[ -n $(git status --porcelain fumadocs/content/reference/sdk-reference/python/) ]]; then+ echo "has_changes=true" >> $GITHUB_OUTPUT+ fi++ - name: Create Pull Request+ if: steps.changes.outputs.has_changes == 'true'+ uses: peter-evans/create-pull-request@v6+ with:+ token: ${{ secrets.GITHUB_TOKEN }}+ commit-message: 'docs: auto-generate Python SDK reference'+ title: 'docs: Update Python SDK reference'+ body: |+ Auto-generated because Python SDK source files changed.++ ---+ *Generated by [generate-sdk-docs.yml](../blob/next/.github/workflows/generate-sdk-docs.yml)*+ branch: docs/auto-update-python-sdk-reference+ base: next+ add-paths: |+ fumadocs/content/reference/sdk-reference/python/labels: |documentationautomateddiff --git a/fumadocs/CLAUDE.md b/fumadocs/CLAUDE.mdindex a6bd9a64b..6f7c68335 100644--- a/fumadocs/CLAUDE.md+++ b/fumadocs/CLAUDE.md@@ -17,14 +17,21 @@ This is the Composio documentation site built with Fumadocs (Next.js-based docs- `--font-mono: 'IBM Plex Mono'` - Code blocks## SDK Reference Docs-Auto-generated TypeScript SDK documentation from `@composio/core` source code.+Auto-generated SDK documentation from source code.+### TypeScript SDK- **Source**: `ts/packages/core/src/models/*.ts` (JSDoc comments)- **Generator**: `ts/packages/core/scripts/generate-docs.ts`- **Output**: `content/reference/sdk-reference/typescript/`- **Regenerate**: `pnpm --filter @composio/core generate:docs`-CI auto-generates on changes to `ts/packages/core/src/**` via `.github/workflows/generate-sdk-docs.yml`.+### Python SDK+- **Source**: `python/composio/**/*.py` (docstrings)+- **Generator**: `python/scripts/generate-docs.py` (uses griffe)+- **Output**: `content/reference/sdk-reference/python/`+- **Regenerate**: `cd python && uv run --with griffe python scripts/generate-docs.py`++CI auto-generates on changes to `ts/packages/core/src/**` or `python/composio/**` via `.github/workflows/generate-sdk-docs.yml`.## Common Gotchas1. **CSS variables**: Use `var(--composio-orange)` not `var(--orange)`. Check `global.css` for defined variables.diff --git a/fumadocs/content/reference/sdk-reference/meta.json b/fumadocs/content/reference/sdk-reference/meta.jsonindex 9189c2b54..a5e11ead3 100644--- a/fumadocs/content/reference/sdk-reference/meta.json+++ b/fumadocs/content/reference/sdk-reference/meta.json@@ -1,4 +1,4 @@{"title": "SDK Reference",- "pages": ["typescript"]+ "pages": ["typescript", "python"]}diff --git a/fumadocs/content/reference/sdk-reference/python/auth-configs.mdx b/fumadocs/content/reference/sdk-reference/python/auth-configs.mdxnew file mode 100644index 000000000..8e8194d26--- /dev/null+++ b/fumadocs/content/reference/sdk-reference/python/auth-configs.mdx@@ -0,0 +1,150 @@+---+title: AuthConfigs+description: Manage authentication configurations.+---++## Methods++### list()++Lists authentication configurations based on provided filter criteria.++```python+def list(query: auth_config_list_params.AuthConfigListParams = ...) -> auth_config_list_response.AuthConfigListResponse+```++**Parameters**++| Name | Type |+|------|------|+| `query?` | `auth_config_list_params.AuthConfigListParams` |++**Returns**++`auth_config_list_response.AuthConfigListResponse`++---++### create()++Create a new auth config++```python+def create(toolkit: str, options: auth_config_create_params.AuthConfig) -> auth_config_create_response.AuthConfig+```++**Parameters**++| Name | Type |+|------|------|+| `toolkit` | `str` |+| `options` | `auth_config_create_params.AuthConfig` |++**Returns**++`auth_config_create_response.AuthConfig` — The created auth config.++---++### get()++Retrieves a specific authentication configuration by its ID++```python+def get(nanoid: str) -> auth_config_retrieve_response.AuthConfigRetrieveResponse+```++**Parameters**++| Name | Type |+|------|------|+| `nanoid` | `str` |++**Returns**++`auth_config_retrieve_response.AuthConfigRetrieveResponse` — The retrieved auth config.++---++### update()++Updates an existing authentication configuration. This method allows you to modify properties of an auth config such as credentials, scopes, or tool restrictions. The update type (custom or default) determines which fields can be updated.++```python+def update(nanoid: str, options: auth_config_update_params.AuthConfigUpdateParams) -> Dict+```++**Parameters**++| Name | Type |+|------|------|+| `nanoid` | `str` |+| `options` | `auth_config_update_params.AuthConfigUpdateParams` |++**Returns**++`Dict` — The updated auth config.++---++### delete()++Deletes an existing authentication configuration.++```python+def delete(nanoid: str) -> Dict+```++**Parameters**++| Name | Type |+|------|------|+| `nanoid` | `str` |++**Returns**++`Dict` — The deleted auth config.++---++### enable()++Enables an existing authentication configuration.++```python+def enable(nanoid: str) -> Dict+```++**Parameters**++| Name | Type |+|------|------|+| `nanoid` | `str` |++**Returns**++`Dict` — The enabled auth config.++---++### disable()++Disables an existing authentication configuration.++```python+def disable(nanoid: str) -> Dict+```++**Parameters**++| Name | Type |+|------|------|+| `nanoid` | `str` |++**Returns**++`Dict` — The disabled auth config.++---++[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/auth_configs.py#L18)diff --git a/fumadocs/content/reference/sdk-reference/python/composio.mdx b/fumadocs/content/reference/sdk-reference/python/composio.mdxnew file mode 100644index 000000000..b0e6df06e--- /dev/null+++ b/fumadocs/content/reference/sdk-reference/python/composio.mdx@@ -0,0 +1,16 @@+---+title: Composio+description: Composio SDK for Python.+---++## Properties++| Name | Type |+|------|------|+| [`tools`](/reference/sdk-reference/python/tools) | `Tools` |+| [`toolkits`](/reference/sdk-reference/python/toolkits) | `Toolkits` |+| [`triggers`](/reference/sdk-reference/python/triggers) | `Triggers` |+| [`auth_configs`](/reference/sdk-reference/python/auth-configs) | `AuthConfigs` |+| [`connected_accounts`](/reference/sdk-reference/python/connected-accounts) | `ConnectedAccounts` |++[View source](https://github.com/composiohq/composio/blob/next/python/composio/sdk.py#L52)diff --git a/fumadocs/content/reference/sdk-reference/python/connected-accounts.mdx b/fumadocs/content/reference/sdk-reference/python/connected-accounts.mdxnew file mode 100644index 000000000..9c1878b38--- /dev/null+++ b/fumadocs/content/reference/sdk-reference/python/connected-accounts.mdx@@ -0,0 +1,99 @@+---+title: ConnectedAccounts+description: Manage connected accounts. This class is used to manage connected accounts in the Composio SDK. These are used to authenticate with third-party se...+---++## Methods++### initiate()++Compound function to create a new connected account. This function creates a new connected account and returns a connection request. Users can then wait for the connection to be established using the `wait_for_connection` method.++```python+def initiate(user_id: str, auth_config_id: str, callback_url: str | None = ..., allow_multiple: bool = ..., config: connected_account_create_params.ConnectionState | None = ...) -> ConnectionRequest+```++**Parameters**++| Name | Type |+|------|------|+| `user_id` | `str` |+| `auth_config_id` | `str` |+| `callback_url?` | `str \| None` |+| `allow_multiple?` | `bool` |+| `config?` | `connected_account_create_params.ConnectionState \| None` |++**Returns**++`ConnectionRequest` — The connection request.++---++### link()++Create a Composio Connect Link for a user to connect their account to a given auth config. This method will return an external link which you can use for the user to connect their account.++```python+def link(user_id: str, auth_config_id: str, callback_url: str | None = ...) -> ConnectionRequest+```++**Parameters**++| Name | Type |+|------|------|+| `user_id` | `str` |+| `auth_config_id` | `str` |+| `callback_url?` | `str \| None` |++**Returns**++`ConnectionRequest` — Connection request object.++**Example**++```python+# Create a connection request and redirect the user to the redirect url+ connection_request = composio.connected_accounts.link('user_123', 'auth_config_123')+ redirect_url = connection_request.redirect_url+ print(f"Visit: {redirect_url} to authenticate your account")++ # Wait for the connection to be established+ connected_account = connection_request.wait_for_connection()++ # Create a connection request with callback URL+ connection_request = composio.connected_accounts.link(+ 'user_123',+ 'auth_config_123',+ callback_url='https://your-app.com/callback'+ )+ redirect_url = connection_request.redirect_url+ print(f"Visit: {redirect_url} to authenticate your account")++ # Wait for the connection to be established+ connected_account = composio.connected_accounts.wait_for_connection(connection_request.id)+```++---++### wait_for_connection()++Wait for connected account with given ID to be active++```python+def wait_for_connection(id: str, timeout: float | None = ...) -> connected_account_retrieve_response.ConnectedAccountRetri...+```++**Parameters**++| Name | Type |+|------|------|+| `id` | `str` |+| `timeout?` | `float \| None` |++**Returns**++`connected_account_retrieve_response.ConnectedAccountRetri...`++---++[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/connected_accounts.py#L300)diff --git a/fumadocs/content/reference/sdk-reference/python/index.mdx b/fumadocs/content/reference/sdk-reference/python/index.mdxnew file mode 100644index 000000000..3c19bceaf--- /dev/null+++ b/fumadocs/content/reference/sdk-reference/python/index.mdx@@ -0,0 +1,82 @@+---+title: Python SDK Reference+description: API reference for the Composio Python SDK+---++# Python SDK Reference++Complete API reference for the `composio` Python package.++## Installation++```bash+pip install composio+```++Or with uv:++```bash+uv add composio+```++## Classes++| Class | Description |+|-------|-------------|+| [`Composio`](/reference/sdk-reference/python/composio) | Composio SDK for Python. |+| [`Tools`](/reference/sdk-reference/python/tools) | Tools class definition This class is used to manage tools in the Composio SDK. ... |+| [`Toolkits`](/reference/sdk-reference/python/toolkits) | Toolkits are a collectiono of tools that can be used to perform various tasks. T... |+| [`Triggers`](/reference/sdk-reference/python/triggers) | Triggers (instance) class |+| [`ConnectedAccounts`](/reference/sdk-reference/python/connected-accounts) | Manage connected accounts. This class is used to manage connected accounts in t... |+| [`AuthConfigs`](/reference/sdk-reference/python/auth-configs) | Manage authentication configurations. |++## Quick Start++```python+from composio import Composio++composio = Composio(api_key="your-api-key")++# Get tools for a user+tools = composio.tools.get("user-123", toolkits=["github"])++# Execute a tool+result = composio.tools.execute(+ "GITHUB_GET_REPOS",+ arguments={"owner": "composio"},+ user_id="user-123"+)+```++## Decorators++### before_execute++[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/_modifiers.py#L171)++```python+@before_execute(modifier: BeforeExecute | None = ..., tools: List[str | None] = ..., toolkits: List[str | None] = ...)+def my_modifier(...):+ ...+```++### after_execute++[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/_modifiers.py#L132)++```python+@after_execute(modifier: AfterExecute | None = ..., tools: List[str | None] = ..., toolkits: List[str | None] = ...)+def my_modifier(...):+ ...+```++### schema_modifier++[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/_modifiers.py#L210)++```python+@schema_modifier(modifier: SchemaModifier | None = ..., tools: List[str | None] = ..., toolkits: List[str | None] = ...)+def my_modifier(...):+ ...+```+diff --git a/fumadocs/content/reference/sdk-reference/python/meta.json b/fumadocs/content/reference/sdk-reference/python/meta.jsonnew file mode 100644index 000000000..502bdbc49--- /dev/null+++ b/fumadocs/content/reference/sdk-reference/python/meta.json@@ -0,0 +1,11 @@+{+ "title": "Python SDK",+ "pages": [+ "composio",+ "tools",+ "toolkits",+ "triggers",+ "connected-accounts",+ "auth-configs"+ ]+}\ No newline at end of filediff --git a/fumadocs/content/reference/sdk-reference/python/toolkits.mdx b/fumadocs/content/reference/sdk-reference/python/toolkits.mdxnew file mode 100644index 000000000..ad79a68e9--- /dev/null+++ b/fumadocs/content/reference/sdk-reference/python/toolkits.mdx@@ -0,0 +1,122 @@+---+title: Toolkits+description: "Toolkits are a collectiono of tools that can be used to perform various tasks. They're conceptualized as a set of tools. Ex: Github toolkit can per..."+---++## Methods++### list()++List all toolkits.++```python+def list(category: str | None = ..., cursor: str | None = ..., limit: float | None = ..., sort_by: Literal['usage', 'alphabetically' | None] = ..., managed_by: Literal['composio', 'all', 'project' | None] = ...) -> toolkit_list_response.ToolkitListResponse+```++**Parameters**++| Name | Type |+|------|------|+| `category?` | `str \| None` |+| `cursor?` | `str \| None` |+| `limit?` | `float \| None` |+| `sort_by?` | `Literal['usage', 'alphabetically' \| None]` |+| `managed_by?` | `Literal['composio', 'all', 'project' \| None]` |++**Returns**++`toolkit_list_response.ToolkitListResponse`++---++### get()++```python+def get(slug: str | None = ..., query: toolkit_list_params.ToolkitListParams | None = ...) -> Union[toolkit_retrieve_response.ToolkitRetrieveResponse, ...+```++**Parameters**++| Name | Type |+|------|------|+| `slug?` | `str \| None` |+| `query?` | `toolkit_list_params.ToolkitListParams \| None` |++**Returns**++`Union[toolkit_retrieve_response.ToolkitRetrieveResponse, ...`++---++### list_categories()++List all categories of toolkits.++```python+def list_categories()+```++---++### authorize()++Authorize a user to a toolkit If auth config is not found, it will be created using composio managed auth.++```python+def authorize(user_id: str, toolkit: str)+```++**Parameters**++| Name | Type |+|------|------|+| `user_id` | `str` |+| `toolkit` | `str` |++---++### get_connected_account_initiation_fields()++Get the required property for a given toolkit and auth scheme.++```python+def get_connected_account_initiation_fields(toolkit: str, auth_scheme: AuthSchemeL, required_only: bool = ...) -> AuthFieldsT+```++**Parameters**++| Name | Type |+|------|------|+| `toolkit` | `str` |+| `auth_scheme` | `AuthSchemeL` |+| `required_only?` | `bool` |++**Returns**++`AuthFieldsT`++---++### get_auth_config_creation_fields()++Get the required property for a given toolkit and auth scheme.++```python+def get_auth_config_creation_fields(toolkit: str, auth_scheme: AuthSchemeL, required_only: bool = ...) -> AuthFieldsT+```++**Parameters**++| Name | Type |+|------|------|+| `toolkit` | `str` |+| `auth_scheme` | `AuthSchemeL` |+| `required_only?` | `bool` |++**Returns**++`AuthFieldsT`++---++[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/toolkits.py#L26)diff --git a/fumadocs/content/reference/sdk-reference/python/tools.mdx b/fumadocs/content/reference/sdk-reference/python/tools.mdxnew file mode 100644index 000000000..581e268c8--- /dev/null+++ b/fumadocs/content/reference/sdk-reference/python/tools.mdx@@ -0,0 +1,129 @@+---+title: Tools+description: Tools class definition This class is used to manage tools in the Composio SDK. It provides methods to list, get, and execute tools.+---++## Methods++### get_raw_composio_tool_by_slug()++Returns schema for the given tool slug.++```python+def get_raw_composio_tool_by_slug(slug: str) -> Tool+```++**Parameters**++| Name | Type |+|------|------|+| `slug` | `str` |++**Returns**++`Tool`++---++### get_raw_composio_tools()++Get a list of tool schemas based on the provided filters.++```python+def get_raw_composio_tools(tools: list[str | None] = ..., search: str | None = ..., toolkits: list[str | None] = ..., scopes: List[str | None] = ..., limit: int | None = ...) -> list[Tool]+```++**Parameters**++| Name | Type |+|------|------|+| `tools?` | `list[str \| None]` |+| `search?` | `str \| None` |+| `toolkits?` | `list[str \| None]` |+| `scopes?` | `List[str \| None]` |+| `limit?` | `int \| None` |++**Returns**++`list[Tool]`++---++### get()++Get a tool or list of tools based on the provided arguments.++```python+def get(user_id: str, slug: str | None = ..., tools: list[str | None] = ..., search: str | None = ..., toolkits: list[str | None] = ..., scopes: List[str | None] = ..., modifiers: Modifiers | None = ..., limit: int | None = ...)+```++**Parameters**++| Name | Type |+|------|------|+| `user_id` | `str` |+| `slug?` | `str \| None` |+| `tools?` | `list[str \| None]` |+| `search?` | `str \| None` |+| `toolkits?` | `list[str \| None]` |+| `scopes?` | `List[str \| None]` |+| `modifiers?` | `Modifiers \| None` |+| `limit?` | `int \| None` |++---++### execute()++Execute a tool with the provided parameters. This method calls the Composio API or a custom tool handler to execute the tool and returns the response. It automatically determines whether to use a custom tool or a Composio API tool based on the slug.++```python+def execute(slug: str, arguments: Dict, connected_account_id: str | None = ..., custom_auth_params: tool_execute_params.CustomAuthParams | None = ..., custom_connection_data: tool_execute_params.CustomConnectionData | None = ..., user_id: str | None = ..., text: str | None = ..., version: str | None = ..., dangerously_skip_version_check: bool | None = ..., modifiers: Modifiers | None = ...) -> ToolExecutionResponse+```++**Parameters**++| Name | Type |+|------|------|+| `slug` | `str` |+| `arguments` | `Dict` |+| `connected_account_id?` | `str \| None` |+| `custom_auth_params?` | `tool_execute_params.CustomAuthParams \| None` |+| `custom_connection_data?` | `tool_execute_params.CustomConnectionData \| None` |+| `user_id?` | `str \| None` |+| `text?` | `str \| None` |+| `version?` | `str \| None` |+| `dangerously_skip_version_check?` | `bool \| None` |+| `modifiers?` | `Modifiers \| None` |++**Returns**++`ToolExecutionResponse` — The response from the tool.++---++### proxy()++Proxy a tool call to the Composio API++```python+def proxy(endpoint: str, method: Literal['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD'], body: object | None = ..., connected_account_id: str | None = ..., parameters: List[tool_proxy_params.Parameter | None] = ..., custom_connection_data: tool_proxy_params.CustomConnectionData | None = ...) -> tool_proxy_response.ToolProxyResponse+```++**Parameters**++| Name | Type |+|------|------|+| `endpoint` | `str` |+| `method` | `Literal['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD']` |+| `body?` | `object \| None` |+| `connected_account_id?` | `str \| None` |+| `parameters?` | `List[tool_proxy_params.Parameter \| None]` |+| `custom_connection_data?` | `tool_proxy_params.CustomConnectionData \| None` |++**Returns**++`tool_proxy_response.ToolProxyResponse`++---++[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/tools.py#L48)diff --git a/fumadocs/content/reference/sdk-reference/python/triggers.mdx b/fumadocs/content/reference/sdk-reference/python/triggers.mdxnew file mode 100644index 000000000..dfbd9768a--- /dev/null+++ b/fumadocs/content/reference/sdk-reference/python/triggers.mdx@@ -0,0 +1,154 @@+---+title: Triggers+description: Triggers (instance) class+---++## Methods++### get_type()++Get a trigger type by its slug Uses the global toolkit version provided when initializing composio instance to fetch trigger for specific toolkit version++```python+def get_type(slug: str) -> TriggersTypeRetrieveResponse+```++**Parameters**++| Name | Type |+|------|------|+| `slug` | `str` |++**Returns**++`TriggersTypeRetrieveResponse` — The trigger type++---++### list_active()++List all active triggers++```python+def list_active(trigger_ids: list[str | None] = ..., trigger_names: list[str | None] = ..., auth_config_ids: list[str | None] = ..., connected_account_ids: list[str | None] = ..., show_disabled: bool | None = ..., limit: int | None = ..., page: int | None = ...)+```++**Parameters**++| Name | Type |+|------|------|+| `trigger_ids?` | `list[str \| None]` |+| `trigger_names?` | `list[str \| None]` |+| `auth_config_ids?` | `list[str \| None]` |+| `connected_account_ids?` | `list[str \| None]` |+| `show_disabled?` | `bool \| None` |+| `limit?` | `int \| None` |+| `page?` | `int \| None` |++---++### list()++List all the trigger types.++```python+def list(cursor: str | None = ..., limit: int | None = ..., toolkit_slugs: list[str | None] = ...)+```++**Parameters**++| Name | Type |+|------|------|+| `cursor?` | `str \| None` |+| `limit?` | `int \| None` |+| `toolkit_slugs?` | `list[str \| None]` |++---++### create()++Create a trigger instance++```python+def create(slug: str, user_id: str | None = ..., connected_account_id: str | None = ..., trigger_config: Dict[str, Any | None] = ...) -> trigger_instance_upsert_response.TriggerInstanceUpsertRes...+```++**Parameters**++| Name | Type |+|------|------|+| `slug` | `str` |+| `user_id?` | `str \| None` |+| `connected_account_id?` | `str \| None` |+| `trigger_config?` | `Dict[str, Any \| None]` |++**Returns**++`trigger_instance_upsert_response.TriggerInstanceUpsertRes...` — The trigger instance++---++### subscribe()++Subscribe to a trigger and receive trigger events.++```python+def subscribe(timeout: float = ...) -> TriggerSubscription+```++**Parameters**++| Name | Type |+|------|------|+| `timeout?` | `float` |++**Returns**++`TriggerSubscription` — The trigger subscription handler.++---++### verify_webhook()++Verify an incoming webhook payload and signature. This method validates that the webhook request is authentic by: 1. Verifying the HMAC-SHA256 signature matches the payload 2. Optionally checking that the webhook timestamp is within the tolerance window++```python+def verify_webhook(payload: str, signature: str, secret: str, tolerance: int = ...) -> TriggerEvent+```++**Parameters**++| Name | Type |+|------|------|+| `payload` | `str` |+| `signature` | `str` |+| `secret` | `str` |+| `tolerance?` | `int` |++**Returns**++`TriggerEvent` — The verified and parsed webhook payload as a TriggerEvent :raises WebhookSignatureVerificationError: If the signature verification fails :raises WebhookPayloadError: If the payload cannot be parsed or is invalid++**Example**++```python+# In a Flask webhook handler+ @app.route('/webhook', methods=['POST'])+ def webhook():+ try:+ event = composio.triggers.verify_webhook(+ payload=request.get_data(as_text=True),+ signature=request.headers.get('x-composio-signature', ''),+ secret=os.environ['COMPOSIO_WEBHOOK_SECRET'],+ )++ # Process the verified payload+ print(f"Received trigger: {event['trigger_slug']}")+ return 'OK', 200+ except WebhookSignatureVerificationError:+ return 'Unauthorized', 401+```++---++[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/triggers.py#L629)diff --git a/python/scripts/generate-docs.py b/python/scripts/generate-docs.pynew file mode 100644index 000000000..fd9ccdf01--- /dev/null+++ b/python/scripts/generate-docs.py@@ -0,0 +1,536 @@+#!/usr/bin/env python3+"""+Python SDK Documentation Generator++Generates MDX documentation from Python source code using griffe.+Output is written to the fumadocs content directory.++Run: cd python && uv run --with griffe python scripts/generate-docs.py+"""++from __future__ import annotations++import json+import re+import shutil+from pathlib import Path+from typing import Any++try:+ import griffe+except ImportError:+ print("Error: griffe not installed. Run: pip install griffe")+ raise SystemExit(1)++# Paths+SCRIPT_DIR = Path(__file__).parent+PACKAGE_DIR = SCRIPT_DIR.parent+OUTPUT_DIR = PACKAGE_DIR.parent / "fumadocs" / "content" / "reference" / "sdk-reference" / "python"++# GitHub base URL for source links+GITHUB_BASE = "https://github.com/composiohq/composio/blob/next/python"++# Decorators to document+DECORATORS_TO_DOCUMENT = [+ ("before_execute", "composio.core.models._modifiers"),+ ("after_execute", "composio.core.models._modifiers"),+ ("schema_modifier", "composio.core.models._modifiers"),+]++# Classes to skip (internal/helper classes)+SKIP_CLASSES = {"WithLogger", "SDKConfig", "TProvider"}++# Expected classes to document (maps class name -> property name on Composio)+EXPECTED_CLASSES = {+ "Tools": "tools",+ "Toolkits": "toolkits",+ "Triggers": "triggers",+ "ConnectedAccounts": "connected_accounts",+ "AuthConfigs": "auth_configs",+}++# Modules to search for classes+CLASS_MODULES = [+ "core.models.tools",+ "core.models.toolkits",+ "core.models.triggers",+ "core.models.connected_accounts",+ "core.models.auth_configs",+]+++def to_kebab_case(name: str) -> str:+ """Convert PascalCase to kebab-case."""+ s1 = re.sub("(.)([A-Z][a-z]+)", r"\1-\2", name)+ return re.sub("([a-z0-9])([A-Z])", r"\1-\2", s1).lower()+++def escape_yaml_string(s: str) -> str:+ """Escape a string for YAML frontmatter."""+ if any(c in s for c in [':', '"', "'", '\n', '#', '{', '}']):+ return f'"{s.replace(chr(34), chr(92)+chr(34))}"'+ return s+++def get_source_link(obj: griffe.Object) -> str | None:+ """Get GitHub source link for an object."""+ if not hasattr(obj, "filepath") or not obj.filepath:+ return None+ try:+ rel_path = Path(obj.filepath).relative_to(PACKAGE_DIR)+ except ValueError:+ return None+ line = obj.lineno if hasattr(obj, "lineno") and obj.lineno else 1+ return f"{GITHUB_BASE}/{rel_path}#L{line}"+++def format_type(annotation: Any) -> str:+ """Format a type annotation to readable string."""+ if annotation is None:+ return "Any"++ type_str = str(annotation)+ # Clean up common prefixes+ type_str = type_str.replace("typing.", "").replace("typing_extensions.", "")+ type_str = type_str.replace("composio.client.types.", "")+ type_str = re.sub(r'\bt\.', '', type_str)+ type_str = re.sub(r'\bte\.', '', type_str) # typing_extensions alias+ type_str = re.sub(r'Optional\[([^\]]+)\]', r'\1 | None', type_str)+ # Clean up Unpack to just show the type+ type_str = re.sub(r'Unpack\[([^\]]+)\]', r'\1', type_str)++ # Truncate very long types+ if len(type_str) > 60:+ return type_str[:57] + "..."+ return type_str+++def parse_docstring(docstring: str | None) -> dict[str, Any]:+ """Parse docstring into components."""+ if not docstring:+ return {"description": "", "params": {}, "returns": None, "examples": []}++ lines = docstring.strip().split("\n")+ description_lines = []+ params: dict[str, str] = {}+ returns = None+ examples: list[str] = []++ section = "description"+ current_param = None+ example_lines: list[str] = []++ for line in lines:+ stripped = line.strip()++ # Check for :param name: description+ param_match = re.match(r":param\s+(\w+):\s*(.*)", stripped)+ if param_match:+ section = "params"+ current_param = param_match.group(1)+ params[current_param] = param_match.group(2)+ continue++ # Check for :returns: or :return:+ return_match = re.match(r":returns?:\s*(.*)", stripped)+ if return_match:+ section = "returns"+ returns = return_match.group(1)+ continue++ # Check for Example section+ if stripped.lower().startswith("example"):+ section = "examples"+ continue++ # Add to appropriate section+ if section == "description":+ description_lines.append(stripped)+ elif section == "params" and current_param and stripped:+ params[current_param] += " " + stripped+ elif section == "returns" and returns and stripped:+ returns += " " + stripped+ elif section == "examples":+ example_lines.append(line)++ if example_lines:+ examples.append("\n".join(example_lines).strip())++ return {+ "description": " ".join(description_lines).strip(),+ "params": params,+ "returns": returns,+ "examples": examples,+ }+++def extract_class_info(cls: griffe.Class, class_name: str, config: dict) -> dict[str, Any]:+ """Extract documentation from a class."""+ doc = parse_docstring(cls.docstring.value if cls.docstring else None)++ info = {+ "name": class_name,+ "access": config.get("access"),+ "source_link": get_source_link(cls),+ "description": doc["description"],+ "properties": [],+ "methods": [],+ }++ # Extract properties/attributes+ for name, member in cls.members.items():+ if name.startswith("_"):+ continue+ if isinstance(member, griffe.Attribute):+ attr_doc = member.docstring.value if member.docstring else ""+ info["properties"].append({+ "name": name,+ "type": format_type(member.annotation),+ "description": attr_doc.strip() if attr_doc else "",+ })++ # Extract methods+ for name, member in cls.members.items():+ if name.startswith("_"):+ continue+ if isinstance(member, griffe.Function):+ method_doc = parse_docstring(member.docstring.value if member.docstring else None)++ params = []+ for p in member.parameters:+ if p.name in ("self", "cls"):+ continue+ params.append({+ "name": p.name,+ "type": format_type(p.annotation),+ "optional": p.default is not None,+ "description": method_doc["params"].get(p.name, ""),+ })++ info["methods"].append({+ "name": name,+ "source_link": get_source_link(member),+ "description": method_doc["description"],+ "parameters": params,+ "return_type": format_type(member.returns),+ "return_description": method_doc["returns"],+ "examples": method_doc["examples"],+ })++ return info+++def generate_class_mdx(info: dict[str, Any], prop_to_class: dict[str, str] = None) -> str:+ """Generate MDX for a class."""+ lines = []++ # Frontmatter+ desc = info["description"].split("\n")[0] if info["description"] else f"{info['name']} class"+ if len(desc) > 150:+ desc = desc[:147] + "..."++ lines.append("---")+ lines.append(f"title: {info['name']}")+ lines.append(f"description: {escape_yaml_string(desc)}")+ lines.append("---")+ lines.append("")++ source_link = info.get("source_link", "")++ # Properties - as table for Composio class+ if prop_to_class:+ prop_rows = []+ for prop in info["properties"]:+ prop_name = prop["name"]+ if prop_name in prop_to_class:+ class_name = prop_to_class[prop_name]+ link = f"/reference/sdk-reference/python/{to_kebab_case(class_name)}"+ prop_rows.append(f"| [`{prop_name}`]({link}) | `{class_name}` |")++ if prop_rows:+ lines.append("## Properties")+ lines.append("")+ lines.append("| Name | Type |")+ lines.append("|------|------|")+ lines.extend(prop_rows)+ lines.append("")++ # Methods+ if info["methods"]:+ lines.append("## Methods")+ lines.append("")++ for method in info["methods"]:+ lines.append(f"### {method['name']}()")+ lines.append("")++ if method["description"]:+ lines.append(method["description"])+ lines.append("")++ # Signature+ params_str = ", ".join(+ f"{p['name']}: {p['type']}" + (" = ..." if p["optional"] else "")+ for p in method["parameters"]+ )+ ret_type = method["return_type"] if method["return_type"] != "Any" else ""+ sig = f"def {method['name']}({params_str})"+ if ret_type:+ sig += f" -> {ret_type}"++ lines.append("```python")+ lines.append(sig)+ lines.append("```")+ lines.append("")++ # Parameters+ if method["parameters"]:+ lines.append("**Parameters**")+ lines.append("")+ lines.append("| Name | Type |")+ lines.append("|------|------|")+ for p in method["parameters"]:+ opt = "?" if p["optional"] else ""+ safe_type = p["type"].replace("|", "\\|")+ lines.append(f"| `{p['name']}{opt}` | `{safe_type}` |")+ lines.append("")++ # Returns+ if method["return_type"] and method["return_type"] not in ("None", "Any"):+ ret_desc = method["return_description"] or ""+ lines.append("**Returns**")+ lines.append("")+ if ret_desc:+ lines.append(f"`{method['return_type']}` — {ret_desc}")+ else:+ lines.append(f"`{method['return_type']}`")+ lines.append("")++ # Examples+ if method["examples"]:+ lines.append("**Example**")+ lines.append("")+ for ex in method["examples"]:+ lines.append("```python")+ lines.append(ex)+ lines.append("```")+ lines.append("")++ lines.append("---")+ lines.append("")++ # Source link at bottom+ if source_link:+ lines.append(f"[View source]({source_link})")+ lines.append("")++ return "\n".join(lines)+++def generate_index_mdx(classes: list[dict], decorators: list[dict]) -> str:+ """Generate index page."""++ # Classes table+ class_rows = []+ for c in classes:+ link = f"/reference/sdk-reference/python/{to_kebab_case(c['name'])}"+ desc = c["description"][:80] + "..." if len(c["description"]) > 80 else c["description"]+ class_rows.append(f"| [`{c['name']}`]({link}) | {desc} |")++ # Decorators section+ dec_section = ""+ if decorators:+ dec_lines = ["## Decorators", ""]+ for d in decorators:+ dec_lines.append(f"### {d['name']}")+ dec_lines.append("")+ if d["description"]:+ dec_lines.append(d["description"])+ dec_lines.append("")+ if d["source_link"]:+ dec_lines.append(f"[View source]({d['source_link']})")+ dec_lines.append("")+ # Signature+ params = ", ".join(+ f"{p['name']}: {p['type']}" + (" = ..." if p["optional"] else "")+ for p in d["parameters"]+ )+ dec_lines.append("```python")+ dec_lines.append(f"@{d['name']}({params})")+ dec_lines.append("def my_modifier(...):")+ dec_lines.append(" ...")+ dec_lines.append("```")+ dec_lines.append("")+ dec_section = "\n".join(dec_lines)++ return f'''---+title: Python SDK Reference+description: API reference for the Composio Python SDK+---++# Python SDK Reference++Complete API reference for the `composio` Python package.++## Installation++```bash+pip install composio+```++Or with uv:++```bash+uv add composio+```++## Classes++| Class | Description |+|-------|-------------|+{chr(10).join(class_rows)}++## Quick Start++```python+from composio import Composio++composio = Composio(api_key="your-api-key")++# Get tools for a user+tools = composio.tools.get("user-123", toolkits=["github"])++# Execute a tool+result = composio.tools.execute(+ "GITHUB_GET_REPOS",+ arguments={{"owner": "composio"}},+ user_id="user-123"+)+```++{dec_section}+'''+++def main():+ print("Starting Python SDK documentation generation...\n")+ print(f"Output: {OUTPUT_DIR}\n")++ # Clean output+ if OUTPUT_DIR.exists():+ shutil.rmtree(OUTPUT_DIR)+ OUTPUT_DIR.mkdir(parents=True)++ # Load package+ print("Loading composio package...")+ try:+ package = griffe.load("composio", search_paths=[str(PACKAGE_DIR)])+ except Exception as e:+ print(f"Error: {e}")+ raise SystemExit(1)++ # Find Composio class+ composio_cls = package.members["sdk"].members["Composio"]+ print(" Found Composio class")++ # Discover classes from EXPECTED_CLASSES+ classes_to_doc = {"Composio": {"cls": composio_cls, "access": None, "prop": None}}+ prop_to_class = {} # Maps property name -> class name++ for module_name in CLASS_MODULES:+ try:+ parts = module_name.split(".")+ current = package+ for part in parts:+ current = current.members[part]++ # Find expected classes in this module+ for class_name, prop_name in EXPECTED_CLASSES.items():+ if class_name in current.members:+ cls = current.members[class_name]+ if isinstance(cls, griffe.Class):+ classes_to_doc[class_name] = {+ "cls": cls,+ "access": f"composio.{prop_name}",+ "prop": prop_name,+ }+ prop_to_class[prop_name] = class_name+ print(f" Found {class_name} (via composio.{prop_name})")+ except (KeyError, AttributeError):+ continue++ # Generate docs for each class+ documented_classes = []++ for class_name, config in classes_to_doc.items():+ cls = config["cls"]+ print(f" Processing {class_name}...")++ info = extract_class_info(cls, class_name, {"access": config["access"]})++ # Only Composio gets prop_to_class for linking+ if class_name == "Composio":+ mdx = generate_class_mdx(info, prop_to_class)+ else:+ mdx = generate_class_mdx(info, None)++ file_path = OUTPUT_DIR / f"{to_kebab_case(class_name)}.mdx"+ file_path.write_text(mdx)++ documented_classes.append({+ "name": class_name,+ "description": info["description"] or f"{class_name} class",+ })++ # Process decorators+ decorators = []+ for dec_name, dec_module in DECORATORS_TO_DOCUMENT:+ module_path = dec_module.split(".")+ current = package++ for part in module_path[1:]:+ if part in current.members:+ current = current.members[part]++ if dec_name in current.members:+ func = current.members[dec_name]+ if isinstance(func, griffe.Function):+ print(f" Processing decorator {dec_name}...")+ doc = parse_docstring(func.docstring.value if func.docstring else None)++ params = []+ for p in func.parameters:+ if p.name in ("self", "cls"):+ continue+ params.append({+ "name": p.name,+ "type": format_type(p.annotation),+ "optional": p.default is not None,+ "description": doc["params"].get(p.name, ""),+ })++ decorators.append({+ "name": dec_name,+ "source_link": get_source_link(func),+ "description": doc["description"],+ "parameters": params,+ })++ # Generate index+ index_content = generate_index_mdx(documented_classes, decorators)+ (OUTPUT_DIR / "index.mdx").write_text(index_content)++ # Generate meta.json+ meta = {+ "title": "Python SDK",+ "pages": [to_kebab_case(c["name"]) for c in documented_classes],+ }+ (OUTPUT_DIR / "meta.json").write_text(json.dumps(meta, indent=2))++ print(f"\nDone! Generated {len(documented_classes)} class docs + index")+ print(f" Classes: {', '.join(c['name'] for c in documented_classes)}")+ print(f" Decorators: {', '.join(d['name'] for d in decorators)}")+++if __name__ == "__main__":+ main()