From API to AI Agent: Turning a Laravel Backend Into a Tool-Using System
Description and use
Transforming a Laravel backend into an agent‑ready system by exposing action‑centric tools, generating schemas from PHP attributes, enforcing authorization inside tools, and offloading execution to queues eliminates costly HTTP calls, prevents data leaks, and ensures reliable agent behavior.
Problem
Exposing Laravel REST routes to an LLM creates expensive, unpredictable, and insecure agent behavior because agents interpret JSON schemas, not HTTP semantics, leading to token overuse, validation errors, and authorization bypasses.
Outcome
By shifting from HTTP routes to action‑centric tools, the team reduced token costs, eliminated validation errors, prevented PII leaks, and achieved a reliable, maintainable agent integration.
Workflow
- 1. Stop exposing HTTP routes to the agent; expose invokable Action classes as tools.
- 2. Annotate Action classes and parameters with PHP 8 attributes (AgentTool, ToolParam).
- 3. Build a ToolRegistry that reflects on attributes to generate OpenAI/Anthropic JSON schemas.
- 4. Inject user context and enforce Laravel Gates/Policies inside each tool to prevent authorization bypass.
- 5. Structure tool outputs as strict JSON to keep context size small and avoid prompt injection.
- 6. Wrap tool execution in a retry‑safe loop and offload long‑running tasks to Laravel queues.
- 7. Add observability: log agent thoughts, tool calls, and outcomes for debugging.
Evidence
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.
Decouple your business logic from your HTTP controllers and expose invokable Action classes as tools.
Inject the authorization context explicitly into the agent loop, and enforce Laravel Gates or Policies inside the tool execution boundary.
- Record date: 2026-09-11T04:46:40.784Z