Files

11 KiB

Steering Agent 使用指南

概述

Steering Agent 是一个项目约束管理工具,用于:

  • 从代码库自动提取项目知识
  • 管理用户定义的规则
  • 在代码生成前提供上下文
  • 在代码生成后进行合规检查

工作流程

┌─────────────────┐     ┌─────────────────┐     ┌─────────────────┐
│   知识提取       │ ──▶ │   规则定义       │ ──▶ │   使用场景       │
│                 │     │                 │     │                 │
│ extract_        │     │ add_rule        │     │ get_context     │
│ project_        │     │ remove_rule     │     │ check_          │
│ knowledge       │     │ list_rules      │     │ compliance      │
└─────────────────┘     └─────────────────┘     └─────────────────┘

API 使用


1. 知识提取

提取项目知识

POST /api/v1/extract

curl -X POST http://localhost:8000/api/v1/extract \
  -H "Content-Type: application/json" \
  -d '{
    "project_path": "/home/user/my_project"
  }'

请求参数:

参数 类型 必需 说明
project_path string 是 项目根目录路径
include_patterns array 否 包含的文件模式
exclude_patterns array 否 排除的文件模式

响应示例:

{
  "success": true,
  "knowledge": {
    "project_path": "/home/user/my_project",
    "extracted_at": "2024-01-01T12:00:00",
    "tech_stack": {
      "language": {"name": "Python", "version": "3.12"},
      "framework": [{"name": "FastAPI", "version": ">=0.109.0"}],
      "dependencies": {"production": ["fastapi>=0.109.0", "..."]}
    },
    "structure": {
      "pattern": {"name": "agent_templates", "confidence": 0.95},
      "key_files": {"entry_point": "run_api_server.py", "...": "..."}
    },
    "naming": {
      "files": {"dominant_pattern": "snake_case", "consistency": 1.0},
      "classes": {"dominant_pattern": "PascalCase", "consistency": 1.0}
    },
    "patterns": {
      "async_usage": {"async_required": true, "async_function_ratio": 0.85},
      "error_handling": {"style": "try-except-json-response"}
    },
    "config": {
      "env_variables": [
        {"name": "OPENAI_API_KEY", "required": true, "description": "OpenAI API Key"}
      ]
    }
  }
}

2. 规则管理

添加规则

POST /api/v1/rules

curl -X POST http://localhost:8000/api/v1/rules \
  -H "Content-Type: application/json" \
  -d '{
    "rule_type": "must",
    "rule_content": "所有 MCP 工具必须返回 JSON 格式",
    "category": "output",
    "priority": "high"
  }'

请求参数:

参数 类型 必需 说明
rule_type string 是 规则类型: must/must_not/prefer/security/architecture
rule_content string 是 规则内容
category string 否 分类标签
priority string 否 优先级: high/normal/low

响应示例:

{
  "success": true,
  "rule": {
    "id": "a1b2c3d4",
    "rule_type": "must",
    "content": "所有 MCP 工具必须返回 JSON 格式",
    "category": "output",
    "priority": "high",
    "created_at": "2024-01-01T12:00:00"
  }
}

列出规则

GET /api/v1/rules

# 列出所有规则
curl http://localhost:8000/api/v1/rules

# 按类型过滤
curl "http://localhost:8000/api/v1/rules?rule_type=must"

# 按分类过滤
curl "http://localhost:8000/api/v1/rules?category=output"

响应示例:

{
  "success": true,
  "rules": [
    {
      "id": "a1b2c3d4",
      "rule_type": "must",
      "content": "所有 MCP 工具必须返回 JSON 格式",
      "category": "output",
      "priority": "high"
    }
  ],
  "statistics": {
    "total": 5,
    "by_type": {"must": 2, "must_not": 2, "prefer": 1},
    "by_priority": {"high": 1, "normal": 4}
  }
}

删除规则

DELETE /api/v1/rules/{rule_id}

curl -X DELETE http://localhost:8000/api/v1/rules/a1b2c3d4

3. 获取项目上下文

获取 JSON 格式上下文

GET /api/v1/context

curl "http://localhost:8000/api/v1/context?format=json"

响应示例:

{
  "success": true,
  "format": "json",
  "context": {
    "project_context": {
      "name": "my_project",
      "tech_stack": {"language": {"name": "Python", "version": "3.12"}},
      "structure": {"pattern": {"name": "agent_templates"}}
    },
    "naming_conventions": {
      "files": "snake_case",
      "classes": "PascalCase",
      "functions": "snake_case"
    },
    "code_patterns": {
      "async_required": true,
      "error_handling": "try-except-json-response",
      "logging": "print"
    },
    "rules": {
      "must": ["所有 MCP 工具必须返回 JSON 格式"],
      "must_not": ["禁止硬编码 API Key"],
      "prefer": [],
      "security": [],
      "architecture": []
    }
  }
}

获取 Markdown 格式上下文

curl "http://localhost:8000/api/v1/context?format=markdown"

4. 合规检查

检查代码合规性

POST /api/v1/check

curl -X POST http://localhost:8000/api/v1/check \
  -H "Content-Type: application/json" \
  -d '{
    "code": "@server.tool()\nasync def my_tool():\n    return \"result\"",
    "file_type": "python",
    "strict_mode": false
  }'

请求参数:

参数 类型 必需 说明
code string 是 待检查的代码
file_type string 否 文件类型
strict_mode boolean 否 严格模式(警告视为错误)

响应示例:

