

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 伺服器端工具使用
<a name="tool-use-server-side"></a>

如果您使用回應 API 來叫用模型，則除了我們之前討論的用戶端工具呼叫之外，它還可以使用伺服器端工具呼叫。伺服器端工具呼叫是一種機制，其中工具 APIs、函數、工作流程） 是在信任的後端環境中執行，而不是在用戶端上執行。這可改善應用程式的安全性、可靠性和控管狀態。在 Amazon Bedrock 執行實作工具使用的 Lambda 函數之前，它會確保 Lambda 函數具有與呼叫它的應用程式相同的 IAM 政策。隨著 Amazon Bedrock 推動工具的執行，用戶端可以專注於實作其商業邏輯，而不是新增工具功能。Amazon Bedrock 也支援最高控管標準，例如符合 ISO、SOC 和 HIPAA 資格。客戶可以提交自己的自訂 Lambda 函數來執行工具，或使用現有的預先定義工具，例如備註和任務。使用 Responses API 的伺服器端工具從 OpenAI 的 GPT OSS 20B/120B 模型開始提供，並支援即將推出的其他模型。您可以使用模型 API 來探索可與回應 API 搭配使用的可用模型。如需回應 API 的詳細資訊，請參閱[使用 OpenAI APIs產生回應](https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-mantle.html)。

您可以搭配 Amazon Bedrock 使用兩種類型的工具：使用 Lambda 的自訂工具，或 Bedrock 支援的預先定義工具。在本節中，我們將檢閱如何使用 Responses API 建立自訂 Lambda 工具。讓我們詳細討論兩者。

**在回應 API 中使用 Lambda 的自訂工具**

透過使用 Lambda 函數作為 Bedrock 中的自訂工具，您可以透過將自訂 AWS Lambda 函數整合為工具來擴展代理程式的功能。這可讓您建立無伺服器、可擴展的工具，AI 助理和其他應用程式可透過模型內容通訊協定 (MCP) 呼叫這些工具。以下是此功能的優點：
+ 擴展功能：新增自訂商業邏輯、API 整合或資料處理功能。
+ 安全地執行工具：Lambda 允許工具存取 VPC 內的資源，而不必授予完整的 VPC 存取權。
+ 無伺服器架構：沒有基礎設施管理，Lambda 會自動處理擴展。
+ 成本效益：僅支付執行時間，而非閒置資源。
+ 輕鬆整合：Lambda 函數與內建工具一起無縫顯示。

若要讓 Amazon Bedrock 中的模型使用工具來完成訊息的回應，您可以將訊息和一或多個工具的定義傳送到模型。根據您應用程式的提示，如果模型判斷其中一個工具可協助產生回應，則會傳回 Bedrock 使用該工具的請求，並將工具結果傳回模型。模型接著會使用結果來產生對原始訊息的回應。

下列步驟說明如何搭配 [Responses API](https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-mantle.html) 使用工具。

**運作方式**

1. **Lambda 函數**：建立實作 MCP 通訊協定的 Lambda 函數

1. **工具探索**：Bedrock 呼叫您的 Lambda 函數來探索可用的工具

1. **工具註冊**：您的工具已向 Bedrock 註冊

1. **工具執行**：當代理程式請求您的工具時， Bedrock 會叫用您的 Lambda 函數

1. **回應處理**：結果會透過標準界面傳回給客服人員

**步驟 1：定義 Lambda 函數以取得最熱門的歌曲**

建立實作 MCP 通訊協定的 Lambda 函數。以下是簡單的 Python 範例：

```
import json

def lambda_handler(event, context):
    # Parse JSON-RPC request
    method = event.get('method')
    params = event.get('params', {})
    request_id = event.get('id')
    
    if method == 'tools/list':
        return {
            "jsonrpc": "2.0",
            "id": request_id,
            "result": {
                "tools": [
                    {
                        "name": "my_custom_tool",
                        "description": "My custom business logic tool",
                        "inputSchema": {
                            "type": "object",
                            "properties": {
                                "input": {
                                    "type": "string",
                                    "description": "Input text to process"
                                }
                            },
                            "required": ["input"]
                        }
                    }
                ]
            }
        }
    elif method == 'tools/call':
        tool_name = params.get('name')
        arguments = params.get('arguments', {})
        
        if tool_name == 'my_custom_tool':
            # Your custom logic here
            result = f"Processed: {arguments.get('input', '')}"
            return {
                "jsonrpc": "2.0",
                "id": request_id,
                "result": {
                    "content": [
                        {
                            "type": "text",
                            "text": result
                        }
                    ]
                }
            }
    
    # Error response for unsupported methods
    return {
        "jsonrpc": "2.0",
        "id": request_id,
        "error": {
            "code": -32601,
            "message": "Method not found"
        }
    }
```

**步驟 2：部署 Lambda 函數**

接著，使用您的 IAM 角色部署此 Lambda 函數以取得 ARN。您可以在[此處](https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html)閱讀更多有關部署 Lambda 函數的資訊。

