Onboarding an AWS AgentCore agent to Microsoft Agent 365 and Entra Agent ID: identity, governance, data security and observability, with no sidecar.

An agent that runs on AWS can be governed by Microsoft like an agent that runs on Azure. Two earlier articles showed parts of that:

This article puts the whole thing together for one AgentCore agent, from nothing to a governed agent, and adds the parts the earlier articles didn’t cover:

  • onboarding as code: the blueprint, the agent identity and every permission grant come from two YAML files, through pull requests and an approval step;
  • governance: sponsors, least-privilege grants, Conditional Access for agents, and who may call the agent;
  • the no-sidecar token exchange, in full, in .NET (Microsoft.Identity.Web) and in Python (by hand);
  • observability with the Agent 365 SDK, and exactly what lands in the unified audit log, Defender and Purview;
  • data security: Microsoft Purview DLP checking the agent’s prompts and answers inline;
  • as an optional extra, publishing through Agent 365’s request process: what works, and why offering the agent as an instance in Teams needs a front end in front of AgentCore.

It is self-contained: you don’t need the earlier articles to follow it.

What was tested, on AgentCore Runtime, in November 2026: a Python agent (LangChain, an Amazon Bedrock model, one MCP tool server) and a .NET agent (Microsoft.Identity.Web), both running as the AgentCore agent identity. Callers without a valid token, or with a token for a different blueprint, were rejected before the container ran; the token chain produced app-only, on-behalf-of and telemetry tokens with the expected claims; a signed-in user’s question was answered through an MCP tool that accepts only Entra tokens; the activity appeared in the unified audit log and in Defender; and a prompt containing a credit card number, sent as a signed-in user, was blocked by a Purview DLP policy scoped to the agent. So the end-to-end onboarding, governance, token exchange, observability and DLP all work on AgentCore. Offering the agent as an Agent 365 instance in Teams is an optional extra on top of that, and it wasn’t achieved: publishing through Agent 365’s request process got as far as an available template, but creating an instance needs a front end in front of AgentCore and a license for the instance’s agent user. The optional section near the end explains why, and the appendix has the step-by-step results.

Status of the APIs. Entra Agent ID, the Agent Registration API, the Agent 365 SDKs and CLI, Conditional Access for agents, the Purview data security APIs for AI apps and AgentCore’s inbound JWT authorization were in preview or recently released when this was written (November 2026). Names, permissions, defaults, portal locations and endpoints may change; check the current Microsoft and AWS documentation before relying on them.

Licensing and availability. Microsoft licensing for Agent 365, Entra Agent ID, Conditional Access for agents, Purview and Defender is complex and changes often, and some capabilities depend on preview enrollment (Agent 365 publishing, for example, expects the tenant to be in the Frontier program). Nothing in this article is licensing advice. Confirm what your tenant needs, and what is available to it, with your Microsoft account team before you plan or build.

Conventions

Values in angle brackets are placeholders: <tenant-id>, <aws-account-id>, <region>, <blueprint-app-id>, <blueprint-object-id>, <agent-identity-id>, <tools-api-app-id>, <agentcore-role-arn>, <agent-name>, <sponsor-object-id> and so on. Nothing in this article is specific to one environment.

The examples use an inventory agent that answers questions about product stock through one tool server, the inventory tools API (api://<tools-api-app-id>). The tools API exposes a delegated scope Inventory.Read (the agent acting for a user) and an application role Inventory.Read.All (the agent acting on its own). Names such as inventory-agent-agentcore are examples; substitute your own.

Constants published by Microsoft, the same in every tenant:

ConstantValue
Token-exchange audience (AWS token and exchange scope)api://AzureADTokenExchange
Agent 365 observability API9b975845-388f-4429-889e-eab1ef63949c
Microsoft Graphwritten here as <microsoft-graph-app-id>: Microsoft Graph’s well-known application ID, the same in every tenant

The idea in one paragraph

AWS signs a short-lived token that says “this is IAM role X in account Y”. The agent’s Entra blueprint trusts exactly that issuer and that role through a federated identity credential, so no secret exists anywhere. When the agent needs an Entra token, it asks AWS STS for the signed token, presents it to Entra as the blueprint’s credential, receives an exchange token for its own agent identity, and uses that to get the token it actually needs: as itself (app-only) or for the user who called it (on-behalf-of). Everything else in this article (who created those objects, who approved the grants, who may call the agent, what Purview checks, where the audit trail lands) is built around that one exchange.

Architecture

There is one container per runtime and no sidecar.

PartWhereWhat it does
Onboarding configurationA Git repositoryblueprints.yaml (agent types) and agents.yaml (agents). Pull requests plan; merges apply.
Platform, workload and access flowsCI/CD, each with its own Entra identityCreate the blueprint, the agent identity and registry entry, and the permission grants (the last one behind a human approval).
AWS IAM outbound identity federationAWS accountLets the runtime’s IAM role call sts:GetWebIdentityToken and get a JWT signed by the account’s issuer.
AgentCore execution roleAWS IAMThe role the agent runtime assumes. Its ARN is the subject the blueprint trusts.
Agent runtimeAgentCore RuntimeOne arm64 container: POST /invocations, GET /ping, port 8080. A custom JWT authorizer checks callers before the container runs; a request header allowlist forwards their token.
Tool serverAgentCore Runtime (MCP)An MCP server that accepts only Entra tokens for its own API, and logs who called it.
Blueprint, blueprint principal, agent identityEntraWho the agent is (next section).
Agent 365 observability and Microsoft PurviewMicrosoft 365Receive the agent’s spans and audit records; evaluate its prompts and answers against DLP policies.

The request path, in short:

Show codeHide code14 lines
caller --(Entra token, aud = blueprint)--> AgentCore custom JWT authorizer   [rejects before the container runs]
                                               |
                                               v  Authorization header (allowlisted)
                                           agent container
  0. AWS STS  GetWebIdentityToken (aud api://AzureADTokenExchange, RS256, 300 s)   -> AWS-signed JWT
  1. Entra    as the blueprint: client_credentials, fmi_path = <agent-identity-id>,
              client_assertion = AWS JWT, scope api://AzureADTokenExchange/.default  -> T1
  2a. Entra   as the agent identity: client_credentials, client_assertion = T1      -> app-only token (roles)
  2b. Entra   as the agent identity: jwt-bearer on_behalf_of, assertion = caller token,
              client_assertion = T1                                                  -> delegated token (scp, oid = user)
                                               |
          +------------------+-----------------+---------------------+
          v                  v                                       v
   MCP tool server     Microsoft Graph (Purview DLP, delegated)   Agent 365 observability (app-only)

The identity model

Four Entra objects, and one rule about how many of them to have.

Blueprint. An application object with @odata.type #microsoft.graph.agentIdentityBlueprint. It is the template for one type of agent. It holds the only credential in the design (the federated identity credential), exposes the scope users sign in to the agent with (access_agent), and is the audience of every caller’s token. A blueprint is not a general-purpose app: it can get exchange tokens for its own agent identities and little else.

Blueprint principal. The blueprint’s service principal in the tenant (#microsoft.graph.agentIdentityBlueprintPrincipal). It is not created automatically. Caller assignments (“who may use agents of this type”) and grants that agents inherit are made against it.

Agent identity. A service principal of type #microsoft.graph.agentIdentity, created from the blueprint, with a sponsor. This is the identity that holds permissions, appears in sign-in logs, is evaluated by Conditional Access for agents, and is named in Agent 365, Purview and Defender.

Inheritable permissions. A blueprint can declare that its agent identities inherit grants made to the blueprint principal, per resource application. Here the blueprint principal holds Agent365.Observability.OtelWrite on the Agent 365 observability API and the blueprint marks that resource’s roles as inheritable, so every agent created from it can send telemetry without a grant of its own.

One blueprint per trust boundary. The AgentCore agent has its own blueprint and its own agent identity, separate from the ECS agent of the earlier article. The AgentCore blueprint’s only federated credential is the AgentCore execution role; the ECS blueprint no longer trusts that role. A blueprint can get an exchange token for any of its agent identities, so whoever can present the blueprint’s credential can act as all of them. If two runtimes share a blueprint, a compromise of one runtime’s IAM role lets it mint tokens for the other runtime’s agents. Separate blueprints keep that blast radius to one runtime, and keep sign-in logs and Agent 365 easier to read.

Prerequisites

  • An AWS account in a region where AgentCore Runtime is available, with Amazon Bedrock model access for your model.
  • Container images built for arm64: AgentCore Runtime runs arm64. On an x86 build machine use docker buildx --platform linux/arm64 with QEMU.
  • A Microsoft tenant with Entra Agent ID, Agent 365 and Purview available, and the licensing they require (see the note above).
  • A sponsor for the agent (a user accountable for it).
  • The administrator roles in Roles and permissions below.
  • Library versions that were tested together:
Python.NET
bedrock-agentcore==1.24.1Microsoft.Identity.Web 4.16.1
boto3==1.43.111 (1.24.1 needs a recent boto3)Microsoft.Identity.Web.AgentIdentities 4.16.1
httpx==0.28.1AWSSDK.SecurityToken 4.0.101.3
microsoft-opentelemetry[langchain]==1.3.9.NET 8
langchain==1.4.2, langchain-aws==1.7.9, langgraph==1.2.12

Terraform used the hashicorp/aws provider 6.67 or later (for aws_bedrockagentcore_agent_runtime) and the microsoft/msgraph provider 0.6 (the azuread provider has no Agent ID resources).

Roles and permissions

In this pattern nobody creates the blueprint or the agent identity by hand: three pipeline identities do it, with the Microsoft Graph application permissions listed in section 1.3. People need roles for four things: the one-time bootstrap that creates those identities, approving the access flow, deploying the AgentCore runtimes, and the governance, monitoring and data security tasks. The tables give the least-privileged role that Microsoft Learn and the AWS documentation name for each task as of November 2026. Where I used a broader role, or couldn’t confirm a role in the documentation, the notes say so: verify those in your tenant.

Two rules apply throughout. The Agent ID APIs reject Azure CLI user tokens with 403, because they carry Directory.AccessAsUser.All, so automate with a service principal or managed identity. And never give that identity Directory.ReadWrite.All or Directory.AccessAsUser.All: a client holding either has its Agent ID permissions ignored.

One-time bootstrap

TaskRole or permissionNotes
Create the three user-assigned managed identities and their federated credentials for the CI system’s OIDC tokensManaged Identity Contributor on the resource group, or ContributorI ran the bootstrap as Contributor and User Access Administrator; verify that Managed Identity Contributor alone covers federated credentials
Grant the pipeline identities their Graph application permissionsPrivileged Role Administrator (least privileged) or Global AdministratorApplication Administrator and Cloud Application Administrator can’t grant Microsoft Graph application permissions
Terraform state in Azure StorageContributor to create the account; User Access Administrator or Role Based Access Control Administrator to assign Storage Blob Data Contributor on the state containerTurn storage keys off
Or Terraform state in Amazon S3An AWS administrator creates the bucket, the GitHub OIDC provider and a role limited to s3:ListBucket, GetObject, PutObject and DeleteObject on that bucketI used S3 because a tenant policy blocked hosted runners from Azure Storage
GitHub environments, required reviewers and repository variablesAdmin on the onboarding repositoryRequired reviewers on a private repository need GitHub Pro, Team or Enterprise

Running the flows

TaskRole or permissionNotes
Open a pull request that changes blueprints.yaml or agents.yamlWrite access to the repositoryThe plan runs as the platform or workload identity: it can read, not grant
Approve the access flow (app roles, delegated grants, caller groups)Required reviewer of the access environmentThe human check on every grant: the access identity can grant anything, including to itself
Be a sponsorNo admin role: a user, dynamic group or Microsoft 365 group named in the YAMLSecurity groups and role-assignable groups can’t be sponsors
Add owners to a blueprint (needed before registering a messaging endpoint)Agent ID Administrator, or an existing ownerThe platform identity’s default permissions got 403 on owners

Microsoft Entra: grants, approval and Conditional Access

TaskRole or permissionNotes
Grant the agent identity app roles and delegated scopes on your own APIs, and Agent365.Observability.OtelWriteAgent ID Administrator for app role assignments; Cloud Application Administrator or Application Administrator for delegated grantsI used Global Administrator; verify the narrower roles cover agent identities. The access flow does this as a workload identity
Grant the Purview Graph permissions (ProtectionScopes.Compute.User, Content.Process.User, delegated)Cloud Application Administrator or Application AdministratorEntra blocks high-risk Graph permissions for agents, even for an administrator
Create the approval attribute set and attributeAttribute Definition AdministratorGlobal Administrator has no custom security attribute rights by default
Set the approval attribute on agent identitiesAttribute Assignment Administrator
Create the Conditional Access policy for agentsConditional Access Administrator
Read agent sign-in logsReports Reader or Security Reader

Microsoft 365 admin center, Defender and Purview

TaskRole or permissionNotes
Agents pages: inventory, registry, approve requests, block an agentAI AdministratorIt can’t consent to permissions; a request that needs admin consent also needs a Global Administrator
Assign Microsoft 365 E7 or Agent 365 licensesLicense Administrator or User AdministratorAgent telemetry isn’t ingested without an assigned license
Connect the Microsoft 365 app connector in Defender for Cloud AppsSecurity Administrator or Global AdministratorVerify in your tenant. Without it, CloudAppEvents stays empty
Run advanced hunting queriesSecurity Reader, or the unified RBAC permission Security data basics (read)
Create custom detection rulesSecurity Administrator, or Security settings (manage)
Search the Purview audit logAudit Logs or View-Only Audit Logs (for example the Audit Reader role group)Search-UnifiedAuditLog also needs the role in the Exchange admin center
Create the DLP policyCompliance Administrator, Compliance Data Administrator or Information Protection role group, or the DLP Compliance Management role
View DSPM AI activitiesPurview Security Reader, Data Security AI Viewer or AI Administrator to view; Data Security AI Content Viewer to see prompt textDocumented for classic DSPM for AI; verify for the new DSPM

AWS

TaskPermissionNotes
Enable outbound identity federation and read the issuer (once per account)iam:EnableOutboundWebIdentityFederation, iam:GetOutboundWebIdentityFederationInfoNamed after the API calls; verify in the AWS Service Authorization Reference
Create the execution rolesiam:CreateRole, iam:PutRolePolicy; iam:PassRole with iam:PassedToService = bedrock-agentcore.amazonaws.comUse a name prefix and a permissions boundary so deployers can’t create broader roles
Create or update the runtimes and push arm64 imagesbedrock-agentcore:CreateAgentRuntime, UpdateAgentRuntime, GetAgentRuntime (or the BedrockAgentCoreFullAccess managed policy); ECR push on the agent’s repositories; iam:CreateServiceLinkedRole for bedrock-agentcore.amazonaws.comAWS recommends a custom policy over the managed one
Call the agentAn Entra token for the blueprint’s scope; no AWS permissionWith the JWT authorizer, AgentCore checks the bearer token, not SigV4
The agent’s execution role at runtimests:GetWebIdentityToken (audience api://AzureADTokenExchange), Bedrock, ECR pull, logsPolicies in Phase 0. The tool server’s role has no sts:GetWebIdentityToken

Phase 0: Prepare AWS

0.1 Enable outbound identity federation (once per account)

aws iam enable-outbound-web-identity-federation
aws iam get-outbound-web-identity-federation-info --query IssuerIdentifier

Why: this gives the account its own token issuer, of the form https://<issuer-id>.tokens.sts.global.api.aws. The blueprint’s federated credential names it.

Order: first. The issuer doesn’t exist until the feature is enabled.

0.2 Create the AgentCore execution role (once per agent type)

Trust policy: AgentCore assumes the role, only for your account.

Show codeHide codejson · 9 lines
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Service": "bedrock-agentcore.amazonaws.com" },
    "Action": "sts:AssumeRole",
    "Condition": { "StringEquals": { "aws:SourceAccount": "<aws-account-id>" } }
  }]
}

Permissions: the model, the image, logs, and one federation statement.

Show codeHide codejson · 20 lines
{
  "Version": "2012-10-17",
  "Statement": [
    { "Sid": "Model", "Effect": "Allow",
      "Action": ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"],
      "Resource": ["arn:aws:bedrock:<region>:<aws-account-id>:inference-profile/<inference-profile-id>",
                   "arn:aws:bedrock:*::foundation-model/<foundation-model-id>"] },
    { "Sid": "Image", "Effect": "Allow",
      "Action": ["ecr:GetAuthorizationToken", "ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer",
                 "ecr:BatchCheckLayerAvailability"],
      "Resource": "*" },
    { "Sid": "Logs", "Effect": "Allow",
      "Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents", "logs:DescribeLogStreams"],
      "Resource": "*" },
    { "Sid": "EntraFederationAssertion", "Effect": "Allow",
      "Action": "sts:GetWebIdentityToken", "Resource": "*",
      "Condition": { "ForAllValues:StringEquals": {
        "sts:IdentityTokenAudience": ["api://AzureADTokenExchange"] } } }
  ]
}

