Introduction
Smart contract auditing is a critical yet time-intensive process in Web3 development. Vulnerabilities like reentrancy attacks, integer overflows, or unsafe external calls can lead to millions in losses, as seen in high-profile exploits like the Ronin Bridge hack. Traditional tools like Slither or Mythril help, but they lack the contextual reasoning power of large language models (LLMs).
Enter MCP (Model Context Protocol) servers—powerful extensions for Claude AI that provide real-time, structured data access and tool integration. In this guide, we'll build an MCP server tailored for Web3 auditing, enabling Claude (Opus, Sonnet, or Haiku) to analyze Solidity code, fetch on-chain data, and generate comprehensive audit reports. This Claude-specific workflow solves real problems for developers and auditors, blending AI reasoning with blockchain-native tools.
By the end, you'll have a deployable MCP server and prompts to audit contracts faster and more accurately.
What Are MCP Servers?
MCP servers are lightweight HTTP/WS servers that extend Claude's context via the Model Context Protocol. They act as "external brains" for Claude, handling:
- Tool calls: Claude invokes endpoints with JSON payloads (e.g., via function calling).
- Data retrieval: Fetch blockchain state, contract bytecode, or analysis results.
- Stateful sessions: Maintain audit context across Claude conversations.
Unlike generic APIs, MCP is optimized for Claude's XML-tagged tool use, ensuring low-latency integration. Anthropic's ecosystem supports MCP out-of-the-box in Claude Desktop, Claude Code, and API via SDKs.
Key Benefits for Web3:
- Real-time Etherscan/Alchemy queries without token limits.
- Automated static analysis with tools like solc or Slither.
- Claude's nuanced vulnerability detection (e.g., business logic flaws).
Challenges in Smart Contract Auditing
Manual audits are error-prone:
- Static analysis misses context: Slither flags issues but can't explain DeFi-specific risks.
- On-chain verification: Hard to correlate code with deployed bytecode.
- Scale: Auditing 100+ contracts for a project is tedious.
- False positives: Tools overwhelm with noise.
Claude alone lacks Solidity parsers or blockchain RPC access. MCP bridges this gap.
Building Your MCP Server for Web3 Auditing
We'll use Node.js for simplicity, but Python/FastAPI works too. Deploy to Vercel, Railway, or a VPS.
Prerequisites
- Node.js 18+
- Alchemy/Etherscan API key (free tier suffices)
- Slither CLI:
pip install slither-analyzer - Claude API key
Step 1: Project Setup
git clone <your-repo>
cd mcp-web3-auditor
npm init -y
npm install express axios child_process cors
Step 2: Core MCP Server
MCP expects /mcp endpoint for handshake and /tools for Claude's function calls. Here's the base server:
const express = require('express');
const { exec } = require('child_process');
const axios = require('axios');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
// MCP Handshake
app.post('/mcp', (req, res) => {
res.json({ protocol: '1.0', capabilities: ['solidity-analysis', 'blockchain-query'] });
});
// Tool Registry (Claude queries this)
app.get('/tools', (req, res) => {
res.json([
{
name: 'analyze_solidity',
description: 'Run Slither on Solidity code for vulnerabilities',
parameters: {
type: 'object',
properties: {
code: { type: 'string' },
contractName: { type: 'string' }
}
}
},
{
name: 'get_contract_data',
description: 'Fetch on-chain data via Alchemy/Etherscan',
parameters: {
type: 'object',
properties: {
address: { type: 'string' },
chainId: { type: 'number', enum: [1, 5, 137] } // Mainnet, Goerli, Polygon
}
}
}
]);
});
app.listen(3000, () => console.log('MCP Server on port 3000'));
Step 3: Implement Solidity Analysis Tool
Integrate Slither for static analysis:
app.post('/tools/analyze_solidity', async (req, res) => {
const { code, contractName } = req.body;
const tempDir = `/tmp/${Date.now()}`;
// Write Solidity file
require('fs').mkdirSync(tempDir);
require('fs').writeFileSync(`${tempDir}/${contractName}.sol`, code);
exec(`slither ${tempDir} --json -`, (err, stdout) => {
if (err) return res.json({ error: err.message });
const results = JSON.parse(stdout);
res.json({
vulnerabilities: results.results,
confidence: results.confidence_scores || []
});
});
});
Pro Tip: For production, use Dockerized Slither to avoid temp files.
Step 4: Blockchain Data Integration
Query deployed contracts:
app.post('/tools/get_contract_data', async (req, res) => {
const { address, chainId } = req.body;
const apiKey = process.env.ALCHEMY_KEY;
const url = `https://eth-${chainId === 1 ? '' : chainId === 5 ? 'goerli.' : 'polygon.'}g.alchemy.com/v2/${apiKey}`;
try {
const [source, bytecode] = await Promise.all([
axios.get(`https://api.etherscan.io/api?module=contract&action=getsourcecode&address=${address}&apikey=${process.env.ETHERSCAN_KEY}`),
axios.post(url, { jsonrpc: '2.0', method: 'eth_getCode', params: [address, 'latest'], id: 1 })
]);
res.json({
sourceCode: source.data.result[0].SourceCode,
bytecode: bytecode.data.result,
verified: source.data.result[0].SourceCode !== ''
});
} catch (error) {
res.json({ error: error.message });
}
});
Integrating with Claude
Connect via Claude API or Claude Desktop (set MCP_URL=http://localhost:3000).
Sample Prompt for Auditing
Use this in Claude's chat or API:
<tool_use>
You are a Web3 security auditor. Audit this smart contract:
Solidity Code: [paste code]
Contract Address: 0x...
Chain: Ethereum Mainnet
1. Call analyze_solidity on the code.
2. Call get_contract_data on the address.
3. Compare source vs. bytecode.
4. List high/medium/low risks with fixes.
5. Score overall security (A-F).
</tool_use>
Claude will auto-invoke tools via XML tags, like:
<tool_call name="analyze_solidity">
<parameters>{ "code": "...", "contractName": "MyContract" }</parameters>
</tool_call>
Full API Example (Node.js + Claude SDK)
const { Claude } = require('@anthropic-ai/sdk');
const claude = new Claude({ apiKey: process.env.CLAUDE_API_KEY });
const mcpUrl = 'http://localhost:3000';
const audit = async (code, address) => {
const msg = await claude.messages.create({
model: 'claude-3-5-sonnet-20240620',
max_tokens: 2000,
tools: [{ type: 'mcp', mcp_url: mcpUrl }],
messages: [{ role: 'user', content: `Audit: ${code} at ${address}` }]
});
console.log(msg.content);
};
Real-World Example: Auditing a Reentrancy-Vulnerable Contract
Consider this flawed ERC20 token:
// Vulnerable.sol
contract Vulnerable {
mapping(address => uint) balances;
mapping(address => bool) frozen;
function withdraw(uint amount) public {
require(!frozen[msg.sender]);
(bool success, ) = msg.sender.call{value: amount}('');
require(success);
balances[msg.sender] -= amount;
} // Reentrancy risk!
}
Claude's Audit Output (via MCP):
- High Risk: Reentrancy in
withdraw. Fix: Use Checks-Effects-Interactions. - Slither Results:
Reentrancydetector fired (detectors: 5, impact: high). - On-Chain: Bytecode matches source (verified on Etherscan).
- Score: D (Mitigate before deploy).
Run it: MCP flags the issue in <10s, vs. hours manually.
Advanced Features
- Multi-Contract Analysis: Extend to
--solc-jsonfor libraries. - Custom Detectors: Add Mythril via Docker subprocess.
- Agents: Chain with Claude Agents for auto-fork testing (Hardhat + Anvil).
- Enterprise: Authenticate MCP with JWT for team audits.
Scaling Tips:
- Cache queries with Redis.
- Use Haiku for quick scans, Opus for deep reviews.
- Integrate with CI/CD: GitHub Actions calls MCP via Claude Code.
Limitations and Best Practices
- MCP Limits: 10s/tool call timeout; batch wisely.
- Not a Replacement: Claude + MCP augments, doesn't replace manual audits (e.g., Certik).
- Privacy: Self-host MCP for proprietary code.
- Updates: Track Anthropic's MCP spec changes.
Best Practices:
- Always verify bytecode.
- Prompt Claude for exploit PoCs.
- Test on testnets first.
Conclusion
MCP servers transform Claude into a Web3 auditing powerhouse, combining AI insight with precise tools. Deploy this setup to catch bugs early, save time, and build safer dApps. Fork the repo, tweak for your chain (Solana via Anchor?), and share your audits in Claude Directory comments.
Next Steps:
- Deploy:
vercel --prod - Explore: MCP for DeFi sims or NFT metadata.
- Resources: Anthropic MCP Docs, Slither GitHub
(Word count: 1428)
Stay ahead of the AI curve
The most important updates, news, and content — delivered in one weekly newsletter.