AmanNadaf/Claude-salesforce-mcp-server
If you are the rightful owner of Claude-salesforce-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 henry@mcphub.com.
Custom Python MCP server bridges Claude AI with Salesforce APIs, enabling natural language queries, automated data management, and intelligent sales insights.
Salesforce MCP Server with Enhanced Test Execution
A production-ready Salesforce MCP (Model Context Protocol) server featuring comprehensive test execution with detailed failure reporting, intelligent authentication, and complete Salesforce API coverage for universal LLM integration.
โจ Key Features
๐งช Enhanced Test Execution & Coverage
- Detailed Failure Reporting - Line numbers, stack traces, and error context
- Comprehensive Coverage Analysis - Org-wide and class-specific coverage metrics
- Smart Test Monitoring - Automatic status detection and result retrieval
- Multiple Execution Methods - Tooling API, REST API, and queue-based approaches
๐ Intelligent Authentication
- Simple-Salesforce Backend - Reliable, battle-tested Salesforce client
- Flexible Credential Management - Environment variables with secure token handling
- Connection Retry Logic - Automatic reconnection with exponential backoff
- Session Management - Persistent connections with validation
๐ Comprehensive Salesforce API Coverage
- SOQL/SOSL Queries - Full query capabilities with smart normalization
- DML Operations - Create, Read, Update, Delete with validation
- Metadata Management - Custom objects and fields creation/modification
- Bulk Operations - High-performance CSV-based bulk processing
- Test Execution - Complete Apex test lifecycle management
๐ Quick Start
1. Install Dependencies
pip3 install simple-salesforce python-dotenv requests
2. Configure Authentication
Create a .env
file with your Salesforce configuration:
SALESFORCE_USERNAME=your_username@company.com
SALESFORCE_PASSWORD=your_password
SALESFORCE_SECURITY_TOKEN=your_security_token
SALESFORCE_INSTANCE_URL=https://your-domain.my.salesforce.com # Optional
3. Run the Server
# Start MCP server
python3 salesforce_mcp_server.py
# Or run as module
python3 -m salesforce_mcp_server
4. Test the Setup
Test basic connectivity:
# Test connection
from salesforce_mcp_server import test_connection
result = test_connection()
print(result['message'])
Overview
python3 -m pip install --user --upgrade pip
python3 -m pip install --user requests simple-salesforce python-dotenv
export PATH="$HOME/Library/Python/$(python3 -c 'import sys;print(f\"{sys.version_info.major}.{sys.version_info.minor}\")')/bin:$PATH"
python3 /Users/amnadaf/salesforce-mcp-server/server.py
๐งช Enhanced Test Execution Features
Detailed Failure Reporting
When tests fail, get comprehensive diagnostic information:
๐งช **Apex Test Execution Complete**
๐ **Summary:**
โข Total Tests: 2
โข โ
Passed: 0
โข โ Failed: 2
โข Success Rate: 0.0%
โข Job ID: 707gL00000BEzFbQAL
โ **Failed Tests (Detailed):**
**1. ContactManagerTest.testSyncMailingAddress_NoAccountFail**
๐ **Line:** 17
โฑ๏ธ **Runtime:** 150ms
๐จ **Error:** System.DmlException: Insert failed. FIELD_INTEGRITY_EXCEPTION,
There's a problem with this country: [BillingCountry]
๐ **Stack Trace:**
Class.ContactManagerTest.makeData: line 17, column 1
**2. ContactManagerTest.testSyncMailingAddress_Success**
๐ **Line:** 17
๐จ **Error:** System.DmlException: Insert failed. FIELD_INTEGRITY_EXCEPTION,
There's a problem with this country: [BillingCountry]
๐ **Stack Trace:**
Class.ContactManagerTest.makeData: line 17, column 1
๐ **Code Coverage Details:**
๐ข AccountManager: 100.0% (7/7 lines)
๐ด ContactManager: 0.0% (0/14 lines)
๐ก **Recommendations:**
โข Review failed test details above
โข Check the specific line numbers where failures occurred
โข Fix the underlying code issues causing test failures
โข Re-run tests after making corrections
Smart Coverage Integration
Check coverage with automatic failure detection:
# After running tests, check coverage to see detailed results
check_test_status_and_coverage(class_names=['ContactManagerTest'])
๐ ๏ธ Available Tools (15 Total)
Test Execution Tools (3)
run_apex_tests_comprehensive
- Run tests with detailed failure reportingcheck_test_status_and_coverage
- Get coverage with failure detailsget_current_org_coverage
- Organization-wide coverage analysis
Data Query Tools (3)
salesforce_query
- Execute SOQL queries with smart normalizationquery_tooling_api_direct
- Direct Tooling API access for metadatasalesforce_connection_test
- Test and validate connection
Data Manipulation Tools (2)
get_object_required_fields
- Get required fields for validationcreate_records_with_validation
- Create records with comprehensive validation
Metadata Management Tools (6)
create_custom_object
- Create custom objects with standard fieldscreate_custom_field
- Add custom fields to objectsupdate_custom_object
- Modify object propertiesupdate_custom_field
- Modify field propertiesdelete_custom_object
- Remove custom objects (with warning)delete_custom_field
- Remove custom fields (with warning)
Bulk Operations Tools (2)
salesforce_bulk_insert_simple
- Bulk insert from CSV datasalesforce_bulk_update_simple
- Bulk update from CSV datasalesforce_describe_object
- Get detailed object metadata
๐ Comprehensive Test Execution Example
1. Run Tests with Enhanced Reporting
# Run specific test classes
run_apex_tests_comprehensive(
class_names=['ContactManagerTest', 'AccountManagerTest'],
test_level='RunSpecifiedTests',
code_coverage=True,
verbose=True
)
Output:
โ
Successfully enqueued 2 test classes!
๐ **Enqueued Tests:**
โข ContactManagerTest (Queue ID: 709gL000003EcbdQAC)
โข AccountManagerTest (Queue ID: 709gL000003EcbeQAC)
๐ก **Monitor Progress:** Check Setup โ Apex Test Execution
โณ **Note:** Tests are now running. Use 'check coverage' to see results once complete.
2. Check Results with Detailed Failures
# Get comprehensive results including failures and coverage
check_test_status_and_coverage(class_names=['ContactManagerTest'])
Output includes:
- โ Test execution summary with pass/fail counts
- ๐จ Detailed failure analysis with line numbers and stack traces
- ๐ Code coverage metrics with class-by-class breakdown
- ๐ก Actionable recommendations for fixing issues
3. Organization-Wide Coverage Analysis
# Get org-wide coverage without running tests
get_current_org_coverage()
Output:
๐ **Current Org Code Coverage**
๐ **Overall Statistics:**
โข Total Classes: 127
โข Overall Coverage: 82.3%
โข Total Lines: 15,847
โข Covered Lines: 13,042
โข Uncovered Lines: 2,805
๐ข **High Coverage (โฅ85%):** 89 classes
๐ข AccountManager: 100.0% (156/156 lines)
๐ข ContactProcessor: 94.2% (243/258 lines)
๐ด **Low Coverage (<75%):** 12 classes
๐ด ContactManager: 0.0% (0/14 lines)
๐ด DataHelper: 45.2% (67/148 lines)
๐ง Smart Features
Query Normalization
Automatically fixes common SOQL issues:
- โ
COUNT()
โCOUNT(Id)
for better compatibility - โ
Removes
LIMIT
fromCOUNT
queries (not supported) - โ Handles environment variable substitution
Intelligent Error Handling
- ๐ Connection retry with exponential backoff
- ๐ Detailed error messages with context and suggestions
- ๐ก๏ธ Safe credential logging (masked sensitive data)
- โก Graceful fallbacks across multiple API approaches
Comprehensive Validation
Before creating records, validates:
- โ Required fields are provided
- โ Data types match field definitions
- โ Picklist values are valid options
- โ Field lengths don't exceed limits
- โ Format requirements (dates, emails, etc.)
๐๏ธ Architecture
Clean Modular Design
salesforce_mcp_server.py
โโโ ๐ Authentication & Connection Management
โ โโโ initialize_salesforce() # Smart connection with retry
โ โโโ ensure_connection() # Connection validation
โ โโโ test_connection() # Connection diagnostics
โ
โโโ ๐งช Enhanced Test Execution Engine
โ โโโ run_apex_tests_comprehensive() # Multi-method test execution
โ โโโ check_test_status_and_coverage() # Results with failure details
โ โโโ get_test_results_for_classes() # Detailed result retrieval
โ โโโ parse_line_number_from_stack_trace() # Error analysis
โ
โโโ ๐ Coverage Analysis System
โ โโโ get_comprehensive_coverage_data() # Multi-source coverage
โ โโโ get_current_org_coverage() # Org-wide analysis
โ โโโ format_comprehensive_test_results() # Rich formatting
โ
โโโ ๐ Data Management Tools
โ โโโ salesforce_query() # Smart SOQL execution
โ โโโ create_records_with_validation() # Validated record creation
โ โโโ get_object_required_fields() # Field requirement analysis
โ โโโ bulk operations # CSV-based bulk processing
โ
โโโ ๐๏ธ Metadata Management
โ โโโ create_custom_object() # Object creation with standards
โ โโโ create_custom_field() # Field creation with validation
โ โโโ describe_object() # Detailed metadata retrieval
โ
โโโ ๐ง MCP Protocol Integration
โโโ do_list_tools() # Tool discovery and registration
โโโ do_call_tool() # Tool execution with error handling
โโโ main() # MCP server event loop
Multi-Method Test Execution
Intelligent fallback system for maximum compatibility:
- ๐ ApexTestQueueItem (Primary) - Direct queue-based execution
- ๐ง Tooling API Enhanced - Advanced API with proper payloads
- ๐ Analysis Mode - Information gathering when execution unavailable
Comprehensive Coverage Retrieval
Multiple data sources ensure complete coverage information:
- ๐ฏ Job-Specific Coverage - Tooling API with AsyncApexJobId
- ๐ Aggregate Coverage - ApexCodeCoverageAggregate queries
- ๐ Detailed Coverage - ApexCodeCoverage with method-level data
- โฐ Recent Coverage - Time-based coverage queries
๐ Configuration Options
Environment Variables
Variable | Description | Required | Default |
---|---|---|---|
SALESFORCE_USERNAME | Salesforce username | โ | - |
SALESFORCE_PASSWORD | Salesforce password | โ | - |
SALESFORCE_SECURITY_TOKEN | Salesforce security token | โ | - |
SALESFORCE_INSTANCE_URL | Custom instance URL | โ | Auto-detected |
Test Execution Options
run_apex_tests_comprehensive(
class_names=['TestClass1', 'TestClass2'], # Specific classes
test_level='RunSpecifiedTests', # Test scope
async_execution=False, # Wait for completion
code_coverage=True, # Include coverage
verbose=True # Detailed output
)
Coverage Analysis Options
check_test_status_and_coverage(
class_names=['MyTestClass'] # Optional: specific classes
)
get_current_org_coverage() # Org-wide analysis
๐งช Testing & Validation
Connection Testing
# Test basic connectivity
python3 -c "
from salesforce_mcp_server import test_connection
result = test_connection()
print(f'Status: {result[\"status\"]}')
print(f'Message: {result[\"message\"]}')
"
Query Testing
# Test SOQL execution
python3 -c "
from salesforce_mcp_server import do_call_tool
result = do_call_tool({
'name': 'salesforce_query',
'arguments': {'query': 'SELECT COUNT(Id) FROM Account'}
})
print(result)
"
Test Execution Validation
# Run and check a test class
python3 -c "
from salesforce_mcp_server import run_apex_tests_comprehensive, check_test_status_and_coverage
import time
# Run tests
result = run_apex_tests_comprehensive(class_names=['MyTestClass'])
print('Test Execution:', result['message'])
# Wait and check results
time.sleep(30)
coverage = check_test_status_and_coverage(class_names=['MyTestClass'])
print('Coverage Results:', coverage['message'])
"
๐ MCP Client Integration
Claude Desktop Configuration
Add to your MCP settings file:
{
"mcpServers": {
"salesforce": {
"command": "python3",
"args": ["salesforce_mcp_server.py"],
"cwd": "/path/to/your/salesforce-mcp-server",
"env": {
"SALESFORCE_USERNAME": "your_username@company.com",
"SALESFORCE_PASSWORD": "your_password",
"SALESFORCE_SECURITY_TOKEN": "your_token"
}
}
}
}
Usage in Claude Desktop
"Run tests for ContactManagerTest and show me detailed failure information"
"Check the code coverage for my org and tell me which classes need improvement"
"Create a new custom object called ProjectTracker with fields for Name, Status, and Due Date"
"Query all Accounts created this month and show me the first 10 results"
๐ Security Features
Credential Protection
- โ Masked logging - Sensitive data never appears in logs
- โ
Environment isolation - Credentials stored in
.env
files - โ Connection validation - Immediate feedback on auth issues
- โ Session management - Automatic token refresh and retry
Error Handling
- ๐ก๏ธ Safe error messages - No credential exposure in errors
- ๐ Detailed diagnostics - Rich context without sensitive data
- ๐ Automatic retry - Intelligent reconnection on auth failures
- โก Graceful degradation - Fallbacks when features unavailable
๐ Performance Optimizations
Smart Connection Management
- ๐ Connection reuse - Persistent sessions across operations
- โก Lazy initialization - Connect only when needed
- ๐ง Connection validation - Quick health checks before operations
- ๐ Automatic retry - Intelligent reconnection strategies
Efficient Test Execution
- ๐ฏ Targeted queries - Job-specific result retrieval
- ๐ Parallel coverage - Multiple coverage data sources
- ๐ Queue optimization - Efficient ApexTestQueueItem usage
- ๐พ Result caching - Avoid redundant API calls
Optimized Bulk Operations
- ๐ฆ Batch processing - Configurable batch sizes
- ๐ CSV streaming - Memory-efficient data processing
- โก Bulk API usage - High-performance simple-salesforce bulk
- ๐ Progress tracking - Real-time operation monitoring
๐ Troubleshooting
Common Connection Issues
# Test connection with detailed logging
PYTHONPATH=. python3 -c "
import logging
logging.basicConfig(level=logging.DEBUG)
from salesforce_mcp_server import test_connection
result = test_connection()
print(result)
"
Test Execution Problems
- Tests not found - Verify class names are exact matches
- Permission errors - Ensure user has test execution permissions
- Timeout issues - Check org performance and test complexity
- Coverage missing - Verify code coverage is enabled in org
Authentication Troubleshooting
- Invalid credentials - Check username, password, and token
- Security token issues - Reset token if IP restrictions changed
- Instance URL problems - Verify custom domain configuration
- API version compatibility - Update to latest supported version
๐ค Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Add comprehensive tests for new functionality
- Ensure all tests pass and coverage is maintained
- Update documentation with examples
- Submit a pull request with detailed description
Development Setup
# Clone and setup
git clone https://github.com/your-username/salesforce-mcp-server
cd salesforce-mcp-server
# Install dependencies
pip3 install -r requirements.txt
# Setup environment
cp .env.example .env
# Edit .env with your credentials
# Run tests
python3 -m pytest tests/ -v
# Test MCP integration
python3 salesforce_mcp_server.py
๐ License
This project is licensed under the MIT License - see the file for details.
๐ Recent Updates
Latest Features (Production Ready)
๐งช Enhanced Test Execution Engine
- Line Number Extraction - Precise error location from stack traces
- Detailed Error Context - Full error messages with truncation handling
- Smart Job Detection - Automatic recent job ID discovery
- Multi-Method Execution - Fallback strategies for maximum compatibility
๐ Advanced Coverage Analysis
- Comprehensive Data Sources - Tooling API + Regular API coverage
- Class-Level Breakdown - Individual class coverage with insights
- Method-Level Details - Test method coverage when available
- Org-Wide Analytics - Complete organization coverage analysis
๐ง Improved Tool Architecture
- Enhanced Error Handling - Better error messages with context
- Smart Query Normalization - Automatic SOQL fixes and improvements
- Comprehensive Validation - Pre-creation field validation with helpful guidance
- Flexible Authentication - Multiple connection strategies with retry logic
๐ Performance & Reliability
- Connection Optimization - Smart connection reuse and validation
- Robust Error Recovery - Automatic retry with exponential backoff
- Memory Efficiency - Optimized bulk operations and data processing
- Production Hardening - Comprehensive logging and monitoring
โญ Star this repository if it helps you integrate Salesforce with your LLM workflows!
Claude-salesforce-mcp-server
Custom Python MCP server bridges Claude AI with Salesforce APIs, enabling natural language queries, automated data management, and intelligent sales insights. Claude processes SOQL queries conversationally while the server handles bulk operations, custom objects, and real-time sync. Delivers 75% faster data processing and AI-powered CRM automation.