谷歌认证mcp
用于MCP(模型上下文协议)服务器的简单、健壮和安全的Google OAuth 2.0身份验证包。以最少的配置提供自动令牌管理、安全的本地存储和自动令牌刷新。
特性
- 简单设置:1-2行用于基本身份验证
- 自动令牌管理:使用5分钟缓冲区处理令牌刷新
- 安全存储:以0o600权限存储的令牌(仅限所有者读/写)
- 稳健的错误处理:带有重试逻辑的键入错误
- TypeScript支持:具有严格类型的完全TypeScript支持
- 最小依赖性:只有必要的Google身份验证库
- 可扩展:用于未来远程存储的可插拔存储接口
安装
npm install google-auth-mcpbun install google-auth-mcp先决条件
- Node.js>=22 (需要ESM支持)
- 谷歌云控制台设置:
- 在中创建项目 谷歌云控制台 - 启用要使用的API(例如,YouTube API、Drive API) - 为“桌面应用程序”创建OAuth 2.0客户端ID凭据 - 下载 credentials.json 文件
快速开始
1.基本用法
放置您的 credentials.json 将文件放在项目根目录中,然后:
import { createAuth } from 'google-auth-mcp';
// Create auth instance
const auth = createAuth({
scopes: [
'https://www.googleapis.com/auth/youtube.readonly',
'https://www.googleapis.com/auth/drive.metadata.readonly'
]
});
// Get authorization header for API requests
const headers = await auth.getAuthHeader();
// Returns: { Authorization: 'Bearer ya29.a0...' }
// Use with fetch
const response = await fetch('https://www.googleapis.com/youtube/v3/channels?part=snippet&mine=true', {
headers: await auth.getAuthHeader()
});2.MCP服务器集成
import { createAuth, GoogleAuthMCP } from 'google-auth-mcp';
class MyMCPServer {
private auth: GoogleAuthMCP;
constructor() {
this.auth = createAuth({
scopes: ['https://www.googleapis.com/auth/youtube.readonly']
});
}
async handleYouTubeRequest() {
try {
// The first call will trigger browser-based OAuth flow
const headers = await this.auth.getAuthHeader();
const response = await fetch('https://www.googleapis.com/youtube/v3/channels?part=snippet&mine=true', {
headers
});
return await response.json();
} catch (error) {
console.error('YouTube API request failed:', error);
throw error;
}
}
}api参考
createAuth(options: AuthOptions): GoogleAuthMCP
创建新的身份验证实例。
身份验证选项
interface AuthOptions {
scopes: string[]; // Required: OAuth scopes
credentialsPath?: string; // Default: './credentials.json'
tokenPath?: string; // Default: './tokens/default.token.json'
storage?: Storage; // Custom storage implementation
accountId?: string; // For future multi-account support
logger?: Pick; // Default: console
}GoogleAuthMCP方法
getAuthHeader(): Promise-获取HTTP请求的授权标头getAccessToken(): Promise-获取原始访问令牌getClient(): Promise-获取底层OAuth2ClientisAuthenticated(): Promise-检查当前是否已通过身份验证signIn(): Promise-强制重新身份验证signOut(): Promise-注销并撤销代币
配置示例
自定义路径
const auth = createAuth({
scopes: ['https://www.googleapis.com/auth/drive.readonly'],
credentialsPath: './config/google-credentials.json',
tokenPath: './config/tokens/drive.token.json'
});定制存储(未来:远程存储)
import { Storage, TokenData, CredentialsJson } from 'google-auth-mcp';
class DatabaseStorage implements Storage {
async readCredentials(): Promise {
// Read from database
}
async readToken(accountId?: string): Promise {
// Read from database
}
async writeToken(token: TokenData, accountId?: string): Promise {
// Write to database
}
async deleteToken(accountId?: string): Promise {
// Delete from database
}
}
const auth = createAuth({
scopes: ['https://www.googleapis.com/auth/drive.readonly'],
storage: new DatabaseStorage()
});身份验证流程
- 第一次:打开浏览器以获得Google OAuth同意,在本地保存令牌
- 后续通话:使用保存的令牌,在需要时自动刷新
- 令牌刷新:使用指数退避重试逻辑自动处理
- 错误恢复:清除常见问题的错误消息
错误处理
import {
AuthenticationError,
TokenExpiredError,
StorageError
} from 'google-auth-mcp';
try {
const headers = await auth.getAuthHeader();
} catch (error) {
if (error instanceof TokenExpiredError) {
console.log('Token expired, trying to sign in again...');
await auth.signIn();
} else if (error instanceof StorageError) {
console.log('Storage issue:', error.message);
} else if (error instanceof AuthenticationError) {
console.log('Authentication failed:', error.message);
}
}安全功能
- 保护文件权限:使用0o600创建的令牌文件(仅限所有者读/写)
- 无秘密日志记录:从未记录的令牌和秘密
- 路径安全:用途
path.resolve()防止遍历攻击 - 自动刷新:令牌在到期前5分钟刷新
常见OAuth作用域
// YouTube
'https://www.googleapis.com/auth/youtube.readonly'
'https://www.googleapis.com/auth/youtube'
// Google Drive
'https://www.googleapis.com/auth/drive.readonly'
'https://www.googleapis.com/auth/drive.file'
'https://www.googleapis.com/auth/drive'
// Gmail
'https://www.googleapis.com/auth/gmail.readonly'
'https://www.googleapis.com/auth/gmail.send'
// Calendar
'https://www.googleapis.com/auth/calendar.readonly'
'https://www.googleapis.com/auth/calendar'故障排除
“未收到刷新令牌”
这通常发生在您之前已授权应用程序的情况下。解决:
- 删除现有令牌文件:
rm -rf ./tokens/ - 取消访问 Google帐号设置
- 重新运行应用程序
“找不到凭据文件”
确保 credentials.json 位置正确:
ls -la credentials.json“凭据无效.json”
验证凭据文件的结构是否正确:
{
"installed": {
"client_id": "your-client-id",
"client_secret": "your-client-secret",
"redirect_uris": ["http://localhost"]
}
}文件结构
your-project/
├── credentials.json # Google OAuth credentials
├── tokens/
│ └── default.token.json # Saved auth tokens (auto-created)
└── your-code.js需求
- Node.js>=18(ESM支持)
- 使用OAuth 2.0凭据的Google Cloud Console项目
- 用于初始身份验证和令牌刷新的互联网接入
许可证
麻省理工学院
贡献
问题和拉取请求欢迎访问
