feat(marketplace): command consolidation + 8 new plugins (v8.1.0 → v9.0.0) [BREAKING]

Phase 1b: Rename all ~94 commands across 12 plugins to /<noun> <action>
sub-command pattern. Git-flow consolidated from 8→5 commands (commit
variants absorbed into --push/--merge/--sync flags). Dispatch files,
name: frontmatter, and cross-reference updates for all plugins.

Phase 2: Design documents for 8 new plugins in docs/designs/.

Phase 3: Scaffold 8 new plugins — saas-api-platform, saas-db-migrate,
saas-react-platform, saas-test-pilot, data-seed, ops-release-manager,
ops-deploy-pipeline, debug-mcp. Each with plugin.json, commands, agents,
skills, README, and claude-md-integration. Marketplace grows from 12→20.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-06 14:52:11 -05:00
parent 5098422858
commit 2d51df7a42
321 changed files with 13582 additions and 1019 deletions

View File

@@ -0,0 +1,26 @@
{
"name": "saas-api-platform",
"description": "REST and GraphQL API scaffolding, validation, and documentation for FastAPI and Express",
"version": "1.0.0",
"author": {
"name": "Leo Miranda",
"email": "leobmiranda@gmail.com"
},
"homepage": "https://gitea.hotserv.cloud/personal-projects/leo-claude-mktplace/src/branch/main/plugins/saas-api-platform/README.md",
"repository": "https://gitea.hotserv.cloud/personal-projects/leo-claude-mktplace.git",
"license": "MIT",
"keywords": [
"api",
"rest",
"graphql",
"fastapi",
"express",
"openapi",
"scaffolding",
"middleware"
],
"commands": [
"./commands/"
],
"domain": "saas"
}

View File

@@ -0,0 +1,43 @@
# saas-api-platform
REST and GraphQL API scaffolding, validation, and documentation for FastAPI and Express.
## Overview
The saas-api-platform plugin provides a complete API development toolkit. It detects your framework, generates routes and models following RESTful conventions, validates implemented endpoints against OpenAPI specifications, and manages middleware configuration.
## Supported Frameworks
- **FastAPI** (Python) - Pydantic models, dependency injection, async endpoints
- **Express** (Node.js/TypeScript) - Router patterns, Zod/Joi validation, middleware chains
## Commands
| Command | Description |
|---------|-------------|
| `/api setup` | Setup wizard - detect framework, map project structure |
| `/api scaffold <resource>` | Generate CRUD routes, models, and schemas |
| `/api validate` | Validate routes against OpenAPI specification |
| `/api docs` | Generate or update OpenAPI 3.x specification from code |
| `/api test-routes` | Generate test cases for API endpoints |
| `/api middleware <type>` | Add and configure middleware (auth, CORS, rate-limit, etc.) |
## Agents
| Agent | Model | Mode | Purpose |
|-------|-------|------|---------|
| `api-architect` | sonnet | default | Route design, schema generation, middleware planning |
| `api-validator` | haiku | plan (read-only) | OpenAPI compliance validation |
## Installation
This plugin is part of the Leo Claude Marketplace. It is installed automatically when the marketplace is configured.
### Prerequisites
- A FastAPI or Express project to work with
- Run `/api setup` before using other commands
## Configuration
The `/api setup` command creates `.api-platform.json` in your project root with detected settings. All subsequent commands read this file for framework and convention configuration.

View File

@@ -0,0 +1,83 @@
---
name: api-architect
description: Route design, schema generation, and middleware planning for API projects
model: sonnet
permissionMode: default
---
# API Architect Agent
You are an API architect specializing in REST and GraphQL API design for FastAPI and Express. You generate production-quality scaffolding, maintain OpenAPI specifications, and configure middleware stacks.
## Visual Output Requirements
**MANDATORY: Display header at start of every response.**
```
+----------------------------------------------------------------------+
| API-PLATFORM - API Architect |
| [Context Line] |
+----------------------------------------------------------------------+
```
## Expertise
- RESTful API design principles and best practices
- OpenAPI 3.x specification authoring and maintenance
- FastAPI application architecture (routers, dependencies, Pydantic models)
- Express application architecture (routers, middleware chains, validation)
- Authentication patterns (JWT, OAuth2, API keys)
- Pagination, filtering, sorting, and versioning strategies
- Middleware configuration and ordering
## Skills to Load
- skills/framework-detection.md
- skills/route-patterns.md
- skills/openapi-conventions.md
- skills/middleware-catalog.md
- skills/visual-header.md
## Operating Principles
### Framework-Aware Code Generation
Always check `.api-platform.json` before generating any code. Adapt output to the detected framework:
- **FastAPI**: Use type hints, Pydantic models, dependency injection, async endpoints
- **Express**: Use middleware chains, Zod/Joi validation, async/await handlers, error-first callbacks where appropriate
### Code Quality Standards
All generated code must:
1. Include proper error handling (try/catch, HTTP exception mapping)
2. Use framework-idiomatic patterns (no mixing conventions)
3. Include inline comments explaining non-obvious design decisions
4. Follow project's existing code style (detected during setup)
5. Import only what is needed (no wildcard imports)
### RESTful Design Compliance
When generating routes:
1. Use plural nouns for resource collections (`/users`, not `/user`)
2. Use HTTP methods correctly (GET = read, POST = create, PUT = replace, PATCH = partial update, DELETE = remove)
3. Return appropriate status codes (200, 201, 204, 400, 401, 403, 404, 409, 422, 500)
4. Include pagination metadata in list responses
5. Support filtering via query parameters with consistent naming
6. Version APIs via URL prefix when configured
### Schema Generation
When creating models/schemas:
1. Separate create, update, and response schemas (different required fields)
2. Include field descriptions and examples for documentation
3. Add validation constraints (min/max length, regex patterns, enums)
4. Use proper types (datetime, UUID, Decimal where appropriate)
5. Include timestamp fields (created_at, updated_at) on response schemas
## Communication Style
Concise and technical. Show generated file contents with brief explanations of design decisions. When multiple approaches exist, explain the chosen one and why. Always list files created or modified with clear indicators ([+] new, [~] modified).

View File

@@ -0,0 +1,85 @@
---
name: api-validator
description: Read-only validation of API routes against OpenAPI specification
model: haiku
permissionMode: plan
disallowedTools: Write, Edit, MultiEdit
---
# API Validator Agent
You are a strict API compliance auditor. Your role is to compare implemented API routes against OpenAPI specifications and report discrepancies. You never modify files; you only read and report.
## Visual Output Requirements
**MANDATORY: Display header at start of every response.**
```
+----------------------------------------------------------------------+
| API-PLATFORM - API Validator |
| [Context Line] |
+----------------------------------------------------------------------+
```
## Expertise
- OpenAPI 3.x specification parsing and interpretation
- REST API compliance auditing
- Schema comparison and drift detection
- HTTP status code correctness verification
- Parameter validation (path, query, header, cookie)
## Skills to Load
- skills/openapi-conventions.md
- skills/route-patterns.md
- skills/visual-header.md
## Validation Methodology
### 1. Spec Parsing
Read the OpenAPI specification and build an internal map of:
- All defined paths with their methods
- Parameter definitions (required/optional, types, constraints)
- Request body schemas per operation
- Response schemas per status code
- Security requirements per operation
- Deprecated operations
### 2. Code Scanning
Read route files and extract:
- Registered paths and HTTP methods
- Path parameters and query parameters used
- Request body validation schemas
- Response status codes returned
- Middleware/dependency applied (auth, validation)
### 3. Cross-Reference Analysis
Compare the two maps and flag discrepancies:
| Check | Code has, Spec missing | Spec has, Code missing |
|-------|----------------------|----------------------|
| Endpoint | FAIL: Undocumented endpoint | FAIL: Unimplemented endpoint |
| Parameter | WARN: Undocumented param | WARN: Unused param in spec |
| Response code | WARN: Undocumented response | INFO: Aspirational response |
| Schema field | WARN: Schema drift | WARN: Schema drift |
| Auth requirement | WARN: Missing auth docs | FAIL: Auth not enforced |
### 4. Severity Classification
| Level | Criteria | Action |
|-------|----------|--------|
| **FAIL** | Endpoint exists in one place but not the other; auth in spec but not enforced | Must fix before release |
| **WARN** | Schema drift, undocumented parameters or status codes, deprecated endpoints still active | Should fix |
| **INFO** | Missing descriptions, missing examples, optimization suggestions | Improve documentation |
## Report Format
Always output findings grouped by severity, with exact locations (file:line where possible) and actionable fix instructions. Include a summary with endpoint coverage percentage and pass/fail verdict.
## Communication Style
Precise and factual. Report what was found, where, and what to do about it. No opinions or subjective assessments. Every finding must include the specific location and a concrete fix action.

View File

@@ -0,0 +1,64 @@
# saas-api-platform Plugin - CLAUDE.md Integration
Add this section to your project's CLAUDE.md to enable saas-api-platform plugin features.
## Suggested CLAUDE.md Section
```markdown
## API Platform Integration
This project uses the saas-api-platform plugin for API development workflows.
### Configuration
Run `/api setup` to auto-detect framework and configure project paths.
Settings stored in `.api-platform.json` in project root.
### Available Commands
| Command | Purpose |
|---------|---------|
| `/api setup` | Detect framework and configure project |
| `/api scaffold <resource>` | Generate CRUD routes, models, schemas |
| `/api validate` | Check routes against OpenAPI spec |
| `/api docs` | Generate/update OpenAPI specification |
| `/api test-routes` | Generate endpoint test cases |
| `/api middleware <type>` | Add auth, CORS, rate-limit, logging |
### When to Use
- **Starting a new resource**: `/api scaffold orders` generates routes, models, and registers the router
- **Before PR/deploy**: `/api validate` ensures spec and code are in sync
- **After route changes**: `/api docs --update` refreshes the OpenAPI spec
- **Adding infrastructure**: `/api middleware auth` adds JWT authentication
- **Before release**: `/api test-routes --coverage=full` generates comprehensive tests
### Conventions
- All routes follow RESTful naming (plural nouns, no verbs in paths)
- Versioning via URL prefix (`/v1/`) when configured
- Pagination on all list endpoints (page, page_size parameters)
- Consistent error response format with error codes and request IDs
```
## Typical Workflows
### New Resource
```
/api scaffold products
/api docs --update
/api test-routes products
/api validate
```
### Add Authentication
```
/api middleware add auth
/api validate --strict
```
### Pre-Release Check
```
/api validate --strict
/api test-routes --coverage=full
```

View File

@@ -0,0 +1,109 @@
---
name: api docs
description: Generate or update OpenAPI specification from code
agent: api-architect
---
# /api docs - OpenAPI Specification Generator
## Skills to Load
- skills/openapi-conventions.md
- skills/framework-detection.md
- skills/visual-header.md
## Visual Output
Display header: `API-PLATFORM - Docs`
## Usage
```
/api docs [--format=yaml|json] [--output=<path>] [--update]
```
**Arguments:**
- `--format`: Output format, default `yaml`
- `--output`: Output file path (default: `openapi.yaml` or `openapi.json` in project root)
- `--update`: Update existing spec instead of regenerating from scratch
## Process
### 1. Scan Route Definitions
Read all route files identified during `/api setup`:
**FastAPI:**
- Parse `@app.get`, `@app.post`, `@router.get`, etc. decorators
- Extract path, method, response_model, status_code, dependencies
- Read Pydantic model definitions for schema extraction
- Capture docstrings as endpoint descriptions
**Express:**
- Parse `router.get`, `router.post`, etc. calls
- Extract path patterns and middleware chains
- Read Zod/Joi/JSON Schema validators for schema extraction
- Capture JSDoc comments as endpoint descriptions
### 2. Build OpenAPI Document
Generate OpenAPI 3.x specification:
- **Info section**: Title from package name, version from package config
- **Servers**: Extract from environment or configuration
- **Paths**: One entry per endpoint with method, parameters, request body, responses
- **Components/Schemas**: Extracted from model/schema definitions
- **Security schemes**: Based on detected auth patterns (JWT, API key, OAuth2)
- **Tags**: Group endpoints by resource/router prefix
### 3. Handle Updates (--update mode)
When updating existing spec:
- Preserve manually-added descriptions, examples, and extensions
- Add new endpoints not yet in spec
- Flag removed endpoints for user review (do not auto-delete)
- Update schemas that changed in code
- Show diff of changes before writing
### 4. Write Output
Write the generated or updated spec to the target file.
## Output Format
```
+----------------------------------------------------------------------+
| API-PLATFORM - Docs |
+----------------------------------------------------------------------+
Mode: Generate (new)
Format: YAML
Output: ./openapi.yaml
Extracted:
Routes: 14 endpoints from 4 files
Schemas: 8 models extracted
Auth: JWT Bearer scheme detected
Tags: users, orders, products, auth
OpenAPI 3.0.3 spec written to openapi.yaml
Sections Generated:
[+] info (title, version, description)
[+] servers (1 server)
[+] paths (14 operations)
[+] components (8 schemas, 1 security scheme)
[+] tags (4 tags)
Next Steps:
- Review generated spec for accuracy
- Add examples to request/response bodies
- Run /api validate to verify consistency
```
## Important Notes
- Generated spec is a starting point; review and enrich with examples
- Descriptions are extracted from docstrings when available
- Complex schemas (inheritance, unions) may need manual adjustment
- The `--update` flag preserves manual additions to the spec

View File

@@ -0,0 +1,132 @@
---
name: api middleware
description: Add and configure API middleware
agent: api-architect
---
# /api middleware - Middleware Manager
## Skills to Load
- skills/middleware-catalog.md
- skills/framework-detection.md
- skills/visual-header.md
## Visual Output
Display header: `API-PLATFORM - Middleware`
## Usage
```
/api middleware <action> [<type>] [--options]
```
**Actions:**
- `add <type>` - Add middleware to the application
- `list` - List currently configured middleware
- `remove <type>` - Remove middleware configuration
**Middleware Types:**
- `auth` - Authentication (JWT, OAuth2, API key)
- `cors` - Cross-Origin Resource Sharing
- `rate-limit` - Rate limiting per client/IP
- `logging` - Request/response logging
- `error-handler` - Global error handling and formatting
- `validation` - Request body/query validation
## Process
### 1. Detect Framework
Read `.api-platform.json` to determine target framework. Middleware implementation differs significantly between FastAPI and Express.
### 2. Add Middleware (`add` action)
**Auth Middleware:**
- Ask user for auth type: JWT Bearer, OAuth2, API key header
- Generate middleware file with token validation logic
- Add dependency/middleware registration to app
- Create auth utility functions (decode token, verify permissions)
- Generate `.env.example` entries for secrets (JWT_SECRET, etc.)
**CORS Middleware:**
- Ask for allowed origins (default: `["*"]` for development)
- Configure allowed methods, headers, credentials
- Set max_age for preflight caching
- FastAPI: `CORSMiddleware` configuration
- Express: `cors` package configuration
**Rate Limiting:**
- Ask for rate limit strategy: fixed window, sliding window, token bucket
- Configure limits per endpoint or global (requests/minute)
- Set burst allowance
- Configure response headers (X-RateLimit-Limit, X-RateLimit-Remaining)
- FastAPI: `slowapi` or custom middleware
- Express: `express-rate-limit` package
**Logging:**
- Configure log format (JSON structured, Apache combined, custom)
- Set log levels per environment (debug for dev, info for prod)
- Include request ID generation and propagation
- Configure sensitive field masking (Authorization header, passwords)
- FastAPI: custom middleware with `structlog` or `logging`
- Express: `morgan` or `pino-http`
**Error Handler:**
- Global exception/error handler with consistent response format
- Map framework exceptions to HTTP status codes
- Include request ID in error responses
- Mask internal details in production mode
- Log full stack traces server-side
**Validation:**
- Request body validation using framework-native tools
- Query parameter validation and type coercion
- Custom validation error response format
### 3. List Middleware (`list` action)
Scan app configuration and display active middleware in execution order.
### 4. Remove Middleware (`remove` action)
Remove middleware registration and associated files. Warn about dependencies.
## Output Format
```
+----------------------------------------------------------------------+
| API-PLATFORM - Middleware |
+----------------------------------------------------------------------+
Action: add
Type: rate-limit
Framework: FastAPI
Files Created/Modified:
[+] app/middleware/rate_limit.py (rate limiter implementation)
[~] app/main.py (middleware registered)
[~] .env.example (RATE_LIMIT_PER_MINUTE added)
Configuration:
Strategy: Sliding window
Global Limit: 60 requests/minute
Burst: 10 additional
Headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset
Dependencies Added:
slowapi>=0.1.9
Next Steps:
- pip install slowapi
- Configure RATE_LIMIT_PER_MINUTE in .env
- Override per-endpoint limits in route decorators if needed
```
## Important Notes
- Middleware order matters; auth should run before rate-limiting
- CORS must be configured before route handlers
- Error handler should be the outermost middleware
- Rate limiting should use persistent store (Redis) in production

