稳健性审计MCP
  ](https://nodejs.org/) 
用于Solidity智能合约自动安全分析的模型上下文协议(MCP)服务器。与Slither和Aderyn等行业标准工具集成,并与SWC注册表进行内置模式匹配。
快速入门:将审核添加到项目中
在2分钟内为任何Solidity项目添加自动安全审计:
1.将工作流复制到您的项目中
创建 .github/workflows/audit.yml 在您的Solidity项目中:
name: Smart Contract Audit
on:
pull_request:
paths: ["**.sol"]
push:
branches: [main]
paths: ["**.sol"]
permissions:
contents: read
pull-requests: write
security-events: write
checks: write
jobs:
audit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: "20"
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Install audit tools
run: |
pip install slither-analyzer solc-select
solc-select install 0.8.28 && solc-select use 0.8.28
curl -L https://foundry.paradigm.xyz | bash
~/.foundry/bin/foundryup
echo "$HOME/.foundry/bin" >> $GITHUB_PATH
# Install Aderyn (x86_64 Linux)
ADERYN_VER=$(curl -sf https://api.github.com/repos/Cyfrin/aderyn/releases/latest | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/')
curl -fL "https://github.com/Cyfrin/aderyn/releases/download/${ADERYN_VER}/aderyn-x86_64-unknown-linux-gnu.tar.xz" | tar -xJf - -C /tmp
sudo install -m 755 /tmp/aderyn /usr/local/bin/aderyn
npm install -g solidity-audit-mcp
- name: Run Audit
run: |
audit-cli audit contracts/ --format markdown
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}2.就是这样!
每一个触及的PR .sol 文件将被自动审核。
运作原理
┌─────────────────────────────────────────────────────────────────────┐
│ YOUR PROJECT │
│ (e.g., smart-contract-audit-example) │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ 1. You modify Token.sol and create a PR │
│ │
│ 2. GitHub triggers the audit workflow │
│ │
│ 3. MCP Audit Server runs ALL analyzers on changed .sol files │
│ (Slither, Aderyn, Slang AST, SWC patterns, Gas optimizer, │
│ Echidna & Halmos when opt-in test functions are present) │
│ │
│ 4. Results appear directly in your PR: │
│ ├── ✓ Inline annotations on problematic lines │
│ ├── ✓ Summary comment with all findings │
│ ├── ✓ Check status (pass/fail based on severity) │
│ └── ✓ Security tab integration (SARIF) │
│ │
└─────────────────────────────────────────────────────────────────────┘你在PR中看到了什么
每个易受攻击行上的内联注释:
function withdraw(uint256 amount) external {
require(balances[msg.sender] >= amount);
(bool success, ) = msg.sender.call{value: amount}("");
// ▲ 🟠 HIGH: Reentrancy vulnerability
// │ State change after external call allows reentrancy attack.
// │ Recommendation: Use checks-effects-interactions pattern.
// └─ Detector: slither
require(success);
balances[msg.sender] -= amount; // ← State change should be BEFORE the call
}PR评论及完整报告:
┌────────────────────────────────────────────────────────────┐
│ 🔍 Smart Contract Audit Report │
│ │
│ Risk Level: 🟠 HIGH │
│ Findings: 0 critical, 2 high, 3 medium │
│ Gas Optimizations: 5 suggestions (~500 gas savings) │
│ │
│ ┌──────────┬─────────────────────┬─────────────┬───────┐ │
│ │ Severity │ Title │ Location │ Tool │ │
│ ├──────────┼─────────────────────┼─────────────┼───────┤ │
│ │ HIGH │ Reentrancy │ Token.sol:45│slither│ │
│ │ HIGH │ Unprotected withdraw│ Token.sol:32│aderyn │ │
│ │ MEDIUM │ Floating pragma │ Token.sol:1 │slang │ │
│ └──────────┴─────────────────────┴─────────────┴───────┘ │
└────────────────────────────────────────────────────────────┘检查PR上的状态:
- 🔴 失败 -如果存在严重或高度严重的发现
- 🟢 通过 -如果没有发现高于您配置的阈值
可选:通过问题进行按需审计
想通过创建问题或评论来触发审核吗?添加 .github/workflows/audit-on-demand.yml:
name: On-Demand Audit
on:
issues:
types: [opened]
issue_comment:
types: [created]
permissions:
contents: read
issues: write
jobs:
audit:
if: contains(github.event.issue.title, 'audit') || contains(github.event.comment.body, 'audit')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Install tools
run: |
pip install slither-analyzer
npm install -g solidity-audit-mcp
- name: Run Audit
id: audit
run: |
audit-cli audit contracts/ --format markdown > report.md
- name: Post Report
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const report = fs.readFileSync('report.md', 'utf8');
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: report
});现在,在标题中创建一个带有“审计”的问题,并获得一份完整的安全报告作为评论。
______________________________________________________________________
它的作用
Solidity Audit MCP为人工智能助手(如Claude)提供了对Solidity智能合约进行全面安全审计的能力。它结合了多种分析方法:
外部分析仪(需要安装):
- 滑行 -使用90+漏洞检测器追踪Bits的静态分析框架
- Aderyn -Cyfrin基于Rust的分析仪,可实现快速、准确的检测
- 铸造厂 -运行伪造测试并获取覆盖率报告
- 针鼹 *(选择加入)* -Trail of Bits基于属性的模糊器;当合同包含以下内容时激活
echidna_*测试功能(仅限x86_64) - 哈尔莫斯 *(选择加入)* -符号执行引擎;当合同包含以下内容时激活
check_*测试函数
内置分析(无外部依赖):
- 俚语分析器 -Nomic Foundation的Solidity解析器(
@nomicfoundation/slang)用于精确的基于AST的漏洞检测。包含在npm依赖项中。 - SWC模式匹配 -针对智能合约弱点分类注册表的检测(86个检测器)
多个工具的结果会自动进行重复数据消除并按严重程度排序,从而为您提供潜在问题的统一视图。
先决条件
Node.js 20+
# Using nvm (recommended)
nvm install 20
nvm use 20
# Or download from https://nodejs.org/滑行
Trail of Bits的静态分析框架。
# Using pip (requires Python 3.8+)
pip install slither-analyzer
# Or using pipx for isolated installation
pipx install slither-analyzer
# Verify installation
slither --version注: Slither需要 solc (Solidity编译器)待安装。
Aderyn
Cyfrin的锈基分析仪。
# Using cargo (requires Rust)
cargo install aderyn
# Or using curl (Linux/macOS)
curl -L https://raw.githubusercontent.com/Cyfrin/aderyn/dev/cyfrinup/install | bash
cyfrinup
# Verify installation
aderyn --version铸造厂
以太坊开发工具包(包括锻造、铸造、铁砧)。
# Install foundryup
curl -L https://foundry.paradigm.xyz | bash
# Then run foundryup to install forge, cast, anvil
foundryup
# Verify installation
forge --versionsolc(Solidity编译器)
Slither要求编译。
# Using solc-select (recommended - allows multiple versions)
pip install solc-select
solc-select install 0.8.20
solc-select use 0.8.20
# Or on macOS with Homebrew
brew install solidity
# Or on Ubuntu/Debian
sudo add-apt-repository ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install solc
# Verify installation
solc --version针鼹 *(可选--属性模糊器)*
Trail of Bits的基于属性的模糊器。仅当您的合同明确规定时才需要 echidna_* 测试功能。
预构建二进制文件(Linux x86_64/macOS):
# macOS (via brew)
brew install echidna
# Linux x86_64 — download latest pre-built binary
ECHIDNA_VER=$(curl -sf https://api.github.com/repos/crytic/echidna/releases/latest | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/')
ECHIDNA_VER_CLEAN="${ECHIDNA_VER#v}"
curl -L "https://github.com/crytic/echidna/releases/download/${ECHIDNA_VER}/echidna-${ECHIDNA_VER_CLEAN}-x86_64-linux.tar.gz" -o /tmp/echidna.tar.gz
tar -xzf /tmp/echidna.tar.gz -C /tmp
sudo install -m 755 /tmp/echidna /usr/local/bin/echidna
# Verify installation
echidna --version注: 没有预构建的ARM64(Apple Silicon)二进制文件可用。在ARM64上,Echidna被优雅地跳过——所有其他分析器都保持正常工作。
哈尔莫斯 *(可选--符号执行)*
a16z的符号执行引擎。仅当您的合同明确规定时才需要 check_* 测试功能。
# Using pip (requires Python 3.8+)
pip install halmos
# Or using pipx
pipx install halmos
# Verify installation
halmos --version注: Halmos依赖于z3-solver在ARM64(Apple Silicon)上,预构建的轮子可能不可用,需要从源代码编译cmake和build-essential。如果安装失败,Halmos将被优雅地跳过。
安装
# Clone the repository
git clone https://github.com/mariano-aguero/solidity-audit-mcp.git
cd solidity-audit-mcp
# Install dependencies
npm install
# Build the project
npm run build
# Verify the build
node dist/index.js
# Should output: [INFO] Starting solidity-audit-mcp v1.6.0
# Press Ctrl+C to exit码头工人
对于预装了所有工具的完整环境,请使用Docker:
# Build the image
npm run docker:build
# Run MCP server
npm run docker:run
# Run CLI audit
npm run docker:cli -- analyze /contracts/MyContract.sol
# Interactive shell with all tools
npm run docker:shellDocker与克劳德桌面
{
"mcpServers": {
"audit": {
"command": "docker",
"args": ["run", "-i", "-v", "/path/to/contracts:/contracts", "solidity-audit-mcp"]
}
}
}包含什么
Docker镜像包括:
- Node.js 20
- Slither(Python)——静态分析
- Aderyn v0.6.8(Rust)——基于AST的快速检测
- 铸造厂(锻造、铸造、砧座)——测试和覆盖
- solc选择常用的Solidity版本(0.8.28、0.8.24、0.8.20等)
- Halmos——符号执行(仅限x86_64;ARM64优雅跳过)
- Echidna——属性模糊器(仅限x86_64;ARM64优雅跳过)
平台说明:
- 所有工具都适用于x86_64(标准CI/CD环境)
- 在ARM64(苹果硅)上,Slither、Aderyn和Forge完全可用;Echidna和Halmos需要x86_64
SaaS模式(远程服务器)
将MCP服务器作为任何MCP客户端都可以通过HTTP/SSE连接的远程服务运行。
快速开始
# Build and start the SaaS server
npm run saas:build
npm run saas:up
# Check status
curl http://localhost:3000/health
# View logs
npm run saas:logs
# Stop
npm run saas:down配置
# 1. Copy example environment file
cp .env.example .env
# 2. Generate a secure API key
openssl rand -hex 32
# 3. Edit .env and set your API key
# MCP_API_KEY=your-generated-key
# 4. Start the server
npm run saas:up或者将API键设置为内联:
MCP_API_KEY=your-secret-key npm run saas:upMCP客户端配置(SSE传输)
配置您的MCP客户端以连接到远程服务器:
{
"mcpServers": {
"audit": {
"transport": {
"type": "sse",
"url": "http://localhost:3000/sse"
}
}
}
}使用API密钥验证:
{
"mcpServers": {
"audit": {
"transport": {
"type": "sse",
"url": "http://your-server.com:3000/sse",
"headers": {
"X-API-Key": "your-secret-key"
}
}
}
}
}API终点
| 端点 | 方法 | 描述 |
|---|---|---|
/health | GET | 使用分析器状态进行全面健康检查 |
/health/quick | GET | 快速健康检查(无需分析仪验证) |
/info | GET | 服务器信息和可用工具 |
/sse | MCP的GET | SSE连接 |
/message | POST | MCP的消息处理程序 |
/api/analyze | POST | 从源代码分析合同 |
/api/check | POST | 从源代码快速检查漏洞 |
/api/ci/review | POST | CI:分析并发布在线公关评论 |
健康检查响应
{
"status": "healthy",
"server": "solidity-audit-mcp",
"version": "1.6.0",
"uptime": 3600,
"tools": 10,
"analyzers": {
"slither": { "available": true, "version": "0.11.5" },
"aderyn": { "available": true, "version": "0.6.8" },
"forge": { "available": true, "version": "1.5.1-stable" },
"solc": { "available": true, "version": "0.8.28" },
"echidna": { "available": false, "error": "..." },
"halmos": { "available": false, "error": "..." },
"slang": { "available": true, "version": "available" }
},
"timestamp": "2026-01-15T10:30:00.000Z"
}状态值:
healthy--岩芯分析仪(Slither+Forge)可用degraded--只有一个核心分析仪可用,或只有Slang(内置)unhealthy--没有可用的分析器(返回HTTP 503)
注:echidna和halmos是需要明确设置的选择性模糊器。他们的缺席并不影响整体状况。
环境变量
复制 .env.example 到 .env 并配置:
cp .env.example .env| 变量 | 默认值 | 描述 |
|---|---|---|
PORT | 3000 | 服务器端口 |
HOST | 0.0.0.0 | 服务器主机 |
MCP_API_KEY | (none) | 用于身份验证的API密钥(推荐用于生产) |
MCP_AUDIT_LOG_LEVEL | info | 日志级别(调试、信息、警告、错误) |
NODE_ENV | 生产 | 节点环境 |
支持的身份验证方法:
- 头球
X-API-Key: your-key - 持票人:
Authorization: Bearer your-key
生产部署
对于生产,请考虑:
- 使用HTTPS -使用SSL设置反向代理(nginx)
- 启用身份验证 -设置
MCP_API_KEY - 安装合同 -将您的合同目录装载到容器中
- 资源限制 -在docker compose中设置内存/CPU限制
nginx SSL示例:
docker-compose -f docker/docker-compose.saas.yml --profile with-ssl up -d配置
选项1:项目级配置(.mcp.json)
创建一个 .mcp.json 项目根目录中的文件:
{
"mcpServers": {
"audit": {
"command": "node",
"args": ["/path/to/solidity-audit-mcp/dist/index.js"]
}
}
}选项2:全局配置(~/.claude/mcp.json)
为了获得系统范围内的可用性,请添加到您的Claude MCP配置中:
{
"mcpServers": {
"audit": {
"command": "node",
"args": ["/path/to/solidity-audit-mcp/dist/index.js"]
}
}
}选项3:使用npx(如果已发布)
{
"mcpServers": {
"audit": {
"command": "npx",
"args": ["solidity-audit-mcp"]
}
}
}使用Claude代码
配置后,审计工具在Claude Code中可用。以下是一些示例提示:
Analyze the security of contracts/Token.solCheck contracts/Vault.sol for vulnerabilities against SWC-107 and SWC-115Get the attack surface info for src/MyContract.solRun the full audit pipeline on contracts/Protocol.sol including tests可用工具
analyze_contract
在Solidity合约上运行完整的安全分析管道。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
contractPath | string | 是 | 路径 .sol 文件 |
projectRoot | string | 否 | 项目的根目录(如果未提供,则自动检测) |
runTests | boolean | 否 | 是否将伪造测试作为分析的一部分运行(默认值:false) |
analyzers | string\[\] | 否 | 要运行的特定分析器: "slither", "aderyn", "slang", "gas", "echidna", "halmos" (如果省略,则运行所有可用项) |
它的作用:
- 解析合约元数据(函数、状态变量、继承)
- Slither和Aderyn并行运行
- 检测有风险的代码模式
- 消除来自多个工具的重复发现
- 按严重程度对发现进行排序
- 返回包含JSON数据的格式化报告
______________________________________________________________________
get_contract_info
在不运行完整分析的情况下提取元数据和攻击面信息。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
contractPath | string | 是 | 路径 .sol 文件 |
退货:
- 合约名称、编译器版本、继承链
- 按可见性分组的功能(外部、公共、内部、私有)
- 状态变量及其可见性
- 事件、错误和修饰符
- 攻击面指标(付费功能、委托呼叫使用等)
- 基于检测到的模式的安全考虑
______________________________________________________________________
check_vulnerabilities
使用基于正则表达式的检测根据SWC注册表模式扫描合约。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
contractPath | string | 是 | 路径 .sol 文件 |
detectors | string\[\] | 否 | 要检查的特定SWC ID的数组(例如。, ["SWC-107", "SWC-115"]) |
支持的SWC模式:
- SWC-100:功能默认可见性
- SWC-101:整数溢出/欠流(未检查的块)
- SWC-103:浮动Pragma
- SWC-104:未选中的呼叫返回值
- SWC-105:无保护乙醚提取
- SWC-106:无保护的自毁
- SWC-107:重新收缩
- SWC-115:通过tx.origin授权
- SWC-116:块值作为时间代理
- 还有20+。..
______________________________________________________________________
run_tests
执行伪造测试并返回具有可选覆盖率的结果。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
projectRoot | string | 是 | Foundry项目的根目录 |
contractName | string | 否 | 要测试的特定合约(如果省略则全部运行) |
退货:
- 测试通过/失败/跳过计数
- 覆盖百分比(如果配置)
- 气体报告
- 执行时间
______________________________________________________________________
generate_report
根据调查结果和合同元数据生成格式化的审计报告。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
findings | 正在查找\[\] | 是 | 从分析中查找对象的数组 |
contractInfo | ContractInfo | 是 | 具有合同元数据的ContractInfo对象 |
format | string | 否 | 输出格式- "markdown" (默认)或 "json" |
projectName | string | 否 | 被审核项目的名称 |
auditorName | string | 否 | 审核员姓名(默认:“Solidity Audit MCP”) |
退货:
- 风险等级执行摘要
- 合同概述
- 详细调查结果及建议
- 补救指导
______________________________________________________________________
optimize_gas
分析天然气优化机会的合同。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
contractPath | string | 是 | 路径 .sol 文件 |
includeInformational | boolean | 否 | 包括低影响建议(默认值:false) |
退货:
- 存储优化(打包、缓存)
- 循环优化
- 功能可见性建议
- 通话数据与内存建议
- 预计节省的天然气
______________________________________________________________________
diff_audit
比较合同的两个版本,只审核更改。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
oldContractPath | string | 是 | 旧版本的路径 |
newContractPath | string | 是 | 新版本的路径 |
focusOnly | boolean | 否 | 仅报告更改代码中的问题(默认值:true) |
退货:
- 添加/删除/修改功能
- 引入新漏洞
- 通过更改解决的问题
- 变更风险评估
______________________________________________________________________
audit_project
扫描整个项目目录以查找Solidity合同并审核所有合同。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
projectRoot | string | 是 | 项目的根目录 |
pattern | string | 否 | 合同的全局模式(默认值: **/*.sol) |
exclude | string\[\] | 否 | 要排除的模式(默认值: ["node_modules/**", "test/**"]) |
退货:
- 找到的所有合同摘要
- 所有合同的汇总结果
- 按合同细分
- 项目级风险评估
______________________________________________________________________
generate_invariants
分析Solidity合约并生成现成的Foundry不变测试模板。自动从源代码和继承中检测协议类型,以生成目标不变量。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
contractPath | string | 是 | 路径 .sol 文件 |
protocolType | string | 否 | 协议类型: "auto" (默认), "erc20", "erc721", "vault", "lending", "amm", "governance", "staking" |
includeStateful | boolean | 否 | 包含有状态的不变建议 forge test --invariant 运行命令(默认值:true) |
支持的协议类型:
- ERC-20 --全面供应节约、批准安全、转移偿付能力
- ERC-4626保险库 --totalAssets≥总市值,股价不减,存/取款往返
- 借贷 --协议偿付能力、可清算头寸、非负利息应计
- AMM --不变的产品k,没有免费的午餐交换,LP份额保护
- 治理 --提案状态机、法定人数不变性、投票权重守恒
- 质押 --奖励单调性、总质押余额、削减会计
- 通用的 --平衡保护、访问控制、无未经授权的造币/焚烧
退货:
- 严重性分类不变建议(严重/高/中)
- 准备粘贴
invariant_*()功能体 - 带有处理程序合同的Foundry设置模板
- 运行以下命令
forge test --invariant
______________________________________________________________________
explain_finding
返回安全发现的详细说明。接受SWC注册表ID、自定义检测器ID或自由文本关键字。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
findingId | string | Yes | 查找ID或关键字--例如。 "SWC-107", "CUSTOM-032", "reentrancy", "flash loan", "paymaster" |
severity | string | 否 | 其他上下文的严重性级别("critical", "high", "medium", "low", "informational") |
contractContext | string | 否 | 对合同进行简要描述以定制解释 |
支持的查找ID(共19个):
| ID | 标题 | 严重性 |
|---|---|---|
SWC-101 | 整数溢出/欠流 | 高 |
SWC-103 | 浮动Pragma | 低 |
SWC-104 | 未检查的返回值 | 高 |
SWC-107 | 重新进入 | 关键 |
SWC-112 | 将呼叫委托给不受信任的呼叫者 | 严重 |
SWC-115 | 通过tx.origin授权 | 高 |
SWC-116 | 块时间戳依赖性 | 中等 |
CUSTOM-001 | 数组长度不匹配 | 高 |
CUSTOM-004 | Oracle价格操纵/闪电贷款攻击 | 严重 |
CUSTOM-005 | 缺少零地址验证 | 中等 |
CUSTOM-006 | 关键状态更改缺少事件 | 低 |
CUSTOM-011 | 无重放保护的签名 | 高 |
CUSTOM-013 | 通过abi.encodePacked进行哈希冲突 | 中等 |
CUSTOM-015 | 乘法前除法 | 中等 |
CUSTOM-016 | 无截止日期的许可证 | 中等 |
CUSTOM-017 | 关键功能缺少访问控制 | 关键 |
CUSTOM-018 | ERC-7702未受保护的初始化器 | 严重 |
CUSTOM-029 | Merkle双重索赔 | 高 |
CUSTOM-032 | ERC-4337付款主管流失 | 严重 |
支持的关键字: reentrancy, overflow, underflow, pragma, unchecked return, timestamp, delegatecall, tx.origin, array length, zero address, missing events, replay, nonce, encodepacked, hash collision, precision loss, permit, access control, merkle, airdrop, flash loan, oracle, erc-7702, paymaster, erc-4337
退货:
- 根本原因分析
- 具体影响描述
- 逐步利用场景
- 易受攻击的代码示例与安全代码示例
- Foundry PoC测试模板
- 补救步骤
- 参考文献(SWC注册表、审计报告、研究)
CLI使用情况
审计服务器包括一个CLI,用于在Claude Code之外运行审计,这对CI/CD管道很有用。
安装
# Global installation
npm install -g solidity-audit-mcp
# Or run directly
npx solidity-audit-mcp命令
# Run security audit
solidity-audit-cli audit ./contracts/Token.sol
# Compare contract versions
solidity-audit-cli diff ./old/Token.sol ./new/Token.sol
# Analyze gas optimizations
solidity-audit-cli gas ./contracts/Token.sol
# Output formats
solidity-audit-cli audit ./contracts/Token.sol --format json
solidity-audit-cli audit ./contracts/Token.sol --format sarif --output results.sarif
solidity-audit-cli audit ./contracts/Token.sol --format markdown
# Filter by severity
solidity-audit-cli audit ./contracts/Token.sol --severity-threshold highCLI选项
| 选项 | 简短 | 描述 |
|---|---|---|
--format | -f | 输出格式:markdown、json、sarif |
--output | -o | 将输出写入文件而不是stdout |
--severity-threshold | -s | 最低严重程度:严重、高、中、低、信息性 |
--quiet | -q | 抑制进度消息 |
--no-color | 禁用彩色输出 |
退出代码
| 代码 | 含义 |
|---|---|
| 0 | 未发现高于阈值的结果 |
| 1 | 检测到的结果高于阈值 |
| 2 | 执行错误 |
GitHub代码扫描集成
审计服务器可以使用SARIF格式将结果上传到GitHub的安全选项卡。这使得:
- 安全选项卡警报 -在“安全”>“代码扫描”部分查看所有发现
- PR注释 -在pull请求中受影响的行上添加内联注释
- 安全概述 -存储库级安全见解
启用GitHub代码扫描
- 启用GitHub高级安全 (公共存储库免费)
- 首选 设置>安全>代码安全和分析 - 启用 代码扫描
- 添加工作流 到您的存储库:
# .github/workflows/code-scanning.yml
name: Code Scanning
on:
push:
branches: [main]
paths: ["**.sol"]
pull_request:
paths: ["**.sol"]
permissions:
contents: read
security-events: write
jobs:
analyze:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Install tools
run: |
pip install slither-analyzer
npm install -g solidity-audit-mcp
- name: Run Audit
run: |
solidity-audit-cli audit contracts/ --format sarif --output results.sarif
- name: Upload SARIF
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: results.sarif
category: "smart-contract-security"- 查看结果 工作流运行后,在“安全”选项卡中
SARIF输出
SARIF格式包括:
- 具有严重性映射的规则定义
- 带有行号的精确文件位置
- 安全严重性评分(0-10分)
- 用于追踪不同跑步记录的指纹
- 分类标签(可重入性、访问控制等)
# Generate SARIF locally
solidity-audit-cli audit contracts/Token.sol --format sarif --output audit.sarif
# View the structure
cat audit.sarif | jq '.runs[0].results | length'CI/CD集成
GitHub操作
使用提供的可重用操作进行全面的PR审核:
# .github/workflows/audit.yml
name: Smart Contract Audit
on:
pull_request:
paths: ["contracts/**", "src/**/*.sol"]
permissions:
contents: read
pull-requests: write
security-events: write
jobs:
audit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install tools
run: |
pip install slither-analyzer
curl -L https://foundry.paradigm.xyz | bash
~/.foundry/bin/foundryup
- name: Run Audit
uses: ./.github/actions/audit
with:
contracts-path: contracts/
severity-threshold: high
include-gas: "true"
diff-only: "true"
comment-on-pr: "true"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}动作输入
| 输入 | 默认值 | 描述 |
|---|---|---|
contracts-path | contracts/ | 合同目录路径 |
severity-threshold | high | 故障的最低严重程度 |
include-gas | true | 运行气体优化分析 |
diff-only | true | 仅审核PR中更改的文件 |
comment-on-pr | true | 将结果作为公关评论发布 |
fail-on-findings | true | 如果检测到结果,则操作失败 |
sarif-output | true | 生成用于代码扫描的SARIF |
行动输出
| 输出 | 描述 |
|---|---|
findings-count | 安全调查结果总数 |
critical-count | 关键发现数量 |
high-count | 严重程度较高的发现数量 |
risk-level | 总体风险:严重、高、中、低、清洁 |
sarif-file | 生成的SARIF文件的路径 |
PR评论格式
该操作在PR上发布了一条格式化的评论:
## Smart Contract Audit Report

**Risk Level:** HIGH
**Findings:** 0 critical, 2 high, 3 medium
**Gas Optimizations:** 5 suggestions (~500 gas savings)
Security Findings (5)
| Severity | Title | Location | Detector |
|----------|-------|----------|----------|
| HIGH | Reentrancy | Token.sol:45 | slither |
...
Gas Optimizations (5)
...
调查结果跟踪
审计服务器包括一个基于SQLite的系统,用于随时间跟踪调查结果。
特性
- 坚持 -结果存储在本地
.audit-history/findings.db - 状态跟踪 -将发现标记为
open,acknowledged,fixed,false_positive,或wont_fix - 趋势分析 -随着时间的推移,跟踪新发现与已解决的发现
- 去重 -跨运行的相同发现被跟踪为一个具有发生次数的条目
用法
import {
initDb,
recordAuditRun,
updateFindingStatus,
getOpenFindings,
getFindingTrend,
getStats,
} from "solidity-audit-mcp/storage";
// Initialize database
initDb("/path/to/project");
// Record an audit run
const summary = recordAuditRun(
"/path/to/project",
findings, // Array of Finding objects
"contracts/Token.sol",
["slither", "aderyn"]
);
console.log(`New: ${summary.newFindings}`);
console.log(`Resolved: ${summary.resolvedFindings}`);
console.log(`Total Open: ${summary.totalOpen}`);
// Mark a finding as false positive
updateFindingStatus(
"/path/to/project",
"finding-id",
"false_positive",
"Not exploitable in our context"
);
// Get open findings
const open = getOpenFindings("/path/to/project");
// Get trend data for last 30 days
const trend = getFindingTrend("/path/to/project", 30);
// { dates: [...], openCounts: [...], newCounts: [...], resolvedCounts: [...] }
// Get statistics
const stats = getStats("/path/to/project");
// { totalFindings, openFindings, fixedFindings, bySeverity, byDetector, ... }数据库模式
调查结果表:
| 列 | 类型 | 描述 |
|---|---|---|
| id | TEXT | 查找属性的SHA256哈希 |
| contract_path | TEXT | 合同文件的路径 |
| title | 文本 | 查找标题 |
| 严重性 | 文本 | 严重、高、中、低、信息性 |
| 状态 | 文本 | 打开、已确认、已修复、假阳性、wont_fix |
| first_seen | TEXT | 首次检测的ISO时间戳 |
| last_seen | TEXT | 上次检测的ISO时间戳 |
| 事件 | 整数 | 检测到的次数 |
audit_runs表:
| 列 | 类型 | 描述 |
|---|---|---|
| id | 文本 | UUID |
| 时间戳 | 文本 | ISO时间戳 |
| total_findings | INTEGER | 本次运行的总结果 |
| new_findings | INTEGER | 检测到新发现 |
| resolved_sessions | INTEGER | 自上次运行以来已修复的发现 |
| commit_hash | TEXT | Git提交哈希(如果可用) |
Git集成
默认情况下, .audit-history/ 已在评论中删除 .gitignore。您可以:
- 忽略它 -每个开发人员/CI都有自己的本地历史
- 承诺吧 -在整个团队中共享发现历史记录(在中取消注释
.gitignore)
输出示例
===============================================================================
SECURITY ANALYSIS REPORT: VulnerableVault
===============================================================================
Contract: VulnerableVault
Path: contracts/VulnerableVault.sol
Compiler: ^0.8.20
Analysis time: 12.5s
Tools: slither (5 findings), aderyn (3 findings)
-------------------------------------------------------------------------------
SUMMARY
-------------------------------------------------------------------------------
Total findings: 6
Critical: 1
High: 2
Medium: 2
Low: 1
Informational: 0
CRITICAL ISSUES FOUND - DO NOT DEPLOY
-------------------------------------------------------------------------------
HIGH-RISK PATTERNS DETECTED
-------------------------------------------------------------------------------
Line 45: tx.origin - Using tx.origin for authorization is vulnerable to phishing
Line 78: delegatecall - delegatecall executes code in the context of calling contract
Line 92: selfdestruct - selfdestruct can destroy the contract
-------------------------------------------------------------------------------
TOP FINDINGS
-------------------------------------------------------------------------------
[CRITICAL] Reentrancy Vulnerability
Location: contracts/VulnerableVault.sol:45
State change after external call in withdraw() allows reentrancy attack
[HIGH] Authorization through tx.origin
Location: contracts/VulnerableVault.sol:32
tx.origin used for authentication is vulnerable to phishing attacks
[HIGH] Unprotected SELFDESTRUCT
Location: contracts/VulnerableVault.sol:92
selfdestruct can be called by any address matching owner check严重程度级别
| 级别 | 图标 | 描述 |
|---|---|---|
| 严重 | :red_circle: | 可导致直接资金损失的可利用漏洞 |
| 高 | :orange_circle: | 可能导致重大影响的安全问题 |
| 中等 | :黄色_圆形: | 可能导致意外行为的问题 |
| 低 | :large_blue_circle: | 小问题或与最佳实践的偏差 |
| 信息 | :white_circle: | 建议和代码质量改进 |
局限性
这并不能取代正式审计
- 自动化工具可能会错过复杂的漏洞
- 业务逻辑问题需要人工审查
- 始终聘请专业审计师进行主网部署
工具依赖性
- 完整分析需要安装Slither和/或Aderyn
- 没有这些工具,只有基本的模式匹配可用
- 测试执行需要Foundry(锻造)
解析器限制
- 使用@nomicfoundation/slank进行基于AST的正则表达式回退解析
- 当存在多个合约时,解析文件中的第一个合约
- 复杂继承中的某些边缘情况可能无法完全检测到
假阳性
- 模式匹配可以标记合法的代码模式
- 始终结合上下文审查调查结果
- 使用置信度来确定审查的优先级
- 一些探测器故意具有攻击性
发展
# Run in development mode (with hot reload)
npm run dev
# Run CLI in development
npm run cli -- analyze ./contracts/MyContract.sol
# Type check
npm run typecheck
# Run tests (vitest)
npm test
# Run single test file
npx vitest run __tests__/analyzers/slither.test.ts
# Run tests matching a pattern
npx vitest run -t "deduplication"
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverage
# Lint the code
npm run lint
# Format code
npm run format
# Run all checks (typecheck + lint + test)
npm run check
# Clean build artifacts
npm run clean项目结构
solidity-audit-mcp/
├── src/
│ ├── index.ts # MCP server entry point (stdio) - ~40 lines
│ ├── server.ts # HTTP/SSE server entry point - ~280 lines
│ ├── cli.ts # CLI entry point (solidity-audit-cli)
│ │
│ ├── server/ # Server module (modular architecture)
│ │ ├── index.ts # Public API exports
│ │ ├── config.ts # Server configuration
│ │ ├── McpServer.ts # MCP server factory
│ │ ├── schemas/ # Zod validation schemas
│ │ ├── tools/ # MCP tool definitions
│ │ ├── handlers/ # Tool & HTTP handlers
│ │ ├── health/ # Health check logic
│ │ └── middleware/ # Auth & CORS
│ │
│ ├── analyzers/ # Analyzer adapters (Adapter pattern)
│ │ ├── IAnalyzer.ts # Interface + BaseAnalyzer
│ │ ├── AnalyzerRegistry.ts # Factory + Registry
│ │ ├── AnalyzerOrchestrator.ts # Parallel execution
│ │ └── adapters/ # Self-contained adapters (each owns its full implementation)
│ │ ├── SlitherAdapter.ts # Slither runner + detector map
│ │ ├── AderynAdapter.ts # Aderyn runner + deduplication
│ │ ├── SlangAdapter.ts # AST parsing with @nomicfoundation/slang
│ │ ├── GasAdapter.ts # Gas optimization patterns
│ │ ├── EchidnaAdapter.ts # Property fuzzer (opt-in)
│ │ └── HalmosAdapter.ts # Symbolic execution (opt-in)
│ │
│ ├── tools/ # MCP tool implementations (10 tools)
│ │ ├── analyzeContract.ts
│ │ ├── getContractInfo.ts
│ │ ├── checkVulnerabilities.ts
│ │ ├── runTests.ts
│ │ ├── generateReport.ts
│ │ ├── optimizeGas.ts
│ │ ├── diffAudit.ts
│ │ ├── auditProject.ts
│ │ ├── generateInvariants.ts # Foundry invariant test generator
│ │ └── explainFinding.ts # Finding KB (19 entries, 25+ keywords)
│ │
│ ├── templates/ # Markdown report templates
│ │ ├── index.ts # Template utilities
│ │ ├── reportTemplate.md
│ │ ├── findingTemplate.md
│ │ ├── prSummaryTemplate.md
│ │ ├── prLineCommentTemplate.md
│ │ └── diffAuditTemplate.md
│ │
│ ├── detectors/ # Custom detector system
│ │ ├── customDetectorEngine.ts
│ │ └── presets/ # Detector presets (web3, defi)
│ │
│ ├── ci/ # CI/CD integration
│ │ ├── index.ts
│ │ └── githubComment.ts # PR comment generator
│ │
│ ├── storage/ # Persistence layer
│ │ ├── index.ts
│ │ └── findingsDb.ts # SQLite findings tracker
│ │
│ ├── types/ # TypeScript type definitions
│ │ ├── index.ts
│ │ ├── analyzer.ts # Analyzer types
│ │ ├── result.ts # Rust-style Result type
│ │ └── tools.ts # Tool registry pattern
│ │
│ └── utils/ # Utility functions
│ ├── executor.ts # Command execution
│ ├── logger.ts # Structured logging
│ ├── severity.ts # Severity utilities
│ └── sarif.ts # SARIF report generator
│
├── __tests__/ # Test files (486 tests)
│ ├── analyzers/ # Adapter & orchestrator tests
│ ├── tools/ # Tool integration tests
│ ├── ci/ # GitHub comment tests
│ ├── detectors/ # Custom detector tests
│ ├── utils/ # Utility tests
│ └── fixtures/ # Test Solidity contracts
│
├── docs/
│ └── ARCHITECTURE.md # Architecture guide with diagrams
│
├── .github/
│ ├── actions/audit/ # Reusable GitHub Action
│ └── workflows/ # Example workflows
│
├── docker/
│ ├── Dockerfile.saas # SaaS Docker (HTTP/SSE) — all tools included
│ ├── Dockerfile.dev # Development Docker (hot-reload)
│ ├── docker-compose.yml # Local container orchestration
│ └── docker-compose.saas.yml # SaaS deployment orchestration
├── .env.example # Environment variables template
├── package.json
├── tsconfig.json
├── vitest.config.ts # Test configuration
├── CLAUDE.md # Claude Code instructions
└── README.md贡献
添加新的SWC探测器
编辑 src/tools/checkVulnerabilities.ts 并添加到 SWC_PATTERNS 数组:
{
id: "SWC-XXX",
title: "Your Detector Title",
description: "What this vulnerability is about",
severity: Severity.HIGH,
patterns: [/your-regex-pattern/g],
negativePatterns: [/pattern-that-indicates-safe-code/g], // optional
remediation: "How to fix this issue",
references: ["https://swcregistry.io/docs/SWC-XXX"],
}添加滑检测器映射
编辑 src/analyzers/adapters/SlitherAdapter.ts 并添加到 SLITHER_DETECTOR_MAP:
"detector-name": {
title: "Human-readable title",
description: "What this detector finds",
}添加代码模式检测
编辑 src/analyzers/adapters/SlangAdapter.ts:
对于基于AST的检测(首选): 增添 SECURITY_DETECTORS 和 QUERY_STRINGS:
// In SECURITY_DETECTORS array
{
id: "SLANG-XXX",
title: "Your Detector Title",
description: "What this vulnerability is about",
severity: Severity.HIGH,
recommendation: "How to fix this issue",
}
// In QUERY_STRINGS object
"SLANG-XXX": `
@match [YourASTPattern]
`对于基于正则表达式的检测: 增添 patternDefs 在 detectPatterns() 功能:
{
name: "pattern-name",
regex: /your-regex/,
risk: "high" | "medium" | "low" | "info",
description: "Why this pattern is risky",
}运行测试套件
# Run all tests
npm test
# Run specific test file
npm test -- __tests__/analyzers/slither.test.ts
# Run tests matching a pattern
npm test -- -t "deduplication"许可证
麻省理工学院
