> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # 마스트라 클라이언트 SDK Mastra Client SDK는 사용자와 상호 작용하기 위한 간결하고 유형이 안전한 인터페이스를 제공합니다.[Mastra Server](https://mastra.zisheng.pro/ko/docs/server/mastra-server)클라이언트 환경에서. ## 전제조건 로컬 개발을 시작하기 전에 다음을 갖추십시오. - Node.js `v22.13.0` 이상 - TypeScript `v4.7` 이상(TypeScript를 사용하는 경우) - 실행 중인 로컬 Mastra 서버(일반적으로 포트 `4111`) > **노트:** Mastra Client SDK는 브라우저 환경용으로 설계되었으며, 기본 `fetch` API를 사용하여 Mastra 서버에 HTTP 요청을 보냅니다. ## 설치 Mastra Client SDK를 사용하려면 필수 종속성을 설치하십시오. **npm**: ```bash npm install @mastra/client-js@latest ``` **pnpm**: ```bash pnpm add @mastra/client-js@latest ``` **Yarn**: ```bash yarn add @mastra/client-js@latest ``` **Bun**: ```bash bun add @mastra/client-js@latest ``` ### 초기화`MastraClient` `baseUrl`로 초기화하면 `MastraClient`가 Agent, Tool 및 Workflow를 호출할 수 있는 유형 안전 인터페이스를 제공합니다. ```typescript import { MastraClient } from '@mastra/client-js' export const mastraClient = new MastraClient({ baseUrl: process.env.MASTRA_API_URL || 'http://localhost:4111', }) ``` ## 핵심 API Mastra Client SDK는 Mastra Server가 제공하는 모든 리소스를 노출합니다. - **[Agent](https://mastra.zisheng.pro/ko/reference/client-js/agents)**: 응답을 생성하고 대화를 스트리밍합니다. - **[A2A](https://mastra.zisheng.pro/ko/docs/agents/a2a)**: Agent 카드를 통해 Agent를 검색하고 작업 기반 A2A 스트림으로 작업합니다. - **[Memory](https://mastra.zisheng.pro/ko/reference/client-js/memory)**: 대화 스레드 및 메시지 기록을 관리합니다. - **[Tool](https://mastra.zisheng.pro/ko/reference/client-js/tools)**: 실행 및 관리되는 Tool입니다. - **[Workflow](https://mastra.zisheng.pro/ko/reference/client-js/workflows)**: Workflow를 트리거하고 실행을 추적합니다. - **[벡터](https://mastra.zisheng.pro/ko/reference/client-js/vectors)**: 의미론적 검색을 위해 벡터 임베딩을 사용합니다. - **[응답](https://mastra.zisheng.pro/ko/reference/client-js/responses)**: OpenAI 호환 Agent 지원 인터페이스를 통해 Mastra Agent를 응답 API로 사용합니다. 이 API는 현재 실험적입니다. - **[대화](https://mastra.zisheng.pro/ko/reference/client-js/conversations)**: Mastra Agents 뒤에 저장된 대화 스레드 및 항목 기록을 응답 API로 사용합니다. 이 API는 현재 실험적입니다. - **[로그](https://mastra.zisheng.pro/ko/reference/client-js/logs)**: 로그를 보고 시스템 동작을 디버그합니다. - **[원격 측정](https://mastra.zisheng.pro/ko/reference/client-js/telemetry)**: 앱 성능을 확인하고 활동을 추적합니다. ## 동적 Workflow 생성 및 실행 지속되는 Workflow 정의를 생성하거나 교체하려면 `upsertDynamicWorkflow()`를 사용하세요. 업서트에 성공하면 전체 정의를 검증하고, 실행 중인 Mastra 인스턴스에 등록하며, 표준 Workflow 실행 API를 통해 사용할 수 있게 합니다. 다음 예에서는 생성 및 검사부터 실행 및 삭제까지 매핑 Workflow의 전체 수명 주기를 보여줍니다. ```typescript import { MastraClient } from '@mastra/client-js' import type { UpsertDynamicWorkflowParams } from '@mastra/client-js' const client = new MastraClient({ baseUrl: process.env.MASTRA_API_URL || 'http://localhost:4111', }) const definition = { id: 'greeting-workflow', description: 'Returns a greeting for the supplied name', inputSchema: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'], }, outputSchema: { type: 'object', properties: { message: { type: 'string' } }, required: ['message'], }, graph: [ { type: 'mapping', id: 'create-greeting', mapConfig: JSON.stringify({ message: { template: 'Hello, ${initData.name}!' }, }), }, ], } satisfies UpsertDynamicWorkflowParams await client.upsertDynamicWorkflow(definition) const dynamicWorkflow = client.getDynamicWorkflow(definition.id) const dynamicDefinition = await dynamicWorkflow.details() const workflow = client.getWorkflow(dynamicDefinition.id) const run = await workflow.createRun() const result = await run.startAsync({ inputData: { name: 'Ada' } }) console.log(result) await dynamicWorkflow.delete() ``` 지속되는 정의를 나열하려면 `listDynamicWorkflows()`를 사용하세요. 동일한 `id`로 `upsertDynamicWorkflow()`를 다시 호출하면 저장된 정의와 라이브 Workflow 등록을 교체합니다. > **경고:** 내구성 있는 스토리지에는 `workflowDefinitions` 도메인을 지원하도록 구성된 스토리지 어댑터가 필요합니다. 이 도메인이 없으면 Core가 메모리에 Workflow를 등록할 수는 있지만, 서버의 동적 Workflow API가 다시 시작한 후까지 이를 유지할 수 없습니다. 저장된 정의는 선언적 Agent, Tool, 매핑, 중첩된 Workflow, 병렬, foreach, 절전, 절전 종료까지, 조건부 및 루프 항목을 지원합니다. JavaScript 클로저를 포함할 수 없습니다. 조건부 및 루프 논리는 선언적 조건자 형식을 사용해야 하며 참조된 Agent, Tool 및 중첩된 Workflow가 이미 등록되어 있어야 합니다. > > 인증된 서버에서는 정의 작업에 `stored-workflows:read` 또는 `stored-workflows:write` 권한이 필요하며, Workflow를 실행하려면 `workflows:execute` 권한이 필요합니다. ## 응답 생성 문자열 Prompt로 `.generate()`를 호출합니다. ```typescript import { mastraClient } from 'lib/mastra-client' const testAgent = async () => { try { const agent = mastraClient.getAgent('testAgent') const response = await agent.generate('Hello') console.log(response.text) } catch (error) { return 'Error occurred while generating response' } } ``` > **정보:** `role`과 `content`를 포함하는 메시지 객체 배열로 `.generate()`를 호출할 수도 있습니다. 자세한 내용은 [.generate() 레퍼런스](https://mastra.zisheng.pro/ko/reference/client-js/agents)를 참조하세요. ## 스트리밍 응답 문자열 Prompt로 실시간 응답을 받으려면 `.stream()`을 사용하세요. ```typescript import { mastraClient } from 'lib/mastra-client' const testAgent = async () => { try { const agent = mastraClient.getAgent('testAgent') const stream = await agent.stream('Hello') stream.processDataStream({ onTextPart: text => { console.log(text) }, }) } catch (error) { return 'Error occurred while generating response' } } ``` > **정보:** `role`과 `content`를 포함하는 메시지 객체 배열로 `.stream()`을 호출할 수도 있습니다. 자세한 내용은 [.stream() 레퍼런스](https://mastra.zisheng.pro/ko/reference/client-js/agents)를 참조하세요. ## 구성 옵션 `MastraClient`는 요청 동작을 제어하기 위한 `retries`, `backoffMs`, `headers` 같은 선택적 매개변수를 허용합니다. 이러한 매개변수는 재시도 동작을 제어하고 진단 메타데이터를 포함할 때 유용합니다. ```typescript import { MastraClient } from '@mastra/client-js' export const mastraClient = new MastraClient({ retries: 3, backoffMs: 300, maxBackoffMs: 5000, headers: { 'X-Development': 'true', }, }) ``` 더 많은 구성 옵션은 [MastraClient](https://mastra.zisheng.pro/ko/reference/client-js/mastra-client)를 참조하세요. ## 자격 증명 및 세션 쿠키 **세션 쿠키를 사용하여 Mastra API 호출을 인증하려면** UI와 Mastra API가 동일한 출처에 있지 않고 서로 다른 호스트, 하위 도메인 또는 포트에 있는 경우(예: 한 포트에는 Mastra Studio가 있고 다른 포트에는 사용자 지정 서버가 있는 경우), 각 요청에 로그인 후 사용자가 이미 보유한 쿠키가 포함되도록 `MastraClient`에 \*\*`credentials: 'include'`\*\*를 추가하세요. 이를 생략하면 브라우저에서 로그인에 성공했더라도 Mastra에서 **`401`** 응답을 받는 경우가 많습니다. ```typescript import { MastraClient } from '@mastra/client-js' export const mastraClient = new MastraClient({ baseUrl: process.env.MASTRA_API_URL || 'http://localhost:4111', credentials: 'include', }) ``` **서버에서 인증된 교차 출처 요청을 허용하려면** [CORS: 자격 증명이 포함된 요청](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS#requests_with_credentials)을 참조하세요. 구체적인 `Access-Control-Allow-Origin` 값(`*` 아님)과 `Access-Control-Allow-Credentials: true`가 필요합니다. 그렇지 않으면 호출이 Mastra에 도달하기 전에 브라우저가 차단합니다. **`@mastra/react`를 사용하시나요?**앱을 `MastraReactProvider`로 감싸고 서버와 일치하도록 `baseUrl` 및 `apiPrefix`를 설정한 다음 기본값인 `credentials: 'include'`를 사용하세요. `same-origin` 또는 `omit` 동작이 필요한 경우에만 `credentials`를 변경하세요. ## 요청 취소 추가 중 `MastraClient`는 표준 Node.js `AbortSignal` API를 사용한 요청 취소를 지원합니다. 사용자가 작업을 중단하거나 오래된 네트워크 호출을 정리하는 경우처럼 진행 중인 요청을 취소할 때 유용합니다. 모든 요청에서 취소 기능을 활성화하려면 클라이언트 생성자에 `AbortSignal`을 전달하세요. ```typescript import { MastraClient } from '@mastra/client-js' export const controller = new AbortController() export const mastraClient = new MastraClient({ baseUrl: process.env.MASTRA_API_URL || 'http://localhost:4111', abortSignal: controller.signal, }) ``` ### 사용하여`AbortController` `.abort()`를 호출하면 해당 신호와 연결된 진행 중인 모든 요청이 취소됩니다. ```typescript import { mastraClient, controller } from 'lib/mastra-client' const handleAbort = () => { controller.abort() } ``` ## 클라이언트 Tool `createTool()` 함수를 사용하여 클라이언트 측 애플리케이션에서 직접 Tool을 정의하세요. `.generate()` 또는 `.stream()` 호출에서 `clientTools` 매개변수를 통해 Agent에 전달하세요. 이를 통해 Agent는 DOM 조작, 로컬 저장소 액세스 또는 기타 웹 API와 같은 브라우저 측 기능을 트리거하여 서버가 아닌 사용자 환경에서 Tool을 실행할 수 있습니다. ```typescript import { createTool } from '@mastra/client-js' import { z } from 'zod' const handleClientTool = async () => { try { const agent = mastraClient.getAgent('colorAgent') const colorChangeTool = createTool({ id: 'color-change-tool', description: 'Changes the HTML background color', inputSchema: z.object({ color: z.string(), }), outputSchema: z.object({ success: z.boolean(), }), execute: async inputData => { const { color } = inputData document.body.style.backgroundColor = color return { success: true } }, }) const response = await agent.generate('Change the background to blue', { clientTools: { colorChangeTool }, }) console.log(response) } catch (error) { console.error(error) } } ``` ### 클라이언트 Tool Agent 이는 위에서 정의한 브라우저 기반 클라이언트 Tool과 함께 작동하도록 16진수 색상 코드를 반환하게 구성된 표준 Mastra [Agent](https://mastra.zisheng.pro/ko/docs/agents/overview)입니다. ```typescript import { Agent } from '@mastra/core/agent' export const colorAgent = new Agent({ id: 'color-agent', name: 'Color Agent', instructions: `You are a helpful CSS assistant. You can change the background color of web pages. Respond with a hex reference for the color requested by the user`, model: 'openai/gpt-5.6-sol', }) ``` ## 서버에서 MastraClient 사용 API 경로, 서버리스 함수 또는 액션 같은 서버 측 환경에서도 `MastraClient`를 사용할 수 있습니다. 사용법은 동일하지만 클라이언트용 응답을 다시 생성해야 할 수 있습니다. ```typescript export async function action() { const agent = mastraClient.getAgent('testAgent') const stream = await agent.stream('Hello') return new Response(stream.body) } ``` ## 모범 사례 1. **오류 처리**: 개발 시나리오에서는 [오류 처리](https://mastra.zisheng.pro/ko/reference/client-js/error-handling)를 사용합니다. 2. **환경 변수**: 구성에는 환경 변수를 사용합니다. 3. **디버깅**: 필요한 경우 상세 [로깅](https://mastra.zisheng.pro/ko/reference/client-js/logs)을 활성화합니다. 4. **성능**: 애플리케이션 성능, [텔레메트리](https://mastra.zisheng.pro/ko/reference/client-js/telemetry), Trace를 추적합니다.