From API to AI Agent: Turning a Laravel Backend Into a Tool-Using System
Your team decides to add an AI agent to your Laravel application. The initial plan seems straightforward: give the LLM access to your existing REST API, let it figure out the endpoints, and watch it automate customer support. Then production happens. The agent calls GET /api/users and pulls 14,000 records into its context window, blowing past the token limit and costing $0.80 for a single turn. It tries to POST to a nested route, guesses the JSON payload wrong, and triggers a validation exception. Worse, it calls the refund endpoint without checking if the current user actually owns the order, because your API relies on middleware that the agent orchestrator bypassed. Building an API for human developers or frontend frameworks is fundamentally different from building an API for an AI agent. Humans read Swagger docs and write deterministic code. Agents read JSON schemas, reason probabilistically, and execute in a loop. If you just expose your Laravel routes to an LLM, you aren't building an agent. You're building a very expensive, highly unpredictable curl client. TL;DR: Turning a Laravel backend into an agent-ready system requires shifting from HTTP-centric controllers to action-centric tools. You must generate strict JSON schemas from PHP attributes, enforce authorization inside the tool boundary, curate outputs to protect the context window, handle failures without breaking the agentic loop, and offload execution to background queues. 📋 Table of Contents 1. Stop Exposing Routes, Start Exposing Actions 2. Generating Tool Schemas from PHP Attributes 3. The Authorization Gap: When Agents Bypass Policies 4. Taming the Context Window with Structured Tool Outputs 5. Surviving the "Infinite Retry" Loop on Flaky Tools 6. Building the Agentic Loop with Laravel Queues 7. Defending Against Tool-Output Prompt Injection 8. Observability: Tracing the Agent's Thought Process The Agent-Ready Backend Checklist 1. Stop Exposing Routes, Start Exposing Actions Scenario: You give an L