Skip to content

Cloudflare Access MCP Server #191

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions apps/cloudflare-one-access/.dev.vars.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
CLOUDFLARE_CLIENT_ID=
CLOUDFLARE_CLIENT_SECRET=
DEV_DISABLE_OAUTH=
DEV_CLOUDFLARE_API_TOKEN=
DEV_CLOUDFLARE_EMAIL=
34 changes: 34 additions & 0 deletions apps/cloudflare-one-access/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "cloudflare-one-access-mcp-server",
"version": "0.0.1",
"private": true,
"scripts": {
"check:lint": "run-eslint-workers",
"check:types": "run-tsc",
"deploy": "run-wrangler-deploy",
"dev": "wrangler dev",
"start": "wrangler dev",
"types": "wrangler types --include-env=false",
"test": "vitest run"
},
"dependencies": {
"@cloudflare/workers-oauth-provider": "0.0.5",
"@hono/zod-validator": "0.4.3",
"@modelcontextprotocol/sdk": "1.10.2",
"@repo/mcp-common": "workspace:*",
"@repo/mcp-observability": "workspace:*",
"agents": "0.0.67",
"cloudflare": "4.2.0",
"hono": "4.7.6",
"zod": "3.24.2"
},
"devDependencies": {
"@cloudflare/vitest-pool-workers": "0.8.14",
"@types/jsonwebtoken": "9.0.9",
"@types/node": "22.14.1",
"prettier": "3.5.3",
"typescript": "5.5.4",
"vitest": "3.0.9",
"wrangler": "4.10.0"
}
}
122 changes: 122 additions & 0 deletions apps/cloudflare-one-access/src/access.app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import OAuthProvider from '@cloudflare/workers-oauth-provider'
import { McpAgent } from 'agents/mcp'

import {
createAuthHandlers,
handleTokenExchangeCallback,
} from '@repo/mcp-common/src/cloudflare-oauth-handler'
import { handleDevMode } from '@repo/mcp-common/src/dev-mode'
import { getUserDetails, UserDetails } from '@repo/mcp-common/src/durable-objects/user_details.do'
import { getEnv } from '@repo/mcp-common/src/env'
import { RequiredScopes } from '@repo/mcp-common/src/scopes'
import { CloudflareMCPServer } from '@repo/mcp-common/src/server'
import { registerAccountTools } from '@repo/mcp-common/src/tools/account.tools'
import { MetricsTracker } from '@repo/mcp-observability'

import { registerZeroTrustAccessTools } from './tools/access.tools'

import type { AuthProps } from '@repo/mcp-common/src/cloudflare-oauth-handler'
import type { Env } from './access.context'

export { UserDetails }

const env = getEnv<Env>()

const metrics = new MetricsTracker(env.MCP_METRICS, {
name: env.MCP_SERVER_NAME,
version: env.MCP_SERVER_VERSION,
})

// Context from the auth process, encrypted & stored in the auth token
// and provided to the DurableMCP as this.props
type Props = AuthProps

type State = { activeAccountId: string | null }

export class ZeroTrustAccessMCP extends McpAgent<Env, State, Props> {
_server: CloudflareMCPServer | undefined
set server(server: CloudflareMCPServer) {
this._server = server
}

get server(): CloudflareMCPServer {
if (!this._server) {
throw new Error('Tried to access server before it was initialized')
}

return this._server
}

constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env)
}

async init() {
this.server = new CloudflareMCPServer({
userId: this.props.user.id,
wae: this.env.MCP_METRICS,
serverInfo: {
name: this.env.MCP_SERVER_NAME,
version: this.env.MCP_SERVER_VERSION,
},
})

registerAccountTools(this)
registerZeroTrustAccessTools(this)
}

async getActiveAccountId() {
try {
// Get UserDetails Durable Object based off the userId and retrieve the activeAccountId from it
// we do this so we can persist activeAccountId across sessions
const userDetails = getUserDetails(env, this.props.user.id)
return await userDetails.getActiveAccountId()
} catch (e) {
this.server.recordError(e)
return null
}
}

async setActiveAccountId(accountId: string) {
try {
const userDetails = getUserDetails(env, this.props.user.id)
await userDetails.setActiveAccountId(accountId)
} catch (e) {
this.server.recordError(e)
}
}
}

const ZeroTrustGatewayScopes = {
...RequiredScopes,
'account:read': 'See your account info such as account details, analytics, and memberships.',
'teams:read': 'See Cloudflare One Resources',
} as const

export default {
fetch: async (req: Request, env: Env, ctx: ExecutionContext) => {
if (env.ENVIRONMENT === 'development' && env.DEV_DISABLE_OAUTH === 'true') {
return await handleDevMode(ZeroTrustAccessMCP, req, env, ctx)
}

return new OAuthProvider({
apiHandlers: {
'/mcp': ZeroTrustAccessMCP.serve('/mcp'),
'/sse': ZeroTrustAccessMCP.serveSSE('/sse'),
},
// @ts-ignore
defaultHandler: createAuthHandlers({ scopes: ZeroTrustAccessScopes, metrics }),
authorizeEndpoint: '/oauth/authorize',
tokenEndpoint: '/token',
tokenExchangeCallback: (options) =>
handleTokenExchangeCallback(
options,
env.CLOUDFLARE_CLIENT_ID,
env.CLOUDFLARE_CLIENT_SECRET
),
// Cloudflare access token TTL
accessTokenTTL: 3600,
clientRegistrationEndpoint: '/register',
}).fetch(req, env, ctx)
},
}
16 changes: 16 additions & 0 deletions apps/cloudflare-one-access/src/access.context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type { UserDetails, ZeroTrustAccessMCP } from './access.app'

export interface Env {
ENVIRONMENT: 'development' | 'staging' | 'production'
MCP_SERVER_NAME: string
MCP_SERVER_VERSION: string
MCP_OBJECT: DurableObjectNamespace<ZeroTrustAccessMCP>
MCP_METRICS: AnalyticsEngineDataset
AI: Ai
CLOUDFLARE_CLIENT_ID: string
CLOUDFLARE_CLIENT_SECRET: string
USER_DETAILS: DurableObjectNamespace<UserDetails>
DEV_DISABLE_OAUTH: string
DEV_CLOUDFLARE_API_TOKEN: string
DEV_CLOUDFLARE_EMAIL: string
}
Loading