View a markdown version of this page

从 AgentCore 网关读取资源 - Amazon Bedrock AgentCore

从 AgentCore 网关读取资源

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

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

替换以下值:

响应返回一个contents数组,其中每个条目都包含urimimeType、和text(对于文本内容)或blob(base64 编码的二进制内容)。

注意

resources/read操作将请求实时代理到下游 MCP 服务器。资源 URI 是返回的原始 URIresources/list(无目标前缀)。

注意

当多个目标公开相同的资源 URI 时,网关会将请求路由到resourcePriority值最低的目标。

重要

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

用于读取资源的代码示例

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

curl
  1. 以下 curl 请求显示了config://app-settings通过 ID mygateway-abcdefghij 为 URI 的网关读取带有 URI 的资源的示例请求。

    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": "read-resource-request", "method": "resources/read", "params": { "uri": "config://app-settings" } }'
Python requests package
  1. import requests import json def read_resource(gateway_url, access_token, resource_uri): headers = { "Content-Type": "application/json", "Authorization": f"Bearer {access_token}" } 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))
MCP Client
  1. 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 MCP Client
  1. 注意: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 Client
  1. 注意: 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" ))

错误

resources/read操作可能返回以下类型的错误:

  • 作为 HTTP 状态码的一部分返回的错误:

    AuthenticationError

    由于身份验证凭证无效,请求失败。

    HTTP 状态码:401

    AuthorizationError

    调用者无权读取资源。

    HTTP 状态码:403

    ResourceNotFoundError

    指定的资源 URI 不存在或未被任何目标公开。

    HTTP 状态码:404

    ValidationError

    提供的 URI 格式错误或缺失。

    HTTP 状态码:400

    InternalServerError

    发生内部服务器错误。

    HTTP 状态码:500

  • MCP 错误。有关这些类型的错误的更多信息,请参阅模型上下文协议 (MCP) 文档中的资源