Evaluating the security of a Model Context Protocol (MCP)

Evaluating the security of a Model Context Protocol (MCP) server or client requires analyzing the boundary where non-deterministic AI outputs meet deterministic tools and systems. Traditional API security models (like strictly defined REST schemas) often fail because MCP tools are invoked based on natural language model context, making them vulnerable to prompt injection, confused deputy attacks, and supply chain threats.

Below is a structured evaluation matrix to assess an MCP integration across the five critical security pillars.

The MCP Security Evaluation Matrix

       [ Client / Host Application ]
                     │  (Natural Language & Tool Schema)
                     ▼
       ┌──────────────────────────┐
       │   MCP Security Boundary  │
       └─────────────┬────────────┘
                     │
    ┌────────────────┼────────────────┬────────────────┐
    ▼                ▼                ▼                ▼
1. Transport &   2. Tool Definition   3. Context &    4. Secrets &
   Auth Scope       & Shadowing       Data Isolation     Local OS
1. Transport, Authentication, and Scope
  • Authentication Method:Verify whether the MCP server communicates locally (STDIO) or remotely (HTTP/SSE).Remote servers should implement standard OAuth 2.0 or mutual TLS.
  • Confused Deputy Prevention:Ensure the MCP server executes actions scoped specifically to the end-user’s identity rather than inheriting the full service account permissions of the host host environment.
  • Audience Binding:Confirm tokens passed over MCP cannot be reused or forwarded across unauthorized target domains.
2. Tool Exposure and Definition Integrity
  • Tool Shadowing & Collisions:Check if a server exposes tool names identical to core or system tools (e.g., exposing a custom execute_command or read_file tool to override or shadow a native client capability).
  • Tool Poisoning in Descriptions: Inspect the description fields of MCP tool definitions. Attackers can embed indirect prompt injections directly into the JSON metadata of a tool to manipulate model behavior before the tool is even called.
  • Parameter Validation: Validate whether parameter schemas enforce strict data types, length limits, and format regexes rather than relying on open-ended string inputs.
3. Indirect Prompt Injection & Context Isolation
  • Data vs. Instruction Separation: Assess how output returned from an MCP tool (e.g., a retrieved web page or database record) is parsed by the client host. If raw data contains system-prompt-style instructions, determine if the host application accidentally treats it as executable system context.
  • Data Exfiltration Vectors: Verify if tools with external network capabilities (e.g., fetch_url) can be combined with local file-reading tools to leak sensitive local data.
4. Secret Management and Execution Sandboxing
  • Configuration Storage:Check how API keys and tokens are supplied to the MCP server. Storing keys in plain-text mcp_config.json files on local disk creates severe exposure risks. Prefer passing credentials via environment variables or secret vaults.
  • Command & Code Execution:Any MCP tool invoking shell scripts, system binaries, or arbitrary SQL must strictly sanitize parameters to prevent command injection.
  • Sandboxing: Local STDIO-based MCP servers should execute within a containerized or sandboxed process (e.g., Docker, AppArmor, or macOS sandbox) with restricted filesystem and network access.
5. Supply Chain & Package Integrity
  • Package Source Verification: Verify the origin of the server repository or npm/uv package. Look for signed releases and pinned package dependencies to prevent “rug pulls” where a trusted server version is modified post-release.
  • Post-Install Scripts: Audit package.json or build hooks for malicious post-install scripts that run during initial setup.

Evaluation Checklist

To run an evaluation on a target MCP server, verify each baseline control below:

Security DomainControl CheckStatus
SandboxServer runs in an isolated, unprivileged process space.[ ]
CredentialsAPI keys are injected at runtime, not written to configuration files.[ ]
PermissionsHigh-impact actions require explicit Human-in-the-Loop (HITL) approval.[ ]
Tool NamesTool identifiers use unique namespaces to avoid naming collisions.[ ]
Input SanitizationFunction arguments are strictly sanitized before reaching system calls.[ ]
LoggingSensitive parameters and authorization tokens are redacted from MCP traces.[ ]

Securing Azure AI Foundry (now branded Microsoft Foundry)

Securing Azure AI Foundry (now branded Microsoft Foundry, so you may see both names in docs)

The core controls fall into a few layers:

  • Identity and access: Use Entra ID with managed identities instead of API keys, and apply least-privilege RBAC at the hub, project, and resource level. Disable key-based auth where you can.
  • Network isolation: Private endpoints, managed virtual networks for hubs and projects, and public network access disabled for production. Watch the outbound rules for agents and tools, since that’s where data exfiltration paths hide.
  • Data protection: Customer-managed keys, careful scoping of storage and Key Vault connections, and clear rules on what grounding data (e.g., Azure AI Search indexes) models and agents can reach.
  • Content safety and model-layer defenses: Azure AI Content Safety filters, Prompt Shields against direct and indirect prompt injection, groundedness detection, and per-deployment content filter policies.
  • Governance and monitoring: Azure Policy for guardrails, Defender for Cloud’s AI workload protection, diagnostic logging to Log Analytics/Sentinel, and tracing of agent and tool calls.

Broader AI security initiatives

  • Threat modeling against frameworks like the OWASP Top 10 for LLM applications, MITRE ATLAS, and NIST AI RMF.
  • AI red teaming (Microsoft’s PyRIT is a common tool) covering jailbreaks, prompt injection, data leakage, and model abuse.
  • Securing the AI supply chain: model provenance, third-party models and plugins, and MCP/tool servers.
  • Controlling agentic risk: excessive agency, tool permissions, and human-in-the-loop approval for high-impact actions.
  • Shadow AI discovery and data loss prevention for employee use of AI services.

Securing emerging cloud AI services generally

The common pattern is that each new service ships with permissive defaults and fast-moving features, so the work is establishing a baseline early: inventory the services, enforce network and identity standards through policy, log everything, and review new capabilities (agents, MCP connectors, fine-tuning) before enabling them broadly.

Here’s a prep guide for an AI security / cloud AI security role (security engineer, architect, or similar). I’ve grouped the questions by how interviewers usually probe, with the points a strong answer should hit.

1. Foundational and architecture questions

“How would you secure an Azure AI Foundry deployment for a regulated workload?”


Structure the answer in layers: identity (managed identities, Entra RBAC, keys disabled), network (private endpoints, managed VNet, public access off, outbound rules controlled), data (CMK, scoped storage and AI Search access, data residency), model layer (content filters, Prompt Shields), and governance (Azure Policy, Defender for Cloud, diagnostics to Sentinel). Mention that you’d start with a threat model and the data classification, not with the controls.

“Why prefer managed identity over API keys?”


Keys are long-lived, hard to attribute, easy to leak, and can’t be scoped per caller. Managed identity gives short-lived tokens, per-identity RBAC, and audit trails in Entra logs.

“Where are the exfiltration paths in an agent-based system?”


Outbound network access from tools, overly broad connections to data stores, tool calls that can send data to external URLs, and markdown/image rendering that leaks data through URLs. The answer should end with egress restriction plus least-privilege tools.

2. AI-specific threat questions

“Explain direct vs. indirect prompt injection, and how you’d mitigate each.”


Direct: the user attacks the model. Indirect: malicious instructions hidden in retrieved documents, emails, or web pages. No single fix exists. Cover layered defenses: Prompt Shields, separating trusted instructions from untrusted data, least-privilege tool permissions, output filtering, and human approval for high-impact actions.

“What is excessive agency and how do you limit it?”