Why: the federation statement is the only thing that lets this workload speak to Entra, and the condition limits it to the token-exchange audience. The role ARN (<agentcore-role-arn>) is the subject Entra will trust: keep the name stable. The tool server runs under a separate role without the federation statement, because it never needs to act as an agent.

Phase 1: Onboard the agent as code

The blueprint, the agent identity, the registry entry and every grant come from two YAML files. Three flows apply them, each with its own identity and only the permissions it needs.

1.1 Describe the agent type: blueprints.yaml

Show codeHide codeyaml · 27 lines
blueprints:
  inventory-agent-agentcore:
    description: Inventory agent on Amazon Bedrock AgentCore Runtime, authenticated in process (no sidecar).
    sponsors: [<sponsor-object-id>]          # accountable people
    owners: []                               # optional; see "Lessons learned"
    user_scope: access_agent                 # delegated scope users sign in to the agent with
    preauthorized_client_app_ids: []         # client apps that skip the consent prompt

    # The only credential: workload identity federation with the AgentCore execution role.
    federated_credentials:
      aws-agentcore:
        description: AgentCore execution role of the inventory agent
        issuer: https://<issuer-id>.tokens.sts.global.api.aws
        subject: <agentcore-role-arn>        # arn:aws:iam::<aws-account-id>:role/<execution-role-name>

    # What agent identities inherit from the blueprint principal's grants, per resource app ID.
    inheritable_permissions:
      9b975845-388f-4429-889e-eab1ef63949c:  # Agent 365 observability
        roles: all

    # Privileged: applied by the approval-gated access flow.
    access:
      assignment_required: true              # only assigned users and groups get tokens for the agent
      caller_group_ids: [<caller-group-id>]
      app_roles:
        9b975845-388f-4429-889e-eab1ef63949c: [Agent365.Observability.OtelWrite]
      delegated_scopes: {}

1.2 Describe the agent: agents.yaml

Show codeHide codeyaml · 24 lines
agents:
  inventory-agent-agentcore-prod:
    blueprint: inventory-agent-agentcore
    description: Inventory agent on Amazon Bedrock AgentCore Runtime (no sidecar).
    sponsors: [<sponsor-object-id>]
    agent_user:
      enabled: false                         # no mailbox or Teams presence needed
    registration:                            # Agent 365 registry entry
      enabled: true
      provider: <your-organization>
      version: 1.0.0
      skills:
        - id: inventory
          name: Product inventory
          description: Answers questions about product stock through a governed MCP tool.

    # Privileged: applied by the approval-gated access flow.
    access:
      telemetry: false                       # OtelWrite is inherited from the blueprint
      app_roles:                             # the agent acting on its own
        <tools-api-app-id>: [Inventory.Read.All]
      delegated_scopes:                      # the agent acting for a user, consented for all users
        <tools-api-app-id>: [Inventory.Read]
        <microsoft-graph-app-id>: [ProtectionScopes.Compute.User, Content.Process.User]   # Purview DLP

That is the whole description of the agent: one app role and one delegated scope on the tool it uses, two delegated Graph permissions for Purview, and telemetry inherited from its type.

1.3 Pull request, platform, workload, access

StepTriggerRuns asWhat happens
PlanPull request that changes either filePlatform or workload identityTerraform plan posted on the pull request for review
Platform flowMerge of blueprints.yamlPlatform identityCreates or updates the blueprint, scope, blueprint principal, federated credentials, inheritable permissions
Workload flowMerge of agents.yaml, or a successful platform runWorkload identityCreates the agent identity (with sponsors), optional agent user, Agent 365 registry entry
Access flowAfter the workload flow, only once a reviewer approvesAccess identityApp role assignments, delegated permission grants, caller assignments, “assignment required”
Runtime deploymentSeparate, manualDeployment identityBuilds the images and deploys the AgentCore runtimes (Phase 3)

No pipeline holds a secret: in the implementation behind this article each pipeline identity was a user-assigned managed identity that trusts the CI system’s OIDC tokens for one deployment environment only. The access flow runs in its own environment with required reviewers, because the permissions it needs can grant anything, including to itself.

