AWS Builder Center

Enforcing the RAG/MCP Boundary in Production Agentic Systems on AWS

Category: Architecture | AI/ML | Reliability & Availability

Senior DevOps & SRE | IEEE Senior Member | AI Observability & Cloud Resilience

The "RAG vs. MCP" debate is a category error — and teams that treat it as an architectural tradeoff are building systems with a missing safety layer.
RAG and MCP don't compete. They operate at different levels of the agentic stack:
  • RAG answers what the agent knows — runbook context, historical incident patterns, policy constraints, architecture state.
  • MCP answers what the agent can do — live metric fetching, system state reads, remediation execution against real infrastructure.
Conflating these two layers creates a specific, reproducible class of production failure: an agent that treats "I retrieved something relevant" as equivalent to "I have permission to execute it." That's an agent without a safety layer. In a regulated fintech environment running on AWS, the blast radius of that conflation is not theoretical.
This post shows how to enforce the boundary in code across three AWS-native patterns using the  agentsre  library.



Why This Failure Mode Is Predictable

The mechanism is consistent across incidents I've observed:
  1. Agent retrieves documentation via RAG with high similarity confidence.
  1. Retrieved document is stale — authored before an infrastructure migration, configuration change, or topology shift.
  1. No gate exists between retrieval and execution.
  1. Agent executes against a live system based on stale context.
  1. Blast radius is immediate.
The inverse failure is also common: knowledge queries that only need read-only context get routed through heavy MCP tooling with live-system access, adding latency and consuming rate-limited API quota unnecessarily.
Both failures share the same root cause: the boundary between the knowledge layer and the execution layer was implicitly trusted rather than explicitly enforced.



The Three-Layer Architecture

Before the code: the architecture that makes enforcement possible.
┌─────────────────────────────────────────────────────────┐
│ Layer 1: Situational Awareness (RAG) │
│ ─ Read-only. No execution authority. │
│ ─ Outputs: structured context package + freshness tag │
└────────────────────────┬────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ Layer 2: Decision Gate │
│ ─ Freshness check on retrieved context │
│ ─ Blast radius classification │
│ ─ Error budget check (block execution if burning fast) │
│ ─ Human escalation for high-risk action classes │
└────────────────────────┬────────────────────────────────┘
│ (only passes if gate clears)
▼
┌─────────────────────────────────────────────────────────┐
│ Layer 3: Execution (MCP) │
│ ─ Scoped tool calls. Permissions tied to approved │
│ action class, not to full tool access. │
│ ─ Dry-run mode for blast-radius-above-threshold ops. │
│ ─ Audit trail to CloudWatch Logs. │
└─────────────────────────────────────────────────────────┘
Layer 2 is where most agentic systems have nothing. The model handles it implicitly. Implicit model reasoning is not a reliability control.



Pattern 1: Context Freshness Gate

The first enforcement point: before any retrieved context informs an execution decision, validate that it's fresh enough to act on for the proposed action class.
Different action classes have different staleness tolerances. Restarting a pod can tolerate a runbook that's a week old. Modifying IAM policies cannot.
python
import boto3
import logging
from dataclasses import dataclass
from datetime import datetime, timezone
from enum import Enum
from typing import Optional

logger = logging.getLogger(__name__)

class ActionClass(str, Enum):
"""
Risk tiers for remediation actions.
Staleness tolerance decreases as risk increases.
"""
READ_ONLY = "READ_ONLY" # No execution; any context age acceptable
LOW_RISK = "LOW_RISK" # Pod restarts, log rotation, cache flush
MEDIUM_RISK = "MEDIUM_RISK" # Scaling events, config changes, deploy rollback
HIGH_RISK = "HIGH_RISK" # IAM changes, DB failover, network policy edits
CRITICAL = "CRITICAL" # Always requires human review regardless of freshness

# Max acceptable document age (seconds) per action class
STALENESS_LIMITS: dict[ActionClass, Optional[int]] = {
ActionClass.READ_ONLY: None, # No limit
ActionClass.LOW_RISK: 7 * 86400, # 7 days
ActionClass.MEDIUM_RISK: 2 * 86400, # 2 days
ActionClass.HIGH_RISK: 4 * 3600, # 4 hours
ActionClass.CRITICAL: 0, # Always escalate
}

@dataclass
class RetrievedContext:
"""
Output of the RAG layer — structured context package with provenance.

Attributes
----------
document_id : str
Unique ID of the source document in the knowledge base.
content : str
Retrieved document text or structured summary.
similarity_score : float
Cosine similarity or equivalent retrieval confidence [0.0, 1.0].
last_modified_utc : datetime
When the source document was last updated. UTC-aware.
source_system : str
Knowledge base source (e.g. "confluence", "s3-runbooks", "pagerduty").
metadata : dict
Arbitrary metadata from the retrieval system.
"""
document_id: str
content: str
similarity_score: float
last_modified_utc: datetime
source_system: str
metadata: dict

