본문으로 건너뛰기

MCP 개요

마스트라는 다음을 지원합니다.Model Context Protocol (MCP), AI Agent를 외부 Tool 및 리소스에 연결하기 위한 개방형 표준입니다.

MCPClient를 사용하여 MCP 서버에 연결합니다. MCPServer를 사용하여 Mastra Agent, Tool, Workflow, Prompt 및 리소스를 다른 MCP 호환 시스템에 노출합니다.

MCP 서버에 연결
MCP 서버에 연결에 대한 직접 링크

MCP 패키지를 설치합니다.

npm install @mastra/mcp@latest

로컬 명령이나 원격 URL을 사용하여 각 서버를 구성합니다.

src/mastra/mcp/client.ts
import { MCPClient } from '@mastra/mcp'

export const mcpClient = new MCPClient({
id: 'my-mcp-client',
servers: {
wikipedia: {
command: 'npx',
args: ['-y', 'wikipedia-mcp'],
},
weather: {
url: new URL('https://weather.example.com/mcp'),
requestInit: {
headers: {
Authorization: `Bearer ${process.env.WEATHER_API_KEY}`,
},
},
},
},
})
인증

OAuth로 보호된 서버에서는 authenticate()를 사용하여 브라우저 기반 인증 흐름을 완료합니다. 구성 세부 정보는 OAuth 인증을 참조하세요.

구성된 서버의 Tool을 Agent에 전달합니다.

src/mastra/agents/assistant.ts
import { Agent } from '@mastra/core/agent'
import { mcpClient } from '../mcp/client'

export const assistant = new Agent({
id: 'assistant',
name: 'Assistant',
instructions: `
Use the available MCP tools to answer questions.
Include the source of any information you retrieve.
`,
model: 'openai/gpt-5.6-sol',
tools: await mcpClient.listTools(),
})

정적 및 런타임 Tool
정적 및 런타임 Tool에 대한 직접 링크

요청 간에 서버 구성이 변경되는지 여부에 따라 Tool을 로드하는 방법을 선택합니다.

정적 Tool런타임 Tool 세트
방법await mcpClient.listTools()await mcpClient.listToolsets()
사용 사례공유되는 고정 구성사용자별 또는 요청별 구성
자격 증명모든 요청에서 공유요청마다 다르게 설정 가능
Agent APIAgent 생성자의 toolsgenerate() 또는 stream()toolsets
앞의 Agent 예에서는 정적 Tool을 사용합니다. 런타임 자격 증명의 경우 요청에 대한 클라이언트를 생성하고 Agent 호출 시 해당 Tool 세트를 전달합니다.
src/handle-request.ts
import { MCPClient } from '@mastra/mcp'
import { mastra } from './mastra'

export async function handleRequest(prompt: string, apiKey: string) {
const userMcpClient = new MCPClient({
servers: {
weather: {
url: new URL('https://weather.example.com/mcp'),
requestInit: {
headers: { Authorization: `Bearer ${apiKey}` },
},
},
},
})

const agent = mastra.getAgent('assistant')
const response = await agent.generate(prompt, {
toolsets: await userMcpClient.listToolsets(),
})

await userMcpClient.disconnect()
return response.text
}

전체 API는 listTools()listToolsets()를 참조하세요.

Tool 승인
Tool 승인에 대한 직접 링크

서버의 모든 Tool에 승인을 요구하려면 서버에 requireToolApproval을 설정하세요.

const mcpClient = new MCPClient({
servers: {
github: {
url: new URL('https://github.example.com/mcp'),
requireToolApproval: true,
},
},
})

Tool 이름, 인수 또는 주석을 기반으로 결정하는 함수를 제공할 수도 있습니다.

requireToolApproval: ({ toolName }) => toolName.startsWith('delete_')

직접 제어하지 않는 서버의 Tool 주석은 신뢰할 수 없는 힌트로 취급하세요. 콜백 컨텍스트와 보안 지침은 Tool 승인을 참조하세요.

보안
보안에 대한 직접 링크

