Skip to content

Commit df712cc

Browse files
committed
new
1 parent 2b905f2 commit df712cc

File tree

13 files changed

+3033
-181
lines changed

13 files changed

+3033
-181
lines changed

CLAUDE.md

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# CLAUDE.md
2+
3+
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4+
5+
## Project Overview
6+
7+
This is an MCP (Model Context Protocol) OAuth 2.1 server implementation built with Next.js 15, providing secure authentication for MCP clients. The application serves as an OAuth authorization server that enables MCP clients to authenticate users and access protected MCP resources.
8+
9+
## Core Architecture
10+
11+
### Authentication Flow
12+
- **NextAuth.js**: Handles user authentication via Google OAuth provider
13+
- **OAuth 2.1 Server**: Custom implementation with PKCE support for MCP client authorization
14+
- **Database**: PostgreSQL with Prisma ORM storing OAuth clients, tokens, and user sessions
15+
- **MCP Integration**: Uses `@vercel/mcp-adapter` for MCP protocol handling
16+
17+
### Key Components
18+
- `app/auth.ts`: NextAuth configuration with Google provider and Prisma adapter
19+
- `app/api/oauth/`: OAuth 2.1 server endpoints (register, token, authorize)
20+
- `app/mcp/[transport]/route.ts`: MCP server with authentication middleware
21+
- `prisma/schema.prisma`: Database schema for OAuth entities and NextAuth models
22+
23+
### Database Schema
24+
The Prisma schema includes:
25+
- NextAuth models (User, Account, Session, VerificationToken)
26+
- OAuth 2.1 models (Client, AccessToken, AuthCode) with PKCE support
27+
- Proper foreign key relationships and cascading deletes
28+
29+
## Development Commands
30+
31+
```bash
32+
# Start development server
33+
pnpm dev
34+
35+
# Build for production
36+
pnpm build
37+
38+
# Start production server
39+
pnpm start
40+
41+
# Lint code
42+
pnpm lint
43+
44+
# Database operations
45+
pnpm prisma generate # Generate Prisma client
46+
pnpm prisma db push # Push schema changes to database
47+
pnpm prisma migrate dev # Create and apply migrations
48+
pnpm prisma studio # Open database admin interface
49+
```
50+
51+
## Environment Setup
52+
53+
Required environment variables:
54+
- `DATABASE_URL`: PostgreSQL connection string
55+
- `AUTH_SECRET`: NextAuth secret key
56+
- `GOOGLE_CLIENT_ID`: Google OAuth client ID
57+
- `GOOGLE_CLIENT_SECRET`: Google OAuth client secret
58+
- `REDIS_URL`: Optional Redis URL for SSE transport support
59+
60+
## Database Management
61+
62+
PostgreSQL must be running locally for development:
63+
```bash
64+
# Start PostgreSQL (macOS with Homebrew)
65+
brew services start postgresql@14
66+
67+
# Stop PostgreSQL
68+
brew services stop postgresql@14
69+
```
70+
71+
## MCP Integration
72+
73+
The MCP server (`app/mcp/[transport]/route.ts`) implements:
74+
- Bearer token authentication using OAuth access tokens
75+
- Token audience validation for security
76+
- CORS headers for cross-origin requests
77+
- Sample tool implementation (`add_numbers`)
78+
79+
## Security Considerations
80+
81+
- PKCE (Proof Key for Code Exchange) is implemented for public clients
82+
- Access tokens are validated against database and checked for expiration
83+
- Token audience validation prevents token misuse across different resources
84+
- Proper CORS configuration for MCP client access
85+
86+
## Testing MCP Integration
87+
88+
MCP clients can connect using:
89+
- SSE transport: `https://your-domain.com/mcp/sse`
90+
- HTTP transport: `https://your-domain.com/mcp/mcp`
91+
92+
Clients must include OAuth access token in Authorization header as Bearer token.
93+
94+
## Prisma Client Location
95+
96+
The Prisma client is generated to `generated/prisma/` directory (not the default location) as specified in the schema generator configuration.

MCP_IMPLEMENTATION_ANALYSIS.md

Lines changed: 109 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,19 @@ ALTER TABLE "AuthCode" ADD COLUMN "resource" TEXT;
117117

