前言

🎯 你將學到什麼 ✅ 先決條件 🤖 Copilot 家族 📚 課程結構 📋 指令參考
GitHub Copilot CLI 入門
✨ 學習使用 AI 驅動的命令列輔助工具,大幅提升你的開發工作流程。
GitHub Copilot CLI 將 AI 輔助功能直接帶入你的終端機 (terminal)。你不必切換到瀏覽器或程式碼編輯器,就能直接在命令列中提問、產生完整功能的應用程式、審查程式碼、產生測試,以及除錯問題。
可以把它想像成一位隨時待命的資深同事,能閱讀你的程式碼、解釋令人困惑的模式,並幫助你更快完成工作!
📘 偏好網頁體驗? 你可以直接在 GitHub 上閱讀本課程,也可以在 Awesome Copilot 上以更傳統的瀏覽體驗來檢視。
本課程適合以下對象:
- 軟體開發人員——想要從命令列使用 AI
- 終端機使用者——偏好鍵盤驅動的工作流程,而非 IDE 整合
- 希望建立標準化 AI 輔助程式碼審查與開發實踐的團隊
🎯 你將學到什麼
這門實作課程將帶你從零開始,熟練使用 GitHub Copilot CLI。你將在所有章節中使用同一個 Python 書籍收藏應用程式,透過 AI 輔助的工作流程逐步改善它。課程結束後,你將能自信地使用 AI 來審查程式碼、產生測試、除錯問題,以及自動化工作流程——全部在終端機中完成。
不需要 AI 經驗。 只要你會使用終端機,就能學會這些。
適合: 開發人員、學生,以及任何具有軟體開發經驗的人。
✅ 先決條件
開始之前,請確認你具備以下條件:
🤖 認識 GitHub Copilot 家族
GitHub Copilot 已發展為一系列 AI 驅動的工具。以下是各產品的運作環境:
| 產品 | 運作環境 | 說明 |
|---|---|---|
| GitHub Copilot CLI<br>(本課程) | 你的終端機 | 終端機原生的 AI 程式碼助手 |
| GitHub Copilot | VS Code、Visual Studio、JetBrains 等 | Agent 模式、聊天、行內建議 |
| Copilot on GitHub.com | GitHub | 關於你的 repo 的沉浸式聊天、建立 agent 等功能 |
| GitHub Copilot cloud agent | GitHub | 將 issue 指派給 agent,取得 PR 回覆 |
本課程聚焦於 GitHub Copilot CLI,將 AI 輔助功能直接帶入你的終端機。
📚 課程結構

| 章節 | 標題 | 你將建構的內容 |
|---|---|---|
| 00 | 🚀 快速入門 | 安裝與驗證 |
| 01 | 👋 初體驗 | 實際示範 + 三種互動模式 |
| 02 | 🔍 上下文與對話 | 多檔案專案分析 |
| 03 | ⚡ 開發工作流程 | 程式碼審查、除錯、測試產生 |
| 04 | 🤖 建立專業化 AI 助手 | 為你的工作流程自訂 agent |
| 05 | 🛠️ 自動化重複性任務 | 自動載入的 skill |
| 06 | 🔌 連接 GitHub、資料庫與 API | MCP 伺服器整合 |
| 07 | 🎯 綜合應用 | 完整的功能開發工作流程 |
📖 本課程的運作方式
每個章節都遵循相同的模式:
- 真實世界類比:透過熟悉的比喻來理解概念
- 核心概念:學習基礎知識
- 實作範例:執行實際指令並查看結果
- 作業:練習你所學到的內容
- 下一步:預覽下一章節
程式碼範例皆可執行。 本課程中每段 copilot 文字區塊都可以複製並在終端機中執行。
📋 GitHub Copilot CLI 指令參考
GitHub Copilot CLI 指令參考幫助你找到指令與快捷鍵,讓你更有效率地使用 Copilot CLI。
🙋 取得協助
- 🐛 發現錯誤? 提交 Issue
- 🤝 想要貢獻? 歡迎提交 PR!
- 📚 官方文件: GitHub Copilot CLI 文件
授權條款
本專案採用 MIT 開放原始碼授權條款。完整條款請參閱 LICENSE 檔案。
第零章 快速入門

歡迎!在本章中,你將安裝 GitHub Copilot CLI(命令列介面)、使用 GitHub 帳號登入,並驗證一切正常運作。這是一個快速設定章節。一旦準備就緒,真正的示範將從第 01 章開始!
🎯 學習目標
完成本章後,你將:
- 安裝好 GitHub Copilot CLI
- 使用 GitHub 帳號登入
- 透過簡單測試驗證其運作
⏱️ 預估時間:約 10 分鐘(5 分鐘閱讀 + 5 分鐘實作)
✅ 前置需求
- 擁有 Copilot 存取權限的 GitHub 帳號。查看訂閱方案。學生與教師可透過 GitHub Education 免費使用 Copilot Pro。
- 終端機基礎操作:熟悉
cd和ls等指令
「Copilot 存取權限」是什麼意思
GitHub Copilot CLI 需要有效的 Copilot 訂閱。你可以在 github.com/settings/copilot 查看你的狀態。你應該會看到以下其中一種:
- Copilot Individual — 個人訂閱
- Copilot Business — 透過你的組織
- Copilot Enterprise — 透過你的企業
- GitHub Education — 經驗證的學生/教師免費使用
如果你看到「You don't have access to GitHub Copilot」,你需要使用免費方案、訂閱付費方案,或加入提供存取權限的組織。
安裝
⏱️ 時間預估:安裝需要 2-5 分鐘。驗證身分另需 1-2 分鐘。
GitHub Codespaces(零設定)
如果你不想安裝任何前置需求,可以使用 GitHub Codespaces,它已預裝好 GitHub Copilot CLI(你仍需登入),並預先安裝了 Python 和 pytest。
- 將此 repo 進行 Fork 到你的 GitHub 帳號
- 選擇 Code > Codespaces > Create codespace on main
- 等待幾分鐘讓容器建置完成
- 準備就緒!終端機會在 Codespace 環境中自動開啟。
💡 在 Codespace 中驗證:執行
cd samples/book-app-project && python book_app.py help以確認 Python 和範例應用程式正常運作。
本機安裝
如果你想在本機上搭配課程範例執行 Copilot CLI,請依照以下步驟操作。
- 複製 repo 以取得課程範例到你的電腦:
```bash
git clone https://github.com/github/copilot-cli-for-beginners
cd copilot-cli-for-beginners
```
- 使用以下其中一種方式安裝 Copilot CLI。
💡 不確定選哪個? 如果你已安裝 Node.js,請使用
npm。否則,選擇符合你系統的選項。
所有平台(npm)
```bash
如果你已安裝 Node.js,這是取得 CLI 的快速方式
npm install -g @github/copilot
```
macOS/Linux(Homebrew)
```bash
brew install copilot-cli
```
Windows(WinGet)
```bash
winget install GitHub.Copilot
```
macOS/Linux(安裝腳本)
```bash
curl -fsSL https://gh.io/copilot-install | bash
```
驗證身分
在 copilot-cli-for-beginners repo 根目錄開啟終端機視窗,啟動 CLI 並允許存取該資料夾。
copilot
系統會詢問你是否信任包含 repo 的資料夾(如果你尚未信任過的話)。你可以選擇僅信任一次,或在所有未來的 session(工作階段)中信任。
信任資料夾後,你可以使用 GitHub 帳號登入。
> /login
接下來會發生什麼:
- Copilot CLI 顯示一組一次性驗證碼(如
ABCD-1234) - 瀏覽器會開啟 GitHub 的裝置授權頁面。如果尚未登入 GitHub,請先登入。
- 在提示時輸入該驗證碼
- 選擇「Authorize」以授權 GitHub Copilot CLI 存取
- 回到終端機——你已成功登入!
裝置授權流程:終端機產生一組驗證碼,你在瀏覽器中驗證,Copilot CLI 即完成驗證。
提示:登入狀態會跨 session 持續保留。除非 token(權杖)過期或你主動登出,否則只需執行一次。
驗證是否正常運作
步驟 1:測試 Copilot CLI
既然你已經登入,讓我們驗證 Copilot CLI 是否正常運作。在終端機中,如果尚未啟動 CLI 請先啟動:
> Say hello and tell me what you can help with
收到回應後,你可以退出 CLI:
> /exit
🎬 看看實際操作!

示範輸出會因人而異。你的模型、工具和回應會與此處顯示的不同。
預期輸出:一段友善的回應,列出 Copilot CLI 的功能。
步驟 2:執行範例書籍應用程式
本課程提供一個範例應用程式,你將在整個課程中使用 CLI 來探索和改進它(你可以在 /samples/book-app-project 查看程式碼)。在開始之前,請確認 Python 書籍收藏終端機應用程式可以正常運作。根據你的系統執行 python 或 python3。
注意: 整個課程中主要使用的範例是 Python(
samples/book-app-project),因此如果你選擇本機安裝,需要在本機上安裝 Python 3.10+(Codespace 已預先安裝)。也提供 JavaScript(samples/book-app-project-js)和 C#(samples/book-app-project-cs)版本,如果你偏好使用這些語言的話。每個範例都有 README 說明如何以該語言執行應用程式。
cd samples/book-app-project
python book_app.py list
預期輸出:一份包含 5 本書的清單,包括「The Hobbit」、「1984」和「Dune」。
步驟 3:使用 Copilot CLI 搭配書籍應用程式
如果你執行了步驟 2,請先導覽回 repo 根目錄:
cd ../.. # 如有需要,返回 repo 根目錄
copilot
> What does @samples/book-app-project/book_app.py do?
預期輸出:書籍應用程式主要功能和指令的摘要。
如果你看到錯誤訊息,請查看下方的疑難排解章節。
完成後,你可以退出 Copilot CLI:
> /exit
✅ 準備就緒!
安裝到此結束。真正的樂趣從第 01 章開始,屆時你將:
- 觀看 AI 審查書籍應用程式並即時發現程式碼品質問題
- 學習三種不同的 Copilot CLI 使用方式
- 從自然語言產生可運作的程式碼
<a id="troubleshooting"></a>疑難排解
「copilot: command not found」
CLI 尚未安裝。請嘗試其他安裝方式:
# 如果 brew 失敗,請嘗試 npm:
npm install -g @github/copilot
# 或使用安裝腳本:
curl -fsSL https://gh.io/copilot-install | bash
「You don't have access to GitHub Copilot」
- 在 github.com/settings/copilot 確認你有 Copilot 訂閱
- 如果使用工作帳號,請確認你的組織允許 CLI 存取
「Authentication failed」
重新驗證身分:
copilot
> /login
瀏覽器未自動開啟
手動前往 github.com/login/device 並輸入終端機中顯示的驗證碼。
Token 過期
再次執行 /login 即可:
copilot
> /login
還是卡住了?
🔑 重點摘要
- GitHub Codespace 是快速入門的好方法 — Python、pytest 和 GitHub Copilot CLI 皆已預裝,你可以直接開始示範
- 多種安裝方式 — 選擇適合你系統的方式(Homebrew、WinGet、npm 或安裝腳本)
- 一次性驗證 — 登入狀態會持續到 token 過期
- 書籍應用程式正常運作 — 你將在整個課程中使用
samples/book-app-project
📚 官方文件:安裝 Copilot CLI 以了解安裝選項和需求。
📋 快速參考:查看 GitHub Copilot CLI 指令參考 以取得完整的指令與快捷鍵清單。
第一章 安裝與初步

觀看 AI 即時發現錯誤、解釋令人困惑的程式碼,並產生可運作的腳本。接著學習三種使用 GitHub Copilot CLI (命令列介面) 的方式。
本章是魔法開始的地方!你將親身體驗為什麼開發者形容 GitHub Copilot CLI 就像隨時有一位資深工程師在旁邊。你會看到 AI 在幾秒鐘內找到安全漏洞、用淺顯的語言解釋複雜的程式碼,並即時產生可運作的腳本。然後你將掌握三種互動模式(Interactive、Plan 和 Programmatic),讓你確切知道在任何任務中該使用哪一種。
⚠️ 先決條件:請確保你已完成 第 00 章:快速入門。在執行以下示範之前,你需要先安裝並完成 GitHub Copilot CLI 的身分驗證。
🎯 學習目標
在本章結束時,你將能夠:
- 透過實作示範體驗 GitHub Copilot CLI 帶來的生產力提升
- 針對任何任務選擇正確的模式(Interactive、Plan 或 Programmatic)
- 使用 slash command(斜線指令)來控制你的 session(工作階段)
⏱️ 預估時間:約 45 分鐘(15 分鐘閱讀 + 30 分鐘實作)
你的第一次 Copilot CLI 體驗
立刻動手,看看 Copilot CLI 能做什麼。
暖身:你的第一批 prompt(提示詞)
在進入令人驚豔的示範之前,先從一些簡單的 prompt 開始,你現在就可以試試看。不需要任何程式碼儲存庫!只要打開終端機並啟動 Copilot CLI:
copilot
試試這些適合初學者的 prompt:
> Explain what a dataclass is in Python in simple terms
> Write a function that sorts a list of dictionaries by a specific key
> What's the difference between a list and a tuple in Python?
> Give me 5 best practices for writing clean Python code
不用 Python?沒問題!只要提出關於你所使用的程式語言的問題即可。
注意這感覺有多自然。就像跟同事聊天一樣直接提問。探索完畢後,輸入 /exit 離開 session。
關鍵洞見:GitHub Copilot CLI 是對話式的。你不需要特殊語法就能開始使用。只要用自然的語言提問即可。
實際操作
現在讓我們看看為什麼開發者稱這是「隨時有一位資深工程師在旁邊」。
📖 閱讀範例說明:以
>開頭的行是你在互動式 Copilot CLI session 中輸入的 prompt。沒有>前綴的行是你在終端機中執行的 shell 指令。
💡 關於範例輸出:本課程中展示的範例輸出僅供說明參考。因為 Copilot CLI 的回應每次都不同,你的結果在用字、格式和細節上會有所差異。請關注回傳的資訊類型,而非確切的文字。
示範 1:幾秒鐘完成程式碼審查
本課程包含了有故意設計的程式碼品質問題的範例檔案。如果你在本機上操作且尚未 clone(複製)儲存庫,請執行以下 git clone 指令,切換到 copilot-cli-for-beginners 資料夾,然後執行 copilot 指令。
# 如果你在本機操作且尚未 clone,請先複製課程儲存庫
git clone https://github.com/github/copilot-cli-for-beginners
cd copilot-cli-for-beginners
# 啟動 Copilot
copilot
進入互動式 Copilot CLI session 後,執行以下指令:
> Review @samples/book-app-project/book_app.py for code quality issues and suggest improvements
💡
@符號是做什麼用的?@符號告訴 Copilot CLI 讀取一個檔案。你將在第 02 章學到更多相關內容。現在只要照著範例完整複製指令即可。
🎬 看看實際操作!

示範輸出會有所不同。你的模型、工具和回應會與此處展示的不同。
重點:幾秒鐘完成專業的程式碼審查。手動審查需要……嗯……比那多得多的時間!
示範 2:解釋令人困惑的程式碼
有沒有盯著程式碼卻不知道它在做什麼的經驗?在你的 Copilot CLI session 中試試這個:
> Explain what @samples/book-app-project/books.py does in simple terms
🎬 看看實際操作!

示範輸出會有所不同。你的模型、工具和回應會與此處展示的不同。
結果:(你的輸出會有所不同)Copilot CLI 讀取檔案、理解程式碼,並用淺顯的語言解釋。
This is a book collection management module using Python dataclasses.
Think of it like a digital bookshelf:
- Book is a dataclass - a simple way to store book information (title, author, year, read status)
- BookCollection manages the entire collection and handles saving/loading
Key components:
1. @dataclass decorator (line 8)
- Automatically creates __init__, __repr__, etc.
- Clean way to define data structures in Python
2. BookCollection class (line 16)
- Maintains a list of Book objects
- Handles persistence with JSON file I/O
- load_books() reads from data.json
- save_books() writes to data.json using asdict()
3. Book operations:
- add_book() - creates and saves new books
- find_book_by_title() - searches collection
- mark_as_read() - updates read status
- find_by_author() - filters by author name
Common pattern: Read from JSON → Work with Python objects → Write back to JSON
重點:複雜的程式碼被解釋得就像一位有耐心的導師在教你一樣。
示範 3:產生可運作的程式碼
需要一個原本要花 15 分鐘上網搜尋的函式?繼續在你的 session 中:
> Write a Python function that takes a list of books and returns statistics:
total count, number read, number unread, oldest and newest book
🎬 看看實際操作!

