Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | Python SDK Documentation Generator |
| 4 | |
| 5 | Generates MDX documentation from Python source code using griffe. |
| 6 | Output is written to the docs content directory. |
| 7 | |
| 8 | Run: cd python && uv run --frozen --only-group docs-reference python scripts/generate-docs.py |
| 9 | """ |
| 10 | |
| 11 | from __future__ import annotations |
| 12 | |
| 13 | import json |
| 14 | import re |
| 15 | import shutil |
| 16 | import textwrap |
| 17 | from pathlib import Path |
| 18 | from typing import Any |
| 19 | |
| 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( |
| 36 | "Error: griffe not installed. Run: " |
| 37 | "uv run --frozen --only-group docs-reference python scripts/generate-docs.py" |
| 38 | ) |
| 39 | raise SystemExit(1) |
| 40 | _griffe = griffe_module |
| 41 | return _griffe |
| 42 | |
| 43 | |
| 44 | # Paths |
| 45 | SCRIPT_DIR = Path(__file__).parent |
| 46 | PACKAGE_DIR = SCRIPT_DIR.parent |
| 47 | OUTPUT_DIR = ( |
| 48 | PACKAGE_DIR.parent / "docs" / "content" / "reference" / "sdk-reference" / "python" |
| 49 | ) |
| 50 | |
| 51 | # GitHub base URL for source links |
| 52 | GITHUB_BASE = "https://github.com/composiohq/composio/blob/next/python" |
| 53 | |
| 54 | # Decorators to document |
| 55 | DECORATORS_TO_DOCUMENT = [ |
| 56 | ("before_execute", "composio.core.models._modifiers"), |
| 57 | ("after_execute", "composio.core.models._modifiers"), |
| 58 | ("before_file_upload", "composio.core.models._modifiers"), |
| 59 | ("schema_modifier", "composio.core.models._modifiers"), |
| 60 | ] |
| 61 | |
| 62 | # Classes to skip (internal/helper classes) |
| 63 | SKIP_CLASSES = {"WithLogger", "SDKConfig", "TProvider"} |
| 64 | |
| 65 | # Expected classes to document (maps class name -> property name on Composio) |
| 66 | EXPECTED_CLASSES = { |
| 67 | "Tools": "tools", |
| 68 | "Toolkits": "toolkits", |
| 69 | "Triggers": "triggers", |
| 70 | "ConnectedAccounts": "connected_accounts", |
| 71 | "AuthConfigs": "auth_configs", |
| 72 | "MCP": "mcp", |
| 73 | } |
| 74 | |
| 75 | # Additional public-facing classes worth documenting even though they are not |
| 76 | # exposed as direct properties on ``Composio``. |
| 77 | # |
| 78 | # ``SessionContextImpl`` is intentionally omitted: it is an internal |
| 79 | # implementation detail handed to custom-tool execute functions as a |
| 80 | # ``SessionContext`` instance, never referenced directly, so it must not |
| 81 | # appear in the public SDK reference. |
| 82 | ADDITIONAL_CLASSES = { |
| 83 | "ToolRouterSession": "core.models.tool_router_session", |
| 84 | } |
| 85 | |
| 86 | # Modules to search for classes |
| 87 | CLASS_MODULES = [ |
| 88 | "core.models.tools", |
| 89 | "core.models.toolkits", |
| 90 | "core.models.triggers", |
| 91 | "core.models.connected_accounts", |
| 92 | "core.models.auth_configs", |
| 93 | "core.models.mcp", |
| 94 | ] |
| 95 | |
| 96 | # Pure-docs presentation overrides. The public class name ``ToolRouterSession`` |
| 97 | # is kept in source (renaming is a breaking change), but the SDK reference |
| 98 | # presents the session object under the canonical "Session" naming. |
| 99 | DISPLAY_NAME_OVERRIDES = { |
| 100 | "ToolRouterSession": "Session", |
| 101 | } |
| 102 | |
| 103 | SLUG_OVERRIDES = { |
| 104 | "ToolRouterSession": "session", |
| 105 | } |
| 106 | |
| 107 | |
| 108 | def to_kebab_case(name: str) -> str: |
| 109 | """Convert PascalCase to kebab-case.""" |
| 110 | s1 = re.sub("(.)([A-Z][a-z]+)", r"\1-\2", name) |
| 111 | return re.sub("([a-z0-9])([A-Z])", r"\1-\2", s1).lower() |
| 112 | |
| 113 | |
| 114 | def display_name_for(class_name: str) -> str: |
| 115 | """Resolve the display title for a class (falls back to the class name).""" |
| 116 | return DISPLAY_NAME_OVERRIDES.get(class_name, class_name) |
| 117 | |
| 118 | |
| 119 | def slug_for(class_name: str) -> str: |
| 120 | """Resolve the URL slug / filename stem (falls back to kebab-case).""" |
| 121 | return SLUG_OVERRIDES.get(class_name, to_kebab_case(class_name)) |
| 122 | |
| 123 | |
| 124 | def escape_yaml_string(s: str) -> str: |
| 125 | """Escape a string for YAML frontmatter.""" |
| 126 | return json.dumps(s) |
| 127 | |
| 128 | |
| 129 | def get_source_link(obj: griffe_t.Object) -> str | None: |
| 130 | """Get GitHub source link for an object.""" |
| 131 | if not hasattr(obj, "filepath") or not obj.filepath: |
| 132 | return None |
| 133 | try: |
| 134 | raw_filepath = obj.filepath |
| 135 | # Handle case where filepath might be a list (griffe edge case) |
| 136 | if isinstance(raw_filepath, list): |
| 137 | resolved_path: Path | None = raw_filepath[0] if raw_filepath else None |
| 138 | else: |
| 139 | resolved_path = raw_filepath |
| 140 | if not resolved_path: |
| 141 | return None |
| 142 | rel_path = resolved_path.relative_to(PACKAGE_DIR) |
| 143 | except ValueError: |
| 144 | return None |
| 145 | line = obj.lineno if hasattr(obj, "lineno") and obj.lineno else 1 |
| 146 | return f"{GITHUB_BASE}/{rel_path}#L{line}" |
| 147 | |
| 148 | |
| 149 | def _matching_bracket(text: str, open_index: int) -> int | None: |
| 150 | """Return the index of the ``]`` closing the ``[`` at ``open_index``. |
| 151 | |
| 152 | Brackets inside quoted strings, such as ``Literal['[']``, are ignored. |
| 153 | """ |
| 154 | depth = 0 |
| 155 | quote: str | None = None |
| 156 | escaped = False |
| 157 | for index in range(open_index, len(text)): |
| 158 | char = text[index] |
| 159 | if quote is not None: |
| 160 | if escaped: |
| 161 | escaped = False |
| 162 | elif char == "\\": |
| 163 | escaped = True |
| 164 | elif char == quote: |
| 165 | quote = None |
| 166 | elif char in ("'", '"'): |
| 167 | quote = char |
| 168 | elif char == "[": |
| 169 | depth += 1 |
| 170 | elif char == "]": |
| 171 | depth -= 1 |
| 172 | if depth == 0: |
| 173 | return index |
| 174 | return None |
| 175 | |
| 176 | |
| 177 | def _rewrite_subscript(type_str: str, name: str, render: t.Callable[[str], str]) -> str: |
| 178 | """Replace every ``name[...]`` with ``render(...)``, honoring nested brackets. |
| 179 | |
| 180 | The outermost occurrence is rewritten first, and the search restarts from |
| 181 | the beginning so occurrences nested in its arguments are rewritten too. |
| 182 | """ |
| 183 | pattern = re.compile(rf"(?<!\w){re.escape(name)}\[") |
| 184 | while match := pattern.search(type_str): |
| 185 | open_index = match.end() - 1 |
| 186 | close_index = _matching_bracket(type_str, open_index) |
| 187 | if close_index is None: |
| 188 | break |
| 189 | inner = type_str[open_index + 1 : close_index] |
| 190 | type_str = ( |
| 191 | type_str[: match.start()] + render(inner) + type_str[close_index + 1 :] |
| 192 | ) |
| 193 | return type_str |
| 194 | |
| 195 | |
| 196 | def format_type( |
| 197 | annotation: Any, *, max_length: int | None = 60, unwrap_unpack: bool = True |
| 198 | ) -> str: |
| 199 | """Format a type annotation to readable string. |
| 200 | |
| 201 | Types longer than ``max_length`` are elided; pass ``None`` to keep the |
| 202 | full type, which parameter signatures need so quoted forward references |
| 203 | such as ``'Omit'`` are never cut mid-token. |
| 204 | """ |
| 205 | if annotation is None: |
| 206 | return "Any" |
| 207 | |
| 208 | type_str = str(annotation) |
| 209 | # Clean up common prefixes |
| 210 | type_str = type_str.replace("typing.", "").replace("typing_extensions.", "") |
| 211 | type_str = type_str.replace("composio.client.types.", "") |
| 212 | type_str = re.sub(r"\bt\.", "", type_str) |
| 213 | type_str = re.sub(r"\bte\.", "", type_str) # typing_extensions alias |
| 214 | type_str = _rewrite_subscript(type_str, "Optional", lambda inner: f"{inner} | None") |
| 215 | if unwrap_unpack: |
| 216 | type_str = _rewrite_subscript(type_str, "Unpack", lambda inner: inner) |
| 217 | |
| 218 | # Truncate very long types |
| 219 | if max_length is not None and len(type_str) > max_length: |
| 220 | return type_str[: max_length - 3] + "..." |
| 221 | return type_str |
| 222 | |
| 223 | |
| 224 | def _render_rst_role(match: re.Match[str]) -> str: |
| 225 | """Render an reST role match as inline code, honoring ``~`` short names.""" |
| 226 | target = match.group(1) |
| 227 | if target.startswith("~"): |
| 228 | target = target.rsplit(".", 1)[-1] |
| 229 | return f"`{target}`" |
| 230 | |
| 231 | |
| 232 | def normalize_inline_rst(text: str) -> str: |
| 233 | """Normalize inline reStructuredText markup to MDX-friendly markdown. |
| 234 | |
| 235 | Converts reST roles such as ``:class:`Foo` `` into plain inline code and |
| 236 | reST double-backtick literals (``name``) into single-backtick inline code |
| 237 | so generated prose renders correctly on the docs site. A ``~`` role prefix |
| 238 | (``:class:`~mod.Foo` ``) renders as the short target name, matching Sphinx. |
| 239 | """ |
| 240 | if not text: |
| 241 | return text |
| 242 | # ReST roles: :class:`X`, :func:`mod.func`, :meth:`X.y`, :mod:`~pkg.mod`, |
| 243 | # ... A leading ``~`` requests the short target name, so drop the path. |
| 244 | normalized = re.sub(r":[a-zA-Z]+:`([^`]+)`", _render_rst_role, text) |
| 245 | # ReST double-backtick literals: ``name`` -> `name` |
| 246 | return re.sub(r"``([^`]+)``", r"`\1`", normalized) |
| 247 | |
| 248 | |
| 249 | def parse_docstring(docstring: str | None) -> dict[str, Any]: |
| 250 | """Parse docstring into components.""" |
| 251 | if not docstring: |
| 252 | return { |
| 253 | "description": "", |
| 254 | "params": {}, |
| 255 | "returns": None, |
| 256 | "examples": [], |
| 257 | "raises": [], |
| 258 | "deprecated": None, |
| 259 | } |
| 260 | |
| 261 | lines = docstring.strip().split("\n") |
| 262 | description_lines = [] |
| 263 | params: dict[str, str] = {} |
| 264 | returns = None |
| 265 | examples: list[str] = [] |
| 266 | raises: list[dict[str, str]] = [] |
| 267 | deprecated_lines: list[str] = [] |
| 268 | |
| 269 | section = "description" |
| 270 | current_param = None |
| 271 | current_raise: dict[str, str] | None = None |
| 272 | example_lines: list[str] = [] |
| 273 | |
| 274 | for line in lines: |
| 275 | stripped = line.strip() |
| 276 | |
| 277 | # Check for a ``.. deprecated::`` directive (reStructuredText). |
| 278 | if re.match(r"\.\.\s+deprecated::", stripped): |
| 279 | section = "deprecated" |
| 280 | rest = re.sub(r"\.\.\s+deprecated::\s*", "", stripped).strip() |
| 281 | if rest: |
| 282 | deprecated_lines.append(rest) |
| 283 | continue |
| 284 | |
| 285 | # Check for :param name: description |
| 286 | param_match = re.match(r":param\s+(\w+):\s*(.*)", stripped) |
| 287 | if param_match: |
| 288 | section = "params" |
| 289 | current_param = param_match.group(1) |
| 290 | params[current_param] = param_match.group(2) |
| 291 | continue |
| 292 | |
| 293 | # Check for :returns: or :return: |
| 294 | return_match = re.match(r":returns?:\s*(.*)", stripped) |
| 295 | if return_match: |
| 296 | section = "returns" |
| 297 | returns = return_match.group(1) |
| 298 | continue |
| 299 | |
| 300 | # Check for :raises Exc: description (plus common Sphinx synonyms). |
| 301 | raise_match = re.match( |
| 302 | r":(?:raises?|except|throws?)\s+([\w.]+):\s*(.*)", stripped |
| 303 | ) |
| 304 | if raise_match: |
| 305 | section = "raises" |
| 306 | current_raise = { |
| 307 | "exception": raise_match.group(1), |
| 308 | "description": raise_match.group(2).strip(), |
| 309 | } |
| 310 | raises.append(current_raise) |
| 311 | continue |
| 312 | |
| 313 | # Check for Example section |
| 314 | if stripped.lower().startswith("example"): |
| 315 | section = "examples" |
| 316 | continue |
| 317 | |
| 318 | # Add to appropriate section |
| 319 | if section == "description": |
| 320 | description_lines.append(stripped) |
| 321 | elif section == "params" and current_param and stripped: |
| 322 | params[current_param] += " " + stripped |
| 323 | elif section == "returns" and returns and stripped: |
| 324 | returns += " " + stripped |
| 325 | elif section == "raises" and current_raise is not None and stripped: |
| 326 | current_raise["description"] = ( |
| 327 | current_raise["description"] + " " + stripped |
| 328 | ).strip() |
| 329 | elif section == "examples": |
| 330 | example_lines.append(line) |
| 331 | elif section == "deprecated" and stripped: |
| 332 | deprecated_lines.append(stripped) |
| 333 | |
| 334 | if example_lines: |
| 335 | examples.append(normalize_example("\n".join(example_lines))) |
| 336 | |
| 337 | return { |
| 338 | "description": normalize_inline_rst(" ".join(description_lines).strip()), |
| 339 | "params": {name: normalize_inline_rst(desc) for name, desc in params.items()}, |
| 340 | "returns": normalize_inline_rst(returns) if returns else None, |
| 341 | "examples": examples, |
| 342 | "raises": [ |
| 343 | { |
| 344 | "exception": entry["exception"], |
| 345 | "description": normalize_inline_rst(entry["description"]), |
| 346 | } |
| 347 | for entry in raises |
| 348 | ], |
| 349 | "deprecated": ( |
| 350 | normalize_inline_rst(" ".join(deprecated_lines).strip()) |
| 351 | if deprecated_lines |
| 352 | else None |
| 353 | ), |
| 354 | } |
| 355 | |
| 356 | |
| 357 | def normalize_example(example: str) -> str: |
| 358 | """Normalize a docstring example before wrapping it in an MDX code fence.""" |
| 359 | normalized = textwrap.dedent(example).strip() |
| 360 | lines = normalized.splitlines() |
| 361 | |
| 362 | if len(lines) >= 2 and lines[0].strip().startswith("```"): |
| 363 | closing_index = len(lines) - 1 |
| 364 | if lines[closing_index].strip() == "```": |
| 365 | normalized = "\n".join(lines[1:closing_index]).strip() |
| 366 | |
| 367 | return normalized |
| 368 | |
| 369 | |
| 370 | def extract_class_info( |
| 371 | cls: griffe_t.Class, class_name: str, config: dict |
| 372 | ) -> dict[str, Any]: |
| 373 | """Extract documentation from a class.""" |
| 374 | griffe_module = load_griffe() |
| 375 | doc = parse_docstring(cls.docstring.value if cls.docstring else None) |
| 376 | |
| 377 | info = { |
| 378 | "name": class_name, |
| 379 | "access": config.get("access"), |
| 380 | "source_link": get_source_link(cls), |
| 381 | "description": doc["description"], |
| 382 | "deprecated": doc.get("deprecated"), |
| 383 | "properties": [], |
| 384 | "methods": [], |
| 385 | } |
| 386 | |
| 387 | # Extract properties/attributes |
| 388 | for name, member in cls.members.items(): |
| 389 | if name.startswith("_"): |
| 390 | continue |
| 391 | if isinstance(member, griffe_module.Attribute): |
| 392 | attr_doc = member.docstring.value if member.docstring else "" |
| 393 | info["properties"].append( |
| 394 | { |
| 395 | "name": name, |
| 396 | "type": format_type(member.annotation), |
| 397 | "description": ( |
| 398 | normalize_inline_rst(attr_doc.strip()) if attr_doc else "" |
| 399 | ), |
| 400 | } |
| 401 | ) |
| 402 | |
| 403 | # Extract methods |
| 404 | for name, member in cls.members.items(): |
| 405 | if name.startswith("_"): |
| 406 | continue |
| 407 | if isinstance(member, griffe_module.Function): |
| 408 | method_doc = parse_docstring( |
| 409 | member.docstring.value if member.docstring else None |
| 410 | ) |
| 411 | |
| 412 | params = [] |
| 413 | for p in member.parameters: |
| 414 | if p.name in ("self", "cls"): |
| 415 | continue |
| 416 | params.append( |
| 417 | { |
| 418 | "name": p.name, |
| 419 | "kind": p.kind.value if p.kind else None, |
| 420 | "type": format_type( |
| 421 | p.annotation, |
| 422 | max_length=None, |
| 423 | unwrap_unpack=p.kind |
| 424 | != griffe_module.ParameterKind.var_keyword, |
| 425 | ), |
| 426 | "optional": p.default is not None, |
| 427 | "description": method_doc["params"].get(p.name, ""), |
| 428 | } |
| 429 | ) |
| 430 | |
| 431 | info["methods"].append( |
| 432 | { |
| 433 | "name": name, |
| 434 | "source_link": get_source_link(member), |
| 435 | "description": method_doc["description"], |
| 436 | "parameters": params, |
| 437 | "return_type": format_type(member.returns), |
| 438 | "return_description": method_doc["returns"], |
| 439 | "raises": method_doc["raises"], |
| 440 | "examples": method_doc["examples"], |
| 441 | } |
| 442 | ) |
| 443 | |
| 444 | return info |
| 445 | |
| 446 | |
| 447 | def format_method_parameters(parameters: list[dict[str, Any]]) -> str: |
| 448 | """Preserve the parameter kinds that constrain how a method is called.""" |
| 449 | parts = [] |
| 450 | previous_kind = None |
| 451 | has_star = False |
| 452 | for param in parameters: |
| 453 | kind = param["kind"] |
| 454 | if previous_kind == "positional-only" and kind != previous_kind: |
| 455 | parts.append("/") |
| 456 | if kind == "keyword-only" and not has_star: |
| 457 | parts.append("*") |
| 458 | has_star = True |
| 459 | |
| 460 | name = param["name"] |
| 461 | if kind == "variadic positional": |
| 462 | name = f"*{name}" |
| 463 | has_star = True |
| 464 | elif kind == "variadic keyword": |
| 465 | name = f"**{name}" |
| 466 | part = f"{name}: {param['type']}" |
| 467 | if param["optional"] and kind not in ( |
| 468 | "variadic positional", |
| 469 | "variadic keyword", |
| 470 | ): |
| 471 | part += " = ..." |
| 472 | parts.append(part) |
| 473 | previous_kind = kind |
| 474 | |
| 475 | if previous_kind == "positional-only": |
| 476 | parts.append("/") |
| 477 | return ", ".join(parts) |
| 478 | |
| 479 | |
| 480 | def generate_class_mdx( |
| 481 | info: dict[str, Any], prop_to_class: dict[str, str] | None = None |
| 482 | ) -> str: |
| 483 | """Generate MDX for a class.""" |
| 484 | lines = [] |
| 485 | |
| 486 | # Frontmatter |
| 487 | desc = ( |
| 488 | info["description"].split("\n")[0] |
| 489 | if info["description"] |
| 490 | else f"{info['name']} class" |
| 491 | ) |
| 492 | if len(desc) > 150: |
| 493 | desc = desc[:147] + "..." |
| 494 | |
| 495 | lines.append("---") |
| 496 | lines.append(f"title: {escape_yaml_string(display_name_for(info['name']))}") |
| 497 | lines.append(f"description: {escape_yaml_string(desc)}") |
| 498 | lines.append("---") |
| 499 | lines.append("") |
| 500 | |
| 501 | # Class-level deprecation callout (rendered as a fumadocs warning callout). |
| 502 | deprecated_note = info.get("deprecated") |
| 503 | if deprecated_note: |
| 504 | lines.append('<Callout type="warn" title="Deprecated">') |
| 505 | lines.append(deprecated_note) |
| 506 | lines.append("</Callout>") |
| 507 | lines.append("") |
| 508 | |
| 509 | source_link = info.get("source_link", "") |
| 510 | |
| 511 | # Properties |
| 512 | property_rows = [] |
| 513 | if info["properties"]: |
| 514 | if prop_to_class: |
| 515 | for prop in info["properties"]: |
| 516 | prop_name = prop["name"] |
| 517 | if prop_name in prop_to_class: |
| 518 | class_name = prop_to_class[prop_name] |
| 519 | link = ( |
| 520 | f"/reference/sdk-reference/python/{to_kebab_case(class_name)}" |
| 521 | ) |
| 522 | property_rows.append( |
| 523 | { |
| 524 | "name": f"[`{prop_name}`]({link})", |
| 525 | "type": f"`{class_name}`", |
| 526 | "description": prop["description"], |
| 527 | } |
| 528 | ) |
| 529 | elif info["name"] in ADDITIONAL_CLASSES: |
| 530 | for prop in info["properties"]: |
| 531 | property_rows.append( |
| 532 | { |
| 533 | "name": f"`{prop['name']}`", |
| 534 | "type": f"`{prop['type']}`", |
| 535 | "description": prop["description"], |
| 536 | } |
| 537 | ) |
| 538 | |
| 539 | if property_rows: |
| 540 | include_descriptions = any(row["description"] for row in property_rows) |
| 541 | lines.append("## Properties") |
| 542 | lines.append("") |
| 543 | if include_descriptions: |
| 544 | lines.append("| Name | Type | Description |") |
| 545 | lines.append("|------|------|-------------|") |
| 546 | for row in property_rows: |
| 547 | lines.append( |
| 548 | f"| {row['name']} | {row['type']} | {row['description']} |" |
| 549 | ) |
| 550 | else: |
| 551 | lines.append("| Name | Type |") |
| 552 | lines.append("|------|------|") |
| 553 | for row in property_rows: |
| 554 | lines.append(f"| {row['name']} | {row['type']} |") |
| 555 | lines.append("") |
| 556 | |
| 557 | # Methods |
| 558 | if info["methods"]: |
| 559 | lines.append("## Methods") |
| 560 | lines.append("") |
| 561 | |
| 562 | for method in info["methods"]: |
| 563 | lines.append(f"### {method['name']}()") |
| 564 | lines.append("") |
| 565 | |
| 566 | if method["description"]: |
| 567 | lines.append(method["description"]) |
| 568 | lines.append("") |
| 569 | |
| 570 | # Signature |
| 571 | params_str = format_method_parameters(method["parameters"]) |
| 572 | ret_type = method["return_type"] if method["return_type"] != "Any" else "" |
| 573 | sig = f"def {method['name']}({params_str})" |
| 574 | if ret_type: |
| 575 | sig += f" -> {ret_type}" |
| 576 | |
| 577 | lines.append("```python") |
| 578 | lines.append(sig) |
| 579 | lines.append("```") |
| 580 | lines.append("") |
| 581 | |
| 582 | # Parameters |
| 583 | if method["parameters"]: |
| 584 | lines.append("**Parameters**") |
| 585 | lines.append("") |
| 586 | include_descriptions = any( |
| 587 | p["description"] for p in method["parameters"] |
| 588 | ) |
| 589 | if include_descriptions: |
| 590 | lines.append("| Name | Type | Description |") |
| 591 | lines.append("|------|------|-------------|") |
| 592 | else: |
| 593 | lines.append("| Name | Type |") |
| 594 | lines.append("|------|------|") |
| 595 | for p in method["parameters"]: |
| 596 | opt = "?" if p["optional"] else "" |
| 597 | safe_type = p["type"].replace("|", "\\|") |
| 598 | parameter_row = f"| `{p['name']}{opt}` | `{safe_type}` |" |
| 599 | if include_descriptions: |
| 600 | description = p["description"].replace("|", "\\|") |
| 601 | parameter_row += f" {description} |" |
| 602 | lines.append(parameter_row) |
| 603 | lines.append("") |
| 604 | |
| 605 | # Returns |
| 606 | if method["return_type"] and method["return_type"] not in ("None", "Any"): |
| 607 | ret_desc = method["return_description"] or "" |
| 608 | lines.append("**Returns**") |
| 609 | lines.append("") |
| 610 | if ret_desc: |
| 611 | lines.append(f"`{method['return_type']}` — {ret_desc}") |
| 612 | else: |
| 613 | lines.append(f"`{method['return_type']}`") |
| 614 | lines.append("") |
| 615 | |
| 616 | # Raises |
| 617 | raises = method.get("raises") or [] |
| 618 | if raises: |
| 619 | lines.append("**Raises**") |
| 620 | lines.append("") |
| 621 | for entry in raises: |
| 622 | exc_desc = entry["description"] |
| 623 | if exc_desc: |
| 624 | lines.append(f"- `{entry['exception']}` — {exc_desc}") |
| 625 | else: |
| 626 | lines.append(f"- `{entry['exception']}`") |
| 627 | lines.append("") |
| 628 | |
| 629 | # Examples |
| 630 | if method["examples"]: |
| 631 | lines.append("**Example**") |
| 632 | lines.append("") |
| 633 | for ex in method["examples"]: |
| 634 | lines.append("```python") |
| 635 | lines.append(ex) |
| 636 | lines.append("```") |
| 637 | lines.append("") |
| 638 | |
| 639 | lines.append("---") |
| 640 | lines.append("") |
| 641 | |
| 642 | # Source link at bottom |
| 643 | if source_link: |
| 644 | lines.append(f"[View source]({source_link})") |
| 645 | lines.append("") |
| 646 | |
| 647 | return "\n".join(lines) |
| 648 | |
| 649 | |
| 650 | def generate_index_mdx(classes: list[dict], decorators: list[dict]) -> str: |
| 651 | """Generate index page.""" |
| 652 | |
| 653 | # Classes table |
| 654 | class_rows = [] |
| 655 | for c in classes: |
| 656 | link = f"/reference/sdk-reference/python/{slug_for(c['name'])}" |
| 657 | desc = ( |
| 658 | c["description"][:80] + "..." |
| 659 | if len(c["description"]) > 80 |
| 660 | else c["description"] |
| 661 | ) |
| 662 | class_rows.append(f"| [`{display_name_for(c['name'])}`]({link}) | {desc} |") |
| 663 | |
| 664 | # Decorators section |
| 665 | dec_section = "" |
| 666 | if decorators: |
| 667 | dec_lines = ["## Decorators", ""] |
| 668 | for d in decorators: |
| 669 | dec_lines.append(f"### {d['name']}") |
| 670 | dec_lines.append("") |
| 671 | if d["description"]: |
| 672 | dec_lines.append(d["description"]) |
| 673 | dec_lines.append("") |
| 674 | if d["source_link"]: |
| 675 | dec_lines.append(f"[View source]({d['source_link']})") |
| 676 | dec_lines.append("") |
| 677 | # Signature |
| 678 | params = ", ".join( |
| 679 | f"{p['name']}: {p['type']}" + (" = ..." if p["optional"] else "") |
| 680 | for p in d["parameters"] |
| 681 | ) |
| 682 | dec_lines.append("```python") |
| 683 | dec_lines.append(f"@{d['name']}({params})") |
| 684 | dec_lines.append("def my_modifier(...):") |
| 685 | dec_lines.append(" ...") |
| 686 | dec_lines.append("```") |
| 687 | dec_lines.append("") |
| 688 | dec_section = "\n".join(dec_lines) |
| 689 | |
| 690 | return f"""--- |
| 691 | title: {escape_yaml_string("Python SDK Reference")} |
| 692 | description: {escape_yaml_string("API reference for the Composio Python SDK")} |
| 693 | --- |
| 694 | |
| 695 | # Python SDK Reference |
| 696 | |
| 697 | Complete API reference for the `composio` Python package. |
| 698 | |
| 699 | ## Installation |
| 700 | |
| 701 | <PackageInstall ecosystem="python" packages="composio" /> |
| 702 | |
| 703 | ## Classes |
| 704 | |
| 705 | | Class | Description | |
| 706 | |-------|-------------| |
| 707 | {chr(10).join(class_rows)} |
| 708 | |
| 709 | ## Quick Start |
| 710 | |
| 711 | ```python |
| 712 | from composio import Composio |
| 713 | |
| 714 | composio = Composio(api_key="your-api-key") |
| 715 | |
| 716 | # Get tools for a user |
| 717 | tools = composio.tools.get("user-123", toolkits=["github"]) |
| 718 | |
| 719 | # Execute a tool |
| 720 | result = composio.tools.execute( |
| 721 | "GITHUB_GET_REPOS", |
| 722 | arguments={{"owner": "composio"}}, |
| 723 | user_id="user-123" |
| 724 | ) |
| 725 | ``` |
| 726 | |
| 727 | {dec_section} |
| 728 | """ |
| 729 | |
| 730 | |
| 731 | def main(): |
| 732 | griffe_module = load_griffe() |
| 733 | |
| 734 | print("Starting Python SDK documentation generation...\n") |
| 735 | print(f"Output: {OUTPUT_DIR}\n") |
| 736 | |
| 737 | # Clean output |
| 738 | if OUTPUT_DIR.exists(): |
| 739 | shutil.rmtree(OUTPUT_DIR) |
| 740 | OUTPUT_DIR.mkdir(parents=True) |
| 741 | |
| 742 | # Load package |
| 743 | print("Loading composio package...") |
| 744 | try: |
| 745 | package = griffe_module.load("composio", search_paths=[str(PACKAGE_DIR)]) |
| 746 | except Exception as e: |
| 747 | print(f"Error: {e}") |
| 748 | raise SystemExit(1) |
| 749 | |
| 750 | # Find Composio class |
| 751 | composio_cls = package.members["sdk"].members["Composio"] |
| 752 | print(" Found Composio class") |
| 753 | |
| 754 | # Discover classes from EXPECTED_CLASSES |
| 755 | classes_to_doc = {"Composio": {"cls": composio_cls, "access": None, "prop": None}} |
| 756 | prop_to_class = {} # Maps property name -> class name |
| 757 | |
| 758 | for module_name in CLASS_MODULES: |
| 759 | try: |
| 760 | parts = module_name.split(".") |
| 761 | current = package |
| 762 | for part in parts: |
| 763 | current = current.members[part] |
| 764 | |
| 765 | # Find expected classes in this module |
| 766 | for class_name, prop_name in EXPECTED_CLASSES.items(): |
| 767 | if class_name in current.members: |
| 768 | cls = current.members[class_name] |
| 769 | if isinstance(cls, griffe_module.Class): |
| 770 | classes_to_doc[class_name] = { |
| 771 | "cls": cls, |
| 772 | "access": f"composio.{prop_name}", |
| 773 | "prop": prop_name, |
| 774 | } |
| 775 | prop_to_class[prop_name] = class_name |
| 776 | print(f" Found {class_name} (via composio.{prop_name})") |
| 777 | except (KeyError, AttributeError): |
| 778 | continue |
| 779 | |
| 780 | # Add standalone public-facing classes that are not surfaced via a direct |
| 781 | # ``composio.<property>`` access pattern. |
| 782 | for class_name, module_name in ADDITIONAL_CLASSES.items(): |
| 783 | try: |
| 784 | parts = module_name.split(".") |
| 785 | current = package |
| 786 | for part in parts: |
| 787 | current = current.members[part] |
| 788 | |
| 789 | if class_name in current.members: |
| 790 | cls = current.members[class_name] |
| 791 | if isinstance(cls, griffe_module.Class): |
| 792 | classes_to_doc[class_name] = { |
| 793 | "cls": cls, |
| 794 | "access": None, |
| 795 | "prop": None, |
| 796 | } |
| 797 | print(f" Found {class_name}") |
| 798 | except (KeyError, AttributeError): |
| 799 | continue |
| 800 | |
| 801 | # Generate docs for each class |
| 802 | documented_classes = [] |
| 803 | |
| 804 | for class_name, config in classes_to_doc.items(): |
| 805 | cls = config["cls"] |
| 806 | print(f" Processing {class_name}...") |
| 807 | |
| 808 | info = extract_class_info(cls, class_name, {"access": config["access"]}) |
| 809 | |
| 810 | # Only Composio gets prop_to_class for linking |
| 811 | if class_name == "Composio": |
| 812 | mdx = generate_class_mdx(info, prop_to_class) |
| 813 | else: |
| 814 | mdx = generate_class_mdx(info, None) |
| 815 | |
| 816 | file_path = OUTPUT_DIR / f"{slug_for(class_name)}.mdx" |
| 817 | file_path.write_text(mdx) |
| 818 | |
| 819 | documented_classes.append( |
| 820 | { |
| 821 | "name": class_name, |
| 822 | "description": info["description"] or f"{class_name} class", |
| 823 | } |
| 824 | ) |
| 825 | |
| 826 | # Process decorators |
| 827 | decorators = [] |
| 828 | for dec_name, dec_module in DECORATORS_TO_DOCUMENT: |
| 829 | module_path = dec_module.split(".") |
| 830 | current = package |
| 831 | |
| 832 | for part in module_path[1:]: |
| 833 | if part in current.members: |
| 834 | current = current.members[part] |
| 835 | |
| 836 | if dec_name in current.members: |
| 837 | func = current.members[dec_name] |
| 838 | if isinstance(func, griffe_module.Function): |
| 839 | print(f" Processing decorator {dec_name}...") |
| 840 | doc = parse_docstring(func.docstring.value if func.docstring else None) |
| 841 | |
| 842 | params = [] |
| 843 | for p in func.parameters: |
| 844 | if p.name in ("self", "cls"): |
| 845 | continue |
| 846 | params.append( |
| 847 | { |
| 848 | "name": p.name, |
| 849 | "type": format_type(p.annotation, max_length=None), |
| 850 | "optional": p.default is not None, |
| 851 | "description": doc["params"].get(p.name, ""), |
| 852 | } |
| 853 | ) |
| 854 | |
| 855 | decorators.append( |
| 856 | { |
| 857 | "name": dec_name, |
| 858 | "source_link": get_source_link(func), |
| 859 | "description": doc["description"], |
| 860 | "parameters": params, |
| 861 | } |
| 862 | ) |
| 863 | |
| 864 | # Generate index |
| 865 | index_content = generate_index_mdx(documented_classes, decorators) |
| 866 | (OUTPUT_DIR / "index.mdx").write_text(index_content) |
| 867 | |
| 868 | # Generate meta.json |
| 869 | meta = { |
| 870 | "title": "Python SDK", |
| 871 | "pages": [slug_for(c["name"]) for c in documented_classes], |
| 872 | } |
| 873 | (OUTPUT_DIR / "meta.json").write_text(json.dumps(meta, indent=2)) |
| 874 | |
| 875 | print(f"\nDone! Generated {len(documented_classes)} class docs + index") |
| 876 | print(f" Classes: {', '.join(c['name'] for c in documented_classes)}") |
| 877 | print(f" Decorators: {', '.join(d['name'] for d in decorators)}") |
| 878 | |
| 879 | |
| 880 | if __name__ == "__main__": |
| 881 | main() |