An agent with more permissions or autonomy than the task needs. Limit it with scoped credentials per tool, allowlisted actions, approval gates, rate limits, and logging of every tool call.

“How would you threat model an LLM application?”


Draw the data flow (user, orchestrator, model, retrieval, tools), mark trust boundaries, then walk through OWASP Top 10 for LLM Apps and MITRE ATLAS. Note the non-determinism: you can’t prove safety, so you rely on defense in depth, testing, and monitoring.

“How do you secure a RAG pipeline?”


Document-level access control enforced at retrieval (not just at the app), poisoning risks in the ingestion path, sensitive data in the index, and citation/groundedness checks.

3. Operational and program questions

“How do you red team an AI system?”
Define scope and harm categories, use automated tooling (PyRIT, Garak) for breadth, then manual testing for creative attacks. Cover jailbreaks, injection, data leakage, and abuse of tools. Emphasize measuring and retesting after each model or prompt change.

“How would you detect shadow AI in an organization?”
Network/proxy and CASB telemetry, Defender for Cloud Apps discovery, DLP policies, plus an approved alternative so people have a sanctioned path. Policy alone without an alternative fails.

“A new model or feature (say, an MCP connector) is released. What’s your review process?”
Inventory what it touches, review its permissions and data flows, test in a sandbox subscription, add policy guardrails, define logging, then roll out in stages.

4. Scenario question to practice out loud

“A developer wants to connect an internal agent to production customer data and the public internet. Walk me through your response.”
A good answer asks about the use case first, proposes separating the retrieval and browsing capabilities (the “lethal trifecta” idea: private data, untrusted content, and external communication together is the dangerous combination), and offers a safer design rather than just saying no.

Tips

  • Lead with trade-offs and risk reasoning, not a list of product names.
  • Be honest about what’s unsolved (prompt injection has no complete fix). Interviewers trust that more than overconfidence.
  • Verify current product names and features before the interview, since Azure AI branding and capabilities change quickly.

Agents and Skills

The fundamental distinction between Agents and Skills comes down to who drives the task (runtime) versus what knowledge or tooling is applied (capability).

Core Comparison

DimensionAI Agent (The “Actor”)AI Skill (The “Asset”)
Primary RoleThe autonomous decision-maker / runtime engine.Modular package of capability, domain knowledge, or tooling.
Question It Answers“Who is doing the task, and how do they reason?”“What step-by-step instructions or tools are needed?”
Control FlowDynamic loop: evaluates state, plans next steps, decides when to stop.Passive/Declarative: loaded on demand to perform a specific function.
ScopeGoal-oriented across multiple steps or tools.Task-bound (e.g., parse PDF, format JSON, query SQL).
ReusabilityLow to medium; typically bound to a specific workflow/persona.High; can be attached to any generalist agent on demand.

Key Concepts

1. Agent (Runtime & Reasoning)

An Agent is the orchestrator. It manages memory, maintains state across turns, plans sub-tasks, and evaluates its own progress.

  • Example: A “DevOps Engineer Agent” that monitors server health, investigates alerts, and decides whether to restart a service or escalate to a human.

2. Skill (Knowledge & Execution)

A Skill is a self-contained module containing domain guidelines, scripts, API calls, or instructions loaded dynamically when needed.Skills prevent you from overloading an Agent’s system prompt with information irrelevant to the current step.

  • Example:A docker-log-parser skill or a jira-ticket-creator skill.

How They Work Together

Rather than building a complex fleet of specialized agents (which can lead to “agent sprawl”), modern AI architectures favor using a generalist agent powered by a library of skills:

┌─────────────────────────────────────────────────────────┐
│ AI AGENT │
│ (Maintains goal, plans steps, reasons over outputs) │
└──────────────────────────┬──────────────────────────────┘
│
Reads context & loads on demand
│
┌───────────────────┼───────────────────┐
▼ ▼ ▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ PDF Parser │ │ SQL Query │ │ Chart Visual │
│ Skill │ │ Skill │ │ Skill │
└──────────────┘ └──────────────┘ └──────────────┘
  1. User Request: “Analyze this quarterly PDF report and update the SQL database.”
  2. Agent Action: Recognizes the plan requires two distinct tasks.
  3. Skill Loading: Dynamically pulls the pdf-parsing skill into its active context to extract text. Once complete, drops that context and loads the sql-database skill to run queries.

The Agent Skills standard (pioneered by Anthropic and adopted across tools like GitHub Copilot, Cursor, and Claude Code) relies on a standardized, file-based architecture centered around a SKILL.md manifest.

This format leverages progressive disclosure: the host system only loads the metadata (~100 tokens) at boot, and only reads the full SKILL.md instructions when a user request triggers the description.

1. Directory Blueprint

A production-grade skill is self-contained inside a directory named after the skill.

Plaintext

my-agent-skill/
├── SKILL.md # REQUIRED: Metadata + Primary System Prompt
├── scripts/ # Executable helpers run by the agent (e.g. Python/Bash)
│ └── helper.py
├── references/ # Supplemental context (loaded by agent on demand)
│ └── api_docs.md
└── assets/ # Fixed files (e.g., templates, schemas)
└── report_template.json

2. Anatomy of SKILL.md

SKILL.md is composed of two main parts: YAML Frontmatter (determines when the agent activates the skill) and the Markdown Body (tells the agent how to execute the task).

Markdown

---
name: sql-database-analyst
description: Generates, validates, and runs analytical SQL queries against PostgreSQL databases. Use when the user asks to query metrics, build reports, or inspect database schemas.
when_to_use:
- User asks for SQL query generation or database investigation
- User asks for key performance metrics (ARR, Churn, Active Users)
- Do NOT use for: Data migration scripts or schema mutation (DDL) tasks
allowed-tools:
- bash
- read_file
- execute_sql
arguments:
- name: database_url
description: Target PostgreSQL connection string
required: false
---
# SQL Database Analyst Skill
## System Role & Instructions
You are an expert PostgreSQL DBA and Data Analyst. When assigned a querying task, follow this exact protocol:
1. **Schema Check:** Inspect the database tables using `references/schema_map.md` or by running `\dt` using the `execute_sql` tool.
2. **Query Draft:** Write standard ANSI-compliant PostgreSQL queries. Avoid non-standard extensions.
3. **Safety Check:** Ensure all queries are read-only (`SELECT`). Do not issue `UPDATE`, `INSERT`, `DELETE`, or `DROP`.
---
## Tool Execution Guide
If you need to calculate statistical distributions, execute the python calculation script rather than calculating manually:
```bash
python scripts/helper.py --input-data ./data.json

Output Format Requirements

Always format your response to the user with the following template:

Markdown

### Key Insights
- [Bullet points summarizing findings]
### SQL Query Used
```sql
[Generated Query]

---

## Common Edge Cases & Rules
- **Null Values:** Always use `COALESCE(column, 0)` for financial sums.
- **Timezones:** Convert all timestamp columns to `UTC` before aggregation.


3. Frontmatter Field Breakdown

FieldRequired?Purpose & Best Practices
nameYesLowercase identifier matching directory name. (Max 64 chars, no spaces/underscores).
descriptionYesThe most important field. Describes what the skill does and includes trigger phrases. The agent reads this to decide if the skill should fire.
when_to_useOptionalGranular activation criteria, explicit trigger phrases, and negative constraints (“Do NOT use for…”).
allowed-toolsOptionalRestricts which agent tools (e.g., bash, read_file) this skill is authorized to invoke.
argumentsOptionalDefines structured variables required or accepted by the skill.

4. How the Agent Loads and Runs the Skill

┌────────────────────────────────────────────────────────┐
│ Agent App Startup │
│ Agent scans directory and reads frontmatter (~100 tokens)│
└──────────────────────────┬─────────────────────────────┘
│
User prompt matches 'description'
│
▼
┌────────────────────────────────────────────────────────┐
│ Skill Activation │
│ Agent dynamically loads entire SKILL.md into context │
└──────────────────────────┬─────────────────────────────┘
│
Needs deeper context?
│
▼
┌────────────────────────────────────────────────────────┐
│ Selective Execution │
│ Agent reads references/ or executes scripts/ as needed │
└────────────────────────────────────────────────────────┘
  1. Zero Context Overhead at Boot: System prompts stay slim because only the frontmatter description is loaded into memory.
  2. Context Window Protection: Detailed documentation or large JSON schemas are placed in /references or /assets so the agent only pulls them if a specific sub-task demands it.
  3. Execution, Not Context Inflation: If complex logic (like data parsing or API transformation) is required, place it inside a script in /scripts. The agent executes the script using terminal tools and only receives the output, preserving token limits.

Here is a complete, production-grade SKILL.md file designed specifically for an AI Agent performing Log Parsing, Normalization, and AI-Powered Anomaly Detection.

You can save this structure inside a project directory as .claude/skills/log-parser/SKILL.md or .agents/skills/log-parser/SKILL.md.

File Path: log-parser/SKILL.md

Markdown

---
name: log-parser
description: Auto-detects, parses, normalizes, and analyzes log files (JSON, Syslog, Apache/Nginx, Log4j, Stacktraces). Use when a user asks to parse raw logs, extract metrics, detect anomalies, or clean log streams before indexing.
when_to_use:
- User provides raw unformatted log lines or stack traces
- User asks to convert unstructured text logs into structured JSON/ECS format
- User asks to extract top errors, IP addresses, or failure patterns from log dumps
- Do NOT use for: Database performance queries (use `sql-database-analyst` skill)
allowed-tools:
- bash
- read_file
- write_file
arguments:
- name: log_format
description: Known format (e.g., json, syslog, nginx, log4j, auto). Defaults to auto-detect.
required: false
---
# Log Parsing & Anomaly Analysis Skill
## Role & Mission
You are a Principal Observability & Site Reliability Engineer (SRE). Your objective is to ingest raw log data, automatically identify the underlying log schema, extract key fields into Elastic Common Schema (ECS) standard key-value pairs, and report critical failure vectors.
---
## Step 1: Format Detection & Ingestion
Examine the first 10 lines of the provided log data to identify the schema format:
| Pattern Recognized | Target Format | Parser Strategy |
| :--- | :--- | :--- |
| `{"timestamp": ...}` | **Structured JSON** | Direct extraction |
| `<13>1 2026-10-08T...` | **RFC 5424 Syslog** | Regex pattern match |
| `127.0.0.1 - - [08/Oct/2026...]` | **Nginx / Apache Common** | Standard Web Log Regex |
| `2026-10-08 14:02:11,102 [main] ERROR` | **Log4j / Python Logging** | Multiline Grok extraction |
*Note: If multiline exception stack traces are detected (e.g., Python `Traceback` or Java `Exception in thread`), group all indented child lines into a single log record before parsing.*
---
## Step 2: Normalization Strategy (ECS Format)
Convert extracted raw attributes into standard **Elastic Common Schema (ECS)** field names:
* `@timestamp` $\rightarrow$ Standard ISO 8601 UTC timestamp string.
* `log.level` $\rightarrow$ Normalized string in lowercase (`debug`, `info`, `warn`, `error`, `critical`, `fatal`).
* `service.name` $\rightarrow$ Name of the service or application emitting the log.
* `host.ip` or `client.ip` $\rightarrow$ Extracted IPv4 / IPv6 addresses.
* `http.response.status_code` $\rightarrow$ Integer status codes (if web traffic).
* `message` $\rightarrow$ Clean textual message string stripped of timestamps and levels.
* `error.stack_trace` $\rightarrow$ Preserved full multiline exception payload (if present).
---
## Step 3: Execution Helpers
If processing large log dumps (over 500 lines), run the automated Python parser script located in this skill package rather than manually reading lines into context:
```bash
python scripts/parse_logs.py --input ./raw_logs.log --format auto --output ./parsed_logs.json

Step 4: Output Presentation Protocol

Always structure your analysis output to the user using the following layout:

Markdown

### Log Analysis Overview
- **Total Lines Parsed:** [Count]
- **Detected Format:** [JSON / Syslog / Grok / Unstructured]
- **Primary Severity Distribution:** `ERROR`: X | `WARN`: Y | `INFO`: Z
### Critical Anomalies & Root Cause
1. **[Error Pattern 1 Name]** (Occurred X times)
- **First Seen:** [Timestamp]
- **Sample Log:** `[Raw snippet]`
- **AI Analysis:** [1-sentence explanation of what failed and how to remediate]
### Normalized Sample (ECS JSON Format)
```json
[
{
"@timestamp": "2026-10-08T14:02:11Z",
"log.level": "error",
"service.name": "user-auth-service",
"message": "Connection back-off failure, system.db.Pool empty.",
"error": {
"code": "DB_POOL_EMPTY"
}
}
]

---

## Safety Constraints & Rules
* **Data Anonymization:** Automatically redact sensitive tokens, authorization headers (`Bearer eyJ...`), passwords, and PII (Social Security numbers, Credit Card numbers) replaced with `[REDACTED]`.
* **Timestamp Handling:** If no year is specified in the log, assume the current system year (`2026`). Always convert relative timestamps into standard UTC.


Complementary Directory Structure

To deploy this skill completely, place it in the agent directory alongside its helper scripts:

Plaintext

log-parser/
├── SKILL.md
├── scripts/
│ └── parse_logs.py # Python script that executes fast regex/grok batch processing
└── references/
└── ecs_cheatsheet.md # Standard Elastic Common Schema field reference guide

Securing emerging cloud AI services

Securing emerging cloud AI services requires extending classical cloud security principles (like Zero Trust and defense-in-depth) to cover AI-specific threat vectors—such as prompt injection, agentic over-privilege, and data leakage into model contexts.

Below are the architectural patterns for securing Azure AI Foundry, building an AI Security Initiative, and protecting enterprise Generative AI & Agentic workloads.

1. Architecture Pattern: Azure AI Foundry Network Isolation

By default, AI services expose public endpoints. For enterprise production, you must isolate the Foundry Hub, Foundry Projects, and all Dependent Services (Azure AI Search, Storage Accounts, Key Vault, and Azure Container Registry) inside a private boundary.

   
Key Security Controls for Azure AI Foundry
  1. Managed Network Isolation: Enable Managed VNet on the Foundry Hub. This creates private endpoints for compute instances, serverless endpoints, and outbound connections. Set the public access toggle to Disabled.
  2. Keyless Authentication (Entra ID): Disable local API keys. Force applications, developers, and agents to authenticate using User-Assigned Managed Identities or Entra ID tokens with built-in roles (e.g., Azure AI Developer, Cognitive Services OpenAI User).
  3. Storage & RAG Protection:Secure the underlying Azure AI Search instance and Azure Blob Storage containing vector embeddings using Private Endpoints.Enable Customer-Managed Keys (CMK) via Key Vault for data at rest.

2. Comprehensive AI Security Initiative Matrix

When building an enterprise AI Security Initiative (governed by Azure Policy and Defender for Cloud), security teams must address five distinct layers:

LayerPrimary Threat VectorSecurity Control / Azure Native Tool
1. Shadow AI DiscoveryUnsanctioned AI tools & unmonitored model deployments.Defender for Cloud (CSPM for AI): Auto-discovers Generative AI Bill of Materials (AI BOM), shadow API calls, and attack paths.
2. Access & IdentityLeaked API keys, agent credential theft, privilege escalation.Entra ID Agent ID & Managed Identity: Enforce short-lived token access; eliminate hardcoded keys.
3. Input / Output GuardrailsDirect/Indirect Prompt Injections, Jailbreaks, PII leakage.Azure AI Content Safety: Deploy input-side prompt shields and output-side filters for hate, violence, and self-harm.
4. Data Protection & RAGPoisoned vector data, sensitive data exfiltration to model outputs.Microsoft Purview DSPM for AI: Sensitivity labels on prompts/RAG data, blocking DLP policy violations.
5. Threat DetectionAnomalous API spikes, automated adversarial attacks.Defender for AI: Real-time threat detection for runtime model abuse; continuous testing with PyRIT.

3. Bicep Pattern: Secure Azure AI Foundry Baseline

This Bicep module provisions a secure-by-default Azure AI Foundry Resource with Public Access Disabled, Keyless Authentication Enforced, and a System-Assigned Managed Identity enabled.

Code snippet

targetScope = 'resourceGroup'
@description('Location for all resources')
param location string = resourceGroup().location
@description('Name of the Azure AI Foundry Resource')
param foundryName string = 'foundry-prod-sec-01'
resource aiFoundry 'Microsoft.CognitiveServices/accounts@2024-10-01' = {
name: foundryName
location: location
kind: 'AIServices'
sku: {
name: 'S0'
}
identity: {
type: 'SystemAssigned' // Enforces identity-based access to dependent services
}
properties: {
// 1. Disable local API keys (Forces Entra ID / Managed Identity auth)
disableLocalAuth: true
// 2. Lock down network access (Requires Private Endpoints)
publicNetworkAccess: 'Disabled'
// 3. Enable Custom Subdomain (Mandatory for Entra ID token auth)
customSubDomainName: toLower(foundryName)
networkAcls: {
defaultAction: 'Deny'
ipRules: []
virtualNetworkRules: []
}
// 4. Force TLS 1.2+
minTlsVersion: 'TLS1_2'
}
}
output foundryId string = aiFoundry.id
output foundryPrincipalId string = aiFoundry.identity.principalId

4. Governance & Continuous Testing

  1. Deploy Policy Guardrails: Enforce Azure Policy across your subscriptions to deny creation of public AI services (Microsoft.CognitiveServices/accounts where publicNetworkAccess != 'Disabled').
  2. Implement Agentic Least-Privilege: If using autonomous agents via the Foundry Agent Service, scope tool permissions so agents cannot perform destructive database writes or unrestricted external HTTP calls without explicit Human-in-the-Loop (HITL) approval steps.
  3. Automate Adversarial Red Teaming:Integrate PyRIT (Python Risk Identification Tool for GenAI) into CI/CD pipelines to run automated prompt-injection test suits against staging Foundry endpoints before promoting new agent capabilities to production.

Azure Security Patterns

Building and maintaining Azure Security Patterns requires establishing structured, repeatable architectural designs that enforce zero-trust security and continuous governance across your environment.

Security patterns are codified blueprints that solve specific architecture problems (e.g., identity, perimeter defense, data egress control) and are enforced automatically across the application lifecycle.

Core Architectural Patterns


1. Gatekeeper & Gateway Offloading (Network Edge)
  • Goal: Protect private backend workloads from direct public network exposure.
  • Pattern Implementation: Place an Azure Front Door or Application Gateway with WAF in front of your workloads. The Gateway acts as the “Gatekeeper,” terminating SSL/TLS, filtering malicious OWASP payloads, and inspecting incoming requests before passing clean traffic to internal VNets.
2. Bulkhead Pattern (Micro-Segmentation)
  • Goal:Contain security breaches to a specific isolated boundary (blast radius control).
  • Pattern Implementation: Separate application tiers (Web, API, DB) into dedicated subnets or distinct Spoke VNets. Use strict Network Security Groups (NSGs) and Application Security Groups (ASGs) to block lateral movement between tiers.
3. Valet Key & Claim Check Pattern (Zero-Trust Data Access)
  1. Goal:Grant temporary, restricted access to data stores without sharing permanent connection keys.
  2. Pattern Implementation: Instead of storing storage connection strings in app configurations, applications request short-lived Shared Access Signatures (SAS) using User-Assigned Managed Identities and Azure Key Vault. Access expires automatically.
4. Private Endpoint Injection Pattern (PaaS Isolation)
  • Goal: Eliminate public IP access on PaaS services (SQL, Storage, Key Vaults).
  • Pattern Implementation: Disable public network access on all PaaS resources and project them into internal VNet subnets using Azure Private Link. Combine this with Azure Private DNS Zones to route internal traffic securely.

The Lifecycle: How to Maintain Patterns

Designing patterns is only half the battle; maintaining them requires continuous validation and enforcement across your Azure Landing Zones.

┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ 1. Define Code │ ───► │ 2. CI/CD Gate │ ───► │ 3. Policy Guard│ ───► │4. Auto-Remediate│
│ (Bicep/Terra) │ │ (Checkov/psrule)│ │ (Azure Policy) │ │ (Defender/Logic)│
└─────────────────┘ └─────────────────┘ └─────────────────┘ └─────────────────┘
Phase 1: Codify Patterns in IaC (Infrastructure as Code)

Never deploy security patterns manually. Express patterns as standardized Bicep or Terraform modules.

  • Pattern Repository: Store pattern templates centrally (e.g., modules/networking/secure-vnet, modules/security/keyvault-private).
  • Defaults: Set security features to “On” by default inside modules (e.g., enableSoftDelete = true, publicNetworkAccess = 'Disabled').
Phase 2: Shift-Left Policy Testing (CI/CD Pipeline)

Scan pattern modules before they are deployed to Azure.

  • Run static code analysis tools like Checkov, Trivy, or PSRule for Azure inside GitHub Actions or Azure DevOps pipelines.
  • Block PRs if a developer attempts to bypass a baseline security pattern (e.g., trying to deploy a public Storage Account).
Phase 3: Enforce Policy at Runtime (Azure Policy)

Enforce pattern guardrails at the ARM engine level using Azure Policy Initiatives scoped at the Management Group level:

  • Deny Policy: Prevent non-compliant resources from deploying (e.g., Deny public IP creation on virtual machines).
  • DeployIfNotExists (DINE): Automatically append required security configurations during deployment (e.g., automatically attach Log Analytics diagnostic settings to new resources).
Phase 4: Continuous Drift Monitoring & Remediation
  • Posture Management: Monitor pattern compliance continuously using Microsoft Defender for Cloud (CSPM) and Microsoft Cloud Security Benchmark (MCSB) baselines.
  • Automated Remediation: Use Azure Logic Apps or Azure Policy Remediation Tasks to automatically fix drift (e.g., re-enabling disk encryption if a resource is modified outside of code).

Security Pattern Architecture Checklist

Control AreaSecurity PatternImplementation Native Services
IdentityJust-In-Time & PasswordlessEntra ID PIM, Managed Identities, FIDO2 / Passkeys
PerimeterCentralized Ingress/Egress InspectionAzure Firewall Premium + Hub-and-Spoke VNet
ApplicationWeb Application Firewall & Rate LimitingAzure Front Door WAF + API Management
Data ProtectionEnforced Encryption at Rest & TransitKey Vault (Customer-Managed Keys) + TLS 1.3 enforced
Audit & LogsCentralized SIEM/SOAR LoggingAzure Monitor Log Analytics + Microsoft Sentinel

Azure AI Foundry

Microsoft Foundry (formerly referred to as Azure AI Foundry or Azure AI Studio) is Microsoft’s unified enterprise platform and toolset for building, deploying, and governing custom AI applications and multi-agent workflows.

If Azure OpenAI provides the raw “engines” (the models), Foundry is the entire “factory floor”—providing developer tooling, data integration, agent orchestrators, safety guardrails, and central governance.

1. Key Pillars of Azure Foundry

PillarWhat It Provides
Model CatalogAccess to 1,800+ frontier models via unified APIs—including Azure OpenAI (GPT-4o, o3, Sora), Meta Llama, Mistral AI, Anthropic Claude, DeepSeek, xAI (Grok), and open-source models.
Agent ServiceNative framework for building autonomous AI Agents equipped with enterprise tools, memory, multi-agent orchestration, and Model Context Protocol (MCP) support.
Tooling & RAGAgentic Retrieval capabilities integrated with Azure AI Search to grounding models on private enterprise data securely.
Trust & SafetyBuilt-in content filtering, prompt injection detection, and data privacy boundaries.
ObservabilityUnified monitoring for token consumption, latency, evaluation metrics, and agent tracing hooked directly into Azure Monitor.

2. How Architectural Hierarchy Works

Foundry separates admin governance from developer workspace isolation using a two-tier model:

Top-Level Foundry Resource (IT Admin & Security Control)
├── Security, RBAC, Managed Identities, VNet setup
├── Unified Model Deployments & Quotas
│
├── 📂 Project A (e.g., HR Knowledge Base Agent)
│ ├── Custom Files, Connections, & Prompts
│ └── Evaluation Runs & Logs
│
└── 📂 Project B (e.g., Customer Support Multi-Agent System)
├── Isolated Vector Index
└── Dedicated Fine-Tuned Model Instances
  • Foundry Resource: The parent management boundary set up by cloud admins. It controls network security (VNets), role-based access control (RBAC), and shared billing/quotas.
  • Foundry Project: Isolated project containers for dev teams. Developers experiment, build agents, attach datasets, and run evaluations inside their designated project without affecting global settings.

3. Core Developer Workflow in Foundry

1. Select Model ──> 2. Attach Data (RAG) ──> 3. Build Agent/Logic ──> 4. Evaluate & Safety Test ──> 5. Deploy & Monitor
  1. Model Selection: Choose standard LLMs or fine-tune models (using LoRA/DPO) from the unified catalog.
  2. Data Grounding: Connect your data sources (Blob Storage, SQL, Cosmos DB) via Azure AI Search.
  3. Agent & Prompt Orchestration: Write code with the Foundry SDK or use low-code canvases to wire together system prompts, tools, and multi-agent coordination.
  4. Evaluation: Run automated test sets evaluating Groundedness, Relevance, and Coherence against synthetic or real benchmark datasets.
  5. Deployment: Expose endpoints for web apps, or publish agents directly into platforms like Microsoft Teams, Slack, or custom web APIs.

4. Edge & Local Runtime (Foundry Local)

For scenarios requiring on-device inference or low-latency processing without cloud round-trips, Foundry Local acts as a local runtime for Windows and macOS. Managed via Azure Arc, it lets you deploy models locally while keeping central governance and updates in the cloud.

Summary Checklist: When to use Foundry?

  • You want one portal and SDK to manage OpenAI models along with Claude, Llama, or DeepSeek.
  • You need multi-agent orchestration with strict enterprise RBAC and VNet isolation.
  • You need tracing and monitoring for agent steps and LLM token usage.

Kong AI Gateway — Unified Architecture

ARCHITECTURE SUMMARY

Kong AI Gateway — Unified Architecture

Single Ingress Point for All AI Model and MCP Traffic

Mission

Every AI interaction in the enterprise — app-to-model, agent-to-agent, agent-to-tool — flows through one gateway. No exceptions, no direct provider calls, no shadow credentials. This document ties together the four pillars of the architecture.

1. Single Ingress Point

All apps, agents, and MCP clients hit one endpoint family on Kong, never a provider directly. This is the architectural premise everything else depends on: if traffic can bypass the gateway, none of the governance below actually holds.

2. Credential Governance

  • Every provider key (Anthropic, Bedrock, OpenAI, internal APIs, MCP servers) lives in a vault, never in app code or Kong config.
  • Agents authenticate to Kong with their own Consumer credential — an identity Kong owns and can revoke independently of the underlying provider key.
  • Kong resolves the real credential at request time and injects it server-side. A leaked client-side key exposes nothing about the provider account behind it.
  • One Consumer model covers both LLM and MCP auth (OAuth2 for MCP), so access governance and credential governance are the same system.

3. MCP Registry & Gateway

  • The MCP Registry (Konnect Catalog, tech preview) catalogs approved MCP servers — owner, purpose, status — so agents discover tools in one place instead of hardcoding server URLs.
  • The AI MCP Proxy plugin fronts internal servers (passthrough), converts REST APIs into tools (conversion), or aggregates multiple servers into one endpoint (listener).
  • Tool-level ACLs gate both discovery and invocation, so a Consumer’s permissions extend down to individual tools, not just “can call MCP or not.”

4. Multi-Provider Failover

  • AI Proxy Advanced’s priority algorithm ranks providers into tiers (e.g. Anthropic → Bedrock → OpenAI). The top tier takes all traffic while healthy; the balancer only spills to the next tier on failure.
  • Active and passive health checks on the Upstream detect a degraded provider and flip targets automatically — no manual intervention during an outage.
  • Each tier still uses its own vault-backed credential, since Bedrock’s SigV4 auth, Anthropic’s API key, and OpenAI’s bearer token are structurally different.

5. Observability — The Thread Through All Three

  • Metrics, audit logs, and cost data are captured centrally, keyed to Consumer identity, not to whichever provider or MCP server actually served the request.
  • Failover events, tool invocations, and credential resolutions all land in the same logging/alerting pipeline, so “who called what, through which path, at what cost” is answerable from one place.

The Four Pillars at a Glance

Credential Governance Vault-backed keys, Consumer-level auth, server-side injection.MCP Registry & Gateway Catalog of approved servers, tool-level ACLs, proxy modes.Multi-Provider Failover Priority groups, health checks, automatic tier fallback.Observability Unified metrics, audit logs, cost tracking, failover alerts.

Why This Design Holds Together

Take any pillar away and the “single ingress point” claim weakens:

  • No credential governance → the gateway is a pass-through, not a security boundary.
  • No MCP registry/gateway → agents discover and call tools outside Kong’s visibility.
  • No failover → a single provider outage becomes a company-wide AI outage.
  • No shared observability → incidents can’t be traced back to an owner or a root cause.

Together, they turn “Kong is where AI traffic goes” into “Kong is where AI traffic is governed” — which is the actual job of the architect role.

on-prem Kong AI Gateway implementation

I would implement it from scratch in a controlled POC first, using Kong Gateway Enterprise 3.16 + PostgreSQL + Ollama, so the whole AI path can run on-prem without needing an external LLM API. Once that works, replace/augment Ollama with Azure OpenAI, OpenAI, vLLM, etc.

Kong’s current self-managed AI Gateway model uses standard Services + Routes + AI plugins; for multiple providers/models, the main plugin is ai-proxy-advanced. That plugin requires an AI license. Kong Docs

1. Target architecture

Start with this:

                 Client / Application
|
| HTTPS
v
+----------------+
| Kong |
| AI Gateway |
| |
| :8000 Proxy |
| :8001 Admin |
+-------+--------+
|
AI Proxy Advanced
|
v
+---------------+
| Ollama |
| :11434 |
+-------+-------+
|
v
Qwen/Llama

+---------------+
| PostgreSQL |
| :5432 |
+---------------+


For a lab, I’d use three Ubuntu 24.04 VMs:

kong01 4 vCPU 8 GB RAM
postgres01 2 vCPU 4 GB RAM
ollama01 8+ vCPU 16+ GB RAM

GPU on ollama01 is preferable but isn’t required for basic testing.


2. Install PostgreSQL

On postgres01:

sudo apt update
sudo apt install postgresql postgresql-contrib -y

Create Kong DB/user:

sudo -u postgres psql

Then:

CREATE USER kong WITH PASSWORD 'StrongKongPassword';
CREATE DATABASE kong OWNER kong;
GRANT ALL PRIVILEGES ON DATABASE kong TO kong;
\q

Configure PostgreSQL to accept your Kong server.

Edit:

sudo vi /etc/postgresql/*/main/postgresql.conf

Set:

listen_addresses = '*'

Then:

sudo vi /etc/postgresql/*/main/pg_hba.conf

For example:

host kong kong 192.168.10.0/24 scram-sha-256

Restart:

sudo systemctl restart postgresql
sudo systemctl enable postgresql

Test from Kong VM:

psql -h postgres01 -U kong -d kong

3. Install Kong Gateway

Kong currently documents self-managed Gateway 3.16.0.0 packages for Ubuntu. Kong Docs

On kong01:

sudo apt update
sudo apt install -y curl gnupg

Add Kong repository:

curl -1sLf \
"https://packages.konghq.com/public/gateway-316/gpg.998DFF461A62FF7C.key" \
| gpg --dearmor \
| sudo tee /usr/share/keyrings/kong-gateway-316-archive-keyring.gpg \
> /dev/null

For Ubuntu 24.04/Noble:

curl -1sLf \
"https://packages.konghq.com/public/gateway-316/config.deb.txt?distro=ubuntu&codename=noble" \
| sudo tee /etc/apt/sources.list.d/kong-gateway-316.list

Then:

sudo apt update
sudo apt install kong-enterprise-edition=3.16.0.0

Verify:

kong version

Expected roughly:

3.16.0.0

4. Configure Kong

Edit:

sudo vi /etc/kong/kong.conf

Basic lab configuration:

database = postgres
pg_host = postgres01
pg_port = 5432
pg_user = kong
pg_password = StrongKongPassword
pg_database = kong
proxy_listen = 0.0.0.0:8000
proxy_listen_ssl = 0.0.0.0:8443 ssl
admin_listen = 0.0.0.0:8001
admin_listen_ssl = 0.0.0.0:8444 ssl
status_listen = 0.0.0.0:8100
admin_gui_listen = 0.0.0.0:8002
admin_gui_ssl_listen = 0.0.0.0:8445

Do not expose 8001/8002 externally in production.


5. Add the Kong Enterprise / AI license

AI Proxy Advanced is an AI-license-required plugin. Kong Docs

Your license normally gets configured securely rather than embedded directly into scripts.

Confirm Kong sees the relevant plugins:

kong config parse /etc/kong/kong.conf

Later you can also check:

curl http://localhost:8001/plugins/enabled

Look for:

ai-proxy
ai-proxy-advanced
ai-prompt-guard
ai-rate-limiting-advanced
...

6. Bootstrap the Kong database

Run:

sudo -u kong kong migrations bootstrap \
-c /etc/kong/kong.conf

Then:

sudo kong start -c /etc/kong/kong.conf

Check:

curl http://localhost:8001/status

And:

curl http://localhost:8001

7. Install Ollama

Now create the local AI backend.

On ollama01, install Ollama using its supported installation method for your OS.

After installation verify:

systemctl status ollama

It normally listens on:

11434

You need it reachable from Kong:

kong01
|
| TCP 11434
v
ollama01

Test connectivity from Kong:

curl http://ollama01:11434/api/tags

You should receive JSON.


8. Pull an LLM

For the current Kong example, Kong documents a local Qwen 3 model using Ollama. Kong Docs

On Ollama:

ollama pull qwen3

Check:

ollama list

You should see:

NAME
qwen3

Test Ollama directly first.

For example:

curl http://ollama01:11434/api/chat \
-H "Content-Type: application/json" \
-d '{
"model":"qwen3",
"messages":[
{
"role":"user",
"content":"What is Kong Gateway?"
}
]
}'

This is important: make Ollama work before introducing Kong.


9. Create the Kong AI Service

Create a Service:

curl -X POST http://localhost:8001/services \
--data name=ai-service \
--data url=http://ollama01:11434

Verify:

curl http://localhost:8001/services/ai-service

10. Create the AI Route

Create:

curl -X POST \
http://localhost:8001/services/ai-service/routes \
--data name=ai-chat-route \
--data 'paths[]=/ai/chat'

Check:

curl http://localhost:8001/routes

You now have:

Client
|
v
http://kong01:8000/ai/chat
|
v
ai-service

But we haven’t added AI translation yet.


11. Enable AI Proxy Advanced

This is the important part.

Attach ai-proxy-advanced to the route:

curl -X POST \
http://localhost:8001/routes/ai-chat-route/plugins \
-H "Content-Type: application/json" \
-d '{
"name": "ai-proxy-advanced",
"config": {
"targets": [
{
"route_type": "llm/v1/chat",
"model": {
"provider": "ollama",
"name": "qwen3",
"options": {
"upstream_url": "http://ollama01:11434"
}
}
}
]
}
}'

This configuration matches Kong’s documented Ollama/Qwen AI Proxy Advanced pattern. Kong Docs

Check it:

curl \
http://localhost:8001/routes/ai-chat-route/plugins

12. Test through Kong

Now the important test.

Instead of calling:

Ollama directly

you call:

Kong

Example:

curl -X POST \
http://kong01:8000/ai/chat \
-H "Content-Type: application/json" \
-d '{
"messages": [
{
"role": "user",
"content": "Explain what an API gateway does."
}
]
}'

Flow:

curl
|
v
Kong :8000
|
Route
|
AI Proxy Advanced
|
provider = ollama
|
model = qwen3
|
v
Ollama :11434
|
v
Qwen

At this point you have built your first working Kong AI Gateway.


13. Add API authentication

Don’t leave:

/ai/chat

public.

For the initial lab you can use key-auth:

curl -X POST \
http://localhost:8001/routes/ai-chat-route/plugins \
--data name=key-auth

Create Consumer:

curl -X POST \
http://localhost:8001/consumers \
--data username=ai-application

Create key:

curl -X POST \
http://localhost:8001/consumers/ai-application/key-auth \
--data key=my-secret-ai-key

Test without key:

curl http://kong01:8000/ai/chat

Should return:

401 Unauthorized

Use:

curl -X POST \
http://kong01:8000/ai/chat \
-H "apikey: my-secret-ai-key" \
-H "Content-Type: application/json" \
-d '{
"messages":[
{
"role":"user",
"content":"Explain Kong AI Gateway."
}
]
}'