示範輸出會有所不同。你的模型、工具和回應會與此處展示的不同。
結果:幾秒鐘內就得到一個完整、可運作的函式,你可以直接複製貼上執行。
探索完畢後,退出 session:
> /exit
重點:立即獲得成果,而且你全程都在同一個連續的 session 中。
模式與指令
你已經看過 Copilot CLI 能做什麼了。現在讓我們了解如何有效地使用這些功能。關鍵在於知道針對不同情境該使用三種互動模式中的哪一種。
💡 注意:Copilot CLI 還有一個 Autopilot 模式,它會自動完成任務而不需要你在每一步之後確認。這個模式很強大,但需要授予完整權限,且會自主使用 premium request(進階請求)。本課程聚焦於以下三種模式。等你熟悉基礎之後,我們會指引你了解 Autopilot。
🧩 真實世界的比喻:外出用餐
把使用 GitHub Copilot CLI 想像成外出用餐。從規劃行程到點餐,不同的情境需要不同的方式:
| 模式 | 用餐比喻 | 適用時機 |
|---|---|---|
| Plan | 到餐廳的 GPS 路線 | 複雜任務——先規劃路線、確認停靠點、同意計畫,然後出發 |
| Interactive | 與服務生交談 | 探索與反覆修改——提問、客製化、獲得即時回饋 |
| Programmatic | 得來速點餐 | 快速、明確的任務——留在你的環境中,快速得到結果 |
就像外出用餐一樣,你會自然地學會什麼時候該用哪種方式。
根據任務選擇你的模式:Plan 用來事先規劃、Interactive 用來來回協作、Programmatic 用來快速取得一次性結果
我該從哪個模式開始?
從 Interactive 模式開始。
- 你可以實驗並提出後續問題
- 上下文透過對話自然建立
- 犯錯時用
/clear很容易修正
熟悉之後,可以嘗試:
- Programmatic 模式(
copilot -p "<your prompt>")用於快速的一次性問題 - Plan 模式(
/plan)當你需要在寫程式碼之前更詳細地規劃
三種模式
模式 1:Interactive 模式(從這裡開始)
最適合:探索、反覆修改、多輪對話。就像與服務生交談,可以回答問題、接受回饋,並即時調整訂單。
開始一個互動式 session:
copilot
正如你到目前為止所見,你會看到一個提示符,可以自然地輸入。要查看可用指令的說明,只需輸入:
> /help
關鍵洞見:Interactive 模式會維護上下文。每條訊息都建立在前一條的基礎上,就像真正的對話一樣。
Interactive 模式範例
copilot
> Review @samples/book-app-project/utils.py and suggest improvements
> Add type hints to all functions
> Make the error handling more robust
> /exit
注意每個 prompt 如何建立在前一個回答之上。你是在進行對話,而不是每次從頭開始。
模式 2:Plan 模式
最適合:在執行之前想先審查方案的複雜任務。類似於在旅行前用 GPS 規劃路線。
Plan 模式幫助你在撰寫任何程式碼之前建立逐步計畫。使用 /plan 指令或按 Shift+Tab 切換到 Plan 模式:
💡 提示:Shift+Tab 可在模式間循環切換:Interactive → Plan → Autopilot。在互動式 session 中隨時按下即可切換模式,無需輸入指令。
copilot
> /plan Add a "mark as read" command to the book app
Plan 模式輸出:(你的輸出可能會不同)
📋 Implementation Plan
Step 1: Update the command handler in book_app.py
- Add new elif branch for "mark" command
- Create handle_mark_as_read() function
Step 2: Implement the handler function
- Prompt user for book title
- Call collection.mark_as_read(title)
- Display success/failure message
Step 3: Update help text
- Add "mark" to available commands list
- Document the command usage
Step 4: Test the flow
- Add a book
- Mark it as read
- Verify status changes in list output
Proceed with implementation? [Y/n]
關鍵洞見:Plan 模式讓你在撰寫任何程式碼之前審查並修改方案。計畫完成後,你甚至可以告訴 Copilot CLI 將它儲存到檔案中以供日後參考。例如,「Save this plan to mark_as_read_plan.md」就會建立一個包含計畫細節的 markdown 檔案。
💡 想要更複雜的? 試試:
/plan Add search and filter capabilities to the book app。Plan 模式可以從簡單功能擴展到完整應用程式。
📚 Autopilot 模式:你可能已注意到 Shift+Tab 會循環切換到第三種模式 Autopilot。在 Autopilot 模式中,Copilot 會自動完成整個計畫,不需要你在每一步之後確認——就像把任務交給同事並說「完成後告訴我」。典型的工作流程是 plan → accept → autopilot,這代表你需要先擅長撰寫計畫。先熟悉 Interactive 和 Plan 模式,準備好之後再參閱官方文件。
模式 3:Programmatic 模式
最適合:自動化、腳本、CI/CD、一次性指令。就像用得來速快速點餐,不需要跟服務生交談。
使用 -p 旗標執行不需要互動的一次性指令:
# 產生程式碼
copilot -p "Write a function that checks if a number is even or odd"
# 快速取得幫助
copilot -p "How do I read a JSON file in Python?"
關鍵洞見:Programmatic 模式給你一個快速回答就結束。不需要對話,就是輸入 → 輸出。
📚 進階:在腳本中使用 Programmatic 模式(點擊展開)
熟悉之後,你可以在 shell 腳本中使用 -p:
#!/bin/bash
# 自動產生 commit 訊息
COMMIT_MSG=$(copilot -p "Generate a commit message for: $(git diff --staged)")
git commit -m "$COMMIT_MSG"
# 審查檔案
copilot --allow-all -p "Review @myfile.py for issues"
⚠️ 關於
--allow-all:這個旗標會跳過所有權限提示,讓 Copilot CLI 不需詢問即可讀取檔案、執行指令和存取 URL。這在 Programmatic 模式(-p)中是必要的,因為沒有互動式 session 來批准操作。只在你自己撰寫的 prompt 和你信任的目錄中使用--allow-all。絕對不要在不受信任的輸入或敏感目錄中使用。
必備斜線指令
這些指令在 Interactive 模式中使用。先學會這六個就好——它們涵蓋了日常使用的 90%:
| 指令 | 功能 | 適用時機 |
|---|---|---|
/clear | 清除對話並重新開始 | 切換主題時 |
/help | 顯示所有可用指令 | 忘記指令時 |
/model | 顯示或切換 AI 模型 | 想要更換 AI 模型時 |
/plan | 在寫程式碼前規劃你的工作 | 處理較複雜的功能時 |
/research | 使用 GitHub 和網路來源進行深入研究 | 需要在寫程式碼前調查某個主題時 |
/exit | 結束 session | 完成工作時 |
入門就是這些!隨著你越來越熟練,可以探索更多指令。
📚 官方文件:CLI 指令參考 提供完整的指令和旗標列表。
📚 更多指令(點擊展開)
💡 上面的必備指令涵蓋了你日常使用的大部分需求。這份參考資料是讓你準備好探索更多功能時使用的。
Agent(代理)環境
| 指令 | 功能 |
|---|---|
/agent | 瀏覽並選擇可用的 agent |
/init | 為你的 repo(儲存庫)初始化 Copilot 指示 |
/mcp | 管理 MCP(模型上下文協定)伺服器設定 |
/skills | 管理 skill(技能)以增強功能 |
模型與子代理
| 指令 | 功能 |
|---|---|
/delegate | 將任務交給 GitHub Copilot 雲端 agent |
/fleet | 將複雜任務拆分為平行子任務以加快完成速度 |
/model | 顯示或切換 AI 模型 |
/tasks | 查看背景子代理和分離的 shell session |
程式碼
| 指令 | 功能 |
|---|---|
/diff | 審查目前目錄中的變更 |
/pr | 操作目前分支的 PR(拉取請求) |
/research | 使用 GitHub 和網路來源執行深入研究調查 |
/review | 執行程式碼審查 agent 來分析變更 |
/terminal-setup | 啟用多行輸入支援(shift+enter 和 ctrl+enter) |
權限
| 指令 | 功能 | ||
|---|---|---|---|
/add-dir <directory> | 將目錄新增到允許清單 | ||
| `/allow-all [on | off | show]` | 自動批准所有權限提示;使用 on 啟用、off 停用、show 查看目前狀態 |
/cwd, /cd [directory] | 查看或變更工作目錄 | ||
/list-dirs | 顯示所有已允許的目錄 |
⚠️ 請謹慎使用:
/allow-all會跳過確認提示。在信任的專案中很方便,但處理不受信任的程式碼時要小心。
Session
| 指令 | 功能 |
|---|---|
/clear | 放棄目前的 session(不儲存歷史紀錄)並開始全新的對話 |
/compact | 摘要對話以減少 context window(上下文視窗)使用量 |
/context | 顯示 context window 的 token(符記)使用量和視覺化 |
/new | 結束目前的 session(將其儲存到歷史紀錄以便搜尋/恢復)並開始全新的對話 |
/resume | 切換到另一個 session(可選擇指定 session ID) |
/rename | 重新命名目前的 session(省略名稱可自動產生) |
/rewind | 開啟時間軸選取器,回溯到對話中任何較早的時間點 |
/usage | 顯示 session 使用指標和統計資料 |
/session | 顯示 session 資訊和工作區摘要 |
/share | 將 session 匯出為 markdown 檔案、GitHub gist 或獨立的 HTML 檔案 |
說明與回饋
| 指令 | 功能 |
|---|---|
/changelog | 顯示 CLI 版本的變更日誌 |
/feedback | 向 GitHub 提交回饋 |
/help | 顯示所有可用指令 |
/theme | 查看或設定終端機佈景主題 |
快速 Shell 指令
在指令前加上 ! 即可直接執行 shell 指令,不經過 AI:
copilot
> !git status
# 直接執行 git status,繞過 AI
> !python -m pytest tests/
# 直接執行 pytest
切換模型
Copilot CLI 支援來自 OpenAI、Anthropic、Google 及其他廠商的多種 AI 模型。你可用的模型取決於你的訂閱方案和地區。使用 /model 查看你的選項並在模型之間切換:
copilot
> /model
# 顯示可用的模型並讓你選擇。選擇 Sonnet 4.5。
💡 提示:有些模型比其他模型消耗更多的「premium request」。標記為 1x 的模型(如 Claude Sonnet 4.5)是很好的預設選擇。它們能力強且效率高。較高倍率的模型會更快消耗你的 premium request 配額,所以在真正需要時再使用。
練習
是時候將你學到的東西付諸實踐了。
▶️ 自己動手試試
互動式探索
啟動 Copilot 並使用後續 prompt 來反覆改進書籍應用程式:
copilot
> Review @samples/book-app-project/book_app.py - what could be improved?
> Refactor the if/elif chain into a more maintainable structure
> Add type hints to all the handler functions
> /exit
規劃一個功能
使用 /plan 讓 Copilot CLI 在撰寫任何程式碼之前先規劃實作方案:
copilot
> /plan Add a search feature to the book app that can find books by title or author
# 審查計畫
# 批准或修改
# 觀看它逐步實作
使用 Programmatic 模式自動化
-p 旗標讓你直接從終端機執行 Copilot CLI,不需進入 Interactive 模式。從儲存庫根目錄將以下腳本複製貼上到你的終端機(不是在 Copilot 裡面),以審查書籍應用程式中的所有 Python 檔案。
# 審查書籍應用程式中的所有 Python 檔案
for file in samples/book-app-project/*.py; do
echo "Reviewing $file..."
copilot --allow-all -p "Quick code quality review of @$file - critical issues only"
done
PowerShell (Windows):
# 審查書籍應用程式中的所有 Python 檔案
Get-ChildItem samples/book-app-project/*.py | ForEach-Object {
$relativePath = "samples/book-app-project/$($_.Name)";
Write-Host "Reviewing $relativePath...";
copilot --allow-all -p "Quick code quality review of @$relativePath - critical issues only"
}
完成示範後,試試這些變化練習:
- Interactive 挑戰:啟動
copilot並探索書籍應用程式。詢問@samples/book-app-project/books.py並連續要求改進 3 次。
- Plan 模式挑戰:執行
/plan Add rating and review features to the book app。仔細閱讀計畫。它合理嗎?
- Programmatic 挑戰:執行
copilot --allow-all -p "List all functions in @samples/book-app-project/book_app.py and describe what each does"。第一次就成功了嗎?
📝 作業
主要挑戰:改進書籍應用程式的工具模組
實作範例著重於審查和重構 book_app.py。現在在另一個檔案 utils.py 上練習相同的技能:
- 開始一個互動式 session:
copilot - 請 Copilot CLI 摘要該檔案:
@samples/book-app-project/utils.py What does each function in this file do? - 請它加入輸入驗證:「Add validation to
get_user_choice()so it handles empty input and non-numeric entries」 - 請它改進錯誤處理:「What happens if
get_book_details()receives an empty string for the title? Add guards for that.」 - 請它加入文件字串:「Add a comprehensive docstring to
get_book_details()with parameter descriptions and return values」 - 觀察上下文如何在 prompt 之間延續。每次改進都建立在前一次的基礎上
- 使用
/exit退出
成功標準:你應該得到一個改進後的 utils.py,包含輸入驗證、錯誤處理和文件字串,全部透過多輪對話建立。
💡 提示(點擊展開)
可嘗試的範例 prompt:
> @samples/book-app-project/utils.py What does each function in this file do?
> Add validation to get_user_choice() so it handles empty input and non-numeric entries
> What happens if get_book_details() receives an empty string for the title? Add guards for that.
> Add a comprehensive docstring to get_book_details() with parameter descriptions and return values
常見問題:
- 如果 Copilot CLI 提出澄清問題,直接自然地回答即可
- 上下文會向前延續,因此每個 prompt 都建立在前一個的基礎上
- 如果想重新開始,使用
/clear
加分挑戰:比較各模式
範例中使用了 /plan 來規劃搜尋功能,以及 -p 來批次審查。現在在一個新任務上嘗試三種模式:為 BookCollection 類別新增一個 list_by_year() 方法:
- Interactive:
copilot→ 請它逐步設計和建構這個方法 - Plan:
/plan Add a list_by_year(start, end) method to BookCollection that filters books by publication year range - Programmatic:
copilot --allow-all -p "@samples/book-app-project/books.py Add a list_by_year(start, end) method that returns books published between start and end year inclusive"
反思:哪種模式感覺最自然?你會在什麼時候使用每種模式?
🔧 常見錯誤與疑難排解(點擊展開)
常見錯誤
| 錯誤 | 會發生什麼 | 修正方式 |
|---|---|---|
輸入 exit 而不是 /exit | Copilot CLI 會把「exit」當作 prompt,而不是指令 | 斜線指令一定要以 / 開頭 |
使用 -p 進行多輪對話 | 每次 -p 呼叫都是獨立的,不記得之前的呼叫 | 需要建立在上下文之上的對話請使用 Interactive 模式(copilot) |
忘記在包含 $ 或 ! 的 prompt 外加引號 | Shell 會在 Copilot CLI 看到之前就解譯特殊字元 | 用引號包住 prompt:copilot -p "What does $HOME mean?" |
疑難排解
「Model not available」 — 你的訂閱方案可能不包含所有模型。使用 /model 查看可用的模型。
「Context too long」 — 你的對話已用完整個 context window。使用 /clear 重置,或開始新的 session。
「Rate limit exceeded」 — 等待幾分鐘後再試。考慮使用 Programmatic 模式搭配延遲來進行批次操作。
總結
🔑 重點整理
- Interactive 模式 用於探索和反覆修改——上下文會向前延續。就像與一個記得你之前說過什麼的人對話。
- Plan 模式 通常用於較複雜的任務。在實作前先審查。
- Programmatic 模式 用於自動化。不需要互動。
- 必備指令(
/help、/clear、/plan、/research、/model、/exit)涵蓋大部分日常使用。
📋 快速參考:參閱 GitHub Copilot CLI 指令參考 取得完整的指令和快捷鍵列表。
➡️ 下一步
現在你已了解三種模式,讓我們來學習如何為 Copilot CLI 提供關於你的程式碼的上下文。
在 第 02 章:上下文與對話 中,你將學到:
- 使用
@語法來參照檔案和目錄 - 使用
--resume和--continue進行 session 管理 - 上下文管理如何讓 Copilot CLI 真正強大
第二章 上下文與對話

如果 AI 能看到你的整個程式碼庫,而不只是一次一個檔案呢?
在本章中,你將解鎖 GitHub Copilot CLI (命令列介面) 的真正力量:context (上下文)。你將學會使用 @ 語法來參照檔案與目錄,讓 Copilot CLI 深入理解你的程式碼庫。你將了解如何在不同 session (工作階段) 之間維持對話、數天後精確地從上次中斷處繼續工作,並看到跨檔案分析如何抓出單一檔案審查完全遺漏的 bug。
🎯 學習目標
完成本章後,你將能夠:
- 使用
@語法參照檔案、目錄和圖片 - 使用
--resume和--continue恢復先前的 session - 了解 context window (上下文視窗) 的運作方式
- 撰寫有效的多輪對話
- 管理目錄權限以支援多專案工作流程
⏱️ 預估時間:約 50 分鐘(20 分鐘閱讀 + 30 分鐘實作)
🧩 真實世界類比:與同事協作
就像你的同事一樣,Copilot CLI 不是讀心術師。提供更多資訊能幫助人類和 Copilot 同樣地給出有針對性的支援!
想像向同事解釋一個 bug:
沒有上下文:「書籍應用程式不能用了。」
有上下文:「看一下
books.py,特別是find_book_by_title函式。它沒有做不區分大小寫的比對。」
要為 Copilot CLI 提供上下文,請使用 @ 語法 將 Copilot CLI 指向特定檔案。
基礎篇:基本上下文
本節涵蓋有效使用上下文所需的一切。請先掌握這些基礎知識。
@ 語法
@ 符號用於在你的 prompt (提示詞) 中參照檔案和目錄。這是你告訴 Copilot CLI「看看這個檔案」的方式。
💡 注意:本課程中的所有範例都使用本儲存庫中包含的
samples/資料夾,因此你可以直接嘗試每個指令。
立即試試(無需設定)
你可以用電腦上的任何檔案來嘗試:
copilot
# 指向你擁有的任何檔案
> Explain what @package.json does
> Summarize @README.md
> What's in @.gitignore and why?
💡 手邊沒有專案? 建立一個快速測試檔案:
```bash
echo "def greet(name): return 'Hello ' + name" > test.py
copilot
What does @test.py do?
```
基本 @ 模式
| 模式 | 功能 | 使用範例 |
|---|---|---|
@file.py | 參照單一檔案 | Review @samples/book-app-project/books.py |
@folder/ | 參照目錄中的所有檔案 | Review @samples/book-app-project/ |
@file1.py @file2.py | 參照多個檔案 | Compare @samples/book-app-project/book_app.py @samples/book-app-project/books.py |
參照單一檔案
copilot
> Explain what @samples/book-app-project/utils.py does
🎬 觀看實際操作!

展示輸出會有所不同。你的模型、工具和回應將與此處顯示的不同。
參照多個檔案
copilot
> Compare @samples/book-app-project/book_app.py and @samples/book-app-project/books.py for consistency
參照整個目錄
copilot
> Review all files in @samples/book-app-project/ for error handling
跨檔案智慧分析
這就是上下文成為超能力的地方。單一檔案分析很有用。跨檔案分析則具有變革性。
示範:找出跨越多個檔案的 Bug
copilot
> @samples/book-app-project/book_app.py @samples/book-app-project/books.py
>
> How do these files work together? What's the data flow?
💡 進階選項:若要進行以安全為重點的跨檔案分析,請嘗試 Python 安全性範例:
```bash
@samples/buggy-code/python/user_service.py @samples/buggy-code/python/payment_processor.py
Find security vulnerabilities that span BOTH files
```
🎬 觀看實際操作!

展示輸出會有所不同。你的模型、工具和回應將與此處顯示的不同。
Copilot CLI 發現的內容:
Cross-Module Analysis
=====================
1. DATA FLOW PATTERN
book_app.py creates BookCollection instance and calls methods
books.py defines BookCollection class and manages data persistence
Flow: book_app.py (UI) → books.py (business logic) → data.json (storage)
2. DUPLICATE DISPLAY FUNCTIONS
book_app.py:9-21 show_books() function
utils.py:28-36 print_books() function
Impact: Two nearly identical functions doing the same thing. If you update
one (like changing the format), you must remember to update the other.
3. INCONSISTENT ERROR HANDLING
book_app.py handles ValueError from year conversion
books.py silently returns None/False on errors
Pattern: No unified approach to error handling across modules
為什麼這很重要:單一檔案的審查會遺漏全局。只有跨檔案分析才能揭示:
- 重複程式碼——應該整合的部分
- 資料流模式——顯示元件之間如何互動
- 架構問題——影響可維護性的因素
示範:60 秒內理解一個程式碼庫
剛接觸一個專案?使用 Copilot CLI 快速了解它。
copilot
> @samples/book-app-project/
>
> In one paragraph, what does this app do and what are its biggest quality issues?
你會得到的結果:
This is a CLI book collection manager that lets users add, list, remove, and
search books stored in a JSON file. The biggest quality issues are:
1. Duplicate display logic - show_books() and print_books() do the same thing
2. Inconsistent error handling - some errors raise exceptions, others return False
3. No input validation - year can be 0, empty strings accepted for title/author
4. Missing tests - no test coverage for critical functions like find_book_by_title
Priority fix: Consolidate duplicate display functions and add input validation.
結果:原本需要一小時的程式碼閱讀,壓縮成 10 秒。你確切地知道該把重心放在哪裡。
實用範例
範例 1:帶上下文的程式碼審查
copilot
> @samples/book-app-project/books.py Review this file for potential bugs
# Copilot CLI 現在擁有完整的檔案內容,可以給出具體的回饋:
# 「第 49 行:區分大小寫的比較可能會遺漏書籍...」
# 「第 29 行:JSON 解碼錯誤被捕獲了,但資料損壞未被記錄...」
> What about @samples/book-app-project/book_app.py?
# 現在審查 book_app.py,但仍保有 books.py 的上下文
範例 2:理解一個程式碼庫
copilot
> @samples/book-app-project/books.py What does this module do?
# Copilot CLI 讀取 books.py 並理解 BookCollection 類別
> @samples/book-app-project/ Give me an overview of the code structure
# Copilot CLI 掃描目錄並提供摘要
> How does the app save and load books?
# Copilot CLI 可以追蹤它已經看過的程式碼
🎬 觀看多輪對話的實際操作!

展示輸出會有所不同。你的模型、工具和回應將與此處顯示的不同。
範例 3:多檔案重構
copilot
> @samples/book-app-project/book_app.py @samples/book-app-project/utils.py
> I see duplicate display functions: show_books() and print_books(). Help me consolidate these.
# Copilot CLI 看到兩個檔案,可以建議如何合併重複的程式碼
Session 管理
Session 會在你工作時自動儲存。你可以恢復先前的 session 以從上次中斷處繼續。
Session 自動儲存
每段對話都會自動儲存。只需正常退出:
copilot
> @samples/book-app-project/ Let's improve error handling across all modules
[... do some work ...]
> /exit
恢復最近的 Session
# 從上次中斷處繼續
copilot --continue
恢復特定的 Session
# 從 session 清單中互動式選取
copilot --resume
# 或透過 ID 恢復特定 session
copilot --resume abc123
💡 如何找到 session ID? 你不需要記住它們。不帶 ID 執行
copilot --resume會顯示一個互動式清單,列出你先前的 session、其名稱、ID 和最後活動時間。只需選擇你想要的即可。
多個終端機怎麼辦? 每個終端機視窗都是各自獨立的 session,擁有自己的上下文。如果你在三個終端機中開啟 Copilot CLI,那就是三個獨立的 session。從任何終端機執行
--resume都能瀏覽所有 session。--continue旗標會抓取最近關閉的 session,無論它在哪個終端機中。
可以在不重新啟動的情況下切換 session 嗎? 可以。在活動的 session 中使用
/resumeslash command (斜線指令):
```
/resume
# Shows a list of sessions to switch to
```
整理你的 Session
為 session 取有意義的名稱,方便日後查找:
copilot
> /rename book-app-review
# Session 已重新命名,方便辨識
檢查和管理上下文
隨著你新增檔案和對話,Copilot CLI 的 context window 會逐漸填滿。有幾個指令可以幫助你保持掌控:
copilot
> /context
Context usage: 62k/200k tokens (31%)
> /clear
# 放棄目前的 session(不儲存歷史紀錄)並開始全新的對話
> /new
# 結束目前的 session(將其儲存到歷史紀錄以供搜尋/恢復)並開始全新的對話
> /rewind
# 開啟時間軸選取器,讓你回溯到對話中的較早時間點
💡 何時使用
/clear或/new:如果你一直在審查 books.py 並想切換到討論 utils.py,請先執行 /new(如果你不需要 session 歷史紀錄則用 /clear)。否則舊主題的過時上下文可能會干擾回應。
💡 犯了錯誤或想嘗試不同的方法? 使用
/rewind(或按兩次 Esc)來開啟時間軸選取器,讓你回溯到對話中的任何較早時間點,而不僅僅是最近的一個。當你走錯方向並想回頭而不必完全從頭開始時,這非常有用。
從上次中斷處繼續
Session 在你退出時自動儲存。數天後恢復時完整的上下文:檔案、問題和進度都會被記住。
想像這個跨越多天的工作流程:
# 週一:開始書籍應用程式審查
copilot
> /rename book-app-review
> @samples/book-app-project/books.py
> Review and number all code quality issues
Quality Issues Found:
1. Duplicate display functions (book_app.py & utils.py) - MEDIUM
2. No input validation for empty strings - MEDIUM
3. Year can be 0 or negative - LOW
4. No type hints on all functions - LOW
5. Missing error logging - LOW
> Fix issue #1 (duplicate functions)
# 進行修復...
> /exit
# 週三:精確地從上次中斷處恢復
copilot --continue
> What issues remain unfixed from our book app review?
Remaining issues from our book-app-review session:
2. No input validation for empty strings - MEDIUM
3. Year can be 0 or negative - LOW
4. No type hints on all functions - LOW
5. Missing error logging - LOW
Issue #1 (duplicate functions) was fixed on Monday.
> Let's tackle issue #2 next
這為什麼如此強大:數天之後,Copilot CLI 記得:
- 你正在處理的確切檔案
- 編號的問題清單
- 哪些已經被處理過
- 你對話的上下文
不需要重新解釋。不需要重新讀取檔案。直接繼續工作。
🎉 你現在已經掌握了基礎! @ 語法、session 管理(--continue/--resume//rename)以及上下文指令(/context//clear)已足以讓你高效工作。以下內容都是選修的。準備好了再回來看。
選修篇:深入探索
這些主題建立在上述基礎之上。挑選你感興趣的,或直接跳到練習。
| 我想學習…… | 跳至 |
|---|---|
| 萬用字元模式與進階 session 指令 | 額外的 @ 模式與 Session 指令 |
| 跨多個 prompt 累積上下文 | 上下文感知對話 |
Token (符記) 限制與 /compact | 理解 Context Window |
| 如何選擇正確的檔案來參照 | 選擇要參照的內容 |
| 分析螢幕截圖和設計稿 | 使用圖片 |
額外的 @ 模式與 Session 指令
額外的 @ 模式
對於進階使用者,Copilot CLI 支援萬用字元模式和圖片參照:
| 模式 | 功能 |
|---|---|
@folder/*.py | 資料夾中的所有 .py 檔案 |
@**/test_*.py | 遞迴萬用字元:尋找任何位置的所有測試檔案 |
@image.png | 用於 UI 審查的圖片檔案 |
copilot
> Find all TODO comments in @samples/book-app-project/**/*.py
檢視 Session 資訊
copilot
> /session
# 顯示目前 session 的詳細資訊和工作區摘要
> /usage
# 顯示 session 的指標和統計資料
分享你的 Session
copilot
> /share file ./my-session.md
# 將 session 匯出為 markdown 檔案
> /share gist
# 建立包含 session 的 GitHub gist
> /share html
# 將 session 匯出為獨立的互動式 HTML 檔案
# 適合與團隊成員分享精美的 session 報告或保存以供參考
上下文感知對話
上下文感知對話
當你進行相互建構的多輪對話時,魔法就會發生。
範例:漸進式增強
copilot
> @samples/book-app-project/books.py Review the BookCollection class
Copilot CLI: "The class looks functional, but I notice:
1. Missing type hints on some methods
2. No validation for empty title/author
3. Could benefit from better error handling"
> Add type hints to all methods
Copilot CLI: "Here's the class with complete type hints..."
[Shows typed version]
> Now improve error handling
Copilot CLI: "Building on the typed version, here's improved error handling..."
[Adds validation and proper exceptions]
> Generate tests for this final version
Copilot CLI: "Based on the class with types and error handling..."
[Generates comprehensive tests]
注意每個 prompt 如何建立在先前工作的基礎上。這就是上下文的力量。
理解 Context Window
理解 Context Window
你已經從基礎篇中認識了 /context 和 /clear。以下是 context window 運作方式的更深入說明。
每個 AI 都有一個「context window」,也就是它一次能考慮的文字量。
Context window 就像一張書桌:它一次只能放這麼多東西。檔案、對話歷史和系統提示詞都會佔用空間。
達到限制時會發生什麼
copilot
> /context
Context usage: 45,000 / 128,000 tokens (35%)
# 隨著你新增更多檔案和對話,這個數字會增長
> @large-codebase/
Context usage: 120,000 / 128,000 tokens (94%)
# 警告:接近上下文限制
> @another-large-file.py
Context limit reached. Older context will be summarized.
/compact 指令
當你的上下文快滿了但你不想失去對話時,/compact 會摘要你的歷史紀錄以釋放 token:
copilot
> /compact
# 摘要對話歷史,釋放上下文空間
# 你的關鍵發現和決策會被保留
上下文效率技巧
| 情境 | 操作 | 原因 |
|---|---|---|
| 開始新主題 | /clear | 移除無關的上下文 |
| 走錯方向 | /rewind | 回溯到任何較早的時間點 |
| 長時間對話 | /compact | 摘要歷史,釋放 token |
| 需要特定檔案 | 用 @file.py 而非 @folder/ | 只載入你需要的 |
| 達到限制 | /new 或 /clear | 全新的上下文 |
| 多個主題 | 每個主題使用 /rename | 方便恢復正確的 session |
大型程式碼庫的最佳實踐
- 具體明確:用
@samples/book-app-project/books.py而非@samples/book-app-project/ - 切換主題時清除上下文:切換焦點時使用
/new或/clear - 使用
/compact:摘要對話以釋放上下文 - 使用多個 session:每個功能或主題一個 session
選擇要參照的內容
選擇要參照的內容
並非所有檔案在上下文方面都同等重要。以下是如何明智地選擇:
檔案大小考量
| 檔案大小 | 大約 Token 數 | 策略 |
|---|---|---|
| 小型(<100 行) | ~500-1,500 token | 自由參照 |
| 中型(100-500 行) | ~1,500-7,500 token | 參照特定檔案 |
| 大型(500+ 行) | 7,500+ token | 有選擇性,使用特定檔案 |
| 超大型(1000+ 行) | 15,000+ token | 考慮拆分或針對特定區段 |
具體範例:
- 書籍應用程式的 4 個 Python 檔案合計 ≈ 2,000-3,000 token
- 一個典型的 Python 模組(200 行)≈ 3,000 token
- 一個 Flask API 檔案(400 行)≈ 6,000 token
- 你的 package.json ≈ 200-500 token
- 一段簡短的 prompt + 回應 ≈ 500-1,500 token
💡 程式碼的快速估算: 將程式碼行數乘以約 15 即可得到大約的 token 數。請記住這只是估算值。
該包含什麼 vs. 該排除什麼
高價值(包含這些):
- 進入點(
book_app.py、main.py、app.py) - 你正在詢問的特定檔案
- 被你的目標檔案直接匯入的檔案
- 組態檔(
requirements.txt、pyproject.toml) - 資料模型或 dataclass
較低價值(考慮排除):
- 產生的檔案(編譯輸出、打包的資源)
- Node modules 或 vendor 目錄
- 大型資料檔案或測試資料
- 與你的問題無關的檔案
具體度光譜
較不具體 ────────────────────────► 較具體
@samples/book-app-project/ @samples/book-app-project/books.py:47-52
│ │
└─ 掃描所有內容 └─ 只有你需要的
(使用更多上下文) (保留上下文)
何時使用廣泛參照(@samples/book-app-project/):
- 初次探索程式碼庫
- 在多個檔案中尋找模式
- 架構審查
何時使用具體參照(@samples/book-app-project/books.py):
- 除錯特定問題
- 審查特定檔案的程式碼
- 詢問關於單一函式的問題
實用範例:分階段載入上下文
copilot
# 步驟 1:從結構開始
> @package.json What frameworks does this project use?
# 步驟 2:根據回答縮小範圍
> @samples/book-app-project/ Show me the project structure
# 步驟 3:聚焦在重要的部分
> @samples/book-app-project/books.py Review the BookCollection class
# 步驟 4:僅在需要時才加入相關檔案
> @samples/book-app-project/book_app.py @samples/book-app-project/books.py How does the CLI use the BookCollection?
這種分階段的方法使上下文保持聚焦且高效。
使用圖片
使用圖片
你可以使用 @ 語法在對話中包含圖片,或直接從剪貼簿貼上(Cmd+V / Ctrl+V)。Copilot CLI 可以分析螢幕截圖、設計稿和圖表,協助 UI 除錯、設計實作和錯誤分析。
copilot
> @images/screenshot.png What is happening in this image?
> @images/mockup.png Write the HTML and CSS to match this design. Place it in a new file called index.html and put the CSS in styles.css.
📖 了解更多:參閱額外的上下文功能以了解支援的格式、實用案例以及結合圖片與程式碼的技巧。
練習
是時候應用你的上下文和 session 管理技能了。
▶️ 自己動手試試
完整專案審查
本課程包含你可以直接審查的範例檔案。啟動 copilot 並執行接下來顯示的 prompt:
copilot
> @samples/book-app-project/ Give me a code quality review of this project
# Copilot CLI 會找出以下問題:
# - 重複的顯示函式
# - 缺少輸入驗證
# - 不一致的錯誤處理
💡 想用你自己的檔案試試? 建立一個小型 Python 專案(
mkdir -p my-project/src),新增一些 .py 檔案,然後使用@my-project/src/來審查它們。如果你願意,也可以請 copilot 為你建立範例程式碼!
Session 工作流程
copilot
> /rename book-app-review
> @samples/book-app-project/books.py Let's add input validation for empty titles
[Copilot CLI suggests validation approach]
> Implement that fix
> Now consolidate the duplicate display functions in @samples/book-app-project/
> /exit
# 稍後——從上次中斷處恢復
copilot --continue
> Generate tests for the changes we made
完成示範後,試試這些變化:
- 跨檔案挑戰:分析 book_app.py 和 books.py 如何協同工作:
```bash
copilot
@samples/book-app-project/book_app.py @samples/book-app-project/books.py
What's the relationship between these files? Are there any code smells?
```
- Session 挑戰:啟動一個 session,用
/rename my-first-session命名,做一些工作,用/exit退出,然後執行copilot --continue。它還記得你在做什麼嗎?
- 上下文挑戰:在 session 進行中執行
/context。你使用了多少 token?試試/compact然後再檢查一次。(更多關於/compact的內容,請參閱「深入探索」中的理解 Context Window。)
自我檢查:當你能解釋為什麼 @folder/ 比逐一開啟每個檔案更強大時,你就理解了上下文。
📝 作業
主要挑戰:追蹤資料流
實作範例專注於程式碼品質審查和輸入驗證。現在用不同的任務來練習相同的上下文技能——追蹤資料如何在應用程式中流動:
- 啟動互動式 session:
copilot - 同時參照
books.py和book_app.py:
@samples/book-app-project/books.py @samples/book-app-project/book_app.py Trace how a book goes from user input to being saved in data.json. What functions are involved at each step?
- 帶入資料檔案以提供額外上下文:
@samples/book-app-project/data.json What happens if this JSON file is missing or corrupted? Which functions would fail?
- 要求跨檔案改進建議:
@samples/book-app-project/books.py @samples/book-app-project/utils.py Suggest a consistent error-handling strategy that works across both files.
- 重新命名 session:
/rename data-flow-analysis - 用
/exit退出,然後用copilot --continue恢復,並就資料流提出後續問題
成功標準:你能追蹤跨多個檔案的資料、恢復已命名的 session,並獲得跨檔案的建議。
💡 提示(點選展開)
開始入門:
cd /path/to/copilot-cli-for-beginners
copilot
> @samples/book-app-project/books.py @samples/book-app-project/book_app.py Trace how a book goes from user input to being saved in data.json.
> @samples/book-app-project/data.json What happens if this file is missing or corrupted?
> /rename data-flow-analysis
> /exit
然後用以下指令恢復:copilot --continue
實用指令:
@file.py- 參照單一檔案@folder/- 參照資料夾中的所有檔案(注意結尾的/)/context- 檢查你使用了多少上下文/rename <name>- 為你的 session 命名以方便恢復
加分挑戰:上下文限制
- 使用
@samples/book-app-project/一次參照所有書籍應用程式的檔案 - 針對不同檔案提出多個詳細問題(
books.py、utils.py、book_app.py、data.json) - 執行
/context查看用量。它填滿的速度有多快? - 練習使用
/compact回收空間,然後繼續對話 - 嘗試使用更具體的檔案參照(例如用
@samples/book-app-project/books.py取代整個資料夾),看看它如何影響上下文用量
🔧 常見錯誤與疑難排解(點選展開)
常見錯誤
| 錯誤 | 發生的情況 | 修正方式 |
|---|---|---|
忘記在檔案名稱前加 @ | Copilot CLI 將「books.py」視為純文字 | 使用 @samples/book-app-project/books.py 來參照檔案 |
| 期望 session 自動持續 | 重新啟動 copilot 會失去所有先前的上下文 | 使用 --continue(上次的 session)或 --resume(選擇一個 session) |
| 參照目前目錄之外的檔案 | 「Permission denied」或「File not found」錯誤 | 使用 /add-dir /path/to/directory 授予存取權限 |
切換主題時未使用 /clear | 舊的上下文會干擾新主題的回應 | 在開始不同任務前執行 /clear |
疑難排解
「File not found」錯誤 - 確保你在正確的目錄中:
pwd # Check current directory
ls # List files
# 然後啟動 copilot 並使用相對路徑
copilot
> Review @samples/book-app-project/books.py
「Permission denied」 - 將目錄加入你的允許清單:
copilot --add-dir /path/to/directory
# 或在 session 中:
> /add-dir /path/to/directory
上下文太快填滿:
- 使用更具體的檔案參照
- 在不同主題之間使用
/clear - 將工作拆分到多個 session
總結
🔑 重點回顧
@語法 為 Copilot CLI 提供關於檔案、目錄和圖片的上下文- 多輪對話 隨著上下文的累積而相互建構
- Session 自動儲存:使用
--continue或--resume從上次中斷處繼續 - Context window 有其限制:使用
/clear、/compact、/context、/new和/rewind來管理 - 權限旗標(
--add-dir、--allow-all)控制多目錄的存取。請謹慎使用! - 圖片參照(
@screenshot.png)有助於以視覺方式除錯 UI 問題
📚 官方文件:Use Copilot CLI 提供關於上下文、session 和檔案操作的完整參考。
📋 快速參考:參閱 GitHub Copilot CLI command reference 以取得完整的指令和快捷鍵清單。
➡️ 下一步
現在你已經能為 Copilot CLI 提供上下文了,讓我們將它應用到真實的開發任務中。你剛學到的上下文技巧(檔案參照、跨檔案分析和 session 管理)是下一章強大工作流程的基礎。
在 第 03 章:開發工作流程 中,你將學到:
- 程式碼審查工作流程
- 重構模式
- 除錯輔助
- 測試產生
- Git 整合
第三章 開發工作流程

