

# AgentCore 게이트웨이에서 도구 호출
<a name="gateway-using-mcp-call"></a>

특정 도구를 호출하려면 게이트웨이의 MCP 엔드포인트에 POST 요청을 하고 요청 본문의 메`tools/call`서드로 , 도구 이름 및 인수를 지정합니다.

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

${RequestBody}
```

다음 값을 교체합니다.
+  `${GatewayEndpoint}` - [CreateGateway](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_CreateGateway.html) API의 응답에 제공된 게이트웨이의 URL입니다.
+  `${Authorization header}` - [인바운드 권한 부여를 설정할 때 자격 증명 공급자의 권한 부여](gateway-inbound-auth.md) 자격 증명입니다.
+  `${RequestBody}` - [모델 컨텍스트 프로토콜(MCP)](https://modelcontextprotocol.io/docs/getting-started/intro)의 [호출 도구](https://modelcontextprotocol.io/specification/2025-06-18/server/tools#calling-tools)에 지정된 요청 본문의 JSON 페이로드입니다. 를 `tools/call`로 포함하고 도구 및 해당 `name`의를 `method` 포함합니다`arguments`.

응답은 도구 및 관련 메타데이터에서 반환된 콘텐츠를 반환합니다.

## 호출 도구용 코드 샘플
<a name="gateway-using-mcp-call-examples"></a>

게이트웨이에서 사용 가능한 도구를 나열하는 예를 보려면 다음 방법 중 하나를 선택합니다.

**Example**  

1. 다음 curl 요청은 ID가 인 게이트웨이를 `searchProducts` 통해 라는 도구를 호출하는 요청의 예를 보여줍니다`mygateway-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
           }
         }
       }
   }'
   ```

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))
   ```

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())
   ```

1. 참고: 에이전트를 호출하기 위한 것입니다.

   ```
   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)
   ```

1. 참고: 에이전트를 호출하기 위한 것입니다.

   ```
   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/docs/getting-started/intro) 설명서의 [오류 처리를](https://modelcontextprotocol.io/specification/2024-11-05/server/tools#error-handlinghttps://modelcontextprotocol.io/specification/2024-11-05/server/tools#error-handling) 참조하세요.