The Microsoft Graph application permissions each identity needs:

IdentityPermissions
PlatformAgentIdentityBlueprint.Create, .Read.All, .AddRemoveCreds.All, .UpdateAuthProperties.All, .DeleteRestore.All; AgentIdentityBlueprintPrincipal.Create, .Read.All, .DeleteRestore.All
WorkloadAgentIdentityBlueprint.Read.All; AgentIdentity.Create.All, .Read.All, .DeleteRestore.All; AgentRegistration.ReadWrite.All; User.ReadBasic.All; AgentIdUser.ReadWrite.All only if you use agent users. The narrower AgentIdUser.ReadWrite.IdentityParentedBy returns 403 “Insufficient privileges” for a pipeline identity, because it only applies to the blueprint itself. User.ReadBasic.All lets Terraform confirm that a deleted agent user is gone
AccessApplication.Read.All, AppRoleAssignment.ReadWrite.All, DelegatedPermissionGrant.ReadWrite.All, AgentIdentityBlueprintPrincipal.ReadWrite.All

Don’t give any of them Directory.ReadWrite.All or Directory.AccessAsUser.All: Microsoft documents that a client holding either has its Agent ID permissions ignored.

1.4 What the flows do in Microsoft Graph

If you don’t use pipelines, these are the calls, in order. Run them as an identity holding the permissions above (Microsoft documents that the Agent ID APIs reject Azure CLI user tokens).

  1. POST /v1.0/applications with "@odata.type": "#microsoft.graph.agentIdentityBlueprint", a display name and sponsors@odata.bind: the blueprint.
  2. PATCH the blueprint with identifierUris = ["api://<blueprint-app-id>"] and the access_agent scope (type User); then a second PATCH that repeats the scope and adds pre-authorized client apps (the api block is replaced as a whole).
  3. POST /v1.0/servicePrincipals with "@odata.type": "#microsoft.graph.agentIdentityBlueprintPrincipal" and the blueprint’s appId: the blueprint principal.
  4. The federated credential and the inheritable permissions (below).
  5. POST /v1.0/servicePrincipals with "@odata.type": "#microsoft.graph.agentIdentity", agentIdentityBlueprintId and sponsors@odata.bind: the agent identity.
  6. POST /beta/copilot/agentRegistrations with the agent identity, blueprint, owners and an agent card listing the skills: the Agent 365 registry entry. Without it, an agent created through Graph doesn’t show in the registry.

The trust in the AgentCore execution role (the key call):

Show codeHide codebash · 9 lines
az rest --method POST \
  --url "https://graph.microsoft.com/v1.0/applications/<blueprint-object-id>/federatedIdentityCredentials" \
  --headers "Content-Type=application/json" --body '{
    "name": "aws-agentcore",
    "description": "AgentCore execution role of the inventory agent",
    "issuer": "https://<issuer-id>.tokens.sts.global.api.aws",
    "subject": "<agentcore-role-arn>",
    "audiences": ["api://AzureADTokenExchange"]
  }'

Inheritable permissions for the Agent 365 observability API:

Show codeHide codebash · 7 lines
az rest --method POST \
  --url "https://graph.microsoft.com/v1.0/applications/microsoft.graph.agentIdentityBlueprint/<blueprint-object-id>/inheritablePermissions" \
  --headers "Content-Type=application/json" --body '{
    "resourceAppId": "9b975845-388f-4429-889e-eab1ef63949c",
    "inheritableScopes": { "@odata.type": "microsoft.graph.noScopes", "kind": "none" },
    "inheritableRoles":  { "@odata.type": "microsoft.graph.allAllowedRoles", "kind": "allAllowed" }
  }'

Details that matter:

  • Entra replicates asynchronously. Retry on Request_ResourceNotFound and NoBackingApplicationObject right after creating an object.
  • The federated credential’s issuer, subject and audience must match the AWS token exactly, including case. An application can hold a limited number of federated credentials (20 at the time of writing): one per runtime role, not one per deployment.
  • The inheritable-permissions endpoint is keyed by resourceAppId; the implementation created each entry with nothing inherited and then set the kinds with a PATCH, so changes show up in Terraform plans.
  • The trust must exist before the runtime’s first invocation.

1.5 The onboarding audit trail

Every one of those changes is recorded in the unified audit log (workload AzureActiveDirectory), with the pipeline identity as the actor. For this agent the onboarding produced:

OperationWhat it was
Add applicationThe blueprint
Create application – Certificates and secrets managementThe federated identity credential (the only credential)
Add service principalThe blueprint principal and the agent identity
Add user sponsorThe sponsor on the agent objects
Add app role assignment to service principalInventory.Read.All for the agent identity; Agent365.Observability.OtelWrite for the blueprint principal (inherited by the agent)
Add delegated permission grantInventory.Read on the tools API; the Purview Graph scopes

So the question “who gave this agent this permission, and when” has an answer in the same place your auditors already look, and the pull request that caused it is one click away in the CI run.

Phase 2: Govern the agent

2.1 Grants: least privilege, approved by a person

The access flow turns the access sections into two kinds of grant. By hand:

Show codeHide codebash · 11 lines
# App-only (the agent acting as itself): an app role assignment
az rest --method POST --headers "Content-Type=application/json" \
  --url "https://graph.microsoft.com/v1.0/servicePrincipals/<tools-api-sp-id>/appRoleAssignedTo" \
  --body '{ "principalId": "<agent-identity-object-id>", "resourceId": "<tools-api-sp-id>",
            "appRoleId": "<Inventory.Read.All-role-id>" }'

# On behalf of a user: a delegated permission grant, consented for all users
az rest --method POST --headers "Content-Type=application/json" \
  --url "https://graph.microsoft.com/v1.0/oauth2PermissionGrants" \
  --body '{ "clientId": "<agent-identity-object-id>", "consentType": "AllPrincipals",
            "resourceId": "<tools-api-sp-id>", "scope": "Inventory.Read" }'

Why both, and why only these: they are different paths with different claims. App-only tokens carry roles and are evaluated by Conditional Access for agents; on-behalf-of tokens carry scp, name the user in oid and the agent in azp, and are evaluated by the user’s policies. This agent gets one app role and one delegated scope on the one API it calls, plus the two Graph scopes Purview needs, and nothing on Graph app-only.

2.2 Sponsors and owners

The sponsor is set when the blueprint and agent identity are created: the accountable person, who is asked about the agent in access reviews and lifecycle decisions. Owners (people who technically manage the objects) are optional. A blueprint created by a pipeline identity has no owners, because the pipeline doesn’t become one; adding owners needs more than the platform identity’s default permissions.

2.3 Decide who may call the agent

Assign users or a group to the blueprint principal and set appRoleAssignmentRequired to true (assignment_required and caller_group_ids in the YAML). Entra then refuses to issue a token for the agent to anyone not assigned (AADSTS50105), before a request reaches AWS. Make the assignments first, then turn on “assignment required”, or you lock out your own callers.

2.4 Conditional Access for agents

Mark approved agents with a custom security attribute (for example AgentGovernance/Approval = Approved) and create a Conditional Access policy that blocks agent identities without it. An agent identity that isn’t approved then fails at token issuance with AADSTS53003. This was observed from inside AgentCore Runtime in an October 2026 pilot, in both Python and .NET: the in-process exchange gets exactly the same answer as any other client. Test it with a second, unapproved agent identity before you rely on it.

Disabling the agent identity in Entra should stop both paths, app-only and on-behalf-of, because both tokens are issued to the agent identity. That makes it the kill switch: one property on one object, no change on AWS. (This follows from how the tokens are issued; I tested the Conditional Access block above, not the disable switch itself, so try it in your tenant before you rely on it in a runbook.)

2.5 No secrets

The blueprint’s only credential is the federated credential. The pipelines authenticate with OIDC. The agent’s tokens live in process memory. There is nothing to rotate and nothing to leak. (If you create blueprints with the Agent 365 CLI instead, it adds a client secret; delete it once the federated credential works.)

Phase 3: Configure the AgentCore runtimes

3.1 The agent runtime: custom JWT authorizer and header allowlist

Show codeHide codehcl · 34 lines
resource "aws_bedrockagentcore_agent_runtime" "agent" {
  agent_runtime_name = "inventory_agent"
  role_arn           = aws_iam_role.agentcore_agent.arn      # <agentcore-role-arn>

  agent_runtime_artifact {
    container_configuration { container_uri = "<ecr-image-uri-arm64>" }
  }
  network_configuration { network_mode = "PUBLIC" }

  # Only Entra tokens issued for this agent's blueprint get through.
  authorizer_configuration {
    custom_jwt_authorizer {
      discovery_url    = "https://login.microsoftonline.com/<tenant-id>/v2.0/.well-known/openid-configuration"
      allowed_audience = ["<blueprint-app-id>", "api://<blueprint-app-id>"]
      # No allowed_clients: AgentCore matches it against a client_id claim; Entra tokens carry azp.
    }
  }

  # Forward the validated caller token to the container (needed for on-behalf-of).
  request_header_configuration {
    request_header_allowlist = ["Authorization"]
  }

  environment_variables = {
    AZURE_TENANT_ID    = "<tenant-id>"
    AGENT_BLUEPRINT_ID = "<blueprint-app-id>"
    AGENT_IDENTITY_ID  = "<agent-identity-id>"
    AGENT_NAME         = "<agent-name>"
    CHANNEL_NAME       = "agentcore-runtime"
    TOOLS_SCOPE        = "api://<tools-api-app-id>/.default"
    TOOLS_MCP_URL      = "<tool-runtime-invocation-url>"
    PURVIEW_DLP        = "on"
  }
}

Why v2: blueprints issue v2 access tokens: iss is https://login.microsoftonline.com/<tenant-id>/v2.0 and aud is the bare blueprint app ID. AgentCore compares the token’s issuer with the discovery document’s, so the v1 discovery URL fails every call with Claim 'iss' value mismatch. Listing both audience forms costs nothing.

What you get: a request without a valid token is rejected by AgentCore before the container runs (401 or 403, depending on how the request is formed: AWS documents 401 for a missing bearer token, and a request with no Authorization header at all can be treated as an unsigned AWS request and get 403). A valid Entra token issued for a different blueprint gets 401: the runtime accepts only its own blueprint as audience. With a JWT authorizer configured, callers use a bearer token, not SigV4; a runtime accepts one or the other.

Why the allowlist: by default the container doesn’t see the caller’s Authorization header. Without it, the agent has no user token to exchange, and on-behalf-of is impossible. App-only keeps working, which hides the problem until the first delegated call.

The runtime ID and blueprint app ID come from the workload flow’s summary; in the implementation, the runtime’s Terraform looked them up in Graph by display name and refused to apply if either was missing.

3.2 The tool server: an MCP runtime that only accepts Entra tokens

The tools API is an ordinary Entra app registration (requestedAccessTokenVersion = 2) with the Inventory.Read scope and the Inventory.Read.All app role. Its MCP server runs on its own AgentCore runtime, defined like the agent’s but with protocol_configuration { server_protocol = "MCP" } (the server answers POST /mcp on port 8000), an execution role without sts:GetWebIdentityToken, the same v2 discovery URL, allowed_audience = ["<tools-api-app-id>", "api://<tools-api-app-id>"], and the Authorization header allowlisted. AgentCore rejects any token that isn’t for the tools API.

Inside, the server validates the token again (signature against the tenant’s keys, issuer, audience, expiry, tenant) and then authorizes:

Show codeHide codepython · 10 lines
def _allowed(claims: dict) -> bool:
    return ("Inventory.Read" in str(claims.get("scp", "")).split()        # an agent acting for a user
            or "Inventory.Read.All" in (claims.get("roles") or []))       # an agent acting on its own

def _who(claims: dict) -> dict:
    delegated = bool(claims.get("scp"))
    return {"token_type": "delegated" if delegated else "app-only",
            "user_oid": claims.get("oid") if delegated else None,
            "agent": claims.get("azp") or claims.get("appid"),
            "scp": claims.get("scp"), "roles": claims.get("roles")}

Every tool call is logged as one JSON line with _who(...) and the W3C traceparent the agent sent. That log is the tool’s own evidence of who called it: a user through which agent, or an agent on its own. If you want to restrict the tool to specific agents, check azp against a list of agent identity IDs as well.

Phase 4: The token exchange in code

4.1 .NET: Microsoft.Identity.Web does the protocol

Microsoft.Identity.Web with its agent identities package already implements steps 1, 2a and 2b. The one missing piece is where the blueprint’s credential comes from. A custom signed-assertion provider supplies it from AWS STS:

Show codeHide codecsharp · 27 lines
public sealed class AwsStsSignedAssertionLoader(IAmazonSecurityTokenService sts) : ICustomSignedAssertionProvider
{
    public string Name => "AwsSts";
    public CredentialSource CredentialSource => CredentialSource.CustomSignedAssertion;

    public Task LoadIfNeededAsync(CredentialDescription credentialDescription,
                                  CredentialSourceLoaderParameters? parameters = null)
    {
        credentialDescription.CachedValue ??= new AwsStsAssertion(sts);
        return Task.CompletedTask;
    }
}

// Microsoft.Identity.Web calls this when it needs a fresh assertion; the base class caches it until expiry.
public sealed class AwsStsAssertion(IAmazonSecurityTokenService sts) : ClientAssertionProviderBase
{
    protected override async Task<ClientAssertion> GetClientAssertionAsync(AssertionRequestOptions? options)
    {
        var resp = await sts.GetWebIdentityTokenAsync(new GetWebIdentityTokenRequest
        {
            Audience = ["api://AzureADTokenExchange"],
            SigningAlgorithm = "RS256",   // the algorithm Entra accepts here
            DurationSeconds = 300,        // longer fails inside AgentCore (see lessons learned)
        });
        return new ClientAssertion(resp.WebIdentityToken, resp.Expiration);
    }
}

Configuration: the blueprint is the client, and its credential is the custom assertion.

Show codeHide codecsharp · 16 lines
builder.WebHost.UseUrls("http://0.0.0.0:8080");
builder.Services.AddSingleton<IAmazonSecurityTokenService>(_ => new AmazonSecurityTokenServiceClient());
builder.Services.AddSingleton<ICustomSignedAssertionProvider, AwsStsSignedAssertionLoader>();

builder.Configuration["AzureAd:Instance"] = "https://login.microsoftonline.com/";
builder.Configuration["AzureAd:TenantId"] = tenantId;
builder.Configuration["AzureAd:ClientId"] = blueprintAppId;
builder.Configuration["AzureAd:ClientCredentials:0:SourceType"] = "CustomSignedAssertion";
builder.Configuration["AzureAd:ClientCredentials:0:CustomSignedAssertionProviderName"] = "AwsSts";
// Do NOT set AzureAd:Audience: api://<blueprint> rejects the v2 token's bare-app-ID audience.

builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration, "AzureAd")
    .EnableTokenAcquisitionToCallDownstreamApi()
    .AddInMemoryTokenCaches();
builder.Services.AddAgentIdentities();
builder.Services.AddAuthorization();

AddMicrosoftIdentityWebApiAuthentication validates the forwarded caller token a second time (defense in depth behind AgentCore’s authorizer) and keeps it for on-behalf-of. Map POST /invocations with .RequireAuthorization() and GET /ping, then in the handler:

Show codeHide codecsharp · 12 lines
// As the agent (app-only; Conditional Access for agents applies)
var appHeader = await headers.CreateAuthorizationHeaderForAppAsync(
    toolsScope, new AuthorizationHeaderProviderOptions().WithAgentIdentity(agentIdentityId));

// On behalf of the validated caller (the user's policies apply)
var oboHeader = await headers.CreateAuthorizationHeaderForUserAsync(
    [toolsScope], new AuthorizationHeaderProviderOptions().WithAgentIdentity(agentIdentityId), http.User);

// Telemetry token for Agent 365 (role inherited from the blueprint)
var a365Header = await headers.CreateAuthorizationHeaderForAppAsync(
    "api://9b975845-388f-4429-889e-eab1ef63949c/.default",
    new AuthorizationHeaderProviderOptions().WithAgentIdentity(agentIdentityId));

That is the whole .NET identity layer: one class pair and one configuration block.

4.2 Python: the protocol by hand

At the time of writing I found no supported Python library that performs the agent identity exchange in-process; Microsoft’s route for Python and other non-.NET languages is the sidecar, which AgentCore Runtime has no room for. So the exchange is three posts to the Entra token endpoint, following Microsoft’s documented agent protocol, in one small module with an in-memory cache:

Show codeHide codepython · 60 lines
import base64, json, os, threading, time
import boto3, httpx

TENANT_ID = os.environ["AZURE_TENANT_ID"]
BLUEPRINT_APP_ID = os.environ["AGENT_BLUEPRINT_ID"]
AUTHORITY = f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token"
JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
SKEW = 300  # renew five minutes before expiry

_sts = boto3.client("sts", region_name=os.environ.get("AWS_REGION"))
_http = httpx.Client(timeout=20)
_lock, _cache = threading.Lock(), {}

def _exp(token):
    p = token.split(".")[1]; p += "=" * (-len(p) % 4)
    return float(json.loads(base64.urlsafe_b64decode(p)).get("exp", 0))

def _cached(key, fetch):
    with _lock:
        hit = _cache.get(key)
        if hit and hit[1] - SKEW > time.time():
            return hit[0]
    token = fetch()
    with _lock:
        _cache[key] = (token, _exp(token))
    return token

def _post(form):
    r = _http.post(AUTHORITY, data=form)
    if r.status_code != 200:   # AADSTS codes are safe to surface; tokens never are
        body = r.json() if r.headers.get("content-type", "").startswith("application/json") else {}
        raise PermissionError(f"Entra {r.status_code} {body.get('error_codes')} "
                              f"{body.get('error_description', '')[:300]}")
    return r.json()["access_token"]

def aws_assertion():
    """Step 0: AWS-signed JWT for the execution role. Not cached: used once, to get T1."""
    return _sts.get_web_identity_token(Audience=["api://AzureADTokenExchange"],
                                       SigningAlgorithm="RS256", DurationSeconds=300)["WebIdentityToken"]

def exchange_token(agent_identity):
    """Step 1: T1, the blueprint acting for one of its agent identities."""
    return _cached(("t1", agent_identity), lambda: _post({
        "client_id": BLUEPRINT_APP_ID, "grant_type": "client_credentials",
        "scope": "api://AzureADTokenExchange/.default", "fmi_path": agent_identity,
        "client_assertion_type": JWT_BEARER, "client_assertion": aws_assertion()}))

def app_token(agent_identity, scope):
    """Step 2a: as the agent itself (roles; Conditional Access for agents applies)."""
    return _cached(("app", agent_identity, scope), lambda: _post({
        "client_id": agent_identity, "grant_type": "client_credentials", "scope": scope,
        "client_assertion_type": JWT_BEARER, "client_assertion": exchange_token(agent_identity)}))

def obo_token(agent_identity, user_token, scope):
    """Step 2b: on behalf of the caller (scp; oid = user, azp = agent). The user token's aud must be the blueprint."""
    return _cached(("obo", agent_identity, scope, user_token[-32:]), lambda: _post({
        "client_id": agent_identity, "scope": scope,
        "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
        "assertion": user_token, "requested_token_use": "on_behalf_of",
        "client_assertion_type": JWT_BEARER, "client_assertion": exchange_token(agent_identity)}))

fmi_path is what makes step 1 specific: it tells Entra which of the blueprint’s agent identities the exchange token is for, and the result (T1) can be used as a client assertion by that one agent identity only.

The AgentCore entry point reads the forwarded header, picks the mode, and hands the LangChain tools a token function:

Show codeHide codepython · 38 lines
import telemetry          # first: installs the OpenTelemetry providers before LangChain loads
from bedrock_agentcore.runtime import BedrockAgentCoreApp
import purview, tokens

app = BedrockAgentCoreApp()

@app.entrypoint
def invoke(payload, context):
    prompt, mode = payload.get("prompt", ""), payload.get("mode", "user")
    headers = getattr(context, "request_headers", None) or {}
    auth = headers.get("Authorization") or headers.get("authorization") or ""
    user_token = auth.split(" ", 1)[1] if auth.lower().startswith("bearer ") else ""

    # AgentCore's authorizer has validated the token; here we only read its claims.
    caller = tokens.claims(user_token) if user_token else {}
    delegated = "access_agent" in str(caller.get("scp", "")).split()

    if mode == "autonomous":
        tools_token = lambda: tokens.app(TOOLS_SCOPE)
    elif delegated:
        tools_token = lambda: tokens.obo(user_token, TOOLS_SCOPE)
    else:
        return {"error": "mode=user needs a user token with the access_agent scope"}

    session = getattr(context, "session_id", None)
    with telemetry.invoke_scope(prompt, session, caller if delegated else {}) as scope:
        try:
            purview.check(prompt, "uploadText", user_token if delegated else "", caller.get("oid"), session, 0)
            reply = build_agent(tools_token).invoke(
                {"messages": [{"role": "user", "content": prompt}]})["messages"][-1].content
            purview.check(reply, "downloadText", user_token if delegated else "", caller.get("oid"), session, 1)
        except purview.Blocked:
            reply = purview.BLOCKED_MESSAGE
        scope.record_output_messages(reply)
    return {"reply": reply, "mode": mode}