@dataclass
class GateDecision:
"""
Result of the context freshness gate.

Attributes
----------
approved : bool
True if context is fresh enough for the proposed action class.
action_class : ActionClass
The action class evaluated against.
document_age_seconds : int
Age of the retrieved document at evaluation time.
staleness_limit_seconds : int or None
Configured limit for this action class. None means no limit.
escalation_required : bool
True when action class is CRITICAL or context is too stale.
escalation_reason : str
Human-readable reason for escalation, if applicable.
"""
approved: bool
action_class: ActionClass
document_age_seconds: int
staleness_limit_seconds: Optional[int]
escalation_required: bool
escalation_reason: str = ""

def evaluate_context_freshness(
context: RetrievedContext,
proposed_action_class: ActionClass,
sns_escalation_topic_arn: Optional[str] = None,
) -> GateDecision:
"""
Gate 1: Validate that retrieved RAG context is fresh enough to inform
an execution decision for the proposed action class.

This is the explicit enforcement point between the RAG layer (knowing)
and the MCP layer (doing). An agent that passes this gate has context
that is within the configured staleness tolerance for its action class.
An agent that fails this gate escalates to a human — it does not proceed.

Parameters
----------
context : RetrievedContext
The RAG-retrieved context package to evaluate.
proposed_action_class : ActionClass
The risk tier of the remediation action being considered.
sns_escalation_topic_arn : str or None
If provided, publishes an escalation notification to SNS when
the gate blocks execution.

Returns
-------
GateDecision
approved=True means the agent may proceed to the execution layer.
approved=False means the agent must escalate. No execution.

Example
-------
>>> decision = evaluate_context_freshness(
... context=retrieved_runbook,
... proposed_action_class=ActionClass.HIGH_RISK,
... sns_escalation_topic_arn="arn:aws:sns:us-east-1:123456789012:sre-escalations",
... )
>>> if not decision.approved:
... escalate_to_human(decision.escalation_reason)
... return
"""
now = datetime.now(tz=timezone.utc)
age_seconds = int((now - context.last_modified_utc).total_seconds())
staleness_limit = STALENESS_LIMITS[proposed_action_class]

# CRITICAL always escalates regardless of document age
if proposed_action_class == ActionClass.CRITICAL:
reason = (
f"Action class CRITICAL always requires human review. "
f"Document: {context.document_id} | Source: {context.source_system}"
)
_publish_escalation(sns_escalation_topic_arn, reason, context, proposed_action_class)
logger.warning(
"Context freshness gate: CRITICAL escalation",
extra={
"document_id": context.document_id,
"action_class": proposed_action_class,
"document_age_seconds": age_seconds,
},
)
return GateDecision(
approved=False,
action_class=proposed_action_class,
document_age_seconds=age_seconds,
staleness_limit_seconds=0,
escalation_required=True,
escalation_reason=reason,
)

# READ_ONLY: always approve, no execution authority involved
if proposed_action_class == ActionClass.READ_ONLY or staleness_limit is None:
return GateDecision(
approved=True,
action_class=proposed_action_class,
document_age_seconds=age_seconds,
staleness_limit_seconds=staleness_limit,
escalation_required=False,
)

# Staleness check for all other action classes
if age_seconds > staleness_limit:
reason = (
f"Retrieved context is too stale for action class {proposed_action_class}. "
f"Document age: {age_seconds}s | Limit: {staleness_limit}s | "
f"Document: {context.document_id} | Last modified: {context.last_modified_utc.isoformat()}"
)
_publish_escalation(sns_escalation_topic_arn, reason, context, proposed_action_class)
logger.error(
"Context freshness gate: BLOCKED — stale context for action class",
extra={
"document_id": context.document_id,
"action_class": proposed_action_class,
"document_age_seconds": age_seconds,
"staleness_limit_seconds": staleness_limit,
"source_system": context.source_system,
},
)
return GateDecision(
approved=False,
action_class=proposed_action_class,
document_age_seconds=age_seconds,
staleness_limit_seconds=staleness_limit,
escalation_required=True,
escalation_reason=reason,
)

logger.info(
"Context freshness gate: APPROVED",
extra={
"document_id": context.document_id,
"action_class": proposed_action_class,
"document_age_seconds": age_seconds,
"staleness_limit_seconds": staleness_limit,
},
)
return GateDecision(
approved=True,
action_class=proposed_action_class,
document_age_seconds=age_seconds,
staleness_limit_seconds=staleness_limit,
escalation_required=False,
)

