🚀 Metabase AI Assistant 🤖
AI-powered assistant that directly connects to Metabase and PostgreSQL databases via the Model Context Protocol (MCP) for Claude Desktop and Claude Code. It can create models, SQL queries, metrics, and dashboards using both the Metabase API and direct database connections.
🚀 MCP Server for Claude Desktop & Claude Code - Metabase + Direct DB Access
⭐ If you find this project useful, please give it a star! ⭐

🚀 Quick Start
To get started with the Metabase AI Assistant, follow the steps below:
- Installation: Clone the repository and install the necessary dependencies.
- Configuration: Edit the
.env file with your Metabase and API credentials.
- Integration: Set up the integration with Claude Desktop or Claude Code.
- Usage: Start using the assistant through the interactive CLI or programmatically.
✨ Features
🔌 MCP Integration (Claude Desktop & Claude Code)
- Model Context Protocol: Native integration with Claude Desktop and Claude Code.
- Direct Database Access: Direct connections to PostgreSQL databases.
- Metabase API Integration: Full integration with Metabase instances.
- Schema Discovery: Automatic discovery and analysis of database schemas.
- Relationship Detection: Detection and suggestions for table relationships.
🤖 AI-Powered Features
- Natural Language SQL: Generate SQL queries from natural language descriptions.
- Smart Model Building: AI-assisted creation of Metabase models.
- Intelligent Dashboards: Automatic dashboard layout and widget suggestions.
- Query Optimization: Optimization of SQL query performance.
- Data Insights: Data analysis and pattern detection.
🛠️ Developer Tools
- DDL Operations: Safe creation of tables, views, and indexes (prefix-protected).
- Batch Operations: Bulk data processing operations.
- Connection Management: Hybrid connection management (API + Direct).
- Security Controls: AI object prefix control and approval workflows.
- Performance Monitoring: Operation timing and timeout controls.
📦 Installation
git clone https://github.com/onmartech/metabase-ai-assistant.git
cd metabase-ai-assistant
npm install
cp .env.example .env
⚙️ Configuration
Edit the .env file as follows:
# Metabase Configuration
METABASE_URL=http://your-metabase-instance.com
METABASE_USERNAME=your_username
METABASE_PASSWORD=your_password
METABASE_API_KEY=your_metabase_api_key
# AI Provider (at least one required)
ANTHROPIC_API_KEY=your_anthropic_key
# or
OPENAI_API_KEY=your_openai_key
# Application Settings
LOG_LEVEL=info
⚠️ Important Note
Never commit the .env file to version control. This file is already included in .gitignore.
💻 Usage Examples
Interactive CLI
npm start
Programmatic Usage
import { MetabaseClient } from './src/metabase/client.js';
import { MetabaseAIAssistant } from './src/ai/assistant.js';
const client = new MetabaseClient({
url: 'http://your-metabase.com',
username: 'user',
password: 'pass'
});
const assistant = new MetabaseAIAssistant({
metabaseClient: client,
aiProvider: 'anthropic',
anthropicApiKey: 'your-key'
});
const model = await assistant.createModel(
'Customer segmentation model',
databaseId
);
const sql = await assistant.generateSQL(
'Total sales in the last 30 days',
schema
);
📚 Documentation
📋 Requirements
🖥️ System
- Node.js 18+
- Claude Desktop (for MCP support) OR Claude Code
- PostgreSQL Database (for direct connections)
🔗 Services
- Metabase instance (v0.48+)
- Anthropic API (included in Claude Desktop/Code)
🔌 Claude Desktop & Claude Code Integration (MCP)
For Claude Desktop
- Edit the
~/Library/Application Support/Claude/claude_desktop_config.json file:
{
"mcpServers": {
"metabase-ai-assistant": {
"command": "node",
"args": ["/path/to/your/metabase-ai-assistant/src/mcp/server.js"],
"env": {
"METABASE_URL": "http://your-metabase-instance.com",
"METABASE_USERNAME": "your_username",
"METABASE_PASSWORD": "your_password",
"ANTHROPIC_API_KEY": "your_anthropic_key"
}
}
}
}
- Restart Claude Desktop, and the MCP tools will be available.
For Claude Code
- Global Installation
npm link
which metabase-ai-mcp
npm list -g | grep metabase-ai-assistant
- Environment Setup
Ensure your
.env file is properly configured with your Metabase credentials:
METABASE_URL=http://your-metabase-instance.com
METABASE_USERNAME=your_username
METABASE_PASSWORD=your_password
METABASE_API_KEY=your_api_key
ANTHROPIC_API_KEY=your_anthropic_key
- Test MCP Server
node src/mcp/server.js
export METABASE_URL="http://your-instance.com"
export METABASE_USERNAME="your_username"
export METABASE_PASSWORD="your_password"
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' | node src/mcp/server.js
- Verify Integration
In Claude Code, ask: "What MCP tools do you have available?"
You should see 27 Metabase AI Assistant tools available:
📊 Database Tools:
db_list - List all Metabase databases
db_schemas - Get schema information
db_tables - List tables with details
sql_execute - Run SQL queries
🎯 Metabase Tools:
mb_question_create - Create questions/charts
mb_dashboard_create - Create dashboards
mb_dashboard_template_executive - Auto-generate executive dashboards
mb_question_create_parametric - Create parametric questions
🔍 AI-Powered Tools:
ai_sql_generate - Generate SQL from natural language
ai_sql_optimize - Optimize SQL performance
ai_sql_explain - Explain SQL queries
📚 Documentation Tools:
web_explore_metabase_docs - Crawl Metabase documentation
web_search_metabase_docs - Search documentation
The server provides comprehensive Metabase and PostgreSQL integration with 27 tools for:
- Database schema exploration and analysis
- Natural language SQL query generation and optimization
- Executive dashboard templates and parametric questions
- Direct DDL operations with security controls
- Metabase documentation crawling and search
- Table relationship detection and mapping
🛠️ CLI Komutları
The following commands are available in the interactive CLI:
- 📊 Create Model: Create a model with AI assistance.
- ❓ Create Question: Create an SQL query.
- 📈 Create Metric: Define a metric.
- 📋 Create Dashboard: Prepare a dashboard.
- 🔍 Explore Schema: Explore the database schema.
- 🚀 Execute SQL: Run an SQL query.
- 🔧 Optimize Query: Optimize a query.
- 💡 AI Query Builder: Create a query in natural language.
📂 Proje Yapısı
metabase-ai-assistant/
├── src/
│ ├── mcp/
│ │ └── server.js # MCP Server (Claude Desktop integration)
│ ├── metabase/
│ │ └── client.js # Metabase API client
│ ├── database/
│ │ ├── direct-client.js # Direct PostgreSQL client
│ │ └── connection-manager.js # Hybrid connection manager
│ ├── ai/
│ │ └── assistant.js # AI helper functions
│ ├── cli/
│ │ └── interactive.js # Interactive CLI (standalone)
│ ├── utils/
│ │ └── logger.js # Logging utilities
│ └── index.js # Main entry point (CLI mode)
├── tests/ # Test files
├── .env.example # Environment template
├── package.json
└── README.md
🔍 API Referansı
MetabaseClient
getDatabases()
getDatabase(id)
getDatabaseSchemas(databaseId)
getDatabaseTables(databaseId)
getModels()
createModel(modelData)
getQuestions(collectionId)
createQuestion(questionData)
executeNativeQuery(databaseId, sql)
getMetrics()
createMetric(metricData)
getDashboards()
createDashboard(dashboardData)
addCardToDashboard(dashboardId, cardId, options)
MetabaseAIAssistant
analyzeRequest(userRequest)
generateSQL(description, schema)
suggestVisualization(data, questionType)
optimizeQuery(sql)
explainQuery(sql)
createModel(description, databaseId)
createQuestion(description, databaseId, collectionId)
createMetric(description, tableId)
createDashboard(description, questions)
🧪 Test
npm test
npm run test:connection
npm run test:coverage
🔧 Technical Details
🔒 Security
Data Security
- Environment Variables: All sensitive data (API keys, passwords) are stored in the
.env file.
- Git Ignore: The
.env file is excluded from version control.
- SQL Injection Protection: Parameterized queries and input validation are used.
- Rate Limiting: API request rate limiting is applied.
- Audit Logging: All database operations are logged for security monitoring.
- No Hardcoded Credentials: A security-first approach prevents credential exposure.
Database Security
- AI Object Prefix: All AI-created objects are marked with the
claude_ai_ prefix for safety.
- Schema Isolation: Operations are limited to specified schemas only.
- Read-Only Mode: Default read-only permissions with explicit approval for modifications.
- DDL Approval System: Database changes require explicit confirmation.
- Prefix Validation: Only AI-prefixed objects can be modified or deleted.
MCP Security
- Secure Transport: MCP communication is over secure channels.
- Environment Isolation: Credentials are passed via environment variables.
- Tool Validation: All tool inputs are validated before execution.
- Error Handling: Sensitive information is filtered from error messages.
Production Deployment
- Use environment-specific configuration files.
- Prefer SSL/TLS connections for all database communications.
- Grant minimum required permissions to database users.
- Protect API endpoints with authentication and authorization.
- Regularly rotate API keys and database passwords.
- Monitor and log all tool usage for security auditing.
🐛 Troubleshooting
Connection Errors
- Verify that the Metabase URL is accessible.
- Ensure that the API key and credentials are valid.
- Check network connectivity and firewall settings.
- Confirm that the environment variables are properly set.
MCP Integration Issues
- Ensure that
npm link was run successfully.
- Verify that the MCP server binary is in the PATH:
which metabase-ai-mcp.
- Check that the environment variables are exported:
echo $METABASE_URL.
- Test the MCP server directly:
node src/mcp/server.js.
- Restart Claude Code after global installation.
Query Errors
- Validate SQL syntax and formatting.
- Verify that table and column names exist.
- Check database permissions and schema access.
- Ensure proper schema selection for operations.
Security Warnings
- Never commit
.env files to version control.
- Avoid hardcoding credentials in source code.
- Use prefix validation for AI-created objects.
- Monitor database operations for security compliance.
🚀 Production Deployment
Option 1: PM2 Process Manager (Recommended)
npm install -g pm2
npm run pm2:start
npm run pm2:logs
npm run pm2:restart
npm run pm2:stop
pm2 startup
pm2 save
Option 2: Docker Container
npm run docker:run
npm run docker:logs
npm run docker:stop
Option 3: Cloud Deployment
- Railway: One-click deploy with
railway.json.
- Heroku: Deploy with the Heroku CLI (see
deploy/heroku-deploy.md).
- DigitalOcean: App Platform with Docker.
- AWS: ECS Fargate or EC2 with a systemd service.
Option 4: Systemd Service (Linux)
sudo cp metabase-ai-mcp.service /etc/systemd/system/
sudo systemctl enable metabase-ai-mcp
sudo systemctl start metabase-ai-mcp
sudo systemctl status metabase-ai-mcp
sudo journalctl -u metabase-ai-mcp -f
Production Scripts
npm run mcp:prod
npm run test:connection
npm run lint
📈 Roadmap
- [ ] Improve Natural Language Processing.
- [ ] Develop a visual query builder.
- [ ] Implement an automatic dashboard recommendation system.
- [ ] Support multi-database environments.
- [ ] Enable real-time data streaming.
- [ ] Develop advanced ML models.
🤝 Contributing
If you like this project and want to contribute to its development:
⭐ Support the Project
- Star on GitHub: If you find the project useful, give it a ⭐ star.
- Follow: Follow the @onmartech account to stay updated on changes.
- Share: Share it on social media and recommend it to your friends.
🔧 Contribute to Development
- Fork the repository.
- Create a Feature branch (
git checkout -b feature/new-feature).
- Commit your changes (
git commit -m 'feat: Added a new feature').
- Push your changes (
git push origin feature/new-feature).
- Open a Pull Request.
💡 Contribution Ideas
- Integrate new AI models.
- Create dashboard templates.
- Develop Metabase connectors.
- Improve documentation.
- Fix bugs and optimize performance.
📋 Contribution Rules
- Write tests for code changes.
- Use Conventional Commits for commit messages.
- Follow ESLint and Prettier settings.
- Document your changes.
📄 License
This project is licensed under the MIT License. See the LICENSE file for details.
Copyright (c) 2024 ONMARTECH LLC
👥 Support and Contact
🐛 Bug Reports & Feature Requests
- GitHub Issues: Use the Issues page.
- Bug Template: Use the templates when opening an issue.
- Feature Requests: Describe the features you want in detail.
💬 Community
- GitHub Discussions: For Q&A and ideas.
- Documentation: Contribute to the Wiki pages.
- Examples: Share example use cases.
🚀 Commercial Support
Professional support and customization services are available from ONMARTECH LLC.
🏆 Contributors
Thanks to everyone who made this project possible:
- ONMARTECH LLC - Project development and maintenance.
- Metabase Team - An excellent platform.
- Open Source Community - Continuous inspiration and feedback.
🌟 Hall of Fame
Developers who have made significant contributions will be listed here.
If you find this project useful, don't forget to give it a ⭐ star and 🔄 share it!