> 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/tools/setup_api_tool.md).

# 建立 API 工具

本指南將引導您在平台中建立新的 MCP 工具。

{% hint style="info" %}
您可以使用 MaiAgent 製作的 [工具製作 AI 助理](https://chat.maiagent.ai/web-chats/27934296-105a-4f3f-80f0-7e9dcdb638d3) 協助您建立 API 工具
{% endhint %}

API 工具用於整合外部服務、自動化操作流程。

## **什麼是 API？** <a href="#what-is-api" id="what-is-api"></a>

**API（Application Programming Interface，應用程式介面）** 是不同軟體系統之間溝通的橋樑。簡單來說，它就像是**軟體世界的「服務員」**，幫助不同的程式互相傳遞資訊和執行功能。

想像你在餐廳用餐：

* **你**：需要食物的客戶（應用程式）
* **廚房**：製作食物的地方（提供服務的系統）
* **服務員**：在你和廚房之間傳遞訊息（**API**）

你不需要直接進廚房，只要告訴服務員你要什麼，服務員會把你的需求傳達給廚房，然後把做好的餐點送到你面前。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-affedbd5ccc8692a11a20ce5fc69a39886d0e2d3%2Fplayma%20(10)%20(1).png?alt=media" alt=""><figcaption><p>API 流程示意圖</p></figcaption></figure>

API 工具可以協助您自動操作標準化流程及設置特定的回傳格式，也可以協助您獲取您系統中的資訊如：

**電商客服自動化**

```
客戶詢問訂單 ➡️ API 查詢訂單狀態 ➡️ 自動回覆配送進度
```

**行銷活動管理**

```
新產品上架 ➡️ 自動更新官網 ➡️ 發送 EDM ➡️ 社群平台宣傳
```

**線上課程平台：**

```
學生詢問課程進度 ➡️ API 查詢學習紀錄 ➡️ 自動回覆完成百分比和下次上課時間
```

透過 API 工具，AI 助理從單純的對話機器人，進化成能夠實際執行業務流程的智慧助理，大幅提升工作效率和自動化程度。

## 快速建立 API 工具 <a href="#quick-create-api-tool" id="quick-create-api-tool"></a>

### 1. 進入工具管理介面 <a href="#step-1-enter-tool-management" id="step-1-enter-tool-management"></a>

首先，請從左側導航欄進入「 <mark style="color:blue;">AI 功能</mark>」區塊，然後點擊「<mark style="color:blue;">🔧 工具</mark>」。進入工具列表頁面後，點選右上角的「<mark style="color:blue;">➕ 新增工具</mark>」按鈕。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-1849091665b669bc0c5964295e91459b75acbe42%2FMCP%E5%B7%A5%E5%85%B7.png?alt=media" alt="工具列表頁面與新增按鈕"><figcaption><p>點擊「➕ 新增工具」開始建立</p></figcaption></figure>

### 2. 選擇工具類型 <a href="#step-2-select-tool-type" id="step-2-select-tool-type"></a>

工具類型，選擇 API。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-36d929d6f379aadbfe05520796e63d6f8fefaf4f%2FAPI%E5%B7%A5%E5%85%B7.png?alt=media" alt=""><figcaption></figcaption></figure>

### 3. 設定顯示名稱 <a href="#step-3-set-display-name" id="step-3-set-display-name"></a>

為工具設定清晰的顯示名稱，這邊設為 <mark style="color:blue;">google calendar</mark>。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-1b6a8ebbc7b3900a46b0a20494b1c11c118fbe47%2FAPI%E5%B7%A5%E5%85%B7%20(2).png?alt=media" alt=""><figcaption></figcaption></figure>

* **用途**：此名稱將會顯示在平台介面中，供所有用戶查看。
* **建議**：選擇一個能清晰表達工具主要功能的名稱，方便用戶理解。此名稱沒有嚴格的格式限制。

### 4. 設定工具名稱 <a href="#step-4-set-tool-name" id="step-4-set-tool-name"></a>

接下來是「<mark style="color:blue;">工具名稱</mark>」欄位。

* **用途**：此名稱是 AI 助理在內部呼叫和識別此工具時使用的唯一標識符。
* **命名規則 (重要)**：
  * 必須使用英文。
  * 只能包含：
    * 小寫英文字母 (a-z)
    * 大寫英文字母 (A-Z)
    * 數字 (0-9)
    * 底線 (`_`)
    * 連字符 (`-`)
  * **範例**：`get_weather_forecast`, `database-query-tool`

下圖設為 <mark style="color:blue;">google\_calendar\_retriever</mark>

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-e60b90c068677f55f73f007d3f191a41bc3a9e5f%2FAPI%E5%B7%A5%E5%85%B7%20(4).png?alt=media" alt=""><figcaption><p>API 工具名稱定義</p></figcaption></figure>

### 5. 撰寫工具描述 <a href="#step-5-write-tool-description" id="step-5-write-tool-description"></a>

在「<mark style="color:blue;">工具描述</mark>」欄位中，用戶可以提供清晰且詳細的工具說明。

* **重要性**：良好的描述能幫助 AI 助理更準確地理解：
  * 工具的功能和目的。
  * 何時應該使用這個工具。
  * 如何解釋工具的輸出結果。
* **建議內容**：說明工具做什麼、輸入什麼、輸出什麼，以及任何使用上的注意事項。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-61fe2994e26226077604c4865223522621a0c39c%2FAPI%E5%B7%A5%E5%85%B7%20(5).png?alt=media" alt=""><figcaption><p>工具描述</p></figcaption></figure>

### 6. API 配置詳細設定 <a href="#step-6-api-configure-details" id="step-6-api-configure-details"></a>

#### a. 🔗 API URL <a href="#api-url" id="api-url"></a>

* 填寫目標 API 端點的完整網址 (包含 `http://` 或 `https://`)。
* **範例**：`https://api.opencalendar.org/data/2.5`

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-7c8ec1446f411f007db93eecab4a2de07ee8036e%2FAPI%E5%B7%A5%E5%85%B7%20(6).png?alt=media" alt=""><figcaption></figcaption></figure>

#### b. 📮 HTTP 方法 <a href="#http-method" id="http-method"></a>

* 從下拉選單中選擇 API 服務要求的 HTTP 動詞：
  * `GET`：通常用於獲取資源。
  * `POST`：通常用於創建新資源或提交數據。
  * `PUT`：通常用於完整替換或更新資源。
  * `DELETE`：通常用於刪除資源。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-a96418d1f33a03fb89d7c99d75cbff4200fa5851%2FAPI%E5%B7%A5%E5%85%B7%20(8).png?alt=media" alt=""><figcaption></figcaption></figure>

#### c. 📰 標頭 (Headers) <a href="#headers" id="headers"></a>

標頭就像是信件的「<mark style="color:blue;">信封</mark>」，在看到實際的資料內容前，先告訴接收方一些重要的資訊，**沒有正確的標頭，API 請求可能無法通過驗證，或者接收方無法正確解析資料。**。

**常見用途**：

* 身份驗證 (`Authorization`, `X-API-Key`)
* 指定內容類型 (`Content-Type`)
* 指定接受的回應格式 (`Accept`)

若要新增標頭，您需要：

* 點擊「<mark style="color:blue;">➕ 新增標頭</mark>」來定義隨請求發送的 HTTP 標頭。
* **格式**：必須是有效的 JSON 物件，其中鍵 (Key) 是標頭名稱，值 (Value) 是標頭內容 (字串)。
* **範例**：

  ```json
  {
    "Content-Type": "application/json; charset=utf-8",
    "Authorization": "Bearer {{SECRET_API_TOKEN}}",
    "Accept": "application/vnd.github.v3+json"
  }
  ```

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-6d67f75950755371440b5dcd1a50016f36259224%2FAPI%E5%B7%A5%E5%85%B7%20(9).png?alt=media" alt="API 標頭設定截圖"><figcaption><p>設定必要的 HTTP 請求標頭</p></figcaption></figure>

#### d. 🔎 Query 參數 (Query Params) <a href="#query-params" id="query-params"></a>

Query 參數是附加在網址問號後面的查詢字串（例如 `?format=json&limit=10`），每次呼叫都會隨請求送出。適合放固定的查詢條件，或是只能透過 query string 傳遞的 API 金鑰。

* 點擊「<mark style="color:blue;">可用的情境變數</mark>」可展開目前支援的變數清單（聯絡人 ID、對話 ID、收件匣 ID 等）。
* **格式**：有效的 JSON 物件，鍵 (Key) 是參數名稱，值 (Value) 是參數內容（字串）。
* 值可以寫成固定文字，也可以用 `{{參數名}}` 引用「參數結構」中宣告、由 AI 助理在呼叫時填入的參數，讓「前半固定、後半由使用者提供」的查詢條件用設定就能完成，詳見下方 [在 Query 參數中引用 AI 助理的參數](#query-param-templates)。
* **範例**：

  ```json
  {
    "$format": "json",
    "$filter": "ProductName eq '{{product_name}}'"
  }
  ```

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-a0552130721b327022bc32313554617846bf0bf7%2Fapi-tool-query-params.png?alt=media" alt="工具設定視窗中的 Query 參數欄位，值裡使用 {{product_name}} 引用參數"><figcaption><p>Query 參數欄位與「可用的情境變數」清單</p></figcaption></figure>

#### e. 🧩 參數結構 (Parameters Schema) <a href="#parameters-schema" id="parameters-schema"></a>

**參數結構就像是「點餐單」**，告訴 AI 助理可以向 API 要求什麼資料，以及要怎麼要求。

* **核心設定**：定義 AI 助理在呼叫此工具時，可以或必須提供哪些參數(要傳遞給系統處理的內容)，以及這些參數的格式。
* **格式**：使用標準的 **JSON Schema** 格式。
* **關鍵元素**：
  * `type: "object"`：表示參數是一個物件。
  * `properties`: 定義每個參數的物件。
    * **參數名稱** (例如 `"search"`)：對應的物件包含該參數的細節。
      * `type`: 參數的資料類型 (`string`, `integer`, `number`, `boolean`, `array`, `object`)。
      * `description`: 對 AI 助理的說明，解釋此參數的意義。
      * `default` (可選): 參數的默認值。
      * `enum` (可選): 如果參數值只能是特定幾個選項之一，在此列出。
  * `required`: 一個包含所有**必填**參數名稱的陣列。
* **範例** (影音搜尋工具)：

  ```json
  {
      "type": "object",
      "properties": {
          "limit": {
              "type": "integer",
              "minimum": 1,
              "description": "回傳結果數量上限"
          },
          "fields": {
              "type": "string",
              "description": "以逗號分隔的欄位清單"
          },
          "search": {
              "type": "string",
              "description": "搜尋關鍵字"
          }
      },
      "required": ["search"]
  }
  ```

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-5932120820f0a885644b441bac5c63a4492ae567%2FAPI%E5%B7%A5%E5%85%B7%20(11).png?alt=media" alt="API 參數結構設定截圖"><figcaption><p>使用 JSON Schema 精確定義 API 參數</p></figcaption></figure>

### 7. 💾 儲存工具 <a href="#step-7-save-tool" id="step-7-save-tool"></a>

確認所有設定無誤後，捲動到頁面底部，點擊「<mark style="color:blue;">確認</mark>」按鈕。您的新工具就建立完成了！

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-eb2d956da69f2a187bf9f57c4cc86d0a07c2de73%2FAPI%E5%B7%A5%E5%85%B7%20(13).png?alt=media" alt=""><figcaption></figcaption></figure>

## 在 Query 參數中引用 AI 助理的參數 <a href="#query-param-templates" id="query-param-templates"></a>

許多第三方 API 的查詢條件是「固定語法＋使用者提供的值」組成的一整個字串，例如 OData 風格的 `$filter=ProductName eq 'Chai'`，或搜尋類 API 的 `q=` 參數。這類 API 要的不是一個獨立的參數，而是把值嵌進固定的字串裡。

在「Query 參數」的值裡寫 `{{參數名}}`，MaiAgent 會在 AI 助理呼叫工具時，把「參數結構」中同名參數的值代入後再送出請求。設定者負責寫好固定的骨架，AI 助理只負責填值，語法正確性不再交給模型判斷。

### 使用情境 <a href="#query-param-templates-use-case" id="query-param-templates-use-case"></a>

採購部門想讓公司內部的 AI 助理直接回答「某個產品目前的單價和庫存是多少」，資料來源是公司商品目錄系統提供的 OData 查詢服務。過去這類查詢必須為每一支 API 另外寫程式；現在採購專員只要建立一個 API 工具，把查詢條件寫成 `ProductName eq '{{product_name}}'`，再把工具配置給 AI 助理。同事在對話中問「Chai 這個產品的單價和庫存是多少？」，AI 助理會自動把 `Chai` 填進查詢條件、呼叫 API，並回覆產品名稱、單價與庫存。

### 設定步驟 <a href="#query-param-templates-steps" id="query-param-templates-steps"></a>

以下用公開的 Northwind 示範資料服務（OData）示範，可直接照做：

{% stepper %}
{% step %}

### 建立工具並填入基本資料 <a href="#query-param-step-basic" id="query-param-step-basic"></a>

依照上方「快速建立 API 工具」的步驟新增一個 API 工具，填入顯示名稱（例如 <mark style="color:blue;">產品價格查詢</mark>）、工具名稱 `product_price_lookup`、描述與提示詞，並將 <mark style="color:blue;">API URL</mark> 設為：

```
https://services.odata.org/V4/Northwind/Northwind.svc/Products
```

<mark style="color:blue;">HTTP 方法</mark> 維持 `GET`。
{% endstep %}

{% step %}

### 在參數結構宣告要由 AI 助理填入的參數 <a href="#query-param-step-schema" id="query-param-step-schema"></a>

在 <mark style="color:blue;">參數結構 (JSON Schema)</mark> 宣告 `product_name`，並用 `description` 告訴 AI 助理該填什麼：

```json
{
  "type": "object",
  "properties": {
    "product_name": {
      "type": "string",
      "description": "完整的英文產品名稱，例如 Chai"
    }
  },
  "required": ["product_name"]
}
```

{% endstep %}

{% step %}

### 在 Query 參數的值裡引用該參數 <a href="#query-param-step-template" id="query-param-step-template"></a>

在 <mark style="color:blue;">Query 參數 (JSON)</mark> 填入固定的查詢骨架，並在值裡用 `{{product_name}}` 引用剛才宣告的參數：

```json
{
  "$format": "json",
  "$select": "ProductID,ProductName,UnitPrice,UnitsInStock",
  "$filter": "ProductName eq '{{product_name}}'"
}
```

點擊「<mark style="color:blue;">確認</mark>」儲存工具。
{% endstep %}

{% step %}

### 配置給 AI 助理並測試 <a href="#query-param-step-test" id="query-param-step-test"></a>

依照 [爲 AI 助理配置工具](/tools/configure_tools.md) 把這個工具加入一個 Agent 模式的 AI 助理並儲存。接著從左側導航列進入「<mark style="color:blue;">Agent 市集</mark>」，切換到「<mark style="color:blue;">組織自建</mark>」，點選該 AI 助理開始對話，輸入「請問 Chai 這個產品的單價和庫存是多少？」。AI 助理會顯示「已使用工具」，並回覆 Chai 的單價與庫存。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-d301cae503ac598952cb9c0c4ef494c0b8bae727%2Fapi-tool-query-params-chat.png?alt=media" alt="AI 助理在對話中使用工具，回覆產品名稱、單價與庫存"><figcaption><p>AI 助理把使用者提供的產品名稱代入查詢條件後呼叫 API</p></figcaption></figure>
{% endstep %}
{% endstepper %}

### 代入規則 <a href="#query-param-templates-rules" id="query-param-templates-rules"></a>

| 規則                | 說明                                                                             |
| ----------------- | ------------------------------------------------------------------------------ |
| **變數名稱必須與參數結構一致** | `{{product_name}}` 對應「參數結構」中 `properties` 的參數名稱，大小寫需完全相符                       |
| **只有值會代入**        | 模板只作用在 Query 參數的值；鍵 (Key) 維持原樣，不做代入                                            |
| **值以原文代入**        | 參數值一律以字面文字代入，不做數值轉換；例如統一編號 `04595257` 的前導零會保留                                  |
| **缺值即中止**         | AI 助理這次呼叫沒有提供該參數（或值為空）時，工具會以錯誤中止並指出是哪個參數缺值，不會把 `{{product_name}}` 原樣送出去        |
| **情境變數優先**        | 若參數名稱與情境變數（如 `contact_id`、`conversation_id`）相同，一律代入情境變數的值，AI 助理提供的值不會覆蓋        |
| **被引用的參數仍會一併送出**  | 被模板引用的參數仍會照原本的行為當成獨立的 query 參數一起送出（例如同時送出 `product_name=Chai`），多數 API 會忽略多餘的參數 |
| **參數名稱原樣保存**      | Query 參數的鍵含底線或大寫（例如 `Business_Accounting_NO`）會原樣保存，不會被系統改寫                     |

{% hint style="info" %}
「<mark style="color:blue;">標頭 (JSON)</mark>」的值同樣支援 `{{參數名}}` 引用參數結構中的參數，規則與 Query 參數相同。
{% endhint %}

{% hint style="warning" %}
不含 `{{ }}` 的既有工具設定完全不受影響。若舊工具的 Query 參數名稱曾被系統改寫（例如 `Business_Accounting_NO` 變成 `business__accounting_no`），重新開啟該工具、把名稱改回正確寫法並儲存即可。重新開啟編輯視窗時，Query 參數的值會以 `****` 遮罩顯示，直接儲存不會遺失原值。
{% endhint %}

## ⚠️ 重要提醒 <a href="#important-notes" id="important-notes"></a>

**連線測試**

* 建立工具後，建議先測試 API 是否正常運作
* 可使用測試工具驗證工具功能，如：
  * POSTMAN
  * 企業自己搭建的 API 測試請求平台

**權限管理**

* 定期檢查工具使用狀況及權限開放狀態


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.maiagent.ai/tools/setup_api_tool.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
