tools()
Returns a resolver for the tools of every provider connected to a Mastra platform project. Pass it to an agent's tools option, and Mastra calls it on each generate() and stream(). The resolver caches the tools for ttlMs and starts a background refresh when called after the cache expires.
import { Agent } from '@mastra/core/agent'
import { tools } from '@mastra/connect'
export const opsAgent = new Agent({
id: 'ops',
name: 'ops',
instructions: 'You help the team track work in Linear and GitHub.',
model: 'openai/gpt-6-luna',
tools: tools(),
})
Returns: ToolsResolver, a resolver producing a flat tool record keyed by tool key (for example linear_create_issue). See The resolver.
See Connect to get started.
ParametersDirect link to Parameters
options?:
projectId?:
providers?:
allowTools?:
disallowTools?:
requireApproval?:
client?:
ttlMs?:
Per-request optionsDirect link to Per-request options
Pass a callback instead of an options object to vary options per request, for example role-based filters or approval policies. The callback runs on every resolution (sync or async) and receives the same context Mastra passes the resolver (requestContext is populated when the resolver is an agent's tools option):
const connected = tools(ctx => ({
providers: {
linear:
ctx?.requestContext?.get('role') === 'viewer'
? { allowTools: ['linear_list_*'] }
: { requireApproval: ['linear_delete_*'] },
},
}))
The resolver memoizes snapshots per distinct options value, so requests producing the same options share one cached snapshot with the usual ttlMs and stale-while-revalidate semantics. Structurally equal options returned from different calls count as the same value, except that non-serializable values such as a custom client.fetch compare by identity. The resolver keeps caches for at most 32 distinct options values and evicts the least recently used one past that, so derive options from a small, closed set of inputs such as roles, not from unbounded per-request data.
With the callback form, option validation runs at the first resolution that produces an options value rather than at tools() time, and a validation error fails that resolution. refresh() fetches for the options the callback returns without a context (the same variant a direct await connected() call uses), and disconnect() closes every memoized variant.
Per-provider optionsDirect link to Per-provider options
Each value in the providers record form is true, false, or a ToolsProviderOptions:
connectionId?:
allowTools?:
disallowTools?:
requireApproval?:
ConnectClientOptionsDirect link to ConnectClientOptions
Every field except fetch and resourceId falls back to an environment variable. fetch defaults to globalThis.fetch, and resourceId has no fallback, so a fully env-configured app that doesn't scope calls to a resource can pass nothing.
accessToken?:
orgId?:
projectId?:
resourceId?:
baseUrl?:
fetch?:
The resolverDirect link to The resolver
The returned ToolsResolver caches its tools. Within ttlMs of the last fetch, it returns the cache. The first call after expiry still returns the cache right away and starts a background fetch from the platform (stale-while-revalidate). Later calls use the updated snapshot once the fetch succeeds, or keep using the cached snapshot if the refresh fails. Refreshes depend on calls to the resolver rather than idle polling. Use await connected.refresh() to wait for a fresh tool record.
Call the resolver directly when you need a plain tool record, for example for the toolsets option at generate time:
import { tools } from '@mastra/connect'
const connected = tools()
const response = await agent.generate('Summarize my open issues.', {
toolsets: { connect: await connected() },
})
The resolver also exposes methods for manual control:
refresh()fetches from the platform immediately, then updates the cache and returns the tool record. Rejects if the platform fetch fails.disconnect()clears the cached snapshots and closes the MCP transports of the state behind this resolver. Resolvers created with identical options share that state, so this disconnects them too. A later resolution rebuilds the state, and already-returned MCP tools reconnect on their next call.with(extra)returns a new resolver that merges extra tools into every resolution, giving extras priority on key collision. It accepts a static tool record or a function (sync or async) and calls chain. For the same merge using a spread of the resolver's result in atoolscallback, see Add tools to an agent.codeMode(options)exposes the tools through Code Mode.
To filter on something other than tool keys, or on data that options can't express, post-process the resolved record in the agent's tools function. Create the resolver once, outside the function, so its cache is shared:
import { Agent } from '@mastra/core/agent'
import { tools } from '@mastra/connect'
const connectTools = tools({ providers: ['linear'] })
const viewerTools = new Set(['linear_list_issues'])
export const opsAgent = new Agent({
id: 'ops',
name: 'ops',
instructions: 'You help the team track work in Linear.',
model: 'openai/gpt-6-luna',
tools: async ctx => {
const all = await connectTools(ctx)
if (ctx.requestContext?.get('role') === 'admin') {
return all
}
return Object.fromEntries(Object.entries(all).filter(([key]) => viewerTools.has(key)))
},
})
Only the admin role gets every tool. Any other or missing role gets the viewer subset. Set role in trusted server-side code based on the authenticated user. Vary tools by channel applies the same pattern to channel messages.
Error handling depends on the cause:
- Configuration errors (missing project ID or token, a malformed provider ID, both
allowToolsanddisallowToolsat one level, invalidttlMs) throw when you calltools(). With the callback form, they fail the first resolution that produces the invalid options instead. - An enabled provider ID that the platform catalog confirms is unknown fails the resolution with
invalid_options. An unknown tool key or zero-match glob in a per-provider filter does the same. If the catalog can't be reached, an unknown ID downgrades to a warning and is skipped. - If a background refresh fails while a snapshot is cached, the resolver keeps serving the cached toolsets and warns. It rejects only when nothing was ever cached.
- A problem with one provider, such as a connection that needs reauthorization, logs a warning and skips that provider. The other providers' tools still load.
Code ModeDirect link to Code Mode
codeMode() gives the agent the connected tools through Code Mode: the agent writes one TypeScript program that calls the tools as external_* functions, instead of calling each tool in its own step. Use it when tasks fan out across many calls or providers, such as listing items in one provider and looking each one up in another.
import { Agent } from '@mastra/core/agent'
import { LocalSandbox } from '@mastra/core/workspace'
import { tools } from '@mastra/connect'
const code = tools({ providers: ['linear', 'slack'] }).codeMode({ sandbox: new LocalSandbox() })
export const opsAgent = new Agent({
id: 'ops',
name: 'ops',
instructions: async ctx => ['You help the team track work.', await code.instructions(ctx)],
model: 'openai/gpt-6-luna',
tools: code.tools,
})
LocalSandbox runs the model-written program as a host node process with host privileges. Connected tools return third-party data, such as issue text, that can influence the code the model writes. Use LocalSandbox only for trusted or local development. See how Code Mode works for isolated alternatives.
codeMode() returns two functions, tools and instructions. Pass both to the agent. Like the resolver, they resolve the current connections on every request. The functions the program can call change as providers are connected or disconnected. Within one request both use the same resolution, and the instructions never declare a function the program can't call.
The method accepts every createCodeMode() option except tools (sandbox, timeout, id), plus transport for a remote sandbox or in-process isolation, and toolSearch for tool search. Every resolver provides it, including the callback form and resolvers returned by with(). Extra tools from with() join the program's functions.
Some tools stay direct agent tools instead of program functions, because they pause the agent run and a call from inside a program can't:
- Tools that need approval through
requireApproval. The agent still waits for the user to approve each call. - The
request_connectiontool, so the connect prompt can still pause the run until the user connects.
For MCP providers, a requireApproval list keeps all of that provider's tools direct, including the ones the list doesn't name. Mastra discovers MCP tools at request time and checks the list on each call, so Code Mode has no way to know in advance which calls need approval and keeps every tool from that provider out of the program. Generated HTTP tools work differently, because only the tools that match the list stay direct.
// Every neon-mcp tool stays direct, not just neon-mcp_run_sql
const ops = tools({
providers: { 'neon-mcp': { requireApproval: ['neon-mcp_run_sql'] } },
}).codeMode({ sandbox })
To let a program call that provider's other tools, remove the gated tools with disallowTools instead of gating them. To keep them gated, accept that the agent calls the provider's tools one at a time.
When there is nothing to orchestrate, for example when the project has no connections yet, tools returns only the direct tools and instructions returns an empty string.
Tool searchDirect link to Tool search
Declaring every function in the instructions uses context on every request: about 4,000 tokens for Linear alone and over 20,000 for Linear, GitHub, and Stripe together. With tool search, the instructions list only the function names, and the agent gets a search_functions tool that returns the TypeScript declarations for the functions it needs. The agent searches by what it wants to do or by exact names from the list, then writes the program. The program can still call every function. Only the declarations move behind the search.
Tool search turns on by itself when declaring every function would take more than about 10,000 tokens. Set toolSearch to choose:
// Always list names only and search for declarations
const searching = tools().codeMode({ sandbox: new LocalSandbox(), toolSearch: true })
// Always declare every function up front
const declared = tools().codeMode({ sandbox: new LocalSandbox(), toolSearch: false })
Choosing providersDirect link to Choosing providers
The providers array form is an allowlist: only listed providers are returned. Without the option, every connected provider with a supported toolset is included. A listed provider with no connection in the project yet is skipped and included automatically once a connection is attached. In the record form, false excludes a provider and never errors, even for IDs that match nothing.
Use an array to restrict discovery to named providers. A record configures named providers without excluding the others:
const onlyLinear = tools({ providers: ['linear'] })
const allWithLinearApproval = tools({
providers: { linear: { requireApproval: true } },
})
Tool keys for allowTools and disallowTools are listed per provider in the provider toolsets reference.
Connection resolutionDirect link to Connection resolution
For each provider present in the project's connections:
- An explicit
connectionIdoption wins. - Otherwise, a single active connection is used automatically.
- Otherwise the provider is left unpinned and routed per call: the toolset gains a
<provider>__list_connectionstool, every other tool takes a requiredconnection_nameinput, and the agent picks a connection per call using the display nameslist_connectionsreturns. Aconnection_namethat matches no active connection fails that call withunknown_connection.
The synthetic list_connections helper doesn't require approval and remains available even when top-level allowTools or disallowTools filters would exclude it.
Connections in needs_reauth status are skipped with a warning until someone replaces them.
MCP providersDirect link to MCP providers
Beyond the generated toolsets, the resolver discovers any connected provider that advertises MCP capability in the platform catalog. Discovered tools use the same flat contract, namespaced as <provider-id>_<tool-name>. If a provider has both a generated toolset and an MCP capability, the MCP catalog is preferred.
The application sends only its platform token. Before proxying each protocol request to the provider's MCP server, the platform removes caller authentication and injects the provider credential. MCP sessions are reused across refreshes and closed when the connection changes, the provider is detached, or disconnect() is called.
Discovered MCP tools follow the same approval policy as generated tools: none require approval unless requireApproval asks for it, for example 'neon-mcp': { requireApproval: ['neon-mcp_run_sql'] }. Passing the removed autoApproveTools key throws an invalid_options error at call time.
Environment variablesDirect link to Environment variables
tools(), channels(), and credential() read these environment variables. Options passed in code take precedence.
| Variable | Purpose |
|---|---|
MASTRA_PLATFORM_ACCESS_TOKEN | Platform access token used to authenticate every request |
MASTRA_PLATFORM_SECRET_KEY | Fallback token when MASTRA_PLATFORM_ACCESS_TOKEN is unset |
MASTRA_PROJECT_ID | Project whose connections to use |
MASTRA_ORG_ID | Organization ID, sent as the x-organization-id header when set |
MASTRA_PLATFORM_REGION | us or eu. Selects https://integrations.us.mastra.ai or https://integrations.eu.mastra.ai instead of the default https://integrations.mastra.ai |
MASTRA_INTEGRATIONS_API_URL | Connect API base URL. Overrides the region |
ErrorsDirect link to Errors
Throws MastraConnectError with a code property:
| Code | When |
|---|---|
missing_project_id | No project ID configured |
missing_access_token | No platform token configured |
invalid_options | Unknown or malformed provider ID, conflicting filters, duplicate or unmatched tool keys or globs, or invalid ttlMs |
unauthorized | The platform rejected the token (401/403) |
proxy_error | A proxied provider request failed, with status and detail carrying the provider response |
unknown_connection | A tool call supplied a connection_name that matches no active connection |
platform_error | Any other platform request failure |