> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# 创建 Boost 的自定义 Agent

> 深入 Laravel Boost 的扩展架构，讲解如何实现 SupportsGuidelines、SupportsMcp、SupportsSkills 契约的自定义 Agent。

## 为什么需要自定义 Agent

Laravel Boost 内置支持 Claude Code、Cursor、Codex、GitHub Copilot（VS Code）等主流 AI 编码工具。但若要适配公司内部工具、新兴 AI Agent 或独立的工作流，就需要使用 Boost 的扩展机制来实现自定义 Agent。

自定义 Agent 适用的场景：

* 使用 Boost 尚未支持的 IDE 或 AI 工具
* 希望将 Boost 集成到公司内部开发流程或自有 CI/CD 流水线中
* Agent 拥有独立的配置文件格式或安装步骤

## Boost 的扩展架构

### Agent 基类

所有 Agent 都继承 `Laravel\Boost\Install\Agents\Agent`。该抽象类提供的能力：

* Agent 的检测（系统级 / 项目级）
* MCP 服务器的安装（基于文件 / 基于 Shell 命令）
* 指南（Guidelines）的转换钩子（`transformGuidelines`）

必须实现的抽象方法有 2 个（如下表还列出了常见需要覆盖的方法）。

| 方法                                          | 说明                             |
| ------------------------------------------- | ------------------------------ |
| `name()`                                    | Agent 的内部标识符（例如 `claude_code`） |
| `displayName()`                             | 安装时显示的名称（例如 `Claude Code`）     |
| `systemDetectionConfig(Platform $platform)` | 系统级安装的检测配置                     |
| `projectDetectionConfig()`                  | 项目级安装的检测配置                     |

### 3 个契约

为按需启用 Boost 的功能，只需实现下面所需的契约。

| 契约                   | 作用                 |
| -------------------- | ------------------ |
| `SupportsGuidelines` | AI 指南文件的输出路径与转换处理  |
| `SupportsMcp`        | 安装 MCP 服务器配置       |
| `SupportsSkills`     | Agent Skills 的安装路径 |

<Info>
  这 3 个契约都是可选的。也可以只支持指南而不支持 MCP。
</Info>

### SupportsGuidelines 契约

```php theme={null}
interface SupportsGuidelines
{
    // AI 指南写入的文件路径
    public function guidelinesPath(): string;

    // 指南文件是否需要 frontmatter
    public function frontmatter(): bool;

    // 对生成的指南 Markdown 做后处理
    public function transformGuidelines(string $markdown): string;
}
```

`guidelinesPath()` 返回生成的指南要写入的路径。例如 Claude Code 是 `CLAUDE.md`，Cursor 是 `.cursor/rules/laravel-boost.mdc`，需要匹配 Agent 读取的格式。

`transformGuidelines()` 是对生成后的 Markdown 进行加工的钩子。可以添加 Agent 专属头部或转换为特殊格式。`Agent` 基类的默认实现原样返回字符串。

### SupportsMcp 契约

```php theme={null}
interface SupportsMcp
{
    // MCP 命令是否使用绝对路径
    public function useAbsolutePathForMcp(): bool;

    // 返回 PHP 可执行文件的路径
    public function getPhpPath(bool $forceAbsolutePath = false): string;

    // 返回 artisan 的路径
    public function getArtisanPath(bool $forceAbsolutePath = false): string;

    // 安装 MCP 服务器配置
    public function installMcp(string $key, string $command, array $args = [], array $env = []): bool;

    // 安装通过 HTTP 使用的 MCP 服务器配置
    public function installHttpMcp(string $key, string $url): bool;
}
```

由于 `Agent` 基类已提供 `installMcp()` 与 `installHttpMcp()` 的默认实现，多数情况下只需覆盖 `mcpInstallationStrategy()` 与 `mcpConfigPath()` 即可。

安装策略有两种：

| `McpInstallationStrategy` | 行为                       |
| ------------------------- | ------------------------ |
| `FILE`                    | 将配置写入 JSON / TOML 文件（默认） |
| `SHELL`                   | 执行 Shell 命令注册 MCP        |
| `NONE`                    | 跳过 MCP 安装                |

