

# 从 AgentCore 网关获取提示
<a name="gateway-using-mcp-prompts-get"></a>

要获得特定的提示，请向网关的 MCP 端点发出 POST 请求，并在请求正文中指定`prompts/get`方法、提示名称和参数：

```
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的响应所示。
+  `${Authorization header}`— 设置[入站授权时身份提供商提供的授权凭证](gateway-inbound-auth.md)。
+  `${RequestBody}`— 请求正文的 JSON 有效负载，如在[模型上下文协议 (MCP)](https://modelcontextprotocol.io/docs/getting-started/intro) 中[获取提示](https://modelcontextprotocol.io/specification/2025-06-18/server/prompts#getting-a-prompt)中所述。包含`prompts/get`为`method`并包括提示及其的`arguments`。`name`

响应以消息数组的形式返回呈现的提示，每条消息都有角色和内容。

**注意**  
该`prompts/get`操作将请求实时代理到下游 MCP 服务器。提示名称必须包含目标前缀（例如`myTarget___myPrompt`）。

## 获取提示的代码示例
<a name="gateway-using-mcp-prompts-get-examples"></a>

要查看从网关获取提示的示例，请选择以下方法之一：

**Example**  

1. 以下 curl 请求显示了`myTarget___code_review`通过网关调用 ID `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": "get-prompt-request",
       "method": "prompts/get",
       "params": {
         "name": "myTarget___code_review",
         "arguments": {
           "language": "python",
           "code": "print(\"hello\")"
         }
       }
   }'
   ```

1. 

   ```
   import requests
   import json
   
   def get_prompt(gateway_url, access_token, prompt_name, arguments):
       headers = {
           "Content-Type": "application/json",
           "Authorization": f"Bearer {access_token}"
       }
   
       payload = {
           "jsonrpc": "2.0",
           "id": "get-prompt-request",
           "method": "prompts/get",
           "params": {
               "name": prompt_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 = get_prompt(
       gateway_url,
       access_token,
       "myTarget___code_review",  # Replace with {targetName}___{promptName}
       {"language": "python", "code": "print('hello')"}
   )
   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,
       prompt_name,
       prompt_arguments,
       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. Get specific prompt
               print(f"Getting prompt: {prompt_name}")
               prompt_response = await session.get_prompt(
                   name=prompt_name,
                   arguments=prompt_arguments
               )
               print(f"Prompt response: {prompt_response}")
               return prompt_response
   
   async def main():
       url = "https://${GatewayEndpoint}/mcp"
       token = "your_bearer_token_here"
       prompt_name = "myTarget___code_review"
       prompt_arguments = {
           "language": "python",
           "code": "print('hello')"
       }
       await execute_mcp(
           url=url,
           token=token,
           prompt_name=prompt_name,
           prompt_arguments=prompt_arguments
       )
   
   
   if __name__ == "__main__":
       asyncio.run(main())
   ```

1. 注意： LangGraph MCP 适配器提示支持可能有所不同。使用上面的 MCP 客户端方法实现最可靠的`prompts/get`实现。

   ```
   import asyncio
   from mcp import ClientSession
   from mcp.client.streamable_http import streamablehttp_client
   
   async def get_prompt(url, token, prompt_name, arguments):
       headers = {"Authorization": f"Bearer {token}"}
       async with streamablehttp_client(url=url, headers=headers) as (
           read_stream, write_stream, callA
       ):
           async with ClientSession(read_stream, write_stream) as session:
               await session.initialize()
               response = await session.get_prompt(
                   name=prompt_name,
                   arguments=arguments
               )
               for message in response.messages:
                   print(f"{message.role}: {message.content}")
   
   asyncio.run(get_prompt(
       "https://${GatewayEndpoint}/mcp",
       "${AccessToken}",
       "myTarget___code_review",
       {"language": "python", "code": "print('hello')"}
   ))
   ```

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

该`prompts/get`操作可能返回以下类型的错误：
+ 作为 HTTP 状态码的一部分返回的错误：  
 **AuthenticationError**   
由于身份验证凭证无效，请求失败。  
 **HTTP 状态码**：401  
 **AuthorizationError**   
来电者没有获得提示的权限。  
 **HTTP 状态码**：403  
 **ResourceNotFoundError**   
指定的提示不存在。  
 **HTTP 状态码**：404  
 **ValidationError**   
提供的参数不满足提示的必需参数。  
 **HTTP 状态码**：400  
 **InternalServerError**   
发生内部服务器错误。  
 **HTTP 状态码**：500
+ MCP 错误。有关这些类型的错误的更多信息，请参阅[模型上下文协议 (MCP)](https://modelcontextprotocol.io/docs/getting-started/intro) 文档中的[提示](https://modelcontextprotocol.io/specification/2025-06-18/server/prompts)。