@andrew_eragon/mcp-server-salesforce
Version:
A SaaS-ready Salesforce connector MCP Server with connection pooling and multi-user support.
471 lines (400 loc) • 17.6 kB
Markdown
An MCP (Model Context Protocol) server implementation that integrates Claude with Salesforce, enabling natural language interactions with your Salesforce data and metadata. This server allows Claude to query, modify, and manage your Salesforce objects and records using everyday language.
<a href="https://glama.ai/mcp/servers/kqeniawbr6">
<img width="380" height="200" src="https://glama.ai/mcp/servers/kqeniawbr6/badge" alt="Salesforce Server MCP server" />
</a>
* **🚀 SaaS-Ready Architecture**: Built-in connection pooling and multi-tenant support for handling multiple users concurrently
* **⚡ Connection Pooling**: Efficient connection reuse and automatic cleanup for optimal performance
* **🔄 Auto-Retry & Timeout**: Robust error handling with automatic retry logic and connection timeouts
* **👥 Multi-User Support**: Handles multiple users with different Salesforce credentials simultaneously
* **Object and Field Management**: Create and modify custom objects and fields using natural language
* **Smart Object Search**: Find Salesforce objects using partial name matches
* **Detailed Schema Information**: Get comprehensive field and relationship details for any object
* **Flexible Data Queries**: Query records with relationship support and complex filters
* **Data Manipulation**: Insert, update, delete, and upsert records with ease
* **Cross-Object Search**: Search across multiple objects using SOSL
* **Apex Code Management**: Read, create, and update Apex classes and triggers
* **Intuitive Error Handling**: Clear feedback with Salesforce-specific error details
```bash
npm install -g @andrew_eragon/mcp-server-salesforce
```
Search for standard and custom objects:
* Search by partial name matches
* Finds both standard and custom objects
* Example: "Find objects related to Account" will find Account, AccountHistory, etc.
Get detailed object schema information:
* Field definitions and properties
* Relationship details
* Picklist values
* Example: "Show me all fields in the Account object"
Query records with relationship support:
* Parent-to-child relationships
* Child-to-parent relationships
* Complex WHERE conditions
* Example: "Get all Accounts with their related Contacts"
* Note: For queries with GROUP BY or aggregate functions, use salesforce_aggregate_query
Execute aggregate queries with GROUP BY:
* GROUP BY single or multiple fields
* Aggregate functions: COUNT, COUNT_DISTINCT, SUM, AVG, MIN, MAX
* HAVING clauses for filtering grouped results
* Date/time grouping functions
* Example: "Count opportunities by stage" or "Find accounts with more than 10 opportunities"
Perform data operations:
* Insert new records
* Update existing records
* Delete records
* Upsert using external IDs
* Example: "Update status of multiple accounts"
Create and modify custom objects:
* Create new custom objects
* Update object properties
* Configure sharing settings
* Example: "Create a Customer Feedback object"
Manage object fields:
* Add new custom fields
* Modify field properties
* Create relationships
* Automatically grants Field Level Security to System Administrator by default
* Use `grantAccessTo` parameter to specify different profiles
* Example: "Add a Rating picklist field to Account"
Manage Field Level Security (Field Permissions):
* Grant or revoke read/edit access to fields for specific profiles
* View current field permissions
* Bulk update permissions for multiple profiles
* Useful for managing permissions after field creation or for existing fields
* Example: "Grant System Administrator access to Custom_Field__c on Account"
### salesforce_search_all
Search across multiple objects:
* SOSL-based search
* Multiple object support
* Field snippets
* Example: "Search for 'cloud' across Accounts and Opportunities"
### salesforce_read_apex
Read Apex classes:
* Get full source code of specific classes
* List classes matching name patterns
* View class metadata (API version, status, etc.)
* Support for wildcards (* and ?) in name patterns
* Example: "Show me the AccountController class" or "Find all classes matching Account*Cont*"
### salesforce_write_apex
Create and update Apex classes:
* Create new Apex classes
* Update existing class implementations
* Specify API versions
* Example: "Create a new Apex class for handling account operations"
### salesforce_read_apex_trigger
Read Apex triggers:
* Get full source code of specific triggers
* List triggers matching name patterns
* View trigger metadata (API version, object, status, etc.)
* Support for wildcards (* and ?) in name patterns
* Example: "Show me the AccountTrigger" or "Find all triggers for Contact object"
### salesforce_write_apex_trigger
Create and update Apex triggers:
* Create new Apex triggers for specific objects
* Update existing trigger implementations
* Specify API versions and event operations
* Example: "Create a new trigger for the Account object" or "Update the Lead trigger"
### salesforce_execute_anonymous
Execute anonymous Apex code:
* Run Apex code without creating a permanent class
* View debug logs and execution results
* Useful for data operations not directly supported by other tools
* Example: "Execute Apex code to calculate account metrics" or "Run a script to update related records"
### salesforce_manage_debug_logs
Manage debug logs for Salesforce users:
* Enable debug logs for specific users
* Disable active debug log configurations
* Retrieve and view debug logs
* Configure log levels (NONE, ERROR, WARN, INFO, DEBUG, FINE, FINER, FINEST)
* Example: "Enable debug logs for user@example.com" or "Retrieve recent logs for an admin user"
## Setup
### SaaS Integration
This server is **SaaS-ready** and supports multi-tenant deployments. When integrating with a SaaS application:
#### Per-Request Credentials
The server automatically extracts user credentials from environment variables set per-request by your application. This enables:
- **Multiple concurrent users** with different Salesforce orgs
- **Connection pooling** for performance optimization
- **Automatic connection reuse** (30-minute idle timeout)
- **Graceful connection cleanup** (every 5 minutes)
#### Connection Pooling Features
- Connections are cached and reused based on user credentials
- Invalid connections are automatically detected and recreated
- Idle connections are cleaned up after 30 minutes of inactivity
- Built-in retry logic (3 attempts) with exponential backoff
- 30-second timeout for connection establishment
#### Example SaaS Integration (Python with Agno Framework)
**Using Access Token Authentication:**
```python
async with MCPTools(
command="mcp-server-salesforce",
env={
"SALESFORCE_CONNECTION_TYPE": "Access_Token",
"SALESFORCE_ACCESS_TOKEN": user_access_token,
"SALESFORCE_INSTANCE_URL": user_instance_url,
},
timeout_seconds=120,
) as toolkit:
# Each user gets isolated connection from pool
result = await toolkit.call_tool("salesforce_query_records", {...})
```
**Using OAuth Response Authentication (with backend OAuth data):**
```python
# Assuming auth_data contains the OAuth response from your backend
async with MCPTools(
command="mcp-server-salesforce",
env={
"SALESFORCE_CONNECTION_TYPE": "OAuth_Response",
"SALESFORCE_ACCESS_TOKEN": auth_data["authData"]["access_token"],
"SALESFORCE_INSTANCE_URL": auth_data["authData"]["instance_url"],
# Optional: Include other OAuth metadata for completeness
"SALESFORCE_ID": auth_data["authData"]["id"],
"SALESFORCE_SCOPE": auth_data["authData"]["scope"],
"SALESFORCE_ISSUED_AT": auth_data["authData"]["issued_at"],
"SALESFORCE_SIGNATURE": auth_data["authData"]["signature"],
"SALESFORCE_TOKEN_TYPE": auth_data["authData"]["token_type"],
# Note: refresh_token not needed - backend handles token refresh
},
timeout_seconds=120,
) as toolkit:
# Each user gets isolated connection from pool
# When tokens expire, your backend provides fresh ones
result = await toolkit.call_tool("salesforce_query_records", {...})
```
You can connect to Salesforce using one of four authentication methods:
1. Obtain an access token from Salesforce OAuth flow
2. Pass the access token and instance URL per request
3. **Best for**: SaaS applications with multiple users
1. Set up your Salesforce credentials
2. Get your security token (Reset from Salesforce Settings)
3. **Best for**: Development and single-user deployments
#### 3. OAuth 2.0 Client Credentials Flow
1. Create a Connected App in Salesforce
2. Enable OAuth settings and select "Client Credentials Flow"
3. Set appropriate scopes (typically "api" is sufficient)
4. Save the Client ID and Client Secret
5. **Important**: Note your instance URL (e.g., `https://your-domain.my.salesforce.com`) as it's required for authentication
#### 4. OAuth Response Authentication (Custom Backend Integration)
1. Use OAuth response data from your backend authentication service
2. **Required**: `access_token` and `instance_url` only
3. **Token refresh**: Handled by your backend - provide fresh tokens when needed
4. **Best for**: Custom applications with backend OAuth handling
5. **Simple and reliable**: No client credentials needed, no refresh token complexity
### Usage with Claude Desktop
Add to your `claude_desktop_config.json`:
#### For Access Token Authentication (SaaS/Multi-User):
```json
{
"mcpServers": {
"salesforce": {
"command": "npx",
"args": ["-y", "@andrew_eragon/mcp-server-salesforce"],
"env": {
"SALESFORCE_CONNECTION_TYPE": "Access_Token",
"SALESFORCE_ACCESS_TOKEN": "your_access_token",
"SALESFORCE_INSTANCE_URL": "https://your-domain.my.salesforce.com"
}
}
}
}
```
```json
{
"mcpServers": {
"salesforce": {
"command": "npx",
"args": ["-y", "@andrew_eragon/mcp-server-salesforce"],
"env": {
"SALESFORCE_CONNECTION_TYPE": "User_Password",
"SALESFORCE_USERNAME": "your_username",
"SALESFORCE_PASSWORD": "your_password",
"SALESFORCE_TOKEN": "your_security_token",
"SALESFORCE_INSTANCE_URL": "org_url" // Optional. Default value: https://login.salesforce.com
}
}
}
}
```
```json
{
"mcpServers": {
"salesforce": {
"command": "npx",
"args": ["-y", "@andrew_eragon/mcp-server-salesforce"],
"env": {
"SALESFORCE_CONNECTION_TYPE": "OAuth_2.0_Client_Credentials",
"SALESFORCE_CLIENT_ID": "your_client_id",
"SALESFORCE_CLIENT_SECRET": "your_client_secret",
"SALESFORCE_INSTANCE_URL": "https://your-domain.my.salesforce.com" // REQUIRED: Must be your exact Salesforce instance URL
}
}
}
}
```
> **Note**: For OAuth 2.0 Client Credentials Flow, the `SALESFORCE_INSTANCE_URL` must be your exact Salesforce instance URL (e.g., `https://your-domain.my.salesforce.com`). The token endpoint will be constructed as `<instance_url>/services/oauth2/token`.
#### For OAuth Response Authentication (Custom Backend):
```json
{
"mcpServers": {
"salesforce": {
"command": "npx",
"args": ["-y", "@andrew_eragon/mcp-server-salesforce"],
"env": {
"SALESFORCE_CONNECTION_TYPE": "OAuth_Response",
"SALESFORCE_ACCESS_TOKEN": "00Dfh000005fLtV!AQEAQP6feeG3wWWBIER1BGaRZHp3_FoIiLClKtFI7HiEToF4M9i61Ww7oJqML5lAoBa_4iOWITyIhf1hEEQRmdyFu_adY01F",
"SALESFORCE_REFRESH_TOKEN": "5Aep861NLJve9Onzo0VWB7dtzhYENU6E96LfiMvXemrVQ2IVUNWOO.uLNfBaW7B9SFjPYb6.tjfGA==",
"SALESFORCE_INSTANCE_URL": "https://dream-innovation-8563.my.salesforce.com",
"SALESFORCE_ID": "https://login.salesforce.com/id/00Dfh000005fLtVEAU/005fh000000QceLAAS",
"SALESFORCE_SCOPE": "refresh_token api",
"SALESFORCE_ISSUED_AT": "1759515618034",
"SALESFORCE_SIGNATURE": "zAIWCMgWR8UipmFFOrJH9OYwfgdOk1hpi5p5oeuQRjE=",
"SALESFORCE_TOKEN_TYPE": "Bearer"
}
}
}
}
```
> **Note**: For OAuth Response Authentication, only `SALESFORCE_ACCESS_TOKEN` and `SALESFORCE_INSTANCE_URL` are required. Refresh tokens are not used by the MCP server - your backend should handle token refresh and provide fresh access tokens when needed. Additional OAuth metadata fields can be provided but are not used by the connection.
```
"Find all objects related to Accounts"
"Show me objects that handle customer service"
"What objects are available for order management?"
```
```
"What fields are available in the Account object?"
"Show me the picklist values for Case Status"
"Describe the relationship fields in Opportunity"
```
```
"Get all Accounts created this month"
"Show me high-priority Cases with their related Contacts"
"Find all Opportunities over $100k"
```
```
"Count opportunities by stage"
"Show me the total revenue by account"
"Find accounts with more than 10 opportunities"
"Calculate average deal size by sales rep and quarter"
"Get the number of cases by priority and status"
```
```
"Create a Customer Feedback object"
"Add a Rating field to the Feedback object"
"Update sharing settings for the Service Request object"
```
Examples with Field Level Security:
```
"Create a Status picklist field on Custom_Object__c"
"Create a Revenue currency field on Account and grant access to Sales User and Marketing User profiles"
```
```
"Grant System Administrator access to Custom_Field__c on Account"
"Give read-only access to Rating__c field for Sales User profile"
"View which profiles have access to the Custom_Field__c"
"Revoke field access for specific profiles"
```
```
"Search for 'cloud' in Accounts and Opportunities"
"Find mentions of 'network issue' in Cases and Knowledge Articles"
"Search for customer name across all relevant objects"
```
```
"Show me all Apex classes with 'Controller' in the name"
"Get the full code for the AccountService class"
"Create a new Apex utility class for handling date operations"
"Update the LeadConverter class to add a new method"
```
```
"List all triggers for the Account object"
"Show me the code for the ContactTrigger"
"Create a new trigger for the Opportunity object"
"Update the Case trigger to handle after delete events"
```
```
"Execute Apex code to calculate account metrics"
"Run a script to update related records"
"Execute a batch job to process large datasets"
```
```
"Enable debug logs for user@example.com"
"Retrieve recent logs for an admin user"
"Disable debug logs for a specific user"
"Configure log level to DEBUG for a user"
```
The server implements a robust connection pooling system that:
- Maintains a pool of authenticated Salesforce connections
- Identifies users by their credentials (access token, username, or client ID)
- Reuses connections for the same user across multiple requests
- Automatically validates and recreates invalid connections
- Cleans up idle connections after 30 minutes
### Multi-Tenant Support
- **Per-Request Isolation**: Each request extracts credentials from environment variables
- **Concurrent Requests**: Handles multiple users simultaneously without interference
- **Connection Reuse**: Efficient connection sharing for the same user
- **Automatic Cleanup**: Idle connections are cleaned up every 5 minutes
### Reliability Features
- **Retry Logic**: Automatically retries failed connections up to 3 times with exponential backoff
- **Timeout Protection**: 30-second timeout for connection establishment
- **Error Handling**: Comprehensive error messages with pool statistics
- **Graceful Shutdown**: Properly closes all connections on server shutdown
### Performance Optimization
- Connection pooling reduces authentication overhead
- Cached connections eliminate redundant API calls
- Parallel request handling for concurrent users
- Automatic cleanup prevents memory leaks
### Monitoring
The server logs detailed information:
- Connection pool statistics (active connections)
- Connection acquisition time per request
- Cache hit/miss rates
- Error details with timing information
## Development
### Building from source
```bash
# Clone the repository
git clone https://github.com/andrew_eragon/mcp-server-salesforce.git
# Navigate to directory
cd mcp-server-salesforce
# Install dependencies
npm install
# Build the project
npm run build
```
## Contributing
Contributions are welcome! Feel free to submit a Pull Request.
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## Issues and Support
If you encounter any issues or need support, please file an issue on the [GitHub repository](https://github.com/andrew_eragon/mcp-server-salesforce/issues).