{"title":"Define and register an agent programmatically (preview)","url":"https://jonas-paprotka.de/docs/dev-itpro/ai/ai-agent-sdk-define-register/","by":"JOP-AL","license":"Copyright (c) Microsoft Corporation. CC BY 4.0, https://creativecommons.org/licenses/by/4.0/; code samples MIT. From https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/ai/ai-agent-sdk-define-register, MicrosoftDocs/dynamics365smb-devitpro-pb at 828b6ee (2026-11-19). Changed: includes filled in, links to this site, and for agents shortened without dropping a fact.","credit":"Microsoft Corporation, CC BY 4.0","origin":"https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/ai/ai-agent-sdk-define-register","source":{"name":"Business Central developer and IT pro docs","repo":"https://github.com/MicrosoftDocs/dynamics365smb-devitpro-pb","commit":"828b6ee72fcd75755627cd6011f3d20899217ab2","date":"2026-11-19"},"checked":"2026-11-19","description":"Learn how to define and register AI agents programmatically in Dynamics 365 Business Central using the AI development toolkit.","date":"2026-10-02","meta":{"topic":"concept-article"},"outline":[{"level":1,"title":"Define and register an agent programmatically (preview)","slug":"define-and-register-an-agent-programmatically-preview","at":0,"chars":15448},{"level":2,"title":"Register the agent type","slug":"register-the-agent-type","at":952,"chars":567},{"level":2,"title":"Register the Copilot capability","slug":"register-the-copilot-capability","at":1519,"chars":1799},{"level":2,"title":"IAgentFactory interface","slug":"iagentfactory-interface","at":3318,"chars":3846},{"level":3,"title":"Define the setup page","slug":"define-the-setup-page","at":3564,"chars":811},{"level":3,"title":"Control agent instance creation","slug":"control-agent-instance-creation","at":4375,"chars":1817},{"level":3,"title":"Set the default profile","slug":"set-the-default-profile","at":6192,"chars":463},{"level":3,"title":"Set the default permissions","slug":"set-the-default-permissions","at":6655,"chars":509},{"level":2,"title":"IAgentMetadata interface","slug":"iagentmetadata-interface","at":7164,"chars":2183},{"level":3,"title":"Customize the task message review page","slug":"customize-the-task-message-review-page","at":7433,"chars":457},{"level":3,"title":"Add agent-level annotations","slug":"add-agent-level-annotations","at":7890,"chars":1075},{"level":3,"title":"Define a summary page with KPIs","slug":"define-a-summary-page-with-kpis","at":8965,"chars":382},{"level":2,"title":"IAgentTaskExecution interface","slug":"iagenttaskexecution-interface","at":9347,"chars":4558},{"level":3,"title":"Validate and post-process messages","slug":"validate-and-post-process-messages","at":9584,"chars":2281},{"level":3,"title":"Provide user intervention suggestions","slug":"provide-user-intervention-suggestions","at":11865,"chars":2040},{"level":2,"title":"IAgentArchiving interface","slug":"iagentarchiving-interface","at":13905,"chars":1040},{"level":2,"title":"Related information","slug":"related-information","at":14945,"chars":503}],"text":"# Define and register an agent programmatically (preview)\n[This article is prerelease documentation and is subject to change.]\n> IMPORTANT\n > This is a preview feature. Preview features might have restricted functionality and are subject to supplemental terms of use<https://www.microsoft.com/en-us/business-applications/legal/supp-powerplatform-preview/>.\n > The AI development toolkit is available in sandbox environments only. The Agent SDK for AL is available in sandbox environments and, starting from version 28.1, also in production environments.\n > This article is primarily intended for product owners, domain experts, consultants, and developers who want to experiment with AI capabilities in Business Central.\nTo define an agent in AL, you need to extend the enum that defines the available types of agents and to implement several interfaces that configure how the agent is created, how it presents itself in the UI, and how it runs tasks.\n## Register the agent type\nRegister your agent by extending the `Agent Metadata Provider` enum. This creates a unique identifier for your agent type and specifies which codeunits implement the required interfaces.\n```al\nenumextension 50101 \"My Agent Metadata Provider\" extends \"Agent Metadata Provider\"\n{\n    value(50101; \"My Agent\")\n    {\n        Caption = 'My Agent';\n        Implementation = IAgentFactory = MyAgentFactory,\n                         IAgentMetadata = MyAgentMetadata,\n                         IAgentTaskExecution = MyAgentTaskExecution;\n    }\n}\n```\n## Register the Copilot capability\nEach agent type must have a corresponding Copilot capability registered. This capability acts simultaneously as a feature switch and an overview for your agent. Register your capability by extending the `Copilot Capability` enum:\n```al\nenumextension 50100 \"My Agent Copilot Capability\" extends \"Copilot Capability\"\n{\n    value(50100; \"My Agent Capability\")\n    {\n        Caption = 'My Agent';\n    }\n}\n```\nThe capability enum value must be unique across all installed extensions. This capability is referenced by the IAgentFactory interface to link your agent type to its AI capabilities.\nThe Copilot capability must also be registered when your extension is installed. Use an install codeunit to register the capability with the `Copilot Capability` codeunit:\n```al\ncodeunit 50101 \"My Agent Install\"\n{\n    Subtype = Install;\n    Access = Internal;\n\n    trigger OnInstallAppPerDatabase()\n    begin\n        RegisterCapability();\n    end;\n\n    local procedure RegisterCapability()\n    var\n        CopilotCapability: Codeunit \"Copilot Capability\";\n        LearnMoreUrlTxt: Label 'link-to-your-documentation', Locked = true;\n    begin\n        if not CopilotCapability.IsCapabilityRegistered(Enum::\"Copilot Capability\"::\"My Agent Capability\") then\n            CopilotCapability.RegisterCapability(\n            Enum::\"Copilot Capability\"::\"My Agent Capability\",\n            Enum::\"Copilot Availability\"::Preview,\n            \"Copilot Billing Type\"::\"Microsoft Billed\",\n            LearnMoreUrlTxt);\n    end;\n}\n```\nThe RegisterCapability method takes the capability enum value, an availability level (such as Preview or GenerallyAvailable), and a URL to documentation about the capability. This registration makes your agent visible in the Copilot & AI Capabilities page.\n## IAgentFactory interface\nThe IAgentFactory interface defines how agent instances are created and configured. This interface is called by the agent framework when creating new agent instances or when displaying agent creation options in the UI.\n### Define the setup page\nThe GetFirstTimeSetupPageId method returns the ID of the page displayed when configuring a new agent instance for the first time. This is different from GetSetupPageId on the IAgentMetadata interface, which is used for subsequent configuration of existing agents.\nBoth methods typically return the same page ID, but they serve different purposes:\n GetFirstTimeSetupPageId (IAgentFactory): Called during initial agent creation\n GetSetupPageId (IAgentMetadata): Called when editing an existing agent's configuration\nThe source table of the setup page must contain a `User Security ID` field of type Guid. The runtime uses this field to provide the agent user ID when the page is opened.\n```al\nprocedure GetFirstTimeSetupPageId(): Integer\nbegin\n    exit(Page::\"My Agent Setup\");\nend;\n```\n### Control agent instance creation\nThe ShowCanCreateAgent method controls whether users can create new agent instances through the UI. This method allows for fine-grained control of agent instance creation. Returning false doesn't prevent programmatic creation of agents.\nCommon patterns for this method:\n Single-instance agent: Return true only if no instances of the agent exist\n Conditional creation: Return true only if specific licensing or configuration conditions are met\n Always allow creation: Always return true\n Creation only via code: Always return false\n```al\nprocedure ShowCanCreateAgent(): Boolean\nvar\n    MyAgentSetup: Record \"My Agent Setup\";\nbegin\n    // Example: Only allow one instance of this agent\n    exit(MyAgentSetup.IsEmpty());\nend;\n```\n> IMPORTANT\n> From version 28.1 and onward, agent discovery and creation isn't limited to agent administrators anymore. If you only want agent administrators to discover your agent, you need to implement ShowCanCreateAgent accordingly.\n```al\nprocedure ShowCanCreateAgent(): Boolean\nvar\n    AgentSystemPermissions: Codeunit \"Agent System Permissions\";\nbegin\n    // Example: Only allow agent creation for agent administrators.\n    exit(AgentSystemPermissions.CurrentUserHasCanManageAllAgentsPermission());\nend;\n```\n> NOTE\n> In addition to the ShowCanCreateAgent method, agent instance creation for extension agents is also governed by the Agent Configuration Rights page. This page allows agent administrators to define rules that restrict which non-administrator users can create specific agent types in specific companies. By default, a rule is inserted to allow all users to create all types of agents in all companies. See Understand agent visibility<ai-development-toolkit-agent-visibility> and Agent permissions<ai-development-toolkit-permissions>.\n### Set the default profile\nThe GetDefaultProfile method provides the default user profile assigned to new agent instances. The profile determines which Role Center and UI elements the agent uses when navigating the application.\n```al\nprocedure GetDefaultProfile(var TempAllProfile: Record \"All Profile\" temporary)\nbegin\n    TempAllProfile.\"Profile ID\" := 'ACCOUNTANT';\n    TempAllProfile.\"App ID\" := SystemApplicationAppId;\n    TempAllProfile.Insert();\nend;\n```\n### Set the default permissions\nThe GetDefaultAccessControls method provides the default permission sets assigned to new agent instances. These permissions determine what data and operations the agent can access.\n```al\nprocedure GetDefaultAccessControls(var TempAccessControlBuffer: Record \"Access Control Buffer\" temporary)\nbegin\n    TempAccessControlBuffer.\"Role ID\" := 'D365 BASIC';\n    TempAccessControlBuffer.Scope := TempAccessControlBuffer.Scope::System;\n    TempAccessControlBuffer.Insert();\nend;\n```\n## IAgentMetadata interface\nThe IAgentMetadata interface provides runtime metadata for individual agent instances. Unlike IAgentFactory, which handles creation, this interface is called during agent execution and UI rendering to retrieve instance-specific information.\n### Customize the task message review page\nThe GetAgentTaskMessagePageId method returns the ID of the page used to display agent task messages. The source table of this page must be the `Agent Task Message` table. If you don't need a custom message display, return the default `Page::\"Agent Task Message Card\"`.\n```al\nprocedure GetAgentTaskMessagePageId(AgentUserId: Guid; MessageId: Guid): Integer\nbegin\n    exit(Page::\"Agent Task Message Card\");\nend;\n```\n### Add agent-level annotations\nThe GetAgentAnnotations method returns annotations (errors or warnings) to display for the agent at the agent level. These annotations aren't persisted and are regularly requested by the server. Use this method to validate preconditions for agent operation, such as licensing requirements or the validity of its configuration.\n```al\nprocedure GetAgentAnnotations(AgentUserId: Guid; var Annotations: Record \"Agent Annotation\")\nvar\n    MyAgentLicenseMgt: Codeunit \"My Agent License Mgt.\";\n    LicenseMissingMsg: Label 'Agent license not found.';\n    LicenseMissingDetailsTxt: Label 'A premium license is required to use this agent. Please contact your administrator to add the necessary license.';\nbegin\n    Clear(Annotations);\n\n    if not MyAgentLicenseMgt.IsLicenseActive() then begin\n        Annotations.Code := 'LICENSE001';\n        Annotations.Severity := Annotations.Severity::Error;\n        Annotations.Message := LicenseMissingMsg;\n        Annotations.Details := LicenseMissingDetailsTxt;\n        Annotations.Insert();\n    end;\nend;\n```\n### Define a summary page with KPIs\nThe GetSummaryPageId method returns the ID of the page shown when users hover over the agent icons in the role center. This summary page displays important KPIs relevant to the agent. The page only supports displaying numeric values.\n```al\nprocedure GetSummaryPageId(AgentUserId: Guid): Integer\nbegin\n    exit(Page::\"My Agent Summary\");\nend;\n```\n## IAgentTaskExecution interface\nThe IAgentTaskExecution interface controls how agents process and execute tasks. These methods are executed in the context of the agent user and allow fine-tuning of agent behavior during task execution.\n### Validate and post-process messages\nThe AnalyzeAgentTaskMessage method analyzes the content of agent task messages and their attachments. This method is called for both input (incoming) and output (outgoing) messages, allowing you to validate inputs and post-process outputs.\nFor input messages, you can add annotations to flag issues:\n Error annotations stop the task from being processed further\n Warning annotations trigger a request for user intervention\nFor output messages, you can modify the content before it's sent (for example, adding an email signature).\n```al\nprocedure AnalyzeAgentTaskMessage(AgentTaskMessage: Record \"Agent Task Message\"; var Annotations: Record \"Agent Annotation\")\nbegin\n    if AgentTaskMessage.Type = AgentTaskMessage.Type::Output then\n        PostProcessOutputMessage(AgentTaskMessage)\n    else\n        ValidateInputMessage(AgentTaskMessage, Annotations);\nend;\n\nlocal procedure ValidateInputMessage(AgentTaskMessage: Record \"Agent Task Message\"; var Annotations: Record \"Agent Annotation\")\nvar\n    AgentMessage: Codeunit \"Agent Message\";\n    MyAgentRelevance: Codeunit \"My Agent Relevance\";\n    MessageText: Text;\n    NotRelevantMsg: Label 'This message does not appear to be relevant to sales order processing.';\n    NotRelevantDetailsTxt: Label 'The agent is designed to handle sales orders. Please provide a message related to sales order creation, updates, or inquiries.';\nbegin\n    MessageText := AgentMessage.GetText(AgentTaskMessage);\n\n    if not MyAgentRelevance.IsMessageRelevant(MessageText) then begin\n        Annotations.Code := 'RELEVANCE001';\n        Annotations.Severity := Annotations.Severity::Warning;\n        Annotations.Message := NotRelevantMsg;\n        Annotations.Details := NotRelevantDetailsTxt;\n        Annotations.Insert();\n    end;\nend;\n\nlocal procedure PostProcessOutputMessage(var AgentTaskMessage: Record \"Agent Task Message\")\nvar\n    AgentMessage: Codeunit \"Agent Message\";\n    OldText: Text;\n    SignatureTxt: Label '\\n\\nWritten with the help of AI\\n';\nbegin\n    OldText := AgentMessage.GetText(AgentTaskMessage);\n    AgentMessage.UpdateText(AgentTaskMessage, OldText + SignatureTxt);\nend;\n```\n> NOTE\n> For implementing relevance checks with Azure OpenAI, see ../developer/developer-tools-for-copilot-overview.\n### Provide user intervention suggestions\nThe GetAgentTaskUserInterventionSuggestions method provides contextual suggestions when the agent requests assistance. These suggestions help guide users on what actions they can take to help the agent complete its task.\nEach suggestion includes:\n Summary: A user-friendly title for the suggestion\n Description: Context about when this suggestion applies (used by the system to determine relevance)\n Instructions: Detailed steps for the agent to follow\n```al\nprocedure GetAgentTaskUserInterventionSuggestions(\n    AgentTaskUserInterventionRequestDetails: Record \"Agent User Int Request Details\";\n    var Suggestions: Record \"Agent Task User Int Suggestion\")\nvar\n    ApproveSalesOrderLbl: Label 'Approve the sales order';\n    // Descriptions are locked as they are used internally to decide relevance\n    ApproveSalesOrderDescriptionLbl: Label 'Use when the agent needs approval to proceed with a sales order.', Locked = true;\n    ApproveSalesOrderInstructionsLbl: Label 'Review the sales order details and click Approve if everything is correct.';\n    ProvideMissingCustomerInfoLbl: Label 'Provide missing customer information';\n    ProvideMissingCustomerInfoDescriptionLbl: Label 'Use when customer data is incomplete or invalid.', Locked = true;\n    ProvideMissingCustomerInfoInstructionsLbl: Label 'Update the customer record with the correct information, then retry the task.';\nbegin\n    if AgentTaskUserInterventionRequestDetails.Type = AgentTaskUserInterventionRequestDetails.Type::Assistance then begin\n        Suggestions.Summary := ApproveSalesOrderLbl;\n        Suggestions.Description := ApproveSalesOrderDescriptionLbl;\n        Suggestions.Instructions := ApproveSalesOrderInstructionsLbl;\n        Suggestions.Insert();\n\n        Suggestions.Summary := ProvideMissingCustomerInfoLbl;\n        Suggestions.Description := ProvideMissingCustomerInfoDescriptionLbl;\n        Suggestions.Instructions := ProvideMissingCustomerInfoInstructionsLbl;\n        Suggestions.Insert();\n    end;\nend;\n```\n## IAgentArchiving interface\n> APPLIES TO: Business Central 2026 release wave 2 and later\nThe IAgentArchiving interface<https://learn.microsoft.com/dynamics365/business-central/application/system-application/interface/system.agents.iagentarchiving> defines how your agent type takes part in archiving. It currently contains the IsArchivingSupported<https://learn.microsoft.com/dynamics365/business-central/application/system-application/interface/system.agents.iagentarchiving#isarchivingsupported> method, which controls whether users can archive agents of your type.\nArchiving is supported by default: agent types that don't specify IAgentArchiving in the Implementation list use the default implementation, which returns true. If your agent type needs specific handling as part of archiving that isn't in place yet, you can opt out by implementing IAgentArchiving and returning false from IsArchivingSupported.\nWhen the method returns false, the Archive action fails with a message stating that the agent type doesn't support archiving.\n## Related information\nCoding agents in AL (preview)<ai-agent-sdk-overview>\nAgent setup and configuration (preview)<ai-agent-sdk-configuration>\nUnderstand agent visibility (preview)<ai-development-toolkit-agent-visibility#archived-agents>\nManaging agent tasks programmatically (preview)<ai-agent-sdk-tasks>\nOverview (preview)<https://learn.microsoft.com/dynamics365/business-central/dev-itpro/ai/ai-development-toolkit-landing-page>\nDesigning and coding agents (preview)<ai-development-toolkit-overview>"}