View File

@@ -0,0 +1,123 @@
---
name: api scaffold
description: Generate API routes, models, and schemas
agent: api-architect
---
# /api scaffold - Route and Model Scaffolding
## Skills to Load
- skills/framework-detection.md
- skills/route-patterns.md
- skills/openapi-conventions.md
- skills/visual-header.md
## Visual Output
Display header: `API-PLATFORM - Scaffold`
## Usage
```
/api scaffold <resource-name> [--methods=GET,POST,PUT,DELETE] [--nested-under=<parent>]
```
**Arguments:**
- `<resource-name>`: Name of the resource (e.g., `users`, `orders`, `products`)
- `--methods`: Comma-separated HTTP methods (default: all CRUD)
- `--nested-under`: Create as nested resource under parent (e.g., `--nested-under=users`)
## Prerequisites
Run `/api setup` first. This command reads `.api-platform.json` for framework and conventions.
## Process
### 1. Read Configuration
Load `.api-platform.json` to determine:
- Target framework (FastAPI or Express)
- Route and model directories
- Versioning scheme
- Response format conventions
### 2. Generate Route File
Create route/controller file with endpoints:
**FastAPI Example (`routes/{resource}.py`):**
- `GET /{version}/{resource}` - List with pagination, filtering, sorting
- `GET /{version}/{resource}/{id}` - Get by ID with 404 handling
- `POST /{version}/{resource}` - Create with request body validation
- `PUT /{version}/{resource}/{id}` - Full update with 404 handling
- `PATCH /{version}/{resource}/{id}` - Partial update
- `DELETE /{version}/{resource}/{id}` - Delete with 204 response
**Express Example (`routes/{resource}.js`):**
- Same endpoints adapted to Express router patterns
- Includes error handling middleware chain
### 3. Generate Request/Response Models
Create schema definitions appropriate to the framework:
- **FastAPI**: Pydantic models in `models/{resource}.py`
- `{Resource}Create` - POST/PUT request body
- `{Resource}Update` - PATCH request body (all fields optional)
- `{Resource}Response` - Response model with `id`, timestamps
- `{Resource}List` - Paginated list wrapper
- **Express**: JSON Schema or Zod schemas in `schemas/{resource}.js`
- Create schema, Update schema, Response schema
### 4. Generate Validation Schemas
Add input validation:
- Required fields, type constraints, string length limits
- Enum values where appropriate
- Nested object validation for complex resources
### 5. Register Routes
Update the main router/app file to include new routes:
- Add import statement
- Register route prefix
- Maintain alphabetical ordering of imports
## Output Format
```
+----------------------------------------------------------------------+
| API-PLATFORM - Scaffold |
+----------------------------------------------------------------------+
Resource: orders
Framework: FastAPI
Versioning: /v1/
Files Created:
[+] app/routes/orders.py (6 endpoints)
[+] app/models/orders.py (4 Pydantic models)
[~] app/main.py (route registered)
Endpoints Generated:
GET /v1/orders List with pagination
GET /v1/orders/{id} Get by ID
POST /v1/orders Create
PUT /v1/orders/{id} Full update
PATCH /v1/orders/{id} Partial update
DELETE /v1/orders/{id} Delete
Next Steps:
- Add business logic to route handlers
- Run /api validate to check against OpenAPI spec
- Run /api test-routes to generate test cases
```
## Nested Resources
When `--nested-under` is specified:
- Routes are prefixed: `/{parent}/{parent_id}/{resource}`
- Models include `{parent}_id` foreign key field
- Route file includes parent ID path parameter validation

View File

@@ -0,0 +1,99 @@
---
name: api setup
description: Setup wizard for saas-api-platform
agent: api-architect
---
# /api setup - API Platform Setup Wizard
## Skills to Load
- skills/framework-detection.md
- skills/visual-header.md
## Visual Output
Display header: `API-PLATFORM - Setup Wizard`
## Usage
```
/api setup
```
## Workflow
### Phase 1: Framework Detection
Scan the project root for framework indicators:
| File / Pattern | Framework | Confidence |
|----------------|-----------|------------|
| `main.py` with `from fastapi` | FastAPI | High |
| `app.py` with `from fastapi` | FastAPI | High |
| `requirements.txt` containing `fastapi` | FastAPI | Medium |
| `pyproject.toml` with `fastapi` dependency | FastAPI | Medium |
| `package.json` with `express` dependency | Express | High |
| `app.js` or `app.ts` with `require('express')` | Express | High |
| `tsconfig.json` + express in deps | Express (TypeScript) | High |
If no framework detected, ask user to select one.
### Phase 2: Project Structure Mapping
Identify existing project layout:
- **Route files**: Locate route/controller directories
- **Models**: Locate model/schema definition files
- **Middleware**: Locate existing middleware
- **Tests**: Locate test directories and test runner config
- **OpenAPI spec**: Check for existing `openapi.yaml`, `openapi.json`, or `swagger.json`
Report findings to user with directory tree.
### Phase 3: Convention Configuration
Ask user about project conventions:
- **Route style**: RESTful nested (`/users/{id}/posts`) vs flat (`/user-posts`)
- **Versioning**: URL prefix (`/v1/`) vs header-based vs none
- **Auth pattern**: JWT, OAuth2, API key, or none
- **Response format**: JSON:API, HAL, plain JSON
Store decisions in `.api-platform.json` in project root for future commands.
### Phase 4: Validation
Verify detected configuration:
- Confirm framework version
- Confirm route directory location
- Confirm model directory location
- Display summary with all detected settings
## Output Format
```
+----------------------------------------------------------------------+
| API-PLATFORM - Setup Wizard |
+----------------------------------------------------------------------+
Framework: FastAPI 0.104.1
Route Dir: ./app/routes/
Models Dir: ./app/models/
Tests Dir: ./tests/
OpenAPI Spec: ./openapi.yaml (existing)
Conventions:
Versioning: /v1/ URL prefix
Auth: JWT Bearer
Response: Plain JSON
Configuration saved to .api-platform.json
```
## Important Notes
- This command does NOT create project files; it only detects and configures
- If `.api-platform.json` already exists, offer to update or keep existing
- All subsequent commands rely on setup configuration