MCP 서버는 Agent를 대신하여 코드를 실행하고 콘텐츠를 반환하므로 다른 외부 종속성과 동일한 주의를 기울여 구성합니다.

  • Stdio 하위 프로세스 환경: 하위 프로세스는 전체 부모 환경이 아니라 MCP SDK에서 선별한 환경 변수 허용 목록만 상속합니다(예: POSIX의 PATHHOME). env에 나열한 변수만 전달하려면 서버에서 inheritDefaultEnv: false를 설정하세요.
  • 아웃바운드 호스트 제한: 신뢰할 수 없는 구성에서 HTTP 서버 URL을 가져오는 경우 allowedHosts를 설정하여 클라이언트가 접속할 호스트를 제한하세요. 기본 fetch 경로에서는 리디렉션 요청이 전송되기 전에도 이를 차단합니다. 사용자 지정 fetch는 요청이 실행된 후 최종 응답 URL을 검증하므로, 아웃바운드 연결을 방지해야 한다면 자체적으로 리디렉션 정책을 적용해야 합니다.
  • Tool 응답 신뢰: Tool 결과는 신뢰할 수 없는 Model 입력입니다. 콘텐츠가 Model에 도달하기 전에 검사하거나 정제하려면 입력 및 출력 프로세서를 사용하고, 민감한 Tool에는 requireToolApproval을 설정하세요. 각 옵션의 적용 방식에 대한 자세한 내용은 MCPClient 보안 참고 문서를 참조하세요.

MCP 레지스트리
MCP 레지스트리에 대한 직접 링크

레지스트리는 호스팅되거나 패키지된 MCP 서버를 제공합니다. 위의 클라이언트 구성은 레지스트리 끝점 및 명령과 함께 작동합니다.

레지스트리연결참고
Klavis AI호스팅 HTTP엔터프라이즈 인증 및 관리형 서버
mcp.run서명된 SSE URL프로필 URL을 비밀 정보로 취급하세요.
Composio호스팅 SSE URLURL은 특정 사용자 계정에 연결되는 경우가 많습니다.
SmitheryCLI 또는 호스팅 URLnpx를 통해 로컬 패키지를 실행합니다.
Apify호스팅 HTTPApify API 토큰으로 인증합니다.
AmpersandSSE 또는 stdio구성된 SaaS 통합에 연결합니다.
서명된 URL, API 키, 토큰을 환경 변수에 저장합니다. 각 서버에 대한 끝점, 명령 및 자격 증명을 얻으려면 레지스트리 설명서를 따르십시오.

Mastra MCP 서버 노출
Mastra MCP 서버 노출에 대한 직접 링크

외부 MCP 클라이언트에 Mastra 기본 요소를 노출하려면 MCPServer를 생성하세요.

src/mastra/mcp/server.ts
import { MCPServer } from '@mastra/mcp'
import { assistant } from '../agents/assistant'
import { weatherTool } from '../tools/weather'
import { weatherWorkflow } from '../workflows/weather'

export const mcpServer = new MCPServer({
id: 'my-mcp-server',
name: 'My MCP Server',
version: '1.0.0',
agents: { assistant },
tools: { weatherTool },
workflows: { weatherWorkflow },
})

메인에 서버를 등록하세요Mastra instance:

src/mastra/index.ts
import { Mastra } from '@mastra/core/mastra'
import { mcpServer } from './mcp/server'

export const mastra = new Mastra({
mcpServers: { mcpServer },
})
인증

OAuth 미들웨어로 HTTP MCP 서버를 보호하세요. 설정 방법은 OAuth 보호를 참조하세요.

Prompt, 리소스, 전송 방식 및 기타 서버 옵션은 MCPServer 참고 문서를 참조하세요.

MCP 앱 구축
MCP 앱 구축에 대한 직접 링크

MCP Apps 확장을 사용하면 MCP Tool이 ui:// 리소스를 통해 대화형 HTML 인터페이스를 제공할 수 있습니다. Mastra Studio는 Tool 페이지와 Agent 채팅의 Sandbox 처리된 iframe에서 이러한 앱을 렌더링합니다. 양식, 계산기, 색상 선택기 또는 데이터 시각화와 같은 상호 작용을 통해 Tool 결과가 도움이 되는 경우 MCP 앱을 사용하십시오.

앱 리소스 정의
앱 리소스 정의에 대한 직접 링크

Model에는 간단한 content 요약을 반환하고 UI 데이터는 structuredContent에 넣으세요. _meta.ui.resourceUriappResources에 사용한 것과 동일한 ui:// URI로 설정하여 Tool을 앱에 연결합니다.

src/mastra/mcp/calculator.ts
import { MCPServer } from '@mastra/mcp'
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'

export const calculatorTool = createTool({
id: 'calculatorWithUI',
description: 'Calculate the sum of two numbers',
inputSchema: z.object({
num1: z.number(),
num2: z.number(),
}),
execute: async ({ num1, num2 }) => ({
content: [{ type: 'text', text: 'The result is displayed in the calculator app.' }],
structuredContent: { result: num1 + num2 },
}),
})

calculatorTool._meta = {
ui: { resourceUri: 'ui://calculator/main' },
}

export const calculatorMcpServer = new MCPServer({
id: 'calculator-app-server',
name: 'Calculator App Server',
version: '1.0.0',
tools: { calculatorTool },
appResources: {
'ui://calculator/main': {
name: 'Calculator',
htmlPath: './src/mastra/mcp/calculator.html',
},
},
})

