메시지 구성 및 LLM 호출
get_context_from_mcp(user_query) 헬퍼 함수를 만들어 리소스 텍스트와 프롬프트 텍스트를 반환할 수 있게 되었으니, 이제 해당 정보를 LLM에 전달할 차례입니다!
통화 서버, get_context_from_mcp(), get_tools_from_mcp(), call_mcp_tool(), 그리고 Claude 클라이언트는 백그라운드에서 이미 설정되어 있습니다. 프롬프트를 구성하고, 모델을 호출하며, 직접 메시지 또는 도구 호출을 처리하는 함수를 완성해 보세요. MCP 프롬프트가 실제로 차이를 만드는지 확인할 수 있도록 모호한 입력과 명확한 사용자 입력이 함께 제공됩니다!
이 연습은 강의의 일부입니다
Model Context Protocol (MCP) 입문
연습 안내
- 37번 줄에서
prompt_text, 문자열"\n\nSupported currencies:\n",resource_text를 순서대로 연결하여full_prompt를 구성하세요. - 47번 줄에서
full_prompt(사용자 메시지 내용)와anthropic_tools리스트를 모델에 전달하세요. - 52~55번 줄에서 응답의
stop_reason이"end_turn"이면str(text)를 반환하세요. - 58~60번 줄에서 응답의
stop_reason이"tool_use"이면 도구 사용 블록의.name과.input을call_mcp_tool()에 전달하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def get_context_from_mcp(user_query: str) -> tuple[str, 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()
resource_result = await session.read_resource("file://currencies.txt")
resource_text = resource_result.contents[0].text
prompt_result = await session.get_prompt("convert_currency_prompt",
arguments={"currency_request": user_query})
prompt_text = prompt_result.messages[0].content.text
return resource_text, prompt_text
async def get_tools_from_mcp():
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()
response = await session.list_tools()
return response.tools
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()
result = await session.call_tool(tool_name, arguments)
return str(result.content[0].text)
async def call_llm_with_context(user_query: str):
"""Call the LLM with resource and prompt context from MCP."""
resource_text, prompt_text = await get_context_from_mcp(user_query)
# Combine the resource and prompt text
full_prompt = ____ + "\n\nSupported currencies:\n" + ____
client = AsyncAnthropic(api_key="")
mcp_tools = await get_tools_from_mcp()
anthropic_tools = [{"name": t.name, "description": t.description or "", "input_schema": t.inputSchema} for t in mcp_tools]
# Send full_prompt (as a user message) and the tools list to the model
response = await client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": ____}],
tools=anthropic_tools,
)
# Return the text response
if response.stop_reason == "____":
text = next((block.text for block in response.content if block.type == "text"), "")
print(f"\nAssistant: {text}")
return str(____)
# Call the tool requested in the LLM's tool use
if response.stop_reason == "____":
tool_use = next(block for block in response.content if block.type == "tool_use")
result = await call_mcp_tool(____.name, ____)
followup = await client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[
{"role": "user", "content": full_prompt},
{"role": "assistant", "content": response.content},
{"role": "user", "content": [{"type": "tool_result", "tool_use_id": tool_use.id, "content": result}]},
],
tools=anthropic_tools,
)
final_text = next((block.text for block in followup.content if block.type == "text"), None)
if final_text:
print(f"\nAssistant: {final_text}")
return str(final_text)
print("=== Ambiguous request (prompt asks for clarification) ===")
asyncio.run(call_llm_with_context("Convert some euros to dollars"))
print("\n=== Unambiguous request (model calls tool) ===")
asyncio.run(call_llm_with_context("How much is 50 GBP in euros?"))