View a markdown version of this page

Leggere una risorsa da un AgentCore gateway - Amazon Bedrock AgentCore

Leggere una risorsa da un AgentCore gateway

Per leggere una risorsa specifica, effettuate una richiesta POST all'endpoint MCP del gateway e specificate resources/read come metodo nel corpo della richiesta e nell'URI della risorsa:

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

Sostituisci i valori seguenti:

  • ${GatewayEndpoint}— L'URL del gateway, come fornito nella risposta dell'CreateGatewayAPI.

  • ${Authorization header}— Le credenziali di autorizzazione fornite dal provider di identità quando si configura l'autorizzazione in entrata.

  • ${RequestBody}— Il payload JSON del corpo della richiesta, come specificato in Reading resources in the Model Context Protocol (MCP). resources/readIncludi come method e uri includi la risorsa.

La risposta restituisce una contents matrice in cui ogni voce include urimimeType, e text (per il contenuto di testo) o blob (contenuto binario con codifica base64).

Nota

L'resources/readoperazione invia la richiesta in tempo reale al server MCP a valle. L'URI della risorsa è l'URI non elaborato restituito da resources/list (nessun prefisso di destinazione).

Nota

Quando più destinazioni espongono lo stesso URI di risorsa, il gateway indirizza la richiesta alla destinazione con il valore più bassoresourcePriority.

Importante

Il uri parametro viene passato alla destinazione del server MCP a valle senza sanificazione. Un URI di risorsa fornito dall'utente potrebbe contenere un endpoint URL dannoso destinato agli attacchi SSRF o al tentativo di leggere i percorsi dei file system locali (ad esempio,). file:///etc/passwd Convalida gli URI delle risorse rispetto a un elenco consentito di schemi e modelli URI previsti prima della chiamata. resources/read Utilizza solo gli URI restituiti resources/list da destinazioni server MCP affidabili.

Esempi di codice per leggere una risorsa

Per visualizzare esempi di lettura di una risorsa dal gateway, selezionate uno dei seguenti metodi:

Esempio
curl
  1. La seguente richiesta curl mostra un esempio di richiesta di lettura di una risorsa con URI config://app-settings attraverso un gateway con l'IDmygateway-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. NOTA: il supporto delle risorse Strands SDK può variare. Utilizzate l'approccio MCP Client di cui sopra per l'implementazione più affidabile. 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. NOTA: il supporto delle risorse dell'adattatore LangGraph MCP può variare. Utilizzate l'approccio MCP Client di cui sopra per l'implementazione più affidabileresources/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" ))

Errori

L'resources/readoperazione può restituire i seguenti tipi di errori:

  • Errori restituiti come parte del codice di stato HTTP:

    AuthenticationError

    La richiesta non è riuscita a causa di credenziali di autenticazione non valide.

    Codice di stato HTTP: 401

    AuthorizationError

    Il chiamante non è autorizzato a leggere la risorsa.

    Codice di stato HTTP: 403

    ResourceNotFoundError

    L'URI della risorsa specificata non esiste o non è esposto da nessuna destinazione.

    Codice di stato HTTP: 404

    ValidationError

    L'URI fornito non è valido o è mancante.

    Codice di stato HTTP: 400

    InternalServerError

    Si è verificato un errore interno del server.

    Codice di stato HTTP: 500

  • Errori MCP. Per ulteriori informazioni su questi tipi di errori, vedete Risorse nella documentazione del Model Context Protocol (MCP).