MCP 서버 개발 과정 요약 및 단계별 예시 코드
MCP(Model Context Protocol) 서버는 AI 모델과 다양한 툴(도구), 리소스, 프롬프트 등을 연결해주는 표준화된 서버입니다. 아래는 MCP 서버 개발 과정을 단계별로 쉽게 설명하고, 각 단계마다 예시 코드를 제공합니다.
1. MCP 서버 구조 및 기본 개념
- MCP 서버는 리소스 제공, 도구 실행, 프롬프트 처리 등 세 가지 주요 역할을 담당합니다.
- 구성 요소: 클라이언트, API 게이트웨이, 마이크로서비스(도구), 데이터베이스, 메시지 브로커, 모니터링/로깅, 보안, 배포/오케스트레이션 등[2][3][4].
2. 개발 환경 준비
- Python:
fastmcp
또는mcp
패키지 활용 - Node.js/TypeScript:
mcp-framework
활용 - C#: 공식 SDK 활용
예시: Python 환경 준비
# 프로젝트 디렉토리 생성 및 진입
uv init my-mcp-server
cd my-mcp-server
# 가상환경 생성 및 활성화
uv venv
source .venv/bin/activate
# MCP 및 의존성 설치
uv add "mcp[cli]" httpx
# 메인 파일 생성
touch main.py
3. MCP 서버 코드 작성
A. Python (fastmcp 활용)
from fastmcp import FastMCP
mcp = FastMCP("Demo 🚀")
# 리소스 예시
@mcp.resource("config://app")
def get_config() -> str:
return "App configuration here"
# 동적 리소스 예시
@mcp.resource("users://{user_id}/profile")
def get_user_profile(user_id: str) -> str:
return f"Profile data for user {user_id}"
# MCP 서버 실행
if __name__ == "__main__":
mcp.run()
B. TypeScript (mcp-framework 활용)
import { MCPServer } from "mcp-framework";
const server = new MCPServer();
server.start().catch((error) => {
console.error("서버 오류:", error);
process.exit(1);
});
도구(툴) 추가 예시: 날씨 정보 도구
import { MCPTool } from "mcp-framework";
import { z } from "zod";
interface WeatherInput {
city: string;
}
class WeatherTool extends MCPTool {
name = "weather";
description = "도시의 날씨 정보를 가져오기";
schema = {
city: {
type: z.string(),
description: "도시 이름 (예: 서울)",
},
};
async execute({ city }: WeatherInput) {
// 실제 API 연동 가능
return {
city,
temperature: 22,
condition: "맑음",
humidity: 45,
};
}
}
export default WeatherTool;
C. C# (공식 SDK 활용)
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;
using System.ComponentModel;
var builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddConsole(consoleLogOptions =>
consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace);
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly();
await builder.Build().RunAsync();
툴(도구) 정의 예시
[McpServerToolType]
public static class EchoTool
{
[McpServerTool, Description("Echoes the message back to the client.")]
public static string Echo(string message) => $"Hello from C#: {message}";
[McpServerTool, Description("Echoes in reverse the message sent by the client.")]
public static string ReverseEcho(string message) => new string(message.Reverse().ToArray());
}
4. 서버 실행 및 테스트
- Python:
python main.py
- Node.js:
npm run build
후node dist/index.js
- C#:
dotnet run
테스트는 MCP Inspector, Postman, curl 등으로 도구와 리소스가 정상 동작하는지 확인합니다[6].
5. 실제 API 연동 및 고도화
- 예시 코드의 도구(툴) 부분에 실제 Open-Meteo 등 외부 API 호출을 추가하여 실시간 데이터 제공이 가능합니다.
- 보안, 로깅, 모니터링, 배포(도커, 쿠버네티스 등) 확장도 필수입니다[2][6].
정리
단계 | 주요 내용 | 예시 코드 |
---|---|---|
환경 준비 | MCP 프레임워크 설치, 프로젝트 생성 | Python/Node.js/C# 설치 및 초기화 |
서버 코드 작성 | 리소스/도구/프롬프트 구현 | @mcp.resource , MCPTool 클래스, [McpServerTool] |
도구 추가 | 실제 기능 구현 | 날씨 정보, 에코, 사용자 프로필 등 |
실행 및 테스트 | 서버 구동 및 동작 확인 | MCP Inspector, curl 등 |
확장 | 외부 API, 보안, 배포 등 | Open-Meteo 연동, 도커화 등 |
참고
- MCP 서버는 언어와 프레임워크에 따라 구현 방식이 다르지만, 리소스/도구/프롬프트라는 공통 개념을 중심으로 설계합니다.
- 예시 코드를 바탕으로 각자의 서비스에 맞게 도구와 리소스를 확장하면 됩니다[1][3][4][5][6].
[1] https://techblog.lycorp.co.jp/ko/introduction-to-mcp-and-building-mcp-server-using-line-messaging-api
[2] https://www.rapidinnovation.io/post/building-an-mcp-server-a-step-by-step-guide-for-developers
[3] https://dytis.tistory.com/113
[4] https://wikidocs.net/268823
[5] https://devblogs.microsoft.com/dotnet/build-a-model-context-protocol-mcp-server-in-csharp/
[6] https://apidog.com/kr/blog/build-an-mcp-server-kr/
[7] https://www.philschmid.de/mcp-introduction
[8] https://digitalbourgeois.tistory.com/973
[9] https://digitalbourgeois.tistory.com/961
[10] https://modulabs.co.kr/community/momos/8/feeds/653
[11] https://rudaks.tistory.com/entry/MCP-Server-%EA%B0%9C%EB%B0%9C-Python
[12] https://velog.io/@todd/%EA%B0%84%EB%8B%A8%ED%95%98%EA%B2%8C-%EB%A7%8C%EB%93%A4%EB%A9%B4%EC%84%9C-%EC%9D%B4%ED%95%B4%ED%95%B4%EB%B3%B4%EB%8A%94-MCP
[13] https://tiaz.dev/ai/3
[14] https://bcho.tistory.com/1471
[15] https://www.youtube.com/watch?v=zVSZ2gXvhVE
[16] https://3.wlog.co.kr/entry/mcp-server-%EB%A7%8C%EB%93%A4%EA%B8%B0-%EB%82%98%EB%A7%8C%EC%9D%98-%EC%84%9C%EB%B2%84-%EA%B5%AC%EC%B6%95-%EA%B0%80%EC%9D%B4%EB%93%9C
[17] https://rudaks.tistory.com/entry/mcp-%EC%84%9C%EB%B2%84-%EA%B0%9C%EB%B0%9C%EC%9E%90%EB%A5%BC-%EC%9C%84%ED%95%9C-%ED%80%B5%EC%8A%A4%ED%83%80%ED%8A%B8
[18] https://code.visualstudio.com/docs/copilot/chat/mcp-servers
'Code Story' 카테고리의 다른 글
GIT 명령어 (4) | 2025.06.13 |
---|---|
MCP(모델 컨텍스트 프로토콜) 공부 (3) | 2025.06.12 |
LangGraph 기반 지능형 에이전트 개발 및 서비스화 (0) | 2025.06.11 |
[꿀팁] 쉘스크립트 만들기 (0) | 2023.07.21 |
[Python] 정규식을 이용한 날짜 포맷 확인 (0) | 2022.05.30 |