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.
ParametersParameters的直接链接
connectionId:
options?:
Credential handlingCredential 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.
ErrorsErrors的直接链接
Throws MastraConnectError with a code property:
| Code | When |
|---|---|
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 |