{
  "success": true,
  "compliant": false,
  "violations": [
    {
      "rule": "所有 MCP 工具必须返回 JSON 格式",
      "rule_type": "must",
      "severity": "error",
      "suggestion": "MCP 工具应使用 json.dumps() 返回 JSON 格式"
    }
  ],
  "warnings": [],
  "summary": {
    "total_violations": 1,
    "total_warnings": 0,
    "rules_checked": 5
  }
}

5. 生成规范文档

生成 Markdown 文档

GET /api/v1/doc

curl "http://localhost:8000/api/v1/doc?format=markdown&include_examples=true"

响应示例:

{
  "success": true,
  "document": "# my_project - 项目规范文档\n\n> 生成时间: 2024-01-01 12:00:00\n..."
}

MCP 协议使用

工具列表

curl -X POST http://localhost:8000/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/list"
  }'

调用工具

curl -X POST http://localhost:8000/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "extract_project_knowledge",
      "arguments": {
        "project_path": "/path/to/project"
      }
    }
  }'

完整使用流程示例

import requests
import json

BASE_URL = "http://localhost:8000"

# 1. 提取项目知识
print("=== 1. 提取项目知识 ===")
resp = requests.post(
    f"{BASE_URL}/api/v1/extract",
    json={"project_path": "/path/to/my_project"}
)
knowledge = resp.json()
print(f"技术栈: {knowledge['knowledge']['tech_stack']['language']}")

# 2. 添加规则
print("\n=== 2. 添加规则 ===")
rules_to_add = [
    {"rule_type": "must", "rule_content": "所有 MCP 工具必须返回 JSON 格式"},
    {"rule_type": "must_not", "rule_content": "禁止硬编码 API Key"},
    {"rule_type": "prefer", "rule_content": "优先使用 async/await"},
]

for rule in rules_to_add:
    resp = requests.post(f"{BASE_URL}/api/v1/rules", json=rule)
    print(f"添加规则: {rule['rule_content']}")

# 3. 获取项目上下文
print("\n=== 3. 获取项目上下文 ===")
resp = requests.get(f"{BASE_URL}/api/v1/context?format=json")
context = resp.json()
print(f"规则数量: {len(context['context']['rules']['must'])} must, "
      f"{len(context['context']['rules']['must_not'])} must_not")

# 4. 检查代码合规性
print("\n=== 4. 检查代码合规性 ===")
code_to_check = '''
@server.tool()
async def my_tool():
    api_key = "sk-1234567890abcdef"
    return "result"
'''

resp = requests.post(
    f"{BASE_URL}/api/v1/check",
    json={"code": code_to_check, "file_type": "python"}
)
result = resp.json()
print(f"合规: {result['compliant']}")
for violation in result['violations']:
    print(f"  - {violation['rule']}: {violation['suggestion']}")

# 5. 生成规范文档
print("\n=== 5. 生成规范文档 ===")
resp = requests.get(f"{BASE_URL}/api/v1/doc")
doc = resp.json()
# 保存到文件
with open("project_spec.md", "w") as f:
    f.write(doc["document"])
print("规范文档已保存到 project_spec.md")

与其他 Agent 集成

与 specs_agent 集成

# 1. 从 steering_agent 获取上下文
context_resp = requests.get("http://steering-agent:8000/api/v1/context?format=json")
context = context_resp.json()["context"]

# 2. 将上下文传递给 specs_agent
specs_resp = requests.post(
    "http://specs-agent:8000/api/v1/requirements",
    headers={"api-key": "your-key"},
    json={
        "brief_description": "创建一个数据去重Agent",
        "context": json.dumps(context)  # 传递项目上下文
    }
)

与 format_police_agent 集成

# 1. 检查代码合规性
check_resp = requests.post(
    "http://steering-agent:8000/api/v1/check",
    json={"code": generated_code}
)

# 2. 如果有输出,使用 format_police 检查格式
if check_resp.json()["compliant"]:
    format_resp = requests.post(
        "http://format-police-agent:8000/api/v1/check",
        json={"content": output}
    )

常见规则示例

必须遵循 (must)

{"rule_type": "must", "rule_content": "所有 MCP 工具必须返回 JSON 格式"}
{"rule_type": "must", "rule_content": "所有函数必须有 docstring"}
{"rule_type": "must", "rule_content": "必须实现 /health 健康检查端点"}
{"rule_type": "must", "rule_content": "所有 API 端点必须有类型提示"}

禁止事项 (must_not)

{"rule_type": "must_not", "rule_content": "禁止硬编码 API Key"}
{"rule_type": "must_not", "rule_content": "禁止使用 print 进行日志输出"}
{"rule_type": "must_not", "rule_content": "禁止使用同步阻塞操作"}
{"rule_type": "must_not", "rule_content": "禁止在工具函数中直接抛出异常"}

安全规则 (security)

{"rule_type": "security", "rule_content": "禁止使用 eval() 或 exec()"}
{"rule_type": "security", "rule_content": "所有用户输入必须验证"}
{"rule_type": "security", "rule_content": "敏感信息必须使用环境变量"}

架构规则 (architecture)

{"rule_type": "architecture", "rule_content": "MCP 工具必须定义在 mcp_server.py"}
{"rule_type": "architecture", "rule_content": "API 端点必须定义在 api_server.py"}
{"rule_type": "architecture", "rule_content": "遵循 agent_templates 目录结构"}

错误处理

所有 API 在失败时返回:

{
  "success": false,
  "error": "错误信息"
}

常见错误:

  • 项目路径不存在: 检查 project_path 是否正确
  • 无效的规则类型: rule_type 必须是 must/must_not/prefer/security/architecture
  • 规则已存在: 相同内容的规则已添加
  • 规则不存在: 要删除的规则 ID 不存在