Files
taiji-AI-PAD/Docs/前后端调试说明/API接口文档.md
T
xiaohei ed50bd9146 test: 添加 MCP Server 单元测试
新增内容:
- tests/test_function_registry.py: 函数注册表单元测试
- tests/test_sandbox_executor.py: 沙箱执行器单元测试
- tests/test_mcp_function_tool.py: MCP函数工具调用测试
- tests/conftest.py: pytest 配置
- tests/README.md: 测试文档
- pytest.ini: pytest 配置文件
- run_tests.sh: 测试运行脚本

测试覆盖:
- 16个内置函数的完整测试
- 函数注册和查询功能
- 沙箱执行器(超时、异常处理)
- MCP协议函数工具调用集成测试

版本: v1.2.1
2025-12-22 05:47:49 +00:00

15 KiB

taiji-AI-PAD API 接口文档

版本: v1.2.1
更新时间: 2025年12月22日
最后更新: 2025年12月22日
基础URL:

  • Data Ingestion 服务: http://localhost:8001
  • MCP Server 服务: http://localhost:8000
  • API Gateway: http://localhost:80

📋 目录

  1. Data Ingestion 服务 API
  2. MCP Server 服务 API
  3. 通用响应格式
  4. 错误码说明

Data Ingestion 服务 API

基础URL: http://localhost:8001

1. 健康检查

GET /health

检查服务健康状态。

响应示例:

{
  "status": "healthy",
  "timestamp": "2025-12-22T05:04:23.211960",
  "services": {
    "data_ingestion": "healthy",
    "redis": "healthy",
    "nats": "healthy",
    "rapidapi": "healthy",
    "apillama": "healthy"
  },
  "stats": {
    "total_apis": 0,
    "processed_apis": 0,
    "generated_tools": 20,
    "cache_size": 44
  }
}

2. 同步 RapidAPI 端点

POST /rapidapi/sync

同步 RapidAPI 端点列表。

查询参数:

  • category (string, 可选): API 分类
  • limit (int, 可选, 默认: 100): 同步数量限制

请求示例:

POST /rapidapi/sync?category=weather&limit=50

响应示例:

{
  "message": "RapidAPI端点同步已启动",
  "category": "weather",
  "limit": 50
}

3. 测试 RapidAPI 端点

POST /rapidapi/test

测试 RapidAPI 端点调用。

请求体:

{
  "endpoint": "https://rapidapi.com/api/weather/v1/current",
  "method": "GET",
  "params": {
    "location": "Beijing"
  },
  "headers": {
    "X-Custom-Header": "value"
  }
}

响应示例:

{
  "success": true,
  "status_code": 200,
  "data": {
    "temperature": 25,
    "condition": "sunny"
  },
  "response_time": 123.45,
  "headers": {
    "content-type": "application/json"
  }
}

4. 解析 OpenAPI 规范

POST /openapi/parse

解析 OpenAPI/Swagger 规范文档。

查询参数:

  • url (string, 必需): OpenAPI 文档 URL

请求示例:

POST /openapi/parse?url=https://api.example.com/openapi.json

响应示例:

{
  "url": "https://api.example.com/openapi.json",
  "title": "Example API",
  "version": "1.0.0",
  "endpoints_count": 15,
  "schemas_count": 8,
  "parsed_data": {
    "info": {
      "title": "Example API",
      "version": "1.0.0"
    },
    "paths": {
      "/users": {
        "get": {
          "summary": "Get users",
          "responses": {
            "200": {
              "description": "Success"
            }
          }
        }
      }
    }
  },
  "parsing_time": 0.234
}

5. APILLAMA 处理 API 文档

POST /apillama/process

使用 APILLAMA 处理 API 文档,生成结构化 Schema。

请求体:

{
  "api_doc": {
    "title": "Weather API",
    "description": "Get weather information",
    "parameters": [
      {
        "name": "location",
        "type": "string",
        "description": "City name",
        "required": true
      }
    ]
  },
  "context": {
    "service": "Weather service",
    "version": "1.0"
  },
  "output_format": "json_schema"
}

