|
| 1 | +import OAuthProvider from '@cloudflare/workers-oauth-provider' |
| 2 | +import { McpAgent } from 'agents/mcp' |
| 3 | + |
| 4 | +import { |
| 5 | + createAuthHandlers, |
| 6 | + handleTokenExchangeCallback, |
| 7 | +} from '@repo/mcp-common/src/cloudflare-oauth-handler' |
| 8 | +import { handleDevMode } from '@repo/mcp-common/src/dev-mode' |
| 9 | +import { getUserDetails, UserDetails } from '@repo/mcp-common/src/durable-objects/user_details' |
| 10 | +import { getEnv } from '@repo/mcp-common/src/env' |
| 11 | +import { RequiredScopes } from '@repo/mcp-common/src/scopes' |
| 12 | +import { initSentryWithUser } from '@repo/mcp-common/src/sentry' |
| 13 | +import { CloudflareMCPServer } from '@repo/mcp-common/src/server' |
| 14 | +import { registerAccountTools } from '@repo/mcp-common/src/tools/account' |
| 15 | +import { registerWorkersTools } from '@repo/mcp-common/src/tools/worker' |
| 16 | + |
| 17 | +import { MetricsTracker } from '../../../packages/mcp-observability/src' |
| 18 | +import { registerObservabilityTools } from './tools/observability' |
| 19 | + |
| 20 | +import type { AuthProps } from '@repo/mcp-common/src/cloudflare-oauth-handler' |
| 21 | +import type { Env } from './context' |
| 22 | + |
| 23 | +export { UserDetails } |
| 24 | + |
| 25 | +const env = getEnv<Env>() |
| 26 | + |
| 27 | +const metrics = new MetricsTracker(env.MCP_METRICS, { |
| 28 | + name: env.MCP_SERVER_NAME, |
| 29 | + version: env.MCP_SERVER_VERSION, |
| 30 | +}) |
| 31 | + |
| 32 | +// Context from the auth process, encrypted & stored in the auth token |
| 33 | +// and provided to the DurableMCP as this.props |
| 34 | +type Props = AuthProps |
| 35 | + |
| 36 | +type State = { activeAccountId: string | null } |
| 37 | + |
| 38 | +export class ObservabilityMCP extends McpAgent<Env, State, Props> { |
| 39 | + _server: CloudflareMCPServer | undefined |
| 40 | + set server(server: CloudflareMCPServer) { |
| 41 | + this._server = server |
| 42 | + } |
| 43 | + get server(): CloudflareMCPServer { |
| 44 | + if (!this._server) { |
| 45 | + throw new Error('Tried to access server before it was initialized') |
| 46 | + } |
| 47 | + |
| 48 | + return this._server |
| 49 | + } |
| 50 | + |
| 51 | + async init() { |
| 52 | + this.server = new CloudflareMCPServer({ |
| 53 | + userId: this.props.user.id, |
| 54 | + wae: this.env.MCP_METRICS, |
| 55 | + serverInfo: { |
| 56 | + name: this.env.MCP_SERVER_NAME, |
| 57 | + version: this.env.MCP_SERVER_VERSION, |
| 58 | + }, |
| 59 | + sentry: initSentryWithUser(env, this.ctx, this.props.user.id), |
| 60 | + options: { |
| 61 | + instructions: `# Cloudflare Workers Observability Tool |
| 62 | + * A cloudflare worker is a serverless function |
| 63 | + * Workers Observability is the tool to inspect the logs for your cloudflare Worker |
| 64 | + * Each log is a structured JSON payload with keys and values |
| 65 | +
|
| 66 | +
|
| 67 | + This server allows you to analyze your Cloudflare Workers logs and metrics. |
| 68 | + `, |
| 69 | + }, |
| 70 | + }) |
| 71 | + |
| 72 | + registerAccountTools(this) |
| 73 | + |
| 74 | + // Register Cloudflare Workers tools |
| 75 | + registerWorkersTools(this) |
| 76 | + |
| 77 | + // Register Cloudflare Workers logs tools |
| 78 | + registerObservabilityTools(this) |
| 79 | + } |
| 80 | + |
| 81 | + async getActiveAccountId() { |
| 82 | + try { |
| 83 | + // Get UserDetails Durable Object based off the userId and retrieve the activeAccountId from it |
| 84 | + // we do this so we can persist activeAccountId across sessions |
| 85 | + const userDetails = getUserDetails(env, this.props.user.id) |
| 86 | + return await userDetails.getActiveAccountId() |
| 87 | + } catch (e) { |
| 88 | + this.server.recordError(e) |
| 89 | + return null |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + async setActiveAccountId(accountId: string) { |
| 94 | + try { |
| 95 | + const userDetails = getUserDetails(env, this.props.user.id) |
| 96 | + await userDetails.setActiveAccountId(accountId) |
| 97 | + } catch (e) { |
| 98 | + this.server.recordError(e) |
| 99 | + } |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +const ObservabilityScopes = { |
| 104 | + ...RequiredScopes, |
| 105 | + 'account:read': 'See your account info such as account details, analytics, and memberships.', |
| 106 | + 'workers:write': |
| 107 | + 'See and change Cloudflare Workers data such as zones, KV storage, namespaces, scripts, and routes.', |
| 108 | + 'workers_observability:read': 'See observability logs for your account', |
| 109 | +} as const |
| 110 | + |
| 111 | +export default { |
| 112 | + fetch: async (req: Request, env: Env, ctx: ExecutionContext) => { |
| 113 | + if (env.ENVIRONMENT === 'development' && env.DEV_DISABLE_OAUTH === 'true') { |
| 114 | + return await handleDevMode(ObservabilityMCP, req, env, ctx) |
| 115 | + } |
| 116 | + |
| 117 | + return new OAuthProvider({ |
| 118 | + apiHandlers: { |
| 119 | + '/mcp': ObservabilityMCP.serve('/mcp'), |
| 120 | + '/sse': ObservabilityMCP.serveSSE('/sse'), |
| 121 | + }, |
| 122 | + // @ts-ignore |
| 123 | + defaultHandler: createAuthHandlers({ scopes: ObservabilityScopes, metrics }), |
| 124 | + authorizeEndpoint: '/oauth/authorize', |
| 125 | + tokenEndpoint: '/token', |
| 126 | + tokenExchangeCallback: (options) => |
| 127 | + handleTokenExchangeCallback( |
| 128 | + options, |
| 129 | + env.CLOUDFLARE_CLIENT_ID, |
| 130 | + env.CLOUDFLARE_CLIENT_SECRET |
| 131 | + ), |
| 132 | + // Cloudflare access token TTL |
| 133 | + accessTokenTTL: 3600, |
| 134 | + clientRegistrationEndpoint: '/register', |
| 135 | + }).fetch(req, env, ctx) |
| 136 | + }, |
| 137 | +} |
0 commit comments