MCP Session Management
MCP Session Management
Section titled “MCP Session Management”This document describes the session management implementation in the MCP (Model Context Protocol) server.
Overview
Section titled “Overview”The MCP server provides comprehensive session management tools that integrate with the existing authentication system. Sessions are created using username/password authentication and can be used for subsequent API operations across all protocols (REST, gRPC, WebSocket).
Features
Section titled “Features”- User Authentication: Authenticate users with username/password credentials
- Session Creation: Create time-limited sessions with JWT tokens
- Session Listing: List active sessions for a specific user
- Session Deletion: Manually delete sessions before expiration
- Browser Context Creation: Create Puppeteer browser contexts with authenticated sessions
- Multi-Protocol Support: Use sessions across REST, gRPC, and WebSocket protocols
Security Features
Section titled “Security Features”- NIST Compliance: All authentication operations are tagged with NIST security controls
- Audit Logging: All authentication attempts and session operations are logged
- Password Hashing: Passwords are hashed using SHA-256 (production should use bcrypt/argon2)
- Token Generation: Sessions include both access and refresh JWT tokens
- Permission Enforcement: Role-based access control (RBAC) with granular permissions
- Session Expiration: Configurable session duration with automatic cleanup
Available Tools
Section titled “Available Tools”1. create-session
Section titled “1. create-session”Creates a new authenticated session.
Input Schema:
{ "username": "string (required)", "password": "string (required)", "duration": "number (optional, seconds, default: 3600)"}
Response:
{ "sessionId": "uuid", "userId": "uuid", "username": "string", "roles": ["string"], "createdAt": "ISO 8601 datetime", "expiresAt": "ISO 8601 datetime", "tokens": { "accessToken": "JWT string", "refreshToken": "JWT string", "expiresIn": "number (seconds)" }}
Error Response:
{ "error": "string", "code": "INVALID_CREDENTIALS | AUTH_FAILED"}
2. list-sessions
Section titled “2. list-sessions”Lists active sessions for a specific user.
Input Schema:
{ "userId": "string (optional)"}
Response:
{ "sessions": [ { "id": "uuid", "userId": "uuid", "username": "string", "roles": ["string"], "createdAt": "ISO 8601 datetime", "expiresAt": "ISO 8601 datetime", "lastAccessedAt": "ISO 8601 datetime", "metadata": {} } ], "count": "number"}
3. delete-session
Section titled “3. delete-session”Deletes an active session.
Input Schema:
{ "sessionId": "string (required)"}
Response:
{ "success": true, "sessionId": "string", "message": "Session deleted successfully"}
Error Response:
{ "error": "string", "code": "INVALID_SESSION_ID | SESSION_NOT_FOUND | DELETE_FAILED"}
4. create-browser-context
Section titled “4. create-browser-context”Creates a Puppeteer browser context using an authenticated session.
Input Schema:
{ "sessionId": "string (required)", "name": "string (optional)", "options": { "headless": "boolean (optional)", "viewport": { "width": "number (optional)", "height": "number (optional)" } }}
Response:
{ "contextId": "uuid", "name": "string", "type": "puppeteer", "status": "active", "createdAt": "ISO 8601 datetime"}
Demo Users
Section titled “Demo Users”The system includes three demo users for testing:
Admin User
Section titled “Admin User”- Username: admin
- Password: admin123!
- Roles: [‘admin’, ‘user’]
- Description: Full administrative permissions
Demo User
Section titled “Demo User”- Username: demo
- Password: demo123!
- Roles: [‘user’]
- Description: Standard user permissions
Viewer User
Section titled “Viewer User”- Username: viewer
- Password: viewer123!
- Roles: [‘viewer’]
- Description: Read-only permissions
Usage Examples
Section titled “Usage Examples”Creating a Session
Section titled “Creating a Session”// MCP tool call{ "tool": "create-session", "arguments": { "username": "demo", "password": "demo123!", "duration": 7200 // 2 hours }}
Using Session for API Calls
Section titled “Using Session for API Calls”// Use session with execute-api tool{ "tool": "execute-api", "arguments": { "protocol": "rest", "operation": { "method": "GET", "endpoint": "/api/v1/contexts" }, "auth": { "type": "session", "credentials": "session-uuid-here" } }}
Authentication Flow
Section titled “Authentication Flow”- Login: Create session with username/password
- Receive Tokens: Get session ID and JWT tokens
- Use Session: Include session ID in subsequent operations
- Auto-Expiration: Sessions expire after the specified duration
- Manual Cleanup: Delete session when done (optional)
Implementation Details
Section titled “Implementation Details”Session Store
Section titled “Session Store”Sessions are stored in an in-memory store (InMemorySessionStore
) with the following features:
- Automatic cleanup of expired sessions (runs every minute)
- User-based session tracking
- Audit logging for all operations
- Touch mechanism to update last accessed time
Authentication Bridge
Section titled “Authentication Bridge”The MCPAuthBridge
provides unified authentication across different methods:
- JWT token verification
- API key verification
- Session-based authentication
- Permission checking for MCP tools
Security Logging
Section titled “Security Logging”All authentication events are logged with appropriate NIST tags:
@nist ia-2
: Identification and authentication@nist ac-3
: Access enforcement@nist au-3
: Content of audit records@nist ia-5
: Authenticator management
Error Handling
Section titled “Error Handling”The implementation includes comprehensive error handling:
- Input validation using Zod schemas
- Detailed error messages with error codes
- Security event logging for failures
- Graceful handling of edge cases
Production Considerations
Section titled “Production Considerations”- Password Hashing: Replace SHA-256 with bcrypt or argon2
- Session Storage: Use Redis or similar for distributed systems
- Rate Limiting: Implement rate limiting on authentication endpoints
- Token Rotation: Implement automatic token rotation
- Multi-Factor Authentication: Add MFA support for enhanced security
- Session Monitoring: Implement real-time session monitoring
- Compliance Reporting: Generate NIST compliance reports
Testing
Section titled “Testing”The implementation includes comprehensive unit tests covering:
- Valid and invalid authentication
- Session lifecycle management
- Permission enforcement
- Error scenarios
- Full authentication workflow
Run tests with:
npm test src/mcp/server.test.ts
Future Enhancements
Section titled “Future Enhancements”- OAuth2/OIDC Support: Integration with external identity providers
- Session Persistence: Database-backed session storage
- Session Analytics: Track session usage patterns
- Geolocation Tracking: Log session locations for security
- Device Fingerprinting: Enhanced security through device tracking
- Session Sharing: Allow session delegation between users
- Batch Operations: Bulk session management operations