PowerShell Speaks A2A: Let Your Foundry Agents Call Each Other

Over the last few posts we’ve built quite a few agents. A hosted one, one with memory, a scheduled one in and a script reviewer. Every one of them was its own island. If I wanted agent A to use agent B’s skills, I had to sit in the middle and copy answers back and forth.

At Ignite (17 to 20 November) Microsoft made Agent-to-Agent (A2A) generally available in Foundry Agent Service. A2A is an open protocol that lets agents find each other and hand work over. Two things caught my attention in the docs. Turning on incoming A2A isn’t in the Foundry portal yet, so you need the REST API or the Python SDK. And the protocol itself is plain JSON-RPC over HTTPS.

Time to play around and see how this works!

🎬 marks steps to follow, 📒 marks deep-dives. Let’s go! 🚀

Oh before I forget, the script used in this blog for managing foundry can be found at the bottom of this blog.

What We’re Building

Two agents and one PowerShell console:

  • PS-Reviewer-a2a: a prompt agent that reviews PowerShell scripts. We expose it as an A2A endpoint with an agent card.
  • PowerShell as an A2A client: we read the agent card and send the reviewer a script, the same way any other A2A client would.
  • PS-Coordinator: a second agent with an A2A tool. Ask it “can this go to production on Friday?” and it delegates the review to the reviewer, then gives you a release recommendation.
. .\Manage-FoundryA2A.ps1

Set-FoundryAgentEndpoint -FoundryEndpoint $endpoint -AgentName "ps-reviewer-a2a" `
    -Version 1 -EnableA2A -AgentCard $card

Send-A2AMessage -A2AUrl $a2aUrl -Message "Review this script." -ScriptPath .\samples\Get-StaleUsers.ps1

MCP or A2A?

In my previous blogs we built MCP servers and clients, so it’s fair to ask what A2A adds. They connect different things:

MCPA2A
ConnectsAn agent to toolsAn agent to another agent
The other side isA function: input in, result outAn agent with its own model, instructions and reasoning
Describes itself withA tool list with JSON schemasAn agent card with skills and examples
Unit of workA tool callA task, inside a context that can span turns
Typical question“Run Get-Service on server X”“Review this script and tell me if it’s safe”

📒 My rule of thumb: if you know exactly what should happen, write a tool. If you want to hand over a problem and let someone else decide how to solve it, that someone is an agent, and A2A is how you reach it.

Prerequisites

  • A Foundry project with a model deployment. I’m using gpt-5.4-mini again.
  • Foundry User on the project to create agents, and Foundry Project Manager to create the A2A connection in step 5.
  • To call an A2A endpoint you need Foundry Agent Consumer (or a role that includes endpoint access) on the project or the agent. As project owner you probably have that already. The coordinator agent doesn’t, and we fix that in step 6.
  • Azure CLI (az login) and PowerShell 7+.

How A2A Works in Foundry

📒 Three concepts are worth knowing before we write any code.

The agent card. This is the agent’s business card: a name, a description and a list of skills, each with tags and examples. A client reads the card first, and so does the model of a calling agent. When the coordinator decides whether to delegate, the card’s description is what it has to go on. Write it like documentation, because that’s what it is.

Two protocol versions on one URL. Foundry supports A2A 1.0 (GA) and 0.3 (preview), both under the same base path:

https://<account>.services.ai.azure.com/api/projects/<project>/agents/<agent>/endpoint/protocols/a2a

You must choose the 1.0 version using the agent card path (/agentCard/v1.0), the A2A-Version: 1.0 header, or the ?a2a-version=1.0 query. If you don’t choose, Foundry defaults to version 0.3. This can cause issues, so always include it in your scripts. Do not use both the header and the query string with different values, or Foundry will return an HTTP 400 error for version conflict.

Tasks and contexts. You send a message. The agent answers with either a direct message or a task that has a state (TASK_STATE_COMPLETED, TASK_STATE_INPUT_REQUIRED, and so on) and artifacts holding the output. Every message belongs to a context: send the same contextId again and the agent continues the conversation. Foundry keeps tasks and contexts for 60 days after the last write.

🎬 Step 1: Create the Reviewer

A plain prompt agent this time. The harness from the previous blog here has its own endpoint rules, and I want this post to be about A2A, not about combining two previews.

$endpoint = "https://your-resource.services.ai.azure.com/api/projects/your-project"
az login

$reviewer = New-FoundryPromptAgent -FoundryEndpoint $endpoint -AgentName "ps-reviewer-a2a" `
    -ModelDeployment "gpt-5.4-mini" -Instructions $reviewerInstructions `
    -Description "Reviews PowerShell scripts against house guidelines."

🎬 Step 2: Switch On A2A

This is the part the portal can’t do yet. It’s a single patch on the agent:

$card = @{
    version     = '1.0.0'
    description = 'Reviews PowerShell scripts for security, reliability and style. Send the full script as text.'
    skills      = @(
        @{
            id          = 'review-powershell'
            name        = 'Review a PowerShell script'
            description = 'Returns a verdict, a findings table with severity and line numbers, and a corrected script.'
            tags        = @('powershell', 'code-review', 'security')
            examples    = @('Review this script: Get-ChildItem | % { ... }')
        }
    )
}

Set-FoundryAgentEndpoint -FoundryEndpoint $endpoint -AgentName "ps-reviewer-a2a" `
    -Version $reviewer.Version -EnableA2A -AgentCard $card

