PHPackages                             datashaman/claude-agent-sdk - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. datashaman/claude-agent-sdk

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

datashaman/claude-agent-sdk
===========================

PHP SDK for building autonomous agents powered by Claude

v0.1.3(2mo ago)053↓91.7%1MITPHPPHP &gt;=8.2

Since Mar 25Pushed 2mo agoCompare

[ Source](https://github.com/datashaman/claude-agent-sdk)[ Packagist](https://packagist.org/packages/datashaman/claude-agent-sdk)[ RSS](/packages/datashaman-claude-agent-sdk/feed)WikiDiscussions main Synced 3w ago

READMEChangelog (4)Dependencies (2)Versions (11)Used By (1)

Claude Agent SDK for PHP
========================

[](#claude-agent-sdk-for-php)

PHP SDK for building autonomous agents powered by Claude. This is the PHP equivalent of the official [TypeScript](https://github.com/anthropics/claude-agent-sdk-typescript) and [Python](https://github.com/anthropics/claude-agent-sdk-python) SDKs.

Requirements
------------

[](#requirements)

- PHP 8.2+
- [Claude CLI](https://docs.anthropic.com/en/docs/claude-code/overview) installed and authenticated

### Web Server Authentication (PHP-FPM)

[](#web-server-authentication-php-fpm)

When running under a web server (PHP-FPM with Nginx/Valet/etc.), the Claude CLI cannot access the macOS login keychain used by `claude login`. You must set up a file-based authentication token:

```
claude setup-token
```

This creates a long-lived token tied to your **Claude Code subscription** that works without keychain access. Add the token to your `.env`:

```
CLAUDE_CLI_PATH=/path/to/claude
CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-...
```

The SDK automatically passes `CLAUDE_*` and `ANTHROPIC_*` environment variables to the CLI process, with one important exception:

### Environment Variable Exclusions

[](#environment-variable-exclusions)

`ANTHROPIC_API_KEY` is **excluded by default**. When present, it causes the CLI to use direct API access (pay-per-use) instead of your Claude Code subscription. Since this SDK is designed to drive the Claude CLI with subscription-based auth, passing the API key would bypass your subscription and incur unexpected charges.

Default exclusions are defined in `ClaudeAgentOptions::DEFAULT_EXCLUDED_ENV_KEYS`.

To override the exclusion list (e.g. if you explicitly want API key auth):

```
$options = ClaudeAgentOptions::create()
    ->excludeEnvKeys([]); // pass all env vars through
```

To add additional exclusions:

```
$options = ClaudeAgentOptions::create()
    ->excludeEnvKeys([
        ...ClaudeAgentOptions::DEFAULT_EXCLUDED_ENV_KEYS,
        'ANTHROPIC_CUSTOM_VAR',
    ]);
```

Installation
------------

[](#installation)

```
composer require datashaman/claude-agent-sdk
```

Quick Start
-----------

[](#quick-start)

### Basic Query

[](#basic-query)

```
use DataShaman\Claude\AgentSdk\Claude;

foreach (Claude::query('What is PHP?') as $message) {
    if ($message->type === 'content_block_delta' && isset($message->delta['text'])) {
        echo $message->delta['text'];
    }
}
```

### Query with Options

[](#query-with-options)

```
use DataShaman\Claude\AgentSdk\Claude;
use DataShaman\Claude\AgentSdk\ClaudeAgentOptions;
use DataShaman\Claude\AgentSdk\Enum\PermissionMode;

$options = ClaudeAgentOptions::create()
    ->model('claude-sonnet-4-6')
    ->maxTurns(5)
    ->systemPrompt('You are a helpful PHP expert.')
    ->permissionMode(PermissionMode::AcceptEdits);

foreach (Claude::query('Explain generators', $options) as $message) {
    // Process streaming messages
}
```

### Custom Tools

[](#custom-tools)

Define tools using PHP attributes:

```
use DataShaman\Claude\AgentSdk\Attribute\Tool;
use DataShaman\Claude\AgentSdk\Attribute\Parameter;
use DataShaman\Claude\AgentSdk\Claude;
use DataShaman\Claude\AgentSdk\ClaudeAgentOptions;

#[Tool(name: 'get_weather', description: 'Get current weather for a city')]
function getWeather(
    #[Parameter(description: 'City name')]
    string $city,
    #[Parameter(description: 'Temperature unit', enum: ['celsius', 'fahrenheit'])]
    string $unit = 'celsius',
): array {
    // Your weather API logic here
    return ['temp' => 22, 'unit' => $unit, 'city' => $city];
}

$options = ClaudeAgentOptions::create()
    ->tools(['getWeather']);

foreach (Claude::query('What is the weather in London?', $options) as $message) {
    // Tool calls are handled automatically
}
```

### Session Management

[](#session-management)

```
use DataShaman\Claude\AgentSdk\ClaudeAgentClient;
use DataShaman\Claude\AgentSdk\ClaudeAgentOptions;

$client = ClaudeAgentClient::create(
    ClaudeAgentOptions::create()->model('claude-sonnet-4-6')
);

// First message
foreach ($client->send('Hello!') as $message) {
    // Process response
}

// Continue the conversation (same session)
foreach ($client->send('Tell me more') as $message) {
    // Process response
}

// List all sessions
$sessions = $client->listSessions();

// Get messages from a session
$messages = $client->getSessionMessages($sessionId);
```

### MCP Server

[](#mcp-server)

Create an MCP server that exposes tools to Claude:

```
use function DataShaman\Claude\AgentSdk\Mcp\createSdkMcpServer;

$server = createSdkMcpServer([
    'getWeather', // Pass tool callables
]);

$server->run(); // Starts listening on stdio
```

Connect to external MCP servers:

```
$options = ClaudeAgentOptions::create()
    ->mcpServers([
        'myserver' => [
            'command' => 'node',
            'args' => ['path/to/server.js'],
        ],
    ]);
```

API Reference
-------------

[](#api-reference)

### `Claude::query(string $prompt, ?ClaudeAgentOptions $options = null): Generator`

[](#claudequerystring-prompt-claudeagentoptions-options--null-generatormessage)

One-off query that returns a Generator yielding `Message` objects as they stream from the CLI.

### `ClaudeAgentOptions`

[](#claudeagentoptions)

Immutable configuration object with fluent builder:

MethodDescription`model(string)`Claude model to use`maxTurns(int)`Maximum agent turns`systemPrompt(string)`Replace system prompt`appendSystemPrompt(string)`Append to system prompt`tools(array)`Custom tool callables`mcpServers(array)`MCP server configurations`permissionMode(PermissionMode)`Permission mode`allowedTools(array)`Restrict available tools`cwd(string)`Working directory for CLI`env(array)`Environment variables (full override)`excludeEnvKeys(array)`Env keys to exclude from passthrough (default: `ANTHROPIC_API_KEY`)`sessionId(string)`Resume a session`extendedThinking(array)`Extended thinking config`permissionPromptHandler(callable)`Permission callback### `ClaudeAgentClient`

[](#claudeagentclient)

Stateful client for multi-turn conversations:

MethodDescription`send(string)`Send a message, returns Generator`getSessionId()`Current session ID`listSessions()`List all sessions`getSessionMessages(string)`Get session history### `Message`

[](#message)

Readonly DTO for streaming events:

PropertyTypeDescription`type``string`Event type (message\_start, content\_block\_delta, etc.)`index``?int`Content block index`message``?array`Full message (for message\_start)`contentBlock``?array`Content block data`delta``?array`Delta data for streaming`sessionId``string`Session ID`uuid``string`Event UUID### Permission Modes

[](#permission-modes)

```
PermissionMode::Default           // Default CLI behavior
PermissionMode::AcceptEdits       // Auto-accept file edits
PermissionMode::BlockEdits        // Block all file edits
PermissionMode::BypassPermissions // Skip all permission prompts
```

License
-------

[](#license)

MIT

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance83

Actively maintained with recent releases

Popularity8

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

4

Last Release

89d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/48372fbab9c5059c6d5773bb3d42dff0382443ceb65d008fc219ad38a383eafd?d=identicon)[datashaman](/maintainers/datashaman)

---

Top Contributors

[![datashaman](https://avatars.githubusercontent.com/u/59514?v=4)](https://github.com/datashaman "datashaman (9 commits)")

---

Tags

agentaianthropicclaudecomposerllmmcpphpsdkstreamingsdkmcpaistreamingAgentclaudellmanthropic

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/datashaman-claude-agent-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/datashaman-claude-agent-sdk/health.svg)](https://phpackages.com/packages/datashaman-claude-agent-sdk)
```

###  Alternatives

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

Anthropic Claude Agent SDK for PHP &amp; Laravel — build AI agents with tool use, sandboxing, MCP servers, subagents, hooks, and structured output via the Claude Code CLI

171.1k](/packages/mohamed-ashraf-elsaed-claude-agent-sdk-laravel)[mozex/anthropic-laravel

Laravel integration for the Anthropic API: facade, config publishing, install command, testing fakes, messages, streaming, tool use, thinking, and batches.

72287.1k1](/packages/mozex-anthropic-laravel)[mozex/anthropic-php

PHP client for the Anthropic API: messages, streaming, tool use, thinking, web search, code execution, batches, and more.

47480.9k16](/packages/mozex-anthropic-php)[alle-ai/anthropic-api-php

The go-to PHP library for the Anthropic API — Messages, streaming, tool use, vision, prompt caching, extended thinking, MCP, Files, Batches. Maintained by Alle-AI.

2625.3k](/packages/alle-ai-anthropic-api-php)[stimmt/craft-mcp

MCP (Model Context Protocol) server for Craft CMS

261.3k](/packages/stimmt-craft-mcp)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
