> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # 서버 어댑터 서버 어댑터를 사용하면 생성된 Hono 서버 대신 자체 HTTP 서버로 Mastra를 실행할 수 있습니다.`mastra build`. 사용자 정의 미들웨어 순서, 인증, 로깅 및 배포 구성을 포함하여 서버 설정에 대한 더 많은 제어를 제공합니다. Agent나 Workflow가 실행되는 방식을 변경하지 않고도 Mastra를 Node.js 애플리케이션에 통합할 수 있습니다. > **경고:** 서버 어댑터는 다음을 사용합니다.`mastra` 전달한 인스턴스를 사용하며 파일 기반 탐색을 실행하지 않습니다. 코드에서 해당 인스턴스에 Agent를 등록하세요. 파일 기반 Agent를 사용하려면 Mastra를 별도 서버로 실행하고 `mastra dev` or `mastra build`. ## 서버 어댑터를 사용하는 경우 - Mastra의 엔드포인트가 기존 애플리케이션에 자동으로 추가되기를 원합니다. - 사용자 정의 구성을 위해서는 서버 인스턴스에 직접 액세스해야 합니다. - 귀하의 팀은 다음에서 만든 Hono 서버 대신 다른 서버 프레임워크를 사용하는 것을 선호합니다.`mastra build`. > **팁:** 사용자 지정 서버 요구 사항이 없는 배포의 경우 다음을 사용합니다.`mastra build` 대신 사용하세요. 서버 설정을 구성하고 미들웨어를 등록하며 프로젝트 구성에 따라 배포 설정도 적용합니다. [Server Configuration](https://mastra.zisheng.pro/ko/docs/server/mastra-server). > > 사용하고 싶다면[Studio](https://mastra.zisheng.pro/ko/docs/studio/overview) with your server adapter, use [`mastra studio`](https://mastra.zisheng.pro/ko/reference/cli/mastra) to only launch the Studio UI. ## 사용 가능한 어댑터 Mastra는 현재 다음과 같은 공식 서버 어댑터를 제공합니다. - [@마스트라/익스프레스](https://mastra.zisheng.pro/ko/reference/server/express-adapter) - [@마스트라/호노](https://mastra.zisheng.pro/ko/reference/server/hono-adapter) - [@mastra/fastify](https://mastra.zisheng.pro/ko/reference/server/fastify-adapter) - [@마스트라/코아](https://mastra.zisheng.pro/ko/reference/server/koa-adapter) - [@mastra/nestjs](https://mastra.zisheng.pro/ko/reference/server/nestjs-adapter) 자신만의 어댑터를 만들 수 있습니다.[custom adapters](https://mastra.zisheng.pro/ko/docs/server/custom-adapters) for details. ## 설치 선택한 프레임워크에 맞는 어댑터를 설치하세요. **Express**: **npm**: ```bash npm install @mastra/express@latest ``` **pnpm**: ```bash pnpm add @mastra/express@latest ``` **Yarn**: ```bash yarn add @mastra/express@latest ``` **Bun**: ```bash bun add @mastra/express@latest ``` **Hono**: ```bash npm install @mastra/express@latest ``` **Fastify**: ```bash pnpm add @mastra/express@latest ``` **Koa**: ```bash yarn add @mastra/express@latest ``` **NestJS**: ```bash bun add @mastra/express@latest ``` **Tab 6**: **npm**: ```bash npm install @mastra/hono@latest ``` **pnpm**: ```bash pnpm add @mastra/hono@latest ``` **Yarn**: ```bash yarn add @mastra/hono@latest ``` **Bun**: ```bash bun add @mastra/hono@latest ``` **Tab 7**: ```bash npm install @mastra/hono@latest ``` **Tab 8**: ```bash pnpm add @mastra/hono@latest ``` **Tab 9**: ```bash yarn add @mastra/hono@latest ``` **Tab 10**: ```bash bun add @mastra/hono@latest ``` **Tab 11**: **npm**: ```bash npm install @mastra/fastify@latest ``` **pnpm**: ```bash pnpm add @mastra/fastify@latest ``` **Yarn**: ```bash yarn add @mastra/fastify@latest ``` **Bun**: ```bash bun add @mastra/fastify@latest ``` **Tab 12**: ```bash npm install @mastra/fastify@latest ``` **Tab 13**: ```bash pnpm add @mastra/fastify@latest ``` **Tab 14**: ```bash yarn add @mastra/fastify@latest ``` **Tab 15**: ```bash bun add @mastra/fastify@latest ``` **Tab 16**: **npm**: ```bash npm install @mastra/koa@latest ``` **pnpm**: ```bash pnpm add @mastra/koa@latest ``` **Yarn**: ```bash yarn add @mastra/koa@latest ``` **Bun**: ```bash bun add @mastra/koa@latest ``` **Tab 17**: ```bash npm install @mastra/koa@latest ``` **Tab 18**: ```bash pnpm add @mastra/koa@latest ``` **Tab 19**: ```bash yarn add @mastra/koa@latest ``` **Tab 20**: ```bash bun add @mastra/koa@latest ``` **Tab 21**: **npm**: ```bash npm install @mastra/nestjs@latest ``` **pnpm**: ```bash pnpm add @mastra/nestjs@latest ``` **Yarn**: ```bash yarn add @mastra/nestjs@latest ``` **Bun**: ```bash bun add @mastra/nestjs@latest ``` **Tab 22**: ```bash npm install @mastra/nestjs@latest ``` **Tab 23**: ```bash pnpm add @mastra/nestjs@latest ``` **Tab 24**: ```bash yarn add @mastra/nestjs@latest ``` **Tab 25**: ```bash bun add @mastra/nestjs@latest ``` ## 구성 평소처럼 앱을 초기화한 다음`MastraServer` by passing in the `app` and your main `mastra` instance from `src/mastra/index.ts`. Calling `init()` Mastra 미들웨어와 사용 가능한 모든 엔드포인트를 자동으로 등록합니다. 이전이나 이후 어느 위치에서든 평소처럼 자체 라우트를 계속 추가할 수 있습니다. `init()`, and they’ll run alongside Mastra’s endpoints. **Express**: ```typescript import express from 'express' import { MastraServer } from '@mastra/express' import { mastra } from './mastra' const app = express() app.use(express.json()) const server = new MastraServer({ app, mastra }) await server.init() app.listen(4111, () => { console.log('Server running on port 4111') }) ``` 참조[Express Adapter](https://mastra.zisheng.pro/ko/reference/server/express-adapter) documentation for full configuration options. **Hono**: ```typescript import { Hono } from 'hono' import { serve } from '@hono/node-server' import { HonoBindings, HonoVariables, MastraServer } from '@mastra/hono' import { mastra } from './mastra' const app = new Hono<{ Bindings: HonoBindings; Variables: HonoVariables }>() const server = new MastraServer({ app, mastra }) await server.init() serve({ fetch: app.fetch, port: 4111 }, () => { console.log('Server running on port 4111') }) ``` 참조[Hono Adapter](https://mastra.zisheng.pro/ko/reference/server/hono-adapter) documentation for full configuration options. **Fastify**: ```typescript import Fastify from 'fastify' import { MastraServer } from '@mastra/fastify' import { mastra } from './mastra' const app = Fastify() const server = new MastraServer({ app, mastra }) await server.init() app.get('/health', async request => { const mastraInstance = request.mastra const agents = Object.keys(mastraInstance.listAgents()) return { status: 'ok', agents } }) const port = 4111 app.listen({ port }, () => { console.log(`Server running on http://localhost:${port}`) console.log(`Try: curl http://localhost:${port}/api/agents`) }) ``` 참조[Fastify Adapter](https://mastra.zisheng.pro/ko/reference/server/fastify-adapter) documentation for full configuration options. **Koa**: ```typescript import Koa from 'koa' import bodyParser from 'koa-bodyparser' import { MastraServer } from '@mastra/koa' import { mastra } from './mastra' const app = new Koa() app.use(bodyParser()) // Required for body parsing const server = new MastraServer({ app, mastra }) await server.init() app.use(async (ctx, next) => { if (ctx.path === '/health' && ctx.method === 'GET') { const mastraInstance = ctx.state.mastra const agents = Object.keys(mastraInstance.listAgents()) ctx.body = { status: 'ok', agents } return } await next() }) const port = 4111 app.listen(port, () => { console.log(`Server running on http://localhost:${port}`) console.log(`Try: curl http://localhost:${port}/api/agents`) }) ``` 참조[Koa Adapter](https://mastra.zisheng.pro/ko/reference/server/koa-adapter) documentation for full configuration options. **NestJS**: ```typescript import { Module } from '@nestjs/common' import { MastraModule } from '@mastra/nestjs' import { mastra } from './mastra' @Module({ imports: [ MastraModule.register({ mastra, }), ], }) export class AppModule {} ``` ```typescript import { NestFactory } from '@nestjs/core' import { AppModule } from './app.module' async function bootstrap() { const app = await NestFactory.create(AppModule) await app.listen(3000) } bootstrap() ``` 참조[NestJS Adapter](https://mastra.zisheng.pro/ko/reference/server/nestjs-adapter) documentation for full configuration options. ## 초기화 흐름 부름`init()` 세 단계를 순서대로 실행합니다. 이 흐름을 이해하면 특정 지점에 자체 미들웨어를 삽입해야 할 때 도움이 됩니다. 1. `registerContextMiddleware()`: 모든 요청에 ​​Mastra 인스턴스, 요청 컨텍스트, Tool 및 중단 신호를 연결합니다. 이를 통해 모든 후속 미들웨어 및 경로 처리기에서 Mastra를 사용할 수 있습니다. 2. `registerAuthMiddleware()`: 초기화 중에 어댑터 인증 후크를 실행합니다. 공식 어댑터는 Mastra가 내장 경로를 등록할 때 인라인 인증을 시행하고`registerApiRoute()` 라우트이므로 원시 프레임워크 라우트에서는 어댑터가 내보내는 `createAuthMiddleware()` helper when they need Mastra auth. 3. `registerRoutes()`: Agent, Workflow 및 기타 기능에 대한 모든 Mastra API 경로를 등록합니다. MCP 서버가 구성된 경우 MCP 경로도 등록합니다. ### 수동 초기화 사용자 정의 미들웨어 주문의 경우 대신 각 메소드를 개별적으로 호출하십시오.`init()`. Mastra 컨텍스트가 설정되기 전에 실행되는 미들웨어가 필요하거나 초기화 단계 사이에 로직을 삽입해야 할 때 유용합니다. ```typescript const server = new MastraServer({ app, mastra }); // Your middleware first app.use(loggingMiddleware); server.registerContextMiddleware(); // Middleware that needs Mastra context app.use(customMiddleware); await server.registerRoutes(); // Routes after Mastra app.get('/health', ...); ``` > **팁:** Mastra의 컨텍스트를 사용할 수 있기 전에 실행되는 미들웨어가 필요하거나 컨텍스트와 인증 단계 사이에 미들웨어를 삽입해야 하는 경우 수동 초기화를 사용하세요. ## 커스텀 경로 추가 Mastra의 경로와 함께 앱에 자신의 경로를 추가할 수 있습니다. - 추가된 경로**before** `init()` won't have Mastra context available. - 추가된 경로**after** `init()` Mastra 컨텍스트(Mastra 인스턴스, 요청 컨텍스트, 인증된 사용자 등)에 접근할 수 있습니다. - 다음과 같은 Mastra 관리 인증 및 경로 메타데이터를 원하는 경우`requiresAuth`, prefer `registerApiRoute()`. - 프레임워크 앱에 경로를 직접 마운트하는 경우 어댑터의 내보낸 경로를 사용하세요.`createAuthMiddleware()` helper if those routes need Mastra auth. 자세한 내용은 '맞춤 경로 추가'를 참조하세요.[Express](https://mastra.zisheng.pro/ko/reference/server/express-adapter) and [Hono](https://mastra.zisheng.pro/ko/reference/server/hono-adapter) for more information. ## 경로 접두사 기본적으로 Mastra 경로는 다음 위치에 등록됩니다.`/api/agents`, `/api/workflows`, etc. Use the `prefix` 옵션을 사용해 이를 변경할 수 있습니다. API 버전 관리가 필요하거나 자체 `/api` routes. ```typescript const server = new MastraServer({ app, mastra, prefix: '/api/v2', }) ``` 이 접두사를 사용하면 Mastra 경로는 다음과 같습니다.`/api/v2/agents`, `/api/v2/workflows`등이 있는 기존 앱과 통합할 때 유용합니다. 앱에 직접 추가한 사용자 지정 라우트에는 이 접두사가 적용되지 않습니다. ## OpenAPI 사양 Mastra는 등록된 모든 경로에 대해 OpenAPI 사양을 생성할 수 있습니다. 이는 문서화, 클라이언트 생성 또는 API Tool와의 통합에 유용합니다. 설정하여 활성화합니다.`openapiPath` option: ```typescript const server = new MastraServer({ app, mastra, openapiPath: '/openapi.json', }) ``` 사양은 각 경로에 정의된 Zod 스키마에서 생성되고 지정된 경로에서 제공됩니다. 여기에는 모든 Mastra 경로와 다음으로 생성된 모든 사용자 지정 경로가 포함됩니다.`createRoute()`. ## 스트림 데이터 수정 스트리밍 Agent가 HTTP를 통해 응답할 때 HTTP 스트리밍 계층은 스트림 청크에서 중요한 정보를 클라이언트에 보내기 전에 수정합니다. 이렇게 하면 다음에 대한 우발적인 노출을 방지할 수 있습니다. - 시스템 Prompt 및 Agent 지침 - Tool 정의 및 해당 매개변수 - 요청 본문의 API 키 및 기타 자격 증명 - 내부 구성 데이터 이 수정은 HTTP 경계에서 발생하므로 다음과 같은 내부 콜백은`onStepFinish` 디버깅 및 Observability 목적으로 전체 요청 데이터에 계속 접근할 수 있습니다. 기본적으로 수정은 활성화되어 있습니다. 다음을 통해 이 동작을 구성하세요.`streamOptions`. Set `redact: false` 스트림 응답에서 전체 요청 데이터에 접근해야 하는 내부 서비스 또는 디버깅 시나리오에서만 사용하세요. ```typescript const server = new MastraServer({ app, mastra, streamOptions: { redact: true, // Default }, }) ``` 보다[MastraServer](https://mastra.zisheng.pro/ko/reference/server/mastra-server) for full configuration options. ## 경로별 인증 재정의 Mastra 인스턴스에 인증이 구성되면 기본적으로 모든 경로에 인증이 필요합니다. 때로는 예외가 필요할 수도 있습니다. 즉, 공개 상태 확인 엔드포인트나 웹훅 수신기 또는 더 엄격한 제어가 필요한 관리 경로가 필요합니다. 사용`customRouteAuthConfig` 특정 라우트의 인증 동작을 재정의하는 데 사용합니다. 키는 `METHOD:PATH` where method is `GET`, `POST`, `PUT`, `DELETE`, or `ALL`. Paths support wildcards (`*`) 형식을 따르며 여러 라우트를 일치시킬 수 있습니다. 값을 `false` makes the route public, while `true` requires authentication. ```typescript const server = new MastraServer({ app, mastra, customRouteAuthConfig: new Map([ // Public health check ['GET:/api/health', false], // Public API spec ['GET:/api/openapi.json', false], // Public webhook endpoints ['POST:/api/webhooks/*', false], // Require auth even if globally disabled ['POST:/api/admin/reset', true], // Protect all methods on internal routes ['ALL:/api/internal/*', true], ]), }) ``` 보다[MastraServer](https://mastra.zisheng.pro/ko/reference/server/mastra-server) for full configuration options. ## 앱에 액세스하기 어댑터를 만든 후에도 여전히 기본 프레임워크 앱에 액세스해야 할 수 있습니다. 이는 플랫폼에 전달할 때 유용합니다.`serve` 함수에서 또는 다른 모듈의 라우트를 추가할 때 사용합니다. ```typescript // Via the MastraServer instance const app = server.getApp() // Via the Mastra instance (available after adapter construction) const app = mastra.getServerApp() ``` 두 메서드 모두 동일한 앱 인스턴스를 반환합니다. 범위에 따라 더 편리한 것을 사용하세요. ## 서버 구성과 어댑터 옵션 서버 어댑터를 사용할 때 구성은 두 위치에서 이루어집니다.`server` config (passed to the `Mastra` 생성자)와 어댑터 생성자 옵션입니다. 어떤 옵션이 어디에서 제공되는지 이해하면 설정이 적용되지 않는 것처럼 보일 때 혼동을 줄일 수 있습니다. ### 어댑터에서 사용됨 어댑터는 다음에서 이러한 설정을 읽습니다.`mastra.getServer()`: | 옵션 | 설명 | | --------------- | --------------------------------------------------------------------------------------------------------------------------- | | `auth` | Authentication config, used by `registerAuthMiddleware()`. | | `bodySizeLimit` | 기본 요청 본문 크기 제한(바이트)입니다. 어댑터별로 `bodyLimitOptions`. | | `onError` | 라우트 핸들러에서 처리되지 않은 오류가 발생할 때 호출되는 사용자 지정 오류 핸들러입니다. [server.onError](https://mastra.zisheng.pro/ko/reference/configuration). | ### 어댑터 생성자만 이러한 옵션은 어댑터 생성자에 직접 전달되며 Mastra 구성에서 읽혀지지 않습니다. | 옵션 | 설명 | | ----------------------- | --------------------------------------------------------------------------- | | `prefix` | Route path prefix | | `openapiPath` | OpenAPI spec endpoint | | `bodyLimitOptions` | Body size limit with custom error handler | | `streamOptions` | Stream redaction settings | | `customRouteAuthConfig` | Per-route auth overrides | | `mcpOptions` | MCP transport options (e.g., `serverless: true` for stateless environments) | ### 어댑터에서는 사용되지 않음 이것들`server` config options are only used by `mastra build` 에서만 사용되며 어댑터를 직접 사용할 때는 아무런 효과가 없습니다: | 옵션 | 사용하는 사람 | | -------------- | --------------------------------------- | | `port`, `host` | `mastra dev`, `mastra build` | | `cors` | `mastra build` adds CORS middleware | | `timeout` | `mastra build` | | `apiRoutes` | `registerApiRoute()` for `mastra build` | | `middleware` | Middleware config for `mastra build` | 어댑터를 사용할 때 프레임워크를 사용하여 이러한 기능을 직접 구성하세요. 예를 들어 Hono 또는 Express의 내장 CORS 패키지를 사용하여 CORS 미들웨어를 추가하고 프레임워크의 수신 기능을 호출할 때 포트를 설정하세요. ## MCP 지원 서버 어댑터는 MCP(Model 컨텍스트 프로토콜) 경로를 등록합니다.`registerRoutes()` Mastra 인스턴스에 MCP 서버가 구성되어 있을 때 사용됩니다. MCP를 통해 외부 Tool과 서비스가 Mastra 서버에 연결되어 Agent와 상호작용할 수 있습니다. 어댑터는 HTTP 및 SSE(서버 전송 이벤트) 전송에 대한 경로를 등록하여 다양한 클라이언트 연결 패턴을 활성화합니다. ### 서버리스 모드 Cloudflare Workers 또는 Vercel Edge와 같은 서버리스 환경의 경우 다음을 통해 상태 비저장 모드를 활성화하세요.`mcpOptions`. Mastra 배포자(표준`mastra dev` / `mastra build` path), set `mcpOptions` in your server config: ```typescript const mastra = new Mastra({ server: { mcpOptions: { serverless: true, }, }, }) ``` 서버 어댑터를 수동으로 생성하는 경우 다음을 통과하십시오.`mcpOptions` directly: ```typescript const server = new MastraServer({ app, mastra, mcpOptions: { serverless: true, }, }) ``` 언제`serverless: true`, MCP HTTP 요청은 세션 관리 없이 실행되므로 상태 비저장 실행 환경과 호환됩니다. 보다[MCP](https://mastra.zisheng.pro/ko/docs/mcp/overview) 에서 구성 세부 정보와 MCP 서버 설정 방법을 확인하세요. ## 관련된 - [호노 어댑터](https://mastra.zisheng.pro/ko/reference/server/hono-adapter)- Hono 전용 설정 - [익스프레스 어댑터](https://mastra.zisheng.pro/ko/reference/server/express-adapter)- Express 전용 설정 - [NestJS 어댑터](https://mastra.zisheng.pro/ko/reference/server/nestjs-adapter)- NestJS 관련 설정 - [맞춤형 어댑터](https://mastra.zisheng.pro/ko/docs/server/custom-adapters)- 다른 프레임워크용 어댑터 빌드 - [서버 구성](https://mastra.zisheng.pro/ko/docs/server/mastra-server)- 사용`mastra build` instead - [입증](https://mastra.zisheng.pro/ko/docs/server/auth)- 서버에 대한 인증 구성 - [Mastra서버 참조](https://mastra.zisheng.pro/ko/reference/server/mastra-server)- 전체 API 참조 - [createRoute() 참조](https://mastra.zisheng.pro/ko/reference/server/create-route)- 유형이 안전한 사용자 지정 경로 만들기