- MCP Server Base Python
MCP Server Base Python
Content
MCP Server Base Python
Content
- [ MCP 서버 소개 ]
- [ 로컬 앱 실행하기 ]
- [ 도커 컨테이너 실행하기 ]
- [ 실행한 도커 컨테이너 종료하기 ]
- [ MCP 인스펙터 연결하기 ]
- [ FastAPI MCP 라우터 사용하기 ]
- [ 커스텀 도구 추가하기 ]
- [ 리소스 및 프롬프트 활용하기 ]
- [ catalog-info.yaml ]
MCP 서버 소개
MCP(Model Context Protocol) 서버는 LLM(Large Language Model)과 통신하기 위한 인터페이스를 제공합니다. 이 템플릿은 다음 기능을 포함합니다:
- 도구(Tools): LLM이 호출할 수 있는 함수 제공
- 리소스(Resources): LLM이 참조할 수 있는 데이터 제공
- 프롬프트(Prompts): 재사용 가능한 프롬프트 템플릿 제공
사전 준비
- Mac / Linux 환경
- docker 설치
- Python 3.10 이상
- npm (MCP Inspector 실행용)
스크립트를 통해 실행할 경우
bash scripts/run_server.sh
## localhost:8000/docs 접속하여 FastAPI 문서 확인
도커 컨테이너 실행하기
- 도커 컨테이너 실행 스크립트 실행
- Fast Api 애플리케이션 접속
bash scripts/run_docker.sh
실행한 도커 컨테이너 종료하기
bash scripts/stop_docker.sh
MCP 인스펙터 연결하기
MCP 서버가 실행된 후, MCP Inspector를 사용하여 서버와 통신할 수 있습니다:
# npm을 통해 MCP Inspector 실행
npx @modelcontextprotocol/inspector
브라우저에서 Inspector 접속 (기본 MCP Server URL: http://localhost:8000/sse)
FastAPI MCP 라우터 사용하기
FastAPI MCP는 APIRouter를 FastAPI 애플리케이션에 포함시켜 사용합니다. 현재 프로젝트는 다음과 같은 구조로 구현되어 있습니다:
- APIRouter를 사용한 Tool API 구현 (
src/items/tool_factory.py) - FastAPI 앱에 라우터 포함 (
src/main.py) - MCP 서버 팩토리를 통한 다양한 MCP 엔드포인트 생성 (
src/items/mcp_server_factory.py)
# 라우터 정의 예시 (src/items/tool_factory.py)
from fastapi import APIRouter
app = APIRouter(
responses={404: {"description": "Not found"}},
)
@app.get("/items/", tags=["items"], operation_id="list_items")
async def list_items():
# 구현...
pass
# MCP 서버 팩토리 예시 (src/items/mcp_server_factory.py)
def mcp_facotry(api_app: FastAPI):
# FastApiMCP 인스턴스 생성
include_operations_mcp = FastApiMCP(
api_app,
name="Item API MCP",
description="MCP server showing operations",
base_url="http://localhost:8000",
include_operations=["get_item", "list_items"],
)
# 경로에 MCP 서버 마운트
include_operations_mcp.mount(mount_path="/include-operations-mcp")
커스텀 도구 추가하기
새로운 API 도구를 추가하려면 다음 단계를 따르세요:
src/items/tool_factory.py파일에 새로운 엔드포인트 추가:
@app.get("/custom-path/", tags=["custom"], operation_id="custom_operation")
async def custom_operation():
"""도구에 대한 설명을 작성하세요."""
# 로직 구현
return {"result": "작업 결과"}
src/items/mcp_server_factory.py에서 필요한 경우 해당 오퍼레이션을 MCP에 포함/제외:
include_operations_mcp = FastApiMCP(
api_app,
name="Custom MCP",
description="Custom MCP server",
base_url="http://localhost:8000",
include_operations=["custom_operation"],
)
리소스 및 프롬프트 활용하기
- 리소스 추가:
src/factory/resources_factory.py - 프롬프트 추가:
src/factory/prompts_factory.py
프로젝트 구조
src/
├── main.py # FastAPI 및 MCP 서버 초기화
├── settings.py # 환경 설정 (Pydantic)
├── items/
│ ├── tool_factory.py # APIRouter 기반 API 도구 정의
│ └── mcp_server_factory.py # FastApiMCP 인스턴스 생성 및 마운트
└── factory/
├── tools_factory.py # 일반 MCP 도구 정의
├── resources_factory.py # MCP 리소스 정의
└── prompts_factory.py # MCP 프롬프트 정의
catalog-info.yaml
- 백스테이지 ( Backstage ) 에서 컴포넌트 등록을 위한 파일
- 자동으로 생성되므로 삭제하면 안됨.
MCP 서버를 외부 클라이언트에서 사용하기
MCP 서버는 다양한 AI 클라이언트와 연동할 수 있습니다. 아래는 대표적인 클라이언트와의 연동 방법입니다.
Cursor에서 MCP 서버 사용하기
Cursor는 MCP 프로토콜을 지원하는 코드 에디터입니다. Cursor에서 이 MCP 서버를 사용하려면:
- Cursor를 설치합니다.
- 프로젝트 폴더에
.cursor/mcp.json파일 또는 전역 설정 파일~/.cursor/mcp.json을 생성합니다. - 다음과 같이 구성합니다:
{
"mcpServers": {
"{mcp-server 이름을 입력하세요}": {
"url": "https://{argo-cd 혹은 백스테이지에서 확인하세요.}/{mcp_server_mount}",
"env": {
}
}
}
}
자세한 정보는 Cursor MCP 문서를 참조하세요.
Claude Desktop에서 MCP 서버 사용하기
Claude Desktop에서도 MCP 서버를 연동할 수 있습니다:
- Claude Desktop을 설치합니다.
- Claude 메뉴에서 "Settings..."를 선택합니다.
- "Developer" 탭에서 "Edit Config"를 클릭합니다.
- 구성 파일에 다음 내용을 추가합니다:
{
"mcpServers": {
"{mcp-server 이름을 입력하세요}": {
"command": "npx",
"args": ["mcp-remote", "https://{argo-cd 혹은 백스테이지에서 확인하세요.}/{mcp_server_mount}"]
}
}
}
자세한 정보는 Claude Desktop MCP 가이드를 참조하세요.
참고 자료
Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题;
Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
CursorThe AI Code Editor
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
ChatWiseThe second fastest AI chatbot™
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
Tavily Mcp
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
WindsurfThe new purpose-built IDE to harness magic
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
Amap Maps高德地图官方 MCP Server
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
Serper MCP ServerA Serper MCP Server
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
DeepChatYour AI Partner on Desktop
Playwright McpPlaywright MCP server