Skip to main content

Sentry Error Monitoring & Debugging

Status: Production-ready configuration with MCP integration Last Updated: 2025-11-18 Aligned with: CLAUDE.md Project Values

Table of Contents


Overview

Purpose

Sentry provides real-time error monitoring, performance tracking, and debugging for the Sanctiv mobile app. This document outlines our production-ready configuration aligned with project values:
  • 100% Excellence - Proper error boundaries, source maps, release tracking
  • Speed to Market - Fast debugging with AI-assisted root cause analysis
  • Multi-Tenant Architecture - org_id tagging for church isolation
  • Follow the Leader - Best-in-class Sentry configuration

Key Capabilities

  • βœ… Real-time error tracking (JS + Native crashes)
  • βœ… Performance monitoring (20% sampling in production)
  • βœ… Session tracking & crash-free rate
  • βœ… Breadcrumb trails for debugging context
  • βœ… AI-powered root cause analysis (via MCP)
  • βœ… Multi-tenant context tagging
  • 🚧 Source maps upload (pending CI/CD)
  • 🚧 Release tracking (pending versioning)
  • 🚧 User feedback integration (pending)

Current Status

βœ… What’s Working

Configuration: src/lib/sentry.ts Current Sentry configuration:
  • DSN: Hardcoded in src/lib/sentry.ts (public, safe to commit)
  • Fallback: Can override via EXPO_PUBLIC_SENTRY_DSN env var if needed
  • Note: DSN is PUBLIC and safe to commit - it’s visible in client-side code anyway
  • Debug mode: Enabled in __DEV__, disabled in production
  • Traces sample rate: 100% in development, 20% in production
  • Session tracking: 10-second intervals, auto-tracking enabled
  • Native crash handling: Enabled for both iOS and Android
  • Error boundaries: App wrapped with Sentry.wrap() in App.tsx
  • Initialization: Called via initializeSentry() in App.tsx with graceful fallback
Testing Tools: src/lib/sentryTest.ts Developer Tools available in Settings screen (DEV only):
  • Send Test Error
  • Send Test Message
  • Send Error with Breadcrumbs
  • Run Full Sentry Test (all 3 tests)
Verified Working:
  • βœ… Errors captured and sent to Sentry dashboard
  • βœ… Test utilities functional with Alert confirmations
  • βœ… Console logging for debugging
  • βœ… Graceful fallback if DSN not configured

🚧 Needs Implementation

The following features are documented but not yet implemented:
  1. Source Maps Upload - Required for readable stack traces in production (see Production Configuration)
  2. Release Tracking - Version tracking and regression detection (see Production Configuration)
  3. Multi-Tenant Context - Organization tagging for B2B error isolation (see Multi-Tenant Context)
  4. Performance Optimization - Sample rate tuning based on volume (see Production Configuration)
  5. User Feedback Integration - Allow users to report issues (see Production Configuration)
Implementation Priority for Pilot:
  • πŸ”΄ Critical: Source maps, Release tracking
  • 🟑 High: Multi-tenant context (org_id tagging)
  • 🟒 Medium: Performance tuning, User feedback

MCP Server Setup

What is Sentry MCP?

The Sentry Model Context Protocol (MCP) server allows AI agents (like Claude Code) to:
  • Query Sentry issues and events in real-time
  • Analyze errors with AI-powered root cause analysis
  • Get fix recommendations from Sentry’s Seer AI
  • Monitor release health and trends
Official Docs: https://docs.sentry.io/product/sentry-mcp/ Project Configuration: The Sentry MCP server is pre-configured in .cursor/mcp.json. To enable it:
  1. Set Sentry Auth Token in Cursor Secrets:
  2. Restart Cursor:
    • Restart Cursor IDE to load MCP server configuration
    • MCP server will automatically use SENTRY_AUTH_TOKEN from secrets
  3. Verify Connection:
    • MCP server uses the same token as Sentry CLI
    • Both CLI (sentry-cli) and MCP server share the same authentication
    • Test with: ./scripts/verify-sentry-events.sh
Configuration File: .cursor/mcp.json
{
  "mcpServers": {
    "sentry": {
      "command": "npx",
      "args": ["-y", "@sentry/mcp-server"],
      "env": {
        "SENTRY_AUTH_TOKEN": "${SENTRY_AUTH_TOKEN}"
      }
    }
  }
}
Benefits:
  • βœ… Persistent configuration (secrets stored in Cursor)
  • βœ… Works with Cloud Agents automatically
  • βœ… Same token for CLI and MCP server
  • βœ… No manual token management needed
See .cursor/README.md for more details.

Setup for Claude Code (CLI)

# Add Sentry MCP server
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp

# Authenticate with OAuth
claude
# Follow OAuth prompts to authenticate with Sentry

Option 2: Local STDIO

  1. Clone the Sentry MCP server:
git clone https://github.com/getsentry/sentry-mcp-stdio.git
cd sentry-mcp-stdio
bun install
  1. Get Sentry Auth Token:
  2. Configure Claude Code:
# Edit config
code ~/.config/claude/config.json
Add:
{
  "mcpServers": {
    "sentry": {
      "command": "bun",
      "args": ["run", "/path/to/sentry-mcp-stdio/index.ts"],
      "env": {
        "SENTRY_AUTH": "your-auth-token-here"
      }
    }
  }
}

Setup for Claude Desktop

  1. Open Claude Desktop Settings
  2. Navigate to: Settings β†’ Developer β†’ Edit Config
  3. Add to claude_desktop_config.json:
{
  "mcpServers": {
    "sentry": {
      "url": "https://mcp.sentry.dev/mcp"
    }
  }
}
  1. Restart Claude Desktop
  2. Authenticate via OAuth when prompted

Available MCP Tools

Once configured, you can:
# Query recent issues
"Show me the latest 10 errors in Sanctiv"

# Analyze specific error
"Analyze error ABC123 and suggest fixes"

# Check release health
"What's the crash-free rate for version 1.0.1?"

# Monitor trends
"Show error trends over the last 7 days"

# Get AI recommendations
"Run Seer analysis on issue XYZ456"

Production Configuration

Critical: Source Maps

Why: Without source maps, stack traces show minified code, making debugging impossible. Implementation:
  1. Install Sentry CLI as dev dependency:
# Already available via npx
npx sentry-cli --version
  1. Configure Sentry properties:
Create sentry.properties:
defaults.url=https://sentry.io/
defaults.org=sanctiv
defaults.project=sanctiv-app

# Add to .env (never commit):
# SENTRY_AUTH_TOKEN=your-token-here
  1. Add to package.json:
{
  "scripts": {
    "build:ios": "npx expo run:ios --no-build-cache",
    "postbuild:ios": "npx sentry-cli sourcemaps upload --org sanctiv --project sanctiv-app ./dist",
    "build:android": "npx expo run:android --no-build-cache",
    "postbuild:android": "npx sentry-cli sourcemaps upload --org sanctiv --project sanctiv-app ./dist"
  }
}
  1. Configure in EAS Build (eas.json):
{
  "build": {
    "production": {
      "env": {
        "SENTRY_AUTH_TOKEN": "@sentry_auth_token"
      }
    }
  }
}
  1. Set EAS secret:
eas secret:create --scope project --name SENTRY_AUTH_TOKEN --value "your-token"

Critical: Release Tracking

Why: Track which version has which bugs, monitor release health, identify regressions. Implementation: Update src/lib/sentry.ts:
import Constants from "expo-constants";

Sentry.init({
  dsn: sentryDsn,
  release: `sanctiv-app@${Constants.expoConfig?.version}+${Constants.expoConfig?.ios?.buildNumber || Constants.expoConfig?.android?.versionCode}`,
  dist: Constants.expoConfig?.ios?.buildNumber || Constants.expoConfig?.android?.versionCode?.toString(),
  environment: __DEV__ ? "development" : "production",
  // ... rest of config
});

Critical: Performance Monitoring

Current: 20% traces sample rate in production βœ… Optimization: Adjust based on volume:
// In production with high traffic:
tracesSampleRate: 0.1, // 10%

// Low traffic (pilot phase):
tracesSampleRate: 0.5, // 50% - more data for optimization

Optional: User Feedback

Allow users to report issues directly:
import * as Sentry from "@sentry/react-native";

// In error boundary or error screen:
Sentry.captureUserFeedback({
  event_id: eventId,
  name: user?.user_metadata?.full_name,
  email: user?.email,
  comments: "Description of what happened..."
});

Multi-Tenant Context

Critical for B2B SaaS

Since Sanctiv is a multi-tenant B2B platform, always tag errors with org_id to:
  • Filter issues by church/organization
  • Identify organization-specific bugs
  • Track error rates per customer
  • Prioritize fixes based on customer impact

Proposed Implementation

🚧 To Implement: Multi-tenant context tagging (not yet implemented) Step 1: Create src/lib/sentryContext.ts:
import * as Sentry from "@sentry/react-native";
import { useAuthStore } from "../state/authStore";

/**
 * Set Sentry context with user and organization data
 * Call this after login/org selection
 */