如果 AI 能找到你根本不知道該問的 bug 呢?
在本章中,GitHub Copilot CLI(命令列介面)將成為你的日常利器。你將在每天已經依賴的工作流程中使用它:test(測試)、重構、debug(除錯)和 Git。
🎯 學習目標
完成本章後,你將能夠:
- 使用 Copilot CLI 執行全面的 code review(程式碼審查)
- 安全地重構舊有程式碼
- 藉由 AI 輔助進行 debug
- 自動產生 test
- 將 Copilot CLI 整合至你的 Git 工作流程
⏱️ 預估時間:約 60 分鐘(15 分鐘閱讀 + 45 分鐘實作)
🧩 真實世界比喻:木匠的工作流程
木匠不僅僅是知道如何使用工具,他們對不同的工作有各自的工作流程:
同樣地,開發者對不同的任務也有各自的工作流程。GitHub Copilot CLI 強化了每一種工作流程,讓你在日常的程式撰寫工作中更加高效且有成效。
五大工作流程
以下每個工作流程都是獨立完整的。挑選符合你目前需求的工作流程,或者全部都練習一遍。
選擇你的冒險路線
本章涵蓋開發者常用的五種工作流程。但你不需要一次讀完所有內容!每個工作流程都獨立收納在下方的可摺疊區段中。挑選符合你需求、最適合你目前專案的工作流程。你隨時可以回來探索其他的工作流程。
| 我想要... | 跳至 |
|---|---|
| 在合併前審查程式碼 | 工作流程 1:Code Review |
| 清理雜亂或舊有程式碼 | 工作流程 2:重構 |
| 追蹤並修復 bug | 工作流程 3:Debug |
| 為我的程式碼產生 test | 工作流程 4:Test 產生 |
| 撰寫更好的 commit 和 PR(Pull Request,拉取請求) | 工作流程 5:Git 整合 |
| 在撰寫程式碼前先做研究 | 小秘訣:在規劃或撰寫程式碼前先做研究 |
| 完整看一遍 bug 修復工作流程 | 統整練習 |
點選下方的工作流程以展開,看看 GitHub Copilot CLI 如何強化你在該領域的開發流程。
工作流程 1:Code Review — 審查檔案、使用 /review agent(代理程式)、建立嚴重性檢核清單
基本審查
此範例使用 @ 符號來參照檔案,讓 Copilot CLI 可以直接存取其內容進行審查。
copilot
> Review @samples/book-app-project/book_app.py for code quality
🎬 看看實際操作!

Demo 輸出結果會有所不同。你的模型、工具和回應將與此處顯示的內容有所差異。
輸入驗證審查
請 Copilot CLI 將審查重點放在特定的關注點上(此處為輸入驗證),在 prompt(提示詞)中列出你關心的類別。
copilot
> Review @samples/book-app-project/utils.py for input validation issues. Check for: missing validation, error handling gaps, and edge cases
跨檔案專案審查
使用 @ 參照整個目錄,讓 Copilot CLI 一次掃描專案中的所有檔案。
copilot
> @samples/book-app-project/ Review this entire project. Create a markdown checklist of issues found, categorized by severity
互動式 Code Review
使用多輪對話深入探討。先從廣泛的審查開始,然後提出後續問題,無需重新啟動。
copilot
> @samples/book-app-project/book_app.py Review this file for:
> - Input validation
> - Error handling
> - Code style and best practices
# Copilot CLI 提供詳細的審查結果
> The user input handling - are there any edge cases I'm missing?
# Copilot CLI 顯示空字串、特殊字元等潛在問題
> Create a checklist of all issues found, prioritized by severity
# Copilot CLI 產生按優先順序排列的行動項目
審查檢核清單範本
請 Copilot CLI 以特定格式組織其輸出(此處為可貼至 issue 的嚴重性分類 markdown 檢核清單)。
copilot
> Review @samples/book-app-project/ and create a markdown checklist of issues found, categorized by:
> - Critical (data loss risks, crashes)
> - High (bugs, incorrect behavior)
> - Medium (performance, maintainability)
> - Low (style, minor improvements)
理解 Git 變更(對 /review 很重要)
在使用 /review 指令之前,你需要瞭解 Git 中的兩種變更類型:
| 變更類型 | 含義 | 查看方式 |
|---|---|---|
| 已暫存的變更 | 你已使用 git add 標記為下次 commit 的檔案 | git diff --staged |
| 未暫存的變更 | 你已修改但尚未加入的檔案 | git diff |
# 快速參考
git status # 顯示已暫存和未暫存的變更
git add file.py # 將檔案暫存以準備 commit
git diff # 顯示未暫存的變更
git diff --staged # 顯示已暫存的變更
使用 /review 指令
/review 指令會呼叫內建的 code-review agent,它經過最佳化,能以高訊噪比的輸出來分析已暫存和未暫存的變更。使用 slash command(斜線指令)來觸發專門的內建 agent,而非撰寫自由格式的 prompt。
copilot
> /review
# 對已暫存/未暫存的變更呼叫 code-review agent
# 提供聚焦、可行動的回饋
> /review Check for security issues in authentication
# 以特定的重點領域執行 review
💡 提示:code-review agent 在你有待處理的變更時效果最佳。使用
git add暫存你的檔案以獲得更聚焦的審查。
工作流程 2:重構 — 重整程式碼結構、分離關注點、改善錯誤處理
簡單重構
先試試看:
@samples/book-app-project/book_app.py The command handling uses if/elif chains. Refactor it to use a dictionary dispatch pattern.
從簡單的改進開始。在 book app 上試試這些。每個 prompt 都使用 @ 檔案參照搭配特定的重構指令,讓 Copilot CLI 確切知道該修改什麼。
copilot
> @samples/book-app-project/book_app.py The command handling uses if/elif chains. Refactor it to use a dictionary dispatch pattern.
> @samples/book-app-project/utils.py Add type hints to all functions
> @samples/book-app-project/book_app.py Extract the book display logic into utils.py for better separation of concerns
💡 重構新手?先從簡單的請求開始,像是加入型別提示或改善變數名稱,然後再處理複雜的轉換。
🎬 看看實際操作!

Demo 輸出結果會有所不同。你的模型、工具和回應將與此處顯示的內容有所差異。
分離關注點
在單一 prompt 中使用 @ 參照多個檔案,讓 Copilot CLI 可以在重構過程中在檔案之間移動程式碼。
copilot
> @samples/book-app-project/utils.py @samples/book-app-project/book_app.py
> The utils.py file has print statements mixed with logic. Refactor to separate display functions from data processing.
改善錯誤處理
提供兩個相關檔案並描述跨越兩者的關注點,讓 Copilot CLI 能在兩者之間建議一致的修正方案。
copilot
> @samples/book-app-project/utils.py @samples/book-app-project/books.py
> These files have inconsistent error handling. Suggest a unified approach using custom exceptions.
新增說明文件
使用詳細的項目清單來精確指定每個 docstring 應包含的內容。
copilot
> @samples/book-app-project/books.py Add comprehensive docstrings to all methods:
> - Include parameter types and descriptions
> - Document return values
> - Note any exceptions raised
> - Add usage examples
搭配 Test 的安全重構
在多輪對話中串聯兩個相關的請求。先產生 test,然後在有 test 作為安全網的情況下進行重構。
copilot
> @samples/book-app-project/books.py Before refactoring, generate tests for current behavior
# 先取得 test
> Now refactor the BookCollection class to use a context manager for file operations
# 放心重構 - test 會驗證行為是否被保留
工作流程 3:Debug — 追蹤 bug、安全性稽核、跨檔案追蹤問題
簡單 Debug
先試試看:
@samples/book-app-buggy/books_buggy.py Users report that searching for "The Hobbit" returns no results even though it's in the data. Debug why.
從描述問題開始。以下是你可以在有 bug 的 book app 上嘗試的常見 debug 模式。每個 prompt 都將 @ 檔案參照搭配清楚的症狀描述,讓 Copilot CLI 能定位並診斷 bug。
copilot
# 模式:「預期 X 但得到 Y」
> @samples/book-app-buggy/books_buggy.py Users report that searching for "The Hobbit" returns no results even though it's in the data. Debug why.
# 模式:「非預期的行為」
> @samples/book-app-buggy/book_app_buggy.py When I remove a book that doesn't exist, the app says it was removed. Help me find why.
# 模式:「錯誤的結果」
> @samples/book-app-buggy/books_buggy.py When I mark one book as read, ALL books get marked. What's the bug?
💡 Debug 提示:描述症狀(你看到的)和預期結果(應該發生的)。Copilot CLI 會搞定其餘的。
🎬 看看實際操作!

Demo 輸出結果會有所不同。你的模型、工具和回應將與此處顯示的內容有所差異。
「Bug 偵探」— AI 找出相關的 Bug
這就是具備上下文感知的 debug 發揮作用的地方。在有 bug 的 book app 上試試這個情境。透過 @ 提供完整檔案並僅描述使用者回報的症狀。Copilot CLI 會追蹤根本原因,並可能發現附近的其他 bug。
copilot
> @samples/book-app-buggy/books_buggy.py
>
> Users report: "Finding books by author name doesn't work for partial names"
> Debug why this happens
Copilot CLI 的處理結果:
Root Cause: Line 80 uses exact match (==) instead of partial match (in).
Line 80: return [b for b in self.books if b.author == author]
The find_by_author function requires an exact match. Searching for "Tolkien"
won't find books by "J.R.R. Tolkien".
Fix: Change to case-insensitive partial match:
return [b for b in self.books if author.lower() in b.author.lower()]
為什麼這很重要:Copilot CLI 讀取整個檔案、理解你 bug 回報的上下文,並給你附帶清楚說明的具體修復方案。
💡 附加好處:因為 Copilot CLI 分析整個檔案,它經常會發現你沒有詢問的其他問題。例如,在修復作者搜尋時,Copilot CLI 也可能注意到
find_book_by_title中的大小寫敏感性 bug!
真實世界安全性補充
雖然 debug 自己的程式碼很重要,但理解正式環境應用程式中的安全性漏洞更為關鍵。試試這個範例:將 Copilot CLI 指向一個不熟悉的檔案,並要求它稽核安全性問題。
copilot
> @samples/buggy-code/python/user_service.py Find all security vulnerabilities in this Python user service
此檔案展示了你在正式環境應用程式中會遇到的真實安全性模式。
💡 你會遇到的常見安全性術語:
- SQL injection(SQL 注入):當使用者輸入直接放入資料庫查詢中,讓攻擊者能執行惡意命令
- 參數化查詢:安全的替代方案 - 佔位符(
?)將使用者資料與 SQL 命令分開
- 競爭條件:當兩個操作同時發生並互相干擾
- XSS(跨站腳本攻擊):當攻擊者將惡意腳本注入網頁
理解錯誤訊息
將堆疊追蹤直接貼入你的 prompt,並搭配 @ 檔案參照,讓 Copilot CLI 能將錯誤對應到原始碼。
copilot
> I'm getting this error:
> AttributeError: 'NoneType' object has no attribute 'title'
> at show_books (book_app.py:19)
>
> @samples/book-app-project/book_app.py Explain why and how to fix it
搭配測試案例的 Debug
描述確切的輸入和觀察到的輸出,給 Copilot CLI 一個具體、可重現的測試案例來推理。
copilot
> @samples/book-app-buggy/books_buggy.py The remove_book function has a bug. When I try to remove "Dune",
> it also removes "Dune Messiah". Debug this: explain the root cause and provide a fix.
跨程式碼追蹤問題
參照多個檔案並請 Copilot CLI 跨檔案追蹤資料流,以定位問題的源頭。
copilot
> Users report that the book list numbering starts at 0 instead of 1.
> @samples/book-app-buggy/book_app_buggy.py @samples/book-app-buggy/books_buggy.py
> Trace through the list display flow and identify where the issue occurs
理解資料問題
將資料檔案與讀取它的程式碼一起提供,讓 Copilot CLI 在建議錯誤處理改進時能理解完整的全貌。
copilot
> @samples/book-app-project/data.json @samples/book-app-project/books.py
> Sometimes the JSON file gets corrupted and the app crashes. How should we handle this gracefully?
工作流程 4:Test 產生 — 自動產生全面的 test 和邊界情況
先試試看:
@samples/book-app-project/books.py Generate pytest tests for all functions including edge cases
「Test 大爆炸」— 2 個 Test 對比 15 個以上的 Test
手動撰寫 test 時,開發者通常只建立 2-3 個基本的 test:
- 測試有效輸入
- 測試無效輸入
- 測試一個邊界情況
看看當你請 Copilot CLI 產生全面的 test 時會發生什麼!這個 prompt 使用帶有 @ 檔案參照的結構化項目清單,引導 Copilot CLI 達成全面的測試覆蓋率:
copilot
> @samples/book-app-project/books.py Generate comprehensive pytest tests. Include tests for:
> - Adding books
> - Removing books
> - Finding by title
> - Finding by author
> - Marking as read
> - Edge cases with empty data
🎬 看看實際操作!

Demo 輸出結果會有所不同。你的模型、工具和回應將與此處顯示的內容有所差異。
你會得到:15 個以上全面的 test,包括:
class TestBookCollection:
# 正常路徑
def test_add_book_creates_new_book(self):
...
def test_list_books_returns_all_books(self):
...
# 查詢操作
def test_find_book_by_title_case_insensitive(self):
...
def test_find_book_by_title_returns_none_when_not_found(self):
...
def test_find_by_author_partial_match(self):
...
def test_find_by_author_case_insensitive(self):
...
# 邊界情況
def test_add_book_with_empty_title(self):
...
def test_remove_nonexistent_book(self):
...
def test_mark_as_read_nonexistent_book(self):
...
# 資料持久化
def test_save_books_persists_to_json(self):
...
def test_load_books_handles_missing_file(self):
...
def test_load_books_handles_corrupted_json(self):
...
# 特殊字元
def test_add_book_with_unicode_characters(self):
...
def test_find_by_author_with_special_characters(self):
...
結果:在 30 秒內,你就得到了需要花一小時才能想到和撰寫的邊界情況 test。
單元測試
鎖定單一函式並列舉你想測試的輸入類別,讓 Copilot CLI 產生聚焦、全面的單元測試。
copilot
> @samples/book-app-project/utils.py Generate comprehensive pytest tests for get_book_details covering:
> - Valid input
> - Empty strings
> - Invalid year formats
> - Very long titles
> - Special characters in author names
執行 Test
向 Copilot CLI 用白話詢問你的工具鏈問題。它可以為你產生正確的 shell 指令。
copilot
> How do I run the tests? Show me the pytest command.
# Copilot CLI 回應:
# cd samples/book-app-project && python -m pytest tests/
# 或取得詳細輸出:python -m pytest tests/ -v
# 查看 print 輸出:python -m pytest tests/ -s
針對特定情境的 Test
列出你想涵蓋的進階或棘手情境,讓 Copilot CLI 超越正常路徑的測試。
copilot
> @samples/book-app-project/books.py Generate tests for these scenarios:
> - Adding duplicate books (same title and author)
> - Removing a book by partial title match
> - Finding books when collection is empty
> - File permission errors during save
> - Concurrent access to the book collection
將 Test 新增至現有檔案
要求為單一函式新增額外的 test,讓 Copilot CLI 產生與你現有測試互補的新案例。
copilot
> @samples/book-app-project/books.py
> Generate additional tests for the find_by_author function with edge cases:
> - Author name with hyphens (e.g., "Jean-Paul Sartre")
> - Author with multiple first names
> - Empty string as author
> - Author name with accented characters
工作流程 5:Git 整合 — Commit 訊息、PR 描述、/pr、/delegate 和 /diff
💡 本工作流程假設你具備基本的 Git 知識(暫存、commit、分支)。如果你對 Git 還不熟悉,建議先嘗試其他四個工作流程。
產生 Commit 訊息
先試試看:
copilot -p "Generate a conventional commit message for: $(git diff --staged)"— 暫存一些變更,然後執行此指令,看看 Copilot CLI 如何撰寫你的 commit 訊息。
此範例使用 -p 行內 prompt 旗標搭配 shell 指令替換,將 git diff 的輸出直接導入 Copilot CLI 以產生一次性的 commit 訊息。$(...) 語法會執行括號內的指令並將其輸出插入外部指令中。
# 查看變更了什麼
git diff --staged
# 使用 [Conventional Commit](../GLOSSARY.md#conventional-commit) 格式產生 commit 訊息
# (結構化的訊息如 "feat(books): add search" 或 "fix(data): handle empty input")
copilot -p "Generate a conventional commit message for: $(git diff --staged)"
# 輸出:"feat(books): add partial author name search
#
# - Update find_by_author to support partial matches
# - Add case-insensitive comparison
# - Improve user experience when searching authors"
🎬 看看實際操作!