```
# Example using AWS CLI
aws lambda create-function \
  --function-name my-custom-tool \
  --runtime python3.14 \
  --role arn:aws:iam::YOUR-ACCOUNT:role/lambda-execution-role \
  --handler lambda_function.lambda_handler \
  --zip-file fileb://function.zip
```

假設您的 ARN 是： `arn:aws:lambda:us-west-2:123456789012:function:my-custom-tool`

**步驟 3：在推論請求中定義訊息和工具定義**

若要傳送訊息和工具定義，您可以使用 [Responses API](https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-mantle.html) 操作。Amazon Bedrock 使用回應 API 的[連接器和遠端 MCP 伺服器功能](https://platform.openai.com/docs/guides/tools-connectors-mcp)來提供工具使用功能。工具的定義是您在 mcp 請求參數中傳遞至建立操作的 JSON 結構描述。在回應連接器 API 的 `connector_id` 欄位中，您可以傳入您在上一個步驟中建立的 Lambda ARN。您不需要提供授權登入資料，因為 Bedrock 使用與叫用模型的應用程式相同的 IAM 角色和政策。以下是工具的範例結構描述，該工具會取得在廣播電台上播放的熱門歌曲。

```
from openai import OpenAI

client = OpenAI()

resp = client.responses.create(
    model="oss-gpt-120b",
    tools=[
        {
            "type": "mcp",
            "server_label": "xamzn_arn",
            "connector_id": "arn:aws:lambda:us-west-2:123456789012:function:my-custom-tool",
            "require_approval": "never",
        },
    ],
    input="My custom prompt.",
)

print(resp.output_text)
```

**步驟 4：Bedrock 呼叫工具並將回應傳遞回模型**

在支援[回應 API ](https://platform.openai.com/docs/api-reference/responses/create)的模型中，可以使用連接器工具。[在此處](https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-mantle.html)檢查哪些工具支援您的模型。當您使用 回應 API 使用工具時，您只需支付匯入工具定義或進行工具呼叫時使用的[字符](https://platform.openai.com/docs/pricing)。每次工具呼叫不收取額外費用。

當您在 `tools` 參數中指定 Lambda 函數時，API 會嘗試從伺服器取得工具清單。如果成功擷取工具清單，新的`mcp_list_tools`輸出項目會出現在模型回應輸出中。此物件的 `tools` 屬性會顯示已成功匯入的工具。一旦模型可以存取這些工具定義，它可以選擇根據模型內容中的內容來呼叫它們。當模型決定呼叫 Lambda 工具時，API 將向 Lambda 函數提出請求，以呼叫該工具並將其輸出放入模型的內容中。您可以在 [OpenAI 文件](https://platform.openai.com/docs/guides/tools-connectors-mcp?quickstart-panels=connector)的清單工具和呼叫工具上閱讀更多資訊。請注意，您的 Lambda 函數必須與在 Bedrock 中呼叫模型的應用程式連接相同的 IAM 角色和政策，否則 Lambda 函數會失敗。以下是錯誤定義。

```
{
    "jsonrpc": "2.0",
    "id": 1,
    "error": {
        "code": -32000,
        "message": "Tool execution failed",
        "data": "Additional error details"
    }
}
```

**在回應 API 中使用 AWS 提供的工具**

`openai.gpt-oss-20b` 和 `openai.gpt-oss-120b`模型內建兩種 AWS 提供的工具：筆記功能 （備註工具） 和任務管理 （任務工具）。這些工具會自動提供 - 您不需要在 `tools` 參數中定義它們。

**Notes 工具概觀**

此`notes`工具可讓模型在相同的對話工作階段中存放備註。這提供了簡單的記憶體機制，用於維護多個互動之間的內容。記憶體範圍僅限於目前的對話。

當模型使用筆記工具時，它會發出將 `name`設為 的`mcp_call`輸出`"notes"`。模型會根據您的請求決定適當的引數。

您可以使用自然語言 （例如，「記住我的最愛顏色是藍色」、「我告訴過您我的最愛顏色是什麼？」、「儲存我偏好早會的事實」、「回想我說的會議偏好設定」) 或您可以在提示中使用直接工具呼叫 (「使用筆記工具將我的電子郵件儲存為 john@example.com」、「查看我電子郵件地址的備註」)。

**任務工具概觀**

此`tasks`工具提供堆疊，用於管理對話工作階段中的任務。您可以將任務推送到堆疊並彈出，這有助於管理工作流程、提醒或階層式任務管理。任務會在整個對話工作階段中保留。記憶體範圍僅限於目前的對話。

當模型使用任務工具時，它會發出將 `name` 設為 的`mcp_call`輸出`"tasks"`。模型會根據您的請求決定適當的引數 （例如 `task.title`、 `method`和 `task.description`)。

您可以使用自然語言 （例如「新增任務以檢閱預算」、「推送提醒以呼叫用戶端」、「我需要執行的下一個任務是什麼？」、「退出最新任務」、「從我的堆疊取得最新任務」) 或直接在提示中呼叫工具 (「使用任務工具來推送「完成簡報」、「從堆疊中提取任務」、「新增「排程會議」到我的任務清單」)。

