Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@

# AI Gateway is the model and tool front door for this sample.
AZURE_AI_GATEWAY_ENDPOINT="https://<gateway-host-name>/"
# MCP clients use this URL and send AZURE_AI_GATEWAY_API_KEY in the Api-Key header.
# Direct MCP clients use an Entra bearer token and need Tools User on this server.
AZURE_AI_GATEWAY_GITHUB_MCP_ENDPOINT="https://<gateway-host-name>/default/toolservers/github/mcp"
AZURE_AI_GATEWAY_API_KEY="<gateway-api-key>"
AZURE_AI_GATEWAY_MODEL="gpt-latest"
AZURE_AI_GATEWAY_MINI_MODEL="gpt-mini-latest"

Expand Down
4 changes: 4 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
FROM python:3.13-slim
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /usr/local/bin/

ARG UV_INDEX_URL=https://packagefeedproxy.microsoft.io/pypi/simple/
ARG UV_DEFAULT_INDEX=https://packagefeedproxy.microsoft.io/pypi/simple/
ARG PIP_INDEX_URL=https://packagefeedproxy.microsoft.io/pypi/simple/

WORKDIR /app

COPY . .
Expand Down
119 changes: 62 additions & 57 deletions IMPLEMENTATION_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ Functions application.
- `infra/foundry-agents/main.bicep` creates the agent project, storage,
Container Registry, monitoring, connections, and RBAC.
- `infra/ai-gateway/main.bicep` creates AI Gateway,
model provider, model registrations, runtime key, and workspace-based
model provider, model registrations, alias-scoped runtime roles, and workspace-based
Application Insights resource, and invokes
`infra/foundry-agents/github-connection.bicep` in the agents resource group.
- `chat.py` is a local console client for the Responses endpoint.
Expand All @@ -48,9 +48,9 @@ flowchart LR
github["GitHub MCP server"]

operator --> agent
agent -->|"model request (Entra ID or Api-Key)"| gateway
agent -->|"Entra ID and alias Models User"| gateway
agent -->|"Entra identity"| toolbox
toolbox -->|"project managed identity (AI Gateway User RBAC)"| gateway
toolbox -->|"project identity and server Tools User"| gateway
gateway -->|"managed identity and Foundry User RBAC"| models
gateway -->|"repository-scoped read-only credential"| github
```
Expand All @@ -74,9 +74,9 @@ Agent -> Foundry Toolbox -> AI Gateway -> GitHub MCP

`toolbox.yaml` declares one MCP source backed by the `aigw-github` project
connection. Bicep creates that `RemoteTool` / `ProjectManagedIdentity`
connection (`audience: https://azure-api.net/aigateway`) and assigns the
`AI Gateway User` (`caad7a21-134e-43f4-a550-c5ffc17e051c`) role on AI Gateway
to the Foundry project and account managed identities. The postprovision hook
connection (`audience: https://ai.gateway.azure.com`). The postprovision hook
assigns AI Gateway Tools User on `workspaces/default/toolServers/github`
to the Foundry project managed identity and
creates `repo-digest-tools` through the Foundry data-plane API using that
connection; it no longer runs `azd ai connection create`. `FoundryToolbox`
authenticates the agent-to-Toolbox request with Entra identity.
Expand Down Expand Up @@ -155,7 +155,7 @@ the command line.
> token's settings). Regenerate the token with an **expiration of 7 days or
> less** (step 3 below).
> - **Missing public-repo scope.** A fine-grained token cannot read a repository
> you do not own unless it is scoped with **Repository access → Public
> you do not own unless it is scoped with **Repository access -> Public
> repositories (read-only)** (step 5 below). "Only select repositories" cannot
> include a repo you do not administer, so it yields no read access.
>
Expand All @@ -170,8 +170,8 @@ the command line.
### 1. Create the token in the GitHub portal