Demo 輸出結果會有所不同。你的模型、工具和回應將與此處顯示的內容有所差異。
說明變更
將 git show 的輸出導入 -p prompt,以取得最近一次 commit 的白話摘要。
# 這次 commit 改了什麼?
copilot -p "Explain what this commit does: $(git show HEAD --stat)"
PR 描述
結合 git log 輸出與結構化的 prompt 範本,自動產生完整的 PR 描述。
# 從分支變更產生 PR 描述
copilot -p "Generate a pull request description for these changes:
$(git log main..HEAD --oneline)
Include:
- Summary of changes
- Why these changes were made
- Testing done
- Breaking changes? (yes/no)"
在互動模式中對目前分支使用 /pr
如果你在 Copilot CLI 的互動模式中處理某個分支,可以使用 /pr 指令來處理 Pull Request。使用 /pr 來查看 PR、建立新 PR、修復現有 PR,或讓 Copilot CLI 根據分支狀態自動決定。
copilot
> /pr [view|create|fix|auto]
推送前審查
在 -p prompt 中使用 git diff main..HEAD,對所有分支變更進行快速的推送前健全性檢查。
# 推送前的最後檢查
copilot -p "Review these changes for issues before I push:
$(git diff main..HEAD)"
使用 /delegate 進行背景任務
/delegate 指令將工作交給 GitHub Copilot 雲端 agent。使用 /delegate slash command(或 & 快捷鍵)將定義明確的任務交給背景 agent 處理。
copilot
> /delegate Add input validation to the login form
# 或使用 & 前綴快捷鍵:
> & Fix the typo in the README header
# Copilot CLI:
# 1. 將你的變更 commit 到新分支
# 2. 開啟一個 draft Pull Request
# 3. 在 GitHub 背景中工作
# 4. 完成後請求你的 review
這對於你想在專注於其他工作時完成的明確定義任務非常適合。
使用 /diff 審查 Session 變更
/diff 指令顯示你在目前 session(工作階段)期間所做的所有變更。使用此 slash command 在 commit 之前查看 Copilot CLI 已修改的所有內容的視覺化差異比對。
copilot
# 在做了一些變更之後...
> /diff
# 顯示此 session 中所有已修改檔案的視覺化差異比對
# 非常適合在 commit 前進行審查
小秘訣:在規劃或撰寫程式碼前先做研究
當你需要調查一個函式庫、瞭解最佳實踐或探索不熟悉的主題時,在撰寫任何程式碼之前使用 /research 進行深度研究調查:
copilot
> /research What are the best Python libraries for validating user input in CLI apps?
Copilot 搜尋 GitHub 儲存庫和網路資源,然後回傳附帶參考來源的摘要。這在你即將開始一個新功能並想先做出明智決策時非常有用。你可以使用 /share 分享結果。
💡 提示:
/research在/plan之前使用效果很好。先研究方法,然後再規劃實作。
統整練習:Bug 修復工作流程
以下是修復回報 bug 的完整工作流程:
# 1. 理解 bug 回報
copilot
> Users report: 'Finding books by author name doesn't work for partial names'
> @samples/book-app-project/books.py Analyze and identify the likely cause
# 2. Debug 問題(在同一個 session 中繼續)
> Based on the analysis, show me the find_by_author function and explain the issue
> Fix the find_by_author function to handle partial name matches
# 3. 為修復產生 test
> @samples/book-app-project/books.py Generate pytest tests specifically for:
> - Full author name match
> - Partial author name match
> - Case-insensitive matching
> - Author name not found
# 4. 產生 commit 訊息
copilot -p "Generate commit message for: $(git diff --staged)"
# 輸出:"fix(books): support partial author name search"
Bug 修復工作流程摘要
| 步驟 | 動作 | Copilot 命令 |
|---|---|---|
| 1 | 理解 bug | > [描述 bug] @relevant-file.py Analyze the likely cause |
| 2 | 取得詳細分析 | > Show me the function and explain the issue |
| 3 | 實作修復 | > Fix the [specific issue] |
| 4 | 產生 test | > Generate tests for [specific scenarios] |
| 5 | Commit | copilot -p "Generate commit message for: $(git diff --staged)" |
實作練習
現在輪到你來運用這些工作流程了。
▶️ 自己動手試試
完成示範後,試試這些變化練習:
- Bug 偵探挑戰:請 Copilot CLI debug
samples/book-app-buggy/books_buggy.py中的mark_as_read函式。它有解釋為什麼這個函式會將所有書籍標記為已讀,而不是只標記一本嗎?
- Test 挑戰:為 book app 中的
add_book函式產生 test。數數看 Copilot CLI 包含了多少你想不到的邊界情況。
- Commit 訊息挑戰:對 book app 的任何檔案做一個小修改,暫存它(
git add .),然後執行:
```bash
copilot -p "Generate a conventional commit message for: $(git diff --staged)"
```
產生的訊息比你快速撰寫的更好嗎?
自我檢核:當你能解釋為什麼「debug this bug」比「find bugs」更強大時(上下文很重要!),你就理解開發工作流程了。
📝 作業
主要挑戰:重構、測試和交付
實作範例著重在 find_book_by_title 和 code review。現在在 book-app-project 中的不同函式上練習相同的工作流程技能:
- Review:請 Copilot CLI 審查
books.py中的remove_book()的邊界情況和潛在問題:
@samples/book-app-project/books.py Review the remove_book() function. What happens if the title partially matches another book (e.g., "Dune" vs "Dune Messiah")? Are there any edge cases not handled?
- 重構:請 Copilot CLI 改善
remove_book(),處理大小寫不敏感匹配等邊界情況,並在找不到書籍時回傳有用的回饋 - Test:專門為改善後的
remove_book()函式產生 pytest test,涵蓋:
- 移除一本存在的書
- 大小寫不敏感的標題匹配
- 不存在的書回傳適當的回饋
- 從空集合中移除
- Review:暫存你的變更並執行
/review以檢查是否有任何剩餘問題 - Commit:產生一個 conventional commit 訊息:
copilot -p "Generate a conventional commit message for: $(git diff --staged)"
💡 提示(點擊展開)
每個步驟的範例 prompt:
copilot
# 步驟 1:Review
> @samples/book-app-project/books.py Review the remove_book() function. What edge cases are not handled?
# 步驟 2:重構
> Improve remove_book() to use case-insensitive matching and return a clear message when the book isn't found. Show me the before and after code.
# 步驟 3:Test
> Generate pytest tests for the improved remove_book() function, including:
> - Removing a book that exists
> - Case-insensitive matching ("dune" should remove "Dune")
> - Book not found returns appropriate response
> - Removing from an empty collection
# 步驟 4:Review
> /review
# 步驟 5:Commit
> Generate a conventional commit message for this refactor
提示:在改善 remove_book() 之後,試著問 Copilot CLI:「Are there any other functions in this file that could benefit from the same improvements?」。它可能會建議對 find_book_by_title() 或 find_by_author() 做類似的改進。
額外挑戰:使用 Copilot CLI 建立應用程式
💡 注意:這個 GitHub Skills 練習使用的是 Node.js 而非 Python。你將練習的 GitHub Copilot CLI 技巧 — 建立 issue、產生程式碼以及從終端機協作 — 適用於任何語言。
此練習向開發者展示如何使用 GitHub Copilot CLI 在建構 Node.js 計算機應用程式的同時,建立 issue、產生程式碼並從終端機進行協作。你將安裝 CLI、使用範本和 agent,並練習迭代式、命令列驅動的開發。
<img src="../images/github-skills-logo.png" width="28" align="center" /> 開始「使用 Copilot CLI 建立應用程式」Skills 練習
🔧 常見錯誤與疑難排解(點擊展開)
常見錯誤
| 錯誤 | 發生什麼事 | 修正方式 |
|---|---|---|
| 使用模糊的 prompt 如「Review this code」 | 得到通用的回饋,遺漏具體問題 | 要具體:「Review for SQL injection, XSS, and auth issues」 |
沒有使用 /review 進行 code review | 錯過了最佳化的 code-review agent | 使用 /review,它針對高訊噪比輸出進行了調校 |
| 要求「find bugs」但沒有提供上下文 | Copilot CLI 不知道你遇到了什麼 bug | 描述症狀:「Users report X happens when Y」 |
| 產生 test 時沒有指定框架 | test 可能使用錯誤的語法或斷言函式庫 | 指定:「Generate tests using Jest」或「using pytest」 |
疑難排解
Review 似乎不完整 — 對要查找的內容更加具體:
copilot
# 不要這樣:
> Review @samples/book-app-project/book_app.py
# 改為這樣:
> Review @samples/book-app-project/book_app.py for input validation, error handling, and edge cases
Test 不符合我的框架 — 指定框架:
copilot
> @samples/book-app-project/books.py Generate tests using pytest (not unittest)
重構改變了行為 — 請 Copilot CLI 保留行為:
copilot
> @samples/book-app-project/book_app.py Refactor command handling to use dictionary dispatch. IMPORTANT: Maintain identical external behavior - no breaking changes
總結
🔑 重點摘要
- Code review 透過具體的 prompt 變得全面
- 重構在你先產生 test 時更安全
- Debug 受益於同時向 Copilot CLI 展示錯誤和程式碼
- Test 產生應包含邊界情況和錯誤情境
- Git 整合自動化 commit 訊息和 PR 描述
📋 快速參考:請見 GitHub Copilot CLI 命令參考 取得完整的命令和快捷鍵清單。
✅ 檢查點:你已精通基礎知識
恭喜!你現在已擁有使用 GitHub Copilot CLI 提高生產力所需的所有核心技能:
| 技能 | 章節 | 你現在可以... |
|---|---|---|
| 基本命令 | 第 01 章 | 使用互動模式、plan 模式、程式化模式(-p)和 slash command |
| 上下文 | 第 02 章 | 使用 @ 參照檔案、管理 session、理解 context window |
| 工作流程 | 第 03 章 | 進行 code review、重構、debug、產生 test、與 Git 整合 |
第 04-06 章涵蓋了額外功能,能增添更多威力,值得學習。
🛠️ 建立你的個人工作流程
使用 GitHub Copilot CLI 沒有單一的「正確」方式。以下是你在發展自己模式時的一些提示:
📚 官方文件:Copilot CLI 最佳實踐 取得 GitHub 推薦的工作流程和提示。
- 對任何非瑣碎的事情從
/plan開始。在執行前精煉計畫 — 好的計畫帶來更好的結果。 - 儲存效果好的 prompt。當 Copilot CLI 犯錯時,記下哪裡出了問題。隨著時間推移,這會成為你的個人操作手冊。
- 自由實驗。有些開發者偏好長而詳細的 prompt。其他人偏好簡短的 prompt 搭配後續追問。嘗試不同的方法,注意什麼感覺最自然。
💡 即將登場:在第 04 章和第 05 章中,你將學習如何將最佳實踐編入 Copilot CLI 自動載入的自訂指令和 skill(技能)。
➡️ 下一步
其餘章節涵蓋擴展 Copilot CLI 功能的額外特性:
| 章節 | 涵蓋內容 | 你何時會需要 |
|---|---|---|
| 第 04 章:Agent | 建立專門的 AI 角色 | 當你想要領域專家(前端、安全性) |
| 第 05 章:Skill | 為任務自動載入指令 | 當你經常重複相同的 prompt |
| 第 06 章:MCP(模型上下文協定) | 連接外部服務 | 當你需要來自 GitHub、資料庫的即時資料 |
建議:先用核心工作流程一週,然後在有具體需求時再回來學習第 04-06 章。
繼續進入額外主題
在第 04 章:Agent 與自訂指令中,你將學習:
- 使用內建 agent(
/plan、/review) - 使用
.agent.md檔案建立專門的 agent(前端專家、安全性稽核員) - 多 agent 協作模式
- 用於專案標準的自訂指令檔案
第四章 自訂 Agent

如果你能同時聘請一位 Python 程式碼審查員、測試專家和資安審查員……而且全部整合在一個工具裡呢?
在第三章中,你已精通核心工作流程:程式碼審查、重構、除錯、test 產生,以及 Git 整合。這些讓你在使用 GitHub Copilot CLI (命令列介面) 時大幅提升生產力。現在,讓我們更進一步。
到目前為止,你一直將 Copilot CLI 當作通用助理來使用。Agent (代理程式) 能讓你賦予它特定角色與內建標準——例如一個會強制要求型別提示和 PEP 8 的程式碼審查員,或一個會撰寫 pytest 測試案例的測試助手。你將看到同樣的 prompt (提示詞) 在經由具有針對性指令的 agent 處理後,會產生明顯更好的結果。
🎯 學習目標
完成本章後,你將能夠:
- 使用內建 agent:Plan (
/plan)、Code-review (/review),以及瞭解自動化 agent(Explore、Task) - 使用 agent 檔案 (
.agent.md) 建立專門化的 agent - 針對特定領域的任務使用 agent
- 透過
/agent和--agent切換不同的 agent - 撰寫自訂指令檔案 (custom instruction files),用於專案特定的標準
⏱️ 預估時間:約 55 分鐘(20 分鐘閱讀 + 35 分鐘實作)
🧩 現實世界的類比:聘請專家
當你的房子需要維修時,你不會只找一個「萬能工人」。你會找專家:
| 問題 | 專家 | 原因 |
|---|---|---|
| 水管漏水 | 水管工 | 熟悉水管法規,擁有專業工具 |
| 重新配線 | 電工 | 瞭解安全規範,符合法規 |
| 新屋頂 | 屋頂工 | 熟悉建材,瞭解當地氣候考量 |
Agent 的運作方式如出一轍。與其使用通用 AI,不如使用專注於特定任務且知道正確流程的 agent。只需設定一次指令,之後每當你需要該專業時即可重複使用:程式碼 review、測試、資安、文件撰寫。
使用 Agent
立即開始使用內建和自訂 agent。
Agent 新手? 從這裡開始!
從未使用或建立過 agent?以下是本課程所需的全部入門知識。
- 立刻試試內建 agent:
```bash
copilot
/plan Add input validation for book year in the book app
```
這會呼叫 Plan agent 來建立逐步的實作計畫。
- 看看我們的自訂 agent 範例: 定義 agent 的指令非常簡單,查看我們提供的 python-reviewer.agent.md 檔案即可瞭解其模式。
- 理解核心概念: Agent 就像諮詢專家而非通才。一個「前端 agent」會自動聚焦於無障礙設計和元件模式——你不需要每次提醒它,因為這些已經寫在 agent 的指令中了。
內建 Agent
你在第三章開發工作流程中已經使用過一些內建 agent 了!
`/plan` 和 `/review` 其實就是內建 agent。現在你知道底層是如何運作的了。以下是完整清單:
| Agent | 如何呼叫 | 功能說明 |
|---|---|---|
| Plan | /plan 或 Shift+Tab(切換模式) | 在撰寫程式碼前建立逐步實作計畫 |
| Code-review | /review | 審查已暫存/未暫存的變更,提供聚焦且可操作的回饋 |
| Init | /init | 產生專案組態檔(指令、agent) |
| Explore | 自動觸發 | 當你要求 Copilot 探索或分析程式碼庫時,內部自動使用 |
| Task | 自動觸發 | 執行 test、建置、lint 檢查及相依套件安裝等指令 |
內建 agent 實戰範例 - Plan、Code-review、Explore 和 Task 的呼叫範例
copilot
# 呼叫 Plan agent 建立實作計畫
> /plan Add input validation for book year in the book app
# 呼叫 Code-review agent 審查你的變更
> /review
# Explore 和 Task agent 會在相關時自動呼叫:
> Run the test suite # 使用 Task agent
> Explore how book data is loaded # 使用 Explore agent
那 Task Agent 呢?它在幕後運作,管理和追蹤正在執行的工作,並以簡潔清晰的格式回報結果:
| 結果 | 你會看到什麼 |
|---|---|
| ✅ 成功 | 簡短摘要(例如「All 247 tests passed」、「Build succeeded」) |
| ❌ 失敗 | 完整輸出,包含堆疊追蹤、編譯器錯誤和詳細日誌 |
📚 官方文件:GitHub Copilot CLI Agents
將 Agent 加入 Copilot CLI
你可以輕鬆定義自己的 agent 並融入工作流程!只需定義一次,即可直接調度!
🗂️ 新增你的 agent
Agent 檔案是副檔名為 .agent.md 的 Markdown 檔案。它們包含兩個部分:YAML 前置資料 (frontmatter)(中繼資料)和 Markdown 指令。
💡 YAML 前置資料是什麼? 它是檔案頂端的一小段設定區塊,由
---標記包圍。YAML 就是key: value的鍵值對。檔案的其餘部分是一般的 Markdown。
以下是一個最簡 agent:
---
name: my-reviewer
description: Code reviewer focused on bugs and security issues
---
# Code Reviewer
You are a code reviewer focused on finding bugs and security issues.
When reviewing code, always check for:
- SQL injection vulnerabilities
- Missing error handling
- Hardcoded secrets
💡 必填 vs 選填:
description欄位為必填。其他欄位如name、tools和model為選填。
放置 agent 檔案的位置
| 位置 | 作用範圍 | 最適用於 |
|---|---|---|
.github/agents/ | 專案特定 | 團隊共享的 agent,包含專案慣例 |
~/.copilot/agents/ | 全域(所有專案) | 你在任何專案都會使用的個人 agent |
本專案在 .github/agents/ 資料夾中包含了範例 agent 檔案。你可以自行撰寫,或客製化已提供的範例。
📂 查看本課程的範例 agent
| 檔案 | 說明 |
|---|---|
hello-world.agent.md | 最簡範例 - 從這裡開始 |
python-reviewer.agent.md | Python 程式碼品質審查員 |
pytest-helper.agent.md | pytest 測試專家 |
# 或將其複製到你的個人 agent 資料夾(所有專案皆可使用)
cp .github/agents/python-reviewer.agent.md ~/.copilot/agents/
更多社群 agent 請參閱 github/awesome-copilot
🚀 使用自訂 agent 的兩種方式
互動模式
在互動模式中,使用 /agent 列出 agent 並選擇要使用的 agent。
選擇一個 agent 來繼續你的對話。
copilot
> /agent
要切換到其他 agent 或返回預設模式,再次使用 /agent 指令即可。
程式化模式
直接以指定的 agent 啟動新的 session (工作階段)。
copilot --agent python-reviewer
> Review @samples/book-app-project/books.py
💡 切換 agent:你可以隨時透過
/agent或--agent切換到不同的 agent。要回到標準 Copilot CLI 體驗,使用/agent並選擇 no agent。
深入探討 Agent
💡 本節為選讀。 內建 agent(
/plan、/review)對大多數工作流程已經足夠強大。當你需要在工作中持續應用專門化的專業知識時,再建立自訂 agent。
以下各主題皆為獨立內容。挑選你感興趣的部分即可——不需要一次全部讀完。
| 我想要... | 跳至 |
|---|---|
| 瞭解為什麼 agent 比通用 prompt 更好 | 專家 vs 通用 |
| 在一個功能中組合多個 agent | 使用多個 Agent 協作 |
| 整理、命名和分享 agent | 整理與分享 Agent |
| 設定始終啟用的專案情境 | 為 Copilot 設定你的專案 |
| 查詢 YAML 屬性和工具 | Agent 檔案參考 |
選擇下方的情境來展開。
專家 vs 通用:看看差異 - 為什麼 agent 比通用 prompt 產出更好的結果
專家 vs 通用:看看差異
這正是 agent 展現價值之處。看看差別:
沒有 Agent(通用 Copilot)
copilot
> Add a function to search books by year range in the book app
通用輸出:
def search_by_year_range(books, start_year, end_year):
results = []
for book in books:
if book['year'] >= start_year and book['year'] <= end_year:
results.append(book)
return results
基本功能。能用。但缺少很多東西。
使用 Python Reviewer Agent
copilot
> /agent
# 選擇 "python-reviewer"
> Add a function to search books by year range in the book app
專家輸出:
from typing import List, Dict, Any
def search_by_year_range(
books: List[Dict[str, Any]],
start_year: int,
end_year: int
) -> List[Dict[str, Any]]:
"""
Search for books within a specified year range.
Args:
books: List of book dictionaries
start_year: Starting year (inclusive)
end_year: Ending year (inclusive)
Returns:
List of books published within the year range
Raises:
ValueError: If start_year is greater than end_year
TypeError: If year values are not integers
"""
if not isinstance(start_year, int) or not isinstance(end_year, int):
raise TypeError("Year values must be integers")
if start_year > end_year:
raise ValueError(f"Start year ({start_year}) cannot be greater than end year ({end_year})")
return [
book for book in books
if isinstance(book.get('year'), int)
and start_year <= book['year'] <= end_year
]
python-reviewer agent 自動加入的內容:
- ✅ 所有參數和回傳值都有型別提示
- ✅ 完整的 docstring,包含 Args/Returns/Raises
- ✅ 具備適當錯誤處理的輸入驗證
- ✅ 使用串列推導式 (list comprehension) 以提升效能
- ✅ 邊界情況處理(缺少或無效的年份值)
- ✅ 符合 PEP 8 格式規範
- ✅ 防禦性程式設計實踐
差別所在:相同的 prompt,大幅改善的輸出。Agent 帶來了你可能忘記要求的專業知識。
使用多個 Agent 協作 - 組合專家、中途切換、agent 作為工具
使用多個 Agent 協作
真正的威力來自於多位專家在同一功能上協同工作。
範例:構建一個簡單功能
copilot
> I want to add a "search by year range" feature to the book app
# 使用 python-reviewer 進行設計
> /agent
# 選擇 "python-reviewer"
> @samples/book-app-project/books.py Design a find_by_year_range method. What's the best approach?
# 切換到 pytest-helper 進行測試設計
> /agent
# 選擇 "pytest-helper"
> @samples/book-app-project/tests/test_books.py Design test cases for a find_by_year_range method.
> What edge cases should we cover?
# 綜合兩邊的設計
> Create an implementation plan that includes the method implementation and comprehensive tests.
關鍵洞察:你是指揮專家的架構師。他們處理細節,你掌握全局。
🎬 看看實際操作!

