Skip to main content

credential()

Fetches the raw credential for a platform connection, for custom interactions the generated toolsets don't cover, such as driving a provider SDK or an MCP server yourself.

import { credential } from '@mastra/connect'

const cred = await credential('c_yourconnectionid')

if (cred.type === 'oauth2') {
startSdkSession(cred.accessToken)
} else if (cred.type === 'api_key') {
startSdkSession(cred.apiKey)
} else if (cred.type === 'two_step') {
startSdkSession(cred.token)
}

Returns: Promise<ConnectionCredential>, a discriminated union:

type ConnectionCredential =
| {
type: 'oauth2'
accessToken: string
expiresAt: string | null
secondaryAccessTokens?: Record<string, { accessToken: string; expiresAt: string | null }>
}
| { type: 'api_key'; apiKey: string }
| { type: 'two_step'; token: string; expiresAt: string | null }

An OAuth2 credential can include secondaryAccessTokens for additional API audiences, keyed by the provider's connection-config field name. Each token has its own expiry.

Most applications should prefer tools(), which keeps credentials entirely on the platform.

Parameters
Direct link to Parameters

connectionId:

string
ID of the connection to fetch credentials for.

options?:

{ client?: ConnectClientOptions }
Optional platform client overrides (accessToken, orgId, baseUrl, fetch). See ConnectClientOptions in tools().

Credential handling
Direct link to Credential handling

Returned credentials grant direct access to the provider account and bypass the proxy's guardrails. Don't log them or embed them in agent output. OAuth2 and two_step tokens can expire. Check their expiresAt fields, including those of secondary access tokens, and re-fetch the credential when needed.

Connections that use credential types this function doesn't support (for example basic auth) throw unsupported_credential_type.

Errors
Direct link to Errors

Throws MastraConnectError with a code property:

CodeWhen
missing_access_tokenNo platform token configured
connection_not_foundThe connection doesn't exist or isn't accessible
unsupported_credential_typeThe connection's credential type can't be returned
unauthorizedThe platform rejected the token (401/403)
platform_errorAny other platform response failure: a non-2xx status or an unparseable body. A network-level fetch failure isn't wrapped and surfaces as the runtime's own error, without a code
On this page