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

# Laravel AI Agent 支援 MCP 伺服器

> 解說 Laravel AI SDK 與 Laravel MCP 新增的 MCP 用戶端功能。現在可將 MCP 伺服器的 tool 原封不動地整合到 Agent 的 tools() 內。

## 概觀

2026 年 6 月，[Laravel 官方部落格](https://laravel.com/blog/laravel-ai-agents-now-support-mcp-servers)發佈了以 Laravel AI SDK 建構的 AI Agent 可連接 **MCP（Model Context Protocol）伺服器**的消息。

過去 Laravel MCP 提供的是「將 Laravel 應用**作為 MCP 伺服器**公開」的功能，這次新增的是反向功能，也就是「讓 Laravel 應用**作為 MCP 用戶端**連接其他 MCP 伺服器」。

<Info>
  MCP 本身的詳細機制請參考 [Laravel MCP 文件](https://laravel.com/docs/mcp)。本頁只聚焦於用戶端功能。
</Info>

## 為何實作在 Laravel MCP 而不是 AI SDK 本體

MCP 是一個涵蓋傳輸協商、handshake、認證流程等廣泛範圍的協定。若直接實作在 AI SDK 內，就無法在不透過 Agent 而想與 MCP 伺服器通訊的場景（例如佇列 Job 或 Console 指令）中重用。

因此 Laravel 團隊將功能分成兩個部分。

```mermaid theme={null}
graph LR
    A["laravel/mcp<br>MCP 用戶端"] --> B["連線、認證、handshake"]
    C["laravel/ai<br>薄整合層"] --> D["把 MCP tool 原封不動<br>加入 Agent 的 tools()"]
    A --> C
```

* **`laravel/mcp`**：負責連線、協商、認證與 tool 呼叫的 MCP 用戶端本體
* **`laravel/ai`**：讓 Agent 能自然地從 `tools()` 使用該用戶端的薄整合層

兩者可單獨使用，組合後就能讓 Agent 使用 MCP 伺服器的 tool，操作方式和手寫 tool 一模一樣。

## 連接到 MCP 伺服器

同時支援以本機 process 啟動的 STDIO 伺服器，以及透過 HTTP 的遠端伺服器。

```php theme={null}
use Laravel\Mcp\Client;

// 本機伺服器（STDIO）
$client = Client::local('npx', ['-y', '@modelcontextprotocol/puppeteer']);
$tools = $client->tools();

// 遠端伺服器（Streamable HTTP）
$client = Client::web('https://nightwatch.laravel.com/mcp');
$tools = $client->tools();
```

連線、handshake、協定版本協商全部由用戶端處理，應用端只要呼叫 `tools()` 即可。

## 認證

### Bearer Token

```php theme={null}
$tools = Client::web('https://mcp.example.com')
    ->withToken($token)
    ->tools();
```

### OAuth

包含 Nightwatch 在內許多託管的 MCP 伺服器需要 OAuth。在 Service Provider 註冊具名用戶端。

```php theme={null}
use Laravel\Mcp\Client;
use Laravel\Mcp\Facades\Mcp;

Mcp::registerClient('nightwatch', fn () =>
    Client::web('https://nightwatch.laravel.com/mcp')->withOAuth()
);
```

接著配置 OAuth 路由與 callback 處理。

```php theme={null}
use Laravel\Mcp\Facades\Mcp;
use Laravel\Mcp\Client\OAuth\TokenSet;

Mcp::oAuthRoutesFor('nightwatch', function (string $provider, TokenSet $token) {
    auth()->user()->update([
        'mcp_nightwatch_token' => encrypt($token->accessToken),
        'mcp_nightwatch_refresh' => encrypt($token->refreshToken),
    ]);

    return redirect('/dashboard');
}, middleware: 'auth');
```

這樣會產生 `mcp.oauth.nightwatch.connect` 與對應的 callback 路由。在 Blade 側只需放上連線按鈕。

```blade theme={null}
<a href="{{ route('mcp.oauth.nightwatch.connect') }}">
    Connect Nightwatch
</a>
```

使用者登入並同意授權後，callback closure 就會收到 token。你不需要自己處理重新導向 URL 與 PKCE 細節。

對於沒有使用者介入的背景處理，也提供 Client Credentials Grant。

```php theme={null}
$token = Mcp::client('billing')->oAuthClient()->clientCredentials();
```

## 整合到 Agent 中

最大的重點是：不需要修改 Agent 的 `tools()` 方法就能混入 MCP tool。

```php theme={null}
use Laravel\Mcp\Facades\Mcp;
use App\Tools\SendSlackMessage;

class SupportAgent extends Agent
{
    public function instructions(): string
    {
        return 'You help triage production issues.';
    }

    public function tools(): array
    {
        return [
            ...Mcp::client('nightwatch')
                ->withToken(auth()->user()->mcp_nightwatch_token)
                ->tools(),
            new SendSlackMessage,
        ];
    }
}
```

Laravel AI 會偵測 `tools()` 陣列內是否有 MCP tool，並包裝成符合 Agent 的 tool 契約。它會把 MCP 的輸入 schema 轉為 Laravel 的 JSON schema，當模型呼叫 tool 時發起遠端呼叫並將結果正規化後回傳。錯誤、結構化資料、純文字、串流更新皆自動處理，MCP 的細節不會滲入 Agent 側程式碼。

也可以在一個 Agent 中混用多種傳輸方式。

```php theme={null}
public function tools(): array
{
    return [
        ...Mcp::client('nightwatch')->tools(),
        ...Client::local('npx', ['-y', '@modelcontextprotocol/server-puppeteer'])->tools(),
        new SendSlackMessage,
    ];
}
```

此外，為自己的 Laravel MCP 伺服器撰寫的 tool 類別，可以不透過用戶端連線就直接交給 Agent。也就是同一組 tool 可同時用於對外公開與 Agent 使用。

```php theme={null}
use App\Mcp\Tools\CurrentWeatherTool;

public function tools(): array
{
    return [
        new CurrentWeatherTool,
        new SendSlackMessage,
    ];
}
```

## 快取 Tool 清單

取得 tool 清單需要一趟往返伺服器。特別是走 OAuth 的遠端伺服器，每次 prompt 都呼叫就是浪費。由於 tool 清單不常變更，很適合作為快取對象。

```php theme={null}
public function tools(): array
{
    $tools = Cache::remember('mcp.nightwatch.tools', now()->addHour(), fn () =>
        Mcp::client('nightwatch')->tools()
    );

    return [...$tools, new SendSlackMessage];
}
```

MCP tool 會以純資料回傳，從快取還原後也能直接運作。

## 測試

就算沒有實際運作中的 MCP 伺服器，也能用 Laravel AI 的 fake 功能測試 Agent。MCP tool 名稱遵循 `mcp_tools_<name>` 的命名慣例，因此名為 `search` 的 tool 會以 `mcp_tools_search` 出現。

```php theme={null}
use Laravel\Ai\Responses\Data\ToolCall;

SupportAgent::fake([
    new ToolCall('call_1', 'mcp_tools_search', ['query' => 'laravel']),
    'Found the issue.',
]);

$response = (new SupportAgent)->prompt('Find the latest error');

expect($response->toolCalls)->toHaveCount(1);
expect($response->toolResults->first()->result)->toContain('Found');
```

Agent 的一般迴圈會照樣執行，只有模型的發言由 fake 決定。tool 呼叫本身仍實際通過 MCP 層，因此不需要網路也能測試與正式環境相同的路徑。

## 目前支援的範圍

此首發版本在 STDIO 與 Streamable HTTP 兩種傳輸方式下支援 tool 與 prompt。認證方面支援 Bearer Token 與 OAuth。隨著 MCP 自身發展，支援範圍預計持續擴大。

## 相關頁面

<CardGroup cols={2}>
  <Card title="打造 AI SDK 的自訂 Provider" href="/zh-TW/advanced/ai-sdk-custom-provider" icon="plug">
    介紹對應非內建 AI 服務的自訂 Provider 實作方式
  </Card>

  <Card title="Laravel Nightwatch 入門" href="/zh-TW/blog/nightwatch-introduction" icon="binoculars">
    解說本文範例中使用的託管監控服務 Nightwatch
  </Card>
</CardGroup>


## Related topics

- [2026 年 6 月 Laravel 更新](/zh-TW/blog/changelog/202606.md)
- [用 Laravel 構建 MCP 伺服器](/zh-TW/advanced/mcp-server.md)
- [建立 Boost 的自定義 Agent](/zh-TW/advanced/boost-custom-agent.md)
- [Laravel MCP](/zh-TW/mcp.md)
- [laravel/agent-skills — Laravel 官方 AI Agent 技能集](/zh-TW/blog/agent-skills-introduction.md)
