DEV Community

mohamed ashraf
mohamed ashraf

Posted on

Building AI Agents in Laravel with Claude Code SDK

I just released an open-source Laravel package that lets you build AI agents powered by Claude Code directly in your PHP applications.

The Problem

Claude Code is an incredibly powerful agent — it can read files, edit code, run bash commands, search the web, and delegate to subagents. But it's a CLI tool. If you want those capabilities inside a Laravel app (automated code reviews, AI-powered admin tools, agentic workflows), you need a programmatic interface.

The Solution

Claude Agent SDK for Laravel wraps the Claude Code CLI and gives you a fluent PHP API.

composer require mohamed-ashraf-elsaed/claude-agent-sdk-laravel
Enter fullscreen mode Exit fullscreen mode

Quick Start

use ClaudeAgentSDK\Facades\ClaudeAgent;

$result = ClaudeAgent::query('What files are in this directory?');

echo $result->text();       // Final text result
echo $result->costUsd();    // Cost in USD
echo $result->sessionId;    // Session ID for resuming
Enter fullscreen mode Exit fullscreen mode

Fluent Options Builder

use ClaudeAgentSDK\Options\ClaudeAgentOptions;

$options = ClaudeAgentOptions::make()
    ->tools(['Read', 'Edit', 'Bash', 'Grep', 'Glob'])
    ->permission('acceptEdits')
    ->maxTurns(10)
    ->model('claude-sonnet-4-5-20250929')
    ->cwd(base_path());

$result = ClaudeAgent::query('Find and fix the bug in auth.php', $options);
Enter fullscreen mode Exit fullscreen mode

Real-Time Streaming

Perfect for broadcasting progress to your frontend via WebSockets:

$result = ClaudeAgent::streamCollect(
    prompt: 'Create a REST API for products',
    onMessage: function ($message) {
        if ($message instanceof AssistantMessage) {
            broadcast(new AgentProgress($message->text()));
        }
    },
);
Enter fullscreen mode Exit fullscreen mode

Subagents

Define specialized agents that Claude delegates tasks to:

$options = ClaudeAgentOptions::make()
    ->tools(['Read', 'Grep', 'Task'])
    ->agent('security-reviewer', new AgentDefinition(
        description: 'Security code review specialist',
        prompt: 'Find vulnerabilities in PHP/Laravel code.',
        tools: ['Read', 'Grep', 'Glob'],
    ))
    ->agent('test-writer', new AgentDefinition(
        description: 'PHPUnit test writer',
        prompt: 'Write comprehensive PHPUnit tests.',
        tools: ['Read', 'Write', 'Bash'],
    ));
Enter fullscreen mode Exit fullscreen mode

Structured Output

Get validated JSON matching a schema:

$options = ClaudeAgentOptions::make()
    ->outputFormat([
        'type' => 'object',
        'properties' => [
            'issues' => [
                'type' => 'array',
                'items' => [
                    'type' => 'object',
                    'properties' => [
                        'file' => ['type' => 'string'],
                        'severity' => ['type' => 'string'],
                        'message' => ['type' => 'string'],
                    ],
                ],
            ],
        ],
    ]);

$data = ClaudeAgent::query('Find TODOs in src/', $options)->structured();
Enter fullscreen mode Exit fullscreen mode

Session Management

Continue conversations across requests:

$result1 = ClaudeAgent::query('Read the auth module');
$sessionId = $result1->sessionId;

// Later — resume with full context
$result2 = ClaudeAgent::query(
    'Now add email verification',
    ClaudeAgentOptions::make()->resume($sessionId),
);
Enter fullscreen mode Exit fullscreen mode

MCP Server Integration

Connect external tools via Model Context Protocol:

use ClaudeAgentSDK\Tools\McpServerConfig;

$options = ClaudeAgentOptions::make()
    ->mcpServer('database', McpServerConfig::stdio(
        command: 'npx',
        args: ['@modelcontextprotocol/server-database'],
        env: ['DB_URL' => config('database.url')],
    ));
Enter fullscreen mode Exit fullscreen mode

Full Feature List

  • Fluent options builder with IDE autocompletion
  • Streaming with real-time message processing
  • Subagent delegation
  • MCP server integration (stdio + SSE)
  • Structured output with JSON schema
  • Session resume and fork
  • Full message/content block parsing
  • Laravel service provider, facade, config publishing
  • PHP 8.1-8.4, Laravel 10/11/12
  • Full test suite

Links


If you have feedback or feature requests, open an issue on GitHub. Contributions welcome!

Top comments (0)