К основному содержанию
скилл CX Codex

api-documentation — скилл для Claude Code: правила документирования

Набор правил, по которым агент пишет докстринги, JSDoc, Godoc и описания эндпоинтов. Пригодится, когда API документируют в нескольких агентах и текст расползается.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add bobmatnyc/claude-mpm-skills --skill api-documentation -a claude-code
Открыть на GitHub

Что делает api-documentation

Скилл задаёт пять принципов: объяснять зачем, а не только что; держать документацию рядом с кодом; описывать контракт, а не реализацию; давать примеры; обновлять доки вместе с кодом. Дальше идут готовые образцы под конкретные языки и форматы — Python-докстринги, JSDoc, Godoc, OpenAPI, GraphQL SDL, описание класса с примером вызова.

Внутри только текст с примерами. Никаких скриптов и внешних вызовов, ставить нечего кроме самого файла скилла. Автор заявляет, что это убирает примерно 100–150 строк одинаковых указаний по документации в каждом агенте — если у вас несколько агентов дублируют одни и те же требования к докам, это повод проверить, не пора ли свести их в один скилл.

Скилл помечен как user-invocable: false и disable-model-invocation: true, то есть вызвать его вручную слэш-командой не получится: он подхватывается как справочный материал, когда агент пишет или правит документацию. Примеры в файле построены вокруг функции расчёта скидки, так что за основу берите структуру разделов, а не сам код.

Какие задачи решает

  • написать докстринг к функции с описанием аргументов и исключений
  • оформить описание REST-эндпоинта в OpenAPI
  • задокументировать GraphQL-тип и его поля
  • описать класс с примером использования и пометкой о потокобезопасности
  • собрать структуру README с установкой и быстрым стартом

Примеры запросов агенту

  • Задокументируй функцию calculate_discount по образцу из скилла api-documentation: аргументы, возврат, исключения, примеры.
  • Опиши эндпоинт GET /users/{userId} в OpenAPI 3.0 с ответами 200, 404 и 401.
  • Добавь к классу UserManager докстринг с примером вызова и разделом про потокобезопасность.

Как установить api-documentation

1Через Skills CLI (Vercel)

npx skills add bobmatnyc/claude-mpm-skills --skill api-documentation -a claude-code

2Вручную: положить файлы

~/.claude/skills/api-documentation/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/api-documentation/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о api-documentation

Как установить api-documentation в Claude?

Выполните npx skills add bobmatnyc/claude-mpm-skills --skill api-documentation -a claude-code. Файл скилла окажется по пути ~/.claude/skills/api-documentation/SKILL.md.

Что делает api-documentation?

Даёт агенту единые правила оформления документации к коду и API: докстринги, JSDoc, Godoc, OpenAPI, GraphQL. Вместо того чтобы повторять эти указания в каждом агенте, вы держите их в одном скилле.

Можно ли вызвать скилл вручную?

Нет. В нём стоит user-invocable: false и disable-model-invocation: true, поэтому слэш-команды у него нет — он работает как справочный материал.

Исходный текст

SKILL.md · MIT
---
name: api-documentation
description: Best practices for documenting APIs and code interfaces, eliminating redundant documentation guidance per agent.
user-invocable: false
disable-model-invocation: true
updated_at: 2025-10-30T17:00:00Z
tags: [api, documentation, best-practices, interfaces]
progressive_disclosure:
  entry_point:
    summary: "Best practices for documenting APIs and code interfaces, eliminating redundant documentation guidance per agent."
    when_to_use: "When designing, implementing, or documenting APIs."
    quick_start: "1. Review the core concepts below. 2. Apply patterns to your use case. 3. Follow best practices for implementation."
---
# API Documentation

Best practices for documenting APIs and code interfaces. Eliminates ~100-150 lines of redundant documentation guidance per agent.

## Core Documentation Principles

1. **Document the why, not just the what** - Explain intent and rationale
2. **Keep docs close to code** - Inline documentation stays synchronized
3. **Document contracts, not implementation** - Focus on behavior
4. **Examples are essential** - Show real usage
5. **Update docs with code** - Outdated docs are worse than no docs

## Function/Method Documentation

### Python (Docstrings)

```python
def calculate_discount(price: float, discount_percent: float) -> float:
    """
    Calculate discounted price with percentage off.

    Args:
        price: Original price in dollars (must be positive)
        discount_percent: Discount percentage (0-100)

    Returns:
        Final price after discount, rounded to 2 decimals

    Raises:
        ValueError: If price is negative or discount > 100

    Examples:
        >>> calculate_discount(100.0, 20.0)
        80.0
        >>> calculate_discount(50.0, 50.0)
        25.0

    Note:
        Discount percent is capped at 100% (minimum price of 0)
    """
    if price < 0:
        raise ValueError("Price cannot be negative")
    if discount_percent > 100:
        raise ValueError("Discount cannot exceed 100%")

    discount_amount = price * (discount_percent / 100)
    return round(price - discount_amount, 2)
```

### JavaScript (JSDoc)

