The complete Model Context Protocol (MCP) server for Salesforce development Deploy metadata, run SOQL, manage multiple orgs, and automate everything - all through Claude Desktop.
Created by Sameer | Report Issues | Complete Guide
Transform Claude Desktop into a powerful Salesforce IDE with 60 optimized tools for metadata management, testing, multi-org operations, and more. No manual API calls, no context switching - just natural language commands.
NEW v2.0: Tool consolidation reduces 106 tools β 57 tools (46% reduction) for better LLM performance!
NEW v2.1: Added comprehensive debugging tool - diagnose and fix any Salesforce defect!
NEW v2.2: Added analyze_field_usage - comprehensive field usage analysis across ALL metadata with CSV export!
NEW v2.3: API-only authentication - reliable username/password login for Claude Desktop!
- π API-Based Authentication - Reliable username/password login that works perfectly in Claude Desktop
- π οΈ 60 Optimized Tools - Complete Salesforce API coverage with LLM-friendly design
- π― Smart Infrastructure - Caching, connection pooling, pagination, and enhanced error handling
- π Field Usage Analysis - Analyze where 500+ fields are used across ALL metadata with CSV export
- π Intelligent Debugging - Diagnose and fix triggers, flows, validations, fields, permissions, and more
- π Multi-Org Management - Work with multiple orgs simultaneously and compare metadata
- π¦ Bulk Operations - Handle thousands of records with Bulk API 2.0
- π§ͺ Apex Testing - Run tests, get coverage, debug with full logs
- π Schema Analysis - Analyze dependencies, find unused fields, generate ERDs
- π Health Monitoring - Check org limits, API usage, and system health
- π¦ Production-Ready - Retry logic, input validation, structured logging
- Python 3.11+ (Download)
- Claude Desktop (Download)
- Salesforce Org (Production, Sandbox, or Developer)
Recommended: Use username/password authentication (most reliable for MCP servers)
Step 1: Get domain from your org URL
Use salesforce_get_domain_from_url with: https://your-org.salesforce.com
Step 2: Login
Use salesforce_login_username_password with:
- username: your.email@company.com
- password: YourPassword
- security_token: [Get from Salesforce Settings β Reset Security Token]
- domain: [from step 1]
Step 3: Start using tools!
Use execute_soql_query to run: SELECT Id, Name FROM Account LIMIT 10
π Complete Authentication Guide - Detailed instructions with examples
# Clone repository
git clone https://github.com/UltralegendSam-Fs/Salesforce-MCP-Server
cd Salesforce-MCP-Server
# Create virtual environment
python -m venv venv
venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Test server (optional)
python -m app.main --mcp-stdio# Clone repository
git clone https://github.com/UltralegendSam-Fs/Salesforce-MCP-Server
cd Salesforce-MCP-Server
# Create virtual environment
python3 -m venv venv
source venv/bin/activate
# Install dependencies
pip install -r requirements.txt
# Test server (optional)
python -m app.main --mcp-stdioEdit %APPDATA%\Claude\claude_desktop_config.json:
{
"mcpServers": {
"salesforce-mcp-server": {
"command": "C:\\path\\to\\Salesforce-MCP-Server\\start_mcp.bat"
}
}
}Edit ~/Library/Application Support/Claude/claude_desktop_config.json:
{
"mcpServers": {
"salesforce-mcp-server": {
"command": "/bin/bash",
"args": [
"-lc",
"cd '/absolute/path/to/Salesforce-MCP-Server' && source venv/bin/activate && python -m app.main --mcp-stdio"
]
}
}
}Important: Replace with your actual absolute path!
- Restart Claude Desktop
- Login: Type
"Login to Salesforce production"in a new Claude chat - Authenticate: Browser window opens β Login β Allow access
- Start Using: Try
"Check my Salesforce org health"
Universal tools that replace 59 specialized tools:
deploy_metadata- Deploy any metadata type (Apex, LWC, Fields, etc.) with single toolfetch_metadata- Fetch any metadata type with consistent interfacelist_metadata- List metadata of any type with filteringbulk_operation- Unified bulk insert/update/delete operationsexport_data- Export data in CSV, JSON, or backup formatsoql_query- Build and execute queries with optional analysisget_object_metadata- Get fields, relationships, and metadata in one callmanage_user_permissions- Manage profiles and permission sets
Benefits: Easier for LLMs to select, more consistent API, flexible parameters
diagnose_and_fix_issue- Comprehensive debugging for triggers, flows, validations, fields, permissions, formulas, picklists, lookups, layouts, and reports
Powered by 25 real-world QA scenario patterns:
- Trigger recursion and SOQL limit issues
- Flow null handling and decision logic
- Validation rule date/required field errors
- Field-level security and permission issues
- Formula field calculations and references
- Page layout assignment problems
- Report field visibility issues
- Broken lookup relationships
Handles 10+ issue types with intelligent diagnosis, root cause analysis, and actionable fix recommendations. See Debugging Guide for complete details.
salesforce_production_login- OAuth to production orgsalesforce_sandbox_login- OAuth to sandbox (test.salesforce.com)salesforce_custom_login- OAuth to custom domainsalesforce_login_username_password- Login with username/password/tokensalesforce_logout- Clear all sessionssalesforce_auth_status- Check authentication status
list_connected_orgs- List all connected orgsswitch_active_org- Switch between orgscompare_metadata_between_orgs- Compare Apex, Flows, etc.compare_object_schemas- Compare field schemasget_org_differences_summary- High-level org comparison
16 Metadata Types Γ 3 Operations (fetch, create, upsert):
- Apex Classes - Full CRUD operations
- Apex Triggers - Create and manage triggers
- Validation Rules - Deploy validation logic
- LWC (Lightning Web Components) - Complete bundle management
- Custom Objects - Create and configure objects
- Custom Fields - Add fields to any object
- Flows - Manage Flow definitions
- Email Templates - Create email templates
- Permission Sets - Configure permissions
- Static Resources - Upload JavaScript, CSS, etc.
- Custom Metadata Types - Configuration management
- Aura Components - Legacy Lightning components
- Custom Labels - Translation labels
- Record Types - Object record types
- Quick Actions - Create quick actions
- Custom Tabs - Configure custom tabs
run_apex_tests- Run tests with coverageget_apex_test_coverage- Get code coverage detailslist_apex_test_classes- List all test classes
bulk_insert_records- Insert thousands via Bulk API 2.0bulk_update_records- Update thousands of recordsbulk_delete_records- Delete thousands of recordsget_bulk_job_status- Check job progress
export_data_to_csv- Export SOQL results to CSVexport_object_data- Export entire objectsbackup_object_records- Create timestamped backupsget_record_count- Fast record countingexport_schema_to_json- Export object schemas
build_soql_query- Build queries from componentsget_object_fields- Get field metadataget_field_relationships- Get all relationshipsexplain_soql_query- Analyze and optimize queriesquery_with_related_records- Query parent-child records
analyze_object_dependencies- Full dependency analysisfind_unused_fields- Identify unused fieldsgenerate_object_diagram- Generate ERD datalist_all_objects- List all objects (custom/standard)get_field_usage_stats- Field population statisticsanalyze_field_usage- NEW! Comprehensive field usage analysis - find where fields are used across ALL metadata (Apex, Triggers, Flows, Validation Rules, Formulas, Page Layouts, Reports) with CSV export
list_batch_jobs- List Batch Apex jobsget_batch_job_details- Get detailed job infolist_scheduled_jobs- List scheduled Apexabort_batch_job- Stop running batchdelete_scheduled_job- Delete scheduled jobexecute_anonymous_apex- Execute Apex instantlyget_debug_logs- Retrieve debug logsget_debug_log_body- Get full log content
salesforce_health_check- Comprehensive health checkget_org_limits- API/storage limitsget_org_info- Organization detailsget_current_user_info- Current user profilelist_installed_packages- List managed packagesget_api_usage_stats- API usage statistics
execute_soql_query- Run any SOQL queryget_metadata_deploy_status- Check deployment status
change_user_profile- Change a user's profileassign_permission_set- Assign permission set to a userremove_permission_set- Remove permission set from a userlist_user_permissions- List user's permission sets and profilelist_available_profiles- List all profiles in the orglist_available_permission_sets- List all permission sets in the org
compare_profiles- Compare two profiles side-by-sidecompare_permission_sets- Compare two permission setscompare_object_field_counts- Compare field counts between orgsfind_similar_fields_across_objects- Find fields with similar names/typescompare_org_object_counts- Compare total object counts between orgs
# Authentication
"Login to Salesforce production"
"Login to Salesforce sandbox"
"Check my login status"
# Health Check
"Check my Salesforce org health"
"Show me my API limits"
# Run Query
"Run SOQL: SELECT Id, Name FROM Account WHERE Industry = 'Technology' LIMIT 10"
# Get Information
"Show me all custom fields on the Account object"
"List all Apex classes in the org"
# Create Apex Class
"Create an Apex class called AccountService with this code:
public class AccountService {
public static List<Account> getHighValueAccounts() {
return [SELECT Id, Name, AnnualRevenue FROM Account WHERE AnnualRevenue > 1000000];
}
}"
# Create Custom Field
"Create a text field called Customer_Code__c on Account with length 50"
# Create Validation Rule
"Create a validation rule on Opportunity that requires Amount when Stage is Closed Won"
# Deploy LWC Component
"Create an LWC component called accountCard"
# Run Tests
"Run all Apex tests and show me the code coverage"
"Run tests from AccountServiceTest class"
"Show me code coverage for AccountService"
# Debug
"Get my last 10 debug logs"
"Show me the full log for 07L4x000000AbcD"
"Execute this Apex: System.debug('Test message');"
# Connect Multiple Orgs
"Login to Salesforce production"
"Login to Salesforce sandbox"
# List & Switch
"List all my connected orgs"
"Switch to org 00D4x000000XyzE"
# Compare
"Compare Apex classes between production and sandbox"
"Compare Account schema between the two orgs"
"Get differences summary between my orgs"
# Bulk Insert
"Bulk insert 1000 Account records with this CSV data: [...]"
# Bulk Update
"Bulk update all Contacts where State is null to set State = 'Unknown'"
# Check Status
"Check status of bulk job 7504x000000AbcD"
# Export to CSV
"Export all Opportunities from Q4 2024 to CSV"
# Backup
"Backup all Account records"
# Count Records
"How many Leads were created today?"
# Export Schema
"Export Account, Contact, and Opportunity schemas to JSON"
# Analyze single field (fast - excludes reports by default)
"Where is the Case Status field used?"
"Analyze usage of Account.Customer_Type__c field"
# Analyze with reports included (slower but comprehensive)
"Check if Case Status field is used in any reports"
"Analyze Case.Priority including reports"
# Analyze ALL fields on an object (handles 500+ fields)
"Analyze all Case fields and show me where they are used"
"Create a field usage report for all Account fields"
# Analyze all fields including reports
"Analyze all Case fields and check reports too"
# Custom CSV output
"Analyze all Opportunity fields and export to opportunity_audit.csv"
# Results include usage in:
# - Apex Classes (with class names) β
Always checked
# - Apex Triggers (with trigger names) β
Always checked
# - Flows (with flow names) β
Always checked
# - Validation Rules (with rule names) β
Always checked
# - Formula Fields (with field names) β
Always checked
# - Workflow Rules β
Always checked
# - Page Layouts β
Always checked
# - Email Templates β
Always checked
# - Reports β‘ Optional (only if you say "include reports" or "check reports")
# Batch Jobs
"Show all running batch jobs"
"Get details for batch job 7074x000000AbcD"
"Abort batch job 7074x000000AbcD"
# Scheduled Jobs
"List all scheduled Apex jobs"
"Delete scheduled job 0884x000000XyzA"
# Change User Profiles
"Change profile for user john.doe@example.com to System Administrator"
"Assign Standard User profile to jane.smith@example.com"
# Manage Permission Sets
"Assign Sales_User permission set to john.doe@example.com"
"Remove Marketing_Access permission set from jane.smith@example.com"
"List all permission sets for user john.doe@example.com"
# Query Profiles and Permission Sets
"List all available profiles in the org"
"Show me all permission sets"
# Profile Comparison
"Compare System Administrator and Standard User profiles"
"What are the differences between Sales User and Service User profiles?"
# Permission Set Comparison
"Compare Marketing_Admin and Marketing_User permission sets"
# Cross-Org Comparison
"Compare Account object fields between my two connected orgs"
"Find similar fields across Account and Contact objects"
"Compare total object counts between production and sandbox"
The analyze_field_usage tool provides comprehensive field usage analysis across your entire Salesforce org. Perfect for field audits, cleanup projects, and impact analysis before making changes.
Analyzes where fields are used across ALL metadata types:
- β Apex Classes - Shows which classes reference the field
- β Apex Triggers - Identifies trigger dependencies
- β Flows - Finds flows using the field (including Process Builder)
- β Validation Rules - Checks validation rule formulas
- β Formula Fields - Identifies formula field dependencies
- β Workflow Rules - Finds workflow field criteria
- β Page Layouts - Shows layout field placement
- β Reports - Identifies reports using the field
- Field Cleanup - Find unused fields before archiving
- Impact Analysis - Understand dependencies before changes
- Compliance Audit - Document field usage for auditors
- Migration Planning - Map field usage across orgs
- Documentation - Generate comprehensive field reference
# Analyze a single field
"Where is the Case Status field used?"
# Analyze ALL fields on an object (handles 500+ fields efficiently)
"Analyze all Case fields and create a CSV report"
# Custom output filename
"Analyze Account fields and save to account_field_audit.csv"
The tool automatically generates a CSV file saved in the Documents/ folder with these columns:
- Field Name, Label, Type
- Is Custom, Is Required
- Apex Classes Count + Names
- Triggers Count + Names
- Flows Count + Names
- Validation Rules Count + Names
- Formula Fields Count + Names
- Workflow Rules Count + Names
- Page Layouts Count + Names
- Reports Count + Names
- Total Usage Count
- Is Referenced (Yes/No)
Storage Location: Documents/{ObjectName}_field_usage_{timestamp}.csv
NEW in v2.2 - MASSIVELY IMPROVED:
- 5-6x faster with intelligent batch processing
- 500 fields analyzed in 5-10 minutes (was 30-45 minutes!)
- 99% fewer API calls - Only ~15-20 calls for any field count
- Smart caching - Fetches ALL metadata once, checks all fields against it
- Progress tracking - Updates every 50 fields
- Memory efficient - Handles unlimited fields
How it works:
- Fetches all Apex, Triggers, Flows, Validations, Workflows, Layouts, Reports ONCE
- Caches everything in memory
- Checks all fields against cached data (instant!)
- Result: 500 fields in ~5-10 minutes instead of 45 minutes!
Create a .env file (copy from .env.example):
# Server Configuration
SFMCP_MCP_SERVER_NAME=salesforce-mcp-server
SFMCP_LOG_LEVEL=INFO
SFMCP_DEBUG_MODE=false
# OAuth Configuration
SFMCP_OAUTH_CALLBACK_PORT=1717
SFMCP_OAUTH_TIMEOUT_SECONDS=300
# API Configuration
SFMCP_SALESFORCE_API_VERSION=59.0
SFMCP_MAX_RETRIES=3
SFMCP_REQUEST_TIMEOUT_SECONDS=120
# Deployment
SFMCP_DEPLOY_TIMEOUT_SECONDS=300
SFMCP_DEPLOY_POLL_INTERVAL_SECONDS=5Salesforce-MCP-Server/
βββ app/
β βββ main.py # Entry point, tool imports
β βββ config.py # Configuration management
β β
β βββ mcp/
β β βββ server.py # MCP server setup, tool registration
β β βββ tools/ # All 57 MCP tools
β β βββ __init__.py
β β βββ consolidated_metadata.py # Unified metadata deploy/fetch/list
β β βββ consolidated_operations.py # Bulk ops, export, queries, permissions
β β βββ oauth_auth.py # OAuth 2.0 authentication
β β βββ debugging.py # NEW: Issue diagnosis (25 QA patterns)
β β βββ dynamic_tools.py # Apex, triggers, flows, etc.
β β βββ multi_org.py # Multi-org management
β β βββ advanced_comparison.py # Profile/permset/schema comparison
β β βββ user_management.py # User profile/permission management
β β βββ schema_analysis.py # Dependencies, unused fields, ERDs
β β βββ org_management.py # Health check, limits, org info
β β βββ automation.py # Batch jobs, scheduled jobs
β β βββ testing.py # Apex tests, coverage
β β βββ bulk_operations.py # Bulk API operations
β β βββ data_export.py # Export/backup tools
β β βββ query_helpers.py # Query builders
β β βββ utils.py # Response formatting, error handling
β β
β βββ services/
β β βββ salesforce.py # Salesforce connection management
β β
β βββ utils/ # Production-grade utilities
β βββ __init__.py # Utility exports
β βββ validators.py # SOQL injection protection, input validation
β βββ retry.py # Retry logic with exponential backoff
β βββ logging.py # Structured logging
β βββ cache.py # NEW: Caching system (LRU, metadata cache)
β βββ errors.py # NEW: Enhanced error handling
β βββ pagination.py # NEW: Pagination utilities
β βββ connection_pool.py # NEW: Connection pooling
β
βββ requirements.txt # Dependencies
βββ .env.example # Example configuration
βββ README.md # Main documentation
βββ test_all_mcp_tools.py # Comprehensive testing suite
βββ start_mcp.bat # Windows startup script
βββ Documents/ # CSV exports and reports stored here
βββ README.md # Documents folder info
βββ *.csv # Field usage reports, data exports
Total Size: 12,500+ lines of Python code (tools only)
All API calls automatically retry with exponential backoff:
- Max attempts: 3 (configurable)
- Backoff multiplier: 2.0
- Handles transient failures gracefully
Built-in protection against:
- SOQL injection
- Invalid metadata names
- Malformed API requests
- Unsafe operations
Track all operations with correlation IDs:
- Request tracking
- Error debugging
- Performance monitoring
- Audit trails
Built-in production-grade utilities for optimal performance:
- LRU cache for metadata and field definitions
- Automatic cache invalidation with TTL
- Validation rule caching for faster lookups
- Significant performance improvements for repeated queries
- Custom
SalesforceErrorexception with error categories - Error categories: auth, query, deployment, bulk operations
- Troubleshooting hints embedded in error messages
- Structured error responses with actionable suggestions
- Cursor-based pagination for large result sets
- SOQL pagination helpers with automatic batching
- List pagination for API responses
- Handle datasets of any size efficiently
- Multi-org connection pooling with state management
- Thread-local storage for connection isolation
- Pool statistics and monitoring
- Automatic cleanup of stale connections
Solution: Login first: "Login to Salesforce production"
Solution: Logout and re-login:
"Logout from all Salesforce orgs"
"Login to Salesforce production"
Solution: Increase timeout in .env:
SFMCP_DEPLOY_TIMEOUT_SECONDS=600Solution: Check limits: "Get org limits"
Solution:
"List connected orgs"
"Switch to org [user_id]"
Solution:
- Check Claude Desktop config file
- Verify absolute path is correct
- Restart Claude Desktop
- Check logs:
%APPDATA%\Claude\logs\
We welcome contributions! See our Contributing Guide for details.
- Create tool function in appropriate module under
app/mcp/tools/ - Add
@register_tooldecorator - Write docstring with examples
- Add attribution:
"Added by Sameer"in docstring - Test thoroughly before submitting PR
- Update documentation in
COMPLETE_GUIDE.md
Before submitting PRs:
- β All existing tests must pass
- β New tools must include test scenarios
- β Test in sandbox environment first
- β Document any API limit implications
- Complete Guide - Comprehensive 2000+ line guide with all tools
- Debugging Guide - NEW! Diagnose and fix any Salesforce defect
- Updates Summary - Latest v2.1 debugging capabilities
- Capabilities Overview - Feature summary
- Test Report - Latest test results
- Contributing - Contribution guidelines
- β Multi-org management (COMPLETED)
- β Bulk operations (COMPLETED)
- β Schema analysis tools (COMPLETED)
- β Apex testing suite (COMPLETED)
- β User management tools (COMPLETED)
- β Profile and permission set analysis (COMPLETED)
- β Advanced comparison tools (COMPLETED)
- β Comprehensive debugging and defect-solving (COMPLETED v2.1)
- π Enhanced Flow builder capabilities
- π Data quality checking
- π Automated backup scheduling
- π CI/CD integration helpers
- π Token persistence with encryption
- π Dashboard creation tools
- π Enhanced security scanning
- π Performance profiling
- π Multi-language support
"Deployed a complete feature with 5 Apex classes, 3 triggers, and 10 fields in under 10 minutes using just natural language commands." β Development Team Lead
"Multi-org comparison saved us hours during pre-deployment validation." β DevOps Engineer
"The health check and monitoring tools helped us catch API limit issues before they became critical." β Salesforce Admin
MIT License - See LICENSE for details
Created by Sameer | Built with Model Context Protocol
- Issues: GitHub Issues
- Documentation: Complete Guide
- Discussions: GitHub Discussions
If this project saved you time, please star the repository! β
Made with β€οΈ by Sameer | Powered by Anthropic Claude