View File

@@ -0,0 +1,126 @@
---
name: api test-routes
description: Generate request/response test cases for API endpoints
agent: api-architect
---
# /api test-routes - API Test Generator
## Skills to Load
- skills/route-patterns.md
- skills/visual-header.md
## Visual Output
Display header: `API-PLATFORM - Test Routes`
## Usage
```
/api test-routes [<resource>] [--coverage=basic|full] [--runner=pytest|jest|vitest]
```
**Arguments:**
- `<resource>`: Specific resource to generate tests for (default: all)
- `--coverage`: `basic` generates happy-path only; `full` includes edge cases (default: `full`)
- `--runner`: Test runner to target (auto-detected from project)
## Prerequisites
Run `/api setup` first. Route files must exist (either manually written or via `/api scaffold`).
## Process
### 1. Detect Test Runner
Auto-detect based on framework:
- **FastAPI**: `pytest` with `httpx` (TestClient)
- **Express**: `jest` or `vitest` with `supertest`
Check for existing test config (`pytest.ini`, `jest.config.*`, `vitest.config.*`).
### 2. Scan Endpoints
For each route file, extract:
- HTTP method and path
- Required and optional parameters
- Request body schema with field types and constraints
- Expected response status codes
- Authentication requirements
### 3. Generate Test Cases
For each endpoint, generate test cases in categories:
**Happy Path (basic coverage):**
- Valid request returns expected status code
- Response body matches expected schema
- List endpoints return paginated results
- Create endpoint returns created resource with ID
**Validation (full coverage):**
- Missing required fields returns 422/400
- Invalid field types return 422/400
- String fields exceeding max length return 422/400
- Invalid enum values return 422/400
**Authentication (full coverage):**
- Request without auth token returns 401
- Request with expired token returns 401
- Request with insufficient permissions returns 403
**Edge Cases (full coverage):**
- GET non-existent resource returns 404
- DELETE already-deleted resource returns 404
- PUT with partial body returns 422/400
- Concurrent creation of duplicate resources
**Pagination (full coverage for list endpoints):**
- Default pagination returns correct page size
- Custom page size works correctly
- Out-of-range page returns empty results
- Sort parameters produce correct ordering
### 4. Write Test Files
Create test files in the project test directory:
- One test file per resource
- Test fixtures for common setup (auth tokens, sample data)
- Helper functions for repetitive assertions
## Output Format
```
+----------------------------------------------------------------------+
| API-PLATFORM - Test Routes |
+----------------------------------------------------------------------+
Coverage: full
Runner: pytest + httpx
Resource: orders
Files Created:
[+] tests/test_orders.py (18 test cases)
[+] tests/conftest.py (fixtures updated)
Test Cases Generated:
Happy Path: 6 tests
Validation: 5 tests
Auth: 3 tests
Edge Cases: 4 tests
Total: 18 test cases for 6 endpoints
Next Steps:
- Review generated tests and adjust sample data
- Add database fixtures for integration tests
- Run: pytest tests/test_orders.py -v
```
## Important Notes
- Generated tests use placeholder sample data; review and adjust for your domain
- Auth tests require a fixture that provides valid/invalid tokens
- Integration tests may need database setup/teardown fixtures
- Tests follow Arrange-Act-Assert pattern

View File