def _publish_escalation(
topic_arn: Optional[str],
reason: str,
context: RetrievedContext,
action_class: ActionClass,
):
if not topic_arn:
return
try:
sns = boto3.client("sns")
sns.publish(
TopicArn=topic_arn,
Subject=f"[agentsre] Context freshness gate blocked execution — {action_class}",
Message=(
f"Action class: {action_class}\n"
f"Reason: {reason}\n"
f"Document ID: {context.document_id}\n"
f"Source: {context.source_system}\n"
f"Similarity score: {context.similarity_score}\n"
),
)
except Exception as e:
logger.warning("SNS escalation publish failed", extra={"error": str(e)})



Pattern 2: Scoped MCP Execution Wrapper

Gate 1 validates freshness. Gate 2 scopes what the agent is allowed to do even after it clears the freshness check.
The key principle: the available tool set in the execution layer is determined by the approved action class — not by everything the agent has access to at runtime.
python
import json
from dataclasses import dataclass, field
from typing import Any, Callable

import boto3

# Tool permissions per action class
# Each entry is the set of tool names available for that action class.
# An agent approved for LOW_RISK cannot call HIGH_RISK tools even if it
# has the tool definitions in its context.
ACTION_CLASS_TOOL_SCOPES: dict[ActionClass, set[str]] = {
ActionClass.READ_ONLY: {
"fetch_cloudwatch_metrics",
"describe_ec2_instances",
"list_ecs_services",
"get_rds_status",
},
ActionClass.LOW_RISK: {
"fetch_cloudwatch_metrics",
"describe_ec2_instances",
"list_ecs_services",
"get_rds_status",
"restart_ecs_task",
"flush_elasticache",
"rotate_log_group",
},
ActionClass.MEDIUM_RISK: {
"fetch_cloudwatch_metrics",
"describe_ec2_instances",
"list_ecs_services",
"get_rds_status",
"restart_ecs_task",
"flush_elasticache",
"rotate_log_group",
"update_asg_desired_capacity",
"rollback_ecs_deployment",
"update_ssm_parameter",
},
ActionClass.HIGH_RISK: set(), # Always escalates; no automated tooling
ActionClass.CRITICAL: set(), # Always escalates; no automated tooling
}

@dataclass
class ScopedExecutionContext:
"""
Execution context derived from a cleared decision gate.

Only created when a GateDecision.approved is True.
Carries the approved action class and available tool scope into
the execution layer so the agent cannot self-elevate permissions.
"""
gate_decision: GateDecision
retrieved_context: RetrievedContext
approved_tools: set[str] = field(default_factory=set)
dry_run: bool = False

def __post_init__(self):
self.approved_tools = ACTION_CLASS_TOOL_SCOPES.get(
self.gate_decision.action_class, set()
)

@dataclass
class ExecutionResult:
"""Result of a scoped tool call through the execution layer."""
tool_name: str
action_class: ActionClass
dry_run: bool
success: bool
result: Any
audit_log_event: dict

class ScopedMCPExecutor:
"""
Execution layer: MCP tool calls scoped to the approved action class.

Enforces the right side of the RAG/MCP boundary. An agent that has
cleared the context freshness gate receives a ScopedExecutionContext
that limits available tools to those appropriate for the approved
action class. Tool calls outside that scope are blocked and audited —
the agent cannot self-elevate by requesting a higher-risk tool.

All executions are audited to CloudWatch Logs for compliance traceability.

Parameters
----------
cloudwatch_log_group : str
CloudWatch log group for execution audit trail.
"""

def __init__(self, cloudwatch_log_group: str = "/agentsre/execution-audit"):
self.log_group = cloudwatch_log_group
self._cw_logs = boto3.client("logs")
self._tool_registry: dict[str, Callable] = {}

def register_tool(self, name: str, fn: Callable):
"""Register an MCP tool implementation by name."""
self._tool_registry[name] = fn

