> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # 익스프레스 어댑터 그만큼`@mastra/express`패키지는 Mastra를 실행하기 위한 서버 어댑터를 제공합니다.[표현하다](https://expressjs.com). 일반적인 어댑터 개념(생성자 옵션, 초기화 흐름 등)은 다음을 참조하세요.[서버 어댑터](https://mastra.zisheng.pro/ko/docs/server/server-adapters). ## 설치 Express 어댑터 및 Express 프레임워크를 설치합니다. **npm**: ```bash npm install @mastra/express@latest express ``` **pnpm**: ```bash pnpm add @mastra/express@latest express ``` **Yarn**: ```bash yarn add @mastra/express@latest express ``` **Bun**: ```bash bun add @mastra/express@latest express ``` ## 사용예 ```typescript import express from 'express' import { MastraServer } from '@mastra/express' import { mastra } from './mastra' const app = express() app.use(express.json()) // Required for body parsing const server = new MastraServer({ app, mastra }) await server.init() app.listen(4111, () => { console.log('Server running on port 4111') }) ``` > **노트:** Express에서 JSON 본문을 파싱하려면 `express.json()` 미들웨어가 필요합니다. `MastraServer`를 생성하기 전에 추가하세요. ## 생성자 매개변수 **app** (`Application`): Express 앱 인스턴스 **mastra** (`Mastra`): Mastra 인스턴스 **prefix** (`string`): 경로 경로 접두사(예: /api/v2) (Default: `''`) **openapiPath** (`string`): OpenAPI 명세를 제공할 경로(예: /openapi.json) (Default: `''`) **bodyLimitOptions** (`{ maxSize: number, onError: (err) => unknown }`): 요청 본문 크기 제한 **streamOptions** (`{ redact?: boolean }`): 스트림 마스킹 구성입니다. true이면 스트림에서 민감한 데이터를 마스킹합니다. (Default: `{ redact: true }`) **customRouteAuthConfig** (`Map`): 경로별 인증 재정의입니다. 키는 METHOD:PATH 형식입니다(예: GET:/api/health). 값이 false이면 경로가 공개되고, true이면 인증이 필요합니다. **tools** (`Record`): 서버에서 사용할 수 있는 Tool **taskStore** (`InMemoryTaskStore`): A2A(Agent-to-Agent) 작업을 위한 작업 저장소 **mcpOptions** (`MCPOptions`): MCP 전송 옵션입니다. Cloudflare Workers 또는 Vercel Edge 같은 상태 비저장 환경에서는 serverless: true로 설정하세요. ## 호노와의 차이점 | 측면 | Express | Hono | | --------- | --------------------------- | --------------------- | | 본문 파싱 | `express.json()` 필요 | 프레임워크에서 처리 | | 컨텍스트 저장소 | `res.locals` | `c.get()` / `c.set()` | | 미들웨어 시그니처 | `(req, res, next)` | `(c, next)` | | 스트리밍 | `res.write()` / `res.end()` | `stream()` 도우미 | | 중단 신호 | `req.on('close')`에서 생성 | `c.req.raw.signal` | ## 커스텀 경로 추가 Express 앱에 직접 경로를 추가하세요. ```typescript const app = express() app.use(express.json()) const server = new MastraServer({ app, mastra }) // Before init - runs before Mastra middleware app.get('/early-health', (req, res) => res.json({ status: 'ok' })) await server.init() // After init - has access to Mastra context app.get('/custom', (req, res) => { const mastraInstance = res.locals.mastra res.json({ agents: Object.keys(mastraInstance.listAgents()) }) }) app.listen(4111) ``` > **팁:** `init()` 전에 추가된 경로는 Mastra 컨텍스트 없이 실행됩니다. Mastra 인스턴스와 요청 컨텍스트에 접근하려면 `init()` 후에 경로를 추가하세요. `requiresAuth` 같은 Mastra 관리 인증 및 경로 메타데이터가 필요하다면 [`registerApiRoute()`](https://mastra.zisheng.pro/ko/reference/server/register-api-route)를 사용하는 것이 좋습니다. `app`에 직접 마운트된 원시 Express 경로에는 `createAuthMiddleware()`를 사용하세요. ```typescript import express from 'express' import { createAuthMiddleware, 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.get('/custom/protected', createAuthMiddleware({ mastra }), (req, res) => { const user = res.locals.requestContext.get('user') res.json({ user }) }) app.get('/custom/public', createAuthMiddleware({ mastra, requiresAuth: false }), (req, res) => { res.json({ ok: true }) }) ``` ## 컨텍스트에 액세스 Express 미들웨어 및 경로에서 다음을 통해 Mastra 컨텍스트에 액세스합니다.`res.locals`: ```typescript app.get('/custom', (req, res) => { const mastra = res.locals.mastra const requestContext = res.locals.requestContext const abortSignal = res.locals.abortSignal const agent = mastra.getAgent('myAgent') res.json({ agent: agent.name }) }) ``` 사용 가능한 속성`res.locals`: | 키 | 설명 | | ----------------------- | ------------------- | | `mastra` | Mastra 인스턴스 | | `requestContext` | 요청 컨텍스트 맵 | | `abortSignal` | 요청 취소 신호 | | `tools` | 사용 가능한 Tool | | `taskStore` | A2A 작업용 작업 저장소 | | `customRouteAuthConfig` | 경로별 인증 재정의 | | `user` | 인증된 사용자(인증이 구성된 경우) | ## 미들웨어 추가 이전 또는 이후에 Express 미들웨어 추가`init()`: ```typescript const app = express() app.use(express.json()) // Middleware before init app.use((req, res, next) => { console.log(`${req.method} ${req.url}`) next() }) const server = new MastraServer({ app, mastra }) await server.init() // Middleware after init has access to Mastra context app.use((req, res, next) => { const mastra = res.locals.mastra next() }) ``` ## 수동 초기화 사용자 정의 미들웨어 순서가 필요하다면 `init()` 대신 각 메서드를 개별적으로 호출하세요. 자세한 내용은 [수동 초기화](https://mastra.zisheng.pro/ko/docs/server/server-adapters)를 참조하세요. ## 예 - [익스프레스 어댑터](https://github.com/mastra-ai/mastra/tree/main/examples/server-express-adapter): 기본 Express 서버 설정 ## 관련된 - [서버 어댑터](https://mastra.zisheng.pro/ko/docs/server/server-adapters): 공유 어댑터 개념 - [Mastra서버 참조](https://mastra.zisheng.pro/ko/reference/server/mastra-server): 전체 API 참조 - [createRoute() 참조](https://mastra.zisheng.pro/ko/reference/server/create-route): 유형이 안전한 사용자 지정 경로 만들기