if __name__ == "__main__":
    app.run()   # POST /invocations and GET /ping on 0.0.0.0:8080

tokens.app and tokens.obo are thin wrappers over app_token and obo_token with the agent identity filled in; tokens.claims decodes a JWT payload without checking the signature, for routing and logging only. The Python agent relies on AgentCore’s authorizer for signature validation; the .NET agent validates again. If your threat model wants defense in depth in Python too, validate the forwarded token against the tenant’s keys as the tool server does.

Details that matter:

  • Tokens live in process memory only: never on disk, never in logs. Log AADSTS codes, not responses.
  • Cache T1 and the downstream tokens; don’t cache the AWS assertion.
  • The on-behalf-of cache key must include something unique to the user token, or one user’s token could be served to another.
  • Microsoft recommends its SDKs over hand-written protocol code. This works, but it is your code to keep in step with the protocol. If you can choose the language for an AgentCore agent, .NET carries less of that burden.

4.3 Calling the agent

Show codeHide codebash · 8 lines
TOKEN=$(az account get-access-token --scope "api://<blueprint-app-id>/access_agent" \
        --query accessToken -o tsv)

curl -s -X POST \
  "https://bedrock-agentcore.<region>.amazonaws.com/runtimes/<url-encoded-runtime-arn>/invocations?qualifier=DEFAULT" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -H "X-Amzn-Bedrock-AgentCore-Runtime-Session-Id: <session-id-of-33-or-more-characters>" \
  -d '{"prompt": "Which products are out of stock?", "mode": "user"}'

The Azure CLI works as a client because the onboarding adds it to the blueprint’s pre-authorized client applications. The caller needs no AWS credentials. The session ID header is optional: without it, AgentCore starts a new session for the request. That matters for callers that can’t set custom headers.

4.4 Is it the right agent? Validating agent tokens

Three layers make sure a token belongs to the right agent.

What Entra enforces before it issues anything. The blueprint’s federated credential trusts one IAM role, so a token from any other role fails the first step (AADSTS70021). The blueprint can act only as its own agents: asking for an agent identity under another blueprint fails with AADSTS7002134 (“has a different blueprint as parent”), which I saw in both the Python and the .NET agent. Assignment required on the blueprint principal refuses unassigned callers (AADSTS50105), and Conditional Access for agents can refuse the token outright (AADSTS53003).

A check in the agent before it uses a token. Microsoft asks clients to treat access tokens as opaque, so this is a fail-closed sanity check, not a replacement for the API’s validation: azp must be this agent identity, oid the agent (app-only) or the calling user (on-behalf-of), aud the API it’s about to call, and roles or scp the grant it expects. Log decoded claims only, never the token.

The validation in the API that receives it. Microsoft documents four checks: the signature against the tenant’s keys, the issuer, the audience, and an agent marker (xms_par_app_azp present, xms_act_fct containing 11). Then authorize the specific agent: azp on an allowlist of agent identity IDs, plus roles or scp. Don’t authorize on xms_par_app_azp, the blueprint: one blueprint can have many agents. Log it for audit instead. xms_sub_fct containing 13 marks an agent’s user account, which idtyp alone can’t tell from a person.

One finding changes how you use the marker: the agent claims are optional claims, and an API gets them only if its app registration asks for them. Tokens issued to a v2 API with no optional claims carried azp, oid, roles or scp and tid, but no idtyp, xms_par_app_azp, xms_act_fct or xms_sub_fct, so a marker check would have rejected every agent. After adding the four as access token optional claims, fresh tokens carried them within a minute:

ClaimApp-only tokenOn-behalf-of token
xms_par_app_azpThe blueprint app IDThe blueprint app ID
xms_act_fctContains 11Contains 11
xms_sub_fctContains 11 (the agent)No 13: the subject is a person
idtypappAbsent: test for scp instead

The facet values came back in a different order on each token, so test whether a value is in the set, never its position.

Show codeHide codehttp · 11 lines
PATCH https://graph.microsoft.com/v1.0/applications/<api-object-id>
{
  "optionalClaims": {
    "accessToken": [
      { "name": "idtyp" },
      { "name": "xms_par_app_azp" },
      { "name": "xms_act_fct" },
      { "name": "xms_sub_fct" }
    ]
  }
}

The PATCH replaces the whole optionalClaims object, so include any the API already has. If Terraform manages the app registration, put optionalClaims in its definition too, or a later apply may remove them.

The API-side check below ran against locally signed tokens (19 cases) and then inside an AgentCore agent on real tokens: the app-only and on-behalf-of tokens were accepted, with the signature checked against the tenant’s keys, and a token for another API, a missing role, an agent not on the allowlist and a tampered signature were rejected. Return 401 when steps 1 to 3 fail and 403 for the wrong agent or a missing permission.

Show codeHide codepython · 56 lines
# Environment: TENANT_ID=<tenant-id>
#   API_AUDIENCES=<api-app-id>,api://<api-app-id>
#   ALLOWED_AGENT_IDS=<agent-identity-id>[,<agent-identity-id>...]

# In the API that receives agent tokens (pip install "pyjwt[crypto]").
import os

import jwt

TENANT_ID = os.environ["TENANT_ID"]
# v2 tokens carry the API's app ID as aud; v1 tokens carry its identifier URI
AUDIENCES = os.environ["API_AUDIENCES"].split(",")              # <api-app-id>,api://<api-app-id>
ALLOWED_AGENTS = set(os.environ["ALLOWED_AGENT_IDS"].split(","))  # agent identity IDs, not blueprint IDs
# Needs the optional claims xms_par_app_azp and xms_act_fct on the API's app registration
REQUIRE_AGENT_MARKER = os.getenv("REQUIRE_AGENT_MARKER", "true") == "true"
ISSUERS = [f"https://login.microsoftonline.com/{TENANT_ID}/v2.0", f"https://sts.windows.net/{TENANT_ID}/"]
JWKS = jwt.PyJWKClient(f"https://login.microsoftonline.com/{TENANT_ID}/discovery/v2.0/keys")

class Rejected(Exception):
    """Return 401 (bad token) or 403 (wrong agent or permission) with this message."""

def facets(claims: dict, name: str) -> set[str]:
    return set(str(claims.get(name, "")).split())   # space-separated, any order

def validate(authorization: str, role: str | None = None, scope: str | None = None) -> dict:
    if not authorization.startswith("Bearer "):
        raise Rejected("no bearer token")
    token = authorization[7:]
    key = JWKS.get_signing_key_from_jwt(token)
    # 1-3. Signature, expiry, issuer and audience
    claims = jwt.decode(token, key.key, algorithms=["RS256"], audience=AUDIENCES, issuer=ISSUERS,
                        options={"require": ["exp", "iss", "aud"]})
    if claims.get("tid") != TENANT_ID:
        raise Rejected("token from another tenant")
    # 4. An agent identity, not an ordinary app
    if REQUIRE_AGENT_MARKER:
        if not claims.get("xms_par_app_azp"):
            raise Rejected("not an agent identity token")
        if "11" not in facets(claims, "xms_act_fct"):
            raise Rejected("the actor is not an agent identity")
    # 5. The specific agent: authorize on azp, never on the blueprint
    agent = claims.get("azp") or claims.get("appid")
    if agent not in ALLOWED_AGENTS:
        raise Rejected(f"agent {agent} is not allowed")
    # 6. Its permission: scp when a user is present, roles when the agent acts alone
    scp = claims.get("scp", "")
    if scp and scp != "/":
        if scope and scope not in scp.split():
            raise Rejected(f"missing scope {scope}")
        kind = "agent user" if "13" in facets(claims, "xms_sub_fct") else "on behalf of a user"
    else:
        if role and role not in claims.get("roles", []):
            raise Rejected(f"missing app role {role}")
        kind = "agent acting alone"
    # Log these; the blueprint (xms_par_app_azp) is for audit only
    return {"agent": agent, "blueprint": claims.get("xms_par_app_azp"), "subject": claims.get("oid"), "kind": kind}

Phase 5: Observability with the Agent 365 SDK

5.1 Set it up before anything else

Show codeHide codepython · 18 lines
from microsoft.opentelemetry import use_microsoft_opentelemetry
from opentelemetry.sdk.resources import Resource

A365_SCOPE = "api://9b975845-388f-4429-889e-eab1ef63949c/.default"

def _resolver(agent_id, tenant_id):
    return tokens.app(A365_SCOPE)        # app-only, as the agent identity; cached

use_microsoft_opentelemetry(
    resource=Resource.create({"service.name": AGENT_NAME, "cloud.provider": "aws",
                              "cloud.region": AWS_REGION}),
    enable_a365=True,
    a365_enable_observability_exporter=True,
    a365_use_s2s_endpoint=True,          # export as the agent identity
    a365_token_resolver=_resolver,
    a365_exporter_storage_directory="/tmp/otel/a365",   # the image's working directory may be read-only
    enable_sensitive_data=True,          # prompts and responses: Purview and Defender need them
)

Why each setting:

  • The exporter authenticates to Agent 365 as the agent identity with a token whose roles contain Agent365.Observability.OtelWrite. Here that role is inherited from the blueprint, so no per-agent grant was needed.
  • enable_sensitive_data=True records prompts and responses. That is the governance decision in this file: without it compliance tooling has nothing to inspect; with it, treat the telemetry as sensitive data.
  • Import this module before LangChain. Objects created earlier aren’t instrumented. AgentCore also runs its own OpenTelemetry pipeline for CloudWatch; keep to one global tracer provider and install Microsoft’s first.

5.2 One root span per request

Show codeHide codepython · 21 lines
from microsoft.opentelemetry.a365.core import (
    AgentDetails, BaggageBuilder, CallerDetails, Channel, InvokeAgentScope,
    InvokeAgentScopeDetails, Request, UserDetails)

AGENT = AgentDetails(agent_id=AGENT_IDENTITY_ID, agent_name=AGENT_NAME,
                     agent_blueprint_id=BLUEPRINT_APP_ID, tenant_id=TENANT_ID,
                     agent_version=APP_VERSION, provider_name="LangChain")

