Show HN:phpClaw——集成工具、记忆与安全防护的 PHP 版 AI Agent 运行时引擎
英文标题:🔶 Show HN: phpClaw – AI agent runtime for PHP with tools, memory and guards
phpClaw 是一款专为 PHP 生态打造的通用开源 AI Agent 运行时引擎,其核心库完全零框架依赖,仅需 PHP 8.1+ 及基础扩展即可运行。该引擎内置了开箱即用的 ReAct 推理执行循环、多后端可插拔记忆、8 种默认安全防护机制,并原生支持 Anthropic、OpenAI、DeepSeek 等 7 大主流大模型厂商及自定义端点。此外,phpClaw 还提供了 Laravel、Symfony、WordPress 等 8 大主流框架与 CMS 的原生适配器,并集成了 MCP 服务器支持。这一项目的推出填补了 PHP 开发者在构建具备生产级安全管控与多 Agent 编排能力时缺乏标准化运行时的空白。
26.0 KB
25.4 KB
33.0 KB
24.7 KB
55.0 KB
61.4 KB
29.0 KB
965 B
2.5 MB
57.3 KB
中文
面向 PHP 的通用 AI Agent 引擎
工具、记忆、安全防护与 ReAct 循环均已内置。核心层对第三方框架零依赖。支持任意 LLM 提供商。
官方文档 · 适配器 · 为什么选择 phpClaw · 安装指南 · MCP · 安全机制
bash composer require phpclaw/phpclaw export ANTHROPIC_API_KEY="sk-ant-..."
php $agent = PhpClaw\Claw::builder()->build(); echo $agent->send('What can you help me with?')->text;
一个环境变量,一个构建器,一次 send() 调用。构建器会按顺序依次检测 ANTHROPIC_API_KEY、OPENAI_API_KEY、GROQ_API_KEY、GEMINI_API_KEY、MISTRAL_API_KEY、DEEPSEEK_API_KEY 和 OLLAMA_HOST,并自动选用最先找到的提供商。无需编写 YAML,无需学习复杂的 Agent 框架,亦无供应商锁定风险。
没有工具的 Agent 只能聊天。注册你应用所需的工具,它便能开始处理真实业务:
php use PhpClaw\Claw; use PhpClaw\Tools\ShellTool; use PhpClaw\Tools\HttpTool; use PhpClaw\Tools\FileReadTool; use PhpClaw\Tools\DatabaseQueryTool; use PhpClaw\Tools\CodeSearchTool;
$agent = Claw::builder() ->tools([ new ShellTool(allowlist: ['ls', 'df', 'tail']), new HttpTool(), new FileReadTool(), new DatabaseQueryTool($pdo), new CodeSearchTool(), ]) ->build();
检查磁盘使用情况,并查看错误日志最后 20 行
api.example.com 现在是否正常响应?
执行一条只读 SELECT 语句统计今日订单量
在当前代码库中找出所有使用 UserService 的地方
Agent 会自行决定调用哪些工具以及调用顺序,在单个推理循环中运行 ReAct(推理-执行-观察-重复),直到得出答案或达到迭代上限。无论是操作系统 Shell、数据库、HTTP API 还是代码库,这一机制的运作方式都完全一致。
每一篇「在 PHP 中使用 AI」的教程结尾往往如出一辙:在提供商 API 上硬套一个 HTTP 客户端,手写一个简陋的工具调用循环,然后暗自祈祷 Prompt 在生产环境中不会崩溃。通用的 LLM SDK 仅仅为你提供了 API 客户端;而 phpClaw 为你提供了围绕它的完整 Agent 运行时环境:执行循环、安全护栏、上下文记忆、框架集成,全部预先装配妥当。
| phpClaw | 通用 LLM SDK |
|---|---|
| 工具调用循环 (Tool-calling loop) | 内置 ReAct 循环 |
| 框架原生适配器 | 8 款,符合各框架工程习惯 |
| 提示词注入防御 (Prompt injection defence) | 默认启用 8 项防护 + 可选速率限制 |
| 记忆抽象层 (Memory abstraction) | 支持可插拔驱动 |
| 流式传输与工具调用混用 | 混合模式 (Hybrid mode) |
| 内置 MCP 服务器 | 可直接将任何应用暴露给 Claude Desktop |
| 链式调用与多智能体图 (Chains and Graphs) | Pipeline 与 Graph:支持循环、人工介入暂停与恢复、任务扇出 (fan-out) |
| 核心层零框架依赖 | 仅需 ext-curl、ext-json、ext-mbstring 即可 |
| 核心许可证 | MIT,无保留门槛 |
并非万事包揽。 phpClaw 并非 RAG 框架:它不包含向量嵌入 (embeddings) 或向量数据库 (vector stores)。它的设计目标是为 LLM 接入真实业务应用所需的工具、记忆与安全控制,并在单次调用无法满足需求时,将这些 Agent 编排进流水线与执行图中。
Agent 运行时。 具备严格迭代上限(max_iterations,默认 20 次)的 ReAct 循环、可插拔工具、可插拔记忆,以及模型可通过 load_skill 工具按需加载的技能 (Skills),所有这一切均在单一推理周期内执行。
流水线与执行图。 Pipeline 可将多个步骤(提示词模板、Agent、结构化输出、自定义可调用对象)串联起来,并支持重试与降级机制。Graph 运行的节点则支持循环、分支、暂停等待人工确认、在另一进程中恢复执行,以及向外扇出分支——这些分支既可以内联运行,也可以由定时任务 (cron)、消息队列或 CLI 中的工作进程消费完成。详见流水线与执行图 (Pipelines and Graphs)。
灵活的提供商支持。 支持根据环境变量自动检测 7 家主流提供商:Anthropic、OpenAI、Groq、Gemini、Mistral、DeepSeek、Ollama。同时支持兼容 OpenAI 规范的自定义端点(通过指定 PHPCLAW_PROVIDER=custom 启用)。通过 ->provider() 与 ->model() 即可无缝切换提供商,其他代码无需改动。
生产级安全管控。 默认开启 8 种安全守卫(提示词注入、PII 个人隐私脱敏、代码注入、Unicode、同形异义字、角色切换、破坏性 SQL、消息长度防护),并提供可选的速率限制守卫。工具返回结果会无条件由独立于守卫注册表之外的 ToolOutputGuard 进行清洗,而针对 LLM 输出的清理机制同样默认开启,可通过 ->sanitiseOutput(false) 关闭。ShellTool 采用纯白名单模式,并内置不可覆写的硬编码危险命令黑名单。HttpTool 不仅验证主机名,还会对解析后的实际 IP 进行校验,从而封堵仅靠前缀黑名单无法防范的 DNS 重绑定 (DNS-rebinding) 漏洞。FileReadTool/FileWriteTool 受到工作空间沙箱隔离,强制拒绝访问敏感路径与后缀。
开发者体验。 支持逐 Token 流式传输、提示词缓存(Prompt Caching,缓存的输入 Token 按 Anthropic 折扣后的缓存读取费率计费,具体价格见 Anthropic 定价页面),以及扩展思考(Extended Thinking,可通过 $response->thinking 直接读取 Claude 的推理链)。
生态系统。 提供 8 款框架与 CMS 适配器,一个用于向 Claude Desktop 和 Claude Code 暴露业务工具的 MCP 服务器,以及用于托管、持续更新提示词扫描防护的可选云传输通道。
每个适配器都严格按照宿主系统自身的编程习惯将 phpClaw 无缝接入:Laravel 采用 Eloquent、Symfony 采用 Doctrine、WordPress 采用 WP-CLI、Drupal 采用 Drush,等等。每个适配器都随附管理后台聊天界面或 CLI,底层使用完全相同的 3 表记忆架构。
| 平台 | 软件包 | 安装方式 | 支持版本 |
|---|---|---|---|
| Laravel | phpclaw/phpclaw-laravel |
Composer | 10, 11, 12, 13 |
| Symfony | phpclaw/phpclaw-symfony |
Composer | 6.4, 7.x, 8.x |
| Drupal | phpclaw/phpclaw-drupal |
Composer | 10, 11 |
| Magento / Adobe Commerce | phpclaw/phpclaw-magento |
Composer | 2.4.x |
| WordPress + WooCommerce | -- | ZIP 上传 | 6.2+ |
| Joomla | -- | ZIP 上传 | 4, 5, 6 |
| OpenCart | -- | ZIP 上传 | 3.x, 4.x |
| PrestaShop | -- | ZIP 上传 | 8.x, 9.x |
CMS 适配器以 ZIP 包形式发布在 Releases,而非通过 Composer,因为这些宿主平台本身习惯通过该方式安装扩展。
bash php artisan phpclaw "deploy staging and notify #ops" # Laravel bin/console phpclaw "check all database connections" # Symfony drush phpclaw:run "list recently-active users" # Drupal bin/magento phpclaw:run "check order-queue status" # Magento wp phpclaw send "summarise today's posts" # WordPress php cli/joomla.php phpclaw "list recent articles" # Joomla php cli/phpclaw.php send "check low stock products" # OpenCart php modules/phpclaw/cli/phpclaw.php send "check stock levels" # PrestaShop
各适配器的完整参考文档(包含工具、REST 路由、CLI 命令、配置项、记忆驱动)均维护在官方文档站点中。各个适配器自带的 README 仅作为简短指引,而非完整手册。想要构建新的适配器?请参阅社区适配器开发指南。
phpclaw/phpclaw-mcp 将你现有的 ToolRegistry 通过模型上下文协议 (Model Context Protocol, MCP) 暴露,使 Claude Desktop、Claude Code、Cursor 或任何兼容 MCP 的客户端可以直接调用你的工具;同时默认守卫会对每次工具调用的参数进行安全扫描(仅限 Prompt 的代码注入、PII 和长度守卫只作用于聊天消息,不作用于工具参数)。现有工具本身无需任何改动。
bash composer require phpclaw/phpclaw-mcp
完整快速上手、传输协议及安全细节详见:phpclaw.ai/docs/mcp。
所有消息在抵达模型提供商之前,都会先经过默认的守卫链进行处理。ShellTool 仅运行白名单内的命令(默认包含 ls、pwd、df、wc、date、uptime、hostname、whoami),匹配严格区分大小写;无论白名单如何配置,系统均会优先检查固定的、不可覆写的危险命令黑名单。HttpTool 首先按主机名前缀拦截请求,随后重新验证每一个解析出的 IP 地址,精准拦截主机名检查无法察觉的 CGNAT 与 DNS 重绑定攻击。FileReadTool 与 FileWriteTool 被限制在指定的工作区根目录沙箱内,无条件拒绝访问凭据、密钥及安全目录(如 .git、.ssh、wp-admin 等),并默认禁止访问 vendor/ 与 node_modules/。
完整的守卫参考、具体的 ShellTool 黑名单列表以及 SSRF/沙箱实现细节,请查阅:phpclaw.ai/docs/security。若发现安全漏洞,请阅读 SECURITY.md,切勿公开提交 issue。
text Message(消息) → Guards (在 LLM 接收前拦截注入与 PII 泄露) → Hooks (触发生命周期事件,循环中共有 44 个事件钩子) → Agent (ReAct 循环:提供商 + 工具 + 记忆 + 技能) → AgentResponse(文本、Token 统计、工具调用记录、耗时)
提供商、工具、记忆、守卫与技能均通过注册表实现可插拔架构;各个适配器会根据自身配置或环境变量进行装配。完整架构图与设计原则详见:phpclaw.ai/docs/architecture。
系统包含 5 个静态注册表(GuardRegistry、HookRegistry、MemoryRegistry、ProviderRegistry、SkillRegistry)以及按 Agent 实例划分的 ToolRegistry。在 packages/core/src/<Subsystem>/ 目录下添加一个带有对应属性标注(#[Tool]、#[Provider]、#[Memory]、#[Skill]、#[Hook]、#[Guard])的类,执行 composer dump-autoload 即可自动生效。亦可通过代码手动注册:GuardRegistry::register()、HookRegistry::on()、$toolRegistry->register([...])。
各子系统的完整扩展方案及可运行代码示例参见:phpclaw.ai/docs。
bash for pkg in core cloud mcp; do (cd packages/$pkg && composer test); done
单元测试针对 HTTP 客户端、\Redis 以及文件系统均使用了 Mock 和 Stub 替身:运行 core、cloud 或 mcp 的测试套件时,无需进行任何外部网络调用,亦无需配置 API 密钥。完整的测试规范(包括如何通过适配器测试 core 层变更)请参见贡献指南。
本 README 旨在帮助你快速完成安装。关于系统架构、提供商/工具/守卫/钩子/记忆/技能完整参考、各适配器工具与 REST 路由表格、代码示例、版本升级与故障排查等更多内容,请访问:
- PHP 版本: 8.1, 8.2, 8.3, 8.4
- 扩展依赖:
ext-curl、ext-json、ext-mbstring(仅指核心库;各适配器可能需要其他扩展,具体以各包文档为准)
English / 原文
The universal AI agent engine for PHP.
Tools, memory, security, and a ReAct loop, already built. Zero framework dependencies in core. Any LLM provider.
Documentation · Adapters · Why phpClaw · Install · MCP · Security
composer require phpclaw/phpclaw
export ANTHROPIC_API_KEY="sk-ant-..."
$agent = PhpClaw\Claw::builder()->build();
echo $agent->send('What can you help me with?')->text;
One env var, one builder, one send(). The builder checks ANTHROPIC_API_KEY, then OPENAI_API_KEY, GROQ_API_KEY, GEMINI_API_KEY, MISTRAL_API_KEY, DEEPSEEK_API_KEY, OLLAMA_HOST, in that order, and uses whichever it finds first. No YAML, no agent framework to learn, no vendor lock-in.
An agent without tools can only talk. Register the ones your application needs and it starts doing real work:
use PhpClaw\Claw;
use PhpClaw\Tools\ShellTool;
use PhpClaw\Tools\HttpTool;
use PhpClaw\Tools\FileReadTool;
use PhpClaw\Tools\DatabaseQueryTool;
use PhpClaw\Tools\CodeSearchTool;
$agent = Claw::builder()
->tools([
new ShellTool(allowlist: ['ls', 'df', 'tail']),
new HttpTool(),
new FileReadTool(),
new DatabaseQueryTool($pdo),
new CodeSearchTool(),
])
->build();
> Check disk usage and tail the last 20 lines of the error log
> Is api.example.com responding right now?
> Run a read-only SELECT to count today's orders
> Find every place UserService is used in this codebase
The agent decides which tools to call and in what order, running a ReAct loop (reason, act, observe, repeat) until it has an answer or hits the iteration cap. This works identically whether the tools touch your shell, your database, your HTTP APIs, or your codebase.
Every "AI in PHP" tutorial ends the same way: an HTTP client bolted onto a provider API, a hand-rolled tool-call loop, and a prayer that the prompt holds up in production. A generic LLM SDK gives you the API client. phpClaw gives you the agent runtime around it: the loop, the guards, the memory, the framework wiring, already assembled.
| phpClaw | Generic LLM SDK
---|---|---
Tool-calling loop | ReAct, built in | You write it
Framework-native adapters | 8, idiomatic per framework | None
Prompt injection defence | 8 default guards + opt-in rate limiting | None
Memory abstraction | Swappable drivers | None
Streaming + tool-calls together | Hybrid mode | Varies
MCP server bundled | Expose any app to Claude Desktop | None
Chains and multi-agent graphs | Pipeline and Graph: loops, human pause and resume, fan-out | You build it
Zero framework deps in core | ext-curl, ext-json, ext-mbstring, done | Depends
Core license | MIT, nothing gated | Varies
Not trying to be everything. phpClaw isn't a RAG framework: there are no embeddings or vector stores. It's built to give an LLM tools, memory and security controls against your real application, and to chain those agents into pipelines and graphs when one call isn't enough.
Agent runtime. A ReAct loop with a hard iteration cap (max_iterations, default 20), pluggable tools, pluggable memory, and skills the model loads on demand through the load_skill tool, all running inside a single reasoning cycle.
Pipelines and graphs. Pipeline chains steps (prompt template, agent, structured output, your own callables) with retry and fallback. Graph runs nodes that loop, branch, pause for a human, resume in another process, and fan out to branches that run inline or are drained by workers from cron, a queue or the CLI. See Pipelines and Graphs.
Provider flexibility. 7 providers auto-detected from environment variables: Anthropic, OpenAI, Groq, Gemini, Mistral, DeepSeek, Ollama. A custom OpenAI-compatible endpoint is also supported, opt-in via PHPCLAW_PROVIDER=custom. Switch providers with ->provider() and ->model(), no code changes elsewhere.
Production controls. 8 security guards on by default (prompt injection, PII, code injection, Unicode, homoglyph, role-switch, destructive SQL, message length), plus rate limiting available as an opt-in guard. Tool results are sanitised unconditionally by ToolOutputGuard, which sits outside the guard registry, and LLM output sanitisation is on by default and can be disabled with ->sanitiseOutput(false). ShellTool is allowlist-only with a hard-coded command blocklist that can't be overridden. HttpTool validates resolved IPs, not just hostnames, closing the DNS-rebinding gap a prefix blocklist alone would miss. FileReadTool/FileWriteTool are workspace-sandboxed and refuse sensitive paths and extensions.
Developer experience. Token-by-token streaming, prompt caching (cached input tokens billed at Anthropic's discounted cache-read rate, see Anthropic's pricing for the exact figure), and extended thinking (Claude's reasoning chain exposed on $response->thinking).
Ecosystem. 8 framework and CMS adapters, an MCP server for exposing your tools to Claude Desktop and Claude Code, and an optional cloud transport for a hosted, continuously-updated prompt-scan guard.
Each adapter wires phpClaw into its host's own idioms: Eloquent for Laravel, Doctrine for Symfony, WP-CLI for WordPress, Drush for Drupal, and so on. Every adapter ships an admin chat or CLI and the same 3-table memory schema underneath.
| Platform | Package | Install | Versions |
|---|---|---|---|
| Laravel | phpclaw/phpclaw-laravel |
Composer | 10, 11, 12, 13 |
| Symfony | phpclaw/phpclaw-symfony |
Composer | 6.4, 7.x, 8.x |
| Drupal | phpclaw/phpclaw-drupal |
Composer | 10, 11 |
| Magento / Adobe Commerce | phpclaw/phpclaw-magento |
Composer | 2.4.x |
| WordPress + WooCommerce | -- | ZIP upload | 6.2+ |
| Joomla | -- | ZIP upload | 4, 5, 6 |
| OpenCart | -- | ZIP upload | 3.x, 4.x |
| PrestaShop | -- | ZIP upload | 8.x, 9.x |
CMS adapters ship as ZIP downloads from Releases, not Composer, because that's how their host platforms install extensions.
php artisan phpclaw "deploy staging and notify #ops" # Laravel
bin/console phpclaw "check all database connections" # Symfony
drush phpclaw:run "list recently-active users" # Drupal
bin/magento phpclaw:run "check order-queue status" # Magento
wp phpclaw send "summarise today's posts" # WordPress
php cli/joomla.php phpclaw "list recent articles" # Joomla
php cli/phpclaw.php send "check low stock products" # OpenCart
php modules/phpclaw/cli/phpclaw.php send "check stock levels" # PrestaShop
Full per-adapter reference (tools, REST routes, CLI commands, settings, memory drivers) lives on the doc site. Each adapter's own README is a short pointer, not a manual. Building a new one? See the community adapter guides.
phpclaw/phpclaw-mcp exposes your existing ToolRegistry over the Model Context Protocol, so Claude Desktop, Claude Code, Cursor, or any MCP-compatible client can call your tools directly, with the default guards scanning every tool call's arguments (the prompt-only code-injection, PII and length guards apply to chat messages, not tool arguments). No changes to the tools themselves.
composer require phpclaw/phpclaw-mcp
Full quick start, transport, and security details: phpclaw.ai/docs/mcp.
Every message runs through the default guard chain before it reaches the provider. ShellTool runs only commands on its allowlist (default ls, pwd, df, wc, date, uptime, hostname, whoami), matched exactly and case-sensitively; a fixed, non-overridable blocklist of dangerous commands is checked first regardless of what's allowlisted. HttpTool blocks requests by hostname prefix, then re-validates every resolved IP address, catching CGNAT and DNS-rebinding attempts that hostname checks alone would miss. FileReadTool and FileWriteTool are sandboxed to a configured workspace root and refuse credentials, keys and security directories (.git, .ssh, wp-admin, ...) unconditionally, and vendor/ and node_modules/ by default.
Full guard reference, the exact ShellTool blocklist, and the SSRF/sandbox implementation details: phpclaw.ai/docs/security. Found a vulnerability? See SECURITY.md, do not open a public issue.
Message
→ Guards (blocks injection/PII before the LLM sees it)
→ Hooks (lifecycle events fire, 44 across the loop)
→ Agent (ReAct loop: provider + tools + memory + skills)
→ AgentResponse (text, tokens, tool calls, timing)
Providers, tools, memory, guards, and skills are all pluggable through registries; every adapter wires them from its own config or environment. Full architecture diagram and design rules: phpclaw.ai/docs/architecture.
Five static registries (GuardRegistry, HookRegistry, MemoryRegistry, ProviderRegistry, SkillRegistry) plus the per-agent ToolRegistry instance. Drop a class in packages/core/src/<Subsystem>/ with the matching attribute (#[Tool], #[Provider], #[Memory], #[Skill], #[Hook], #[Guard]), run composer dump-autoload, it's live. Or register from code: GuardRegistry::register(), HookRegistry::on(), $toolRegistry->register([...]).
Full extension recipes with working code for every subsystem: phpclaw.ai/docs.
for pkg in core cloud mcp; do (cd packages/$pkg && composer test); done
Unit tests use mocks and stubs for HTTP clients, \Redis, and the filesystem: no external network calls and no API keys are needed to run the suite for core, cloud, or mcp. The full testing rules, including how to test a core change through an adapter, are in the contributing guide.
This README gets you installed. Everything else, architecture, the full provider/tool/guard/hook/memory/skill reference, per-adapter tool and REST tables, code examples, upgrading, troubleshooting, lives at:
- PHP: 8.1, 8.2, 8.3, 8.4
- Extensions:
ext-curl,ext-json,ext-mbstring(core only; adapters may need more, documented per-package)
MIT, built with love for the PHP community. Part of the phpClaw project.