📒 Under the hood that’s this request:

PATCH /agents/ps-reviewer-a2a?api-version=v1
Content-Type: application/merge-patch+json
{
  "agent_endpoint": {
    "version_selector": {
      "version_selection_rules": [
        { "type": "FixedRatio", "agent_version": "1", "traffic_percentage": 100 }
      ]
    },
    "protocol_configuration": { "responses": {}, "a2a": {} }
  },
  "agent_card": {
    "version": "1.0.0",
    "description": "Reviews PowerShell scripts ...",
    "skills": [ { "id": "review-powershell", "name": "Review a PowerShell script", "...": "..." } ]
  }
}

A few things to note here:

A protocol is on when its key is present. "a2a": {} looks like it does nothing, but having the key there is what switches A2A on. Leave responses in as well, because A2A requires an agent that uses the responses protocol.

The version selector belongs to the endpoint, not the agent. Create version 2 and the endpoint keeps routing to version 1 until you patch it again. That’s annoying the first time and useful once you’re in production: FixedRatio with two rules gives you a canary rollout (90/10) on the same A2A URL.

Card limits. At least 1 and at most 16 skills, each with up to 5 tags and 5 examples. The REST spec enforces these limits, so a card with 17 skills fails at the PATCH.

🎬 Step 3: Read the Agent Card

Discovery is the first thing any A2A client does, so it’s our first call too:

$a2aUrl = Get-FoundryA2AUrl -FoundryEndpoint $endpoint -AgentName "ps-reviewer-a2a"
$agentCard = Get-A2AAgentCard -A2AUrl $a2aUrl

That’s a GET .../a2a/agentCard/v1.0 with a bearer token. Two security details:

  • Every A2A URL needs Microsoft Entra ID, including the card.
  • The token scope is https://ai.azure.com

🎬 Step 4: PowerShell as an A2A Client

$first = Send-A2AMessage -A2AUrl $a2aUrl -Message "Review this script." `
    -ScriptPath .\samples\Get-StaleUsers.ps1

It’s the same flawed script as in 2 blogs prior to this one: a hardcoded password in $pwd, aliases, Write-Host used for data, += in a loop, an Invoke-Expression and an empty catch {}.

📒 This is what goes over the wire:

{
  "jsonrpc": "2.0",
  "id": "5f0c...",
  "method": "SendMessage",
  "params": {
    "message": {
      "messageId": "a81e...",
      "role": "ROLE_USER",
      "parts": [ { "text": "Review this script. ..." } ]
    }
  }
}

If you’ve seen A2A examples online, they probably look slightly different, Three things in versions;

0.31.0
Methodmessage/sendSendMessage
Role"user""ROLE_USER"
Text part{ "kind": "text", "text": "..." }{ "text": "..." }

Mix them up and you get a JSON-RPC error. Note that this error usually arrives in a 200 response: JSON-RPC puts errors in the body, not in the HTTP status. Invoke-RestMethod won’t throw, so Send-A2AMessage checks $response.error itself.

The answer comes back as result.task or result.message. The function handles both and pulls the text from the task’s artifacts (or from the status message if there are none). Foundry answered every call in my run with a task:

🎬 Now continue in the same context:

Send-A2AMessage -A2AUrl $a2aUrl -ContextId $first.ContextId `
    -Message "Which of your findings is the one you'd fix first, and why? Two sentences."

Same context ID, and the reviewer knows exactly which script you mean (it picked Invoke-Expression). Leave out -ContextId and it has no idea what you’re talking about. It needs to have some idea

🎬 Step 5: Give Another Agent an A2A Tool

Now the agents start talking to each other. The coordinator needs two things: a project connection that points at the reviewer, and an a2a tool that uses the connection.

$connection = New-FoundryA2AConnection -FoundryEndpoint $endpoint `
    -SubscriptionId $subscriptionId -ResourceGroup $resourceGroup `
    -ConnectionName "a2a-ps-reviewer" -TargetA2AUrl $a2aUrl
{
  "properties": {
    "authType": "AgenticIdentityToken",
    "category": "RemoteA2A",
    "target": "https://.../agents/ps-reviewer-a2a/endpoint/protocols/a2a",
    "audience": "https://ai.azure.com",
    "Credentials": {},
    "metadata": {}
  }
}

AgenticIdentityToken means the coordinator signs in as itself, with its own agent identity. No secret is stored anywhere. For a Foundry target, leave out the agent card path: Foundry finds the card and negotiates the version itself.

Then create the coordinator with the tool:

$a2aTool = @{
    type                  = 'a2a'
    a2a_version           = '1.0'
    project_connection_id = $connection.Id
}

$coordinator = New-FoundryPromptAgent -FoundryEndpoint $endpoint -AgentName "ps-coordinator" `
    -ModelDeployment "gpt-5.4-mini" -Instructions $coordinatorInstructions -Tools $a2aTool

Set-FoundryAgentEndpoint -FoundryEndpoint $endpoint -AgentName "ps-coordinator" -Version $coordinator.Version

Use type: "a2a", which is the GA tool for protocol 1.0. You’ll also find a2a_preview in samples. That’s the old 0.3 variant, and Microsoft keeps it for existing integrations only.

🎬 Step 6: Let the Coordinator In

Being in the same project isn’t enough. I tried it: I asked the coordinator for a review before granting anything, and this is what came back:

Not a 403, but an HTTP 400 with tool_user_error and “A user error occurred while executing a tool call.” Nothing in that message points at permissions, so remember it: tool_user_error on an A2A tool means “check the role first”. The calling identity needs Foundry Agent Consumer on the target:

$identity = Get-FoundryAgentIdentity -FoundryEndpoint $endpoint -AgentName "ps-coordinator"

Grant-FoundryAgentConsumer -SubscriptionId $subscriptionId -ResourceGroup $resourceGroup `
    -FoundryEndpoint $endpoint -TargetAgentName "ps-reviewer-a2a" -PrincipalId $identity.PrincipalId

📒 Two details I’d have got wrong without the docs:

Object ID, not client ID. The agent’s instance_identity has both. Role assignments need the principal_id. The docs call this out explicitly, and the two GUIDs look exactly alike, so it’s an easy one to get wrong.

Scope it to the agent. You can grant the role on the whole project, but the scope can also be one agent: .../projects/<project>/agents/ps-reviewer-a2a. Least privilege again: the coordinator can now call the reviewer and nothing else.

RBAC can take a few minutes to propagate. In my run, about three minutes passed between the grant and the next call (I spent them taking portal screenshots), and that was enough. If you still get tool_user_error right after granting, wait a bit before you start debugging.

🎬 Step 7: Ask the Coordinator

$run = Invoke-FoundryAgent -FoundryEndpoint $endpoint -AgentName "ps-coordinator" `
    -Message "Can this go to production on Friday?" -ScriptPath .\samples\Get-StaleUsers.ps1

“Fix first, not ready for production on Friday”, in 9.9 seconds and 2,241 tokens. The “Steps” line again lists everything in output that isn’t the final answer: one a2a_preview_call and one a2a_preview_call_output. Note the name. We created the tool as the GA a2a type, yet the output items still carry _preview in their type. If you filter on item types in your own code, filter on what the service actually returns, not on what you’d expect.

📒 Those items show exactly what one agent told the other:

$call = $run.Raw.output | Where-Object type -eq 'a2a_preview_call'
$call.arguments

This is my favourite screenshot of the whole post. The coordinator sends the full script, as expected. But look at how it phrases the request: “Return a verdict, findings table with severity and line numbers, and a corrected script.” I never told the coordinator that. Those are the words from the reviewer’s agent card. The calling model read the card and used it to write its delegation. That’s the agent card doing its job, and also the reason the security note further down matters.

Last check, in Foundry itself. Open the project from the Azure portal (Go to Foundry portal on the resource) and both agents are listed:

And under Traces the whole run is visible, including the call that failed without the role (0.001 seconds, 0 tokens):

Things to Know

Text only. Foundry’s A2A supports text. No files and no other modalities, which is why the script travels as text inside the message.

No streaming. Server-sent events aren’t supported, so SendStreamingMessage is out. For long-running work the A2A spec describes returnImmediately plus polling with GetTask. I haven’t tested whether Foundry supports that combination.

Responses protocol only. The target agent must speak responses. Prompt agents do by default. A hosted agent has to be built for it.

Agent cards are untrusted input. This is the one I’d underline. Microsoft doesn’t test or verify third-party A2A endpoints, and a card’s description can steer the model of the agent that reads it. Connecting to an external agent means a stranger gets to write part of your agent’s prompt. Enforce permissions outside the model, and log what you share.

Connected Agents are gone. If you used Connected Agents or agent.as_tool in the classic Agents API, the A2A tool (or workflows) is the replacement in the new Agent Service.

No Foundry-Features header needed. In the REST spec the endpoint PATCH carries an optional A2AAgents=V1Preview header. For a prompt agent on A2A 1.0 it isn’t needed: my PATCH went through without it. A2A passthrough to hosted agents is still preview and does need it; that’s what the -Features parameter on Set-FoundryAgentEndpoint is for.

Wrapping Up

Up to now, every agent in this series did its job alone. With A2A, the reviewer from this post becomes a service: any agent, in Foundry or elsewhere, can read its card and hand it a script. And because the protocol is plain JSON-RPC, two PowerShell functions are enough for a working A2A client, with no SDK needed.

Next step for me: putting an agent that isn’t in Foundry on the other end of the line. 😉

Until next time, happy scripting! 🚀

Resources

#Save this file for manaaging a2a foundry

function Get-FoundryHeaders {
    param(
        [ValidateSet('Foundry', 'Arm')]
        [string]$Audience = 'Foundry',
        [string]$Features                    # optional Foundry-Features header value
    )

    $resource = if ($Audience -eq 'Arm') { 'https://management.azure.com' } else { 'https://ai.azure.com' }
    $token = az account get-access-token --resource $resource --query accessToken -o tsv
    if ($LASTEXITCODE -ne 0) { throw "Failed to get an access token for $resource. Run 'az login' first." }

    $headers = @{ Authorization = "Bearer $token" }
    if ($Features) { $headers['Foundry-Features'] = $Features }
    return $headers
}

function Invoke-FoundryJson {
    # Invoke-RestMethod with a UTF-8 JSON body and readable errors
    param(
        [Parameter(Mandatory)] [string]$Method,
        [Parameter(Mandatory)] [string]$Uri,
        [Parameter(Mandatory)] [hashtable]$Headers,
        [object]$Body,
        [string]$ContentType = 'application/json; charset=utf-8',
        [int]$TimeoutSec = 300
    )

    $splat = @{ Method = $Method; Uri = $Uri; Headers = $Headers; TimeoutSec = $TimeoutSec }
    if ($null -ne $Body) {
        $splat.Body        = [Text.Encoding]::UTF8.GetBytes(($Body | ConvertTo-Json -Depth 20))
        $splat.ContentType = $ContentType
    }

    try {
        return Invoke-RestMethod @splat
    }
    catch {
        $detail = if ($_.ErrorDetails.Message) { $_.ErrorDetails.Message } else { $_.Exception.Message }
        Write-Host "  $Method $Uri failed: $detail" -ForegroundColor Red
        throw
    }
}

function Get-FoundryProjectInfo {
    # https://<account>.services.ai.azure.com/api/projects/<project>  ->  account + project names
    param([Parameter(Mandatory)] [string]$FoundryEndpoint)

    if ($FoundryEndpoint.TrimEnd('/') -notmatch '^https://([^./]+)\.services\.ai\.azure\.com/api/projects/([^/]+)$') {
        throw "Unexpected project endpoint format: $FoundryEndpoint"
    }
    return [pscustomobject]@{ Account = $Matches[1]; Project = $Matches[2] }
}

function Get-FoundryA2AUrl {
    param(
        [Parameter(Mandatory)] [string]$FoundryEndpoint,
        [Parameter(Mandatory)] [string]$AgentName
    )
    return "$($FoundryEndpoint.TrimEnd('/'))/agents/$AgentName/endpoint/protocols/a2a"
}

function New-FoundryPromptAgent {
    # Creates the agent, or a new version when it already exists
    param(
        [Parameter(Mandatory)] [string]$FoundryEndpoint,
        [Parameter(Mandatory)] [string]$AgentName,
        [Parameter(Mandatory)] [string]$Instructions,
        [string]$ModelDeployment = 'gpt-5.4-mini',
        [object[]]$Tools = @(),
        [string]$Description
    )

    $headers = Get-FoundryHeaders
    $definition = @{ kind = 'prompt'; model = $ModelDeployment; instructions = $Instructions }
    if ($Tools) { $definition.tools = @($Tools) }

    $exists = $true
    try { Invoke-RestMethod -Method Get -Uri "$FoundryEndpoint/agents/$AgentName`?api-version=v1" -Headers $headers | Out-Null }
    catch {
        if ($_.Exception.Response.StatusCode.value__ -ne 404) { throw }
        $exists = $false
    }

    if ($exists) {
        $uri  = "$FoundryEndpoint/agents/$AgentName/versions?api-version=v1"
        $body = @{ definition = $definition }
    }
    else {
        $uri  = "$FoundryEndpoint/agents?api-version=v1"
        $body = @{ name = $AgentName; definition = $definition }
    }
    if ($Description) { $body.description = $Description }

    $response = Invoke-FoundryJson -Method Post -Uri $uri -Headers $headers -Body $body
    $version  = if ($response.version) { $response.version } else { $response.versions.latest.version }

    Write-Host "  Agent ready: $AgentName (version $version)" -ForegroundColor Green
    return [pscustomobject]@{ AgentName = $AgentName; Version = "$version" }
}

