> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # 구성 다음 참조는 Mastra에서 지원되는 모든 옵션을 다룹니다. 인스턴스화하여 Mastra를 초기화하고 구성합니다.[`Mastra` class](https://mastra.zisheng.pro/ko/reference/core/mastra-class). ```ts import { Mastra } from '@mastra/core' export const mastra = new Mastra({ // Your options... }) ``` ## 최상위 옵션 ### Agent **유형:** `Record` 이름으로 입력된 Agent 인스턴스의 기록입니다. Agent는 AI Model, Tool 및 Memory를 사용하여 결정을 내리고 조치를 취할 수 있는 자율 시스템입니다. 자세한 내용은 [Agent 문서](https://mastra.zisheng.pro/ko/docs/agents/overview)를 참조하세요. ```typescript import { Mastra } from '@mastra/core' import { Agent } from '@mastra/core/agent' export const mastra = new Mastra({ agents: { weatherAgent: new Agent({ id: 'weather-agent', name: 'Weather Agent', instructions: 'You help with weather information', model: 'openai/gpt-5.6-sol', }), }, }) ``` ### 배경작업 **유형:** `BackgroundTaskManagerConfig` 백그라운드 작업 관리자를 활성화하고 구성합니다. 활성화하면 Agent 루프가 계속되는 동안 장기 실행 Tool 호출(하위 Agent 호출 포함)을 비동기적으로 실행하도록 디스패치할 수 있습니다. 작업은 유지되므로 구성된 `storage` 백엔드가 필요합니다. 자세한 내용은 [백그라운드 작업 문서](https://mastra.zisheng.pro/ko/docs/long-running-agents/background-tasks)를 참조하세요. ```typescript import { Mastra } from '@mastra/core' import { LibSQLStore } from '@mastra/libsql' export const mastra = new Mastra({ storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./mastra.db', }), backgroundTasks: { enabled: true, globalConcurrency: 10, perAgentConcurrency: 5, backpressure: 'queue', defaultTimeoutMs: 300_000, }, }) ``` **enabled** (`boolean`): 백그라운드 작업 관리자를 사용할 수 있는지 여부입니다. 이 값이 true이고 스토리지 백엔드가 구성된 경우에만 관리자가 초기화됩니다. 이는 기능 가용성 스위치일 뿐이며 어떤 Tool도 백그라운드 디스패치에 자동으로 참여시키지 않습니다. Tool 또는 Agent 계층에서 명시적으로 참여해야 합니다(백그라운드 작업 가이드 참조). (Default: `false`) **globalConcurrency** (`number`): 모든 Agent에서 동시에 실행되는 백그라운드 작업의 최대 개수입니다. (Default: `10`) **perAgentConcurrency** (`number`): 단일 Agent에서 동시에 실행되는 백그라운드 작업의 최대 개수입니다. (Default: `5`) **backpressure** (`'queue' | 'reject' | 'fallback-sync'`): 동시성 제한에 도달했을 때의 동작입니다. 'queue'는 슬롯이 생길 때까지 대기하고, 'reject'는 큐에 추가할 때 오류를 발생시키며, 'fallback-sync'는 대신 Agent 루프에서 Tool을 동기적으로 실행합니다. (Default: `'queue'`) **defaultTimeoutMs** (`number`): 작업별 기본 타임아웃(밀리초)입니다. Tool별 또는 호출별로 재정의할 수 있습니다. (Default: `300000`) **defaultRetries** (`RetryConfig`): 실패한 작업에 적용되는 기본 재시도 정책입니다. **defaultRetries.maxRetries** (`number`): 작업을 실패로 표시하기 전까지의 최대 재시도 횟수입니다. **defaultRetries.retryDelayMs** (`number`): 재시도 사이의 지연 시간(밀리초)입니다. **defaultRetries.backoffMultiplier** (`number`): 이후 각 재시도에서 retryDelayMs에 적용되는 배수입니다. **defaultRetries.maxRetryDelayMs** (`number`): 백오프와 관계없이 적용되는 재시도 지연 시간의 상한입니다. **defaultRetries.retryableErrors** (`(error: Error) => boolean`): 주어진 오류를 재시도할지 결정하는 조건자입니다. 기본값: 모든 오류를 재시도합니다. **cleanup** (`CleanupConfig`): 작업 레코드의 보관 기간과 정리 프로세스 실행 주기를 제어합니다. **cleanup.completedTtlMs** (`number`): 완료된 작업 레코드를 보관하는 기간(밀리초)입니다. 기본값: 1시간. **cleanup.failedTtlMs** (`number`): 실패한 작업 레코드를 보관하는 기간(밀리초)입니다. 기본값: 24시간. **cleanup.cleanupIntervalMs** (`number`): 정리 프로세스의 실행 주기(밀리초)입니다. 기본값: 1분. **waitTimeoutMs** (`number`): Agent 루프가 다음으로 넘어가기 전에 백그라운드 작업 완료를 기다리는 시간입니다. 이 시간 내에 작업이 완료되지 않으면 루프는 isContinued를 설정하지 않고 진행합니다. 기본값: undefined(대기하지 않음). Agent별 또는 Tool별로 재정의할 수 있습니다. **onTaskComplete** (`(task: BackgroundTask) => void | Promise`): 백그라운드 작업이 성공적으로 완료될 때 호출되는 전역 콜백입니다. Tool별 및 Agent별 콜백에 추가로 실행됩니다. **onTaskFailed** (`(task: BackgroundTask) => void | Promise`): 백그라운드 작업이 실패할 때 호출되는 전역 콜백입니다. Tool별 및 Agent별 콜백에 추가로 실행됩니다. ### 배포자 **유형:** `MastraDeployer` 클라우드 플랫폼에 애플리케이션을 게시하기 위한 배포 공급자입니다. 자세한 내용은 [배포 문서](https://mastra.zisheng.pro/ko/docs/deployment/overview)를 참조하세요. ```typescript import { Mastra } from '@mastra/core' import { NetlifyDeployer } from '@mastra/deployer-netlify' export const mastra = new Mastra({ deployer: new NetlifyDeployer(), }) ``` ### 이벤트 **유형:** `Record` 내부 게시/구독 시스템용 이벤트 핸들러입니다. 이벤트가 해당 주제에 게시될 때 호출되는 처리기 함수에 이벤트 주제를 매핑합니다. > **경고:** 이는 Mastra의 Workflow 엔진에서 내부적으로 사용됩니다. 대부분의 사용자는 이 옵션을 구성할 필요가 없습니다. ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ events: { 'my-topic': async event => { console.log('Event received:', event) }, }, }) ``` ### 게이트웨이 **유형:** `Record` LLM Provider에 액세스하기 위한 맞춤형 Model 라우터 게이트웨이입니다. 게이트웨이는 공급자별 인증, URL 구성 및 Model 확인을 처리합니다. 이를 사용하여 맞춤형 또는 자체 호스팅 LLM Provider에 대한 지원을 추가합니다. 자세한 내용은 [사용자 정의 게이트웨이 문서](https://mastra.zisheng.pro/ko/models/gateways/custom-gateways)를 참조하세요. ```typescript import { Mastra } from '@mastra/core' import { MyPrivateGateway } from './gateways' export const mastra = new Mastra({ gateways: { private: new MyPrivateGateway(), }, }) ``` ### 아이디 생성기 **유형:** `(context?: IdGeneratorContext) => string`\ **Default:** `crypto.randomUUID()` 고유 식별자를 생성하기 위한 사용자 정의 ID 생성기 기능입니다. Mastra는 생성되는 항목을 기반으로 ID를 생성할 수 있도록 선택적 컨텍스트를 전달합니다. `IdGeneratorContext`다음이 포함됩니다: - `idType`: `'thread' | 'message' | 'run' | 'step' | 'generic'` - `source?`: `'agent' | 'workflow' | 'memory'` - `entityId?`: 요청 Agent/Workflow/Memory 엔터티의 ID - `threadId?`: 관련된 경우 스레드 ID(예: 메시지 ID를 생성하는 경우) - `resourceId?`: 관련된 경우 리소스 ID(예: 사용자 범위 스레드) - `role?`: 메시지 ID 생성 시 메시지 역할 - `stepType?`: 단계 ID 생성 시 Workflow 단계 유형 > **경고:** 이는 Workflow 실행, Agent 대화 및 기타 리소스에 대한 ID를 생성하기 위해 Mastra에서 내부적으로 사용됩니다. 대부분의 사용자는 이 옵션을 구성할 필요가 없습니다. ```typescript import { v4 as uuid } from '@lukeed/uuid' import { Mastra } from '@mastra/core' export const mastra = new Mastra({ idGenerator: context => { if (context?.idType === 'message' && context?.threadId) { return `msg-${context.threadId}-${uuid()}` } if (context?.idType === 'run' && context?.source && context?.entityId) { return `${context.source}-run-${context.entityId}-${uuid()}` } return uuid() }, }) ``` ### 나무꾼 **유형:** `IMastraLogger | false`\ **기본값:** 개발 환경에서는 `INFO` 수준, 프로덕션 환경에서는 `WARN` 수준의 `ConsoleLogger` 애플리케이션 로깅 및 디버깅을 위한 로거 구현입니다. 로깅을 완전히 비활성화하려면 `false`로 설정하세요. 자세한 내용은 [로깅 문서](https://mastra.zisheng.pro/ko/docs/observability/logging)를 참조하세요. ```typescript import { Mastra } from '@mastra/core' import { PinoLogger } from '@mastra/loggers' export const mastra = new Mastra({ logger: new PinoLogger({ name: 'MyApp', level: 'debug' }), }) ``` ### mcp서버 **유형:** `Record` Mastra Tool, Agent, Workflow 및 리소스를 MCP 호환 클라이언트에 노출하는 MCP(Model 컨텍스트 프로토콜) 서버입니다. 이를 사용하여 프로토콜을 지원하는 모든 시스템에서 사용할 수 있는 자체 MCP 서버를 작성합니다. 자세한 내용은 [MCP 개요](https://mastra.zisheng.pro/ko/docs/mcp/overview)를 참조하세요. ```typescript import { Mastra } from '@mastra/core' import { MCPServer } from '@mastra/mcp' const mcpServer = new MCPServer({ id: 'my-mcp-server', name: 'My MCP Server', version: '1.0.0', }) export const mastra = new Mastra({ mcpServers: { myServer: mcpServer, }, }) ``` ### Memory **유형:** `Record` Agent가 참조할 수 있는 Memory 인스턴스의 레지스트리입니다. 기억은 과거 대화의 관련 정보를 유지하여 Agent가 상호 작용 전반에 걸쳐 일관성을 갖도록 해줍니다. Mastra는 최근 메시지에 대한 메시지 기록과 지속적인 사용자별 세부 정보에 대한 작업 Memory를 지원합니다. 의미적 회상은 관련성을 기준으로 오래된 메시지를 검색합니다. 자세한 내용은 [Memory 문서](https://mastra.zisheng.pro/ko/docs/memory/overview)를 참조하세요. > **노트:** 대부분의 사용자는 Agent에서 직접 Memory를 구성합니다. 이 최상위 구성은 여러 Agent에서 공유할 수 있는 재사용 가능한 Memory 인스턴스를 정의하기 위한 것입니다. ```typescript import { Mastra } from '@mastra/core' import { Memory } from '@mastra/memory' import { LibSQLStore } from '@mastra/libsql' export const mastra = new Mastra({ storage: new LibSQLStore({ id: 'mastra-storage', url: ':memory:', }), memory: { chatMemory: new Memory({ options: { lastMessages: 20, }, }), }, }) ``` ### Observability **유형:** `ObservabilityEntrypoint` Mastra는 AI 애플리케이션에 대한 관찰 기능을 제공합니다. AI 관련 패턴을 이해하는 Tool을 사용하여 LLM 작업을 모니터링하고, Agent 결정을 추적하고, 복잡한 Workflow를 디버그하세요. 추적은 Model 상호 작용, Agent 실행 경로, Tool 호출 및 Workflow 단계를 캡처합니다. 자세한 내용은 [Observability 문서](https://mastra.zisheng.pro/ko/docs/observability/overview)를 참조하세요. ```typescript import { Mastra } from '@mastra/core' import { LibSQLStore } from '@mastra/libsql' import { Observability, MastraStorageExporter } from '@mastra/observability' export const mastra = new Mastra({ storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./mastra.db', }), observability: new Observability({ configs: { default: { serviceName: 'my-app', exporters: [new MastraStorageExporter()], }, }, }), }) ``` ### 프로세서 **유형:** `Record` Agent 입력 및 출력을 변환하기 위한 입력/출력 프로세서입니다. 프로세서는 Agent 실행 파이프라인의 특정 지점에서 실행되므로 언어 ​​Model에 도달하기 전에 입력을 수정하거나 반환되기 전에 출력을 수정할 수 있습니다. 프로세서를 사용하여 가드레일을 추가하고, 즉각적인 삽입을 감지하고, 콘텐츠를 조정하거나, 맞춤형 비즈니스 로직을 적용하세요. 자세한 내용은 [프로세서 문서](https://mastra.zisheng.pro/ko/docs/agents/processors)를 참조하세요. > **노트:** 대부분의 사용자는 Agent에서 직접 프로세서를 구성합니다. 이 최상위 구성은 여러 Agent에서 공유할 수 있는 재사용 가능한 프로세서 인스턴스를 정의하기 위한 것입니다. ```typescript import { Mastra } from '@mastra/core' import { ModerationProcessor } from '@mastra/core/processors' export const mastra = new Mastra({ processors: { moderation: new ModerationProcessor({ model: 'openai/gpt-5-mini', categories: ['hate', 'harassment', 'violence'], }), }, }) ``` ### 게시자 **유형:** `PubSub`\ **Default:** `EventEmitterPubSub` 구성 요소 간의 이벤트 기반 통신을 위한 Pub/Sub 시스템입니다. Workflow 이벤트 처리 및 구성 요소 통신을 위해 Mastra에서 내부적으로 사용됩니다. > **경고:** 이는 Mastra에서 내부적으로 사용됩니다. 대부분의 사용자는 이 옵션을 구성할 필요가 없습니다. ```typescript import { Mastra } from '@mastra/core' import { CustomPubSub } from './pubsub' export const mastra = new Mastra({ pubsub: new CustomPubSub(), }) ``` ### 득점자 **유형:** `Record` 채점자는 Agent 응답 및 Workflow 출력의 품질을 평가합니다. Model 등급, 규칙 기반 및 통계 방법을 사용하여 Agent 품질을 측정하기 위한 수량화 가능한 측정항목을 제공합니다. 채점자를 사용하여 성과를 추적하고 접근 방식을 비교하세요. 또한 개선이 필요한 영역을 식별할 수도 있습니다. 자세한 내용은 [스코어러 문서](https://mastra.zisheng.pro/ko/docs/evals/overview)를 참조하세요. > **노트:** 대부분의 사용자는 Agent에서 직접 채점자를 구성합니다. 이 최상위 구성은 여러 Agent에서 공유할 수 있는 재사용 가능한 채점자 인스턴스를 정의하기 위한 것입니다. ```typescript import { Mastra } from '@mastra/core' import { createToxicityScorer } from '@mastra/evals/scorers/prebuilt' export const mastra = new Mastra({ scorers: { toxicity: createToxicityScorer({ model: 'openai/gpt-5-mini' }), }, }) ``` ### 저장 **유형:** `MastraCompositeStore` 애플리케이션 데이터를 유지하기 위한 스토리지 공급자입니다. 지속성이 필요한 Memory, Workflow, 추적 및 기타 구성 요소에서 사용됩니다. Mastra는 PostgreSQL, MongoDB, libSQL 등을 포함한 여러 데이터베이스 백엔드를 지원합니다. 자세한 내용은 [스토리지 문서](https://mastra.zisheng.pro/ko/docs/storage/overview)를 참조하세요. ```typescript import { Mastra } from '@mastra/core' import { LibSQLStore } from '@mastra/libsql' export const mastra = new Mastra({ storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./mastra.db', }), }) ``` ### Tool **유형:** `Record` Tool은 Agent가 외부 시스템과 상호 작용하는 데 사용할 수 있는 재사용 가능한 기능입니다. 각 Tool은 입력, 출력 및 실행 논리를 정의합니다. 자세한 내용은 [Tool 문서](https://mastra.zisheng.pro/ko/docs/agents/using-tools)를 참조하세요. :::참고 대부분의 사용자는 Agent에서 직접 Tool을 구성합니다. 이 최상위 구성은 여러 Agent에서 공유할 수 있는 재사용 가능한 Tool을 정의하기 위한 것입니다. ::: ```typescript import { Mastra } from '@mastra/core' import { createTool } from '@mastra/core/tools' import { z } from 'zod' const weatherTool = createTool({ id: 'get-weather', description: 'Fetches weather for a city', inputSchema: z.object({ city: z.string(), }), execute: async () => { return { temperature: 20, conditions: 'Sunny' } }, }) export const mastra = new Mastra({ tools: { weather: weatherTool, }, }) ``` ### ㅜㅜ **유형:** `Record` 음성 합성 기능을 위한 텍스트 음성 변환 제공자입니다. Agent가 텍스트 응답을 음성 오디오로 변환할 수 있도록 음성 공급자를 등록하세요. 자세한 내용은 [음성 문서](https://mastra.zisheng.pro/ko/guides/voice/overview)를 참조하세요. :::참고 대부분의 사용자는 Agent에서 직접 음성을 구성합니다. 이 최상위 구성은 여러 Agent에서 공유할 수 있는 재사용 가능한 음성 공급자를 정의하기 위한 것입니다. ::: ```typescript import { Mastra } from '@mastra/core' import { OpenAIVoice } from '@mastra/voice-openai' export const mastra = new Mastra({ tts: { openai: new OpenAIVoice(), }, }) ``` ### 벡터 **유형:** `Record` 의미론적 검색 및 임베딩을 위한 벡터 저장소입니다. RAG 파이프라인, 유사성 검색 및 기타 임베딩 기반 기능에 사용됩니다. Mastra는 Pinecone, PostgreSQL(pgVector 포함), OracleDB, MongoDB 등을 포함한 여러 벡터 데이터베이스를 지원합니다. 자세한 내용은 [RAG 문서](https://mastra.zisheng.pro/ko/guides/rag/overview)를 참조하세요. :::참고 대부분의 사용자는 RAG 파이프라인을 구축할 때 벡터 저장소를 직접 생성합니다. 이 최상위 구성은 애플리케이션 전체에서 공유할 수 있는 재사용 가능한 벡터 저장소 인스턴스를 정의하기 위한 것입니다. ::: ```typescript import { Mastra } from '@mastra/core' import { PineconeVector } from '@mastra/pinecone' export const mastra = new Mastra({ vectors: { pinecone: new PineconeVector({ id: 'pinecone-vector', apiKey: process.env.PINECONE_API_KEY, }), }, }) ``` ### Workflow **유형:** `Record` Workflow는 유형이 안전한 입력 및 출력을 사용하여 단계 기반 실행 파이프라인을 정의합니다. 특정 실행 순서가 있는 여러 단계가 포함된 작업에 Workflow를 사용하면 단계 간 데이터 흐름 방식을 제어할 수 있습니다. 자세한 내용은 [Workflow 문서](https://mastra.zisheng.pro/ko/docs/workflows/overview)를 참조하세요. ```typescript import { Mastra } from '@mastra/core' import { testWorkflow } from './workflows/test-workflow' export const mastra = new Mastra({ workflows: { testWorkflow, }, }) ``` ### 작업 공간 **유형:** `Workspace` Mastra Workspace는 Agent에 파일 저장 및 명령 실행을 위한 지속적인 환경을 제공합니다. 자체 Workspace가 구성되지 않은 Agent는 `Mastra` 클래스의 전역 Workspace를 상속합니다. 구현 세부 정보는 [Workspace 문서](https://mastra.zisheng.pro/ko/docs/workspace/overview)를 참조하세요. ```typescript import { Mastra } from '@mastra/core' import { Workspace, LocalFilesystem } from '@mastra/core/workspace' const workspace = new Workspace({ filesystem: new LocalFilesystem({ basePath: './workspace' }), }) const mastra = new Mastra({ workspace, }) ``` ## 번들러 옵션 ### 번들러.항목 **유형:** `Record`\ **Default:** `{}` Mastra 디렉터리 기준 소스 경로에 출력 이름을 매핑하여 서버 번들과 함께 내보낼 추가 프로세스 엔트리입니다. 각 엔트리는 `.mastra/output`에서 고유한 `.mjs`가 됩니다. Mastra 서버 내부가 아니라 서버와 나란히 실행되는 장기 실행 프로세스(예: [LiveKit 음성 worker](https://mastra.zisheng.pro/ko/guides/voice/realtime-voice))에 이 기능을 사용하세요. 이 엔트리는 서버와 출력 디렉터리, `package.json`, 설치된 종속성을 공유하므로 한 번의 `mastra build`로 각기 다른 명령으로 시작할 수 있는 하나의 배포 가능 아티팩트를 생성합니다. ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ bundler: { entries: { 'voice-worker': './voice-worker.ts' }, }, }) ``` 이렇게 하면 `.mastra/output/index.mjs` 옆에 `.mastra/output/voice-worker.mjs`가 생성됩니다. 추가 엔트리에서만 가져오는 종속성도 분석되므로 출력에 설치됩니다. 엔트리 이름에는 출력을 중첩하기 위한 `/`를 포함할 수 있습니다. 서버 번들인 `index`, Tool 애그리게이터인 `tools`는 사용할 수 없으며, Tool 번들용으로 예약된 `tools/`로 시작할 수도 없습니다. > **노트:** `mastra build`는 번들러 옵션을 전혀 설정하지 않았을 때만 [`bundler.externals`](#bundlerexternals)의 기본값 `true`를 적용합니다. `entries`를 설정한 후 추가 엔트리가 네이티브 모듈처럼 번들링할 수 없는 패키지에 의존한다면 `externals`도 명시적으로 설정하세요. ### 번들러.외부 **유형:** `boolean | string[]`\ **Default:** `true` `mastra build`를 실행하면 Mastra가 프로젝트를 `.mastra/output` 디렉터리에 번들링합니다. 이 옵션은 번들에서 제외되어 "external"로 표시되고 패키지 관리자를 통해 별도로 설치되는 패키지를 제어합니다. 내부 Mastra 번들러([Rollup](https://rollupjs.org/configuration-options/#external))가 패키지를 번들링하는 데 문제가 있을 때 유용합니다. 기본적으로 `mastra build`는 이 옵션을 `true`로 설정합니다. 값에는 다음과 같은 의미가 있습니다. - `true`: 프로젝트의 `package.json`에 나열된 모든 종속성을 external로 표시합니다 - `false`: 어떤 종속성도 external로 표시하지 않습니다. 모든 항목을 함께 번들링합니다 - `string[]`: external로 표시할 패키지 이름의 배열입니다. 나머지는 함께 번들링됩니다 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ bundler: { externals: ['some-package', 'another-package'], }, }) ``` ### 번들러.소스맵 **유형:** `boolean`\ **Default:** `false` 번들 출력에 대한 소스 맵 생성을 활성화합니다. ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ bundler: { sourcemap: true, }, }) ``` ### Bundler.transpile패키지 **유형:** `string[]`\ **Default:** `[]` 빌드 프로세스 중에 esbuild를 통해 소스 코드를 트랜스파일해야 하는 패키지 목록입니다. 번들링하기 전에 컴파일이 필요한 TypeScript 또는 기타 코드가 포함된 종속성에 대해 이를 사용하세요. 컴파일되지 않은 소스 코드를 직접 가져오는 경우에만 이 옵션이 필요합니다. 패키지가 이미 CommonJS 또는 ESM으로 컴파일된 경우 여기에 나열할 필요가 없습니다. Mastra는 모노레포 설정에서 작업 공간 패키지를 자동으로 감지하여 이 목록에 추가하므로 일반적으로 변환이 필요한 외부 패키지만 지정하면 됩니다. Mastra는 빌드 중 `tsconfig.json`의 `baseUrl` 및 `paths` 별칭도 해석합니다. 여기에는 TypeScript 소스 파일을 가리키는 `~/utils/logger.js` 같은 ESM 스타일 import가 포함됩니다. ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ bundler: { transpilePackages: ['@my-org/shared-utils'], }, }) ``` ## 서버 옵션 ### server.api경로 **유형:** `ApiRoute[]` Mastra는 서버를 통해 등록된 Agent와 Workflow를 자동으로 노출합니다. 추가 동작을 위해 자체 HTTP 경로를 정의할 수 있습니다. 자세한 내용은 [사용자 정의 API 경로](https://mastra.zisheng.pro/ko/docs/server/custom-api-routes) 문서를 참조하세요. ```typescript import { Mastra } from '@mastra/core' import { registerApiRoute } from '@mastra/core/server' export const mastra = new Mastra({ server: { apiRoutes: [ registerApiRoute('/my-custom-route', { method: 'GET', handler: async c => { return c.json({ message: 'Custom route' }) }, }), ], }, }) ``` ### 서버.인증 **유형:** `MastraAuthConfig | MastraAuthProvider` 서버에 대한 인증 구성입니다. Mastra는 JWT, Clerk, Supabase, Firebase, WorkOS 및 Auth0을 포함한 여러 인증 공급자를 지원합니다. 자세한 내용은 [인증 문서](https://mastra.zisheng.pro/ko/docs/server/auth)를 참조하세요. ```typescript import { Mastra } from '@mastra/core' import { MastraJwtAuth } from '@mastra/auth' export const mastra = new Mastra({ server: { auth: new MastraJwtAuth({ secret: process.env.MASTRA_JWT_SECRET, mapUserToResourceId: user => user.id, }), }, }) ``` `mapUserToResourceId` 콜백은 인증된 사용자를 Memory/스레드 범위 지정에 사용할 리소스 ID로 매핑합니다. 제공하면 인증 성공 후 호출되며, 반환된 값이 요청 컨텍스트에 `MASTRA_RESOURCE_ID_KEY`로 설정됩니다. 자세한 내용은 [권한 부여(사용자 격리)](https://mastra.zisheng.pro/ko/docs/server/middleware)를 참조하세요. ### server.bodySizeLimit **유형:** `number`\ **Default:** `4_718_592` (4.5 MB) 최대 요청 본문 크기(바이트)입니다. 애플리케이션이 더 큰 페이로드를 처리해야 하는 경우 이 제한을 늘립니다. ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { bodySizeLimit: 10 * 1024 * 1024, // 10mb }, }) ``` ### server.mcp옵션 **유형:** `object`\ **Default:** `undefined` 모든 MCP HTTP 및 SSE 경로에 적용되는 MCP 전송 옵션입니다. 이를 사용하면 지속적인 연결과 Memory 내 세션 상태를 사용할 수 없는 서버리스 환경(Cloudflare Workers, Vercel Edge, AWS Lambda 등)에 대해 상태 비저장 모드를 활성화할 수 있습니다. | 속성 | 유형 | 기본값 | 설명 | | -------------------- | -------------- | ----------- | ----------------------- | | `serverless` | `boolean` | `false` | 세션 관리 없이 무상태 모드로 MCP 실행 | | `sessionIdGenerator` | `() => string` | `undefined` | 사용자 정의 세션 ID 생성기 함수 | ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { mcpOptions: { serverless: true, }, }, }) ``` ### 서버.빌드 서버 기능에 대한 빌드 타임 구성입니다. 이러한 옵션은 로컬 개발 중에는 활성화되지만 프로덕션 환경에서는 기본적으로 비활성화되는 Swagger UI 및 요청 로깅과 같은 개발 Tool을 제어합니다. | 속성 | 유형 | 기본값 | 설명 | | ------------- | --------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `swaggerUI` | `boolean` | `false` | 대화형 API 탐색을 위해 `/swagger-ui`에서 Swagger UI 활성화(`openAPIDocs`가 `true`여야 함) | | `apiReqLogs` | `boolean` | `false` | 콘솔에 API 요청 로깅 활성화 | | `openAPIDocs` | `boolean` | `false` | `/api/openapi.json`에서 OpenAPI 명세 활성화. 기본 제공 Mastra 경로는 `servers: [{url: "/api"}]`를 사용하고, 사용자 정의 경로에는 경로별 `servers: [{url: "/"}]` 재정의가 적용됩니다. | ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { build: { swaggerUI: true, apiReqLogs: true, openAPIDocs: true, }, }, }) ``` ### 서버.cors **유형:** `CorsOptions | false` 서버의 CORS(Cross-Origin Resource Sharing) 구성입니다. CORS를 완전히 비활성화하려면 `false`로 설정하세요. 모든 경로에 하나의 정책을 적용할 때 사용합니다. 경로별 사용자 정의 정책에는 [`registerApiRoute()`](https://mastra.zisheng.pro/ko/reference/server/register-api-route)의 `cors` 옵션을 사용하세요. | 속성 | 유형 | 기본값 | 설명 | | --------------- | -------------------- | -------------------------------------------------------------------------------------- | --------------------- | | `origin` | `string \| string[]` | `'*'` | CORS 요청의 origin | | `allowMethods` | `string[]` | `['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']` | HTTP 메서드 | | `allowHeaders` | `string[]` | `['Content-Type', 'Authorization', 'x-mastra-client-type', 'x-mastra-dev-playground']` | 요청 헤더 | | `exposeHeaders` | `string[]` | `['Content-Length', 'X-Requested-With']` | 브라우저에 노출할 헤더 | | `credentials` | `boolean` | `false` | 자격 증명(쿠키, 인증 헤더) | | `maxAge` | `number` | `3600` | preflight 요청 캐시 기간(초) | ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { cors: { origin: ['https://example.com'], allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], allowHeaders: ['Content-Type', 'Authorization'], credentials: false, }, }, }) ``` ### 서버.호스트 **유형:** `string`\ **기본값:** `localhost`(또는 설정된 경우 `MASTRA_HOST` 환경 변수) Mastra 개발 서버가 바인딩되는 호스트 주소입니다. `MASTRA_HOST` 환경 변수가 설정되어 있으면 기본값보다 우선합니다. ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { host: '0.0.0.0', }, }) ``` ### 서버.https **유형:** `{ key: Buffer; cert: Buffer }` TLS를 사용해 개발 서버를 실행하기 위한 HTTPS 구성입니다. Mastra는 인증서를 자동으로 생성하고 관리하는 `mastra dev --https` 플래그를 통해 로컬 HTTPS 개발을 지원합니다. 인증서를 직접 관리하려면 자체 키 및 인증서 파일을 제공하세요. ```typescript import { Mastra } from '@mastra/core' import fs from 'node:fs' export const mastra = new Mastra({ server: { https: { key: fs.readFileSync('path/to/key.pem'), cert: fs.readFileSync('path/to/cert.pem'), }, }, }) ``` ### 서버.미들웨어 **유형:** `Middleware | Middleware[]` 경로 핸들러 전후에 요청을 가로채는 사용자 정의 미들웨어 함수입니다. 미들웨어는 인증, 로깅, 요청별 컨텍스트 삽입 또는 헤더 추가에 사용할 수 있습니다. 각 미들웨어는 Hono `Context`와 `next` 함수를 받습니다. 요청을 단락시키려면 `Response`를 반환하고, 처리를 계속하려면 `next()`를 호출하세요. 자세한 내용은 [미들웨어 문서](https://mastra.zisheng.pro/ko/docs/server/middleware)를 참조하세요. ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { middleware: [ { handler: async (c, next) => { const authHeader = c.req.header('Authorization') if (!authHeader) { return new Response('Unauthorized', { status: 401 }) } await next() }, path: '/api/*', }, ], }, }) ``` ### 서버.오류 **유형:** `(err: Error, c: Context) => Response | Promise` 처리되지 않은 오류가 발생할 때 호출되는 사용자 정의 오류 핸들러입니다. 이를 사용하여 오류 응답을 사용자 정의하고, Sentry와 같은 외부 서비스에 오류를 기록하거나, 사용자 정의 오류 형식을 구현합니다. 이 후크는 모든 서버 어댑터에서 지원됩니다. `c` 매개변수는 Hono 호환 컨텍스트 객체를 제공합니다. Hono 이외의 어댑터(Koa, Express, Fastify)에는 `c.json()` 및 `c.req.path`처럼 자주 사용하는 메서드가 포함된 shim이 제공됩니다. ```typescript import { Mastra } from '@mastra/core' import * as Sentry from '@sentry/node' export const mastra = new Mastra({ server: { onError: (err, c) => { Sentry.captureException(err) return c.json( { error: err.message, timestamp: new Date().toISOString(), }, 500, ) }, }, }) ``` ### server.onValidationError **유형:** `(error: ZodError, context: 'query' | 'body' | 'path') => { status: number; body: unknown } | undefined` 요청이 Zod 스키마 검증에 실패하면 호출되는 사용자 정의 핸들러입니다. 이를 사용하여 유효성 검사 오류 응답을 사용자 지정하고, 상태 코드를 변경하고, API 표준에 맞게 오류 형식을 지정합니다. 기본 `400` 응답을 재정의하려면 `{ status, body }` 객체를 반환하고, 기본 동작을 사용하려면 `undefined`를 반환하세요. 이 후크는 모든 서버 어댑터(Hono, Express, Fastify, Koa)에서 지원됩니다. `context` 매개변수는 요청에서 검증에 실패한 부분을 나타냅니다. - `'query'`: 쿼리 매개변수 - `'body'`: 요청 본문 - `'path'`: 경로 매개변수 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { onValidationError: (error, context) => ({ status: 422, body: { ok: false, errors: error.issues.map(i => ({ path: i.path.join('.'), message: i.message, })), source: context, }, }), }, }) ``` `createRoute()`로 생성한 개별 경로에도 `onValidationError`를 설정할 수 있습니다. 경로 수준 후크가 서버 수준 후크보다 우선합니다. ### 서버.포트 **유형:** `number`\ **기본값:** `4111`(또는 설정된 경우 `PORT` 환경 변수) Mastra 개발 서버가 바인딩되는 포트입니다. `PORT` 환경 변수가 설정되어 있으면 기본값보다 우선합니다. ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { port: 8080, }, }) ``` ### 서버.스튜디오베이스 **유형:** `string`\ **Default:** `/` [Studio](https://mastra.zisheng.pro/ko/docs/studio/overview)를 호스팅하기 위한 기준 경로입니다. 루트 대신 기존 애플리케이션의 하위 경로에서 Studio를 호스팅할 때 사용하세요. 이는 기존 애플리케이션과 통합하거나 공유 도메인의 이점을 활용하는 Cloudflare Zero Trust와 같은 인증 Tool을 사용하거나 단일 도메인에서 여러 서비스를 관리할 때 유용합니다. ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { studioBase: '/my-mastra-studio', }, }) ``` **예시 URL:** - 기본값: `http://localhost:4111/`(루트의 Studio) - `studioBase` 사용: `http://localhost:4111/my-mastra-studio/`(하위 경로의 Studio) ### 서버.시간 초과 **유형:** `number`\ **Default:** `180000` (3 minutes) 요청 제한 시간(밀리초)입니다. 이 기간을 초과하는 요청은 종료됩니다. ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { timeout: 30000, // 30 seconds }, }) ```