Agentic AI

강력한 AI 에이전트 구축하기: LangChain과 MCP를 활용한 단계별 튜토리얼

AgentAIHub 2025. 3. 26. 10:34
728x90

멀티 에이전트 시스템의 세계로 여러분을 초대합니다! 이 튜토리얼에서는 LangChain과 MCP(Multi-Chain Processing)를 활용하여 강력하면서도 사용자 정의가 가능한 AI 에이전트를 구축하는 방법을 단계별로 알아보겠습니다. 특히 MCP 서버를 통해 제공되는 다양한 도구를 활용하여 에이전트의 능력을 확장하고, Kestra 워크플로우 엔진으로 전체 프로세스를 자동화하는 방법에 중점을 두고 있습니다. 코드 예제와 함께 실용적인 지식을 쌓아보세요!

 

 

 

How to use MCP servers from a custom AI agent (step by step)

이 튜토리얼은 **Langchain**과 **MCP(Multi-Chain Processing)**를 사용하여 사용자 정의 AI 에이전트를 구축하는 방법을 단계별로 안내합니다. 핵심은 MCP 서버를 통해 제공되는 도구를 활용하여 에이전트의

lilys.ai

 

MCP와 LangChain을 활용한 AI 에이전트 구축 개요

최근 AI 개발의 핵심 트렌드 중 하나는 바로 멀티 에이전트 시스템입니다. 단일 모델만으로는 해결하기 어려운 복잡한 작업을 여러 특화된 에이전트들이 협업하여 수행하는 방식이죠. 이러한 트렌드 속에서 MCP(Multi-Chain Processing)는 AI 에이전트 개발에 혁신적인 접근법을 제공합니다.

MCP와 AI 에이전트의 관계

MCP는 여러 AI 에이전트와 도구들을 효과적으로 연결하고 관리하는 프레임워크입니다. 특히 오케스트레이터 에이전트가 작업을 계획하고, 진행 상황을 추적하며, 오류 발생 시 재계획하는 구조로 작동합니다5. 이러한 구조는 복잡한 작업을 효율적으로 처리할 수 있게 해줍니다.

 

왜 MCP와 LangChain을 함께 사용해야 할까?

LangChain은 언어 모델을 기반으로 한 애플리케이션 개발을 단순화해주는 도구입니다. MCP와 LangChain을 함께 사용하면 복잡한 워크플로우를 더 쉽게 구현할 수 있습니다1. 특히 LangChain과 MCP를 통합하면:

  • 에이전트 간 효율적인 통신 구조 구축 가능
  • 도메인 특화 지식과 도구의 쉬운 통합
  • 동적인 작업 할당 및 관리
  • 다단계 추론 및 문제 해결 능력 향상

이제 실제로 MCP 서버를 구축하고 AI 에이전트와 통합하는 과정을 살펴보겠습니다.

MCP 서버 구축하기: 기본부터 응용까지

MCP 서버의 핵심 구성요소

MCP 서버를 구축하기 위해서는 먼저 Python의 MCPSDK를 사용합니다. 이 서버는 에이전트들이 사용할 수 있는 다양한 도구(tools)를 제공하는 역할을 합니다. 우리 예제에서는 두 가지 특별한 도구를 구현할 것입니다:

  1. 'yell' 도구: 입력 문장을 대문자로 변환하고 느낌표 세 개(!!!)를 추가합니다.
  2. 'sarcasm' 도구: 입력 문장의 문자를 번갈아 대소문자로 변환하고 마지막에 눈 올리는 이모지(🙄)를 추가합니다.

MCP 서버 코드 예제

from mcpsdk import MCP, MCPServer, Tool, Request, Response

# 도구 기능 정의
def yell(text):
    return text.upper() + "!!!"

def sarcasm(text):
    result = ""
    for i, char in enumerate(text):
        if i % 2 == 0:
            result += char.upper()
        else:
            result += char.lower()
    return result + " 🙄"

# MCP 서버 설정
server = MCPServer(port=8000)

# 도구 등록
server.register_tool(Tool(name="yell", function=yell))
server.register_tool(Tool(name="sarcasm", function=sarcasm))

# 서버 시작
if __name__ == "__main__":
    server.start()
    print("MCP 서버가 시작되었습니다. 포트: 8000")
  

이 코드는 단순하지만 강력한 MCP 서버를 생성합니다. 포트 8000에서 실행되며, 'yell'과 'sarcasm'이라는 두 가지 도구를 등록합니다.

 

MCP 클라이언트 구축: 에이전트 통합의 핵심

MCP 서버와 통신하기 위해서는 클라이언트를 구축해야 합니다. 이 클라이언트는 LangChain과 함께 작동하여 AI 에이전트의 능력을 확장시킵니다.

클라이언트 구축 기본 원칙

클라이언트와 서버는 일대일 관계를 가져야 합니다. 클라이언트는 서버의 도구를 활용하고, 에이전트는 이러한 도구를 통해 확장된 기능을 수행합니다3.

MCP 클라이언트 코드 예제

 

 이 클라이언트는 두 명의 등장인물(Mary와 두 번째 사람) 간의 대화를 생성합니다. 두 번째 사람의 대사에는 'yell' 도구가, Mary의 대사에는 'sarcasm' 도구가 적용됩니다. 

import sys
from langchain.llms import OpenAI
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from mcpsdk import MCP, MCPClient

# 명령줄 인자로 두 번째 사람 이름 받기
if len(sys.argv) > 1:
    second_person = sys.argv[1]
else:
    second_person = "John"  # 기본값

# OpenAI 모델 초기화
llm = OpenAI(temperature=0.7)

# 프롬프트 템플릿 정의
prompt = PromptTemplate(
    input_variables=["name"],
    template="Mary와 {name} 사이의 대화를 5개의 교환으로 생성해주세요. {name}은 항상 소리를 지르고, Mary는 항상 비꼬는 말투를 사용합니다."
)

# LLM 체인 생성
chain = LLMChain(llm=llm, prompt=prompt)

# MCP 클라이언트 초기화
client = MCPClient(server_url="http://localhost:8000")

# 세션 시작
session = client.start_session()

# 대화 생성
result = chain.run(name=second_person)

# 대화 내용 처리 및 도구 적용
lines = result.strip().split('\n')
processed_dialogue = []

for line in lines:
    if f"{second_person}:" in line:
        # yell 도구 적용
        text = line.split(f"{second_person}:")[1].strip()
        processed_text = session.use_tool("yell", text)
        processed_dialogue.append(f"{second_person}: {processed_text}")
    elif "Mary:" in line:
        # sarcasm 도구 적용
        text = line.split("Mary:")[1].strip()
        processed_text = session.use_tool("sarcasm", text)
        processed_dialogue.append(f"Mary: {processed_text}")

# 결과 출력
print("\n".join(processed_dialogue))

MCP 서버와 AI 에이전트 간의 세션 흐름

MCP 서버와 AI 에이전트 간의 통신은 세션을 통해 이루어집니다. 이 세션은 다음과 같은 흐름으로 진행됩니다:

  1. 세션 초기화: 클라이언트가 서버에 연결하여 세션을 시작합니다.
  2. 능력 교환: 클라이언트는 자신의 능력을 서버에 알리고, 서버는 제공 가능한 도구 목록을 전달합니다.
  3. 도구 사용: 클라이언트는 필요에 따라 서버의 도구를 요청하고 사용합니다.
  4. 결과 처리: 도구 사용 결과를 받아 에이전트의 출력에 반영합니다.

이러한 세션 관리는 참고자료7에서 볼 수 있듯이, 효율적인 디버깅과 모니터링을 가능하게 합니다.

세션 관리의 중요성

효과적인 세션 관리는 에이전트의 성능과 안정성에 직접적인 영향을 미칩니다. 오류가 발생했을 때 세션을 초기화하거나, 이전 상태로 되돌리는 기능은 디버깅과 지속적인 개발에 필수적입니다7.

Kestra를 활용한 워크플로우 자동화

Kestra는 복잡한 워크플로우를 관리하고 자동화하기 위한 강력한 도구입니다. MCP 서버와 AI 에이전트를 통합한 워크플로우를 Kestra로 자동화하면 더욱 효율적인 시스템을 구축할 수 있습니다.

Kestra 워크플로우 구성 단계

  1. 이름 생성 단계: OpenAI API를 사용하여 임의의 이름을 생성합니다.
  2. Python 스크립트 실행 단계: 생성된 이름을 매개변수로 클라이언트 스크립트를 실행합니다.
  3. 결과 출력 단계: 생성된 대화를 출력하고 저장합니다.

Kestra 워크플로우 YAML 예제

 
id: mcp-agent-workflow
namespace: ai-agents
tasks:
  - id: generate-name
    type: io.kestra.plugin.openai.ChatCompletion
    apiKey: ${OPENAI_API_KEY}
    model: gpt-3.5-turbo
    messages:
      - role: user
        content: "남성 이름을 하나만 반환해주세요. 단어 하나만 작성하고 다른 설명이나 인용부호는 포함하지 마세요."
    outputs:
      - name: name
        value: "{{ outputs.result }}"

  - id: run-mcp-client
    type: io.kestra.plugin.scripts.python.Script
    runner: DOCKER
    dockerOptions:
      image: python:3.9
    commands:
      - pip install langchain openai mcpsdk
      - python client.py {{ outputs.generate-name.name }}
    files:
      server.py: |
        # MCP 서버 코드 내용
      client.py: |
        # MCP 클라이언트 코드 내용
      requirements.txt: |
        langchain==0.1.0
        openai==1.3.0
        mcpsdk==0.2.0
    env:
      OPENAI_API_KEY: ${OPENAI_API_KEY}
    outputs:
      - name: dialogue
        value: "{{ outputs.stdout }}"

  - id: print-dialogue
    type: io.kestra.core.tasks.debugs.Echo
    format: "생성된 대화:\n{{ outputs.run-mcp-client.dialogue }}"

 

이 YAML 파일은 Kestra에서 실행 가능한 워크플로우를 정의합니다. 이 워크플로우는 이름 생성부터 MCP 클라이언트 실행, 결과 출력까지의 모든 과정을 자동화합니다.

 

MCP 서버 활용 방법: 실전 팁과 확장 가능성

새로운 도구 추가하기

MCP 서버의 강점은 필요에 따라 새로운 도구를 추가할 수 있다는 점입니다. 예를 들어, 감정 분석, 언어 번역, 데이터 처리 등의 도구를 추가할 수 있습니다6.

 
# 새로운 감정 분석 도구 예제
def analyze_sentiment(text):
    # 감정 분석 로직 구현
    # 예시로 간단하게 구현
    positive_words = ["행복", "좋아", "훌륭", "멋져", "감사"]
    negative_words = ["슬픔", "화나", "실망", "나쁜", "싫어"]
    
    pos_count = sum(1 for word in positive_words if word in text)
    neg_count = sum(1 for word in negative_words if word in text)
    
    if pos_count > neg_count:
        return "긍정적 😊"
    elif neg_count > pos_count:
        return "부정적 😞"
    else:
        return "중립적 😐"

# MCP 서버에 도구 등록
server.register_tool(Tool(name="analyze_sentiment", function=analyze_sentiment))
 

다양한 시나리오에 MCP 적용하기

MCP와 AI 에이전트의 조합은 다양한 실제 시나리오에 활용될 수 있습니다:

  1. 문서 처리 파이프라인: 여러 문서를 처리하고 분석하는 자동화된 파이프라인 구축
  2. 고객 서비스 자동화: 고객 문의에 맞춤형 응답을 제공하는 에이전트 시스템
  3. 데이터 분석 및 보고서 생성: 데이터를 분석하고 인사이트를 추출하여 보고서를 자동으로 생성
  4. 교육용 상호작용 시스템: 학습자와 상호작용하며 개인화된 학습 경험 제공

에이전트 행동 모듈화

참고자료4에서 언급된 ROAM(Robust Autonomous Modulation) 개념을 활용하면, 에이전트의 행동을 더욱 효과적으로 모듈화할 수 있습니다. 이를 통해 에이전트가 다양한 상황에 적응하고 더 자연스러운 상호작용을 제공할 수 있습니다.

결론: MCP와 LangChain의 무한한 가능성

MCP와 LangChain을 결합한 AI 에이전트 구축은 단순한 자동화를 넘어 지능적이고 적응력 있는 시스템을 만들 수 있는 길을 열어줍니다. 이 튜토리얼을 통해 소개된 방법론은 단지 시작에 불과하며, 여러분의 창의력과 필요에 따라 무한히 확장될 수 있습니다.

특히 멀티 에이전트 시스템의 발전은 앞으로 AI 개발의 중요한 흐름이 될 것입니다5. MCP를 활용한 에이전트 개발은 이러한 트렌드에 발맞춰 나아가는 좋은 시작점이 될 것입니다.

지금까지 배운 내용을 바탕으로 여러분만의 혁신적인 AI 에이전트를 구축해보세요. 복잡한 문제를 해결하고, 사용자 경험을 개선하며, 새로운 가능성을 탐색하는 여정에 MCP가 든든한 동반자가 될 것입니다!

다음 단계 추천

  • 더 복잡한 도구 개발 및 통합하기
  • 여러 에이전트 간의 협업 패턴 구현하기
  • 실제 비즈니스 문제에 MCP 적용하기
  • 에이전트 성능 모니터링 및 최적화 시스템 구축하기

 #AI에이전트 #LangChain #MCP #멀티에이전트시스템 #워크플로우자동화 #Kestra #AIツール開発 #대화형AI #에이전트개발 #Python #OpenAI #MCPSDK #인공지능개발 #AIapplication

Building Powerful AI Agents: A Step-by-Step Tutorial Using LangChain and MCP

Welcome to the world of multi-agent systems! In this tutorial, we'll explore how to build powerful and customizable AI agents using LangChain and MCP (Multi-Chain Processing). We'll focus particularly on expanding agent capabilities through tools provided by the MCP server, and automating the entire process with the Kestra workflow engine. Let's build practical knowledge with code examples!

Overview of Building AI Agents with MCP and LangChain

One of the key trends in recent AI development is multi-agent systems. These systems enable complex tasks that are difficult to solve with a single model by having multiple specialized agents collaborate. Within this trend, MCP (Multi-Chain Processing) offers an innovative approach to AI agent development.

The Relationship Between MCP and AI Agents

MCP is a framework that effectively connects and manages multiple AI agents and tools. In particular, it operates with a structure where an orchestrator agent plans tasks, tracks progress, and re-plans when errors occur5. This structure enables efficient handling of complex tasks.

Why Use MCP and LangChain Together?

LangChain is a tool that simplifies the development of applications based on language models. Using MCP and LangChain together makes it easier to implement complex workflows1. Specifically, integrating LangChain and MCP allows:

  • Building efficient communication structures between agents
  • Easy integration of domain-specific knowledge and tools
  • Dynamic task assignment and management
  • Enhanced multi-step reasoning and problem-solving capabilities

Now, let's look at the process of building an MCP server and integrating it with AI agents.

Building an MCP Server: From Basics to Application

Core Components of an MCP Server

To build an MCP server, we first use Python's MCPSDK. This server provides various tools that agents can use. In our example, we'll implement two special tools:

  1. 'yell' tool: Converts input sentences to uppercase and adds three exclamation marks (!!!).
  2. 'sarcasm' tool: Alternates uppercase and lowercase characters in the input sentence and adds a rolling eyes emoji (🙄) at the end.

MCP Server Code Example

 
from mcpsdk import MCP, MCPServer, Tool, Request, Response

# Define tool functions
def yell(text):
    return text.upper() + "!!!"

def sarcasm(text):
    result = ""
    for i, char in enumerate(text):
        if i % 2 == 0:
            result += char.upper()
        else:
            result += char.lower()
    return result + " 🙄"

# Set up MCP server
server = MCPServer(port=8000)

# Register tools
server.register_tool(Tool(name="yell", function=yell))
server.register_tool(Tool(name="sarcasm", function=sarcasm))

# Start server
if __name__ == "__main__":
    server.start()
    print("MCP server started. Port: 8000")

 

This code creates a simple but powerful MCP server. It runs on port 8000 and registers two tools: 'yell' and 'sarcasm'.

Building an MCP Client: The Core of Agent Integration

To communicate with the MCP server, we need to build a client. This client works with LangChain to extend the capabilities of AI agents.

Basic Principles of Client Building