@@ -0,0 +1,124 @@
---
name: api validate
description: Validate routes against OpenAPI specification
agent: api-validator
---
# /api validate - OpenAPI Validation
## Skills to Load
- skills/openapi-conventions.md
- skills/route-patterns.md
- skills/visual-header.md
## Visual Output
Display header: `API-PLATFORM - Validate`
## Usage
```
/api validate [--spec=<path>] [--strict]
```
**Arguments:**
- `--spec`: Path to OpenAPI spec file (default: auto-detect `openapi.yaml` or `openapi.json`)
- `--strict`: Treat warnings as errors
## Prerequisites
Run `/api setup` first. Requires an existing OpenAPI specification to validate against.
## Process
### 1. Locate OpenAPI Spec
Search for spec file in order:
1. Path provided via `--spec` flag
2. `openapi.yaml` in project root
3. `openapi.json` in project root
4. `swagger.yaml` or `swagger.json` in project root
5. `docs/openapi.yaml` or `docs/openapi.json`
If not found, report error and suggest `/api docs` to generate one.
### 2. Parse Route Definitions
Scan route files to extract implemented endpoints:
- HTTP method and path pattern
- Path parameters and query parameters
- Request body schema (if POST/PUT/PATCH)
- Response status codes and schemas
- Authentication requirements
### 3. Compare Against Spec
Run validation checks:
| Check | Severity | Description |
|-------|----------|-------------|
| Missing endpoint in spec | FAIL | Route exists in code but not in OpenAPI spec |
| Missing endpoint in code | FAIL | Spec defines endpoint not implemented |
| Parameter mismatch | FAIL | Path/query parameters differ between code and spec |
| Schema mismatch | WARN | Request/response model fields differ from spec |
| Missing response codes | WARN | Code returns status codes not documented in spec |
| Missing descriptions | INFO | Endpoints or parameters lack descriptions |
| Missing examples | INFO | Spec lacks request/response examples |
| Deprecated endpoint still active | WARN | Spec marks endpoint deprecated but code still serves it |
### 4. Generate Report
Group findings by severity and provide actionable fixes.
## Output Format
```
+----------------------------------------------------------------------+
| API-PLATFORM - Validate |
+----------------------------------------------------------------------+
Spec: openapi.yaml (OpenAPI 3.0.3)
Routes Scanned: 14 endpoints in 4 files
Spec Endpoints: 16 defined
FINDINGS
FAIL (2)
1. [POST /v1/orders] Missing from OpenAPI spec
Fix: Add path definition to openapi.yaml
2. [GET /v1/users] Query param 'role' not in spec
Fix: Add 'role' query parameter to path definition
WARN (3)
1. [PUT /v1/products/{id}] Response 422 not documented
Fix: Add 422 response to spec with validation error schema
2. [GET /v1/orders] Schema mismatch - 'total_amount' field
Code: float, Spec: string
Fix: Update spec to use number type
3. [DELETE /v1/users/{id}] Marked deprecated in spec
Suggestion: Remove endpoint or update spec status
INFO (1)
1. [GET /v1/products] Missing response example
Suggestion: Add example to improve documentation
SUMMARY
Endpoints: 14 implemented / 16 in spec
Coverage: 87.5%
FAIL: 2 (must fix)
WARN: 3 (should fix)
INFO: 1 (improve)
VERDICT: FAIL (2 blocking issues)
```
## Exit Guidance
- FAIL findings: Block deployment, spec and code must agree
- WARN findings: Fix before release for accurate documentation
- INFO findings: Improve for developer experience
- `--strict` mode: All WARN become FAIL

View File

@@ -0,0 +1,19 @@
---
name: api
description: API development toolkit — route scaffolding, OpenAPI validation, middleware management
---
# /api
REST and GraphQL API scaffolding, validation, and documentation for FastAPI and Express.
## Sub-commands
| Sub-command | Description |
|-------------|-------------|
| `/api setup` | Setup wizard for saas-api-platform |
| `/api scaffold` | Generate routes, models, and schemas |
| `/api validate` | Validate routes against OpenAPI spec |
| `/api docs` | Generate or update OpenAPI specification |
| `/api test-routes` | Generate test cases for API endpoints |
| `/api middleware` | Add and configure middleware |

View File

@@ -0,0 +1,81 @@
---
name: framework-detection
description: Detect FastAPI vs Express, identify project structure, locate route files and models
---
# Framework Detection
## Purpose
Identify the API framework in use and map the project structure. This skill is loaded by the `api-architect` agent during setup and code generation to ensure framework-appropriate output.
---
## Detection Rules
### FastAPI Detection
| Indicator | Location | Confidence |
|-----------|----------|------------|
| `from fastapi import` in Python files | `*.py` | High |
| `fastapi` in `requirements.txt` | Project root | Medium |
| `fastapi` in `pyproject.toml` dependencies | Project root | Medium |
| `uvicorn` in requirements alongside fastapi | Project root | High |
| `@app.get`, `@router.post` decorators | `*.py` | High |
**FastAPI Project Structure (typical):**
```
app/
__init__.py
main.py # FastAPI app instance, middleware, router includes
routes/ # Route modules (one per resource)
models/ # Pydantic models (request/response schemas)
dependencies/ # Dependency injection functions
middleware/ # Custom middleware
core/ # Config, security, database setup
```
### Express Detection
| Indicator | Location | Confidence |
|-----------|----------|------------|
| `express` in `package.json` dependencies | Project root | High |
| `require('express')` or `import express` | `*.js`, `*.ts` | High |
| `express.Router()` usage | `*.js`, `*.ts` | High |
| `tsconfig.json` present alongside Express | Project root | Express+TS variant |
**Express Project Structure (typical):**
```
src/
app.js or app.ts # Express app instance, middleware, router mounts
routes/ # Route modules (one per resource)
models/ # Database models (Sequelize, Mongoose, etc.)
schemas/ # Validation schemas (Zod, Joi)
middleware/ # Custom middleware
config/ # Environment config, database setup
```
---
## Project Mapping Procedure
1. **Check package files first**: `requirements.txt`, `pyproject.toml`, `package.json`
2. **Scan entry points**: `main.py`, `app.py`, `app.js`, `app.ts`, `index.js`, `index.ts`
3. **Locate route directory**: Search for `routes/`, `routers/`, `controllers/`, `api/`
4. **Locate model directory**: Search for `models/`, `schemas/`, `entities/`
5. **Locate test directory**: Search for `tests/`, `test/`, `__tests__/`, `spec/`
6. **Check for existing OpenAPI spec**: `openapi.yaml`, `openapi.json`, `swagger.*`
---
## Framework Version Detection
**FastAPI**: Parse version from `requirements.txt` pin or `pyproject.toml` constraint. Important for feature availability (e.g., `lifespan` parameter in 0.93+).
**Express**: Parse version from `package.json` dependencies. Important for middleware compatibility (Express 4 vs 5).
---
## Ambiguous Projects
If both FastAPI and Express indicators are found (monorepo), ask the user which service to target. Store the selection in `.api-platform.json` with a `service_root` field pointing to the specific service directory.

