0Pricing
AI Engineering Academy · 강의

첫 MCP 서버 구축

Python MCP SDK를 사용해 리소스, 도구, 프롬프트를 제공하는 서버를 만들고 Claude Desktop에 연결해 전체 흐름이 작동하는 모습을 확인합니다.

첫 MCP 서버 구축은(는) CoddyKit의 무료 AI Engineering Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Engineering Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Engineering Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

MCP 서버 프로젝트 설정

Python으로 MCP 서버를 구축하려면 mcp SDK와 Python 환경이 필요합니다. Claude Desktop 또는 모든 MCP 클라이언트가 stdio를 통해 연결할 수 있는 서버를 만들게 됩니다. 먼저 패키지를 설치하고 서버 파일을 생성하십시오.

# Create a project directory
# mkdir my_mcp_server && cd my_mcp_server

# Create a virtual environment
# python -m venv venv && source venv/bin/activate

# Install the MCP SDK
# pip install mcp httpx

# Project structure:
# my_mcp_server/
#   server.py          <- Your MCP server
#   requirements.txt
#   README.md

서버 객체 생성

mcp 패키지에서 가져온 후 서버 이름으로 Server 인스턴스를 생성합니다. 이 이름은 클라이언트의 MCP 서버 목록에 표시되므로 설명적인 이름을 선택하십시오. 서버 객체는 모든 도구, 리소스, 프롬프트를 등록하는 진입점입니다.

# server.py
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp import types
import asyncio
import httpx

# Create the server — name is shown in Claude Desktop
app = Server('weather-server')

# --- Tool registrations go here ---

# Entry point
if __name__ == '__main__':
    asyncio.run(stdio_server(app))

@app.list_tools()로 도구 등록

@app.list_tools() 데코레이터는 클라이언트가 요청할 때 사용 가능한 도구 목록을 반환하는 처리기를 등록합니다. 각 도구는 이름, 설명, 매개변수를 설명하는 JSON Schema인 inputSchema로 정의됩니다. 클라이언트는 이 목록을 LLM에 전달하여 호출할 수 있는 도구를 알 수 있도록 합니다.

@app.list_tools()
async def list_tools() -> list[types.Tool]:
    return [
        types.Tool(
            name='get_weather',
            description='Get current weather for a city. Use when the user asks about weather in a specific location.',
            inputSchema={
                'type': 'object',
                'properties': {
                    'city': {
                        'type': 'string',
                        'description': 'City name, e.g. London or New York'
                    },
                    'units': {
                        'type': 'string',
                        'enum': ['metric', 'imperial'],
                        'description': 'Temperature units. Default is metric.'
                    }
                },
                'required': ['city']
            }
        ),
        types.Tool(
            name='list_cities',
            description='Return a list of major cities the user can query weather for.',
            inputSchema={'type': 'object', 'properties': {}, 'required': []}
        )
    ]

도구 실행 구현

@app.call_tool() 데코레이터는 도구 실행을 처리합니다. 클라이언트가 도구를 호출하면 이 처리기가 도구 이름과 인수를 받습니다. 적절한 로직을 실행한 후 결과 문자열을 포함하는 TextContent 객체 목록을 반환합니다.

@app.call_tool()
async def call_tool(name: str, arguments: dict) -> list[types.TextContent]:
    if name == 'list_cities':
        cities = ['London', 'New York', 'Tokyo', 'Paris', 'Sydney']
        return [types.TextContent(type='text', text=', '.join(cities))]

    if name == 'get_weather':
        city = arguments['city']
        units = arguments.get('units', 'metric')
        unit_symbol = 'C' if units == 'metric' else 'F'

        # Call real weather API (stub here)
        async with httpx.AsyncClient() as client:
            # Replace with actual API call
            result = f'{city}: 18{chr(176)}{unit_symbol}, partly cloudy, humidity 65%'

        return [types.TextContent(type='text', text=result)]

    raise ValueError(f'Unknown tool: {name}')

리소스 공개하기

리소스는 모델이 읽을 수 있는 정적 또는 동적 데이터이며, 파일과 비슷하다고 생각할 수 있습니다. 리소스 URI를 정의하고 리소스 판독기를 구현합니다. 리소스는 클라이언트에서 AI가 참조할 수 있는 항목으로 표시되며, 구성, 문서 또는 자주 사용하는 데이터 스냅샷에 유용합니다.

@app.list_resources()
async def list_resources() -> list[types.Resource]:
    return [
        types.Resource(
            uri='weather://supported-cities',
            name='Supported Cities List',
            description='Complete list of cities available in this weather server.',
            mimeType='text/plain'
        )
    ]

@app.read_resource()
async def read_resource(uri: str) -> str:
    if uri == 'weather://supported-cities':
        cities = ['London', 'New York', 'Tokyo', 'Paris', 'Sydney', 'Dubai', 'Singapore']
        return '\n'.join(cities)
    raise ValueError(f'Unknown resource URI: {uri}')

프롬프트 템플릿 등록하기

프롬프트는 클라이언트가 슬래시 명령이나 빠른 작업으로 사용자에게 제공하는 재사용 가능한 메시지 템플릿입니다. 매개변수를 받아 대화의 초기 컨텍스트가 되는 메시지 목록을 반환합니다. 프롬프트를 사용하면 사용자가 한 번의 명령으로 실행하는 복잡한 지침을 쉽게 정의할 수 있습니다.

@app.list_prompts()
async def list_prompts() -> list[types.Prompt]:
    return [
        types.Prompt(
            name='weather-report',
            description='Generate a formatted weather report for a city.',
            arguments=[
                types.PromptArgument(name='city', description='City name', required=True)
            ]
        )
    ]

@app.get_prompt()
async def get_prompt(name: str, arguments: dict) -> types.GetPromptResult:
    if name == 'weather-report':
        city = arguments.get('city', 'London')
        return types.GetPromptResult(
            description=f'Weather report for {city}',
            messages=[
                types.PromptMessage(
                    role='user',
                    content=types.TextContent(
                        type='text',
                        text=f'Use the get_weather tool to look up {city} and give me a detailed weather report including what clothing I should wear.'
                    )
                )
            ]
        )
    raise ValueError(f'Unknown prompt: {name}')

Claude Desktop에 연결하기

MCP 서버를 Claude Desktop에서 사용하려면 Claude Desktop 구성 파일에 서버를 추가해야 합니다. macOS에서는 ~/Library/Application Support/Claude/claude_desktop_config.json에 있습니다. 서버를 시작하는 명령과 서버에 필요한 환경 변수를 지정합니다.

# ~/Library/Application Support/Claude/claude_desktop_config.json
# Add this JSON configuration:

# {
#   "mcpServers": {
#     "weather-server": {
#       "command": "/path/to/venv/bin/python",
#       "args": ["/path/to/my_mcp_server/server.py"],
#       "env": {
#         "WEATHER_API_KEY": "your_api_key_here"
#       }
#     }
#   }
# }

# After saving, restart Claude Desktop.
# Your server's tools will appear in Claude's tool list.

MCP CLI로 서버 테스트하기

Claude Desktop에 연결하기 전에 MCP 검사기 또는 CLI 도구를 사용해 서버를 테스트합니다. mcp dev 명령은 서버를 시작하고 브라우저 기반 검사기를 열어 줍니다. 여기서 도구를 수동으로 호출하고 원시 프로토콜 메시지를 확인할 수 있으므로 문제를 쉽게 디버깅할 수 있습니다.

# Install the MCP development tools
# pip install 'mcp[cli]'

# Start the inspector with your server
# mcp dev server.py

# The inspector opens at http://localhost:5173
# You can:
# - See all registered tools and their schemas
# - Call tools with custom arguments
# - Browse available resources
# - Test prompt templates
# - View the full JSON-RPC message exchange

MCP 서버의 오류 처리

MCP 서버는 잘못된 입력 때문에 중단되어서는 안 됩니다. 모든 도구 실행을 try/except로 감싸고 예외를 발생시키는 대신 TextContent로 오류 메시지를 반환합니다. 치명적인 오류(구성 문제, API 키 누락)가 발생하면 시작 시 기록하고 서버가 주 실행 루프에 들어가기 전에 예외를 발생시킵니다.

@app.call_tool()
async def call_tool_safe(name: str, arguments: dict) -> list[types.TextContent]:
    try:
        if name == 'get_weather':
            city = arguments.get('city')
            if not city:
                return [types.TextContent(type='text', text='Error: city argument is required.')]
            result = await fetch_weather(city, arguments.get('units', 'metric'))
            return [types.TextContent(type='text', text=result)]
        raise ValueError(f'Unknown tool: {name}')
    except httpx.TimeoutException:
        return [types.TextContent(type='text', text='Error: Weather API timed out. Try again.')]
    except Exception as e:
        return [types.TextContent(type='text', text=f'Error: {str(e)}')]

MCP 서버의 로깅

MCP 서버는 클라이언트와 stdio를 통해 통신하므로 print 문을 사용하면 프로토콜이 손상됩니다. 로깅에는 항상 stderr를 사용합니다. stderr는 MCP 메시지 교환에 영향을 주지 않는 별도의 스트림으로 전달됩니다. Python의 로깅 모듈이 stderr에 쓰도록 구성합니다.

import logging
import sys

# Configure logging to stderr (NOT stdout — that's the MCP channel)
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(message)s',
    stream=sys.stderr
)
logger = logging.getLogger('weather-server')

# In your tool handler:
# logger.info(f'Getting weather for {city}')
# logger.error(f'API call failed: {e}')

# Claude Desktop captures stderr to a log file:
# ~/Library/Logs/Claude/mcp-server-weather-server.log

MCP 서버 패키징하기

pyproject.toml로 MCP 서버를 패키징해 PyPI에 게시하거나, 팀을 위해 Docker 컨테이너로 배포할 수 있습니다. 모든 비밀 정보(API 키, 데이터베이스 URL)는 환경 변수를 사용해 관리하여 서버 구성을 코드와 분리합니다. 필요한 환경 변수와 예시 구성을 명확한 README에 문서화합니다.

빠른 확인

Python으로 MCP 서버를 구축하는 방법을 얼마나 이해했는지 확인해 보세요.

<p>이 단원에서는 다음을 배웠습니다. <strong>MCP 서버는 @app.list_tools() 및 @app.call_tool() 데코레이터를 통해 도구를 공개합니다</strong>. <strong>리소스와 프롬프트를 사용하면 서버에 읽을 수 있는 데이터와 재사용 가능한 템플릿을 추가할 수 있습니다</strong>. 또한 <strong>stdio MCP 프로토콜 채널의 손상을 방지하려면 로깅에 stderr를 사용해야 합니다</strong>. 다음 단원에서는 MCP 서버를 데이터베이스에 연결하고 페이지 매김을 지원하는 동적 리소스를 공개합니다.</p>

이 레슨에서 다음을 배웠습니다. MCP 서버는 @app.list_tools() 및 @app.call_tool() 데코레이터를 통해 도구를 공개합니다. 또한 리소스와 프롬프트를 사용하면 읽을 수 있는 데이터와 재사용 가능한 템플릿으로 서버를 확장할 수 있습니다. 그리고 stdio MCP 프로토콜 채널이 손상되지 않도록 로깅에는 stderr를 사용해야 합니다. 다음으로 MCP 서버를 데이터베이스에 연결하고 페이지 매김을 지원하는 동적 리소스를 공개해 보겠습니다.

자주 묻는 질문

“첫 MCP 서버 구축” 강의는 무료인가요?

네 — “첫 MCP 서버 구축” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Engineering Academy 강의 전체를 잠금 해제할 수 있습니다. AI Engineering Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“첫 MCP 서버 구축”에서 뭘 배우나요?

Python MCP SDK를 사용해 리소스, 도구, 프롬프트를 제공하는 서버를 만들고 Claude Desktop에 연결해 전체 흐름이 작동하는 모습을 확인합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Engineering Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

AI Engineering Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 AI Engineering Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“첫 MCP 서버 구축” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 AI Engineering Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 AI Engineering Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. MCP란 무엇이며 왜 중요한가
  2. 첫 MCP 서버 구축
  3. MCP로 데이터베이스 리소스 제공
  4. MCP 보안과 인증
← AI Engineering Academy(으)로 돌아가기