Platform metadata api context get

From forcedotcom/sf-skills · View interactive version

Platform metadata api context get is an AI agent skill from the GitHub repository forcedotcom/sf-skills. REQUIRED companion for Salesforce metadata generation — load this schema/API-context skill in the SAME turn as ANY metadata generator (if you load a generator, you ALSO load this). Use whenever you create, generate, edit, or author metadata or a *-meta.xml file (custom object, field, flow, and 604 M

How to use this skill

Skill file

Salesforce Metadata API Skill

This skill provides comprehensive documentation for all 604 Salesforce Metadata API types. Use this skill to create, understand, and modify Salesforce metadata XML files in your Salesforce DX projects.

Overview

The Salesforce Metadata API allows you to retrieve, deploy, create, update, or delete customizations for your org. This skill gives you access to detailed documentation for each metadata type, including:

How to Use This Skill

CRITICAL: Section-Specific Consumption

ALWAYS consume only the specific sections you need from JSON files, NOT entire files.

CRITICAL: For assets/metadata_api/*.json files, always use jq or programmatic JSON parsing to extract only the specific sections you need. Do not load these files whole via Read, cat, read_file, or any other tool that injects the complete file — they contain verbose WSDL segments and other sections that waste 60-80% of tokens. (Loading small files like this SKILL.md or the index table with Read is fine; the rule applies specifically to the large metadata-type JSON files.)

Each JSON file contains multiple sections (fields, description, wsdl_segment, etc.). Most use cases only require 1-2 sections:

This reduces token consumption by 60-80% per file.

Quick Start

To get information about a specific metadata type:

  1. Section-specific (BEST): "Show me only the 'fields' section from CustomObject.json"
  2. Multiple sections: "Show me 'fields' and 'description' from Flow.json"
  3. Avoid loading entire files: Don't ask for "the CustomObject metadata type" - specify sections

Example Queries (Section-Specific)

Recommended:

Avoid:

JSON File Structure

Each metadata type is stored as a JSON file in assets/metadata_api/ with the following structure:

{
  "sections": ["title", "description", "fields", "wsdl_segment", ...],
  "title": "MetadataTypeName - Metadata API",
  "description": "Plain-text description of the metadata type.",
  "fields": {
    "fieldName": {
      "type": "string",
      "description": "Field description",
      "required": true
    }
  },
  "file_information": ".object",
  "directory_location": "objects",
  "wsdl_segment": "<xsd:complexType>...</xsd:complexType>",
  "declarative_metadata_sample_definition": [
    {
      "description": "Example description",
      "code": "<?xml version=\"1.0\"?>\n<MetadataType>...\n</MetadataType>"
    }
  ]
}

Note: string values (title, description, file_information, directory_location, wsdl_segment) are stored as plain text — no markdown headers (#/##) or code fences. file_information holds just the file suffix (e.g. .object, .ai) and directory_location just the SFDX folder name (e.g. objects, aiApplications).

Available Sections

The sections array indicates which top-level keys are present in each file. Common sections include:

Some metadata types have additional sections specific to their functionality. See the Index Table for a complete breakdown.

More detail: background on why token optimization matters, worked usage examples, common workflows, a full section glossary, and versioning/support notes live in CODE0. Load it with the Read tool only when needed.

Token Optimization Strategies

CRITICAL: To minimize token usage and costs:

  1. Load only the specific metadata type(s) you need, not the full corpus
  2. Load only specific sections from each file, not entire files

Section-Specific Loading (BEST PRACTICE)

CRITICAL WARNING: DO NOT use the read_file tool (or any whole-file reading tool) on these JSON files!

read_file loads the entire file content into your context, defeating the purpose of section-specific consumption. You will waste 60-80% of your token budget loading unnecessary WSDL segments and verbose sections. (Using Read on small files such as this SKILL.md or the index table is fine — this rule is only about the large metadata-type JSON files.)

Approach: Programmatically parse the JSON file and extract ONLY the sections you need using code, not whole-file reading tools.

Working Examples Available:

We provide complete, working code examples in multiple languages:

See CODE0 for complete documentation and usage instructions.

Quick Pattern (adapt to your language):

  1. Read the JSON file
  2. Parse it into a data structure
  3. Extract ONLY the sections you need (e.g., fields, description)
  4. Ignore verbose sections (wsdl_segment, declarative_metadata_sample_definition)

What NOT to Do

NEVER use the read_file tool on these JSON files:

read_file assets/metadata_api/CustomObject.json  # Loads entire file into context!
read_file assets/metadata_api/Flow.json          # Wastes 60-80% tokens!

NEVER load all files:

read_file assets/metadata_api/*.json  # This loads ~15MB of data!

Token Impact:

When to Load Multiple Types

When to Load Specific Sections (STRONGLY RECOMMENDED)

Many metadata types have large WSDL segments or extensive field lists. Always load only the specific sections you need from each JSON file rather than consuming the entire file:

  1. First, check available sections by reading just the sections array from the JSON
  2. Extract only the sections you need (e.g., fields for field definitions, description for overview)
  3. Skip WSDL segments unless you specifically need schema validation
  4. Skip declarative_metadata_sample_definition unless you need complete XML examples

This approach can reduce token consumption by 60-80% per file by excluding verbose WSDL definitions and lengthy examples.

Conceptual Approach to Using This Skill

Step 1: Identify Your Need

Ask yourself:

Step 2: Find the Right Type

Use one of these methods:

Step 3: Load Selectively (Section-Specific)

Decision Tree for Section Loading:

Need field definitions?
  → Load ONLY 'fields' section (~50-200 tokens)

Need to understand what the type does?
  → Load ONLY 'description' section (~20-100 tokens)

Need XML structure example?
  → Load ONLY 'declarative_metadata_sample_definition' (~100-300 tokens)

Need all three?
  → Load 'fields' + 'description' + 'declarative_metadata_sample_definition'
  → Still skip 'wsdl_segment', 'file_information', 'directory_location'
  → Savings: ~60-70% vs loading entire file

Need schema validation?
  → Only then load 'wsdl_segment' (this is verbose)

Request format:

Step 4: Apply to Your Code

Use the loaded information to:

File Location

All metadata type JSON files are located in:

assets/metadata_api/
├── CustomObject.json
├── Flow.json
├── ApexClass.json
├── Profile.json
└── ... (600 more files)

Path Resolution

When using this skill, files are referenced as:

The skill will automatically resolve paths based on the working directory.

Metadata File Generation Requirements

When generating Salesforce metadata XML files, follow these requirements to ensure valid, deployable files.

XML Structure Requirements

All metadata files must:

  1. Include XML declaration:

```xml

<?xml version="1.0" encoding="UTF-8"?>

```

  1. Use correct namespace:

```xml

<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">

```

  1. Match root element to metadata type:

Namespace Declaration

The namespace is required and must be exactly:

http://soap.sforce.com/2006/04/metadata

Correct:

<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">

Incorrect:

<CustomObject>  <!-- Missing namespace -->
<CustomObject xmlns="http://salesforce.com/metadata">  <!-- Wrong namespace -->

Required vs. Optional Fields

Each metadata type has different field requirements:

Example from CustomObject (note: practical authoring needs more than what required: true marks):

{
  "fields": {
    "nameField": {
      "type": "CustomField",
      "description": "The name field for the custom object",
      "required": true
    },
    "label": {
      "type": "string",
      "description": "The label for the custom object (effectively required for normal __c objects)",
      "required": false
    },
    "sharingModel": {
      "type": "SharingModel (enumeration)",
      "description": "The sharing model for the object (effectively required for normal __c objects)",
      "required": false
    },
    "enableHistory": {
      "type": "boolean",
      "description": "Enable field history tracking",
      "required": false
    }
  }
}

Validation Tips

Before deploying:

  1. Validate XML syntax: Ensure well-formed XML (matching tags, proper nesting)
  2. Check required fields: Verify all required fields are present
  3. Verify namespaces: Namespace must be exact
  4. Test field types: Ensure field values match expected types
  5. Use Salesforce CLI: Run sf project deploy validate to catch errors

More detail: field-type→XML mapping tables, file-naming/two-file/child-type conventions, and full well-formed-file examples are in CODE0.

Duplicate and Ambiguous Type Names

Some Metadata API type names also exist as Enterprise/Data API or Tooling API object names. Examples include ApexClass, ApexTrigger, CustomField, CustomObject, EmailTemplate, Layout, Profile, PermissionSet, RecordType, StaticResource, WebLink, ValidationRule, and Flow.

When the prompt is ambiguous (e.g., "tell me about Profile" or "what fields are on ApexClass"), ask whether the user wants:

  1. Metadata API XML structure for source/deployment authoring (this skill, e.g. .profile-meta.xml, .cls-meta.xml).
  2. Enterprise/Data API runtime sObject/record reference (no dedicated skill currently — fall back to the Salesforce API family router).
  3. Tooling API developer tooling record reference (no dedicated skill currently — fall back to the Salesforce API family router).

Heuristics that resolve most ambiguity without asking:

Default-when-no-signals rule: if the prompt has none of the signals above AND this skill (platform-metadata-api-context-get) was invoked directly by name, default to the Metadata API interpretation and explicitly disclose the assumption to the user (e.g., "Interpreting this as the Metadata API type for .cls-meta.xml authoring; let me know if you meant the Tooling API record or Enterprise/Data sObject"). The skill-invocation context itself is a signal of authoring/deployment intent.

Troubleshooting

File Not Found

Problem: Cannot find metadata type file

Solutions:

1. Normalize-and-substring (handles case + separator variants): strip non-alphanumeric characters and lowercase both the query and each index entry, then look for substring matches. Resolves: customobject, Custom_Object, Custom-Object → CustomObject.

2. On miss, fuzzy-match (handles missing-letter typos): use difflib.get_close_matches(query_normalized, index_normalized, n=3, cutoff=0.7) or Levenshtein distance ≤ 2. Resolves: customfeld → CustomField, apxclass → ApexClass. Pure substring matching cannot recover character deletions.

SOAP Envelope / Header Types (thin by design)

Two related patterns to recognize:

  1. Result types (AsyncResult, SaveResult, DeleteResult, UpsertResult, Error, DescribeMetadataResult, etc.) — fields is empty AND wsdl_segment is populated. These are SOAP response wrappers; their schema lives entirely in wsdl_segment. Consume that section if you need their structure. They are not deployable source files.
  2. SOAP request headers (AllOrNoneHeader, SessionHeader, CallOptions, DebuggingHeader, OwnerChangeOptions, etc.) — fields has 1–2 minimal entries, no wsdl_segment. These configure SOAP request behavior; they are call-time options, not metadata you author or deploy.

In both cases, the thin JSON output is correct. Don't try to author a .AsyncResult-meta.xml — these types have no source-file form.

Missing Section

Problem: Expected section not in JSON file

Solutions:

Incomplete Field Information

Problem: Field definition lacks details

Solutions:

Following Sub-Type Pointers (e.g., `ProfileObjectPermissions[]`)

When the fields section gives a complex type name like ProfileObjectPermissions[] or LayoutItem[] or ApprovalStep[], the sub-fields of that nested type are NOT in the fields section — they live in wsdl_segment for that complex type. The skill's "skip wsdl_segment by default" rule is for token economy on the simple-field path; for nested types you need to drill in.

Worked example — find the sub-fields of objectPermissions on Profile:

# 1. Get the field type name from the fields section
jq '.fields.objectPermissions' assets/metadata_api/Profile.json
# → {"type": "ProfileObjectPermissions[]", ...}

# 2. Pull just the matching complexType from wsdl_segment using grep -A
jq -r '.wsdl_segment' assets/metadata_api/Profile.json   | grep -A 30 'complexType name="ProfileObjectPermissions"'

The grep -A N window keeps token cost ~150 tokens instead of loading the whole wsdl_segment (which can be 5K+ tokens on large types). Use this pattern any time fields returns a Foo[] type and you need Foo's sub-fields.

XML Generation Errors

Problem: Generated XML fails validation

Solutions:

Deployment Failures

Problem: Metadata file won't deploy

Solutions:

Quick Reference: Common Metadata Types

Here are the most frequently used metadata types:

For a complete list of all metadata types, see Index Table.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.