Skip to content

Commit d0866b1

Browse files
Maximo-GukCathy Chijasoncabot
authored
Logpush (copied over from !93) (#101)
* Logpush jobs by accountID * Renamed to logpush and updated local dev handling of token * Fix up wrangler.json, add dev handler, and new createApiHandler for dealing with SSE + Streamable HTTP --------- Co-authored-by: Cathy Chi <[email protected]> Co-authored-by: Jason Cabot <[email protected]>
1 parent ed8c963 commit d0866b1

File tree

14 files changed

+6366
-0
lines changed

14 files changed

+6366
-0
lines changed

apps/docs-vectorize/.dev.vars.example

Whitespace-only changes.

apps/logpush/.dev.vars.example

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
CLOUDFLARE_CLIENT_ID=
2+
CLOUDFLARE_CLIENT_SECRET=
3+
DEV_DISABLE_OAUTH=
4+
DEV_CLOUDFLARE_API_TOKEN=
5+
DEV_CLOUDFLARE_EMAIL=

apps/logpush/.eslintrc.cjs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
/** @type {import("eslint").Linter.Config} */
2+
module.exports = {
3+
root: true,
4+
extends: ['@repo/eslint-config/default.cjs'],
5+
}

apps/logpush/README.md

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
# Model Context Protocol (MCP) Server + Cloudflare OAuth
2+
3+
This is a [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) server that supports remote MCP connections, with Cloudflare OAuth built-in.
4+
5+
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.
6+
7+
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).
8+
9+
The MCP server (powered by [Cloudflare Workers](https://developers.cloudflare.com/workers/)):
10+
11+
- Acts as OAuth _Server_ to your MCP clients
12+
- Acts as OAuth _Client_ to your _real_ OAuth server (in this case, Cloudflare)
13+
14+
## Getting Started
15+
16+
### For Production
17+
18+
- Set secrets via Wrangler
19+
20+
```bash
21+
wrangler secret put CLOUDFLARE_CLIENT_ID
22+
wrangler secret put CLOUDFLARE_CLIENT_SECRET
23+
```
24+
25+
#### Set up a KV namespace
26+
27+
- Create the KV namespace:
28+
`wrangler kv:namespace create "OAUTH_KV"`
29+
- Update the Wrangler file with the KV ID
30+
31+
#### Deploy & Test
32+
33+
Deploy the MCP server to make it available on your workers.dev domain
34+
` wrangler deploy`
35+
36+
Test the remote server using [Inspector](https://modelcontextprotocol.io/docs/tools/inspector):
37+
38+
```
39+
npx @modelcontextprotocol/inspector@latest
40+
```
41+
42+
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:
43+
44+
<img width="640" alt="image" src="https://github.com/user-attachments/assets/7973f392-0a9d-4712-b679-6dd23f824287" />
45+
46+
You now have a remote MCP server deployed!
47+
48+
#### Access the remote MCP server from Claude Desktop
49+
50+
Open Claude Desktop and navigate to Settings -> Developer -> Edit Config. This opens the configuration file that controls which MCP servers Claude can access.
51+
52+
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.
53+
54+
```
55+
{
56+
"mcpServers": {
57+
"cloudflare": {
58+
"command": "npx",
59+
"args": [
60+
"mcp-remote",
61+
"https://<your-subdomain>.workers.dev/sse"
62+
]
63+
}
64+
}
65+
}
66+
```
67+
68+
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.
69+
70+
### For Local Development
71+
72+
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:
73+
74+
- Create a `.dev.vars` file in your project root with:
75+
76+
```
77+
CLOUDFLARE_CLIENT_ID=your_development_cloudflare_client_id
78+
CLOUDFLARE_CLIENT_SECRET=your_development_cloudflare_client_secret
79+
```
80+
81+
#### Develop & Test
82+
83+
Run the server locally to make it available at `http://localhost:8788`
84+
`wrangler dev`
85+
86+
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".
87+
88+
#### Using Claude and other MCP Clients
89+
90+
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.
91+
92+
#### Using Cursor and other MCP Clients
93+
94+
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`).
95+
96+
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).
97+
98+
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.
99+
100+
## How does it work?
101+
102+
#### OAuth Provider
103+
104+
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:
105+
106+
- Authenticating MCP clients that connect to your server
107+
- Managing the connection to Cloudflare's OAuth services
108+
- Securely storing tokens and authentication state in KV storage
109+
110+
#### Durable MCP
111+
112+
Durable MCP extends the base MCP functionality with Cloudflare's Durable Objects, providing:
113+
114+
- Persistent state management for your MCP server
115+
- Secure storage of authentication context between requests
116+
- Access to authenticated user information via `this.props`
117+
- Support for conditional tool availability based on user identity
118+
119+
#### MCP Remote
120+
121+
The MCP Remote library enables your server to expose tools that can be invoked by MCP clients like the Inspector. It:
122+
123+
- Defines the protocol for communication between clients and your server
124+
- Provides a structured way to define tools
125+
- Handles serialization and deserialization of requests and responses
126+
- Maintains the Server-Sent Events (SSE) connection between clients and your server

apps/logpush/package.json

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
{
2+
"name": "logpush",
3+
"version": "0.0.1",
4+
"private": true,
5+
"scripts": {
6+
"check:lint": "run-eslint-workers",
7+
"check:types": "run-tsc",
8+
"deploy": "wrangler deploy",
9+
"dev": "wrangler dev",
10+
"start": "wrangler dev",
11+
"types": "wrangler types --include-env=false",
12+
"test": "vitest run"
13+
},
14+
"dependencies": {
15+
"@cloudflare/workers-oauth-provider": "0.0.3",
16+
"@hono/zod-validator": "0.4.3",
17+
"@modelcontextprotocol/sdk": "1.10.2",
18+
"@repo/mcp-common": "workspace:*",
19+
"@repo/mcp-observability": "workspace:*",
20+
"agents": "0.0.67",
21+
"cloudflare": "4.2.0",
22+
"hono": "4.7.6",
23+
"zod": "3.24.2"
24+
},
25+
"devDependencies": {
26+
"@cloudflare/vitest-pool-workers": "0.8.14",
27+
"@types/node": "22.14.1",
28+
"prettier": "3.5.3",
29+
"typescript": "5.5.4",
30+
"vitest": "3.0.9",
31+
"wrangler": "4.10.0"
32+
}
33+
}

apps/logpush/src/context.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import type { UserDetails } from '@repo/mcp-common/src/durable-objects/user_details'
2+
import type { LogsMCP } from './index'
3+
4+
export interface Env {
5+
OAUTH_KV: KVNamespace
6+
ENVIRONMENT: 'development' | 'staging' | 'production'
7+
MCP_SERVER_NAME: string
8+
MCP_SERVER_VERSION: string
9+
CLOUDFLARE_CLIENT_ID: string
10+
CLOUDFLARE_CLIENT_SECRET: string
11+
MCP_OBJECT: DurableObjectNamespace<LogsMCP>
12+
USER_DETAILS: DurableObjectNamespace<UserDetails>
13+
MCP_METRICS: AnalyticsEngineDataset
14+
DEV_DISABLE_OAUTH: string
15+
DEV_CLOUDFLARE_API_TOKEN: string
16+
DEV_CLOUDFLARE_EMAIL: string
17+
}

apps/logpush/src/index.ts

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
import OAuthProvider from '@cloudflare/workers-oauth-provider'
2+
import { McpAgent } from 'agents/mcp'
3+
4+
import { createApiHandler } from '@repo/mcp-common/src/api-handler'
5+
import {
6+
createAuthHandlers,
7+
handleTokenExchangeCallback,
8+
} from '@repo/mcp-common/src/cloudflare-oauth-handler'
9+
import { handleDevMode } from '@repo/mcp-common/src/dev-mode'
10+
import { getUserDetails, UserDetails } from '@repo/mcp-common/src/durable-objects/user_details'
11+
import { getEnv } from '@repo/mcp-common/src/env'
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'
15+
16+
import { MetricsTracker } from '../../../packages/mcp-observability/src'
17+
import { registerLogsTools } from './tools/logs'
18+
19+
import type { AuthProps } from '@repo/mcp-common/src/cloudflare-oauth-handler'
20+
import type { Env } from './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+
type State = { activeAccountId: string | null }
35+
36+
export class LogsMCP extends McpAgent<Env, State, Props> {
37+
_server: CloudflareMCPServer | undefined
38+
set server(server: CloudflareMCPServer) {
39+
this._server = server
40+
}
41+
get server(): CloudflareMCPServer {
42+
if (!this._server) {
43+
throw new Error('Tried to access server before it was initialized')
44+
}
45+
46+
return this._server
47+
}
48+
49+
constructor(ctx: DurableObjectState, env: Env) {
50+
super(ctx, env)
51+
}
52+
53+
async init() {
54+
this.server = new CloudflareMCPServer({
55+
userId: this.props.user.id,
56+
wae: this.env.MCP_METRICS,
57+
serverInfo: {
58+
name: this.env.MCP_SERVER_NAME,
59+
version: this.env.MCP_SERVER_VERSION,
60+
},
61+
})
62+
63+
registerAccountTools(this)
64+
65+
// Register Cloudflare Log Push tools
66+
registerLogsTools(this)
67+
}
68+
69+
async getActiveAccountId() {
70+
try {
71+
// Get UserDetails Durable Object based off the userId and retrieve the activeAccountId from it
72+
// we do this so we can persist activeAccountId across sessions
73+
const userDetails = getUserDetails(env, this.props.user.id)
74+
return await userDetails.getActiveAccountId()
75+
} catch (e) {
76+
this.server.recordError(e)
77+
return null
78+
}
79+
}
80+
81+
async setActiveAccountId(accountId: string) {
82+
try {
83+
const userDetails = getUserDetails(env, this.props.user.id)
84+
await userDetails.setActiveAccountId(accountId)
85+
} catch (e) {
86+
this.server.recordError(e)
87+
}
88+
}
89+
}
90+
91+
const LogPushScopes = {
92+
...RequiredScopes,
93+
'account:read': 'See your account info such as account details, analytics, and memberships.',
94+
'logpush:write':
95+
'Grants read and write access to Logpull and Logpush, and read access to Instant Logs. Note that all Logpush API operations require Logs: Write permission because Logpush jobs contain sensitive information.',
96+
} as const
97+
98+
export default {
99+
fetch: async (req: Request, env: Env, ctx: ExecutionContext) => {
100+
if (env.ENVIRONMENT === 'development' && env.DEV_DISABLE_OAUTH === 'true') {
101+
return await handleDevMode(LogsMCP, req, env, ctx)
102+
}
103+
104+
return new OAuthProvider({
105+
apiRoute: ['/mcp', '/sse'],
106+
apiHandler: createApiHandler(LogsMCP),
107+
// @ts-ignore
108+
defaultHandler: createAuthHandlers({ scopes: LogPushScopes, metrics }),
109+
authorizeEndpoint: '/oauth/authorize',
110+
tokenEndpoint: '/token',
111+
tokenExchangeCallback: (options) =>
112+
handleTokenExchangeCallback(
113+
options,
114+
env.CLOUDFLARE_CLIENT_ID,
115+
env.CLOUDFLARE_CLIENT_SECRET
116+
),
117+
// Cloudflare access token TTL
118+
accessTokenTTL: 3600,
119+
clientRegistrationEndpoint: '/register',
120+
}).fetch(req, env, ctx)
121+
},
122+
}

0 commit comments

Comments
 (0)