Skip to content

Documentation Generation - Cursor IDE

Your open-source library has gained traction with 10K GitHub stars, but users complain about poor documentation. You need to create API references, usage guides, architecture docs, migration guides, and interactive examples. The codebase spans 50K lines with complex APIs, and you need everything ready for the major v2.0 release next week.

By completing this lesson, you’ll master:

  • AI-powered documentation generation
  • Creating different documentation types
  • Maintaining documentation freshness
  • Building interactive documentation
  • Generating code examples automatically
  • Setting up documentation pipelines
  • Understanding of documentation types
  • Basic markdown knowledge
  • Completed previous lessons
  • Familiarity with documentation tools
  • Optional: Context7 MCP for library docs (see setup)

Create comprehensive documentation including:

  • Complete API reference
  • Getting started guides
  • Architecture documentation
  • Migration guides
  • Interactive examples
  • Searchable documentation site
  1. Assess Current Documentation

Start by analyzing what exists:

@src @docs
"Analyze the current documentation state:
- What documentation exists?
- What's outdated or incorrect?
- What's completely missing?
- How is it organized?
- What formats are used?
Create a documentation gap analysis report"
  1. Define Documentation Architecture
"Design a comprehensive documentation structure for:
- API Reference (auto-generated from code)
- Tutorials (task-based learning)
- Conceptual Guides (understanding the system)
- How-to Guides (solving specific problems)
- Architecture Docs (system design)
- Contributing Guide (for open source)
Create a documentation plan with priorities"
  1. Set Up Documentation Infrastructure

Switch to Agent mode:

"Set up modern documentation infrastructure:
- Install and configure documentation generator
- Set up markdown processing pipeline
- Configure syntax highlighting
- Add search functionality
- Set up deployment workflow
Use Docusaurus or similar tool"

Example documentation config:

docusaurus.config.js
module.exports = {
title: 'MyLibrary Documentation',
tagline: 'Powerful, Type-Safe, and Easy to Use',
url: 'https://docs.mylibrary.dev',
baseUrl: '/',
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
sidebarPath: require.resolve('./sidebars.js'),
editUrl: 'https://github.com/myorg/mylibrary/edit/main/',
remarkPlugins: [
require('remark-code-import'),
require('remark-math'),
],
rehypePlugins: [
require('rehype-katex'),
],
},
theme: {
customCss: require.resolve('./src/css/custom.css'),
},
},
],
],
plugins: [
[
'@docusaurus/plugin-content-docs',
{
id: 'api',
path: 'api',
routeBasePath: 'api',
sidebarPath: require.resolve('./sidebarsApi.js'),
},
],
'@docusaurus/plugin-ideal-image',
[
'docusaurus-plugin-typedoc',
{
entryPoints: ['../src/index.ts'],
tsconfig: '../tsconfig.json',
out: 'api',
sidebar: {
categoryLabel: 'API Reference',
position: 1,
},
},
],
],
themeConfig: {
navbar: {
title: 'MyLibrary',
items: [
{
type: 'doc',
docId: 'intro',
position: 'left',
label: 'Docs',
},
{
to: '/api',
label: 'API',
position: 'left',
},
{
href: 'https://github.com/myorg/mylibrary',
label: 'GitHub',
position: 'right',
},
],
},
algolia: {
appId: 'YOUR_APP_ID',
apiKey: 'YOUR_SEARCH_API_KEY',
indexName: 'mylibrary',
},
prism: {
theme: lightCodeTheme,
darkTheme: darkCodeTheme,
additionalLanguages: ['rust', 'elixir'],
},
},
};

Phase 1.5: Leveraging Context7 MCP for Documentation

Section titled “Phase 1.5: Leveraging Context7 MCP for Documentation”
  1. Configure Context7 MCP
~/.cursor/mcp.json
{
"mcpServers": {
"context7": {
"command": "npx",
"args": ["-y", "@upstash/context7-mcp"]
}
}
}
  1. Research Current Best Practices
"Using Context7 MCP, show me the latest:
- React 18 documentation patterns
- TypeScript 5 doc comment standards
- Jest testing documentation examples
- Popular library documentation structures"
// Get specific library docs
"Using Context7: How does Next.js 14 document:
- API routes
- Component props
- Configuration options
- Migration guides"
  1. Generate Docs Based on Latest Standards
"Using Context7, show current JSDoc standards for:
- Async functions
- Generic types
- React components
- Error handling
Then apply to our codebase"
  1. Compare Documentation Approaches
