# Glucose MCP Server - Claude Code Guide
**Production MCP server for continuous glucose monitoring (CGM) data and blood sugar analysis**
---
## What This Service Does
Glucose MCP Server provides continuous glucose monitoring data through the Model Context Protocol. It integrates with the health-data-storage backend to query CGM readings, analyze blood sugar patterns, detect trends (spikes, drops), calculate averages, and provide insights for diabetes management and metabolic health. Features OAuth 2.1 authentication for Claude integration.
---
## Architecture
**Tech Stack:**
- TypeScript/Node.js with MCP SDK
- Express for HTTP/OAuth endpoints
- SSE (Server-Sent Events) transport for MCP
- PostgreSQL (via health-data-storage API)
- Deploys to: Google Cloud Run
**Dependencies:**
- `@modelcontextprotocol/sdk` - MCP protocol implementation
- `express` - HTTP server for OAuth flows
- `axios` - Health-data-storage API client
- `uuid` - Session ID generation
- `cors` - CORS support for Claude/ChatGPT
- `dotenv` - Environment variable management
---
## Common Commands
### Development
```bash
npm install # Install dependencies
npm run build # Build TypeScript (creates build/ directory)
npm run watch # Watch mode (auto-rebuild on changes)
npm start # Start production server (MCP via stdio)
npm run start:http # Start HTTP server with OAuth support
```
### Deployment
```bash
# Deploy with OAuth support (REQUIRED for Claude)
GOOGLE_CLOUD_PROJECT=personal-assistant-e4351 \
OAUTH_CLIENT_SECRET='<secret-from-database>' \
./deploy-oauth.sh
# Note: Always run 'npm run build' before deploying
```
**Required Environment Variables:**
- `GOOGLE_CLOUD_PROJECT` - GCP project ID (personal-assistant-e4351)
- `OAUTH_CLIENT_ID` - OAuth client identifier (glucose-mcp-production)
- `OAUTH_CLIENT_SECRET` - OAuth client secret from database
- `BACKEND_URL` - Health data storage API URL
- `DATABASE_URL` - PostgreSQL connection string (optional, uses BACKEND_URL)
- `NODE_ENV` - Environment (production/development)
---
## Approval Gates
The following areas require explicit user approval before changes:
### Authentication & Security
- OAuth flow implementation (`src/http-server-oauth.ts`)
- RFC 9728 metadata endpoints (`.well-known/*`)
- API authentication with backend
- Secret Manager integration
### Database & Storage
- Glucose reading schema changes
- Data retention policies for CGM data
- Query patterns for time-series analysis
### Infrastructure
- Deployment scripts (`deploy.sh`, `deploy-oauth.sh`)
- Cloud Build configuration
- Dockerfile changes
- Environment variable configuration
### API Contracts
- MCP tool definitions (breaking changes to schemas)
- Integration with health-data-storage API
- Glucose data format and units (mg/dL vs mmol/L)
- Alert thresholds and patterns
### Health & Safety
- Hypoglycemia/hyperglycemia detection thresholds
- Medical accuracy of trend analysis
- Disclaimer language for health advice
- Emergency alert patterns
---
## Key Files
| File | Purpose |
|------|---------|
| `src/index.ts` | MCP server implementation with glucose monitoring tools |
| `src/http-server.ts` | HTTP server with OAuth support |
| `deploy-oauth.sh` | Cloud Run deployment with OAuth support |
| `deploy.sh` | Basic deployment script |
---
## MCP Tools
This server provides the following tools for Claude/ChatGPT:
### `glucose_get_readings`
Get CGM readings for a date range.
**Input:**
```json
{
"user_id": "...",
"start_date": "2025-11-22",
"end_date": "2025-11-22",
"interval_minutes": 5
}
```
**Returns:** Array of glucose readings with timestamps (mg/dL)
### `glucose_get_current`
Get most recent glucose reading.
**Input:**
```json
{
"user_id": "..."
}
```
**Returns:** Latest glucose value with timestamp and trend
### `glucose_analyze_trends`
Analyze glucose patterns over time.
**Input:**
```json
{
"user_id": "...",
"start_date": "2025-11-22",
"end_date": "2025-11-22",
"analysis_type": "daily_summary"
}
```
**Returns:**
- Average glucose level
- Standard deviation (variability)
- Time in range (70-180 mg/dL)
- Hypoglycemia episodes (<70 mg/dL)
- Hyperglycemia episodes (>180 mg/dL)
- Peak and trough times
### `glucose_detect_spikes`
Detect rapid glucose changes.
**Input:**
```json
{
"user_id": "...",
"start_date": "2025-11-22",
"end_date": "2025-11-22",
"threshold_rate": 2.0
}
```
**Returns:** Array of spike events with magnitude and timing
### `glucose_correlate_meals`
Correlate glucose responses with food intake.
**Input:**
```json
{
"user_id": "...",
"date": "2025-11-22"
}
```
**Returns:** Meal times with post-meal glucose curves, peak values
### `glucose_get_statistics`
Get comprehensive glucose statistics for a period.
**Input:**
```json
{
"user_id": "...",
"start_date": "2025-11-15",
"end_date": "2025-11-22"
}
```
**Returns:**
- Mean glucose
- Median glucose
- GMI (Glucose Management Indicator)
- Coefficient of variation
- Time in range percentages
---
## Glucose Metrics
**Standard CGM Metrics:**
- **Time in Range (TIR):** % of readings 70-180 mg/dL (target: >70%)
- **Time Below Range:** % of readings <70 mg/dL (target: <4%)
- **Time Above Range:** % of readings >180 mg/dL (target: <25%)
- **Mean Glucose:** Average over period
- **GMI:** Estimated A1C from CGM data
- **Coefficient of Variation:** Glucose variability (target: <36%)
**Alert Thresholds:**
- Hypoglycemia: <70 mg/dL (urgent: <54 mg/dL)
- Hyperglycemia: >180 mg/dL (urgent: >250 mg/dL)
- Rapid drop: >2 mg/dL per minute
- Rapid rise: >2 mg/dL per minute
---
## Testing
### Local Testing
```bash
# Build and test
npm run build
npm start
# Watch mode for development
npm run watch
# Start HTTP server for OAuth testing
npm run start:http
```
### Verify Deployment
```bash
# Test OAuth metadata endpoints
curl https://glucose-mcp-production-835031330028.us-central1.run.app/.well-known/oauth-protected-resource/sse
# Test health endpoint
curl https://glucose-mcp-production-835031330028.us-central1.run.app/health
# Test unauthorized access (should return 401)
curl -i https://glucose-mcp-production-835031330028.us-central1.run.app/sse
# View logs
gcloud logging read "resource.type=cloud_run_revision AND resource.labels.service_name=glucose-mcp-production" \
--limit 50 --format json
```
### Integration Testing
```bash
# Test glucose query via backend API
curl -X GET "https://health-data-storage-835031330028.us-central1.run.app/api/glucose?date=2025-11-22" \
-H "Authorization: Bearer <api-key>"
# Test glucose logging
curl -X POST "https://health-data-storage-835031330028.us-central1.run.app/api/glucose" \
-H "Authorization: Bearer <api-key>" \
-H "Content-Type: application/json" \
-d '{
"timestamp": "2025-11-22T12:00:00Z",
"glucose_mg_dl": 95
}'
```
---
## Data Sources
**Glucose data can come from:**
1. Manual entry via iOS app or API
2. CGM device integration (Dexcom, FreeStyle Libre, etc.)
3. Blood glucose meter uploads
4. Third-party health apps (Apple Health, MyFitnessPal)
**Current Integration:**
- Manual entry via health-data-storage API
- [Future] Dexcom API integration
- [Future] Apple Health import
---
## Troubleshooting
### Common Issues
**Build Errors:**
```bash
# Clean rebuild
rm -rf build/ node_modules/
npm install
npm run build
# Verify build output
ls -la build/
```
**OAuth Errors:**
```bash
# Check metadata endpoints exist
curl https://glucose-mcp-production-*.run.app/.well-known/oauth-protected-resource/sse
# Verify client in database
DATABASE_URL='<url>' npx tsx -e "import pg from 'pg'; const pool = new pg.Pool({connectionString: process.env.DATABASE_URL}); pool.query('SELECT client_id FROM oauth_clients WHERE client_id=\'glucose-mcp-production\'').then(r => console.log(r.rows))"
```
**Backend Connection Errors:**
```bash
# Verify BACKEND_URL is set correctly
gcloud run services describe glucose-mcp-production --region us-central1 --format="value(spec.template.spec.containers[0].env)"
# Test backend health
curl https://health-data-storage-835031330028.us-central1.run.app/health
```
**Missing Data:**
```bash
# Check if glucose readings exist
DATABASE_URL='<url>' npx tsx -e "import pg from 'pg'; const pool = new pg.Pool({connectionString: process.env.DATABASE_URL}); pool.query('SELECT COUNT(*) FROM glucose_readings').then(r => console.log(r.rows))"
```
### Debug Commands
```bash
# Check service status
gcloud run services describe glucose-mcp-production --region us-central1
# View real-time logs
gcloud logging tail "resource.type=cloud_run_revision AND resource.labels.service_name=glucose-mcp-production"
# Test local connection to backend
BACKEND_URL='http://localhost:8080' npm run start:http
```
---
## Medical Disclaimer
**IMPORTANT:** This server provides informational glucose data analysis only. It is not a medical device and should not be used for diabetes treatment decisions without consulting a healthcare provider. Always verify CGM readings with a blood glucose meter when making treatment decisions.
---
## Notes
- **Always build before deploying** - Run `npm run build` to compile TypeScript
- **OAuth required** - Use `deploy-oauth.sh` for Claude compatibility
- **Units** - All glucose values in mg/dL (convert from mmol/L if needed: mmol/L × 18 = mg/dL)
- **Timezone awareness** - All timestamps respect user's timezone setting
- **Data frequency** - CGM typically provides readings every 5-15 minutes
- **Medical accuracy** - Consult healthcare provider for interpretation
---
**Production URL:** `https://glucose-mcp-production-835031330028.us-central1.run.app/sse`
**Last Updated:** 2025-11-22
**Service Owner:** LifeOS Platform Team
**Related Docs:** See `/docs/CLAUDE_MCP_INTEGRATION.md`, `/MCP_BEST_PRACTICES.md`