请求参数说明:

  • api_doc (string | object, 必需): API 文档,可以是字符串或对象
  • context (object, 可选): 上下文信息
  • output_format (string, 可选): 输出格式,可选值: json_schema, pydantic, openapi (默认: json_schema)

响应示例:

{
  "processed": true,
  "output_format": "json_schema",
  "schema": {
    "type": "object",
    "properties": {
      "location": {
        "type": "string",
        "description": "City name"
      }
    },
    "required": ["location"]
  },
  "description": "Weather API for getting current weather information",
  "parameters": [
    {
      "name": "location",
      "type": "string",
      "description": "City name",
      "required": true
    }
  ],
  "examples": [
    {
      "location": "Beijing",
      "temperature": 25
    }
  ],
  "processing_time": 1.234,
  "confidence_score": 0.95,
  "completeness_score": 0.88
}

6. 生成工具定义

POST /tools/generate

从 API 端点生成工具定义。

请求体:

{
  "url": "https://api.example.com/users",
  "method": "GET",
  "name": "get_users",
  "description": "Get list of users",
  "parameters": [
    {
      "name": "page",
      "type": "integer",
      "required": false
    }
  ],
  "headers": {
    "Authorization": "Bearer token"
  }
}

响应示例:

{
  "message": "工具生成任务已启动",
  "endpoint": "https://api.example.com/users",
  "method": "GET"
}

7. 获取工具列表

GET /tools

获取已生成的工具列表。

查询参数:

  • category (string, 可选): 工具分类
  • limit (int, 可选, 默认: 100): 返回数量限制
  • offset (int, 可选, 默认: 0): 偏移量

请求示例:

GET /tools?category=weather&limit=20&offset=0

响应示例:

[
  {
    "name": "get_weather",
    "description": "Get weather information",
    "category": "weather",
    "url": "https://api.example.com/weather",
    "method": "GET",
    "parameters": [
      {
        "name": "location",
        "type": "string",
        "required": true
      }
    ],
    "created_at": "2025-12-22T05:00:00Z"
  }
]

8. 获取特定工具定义

GET /tools/{tool_name}

获取特定工具的定义。

路径参数:

  • tool_name (string, 必需): 工具名称

响应示例:

{
  "name": "get_weather",
  "description": "Get weather information",
  "category": "weather",
  "url": "https://api.example.com/weather",
  "method": "GET",
  "parameters": [
    {
      "name": "location",
      "type": "string",
      "required": true
    }
  ],
  "created_at": "2025-12-22T05:00:00Z"
}

9. 删除工具

DELETE /tools/{tool_name}

删除指定的工具定义。

路径参数:

  • tool_name (string, 必需): 工具名称

响应示例:

{
  "message": "工具已删除",
  "tool_name": "get_weather"
}

10. 获取统计信息

GET /stats

获取服务统计信息。

响应示例:

{
  "total_apis": 100,
  "processed_apis": 85,
  "generated_tools": 20,
  "failed_processes": 2,
  "cache_size": 44,
  "last_sync": "2025-12-22T05:00:00Z",
  "categories": {
    "weather": 15,
    "finance": 10,
    "general": 5
  }
}

11. 清除缓存

POST /cache/clear

清除所有缓存数据。

查询参数:

  • pattern (string, 可选): 缓存键模式,如 rapidapi:*

请求示例:

POST /cache/clear?pattern=rapidapi:*

响应示例:

{
  "message": "缓存已清除",
  "cleared_keys": 150
}

12. Prometheus Metrics

GET /metrics

获取 Prometheus 格式的监控指标。

响应格式: Prometheus 文本格式

示例:

# HELP http_requests_total Total number of HTTP requests
# TYPE http_requests_total counter
http_requests_total{method="GET",status="200"} 1500
http_requests_total{method="POST",status="200"} 800

# HELP apillama_processing_duration_seconds APILLAMA processing duration
# TYPE apillama_processing_duration_seconds histogram
apillama_processing_duration_seconds_bucket{le="0.5"} 100
apillama_processing_duration_seconds_bucket{le="1.0"} 200