118118
-- AccessToken table
119119
ALTER TABLE "AccessToken" ADD COLUMN "resource" TEXT;
120+
121+
-- RefreshToken table (NEW - for refresh token support)
122+
CREATE TABLE "RefreshToken" (
123+
"id" TEXT NOT NULL PRIMARY KEY DEFAULT gen_random_uuid(),
124+
"token" TEXT NOT NULL UNIQUE,
125+
"expiresAt" TIMESTAMP(3) NOT NULL,
126+
"clientId" TEXT NOT NULL,
127+
"userId" TEXT NOT NULL,
128+
"resource" TEXT,
129+
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
130+
CONSTRAINT "RefreshToken_clientId_fkey" FOREIGN KEY ("clientId") REFERENCES "Client" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
131+
CONSTRAINT "RefreshToken_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
132+
);
120133
```
121134

122135
## MCP Authorization Flow (Now Compliant)
@@ -174,8 +187,100 @@ After deploying these changes, verify:
174187
## Next Steps
175188

176189
1. **Deploy changes** to your Vercel instance
177-
2. **Run database migration**: `pnpm prisma db push`
178-
3. **Test with MCP client** (Cursor, Claude, etc.)
179-
4. **Monitor logs** for successful authorization flows
190+
2. **Run database migration**: `pnpm prisma db push` (includes new RefreshToken table)
191+
3. **Generate Prisma client**: `pnpm prisma generate` (required for RefreshToken model)
192+
4. **Test authorization flow** with MCP client (Cursor, Claude, etc.)
193+
5. **Test refresh token flow** to verify automatic token refresh
194+
6. **Monitor logs** for successful authorization and refresh flows
195+
196+
### Verification Commands
197+
198+
Test refresh token discovery:
199+
```bash
200+
curl https://your-domain.com/.well-known/oauth-authorization-server | jq '.grant_types_supported'
201+
```
202+
203+
Test token endpoint with refresh_token grant:
204+
```bash
205+
# First get tokens via authorization flow, then test refresh
206+
curl -X POST https://your-domain.com/api/oauth/token \
207+
-d "grant_type=refresh_token&refresh_token=your_refresh_token&client_id=your_client_id"
208+
```
209+
210+
### Testing Refresh Token Flow
211+
212+
With 5-minute access tokens, you can easily test the refresh functionality:
213+
214+
1. **Complete OAuth flow** - Get initial access + refresh tokens
215+
2. **Use access token** - Make MCP requests (works for 5 minutes)
216+
3. **Wait 5+ minutes** - Access token expires
217+
4. **Test expiry** - MCP request should return 401
218+
5. **Use refresh token** - Get new access + refresh tokens
219+
6. **Resume requests** - New access token should work
220+
221+
This short expiry makes it easy to test token refresh without waiting 30 minutes!
222+
223+
Your implementation is now **MCP specification compliant** and should work with standard MCP clients! 🎉
224+
225+
## Refresh Token Implementation (NEW)
226+
227+
### ✅ Added Refresh Token Support
228+
229+
To improve user experience and follow OAuth 2.1 best practices, refresh token support has been implemented:
230+
231+
#### **Key Features:**
232+
- **Short-lived access tokens**: 5 minutes for easy testing (configurable)
233+
- **Long-lived refresh tokens**: 7 days lifetime
234+
- **Token rotation**: For public clients (no client secret), refresh tokens are rotated per OAuth 2.1 requirements
235+
- **Resource binding**: Refresh tokens maintain the same audience binding as the original access token
236+
- **Standard OAuth error codes**: Proper error responses (`invalid_grant`, `invalid_client`, etc.)
237+
238+
#### **Authorization Server Metadata Updated:**
239+
```json
240+
{
241+
"grant_types_supported": ["authorization_code", "refresh_token"],
242+
"resource_parameter_supported": true
243+
}
244+
```
245+
246+
#### **Token Response Format (Updated):**
247+
```json
248+
{
249+
"access_token": "abc123...",
250+
"refresh_token": "def456...",
251+
"token_type": "Bearer",
252+
"expires_in": 300
253+
}
254+
```
255+
256+
#### **Refresh Token Grant Usage:**
257+
```http
258+
POST /api/oauth/token
259+
Content-Type: application/x-www-form-urlencoded
260+
261+
grant_type=refresh_token
262+
&refresh_token=def456...
263+
&client_id=client123
264+
&resource=https://mcp.example.com
265+
```
180266

181-
Your implementation is now **MCP specification compliant** and should work with standard MCP clients! 🎉
267+
#### **Security Enhancements:**
268+
1. **Token Rotation**: Public clients get new refresh tokens with each refresh
269+
2. **Audience Validation**: Refresh tokens maintain resource binding
270+
3. **Expiry Management**: Both access and refresh tokens have proper expiration
271+
4. **Client Authentication**: Confidential clients must provide client_secret
272+
273+
#### **Implementation Benefits:**
274+
- **No Re-authentication**: Users stay logged in as long as refresh token is valid
275+
- **Better Security**: Shorter access token lifetime reduces risk of token theft
276+
- **OAuth 2.1 Compliant**: Follows latest OAuth security recommendations
277+
- **MCP Compatible**: Works seamlessly with MCP client discovery flow
278+
279+
### Updated Database Schema
280+
281+
The `RefreshToken` model includes:
282+
- Unique token identifier
283+
- Expiration timestamp (7 days)
284+
- Client and user relationships
285+
- Resource binding for audience validation
286+
- Cascade delete for cleanup

0 commit comments

Comments
 (0)