Skip to main content

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.

src/mastra/agents/ops.ts
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.

Parameters
Direct link to Parameters

options?:

ToolsOptions | ((ctx?: ToolsResolverContext) => ToolsOptions | Promise<ToolsOptions>)
Optional discovery and client configuration, or a callback returning it per request. See Per-request options below.
ToolsOptions

projectId?:

string
Platform project whose connections to discover. Falls back to MASTRA_PROJECT_ID.

providers?:

string[] | Record<string, boolean | ToolsProviderOptions>
Providers to resolve, keyed by provider ID. The array form is an allowlist: only the listed providers resolve, with default options. The record form leaves unlisted providers enabled and configures listed providers individually: true (or {}) enables one with defaults, false excludes it even when connected, and an options object adds per-provider settings. An enabled ID that matches no provider fails resolution with an invalid_options error. See Per-provider options below.

allowTools?:

string[]
Default allowlist of tool keys or * globs applied to every provider without its own allowTools or disallowTools. Applied leniently per provider; an entry that matches nothing anywhere logs a warning. Mutually exclusive with the top-level disallowTools.

disallowTools?:

string[]
Default denylist of tool keys or * globs applied to every provider without its own filter. Applied leniently per provider; an entry that matches nothing anywhere logs a warning. Mutually exclusive with the top-level allowTools.

requireApproval?:

boolean | string[]
Default tool-approval policy applied to every provider without its own requireApproval. true gates every provider tool except the synthetic <provider>__list_connections helper; an array of keys or * globs gates matching provider tools, with the same exception. A provider opts out with requireApproval: false.

client?:

ConnectClientOptions
Platform client overrides. See ConnectClientOptions below.

ttlMs?:

number
How long a resolved snapshot stays fresh, in milliseconds. Default 30000. 0 revalidates on every resolution.

Per-request options
Direct 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 options
Direct link to Per-provider options

Each value in the providers record form is true, false, or a ToolsProviderOptions:

connectionId?:

string
Pin a specific connection ID, bypassing single-active-connection resolution.

allowTools?:

string[]
Restrict the returned toolset to these tool keys or * globs (for example linear_get_*). An unknown key, or a glob matching nothing, fails resolution with an invalid_options error. Mutually exclusive with disallowTools. Setting it opts the provider out of the top-level defaults.

disallowTools?:

string[]
Remove these tool keys or * globs from the returned toolset. An unknown key, or a glob matching nothing, fails resolution with an invalid_options error. Mutually exclusive with allowTools. Setting it opts the provider out of the top-level defaults.

requireApproval?:

boolean | string[]
Tool-approval policy for this provider, applied to discovered MCP tools and generated HTTP tools alike. Tools require no approval by default. Pass true to require approval for every provider tool except the synthetic <provider>__list_connections helper, or an array of tool keys or * globs to require approval only for matching provider tools. An unknown name, or a glob matching nothing, fails resolution with an invalid_options error, so a typo never silently widens access. Setting it (including false) opts the provider out of the top-level requireApproval default.

ConnectClientOptions
Direct 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?:

string
Platform access token. Falls back to MASTRA_PLATFORM_ACCESS_TOKEN, then MASTRA_PLATFORM_SECRET_KEY.

orgId?:

string
Organization ID. Falls back to MASTRA_ORG_ID; sent as the x-organization-id header when present.

projectId?:

string
Project ID, sent as the x-mastra-project-id header so the platform can attribute proxy activity to the project. Falls back to MASTRA_PROJECT_ID; the header is omitted when absent.

resourceId?:

string
End-user resource key the client acts for, sent as the x-mastra-resource-id header. Connection listings are scoped to global connections plus that resource's connections. Has no environment variable fallback.

baseUrl?:

string
Connect API base URL. Falls back to MASTRA_INTEGRATIONS_API_URL, then the regional default from MASTRA_PLATFORM_REGION (us or eu), then https://integrations.mastra.ai.

fetch?:

typeof globalThis.fetch
Fetch implementation, for testing or custom transports. Defaults to globalThis.fetch.

The resolver
Direct 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 a tools callback, 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:

src/mastra/agents/ops.ts
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 allowTools and disallowTools at one level, invalid ttlMs) throw when you call tools(). 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 Mode
Direct 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.

src/mastra/agents/ops.ts
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,
})
warning

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_connection tool, 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.

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:

src/mastra/agents/ops.ts
// 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 providers
Direct 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 resolution
Direct link to Connection resolution

For each provider present in the project's connections:

  1. An explicit connectionId option wins.
  2. Otherwise, a single active connection is used automatically.
  3. Otherwise the provider is left unpinned and routed per call: the toolset gains a <provider>__list_connections tool, every other tool takes a required connection_name input, and the agent picks a connection per call using the display names list_connections returns. A connection_name that matches no active connection fails that call with unknown_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 providers
Direct 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 variables
Direct link to Environment variables

tools(), channels(), and credential() read these environment variables. Options passed in code take precedence.

VariablePurpose
MASTRA_PLATFORM_ACCESS_TOKENPlatform access token used to authenticate every request
MASTRA_PLATFORM_SECRET_KEYFallback token when MASTRA_PLATFORM_ACCESS_TOKEN is unset
MASTRA_PROJECT_IDProject whose connections to use
MASTRA_ORG_IDOrganization ID, sent as the x-organization-id header when set
MASTRA_PLATFORM_REGIONus 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_URLConnect API base URL. Overrides the region

Errors
Direct link to Errors

Throws MastraConnectError with a code property:

CodeWhen
missing_project_idNo project ID configured
missing_access_tokenNo platform token configured
invalid_optionsUnknown or malformed provider ID, conflicting filters, duplicate or unmatched tool keys or globs, or invalid ttlMs
unauthorizedThe platform rejected the token (401/403)
proxy_errorA proxied provider request failed, with status and detail carrying the provider response
unknown_connectionA tool call supplied a connection_name that matches no active connection
platform_errorAny other platform request failure