Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(py): normalize generated SDK doc examples (#3689)

Alberto Schiabele7bb45f44966
diff --git a/docs/content/reference/sdk-reference/python/connected-accounts.mdx b/docs/content/reference/sdk-reference/python/connected-accounts.mdx
index c57dac703..49f79f6fb 100644
--- a/docs/content/reference/sdk-reference/python/connected-accounts.mdx
+++ b/docs/content/reference/sdk-reference/python/connected-accounts.mdx
@@ -29,10 +29,10 @@ def update(nanoid: str, alias: str | None = ..., connection: connected_account_p
```python
# Set an alias
- composio.connected_accounts.update('ca_abc123', alias='work-gmail')
+composio.connected_accounts.update('ca_abc123', alias='work-gmail')
- # Clear an alias
- composio.connected_accounts.update('ca_abc123', alias='')
+# Clear an alias
+composio.connected_accounts.update('ca_abc123', alias='')
```
---
@@ -62,10 +62,10 @@ def update_acl(nanoid: str, allow_all_users: bool | None = ..., allowed_user_ids
```python
composio.connected_accounts.update_acl(
- 'ca_abc',
- allow_all_users=True,
- not_allowed_user_ids=['user_bob'],
- )
+ 'ca_abc',
+ allow_all_users=True,
+ not_allowed_user_ids=['user_bob'],
+)
```
---
@@ -122,36 +122,36 @@ def link(user_id: str, auth_config_id: str, callback_url: str | None = ..., alia
```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)
-
- connection_request = composio.connected_accounts.link(
- 'user_creator',
- 'auth_config_123',
- experimental={
- 'account_type': 'SHARED',
- 'acl_config_for_shared': {
- 'allow_all_users': True,
- 'not_allowed_user_ids': ['user_bob'],
- },
+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)
+
+connection_request = composio.connected_accounts.link(
+ 'user_creator',
+ 'auth_config_123',
+ experimental={
+ 'account_type': 'SHARED',
+ 'acl_config_for_shared': {
+ 'allow_all_users': True,
+ 'not_allowed_user_ids': ['user_bob'],
},
- )
+ },
+)
```
---
diff --git a/docs/content/reference/sdk-reference/python/mcp.mdx b/docs/content/reference/sdk-reference/python/mcp.mdx
index 3a5970578..000782530 100644
--- a/docs/content/reference/sdk-reference/python/mcp.mdx
+++ b/docs/content/reference/sdk-reference/python/mcp.mdx
@@ -4,7 +4,7 @@ description: "MCP (Model Control Protocol) class. Provides enhanced MCP server o
---
<Callout type="warn" title="Deprecated">
-Use a session's MCP endpoint instead: `composio.create(user_id, mcp=True)` returns a session that exposes `session.mcp.url` / `session.mcp.headers`. The standalone `composio.mcp` server-management API is kept for backwards compatibility. See https://docs.composio.dev/docs/sessions-via-mcp
+Use a session's MCP endpoint instead: `composio.create(user_id, mcp=True)` returns a session that exposes `session.mcp.url` / `session.mcp.headers`. MCP is now opt-in per session; this standalone `composio.mcp` server-management API is kept only for backwards compatibility. Prefer the session MCP endpoint; do not generate new code against `composio.mcp`. See https://docs.composio.dev/docs/sessions-via-mcp
</Callout>
## Methods
@@ -34,38 +34,38 @@ def create(name: str, toolkits: List[Union[ConfigToolkit, str]], manually_manage
```python
>>> # Using toolkit configuration objects with auth
- >>> server = composio.experimental.mcp.create(
- ... 'personal-mcp-server',
- ... toolkits=[
- ... {
- ... 'toolkit': 'github',
- ... 'auth_config_id': 'ac_xyz',
- ... },
- ... {
- ... 'toolkit': 'slack',
- ... 'auth_config_id': 'ac_abc',
- ... },
- ... ],
- ... allowed_tools=['GITHUB_CREATE_ISSUE', 'GITHUB_LIST_REPOS', 'SLACK_SEND_MESSAGE'],
- ... manually_manage_connections=False
- ... )
- >>>
- >>> # Using simple toolkit names (most common usage)
- >>> server = composio.experimental.mcp.create(
- ... 'simple-mcp-server',
- ... toolkits=['composio_search', 'text_to_pdf'],
- ... allowed_tools=['COMPOSIO_SEARCH_DUCK_DUCK_GO_SEARCH', 'TEXT_TO_PDF_CONVERT_TEXT_TO_PDF']
- ... )
- >>>
- >>> # Using all tools from toolkits (default behavior)
- >>> server = composio.experimental.mcp.create(
- ... 'all-tools-server',
- ... toolkits=['composio_search', 'text_to_pdf']
- ... # allowed_tools=None means all tools from these toolkits
- ... )
- >>>
- >>> # Get server instance for a user
- >>> mcp = server.generate('user_12345')
+>>> server = composio.experimental.mcp.create(
+... 'personal-mcp-server',
+... toolkits=[
+... {
+... 'toolkit': 'github',
+... 'auth_config_id': 'ac_xyz',
+... },
+... {
+... 'toolkit': 'slack',
+... 'auth_config_id': 'ac_abc',
+... },
+... ],
+... allowed_tools=['GITHUB_CREATE_ISSUE', 'GITHUB_LIST_REPOS', 'SLACK_SEND_MESSAGE'],
+... manually_manage_connections=False
+... )
+>>>
+>>> # Using simple toolkit names (most common usage)
+>>> server = composio.experimental.mcp.create(
+... 'simple-mcp-server',
+... toolkits=['composio_search', 'text_to_pdf'],
+... allowed_tools=['COMPOSIO_SEARCH_DUCK_DUCK_GO_SEARCH', 'TEXT_TO_PDF_CONVERT_TEXT_TO_PDF']
+... )
+>>>
+>>> # Using all tools from toolkits (default behavior)
+>>> server = composio.experimental.mcp.create(
+... 'all-tools-server',
+... toolkits=['composio_search', 'text_to_pdf']
+... # allowed_tools=None means all tools from these toolkits
+... )
+>>>
+>>> # Get server instance for a user
+>>> mcp = server.generate('user_12345')
```
---
@@ -98,13 +98,13 @@ def list(page_no: int | None = ..., limit: int | None = ..., toolkits: str | Non
```python
>>> # List all servers
- >>> all_servers = composio.experimental.mcp.list()
- >>>
- >>> # List with pagination
- >>> paged_servers = composio.experimental.mcp.list(page_no=2, limit=5)
- >>>
- >>> # Filter by toolkit
- >>> github_servers = composio.experimental.mcp.list(toolkits='github', name='personal')
+>>> all_servers = composio.experimental.mcp.list()
+>>>
+>>> # List with pagination
+>>> paged_servers = composio.experimental.mcp.list(page_no=2, limit=5)
+>>>
+>>> # Filter by toolkit
+>>> github_servers = composio.experimental.mcp.list(toolkits='github', name='personal')
```
---
@@ -127,11 +127,11 @@ def get(server_id: str)
```python
>>> server = composio.experimental.mcp.get('mcp_12345')
- >>>
- >>> print(server['name']) # "My Personal MCP Server"
- >>> print(server['allowed_tools']) # ["GITHUB_CREATE_ISSUE", "SLACK_SEND_MESSAGE"]
- >>> print(server['toolkits']) # ["github", "slack"]
- >>> print(server['server_instance_count']) # 3
+>>>
+>>> print(server['name']) # "My Personal MCP Server"
+>>> print(server['allowed_tools']) # ["GITHUB_CREATE_ISSUE", "SLACK_SEND_MESSAGE"]
+>>> print(server['toolkits']) # ["github", "slack"]
+>>> print(server['server_instance_count']) # 3
```
---
@@ -158,28 +158,28 @@ def update(server_id: str, name: str | None = ..., toolkits: List[Union[ConfigTo
```python
>>> # Update server name only
- >>> updated_server = composio.experimental.mcp.update(
- ... 'mcp_12345',
- ... name='My Updated MCP Server'
- ... )
- >>>
- >>> # Update toolkits and tools
- >>> server_with_new_tools = composio.experimental.mcp.update(
- ... 'mcp_12345',
- ... toolkits=['github', 'slack'],
- ... allowed_tools=['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE']
- ... )
- >>>
- >>> # Update with auth configs
- >>> server_with_auth = composio.experimental.mcp.update(
- ... 'mcp_12345',
- ... toolkits=[
- ... {'toolkit': 'github', 'auth_config_id': 'auth_abc123'},
- ... {'toolkit': 'slack', 'auth_config_id': 'auth_def456'}
- ... ],
- ... allowed_tools=['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE'],
- ... manually_manage_connections=False
- ... )
+>>> updated_server = composio.experimental.mcp.update(
+... 'mcp_12345',
+... name='My Updated MCP Server'
+... )
+>>>
+>>> # Update toolkits and tools
+>>> server_with_new_tools = composio.experimental.mcp.update(
+... 'mcp_12345',
+... toolkits=['github', 'slack'],
+... allowed_tools=['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE']
+... )
+>>>
+>>> # Update with auth configs
+>>> server_with_auth = composio.experimental.mcp.update(
+... 'mcp_12345',
+... toolkits=[
+... {'toolkit': 'github', 'auth_config_id': 'auth_abc123'},
+... {'toolkit': 'slack', 'auth_config_id': 'auth_def456'}
+... ],
+... allowed_tools=['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE'],
+... manually_manage_connections=False
+... )
```
---
@@ -206,12 +206,12 @@ def delete(server_id: str) -> Dict[str, Any]
```python
>>> # Delete a server
- >>> result = composio.experimental.mcp.delete('mcp_12345')
- >>>
- >>> if result['deleted']:
- ... print(f"Server {result['id']} has been successfully deleted")
- >>> else:
- ... print(f"Failed to delete server {result['id']}")
+>>> result = composio.experimental.mcp.delete('mcp_12345')
+>>>
+>>> if result['deleted']:
+... print(f"Server {result['id']} has been successfully deleted")
+>>> else:
+... print(f"Failed to delete server {result['id']}")
```
---
@@ -240,13 +240,13 @@ def generate(user_id: str, mcp_config_id: str, manually_manage_connections: bool
```python
>>> mcp = composio.experimental.mcp.generate(
- ... 'user_12345',
- ... 'mcp_67890',
- ... manually_manage_connections=False
- ... )
- >>>
- >>> print(mcp['url']) # Server URL for the user
- >>> print(mcp['allowed_tools']) # Available tools
+... 'user_12345',
+... 'mcp_67890',
+... manually_manage_connections=False
+... )
+>>>
+>>> print(mcp['url']) # Server URL for the user
+>>> print(mcp['allowed_tools']) # Available tools
```
---
diff --git a/docs/content/reference/sdk-reference/python/session.mdx b/docs/content/reference/sdk-reference/python/session.mdx
index 93adcc6d1..84b697115 100644
--- a/docs/content/reference/sdk-reference/python/session.mdx
+++ b/docs/content/reference/sdk-reference/python/session.mdx
@@ -183,10 +183,10 @@ def proxy_execute(toolkit: str, endpoint: str, method: Literal['GET', 'POST', 'P
### update()
-Partially update the session configuration. Only the fields provided will be changed; omitted fields are preserved. Mutates this session's ``preload`` in-place. Pass ``None`` for ``manage_connections``, ``workbench``, or ``multi_account`` to clear the stored value. All parameters use the same types as the Stainless-generated ``client.tool_router.session.patch()`` method.
+Partially update the session configuration. Only the fields provided will be changed; omitted fields are preserved. Mutates this session's ``preload`` in-place. Pass ``None`` for ``manage_connections``, ``sandbox``/``workbench``, or ``multi_account`` to clear the stored value. ``workbench`` is a backwards-compatible alias for ``sandbox``. Prefer ``sandbox`` in new code. All parameters use the same types as the Stainless-generated ``client.tool_router.session.patch()`` method.
```python
-def update(toolkits: Union[session_patch_params.Toolkits, 'Omit'] = ..., tools: Union[Dict[str, session_patch_params.Tools], 'Omit'] = ..., tags: Union[session_patch_params.Tags, 'Omit'] = ..., auth_configs: Union[Dict[str, str], 'Omit'] = ..., connected_accounts: Union[Dict[str, SequenceNotStr[str | None]], 'Omit'] = ..., manage_connections: Union[session_patch_params.ManageConnections | None, 'Omit'] = ..., workbench: Union[session_patch_params.Workbench | None, 'Omit'] = ..., multi_account: Union[session_patch_params.MultiAccount | None, 'Omit'] = ..., preload: Union[session_patch_params.Preload, 'Omit'] = ...) -> None
+def update(toolkits: Union[session_patch_params.Toolkits, 'Omit'] = ..., tools: Union[Dict[str, session_patch_params.Tools], 'Omit'] = ..., tags: Union[session_patch_params.Tags, 'Omit'] = ..., auth_configs: Union[Dict[str, str], 'Omit'] = ..., connected_accounts: Union[Dict[str, SequenceNotStr[str | None]], 'Omit'] = ..., manage_connections: Union[session_patch_params.ManageConnections | None, 'Omit'] = ..., sandbox: Union[session_patch_params.Workbench | None, 'Omit'] = ..., workbench: Union[session_patch_params.Workbench | None, 'Omit'] = ..., multi_account: Union[session_patch_params.MultiAccount | None, 'Omit'] = ..., preload: Union[session_patch_params.Preload, 'Omit'] = ...) -> None
```
**Parameters**
@@ -199,6 +199,7 @@ def update(toolkits: Union[session_patch_params.Toolkits, 'Omit'] = ..., tools:
| `auth_configs?` | `Union[Dict[str, str], 'Omit']` |
| `connected_accounts?` | `Union[Dict[str, SequenceNotStr[str \| None]], 'Omit']` |
| `manage_connections?` | `Union[session_patch_params.ManageConnections \| None, 'Omit']` |
+| `sandbox?` | `Union[session_patch_params.Workbench \| None, 'Omit']` |
| `workbench?` | `Union[session_patch_params.Workbench \| None, 'Omit']` |
| `multi_account?` | `Union[session_patch_params.MultiAccount \| None, 'Omit']` |
| `preload?` | `Union[session_patch_params.Preload, 'Omit']` |
diff --git a/docs/content/reference/sdk-reference/python/tools.mdx b/docs/content/reference/sdk-reference/python/tools.mdx
index 5cd8a436b..b9d31279b 100644
--- a/docs/content/reference/sdk-reference/python/tools.mdx
+++ b/docs/content/reference/sdk-reference/python/tools.mdx
@@ -71,30 +71,28 @@ def get_raw_tool_router_meta_tools(session_id: str, modifiers: 'Modifiers' | Non
**Example**
```python
-```python
- from composio import Composio
+from composio import Composio
- composio = Composio()
- tools_model = composio.tools
+composio = Composio()
+tools_model = composio.tools
- # Get meta tools for a session
- meta_tools = tools_model.get_raw_tool_router_meta_tools("session_123")
- print(meta_tools)
+# Get meta tools for a session
+meta_tools = tools_model.get_raw_tool_router_meta_tools("session_123")
+print(meta_tools)
- # Get meta tools with schema modifiers
- from composio.core.models import schema_modifier
+# Get meta tools with schema modifiers
+from composio.core.models import schema_modifier
- @schema_modifier
- def modify_schema(tool: str, toolkit: str, schema):
- # Customize the schema
- schema.description = f"Modified: {schema.description}"
- return schema
+@schema_modifier
+def modify_schema(tool: str, toolkit: str, schema):
+ # Customize the schema
+ schema.description = f"Modified: {schema.description}"
+ return schema
- meta_tools = tools_model.get_raw_tool_router_meta_tools(
- "session_123",
- modifiers=[modify_schema]
- )
- ```
+meta_tools = tools_model.get_raw_tool_router_meta_tools(
+ "session_123",
+ modifiers=[modify_schema]
+)
```
---
diff --git a/docs/content/reference/sdk-reference/python/triggers.mdx b/docs/content/reference/sdk-reference/python/triggers.mdx
index 583ef0ec7..a3cfe6302 100644
--- a/docs/content/reference/sdk-reference/python/triggers.mdx
+++ b/docs/content/reference/sdk-reference/python/triggers.mdx
@@ -29,8 +29,8 @@ def set_webhook_subscription(webhook_url: str, enabled_events: Sequence[str | No
```python
composio.triggers.set_webhook_subscription(
- webhook_url=f"{APP_URL}/webhooks/composio",
- )
+ webhook_url=f"{APP_URL}/webhooks/composio",
+)
```
---
@@ -165,23 +165,72 @@ def verify_webhook(id: str, payload: str, secret: str, signature: str, timestamp
```python
# In a Flask webhook handler
- @app.route('/webhook', methods=['POST'])
- def webhook():
- try:
- result = composio.triggers.verify_webhook(
- id=request.headers.get('webhook-id', ''),
- payload=request.get_data(as_text=True),
- signature=request.headers.get('webhook-signature', ''),
- timestamp=request.headers.get('webhook-timestamp', ''),
- secret=os.environ['COMPOSIO_WEBHOOK_SECRET'],
- )
-
- # Process the verified payload
- print(f"Version: {result['version']}")
- print(f"Received trigger: {result['payload']['trigger_slug']}")
- return 'OK', 200
- except WebhookSignatureVerificationError:
- return 'Unauthorized', 401
[email protected]('/webhook', methods=['POST'])
+def webhook():
+ try:
+ result = composio.triggers.verify_webhook(
+ id=request.headers.get('webhook-id', ''),
+ payload=request.get_data(as_text=True),
+ signature=request.headers.get('webhook-signature', ''),
+ timestamp=request.headers.get('webhook-timestamp', ''),
+ secret=os.environ['COMPOSIO_WEBHOOK_SECRET'],
+ )
+
+ # Process the verified payload
+ print(f"Version: {result['version']}")
+ print(f"Received trigger: {result['payload']['trigger_slug']}")
+ return 'OK', 200
+ except WebhookSignatureVerificationError:
+ return 'Unauthorized', 401
+```
+
+---
+
+### parse()
+
+Parse an incoming webhook request into a typed, normalized trigger payload. Pass a framework request object, or pass ``body=`` and ``headers=`` explicitly. When ``verify_secret`` is provided, the SDK verifies the webhook signature before returning the normalized trigger payload. When it is omitted, the SDK parses the body without verifying the signature. ``request`` may be any object exposing the request body and headers, such as a Flask, Django, or FastAPI request. The body is read from ``.body`` (or ``.data`` / ``.get_data()``), and the headers are read from ``.headers``. Because this SDK is synchronous, async frameworks must pass an already-read raw body, for example via ``body=await request.body()``.
+
+```python
+def parse(request: Any = ..., body: Union[str, bytes, Mapping[str, Any], None] = ..., headers: Union[Mapping[str, Any], None] = ..., verify_secret: Union[str, None, Omit] = ..., tolerance: int = ...) -> VerifyWebhookResult
+```
+
+**Parameters**
+
+| Name | Type |
+|------|------|
+| `request?` | `Any` |
+| `body?` | `Union[str, bytes, Mapping[str, Any], None]` |
+| `headers?` | `Union[Mapping[str, Any], None]` |
+| `verify_secret?` | `Union[str, None, Omit]` |
+| `tolerance?` | `int` |
+
+**Returns**
+
+`VerifyWebhookResult` — VerifyWebhookResult containing version, normalized payload, and raw payload :raises ValidationError: If ``verify_secret`` is empty, or is set but signature headers are missing :raises WebhookSignatureVerificationError: If signature verification fails :raises WebhookPayloadError: If the payload cannot be parsed
+
+**Example**
+
+```python
+# Flask: verify the signature
[email protected]('/webhooks/composio', methods=['POST'])
+def webhook():
+ try:
+ result = composio.triggers.parse(
+ request,
+ verify_secret=os.environ['COMPOSIO_WEBHOOK_SECRET'],
+ )
+ print(f"Trigger: {result['payload']['trigger_slug']}")
+ print(f"Event data: {result['payload']['payload']}")
+ return 'OK', 200
+ except exceptions.WebhookSignatureVerificationError:
+ return 'Unauthorized', 401
+
+# FastAPI: parse without verifying after reading the async body
[email protected]('/webhooks/composio')
+async def webhook(request: Request):
+ raw = await request.body()
+ result = composio.triggers.parse(body=raw, headers=request.headers)
+ return {'trigger': result['payload']['trigger_slug']}
```
---
diff --git a/python/composio/core/models/triggers.py b/python/composio/core/models/triggers.py
index 481c4f0eb..997bc0505 100644
--- a/python/composio/core/models/triggers.py
+++ b/python/composio/core/models/triggers.py
@@ -1270,21 +1270,16 @@ class Triggers(Resource):
"""
Parse an incoming webhook request into a typed, normalized trigger payload.
- Dump the incoming request in and get back the parsed Composio trigger
- event. When ``verify_secret`` is provided, the request signature is
- verified before the payload is returned (delegating to
- :meth:`verify_webhook`); without it, the body is parsed without
- verification.
+ Pass a framework request object, or pass ``body=`` and ``headers=``
+ explicitly. When ``verify_secret`` is provided, the SDK verifies the
+ webhook signature before returning the normalized trigger payload. When
+ it is omitted, the SDK parses the body without verifying the signature.
``request`` may be any object exposing the request body and headers, such
- as a Flask/Django/FastAPI request. The body is read from ``.body`` (or
- ``.data`` / ``.get_data()``) and the headers from ``.headers``. Because
- this SDK is synchronous, the caller must pass an already-read raw body for
- async frameworks (e.g. FastAPI ``await request.body()``) — either via the
- ``body`` keyword or by reading it first.
-
- Alternatively, pass ``body=`` and ``headers=`` explicitly instead of a
- ``request`` object.
+ as a Flask, Django, or FastAPI request. The body is read from ``.body``
+ (or ``.data`` / ``.get_data()``), and the headers are read from
+ ``.headers``. Because this SDK is synchronous, async frameworks must pass
+ an already-read raw body, for example via ``body=await request.body()``.
:param request: The incoming webhook request object (Flask/Django/FastAPI)
:param body: The raw request body (str/bytes/parsed mapping); overrides ``request``
@@ -1300,7 +1295,7 @@ class Triggers(Resource):
:raises WebhookPayloadError: If the payload cannot be parsed
Example:
- # Flask — verify the signature
+ # Flask: verify the signature
@app.route('/webhooks/composio', methods=['POST'])
def webhook():
try:
@@ -1314,7 +1309,7 @@ class Triggers(Resource):
except exceptions.WebhookSignatureVerificationError:
return 'Unauthorized', 401
- # FastAPI — parse without verifying (read the async body first)
+ # FastAPI: parse without verifying after reading the async body
@app.post('/webhooks/composio')
async def webhook(request: Request):
raw = await request.body()
diff --git a/python/scripts/generate-docs.py b/python/scripts/generate-docs.py
index e68317cca..c3fc9a909 100644
--- a/python/scripts/generate-docs.py
+++ b/python/scripts/generate-docs.py
@@ -13,14 +13,30 @@ from __future__ import annotations
import json
import re
import shutil
+import textwrap
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)
+import typing as t
+
+if t.TYPE_CHECKING:
+ import griffe as griffe_t
+
+_griffe: Any | None = None
+
+
+def load_griffe() -> Any:
+ """Load griffe lazily so parser helpers can be unit-tested without it."""
+ global _griffe
+ if _griffe is None:
+ try:
+ import griffe as griffe_module
+ except ImportError:
+ print("Error: griffe not installed. Run: pip install griffe")
+ raise SystemExit(1)
+ _griffe = griffe_module
+ return _griffe
+
# Paths
SCRIPT_DIR = Path(__file__).parent
@@ -107,7 +123,7 @@ def escape_yaml_string(s: str) -> str:
return json.dumps(s)
-def get_source_link(obj: griffe.Object) -> str | None:
+def get_source_link(obj: griffe_t.Object) -> str | None:
"""Get GitHub source link for an object."""
if not hasattr(obj, "filepath") or not obj.filepath:
return None
@@ -214,7 +230,7 @@ def parse_docstring(docstring: str | None) -> dict[str, Any]:
deprecated_lines.append(stripped)
if example_lines:
- examples.append("\n".join(example_lines).strip())
+ examples.append(normalize_example("\n".join(example_lines)))
return {
"description": " ".join(description_lines).strip(),
@@ -225,10 +241,24 @@ def parse_docstring(docstring: str | None) -> dict[str, Any]:
}
+def normalize_example(example: str) -> str:
+ """Normalize a docstring example before wrapping it in an MDX code fence."""
+ normalized = textwrap.dedent(example).strip()
+ lines = normalized.splitlines()
+
+ if len(lines) >= 2 and lines[0].strip().startswith("```"):
+ closing_index = len(lines) - 1
+ if lines[closing_index].strip() == "```":
+ normalized = "\n".join(lines[1:closing_index]).strip()
+
+ return normalized
+
+
def extract_class_info(
- cls: griffe.Class, class_name: str, config: dict
+ cls: griffe_t.Class, class_name: str, config: dict
) -> dict[str, Any]:
"""Extract documentation from a class."""
+ griffe_module = load_griffe()
doc = parse_docstring(cls.docstring.value if cls.docstring else None)
info = {
@@ -245,7 +275,7 @@ def extract_class_info(
for name, member in cls.members.items():
if name.startswith("_"):
continue
- if isinstance(member, griffe.Attribute):
+ if isinstance(member, griffe_module.Attribute):
attr_doc = member.docstring.value if member.docstring else ""
info["properties"].append(
{
@@ -259,7 +289,7 @@ def extract_class_info(
for name, member in cls.members.items():
if name.startswith("_"):
continue
- if isinstance(member, griffe.Function):
+ if isinstance(member, griffe_module.Function):
method_doc = parse_docstring(
member.docstring.value if member.docstring else None
)
@@ -537,6 +567,8 @@ result = composio.tools.execute(
def main():
+ griffe_module = load_griffe()
+
print("Starting Python SDK documentation generation...\n")
print(f"Output: {OUTPUT_DIR}\n")
@@ -548,7 +580,7 @@ def main():
# Load package
print("Loading composio package...")
try:
- package = griffe.load("composio", search_paths=[str(PACKAGE_DIR)])
+ package = griffe_module.load("composio", search_paths=[str(PACKAGE_DIR)])
except Exception as e:
print(f"Error: {e}")
raise SystemExit(1)
@@ -572,7 +604,7 @@ def main():
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):
+ if isinstance(cls, griffe_module.Class):
classes_to_doc[class_name] = {
"cls": cls,
"access": f"composio.{prop_name}",
@@ -594,7 +626,7 @@ def main():
if class_name in current.members:
cls = current.members[class_name]
- if isinstance(cls, griffe.Class):
+ if isinstance(cls, griffe_module.Class):
classes_to_doc[class_name] = {
"cls": cls,
"access": None,
@@ -641,7 +673,7 @@ def main():
if dec_name in current.members:
func = current.members[dec_name]
- if isinstance(func, griffe.Function):
+ if isinstance(func, griffe_module.Function):
print(f" Processing decorator {dec_name}...")
doc = parse_docstring(func.docstring.value if func.docstring else None)
diff --git a/python/tests/test_generate_docs.py b/python/tests/test_generate_docs.py
new file mode 100644
index 000000000..f8891a79f
--- /dev/null
+++ b/python/tests/test_generate_docs.py
@@ -0,0 +1,58 @@
+"""Regression tests for SDK reference generation."""
+
+from __future__ import annotations
+
+import ast
+import importlib.util
+from pathlib import Path
+
+import pytest
+
+from composio.core.models.triggers import Triggers
+
+
+def load_generate_docs_module():
+ script_path = Path(__file__).resolve().parents[1] / "scripts" / "generate-docs.py"
+ spec = importlib.util.spec_from_file_location("_generate_docs", script_path)
+ assert spec is not None
+ assert spec.loader is not None
+
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def test_triggers_parse_generated_example_is_valid_python():
+ generate_docs = load_generate_docs_module()
+
+ parsed = generate_docs.parse_docstring(Triggers.parse.__doc__)
+ assert parsed["examples"], "Triggers.parse() must keep its public example"
+
+ try:
+ ast.parse(parsed["examples"][0])
+ except SyntaxError as exc:
+ pytest.fail(
+ "Triggers.parse() generated SDK reference example must be "
+ f"copy-pasteable Python: {exc}"
+ )
+
+
+def test_generated_examples_do_not_keep_nested_markdown_fences():
+ generate_docs = load_generate_docs_module()
+
+ parsed = generate_docs.parse_docstring(
+ """
+ Fetch SDK data.
+
+ Example:
+ ```python
+ result = composio.tools.get_raw_tool_router_meta_tools("session_123")
+ print(result)
+ ```
+ """
+ )
+
+ assert parsed["examples"] == [
+ 'result = composio.tools.get_raw_tool_router_meta_tools("session_123")\n'
+ "print(result)"
+ ]