Integration Examples

Practical code examples for common MCPulse integration scenarios.

Express.js MCP Server

Monitor an MCP server built with Express.js. Perfect for HTTP-based MCP implementations.

const express = require('express');
const MCPulseMonitor = require('mcpulse-monitor');

const app = express();
app.use(express.json());

// Initialize MCPulse Monitor
const monitor = new MCPulseMonitor({
  apiKey: process.env.MCPULSE_API_KEY,
  serverId: 'weather-mcp-prod',
  reportingInterval: 60000,  // Send metrics every 60 seconds
  silent: false  // Enable logging for debugging
});

// Your MCP server routes
const mcpServer = {
  async callTool(toolName, input) {
    if (toolName === 'getWeather') {
      // Simulate weather API call
      const weather = await fetch(`https://api.weather.com/...`);
      return await weather.json();
    }
    throw new Error(`Unknown tool: ${toolName}`);
  }
};

// Wrap the MCP server for monitoring
monitor.wrap(mcpServer);

// Start monitoring
monitor.start();

// MCP endpoint
app.post('/mcp/call', async (req, res) => {
  try {
    const { tool, input } = req.body;
    const result = await mcpServer.callTool(tool, input);
    res.json({ success: true, result });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

// Health check
app.get('/health', (req, res) => {
  res.json({ status: 'ok', metrics: monitor.getMetrics() });
});

// Graceful shutdown
process.on('SIGTERM', () => {
  console.log('Shutting down...');
  monitor.stop();
  server.close(() => {
    console.log('Server closed');
    process.exit(0);
  });
});

const server = app.listen(3000, () => {
  console.log('MCP server running on port 3000');
  console.log('MCPulse monitoring active');
});

💡 Pro Tip: Add a /health endpoint that returns current metrics for local debugging.

Custom MCP Server Implementation

Monitor a custom MCP server that implements the MCP protocol directly.

const MCPulseMonitor = require('mcpulse-monitor');

// Your custom MCP server
class WeatherMCPServer {
  constructor() {
    this.tools = {
      getCurrentWeather: this.getCurrentWeather.bind(this),
      getForecast: this.getForecast.bind(this),
      getAlerts: this.getAlerts.bind(this)
    };
  }

  async getCurrentWeather(location) {
    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 100));
    return {
      location,
      temperature: 72,
      conditions: 'Sunny',
      humidity: 45
    };
  }

  async getForecast(location, days = 7) {
    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 200));
    return {
      location,
      forecast: Array(days).fill(0).map((_, i) => ({
        day: i + 1,
        temp: 70 + Math.floor(Math.random() * 10),
        conditions: 'Partly Cloudy'
      }))
    };
  }

  async getAlerts(location) {
    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 50));
    return { location, alerts: [] };
  }

  async callTool(toolName, input) {
    if (!this.tools[toolName]) {
      throw new Error(`Unknown tool: ${toolName}`);
    }
    return await this.tools[toolName](input);
  }

  listTools() {
    return Object.keys(this.tools).map(name => ({
      name,
      description: `Tool: ${name}`
    }));
  }
}

// Initialize server
const server = new WeatherMCPServer();

// Initialize MCPulse Monitor
const monitor = new MCPulseMonitor({
  apiKey: process.env.MCPULSE_API_KEY,
  serverId: 'weather-mcp-prod',
  reportingInterval: 60000,
  heartbeatInterval: 60000,
  maxBufferedMetrics: 1000
});

// Wrap the server
monitor.wrap(server);

// Start monitoring
monitor.start();

console.log('Weather MCP Server started with MCPulse monitoring');

// Example usage
(async () => {
  // These calls will be automatically tracked
  const weather = await server.callTool('getCurrentWeather', 'San Francisco');
  console.log('Current weather:', weather);

  const forecast = await server.callTool('getForecast', 'San Francisco');
  console.log('7-day forecast:', forecast);

  // Get current metrics
  const metrics = monitor.getMetrics();
  console.log('Metrics:', metrics);
})();

Badge Embedding

Showcase your server's reliability with embeddable badges in your README or documentation.

Available Badge Types

Reliability Score

Reliability Badge

Shows your overall reliability score (0-100) with grade (A+, A, B, C, D, F).