View File

@@ -0,0 +1,137 @@
---
name: middleware-catalog
description: Common middleware patterns for auth, CORS, rate-limiting, logging, and error handling per framework
---
# Middleware Catalog
## Purpose
Reference catalog of middleware patterns for FastAPI and Express. This skill is loaded by the `api-architect` agent when adding or configuring middleware, ensuring correct implementation per framework.
---
## Middleware Execution Order
Middleware should be registered in this order (outermost to innermost):
1. **Error Handler** - Catches all unhandled exceptions
2. **CORS** - Must run before any route processing
3. **Request ID** - Generate unique ID for tracing
4. **Logging** - Log incoming request details
5. **Rate Limiting** - Reject excessive requests early
6. **Authentication** - Validate credentials
7. **Authorization** - Check permissions (often per-route)
8. **Validation** - Validate request body/params (often per-route)
9. **Route Handler** - Business logic
---
## Authentication Middleware
### JWT Bearer (FastAPI)
- Use `fastapi.security.HTTPBearer` dependency
- Decode token with `python-jose` or `PyJWT`
- Store decoded claims in request state
- Return 401 for missing/invalid/expired tokens
- Environment: `JWT_SECRET`, `JWT_ALGORITHM` (default HS256)
### JWT Bearer (Express)
- Use `express-jwt` or custom middleware
- Decode token from `Authorization: Bearer <token>` header
- Attach decoded user to `req.user`
- Return 401 for missing/invalid/expired tokens
- Environment: `JWT_SECRET`, `JWT_ALGORITHM`
### API Key
- Read from `X-API-Key` header
- Compare against stored keys (database or environment)
- Return 401 for missing key, 403 for invalid key
---
## CORS Middleware
### FastAPI
```python
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Restrict in production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
max_age=600,
)
```
### Express
```javascript
const cors = require('cors');
app.use(cors({
origin: '*', // Restrict in production
credentials: true,
methods: ['GET','POST','PUT','PATCH','DELETE'],
maxAge: 600,
}));
```
---
## Rate Limiting
### Strategies
- **Fixed window**: N requests per time window (simple, bursty at boundaries)
- **Sliding window**: Smooth rate enforcement (recommended)
- **Token bucket**: Allows controlled bursts
### Response Headers
- `X-RateLimit-Limit`: Maximum requests allowed
- `X-RateLimit-Remaining`: Requests remaining in window
- `X-RateLimit-Reset`: Timestamp when limit resets
### Production Notes
- Use Redis as backend store for distributed rate limiting
- In-memory stores do not work with multiple server instances
- Consider different limits for authenticated vs anonymous users
---
## Logging Middleware
### Structured Logging Fields
Every request log entry should include:
- `request_id`: Unique identifier for tracing
- `method`: HTTP method
- `path`: Request path
- `status_code`: Response status
- `duration_ms`: Processing time
- `client_ip`: Client IP address
- `user_id`: Authenticated user ID (if available)
### Sensitive Field Masking
Never log: `Authorization` header values, request bodies containing `password`, `token`, `secret`, `credit_card` fields.
---
## Error Handler
### Standard Error Response
All errors must produce consistent JSON:
```json
{
"error": {
"code": "ERROR_CODE",
"message": "Human-readable message",
"request_id": "abc-123"
}
}
```
### Exception Mapping
- Validation errors: 422 with field-level details
- Not found: 404 with resource type and ID
- Authentication: 401 with generic message (no details)
- Authorization: 403 with required permission
- Conflict: 409 with conflicting field
- Internal: 500 with request_id only (no stack traces in production)

View File

@@ -0,0 +1,125 @@
---
name: openapi-conventions
description: OpenAPI 3.x spec generation rules, path naming, schema definitions, response codes
---
# OpenAPI Conventions
## Purpose
Defines rules and patterns for generating and validating OpenAPI 3.x specifications. This skill ensures consistency between generated specs and industry best practices.
---
## Specification Structure
An OpenAPI 3.0.3 document must include:
```yaml
openapi: "3.0.3"
info:
title: <project name>
version: <project version>
description: <project description>
servers:
- url: <base url>
description: <environment name>
paths:
/<resource>: ...
components:
schemas: ...
securitySchemes: ...
tags: ...
```
---
## Path Naming Rules
| Rule | Example | Anti-Pattern |
|------|---------|-------------|
| Plural nouns for collections | `/users` | `/user`, `/getUsers` |
| Lowercase with hyphens | `/order-items` | `/orderItems`, `/order_items` |
| Resource ID in path | `/users/{user_id}` | `/users?id=123` |
| Nested resources max 2 levels | `/users/{id}/orders` | `/users/{id}/orders/{oid}/items/{iid}` |
| No verbs in paths | `/users` + POST | `/createUser` |
| Version prefix when configured | `/v1/users` | `/api/v1/users` (redundant) |
---
## Response Code Standards
| Method | Success | Client Error | Server Error |
|--------|---------|-------------|-------------|
| GET (single) | 200 | 404 | 500 |
| GET (list) | 200 | 400 (bad params) | 500 |
| POST | 201 | 400, 409 (conflict), 422 | 500 |
| PUT | 200 | 400, 404, 422 | 500 |
| PATCH | 200 | 400, 404, 422 | 500 |
| DELETE | 204 | 404 | 500 |
All endpoints should also document 401 (unauthorized) and 403 (forbidden) when auth is required.
---
## Schema Definition Rules
1. **Naming**: PascalCase for schema names (`UserCreate`, `OrderResponse`)
2. **Reuse**: Use `$ref` for shared schemas instead of duplication
3. **Required fields**: Explicitly list required fields; do not rely on defaults
4. **Types**: Use specific types (`integer` not `number` for IDs; `string` with `format: date-time` for timestamps)
5. **Descriptions**: Every property should have a `description` field
6. **Examples**: Include `example` values for key properties
7. **Nullable**: Use `nullable: true` explicitly when fields can be null
---
## Pagination Schema
List endpoints must return a paginated wrapper:
```yaml
PaginatedResponse:
type: object
properties:
items:
type: array
items:
$ref: '#/components/schemas/ResourceResponse'
total:
type: integer
description: Total number of items
page:
type: integer
description: Current page number
page_size:
type: integer
description: Items per page
pages:
type: integer
description: Total number of pages
```
---
## Security Scheme Patterns
**JWT Bearer:**
```yaml
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
```
**API Key:**
```yaml
securitySchemes:
ApiKeyAuth:
type: apiKey
in: header
name: X-API-Key
```
Apply globally or per-operation using the `security` field.

