documenso-observability

0
0
Source

Implement monitoring, logging, and tracing for Documenso integrations. Use when setting up observability, implementing metrics collection, or debugging production issues. Trigger with phrases like "documenso monitoring", "documenso metrics", "documenso logging", "documenso tracing", "documenso observability".

Install

mkdir -p .claude/skills/documenso-observability && curl -L -o skill.zip "https://mcp.directory/api/skills/download/8428" && unzip -o skill.zip -d .claude/skills/documenso-observability && rm skill.zip

Installs to .claude/skills/documenso-observability

About this skill

Documenso Observability

Overview

Implement monitoring, structured logging, and health checks for Documenso integrations. Since Documenso does not expose rate limit headers or usage metrics via API, observability is built around your API call patterns, latency, error rates, and webhook delivery.

Prerequisites

  • Working Documenso integration
  • Monitoring stack (Prometheus/Grafana, Datadog, or CloudWatch)
  • Logging infrastructure

Instructions

Step 1: Instrumented Client Wrapper

// src/observability/documenso-metrics.ts
import { Documenso } from "@documenso/sdk-typescript";

interface Metrics {
  requestCount: number;
  errorCount: number;
  totalLatencyMs: number;
  errorsByStatus: Record<number, number>;
}

const metrics: Metrics = {
  requestCount: 0,
  errorCount: 0,
  totalLatencyMs: 0,
  errorsByStatus: {},
};

export function createInstrumentedClient(): Documenso {
  const client = new Documenso({ apiKey: process.env.DOCUMENSO_API_KEY! });

  return new Proxy(client, {
    get(target, prop) {
      const value = (target as any)[prop];
      if (typeof value === "object" && value !== null) {
        return new Proxy(value, {
          get(innerTarget, method) {
            const fn = (innerTarget as any)[method];
            if (typeof fn !== "function") return fn;

            return async (...args: any[]) => {
              const start = Date.now();
              metrics.requestCount++;

              try {
                const result = await fn.apply(innerTarget, args);
                metrics.totalLatencyMs += Date.now() - start;
                return result;
              } catch (err: any) {
                metrics.errorCount++;
                const status = err.statusCode ?? 0;
                metrics.errorsByStatus[status] = (metrics.errorsByStatus[status] || 0) + 1;
                metrics.totalLatencyMs += Date.now() - start;
                throw err;
              }
            };
          },
        });
      }
      return value;
    },
  });
}

// Expose metrics for Prometheus scraping
export function getMetrics() {
  return {
    ...metrics,
    avgLatencyMs: metrics.requestCount > 0
      ? Math.round(metrics.totalLatencyMs / metrics.requestCount)
      : 0,
    errorRate: metrics.requestCount > 0
      ? (metrics.errorCount / metrics.requestCount * 100).toFixed(2) + "%"
      : "0%",
  };
}

Step 2: Structured Logging

// src/observability/logger.ts
import { createLogger, format, transports } from "winston";

const logger = createLogger({
  level: process.env.LOG_LEVEL ?? "info",
  format: format.combine(
    format.timestamp(),
    format.json()
  ),
  defaultMeta: { service: "documenso-integration" },
  transports: [
    new transports.Console(),
    // Add file or cloud transport for production
  ],
});

// Log Documenso operations with structured context
export function logDocumensoOperation(
  operation: string,
  documentId?: number,
  extra?: Record<string, any>
) {
  logger.info("documenso_operation", {
    operation,
    documentId,
    ...extra,
  });
}

// Log errors with full context
export function logDocumensoError(
  operation: string,
  error: any,
  documentId?: number
) {
  logger.error("documenso_error", {
    operation,
    documentId,
    statusCode: error.statusCode,
    message: error.message,
    // Never log API keys
  });
}

Step 3: Health Check Endpoint

// src/api/health.ts
import { Documenso } from "@documenso/sdk-typescript";

interface HealthStatus {
  status: "healthy" | "degraded" | "unhealthy";
  latencyMs: number;
  message: string;
}

