initial commit

Signed-off-by: ale <ale@manalejandro.com>
Este commit está contenido en:
ale
2025-10-11 03:22:03 +02:00
commit 2f8e4dec54
Se han modificado 35 ficheros con 11905 adiciones y 0 borrados

134
examples/README.md Archivo normal
Ver fichero

@@ -0,0 +1,134 @@
# Examples
This directory contains example code demonstrating how to use the MCP ProcFS Server.
## Files
### `basic-usage.ts`
TypeScript example showing how to use the ProcFS reader and writer libraries directly.
**Run:**
```bash
cd /path/to/mcp-proc
npm install
npm run build
npx tsx examples/basic-usage.ts
```
### `python-client.py`
Python example demonstrating how to interact with the HTTP API.
**Requirements:**
```bash
pip install requests
```
**Run:**
```bash
# Start the server first
npm run start:sse
# In another terminal
python examples/python-client.py
```
### `monitoring-dashboard.js`
Real-time system monitoring dashboard using Server-Sent Events (SSE).
**Requirements:**
```bash
npm install eventsource node-fetch
```
**Run:**
```bash
# Start the server first
npm run start:sse
# In another terminal
node examples/monitoring-dashboard.js
```
### `mcp-config.json`
Example MCP client configuration file. Use this with MCP-compatible clients like Claude Desktop.
**Usage:**
1. Copy to your MCP client config location
2. Update the path to point to your installation
3. Restart your MCP client
For Claude Desktop on macOS:
```bash
cp examples/mcp-config.json ~/Library/Application\ Support/Claude/claude_desktop_config.json
```
## More Examples
### Using cURL
```bash
# Start the HTTP server
npm run start:sse
# Get CPU information
curl http://localhost:3000/api/cpu
# Get memory info
curl http://localhost:3000/api/memory
# Read a sysctl parameter
curl http://localhost:3000/api/sysctl/kernel.hostname
# Write a sysctl parameter (requires permissions)
curl -X POST http://localhost:3000/api/sysctl \
-H "Content-Type: application/json" \
-d '{"key": "vm.swappiness", "value": 10}'
```
### Using JavaScript Fetch API
```javascript
// Get CPU information
const response = await fetch('http://localhost:3000/api/cpu');
const data = await response.json();
console.log(data);
// Write sysctl parameter
await fetch('http://localhost:3000/api/sysctl', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
key: 'net.ipv4.ip_forward',
value: 1
})
});
```
### Using the MCP Protocol
```bash
# Start the MCP server on stdio
npm start
# Send a JSON-RPC request (via stdin)
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | npm start
```
## Interactive API Documentation
The HTTP server includes interactive Swagger documentation:
1. Start the server: `npm run start:sse`
2. Open browser: http://localhost:3000/api-docs
3. Try out the endpoints directly from the browser
## Need Help?
- Check the [API Documentation](../docs/API.md)
- See [Quick Start Guide](../docs/QUICKSTART.md)
- Review the [main README](../README.md)

89
examples/basic-usage.ts Archivo normal
Ver fichero