"Using Context7 MCP, compare documentation styles:
- React vs Vue component docs
- Express vs Fastify API docs
- Prisma vs TypeORM schema docs
What patterns work best for our library?"
// Get framework-specific conventions
"Using Context7: Show me Docusaurus best practices for:
- Navigation structure
- Search optimization
- Versioned documentation
- Interactive examples"
  1. Stay Current with Dependencies
"Using Context7 MCP, check our dependencies:
- Are we using deprecated APIs?
- What's the migration path for outdated methods?
- Which libraries have major updates?
- What are the new best practices?"
// Update documentation accordingly
"Based on Context7 findings, update our docs to:
- Reference current API methods
- Use modern syntax examples
- Follow latest conventions
- Include deprecation warnings"

Real-time Updates:

"Using Context7, what's new in React Router v6.4+?
Update our routing documentation to reflect:
- New data loading patterns
- Error boundary changes
- Route configuration updates"

Cross-Library Learning:

"Using Context7, how do popular libraries document:
- Authentication flows (NextAuth, Auth0, Supabase)
- State management (Redux, Zustand, Jotai)
- Form handling (React Hook Form, Formik)
Apply best patterns to our docs"

Version-Aware Documentation:

"Using Context7, create version-specific docs:
- v1.x using old API
- v2.x with new features
- Migration guide between versions
- Compatibility matrix"
  1. Generate API Reference
@src
"Generate comprehensive API documentation:
- Extract all public APIs
- Document parameters and return types
- Include type information
- Add usage examples for each method
- Document edge cases and errors
- Create cross-references
Use JSDoc/TSDoc format"

Example generated documentation:

/**
* Creates a connection pool for database operations with automatic
* retry logic and connection recycling.
*
* @example
* ```typescript
* // Basic usage
* const pool = createPool({
* host: 'localhost',
* database: 'myapp',
* max: 20
* });
*
* // With advanced options
* const pool = createPool({
* host: 'db.example.com',
* port: 5432,
* database: 'production',
* user: 'dbuser',
* password: process.env.DB_PASSWORD,
* max: 50,
* idleTimeoutMillis: 30000,
* connectionTimeoutMillis: 2000,
* retryAttempts: 3,
* retryDelay: 1000,
* ssl: {
* rejectUnauthorized: true,
* ca: fs.readFileSync('./ca-cert.pem')
* }
* });
*
* // Using the pool
* const result = await pool.query('SELECT * FROM users WHERE id = $1', [userId]);
* ```
*
* @param config - Pool configuration options
* @param config.host - Database host address
* @param config.port - Database port (default: 5432)
* @param config.database - Database name
* @param config.user - Database user
* @param config.password - Database password
* @param config.max - Maximum number of clients in the pool (default: 10)
* @param config.idleTimeoutMillis - Idle client timeout (default: 10000)
* @param config.connectionTimeoutMillis - Connection timeout (default: 0)
* @param config.retryAttempts - Number of retry attempts (default: 3)
* @param config.retryDelay - Delay between retries in ms (default: 1000)
* @param config.ssl - SSL configuration object or boolean
*
* @returns A configured database pool instance
*
* @throws {ConnectionError} When unable to establish database connection
* @throws {ConfigurationError} When required configuration is missing
* @throws {SSLError} When SSL configuration is invalid
*
* @see {@link Pool} for pool instance methods
* @see {@link query} for executing queries
* @see {@link transaction} for transaction support
*
* @since 1.0.0
* @public
*/
export function createPool(config: PoolConfig): Pool {
validateConfig(config);
const pool = new Pool({
...defaultConfig,
...config,
// Retry logic wrapper
Client: createRetryableClient(config),
});
// Add event handlers
pool.on('error', (err, client) => {
logger.error('Unexpected error on idle client', err);
});
pool.on('connect', (client) => {
logger.debug('New client connected to pool');
});
return wrapPoolMethods(pool);
}
/**
* Pool configuration options
* @public
*/
export interface PoolConfig {
/** Database host address */
host: string;
/** Database port @defaultValue 5432 */
port?: number;
/** Database name */
database: string;
/** Database user */
user?: string;
/** Database password */
password?: string;
/**
* Maximum number of clients in the pool
* @defaultValue 10
* @remarks
* Consider your database's connection limits when setting this value.
* Each client consumes resources on both application and database server.
*/
max?: number;
/**
* Number of milliseconds a client must sit idle before being closed
* @defaultValue 10000
*/
idleTimeoutMillis?: number;
/**
* Number of milliseconds to wait before timing out when connecting
* @defaultValue 0 (no timeout)
*/
connectionTimeoutMillis?: number;
/**
* Number of times to retry failed connections
* @defaultValue 3
*/
retryAttempts?: number;
/**
* Delay between connection retry attempts in milliseconds
* @defaultValue 1000
*/
retryDelay?: number;
/**
* SSL configuration
* @example
* ```typescript
* // Enable SSL with default settings
* ssl: true
*
* // Custom SSL configuration
* ssl: {
* rejectUnauthorized: true,
* ca: fs.readFileSync('./ca-cert.pem'),
* key: fs.readFileSync('./client-key.pem'),
* cert: fs.readFileSync('./client-cert.pem')
* }
* ```
*/
ssl?: boolean | SSLConfig;
}
  1. Generate Type Documentation
