spinny:~/writing $ less mcp-model-context-protocol-guide.md
12**Model Context Protocol (MCP)**은 Anthropic이 만든 오픈 표준으로, AI 모델이 외부 도구, 데이터 소스, 서비스와 어떻게 통신하는지를 정의합니다. 이것을 "AI의 USB-C"라고 생각하세요 - 표준화된 인터페이스를 통해 어떤 AI 에이전트든 어떤 도구와든 통신할 수 있게 해주는 범용 커넥터입니다.34출시 이후 MCP는 **월간 SDK 다운로드 9,700만 회**를 돌파했으며, 모든 주요 AI 제공업체가 채택했습니다: Anthropic, OpenAI, Google, Microsoft, Amazon. 이 가이드에서는 MCP로 구축하기 위해 알아야 할 모든 것을 살펴봅니다.56## MCP가 존재하는 이유78MCP 이전에는 모든 AI 애플리케이션이 사용하려는 각 도구에 대해 커스텀 통합을 구축해야 했습니다. AI가 파일을 읽게 하고 싶나요? 커스텀 코드를 작성하세요. 데이터베이스를 쿼리하나요? 더 많은 커스텀 코드. Slack에 게시하나요? 또 다른 통합.910이것은 **N×M 문제**를 만들었습니다: N개의 AI 애플리케이션이 각각 M개의 커스텀 통합을 필요로 하여 중복 노력과 파편화된 에코시스템으로 이어졌습니다.1112```mermaid13graph TD14 subgraph "Before MCP (N×M)"15 A1[AI App 1] --> T1[GitHub Integration]16 A1 --> T2[Slack Integration]17 A1 --> T3[DB Integration]18 A2[AI App 2] --> T4[GitHub Integration]19 A2 --> T5[Slack Integration]20 A2 --> T6[DB Integration]21 end22```2324MCP는 어떤 AI 클라이언트든 어떤 MCP 서버와든 통신할 수 있는 **단일 프로토콜**로 이를 해결합니다:2526```mermaid27graph TD28 subgraph "With MCP (N+M)"29 A1[AI App 1] --> MCP[MCP Protocol]30 A2[AI App 2] --> MCP31 MCP --> S1[GitHub Server]32 MCP --> S2[Slack Server]33 MCP --> S3[DB Server]34 end35```3637## 핵심 개념3839MCP에는 세 가지 기본 프리미티브가 있습니다:4041### 1. 도구 (Tools)42도구는 AI가 호출할 수 있는 함수입니다. "파일 생성", "데이터베이스 쿼리", "메시지 전송"과 같은 작업을 나타냅니다. 각 도구에는 이름, 설명, 매개변수에 대한 JSON Schema가 있습니다.4344```typescript45{46 name: "create_issue",47 description: "Create a new GitHub issue",48 inputSchema: {49 type: "object",50 properties: {51 title: { type: "string", description: "Issue title" },52 body: { type: "string", description: "Issue body" },53 repo: { type: "string", description: "Repository name" }54 },55 required: ["title", "repo"]56 }57}58```5960### 2. 리소스 (Resources)61리소스는 AI가 읽을 수 있는 데이터입니다. 파일, 데이터베이스 레코드, API 응답 또는 기타 데이터 소스를 나타냅니다. 리소스는 URI로 식별됩니다.6263```typescript64{65 uri: "file:///Users/dev/project/README.md",66 name: "Project README",67 mimeType: "text/markdown"68}69```7071### 3. 프롬프트 (Prompts)72프롬프트는 상호작용을 구조화하는 데 도움이 되는 재사용 가능한 템플릿입니다. 동적 매개변수를 포함할 수 있으며 일반적인 워크플로우를 표준화하는 데 유용합니다.7374```typescript75{76 name: "code_review",77 description: "Review code changes for quality and security",78 arguments: [79 { name: "diff", description: "The code diff to review", required: true }80 ]81}82```8384## 아키텍처8586MCP는 클라이언트-서버 아키텍처를 따릅니다:8788```mermaid89graph LR90 subgraph "Host Application"91 Client[MCP Client]92 end9394 subgraph "MCP Server"95 Server[Server Process]96 Server --> Tools[Tools]97 Server --> Resources[Resources]98 Server --> Prompts[Prompts]99 end100101 Client -- "JSON-RPC 2.0\n(stdio or SSE)" --> Server102```103104- **호스트**: AI 애플리케이션 (Claude Desktop, Cursor, 커스텀 앱)105- **클라이언트**: MCP 서버와 1:1 연결을 유지106- **서버**: 클라이언트에 도구, 리소스, 프롬프트를 노출107- **전송**: stdio(로컬) 또는 Server-Sent Events(원격)을 통한 JSON-RPC 2.0으로 통신108109## MCP 서버 구축110111JSON 파일에 저장된 할 일 목록과 상호작용하는 실용적인 MCP 서버를 구축해 봅시다.112113### 설정114115```bash116mkdir mcp-todo-server && cd mcp-todo-server117npm init -y118npm install @modelcontextprotocol/sdk zod119```120121### 서버 구현122123```typescript124// src/index.ts125import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";126import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";127import { z } from "zod";128import fs from "fs";129130const TODO_FILE = "./todos.json";131132function readTodos(): { id: number; text: string; done: boolean }[] {133 if (!fs.existsSync(TODO_FILE)) return [];134 return JSON.parse(fs.readFileSync(TODO_FILE, "utf-8"));135}136137function writeTodos(todos: { id: number; text: string; done: boolean }[]) {138 fs.writeFileSync(TODO_FILE, JSON.stringify(todos, null, 2));139}140141const server = new McpServer({142 name: "todo-server",143 version: "1.0.0",144});145146// Tool: Add a todo147server.tool(148 "add_todo",149 "Add a new todo item",150 { text: z.string().describe("The todo text") },151 async ({ text }) => {152 const todos = readTodos();153 const newTodo = { id: Date.now(), text, done: false };154 todos.push(newTodo);155 writeTodos(todos);156 return { content: [{ type: "text", text: `Added: "${text}"` }] };157 }158);159160// Tool: List todos161server.tool(162 "list_todos",163 "List all todo items",164 {},165 async () => {166 const todos = readTodos();167 const list = todos168 .map((t) => `${t.done ? "✅" : "⬜"} [${t.id}] ${t.text}`)169 .join("\n");170 return { content: [{ type: "text", text: list || "No todos yet." }] };171 }172);173174// Tool: Complete a todo175server.tool(176 "complete_todo",177 "Mark a todo as completed",178 { id: z.number().describe("The todo ID to complete") },179 async ({ id }) => {180 const todos = readTodos();181 const todo = todos.find((t) => t.id === id);182 if (!todo) return { content: [{ type: "text", text: "Todo not found." }] };183 todo.done = true;184 writeTodos(todos);185 return { content: [{ type: "text", text: `Completed: "${todo.text}"` }] };186 }187);188189// Resource: Current todos as a readable resource190server.resource(191 "todos://list",192 "Current todo list",193 async () => ({194 contents: [{195 uri: "todos://list",196 mimeType: "application/json",197 text: JSON.stringify(readTodos(), null, 2),198 }],199 })200);201202// Start the server203const transport = new StdioServerTransport();204await server.connect(transport);205```206207### 설정208209이 서버를 Claude Desktop에서 사용하려면 설정에 추가하세요:210211```json212{213 "mcpServers": {214 "todo": {215 "command": "npx",216 "args": ["tsx", "/path/to/mcp-todo-server/src/index.ts"]217 }218 }219}220```221222## MCP 클라이언트 구축223224어떤 MCP 서버에든 연결하는 커스텀 클라이언트도 구축할 수 있습니다:225226```typescript227import { Client } from "@modelcontextprotocol/sdk/client/index.js";228import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";229230const transport = new StdioClientTransport({231 command: "npx",232 args: ["tsx", "./src/index.ts"],233});234235const client = new Client({ name: "my-client", version: "1.0.0" });236await client.connect(transport);237238// List available tools239const { tools } = await client.listTools();240console.log("Available tools:", tools.map((t) => t.name));241242// Call a tool243const result = await client.callTool({244 name: "add_todo",245 arguments: { text: "Write MCP blog post" },246});247console.log(result);248```249250## 인기 MCP 서버251252MCP 에코시스템은 빠르게 성장했습니다. 가장 인기 있는 서버들을 소개합니다:253254| 서버 | 설명 | 사용 사례 |255|------|------|----------|256| **GitHub** | Issue, PR 생성, 저장소 관리 | 개발 워크플로우 |257| **Slack** | 메시지 전송, 채널 관리 | 팀 커뮤니케이션 |258| **PostgreSQL** | 데이터베이스 쿼리 및 관리 | 데이터 접근 |259| **Filesystem** | 파일 읽기, 쓰기, 검색 | 로컬 개발 |260| **Puppeteer** | 브라우저 자동화 및 스크래핑 | 웹 테스트 |261| **Sentry** | 오류 모니터링 및 디버깅 | 프로덕션 지원 |262| **Supabase** | 데이터베이스, 인증, 스토리지 | 백엔드 운영 |263264## MCP vs A2A (Agent-to-Agent)265266MCP가 **에이전트-도구** 통신을 처리하는 반면, Google의 **A2A (Agent-to-Agent)** 프로토콜은 **에이전트-에이전트** 통신을 처리합니다. 이 둘은 상호보완적입니다:267268```mermaid269graph TD270 Agent1[Agent 1] -- "A2A Protocol" --> Agent2[Agent 2]271 Agent1 -- "MCP Protocol" --> Tool1[GitHub MCP Server]272 Agent2 -- "MCP Protocol" --> Tool2[Database MCP Server]273```274275- **MCP**: AI 에이전트가 도구를 사용하는 방법 (수직 통합)276- **A2A**: AI 에이전트들이 서로 협업하는 방법 (수평 통합)277278## 모범 사례2792801. **서버를 집중적으로 유지하세요**: 도메인당 하나의 서버 (GitHub 서버, Slack 서버 등). 모놀리식 서버를 구축하지 마세요.2812. **Zod로 입력을 검증하세요**: 항상 적절한 스키마로 도구 입력을 검증하세요.2823. **오류를 우아하게 처리하세요**: 스택 트레이스가 아닌 의미 있는 오류 메시지를 반환하세요.2834. **읽기 전용 데이터에는 리소스를 사용하세요**: AI가 데이터만 읽으면 되는 경우, 도구가 아닌 리소스로 노출하세요.2845. **적절한 설명을 추가하세요**: 좋은 도구 및 매개변수 설명은 AI가 각 도구를 언제, 어떻게 사용할지 이해하는 데 도움이 됩니다.2856. **MCP Inspector로 테스트하세요**: `npx @modelcontextprotocol/inspector`를 사용하여 서버를 대화형으로 테스트하세요.286287## 시작하기288289```bash290# Create a new MCP server from template291npx @modelcontextprotocol/create-server my-server292293# Test with the MCP Inspector294npx @modelcontextprotocol/inspector npx tsx ./src/index.ts295```296297## 결론298299MCP는 2026년 AI 도구 사용의 사실상 표준이 되었습니다. 커스텀 AI 에이전트를 구축하든, Claude Code를 확장하든, 기존 플랫폼을 위한 통합을 만들든, MCP를 이해하는 것은 필수적입니다. 이 프로토콜은 하루 오후면 배울 수 있을 만큼 간단하지만 프로덕션 수준의 AI 워크플로우를 구축할 만큼 강력합니다.300301**다음 단계:**302- [MCP 사양](https://spec.modelcontextprotocol.io/)을 탐색하세요303- 영감을 위해 [기존 MCP 서버](https://github.com/modelcontextprotocol/servers)를 둘러보세요304- TypeScript 또는 Python SDK로 첫 번째 서버를 구축하세요305- Claude Desktop 또는 MCP Inspector로 테스트하세요306
:MCP (Model Context Protocol): 개발자를 위한 완벽 가이드lines 1-306 (END) — press q to close