개발자 문서
개발자 문서

서버에서 직접 호출

자사 AI 채팅·자동화 서버에서 XBOSS MCP 를 호출하는 전체 코드입니다. Node.js 와 Python 을 제공합니다.

MCP 는 HTTP POST + JSON-RPC 한 가지 형식입니다. 별도 SDK 없이 fetch 나 requests 로 부를 수 있습니다.

흐름은 언어·모델과 상관없이 같습니다.

아래 코드의 CLIENT_ID 와 CLIENT_SECRET 자리에 발급받은 값을 넣습니다. 키는 API 키 발급에서 받습니다.

  1. STEP 01
    tools/list

    쓸 수 있는 도구 목록을 받습니다.

  2. STEP 02
    LLM 형식으로 변환

    OpenAI 는 function, Anthropic 은 input_schema 형식입니다.

  3. STEP 03
    LLM 호출

    사용자 메시지와 도구 목록을 함께 보냅니다.

  4. STEP 04
    tools/call 실행

    LLM 이 고른 도구를 실행하고 결과를 돌려줍니다.

도구 목록을 받아 LLM 형식으로 바꾸고, LLM 이 고른 도구를 XBOSS 로 실행해 결과를 돌려줍니다.

OpenAI 계열 모델

bash
npm install openai    # Node.js
pip install openai requests    # Python
xboss-mcp.mjs
javascript
// npm install openai
import OpenAI from 'openai';

const MCP_URL = 'https://api.xdata.kr/mcp';
const AUTH = Buffer.from('CLIENT_ID:CLIENT_SECRET').toString('base64');

async function mcpPost(method, params = {}) {
  const res = await fetch(MCP_URL, {
    method: 'POST',
    headers: {
      Authorization: `Basic ${AUTH}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ jsonrpc: '2.0', id: Date.now(), method, params }),
  });
  let body;
  try {
    body = await res.json();
  } catch {
    throw new Error('MCP 응답을 읽을 수 없습니다 (HTTP ' + res.status + ')');
  }
  if (!res.ok || body.error) {
    const error = new Error(body.error?.message ?? ('MCP HTTP 오류: ' + res.status));
    error.code = body.error?.code;
    error.data = body.error?.data;
    throw error;
  }
  return body;
}

// 1. tools/list → OpenAI tools 포맷으로 변환
const { result } = await mcpPost('tools/list');
// 모델용 이름은 64자 이내의 영문·숫자·밑줄·하이픈만 씁니다.
// 모든 이름에 목록 인덱스를 붙여 잘린 이름끼리도 충돌하지 않게 합니다.
const toolNames = new Map();
const tools = result.tools.map((t, index) => {
  const suffix = '_' + index;
  const name = t.name.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 64 - suffix.length) + suffix;
  toolNames.set(name, t.name);
  return {
    type: 'function',
    function: { name, description: t.description, parameters: t.inputSchema },
  };
});

// 2. OpenAI 호출 (Gemini, Azure, OpenAI 호환 모두 동일)
const openai = new OpenAI(/* baseURL, apiKey 등 필요 시 추가 */);
const response = await openai.chat.completions.create({
  model: 'gpt-4o',
  tools,
  messages: [{ role: 'user', content: '질문 입력' }],
});

// 3. tool_calls → XBOSS 실행
for (const call of response.choices[0].message.tool_calls ?? []) {
  const name = toolNames.get(call.function.name);
  if (!name) throw new Error('목록에 없는 도구 이름: ' + call.function.name);
  const { result: res } = await mcpPost('tools/call', {
    name,
    arguments: JSON.parse(call.function.arguments),
  });
  console.log(res);
}

Anthropic 모델

bash
npm install @anthropic-ai/sdk    # Node.js
pip install anthropic requests    # Python
xboss-mcp-anthropic.mjs
javascript
// npm install @anthropic-ai/sdk
import Anthropic from '@anthropic-ai/sdk';

const MCP_URL = 'https://api.xdata.kr/mcp';
const AUTH = Buffer.from('CLIENT_ID:CLIENT_SECRET').toString('base64');

async function mcpPost(method, params = {}) {
  const res = await fetch(MCP_URL, {
    method: 'POST',
    headers: {
      Authorization: `Basic ${AUTH}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ jsonrpc: '2.0', id: Date.now(), method, params }),
  });
  let body;
  try {
    body = await res.json();
  } catch {
    throw new Error('MCP 응답을 읽을 수 없습니다 (HTTP ' + res.status + ')');
  }
  if (!res.ok || body.error) {
    const error = new Error(body.error?.message ?? ('MCP HTTP 오류: ' + res.status));
    error.code = body.error?.code;
    error.data = body.error?.data;
    throw error;
  }
  return body;
}

// 1. tools/list → Anthropic tools 포맷으로 변환
const { result } = await mcpPost('tools/list');
const tools = result.tools.map(t => ({
  name: t.name,
  description: t.description,
  input_schema: t.inputSchema,
}));

// 2. Anthropic 호출
const client = new Anthropic();
const response = await client.messages.create({
  model: 'claude-opus-5',
  max_tokens: 16000,
  tools,
  messages: [{ role: 'user', content: '질문 입력' }],
});

// 3. tool_use → XBOSS 실행
for (const block of response.content) {
  if (block.type === 'tool_use') {
    const { result: res } = await mcpPost('tools/call', {
      name: block.name,
      arguments: block.input,
    });
    console.log(res);
  }
}

Gemini · Azure OpenAI · Groq · Ollama 처럼 OpenAI 호환 API 는 위 OpenAI 코드에서 baseURL 과 apiKey 만 바꾸면 됩니다. 도구 형식이 같습니다.

X-MCP-Env-Scope 헤더는 넣지 않아도 됩니다.

넣지 않으면 자격증명이 환경을 정합니다. 요금제를 시작하기 전의 계정은 데모(real_test), 요금제를 시작한 계정은 정식(production)입니다.

한 자격증명으로 다른 환경을 부를 때만 X-MCP-Env-Scope: real_test 또는 X-MCP-Env-Scope: production 을 더합니다.

플랜이 허용하지 않는 환경을 지정하면 거절됩니다.

REST 의 X-Env-Scope 는 MCP 에 적용되지 않고, real_test 와 production 이 아닌 값은 -32602 로 거절됩니다.

도구 이름과 자격증명

도구 이름은 tools/list 결과에 있습니다. XBOSS 작업(action)의 점을 밑줄 두 개로 바꾼 형태입니다.

account_link_id 는 그 기관에 등록한 자격증명이 하나뿐이면 넘기지 않아도 됩니다.

등록한 자격증명이 없으면 도구가 실행되지 않고 -32602 로 안내가 옵니다. MCP 오류 코드의 -32602 표를 봅니다.

부르기 전에도 tools/list 의 각 도구에 있는 _meta["xdata.kr/credential"] 에서 등록이 필요한지(required)와 등록 화면 주소(register_url)를 알 수 있습니다.