The client and server must have a one-to-one relationship. The client utilizes the server's tools, and the agent performs extended functions through these tools3.

MCP Client Code Example

 
import sys
from langchain.llms import OpenAI
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from mcpsdk import MCP, MCPClient

# Get second person's name from command line argument
if len(sys.argv) > 1:
    second_person = sys.argv[1]
else:
    second_person = "John"  # Default value

# Initialize OpenAI model
llm = OpenAI(temperature=0.7)

# Define prompt template
prompt = PromptTemplate(
    input_variables=["name"],
    template="Generate a conversation with 5 exchanges between Mary and {name}. {name} always shouts, and Mary always uses a sarcastic tone."
)

# Create LLM chain
chain = LLMChain(llm=llm, prompt=prompt)

# Initialize MCP client
client = MCPClient(server_url="http://localhost:8000")

# Start session
session = client.start_session()

# Generate conversation
result = chain.run(name=second_person)

# Process dialogue content and apply tools
lines = result.strip().split('\n')
processed_dialogue = []

for line in lines:
    if f"{second_person}:" in line:
        # Apply yell tool
        text = line.split(f"{second_person}:")[1].strip()
        processed_text = session.use_tool("yell", text)
        processed_dialogue.append(f"{second_person}: {processed_text}")
    elif "Mary:" in line:
        # Apply sarcasm tool
        text = line.split("Mary:")[1].strip()
        processed_text = session.use_tool("sarcasm", text)
        processed_dialogue.append(f"Mary: {processed_text}")

# Output results
print("\n".join(processed_dialogue))

This client generates a conversation between two characters (Mary and the second person). The 'yell' tool is applied to the second person's lines, and the 'sarcasm' tool is applied to Mary's lines.

Session Flow Between MCP Server and AI Agent

Communication between the MCP server and AI agents occurs through sessions. This session proceeds with the following flow:

  1. Session Initialization: The client connects to the server to start a session.
  2. Capability Exchange: The client informs the server of its capabilities, and the server provides a list of available tools.
  3. Tool Usage: The client requests and uses the server's tools as needed.
  4. Result Processing: The tool usage results are received and reflected in the agent's output.

Such session management, as seen in reference7, enables efficient debugging and monitoring.

The Importance of Session Management

Effective session management directly impacts the performance and stability of agents. The ability to initialize a session or revert to a previous state when errors occur is essential for debugging and continuous development7.

Workflow Automation with Kestra

Kestra is a powerful tool for managing and automating complex workflows. Automating workflows that integrate MCP servers and AI agents with Kestra can create more efficient systems.

Kestra Workflow Configuration Steps

  1. Name Generation Step: Generate a random name using the OpenAI API.
  2. Python Script Execution Step: Run the client script with the generated name as a parameter.
  3. Result Output Step: Output and save the generated conversation.

Kestra Workflow YAML Example

 
id: mcp-agent-workflow
namespace: ai-agents
tasks:
  - id: generate-name
    type: io.kestra.plugin.openai.ChatCompletion
    apiKey: ${OPENAI_API_KEY}
    model: gpt-3.5-turbo
    messages:
      - role: user
        content: "Return just one male name. Write only one word without any explanations or quotation marks."
    outputs:
      - name: name
        value: "{{ outputs.result }}"

  - id: run-mcp-client
    type: io.kestra.plugin.scripts.python.Script
    runner: DOCKER
    dockerOptions:
      image: python:3.9
    commands:
      - pip install langchain openai mcpsdk
      - python client.py {{ outputs.generate-name.name }}
    files:
      server.py: |
        # MCP server code content
      client.py: |
        # MCP client code content
      requirements.txt: |
        langchain==0.1.0
        openai==1.3.0
        mcpsdk==0.2.0
    env:
      OPENAI_API_KEY: ${OPENAI_API_KEY}
    outputs:
      - name: dialogue
        value: "{{ outputs.stdout }}"

  - id: print-dialogue
    type: io.kestra.core.tasks.debugs.Echo
    format: "Generated conversation:\n{{ outputs.run-mcp-client.dialogue }}"

 

This YAML file defines a workflow that can be executed in Kestra. This workflow automates the entire process from name generation to MCP client execution and result output.

How to Utilize MCP Server: Practical Tips and Scalability

Adding New Tools

The strength of MCP servers is that new tools can be added as needed. For example, tools for sentiment analysis, language translation, data processing, and more can be added6.

 
# New sentiment analysis tool example
def analyze_sentiment(text):
    # Implement sentiment analysis logic
    # Simple implementation for example
    positive_words = ["happy", "good", "excellent", "awesome", "thanks"]
    negative_words = ["sad", "angry", "disappointed", "bad", "hate"]
    
    pos_count = sum(1 for word in positive_words if word in text)
    neg_count = sum(1 for word in negative_words if word in text)
    
    if pos_count > neg_count:
        return "Positive 😊"
    elif neg_count > pos_count:
        return "Negative 😞"
    else:
        return "Neutral 😐"

# Register tool to MCP server
server.register_tool(Tool(name="analyze_sentiment", function=analyze_sentiment))
 
 
 

Applying MCP to Various Scenarios

The combination of MCP and AI agents can be used in various real-world scenarios:

  1. Document Processing Pipeline: Building automated pipelines for processing and analyzing multiple documents
  2. Customer Service Automation: Agent systems that provide customized responses to customer inquiries
  3. Data Analysis and Report Generation: Automatically analyzing data, extracting insights, and generating reports
  4. Interactive Educational Systems: Providing personalized learning experiences by interacting with learners

Agent Behavior Modulation

Using the ROAM (Robust Autonomous Modulation) concept mentioned in reference4, agent behavior can be modularized more effectively. This allows agents to adapt to various situations and provide more natural interactions.

Conclusion: Infinite Possibilities of MCP and LangChain

Building AI agents by combining MCP and LangChain opens the door to creating intelligent and adaptive systems beyond simple automation. The methodology introduced in this tutorial is just the beginning and can be infinitely expanded according to your creativity and needs.

In particular, the development of multi-agent systems will be an important trend in AI development going forward5. Agent development using MCP will be a good starting point to keep pace with this trend.

Build your own innovative AI agents based on what you've learned so far. MCP will be a reliable companion on your journey to solve complex problems, improve user experiences, and explore new possibilities!

Recommended Next Steps

  • Develop and integrate more complex tools
  • Implement collaboration patterns between multiple agents
  • Apply MCP to real business problems
  • Build systems for monitoring and optimizing agent performance

Hashtags: #AIagent #LangChain #MCP #MultiAgentSystem #WorkflowAutomation #Kestra #AIToolDevelopment #ConversationalAI #AgentDevelopment #Python #OpenAI #MCPSDK #AIDevelopment #AIapplication

Citations:

  1. https://arxiv.org/html/2411.15221v1
  2. https://arxiv.org/pdf/1806.10018.pdf
  3. https://arxiv.org/pdf/2501.00881.pdf
  4. https://arxiv.org/pdf/2311.01059.pdf
  5. https://arxiv.org/html/2411.04468v1
  6. https://arxiv.org/html/2502.05932v2
  7. https://arxiv.org/html/2503.02068v1
  8. https://arxiv.org/pdf/2401.15071.pdf
  9. https://arxiv.org/html/2503.07137v1
  10. https://arxiv.org/html/2410.02052v2
  11. http://arxiv.org/pdf/2407.09982.pdf
  12. https://arxiv.org/html/2409.13588v1
  13. https://arxiv.org/pdf/2401.10938.pdf
  14. https://arxiv.org/html/2501.00083
  15. https://openreview.net/pdf/77f78b692f36356e5e5bbddd012a3367bd821b29.pdf
  16. https://arxiv.org/pdf/2502.01562.pdf
  17. https://arxiv.org/pdf/2306.16021.pdf
  18. https://arxiv.org/html/2501.00881v1
  19. https://arxiv.org/html/2503.10029v1
  20. https://arxiv.org/html/2411.14033v1
  21. http://arxiv.org/list/cs/2024-12?skip=1800&show=2000
  22. https://arxiv.org/html/2404.11584v1

 #AI에이전트 #LangChain #MCP #멀티에이전트시스템 #워크플로우자동화 #Kestra  #에이전트개발 #Python #OpenAI #MCPSDK #인공지능개발 #AIapplication

728x90
반응형