# Salesforce MCP Server

Model Context Protocol (MCP) server for Salesforce integration. Provides tools for querying and managing Salesforce data through the REST API.

## Features

- **SOQL Queries**: Execute powerful SOQL queries with automatic pagination
- **CRUD Operations**: Create, read, update, and delete records across all Salesforce objects
- **Bulk API**: Handle large data operations efficiently with Bulk API 2.0
- **Composite Requests**: Batch multiple operations in a single API call
- **Object Metadata**: Describe Salesforce objects and fields
- **Rate Limiting**: Automatic retry with exponential backoff and API limit tracking
- **Type Safety**: Comprehensive TypeScript types for all Salesforce entities

## Installation

```bash
npm install
npm run build
```

## Configuration

Create a `.env` file based on `.env.example`:

```bash
SF_ACCESS_TOKEN=your_oauth2_access_token_here
SF_INSTANCE_URL=https://yourinstance.my.salesforce.com
SF_API_VERSION=v59.0  # Optional, defaults to v59.0
```

### Getting an Access Token

1. **Connected App**: Create a Connected App in Salesforce Setup
2. **OAuth Flow**: Use OAuth 2.0 to obtain an access token
3. **Refresh Token**: Implement token refresh logic for long-running servers

For development, you can use Salesforce CLI:
```bash
sfdx force:org:display --verbose -u your_org_alias
```

## Usage

### Development Mode

```bash
npm run dev
```

### Production Mode

```bash
npm run build
npm start
```

## Available Tools

### Query Tools

- `salesforce_query`: Execute SOQL queries
- `salesforce_describe_object`: Get object metadata

### CRUD Tools

- `salesforce_create_record`: Create new records
- `salesforce_update_record`: Update existing records
- `salesforce_delete_record`: Delete records

### Bulk Operations

- Bulk API 2.0 support for large data operations
- Automatic CSV upload and job monitoring

## Architecture

### Core Components

- **`src/types/index.ts`**: TypeScript definitions for all Salesforce entities
- **`src/clients/salesforce.ts`**: REST API client with retry logic and caching
- **`src/server.ts`**: MCP server with lazy-loaded tool modules
- **`src/main.ts`**: Entry point with environment validation

### Supported Objects

- Standard Objects: Account, Contact, Lead, Opportunity, Case, Task, Event
- Marketing: Campaign, CampaignMember
- Admin: User, UserRole, Profile, PermissionSet
- Reports: Report, Dashboard
- Files: ContentDocument, ContentVersion, Attachment
- Custom Objects: Generic support for any custom object

## API Patterns

### SOQL Queries

```typescript
// Simple query
const result = await client.query('SELECT Id, Name FROM Account LIMIT 10');

// Query builder
const soql = client.buildSOQL({
  select: ['Id', 'Name', 'Industry'],
  from: 'Account',
  where: "Industry = 'Technology'",
  orderBy: 'Name ASC',
  limit: 100
});

// Query all (auto-pagination)
const allAccounts = await client.queryAll('SELECT Id, Name FROM Account');
```

### CRUD Operations

```typescript
// Create
const result = await client.createRecord('Account', {
  Name: 'Acme Corp',
  Industry: 'Technology'
});

// Update
await client.updateRecord('Account', accountId, {
  Phone: '555-1234'
});

// Delete
await client.deleteRecord('Account', accountId);
```

### Bulk API

```typescript
// Create bulk job
const job = await client.createBulkJob({
  object: 'Account',
  operation: 'insert'
});

// Upload CSV data
await client.uploadBulkData(job.id, csvData);

// Close job
await client.closeBulkJob(job.id);
```

## Error Handling

The client includes:
- Automatic retry with exponential backoff (3 retries)
- Rate limit detection and handling
- Structured error responses
- API limit tracking via `Sforce-Limit-Info` header

## Resources

- [Salesforce REST API Documentation](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/)
- [SOQL Reference](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/)
- [Bulk API 2.0](https://developer.salesforce.com/docs/atlas.en-us.api_bulk_v2.meta/api_bulk_v2/)

## License

MIT