**程式碼範例：使用筆記和任務工具**

備註和任務工具內建於 `openai.gpt-oss-20b`和 `openai.gpt-oss-120b`模型中。您不需要在 `tools` 參數中明確定義它們，只需在提示中參考它們：

```
from openai import OpenAI

client = OpenAI(
    base_url="https://bedrock-mantle.us-east-1.api.aws/v1"
)

# The notes tool is built-in — just ask the model to use it
resp = client.responses.create(
    model="openai.gpt-oss-120b",
    input="Use the notes tool to store that my preferred language is Python.",
)

print(resp.output)
# The model automatically calls the notes tool via mcp_call

# Use the tasks tool to push a task
resp = client.responses.create(
    model="openai.gpt-oss-120b",
    input="Use the tasks tool to push a task: review the API documentation",
)

print(resp.output)
```

## 伺服器端工具使用與 AgentCore Gateway 整合
<a name="tool-use-agentcore-gateway"></a>

Amazon Bedrock 現在支援 [AgentCore Gateway](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway.html) 做為呼叫整合類型的伺服器端工具。此功能可讓您將模型直接連線至 AgentCore Gateway 端點，以便無縫存取透過閘道基礎設施管理的工具。

AgentCore Gateway 整合遵循與 Lambda 函數整合相同的模式，具有一個關鍵差異。

**Lambda 整合：**
+ 使用 Lambda ARNs
+ 直接叫用 AWS Lambda 函數

**AgentCore Gateway 整合：**
+ 使用 AgentCore Gateway ARNs
+ 透過 AgentCore Gateway 基礎設施路由工具呼叫
+ 提供集中式工具管理和探索

### Configuration
<a name="agentcore-gateway-configuration"></a>

**請求結構**

將 AgentCore Gateway 設定為工具來源時，請在回應 API 請求的`tools`陣列中使用下列結構。

```
{
  "type":"mcp",
  "server_label":"agentcore_tools",
  "connector_id":"arn:aws:bedrock-agentcore:us-west-2:342789630635:gateway/agentcore-intro-gateway-v2-swvq44sovp",
  "server_description":"AgentCore Gateway providing custom tools",
  "require_approval":"never"
}
```

**參數**


| 參數 | Type | 必要 | 描述 | 
| --- | --- | --- | --- | 
| type | string | 是 | 必須設定為 mcp | 
| server\_label | string | 是 | 請求中此工具連接器的唯一識別符 | 
| connector\_id | string | 是 | AgentCore Gateway 的 ARN | 
| server\_description | string | 否 | 此閘道所提供工具的人類可讀取描述 | 
| require\_approval | string | 是 | 欄位必須是 "never" | 

**完成請求範例**

```
{
  "model":"openai.gpt-oss-120b",
  "stream":true,
  "background":false,
  "store":false,
  "tools": [
    {
      "type":"mcp",
      "server_label":"agentcore_tools",
      "connector_id":"arn:aws:bedrock-agentcore:us-west-2:342789630635:gateway/agentcore-intro-gateway-v2-swvq44sovp",
      "server_description":"AgentCore Gateway providing custom tools",
      "require_approval":"never"
    }
  ],
  "input": [
    {
      "type":"message",
      "role":"user",
      "content": [
        {
          "type":"input_text",
          "text":"What is the weather in Seattle?"
        }
      ]
    }
  ]
}
```

### 先決條件
<a name="agentcore-gateway-prerequisites"></a>

使用 AgentCore Gateway 整合之前，請確定您有：

1. 建立具有設定目標的** AgentCore Gateway** (Lambda 函數、API Gateway 階段、OpenAPI 結構描述或 MCP 伺服器）

1. **設定的 IAM 許可**，允許 Bedrock 服務角色叫用閘道。請注意， Bedrock 僅支援具有 IAM 身分驗證的閘道。

1. 正確格式的**閘道 ARN** 

### AgentCore Gateway 整合的優點
<a name="agentcore-gateway-benefits"></a>
+ **集中式工具管理**：透過單一閘道端點管理所有工具
+ **工具探索**：客服人員可以透過閘道動態探索可用的工具
+ **安全性**：透過 IAM 和閘道政策的內建身分驗證和授權
+ 可**觀測性**：全面監控和記錄工具叫用
+ **彈性**：支援多種目標類型 (Lambda、API Gateway、OpenAPI、MCP 伺服器）

### IAM 許可
<a name="agentcore-gateway-iam"></a>

您的 Bedrock 執行角色需要許可才能叫用 AgentCore Gateway：

```
{
  "Version": "2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "bedrock-agentcore:InvokeGateway"
      ],
      "Resource": "arn:aws:bedrock-agentcore:us-west-2:342789630635:gateway/agentcore-intro-gateway-v2-swvq44sovp"
    }
  ]
}
```

### 後續步驟
<a name="agentcore-gateway-next-steps"></a>
+ 進一步了解如何[建立 AgentCore Gateway](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-create.html)
+ 探索[閘道目標類型](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-targets.html)
+ 檢閱[閘道安全最佳實務](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-security.html)