Abhuday2709/MCP-SERVER
If you are the rightful owner of MCP-SERVER and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.
The MCP Chatbot Server is a Node.js/Express backend server that integrates Google Gemini AI with the Model Context Protocol (MCP) to provide intelligent chatbot capabilities with Gmail integration through OAuth2 authentication.
MCP Chatbot Server
A Node.js/Express backend server that integrates Google Gemini AI with the Model Context Protocol (MCP) to provide intelligent chatbot capabilities with Gmail integration through OAuth2 authentication.
🏗️ Architecture
Technology Stack
- Runtime: Node.js (ES Modules)
- Framework: Express.js 5.x
- AI Model: Google Gemini 2.5 Flash
- Authentication: JWT with HTTP-only cookies
- OAuth2: Google OAuth2 for Gmail access
- Database/Cache: Redis (Upstash compatible)
- Protocol: Model Context Protocol (MCP) SDK
- API Client: Google APIs (googleapis)
Project Structure
server/
├── config/
│ ├── googleConfig.js # Google OAuth2 configuration
│ └── redisClient.js # Redis connection setup
├── controllers/
│ ├── authController.js # Authentication logic
│ └── chatController.js # AI chat & MCP integration
├── mcp/
│ ├── client/
│ │ └── mcp-client.js # MCP client manager
│ └── servers/
│ └── gmail-server.js # Gmail MCP server implementation
├── middleware/
│ └── auth.js # JWT authentication middleware
├── routes/
│ ├── authRoutes.js # Auth endpoints
│ └── chatRoute.js # Chat endpoints
├── utils/
│ ├── jwt.js # JWT helper functions
│ └── testMCP.js # MCP testing utilities
├── .env # Environment variables
├── app.js # Main application entry
└── package.json # Dependencies
🎯 Core Features
1. Intelligent AI Chat with MCP Integration
- Automatic Tool Detection: Analyzes user queries to determine if Gmail tools are needed
- Context-Aware Responses: Maintains conversation history (last 5 messages)
- Dual Mode Operation:
- Standard mode: Direct Gemini AI responses
- MCP mode: Gmail tool execution with AI interpretation
- Smart Query Classification: Detects email-related keywords automatically
2. Google OAuth2 Authentication
- Secure authorization flow with Google
- JWT token generation and validation
- Redis-based token storage (30-day expiration)
- HTTP-only cookie management
- Support for refresh tokens
3. Gmail Integration via MCP
Four powerful Gmail tools:
gmail_list_messages: List emails with filtersgmail_get_message: Get full email detailsgmail_search_messages: Advanced search with multiple criteriagmail_send_message: Send emails programmatically
4. Model Context Protocol (MCP) Architecture
- Client-server communication via stdio transport
- Dynamic tool discovery and execution
- Tool result formatting with AI
- Graceful error handling and fallback
5. Security Features
- JWT authentication with 7-day expiration
- HTTP-only cookies (XSS protection)
- CORS with credentials support
- Secure token storage in Redis
- Environment-based security configurations
📋 Prerequisites
- Node.js: v18.0.0 or higher
- Redis: Local instance or Upstash cloud Redis
- Google Cloud Project: With OAuth2 credentials
- Gmail API: Enabled in Google Cloud Console
🛠️ Installation
1. Clone and Navigate
cd server
2. Install Dependencies
npm install
3. Configure Google Cloud
- Go to Google Cloud Console
- Create a new project or select existing
- Enable Gmail API
- Go to Credentials → Create Credentials → OAuth 2.0 Client ID
- Configure OAuth consent screen:
- Add scopes:
gmail.readonly,gmail.send,userinfo.email,userinfo.profile - Add test users (during development)
- Add scopes:
- Create OAuth 2.0 Client ID:
- Application type: Web application
- Authorized redirect URIs:
http://localhost:3000/api/auth/google/callback
- Download credentials (Client ID and Secret)
3b. Configure Microsoft Azure (Optional - for Teams Integration)
For Microsoft Teams integration, you'll need to register an application in Azure Active Directory.
See detailed setup instructions in
Quick steps:
- Go to Azure Portal
- Navigate to Azure Active Directory → App registrations
- Create a new registration
- Add redirect URI:
http://localhost:3000/api/auth/microsoft/callback - Create a client secret
- Add Microsoft Graph API permissions (Delegated):
- Required permissions:
User.Read- Read user profileChat.Read- Read user chatsChat.ReadWrite- Send and read chat messagesChannelMessage.Read.All- Read channel messages (requires admin consent)ChannelMessage.Send- Send channel messagesChannel.ReadBasic.All- Read channel namesTeam.ReadBasic.All- Read team namesCalendars.Read- Read user calendars (optional)Calendars.ReadWrite- Manage calendars (optional)offline_access- Maintain access to dataopenid,profile,email- Basic authentication
- Note: Some permissions (like
ChannelMessage.Read.All) require admin consent
- Required permissions:
- Copy Client ID, Client Secret, and Tenant ID
4. Set Up Redis
Option A: Local Redis
# Install Redis
# Windows: Download from https://redis.io/download
# macOS: brew install redis
# Linux: sudo apt-get install redis-server
# Start Redis
redis-server
Option B: Upstash (Recommended for Production)
- Go to Upstash Console
- Create a new Redis database
- Copy the Redis URL
5. Configure Environment Variables
Create a .env file in the server directory:
# Server Configuration
PORT=3000
NODE_ENV=development
FRONTEND_URL=http://localhost:5173
# Google OAuth2
GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_REDIRECT_URI=http://localhost:3000/api/auth/google/callback
# Microsoft OAuth2 (Optional - for Teams Integration)
MICROSOFT_CLIENT_ID=your-microsoft-client-id
MICROSOFT_CLIENT_SECRET=your-microsoft-client-secret
MICROSOFT_REDIRECT_URI=http://localhost:3000/api/auth/microsoft/callback
MICROSOFT_TENANT_ID=common
# JWT Secret
JWT_SECRET=your-super-secret-jwt-key-min-32-characters-long
# Google Gemini AI
GEMINI_API_KEY=your-gemini-api-key
# Redis
REDIS_URL=redis://localhost:6379
# For Upstash: redis://default:your-password@your-endpoint.upstash.io:6379
6. Get Gemini API Key
- Go to Google AI Studio
- Create a new API key
- Copy and paste into
.env
7. Start the Server
Development mode (with auto-reload):
npm run dev
Production mode:
npm start
The server will start on http://localhost:3000
🔐 Authentication Flow
┌─────────────┐
│ Frontend │
└──────┬──────┘
│ 1. GET /api/auth/google
▼
┌─────────────┐
│ Backend │ 2. Returns authUrl
└──────┬──────┘
│ 3. Redirect to Google
▼
┌─────────────┐
│ Google │ 4. User logs in & grants permissions
└──────┬──────┘
│ 5. Redirects to callback with code
▼
┌─────────────┐
│ Backend │ 6. Exchange code for tokens
└──────┬──────┘ 7. Get user info
│ 8. Generate JWT
│ 9. Store tokens in Redis
│ 10. Set JWT cookie
▼
┌─────────────┐
│ Frontend │ 11. Redirects to success page
└──────┬──────┘
│ 12. GET /api/auth/status
▼
┌─────────────┐
│ Backend │ 13. Returns user info from JWT
└─────────────┘
🤖 AI Chat Flow
Standard Chat (No Gmail)
User Message → Gemini AI → Response
MCP-Enhanced Chat (Gmail Access)
User: "Show my recent emails"
│
▼
┌──────────────────────┐
│ Keyword Detection │ → Email-related? Yes
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Gemini Analyzes │ → Which tool? gmail_list_messages
│ & Decides Tool │ → Parameters? { maxResults: 10 }
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ MCP Client calls │ → Passes access token
│ gmail-server.js │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Gmail API Request │ → Returns email data
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Gemini Formats │ → Human-readable response
│ Result for User │
└──────────┬───────────┘
│
▼
Response to User
🔒 Security Best Practices
1. Environment Variables
- Never commit
.envto version control - Use strong, random JWT secrets (32+ characters)
- Rotate secrets periodically
2. JWT Configuration
// Production settings
{
httpOnly: true, // Prevents XSS attacks
secure: true, // HTTPS only
sameSite: 'none', // Cross-site requests
maxAge: 7 days // Auto expiration
}
3. CORS Configuration
{
origin: process.env.FRONTEND_URL, // Specific origin only
credentials: true, // Allow cookies
methods: ['GET', 'POST', ...], // Explicit methods
allowedHeaders: [...] // Explicit headers
}
4. Token Storage
- JWT in HTTP-only cookies (client can't access)
- OAuth tokens in Redis with TTL
- Automatic cleanup on logout
5. API Rate Limiting (Recommended)
npm install express-rate-limit
import rateLimit from 'express-rate-limit';
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
app.use('/api/', limiter);
📄 License
This project is licensed under the ISC License.
🔗 Related Documentation
- Model Context Protocol Specification
- Google OAuth2 Documentation
- Gmail API Reference
- Google Gemini AI Documentation
- Redis Documentation
- Express.js Guide
📞 Support
For issues and questions:
- Open an issue on GitHub
- Check existing issues for solutions
- Review troubleshooting section above
- Check server logs for detailed errors
Built with ❤️ using Node.js, Express, and Google Gemini AI