MCP · API REFERENCE

Tools / Resources / Prompts API

📋 JSON Schema 스펙 💻 Python 구현 🔧 타입 레퍼런스

세 가지 핵심 프리미티브의 전체 스펙과 Python 구현 레퍼런스. 각 프리미티브의 요청/응답 구조, 필드 타입, 제약 조건을 정확히 파악합니다.

🔧 Tools API

Tool은 AI가 실행을 요청할 수 있는 함수입니다. 사이드 이펙트(DB 쓰기, API 호출 등)를 허용하며, 반드시 JSON Schema로 입력을 정의합니다.

Tool 정의 스펙

필드타입필수설명
namestring필수Tool 식별자. 영숫자, 언더스코어, 하이픈만 허용
descriptionstring권장LLM이 Tool 선택에 사용하는 자연어 설명. 명확하게 작성할수록 정확도 향상
inputSchemaobject필수JSON Schema (Draft 7). 파라미터 타입, 설명, 제약 조건 정의
annotationsToolAnnotations선택readOnlyHint, destructiveHint, idempotentHint, openWorldHint

tools/call 요청 & 응답

jsontools/call 요청
{
  "jsonrpc": "2.0", "id": 42,
  "method": "tools/call",
  "params": {
    "name": "web_search",
    "arguments": { "query": "MCP protocol spec", "max_results": 3 }
  }
}
jsontools/call 응답 — CallToolResult
{
  "jsonrpc": "2.0", "id": 42,
  "result": {
    "content": [
      { "type": "text", "text": "검색 결과: ..." },
      { "type": "image", "data": "base64...", "mimeType": "image/png" }
    ],
    "isError": false  // true면 content가 에러 메시지
  }
}

Content 타입

type필드설명
texttext: string일반 텍스트 또는 마크다운
imagedata: base64, mimeTypePNG, JPEG 등 이미지
resourceresource: ResourceContentsembedded Resource 참조

📄 Resources API

Resource는 URI로 식별되는 읽기 전용 데이터입니다. 파일, DB 스키마, 설정, 로그 등 LLM에게 문맥 정보를 제공할 때 사용합니다.

Resource 정의 스펙

필드타입필수설명
uristring (URI)필수리소스 식별자. file://, config://, db:// 등 커스텀 스킴 가능
namestring필수사람이 읽는 이름
descriptionstring선택리소스 내용 설명
mimeTypestring권장MIME 타입 (예: text/plain, application/json)
sizeinteger선택바이트 크기 (힌트)

URI 템플릿 (동적 리소스)

python정적 vs 동적 Resource
# 정적 URI — 항상 같은 리소스
@mcp.resource("config://app/settings")
def app_settings() -> str:
    """앱 설정값 JSON."""
    return json.dumps(load_settings())

# 동적 URI 템플릿 — {user_id} 변수
@mcp.resource("users://{user_id}/profile")
def user_profile(user_id: str) -> str:
    """특정 사용자 프로필."""
    user = db.get_user(user_id)
    if not user:
        raise ValueError(f"사용자를 찾을 수 없음: {user_id}")
    return json.dumps(user.to_dict())

# resources/list 응답에 포함되는 메타데이터 명시적 지정
@mcp.resource(
    "logs://app/recent",
    name="최근 애플리케이션 로그",
    description="최근 100줄의 앱 로그",
    mime_type="text/plain"
)
def recent_logs() -> str:
    return tail_log("/var/log/app.log", n=100)

💬 Prompts API

Prompt는 재사용 가능한 메시지 템플릿입니다. 인수를 받아 완성된 메시지 시퀀스를 반환합니다. Tool과 달리 실행이 아닌 대화 시작점을 제공합니다.

Prompt 정의 스펙

필드타입필수설명
namestring필수Prompt 식별자
descriptionstring권장Prompt 목적 설명
argumentsPromptArgument[]선택각 인수의 name, description, required 정의
python다중 메시지 Prompt 예제
import mcp.types as types

@mcp.prompt()
def debug_assistant(
    error_message: str,
    code_snippet: str,
    language: str = "python"
) -> list[types.Message]:
    """디버깅 도우미 프롬프트. 에러 메시지와 코드를 받아 분석 요청을 만듭니다."""
    return [
        types.SystemMessage(
            "당신은 시니어 소프트웨어 엔지니어입니다. "
            "에러를 분석하고 구체적인 수정 방법을 알려주세요."
        ),
        types.UserMessage(
            f"다음 {language} 코드에서 에러가 발생했습니다.\n\n"
            f"**에러:**\n```\n{error_message}\n```\n\n"
            f"**코드:**\n```{language}\n{code_snippet}\n```\n\n"
            "원인과 수정 방법을 알려주세요."
        )
    ]
💡 Tool vs Resource vs Prompt 선택 기준
  • Tool: 실행이 필요한 작업 (검색, 계산, DB 쓰기)
  • Resource: 문맥 데이터 제공 (파일 내용, 설정, 스키마 정보)
  • Prompt: 반복적인 대화 패턴을 템플릿화 (리뷰 요청, 분석 시작)