

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 从 AgentCore 网关读取资源
<a name="gateway-using-mcp-resources-read"></a>

要读取特定资源，请向网关的 MCP 端点发出 POST 请求`resources/read`，并在请求正文和资源的 URI 中指定为方法：

**Example**  

```
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`，每个请求都带有`MCP-Protocol-Version`标头、`Mcp-Method`和`Mcp-Name`请求元数据标头以及正`_meta`文中的版本字段。因`Mcp-Name`为`resources/read`，是资源`uri`。  

```
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: resources/read
Mcp-Name: ${ResourceUri}

${RequestBody}
```

**注意**  
网关仅接受其`protocolConfiguration.mcp`配置`supportedVersions`字段中列出的 MCP 协议版本。要使用版本`2026-07-28`，请确保您的网关`supportedVersions`包含该版本。您可以使用 [ UpdateGateway ](https://docs.amazonaws.cn/bedrock-agentcore-control/latest/APIReference/API_UpdateGateway.html) API 更改支持的版本。

替换以下值：
+  `${GatewayEndpoint}`— 网关的 URL，如 [ CreateGateway ](https://docs.amazonaws.cn/bedrock-agentcore-control/latest/APIReference/API_CreateGateway.html) API 的响应中所提供。
+  `${Authorization header}`— 设置[入站授权时身份提供商提供的授权凭证](gateway-inbound-auth.md)。
+  `${McpProtocolVersion}`— 请求的 MCP 协议版本，例如`2025-11-25`。该版本必须是您的网关支持的版本。
+  `${ResourceUri}`— 资源的 URI，与请求正文`uri`中的相匹配。
+  `${RequestBody}`— 请求正文的 JSON 负载，如[模型上下文协议 (MCP) [https://modelcontextprotocol.io/specification/2025-06-18/server/resources#reading-resources](https://modelcontextprotocol.io/specification/2025-06-18/server/resources#reading-resources) 中的](https://modelcontextprotocol.io/docs/getting-started/intro)读取资源中所述。`resources/read`作为资源包括`method`并包括`uri`在内。在版本中`2026-07-28`，还要包括`_meta`版本字段`params`。

响应返回一个`contents`数组，其中每个条目都包含`uri``mimeType`、和`text`（对于文本内容）或`blob`（base64 编码的二进制内容）。

**注意**  
该`resources/read`操作将请求实时代理到下游 MCP 服务器。资源 URI 是返回的原始 URI`resources/list`（无目标前缀）。

**注意**  
当多个目标暴露相同的资源 URI 时，网关会将请求路由到具有最低`resourcePriority`值的目标。

**重要**  
该`uri`参数无需清理即可传递到下游 MCP 服务器目标。用户提供的资源 URI 可能包含恶意 URL 端点，用于 SSRF 攻击或尝试读取本地文件系统路径（例如，）。`file:///etc/passwd`在调用之前，根据预期的 URI 架构和模式的许可清单验证资源 URI。`resources/read`仅使用`resources/list`从可信的 MCP 服务器目标返回的 URI。

## 读取资源的代码示例
<a name="gateway-using-mcp-resources-read-examples"></a>

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

**Example**  
以下 curl 请求显示了`config://app-settings`通过带有 URI 的网关读取带有 URI 的资源的示例请求。`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": "read-resource-request",
    "method": "resources/read",
    "params": {
      "uri": "config://app-settings"
    }
}'
```
在版本上`2026-07-28`，在正文中包括`Mcp-Method`和`Mcp-Name`请求元数据标头以及`_meta`版本字段。对于`resources/read`，`Mcp-Name`是资源`uri`，`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: resources/read" \
  -H "Mcp-Name: config://app-settings" \
  -d '{
    "jsonrpc": "2.0",
    "id": "read-resource-request",
    "method": "resources/read",
    "params": {
      "uri": "config://app-settings",
      "_meta": {
        "io.modelcontextprotocol/protocolVersion": "2026-07-28",
        "io.modelcontextprotocol/clientInfo": {
          "name": "my-agent",
          "version": "1.0.0"
        },
        "io.modelcontextprotocol/clientCapabilities": {}
      }
    }
}'
```
将标`MCP-Protocol-Version`头设置为您的网关支持的版本。  

```
import requests
import json

def read_resource(gateway_url, access_token, resource_uri):
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {access_token}",
        "MCP-Protocol-Version": "2025-11-25"
    }

    payload = {
        "jsonrpc": "2.0",
        "id": "read-resource-request",
        "method": "resources/read",
        "params": {
            "uri": resource_uri
        }
    }

    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 = read_resource(
    gateway_url,
    access_token,
    "config://app-settings"  # Replace with the resource URI from resources/list
)
print(json.dumps(result, indent=2))
```
在版本上`2026-07-28`，在正文中包括`Mcp-Method`和`Mcp-Name`请求元数据标头以及`_meta`版本字段。对于`resources/read`，`Mcp-Name`是资源`uri`，`MCP-Protocol-Version`标头必须匹配`_meta.io.modelcontextprotocol/protocolVersion`。您的网关`supportedVersions`必须包括`2026-07-28`。  

```
import requests
import json

def read_resource(gateway_url, access_token, resource_uri):
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {access_token}",
        "MCP-Protocol-Version": "2026-07-28",
        "Mcp-Method": "resources/read",
        "Mcp-Name": resource_uri
    }

    payload = {
        "jsonrpc": "2.0",
        "id": "read-resource-request",
        "method": "resources/read",
        "params": {
            "uri": resource_uri,
            "_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 = read_resource(
    gateway_url,
    access_token,
    "config://app-settings"  # Replace with the resource URI from resources/list
)
print(json.dumps(result, indent=2))
```

```
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
from pydantic import AnyUrl
import asyncio

async def execute_mcp(
    url,
    token,
    resource_uri,
    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. Read specific resource
            print(f"Reading resource: {resource_uri}")
            resource_response = await session.read_resource(uri=AnyUrl(resource_uri))
            for content in resource_response.contents:
                print(f"URI: {content.uri}, MIME: {content.mimeType}")
                if hasattr(content, 'text') and content.text:
                    print(f"Text: {content.text}")
                elif hasattr(content, 'blob') and content.blob:
                    print(f"Blob (base64): {content.blob[:100]}...")
            return resource_response

async def main():
    url = "https://${GatewayEndpoint}/mcp"
    token = "your_bearer_token_here"
    resource_uri = "config://app-settings"
    await execute_mcp(
        url=url,
        token=token,
        resource_uri=resource_uri
    )


if __name__ == "__main__":
    asyncio.run(main())
```
注意：Strands SDK 资源支持可能会有所不同。使用前面显示的 MCP 客户端方法来实现最可靠的`resources/read`实现。  

```
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.read_resource_sync(uri="config://app-settings")
        print(result)

run_agent(<MCP URL>, <Access token>)
```
注意： LangGraph MCP 适配器资源支持可能会有所不同。使用前面显示的 MCP 客户端方法来实现最可靠的`resources/read`实现。  

```
import asyncio
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
from pydantic import AnyUrl

async def read_resource(url, token, resource_uri):
    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.read_resource(uri=AnyUrl(resource_uri))
            for content in response.contents:
                if hasattr(content, 'text') and content.text:
                    print(f"{content.uri}: {content.text}")
                elif hasattr(content, 'blob') and content.blob:
                    print(f"{content.uri}: <blob, {len(content.blob)} chars base64>")

asyncio.run(read_resource(
    "https://${GatewayEndpoint}/mcp",
    "${AccessToken}",
    "config://app-settings"
))
```

## 错误
<a name="gateway-using-mcp-resources-read-errors"></a>

该`resources/read`操作可能会返回以下类型的错误：
+ 作为 HTTP 状态码的一部分返回的错误：  
 **AuthenticationError**   
由于身份验证凭据无效，请求失败。  
 **HTTP 状态码**：401  
 **AuthorizationError**   
调用者没有读取资源的权限。  
 **HTTP 状态码**：403  
 **ResourceNotFoundError**   
指定的资源 URI 不存在或未被任何目标公开。  
 **HTTP 状态码**：404  
 **ValidationError**   
提供的 URI 格式错误或缺失。  
 **HTTP 状态码**：400  
 **InternalServerError**   
发生内部服务器错误。  
 **HTTP 状态码**：500
+ MCP 错误。有关这些类型错误的更多信息，请参阅[模型上下文协议 (MCP) ](https://modelcontextprotocol.io/docs/getting-started/intro) 文档[中的](https://modelcontextprotocol.io/specification/2025-06-18/server/resources)资源。