Documentation Generation: Building a Doc-Writing Skill
Create a Claude Code skill that generates comprehensive documentation. From API docs to READMEs, automate your documentation workflow.
Create a Claude Code skill that generates comprehensive documentation. From API docs to READMEs, automate your documentation workflow.
Documentation is the part of software development everyone knows is important but nobody wants to do. It's tedious, time-consuming, and becomes outdated the moment code changes.
What if documentation wrote itself? What if every time you finished a feature, the docs were already there, accurate and comprehensive?
This tutorial shows you how to build documentation generation skills that keep your docs in sync with your code.
.claude/commands/doc.md:
---
description: Generate documentation for code
arguments:
- name: target
description: File, directory, or symbol to document
required: true
- name: type
description: Doc type (api, readme, guide, inline)
required: false
default: auto
- name: format
description: Output format (markdown, jsdoc, docstring)
required: false
default: markdown
---
# Documentation Generator
When the user runs /doc [target], generate comprehensive documentation.
## Analyze Target
First, understand what you're documenting:
### If target is a file:
1. Read the entire file
2. Identify language and framework
3. Map exports, classes, functions
4. Note dependencies and integrations
### If target is a directory:
1. List all source files
2. Build dependency graph
3. Identify entry points
4. Note architecture patterns
### If target is a symbol (function/class name):
1. Find the symbol in codebase
2. Read its implementation
3. Find all usages
4. Understand context
## Determine Documentation Type
If type is "auto", choose based on context:
- Single function → API documentation
- Single class → Class documentation
- Entire module → Module documentation
- Package root → README
- Complex workflow → Guide
## Generate Documentation
### For API Documentation:
```markdown
# API Reference: [Module/Class Name]
## Overview
[1-2 paragraph description of what this does and why]
## Installation
```bash
[installation command if applicable]
[minimal working example]
[Description of what it does]
Signature:
[function signature with types]
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
| param1 | string | Yes | Description |
| param2 | number | No | Description (default: 10) |
Returns:
ReturnType - Description of return value
Throws:
ErrorType - When this condition occursExample:
[usage example]
[Repeat for each function/method]
[type definition]
Description of the type and its fields.
[Description of error patterns]
### For README:
```markdown
# [Project Name]
[One-line description]
## Features
- Feature 1
- Feature 2
- Feature 3
## Installation
```bash
[installation steps]
[minimal example to get started]
[Common use cases with examples]
[Configuration options if applicable]
[Link to full API docs or summary]
[How to contribute]
[License info]
### For Inline Documentation:
Generate comments appropriate to the language:
**JavaScript/TypeScript (JSDoc):**
```javascript
/**
* Brief description of the function.
*
* Longer description if needed, explaining the purpose,
* behavior, and any important notes.
*
* @param {string} param1 - Description of param1
* @param {number} [param2=10] - Optional param with default
* @returns {Promise<Result>} Description of return value
* @throws {ValidationError} When input is invalid
* @example
* const result = await myFunction('test');
* console.log(result);
*/
Python (docstring):
def function_name(param1: str, param2: int = 10) -> Result:
"""Brief description of the function.
Longer description if needed, explaining the purpose,
behavior, and any important notes.
Args:
param1: Description of param1
param2: Optional param with default (default: 10)
Returns:
Result: Description of return value
Raises:
ValidationError: When input is invalid
Example:
>>> result = function_name('test')
>>> print(result)
"""
Generated documentation must:
### README Generator
**.claude/commands/readme.md:**
```markdown
---
description: Generate or update project README
arguments:
- name: style
description: README style (minimal, standard, detailed)
required: false
default: standard
---
# README Generator
Generate a comprehensive README for the project.
## Gather Project Information
### From Files
1. `package.json` / `setup.py` / `Cargo.toml`:
- Project name
- Description
- Version
- Dependencies
- Scripts
2. `LICENSE`:
- License type
3. Source files:
- Main entry points
- Key exports
- Architecture patterns
4. Existing docs:
- Any existing README
- CHANGELOG
- CONTRIBUTING
### From Git
1. Repository URL
2. Recent commits for activity
3. Contributors
## Generate README
### Minimal Style
```markdown
# [Project Name]
[Description]
## Install
```bash
[command]
[example]
[License]
### Standard Style
```markdown
# [Project Name]
[Badge: version] [Badge: license] [Badge: build status]
[2-3 sentence description]
## Features
- [Key feature 1]
- [Key feature 2]
- [Key feature 3]
## Installation
```bash
[installation command]
[minimal working example]
[Link to full docs or brief API reference]
[Brief contribution guidelines or link]
[License name] - see LICENSE
### Detailed Style
Include all sections from standard plus:
- Table of Contents
- Detailed installation options
- Full API reference or link
- Configuration options
- Troubleshooting section
- FAQ
- Roadmap
- Acknowledgments
## Update vs Replace
If README already exists:
1. Read existing content
2. Preserve custom sections
3. Update generated sections
4. Mark sections that might need manual review
.claude/commands/api-docs.md:
---
description: Generate API documentation
arguments:
- name: target
description: Source file or directory
required: true
- name: output
description: Output directory for docs
required: false
default: docs/api
---
# API Documentation Generator
Generate comprehensive API documentation from source code.
## Analyze Source
1. Parse all source files
2. Extract:
- Classes and their methods
- Standalone functions
- Type definitions
- Constants and configuration
3. Build relationships:
- Inheritance hierarchies
- Dependencies between modules
- Usage patterns
## Generate Documentation Structure
docs/api/ ├── index.md # Overview and navigation ├── getting-started.md # Quick start guide ├── modules/ │ ├── module-a.md # Each module │ └── module-b.md ├── classes/ │ ├── ClassA.md # Each class │ └── ClassB.md ├── functions/ │ └── utilities.md # Grouped functions └── types/ └── types.md # Type definitions
## Documentation Format
### Module Page
```markdown
# [Module Name]
## Overview
[Module description and purpose]
## Exports
| Export | Type | Description |
|--------|------|-------------|
| funcA | Function | Brief description |
| ClassB | Class | Brief description |
## Dependencies
This module depends on:
- [Module X](./module-x.md)
- [External: lodash]
## Example
```[language]
[Complete usage example]
### Class Page
```markdown
# Class: [ClassName]
[Brief description]
## Hierarchy
ParentClass └── ClassName ├── ChildClassA └── ChildClassB
## Constructor
```[language]
new ClassName(param1: Type, param2: Type)
Parameters:
param1 (Type) - Descriptionparam2 (Type) - Descriptionproperty1: Type
Description of the property.
methodName(param: Type): ReturnType
[Method description]
Parameters:
param (Type) - DescriptionReturns: ReturnType - Description
Example:
const instance = new ClassName();
const result = instance.methodName(value);
[Similar format to instance methods]
Fired when [condition].
Event data:
{ property: Type }
## Cross-Reference
Add links between related docs:
- Parent/child classes link to each other
- Function parameters link to type definitions
- Examples reference real use cases
.claude/agents/doc-sync.md:
---
description: Keep documentation in sync with code
trigger:
event: post-commit
files: ["src/**/*"]
---
# Documentation Sync Agent
Automatically update documentation when code changes.
## On Code Change
When source files change:
1. Identify what changed:
- New functions/classes
- Modified signatures
- Deleted exports
- Changed behavior
2. Find related documentation:
- API docs for modified functions
- README sections referencing changed code
- Inline comments that might be outdated
3. Update documentation:
- Regenerate affected API docs
- Update examples if behavior changed
- Flag potentially stale content
## Notification
After sync, report:
Files changed: 3 Docs updated: 2 Docs needing review: 1
Updated:
Needs review:
Run /doc-review to see details.
## Limitations
DO NOT automatically update:
- README sections with custom content
- Guides and tutorials (may need rewriting)
- Marketing copy
- Version-specific documentation
.claude/commands/doc-review.md:
---
description: Review documentation for accuracy
arguments:
- name: path
description: Path to documentation
required: false
default: docs/
---
# Documentation Review
Check documentation for accuracy against code.
## Analysis
For each documentation file:
1. **Extract code references:**
- Function names mentioned
- Class names mentioned
- Code examples
2. **Verify against source:**
- Do referenced functions exist?
- Are signatures correct?
- Do examples still work?
3. **Check for staleness:**
- References to deleted code
- Outdated examples
- Missing new features
## Report Format
Files reviewed: 15 Issues found: 7
docs/api/utils.md:42
References formatDate() which no longer exists
Suggested action: Remove or update to formatDateTime()
docs/guide/auth.md:89
Example uses deprecated login() method
Suggested action: Update to authenticate()
createUser(name: string, email: string)
Docs: createUser(name: string)
.claude/commands/changelog.md:
---
description: Generate or update CHANGELOG
arguments:
- name: version
description: New version number
required: true
- name: since
description: Git ref to compare from
required: false
---
# Changelog Generator
Generate a CHANGELOG entry from git history.
## Gather Changes
1. Get commits since last tag (or specified ref):
`git log [since]..HEAD --oneline`
2. Categorize commits:
- **Added**: New features (feat:)
- **Changed**: Changes to existing features (refactor:, change:)
- **Deprecated**: Soon-to-be removed features
- **Removed**: Removed features (remove:)
- **Fixed**: Bug fixes (fix:)
- **Security**: Security fixes (security:)
## Format
```markdown
## [version] - YYYY-MM-DD
### Added
- Add user authentication system (#42)
- New dashboard component
### Changed
- Improve database query performance
- Update dependencies
### Fixed
- Fix login redirect loop (#38)
- Correct date formatting in reports
### Security
- Patch XSS vulnerability in comments
If CHANGELOG.md exists:
If no CHANGELOG.md:
### Contributing Guide Generator
**.claude/commands/contributing.md:**
```markdown
---
description: Generate CONTRIBUTING.md
---
# Contributing Guide Generator
Generate a comprehensive contributing guide.
## Analyze Project
1. Check for:
- Test framework
- Linting rules
- Build process
- PR workflow
2. Detect conventions:
- Commit message format
- Branch naming
- Code style
## Generate Guide
```markdown
# Contributing to [Project Name]
Thank you for your interest in contributing!
## Getting Started
### Prerequisites
- [Requirement 1]
- [Requirement 2]
### Setup
```bash
# Clone the repository
git clone [repo-url]
cd [project-name]
# Install dependencies
[install command]
# Run tests to verify setup
[test command]
feature/description - New featuresfix/description - Bug fixesdocs/description - DocumentationWe use conventional commits:
type(scope): description
[optional body]
[optional footer]
Types: feat, fix, docs, style, refactor, test, chore
[test command][lint command]main[Code style guidelines or link to style guide]
[How to run tests, what to test]
[How to get help - issues, discussions, etc.]
Generate docs as you code, not after:
/doc after each new function/readme when starting a project/api-docs before code reviewCreate team templates for consistency:
## Function Documentation Template
- What it does (one sentence)
- Why it exists (context)
- How to use it (example)
- What can go wrong (errors)
Every example should be tested:
## Example Verification
Before including an example:
1. Run the code
2. Verify output matches
3. Check for edge cases
Documentation should connect:
Use the doc-sync agent or remember to:
Documentation doesn't have to be painful. With the right skills, you can:
| Skill | Purpose |
|---|---|
/doc | Generate documentation for any target |
/readme | Create or update README |
/api-docs | Generate full API documentation |
/changelog | Generate CHANGELOG entries |
/contributing | Generate contributing guide |
/doc-review | Check docs for accuracy |
Ready to integrate with GitHub? Check out GitHub Integration for automating GitHub workflows.
Build a concise security Blue Book for sensitive apps covering threat model, auth, logging, and IR
Build Model Context Protocol (MCP) servers and integrations. Create custom tools and capabilities for Claude.
Manage conditional pauses and delays in automated workflows.
Lab environment for experimenting with Claude superpowers and capabilities.