定制 datashaman/claude-agent-sdk 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

datashaman/claude-agent-sdk

Composer 安装命令:

composer require datashaman/claude-agent-sdk

包简介

PHP SDK for building autonomous agents powered by Claude

README 文档

README

PHP SDK for building autonomous agents powered by Claude. This is the PHP equivalent of the official TypeScript and Python SDKs.

Requirements

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

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

composer require datashaman/claude-agent-sdk

Quick Start

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

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

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

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

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

Claude::query(string $prompt, ?ClaudeAgentOptions $options = null): Generator<Message>

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

ClaudeAgentOptions

Immutable configuration object with fluent builder:

Method Description
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

Stateful client for multi-turn conversations:

Method Description
send(string) Send a message, returns Generator
getSessionId() Current session ID
listSessions() List all sessions
getSessionMessages(string) Get session history

Message

Readonly DTO for streaming events:

Property Type Description
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

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

License

MIT

datashaman/claude-agent-sdk 适用场景与选型建议

datashaman/claude-agent-sdk 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 53 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 03 月 25 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「sdk」 「streaming」 「Agent」 「ai」 「mcp」 「llm」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 datashaman/claude-agent-sdk 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 datashaman/claude-agent-sdk 我们能提供哪些服务?
定制开发 / 二次开发

基于 datashaman/claude-agent-sdk 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 53
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 25
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-25