@src/types
"Document all TypeScript types and interfaces:
- Extract type definitions
- Document type parameters
- Show inheritance hierarchy
- Create type usage examples
- Document discriminated unions
- Add type guards examples"
  1. Create Code Examples
@src @tests
"Generate code examples for all major features:
- Basic usage examples
- Advanced patterns
- Error handling examples
- Performance optimization examples
- Integration examples
- Full application examples
Extract from tests where possible"
  1. Generate Getting Started Guide
@src @examples
"Create a comprehensive getting started guide:
- Installation instructions (npm, yarn, pnpm)
- Basic setup and configuration
- First simple example
- Common use cases
- Troubleshooting section
- Next steps
Make it beginner-friendly but comprehensive"

Example getting started guide:

# Getting Started with MyLibrary
## Installation
MyLibrary can be installed using your favorite package manager:
```bash
# npm
npm install mylibrary
# yarn
yarn add mylibrary
# pnpm
pnpm add mylibrary
// ES Modules (recommended)
import { createPool, query } from 'mylibrary';
// CommonJS
const { createPool, query } = require('mylibrary');
import { createPool } from 'mylibrary';
// Create a connection pool
const pool = createPool({
host: 'localhost',
database: 'myapp',
user: 'myuser',
password: 'mypassword'
});
// Test the connection
try {
const result = await pool.query('SELECT NOW()');
console.log('Connected successfully:', result.rows[0]);
} catch (error) {
console.error('Connection failed:', error);
}
// Simple query
const users = await pool.query('SELECT * FROM users');
console.log(`Found ${users.rowCount} users`);
// Parameterized query (prevents SQL injection)
const userId = 123;
const user = await pool.query(
'SELECT * FROM users WHERE id = $1',
[userId]
);
// Using the query builder
const activeUsers = await pool
.select('id', 'name', 'email')
.from('users')
.where('active', true)
.orderBy('created_at', 'DESC')
.limit(10)
.execute();
// Automatic connection management
async function getUser(id: number) {
// Connection is automatically acquired and released
return pool.query('SELECT * FROM users WHERE id = $1', [id]);
}
// Manual connection management for transactions
async function transferFunds(from: number, to: number, amount: number) {
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query(
'UPDATE accounts SET balance = balance - $1 WHERE id = $2',
[amount, from]
);
await client.query(
'UPDATE accounts SET balance = balance + $1 WHERE id = $2',
[amount, to]
);
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
}
import { DatabaseError, ConnectionError } from 'mylibrary';
try {
const result = await pool.query('SELECT * FROM users');
} catch (error) {
if (error instanceof ConnectionError) {
console.error('Database connection failed:', error.message);
// Implement retry logic or fallback
} else if (error instanceof DatabaseError) {
console.error('Query failed:', error.message);
// Log query details for debugging
} else {
console.error('Unexpected error:', error);
}
}
const pool = createPool({
host: process.env.DB_HOST || 'localhost',
port: parseInt(process.env.DB_PORT || '5432'),
database: process.env.DB_NAME || 'development',
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
max: parseInt(process.env.DB_POOL_SIZE || '10'),
// Enable SSL in production
ssl: process.env.NODE_ENV === 'production'
});
const pool = createPool({
// Connection settings
host: 'db.example.com',
port: 5432,
database: 'production',
// Pool settings
max: 20, // Maximum pool size
min: 5, // Minimum pool size
idleTimeoutMillis: 30000, // Close idle clients after 30s
connectionTimeoutMillis: 2000, // Timeout new connections after 2s
// Retry settings
retryAttempts: 3,
retryDelay: 1000,
// Monitoring
onConnect: (client) => {
console.log('Client connected');
},
onError: (error, client) => {
console.error('Pool error:', error);
}
});

Connection Timeout

// Increase connection timeout
const pool = createPool({
connectionTimeoutMillis: 5000, // 5 seconds
// ... other config
});

Too Many Connections

// Monitor pool usage
console.log('Total clients:', pool.totalCount);
console.log('Idle clients:', pool.idleCount);
console.log('Waiting requests:', pool.waitingCount);
// Adjust pool size based on usage
const pool = createPool({
max: 50, // Increase maximum connections
// ... other config
});

SSL Connection Issues

// Debug SSL connections
const pool = createPool({
ssl: {
rejectUnauthorized: false, // Only for development!
// For production, provide proper certificates
ca: fs.readFileSync('./server-ca.pem'),
}
});

Now that you have MyLibrary up and running:

  1. Explore Advanced Features

  2. Best Practices

  3. Integration Guides

2. **Create Topic Guides**
```typescript
"Generate in-depth guides for specific topics:
- Authentication patterns
- Performance optimization
- Error handling strategies
- Testing approaches
- Deployment guides
- Security best practices
Each guide should be comprehensive and practical"
  1. Build Interactive Examples
