Skip to main content
Glama
huafua

mcp-simulator

by huafua

MCP Simulator (Node.js MCP Server)

mcp simulator는 Node.js 기반으로 구축된 경량 **MCP 서버(Model Context Protocol Server)**입니다. 이 프로젝트는 제로 외부 의존성 설계(네이티브 http 모듈만 사용)를 채택하며, 모듈화된 McpServer와 McpRegistry를 통해 동적 도구 등록 및 HTTP 원격 호출(RPC) 기능을 제공합니다.


🚀 핵심 기능

  • 제로 외부 의존성: Node.js 네이티브 http 모듈에만 완전히 의존하며 express 등의 프레임워크가 필요 없습니다.

  • 새로운 MCP 핵심 아키텍처:

    • McpRegistry: 도구 목록과 실행 로직을 유지 관리합니다(동기 및 비동기 async 메서드 지원).

    • McpServer: HTTP POST 기반 실행 진입점과 통일된 JSON 응답 캡슐화를 제공합니다.

  • 간결한 API 등록 설계: 체인 호출을 지원하는 register() 인터페이스를 제공하며, '도구 정의'와 '실행 콜백' 두 매개변수만 제공하면 쉽게 등록할 수 있습니다.

  • 내장 도구 및 리플렉션 메커니즘:

    • 내장 tool/list로 등록된 모든 도구를 동적으로 조회합니다.

    • 동기 계산, 텍스트 처리, 비동기(async) 모의 API 요청(fetch-posts) 등 완전한 데모를 제공합니다.


Related MCP server: Swagger/Postman MCP Server

📁 파일 구조

mcp-simulator/
├── mcp.core.js             # 伺服器核心引擎(定義 McpServer 與 McpRegistry 類別)
├── index.js                # 專案主入口(載入核心引擎並註冊具體工具)
├── index.http              # HTTP API 測試腳本(搭配 VS Code REST Client 使用)
├── package.json            # 專案配置文件
└── README.md               # 本專案說明文件

⚙️ 빠른 시작

서버 시작

프로젝트 루트 디렉터리에서 다음 명령을 실행하세요:

node index.js

서버는 기본적으로 8889 포트를 수신합니다(또는 환경 변수 PORT를 읽습니다). 시작 후 콘솔에 다음이 표시됩니다:

Server running at 8889

🔌 API 프로토콜 규격

모든 API 호출은 단일 진입점을 통해 이루어집니다.

  • 요청 메서드: POST

  • 서버 주소: http://localhost:8889

  • 요청 헤더(Header): Content-Type: application/json

  • 요청 본문 형식(Payload):

    {
        "name": "要調用的工具名稱",
        "args": {
            "參數鍵": "參數值"
        }
    }

통일 응답 구조(Response)

모든 요청이 성공적으로 처리되면 서버는 통일된 캡슐화 JSON 구조를 반환합니다:

{
    "code": 200,
    "message": "success",
    "data": {
        /* 工具回傳的原始結果 */
    }
}

서버 오류 상태 목록

HTTP 상태 코드

상황 설명

응답 내용(JSON)

200

Header 오류(application/json 미지정)

{"code": 406, "message": "Content-type must be 'application/json'"}

200

JSON 형식 오류(파싱 불가)

{"code": 500, "message": "Request body is not valid format"}

200

도구 이름 미제공(name 필드 누락)

{"code": 406, "message": "Name must be provided"}

200

등록되지 않은 도구 호출

{"code": 200, "message": "success", "data": null}


🛠️ 내장 메서드 호출 예시

다음은 localhost:8889를 기준으로 한 실제 호출 데이터입니다:

1. 사용 가능한 도구 목록 가져오기 (tool/list)

서버에 등록된 모든 도구 정의를 나열합니다.

  • 요청 Payload: {"name": "tool/list", "args": {}}

  • 응답 예시:

    {
        "code": 200,
        "message": "success",
        "data": [
            { "name": "info", "description": "..." },
            {
                "name": "hello",
                "description": "just say hello to someone",
                "args": { "username": "string" }
            },
            {
                "name": "calculate",
                "description": "calculate sum of two numbers",
                "args": { "a": "number", "b": "number" }
            },
            {
                "name": "fetch-posts",
                "description": "fetch posts from https://jsonplaceholder.typicode.com/posts"
            }
        ]
    }

2. 두 수의 합 계산 (calculate)

  • 요청 Payload: {"name": "calculate", "args": {"a": 20, "b": 30}}

  • 응답 예시:

    {
        "code": 200,
        "message": "success",
        "data": { "result": 50 }
    }

3. 비동기 요청 테스트 (fetch-posts)

async 콜백 함수의 사용법을 보여주며, 사용자 가짜 데이터(배열)를 반환합니다.

  • 요청 Payload: {"name": "fetch-posts"}

  • 응답 예시:

    {
        "code": 200,
        "message": "success",
        "data": [
            {
                "id": 1,
                "name": "Leanne Graham",
                "username": "Bret",
                "email": "Sincere@april.biz"
                // ... (其他資料略)
            }
        ]
    }

📝 사용자 정의 도구 개발 및 확장

index.js를 수정하고 체인 호출 .register()를 통해 도구를 추가할 수 있습니다.

API 시그니처

server.register(toolDefinition, callback);
  • toolDefinition(Object): name을 반드시 포함해야 하며, 선택적으로 description과 args(매개변수 정의)를 제공할 수 있습니다.

  • callback(Function / Async Function): 요청을 수신할 때 실행되는 콜백입니다. req.params.args에서 전달된 단일 객체 매개변수를 받습니다.

등록 예시

const { McpServer } = require("./mcp.core");

new McpServer(8889)
    // 註冊一個需要參數的非同步工具
    .register(
        {
            name: "get_user",
            description: "獲取特定使用者資料",
            args: { userId: "number" },
        },
        async ({ userId }) => {
            // ⚠️ 必須使用物件解構讀取參數
            const user = await database.find(userId);
            return { result: user };
        },
    )
    .start();

💡 개발 핵심 참고 사항:

  1. 매개변수 수신: 클라이언트가 보낸 args는 단일 객체로 콜백 함수에 전달되므로, 도구에 여러 매개변수가 정의된 경우 콜백 함수에서 { param1, param2 }를 사용하여 객체 구조 분해를 반드시 수행해야 합니다.

  2. 비동기 지원: McpRegistry 내부에서 await를 사용하여 도구를 실행하므로, 콜백 함수에서 async/await를 사용하여 데이터베이스 조회나 네트워크 요청을 안심하고 수행할 수 있습니다.


📄 라이선스

이 프로젝트는 MIT License 조항에 따라 오픈소스로 제공됩니다.

Related MCP Connectors

Related MCP Servers

  • A
    license
    B
    quality
    D
    maintenance
    A lightweight, modular API service that provides useful tools like weather, date/time, calculator, search, email, and task management through a RESTful interface, designed for integration with AI agents and automated workflows.
    5
    1
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    Server that ingests Swagger/OpenAPI specifications and Postman collections, providing just 4 strategic tools that allow AI agents to dynamically discover and interact with APIs instead of generating hundreds of individual tools.
    3
    -
  • A
    license
    Not graded
    quality
    D
    maintenance
    A lightweight Node.js-based MCP server that exposes custom tools via HTTP and Server-Sent Events (SSE) for clients like Postman. It allows users to register tools with type-safe validation to establish bidirectional communication with MCP clients.
    1,107 npm
    1
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    A modular server for managing and registering tools, enabling extensible functionality through tool registration and configuration.
    -