

# AgentCore Gateway 入門
<a name="gateway-quick-start"></a>

在此快速入門指南中，您將了解如何設定閘道，並使用 AgentCore CLI 將其整合到您的代理程式。如需更完整的指南和範例，請參閱 [Amazon Bedrock AgentCore Gateway GitHub 儲存庫](https://github.com/awslabs/amazon-bedrock-agentcore-samples/tree/main/01-tutorials/02-AgentCore-gateway)。

**注意**  
AgentCore CLI 提供命令和互動式 TUI 精靈，用於管理 AgentCore Gateway 資源。如需完整的 AWS SDK API 參考，請參閱 [AgentCore 控制平面操作](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/bedrock-agentcore-control.html)。

**Topics**
+ [先決條件](#gateway-quick-start-prereqs)
+ [步驟 1：設定和安裝](#gateway-quick-start-setup)
+ [步驟 2：建立閘道](#gateway-quick-start-create-gateway-setup)
+ [步驟 3：執行設定](#gateway-quick-start-run-setup)
+ [步驟 4：搭配 代理程式使用閘道](#gateway-quick-start-use-gateway-with-agents)
+ [您已建置的內容](#gateway-quick-start-what-youve-built)
+ [疑難排解](#gateway-quick-start-troubleshooting)
+ [快速驗證](#gateway-quick-start-quick-validation)
+ [清除](#gateway-quick-start-cleanup)
+ [後續步驟](#gateway-quick-start-next-steps)

## 先決條件
<a name="gateway-quick-start-prereqs"></a>

開始之前，請確定您有下列項目：
+  ** AWS 已設定登入資料的帳戶**。若要設定登入資料，您可以依照 [CLI AWS 入門](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html)中的步驟安裝和使用 AWS 命令列界面。
+  已安裝 **Node.js 18\+** （適用於 AgentCore CLI)。
+  已安裝 **Python 3.10\+** （適用於代理程式指令碼）。
+  建立角色、Lambda 函數和使用 Amazon Bedrock AgentCore 的 **IAM 許可**。
+  **模型存取** – 在 Amazon Bedrock 主控台 （或示範代理程式的其他模型） 中啟用 Anthropic 的 Claude Sonnet 3.7

## 步驟 1：設定和安裝
<a name="gateway-quick-start-setup"></a>

全域安裝 AgentCore CLI：

```
npm install -g @aws/agentcore
```

使用 代理程式和閘道建立新的 AgentCore 專案：

**Example**  

1. 

   ```
   agentcore create --name MyGatewayAgent --defaults
   ```

   `--defaults` 旗標會使用預設 Python Strands 代理程式建立專案。或者，省略 `--defaults`和 `--name` 以使用互動式精靈來選取您偏好的架構。

1. 您也可以`agentcore create`在沒有旗標的情況下執行 ，以使用互動式精靈。精靈會引導您選取專案名稱、客服人員架構、模型提供者和其他選項。

## 步驟 2：建立閘道
<a name="gateway-quick-start-create-gateway-setup"></a>

使用 AgentCore CLI 將閘道和目標新增至您的專案：

**Example**  

1. 

   ```
   # Add a gateway with no inbound auth (simplest for getting started)
   agentcore add gateway --name TestGateway --authorizer-type NONE --runtimes MyGatewayAgent
   
   # Add a Lambda function target
   agentcore add gateway-target --name TestLambdaTarget --type lambda-function-arn \
     --lambda-arn <YOUR_LAMBDA_ARN> \
     --tool-schema-file tools.json \
     --gateway TestGateway
   ```

1. 執行 `agentcore`以開啟 TUI，然後選取**新增**，然後選擇**閘道** ：

1. 輸入閘道名稱：  
![閘道精靈：輸入名稱](https://docs.aws.amazon.com/zh_tw/bedrock-agentcore/latest/devguide/images/tui/gateway-add-name.png)

1. 選取授權方類型。針對此快速入門，選擇 **NONE** ：  
![閘道精靈：選取 NONE 授權方](https://docs.aws.amazon.com/zh_tw/bedrock-agentcore/latest/devguide/images/tui/gateway-add-auth-none.png)

1. 設定進階選項或接受預設值：  
![閘道精靈：進階組態](https://docs.aws.amazon.com/zh_tw/bedrock-agentcore/latest/devguide/images/tui/gateway-add-advanced.png)

1. 檢閱組態，然後按 **Enter** 鍵確認：  
![閘道精靈：檢閱組態](https://docs.aws.amazon.com/zh_tw/bedrock-agentcore/latest/devguide/images/tui/gateway-add-confirm.png)

   接著，再次選取**新增**，然後選擇**閘道目標**以新增 Lambda 函數目標：

1. 輸入目標名稱。

1. 選取 **Lambda 函數**做為目標類型：  
![閘道目標精靈：選取 Lambda 函數](https://docs.aws.amazon.com/zh_tw/bedrock-agentcore/latest/devguide/images/tui/gateway-target-type-lambda.png)

1. 輸入 Lambda ARN 和工具結構描述檔案路徑，然後確認。

若要改用 JWT 型授權，`--authorizer-type CUSTOM_JWT`請使用 OAuth 探索 URL 指定 ：

**Example**  

1. 

   ```
   agentcore add gateway --name TestGateway \
     --authorizer-type CUSTOM_JWT \
     --discovery-url https://cognito-idp.us-east-1.amazonaws.com/<POOL_ID>/.well-known/openid-configuration \
     --allowed-audience <CLIENT_ID> \
     --runtimes MyGatewayAgent
   ```

1. 執行 `agentcore`以開啟 TUI，然後選取**新增**，然後選擇**閘道** 。出現授權方類型的提示時，選取**自訂 JWT**：

1. 輸入閘道名稱：  
![閘道精靈：輸入名稱](https://docs.aws.amazon.com/zh_tw/bedrock-agentcore/latest/devguide/images/tui/gateway-add-name.png)

1. 選取**自訂 JWT** 做為授權方類型：  
![閘道精靈：選取自訂 JWT 授權方](https://docs.aws.amazon.com/zh_tw/bedrock-agentcore/latest/devguide/images/tui/gateway-add-auth-jwt.png)

1. 輸入 OAuth 探索 URL，並在出現提示時允許對象。

1. 設定進階選項或接受預設值：  
![閘道精靈：進階組態](https://docs.aws.amazon.com/zh_tw/bedrock-agentcore/latest/devguide/images/tui/gateway-add-advanced.png)

1. 檢閱組態，然後按 **Enter** 鍵確認：  
![閘道精靈：檢閱組態](https://docs.aws.amazon.com/zh_tw/bedrock-agentcore/latest/devguide/images/tui/gateway-add-confirm.png)

## 步驟 3：執行設定
<a name="gateway-quick-start-run-setup"></a>

將您的專案部署至 AWS：

```
agentcore deploy
```

CLI 會合成 AWS CDK 堆疊，並將您的閘道、目標和代理程式部署到 Amazon Bedrock AgentCore。這大約需要 2-3 分鐘。

## 步驟 4：搭配 代理程式使用閘道
<a name="gateway-quick-start-use-gateway-with-agents"></a>

使用 AgentCore CLI 擷取您的閘道 URL：

```
agentcore status
```

建立名為 的新檔案`run_agent.py`，並插入下列程式碼。首先安裝 Python 相依性：

```
pip install strands-agents mcp
```

```
"""
Agent script to test the Gateway
Run this after setup: python run_agent.py
"""

from strands import Agent
from strands.models import BedrockModel
from strands.tools.mcp.mcp_client import MCPClient
from mcp.client.streamable_http import streamablehttp_client
import json
import sys

def create_streamable_http_transport(mcp_url: str):
    return streamablehttp_client(mcp_url)

def get_full_tools_list(client):
    """Get all tools with pagination support"""
    more_tools = True
    tools = []
    pagination_token = None
    while more_tools:
        tmp_tools = client.list_tools_sync(pagination_token=pagination_token)
        tools.extend(tmp_tools)
        if tmp_tools.pagination_token is None:
            more_tools = False
        else:
            more_tools = True
            pagination_token = tmp_tools.pagination_token
    return tools

def run_agent():
    # Get the gateway URL from agentcore status
    gateway_url = "<YOUR_GATEWAY_URL>"  # Replace with URL from 'agentcore status'

    # Model configuration - change if needed
    model_id = "anthropic.claude-3-7-sonnet-20250219-v1:0"

    print("Starting AgentCore Gateway Test Agent")
    print(f"Gateway URL: {gateway_url}")
    print(f"Model: {model_id}")
    print("-" * 60)

    # Setup Bedrock model
    bedrockmodel = BedrockModel(
        model_id=model_id,
        streaming=True,
    )

    # Setup MCP client (no auth token needed for NONE authorizer)
    mcp_client = MCPClient(lambda: create_streamable_http_transport(gateway_url))

    with mcp_client:
        # List available tools
        tools = get_full_tools_list(mcp_client)
        print(f"\nAvailable tools: {[tool.tool_name for tool in tools]}")
        print("-" * 60)

        # Create agent
        agent = Agent(model=bedrockmodel, tools=tools)

        # Interactive loop
        print("\nInteractive Agent Ready!")
        print("Try asking: 'What's the weather in Seattle?'")
        print("Type 'exit', 'quit', or 'bye' to end.\n")

        while True:
            user_input = input("You: ")
            if user_input.lower() in ["exit", "quit", "bye"]:
                print("Goodbye!")
                break

            print("\nThinking...\n")
            response = agent(user_input)
            print(f"\nAgent: {response.message.get('content', response)}\n")

if __name__ == "__main__":
    run_agent()
```

### 執行您的代理程式
<a name="gateway-quick-start-run-agent"></a>

透過執行代理程式並與工具互動來測試您的閘道。

```
python run_agent.py
```

就這樣！代理程式將啟動，您可以詢問下列問題：
+ 「西雅圖的天氣如何？」
+ 「在紐約是幾點？」

## 您已建置的內容
<a name="gateway-quick-start-what-youve-built"></a>

透過本入門教學課程，您已建立下列資源：
+  **MCP 伺服器 （閘道）**：位於 的受管端點 `https://gateway-id.gateway.bedrock-agentcore.region.amazonaws.com/mcp` 
+  **Lambda 工具** ：傳回測試資料的模擬函數 （天氣：「72°F，陽光」，時間：「下午 2：30」)
+  **AI 代理程式** ：可探索和使用您的工具的 Claude 支援助理

## 疑難排解
<a name="gateway-quick-start-troubleshooting"></a>

下表顯示一些可能的問題及其解決方案：


| 問題 | 解決方案 | 
| --- | --- | 
| 「沒有名為 'strands' 的模組」 | 執行： `pip install strands-agents` | 
| 「未啟用模型」 | 在 Bedrock 主控台中啟用 Claude Sonnet 3.7 → 模型存取 | 
| 「AccessDeniedException」 | 檢查 bedrock-agentcore 的 IAM 許可：\* | 
| 閘道未回應 | 建立 DNS 傳播後等待 30-60 秒 | 

## 快速驗證
<a name="gateway-quick-start-quick-validation"></a>

在終端機中執行下列命令，以檢查您的閘道是否正常運作。

```
# Check your Gateway is working
curl -X POST YOUR_GATEWAY_URL \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'

# Watch live logs
aws logs tail /aws/bedrock-agentcore/gateways/YOUR_GATEWAY_ID --follow
```

## 清除
<a name="gateway-quick-start-cleanup"></a>

若要從專案中移除閘道及其目標：

```
agentcore remove gateway --name TestGateway
```

若要移除所有資源並重新部署：

```
agentcore remove all
agentcore deploy
```

## 後續步驟
<a name="gateway-quick-start-next-steps"></a>
+  **自訂 Lambda 工具** ：使用業務邏輯建立 Lambda 函數
+  **新增您自己的 APIs**：使用真實服務的 OpenAPI 規格擴展閘道
+  **生產設定**：設定 VPC 端點、自訂網域和監控