export function setSentryContext() {
  const user = useAuthStore.getState().user;
  const orgId = useAuthStore.getState().currentOrgId;

  if (user) {
    Sentry.setUser({
      id: user.id,
      email: user.email,
      username: user.user_metadata?.full_name || user.email,
    });
  }

  if (orgId) {
    Sentry.setTag("org_id", orgId);
    Sentry.setContext("organization", {
      org_id: orgId,
      // Add more org context as needed
    });
  }
}

/**
 * Clear Sentry context on logout
 */
export function clearSentryContext() {
  Sentry.setUser(null);
  Sentry.setTag("org_id", undefined);
}
Step 2: Use in your authentication flow (after implementing Step 1):
// After successful login:
setSentryContext();

// After logout:
clearSentryContext();
Step 3: Query by organization in Sentry Dashboard:
# Filter by organization
org_id:"church-123"

# Find issues affecting specific customer
is:unresolved org_id:"church-123"

# Compare error rates
org_id:"church-123" vs org_id:"church-456"

Best Practices

1. Error Boundaries

Already implemented: App.tsx wrapped with Sentry.wrap(App) βœ… Add screen-level boundaries:
import { ErrorBoundary } from "@sentry/react-native";

function MyScreen() {
  return (
    <ErrorBoundary
      fallback={<ErrorFallbackScreen />}
      onError={(error, componentStack) => {
        // Additional error handling
        console.error("Screen error:", error);
      }}
    >
      <YourScreenContent />
    </ErrorBoundary>
  );
}

2. Breadcrumbs

Already available: addBreadcrumb() helper in sentry.ts βœ… Usage examples:
// Navigation
addBreadcrumb("Navigated to journal", { screen: "JournalScreen" }, "info");

// User actions
addBreadcrumb("Journal entry created", { entryId: "123" }, "info");

// API calls
addBreadcrumb("API call started", { endpoint: "/journal" }, "info");

// State changes
addBreadcrumb("User logged in", { userId: user.id }, "info");

3. Structured Error Capture

try {
  await supabase.from("journal_entries").insert(entry);
} catch (error) {
  captureException(error as Error, {
    context: "journal_creation",
    org_id: currentOrgId,
    entry_type: "text",
  });
  // Show user-friendly error
}

4. Filter Noise

Add to Sentry.init():
beforeSend(event) {
  // Filter out network errors during development
  if (__DEV__ && event.exception?.values?.[0]?.type === "NetworkError") {
    return null;
  }

  // Filter known non-critical errors
  if (event.message?.includes("hapticpatternlibrary")) {
    return null; // iOS simulator haptic warnings
  }

  return event;
},

5. Sampling Strategy

Current: 100% dev, 20% production βœ… Adjust for pilot phase:
tracesSampleRate: __DEV__ ? 1.0 :
  Constants.expoConfig?.version?.startsWith("0.") ? 0.5 : 0.2,
// 50% sampling during 0.x pilot, 20% after 1.0 launch

Development Tools

Testing Sentry Integration

Location: Settings β†’ Developer Tools (DEV mode only) Available Tests:
  1. Send Test Error - Single error with context
  2. Send Test Message - Info-level message
  3. Send Error with Breadcrumbs - Error with navigation trail
  4. Run Full Sentry Test - All 3 tests sequentially
Console Logs: Watch for πŸ”§ [DEV TOOLS] prefixed logs to verify test execution.

Manual Testing

import { sendTestError } from "./src/lib/sentryTest";

// In any component
sendTestError();

Sentry CLI Commands

Authentication: For Cursor Cloud Agents (Recommended):
  • Set SENTRY_AUTH_TOKEN in Cursor Settings β†’ Cloud Agents β†’ Secrets
  • Setup workflow (/setup) will automatically configure ~/.sentryclirc
  • MCP server will use the same token automatically
  • No manual configuration needed
For Local Development:
# Option 1: User Auth Token (Full Access)
# Create at: https://sentry.io/settings/account/api/auth-tokens/
# Scopes: org:read, project:read, event:read, project:releases
echo "[auth]" > ~/.sentryclirc
echo "token=YOUR_USER_TOKEN" >> ~/.sentryclirc
chmod 600 ~/.sentryclirc

# Option 2: Interactive Login (Org Token - Write Only)
npx sentry-cli login
Note: If SENTRY_AUTH_TOKEN environment variable is set (from Cursor Secrets), the setup workflow will automatically configure ~/.sentryclirc from it. Verify Token Access:
# Use verification script (recommended)
./scripts/verify-sentry-events.sh

