

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 在 AgentCore 网关中调用工具
<a name="gateway-using-mcp-call"></a>

要调用特定工具，请向网关的 MCP 端点发出 POST 请求。在请求正文中指定`tools/call`为方法，并指定工具的名称及其参数。请求格式取决于 MCP 协议版本：

**Example**  

```
POST /mcp HTTP/1.1
Host: ${GatewayEndpoint}
Accept: application/json, text/event-stream
Content-Type: application/json
Authorization: ${Authorization header}
MCP-Protocol-Version: ${McpProtocolVersion}

${RequestBody}
```
在版本上`2026-07-28`，每个请求都带有`MCP-Protocol-Version`标头、`Mcp-Method`和`Mcp-Name`请求元数据标头以及正`_meta`文中的版本字段。  

```
POST /mcp HTTP/1.1
Host: ${GatewayEndpoint}
Accept: application/json, text/event-stream
Content-Type: application/json
Authorization: ${Authorization header}
MCP-Protocol-Version: 2026-07-28
Mcp-Method: tools/call
Mcp-Name: ${ToolName}

${RequestBody}
```

**注意**  
网关仅接受其`protocolConfiguration.mcp`配置`supportedVersions`字段中列出的 MCP 协议版本。要使用版本`2026-07-28`，请确保您的网关`supportedVersions`包含该版本。您可以使用 [ UpdateGateway ](https://docs.amazonaws.cn/bedrock-agentcore-control/latest/APIReference/API_UpdateGateway.html) API 更改支持的版本。

替换以下值：
+  `${GatewayEndpoint}`— 网关的 URL，如 [ CreateGateway ](https://docs.amazonaws.cn/bedrock-agentcore-control/latest/APIReference/API_CreateGateway.html) API 的响应中所提供。
+  `${Authorization header}`— 设置[入站授权时身份提供商提供的授权凭证](gateway-inbound-auth.md)。
+  `${McpProtocolVersion}`— 请求的 MCP 协议版本，例如`2025-11-25`。该版本必须是您的网关支持的版本。
+  `${RequestBody}`— 请求正文的 JSON 负载，如[模型上下文协议 (MCP) [https://modelcontextprotocol.io/specification/2025-06-18/server/tools#calling-tools](https://modelcontextprotocol.io/specification/2025-06-18/server/tools#calling-tools) 中的](https://modelcontextprotocol.io/docs/getting-started/intro)调用工具中所述。`tools/call`作为 “包括” `method` 并`name`包括该工具及其`arguments`的。

响应返回该工具返回的内容和相关的元数据。

## 调用工具的代码示例
<a name="gateway-using-mcp-call-examples"></a>

要查看网关中调用工具的示例，请选择以下方法之一：

**Example**  
以下 curl 请求显示了`searchProducts`通过网关调用具有 ID `mygateway-abcdefghij` 的工具的示例请求。将标`MCP-Protocol-Version`头设置为您的网关支持的版本。  

```
curl -X POST \
  https://mygateway-abcdefghij.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp \
  -H "Accept: application/json, text/event-stream" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "MCP-Protocol-Version: 2025-11-25" \
  -d '{
    "jsonrpc": "2.0",
    "id": "invoke-tool-request",
    "method": "tools/call",
    "params": {
      "name": "searchProducts",
      "arguments": {
        "query": "wireless headphones",
        "category": "Electronics",
        "maxResults": 2,
        "priceRange": {
          "min": 50.00,
          "max": 200.00
        }
      }
    }
}'
```
在版本上`2026-07-28`，在正文中包括`Mcp-Method`和`Mcp-Name`请求元数据标头以及`_meta`版本字段。标`MCP-Protocol-Version`题必须匹配`_meta.io.modelcontextprotocol/protocolVersion`。您的网关`supportedVersions`必须包括`2026-07-28`。  

```
curl -X POST \
  https://mygateway-abcdefghij.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp \
  -H "Accept: application/json, text/event-stream" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "MCP-Protocol-Version: 2026-07-28" \
  -H "Mcp-Method: tools/call" \
  -H "Mcp-Name: searchProducts" \
  -d '{
    "jsonrpc": "2.0",
    "id": "invoke-tool-request",
    "method": "tools/call",
    "params": {
      "name": "searchProducts",
      "arguments": {
        "query": "wireless headphones",
        "category": "Electronics",
        "maxResults": 2,
        "priceRange": {
          "min": 50.00,
          "max": 200.00
        }
      },
      "_meta": {
        "io.modelcontextprotocol/protocolVersion": "2026-07-28",
        "io.modelcontextprotocol/clientInfo": {
          "name": "my-agent",
          "version": "1.0.0"
        },
        "io.modelcontextprotocol/clientCapabilities": {}
      }
    }
}'
```
将标`MCP-Protocol-Version`头设置为您的网关支持的版本。  

```
import requests
import json

def call_tool(gateway_url, access_token, tool_name, arguments):
    headers = {
        "Accept": "application/json, text/event-stream",
        "Content-Type": "application/json",
        "Authorization": f"Bearer {access_token}",
        "MCP-Protocol-Version": "2025-11-25"
    }

    payload = {
        "jsonrpc": "2.0",
        "id": "call-tool-request",
        "method": "tools/call",
        "params": {
            "name": tool_name,
            "arguments": arguments
        }
    }

    response = requests.post(gateway_url, headers=headers, json=payload)
    return response.json()

# Example usage
gateway_url = "https://${GatewayEndpoint}/mcp" # Replace with your actual gateway endpoint
access_token = "${AccessToken}" # Replace with your actual access token
result = call_tool(
    gateway_url,
    access_token,
    "openapi-target-1___get_orders_byId",  # Replace with <{TargetId}__{ToolName}>
    {"orderId": "ORD-12345-67890", "customerId": "CUST-98765"}
)
print(json.dumps(result, indent=2))
```
在版本上`2026-07-28`，在正文中包括`Mcp-Method`和`Mcp-Name`请求元数据标头以及`_meta`版本字段。标`MCP-Protocol-Version`题必须匹配`_meta.io.modelcontextprotocol/protocolVersion`。您的网关`supportedVersions`必须包括`2026-07-28`。  

```
import requests
import json

def call_tool(gateway_url, access_token, tool_name, arguments):
    headers = {
        "Accept": "application/json, text/event-stream",
        "Content-Type": "application/json",
        "Authorization": f"Bearer {access_token}",
        "MCP-Protocol-Version": "2026-07-28",
        "Mcp-Method": "tools/call",
        "Mcp-Name": tool_name
    }

    payload = {
        "jsonrpc": "2.0",
        "id": "call-tool-request",
        "method": "tools/call",
        "params": {
            "name": tool_name,
            "arguments": arguments,
            "_meta": {
                "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                "io.modelcontextprotocol/clientInfo": {"name": "my-agent", "version": "1.0.0"},
                "io.modelcontextprotocol/clientCapabilities": {}
            }
        }
    }

    response = requests.post(gateway_url, headers=headers, json=payload)
    return response.json()

# Example usage
gateway_url = "https://${GatewayEndpoint}/mcp" # Replace with your actual gateway endpoint
access_token = "${AccessToken}" # Replace with your actual access token
result = call_tool(
    gateway_url,
    access_token,
    "openapi-target-1___get_orders_byId",  # Replace with <{TargetId}__{ToolName}>
    {"orderId": "ORD-12345-67890", "customerId": "CUST-98765"}
)
print(json.dumps(result, indent=2))
```

```
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
import asyncio

async def execute_mcp(
    url,
    token,
    tool_params,
    headers=None
):
    default_headers = {
        "Authorization": f"Bearer {token}"
    }
    headers = {**default_headers, **(headers or {})}

    async with streamablehttp_client(
       url=url,
       headers=headers,
    ) as (
        read_stream,
        write_stream,
        callA,
    ):
        async with ClientSession(read_stream, write_stream) as session:
            # 1. Perform initialization handshake
            print("Initializing MCP...")
            _init_response = await session.initialize()
            print(f"MCP Server Initialize successful! - {_init_response}")

            # 2. Call specific tool
            print(f"Calling tool: {tool_params['name']}")
            tool_response = await session.call_tool(
                name=tool_params['name'],
                arguments=tool_params['arguments']
            )
            print(f"Tool response: {tool_response}")
            return tool_response

async def main():
    url = "https://${GatewayEndpoint}/mcp"
    token = "your_bearer_token_here"
    tool_params = {
        "name": "LambdaTarget___get_order_tool",
        "arguments": {
            "orderId": "order123"
        }
    }
    await execute_mcp(
        url=url,
        token=token,
        tool_params=tool_params
    )


if __name__ == "__main__":
    asyncio.run(main())
```
注意：这是为了调用代理。  

```
from strands.tools.mcp.mcp_client import MCPClient
from mcp.client.streamable_http import streamablehttp_client

def create_streamable_http_transport(mcp_url: str, access_token: str):
    return streamablehttp_client(mcp_url, headers={"Authorization": f"Bearer {access_token}"})

def run_agent(mcp_url: str, access_token: str):
    mcp_client = MCPClient(lambda: create_streamable_http_transport(mcp_url, access_token))

    with mcp_client:
        result = mcp_client.call_tool_sync(
            tool_use_id="tool-123",  # A unique ID for the tool call
            name="openapi-target-1___get_orders",  # The name of the tool to invoke
            arguments={}  # A dictionary of arguments for the tool
        )
        print(result)

url = {gatewayUrl}
token = {AccessToken}
run_agent(url, token)
```
注意：这是为了调用代理。  

```
import asyncio

from langgraph.prebuilt import create_react_agent

def execute_agent(
    user_prompt,
    model_id,
    region,
    tools
):
    model = ChatBedrock(model_id=model_id, region_name=region)

    agent = create_react_agent(model, tools)
    _response = asyncio.run(agent.ainvoke({
        "messages": user_prompt
    }))

    _response = _response.get('messages', {})[1].content
    print(
        f"Invoke Langchain Agents Response"
        f"Response - \n{_response}\n"
    )
    return _response
```

## 错误
<a name="gateway-using-mcp-call-errors"></a>

该`tools/call`操作可能会返回以下类型的错误：
+ 作为 HTTP 状态码的一部分返回的错误：  
 **AuthenticationError**   
由于身份验证凭据无效，请求失败。  
 **HTTP 状态码**：401  
 **AuthorizationError**   
呼叫者无权调用该工具。  
 **HTTP 状态码**：403  
 **ResourceNotFoundError**   
指定的工具不存在。  
 **HTTP 状态码**：404  
 **ValidationError**   
提供的参数不符合该工具的输入架构。  
 **HTTP 状态码**：400  
 **ToolExecutionError**   
执行该工具时出错。  
 **HTTP 状态码**：500  
 **InternalServerError**   
发生内部服务器错误。  
 **HTTP 状态码**：500
+ MCP 错误。有关这些类型错误的更多信息，请参阅[模型上下文协议 (MCP) [ 中的](https://modelcontextprotocol.io/specification/2024-11-05/server/tools#error-handlinghttps://modelcontextprotocol.io/specification/2024-11-05/server/tools#error-handling)错误处理](https://modelcontextprotocol.io/docs/getting-started/intro)文档。