Skip to main content
Glama
simonl77

Salesforce MCP Server

by simonl77

salesforce_manage_field_permissions

Manage Salesforce field permissions by granting, revoking, or viewing read/edit access for profiles and permission sets on custom and standard fields.

Instructions

Manage Field Level Security (Field Permissions) for custom and standard fields.

  • Grant or revoke read/edit access to fields for specific profiles or permission sets

  • View current field permissions

  • Bulk update permissions for multiple profiles

Examples:

  1. Grant System Administrator access to a field

  2. Give read-only access to a field for specific profiles

  3. Check which profiles have access to a field

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
operationYesOperation to perform on field permissions
objectNameYesAPI name of the object (e.g., 'Account', 'Custom_Object__c')
fieldNameYesAPI name of the field (e.g., 'Custom_Field__c')
profileNamesNoNames of profiles to grant/revoke access (e.g., ['System Administrator', 'Sales User'])
readableNoGrant/revoke read access (default: true)
editableNoGrant/revoke edit access (default: true)

Implementation Reference

  • The core handler function implementing the tool logic for managing Salesforce field permissions (grant, revoke, view) using SOQL queries and DML operations on FieldPermissions object.
    export async function handleManageFieldPermissions(conn: any, args: ManageFieldPermissionsArgs) {
      const { operation, objectName, fieldName, readable = true, editable = true } = args;
      let { profileNames } = args;
    
      try {
        // Ensure field name has __c suffix if it's a custom field and doesn't already have it
        const fieldApiName = fieldName.endsWith('__c') || fieldName.includes('.') ? fieldName : `${fieldName}__c`;
        const fullFieldName = `${objectName}.${fieldApiName}`;
    
        if (operation === 'view') {
          // Query existing field permissions
          const permissionsQuery = `
            SELECT Id, Parent.ProfileId, Parent.Profile.Name, Parent.IsOwnedByProfile,
                   Parent.PermissionSetId, Parent.PermissionSet.Name,
                   Field, PermissionsRead, PermissionsEdit
            FROM FieldPermissions
            WHERE SobjectType = '${objectName}'
            AND Field = '${fullFieldName}'
            ORDER BY Parent.Profile.Name
          `;
    
          const result = await conn.query(permissionsQuery);
          
          if (result.records.length === 0) {
            return {
              content: [{
                type: "text",
                text: `No field permissions found for ${fullFieldName}. This field might not have any specific permissions set, or it might be universally accessible.`
              }],
              isError: false,
            };
          }
    
          let responseText = `Field permissions for ${fullFieldName}:\n\n`;
          
          result.records.forEach((perm: any) => {
            const name = perm.Parent.IsOwnedByProfile 
              ? perm.Parent.Profile?.Name 
              : perm.Parent.PermissionSet?.Name;
            const type = perm.Parent.IsOwnedByProfile ? 'Profile' : 'Permission Set';
            
            responseText += `${type}: ${name}\n`;
            responseText += `  - Read Access: ${perm.PermissionsRead ? 'Yes' : 'No'}\n`;
            responseText += `  - Edit Access: ${perm.PermissionsEdit ? 'Yes' : 'No'}\n\n`;
          });
    
          return {
            content: [{
              type: "text",
              text: responseText
            }],
            isError: false,
          };
        }
    
        // For grant/revoke operations
        if (!profileNames || profileNames.length === 0) {
          // If no profiles specified, default to System Administrator
          profileNames = ['System Administrator'];
        }
    
        // Get profile IDs
        const profileQuery = await conn.query(`
          SELECT Id, Name 
          FROM Profile 
          WHERE Name IN (${profileNames.map(name => `'${name}'`).join(', ')})
        `);
    
        if (profileQuery.records.length === 0) {
          return {
            content: [{
              type: "text",
              text: `No profiles found matching: ${profileNames.join(', ')}`
            }],
            isError: true,
          };
        }
    
        const results: any[] = [];
        const errors: string[] = [];
    
        for (const profile of profileQuery.records) {
          try {
            if (operation === 'grant') {
              // First, check if permission already exists
              const existingPerm = await conn.query(`
                SELECT Id, PermissionsRead, PermissionsEdit
                FROM FieldPermissions
                WHERE ParentId IN (
                  SELECT Id FROM PermissionSet 
                  WHERE IsOwnedByProfile = true 
                  AND ProfileId = '${profile.Id}'
                )
                AND Field = '${fullFieldName}'
                AND SobjectType = '${objectName}'
                LIMIT 1
              `);
    
              if (existingPerm.records.length > 0) {
                // Update existing permission
                const updateResult = await conn.sobject('FieldPermissions').update({
                  Id: existingPerm.records[0].Id,
                  PermissionsRead: readable,
                  PermissionsEdit: editable && readable // Edit requires read
                });
                
                results.push({
                  profile: profile.Name,
                  action: 'updated',
                  success: updateResult.success
                });
              } else {
                // Get the PermissionSet ID for this profile
                const permSetQuery = await conn.query(`
                  SELECT Id FROM PermissionSet 
                  WHERE IsOwnedByProfile = true 
                  AND ProfileId = '${profile.Id}'
                  LIMIT 1
                `);
    
                if (permSetQuery.records.length > 0) {
                  // Create new permission
                  const createResult = await conn.sobject('FieldPermissions').create({
                    ParentId: permSetQuery.records[0].Id,
                    SobjectType: objectName,
                    Field: fullFieldName,
                    PermissionsRead: readable,
                    PermissionsEdit: editable && readable // Edit requires read
                  });
    
                  results.push({
                    profile: profile.Name,
                    action: 'created',
                    success: createResult.success
                  });
                } else {
                  errors.push(`Could not find permission set for profile: ${profile.Name}`);
                }
              }
            } else if (operation === 'revoke') {
              // Find and delete the permission
              const existingPerm = await conn.query(`
                SELECT Id
                FROM FieldPermissions
                WHERE ParentId IN (
                  SELECT Id FROM PermissionSet 
                  WHERE IsOwnedByProfile = true 
                  AND ProfileId = '${profile.Id}'
                )
                AND Field = '${fullFieldName}'
                AND SobjectType = '${objectName}'
                LIMIT 1
              `);
    
              if (existingPerm.records.length > 0) {
                const deleteResult = await conn.sobject('FieldPermissions').delete(existingPerm.records[0].Id);
                results.push({
                  profile: profile.Name,
                  action: 'revoked',
                  success: true
                });
              } else {
                results.push({
                  profile: profile.Name,
                  action: 'no permission found',
                  success: true
                });
              }
            }
          } catch (error) {
            errors.push(`${profile.Name}: ${error instanceof Error ? error.message : String(error)}`);
          }
        }
    
        // Format response
        let responseText = `Field permission ${operation} operation completed for ${fullFieldName}:\n\n`;
        
        const successful = results.filter(r => r.success);
        const failed = results.filter(r => !r.success);
        
        if (successful.length > 0) {
          responseText += 'Successful:\n';
          successful.forEach(r => {
            responseText += `  - ${r.profile}: ${r.action}\n`;
          });
        }
        
        if (failed.length > 0 || errors.length > 0) {
          responseText += '\nFailed:\n';
          failed.forEach(r => {
            responseText += `  - ${r.profile}: ${r.action}\n`;
          });
          errors.forEach(e => {
            responseText += `  - ${e}\n`;
          });
        }
    
        if (operation === 'grant') {
          responseText += `\nPermissions granted:\n  - Read: ${readable ? 'Yes' : 'No'}\n  - Edit: ${editable ? 'Yes' : 'No'}`;
        }
    
        return {
          content: [{
            type: "text",
            text: responseText
          }],
          isError: false,
        };
    
      } catch (error) {
        return {
          content: [{
            type: "text",
            text: `Error managing field permissions: ${error instanceof Error ? error.message : String(error)}`
          }],
          isError: true,
        };
      }
  • Tool schema definition including name, description, and inputSchema for validating tool arguments.
    export const MANAGE_FIELD_PERMISSIONS: Tool = {
      name: "salesforce_manage_field_permissions",
      description: `Manage Field Level Security (Field Permissions) for custom and standard fields.
      - Grant or revoke read/edit access to fields for specific profiles or permission sets
      - View current field permissions
      - Bulk update permissions for multiple profiles
      
      Examples:
      1. Grant System Administrator access to a field
      2. Give read-only access to a field for specific profiles
      3. Check which profiles have access to a field`,
      inputSchema: {
        type: "object",
        properties: {
          operation: {
            type: "string",
            enum: ["grant", "revoke", "view"],
            description: "Operation to perform on field permissions"
          },
          objectName: {
            type: "string",
            description: "API name of the object (e.g., 'Account', 'Custom_Object__c')"
          },
          fieldName: {
            type: "string",
            description: "API name of the field (e.g., 'Custom_Field__c')"
          },
          profileNames: {
            type: "array",
            items: { type: "string" },
            description: "Names of profiles to grant/revoke access (e.g., ['System Administrator', 'Sales User'])",
            optional: true
          },
          readable: {
            type: "boolean",
            description: "Grant/revoke read access (default: true)",
            optional: true
          },
          editable: {
            type: "boolean",
            description: "Grant/revoke edit access (default: true)",
            optional: true
          }
        },
        required: ["operation", "objectName", "fieldName"]
      }
    };
  • src/index.ts:180-194 (registration)
    Switch case registration in the main tool dispatcher that validates arguments and calls the handleManageFieldPermissions function.
    case "salesforce_manage_field_permissions": {
      const permArgs = args as Record<string, unknown>;
      if (!permArgs.operation || !permArgs.objectName || !permArgs.fieldName) {
        throw new Error('operation, objectName, and fieldName are required for field permissions management');
      }
      const validatedArgs: ManageFieldPermissionsArgs = {
        operation: permArgs.operation as 'grant' | 'revoke' | 'view',
        objectName: permArgs.objectName as string,
        fieldName: permArgs.fieldName as string,
        profileNames: permArgs.profileNames as string[] | undefined,
        readable: permArgs.readable as boolean | undefined,
        editable: permArgs.editable as boolean | undefined
      };
      return await handleManageFieldPermissions(conn, validatedArgs);
    }
  • src/index.ts:47-62 (registration)
    Inclusion of the MANAGE_FIELD_PERMISSIONS tool in the listTools response.
      SEARCH_OBJECTS, 
      DESCRIBE_OBJECT, 
      QUERY_RECORDS, 
      AGGREGATE_QUERY,
      DML_RECORDS,
      MANAGE_OBJECT,
      MANAGE_FIELD,
      MANAGE_FIELD_PERMISSIONS,
      SEARCH_ALL,
      READ_APEX,
      WRITE_APEX,
      READ_APEX_TRIGGER,
      WRITE_APEX_TRIGGER,
      EXECUTE_ANONYMOUS,
      MANAGE_DEBUG_LOGS
    ],
  • src/index.ts:19-19 (registration)
    Import of the tool schema, handler, and types from the implementation file.
    import { MANAGE_FIELD_PERMISSIONS, handleManageFieldPermissions, ManageFieldPermissionsArgs } from "./tools/manageFieldPermissions.js";
