Nightscout MCP Server
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Nightscout MCP Server What's my current glucose?"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
What is this?
Nightscout MCP is a Model Context Protocol server that bridges your Nightscout CGM instance with AI assistants. Ask questions about your glucose data in natural language — the AI gets structured access to your readings, treatments, profiles, statistics, and pattern analysis.
"What's my TIR for the past week?" "How did that pizza affect my glucose?" "Detect patterns in my overnight readings" "Compare training days vs rest days"
Works with any MCP-compatible client.
Related MCP server: Sensor Bio MCP Server
⚡ Quick Start
# 1. Clone and install
git clone https://github.com/adminpb/Nightscout-MCP.git
cd Nightscout-MCP
npm install
# 2. Build
npm run build
# 3. Configure your MCP client (see below)MCP Client Configuration
Add to your MCP client config (e.g. claude_desktop_config.json):
{
"mcpServers": {
"nightscout": {
"command": "node",
"args": ["C:\\Magic\\Nightscout-MCP\\dist\\index.js"],
"env": {
"NIGHTSCOUT_URL": "https://your-nightscout.example.com",
"NIGHTSCOUT_TOKEN": "your-read-token",
"NIGHTSCOUT_UNITS": "mmol/L",
"NIGHTSCOUT_LOCALE": "en"
}
}
}
}🔧 Tools
Reading Data
Tool | Description |
| Latest glucose with trend arrow ↗, delta, age, and status |
| SGV entries for any time period — hours lookback or exact date range |
| Insulin boluses, carb entries, notes, exercise — with summaries |
| Active profile: ISF, ICR, basal rates, target ranges, DIA |
| Pump/sensor/loop status, IOB, COB, battery, predictions |
| Glucose at a specific moment: "what was my BG at 3 AM?" |
| Search treatments/notes by text or type: "when did I change my sensor?" |
Analytics
Tool | Description |
| TIR, average glucose, estimated HbA1c, GMI, SD, CV, time-in-ranges |
| Full day summary: glucose stats + treatments + notable events |
| Automatic pattern recognition: overnight lows, dawn phenomenon, post-meal spikes, variability |
| Side-by-side comparison of two periods: training vs rest, this week vs last |
| Automatic post-meal analysis: peak, time-to-peak, rise, recovery, bolus assessment |
| Detailed overnight report: stability, drift, dawn phenomenon, basal adequacy |
| Project future HbA1c based on CGM trends and optional last lab result |
| One-call this week vs last week with improvement indicators |
| Real-world ISF analysis from correction boluses vs profile |
| Real-world ICR analysis from meal boluses vs profile |
| Detect false lows from sensor compression during sleep |
| Export glucose + treatments as CSV for doctors or spreadsheets |
Writing Data
Tool | Description |
| Add insulin, carbs, exercise, site change, or any treatment entry |
| Quick timestamped note — meals, symptoms, activities |
Write tools require
NIGHTSCOUT_READONLY=false.
📋 Prompts
Pre-built prompt templates for common workflows:
Prompt | What it does |
| Comprehensive analysis of today's glucose patterns |
| Post-meal glucose response assessment |
| 7-day report with TIR trends and recommendations |
| Data-driven suggestions for basal/ISF/ICR adjustments |
📦 Resources
URI | Description |
| Server status, API permissions, version |
| Full active profile as context |
⚙️ Configuration
Variable | Required | Default | Description |
| ✅ | — | Your Nightscout instance URL |
| ✅* | — | Read token (recommended) |
| ✅* | — | Or API secret (hashed automatically) |
|
| Glucose units: | |
|
| Set | |
|
| Language: |
* Either
NIGHTSCOUT_TOKENorNIGHTSCOUT_API_SECRETis required.
🌍 Localization
Nightscout MCP supports multiple languages. All tool names and MCP interface remain in English for compatibility. Locale affects status labels, messages, and report strings in tool responses.
Locale | Language |
| English (default) |
| Українська (Ukrainian) |
Adding a new locale: create a translation object in src/i18n/index.ts following the TranslationStrings interface. PRs welcome!
🔒 Security
Tokens never reach the AI — only processed data is returned via MCP
Read-only by default — write operations require explicit opt-in
Input validation — all parameters validated with Zod schemas
SHA1 hashing — API secrets are hashed before transmission
🛠 Development
npm run dev # TypeScript watch mode
npm run build # Production build
npm start # Run the serverProject Structure
src/
├── index.ts # MCP server — tools, resources, prompts
├── config.ts # Environment variable configuration
├── client.ts # Nightscout REST API v1 client
├── i18n/
│ └── index.ts # Internationalization (en, uk)
└── tools/
├── get_current_glucose.ts
├── get_glucose_history.ts
├── get_statistics.ts
├── get_treatments.ts
├── get_profile.ts
├── get_device_status.ts
├── get_daily_report.ts
├── detect_patterns.ts
├── compare_periods.ts
├── analyze_meal.ts
├── overnight_analysis.ts
├── find_events.ts
├── glucose_at_time.ts
├── a1c_estimator.ts
├── export_csv.ts
├── weekly_comparison.ts
├── insulin_sensitivity_check.ts
├── carb_ratio_check.ts
├── compression_low_analysis.ts
├── add_treatment.ts
└── add_note.ts📊 Example Queries
Once connected, you can ask your AI assistant:
"What's my glucose right now?"
"Show my TIR for the past 7 days"
"Analyze how coffee with kefir spiked my glucose"
"Give me a daily report for yesterday"
"What were my lows this week?"
"Do I have a dawn phenomenon?"
"Detect patterns in my last 14 days"
"Compare my glucose on workout days vs rest days"
"Are my basal rates set correctly based on overnight patterns?"
"Is my ISF accurate? Check correction bolus data"
"Am I bolusing enough for meals? Check my carb ratios"
"How am I doing this week compared to last?"
"Are my nighttime lows real or compression artifacts?"
"Estimate my HbA1c for my lab appointment on March 16"
"Export my last 2 weeks as CSV for my doctor"
"Log 45g carbs and 4U insulin for lunch"Roadmap
Core tools: glucose, treatments, statistics, profiles, device status
Daily reports with notable events
Localization (EN / UK)
detect_patterns— overnight lows, dawn phenomenon, post-meal spikes, variabilityadd_treatment/add_note— write operationscompare_periods— side-by-side period comparisonanalyze_meal/overnight_analysis— deep analyticsfind_events/glucose_at_time— search and lookupa1c_estimator— future HbA1c projectionexport_csv— data export for doctorsAPI response caching with TTL
weekly_comparison— auto this-week vs last-weekinsulin_sensitivity_check— real ISF from correction datacarb_ratio_check— real ICR from meal datacompression_low_analysis— false low detectionnpm package publishing
Docker image
More locales (ES, DE, PL, ...)
📄 License
GPL v3 with additional terms under Section 7:
Attribution required — original author adminpb <adminpb@ukr.net> must be credited in all copies and derivatives
🇷🇺 Russia restriction — use of this software within the Russian Federation, by RF citizens, or by RF-registered entities is expressly prohibited
Free and open source for everyone else. See LICENSE for full details.
Що це?
Nightscout MCP — це сервер Model Context Protocol, який з'єднує ваш Nightscout з AI-асистентами. Запитуйте про глюкозу природною мовою — AI отримує структурований доступ до показників, лікування, профілів, статистики та аналізу патернів.
«Який у мене TIR за останній тиждень?» «Як піца вплинула на глюкозу?» «Знайди патерни в нічних показниках» «Порівняй дні з тренуванням і без»
Швидкий старт
git clone https://github.com/adminpb/Nightscout-MCP.git
cd Nightscout-MCP
npm install
npm run buildДодайте в конфігурацію вашого MCP-клієнта:
{
"mcpServers": {
"nightscout": {
"command": "node",
"args": ["C:\\Magic\\Nightscout-MCP\\dist\\index.js"],
"env": {
"NIGHTSCOUT_URL": "https://ваш-nightscout.example.com",
"NIGHTSCOUT_TOKEN": "ваш-токен",
"NIGHTSCOUT_UNITS": "mmol/L",
"NIGHTSCOUT_LOCALE": "uk"
}
}
}
}Інструменти
Читання даних
Інструмент | Опис |
| Поточна глюкоза + тренд ↗, дельта, вік показника |
| Історія SGV за будь-який період |
| Болюси, вуглеводи, нотатки, вправи |
| Профіль: ISF, ICR, базальні рати, цільові діапазони |
| Помпа, сенсор, IOB, COB, батарея |
| Глюкоза в конкретний момент: «яка була о 3 ночі?» |
| Пошук по записах: «коли міняв сенсор?», «знайди всі записи про каву» |
Аналітика
Інструмент | Опис |
| TIR, середня, HbA1c, GMI, SD, CV, час у діапазонах |
| Повний звіт за день |
| Патерни: нічні гіпо, феномен світанку, постпрандіальні піки, варіабельність |
| Порівняння двох періодів: тренування vs відпочинок, цей тиждень vs минулий |
| Аналіз після їжі: пік, час до піку, підйом, відновлення, оцінка болюсу |
| Нічний звіт: стабільність, дрейф, феномен світанку, оцінка базалу |
| Прогноз HbA1c на дату аналізу на основі CGM трендів |
| Цей тиждень vs минулий з індикаторами покращення |
| Реальна ISF з корекційних болюсів vs профіль |
| Реальний ICR з їжі vs профіль |
| Виявлення хибних лоу від компресії сенсора під час сну |
| Експорт глюкози + лікування в CSV для лікаря або Excel |
Запис даних
Інструмент | Опис |
| Додати інсулін, вуглеводи, вправу, заміну катетера |
| Швидка нотатка з відміткою часу |
Запис потребує
NIGHTSCOUT_READONLY=false.
Шаблони запитів (Prompts)
Шаблон | Що робить |
| Аналіз глюкози за сьогодні |
| Вплив їжі на глюкозу |
| Тижневий звіт з трендами |
| Рекомендації по налаштуваннях |
Змінні середовища
Змінна | Обов'язкова | Опис |
| ✅ | URL Nightscout інстансу |
| ✅* | Токен доступу (рекомендовано) |
| ✅* | Або API secret |
|
| |
|
| |
|
|
Безпека
Токени ніколи не передаються в AI — тільки оброблені дані
Read-only за замовчуванням — запис вимагає явного увімкнення
Валідація входу — Zod-схеми для всіх параметрів
Локалізація
Встановіть NIGHTSCOUT_LOCALE=uk для українських статусів та повідомлень. Назви інструментів залишаються англійською для сумісності.
Хочете додати свою мову? Створіть об'єкт перекладу в src/i18n/index.ts за інтерфейсом TranslationStrings.
Ліцензія
GPL v3 з додатковими умовами (Секція 7):
Обов'язкове зазначення автора — оригінальний автор adminpb <adminpb@ukr.net> має бути вказаний у всіх копіях та похідних роботах
🇷🇺 Обмеження для РФ — використання цього ПЗ на території Російської Федерації, громадянами РФ або юридичними особами, зареєстрованими в РФ, суворо заборонено
Безкоштовний відкритий код для всіх інших. Деталі в LICENSE.
Available Tools
21 toolsa1c_estimatorA
Estimate future HbA1c based on current CGM data and optional last lab result. Uses GMI from recent data weighted with historical HbA1c decay. Useful before lab visits to set expectations.
Inputs: last_a1c, target_date, last_a1c_date.
add_noteA
Quickly add a timestamped note to Nightscout. Useful for logging meals, activities, symptoms, or any context. Requires NIGHTSCOUT_READONLY=false.
Inputs: text (required), created_at.
add_treatmentA
Add a treatment entry to Nightscout: insulin bolus, carbs, note, exercise, site change, etc. Requires NIGHTSCOUT_READONLY=false. Returns the created entry for confirmation.
Inputs: eventType (required), carbs, notes, insulin, +2 more.
analyze_mealA
Automatically analyze post-meal glucose response. Finds the meal bolus/carbs entry, tracks glucose before, during, and after the meal. Calculates: pre-meal glucose, peak value, time to peak, rise amount, time to return to range. Assesses bolus adequacy.
Inputs: meal_time, hours_after.
carb_ratio_checkA
Analyze real-world carb ratios by evaluating meal boluses and their post-meal glucose impact. Compares actual ICR effectiveness vs profile settings. Identifies if you're under- or over-bolusing for meals.
Inputs: days, target_rise_max.
compare_periodsA
Compare glucose statistics between two time periods side by side. Use for: training vs rest days, this week vs last week, before vs after medication changes, weekdays vs weekends. Returns TIR, average, SD, CV, HbA1c, and time-in-ranges for both periods with deltas.
Inputs: periodA_to (required), periodB_to (required), periodA_from (required), periodB_from (required), +2 more.
compression_low_analysisA
Detect probable compression lows (false low readings caused by lying on the CGM sensor). Identifies characteristic patterns: sudden drop during sleep hours, quick V-shaped recovery without treatment, readings that seem too low for the context. Helps distinguish real lows from sensor artifacts.
Inputs: days.
detect_patternsA
Analyze glucose data over multiple days to detect recurring patterns: overnight lows, dawn phenomenon, post-meal spikes, time-of-day trends, and day-to-day variability. Requires at least 3 days of data.
Inputs: days, targetLow, targetHigh.
export_csvA
Export glucose data (and optionally treatments) as CSV text. Useful for sharing with healthcare providers, importing into spreadsheets, or further analysis. Returns CSV as text content.
Inputs: hours, dateTo, dateFrom, include_treatments.
find_eventsA
Search treatment entries by text in notes or by event type. Use to answer: 'when did I last change my sensor?', 'show all coffee entries', 'find exercise logs this week'. Searches up to 30 days of history.
Inputs: hours, query, dateTo, dateFrom, +1 more.
get_current_glucoseA
Get the current (latest) glucose value with trend direction, delta from previous reading, and how old the reading is. Always call this first to understand the current state.
Inputs: no named parameters.
get_daily_reportA
Generate a comprehensive daily report: glucose stats (min/max/avg/TIR), all treatments (insulin, carbs, notes), time in ranges, and notable events. Perfect for daily review.
Inputs: date.
get_device_statusA
Get device status: pump reservoir/battery, sensor info, loop status, active IOB (insulin on board), COB (carbs on board), and predictions. Shows the current state of the diabetes management system.
Inputs: count.
get_glucose_historyA
Get glucose reading history for a specified time period. Returns SGV values with timestamps and trend directions. Use 'hours' for simple lookback or 'dateFrom'/'dateTo' for precise ranges.
Inputs: count, hours, dateTo, dateFrom.
get_profileA
Get the active Nightscout profile: insulin sensitivity factor (ISF), insulin-to-carb ratio (ICR), basal rates, target glucose ranges, and DIA. Useful for understanding pump/loop settings.
Inputs: no named parameters.
get_statisticsA
Calculate glucose statistics: Time in Range (TIR), average glucose, estimated HbA1c, standard deviation (SD), coefficient of variation (CV), and time in various ranges. Essential for understanding overall glucose control quality.
Inputs: hours, dateTo, dateFrom, targetLow, +1 more.
get_treatmentsA
Get treatment records: insulin boluses, carb entries, notes, exercise logs, temp basals, and more. Use to understand insulin and carb history for analysis.
Inputs: count, hours, dateTo, dateFrom, +1 more.
glucose_at_timeA
Get the glucose reading closest to a specific point in time. Returns the nearest reading within a configurable window, plus surrounding context (readings before and after). Use for: 'what was my glucose at 3 AM?', 'glucose when I woke up yesterday'.
Inputs: time (required), window.
insulin_sensitivity_checkA
Analyze real-world insulin sensitivity by tracking correction boluses and their glucose impact. Compares actual ISF from data with profile ISF to detect if settings need adjustment. Requires at least 3 days with correction events.
Inputs: days.
overnight_analysisA
Detailed overnight glucose analysis: stability, trend direction, min/max with timestamps, dawn phenomenon detection, time in range, and basal adequacy assessment. Analyzes from evening to morning.
Inputs: date, night_end, night_start.
weekly_comparisonA
One-call comparison of this week vs last week. Automatically calculates both periods and returns side-by-side stats: TIR, average, CV, HbA1c, time-in-ranges with improvement indicators. No parameters needed.
Inputs: no named parameters.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 21 tools
Most tools have a distinct resource type (glucose, treatments, profile, device), but the analytics cluster overlaps: weekly_comparison vs compare_periods, get_statstics vs get_daaily_report, and detect_paterns vs overnight_analysis cover similar ground. Descriptions reduce ambiguity, but an agent could still misselect between comparison/statistics tools.
The majority of names follow a readable snake_case get_/analyze_/compare_ verb pattern, with clear nouns. Minor deviations like weekly_comparison, glucose_at_time, and a1c_estimator omit a verb, but the overall naming is predictable and easy to scan.
21 tool is on the heavy side for an MCP server, especially with many single-purpose analysis tools such as carb_ratio_check, insulin_sensitivity_check, and compression_low_analysis. It is not wildly bloated, but several routines could has been consolidated without hurting the server's utility.
The set covers current glucose, history, treatments, profile/device status, reporting, pattern detection, meal/overnight analysis, CSV export, and adding treatments/notes, so the main Nightscout workflows have no dead ends. Minor gaps include no update/delete for treatments/notes and no dedicated event-type filtering beyond find_events.
Maintenance
Related MCP Connectors
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
Your own SLATE health data in your AI assistant: read, trend, plan and log. Never suggests a dose.
Glucose readings from your LibreLink Up sensor: graph, logbook, stats and summaries (read-only). Sec
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceConnects AI assistants to Nightscout for real-time glucose monitoring, analysis, and treatment logging, enabling natural language interaction with CGM data.7MIT

Sensor Bio MCP Serverofficial
AlicenseAqualityCmaintenanceConnects Sensor Bio wearable data to AI assistants via the Model Context Protocol, enabling queries about sleep, heart rate, activity, and other biometrics.131MIT- AlicenseNot gradedqualityBmaintenanceA Model Context Protocol (MCP) server that connects Claude to your personal Dexcom CGM (Continuous Glucose Monitor) for assistive diabetes management intelligence.MIT
- AlicenseBqualityDmaintenanceEnables AI assistants to access and analyze Continuous Glucose Monitor (CGM) data from Nightscout, providing real-time readings, history, and analytics.71MIT