"Create interactive documentation:
- Live code playgrounds
- Runnable examples
- Interactive API explorer
- Step-by-step tutorials
- Video demonstrations
Use CodeSandbox or similar"
  1. Generate Architecture Diagrams
@src
"Create architecture documentation:
- System overview diagram
- Component relationships
- Data flow diagrams
- Sequence diagrams for key flows
- Deployment architecture
Use Mermaid or PlantUML"

Example architecture documentation:

# System Architecture
## Overview
MyLibrary follows a modular architecture designed for scalability and maintainability.
```mermaid
graph TB
subgraph "Application Layer"
APP[Your Application]
end
subgraph "MyLibrary Core"
API[Public API]
QM[Query Manager]
PM[Pool Manager]
CM[Connection Manager]
RM[Retry Manager]
end
subgraph "Database Layer"
PG[(PostgreSQL)]
MY[(MySQL)]
MS[(SQL Server)]
end
APP --> API
API --> QM
API --> PM
QM --> CM
PM --> CM
CM --> RM
RM --> PG
RM --> MY
RM --> MS

Responsible for managing database connection pools:

  • Connection lifecycle management
  • Pool sizing and optimization
  • Health monitoring
  • Metrics collection

Handles query execution and optimization:

  • Query parsing and validation
  • Parameter binding
  • Result transformation
  • Query caching

Low-level connection handling:

  • Protocol implementation
  • SSL/TLS negotiation
  • Authentication
  • Keep-alive management

Implements resilience patterns:

  • Exponential backoff
  • Circuit breaker
  • Timeout handling
  • Error classification
sequenceDiagram participant App participant API participant Pool participant Connection participant Database App->>API: query(sql, params) API->>Pool: getConnection() alt Connection Available Pool->>API: connection else Pool Exhausted Pool->>API: wait in queue Pool->>API: connection (when available) end API->>Connection: execute(sql, params) Connection->>Database: send query Database->>Connection: result Connection->>API: transformed result API->>Pool: release(connection) API->>App: result

The core functionality has no external dependencies, ensuring:

  • Minimal bundle size
  • Reduced security surface
  • Easier maintenance
  • Better performance

Extended functionality through plugins:

import { createPool } from 'mylibrary';
import { metricsPlugin } from 'mylibrary-metrics';
import { cachingPlugin } from 'mylibrary-cache';
const pool = createPool({
// ... config
plugins: [
metricsPlugin({ provider: 'prometheus' }),
cachingPlugin({ ttl: 300 })
]
});

Full TypeScript support with:

  • Inferred query results
  • Type-safe query builders
  • Compile-time validation
  • Auto-completion support
2. **Document Design Decisions**
```typescript
"Create ADR (Architecture Decision Records):
- Key design decisions
- Alternatives considered
- Rationale for choices
- Trade-offs accepted
- Migration strategies
Follow ADR template"
  1. Performance Documentation
"Document performance characteristics:
- Benchmark results
- Optimization techniques
- Scaling strategies
- Resource requirements
- Bottleneck analysis
Include real measurements"
  1. Set Up Auto-generation Pipeline
"Create automated documentation pipeline:
- Extract docs from source code
- Generate on every commit
- Update version-specific docs
- Deploy to documentation site
- Notify about breaking changes
Use GitHub Actions"

Example automation workflow:

.github/workflows/docs.yml
name: Documentation
on:
push:
branches: [main]
paths:
- 'src/**'
- 'docs/**'
pull_request:
branches: [main]
jobs:
generate-docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Generate API documentation
run: |
npm run docs:api
npm run docs:types
- name: Check documentation coverage
run: |
npm run docs:coverage
# Fail if coverage < 90%
- name: Generate examples from tests
run: npm run docs:examples
- name: Build documentation site
run: npm run docs:build
- name: Run documentation tests
run: |
# Test all code examples
npm run docs:test-examples
# Check for broken links
npm run docs:check-links
- name: Deploy to GitHub Pages
if: github.ref == 'refs/heads/main'
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./docs/build
- name: Update search index
if: github.ref == 'refs/heads/main'
run: |
npm run docs:update-search
env:
ALGOLIA_API_KEY: ${{ secrets.ALGOLIA_API_KEY }}
  1. Create Documentation Tests
