MCP扫描API

一个基于FastAPI的Web服务,封装了Cisco AI Defense MCP Scanner工具,通过REST API扫描远程MCP服务器的安全漏洞。

  • by Stinny
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 Stinny/mcpscan

使用说明

MCP扫描仪API

一个基于FastAPI的web服务,它封装了 思科AI防御MCP扫描仪 工具,使您能够通过REST API扫描远程MCP(模型上下文协议)服务器的安全漏洞。

特性

  • REST API:从您的MERN应用程序或任何HTTP客户端以编程方式扫描MCP服务器
  • 多台分析仪:
    • API分析仪:思科人工智能防御基于云的威胁检测
    • YARA 分析仪:恶意代码的模式匹配
    • LLM分析仪:基于人工智能的情境感知威胁评估
  • 认证:基于API密钥的身份验证,以确保端点的安全
  • 全面扫描:MCP服务器上的扫描工具、提示和资源
  • 灵活的身份验证:支持对MCP服务器的Bearer、OAuth和API密钥身份验证
  • 渲染就绪:已预先配置,可通过GitHub部署到Render

快速开始

先决条件

  • Python 3.11、3.12或3.13(注意:由于包兼容性,不支持Python 3.14)
  • Cisco AI Defense API密钥(从 aidefense.security.cisco.com)
  • LLM API密钥(OpenAI、Anthropic、AWS Bedrock等)

本地开发

  1. 克隆存储库
git clone <your-repo-url>
cd mcpscan
  1. 创建虚拟环境
# If you have Python 3.14, install Python 3.13 first:
brew install python@3.13

# Create virtual environment with Python 3.13 (or 3.11/3.12)
python3.13 -m venv venv

# Activate the virtual environment
source venv/bin/activate  # On Windows: venv\Scripts\activate
  1. 安装依赖项
pip install -r requirements.txt
  1. 配置环境变量
cp .env.example .env

编辑 .env 并设置您的API密钥:

API_KEY=your-secure-api-key-here
MCP_SCANNER_API_KEY=your-cisco-api-defense-key
MCP_SCANNER_LLM_API_KEY=your-llm-provider-key
  1. 运行服务器
uvicorn app.main:app --reload --port 8000
  1. 访问API
  • API文件:http://localhost:8000/docs
  • 备选文件:http://localhost:8000/redoc
  • 健康检查:http://localhost:8000/health

要渲染的部署

选项1:使用render.yaml(推荐)

  1. 推送到GitHub
git init
git add .
git commit -m "Initial commit"
git branch -M main
git remote add origin <your-github-repo-url>
git push -u origin main
  1. 连接到渲染
  • 首选 渲染仪表板
  • 点击“新建+”→ “蓝图”
  • 连接您的GitHub存储库
  • 渲染将自动检测 render.yaml
  1. 设置环境变量

在“渲染”仪表板中,设置以下环境变量:

  • API_KEY:您的安全API密钥(生成一个强随机字符串)
  • MCP_SCANNER_API_KEY:您的Cisco AI Defense API密钥
  • MCP_SCANNER_LLM_API_KEY:您的LLM提供商API密钥
  1. 部署

Render将自动构建和部署您的服务。任何未来都会推动 main 将触发自动重新部署。

选项2:手动设置

  1. 在Render上创建新的Web服务
  2. 连接您的GitHub存储库
  3. 配置:
    • 名字:mcp扫描器api
    • 运行时:Python 3
    • 生成命令: pip install -r requirements.txt
    • 启动命令: uvicorn app.main:app --host 0.0.0.0 --port $PORT
  4. 添加环境变量(见上文)
  5. 部署

API 文档

认证

所有端点(除 /health)需要中的API密钥 X-API-Key 头球

curl -H "X-API-Key: your-api-key" https://your-app.onrender.com/health

端点

健康检查

GET /health

返回服务状态和扫描仪可用性。

答复:

{
  "status": "healthy",
  "version": "1.0.0",
  "scanner_available": true
}

