MCP HubMCP Hub
스킬 목록으로 돌아가기

build-custom-mcp-server

pjt222
업데이트됨 Yesterday
5 조회
17
2
17
GitHub에서 보기
메타aitestingapimcpdesign

정보

이 스킬은 개발자들이 도메인 특화 도구를 AI 어시스턴트에 노출하기 위해 맞춤형 MCP 서버를 구축하는 방법을 안내합니다. Node.js 또는 R에서의 구현 방법을 다루며, 도구 정의, 전송 구성, Claude Code를 이용한 테스트를 포함합니다. 표준 도구를 넘어선 특수 통합이 필요하거나 기존 API를 MCP 서비스로 래핑해야 할 때 활용하세요.

빠른 설치

Claude Code

추천
기본
npx skills add pjt222/agent-almanac -a claude-code
플러그인 명령대체
/plugin add https://github.com/pjt222/agent-almanac
Git 클론대체
git clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/build-custom-mcp-server

Claude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요

문서

Build Custom MCP Server

Create custom MCP server exposing domain-specific tools to AI assistants.

When Use

  • Need to expose custom functionality to Claude Code or Claude Desktop
  • Building specialized tools beyond what mcptools provides
  • Creating domain-specific AI assistant integration
  • Wrapping existing APIs or services as MCP tools

Inputs

  • Required: List of tools to expose (name, description, parameters, behavior)
  • Required: Implementation language (Node.js or R)
  • Required: Transport type (stdio or HTTP)
  • Optional: Authentication requirements
  • Optional: Docker packaging needs

Steps

Step 1: Define Tool Specifications

Before writing code, define each tool:

tools:
  - name: query_database
    description: Execute a read-only SQL query against the analysis database
    parameters:
      query:
        type: string
        description: SQL SELECT query to execute
        required: true
      limit:
        type: integer
        description: Maximum rows to return
        default: 100
    returns: JSON array of result rows

  - name: run_analysis
    description: Execute a predefined statistical analysis by name
    parameters:
      analysis_name:
        type: string
        description: Name of the analysis to run
        enum: [descriptive, regression, survival]
      dataset:
        type: string
        description: Dataset identifier
        required: true

Got: YAML or markdown spec for each tool with name, description, parameters (types, defaults, required flags), return type documented before writing code.

If fail: Tool specifications unclear? Interview domain expert or review existing API documentation for parameter types and return formats.

Step 2: Implement in Node.js (Using MCP SDK)

// server.js
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-analysis-server",
  version: "1.0.0",
});

// Define tools
server.tool(
  "query_database",
  "Execute a read-only SQL query against the analysis database",
  {
    query: z.string().describe("SQL SELECT query"),
    limit: z.number().default(100).describe("Max rows to return"),
  },
  async ({ query, limit }) => {
    // Validate read-only
    if (!/^\s*SELECT/i.test(query)) {
      return {
        content: [{ type: "text", text: "Error: Only SELECT queries allowed" }],
        isError: true,
      };
    }

    const results = await executeQuery(query, limit);
    return {
      content: [{ type: "text", text: JSON.stringify(results, null, 2) }],
    };
  }
);

server.tool(
  "run_analysis",
  "Execute a predefined statistical analysis",
  {
    analysis_name: z.enum(["descriptive", "regression", "survival"]),
    dataset: z.string().describe("Dataset identifier"),
  },
  async ({ analysis_name, dataset }) => {
    const result = await runAnalysis(analysis_name, dataset);
    return {
      content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
    };
  }
);

// Start server with stdio transport
const transport = new StdioServerTransport();
await server.connect(transport);

Got: Working server.js imports MCP SDK, defines tools with Zod schemas, connects via stdio transport. Running node server.js starts server without errors.

If fail: Verify @modelcontextprotocol/sdk and zod installed (npm install). Check import paths match SDK version (SDK reorganized exports between versions).

Step 3: Implement in R (Using mcptools)

# server.R
library(mcptools)

# Register custom tools
mcp_tool(
  name = "query_database",
  description = "Execute a read-only SQL query",
  parameters = list(
    query = list(type = "string", description = "SQL SELECT query"),
    limit = list(type = "integer", description = "Max rows", default = 100)
  ),
  handler = function(query, limit = 100) {
    if (!grepl("^\\s*SELECT", query, ignore.case = TRUE)) {
      stop("Only SELECT queries allowed")
    }
    result <- DBI::dbGetQuery(con, paste(query, "LIMIT", limit))
    jsonlite::toJSON(result, auto_unbox = TRUE)
  }
)

# Start server
mcptools::mcp_server()

Got: Working server.R registers custom tools with mcp_tool(), starts server with mcp_server(). Running Rscript server.R starts MCP server.

If fail: Ensure mcptools installed from GitHub (remotes::install_github("posit-dev/mcptools")). Check handler function signatures match parameter definitions.

Step 4: Set Up Project Structure

my-mcp-server/
├── package.json          # Node.js dependencies
├── server.js             # Server implementation
├── tools/                # Tool implementations
│   ├── database.js
│   └── analysis.js
├── test/                 # Tests
│   └── tools.test.js
├── Dockerfile            # Container packaging
└── README.md             # Setup instructions

Got: Project directory created with server.js (or server.R), package.json, tools/ directory for modular tool implementations, test/ for tests.

If fail: Directory structure doesn't match implementation language? Adjust accordingly. R servers may use R/ instead of tools/ and tests/testthat/ instead of test/.

Step 5: Test the Server

Manual testing with stdio:

