# 智文助手 API 文档
本文档详细介绍智文助手的API接口、数据模型和使用方法。
## 📚 目录
- [概述](#概述)
- [核心API](#核心api)
- [数据模型](#数据模型)
- [错误处理](#错误处理)
- [使用示例](#使用示例)
- [高级用法](#高级用法)
## 🎯 概述
智文助手基于MCP协议提供以下核心功能:
- **文档生成**: 自动生成README.md文件
- **思维导图**: 生成项目结构思维导图
- **文档更新**: 批量更新项目文档
- **结构查询**: 获取文件夹结构信息
## 🔧 核心API
### 1. generate_readme_files
为项目中的每个主要文件夹生成中文README.md文件。
#### 请求参数
```typescript
interface GenerateReadmeInput {
root_dir: string; // 项目根目录路径(必需)
exclude_dirs?: string[]; // 排除的目录列表(可选)
force_update?: boolean; // 是否强制更新现有README.md文件(可选)
}
```
#### 响应结果
```typescript
interface GenerateReadmeResult {
success: boolean; // 操作是否成功
message: string; // 结果消息
generated_count: number; // 生成的文件数量
skipped_count: number; // 跳过的文件数量
execution_time: number; // 执行时间(秒)
}
```
#### 使用示例
```python
# 基础用法
result = await generate_readme_files({
"root_dir": "/path/to/your/project"
})
# 高级用法
result = await generate_readme_files({
"root_dir": "/path/to/your/project",
"exclude_dirs": [".git", "__pycache__", "node_modules"],
"force_update": True
})
print(f"生成 {result['generated_count']} 个README.md文件")
```
### 2. generate_mindmap
生成项目文件夹结构的思维导图。
#### 请求参数
```typescript
interface GenerateMindmapInput {
root_dir: string; // 项目根目录路径(必需)
output_file?: string; // 思维导图输出文件路径(可选)
exclude_dirs?: string[]; // 排除的目录列表(可选)
max_depth?: number; // 最大扫描深度(可选)
format?: string; // 输出格式:'mermaid'|'plantuml'|'dot'(可选)
}
```
#### 响应结果
```typescript
interface GenerateMindmapResult {
success: boolean; // 操作是否成功
message: string; // 结果消息
output_file: string; // 输出文件路径
file_size: number; // 文件大小(字节)
execution_time: number; // 执行时间(秒)
}
```
#### 使用示例
```python
# 基础用法
result = await generate_mindmap({
"root_dir": "/path/to/your/project"
})
# 自定义用法
result = await generate_mindmap({
"root_dir": "/path/to/your/project",
"output_file": "custom_structure.md",
"exclude_dirs": [".git", "temp"],
"max_depth": 5,
"format": "mermaid"
})
print(f"思维导图已保存到: {result['output_file']}")
```
### 3. update_documentation
更新项目中的README.md文件和思维导图。
#### 请求参数
```typescript
interface UpdateDocumentationInput {
root_dir: string; // 项目根目录路径(必需)
exclude_dirs?: string[]; // 排除的目录列表(可选)
update_mindmap?: boolean; // 是否更新思维导图(可选)
incremental?: boolean; // 是否增量更新(可选)
backup?: boolean; // 是否创建备份(可选)
}
```
#### 响应结果
```typescript
interface UpdateDocumentationResult {
success: boolean; // 操作是否成功
message: string; // 结果消息
updated_count: number; // 更新的文件数量
generated_count: number; // 新生成的文件数量
backup_files: string[]; // 备份文件列表
execution_time: number; // 执行时间(秒)
}
```
#### 使用示例
```python
# 基础用法
result = await update_documentation({
"root_dir": "/path/to/your/project"
})
# 高级用法
result = await update_documentation({
"root_dir": "/path/to/your/project",
"exclude_dirs": [".git", "__pycache__"],
"update_mindmap": True,
"incremental": True,
"backup": True
})
print(f"更新完成: {result['message']}")
```
### 4. get_folder_structure
获取项目的文件夹结构。
#### 请求参数
```typescript
interface GetFolderStructureInput {
root_dir: string; // 项目根目录路径(必需)
exclude_dirs?: string[]; // 排除的目录列表(可选)
max_depth?: number; // 最大扫描深度(可选)
include_files?: boolean; // 是否包含文件(可选)
format?: string; // 输出格式:'tree'|'json'|'list'(可选)
}
```
#### 响应结果
```typescript
interface GetFolderStructureResult {
success: boolean; // 操作是否成功
message: string; // 结果消息
structure: string|object; // 文件夹结构
total_dirs: number; // 目录总数
total_files: number; // 文件总数
execution_time: number; // 执行时间(秒)
}
```
#### 使用示例
```python
# 基础用法
result = await get_folder_structure({
"root_dir": "/path/to/your/project"
})
# 自定义用法
result = await get_folder_structure({
"root_dir": "/path/to/your/project",
"exclude_dirs": [".git"],
"max_depth": 3,
"include_files": True,
"format": "json"
})
print(f"发现 {result['total_dirs']} 个目录和 {result['total_files']} 个文件")
```
## 📊 数据模型
### GenerateReadmeInput
```python
class GenerateReadmeInput(BaseModel):
"""生成README.md文件输入模型"""
root_dir: str = Field(..., description="项目根目录路径")
exclude_dirs: List[str] = Field(default_factory=list, description="排除的目录列表")
force_update: bool = Field(default=False, description="是否强制更新现有README.md文件")
```
### GenerateMindmapInput
```python
class GenerateMindmapInput(BaseModel):
"""生成思维导图输入模型"""
root_dir: str = Field(..., description="项目根目录路径")
output_file: str = Field(default="folder_structure_mindmap.md", description="思维导图输出文件路径")
exclude_dirs: List[str] = Field(default_factory=list, description="排除的目录列表")
max_depth: int = Field(default=10, description="最大扫描深度")
format: str = Field(default="mermaid", description="输出格式")
```
### UpdateDocumentationInput
```python
class UpdateDocumentationInput(BaseModel):
"""更新文档输入模型"""
root_dir: str = Field(..., description="项目根目录路径")
exclude_dirs: List[str] = Field(default_factory=list, description="排除的目录列表")
update_mindmap: bool = Field(default=True, description="是否更新思维导图")
incremental: bool = Field(default=False, description="是否增量更新")
backup: bool = Field(default=False, description="是否创建备份")
```
### GetFolderStructureInput
```python
class GetFolderStructureInput(BaseModel):
"""获取文件夹结构输入模型"""
root_dir: str = Field(..., description="项目根目录路径")
exclude_dirs: List[str] = Field(default_factory=list, description="排除的目录列表")
max_depth: int = Field(default=10, description="最大扫描深度")
include_files: bool = Field(default=True, description="是否包含文件")
format: str = Field(default="tree", description="输出格式")
```
## ⚠️ 错误处理
### 错误类型
#### 1. ValidationError
**描述**: 输入参数验证失败
**示例**:
```python
try:
result = await generate_readme_files({"root_dir": ""})
except ValidationError as e:
print(f"参数验证失败: {e}")
```
#### 2. PathError
**描述**: 路径不存在或无法访问
**示例**:
```python
try:
result = await generate_readme_files({"root_dir": "/nonexistent/path"})
except PathError as e:
print(f"路径错误: {e}")
```
#### 3. PermissionError
**描述**: 文件系统权限不足
**示例**:
```python
try:
result = await generate_readme_files({"root_dir": "/restricted/path"})
except PermissionError as e:
print(f"权限错误: {e}")
```
#### 4. SecurityError
**描述**: 安全检查失败
**示例**:
```python
try:
result = await generate_readme_files({"root_dir": "/dangerous/path"})
except SecurityError as e:
print(f"安全错误: {e}")
```
### 错误响应格式
```typescript
interface ErrorResponse {
success: false; // 操作失败
error: {
type: string; // 错误类型
code: string; // 错误代码
message: string; // 错误消息
details?: any; // 错误详情
}
timestamp: string; // 时间戳
}
```
## 💡 使用示例
### 完整工作流示例
```python
#!/usr/bin/env python3
"""
智文助手API使用示例
"""
import asyncio
from folder_documentation_mcp import (
generate_readme_files,
generate_mindmap,
update_documentation,
get_folder_structure
)
async def documentation_workflow():
"""完整的文档生成工作流"""
project_path = "/path/to/your/project"
try:
# 1. 获取项目结构
print("📊 获取项目结构...")
structure = await get_folder_structure({
"root_dir": project_path,
"format": "json",
"max_depth": 3
})
print(f"发现 {structure['total_dirs']} 个目录和 {structure['total_files']} 个文件")
# 2. 生成README文档
print("📝 生成README文档...")
readme_result = await generate_readme_files({
"root_dir": project_path,
"exclude_dirs": [".git", "__pycache__", "node_modules"],
"force_update": True
})
print(f"生成 {readme_result['generated_count']} 个README.md文件")
# 3. 生成思维导图
print("🧠 生成思维导图...")
mindmap_result = await generate_mindmap({
"root_dir": project_path,
"output_file": "project_structure.md",
"format": "mermaid"
})
print(f"思维导图保存到: {mindmap_result['output_file']}")
# 4. 创建备份并更新
print("💾 创建备份并更新...")
update_result = await update_documentation({
"root_dir": project_path,
"backup": True,
"incremental": False
})
print(f"更新完成: {update_result['message']}")
except Exception as e:
print(f"❌ 错误: {e}")
# 运行工作流
asyncio.run(documentation_workflow())
```
### 批量处理示例
```python
#!/usr/bin/env python3
"""
批量处理多个项目的文档
"""
import asyncio
import os
from folder_documentation_mcp import generate_readme_files
async def batch_process_projects():
"""批量处理多个项目"""
# 获取所有项目目录
projects_root = "/path/to/projects"
projects = [
os.path.join(projects_root, d)
for d in os.listdir(projects_root)
if os.path.isdir(os.path.join(projects_root, d))
]
# 并行处理所有项目
tasks = []
for project in projects:
task = generate_readme_files({
"root_dir": project,
"exclude_dirs": [".git", "__pycache__"],
"force_update": False
})
tasks.append(task)
# 等待所有任务完成
results = await asyncio.gather(*tasks, return_exceptions=True)
# 处理结果
for i, result in enumerate(results):
if isinstance(result, Exception):
print(f"❌ 项目 {i+1} 处理失败: {result}")
else:
print(f"✅ 项目 {i+1} 处理成功: {result['message']}")
asyncio.run(batch_process_projects())
```
## 🔧 高级用法
### 1. 自定义配置
```python
# 加载自定义配置
import yaml
with open("custom_config.yaml", "r") as f:
custom_config = yaml.safe_load(f)
# 使用自定义配置调用API
await generate_readme_files({
"root_dir": "/project/path",
**custom_config["readme_options"]
})
```
### 2. 监控和日志
```python
import logging
# 设置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("zhiwen_assistant")
async def monitored_documentation():
"""带监控的文档生成"""
try:
logger.info("开始文档生成...")
start_time = time.time()
result = await generate_readme_files({
"root_dir": "/project/path",
"exclude_dirs": [".git"]
})
execution_time = time.time() - start_time
logger.info(f"文档生成完成,耗时: {execution_time:.2f}秒")
except Exception as e:
logger.error(f"文档生成失败: {e}")
raise
```
### 3. 事件处理
```python
from folder_documentation_mcp import event_handler
@event_handler.on("file_generated")
def handle_file_generated(event):
"""处理文件生成事件"""
print(f"文件已生成: {event['file_path']}")
@event_handler.on("error_occurred")
def handle_error(event):
"""处理错误事件"""
print(f"错误发生: {event['error']}")
```
---
*更新时间: 2025-12-19*