扫描所有工具

POST /api/v1/scan/tools

扫描MCP服务器上的所有工具。

请求正文:

{
  "server_url": "https://example.com/mcp",
  "auth": {
    "type": "bearer",
    "bearer_token": "your-mcp-server-token"
  },
  "analyzers": ["api", "yara", "llm"],
  "output_format": "summary"
}

答复:

{
  "server_url": "https://example.com/mcp",
  "total_scanned": 5,
  "safe_count": 3,
  "unsafe_count": 2,
  "results": [
    {
      "tool_name": "execute_command",
      "tool_description": "Execute shell commands",
      "status": "completed",
      "analyzers": ["api", "yara", "llm"],
      "findings": [
        {
          "severity": "HIGH",
          "summary": "Potential command injection vulnerability",
          "analyzer": "api",
          "details": {}
        }
      ],
      "is_safe": false
    }
  ]
}

扫描专用工具

POST /api/v1/scan/tool/{tool_name}

按名称扫描特定工具。

扫描所有提示

POST /api/v1/scan/prompts

扫描MCP服务器上的所有提示。

扫描特定提示

POST /api/v1/scan/prompt/{prompt_name}

按名称扫描特定提示。

扫描所有资源

POST /api/v1/scan/resources

扫描MCP服务器上的所有资源。

请求正文:

{
  "server_url": "https://example.com/mcp",
  "allowed_mime_types": ["text/plain", "text/html"],
  "analyzers": ["api", "yara"]
}

扫描特定资源

POST /api/v1/scan/resource

扫描特定资源。

请求正文:

{
  "server_url": "https://example.com/mcp",
  "resource_uri": "file:///path/to/resource",
  "analyzers": ["yara"]
}

MCP服务器身份验证

API支持多种身份验证类型,用于连接到MCP服务器:

无身份验证:

{
  "auth": null
}

承载令牌:

{
  "auth": {
    "type": "bearer",
    "bearer_token": "your-token"
  }
}

API密钥:

{
  "auth": {
    "type": "apikey",
    "api_key": "your-key",
    "api_key_header": "X-API-Key"
  }
}

OAuth:

{
  "auth": {
    "type": "oauth",
    "client_id": "your-client-id",
    "client_secret": "your-secret",
    "scopes": ["read:tools", "read:prompts"]
  }
}

分析器

  • 接口:思科人工智能防御基于云的威胁检测(需要 MCP_SCANNER_API_KEY)
  • 儿童:恶意代码的模式匹配(不需要API密钥)
  • 大语言模型:基于人工智能的威胁评估(需要 MCP_SCANNER_LLM_API_KEY)

您可以在请求中启用任何分析器组合。

与MERN应用程序集成

示例:React前端

const API_KEY = process.env.REACT_APP_MCP_SCANNER_API_KEY;
const API_BASE_URL = 'https://your-app.onrender.com';

async function scanMCPServer(serverUrl, bearerToken = null) {
  const response = await fetch(`${API_BASE_URL}/api/v1/scan/tools`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': API_KEY,
    },
    body: JSON.stringify({
      server_url: serverUrl,
      auth: bearerToken ? {
        type: 'bearer',
        bearer_token: bearerToken
      } : null,
      analyzers: ['api', 'yara', 'llm'],
      output_format: 'summary'
    })
  });

  if (!response.ok) {
    throw new Error(`Scan failed: ${response.statusText}`);
  }

  return await response.json();
}

// Usage
scanMCPServer('https://example.com/mcp', 'optional-bearer-token')
  .then(results => {
    console.log(`Scanned ${results.total_scanned} tools`);
    console.log(`Safe: ${results.safe_count}, Unsafe: ${results.unsafe_count}`);

    results.results.forEach(tool => {
      if (!tool.is_safe) {
        console.warn(`⚠️ ${tool.tool_name}:`, tool.findings);
      }
    });
  })
  .catch(error => console.error(error));

示例:Node.js/Express后端