### SupportsSkills 契约

```php theme={null}
interface SupportsSkills
{
    // 写入 Agent Skills 的目录路径
    public function skillsPath(): string;
}
```

返回 Agent 读取的 Skill 目录路径。例如 Claude Code 是 `.claude/skills`，Cursor 是 `.cursor/skills`，需要匹配 Agent 的规范。

## 创建自定义 Agent

下面我们来实现一个独立的 Agent 类。这里以嵌入自有 CI/CD 工作流的虚构 Agent「MyAgent」为例。

<Steps>
  <Step title="创建 Agent 类">
    创建 `app/Boost/MyAgent.php`。

    ```php theme={null}
    <?php

    declare(strict_types=1);

    namespace App\Boost;

    use Laravel\Boost\Contracts\SupportsGuidelines;
    use Laravel\Boost\Contracts\SupportsMcp;
    use Laravel\Boost\Contracts\SupportsSkills;
    use Laravel\Boost\Install\Agents\Agent;
    use Laravel\Boost\Install\Enums\McpInstallationStrategy;
    use Laravel\Boost\Install\Enums\Platform;

    class MyAgent extends Agent implements SupportsGuidelines, SupportsMcp, SupportsSkills
    {
        public function name(): string
        {
            return 'my_agent';
        }

        public function displayName(): string
        {
            return 'MyAgent';
        }

        public function systemDetectionConfig(Platform $platform): array
        {
            return match ($platform) {
                Platform::Darwin, Platform::Linux => [
                    'command' => 'command -v myagent',
                ],
                Platform::Windows => [
                    'command' => 'cmd /c where myagent 2>nul',
                ],
            };
        }

        public function projectDetectionConfig(): array
        {
            return [
                'files' => ['.myagent.json'],
            ];
        }

        // --- SupportsGuidelines ---

        public function guidelinesPath(): string
        {
            return 'MYAGENT.md';
        }

        // frontmatter() 使用 Agent 基类默认（false）
        // transformGuidelines() 也使用基类默认（原样返回）

        // --- SupportsMcp ---

        // useAbsolutePathForMcp()、getPhpPath()、getArtisanPath()、
        // installMcp()、installHttpMcp() 都由 Agent 基类实现

        public function mcpInstallationStrategy(): McpInstallationStrategy
        {
            return McpInstallationStrategy::FILE;
        }

        public function mcpConfigPath(): string
        {
            return '.myagent.json';
        }

        // --- SupportsSkills ---

        public function skillsPath(): string
        {
            return '.myagent/skills';
        }
    }
    ```

    <Info>
      `systemDetectionConfig()` 与 `projectDetectionConfig()` 用于 Boost 在系统与项目中自动检测 Agent。执行 `boost:install` 时会自动把匹配的 Agent 显示为候选。
    </Info>
  </Step>

  <Step title="注册 Agent">
    在 `App\Providers\AppServiceProvider` 的 `boot` 方法中注册自定义 Agent。

    ```php theme={null}
    <?php

    namespace App\Providers;

    use App\Boost\MyAgent;
    use Illuminate\Support\ServiceProvider;
    use Laravel\Boost\Boost;

    class AppServiceProvider extends ServiceProvider
    {
        public function boot(): void
        {
            Boost::registerAgent('my_agent', MyAgent::class);
        }
    }
    ```

    注册后执行 `php artisan boost:install`，MyAgent 就会出现在选项中。
  </Step>

  <Step title="验证">
    ```shell theme={null}
    php artisan boost:install
    ```

    在选择安装目标 Agent 的界面会显示 MyAgent。选择后会生成 `MYAGENT.md`、`.myagent.json` 与 `.myagent/skills/`。
  </Step>
</Steps>

## 指南的自定义

### guidelinesPath 的设置

不同 Agent 读取指南文件的位置不同。

```php theme={null}
// 作为单文件输出时
public function guidelinesPath(): string
{
    return 'MYAGENT.md';
}
```

若允许通过配置文件覆盖，会更灵活。

```php theme={null}
public function guidelinesPath(): string
{
    return config('boost.agents.my_agent.guidelines_path', 'MYAGENT.md');
}
```

