{
  "nbformat": 4,
  "nbformat_minor": 5,
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.13.0"
    },
    "blog_metadata": {
      "topic": "My playbook for giving Azure AI agents real tools without turning them into security incidents",
      "slug": "my-playbook-for-giving-azure-ai-agents-real-tools-without-tu",
      "generated_by": "LinkedIn Post Generator + Azure OpenAI",
      "generated_at": "2026-11-11T21:12:33.388Z"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# My playbook for giving Azure AI agents real tools without turning them into security incidents\n",
        "\n",
        "This notebook turns the blog post into a hands-on validation guide focused on secure tool design for Azure AI agents. The core idea is simple: model reasoning can be probabilistic, but authorization, approvals, and side effects must be deterministic, constrained, and auditable. You will validate allowlisted tool contracts, approval checks, idempotency, audit logging, and safe downstream execution patterns."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "%pip install fastapi pydantic pandas"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from __future__ import annotations\n",
        "\n",
        "import asyncio\n",
        "import base64\n",
        "import hashlib\n",
        "import json\n",
        "from datetime import datetime, timezone, timedelta\n",
        "from typing import Literal\n",
        "\n",
        "import pandas as pd\n",
        "from fastapi import FastAPI, Header, HTTPException\n",
        "from pydantic import BaseModel, Field, ValidationError"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Operating principle and action inventory\n",
        "\n",
        "Before choosing models or frameworks, inventory the actions an agent may take. The security boundary is the full chain from user intent through tool execution and audit, not the chat interface alone.\n",
        "\n",
        "This cell creates a simple action inventory and classifies each action by risk and disposition so you can validate whether a tool should be denied, narrowly allowed, approval-gated, or kept fully human."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "action_inventory = [\n",
        "    {\n",
        "        \"operation\": \"get_ticket_status\",\n",
        "        \"target_system\": \"Ticket API\",\n",
        "        \"data_classification\": \"internal\",\n",
        "        \"business_impact\": \"low\",\n",
        "        \"reversibility\": \"n/a\",\n",
        "        \"actor_identity\": \"delegated_user\",\n",
        "        \"required_approver\": \"none\",\n",
        "        \"allowed_environment\": \"prod\",\n",
        "        \"audit_requirement\": \"standard\",\n",
        "        \"bucket\": \"Read-only retrieval\",\n",
        "        \"disposition\": \"allow through a narrow tool\",\n",
        "    },\n",
        "    {\n",
        "        \"operation\": \"add_ticket_comment\",\n",
        "        \"target_system\": \"Ticket API\",\n",
        "        \"data_classification\": \"internal\",\n",
        "        \"business_impact\": \"medium\",\n",
        "        \"reversibility\": \"partial\",\n",
        "        \"actor_identity\": \"app_identity\",\n",
        "        \"required_approver\": \"service_owner\",\n",
        "        \"allowed_environment\": \"nonprod\",\n",
        "        \"audit_requirement\": \"enhanced\",\n",
        "        \"bucket\": \"Low-risk writes\",\n",
        "        \"disposition\": \"require approval\",\n",
        "    },\n",
        "    {\n",
        "        \"operation\": \"restart_approved_workload\",\n",
        "        \"target_system\": \"Azure workload\",\n",
        "        \"data_classification\": \"internal\",\n",
        "        \"business_impact\": \"high\",\n",
        "        \"reversibility\": \"partial\",\n",
        "        \"actor_identity\": \"app_identity\",\n",
        "        \"required_approver\": \"ops_manager\",\n",
        "        \"allowed_environment\": \"prod\",\n",
        "        \"audit_requirement\": \"strict\",\n",
        "        \"bucket\": \"High-impact changes\",\n",
        "        \"disposition\": \"require approval\",\n",
        "    },\n",
        "    {\n",
        "        \"operation\": \"export_sensitive_records\",\n",
        "        \"target_system\": \"Data platform\",\n",
        "        \"data_classification\": \"regulated\",\n",
        "        \"business_impact\": \"critical\",\n",
        "        \"reversibility\": \"none\",\n",
        "        \"actor_identity\": \"n/a\",\n",
        "        \"required_approver\": \"security_and_data_owner\",\n",
        "        \"allowed_environment\": \"prod\",\n",
        "        \"audit_requirement\": \"strict\",\n",
        "        \"bucket\": \"Irreversible or regulated actions\",\n",
        "        \"disposition\": \"require a human outside the agent\",\n",
        "    },\n",
        "]\n",
        "\n",
        "df_actions = pd.DataFrame(action_inventory)\n",
        "df_actions"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Tool contract with allowlisted actions and typed inputs\n",
        "\n",
        "A production tool should expose a narrow business verb, not a broad enterprise API. This example mirrors the blog's FastAPI pattern and shows that the service, not the prompt, enforces the contract.\n",
        "\n",
        "You can validate both successful and rejected requests using a typed request model and a strict action allowlist."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "app = FastAPI()\n",
        "ALLOWED_ACTIONS = {\"ticket.read\", \"ticket.comment\"}\n",
        "\n",
        "class ToolRequest(BaseModel):\n",
        "    action: Literal[\"ticket.read\", \"ticket.comment\"]\n",
        "    ticket_id: str = Field(min_length=3, max_length=32)\n",
        "    comment: str | None = Field(default=None, max_length=500)\n",
        "\n",
        "async def tool(req: ToolRequest, x_correlation_id: str):\n",
        "    if req.action not in ALLOWED_ACTIONS:\n",
        "        raise HTTPException(status_code=403, detail=\"action_not_allowed\")\n",
        "    return {\"accepted\": True, \"correlationId\": x_correlation_id, \"action\": req.action}\n",
        "\n",
        "valid_req = ToolRequest(action=\"ticket.read\", ticket_id=\"T-100\")\n",
        "valid_result = asyncio.run(tool(valid_req, x_correlation_id=\"corr-001\"))\n",
        "print(\"Valid result:\", valid_result)\n",
        "\n",
        "try:\n",
        "    ToolRequest(action=\"admin.delete\", ticket_id=\"T-100\")\n",
        "except ValidationError as exc:\n",
        "    print(\"\\nInvalid request rejected by typed contract:\")\n",
        "    print(exc)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Required variables and secret handling\n",
        "\n",
        "This notebook does not require live secrets to run. In production, keep secrets out of prompts, tool arguments, and model-visible responses.\n",
        "\n",
        "Typical infrastructure variables for a real deployment would include:\n",
        "- `TOOL_ALLOWED_ACTIONS`\n",
        "- `DOWNSTREAM_API_BASE`\n",
        "- `DOWNSTREAM_API_KEY` (prefer Key Vault reference or managed identity)\n",
        "- `AUDIT_MODE`\n",
        "- `APPROVAL_SIGNING_KEY` or equivalent approval validation material"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Approval token verification with scope and expiry\n",
        "\n",
        "High-impact actions should require a first-class approval state, not a model confidence score. This example validates a time-bound approval token and checks that the requested scope is explicitly allowed.\n",
        "\n",
        "The test cases below show success, expiry failure, and scope denial."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "def verify_approval_token(token: str, required_scope: str) -> dict:\n",
        "    try:\n",
        "        payload = json.loads(base64.urlsafe_b64decode(token + \"==\").decode())\n",
        "    except Exception as exc:\n",
        "        raise HTTPException(status_code=401, detail=\"invalid_approval_token\") from exc\n",
        "\n",
        "    exp = datetime.fromtimestamp(payload[\"exp\"], tz=timezone.utc)\n",
        "    if exp <= datetime.now(timezone.utc):\n",
        "        raise HTTPException(status_code=401, detail=\"approval_expired\")\n",
        "    if required_scope not in payload.get(\"scopes\", []):\n",
        "        raise HTTPException(status_code=403, detail=\"scope_denied\")\n",
        "    return payload\n",
        "\n",
        "def make_token(payload: dict) -> str:\n",
        "    raw = json.dumps(payload).encode()\n",
        "    return base64.urlsafe_b64encode(raw).decode().rstrip(\"=\")\n",
        "\n",
        "valid_payload = {\n",
        "    \"sub\": \"approver-123\",\n",
        "    \"exp\": int((datetime.now(timezone.utc) + timedelta(minutes=10)).timestamp()),\n",
        "    \"scopes\": [\"ticket.comment\", \"ticket.read\"],\n",
        "}\n",
        "expired_payload = {\n",
        "    \"sub\": \"approver-123\",\n",
        "    \"exp\": int((datetime.now(timezone.utc) - timedelta(minutes=10)).timestamp()),\n",
        "    \"scopes\": [\"ticket.read\"],\n",
        "}\n",
        "wrong_scope_payload = {\n",
        "    \"sub\": \"approver-123\",\n",
        "    \"exp\": int((datetime.now(timezone.utc) + timedelta(minutes=10)).timestamp()),\n",
        "    \"scopes\": [\"ticket.read\"],\n",
        "}\n",
        "\n",
        "valid_token = make_token(valid_payload)\n",
        "expired_token = make_token(expired_payload)\n",
        "wrong_scope_token = make_token(wrong_scope_payload)\n",
        "\n",
        "print(\"Valid approval:\")\n",
        "print(verify_approval_token(valid_token, \"ticket.comment\"))\n",
        "\n",
        "for label, token, scope in [\n",
        "    (\"Expired approval\", expired_token, \"ticket.read\"),\n",
        "    (\"Wrong scope\", wrong_scope_token, \"ticket.comment\"),\n",
        "]:\n",
        "    try:\n",
        "        verify_approval_token(token, scope)\n",
        "    except HTTPException as exc:\n",
        "        print(f\"\\n{label}: status={exc.status_code}, detail={exc.detail}\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Idempotency and correlated audit emission\n",
        "\n",
        "Every consequential action should be traceable and replay-safe. This example emits a correlated audit event before the downstream call and uses an idempotency key to prevent duplicate execution.\n",
        "\n",
        "Run it twice with the same key to confirm that the second call is treated as a replay."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "IDEMPOTENCY_STORE: dict[str, dict] = {}\n",
        "AUDIT_LOG: list[dict] = []\n",
        "\n",
        "def process_once(idempotency_key: str, correlation_id: str, body: dict) -> dict:\n",
        "    if idempotency_key in IDEMPOTENCY_STORE:\n",
        "        return {\"replayed\": True, \"result\": IDEMPOTENCY_STORE[idempotency_key]}\n",
        "\n",
        "    event = {\n",
        "        \"ts\": datetime.now(timezone.utc).isoformat(),\n",
        "        \"correlationId\": correlation_id,\n",
        "        \"bodyHash\": hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest(),\n",
        "        \"decision\": \"approved\",\n",
        "    }\n",
        "    AUDIT_LOG.append(event)\n",
        "    result = {\"status\": \"queued\", \"reference\": body[\"ticket_id\"]}\n",
        "    IDEMPOTENCY_STORE[idempotency_key] = result\n",
        "    return {\"replayed\": False, \"result\": result}\n",
        "\n",
        "body = {\"action\": \"ticket.read\", \"ticket_id\": \"T-103\"}\n",
        "first = process_once(\"same-key\", \"corr-103\", body)\n",
        "second = process_once(\"same-key\", \"corr-103\", body)\n",
        "\n",
        "print(\"First call:\", first)\n",
        "print(\"Second call:\", second)\n",
        "print(\"\\nAudit log:\")\n",
        "pd.DataFrame(AUDIT_LOG)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Safe downstream execution with timeout and sanitized response mapping\n",
        "\n",
        "Tool wrappers should bound execution time and return a controlled response shape back to the agent. They should never fall back to a broader, more privileged path when a narrow tool fails.\n",
        "\n",
        "This example simulates a downstream service, applies a timeout, and returns only minimal structured output."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "async def call_downstream(action: str, ticket_id: str, comment: str | None = None) -> dict:\n",
        "    if ticket_id == \"slow\":\n",
        "        await asyncio.sleep(1.2)\n",
        "    else:\n",
        "        await asyncio.sleep(0.05)\n",
        "    if action == \"ticket.read\":\n",
        "        return {\"ticketId\": ticket_id, \"state\": \"open\"}\n",
        "    if action == \"ticket.comment\":\n",
        "        return {\"ticketId\": ticket_id, \"commentAccepted\": bool(comment)}\n",
        "    raise ValueError(\"unsupported_action\")\n",
        "\n",
        "async def safe_tool_execution(req: dict) -> dict:\n",
        "    result = await asyncio.wait_for(\n",
        "        call_downstream(req[\"action\"], req[\"ticket_id\"], req.get(\"comment\")),\n",
        "        timeout=1.0,\n",
        "    )\n",
        "    return {\"ok\": True, \"data\": result}\n",
        "\n",
        "print(asyncio.run(safe_tool_execution({\"action\": \"ticket.read\", \"ticket_id\": \"T-200\"})))\n",
        "\n",
        "try:\n",
        "    print(asyncio.run(safe_tool_execution({\"action\": \"ticket.read\", \"ticket_id\": \"slow\"})))\n",
        "except TimeoutError as exc:\n",
        "    print(\"Timeout triggered as expected:\", type(exc).__name__)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## End-to-end governed tool flow validation\n",
        "\n",
        "This cell combines the earlier patterns into one transaction path: validate action against an allowlist, verify approval scope and expiry, enforce idempotency, call the downstream service with bounded execution, and emit correlated audit evidence.\n",
        "\n",
        "It also simulates negative cases such as malformed approval, expired approval, invalid scope, replay, timeout, and unsupported action."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "IDEMPOTENCY_STORE_E2E: dict[str, dict] = {}\n",
        "AUDIT_LOG_E2E: list[dict] = []\n",
        "ALLOWED_ACTIONS_E2E = {\"ticket.read\", \"ticket.comment\"}\n",
        "\n",
        "class GovernedToolRequest(BaseModel):\n",
        "    action: Literal[\"ticket.read\", \"ticket.comment\"]\n",
        "    ticket_id: str = Field(min_length=3, max_length=32)\n",
        "    comment: str | None = Field(default=None, max_length=500)\n",
        "\n",
        "\n",
        "def emit_audit(correlation_id: str, body: dict, decision: str, detail: str) -> None:\n",
        "    AUDIT_LOG_E2E.append(\n",
        "        {\n",
        "            \"ts\": datetime.now(timezone.utc).isoformat(),\n",
        "            \"correlationId\": correlation_id,\n",
        "            \"bodyHash\": hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest(),\n",
        "            \"decision\": decision,\n",
        "            \"detail\": detail,\n",
        "        }\n",
        "    )\n",
        "\n",
        "\n",
        "def process_once_e2e(idempotency_key: str, result: dict) -> dict:\n",
        "    if idempotency_key in IDEMPOTENCY_STORE_E2E:\n",
        "        return {\"replayed\": True, \"result\": IDEMPOTENCY_STORE_E2E[idempotency_key]}\n",
        "    IDEMPOTENCY_STORE_E2E[idempotency_key] = result\n",
        "    return {\"replayed\": False, \"result\": result}\n",
        "\n",
        "\n",
        "async def governed_tool_endpoint(body: dict, headers: dict) -> dict:\n",
        "    correlation_id = headers.get(\"x-correlation-id\")\n",
        "    approval_token = headers.get(\"x-approval-token\")\n",
        "    idempotency_key = headers.get(\"Idempotency-Key\", f\"auto-{hashlib.md5(json.dumps(body, sort_keys=True).encode()).hexdigest()}\")\n",
        "\n",
        "    if not correlation_id:\n",
        "        raise HTTPException(status_code=400, detail=\"missing_correlation_id\")\n",
        "\n",
        "    try:\n",
        "        req = GovernedToolRequest(**body)\n",
        "    except ValidationError as exc:\n",
        "        emit_audit(correlation_id, body, \"denied\", \"validation_error\")\n",
        "        raise HTTPException(status_code=422, detail=str(exc)) from exc\n",
        "\n",
        "    if req.action not in ALLOWED_ACTIONS_E2E:\n",
        "        emit_audit(correlation_id, body, \"denied\", \"action_not_allowed\")\n",
        "        raise HTTPException(status_code=403, detail=\"action_not_allowed\")\n",
        "\n",
        "    verify_approval_token(approval_token, req.action)\n",
        "\n",
        "    if idempotency_key in IDEMPOTENCY_STORE_E2E:\n",
        "        emit_audit(correlation_id, body, \"replay\", \"cached_result_returned\")\n",
        "        return {\"ok\": True, **process_once_e2e(idempotency_key, IDEMPOTENCY_STORE_E2E[idempotency_key])}\n",
        "\n",
        "    result = await safe_tool_execution(req.model_dump())\n",
        "    emit_audit(correlation_id, body, \"approved\", \"downstream_called\")\n",
        "    return {\"ok\": True, **process_once_e2e(idempotency_key, result)}\n",
        "\n",
        "\n",
        "def run_case(name: str, body: dict, headers: dict) -> dict:\n",
        "    try:\n",
        "        result = asyncio.run(governed_tool_endpoint(body, headers))\n",
        "        return {\"Case\": name, \"Outcome\": \"Success\", \"Result\": json.dumps(result)}\n",
        "    except HTTPException as exc:\n",
        "        return {\"Case\": name, \"Outcome\": \"HTTPException\", \"Status\": exc.status_code, \"Detail\": exc.detail}\n",
        "    except TimeoutError as exc:\n",
        "        return {\"Case\": name, \"Outcome\": \"Timeout\", \"Detail\": type(exc).__name__}\n",
        "    except Exception as exc:\n",
        "        return {\"Case\": name, \"Outcome\": \"Error\", \"Detail\": repr(exc)}\n",
        "\n",
        "valid_comment_token = make_token({\n",
        "    \"sub\": \"approver-ops\",\n",
        "    \"exp\": int((datetime.now(timezone.utc) + timedelta(minutes=5)).timestamp()),\n",
        "    \"scopes\": [\"ticket.read\", \"ticket.comment\"],\n",
        "})\n",
        "expired_read_token = make_token({\n",
        "    \"sub\": \"approver-ops\",\n",
        "    \"exp\": int((datetime.now(timezone.utc) - timedelta(minutes=5)).timestamp()),\n",
        "    \"scopes\": [\"ticket.read\"],\n",
        "})\n",
        "read_only_token = make_token({\n",
        "    \"sub\": \"approver-ops\",\n",
        "    \"exp\": int((datetime.now(timezone.utc) + timedelta(minutes=5)).timestamp()),\n",
        "    \"scopes\": [\"ticket.read\"],\n",
        "})\n",
        "\n",
        "cases = [\n",
        "    (\n",
        "        \"AllowedRead\",\n",
        "        {\"action\": \"ticket.read\", \"ticket_id\": \"T-100\"},\n",
        "        {\"x-correlation-id\": \"c1\", \"x-approval-token\": valid_comment_token, \"Idempotency-Key\": \"k1\"},\n",
        "    ),\n",
        "    (\n",
        "        \"ExpiredApproval\",\n",
        "        {\"action\": \"ticket.read\", \"ticket_id\": \"T-101\"},\n",
        "        {\"x-correlation-id\": \"c2\", \"x-approval-token\": expired_read_token, \"Idempotency-Key\": \"k2\"},\n",
        "    ),\n",
        "    (\n",
        "        \"InvalidScope\",\n",
        "        {\"action\": \"ticket.comment\", \"ticket_id\": \"T-102\", \"comment\": \"hi\"},\n",
        "        {\"x-correlation-id\": \"c3\", \"x-approval-token\": read_only_token, \"Idempotency-Key\": \"k3\"},\n",
        "    ),\n",
        "    (\n",
        "        \"ReplayFirst\",\n",
        "        {\"action\": \"ticket.read\", \"ticket_id\": \"T-103\"},\n",
        "        {\"x-correlation-id\": \"c4\", \"x-approval-token\": valid_comment_token, \"Idempotency-Key\": \"same-key\"},\n",
        "    ),\n",
        "    (\n",
        "        \"ReplaySecond\",\n",
        "        {\"action\": \"ticket.read\", \"ticket_id\": \"T-103\"},\n",
        "        {\"x-correlation-id\": \"c4\", \"x-approval-token\": valid_comment_token, \"Idempotency-Key\": \"same-key\"},\n",
        "    ),\n",
        "    (\n",
        "        \"Timeout\",\n",
        "        {\"action\": \"ticket.read\", \"ticket_id\": \"slow\"},\n",
        "        {\"x-correlation-id\": \"c5\", \"x-approval-token\": valid_comment_token, \"Idempotency-Key\": \"k5\"},\n",
        "    ),\n",
        "    (\n",
        "        \"MalformedInput\",\n",
        "        {\"action\": \"ticket.comment\", \"ticket_id\": \"T-106\", \"comment\": \"x\" * 600},\n",
        "        {\"x-correlation-id\": \"c6\", \"x-approval-token\": valid_comment_token, \"Idempotency-Key\": \"k6\"},\n",
        "    ),\n",
        "]\n",
        "\n",
        "results = [run_case(name, body, headers) for name, body, headers in cases]\n",
        "pd.DataFrame(results)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Mermaid reference: governed tool flow\n",
        "\n",
        "The original post included Mermaid diagrams. Since Mermaid is not executable Python in a notebook code cell, this cell preserves the flow as a Python multiline string so you can inspect or export it during validation."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "flowchart_mermaid = r'''flowchart TD\n",
        "    A[Azure AI Agent] --> B[Tool Gateway API]\n",
        "    B --> C{Validate action<br/>against allowlist}\n",
        "    C -- no --> X[Reject + audit]\n",
        "    C -- yes --> D{Approval token<br/>valid and unexpired?}\n",
        "    D -- no --> X\n",
        "    D -- yes --> E{Idempotency key<br/>already seen?}\n",
        "    E -- yes --> F[Return cached result]\n",
        "    E -- no --> G[Call downstream service<br/>with least privilege]\n",
        "    G --> H[Emit correlated audit event]\n",
        "    H --> I[Return sanitized response]\n",
        "'''\n",
        "\n",
        "sequence_mermaid = r'''sequenceDiagram\n",
        "    participant Agent as Azure AI Agent\n",
        "    participant API as Tool Gateway\n",
        "    participant Approver as Approval Service\n",
        "    participant Audit as Audit Sink\n",
        "    participant Downstream as Ticket API\n",
        "\n",
        "    Agent->>API: POST /tool + action + idempotency key\n",
        "    API->>Approver: Validate approval token + scope + expiry\n",
        "    Approver-->>API: Approved / Denied\n",
        "    API->>Audit: Emit correlated decision event\n",
        "    alt replay detected\n",
        "        API-->>Agent: Cached prior result\n",
        "    else approved and new\n",
        "        API->>Downstream: Least-privilege action\n",
        "        Downstream-->>API: Sanitized result\n",
        "        API-->>Agent: Response\n",
        "    end\n",
        "'''\n",
        "\n",
        "print(flowchart_mermaid)\n",
        "print(\"\\n---\\n\")\n",
        "print(sequence_mermaid)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Infrastructure references as deployable text artifacts\n",
        "\n",
        "The blog also included Bicep examples for app settings, Key Vault references, and APIM as a governed front door. Because the notebook's primary language is Python, this cell stores those templates as strings for review, linting, or export rather than attempting to execute Bicep directly."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "bicep_keyvault_settings = r'''// Key Vault secret reference for downstream credentials and app settings for strict tool execution\n",
        "param location string = resourceGroup().location\n",
        "param appName string = 'func-agent-tools'\n",
        "param keyVaultName string = 'kv-agent-tools'\n",
        "\n",
        "resource app 'Microsoft.Web/sites@2023-12-01' existing = {\n",
        "  name: appName\n",
        "}\n",
        "\n",
        "resource kv 'Microsoft.KeyVault/vaults@2023-07-01' existing = {\n",
        "  name: keyVaultName\n",
        "}\n",
        "\n",
        "resource appSettings 'Microsoft.Web/sites/config@2023-12-01' = {\n",
        "  name: '${app.name}/appsettings'\n",
        "  properties: {\n",
        "    'TOOL_ALLOWED_ACTIONS': 'ticket.read,ticket.comment'\n",
        "    'DOWNSTREAM_API_BASE': 'https://tickets.contoso.com'\n",
        "    'DOWNSTREAM_API_KEY': '@Microsoft.KeyVault(SecretUri=${kv.properties.vaultUri}secrets/downstream-api-key/)'\n",
        "    'AUDIT_MODE': 'required'\n",
        "  }\n",
        "}\n",
        "'''\n",
        "\n",
        "bicep_apim_frontdoor = r'''// APIM policy-backed front door with rate limiting and managed identity to the tool app\n",
        "param location string = resourceGroup().location\n",
        "param apimName string = 'apim-agent-tools'\n",
        "param appName string = 'func-agent-tools'\n",
        "\n",
        "resource apim 'Microsoft.ApiManagement/service@2023-05-01-preview' = {\n",
        "  name: apimName\n",
        "  location: location\n",
        "  sku: { name: 'Consumption'; capacity: 0 }\n",
        "  properties: {\n",
        "    publisherEmail: 'ops@contoso.com'\n",
        "    publisherName: 'Contoso'\n",
        "  }\n",
        "}\n",
        "\n",
        "resource app 'Microsoft.Web/sites@2023-12-01' existing = {\n",
        "  name: appName\n",
        "}\n",
        "'''\n",
        "\n",
        "print(bicep_keyvault_settings)\n",
        "print(\"\\n---\\n\")\n",
        "print(bicep_apim_frontdoor)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Governance maturity self-assessment\n",
        "\n",
        "The post ends with an operating model: autonomy is earned per tool. Use this quick checklist to rate your current state from 1 to 5 and identify whether any broad APIs are still exposed to agents."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "maturity_ladder = pd.DataFrame(\n",
        "    [\n",
        "        {\"Level\": 1, \"Stage\": \"Observe-only\"},\n",
        "        {\"Level\": 2, \"Stage\": \"Read-only assistance\"},\n",
        "        {\"Level\": 3, \"Stage\": \"Human-approved writes\"},\n",
        "        {\"Level\": 4, \"Stage\": \"Narrowly autonomous low-risk actions\"},\n",
        "        {\"Level\": 5, \"Stage\": \"Continuously reviewed production automation\"},\n",
        "    ]\n",
        ")\n",
        "\n",
        "review_criteria = pd.DataFrame(\n",
        "    [\n",
        "        {\"Criterion\": \"Scope is explicit\", \"Met\": True},\n",
        "        {\"Criterion\": \"Identity is constrained\", \"Met\": True},\n",
        "        {\"Criterion\": \"Approval path is enforceable\", \"Met\": True},\n",
        "        {\"Criterion\": \"Audit trail is reconstructable\", \"Met\": True},\n",
        "        {\"Criterion\": \"Broad APIs still exposed anywhere\", \"Met\": False},\n",
        "    ]\n",
        ")\n",
        "\n",
        "print(\"Maturity ladder:\")\n",
        "display(maturity_ladder)\n",
        "print(\"\\nReview criteria:\")\n",
        "display(review_criteria)\n",
        "\n",
        "score = int(review_criteria[review_criteria[\"Met\"]].shape[0] / review_criteria.shape[0] * 5)\n",
        "print(f\"Suggested governance score: {score}/5\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Next Steps\n",
        "\n",
        "This notebook validated the main production controls at the tool boundary: narrow contracts, typed inputs, approval verification, idempotency, audit correlation, and safe downstream execution. The key rule is that every tool call should be treated like a privileged production operation.\n",
        "\n",
        "Next steps:\n",
        "1. Replace any broad API exposure with business-verb tools.\n",
        "2. Put authorization and approval checks inside the tool service and gateway.\n",
        "3. Separate identities and environments strictly.\n",
        "4. Send correlated audit and security signals to your SIEM.\n",
        "5. Build a pre-production negative test suite for prompt injection, scope drift, replay, timeout, and approval bypass attempts."
      ]
    }
  ]
}