MCPClient
The MCPClient class provides a way to manage multiple MCP server connections and their tools in a Mastra application. It handles connection lifecycle and tool namespacing while providing access to tools across all configured servers.
Upgrading from @mastra/mcp 1.x? See the migration guide.
ConstructorDirect link to Constructor
Creates a new instance of the MCPClient class.
constructor({
id?: string;
servers: Record<string, MastraMCPServerDefinition>;
timeout?: number;
}: MCPClientOptions)
MCPClientOptionsDirect link to MCPClientOptions
id?:
servers:
timeout?:
MastraMCPServerDefinitionDirect link to mastramcpserverdefinition
Each server in the servers map is configured using the MastraMCPServerDefinition type. The transport type is detected based on the provided parameters:
- If
commandis provided, it uses the Stdio transport. - If
urlis provided, it uses the Streamable HTTP transport.
The client speaks the MCP 2026-07-28 revision. On connect it asks the server which revisions it offers (server/discover) and falls back to the pre-2026 initialize handshake for servers that haven't upgraded, so tools, resources and prompts keep working against either. Features the older revisions lack (resources.subscribe(), inputRequests) fail with an error naming the negotiated revision. Set protocolVersion to skip the probe.
command?:
args?:
env?:
inheritDefaultEnv?:
false, only the variables explicitly listed in env are passed to the subprocess. Note that a subprocess without PATH may fail to spawn commands that are not absolute paths.url?:
requestInit?:
fetch?:
requestContext parameter containing request-scoped data (e.g., authentication cookies, bearer tokens) from the incoming request. When provided, this function will be used for all HTTP requests, allowing you to add dynamic authentication headers, forward request-scoped credentials to the MCP server, customize request behavior per-request, or intercept and modify requests/responses. When fetch is provided, requestInit and authProvider become optional, as you can handle these concerns within your custom fetch function.allowedHosts?:
"api.example.com" or "localhost:8080". Matching is exact and case-insensitive on the hostname; wildcards are not supported and the URL scheme is not checked. An empty array denies all requests. When unset, no restriction is applied. See the Security section below for enforcement details.logger?:
protocolVersion?:
'2026-07-28' connects only to servers that offer the current revision. 'legacy' uses the pre-2026 initialize handshake without probing, for servers known not to have upgraded. When omitted the client probes with server/discover and speaks whichever revision the server offers.timeout?:
timeout when omitted.capabilities?:
elicitation and extensions. elicitation is only accepted together with an inputRequests handler and defaults to form support when a handler is configured. Roots and sampling are not supported.inputRequests?:
input_required, the handler is called with each embedded request and the client retries the call with the answers. Without a handler an input_required result surfaces as an error. See Answering input requests below.authProvider?:
enableServerLogs?:
io.modelcontextprotocol/logLevel metadata key to every request so the server delivers notifications/message for it, and forwards delivered messages to logger.serverLogLevel?:
enableProgressTracking?:
progressToken with tool calls so the server can report progress. See the progress property.traceContext?:
traceparent, optional tracestate and baggage to send as request _meta on every call to this server. Called when each request is sent so it can read a request-local carrier. Explicit _meta keys on a tool call take precedence. Servers built with MCPServer expose the received values to tools as requestContext.get("traceContext"); they are observability data and are never used for authorization.forwardInstructions?:
instructionsMaxLength?:
requireToolApproval?:
true, all tools require approval. When set to a function, the function is called with the tool name, arguments, request context, and any tool annotations advertised by the server to dynamically decide whether approval is needed.onToolError?:
isError: true. 'throw' raises a MastraError carrying the server's error text, so the failure reaches tool spans, stream chunks, scorers, and the model. 'return' resolves with the raw result and ignores isError.jsonSchemaValidator?:
Tool approvalDirect link to Tool approval
Use requireToolApproval on a server definition to require human approval before any tool from that server is executed. This works with the existing human-in-the-loop approval flow.
Require approval for all toolsDirect link to Require approval for all tools
Set requireToolApproval to true to require approval for every tool on the server:
const mcp = new MCPClient({
servers: {
github: {
url: new URL('http://localhost:3000/mcp'),
requireToolApproval: true,
},
},
})
Dynamic approval with a functionDirect link to Dynamic approval with a function
Pass a function to decide per-call whether approval is needed. The function receives the tool name, the arguments the model passed, any request context from the incoming request, and the tool's MCP annotations (when the server advertises them):
const mcp = new MCPClient({
servers: {
github: {
url: new URL('http://localhost:3000/mcp'),
requireToolApproval: ({ toolName, args, requestContext }) => {
// Read-only tools don't need approval
if (toolName === 'list_repos') return false
// Destructive tools with force flag always need approval
if (toolName === 'delete_repo') return args.force === true
// Non-admin users need approval for everything else
return requestContext?.userRole !== 'admin'
},
},
},
})
The function can also be async. It receives requestContext from the incoming request, which you can use for auth checks or other per-request logic.
Use tool annotations from a trusted serverDirect link to Use tool annotations from a trusted server
If you trust the MCP server, you can use its tool annotations (readOnlyHint, destructiveHint, idempotentHint, openWorldHint, title) to drive approval decisions:
const mcp = new MCPClient({
servers: {
github: {
url: new URL('http://localhost:3000/mcp'),
requireToolApproval: ({ annotations }) => {
// Skip approval for tools the server has marked read-only
if (annotations?.readOnlyHint) return false
// Always require approval for destructive tools
if (annotations?.destructiveHint) return true
return true
},
},
},
})
Per the MCP specification: clients MUST consider tool annotations to be untrusted unless they come from trusted servers. Annotations are advisory hints and provide no security boundary. A malicious or buggy server can claim a tool is read-only when it isn't. Only use annotations to relax approval requirements for servers you trust.
The same annotations are also exposed on the tools returned by listTools() and listToolsets() under tool.mcp.annotations, so you can inspect them when wiring tools into an agent.
Each tool also carries tool.title, set from the server's tool title and falling back to annotations.title. When the server provides neither, tool.title is undefined and the tool name is the display fallback, matching the MCP display-name precedence.
Server instructionsDirect link to Server instructions
When an MCP server advertises instructions during initialization, MCPClient stores them for that server. Forwarding those instructions into an agent's system prompt is opt-in: set forwardInstructions: true on a server to have agents that use its tools (via listTools() or listToolsets()) receive its instructions automatically.
The guidance is grouped by server name and truncated to instructionsMaxLength characters per server.
const mcp = new MCPClient({
servers: {
db: {
url: new URL('http://localhost:3000/mcp'),
forwardInstructions: true,
instructionsMaxLength: 512,
},
},
})
const agent = new Agent({
id: 'db-agent',
name: 'DB Agent',
instructions: 'Help with database changes.',
model,
tools: await mcp.listTools(),
})
When forwardInstructions is omitted (the default), instructions are still cached and can be inspected via getServerInstructions(), but aren't added to any agent's system prompt.
Security note: server instructions are forwarded verbatim (subject only to length truncation) into the agent's system prompt. A malicious or compromised MCP server can use them to inject instructions the agent will treat as trusted system guidance. Only enable
forwardInstructionsfor servers you trust, and prefer reviewing instructions withgetServerInstructions()before forwarding instructions from third-party servers.
SecurityDirect link to Security
Subprocess environment for Stdio serversDirect link to Subprocess environment for Stdio servers
Stdio subprocesses don't inherit the full parent process environment. By default the subprocess environment starts from the MCP SDK's curated whitelist (POSIX: HOME, LOGNAME, PATH, SHELL, TERM, USER; Windows: APPDATA, HOMEDRIVE, HOMEPATH, LOCALAPPDATA, PATH, PROCESSOR_ARCHITECTURE, SYSTEMDRIVE, SYSTEMROOT, TEMP, USERNAME, USERPROFILE), merged with any variables you set in env. Sensitive variables such as API keys aren't inherited unless you pass them explicitly.
For stricter isolation, set inheritDefaultEnv: false so only your configured env entries reach the subprocess:
const mcp = new MCPClient({
servers: {
myTool: {
command: '/usr/local/bin/my-mcp-server',
inheritDefaultEnv: false,
env: { MY_TOOL_API_KEY: process.env.MY_TOOL_API_KEY! },
},
},
})
Variables you place in env are forwarded verbatim, so treat server configurations that come from untrusted sources (for example, user-supplied config files) as untrusted input.
Restricting outbound hosts with allowedHostsDirect link to restricting-outbound-hosts-with-allowedhosts
When HTTP server URLs come from untrusted configuration, an attacker-controlled URL can point the client at internal services (server-side request forgery). Set allowedHosts on such servers to restrict which hosts the client will contact:
const mcp = new MCPClient({
servers: {
remote: {
url: new URL(untrustedConfig.serverUrl),
allowedHosts: ['api.example.com'],
},
},
})
Enforcement details:
- On the default fetch path, requests to disallowed hosts, including every redirect hop, are blocked before they're sent. Redirects are followed manually (up to 5 hops) so each hop is validated, and the
Authorizationheader isn't carried across hops to a different origin (any scheme, host, or port change drops it, matching standard fetch behavior). - When you supply a custom
fetch, the initial URL is still checked before the request, but redirect hops are validated after the fact usingresponse.url: the outbound hop may occur, and the response is discarded when its final URL points at a disallowed host. A hand-builtResponsewith an emptyresponse.urlskips this post-hoc check. - OAuth requests made through
authProvider(authorization server metadata discovery, token exchange, refresh) are also validated. If your authorization server runs on a different host than the MCP server, add that host toallowedHoststoo. - A blocked host fails the connection with a clear error and is never retried by the reconnect logic.
allowedHosts is intentionally minimal: it matches exact hosts and doesn't support wildcards or scheme checks. If you need richer policy (scheme checks, IP-range rules), supply a custom fetch implementation, which is invoked for every request the client makes.
Treat tool responses as untrusted inputDirect link to Treat tool responses as untrusted input
Tool results returned by MCP servers flow into your agent's context as model input. A malicious or compromised server can use tool output for prompt injection. The transport client doesn't sanitize tool responses: sanitization policy belongs at the agent layer, where Mastra's input and output processors let you inspect, transform, or block content before and after it reaches the model. Combine this with requireToolApproval and the forwardInstructions security note above when working with third-party servers.
MethodsDirect link to Methods
listTools()Direct link to listtools
Retrieves all tools from all configured servers, with tool names namespaced by their server name (in the format serverName_toolName) to prevent conflicts.
Intended to be passed onto an Agent definition.
new Agent({ id: 'agent', tools: await mcp.listTools() })
listToolsWithErrors(options?)Direct link to listtoolswitherrorsoptions
Retrieves all tools from all configured servers, with tool names namespaced by their server name. Also returns per-server errors for servers that failed to connect or list tools.
Set perServerTimeoutMs to limit how long discovery waits for each server. Servers that finish within the limit remain in tools. Timed-out servers appear in errors, and durations reports each server's discovery time in milliseconds.
const { tools, errors, errorDetails, durations } = await mcp.listToolsWithErrors({
perServerTimeoutMs: 3_000,
})
new Agent({ id: 'agent', tools })
console.log(errors, errorDetails, durations)
errors remains a string map for backward compatibility. errorDetails provides the same message plus machine-readable httpStatus and transport code fields when the underlying error exposes them. When an HTTP status is available, the legacy message also includes an (HTTP nnn) suffix.
When called without options, the method omits only durations; tools, errors, and errorDetails are always returned.
listToolsets()Direct link to listtoolsets
Returns an object mapping namespaced tool names (in the format serverName.toolName) to their tool implementations.
Intended to be passed at runtime into the generate or stream method.
const res = await agent.stream(prompt, {
toolsets: await mcp.listToolsets(),
})
listToolsetsWithErrors(options?)Direct link to listtoolsetswitherrorsoptions
Returns toolsets grouped by server name, along with per-server discovery errors. Set perServerTimeoutMs to limit each server independently and include per-server durations in milliseconds.
const { toolsets, errors, errorDetails, durations } = await mcp.listToolsetsWithErrors({
perServerTimeoutMs: 3_000,
})
const res = await agent.stream(prompt, { toolsets })
console.log(errors, errorDetails, durations)
When called without options, the method omits only durations; toolsets, errors, and errorDetails are always returned.
listToolDefinitions()Direct link to listtooldefinitions
Returns every server's tools as plain, serializable definitions, grouped by server name and keyed by the server's own tool name (without the serverName_toolName namespacing that listTools() applies).
Unlike listTools(), the result contains no functions or references to a live client, so it can be passed through JSON.stringify and cached in Redis or a database, as well as a build artifact. Each definition holds the data from the MCP tools/list response (name, title, description, input schema, output schema, annotations, and _meta), plus the server name, version, and instructions captured at discovery time.
const definitions = await mcp.listToolDefinitions()
await cache.set('mcp-tools', JSON.stringify(definitions))
listToolDefinitionsWithErrors(options?)Direct link to listtooldefinitionswitherrorsoptions
Like listToolDefinitions(), but also returns per-server errors for servers that failed to connect. Use this when caching a catalog, so you don't persist a partial manifest that omits a server that was down at discovery time.
Set perServerTimeoutMs to limit each server independently. When options are provided, durations reports each server's discovery time in milliseconds.
const { definitions, errors, errorDetails, durations } = await mcp.listToolDefinitionsWithErrors({
perServerTimeoutMs: 3_000,
})
if (Object.keys(errors).length === 0) {
await cache.set('mcp-tools', JSON.stringify(definitions))
}
console.log(errorDetails, durations)
When called without options, the method omits only durations; definitions, errors, and errorDetails are always returned.
toolFromDefinition()Direct link to toolfromdefinition
Rebuilds a single executable tool from a cached definition. No connection is opened here. The client connects lazily, the first time the tool is executed.
The returned tool behaves exactly like one from listTools(), with the same strict-mode metadata, approval policy, structured content handling, tool error handling, and reconnect behavior. Successful structured results are validated against the advertised outputSchema on both paths. Invalid results reject the tool call. MCP error results skip output validation.
MCP schemas without a $schema declaration use JSON Schema 2020-12. Local $ref and $defs references, composition keywords, and boolean subschemas are supported. To bound validation work from untrusted tool catalogs, input and output schemas are limited to 128 nested subschema levels and 10,000 subschema nodes.
structuredContent can be any JSON value, including strings, numbers, booleans, and null. Object and array results also expose the MCP content and _meta envelopes through non-enumerable Mastra metadata properties. Scalar and null results can't carry those properties and remain unchanged rather than being wrapped.
const definitions = JSON.parse(await cache.get('mcp-tools'))
const tool = await mcp.toolFromDefinition({
serverName: 'weather',
definition: definitions.weather.getForecast,
})
toolsFromDefinitions()Direct link to toolsfromdefinitions
Rebuilds an entire cached catalog into a namespaced tool map, without connecting. This is the cached counterpart to listTools(). It produces the same serverName_toolName keys, so you can reconstruct an agent's tool map on a cold start, and connections only open for the servers whose tools are actually called.
Servers present in the catalog but no longer configured on the client are skipped, so a stale cached manifest degrades gracefully.
const definitions = JSON.parse(await cache.get('mcp-tools'))
new Agent({ id: 'agent', tools: await mcp.toolsFromDefinitions({ definitions }) })
getServerInstructions()Direct link to getserverinstructions
Returns the instructions currently known for each configured MCP server. Servers that haven't connected yet, or don't advertise instructions, return undefined.
getServerInstructions(): Record<string, string | undefined>
Example:
await mcp.listTools()
const instructionsByServer = mcp.getServerInstructions()
console.log(instructionsByServer.db)
getServerInfo()Direct link to getserverinfo
Returns the identity each configured MCP server announced when it connected (its serverInfo, from the server/discover result or, for servers on an older revision, the initialize handshake): name and version, plus title, description, websiteUrl, and icons when the server provides them. A server's entry is undefined if it hasn't connected yet, or if it connected over the 2026-07-28 revision without announcing an identity, which that revision allows. Don't use it to check whether a server is connected. The values come from the remote server and aren't validated, so treat icon and website URLs as untrusted.
getServerInfo(): Record<string, MCPServerImplementation | undefined>
Example:
await mcp.listTools()
const info = mcp.getServerInfo()
console.log(info.myServer?.title, info.myServer?.version)
authenticate()Direct link to authenticate
Runs the interactive OAuth authorization-code flow for a server whose MCPOAuthClientProvider uses a loopback redirect URL. A local callback server passes the authorization URL to the provider's onRedirectToAuthorization callback and waits for the browser to return the code. It then exchanges the code for tokens and reconnects. See Interactive browser authentication.
The optional timeoutMs bounds how long the flow waits for the browser to return the authorization code before rejecting, and defaults to 5 minutes.
async authenticate(serverName: string, options?: { timeoutMs?: number }): Promise<void>
getServerAuthState()Direct link to getserverauthstate
Returns the OAuth authorization state of a configured server: 'needs-auth' after a connection attempt was rejected with an authorization error, 'authorized' once the server accepted the provider's credentials, or undefined for servers without an authProvider or that haven't attempted a connection yet.
getServerAuthState(serverName: string): 'needs-auth' | 'authorized' | undefined
cancelAuthentication()Direct link to cancelauthentication
Cancels an in-progress authenticate() flow for a server, so an abandoned browser authorization doesn't leave the client waiting indefinitely. It aborts the flow (including its setup phase, before the callback server binds), closes the local callback server if one is listening, and the pending authenticate() call rejects. Returns true if a flow was cancelled, or false when no flow was in progress.
The resulting getServerAuthState() depends on how far the flow progressed. A flow cancelled after a 401 rejection stays at 'needs-auth' and can be retried immediately. Cancellation during setup leaves the state unchanged (typically undefined) if no connection was attempted.
async cancelAuthentication(serverName: string): Promise<boolean>
disconnect()Direct link to disconnect
Disconnects from all MCP servers and cleans up resources.
async disconnect(): Promise<void>
toMCPServerProxies()Direct link to tomcpserverproxies
Returns a map of MCPClientServerProxy instances, one per configured server. Each proxy wraps the underlying client connection as an MCPServerBase instance, allowing external (non-Mastra) MCP servers to be registered in mcpServers and appear in Studio.
async toMCPServerProxies(): Promise<Record<string, MCPClientServerProxy>>
Spread the result into the mcpServers config on Mastra:
import { Mastra } from '@mastra/core/mastra'
import { MCPClient } from '@mastra/mcp'
const mcpClient = new MCPClient({
servers: {
'color-mixer': {
command: 'node',
args: ['path/to/color-mixer-server.js'],
},
},
})
export const mastra = new Mastra({
mcpServers: {
...(await mcpClient.toMCPServerProxies()),
},
})
This is useful for connecting external MCP servers that implement the MCP Apps extension or other features to Studio without wrapping them in a Mastra MCPServer.
resources PropertyDirect link to resources-property
The MCPClient instance has a resources property that provides access to resource-related operations.
const mcpClient = new MCPClient({/* ...servers configuration... */})
// Access resource methods via mcpClient.resources
const allResourcesByServer = await mcpClient.resources.list()
const templatesByServer = await mcpClient.resources.templates()
// ... and so on for other resource methods.
resources.list()Direct link to resourceslist
Retrieves all available resources from all connected MCP servers, grouped by server name.
async list(): Promise<Record<string, Resource[]>>
Example:
const resourcesByServer = await mcpClient.resources.list()
for (const serverName in resourcesByServer) {
console.log(`Resources from ${serverName}:`, resourcesByServer[serverName])
}
resources.listWithErrors(options?)Direct link to resourceslistwitherrorsoptions
Preserves successful resources while reporting failed servers through legacy string errors and structured errorDetails. Pass perServerTimeoutMs to bound each server independently and include durations.
const { resources, errors, errorDetails, durations } = await mcpClient.resources.listWithErrors({
perServerTimeoutMs: 3_000,
})
console.log(resources, errors, errorDetails, durations)
resources.templates()Direct link to resourcestemplates
Retrieves all available resource templates from all connected MCP servers, grouped by server name.
async templates(): Promise<Record<string, ResourceTemplate[]>>
Example:
const templatesByServer = await mcpClient.resources.templates()
for (const serverName in templatesByServer) {
console.log(`Templates from ${serverName}:`, templatesByServer[serverName])
}
resources.templatesWithErrors(options?)Direct link to resourcestemplateswitherrorsoptions
Returns successful resource templates together with per-server string errors, structured errorDetails, and optional durations.
const { templates, errors, errorDetails } = await mcpClient.resources.templatesWithErrors()
console.log(templates, errors, errorDetails)
resources.read(serverName: string, uri: string)Direct link to resourcesreadservername-string-uri-string
Reads the content of a specific resource from a server.
async read(serverName: string, uri: string): Promise<ReadResourceResult>
serverName: The identifier of the server (key used in theserversconstructor option).uri: The URI of the resource to read.
Example:
const content = await mcpClient.resources.read('myWeatherServer', 'weather://current')
console.log('Current weather:', content.contents[0].text)
resources.subscribe(serverName: string, uri: string)Direct link to resourcessubscribeservername-string-uri-string
Subscribes to updates for a specific resource on a server. Mastra adds the URI to a single managed subscriptions/listen stream per server. Subscribing to the same URI more than once has no effect while the stream is active. Mastra restores the stream after a reconnect and closes it when the client disconnects.
The method rejects if the server doesn't honor the requested URI. If stream restoration fails after a reconnect, the connection remains available and calling subscribe() again retries the stream.
async subscribe(serverName: string, uri: string): Promise<void>
Example:
await mcpClient.resources.subscribe('myWeatherServer', 'weather://current')
resources.unsubscribe(serverName: string, uri: string)Direct link to resourcesunsubscribeservername-string-uri-string
Unsubscribes from updates for a specific resource on a server. Mastra removes the URI from the managed subscriptions/listen filter and replaces the stream. When nothing remains to listen for, Mastra closes the stream.
async unsubscribe(serverName: string, uri: string): Promise<void>
Example:
await mcpClient.resources.unsubscribe('myWeatherServer', 'weather://current')
resources.onUpdated(serverName: string, handler: (params: { uri: string }) => void)Direct link to resourcesonupdatedservername-string-handler-params--uri-string---void
Sets a notification handler that will be called when a subscribed resource on a specific server is updated.
async onUpdated(serverName: string, handler: (params: { uri: string }) => void): Promise<void>
Example:
mcpClient.resources.onUpdated('myWeatherServer', params => {
console.log(`Resource updated on myWeatherServer: ${params.uri}`)
// You might want to re-fetch the resource content here
// await mcpClient.resources.read("myWeatherServer", params.uri);
})
resources.onListChanged(serverName: string, handler: () => void)Direct link to resourcesonlistchangedservername-string-handler---void
Sets a notification handler that will be called when the list of available resources changes on a specific server.
async onListChanged(serverName: string, handler: () => void): Promise<void>
Example:
mcpClient.resources.onListChanged('myWeatherServer', () => {
console.log('Resource list changed on myWeatherServer.')
// You should re-fetch the list of resources
// await mcpClient.resources.list();
})
prompts PropertyDirect link to prompts-property
The MCPClient instance has a prompts property that provides access to prompt-related operations.
const mcpClient = new MCPClient({/* ...servers configuration... */})
// Access prompt methods via mcpClient.prompts
const allPromptsByServer = await mcpClient.prompts.list()
const { prompt, messages } = await mcpClient.prompts.get({
serverName: 'myWeatherServer',
name: 'current',
})
prompts.list()Direct link to promptslist
Retrieves all available prompts from all connected MCP servers, grouped by server name.
async list(): Promise<Record<string, Prompt[]>>
Example:
const promptsByServer = await mcpClient.prompts.list()
for (const serverName in promptsByServer) {
console.log(`Prompts from ${serverName}:`, promptsByServer[serverName])
}
prompts.listWithErrors(options?)Direct link to promptslistwitherrorsoptions
Returns successful prompts together with per-server string errors, structured errorDetails, and optional durations.
const { prompts, errors, errorDetails } = await mcpClient.prompts.listWithErrors()
console.log(prompts, errors, errorDetails)
prompts.get({ serverName, name, args? })Direct link to promptsget-servername-name-args-
Retrieves a specific prompt and its messages from a server.
async get({
serverName,
name,
args?,
}: {
serverName: string;
name: string;
args?: Record<string, any>;
}): Promise<GetPromptResult>
Example:
const { messages } = await mcpClient.prompts.get({
serverName: 'myWeatherServer',
name: 'current',
args: { location: 'London' },
})
console.log(messages)
prompts.onListChanged(serverName: string, handler: () => void)Direct link to promptsonlistchangedservername-string-handler---void
Sets a notification handler that will be called when the list of available prompts changes on a specific server.
async onListChanged(serverName: string, handler: () => void): Promise<void>
Example:
mcpClient.prompts.onListChanged('myWeatherServer', () => {
console.log('Prompt list changed on myWeatherServer.')
// You should re-fetch the list of prompts
// await mcpClient.prompts.list();
})
tools PropertyDirect link to tools-property
The MCPClient instance has a tools property for subscribing to tool list change notifications. To fetch tools, use listTools() or listToolsets().
tools.onListChanged(serverName: string, handler: () => void)Direct link to toolsonlistchangedservername-string-handler---void
Sets a notification handler that will be called when the list of available tools changes on a specific server (for example, when the server adds or removes tools at runtime).
async onListChanged(serverName: string, handler: () => void): Promise<void>
Example:
await mcpClient.tools.onListChanged('myWeatherServer', async () => {
console.log('Tool list changed on myWeatherServer.')
// You should re-fetch the tools
// const tools = await mcpClient.listTools();
})
progress PropertyDirect link to progress-property
The MCPClient instance has a progress property for subscribing to progress notifications emitted by MCP servers while tools execute.
const mcpClient = new MCPClient({
servers: {
myServer: {
url: new URL('http://localhost:4111/api/mcp/myServer/mcp'),
// Off by default: opt in so tool calls carry a progressToken
enableProgressTracking: true,
},
},
})
// Subscribe to progress updates for a specific server
await mcpClient.progress.onUpdate('myServer', params => {
console.log('📊 Progress:', params.progress, '/', params.total)
if (params.message) console.log('Message:', params.message)
if (params.progressToken) console.log('Token:', params.progressToken)
})
progress.onUpdate(serverName: string, handler)Direct link to progressonupdateservername-string-handler
Registers a handler function to receive progress updates from the specified server.
async onUpdate(
serverName: string,
handler: (params: {
progressToken: string;
progress: number;
total?: number;
message?: string;
}) => void,
): Promise<void>
Notes:
- When
enableProgressTrackingis true, tool calls include aprogressTokenso you can correlate updates to a specific run. Servers only send progress for requests that carry a token. - If you pass a
runIdwhen executing a tool, it will be used as theprogressToken.
Answering input requestsDirect link to Answering input requests
A server tool, resource or prompt that needs something from the user ends its call with an input_required result instead of a value. The result carries one or more embedded requests, each with a server-chosen key and either a form (requestedSchema) or a URL the user must visit. Configure inputRequests on the server definition to answer them: the client calls the handler once per embedded request, retries the original call with the answers, and resolves the tool call with the final result. Without a handler an input_required result surfaces as an error.
import { MCPClient } from '@mastra/mcp'
const mcpClient = new MCPClient({
servers: {
interactiveServer: {
url: new URL('http://localhost:3000/mcp'),
inputRequests: async ({ key, params, signal }) => {
if (params.mode === 'url') {
return { action: 'decline' }
}
const content = await collectUserInput(params.message, params.requestedSchema, { signal })
return { action: 'accept', content }
},
},
},
})
MCPInputRequestDirect link to mcpinputrequest
The handler receives:
key: The server-chosen key the answer is filed under. Pass it through to your UI when several requests arrive in one round.params: The request. In form mode it hasmessageandrequestedSchema, a flat JSON Schema object of primitive fields. In url mode it hasmessageandurl.signal: Aborts when the originating call is cancelled or times out.
Configuring a handler advertises form support to the server. To accept url-mode requests as well, widen capabilities.elicitation on the same server definition.
Response typesDirect link to Response types
Return an ElicitResult:
-
Accept: The user provided data and confirmed submission.
contentmust matchrequestedSchema.return {action: 'accept',content: { name: 'John Doe', email: 'john@example.com' },} -
Decline: The user explicitly declined to provide the information.
return { action: 'decline' } -
Cancel: The user dismissed the request.
return { action: 'cancel' }
A declined or cancelled request ends the tool call with an error. A server can ask again after an accepted answer, so the handler may run several times for one tool call.
Schema-based input collectionDirect link to Schema-based input collection
Walk requestedSchema to prompt for each field:
inputRequests: async ({ params }) => {
if (params.mode === 'url') return { action: 'decline' }
const { properties, required = [] } = params.requestedSchema
const content: Record<string, string | number | boolean> = {}
for (const [fieldName, fieldSchema] of Object.entries(properties)) {
const value = await promptUser({
name: fieldName,
title: fieldSchema.title,
description: fieldSchema.description,
required: required.includes(fieldName),
})
if (value !== null) {
content[fieldName] = value
}
}
return { action: 'accept', content }
}
Best practicesDirect link to Best practices
- Configure the handler up front: it's part of the server definition, so a tool that asks for input never runs without one.
- Validate input: Check that required fields are provided.
- Respect user choice: Handle decline and cancel responses gracefully.
- Clear UI: Make it obvious what information is being requested and why.
- Security: Never auto-accept requests for sensitive information, and treat url-mode requests as links to untrusted sites.
OAuth authenticationDirect link to OAuth authentication
For connecting to MCP servers that require OAuth authentication per the MCP 2026-07-28 authorization specification, use the MCPOAuthClientProvider. The provider never registers a client at runtime: give it either clientInformation for a client pre-registered with the authorization server, or a Client ID Metadata Document URL as clientMetadataUrl:
import { MCPClient, MCPOAuthClientProvider } from '@mastra/mcp'
// Create an OAuth provider
const clientMetadataUrl = 'https://app.example.com/oauth/client-metadata.json'
const oauthProvider = new MCPOAuthClientProvider({
redirectUrl: 'http://localhost:3000/oauth/callback',
clientMetadataUrl,
clientMetadata: {
client_id: clientMetadataUrl,
redirect_uris: ['http://localhost:3000/oauth/callback'],
client_name: 'My MCP Client',
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
},
onRedirectToAuthorization: url => {
// Handle authorization redirect (open browser, redirect response, etc.)
console.log(`Please visit: ${url}`)
},
})
// Use the provider with MCPClient
const client = new MCPClient({
servers: {
protectedServer: {
url: new URL('https://mcp.example.com/mcp'),
authProvider: oauthProvider,
},
},
})
The document served at clientMetadataUrl must contain the same client_id, client_name, and redirect_uris. For loopback callbacks, include every fallback URL returned by getCallbackUrlCandidates() in the hosted document. The URL is sent as the client_id; the provider never calls a registration endpoint, so an authorization server that accepts neither the metadata document nor a pre-registered clientInformation fails the flow explicitly. Configure exactly one identity: the constructor throws when both clientInformation and clientMetadataUrl are set.
Tokens saved by MCPOAuthClientProvider are bound to the authorization server's validated issuer, and discovery state is persisted so the code exchange is only sent to the server that issued the redirect. The loopback callback also forwards the RFC 9207 iss parameter to the SDK, which rejects a mismatch before exchanging the authorization code.
Give each server its own MCPOAuthClientProvider instance. A provider holds per-server session and credential state during authorization, so sharing one instance across multiple servers lets their flows overwrite each other. When configuring several protected servers, construct a separate provider for each. If those providers use the same persistent backend, give each provider a separate OAuthStorage namespace because storage mutation ordering is coordinated only within one provider instance.
Interactive browser authenticationDirect link to Interactive browser authentication
When a server rejects a connection because authorization is required, the client records a 'needs-auth' state instead of failing outright. Calling authenticate() completes the flow. It starts a one-shot callback server on the provider's loopback redirect URL, falling back to the next sequential ports when it's in use. The SDK then performs discovery and uses the configured client identity. onRedirectToAuthorization receives the authorization URL so your application can open it in the user's browser. The token exchange finishes after the browser returns the authorization code:
import { MCPClient, MCPOAuthClientProvider } from '@mastra/mcp'
const clientMetadataUrl = 'https://app.example.com/oauth/client-metadata.json'
const oauthProvider = new MCPOAuthClientProvider({
redirectUrl: 'http://127.0.0.1:5533/oauth/callback',
clientMetadataUrl,
clientMetadata: {
client_id: clientMetadataUrl,
redirect_uris: ['http://127.0.0.1:5533/oauth/callback'],
client_name: 'My MCP Client',
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
},
onRedirectToAuthorization: url => {
// Open the user's browser at the consent page
console.log(`Please visit: ${url}`)
},
})
const mcp = new MCPClient({
servers: {
protectedServer: {
url: new URL('https://mcp.example.com/mcp'),
authProvider: oauthProvider,
},
},
})
try {
await mcp.listTools()
} catch {
if (mcp.getServerAuthState('protectedServer') === 'needs-auth') {
await mcp.authenticate('protectedServer')
}
}
Concurrent authenticate() calls for the same server join the pending flow. Different servers authenticate independently. With valid stored tokens the call reconnects without opening a browser.
Hosts that drive the flow can capture the authorization code with the exported createOAuthCallbackServer helper. It creates a one-shot loopback server that validates the OAuth state parameter before resolving with the code. Because the server uses plain HTTP, use it only for local loopback redirects. Web applications with an HTTPS redirect URL must host their own callback endpoint and drive the provider directly:
import { createOAuthCallbackServer, getCallbackUrlCandidates } from '@mastra/mcp'
// getCallbackUrlCandidates() lists every URL the helper may bind, so list all
// of them as redirect_uris in your pre-registration or metadata document.
const redirectUris = getCallbackUrlCandidates('http://127.0.0.1:5533/oauth/callback').map(url =>
url.toString(),
)
const server = await createOAuthCallbackServer({
redirectUrl: 'http://127.0.0.1:5533/oauth/callback',
state: expectedState,
})
// server.url reflects the port actually bound — use it as the redirect_uri.
try {
const { code, iss } = await server.waitForCode()
// Exchange the code here, passing `iss` so the SDK validates the issuer.
} finally {
await server.close()
}
Quick Token ProviderDirect link to Quick Token Provider
For testing or when you already have a valid access token:
import { MCPClient, createSimpleTokenProvider } from '@mastra/mcp'
const provider = createSimpleTokenProvider('your-access-token', {
redirectUrl: 'http://localhost:3000/callback',
clientMetadata: {
redirect_uris: ['http://localhost:3000/callback'],
client_name: 'Test Client',
},
clientInformation: { client_id: 'test-client' },
})
const client = new MCPClient({
servers: {
testServer: {
url: new URL('https://mcp.example.com/mcp'),
authProvider: provider,
},
},
})
Custom Token StorageDirect link to Custom Token Storage
For persistent token storage across sessions, implement the OAuthStorage interface. The provider stores tokens (both the latest set and one entry per authorization-server issuer), discovery state, and the PKCE verifier under string keys, so the backend only needs a key-value contract:
import { MCPOAuthClientProvider, OAuthStorage } from '@mastra/mcp'
class DatabaseOAuthStorage implements OAuthStorage {
constructor(
private db: Database,
private userId: string,
) {}
async set(key: string, value: string): Promise<void> {
await this.db.query(
'INSERT INTO oauth_tokens (user_id, key, value) VALUES (?, ?, ?) ON CONFLICT DO UPDATE SET value = ?',
[this.userId, key, value, value],
)
}
async get(key: string): Promise<string | undefined> {
const result = await this.db.query(
'SELECT value FROM oauth_tokens WHERE user_id = ? AND key = ?',
[this.userId, key],
)
return result?.[0]?.value
}
async delete(key: string): Promise<void> {
await this.db.query('DELETE FROM oauth_tokens WHERE user_id = ? AND key = ?', [
this.userId,
key,
])
}
}
const provider = new MCPOAuthClientProvider({
redirectUrl: 'http://localhost:3000/callback',
clientMetadata: {/* ... */},
clientInformation: { client_id: 'my-registered-client' },
storage: new DatabaseOAuthStorage(db, 'user-123'),
})
ExamplesDirect link to Examples
Static Tool ConfigurationDirect link to Static Tool Configuration
For tools where you have a single connection to the MCP server for you entire app, use listTools() and pass the tools to your agent:
import { MCPClient } from '@mastra/mcp'
import { Agent } from '@mastra/core/agent'
const mcp = new MCPClient({
servers: {
stockPrice: {
command: 'npx',
args: ['tsx', 'stock-price.ts'],
env: {
API_KEY: 'your-api-key',
},
logger: logMessage => {
console.log(`[${logMessage.level}] ${logMessage.message}`)
},
},
weather: {
url: new URL('http://localhost:8080/mcp'),
},
},
timeout: 30000, // Global 30s timeout
})
// Create an agent with access to all tools
const agent = new Agent({
id: 'multi-tool-agent',
name: 'Multi-tool Agent',
instructions: 'You have access to multiple tool servers.',
model: 'openai/gpt-5.6-sol',
tools: await mcp.listTools(),
})
// Example of using resource methods
async function checkWeatherResource() {
try {
const weatherResources = await mcp.resources.list()
if (weatherResources.weather && weatherResources.weather.length > 0) {
const currentWeatherURI = weatherResources.weather[0].uri
const weatherData = await mcp.resources.read('weather', currentWeatherURI)
console.log('Weather data:', weatherData.contents[0].text)
}
} catch (error) {
console.error('Error fetching weather resource:', error)
}
}
checkWeatherResource()
// Example of using prompt methods
async function checkWeatherPrompt() {
try {
const weatherPrompts = await mcp.prompts.list()
if (weatherPrompts.weather && weatherPrompts.weather.length > 0) {
const currentWeatherPrompt = weatherPrompts.weather.find(p => p.name === 'current')
if (currentWeatherPrompt) {
console.log('Weather prompt:', currentWeatherPrompt)
} else {
console.log('Current weather prompt not found')
}
}
} catch (error) {
console.error('Error fetching weather prompt:', error)
}
}
checkWeatherPrompt()
Dynamic toolsetsDirect link to Dynamic toolsets
When you need a new MCP connection for each user, use listToolsets() and add the tools when calling stream or generate:
import { Agent } from '@mastra/core/agent'
import { MCPClient } from '@mastra/mcp'
// Create the agent first, without any tools
const agent = new Agent({
id: 'multi-tool-agent',
name: 'Multi-tool Agent',
instructions: 'You help users check stocks and weather.',
model: 'openai/gpt-5.6-sol',
})
// Later, configure MCP with user-specific settings
const mcp = new MCPClient({
servers: {
stockPrice: {
command: 'npx',
args: ['tsx', 'stock-price.ts'],
env: {
API_KEY: 'user-123-api-key',
},
timeout: 20000, // Server-specific timeout
},
weather: {
url: new URL('http://localhost:8080/mcp'),
requestInit: {
headers: {
Authorization: `Bearer user-123-token`,
},
},
},
},
})
// Pass all toolsets to stream() or generate()
const response = await agent.stream('How is AAPL doing and what is the weather?', {
toolsets: await mcp.listToolsets(),
})
Instance managementDirect link to Instance management
The MCPClient class includes built-in memory leak prevention for managing multiple instances:
- Creating multiple instances with identical configurations without an
idwill throw an error to prevent memory leaks - If you need multiple instances with identical configurations, provide a unique
idfor each instance - Call
await configuration.disconnect()before recreating an instance with the same configuration - If you only need one instance, consider moving the configuration to a higher scope to avoid recreation
For example, if you try to create multiple instances with the same configuration without an id:
// First instance - OK
const mcp1 = new MCPClient({
servers: {/* ... */},
})
// Second instance with same config - Will throw an error
const mcp2 = new MCPClient({
servers: {/* ... */},
})
// To fix, either:
// 1. Add unique IDs
const mcp3 = new MCPClient({
id: 'instance-1',
servers: {/* ... */},
})
// 2. Or disconnect before recreating
await mcp1.disconnect()
const mcp4 = new MCPClient({
servers: {/* ... */},
})
Server lifecycleDirect link to Server lifecycle
MCPClient handles server connections gracefully:
- Automatic connection management for multiple servers
- Graceful server shutdown to prevent error messages during development
- Proper cleanup of resources when disconnecting
Using custom fetch for runtime-defined authenticationDirect link to Using custom fetch for runtime-defined authentication
For HTTP servers, you can provide a custom fetch function to handle runtime-defined authentication or request interception. It can also handle other custom behavior. This is particularly useful when you need to refresh tokens on each request or forward user credentials from the incoming request to the MCP server.
The custom fetch function receives an optional third requestContext parameter, which provides access to request-scoped data (e.g., authentication cookies, bearer tokens) set by middleware or passed during agent/tool execution. The requestContext is null during the initial connection handshake.
When fetch is provided, requestInit and authProvider become optional, as you can handle these concerns within your custom fetch function.
const mcpClient = new MCPClient({
servers: {
apiServer: {
url: new URL('https://api.example.com/mcp'),
fetch: async (url, init, requestContext) => {
const headers = new Headers(init?.headers)
// Forward auth cookie from the incoming request
const cookie = requestContext?.get('cookie')
if (cookie) {
headers.set('cookie', cookie)
}
return fetch(url, { ...init, headers })
},
},
},
})
// Use with an agent — requestContext is automatically forwarded
const agent = new Agent({
id: 'my-agent',
name: 'My Agent',
instructions: 'You are a helpful assistant.',
model: openai('gpt-5.4'),
tools: await mcpClient.listTools(),
})
await agent.generate('Hello!', {
requestContext: myRequestContext, // forwarded to the custom fetch
})
Handling auth failures inside custom fetchDirect link to Handling auth failures inside custom fetch
A custom fetch shouldn't throw when authentication is unavailable. Every MCP request is a POST, and the SDK surfaces a non-2xx response as an error to the caller of listTools(), tools/call and so on, which is the behavior you want. A thrown fetch is reported the same way but loses the server's status and body. The only long-lived request is the subscriptions/listen POST the client opens for resources.subscribe(), and it's retried after a failure, so an unauthenticated stream can loop. Wait for the token, then forward the request:
async function waitForToken(timeoutMs = 5000): Promise<string | null> {
// Replace with your token lookup. Return null if no token is available.
return getAuthToken({ timeoutMs })
}
const mcpClient = new MCPClient({
servers: {
apiServer: {
url: new URL('https://api.example.com/mcp'),
fetch: async (url, init) => {
const token = await waitForToken()
if (!token) {
// Forward the request without a token and let the server reject it.
return fetch(url, init)
}
const headers = new Headers(init?.headers)
headers.set('authorization', `Bearer ${token}`)
return fetch(url, { ...init, headers })
},
},
},
})
Sending request headersDirect link to Sending request headers
Static headers go in requestInit. They're sent on every request, including the subscriptions/listen stream:
const client = new MCPClient({
servers: {
exampleServer: {
url: new URL('https://your-mcp-server.com/mcp'),
requestInit: {
headers: {
Authorization: 'Bearer your-token',
},
},
},
},
})
Use a custom fetch when the value changes per request.
Related informationDirect link to Related information
- For creating MCP servers, see the MCPServer documentation.
- Migrating from
@mastra/mcp1.x: Migrate @mastra/mcp from v1 to v2. - For more about the Model Context Protocol, see the @modelcontextprotocol/sdk documentation.