MCP Server 服务 API

基础URL: http://localhost:8000

1. 健康检查

GET /health

检查 MCP Server 健康状态。

响应示例:

{
  "status": "healthy",
  "timestamp": "2025-12-22T05:04:23.211960",
  "services": {
    "database": "healthy",
    "redis": "healthy",
    "nats": "healthy"
  }
}

2. 注册 Agent

POST /agents

注册新的 Agent。

请求体:

{
  "name": "weather_agent",
  "description": "Weather information agent",
  "capabilities": ["weather_query", "location_search"],
  "metadata": {
    "version": "1.0.0",
    "author": "taiji-team"
  }
}

响应示例:

{
  "agent_id": "agent_123456",
  "name": "weather_agent",
  "description": "Weather information agent",
  "status": "active",
  "created_at": "2025-12-22T05:00:00Z",
  "capabilities": ["weather_query", "location_search"],
  "metadata": {
    "version": "1.0.0",
    "author": "taiji-team"
  }
}

3. 获取 Agent 列表

GET /agents

获取所有注册的 Agent 列表。

查询参数:

  • status (string, 可选): 过滤状态,如 active, inactive
  • limit (int, 可选, 默认: 100): 返回数量限制
  • offset (int, 可选, 默认: 0): 偏移量

响应示例:

[
  {
    "agent_id": "agent_123456",
    "name": "weather_agent",
    "description": "Weather information agent",
    "status": "active",
    "created_at": "2025-12-22T05:00:00Z"
  }
]

4. 获取特定 Agent

GET /agents/{agent_id}

获取特定 Agent 的详细信息。

路径参数:

  • agent_id (string, 必需): Agent ID

响应示例:

{
  "agent_id": "agent_123456",
  "name": "weather_agent",
  "description": "Weather information agent",
  "status": "active",
  "created_at": "2025-12-22T05:00:00Z",
  "capabilities": ["weather_query", "location_search"],
  "metadata": {
    "version": "1.0.0",
    "author": "taiji-team"
  }
}

5. 执行 Agent 工具

POST /agents/{agent_id}/execute

执行 Agent 的工具调用。支持三种工具类型:

  • API 工具: 调用外部 API
  • 函数工具: 执行本地 Python 函数(新增)
  • LLM 工具: 调用 LLM 模型

路径参数:

  • agent_id (string, 必需): Agent ID

请求体:

{
  "tool_name": "math_add",
  "parameters": {
    "a": 10,
    "b": 20
  },
  "context": {
    "session_id": "session_123"
  }
}

函数工具示例:

{
  "tool_name": "math_add",
  "parameters": {
    "a": 10,
    "b": 20
  }
}

响应示例:

{
  "success": true,
  "result": 30.0,
  "execution_time": 0.001,
  "tool_name": "math_add"
}

可用的函数工具:

  • 数学函数: math_add, math_subtract, math_multiply, math_divide, math_power
  • 字符串函数: string_upper, string_lower, string_length, string_replace
  • 日期时间: datetime_now
  • JSON: json_parse, json_stringify
  • 哈希: hash_md5, hash_sha256
  • Base64: base64_encode, base64_decode

安全特性:

  • ✅ 函数白名单验证
  • ✅ 沙箱执行环境
  • ✅ 超时控制(默认 5 秒)
  • ✅ 参数验证和类型检查

6. 获取工具列表

GET /tools

获取所有可用工具列表。

查询参数:

  • category (string, 可选): 工具分类
  • limit (int, 可选, 默认: 100): 返回数量限制

响应示例:

[
  {
    "name": "get_weather",
    "description": "Get weather information",
    "category": "weather",
    "parameters": [
      {
        "name": "location",
        "type": "string",
        "required": true
      }
    ]
  }
]

7. Prometheus Metrics

GET /metrics

获取 Prometheus 格式的监控指标。

注意: 当前返回 TODO 消息,待实现。


WebSocket API

MCP Protocol WebSocket

WebSocket URL: ws://localhost:8000/ws/{agent_id}

连接示例:

const ws = new WebSocket('ws://localhost:8000/ws/agent_123456');