示範輸出可能不同——你的模型、工具和回應會與此處顯示的有所差異。
Agent 作為工具
當 agent 已設定好時,Copilot 也可以在執行複雜任務時將它們作為工具呼叫。如果你要求實作一個全端功能,Copilot 可能會自動將各部分委派給適當的專家 agent。
整理與分享 Agent - 命名、檔案放置、指令檔案和團隊分享
整理與分享 Agent
為你的 Agent 命名
建立 agent 檔案時,名稱很重要。它是你在 /agent 或 --agent 後要輸入的內容,也是你的隊友在 agent 清單中看到的名稱。
| ✅ 好的名稱 | ❌ 避免使用 |
|---|---|
frontend | my-agent |
backend-api | agent1 |
security-reviewer | helper |
react-specialist | code |
python-backend | assistant |
命名慣例:
- 使用小寫加連字號:
my-agent-name.agent.md - 包含領域名稱:
frontend、backend、devops、security - 需要時加上具體描述:
react-typescript而非單純的frontend
與團隊分享
將 agent 檔案放在 .github/agents/ 中,它們就會被版本控制。推送到你的 repo 後,每個團隊成員都會自動獲得。但 agent 只是 Copilot 從你的專案中讀取的檔案類型之一。它還支援指令檔案 (instruction files),這些會自動套用於每個 session,不需要任何人執行 /agent。
可以這樣理解:agent 是你按需呼叫的專家,而指令檔案是始終生效的團隊規範。
檔案放置位置
你已經知道兩個主要位置了(參見上方的放置 agent 檔案的位置)。使用此決策樹來選擇:
從簡單開始: 在你的專案資料夾中建立一個 *.agent.md 檔案。滿意後再移到永久位置。
除了 agent 檔案之外,Copilot 還會自動讀取專案層級的指令檔案——不需要 /agent。有關 AGENTS.md、.instructions.md 和 /init 的詳細說明,請參見下方的為 Copilot 設定你的專案。
為 Copilot 設定你的專案 - AGENTS.md、指令檔案和 /init 設定
為 Copilot 設定你的專案
Agent 是你按需呼叫的專家。專案組態檔則不同:Copilot 會在每個 session 中自動讀取它們,以瞭解你的專案慣例、技術堆疊和規範。不需要任何人執行 /agent——對在此 repo 工作的所有人,這些情境始終處於啟用狀態。
使用 /init 快速設定
最快的入門方式是讓 Copilot 為你產生組態檔:
copilot
> /init
Copilot 會掃描你的專案並建立量身打造的指令檔案。你可以之後再進行編輯。
指令檔案格式
| 檔案 | 作用範圍 | 備註 |
|---|---|---|
AGENTS.md | 專案根目錄或子目錄 | 跨平台標準 - 可搭配 Copilot 和其他 AI 助理使用 |
.github/copilot-instructions.md | 專案 | GitHub Copilot 專用 |
.github/instructions/*.instructions.md | 專案 | 細粒度、按主題分類的指令 |
CLAUDE.md、GEMINI.md | 專案根目錄 | 為相容性而支援 |
🎯 剛入門? 使用
AGENTS.md作為專案指令。之後有需要時再探索其他格式。
AGENTS.md
AGENTS.md 是推薦的格式。它是一個開放標準,適用於 Copilot 和其他 AI 程式碼工具。將它放在你的 repo 根目錄,Copilot 就會自動讀取。本專案自身的 AGENTS.md 就是一個實際運作的範例。
一個典型的 AGENTS.md 會描述你的專案情境、程式碼風格、資安要求和測試標準。使用 /init 來產生一個,或參照我們範例檔案中的模式自行撰寫。
自訂指令檔案 (.instructions.md)
對於需要更細粒度控制的團隊,可將指令拆分為按主題分類的檔案。每個檔案涵蓋一項關注點並自動套用:
.github/
└── instructions/
├── python-standards.instructions.md
├── security-checklist.instructions.md
└── api-design.instructions.md
💡 注意:指令檔案可搭配任何程式語言使用。此範例使用 Python 以配合我們的課程專案,但你可以為 TypeScript、Go、Rust 或團隊使用的任何技術建立類似的檔案。
尋找社群指令檔案:瀏覽 github/awesome-copilot,可找到涵蓋 .NET、Angular、Azure、Python、Docker 等眾多技術的現成指令檔案。
停用自訂指令
如果你需要讓 Copilot 忽略所有專案特定的組態(適用於 debug 或比較行為差異時):
copilot --no-custom-instructions
Agent 檔案參考 - YAML 屬性、工具別名和完整範例
Agent 檔案參考
更完整的範例
你已經在上方看過最簡 agent 格式。以下是一個使用 tools 屬性的更完整 agent。建立 ~/.copilot/agents/python-reviewer.agent.md:
---
name: python-reviewer
description: Python code quality specialist for reviewing Python projects
tools: ["read", "edit", "search", "execute"]
---
# Python Code Reviewer
You are a Python specialist focused on code quality and best practices.
**Your focus areas:**
- Code quality (PEP 8, type hints, docstrings)
- Performance optimization (list comprehensions, generators)
- Error handling (proper exception handling)
- Maintainability (DRY principles, clear naming)
**Code style requirements:**
- Use Python 3.10+ features (dataclasses, type hints, pattern matching)
- Follow PEP 8 naming conventions
- Use context managers for file I/O
- All functions must have type hints and docstrings
**When reviewing code, always check:**
- Missing type hints on function signatures
- Mutable default arguments
- Proper error handling (no bare except)
- Input validation completeness
YAML 屬性
| 屬性 | 是否必填 | 說明 |
|---|---|---|
name | 否 | 顯示名稱(預設使用檔案名稱) |
description | 是 | agent 的功能描述 - 幫助 Copilot 瞭解何時建議使用它 |
tools | 否 | 允許使用的工具清單(省略 = 所有工具皆可用)。參見下方工具別名。 |
target | 否 | 限定僅用於 vscode 或 github-copilot |
工具別名
在 tools 清單中使用這些名稱:
read- 讀取檔案內容edit- 編輯檔案search- 搜尋檔案(grep/glob)execute- 執行 shell 指令(也可使用:shell、Bash)agent- 呼叫其他自訂 agent
📖 官方文件:Custom agents configuration
⚠️ 僅限 VS Code:
model屬性(用於選擇 AI 模型)在 VS Code 中可用,但 GitHub Copilot CLI 不支援。你可以放心地將它包含在跨平台的 agent 檔案中。GitHub Copilot CLI 會忽略它。
更多 Agent 範本
💡 給初學者的說明:以下範例都是範本。請將特定技術替換為你的專案所使用的技術。 重要的是 agent 的結構,而非其中提到的特定技術。
本專案在 .github/agents/ 資料夾中包含可運作的範例:
- hello-world.agent.md - 最簡範例,從這裡開始
- python-reviewer.agent.md - Python 程式碼品質審查員
- pytest-helper.agent.md - pytest 測試專家
更多社群 agent 請參閱 github/awesome-copilot。
練習
建立你自己的 agent 並看它們實際運作。
▶️ 自己試試看
# 建立 agents 目錄(如果不存在的話)
mkdir -p .github/agents
# 建立一個程式碼審查員 agent
cat > .github/agents/reviewer.agent.md << 'EOF'
---
name: reviewer
description: Senior code reviewer focused on security and best practices
---
# Code Reviewer Agent
You are a senior code reviewer focused on code quality.
**Review priorities:**
1. Security vulnerabilities
2. Performance issues
3. Maintainability concerns
4. Best practice violations
**Output format:**
Provide issues as a numbered list with severity tags:
[CRITICAL], [HIGH], [MEDIUM], [LOW]
EOF
# 建立一個文件撰寫 agent
cat > .github/agents/documentor.agent.md << 'EOF'
---
name: documentor
description: Technical writer for clear and complete documentation
---
# Documentation Agent
You are a technical writer who creates clear documentation.
**Documentation standards:**
- Start with a one-sentence summary
- Include usage examples
- Document parameters and return values
- Note any gotchas or limitations
EOF
# 現在來使用它們
copilot --agent reviewer
> Review @samples/book-app-project/books.py
# 或切換 agent
copilot
> /agent
# 選擇 "documentor"
> Document @samples/book-app-project/books.py
📝 作業
主要挑戰:建立一個專家 Agent 團隊
實作範例已建立了 reviewer 和 documentor agent。現在練習為不同任務建立和使用 agent——改進書籍應用程式中的資料驗證:
- 建立 3 個 agent 檔案 (
.agent.md),專為書籍應用程式量身打造,每個 agent 一個檔案,放在.github/agents/ - 你的 agent:
- data-validator:檢查
data.json中缺失或格式不正確的資料(空的作者欄位、year=0、缺少欄位) - error-handler:審查 Python 程式碼中不一致的錯誤處理,並建議統一的方法
- doc-writer:產生或更新 docstring 和 README 內容
- 在書籍應用程式中使用每個 agent:
data-validator→ 稽核@samples/book-app-project/data.jsonerror-handler→ 審查@samples/book-app-project/books.py和@samples/book-app-project/utils.pydoc-writer→ 為@samples/book-app-project/books.py加入 docstring
- 協作:使用
error-handler找出錯誤處理的缺口,再用doc-writer記錄改進後的方法
成功標準:你有 3 個可運作的 agent,能產出一致、高品質的輸出,且你可以使用 /agent 在它們之間切換。
💡 提示(點擊展開)
入門範本:在 .github/agents/ 中為每個 agent 建立一個檔案:
data-validator.agent.md:
---
description: Analyzes JSON data files for missing or malformed entries
---
You analyze JSON data files for missing or malformed entries.
**Focus areas:**
- Empty or missing author fields
- Invalid years (year=0, future years, negative years)
- Missing required fields (title, author, year, read)
- Duplicate entries
error-handler.agent.md:
---
description: Reviews Python code for error handling consistency
---
You review Python code for error handling consistency.
**Standards:**
- No bare except clauses
- Use custom exceptions where appropriate
- All file operations use context managers
- Consistent return types for success/failure
doc-writer.agent.md:
---
description: Technical writer for clear Python documentation
---
You are a technical writer who creates clear Python documentation.
**Standards:**
- Google-style docstrings
- Include parameter types and return values
- Add usage examples for public methods
- Note any exceptions raised
測試你的 agent:
💡 注意: 你的本機 repo 副本中應已有
samples/book-app-project/data.json。如果缺少,請從原始 repo 下載原版:
copilot
> /agent
# 從清單中選擇 "data-validator"
> @samples/book-app-project/data.json Check for books with empty author fields or invalid years
提醒: YAML 前置資料中的 description 欄位是 agent 正常運作所必需的。
進階挑戰:指令庫
你已經建立了按需呼叫的 agent。現在試試另一面:指令檔案——Copilot 會在每個 session 中自動讀取,不需要 /agent。
建立一個 .github/instructions/ 資料夾,至少包含 3 個指令檔案:
python-style.instructions.md:用於強制執行 PEP 8 和型別提示慣例test-standards.instructions.md:用於在測試檔案中強制執行 pytest 慣例data-quality.instructions.md:用於驗證 JSON 資料條目
在書籍應用程式的程式碼上測試每個指令檔案。
🔧 常見錯誤與疑難排解(點擊展開)
常見錯誤
| 錯誤 | 會發生什麼 | 修正方式 |
|---|---|---|
agent 前置資料中缺少 description | Agent 無法載入或無法被發現 | 務必在 YAML 前置資料中包含 description: |
| agent 的檔案位置錯誤 | 嘗試使用時找不到 agent | 放在 ~/.copilot/agents/(個人)或 .github/agents/(專案) |
使用 .md 而非 .agent.md | 檔案可能不會被識別為 agent | 將檔案命名為如 python-reviewer.agent.md |
| agent prompt 過長 | 可能超過 30,000 字元限制 | 保持 agent 定義聚焦;對詳細指令使用 skill |
疑難排解
找不到 Agent - 檢查 agent 檔案是否存在於以下位置之一:
~/.copilot/agents/.github/agents/
列出可用的 agent:
copilot
> /agent
# 顯示所有可用的 agent
Agent 不遵循指令 - 在你的 prompt 中更明確,並在 agent 定義中加入更多細節:
- 指定框架/函式庫及其版本
- 團隊慣例
- 範例程式碼模式
自訂指令未載入 - 在你的專案中執行 /init 來設定專案特定的指令:
copilot
> /init
或檢查是否被停用了:
# 如果你想要載入自訂指令,請勿使用 --no-custom-instructions
copilot # 預設會載入自訂指令
總結
🔑 關鍵要點
- 內建 agent:
/plan和/review可直接呼叫;Explore 和 Task 會自動運作 - 自訂 agent 是定義在
.agent.md檔案中的專家 - 好的 agent 具有清晰的專業領域、標準和輸出格式
- 多 agent 協作透過結合專業知識來解決複雜問題
- 指令檔案 (
.instructions.md) 將團隊標準編碼為自動套用的規範 - 一致的輸出來自於定義完善的 agent 指令
📋 快速參考:請參閱 GitHub Copilot CLI command reference 以取得完整的指令和快捷鍵清單。
➡️ 下一步
Agent 改變了 Copilot 如何針對性地處理和操作你的程式碼。接下來,你將學習 skill (技能)——它改變的是 Copilot 執行哪些步驟。好奇 agent 和 skill 有什麼不同?第五章會直接探討這個問題。
在 第五章:Skill 系統 中,你將學到:
- Skill 如何從你的 prompt 自動觸發(不需要 slash command)
- 安裝社群 skill
- 使用 SKILL.md 檔案建立自訂 skill
- Agent、skill 和 MCP 之間的差異
- 何時使用哪一個
第五章 Skill 技能

如果 Copilot 能自動套用你團隊的最佳實務,不必每次都重新解釋,那會怎樣?
在本章中,你將學習 Agent Skill(代理技能):一組指令資料夾,Copilot 會在與你的任務相關時自動載入。Agent 改變的是 Copilot 思考的方式,而 skill 則教導 Copilot 完成任務的特定方法。你將建立一個安全稽核 skill,讓 Copilot 在你詢問安全性問題時自動套用;建立團隊標準的審查標準以確保一致的程式碼品質;並學習 skill 如何跨 Copilot CLI、VS Code 和 GitHub Copilot 雲端 agent 運作。
🎯 學習目標
完成本章後,你將能夠:
- 了解 Agent Skill 的運作方式及使用時機
- 使用 SKILL.md 檔案建立自訂 skill
- 使用來自共享儲存庫的社群 skill
- 知道何時該使用 skill、agent 或 MCP
⏱️ 預估時間:約 55 分鐘(20 分鐘閱讀 + 35 分鐘實作)
🧩 真實世界類比:電動工具
通用電鑽很實用,但專用的配件能讓它更強大。
Skill 的運作方式完全相同。就像為不同工作更換鑽頭一樣,你可以為不同任務為 Copilot 新增 skill:
| Skill 配件 | 用途 |
|---|---|
commit | 產生一致的 commit 訊息 |
security-audit | 檢查 OWASP 弱點 |
generate-tests | 建立完整的 pytest 測試 |
code-checklist | 套用團隊程式碼品質標準 |
Skill 是專門的配件,能擴展 Copilot 的功能
Skill 的運作方式
了解什麼是 skill、為什麼它們重要,以及它們與 agent 和 MCP 的差異。
初次接觸 Skill? 從這裡開始!
- 查看已有哪些 skill 可用:
```bash
copilot
/skills list
```
這會顯示 Copilot 在你的專案和個人資料夾中找到的所有 skill。
- 查看真實的 skill 檔案: 參考我們提供的 code-checklist SKILL.md 來了解格式。它只是 YAML frontmatter(前置資料)加上 markdown 指令。
- 了解核心概念: Skill 是任務專用的指令,當你的 prompt 與 skill 的描述相符時,Copilot 會自動載入。你不需要啟動它們,只要自然地提問即可。
了解 Skill
Agent Skill 是包含指令、腳本和資源的資料夾,Copilot 會在與你的任務相關時自動載入。Copilot 會讀取你的 prompt,檢查是否有任何 skill 符合,並自動套用相關指令。
copilot
> Check books.py against our quality checklist
# Copilot 偵測到這與你的「code-checklist」skill 相符
# 並自動套用其 Python 品質檢查清單
> Generate tests for the BookCollection class
# Copilot 載入你的「pytest-gen」skill
# 並套用你偏好的測試結構
> What are the code quality issues in this file?
# Copilot 載入你的「code-checklist」skill
# 並根據你團隊的標準進行檢查
💡 關鍵觀念:Skill 會根據你的 prompt 與 skill 描述的配對自動觸發。只要自然地提問,Copilot 就會在幕後套用相關的 skill。你也可以直接呼叫 skill,接下來會學到這部分。
🧰 即用模板:查看 .github/skills 資料夾,取得可直接複製貼上使用的 skill。
直接使用 Slash Command 呼叫
雖然自動觸發是 skill 的主要運作方式,你也可以使用 skill 名稱作為 slash command 直接呼叫 skill:
> /generate-tests Create tests for the user authentication module
> /code-checklist Check books.py for code quality issues
> /security-audit Check the API endpoints for vulnerabilities
這讓你在想確保使用特定 skill 時擁有明確的控制權。
📝 Skill 與 Agent 呼叫方式的差異:不要混淆 skill 呼叫和 agent 呼叫:
- Skill:
/skill-name <prompt>,例如/code-checklist Check this file
- Agent:
/agent(從清單中選擇)或copilot --agent <name>(命令列)
如果你同時有名為「code-reviewer」的 skill 和 agent,輸入
/code-reviewer會呼叫 skill,而非 agent。
如何知道 Skill 是否被使用?
你可以直接詢問 Copilot:
> What skills did you use for that response?
> What skills do you have available for security reviews?
Skill、Agent 與 MCP 的比較
Skill 只是 GitHub Copilot 擴充模型的一部分。以下是它們與 agent 和 MCP server 的比較。
先別擔心 MCP。我們會在 Chapter 06 中介紹。這裡列出來是為了讓你看到 skill 在整體架構中的位置。
| 功能 | 作用 | 使用時機 |
|---|---|---|
| Agent | 改變 AI 的思維方式 | 需要跨多種任務的專業知識 |
| Skill | 提供任務專用指令 | 具有詳細步驟的特定、可重複任務 |
| MCP | 連接外部服務 | 需要來自 API 的即時資料 |
使用 agent 取得廣泛的專業知識,使用 skill 取得特定的任務指令,使用 MCP 取得外部資料。一個 agent 可以在對話中使用一個或多個 skill。例如,當你要求 agent 檢查你的程式碼時,它可能會自動同時套用 security-audit skill 和 code-checklist skill。
📚 了解更多:參閱官方 About Agent Skills 文件,取得 skill 格式和最佳實務的完整參考。
從手動 Prompt 到自動化專業知識
在深入了解如何建立 skill 之前,先來看看為什麼值得學習它們。一旦你看到一致性帶來的收益,「如何做」就會更合理。
使用 Skill 之前:不一致的審查
每次程式碼審查,你可能會忘記某些事:
copilot
> Review this code for issues
# 通用審查——可能會遺漏你團隊特定的關注點
或者你每次都寫一長串 prompt:
> Review this code checking for bare except clauses, missing type hints,
> mutable default arguments, missing context managers for file I/O,
> functions over 50 lines, print statements in production code...
時間:30 秒以上才能打完。一致性:取決於記憶力。
使用 Skill 之後:自動化最佳實務
安裝了 code-checklist skill 後,只要自然地提問:
copilot
> Check the book collection code for quality issues
幕後發生的事:
- Copilot 看到你的 prompt 中有「code quality」和「issues」
- 檢查 skill 描述,發現你的
code-checklistskill 相符 - 自動載入你團隊的品質檢查清單
- 套用所有檢查項目,無需你逐一列出
只要自然地提問。Copilot 會將你的 prompt 配對到正確的 skill 並自動套用。
輸出:
## Code Checklist: books.py
### Code Quality
- [PASS] All functions have type hints
- [PASS] No bare except clauses
- [PASS] No mutable default arguments
- [PASS] Context managers used for file I/O
- [PASS] Functions are under 50 lines
- [PASS] Variable and function names follow PEP 8
### Input Validation
- [FAIL] User input is not validated - add_book() accepts any year value
- [FAIL] Edge cases not fully handled - empty strings accepted for title/author
- [PASS] Error messages are clear and helpful
### Testing
- [FAIL] No corresponding pytest tests found
### Summary
3 items need attention before merge
差異在於:你團隊的標準每次都會自動套用,不需要手動輸入。
🎬 看看實際效果!

示範輸出僅供參考。你的模型、工具和回應將與此處顯示的不同。
大規模的一致性:團隊 PR 審查 Skill
想像你的團隊有一份 10 項的 PR 檢查清單。沒有 skill 的話,每位開發者都必須記住全部 10 項,而且總有人會忘記其中一項。有了 pr-review skill,整個團隊都能得到一致的審查:
copilot
> Can you review this PR?
Copilot 會自動載入你團隊的 pr-review skill 並檢查全部 10 項:
PR Review: feature/user-auth
## Security ✅
- No hardcoded secrets
- Input validation present
- No bare except clauses
## Code Quality ⚠️
- [WARN] print statement on line 45 - remove before merge
- [WARN] TODO on line 78 missing issue reference
- [WARN] Missing type hints on public functions
## Testing ✅
- New tests added
- Edge cases covered
## Documentation ❌
- [FAIL] Breaking change not documented in CHANGELOG
- [FAIL] API changes need OpenAPI spec update
強大之處:每位團隊成員都會自動套用相同的標準。新進人員不需要背誦檢查清單,因為 skill 會處理這一切。
建立自訂 Skill
從 SKILL.md 檔案建立你自己的 skill。
Skill 的存放位置
Skill 存放在 .github/skills/(專案專用)或 ~/.copilot/skills/(使用者層級)。
Copilot 如何找到 Skill
Copilot 會自動掃描以下位置以找到 skill:
| 位置 | 範圍 |
|---|---|
.github/skills/ | 專案專用(透過 Git 與團隊共享) |
~/.copilot/skills/ | 使用者專用(你的個人 skill) |
Skill 結構
每個 skill 都位於自己的資料夾中,包含一個 SKILL.md 檔案。你可以選擇性地包含腳本、範例或其他資源:
.github/skills/
└── my-skill/
├── SKILL.md # 必要:Skill 定義和指令
├── examples/ # 選用:Copilot 可參考的範例檔案
│ └── sample.py
└── scripts/ # 選用:Skill 可使用的腳本
└── validate.sh
💡 提示:目錄名稱應與 SKILL.md frontmatter 中的
name一致(小寫加連字號)。
SKILL.md 格式
Skill 使用帶有 YAML frontmatter 的簡單 markdown 格式:
---
name: code-checklist
description: Comprehensive code quality checklist with security, performance, and maintainability checks
license: MIT
---
# Code Checklist
When checking code, look for:
## Security
- SQL injection vulnerabilities
- XSS vulnerabilities
- Authentication/authorization issues
- Sensitive data exposure
## Performance
- N+1 query problems (running one query per item instead of one query for all items)
- Unnecessary loops or computations
- Memory leaks
- Blocking operations
## Maintainability
- Function length (flag functions > 50 lines)
- Code duplication
- Missing error handling
- Unclear naming
## Output Format
Provide issues as a numbered list with severity:
- [CRITICAL] - Must fix before merge
- [HIGH] - Should fix before merge
- [MEDIUM] - Should address soon
- [LOW] - Nice to have
YAML 屬性:
| 屬性 | 必要 | 說明 |
|---|---|---|
name | 是 | 唯一識別碼(小寫,空格用連字號) |
description | 是 | Skill 的功能及 Copilot 何時應使用它 |
license | 否 | 適用於此 skill 的授權條款 |
📖 官方文件:About Agent Skills
建立你的第一個 Skill
讓我們建立一個檢查 OWASP Top 10 弱點的安全稽核 skill:
# 建立 skill 目錄
mkdir -p .github/skills/security-audit
# 建立 SKILL.md 檔案
cat > .github/skills/security-audit/SKILL.md << 'EOF'
---
name: security-audit
description: Security-focused code review checking OWASP (Open Web Application Security Project) Top 10 vulnerabilities
---
# Security Audit
Perform a security audit checking for:
## Injection Vulnerabilities
- SQL injection (string concatenation in queries)
- Command injection (unsanitized shell commands)
- LDAP injection
- XPath injection
## Authentication Issues
- Hardcoded credentials
- Weak password requirements
- Missing rate limiting
- Session management flaws
## Sensitive Data
- Plaintext passwords
- API keys in code
- Logging sensitive information
- Missing encryption
## Access Control
- Missing authorization checks
- Insecure direct object references
- Path traversal vulnerabilities
## Output
For each issue found, provide:
1. File and line number
2. Vulnerability type
3. Severity (CRITICAL/HIGH/MEDIUM/LOW)
4. Recommended fix
EOF
# 測試你的 skill(skill 會根據你的 prompt 自動載入)
copilot
> @samples/book-app-project/ Check this code for security vulnerabilities
# Copilot 偵測到「security vulnerabilities」與你的 skill 相符
# 並自動套用其 OWASP 檢查清單
預期輸出(你的結果會有所不同):
Security Audit: book-app-project
[HIGH] Hardcoded file path (book_app.py, line 12)
File path is hardcoded rather than configurable
Fix: Use environment variable or config file
[MEDIUM] No input validation (book_app.py, line 34)
User input passed directly to function without sanitization
Fix: Add input validation before processing
✅ No SQL injection found
✅ No hardcoded credentials found
撰寫良好的 Skill 描述
SKILL.md 中的 description 欄位至關重要!它是 Copilot 決定是否載入你的 skill 的依據:
---
name: security-audit
description: Use for security reviews, vulnerability scanning,
checking for SQL injection, XSS, authentication issues,
OWASP Top 10 vulnerabilities, and security best practices
---
💡 提示:包含與你自然提問方式相符的關鍵字。如果你會說「security review」,就在描述中包含「security review」。
將 Skill 與 Agent 結合使用
Skill 和 agent 可以搭配運作。Agent 提供專業知識,skill 提供具體指令:
# 使用 code-reviewer agent 開始
copilot --agent code-reviewer
> Check the book app for quality issues
# code-reviewer agent 的專業知識結合
# 你的 code-checklist skill 的檢查清單
管理與分享 Skill
探索已安裝的 skill、尋找社群 skill,以及分享你自己的 skill。
使用 /skills 指令管理 Skill
使用 /skills 指令來管理你已安裝的 skill:
| 指令 | 功能 |
|---|---|
/skills list | 顯示所有已安裝的 skill |
/skills info <name> | 取得特定 skill 的詳細資訊 |
/skills add <name> | 啟用 skill(來自儲存庫或市集) |
/skills remove <name> | 停用或解除安裝 skill |
/skills reload | 編輯 SKILL.md 檔案後重新載入 skill |
💡 請記住:你不需要為每個 prompt「啟動」skill。安裝後,skill 會在你的 prompt 與其描述相符時自動觸發。這些指令用於管理哪些 skill 可用,而非用於使用它們。
範例:查看你的 Skill
copilot
> /skills list
Available skills:
- security-audit: Security-focused code review checking OWASP Top 10
- generate-tests: Generate comprehensive unit tests with edge cases
- code-checklist: Team code quality checklist
...
> /skills info security-audit
Skill: security-audit
Source: Project
Location: .github/skills/security-audit/SKILL.md
Description: Security-focused code review checking OWASP Top 10 vulnerabilities
看看實際效果!

示範輸出僅供參考。你的模型、工具和回應將與此處顯示的不同。
何時使用 /skills reload
建立或編輯 skill 的 SKILL.md 檔案後,執行 /skills reload 即可套用變更,無需重新啟動 Copilot:
# 編輯你的 skill 檔案
# 然後在 Copilot 中:
> /skills reload
Skills reloaded successfully.
💡 小知識:即使使用
/compact摘要你的對話歷史後,skill 仍然有效。壓縮後不需要重新載入。
尋找和使用社群 Skill
使用外掛套件安裝 Skill
💡 什麼是外掛套件? 外掛套件(Plugin)是可安裝的套件,能將 skill、agent 和 MCP server 設定打包在一起。可以把它們想成 Copilot CLI 的「應用程式商店」擴充功能。
/plugin 指令可讓你瀏覽和安裝這些套件:
copilot
> /plugin list
# 顯示已安裝的外掛套件
> /plugin marketplace
# 瀏覽可用的外掛套件
> /plugin install <plugin-name>
# 從市集安裝外掛套件
外掛套件可以將多種功能打包在一起——單一外掛套件可能包含協同運作的相關 skill、agent 和 MCP server 設定。
社群 Skill 儲存庫
預製的 skill 也可從社群儲存庫取得:
- Awesome Copilot - 官方 GitHub Copilot 資源,包含 skill 文件和範例
手動安裝社群 Skill
如果你在 GitHub 儲存庫中找到一個 skill,將其資料夾複製到你的 skill 目錄中:
# 複製 awesome-copilot 儲存庫
git clone https://github.com/github/awesome-copilot.git /tmp/awesome-copilot
# 將特定 skill 複製到你的專案
cp -r /tmp/awesome-copilot/skills/code-checklist .github/skills/
# 或用於跨所有專案的個人使用
cp -r /tmp/awesome-copilot/skills/code-checklist ~/.copilot/skills/
⚠️ 安裝前先審查:在將 skill 複製到你的專案之前,務必先閱讀其
SKILL.md。Skill 控制 Copilot 的行為,惡意的 skill 可能會指示它執行有害的指令或以非預期的方式修改程式碼。
實作練習
透過建立和測試你自己的 skill 來實踐所學。
▶️ 自己動手試試
建立更多 Skill
以下是兩個展示不同模式的 skill。按照上面「建立你的第一個 Skill」中相同的 mkdir + cat 工作流程操作,或將 skill 複製貼上到正確的位置。更多範例可在 .github/skills 中找到。
pytest 測試產生 Skill
一個確保你的程式碼庫中 pytest 結構一致的 skill:
mkdir -p .github/skills/pytest-gen
cat > .github/skills/pytest-gen/SKILL.md << 'EOF'
---
name: pytest-gen
description: Generate comprehensive pytest tests with fixtures and edge cases
---
# pytest Test Generation
Generate pytest tests that include:
## Test Structure
- Use pytest conventions (test_ prefix)
- One assertion per test when possible
- Clear test names describing expected behavior
- Use fixtures for setup/teardown
## Coverage
- Happy path scenarios
- Edge cases: None, empty strings, empty lists
- Boundary values
- Error scenarios with pytest.raises()
## Fixtures
- Use @pytest.fixture for reusable test data
- Use tmpdir/tmp_path for file operations
- Mock external dependencies with pytest-mock
## Output
Provide complete, runnable test file with proper imports.
EOF
團隊 PR 審查 Skill
一個在你的團隊中強制執行一致 PR 審查標準的 skill:
mkdir -p .github/skills/pr-review
cat > .github/skills/pr-review/SKILL.md << 'EOF'
---
name: pr-review
description: Team-standard PR review checklist
---
# PR Review
Review code changes against team standards:
## Security Checklist
- [ ] No hardcoded secrets or API keys
- [ ] Input validation on all user data
- [ ] No bare except clauses
- [ ] No sensitive data in logs
## Code Quality
- [ ] Functions under 50 lines
- [ ] No print statements in production code
- [ ] Type hints on public functions
- [ ] Context managers for file I/O
- [ ] No TODOs without issue references
## Testing
- [ ] New code has tests
- [ ] Edge cases covered
- [ ] No skipped tests without explanation
## Documentation
- [ ] API changes documented
- [ ] Breaking changes noted
- [ ] README updated if needed
## Output Format
Provide results as:
- ✅ PASS: Items that look good
- ⚠️ WARN: Items that could be improved
- ❌ FAIL: Items that must be fixed before merge
EOF
更進一步
- Skill 建立挑戰:建立一個
quick-reviewskill,執行 3 項檢查:
- 裸 except 子句
- 缺少 type hints
- 不清楚的變數命名
測試方式:詢問「Do a quick review of books.py」
- Skill 比較:計時自己手動撰寫一個詳細的安全審查 prompt。然後只需要求「Check for security issues in this file」,讓你的 security-audit skill 自動載入。Skill 節省了多少時間?
- 團隊 Skill 挑戰:想想你團隊的程式碼審查清單。你能把它編碼成一個 skill 嗎?寫下這個 skill 應該始終檢查的 3 件事。
自我檢查:當你能解釋為什麼 description 欄位很重要時(它是 Copilot 決定是否載入你的 skill 的依據),就代表你已經理解 skill 了。
📝 作業
主要挑戰:建立 Book Summary Skill
上面的範例建立了 pytest-gen 和 pr-review skill。現在練習建立一個完全不同類型的 skill:用於從資料產生格式化輸出的 skill。
- 列出你目前的 skill:執行 Copilot 並輸入
/skills list。你也可以使用ls .github/skills/查看專案 skill,或ls ~/.copilot/skills/查看個人 skill。 - 在
.github/skills/book-summary/SKILL.md建立一個book-summaryskill,用於產生書籍收藏的格式化 markdown 摘要 - 你的 skill 應包含:
- 清晰的名稱和描述(描述對於配對至關重要!)
- 具體的格式規則(例如,包含標題、作者、年份、閱讀狀態的 markdown 表格)
- 輸出慣例(例如,使用 ✅/❌ 表示閱讀狀態,按年份排序)
- 測試 skill:
@samples/book-app-project/data.json Summarize the books in this collection - 透過檢查
/skills list驗證 skill 是否自動觸發 - 嘗試直接呼叫:
/book-summary Summarize the books in this collection
成功標準:你有一個可運作的 book-summary skill,Copilot 在你詢問書籍收藏時會自動套用。
💡 提示(點擊展開)
起始模板:建立 .github/skills/book-summary/SKILL.md:
---
name: book-summary
description: Generate a formatted markdown summary of a book collection
---
# Book Summary Generator
Generate a summary of the book collection following these rules:
1. Output a markdown table with columns: Title, Author, Year, Status
2. Use ✅ for read books and ❌ for unread books
3. Sort by year (oldest first)
4. Include a total count at the bottom
5. Flag any data issues (missing authors, invalid years)
Example:
| Title | Author | Year | Status |
|-------|--------|------|--------|
| 1984 | George Orwell | 1949 | ✅ |
| Dune | Frank Herbert | 1965 | ❌ |
**Total: 2 books (1 read, 1 unread)**
測試方式:
copilot
> @samples/book-app-project/data.json Summarize the books in this collection
# Skill 應根據描述配對自動觸發
如果沒有觸發: 試試 /skills reload 然後再次提問。
額外挑戰:Commit Message Skill
- 建立一個
commit-messageskill,用於產生具有一致格式的 conventional commit 訊息 - 測試方式:暫存一個變更並詢問「Generate a commit message for my staged changes」
- 為你的 skill 撰寫文件,並在 GitHub 上使用
copilot-skill主題分享
🔧 常見錯誤與疑難排解(點擊展開)
常見錯誤
| 錯誤 | 會發生什麼 | 修正方式 |
|---|---|---|
檔案命名不是 SKILL.md | Skill 不會被識別 | 檔案必須命名為 SKILL.md |
description 欄位太模糊 | Skill 永遠不會被自動載入 | 描述是主要的發現機制。使用具體的觸發關鍵字 |
frontmatter 中缺少 name 或 description | Skill 載入失敗 | 在 YAML frontmatter 中加入兩個欄位 |
| 資料夾位置錯誤 | 找不到 Skill | 使用 .github/skills/skill-name/(專案)或 ~/.copilot/skills/skill-name/(個人) |
疑難排解
Skill 沒有被使用 - 如果 Copilot 在預期時沒有使用你的 skill:
- 檢查描述:描述是否與你的提問方式相符?
```markdown
不好:太模糊
description: Reviews code
好:包含觸發關鍵字
description: Use for code reviews, checking code quality,
finding bugs, security issues, and best practice violations
```
- 確認檔案位置:
```bash
專案 skill
ls .github/skills/
使用者 skill
ls ~/.copilot/skills/
```
- 檢查 SKILL.md 格式:frontmatter 是必要的:
```markdown
name: skill-name
description: What the skill does and when to use it
Instructions here
```
Skill 沒有出現 - 確認資料夾結構:
.github/skills/
└── my-skill/ # 資料夾名稱
└── SKILL.md # 必須是 SKILL.md(區分大小寫)
建立或編輯 skill 後執行 /skills reload 以確保變更被採用。
測試 skill 是否載入 - 直接詢問 Copilot:
> What skills do you have available for checking code quality?
# Copilot 會描述它找到的相關 skill
如何知道我的 skill 是否真的在運作?
- 檢查輸出格式:如果你的 skill 指定了輸出格式(如
[CRITICAL]標籤),在回應中尋找該格式 - 直接詢問:得到回應後,問「Did you use any skills for that?」
- 有無比較:使用
--no-custom-instructions嘗試相同的 prompt 來查看差異:
```bash
有 skill
copilot --allow-all -p "Review @file.py for security issues"
無 skill(基準比較)
copilot --allow-all -p "Review @file.py for security issues" --no-custom-instructions
```
- 檢查具體檢查項目:如果你的 skill 包含具體的檢查項目(如「functions over 50 lines」),看看輸出中是否出現
總結
🔑 重點整理
- Skill 是自動的:當你的 prompt 與 skill 的描述相符時,Copilot 會自動載入
- 直接呼叫:你也可以使用
/skill-name作為 slash command 直接呼叫 skill - SKILL.md 格式:YAML frontmatter(name、description、選用的 license)加上 markdown 指令
- 位置很重要:
.github/skills/用於專案/團隊共享,~/.copilot/skills/用於個人使用 - 描述是關鍵:撰寫與你自然提問方式相符的描述
📋 快速參考:參閱 GitHub Copilot CLI command reference 取得完整的指令和快捷鍵列表。
➡️ 下一步
Skill 透過自動載入的指令擴展 Copilot 的功能。但如果要連接外部服務呢?這就是 MCP 的用途。
在 Chapter 06:MCP Server 中,你將學到:
- 什麼是 MCP(Model Context Protocol,模型上下文協定)
- 連接 GitHub、檔案系統和文件服務
- 設定 MCP server
- 多伺服器工作流程
第六章 MCP Server

如果 Copilot 能讀取你的 GitHub issue、檢查你的資料庫、建立 PR⋯⋯全部在終端機中完成呢?
到目前為止,Copilot 只能處理你直接提供的內容:你用 @ 參照的檔案、對話歷史,以及它自己的訓練資料。但如果它能主動查看你的 GitHub 儲存庫、瀏覽你的專案檔案,或查閱某個函式庫的最新文件呢?
這就是 MCP(Model Context Protocol,模型上下文協定)的功能。它是一種將 Copilot 連接到外部服務的方式,讓它能存取即時的真實世界資料。Copilot 連接的每個服務稱為一個「MCP server」。在本章中,你將設定幾個這樣的連線,並看看它們如何讓 Copilot 變得更加實用。
💡 已經熟悉 MCP? 跳到快速入門 確認它是否正常運作並開始設定伺服器。
🎯 學習目標
完成本章後,你將能夠:
- 了解什麼是 MCP 以及為什麼它很重要
- 使用
/mcp指令管理 MCP server - 為 GitHub、檔案系統和文件設定 MCP server
- 使用 MCP 驅動的工作流程操作 book app 專案
- 知道何時以及如何建立自訂 MCP server(選用)
⏱️ 預估時間:約 50 分鐘(15 分鐘閱讀 + 35 分鐘實作)
🧩 真實世界類比:瀏覽器擴充功能
把 MCP server 想成瀏覽器擴充功能。你的瀏覽器本身可以顯示網頁,但擴充功能能將它連接到額外的服務:
| 瀏覽器擴充功能 | 連接到什麼 | MCP 對應 |
|---|---|---|
| 密碼管理器 | 你的密碼庫 | GitHub MCP → 你的 repo、issue、PR |
| Grammarly | 寫作分析服務 | Context7 MCP → 函式庫文件 |
| 檔案管理器 | 雲端儲存 | Filesystem MCP → 本機專案檔案 |
沒有擴充功能,你的瀏覽器仍然好用,但有了它們,就會變成強大的工具。MCP server 對 Copilot 的作用也一樣。它們將 Copilot 連接到真實的即時資料來源,讓它能讀取你的 GitHub issue、探索你的檔案系統、取得最新的文件等等。
MCP server 將 Copilot 連接到外部世界:GitHub、儲存庫、文件等等
💡 關鍵觀念:沒有 MCP 時,Copilot 只能看到你用
@明確分享的檔案。有了 MCP,它可以主動探索你的專案、檢查你的 GitHub repo,以及查閱文件,全部自動完成。
快速入門:30 秒了解 MCP
開始使用內建的 GitHub MCP server
讓我們在設定任何東西之前,先來看看 MCP 的實際效果。
GitHub MCP server 預設就已包含在內。試試這個:
copilot
> List the recent commits in this repository
如果 Copilot 回傳了真實的 commit 資料,你就見證了 MCP 的實際運作。那是 GitHub MCP server 代替你向 GitHub 發出請求。但 GitHub 只是一個伺服器。本章會教你如何新增更多(檔案系統存取、最新文件等等),讓 Copilot 能做更多事。
/mcp show 指令
使用 /mcp show 查看哪些 MCP server 已設定以及是否已啟用:
copilot
> /mcp show
MCP Servers:
✓ github (enabled) - GitHub integration
✓ filesystem (enabled) - File system access
💡 只看到 GitHub 伺服器? 這是正常的!如果你還沒有新增任何額外的 MCP server,GitHub 是唯一被列出的。你將在下一節新增更多。
📚 想查看所有
/mcp指令? 還有更多用於新增、編輯、啟用和刪除伺服器的指令。請參閱本章末尾的完整指令參考。
🎬 看看實際效果!

示範輸出僅供參考。你的模型、工具和回應將與此處顯示的不同。
MCP 帶來了什麼改變?
以下是 MCP 在實務中帶來的差異:
沒有 MCP:
> What's in GitHub issue #42?
"I don't have access to GitHub. You'll need to copy and paste the issue content."
有 MCP:
> What's in GitHub issue #42 of this repository?
Issue #42: Login fails with special characters
Status: Open
Labels: bug, priority-high
Description: Users report that passwords containing...
MCP 讓 Copilot 感知你的實際開發環境。
📚 官方文件:About MCP 深入了解 MCP 如何與 GitHub Copilot 搭配運作。
設定 MCP Server
現在你已經看過 MCP 的實際效果,讓我們設定額外的伺服器。本節涵蓋設定檔格式以及如何新增伺服器。
MCP 設定檔
MCP server 在 ~/.copilot/mcp-config.json(使用者層級,套用至所有專案)或 .vscode/mcp.json(專案層級,僅套用至目前的工作區)中設定。
{
"mcpServers": {
"server-name": {
"type": "local",
"command": "npx",
"args": ["@package/server-name"],
"tools": ["*"]
}
}
}
大多數 MCP server 以 npm 套件形式發布,並透過 npx 指令執行。
💡 JSON 新手? 點擊這裡了解每個欄位的含義
| 欄位 | 含義 |
|---|---|
"mcpServers" | 所有 MCP server 設定的容器 |
"server-name" | 你選擇的名稱(例如 "github"、"filesystem") |
"type": "local" | 伺服器在你的本機上執行 |
"command": "npx" | 要執行的程式(npx 執行 npm 套件) |
"args": [...] | 傳遞給指令的參數 |
"tools": ["*"] | 允許此伺服器的所有工具 |
重要的 JSON 規則:
- 字串使用雙引號
"(不是單引號) - 最後一項後面不要加逗號
- 檔案必須是有效的 JSON(如不確定可使用 JSON 驗證器)
新增 MCP Server
GitHub MCP server 是內建的,不需要設定。以下是你可以新增的額外伺服器。選擇你有興趣的,或按順序逐一操作。
| 我想要... | 跳到 |
|---|---|
| 讓 Copilot 瀏覽我的專案檔案 | Filesystem Server |
| 取得最新的函式庫文件 | Context7 Server |
| 探索進階選項(自訂伺服器、web_fetch) | Beyond the Basics |
Filesystem Server - 讓 Copilot 探索你的專案檔案
Filesystem Server
{
"mcpServers": {
"filesystem": {
"type": "local",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "."],
"tools": ["*"]
}
}
}
💡
.路徑:.表示「目前目錄」。Copilot 可以存取相對於你啟動位置的檔案。在 Codespace 中,這是你的工作區根目錄。你也可以使用絕對路徑,例如/workspaces/copilot-cli-for-beginners。
將此新增到你的 ~/.copilot/mcp-config.json 並重新啟動 Copilot。
Context7 Server - 取得最新的函式庫文件
Context7 Server(文件)
Context7 讓 Copilot 能存取熱門框架和函式庫的最新文件。Copilot 不再依賴可能過時的訓練資料,而是取得實際的最新文件。
{
"mcpServers": {
"context7": {
"type": "local",
"command": "npx",
"args": ["-y", "@upstash/context7-mcp"],
"tools": ["*"]
}
}
}
- ✅ 不需要 API 金鑰
- ✅ 不需要帳號
- ✅ 你的程式碼保留在本機
將此新增到你的 ~/.copilot/mcp-config.json 並重新啟動 Copilot。
Beyond the Basics - 自訂伺服器和網路存取(選用)
這些是選用的進階功能,適合你熟悉上述核心伺服器後再使用。
Microsoft Learn MCP Server
到目前為止你看到的每個 MCP server(filesystem、Context7)都在你的本機上執行。但 MCP server 也可以在遠端執行,這表示你只要將 Copilot CLI 指向一個 URL,它就會處理其餘的事。不需要 npx 或 python、不需要本機程式、不需要安裝相依套件。
Microsoft Learn MCP Server 就是一個好例子。它讓 Copilot CLI 能直接存取官方 Microsoft 文件(Azure、Microsoft Foundry 及其他 AI 主題、.NET、Microsoft 365 等等),因此它可以搜尋文件、取得完整頁面、找到官方程式碼範例,而不是依賴模型的訓練資料。
- ✅ 不需要 API 金鑰
- ✅ 不需要帳號
- ✅ 不需要本機安裝
使用 /plugin install 快速安裝:
你不需要手動編輯 JSON 設定檔,只需一個指令就能安裝:
copilot
> /plugin install microsoftdocs/mcp
這會自動新增伺服器及其關聯的 agent skill。安裝的 skill 包括:
- microsoft-docs:概念、教學和事實查詢
- microsoft-code-reference:API 查詢、程式碼範例和疑難排解
- microsoft-skill-creator:用於產生 Microsoft 技術相關自訂 skill 的元 skill
使用方式:
copilot
> What's the recommended way to deploy a Python app to Azure App Service? Search Microsoft Learn.
📚 了解更多:Microsoft Learn MCP Server overview
使用 web_fetch 進行網路存取
Copilot CLI 包含內建的 web_fetch 工具,可以從任何 URL 取得內容。這對於在不離開終端機的情況下引入 README、API 文件或版本發行說明很有用。不需要 MCP server。
你可以透過 ~/.copilot/config.json(一般 Copilot 設定)控制哪些 URL 可以存取,這與 ~/.copilot/mcp-config.json(MCP server 定義)是分開的。
{
"permissions": {
"allowedUrls": [
"https://api.github.com/**",
"https://docs.github.com/**",
"https://*.npmjs.org/**"
],
"blockedUrls": [
"http://**"
]
}
}
使用方式:
copilot
> Fetch and summarize the README from https://github.com/facebook/react
建立自訂 MCP Server
想要將 Copilot 連接到你自己的 API、資料庫或內部工具?你可以用 Python 建立自訂 MCP server。這完全是選用的,因為預建的伺服器(GitHub、filesystem、Context7)已涵蓋大多數使用情境。
📖 參閱 Custom MCP Server Guide 取得使用 book app 作為範例的完整教學。
📚 更多背景知識,參閱 MCP for Beginners course。
完整設定檔
以下是包含 filesystem 和 Context7 伺服器的完整 mcp-config.json:
💡 注意: GitHub MCP 是內建的。你不需要將它加入設定檔。
{
"mcpServers": {
"filesystem": {
"type": "local",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "."],
"tools": ["*"]
},
"context7": {
"type": "local",
"command": "npx",
"args": ["-y", "@upstash/context7-mcp"],
"tools": ["*"]
}
}
}
將此儲存為 ~/.copilot/mcp-config.json 以供全域存取,或儲存為 .vscode/mcp.json 以供專案專用設定。
使用 MCP Server
現在你已經設定好 MCP server,讓我們看看它們能做什麼。
伺服器使用範例
選擇一個伺服器來探索,或按順序逐一操作。
| 我想試試... | 跳到 |
|---|---|
| GitHub repo、issue 和 PR | GitHub Server |
| 瀏覽專案檔案 | Filesystem Server Usage |
| 函式庫文件查詢 | Context7 Server Usage |
| 自訂伺服器、Microsoft Learn MCP 和 web_fetch 用法 | Beyond the Basics Usage |
GitHub Server(內建) - 存取 repo、issue、PR 等等
GitHub Server(內建)
GitHub MCP server 是內建的。如果你已登入 Copilot(在初始設定時完成的),它就已經可以運作了。不需要設定!
💡 無法運作? 執行
/login重新向 GitHub 驗證身分。
在 Dev Container 中驗證身分
- GitHub Codespaces(推薦):驗證是自動的。
ghCLI 會繼承你的 Codespace token。不需要任何操作。 - 本機 dev container(Docker):容器啟動後執行
gh auth login,然後重新啟動 Copilot。
驗證疑難排解:
# 檢查是否已驗證
gh auth status
# 如果未驗證,請登入
gh auth login
# 確認 GitHub MCP 已連接
copilot
> /mcp show
| 功能 | 範例 |
|---|---|
| 儲存庫資訊 | 查看 commit、分支、貢獻者 |
| Issue | 列出、建立、搜尋和評論 issue |
| Pull Request | 查看 PR、diff、建立 PR、檢查狀態 |
| 程式碼搜尋 | 跨儲存庫搜尋程式碼 |
| Actions | 查詢工作流程執行狀態 |
copilot
# 查看此 repo 的近期活動
> List the last 5 commits in this repository
Recent commits:
1. abc1234 - Update chapter 05 skills examples (2 days ago)
2. def5678 - Add book app test fixtures (3 days ago)
3. ghi9012 - Fix typo in chapter 03 README (4 days ago)
...
# 探索 repo 結構
> What branches exist in this repository?
Branches:
- main (default)
- chapter6 (current)
# 跨 repo 搜尋程式碼模式
> Search this repository for files that import pytest
Found 1 file:
- samples/book-app-project/tests/test_books.py
💡 在你自己的 fork 上工作? 如果你 fork 了這個課程 repo,你也可以嘗試寫入操作,例如建立 issue 和 pull request。我們會在下面的練習中練習。
⚠️ 看不到結果? GitHub MCP 操作的是儲存庫的遠端(在 github.com 上),而不僅是本機檔案。確保你的 repo 有遠端:執行
git remote -v來檢查。
Filesystem Server - 瀏覽和分析專案檔案
Filesystem Server
設定完成後,filesystem MCP 會提供 Copilot 可以自動使用的工具:
copilot
> How many Python files are in the book-app-project directory?
Found 3 Python files in samples/book-app-project/:
- book_app.py
- books.py
- utils.py
> What's the total size of the data.json file?
samples/book-app-project/data.json: 2.4 KB
> Find all functions that don't have type hints in the book app
Found 2 functions without type hints:
- samples/book-app-project/utils.py:10 - get_user_choice()
- samples/book-app-project/utils.py:14 - get_book_details()
Context7 Server - 查詢函式庫文件
Context7 Server
copilot
> What are the best practices for using pytest fixtures?
From pytest Documentation:
Fixtures - Use fixtures to provide a fixed baseline for tests:
import pytest
@pytest.fixture
def sample_books():
return [
{"title": "1984", "author": "George Orwell", "year": 1949},
{"title": "Dune", "author": "Frank Herbert", "year": 1965},
]
def test_find_by_author(sample_books):
# fixture is automatically passed as argument
results = [b for b in sample_books if "Orwell" in b["author"]]
assert len(results) == 1
Best practices:
- Use fixtures instead of setup/teardown methods
- Use tmp_path fixture for temporary files
- Use monkeypatch for modifying environment
- Scope fixtures appropriately (function, class, module, session)
> How can I apply this to the book app's test file?
# Copilot 現在知道官方的 pytest 模式
# 並可以將它們套用到 samples/book-app-project/tests/test_books.py
Beyond the Basics - 自訂伺服器和 web_fetch 用法
Beyond the Basics
自訂 MCP Server:如果你按照 Custom MCP Server Guide 建立了 book-lookup 伺服器,你可以直接查詢你的書籍收藏:
copilot
> Look up information about "1984" using the book lookup server. Search for books by George Orwell
Microsoft Learn MCP:如果你安裝了 Microsoft Learn MCP server,你可以直接查詢官方 Microsoft 文件:
copilot
> How do I configure managed identity for an Azure Function? Search Microsoft Learn.
Web Fetch:使用內建的 web_fetch 工具從任何 URL 引入內容:
copilot
> Fetch and summarize the README from https://github.com/facebook/react
多伺服器工作流程
這些工作流程展示了為什麼開發者說「我再也不想沒有它了」。每個範例都在單一 session 中結合多個 MCP server。
完整的 MCP 工作流程:GitHub MCP 擷取 repo 資料、Filesystem MCP 尋找程式碼、Context7 MCP 提供最佳實務,而 Copilot 負責分析
以下每個範例都是獨立的。選一個你有興趣的,或全部閱讀。
| 我想看... | 跳到 |
|---|---|
| 多個伺服器協同運作 | Multi-Server Exploration |
| 在一個 session 中從 issue 到 PR | Issue-to-PR Workflow |
| 快速的專案健康檢查 | Health Dashboard |
Multi-Server Exploration - 在一個 session 中結合 filesystem、GitHub 和 Context7
使用多個 MCP Server 探索 Book App
copilot
# 步驟 1:使用 filesystem MCP 探索 book app
> List all Python files in samples/book-app-project/ and summarize
> what each file does
Found 3 Python files:
- book_app.py: CLI entry point with command routing (list, add, remove, find)
- books.py: BookCollection class with data persistence via JSON
- utils.py: Helper functions for user input and display
# 步驟 2:使用 GitHub MCP 查看近期變更
> What were the last 3 commits that touched files in samples/book-app-project/?
Recent commits affecting book app:
1. abc1234 - Add test fixtures for BookCollection (2 days ago)
2. def5678 - Add find_by_author method (5 days ago)
3. ghi9012 - Initial book app setup (1 week ago)
# 步驟 3:使用 Context7 MCP 取得最佳實務
> What are Python best practices for JSON data persistence?
From Python Documentation:
- Use context managers (with statements) for file I/O
- Handle JSONDecodeError for corrupted files
- Use dataclasses for structured data
- Consider atomic writes to prevent data corruption
# 步驟 4:綜合建議
> Based on the book app code and these best practices,
> what improvements would you suggest?
Suggestions:
1. Add input validation in add_book() for empty strings and invalid years
2. Consider atomic writes in save_books() to prevent data corruption
3. Add type hints to utils.py functions (get_user_choice, get_book_details)
🎬 看看 MCP 工作流程的實際效果!

示範輸出僅供參考。你的模型、工具和回應將與此處顯示的不同。
結果:程式碼探索 → 歷史審查 → 最佳實務查詢 → 改善計畫。全部在一個終端機 session 中完成,使用三個 MCP server 協同運作。
Issue-to-PR Workflow - 不離開終端機,從 GitHub issue 到 pull request
Issue-to-PR 工作流程(在你自己的 Repo 上)
這在你有寫入權限的 fork 或儲存庫上效果最好:
💡 如果現在無法嘗試也不用擔心。 如果你在唯讀的 clone 上,你會在作業中練習這個。現在只需閱讀以了解流程。
copilot
> Get the details of GitHub issue #1
Issue #1: Add input validation for book year
Status: Open
Description: The add_book function accepts any year value...
> @samples/book-app-project/books.py Fix the issue described in issue #1
[Copilot implements year validation in add_book()]
> Run the tests to make sure the fix works
All 8 tests passed ✓
> Create a pull request titled "Add year validation to book app"
✓ Created PR #2: Add year validation to book app
零複製貼上。零上下文切換。一個終端機 session。
Health Dashboard - 使用多個伺服器進行快速專案健康檢查
Book App 健康儀表板
copilot
> Give me a health report for the book app project:
> 1. List all functions across the Python files in samples/book-app-project/
> 2. Check which functions have type hints and which don't
> 3. Show what tests exist in samples/book-app-project/tests/
> 4. Check the recent commit history for this directory
Book App Health Report
======================
📊 Functions Found:
- books.py: 8 methods in BookCollection (all have type hints ✓)
- book_app.py: 6 functions (4 have type hints, 2 missing)
- utils.py: 3 functions (1 has type hints, 2 missing)
🧪 Test Coverage:
- test_books.py: 8 test functions covering BookCollection
- Missing: no tests for book_app.py CLI functions
- Missing: no tests for utils.py helper functions
📝 Recent Activity:
- 3 commits in the last week
- Most recent: added test fixtures
Recommendations:
- Add type hints to utils.py functions
- Add tests for book_app.py CLI handlers
- All files well-sized (<100 lines) - good structure!
結果:多個資料來源在幾秒內彙整。手動操作的話,需要執行 grep、計算行數、查看 git log 和瀏覽測試檔案。輕鬆超過 15 分鐘以上的工作量。
實作練習
🎉 你現在已經掌握了基本知識! 你了解 MCP,你已經看過如何設定伺服器,也看過實際的工作流程。現在是你自己動手的時候了。
▶️ 自己動手試試
現在輪到你了!完成這些練習來練習使用 MCP server 操作 book app 專案。
練習 1:檢查你的 MCP 狀態
先看看有哪些 MCP server 可用:
copilot
> /mcp show
你應該看到 GitHub 伺服器被列為已啟用。如果沒有,執行 /login 進行驗證。
練習 2:使用 Filesystem MCP 探索 Book App
如果你已設定 filesystem 伺服器,用它來探索 book app:
copilot
> How many Python files are in samples/book-app-project/?
> What functions are defined in each file?
預期結果:Copilot 列出 book_app.py、books.py 和 utils.py 及其函式。
💡 還沒設定 filesystem MCP? 從上面的完整設定區段建立設定檔。然後重新啟動 Copilot。
練習 3:使用 GitHub MCP 查詢儲存庫歷史
使用內建的 GitHub MCP 探索此課程儲存庫:
copilot
> List the last 5 commits in this repository
> What branches exist in this repository?
預期結果:Copilot 顯示來自 GitHub 遠端的近期 commit 訊息和分支名稱。
⚠️ 在 Codespace 中? 這會自動運作。驗證是繼承的。如果你在本機 clone 上,確保
gh auth status顯示你已登入。
練習 4:結合多個 MCP Server
現在在單一 session 中結合 filesystem 和 GitHub MCP:
copilot
> Read samples/book-app-project/data.json and tell me what books are
> in the collection. Then check the recent commits to see when this
> file was last modified.
預期結果:Copilot 讀取 JSON 檔案(filesystem MCP),列出 5 本書,包括「The Hobbit」、「1984」、「Dune」、「To Kill a Mockingbird」和「Mysterious Book」,然後查詢 GitHub 的 commit 歷史。
自我檢查:當你能解釋為什麼「Check my repo's commit history」比手動執行 git log 並將輸出貼到你的 prompt 中更好時,就代表你已經理解 MCP 了。
📝 作業
主要挑戰:Book App MCP 探索
練習在 book app 專案上一起使用 MCP server。在單一 Copilot session 中完成以下步驟:
- 確認 MCP 是否運作:執行
/mcp show並確認至少 GitHub 伺服器已啟用 - 設定 filesystem MCP(如果尚未完成):建立包含 filesystem 伺服器設定的
~/.copilot/mcp-config.json - 探索程式碼:要求 Copilot 使用 filesystem 伺服器來:
- 列出
samples/book-app-project/books.py中的所有函式 - 檢查
samples/book-app-project/utils.py中哪些函式缺少 type hints - 讀取
samples/book-app-project/data.json並識別任何資料品質問題(提示:看最後一筆)
- 檢查儲存庫活動:要求 Copilot 使用 GitHub MCP 來:
- 列出涉及
samples/book-app-project/檔案的近期 commit - 檢查是否有任何開啟的 issue 或 pull request
- 結合伺服器:在單一 prompt 中,要求 Copilot:
- 讀取
samples/book-app-project/tests/test_books.py測試檔案 - 將已測試的函式與
books.py中的所有函式進行比較 - 摘要缺少哪些測試覆蓋率
成功標準:你能在單一 Copilot session 中無縫結合 filesystem 和 GitHub MCP 資料,並能解釋每個 MCP server 對回應的貢獻。
💡 提示(點擊展開)
步驟 1:確認 MCP
copilot
> /mcp show
# 應顯示 "github" 為已啟用
# 如果沒有,執行:/login
步驟 2:建立設定檔
使用上面完整設定區段的 JSON,儲存為 ~/.copilot/mcp-config.json。
步驟 3:要尋找的資料品質問題
data.json 中的最後一本書是:
{
"title": "Mysterious Book",
"author": "",
"year": 0,
"read": false
}
空的作者和年份為 0。這就是資料品質問題!
步驟 5:測試覆蓋率比較
test_books.py 中的測試涵蓋:add_book、mark_as_read、remove_book、get_unread_books 和 find_book_by_title。像 load_books、save_books 和 list_books 等函式沒有直接測試。book_app.py 中的 CLI 函式和 utils.py 中的輔助函式完全沒有測試。
如果 MCP 無法運作: 編輯設定檔後重新啟動 Copilot。
額外挑戰:建立自訂 MCP Server
準備好深入了解了嗎?按照 Custom MCP Server Guide 建立你自己的 Python MCP server,連接到任何 API。
🔧 常見錯誤與疑難排解(點擊展開)
常見錯誤
| 錯誤 | 會發生什麼 | 修正方式 |
|---|---|---|
| 不知道 GitHub MCP 是內建的 | 嘗試手動安裝/設定它 | GitHub MCP 預設就已包含。直接試試:「List the recent commits in this repo」 |
| 在錯誤的位置尋找設定 | 找不到或無法編輯 MCP 設定 | 使用者層級設定在 ~/.copilot/mcp-config.json,專案層級在 .vscode/mcp.json |
| 設定檔中的 JSON 無效 | MCP server 載入失敗 | 使用 /mcp show 檢查設定;驗證 JSON 語法 |
| 忘記驗證 MCP server | 「Authentication failed」錯誤 | 某些 MCP 需要單獨驗證。檢查每個伺服器的要求 |
疑難排解
「MCP server not found」 - 確認:
- npm 套件存在:
npm view @modelcontextprotocol/server-github - 你的設定是有效的 JSON
- 伺服器名稱與你的設定相符
使用 /mcp show 查看目前的設定。
「GitHub authentication failed」 - 內建的 GitHub MCP 使用你的 /login 憑證。嘗試:
copilot
> /login
這會重新向 GitHub 驗證你的身分。如果問題持續,請確認你的 GitHub 帳號對你要存取的儲存庫具有必要的權限。
「MCP server failed to start」 - 檢查伺服器日誌:
# 手動執行伺服器指令以查看錯誤
npx -y @modelcontextprotocol/server-github
MCP 工具不可用 - 確保伺服器已啟用:
copilot
> /mcp show
# 檢查伺服器是否已列出且已啟用
如果伺服器已停用,參閱下方的額外 /mcp 指令了解如何重新啟用。
📚 額外的 /mcp 指令(點擊展開)
除了 /mcp show 之外,還有其他幾個用於管理 MCP server 的指令:
| 指令 | 功能 |
|---|---|
/mcp show | 顯示所有已設定的 MCP server 及其狀態 |
/mcp add | 互動式設定以新增伺服器 |
/mcp edit <server-name> | 編輯現有的伺服器設定 |
/mcp enable <server-name> | 啟用已停用的伺服器 |
/mcp disable <server-name> | 暫時停用伺服器 |
/mcp delete <server-name> | 永久移除伺服器 |
/mcp auth <server-name> | 重新向使用 OAuth 的 MCP server 驗證身分(例如切換帳號後) |
在本課程的大部分內容中,/mcp show 就是你需要的全部。其他指令在你管理更多伺服器時會變得有用。
總結
🔑 重點整理
- MCP 將 Copilot 連接到外部服務(GitHub、檔案系統、文件)
- GitHub MCP 是內建的 - 不需要設定,只需
/login - Filesystem 和 Context7 透過
~/.copilot/mcp-config.json設定 - 多伺服器工作流程在單一 session 中結合來自多個來源的資料
- 檢查伺服器狀態使用
/mcp show(還有額外的指令可用於管理伺服器) - 自訂伺服器讓你能連接任何 API(選用,在附錄指南中介紹)
📋 快速參考:參閱 GitHub Copilot CLI command reference 取得完整的指令和快捷鍵列表。
➡️ 下一步
你現在擁有了所有的建構模組:模式、上下文、工作流程、agent、skill 和 MCP。是時候把它們全部整合在一起了。
在 Chapter 07:Putting It All Together 中,你將學到:
- 在統一的工作流程中結合 agent、skill 和 MCP
- 從構想到合併 PR 的完整功能開發
- 使用 hook 進行自動化
- 團隊環境的最佳實務
第七章 整合應用

你所學到的一切在此匯聚。在一次 session(工作階段)中,從構想到合併 PR。
在本章中,你將把所學的一切整合成完整的工作流程。你將運用多 agent(代理)協作來建置功能、設定 pre-commit hook(預提交鉤子)在程式碼提交前捕捉安全問題、將 Copilot 整合至 CI/CD 管線,並在單一終端機 session 中從功能構想到合併 PR。這就是 GitHub Copilot CLI 成為真正效率倍增器的時刻。
💡 注意:本章展示如何結合你所學的一切。你不需要 agent、skill(技能)或 MCP 也能高效工作(雖然它們非常有幫助)。 核心工作流程——描述、規劃、實作、測試、審查、交付——僅用第 00-03 章的內建功能就能完成。
🎯 學習目標
完成本章後,你將能夠:
- 在統一的工作流程中結合 agent、skill 和 MCP(Model Context Protocol,模型上下文協定)
- 使用多工具方法建置完整功能
- 設定基本的 hook 自動化
- 應用專業開發的最佳實踐
⏱️ 預估時間:約 75 分鐘(15 分鐘閱讀 + 60 分鐘實作)
🧩 現實世界類比:管弦樂團
交響管弦樂團由許多樂部組成:
- 弦樂提供基礎(如同你的核心工作流程)
- 銅管增添力量(如同具備專業知識的 agent)
- 木管增添色彩(如同擴展能力的 skill)
- 打擊樂保持節奏(如同連接外部系統的 MCP)
單獨來看,每個樂部聽起來有所侷限。但在優秀指揮的帶領下合奏,它們能創造出令人驚嘆的作品。
這就是本章要教你的!<br>
如同指揮家指揮管弦樂團,你將協調 agent、skill 和 MCP 成為統一的工作流程
讓我們從一個情境開始,在一次 session 中修改程式碼、產生測試、審查並建立 PR。
<a id="idea-to-merged-pr-in-one-session"></a>從構想到合併 PR 一次完成
與其在編輯器、終端機、測試執行器和 GitHub UI 之間來回切換,每次切換都會流失上下文,你可以在一個終端機 session 中結合所有工具。我們將在下方的整合模式小節中拆解這個模式。
# 以互動模式啟動 Copilot
copilot
> I need to add a "list unread" command to the book app that shows only
> books where read is False. What files need to change?
# Copilot 建立高層級計畫...
# 切換至 PYTHON-REVIEWER AGENT
> /agent
# 選擇 "python-reviewer"
> @samples/book-app-project/books.py Design a get_unread_books method.
> What is the best approach?
# Python-reviewer agent 產出:
# - 方法簽名和回傳型別
# - 使用列表推導式的篩選實作
# - 空集合的邊界情況處理
# 切換至 PYTEST-HELPER AGENT
> /agent
# 選擇 "pytest-helper"
> @samples/book-app-project/tests/test_books.py Design test cases for
> filtering unread books.
# Pytest-helper agent 產出:
# - 空集合的測試案例
# - 混合已讀/未讀書籍的測試案例
# - 所有書籍皆已讀的測試案例
# 實作
> Add a get_unread_books method to BookCollection in books.py
> Add a "list unread" command option in book_app.py
> Update the help text in the show_help function
# 測試
> Generate comprehensive tests for the new feature
# 產生多個類似以下的測試:
# - 正常路徑(3 個測試)—— 正確篩選、排除已讀、包含未讀
# - 邊界情況(4 個測試)—— 空集合、全部已讀、全部未讀、單本書籍
# - 參數化(5 個案例)—— 透過 @pytest.mark.parametrize 測試不同已讀/未讀比例
# - 整合測試(4 個測試)—— 與 mark_as_read、remove_book、add_book 的交互作用及資料完整性
# 審查變更
> /review
# 如果審查通過,使用 /pr 操作當前分支的 pull request
> /pr [view|create|fix|auto]
# 或者用自然語言讓 Copilot 從終端機起草
> Create a pull request titled "Feature: Add list unread books command"
傳統做法:在編輯器、終端機、測試執行器、文件和 GitHub UI 之間切換。每次切換都會造成上下文流失和摩擦。
關鍵洞察:你像架構師一樣指揮專家。他們處理細節,你掌握全局。
💡 更進一步:對於像這樣的大型多步驟計畫,試試
/fleet讓 Copilot 平行執行獨立子任務。詳見官方文件。
其他工作流程
對於完成了第 04-06 章的進階使用者,這些工作流程展示了 agent、skill 和 MCP 如何倍增你的效率。
<a id="the-integration-pattern-for-power-users"></a>整合模式
以下是結合所有工具的心智模型:
工作流程 1:臭蟲調查與修復
結合完整工具的真實世界臭蟲修復:
copilot
# 第 1 階段:從 GitHub 了解臭蟲(MCP 提供此功能)
> Get the details of issue #1
# 了解到:「find_by_author 不支援部分名稱搜尋」
# 第 2 階段:研究最佳實踐(使用網路和 GitHub 來源進行深度研究)
> /research Best practices for Python case-insensitive string matching
# 第 3 階段:尋找相關程式碼
> @samples/book-app-project/books.py Show me the find_by_author method
# 第 4 階段:取得專家分析
> /agent
# 選擇 "python-reviewer"
> Analyze this method for issues with partial name matching
# Agent 識別出:方法使用完全比對而非子字串比對
# 第 5 階段:依照 agent 的指引修復
> Implement the fix using lowercase comparison and 'in' operator
# 第 6 階段:產生測試
> /agent
# 選擇 "pytest-helper"
> Generate pytest tests for find_by_author with partial matches
> Include test cases: partial name, case variations, no matches
# 第 7 階段:提交和 PR
> Generate a commit message for this fix
> Create a pull request linking to issue #1
<a id="workflow-2-code-review-automation-optional"></a>工作流程 2:程式碼審查自動化(選修)
💡 此章節為選修。 Pre-commit hook 對團隊很有用,但並非提高生產力的必要條件。如果你才剛入門,可以跳過。
⚠️ 效能提醒:此 hook 會對每個暫存檔案呼叫
copilot -p,每個檔案需要數秒時間。對於大型提交,請考慮僅針對關鍵檔案執行,或改用/review手動審查。
Git hook(Git 鉤子)是 Git 在特定時間點自動執行的腳本,例如在提交之前。你可以用它對程式碼進行自動化檢查。以下是設定自動 Copilot 審查的方法:
# 建立 pre-commit hook
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/bash
# 取得暫存檔案(僅 Python 檔案)
STAGED=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.py$')
if [ -n "$STAGED" ]; then
echo "Running Copilot review on staged files..."
for file in $STAGED; do
echo "Reviewing $file..."
# 使用 timeout 防止卡住(每個檔案 60 秒)
# --allow-all 自動核准檔案讀寫,讓 hook 可以無人值守地執行。
# 僅在自動化腳本中使用此選項。在互動式 session 中,讓 Copilot 請求許可。
REVIEW=$(timeout 60 copilot --allow-all -p "Quick security review of @$file - critical issues only" 2>/dev/null)
# 檢查是否逾時
if [ $? -eq 124 ]; then
echo "Warning: Review timed out for $file (skipping)"
continue
fi
if echo "$REVIEW" | grep -qi "CRITICAL"; then
echo "Critical issues found in $file:"
echo "$REVIEW"
exit 1
fi
done
echo "Review passed"
fi
EOF
chmod +x .git/hooks/pre-commit
⚠️ macOS 使用者:macOS 預設未包含
timeout指令。請用brew install coreutils安裝,或將timeout 60替換為不含逾時保護的簡單呼叫。
💡 內建替代方案:Copilot CLI 也有內建的 hook 系統(
copilot hooks),可在 pre-commit 等事件時自動執行。上述手動 Git hook 給予你完全的控制權,而內建系統則更易於設定。請參閱上方文件以決定哪種方式適合你的工作流程。
現在每次提交都會進行快速安全審查:
git add samples/book-app-project/books.py
git commit -m "Update book collection methods"
# 輸出:
# Running Copilot review on staged files...
# Reviewing samples/book-app-project/books.py...
# Critical issues found in samples/book-app-project/books.py:
# - Line 15: File path injection vulnerability in load_from_file
#
# Fix the issue and try again.
工作流程 3:新程式碼庫入門
加入新專案時,結合 context、agent 和 MCP 以快速上手:
# 以互動模式啟動 Copilot
copilot
# 第 1 階段:透過 context 取得全局概覽
> @samples/book-app-project/ Explain the high-level architecture of this codebase
# 第 2 階段:了解特定流程
> @samples/book-app-project/book_app.py Walk me through what happens
> when a user runs "python book_app.py add"
# 第 3 階段:透過 agent 取得專家分析
> /agent
# 選擇 "python-reviewer"
> @samples/book-app-project/books.py Are there any design issues,
> missing error handling, or improvements you would recommend?
# 第 4 階段:尋找可著手的工作(MCP 提供 GitHub 存取)
> List open issues labeled "good first issue"
# 第 5 階段:開始貢獻
> Pick the simplest open issue and outline a plan to fix it
此工作流程將 @ context、agent 和 MCP 結合成單一入門 session,正是本章前面介紹的整合模式。
最佳實踐與自動化
讓你的工作流程更有效率的模式與習慣。
最佳實踐
1. 先蒐集上下文,再進行分析
在要求分析之前,務必先蒐集上下文:
# 好的做法
> Get the details of issue #42
> /agent
# 選擇 python-reviewer
> Analyze this issue
# 較不理想的做法
> /agent
# 選擇 python-reviewer
> Fix login bug
# Agent 沒有 issue 的上下文
2. 了解差異:Agent、Skill 和自訂指示
每種工具都有其最佳用途:
# Agent:你明確啟用的專業角色
> /agent
# 選擇 python-reviewer
> Review this authentication code for security issues
# Skill:當你的 prompt 符合 skill 描述時自動啟用的模組化功能
#(你必須先建立它們——參見第 05 章)
> Generate comprehensive tests for this code
# 如果你已設定測試 skill,它會自動啟用
# 自訂指示(.github/copilot-instructions.md):始終生效的
# 指引,適用於每個 session,無需切換或觸發
💡 關鍵重點:Agent 和 skill 都能分析和產生程式碼。真正的差異在於啟用方式——agent 是明確啟用(
/agent),skill 是自動啟用(prompt 配對),而自訂指示則是始終生效。
3. 保持 Session 專注
使用 /rename 為你的 session 命名(方便在歷史記錄中查找),使用 /exit 乾淨地結束:
# 好的做法:每個功能一個 session
> /rename list-unread-feature
# 開發 list unread 功能
> /exit
copilot
> /rename export-csv-feature
# 開發 CSV 匯出功能
> /exit
# 較不理想的做法:所有事情都在一個冗長的 session 中
4. 使用 Copilot 讓工作流程可重複使用
與其只在 wiki 中記錄工作流程,不如直接編碼在 repo 中讓 Copilot 使用:
- 自訂指示(
.github/copilot-instructions.md):始終生效的程式碼標準、架構規則及建置/測試/部署步驟指引。每個 session 都會自動遵循。 - Prompt 檔案(
.github/prompts/):可重複使用、參數化的 prompt,團隊可以共享——如同程式碼審查、元件產生或 PR 描述的範本。 - 自訂 agent(
.github/agents/):編碼專業角色(例如安全審查員或文件撰寫員),團隊中任何人都能用/agent啟用。 - 自訂 skill(
.github/skills/):將步驟化的工作流程指示打包成在相關時自動啟用的模組。
💡 回報:新團隊成員免費獲得你的工作流程——它們內建在 repo 中,不是鎖在某人腦中。
附加內容:正式環境模式
這些模式為選修,但在專業環境中很有價值。
PR 描述產生器
# 產生完整的 PR 描述
BRANCH=$(git branch --show-current)
COMMITS=$(git log main..$BRANCH --oneline)
copilot -p "Generate a PR description for:
Branch: $BRANCH
Commits:
$COMMITS
Include: Summary, Changes Made, Testing Done, Screenshots Needed"
CI/CD 整合
對於已有 CI/CD 管線的團隊,你可以使用 GitHub Actions 在每個 pull request 上自動化 Copilot 審查。這包括自動發布審查評論和篩選關鍵問題。
📖 深入了解:查看 CI/CD 整合 以取得完整的 GitHub Actions 工作流程、設定選項和疑難排解提示。
練習
將完整的工作流程付諸實踐。
▶️ 自己試試看
完成示範後,嘗試以下變化:
- 端到端挑戰:選擇一個小功能(例如「列出未讀書籍」或「匯出為 CSV」)。使用完整工作流程:
- 用
/plan規劃 - 用 agent 設計(python-reviewer、pytest-helper)
- 實作
- 產生測試
- 建立 PR
- 自動化挑戰:設定程式碼審查自動化工作流程中的 pre-commit hook。進行一次包含故意檔案路徑漏洞的提交,看它是否會被攔截。
- 你的正式環境工作流程:為你常做的一項任務設計自己的工作流程。將它寫成檢查清單。哪些部分可以用 skill、agent 或 hook 自動化?
自我檢查:當你能向同事解釋 agent、skill 和 MCP 如何協同運作——以及何時使用各個工具時,你就完成了本課程。
📝 作業
主要挑戰:端到端功能
實作範例演示了建置「列出未讀書籍」功能。現在用不同的功能來練習完整工作流程:依年份範圍搜尋書籍:
- 啟動 Copilot 並蒐集上下文:
@samples/book-app-project/books.py - 用
/plan Add a "search by year" command that lets users find books published between two years規劃 - 在
BookCollection中實作find_by_year_range(start_year, end_year)方法 - 在
book_app.py中新增handle_search_year()函式,提示使用者輸入起始和結束年份 - 產生測試:
@samples/book-app-project/books.py @samples/book-app-project/tests/test_books.py Generate tests for find_by_year_range() including edge cases like invalid years, reversed range, and no results. - 用
/review審查 - 更新 README:
@samples/book-app-project/README.md Add documentation for the new "search by year" command. - 產生提交訊息
過程中記錄你的工作流程。
成功標準:你已使用 Copilot CLI 完成從構想到提交的整個功能,包括規劃、實作、測試、文件和審查。
💡 附加挑戰:如果你在第 04 章設定了 agent,試試建立和使用自訂 agent。例如,用錯誤處理 agent 進行實作審查,用文件撰寫 agent 更新 README。
💡 提示(點擊展開)
依照本章頂部「從構想到合併 PR」範例的模式操作。關鍵步驟為:
- 用
@samples/book-app-project/books.py蒐集上下文 - 用
/plan Add a "search by year" command規劃 - 實作方法和指令處理器
- 產生含邊界情況的測試(無效輸入、空結果、反轉範圍)
- 用
/review審查 - 用
@samples/book-app-project/README.md更新 README - 用
-p產生提交訊息
需要考慮的邊界情況:
- 如果使用者輸入「2000」和「1990」(反轉範圍)怎麼辦?
- 如果沒有書籍符合範圍怎麼辦?
- 如果使用者輸入非數字怎麼辦?
關鍵是練習完整的工作流程,從構想 → 上下文 → 規劃 → 實作 → 測試 → 文件 → 提交。
🔧 常見錯誤(點擊展開)
| 錯誤 | 後果 | 修正方式 |
|---|---|---|
| 直接跳到實作 | 遺漏設計問題,後續修正成本高 | 先使用 /plan 思考方法 |
| 只用一種工具而非多種搭配 | 速度較慢、結果不夠全面 | 搭配使用:Agent 分析 → Skill 執行 → MCP 整合 |
| 提交前未審查 | 安全問題或臭蟲被遺漏 | 務必執行 /review 或使用 pre-commit hook |
| 忘記與團隊分享工作流程 | 每個人都在重複造輪子 | 將模式記錄在共享的 agent、skill 和指示中 |
總結
🔑 重點摘要
- 整合 > 獨立運作:結合工具以發揮最大效益
- 先有上下文:在分析前務必蒐集必要的上下文
- Agent 分析,Skill 執行:使用正確的工具做正確的事
- 自動化重複工作:Hook 和腳本倍增你的效率
- 記錄工作流程:可分享的模式讓整個團隊受益
📋 快速參考:查看 GitHub Copilot CLI 指令參考 以取得完整的指令與快捷鍵清單。
🎓 課程完成!
恭喜!你已學會:
| 章節 | 學習內容 |
|---|---|
| 00 | Copilot CLI 安裝與快速入門 |
| 01 | 三種互動模式 |
| 02 | 使用 @ 語法的上下文管理 |
| 03 | 開發工作流程 |
| 04 | 專業化 agent |
| 05 | 可擴展的 skill |
| 06 | 使用 MCP 連接外部系統 |
| 07 | 統一的正式環境工作流程 |
你現在已具備將 GitHub Copilot CLI 作為開發工作流程中真正效率倍增器的能力。
➡️ 下一步
你的學習旅程不會在此結束:
- 每天練習:在實際工作中使用 Copilot CLI
- 建立自訂工具:為你的特定需求建立 agent 和 skill
- 分享知識:幫助你的團隊採用這些工作流程
- 持續更新:關注 GitHub Copilot 的更新以獲得新功能
資源
做得好!現在去打造令人驚豔的作品吧。
附錄
附錄 A:額外上下文
額外的上下文功能
📖 先修條件:請先完成第 02 章:上下文與對話再閱讀本附錄。
本附錄涵蓋兩項額外的上下文功能:使用圖片,以及管理多個目錄的存取權限。
使用圖片
你可以使用 @ 語法在對話中加入圖片。Copilot 能夠分析截圖、設計稿、圖表及其他視覺內容。
基本圖片參照
copilot
> @screenshot.png What's happening in this UI?
# Copilot 分析圖片並回應
> @mockup.png @current-design.png Compare these two designs
# 你也可以拖放圖片或從剪貼簿貼上
支援的圖片格式
| 格式 | 最適合用途 |
|---|---|
| PNG | 截圖、UI 設計稿、圖表 |
| JPG/JPEG | 照片、複雜圖片 |
| GIF | 簡單圖表(僅第一幀) |
| WebP | 網頁截圖 |
實用的圖片使用情境
1. UI 除錯
> @bug-screenshot.png The button doesn't align properly. What CSS might cause this?
2. 設計實作
> @figma-export.png Write the HTML and Tailwind CSS to match this design
3. 錯誤分析
> @error-screenshot.png What does this error mean and how do I fix it?
4. 架構審查
> @whiteboard-diagram.png Convert this architecture diagram to a Mermaid diagram I can put in docs
5. 前後比較
> @before.png @after.png What changed between these two versions of the UI?
結合圖片與程式碼
當圖片與程式碼的上下文結合使用時,效果更加強大:
copilot
> @screenshot-of-bug.png @src/components/Header.jsx
> The header looks wrong in the screenshot. What's causing it in the code?
圖片使用技巧
- 裁剪截圖——只顯示相關部分(節省上下文 token)
- 使用高對比度——讓你想分析的 UI 元素更清晰
- 需要時加註標記——上傳前圈出或標亮問題區域
- 每張圖片對應一個概念——多張圖片沒問題,但要保持聚焦
權限模式
預設情況下,Copilot 可以存取你目前目錄中的檔案。若要存取其他位置的檔案,你需要授予存取權限。
新增目錄
# 將目錄加入允許清單
copilot --add-dir /path/to/other/project
# 新增多個目錄
copilot --add-dir ~/workspace --add-dir /tmp
允許所有路徑
# 完全停用路徑限制(請謹慎使用)
copilot --allow-all-paths
在工作階段中操作
copilot
> /add-dir /path/to/other/project
# 現在你可以參照該目錄中的檔案
> /list-dirs
# 查看所有已允許的目錄
用於自動化
# 在非互動式腳本中允許所有權限
copilot -p "Review @src/" --allow-all
# 或使用簡易別名
copilot -p "Review @src/" --yolo
何時需要多目錄存取
以下是你會需要這些權限的常見情境:
- Monorepo 開發——跨套件比較程式碼
- 跨專案重構——更新共用程式庫
- 文件專案——參照多個程式碼庫
- 遷移工作——比較新舊實作
附錄 B:CI/CD 整合
CI/CD 整合
📖 先修條件:請先完成第 07 章:綜合應用再閱讀本附錄。
⚠️ 本附錄適用於已有 CI/CD 管線的團隊。 如果你剛接觸 GitHub Actions 或 CI/CD 概念,請先從第 07 章的程式碼審查自動化章節中較簡單的 pre-commit hook 方式開始。
本附錄說明如何將 GitHub Copilot CLI 整合到你的 CI/CD 管線中,在 pull request 上執行自動化程式碼審查。
GitHub Actions 工作流程
此工作流程會在 pull request 被開啟或更新時,自動審查變更的檔案:
# .github/workflows/copilot-review.yml
name: Copilot Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # 需要用來與 main 分支比較
- name: Install Copilot CLI
run: npm install -g @github/copilot
- name: Review Changed Files
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
# 取得變更的 JS/TS 檔案清單
FILES=$(git diff --name-only origin/main...HEAD | grep -E '\.(js|ts|jsx|tsx)$' || true)
if [ -z "$FILES" ]; then
echo "No JavaScript/TypeScript files changed"
exit 0
fi
echo "# Copilot Code Review" > review.md
echo "" >> review.md
for file in $FILES; do
echo "Reviewing $file..."
echo "## $file" >> review.md
echo "" >> review.md
# 使用 --silent 抑制進度輸出
copilot --allow-all -p "Quick security and quality review of @$file. List only critical issues." --silent >> review.md 2>/dev/null || echo "Review skipped" >> review.md
echo "" >> review.md
done
- name: Post Review Comment
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const review = fs.readFileSync('review.md', 'utf8');
// 僅在有重要內容時才張貼
if (review.includes('CRITICAL') || review.includes('HIGH')) {
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: review
});
} else {
console.log('No critical issues found, skipping comment');
}
設定選項
限縮審查範圍
你可以將審查聚焦於特定類型的問題:
# 僅安全性審查
copilot --allow-all -p "Security review of @$file. Check for: SQL injection, XSS, hardcoded secrets, authentication issues." --silent
# 僅效能審查
copilot --allow-all -p "Performance review of @$file. Check for: N+1 queries, memory leaks, blocking operations." --silent
處理大型 PR
對於包含大量檔案的 PR,可考慮分批處理或設定限制:
# 限制為前 10 個檔案
FILES=$(git diff --name-only origin/main...HEAD | grep -E '\.(js|ts)$' | head -10)
# 或為每個檔案設定逾時
timeout 60 copilot --allow-all -p "Review @$file" --silent || echo "Review timed out"
團隊設定
若要在團隊中保持一致的審查標準,請建立共用設定:
// .copilot/config.json(提交至 repo)
{
"model": "claude-sonnet-4.5",
"permissions": {
"allowedPaths": ["src/**/*", "tests/**/*"],
"deniedPaths": [".env*", "secrets/**/*", "*.min.js"]
}
}
替代方案:PR 審查機器人
若需更精密的審查工作流程,可考慮使用 GitHub Copilot cloud agent:
# .github/workflows/copilot-agent-review.yml
name: Request Copilot Review
on:
pull_request:
types: [opened, ready_for_review]
jobs:
request-review:
runs-on: ubuntu-latest
steps:
- name: Request Copilot Review
uses: actions/github-script@v7
with:
script: |
await github.rest.pulls.requestReviewers({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number,
reviewers: ['copilot[bot]']
});
CI/CD 整合最佳實踐
- 使用
--silent旗標——抑制進度輸出,讓日誌更簡潔 - 設定逾時——防止審查卡住而阻塞你的管線
- 篩選檔案類型——只審查相關檔案(跳過產生的程式碼、相依套件)
- 注意速率限制——對大型 PR 的審查適當間隔
- 優雅地失敗——不要因審查失敗就阻擋合併;記錄並繼續
疑難排解
CI 中出現「Authentication failed」
確認你的工作流程具有正確的權限:
permissions:
contents: read
pull-requests: write
issues: write
審查逾時
增加逾時時間或縮小審查範圍:
timeout 120 copilot --allow-all -p "Quick review of @$file - critical issues only" --silent
大型檔案的 token 限制
跳過非常大的檔案:
if [ $(wc -l < "$file") -lt 500 ]; then
copilot --allow-all -p "Review @$file" --silent
else
echo "Skipping $file (too large)"
fi
詞彙表
術語表
本課程中使用的技術術語快速參考。不必現在就記住這些——需要時隨時回來查閱。
A
Agent
具有特定領域專長的專業化 AI 人格(例如前端、安全)。定義在 .agent.md 檔案中,使用 YAML frontmatter (前導資料),至少需包含一個 description 欄位。
API
Application Programming Interface(應用程式介面)。程式之間相互通訊的方式。
C
CI/CD
Continuous Integration/Continuous Deployment(持續整合/持續部署)。自動化測試與部署的管線流程。
CLI
Command Line Interface(命令列介面)。以文字為基礎與軟體互動的方式(就像這個工具!)。
Context Window(上下文視窗)
AI 一次能考慮的文字量。就像一張只能放這麼多東西的書桌。當你加入檔案、對話紀錄和系統提示時,它們都會佔用這個視窗的空間。
Context Manager(上下文管理器)
Python 中使用 with 陳述式的語法結構,能自動處理設定與清理工作(例如開啟和關閉檔案)。範例:with open("file.txt") as f: 確保即使發生錯誤也會關閉檔案。
Conventional Commit(約定式提交)
一種遵循標準化結構的提交訊息格式:type(scope): description。常見的類型包括 feat(新功能)、fix(錯誤修正)、docs(文件)、refactor(重構)和 test(測試)。範例:feat(auth): add password reset flow。
Dataclass(資料類別)
Python 的裝飾器 (@dataclass),會自動為主要用於儲存資料的類別產生 __init__、__repr__ 及其他方法。在書籍應用程式中用於定義 Book 類別,包含 title、author、year 和 read 等欄位。
F
Frontmatter(前導資料)
位於 Markdown 檔案頂端、以 --- 分隔符號包圍的中繼資料。在 agent 和 skill 檔案中用於以 YAML 格式定義 description 和 name 等屬性。
G
Glob Pattern(萬用字元模式)
使用萬用字元來比對檔案路徑的模式(例如 .py 比對所有 Python 檔案,.js 比對所有 JavaScript 檔案)。
J
JWT
JSON Web Token。一種在系統之間安全傳輸驗證資訊的方式。
M
MCP
Model Context Protocol(模型上下文協定)。一種將 AI 助手連接到外部資料來源的標準。
N
npx
一種 Node.js 工具,可在不全域安裝的情況下執行 npm 套件。在 MCP 伺服器設定中用於啟動伺服器(例如 npx @modelcontextprotocol/server-filesystem)。
O
OWASP
Open Web Application Security Project(開放式 Web 應用程式安全專案)。一個發佈安全最佳實踐、並維護「OWASP Top 10」最關鍵 Web 應用程式安全風險清單的組織。
P
PEP 8
Python Enhancement Proposal 8(Python 增強提案 8)。Python 程式碼的官方風格指南,涵蓋命名慣例(函式使用 snake_case、類別使用 PascalCase)、縮排(4 個空格)及程式碼排版。遵循 PEP 8 能使 Python 程式碼一致且易於閱讀。
Pre-commit Hook(預提交鉤子)
在每次 git commit 之前自動執行的腳本。可用於在程式碼提交前執行 Copilot 安全審查或程式碼品質檢查。
pytest
一個廣受歡迎的 Python 測試框架,以其簡潔的語法、強大的 fixture 和豐富的外掛生態系統聞名。本課程中用於測試書籍應用程式。透過 python -m pytest tests/ 執行測試。
Programmatic Mode(程式化模式)
使用 -p 旗標執行 Copilot,進行無需互動的單一指令。
R
Rate Limiting(速率限制)
在特定時間內對 API 請求次數的限制。如果超出方案的使用配額,Copilot 可能會暫時限制回應。
S
Session(工作階段)
與 Copilot 的對話,能維持上下文並可在稍後繼續。
Skill
包含指示的資料夾,當與你的提示相關時 Copilot 會自動載入。定義在 SKILL.md 檔案中,使用 YAML frontmatter。
Slash Command(斜線指令)
以 / 開頭的指令,用於控制 Copilot(例如 /help、/clear、/model)。
T
Token(權杖)
AI 模型處理的文字單位。大約等於 4 個字元或 0.75 個英文單字。用於衡量輸入(你的提示和上下文)與輸出(AI 的回應)。
Type Hints(型別提示)
Python 中用於標註函式參數與回傳值預期型別的註釋(例如 def add_book(title: str, year: int) -> Book:)。它們不會在執行時強制型別檢查,但有助於程式碼的清晰度、IDE 支援,以及 mypy 等靜態分析工具。
W
WCAG
Web Content Accessibility Guidelines(網頁內容無障礙指引)。由 W3C 發佈的標準,旨在讓網頁內容對身心障礙者更易於存取。WCAG 2.1 AA 是常見的合規目標。
Y
YAML
YAML Ain't Markup Language。一種人類可讀的資料格式,用於設定。在本課程中,YAML 出現在 agent 和 skill 的 frontmatter(.agent.md 和 SKILL.md 檔案頂端以 --- 分隔的區塊)中。
封底
本書翻譯自 GitHub Copilot CLI for Beginners
授權條款
MIT License
Copyright © GitHub, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.