NINSAÚDE MCP Server
by Sudo-psc
README.md
# NINSAÚDE MCP Server
A comprehensive MCP (Model Context Protocol) server for integrating with the NINSAÚDE Clinic API, providing 45+ tools for healthcare management including patient records, appointments, medical records, billing, reporting, and patient surveys.
## Features
- **Secure Authentication**: Refresh-token-first OAuth2 authentication with maximum security
- **One-time credential usage**: Credentials used only once to obtain refresh_token
- **Persistent storage**: Refresh token stored securely in ~/.ninsaude/tokens.json (0o600 permissions)
- **No credential storage**: Credentials never stored or transmitted after initialization
- **Automatic renewal**: All authentications use refresh_token only
- **In-memory caching**: Access tokens cached temporarily (15min expiry, 1min safety buffer)
- **Rate Limiting**: Automatic request throttling with configurable minimum intervals (default 60s between requests)
- **Patient Management**: Complete CRUD operations for patient records
- **Appointment System**: Schedule, reschedule, and manage appointments
- **Medical Records**: Create and manage electronic health records
- **Financial Management**: Track revenue, expenses, and payment status
- **Reporting**: Generate various reports for appointments, finances, and patients
- **Professional & Service Management**: Manage healthcare providers and services
- **Insurance Integration**: Handle insurance companies and plans
- **Alert System**: Create patient alerts and blocks
- **Survey System**: Create and send patient surveys, collect responses, and analyze results
## Installation
### Quick Installation for Claude Desktop
#### macOS/Linux
```bash
# Clone the repository
git clone <repository-url>
cd MCP-NIN
# Run the installation script
./install-claude-desktop.sh
```
#### Windows
```powershell
# Clone the repository
git clone <repository-url>
cd MCP-NIN
# Run the installation script
powershell -ExecutionPolicy Bypass -File install-claude-desktop.ps1
```
### Manual Installation
```bash
# Clone the repository
git clone <repository-url>
cd MCP-NIN
# Install dependencies
npm install
# Build the TypeScript code
npm run build
```
## Configuration
### 1. Environment Setup
Create a `.env` file with your NINSAÚDE API credentials:
```bash
cp .env.example .env
```
Edit `.env` with your credentials:
```env
NINSAUDE_API_URL=https://api.ninsaude.com/v1
NINSAUDE_ACCOUNT=your_account_here
NINSAUDE_USERNAME=your_username_here
NINSAUDE_PASSWORD=your_password_here
NINSAUDE_ACCOUNT_UNIT=your_unit_id_here
# Optional: Configure rate limiting (default is 60 seconds)
NINSAUDE_RATE_LIMIT_SECONDS=60
```
**Important**: Credentials are only used once during initialization. After that, they are never used or stored again.
### 2. Authentication Initialization
Initialize authentication to generate and store the refresh token:
```bash
npm run token:init
```
This command will:
- ✓ Authenticate with your credentials (one-time only)
- ✓ Obtain and store refresh_token securely in `~/.ninsaude/tokens.json`
- ✓ Set file permissions to 0o600 (owner read/write only)
- ✓ Clear credentials from memory after obtaining token
**Security Note**: After initialization, your credentials are never used or transmitted again. All future authentications use only the refresh_token.
### 3. Token Management Commands
```bash
# Check authentication status
npm run token:status
# Revoke token and clear storage (logout)
npm run token:revoke
# Get help
npm run token:help
```
### Rate Limiting Configuration
The MCP server includes built-in rate limiting to prevent overwhelming the NINSAÚDE API:
- **Default Interval**: 60 seconds between requests
- **Configurable**: Set `NINSAUDE_RATE_LIMIT_SECONDS` in `.env`
- **Automatic**: All API requests automatically respect the configured interval
- **Transparent**: Requests are queued and delayed as needed
- **Monitoring**: Check rate limiter statistics for debugging
The rate limiter ensures compliance with API usage policies and prevents service disruptions due to excessive requests.
### Claude Desktop Integration
The installation scripts automatically configure Claude Desktop. If you need to configure manually:
1. Locate Claude Desktop config file:
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Linux**: `~/.config/Claude/claude_desktop_config.json`
- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
2. Add the NINSAÚDE MCP server configuration:
```json
{
"mcpServers": {
"ninsaude-mcp-server": {
"command": "node",
"args": ["/path/to/MCP-NIN/dist/index.js"],
"env": {
"NODE_ENV": "production"
}
}
}
}
```
3. Restart Claude Desktop to load the new server
## Usage
### Starting the Server
```bash
# Production mode
npm start
# Development mode
npm run dev
```
### Available Tools
#### Authentication Tools
- `ninsaude_get_token` - Get OAuth2 access token
- `ninsaude_revoke_token` - Revoke current refresh token
#### Unit Management
- `ninsaude_list_units` - List healthcare units
- `ninsaude_get_unit` - Get specific unit details
#### Patient Management
- `ninsaude_list_patients` - List patients with filtering
- `ninsaude_get_patient` - Get patient by ID
- `ninsaude_create_patient` - Create new patient
- `ninsaude_update_patient` - Update patient information
- `ninsaude_delete_patient` - Delete patient record
#### Appointment Management
- `ninsaude_list_appointments` - List appointments with filters
- `ninsaude_get_appointment` - Get appointment details
- `ninsaude_create_appointment` - Create new appointment
- `ninsaude_update_appointment_status` - Update appointment status
- `ninsaude_reschedule_appointment` - Reschedule appointment
- `ninsaude_list_available_slots` - Check available time slots
#### Professional & Service Management
- `ninsaude_list_professionals` - List healthcare professionals
- `ninsaude_get_professional` - Get professional details
- `ninsaude_list_services` - List available services
- `ninsaude_get_service` - Get service details
#### Medical Records
- `ninsaude_list_medical_records` - List medical records
- `ninsaude_get_medical_record` - Get specific medical record
- `ninsaude_create_medical_record` - Create new medical record
- `ninsaude_list_prescriptions` - List prescriptions
#### Financial Management
- `ninsaude_list_financial_records` - List financial records
- `ninsaude_get_financial_record` - Get financial record details
- `ninsaude_create_financial_record` - Create financial entry
- `ninsaude_update_financial_status` - Update payment status
#### Insurance Management
- `ninsaude_list_insurances` - List insurance companies
- `ninsaude_get_insurance` - Get insurance details
#### Reporting Tools
- `ninsaude_appointment_report` - Generate appointment reports
- `ninsaude_financial_report` - Generate financial reports
- `ninsaude_patient_report` - Generate patient reports
#### Additional Tools
- `ninsaude_list_documents` - List document templates
- `ninsaude_list_patient_alerts` - List patient alerts
- `ninsaude_create_patient_alert` - Create patient alert
## Examples
### Creating a Patient
```javascript
{
"tool": "ninsaude_create_patient",
"arguments": {
"nome": "João Silva",
"cpf": "12345678901",
"dataNascimento": "1990-05-15",
"sexo": "M",
"email": "joao.silva@email.com",
"celular": "11999999999",
"endereco": {
"cep": "01310-100",
"logradouro": "Av. Paulista",
"numero": "1000",
"bairro": "Bela Vista",
"cidade": "São Paulo",
"estado": "SP"
}
}
}
```
### Scheduling an Appointment
```javascript
{
"tool": "ninsaude_create_appointment",
"arguments": {
"pacienteId": 123,
"profissionalId": 45,
"unidadeId": 1,
"servicoId": 10,
"dataHora": "2024-01-20 14:00:00",
"duracao": 30,
"observacoes": "First consultation"
}
}
```
### Listing Appointments with Filters
```javascript
{
"tool": "ninsaude_list_appointments",
"arguments": {
"filter": {
"dataInicio": "2024-01-01",
"dataFim": "2024-01-31",
"status": "AGENDADO",
"profissionalId": 45
},
"limit": 20,
"order": "-dataHora"
}
}
```
### Creating a Medical Record
```javascript
{
"tool": "ninsaude_create_medical_record",
"arguments": {
"pacienteId": 123,
"profissionalId": 45,
"agendamentoId": 789,
"anamnese": "Patient reports headaches for the past week",
"exameFisico": "Blood pressure: 120/80, Temperature: 36.5°C",
"hipoteseDiagnostica": "Tension headache",
"conduta": "Rest and hydration recommended",
"prescricao": [
{
"medicamento": "Paracetamol 500mg",
"dosagem": "1 tablet",
"frequencia": "Every 8 hours",
"duracao": "3 days",
"observacoes": "Take with food"
}
]
}
}
```
## Development
### Running Tests
```bash
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Generate coverage report
npm test -- --coverage
```
### Linting and Formatting
```bash
# Run ESLint
npm run lint
# Format code with Prettier
npm run format
```
## API Rate Limits and Best Practices
- **Automatic Rate Limiting**: The server enforces a minimum interval between requests (default 60s). All requests are automatically delayed if needed
- **Configuration**: Adjust `NINSAUDE_RATE_LIMIT_SECONDS` in `.env` to change the minimum interval (not recommended to go below 30s)
- **Monitoring**: Rate limiting is logged to stderr for debugging and monitoring
- **Pagination**: Use pagination parameters (`limit`, `offset`) for large datasets
- **Caching**: Cache frequently accessed data when possible to reduce API calls
- **Error Handling**: Handle errors gracefully and check error responses
- **Token Lifecycle**:
- Refresh tokens stored persistently (no expiration until revoked)
- Access tokens cached in memory for 15 minutes
- Automatic renewal using refresh_token only
- No credentials required after initial setup
## Error Handling
All tools return consistent error formats:
```javascript
{
"error": "Error message description"
}
```
For API errors, the format includes the HTTP status code:
```javascript
{
"error": "404: Record not found"
}
```
## Contributing
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## License
MIT License - see LICENSE file for details
## Support
For issues and questions:
- Check the NINSAÚDE API documentation
- Review error messages for specific error codes
- Open an issue in the repositoryThis server cannot be deployed
Maintenance
ActivityInactive
ResponsivenessNo issues