```javascript
/**
 * Calculate discounted price with percentage off
 *
 * @param {number} price - Original price in dollars (must be positive)
 * @param {number} discountPercent - Discount percentage (0-100)
 * @returns {number} Final price after discount, rounded to 2 decimals
 * @throws {Error} If price is negative or discount > 100
 *
 * @example
 * calculateDiscount(100.0, 20.0)
 * // returns 80.0
 *
 * @example
 * calculateDiscount(50.0, 50.0)
 * // returns 25.0
 */
function calculateDiscount(price, discountPercent) {
  if (price < 0) {
    throw new Error('Price cannot be negative');
  }
  if (discountPercent > 100) {
    throw new Error('Discount cannot exceed 100%');
  }

  const discountAmount = price * (discountPercent / 100);
  return Math.round((price - discountAmount) * 100) / 100;
}
```

### Go (Godoc)

```go
// CalculateDiscount calculates discounted price with percentage off.
//
// The function applies the given discount percentage to the original price
// and returns the final price rounded to 2 decimal places.
//
// Parameters:
//   - price: Original price in dollars (must be positive)
//   - discountPercent: Discount percentage (0-100)
//
// Returns the final price after discount.
//
// Returns an error if price is negative or discount exceeds 100%.
//
// Example:
//
//	finalPrice, err := CalculateDiscount(100.0, 20.0)
//	// finalPrice = 80.0
func CalculateDiscount(price, discountPercent float64) (float64, error) {
    if price < 0 {
        return 0, errors.New("price cannot be negative")
    }
    if discountPercent > 100 {
        return 0, errors.New("discount cannot exceed 100%")
    }

    discountAmount := price * (discountPercent / 100)
    return math.Round((price-discountAmount)*100) / 100, nil
}
```

## API Endpoint Documentation

### REST API (OpenAPI/Swagger)

```yaml
openapi: 3.0.0
info:
  title: User Management API
  version: 1.0.0

paths:
  /users/{userId}:
    get:
      summary: Get user by ID
      description: Retrieves detailed information for a specific user
      parameters:
        - name: userId
          in: path
          required: true
          schema:
            type: integer
            minimum: 1
          description: Unique user identifier
      responses:
        '200':
          description: User found successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
              example:
                id: 123
                name: "John Doe"
                email: "[email protected]"
        '404':
          description: User not found
        '401':
          description: Unauthorized - authentication required
```

### GraphQL

```graphql
"""
Represents a user in the system
"""
type User {
  """Unique identifier for the user"""
  id: ID!

  """User's full name"""
  name: String!

  """User's email address (validated)"""
  email: String!

  """User's posts (paginated)"""
  posts(limit: Int = 10, offset: Int = 0): [Post!]!
}

"""
Query a specific user by ID
"""
type Query {
  """
  Get user by unique identifier

  Returns null if user not found
  """
  user(id: ID!): User
}
```

## Class/Module Documentation

```python
class UserManager:
    """
    Manages user accounts and authentication.

    This class provides a high-level interface for user management
    operations including creation, authentication, and profile updates.

    Attributes:
        db: Database connection instance
        cache: Redis cache for session management

    Example:
        >>> manager = UserManager(db=get_db(), cache=get_cache())
        >>> user = manager.create_user("[email protected]", "password")
        >>> authenticated = manager.authenticate("[email protected]", "password")
        >>> authenticated is not None
        True

    Thread Safety:
        This class is thread-safe. Multiple threads can safely call
        methods concurrently.

    Note:
        All passwords are automatically hashed using bcrypt before
        storage. Never pass pre-hashed passwords to methods.
    """

    def __init__(self, db: Database, cache: Cache):
        """
        Initialize UserManager with database and cache.

        Args:
            db: Database connection for persistent storage
            cache: Redis cache for session management

        Raises:
            ConnectionError: If unable to connect to database or cache
        """
        self.db = db
        self.cache = cache
```

## README Documentation Structure

```markdown
# Project Name

Brief description of what the project does (1-2 sentences).

## Features

- Key feature 1
- Key feature 2
- Key feature 3

## Installation

```bash
pip install project-name
```

## Quick Start

```python
from project import MainClass

# Simple usage example
client = MainClass(api_key="your-key")
result = client.do_something()
print(result)
```

## Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `api_key` | str | None | API authentication key |
| `timeout` | int | 30 | Request timeout in seconds |

## API Reference

See full [API Documentation](docs/api.md)

### Main Methods

#### `do_something(param1, param2)`

Description of what this does.

**Parameters:**
- `param1` (str): Description of param1
- `param2` (int): Description of param2

**Returns:** Description of return value

**Example:**
```python
result = client.do_something("value", 42)
```

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md)

## License

MIT License - see [LICENSE](LICENSE)
```

## Documentation Anti-Patterns

### ❌ Redundant Comments

```python
# Bad: Obvious comment adds no value
i = i + 1  # Increment i

# Good: Comment explains WHY
i = i + 1  # Skip header row
```

### ❌ Outdated Documentation

