Skip to content

Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.

fix(mcp-oauth-cloudflare): Add configurable scopes and refresh token support

Jez4f4eb17d2de7
diff --git a/skills/mcp-oauth-cloudflare/SKILL.md b/skills/mcp-oauth-cloudflare/SKILL.md
index 6be5c866..7a09df52 100644
--- a/skills/mcp-oauth-cloudflare/SKILL.md
+++ b/skills/mcp-oauth-cloudflare/SKILL.md
@@ -133,10 +133,29 @@ echo "YOUR_GOOGLE_CLIENT_SECRET" | npx wrangler secret put GOOGLE_CLIENT_SECRET
# Cookie encryption key (32+ chars)
python3 -c "import secrets; print(secrets.token_urlsafe(32))" | npx wrangler secret put COOKIE_ENCRYPTION_KEY
+# Optional: Custom Google OAuth scopes (default: 'openid email profile')
+# See "Common Google Scopes" section below for scope recipes
+echo "openid email profile https://www.googleapis.com/auth/drive" | npx wrangler secret put GOOGLE_SCOPES
+
# Deploy to activate secrets
npx wrangler deploy
```
+### 5. Type Definitions (Optional but Recommended)
+
+Copy `templates/env.d.ts` to `src/env.d.ts` for TypeScript type support:
+
+```typescript
+interface Env {
+ GOOGLE_CLIENT_ID: string;
+ GOOGLE_CLIENT_SECRET: string;
+ COOKIE_ENCRYPTION_KEY: string;
+ GOOGLE_SCOPES?: string; // Optional: Override default scopes
+ OAUTH_KV: KVNamespace;
+ MCP_OBJECT: DurableObjectNamespace;
+}
+```
+
## Implementation Guide
### Main Entry Point (index.ts)
@@ -155,6 +174,7 @@ type Props = {
name: string;
picture?: string;
accessToken: string;
+ refreshToken?: string; // Available on first auth with access_type=offline
};
export class MyMcpServer extends McpAgent<Env, Record<string, never>, Props> {
@@ -313,6 +333,9 @@ app.get('/callback', async (c) => {
});
async function redirectToGoogle(request: Request, stateToken: string, headers: Record<string, string> = {}) {
+ // Scopes configurable via GOOGLE_SCOPES env var (see "Common Google Scopes" section)
+ const scopes = env.GOOGLE_SCOPES || 'openid email profile';
+
return new Response(null, {
status: 302,
headers: {
@@ -320,7 +343,7 @@ async function redirectToGoogle(request: Request, stateToken: string, headers: R
location: getUpstreamAuthorizeUrl({
client_id: env.GOOGLE_CLIENT_ID,
redirect_uri: new URL('/callback', request.url).href,
- scope: 'openid email profile',
+ scope: scopes,
state: stateToken,
upstream_url: 'https://accounts.google.com/o/oauth2/v2/auth',
}),
@@ -448,6 +471,45 @@ export async function addApprovedClient(request: Request, clientId: string, cook
6. Add authorized redirect URI: `https://your-worker.workers.dev/callback`
7. Copy Client ID and Client Secret
+## Common Google Scopes
+
+Configure scopes via the `GOOGLE_SCOPES` environment variable or modify the `redirectToGoogle` function.
+
+| Use Case | Scopes |
+|----------|--------|
+| Basic user info (default) | `openid email profile` |
+| Google Drive (full access) | `openid email profile https://www.googleapis.com/auth/drive` |
+| Google Drive (file-level only) | `openid email profile https://www.googleapis.com/auth/drive.file` |
+| Google Docs | `openid email profile https://www.googleapis.com/auth/documents` |
+| Google Docs + Drive | `openid email profile https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/documents` |
+| Gmail (read/send) | `openid email profile https://www.googleapis.com/auth/gmail.modify` |
+| Gmail (read only) | `openid email profile https://www.googleapis.com/auth/gmail.readonly` |
+| Google Calendar | `openid email profile https://www.googleapis.com/auth/calendar` |
+| Google Sheets | `openid email profile https://www.googleapis.com/auth/spreadsheets` |
+| Google Slides | `openid email profile https://www.googleapis.com/auth/presentations` |
+| YouTube Data | `openid email profile https://www.googleapis.com/auth/youtube` |
+
+**Setting Scopes:**
+
+```bash
+# Option 1: Via environment variable (recommended for flexibility)
+echo "openid email profile https://www.googleapis.com/auth/drive" | npx wrangler secret put GOOGLE_SCOPES
+
+# Option 2: In wrangler.jsonc (for non-sensitive scopes)
+{
+ "vars": {
+ "GOOGLE_SCOPES": "openid email profile https://www.googleapis.com/auth/drive"
+ }
+}
+```
+
+**Important Notes:**
+
+- Always include `openid email profile` - required for user identification
+- Additional scopes must be enabled in Google Cloud Console (APIs & Services → Library)
+- Some scopes require OAuth consent screen verification for production use
+- `drive.file` only accesses files the app created or user explicitly opened with it
+
## Common Issues
### "Invalid state" Error
@@ -492,6 +554,7 @@ export async function addApprovedClient(request: Request, clientId: string, cook
| `GOOGLE_CLIENT_ID` | OAuth app ID | Google Cloud Console |
| `GOOGLE_CLIENT_SECRET` | OAuth app secret | Google Cloud Console |
| `COOKIE_ENCRYPTION_KEY` | Sign approval cookies | `secrets.token_urlsafe(32)` |
+| `GOOGLE_SCOPES` (optional) | Override default OAuth scopes | See "Common Google Scopes" section |
## Token Efficiency
@@ -506,6 +569,7 @@ export async function addApprovedClient(request: Request, clientId: string, cook
3. **Token theft** - Session binding via SHA-256
4. **Missing DCR** - OAuthProvider handles automatically
5. **Cookie tampering** - HMAC signatures
+6. **Hardcoded scopes** - Configurable via environment variable
## References
diff --git a/skills/mcp-oauth-cloudflare/templates/env.d.ts b/skills/mcp-oauth-cloudflare/templates/env.d.ts
new file mode 100644
index 00000000..811d21cb
--- /dev/null
+++ b/skills/mcp-oauth-cloudflare/templates/env.d.ts
@@ -0,0 +1,31 @@
+/**
+ * Environment type definition for MCP OAuth Cloudflare Worker
+ *
+ * TEMPLATE: Add your custom bindings and variables here
+ */
+
+interface Env {
+ // === Required Secrets (set via `wrangler secret put`) ===
+ GOOGLE_CLIENT_ID: string;
+ GOOGLE_CLIENT_SECRET: string;
+ COOKIE_ENCRYPTION_KEY: string;
+
+ // === Optional: Custom Google Scopes ===
+ // Set this to override the default 'openid email profile' scopes
+ // Example: 'openid email profile https://www.googleapis.com/auth/drive'
+ GOOGLE_SCOPES?: string;
+
+ // === Bindings ===
+ OAUTH_KV: KVNamespace;
+ MCP_OBJECT: DurableObjectNamespace;
+
+ // === Add your custom bindings below ===
+ // MY_KV: KVNamespace;
+ // MY_D1: D1Database;
+ // MY_R2: R2Bucket;
+ // MY_AI: Ai;
+}
+
+declare module 'cloudflare:workers' {
+ interface Env extends Env {}
+}
diff --git a/skills/mcp-oauth-cloudflare/templates/oauth/google-handler.ts b/skills/mcp-oauth-cloudflare/templates/oauth/google-handler.ts
index 67e12dfa..887c3419 100644
--- a/skills/mcp-oauth-cloudflare/templates/oauth/google-handler.ts
+++ b/skills/mcp-oauth-cloudflare/templates/oauth/google-handler.ts
@@ -118,19 +118,35 @@ app.post('/authorize', async (c) => {
/**
* Redirect to Google OAuth
+ *
+ * TEMPLATE: Customize scopes for your use case
+ * Default scopes provide basic user info (id, email, name, picture)
+ *
+ * Common scopes:
+ * - 'openid email profile' (default) - Basic user info
+ * - 'openid email profile https://www.googleapis.com/auth/drive' - Google Drive
+ * - 'openid email profile https://www.googleapis.com/auth/documents' - Google Docs
+ * - 'openid email profile https://www.googleapis.com/auth/gmail.modify' - Gmail
+ * - 'openid email profile https://www.googleapis.com/auth/calendar' - Calendar
+ * - 'openid email profile https://www.googleapis.com/auth/spreadsheets' - Sheets
+ *
+ * Set via environment variable GOOGLE_SCOPES or modify the default below
*/
async function redirectToGoogle(
request: Request,
stateToken: string,
headers: Record<string, string> = {}
) {
+ // TODO: Customize scopes for your use case (or set GOOGLE_SCOPES env var)
+ const scopes = env.GOOGLE_SCOPES || 'openid email profile';
+
return new Response(null, {
headers: {
...headers,
location: getUpstreamAuthorizeUrl({
client_id: env.GOOGLE_CLIENT_ID,
redirect_uri: new URL('/callback', request.url).href,
- scope: 'openid email profile',
+ scope: scopes,
state: stateToken,
upstream_url: 'https://accounts.google.com/o/oauth2/v2/auth',
}),
@@ -161,8 +177,8 @@ app.get('/callback', async (c) => {
return c.text('Invalid OAuth request data', 400);
}
- // Exchange code for access token
- const [accessToken, errResponse] = await fetchUpstreamAuthToken({
+ // Exchange code for access token (and optional refresh token)
+ const [tokens, errResponse] = await fetchUpstreamAuthToken({
client_id: c.env.GOOGLE_CLIENT_ID,
client_secret: c.env.GOOGLE_CLIENT_SECRET,
code: c.req.query('code'),
@@ -173,7 +189,7 @@ app.get('/callback', async (c) => {
if (errResponse) return errResponse;
// Fetch user info from Google
- const user = await fetchGoogleUserInfo(accessToken);
+ const user = await fetchGoogleUserInfo(tokens.accessToken);
if (!user) {
return c.text('Failed to fetch user info', 500);
}
@@ -186,7 +202,8 @@ app.get('/callback', async (c) => {
label: name || email,
},
props: {
- accessToken,
+ accessToken: tokens.accessToken,
+ refreshToken: tokens.refreshToken, // Available on first auth with access_type=offline
email,
id,
name,
diff --git a/skills/mcp-oauth-cloudflare/templates/oauth/utils.ts b/skills/mcp-oauth-cloudflare/templates/oauth/utils.ts
index 1da6d554..3f4cc19d 100644
--- a/skills/mcp-oauth-cloudflare/templates/oauth/utils.ts
+++ b/skills/mcp-oauth-cloudflare/templates/oauth/utils.ts
@@ -15,6 +15,7 @@ export type Props = {
name: string; // User's display name
picture?: string; // Profile picture URL
accessToken: string; // Google access token (for Google API calls)
+ refreshToken?: string; // Google refresh token (for long-lived access)
};
/**
@@ -50,10 +51,21 @@ export function getUpstreamAuthorizeUrl({
return upstream.href;
}
+/**
+ * Token response from Google OAuth
+ */
+export type TokenResponse = {
+ accessToken: string;
+ refreshToken?: string; // Only returned on first authorization with access_type=offline
+};
+
/**
* Fetches an authorization token from Google
*
- * @returns Tuple of [accessToken, null] on success or [null, Response] on error
+ * @returns Tuple of [TokenResponse, null] on success or [null, Response] on error
+ *
+ * Note: refresh_token is only returned on first authorization when access_type=offline.
+ * Subsequent authorizations won't include it unless the user revokes access and reauthorizes.
*/
export async function fetchUpstreamAuthToken({
client_id,
@@ -67,7 +79,7 @@ export async function fetchUpstreamAuthToken({
client_secret: string;
redirect_uri: string;
client_id: string;
-}): Promise<[string, null] | [null, Response]> {
+}): Promise<[TokenResponse, null] | [null, Response]> {
if (!code) {
return [null, new Response('Missing code', { status: 400 })];
}
@@ -92,7 +104,11 @@ export async function fetchUpstreamAuthToken({
return [null, new Response('Failed to fetch access token', { status: 500 })];
}
- const body = await resp.json() as { access_token?: string; error?: string };
+ const body = await resp.json() as {
+ access_token?: string;
+ refresh_token?: string;
+ error?: string;
+ };
if (body.error) {
console.error('Google OAuth error:', body.error);
@@ -104,7 +120,10 @@ export async function fetchUpstreamAuthToken({
return [null, new Response('Missing access token', { status: 400 })];
}
- return [accessToken, null];
+ return [{
+ accessToken,
+ refreshToken: body.refresh_token, // May be undefined for subsequent auths
+ }, null];
}
/**