Model은 content를 확인하고 앱은 structuredContent를 수신합니다. 인라인 HTML, 파일 경로, 메타데이터 및 콘텐츠 보안 정책 옵션은 appResources를 참조하세요.

Studio에 앱 연결
Studio에 앱 연결에 대한 직접 링크

HTML 리소스 안에서 @modelcontextprotocol/ext-appsApp 클래스를 사용하세요. connect()를 호출하기 전에 이벤트 핸들러를 등록합니다.

src/mastra/mcp/calculator.html
<!doctype html>
<html>
<body>
<p id="result">Waiting for input</p>
<button id="recalculate">Recalculate</button>

<script type="module">
import { App } from 'https://cdn.jsdelivr.net/npm/@modelcontextprotocol/ext-apps/+esm'

const app = new App({ name: 'Calculator', version: '1.0.0' })
let toolInput

app.ontoolinput = params => {
toolInput = params.arguments
}

document.querySelector('#recalculate').addEventListener('click', async () => {
const result = await app.callServerTool({
name: 'calculatorWithUI',
arguments: toolInput,
})
document.querySelector('#result').textContent = JSON.stringify(result)

await app.sendMessage({
role: 'user',
content: [{ type: 'text', text: 'Explain the recalculated result.' }],
})
})

await app.connect()
</script>
</body>
</html>

게스트 측 API는 상호 작용의 다양한 부분을 제공합니다.

API목적
app.ontoolinput호스트 Tool 호출의 인수를 수신합니다.
app.callServerTool()iframe 내부에서 MCP Tool을 호출합니다.
app.sendMessage()채팅에 사용자 메시지를 추가하고 새 Model 턴을 시작합니다.
app.connect()이벤트 핸들러를 등록한 후 호스트에 연결합니다.
상호작용은 다음 순서를 따릅니다.
  1. Agent가 Tool을 호출합니다.
  2. Tool이 Model용 content와 UI용 structuredContent를 반환합니다.
  3. Studio가 연결된 앱 리소스를 렌더링합니다.
  4. 앱은 Tool 입력을 수신하고 서버 Tool을 호출하거나 채팅 메시지를 보낼 수 있습니다. 게스트 측의 모든 메서드와 수명 주기 훅은 외부 App API 참고 문서를 참조하세요.

MCP 앱 등록
MCP 앱 등록에 대한 직접 링크

로컬 앱의 경우 Tool을 Agent에 전달하고 해당 MCP 서버를 Agent에 등록하세요.Mastra:

src/mastra/index.ts
import { Agent } from '@mastra/core/agent'
import { Mastra } from '@mastra/core/mastra'
import { calculatorMcpServer, calculatorTool } from './mcp/calculator'

const calculatorAgent = new Agent({
id: 'calculator-agent',
name: 'Calculator Agent',
instructions: 'Use the calculator tool for arithmetic.',
model: 'openai/gpt-5-mini',
tools: { calculatorTool },
})

export const mastra = new Mastra({
agents: { calculatorAgent },
mcpServers: { calculatorMcpServer },
})

MCP 앱을 구현하는 외부 MCP 서버에서는 MCPClient.listTools()를 사용하여 Tool을 로드하고, Studio가 원격 앱 리소스를 확인할 수 있도록 해당 프록시를 등록하세요.

src/mastra/remote-apps.ts
import { Agent } from '@mastra/core/agent'
import { Mastra } from '@mastra/core/mastra'
import { mcpClient } from './mcp/client'

const tools = await mcpClient.listTools()
const mcpServers = mcpClient.toMCPServerProxies()

const agent = new Agent({
id: 'remote-app-agent',
name: 'Remote App Agent',
instructions: 'Use the available remote tools.',
model: 'openai/gpt-5-mini',
tools,
})

export const mastra = new Mastra({
agents: { agent },
mcpServers,
})

listTools()를 통해 로드된 Tool은 _meta.uiserverId를 포함하므로 Studio가 모든 서버를 검색하지 않고도 각 앱 리소스를 확인할 수 있습니다. 프록시 구성 세부 정보는 toMCPServerProxies()를 참조하세요.

샌드박스 보안
샌드박스 보안에 대한 직접 링크

Mastra Studio는 @mcp-ui/client를 사용하여 Sandbox 프록시를 통해 앱 HTML을 로드하고 postMessage로 JSON-RPC 통신을 수행합니다. 앱 iframe은 스크립트, 양식 및 팝업을 허용합니다. 상위 페이지의 DOM, 쿠키 또는 저장소에 액세스할 수 없습니다. 호스트는 게스트 앱과의 모든 통신을 제어합니다.

다음 단계
다음 단계에 대한 직접 링크