const axios = require('axios');

const API_KEY = process.env.MCP_SCANNER_API_KEY;
const API_BASE_URL = 'https://your-app.onrender.com';

async function scanMCPServer(serverUrl, authConfig = null) {
  try {
    const response = await axios.post(
      `${API_BASE_URL}/api/v1/scan/tools`,
      {
        server_url: serverUrl,
        auth: authConfig,
        analyzers: ['api', 'yara', 'llm'],
        output_format: 'summary'
      },
      {
        headers: {
          'X-API-Key': API_KEY,
          'Content-Type': 'application/json'
        }
      }
    );

    return response.data;
  } catch (error) {
    console.error('Scan error:', error.response?.data || error.message);
    throw error;
  }
}

// Usage in Express route
app.post('/api/scan-mcp', async (req, res) => {
  const { serverUrl, authConfig } = req.body;

  try {
    const results = await scanMCPServer(serverUrl, authConfig);
    res.json(results);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

项目结构

mcpscan/
├── app/
│   ├── __init__.py
│   ├── main.py              # FastAPI application and routes
│   ├── auth.py              # API key authentication
│   ├── models.py            # Pydantic request/response models
│   └── scanner_service.py   # Scanner service wrapper
├── requirements.txt          # Python dependencies
├── render.yaml              # Render deployment configuration
├── .env.example             # Example environment variables
├── .gitignore               # Git ignore rules
└── README.md                # This file

环境变量

变量 必填 描述
API_KEY 是 您的API身份验证密钥(保护端点安全)
MCP_SCANNER_API_KEY 否* Cisco AI Defense API密钥(API分析器必需)
MCP_SCANNER_LLM_API_KEY 无* LLM提供程序API密钥(LLM分析器必需)
MCP_SCANNER_ENDPOINT 否 思科人工智能防御端点(默认:美国端点)

*必须至少配置一个分析仪。YARA分析器不需要API密钥。

安全考虑

  1. 对API密钥保密:从不承诺 .env 文件或在代码中公开API密钥
  2. 使用强API密钥:生成加密安全的随机字符串
  3. CORS配置:更新中的CORS设置 app/main.py 限制起源
  4. 速率限制:考虑增加生产使用的速率限制
  5. 仅限HTTPS:默认情况下,Render提供HTTPS-永远不要禁用它

故障排除

Python 3.14兼容性错误

如果您看到以下错误:

ERROR: Could not find a version that satisfies the requirement cisco-ai-mcp-scanner>=0.1.0

这意味着你使用的是Python 3.14,它不受支持。这 cisco-ai-mcp-scanner 该包需要Python 3.11-3.13。

解决方案:

  1. 安装Python 3.13: brew install python@3.13
  2. 删除旧的虚拟环境: rm -rf venv
  3. 使用Python 3.13创建一个新的venv: python3.13 -m venv venv
  4. 激活并安装依赖项: source venv/bin/activate && pip install -r requirements.txt

“外部管理环境”错误

如果您在运行时看到此错误 pip install,您正尝试在系统范围内安装软件包。始终使用虚拟环境:

python3.13 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

“无效的API密钥”错误

确保你包括 X-API-Key 请求中的标头与 API_KEY 环境变量。

“未设置API_KEY环境变量”

设置 API_KEY 渲染仪表板中的环境变量或 .env 文件。

扫描仪不可用

检查是否已配置以下至少一项:

  • MCP_SCANNER_API_KEY (API分析仪用)
  • MCP_SCANNER_LLM_API_KEY (适用于LLM分析仪)

YARA分析仪始终可用。

MCP服务器连接错误

确保:

  • MCP服务器URL正确且可访问
  • 身份验证凭据有效
  • MCP服务器正在运行并响应

贡献

这是一个将MCP扫描仪集成到MERN应用程序中的个人项目。请随意分叉并适应您的需求。

许可证

该项目封装了思科AI防御MCP扫描器。请参阅 mcp扫描库 扫描仪许可。

资源