> For the complete documentation index, see [llms.txt](https://docs.maiagent.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.maiagent.ai/tech/mcp/mcp-model-context-protocol.md).

# MCP（Model Context Protocol）

MCP（Model Context Protocol）是什麼：AI 應用連接外部工具與資料來源的開放協定，運作原理、核心價值，以及在 MaiAgent 用 MCP 工具接 MCP Server。

{% hint style="info" %}
**MCP 相關頁面怎麼讀**：先看本頁的概念 → 在 Agent 掛上 MCP 工具的後台操作，見使用者手冊的[建立 MCP 工具](https://docs.maiagent.ai/build/tools/mcp-setup) → 自家系統要做成 MCP Server，見[自架 MCP Server 接入規格](/tech/mcp/self-hosted-mcp-server.md)；改用 Composio、Zapier 等託管服務，見[Remote MCP 服務概述](/tech/mcp/remote-mcp.md) → 反方向，讓 Claude、Cursor 等 AI 工具操作 MaiAgent，見[MaiAgent MCP](/tech/mcp/maiagent-mcp.md)。
{% endhint %}

## MCP 是什麼？

MCP，全名為 Model Context Protocol，中文為**模型上下文協定**，是 AI 應用程式連接外部工具與資料來源的開放協定。支援 MCP 的應用程式，不論背後使用 Anthropic Claude、OpenAI GPT 或 Google Gemini 等哪一種大型語言模型，都能用同一套規則連接 MCP 伺服器提供的工具。

### MCP 能協助什麼？

透過 MCP，LLM 除了回答問題，還可以取得外部資料、操作外部系統：

#### **即時連接外部資料源** <a href="#ji-shi-lian-jie-wai-bu-zi-liao-yuan" id="ji-shi-lian-jie-wai-bu-zi-liao-yuan"></a>

* 存取資料庫
* 讀取檔案系統
* 串接雲端服務

#### **主動調用工具** <a href="#zhu-dong-diao-yong-gong-ju" id="zhu-dong-diao-yong-gong-ju"></a>

* 執行程式碼
* 操作應用程式

***

## MCP 的運作原理

MCP 的運作原理如下圖所示，分為：

| 區塊                  | 說明                                                                                                                                                                                      |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **使用者端 (Frontend)** | 使用者透過 UI 或 SDK 發出指令                                                                                                                                                                     |
| **AI 模型層**          | LLM 依工具定義決定要呼叫的工具與參數，由應用程式中的 MCP Client 轉成 MCP 請求送出                                                                                                                                     |
| **協定層 (MCP)**       | <p>以 <code>JSON-RPC 2.0</code> 傳遞訊息，以 JSON Schema 描述工具參數，並定義 stdio 與 Streamable HTTP 等傳輸方式<br><code>JSON-RPC 2.0</code> 是一種通訊協定，要傳遞的資訊將以 JSON 格式定義「請求與回應」的結構，讓 LLM 能使用相同的語言與各種程式溝通。</p> |
| **MCP Servers**     | <p>接收模型請求並與實際工具或資料系統互動<br>除了自行架設 MCP Servers 服務外，您也可以透過<a href="/tech/mcp/remote-mcp.md"> Remote MCP 服務</a>，串聯 LLM 與其他服務。</p>                                                           |
| **外部系統**            | 各種真實世界的資源：資料庫、API、Git、檔案系統等                                                                                                                                                             |

### MCP 運作流程圖示

<figure><img src="https://527168072-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F38pkhhqHl1oA6yyE9R2n%2Fuploads%2FFaLti4vkGZXwCv5LWZ9D%2Fplayma%20(8).png?alt=media&amp;token=007b1d12-dae8-486e-983f-4103b42f3df2" alt=""><figcaption></figcaption></figure>

透過這樣的流程，應用程式只要實作一次 MCP Client，就能連接各種 MCP 伺服器提供的工具。

### MCP 使用案例

#### 案例一：透過 MCP 整理 Google Drive 檔案—文件搜尋及摘要

透過自然語言告知 LLM 任務內容：

> 幫我找出 Google Drive 中所有關於『2024 年度預算』的文件,並整理成摘要報告

LLM 依需求判斷要呼叫的 MCP 工具，例如 `search_files`。以下工具名稱與結果皆為示意。

**MCP 運作流程:**

<figure><img src="https://527168072-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F38pkhhqHl1oA6yyE9R2n%2Fuploads%2FHvbzZyZXFhzFBiPdFDQP%2FUntitled%20diagram-2025-10-27-014125.png?alt=media&amp;token=41dbe986-4957-4dc6-84fc-c033c29ac199" alt=""><figcaption></figcaption></figure>

**AI 實際執行動作:**

1. 🔍 搜尋包含「2024年度預算」關鍵字的文件
2. 📄 讀取找到的 5 個文件內容
3. 🧠 分析各文件重點
4. 📊 生成統整摘要報告
5. 💡 提供預算分析建議

**使用者得到的結果:**

```
找到 5 個相關文件:

1. 【2024年度預算提案.docx】
   - 總預算: NT$ 50,000,000
   - 主要項目: 人事成本 60%、營運成本 25%、研發 15%
   
2. 【Q1預算執行報告.xlsx】
   - 執行率: 92%
   - 超支項目: 行銷費用 +8%
   
3. 【預算修正案_v2.pdf】
   - 調整建議: 增加研發預算 10%
   
... (其他文件摘要)
```

***

#### 案例二：透過 MCP 串聯 Google Sheet、Slack—排程產生每周報表，傳送至群組

LLM 可以透過 MCP 串聯多個外部服務工具，流程如下圖所示：

透過排程服務每週觸發 LLM 執行相同查詢任務內容：

LLM 依需求判斷要呼叫的 MCP 工具，例如 `search_sheet`、`query_sheet`（示意）。在 MaiAgent 可用[代理排程](https://docs.maiagent.ai/build/agent/schedule)定期觸發 Agent 執行這類任務。

<figure><img src="https://527168072-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F38pkhhqHl1oA6yyE9R2n%2Fuploads%2F32901s6K3eVAIKuTWI9S%2FUntitled%20diagram-2025-10-27-015034.png?alt=media&amp;token=16bfc819-3ab0-4ee0-9c78-a94185078966" alt=""><figcaption></figcaption></figure>

Agent 每週處理流程：

1. 🔍 搜尋「銷售資料」試算表
2. 📄 讀取試算表數值內容
3. 📊 根據需求生成統整摘要報告，如：平均營收、同期比較成長幅度等
4. 💡 自動發送彙整結果至 Slack 頻道內

***

## MCP 的核心價值 <a href="#he-xin-jia-zhi-zong-jie" id="he-xin-jia-zhi-zong-jie"></a>

#### 🧠 **LLM 提供智慧** <a href="#llm-ti-gong-zhi-hui" id="llm-ti-gong-zhi-hui"></a>

* 理解自然語言
* 推理與決策
* 知識整合
* 創意生成
* 異常偵測
* 預測分析

#### 📡 **MCP 提供能力** <a href="#mcp-ti-gong-neng-li" id="mcp-ti-gong-neng-li"></a>

* 連接各種工具
* 執行實際操作
* 跨系統整合
* 標準化通訊

LLM 負責理解需求與決定下一步，MCP 負責以標準方式連接工具；兩者搭配，LLM 才能在對話中查資料、執行操作。MCP 協定規範的是連線與授權流程；連上的工具實際能做什麼，取決於 MCP 伺服器的實作，以及授權給它的帳號有哪些權限。

***

## 在 MaiAgent 使用 MCP <a href="#mcp-in-maiagent" id="mcp-in-maiagent"></a>

MaiAgent 是 **MCP Client**：在後台建立 MCP 工具、填入伺服器網址並綁定到 Agent 後，Agent 就能呼叫伺服器提供的工具。反方向讓 Claude、Cursor 等 AI 工具操作 MaiAgent，見 [MaiAgent MCP](/tech/mcp/maiagent-mcp.md)。

### 支援的傳輸方式 <a href="#supported-transports" id="supported-transports"></a>

MaiAgent 只連線遠端的 MCP 伺服器，依網址判斷傳輸方式：路徑結尾為 `/sse`、路徑中含 `/sse/`，或 query string 帶 `transport=sse` 時走 SSE，其餘一律走 Streamable HTTP。

| 傳輸方式                   | 說明                                                | MaiAgent 是否支援 |
| ---------------------- | ------------------------------------------------- | ------------- |
| **Streamable HTTP**    | MCP 規格的標準傳輸：每則訊息以 HTTP POST 送到單一端點，回應可以是 JSON 或串流 | ✅             |
| **SSE（HTTP with SSE）** | 2024-11-05 版規格的傳輸方式，以 Server-Sent Events 串流伺服器訊息  | ✅             |
| **stdio**              | MCP 規格的標準傳輸：由用戶端在本機啟動伺服器程序（例如 `npx`），透過標準輸入輸出通訊   | ❌             |
| **WebSocket 等自訂傳輸**    | 不在 MCP 規格的標準傳輸中                                   | ❌             |

不支援 stdio，是因為平台不會在伺服器上啟動 `npx`、`node` 等本機指令。只提供 stdio 版本的 MCP 伺服器，需要改用服務商的遠端版本，或自行部署成 HTTP 服務。自架 MCP Server 的傳輸方式、URL 與驗證要求詳見 [自架 MCP Server 接入規格](/tech/mcp/self-hosted-mcp-server.md)。

### 圖形介面快速整合

MaiAgent 提供圖形化介面，不需撰寫程式碼即可接入遠端 MCP 伺服器：在後台新增 MCP 工具時，只要填入伺服器網址與驗證方式（固定金鑰填在標頭，或選擇 OAuth 連接器），再從伺服器回傳的工具清單選擇允許 Agent 使用的工具。

{% hint style="info" %}
如何建立 MCP 工具，請參考：[使用者手冊—建立 MCP 工具](https://docs.maiagent.ai/build/tools/mcp-setup)
{% endhint %}

### 平台的處理方式 <a href="#platform-behavior" id="platform-behavior"></a>

* **工具範圍**：只有 MCP 工具「<mark style="color:blue;">允許的工具 (JSON 數組)</mark>」中開啟的工具會交給模型；伺服器新增的工具不會自動開放。
* **逾時與重試**：MCP session 的讀取逾時為 30 秒；連線中斷等暫時性錯誤只對重送也安全的工具自動重試。
* **紀錄**：每次呼叫都會寫入工具執行紀錄，可在 <mark style="color:blue;">AgentOps</mark> → <mark style="color:blue;">工具執行紀錄</mark> 查詢。
* **連線驗證**：直接填網址的 MCP 工具在儲存時就會連線伺服器並取回工具清單，連不上會顯示「MCP 工具驗證失敗」，不會存成半套；OAuth 連接器的工具則在完成授權後取回清單。操作見使用者手冊 [建立 MCP 工具](https://docs.maiagent.ai/build/tools/mcp-setup#mcp-server-url)。

### 排查 `unhandled errors in a TaskGroup` <a href="#taskgroup-errors" id="taskgroup-errors"></a>

工具執行紀錄的錯誤訊息出現 `unhandled errors in a TaskGroup (1 sub-exception)` 時，這不是一種獨立的錯誤：MCP 用戶端把 session 跑在非同步工作群組裡，連線中斷、讀取逾時、伺服器關閉連線等傳輸層錯誤會被包成這個外層訊息，真正的原因在括號後的 sub-exception。排查順序：

1. 到 <mark style="color:blue;">AgentOps</mark> → <mark style="color:blue;">工具執行紀錄</mark> 打開該筆紀錄，看 `errorMessage` 的完整內容與 `status`（`timeout` 代表 30 秒內沒有回應）。
2. 傳輸層錯誤平台會自動重試；重試後仍失敗，先確認伺服器網址可從公網連線、協定（SSE／Streamable HTTP）與伺服器一致、標頭或 OAuth 授權仍有效。
3. 若 sub-exception 是伺服器回的應用錯誤（例如工具回報參數不合法），平台不會重試；請用同一組參數直接呼叫您的 MCP 伺服器重現。
4. 在工具設定頁重新「取得工具清單」能成功，代表連線與認證正常，問題多在該工具執行時的逾時或伺服器端錯誤。

使用 Composio、Zapier 等託管服務時的注意事項，見 [Remote MCP 服務概述](/tech/mcp/remote-mcp.md)。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.maiagent.ai/tech/mcp/mcp-model-context-protocol.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