echo '{"jsonrpc":"2.0","method":"tools/list","id":1}' | node server.js

Register with Claude Code:

claude mcp add my-server stdio "node" "/path/to/server.js"

Verify tools appear:

Start Claude Code session, check custom tools listed and functional.

Got: tools/list JSON-RPC call returns all defined tools with correct names and schemas. claude mcp list shows server registered. Tools callable from Claude Code session.

If fail: tools/list returns empty array? Tools were not registered before server.connect(). Claude Code cannot find server? Verify command path in claude mcp add is absolute, binary is executable.

Step 6: Add Error Handling

server.tool("risky_operation", "...", schema, async (params) => {
  try {
    const result = await performOperation(params);
    return {
      content: [{ type: "text", text: JSON.stringify(result) }],
    };
  } catch (error) {
    return {
      content: [{ type: "text", text: `Error: ${error.message}` }],
      isError: true,
    };
  }
});

Got: Each tool handler wrapped in try/catch. Invalid inputs return isError: true with descriptive message instead of crashing server process.

If fail: Server still crashes on bad input? Check try/catch wraps entire handler body including async operations. Ensure promises awaited within try block.

Step 7: Package for Distribution

Create package.json with bin entry:

{
  "name": "my-mcp-server",
  "version": "1.0.0",
  "bin": {
    "my-mcp-server": "./server.js"
  },
  "dependencies": {
    "@modelcontextprotocol/sdk": "^1.0.0",
    "zod": "^3.22.0"
  }
}

Users install and configure:

npm install -g my-mcp-server
claude mcp add my-server stdio "my-mcp-server"

Got: package.json with bin entry pointing to server entry point. Users install globally with npm install -g, register with claude mcp add.

If fail: Bin entry doesn't work after global install? Ensure server.js has shebang line (#!/usr/bin/env node), is marked executable. Verify package name doesn't conflict with existing npm packages.

Checks

  • Server starts without errors
  • tools/list returns all defined tools with correct schemas
  • Each tool executes correctly with valid input
  • Tools return appropriate errors for invalid input
  • Server works with Claude Code via stdio transport
  • Tools discoverable and usable in Claude sessions

Pitfalls

  • Blocking operations: MCP servers should handle requests asynchronously. Long-running operations block other tool calls.
  • Missing error handling: Unhandled exceptions crash server. Always wrap tool handlers in try/catch.
  • Schema mismatches: Tool parameter schemas must exactly match what handler expects
  • stdio buffering: Using stdio transport? Ensure output flushed. Node.js buffers stdout by default.
  • Security: MCP servers have same access as process. Validate inputs carefully, especially for shell commands or database queries.

See Also

  • configure-mcp-server - connect built server to clients
  • troubleshoot-mcp-connection - debug connectivity issues
  • containerize-mcp-server - package server in Docker

GitHub 저장소

pjt222/agent-almanac
경로: i18n/caveman/skills/build-custom-mcp-server
0
agentsagentskillsai-assisted-developmentclaude-codeskillsteams

연관 스킬

content-collections

메타

이 스킬은 콘텐츠 콜렉션(Content Collections)을 위한 프로덕션 검증된 설정을 제공합니다. 콘텐츠 콜렉션은 Markdown/MDX 파일을 Zod 검증이 포함된 타입 안전한 데이터 콜렉션으로 변환해주는 TypeScript 최우선 도구입니다. 블로그, 문서 사이트 또는 콘텐츠 중심의 Vite + React 애플리케이션을 구축할 때 타입 안전성과 자동 콘텐츠 검증을 보장하기 위해 사용하세요. Vite 플러그인 구성과 MDX 컴파일부터 배포 최적화 및 스키마 검증에 이르기까지 모든 것을 다룹니다.

스킬 보기

polymarket

메타

이 스킬은 개발자들이 Polymarket 예측 시장 플랫폼을 활용한 애플리케이션을 구축할 수 있도록 지원하며, 거래 및 시장 데이터를 위한 API 통합 기능을 포함합니다. 또한 WebSocket을 통한 실시간 데이터 스트리밍을 제공하여 실시간 거래와 시장 활동을 모니터링할 수 있습니다. 이를 통해 거래 전략을 구현하거나 실시간 시장 업데이트를 처리하는 도구를 생성하는 데 활용할 수 있습니다.

스킬 보기

creating-opencode-plugins

메타

이 스킬은 개발자들이 명령어, 파일, LSP 작업 등 25개 이상의 이벤트 유형에 연결되는 OpenCode 플러그인을 만들 수 있도록 돕습니다. JavaScript/TypeScript 모듈을 위한 플러그인 구조, 이벤트 API 명세, 구현 패턴을 제공합니다. OpenCode AI 어시스턴트의 라이프사이클을 사용자 정의 이벤트 기반 로직으로 가로채거나, 모니터링하거나, 확장해야 할 때 사용하세요.

스킬 보기

sglang

메타

SGLang은 RadixAttention 프리픽스 캐싱을 활용하여 JSON, 정규식, 에이전트 워크플로우를 위한 고속 구조화 생성에 특화된 고성능 LLM 서빙 프레임워크입니다. 특히 반복되는 프리픽스가 있는 작업에서 상당히 빠른 추론 속도를 제공하여 복잡한 구조화 출력 및 다중 턴 대화에 이상적입니다. 제약 디코딩이 필요하거나 광범위한 프리픽스 공유가 있는 애플리케이션을 구축할 때는 vLLM과 같은 대안보다 SGLang을 선택하십시오.

스킬 보기