@contextmanager
def invoke_scope(prompt, session_id, user_claims):
    uid, email, name = user_claims.get("oid"), user_claims.get("preferred_username"), user_claims.get("name")
    baggage = (BaggageBuilder().tenant_id(TENANT_ID).agent_id(AGENT_IDENTITY_ID).agent_name(AGENT_NAME)
               .agent_blueprint_id(BLUEPRINT_APP_ID).agent_version(APP_VERSION)
               .conversation_id(session_id).session_id(session_id).channel_name(CHANNEL_NAME)
               .user_id(uid).user_email(email).user_name(name).build())
    request = Request(content=prompt, session_id=session_id, conversation_id=session_id,
                      channel=Channel(name=CHANNEL_NAME))
    caller = CallerDetails(user_details=UserDetails(user_id=uid, user_email=email, user_name=name))
    with baggage, InvokeAgentScope.start(request, InvokeAgentScopeDetails(), AGENT, caller) as scope:
        scope.record_input_messages(prompt)
        yield scope

InvokeAgentScope is the root span (“this caller invoked this agent”); the LangChain instrumentation adds the model and tool spans under it; the baggage copies the agent, blueprint, user, conversation and channel onto every child span. The MCP client also injects the W3C traceparent into each tool request, so the tool server’s log carries the same trace ID as the agent’s spans. The user details come from the token AgentCore validated, so the audit trail names an authenticated person.

5.3 What lands where

PlaceWhat appears
Entra sign-in logs (agent sign-ins)The agent identity’s sign-ins, including to the Agent 365 observability service
Unified audit log, workload Agent365 (searched by Purview Audit)InvokeAgent (RecordType 406), InferenceCall (407), ExecuteToolBySDK (405); Purview Audit search lists run and tool records as AIInvokeAgent and AIExecuteTool
Defender advanced huntingThe same records in CloudAppEvents
Microsoft 365 admin center > AgentsThe registry entry and its activity

In the test, one minute of use produced 5 InvokeAgent, 4 InferenceCall and 2 ExecuteToolBySDK records for the agent. The fields worth knowing:

FieldValue
TargetAgentName, TargetAgentId, TargetAgentBlueprintIDThe agent’s name, its agent identity, its blueprint
UserIdThe signed-in user
ChannelNameagentcore-runtime (from CHANNEL_NAME)
PlatformTargetAgentTypeCustomBuiltAgentsUsingSDK
TraceId, ConversationIdTies the records of one request together
CopilotEventData.ModelTransparencyDetailsOn InferenceCall: the model
ToolNameOn ExecuteToolBySDK: the tool

Two things that look wrong but aren’t. The top-level AgentId and AgentBlueprintId are all zeros: they describe a calling agent, in agent-to-agent calls; the agent that was invoked is the Target agent. And Defender’s own ObjectId and AccountObjectId columns are empty for these events, so filter on RawEventData instead (queries below).

Phase 6: Data security with Microsoft Purview inline DLP

Telemetry tells you what happened. Purview DLP can stop it happening: the agent asks Purview about each prompt before the model sees it, and about each answer before the user sees it.

6.1 Two Microsoft Graph calls, on behalf of the user

Both calls are made with an on-behalf-of token for Microsoft Graph, from the same in-process exchange (tokens.obo(user_token, "https://graph.microsoft.com/.default")). The calling app is the agent identity; the policies that apply are the signed-in user’s. No sidecar is involved.

  1. POST /users/{oid}/dataSecurityAndGovernance/protectionScopes/compute: which Purview policies apply to this user and this agent, for which activities (uploadText for the prompt, downloadText for the answer), and whether each is evaluated inline or offline. Cache the result per user with the ETag Purview returns.
  2. POST /users/{oid}/dataSecurityAndGovernance/processContent: the text itself, with the agent identity and blueprint in agents. Purview returns policy actions; restrictAccess with block means stop. Purview also records the interaction.
Show codeHide codepython · 51 lines
GRAPH = "https://graph.microsoft.com/v1.0"
BLOCKED_MESSAGE = ("Your request was blocked by your organization's data loss prevention policy "
                   "(Microsoft Purview).")
LOCATION = {"@odata.type": "microsoft.graph.policyLocationApplication", "value": AGENT_IDENTITY_ID}

def _compute(oid, auth):
    r = _http.post(f"{GRAPH}/users/{oid}/dataSecurityAndGovernance/protectionScopes/compute",
                   headers={"Authorization": auth},
                   json={"activities": "uploadText,downloadText", "locations": [LOCATION]})
    r.raise_for_status()
    _scopes[oid] = (r.headers.get("ETag", ""), r.json().get("value", []))
    return _scopes[oid]

def check(text, activity, user_token, oid, conversation_id, sequence):
    if not ENABLED or not user_token or not oid:
        return                                   # no user, no user policies: app-only turns aren't checked
    try:
        auth = "Bearer " + tokens.obo(user_token, "https://graph.microsoft.com/.default")
        etag, scopes = _scopes.get(oid) or _compute(oid, auth)
        if not any(activity.lower() in str(s.get("activities", "")).lower() for s in scopes):
            return                               # no policy covers this activity
        now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S")
        body = {"contentToProcess": {
            "contentEntries": [{
                "@odata.type": "microsoft.graph.processConversationMetadata",
                "identifier": str(uuid.uuid4()),
                "content": {"@odata.type": "microsoft.graph.textContent", "data": text},
                "agents": [{"@odata.type": "microsoft.graph.aiAgentInfo", "blueprintId": BLUEPRINT_APP_ID,
                            "identifier": AGENT_IDENTITY_ID, "name": AGENT_NAME, "version": APP_VERSION}],
                "name": f"{AGENT_NAME} {activity}", "correlationId": conversation_id,
                "sequenceNumber": sequence, "isTruncated": False,
                "createdDateTime": now, "modifiedDateTime": now}],
            "activityMetadata": {"activity": activity},
            "deviceMetadata": {"operatingSystemSpecifications": {
                "operatingSystemPlatform": "Amazon Bedrock AgentCore", "operatingSystemVersion": "Runtime"}},
            "protectedAppMetadata": {"name": AGENT_NAME, "version": APP_VERSION, "applicationLocation": LOCATION},
            "integratedAppMetadata": {"name": AGENT_NAME, "version": APP_VERSION}}}
        r = _http.post(f"{GRAPH}/users/{oid}/dataSecurityAndGovernance/processContent",
                       headers={"Authorization": auth, "If-None-Match": etag}, json=body)
        r.raise_for_status()
        result = r.json() if r.content else {}
        if result.get("protectionScopeState") == "modified":
            _scopes.pop(oid, None)               # policies changed: compute again next time
        actions = result.get("policyActions") or []
    except Exception:
        log.warning("Purview %s check failed", activity)
        if FAIL_CLOSED:
            raise Blocked()
        return                                   # fail open unless configured otherwise
    if any(a.get("action") == "restrictAccess" and a.get("restrictionAction") == "block" for a in actions):
        raise Blocked()

(Shortened: the implementation also prefers the inline-evaluated scope when several cover one activity, takes a lock around the cache, and logs the outcome without content.)

Design decisions in that code:

  • Prompt first, answer second. The prompt is checked before the model sees it; the answer before it is returned.
  • Only user turns. A user’s policies can’t be evaluated without the user, so turns where the agent acts on its own (app-only) aren’t checked.
  • Fail open by default. A Purview outage logs a warning and the agent carries on, unless PURVIEW_FAIL_CLOSED=true. Decide this deliberately for each agent.
  • The block message is fixed and names Purview, so users know it was policy, not a fault.

6.2 Permissions

The agent identity needs two delegated Microsoft Graph permissions, consented for all users: ProtectionScopes.Compute.User and Content.Process.User. They are in the agents.yaml example above and arrive through the approval-gated access flow like every other grant.

6.3 The DLP policy

The policy’s location is the agent identity as an Entra application. At the time of writing this was done with Security & Compliance PowerShell:

Show codeHide codepowershell · 15 lines
Connect-IPPSSession -UserPrincipalName <admin-upn> -DisableWAM

$name = 'Block card numbers in <agent-name>'
$loc = @(@{ Workload = 'Applications'; Location = '<agent-identity-id>'; LocationDisplayName = '<agent-name>';
            LocationSource = 'Entra'; LocationType = 'Individual';
            Inclusions = @(@{ Type = 'Tenant'; Identity = 'All' }) }) | ConvertTo-Json -Depth 6 -Compress -AsArray

