시작하기무료로 시작하기

MCP에서 리소스와 프롬프트 가져오기

작성한 통화 서버는 리소스(file://currencies.txt)와 프롬프트(convert_currency_prompt)를 제공합니다. 이 프롬프트는 사용자의 요청에 작업별 컨텍스트와 규칙을 결합한 것입니다. LLM에 데이터를 전달하려면 클라이언트가 두 가지를 한 번에 가져와야 합니다. get_context_from_mcp()라는 헬퍼 함수를 구현하세요. 이 함수는 리소스 텍스트와 프롬프트 텍스트(사용자 쿼리가 이미 포함된)를 반환하여, 호출자가 메시지를 구성할 수 있도록 합니다.

currency_server.py 파일에는 도구, 리소스, 프롬프트가 포함되어 있습니다. 동일한 세션을 사용해 리소스를 읽고, 사용자 입력이 담긴 프롬프트를 가져오세요.

이 연습은 강의의 일부입니다

Model Context Protocol (MCP) 입문

강의 보기

연습 안내

  • 세션 내에서 "file://currencies.txt"의 리소스를 읽는 메서드를 호출하세요.
  • 프롬프트 이름 "convert_currency_prompt"와 키 "currency_request", 값 user_query로 구성된 arguments 딕셔너리를 사용해, 사용자 입력이 포함된 프롬프트를 가져오는 메서드를 호출하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def get_context_from_mcp(user_query: str) -> tuple[str, str]:
    """Fetch resource content and prompt text from the MCP server."""
    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()

            # Read the resource (supported currencies)
            resource_result = await session.____("file://currencies.txt")
            resource_text = resource_result.contents[0].text

            # Get the prompt with the user's query
            prompt_result = await session.____("convert_currency_prompt",
                arguments={"currency_request": user_query})
            prompt_text = prompt_result.messages[0].content.text

            return resource_text, prompt_text

print(asyncio.run(get_context_from_mcp("How much is 50 GBP in euros?")))
코드 편집 및 실행