def execute(
self,
tool_name: str,
tool_args: dict,
exec_ctx: ScopedExecutionContext,
) -> ExecutionResult:
"""
Execute a tool call within the scope of an approved action class.

Blocks and audits any tool call that falls outside the approved scope
for the execution context. In dry_run mode, plans the action without
executing it — useful for blast-radius-above-threshold operations that
need human review before live execution.

Parameters
----------
tool_name : str
Name of the MCP tool to invoke. Must be in exec_ctx.approved_tools.
tool_args : dict
Arguments to pass to the tool.
exec_ctx : ScopedExecutionContext
Execution context from the cleared gate decision.

Returns
-------
ExecutionResult
success=False when the tool is out of scope or execution fails.
Audit event is always populated regardless of success.
"""
audit_event = {
"tool_name": tool_name,
"action_class": exec_ctx.gate_decision.action_class,
"document_id": exec_ctx.retrieved_context.document_id,
"document_age_seconds": exec_ctx.gate_decision.document_age_seconds,
"dry_run": exec_ctx.dry_run,
"tool_args_keys": list(tool_args.keys()), # Keys only, not values (may contain secrets)
}

# Scope enforcement — agent cannot self-elevate
if tool_name not in exec_ctx.approved_tools:
audit_event["blocked"] = True
audit_event["block_reason"] = (
f"Tool '{tool_name}' not in approved scope for "
f"action class {exec_ctx.gate_decision.action_class}. "
f"Approved tools: {sorted(exec_ctx.approved_tools)}"
)
self._audit(audit_event)
logger.error(
"Scoped execution blocked: tool outside approved scope",
extra=audit_event,
)
return ExecutionResult(
tool_name=tool_name,
action_class=exec_ctx.gate_decision.action_class,
dry_run=exec_ctx.dry_run,
success=False,
result=None,
audit_log_event=audit_event,
)

# Dry run: stage the action without executing
if exec_ctx.dry_run:
planned_result = {
"planned_tool": tool_name,
"planned_args": tool_args,
"status": "DRY_RUN — execution staged for human review",
}
audit_event["dry_run_plan"] = planned_result
self._audit(audit_event)
logger.info(
"Dry-run execution staged",
extra={"tool_name": tool_name, "action_class": exec_ctx.gate_decision.action_class},
)
return ExecutionResult(
tool_name=tool_name,
action_class=exec_ctx.gate_decision.action_class,
dry_run=True,
success=True,
result=planned_result,
audit_log_event=audit_event,
)

# Live execution
tool_fn = self._tool_registry.get(tool_name)
if not tool_fn:
audit_event["error"] = f"Tool '{tool_name}' registered in scope but not implemented"
self._audit(audit_event)
return ExecutionResult(
tool_name=tool_name,
action_class=exec_ctx.gate_decision.action_class,
dry_run=False,
success=False,
result=None,
audit_log_event=audit_event,
)

try:
result = tool_fn(**tool_args)
audit_event["success"] = True
self._audit(audit_event)
logger.info(
"Scoped execution completed",
extra={"tool_name": tool_name, "action_class": exec_ctx.gate_decision.action_class},
)
return ExecutionResult(
tool_name=tool_name,
action_class=exec_ctx.gate_decision.action_class,
dry_run=False,
success=True,
result=result,
audit_log_event=audit_event,
)
except Exception as e:
audit_event["success"] = False
audit_event["error"] = str(e)
self._audit(audit_event)
logger.error(
"Scoped execution failed",
extra={"tool_name": tool_name, "error": str(e)},
)
return ExecutionResult(
tool_name=tool_name,
action_class=exec_ctx.gate_decision.action_class,
dry_run=False,
success=False,
result=None,
audit_log_event=audit_event,
)

def _audit(self, event: dict):
"""Write an execution event to the CloudWatch audit log."""
import time
try:
self._cw_logs.put_log_events(
logGroupName=self.log_group,
logStreamName="execution-audit",
logEvents=[
{
"timestamp": int(time.time() * 1000),
"message": json.dumps(event, default=str),
}
],
)
except Exception as e:
logger.warning("Audit log write failed", extra={"error": str(e)})



Pattern 3: Full Pipeline — RAG → Gate → MCP

The complete orchestration: RAG retrieval flows into the freshness gate, which conditionally creates a scoped execution context, which then constrains what MCP tools the agent can invoke.
python
from dataclasses import dataclass
from typing import Optional

@dataclass
class AgentRemediationRequest:
"""
Inputs to the agentic remediation pipeline.

Parameters
----------
incident_summary : str
Natural language description of the incident or alert.
proposed_action_class : ActionClass
Risk tier of the remediation action being considered.
tool_name : str
MCP tool to invoke if the gate clears.
tool_args : dict
Arguments for the MCP tool.
force_dry_run : bool
If True, executes in dry-run mode regardless of action class.
Use for pre-production validation and human review workflows.
sns_escalation_topic_arn : str or None
SNS topic for escalation notifications when gate blocks execution.
"""
incident_summary: str
proposed_action_class: ActionClass
tool_name: str
tool_args: dict
force_dry_run: bool = False
sns_escalation_topic_arn: Optional[str] = None