New-DlpCompliancePolicy -Name $name -Locations $loc -EnforcementPlanes @('Application') -Mode Enable `
  -Comment 'Blocks prompts with credit card numbers for <agent-name>, evaluated inline through processContent.'

New-DlpComplianceRule -Name 'Block credit card numbers in prompts' -Policy $name `
  -ContentContainsSensitiveInformation @(@{ Name = 'Credit Card Number'; minCount = '1' }) `
  -RestrictAccess @(@{ setting = 'UploadText'; value = 'Block' }) -ReportSeverityLevel High

Get-DlpCompliancePolicy -Identity $name | Select-Object Name, Mode, DistributionStatus

These are the commands that ran in the lab (PowerShell 7, ExchangeOnlineManagement module). Building -Locations with ConvertTo-Json -AsArray avoids quoting mistakes in hand-written JSON. It is a preview feature, so check the current Microsoft documentation for the schema before you rely on it.

Details that matter:

  • Policy names have a 64-character limit. A 67-character name failed.
  • Distribution takes time, and the status lags. DistributionStatus starts as Pending. In this test the block took effect about 7 minutes after the policy was created, while the status still showed Pending; in an earlier test, on another agent, it took about 40 minutes. Test a few minutes after creating the policy, and test again later before concluding it doesn’t work.
  • Only UploadText can be blocked for a custom agent. Answers (downloadText) are checked and recorded, not blocked.
  • Test with a realistic prompt. Purview may not recognize a bare number as a card. Include the words “credit card number” and an expiry date, for example: “Refund order 1001 to my Visa credit card number 4111 1111 1111 1111, expiry 12/28, CVV 123.” (4111 1111 1111 1111 is a public test number.)

6.4 Where it shows

PlaceWhat to look for
Unified audit log / Purview AuditConnectedAIAppInteraction (workload ConnectedAIApp, RecordType 328) for each checked prompt and answer; DLPRuleMatch (RecordType 263) with PolicyDetails: policy, rule, sensitive information type, actions
Purview > DSPM > Discover > Activity explorer > AI activities tabThe interactions, under AI app category “Enterprise AI apps”
Defender advanced huntingThe same records in CloudAppEvents

Three things that trip people up. Use the AI activities tab: “All activity types” is the Information Protection explorer for labeled files and email. The App column shows Entra - <agent-identity-id>, not the agent’s name, so filter with Agents involved. Allow about 15 minutes for ingestion. The Purview portal also showed a banner saying the classic DSPM for AI experience retires on 30 November 2026, so use the new DSPM.

6.5 Result of the AgentCore test

Once the DLP policy scoped to the agent identity had distributed, the card-number prompt sent as a signed-in user was blocked inside the agent. The reply was the fixed message: “Your request was blocked by your organization’s data loss prevention policy (Microsoft Purview).”

Purview Audit then showed, for the test agents over the last day:

RecordCountWhat it was
ConnectedAIAppInteraction3The agent’s prompt and answer checks sent to processContent
DLPRuleMatch (workload ComplianceDLPApplications)1The card prompt matching the new policy’s rule; it lines up with the single card prompt sent
New-DlpCompliancePolicy1The policy’s creation

The same interactions appear under DSPM > Activity explorer > AI activities.

One naming detail: Purview Audit search returned the agent’s run and tool records under the operation names AIInvokeAgent and AIExecuteTool, while Defender CloudAppEvents shows the same records as InvokeAgent and ExecuteToolBySDK. When you search in Purview Audit, include both sets of names.

How to know it worked

Give the agent a diagnostic mode that performs each step and returns decoded claims only, never tokens. Then check:

CheckExpectedEvidence in the test
Request with no tokenRejected before the container runs (401 or 403)401 from AgentCore; no container log
Token for a different blueprint401401: the runtime accepts only its own blueprint as audience
Caller token (forwarded)aud = blueprint, iss ends in /v2.0, scp = access_agentMatched
AWS assertioniss = account issuer, sub = <agentcore-role-arn>, aud = api://AzureADTokenExchangeMatched
T1azp = blueprint, sub ends with the agent identityMatched
App-only tokenazp = oid = agent identity, roles = Inventory.Read.AllMatched, Python and .NET
On-behalf-of tokenoid = user, azp = agent identity, scp = Inventory.ReadMatched, Python and .NET
Agent 365 tokenroles = Agent365.Observability.OtelWrite, inherited from the blueprintMatched, Python and .NET
Question as a signed-in userAnswered through the MCP toolTool log: delegated, with the user and the agent identity
Agent acting on its ownTool called app-onlyTool log: app-only, agent identity
TelemetryAudit records within minutesInvokeAgent ×5, InferenceCall ×4, ExecuteToolBySDK ×2
Unapproved agent identityAADSTS53003Observed in the October pilot, both languages
Purview DLPCard prompt blocked; DLPRuleMatchBlocked with the Purview message; DLPRuleMatch ×1, ConnectedAIAppInteraction ×3
Publishing (optional)Template uploaded and available; instance created through the request processTemplate ✅. Instance ❌: license, then 502 because AgentCore can’t accept the instance traffic’s token (see the optional publishing section and the appendix)

The .NET agent in the test implemented the diagnostic mode only (the token chain); the Python agent ran the full LangChain agent with the tool server.

Defender and Purview queries

Defender advanced hunting: which agent did what

Show codeHide codekusto · 9 lines
CloudAppEvents
| where Timestamp > ago(1d)
| where ActionType in ("InvokeAgent", "InferenceCall", "ExecuteToolBySDK", "ConnectedAIAppInteraction", "DLPRuleMatch")
| extend r = RawEventData
| extend Agent = coalesce(tostring(r.TargetAgentName), tostring(r.AgentName)),
         AgentId = coalesce(tostring(r.TargetAgentId), tostring(r.AgentId))
| where Agent == "<agent-name>"
| summarize Events = count(), FirstSeen = min(Timestamp), LastSeen = max(Timestamp)
    by Agent, AgentId, Workload = tostring(r.Workload), ActionType

coalesce handles both shapes: the Agent 365 records name the invoked agent as TargetAgent..., while other workloads use AgentName and AgentId.

Defender advanced hunting: one request end to end

Show codeHide codekusto · 13 lines
CloudAppEvents
| where Timestamp > ago(1d)
| where ActionType in ("InvokeAgent", "InferenceCall", "ExecuteToolBySDK")
| extend r = RawEventData
| extend Agent   = coalesce(tostring(r.TargetAgentName), tostring(r.AgentName)),
         TraceId = coalesce(tostring(r.TraceId), tostring(r.CopilotEventData.TraceId)),
         Model   = tostring(parse_json(tostring(r.CopilotEventData.ModelTransparencyDetails[0])).ModelName),
         Tool    = tostring(r.ToolName),
         User    = tostring(r.UserId)
| where Agent == "<agent-name>"
| summarize Start = min(Timestamp), Steps = make_set(ActionType), Models = make_set_if(Model, isnotempty(Model), 5),
            Tools = make_set_if(Tool, isnotempty(Tool), 10), Users = make_set_if(User, User != "N/A", 5) by TraceId
| order by Start desc

Each row is one request: invoked by whom, which model it used, which tools it called. Filter on the coalesced name, not TargetAgentName alone: only InvokeAgent carries TargetAgentName, and the model and tool records name the agent in AgentName. Filtering on TargetAgentName silently drops every step except the invocation.

Purview Audit (portal)

Purview > Audit > New search. Activities: InvokeAgent, AIInvokeAgent, InferenceCall, ExecuteToolBySDK, AIExecuteTool, ConnectedAIAppInteraction (add DLPRuleMatch for policy matches). Purview Audit returned the run and tool records as AIInvokeAgent and AIExecuteTool, Defender as InvokeAgent and ExecuteToolBySDK, so search for both. Keyword: the agent name. Set the date range and run.

Purview Audit (PowerShell)

Show codeHide codepowershell · 5 lines
Connect-ExchangeOnline
Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-1) -EndDate (Get-Date) `
  -Operations InvokeAgent,AIInvokeAgent,InferenceCall,ExecuteToolBySDK,AIExecuteTool,ConnectedAIAppInteraction `
  -FreeText "<agent-name>" -ResultSize 500 |
  Select-Object CreationDate, Operations, UserIds, RecordType

For onboarding changes, search the same log for the AzureActiveDirectory operations listed in Phase 1.5.

Optional: offering the agent as an Agent 365 instance in Teams (not achieved on AWS AgentCore)

Everything so far makes the agent governed, and none of it depends on this section. Publishing is an optional extra: it makes the agent available to people in Microsoft 365, as an instance they request through Agent 365’s request and approval process and chat with in Teams. I tried it with the AgentCore agent’s blueprint on 5–6 November 2026. It got as far as an available template, not an instance.

In short
What worksGranting the blueprint the permissions instances use; registering the messaging endpoint, once a person owns the blueprint; the Developer Portal settings; a365 publish and the upload, after which the template shows as Available.
What blocks an instance(a) AgentCore’s JWT authorizer can’t accept the instance traffic’s token. Microsoft documents that this traffic carries an Azure Bot Service token, or an Entra token from Microsoft’s own service tenant (Secure your agent). AWS rejects the Bot Service discovery URL (openidconfiguration, without the hyphen), so Add instance returns a 502 and nothing reaches the agent. (b) Each instance gets its own agent user, which needs a license: the template page said “You have run out of licenses”.
What you’d need1. A small front end between Agent 365 and AgentCore. That’s a public HTTPS endpoint, for example API Gateway with a function, which validates the Bot Service (or Microsoft service) token itself, then calls AgentCore with a token AgentCore accepts (an Entra token for the blueprint). I didn’t build it. 2. A license for each instance’s agent user, which in practice means the Agent 365 subscription Microsoft names for autonomous agents. Check with your Microsoft account team. 3. A human owner on the blueprint, or endpoint registration done by an identity that owns it.

Everything up to the template works without these. The request and approval step itself (Request instance in Teams, then approval under Requests) wasn’t reached, because no instance could be created. The step-by-step results, the exact errors and the evidence are in the appendix at the end: Appendix: the instance test, step by step.

The documented flow

Microsoft documents the flow as:

  1. The developer runs a365 publish, which produces a manifest.zip.
  2. A Global Administrator uploads it: Microsoft 365 admin center > Agents > All agents > Upload custom agent.
  3. The agent appears as a template under Agents for your team (Teams and the Agent Store).
  4. A user selects Request instance.
  5. An administrator approves in Agents > All agents > Requests, activates the template, and assigns licenses and policies.
  6. The user selects Create instance; the instance messages the user in Teams.

Prerequisites: the tenant in the Frontier program, the “Microsoft Agent 365 Frontier” subscription, and a Global Administrator for the upload. Instances use Teams, so the agent needs a messaging endpoint, which an AgentCore agent called by API doesn’t have by default. Sources: Publish an agent, Onboard to Agent 365, Manage agent requests.

Lessons learned

Onboarding, security and observability

1. One blueprint per trust boundary. A blueprint can mint exchange tokens for every agent identity it owns. Give each runtime and its IAM role its own blueprint, and make sure no other blueprint still trusts that role. Here the AgentCore blueprint trusts only the AgentCore execution role, and the ECS blueprint no longer does.

2. Five AgentCore settings decide whether anything works. The v2 discovery document (v1 fails every call with Claim 'iss' value mismatch); no allowed_clients (AgentCore matches it against a client_id claim that Entra tokens don’t carry); request_header_allowlist = ["Authorization"] (without it on-behalf-of silently has no user token); a 300-second GetWebIdentityToken (longer fails with SessionDurationEscalationException); and arm64 images. In .NET, also leave AzureAd:Audience unset: api://<blueprint> rejects v2 tokens with a bare 401.

3. The agent identity holds the permissions, never the blueprint. A blueprint asking for an app-only token for another resource fails with AADSTS82001 (for example Bot Framework, if you try to put the agent on a Teams channel), and a blueprint asking for another blueprint’s agent identity fails with AADSTS7002134.

4. Inheritable permissions keep per-agent grants small. OtelWrite granted once to the blueprint principal and marked inheritable means each new agent can send telemetry with no grant of its own; the agent’s access section carries only what is specific to it.

5. Teardown should remove runtime resources, not identities that grants point at. A teardown that tried to delete the tools API’s service principal, through a pipeline identity that no longer owned it, hung for 30 minutes: Graph answered “forbidden” rather than “not found”, and the provider kept retrying. The fix was to destroy only the cloud runtime resources and keep the Entra app registrations that grants refer to.

6. Know the Entra recycle bin. A deleted service principal can be restored from it, and its grants come back with it.

7. Purview DLP needs patience and a realistic test. Names under 64 characters, allow for distribution (the block worked after about 7 minutes while the status still said Pending, and took about 40 minutes in an earlier test), test prompts that look like real card data, and remember that a custom agent can block prompts only.

8. Read the Target fields. In Agent 365 audit records the invoked agent is TargetAgentName / TargetAgentId; the top-level AgentId is all zeros unless an agent called another agent, and Defender’s AccountObjectId is empty. Queries on the obvious column find nothing.

9. Return claims, not tokens, when debugging. A diagnostic mode that returns selected claims for each hop, and AADSTS codes on failure, found every identity problem in minutes without a token leaving the container.

10. Write a blueprint’s inheritable permissions one at a time. Two new inheritable-permission entries written to the same blueprint at the same moment left one missing (the next update failed with Request_ResourceNotFound) and the other without its settings. Applying the changes one after another, and retrying a new entry until it can be read back, fixed it.

11. Search Purview Audit under both names. Purview Audit search lists agent runs and tool calls as AIInvokeAgent and AIExecuteTool, while Defender shows the same records as InvokeAgent and ExecuteToolBySDK.

12. Make the plan step fail when Terraform fails. A pull-request plan reported success while Terraform had errored, because the shell step lacked pipefail and stderr wasn’t captured. Reviewers saw a green check on a broken plan. Set pipefail and post the error to the pull request.

13. Don’t edit a blueprint’s description casually. Changing it re-applies the blueprint principal’s and API’s settings, and that can drop pre-authorized client applications such as the Azure CLI. Treat descriptions as fixed once created, or re-apply the full settings deliberately.

14. Check tenant-wide policies before choosing a state backend. A tenant-root Azure Policy initiative that forces public network access off on storage accounts left GitHub-hosted runners unable to reach Terraform state in Azure Storage. Keeping state in an S3 bucket in the AWS account avoided it.

15. Ask for the agent claims before you rely on them. xms_par_app_azp, xms_act_fct, xms_sub_fct and idtyp are optional claims: an API whose app registration doesn’t request them gets tokens without them, so an agent-marker check rejects every agent. Add them to the API, then authorize on azp against a list of agent identity IDs, never on the blueprint (section 4.4).

Publishing as an Agent 365 instance

1. Give automation-created blueprints a human owner before publishing. A blueprint created by a pipeline has no owners. Registering its Teams messaging endpoint fails with “User … is not the owner of agent blueprint …” until a person is added as an owner. The Agent 365 CLI signs in interactively, so it can’t register the endpoint as the pipeline identity either.

2. AgentCore can’t be an Agent 365 instance endpoint on its own. Instance traffic carries Azure Bot Service (or Microsoft service-tenant) tokens. AgentCore’s authorizer rejects Bot Service’s discovery URL outright, because of the missing hyphen in openidconfiguration. The admin center only shows a 502, and AgentCore logs no rejected tokens. The proof was AgentCore’s Invocations and InboundAuthorizationSuccess metrics staying at zero while containers started. Plan a small front end if you want instances.

3. Instances need licenses you may not have. Each instance gets an agent user that needs a license. The template page warns “You have run out of licenses”, and Add instance stays unavailable until one is free. Check with your account team which subscription your tenant needs before you plan a rollout.

Common problems

Problems in onboarding, security and observability

SymptomCauseFix
Every call: Claim 'iss' value mismatchv1 discovery URLUse .../v2.0/.well-known/openid-configuration
401/403 from AgentCore, container never invokedNo or invalid token; token for another blueprint; allowed_clients setCheck the caller’s aud and iss; remove allowed_clients
SessionDurationEscalationExceptionAWS token lifetime longer than the runtime sessionDurationSeconds=300
AADSTS70021 at step 1Issuer or subject differs from the federated credential (case, renamed role, wrong blueprint)Compare the AWS token’s iss/sub with the blueprint’s credential
AADSTS50013 at step 2bCaller token’s audience isn’t the blueprintRequest the token for api://<blueprint-app-id>/access_agent
On-behalf-of fails: no user tokenAuthorization not allowlistedrequest_header_allowlist = ["Authorization"]
AADSTS50105 / AADSTS53003Caller not assigned / agent identity not approvedAdd the caller to the group / set the approval attribute
AADSTS82001 / AADSTS7002134Token requested as the blueprint, or for another blueprint’s agentRequest tokens as the agent identity, from its own blueprint
API rejects every agent as “not an agent identity token”The agent claims are optional claims the API never requestedAdd idtyp, xms_par_app_azp, xms_act_fct, xms_sub_fct as access token optional claims (section 4.4)
Tool server 403Grant missing, or the access run not yet approvedCheck the agent’s access section and the access run
No audit recordsTelemetry set up after LangChain loaded, two tracer providers, or ingestion delayImport telemetry first; one provider; wait a few minutes
Defender query finds nothingFiltering on AccountObjectId or top-level AgentIdFilter on RawEventData.TargetAgentName / TargetAgentId
Card prompt not blockedPolicy still Pending, not scoped to the agent identity, or card not recognizedWait; check -Locations; include “credit card number” and an expiry
DSPM shows no AI activityWrong tab or filterActivity explorer > AI activities; filter by Agents involved; allow ~15 minutes
Teardown hangs for 30 minutesDeleting an Entra object the pipeline no longer ownsDestroy runtime resources only
Platform run: Request_ResourceNotFound on an inheritable permissionTwo inheritable-permission writes to one blueprint at the same timeApply them one at a time; retry until the new entry is readable

Problems when publishing as an Agent 365 instance

SymptomCauseFix
a365 setup blueprint --endpoint-only fails: “is not the owner of agent blueprint”The blueprint was created by automation and has no ownersAdd a person as an owner of the blueprint, then re-run
“You have run out of licenses” on the agent template; Add instance unavailableNo free license for the instance’s agent userFree or add the license your tenant needs for agent users (check with your account team)
Add instance: “Request failed with status 502”Agent 365 can’t reach the agent: AgentCore rejects the instance traffic’s tokenPut a front end that validates Bot Service tokens in front of AgentCore
AgentCore rejects https://login.botframework.com/v1/.well-known/openidconfigurationAgentCore requires /.well-known/openid-configuration in the discovery URLNot configurable; use a front end

Sidecar or no sidecar?

The ECS article uses the Microsoft Entra auth sidecar; this one doesn’t. Both give the agent the same Entra identity and the same governance.

ChooseWhen
Sidecar (ECS, EKS, any host you control)You can run more than one container; you want Microsoft to own the protocol code in every language.
In-process, .NETThe host runs one container (AgentCore Runtime) and the agent is .NET: Microsoft.Identity.Web does the protocol, you supply the AWS token.
In-process, PythonThe host runs one container and the agent must be Python. It works, but you own about 60 lines of security-critical protocol code; test it with the claim checks above, and revisit when a supported library covers it.

Whichever you choose, keep each hosting pattern on its own blueprint.

What this gives you

  • An AgentCore agent with its own Entra agent identity, sponsor and registry entry, created from two YAML files, with every change reviewed in a pull request and recorded in the unified audit log.
  • No secret anywhere: AWS signs a five-minute token about the execution role; Entra trusts it for one role, one audience and one blueprint. The pipelines use OIDC too.
  • Permissions granted only after a person approves, least privilege by default, with telemetry inherited from the agent’s type.
  • Callers rejected before the container runs, by AgentCore, using Entra’s own keys and only the agent’s own blueprint as audience.
  • The agent can act for the user (the user’s policies and permissions apply) or as itself (Conditional Access for agents applies), and the tools it calls can tell which.
  • Prompts and answers checked by Purview on behalf of the user, before the model and before the user.
  • The same audit trail in Purview, Defender and the Microsoft 365 admin center as an agent hosted on Azure: every request, model call and tool call, attributed to the agent and the person behind it.

No sidecar, no token file, no second container. The only AWS-specific code is a call to STS whenever Entra needs a fresh assertion; everything else is Microsoft’s governance, applied to an agent that happens to run on AWS.

Appendix: the instance test, step by step

The detail behind the optional publishing section. I ran the flow end to end with the AgentCore agent’s blueprint on 5–6 November 2026. The setup steps work; creating an instance doesn’t, for two separate reasons.

StepResult
Grant the blueprint the permissions instances use (Messaging Bot API AgentData.ReadWrite, Power Platform API Connectivity.Connections.Read, both inheritable)✅ Through the same approval-gated access flow as every other grant
Register the messaging endpoint (a365 setup blueprint --endpoint-only --messaging-endpoint <agentcore-invoke-url>)❌ first, then ✅. It failed with Forbidden: User '<user-object-id>' is not the owner of agent blueprint with ID '<blueprint-app-id>'. A blueprint created by automation has no owners, and only an owner can register the endpoint. After adding the administrator as an owner, the same command succeeded. The AgentCore invoke URL, with its URL-encoded ARN and ?qualifier=DEFAULT, was accepted
Developer Portal: Agent Type API Based, Notification URL = the same URL✅
a365 publish, then upload manifest.zip (Agents > All agents > Upload custom agent), published to one user✅ The template showed as Available
License for the instance⚠️ The template page said “You have run out of licenses”, and Add instance was unavailable. Each instance gets its own agent user, which needs a license. The tenant had no Microsoft Agent 365 Frontier subscription, and E7 seats on their own didn’t clear the warning
Add instance❌ “Request failed with status 502”
Did Agent 365 reach the agent?❌ AgentCore counted no authorized invocations during the attempts. Containers started, but nothing reached the agent’s code: AgentCore’s Invocations and InboundAuthorizationSuccess metrics stayed at zero
Can AgentCore accept the instance traffic’s token?❌ No. Pointing the runtime’s JWT authorizer at Azure Bot Service failed validation (see below)

The decisive result was the last one. Microsoft documents that traffic to an agent’s messaging endpoint carries an Azure Bot Service token, or an Entra token from Microsoft’s own service tenant (Secure your agent). AgentCore’s authorizer here accepts only your tenant’s Entra tokens issued for the blueprint, so it turns those calls away, and the admin center reports a 502. Switching the authorizer to Bot Service isn’t possible: AWS rejects the change, because AgentCore requires the discovery URL to end in /.well-known/openid-configuration (or oauth-authorization-server), and Bot Service publishes its metadata at /.well-known/openidconfiguration, without the hyphen:

ValidationException: Value 'https://login.botframework.com/v1/.well-known/openidconfiguration'
at 'authorizerConfiguration.customJWTAuthorizer.discoveryUrl' failed to satisfy constraint:
Member must satisfy regular expression pattern:
[^\s?#]+/\.well-known/(openid-configuration|oauth-authorization-server)(/[^\s?#]+)?

So an AgentCore agent can be onboarded, governed, protected and observed through Agent 365 exactly as the rest of this article describes; offering it as an instance needs the front end, the license and the blueprint owner listed in the optional publishing section.

Discussion

Comments are powered by Giscus / GitHub Discussions. They appear here once configured — see Configure Giscus in the project README and update GISCUS in src/consts.ts.