View a markdown version of this page

在 AgentCore 閘道中呼叫工具 - Amazon Bedrock AgentCore

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

在 AgentCore 閘道中呼叫工具

若要呼叫特定工具,請對閘道的 MCP 端點提出 POST 請求。在請求內文中指定 tools/call作為方法,以及工具的名稱及其引數。請求格式取決於 MCP 通訊協定版本:

範例
2025-11-25 and earlier
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

在版本 上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 API 變更支援的版本。

取代以下的值:

  • ${GatewayEndpoint} – 閘道的 URL,如 CreateGateway API 的回應所提供。

  • ${Authorization header} – 當您設定傳入授權時,來自身分提供者的授權憑證。

  • ${McpProtocolVersion} – 請求的 MCP 通訊協定版本,例如 2025-11-25。版本必須是閘道支援的版本。

  • ${RequestBody} – 請求內文的 JSON 承載,如模型內容通訊協定 (MCP) 中的呼叫工具所指定。包含 tools/call做為 method,並包含 工具name的 及其 arguments。

回應會傳回工具傳回的內容和相關聯的中繼資料。

呼叫工具的程式碼範例

若要查看閘道中呼叫工具的範例,請選取下列其中一種方法:

範例
curl (2025-11-25 and earlier)

下列 curl 請求顯示透過 ID 為 searchProducts的閘道呼叫 工具的範例請求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 } } } }'
curl (2026-07-28)

在版本 上2026-07-28,在內文中包含 Mcp-Method和 Mcp-Name request-metadata 標頭和_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": {} } } }'
Python requests package (2025-11-25 and earlier)

將 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))
Python requests package (2026-07-28)

在版本 上2026-07-28,在內文中包含 Mcp-Method和 Mcp-Name request-metadata 標頭和_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))
MCP Client
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())
Strands MCP Client

注意:這是用於叫用 代理程式。

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)
LangGraph MCP Client

注意:這是用於叫用 代理程式。

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

錯誤

tools/call 操作可能會傳回下列類型的錯誤:

  • 在 HTTP 狀態碼中傳回的錯誤:

    AuthenticationError

    由於身分驗證登入資料無效,請求失敗。

    HTTP 狀態碼:401

    AuthorizationError

    呼叫者沒有叫用工具的許可。

    HTTP 狀態碼:403

    ResourceNotFoundError

    指定的工具不存在。

    HTTP 狀態碼:404

    ValidationError

    提供的引數不符合工具的輸入結構描述。

    HTTP 狀態碼:400

    ToolExecutionError

    執行工具時發生錯誤。

    HTTP 狀態碼:500

    InternalServerError

    發生內部伺服器錯誤。

    HTTP 狀態碼:500

  • MCP 錯誤。如需這些錯誤類型的詳細資訊,請參閱模型內容通訊協定 (MCP) 文件中的錯誤處理。