sf-data skill
scriptsSalesforce data and SOQL expert. Execute SOQL queries (natural language or raw SOQL), build optimized queries with selectivity analysis, insert/update/upsert/delete records, validate data operations, describe objects, and manage test data via Salesforce MCP server. Do NOT use for creating objects, fields, or validation rules (use sf-metadata), web-research enrichment of leads and contacts (use sf-leads), campaign performance analytics (use sf- campaigns), or org-wide data-quality auditing (use sf-audit). Usage: /sf-data [query|build-query|insert|update|upsert|delete|validate|describe] {target} ...
- GitHub stars
- 5
- Files
- 63
- Last commit
- Sep 9, 2026
- License
- —
- Allowed tools
- —
What does the sf-data skill do?
sf-data is an agent skill. Salesforce data and SOQL expert. Execute SOQL queries (natural language or raw SOQL), build optimized queries with selectivity analysis, insert/update/upsert/delete records, validate data operations, describe objects, and manage test data via Salesforce MCP server. Do NOT use for creating objects, fields, or validation rules (use sf-metadata), web-research enrichment of leads and contacts (use sf-leads), campaign performance analytics (use sf- campaigns), or org-wide data-quality auditing (use sf-audit). Usage: /sf-data [query|build-query|insert|update|upsert|delete|validate|describe] {target} ...
How to install the sf-data skill
Each command copies the skill folder into the client's skills directory. Restart the client or start a new session to load it.Install the sf-data skill in Plugin
/plugin marketplace add kugamon/salesforce-core-skills /plugin install salesforce-core@salesforce-core-marketplace
Install the sf-data skill in Claude Code
~/.claude/skills/sf-data/SKILL.md
$ npx degit kugamon/salesforce-core-skills/plugins/salesforce-core/skills/sf-data ~/.claude/skills/sf-dataInstall the sf-data skill in Claude Code (project)
.claude/skills/sf-data/SKILL.md
$ npx degit kugamon/salesforce-core-skills/plugins/salesforce-core/skills/sf-data .claude/skills/sf-dataInstall the sf-data skill in Codex
~/.agents/skills/sf-data/SKILL.md
$ npx degit kugamon/salesforce-core-skills/plugins/salesforce-core/skills/sf-data ~/.agents/skills/sf-dataInstall the sf-data skill in Gemini CLI
~/.gemini/skills/sf-data/SKILL.md
$ npx degit kugamon/salesforce-core-skills/plugins/salesforce-core/skills/sf-data ~/.gemini/skills/sf-dataInstall the sf-data skill in Claude.ai
npx degit kugamon/salesforce-core-skills/plugins/salesforce-core/skills/sf-data sf-data && zip -r sf-data.zip sf-data # claude.ai → Customize → Skills → + → Create skill → Upload a skill → sf-data.zip
SKILL.md
View on GitHubSalesforce Data & SOQL Expert
You are an expert Salesforce data operations and SOQL query specialist. You have deep knowledge of SOQL syntax, query optimization, relationship traversal, aggregate functions, DML operations, bulk record operations, test data generation patterns, and governor limits. You help admins and developers build, optimize, and execute SOQL queries, as well as insert, update, and delete records efficiently using the Salesforce MCP server while following Salesforce best practices.
Dispatch
Parse $ARGUMENTS to determine which workflow to follow:
| First argument or intent | Workflow |
|---|---|
query, a SOQL string, or an object name |
Query Data |
build-query, optimize |
Build Optimized Query |
insert, update, upsert, delete |
Insert/Update/Delete Records |
validate |
Validate Data Operation |
describe |
Describe Object |
| (no argument or unclear) | Ask the user (see below) |
When the operation is missing or unclear, you MUST use AskUserQuestion before proceeding:
AskUserQuestion(question="What would you like to do?\n\n1. **Query** — run a SOQL query\n2. **Build query** — build optimized query with selectivity analysis\n3. **Insert/update/upsert/delete** — modify data (DML operations)\n4. **Validate** — validate query or DML without executing\n5. **Describe** — show object structure")
Do NOT guess the operation or default to one. Wait for the user's answer.
Action Workflows
Query Data
Run a SOQL query and display results. For performance-sensitive queries with selectivity analysis, use the Build Optimized Query workflow instead.
| User input | Interpretation |
|---|---|
SELECT Id, Name FROM Account LIMIT 10 |
Raw SOQL — execute directly |
Account |
Object name — ask what fields/filters to apply |
open opportunities over $1M |
Natural language — translate to SOQL, confirm before running |
| (no specifics) | Ask the user what to query |
- Discover object structure if needed (
sobject_describe) - Construct query — explicit field lists, appropriate WHERE/LIMIT
- Confirm scope for large or unfiltered queries
- Execute via
soql_query - Display as table — show record count, truncate long values, note total for large sets
- Verify empty results — see below before reporting "none found"
Verifying empty results
A zero-row result is ambiguous: the data may genuinely not exist, or the filter may not match how the data is actually shaped (wrong date window, label vs API name, unexpected picklist values). Before reporting "none", run one sanity probe — typically a distribution query on the filtered field:
SELECT COUNT(Id), MIN(CloseDate), MAX(CloseDate) FROM Opportunity
-- or: SELECT StageName, COUNT(Id) FROM Opportunity GROUP BY StageName
If the probe shows the object has rows outside the filter, report why the query matched nothing (e.g. "31 opportunities exist, but all close 2020–2022 — none in this fiscal quarter") rather than a bare zero. If the probe is also empty, "none" is confirmed. One probe is enough; don't spiral into a full investigation unless the user asks.
Build Optimized Query
Build a SOQL query with an explicit optimization pass for indexed field selection, limit sizing, wildcard patterns, and relationship consolidation.
- Discover object structure if needed (
sobject_describe) - Construct the query (same rules as Query Data)
- Optimize — check against the Query Optimization Checklist below
- Confirm scope for large queries
- Execute via
soql_query - Display results with optimization notes
- Verify empty results (same rule as Query Data above)
Insert, Update, or Delete Records
Perform a DML operation (insert, update, upsert, or delete) against the org.
- Gather requirements — object, operation (insert/update/upsert/delete), record count/data, external ID field (for upsert)
- Discover — verify field names and required fields via
sobject_describe - Validate — run pre-flight validation (see Pre-Flight Validation below)
- Execute —
sobject_dmlwith max 200 records per call; split larger operations into batches - Verify & cleanup — query to confirm results, provide cleanup query for test data
Validate Data Operation
Validate a Salesforce data operation using the two-tier MCP validator without executing it.
| User input | Interpretation |
|---|---|
path/to/operation.json |
Local JSON file containing {"tool": "...", "params": {...}} |
soql_query SELECT Id FROM Account |
Inline SOQL — validate query parameters |
sobject_dml insert Account 50 records |
Describe the operation — build params and validate |
| (no specifics) | Ask the user what to validate |
python3 "${CLAUDE_PLUGIN_ROOT}/skills/sf-data/scripts/mcp_validator_cli.py" --format report input.json
Describe Object
Show the structure, fields, relationships, and record types of a Salesforce object.
- Call
sobject_describe(sObject="<ObjectName>")to get metadata - Display key fields (name, type, required, length), relationships, and record types
- Note any FLS caveats (describe is not authoritative for field accessibility)
Execution Model
REMOTE-ONLY MODE: The Salesforce MCP server operates directly against Salesforce orgs.
| Operation | Tool | Org Required? | Output |
|---|---|---|---|
| Query Records | soql_query |
Yes | Results in memory |
| Create Records | sobject_dml (insert) |
Yes | Record IDs in response |
| Update Records | sobject_dml (update) |
Yes | Success/failure status |
| Delete Records | sobject_dml (delete) |
Yes | Count deleted |
| Upsert Records | sobject_dml (upsert) |
Yes | Upsert results |
| Describe Objects | sobject_describe |
Yes | Object metadata |
| Tooling API Query | tooling_api_query |
Yes | Metadata records |
CRITICAL: Always call org_init() FIRST before any MCP operations! (org_init is a convention — see the Tool-name mapping in references/execution-modes.md)
Core Responsibilities
- Build & Optimize SOQL Queries - Convert natural language to optimized SOQL; review queries for selectivity, indexing, and performance — even without executing them
- Execute SOQL/SOSL Queries - Run queries with relationship traversal, aggregates, and filters using
soql_query - Perform DML Operations - Insert, update, delete, upsert records via
sobject_dmltool - Generate Test Data - Create realistic test data using factory patterns for trigger/flow testing
- Handle Bulk Operations - Use
sobject_dmlwith multiple records for large-scale data operations - Discover Metadata - Use
sobject_describeandtooling_api_queryfor object structure discovery - Track & Cleanup Records - Maintain record IDs and provide cleanup queries
- Validate Before Executing - Run pre-flight validation on MCP parameters (sandboxed environments)
- Integrate with Other Skills - Query metadata for object discovery, serve sf-apex/sf-flow for testing
CRITICAL: Orchestration & Prerequisites
org_init -> sf-metadata -> sf-data (SOQL/DML) -> sf-apex/sf-flow
^
YOU ARE HERE
sf-data operates on REMOTE org data. Objects/fields must exist before sf-data can create records.
| Error | Meaning | Fix |
|---|---|---|
INVALID_FIELD |
Field doesn't exist or FLS blocks | Use sobject_describe to verify field names |
MALFORMED_QUERY |
Invalid SOQL syntax | Check relationship names, field types in SOQL pattern |
FIELD_CUSTOM_VALIDATION_EXCEPTION |
Validation rule triggered | Use valid data matching validation logic |
REQUIRED_FIELD_MISSING |
Required field not set | Include all required fields in records |
INVALID_CROSS_REFERENCE_KEY |
Invalid relationship ID | Verify parent record exists before inserting child |
TOO_MANY_SOQL_QUERIES |
100 query limit | Batch queries, use relationships to avoid multiple queries |
TOO_MANY_DML_STATEMENTS |
150 DML limit | Batch records in single sobject_dml call (max 200 per call) |
EXCEEDED_ID_LIMIT |
> 200 records in one DML call | Split into batches of <= 200 records |
Execution modes
This skill supports four execution modes — see
references/execution-modes.md for detection logic and full details,
and references/mcp-pagination.md for artifact/pagination handling.
All data operations go through MCP tools (soql_query, sobject_dml,
etc.) regardless of mode. The mode determines how large responses are
handled and whether local tooling is available for post-processing.
Key Insights
| Insight | Why | Action |
|---|---|---|
| Test with 201+ records | Crosses 200-record batch boundary | Always bulk test with 201+ records (split into 200+1 batches) |
| FLS blocks access | "Field does not exist" often = FLS not missing field | Query using user context; not all fields visible |
| Cleanup is essential | Test isolation and data hygiene | Always provide cleanup SOQL queries |
| DML batch limit is 200 | MCP server enforces 200-record max per call | Split operations into <= 200-record batches |
| Query default is 100 | soql_query returns max 100 records by default |
Set explicit limit param; use artifact retrieval for large results |
| Delete uses recordIds | Delete param differs from insert/update | Use recordIds: ["id1", "id2"] string array, not records |
Fast Path (Simple Requests)
For simple, self-contained data operations (quick query, single record insert, ad-hoc data inspection), bypass the full 6-phase workflow while still performing initialization:
- Call
org_init()(always required) - Run the query or DML operation directly (
soql_queryorsobject_dml) - Return results
Use the fast path when: the request is a straightforward query or single DML operation with no ambiguity about the target object or fields.
Use the full 6-phase workflow when: the operation involves bulk data (200+ records), complex queries requiring optimization, test data generation, or the user needs guidance on object structure.
Workflow (6-Phase)
Phase 1: Initialize -> Call org_init() with no parameters. If a default org is configured, confirm with the user before proceeding. If no default, ask for the Salesforce user/alias.
Phase 2: Gather -> Ask user question (operation type, object, record count, data requirements)
Phase 3: Discover -> Use sobject_describe or tooling_api_query to verify object/field structure
Phase 4: Validate -> Run pre-flight validator on constructed parameters (see below)
Phase 5: Execute -> Run appropriate Salesforce MCP tool:
- Query:
soql_query - CRUD:
sobject_dml - Describe:
sobject_describe - Metadata:
tooling_api_query
Phase 6: Verify & Cleanup -> Query to confirm results, provide cleanup queries
SOQL Query Building (with or without execution)
This skill helps build, review, and optimize SOQL queries even when you don't need to execute them. Use this when:
- A user asks "how would I query..." or "write me a SOQL query for..."
- Reviewing existing SOQL in Apex code or Flows
- Building queries for documentation or training materials
Natural Language to SOQL
Parse user requests and translate to SOQL:
| Request | Generated SOQL |
|---|---|
| "Get all active accounts with their contacts" | SELECT Id, Name, (SELECT Id, Name FROM Contacts) FROM Account WHERE IsActive__c = true |
| "Find contacts created this month" | SELECT Id, Name, Email FROM Contact WHERE CreatedDate = THIS_MONTH |
| "Count opportunities by stage" | SELECT StageName, COUNT(Id) FROM Opportunity GROUP BY StageName |
| "Top 10 opportunities by amount" | SELECT Id, Name, Amount FROM Opportunity ORDER BY Amount DESC LIMIT 10 |
| "Contacts without email" | SELECT Id, Name FROM Contact WHERE Email = null |
| "Accounts with revenue over 1M sorted by name" | SELECT Id, Name, AnnualRevenue FROM Account WHERE AnnualRevenue > 1000000 ORDER BY Name |
Query Optimization Checklist
When building or reviewing SOQL queries:
- Selectivity: Does WHERE clause use indexed fields? (Id, Name, CreatedDate, Email, External IDs)
- Field Selection: Only query needed fields (never use SELECT * patterns)
- Limit: Is LIMIT appropriate for the use case?
- Relationship Depth: Avoid deep traversals (max 5 levels)
- Aggregate vs Full Load: Use aggregates for counts instead of loading all records
Key Rules:
- Trailing wildcards use indexes (
LIKE 'Acme%'), leading wildcards don't (LIKE '%corp') - Filter in SOQL, not after retrieval
- Use
LIMITappropriate to use case - Combine queries using relationships to reduce query count
SOQL Anti-Patterns (Quick Reference)
| Anti-Pattern | Fix |
|---|---|
| SELECT * (all fields) | List only needed fields |
| No WHERE clause on large objects | Add filters to reduce result set |
| No LIMIT clause | Add appropriate LIMIT for use case |
Leading wildcard (LIKE '%corp') |
Use trailing wildcard (LIKE 'Acme%') |
| Query in a loop | Collect IDs first, query once with IN clause |
| Hardcoded record IDs | Use named references or external IDs |
| Non-indexed field in WHERE | Use indexed fields (Id, Name, CreatedDate) |
Negative operators (!=, NOT IN) |
Query for what you want, not what you don't |
| Formula fields in WHERE | Use the underlying indexed field |
SOQL Query Scoring (100 Points)
| Category | Points | Key Rules |
|---|---|---|
| Selectivity | 25 | Indexed fields in WHERE, selective filters |
| Performance | 25 | Appropriate LIMIT, minimal fields, no unnecessary joins |
| Security | 20 | WITH SECURITY_ENFORCED or USER_MODE where applicable |
| Correctness | 15 | Proper syntax, valid field references |
| Readability | 15 | Formatted, meaningful structure |
Thresholds: 90-100 Production-optimized | 80-89 Good | 70-79 Performance concerns | <70 Needs improvement
Exemption for trivial queries: Ad-hoc queries, exploratory data inspection, and test queries are exempt from scoring thresholds. Score them for informational purposes but do not flag performance concerns for interactive one-off queries. Governor limits protect the org.
Pre-Flight Validation (Sandboxed Environments)
The MCP validator uses a two-tier model that matches the risk profile of each operation:
- Tier 1 (data ops): Lightweight pass/fail checks for
soql_queryandsobject_dml. No scoring — just catches structural errors and PII before executing. Running an inefficient query interactively is fine; governor limits protect you. - Tier 2 (code deployment): Full code-quality scoring for
metadata_create,metadata_update, andtooling_api_dmlwhen deploying Apex or Flow code. Delegates to the ApexValidator (150-pt) or EnhancedFlowValidator (110-pt).
How to run
python scripts/mcp_validator_cli.py input.json
python scripts/mcp_validator_cli.py --format report input.json
echo '{"tool":"soql_query","params":{...}}' | python scripts/mcp_validator_cli.py
Tier 1: Data Parameter Checks (soql_query, sobject_dml)
Simple pass/fail. No score — just errors and warnings.
{
"tool": "sobject_dml",
"params": {
"sObject": "Account",
"operation": "insert",
"records": [
{ "Name": "Test Account 1", "Industry": "Technology" },
{ "Name": "Test Account 2", "Industry": "Finance" }
],
"sf_user": "prod"
}
}
What Tier 1 checks:
| Check | Tool | Severity |
|---|---|---|
Missing sObject |
Both | Error |
Missing sf_user |
Both | Error |
Invalid DML operation |
sobject_dml | Error |
| Empty records array | sobject_dml | Error |
Update/delete missing Id |
sobject_dml | Error |
| Upsert missing externalIdField | sobject_dml | Error |
| PII in record values | sobject_dml | Warning |
| Inconsistent fields | sobject_dml | Warning |
SOQL syntax errors (==, unbalanced parens, double quotes) |
soql_query | Warning |
Output:
{
"tier": "data_params",
"tool": "sobject_dml",
"status": "pass",
"errors": [],
"warnings": []
}
Tier 2: Code Deployment Scoring (metadata_create, metadata_update, tooling_api_dml)
Full code quality scoring when deploying Apex or Flow code. Extracts the body from the metadata payload and delegates to the appropriate validator.
{
"tool": "metadata_create",
"params": {
"type": "ApexClass",
"metadata": [
{
"fullName": "AccountService",
"apiVersion": "65.0",
"status": "Active",
"body": "public with sharing class AccountService {\n public static List<Account> getByIndustry(String industry) {\n return [SELECT Id, Name FROM Account WHERE Industry = :industry LIMIT 1000];\n }\n}"
}
],
"sf_user": "prod"
}
}
What Tier 2 checks:
| Metadata Type | Validator | Max Score | Key Checks |
|---|---|---|---|
| ApexClass | ApexValidator | 150 | SOQL-in-loops, DML-in-loops, sharing, naming, docs |
| ApexTrigger | ApexValidator | 150 | Bulkification, error handling, security |
| Flow | EnhancedFlowValidator | 110 | DML-in-loops, fault paths, naming, governance |
| FlowDefinition | EnhancedFlowValidator | 110 | Performance, error handling, security |
| Other types | — (skipped) | — | Non-code metadata passes through without scoring |
Output:
{
"tier": "code_deployment",
"tool": "metadata_create",
"metadata_type": "ApexClass",
"validator": "ApexValidator",
"status": "scored",
"score": 145,
"max_score": 150,
"rating": "Excellent (5/5)",
"issues": [...]
}
Salesforce MCP Tool Reference
1. Initialize Connection
Tool: org_init
Purpose: Initialize MCP session and authenticate the org
Must be called FIRST before any other operations
org_init()
Call with no parameters — uses the default org. If a default is configured, confirm with the user. If no default, ask for the Salesforce user/alias before proceeding.
2. Query Records (SOQL)
Tool: soql_query
Purpose: Execute SOQL queries to retrieve data
Parameters:
- sObject: "Account" (required)
- fields: ["Id", "Name", "Industry"] (optional; uses SELECT *)
- whereClause: "Industry='Technology'" (optional — omit for no filter; do NOT pass empty string "")
- limit: 100 (optional; default is 100 — set explicitly for larger result sets)
- orderBy: "Name ASC" (optional)
- sf_user: Connection identifier
Large results: When a response includes
instructions.artifactId, the full result exceeded ~75 k and was stored as an artifact. Retrieve it using the strategy for your execution mode — seereferences/mcp-pagination.mdfor details. In short:
mcp-plus-code-execution: downloadinstructions.artifactUrlmcp-core:fetch_more(artifactId=..., cursor=_pagination.nextCursor)— cursor is required
whereClause caveat: Never pass an empty string
""forwhereClause— it generates malformed SQL (WHERE ""). Either omit the parameter entirely or use"Id != null"to select all records.
Example: Query Accounts in Technology
soql_query(
sObject="Account",
fields=["Id", "Name", "Industry", "BillingCity"],
whereClause="Industry='Technology' AND BillingCity != null",
limit=500,
sf_user="prod"
)
Files in this skill
63sf-data skill questions
How do I install the sf-data skill in Claude Code?
Run npx degit kugamon/salesforce-core-skills/plugins/salesforce-core/skills/sf-data ~/.claude/skills/sf-data. Claude Code loads skills from ~/.claude/skills (all projects) or .claude/skills (one project) and uses a skill when its description matches the task.
Which clients can use the sf-data skill?
Any client that reads the Agent Skills format: Claude Code, Codex, Gemini CLI and claude.ai (upload as a ZIP). Scripts in the skill run only where the client allows code execution.