FastAgent + FastMCP 개요
1. FastAgent
FastAgent는 자연어 처리(NLP) 기반의 AI 에이전트 개발 및 배포를 위한 프레임워크입니다. Model Context Protocol(MCP)을 기반으로 LLM 에이전트 및 워크플로우를 정의, 프롬프트, 테스트하는 기능을 제공합니다.
주요 특징
- 효율적인 에이전트 개발 및 배포
- 모듈식 설계로 컴포넌트 재사용 용이
- 다양한 LLM(대규모 언어 모델) 지원
- 장기 및 단기 메모리 시스템 내장
- 도구 통합 (API, 데이터베이스, 외부 서비스)
- 멀티모달 기능 지원
기술 스택
- Python 기반, FastAPI 활용
- 벡터 데이터베이스 통합
- 다양한 LLM 지원 (OpenAI, Anthropic, Hugging Face 등)
- Docker 컨테이너화 지원
2. FastMCP
FastMCP는 Model Context Protocol(MCP) 사양을 준수하는 서버와 클라이언트를 Python으로 빠르고 직관적으로 구축할 수 있도록 설계된 고수준 프레임워크입니다. 프로토콜의 복잡성을 추상화하여 개발자가 LLM에 노출할 가치 있는 기능 정의에 집중할 수 있도록 합니다.
장점
- 빠른 개발: 필요한 코드 양을 줄여 개발 프로세스 가속화
- 단순성: 서버 설정, 프로토콜 처리, 오류 관리 등 복잡한 세부 정보 추상화
- Pythonic: Python 모범 사례 준수, 타입 힌트 및 데코레이터 활용
- 완전성: 핵심 MCP 사양 포괄적 구현
모델 컨텍스트 프로토콜(MCP)
1. MCP 개념
MCP는 LLM 애플리케이션(클라이언트)과 외부 시스템(서버) 간의 상호 작용을 위한 표준화된 방법을 정의합니다. "AI를 위한 USB-C 포트"에 비유되며, LLM이 외부 기능에 신뢰할 수 있고 안전하게 액세스할 수 있는 생태계를 목표로 합니다.
2. MCP 주요 구성요소
- 도구(Tools)
- LLM이 서버에 실행을 요청할 수 있는 기능
- REST API의 POST 엔드포인트와 유사
- 데이터베이스 쿼리, API 호출 등 작업 수행
- 리소스(Resources)
- LLM이 읽거나 검색할 수 있는 데이터
- REST API의 GET 엔드포인트와 유사
- 구성 파일, 사용자 프로필, 실시간 데이터 등 제공
- 프롬프트(Prompts)
- LLM과의 상호작용을 구조화하는 재사용 가능한 템플릿
- 대화를 안내하고 특정 작업에 대한 일관된 출력 보장
- 컨텍스트(Context)
- 서버가 사용 가능한 도구 및 리소스와 상호 작용하는 방법에 대한 지침 제공
- 맥락 정보 제공
FastMCP 상세 설명
1. FastMCP 설치
# 일반 설치
pip install fastmcp
# 또는 uv 사용 시
uv pip install fastmcp
# 개발 환경 설정
uv sync
2. FastMCP 서버 구축
from fastmcp import FastMCP, ServerSettings
from pydantic import BaseModel
# FastMCP 서버 인스턴스 생성
mcp = FastMCP(
name="my-server",
description="My awesome MCP server",
settings=ServerSettings(debug=True)
)
# 입력 모델 정의
class CalculatorInput(BaseModel):
a: float
b: float
# 도구 정의
@mcp.tool(description="Add two numbers")
def add(input: CalculatorInput) -> float:
"""Add two numbers together."""
return input.a + input.b
@mcp.tool(description="Subtract second number from first")
def subtract(input: CalculatorInput) -> float:
"""Subtract b from a."""
return input.a - input.b
# 리소스 정의
@mcp.resource(description="Server configuration")
def get_config() -> dict:
"""Return server configuration."""
return {
"version": "1.0",
"max_calculations": 100,
"timeout_seconds": 30
}
# 프롬프트 정의
@mcp.prompt(description="Calculator prompt")
def calculator_prompt() -> str:
"""Return a prompt for using the calculator."""
return """
You are a helpful calculator assistant.
You can add and subtract numbers using the available tools.
"""
# 서버 시작 (stdio 전송 사용)
if __name__ == "__main__":
mcp.run()
3. FastMCP 서버 실행
# 직접 실행 (기본 stdio 전송 사용)
python my_server.py
# 또는 FastMCP CLI 사용
fastmcp run my_server.py:mcp
# HTTP 서버 방식으로 실행
fastmcp run my_server.py:mcp --transport sse --port 8080
# 디버그 모드로 실행
fastmcp run my_server.py:mcp --debug
4. FastMCP 클라이언트 구현
import asyncio
from fastmcp import Client
async def main():
# 서버에 연결
async with Client("stdio://python my_server.py") as client:
# 도구 호출
result = await client.call_tool(
"add",
{"a": 5, "b": 3}
)
print(f"Addition result: {result}") # 출력: Addition result: 8
# 리소스 읽기
config = await client.read_resource("get_config")
print(f"Server config: {config}")
# 프롬프트 가져오기
prompt = await client.get_prompt("calculator_prompt")
print(f"Calculator prompt: {prompt}")
if __name__ == "__main__":
asyncio.run(main())
5. FastMCP 서버 구성
# 직접 인스턴스 생성 시 구성
mcp = FastMCP(
name="configured-server",
settings=ServerSettings(
debug=True,
max_request_size_bytes=1024 * 1024, # 1MB
timeout_seconds=60
)
)
# 또는 환경 변수 사용 (예: .env 파일)
# FASTMCP_SERVER_DEBUG=true
# FASTMCP_SERVER_MAX_REQUEST_SIZE_BYTES=1048576
# FASTMCP_SERVER_TIMEOUT_SECONDS=60
6. 고급 FastMCP 기능
# 여러 서버 결합 (마운팅)
main_server = FastMCP(name="main")
calc_server = FastMCP(name="calculator")
# 계산기 서버를 메인 서버에 마운트
main_server.mount("/calculator", calc_server)
# 다른 서버 임포트
main_server.import_server(calc_server)
# FastMCP 프록시 생성
client = Client("stdio://python my_server.py")
proxy_server = FastMCP.from_client(client)
FastAgent 상세 설명
1. FastAgent 설치
uv pip install fast-agent-mcp
2. 에이전트 정의
# agent.py
import fast
# 간단한 에이전트 정의
@fast.agent(instruction="Given an object, respond only with an estimate of its size.")
def size_estimator():
pass
# 더 복잡한 에이전트
@fast.agent(
name="researcher",
instruction="You are a research assistant that helps find and analyze information.",
model="claude-3-5-sonnet"
)
def researcher():
pass
3. 에이전트 실행
# 기본 실행
uv run agent.py
# 특정 모델 지정 실행
uv run agent.py --model sonnet
# 특정 에이전트 실행
uv run agent.py --agent researcher
# 메시지 전송 후 종료
uv run agent.py --message "How big is an elephant?"
# 프롬프트 파일 적용
uv run agent.py --prompt-file my_prompt.txt
# 서버로 실행 (SSE)
uv run agent.py --server --transport sse --port 8080
# 서버로 실행 (stdio)
uv run agent.py --server --transport stdio
# 최소 출력
uv run agent.py --quiet
4. 에이전트 워크플로우
라우터 (Router)
Router는 LLM을 사용하여 메시지를 평가하고 가장 적절한 에이전트로 라우팅합니다. 에이전트 지침 및 사용 가능한 서버를 기반으로 라우팅 프롬프트가 자동 생성됩니다.
# router.py
import fast
# 에이전트 정의
@fast.agent(instruction="Answer questions about history.")
def historian():
pass
@fast.agent(instruction="Answer questions about science.")
def scientist():
pass
# 라우터 정의
@fast.router(agents=["historian", "scientist"])
def topic_router():
pass
# 메인 코드
if __name__ == "__main__":
fast.run()
오케스트레이터 (Orchestrator)
Orchestrator는 복잡한 작업을 위해 LLM을 사용하여 작업을 사용 가능한 에이전트 간에 분할하는 계획을 생성합니다.
# orchestrator.py
import fast
# 작업별 에이전트 정의
@fast.agent(instruction="Research information about a topic.")
def researcher():
pass
@fast.agent(instruction="Write a summary based on provided information.")
def writer():
pass
# 오케스트레이터 정의
@fast.orchestrator(agents=["researcher", "writer"])
def research_workflow():
pass
# 메인 코드
if __name__ == "__main__":
fast.run()
5. 에이전트 호출 방법
import fast
import asyncio
@fast.agent(name="greeter", instruction="Greet the user.")
def greeter():
pass
async def main():
# 점 표기법
response = await fast.agent.greeter("Hello")
# 사전 접근 방식
response = await fast.agent["greeter"].send("Hello")
# 명시적 send() 메소드
response = await fast.agent.greeter.send("Hello")
# 대화 세션 시작 (메시지 없음)
session = await fast.agent.greeter()
response = await session.send("Hello")
# 기본 프롬프트 설정
session = await fast.agent.greeter.prompt("Be very formal.")
response = await session.send("Hello")
asyncio.run(main())
6. 프롬프트 활용
import fast
from fast import Prompt
import asyncio
from pydantic import BaseModel
@fast.agent(instruction="Provide information about cities.")
def city_info():
pass
# 구조화된 응답을 위한 모델
class CityInfo(BaseModel):
name: str
population: int
country: str
landmarks: list[str]
async def main():
# 기본 텍스트 메시지
response = await fast.agent.city_info.send("Tell me about Paris")
# 파일 자동 변환 (이미지)
response = await fast.agent.city_info.send([
Prompt.user("What city is shown in this image?"),
Prompt.user("paris.jpg") # 자동으로 ImageContent로 변환
])
# 파일 자동 변환 (PDF)
response = await fast.agent.city_info.send([
Prompt.user("Summarize this travel guide"),
Prompt.user("paris_guide.pdf") # 자동으로 EmbeddedResource로 변환
])
# 구조화된 정보 요청
result, message = await fast.agent.city_info.structured(
[Prompt.user("Tell me about Paris")],
CityInfo
)
print(f"City name: {result.name}")
print(f"Population: {result.population}")
print(f"Country: {result.country}")
print(f"Landmarks: {', '.join(result.landmarks)}")
# 특정 리소스와 함께 프롬프트 전송
response = await fast.agent.city_info.with_resource(
"city_database",
"Tell me about the most populated cities"
)
asyncio.run(main())
7. 프롬프트 파일 활용
# my_prompt.txt
# 형식: <role>: <content>
system: You are a helpful assistant that answers questions about cities.
user: Tell me about Paris, France.
# Python 코드에서 로드
from fast.utils import load_prompt, load_prompt_multipart
# 단일 프롬프트 로드
prompt = load_prompt("my_prompt.txt")
# 여러 파일 결합
multipart_prompt = load_prompt_multipart([
"system_instructions.txt",
"user_query.txt"
])
8. 서버 구성 (MCP)
# fastagent.config.yaml
servers:
calculator:
path: "./calculator.py:mcp"
uri_alias: "calculator://"
sampling:
model: "claude-3-5-sonnet"
roots:
- "file:///data/calculator"
database:
path: "./database.py:mcp"
uri_alias: "db://"
sampling:
model: "claude-3-7-sonnet"
# fastagent.secrets.yaml (별도 관리)
servers:
database:
env:
DB_USERNAME: "admin"
DB_PASSWORD: "secure_password"
9. 내부 모델 (Playback)
FastAgent는 "playback" 모델을 사용하여 이전 대화 히스토리를 재현할 수 있습니다. 이는 에이전트 테스트 및 개발에 유용합니다.
# playback.txt
user: What's the capital of France?
assistant: The capital of France is Paris.
user: What about Italy?
assistant: The capital of Italy is Rome.
이 파일을 사용하여 대화를 재현할 수 있습니다.
uv run agent.py --model playback
10. Claude Desktop 통합
FastMCP 서버를 Claude Desktop에 설치하고 상호작용하는 방법
# FastMCP 서버 설치
fastmcp install server.py
# 개발 중 테스트
fastmcp dev server.py
Python 코드 실행
1. FastAgent를 통한 Python 코드 실행 메커니즘
FastAgent에서의 Python 코드 실행은 에이전트가 사용자 요청에 따라 코드를 생성하고 실행하는 기능입니다. 이 프로세스의 동작 방식은 다음과 같습니다.
기본 동작 원리
- 코드 생성 단계
- 사용자 요청을 분석하여 LLM이 적절한 Python 코드를 생성
- 코드는 요청된 작업에 맞게 최적화되며 실행 가능한 형태로 구성됨
- 샌드박스 실행 환경
- 격리된 컨테이너 또는 가상 환경에서 코드 실행
- 보안 제약 조건 적용 (파일 시스템 접근 제한, 네트워크 접근 제어 등)
- 리소스 사용량 제한 (CPU, 메모리, 실행 시간 등)
- 실행 결과 처리
- 표준 출력(stdout), 표준 오류(stderr) 캡처
- 반환 값 수집
- 실행 상태 및 메타데이터(실행 시간, 메모리 사용량 등) 기록
코드 실행 파이프라인
사용자 요청 → LLM 코드 생성 → 코드 검증 → 샌드박스 준비 →
코드 실행 → 결과 캡처 → 결과 해석 → 사용자에게 응답
핵심 구성 요소
- 코드 인터프리터 모듈
- Python 인터프리터 직접 호출
- 코드 실행 전/후 상태 관리
- 변수, 함수, 클래스 등의 컨텍스트 유지
- 가상 환경 관리자
- 각 실행마다 격리된 환경 생성 (Docker, venv 등 활용)
- 필요한 패키지 자동 설치
- 환경 정리 및 재사용
- 코드 분석기
- 실행 전 코드 검증 및 위험 평가
- 잠재적 보안 위험 식별
- 최적화 제안
- 파일 시스템 인터페이스
- 임시 파일 생성 및 관리
- 사용자 데이터 파일 접근 관리
- 실행 결과 저장
2. 원격 서버에서의 FastAgent 코드 실행
원격 서버에서 FastAgent를 통한 Python 코드 실행은 다양한 방식으로 구현할 수 있습니다. 반드시 SSH로 직접 접속할 필요는 없으며, 다음과 같은 접근법이 가능합니다.
API 기반 원격 실행 (SSH 불필요)
이 방식은 FastAgent를 API 서버로 배포하고 HTTP 요청을 통해 코드를 실행합니다.
클라이언트 애플리케이션 → HTTP 요청 → FastAgent API 서버 → Python 코드 실행 → 결과 반환
구현 예시
# 서버 측 코드 (FastAPI 사용)
from fastapi import FastAPI
from pydantic import BaseModel
from fast_agent.code_executor import CodeExecutor
app = FastAPI()
executor = CodeExecutor()
class CodeRequest(BaseModel):
code: str
parameters: dict = {}
@app.post("/execute")
async def execute_code(request: CodeRequest):
result = executor.run(request.code, request.parameters)
return {
"status": result.status,
"output": result.stdout,
"error": result.stderr,
"result": result.return_value
}
# 클라이언트 측 코드
import requests
response = requests.post("https://your-fastagent-server.com/execute", json={
"code": "import pandas as pd; print('Hello from remote server')",
"parameters": {"timeout": 30}
})
print(response.json())
웹 인터페이스 (SSH 불필요)
웹 기반 인터페이스를 통해 코드를 실행하고 결과를 확인하는 방식
- 주피터 노트북과 유사한 웹 인터페이스 제공
- 코드 편집, 실행, 결과 확인을 브라우저에서 처리
- FastAgent가 백엔드에서 코드 실행 담당
메시지 큐 기반 실행 (SSH 불필요)
분산 시스템에서 효율적인 코드 실행을 위한 방식
클라이언트 → 메시지 큐(RabbitMQ/Kafka) → FastAgent 워커 → Python 코드 실행 → 결과 저장 → 클라이언트에 알림
컨테이너 오케스트레이션 (SSH 불필요)
Kubernetes 또는 Docker Swarm을 활용한 확장 가능한 실행 환경
- 각 코드 실행 요청마다 새로운 컨테이너 생성
- 부하 분산 및 자동 확장 가능
- 보안 및 격리 강화
SSH 기반 실행 (SSH 필요)
특정 상황(보안 정책, 기존 인프라 등)에서는 SSH를 통한 실행도 가능합니다:
from fast_agent.remote import SSHExecutor
executor = SSHExecutor(
hostname="remote-server.com",
username="user",
key_file="/path/to/private_key"
)
result = executor.run("import numpy as np; print(np.random.rand(5))")
print(result.output)
3. 권장 아키텍처
대부분의 프로덕션 환경에서는 SSH 접속 없이 다음과 같은 아키텍처를 권장합니다.
- API 서버 모델:
- FastAgent 서버가 API 엔드포인트로 배포됨
- 클라이언트는 HTTP/WebSocket을 통해 요청
- 인증 및 권한 관리 포함
- 컨테이너화된 실행 환경:
- 각 코드 실행이 독립된 컨테이너에서 진행
- 보안 강화 및 리소스 관리 용이
- 상태 관리 시스템:
- 지속적인 세션 관리를 위한 상태 저장소
- Redis 또는 데이터베이스 활용
4. 보안 고려사항
원격 서버에서 코드를 실행할 때 고려해야 할 보안 사항
- 인증 및 권한: 강력한 인증 메커니즘 구현
- 네트워크 보안: HTTPS/TLS 사용, API 키 관리
- 리소스 제한: CPU, 메모리, 디스크 사용량 제한
- 코드 검증: 악성 코드 탐지 및 차단
- 데이터 보호: 민감한 정보 분리 및 암호화
실제 활용 사례
1. 데이터 분석 워크플로우
import fast
from fastmcp import FastMCP
from pydantic import BaseModel
import pandas as pd
import matplotlib.pyplot as plt
import io
import base64
# MCP 서버 설정
mcp = FastMCP(name="data-analysis")
# 데이터 분석 입력 모델
class AnalysisInput(BaseModel):
code: str
data_path: str = "data.csv"
# 데이터 시각화 입력 모델
class VisualizationInput(BaseModel):
code: str
data_path: str = "data.csv"
# 데이터 분석 도구
@mcp.tool(description="Analyze data with pandas")
def analyze_data(input: AnalysisInput) -> dict:
# 로컬 스코프 생성
local_scope = {"pd": pd, "data_path": input.data_path}
try:
# 코드 실행
exec(f"result = {input.code}", globals(), local_scope)
# 결과 반환
if "result" in local_scope:
result = local_scope["result"]
if isinstance(result, pd.DataFrame):
return {
"status": "success",
"type": "dataframe",
"data": result.to_dict(),
"shape": result.shape,
"columns": result.columns.tolist(),
"preview": result.head().to_string()
}
else:
return {
"status": "success",
"type": "other",
"result": str(result)
}
else:
return {
"status": "error",
"message": "No result returned"
}
except Exception as e:
return {
"status": "error",
"message": str(e)
}
# 데이터 시각화 도구
@mcp.tool(description="Visualize data with matplotlib")
def visualize_data(input: VisualizationInput) -> dict:
# 로컬 스코프 생성
local_scope = {"pd": pd, "plt": plt, "data_path": input.data_path}
try:
# 코드 실행
exec(input.code, globals(), local_scope)
# 이미지 캡처
buffer = io.BytesIO()
plt.savefig(buffer, format='png')
buffer.seek(0)
# Base64 인코딩
img_str = base64.b64encode(buffer.read()).decode('utf-8')
# 그래프 초기화
plt.close()
return {
"status": "success",
"type": "image",
"format": "png",
"data": img_str
}
except Exception as e:
return {
"status": "error",
"message": str(e)
}
# 분석가 에이전트
@fast.agent(
instruction="""
You are a data analysis assistant. You can analyze data using pandas and
visualize it using matplotlib. Always explain your analysis approach.
""",
servers=["data-analysis"]
)
def data_analyst():
pass
# 시각화 에이전트
@fast.agent(
instruction="""
You are a data visualization specialist. You can create beautiful and
informative visualizations using matplotlib. Always explain the insights
revealed by your visualizations.
""",
servers=["data-analysis"]
)
def data_visualizer():
pass
# 워크플로우 오케스트레이터
@fast.orchestrator(agents=["data_analyst", "data_visualizer"])
def analysis_workflow():
pass
# 메인 코드
if __name__ == "__main__":
# MCP 서버 등록
fast.register_server("data-analysis", mcp)
fast.run()
2. 멀티모달 대화형 코드 실행기
import fast
from fastmcp import FastMCP
from pydantic import BaseModel
import subprocess
import tempfile
import os
from pathlib import Path
import matplotlib.pyplot as plt
import io
import base64
import json
# MCP 서버 설정
mcp = FastMCP(name="interactive-executor")
# 상태 저장 (세션별)
sessions = {}
# 코드 실행 입력 모델
class CodeInput(BaseModel):
code: str
session_id: str
mode: str = "normal" # normal, step, reset
# 이미지 생성 입력 모델
class ImageGenInput(BaseModel):
code: str
session_id: str
width: int = 640
height: int = 480
# 세션 초기화
def init_session(session_id):
if session_id not in sessions:
sessions[session_id] = {
"variables": {},
"imports": set(),
"history": []
}
# 코드 실행 도구
@mcp.tool(description="Execute Python code interactively")
def execute_code(input: CodeInput) -> dict:
# 세션 초기화
init_session(input.session_id)
session = sessions[input.session_id]
# 세션 재설정
if input.mode == "reset":
session["variables"] = {}
session["imports"] = set()
session["history"] = []
return {
"status": "success",
"message": "Session reset successfully"
}
# 코드 기록 추가
session["history"].append(input.code)
# 코드 전처리 (가져온 모듈 추적)
import_lines = []
code_lines = []
for line in input.code.split("\n"):
if line.strip().startswith("import ") or line.strip().startswith("from "):
import_lines.append(line)
module = line.strip().split()[1].split(".")[0]
session["imports"].add(module)
else:
code_lines.append(line)
# 임시 파일 생성
with tempfile.NamedTemporaryFile(suffix='.py', delete=False) as temp:
temp_path = Path(temp.name)
# 모든 가져오기 먼저 추가
import_content = "\n".join(import_lines) + "\n"
# 세션 변수 저장 코드 추가
save_vars_code = """
import json
import numpy as np
import types
session_vars = {}
for var_name, var_value in list(locals().items()):
if not var_name.startswith('__') and var_name != 'session_vars':
try:
if isinstance(var_value, (int, float, str, bool, list, dict)) or var_value is None:
session_vars[var_name] = var_value
elif isinstance(var_value, np.ndarray):
session_vars[var_name] = var_value.tolist()
else:
# 기타 타입은 유형만 저장
type_name = type(var_value).__name__
session_vars[var_name] = f"<{type_name}>"
except:
pass
with open('/tmp/session_vars.json', 'w') as f:
json.dump(session_vars, f)
"""
# 완전한 코드 작성
temp.write(import_content.encode('utf-8'))
temp.write("\n".join(code_lines).encode('utf-8'))
temp.write("\n\n".encode('utf-8'))
temp.write(save_vars_code.encode('utf-8'))
try:
# 코드 실행
result = subprocess.run(
['python', temp_path],
capture_output=True,
text=True,
timeout=30
)
# 세션 변수 로드
try:
if os.path.exists('/tmp/session_vars.json'):
with open('/tmp/session_vars.json', 'r') as f:
session["variables"] = json.load(f)
except:
pass
return {
'status': 'success',
'stdout': result.stdout,
'stderr': result.stderr,
'returncode': result.returncode,
'session_vars': session["variables"],
'session_id': input.session_id
}
except Exception as e:
return {
'status': 'error',
'message': str(e),
'session_id': input.session_id
}
finally:
# 임시 파일 삭제
if os.path.exists(temp_path):
os.unlink(temp_path)
# 인터랙티브 파이썬 에이전트
@fast.agent(
instruction="""
You are an interactive Python coding assistant. You can execute code and maintain
state between executions. You can also generate visualizations using matplotlib.
Always explain your code and the results. For visualizations, use the generate_image tool.
""",
servers=["interactive-executor"]
)
def interactive_python():
pass
# 메인 코드
if __name__ == "__main__":
# MCP 서버 등록
fast.register_server("interactive-executor", mcp)
fast.run()
TypeScript FastMCP
TypeScript에서도 MCP 서버를 구축할 수 있으며, GitHub의 punkpeye/fastmcp 리포지토리에서 제공됩니다. 이 프레임워크는 stdio 또는 httpStream 전송을 지원하며, Zod, ArkType, Valibot과 같은 스키마 유효성 검사 라이브러리와 함께 사용할 수 있습니다.
// calculator.ts
import { FastMCP, Tool, z } from 'fastmcp';
// MCP 서버 생성
const mcp = new FastMCP({ name: 'calculator' });
// 입력 스키마 정의
const CalculatorInput = z.object({
a: z.number(),
b: z.number()
});
// 도구 정의
mcp.tool({
name: 'add',
description: 'Add two numbers',
input: CalculatorInput,
handler: async ({ a, b }) => {
return a + b;
}
});
mcp.tool({
name: 'subtract',
description: 'Subtract second number from first',
input: CalculatorInput,
handler: async ({ a, b }) => {
return a - b;
}
});
// 리소스 정의
mcp.resource({
name: 'config',
description: 'Server configuration',
handler: async () => {
return {
version: '1.0',
maxCalculations: 100,
timeoutSeconds: 30
};
}
});
// 서버 시작
mcp.start();
주요 GitHub 리포지토리
- jlowin/fastmcp: Python FastMCP 프레임워크의 주요 리포지토리 (현재는 Model Context Protocol Python SDK에 통합)
- evalstate/fast-agent: fast-agent 프레임워크의 주요 리포지토리. MCP 기반 에이전트 및 워크플로우를 정의하고 실행하는 데 사용됩니다.
- punkpeye/fastmcp: MCP 서버 구축을 위한 TypeScript FastMCP 프레임워크.
FastAgent와 FastMCP는 Model Context Protocol을 활용하여 LLM 애플리케이션 개발을 간소화하는 강력한 도구입니다. FastMCP는 Python으로 MCP 서버를 빠르고 직관적으로 구축할 수 있도록 하며, fast-agent는 이러한 서버를 활용하여 LLM 에이전트 및 복잡한 워크플로우를 정의하고 관리하는 프레임워크를 제공합니다. 이들 프레임워크는 데이터 분석, 코드 실행, 대화형 애플리케이션 등 다양한 영역에서 LLM이 외부 시스템, 데이터 및 도구와 효과적으로 상호 작용할 수 있는 새로운 가능성을 열어줍니다.
댓글