### 需要 frontmatter 的 Agent

对于像 Cursor 的 `.cursor/rules/*.mdc` 这种需要 frontmatter 的格式，让 `frontmatter()` 返回 `true`。

```php theme={null}
public function frontmatter(): bool
{
    return true;
}
```

### 指南的后处理

可以使用 `transformGuidelines()` 加工生成后的 Markdown。

```php theme={null}
public function transformGuidelines(string $markdown): string
{
    // 添加 Agent 专属头部
    $header = "<!-- Generated by Laravel Boost for MyAgent -->\n\n";

    return $header . $markdown;
}
```

## 添加自定义 AI 指南

要向 Boost 的指南中追加项目特有的规则，可以把 Blade 文件放入 `.ai/guidelines/` 目录。

```
.ai/
└── guidelines/
    ├── my-domain-rules.blade.php
    └── coding-standards.blade.php
```

示例文件：

```php theme={null}
## 项目专属规则

本项目遵循以下约定：

- 模型必须放置在 `App\Models\` 命名空间下
- 所有 API 端点都创建在 `App\Http\Controllers\Api\` 之下
- 数据库事务使用 `DB::transaction()` 并封装在 Service 类内部

@verbatim
<code-snippet name="Service 类中的事务示例" lang="php">
DB::transaction(function () use ($data) {
    $order = Order::create($data);
    $order->items()->createMany($data['items']);
    event(new OrderCreated($order));
});
</code-snippet>
@endverbatim
```

执行 `boost:install` 后，这些指南会自动与 Boost 内置指南合并输出。

### 覆盖内置指南

若把自定义文件放在与 Boost 内置指南相同的路径下，将优先使用你的文件。

```
# 覆盖 Boost 的 "Inertia React v2 Form Guidance"
.ai/guidelines/inertia-react/2/forms.blade.php
```

## 添加自定义 Skill

### 创建 SKILL.md

在 `.ai/skills/{Skill 名}/SKILL.md` 中定义 Skill。

```
.ai/
└── skills/
    └── creating-invoices/
        └── SKILL.md
```

`SKILL.md` 由 YAML frontmatter 与 Markdown 指令构成。

````markdown theme={null}
---
name: creating-invoices
description: 实现发票（Invoice）的创建、更新、发送相关处理时使用的 Skill。
---

# 发票创建 Skill

## 何时使用此 Skill

用于实现发票模型创建、发票 PDF 生成、邮件发送等场景。

## 文件结构

- `app/Models/Invoice.php` — 发票模型
- `app/Services/InvoiceService.php` — 业务逻辑
- `app/Jobs/SendInvoiceEmail.php` — 邮件发送 Job

## 实现模式

### 创建发票

```php
// $items 是从 Controller 或其他 Service 传入的数组
$invoice = InvoiceService::create([
    'user_id' => $user->id,
    'items' => $items,
    'due_date' => now()->addDays(30),
]);
````

### 生成发票 PDF

PDF 通过 `barryvdh/laravel-dompdf` 生成：

```php theme={null}
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Storage;

$pdf = Pdf::loadView('invoices.pdf', ['invoice' => $invoice]);
Storage::put("invoices/{$invoice->id}.pdf", $pdf->output());
```

<Tip>
  Skill 的设计理念是「按需加载」。将始终需要的信息放在指南中，任务专属的详细模式放在 Skill 中，可以优化 AI 的上下文使用。
</Tip>

### 覆盖内置 Skill

如果使用与 Boost 内置 Skill 相同名字创建自定义 Skill，将覆盖内置版本。

```
# 自定义 livewire-development Skill
.ai/skills/livewire-development/SKILL.md
```

## 为第三方包添加 Boost 支持

要为自己的包添加 Boost 支持，将配置文件放到包的 `resources/boost/` 目录下即可。

### 添加指南

```
resources/
└── boost/
    └── guidelines/
        └── core.blade.php
```

```php theme={null}
## MyPackage

本包提供 [功能概述]。

### 基本用法

