본문 바로가기
1인개발자에서 살아남는법!

실시간 외부 API를 연동하는 AI 서버 구축법 (MCP + Node.js 실전 예제)

by Alan__kang__morlang 2025. 4. 30.
반응형

MCP(Model Context Protocol)는 AI 모델이 외부 시스템의 데이터를 실시간으로 읽고, 명령을 수행할 수 있도록 설계된 개방형 프로토콜입니다. AI와 외부 시스템(DB, API 등)을 연결하는 다리 역할을 하는 것이 바로 MCP 서버입니다.

Node.js로 MCP 서버 구축하기

npm init -y
npm install express body-parser

이후 프로젝트 구조는 아래와 같이 구성합니다.

mcp-server/
├── server.js
├── routes/
│   └── api.js
├── .well-known/
│   └── mcp.json
├── package.json

server.js

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const apiRouter = require('./routes/api');
require('dotenv').config(); // .env 환경변수 로딩

const app = express();
const PORT = 3000;

app.use(bodyParser.json());
app.use('/.well-known', express.static(path.join(__dirname, '.well-known')));
app.use('/api', apiRouter);

app.get('/status', (req, res) => {
  res.json({ status: 'MCP server is running' });
});

app.listen(PORT, () => {
  console.log(`MCP server is running at http://localhost:${PORT}`);
});

.well-known/mcp.json 정의

MCP 정의 정보는 .well-known/mcp.json에 아래와 같이 작성합니다.

{
  "mcp_version": "1.0",
  "endpoints": {
    "status": "/status",
    "data": "/api/data"
  },
  "description": "이 서버는 AI와 외부 시스템을 연결하는 MCP 서버입니다."
}

테스트 주소:

http://localhost:3000/.well-known/mcp.json

외부 날씨 API 연동하기 (OpenWeatherMap)

  1. https://openweathermap.org/ 에 가입
  2. API Key 발급
  3. Axios 설치: npm install axios
  4. API 구현 (routes/api.js)
router.get('/weather', async (req, res) => {
  const city = req.query.city || 'Seoul';
  const apiKey = process.env.OPENWEATHER_API_KEY;

  try {
    const response = await axios.get(
      `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric&lang=kr`
    );
    res.json({
      city: response.data.name,
      temperature: response.data.main.temp,
      description: response.data.weather[0].description,
    });
  } catch (error) {
    res.status(500).json({ error: '날씨 정보를 가져오지 못했습니다.' });
  }
});

API Key 보안 관리 (.env 사용)

보안을 위해 API Key는 코드에 직접 쓰지 않고 .env 파일에 저장합니다.

# .env
OPENWEATHER_API_KEY=발급받은_API_KEY

.gitignore에 다음을 추가해 Git에 올라가지 않도록 합니다.

.env

server.js 최상단에 아래 코드를 추가합니다:

require('dotenv').config();

---

여기까지가 MCP 서버 초기 구축과 외부 API 연동, 그리고 보안 처리 방법입니다. 다음에는 뉴스 API 연결과 DB 연동도 이어서 정리할 예정입니다.

 

반응형