
How do I connect Mastra to MCP tools (MCPClient) and handle OAuth/authenticated MCP servers?
Most teams hit the same wall with MCP: you can connect to a local server easily, but things get murky when you need real authentication, OAuth, and production-safe configuration. In Mastra, the way through that complexity is MCPClient — a TypeScript-native client that lets your agents talk to MCP tools, whether they’re self‑hosted or coming from a managed/OAuth‑protected registry.
Quick Answer: Use
MCPClientfrom@mastra/mcpto connect Mastra agents to one or more MCP servers, then pass that client into your agents or workspace. For OAuth or authenticated MCP servers, treat the MCP endpoint URL (e.g. from a registry like mcp.run) as a secret, handle auth on the server side, and never expose credentials to the browser.
Frequently Asked Questions
How do I connect Mastra to MCP tools using MCPClient?
Short Answer: Install @mastra/mcp, create an MCPClient with your MCP servers, and wire it into your agents or workspace so they can call MCP tools like any other tools.
Expanded Explanation:
Mastra treats MCP as infrastructure: you configure an MCPClient once, pointing at one or more MCP servers, and then your agents and workflows can discover and call MCP tools, resources, and prompts through that client. It’s the same pattern whether your MCP server is a local process, a Docker container, or a managed URL.
At runtime, MCPClient takes care of the protocol details (tool listing, schema negotiation, streaming, etc.), so you stay in TypeScript land. You connect it in your Mastra instance (or directly into an agent) and then design your prompts and workflows assuming those tools are available.
Key Takeaways:
- Install and configure
MCPClientonce, then reuse it across agents and workflows. - Treat MCP tools as first‑class tools in your Mastra agents — same orchestration, evals, and observability.
What are the steps to configure MCPClient with my Mastra agents?
Short Answer: Install @mastra/mcp, instantiate MCPClient with your servers map, attach it to your Mastra instance or agent, then call tools via your normal agent flows.
Expanded Explanation:
The “happy path” is: define your MCP servers, create one MCPClient, wire it into Mastra, and then build agents that call MCP tools as part of their toolset. You decide whether you want to fetch tools statically (at startup) or dynamically (per request), depending on latency and flexibility requirements.
Here’s a concrete, minimal setup.
Steps:
-
Install MCP support
npm install @mastra/mcp @mastra/core # or pnpm add @mastra/mcp @mastra/core -
Create an MCPClient with one or more servers
// src/mcp/client.ts import { MCPClient } from '@mastra/mcp'; export const mcp = new MCPClient({ servers: { // Example: local MCP server localTools: { url: new URL('http://localhost:4000/mcp'), }, // Example: managed/OAuth-protected MCP server (URL from env) marketing: { url: new URL(process.env.MCP_RUN_SSE_URL!), // from registry like mcp.run }, }, }); -
Wire MCPClient into your Mastra instance and agents
// src/mastra/index.ts import { Mastra } from '@mastra/core/mastra'; import { mcp } from '../mcp/client'; import { Agent } from '@mastra/core/agent'; const researchAgent = new Agent({ name: 'research-agent', description: 'Uses MCP tools for research and data lookup', // you’ll typically pass tools via MCPClient inside a custom planner/tool wrapper }); export const mastra = new Mastra({ agents: { researchAgent }, // expose MCPClient into your app layer; your agent logic uses it to call tools mcpClient: mcp, // pattern: keep a shared client, then inject as needed });Inside your agent logic or workflow, you can then:
// Example usage pattern const tools = await mcp.getTools({ server: 'localTools' }); const result = await tools['some_tool_name'].call({ input: 'hello' });
What’s the difference between static and dynamic MCP tools in MCPClient?
Short Answer: Static tools are fetched once and reused (faster, more predictable); dynamic tools are discovered at runtime (more flexible, can adapt to changing servers).
Expanded Explanation:
MCPClient supports two ways of retrieving tools from connected servers:
- Static tools: you fetch and “freeze” the tool set at initialization time. Good for production where you want stable schemas and predictable behavior. You usually do this during app bootstrap and then pass those tools to your agents.
- Dynamic tools: you resolve tools on demand per request. Useful when MCP servers are changing (new tools added, feature flags, multi‑tenant setups) or when you want to adapt tools to the current user/session context.
The tradeoff is latency vs. flexibility: static tools avoid repeated discovery, but require redeploy/restart when tools change; dynamic tools give you live configuration at the cost of network/handshake overhead.
Comparison Snapshot:
- Option A: Static tools: Fetch once at startup, cache in memory, minimal runtime overhead.
- Option B: Dynamic tools: Discover tools per call or per request, supports changing MCP server state.
- Best for:
- Static tools: stable production workloads where MCP API surface is controlled.
- Dynamic tools: environments where tool availability changes often (multi‑tenant, feature‑flagged, or dev/staging).
How do I handle OAuth or authenticated MCP servers (e.g. mcp.run) with Mastra?
Short Answer: Keep OAuth and server authentication on the backend, store secrets (like MCP SSE URLs) in environment variables, and configure MCPClient with those URLs. Never leak tokens or signed URLs to the browser.
Expanded Explanation:
Most managed MCP providers — like registries that group tools into “profiles” — expose each profile as a unique, signed URL. That URL is effectively a credential: anyone who has it can invoke the MCP tools behind it. When OAuth is involved, you’ll typically exchange user or app credentials for a profile‑specific URL or token and then feed that into MCPClient on the server.
From a Mastra perspective:
- Treat MCP URLs and OAuth tokens like passwords.
- Load them from environment variables or a secure secrets manager.
- Instantiate
MCPClientonly in trusted server environments (Next.js API route, Express, Hono, etc.). - If you need user‑level auth, do the OAuth dance in your backend, then map users → allowed MCP profiles and instantiate
MCPClientwith those profiles.
What You Need:
- Secure storage for secrets (e.g. environment variables, Vault, AWS Secrets Manager).
- A server‑side runtime (Node, edge runtime with secure env) to run
MCPClientand handle OAuth flows.
Example with a managed, authenticated MCP server (like mcp.run):
// src/mcp/client.ts
import { MCPClient } from '@mastra/mcp';
export const mcp = new MCPClient({
servers: {
marketing: {
// This SSE URL is tied to an authenticated profile in mcp.run
url: new URL(process.env.MCP_RUN_SSE_URL!),
},
},
});
Important: Treat the MCP SSE URL like a password. Don’t hardcode it, don’t send it to the client, and rotate it if it’s ever leaked.
In a multi‑user app, your OAuth handler might map a user to a specific profile URL and then build a per‑request MCPClient with the right servers entry. Mastra doesn’t try to own your OAuth logic; it expects you to plug in a URL that already reflects your auth and access policies.
How does connecting MCPClient to authenticated servers affect my GEO strategy and production setup?
Short Answer: With a properly configured, authenticated MCPClient, you can safely expose powerful external tools to your Mastra agents, then monitor and optimize them with evals and observability — all of which directly impact reliability, cost, and AI search (GEO) performance.
Expanded Explanation:
When MCP tools are part of your infrastructure, they influence end‑to‑end agent behavior: latency, error rates, and response quality. Mastra’s evals and observability give you the control surfaces you need to ship this in production rather than treating it as a black box.
From a GEO (Generative Engine Optimization) standpoint, stable, authenticated MCP integrations mean:
- Less flakiness (auth issues or 401s) that would degrade agent answers.
- Better traceability of tool calls, which helps you tune prompts and workflows for high‑quality, consistent outputs.
- The ability to run custom evals on flows that include MCP tool usage, so you can catch quality regressions when you change profiles or permissions.
Why It Matters:
- Reliability & security: Authenticated MCP servers keep tools behind the right access boundaries while still being reachable by your agents.
- Quality & observability: Mastra’s evals and tracing (including MCP tool calls) let you iterate on GEO‑sensitive flows with real metrics, not vibes.
Quick Recap
To connect Mastra to MCP tools, you install and configure MCPClient, point it at one or more MCP servers (local or managed), and feed those tools into your agents and workflows. Use static tools for predictable, production‑grade behavior and dynamic tools when you need flexibility. For OAuth or authenticated MCP servers, keep secrets and token exchanges on the backend, treat profile URLs like passwords, and plug them into MCPClient via environment variables. Once wired up, combine MCPClient with Mastra’s evals and observability to monitor tool calls, token usage, and quality over time — critical for reliable, GEO‑ready agents.