@@ -0,0 +1,89 @@
/**
* Example: Using MCP ProcFS Server as a library
*/
import { ProcFSReader, ProcFSWriter } from '../src/index';
async function main() {
const reader = new ProcFSReader();
const writer = new ProcFSWriter();
console.log('=== System Information ===\n');
// Get CPU information
const cpuInfo = await reader.getCPUInfo();
console.log('CPU Information:');
console.log(` Model: ${cpuInfo.model}`);
console.log(` Cores: ${cpuInfo.cores}`);
console.log(` Processors: ${cpuInfo.processors}`);
console.log(` MHz: ${cpuInfo.mhz}`);
console.log();
// Get memory information
const memInfo = await reader.getMemInfo();
console.log('Memory Information:');
console.log(` Total: ${(memInfo.total / 1024).toFixed(2)} GB`);
console.log(` Free: ${(memInfo.free / 1024).toFixed(2)} GB`);
console.log(` Available: ${(memInfo.available / 1024).toFixed(2)} GB`);
console.log(` Cached: ${(memInfo.cached / 1024).toFixed(2)} GB`);
console.log();
// Get load average
const loadAvg = await reader.getLoadAvg();
console.log('Load Average:');
console.log(` 1 min: ${loadAvg.one}`);
console.log(` 5 min: ${loadAvg.five}`);
console.log(` 15 min: ${loadAvg.fifteen}`);
console.log(` Running/Total: ${loadAvg.runningProcesses}/${loadAvg.totalProcesses}`);
console.log();
// Get network statistics
const netStats = await reader.getNetDevStats();
console.log('Network Interfaces:');
for (const iface of netStats) {
console.log(` ${iface.interface}:`);
console.log(` RX: ${(iface.rxBytes / 1024 / 1024).toFixed(2)} MB`);
console.log(` TX: ${(iface.txBytes / 1024 / 1024).toFixed(2)} MB`);
}
console.log();
// Get disk statistics
const diskStats = await reader.getDiskStats();
console.log('Disk Devices:');
for (const disk of diskStats.slice(0, 5)) {
if (disk.readsCompleted > 0 || disk.writesCompleted > 0) {
console.log(` ${disk.device}:`);
console.log(` Reads: ${disk.readsCompleted}`);
console.log(` Writes: ${disk.writesCompleted}`);
}
}
console.log();
// List some processes
const pids = await reader.listPIDs();
console.log(`Total Processes: ${pids.length}`);
console.log('\nFirst 5 processes:');
for (const pid of pids.slice(0, 5)) {
try {
const procInfo = await reader.getProcessInfo(pid);
console.log(` PID ${procInfo.pid}: ${procInfo.name} (${procInfo.state})`);
} catch (error) {
// Process may have terminated
}
}
console.log();
// Read a sysctl parameter (example)
try {
const param = await writer.readSysctl('kernel.hostname');
console.log('Sysctl Parameter:');
console.log(` kernel.hostname = ${param.value}`);
console.log();
} catch (error) {
console.log('Could not read sysctl parameter');
}
console.log('=== Example Complete ===');
}
main().catch(console.error);

9
examples/mcp-config.json Archivo normal
Ver fichero

@@ -0,0 +1,9 @@
{
"mcpServers": {
"procfs": {
"command": "node",
"args": ["/path/to/mcp-proc/dist/cli.js"],
"description": "Linux procfs system information and management"
}
}
}

Ver fichero

@@ -0,0 +1,103 @@
#!/usr/bin/env node
/**
* Example: Monitoring system metrics in real-time using SSE
*/
const EventSource = require('eventsource');
const SSE_URL = 'http://localhost:3000/mcp/sse';
const API_URL = 'http://localhost:3000';
// Connect to SSE endpoint
const eventSource = new EventSource(SSE_URL);
eventSource.onopen = () => {
console.log('Connected to MCP ProcFS Server\n');
startMonitoring();
};
eventSource.addEventListener('connected', (event) => {
const data = JSON.parse(event.data);
console.log('Connection confirmed:', data.clientId);
});
eventSource.onerror = (error) => {
console.error('SSE Error:', error);
};
async function fetchMetric(endpoint) {
try {
const response = await fetch(`${API_URL}${endpoint}`);
const data = await response.json();
return data.data;
} catch (error) {
console.error(`Error fetching ${endpoint}:`, error.message);
return null;
}
}
async function displayMetrics() {
console.clear();
console.log('=== System Monitoring Dashboard ===\n');
// CPU Info
const cpu = await fetchMetric('/api/cpu');
if (cpu) {
console.log('CPU:');
console.log(` Model: ${cpu.model}`);
console.log(` Cores: ${cpu.cores}`);
console.log(` Speed: ${cpu.mhz.toFixed(2)} MHz`);
}
console.log();
// Memory Info
const mem = await fetchMetric('/api/memory');
if (mem) {
const usedPercent = ((mem.total - mem.available) / mem.total * 100).toFixed(1);
console.log('Memory:');
console.log(` Total: ${(mem.total / 1024 / 1024).toFixed(2)} GB`);
console.log(` Available: ${(mem.available / 1024 / 1024).toFixed(2)} GB`);
console.log(` Used: ${usedPercent}%`);
}
console.log();
// Load Average
const load = await fetchMetric('/api/load');
if (load) {
console.log('Load Average:');
console.log(` 1min: ${load.one.toFixed(2)}`);
console.log(` 5min: ${load.five.toFixed(2)}`);
console.log(` 15min: ${load.fifteen.toFixed(2)}`);
console.log(` Processes: ${load.runningProcesses}/${load.totalProcesses}`);
}
console.log();
// Network Stats
const net = await fetchMetric('/api/network');
if (net && net.length > 0) {
console.log('Network Interfaces:');
net.slice(0, 3).forEach(iface => {
console.log(` ${iface.interface}:`);
console.log(` RX: ${(iface.rxBytes / 1024 / 1024).toFixed(2)} MB | TX: ${(iface.txBytes / 1024 / 1024).toFixed(2)} MB`);
});
}
console.log();
console.log('Press Ctrl+C to exit');
console.log(`Last update: ${new Date().toLocaleTimeString()}`);
}
function startMonitoring() {
// Initial display
displayMetrics();
// Update every 2 seconds
setInterval(displayMetrics, 2000);
}
// Handle cleanup
process.on('SIGINT', () => {
console.log('\nClosing connection...');
eventSource.close();
process.exit(0);
});