```python
# Bad: Comment doesn't match code
def get_users(limit=10):  # Comment says: Returns all users
    """Returns all users in the system."""  # But limit is 10!
    return User.query.limit(limit).all()

# Good: Keep docs synchronized
def get_users(limit=10):
    """
    Returns up to 'limit' users from the system.

    Args:
        limit: Maximum number of users to return (default: 10)
    """
    return User.query.limit(limit).all()
```

### ❌ Implementation Documentation

```python
# Bad: Documents HOW (implementation)
def sort_users(users):
    """Uses bubble sort algorithm to sort users."""  # Don't care!
    ...

# Good: Documents WHAT (contract)
def sort_users(users):
    """Returns users sorted alphabetically by name."""
    ...
```

## Documentation Tools

### Python
- **Sphinx**: Generate HTML docs from docstrings
- **pdoc**: Simpler alternative to Sphinx
- **MkDocs**: Markdown-based documentation

### JavaScript
- **JSDoc**: Generate HTML from JSDoc comments
- **TypeDoc**: For TypeScript projects
- **Docusaurus**: Full documentation websites

### Go
- **godoc**: Built-in documentation tool
- **pkgsite**: Go package documentation

### Rust
- **rustdoc**: Built-in documentation with `cargo doc`

## Quick Documentation Checklist

```
□ Public APIs have docstrings/comments
□ Parameters and return values documented
□ Exceptions/errors documented
□ Usage examples provided
□ Edge cases and limitations noted
□ README includes quick start
□ API reference available
□ Configuration options documented
□ Docs are up to date with code
□ Breaking changes documented
```

## Remember

- **Code is read more than written** - Good docs save time
- **Examples speak louder than descriptions** - Show, don't just tell
- **The best docs are no docs** - Write self-documenting code
- **Keep it DRY** - Don't repeat what the code already says
- **Update docs with code** - Outdated docs mislead developers

© bobmatnyc · MIT · bobmatnyc/claude-mpm-skills

Похожие скиллы

Всё по теме «Тексты и документация» →
api-reference-documentation aj-geddes Скилл помогает агенту собрать справочник по API: эндпоинты, аутентификация, примеры запросов и ответов, спецификация OpenAPI. CX Codex +1 494установок doc-api davila7 Разбирает код проекта и собирает документацию по API: спецификацию, примеры запросов и ответов, интерактивную страницу. Пригодится, когда эндпоинтов много, а описывать их руками не хочется. 733установок api-recon-and-docs yaklang Скилл помогает исследовать структуру REST, mobile и GraphQL API перед тестированием. Он ищет скрытые эндпоинты, схемы и старые версии интерфейсов. CX Codex +1 3 800установок api-documenter zhaono1 Скилл для описания REST и GraphQL API в формате OpenAPI/Swagger. Пригодится, когда нужно превратить россыпь эндпоинтов в читаемую спецификацию. CX Codex +1 717установок spring-boot-openapi-documentation giuseppe-trisciuoglio Скилл помогает агенту настроить SpringDoc OpenAPI 3.0 и Swagger UI в проекте на Spring Boot 3.x и разметить эндпоинты аннотациями. CX Codex +1 4 000установок documentation-engineer VoltAgent Community Проектирует и обновляет техническую документацию: справочники API, пошаговые руководства и архитектурные схемы. Пригодится, когда документация отстает от изменений в коде. 735установок

Из того же набора65

kysely Скилл по Kysely: типы от схемы до результата запроса, миграции и транзакции. Пригодится, когда ORM уже мешает, а сырой SQL без типов надоел. CX Codex +1 389установок kubernetes Плейбук по работе с Kubernetes: подсказывает, как безопасно выкатывать сервисы, ставить пробы и разбирать сбои через kubectl. CX Codex +1 383установок systematic-debugging Скилл ведёт агента от воспроизведения ошибки до проверки исправления. Пригодится, когда причина сбоя или неожиданного поведения неясна. CX Codex +1 382установок vue Скилл по Vue 3 для ИИ-агента: Composition API, реактивность, однофайловые компоненты, Vue Router, Pinia, TypeScript и Vite. Пригодится, когда агент пишет фронтенд на Vue. CX Codex +1 381установок software-patterns Помогает выбрать паттерн под конкретную проблему: связанность, отказоустойчивость, границы сервисов. Пригодится, когда код трудно тестировать или сервисы вызывают друг друга по кругу. CX Codex +1 373установок nextjs-v16 Скилл ведёт миграцию проекта на Next.js 16: асинхронные request API, opt-in кеширование через "use cache" и Turbopack. Пригодится, когда обновляете существующее приложение. CX Codex +1 371установок testing-anti-patterns Скилл помогает находить ошибки в тестах: проверки поведения моков, тестовые методы в продакшене и неполные заглушки. CX Codex +1 368установок vercel-deployments-builds Описывает жизненный цикл деплоя на Vercel: сборки, превью, фазы релиза и откат. Пригодится, когда настраиваешь вывод сборки или контролируешь релизы. CX Codex +1 368установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой