Connecting AI agents to internal enterprise tools via the Model Context Protocol (MCP) turns simple prompt injections into remote code execution on your infrastructure—and most security teams are flying completely blind.
For CISOs and CEOs, the business risk is no longer just a brand-damaging chatbot hallucination. When an agent is granted access to a company's financial databases, GitHub repositories, or cloud infrastructure, a compromised agent can execute unauthorized actions that lead directly to data breaches, compliance violations (like GDPR or SOC2), and significant corporate liability. Over 10,000 production MCP servers have been deployed globally as of 2026, creating a vast, heavily distributed attack surface that traditional Web Application Firewalls (WAFs) cannot interpret.
As developers eagerly wire up open-source tools to their foundation models to increase velocity, the security perimeter shifts fundamentally. It moves away from input validation (trying to prevent bad prompts) to runtime execution control (preventing bad actions). Developers often argue that prompt engineering and system instructions are enough to restrict agent behavior. However, relying on the model to govern itself is a critical security failure. A deterministic gateway policy proves that network-level enforcement is the only way to stop a compromised agent from exploiting a tool, satisfying both the speed-to-market required by AI Platform Leaders and the operational coverage demanded by SecOps managers.
This field guide details how to implement zero-trust network egress controls for your AI agents, allowing you to detect and block unauthorized MCP tool calls before they execute against your infrastructure.
What Are Custom Gateway Policies for AI Agents?
When deploying agentic systems, engineering teams and executives quickly realize that relying solely on the LLM to behave itself is not a viable security strategy or a defendable compliance posture. Custom gateway policies are deterministic rules enforced at the network layer—between the AI agent and the external tool or MCP server—that govern exactly what an agent is allowed to do.
The System Prompt vs. Deterministic Network Policy
A system prompt is fundamentally probabilistic. You can instruct an agent with "Do not delete files" or "Only read from the database," but these instructions are processed by the same neural network that processes adversarial user input. If an attacker successfully injects a prompt payload—perhaps hidden in a parsed PDF or a malicious website—the agent's internal reasoning can easily be overridden, leading it to ignore the system prompt entirely.
A deterministic network policy, on the other hand, operates completely outside the agent's context window. It is a set of hard rules (often defined in YAML or JSON) executed by an AI Security Gateway. Regardless of what the LLM decides, if it attempts an action that violates the policy, the gateway blocks the request at the network level. This provides a hard, auditable boundary that cannot be bypassed via prompt injection or context window manipulation, fulfilling the strict access controls required by SOC2 and ISO 42001 auditors.
Why LLM-Native Guardrails Fail Against Rogue Agents
Many early AI security tools focus on LLM-native guardrails, such as "LLM-as-a-judge," where a secondary, smaller model evaluates the primary model's output before execution. While useful for detecting toxic content or off-topic responses in conversational chatbots, these guardrails fail miserably when applied to high-speed agentic tool execution.
First, there is the latency penalty. Gateway policies execute in <7ms, compared to the 1-2 second latency penalty of LLM-as-a-judge guardrails. When an agent is iterating rapidly through a multi-step planning loop, adding seconds of latency to every tool call destroys performance and architectural viability. Second, LLM-as-a-judge is still probabilistic and vulnerable to the same adversarial techniques it is supposed to detect. If an agent goes rogue, it needs to be stopped by mathematics and strict networking rules, not another prompt evaluation.
The AI Security Gateway as the Inline Enforcement Point
To secure MCP tool calls effectively, you need an interception point that sees the payload after the agent generates it but before the tool executes it. This is the role of an AI Security Gateway acting as an inline proxy.
Source: MCP Introduction — Model Context Protocol architecture diagram showing the relationship between Hosts, Clients, and Servers.
The gateway sits between the agent (the client) and the MCP server (the host of the tools). By acting as the unified control plane, the gateway can inspect the exact JSON payload, validate the tool name, parse the arguments, and enforce policies deterministically. As highlighted in Uber's Keynote on Scaling MCP, "Authorization is optional by design in standard MCP implementations, forcing security teams to build custom guardrails at the network perimeter."
Why You Can't Trust Open-Source MCP Servers by Default
The Model Context Protocol has revolutionized agent capabilities by allowing anyone to build and share tools. However, this open ecosystem brings significant supply chain and runtime risks that must be mitigated by platform engineers and overseen by CISOs.
The Explosion of Community-Built MCP Tools
GitHub, file systems, internal databases, and bespoke enterprise APIs—there is an open-source MCP server for almost everything. While this accelerates development, it means that SecOps teams are importing third-party code that executes locally within their environment, often with broad permissions.
You cannot blindly trust the code within an open-source tool to sanitize inputs properly or enforce the principle of least privilege. A vulnerability in the MCP server's implementation can easily become a vector for lateral movement or data exfiltration, bypassing standard identity and access management (IAM) controls. For more on how attackers exploit these tools, see our guide on defending against MCP tool poisoning.
The Risk of Over-Privileged Execution Environments
One of the most insidious problems with agentic tools is over-privileged execution. An engineer might grant an agent a tool intended for read access, such as reading log files or querying a database. However, if the underlying tool or the permissions on the host system are not tightly scoped, an attacker could manipulate the agent to execute a write operation, such as modifying configuration files or dropping a reverse shell.
This violates the principle of least privilege, a core tenet of modern cybersecurity frameworks. If the agent hands off a command like rm -rf / to a poorly configured file system tool, and there is no gateway policy in place, the tool will faithfully execute it.
The NSA Warning on MCP Attack Surfaces
The urgency of this issue is underscored by recent intelligence advisories. As Atef Ataya noted in his breakdown of the NSA Advisory on AI Agent Security, "The architectural root cause of agent vulnerabilities is trusting the tool execution hand-off by default."
The advisory highlights three primary attack surfaces for agentic workflows: authentication, Server-Side Request Forgery (SSRF), and task hand-off injection. Task hand-off injection occurs when a malicious payload is successfully passed from the agent's context window into the execution environment of the tool. If the MCP server processes this payload blindly, the attacker effectively gains remote code execution within your infrastructure.
How to Detect Unauthorized MCP Tool Calls
Detection is the first step toward mitigation. SecOps teams must build observability into the agent's execution layer to identify when a tool is being misused, creating the audit trails necessary for rapid incident response and compliance verification.
Decoupling the Tool Schema from the Request Payload
To detect anomalies, the gateway must deeply inspect the payload traversing the network. This involves decoupling the tool schema (the declared structure of what the agent should be sending) from the agent's actual request (what it actually generated).
According to the OWASP Top 10 for LLM Applications, Excessive Agency (LLM06) and Insecure Output Handling (LLM02) are foundational risks. Agents hallucinate, and attackers manipulate agents into generating malformed requests. By parsing the JSON-RPC payload of an MCP tool call, the gateway validates that the requested tool name exists in the allowed list and that the arguments strictly conform to the expected types and constraints (e.g., verifying that a file_path argument is a string and does not contain directory traversal sequences like ../).
Using Regex and ML Classifiers for Command Injection
Once the structure is validated, the gateway must inspect the content of the arguments for malicious payloads. A common attack vector is command injection, where an attacker tricks the agent into passing bash commands within a legitimate tool argument.
To detect this, gateway policies can employ highly optimized regex patterns and lightweight, discriminative ML classifiers running directly at the edge. These mechanisms look for shell metacharacters, known exploit signatures, and obfuscated bash payloads within the JSON arguments. This approach blocks command injection deterministically without the latency overhead of generative evaluation, preserving the low-latency requirements of the AI architecture.
Logging Anomalous Tool Execution Sequences
Detecting unauthorized agent actions isn't just about inspecting individual requests; it's also about analyzing the sequence of actions. An agent performing a benign task will typically follow a predictable pattern. A compromised agent, however, will often exhibit exploratory behavior reminiscent of a human threat actor.
For example, an attacker might force the agent to explore the local environment. Logging anomalous tool execution sequences—such as an agent calling a list_files tool, followed by a read_env tool, followed immediately by an unauthorized curl tool call—is a strong indicator of compromise (IoC). Gateways can track these stateful sequences and trigger alerts when agents deviate from their baseline behavior.
Build: Writing a Zero-Trust Policy for an MCP Server
Let's walk through exactly how to write custom policies for AI gateways to secure an MCP server. We'll build a deterministic network policy that enforces zero-trust principles, satisfying both SecOps managers and AI platform leaders.
Step 1: Defining the Baseline Schema and Allowed Tools
The foundation of a zero-trust policy is a strict allowlist. We must explicitly define which tools the agent is permitted to call and exactly what arguments are acceptable. Anything not explicitly allowed is denied by default.
This involves defining the tool name and the JSON schema for its arguments. If the agent attempts to call an unregistered tool, or provides an argument outside the bounds of the schema, the gateway rejects the request instantly. This prevents the agent from leveraging undocumented or newly added tools without explicit security approval.
Step 2: Implementing the Network Egress Rule to Prevent SSRF
Server-Side Request Forgery (SSRF) is a critical risk for AI agents, as they can be manipulated to query internal cloud metadata services and extract credentials. We must implement a strict egress rule to block these attempts.
The policy must inspect any URLs or IP addresses passed as arguments to network-capable tools (like fetch or curl). It should explicitly block access to known metadata IP addresses, such as the AWS metadata service at 169.254.169.254, as well as internal network ranges (e.g., 10.0.0.0/8, 192.168.0.0/16) unless explicitly required.
Step 3: Enforcing Time-of-Day and Context-Aware Execution
To further reduce the attack surface, policies should incorporate context-awareness. Does this particular customer support agent need to execute database writes at 3:00 AM on a Sunday? Probably not.
We can enforce time-of-day execution windows or require specific contextual markers (such as an active user session ID or a specific cryptographic identity) before permitting a tool call. If the context does not match the policy requirements, the gateway blocks the action, preventing automated, off-hours exploitation and satisfying strict compliance auditing requirements.
Code Example: A Zero-Trust MCP Gateway Policy Configuration
Below is a conceptual example of a custom gateway policy written in a YAML-like configuration. This policy restricts the agent to a specific tool, blocks directory traversal, and prevents SSRF.
policy_name: secure_mcp_file_reader
target_agent: customer_support_bot
enforcement_mode: blocking
allowed_tools:
- tool_name: "read_customer_file"
schema_validation:
strict: true
arguments:
file_path:
type: "string"
# Block directory traversal attempts
deny_patterns: ["\.\./", "\.\.\\", "^/etc/"]
# Ensure it only reads from the approved directory
must_match: "^/data/customer_docs/"
egress_controls:
- tool_name: "network_fetch"
# Prevent SSRF to cloud metadata and internal networks
deny_ips:
- "169.254.169.254/32"
- "10.0.0.0/8"
- "127.0.0.0/8"
allowed_domains:
- "api.stripe.com"
- "github.com"
# Block destructive shell commands globally across all tool arguments
global_deny_patterns:
- "rm\s+-rf"
- "chmod\s+777"
- "wget\s+"
- "curl\s+"
This configuration serves as a deterministic control plane, ensuring that even if the agent hallucinates or is maliciously prompted, the underlying infrastructure remains protected.
When Should You Block vs. Alert on Agent Actions?
Deciding when to enforce a hard block versus when to simply alert the SOC is a critical operational decision. Overly aggressive blocking can break legitimate workflows and frustrate platform engineers, while purely alert-based systems fail to stop active exploitation, exposing the CEO to business risk.
Setting Up a "Shadow Mode" Baseline
When deploying a new agent or integrating a new MCP tool, it is best practice to deploy gateway policies in "shadow mode" (or audit mode). In this state, the gateway inspects the traffic and evaluates the policies but does not actually block any requests.
Instead, it logs what would have been blocked. This allows SecOps teams to baseline normal agent behavior, identify false positives, and tune their regex patterns and schemas without disrupting production workflows or impacting the velocity of the AI/ML engineering teams.
Configuring Hard Blocks for Destructive Commands
Once the baseline is established and the policy is tuned, you must configure hard blocks for undeniably malicious or destructive actions.
Any attempt to execute shell commands like rm -rf, access credential stores like AWS Secrets Manager without authorization, or query the 169.254.169.254 metadata endpoint should result in an immediate, deterministic block. There is no legitimate business case for a customer support agent to modify system binaries, so the gateway must enforce that boundary rigorously to protect the organization from liability.
Sending Telemetry to the SOC for Incident Response
Whether a tool call is blocked or allowed, the gateway must generate high-fidelity telemetry and forward it to the organization's SIEM or observability platform (e.g., Datadog, Splunk).
When an unauthorized MCP tool call is blocked, the gateway should trigger a high-severity alert to the SOC. The log payload must include the agent ID, the full context window leading up to the action, the attempted tool JSON payload, and the specific policy rule that was violated. This provides incident responders with the complete context needed to determine if it was a hallucination or an active prompt injection attack.
Next Steps: Moving from Visibility to Enforcement
The transition from probabilistic LLM guardrails to deterministic network policies is what separates experimental AI projects from enterprise-ready autonomous systems. To secure your MCP infrastructure, SecOps and AI Platform leaders should prioritize deploying an inline interception point to baseline agent behavior immediately.
For a deeper dive into this architectural shift, read our complete guide on why ephemeral workflows require Agentic EDR for runtime security. As the purpose-built EDR for AI agents, GuardionAI delivers these zero-trust gateway policies out-of-the-box, providing the necessary network interception and real-time telemetry to govern every AI agent action without slowing down your development cycles.
Frequently Asked Questions
How do custom gateway policies differ from API rate limits?
API rate limits focus purely on the volume of requests over time (e.g., 100 requests per minute) to prevent DoS attacks. Custom gateway policies deeply inspect the actual payload of the request—validating tool schemas, argument contents, and execution context—to prevent malicious actions and unauthorized behavior, regardless of the request volume.
Can custom policies inspect encrypted MCP traffic?
Yes, but the AI Security Gateway must be deployed as a trusted inline proxy. The gateway terminates the TLS connection from the agent, inspects the plaintext JSON payload to enforce policies, and then re-encrypts the traffic before forwarding it to the backend MCP server. This is a standard architectural pattern for deep packet inspection.
What happens when a tool call is blocked by the gateway?
When a policy violation occurs, the gateway drops the request to the MCP server and returns a standardized error response (e.g., an HTTP 403 or a specific JSON-RPC error code) back to the agent. The agent's control loop receives this error, allowing it to log the failure and potentially attempt a different, authorized approach.
Do these policies add latency to the agent's reasoning loop?
Deterministic network policies add minimal latency. Because they rely on schema validation, regex matching, and lightweight edge classifiers rather than generative LLM evaluations, policies execute in under 7 milliseconds (often <3ms p99). This avoids the multi-second delays associated with LLM-as-a-judge guardrails.
How do I test a gateway policy before deploying it to production?
The safest approach is to deploy the policy in "shadow mode" (audit only) in your production environment. The gateway will evaluate traffic against the policy and log any violations without actually blocking the requests. This allows you to identify false positives and tune the policy using real-world agent traffic before enabling blocking mode.

