Create middleware wrapper for single-user authentication This is the CRITICAL method that integrates service account auth into MCP servers
Middleware wraps tool, resource, and prompt handlers and injects authContext into extra parameter. Handlers receive a GoogleAuthProvider via extra.authContext.auth for API calls.
Object with withToolAuth, withResourceAuth, withPromptAuth methods
// Server registration
const authMiddleware = provider.authMiddleware();
const tools = toolFactories.map(f => f()).map(authMiddleware.withToolAuth);
const resources = resourceFactories.map(f => f()).map(authMiddleware.withResourceAuth);
const prompts = promptFactories.map(f => f()).map(authMiddleware.withPromptAuth);
// Tool handler receives auth
async function handler({ id }: In, extra: EnrichedExtra) {
// extra.authContext.auth is a GoogleAuthProvider (from middleware)
const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });
}
Get access token for Google APIs Generates fresh JWT and exchanges for access token on each call
Note: accountId parameter is ignored for service accounts (service account is single static identity)
Optional_accountId: stringGet service account email address Used for account registration and display
Note: accountId parameter is ignored for service accounts
Optional_accountId: stringService account email from key file (e.g., "service-account@project.iam.gserviceaccount.com")
Token provider for the service account, to hand to a Google API client via
attachTokenProvider.
Service account ONLY works with accountId='service-account' (single static identity)
OptionalaccountId: string
Account identifier (must be 'service-account' or undefined)
ServiceAccountProvider implements OAuth2TokenStorageProvider using Google Service Accounts with JWT-based (2-legged OAuth) authentication.
This provider:
Example