@verbatim
<code-snippet name="MyPackage 的初始化" lang="php">
$result = MyPackage::create([
    'option' => 'value',
]);
</code-snippet>
@endverbatim
```

### 添加 Skill

```
resources/
└── boost/
    └── skills/
        └── mypackage-development/
            └── SKILL.md
```

```markdown theme={null}
---
name: mypackage-development
description: 使用 MyPackage 功能实现时使用的 Skill。
---

# MyPackage Development

## 何时使用此 Skill
在使用 MyPackage 实现功能时使用。

## 主要功能

- 功能 1：...
- 功能 2：...
```

当包用户执行 `php artisan boost:install` 时，这些指南与 Skill 会自动被检测并展示为可安装对象。

## 实战示例：面向自研 CI/CD Agent 的自定义 Agent

下面是嵌入公司 CI/CD 流水线的虚构 Agent「PipelineAgent」的完整实现示例。该 Agent 仅支持指南，不支持 MCP 与 Skill。

```php theme={null}
<?php

declare(strict_types=1);

namespace App\Boost;

use Laravel\Boost\Contracts\SupportsGuidelines;
use Laravel\Boost\Install\Agents\Agent;
use Laravel\Boost\Install\Enums\Platform;

class PipelineAgent extends Agent implements SupportsGuidelines
{
    public function name(): string
    {
        return 'pipeline_agent';
    }

    public function displayName(): string
    {
        return 'Pipeline Agent (CI/CD)';
    }

    public function systemDetectionConfig(Platform $platform): array
    {
        // 通过 CI 环境变量检测存在性
        return [
            'command' => match ($platform) {
                Platform::Windows => 'cmd /c echo %CI_AGENT_VERSION% 2>nul',
                default => 'echo $CI_AGENT_VERSION',
            },
        ];
    }

    public function projectDetectionConfig(): array
    {
        // 通过项目根的配置文件检测
        return [
            'files' => ['.pipeline-agent.yml'],
        ];
    }

    public function guidelinesPath(): string
    {
        // CI/CD Agent 读取规则的路径
        return '.pipeline/CODING_GUIDELINES.md';
    }

    public function frontmatter(): bool
    {
        return false;
    }

    public function transformGuidelines(string $markdown): string
    {
        // 添加流水线元数据头
        $timestamp = now()->toIso8601String();

        return "<!-- Generated by Laravel Boost at {$timestamp} -->\n\n{$markdown}";
    }
}
```

在 `AppServiceProvider` 中注册：

```php theme={null}
use App\Boost\PipelineAgent;
use Laravel\Boost\Boost;

public function boot(): void
{
    Boost::registerAgent('pipeline_agent', PipelineAgent::class);
}
```

在 CI 环境中可以通过下面的命令只生成指南：

```shell theme={null}
php artisan boost:install --agent=pipeline_agent
```

## 参考链接

<Card title="ClaudeCode.php — 官方实现示例" icon="github" href="https://github.com/laravel/boost/blob/main/src/Install/Agents/ClaudeCode.php">
  可从源码查看随 Boost 附带的 ClaudeCode Agent 的完整实现。
</Card>

<Card title="Agent Skills" icon="book" href="https://agentskills.io/what-are-skills">
  可参考 SKILL.md 的格式规范与最佳实践。
</Card>

<Card title="Laravel Boost Custom Agent for GitHub Copilot CLI" icon="github" href="/zh/packages/laravel-boost-copilot-cli">
  同时支持 Copilot CLI 与 Testbench 的公开包实现示例
</Card>

<Card title="Laravel Boost Custom Agent for PhpStorm with GitHub Copilot" icon="github" href="/zh/packages/laravel-boost-phpstorm-copilot">
  面向 PhpStorm GitHub Copilot 插件的公开包实现示例
</Card>


## Related topics

- [创建 AI SDK 的自定义 Provider](/zh/advanced/ai-sdk-custom-provider.md)
- [Laravel Boost](/zh/boost.md)
- [自定义代理](/zh/packages/laravel-copilot-sdk/custom-agents.md)
- [限流的自定义](/zh/advanced/rate-limiting.md)
- [Labeler](/zh/packages/laravel-bluesky/labeler.md)