function Set-FoundryAgentEndpoint {
    # One merge-patch call: route traffic to a version, pick protocols, optionally publish an agent card
    param(
        [Parameter(Mandatory)] [string]$FoundryEndpoint,
        [Parameter(Mandatory)] [string]$AgentName,
        [Parameter(Mandatory)] [string]$Version,
        [switch]$EnableA2A,
        [hashtable]$AgentCard,                # @{ version; description; skills = @(...) }
        [string]$Features                     # e.g. 'A2AAgents=V1Preview' if the service asks for it
    )

    $protocols = @{ responses = @{} }
    if ($EnableA2A) { $protocols.a2a = @{} }

    $body = @{
        agent_endpoint = @{
            version_selector = @{
                version_selection_rules = @(
                    @{ type = 'FixedRatio'; agent_version = $Version; traffic_percentage = 100 }
                )
            }
            protocol_configuration = $protocols
        }
    }
    if ($AgentCard) { $body.agent_card = $AgentCard }

    $response = Invoke-FoundryJson -Method Patch -Uri "$FoundryEndpoint/agents/$AgentName`?api-version=v1" `
        -Headers (Get-FoundryHeaders -Features $Features) -Body $body -ContentType 'application/merge-patch+json'

    Write-Host "  Endpoint set: $AgentName -> version $Version ($(@($protocols.Keys) -join ', '))" -ForegroundColor Green
    if ($EnableA2A) {
        Write-Host "  A2A url: $(Get-FoundryA2AUrl -FoundryEndpoint $FoundryEndpoint -AgentName $AgentName)" -ForegroundColor DarkGray
    }
    return $response
}

function Get-FoundryAgentIdentity {
    # The principal the agent uses when it calls other things (A2A included)
    param(
        [Parameter(Mandatory)] [string]$FoundryEndpoint,
        [Parameter(Mandatory)] [string]$AgentName
    )

    $agent = Invoke-FoundryJson -Method Get -Uri "$FoundryEndpoint/agents/$AgentName`?api-version=v1" -Headers (Get-FoundryHeaders)
    if (-not $agent.instance_identity.principal_id) {
        throw "Agent '$AgentName' has no instance_identity yet. Give Foundry a minute after creation and try again."
    }
    return [pscustomobject]@{
        PrincipalId = $agent.instance_identity.principal_id   # use this one for role assignments
        ClientId    = $agent.instance_identity.client_id
        Status      = $agent.instance_identity.status
    }
}

