🔍 MCP 도구(Tools)란?
도구는 LLM(대형 언어 모델)이 직접 실행할 수 있는 기능을 의미합니다. MCP 서버에서 도구는 다음과 같은 역할을 수행할 수 있습니다.
✅ 파일 조작
예) 특정 경로에 파일을 저장
✅ API 요청 처리
예) 날씨 API를 호출하여 실시간 날씨 정보를 가져오기
✅ 데이터 분석
예) 판매 데이터의 평균 및 통계를 계산
이처럼 도구를 활용하면 단순한 질문 응답을 넘어, 실제 동작을 수행하는 인공지능 시스템을 만들 수 있습니다.
🛠 MCP 서버에 도구 추가하기
1️⃣ 도구 정의하기
우선, 도구의 구조를 정의해야 합니다. MCP에서는 각 도구가 수행할 작업과 입력 데이터의 스키마(schema)를 지정할 수 있습니다.
export const tools = {
'create-message': {
name: 'create-message',
description: '다양한 옵션을 사용하여 메시지를 생성합니다.',
inputSchema: {
type: 'object',
properties: {
messageType: {
type: 'string',
enum: ['greeting', 'farewell', 'thank-you'],
description: '생성할 메시지 유형',
},
recipient: {
type: 'string',
description: '메시지를 받을 사람',
},
tone: {
type: 'string',
enum: ['formal', 'casual', 'playful'],
description: '메시지의 어조',
},
},
required: ['messageType', 'recipient'],
},
},
};
위 코드에서 create-message라는 도구를 정의했습니다. 이 도구는 인사(greeting), 작별(farewell), 감사(thank-you) 메시지를 생성하는 기능을 제공합니다.
2️⃣ 도구 핸들러 추가하기
다음으로, 도구의 실제 동작을 구현하는 핸들러(handler)를 추가해야 합니다.
const createMessage = (args: { messageType: string; recipient: string; tone?: string }) => {
const messageTemplates = {
greeting: {
formal: (recipient: string) => `안녕하세요, ${recipient}님. 건강하시길 바랍니다.`,
casual: (recipient: string) => `안녕, ${recipient}! 잘 지내?`,
playful: (recipient: string) => `야호! ${recipient}, 오늘 어때? 🎉`,
},
farewell: {
formal: (recipient: string) => `${recipient}님, 건강하십시오. 곧 다시 뵙겠습니다.`,
casual: (recipient: string) => `잘 가, ${recipient}! 다음에 또 봐!`,
playful: (recipient: string) => `안녕히 가세요, ${recipient}! 🎈 즐거운 하루 보내세요!`,
},
'thank-you': {
formal: (recipient: string) => `${recipient}님, 도움 주셔서 진심으로 감사드립니다.`,
casual: (recipient: string) => `고마워, ${recipient}! 정말 감사해!`,
playful: (recipient: string) => `와우! ${recipient}, 넌 최고야! 🌟 정말 고마워!`,
},
};
if (!args.messageType || !args.recipient) {
throw new Error('messageType과 recipient는 필수 입력 값입니다.');
}
const { messageType, recipient, tone = 'casual' } = args;
return { content: [{ type: 'text', text: messageTemplates[messageType][tone](recipient) }] };
};
export const toolHandlers = {
'create-message': createMessage,
};
💡 createMessage 함수는 messageType, recipient, tone 값을 받아 적절한 메시지를 생성합니다.
예를 들어, createMessage({ messageType: 'thank-you', recipient: 'Alice', tone: 'playful' })을 호출하면,
"와우! Alice, 넌 최고야! 🌟 정말 고마워!"
라는 메시지가 반환됩니다.
🚀 도구 실행 테스트하기
도구를 성공적으로 추가한 후, 이를 MCP 서버에서 호출하여 테스트할 수 있습니다.
1️⃣ MCP 서버 핸들러 업데이트
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: Object.values(tools),
}));
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: params } = request.params ?? {};
const handler = toolHandlers[name as keyof typeof toolHandlers];
if (!handler) throw new Error('해당 도구를 찾을 수 없습니다.');
return handler(params);
});
2️⃣ Inspector에서 테스트하기
테스트 환경을 설정한 후 MCP Inspector를 실행합니다.
npm run build
npx @modelcontextprotocol/inspector node build/index.js
Inspector에서 Tools 탭을 클릭하고, create-message 도구를 선택한 후 아래와 같이 입력하면:
{
"messageType": "thank-you",
"recipient": "Alice",
"tone": "playful"
}
💡 출력 결과
{
"content": [
{
"type": "text",
"text": "와우! Alice, 넌 최고야! 🌟 정말 고마워!"
}
]
}
이제 MCP 서버가 도구를 활용하여 동적인 작업을 수행할 수 있도록 완성되었습니다! 🎉
📌 이번 블로그에서 배운 것
✅ MCP 도구의 개념 및 필요성
✅ MCP 서버에 도구 추가하는 방법
✅ 도구의 실행 및 테스트 과정
https://medium.com/@cstroliadavis/building-mcp-servers-f9ce29814f1f
Building MCP Servers
Part 4 — Creating Tools
medium.com
'인공지능' 카테고리의 다른 글
Moonlight: 연구자들을 위한 AI 논문 분석 도구 (0) | 2025.04.03 |
---|---|
Agentic RAG와 MCP 서버 통합 가이드: AI 검색 최적화 방법 (0) | 2025.04.02 |
MCP 서버 구축: 프롬프트 추가하기 (0) | 2025.04.02 |
MCP 서버 확장하기: 리소스 템플릿(Resource Templates) 활용법 (0) | 2025.04.02 |
MCP 서버 구축 가이드: AI와 데이터를 연결하는 새로운 방식 (0) | 2025.04.02 |