View a markdown version of this page

從 AgentCore 閘道讀取資源 - Amazon Bedrock AgentCore

從 AgentCore 閘道讀取資源

若要讀取特定資源,請對閘道的 MCP 端點提出 POST 請求,並在請求內文和資源的 URI 中指定 resources/read 作為方法:

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

取代以下的值:

  • ${GatewayEndpoint} – 閘道的 URL,如 CreateGateway API 的回應所提供。

  • ${Authorization header} – 當您設定傳入授權時,來自身分提供者的授權憑證。

  • ${RequestBody} – 請求內文的 JSON 承載,如模型內容通訊協定 (MCP) 中的讀取資源所指定。包含 resources/read做為 method,並包含 資源uri的 。

回應會傳回contents陣列mimeType,其中每個項目都包含 uri、 和 text(適用於文字內容) 或 blob(base64 編碼的二進位內容)。

注意

resources/read 操作會將即時請求代理到下游 MCP 伺服器。資源 URI 是 傳回的原始 URI resources/list(無目標字首)。

注意

當多個目標公開相同的資源 URI 時,閘道會將請求路由到具有最低resourcePriority值的目標。

重要

uri 參數會傳遞至下游 MCP 伺服器目標,無需淨化。使用者提供的資源 URI 可能包含用於 SSRF 攻擊的惡意 URL 端點,或嘗試讀取本機檔案系統路徑 (例如 file:///etc/passwd)。在呼叫 之前,根據預期 URIs 結構描述和模式的允許清單驗證資源 URIresources/read。僅使用 resources/list自信任的 MCP 伺服器目標傳回URIs。

讀取資源的程式碼範例

若要查看從閘道讀取資源的範例,請選取下列其中一種方法:

範例
curl
  1. 下列 curl 請求顯示透過 ID 為 的config://app-settings閘道讀取具有 URI 資源的範例請求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": "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) 文件中的資源