# Or manually test read access
curl -H "Authorization: Bearer $(grep '^token=' ~/.sentryclirc | cut -d'=' -f2-)" \
  "https://sentry.io/api/0/projects/sanctiv/sanctiv-app/events/?per_page=5"
Common Commands:
# Test authentication
sentry-cli info

# Send test event
sentry-cli send-event --level info --message "Test message"

# List releases
npx sentry-cli releases list

# Upload source maps (manual)
npx sentry-cli sourcemaps upload --org sanctiv --project sanctiv-app ./dist

# Create release
npx sentry-cli releases new "[email protected]+34"

# Finalize release
npx sentry-cli releases finalize "[email protected]+34"
Note: User Auth Tokens (sntryu_...) have full read/write access via REST API, even if sentry-cli info shows only org:ci scope. Org tokens (sntrys_...) are write-only.

Release Tracking

Release Creation Workflow

Automated (via EAS Build): Add to .github/workflows/build.yml (when CI/CD implemented):
- name: Create Sentry Release
  run: |
    npx sentry-cli releases new "sanctiv-app@${{ env.VERSION }}+${{ env.BUILD_NUMBER }}"
    npx sentry-cli releases set-commits "sanctiv-app@${{ env.VERSION }}+${{ env.BUILD_NUMBER }}" --auto
    npx sentry-cli releases finalize "sanctiv-app@${{ env.VERSION }}+${{ env.BUILD_NUMBER }}"
Manual (for pilot builds):
# Get version from app.json
VERSION="1.0.1"
BUILD="34"

# Create release
npx sentry-cli releases new "sanctiv-app@${VERSION}+${BUILD}"

# Associate commits
npx sentry-cli releases set-commits "sanctiv-app@${VERSION}+${BUILD}" --auto

# Upload source maps
npx sentry-cli sourcemaps upload --org sanctiv --project sanctiv-app ./dist

# Finalize
npx sentry-cli releases finalize "sanctiv-app@${VERSION}+${BUILD}"

Monitoring Release Health

Sentry Dashboard:
  1. Go to Releases tab
  2. View crash-free sessions/users
  3. Compare releases
  4. Identify regressions
Via MCP:
"Show me the crash-free rate for the latest release"
"Compare version 1.0.1 vs 1.0.0"
"What new issues appeared in release 1.0.2?"

Troubleshooting

Issue: Errors not appearing in Sentry

Check:
  1. DSN configured: echo $EXPO_PUBLIC_SENTRY_DSN
  2. Sentry initialized: Look for βœ… Sentry initialized in logs
  3. Network connectivity: Test with Developer Tools
  4. Sample rate: May not capture 100% in production
Debug:
// Add to sentry.ts init
debug: true,
beforeSend(event) {
  console.log("πŸ“€ Sending to Sentry:", event);
  return event;
},

Issue: Stack traces are minified

Solution: Upload source maps (see Production Configuration)

Issue: Wrong release version

Check:
// In sentry.ts
console.log("Release:", Constants.expoConfig?.version);
console.log("Build:", Constants.expoConfig?.ios?.buildNumber);
Fix: Ensure app.json version and buildNumber are updated before builds.

Issue: MCP server not connecting

Claude Code:
# Check configured servers
claude mcp list

# Test connection
claude
# Try: "List Sentry projects"
Claude Desktop:
  • Check claude_desktop_config.json syntax
  • Restart Claude Desktop
  • Check OAuth token validity

Issue: Too many errors (noise)

Solution: Add beforeSend filter (see Best Practices)

Next Steps for Pilot

Pre-Launch Checklist

  • Source maps upload configured in EAS Build
  • Release tracking automated
  • Multi-tenant context (org_id) implemented
  • Error boundaries on all critical screens
  • Breadcrumbs added to key user flows
  • Sample rate tuned for pilot volume (50%)
  • Alerts configured for critical errors
  • Team trained on Sentry dashboard
  • MCP server configured for AI debugging
  • User feedback integration (optional)

Monitoring During Pilot

Key Metrics:
  • Crash-free session rate (target: >99%)
  • Error rate per organization
  • Most common errors
  • Performance issues (slow screens)
Weekly Review:
  1. Check new issues
  2. Identify organization-specific problems
  3. Prioritize fixes based on customer impact
  4. Monitor release health trends
AI-Assisted Debugging: Use MCP to:
  • Get daily error summaries
  • Analyze top issues with Seer AI
  • Track fix deployment success
  • Compare church-to-church error rates

Resources

Official Documentation

Internal Files


Maintained by: Development Team Questions? Check CLAUDE.md for AI agent support or Slack #dev-support