이 프로젝트는 FastAPI와 FastMCP를 사용한 MCP(Model Context Protocol) 서버 템플릿입니다. Python + uv + FastMCP + FastAPI + Scalar UI를 결합하여 빠르고 효율적인 MCP 서버 개발을 지원합니다.
uv를 사용하여 Python 가상 환경을 생성하고 활성화합니다:
# uv 사용 (권장)
uv venv
source .venv/bin/activate # Linux/macOS
# 또는 .venv\Scripts\activate # Windows
# 또는 기존 venv 사용
python -m venv .venv
source .venv/bin/activate# uv 사용 시 (권장)
uv pip install -r requirements.txt
# 또는 pyproject.toml 사용
uv sync
# pip 사용 시
pip install -r requirements.txtenv.example 파일을 복사하여 .env 파일을 생성합니다:
cp env.example .env생성된 .env 파일을 열어 필요한 환경 변수를 설정하세요:
# Server Configuration
SERVER_NAME=my-awesome-mcp-server
SERVER_VERSION=1.0.0
SERVER_DESCRIPTION="My awesome MCP server"
# API Configuration
API_HOST=localhost
API_PORT=8001
# External API Configuration (실제 API에 맞게 수정)
EXTERNAL_API_KEY=your_actual_api_key
EXTERNAL_API_SECRET=your_actual_api_secret
EXTERNAL_API_BASE_URL=https://your-api.example.com# uvicorn으로 실행 (hot reload 포함)
uvicorn app.main:app --host 0.0.0.0 --port 8001 --reload
# 또는 Python으로 직접 실행
python -m app.mainuvicorn app.main:app --host 0.0.0.0 --port 8001서버가 실행되면 다음 URL들에 접근할 수 있습니다:
- Scalar UI:
http://localhost:8001/scalar(추천) - Swagger UI:
http://localhost:8001/docs - MCP SSE 엔드포인트:
http://localhost:8001/mcp/sse - Health Check:
http://localhost:8001/health
mcp-server-template/
├── app/ # 메인 애플리케이션 코드
│ ├── main.py # FastAPI 앱 및 MCP 서버 설정
│ ├── config.py # 환경 변수 및 설정 관리
│ └── services/ # 외부 서비스 연동 로직
│ └── example_api_client.py # 예시 API 클라이언트
├── static/ # 정적 파일
│ └── scalar.html # Scalar UI HTML
├── docs/ # 문서 (선택사항)
├── pyproject.toml # uv/Python 프로젝트 설정
├── requirements.txt # Python 의존성 목록
├── env.example # 환경 변수 예시
└── README.md # 프로젝트 문서
MCP 클라이언트 설정 파일에 다음과 같이 추가하세요:
{
"mcpServers": {
"My MCP Server": {
"command": "npx",
"args": [
"-y",
"mcp-remote@latest",
"http://localhost:8001/sse"
]
}
}
}이 템플릿에서 제공하는 기본 MCP 도구들:
- get_data_by_id: 데이터 ID로 특정 데이터 조회
- search_data_by_query: 키워드로 데이터 검색
- create_new_data: 새로운 데이터 생성
- update_existing_data: 기존 데이터 업데이트
- delete_data_by_id: 데이터 삭제
app/services/example_api_client.py 파일을 실제 사용할 외부 API에 맞게 수정하세요:
# 실제 API 엔드포인트 및 인증 방식에 맞게 수정
class YourAPIClient:
def __init__(self):
self.base_url = "https://your-api.example.com"
self.api_key = "your-api-key"
async def your_custom_method(self, param: str):
# 실제 API 호출 로직 구현
passapp/main.py에서 새로운 MCP 도구를 추가할 수 있습니다:
@mcp.tool(description="새로운 기능을 수행합니다.")
async def new_tool(param: str) -> str:
"""새로운 도구 설명"""
try:
# 실제 로직 구현
result = {"message": f"처리 완료: {param}"}
return json.dumps(result, indent=2, ensure_ascii=False)
except Exception as e:
return json.dumps({"error": str(e)}, indent=2, ensure_ascii=False)REST API 엔드포인트도 쉽게 추가할 수 있습니다:
@app.get("/new-endpoint", tags=["Custom"])
async def new_endpoint():
"""새로운 REST API 엔드포인트"""
return {"message": "Hello from new endpoint!"}# 테스트 실행 (pytest 설치 후)
pytest
# 커버리지와 함께 테스트
pytest --cov=app이 템플릿은 다음 개발 도구들을 지원합니다:
- Black: 코드 포매팅
- Ruff: 린팅 및 코드 품질 검사
- pytest: 테스트 프레임워크
# 코드 포매팅
black app/
# 린팅
ruff check app/
# 자동 수정
ruff check app/ --fixDocker를 사용하려면 다음 Dockerfile을 추가하세요:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8001
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8001"]이슈나 개선사항이 있으시면 언제든지 기여해 주세요!
MIT License