|
| 1 | +import OAuthProvider from '@cloudflare/workers-oauth-provider' |
| 2 | +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' |
| 3 | +import { createMcpHandler } from 'agents/mcp' |
| 4 | + |
| 5 | +import { isApiTokenRequest } from '@repo/mcp-common/src/api-token-mode' |
| 6 | +import { |
| 7 | + createAuthHandlers, |
| 8 | + handleTokenExchangeCallback, |
| 9 | +} from '@repo/mcp-common/src/cloudflare-oauth-handler' |
| 10 | +import { getEnv } from '@repo/mcp-common/src/env' |
| 11 | +import { RequiredScopes } from '@repo/mcp-common/src/scopes' |
| 12 | +import { MetricsTracker } from '@repo/mcp-observability' |
| 13 | + |
| 14 | +import { registerWebSearchTools } from './tools/websearch.tools' |
| 15 | +import { BASE_INSTRUCTIONS } from './websearch.context' |
| 16 | + |
| 17 | +import type { Env } from './websearch.context' |
| 18 | + |
| 19 | +const env = getEnv<Env>() |
| 20 | + |
| 21 | +const metrics = new MetricsTracker(env.MCP_METRICS, { |
| 22 | + name: env.MCP_SERVER_NAME, |
| 23 | + version: env.MCP_SERVER_VERSION, |
| 24 | +}) |
| 25 | + |
| 26 | +const WebSearchScopes = { |
| 27 | + ...RequiredScopes, |
| 28 | + 'account:read': 'See your account info such as account details, analytics, and memberships.', |
| 29 | + 'websearch.run': 'Grants access to run Cloudflare Web Search queries.', |
| 30 | +} as const |
| 31 | + |
| 32 | +// Stateless: createMcpHandler requires a fresh server instance per request. |
| 33 | +// TODO(RAG-1300): swap back to CloudflareMCPServer (metrics + per-user userId via |
| 34 | +// getMcpAuthContext) once @repo/mcp-common is on a zod 3.25+/SDK 1.29+ compatible stack. |
| 35 | +function createServer(env: Env): McpServer { |
| 36 | + const server = new McpServer( |
| 37 | + { name: env.MCP_SERVER_NAME, version: env.MCP_SERVER_VERSION }, |
| 38 | + { instructions: BASE_INSTRUCTIONS } |
| 39 | + ) |
| 40 | + registerWebSearchTools(server) |
| 41 | + return server |
| 42 | +} |
| 43 | + |
| 44 | +// Stateless streamable-HTTP handler. Reads the access token from ctx.props, |
| 45 | +// set either by the OAuthProvider (OAuth mode) or below (API-token mode). |
| 46 | +function mcpFetch(req: Request, env: Env, ctx: ExecutionContext): Promise<Response> { |
| 47 | + const handler = createMcpHandler(createServer(env), { route: '/mcp' }) |
| 48 | + return handler(req, env, ctx) |
| 49 | +} |
| 50 | + |
| 51 | +function getBearerToken(req: Request, env: Env): string { |
| 52 | + if (env.DEV_CLOUDFLARE_API_TOKEN && env.DEV_DISABLE_OAUTH === 'true') { |
| 53 | + return env.DEV_CLOUDFLARE_API_TOKEN |
| 54 | + } |
| 55 | + const [, token] = (req.headers.get('Authorization') ?? '').split(' ') |
| 56 | + return token ?? '' |
| 57 | +} |
| 58 | + |
| 59 | +export default { |
| 60 | + fetch: async (req: Request, env: Env, ctx: ExecutionContext): Promise<Response> => { |
| 61 | + // Raw Cloudflare API token bearer → skip OAuth, use it directly. |
| 62 | + // OAuth-issued tokens are excluded by isApiTokenRequest and fall through. |
| 63 | + if (await isApiTokenRequest(req, env)) { |
| 64 | + ctx.props = { type: 'api_token', accessToken: getBearerToken(req, env) } |
| 65 | + return mcpFetch(req, env, ctx) |
| 66 | + } |
| 67 | + |
| 68 | + // OAuth mode: advertises the OAuth endpoints and decrypts OAuth-issued |
| 69 | + // tokens into ctx.props.accessToken before delegating to the MCP handler. |
| 70 | + return new OAuthProvider({ |
| 71 | + apiHandlers: { |
| 72 | + '/mcp': { fetch: mcpFetch }, |
| 73 | + }, |
| 74 | + defaultHandler: createAuthHandlers({ scopes: WebSearchScopes, metrics }), |
| 75 | + authorizeEndpoint: '/oauth/authorize', |
| 76 | + tokenEndpoint: '/token', |
| 77 | + tokenExchangeCallback: (options) => |
| 78 | + handleTokenExchangeCallback( |
| 79 | + options, |
| 80 | + env.CLOUDFLARE_CLIENT_ID, |
| 81 | + env.CLOUDFLARE_CLIENT_SECRET |
| 82 | + ), |
| 83 | + // Cloudflare access token TTL |
| 84 | + accessTokenTTL: 3600, |
| 85 | + refreshTokenTTL: 2592000, // 30 days |
| 86 | + // TODO: Remove after 2026-05-01 — all pre-0.4.0 grants will have expired by then |
| 87 | + resourceMatchOriginOnly: true, |
| 88 | + clientRegistrationEndpoint: '/register', |
| 89 | + }).fetch(req, env, ctx) |
| 90 | + }, |
| 91 | +} |
0 commit comments