MCP 서버에서 LLM 도구 사용하기
최신 환율을 이용해 통화를 변환하는 도구가 포함된 MCP 서버를 만들었습니다. 이 서버를 LLM과 연동하면 통화 및 환율에 관한 질문에 정확하게 답할 수 있게 됩니다. 기본 상태의 LLM만으로는 이러한 질문에 답하기 어렵습니다.
코드의 대부분은 이미 제공되어 있습니다. 여기서는 문법보다 전체 워크플로우를 이해하는 데 집중하세요.
이 연습은 강의의 일부입니다
Model Context Protocol (MCP) 입문
연습 안내
- 사용자 쿼리(
user_query)와 형식화된 도구 목록(anthropic_tools)을 Claude에 전송하세요. - LLM이 선택한 MCP 도구를 호출하되, 도구 사용 블록에서 추출한 이름과 인수를 사용하세요.
- 최종 응답을 위해 결과(
result)를 다시 Claude에 전송하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def call_anthropic_llm(user_query: str):
"""Call Claude with MCP tools."""
print(f"\nUser: {user_query}\n")
mcp_tools = await get_tools_from_mcp()
anthropic_tools = []
for tool in mcp_tools:
anthropic_tool = {
"name": tool.name,
"description": tool.description or "",
"input_schema": tool.inputSchema,
}
anthropic_tools.append(anthropic_tool)
# Send the user query and formatted tools to the LLM
client = AsyncAnthropic(api_key="")
response = await client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=____,
tools=____,
)
if response.stop_reason == "tool_use":
tool_use = next(block for block in response.content if block.type == "tool_use")
name = tool_use.name
args = tool_use.input
print(f"Model decided to call: {name}")
print(f"Arguments: {args}\n")
# Call the MCP tool
result = await call_mcp_tool(____, ____)
# Send the result back to Claude for the final response
followup = await client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[
{"role": "user", "content": user_query},
{"role": "assistant", "content": response.content},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_use.id,
"content": ____,
}
],
},
],
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)
else:
print("No follow-up message from model.")
else:
text = next((block.text for block in response.content if block.type == "text"), "")
print(f"\nAssistant: {text}")
return str(text)
if __name__ == "__main__":
asyncio.run(call_anthropic_llm("How much is 250 US dollars in euros?"))