View a markdown version of this page

Appelez un outil dans une AgentCore passerelle - Amazon Bedrock AgentCore

Appelez un outil dans une AgentCore passerelle

Pour appeler un outil spécifique, envoyez une requête POST au point de terminaison MCP de la passerelle et spécifiez tools/call comme méthode dans le corps de la demande, le nom de l'outil et les arguments :

POST /mcp HTTP/1.1 Host: ${GatewayEndpoint} Content-Type: application/json Authorization: ${Authorization header} ${RequestBody}

Remplacez les valeurs suivantes :

  • ${GatewayEndpoint}— L'URL de la passerelle, telle que fournie dans la réponse de l'CreateGatewayAPI.

  • ${Authorization header}— Les informations d'autorisation fournies par le fournisseur d'identité lorsque vous configurez l'autorisation entrante.

  • ${RequestBody}— La charge utile JSON du corps de la requête, telle que spécifiée dans la section Outils d'appel du protocole MCP (Model Context Protocol). Incluez tools/call en tant que method et incluez name l'outil et sesarguments.

La réponse renvoie le contenu renvoyé par l'outil et les métadonnées associées.

Exemples de code pour les outils d'appel

Pour voir des exemples de liste des outils disponibles dans la passerelle, sélectionnez l'une des méthodes suivantes :

Exemple
curl
  1. La requête curl suivante montre un exemple de demande pour appeler un outil appelé searchProducts via une passerelle avec l'IDmygateway-abcdefghij.

    curl -X POST \ https://mygateway-abcdefghij.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ -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 } } } }'
Python requests package
  1. import requests import json def call_tool(gateway_url, access_token, tool_name, arguments): headers = { "Content-Type": "application/json", "Authorization": f"Bearer {access_token}" } 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))
MCP Client
  1. 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
  1. REMARQUE : Ceci est pour invoquer l'agent

    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
  1. REMARQUE : Ceci est pour invoquer l'agent

    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

Erreurs

L'tools/callopération peut renvoyer les types d'erreurs suivants :

  • Erreurs renvoyées dans le cadre du code d'état HTTP :

    AuthenticationError

    La demande a échoué en raison d'informations d'authentification non valides.

    Code d'état HTTP : 401

    AuthorizationError

    L'appelant n'est pas autorisé à invoquer l'outil.

    Code d'état HTTP : 403

    ResourceNotFoundError

    L'outil spécifié n'existe pas.

    Code d'état HTTP : 404

    ValidationError

    Les arguments fournis ne sont pas conformes au schéma d'entrée de l'outil.

    Code d'état HTTP : 400

    ToolExecutionError

    Une erreur s'est produite lors de l'exécution de l'outil.

    Code d'état HTTP : 500

    InternalServerError

    Une erreur interne du serveur s’est produite.

    Code d'état HTTP : 500

  • Erreurs MCP. Pour plus d'informations sur ces types d'erreurs, consultez la documentation relative à la gestion des erreurs dans la documentation MCP (Model Context Protocol).