AllenYU
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 【Laravel MCP 權威實戰指南】Ep.4:邁向 Production!Web Server 部署、認證與自動化測試 歡迎來到【Laravel MCP 權威實戰指南】系列的最終回! 在前三集裡,我們成功在本地端 (Local) 建立了一個強大的 MCP Server,讓 AI 可以透過 Cursor 等 IDE 直接存取專案的 Tools、Resources 與 Prompts。這對於我們「自己開發專案」來說已經非常無敵了。 但是,**如果我們想把這個 AI 擴充包上線到 Production 呢?** 假設你今天開發了一個 SaaS 服務,你想讓第三方 AI 平台(如 ChatGPT 企業版、Claude 的遠端 Agent)也能夠以 API 的形式串接你的 Laravel 應用,該怎麼做?此時走本機的 CLI 就不管用了,我們必須把 Server 暴露成一個 **Web 端點 (HTTP Endpoint)**。 一旦開放成 Web 端點,**「安全性」**就成了生死攸關的課題。AI 如果拿到權限,會不會不小心刪掉別人的資料? 在這篇 Ep.4 的最終章,我們將帶你一步步將 MCP Server 部署上線,加上企業級的安全認證 (Authentication) 與授權控管 (Authorization),並學會如何為這些 AI 武器撰寫單元測試! --- ## 🌐 第一部:從 Local 走向 Web (註冊 Web Server) 在 Ep.1 中,我們是這樣註冊 Local Server 的: ```php // routes/ai.php Mcp::local('todo', TodoServer::class); ``` 現在,我們要把它轉換成能接收 HTTP POST 請求的 Web Server,這在 Laravel MCP 中簡單到不可思議。你只需要把 `local` 換成 `web`,並指定一個路由路徑: ```php // routes/ai.php use App\Mcp\Servers\TodoServer; use Laravel\Mcp\Facades\Mcp; // 將 MCP Server 註冊為 HTTP 端點 Mcp::web('/mcp/todo', TodoServer::class); ``` 就這樣!你的 Laravel 應用現在已經可以在 `https://your-app.com/mcp/todo` 接收來自全世界 AI Agent 的請求了。 > 💡 與普通的 API 路由一樣,你可以直接鏈式呼叫 `->middleware()` 來限制 AI 呼叫的頻率,避免 AI 暴走把你的伺服器資源吃光: > ```php > Mcp::web('/mcp/todo', TodoServer::class) > ->middleware(['throttle:mcp']); > ``` --- ## 🔒 第二部:堅不可摧的防線 (認證與授權) 一旦端點公開,我們絕不能讓任何人(或任何 AI)都能隨意呼叫。我們需要確認「這個 AI 是代表誰在操作系統?」 ### 1. 身份認證 (Authentication):整合 Sanctum 或 OAuth Laravel MCP 可以無縫整合你現有的認證系統。如果你是建立第一方 AI 客戶端,你可以直接掛上 Laravel Sanctum 的 Middleware: ```php // routes/ai.php Mcp::web('/mcp/todo', TodoServer::class) ->middleware(['auth:sanctum']); // 👈 加上這行,瞬間擁有 Token 防護! ``` 如果你的 AI Agent 是第三方服務,想要代表使用者存取資料,官方也非常推薦使用 **OAuth 2.1** 來核發存取權杖 (Access Token)。Laravel MCP 提供了 `Mcp::oauthRoutes()` 來快速掛載 OAuth 端點: ```php // routes/ai.php use Laravel\Mcp\Facades\Mcp; Mcp::oauthRoutes(); Mcp::web('/mcp/todo', TodoServer::class) ->middleware(['auth:api']); ``` ### 2. 授權控管 (Authorization):結合 Policy 與 Gate 認證只是確認了「你是誰」,但「你能做什麼」才是重點! 假設 AI 幫使用者呼叫了 `DeleteTodoTool`,我們必須確保該使用者**只能刪除自己的任務**。在 Tool 的 `handle` 方法中,你可以直接使用 Laravel 最熟悉的 `Gate::authorize()`: ```php namespace App\Mcp\Tools; use App\Models\Todo; use Illuminate\Support\Facades\Gate; use Laravel\Mcp\Request; use Laravel\Mcp\Response; use Laravel\Mcp\Server\Tool; class DeleteTodoTool extends Tool { public function handle(Request $request): Response { // 1. 驗證參數格式 $validated = $request->validate([ 'todo_id' => 'required|integer|exists:todos,id', ], [ 'todo_id.required' => '你必須提供要刪除的 todo_id。', 'todo_id.exists' => '找不到這筆待辦事項,請確認 ID 是否正確。', ]); $todo = Todo::findOrFail($validated['todo_id']); // 2. 🔐 核心防線:檢查當前使用者是否有權限刪除這筆資料! Gate::authorize('delete', $todo); $todo->delete(); return Response::text("任務 #{$todo->id} 已經成功刪除。"); } } ``` **這就是 `laravel/mcp` 最迷人的地方!** 它沒有發明任何新的權限機制,而是讓你把這幾年學到的 Laravel 技巧(Sanctum、Gates、Policies)100% 應用在 AI 開發上,毫無學習成本。 --- ## 🧪 第三部:專業開發者的浪漫 (測試與除錯) 上線前,如果不測試一下,心裡總是不踏實。Laravel MCP 提供了兩種完整的測試體驗: ### 1. 視覺化除錯:MCP Inspector 在開發階段,如果你不想每次都打開 Cursor 進行盲測,可以使用官方內建的 **MCP Inspector**。只需要一行 Artisan 指令就能啟動: ```bash # 測試 Web Server php artisan mcp:inspector mcp/todo # 測試 Local Server(用 server 名稱) php artisan mcp:inspector todo ``` Inspector 會啟動一個互動式 Web 介面,讓你可以手動觸發 Tools、瀏覽 Resources,並確認 Schema 的輸出是否符合預期。如果你的 Web Server 掛了 Sanctum 認證,記得在連接時帶上 `Authorization: Bearer <token>` 標頭。 ### 2. 單元測試 (Unit Tests):用 Pest 守護邏輯 Laravel MCP 提供了非常直覺的測試 API。你可以透過 `ServerClass::tool()` 靜態方法直接呼叫指定 Tool,框架會幫你處理好所有的 Request 建構細節,並回傳一個可以鏈式斷言的 Response 物件: ```php // tests/Feature/Mcp/Tools/DeleteTodoToolTest.php use App\Mcp\Servers\TodoServer; use App\Mcp\Tools\DeleteTodoTool; use App\Models\Todo; use App\Models\User; test('AI 可以成功刪除自己的 Todo', function () { $user = User::factory()->create(); $todo = Todo::factory()->for($user)->create(); $this->actingAs($user); $response = TodoServer::tool(DeleteTodoTool::class, [ 'todo_id' => $todo->id, ]); $response->assertOk() ->assertSee("任務 #{$todo->id} 已經成功刪除"); $this->assertDatabaseMissing('todos', ['id' => $todo->id]); }); test('AI 傳入錯誤的 todo_id 時會收到明確的錯誤訊息', function () { $user = User::factory()->create(); $this->actingAs($user); $response = TodoServer::tool(DeleteTodoTool::class, [ 'todo_id' => 99999, // 不存在的 ID ]); $response->assertHasErrors(['找不到這筆待辦事項,請確認 ID 是否正確。']); }); ``` 為你的破壞性 Tools(如新增、修改、刪除)寫好測試,是你將 MCP Server 推向 Production 時最大的定心丸! --- ## 🏆 系列總結:迎接 Agentic Development 的大航海時代 經過這四篇文章的洗禮,你已經從一個傳統的 Backend Developer,正式升級為具備 **Agentic Development (AI 代理開發)** 能力的先驅者了! 讓我們快速回顧你的新武器庫: - **Ep.1**:搭建基礎的 MCP Server 與 Tools,並在本地與 IDE 完美串接。 - **Ep.2**:利用 Input/Output Schemas 與 Validation,引導 AI 做出精準且安全的操作。 - **Ep.3**:開放 Resources 給 AI 閱讀上下文,並透過 Prompts 標準化 AI 的工作流程。 - **Ep.4**:將一切化為 Web 端點,掛上 Sanctum 認證、Policy 授權,並寫下堅固的自動化測試。 Anthropic 推出 MCP 協定,而 Laravel 官方光速支援 `laravel/mcp` 套件,這意味著 **「AI 不再只是幫我們寫 Code 的工具,它將成為我們系統中的超級使用者」**。 未來的 SaaS 系統,競爭力將取決於「誰的系統對 AI 更友善、誰暴露了更有價值的 Tools 給 AI 代理」。而身為 Laravel 開發者的你,現在已經站在了最前線。 打開你的終端機,開始為你的專案打造專屬的大腦擴充包吧!Happy Coding!🚀 --- > 📚 **參考資料**:[Laravel MCP 官方文件](https://laravel.com/docs/12.x/mcp)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully