시작하기무료로 시작하기

서버 도구 호출하기

이제 클라이언트에서 서버의 도구 호출을 실행해 볼 차례입니다! 이번에도 다른 작업을 기다리는 동안 오류나 중단이 발생하지 않도록 비동기 작업을 사용합니다.

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

Model Context Protocol (MCP) 입문

강의 보기

연습 안내

  • 사용자가 지정한 tool_namearguments 매개변수를 사용하여 도구를 호출하세요. 서버 응답을 기다리는 동안 호출이 일시 중지되도록 적절한 Python 키워드를 사용하세요.
  • 서버 응답의 텍스트 내용을 추출하여 출력하세요.
  • 유효한 매개변수를 사용하여 "convert_currency" 도구를 실행하세요(원하는 값과 통화 단위를 자유롭게 사용하세요).

실습형 인터랙티브 연습

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

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

async def call_mcp_tool(tool_name: str, arguments: dict) -> str:
    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()

            # Call the currency conversion tool
            result = ____ ____(tool_name, arguments)

            # Extract and print the text content of the server response
            text_content = result.____[0].____

            print(f"Conversion Result: {text_content}")
            return text_content

# Run the "convert_currency" tool
asyncio.run(
    call_mcp_tool("convert_currency",
                  {"amount": 250.0, "from_currency": "USD", "to_currency": "EUR"})
)
코드 편집 및 실행