# Environment Adapters
Debug MCP supports multiple runtime environments through a flexible adapter system. Each adapter generates environment-appropriate code for sending debug logs to the MCP server.
## How Environment Detection Works
The detector uses a multi-pass approach with priority levels:
1. **File Extension** (Highest confidence: 95%)
- `.php` → PHP
- `.py` → Python
- `.wxml/.wxss` → WeChat Mini Program
2. **Framework Markers** (High confidence: 85-90%)
- `require('electron')` → Electron
- `from 'react-native'` → React Native
- `wx./swan./my.` → Mini Programs
3. **Global Objects** (Medium confidence: 80-85%)
- `window/document` → Browser
- `process/__dirname` → Node.js
4. **Path Analysis** (Lower confidence: 60-70%)
- `/server/` or `/api/` → Server-side
- File names: `server.js`, `controller.py`, etc.
## Available Adapters
### 1. Browser Adapter
**Detection:**
- Presence of `window`, `document`, or `navigator` objects
- No `process` or `require` (to avoid false positives)
**Generated Code:**
```javascript
// debug-start
fetch('http://localhost:3000/api/log', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
timestamp: new Date().toISOString(),
level: 'info',
message: 'Your debug message',
data: { var1, var2 }
})
}).catch(err => console.error('[Debug Log Failed]', err));
// debug-end
```
**Best For:** Web applications, Single Page Apps, vanilla JavaScript, React, Vue, Angular
---
### 2. Node.js Adapter (v18+)
**Detection:**
- Presence of `process`, `__dirname`, or `__filename`
- No explicit `http`/`https` module imports
**Generated Code:**
```javascript
// debug-start
fetch('http://localhost:3000/api/log', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
timestamp: new Date().toISOString(),
level: 'info',
message: 'Your debug message',
data: { var1, var2 }
})
}).catch(err => console.error('[Debug Log Failed]', err));
// debug-end
```
**Best For:** Modern Node.js servers (v18+), Express, Koa, Fastify
---
### 3. Node.js Legacy Adapter (v14-17)
**Detection:**
- Presence of `require('http')` or `require('https')`
- Older Node.js patterns
**Generated Code:**
```javascript
// debug-start
const http = require('http');
const logData = JSON.stringify({
timestamp: new Date().toISOString(),
level: 'info',
message: 'Your debug message',
data: { var1, var2 }
});
const req = http.request('http://localhost:3000/api/log', {
method: 'POST',
headers: { 'Content-Type': 'application/json' }
}, (res) => {
if (res.statusCode !== 200) console.error('[Debug Log Failed]', res.statusCode);
});
req.on('error', (err) => console.error('[Debug Log Failed]', err));
req.write(logData);
req.end();
// debug-end
```
**Best For:** Older Node.js versions, environments without native fetch
---
### 4. React Native Adapter
**Detection:**
- Imports from `'react-native'`
- `ReactNative` global object
**Generated Code:**
```javascript
// debug-start
fetch('http://localhost:3000/api/log', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
timestamp: new Date().toISOString(),
level: 'info',
message: 'Your debug message',
data: { var1, var2 }
})
}).catch(err => console.error('[Debug Log Failed]', err));
// debug-end
```
**Best For:** React Native mobile apps (iOS/Android)
**Note:** For production, replace localhost with your actual MCP server address
---
### 5. Electron Main Process Adapter
**Detection:**
- `require('electron')` without `ipcRenderer`
- Main process APIs like `app`, `BrowserWindow`
**Generated Code:**
```javascript
// debug-start
const fs = require('fs');
const path = require('path');
const logEntry = {
timestamp: new Date().toISOString(),
level: 'info',
message: 'Your debug message',
data: { var1, var2 }
};
const logPath = path.join(app.getPath('userData'), '.debug', 'debug.log');
try {
fs.mkdirSync(path.dirname(logPath), { recursive: true });
fs.appendFileSync(logPath, JSON.stringify(logEntry) + '\n');
} catch (err) {
console.error('[Debug Log Failed]', err);
}
// debug-end
```
**Best For:** Electron main process code
**Note:** Writes directly to file instead of HTTP (main process has no network)
---
### 6. Electron Renderer Process Adapter
**Detection:**
- `require('electron')` with `ipcRenderer`
- Renderer process APIs
**Generated Code:**
```javascript
// debug-start
const { ipcRenderer } = require('electron');
ipcRenderer.send('debug-log', {
timestamp: new Date().toISOString(),
level: 'info',
message: 'Your debug message',
data: { var1, var2 }
});
// debug-end
```
**Best For:** Electron renderer process code
**Note:** Requires main process IPC handler to receive and forward logs
---
### 7. WeChat Mini Program Adapter
**Detection:**
- `wx.` global object (WeChat)
- `swan.` (Baidu)
- `my.` (Alipay)
- `.wxml` or `.wxss` files
**Generated Code:**
```javascript
// debug-start
wx.request({
url: 'http://localhost:3000/api/log',
method: 'POST',
data: {
timestamp: new Date().toISOString(),
level: 'info',
message: 'Your debug message',
data: { var1, var2 }
},
fail: (err) => console.error('[Debug Log Failed]', err)
});
// debug-end
```
**Best For:** WeChat Mini Programs, Alipay Mini Programs, Baidu Smart Programs
**Note:** Requires server domain whitelist in production
---
### 8. PHP Adapter
**Detection:**
- `.php` file extension
- `<?php` tags
**Generated Code:**
```php
// debug-start
$logData = json_encode([
'timestamp' => date('c'),
'level' => 'info',
'message' => 'Your debug message',
'data' => ['var1' => $var1, 'var2' => $var2]
]);
$ch = curl_init('http://localhost:3000/api/log');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $logData);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 100);
curl_exec($ch);
curl_close($ch);
// debug-end
```
**Best For:** PHP server-side code (Laravel, WordPress, custom PHP)
**Note:** Short timeout (100ms) prevents blocking main logic
---
### 9. Python Adapter
**Detection:**
- `.py` file extension
- Python syntax
**Generated Code:**
```python
# debug-start
import requests
import json
try:
requests.post(
'http://localhost:3000/api/log',
json={
'timestamp': datetime.now().isoformat(),
'level': 'info',
'message': 'Your debug message',
'data': {'var1': var1, 'var2': var2}
},
timeout=0.1
)
except:
pass
# debug-end
```
**Best For:** Django, Flask, FastAPI, script files
**Note:** Short timeout prevents blocking; requires `requests` library
---
## Manual Environment Specification
If auto-detection fails or you want to override it:
```json
{
"filePath": "src/app.js",
"insertLine": 25,
"logMessage": "Debug message",
"variables": ["data"],
"environment": "browser" // Manually specify
}
```
## Adding New Adapters
To add support for a new environment:
1. Create a new adapter class in `src/adapters/index.ts`:
```typescript
export class MyAdapter implements EnvironmentAdapter {
name = 'my-environment';
generateDebugCode(options: AdapterOptions): AdapterResult {
const { logMessage, variables, level } = options;
return {
code: `// debug-start\n// Your debug code here\n// debug-end`,
language: 'javascript',
description: 'My custom environment'
};
}
}
```
2. Add detection logic in `src/adapters/detector.ts`:
```typescript
private detectByFramework(content: string): DetectionResult {
// Your detection logic
if (content.includes('my-framework')) {
return {
environment: 'my-environment',
confidence: 0.9,
suggestedAdapter: 'my-environment',
reasoning: 'Detected My Framework'
};
}
// ...
}
```
3. Export the adapter in `src/adapters/index.ts`:
```typescript
export const adapters: EnvironmentAdapter[] = [
// ... existing adapters
new MyAdapter()
];
```
## Adapter Selection Flow
```
1. Check if environment explicitly specified → Use specified adapter
↓ No
2. Detect by file extension → High confidence match?
↓ Yes → Use that adapter
↓ No
3. Detect by framework markers → High confidence match?
↓ Yes → Use that adapter
↓ No
4. Detect by global objects → Medium confidence match?
↓ Yes → Use that adapter
↓ No
5. Default to browser for web files, node for server files
↓ No match
6. Final fallback: browser adapter
```
## Testing Adapters
Test which adapter will be used for a file:
```bash
# Using MCP tool
detect_environment({
"filePath": "path/to/your/file.js"
})
```
## Adapter Confidence Levels
- **0.9-1.0**: Very high confidence (file extension, explicit framework)
- **0.7-0.9**: High confidence (framework markers, global objects)
- **0.5-0.7**: Medium confidence (path analysis, patterns)
- **0.0-0.5**: Low confidence (heuristics, defaults)
Higher confidence = less likely to be wrong