MCP Server with DynamoDB Integration
A Model Context Protocol (MCP) server that uses DynamoDB to store and retrieve user information and context to provide personalized question answering capabilities.
🚀 Features
- User Authentication: JWT-based authentication with registration and login
- Context Management: Store and retrieve user conversation history and context
- Question Answering: Context-aware Q&A with user-specific responses
- MCP Protocol: Full Model Context Protocol implementation
- DynamoDB Integration: Scalable NoSQL database for user data
- Security: Rate limiting, CORS, input validation, and secure password handling
- Logging: Comprehensive logging with Winston
- TypeScript: Full TypeScript support with strict typing
📋 Prerequisites
- Node.js 18+
- AWS Account with DynamoDB access
- AWS CLI configured (optional, for local development)
🛠️ Installation
-
Clone the repository
bash git clone <repository-url> cd mcp-dynamodb-server -
Install dependencies
bash npm install -
Set up environment variables
bash cp env.example .env
Edit .env with your configuration:```env
# Server Configuration
PORT=3000
NODE_ENV=development
# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
JWT_EXPIRES_IN=24h
JWT_REFRESH_EXPIRES_IN=7d
# AWS Configuration
AWS_REGION=us-east-1
AWS_ACCESS_KEY_ID=your-aws-access-key
AWS_SECRET_ACCESS_KEY=your-aws-secret-key
# DynamoDB Configuration
DYNAMODB_ENDPOINT=http://localhost:8000 # Use AWS endpoint for production
DYNAMODB_TABLES_USERS=users
DYNAMODB_TABLES_USER_CONTEXTS=user_contexts
DYNAMODB_TABLES_QUESTIONS_ANSWERS=questions_answers
```
-
Set up DynamoDB tables
bash npm run setup-db -
Build the project
bash npm run build -
Start the server```bash
# Development mode
npm run dev
# Production mode
npm start
```
🏗️ Project Structure```
mcp-dynamodb-server/
├── src/
│ ├── server/
│ │ ├── mcp-server.ts # Main MCP server implementation
│ │ ├── handlers/
│ │ │ ├── auth-handler.ts # Authentication endpoints
│ │ │ ├── context-handler.ts # Context management
│ │ │ └── qa-handler.ts # Question answering
│ │ └── middleware/
│ │ ├── auth-middleware.ts # JWT authentication
│ │ └── logging.ts # Request logging
│ ├── database/
│ │ ├── dynamodb-client.ts # DynamoDB connection and operations
│ │ └── models/
│ │ └── user.ts # User data model
│ ├── utils/
│ │ ├── config.ts # Configuration management
│ │ └── logger.ts # Logging utilities
│ └── types/
│ └── mcp-types.ts # TypeScript type definitions
├── scripts/
│ └── setup-dynamodb.js # DynamoDB table creation
├── package.json
├── tsconfig.json
└── README.md
## 🔧 Configuration
### Environment Variables
| Variable | Description | Default |
|----------|-------------|---------|
| `PORT` | Server port | `3000` |
| `NODE_ENV` | Environment | `development` |
| `JWT_SECRET` | JWT signing secret | Required |
| `JWT_EXPIRES_IN` | Access token expiry | `24h` |
| `JWT_REFRESH_EXPIRES_IN` | Refresh token expiry | `7d` |
| `AWS_REGION` | AWS region | `us-east-1` |
| `AWS_ACCESS_KEY_ID` | AWS access key | Required |
| `AWS_SECRET_ACCESS_KEY` | AWS secret key | Required |
| `DYNAMODB_ENDPOINT` | DynamoDB endpoint | `http://localhost:8000` |
### DynamoDB Tables
The server creates three DynamoDB tables:
1. **users** - User profiles and authentication data
2. **user_contexts** - User conversation history and context
3. **questions_answers** - Q&A pairs and responses
## 📚 API Documentation
### Authentication Endpoints
#### Register User```http
POST /api/auth/register
Content-Type: application/json
{
"email": "user@example.com",
"username": "username",
"password": "password123",
"firstName": "John",
"lastName": "Doe"
}
Login```http
POST /api/auth/login
Content-Type: application/json
{
"email": "user@example.com",
"password": "password123"
}
#### Refresh Token```http
POST /api/auth/refresh
Content-Type: application/json
{
"refreshToken": "your-refresh-token"
}
Context Management
Create Context```http
POST /api/context
Authorization: Bearer <access-token>
Content-Type: application/json
{
"content": "User conversation context",
"source": "chat",
"tags": ["conversation", "support"],
"relevance": 0.8
}
#### Get User Context```http
GET /api/context/:userId?limit=10&offset=0
Authorization: Bearer <access-token>
Update Context```http
PUT /api/context/:userId/:contextId
Authorization: Bearer <access-token>
Content-Type: application/json
{
"content": "Updated context content",
"relevance": 0.9
}
### Question Answering
#### Ask Question```http
POST /api/qa/ask
Authorization: Bearer <access-token>
Content-Type: application/json
{
"question": "What is the status of my order?",
"useContext": true,
"contextLimit": 10,
"category": "support",
"priority": 3,
"tags": ["order", "status"]
}
Get Q&A History```http
GET /api/qa/history/:userId?limit=20&offset=0
Authorization: Bearer <access-token>
### MCP Protocol
The server implements the Model Context Protocol and exposes tools:
- `get_user_context` - Retrieve user context and conversation history
- `store_user_context` - Store new user context or conversation
- `answer_question` - Answer a question using user context
- `get_user_profile` - Get user profile information
## 🔒 Security Features
- **JWT Authentication**: Secure token-based authentication
- **Password Hashing**: bcrypt for password security
- **Rate Limiting**: Request rate limiting per IP and user
- **Input Validation**: Joi schema validation for all inputs
- **CORS Protection**: Configurable CORS settings
- **Helmet**: Security headers middleware
- **Request Logging**: Comprehensive request/response logging
## 🧪 Testing```bash
# Run tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode
npm run test:watch
📝 Logging
The server uses Winston for logging with the following levels:
- Error: Application errors and exceptions
- Warn: Warning messages
- Info: General information and requests
- Debug: Detailed debugging information
Logs are written to:
- Console (development)
- logs/app.log (all levels)
- logs/error.log (error level only)
🚀 Deployment
Docker Deployment
-
Build Docker image
bash docker build -t mcp-dynamodb-server . -
Run container
bash docker run -p 3000:3000 --env-file .env mcp-dynamodb-server
AWS Deployment
- Set up AWS credentials
- Create DynamoDB tables
- Deploy to ECS or Lambda
- Configure environment variables
🔧 Development
Available Scripts```bash
npm run build # Build TypeScript
npm run dev # Start development server
npm run start # Start production server
npm run test # Run tests
npm run lint # Run ESLint
npm run lint:fix # Fix ESLint issues
npm run format # Format code with Prettier
npm run setup-db # Set up DynamoDB tables
```
Code Quality
- TypeScript: Strict type checking
- ESLint: Code linting and style enforcement
- Prettier: Code formatting
- Jest: Unit and integration testing
🤝 Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Run the test suite
- Submit a pull request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🆘 Support
For support and questions:
- Create an issue in the repository
- Check the documentation
- Review the API examples
🔮 Roadmap
- [ ] AI service integration (OpenAI, Anthropic)
- [ ] Context summarization and optimization
- [ ] Real-time notifications
- [ ] Advanced analytics and metrics
- [ ] Multi-tenant support
- [ ] GraphQL API
- [ ] WebSocket support for real-time features
