Skip to main content
Glama
mwhesse

Dataverse MCP Server

by mwhesse

Create AutoNumber Column

create_autonumber_column

Add an AutoNumber column to Dataverse tables that automatically generates unique alphanumeric identifiers using sequential numbers, random strings, and datetime placeholders with custom formatting.

Instructions

Creates a new AutoNumber column in a Dataverse table with specified format. AutoNumber columns automatically generate alphanumeric strings using sequential numbers, random strings, and datetime placeholders. Requires a solution context to be set first.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
autoNumberFormatYesAutoNumber format using placeholders like "PREFIX-{SEQNUM:4}-{RANDSTRING:3}-{DATETIMEUTC:yyyyMMdd}"
descriptionNoDescription of the AutoNumber column
displayNameYesDisplay name for the AutoNumber column (e.g., "Serial Number")
entityLogicalNameYesLogical name of the table to add the AutoNumber column to
isAuditEnabledNoWhether auditing is enabled for this column
isValidForAdvancedFindNoWhether the column appears in Advanced Find
isValidForCreateNoWhether the column can be set during create
isValidForUpdateNoWhether the column can be updated
maxLengthNoMaximum length for the column (default: 100, ensure enough room for format expansion)
requiredLevelNoRequired level of the columnNone
schemaNameNoSchema name for the column (auto-generated if not provided)

