Skip to main content
Glama
usama-dtc

Salesforce MCP Server

by usama-dtc

salesforce_query_records

Query Salesforce data using SOQL to retrieve records from any object, including parent-child relationships and custom fields with filtering options.

Instructions

Query records from any Salesforce object using SOQL, including relationship queries.

Examples:

  1. Parent-to-child query (e.g., Account with Contacts):

    • objectName: "Account"

    • fields: ["Name", "(SELECT Id, FirstName, LastName FROM Contacts)"]

  2. Child-to-parent query (e.g., Contact with Account details):

    • objectName: "Contact"

    • fields: ["FirstName", "LastName", "Account.Name", "Account.Industry"]

  3. Multiple level query (e.g., Contact -> Account -> Owner):

    • objectName: "Contact"

    • fields: ["Name", "Account.Name", "Account.Owner.Name"]

  4. Related object filtering:

    • objectName: "Contact"

    • fields: ["Name", "Account.Name"]

    • whereClause: "Account.Industry = 'Technology'"

Note: When using relationship fields:

  • Use dot notation for parent relationships (e.g., "Account.Name")

  • Use subqueries in parentheses for child relationships (e.g., "(SELECT Id FROM Contacts)")

  • Custom relationship fields end in "__r" (e.g., "CustomObject__r.Name")

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
objectNameYesAPI name of the object to query
fieldsYesList of fields to retrieve, including relationship fields
whereClauseNoWHERE clause, can include conditions on related objects
orderByNoORDER BY clause, can include fields from related objects
limitNoMaximum number of records to return

