sf-schema-intelligence
by venkatviswa
README.md
# sf-schema-intelligence
> Deterministic, org-specific Salesforce schema intelligence for LLMs — via MCP.
 [](LICENSE)
> **Beta notice:** This project is in active development. It has been tested with Claude Code and Cursor. Integration with other MCP-compatible clients (OpenAI Agents SDK, Gemini, Windsurf) is in progress — connection instructions are provided but feedback on edge cases is welcome. See [Issues](https://github.com/venkatviswa/sf-schema-intelligence/issues) to report anything unexpected.
## The Problem This Solves
### LLMs Don't Know Your Org
Large language models like Claude, ChatGPT, and Gemini are trained on data up to a cutoff date. For Salesforce developers and architects, this creates three compounding problems:
**1. Salesforce releases 3 times a year**
Salesforce ships major releases in Spring, Summer, and Winter — each introducing new standard objects, deprecated fields, changed relationships, and new Health Cloud or Financial Services Cloud APIs. A model trained in early 2024 knows nothing about Winter 2025 changes. Ask it to write Apex against a new object and it will confidently produce code that does not compile.
**2. Every org is different**
No two Salesforce orgs share the same schema. A Healthcare org has hundreds of custom objects, client-specific fields on standard objects, industry-specific junction objects, and namespace prefixes from installed managed packages. A Financial Services org has its own custom policy, claim, and account hierarchies. Claude knows the generic product. It does not know YOUR org.
**3. Hallucination compounds with complexity**
When an LLM does not know a field name, it guesses plausibly. `ProviderStatus__c` becomes `Status__c`. `InsurancePolicy__c` becomes `Policy__c`. In a SOQL query this is a compile error. In an Apex trigger deployed to production, it is an incident.
### The Solution
sf-schema-intelligence exports your org's real schema to a local cache and exposes it to any LLM via the Model Context Protocol (MCP). The LLM calls your schema tools before answering — getting accurate, org-specific field names, types, and relationships before writing a single line of code.
```
Without sf-schema-intelligence:
You: "Write a SOQL query for active Healthcare Providers"
LLM: SELECT Id, Status__c FROM Provider__c WHERE Status__c = 'Active'
^ wrong field ^ wrong object name ^ wrong value
With sf-schema-intelligence:
You: "Write a SOQL query for active Healthcare Providers"
LLM: [calls get_object_schema("HealthcareProvider__c")]
SELECT Id, ProviderStatus__c, ContractStartDate__c, PrimaryAccount__c
FROM HealthcareProvider__c
WHERE ProviderStatus__c = 'In Network'
^ exact field from your org ^ exact picklist value
```
### Why MCP
The Model Context Protocol (MCP), open-sourced by Anthropic in 2024 and now governed by the Linux Foundation with backing from OpenAI, Google, and Microsoft, is the universal standard for connecting LLMs to external tools and data. One MCP server works across Claude, GPT-4, Gemini, Cursor, and any other MCP-compatible client. You build the schema intelligence once. Every AI tool your team uses benefits from it.
---
## How This Fits the Salesforce MCP Ecosystem
Salesforce itself ships an official MCP server — [`salesforcecli/mcp`](https://github.com/salesforcecli/mcp) — and it is excellent at what it does. It lets an LLM deploy metadata, run Apex tests, execute SOQL queries, manage scratch orgs, and assist with LWC development. It is built for **developers and DevOps engineers** who need an AI assistant that can take action inside an org.
sf-schema-intelligence occupies a different layer entirely. It is built for **architects and technical leads** who need an AI assistant that deeply understands what an org looks like — before a single line of code is written or deployed.
The distinction maps to two different questions:
| | salesforcecli/mcp | sf-schema-intelligence |
|---|---|---|
| Primary question | *What do you want to do to your org?* | *What does your org look like?* |
| Core persona | Developer, DevOps engineer | Architect, technical lead |
| Executes actions | Yes — deploy, test, query, manage | No — read-only schema analysis |
| Schema awareness | None | Full — fields, types, relationships, picklist values |
| ER diagram generation | No | Yes — Mermaid and PlantUML, depth-controlled |
| Breaking change detection | No | Yes — BREAKING / NON-BREAKING / INFO |
| Data integrity workbooks | No | Yes — Markdown reports with field dictionaries, metrics |
| Daily change tracking | No | Yes — snapshot archival + automated diff reports |
| Works offline | No | Yes — local cache, no live org required |
| Multi-org schema diff | No | Yes — compare any two snapshots |
They are designed to be run side by side. The official server executes; this one understands. A complete AI-assisted Salesforce workflow needs both:
```
Architect workflow (sf-schema-intelligence):
"Compare our sandbox to production schemas"
→ surfaces 2 BREAKING changes before any deployment is attempted
Developer workflow (salesforcecli/mcp + sf-schema-intelligence):
"Fix the breaking field type change, then deploy"
→ sf-schema-intelligence provides the exact field structure
→ salesforcecli/mcp executes the deployment and runs the tests
```
The capability sf-schema-intelligence adds — and that no other Salesforce MCP tool currently provides — is treating the org schema itself as the primary subject of intelligence: indexing it, visualizing it, diffing it across org versions, and surfacing all of it to any LLM in a form that eliminates hallucination at the field level.
---
## Architecture
```
+-----------------------------------------------------+
| MCP Clients |
| Claude Desktop . Claude Code . Cursor . OpenAI |
+--------------------+--------------------------------+
| MCP Protocol (stdio / HTTP)
+--------------------v--------------------------------+
| src/mcp/server.py (FastMCP) |
| Thin @mcp.tool wrappers -- no business logic |
+--------------------+--------------------------------+
| Python imports
+--------------------v--------------------------------+
| src/core/ |
| diff.py . graph.py . er_diagram.py . workbook.py |
| Pure Python -- no MCP, no ML, fully testable |
+--------------------+--------------------------------+
| Python imports
+--------------------v--------------------------------+
| src/data/schema_cache.py |
| Load . save . index schema snapshots |
+--------------------+--------------------------------+
| JSON files
+--------------------v--------------------------------+
| schema-cache/ |
| _orgs.json (org registry) |
| prod/ Account.json . _index.json . _meta.json |
| sandbox/ Account.json . _index.json . _meta.json |
+-----------------------------------------------------+
```
Dependency rule: data <- core <- mcp. Never reversed. Core modules never import from MCP. This keeps business logic independently testable without running an MCP server.
---
## Prerequisites
* Python 3.11+
* A Salesforce org with API access
* Salesforce CLI (`sf`) for authentication — install from [developer.salesforce.com/tools/salesforcecli](https://developer.salesforce.com/tools/salesforcecli)
> **Note:** `pip install -e .` (step 1 below) installs all required Python packages: `fastmcp`, `click`, `requests`, `networkx`, and `python-dotenv`. You must run this before using the sync script or CLI.
## Quick Start
### 1. Install
```
git clone https://github.com/venkatviswa/sf-schema-intelligence
cd sf-schema-intelligence
pip install -e ".[dev]"
```
### 2. Authenticate with Salesforce
```
# Log in via browser (replace alias and URL with your org)
sf org login web --alias myorg --instance-url https://your-domain.my.salesforce.com
# Verify connection
sf org display --target-org myorg
```
No `.env` file needed when using `--org` — credentials are pulled from the Salesforce CLI automatically.
### 3. Sync Schema
```
# Sync specific objects using org alias (recommended)
python scripts/sf_schema_sync.py --org myorg \
--objects Account --objects Contact --objects Opportunity \
--objects Case --objects Lead --objects Campaign
# Sync all queryable objects (can be slow for large orgs — 4000+ objects)
python scripts/sf_schema_sync.py --org myorg
```
This creates `schema-cache/myorg/` with one JSON file per object, plus `_index.json` and `_meta.json`. The org is automatically registered in `schema-cache/_orgs.json`.
> **Tip:** Start with a targeted sync of the objects you care about. A full org sync can take a long time on orgs with many managed packages.
### 4. Verify
```
# List synced orgs
python cli.py orgs
# List synced objects for an org
python cli.py --org myorg list
# Describe an object
python cli.py --org myorg describe Account
# Generate an ER diagram
python cli.py --org myorg er Account --depth 1 --format mermaid
```
### 5. Run Tests
```
python -m pytest tests/ -v
```
127 tests covering the graph builder, diff engine, ER diagram renderers, workbook generation, snapshot archival, and multi-org support.
## CLI Reference
All commands accept `--org <alias>` to target a specific org, or `--cache-dir <path>` for a raw directory.
```
# List synced orgs
python cli.py orgs
# Search for objects by keyword
python cli.py --org myorg search provider --custom-only
# Full schema for an object
python cli.py --org myorg describe Account
# Show relationships for an object
python cli.py --org myorg relationships Account
# Generate ER diagram (Mermaid or PlantUML)
python cli.py --org myorg er Account Contact --depth 2 --format mermaid
# Generate hierarchy diagram for self-referencing objects
python cli.py --org myorg hierarchy Account --max-levels 3
# Compare two orgs' schemas
python cli.py diff ./schema-cache/sandbox ./schema-cache/prod --json-output
# List all cached objects
python cli.py --org myorg list --custom-only
# Show cache metadata (last sync, org info)
python cli.py --org myorg meta
# Generate data integrity workbook
python cli.py --org myorg workbook --output workbook.md
python cli.py --org myorg workbook --objects Account --objects Contact --no-picklists
# Diff report (compare current schema vs last archived snapshot)
python cli.py --org myorg diff-report
python cli.py --org myorg diff-report --output changes.md
```
## Connecting to LLM Clients
### Claude Code
```
claude mcp add salesforce-schema -- python -m src.mcp.server
```
Run this from the project directory. The server will appear in Claude Code's MCP tools automatically.
### Cursor
Add to `~/.cursor/mcp.json` for global access (all projects), or `.cursor/mcp.json` in a specific project:
```json
{
"mcpServers": {
"salesforce-schema": {
"command": "python",
"args": ["-m", "src.mcp.server"],
"cwd": "/path/to/sf-schema-intelligence",
"env": {
"SF_SCHEMA_CACHE": "./schema-cache"
}
}
}
}
```
Reload the Cursor window (`Cmd+Shift+P` → "Reload Window") after adding.
Add `.cursorrules` to your project root:
```
Always use the salesforce-schema MCP tools before writing Apex, SOQL, or generating ER diagrams.
Never assume field API names.
```
### Claude Desktop
Add to `claude_desktop_config.json` (found at `~/Library/Application Support/Claude/`):
```json
{
"mcpServers": {
"salesforce-schema": {
"command": "python",
"args": ["-m", "src.mcp.server"],
"cwd": "/path/to/sf-schema-intelligence",
"env": {
"SF_SCHEMA_CACHE": "./schema-cache"
}
}
}
}
```
Restart Claude Desktop. You will see "salesforce-schema" in the tools panel with 13 available tools.
### OpenAI
```python
import asyncio
from agents import Agent, Runner
from agents.mcp import MCPServerStdio
async def main():
sf_schema = MCPServerStdio(params={
"command": "python3",
"args": ["/path/to/src/mcp/server.py"],
"env": {"SF_SCHEMA_CACHE": "/path/to/schema-cache"}
})
agent = Agent(
name="Salesforce Architect",
model="gpt-4o",
instructions="Always call get_object_schema before writing Apex or SOQL.",
mcp_servers=[sf_schema]
)
async with sf_schema:
result = await Runner.run(
agent,
"Write Apex to update InsurancePolicy__c status when a Claim is approved"
)
print(result.final_output)
asyncio.run(main())
```
### Gemini
```python
import asyncio
from fastmcp import Client
from google import genai
from google.genai import types
async def ask(question: str) -> str:
async with Client("/path/to/src/mcp/server.py") as mcp_client:
response = await genai.Client().aio.models.generate_content(
model="gemini-2.0-flash",
contents=question,
config=types.GenerateContentConfig(tools=[mcp_client.session])
)
return response.text
asyncio.run(ask("Generate ER diagram for the insurance policy domain"))
```
## MCP Tools
| Tool | Description |
| --- | --- |
| `list_orgs` | List all synced orgs and show which is currently active |
| `switch_org` | Switch the active org for all subsequent queries |
| `get_object_schema` | Full field definitions and relationships for an object |
| `search_objects` | Search by keyword in API name or label |
| `list_all_objects` | Summary list of all cached objects (filterable to custom only) |
| `get_object_relationships` | Lookup, master-detail, and child relationships |
| `generate_er_diagram_tool` | Deterministic Mermaid or PlantUML ER diagram with depth/direction controls |
| `generate_hierarchy_diagram_tool` | Hierarchy diagram for self-referencing objects (e.g. Account → ParentId) |
| `compare_schemas` | Structured diff between two snapshots or orgs with severity classification |
| `get_schema_meta` | Cache metadata (last sync time, org info, object count) |
| `generate_workbook_tool` | Generate a Markdown data integrity workbook (object inventory, field dictionary, relationship map, metrics) |
| `generate_diff_report` | Compare current schema against the most recent archived snapshot and return a Markdown diff report |
| `refresh_object` | Re-fetch a single object's schema from Salesforce without a full sync |
## Use Case Examples
### Accurate Apex Generation (Healthcare)
**Prompt:** "Write an Apex trigger on HealthcareProvider__c that sets status to Inactive when their insurance policy expires"
**Tool calls:** `get_object_schema("HealthcareProvider__c")`, `get_object_schema("InsurancePolicy__c")`, `get_object_relationships("HealthcareProvider__c")`
**Result:** Apex with exact field names, correct SOQL relationship traversal, accurate picklist values — compiles on first attempt. No guessed field names.
### Client-Specific ER Diagrams
**Prompt:** "Generate an ER diagram for our provider network domain, 2 levels deep"
**Tool calls:** `search_objects("provider")`, `generate_er_diagram_tool(["HealthcareProvider__c", "ProviderLocation__c"], depth=2)`
**Result:** Mermaid diagram with real org objects, client custom fields included, renders in Lucid / Mermaid.live / GitHub. Not a generic diagram from training data.
### Safe Sandbox-to-Production Migration
**Prompt:** "Compare our sandbox schema to production and flag breaking changes"
**Tool calls:** `compare_schemas("sandbox", "prod")` (accepts org aliases or directory paths)
```
BREAKING (2):
HealthcareProvider__c.ProviderStatus__c TYPE CHANGED text -> picklist
InsurancePolicy__c.PolicyNumber__c FIELD REMOVED
NON-BREAKING (14):
Claim__c.AdjudicationNotes__c FIELD ADDED
... 13 more
INFO (6): label changes, description updates
```
### Automated Data Integrity Workbook
**Prompt:** "Generate a data integrity workbook for our org"
**Tool calls:** `generate_workbook_tool()`
**Result:** Complete Markdown document with executive summary, object inventory, field dictionary with picklist values, relationship map, and aggregate metrics — ready to share with leadership or audit teams.
### Daily Change Tracking
**Prompt:** "What changed in our schema since yesterday?"
**Tool calls:** `generate_diff_report()`
**Result:** Markdown diff report showing added/removed/modified objects and fields, with severity classification (BREAKING / NON-BREAKING / INFO) and before/after timestamps.
### Hierarchy Visualization
**Prompt:** "Show me the Account hierarchy in our org"
**Tool calls:** `generate_hierarchy_diagram_tool("Account", max_levels=3)`
**Result:** Flowchart showing self-referencing Account → Account via ParentId. Renders in draw.io and Lucidchart for client presentations.
## Diagram Rendering
| Tool | Support | How to Use |
| --- | --- | --- |
| Claude Desktop / Code | Native | Renders Mermaid inline automatically |
| GitHub Markdown | Native | Paste in ` ```mermaid ` block in any .md file |
| Notion | Native | Insert code block, select Mermaid language |
| draw.io | Full | Arrange > Insert > Mermaid — converts to editable shapes |
| Lucidchart | Full | Import > Mermaid diagram |
| mermaid.live | Full | Paste and share URL — good for client presentations |
| Confluence | Via draw.io | draw.io Confluence app > Insert > Mermaid |
| PlantUML | plantuml.com | Paste `@startuml`/`@enduml` block |
## Multi-Org Support
Sync multiple orgs and switch between them without restarting the MCP server.
### Syncing Multiple Orgs
```
# Authenticate and sync each org
sf org login web --alias prod
python scripts/sf_schema_sync.py --org prod
sf org login web --alias sandbox
python scripts/sf_schema_sync.py --org sandbox --objects Account --objects Contact
```
This creates:
```
schema-cache/
_orgs.json # registry: {prod: {...}, sandbox: {...}}
prod/ # full schema cache
_snapshots/ # archived snapshots (created by --archive flag)
2026-03-04/ # dated subdirectory
2026-03-03/
sandbox/ # targeted schema cache
```
### Switching Orgs in MCP
From Claude, Cursor, or any MCP client:
```
> list_orgs
Synced orgs (2):
prod: https://mycompany.my.salesforce.com (ACTIVE)
sandbox: https://mycompany--uat.sandbox.my.salesforce.com
> switch_org("sandbox")
Switched to 'sandbox'. Last synced: 2026-02-19T06:00:04+00:00
> describe Account # now returns sandbox Account schema
```
### Switching Orgs in CLI
```
python cli.py --org prod describe Account
python cli.py --org sandbox describe Account
```
### Comparing Orgs
```
# Via MCP
compare_schemas("sandbox", "prod")
# Via CLI
python cli.py diff ./schema-cache/sandbox ./schema-cache/prod
```
### Daily Schema Refresh
Use `--archive` to save a snapshot before each sync — this enables daily diff reports to track what changed.
```
crontab -e
# Add one line per org (--archive saves the current snapshot before syncing):
0 7 * * * cd /path/to/sf-schema-intelligence && source .venv/bin/activate && python scripts/sf_schema_sync.py --org prod --archive >> ~/logs/sf-schema.log 2>&1
0 7 * * * cd /path/to/sf-schema-intelligence && source .venv/bin/activate && python scripts/sf_schema_sync.py --org sandbox --archive >> ~/logs/sf-schema.log 2>&1
```
Then view what changed:
```
# Via MCP
> generate_diff_report()
# Via CLI
python cli.py --org prod diff-report --output changes.md
```
### Legacy Single-Org Mode
If you don't use `--org`, the sync script reads credentials from a `.env` file and writes directly to `schema-cache/` (no subdirectories). This is fully backward compatible — existing setups continue to work unchanged.
## Phase Roadmap
| Phase | Status | Description |
| --- | --- | --- |
| 1 | Done | Deterministic diff, ER diagrams, MCP tooling |
| 2 | Planned | Domain auto-discovery via Louvain graph clustering |
| 3 | Planned | Embedding-based rename detection (local, no API) |
**Phase 2 — Domain Auto-Discovery:** Uses NetworkX + Louvain community detection to automatically group objects into business domains (Provider Network, Policy Management, Claims etc.) without any prior configuration. Useful on day one of a new engagement.
**Phase 3 — Embedding-Based Rename Detection:** Uses sentence-transformers (runs locally, no API cost) to detect when objects or fields were renamed between versions — rather than incorrectly reporting them as a delete + add.
---
## License
MIT License — see [LICENSE](LICENSE) for details.
Copyright (c) 2025 Venkat Viswanathan
This server cannot be deployed
Maintenance
ActivityInactive
ResponsivenessOutdated data