langfuse-webhooks-events

0
0
Source

Configure Langfuse webhooks and event callbacks for real-time notifications. Use when setting up trace notifications, configuring evaluation callbacks, or integrating Langfuse events with external systems. Trigger with phrases like "langfuse webhooks", "langfuse events", "langfuse notifications", "langfuse callbacks", "langfuse alerts".

Install

mkdir -p .claude/skills/langfuse-webhooks-events && curl -L -o skill.zip "https://mcp.directory/api/skills/download/9441" && unzip -o skill.zip -d .claude/skills/langfuse-webhooks-events && rm skill.zip

Installs to .claude/skills/langfuse-webhooks-events

About this skill

Langfuse Webhooks & Events

Overview

Configure Langfuse webhooks to receive notifications on prompt version changes. Langfuse supports webhook events for prompt lifecycle: Created, Updated (labels/tags changed), and Deleted. Use webhooks to trigger CI/CD pipelines, sync prompts to external systems, or notify teams via Slack.

Prerequisites

  • Langfuse Cloud or self-hosted instance
  • HTTPS endpoint to receive webhook POST requests
  • Webhook secret for HMAC signature verification

Instructions

Step 1: Create Webhook Endpoint

// app/api/webhooks/langfuse/route.ts (Next.js App Router)
import { NextRequest, NextResponse } from "next/server";
import crypto from "crypto";

const WEBHOOK_SECRET = process.env.LANGFUSE_WEBHOOK_SECRET!;

interface LangfuseWebhookEvent {
  event: "prompt.created" | "prompt.updated" | "prompt.deleted";
  timestamp: string;
  data: {
    promptName: string;
    promptVersion: number;
    labels?: string[];
    projectId: string;
    [key: string]: any;
  };
}

// Verify HMAC SHA-256 signature
function verifySignature(payload: string, signature: string): boolean {
  const expected = crypto
    .createHmac("sha256", WEBHOOK_SECRET)
    .update(payload)
    .digest("hex");

  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expected)
  );
}

export async function POST(request: NextRequest) {
  const payload = await request.text();
  const signature = request.headers.get("x-langfuse-signature");

  // Verify webhook authenticity
  if (!signature || !verifySignature(payload, signature)) {
    return NextResponse.json({ error: "Invalid signature" }, { status: 401 });
  }

  const event: LangfuseWebhookEvent = JSON.parse(payload);
  console.log(`Langfuse webhook: ${event.event} - ${event.data.promptName}`);

  switch (event.event) {
    case "prompt.created":
      await handlePromptCreated(event.data);
      break;
    case "prompt.updated":
      await handlePromptUpdated(event.data);
      break;
    case "prompt.deleted":
      await handlePromptDeleted(event.data);
      break;
  }

  return NextResponse.json({ received: true });
}

async function handlePromptCreated(data: LangfuseWebhookEvent["data"]) {
  // Trigger CI/CD pipeline for new prompt version
  if (data.labels?.includes("production")) {
    await triggerPromptDeployPipeline(data.promptName, data.promptVersion);
  }

  await notifySlack({
    text: `New prompt version: *${data.promptName}* v${data.promptVersion}`,
    labels: data.labels,
  });
}

async function handlePromptUpdated(data: LangfuseWebhookEvent["data"]) {
  // Label change -- check if promoted to production
  if (data.labels?.includes("production")) {
    await notifySlack({
      text: `Prompt *${data.promptName}* v${data.promptVersion} promoted to production`,
    });
  }
}

async function handlePromptDeleted(data: LangfuseWebhookEvent["data"]) {
  await notifySlack({
    text: `Prompt *${data.promptName}* v${data.promptVersion} deleted`,
    level: "warning",
  });
}

Step 2: Configure Webhook in Langfuse

  1. Navigate to Prompts > Create Automation > Webhook
  2. Enter your endpoint URL: https://your-domain.com/api/webhooks/langfuse
  3. Select events to watch: Created, Updated, Deleted
  4. Optionally filter to specific prompts
  5. Generate and save the webhook secret
  6. Click Test to verify connectivity

Step 3: Slack Integration

// lib/slack-notify.ts

async function notifySlack(params: {
  text: string;
  labels?: string[];
  level?: "info" | "warning";
}) {
  const color = params.level === "warning" ? "#ff9800" : "#36a64f";

  await fetch(process.env.SLACK_WEBHOOK_URL!, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      attachments: [
        {
          color,
          blocks: [
            {
              type: "section",
              text: { type: "mrkdwn", text: params.text },
            },
            ...(params.labels
              ? [
                  {
                    type: "context",
                    elements: [
                      {
                        type: "mrkdwn",
                        text: `Labels: ${params.labels.join(", ")}`,
                      },
                    ],
                  },
                ]
              : []),
          ],
        },
      ],
    }),
  });
}

Step 4: Trigger CI/CD Pipeline on Prompt Changes

// Trigger GitHub Actions workflow when production prompt changes
async function triggerPromptDeployPipeline(promptName: string, version: number) {
  await fetch(
    `https://api.github.com/repos/${process.env.GITHUB_REPO}/dispatches`,
    {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.GITHUB_TOKEN}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        event_type: "prompt-updated",
        client_payload: { promptName, version },
      }),
    }
  );
}
# .github/workflows/prompt-deploy.yml
name: Deploy Updated Prompt
on:
  repository_dispatch:
    types: [prompt-updated]

jobs:
  test-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: "20", cache: "npm" }
      - run: npm ci

      - name: Test updated prompt
        env:
          LANGFUSE_PUBLIC_KEY: ${{ secrets.LANGFUSE_PUBLIC_KEY }}
          LANGFUSE_SECRET_KEY: ${{ secrets.LANGFUSE_SECRET_KEY }}
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: |
          echo "Testing prompt: ${{ github.event.client_payload.promptName }}"
          npx vitest run tests/ai/prompt-quality.test.ts

Step 5: Webhook Reliability with Retry Queue

// For production: queue webhook processing to return 200 fast
import { Queue, Worker } from "bullmq";

const webhookQueue = new Queue("langfuse-webhooks", {
  connection: { host: process.env.REDIS_HOST },
});

// In webhook handler -- enqueue and respond immediately
export async function POST(request: NextRequest) {
  const payload = await request.text();
  // ... verify signature ...

  await webhookQueue.add("process", JSON.parse(payload), {
    attempts: 3,
    backoff: { type: "exponential", delay: 1000 },
  });

  return NextResponse.json({ received: true }); // Return fast
}

// Worker processes asynchronously
const worker = new Worker(
  "langfuse-webhooks",
  async (job) => {
    const event = job.data as LangfuseWebhookEvent;
    // Process event...
  },
  { connection: { host: process.env.REDIS_HOST } }
);

Webhook Event Reference

EventTriggerUse Case
prompt.createdNew prompt version addedRun regression tests, notify team
prompt.updatedLabels or tags changedDetect production promotions
prompt.deletedPrompt version removedAlert on accidental deletion

Error Handling

IssueCauseSolution
Invalid signature (401)Wrong webhook secretRe-copy secret from Langfuse settings
Missed eventsHandler threw errorQueue events, return 200 immediately
Duplicate processingRetry without idempotencyDedupe by event + timestamp + promptName
Webhook timeoutSlow handlerEnqueue and process async

Resources

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

6832

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

9229

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

16122

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

5015

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

12014

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

5210

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

1,4211,305

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

1,2361,030

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

9151,017

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

975666

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

979609

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,046505

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.