@devries-cameron20 / composio Mirror · read-only / commits / 3271679ee
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, 12:15 UTC

docs(py): render Raises sections and normalize reST in generated SDK reference

- parse :raises Exc: docstring fields (plus Sphinx synonyms) into a structured Raises section instead of leaking raw directives into the Returns description - normalize inline reST in all rendered prose: roles (:class:, :func:, :meth:, ...) honor ~ short-name semantics; double-backtick literals become single-backtick inline code - regenerate docs/content/reference/sdk-reference/python/ pages - add regression tests for raises parsing and reST normalization Flagged by Greptile on the legacy-repo auto-PR (ComposioHQ/composio#4479).

jkomyno committed Sep 15, 2026 at 13:12 UTC 3271679ee0e938b466db19110d4a65013ad458f5
7 files changed +238 -22
docs/content/reference/sdk-reference/python/connected-accounts.mdx
+4 -4
@@ -23,7 +23,7 @@ def update(nanoid: str, alias: str | None = ..., connection: connected_account_p
23
24 **Returns**
25
26 -`connected_account_patch_response.ConnectedAccountPatchRes...` — Response with ``id``, ``status``, and ``success``.
26 +`connected_account_patch_response.ConnectedAccountPatchRes...` — Response with `id`, `status`, and `success`.
27
28 **Example**
29
@@ -39,7 +39,7 @@ composio.connected_accounts.update('ca_abc123', alias='')
39
40 ### update_acl()
41
42 -Update the per-user ACL on a SHARED connected account. Experimental — shape may change in future releases. Only valid on SHARED connections; raises ``ComposioAclOnlyForSharedError`` on a PRIVATE connection. Omit a parameter to leave it unchanged; pass an empty list to clear an allow/deny list. At least one parameter must be provided.
42 +Update the per-user ACL on a SHARED connected account. Experimental — shape may change in future releases. Only valid on SHARED connections; raises `ComposioAclOnlyForSharedError` on a PRIVATE connection. Omit a parameter to leave it unchanged; pass an empty list to clear an allow/deny list. At least one parameter must be provided.
43
44 ```python
45 def update_acl(nanoid: str, allow_all_users: bool | None = ..., allowed_user_ids: List[str | None] = ..., not_allowed_user_ids: List[str | None] = ...) -> connected_account_patch_response.ConnectedAccountPatchRes...
@@ -56,7 +56,7 @@ def update_acl(nanoid: str, allow_all_users: bool | None = ..., allowed_user_ids
56
57 **Returns**
58
59 -`connected_account_patch_response.ConnectedAccountPatchRes...` — Response with ``id``, ``status``, and ``success``.
59 +`connected_account_patch_response.ConnectedAccountPatchRes...` — Response with `id`, `status`, and `success`.
60
61 **Example**
62
@@ -72,7 +72,7 @@ composio.connected_accounts.update_acl(
72
73 ### initiate()
74
75 -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.
75 +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.
76
77 ```python
78 def initiate(user_id: str, auth_config_id: str, callback_url: str | None = ..., allow_multiple: bool = ..., config: connected_account_create_params.ConnectionState | None = ..., alias: str | None = ...) -> ConnectionRequest
docs/content/reference/sdk-reference/python/index.mdx
+2 -2
@@ -22,7 +22,7 @@ Complete API reference for the `composio` Python package.
22 | [`ConnectedAccounts`](/reference/sdk-reference/python/connected-accounts) | Manage connected accounts. This class is used to manage connected accounts in t... |
23 | [`AuthConfigs`](/reference/sdk-reference/python/auth-configs) | Manage authentication configurations. |
24 | [`MCP`](/reference/sdk-reference/python/mcp) | MCP (Model Control Protocol) class. Provides enhanced MCP server operations Thi... |
25 -| [`Session`](/reference/sdk-reference/python/session) | A Composio session — the object returned by ``composio.create(...)`` / ``composi... |
25 +| [`Session`](/reference/sdk-reference/python/session) | A Composio session — the object returned by `composio.create(...)` / `composio.u... |
26
27 ## Quick Start
28
@@ -66,7 +66,7 @@ def my_modifier(...):
66
67 ### before_file_upload
68
69 -Build a ``Modifier`` for the file-upload hook (same scoping pattern as :func:`before_execute`). Your callable may take **either**: - a single ``context`` argument (:class:`BeforeFileUploadContext`) — the preferred form, exposes ``context["source"]`` (``"path"`` or ``"url"``), or - three positional arguments ``(path, tool, toolkit)`` — legacy form, kept for back-compat. Return a new path/URL string to substitute, or ``False`` to abort the upload (raises :class:`~composio.exceptions.FileUploadAbortedError`). Pass the returned ``Modifier`` in ``modifiers=[...]`` on :meth:`composio.core.models.tools.Tools.execute` or ``tools.get``. Multiple such modifiers are composed in list order.
69 +Build a `Modifier` for the file-upload hook (same scoping pattern as `before_execute`). Your callable may take **either**: - a single `context` argument (`BeforeFileUploadContext`) — the preferred form, exposes `context["source"]` (`"path"` or `"url"`), or - three positional arguments `(path, tool, toolkit)` — legacy form, kept for back-compat. Return a new path/URL string to substitute, or `False` to abort the upload (raises `FileUploadAbortedError`). Pass the returned `Modifier` in `modifiers=[...]` on `composio.core.models.tools.Tools.execute` or `tools.get`. Multiple such modifiers are composed in list order.
70
71 [View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/_modifiers.py#L319)
72
docs/content/reference/sdk-reference/python/session.mdx
+1 -1
@@ -183,7 +183,7 @@ 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``, ``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.
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'] = ..., 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
docs/content/reference/sdk-reference/python/tools.mdx
+5 -1
@@ -23,6 +23,10 @@ def get_raw_composio_tool_by_slug(slug: str) -> Tool
23
24 `Tool`
25
26 +**Raises**
27 +
28 +- `ToolNotFoundError` — when the backend reports the slug as unknown (404, or 400 for a malformed slug). Any other client error, such as an invalid API key, is re-raised unchanged.
29 +
30 ---
31
32 ### get_raw_composio_tools()
@@ -178,4 +182,4 @@ def proxy(endpoint: str, method: Literal['GET', 'POST', 'PUT', 'DELETE', 'PATCH'
182
183 ---
184
181 -[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/tools.py#L119)
185 +[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/tools.py#L123)
docs/content/reference/sdk-reference/python/triggers.mdx
+14 -3
@@ -159,7 +159,12 @@ def verify_webhook(id: str, payload: str, secret: str, signature: str, timestamp
159
160 **Returns**
161
162 -`VerifyWebhookResult` — VerifyWebhookResult containing version, normalized payload, and raw payload :raises WebhookSignatureVerificationError: If the signature verification fails :raises WebhookPayloadError: If the payload cannot be parsed or is invalid
162 +`VerifyWebhookResult` — VerifyWebhookResult containing version, normalized payload, and raw payload
163 +
164 +**Raises**
165 +
166 +- `WebhookSignatureVerificationError` — If the signature verification fails
167 +- `WebhookPayloadError` — If the payload cannot be parsed or is invalid
168
169 **Example**
170
@@ -188,7 +193,7 @@ def webhook():
193
194 ### parse()
195
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()``.
196 +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()`.
197
198 ```python
199 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
@@ -206,7 +211,13 @@ def parse(request: Any = ..., body: Union[str, bytes, Mapping[str, Any], None] =
211
212 **Returns**
213
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
214 +`VerifyWebhookResult` — VerifyWebhookResult containing version, normalized payload, and raw payload
215 +
216 +**Raises**
217 +
218 +- `ValidationError` — If `verify_secret` is empty, or is set but signature headers are missing
219 +- `WebhookSignatureVerificationError` — If signature verification fails
220 +- `WebhookPayloadError` — If the payload cannot be parsed
221
222 **Example**
223
python/scripts/generate-docs.py
+77 -11
@@ -164,6 +164,31 @@ def format_type(annotation: Any) -> str:
164 return type_str
165
166
167 +def _render_rst_role(match: re.Match[str]) -> str:
168 + """Render an reST role match as inline code, honoring ``~`` short names."""
169 + target = match.group(1)
170 + if target.startswith("~"):
171 + target = target.rsplit(".", 1)[-1]
172 + return f"`{target}`"
173 +
174 +
175 +def normalize_inline_rst(text: str) -> str:
176 + """Normalize inline reStructuredText markup to MDX-friendly markdown.
177 +
178 + Converts reST roles such as ``:class:`Foo` `` into plain inline code and
179 + reST double-backtick literals (``name``) into single-backtick inline code
180 + so generated prose renders correctly on the docs site. A ``~`` role prefix
181 + (``:class:`~mod.Foo` ``) renders as the short target name, matching Sphinx.
182 + """
183 + if not text:
184 + return text
185 + # ReST roles: :class:`X`, :func:`mod.func`, :meth:`X.y`, :mod:`~pkg.mod`,
186 + # ... A leading ``~`` requests the short target name, so drop the path.
187 + normalized = re.sub(r":[a-zA-Z]+:`([^`]+)`", _render_rst_role, text)
188 + # ReST double-backtick literals: ``name`` -> `name`
189 + return re.sub(r"``([^`]+)``", r"`\1`", normalized)
190 +
191 +
192 def parse_docstring(docstring: str | None) -> dict[str, Any]:
193 """Parse docstring into components."""
194 if not docstring:
@@ -172,6 +197,7 @@ def parse_docstring(docstring: str | None) -> dict[str, Any]:
197 "params": {},
198 "returns": None,
199 "examples": [],
200 + "raises": [],
201 "deprecated": None,
202 }
203
@@ -180,10 +206,12 @@ def parse_docstring(docstring: str | None) -> dict[str, Any]:
206 params: dict[str, str] = {}
207 returns = None
208 examples: list[str] = []
209 + raises: list[dict[str, str]] = []
210 deprecated_lines: list[str] = []
211
212 section = "description"
213 current_param = None
214 + current_raise: dict[str, str] | None = None
215 example_lines: list[str] = []
216
217 for line in lines:
@@ -212,6 +240,19 @@ def parse_docstring(docstring: str | None) -> dict[str, Any]:
240 returns = return_match.group(1)
241 continue
242
243 + # Check for :raises Exc: description (plus common Sphinx synonyms).
244 + raise_match = re.match(
245 + r":(?:raises?|except|throws?)\s+([\w.]+):\s*(.*)", stripped
246 + )
247 + if raise_match:
248 + section = "raises"
249 + current_raise = {
250 + "exception": raise_match.group(1),
251 + "description": raise_match.group(2).strip(),
252 + }
253 + raises.append(current_raise)
254 + continue
255 +
256 # Check for Example section
257 if stripped.lower().startswith("example"):
258 section = "examples"
@@ -224,6 +265,10 @@ def parse_docstring(docstring: str | None) -> dict[str, Any]:
265 params[current_param] += " " + stripped
266 elif section == "returns" and returns and stripped:
267 returns += " " + stripped
268 + elif section == "raises" and current_raise is not None and stripped:
269 + current_raise["description"] = (
270 + current_raise["description"] + " " + stripped
271 + ).strip()
272 elif section == "examples":
273 example_lines.append(line)
274 elif section == "deprecated" and stripped:
@@ -233,11 +278,22 @@ def parse_docstring(docstring: str | None) -> dict[str, Any]:
278 examples.append(normalize_example("\n".join(example_lines)))
279
280 return {
236 - "description": " ".join(description_lines).strip(),
237 - "params": params,
238 - "returns": returns,
281 + "description": normalize_inline_rst(" ".join(description_lines).strip()),
282 + "params": {name: normalize_inline_rst(desc) for name, desc in params.items()},
283 + "returns": normalize_inline_rst(returns) if returns else None,
284 "examples": examples,
240 - "deprecated": " ".join(deprecated_lines).strip() if deprecated_lines else None,
285 + "raises": [
286 + {
287 + "exception": entry["exception"],
288 + "description": normalize_inline_rst(entry["description"]),
289 + }
290 + for entry in raises
291 + ],
292 + "deprecated": (
293 + normalize_inline_rst(" ".join(deprecated_lines).strip())
294 + if deprecated_lines
295 + else None
296 + ),
297 }
298
299
@@ -281,7 +337,9 @@ def extract_class_info(
337 {
338 "name": name,
339 "type": format_type(member.annotation),
284 - "description": attr_doc.strip() if attr_doc else "",
340 + "description": (
341 + normalize_inline_rst(attr_doc.strip()) if attr_doc else ""
342 + ),
343 }
344 )
345
@@ -315,6 +373,7 @@ def extract_class_info(
373 "parameters": params,
374 "return_type": format_type(member.returns),
375 "return_description": method_doc["returns"],
376 + "raises": method_doc["raises"],
377 "examples": method_doc["examples"],
378 }
379 )
@@ -334,9 +393,6 @@ def generate_class_mdx(
393 if info["description"]
394 else f"{info['name']} class"
395 )
337 - # Normalize reStructuredText ``double backticks`` to single backticks so the
338 - # frontmatter description reads cleanly.
339 - desc = re.sub(r"``([^`]+)``", r"`\1`", desc)
396 if len(desc) > 150:
397 desc = desc[:147] + "..."
398
@@ -349,9 +405,6 @@ def generate_class_mdx(
405 # Class-level deprecation callout (rendered as a fumadocs warning callout).
406 deprecated_note = info.get("deprecated")
407 if deprecated_note:
352 - # Normalize reStructuredText ``double backticks`` to MDX `single` so
353 - # inline code renders correctly.
354 - deprecated_note = re.sub(r"``([^`]+)``", r"`\1`", deprecated_note)
408 lines.append('<Callout type="warn" title="Deprecated">')
409 lines.append(deprecated_note)
410 lines.append("</Callout>")
@@ -456,6 +509,19 @@ def generate_class_mdx(
509 lines.append(f"`{method['return_type']}`")
510 lines.append("")
511
512 + # Raises
513 + raises = method.get("raises") or []
514 + if raises:
515 + lines.append("**Raises**")
516 + lines.append("")
517 + for entry in raises:
518 + exc_desc = entry["description"]
519 + if exc_desc:
520 + lines.append(f"- `{entry['exception']}` — {exc_desc}")
521 + else:
522 + lines.append(f"- `{entry['exception']}`")
523 + lines.append("")
524 +
525 # Examples
526 if method["examples"]:
527 lines.append("**Example**")
python/tests/test_generate_docs.py
+135
@@ -4,6 +4,7 @@ from __future__ import annotations
4
5 import ast
6 import importlib.util
7 +import re
8 from pathlib import Path
9
10 import pytest
@@ -37,6 +38,140 @@ def test_triggers_parse_generated_example_is_valid_python():
38 )
39
40
41 +def test_parse_docstring_extracts_raises_after_returns():
42 + generate_docs = load_generate_docs_module()
43 +
44 + parsed = generate_docs.parse_docstring(
45 + """
46 + Verify a webhook.
47 +
48 + :param secret: The webhook secret
49 + :return: VerifyWebhookResult containing version and payload
50 + :raises WebhookSignatureVerificationError: If the signature verification fails
51 + :raises WebhookPayloadError: If the payload cannot be parsed
52 + """
53 + )
54 +
55 + assert parsed["returns"] == "VerifyWebhookResult containing version and payload"
56 + assert parsed["raises"] == [
57 + {
58 + "exception": "WebhookSignatureVerificationError",
59 + "description": "If the signature verification fails",
60 + },
61 + {
62 + "exception": "WebhookPayloadError",
63 + "description": "If the payload cannot be parsed",
64 + },
65 + ]
66 +
67 +
68 +def test_parse_docstring_keeps_raises_continuation_lines():
69 + generate_docs = load_generate_docs_module()
70 +
71 + parsed = generate_docs.parse_docstring(
72 + """
73 + Fetch a tool.
74 +
75 + :raises ToolNotFoundError: when the backend reports the slug as unknown
76 + (404, or 400 for a malformed slug). Any other client error is
77 + re-raised unchanged.
78 + """
79 + )
80 +
81 + assert parsed["raises"] == [
82 + {
83 + "exception": "ToolNotFoundError",
84 + "description": (
85 + "when the backend reports the slug as unknown (404, or 400 for a "
86 + "malformed slug). Any other client error is re-raised unchanged."
87 + ),
88 + }
89 + ]
90 +
91 +
92 +def test_parse_docstring_normalizes_double_backtick_literals():
93 + generate_docs = load_generate_docs_module()
94 +
95 + parsed = generate_docs.parse_docstring(
96 + """
97 + Parse a webhook. Pass ``body=`` explicitly. Uses ``verify_secret``.
98 +
99 + :return: the normalized payload for ``verify_secret``
100 + :raises ValidationError: If ``verify_secret`` is empty
101 + """
102 + )
103 +
104 + assert "``" not in parsed["description"]
105 + assert "`verify_secret`" in parsed["description"]
106 + assert "`verify_secret`" in parsed["returns"]
107 + assert "`verify_secret`" in parsed["raises"][0]["description"]
108 +
109 +
110 +def test_parse_docstring_normalizes_rst_roles():
111 + generate_docs = load_generate_docs_module()
112 +
113 + parsed = generate_docs.parse_docstring(
114 + """
115 + Build a ``Modifier`` for the file-upload hook (same scoping pattern as
116 + :func:`before_execute`). Raises :class:`~composio.exceptions.FileUploadAbortedError`
117 + on abort; see :meth:`composio.core.models.tools.Tools.execute`.
118 + """
119 + )
120 +
121 + description = parsed["description"]
122 + assert "`Modifier`" in description
123 + assert ":func:" not in description
124 + assert "`before_execute`" in description
125 + assert ":class:" not in description
126 + assert "`FileUploadAbortedError`" in description
127 + assert "`composio.core.models.tools.Tools.execute`" in description
128 +
129 +
130 +def test_generated_mdx_renders_raises_section_without_raw_directives():
131 + generate_docs = load_generate_docs_module()
132 +
133 + info = {
134 + "name": "Triggers",
135 + "access": "composio.triggers",
136 + "source_link": None,
137 + "description": "Trigger management.",
138 + "deprecated": None,
139 + "properties": [],
140 + "methods": [
141 + {
142 + "name": "verify_webhook",
143 + "source_link": None,
144 + "description": "Verify a signed webhook request.",
145 + "parameters": [],
146 + "return_type": "VerifyWebhookResult",
147 + "return_description": "The verified payload",
148 + "raises": [
149 + {
150 + "exception": "WebhookSignatureVerificationError",
151 + "description": "If the signature verification fails",
152 + },
153 + {"exception": "WebhookPayloadError", "description": ""},
154 + ],
155 + "examples": [],
156 + }
157 + ],
158 + }
159 +
160 + mdx = generate_docs.generate_class_mdx(info)
161 +
162 + # Strip legitimate ```python fences before checking for stray reST markup.
163 + prose = re.sub(r"```.*?```", "", mdx, flags=re.DOTALL)
164 +
165 + assert ":raises" not in mdx
166 + assert "``" not in prose
167 + assert "**Raises**" in mdx
168 + assert (
169 + "- `WebhookSignatureVerificationError` — If the signature verification "
170 + "fails" in mdx
171 + )
172 + assert "- `WebhookPayloadError`" in mdx
173 +
174 +
175 def test_generated_examples_do_not_keep_nested_markdown_fences():
176 generate_docs = load_generate_docs_module()
177