Implementation Reference

  • The core handler function that implements the 'create_autonumber_column' tool logic. It retrieves the customization prefix, generates schema names, constructs the AutoNumber column metadata, and creates the column via the Dataverse Metadata API.
      async (params) => {
      
        try {
          // Get the customization prefix from the solution context
          const prefix = client.getCustomizationPrefix();
          if (!prefix) {
            throw new Error('No customization prefix available. Please set a solution context using set_solution_context tool first.');
          }
    
          // Generate schema name if not provided
          const schemaName = params.schemaName || generateColumnSchemaName(params.displayName, prefix);
    
          // Prepare the column metadata
          const columnMetadata = {
            "@odata.type": "Microsoft.Dynamics.CRM.StringAttributeMetadata",
            "AttributeType": "String",
            "SchemaName": schemaName,
            "DisplayName": createLocalizedLabel(params.displayName),
            "Format": "Text", // Required for AutoNumber columns
            "AutoNumberFormat": params.autoNumberFormat,
            "RequiredLevel": {
              "Value": params.requiredLevel,
              "CanBeChanged": true,
              "ManagedPropertyLogicalName": "canmodifyrequirementlevelsettings"
            },
            "MaxLength": params.maxLength,
            "IsCustomAttribute": true,
            ...(params.description && {
              "Description": createLocalizedLabel(params.description)
            }),
            ...(params.isAuditEnabled !== undefined && {
              "IsAuditEnabled": {
                "Value": params.isAuditEnabled,
                "CanBeChanged": true,
                "ManagedPropertyLogicalName": "canmodifyauditsettings"
              }
            }),
            ...(params.isValidForAdvancedFind !== undefined && { "IsValidForAdvancedFind": params.isValidForAdvancedFind }),
            ...(params.isValidForCreate !== undefined && { "IsValidForCreate": params.isValidForCreate }),
            ...(params.isValidForUpdate !== undefined && { "IsValidForUpdate": params.isValidForUpdate })
          };
    
          const result = await client.postMetadata(
            `EntityDefinitions(LogicalName='${params.entityLogicalName}')/Attributes`,
            columnMetadata
          );
    
          return {
            content: [
              {
                type: "text",
                text: `Successfully created AutoNumber column '${schemaName}' with display name '${params.displayName}' in table '${params.entityLogicalName}'.\n\nAutoNumber Format: ${params.autoNumberFormat}\nMax Length: ${params.maxLength}\nRequired Level: ${params.requiredLevel}\n\nResponse: ${JSON.stringify(result, null, 2)}`
              }
            ]
          };
    
        } catch (error: any) {
          // Provide specific error messages for common issues
          let errorMessage = `Error creating AutoNumber column: ${error instanceof Error ? error.message : 'Unknown error'}`;
          
          if (error.message?.includes('Invalid Argument')) {
            errorMessage += '\n\nTip: Check AutoNumber format syntax. Use {SEQNUM:length}, {RANDSTRING:1-6}, {DATETIMEUTC:format}';
          }
          
          return {
            content: [
              {
                type: "text",
                text: errorMessage
              }
            ],
            isError: true
          };
        }
      }
    );
  • The tool specification including title, description, and Zod inputSchema for validating parameters like entityLogicalName, displayName, autoNumberFormat (validated by autoNumberFormatSchema), requiredLevel, maxLength, etc.
    {
      title: 'Create AutoNumber Column',
      description: 'Creates a new AutoNumber column in a Dataverse table with specified format. AutoNumber columns automatically generate alphanumeric strings using sequential numbers, random strings, and datetime placeholders. Requires a solution context to be set first.',
      inputSchema: {
        entityLogicalName: z.string().describe('Logical name of the table to add the AutoNumber column to'),
        displayName: z.string().describe('Display name for the AutoNumber column (e.g., "Serial Number")'),
        schemaName: z.string().optional().describe('Schema name for the column (auto-generated if not provided)'),
        description: z.string().optional().describe('Description of the AutoNumber column'),
        autoNumberFormat: autoNumberFormatSchema.describe('AutoNumber format using placeholders like "PREFIX-{SEQNUM:4}-{RANDSTRING:3}-{DATETIMEUTC:yyyyMMdd}"'),
        requiredLevel: z.enum(['None', 'SystemRequired', 'ApplicationRequired', 'Recommended']).default('None').describe('Required level of the column'),
        maxLength: z.number().min(1).max(4000).default(100).describe('Maximum length for the column (default: 100, ensure enough room for format expansion)'),
        isAuditEnabled: z.boolean().optional().describe('Whether auditing is enabled for this column'),
        isValidForAdvancedFind: z.boolean().optional().describe('Whether the column appears in Advanced Find'),
        isValidForCreate: z.boolean().optional().describe('Whether the column can be set during create'),
        isValidForUpdate: z.boolean().optional().describe('Whether the column can be updated')
      }
    },
  • The exported createAutoNumberColumnTool function that calls server.registerTool to register the 'create_autonumber_column' tool with its schema and handler.
    export function createAutoNumberColumnTool(server: McpServer, client: DataverseClient) {
      server.registerTool(
        'create_autonumber_column',
        {
          title: 'Create AutoNumber Column',
          description: 'Creates a new AutoNumber column in a Dataverse table with specified format. AutoNumber columns automatically generate alphanumeric strings using sequential numbers, random strings, and datetime placeholders. Requires a solution context to be set first.',
          inputSchema: {
            entityLogicalName: z.string().describe('Logical name of the table to add the AutoNumber column to'),
            displayName: z.string().describe('Display name for the AutoNumber column (e.g., "Serial Number")'),
            schemaName: z.string().optional().describe('Schema name for the column (auto-generated if not provided)'),
            description: z.string().optional().describe('Description of the AutoNumber column'),
            autoNumberFormat: autoNumberFormatSchema.describe('AutoNumber format using placeholders like "PREFIX-{SEQNUM:4}-{RANDSTRING:3}-{DATETIMEUTC:yyyyMMdd}"'),
            requiredLevel: z.enum(['None', 'SystemRequired', 'ApplicationRequired', 'Recommended']).default('None').describe('Required level of the column'),
            maxLength: z.number().min(1).max(4000).default(100).describe('Maximum length for the column (default: 100, ensure enough room for format expansion)'),
            isAuditEnabled: z.boolean().optional().describe('Whether auditing is enabled for this column'),
            isValidForAdvancedFind: z.boolean().optional().describe('Whether the column appears in Advanced Find'),
            isValidForCreate: z.boolean().optional().describe('Whether the column can be set during create'),
            isValidForUpdate: z.boolean().optional().describe('Whether the column can be updated')
          }
        },
        async (params) => {
        
          try {
            // Get the customization prefix from the solution context
            const prefix = client.getCustomizationPrefix();
            if (!prefix) {
              throw new Error('No customization prefix available. Please set a solution context using set_solution_context tool first.');
            }
    
            // Generate schema name if not provided
            const schemaName = params.schemaName || generateColumnSchemaName(params.displayName, prefix);
    
            // Prepare the column metadata
            const columnMetadata = {
              "@odata.type": "Microsoft.Dynamics.CRM.StringAttributeMetadata",
              "AttributeType": "String",
              "SchemaName": schemaName,
              "DisplayName": createLocalizedLabel(params.displayName),
              "Format": "Text", // Required for AutoNumber columns
              "AutoNumberFormat": params.autoNumberFormat,
              "RequiredLevel": {
                "Value": params.requiredLevel,
                "CanBeChanged": true,
                "ManagedPropertyLogicalName": "canmodifyrequirementlevelsettings"
              },
              "MaxLength": params.maxLength,
              "IsCustomAttribute": true,
              ...(params.description && {
                "Description": createLocalizedLabel(params.description)
              }),
              ...(params.isAuditEnabled !== undefined && {
                "IsAuditEnabled": {
                  "Value": params.isAuditEnabled,
                  "CanBeChanged": true,
                  "ManagedPropertyLogicalName": "canmodifyauditsettings"
                }
              }),
              ...(params.isValidForAdvancedFind !== undefined && { "IsValidForAdvancedFind": params.isValidForAdvancedFind }),
              ...(params.isValidForCreate !== undefined && { "IsValidForCreate": params.isValidForCreate }),
              ...(params.isValidForUpdate !== undefined && { "IsValidForUpdate": params.isValidForUpdate })
            };
    
            const result = await client.postMetadata(
              `EntityDefinitions(LogicalName='${params.entityLogicalName}')/Attributes`,
              columnMetadata
            );
    
            return {
              content: [
                {
                  type: "text",
                  text: `Successfully created AutoNumber column '${schemaName}' with display name '${params.displayName}' in table '${params.entityLogicalName}'.\n\nAutoNumber Format: ${params.autoNumberFormat}\nMax Length: ${params.maxLength}\nRequired Level: ${params.requiredLevel}\n\nResponse: ${JSON.stringify(result, null, 2)}`
                }
              ]
            };
    
          } catch (error: any) {
            // Provide specific error messages for common issues
            let errorMessage = `Error creating AutoNumber column: ${error instanceof Error ? error.message : 'Unknown error'}`;
            
            if (error.message?.includes('Invalid Argument')) {
              errorMessage += '\n\nTip: Check AutoNumber format syntax. Use {SEQNUM:length}, {RANDSTRING:1-6}, {DATETIMEUTC:format}';
            }
            
            return {
              content: [
                {
                  type: "text",
                  text: errorMessage
                }
              ],
              isError: true
            };
          }
        }
      );
    }
  • src/index.ts:240-240 (registration)
    Invocation of createAutoNumberColumnTool in the main index file, which executes the registration of the tool.
    createAutoNumberColumnTool(server, dataverseClient);
  • Zod refinement schema used to validate the autoNumberFormat parameter, ensuring valid placeholders and length constraints for RANDSTRING (1-6) and SEQNUM (>=1).
    const autoNumberFormatSchema = z.string().refine((format) => {
      // Validate AutoNumber format placeholders
      const validPlaceholders = /^[^{}]*(\{(SEQNUM|RANDSTRING|DATETIMEUTC):[0-9]+\}[^{}]*)*$/;
      const hasValidPlaceholders = validPlaceholders.test(format);
      
      // Check RANDSTRING length constraints (1-6)
      const randStringMatches = format.match(/\{RANDSTRING:(\d+)\}/g);
      if (randStringMatches) {
        for (const match of randStringMatches) {
          const length = parseInt(match.match(/\{RANDSTRING:(\d+)\}/)![1]);
          if (length < 1 || length > 6) {
            return false;
          }
        }
      }
      
      // Check SEQNUM length constraints (minimum 1)
      const seqNumMatches = format.match(/\{SEQNUM:(\d+)\}/g);
      if (seqNumMatches) {
        for (const match of seqNumMatches) {
          const length = parseInt(match.match(/\{SEQNUM:(\d+)\}/)![1]);
          if (length < 1) {
            return false;
          }
        }
      }
      
      return hasValidPlaceholders;
    }, {
      message: "Invalid AutoNumber format. Use placeholders like {SEQNUM:4}, {RANDSTRING:3} (1-6), {DATETIMEUTC:yyyyMMdd}"
    });
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. It discloses that the tool creates a new column (implying a write operation) and mentions a prerequisite, but lacks details on permissions, side effects, error handling, or response format. The description adds some behavioral context but is incomplete for a mutation tool.

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

Conciseness5/5

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

The description is two sentences, front-loaded with the core purpose and followed by additional context. Every sentence earns its place: the first defines the tool, the second explains AutoNumber functionality, and the third states a critical prerequisite. No wasted words.

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?

For a mutation tool with 11 parameters, no annotations, and no output schema, the description is adequate but has gaps. It covers the purpose and a key prerequisite, but lacks details on behavioral traits like permissions, idempotency, or return values. Given the complexity, it should provide more guidance on usage and outcomes.

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 fully documents all 11 parameters. The description adds minimal value by mentioning 'specified format' which relates to 'autoNumberFormat', but does not elaborate on parameter interactions or usage beyond what the schema provides. Baseline 3 is appropriate given 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 action ('Creates'), the resource ('new AutoNumber column in a Dataverse table'), and the key feature ('with specified format'). It distinguishes from siblings like 'create_dataverse_column' by specifying the AutoNumber type and from 'convert_to_autonumber' by indicating creation rather than conversion.

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 explicitly states a prerequisite ('Requires a solution context to be set first'), which provides clear when-to-use guidance. However, it does not mention when not to use this tool or name specific alternatives among siblings, such as 'create_dataverse_column' for non-AutoNumber columns.

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/mwhesse/mcp-dataverse'

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