bcamp136/foundry-mcp-server
If you are the rightful owner of foundry-mcp-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.
The Foundry MCP Server is a Model Context Protocol server designed to facilitate interaction with Foundry, Anvil, and Cast commands, providing a seamless development experience within VS Code.
Foundry MCP Server
A Model Context Protocol (MCP) server that provides tools for interacting with Foundry, Anvil, and Cast commands.
Setup for VS Code
Prerequisites
-
Install Foundry:
curl -L https://foundry.paradigm.xyz | bash foundryup -
Install Node.js (version 18 or higher)
-
Ensure GitHub Copilot is set up in VS Code with MCP support enabled
For detailed information about MCP server setup in VS Code, see the official VS Code MCP documentation.
Local Setup
-
Clone and build the MCP server:
git clone <your-repo-url> cd foundry-mcp-server npm install npm run build -
Configure VS Code settings:
Open your VS Code settings (Command Palette → "Preferences: Open User Settings (JSON)") and add the MCP server configuration:
{ "github.copilot.chat.mcp.servers": { "foundry": { "command": "node", "args": ["/absolute/path/to/foundry-mcp-server/dist/server.js"], "env": { "FOUNDRY_PRIVATE_KEY": "0x_your_private_key_here_optional", "PROJECT_ROOT": "/path/to/your/foundry/project" } } } }Important: Replace
/absolute/path/to/foundry-mcp-serverwith the actual absolute path to where you cloned this repository. -
Restart VS Code to load the MCP server
-
Verify the setup:
- Open GitHub Copilot Chat in VS Code
- You should see the Foundry MCP server listed as connected
- Try using tools like
foundry_project_infoto test the connection
Alternative Setup with npm link
If you prefer to install globally:
cd foundry-mcp-server
npm run build
npm link
Then in your VS Code settings, use:
{
"github.copilot.chat.mcp.servers": {
"foundry": {
"command": "foundry-mcp-server",
"env": {
"FOUNDRY_PRIVATE_KEY": "0x_your_private_key_here_optional",
"PROJECT_ROOT": "/path/to/your/foundry/project"
}
}
}
}
Development Setup
For development and testing:
-
Run in development mode:
npm run dev -
Watch for changes (if you modify the code):
npm run build # Restart VS Code to reload the MCP server
Environment Variables
FOUNDRY_PRIVATE_KEY
Set this environment variable to provide a default private key for Cast operations that require transaction signing:
export FOUNDRY_PRIVATE_KEY="0x your_private_key_here"
When this environment variable is set:
cast_sendoperations will automatically use this key if no explicitprivateKeyparameter is provided- You can check the wallet address associated with this key using the
cast_wallet_infotool
PROJECT_ROOT
Override the default project root directory:
export PROJECT_ROOT="/path/to/your/foundry/project"
If not set, defaults to the current working directory.
Tools
Forge Tools
forge_build- Compile contractsforge_test- Run testsforge_gas_report- Generate detailed gas usage reports with min/avg/median/max costsforge_gas_snapshot- Create, compare, and manage gas snapshots for regression testingforge_gas_optimize- Analyze gas patterns and provide optimization suggestions
Anvil Tools
anvil_start- Start local blockchainanvil_stop- Stop local blockchainanvil_status- Check if Anvil is running
Cast Tools
cast_call- Call read-only contract functionscast_send- Send transactions (uses FOUNDRY_PRIVATE_KEY if no key provided)cast_estimate_gas- Estimate gas for transactionscast_balance- Get address balancecast_wallet_info- Get wallet info for configured private key
Project Tools
foundry_project_info- Get project directory structure
Template Tools
generate_contract_prompt- Generate structured prompts for AI tools following Foundry best practicesfoundry_project_template- Generate complete Foundry project structure with configuration
Gas Analysis Tools
gas_profile_function- Profile specific function gas usage with targeted analysisgas_compare_implementations- Compare gas costs between different implementationsgas_regression_test- Monitor for gas usage regressions against baselinesgas_optimization_suggestions- Get specific optimization recommendations
Creating Smart Contracts with AI
This MCP server includes specialized tools for generating smart contracts using AI tools like ChatGPT or Claude, following Foundry's official prompting guidelines.
Workflow:
-
Generate a structured prompt:
Use the generate_contract_prompt tool with your requirements: - Requirements: "Create an ERC20 token with minting and burning capabilities" - Contract type: "token" - Include comprehensive tests and deployment scripts -
Copy the generated prompt to your AI tool of choice (ChatGPT, Claude, etc.)
-
Get AI-generated code that follows Foundry best practices including:
- Proper project structure
- Comprehensive testing (unit, fuzz, invariant)
- Security best practices
- Deployment scripts with verification
- NatSpec documentation
-
Generate project structure using
foundry_project_templatefor a complete boilerplate
Supported Contract Types:
- Token: ERC20 implementations with advanced features
- Vault: ERC4626 compliant vaults with yield mechanisms
- DeFi: DEX, lending, and other DeFi protocols
- NFT: ERC721/ERC1155 implementations
- Governance: Voting and proposal mechanisms
- Proxy: Upgradeable contract patterns
- Custom: Any other contract type
Gas Optimization Workflow
This MCP server provides comprehensive gas analysis and optimization tools based on Foundry's gas tracking capabilities.
Gas Analysis Pipeline:
-
Generate baseline reports:
Use forge_gas_report to get detailed function-level gas usage Use forge_gas_snapshot with action="create" to establish baselines -
Profile specific functions:
Use gas_profile_function for targeted analysis of expensive functions Compare different implementation approaches with gas_compare_implementations -
Monitor for regressions:
Use gas_regression_test to detect gas increases during development Set up automated testing with configurable thresholds -
Get optimization guidance:
Use gas_optimization_suggestions for targeted improvement recommendations Focus on specific areas: deployment, functions, loops, storage, external_calls
Optimization Strategies Supported:
- Function-level Analysis: Min/avg/median/max gas costs per function
- Snapshot Comparisons: Track gas usage changes over time
- Implementation Testing: A/B test different coding approaches
- Regression Detection: Automated monitoring with configurable thresholds
- Targeted Recommendations: Focus on deployment, loops, storage, or external calls
Example Gas Optimization Workflow:
# 1. Establish baseline
forge_gas_snapshot action="create" snapshotFile=".gas-baseline"
# 2. Get detailed function analysis
forge_gas_report matchContract="MyContract"
# 3. Profile expensive functions
gas_profile_function contractName="MyContract" functionName="expensiveFunction"
# 4. Test optimization
# ... make code changes ...
# 5. Check for regressions
gas_regression_test baselineSnapshot=".gas-baseline" threshold=5
# 6. Compare implementations
gas_compare_implementations implementationTests=["testOriginal", "testOptimized"]
Security
⚠️ Important: Never commit private keys to version control. Always use environment variables or secure key management solutions.
Troubleshooting
Common Issues
-
MCP Server not connecting:
- Ensure the path in VS Code settings is absolute and correct
- Check that the build was successful (
npm run build) - Restart VS Code after configuration changes
-
Foundry commands not working:
- Verify Foundry is installed:
forge --version - Make sure you're in a Foundry project directory or set
PROJECT_ROOT
- Verify Foundry is installed:
-
Private key not working:
- Ensure the private key format is correct (starts with
0x) - Test with
cast_wallet_infoto verify the key is valid
- Ensure the private key format is correct (starts with
-
Permission denied errors:
- Ensure the MCP server script is executable
- Check file permissions on the repository directory
Debug Mode
To see detailed logs, you can run the MCP server directly:
cd foundry-mcp-server
node dist/server.js
This will show any startup errors or connection issues.