Skip to content

Init DEX MCP #96

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

Merged
merged 7 commits into from
Apr 29, 2025
Merged
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/dex-analysis/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/** @type {import("eslint").Linter.Config} */
module.exports = {
root: true,
extends: ['@repo/eslint-config/default.cjs'],
}
126 changes: 126 additions & 0 deletions apps/dex-analysis/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
# Model Context Protocol (MCP) Server + Cloudflare OAuth

This is a [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) server that supports remote MCP connections, with Cloudflare OAuth built-in.

You can deploy it to your own Cloudflare account, and after you create your own Cloudflare OAuth client app, you'll have a fully functional remote MCP server that you can build off. Users will be able to connect to your MCP server by signing in with their Cloudflare account.

You can use this as a reference example for how to integrate other OAuth providers with an MCP server deployed to Cloudflare, using the [`workers-oauth-provider` library](https://github.com/cloudflare/workers-oauth-provider).

The MCP server (powered by [Cloudflare Workers](https://developers.cloudflare.com/workers/)):

- Acts as OAuth _Server_ to your MCP clients
- Acts as OAuth _Client_ to your _real_ OAuth server (in this case, Cloudflare)

## Getting Started

### For Production

- Set secrets via Wrangler

```bash
wrangler secret put CLOUDFLARE_CLIENT_ID
wrangler secret put CLOUDFLARE_CLIENT_SECRET
```

#### Set up a KV namespace

- Create the KV namespace:
`wrangler kv:namespace create "OAUTH_KV"`
- Update the Wrangler file with the KV ID

#### Deploy & Test

Deploy the MCP server to make it available on your workers.dev domain
` wrangler deploy`

Test the remote server using [Inspector](https://modelcontextprotocol.io/docs/tools/inspector):

```
npx @modelcontextprotocol/inspector@latest
```

Enter `https://mcp-cloudflare-staging.<your-subdomain>.workers.dev/sse` and hit connect. Once you go through the authentication flow, you'll see the Tools working:

<img width="640" alt="image" src="https://github.com/user-attachments/assets/7973f392-0a9d-4712-b679-6dd23f824287" />

You now have a remote MCP server deployed!

#### Access the remote MCP server from Claude Desktop

Open Claude Desktop and navigate to Settings -> Developer -> Edit Config. This opens the configuration file that controls which MCP servers Claude can access.

Replace the content with the following configuration. Once you restart Claude Desktop, a browser window will open showing your OAuth login page. Complete the authentication flow to grant Claude access to your MCP server. After you grant access, the tools will become available for you to use.

```
{
"mcpServers": {
"cloudflare": {
"command": "npx",
"args": [
"mcp-remote",
"https://<your-subdomain>.workers.dev/sse"
]
}
}
}
```

Once the Tools (under 🔨) show up in the interface, you can ask Claude to use them. For example: "Could you use the math tool to add 23 and 19?". Claude should invoke the tool and show the result generated by the MCP server.

### For Local Development

If you'd like to iterate and test your MCP server, you can do so in local development. This will require you to create another OAuth App on Cloudflare:

- Create a `.dev.vars` file in your project root with:

```
CLOUDFLARE_CLIENT_ID=your_development_cloudflare_client_id
CLOUDFLARE_CLIENT_SECRET=your_development_cloudflare_client_secret
```

#### Develop & Test

Run the server locally to make it available at `http://localhost:8788`
`wrangler dev`

To test the local server, enter `http://localhost:8788/sse` into Inspector and hit connect. Once you follow the prompts, you'll be able to "List Tools".

#### Using Claude and other MCP Clients

When using Claude to connect to your remote MCP server, you may see some error messages. This is because Claude Desktop doesn't yet support remote MCP servers, so it sometimes gets confused. To verify whether the MCP server is connected, hover over the 🔨 icon in the bottom right corner of Claude's interface. You should see your tools available there.

#### Using Cursor and other MCP Clients

To connect Cursor with your MCP server, choose `Type`: "Command" and in the `Command` field, combine the command and args fields into one (e.g. `npx mcp-remote https://<your-worker-name>.<your-subdomain>.workers.dev/sse`).

Note that while Cursor supports HTTP+SSE servers, it doesn't support authentication, so you still need to use `mcp-remote` (and to use a STDIO server, not an HTTP one).

You can connect your MCP server to other MCP clients like Windsurf by opening the client's configuration file, adding the same JSON that was used for the Claude setup, and restarting the MCP client.

## How does it work?

#### OAuth Provider

The OAuth Provider library serves as a complete OAuth 2.1 server implementation for Cloudflare Workers. It handles the complexities of the OAuth flow, including token issuance, validation, and management. In this project, it plays the dual role of:

- Authenticating MCP clients that connect to your server
- Managing the connection to Cloudflare's OAuth services
- Securely storing tokens and authentication state in KV storage

#### Durable MCP

Durable MCP extends the base MCP functionality with Cloudflare's Durable Objects, providing:

- Persistent state management for your MCP server
- Secure storage of authentication context between requests
- Access to authenticated user information via `this.props`
- Support for conditional tool availability based on user identity

#### MCP Remote

The MCP Remote library enables your server to expose tools that can be invoked by MCP clients like the Inspector. It:

- Defines the protocol for communication between clients and your server
- Provides a structured way to define tools
- Handles serialization and deserialization of requests and responses
- Maintains the Server-Sent Events (SSE) connection between clients and your server
33 changes: 33 additions & 0 deletions apps/dex-analysis/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "dex-analysis",
"version": "0.0.1",
"private": true,
"scripts": {
"check:lint": "run-eslint-workers",
"check:types": "run-tsc",
"deploy": "wrangler deploy",
"dev": "wrangler dev",
"start": "wrangler dev",
"cf-typegen": "wrangler types",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We recently removed the now @cloudflare/workers-types in the apps in our monorepo in this #77 and moved towards running wrangler types ( but avoiding codegening env type due to some issues with Env in global declaration .d.ts scope )

Don't have to do this in this PR, but would be great if you could a "context.ts" file that contains your Env interface, and a "types" field in your package.json so turbo will pick it up, and that way we can ensure we're still able to codegen all our types for all our servers in one command!

"test": "vitest run"
},
"dependencies": {
"@cloudflare/workers-oauth-provider": "0.0.3",
"@hono/zod-validator": "0.4.3",
"@modelcontextprotocol/sdk": "1.10.2",
"@repo/mcp-common": "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",
"@cloudflare/workers-types": "4.20250410.0",
"@types/jsonwebtoken": "9.0.9",
"prettier": "3.5.3",
"typescript": "5.5.4",
"vitest": "3.0.9",
"wrangler": "4.10.0"
}
}
47 changes: 47 additions & 0 deletions apps/dex-analysis/src/api/dex.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { fetchCloudflareApi } from '@repo/mcp-common/src/cloudflare-api'

export const fetchDexTestAnalyzation = async ({
dexTestId,
accountId,
accessToken,
timeStart,
timeEnd,
}: {
dexTestId: string
accountId: string
accessToken: string
timeStart: string
timeEnd: string
}) => {
return await fetchCloudflareApi({
endpoint: `/dex/test-results/by-quartile?from=${timeStart}&to=${timeEnd}&limit=4&testId=${dexTestId}`,
accountId,
apiToken: accessToken,
options: {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
},
})
}

export const fetchDexTests = async ({
accountId,
accessToken,
}: {
accountId: string
accessToken: string
}) => {
return await fetchCloudflareApi({
endpoint: '/dex/tests/overview?per_page=50',
accountId,
apiToken: accessToken,
options: {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
},
})
}
109 changes: 109 additions & 0 deletions apps/dex-analysis/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import OAuthProvider from '@cloudflare/workers-oauth-provider'
import { McpAgent } from 'agents/mcp'
import { env } from 'cloudflare:workers'

import {
createAuthHandlers,
handleTokenExchangeCallback,
} from '@repo/mcp-common/src/cloudflare-oauth-handler'
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'
import { MetricsTracker } from '@repo/mcp-observability'

import { registerDEXTools } from './tools/dex'

import type { AccountSchema, UserSchema } from '@repo/mcp-common/src/cloudflare-oauth-handler'

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
export type Props = {
accessToken: string
user: UserSchema['result']
accounts: AccountSchema['result']
}

export type State = { activeAccountId: string | null }

export class CloudflareDEXMCP 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)
registerDEXTools(this)
}

initialState: State = {
activeAccountId: null,
}

getActiveAccountId() {
// TODO: Figure out why this fail sometimes, and why we need to wrap this in a try catch
try {
return this.state.activeAccountId ?? null
} catch (e) {
return null
}
}

setActiveAccountId(accountId: string) {
// TODO: Figure out why this fail sometimes, and why we need to wrap this in a try catch
try {
this.setState({
...this.state,
activeAccountId: accountId,
})
} catch (e) {
return null
}
}
}

const DexScopes = {
...RequiredScopes,
'dex:read': 'See Cloudflare Cloudflare DEX data for your account',
offline_access: 'Grants refresh tokens for long-lived access.',
} as const

export default new OAuthProvider({
apiRoute: '/sse',
apiHandler: CloudflareDEXMCP.mount('/sse'),
// @ts-ignore
defaultHandler: createAuthHandlers({ scopes: DexScopes, 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',
})
Loading
Loading