Implementation Reference

  • The core handler function `handleQueryRecords` that constructs and executes SOQL queries on Salesforce objects, supports relationship queries (parent/child), validates field syntax, formats nested results, and provides enhanced error handling for invalid fields/relationships.
    export async function handleQueryRecords(conn: any, args: QueryArgs) {
      const { objectName, fields, whereClause, orderBy, limit } = args;
    
      try {
        // Validate relationship field syntax
        const validation = validateRelationshipFields(fields);
        if (!validation.isValid) {
          return {
            content: [{
              type: "text",
              text: validation.error!
            }],
            isError: true,
          };
        }
    
        // Construct SOQL query
        let soql = `SELECT ${fields.join(', ')} FROM ${objectName}`;
        if (whereClause) soql += ` WHERE ${whereClause}`;
        if (orderBy) soql += ` ORDER BY ${orderBy}`;
        if (limit) soql += ` LIMIT ${limit}`;
    
        const result = await conn.query(soql);
        
        // Format the output
        const formattedRecords = result.records.map((record: any, index: number) => {
          const recordStr = fields.map(field => {
            // Handle special case for subqueries (child relationships)
            if (field.startsWith('(SELECT')) {
              const relationshipName = field.match(/FROM\s+(\w+)/)?.[1];
              if (!relationshipName) return `    ${field}: Invalid subquery format`;
              const childRecords = record[relationshipName];
              return `    ${relationshipName}: [${childRecords?.length || 0} records]`;
            }
            return '    ' + formatRelationshipResults(record, field);
          }).join('\n');
          return `Record ${index + 1}:\n${recordStr}`;
        }).join('\n\n');
    
        return {
          content: [{
            type: "text",
            text: `Query returned ${result.records.length} records:\n\n${formattedRecords}`
          }],
          isError: false,
        };
      } catch (error) {
        // Enhanced error handling for relationship queries
        const errorMessage = error instanceof Error ? error.message : String(error);
        let enhancedError = errorMessage;
    
        if (errorMessage.includes('INVALID_FIELD')) {
          // Try to identify which relationship field caused the error
          const fieldMatch = errorMessage.match(/(?:No such column |Invalid field: )['"]?([^'")\s]+)/);
          if (fieldMatch) {
            const invalidField = fieldMatch[1];
            if (invalidField.includes('.')) {
              enhancedError = `Invalid relationship field "${invalidField}". Please check:\n` +
                `1. The relationship name is correct\n` +
                `2. The field exists on the related object\n` +
                `3. You have access to the field\n` +
                `4. For custom relationships, ensure you're using '__r' suffix`;
            }
          }
        }
    
        return {
          content: [{
            type: "text",
            text: `Error executing query: ${enhancedError}`
          }],
          isError: true,
        };
      }
  • Tool schema definition `QUERY_RECORDS` specifying name, detailed description with relationship query examples, and inputSchema with properties for objectName, fields (array), optional whereClause, orderBy, limit.
    export const QUERY_RECORDS: Tool = {
      name: "salesforce_query_records",
      description: `Query records from any Salesforce object using SOQL, including relationship queries.
    
    Examples:
    1. Parent-to-child query (e.g., Account with Contacts):
       - objectName: "Account"
       - fields: ["Name", "(SELECT Id, FirstName, LastName FROM Contacts)"]
    
    2. Child-to-parent query (e.g., Contact with Account details):
       - objectName: "Contact"
       - fields: ["FirstName", "LastName", "Account.Name", "Account.Industry"]
    
    3. Multiple level query (e.g., Contact -> Account -> Owner):
       - objectName: "Contact"
       - fields: ["Name", "Account.Name", "Account.Owner.Name"]
    
    4. Related object filtering:
       - objectName: "Contact"
       - fields: ["Name", "Account.Name"]
       - whereClause: "Account.Industry = 'Technology'"
    
    Note: When using relationship fields:
    - Use dot notation for parent relationships (e.g., "Account.Name")
    - Use subqueries in parentheses for child relationships (e.g., "(SELECT Id FROM Contacts)")
    - Custom relationship fields end in "__r" (e.g., "CustomObject__r.Name")`,
      inputSchema: {
        type: "object",
        properties: {
          objectName: {
            type: "string",
            description: "API name of the object to query"
          },
          fields: {
            type: "array",
            items: { type: "string" },
            description: "List of fields to retrieve, including relationship fields"
          },
          whereClause: {
            type: "string",
            description: "WHERE clause, can include conditions on related objects",
            optional: true
          },
          orderBy: {
            type: "string",
            description: "ORDER BY clause, can include fields from related objects",
            optional: true
          },
          limit: {
            type: "number",
            description: "Maximum number of records to return",
            optional: true
          }
        },
        required: ["objectName", "fields"]
      }
    };
  • src/index.ts:69-83 (registration)
    Registration in the main CallToolRequestSchema handler: switch case for 'salesforce_query_records' that validates input arguments, performs type conversion to QueryArgs, and calls the handleQueryRecords function.
    case "salesforce_query_records": {
      const queryArgs = args as Record<string, unknown>;
      if (!queryArgs.objectName || !Array.isArray(queryArgs.fields)) {
        throw new Error('objectName and fields array are required for query');
      }
      // Type check and conversion
      const validatedArgs: QueryArgs = {
        objectName: queryArgs.objectName as string,
        fields: queryArgs.fields as string[],
        whereClause: queryArgs.whereClause as string | undefined,
        orderBy: queryArgs.orderBy as string | undefined,
        limit: queryArgs.limit as number | undefined
      };
      return await handleQueryRecords(conn, validatedArgs);
    }
  • src/index.ts:37-47 (registration)
    Tool list registration: Includes QUERY_RECORDS in the array returned by ListToolsRequestSchema handler.
      tools: [
        SEARCH_OBJECTS, 
        DESCRIBE_OBJECT, 
        QUERY_RECORDS, 
        DML_RECORDS,
        MANAGE_OBJECT,
        MANAGE_FIELD,
        SEARCH_ALL,
        UPLOAD_REPORT_XML  // Add new tool to the list
      ],
    }));
  • Helper function to validate relationship field syntax in queries, checking dot notation for parent relationships, depth limits, and subquery format for child relationships.
    function validateRelationshipFields(fields: string[]): { isValid: boolean; error?: string } {
      for (const field of fields) {
        // Check for parent relationship syntax (dot notation)
        if (field.includes('.')) {
          const parts = field.split('.');
          // Check for empty parts
          if (parts.some(part => !part)) {
            return {
              isValid: false,
              error: `Invalid relationship field format: "${field}". Relationship fields should use proper dot notation (e.g., "Account.Name")`
            };
          }
          // Check for too many levels (Salesforce typically limits to 5)
          if (parts.length > 5) {
            return {
              isValid: false,
              error: `Relationship field "${field}" exceeds maximum depth of 5 levels`
            };
          }
        }
    
        // Check for child relationship syntax (subqueries)
        if (field.includes('SELECT') && !field.match(/^\(SELECT.*FROM.*\)$/)) {
          return {
            isValid: false,
            error: `Invalid subquery format: "${field}". Child relationship queries should be wrapped in parentheses`
          };
        }
      }
    
      return { isValid: true };
    }
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It adds useful context about relationship query syntax (dot notation, subqueries, custom fields ending in '__r'), which helps the agent understand how to structure queries. However, it doesn't mention important behavioral traits like pagination, rate limits, authentication needs, or error handling, leaving gaps for a tool with 5 parameters and no output schema.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and front-loaded with the core purpose in the first sentence, followed by helpful examples. The examples are well-structured but slightly lengthy; every sentence earns its place by clarifying relationship query usage, though it could be more concise by integrating some explanatory notes into the examples themselves.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of a Salesforce query tool with 5 parameters, no annotations, and no output schema, the description is moderately complete. It covers the core functionality and relationship syntax well but lacks details on behavioral aspects (e.g., result format, error cases, limits) and doesn't fully compensate for the absence of an output schema, leaving the agent uncertain about what to expect from the tool's response.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all 5 parameters thoroughly. The description adds value by providing concrete examples that illustrate how to use parameters like fields and whereClause with relationship queries, but it doesn't add semantic meaning beyond what the schema descriptions already state. This meets the baseline of 3 for high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Query records from any Salesforce object using SOQL, including relationship queries.' This specifies the verb ('query'), resource ('records from any Salesforce object'), and method ('using SOQL'), distinguishing it from siblings like salesforce_dml_records (for data manipulation) and salesforce_search_all/search_objects (for search operations).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context for when to use this tool by emphasizing SOQL queries with relationship support, which implicitly differentiates it from search tools that might use different query languages or scopes. However, it doesn't explicitly state when NOT to use it or name specific alternatives among the siblings, such as when to prefer salesforce_search_all over this tool.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/usama-dtc/salesforce_mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server