code-documentation
Automatically generate clear, comprehensive documentation for codebases — including API references, inline docstrings, README files, and usage guides. Use when the user requests code documentation or provides relevant inputs for this workflow.
git clone --depth 1 https://github.com/seb1n/awesome-ai-agent-skills /tmp/code-documentation && cp -r /tmp/code-documentation/code-and-development/code-documentation ~/.claude/skills/code-documentationSKILL.md
# Code Documentation
This skill enables an AI agent to analyze source code and produce high-quality documentation in multiple formats. It covers everything from single-function docstrings to full project README files, ensuring that both human developers and downstream tooling (IDEs, doc generators) benefit from consistent, accurate descriptions.
## Workflow
1. **Inventory the Codebase**: Walk the project tree and catalog public modules, classes, functions, constants, and type definitions. Note which symbols already have documentation and which are missing or stale.
2. **Determine Documentation Scope**: Based on the user's request, decide whether to generate inline docstrings, a standalone API reference, a project-level README, or a combination. Match the output format to the project's existing conventions (JSDoc, Google-style Python docstrings, TypeDoc, RDoc, etc.).
3. **Analyze Signatures and Behavior**: For each symbol, inspect parameter types, return types, default values, raised exceptions, and side effects. Read surrounding test files when available to understand intended usage and edge cases.
4. **Generate Documentation**: Write documentation that includes a one-line summary, an extended description when the logic is non-trivial, parameter and return-value documentation with types, exception/error documentation, and at least one usage example for public API surfaces.
5. **Insert or Update In-Place**: For inline documentation (docstrings, JSDoc comments), insert the generated text directly above or inside the relevant symbol. For standalone files (README, API reference), create or update the Markdown file at the project root or a `docs/` directory.
6. **Validate and Cross-Reference**: Verify that documented parameter names match the actual signature, that referenced types exist, and that examples are syntactically valid. Flag any inconsistencies for the user to review.
## Supported Formats
- **Python**: Google-style docstrings, NumPy-style docstrings, Sphinx reStructuredText
- **JavaScript / TypeScript**: JSDoc (`@param`, `@returns`, `@throws`), TypeDoc annotations
- **Java**: Javadoc (`@param`, `@return`, `@throws`)
- **Go**: Godoc comment conventions (comment block immediately above the declaration)
- **Rust**: `///` doc comments with Markdown, `#[doc]` attributes
- **Ruby**: YARD (`@param`, `@return`, `@example`)
- **Markdown**: README files, CHANGELOG entries, architecture decision records (ADRs)
## Usage
Point the agent at a file, directory, or specific symbol and describe what documentation you need. Examples of valid requests:
- "Add Google-style docstrings to every public function in `src/services/`."
- "Generate a README for this project based on its structure and package.json."
- "Document this class with JSDoc, including examples for each method."
The agent will respect existing documentation style in the project. If no convention is detected, it will ask which format to use or default to the most common style for the language.
## Examples
### Example 1 — Documenting a Python Class with Google-Style Docstrings
**User Request**: "Add docstrings to this class and its methods."
**Before**:
```python
class TokenBucket:
def __init__(self, capacity, refill_rate):
self.capacity = capacity
self.tokens = capacity
self.refill_rate = refill_rate
self._last_refill = time.monotonic()
def consume(self, tokens=1):
self._refill()
if self.tokens >= tokens:
self.tokens -= tokens
return True
return False
def _refill(self):
now = time.monotonic()
elapsed = now - self._last_refill
self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate)
self._last_refill = now
```
**After**:
```python
class TokenBucket:
"""A token-bucket rate limiter.
Tokens are added at a constant rate and consumed by callers.
When the bucket is empty, requests are rejected until enough
tokens have accumulated.
Args:
capacity: Maximum number of tokens the bucket can hold.
refill_rate: Tokens added per second.
Example:
>>> bucket = TokenBucket(capacity=10, refill_rate=2)
>>> bucket.consume(3)
True
"""
def __init__(self, capacity: float, refill_rate: float) -> None:
self.capacity = capacity
self.tokens = capacity
self.refill_rate = refill_rate
self._last_refill = time.monotonic()
def consume(self, tokens: int = 1) -> bool:
"""Attempt to consume tokens from the bucket.
Triggers an internal refill based on elapsed time before
checking availability.
Args:
tokens: Number of tokens to consume. Defaults to 1.
Returns:
True if the tokens were available and consumed, False otherwise.
"""
self._refill()
if self.tokens >= tokens:
self.tokens -= tokens
return True
return False
def _refill(self) -> None:
"""Refill the bucket based on time elapsed since the last refill."""
now = time.monotonic()
elapsed = now - self._last_refill
self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate)
self._last_refill = now
```
### Example 2 — Generating a Project README from Structure
**User Request**: "Generate a README for this project."
Given a project with the following layout:
```
myapi/
├── package.json (name: @acme/myapi, scripts: dev, build, test)
├── src/
│ ├── index.ts (Express app entry point)
│ ├── routes/
│ │ ├── users.ts
│ │ └── orders.ts
│ └── middleware/
│ └── auth.ts
├── tests/
│ └── users.test.ts
└── Dockerfile
```
**Generated README.md**:
```markdown
# @acme/myapi
A RESTful API service built with Express and TypeScript.
## Getting Started
### Prerequisites
- Node.js >= 18
- npm or yarn
### Installation
git clone https://github.com/aDesign reproducible evaluations for AI agents with representative task sets, explicit rubrics, appropriate graders, baselines, regression gates, and failure analysis. Use when defining agent quality, comparing prompts or models, validating a release, measuring tool-use reliability, investigating regressions, or deciding whether an agent is ready for production.
Design privacy-aware observability for AI agents using traces, spans, structured events, metrics, cost attribution, dashboards, alerts, and investigation workflows. Use when instrumenting an agent, debugging intermittent tool or model failures, defining service-level objectives, analyzing latency or spend, auditing agent decisions, or preparing production monitoring.
Design and verify auditable human oversight, approval gates, escalation paths, and safe state transitions for AI agent workflows. Use when deciding which agent actions require review, adding approve/reject or dual-control flows, preventing unauthorized autonomous effects, creating decision records, reducing rubber-stamping, or recovering safely from rejected, expired, or failed actions.
Design, implement, harden, and verify Model Context Protocol (MCP) servers with precise tool contracts, least-privilege authorization, safe transports, structured errors, and interoperability tests. Use when creating a new MCP server, exposing an API or data source through MCP, reviewing an MCP server design, adding or revising MCP tools, or preparing an MCP server for production.
Design and operate bounded multi-agent workflows with task decomposition, dependency graphs, ownership, handoff contracts, shared-state controls, approvals, recovery, and synthesis. Use when a task contains genuinely independent workstreams, specialized roles, parallel research or implementation, reviewer-worker loops, or coordination problems that one agent should not execute sequentially.
Design and validate model-facing tool definitions with clear names, action-oriented descriptions, bounded JSON Schema parameters, explicit side effects, safe defaults, idempotency, errors, and realistic tests. Use when creating function-calling tools, MCP tools, agent actions, structured tool inputs, or when a model selects the wrong tool, invents arguments, or causes unsafe side effects.
Plan, execute, document, and retest authorized security assessments of AI agents and multi-agent workflows using safe adversarial cases, synthetic identities, canaries, and evidence-based findings. Use when defining red-team rules of engagement, assessing prompt injection or excessive agency, testing tool and identity boundaries, evaluating memory or cross-agent attacks, scoring a campaign, or verifying remediation in an approved environment.
Threat-model and harden AI agents, RAG systems, assistants, and tool-using workflows against direct, indirect, stored, cross-agent, and multimodal prompt injection. Use when reviewing an agent architecture, isolating untrusted content, constraining tools and egress, protecting secrets, adding injection-focused tests, investigating a suspected injection incident, or documenting residual prompt-injection risk.