ChatGPT App with OAuth2 + MCP + Privy
A complete ChatGPT App implementation using MCP with OAuth2 authentication via Privy.io, enabling secure user authentication and interactive widgets rendered in ChatGPT.
README
ChatGPT App with OAuth2 + MCP + Privy
A complete ChatGPT App implementation using the OpenAI Apps SDK (MCP), with OAuth2 authentication via Privy.io.
๐๏ธ Architecture
- Backend: Express + MCP Server (TypeScript/Bun)
- OAuth UI: React + Privy + React Router
- Widgets: React components (rendered in ChatGPT)
- Auth: OAuth2 with PKCE + Privy.io
- Package Manager: Bun
๐ Project Structure
mcp2/
โโโ src/
โ โโโ server/ # Express + MCP server
โ โ โโโ oauth/ # OAuth2 endpoints
โ โ โโโ mcp/ # MCP tools & resources
โ โ โโโ api/ # Backend API integration
โ โ โโโ middleware/ # Auth middleware
โ โโโ client/ # OAuth authorization UI
โ โโโ widgets/ # ChatGPT widget components
โโโ dist/
โ โโโ client/ # Built OAuth UI
โ โโโ widgets/ # Built widget bundles
โ โโโ server/ # Compiled server
โโโ package.json
๐ Quick Start
Prerequisites
1. Install Bun
curl -fsSL https://bun.sh/install | bash
2. Install Dependencies
bun install
3. Generate JWT Keys
# Generate RSA key pair for JWT signing
openssl genrsa -out private-key.pem 2048
openssl rsa -in private-key.pem -pubout -out public-key.pem
# Base64 encode for .env
echo "JWT_PRIVATE_KEY=$(cat private-key.pem | base64)"
echo "JWT_PUBLIC_KEY=$(cat public-key.pem | base64)"
# Clean up PEM files
rm private-key.pem public-key.pem
4. Configure Environment
cp .env.example .env
# Edit .env with your values:
# - PRIVY_APP_ID (from Privy dashboard)
# - PRIVY_APP_SECRET (from Privy dashboard)
# - JWT_PRIVATE_KEY (from step 3)
# - JWT_PUBLIC_KEY (from step 3)
# - BACKEND_API_URL (your existing backend)
5. Build & Run
IMPORTANT: Widgets must be built before starting the server!
# First time: Build widgets (required!)
bun run build:widgets
# Then start development server
bun run dev
The server will start at http://localhost:3002
๐ง Development
Understanding the Widget Build Process
โ ๏ธ Key Point: bun run dev does NOT automatically build widgets. You must build them separately!
There are three development workflows:
Option 1: Manual Build (Recommended for first-time setup)
# 1. Build widgets once
bun run build:widgets
# 2. Start server with auto-reload
bun run dev
# 3. Rebuild widgets manually when you change widget code
bun run build:widgets
Option 2: Watch Mode (Recommended for active widget development)
# Terminal 1: Build widgets in watch mode (auto-rebuilds on changes)
bun run dev:widgets
# Terminal 2: Run server with auto-reload
bun run dev
Option 3: Run Everything (Most convenient)
# Runs both server AND widget watch mode simultaneously
bun run dev:all
Other Development Commands
# Type check
bun run type-check
# Run tests
bun test
# Build everything for production
bun run build
Project Configuration
Server: src/server/index.ts
- OAuth endpoints:
/authorize,/token,/.well-known/* - MCP endpoint:
/mcp - Health check:
/health
OAuth UI: src/client/src/App.tsx
- Authorization page with Privy login
- Consent screen
- Built with Vite + React + React Router
Widgets: src/widgets/src/
- ListView: Interactive list with actions
- Built as standalone bundles
- Communicate via
window.openaiAPI
๐งช Testing
Test with MCP Inspector
# Terminal 1: Run server
bun run dev
# Terminal 2: Run MCP Inspector
bunx @modelcontextprotocol/inspector http://localhost:3002/mcp
Test with ngrok
# Expose local server
ngrok http 3002
# Copy the HTTPS URL (e.g., https://abc123.ngrok.app)
# Use this URL in ChatGPT Settings โ Connectors
Connect to ChatGPT
-
Enable Developer Mode:
- ChatGPT Settings โ Apps & Connectors โ Advanced settings
- Enable "Developer mode"
-
Create Connector:
- Settings โ Connectors โ Create
- Name: "Your App Name"
- Description: "What your app does"
- Connector URL:
https://your-server.com/mcp(or ngrok URL)
-
Test OAuth Flow:
- Start a new ChatGPT conversation
- Click + โ More โ Select your connector
- You'll be redirected to
/authorize - Log in with Privy
- Grant consent
- ChatGPT receives OAuth token
-
Test Tools:
- Ask ChatGPT: "Show me my items"
- The
get-itemstool will be called - Widget will render in ChatGPT
๐ฆ Production Build
# Build everything
bun run build
# Run production server
bun run start
# Or preview locally
bun run preview
Docker Deployment
# Build image
docker build -t chatgpt-app .
# Run container
docker run -p 3000:3000 --env-file .env chatgpt-app
Deploy to Fly.io
# Install flyctl
curl -L https://fly.io/install.sh | sh
# Create app
fly launch
# Set secrets
fly secrets set PRIVY_APP_ID=xxx
fly secrets set PRIVY_APP_SECRET=xxx
fly secrets set JWT_PRIVATE_KEY=xxx
fly secrets set JWT_PUBLIC_KEY=xxx
fly secrets set BACKEND_API_URL=xxx
# Deploy
fly deploy
๐ OAuth2 Flow
- ChatGPT redirects user to
/authorize?client_id=...&code_challenge=... - Server serves React UI (Privy login)
- User authenticates with Privy
- Frontend shows consent screen
- User approves, server generates authorization code
- Frontend redirects back to ChatGPT with code
- ChatGPT exchanges code for access token at
/token - Server validates PKCE, issues JWT
- ChatGPT uses JWT for
/mcprequests
๐จ Adding New Tools
1. Define Tool in src/server/mcp/tools.ts
{
name: 'my-new-tool',
description: 'What the tool does',
inputSchema: {
type: 'object',
properties: {
param: { type: 'string' }
},
required: ['param']
}
}
2. Implement Handler
async function handleMyNewTool(args: any, auth: any) {
// Validate auth
// Call backend API
// Return structured response
}
3. Link to Widget (Optional)
_meta: {
'openai/outputTemplate': 'ui://widget/my-widget.html',
}
๐จ Adding New Widgets
1. Create Widget Component
mkdir -p src/widgets/src/MyWidget
2. Build Widget
// src/widgets/src/MyWidget/index.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { MyWidget } from './MyWidget';
const root = ReactDOM.createRoot(document.getElementById('root')!);
root.render(<MyWidget />);
3. Configure Vite
// Update src/widgets/vite.config.ts
build: {
lib: {
entry: {
'my-widget': 'src/MyWidget/index.tsx'
}
}
}
4. Register Resource
// src/server/mcp/resources.ts
await registerMyWidget(server, widgetPath);
๐ Environment Variables
| Variable | Description | Required |
|---|---|---|
PRIVY_APP_ID |
Your Privy app ID | โ |
PRIVY_APP_SECRET |
Your Privy app secret | โ |
VITE_PRIVY_APP_ID |
Privy app ID (for frontend) | โ |
JWT_PRIVATE_KEY |
Base64-encoded RSA private key | โ |
JWT_PUBLIC_KEY |
Base64-encoded RSA public key | โ |
SERVER_BASE_URL |
Your server URL | โ |
BACKEND_API_URL |
Your existing backend URL | โ |
PORT |
Server port (default: 3000) | โ |
NODE_ENV |
Environment (development/production) | โ |
๐ Troubleshooting
Widgets not loading
# Build widgets first
bun run build:widgets
# Restart server
bun run dev
OAuth flow fails
- Check
SERVER_BASE_URLmatches your actual URL - Verify Privy app ID is correct
- Check JWT keys are properly base64-encoded
- Ensure redirect URI is registered in ChatGPT
Token validation fails
- Verify JWT keys are correct (public/private pair)
- Check token hasn't expired (1 hour default)
- Ensure
audclaim matches your server URL
MCP Inspector can't connect
# Ensure server is running
bun run dev
# Try:
bunx @modelcontextprotocol/inspector http://localhost:3002/mcp
๐ Resources
๐ License
MIT
๐ค Contributing
Contributions welcome! Please open an issue or PR.
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
E2B
Using MCP to run code via e2b.