# ---------------------------------------------------------------------------
# A2A client: PowerShell talks to an agent
# ---------------------------------------------------------------------------

function Get-A2AAgentCard {
    param(
        [Parameter(Mandatory)] [string]$A2AUrl,
        [ValidateSet('1.0', '0.3')] [string]$Version = $script:A2AVersion
    )

    $card = Invoke-FoundryJson -Method Get -Uri "$($A2AUrl.TrimEnd('/'))/agentCard/v$Version" -Headers (Get-FoundryHeaders)

    Write-Host ""
    Write-Host "  $($card.name)" -ForegroundColor Cyan
    if ($card.description) { Write-Host "  $($card.description)" -ForegroundColor DarkGray }
    foreach ($interface in @($card.supportedInterfaces)) {
        if ($interface) { Write-Host "  $($interface.protocolBinding) $($interface.protocolVersion)  $($interface.url)" -ForegroundColor DarkGray }
    }
    $card.skills | Format-Table @{ n = 'Skill'; e = { $_.id } }, name, @{ n = 'Tags'; e = { $_.tags -join ', ' } } -AutoSize | Out-Host

    return $card
}

function ConvertFrom-A2AParts {
    param([object[]]$Parts)
    # v1.0 parts are discriminated by member name: a text part simply has a "text" member
    return (@($Parts) | Where-Object { $_.text } | ForEach-Object { $_.text }) -join "`n"
}

function Send-A2AMessage {
    param(
        [Parameter(Mandatory)] [string]$A2AUrl,
        [Parameter(Mandatory)] [string]$Message,
        [string]$ContextId,                   # pass the ContextId from an earlier call to continue
        [string]$ScriptPath                   # optional: a .ps1 to send along as text
    )

    $text = $Message
    if ($ScriptPath) {
        $content = Get-Content -Path $ScriptPath -Raw -ErrorAction Stop   # no file, no message
        $text = "$Message`n`nFile name: $(Split-Path $ScriptPath -Leaf)`n`n``````powershell`n$content`n``````"
    }

    $a2aMessage = @{
        messageId = [guid]::NewGuid().ToString()
        role      = 'ROLE_USER'               # 0.3 used "user"; 1.0 uses ROLE_USER
        parts     = @(@{ text = $text })      # 0.3 used { kind = 'text'; text = ... }
    }
    if ($ContextId) { $a2aMessage.contextId = $ContextId }

    $rpc = @{
        jsonrpc = '2.0'
        id      = [guid]::NewGuid().ToString()
        method  = 'SendMessage'               # 0.3 called this message/send
        params  = @{ message = $a2aMessage }
    }

    $headers = Get-FoundryHeaders
    $headers['A2A-Version'] = $script:A2AVersion

    Write-Host "  Sending over A2A..." -ForegroundColor Cyan
    $timer = [Diagnostics.Stopwatch]::StartNew()
    $response = Invoke-FoundryJson -Method Post -Uri $A2AUrl.TrimEnd('/') -Headers $headers -Body $rpc -TimeoutSec 600
    $timer.Stop()

    # JSON-RPC reports protocol errors in the body, often with HTTP 200
    if ($response.error) {
        throw "A2A error $($response.error.code): $($response.error.message) $($response.error.data | ConvertTo-Json -Compress -Depth 5)"
    }

    # The result holds either a task or a direct message
    $result = $response.result
    if ($result.task) {
        $task   = $result.task
        $answer = ConvertFrom-A2AParts -Parts @($task.artifacts | ForEach-Object { $_.parts })
        if (-not $answer) { $answer = ConvertFrom-A2AParts -Parts $task.status.message.parts }
        $state  = $task.status.state
        $ctx    = $task.contextId
        $taskId = $task.id
    }
    elseif ($result.message) {
        $answer = ConvertFrom-A2AParts -Parts $result.message.parts
        $state  = 'message'
        $ctx    = $result.message.contextId
        $taskId = $result.message.taskId
    }
    else {
        throw "Unexpected A2A result: $($result | ConvertTo-Json -Depth 10 -Compress)"
    }

    Write-Host ""
    Write-Host $answer
    Write-Host ""
    Write-Host "  $state in $([math]::Round($timer.Elapsed.TotalSeconds, 1))s  (context $ctx)" -ForegroundColor DarkGray

    return [pscustomobject]@{
        Text      = $answer
        State     = $state
        ContextId = $ctx
        TaskId    = $taskId
        Seconds   = [math]::Round($timer.Elapsed.TotalSeconds, 1)
        Raw       = $result
    }
}

