Mastra 프레임워크 완전 가이드: TypeScript 개발자를 위한 AI Agent 필수 도구
title: Mastra 프레임워크 완전 가이드: TypeScript 개발자를 위한 AI Agent 필수 도구 date: 2026-04-01 authors: [kevinpeng] slug: mastra-typescript-ai-agent-framework-2026 categories: - AI 어시스턴트 tags: - Mastra - TypeScript - AI Agent - 오픈소스 프레임워크 - 개발자 도구 cover: https://res.makeronsite.com/freeaitool.com/052-mastra-typescript-ai-agent-framework-2026-cover.webp description: Mastra 는 2026 년 가장 인기 있는 TypeScript AI Agent 프레임워크로, 워크플로우, 메모리, RAG, 평가, 추적 기능을 제공합니다. 본 가이드는 설치, 핵심 개념, 실전 예시, 프로덕션 배포를 다룹니다. lang: ko
왜 Mastra 를 선택해야 할까요?
TypeScript/JavaScript 개발자로서 AI 애플리케이션 개발에서 Python 개발자와 동일한 생산성을 얻고 싶다면, Mastra 가 바로 당신을 위해 만들어진 프레임워크입니다.
Mastra 는 Y Combinator 의 지원을 받는 오픈소스 TypeScript 네이티브 AI Agent 프레임워크로, 웹 개발자를 위해 설계되었습니다. AI 애플리케이션을 구축, 테스트, 배포하는 데 필요한 모든 원시 요소를 제공하여 아이디어에서 프로덕션까지 빠르게 나아갈 수 있게 합니다.
핵심 장점
- TypeScript 네이티브: 완전한 타입 지원과 IDE 인텔리센스
- 프로덕션 준비 완료: 워크플로우, 메모리, RAG, 평가, 추적 내장
- 개발자 경험: 인터랙티브 Playground 및 실시간 디버깅
- 오픈소스 무료: MIT 라이선스, 커뮤니티 주도
빠른 시작
Mastra 설치
# 새 프로젝트 생성
npx create-mastra@latest my-ai-app
# 프로젝트 디렉토리로 이동
cd my-ai-app
# 의존성 설치
npm install
프로젝트 구조
my-ai-app/
├── src/
│ ├── mastra/
│ │ ├── agents/ # Agent 정의
│ │ ├── tools/ # 커스텀 도구
│ │ ├── workflows/ # 워크플로우
│ │ └── index.ts # 메인 엔트리
│ └── index.ts
├── package.json
└── mastra.config.ts
핵심 개념
1. Agent 생성
Agent 는 Mastra 의 핵심 빌딩 블록입니다. 각 Agent 는 특정 역할, 도구, 메모리를 가집니다.
// src/mastra/agents/customer-support.ts
import { Agent } from '@mastra/core/agent';
export const customerSupportAgent = new Agent({
name: 'Customer Support Agent',
instructions: `
당신은 제품 관련 사용자 질문에 대응하는 전문 고객 지원 어시스턴트입니다.
- 친절하고 전문적인 톤 유지
- 정확한 정보 제공
- 답을 모르는 경우 솔직하게 말하고人工 지원 연결을 제안
`,
model: {
provider: 'ANTHROPIC',
name: 'claude-sonnet-4-20250514',
},
});
2. 커스텀 도구 생성
도구는 Agent 가 데이터베이스 쿼리, API 호출 등 구체적인 작업을 수행할 수 있게 합니다.
// src/mastra/tools/order-lookup.ts
import { createTool } from '@mastra/core/tools';
import { z } from 'zod';
export const orderLookupTool = createTool({
id: 'order-lookup',
description: '주문 번호로 주문 상태 조회',
inputSchema: z.object({
orderId: z.string().describe('주문 번호'),
}),
execute: async ({ context }) => {
const { orderId } = context;
// 데이터베이스 쿼리 시뮬레이션
const order = await db.orders.findUnique({
where: { id: orderId },
});
return {
status: order?.status || 'not_found',
items: order?.items || [],
total: order?.total || 0,
};
},
});
3. 도구를 Agent 에 바인딩
// src/mastra/agents/customer-support.ts
import { customerSupportAgent } from './customer-support';
import { orderLookupTool } from '../tools/order-lookup';
// 도구 추가
customerSupportAgent.addTools([orderLookupTool]);
4. 워크플로우 생성
워크플로우를 통해 여러 Agent 와 도구를 오케스트레이션하여 복잡한 비즈니스 프로세스를 구현할 수 있습니다.
// src/mastra/workflows/order-processing.ts
import { Workflow } from '@mastra/core/workflows';
import { agentStep } from '@mastra/core/step';
export const orderProcessingWorkflow = new Workflow({
name: 'order-processing',
triggerSchema: z.object({
orderId: z.string(),
customerEmail: z.string().email(),
}),
});
// 단계 정의
const checkOrder = agentStep({
agent: customerSupportAgent,
outputSchema: z.object({
status: z.string(),
canRefund: z.boolean(),
}),
});
const sendEmail = agentStep({
agent: emailAgent,
outputSchema: z.object({
sent: z.boolean(),
}),
});
// 흐름 오케스트레이션
orderProcessingWorkflow
.step(checkOrder)
.then(sendEmail, {
when: { ref: checkOrder, path: 'canRefund', eq: true },
});
실전 예시: 고객 서비스 봇 구축
주문 조회, 반품 요청, 제품 상담을 처리할 수 있는 완전한 고객 서비스 봇을 구축해 봅시다.
전체 코드
// src/mastra/index.ts
import { Mastra } from '@mastra/core/mastra';
import { customerSupportAgent } from './agents/customer-support';
import { orderLookupTool } from './tools/order-lookup';
import { refundTool } from './tools/refund';
import { orderProcessingWorkflow } from './workflows/order-processing';
export const mastra = new Mastra({
agents: {
'customer-support': customerSupportAgent,
},
tools: {
'order-lookup': orderLookupTool,
'refund': refundTool,
},
workflows: {
'order-processing': orderProcessingWorkflow,
},
});
개발 서버 시작
# Mastra 개발 서버 시작 (Playground 포함)
npx mastra dev
http://localhost:4111 에 접속하여 인터랙티브 Playground 를 열고 Agent 를 실시간으로 테스트할 수 있습니다.
Agent 호출
// src/index.ts
import { mastra } from './mastra';
async function main() {
const agent = mastra.getAgent('customer-support');
const response = await agent.generate(
'제 주문 번호는 ORD-12345 입니다. 상태를 확인해 주세요'
);
console.log(response.text);
}
main();
고급 기능
메모리 시스템
Mastra 는 메모리를 내장하여 Agent 가 대화 기록을 기억할 수 있게 합니다.
import { Memory } from '@mastra/memory';
const memory = new Memory({
storage: {
type: 'postgres',
connectionString: process.env.DATABASE_URL,
},
});
const agent = new Agent({
name: 'Support Agent',
memory,
// ...기타 설정
});
RAG (검색 증강 생성)
import { RAG } from '@mastra/rag';
const rag = new RAG({
vectorStore: {
type: 'pinecone',
apiKey: process.env.PINECONE_API_KEY,
},
});
// 문서 인덱싱
await rag.index({
documents: ['./docs/product-manual.pdf'],
indexName: 'product-knowledge',
});
// Agent 에서 사용
const agent = new Agent({
name: 'Product Expert',
rag: {
indexes: ['product-knowledge'],
},
});
평가 및 추적
import { Eval } from '@mastra/evals';
const eval = new Eval({
name: 'response-quality',
criteria: [
{ name: 'accuracy', weight: 0.4 },
{ name: 'helpfulness', weight: 0.3 },
{ name: 'tone', weight: 0.3 },
],
});
// 평가 실행
const results = await eval.evaluate(agent, testCases);
console.log(results.summary);
프로덕션 배포
Vercel 에 배포
# Vercel CLI 설치
npm i -g vercel
# 배포
vercel deploy --prod
Docker 에 배포
# Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["npm", "start"]
# 빌드 및 실행
docker build -t my-mastra-app .
docker run -p 3000:3000 my-mastra-app
성능 최적화 팁
- 스트리밍 응답 사용: 긴 텍스트 생성 시 streaming 을 활성화하여 사용자 경험 향상
- 도구 결과 캐싱: 자주 호출되는 도구는 결과 캐시 구현
- 배치 처리: 여러 유사한 요청은 배치 API 호출 사용
- 레이턴시 모니터링: Mastra 내장 추적으로 각 단계 소요 시간 모니터링
다른 프레임워크와 비교
| 기능 | Mastra | LangChain.js | Vercel AI SDK |
|---|---|---|---|
| TypeScript 네이티브 | ✅ | ⚠️ | ✅ |
| 내장 워크플로우 | ✅ | ✅ | ❌ |
| 인터랙티브 Playground | ✅ | ❌ | ❌ |
| 메모리 시스템 | ✅ | ✅ | ⚠️ |
| RAG 지원 | ✅ | ✅ | ❌ |
| 평가 도구 | ✅ | ⚠️ | ❌ |
| 학습 곡선 | 중간 | 가파름 | 완만 |
요약
Mastra 는 TypeScript 개발자가 AI Agent 개발에 진입하기 위한 최고의 선택 중 하나입니다. 다음을 제공합니다:
- 🎯 개발자 친화적 API: 타입 안전, 인텔리센스 완벽 지원
- 🔧 풍부한 내장 기능: 워크플로우, 메모리, RAG, 평가 원스톱 솔루션
- 🚀 프로덕션 준비 완료: 개발부터 배포까지 완전한 도구 모음
- 📚 우수한 문서: 상세한 튜토리얼과 예시
이미 TypeScript 생태계에서 작업 중이고 빠르게 AI 앱을 구축하고 싶다면, Mastra 는 시도해 볼 가치가 있습니다.
참고 자료
관련 읽기 추천: