Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Claude Agent Sdk Laravel Laravel Package

mohamed-ashraf-elsaed/claude-agent-sdk-laravel

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require mohamed-ashraf-elsaed/claude-agent-sdk-laravel
    
  2. Publish the config:
    php artisan vendor:publish --provider="ClaudeAgentSdk\ClaudeAgentSdkServiceProvider" --tag="config"
    
  3. Configure .env:
    ANTHROPIC_API_KEY=your_claude_api_key_here
    CLAUDE_CODE_CLI_PATH=/path/to/claude-code-cli  # Defaults to global npm install
    
  4. Verify CLI availability:
    php artisan claude:check
    

First Use Case: Simple Agent Execution

use ClaudeAgentSdk\Agent;

$agent = new Agent();
$response = $agent->run('Write a Laravel controller for a user resource with CRUD operations.');

dump($response->content); // Outputs the generated code

Key Initial Files

  • Config: config/claude-agent-sdk.php (adjust sandbox paths, API limits, etc.)
  • Service Provider: app/Providers/ClaudeAgentSdkServiceProvider.php (register bindings)
  • Artisan Commands: app/Console/Commands/ (extend with custom agent logic)

Implementation Patterns

Core Workflows

1. Tool Integration

Wrap external tools (e.g., database queries, HTTP calls) as structured tools for the agent:

use ClaudeAgentSdk\Tool;

$tool = new Tool('db_query', 'Execute a raw SQL query', [
    'query' => 'string',
    'params' => 'array'
]);

$agent->addTool($tool);

2. Sandboxed File Operations

Use the agent to modify files within a restricted directory:

$agent = new Agent(['sandbox_path' => storage_path('app/agents')]);
$agent->run('Create a new file named `example.txt` with "Hello, Claude!"');

3. Subagents for Modularity

Delegate tasks to specialized subagents:

$subagent = new Agent(['role' => 'code_reviewer']);
$response = $subagent->run('Review this PR: ' . file_get_contents('pr_description.md'));

4. Hooks for Post-Processing

Attach hooks to transform or validate agent outputs:

$agent->on('response', function ($response) {
    if (str_contains($response->content, 'ERROR')) {
        throw new \RuntimeException('Agent failed');
    }
});

5. Structured Output Parsing

Force the agent to return JSON/structured data:

$response = $agent->run('Return a JSON object with keys "name" and "version" for this package.');
$structured = json_decode($response->content, true);

Integration Tips

Laravel Service Container

Bind the agent as a singleton for global access:

$this->app->singleton(Agent::class, function ($app) {
    return new Agent(config('claude-agent-sdk.defaults'));
});

Queue Jobs for Async Processing

Wrap agent execution in a job:

use ClaudeAgentSdk\Jobs\RunAgentJob;

RunAgentJob::dispatch('Analyze this codebase for security risks')
    ->onQueue('agents');

API Route Integration

Expose agent endpoints securely:

Route::middleware('auth:sanctum')->post('/agent/run', function (Request $request) {
    $agent = app(Agent::class);
    return response()->json($agent->run($request->input('prompt')));
});

Testing Agents

Use the AgentTestCase trait for isolated tests:

use ClaudeAgentSdk\Testing\AgentTestCase;

class UserAgentTest extends AgentTestCase {
    public function test_user_creation() {
        $response = $this->runAgent('Create a user with email test@example.com');
        $this->assertStringContainsString('User created', $response->content);
    }
}

Gotchas and Tips

Pitfalls

1. CLI Path Misconfiguration

  • Issue: Agent fails with Command not found if claude-code isn’t in $PATH.
  • Fix: Explicitly set CLAUDE_CODE_CLI_PATH in .env or config:
    CLAUDE_CODE_CLI_PATH=/usr/local/bin/claude-code
    

2. Sandbox Permissions

  • Issue: Agent can’t write to sandbox directory due to permissions.
  • Fix: Ensure the Laravel storage directory is writable:
    chmod -R 775 storage/
    

3. API Rate Limits

  • Issue: 429 Too Many Requests errors if hitting Anthropic’s limits.
  • Fix: Configure retries and delays in config/claude-agent-sdk.php:
    'api' => [
        'max_retries' => 3,
        'retry_delay' => 1000, // ms
    ],
    

4. Tool Schema Validation

  • Issue: Agent ignores tools due to mismatched schemas.
  • Fix: Validate tool definitions with:
    $tool->validateSchema(); // Throws on errors
    

5. Memory Limits

  • Issue: Complex prompts exceed PHP’s memory_limit.
  • Fix: Increase in .env:
    MEMORY_LIMIT=4G
    

Debugging Tips

Enable Verbose Logging

config(['claude-agent-sdk.debug' => true]);

Logs appear in storage/logs/claude-agent-sdk.log.

Inspect Raw CLI Output

Use the --verbose flag in config:

'cli' => [
    'verbose' => true,
],

Common Error Patterns

Error Likely Cause Solution
Invalid API key Wrong ANTHROPIC_API_KEY Verify .env and regenerate key
Sandbox not writable File permissions chmod -R 775 storage/app/agents
Tool not found Incorrect tool name in prompt Use exact tool names (case-sensitive)
JSON decode error Malformed structured output Add ->on('response', fn($r) => $r->validateJson())

Extension Points

Custom Agent Classes

Extend ClaudeAgentSdk\Agent for domain-specific logic:

class CodeReviewAgent extends Agent {
    public function __construct() {
        parent::__construct([
            'role' => 'Senior Code Reviewer',
            'tools' => [
                new Tool('git_diff', 'Show changes in a PR'),
                new Tool('phpstan_analyze', 'Run static analysis'),
            ],
        ]);
    }
}

Dynamic Tool Loading

Load tools from a database or config file:

$tools = config('agent.tools');
foreach ($tools as $toolConfig) {
    $agent->addTool(new Tool(...$toolConfig));
}

Webhook Integration

Trigger agents via HTTP webhooks:

Route::post('/webhook/agent', function (Request $request) {
    $agent = app(Agent::class);
    return $agent->run($request->input('prompt'))
        ->then(fn($r) => response()->json($r->content));
});

Multi-Agent Orchestration

Coordinate multiple agents in a workflow:

$researcher = new Agent(['role' => 'Researcher']);
$writer    = new Agent(['role' => 'Technical Writer']);

$topic = $researcher->run('Research Laravel 13 features');
$document = $writer->run("Write a blog post about: {$topic->content}");

Structured Output Validation

Enforce strict output formats:

$agent->on('response', function ($response) {
    $data = json_decode($response->content, true);
    if (!isset($data['success'], $data['result'])) {
        throw new \InvalidArgumentException('Invalid response format');
    }
});
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle