# MCP 서버 초기화
mcp = FastMCP(
"Weather_server",
instructions="날씨 정보를 제공하는 도우미",
host="0.0.0.0",
port=8005,
)
# 도구 구현
@mcp.tool()
async def get_forecast(latitude: float, longitude: float) -> str:
"""특정 위치의 날씨 예보 가져오기"""
# 외부 API 호출 로직...
return "포맷된 날씨 정보"
예시 (main.py):
# FastAPI 앱 초기화 및 MCP 서버 연결 관리
@asynccontextmanager
async def lifespan(app: FastAPI):
# MCP 서버 시작 및 연결
weather_py_path = os.path.join(os.path.dirname(__file__), "../mcp/weather.py")
server_params = StdioServerParameters(command=sys.executable, args=[weather_py_path])
# 연결 초기화 및 관리
async with stdio_client(server_params) as (read_stream, write_stream):
weather_mcp_session = ClientSession(read_stream, write_stream)
await weather_mcp_session.initialize()
yield
# 종료 시 연결 정리
# 채팅 API 엔드포인트
@app.post("/api/chat", response_model=ChatResponse)
async def api_chat(message: dict = Body(...)):
# 채팅 기록 관리
user_id = "default"
if user_id not in chat_histories:
chat_histories[user_id] = ChatHistory()
# 사용자 메시지 처리
user_message = message.get("message", "")
# 봇 응답 생성 (MCP 도구 호출 포함)
bot_response = generate_bot_response(user_message, chat_histories[user_id].messages)
# 응답 반환
return ChatResponse(response=bot_response)
예시 (ChatContainer.tsx, useChat.ts):
// 채팅 컨테이너 (ChatContainer.tsx)
const ChatContainer: React.FC = () => {
const { messages, isLoading, sendMessage } = useChat([
{ id: 1, text: '안녕하세요!', isUser: false, timestamp: new Date() },
]);
return (
<div className={styles.chatContainer}>
<div className={styles.messagesContainer}>
{messages.map((message) => (
<ChatMessage key={message.id} message={message} />
))}
</div>
<ChatInput onSend={sendMessage} isLoading={isLoading} />
</div>
);
};
// 채팅 로직 (useChat.ts)
const sendMessage = useCallback(async (text: string) => {
// 사용자 메시지 UI에 추가
const userMessage = { id: Date.now(), text, isUser: true };
setMessages(prev => [...prev, userMessage]);
try {
// 백엔드 API 호출
const response = await apiSendMessage(text);
// 봇 응답 UI에 추가
const botMessage = {
id: Date.now() + 1,
text: response.response,
isUser: false
};
setMessages(prev => [...prev, botMessage]);
} catch (error) {
// 오류 처리
}
}, []);
[MCP 서버] <== stdio ==> [백엔드]
[백엔드] <== HTTP/WebSocket ==> [프론트엔드]
이 아키텍처는 특히 여러 도구와 데이터 소스를 필요로 하는 복잡한 애플리케이션에서 강점을 발휘하며, 중앙 집중식 관리와 확장 가능한 구조를 제공한다.