1. Open <https://github.com/settings/personal-access-tokens/new>. This is
**Settings → Developer settings → Personal access tokens → Fine-grained
tokens → Generate new token**.
**Settings -> Developer settings -> Personal access tokens -> Fine-grained
tokens -> Generate new token**.
2. **Token name**: for example `foundry-ai-gateway-repo-digest`.
3. **Expiration**: choose the shortest window that fits your rotation policy. If
the repository owner belongs to an enterprise that caps fine-grained token
Expand All @@ -188,7 +188,7 @@ the command line.
- For a public repository you do not own, choose **Public repositories
(read-only)**. This grants the read-only `pull` permission with no
repository-permission selection required; skip to step 7.
6. **Repository permissions** (only when you selected a specific repository) —
6. **Repository permissions** (only when you selected a specific repository) :
set each of these to **Read-only** and leave everything else at **No
access**:
- Metadata (required; auto-selected)
Expand Down Expand Up @@ -216,7 +216,7 @@ export GH_TOKEN
azd provision
```

macOS (zsh — the default macOS shell). The `read` prompt syntax differs from
macOS (zsh; the default macOS shell). The `read` prompt syntax differs from
bash: the prompt goes *inside* the variable spec as `VAR?prompt`, and `-p` must
not be used (in zsh `-p` reads from a coprocess, so no prompt appears). Paste
one line at a time so `read` does not consume the following lines as input:
Expand Down Expand Up @@ -272,21 +272,20 @@ The root deployment creates three resource groups:
- `gateway` for the standalone AI Gateway, Gateway
monitoring, model provider, model registrations, and model aliases.

The only cross-group runtime authorization is the AI Gateway system identity's
Foundry User role assignment on the model account. The public Azure
Only the AI Gateway system identity receives runtime authorization on the
separate model account through its Foundry User assignment. The public Azure
role-definition ID used by the template is
`53ca6127-db72-4b80-b1b0-d745d6d5456d`.

The AI Gateway module uses the live `2025-09-01-preview` contracts:

- `Microsoft.ApiManagement/aigateways` with SKU `Premium`
- `Microsoft.ApiManagement/aigateways` with SKU `Standard`
- `Microsoft.ApiManagement/aigateways/workspaces`
- `Microsoft.ApiManagement/aigateways/workspaces/modelProviders`
- `Microsoft.ApiManagement/aigateways/workspaces/modelProviders/models`
- `Microsoft.ApiManagement/aigateways/workspaces/aliases`
- `Microsoft.ApiManagement/aigateways/workspaces/toolServers`
- `Microsoft.ApiManagement/aigateways/workspaces/telemetryExporters`
- `Microsoft.ApiManagement/aigateways/apiKeys`

`Microsoft.ApiManagement/aigateways` is a hidden resource type in the Azure
Portal until the portal extension rollout completes. Check **Show hidden types**
Expand All @@ -298,37 +297,34 @@ collection before configuring the GitHub ToolServer.

The gateway module receives the agents account and project names and managed
identity principal IDs from the Foundry module outputs, so it waits for project
provisioning. It assigns the `AI Gateway User`
(`caad7a21-134e-43f4-a550-c5ffc17e051c`) role on AI Gateway to the Foundry
project and account managed identities (and optional developer `principalId`),
provisioning. It assigns AI Gateway Models User
(`a6b68e3d-a1f0-4c60-8678-237c050cf4ea`) on the primary model alias to the
optional developer `principalId`,
and its nested connection module targets the agents resource group. The
connection target is `<gateway>/default/toolservers/github/mcp`, with
`authType: ProjectManagedIdentity` (`audience: https://azure-api.net/aigateway`),
`authType: ProjectManagedIdentity` (`audience: https://ai.gateway.azure.com`),
`isSharedToAll: true`, and `metadata.type: custom_MCP`. Stable resource names
and incremental deployments allow repeated `azd up` runs to update the same
connection.

When `useManagedIdentityForFoundryConnections: false` is explicitly opted into,
the connection falls back to `CustomKeys` using
`runtimeApiKey.listSecrets().?primaryKey ?? runtimeApiKey.listSecrets().?key` at
`2025-09-01-preview` (the live ARM `listSecrets` response returns `primaryKey`
and `secondaryKey`). The value crosses the module boundary only through an
`@secure()` parameter (`securestring` in ARM), never an output. Do not log
resolved deployment parameters or run the hooks with shell tracing/debug
logging.

Both postprovision hooks still retrieve the key with `listSecrets` (preferring
`key`, with legacy response-field and `listValues` compatibility fallbacks) and
save `AZURE_AI_GATEWAY_API_KEY` to the local azd environment for
`create-dev-env.sh`. They also inject the GitHub credential, check model-route
readiness, and create the data-plane Toolbox if absent. Failed-resource
recovery remains in the lifecycle scripts.

Compilation and regression tests verify the ARM expression, secure parameter,
dependencies, target, and absence of secret outputs. A fresh and repeated
`azd up` against the live preview service are still required to validate its
response contract and Toolbox attachment end to end; compilation alone cannot
verify a service response.
Both postprovision hooks inject the separate GitHub credential, deploy the
project's AI Gateway Tools User role
(`dce03f8d-857f-4e40-a90d-67770fa6ecd2`) at the GitHub tool-server scope after
that server exists, check the primary model route with a delegated Entra token,
and create the data-plane Toolbox if absent. Failed-resource recovery remains
in the lifecycle scripts. Neither the account identity nor the developer
receives tool-server access merely for owning or deploying the gateway.

Compilation and regression tests verify connection properties, exact runtime
role scopes, and absence of runtime key resources and retrieval. Live deployment
is needed to establish token acceptance, role propagation, and Toolbox behavior.

