# API.md
**Date:** 2025-10-08
**Version:** 1.0.0
## API Overview
docs-mcp provides a Model Context Protocol (MCP) API for AI assistants to access documentation templates and prompt framework resources. The API exposes three tool endpoints via JSON-RPC over stdio transport, enabling structured documentation generation capabilities.
**Project Reference:** docs-mcp is an MCP server providing structured access to POWER framework templates (README, Architecture, API, Components, Schema) and prompt engineering frameworks (POWER, COSTAR, Five S, CRISPE).
**Architecture Reference:** Built on MCP SDK for Python with async I/O, stdio transport, and file-based template storage. Single-threaded asyncio event loop with read-only file system access. See ARCHITECTURE.md for system topology and data flow details.
## Protocol Details
### Transport Layer
- **Protocol:** Model Context Protocol (MCP) v1.0
- **Transport:** stdio (standard input/output)
- **Message Format:** JSON-RPC 2.0
- **Encoding:** UTF-8
### Communication Pattern
```
Client → JSON-RPC Request → stdio → Server
Server → JSON-RPC Response → stdio → Client
```
## Authentication & Authorization
**Authentication:** None (local-only access via stdio transport)
- No API keys, tokens, or credentials required
- Server inherits parent process permissions
- Access restricted to processes that can spawn the server
**Authorization:** Read-only access
- All operations are read-only file system access
- No write, delete, or execute permissions required
- Predefined directory access only (templates/, frameworks/)
## Rate Limits & Quotas
**Rate Limits:** None
- Local stdio transport has no artificial rate limiting
- Limited only by system I/O performance
**Quotas:** None
- Unlimited requests per time period
- No usage tracking or throttling
**Concurrency:**
- Single-threaded async event loop
- One request processed at a time (MCP model)
- No concurrent request handling
## API Endpoints
### 1. list_templates
Lists all available POWER framework documentation templates.
**Tool Name:** `list_templates`
**Input Schema:**
```json
{
"type": "object",
"properties": {},
"required": []
}
```
**Request Example:**
```json
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "list_templates",
"arguments": {}
}
}
```
**Response Schema:**
```json
{
"type": "object",
"properties": {
"content": {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": { "const": "text" },
"text": { "type": "string" }
}
}
}
}
}
```
**Success Response Example:**
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"content": [
{
"type": "text",
"text": "Available POWER Framework Templates:\n\n1. api\n2. architecture\n3. components\n4. readme\n5. schema\n\nTotal: 5 templates"
}
]
}
}
```
**Error Response Example:**
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"content": [
{
"type": "text",
"text": "Error listing templates: Permission denied"
}
]
}
}
```
**Implementation:** server.py:68-85
- Scans `TEMPLATES_DIR / "*.txt"` files
- Extracts filename stems (without .txt extension)
- Returns sorted, numbered list with total count
---
### 2. get_template
Retrieves the full content of a specific documentation template.
**Tool Name:** `get_template`
**Input Schema:**
```json
{
"type": "object",
"properties": {
"template_name": {
"type": "string",
"description": "Name of template: readme, architecture, api, components, or schema",
"enum": ["readme", "architecture", "api", "components", "schema"]
}
},
"required": ["template_name"]
}
```
**Request Example:**
```json
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "get_template",
"arguments": {
"template_name": "api"
}
}
}
```
**Response Schema:**
```json
{
"type": "object",
"properties": {
"content": {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": { "const": "text" },
"text": { "type": "string" }
}
}
}
}
}
```
**Success Response Example:**
```json
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"content": [
{
"type": "text",
"text": "=== API Template ===\n\nframework: POWER\npurpose: Generate API.md as the technical interface reference.\noutput: Must follow required header/footer with [Date] and [Version]...\n..."
}
]
}
}
```
**Error Response Examples:**
*Template Not Found:*
```json
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"content": [
{
"type": "text",
"text": "Template 'invalid' not found. Available: readme, architecture, api, components, schema"
}
]
}
}
```
*File Read Error:*
```json
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"content": [
{
"type": "text",
"text": "Error reading template: [Errno 13] Permission denied: 'api.txt'"
}
]
}
}
```
**Implementation:** server.py:87-104
- Validates `template_name` against enum: ["readme", "architecture", "api", "components", "schema"]
- Constructs path: `TEMPLATES_DIR / f"{template_name}.txt"`
- Checks file existence before reading
- Reads file with UTF-8 encoding
- Returns content with formatted header
**Template Format:**
All templates follow POWER framework structure:
```
framework: POWER
purpose: [Document objective]
output: [Required format]
work: [Process steps]
examples: [Usage samples]
requirements: [Mandatory elements]
save_as: [Default filename]
store_as: [Reference name]
```
---
### 3. list_frameworks
Lists available prompt engineering framework documentation files.
**Tool Name:** `list_frameworks`
**Input Schema:**
```json
{
"type": "object",
"properties": {},
"required": []
}
```
**Request Example:**
```json
{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "list_frameworks",
"arguments": {}
}
}
```
**Response Schema:**
```json
{
"type": "object",
"properties": {
"content": {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": { "const": "text" },
"text": { "type": "string" }
}
}
}
}
}
```
**Success Response Example:**
```json
{
"jsonrpc": "2.0",
"id": 3,
"result": {
"content": [
{
"type": "text",
"text": "Available Framework Documentation:\n\n1. COSTAR.md (3,245 bytes)\n2. CRISPE.md (2,891 bytes)\n3. FiveS.md (3,102 bytes)\n4. POWER.md (4,567 bytes)\n\nTotal: 4 framework docs"
}
]
}
}
```
**Error Response Example:**
```json
{
"jsonrpc": "2.0",
"id": 3,
"result": {
"content": [
{
"type": "text",
"text": "Error listing frameworks: [Errno 2] No such file or directory: 'frameworks/'"
}
]
}
}
```
**Implementation:** server.py:106-125
- Scans `FRAMEWORKS_DIR / "*.md"` files
- Retrieves file sizes via `stat().st_size`
- Returns sorted, numbered list with sizes and total count
---
## Error Handling
### Error Response Pattern
All errors are returned as successful JSON-RPC responses with error messages in the TextContent:
```json
{
"jsonrpc": "2.0",
"id": <request_id>,
"result": {
"content": [
{
"type": "text",
"text": "Error <operation>: <error_message>"
}
]
}
}
```
**Design Rationale:** Server never crashes on tool errors; all exceptions are caught and returned as TextContent messages.
### Common Error Types
| Error Type | Cause | Example Message | HTTP Equivalent |
|------------|-------|-----------------|-----------------|
| **Template Not Found** | Invalid template name or missing file | `Template 'xyz' not found. Available: readme, architecture, api, components, schema` | 404 Not Found |
| **Permission Denied** | File system permission issue | `Error reading template: [Errno 13] Permission denied` | 403 Forbidden |
| **Directory Not Found** | Missing templates/ or frameworks/ directory | `No templates found in templates/power/` | 404 Not Found |
| **File Read Error** | Encoding or I/O error | `Error reading template: UnicodeDecodeError` | 500 Internal Error |
| **Invalid Tool** | Unknown tool name | `Unknown tool: invalid_tool` | 400 Bad Request |
### Error Handling Implementation
**Implementation References:**
- Template listing errors: server.py:84-85
- Template retrieval errors: server.py:92-96, 103-104
- Framework listing errors: server.py:124-125
- Unknown tool errors: server.py:127-128
**Error Recovery:**
- All file operations wrapped in try-except blocks
- Graceful degradation (missing templates return empty lists)
- Descriptive error messages for debugging
- Server remains responsive after errors
---
## Data Types & Schemas
### Tool Type
```python
Tool(
name: str, # Tool identifier
description: str, # Human-readable description
inputSchema: dict # JSON Schema for input validation
)
```
### TextContent Type
```python
TextContent(
type: "text", # Content type (always "text")
text: str # Response content
)
```
### Input Validation
**template_name Enum:**
```json
{
"enum": ["readme", "architecture", "api", "components", "schema"]
}
```
- Case-sensitive (lowercase only)
- Enforced at tool registration (server.py:46)
- Invalid values return error, not exception
---
## Usage Examples
### Example 1: Discover Available Templates
**Request:**
```json
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "list_templates",
"arguments": {}
}
}
```
**Response:**
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"content": [
{
"type": "text",
"text": "Available POWER Framework Templates:\n\n1. api\n2. architecture\n3. components\n4. readme\n5. schema\n\nTotal: 5 templates"
}
]
}
}
```
**Use Case:** AI assistant discovers available documentation types before requesting specific template.
---
### Example 2: Retrieve README Template
**Request:**
```json
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "get_template",
"arguments": {
"template_name": "readme"
}
}
}
```
**Response:**
```json
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"content": [
{
"type": "text",
"text": "=== README Template ===\n\nframework: POWER\npurpose: Generate README.md as the primary project documentation...\n..."
}
]
}
}
```
**Use Case:** AI assistant retrieves README template to generate project documentation following POWER framework.
---
### Example 3: Explore Prompt Frameworks
**Request:**
```json
{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "list_frameworks",
"arguments": {}
}
}
```
**Response:**
```json
{
"jsonrpc": "2.0",
"id": 3,
"result": {
"content": [
{
"type": "text",
"text": "Available Framework Documentation:\n\n1. COSTAR.md (3,245 bytes)\n2. CRISPE.md (2,891 bytes)\n3. FiveS.md (3,102 bytes)\n4. POWER.md (4,567 bytes)\n\nTotal: 4 framework docs"
}
]
}
}
```
**Use Case:** AI assistant discovers available prompt engineering frameworks for reference.
---
### Example 4: Error Handling - Invalid Template
**Request:**
```json
{
"jsonrpc": "2.0",
"id": 4,
"method": "tools/call",
"params": {
"name": "get_template",
"arguments": {
"template_name": "invalid"
}
}
}
```
**Response:**
```json
{
"jsonrpc": "2.0",
"id": 4,
"result": {
"content": [
{
"type": "text",
"text": "Template 'invalid' not found. Available: readme, architecture, api, components, schema"
}
]
}
}
```
**Use Case:** AI assistant handles invalid input gracefully, receives actionable error message.
---
## Client Integration
### Python Client Example
```python
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def use_docs_mcp():
server_params = StdioServerParameters(
command="python",
args=["C:\\Users\\willh\\.mcp-servers\\docs-mcp\\server.py"]
)
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# List templates
result = await session.call_tool("list_templates", {})
print(result.content[0].text)
# Get specific template
result = await session.call_tool("get_template", {
"template_name": "readme"
})
print(result.content[0].text)
asyncio.run(use_docs_mcp())
```
### Claude Desktop Configuration
```json
{
"mcpServers": {
"docs-mcp": {
"command": "python",
"args": ["C:\\Users\\willh\\.mcp-servers\\docs-mcp\\server.py"]
}
}
}
```
**Configuration File Location:**
- Windows: `%APPDATA%\Claude\claude_desktop_config.json`
- macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
- Linux: `~/.config/Claude/claude_desktop_config.json`
---
## Performance Characteristics
### Response Times
- **list_templates:** < 10ms (directory scan, ~5 files)
- **get_template:** < 20ms (file read, ~5-10KB files)
- **list_frameworks:** < 15ms (directory scan + stat, ~4 files)
**Factors:**
- Local file system I/O (no network latency)
- Small file sizes (< 10KB per template)
- No caching (fresh reads each request)
- Single-threaded async (no parallelization)
### Scalability
- **Templates:** Scales linearly with number of .txt files in templates/power/
- **Frameworks:** Scales linearly with number of .md files in frameworks/
- **Concurrent Requests:** Single-threaded (one at a time)
- **Memory:** Minimal (< 5MB typical, no caching)
**Limits:**
- Practical limit: ~100 templates (directory scan performance)
- File size limit: None (but large files block event loop)
- Request size: No artificial limits
---
## Versioning
**API Version:** 1.0.0
**MCP Protocol:** 1.0
**Server Version:** 1.0.0 (see README.md)
**Versioning Policy:**
- **Major version (1.x.x):** Breaking changes to tool schemas or behavior
- **Minor version (x.1.x):** New tools or backward-compatible features
- **Patch version (x.x.1):** Bug fixes, no API changes
**Backward Compatibility:**
- Tool names are stable (no renames without major version bump)
- Input schemas are additive (new optional fields only)
- Output format (TextContent) is stable
- File paths and directory structure are internal (may change)
---
## Security Considerations
### Access Control
- **Authentication:** None required (local-only stdio transport)
- **Authorization:** Read-only file system access
- **Scope:** Restricted to `templates/` and `frameworks/` directories
### Input Validation
- **Template Names:** Restricted to enum: ["readme", "architecture", "api", "components", "schema"]
- **No Path Traversal:** Uses pathlib, validates template names, no user-provided paths
- **No Command Injection:** No shell execution or eval()
### File System Safety
- **Read-Only:** No write, delete, or execute operations
- **Predefined Paths:** Only reads from `SERVER_DIR/templates/power/` and `SERVER_DIR/frameworks/`
- **Error Handling:** File errors return messages, never expose sensitive paths
### Transport Security
- **stdio Only:** No network exposure
- **Local Process:** Inherits parent process permissions
- **No Remote Access:** Cannot be accessed over network
**Risk Assessment:** Low risk for local AI assistant integration. No write operations, no network exposure, no user-provided paths.
---
## Troubleshooting
### Issue: Tool Not Found
**Symptom:** `Unknown tool: <name>`
**Causes:**
- Tool name misspelled
- Server not restarted after tool addition
- Client using outdated tool list
**Resolution:**
1. Verify tool name matches exactly: `list_templates`, `get_template`, `list_frameworks`
2. Check `@app.list_tools()` registration (server.py:24-61)
3. Restart MCP server and reinitialize client session
---
### Issue: Template Not Found
**Symptom:** `Template 'xyz' not found. Available: readme, architecture, api, components, schema`
**Causes:**
- Invalid template name (not in enum)
- Template file missing from templates/power/
- File extension mismatch (.txt expected)
**Resolution:**
1. Use valid template names: `readme`, `architecture`, `api`, `components`, `schema`
2. Verify file exists: `templates/power/{template_name}.txt`
3. Check file permissions (must be readable)
4. Use `list_templates` to see available options
---
### Issue: Permission Denied
**Symptom:** `Error reading template: [Errno 13] Permission denied`
**Causes:**
- Insufficient file permissions
- File locked by another process
- Parent directory not readable
**Resolution:**
1. Check file permissions: `ls -l templates/power/`
2. Ensure read access for user running server
3. Verify parent directories have execute permission
4. Close any processes locking the files
---
### Issue: Empty Template List
**Symptom:** `No templates found in templates/power/`
**Causes:**
- templates/power/ directory doesn't exist
- No .txt files in directory
- Incorrect working directory
**Resolution:**
1. Verify directory exists: `C:\Users\willh\.mcp-servers\docs-mcp\templates\power\`
2. Check for .txt files: `dir templates\power\*.txt` (Windows) or `ls templates/power/*.txt` (Unix)
3. Ensure server runs from correct directory (SERVER_DIR)
4. Check server.py:17 for TEMPLATES_DIR path
---
## Related Documentation
- **README.md:** Project overview, installation, usage examples, troubleshooting
- **ARCHITECTURE.md:** System topology, module boundaries, data flow, technology stack, design rationale
- **COMPONENTS.md:** (Future) Component-level documentation
- **SCHEMA.md:** (Future) Data schema documentation
---
## AI Integration Notes
This API is optimized for AI assistant integration. Key patterns for AI clients:
### Tool Discovery
1. Use `list_templates()` to discover available templates
2. Use `list_frameworks()` to explore prompt engineering resources
3. Inspect tool schemas via MCP tool listing for input validation
### Workflow Composition
1. **Discovery → Retrieval:** First list templates, then get specific template
2. **Template → Generation:** Use template content to guide documentation generation
3. **Validation → Retry:** Check template_name enum before requesting, handle errors gracefully
### Error Handling
- All errors return TextContent (never exceptions to client)
- Error messages include actionable guidance (e.g., "Available: readme, architecture, ...")
- Safe for speculative execution (read-only, no side effects)
### Template Usage
- Templates include `{{variable}}` placeholders for context substitution
- Follow `work` section for systematic analysis process
- Use `requirements` section as validation checklist
- Reference `examples` for concrete patterns
### Performance Optimization
- No caching needed (responses are fast < 20ms)
- Batch discovery calls if exploring multiple templates
- No rate limiting concerns for local stdio transport
---
**🤖 This API documentation was generated using the docs-mcp API template**
---
**Maintained by:** willh
**Last updated:** 2025-10-08
**Related endpoints:** list_templates, get_template, list_frameworks