|
| 1 | +import OAuthProvider from '@cloudflare/workers-oauth-provider' |
| 2 | +import { McpAgent } from 'agents/mcp' |
| 3 | + |
| 4 | +import { handleApiTokenMode, isApiTokenRequest } from '@repo/mcp-common/src/api-token-mode' |
| 5 | +import { |
| 6 | + createAuthHandlers, |
| 7 | + handleTokenExchangeCallback, |
| 8 | +} from '@repo/mcp-common/src/cloudflare-oauth-handler' |
| 9 | +import { getUserDetails, UserDetails } from '@repo/mcp-common/src/durable-objects/user_details.do' |
| 10 | +import { getEnv } from '@repo/mcp-common/src/env' |
| 11 | +import { getProps } from '@repo/mcp-common/src/get-props' |
| 12 | +import { RequiredScopes } from '@repo/mcp-common/src/scopes' |
| 13 | +import { CloudflareMCPServer } from '@repo/mcp-common/src/server' |
| 14 | +import { registerAccountTools } from '@repo/mcp-common/src/tools/account.tools' |
| 15 | + |
| 16 | +import { MetricsTracker } from '../../../packages/mcp-observability/src' |
| 17 | +import { registerIAMTools } from './tools/iam.tools' |
| 18 | + |
| 19 | +import type { AuthProps } from '@repo/mcp-common/src/cloudflare-oauth-handler' |
| 20 | +import type { Env } from './iam.context' |
| 21 | + |
| 22 | +const env = getEnv<Env>() |
| 23 | + |
| 24 | +export { UserDetails } |
| 25 | + |
| 26 | +const metrics = new MetricsTracker(env.MCP_METRICS, { |
| 27 | + name: env.MCP_SERVER_NAME, |
| 28 | + version: env.MCP_SERVER_VERSION, |
| 29 | +}) |
| 30 | + |
| 31 | +// Context from the auth process, encrypted & stored in the auth token |
| 32 | +// and provided to the DurableMCP as this.props |
| 33 | +type Props = AuthProps |
| 34 | + |
| 35 | +export type State = { activeAccountId: string | null } |
| 36 | + |
| 37 | +export class IAMMCP extends McpAgent<Env, State, Props> { |
| 38 | + _server: CloudflareMCPServer | undefined |
| 39 | + set server(server: CloudflareMCPServer) { |
| 40 | + this._server = server |
| 41 | + } |
| 42 | + get server(): CloudflareMCPServer { |
| 43 | + if (!this._server) { |
| 44 | + throw new Error('Tried to access server before it was initialized') |
| 45 | + } |
| 46 | + |
| 47 | + return this._server |
| 48 | + } |
| 49 | + |
| 50 | + constructor(ctx: DurableObjectState, env: Env) { |
| 51 | + super(ctx, env) |
| 52 | + } |
| 53 | + |
| 54 | + async init() { |
| 55 | + // TODO: Probably we'll want to track account tokens usage through an account identifier at some point |
| 56 | + const props = getProps(this) |
| 57 | + const userId = props.type === 'user_token' ? props.user.id : undefined |
| 58 | + |
| 59 | + this.server = new CloudflareMCPServer({ |
| 60 | + userId, |
| 61 | + wae: this.env.MCP_METRICS, |
| 62 | + serverInfo: { |
| 63 | + name: this.env.MCP_SERVER_NAME, |
| 64 | + version: this.env.MCP_SERVER_VERSION, |
| 65 | + }, |
| 66 | + }) |
| 67 | + registerAccountTools(this) |
| 68 | + |
| 69 | + // Register IAM tools |
| 70 | + registerIAMTools(this) |
| 71 | + } |
| 72 | + |
| 73 | + async getActiveAccountId() { |
| 74 | + try { |
| 75 | + const props = getProps(this) |
| 76 | + // account tokens are scoped to one account |
| 77 | + if (props.type === 'account_token') { |
| 78 | + return props.account.id |
| 79 | + } |
| 80 | + // Get UserDetails Durable Object based off the userId and retrieve the activeAccountId from it |
| 81 | + // we do this so we can persist activeAccountId across sessions |
| 82 | + const userDetails = getUserDetails(env, props.user.id) |
| 83 | + return await userDetails.getActiveAccountId() |
| 84 | + } catch (e) { |
| 85 | + this.server.recordError(e) |
| 86 | + return null |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + async setActiveAccountId(accountId: string) { |
| 91 | + try { |
| 92 | + const props = getProps(this) |
| 93 | + // account tokens are scoped to one account |
| 94 | + if (props.type === 'account_token') { |
| 95 | + return |
| 96 | + } |
| 97 | + const userDetails = getUserDetails(env, props.user.id) |
| 98 | + await userDetails.setActiveAccountId(accountId) |
| 99 | + } catch (e) { |
| 100 | + this.server.recordError(e) |
| 101 | + } |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +const IdentityManagementScopes = { |
| 106 | + ...RequiredScopes, |
| 107 | + // User-level scopes for token management |
| 108 | + 'user:token:read': 'See your API tokens and their permissions.', |
| 109 | + 'user:token:write': 'Create, edit, and delete your API tokens.', |
| 110 | + // Account-level scopes for member management |
| 111 | + 'account:read': 'See your account info such as account details, analytics, and memberships.', |
| 112 | + 'account:member:read': 'See account members and their roles.', |
| 113 | + 'account:member:write': 'Add, update, and remove account members.', |
| 114 | + 'account:role:read': 'See available roles and permissions for your account.', |
| 115 | +} as const |
| 116 | + |
| 117 | +export default { |
| 118 | + fetch: async (req: Request, env: Env, ctx: ExecutionContext) => { |
| 119 | + if (await isApiTokenRequest(req, env)) { |
| 120 | + return await handleApiTokenMode(IAMMCP, req, env, ctx) |
| 121 | + } |
| 122 | + |
| 123 | + return new OAuthProvider({ |
| 124 | + apiHandlers: { |
| 125 | + '/mcp': IAMMCP.serve('/mcp'), |
| 126 | + '/sse': IAMMCP.serveSSE('/sse'), |
| 127 | + }, |
| 128 | + defaultHandler: createAuthHandlers({ scopes: IdentityManagementScopes, metrics }), |
| 129 | + authorizeEndpoint: '/oauth/authorize', |
| 130 | + tokenEndpoint: '/token', |
| 131 | + tokenExchangeCallback: (options) => |
| 132 | + handleTokenExchangeCallback( |
| 133 | + options, |
| 134 | + env.CLOUDFLARE_CLIENT_ID, |
| 135 | + env.CLOUDFLARE_CLIENT_SECRET |
| 136 | + ), |
| 137 | + // Cloudflare access token TTL |
| 138 | + accessTokenTTL: 3600, |
| 139 | + refreshTokenTTL: 2592000, // 30 days |
| 140 | + // TODO: Remove after 2026-05-01 — all pre-0.4.0 grants will have expired by then |
| 141 | + resourceMatchOriginOnly: true, |
| 142 | + clientRegistrationEndpoint: '/register', |
| 143 | + }).fetch(req, env, ctx) |
| 144 | + }, |
| 145 | +} |
0 commit comments