For production, given your existing environment, I’d replace key-auth with Ping Identity + OIDC.


14. Enable Prometheus AI metrics

Kong’s Prometheus plugin supports AI-specific metrics including requests, token consumption, provider/model information, LLM latency and cost information where available. Set:

ai_metrics = true

Kong documents AI metrics from Gateway 3.8+, including consumer attribution in newer releases. Kong Docs

Enable globally:

curl -X POST \
http://localhost:8001/plugins \
--data name=prometheus \
--data config.status_code_metrics=true \
--data config.latency_metrics=true \
--data config.ai_metrics=true

Check:

curl http://kong01:8100/metrics

Useful metrics will include Kong latency plus AI-specific measurements.

Kong recommends the Status API /metrics endpoint when available rather than exposing the Admin API to Prometheus. Kong Docs


15. Prometheus configuration

On Prometheus:

scrape_configs:
- job_name: "kong-ai-gateway"
scrape_interval: 15s
static_configs:
- targets:
- "kong01:8100"

Restart/reload Prometheus.

Check:

Status → Targets

Kong should show:

UP

16. Grafana dashboard

I would build panels for:

AI Gateway Requests/sec
Input Tokens/sec
Output Tokens/sec
Kong latency:
p50
p95
p99
LLM latency:
p50
p95
p99
HTTP:
2xx
4xx
429
5xx
AI provider
AI model
Consumer
Cache hit/miss

For Kong p95:

histogram_quantile(
0.95,
sum by (le) (
rate(kong_kong_latency_ms_bucket[5m])
)
)

And p99:

histogram_quantile(
0.99,
sum by (le) (
rate(kong_kong_latency_ms_bucket[5m])
)
)

17. Add Azure OpenAI later

Once Ollama works, adding Azure OpenAI is easy.

The architecture becomes:

                       Kong AI Gateway
                              |
             +----------------+--------------+
             |                               |
             v                               v
          Ollama                       Azure OpenAI
          Qwen3                         GPT model
        On-premise                       Azure

Kong’s documented Azure configuration uses:

provider: azure
auth:
header_name: api-key
model:
name: gpt-4o
options:
azure_instance: ...
azure_deployment_id: ...
azure_api_version: ...
``` :chatgpt-content-reference{index="7"}
---
# 18. Then introduce AI security controls
Your eventual plugin chain should look like:
```text
Client
|
v
F5
|
v
Kong
|
+-- OIDC / Ping Identity
|
+-- ACL / Consumer Group
|
+-- AI Prompt Guard
|
+-- AI Rate Limiting Advanced
|
+-- AI Semantic Cache
|
+-- AI Proxy Advanced
|
+-- Prometheus
|
+-- HTTP Log
|
v
AI Provider

Don’t add all of those on day one.

Use this order:

1 Kong
2 PostgreSQL
3 Ollama
4 AI Proxy Advanced
5 Validate AI request
6 Authentication
7 Prometheus/Grafana
8 Logging/ELK
9 Prompt Guard
10 AI Rate Limiting
11 Redis
12 Semantic Cache
13 Multiple LLM providers
14 MCP

19. Production architecture

After your single-node POC works, I would move to this:

                         Applications
                              |
                              |
                         +----v----+
                         |   F5    |
                         |   VIP   |
                         +----+----+
                              |
                    +---------+---------+
                    |                   |
                +---v---+           +---v---+
                | DP-01 |           | DP-02 |
                | Kong  |           | Kong  |
                +---+---+           +---+---+
                    |                   |
                    +---------+---------+
                              |
                 AI Providers / Models
                   /        |       \
                  /         |        \
             Ollama       vLLM     Azure OpenAI


          Control plane – NOT in request path

             +-----------+     +-----------+
             | Kong CP01 |     | Kong CP02 |
             +-----+-----+     +-----+-----+
                   \                 /
                    \               /
                     +------v------+
                     | PostgreSQL  |
                     +-------------+


                     +-------------+
                     |    Redis    |
                     +-------------+
                       /         \
                Rate limit    AI cache


DP01/DP02
   |
   +------ Prometheus ------ Grafana
   |
   +------ Filebeat -------- Logstash
                              |
                              v
                         Elasticsearch
                              |
                            Kibana

Kong hybrid mode explicitly separates the roles: the Control Plane uses PostgreSQL and distributes configuration, while the Data Planes run DB-less and proxy traffic. Kong Docs

I would target this configuration for production deployment:

2 x Kong Control Plane
4 vCPU
8–16 GB RAM
2 x Kong Data Plane
8 vCPU
16 GB RAM
1 x PostgreSQL HA service/cluster
1–3 x Redis nodes depending on HA requirements
2 x F5 pool members initially
Prometheus/Grafana
ELK
Ollama/vLLM GPU nodes if running models internally

The important design principle is:

Kong should not perform inference. Kong handles authentication, routing, governance, rate limits, caching, security, metrics and provider abstraction; Ollama/vLLM/Azure/OpenAI performs the actual model inference.

For your environment, I would therefore build the first working POC as:

Ubuntu 24.04 → PostgreSQL → Kong 3.16 → Ollama/Qwen → ai-proxy-advanced → key-auth → Prometheus/Grafana, and only after that convert it to F5 → 2 Kong DP → Ollama/Azure OpenAI with 2 Kong CP + PostgreSQL. Kong Docs

Kong AI Gateway — Plugin Catalog

Kong’s AI capabilities ship as a set of plugins on top of the core Kong Gateway/Konnect data plane, rather than a separate product. The first six AI plugins shipped in Kong Gateway 3.6 (Feb 2024) as open source; more advanced governance plugins were added later and require Kong Enterprise or Konnect licensing.

Traffic proxying & routing

PluginWhat it does
AI ProxyThe base plugin. Normalizes one request format across providers (OpenAI, Anthropic, Azure, Cohere, Bedrock, Gemini, etc.), translates it to the target’s native format, and transforms the response back. Open source.
AI Proxy AdvancedMulti-target version of AI Proxy — proxies to several providers/models at once and adds load balancing. This is what powers the failover setup we built earlier.
AI MCP ProxyFronts MCP servers (passthrough, conversion, or listener mode), covered in the registry/gateway duty above.
AI MCP OAuth2OAuth2 resource-server behavior specifically for MCP traffic.
AI A2A ProxyRoutes Agent2Agent (A2A) protocol traffic through Kong, with the same per-consumer auth and rate-limiting controls as other AI routes.

Load balancing algorithms (inside AI Proxy Advanced)

Configured via the Upstream entity, not separate plugins:

  • Round-robin (weighted) — proportional traffic split by weight.
  • Consistent-hashing — sticky sessions via a hashed header (default X-Kong-LLM-Request-ID).
  • Lowest-latency — routes to whichever target is currently fastest.
  • Lowest-usage — routes based on token/cost usage, including a cost option added to the usage strategy.
  • Priority — tiered failover (what we configured for Anthropic → Bedrock → OpenAI).
  • Semantic — routes prompts to domain-specialized models based on embedding similarity, with distance_metric and threshold controlling match sensitivity.
  • 3.13+ added health checks and a circuit breaker for the load balancer itself, plus failover/circuit-breaking for semantic routing specifically.

Governance & safety