async function checkDocumensoHealth(): Promise<HealthStatus> {
  const client = new Documenso({ apiKey: process.env.DOCUMENSO_API_KEY! });
  const start = Date.now();

  try {
    await client.documents.findV0({ page: 1, perPage: 1 });
    const latencyMs = Date.now() - start;

    if (latencyMs > 5000) {
      return { status: "degraded", latencyMs, message: "High latency" };
    }
    return { status: "healthy", latencyMs, message: "OK" };
  } catch (err: any) {
    return {
      status: "unhealthy",
      latencyMs: Date.now() - start,
      message: `${err.statusCode ?? "unknown"}: ${err.message}`,
    };
  }
}

// Express endpoint
app.get("/health/documenso", async (req, res) => {
  const health = await checkDocumensoHealth();
  const httpStatus = health.status === "healthy" ? 200 : health.status === "degraded" ? 200 : 503;
  res.status(httpStatus).json(health);
});

Step 4: Prometheus Metrics Endpoint

// src/api/metrics.ts
import { getMetrics } from "../observability/documenso-metrics";

app.get("/metrics/documenso", (req, res) => {
  const m = getMetrics();
  res.type("text/plain").send(`
# HELP documenso_requests_total Total API requests
# TYPE documenso_requests_total counter
documenso_requests_total ${m.requestCount}

# HELP documenso_errors_total Total API errors
# TYPE documenso_errors_total counter
documenso_errors_total ${m.errorCount}

# HELP documenso_avg_latency_ms Average request latency
# TYPE documenso_avg_latency_ms gauge
documenso_avg_latency_ms ${m.avgLatencyMs}
  `.trim());
});

Step 5: Webhook Delivery Monitoring

// Track webhook delivery success/failure
const webhookMetrics = {
  received: 0,
  processed: 0,
  failed: 0,
  byEvent: {} as Record<string, number>,
};

app.post("/webhooks/documenso", async (req, res) => {
  webhookMetrics.received++;
  const { event } = req.body;
  webhookMetrics.byEvent[event] = (webhookMetrics.byEvent[event] || 0) + 1;

  res.status(200).json({ received: true });

  try {
    await processWebhookEvent(req.body);
    webhookMetrics.processed++;
  } catch (err) {
    webhookMetrics.failed++;
    logDocumensoError("webhook_processing", err);
  }
});

// Expose webhook metrics
app.get("/metrics/webhooks", (req, res) => {
  res.json(webhookMetrics);
});

Step 6: Alerting Rules

# alerting-rules.yml (Prometheus)
groups:
  - name: documenso
    rules:
      - alert: DocumensoHighErrorRate
        expr: rate(documenso_errors_total[5m]) / rate(documenso_requests_total[5m]) > 0.05
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Documenso error rate above 5%"

      - alert: DocumensoUnhealthy
        expr: up{job="documenso-health"} == 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "Documenso health check failing"

      - alert: DocumensoHighLatency
        expr: documenso_avg_latency_ms > 5000
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Documenso average latency above 5s"

Key Metrics to Monitor

MetricHealthyWarningCritical
API error rate< 1%1-5%> 5%
Average latency< 1s1-5s> 5s
Health checkPassingDegradedFailing
Webhook delivery> 99%95-99%< 95%

Error Handling

Observability IssueCauseSolution
Metrics not appearingScrape config wrongVerify Prometheus targets
Logs missingLog level too highSet LOG_LEVEL=debug temporarily
False alertsThresholds too sensitiveAdjust to match your traffic patterns
Health check flappingTransient network issuesAdd for: 2m to alert rules

Resources

Next Steps

For incident response, see documenso-incident-runbook.

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.

8227

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.

4926

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".

14217

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.

4615

designing-database-schemas

jeremylongshore

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

11514

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

11410

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,1421,171

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.

969933

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."

683829

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.

691549

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.

797540

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.

697374

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.