function New-FoundryA2AConnection {
    # RemoteA2A project connection. AgenticIdentityToken = the calling agent signs in as itself.
    param(
        [Parameter(Mandatory)] [string]$FoundryEndpoint,
        [Parameter(Mandatory)] [string]$SubscriptionId,
        [Parameter(Mandatory)] [string]$ResourceGroup,
        [Parameter(Mandatory)] [string]$ConnectionName,
        [Parameter(Mandatory)] [string]$TargetA2AUrl
    )

    $info = Get-FoundryProjectInfo -FoundryEndpoint $FoundryEndpoint
    $uri  = "https://management.azure.com/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroup" +
            "/providers/Microsoft.CognitiveServices/accounts/$($info.Account)/projects/$($info.Project)" +
            "/connections/$ConnectionName`?api-version=2025-04-01-preview"

    # No agent card path for a Foundry target: Foundry resolves it and negotiates the version itself
    $body = @{
        properties = @{
            authType    = 'AgenticIdentityToken'
            category    = 'RemoteA2A'
            target      = $TargetA2AUrl
            audience    = 'https://ai.azure.com'
            Credentials = @{}
            metadata    = @{}
        }
    }

    Invoke-FoundryJson -Method Put -Uri $uri -Headers (Get-FoundryHeaders -Audience Arm) -Body $body | Out-Null

    # The agent definition wants the connection id; read it back from the project
    $connection = Invoke-FoundryJson -Method Get -Uri "$FoundryEndpoint/connections/$ConnectionName`?api-version=v1" -Headers (Get-FoundryHeaders)

    Write-Host "  Connection ready: $ConnectionName -> $TargetA2AUrl" -ForegroundColor Green
    return [pscustomobject]@{ Name = $ConnectionName; Id = $connection.id }
}

