Labels:
documentation,help wanted
This document provides a comprehensive overview of the MedSync AI system architecture, including component interactions, data flow, and technology stack.
The architecture diagram above illustrates the complete system architecture of MedSync AI, showing the flow between:
- Client Layer (React Frontend) - User interface, pages, context providers, and Socket.IO client
- API Gateway (Express.js Backend) - Express server, routes, middleware, and Socket.IO server
- Business Logic Layer - Controllers, services, utilities, and authentication middleware
- AI Agent Layer - Medical, Emergency, Medicine, and Personal Health agents using LangChain + Groq
- External Services - Google Calendar API, Groq API, Gemini API, and Hugging Face API
- Data Layer - MongoDB database with all data models (User, Medicine, Notification, Health Profile, Report, Conversation)
- Real-time Communication - Notification scheduler and WebSocket connections for real-time updates
User → Login/Signup Page → POST /api/auth/login
→ Auth Controller → JWT Generation → MongoDB (User Model)
→ Response with JWT Token → Frontend stores token
→ Protected Routes check token via Auth Middleware
User → Add Medication Page → POST /api/medicine
→ Auth Middleware validates JWT
→ Medicine Controller → Medicine Model → MongoDB
→ Notification Scheduler creates reminders
→ Google Calendar Sync (if enabled) → Google Calendar API
→ Response → Frontend updates Medication Context
Notification Scheduler (cron-like) → Checks Medicine Model
→ Finds due medications → Creates Notification Model
→ Socket.IO Server emits to user room
→ Socket.IO Client receives → Notification Context updates
→ UI displays notification toast
User → Agents Page → Select Agent Type → POST /api/agents/{type}
→ Auth Middleware validates JWT
→ Agent Controller → LangChain Handler (medical_model.js, etc.)
→ LangChain → Groq/Gemini API → LLM Response
→ Conversation Model stores history → MongoDB
→ Response → Frontend displays in chat UI
User → Reports Page → Upload PDF → POST /api/agents/upload
→ Multer handles file upload → pdf-parse extracts text
→ Report Analysis Utility → LLM (Groq/Gemini) → Analysis
→ Report Model stores analysis → MongoDB
→ User → Chat with Report → POST /api/agents/chat
→ Report Analysis retrieves context → LLM → Response
User → Connect Calendar Page → OAuth2 Flow
→ GET /api/oauth/login → Google OAuth2
→ Callback → /api/oauth/callback → Stores tokens in User Model
→ Add Medication → Calendar Sync Controller
→ Google Calendar API → Creates events → User's Google Calendar
Location: client/src/
Key Components:
- Pages: Dashboard, Login, Signup, AddMedication, Agents, Reports, Analytics, HealthProfile, ConnectCalendar, Notifications
- Components: Navbar, NotificationToast, ProtectedRoute
- Context Providers:
medicationContext.jsx- Medication state managementnotificationContext.jsx- Notification statesocketContext.jsx- Socket.IO connection managementcalendarSyncContext.jsx- Calendar sync state
- Services:
socketService.js- Socket.IO client wrapper
Technologies:
- React 19.2.0 (Vite)
- React Router DOM 7.9.3
- Tailwind CSS 4.1.14
- Socket.IO Client 4.8.1
- Axios 1.12.2
- Recharts 3.2.1
Location: server/src/
Key Components:
auth.js- Authentication (signup, login)medicineRoutes.js- Medication CRUDnotificationRoutes.js- Notification managementagentsRoutes.js- AI agent endpointsreportRoutes.js- Report upload and chathealthRoutes.js- Health profile managementcalendarSyncRoutes.js- Google Calendar syncoauth.js- OAuth2 callback handlinganalytics.js- Analytics endpoints
addMedicineController.js- Medication creationstatusMedicineController.js- Medication status updatestodaysMedicineController.js- Today's medicationsnotificationController.js- Notification scheduling and deliveryanalyticsController.js- Analytics calculationscalendarSyncController.js- Calendar sync operationsreportController.js- Report handling
User.js- User schema (auth, Google tokens)medicineModel.js- Medication schematodayMedicine.js- Daily medication trackingtodayNotifications.js- Notification schemaHealthProfile.js- User health profileReportModel.js- Medical report storageConversationModel.js- AI conversation history
medical_model.js- Medical AI agent (LangChain)emergency_model.js- Emergency triage agentmedicine_model.js- Medication-specific agentpersonal_health_model.js- Personal health advisorreportAnalysis.js- PDF parsing and analysisgoogleCalendar.js- Google Calendar API integration
authMiddleware.js- JWT token validation
sendNotification.js- Notification delivery service
Technologies:
- Express.js 5.1.0
- Socket.IO 4.8.1
- MongoDB 6.20.0 + Mongoose 8.19.0
- LangChain 0.3.35
- JWT (jsonwebtoken 9.0.2)
- Google APIs (googleapis 161.0.0)
- Multer 2.0.2
- pdf-parse 1.1.1
-
Groq API (
@langchain/groq)- Primary LLM provider
- Used by all AI agents
- Model:
llama-3.3-70b-versatile
-
Google Gemini (
@langchain/google-genai)- Secondary LLM provider
- Fallback or alternative responses
-
Hugging Face (
@huggingface/inference)- Optional for specialized models
- OAuth2 Flow: User authorizes → Tokens stored → Calendar events created
- Integration: Medication schedules synced as calendar events
- Library:
googleapis161.0.0
- Authentication credentials (email, hashed password)
- JWT tokens
- Google OAuth2 tokens (for Calendar sync)
- Profile information
- Medication details (name, description, dosage)
- Schedule (dosage times, frequency, start/end dates)
- User association
- Status tracking
- Notification content (title, message)
- User association
- Timestamp and status
- Type (medication reminder, etc.)
- User health information
- Medical history
- Allergies, conditions
- Uploaded PDF reports
- Extracted text
- AI-generated analysis
- User association
- AI agent conversation history
- User messages and AI responses
- Agent type
- Timestamps
- Server-side: Socket.IO server initialized with Express HTTP server
- Client-side: Socket.IO client connects on app load
- Rooms: Users join personal rooms (
user-${userId}) for targeted notifications - Events:
join-user- User joins their notification roomnotification- Server emits notifications to user roomsdisconnect- Handle client disconnections
- Checks medication schedules periodically
- Creates notifications for due medications
- Emits via Socket.IO to user rooms
- Stores notifications in MongoDB
-
Authentication: JWT-based authentication
- Tokens stored in HTTP-only cookies or localStorage
- Auth middleware validates tokens on protected routes
-
Authorization: Role-based access (future enhancement)
- Currently: User-scoped data access
-
API Security:
- CORS configured for allowed origins
- Input validation (express-validator)
- Password hashing (bcryptjs)
-
Environment Variables:
- All secrets stored in
.envfiles - Never committed to repository
- Separate configs for client and server
- All secrets stored in
- Monolithic Express server
- Direct MongoDB connections
- In-memory Socket.IO connections
- File-based notification scheduling
- Microservices: Separate notification service, AI service
- Message Queue: Redis/RabbitMQ for notification delivery
- Caching: Redis for frequently accessed data
- Load Balancing: Multiple server instances
- Database Sharding: For large-scale user base
- CDN: For static assets
- Containerization: Docker for consistent deployments
- Manual testing via Postman/cURL
- Frontend manual testing
- No automated test suite
- Unit Tests: Jest for utilities and models
- Integration Tests: Supertest for API endpoints
- Component Tests: React Testing Library for UI components
- E2E Tests: Playwright/Cypress for full user flows
- Socket.IO Tests: Test real-time communication
- README.md - Project overview and quick start
- CONTRIBUTING.md - Contribution guidelines
- SECURITY.md - Security best practices
User Action
↓
React Frontend (UI/Context)
↓
HTTP Request / WebSocket
↓
Express Routes + Auth Middleware
↓
Controllers / Services
↓
┌─────────────────┬─────────────────┐
│ MongoDB │ External APIs │
│ (Data Store) │ (AI/Calendar) │
└─────────────────┴─────────────────┘
↓
Response / Socket.IO Event
↓
Frontend Update
↓
UI Re-render
Last Updated: 2024
For questions or clarifications about the architecture, please open a GitHub Discussion or Issue.