消息格式:

{
  "type": "mcp_request",
  "payload": {
    "method": "tools/list",
    "params": {}
  }
}

响应格式:

{
  "type": "mcp_response",
  "payload": {
    "result": [...]
  }
}

通用响应格式

成功响应

所有成功响应都遵循以下格式:

{
  "status": "success",
  "data": {...},
  "message": "操作成功"
}

错误响应

所有错误响应都遵循以下格式:

{
  "status": "error",
  "error": {
    "code": "ERROR_CODE",
    "message": "错误描述",
    "details": {...}
  }
}

错误码说明

HTTP 状态码 错误码 说明
400 BAD_REQUEST 请求参数错误
401 UNAUTHORIZED 未授权
403 FORBIDDEN 禁止访问
404 NOT_FOUND 资源不存在
500 INTERNAL_ERROR 服务器内部错误
503 SERVICE_UNAVAILABLE 服务不可用

认证说明

当前版本暂未实现认证机制,所有 API 均可直接访问。

未来版本将支持:

  • API Key 认证
  • JWT Token 认证
  • OAuth 2.0

限流说明

当前版本暂未实现限流机制。

未来版本将支持:

  • 基于 IP 的限流
  • 基于 API Key 的限流
  • 基于用户的限流

交互式 API 文档

Swagger UI

  • Data Ingestion: http://localhost:8001/docs
  • MCP Server: http://localhost:8000/docs

ReDoc

  • Data Ingestion: http://localhost:8001/redoc
  • MCP Server: http://localhost:8000/redoc

OpenAPI JSON

  • Data Ingestion: http://localhost:8001/openapi.json
  • MCP Server: http://localhost:8000/openapi.json

前端集成示例

JavaScript/TypeScript

// 健康检查
const healthCheck = async () => {
  const response = await fetch('http://localhost:8001/health');
  const data = await response.json();
  console.log(data);
};

// APILLAMA 处理
const processAPI = async (apiDoc: any) => {
  const response = await fetch('http://localhost:8001/apillama/process', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      api_doc: apiDoc,
      context: { service: 'example' },
      output_format: 'json_schema'
    })
  });
  const data = await response.json();
  return data;
};

// 获取工具列表
const getTools = async (category?: string) => {
  const url = category 
    ? `http://localhost:8001/tools?category=${category}`
    : 'http://localhost:8001/tools';
  const response = await fetch(url);
  const data = await response.json();
  return data;
};

Python

import requests

# 健康检查
def health_check():
    response = requests.get('http://localhost:8001/health')
    return response.json()

# APILLAMA 处理
def process_api(api_doc, context=None, output_format='json_schema'):
    response = requests.post(
        'http://localhost:8001/apillama/process',
        json={
            'api_doc': api_doc,
            'context': context or {},
            'output_format': output_format
        }
    )
    return response.json()

# 获取工具列表
def get_tools(category=None):
    params = {'category': category} if category else {}
    response = requests.get('http://localhost:8001/tools', params=params)
    return response.json()

cURL

# 健康检查
curl http://localhost:8001/health

# APILLAMA 处理
curl -X POST http://localhost:8001/apillama/process \
  -H "Content-Type: application/json" \
  -d '{
    "api_doc": {"title": "Test API"},
    "context": {"service": "test"},
    "output_format": "json_schema"
  }'

# 获取工具列表
curl http://localhost:8001/tools?category=weather

注意事项

  1. CORS: 当前配置允许所有来源,生产环境需要限制
  2. 认证: 当前版本未实现认证,生产环境需要添加
  3. 限流: 当前版本未实现限流,生产环境需要添加
  4. 错误处理: 所有 API 调用都应该处理错误情况
  5. 超时设置: 建议设置合理的请求超时时间

文档版本: v1.2.1
最后更新: 2025年12月22日
维护者: taiji-AI-PAD 项目组

更新日志

  • v1.2.1 (2025-12-22): 添加 MCP Server 函数工具调用说明
  • v1.2.0 (2025-12-22): 初始版本,包含所有 API 端点文档