mastra-mcp
Skill2 starsChanged 29 days agoApache-2.0View on GitHub
Connect Mastra agents to Model Context Protocol servers with MCPClient, and expose Mastra tools, agents, workflows, resources, and prompts to other MCP clients with MCPServer, including stdio and Streamable HTTP transports, static vs runtime toolsets, per-user credentials, OAuth on both sides, tool approval, and MCP Apps. Use this skill whenever the user wants an agent to use an MCP server (GitHub, Wikipedia, a registry like Smithery or Composio), pass different API keys per user to MCP tools, publish their Mastra tools to Cursor, Claude Desktop, or VS Code, ship an npx stdio MCP server, or protect an MCP endpoint with OAuth. Triggers on MCP, Model Context Protocol, @mastra/mcp, MCPClient, MCPServer, listTools, listToolsets, toolsets, mcpServers, startStdio, startHTTP, MCPOAuthClientProvider, createOAuthMiddleware, requireToolApproval, inputRequests, appResources, MCP events, mcp-types.generated. Also triggers when the user mentions an MCP config file or a server URL ending in /mcp.
- Reads credentials
- Installs packages
In this repository46 other files it gives its agents.
- mastra-a2a-acpSkill
- mastra-agent-approval-hitlSkill
- mastra-agentic-uiSkill
- mastra-agent-skillsSkill
- mastra-agentsSkill
- mastra-authSkill
- mastra-browserSkill
- mastra-build-playbookSkill
- mastra-channelsSkill
- mastra-classifierSkill
- mastra-cli-apiSkill
- mastra-client-sdkSkill
- mastra-datasets-experimentsSkill
- mastra-deploymentSkill
- mastra-evalsSkill
- mastra-file-based-agentsSkill
- mastra-framework-integrationSkill
- mastra-guideSkill
- mastra-harnessSkill
- mastra-knowledgeSkill
- mastra-memorySkill
- mastra-migrationsSkill
- mastra-modelsSkill
- mastra-multi-agentSkill
- mastra-observabilitySkill
- mastra-observational-memorySkill
- mastra-platformSkill
- mastra-processors-guardrailsSkill
- mastra-project-setupSkill
- mastra-ragSkill
- mastra-schedulesSkill
- mastra-semantic-recallSkill
- mastra-serverSkill
- mastra-signalsSkill
- mastra-storageSkill
- mastra-streamingSkill
- mastra-structured-outputSkill
- mastra-studio-editorSkill
- mastra-tool-integrationsSkill
- mastra-toolsSkill
- mastra-troubleshootingSkill
- mastra-vector-storesSkill
- mastra-voiceSkill
- mastra-workflowsSkill
- mastra-workflow-suspend-resumeSkill
- mastra-workspace-sandboxSkill
The file
We split this skill into the rules it gives an agent
3 rules. About 0 are common, 0 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 125
Verify the API: If node_modules/@mastra/ exists, read node_modules/@mastra/mcp/dist/docs/ and the installed MCPClient and MCPServer types.
- Very specific: line 132
Protect the server: Use createOAuthMiddleware with a real validateToken, protect /api/mcp/* REST routes with server.auth, and authorize …
- Very specific: line 173
Per-user keys in
listTools()on a shared agent: Every user shares one credential.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Mastra MCP
Consume MCP servers as agent tools with MCPClient, and publish Mastra capabilities to external MCP clients with MCPServer, with credentials and permissions scoped correctly.
When to use
- Giving an agent tools from a local (
command) or remote (url) MCP server - Choosing static tools (
listTools()) vs per-request toolsets (listToolsets()) - Sending per-user API keys or forwarding request credentials to MCP servers
- Connecting to an OAuth-protected MCP server
- Requiring approval for some or all MCP tools
- Exposing Mastra tools, agents (
ask_<key>), and workflows (run_<key>) as an MCP server - Serving over Mastra's server, a custom HTTP server, serverless, or stdio (
npxpackage) - Protecting an MCP server with OAuth and passing caller identity to tools
- MCP Apps (
ui://resources) and experimental MCP events
When NOT to use
- Writing ordinary tools with
createTool(usemastra-tools) - Managed OAuth for hosted MCP servers through Mastra Connect (use
mastra-tool-integrations) - Remote agents over A2A, ACP coding agents, or SDK agents (use
mastra-a2a-acp) - Approval UI and resuming suspended runs in general (use
mastra-agent-approval-hitl) - Mastra server auth, middleware, and route protection (use
mastra-serverandmastra-auth) - Upgrading from
@mastra/mcp1.x (usemastra-migrations)
Required inputs
- Direction: consume (client), expose (server), or both
- For each server to consume: transport (
command+args, orurl), and credentials - Whose credentials: one shared service account, or each user's own
- Trust in each server (drives
requireToolApproval,forwardInstructions,allowedHosts) - For a server you expose: which tools, agents, workflows; transport; who may call it
The framework: client and server
Both classes come from @mastra/mcp and speak MCP revision 2026-07-28 over stdio and Streamable HTTP.
Client: connect and pass tools to an agent
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}` },
},
},
},
})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-6.1-sol',
tools: await mcpClient.listTools(),
})command selects stdio. url selects Streamable HTTP. listTools() names tools serverName_toolName.
Static tools vs runtime toolsets
| Static tools | Runtime toolsets | |
| Method | await mcpClient.listTools() | await mcpClient.listToolsets() |
| Use case | Shared, fixed configuration | Per-user or per-request configuration |
| Credentials | Shared by all requests | Vary per request |
| Agent API | tools in the Agent constructor | toolsets in generate() or stream() |
Server: expose Mastra primitives
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 }, // tool "ask_assistant", agent needs a description
tools: { weatherTool },
workflows: { weatherWorkflow }, // tool "run_weatherWorkflow", workflow needs a description
})Register it with new Mastra({ mcpServers: { mcpServer } }). Mastra serves it at /api/mcp/:serverId/mcp over Streamable HTTP, which also works on serverless.
Workflow
- Verify the API. If
node_modules/@mastra/exists, readnode_modules/@mastra/mcp/dist/docs/and the installedMCPClientandMCPServertypes. Otherwise fetchhttps://mastra.ai/docs/connections/mcp.md,https://mastra.ai/reference/tools/mcp-client.md, andhttps://mastra.ai/reference/tools/mcp-server.md. Trust these over memory. - Install
npm install @mastra/mcp@latest. - Client side: define servers once at module scope with a stable
id. Secrets come from env vars, never literals. - Pick the loading mode. Shared credentials:
listTools()on the agent. Per-user credentials: build a client per request, passlistToolsets()astoolsets, thendisconnect(). - Set trust controls.
requireToolApproval(boolean or function),allowedHostsfor URLs from untrusted config,inheritDefaultEnv: falsefor stdio servers that should see onlyenv. LeaveforwardInstructionsoff for third-party servers. - OAuth servers: one
MCPOAuthClientProviderper server with eitherclientInformationorclientMetadataUrl. Handle'needs-auth'withauthenticate()in local tools; hosted apps own their callback route. - Server side: give every exposed agent and workflow a
description. Register onMastra, or callstartHTTP()/startStdio()yourself. - Protect the server. Use
createOAuthMiddlewarewith a realvalidateToken, protect/api/mcp/*REST routes withserver.auth, and authorize records inside tools from trusted context. - Test. In Studio, open the agent and the MCP server pages. For servers, connect from an MCP client such as Cursor. Set
legacy: 'stateless'if 2025-era clients must connect.
Deep dive: per-user credentials
Static listTools() bakes one credential into every call. For per-user keys, create a client per request:
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
}Alternative: keep one static client and supply a custom fetch(url, init, requestContext) that adds headers from requestContext. requestContext is null during the initial handshake, so do not throw when it is missing; forward the request and let the server reject it.
For a server you expose, never pass the incoming MCP access token to upstream APIs. Look up a separate credential for the authenticated user.
Failure patterns
MCPClientcreated per request without anidordisconnect(). Identical configs throw to prevent leaks. Give each instance a uniqueid, orawait client.disconnect()before recreating.- Per-user keys in
listTools()on a shared agent. Every user shares one credential. UselistToolsets()per request or a customfetch. - Agent or workflow without
descriptioninMCPServer. Server construction throws. Add a non-empty description. - Expecting tool names to match the server's. Client tools are
server_tool(listTools) orserver.tool(listToolsets). Server-side agents becomeask_<key>, workflowsrun_<key>. - Cursor or VS Code cannot connect over HTTP.
MCPServerrejects 2025-erainitializeclients by default. Setlegacy: 'stateless'. createOAuthMiddlewarewithoutvalidateToken. Tokens are accepted unvalidated. UsecreateIntrospectionValidatoror a JWT check with audience and expiry.- Only protecting
/mcp. Mastra also registers REST routes under/api/mcp/*(including tool execute). Useserver.author default-deny them. - Trusting tool annotations from third-party servers.
readOnlyHintis advisory. Only relax approval for trusted servers. forwardInstructions: trueon an untrusted server. Its instructions enter the system prompt verbatim. Inspect withgetServerInstructions()first.- One
MCPOAuthClientProvidershared across servers. Flows overwrite each other. Use one per server and namespaced storage. - Process exits during graceful shutdown. The client installs signal hooks by default. Set
registerProcessHooks: falseand calldisconnect()yourself. input_requirederrors from a server. ConfigureinputRequestson that server definition.- Continuations failing across instances. Set
requestState.key(32+ bytes from env) onMCPServerso every instance shares it.
Output format
A finished MCP delivery contains:
src/mastra/mcp/client.tsexporting a configuredMCPClient, and/orsrc/mastra/mcp/server.tsexporting anMCPServer- Agent wiring (
tools: await mcpClient.listTools()) or a request handler usingtoolsets - Server registration in
new Mastra({ mcpServers }), or a stdio entry file withbininpackage.json - Env vars in
.env.example(server URLs, API keys, OAuth client settings,MCP_REQUEST_STATE_KEY) - Approval,
allowedHosts, and auth configuration matching the trust level - Evidence: tools listed in Studio, or a successful call from an external MCP client
Reference files
references/api.md-MCPClientoptions, server definition fields, methods;MCPServeroptions, methods, OAuth middleware, context.references/examples.md- Static client agent with approval, per-user toolsets and forwarded headers, exposed server plus stdio package, OAuth-protected HTTP server.references/checklist.md- Client, server, and auth production checklist.
Live docs
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

