MCP Examples

Real-world examples of using NoLag MCP with AI assistants.

Example 1: Building a Notification System

Conversation

You:

I need a notification system for my SaaS app. Users should receive notifications for: new comments on their posts, mentions, and system announcements. Set this up with NoLag.

What Claude Does

  1. Creates a project called "SaaS Notifications"
  2. Creates an app called "notifications-service"
  3. Creates topics:
    • notifications/user/{userId}/comments - Comment notifications
    • notifications/user/{userId}/mentions - Mention notifications
    • notifications/system/announcements - System-wide announcements
  4. Generates client code for subscribing to user notifications
  5. Generates server code for publishing notifications

Generated Client Code

import { NoLag } from '@nolag/js-sdk'

export class NotificationService {
  private client: ReturnType<typeof NoLag> | null = null
  private userId: string

  constructor(userId: string) {
    this.userId = userId
  }

  async connect() {
    this.client = NoLag(process.env.NOLAG_TOKEN!)

    this.client.on('connect', () => {
      // Subscribe to user-specific notifications
      this.client!.subscribe(`notifications/user/${this.userId}/comments`)
      this.client!.subscribe(`notifications/user/${this.userId}/mentions`)

      // Subscribe to system announcements
      this.client!.subscribe('notifications/system/announcements')
    })

    // Handle notifications
    this.client.on(`notifications/user/${this.userId}/comments`, (data) => {
      this.showNotification({ type: 'comment', ...data })
    })
    this.client.on(`notifications/user/${this.userId}/mentions`, (data) => {
      this.showNotification({ type: 'mention', ...data })
    })
    this.client.on('notifications/system/announcements', (data) => {
      this.showNotification({ type: 'announcement', ...data })
    })

    await this.client.connect()
  }

  private showNotification(notification: any) {
    // Display notification in UI
    console.log('New notification:', notification)
  }

  disconnect() {
    this.client?.disconnect()
  }
}

Example 2: Live Collaboration Feature

Conversation

You:

Add real-time cursor tracking to my document editor. Users should see where others are editing, with their cursor position and selection range updating in real-time.

Generated Code

import { NoLag } from '@nolag/js-sdk'

interface CursorPosition {
  userId: string
  userName: string
  color: string
  position: {
    line: number
    column: number
  }
  selection?: {
    start: { line: number; column: number }
    end: { line: number; column: number }
  }
}

export class CollaborativeCursors {
  private client: ReturnType<typeof NoLag>
  private documentId: string
  private cursors = new Map<string, CursorPosition>()
  private onCursorUpdate: (cursors: CursorPosition[]) => void

  constructor(
    client: ReturnType<typeof NoLag>,
    documentId: string,
    onCursorUpdate: (cursors: CursorPosition[]) => void
  ) {
    this.client = client
    this.documentId = documentId
    this.onCursorUpdate = onCursorUpdate

    // Subscribe to cursor updates for this document
    client.subscribe(`documents/${documentId}/cursors`)

    // Handle cursor position updates
    client.on(`documents/${documentId}/cursors`, (data: CursorPosition) => {
      this.cursors.set(data.userId, data)
      this.notifyUpdate()
    })

    // Handle users leaving (presence is project-level)
    client.on('presence:leave', (actor) => {
      this.cursors.delete(actor.actorTokenId)
      this.notifyUpdate()
    })
  }

  // Call this when local cursor moves
  updateCursor(position: CursorPosition) {
    this.client.emit(`documents/${this.documentId}/cursors`, position, { qos: 0 })
  }

  // Throttled cursor updates for performance
  private throttledUpdate = throttle((position: CursorPosition) => {
    this.updateCursor(position)
  }, 50) // 20 updates per second max

  onLocalCursorMove(position: CursorPosition) {
    this.throttledUpdate(position)
  }

  private notifyUpdate() {
    this.onCursorUpdate(Array.from(this.cursors.values()))
  }

  destroy() {
    this.client.unsubscribe(`documents/${this.documentId}/cursors`)
  }
}

// Throttle helper
function throttle<T extends (...args: any[]) => any>(
  func: T,
  limit: number
): T {
  let inThrottle: boolean
  return ((...args) => {
    if (!inThrottle) {
      func(...args)
      inThrottle = true
      setTimeout(() => (inThrottle = false), limit)
    }
  }) as T
}

Example 3: Debugging a Topic

Conversation

You:

Users are complaining that they don't receive messages in the chat/support room. Can you investigate?

Claude:

I'll investigate the chat/support topic. Let me check a few things...

*Uses nolag_get_connections, nolag_list_topics, nolag_get_metrics, nolag_subscribe*

Investigation Results

Findings:

Active Connections12 users subscribed
Messages (24h)0 delivered, 47 published
Topic ACLsubscribe: "authenticated", publish: "admin"
Recent Errors47x "ACL_DENIED" for publish operations

Root Cause:

The topic ACL only allows "admin" role to publish, but support agents have "support" role. Messages are being rejected.

Solution:

Update the topic ACL to allow "support" role to publish:

// Updated ACL
{
  "publish": ["admin", "support"],
  "subscribe": "authenticated"
}

Example 4: Setting Up IoT Data Pipeline

Conversation

You:

I have 500 temperature sensors sending data every 5 seconds. Set up NoLag to handle this with proper topic structure and a dashboard subscription.

Generated Architecture

Topic Structure:
├── sensors/temperature/{sensorId}     # Individual sensor data (QoS 0)
├── sensors/temperature/aggregate      # Aggregated stats (QoS 1)
├── sensors/alerts/temperature         # Alert notifications (QoS 2)
└── sensors/status/{sensorId}          # Sensor health status

Data Flow:
1. Sensors publish to sensors/temperature/{id} at QoS 0
2. Aggregation service subscribes to sensors/temperature/+
3. Aggregation service publishes to sensors/temperature/aggregate every 10s
4. Dashboard subscribes to aggregate topic
5. Alert service monitors for anomalies, publishes to alerts topic

Sensor Code (Generated)

// sensor-client.ts - Runs on each IoT device
import { NoLag } from '@nolag/js-sdk'

const SENSOR_ID = process.env.SENSOR_ID!

async function startSensor() {
  const client = NoLag(process.env.NOLAG_SENSOR_TOKEN!)

  client.on('connect', () => {
    // Report status on connect
    client.emit(`sensors/status/${SENSOR_ID}`, {
      status: 'online',
      timestamp: Date.now()
    }, { qos: 1 })

    // Send temperature readings
    setInterval(() => {
      const temperature = readTemperatureSensor()

      client.emit(`sensors/temperature/${SENSOR_ID}`, {
        sensorId: SENSOR_ID,
        temperature,
        unit: 'celsius',
        timestamp: Date.now()
      }, { qos: 0 }) // Fire and forget for telemetry
    }, 5000)
  })

  await client.connect()
}

function readTemperatureSensor(): number {
  // Hardware-specific implementation
  return 0
}

startSensor()

Next Steps