Building AI Agents in Production: What MCP Rejections, .env Leaks, and 70‑Line Loops Taught Me
Description and use
Implementing MCP rejection handlers, scoped env vars, dynamic credential injection, and loop detection stabilized AI agents in production.
Problem
AI agents often fail in production due to naive engineering: unhandled MCP rejections, environment variable leaks, and infinite reasoning loops.
Outcome
The agent now handles MCP rejections gracefully, no longer leaks credentials, and avoids infinite loops, resulting in stable production runs and reduced on‑call incidents.
Workflow
- 1. Treat MCP rejections as first‑class events and implement a rejection handler that maps codes to recovery actions.
- 2. Scope environment variables per agent deployment and avoid shared containers.
- 3. Fetch credentials dynamically from secure endpoints instead of loading at startup.
- 4. Add an output sanitization layer to redact credential patterns.
- 5. Enforce maximum iteration bounds and progress detection to prevent infinite loops.
- 6. Maintain a hash of recent tool calls to detect and reject duplicates.
- 7. Log and alert on MCP rejections, leaks, and loop detections for rapid incident response.
Evidence
MCP rejections should be treated as first‑class events, not exceptions
The .env leak cost us $47,000
- Record date: 2026-09-15T08:46:55.954Z