Standalone Express.js API for AI chat functionality
This repository contains the backend REST API for the AI Assistant application. The frontend (React Native PWA + Android APK) is in a separate repository.
- Overview
- Architecture
- Features
- Prerequisites
- Getting Started
- API Endpoints
- Environment Variables
- Development
- Deployment
- Testing
- Troubleshooting
This backend API provides:
- AI Chat: Streaming chat with Claude (Anthropic) models
- Authentication: Google OAuth + JWT-based auth
- Conversations: CRUD operations for chat conversations
- MCP Integration: Model Context Protocol server connections
- Database: PostgreSQL for persistent storage
Technology Stack:
- Framework: Express.js 4.21.2
- Language: TypeScript 5
- Database: PostgreSQL 14+
- Deployment: Google Cloud Run
- Default Port: 8080 (production), configurable for development
┌─────────────────────────────────────────┐
│ Frontend (Separate Repository) │
│ - React Native + Expo │
│ - PWA & Android APK │
│ - http://localhost:8081 (dev) │
└──────────────┬──────────────────────────┘
│
│ HTTPS REST API
│
┌──────────────▼──────────────────────────┐
│ Backend API (This Repository) │
│ ├── /health │
│ ├── /api/ai (streaming chat) │
│ ├── /api/auth (OAuth + JWT) │
│ ├── /api/conversations │
│ └── /api/mcp (tool management) │
└──────────────┬──────────────────────────┘
│
▼
PostgreSQL Database
- ✅ Streaming AI Chat: Real-time streaming responses from Claude models
- ✅ Multiple Models: Support for Claude Sonnet 4.5, Opus 4.1, Haiku 3.5
- ✅ User Authentication: Google OAuth with JWT tokens
- ✅ Conversation Management: Save, load, and manage chat histories
- ✅ MCP Support: Connect to external tools (Gmail, Google Drive, Calendar)
- ✅ CORS Protection: Configurable allowed origins
- ✅ Rate Limiting: Prevent API abuse
- ✅ Helmet: Security headers
- ✅ JWT Authentication: Secure API access
- ✅ Token Encryption: Encrypted storage of OAuth tokens
- ✅ Health Checks:
/healthendpoint for monitoring - ✅ Error Handling: Comprehensive error responses
- ✅ Logging: Structured logging for debugging
- ✅ Cloud Run Deployment: Automated CI/CD
- Node.js: 20+ (LTS recommended)
- npm: 10+
- PostgreSQL: 14+ (if using MCP features)
- Anthropic API Key: From https://console.anthropic.com/
- Google OAuth Credentials: From Google Cloud Console
git clone https://github.com/sdhector/ai-agent-backend.git
cd ai-agent-backendnpm installIMPORTANT: GCP Secret Manager is the SINGLE SOURCE OF TRUTH for all secrets.
There is NO local .env file fallback. All secrets must be stored in GCP Secret Manager.
-
Authenticate with GCP:
gcloud auth application-default login
-
Verify secrets exist in Secret Manager:
gcloud secrets list --project=professional-website-462321
-
Required secrets (see SECRETS.md for complete list):
google-client-id→GOOGLE_CLIENT_IDgoogle-client-secret→GOOGLE_CLIENT_SECRETjwt-secret→JWT_SECRETanthropic-api-key→ANTHROPIC_API_KEYdatabase-url→DATABASE_URL(if using MCP)
See SECRETS.md for detailed secret management instructions.
# Development mode (with auto-reload)
npm run dev
# Production mode
npm run build
npm startExpected output:
Server running on port 8080
Health check: http://localhost:8080/health
# Health check
curl http://localhost:8080/health
# Expected response:
# {"status":"healthy","timestamp":"2025-11-10T10:00:00.000Z"}GET /healthReturns server health status. No authentication required.
Response:
{
"status": "healthy",
"timestamp": "2025-11-10T10:00:00.000Z"
}GET /api/auth/googleRedirects to Google OAuth consent screen.
GET /api/auth/google/callback?code=...Handles OAuth callback and returns JWT token.
GET /api/auth/status
Authorization: Bearer <jwt_token>Returns current user information.
POST /api/ai
Authorization: Bearer <jwt_token>
Content-Type: application/json
{
"message": "Hello, how are you?",
"provider": "claude",
"model": "sonnet-4.5",
"conversationId": "optional-uuid"
}Returns Server-Sent Events (SSE) stream with AI response.
GET /api/conversations
Authorization: Bearer <jwt_token>Returns array of user's conversations.
GET /api/conversations/:id
Authorization: Bearer <jwt_token>Returns conversation details and messages.
DELETE /api/conversations/:id
Authorization: Bearer <jwt_token>Deletes a conversation.
GET /api/mcp/servers
Authorization: Bearer <jwt_token>Returns available MCP servers (Gmail, Drive, Calendar).
POST /api/mcp/connect
Authorization: Bearer <jwt_token>
Content-Type: application/json
{
"serverType": "gmail"
}Initiates OAuth flow for MCP server connection.
| Variable | Description | Example |
|---|---|---|
ANTHROPIC_API_KEY |
Anthropic API key | sk-ant-... |
JWT_SECRET |
Secret for signing JWT tokens | your-32-char-secret |
GOOGLE_CLIENT_ID |
Google OAuth client ID | 123.apps.googleusercontent.com |
GOOGLE_CLIENT_SECRET |
Google OAuth client secret | GOCSPX-... |
| Variable | Description | Default |
|---|---|---|
PORT |
Backend server port | 8080 |
BACKEND_PORT |
Alternative port variable | 8080 |
FRONTEND_URL |
Frontend URL for OAuth redirects | http://localhost:8081 |
DATABASE_URL |
PostgreSQL connection string | - |
MCP_ENABLED |
Enable MCP features | false |
NODE_ENV |
Environment (development/production) | development |
ENABLE_RATE_LIMIT |
Enable rate limiting | true |
ENABLE_LOGGING |
Enable request logging | true |
# JWT Secret (32 bytes, base64)
openssl rand -base64 32
# Encryption Key (32 bytes, base64)
openssl rand -base64 32
# Token Encryption Key (32 bytes, hex)
openssl rand -hex 32ai-assistant-backend/
├── config/ # Configuration files
│ └── index.ts # Main config
├── database/ # Database setup
│ └── index.ts # PostgreSQL connection
├── middleware/ # Express middleware
│ ├── auth.ts # JWT authentication
│ └── cors.ts # CORS configuration
├── providers/ # AI providers
│ └── claude.ts # Anthropic Claude provider
├── routes/ # API routes
│ ├── ai.js # Chat endpoints
│ ├── auth.ts # Authentication endpoints
│ ├── conversations.ts # Conversation CRUD
│ ├── health.js # Health check
│ └── mcp.ts # MCP endpoints
├── services/ # Business logic
│ ├── mcp/ # MCP service implementations
│ └── encryption.ts # Token encryption
├── types/ # TypeScript type definitions
├── utils/ # Utility functions
├── server.js # Entry point
├── package.json
├── tsconfig.json
├── Dockerfile
└── cloudbuild.yaml
- Make changes to code
- Test locally:
npm run dev - Run tests:
npm test - Type check:
npm run typecheck - Commit changes:
git commit -m "feat: your changes" - Push to main: Triggers auto-deployment to Cloud Run
- Create route file in
routes/ - Implement route logic
- Add authentication middleware if needed
- Register route in
server.js - Test with curl or Postman
- Update API documentation
This backend automatically deploys to Google Cloud Run when you push to the main branch.
- Google Cloud Project with billing enabled
- Cloud Run API enabled
- Cloud Build API enabled
- GitHub repository connected to Cloud Build
# Authenticate with Google Cloud
gcloud auth login
gcloud config set project YOUR_PROJECT_ID
# Build and deploy
gcloud builds submit --config cloudbuild.yaml
# Verify deployment
gcloud run services describe ai-assistant-backend --region=us-central1Set environment variables in Cloud Run:
# Using gcloud CLI
gcloud run services update ai-assistant-backend \
--region=us-central1 \
--set-env-vars="NODE_ENV=production,PORT=8080,FRONTEND_URL=https://your-pwa.web.app"Or use Google Secret Manager for sensitive values:
# Create secret
echo -n "your-jwt-secret" | gcloud secrets create jwt-secret --data-file=-
# Grant access to Cloud Run
gcloud secrets add-iam-policy-binding jwt-secret \
--member="serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com" \
--role="roles/secretmanager.secretAccessor"
# Use in Cloud Run
gcloud run services update ai-assistant-backend \
--region=us-central1 \
--set-secrets=JWT_SECRET=jwt-secret:latestAfter deployment, your backend will be available at:
https://ai-assistant-backend-<hash>-uc.a.run.app
Update this URL in your frontend's environment configuration.
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coveragecurl http://localhost:8080/health# Step 1: Visit OAuth URL in browser
open http://localhost:8080/api/auth/google
# Step 2: Complete OAuth flow, get JWT token
# Step 3: Use JWT token for authenticated requests
curl -H "Authorization: Bearer YOUR_JWT_TOKEN" \
http://localhost:8080/api/auth/statuscurl -X POST http://localhost:8080/api/ai \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"message": "Hello!",
"provider": "claude",
"model": "sonnet-4.5"
}'Error: Error: listen EADDRINUSE: address already in use :::8080
Solution:
# Find process using port 8080
lsof -i :8080
# Kill the process
kill -9 <PID>
# Or use a different port
PORT=8081 npm run devError: Access-Control-Allow-Origin header missing
Solution:
- Check
config/index.ts→getCorsOrigins() - Add your frontend URL to allowed origins
- Restart backend server
- Hard refresh frontend
Error: Error: connect ECONNREFUSED
Solution:
- Verify PostgreSQL is running
- Check
DATABASE_URLin.env - Test connection:
psql $DATABASE_URL - Check firewall rules
Error: 401 Unauthorized
Solution:
- Verify
JWT_SECRETmatches between frontend and backend - Check token expiration (default 7 days)
- Try logging in again to get fresh token
- Check
Authorizationheader format:Bearer <token>
Error: Build fails or service crashes
Solution:
- Check Cloud Build logs:
gcloud builds list --limit=5 - View build details:
gcloud builds log BUILD_ID - Common issues:
- Missing environment variables
- Docker build errors
- Health check failing
- Test Docker image locally:
docker build -t ai-assistant-backend . docker run -p 8080:8080 --env-file .env ai-assistant-backend
- Fork the repository
- Create feature branch:
git checkout -b feature/your-feature - Make changes and test thoroughly
- Commit changes:
git commit -m "feat: add your feature" - Push to branch:
git push origin feature/your-feature - Create Pull Request
This project is licensed under the ISC License.
For issues, questions, or contributions:
- GitHub Issues: https://github.com/sdhector/ai-agent-backend/issues
- Documentation: See
/docsfolder for detailed guides
- Frontend: https://github.com/sdhector/ai-agent-frontend (React Native PWA + Android APK)
Last Updated: November 10, 2025