PluginWhat it does
AI Prompt GuardBlocks or allows prompts by pattern/keyword rules.
AI Semantic Prompt GuardSame idea, but matches by embedding similarity rather than literal pattern — catches paraphrased attempts at a blocked topic. Enterprise.
AI Prompt DecoratorInjects or modifies system/user prompt content before it reaches the model (e.g. enforcing a system prompt).
AI Request/Response TransformerGeneral-purpose payload transformation for AI requests and responses.
AI Rate Limiting AdvancedRate limits by token count and cost, not just request count — this is the plugin underpinning the per-team quota story from the credential-governance duty. Enterprise.

Cost & performance

PluginWhat it does
AI Semantic CacheCaches responses by embedding similarity so repeated/similar prompts skip the model call entirely. Backed by a vector store (Redis and others). Enterprise.
AI RAG InjectorPulls relevant context from a vector store and injects it into the prompt for retrieval-augmented generation.

Observability

  • Prometheus plugin was extended with AI-specific metrics (token counts, cost, latency, MCP call volume) — this is what feeds the shared observability layer from the architecture summary.

Licensing note

Per Kong’s own docs and third-party comparisons: AI Proxy, AI Proxy Advanced, AI Prompt Guard, and AI Prompt Decorator are open source. AI Rate Limiting Advanced, AI Semantic Cache, AI Semantic Prompt Guard, and AI MCP Proxy sit behind Kong Enterprise/Konnect licensing. Confirm current tier gating against Kong’s plugin hub for your specific version, since this has shifted release to release.

Good — pulled the current plugin hub listing directly. Here’s the accurate, up-to-date table, tagged by license tier and mapped to the four pillars from the architecture doc.

AI Plugin Tier Table (Kong Plugin Hub, current)

Free / open source (no AI license required)

PluginWhat it does
AI ProxyBase multi-provider proxy and normalization
AI Prompt GuardPattern-based allow/deny list for prompts
AI Prompt DecoratorPrepends/appends messages to chat history
AI Prompt TemplateFill-in-the-blank prompt templates
AI Request TransformerLLM-based transform of the client request body
AI Response TransformerLLM-based transform of the upstream response

AI License Required (Enterprise/Konnect AI Gateway tier)

PluginWhat it does
AI Proxy AdvancedMulti-target proxy + load balancing/failover
AI Rate Limiting AdvancedToken/cost-based rate limiting
AI Semantic CacheEmbedding-based response caching
AI Semantic Prompt GuardEmbedding-based topic allow/deny
AI Semantic Response GuardBlocks/permits by similarity to known responses
AI PII SanitizerRedacts sensitive data in request/response bodies
AI Prompt CompressorShrinks prompts to cut cost/latency
AI RAG InjectorInjects vector-store content for RAG
AI MCP ProxyMCP server proxying, conversion, aggregation
AI MCP OAuth2OAuth2 auth for MCP servers
AI A2A ProxyGovernance for Agent-to-Agent protocol traffic
AI LLM as JudgeEvaluates/optimizes model output quality
AI AWS Guardrails / AI Azure Content Safety / AI GCP Model ArmorCloud-native guardrail integrations
AI Custom GuardrailBring-your-own third-party guardrails service
AI Lakera GuardLakera Guard safety-policy enforcement

Third-party (separate vendor licensing)
CrowdStrike Falcon AIDR (Request/Response/MCP), Harness AI Security, Noma Runtime Protection, Prisma AIRS, Skyflow De-identify, Straiker (+ Coding Agent variants), Impart Security, VeriKnox.

Mapped to the four architecture pillars

PillarPlugins that implement it
Credential GovernanceAI Proxy / AI Proxy Advanced (vault-referenced auth blocks); AI PII Sanitizer for data leaving the gateway
MCP Registry & GatewayAI MCP Proxy, AI MCP OAuth2
Multi-Provider FailoverAI Proxy Advanced (priority/weighted/semantic/lowest-latency/lowest-usage load balancing, plus 3.13+ health checks and circuit breaker)
ObservabilityPrometheus (extended with AI metrics), OpenTelemetry, AI LLM as Judge for quality tracking
(Guardrails — a fifth pillar worth adding)AI Prompt Guard, AI Semantic Prompt Guard, AI Semantic Response Guard, AI AWS/Azure/GCP Guardrails, AI Custom Guardrail, AI Lakera Guard

One correction from earlier: I’d said AI Prompt Guard and AI Prompt Decorator might be gated — they’re actually free/open source. AI Proxy Advanced, AI Rate Limiting Advanced, AI Semantic Cache, AI Semantic Prompt Guard, AI MCP Proxy and AI MCP OAuth2 are the ones that need the AI license.

I’d also flag that Guardrails has grown into its own real pillar — with cloud-native integrations (AWS/Azure/GCP) plus third-party options (Lakera, CrowdStrike, Straiker) — separate from what I’d folded into “credential governance” earlier.

Integrate Elasticsearch with Ollama for Log Analysis

integrate Elasticsearch/ELK with Ollama like this:

Filebeat / Logstash
↓
Elasticsearch ← Kibana dashboards
↓
Python log-analysis API
↓
Ollama local LLM
↓
AI summary / root cause / recommendation

1. Install Ollama model

curl -fsSL https://ollama.com/install.sh | sh
ollama pull llama3.1
# or lighter:
ollama pull mistral

Test:

ollama run llama3.1

2. Python script to analyze Elasticsearch logs with Ollama

pip install elasticsearch requests
from elasticsearch import Elasticsearch
import requests
ES_URL = "http://localhost:9200"
OLLAMA_URL = "http://localhost:11434/api/generate"
INDEX = "filebeat-*"
es = Elasticsearch(ES_URL)
query = {
"size": 50,
"sort": [{"@timestamp": {"order": "desc"}}],
"query": {
"bool": {
"must": [
{"match": {"log.level": "error"}}
]
}
}
}
result = es.search(index=INDEX, body=query)
logs = []
for hit in result["hits"]["hits"]:
src = hit["_source"]
logs.append(str(src.get("message", src)))
log_text = "\n".join(logs)
prompt = f"""
You are a senior DevOps/SRE log analyst.
Analyze these logs and provide:
1. Summary
2. Possible root cause
3. Impact
4. Recommended fix
5. Exact next commands to troubleshoot
Logs:
{log_text}
"""
payload = {
"model": "llama3.1",
"prompt": prompt,
"stream": False
}
response = requests.post(OLLAMA_URL, json=payload)
print(response.json()["response"])

Run:

python3 analyze_logs.py

3. Better Elasticsearch query examples

For Docker errors:

{
"size": 100,
"query": {
"bool": {
"must": [
{ "match": { "container.name": "kong" }},
{ "match": { "message": "error" }}
]
}
}
}

For last 15 minutes:

{
"size": 100,
"query": {
"range": {
"@timestamp": {
"gte": "now-15m"
}
}
}
}

4. Best architecture for your ELK setup

For your Docker/syslog environment:

Linux servers
├── Filebeat syslog
├── Filebeat Docker logs
↓
Central Logstash
↓
Elasticsearch
↓
AI Analyzer Service
↓
Ollama
↓
Kibana / Email / Slack report

5. Example AI output you can generate

Incident Summary:
Kong is returning intermittent 500 errors.
Likely Root Cause:
Upstream service closed the connection before Kong received a valid response.
Evidence:
- upstream prematurely closed connection
- HTTP 500 from upstream
- repeated failures from same container
Recommended Actions:
1. Check upstream container logs
2. Verify health checks
3. Check Kong upstream timeout settings
4. Check DNS resolution from Kong container

For production, do not send all logs to Ollama. First filter in Elasticsearch, then send only relevant errors/warnings to the model.