View a markdown version of this page

Chiama uno strumento in un AgentCore gateway - Fondamento Amazon AgentCore

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Chiama uno strumento in un AgentCore gateway

Per chiamare uno strumento specifico, effettua una richiesta POST all'endpoint MCP del gateway. Specificate tools/call come metodo nel corpo della richiesta, insieme al nome dello strumento e ai relativi argomenti. Il formato della richiesta dipende dalla versione del protocollo MCP:

Esempio
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

Nella versione2026-07-28, ogni richiesta contiene l'MCP-Protocol-Versionintestazione, le intestazioni Mcp-Method e i Mcp-Name metadati della richiesta e i campi della versione nel corpo. _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}
Nota

Il gateway accetta solo le versioni del protocollo MCP elencate nel campo della sua configurazione. supportedVersions protocolConfiguration.mcp Per utilizzare la versione2026-07-28, assicurati che sia supportedVersions inclusa nel gateway. Puoi modificare le versioni supportate con l'UpdateGatewayAPI.

Sostituisci i valori seguenti:

  • ${GatewayEndpoint}— L'URL del gateway, come fornito nella risposta dell'CreateGatewayAPI.

  • ${Authorization header}— Le credenziali di autorizzazione del provider di identità quando si imposta l'autorizzazione in entrata.

  • ${McpProtocolVersion}— La versione del protocollo MCP per la richiesta, ad esempio. 2025-11-25 La versione deve essere quella supportata dal gateway.

  • ${RequestBody}— Il payload JSON del corpo della richiesta, come specificato in Calling tools in the Model Context Protocol (MCP). tools/callIncludi come method e name includi lo strumento e il relativo. arguments

La risposta restituisce il contenuto restituito dallo strumento e i metadati associati.

Esempi di codice per chiamare gli strumenti

Per visualizzare esempi di strumenti di chiamata nel gateway, selezionate uno dei seguenti metodi:

Esempio
curl (2025-11-25 and earlier)

La seguente richiesta curl mostra un esempio di richiesta di chiamata a uno strumento chiamato searchProducts tramite un gateway con l'IDmygateway-abcdefghij. Imposta l'MCP-Protocol-Versionintestazione su una versione supportata dal tuo gateway.

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)

A seconda della versione2026-07-28, includi le intestazioni Mcp-Method e dei Mcp-Name metadati di richiesta e i campi della versione nel _meta corpo. L'intestazione deve corrispondere. MCP-Protocol-Version _meta.io.modelcontextprotocol/protocolVersion Il tuo gateway supportedVersions deve includere2026-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)

Imposta l'MCP-Protocol-Versionintestazione su una versione supportata dal tuo gateway.

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)

A seconda della versione2026-07-28, includi le intestazioni Mcp-Method e dei Mcp-Name metadati di richiesta e i campi della versione nel _meta corpo. L'intestazione deve corrispondere. MCP-Protocol-Version _meta.io.modelcontextprotocol/protocolVersion Il tuo gateway supportedVersions deve includere2026-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

NOTA: serve per invocare un agente.

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

NOTA: serve per invocare un agente.

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

Errori

L'tools/calloperazione può restituire i seguenti tipi di errori:

  • Errori restituiti come parte del codice di stato HTTP:

    AuthenticationError

    La richiesta non è riuscita a causa di credenziali di autenticazione non valide.

    Codice di stato HTTP: 401

    AuthorizationError

    Il chiamante non è autorizzato a richiamare lo strumento.

    Codice di stato HTTP: 403

    ResourceNotFoundError

    Lo strumento specificato non esiste.

    Codice di stato HTTP: 404

    ValidationError

    Gli argomenti forniti non sono conformi allo schema di input dello strumento.

    Codice di stato HTTP: 400

    ToolExecutionError

    Si è verificato un errore durante l'esecuzione dello strumento.

    Codice di stato HTTP: 500

    InternalServerError

    Si è verificato un errore interno del server.

    Codice di stato HTTP: 500

  • Errori MCP. Per ulteriori informazioni su questi tipi di errori, consulta la documentazione del Model Context Protocol (MCP).