20분 안에 첫 번째 MCP 서버 만들기 (TypeScript)

발행: (2026년 3월 8일 PM 02:28 GMT+9)
5 분 소요
원문: Dev.to

Source: Dev.to

번역을 진행하려면 번역하고자 하는 전체 텍스트(코드 블록과 URL을 제외한 본문)를 제공해 주시겠어요?
본문을 주시면 원본 형식과 마크다운을 유지하면서 한국어로 번역해 드리겠습니다.

개요

MCP (Model Context Protocol)는 AI 어시스턴트가 외부 도구를 직접 호출할 수 있게 합니다. 이 가이드는 텍스트에서 구조화된 데이터를 추출하는 간단한 MCP 서버를 TypeScript로 구축하는 방법을 보여줍니다.

사전 요구 사항

  • Node.js 18+
  • TypeScript
  • MCP 호환 클라이언트 (예: Claude Desktop, Cursor)

프로젝트 설정

mkdir my-mcp-server && cd my-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "Node16",
    "moduleResolution": "Node16",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "declaration": true
  },
  "include": ["src/**/*"]
}

참고: MCP SDK는 module: "Node16"moduleResolution: "Node16"을 필요로 합니다.

서버 구현 (src/index.ts)

#!/usr/bin/env node

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({
  name: "my-tool",
  version: "1.0.0",
});

// -------------------------------------------------------------------
// Tool definition
// -------------------------------------------------------------------
server.tool(
  "my_tool_name",
  "Description of what this tool does",
  {
    // Parameters defined with Zod
    input_text: z.string().describe("The text to process"),
    format: z.enum(["json", "csv"]).optional().describe("Output format"),
  },
  async ({ input_text, format }) => {
    // Your logic here
    const result = await processText(input_text, format);

    return {
      content: [
        {
          type: "text" as const,
          text: JSON.stringify(result, null, 2),
        },
      ],
    };
  }
);

// -------------------------------------------------------------------
// Server startup
// -------------------------------------------------------------------
async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
}

main().catch(console.error);

도구 정의 세부 사항

부분목적
이름AI가 도구를 호출할 때 사용하는 식별자
설명AI가 언제 사용할지 결정하도록 돕습니다
스키마파라미터를 설명하는 Zod 스키마
핸들러작업을 수행하는 비동기 함수

빌드 및 실행

npx tsc
node dist/index.js

서버는 이제 stdin에서 MCP 메시지를 수신합니다.

MCP Inspector로 테스트하기

npx @modelcontextprotocol/inspector node dist/index.js

Claude Desktop에 서버 등록하기

다음 항목을 ~/Library/Application Support/Claude/claude_desktop_config.json에 추가하십시오:

{
  "mcpServers": {
    "my-tool": {
      "command": "node",
      "args": ["/absolute/path/to/dist/index.js"]
    }
  }
}

Claude Desktop을 재시작하면 도구가 도구 메뉴에 나타납니다.

REST API를 MCP 도구로 래핑하기

server.tool(
  "extract_data",
  "Extract structured JSON from unstructured text",
  {
    text: z.string().describe("Text to extract from"),
    schema: z.enum(["receipt", "invoice", "email", "resume"]),
  },
  async ({ text, schema }) => {
    const response = await fetch("https://your-api.com/extract", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ text, schema }),
    });

    const result = await response.json();

    return {
      content: [
        {
          type: "text" as const,
          text: JSON.stringify(result.data, null, 2),
        },
      ],
    };
  }
);

모범 사례

  • 구체적으로 도구 설명을 작성하세요; AI는 이를 사용해 올바른 도구를 선택합니다.
  • 모든 매개변수에 zod .describe()를 사용하여 AI를 안내하세요.
  • 결과를 type: "text"로 반환하세요; AI는 일반 텍스트에서 JSON을 파싱할 수 있습니다.
  • 오류를 우아하게 처리하세요: 예외를 발생시키는 대신 오류 메시지를 텍스트로 반환합니다.

튜토리얼 건너뛰기 – 준비된 서버 사용

git clone https://github.com/avatrix1/structureai-mcp.git
cd structureai-mcp && npm install && npm run build

이 사전 구축된 서버는 영수증, 청구서, 이메일 등에서 구조화된 데이터를 추출합니다. 10개의 무료 요청을 포함하고 있으며 API 키가 필요 없습니다.

Avatrix LLC가 제작했습니다. 전체 소스:

0 조회
Back to Blog

관련 글

더 보기 »