클라이언트에서 리소스 읽기
이제 마지막 단계입니다. 클라이언트에 기능을 추가하여 MCP 서버에서 리소스 데이터를 읽어올 수 있도록 해 봅시다! 통화 목록과 해당 기호는 LLM이 사용자가 요청한 통화가 convert_currency() 도구에서 지원되는지 확인하고, 도구 함수의 인수가 유효한 통화 기호인지 검증하는 체크리스트로 활용될 수 있습니다.
currency_server.py 파일은 이미 실행 중이며 바로 사용할 수 있습니다.
이 연습은 강의의 일부입니다
Model Context Protocol (MCP) 입문
연습 안내
resource_uri라는str타입 매개변수를 받는 비동기 함수read_resource()를 정의하세요- 함수 내부에서
await와 함께session.read_resource()를 사용하여 주어진 URI의 리소스를 읽고, 결과를resource_content에 할당하세요 - 각 리소스의 내용을 반복하며
.mimeType과.text속성을 출력하세요
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
# Define an async function for reading MCP resources
____ ____ ____(____: ____):
"""Read a specific resource by URI."""
params = StdioServerParameters(
command=sys.executable,
args=["currency_server.py"],
)
async with stdio_client(params) as (reader, writer):
async with ClientSession(reader, writer) as session:
await session.initialize()
print(f"Reading resource: {resource_uri}")
# Read the resource from the session context
resource_content = ____ ____
# Print the contents of each resource
for content in ____:
print(f"\nContent ({content.mimeType}):")
print(content.____)
return resource_content
asyncio.run(read_resource("file://currencies.txt"))