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.
ParametersDirect link to Parameters
connectionId:
options?:
invalid_options is thrown before any request is sent. The value is sent as the x-mastra-resource-id header, takes precedence over client.resourceId, and the platform returns not found for a resource-scoped connection when it's missing or doesn't match.Credential handlingDirect 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.
ErrorsDirect link to Errors
Throws MastraConnectError with a code property:
| Code | When |
|---|---|
invalid_options | An option is invalid, for example an empty resourceId or one longer than 256 characters after trimming |
missing_access_token | No platform token configured |
connection_not_found | The connection doesn't exist or isn't accessible |
unsupported_credential_type | The connection's credential type can't be returned |
unauthorized | The platform rejected the token (401/403) |
platform_error | Any 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 |