97
examples/python-client.py Archivo normal
Ver fichero

@@ -0,0 +1,97 @@
#!/usr/bin/env python3
"""
Example: Using MCP ProcFS Server HTTP API from Python
"""
import requests
import json
from typing import Dict, Any
BASE_URL = "http://localhost:3000"
def pretty_print(data: Any) -> None:
"""Pretty print JSON data"""
print(json.dumps(data, indent=2))
def get_cpu_info() -> Dict:
"""Get CPU information"""
response = requests.get(f"{BASE_URL}/api/cpu")
return response.json()
def get_memory_info() -> Dict:
"""Get memory information"""
response = requests.get(f"{BASE_URL}/api/memory")
return response.json()
def get_load_average() -> Dict:
"""Get system load average"""
response = requests.get(f"{BASE_URL}/api/load")
return response.json()
def get_network_stats(interface: str = None) -> Dict:
"""Get network statistics"""
params = {"interface": interface} if interface else {}
response = requests.get(f"{BASE_URL}/api/network", params=params)
return response.json()
def get_process_info(pid: int) -> Dict:
"""Get process information"""
response = requests.get(f"{BASE_URL}/api/processes/{pid}")
return response.json()
def read_sysctl(key: str) -> Dict:
"""Read sysctl parameter"""
response = requests.get(f"{BASE_URL}/api/sysctl/{key}")
return response.json()
def write_sysctl(key: str, value) -> Dict:
"""Write sysctl parameter"""
response = requests.post(
f"{BASE_URL}/api/sysctl",
json={"key": key, "value": value}
)
return response.json()
def main():
print("=== MCP ProcFS Server Python Client Example ===\n")
# Get CPU info
print("CPU Information:")
cpu_info = get_cpu_info()
pretty_print(cpu_info)
print()
# Get memory info
print("Memory Information:")
mem_info = get_memory_info()
pretty_print(mem_info)
print()
# Get load average
print("Load Average:")
load_avg = get_load_average()
pretty_print(load_avg)
print()
# Get network stats for eth0
print("Network Statistics:")
net_stats = get_network_stats()
pretty_print(net_stats)
print()
# Get process info for PID 1
print("Process Info (PID 1):")
proc_info = get_process_info(1)
pretty_print(proc_info)
print()
# Read sysctl parameter
print("Sysctl Parameter (kernel.hostname):")
sysctl_info = read_sysctl("kernel.hostname")
pretty_print(sysctl_info)
print()
print("=== Example Complete ===")
if __name__ == "__main__":
main()