11import OAuthProvider from '@cloudflare/workers-oauth-provider'
2- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
32import { McpAgent } from 'agents/mcp'
43import { env } from 'cloudflare:workers'
54
65import {
76 createAuthHandlers ,
87 handleTokenExchangeCallback ,
98} from '@repo/mcp-common/src/cloudflare-oauth-handler'
9+ import { CloudflareMCPServer } from '@repo/mcp-common/src/server'
1010import { registerAccountTools } from '@repo/mcp-common/src/tools/account'
1111
12+ import { MetricsTracker } from '../../../packages/mcp-observability/src'
1213import { registerDEXTools } from './tools/dex'
1314
1415import type { AccountSchema , UserSchema } from '@repo/mcp-common/src/cloudflare-oauth-handler'
1516
17+ const metrics = new MetricsTracker ( env . MCP_METRICS , {
18+ name : env . MCP_SERVER_NAME ,
19+ version : env . MCP_SERVER_VERSION ,
20+ } )
21+
1622// Context from the auth process, encrypted & stored in the auth token
1723// and provided to the DurableMCP as this.props
1824export type Props = {
@@ -24,22 +30,41 @@ export type Props = {
2430export type State = { activeAccountId : string | null }
2531
2632export class CloudflareDEXMCP extends McpAgent < Env , State , Props > {
27- server = new McpServer ( {
28- name : 'Remote MCP Server with Cloudflare DEX Analysis' ,
29- version : '1.0.0' ,
30- } )
33+ _server : CloudflareMCPServer | undefined
34+ set server ( server : CloudflareMCPServer ) {
35+ this . _server = server
36+ }
3137
32- initialState : State = {
33- activeAccountId : null ,
38+ get server ( ) : CloudflareMCPServer {
39+ if ( ! this . _server ) {
40+ throw new Error ( 'Tried to access server before it was initialized' )
41+ }
42+
43+ return this . _server
44+ }
45+
46+ constructor ( ctx : DurableObjectState , env : Env ) {
47+ super ( ctx , env )
3448 }
3549
3650 async init ( ) {
37- registerAccountTools ( this )
51+ this . server = new CloudflareMCPServer ( {
52+ userId : this . props . user . id ,
53+ wae : this . env . MCP_METRICS ,
54+ serverInfo : {
55+ name : this . env . MCP_SERVER_NAME ,
56+ version : this . env . MCP_SERVER_VERSION ,
57+ } ,
58+ } )
3859
39- // EXAMPLE TOOLS — register your own here
60+ registerAccountTools ( this )
4061 registerDEXTools ( this )
4162 }
4263
64+ initialState : State = {
65+ activeAccountId : null ,
66+ }
67+
4368 getActiveAccountId ( ) {
4469 // TODO: Figure out why this fail sometimes, and why we need to wrap this in a try catch
4570 try {
@@ -74,7 +99,7 @@ export default new OAuthProvider({
7499 // @ts -ignore
75100 apiHandler : CloudflareDEXMCP . mount ( '/sse' ) ,
76101 // @ts -ignore
77- defaultHandler : createAuthHandlers ( { scopes : DexScopes } ) ,
102+ defaultHandler : createAuthHandlers ( { scopes : DexScopes , metrics } ) ,
78103 authorizeEndpoint : '/oauth/authorize' ,
79104 tokenEndpoint : '/token' ,
80105 tokenExchangeCallback : ( options ) =>
0 commit comments