function Grant-FoundryAgentConsumer {
    # Lets one principal call one agent. Scope it to the agent, not the whole project.
    param(
        [Parameter(Mandatory)] [string]$SubscriptionId,
        [Parameter(Mandatory)] [string]$ResourceGroup,
        [Parameter(Mandatory)] [string]$FoundryEndpoint,
        [Parameter(Mandatory)] [string]$TargetAgentName,
        [Parameter(Mandatory)] [string]$PrincipalId,          # object id, NOT the client id
        [string]$PrincipalType = 'ServicePrincipal'
    )

    $info  = Get-FoundryProjectInfo -FoundryEndpoint $FoundryEndpoint
    $scope = "/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroup/providers/Microsoft.CognitiveServices" +
             "/accounts/$($info.Account)/projects/$($info.Project)/agents/$TargetAgentName"

    # eed3b665-... is the built-in "Foundry Agent Consumer" role
    az role assignment create --assignee-object-id $PrincipalId --assignee-principal-type $PrincipalType `
        --role 'eed3b665-ab3a-47b6-8f48-c9382fb1dad6' --scope $scope --only-show-errors | Out-Null
    if ($LASTEXITCODE -ne 0) { throw "Role assignment failed for $PrincipalId on $scope." }

    Write-Host "  Foundry Agent Consumer granted on $TargetAgentName" -ForegroundColor Green
    Write-Host "  RBAC can take a few minutes to land. A 403 right after this is normal; wait and retry." -ForegroundColor DarkGray
}

function Invoke-FoundryAgent {
    # Responses call on the agent's own endpoint, like #61 and #68
    param(
        [Parameter(Mandatory)] [string]$FoundryEndpoint,
        [Parameter(Mandatory)] [string]$AgentName,
        [Parameter(Mandatory)] [string]$Message,
        [string]$ScriptPath,
        [string]$PreviousResponseId
    )

    $text = $Message
    if ($ScriptPath) {
        $content = Get-Content -Path $ScriptPath -Raw -ErrorAction Stop   # no file, no message
        $text = "$Message`n`nFile name: $(Split-Path $ScriptPath -Leaf)`n`n``````powershell`n$content`n``````"
    }

    $body = @{ input = $text }
    if ($PreviousResponseId) { $body.previous_response_id = $PreviousResponseId }

    $uri = "$($FoundryEndpoint.TrimEnd('/'))/agents/$AgentName/endpoint/protocols/openai/responses?api-version=v1"

    Write-Host "  Working..." -ForegroundColor Cyan
    $timer = [Diagnostics.Stopwatch]::StartNew()
    $response = Invoke-FoundryJson -Method Post -Uri $uri -Headers (Get-FoundryHeaders) -Body $body -TimeoutSec 600
    $timer.Stop()

    $answer = ($response.output |
        Where-Object type -eq 'message' |
        ForEach-Object { $_.content } |
        Where-Object type -eq 'output_text' |
        ForEach-Object { $_.text }) -join "`n"

    # Everything that isn't the final message is something the agent did on the way, A2A calls included
    $steps = @($response.output | Where-Object type -ne 'message' | ForEach-Object type)

    Write-Host ""
    Write-Host $answer
    Write-Host ""
    if ($steps) {
        $summary = $steps | Group-Object | ForEach-Object { "$($_.Name) x$($_.Count)" }
        Write-Host "  Steps: $($summary -join ', ')" -ForegroundColor DarkGray
    }
    Write-Host "  Took $([math]::Round($timer.Elapsed.TotalSeconds, 1))s, $($response.usage.total_tokens) tokens" -ForegroundColor DarkGray

    return [pscustomobject]@{
        ResponseId = $response.id
        Text       = $answer
        Steps      = $steps
        Seconds    = [math]::Round($timer.Elapsed.TotalSeconds, 1)
        Raw        = $response
    }
}

function Remove-A2ADemo {
    param(
        [Parameter(Mandatory)] [string]$FoundryEndpoint,
        [string[]]$AgentName,
        [string]$SubscriptionId,
        [string]$ResourceGroup,
        [string]$ConnectionName
    )

    foreach ($name in $AgentName) {
        Invoke-FoundryJson -Method Delete -Uri "$FoundryEndpoint/agents/$name`?api-version=v1" -Headers (Get-FoundryHeaders) | Out-Null
        Write-Host "  Agent deleted: $name" -ForegroundColor Green
    }

    if ($ConnectionName) {
        if (-not ($SubscriptionId -and $ResourceGroup)) { throw "Pass -SubscriptionId and -ResourceGroup to delete the connection." }
        $info = Get-FoundryProjectInfo -FoundryEndpoint $FoundryEndpoint
        $uri  = "https://management.azure.com/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroup" +
                "/providers/Microsoft.CognitiveServices/accounts/$($info.Account)/projects/$($info.Project)" +
                "/connections/$ConnectionName`?api-version=2025-04-01-preview"
        Invoke-FoundryJson -Method Delete -Uri $uri -Headers (Get-FoundryHeaders -Audience Arm) | Out-Null
        Write-Host "  Connection deleted: $ConnectionName" -ForegroundColor Green
    }
    # Role assignments on a deleted agent scope are left behind as orphans; remove them in the portal (IAM) or with az role assignment delete
}

Leave a Reply

Your email address will not be published. Required fields are marked *