Behavior2/5

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

With no annotations provided, the description carries full burden but offers limited behavioral insight. It mentions operations (grant/revoke/view) and bulk updates, but doesn't disclose critical traits like required permissions, whether changes are reversible, rate limits, or what the response looks like (no output schema). For a mutation tool with security implications, this is a significant gap.

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 well-structured with a clear opening sentence followed by bullet points and examples. It avoids redundancy, though the examples partially restate the bullet points. Every sentence contributes to understanding, but slight trimming of the examples could improve efficiency without losing clarity.

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

Completeness2/5

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

For a complex security management tool with 6 parameters, no annotations, and no output schema, the description is incomplete. It lacks details on error conditions, side effects (e.g., impact on existing permissions), response format, and integration with sibling tools. The examples help but don't compensate for missing behavioral and operational context.

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%, providing baseline documentation for all 6 parameters. The description adds minimal value beyond the schema—it mentions 'profiles or permission sets' (hinting at profileNames usage) and 'read/edit access' (relating to readable/editable), but doesn't clarify parameter interactions (e.g., how profileNames interacts with operation='view') or provide syntax examples beyond what the schema already offers.

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 with specific verbs ('Manage Field Level Security', 'Grant or revoke', 'View', 'Bulk update') and resources ('custom and standard fields', 'profiles or permission sets'). It distinguishes itself from sibling tools like salesforce_manage_field or salesforce_manage_object by focusing specifically on field permissions rather than field/object metadata or DML operations.

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

Usage Guidelines3/5

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

The description implies usage through examples (e.g., 'Grant System Administrator access to a field'), but lacks explicit guidance on when to use this tool versus alternatives like salesforce_manage_field for field metadata or salesforce_dml_records for data manipulation. No clear exclusions or prerequisites are stated, leaving the agent to infer context from the examples.

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/simonl77/mcp-server-salesforce'

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