![MCPulse Reliability](https://stacks.polsia.app/api/badge/YOUR-SERVER-ID?type=reliability)

Uptime

Uptime Badge

Shows 24-hour uptime percentage.

![MCPulse Uptime](https://stacks.polsia.app/api/badge/YOUR-SERVER-ID?type=uptime)

Response Time

Response Time Badge

Shows average response time in milliseconds.

![MCPulse Response Time](https://stacks.polsia.app/api/badge/YOUR-SERVER-ID?type=response_time)

Combined (Recommended)

Combined Badge

Shows reliability score + uptime + response time in one badge.

![MCPulse](https://stacks.polsia.app/api/badge/YOUR-SERVER-ID?type=combined)

Complete README Example

# Weather MCP Server

![MCPulse](https://stacks.polsia.app/api/badge/weather-mcp-prod?type=combined)
[![npm version](https://badge.fury.io/js/weather-mcp.svg)](https://www.npmjs.com/package/weather-mcp)

A reliable MCP server for weather data. Monitored by [MCPulse](https://stacks.polsia.app).

## Features

- ⚡ Fast response times (<200ms average)
- 🔒 99.9% uptime guarantee
- 📊 Real-time reliability monitoring
- 🌍 Global weather coverage

## Installation

\`\`\`bash
npm install weather-mcp
\`\`\`

## Usage

\`\`\`javascript
const WeatherMCP = require('weather-mcp');
const server = new WeatherMCP({ apiKey: 'your-key' });
\`\`\`

## Reliability

This server is monitored by MCPulse for uptime, response time, and error rates.

View live metrics: [MCPulse Dashboard](https://stacks.polsia.app)

## License

MIT

Badge Colors

Badges automatically adjust color based on performance:

● Green: A+/A (95-100)
● Blue: B (80-94)
● Yellow: C (60-79)
● Orange: D (40-59)
● Red: F (<40)
● Gray: No data yet

Graceful Shutdown

Properly stop monitoring during server shutdown to avoid data loss.

const express = require('express');
const MCPulseMonitor = require('mcpulse-monitor');

const app = express();
const monitor = new MCPulseMonitor({
  apiKey: process.env.MCPULSE_API_KEY
});

// ... your server setup ...

monitor.wrap(yourMCPServer);
monitor.start();

const server = app.listen(3000);

// Handle SIGTERM (Kubernetes, Docker, etc.)
process.on('SIGTERM', gracefulShutdown);

// Handle SIGINT (Ctrl+C in terminal)
process.on('SIGINT', gracefulShutdown);

async function gracefulShutdown() {
  console.log('Received shutdown signal, closing gracefully...');

  // 1. Stop accepting new requests
  server.close(() => {
    console.log('HTTP server closed');
  });

  // 2. Stop monitor and flush metrics
  console.log('Flushing metrics...');
  monitor.stop();

  // 3. Wait a moment for final flush
  await new Promise(resolve => setTimeout(resolve, 1000));

  console.log('Shutdown complete');
  process.exit(0);
}

// Handle uncaught errors
process.on('uncaughtException', (error) => {
  console.error('Uncaught exception:', error);
  monitor.stop();
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled rejection:', reason);
  monitor.stop();
  process.exit(1);
});

⚠️ Important: Always call monitor.stop() during shutdown to flush buffered metrics. Otherwise, the last batch of metrics may be lost.

Production Configuration

Recommended settings for production environments.

const MCPulseMonitor = require('mcpulse-monitor');

const monitor = new MCPulseMonitor({
  // API Key from environment variable (REQUIRED)
  apiKey: process.env.MCPULSE_API_KEY,

  // Server ID (use environment-specific IDs)
  serverId: process.env.NODE_ENV === 'production'
    ? 'weather-mcp-prod'
    : 'weather-mcp-dev',

  // Endpoint (optional, defaults to https://stacks.polsia.app)
  endpoint: 'https://stacks.polsia.app',

  // Report every 60 seconds (default)
  // ⚡ Reduce to 30s for real-time monitoring
  // 📊 Increase to 120s to reduce network traffic
  reportingInterval: 60000,

  // Heartbeat every 60 seconds (default)
  // Keep this at 60s for accurate uptime tracking
  heartbeatInterval: 60000,

  // Buffer up to 1000 metrics (default)
  // 🔼 Increase for high-traffic servers (2000-5000)
  // 🔽 Decrease for low-memory environments (500)
  maxBufferedMetrics: 1000,

  // Request timeout (5 seconds default)
  // 🔼 Increase for slow networks or regions
  timeout: 5000,

  // Silent mode (suppress console logs in production)
  silent: process.env.NODE_ENV === 'production'
});

// Wrap server
monitor.wrap(yourMCPServer);

// Start monitoring
monitor.start();

// Log initialization
if (process.env.NODE_ENV !== 'production') {
  console.log('MCPulse monitoring initialized:', {
    serverId: monitor.serverId,
    endpoint: monitor.endpoint,
    reportingInterval: monitor.reportingInterval
  });
}

✅ Production Checklist

  • • Set silent: true to reduce console noise
  • • Use environment-specific server IDs (prod vs dev vs staging)
  • • Store API key in MCPULSE_API_KEY environment variable
  • • Implement graceful shutdown (see example above)
  • • Monitor memory usage and adjust maxBufferedMetrics if needed

🚀 Performance Tips

  • • Use longer reportingInterval (90-120s) to reduce network calls
  • • Keep heartbeatInterval at 60s for accurate uptime
  • • For ultra-high-traffic servers (>10k req/min), increase maxBufferedMetrics to 5000
  • • Monitor CPU/memory impact with your APM tool

Environment Variables

Recommended environment variable setup for different environments.

Development (.env)

# MCPulse Configuration
MCPULSE_API_KEY=mcpulse_sk_dev_abc123...
NODE_ENV=development

# Your app config
PORT=3000

Production (Render/Heroku)

# MCPulse Configuration
MCPULSE_API_KEY=mcpulse_sk_prod_xyz789...
NODE_ENV=production

# Your app config
PORT=3000

Next Steps

Have More Integration Questions?

Need help with a specific use case or custom integration?