View File

@@ -0,0 +1,112 @@
---
name: route-patterns
description: RESTful naming, versioning, pagination, filtering, and sorting conventions
---
# Route Patterns
## Purpose
Defines standard patterns for RESTful route design. This skill is loaded during scaffolding and validation to ensure generated routes follow consistent, industry-standard conventions.
---
## RESTful Resource Naming
| Pattern | URL | Method | Purpose |
|---------|-----|--------|---------|
| List | `/{resource}` | GET | Retrieve paginated collection |
| Create | `/{resource}` | POST | Create new resource |
| Get | `/{resource}/{id}` | GET | Retrieve single resource |
| Replace | `/{resource}/{id}` | PUT | Full replacement of resource |
| Update | `/{resource}/{id}` | PATCH | Partial update |
| Delete | `/{resource}/{id}` | DELETE | Remove resource |
### Nested Resources
For parent-child relationships (max 2 levels deep):
| Pattern | URL | Example |
|---------|-----|---------|
| Child list | `/{parent}/{parent_id}/{child}` | `/users/42/orders` |
| Child create | `/{parent}/{parent_id}/{child}` | POST `/users/42/orders` |
| Child get | `/{parent}/{parent_id}/{child}/{child_id}` | `/users/42/orders/7` |
Beyond 2 levels, flatten with query filters: `/items?order_id=7&user_id=42`
---
## Versioning
| Strategy | Format | Example |
|----------|--------|---------|
| URL prefix (recommended) | `/v{N}/` | `/v1/users`, `/v2/users` |
| Header-based | `Accept: application/vnd.api.v1+json` | Header value |
| Query param (discouraged) | `?version=1` | `/users?version=1` |
URL prefix versioning is the default. Only bump major version for breaking changes.
---
## Pagination
All list endpoints must support pagination:
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `page` | integer | 1 | Page number (1-indexed) |
| `page_size` | integer | 20 | Items per page (max 100) |
Response must include pagination metadata:
```json
{
"items": [...],
"total": 142,
"page": 2,
"page_size": 20,
"pages": 8
}
```
---
## Filtering
Use query parameters for filtering:
| Pattern | Example | Description |
|---------|---------|-------------|
| Exact match | `?status=active` | Field equals value |
| Multiple values | `?status=active,pending` | Field in list |
| Range | `?created_after=2024-01-01&created_before=2024-12-31` | Date/number range |
| Search | `?q=search+term` | Full-text search |
---
## Sorting
| Parameter | Format | Example |
|-----------|--------|---------|
| `sort` | `field` (asc) or `-field` (desc) | `?sort=-created_at` |
| Multiple | Comma-separated | `?sort=-created_at,name` |
---
## Error Response Format
All errors must use a consistent structure:
```json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Human-readable description",
"details": [
{"field": "email", "message": "Invalid email format"}
],
"request_id": "abc-123"
}
}
```
Error codes should be uppercase snake_case constants: `NOT_FOUND`, `UNAUTHORIZED`, `VALIDATION_ERROR`, `CONFLICT`, `INTERNAL_ERROR`.

View File

@@ -0,0 +1,49 @@
---
name: visual-header
description: Standard header format for API platform commands and agents
---
# Visual Header
## Standard Format
Display at the start of every command execution:
```
+----------------------------------------------------------------------+
| API-PLATFORM - [Command Name] |
+----------------------------------------------------------------------+
```
## Command Headers
| Command | Header Text |
|---------|-------------|
| api-setup | Setup Wizard |
| api-scaffold | Scaffold |
| api-validate | Validate |
| api-docs | Docs |
| api-test-routes | Test Routes |
| api-middleware | Middleware |
## Summary Box Format
For completion summaries:
```
+============================================================+
| API-PLATFORM [OPERATION] COMPLETE |
+============================================================+
| Component: [Status] |
| Component: [Status] |
+============================================================+
```
## Status Indicators
- Success: `[check]` or `Ready`
- Warning: `[!]` or `Partial`
- Failure: `[X]` or `Failed`
- New file: `[+]`
- Modified file: `[~]`
- Deleted file: `[-]`