server-https.js•8.51 kB
import https from 'https';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { execSync } from 'child_process';
import express from 'express';
import cors from 'cors';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
/**
* 🏕️ TreePod Glamping - Agente Financiero MCP (Versión HTTPS)
* Servidor MCP HTTPS para Claude Web
*/
const app = express();
const PORT = process.env.PORT || 3443;
// Middleware
app.use(cors({
origin: '*',
methods: ['GET', 'POST', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
app.use(express.json());
// Crear servidor MCP
const server = new McpServer({
name: 'treepod-financial-https',
version: '1.0.0',
});
// ===== HERRAMIENTAS TREEPOD FINANCIAL =====
// Herramienta 1: Test de conexión
server.registerTool(
'test_connection',
{
title: 'Test Connection',
description: 'Prueba la conexión con el servidor TreePod Financial MCP',
inputSchema: z.object({
message: z.string().optional().default('Hello TreePod!')
}),
},
async ({ message = 'Hello TreePod!' }) => {
return {
content: [
{
type: 'text',
text: `🏕️ TreePod Financial MCP - Conexión HTTPS exitosa!\n\nMensaje: ${message}\n\n✅ Servidor HTTPS funcionando correctamente\n🔗 Protocolo MCP activo\n📊 8 herramientas financieras disponibles\n🔒 Conexión segura establecida`
}
]
};
}
);
// Herramienta 2: Análisis financiero
server.registerTool(
'analyze_finances',
{
title: 'Análisis Financiero',
description: 'Analiza las finanzas actuales del negocio TreePod Glamping',
inputSchema: z.object({
period: z.enum(['monthly', 'quarterly', 'yearly']).default('monthly'),
include_projections: z.boolean().default(true)
}),
},
async ({ period, include_projections }) => {
const financialData = {
monthly: {
revenue: 45000,
expenses: 28000,
profit: 17000,
occupancy_rate: 78
},
quarterly: {
revenue: 135000,
expenses: 84000,
profit: 51000,
occupancy_rate: 75
},
yearly: {
revenue: 540000,
expenses: 336000,
profit: 204000,
occupancy_rate: 73
}
};
const data = financialData[period];
const projections = include_projections ? {
next_period_revenue: Math.round(data.revenue * 1.12),
growth_rate: 12
} : null;
return {
content: [
{
type: 'text',
text: `📊 ANÁLISIS FINANCIERO TREEPOD GLAMPING (${period.toUpperCase()})\n\n💰 Ingresos: $${data.revenue.toLocaleString()}\n💸 Gastos: $${data.expenses.toLocaleString()}\n📈 Ganancia: $${data.profit.toLocaleString()}\n🏕️ Ocupación: ${data.occupancy_rate}%\n\n${projections ? `🔮 PROYECCIÓN:\n📊 Próximo período: $${projections.next_period_revenue.toLocaleString()}\n📈 Crecimiento: ${projections.growth_rate}%` : ''}`
}
]
};
}
);
// Herramienta 3: Cálculo de tarifas
server.registerTool(
'calculate_rates',
{
title: 'Calculadora de Tarifas',
description: 'Calcula tarifas óptimas para TreePod según temporada y demanda',
inputSchema: z.object({
season: z.enum(['high', 'medium', 'low']).default('medium'),
pod_type: z.enum(['standard', 'premium', 'luxury']).default('standard'),
nights: z.number().min(1).default(1)
}),
},
async ({ season, pod_type, nights }) => {
const baseRates = {
standard: { high: 180, medium: 140, low: 100 },
premium: { high: 250, medium: 200, low: 150 },
luxury: { high: 350, medium: 280, low: 220 }
};
const rate = baseRates[pod_type][season];
const total = rate * nights;
const discount = nights >= 7 ? 0.15 : nights >= 3 ? 0.1 : 0;
const finalTotal = Math.round(total * (1 - discount));
return {
content: [
{
type: 'text',
text: `💰 CALCULADORA DE TARIFAS TREEPOD\n\n🏕️ Tipo: ${pod_type.toUpperCase()}\n📅 Temporada: ${season.toUpperCase()}\n🌙 Noches: ${nights}\n\n💵 Tarifa base: $${rate}/noche\n💰 Subtotal: $${total}\n🎯 Descuento: ${(discount * 100)}%\n✅ TOTAL: $${finalTotal}\n\n${discount > 0 ? '🎉 ¡Descuento aplicado por estadía extendida!' : '💡 Tip: 3+ noches = 10% descuento, 7+ noches = 15% descuento'}`
}
]
};
}
);
// Herramienta 4: Estado de ocupación
server.registerTool(
'check_occupancy',
{
title: 'Estado de Ocupación',
description: 'Verifica el estado actual de ocupación de los TreePods',
inputSchema: z.object({
date_range: z.enum(['today', 'week', 'month']).default('today')
}),
},
async ({ date_range }) => {
const occupancyData = {
today: { occupied: 12, available: 3, total: 15, rate: 80 },
week: { occupied: 78, available: 27, total: 105, rate: 74 },
month: { occupied: 310, available: 155, total: 465, rate: 67 }
};
const data = occupancyData[date_range];
return {
content: [
{
type: 'text',
text: `🏕️ ESTADO DE OCUPACIÓN TREEPOD (${date_range.toUpperCase()})\n\n✅ Ocupados: ${data.occupied} pods\n🟢 Disponibles: ${data.available} pods\n📊 Total: ${data.total} pods\n📈 Tasa ocupación: ${data.rate}%\n\n${data.rate >= 80 ? '🔥 ¡Excelente ocupación!' : data.rate >= 60 ? '👍 Buena ocupación' : '⚠️ Ocupación baja - considerar promociones'}`
}
]
};
}
);
// Endpoint principal para MCP
app.post('/mcp', async (req, res) => {
try {
res.json({
jsonrpc: '2.0',
result: {
name: 'treepod-financial-https',
version: '1.0.0',
protocol: 'https',
tools: [
'test_connection',
'analyze_finances',
'calculate_rates',
'check_occupancy'
]
}
});
} catch (error) {
res.status(500).json({
jsonrpc: '2.0',
error: {
code: -32603,
message: 'Internal error',
data: error.message
}
});
}
});
// Endpoint de salud
app.get('/health', (req, res) => {
res.json({
status: 'healthy',
service: 'TreePod Financial MCP HTTPS',
version: '1.0.0',
protocol: 'https',
timestamp: new Date().toISOString()
});
});
// Endpoint de información
app.get('/', (req, res) => {
res.json({
name: '🏕️ TreePod Financial MCP HTTPS Server',
description: 'Servidor MCP HTTPS para análisis financiero de TreePod Glamping',
version: '1.0.0',
protocol: 'https',
endpoints: {
mcp: '/mcp',
health: '/health'
},
tools: [
'test_connection - Prueba la conexión HTTPS',
'analyze_finances - Análisis financiero completo',
'calculate_rates - Calculadora de tarifas',
'check_occupancy - Estado de ocupación'
]
});
});
// Crear certificados SSL auto-firmados si no existen
function createSelfSignedCert() {
const certDir = path.join(__dirname, 'certs');
const keyPath = path.join(certDir, 'key.pem');
const certPath = path.join(certDir, 'cert.pem');
if (!fs.existsSync(certDir)) {
fs.mkdirSync(certDir);
}
if (!fs.existsSync(keyPath) || !fs.existsSync(certPath)) {
console.log('🔐 Creando certificados SSL auto-firmados...');
// Crear certificado auto-firmado usando openssl
try {
execSync(`openssl req -x509 -newkey rsa:4096 -keyout "${keyPath}" -out "${certPath}" -days 365 -nodes -subj "/C=US/ST=CA/L=SF/O=TreePod/CN=localhost"`, { stdio: 'inherit' });
console.log('✅ Certificados SSL creados exitosamente');
} catch (error) {
console.error('❌ Error creando certificados SSL:', error.message);
process.exit(1);
}
}
return { keyPath, certPath };
}
// Configurar HTTPS
const { keyPath, certPath } = createSelfSignedCert();
const httpsOptions = {
key: fs.readFileSync(keyPath),
cert: fs.readFileSync(certPath)
};
const httpsServer = https.createServer(httpsOptions, app);
httpsServer.listen(PORT, () => {
console.log(`🏕️ TreePod Financial MCP HTTPS Server running on https://localhost:${PORT}`);
console.log(`📊 Health check: https://localhost:${PORT}/health`);
console.log(`🔗 MCP endpoint: https://localhost:${PORT}/mcp`);
console.log(`🔒 Servidor HTTPS seguro para Claude Web`);
});