@devries-cameron20 / composio Mirror · read-only / commits / e7bb45f44
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 19:45 UTC

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

This PR: - normalizes Python SDK reference examples generated from source docstrings - rewrites the `Triggers.parse()` docstring so the generated Flask/FastAPI examples are copy-pasteable - strips nested Markdown fences before wrapping generated examples in MDX code fences - regenerates `docs/content/reference/sdk-reference/python/` - adds regression coverage for the `Triggers.parse()` generated example and fenced example normalization - does not include a changeset because this only changes docs generation, generated docs, and tests ## Verification - `cd python && .venv/bin/python -m pytest tests/test_generate_docs.py -q` - `cd python && .venv/bin/ruff check --config config/ruff.toml composio/core/models/triggers.py scripts/generate-docs.py tests/test_generate_docs.py` - `cd python && .venv/bin/ruff format --check --config config/ruff.toml composio/core/models/triggers.py scripts/generate-docs.py tests/test_generate_docs.py` - `cd python && .venv/bin/python scripts/generate-docs.py` - `cd docs && bun install --frozen-lockfile` - `cd docs && bun run types:check`

Alberto Schiabel committed Jun 26, 2026 at 15:12 UTC e7bb45f44966117ffb09c313173c23c6fbb4f18e
8 files changed +318 -185
docs/content/reference/sdk-reference/python/connected-accounts.mdx
+36 -36
@@ -29,10 +29,10 @@ def update(nanoid: str, alias: str | None = ..., connection: connected_account_p
29
30 ```python
31 # Set an alias
32 - composio.connected_accounts.update('ca_abc123', alias='work-gmail')
32 +composio.connected_accounts.update('ca_abc123', alias='work-gmail')
33
34 - # Clear an alias
35 - composio.connected_accounts.update('ca_abc123', alias='')
34 +# Clear an alias
35 +composio.connected_accounts.update('ca_abc123', alias='')
36 ```
37
38 ---
@@ -62,10 +62,10 @@ def update_acl(nanoid: str, allow_all_users: bool | None = ..., allowed_user_ids
62
63 ```python
64 composio.connected_accounts.update_acl(
65 - 'ca_abc',
66 - allow_all_users=True,
67 - not_allowed_user_ids=['user_bob'],
68 - )
65 + 'ca_abc',
66 + allow_all_users=True,
67 + not_allowed_user_ids=['user_bob'],
68 +)
69 ```
70
71 ---
@@ -122,36 +122,36 @@ def link(user_id: str, auth_config_id: str, callback_url: str | None = ..., alia
122
123 ```python
124 # Create a connection request and redirect the user to the redirect url
125 - connection_request = composio.connected_accounts.link('user_123', 'auth_config_123')
126 - redirect_url = connection_request.redirect_url
127 - print(f"Visit: {redirect_url} to authenticate your account")
128 -
129 - # Wait for the connection to be established
130 - connected_account = connection_request.wait_for_connection()
131 -
132 - # Create a connection request with callback URL
133 - connection_request = composio.connected_accounts.link(
134 - 'user_123',
135 - 'auth_config_123',
136 - callback_url='https://your-app.com/callback'
137 - )
138 - redirect_url = connection_request.redirect_url
139 - print(f"Visit: {redirect_url} to authenticate your account")
140 -
141 - # Wait for the connection to be established
142 - connected_account = composio.connected_accounts.wait_for_connection(connection_request.id)
143 -
144 - connection_request = composio.connected_accounts.link(
145 - 'user_creator',
146 - 'auth_config_123',
147 - experimental={
148 - 'account_type': 'SHARED',
149 - 'acl_config_for_shared': {
150 - 'allow_all_users': True,
151 - 'not_allowed_user_ids': ['user_bob'],
152 - },
125 +connection_request = composio.connected_accounts.link('user_123', 'auth_config_123')
126 +redirect_url = connection_request.redirect_url
127 +print(f"Visit: {redirect_url} to authenticate your account")
128 +
129 +# Wait for the connection to be established
130 +connected_account = connection_request.wait_for_connection()
131 +
132 +# Create a connection request with callback URL
133 +connection_request = composio.connected_accounts.link(
134 + 'user_123',
135 + 'auth_config_123',
136 + callback_url='https://your-app.com/callback'
137 +)
138 +redirect_url = connection_request.redirect_url
139 +print(f"Visit: {redirect_url} to authenticate your account")
140 +
141 +# Wait for the connection to be established
142 +connected_account = composio.connected_accounts.wait_for_connection(connection_request.id)
143 +
144 +connection_request = composio.connected_accounts.link(
145 + 'user_creator',
146 + 'auth_config_123',
147 + experimental={
148 + 'account_type': 'SHARED',
149 + 'acl_config_for_shared': {
150 + 'allow_all_users': True,
151 + 'not_allowed_user_ids': ['user_bob'],
152 },
154 - )
153 + },
154 +)
155 ```
156
157 ---
docs/content/reference/sdk-reference/python/mcp.mdx
+80 -80
@@ -4,7 +4,7 @@ description: "MCP (Model Control Protocol) class. Provides enhanced MCP server o
4 ---
5
6 <Callout type="warn" title="Deprecated">
7 -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
7 +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
8 </Callout>
9
10 ## Methods
@@ -34,38 +34,38 @@ def create(name: str, toolkits: List[Union[ConfigToolkit, str]], manually_manage
34
35 ```python
36 >>> # Using toolkit configuration objects with auth
37 - >>> server = composio.experimental.mcp.create(
38 - ... 'personal-mcp-server',
39 - ... toolkits=[
40 - ... {
41 - ... 'toolkit': 'github',
42 - ... 'auth_config_id': 'ac_xyz',
43 - ... },
44 - ... {
45 - ... 'toolkit': 'slack',
46 - ... 'auth_config_id': 'ac_abc',
47 - ... },
48 - ... ],
49 - ... allowed_tools=['GITHUB_CREATE_ISSUE', 'GITHUB_LIST_REPOS', 'SLACK_SEND_MESSAGE'],
50 - ... manually_manage_connections=False
51 - ... )
52 - >>>
53 - >>> # Using simple toolkit names (most common usage)
54 - >>> server = composio.experimental.mcp.create(
55 - ... 'simple-mcp-server',
56 - ... toolkits=['composio_search', 'text_to_pdf'],
57 - ... allowed_tools=['COMPOSIO_SEARCH_DUCK_DUCK_GO_SEARCH', 'TEXT_TO_PDF_CONVERT_TEXT_TO_PDF']
58 - ... )
59 - >>>
60 - >>> # Using all tools from toolkits (default behavior)
61 - >>> server = composio.experimental.mcp.create(
62 - ... 'all-tools-server',
63 - ... toolkits=['composio_search', 'text_to_pdf']
64 - ... # allowed_tools=None means all tools from these toolkits
65 - ... )
66 - >>>
67 - >>> # Get server instance for a user
68 - >>> mcp = server.generate('user_12345')
37 +>>> server = composio.experimental.mcp.create(
38 +... 'personal-mcp-server',
39 +... toolkits=[
40 +... {
41 +... 'toolkit': 'github',
42 +... 'auth_config_id': 'ac_xyz',
43 +... },
44 +... {
45 +... 'toolkit': 'slack',
46 +... 'auth_config_id': 'ac_abc',
47 +... },
48 +... ],
49 +... allowed_tools=['GITHUB_CREATE_ISSUE', 'GITHUB_LIST_REPOS', 'SLACK_SEND_MESSAGE'],
50 +... manually_manage_connections=False
51 +... )
52 +>>>
53 +>>> # Using simple toolkit names (most common usage)
54 +>>> server = composio.experimental.mcp.create(
55 +... 'simple-mcp-server',
56 +... toolkits=['composio_search', 'text_to_pdf'],
57 +... allowed_tools=['COMPOSIO_SEARCH_DUCK_DUCK_GO_SEARCH', 'TEXT_TO_PDF_CONVERT_TEXT_TO_PDF']
58 +... )
59 +>>>
60 +>>> # Using all tools from toolkits (default behavior)
61 +>>> server = composio.experimental.mcp.create(
62 +... 'all-tools-server',
63 +... toolkits=['composio_search', 'text_to_pdf']
64 +... # allowed_tools=None means all tools from these toolkits
65 +... )
66 +>>>
67 +>>> # Get server instance for a user
68 +>>> mcp = server.generate('user_12345')
69 ```
70
71 ---
@@ -98,13 +98,13 @@ def list(page_no: int | None = ..., limit: int | None = ..., toolkits: str | Non
98
99 ```python
100 >>> # List all servers
101 - >>> all_servers = composio.experimental.mcp.list()
102 - >>>
103 - >>> # List with pagination
104 - >>> paged_servers = composio.experimental.mcp.list(page_no=2, limit=5)
105 - >>>
106 - >>> # Filter by toolkit
107 - >>> github_servers = composio.experimental.mcp.list(toolkits='github', name='personal')
101 +>>> all_servers = composio.experimental.mcp.list()
102 +>>>
103 +>>> # List with pagination
104 +>>> paged_servers = composio.experimental.mcp.list(page_no=2, limit=5)
105 +>>>
106 +>>> # Filter by toolkit
107 +>>> github_servers = composio.experimental.mcp.list(toolkits='github', name='personal')
108 ```
109
110 ---
@@ -127,11 +127,11 @@ def get(server_id: str)
127
128 ```python
129 >>> server = composio.experimental.mcp.get('mcp_12345')
130 - >>>
131 - >>> print(server['name']) # "My Personal MCP Server"
132 - >>> print(server['allowed_tools']) # ["GITHUB_CREATE_ISSUE", "SLACK_SEND_MESSAGE"]
133 - >>> print(server['toolkits']) # ["github", "slack"]
134 - >>> print(server['server_instance_count']) # 3
130 +>>>
131 +>>> print(server['name']) # "My Personal MCP Server"
132 +>>> print(server['allowed_tools']) # ["GITHUB_CREATE_ISSUE", "SLACK_SEND_MESSAGE"]
133 +>>> print(server['toolkits']) # ["github", "slack"]
134 +>>> print(server['server_instance_count']) # 3
135 ```
136
137 ---
@@ -158,28 +158,28 @@ def update(server_id: str, name: str | None = ..., toolkits: List[Union[ConfigTo
158
159 ```python
160 >>> # Update server name only
161 - >>> updated_server = composio.experimental.mcp.update(
162 - ... 'mcp_12345',
163 - ... name='My Updated MCP Server'
164 - ... )
165 - >>>
166 - >>> # Update toolkits and tools
167 - >>> server_with_new_tools = composio.experimental.mcp.update(
168 - ... 'mcp_12345',
169 - ... toolkits=['github', 'slack'],
170 - ... allowed_tools=['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE']
171 - ... )
172 - >>>
173 - >>> # Update with auth configs
174 - >>> server_with_auth = composio.experimental.mcp.update(
175 - ... 'mcp_12345',
176 - ... toolkits=[
177 - ... {'toolkit': 'github', 'auth_config_id': 'auth_abc123'},
178 - ... {'toolkit': 'slack', 'auth_config_id': 'auth_def456'}
179 - ... ],
180 - ... allowed_tools=['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE'],
181 - ... manually_manage_connections=False
182 - ... )
161 +>>> updated_server = composio.experimental.mcp.update(
162 +... 'mcp_12345',
163 +... name='My Updated MCP Server'
164 +... )
165 +>>>
166 +>>> # Update toolkits and tools
167 +>>> server_with_new_tools = composio.experimental.mcp.update(
168 +... 'mcp_12345',
169 +... toolkits=['github', 'slack'],
170 +... allowed_tools=['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE']
171 +... )
172 +>>>
173 +>>> # Update with auth configs
174 +>>> server_with_auth = composio.experimental.mcp.update(
175 +... 'mcp_12345',
176 +... toolkits=[
177 +... {'toolkit': 'github', 'auth_config_id': 'auth_abc123'},
178 +... {'toolkit': 'slack', 'auth_config_id': 'auth_def456'}
179 +... ],
180 +... allowed_tools=['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE'],
181 +... manually_manage_connections=False
182 +... )
183 ```
184
185 ---
@@ -206,12 +206,12 @@ def delete(server_id: str) -> Dict[str, Any]
206
207 ```python
208 >>> # Delete a server
209 - >>> result = composio.experimental.mcp.delete('mcp_12345')
210 - >>>
211 - >>> if result['deleted']:
212 - ... print(f"Server {result['id']} has been successfully deleted")
213 - >>> else:
214 - ... print(f"Failed to delete server {result['id']}")
209 +>>> result = composio.experimental.mcp.delete('mcp_12345')
210 +>>>
211 +>>> if result['deleted']:
212 +... print(f"Server {result['id']} has been successfully deleted")
213 +>>> else:
214 +... print(f"Failed to delete server {result['id']}")
215 ```
216
217 ---
@@ -240,13 +240,13 @@ def generate(user_id: str, mcp_config_id: str, manually_manage_connections: bool
240
241 ```python
242 >>> mcp = composio.experimental.mcp.generate(
243 - ... 'user_12345',
244 - ... 'mcp_67890',
245 - ... manually_manage_connections=False
246 - ... )
247 - >>>
248 - >>> print(mcp['url']) # Server URL for the user
249 - >>> print(mcp['allowed_tools']) # Available tools
243 +... 'user_12345',
244 +... 'mcp_67890',
245 +... manually_manage_connections=False
246 +... )
247 +>>>
248 +>>> print(mcp['url']) # Server URL for the user
249 +>>> print(mcp['allowed_tools']) # Available tools
250 ```
251
252 ---
docs/content/reference/sdk-reference/python/session.mdx
+3 -2
@@ -183,10 +183,10 @@ def proxy_execute(toolkit: str, endpoint: str, method: Literal['GET', 'POST', 'P
183
184 ### update()
185
186 -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.
186 +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.
187
188 ```python
189 -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
189 +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
190 ```
191
192 **Parameters**
@@ -199,6 +199,7 @@ def update(toolkits: Union[session_patch_params.Toolkits, 'Omit'] = ..., tools:
199 | `auth_configs?` | `Union[Dict[str, str], 'Omit']` |
200 | `connected_accounts?` | `Union[Dict[str, SequenceNotStr[str \| None]], 'Omit']` |
201 | `manage_connections?` | `Union[session_patch_params.ManageConnections \| None, 'Omit']` |
202 +| `sandbox?` | `Union[session_patch_params.Workbench \| None, 'Omit']` |
203 | `workbench?` | `Union[session_patch_params.Workbench \| None, 'Omit']` |
204 | `multi_account?` | `Union[session_patch_params.MultiAccount \| None, 'Omit']` |
205 | `preload?` | `Union[session_patch_params.Preload, 'Omit']` |
docs/content/reference/sdk-reference/python/tools.mdx
+17 -19
@@ -71,30 +71,28 @@ def get_raw_tool_router_meta_tools(session_id: str, modifiers: 'Modifiers' | Non
71 **Example**
72
73 ```python
74 -```python
75 - from composio import Composio
74 +from composio import Composio
75
77 - composio = Composio()
78 - tools_model = composio.tools
76 +composio = Composio()
77 +tools_model = composio.tools
78
80 - # Get meta tools for a session
81 - meta_tools = tools_model.get_raw_tool_router_meta_tools("session_123")
82 - print(meta_tools)
79 +# Get meta tools for a session
80 +meta_tools = tools_model.get_raw_tool_router_meta_tools("session_123")
81 +print(meta_tools)
82
84 - # Get meta tools with schema modifiers
85 - from composio.core.models import schema_modifier
83 +# Get meta tools with schema modifiers
84 +from composio.core.models import schema_modifier
85
87 - @schema_modifier
88 - def modify_schema(tool: str, toolkit: str, schema):
89 - # Customize the schema
90 - schema.description = f"Modified: {schema.description}"
91 - return schema
86 +@schema_modifier
87 +def modify_schema(tool: str, toolkit: str, schema):
88 + # Customize the schema
89 + schema.description = f"Modified: {schema.description}"
90 + return schema
91
93 - meta_tools = tools_model.get_raw_tool_router_meta_tools(
94 - "session_123",
95 - modifiers=[modify_schema]
96 - )
97 - ```
92 +meta_tools = tools_model.get_raw_tool_router_meta_tools(
93 + "session_123",
94 + modifiers=[modify_schema]
95 +)
96 ```
97
98 ---
docs/content/reference/sdk-reference/python/triggers.mdx
+68 -19
@@ -29,8 +29,8 @@ def set_webhook_subscription(webhook_url: str, enabled_events: Sequence[str | No
29
30 ```python
31 composio.triggers.set_webhook_subscription(
32 - webhook_url=f"{APP_URL}/webhooks/composio",
33 - )
32 + webhook_url=f"{APP_URL}/webhooks/composio",
33 +)
34 ```
35
36 ---
@@ -165,23 +165,72 @@ def verify_webhook(id: str, payload: str, secret: str, signature: str, timestamp
165
166 ```python
167 # In a Flask webhook handler
168 - @app.route('/webhook', methods=['POST'])
169 - def webhook():
170 - try:
171 - result = composio.triggers.verify_webhook(
172 - id=request.headers.get('webhook-id', ''),
173 - payload=request.get_data(as_text=True),
174 - signature=request.headers.get('webhook-signature', ''),
175 - timestamp=request.headers.get('webhook-timestamp', ''),
176 - secret=os.environ['COMPOSIO_WEBHOOK_SECRET'],
177 - )
178 -
179 - # Process the verified payload
180 - print(f"Version: {result['version']}")
181 - print(f"Received trigger: {result['payload']['trigger_slug']}")
182 - return 'OK', 200
183 - except WebhookSignatureVerificationError:
184 - return 'Unauthorized', 401
168 +@app.route('/webhook', methods=['POST'])
169 +def webhook():
170 + try:
171 + result = composio.triggers.verify_webhook(
172 + id=request.headers.get('webhook-id', ''),
173 + payload=request.get_data(as_text=True),
174 + signature=request.headers.get('webhook-signature', ''),
175 + timestamp=request.headers.get('webhook-timestamp', ''),
176 + secret=os.environ['COMPOSIO_WEBHOOK_SECRET'],
177 + )
178 +
179 + # Process the verified payload
180 + print(f"Version: {result['version']}")
181 + print(f"Received trigger: {result['payload']['trigger_slug']}")
182 + return 'OK', 200
183 + except WebhookSignatureVerificationError:
184 + return 'Unauthorized', 401
185 +```
186 +
187 +---
188 +
189 +### parse()
190 +
191 +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()``.
192 +
193 +```python
194 +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
195 +```
196 +
197 +**Parameters**
198 +
199 +| Name | Type |
200 +|------|------|
201 +| `request?` | `Any` |
202 +| `body?` | `Union[str, bytes, Mapping[str, Any], None]` |
203 +| `headers?` | `Union[Mapping[str, Any], None]` |
204 +| `verify_secret?` | `Union[str, None, Omit]` |
205 +| `tolerance?` | `int` |
206 +
207 +**Returns**
208 +
209 +`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
210 +
211 +**Example**
212 +
213 +```python
214 +# Flask: verify the signature
215 +@app.route('/webhooks/composio', methods=['POST'])
216 +def webhook():
217 + try:
218 + result = composio.triggers.parse(
219 + request,
220 + verify_secret=os.environ['COMPOSIO_WEBHOOK_SECRET'],
221 + )
222 + print(f"Trigger: {result['payload']['trigger_slug']}")
223 + print(f"Event data: {result['payload']['payload']}")
224 + return 'OK', 200
225 + except exceptions.WebhookSignatureVerificationError:
226 + return 'Unauthorized', 401
227 +
228 +# FastAPI: parse without verifying after reading the async body
229 +@app.post('/webhooks/composio')
230 +async def webhook(request: Request):
231 + raw = await request.body()
232 + result = composio.triggers.parse(body=raw, headers=request.headers)
233 + return {'trigger': result['payload']['trigger_slug']}
234 ```
235
236 ---
python/composio/core/models/triggers.py
+10 -15
@@ -1270,21 +1270,16 @@ class Triggers(Resource):
1270 """
1271 Parse an incoming webhook request into a typed, normalized trigger payload.
1272
1273 - Dump the incoming request in and get back the parsed Composio trigger
1274 - event. When ``verify_secret`` is provided, the request signature is
1275 - verified before the payload is returned (delegating to
1276 - :meth:`verify_webhook`); without it, the body is parsed without
1277 - verification.
1273 + Pass a framework request object, or pass ``body=`` and ``headers=``
1274 + explicitly. When ``verify_secret`` is provided, the SDK verifies the
1275 + webhook signature before returning the normalized trigger payload. When
1276 + it is omitted, the SDK parses the body without verifying the signature.
1277
1278 ``request`` may be any object exposing the request body and headers, such
1280 - as a Flask/Django/FastAPI request. The body is read from ``.body`` (or
1281 - ``.data`` / ``.get_data()``) and the headers from ``.headers``. Because
1282 - this SDK is synchronous, the caller must pass an already-read raw body for
1283 - async frameworks (e.g. FastAPI ``await request.body()``) — either via the
1284 - ``body`` keyword or by reading it first.
1285 -
1286 - Alternatively, pass ``body=`` and ``headers=`` explicitly instead of a
1287 - ``request`` object.
1279 + as a Flask, Django, or FastAPI request. The body is read from ``.body``
1280 + (or ``.data`` / ``.get_data()``), and the headers are read from
1281 + ``.headers``. Because this SDK is synchronous, async frameworks must pass
1282 + an already-read raw body, for example via ``body=await request.body()``.
1283
1284 :param request: The incoming webhook request object (Flask/Django/FastAPI)
1285 :param body: The raw request body (str/bytes/parsed mapping); overrides ``request``
@@ -1300,7 +1295,7 @@ class Triggers(Resource):
1295 :raises WebhookPayloadError: If the payload cannot be parsed
1296
1297 Example:
1303 - # Flask — verify the signature
1298 + # Flask: verify the signature
1299 @app.route('/webhooks/composio', methods=['POST'])
1300 def webhook():
1301 try:
@@ -1314,7 +1309,7 @@ class Triggers(Resource):
1309 except exceptions.WebhookSignatureVerificationError:
1310 return 'Unauthorized', 401
1311
1317 - # FastAPI — parse without verifying (read the async body first)
1312 + # FastAPI: parse without verifying after reading the async body
1313 @app.post('/webhooks/composio')
1314 async def webhook(request: Request):
1315 raw = await request.body()
python/scripts/generate-docs.py
+46 -14
@@ -13,14 +13,30 @@ from __future__ import annotations
13 import json
14 import re
15 import shutil
16 +import textwrap
17 from pathlib import Path
18 from typing import Any
19
19 -try:
20 - import griffe
21 -except ImportError:
22 - print("Error: griffe not installed. Run: pip install griffe")
23 - raise SystemExit(1)
20 +import typing as t
21 +
22 +if t.TYPE_CHECKING:
23 + import griffe as griffe_t
24 +
25 +_griffe: Any | None = None
26 +
27 +
28 +def load_griffe() -> Any:
29 + """Load griffe lazily so parser helpers can be unit-tested without it."""
30 + global _griffe
31 + if _griffe is None:
32 + try:
33 + import griffe as griffe_module
34 + except ImportError:
35 + print("Error: griffe not installed. Run: pip install griffe")
36 + raise SystemExit(1)
37 + _griffe = griffe_module
38 + return _griffe
39 +
40
41 # Paths
42 SCRIPT_DIR = Path(__file__).parent
@@ -107,7 +123,7 @@ def escape_yaml_string(s: str) -> str:
123 return json.dumps(s)
124
125
110 -def get_source_link(obj: griffe.Object) -> str | None:
126 +def get_source_link(obj: griffe_t.Object) -> str | None:
127 """Get GitHub source link for an object."""
128 if not hasattr(obj, "filepath") or not obj.filepath:
129 return None
@@ -214,7 +230,7 @@ def parse_docstring(docstring: str | None) -> dict[str, Any]:
230 deprecated_lines.append(stripped)
231
232 if example_lines:
217 - examples.append("\n".join(example_lines).strip())
233 + examples.append(normalize_example("\n".join(example_lines)))
234
235 return {
236 "description": " ".join(description_lines).strip(),
@@ -225,10 +241,24 @@ def parse_docstring(docstring: str | None) -> dict[str, Any]:
241 }
242
243
244 +def normalize_example(example: str) -> str:
245 + """Normalize a docstring example before wrapping it in an MDX code fence."""
246 + normalized = textwrap.dedent(example).strip()
247 + lines = normalized.splitlines()
248 +
249 + if len(lines) >= 2 and lines[0].strip().startswith("```"):
250 + closing_index = len(lines) - 1
251 + if lines[closing_index].strip() == "```":
252 + normalized = "\n".join(lines[1:closing_index]).strip()
253 +
254 + return normalized
255 +
256 +
257 def extract_class_info(
229 - cls: griffe.Class, class_name: str, config: dict
258 + cls: griffe_t.Class, class_name: str, config: dict
259 ) -> dict[str, Any]:
260 """Extract documentation from a class."""
261 + griffe_module = load_griffe()
262 doc = parse_docstring(cls.docstring.value if cls.docstring else None)
263
264 info = {
@@ -245,7 +275,7 @@ def extract_class_info(
275 for name, member in cls.members.items():
276 if name.startswith("_"):
277 continue
248 - if isinstance(member, griffe.Attribute):
278 + if isinstance(member, griffe_module.Attribute):
279 attr_doc = member.docstring.value if member.docstring else ""
280 info["properties"].append(
281 {
@@ -259,7 +289,7 @@ def extract_class_info(
289 for name, member in cls.members.items():
290 if name.startswith("_"):
291 continue
262 - if isinstance(member, griffe.Function):
292 + if isinstance(member, griffe_module.Function):
293 method_doc = parse_docstring(
294 member.docstring.value if member.docstring else None
295 )
@@ -537,6 +567,8 @@ result = composio.tools.execute(
567
568
569 def main():
570 + griffe_module = load_griffe()
571 +
572 print("Starting Python SDK documentation generation...\n")
573 print(f"Output: {OUTPUT_DIR}\n")
574
@@ -548,7 +580,7 @@ def main():
580 # Load package
581 print("Loading composio package...")
582 try:
551 - package = griffe.load("composio", search_paths=[str(PACKAGE_DIR)])
583 + package = griffe_module.load("composio", search_paths=[str(PACKAGE_DIR)])
584 except Exception as e:
585 print(f"Error: {e}")
586 raise SystemExit(1)
@@ -572,7 +604,7 @@ def main():
604 for class_name, prop_name in EXPECTED_CLASSES.items():
605 if class_name in current.members:
606 cls = current.members[class_name]
575 - if isinstance(cls, griffe.Class):
607 + if isinstance(cls, griffe_module.Class):
608 classes_to_doc[class_name] = {
609 "cls": cls,
610 "access": f"composio.{prop_name}",
@@ -594,7 +626,7 @@ def main():
626
627 if class_name in current.members:
628 cls = current.members[class_name]
597 - if isinstance(cls, griffe.Class):
629 + if isinstance(cls, griffe_module.Class):
630 classes_to_doc[class_name] = {
631 "cls": cls,
632 "access": None,
@@ -641,7 +673,7 @@ def main():
673
674 if dec_name in current.members:
675 func = current.members[dec_name]
644 - if isinstance(func, griffe.Function):
676 + if isinstance(func, griffe_module.Function):
677 print(f" Processing decorator {dec_name}...")
678 doc = parse_docstring(func.docstring.value if func.docstring else None)
679
python/tests/test_generate_docs.py new
+58
@@ -0,0 +1,58 @@
1 +"""Regression tests for SDK reference generation."""
2 +
3 +from __future__ import annotations
4 +
5 +import ast
6 +import importlib.util
7 +from pathlib import Path
8 +
9 +import pytest
10 +
11 +from composio.core.models.triggers import Triggers
12 +
13 +
14 +def load_generate_docs_module():
15 + script_path = Path(__file__).resolve().parents[1] / "scripts" / "generate-docs.py"
16 + spec = importlib.util.spec_from_file_location("_generate_docs", script_path)
17 + assert spec is not None
18 + assert spec.loader is not None
19 +
20 + module = importlib.util.module_from_spec(spec)
21 + spec.loader.exec_module(module)
22 + return module
23 +
24 +
25 +def test_triggers_parse_generated_example_is_valid_python():
26 + generate_docs = load_generate_docs_module()
27 +
28 + parsed = generate_docs.parse_docstring(Triggers.parse.__doc__)
29 + assert parsed["examples"], "Triggers.parse() must keep its public example"
30 +
31 + try:
32 + ast.parse(parsed["examples"][0])
33 + except SyntaxError as exc:
34 + pytest.fail(
35 + "Triggers.parse() generated SDK reference example must be "
36 + f"copy-pasteable Python: {exc}"
37 + )
38 +
39 +
40 +def test_generated_examples_do_not_keep_nested_markdown_fences():
41 + generate_docs = load_generate_docs_module()
42 +
43 + parsed = generate_docs.parse_docstring(
44 + """
45 + Fetch SDK data.
46 +
47 + Example:
48 + ```python
49 + result = composio.tools.get_raw_tool_router_meta_tools("session_123")
50 + print(result)
51 + ```
52 + """
53 + )
54 +
55 + assert parsed["examples"] == [
56 + 'result = composio.tools.get_raw_tool_router_meta_tools("session_123")\n'
57 + "print(result)"
58 + ]