The postdeploy hook reads the deployed agent's `instance_identity.principal_id`
from `azd ai agent show --output json` and deploys
`infra/ai-gateway/agent-models-user-role.bicep`. That identity receives Models
User only on the primary alias. It is separate from the Foundry project identity,
which holds Tools User for the `aigw-github` remote-tool connection. Creating a
project role does not authorize an agent's own model requests.

### Native OpenTelemetry monitoring

Expand Down Expand Up @@ -391,7 +387,7 @@ Sexual, and Violence. With the default deployment capacities, `gpt-latest` and
and Violence; the
postprovision credential PUT preserves that policy. The alias `gpt-latest`
routes through a three-tier failover chain: `gpt-6.1-sol` at
priority 0, `gpt-6-sol` at priority 1, and `gpt-5.4-mini` at priority 2. Each
priority 0, `gpt-6-sol` at priority 1, and `gpt-5-mini` at priority 2. Each
backend explicitly sets a weight of 100; aliases can instead place multiple
backends at the same priority with relative weights for traffic splitting. The
separate `gpt-mini-latest` alias addresses the mini deployment directly. Each
Expand Down Expand Up @@ -429,11 +425,11 @@ The model defaults use Global Standard deployments:
| --- | --- | --- | --- | --- | --- |
| Primary | `gpt-latest` | `gpt-6.1-sol` | `2026-09-29` | `GlobalStandard` | 20 |
| Secondary failover | `gpt-6-sol` | `gpt-6-sol` | `2026-09-22` | `GlobalStandard` | 20 |
| Mini safety net | `gpt-mini-latest` | `gpt-5.4-mini` | `2026-03-17` | `GlobalStandard` | 200 |
| Mini safety net | `gpt-mini-latest` | `gpt-5-mini` | `2025-08-07` | `GlobalStandard` | 200 |

If the primary deployment is unavailable or its quota is exhausted, AI Gateway
automatically tries `gpt-6-sol` in a separate quota pool, then the higher-
capacity `gpt-5.4-mini` deployment. If a model/version is unavailable in the
capacity `gpt-5-mini` deployment. If a model/version is unavailable in the
selected region, override its corresponding name and version parameters with a
supported catalog deployment and keep the remaining fallback tiers configured.

Expand All @@ -447,19 +443,29 @@ uses an estimate based on the prompt and requested maximum output, so this cap
reduces avoidable reservation pressure on the follow-up call after MCP tool
execution.

## Runtime key handling

Bicep creates `apiKeys/default`. The postprovision hook retrieves the Gateway
key through `listSecrets` and retains `listValues` as a preview-contract
fallback. It can reuse the saved azd environment value when a later
reprovision cannot retrieve the value again.

The Gateway key is sent in the explicit `Api-Key` header. It is not sent as
`Authorization: Bearer`. The backing Foundry account has local authentication
disabled, and provisioning does not call the Foundry `listKeys` action.

The runtime fails when the Gateway endpoint or key is missing. It has no direct
Foundry fallback.
## Runtime authentication

All gateway runtime calls use `Authorization: Bearer` with Microsoft Entra ID.
Hosted identities request `https://ai.gateway.azure.com/.default`. Local runs
explicitly invoke `az account get-access-token --scope
https://ai.gateway.azure.com/Data.All`, cache the token in memory, and refresh
before expiry. AzureCliCredential must not translate Data.All into a resource
argument. Token acquisition failures stop the request without changing identity
or falling back to a key.

For the local developer and deployed agent identity, Models User is scoped to
`workspaces/default/aliases/primary-router`, whose
callable name is `gpt-latest`. Changing the client to the mini alias requires a
grant on `workspaces/default/aliases/mini-router`. A model behind a failover
alias does not require another caller role. Tools User is scoped only to
`workspaces/default/toolServers/github` for the project connection identity.
Management roles do not imply either runtime permission.

The deployment creates no gateway runtime keys and persists no gateway tokens.
The backing Foundry account has local authentication disabled, and provisioning
does not retrieve its keys. The runtime fails if its endpoint or credential is
unavailable; it has no direct Foundry fallback. See the root README for deploy
and bearer-call commands and HTTP 401/403 diagnosis.

## AI Gateway deletion lifecycle

Expand Down Expand Up @@ -531,7 +537,6 @@ The local file contains:

```bash
AZURE_AI_GATEWAY_ENDPOINT="https://<gateway-host-name>/"
AZURE_AI_GATEWAY_API_KEY="<gateway-api-key>"
AZURE_AI_GATEWAY_MODEL="gpt-latest"
AZURE_AI_GATEWAY_MINI_MODEL="gpt-mini-latest"

Expand Down
Loading
Loading