본문 바로가기

인공지능

LangChain + MCP 연동법: 복잡한 툴 연결, 이젠 예제로 쉽게 끝내자!

728x90
반응형

“이런 툴 연결, 어렵지 않게 할 수 없을까?”

LangChain과 LangGraph로 멋진 AI 에이전트를 만들고 싶지만, 외부 툴을 연동하려고 하면 어디서부터 시작해야 할지 막막하지 않으셨나요?

  • “툴 서버를 하나씩 직접 만들어야 한다고?”
  • “MCP는 또 뭐고, 그걸 어떻게 LangChain에 붙이란 거지?”
  • “왜 이렇게 설정이 많아... 그냥 포기할까?”

이런 복잡함을 해결해주는 게 바로 LangChain MCP Adapters입니다.
여러 개의 툴 서버(MCP 기반)를 LangChain이나 LangGraph 에이전트에 쉽게 연결하고, 간단한 코드만으로 에이전트를 실행할 수 있도록 도와주는 경량화된 래퍼 라이브러리죠.

이 블로그에서는 이 도구가 정확히 무엇인지, 어떻게 사용하는지, 실전 예제를 중심으로 쉽게 설명해 드립니다.
복잡한 설정은 걱정 마세요. 핵심만 콕 집어 알려드릴게요.

반응형

🧩 LangChain MCP Adapters란?

MCP란 무엇인가요?

MCP는 Model Context Protocol의 약자로, 다양한 도구(툴)를 AI 모델과 연결하기 위한 일종의 인터페이스 역할을 합니다.
서버 형태로 구현된 툴들을 MCP 포맷에 맞춰 제공하면, 이를 클라이언트에서 불러와 사용할 수 있습니다.

왜 MCP와 LangChain을 연결하나요?

LangChain은 다양한 도구를 AI 모델과 함께 사용할 수 있도록 도와주는 프레임워크입니다. 하지만 새로운 툴을 만들고 이를 연결하려면 꽤 번거로운 설정이 필요하죠.

MCP Adapters는 바로 이 부분을 자동화해 줍니다.

정리하면:

  • MCP: 툴을 정의하고 실행하는 서버 구조
  • LangChain MCP Adapter: MCP 툴을 LangChain/LangGraph에서 사용할 수 있도록 바꿔주는 도구

⚙️ 설치 방법

아래 명령어로 필요한 라이브러리를 설치할 수 있습니다:

pip install langchain-mcp-adapters langgraph langchain-openai

🔨 예제 1: 수학 툴 서버 만들기

먼저, 아주 간단한 수학 툴(MCP 서버)을 만들어봅니다.

# math_server.py
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Math")

@mcp.tool()
def add(a: int, b: int) -> int:
    return a + b

@mcp.tool()
def multiply(a: int, b: int) -> int:
    return a * b

if __name__ == "__main__":
    mcp.run(transport="stdio")

위 코드를 math_server.py로 저장한 후, 클라이언트 쪽에서 불러올 준비가 끝났습니다.


🤖 예제 2: LangChain 에이전트에서 툴 사용하기

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from langchain_mcp_adapters.tools import load_mcp_tools
from langgraph.prebuilt import create_react_agent
from langchain_openai import ChatOpenAI

model = ChatOpenAI(model="gpt-4o")

server_params = StdioServerParameters(
    command="python",
    args=["/path/to/math_server.py"],  # 경로 수정 필수
)

async with stdio_client(server_params) as (read, write):
    async with ClientSession(read, write) as session:
        await session.initialize()
        tools = await load_mcp_tools(session)
        agent = create_react_agent(model, tools)
        result = await agent.ainvoke({"messages": "what's (3 + 5) x 12?"})

결과: GPT 모델이 수학 툴을 사용해서 계산을 수행합니다!


🌐 여러 개의 MCP 서버를 동시에 연결하기

수학 외에도 날씨 정보를 제공하는 MCP 서버를 같이 사용하고 싶다면? 걱정 마세요, 가능합니다.

날씨 MCP 서버 예제

# weather_server.py
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Weather")

@mcp.tool()
async def get_weather(location: str) -> str:
    return "It's always sunny in New York"

if __name__ == "__main__":
    mcp.run(transport="sse")

클라이언트에서 둘 다 연결하기

from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent
from langchain_openai import ChatOpenAI

model = ChatOpenAI(model="gpt-4o")

async with MultiServerMCPClient(
    {
        "math": {
            "command": "python",
            "args": ["/path/to/math_server.py"],
            "transport": "stdio",
        },
        "weather": {
            "url": "http://localhost:8000/sse",
            "transport": "sse",
        }
    }
) as client:
    agent = create_react_agent(model, client.get_tools())
    math_res = await agent.ainvoke({"messages": "what's (3 + 5) x 12?"})
    weather_res = await agent.ainvoke({"messages": "what is the weather in nyc?"})

MCP 서버가 각각 다른 방식(stdio, sse)으로 동작해도 문제 없이 연동됩니다.


🧱 LangGraph API 서버와 함께 사용하기

LangGraph API 서버에서도 MCP 툴을 사용할 수 있습니다. 아래와 같은 구조로 설정합니다.

graph.py 파일 예제

from contextlib import asynccontextmanager
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent
from langchain_anthropic import ChatAnthropic

model = ChatAnthropic(model="claude-3-5-sonnet-latest")

@asynccontextmanager
async def make_graph():
    async with MultiServerMCPClient(
        {
            "math": {
                "command": "python",
                "args": ["/path/to/math_server.py"],
                "transport": "stdio",
            },
            "weather": {
                "url": "http://localhost:8000/sse",
                "transport": "sse",
            }
        }
    ) as client:
        agent = create_react_agent(model, client.get_tools())
        yield agent

langgraph.json 설정

{
  "dependencies": ["."],
  "graphs": {
    "agent": "./graph.py:make_graph"
  }
}

728x90

LangChain MCP Adapters는 AI 에이전트 개발에서 툴 연동의 복잡함을 크게 줄여주는 솔루션입니다.

  • ✅ 단 몇 줄의 코드로 외부 MCP 서버를 연결
  • ✅ LangChain, LangGraph 어디서든 작동 가능
  • ✅ 여러 서버를 동시에 연결해 복잡한 에이전트 구성 가능

https://github.com/langchain-ai/langchain-mcp-adapters?tab=readme-ov-file#langchain-mcp-adapters

 

GitHub - langchain-ai/langchain-mcp-adapters

Contribute to langchain-ai/langchain-mcp-adapters development by creating an account on GitHub.

github.com

728x90
반응형