"Create tests for documentation:
- Validate code examples compile
- Test example outputs
- Check API completeness
- Verify link integrity
- Ensure version consistency
Run in CI/CD"
  1. Build Documentation Metrics
"Create documentation quality metrics:
- Coverage percentage
- Freshness indicators
- Example completeness
- Search effectiveness
- User feedback integration
Display in dashboard"

Technique 1: MCP-Powered Documentation Research

Section titled “Technique 1: MCP-Powered Documentation Research”

Use Context7 to stay current:

// Research before documenting
"Using Context7 MCP, research:
- How does React document hooks?
- What's the TypeScript standard for generics?
- How do popular ORMs document queries?"
// Validate against current standards
"Using Context7, verify our examples use:
- Latest syntax (ES2024+)
- Current library versions
- Modern best practices
- Non-deprecated APIs"
// Find documentation inspiration
"Using Context7, show me excellent docs for:
- API rate limiting
- WebSocket connections
- Authentication flows
Use as templates for our docs"

Treat docs like code:

src/database/pool.ts
/**
* @example <caption>Basic connection pool</caption>
* ```typescript
* const pool = createPool({
* host: 'localhost',
* database: 'myapp'
* });
* ```
*
* @example <caption>Production configuration</caption>
* ```typescript
* const pool = createPool({
* host: process.env.DB_HOST,
* database: process.env.DB_NAME,
* max: 50,
* ssl: true
* });
* ```
*/
export function createPool(config: PoolConfig): Pool {
// Implementation
}

Keep docs in sync with code:

// Generate docs from tests
describe('createPool', () => {
it('creates a basic pool', () => {
// @doc-example: basic-pool
const pool = createPool({
host: 'localhost',
database: 'test'
});
expect(pool).toBeDefined();
// @end-doc-example
});
});

Layer information for different audiences:

// Simple select query
const users = await db
.select('*')
.from('users')
.execute();

Problem: Code examples no longer work

Solution:

// Test all examples automatically
import { extractExamples } from './docs-utils';
describe('Documentation Examples', () => {
const examples = extractExamples('./docs');
test.each(examples)('$name should run without errors',
async ({ code }) => {
const result = await runExample(code);
expect(result.error).toBeUndefined();
}
);
});

Advanced documentation features:

  1. Internationalization

    • Multi-language documentation
    • Automated translation
    • Locale-specific examples
    • RTL language support
  2. Interactive Learning

    • Embedded code playgrounds
    • Interactive tutorials
    • Progress tracking
    • Certification system
  3. AI-Powered Features

    • Smart search with NLP
    • Automatic FAQ generation
    • Code example suggestions
    • Personalized learning paths
  4. MCP-Enhanced Documentation

    • Use Context7 for real-time API updates
    • Integrate Notion MCP for collaborative docs
    • Add GitHub MCP for code example syncing
    • Create custom MCP for internal knowledge base

Your documentation succeeds when:

  • ✅ 100% API coverage achieved
  • ✅ All examples tested and working
  • ✅ Search returns relevant results
  • ✅ New users productive in under 30 min
  • ✅ Support tickets reduced by 70%
  • ✅ Community contributions increase
  • ✅ Documentation stays current
  • ✅ Users rate docs 4.5+ stars

Projects with great documentation report:

  • 80% fewer support questions
  • 3x faster user onboarding
  • 5x more community contributions
  • 90% higher user satisfaction

Before publishing:

  • API reference complete
  • Getting started tested by newcomer
  • All examples run successfully
  • Search index updated
  • Links verified
  • Version compatibility noted
  • Performance tips included
  • Troubleshooting section ready
  1. Automate Everything: Generate docs from code
  2. Test Documentation: Treat docs as code
  3. Layer Information: Serve all skill levels
  4. Keep Fresh: Automate updates
  5. Measure Usage: Track what helps users
  • Initial setup: 2 hours
  • API documentation: 3 hours
  • Guides and tutorials: 4 hours
  • Architecture docs: 2 hours
  • Automation setup: 2 hours
  • Total: ~13 hours (saves hundreds of support hours)

You’ve mastered documentation generation. Continue your journey:

Video Tutorials

Create engaging video documentation

API Explorer

Build interactive API playground

Contribution Guide

Enable community documentation

Continue to Next Lesson →