Claude-salesforce-mcp-server

AmanNadaf/Claude-salesforce-mcp-server

3.1

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 reporting
  • check_test_status_and_coverage - Get coverage with failure details
  • get_current_org_coverage - Organization-wide coverage analysis

Data Query Tools (3)

  • salesforce_query - Execute SOQL queries with smart normalization
  • query_tooling_api_direct - Direct Tooling API access for metadata
  • salesforce_connection_test - Test and validate connection

Data Manipulation Tools (2)

  • get_object_required_fields - Get required fields for validation
  • create_records_with_validation - Create records with comprehensive validation

Metadata Management Tools (6)

  • create_custom_object - Create custom objects with standard fields
  • create_custom_field - Add custom fields to objects
  • update_custom_object - Modify object properties
  • update_custom_field - Modify field properties
  • delete_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 data
  • salesforce_bulk_update_simple - Bulk update from CSV data
  • salesforce_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 from COUNT 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:

  1. ๐Ÿš€ ApexTestQueueItem (Primary) - Direct queue-based execution
  2. ๐Ÿ”ง Tooling API Enhanced - Advanced API with proper payloads
  3. ๐Ÿ“Š Analysis Mode - Information gathering when execution unavailable

Comprehensive Coverage Retrieval

Multiple data sources ensure complete coverage information:

  1. ๐ŸŽฏ Job-Specific Coverage - Tooling API with AsyncApexJobId
  2. ๐Ÿ“ˆ Aggregate Coverage - ApexCodeCoverageAggregate queries
  3. ๐Ÿ” Detailed Coverage - ApexCodeCoverage with method-level data
  4. โฐ Recent Coverage - Time-based coverage queries

๐Ÿ“Š Configuration Options

Environment Variables

VariableDescriptionRequiredDefault
SALESFORCE_USERNAMESalesforce usernameโœ…-
SALESFORCE_PASSWORDSalesforce passwordโœ…-
SALESFORCE_SECURITY_TOKENSalesforce security tokenโœ…-
SALESFORCE_INSTANCE_URLCustom 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

  1. Tests not found - Verify class names are exact matches
  2. Permission errors - Ensure user has test execution permissions
  3. Timeout issues - Check org performance and test complexity
  4. Coverage missing - Verify code coverage is enabled in org

Authentication Troubleshooting

  1. Invalid credentials - Check username, password, and token
  2. Security token issues - Reset token if IP restrictions changed
  3. Instance URL problems - Verify custom domain configuration
  4. API version compatibility - Update to latest supported version

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Add comprehensive tests for new functionality
  4. Ensure all tests pass and coverage is maintained
  5. Update documentation with examples
  6. 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. Screenshot 2025-08-05 at 12 43 22โ€ฏAM Screenshot 2025-08-05 at 12 43 31โ€ฏAM