@dataclass
class PipelineResult:
"""Full result of the RAG → Gate → MCP pipeline."""
request: AgentRemediationRequest
retrieved_context: Optional[RetrievedContext]
gate_decision: Optional[GateDecision]
execution_result: Optional[ExecutionResult]
pipeline_blocked: bool
block_reason: str = ""

def run_remediation_pipeline(
request: AgentRemediationRequest,
rag_retriever: Callable[[str], RetrievedContext],
executor: ScopedMCPExecutor,
) -> PipelineResult:
"""
Execute the full RAG → Gate → MCP remediation pipeline.

This is the top-level orchestration that enforces the boundary between
the knowledge layer and the execution layer. The agent cannot reach the
execution layer without passing through the freshness gate. The execution
layer cannot exceed the permissions of the approved action class.

Parameters
----------
request : AgentRemediationRequest
Describes the incident and the proposed remediation.
rag_retriever : Callable[[str], RetrievedContext]
Function that accepts an incident summary and returns the most
relevant retrieved context from the knowledge base.
executor : ScopedMCPExecutor
Configured executor with registered tool implementations.

Returns
-------
PipelineResult
Full result with retrieved context, gate decision, and execution result.
pipeline_blocked=True when the gate blocks or retrieval fails.

Example
-------
>>> result = run_remediation_pipeline(
... request=AgentRemediationRequest(
... incident_summary="ECS service payment-api showing high CPU utilization",
... proposed_action_class=ActionClass.LOW_RISK,
... tool_name="restart_ecs_task",
... tool_args={"cluster": "prod-cluster", "service": "payment-api"},
... sns_escalation_topic_arn="arn:aws:sns:us-east-1:123456789012:sre-alerts",
... ),
... rag_retriever=my_knowledge_base.retrieve,
... executor=my_executor,
... )
>>> print(f"Blocked: {result.pipeline_blocked} | Reason: {result.block_reason}")
"""
# Layer 1: RAG — knowledge retrieval
logger.info(
"Pipeline: RAG retrieval starting",
extra={"incident_summary": request.incident_summary[:200]},
)
try:
context = rag_retriever(request.incident_summary)
except Exception as e:
logger.error("RAG retrieval failed", extra={"error": str(e)})
return PipelineResult(
request=request,
retrieved_context=None,
gate_decision=None,
execution_result=None,
pipeline_blocked=True,
block_reason=f"RAG retrieval failed: {e}",
)

# Layer 2: Decision gate — freshness and action class validation
gate = evaluate_context_freshness(
context=context,
proposed_action_class=request.proposed_action_class,
sns_escalation_topic_arn=request.sns_escalation_topic_arn,
)

if not gate.approved:
return PipelineResult(
request=request,
retrieved_context=context,
gate_decision=gate,
execution_result=None,
pipeline_blocked=True,
block_reason=gate.escalation_reason,
)

# Layer 3: MCP execution — scoped to approved action class
exec_ctx = ScopedExecutionContext(
gate_decision=gate,
retrieved_context=context,
dry_run=request.force_dry_run,
)

exec_result = executor.execute(
tool_name=request.tool_name,
tool_args=request.tool_args,
exec_ctx=exec_ctx,
)

return PipelineResult(
request=request,
retrieved_context=context,
gate_decision=gate,
execution_result=exec_result,
pipeline_blocked=not exec_result.success,
block_reason="" if exec_result.success else str(exec_result.audit_log_event.get("error", "")),
)



Putting It Together in Production

The three patterns compose into a complete reliability control for agentic infrastructure systems:
The freshness gate ( evaluate_context_freshness ) enforces that the knowledge layer is current before it informs execution. The scoped executor ( ScopedMCPExecutor ) enforces that execution authority is bounded by what was approved — the agent cannot self-elevate. The pipeline orchestrator ( run_remediation_pipeline ) enforces that the MCP layer is unreachable without passing through both gates.
These patterns ship as the  knowledge_execution_boundary  module in the  agentsre  library, composable with the existing  pre_action_gate ,  semantic_gap_detection , and  dependency_risk  primitives.


For teams operating autonomous agents against regulated AWS infrastructure: the question worth asking in your next architecture review is whether the boundary between knowing and doing exists explicitly in your codebase, or is it implicit in your assumptions about how the model will reason.
Assumptions don't page. The boundary does — if you build it.


Drop your implementation approach in the comments — how are you separating the knowledge retrieval layer from the execution boundary in your agentic systems?


Tags:  reliability **  aws **  sre **  agentic-ai **  mcp **  rag **  platform-engineering **  python **  production 
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article