> ## 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-TW/packages/laravel-boost-copilot-cli">
  同時支援 Copilot CLI 與 Testbench 的公開包實現示例
</Card>

<Card title="Laravel Boost Custom Agent for PhpStorm with GitHub Copilot" icon="github" href="/zh-TW/packages/laravel-boost-phpstorm-copilot">
  面向 PhpStorm GitHub Copilot 外掛的公開包實現示例
</Card>


## Related topics

- [建立 AI SDK 的自定義 Provider](/zh-TW/advanced/ai-sdk-custom-provider.md)
- [進階主題](/zh-TW/advanced/index.md)
- [Laravel Boost Custom Agent for GitHub Copilot CLI](/zh-TW/packages/laravel-boost-copilot-cli.md)
- [进阶主题](/zh-CN/advanced/index.md)
- [Laravel Boost Custom Agent for PhpStorm with GitHub Copilot](/zh-TW/packages/laravel-boost-phpstorm-copilot.md)
