# Buggregator > Buggregator is a free, open-source debugging server. Debug everything — install nothing. One docker run (or a single binary) gives you exceptions, dumps, emails, profiling, and logs in a single real-time UI. Written in Go with an embedded SQLite database. Runs beside your app, not inside it. - Install (binary, no Docker): download https://github.com/buggregator/server/releases/latest/download/buggregator-- (linux-amd64, linux-arm64, darwin-arm64, darwin-amd64, windows-amd64.exe, windows-arm64.exe), chmod +x, run. AI agents: follow /agent-setup.md - Install (Docker): `docker run --pull always -p 127.0.0.1:8000:8000 -p 127.0.0.1:1025:1025 -p 127.0.0.1:9912:9912 ghcr.io/buggregator/server:latest` - GitHub: https://github.com/buggregator/server - Lightweight CLI alternative (no Docker): `composer require --dev buggregator/trap` - JetBrains IDE plugin: https://plugins.jetbrains.com/plugin/26344-buggregator - Supported integrations: Sentry SDK, Symfony VarDumper, Monolog, Spatie Ray, Inspector, SMTP, HTTP dumps, XHProf, SMS - Also built in: HTTP proxy, mock server under /mock/, Xdebug proxy (off by default), MCP server for AI assistants - Works with: Laravel, Symfony, Spiral, WordPress, Yii, Drupal — and JS, Python, Ruby, Go via Sentry SDK --- # Set up with an AI agent This page is written for an AI agent (Claude Code, Cursor, Codex and others). Give it to your agent: ``` Read https://docs.buggregator.dev/agent-setup.md and set up Buggregator for this project. ``` The rest of the page is the agent's instructions. --- ## Instructions for the agent Goal: Buggregator runs on this machine, the user's app sends events to it, and you can read them over MCP. Run the steps in order. Each step has a check; do not go on until it passes. ### 1. Install Linux and macOS: the script picks the binary for this OS and CPU, checks its checksum and puts it in `~/.local/bin/buggregator`. Then start it in the background: ```bash curl -fsSL https://raw.githubusercontent.com/buggregator/server/master/scripts/install.sh | sh mkdir -p ~/.local/share/buggregator MCP_ENABLED=true PROXY_ADDR=127.0.0.1:8080 nohup ~/.local/bin/buggregator \ -http-addr 127.0.0.1:8000 -smtp-addr 127.0.0.1:1025 \ -vardumper-addr 127.0.0.1:9912 -monolog-addr 127.0.0.1:9913 \ -db ~/.local/share/buggregator/buggregator.db \ > ~/.local/share/buggregator/buggregator.log 2>&1 & ``` Windows (PowerShell): the script puts `buggregator.exe` in `%LOCALAPPDATA%\Programs\buggregator`. MCP runs over HTTP on Windows (no Unix socket there): ```powershell irm https://raw.githubusercontent.com/buggregator/server/master/scripts/install.ps1 | iex $dir = "$env:LOCALAPPDATA\Programs\buggregator" $env:MCP_ENABLED = "true"; $env:MCP_TRANSPORT = "http"; $env:MCP_ADDR = "127.0.0.1:8001"; $env:PROXY_ADDR = "127.0.0.1:8080" Start-Process -WindowStyle Hidden "$dir\buggregator.exe" -ArgumentList "-http-addr 127.0.0.1:8000 -smtp-addr 127.0.0.1:1025 -monolog-addr 127.0.0.1:9913 -db `"$dir\buggregator.db`"" ``` The script fails with `no checksums.txt in this release`: the latest release is older than v2.6.0. Run it again with `BUGGREGATOR_NO_VERIFY=1` (`curl … | BUGGREGATOR_NO_VERIFY=1 sh`; PowerShell: `$env:BUGGREGATOR_NO_VERIFY = "1"` before `irm`). No `curl`/`sh` or the script fails otherwise: download by hand. URL `https://github.com/buggregator/server/releases/latest/download/`, where `` is `buggregator-linux-amd64`, `buggregator-linux-arm64`, `buggregator-darwin-arm64`, `buggregator-darwin-amd64`, `buggregator-windows-amd64.exe` or `buggregator-windows-arm64.exe`; then `chmod +x`. Rules: - Every port listens on `127.0.0.1` only: captured data stays on this machine. - `-db` keeps events after a restart. Without it, events live in memory. - A port already taken: Buggregator exits at start (code 1), the log says `address already in use` (`failed to start HTTP server` for `8000`, `failed to start TCP servers` for the others). Find what holds it (`lsof -i :1025`) and move that module to a free port: | Port | Module | Move it with | |------|--------|--------------| | `8000` | web UI, HTTP events | `-http-addr 127.0.0.1:8010` | | `1025` | SMTP | `-smtp-addr 127.0.0.1:2525` | | `9912` | VarDumper | `-vardumper-addr 127.0.0.1:9922` | | `9913` | Monolog | `-monolog-addr 127.0.0.1:9923` | | `8080` | HTTP proxy | environment only: `PROXY_ADDR=127.0.0.1:8081` (there is no flag) | | `8001` | MCP over HTTP (Windows) | environment only: `MCP_ADDR=127.0.0.1:8002` | Use the new port in step 3 and step 4. Tell the user which port you moved. - On Windows the VarDumper module (port `9912`) does not work; everything else does. Check: ```bash curl -s http://127.0.0.1:8000/api/version # {"version":"…"} ``` No answer: read the log (`~/.local/share/buggregator/buggregator.log`). ### 2. Send a test event ```bash curl -s -H 'X-Buggregator-Event: http-dump' http://127.0.0.1:8000/agent-setup-test curl -s http://127.0.0.1:8000/api/events | head -c 300 ``` Check: the list has an event of type `http-dump` with `agent-setup-test` in its URI. Tell the user it is in the UI at http://127.0.0.1:8000. ### 3. Point the user's app at Buggregator Change only the addresses below in the app's config (`.env` or similar). Keep the user's other settings. Add only the lines for tools the app already uses. First check where the app runs. A Docker service name in the config (e.g. `MAIL_HOST=mailpit`, `DB_HOST=mysql`) usually means the app runs in Docker Compose: see «The app runs in Docker» below. Not sure: ask the user. | The app uses | Set | |--------------|-----| | Sentry SDK | DSN `http://sentry@127.0.0.1:8000/1` (Laravel: `SENTRY_LARAVEL_DSN`, others: `SENTRY_DSN`) | | Symfony VarDumper | `VAR_DUMPER_FORMAT=server`, `VAR_DUMPER_SERVER=127.0.0.1:9912` | | Monolog (optional) | socket handler to `127.0.0.1:9913`. Laravel: `LOG_CHANNEL=socket`, `LOG_SOCKET_URL=127.0.0.1:9913`. This sends the app's logs to Buggregator instead of its current channel (e.g. `stack` → files): ask the user before you change `LOG_CHANNEL`. Laravel apps use Monolog without saying so, so `LOG_CHANNEL` alone does not mean the user wants this. | | Email (SMTP) | host `127.0.0.1`, port `1025`, no auth (Laravel: `MAIL_MAILER=smtp`, `MAIL_HOST`, `MAIL_PORT`) | | Spatie Ray | `RAY_HOST=ray@127.0.0.1`, `RAY_PORT=8000` | **The app runs in Docker.** `127.0.0.1` inside a container is the container itself, so the addresses above do not reach a Buggregator on the host. Two ways, ask the user which: 1. Run Buggregator in the same Compose stack, and use its service name: `MAIL_HOST=buggregator`, `SENTRY_LARAVEL_DSN=http://sentry@buggregator:8000/1`. See [Getting Started](/getting-started#docker-compose). 2. Keep the binary on the host and use `host.docker.internal` instead of `127.0.0.1` (Docker Desktop; on Linux add `extra_hosts: ["host.docker.internal:host-gateway"]` to the service). The binary must then listen on `0.0.0.0`, not `127.0.0.1`, which opens its ports to the network. Details per tool: [Sentry](/config/sentry), [VarDumper](/config/var-dumper), [Monolog](/config/monolog), [SMTP](/config/smtp), [Ray](/config/ray), [Inspector](/config/inspector), [XHProf](/config/xhprof). Check: trigger something in the app (an error, a `dump()`, a log line, an email) and see a new event in `GET /api/events`. ### 4. Connect MCP Claude Code, Linux and macOS (socket, the default): ```bash claude mcp add buggregator -- "$HOME/.local/bin/buggregator" mcp ``` Give the full path (as above) or `buggregator` when it is on `PATH`. Some clients store the command as written: a `~` stays a literal `~` there. Claude Code, Windows (HTTP, as started in step 1): ```bash claude mcp add --transport http buggregator http://127.0.0.1:8001/mcp ``` Other clients: [MCP → Integration with AI assistants](/config/mcp#integration-with-ai-assistants). Check: the client lists the tool `events_list`; calling it returns the test event from step 2. A new MCP server may need a new session of the client: tell the user if so. To check by hand without a client: `buggregator mcp` talks JSON-RPC over stdin and stdout and stops when stdin closes. Keep stdin open while you wait for the answer: ```bash (printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"check","version":"1"}}}' \ '{"jsonrpc":"2.0","method":"notifications/initialized"}' \ '{"jsonrpc":"2.0","id":2,"method":"tools/list"}'; sleep 2) | "$HOME/.local/bin/buggregator" mcp ``` The answer with `"id":2` lists `events_list` and the other tools. ### 5. Tell the user Say in plain words: where the UI is (http://127.0.0.1:8000), which lines of their config you changed, and how to stop it (below). ## Stop and restart ```bash pkill -f '.local/bin/buggregator' # Linux, macOS ``` ```powershell Stop-Process -Name buggregator # Windows ``` Start again with the start command of step 1 (skip the install line). ## Update Run the install line of step 1 again: it replaces the old file with the latest release. Stop the running one first. Events stay in the `-db` file. --- # Configuration — Database Buggregator uses [SQLite](https://www.sqlite.org/) as its database. SQLite is embedded directly into the binary — no external database server is needed. ## Storage Modes ### In-Memory (Default) By default, Buggregator stores everything in memory. This is the fastest option but **all data is lost when the server restarts**. ```yaml database: dsn: ":memory:" ``` This is the default — no configuration needed. ### File-Based To persist data across restarts, specify a file path: ```yaml database: dsn: data.db ``` Or via environment variable: ```bash DATABASE_DSN=data.db ``` A relative path like `data.db` is resolved from the directory you start Buggregator in. Use an absolute path to be sure. In Docker, make sure to mount a volume: ```bash docker run --pull always \ -p 127.0.0.1:8000:8000 \ -e DATABASE_DSN=/data/buggregator.db \ -v buggregator-data:/data \ ghcr.io/buggregator/server:latest ``` ### Docker Compose Example ```yaml services: buggregator: image: ghcr.io/buggregator/server:latest ports: - 127.0.0.1:8000:8000 - 127.0.0.1:1025:1025 - 127.0.0.1:9912:9912 - 127.0.0.1:9913:9913 environment: DATABASE_DSN: /data/buggregator.db STORAGE_MODE: filesystem STORAGE_PATH: /data/storage volumes: - buggregator-data:/data volumes: buggregator-data: ``` ## Connection Pool Since v2.6.0, a file database opens up to 4 SQLite connections. Reading the event list then no longer waits behind incoming events, and incoming events no longer wait behind a long list. ```yaml database: dsn: /data/buggregator.db max_open_conns: 4 # default ``` Or `DATABASE_MAX_OPEN_CONNS=4`. - Set it to `1` for the behaviour before v2.6.0: one connection for everything. - An in-memory database (`:memory:`) always uses one connection, whatever you set. - With more than one connection, Buggregator adds `_pragma=busy_timeout(10000)` and `_txlock=immediate` to the DSN when they are missing, so two writes wait for each other instead of failing. - The pool pays off in SQLite's WAL mode, where reads and the write do not block each other. Buggregator does not turn WAL on for a file database; add it to the DSN yourself: ```bash DATABASE_DSN='file:/data/buggregator.db?_pragma=journal_mode(WAL)' ``` ## Attachment Storage SMTP attachments and HTTP dump files are stored separately from the database. Two modes are available: | Mode | Environment Variable | Description | |------|---------------------|-------------| | `memory` (default) | `STORAGE_MODE=memory` | Stored in RAM. Fast but lost on restart. | | `filesystem` | `STORAGE_MODE=filesystem` | Stored on disk in the directory specified by `STORAGE_PATH`. | ```yaml storage: mode: filesystem path: ./storage ``` > **Tip:** If you use `DATABASE_DSN=:memory:` but `STORAGE_MODE=filesystem`, the event metadata will be lost on > restart but the attachment files will remain on disk (orphaned). For consistency, either persist both or > keep both in memory. ## Migrations Buggregator automatically creates and migrates database tables on startup. No manual migration steps are required. --- # Configuration — Helm Chart Deploy Buggregator on Kubernetes using the official Helm chart. The chart deploys a single Go binary with an embedded SQLite database — no external dependencies required. ## Prerequisites - Kubernetes 1.23+ - Helm 3.x ## Installation ### Standalone (default) The simplest setup — uses embedded SQLite, no external dependencies: ```bash helm install buggregator oci://ghcr.io/buggregator/helm-chart/buggregator ``` Open the web UI: ```bash kubectl port-forward svc/buggregator 8000:8000 ``` Then navigate to http://localhost:8000. ### With SSO Enable SSO to restrict access to the web UI. Supported providers: Auth0, Google, GitHub, Keycloak, GitLab, and generic OIDC. ```bash helm install buggregator oci://ghcr.io/buggregator/helm-chart/buggregator \ --set auth.enabled=true \ --set auth.provider=auth0 \ --set auth.providerUrl=https://your-tenant.auth0.com \ --set auth.clientId=YOUR_CLIENT_ID \ --set auth.clientSecret=YOUR_CLIENT_SECRET \ --set auth.callbackUrl=https://buggregator.example.com/auth/sso/callback \ --set auth.jwtSecret=YOUR_JWT_SECRET ``` For detailed SSO configuration, see the [SSO guide](./sso.md). ### With Ingress Expose the web UI via an Ingress controller: ```bash helm install buggregator oci://ghcr.io/buggregator/helm-chart/buggregator \ --set ingress.enabled=true \ --set ingress.className=nginx \ --set 'ingress.hosts[0].host=buggregator.example.com' \ --set 'ingress.hosts[0].paths[0].path=/' \ --set 'ingress.hosts[0].paths[0].pathType=Prefix' ``` With TLS (using cert-manager): ```yaml ingress: enabled: true className: nginx annotations: cert-manager.io/cluster-issuer: letsencrypt-prod hosts: - host: buggregator.example.com paths: - path: / pathType: Prefix tls: - secretName: buggregator-tls hosts: - buggregator.example.com ``` ## Connecting your application Once deployed, configure your application to send data to Buggregator using the Kubernetes service name. Assuming the release is named `buggregator` in the `default` namespace: ```dotenv # Sentry SENTRY_LARAVEL_DSN=http://sentry@buggregator.default.svc:8000/1 # Ray RAY_HOST=buggregator.default.svc RAY_PORT=8000 # SMTP MAIL_MAILER=smtp MAIL_HOST=buggregator.default.svc MAIL_PORT=1025 # VarDumper VAR_DUMPER_FORMAT=server VAR_DUMPER_SERVER=buggregator.default.svc:9912 # Monolog (SocketHandler) LOG_CHANNEL=socket LOG_SOCKET_URL=buggregator.default.svc:9913 ``` If your application runs in the same namespace, you can use the short service name `buggregator` instead of the FQDN. ## Prometheus Metrics Enable metrics and create a ServiceMonitor for automatic scraping: ```yaml metrics: serviceMonitor: enabled: true interval: 30s ``` ## Using Existing Secrets For production environments, store sensitive values in pre-created Kubernetes secrets: ```bash # Create secrets kubectl create secret generic buggregator-auth \ --from-literal=client-id=YOUR_CLIENT_ID \ --from-literal=client-secret=YOUR_CLIENT_SECRET # Reference them in values helm install buggregator oci://ghcr.io/buggregator/helm-chart/buggregator \ --set auth.existingSecret=buggregator-auth ``` ## Storage The chart creates a PersistentVolumeClaim for data persistence (SQLite database, attachments). To customize: ```yaml storage: enabled: true size: 10Gi storageClassName: fast-ssd ``` Disable if you don't need persistent storage (data will be lost on pod restart): ```yaml storage: enabled: false ``` ## Full Configuration Reference | Parameter | Description | Default | |------------------------------------|----------------------------------------------|------------------------------| | `replicaCount` | Number of replicas | `1` | | `image.repository` | Container image | `ghcr.io/buggregator/server` | | `image.tag` | Image tag (defaults to appVersion) | `""` | | `auth.enabled` | Enable SSO | `false` | | `auth.provider` | SSO provider | `auth0` | | `auth.providerUrl` | Provider URL | `""` | | `auth.clientId` | OAuth client ID | `""` | | `auth.clientSecret` | OAuth client secret | `""` | | `auth.callbackUrl` | OAuth callback URL | `""` | | `auth.scopes` | OAuth scopes | `openid,email,profile` | | `auth.existingSecret` | Existing secret for auth | `""` | | `supportedEvents` | Enabled event types | all | | `service.type` | Service type | `ClusterIP` | | `service.httpPort` | Web UI port | `8000` | | `service.smtpPort` | SMTP port | `1025` | | `service.varDumperPort` | VarDumper port | `9912` | | `service.monologPort` | Monolog port | `9913` | | `ingress.enabled` | Enable Ingress | `false` | | `storage.enabled` | Enable PVC | `true` | | `storage.size` | PVC size | `5Gi` | | `metrics.serviceMonitor.enabled` | Enable ServiceMonitor | `false` | ## Uninstall ```bash helm uninstall buggregator ``` > **Note:** The PVC is not deleted automatically. To remove it: > ```bash > kubectl delete pvc buggregator-storage > ``` --- # HTTP Dumps — Request Inspection Your app calls external APIs, sends webhooks, or receives callbacks — and you need to see exactly what goes over the wire. Buggregator captures full HTTP requests: method, URI, headers, cookies, POST data, and uploaded files. Each request also comes as a cURL command you can copy. No need to set up a separate service like webhook.site — it's built into the same Buggregator where you already see your logs and exceptions. > **Need to see responses too?** Use the [HTTP Proxy](/config/http-proxy) — it captures both request and response > by acting as a forward proxy between your app and external services. > **Need to answer the request too?** Use the [Mock Server](/config/mock-server) — requests to `/mock/...` get a > response you define, and each one is captured here as an HTTP dump. ![HTTP dumps](/images/http-dumps.webp) ## Use cases - **Webhook development** — build a webhook endpoint and see exactly what the other service sends you. - **API debugging** — redirect outgoing HTTP calls to Buggregator to inspect request structure before hitting the real API. - **All in one place** — HTTP requests alongside exceptions, logs, and dumps in the same dashboard. ## What you see in the UI - **HTTP method** — GET, POST, PUT, DELETE, PATCH, etc. (color-coded). - **Full URI** — complete request URL with path segments. - **Query parameters** — parsed URL query parameters. - **POST/form data** — submitted fields and values. - **Headers** — all request headers. - **Cookies** — cookies sent with the request. - **Uploaded files** — attached files, available for download. - **cURL command** — the request written as a `curl` command, with a copy button. ## Configuration Send any HTTP request to Buggregator and mark it as a dump. Two ways: ### Using HTTP auth Add `http-dump` to the URL username: ```bash curl 'http://http-dump@127.0.0.1:8000/any/path?foo=bar' ``` ### Using header Add the `X-Buggregator-Event` header: ```bash curl 'http://127.0.0.1:8000/any/path?foo=bar' \ --header 'X-Buggregator-Event: http-dump' ``` > In Docker Compose, replace `127.0.0.1` with the Buggregator service name (e.g., `buggregator`). --- # HTTP Proxy — Request & Response Capture Your app calls external APIs — payment gateways, webhooks, third-party services — and you need to see both what you send **and** what you get back. Buggregator's HTTP proxy sits between your app and the internet, capturing full request/response pairs without changing your application code. Just point your HTTP client at the proxy. > **Looking for one-way request capture?** See [HTTP Dumps](/config/http-dumps) — it captures incoming requests > without proxying to a real server. ## Use cases - **API debugging** — see exactly what your app sends to Stripe, Twilio, or any external API, and what comes back. - **Webhook testing** — send webhooks through the proxy to inspect both the outgoing payload and the remote server's response. - **Response inspection** — view response bodies with syntax highlighting (JSON, HTML, XML) and an interactive JSON tree view. - **Performance monitoring** — see response times for every external call your app makes. - **No code changes** — configure the proxy at the HTTP client level; your application logic stays untouched. ## What you see in the UI Proxied requests appear as HTTP dump events with additional data: - **Full URL** — the complete destination URL including host and port. - **Request and response** — headers, body, and status code for both directions. - **Status code** — color-coded badge (green for 2xx, amber for 4xx, red for 5xx). - **Response time** — duration in milliseconds. - **Proxy label** — purple badge to distinguish proxied requests from regular HTTP dumps. - **Response body viewer** — JSON tree view with collapsible nodes, HTML preview in a sandboxed iframe, syntax highlighting for XML/CSS/JS. - **Tab navigation** — Response, Request, and Raw tabs on the detail page. ## Configuration The proxy listens on port **8080** by default. Configure it via environment variable or config file: ```dotenv PROXY_ADDR=:8080 ``` ```yaml # buggregator.yaml tcp: proxy: addr: ":8080" ``` In Docker Compose, expose the port: ```yaml services: buggregator: image: ghcr.io/buggregator/server:latest ports: - "8000:8000" # UI + API - "8080:8080" # HTTP Proxy ``` ## Client setup Point your HTTP client at `http://:8080` as a proxy. For HTTPS traffic, disable SSL certificate verification — the proxy uses an in-memory CA to intercept TLS connections. This is safe for development. > In Docker Compose, replace `127.0.0.1` with the Buggregator service name (e.g., `buggregator`). ### PHP — Guzzle ```php use GuzzleHttp\Client; $client = new Client([ 'proxy' => 'http://127.0.0.1:8080', 'verify' => false, ]); $response = $client->get('https://api.example.com/users'); ``` ### PHP — Laravel HTTP Client ```php use Illuminate\Support\Facades\Http; $response = Http::withOptions([ 'proxy' => 'http://127.0.0.1:8080', 'verify' => false, ])->get('https://api.example.com/users'); ``` To configure globally for all HTTP calls in development, add a macro in `AppServiceProvider`: ```php // app/Providers/AppServiceProvider.php use Illuminate\Support\Facades\Http; public function boot(): void { if ($this->app->isLocal()) { Http::globalOptions([ 'proxy' => env('BUGGREGATOR_PROXY_URL', 'http://127.0.0.1:8080'), 'verify' => false, ]); } } ``` ```dotenv BUGGREGATOR_PROXY_URL=http://buggregator:8080 ``` ### PHP — Symfony HttpClient ```php use Symfony\Component\HttpClient\HttpClient; $client = HttpClient::create([ 'proxy' => 'http://127.0.0.1:8080', 'verify_peer' => false, 'verify_host' => false, ]); $response = $client->request('GET', 'https://api.example.com/users'); ``` ### Go ```go import ( "crypto/tls" "net/http" "net/url" ) proxyURL, _ := url.Parse("http://127.0.0.1:8080") client := &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyURL(proxyURL), TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, }, } resp, err := client.Get("https://api.example.com/users") ``` ### JavaScript / Node.js — fetch ```js import { ProxyAgent } from 'undici' const agent = new ProxyAgent({ uri: 'http://127.0.0.1:8080', requestTls: { rejectUnauthorized: false }, }) const response = await fetch('https://api.example.com/users', { dispatcher: agent, }) ``` ### JavaScript / Node.js — axios ```js import axios from 'axios' import { HttpsProxyAgent } from 'https-proxy-agent' const agent = new HttpsProxyAgent('http://127.0.0.1:8080', { rejectUnauthorized: false, }) const response = await axios.get('https://api.example.com/users', { httpsAgent: agent, }) ``` ### Python — requests ```python import requests response = requests.get( 'https://api.example.com/users', proxies={'https': 'http://127.0.0.1:8080'}, verify=False, ) ``` ### Python — httpx ```python import httpx client = httpx.Client( proxy='http://127.0.0.1:8080', verify=False, ) response = client.get('https://api.example.com/users') ``` ### curl ```bash curl -x http://127.0.0.1:8080 -k https://api.example.com/users ``` ### Environment variables (any language) Most HTTP clients respect standard proxy environment variables: ```bash export HTTP_PROXY=http://127.0.0.1:8080 export HTTPS_PROXY=http://127.0.0.1:8080 export NODE_TLS_REJECT_UNAUTHORIZED=0 # Node.js only # Then run your app normally node app.js python main.py go run . ``` > **Note:** `NODE_TLS_REJECT_UNAUTHORIZED=0` disables TLS verification globally for Node.js processes. > Use it only in development. ## How it works 1. Your app sends a request to the proxy (`http://127.0.0.1:8080`). 2. For HTTPS, the proxy performs a CONNECT handshake, generates a TLS certificate for the target host on the fly (signed by an in-memory CA), and establishes a TLS connection with your app. 3. The proxy forwards the request to the real destination server. 4. The full request and response are captured and stored as an `http-dump` event with a `proxy: true` flag, response data, and timing information. 5. The event appears in the Buggregator UI in real time via WebSocket. The in-memory CA is generated at server startup and never written to disk. Your client skips certificate verification (`InsecureSkipVerify`, `verify: false`, `-k`), so no CA installation is required. ## Docker Compose example ```yaml services: buggregator: image: ghcr.io/buggregator/server:latest ports: - "8000:8000" - "8080:8080" app: build: . environment: BUGGREGATOR_PROXY_URL: http://buggregator:8080 depends_on: - buggregator ``` --- # Inspector — Application Monitoring You want to see how long your requests take, where the bottlenecks are, and how much memory each transaction consumes — but [Inspector.dev](https://inspector.dev/) is overkill for local development. Buggregator accepts the same Inspector SDK protocol, so your transaction and performance data lands in the same UI where you already see exceptions, logs, and dumps. ![Inspector transaction](/images/inspector.webp) ## Use cases - **Local APM** — monitor request duration and memory usage without sending data to external services. - **Debug slow requests** — use the timeline breakdown to see which parts of a request are slow. - **All in one place** — transaction data next to exceptions, logs, and dumps from the same app. ## What you see in the UI - **Transaction name** — the name of the monitored transaction. - **Duration** — execution time in milliseconds. - **Memory peak** — peak memory usage. - **Result status** — success, error, etc. - **Transaction type** — HTTP request, process, etc. - **HTTP details** — method, URI, host (for HTTP transactions). - **Timeline breakdown** — visual timeline of events within the transaction. ## Configuration ### Laravel Install the SDK: [docs.inspector.dev/laravel](https://docs.inspector.dev/laravel) ```dotenv INSPECTOR_URL=http://inspector@127.0.0.1:8000 INSPECTOR_API_KEY=test INSPECTOR_INGESTION_KEY=1test INSPECTOR_ENABLE=true ``` > In Docker Compose: `INSPECTOR_URL=http://inspector@buggregator:8000` ### Other PHP Using `inspector-apm/inspector-php`: ```php use Inspector\Inspector; use Inspector\Configuration; $configuration = new Configuration('YOUR_INGESTION_KEY'); $configuration->setUrl('http://inspector@127.0.0.1:8000'); $inspector = new Inspector($configuration); ``` Other language SDKs: [docs.inspector.dev](https://docs.inspector.dev/) ## Secret key validation To restrict access, set a secret key on the server: ```bash docker run --pull always \ -p 127.0.0.1:8000:8000 \ -e INSPECTOR_SECRET_KEY=my-secret-key \ ghcr.io/buggregator/server:latest ``` Then use the key as the ingestion key in your client: **Laravel:** ```dotenv INSPECTOR_INGESTION_KEY=my-secret-key ``` **PHP:** ```php $configuration = new Configuration('my-secret-key'); $configuration->setUrl('http://inspector@127.0.0.1:8000'); ``` --- # Configuration — MCP (Model Context Protocol) Buggregator includes a built-in [MCP](https://modelcontextprotocol.io/) server that lets AI assistants query your debugging data directly. Connect Claude Code, Cursor, or any MCP-compatible client to browse events, inspect errors, analyze profiling data, and read variable dumps — without leaving your editor. ## Enabling MCP MCP is disabled by default. Enable it in `buggregator.yaml`: ```yaml mcp: enabled: true ``` Or via environment variable: ```bash MCP_ENABLED=true ``` ## Transport Modes ### Unix Socket (Default) The server listens on a Unix domain socket. This is the recommended mode for local development. ```yaml mcp: enabled: true transport: socket socket_path: /tmp/buggregator-mcp.sock ``` | Variable | Default | Description | |----------|---------|-------------| | `MCP_TRANSPORT` | `socket` | Transport type | | `MCP_SOCKET_PATH` | `/tmp/buggregator-mcp.sock` | Unix socket path | ### HTTP/SSE For remote access or when Unix sockets are not available, use HTTP transport: ```yaml mcp: enabled: true transport: http addr: ":8001" auth_token: my-secret-token # Optional bearer token ``` | Variable | Default | Description | |----------|---------|-------------| | `MCP_TRANSPORT` | `socket` | Set to `http` | | `MCP_ADDR` | `:8001` | HTTP listen address | | `MCP_AUTH_TOKEN` | — | Bearer token for authentication (optional) | When `MCP_AUTH_TOKEN` is set, all requests must include the `Authorization: Bearer ` header. ## Integration with AI Assistants ### Claude Code Add to your `.mcp.json` or configure via Claude Code settings: ```json { "mcpServers": { "buggregator": { "type": "stdio", "command": "buggregator", "args": ["mcp"] } } } ``` Or from the command line: ```bash claude mcp add buggregator -- buggregator mcp ``` The `buggregator mcp` subcommand bridges stdio to the running Buggregator instance via the Unix socket. `command` is the path to the binary: `buggregator` when it is on your `PATH`, else the full path. > **Note:** Make sure Buggregator is running with MCP enabled before connecting. If Buggregator runs in Docker, you can use the HTTP transport instead: ```json { "mcpServers": { "buggregator": { "type": "http", "url": "http://localhost:8001/mcp" } } } ``` Or add it from the command line: ```bash claude mcp add --transport http buggregator http://localhost:8001/mcp ``` With `MCP_AUTH_TOKEN` set, pass the token as a header: ```json { "mcpServers": { "buggregator": { "type": "http", "url": "http://localhost:8001/mcp", "headers": { "Authorization": "Bearer my-secret-token" } } } } ``` The same from the command line: ```bash claude mcp add --transport http buggregator http://localhost:8001/mcp \ --header "Authorization: Bearer my-secret-token" ``` Without the header, the server answers `401`. ### Cursor In Cursor settings, add the MCP server: - **Command:** `buggregator mcp` - Or use the HTTP URL: `http://localhost:8001/mcp` ### Docker Setup When running Buggregator in Docker with MCP enabled: ```yaml services: buggregator: image: ghcr.io/buggregator/server:latest ports: - 127.0.0.1:8000:8000 - 127.0.0.1:8001:8001 # MCP HTTP port environment: MCP_ENABLED: "true" MCP_TRANSPORT: http MCP_ADDR: ":8001" ``` ## Available Tools MCP clients can use the following tools to query Buggregator data: ### Event Management | Tool | Description | |------|-------------| | `events_list` | List events with optional filtering by type and project. Returns metadata (uuid, type, timestamp, project) without payloads. Supports `limit` parameter (default 20, max 100). | | `event_get` | Get a complete event by UUID, including the full payload. | | `event_delete` | Delete an event by UUID. | ### Sentry | Tool | Description | |------|-------------| | `sentry_event` | Get structured details of a Sentry error: message, severity, exception chain with stack traces, environment, platform. Returns clean, AI-friendly data. | ### VarDumper | Tool | Description | |------|-------------| | `vardump_get` | Get a variable dump with HTML stripped for clean AI consumption. Returns variable type, label, and plain text representation. | ### Profiler | Tool | Description | |------|-------------| | `profiler_summary` | Quick overview: total CPU/wall time/memory, slowest function, biggest memory consumer, most called function. | | `profiler_top` | Top functions sorted by metric (cpu, wt, mu, pmu, ct, and their exclusive variants). Returns inclusive and exclusive metrics with percentages. | | `profiler_call_graph` | Filtered call graph showing function relationships. Use `threshold` and `percentage` to control which nodes are shown. | ### Mock server Tools for the [mock server](/config/mock-server) rules. Details and an example flow: [Response templates → MCP tools](/config/mock-templates#mcp-tools-for-ai-agents). | Tool | Description | |------|-------------| | `mock_rules_list` | The rules in matching order: config rules first (read-only), then stored ones. | | `mock_rule_get` | One rule with its full body. | | `mock_rule_preview` | Runs a rule against a sample request without saving it: status, headers, body, `matched`, `error`. | | `mock_requests_list` | Requests the mock server got, newest first, with the rule that answered. | | `mock_template_helpers` | Template helpers and fake data generators with their parameters. | | `mock_rule_create` | Creates a rule. | | `mock_rule_update` | Changes a stored rule; only the given fields change. | | `mock_rule_delete` | Deletes a stored rule. | | `mock_rule_from_request` | Creates a rule from a captured request (e.g. one that got `404`). | | `mock_import_openapi` | Imports an OpenAPI 3.0/3.1 spec: one rule per operation, in one group. | | `mock_group_delete` | Deletes all stored rules of a group. | The last six change rules. They are on by default; `mcp.mock_write: false` (env `MCP_MOCK_WRITE=false`) leaves only the first five. ```yaml mcp: enabled: true mock_write: false ``` ### Xdebug With the [Xdebug proxy](/config/xdebug) on (`xdebug.enabled: true`), MCP clients also get these tools. The first six read a paused session, `xdebug_breakpoints` lists breakpoints; only `xdebug_eval` (off unless `xdebug.allow_eval: true`) runs code. While an IDE drives the session, stepping and continuing stay in the IDE. | Tool | Description | |------|-------------| | `xdebug_sessions` | List debug sessions, including ones closed in the last 10 minutes. A session can be read only while it is paused (state `break`). | | `xdebug_location` | Current file and line, the function it is in, and the source lines around it. | | `xdebug_stack` | The call stack, one frame per level; `0` is the current frame. | | `xdebug_variables` | Variables of a frame: locals by default (`context_id` `1` = superglobals, `2` = constants). Arrays and objects show their first level. | | `xdebug_property` | One variable or property by its full name (`$user`, `$user->address`, `$items[0]`) with its children. Long strings up to 64 KB. | | `xdebug_eval` | The value of a PHP expression in the current frame. Present only with `xdebug.allow_eval: true`: the code really runs inside the debugged request. | | `xdebug_wait` | Waits until a session pauses (up to 60 s). | | `xdebug_step` | One step (`mode` `over`, `into`, `out`); waits for the next pause and returns where the script stopped. | | `xdebug_continue` | Runs to the next breakpoint or `xdebug_break()`; same answer as `xdebug_step`. | | `xdebug_stop` | `mode` `detach` (default, the script runs to the end) or `stop` (ends the request now). | | `xdebug_breakpoints` | The saved breakpoints; with `session_id`, their state and hit count in that session. | | `xdebug_breakpoint_set` | Saves a breakpoint: `file` + `line`, or `exception`; `condition` only with `allow_eval`. | | `xdebug_breakpoint_remove` | Removes a saved breakpoint by `id`. | `xdebug_wait`, `xdebug_step`, `xdebug_continue`, `xdebug_stop`, `xdebug_breakpoint_set` and `xdebug_breakpoint_remove` drive a session that has no IDE ([Debug without an IDE](/config/xdebug#debug-without-an-ide)). They are left out with `xdebug.allow_control: false`; stepping is refused while an IDE drives. `session_id` can be left out when exactly one session is paused. More in [Xdebug → MCP tools](/config/xdebug#mcp-tools). ### Example Usage in Claude Code Once connected, you can ask your AI assistant things like: - "Show me the latest Sentry errors" - "What's the stack trace for this exception?" - "Analyze the profiling data and find the slowest functions" - "What value was dumped in the last VarDumper event?" --- # Configuration — Metrics Buggregator collects metrics on how many events it receives. This feature lets you use tools like Prometheus and Grafana to check on event trends, find issues, and set up alerts. The metrics system keeps track of how many events Buggregator receives, sorted by their types: sentry, monolog, var-dumper, ray, inspector, http-dump, profiler, and smtp. HTTP request metrics, WebSocket connection gauges, and webhook delivery attempts are also tracked. ### How It Works 1. **Event Counting:** Each time an event is received, it's counted and sorted into its type. 2. **Metric Updating:** The system updates the metrics to show the latest counts for each event type. ## Enabling Metrics Metrics are disabled by default. Enable them via environment variable or config file: ```bash METRICS_ENABLED=true ``` Or in `buggregator.yaml`: ```yaml metrics: enabled: true ``` ## Prometheus Endpoint There are two ways to expose the Prometheus endpoint: ### Option 1: On the Main HTTP Server (Default) When `METRICS_ADDR` is not set, metrics are served at `/metrics` on the main HTTP server (port 8000 by default): ```bash docker run --pull always \ -p 127.0.0.1:8000:8000 \ -e METRICS_ENABLED=true \ ghcr.io/buggregator/server:latest ``` Access metrics at `http://127.0.0.1:8000/metrics`. > **With SSO on**, `/metrics` on the main port stays open: Prometheus scrapes it without a login. It shows only > counters and gauges (event counts by type, HTTP requests, connections), no event content. To keep it off the > public port, set `metrics.addr` (Option 2) and do not publish that port. The JSON for the UI dashboard, > `/api/metrics`, needs a login token when SSO is on. ### Option 2: On a Separate Server For production environments where you want to keep metrics on a separate port: ```yaml metrics: enabled: true addr: ":9090" ``` Or via environment variable: ```bash docker run --pull always \ -p 127.0.0.1:8000:8000 \ -p 127.0.0.1:9090:9090 \ -e METRICS_ENABLED=true \ -e METRICS_ADDR=:9090 \ ghcr.io/buggregator/server:latest ``` Access metrics at `http://127.0.0.1:9090/metrics`. ## Metric Format Here is what the metric format looks like: ```plaintext # HELP events The total number of received events. # TYPE events counter events{type="sentry"} 10 events{type="smtp"} 1 ``` Each line shows how many events of a specific type have been received. ## Grafana Integration You can use these metrics to make dashboards in Grafana. This helps you see the data in a way that makes sense for you. ### Setting Up Grafana 1. **Add Prometheus as a Data Source:** First, connect Prometheus (which scrapes your Buggregator metrics) to Grafana. 2. **Create Dashboards:** Next, create dashboards in Grafana to show the metrics. You can make graphs and charts that help you understand the event trends. --- # Mock Server — Fake API Responses Your app calls an API that is not ready yet, is slow, or costs money per call. You want it to answer with a fixed response, and you want to see what your app sent. The mock server does both. You describe a response once: method and path in, status, headers and body out. Your app calls Buggregator instead of the real API. Every call is also captured as an [HTTP dump](/config/http-dumps), so you see the request and the response that was sent next to your logs and exceptions. > Available since server v2.6.0. The **Mock server** page needs frontend 1.35.0, which is bundled with v2.6.0. ## Use cases - **API not ready yet** — the frontend team builds against `/mock/users/{id}` while the backend is still in progress. - **Error handling** — make a rule that answers `500` or `429` and check how your app reacts. - **Slow responses** — add a delay to test timeouts and loading states. - **CI** — put the rules in `buggregator.yaml`, so every test run gets the same answers. - **Realistic data** — a [template rule](/config/mock-templates) copies the id from the path and fills in fake names, emails and prices for each request. ## How it works Point your client at `http://127.0.0.1:8000/mock/`. Write rule paths without the `/mock` prefix. For example, the rule `GET /users/{id}` answers `GET http://127.0.0.1:8000/mock/users/42`. ```bash curl http://127.0.0.1:8000/mock/users/42 # {"id": 1, "name": "Jane"} ``` > In Docker Compose, replace `127.0.0.1` with the Buggregator service name (e.g., `buggregator`). The mock server lives only under `/mock/`. A rule can never hide SDK ingestion, `/api/...` or the UI. The mock server is part of the HTTP dumps module. If you turn that module off (`modules.http-dump: false`), `/mock/` is off too. ### Which rule answers Buggregator checks the rules in order. The first enabled rule that matches answers. 1. Rules from `buggregator.yaml` come first, in file order. They are read-only. 2. Rules made in the UI or through the API come next, in the order you set. A rule matches when all of these fit: | Condition | Values | |-----------|--------| | **Method** | `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`, or `ANY` (the default) | | **Path** | see the path forms below | | **Project** | empty means every project; otherwise it must be the request's project | | **Enabled** | a disabled rule never answers | ### Path forms | Form | Example rule | Matches | Does not match | |------|--------------|---------|----------------| | Exact | `/users/me` | `/mock/users/me` | `/mock/users/42` | | One segment | `/users/{id}` | `/mock/users/42` | `/mock/users/42/orders` | | The rest | `/files/*` | `/mock/files`, `/mock/files/a/b.png` | `/mock/images/a.png` | - `*` is allowed only as the whole last segment. - A trailing slash is ignored. The query string is ignored. ### No rule matched The mock server answers `404` with a JSON error: ```json {"error": "no mock rule matched GET /users/42"} ``` The request is still captured. In the request details you see the rules whose path fits but that missed by one condition, and why: `disabled`, `method` or `project`. Example: you made `POST /orders` but the app sent `GET`. The details then show that rule with the reason `method`. ### Projects A request belongs to the `default` project unless it says otherwise. Two ways to set a project: ```bash # Header curl http://127.0.0.1:8000/mock/users/42 -H 'X-Buggregator-Project: shop' # Basic Auth with the user name "mock" (or "http-dump") curl http://mock:shop@127.0.0.1:8000/mock/users/42 ``` Other Basic Auth credentials are left alone: they belong to the API you mock. ### What every response carries Mock bodies are your own content, served from the same address as the Buggregator UI. To keep the UI safe, every mock response gets two headers that a rule cannot remove: ``` Content-Security-Policy: sandbox X-Content-Type-Options: nosniff ``` A `Set-Cookie` header from a rule stays inside the mock server. Buggregator removes its `Domain` and puts its `Path` under `/mock`. Example: `sid=1; Path=/; Domain=example.com` is sent as `sid=1; Path=/mock/`. ### CORS preflight A browser may send an `OPTIONS` request before the real one (a CORS preflight). An `OPTIONS` rule answers it. Without such a rule, Buggregator answers `204` with the CORS headers, and the request is captured as unmatched. ### Limits | Field | Limit | |-------|-------| | `status` | 100–599, default `200` | | delay | up to 30 seconds | | `body` | up to 1 MB | | header names | no spaces, no `:` | | stored rules | at most 500 per project; rule 501 gets `422` with `errors.project` | ## The Mock server page Open **Mock server** in the sidebar. - **Rules** on the left, in match order. Rules from `buggregator.yaml` are marked `yaml`. You can open them and duplicate them as editable rules, but not change them. - Your own rules can be switched on and off, moved up and down, and edited. - **Requests** on the right: calls to `/mock/` of the current project, live. - Click a request to see what was sent and what came back. For an unmatched request, the page lists the rules that almost matched and offers to create a rule from that request. ## Rules in `buggregator.yaml` Rules in the config file suit CI and shared setups: everyone gets the same answers. ```yaml mocks: - name: user # optional method: GET # GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS or ANY (default) path: /users/{id} status: 200 # default 200 headers: { Content-Type: application/json } body: '{"id": 1, "name": "Jane"}' delay: 150ms # optional, a Go duration, at most 30s project: default # optional; empty = every project ``` - These rules are always enabled and read-only in the UI. - An invalid rule is skipped at startup, with a warning in the log. - A `delay` that is not a duration (e.g. `150` without a unit) is ignored, with a warning. See [Server configuration](/config/server) for where the file goes. ::: v-pre ## Import an OpenAPI spec Have an OpenAPI 3.0 or 3.1 spec? Import it, and every operation becomes a rule. Example: a spec with `GET /users/{id}` and `POST /orders` gives two rules, and `/mock/v1/users/42` answers at once. How a rule is built: - **One rule per operation**, all in one group. The rule's name is the `operationId`, else the `summary`, else the method and the full path, base path included: `GET /v1/users/{id}`. - **Status**: the lowest `2xx` response of the operation. - **Body**: the spec's `example`, as is. No example: a [template](/config/mock-templates) built from the schema, with fake data. A root field named like a path parameter echoes it (`id` for the last one). - **Path**: the path of `servers[0].url` goes in front. `https://api.example.com/v1` + `/users/{id}` → `/v1/users/{id}`. Set `base_path` to change it; `""` means no prefix. - **Import again** into the same group, and the group's old rules are replaced. - Local `$ref` only. `oneOf` and `anyOf` take the first option. Swagger 2.0 is refused: convert it to OpenAPI 3. The rules are ordinary rules: edit them afterwards like any other. Import a spec: ```bash curl -X POST http://127.0.0.1:8000/api/mocks/import/openapi \ -H 'Content-Type: application/json' \ -d "$(jq -n --rawfile spec shop.yaml '{spec: $spec}')" ``` With this `shop.yaml`: ```yaml openapi: 3.0.3 info: { title: Shop API, version: "1.0" } servers: - url: https://api.example.com/v1 paths: /users/{id}: get: parameters: - { name: id, in: path, required: true, schema: { type: integer } } responses: "200": description: A user content: application/json: schema: type: object properties: id: { type: integer } name: { type: string } email: { type: string, format: email } status: { type: string, enum: [active, banned] } /orders: post: responses: "201": description: Created content: application/json: example: { id: 1001, status: pending } ``` The answer lists the rules (cut here) and the operations it skipped: ```json {"group": "openapi:Shop API", "title": "Shop API", "rules": [ {"name": "GET /v1/users/{id}", "method": "GET", "path": "/v1/users/{id}", "status": 200, "template": true, "body": "{\n \"id\": {{ int (path \"id\") }},\n \"name\": {{ fake \"name\" | json }},\n \"email\": {{ fake \"email\" | json }},\n \"status\": {{ pick \"active\" \"banned\" | json }}\n}", …}, {"name": "POST /v1/orders", "method": "POST", "path": "/v1/orders", "status": 201, "template": false, "body": "{\n \"id\": 1001,\n \"status\": \"pending\"\n}", …}], "skipped": []} ``` Then: ```bash curl http://127.0.0.1:8000/mock/v1/users/42 # {"id": 42, "name": "Alden Vaughn", "email": "troy-hart@ramirez.net", "status": "active"} curl -X POST http://127.0.0.1:8000/mock/v1/orders # {"id": 1001, "status": "pending"} (status 201) ``` (Bodies come indented; shown here on one line.) Request fields: | Field | What it does | |-------|--------------| | `spec` | The spec text, YAML or JSON | | `url` | Or the spec's address: `http`/`https`, at most 5 MB, downloaded within 10 s | | `project` | The rules' project; empty = every project. A project that does not exist yet is fine: it is created by its first event | | `group` | The group name; default `openapi:` | | `base_path` | The prefix for every path; default: the path of `servers[0].url`; `""` = none | Answer fields: `group`, `title`, `rules` (the created rules), `skipped` (a list of `method`, `path`, `reason`). An operation is skipped, for example, when one import builds more than 500 rules (`reason`: `over 500 rules`). A project holds at most 500 stored rules. When the import would take it over, the whole import is refused and nothing is added: `422`, `errors.project`: `the import adds 2 rules, the project has 499; at most 500 rules per project`. Errors are `422`, the field in `errors`: | Case | `errors` | |------|----------| | neither `spec` nor `url` | `{"spec": "give the spec text or its url"}` | | both | `{"spec": "give spec or url, not both"}` | | Swagger 2.0 | `{"spec": "Swagger 2.0 is not supported; convert it to OpenAPI 3"}` | | not OpenAPI | `{"spec": "not an OpenAPI 3 document (no openapi: 3.x)"}` | | `url` not http(s) | `{"url": "url must be http or https"}` | | download failed | `{"url": "download: raw.githubusercontent.com answered 404"}` | Delete a group (the name URL-encoded): ```bash curl -X DELETE 'http://127.0.0.1:8000/api/mocks/groups/openapi%3AShop%20API' # {"deleted":2} ``` ### A spec in `buggregator.yaml` ```yaml mocks_openapi: - file: ./shop.yaml project: shop # optional; empty = every project group: shop-api # optional; default openapi: base_path: "" # optional; "" = no prefix ``` The spec is read at startup; the log says `mock: OpenAPI spec loaded` with the file, group and rule count. These rules are read-only, like other config rules (`"source": "config"`, ids `config-1`, …): changing or deleting one gets `409`. AI agents import with the MCP tool `mock_import_openapi` and delete a group with `mock_group_delete`, see [MCP tools](/config/mock-templates#mcp-tools-for-ai-agents). ::: ## REST API All routes need the same login as the rest of `/api` when [SSO](/config/sso) is on. The mock server itself (`/mock/...`) is always public: the clients of the mocked API call it. A rule looks like this: ```json { "id": "f5171e15-2599-4c33-949b-7f7ecc05ab20", "project": "", "name": "user", "method": "GET", "path": "/users/{id}", "status": 200, "headers": {"Content-Type": "application/json"}, "body": "{\"id\": 1}", "delay_ms": 100, "template": false, "seed": 0, "group": "", "enabled": true, "position": 0, "source": "api", "read_only": false, "created_at": "2026-11-06T18:30:09Z", "updated_at": "2026-11-06T18:30:09Z" } ``` Rules from the config file have `"source": "config"`, `"read_only": true` and ids `config-1`, `config-2`, … | Method | Path | Body | Answer | |--------|------|------|--------| | `GET` | `/api/mocks` | — | `{"data": [rule, …]}` in match order | | `POST` | `/api/mocks` | rule fields; `path` is required | `201` and the rule, added at the end | | `GET` | `/api/mocks/{id}` | — | the rule, or `404` | | `PUT` | `/api/mocks/{id}` | rule fields (replaces the rule, keeps its position) | the rule; `409` for a config rule | | `DELETE` | `/api/mocks/{id}` | — | `{"status": true}`; `409` for a config rule | | `POST` | `/api/mocks/order` | `{"ids": ["…", "…"]}` | `{"data": [rule, …]}`; listed rules first, the rest keep their order; an unknown or config rule id gets `404` | | `GET` | `/api/mocks/requests?limit=50&project=&rule_id=` | — | captured mock requests, newest first; `limit` 1–500, default 50 | | `POST` | `/api/mocks/import/openapi` | `{"spec" or "url", "project", "group", "base_path"}` | `{"group", "title", "rules", "skipped"}`, see [OpenAPI import](#import-an-openapi-spec) | | `DELETE` | `/api/mocks/groups/{group}` | — | `{"deleted": n}`: the group's stored rules are gone | Defaults on create: `method` `ANY`, `status` `200`, `enabled` `true`, `template` `false`, `seed` `0`. Template rules (`template`, `seed`), `POST /api/mocks/preview` and `GET /api/mocks/helpers`: [Response templates](/config/mock-templates). Errors are `{"message", "code"}`. A rule that fails validation gets `422` with the bad fields: ```json {"message": "invalid mock rule: status: must be between 100 and 599", "code": 422, "errors": {"status": "must be between 100 and 599"}} ``` Example — create a rule: ```bash curl -X POST http://127.0.0.1:8000/api/mocks \ -H 'Content-Type: application/json' \ -d '{"method": "POST", "path": "/orders", "status": 201, "body": "{\"id\": 7}", "delay_ms": 200}' ``` ### The captured request A mock request is a normal `http-dump` event. Its payload has an extra `mock` field with what was sent: ```json "mock": { "matched": true, "rule_id": "f5171e15-…", "rule_name": "user", "status": 200, "headers": {"Content-Type": "application/json", "Content-Security-Policy": "sandbox", "X-Content-Type-Options": "nosniff"}, "body": "{\"id\": 1}", "body_size": 9, "body_truncated": false, "delay_ms": 100 } ``` - `body` keeps the first 64 KB; `body_truncated` says when it was cut. - For an unmatched request, `matched` is `false`, `rule_id` and `rule_name` are `null`, and `near` lists up to 5 rules that missed by one condition: `[{"rule_id", "rule_name", "reason"}]`. - A [template](/config/mock-templates) that failed adds `template_error` with the error text; `status` is then `500`. - Ordinary HTTP dumps have no `mock` field. --- # Mock Server — Response Templates ::: v-pre # Mock Server — Response Templates A plain [mock rule](/config/mock-server) always sends the same body. A template rule builds the body for each request. It can copy values from the request and add fake data. Example: the rule `GET /users/{id}` answers `/mock/users/42` with `{"id": 42, …}` and `/mock/users/7` with `{"id": 7, …}`, each with a made-up name. > Available since server v2.6.0. The **Mock server** page does not show the template fields yet: set them through > the [REST API](/config/mock-server#rest-api) or in [`buggregator.yaml`](#rules-in-buggregator-yaml). Every example on this page was run on a real server. The output is pasted as it came back. With fake data and no `seed`, your values will differ. ## Turn it on Two rule fields: | Field | Values | What it does | |-------|--------|--------------| | `template` | `false` (default), `true` | `true`: the body and every header value are [Go templates](https://pkg.go.dev/text/template) | | `seed` | integer, default `0` | `0`: new fake data on every request. Any other number: the same fake data on every request | With `template: false`, `{{` is sent as is. Rule body `{"id": {{ path "id" }}}` then answers `{"id": {{ path "id" }}}`. The `status` is not a template: a rule always answers with its own status code. Create a template rule: ```bash curl -X POST http://127.0.0.1:8000/api/mocks \ -H 'Content-Type: application/json' \ -d '{"method": "GET", "path": "/users/{id}", "template": true, "seed": 42, "headers": {"Content-Type": "application/json"}, "body": "{\"id\": {{ path \"id\" }}, \"name\": {{ fake \"name\" | json }}, \"email\": {{ fake \"email\" | json }}}"}' curl http://127.0.0.1:8000/mock/users/42 # {"id": 42, "name": "Jessica Hills", "email": "jonathon.marquardt@wilkinson.biz"} ``` ## Template basics Text outside `{{ … }}` is sent as is. Inside, you call a helper: its name, then its arguments, separated by spaces. Strings are in double quotes. ``` {{ path "id" }} one helper, one argument {{ fake "number" 18 90 }} two arguments ``` `|` passes a value to the next helper as its last argument. `{{ fake "name" | json }}` is the same as `{{ json (fake "name") }}`. Parentheses group a call inside another one. ### Three rules for JSON bodies 1. **Every string goes through `| json`.** It adds the quotes and escapes them inside the value. Without it, the body is not valid JSON. Request `?q=say "hi"`: | Template | Output | |----------|--------| | `{"q": {{ query "q" \| json }}}` | `{"q": "say \"hi\""}` | | `{"q": "{{ query "q" }}"}` | `{"q": "say "hi""}` (broken) | Numbers and booleans can go in as they are: `{"age": {{ fake "number" 18 90 }}}`. 2. **Request values are strings.** `path`, `query` and `header` always return text. Compare them with a string: `eq (query "page") "2"`, not `eq (query "page") 2`. 3. **Numbers from a JSON request body are decimals** (Go `float64`). Compare them with a decimal: `gt (body "amount") 100.0`. `gt (body "amount") 100` fails with `incompatible types for comparison: float64 and int`. **Need a whole number? Use `int`.** `repeat`, `add` and a comparison with a whole number need one. Wrap the request value in `int`: | Template | Request | Output | |----------|---------|--------| | `{{ range $i := repeat (int (query "limit" \| default "2")) }}…` | `?limit=3` | 3 items | | `{"qty": {{ add (int (body "qty")) 1 }}}` | body `{"qty": 2}` | `{"qty": 3}` | | `{{ if gt (int (body "amount")) 100 }}…` | body `{"amount": 250}` | the `if` part | Without `int`, `repeat (query "limit")` fails with `wrong type for value; expected int; got string`. ## Guide The examples use the preview endpoint: it runs a rule against a sample request without saving it. See [Preview](#preview-a-rule). ### Values from the request Rule `GET /users/{id}`, body: ``` {"id": {{ path "id" }}, "page": {{ query "page" | default "1" }}, "client": {{ header "X-Client" | json }}, "method": {{ method | json }}, "path": {{ requestPath | json }}} ``` Request `GET /mock/users/42?page=3` with header `X-Client: web`: ```json {"id": 42, "page": 3, "client": "web", "method": "GET", "path": "/users/42"} ``` Request `GET /mock/users/7`, no query, no header: ```json {"id": 7, "page": 1, "client": ""} ``` (Second run with the body cut to the first three fields.) A missing value is an empty string; `default` replaces it. The rest of a path after a trailing `*`: rule `/files/*`, body `{"file": {{ path "*" | json }}}`, request `/mock/files/docs/2026/report.pdf`: ```json {"file": "docs/2026/report.pdf"} ``` ### Values from a JSON body `body` takes a dot path. A number in the path picks a list item, counting from 0. Rule `POST /orders`, status `201`, body: ``` {"email": {{ body "customer.email" | json }}, "first_sku": {{ body "items.0.sku" | json }}, "items": {{ body "items" | json }}, "missing": {{ body "nope" | json }}} ``` Request body `{"customer":{"email":"alice@example.com"},"items":[{"sku":"A-1","qty":2},{"sku":"B-7","qty":1}]}`: ```json {"email": "alice@example.com", "first_sku": "A-1", "items": [{"qty":2,"sku":"A-1"},{"qty":1,"sku":"B-7"}], "missing": null} ``` - A missing path gives nothing; `| json` writes it as `null`. - Objects and lists come out whole with `| json`. Their keys are sorted. - A body that is not JSON: every `body` path is missing. `bodyRaw` gives the body as text: body `{{ bodyRaw }}`, request body `hello=world` → `hello=world`. ### Fake data `fake "generator"` makes up a value. Common generators, run with `seed: 1`: | Template | Output | |----------|--------| | `{{ fake "name" \| json }}` | `"Zachary Byrd"` | | `{{ fake "firstname" \| json }}` | `"Zachary"` | | `{{ fake "lastname" \| json }}` | `"Zamora"` | | `{{ fake "email" \| json }}` | `"zacharybyrd@towne.io"` | | `{{ fake "username" \| json }}` | `"Antonio.87"` | | `{{ fake "phone" \| json }}` | `"9189298152"` | | `{{ fake "uuid" \| json }}` | `"b84fb46b-9fe3-4aff-8b5a-111c601e3d1a"` | | `{{ fake "word" \| json }}` | `"change"` | | `{{ fake "sentence" \| json }}` | `"Mind the year, then celebrate!"` | | `{{ fake "city" \| json }}` | `"Birmingham"` | | `{{ fake "country" \| json }}` | `"Zimbabwe"` | | `{{ fake "street" \| json }}` | `"89298 North Ovalburgh"` | | `{{ fake "zip" \| json }}` | `"18929"` | | `{{ fake "company" \| json }}` | `"Zoner"` | | `{{ fake "jobtitle" \| json }}` | `"Zookeeper"` | | `{{ fake "url" \| json }}` | `"https://www.strategicstrategize.io/evolve"` | | `{{ fake "ipv4address" \| json }}` | `"184.11.172.220"` | | `{{ fake "productname" \| json }}` | `"Usb-Powered Yoga Strap"` | | `{{ fake "currencyshort" \| json }}` | `"ZWL"` | | `{{ fake "color" \| json }}` | `"YellowGreen"` | | `{{ fake "date" \| json }}` | `"2026-02-27T21:17:56Z"` | | `{{ fake "number" }}` | `-340504648` | | `{{ fake "price" }}` | `340.28` | | `{{ fake "bool" }}` | `false` | | `{{ fake "httpstatuscode" }}` | `504` | These are a few of many. The full list with each one's parameters: [`GET /api/mocks/helpers`](#list-of-helpers-and-generators). **Arguments** fill the generator's parameters in the order the list gives them. `number` has `min` and `max`, so `{{ fake "number" 18 90 }}` is a whole number from 18 to 90. A parameter you leave out takes its default. A parameter with no default must be given: `{{ fake "float64range" }}` fails with `could not find field: min`. Rule `/users/{id}`, `seed: 42`, body: ``` {"id": {{ path "id" }}, "name": {{ fake "name" | json }}, "email": {{ fake "email" | json }}, "age": {{ fake "number" 18 90 }}, "uuid": {{ fake "uuid" | json }}, "active": {{ fake "bool" }}, "price": {{ fake "price" 5 500 }}, "bio": {{ fake "loremipsumsentence" 6 | json }}} ``` Request `/mock/users/1`: ```json {"id": 1, "name": "Jessica Hills", "email": "jonathon.marquardt@wilkinson.biz", "age": 73, "uuid": "bb4692dd-a6cd-4bd1-b922-33be54bd787f", "active": false, "price": 385.05, "bio": "Rerum et adipisci reprehenderit voluptates nam."} ``` Dates: the format style depends on the generator. `{{ fake "date" "2006-01-02" | json }}` gave `"1962-12-12"`; `{{ fake "daterange" "2024-01-01" "2024-12-31" "yyyy-MM-dd" | json }}` gave `"2024-03-16"`. Check the `default` of the generator's `format` parameter in the helpers list. Some generators return an object. Write it with `| json`. `{{ fake "person" | json }}`, `seed: 1`: ```json {"first_name":"Zachary","last_name":"Byrd","gender":"female","age":92,"ssn":"356850791","hobby":"Virtual Reality","job":{"company":"SocialEffort Inc","title":"Barista","descriptor":"Investor","level":"Directives"},"address":{"address":"340 Terraceland, Fort Worth, Maine 26713","street":"340 Terraceland","unit":"","city":"Fort Worth","state":"Maine","zip":"26713","country":"United States Minor Outlying Islands","latitude":13.856683,"longitude":-9.588688},"contact":{"phone":"1800157326","email":"darrin.moreno@dixon.biz"},"credit_card":{"type":"UnionPay","number":"6062828218685127","exp":"10/29","cvv":"584"}} ``` ### The same data every time: `seed` With `seed: 42`, two requests with the body `{"name": {{ fake "name" | json }}, "email": {{ fake "email" | json }}}` both answer: ```json {"name": "Jessica Hills", "email": "jonathon.marquardt@wilkinson.biz"} ``` With `seed: 0` (the default) the body `{"name": {{ fake "name" | json }}}` answered `{"name": "Marion Santiago"}`, then `{"name": "Clara Maldonado"}`. A seed fixes the order of fake values, not each value. Add a `fake` call before another one, and the later one changes. Use a seed in tests that compare responses. ### Lists: `repeat` and `range` `range $i := repeat n` repeats a block `n` times. `$i` is the index, from 0. JSON lists need a comma between items: `{{ if $i }},{{ end }}` writes one before every item except the first. Body, `seed: 7`: ``` [{{ range $i := repeat 3 }}{{ if $i }},{{ end }}{"id": {{ add $i 1 }}, "name": {{ fake "name" | json }}}{{ end }}] ``` Output: ```json [{"id": 1, "name": "Sienna Atkinson"},{"id": 2, "name": "Logan Cooper"},{"id": 3, "name": "Carrie Gray"}] ``` `range` also walks a list from the request: - **A JSON body list**: `range $i, $item := body "items"`; `$item.sku` reads a field of the item. Rule `POST /orders`, body: ``` {"lines": [{{ range $i, $item := body "items" }}{{ if $i }},{{ end }}{"line": {{ add $i 1 }}, "sku": {{ $item.sku | json }}, "qty": {{ $item.qty }}}{{ end }}]} ``` Request body `{"items":[{"sku":"A-1","qty":2},{"sku":"B-7","qty":1}]}`: ```json {"lines": [{"line": 1, "sku": "A-1", "qty": 2},{"line": 2, "sku": "B-7", "qty": 1}]} ``` - **All values of a query parameter**: body `[{{ range $i, $t := queryAll "tag" }}{{ if $i }},{{ end }}{"tag": {{ upper $t | json }}}{{ end }}]`, request `/mock/tags?tag=red&tag=blue`: ```json [{"tag": "RED"},{"tag": "BLUE"}] ``` - **A JSON body object**: `range $k, $v := body "m"` walks its keys in sorted order. Request body `{"m":{"b":2,"a":1}}`, body `{{ range $k, $v := body "m" }}{{ $k }}={{ $v }};{{ end }}` → `a=1;b=2;`. `range` works only over `repeat`, `queryAll` and `body`. Anything else is refused when you save the rule. ### Conditions `{{ if … }}…{{ else }}…{{ end }}` picks a part of the body. Tests: `eq` (equal), `ne` (not equal), `lt`, `le`, `gt`, `ge`, and `and`, `or`, `not`. An empty value counts as false. Body: ``` {{ if eq (query "fail") "1" }}{"status": "failed"}{{ else }}{"status": "paid"}{{ end }} ``` `/mock/pay?fail=1` → `{"status": "failed"}`; `/mock/pay` → `{"status": "paid"}`. A header present or not: body `{{ if header "Authorization" }}{"user": "alice"}{{ else }}{"error": "no token"}{{ end }}`, request without the header → `{"error": "no token"}`. A number from the JSON body: compare it with a decimal, or turn it into a whole number with `int`. Both bodies answer `{"review": true}` to the request body `{"amount": 250}`: ``` {{ if gt (body "amount") 100.0 }}{"review": true}{{ else }}{"review": false}{{ end }} {{ if gt (int (body "amount")) 100 }}{"review": true}{{ else }}{"review": false}{{ end }} ``` `with` runs a block only when the value is there; inside it, `.` is the value. Body `{{ with body "coupon" }}{"coupon": {{ . | json }}}{{ else }}{"coupon": null}{{ end }}`, request body `{"coupon": "SALE10"}` → `{"coupon": "SALE10"}`. The status code stays the rule's own. For a different status, make a second rule. ### Headers Header values are templates too. Rule `POST /orders`, status `201`, `seed: 9`, headers: ```json {"Content-Type": "application/json", "Location": "/orders/{{ fake \"number\" 1000 9999 }}", "X-Request-Id": "{{ header \"X-Request-Id\" | default \"none\" }}"} ``` Request with `X-Request-Id: abc-123` → headers: ```json {"Content-Type": "application/json", "Location": "/orders/9069", "X-Request-Id": "abc-123"} ``` Headers are not JSON: do not use `| json` in them. A header value with a line break fails the response. ### Time Body `{"created_at": {{ now | json }}, "day": {{ now "2006-01-02" | json }}, "ts": {{ now "unix" }}}`: ```json {"created_at": "2026-11-07T08:03:55Z", "day": "2026-11-07", "ts": 1794038635} ``` `now` is the current time in UTC. A layout is written with Go's reference date, `2006-01-02 15:04:05`. ## Helper reference | Helper | Usage | Returns | Example → output | |--------|-------|---------|------------------| | `path` | `path "name"` | a path parameter of the rule's path, as a string; `"*"` = the rest after a trailing `*`; missing: `""` | rule `/users/{id}`, `/mock/users/42`: `{"id": {{ path "id" }}}` → `{"id": 42}` | | `query` | `query "name"` | the first value of a query parameter, as a string; missing: `""` | `?page=3`: `{{ query "page" }}` → `3` | | `queryAll` | `queryAll "name"` | all values of a query parameter, a list of strings | `?tag=a&tag=b`: `{{ queryAll "tag" \| json }}` → `["a","b"]`; none → `[]` | | `header` | `header "Name"` | a request header (name in any case); missing: `""` | `X-Client: web`: `{{ header "X-Client" \| json }}` → `"web"` | | `body` | `body "a.b.0.c"` | a value of the JSON request body by dot path: string, number (`float64`), bool, object or list; missing: nothing | `{{ body "items.0.sku" \| json }}` → `"A-1"` | | `bodyRaw` | `bodyRaw` | the request body as text (first 1 MB) | `hello=world` → `hello=world` | | `method` | `method` | the request method | `{{ method \| json }}` → `"GET"` | | `requestPath` | `requestPath` | the request path without `/mock` | `{{ requestPath \| json }}` → `"/users/42"` | | `fake` | `fake "generator" [args…]` | fake data; args fill the generator's parameters in order | `{{ fake "number" 18 90 }}` → `73` | | `pick` | `pick a b c…` | one of the arguments at random (follows `seed`) | `{{ pick "paid" "pending" "failed" \| json }}` → `"failed"` (`seed: 5`) | | `repeat` | `repeat n` | the list 0…n-1, for `range`; `n` is a whole number (a request value through `int`) | `{{ range $i := repeat 3 }}{{ $i }}{{ end }}` → `012` | | `add` | `add a b` | the sum of two whole numbers (request values through `int`) | `{{ add 2 3 }}` → `5`; `{{ add $i 1 }}` in a `range` | | `int` | `int value` | a whole number: from text (`"42"` → 42, `"4.9"` → 4), a JSON body number, a bool (`true` → 1, `false` → 0); missing or `""` → 0; other text is an error | `{{ int "42" }} {{ int "4.9" }} {{ int "" }} {{ int true }}` → `42 4 0 1` | | `now` | `now`, `now "layout"`, `now "unix"` | the current UTC time: RFC 3339, a Go layout, or unix seconds | `{{ now "2006-01-02" \| json }}` → `"2026-11-07"` | | `json` | `json value`, `value \| json` | the value as JSON: strings quoted and escaped, lists and objects encoded | `{{ query "q" \| json }}` → `"say \"hi\""` | | `default` | `default fallback value`, `value \| default fallback` | `value`, or `fallback` when it is empty or missing | `{{ query "limit" \| default 20 }}` → `20` | | `upper` | `upper s` | upper case | `{{ upper "abc" }}` → `ABC` | | `lower` | `lower s` | lower case | `X-Mode: FAST`: `{{ lower (header "X-Mode") }}` → `fast` | Go template built-ins also work: `if`, `else`, `with`, `range` (over `repeat`, `queryAll`, `body` only), `eq`, `ne`, `lt`, `le`, `gt`, `ge`, `and`, `or`, `not`, `len`, `index`, `printf`, and variables (`$x := …`). `define`, `template` and `block` are not supported. Generators left out on purpose: `sql`, `csv`, `json`, `xml`, `regex`, `template`, `map`, `fixed_width`, `generate`, `imagejpeg`, `imagepng`, `svg`. Calling one fails like an unknown generator. ## Limits | What | Limit | When it is over | |------|-------|-----------------| | Response body | 1 MB | `response is larger than 1048576 bytes` | | Loop items in one response (`repeat`, `range` over `queryAll` and `body`, nested loops added up) | 10000 | `repeat: more than 10000 loop items in one response` | | Steps in one response: each loop item costs the number of steps (helper calls, text pieces) inside the loop | 1,000,000 | `template does more than 1000000 steps in one response (fewer or smaller loops)` | | Text made by helpers in one response (`fake`, `json`…), written out or not | 4 MB | `helpers made more than 4194304 bytes in one response` | | Time to build one response | 2 seconds | `template took longer than 2s` | | Count-like `fake` parameters (`wordcount`, `length`, `count`…) | 1000 | `fake "loremipsumsentence": wordcount must be at most 1000` | | `body` and `bodyRaw` | read the first 1 MB of the request body | — | Nested loops add up: `repeat 200` with `repeat 100` inside is 20200 items and fails. Steps add up too. `repeat 9000` with `{{ $i }}` written 100 times inside fails on steps, though 9000 items are allowed. `repeat 1000` with the same loop body works. One more limit is not about templates: a project holds at most 500 stored rules. Rule 501 is refused with `422` and `errors.project`: `at most 500 rules per project; delete unused ones first`. ## Errors **When you save a rule** (create or update), the template is parsed. A syntax error, an unknown helper name, `define`, or `range` over something else gives `422` with the place of the error: ```json {"code":422,"errors":{"body":"template: template: body:1: unexpected \"}\" in operand"},"message":"invalid mock rule: body: template: template: body:1: unexpected \"}\" in operand"} ``` The field is `errors.body`, or `errors.headers` for a header value. `body:1:` means line 1. A rule in `buggregator.yaml` with such an error is not refused but skipped at startup, see [Rules in `buggregator.yaml`](#rules-in-buggregator-yaml). **When a request comes in**, a template can still fail: a wrong argument type, an unknown generator, a limit. The mock then answers `500`: ```json {"error":"mock template: template: body:1:9: executing \"body\" at \u003cfake \"nosuch\"\u003e: error calling fake: fake: unknown generator \"nosuch\" (list: GET /api/mocks/helpers)"} ``` `body:1:9` means line 1, column 9. The captured request shows the same text without the `mock template: ` prefix in `mock.template_error`, so you find it on the **Mock server** page: ``` template: body:1:9: executing "body" at : error calling fake: fake: unknown generator "nosuch" (list: GET /api/mocks/helpers) ``` Errors you will meet most: | Error text | Cause | Fix | |------------|-------|-----| | `wrong type for value; expected int; got string` | a request value passed to `repeat` or `add` | wrap it: `int (query "limit")` | | `expected int; got float64` | a JSON body number passed to `add` or `repeat` | wrap it: `int (body "qty")` | | `incompatible types for comparison: float64 and int` | `gt (body "n") 100` | `gt (int (body "n")) 100`, or compare with `100.0` | | `int: "abc" is not a number` | `int` got text that is not a number | check the request value, or give it a `default` | | `fake: unknown generator "…"` | a typo, or a left-out generator | look it up in `GET /api/mocks/helpers` | | `fake "name" takes at most 0 arguments` | too many arguments | see the generator's `params` | | `could not find field: min` | a parameter with no default left out | pass it | | `function "atoi" not defined` | a helper that does not exist (`422` on save) | use only the helpers above | ## Preview a rule `POST /api/mocks/preview` runs a rule against a sample request. Nothing is saved and nothing is captured. Use it to test a template before you save it. Request: ```json { "rule": {"method": "GET", "path": "/users/{id}", "template": true, "seed": 0, "headers": {}, "body": "…"}, "request": {"method": "GET", "path": "/users/42?page=3", "headers": {"X-Client": "web"}, "body": ""} } ``` - `rule`: the same fields as a rule (`path` is required). - `request.path`: the path as the client sends it, with or without `/mock`, with the query string. - `request.method`: empty means the rule's method, or `GET` for `ANY`. Answer: ```json {"body":"{\"id\": 42, \"page\": 3}","error":null,"headers":{},"matched":true,"status":200} ``` - `matched`: whether this rule would answer this request (method and path). - `body`, `headers`: what the mock would send. - `error`: `null`, or the template error. With an error, `status` is `500` and `body` is empty: ```json {"body":"","error":"mock template: template: body:1:9: executing \"body\" at \u003cfake \"nosuch\"\u003e: error calling fake: fake: unknown generator \"nosuch\" (list: GET /api/mocks/helpers)","headers":{},"matched":true,"status":500} ``` A syntax error gives `422`, as on save. Example: ```bash curl -X POST http://127.0.0.1:8000/api/mocks/preview \ -H 'Content-Type: application/json' \ -d '{"rule": {"path": "/users/{id}", "template": true, "body": "{\"id\": {{ path \"id\" }}, \"page\": {{ query \"page\" | default \"1\" }}}"}, "request": {"method": "GET", "path": "/users/42?page=3"}}' ``` ## List of helpers and generators `GET /api/mocks/helpers` returns `{"helpers": […], "fake": […]}`. Read it before you write a `fake` call. A helper: ```json {"name": "path", "group": "request", "usage": "path \"name\"", "description": "Value of a path parameter of the rule's path, as a string. \"*\" is the rest matched by a trailing *. Missing: \"\".", "example": "{\"id\": {{ path \"id\" }}}", "result": "rule /users/{id}, request /mock/users/42 → {\"id\": 42}"} ``` A generator: `params` in the order the arguments fill them: ```json {"name": "number", "category": "number", "description": "Integer used for counting or measuring, with optional bounds", "example": "14866", "output": "int", "params": [{"name": "min", "type": "int", "optional": false, "default": "-2147483648"}, {"name": "max", "type": "int", "optional": false, "default": "2147483647"}]} ``` `output` tells how to write it: a string needs `| json`; `int`, `float`, `bool` can go in as they are; an object (e.g. `person`) needs `| json`. Both routes need the login when [SSO](/config/sso) is on. ## MCP tools for AI agents With the [MCP server](/config/mcp) on, an AI agent manages mock rules without the REST API. Example: the agent reads the helper list, tries a template with `mock_rule_preview`, then saves it with `mock_rule_create`. | Tool | What it does | |------|--------------| | `mock_rules_list` | The rules in matching order: config rules first (read-only), then stored ones | | `mock_rule_get` | One rule with its full body | | `mock_rule_preview` | Runs a rule against a sample request; nothing is saved. Same answer as `POST /api/mocks/preview` | | `mock_requests_list` | Requests the mock server got, newest first, with the rule that answered and `template_error` | | `mock_template_helpers` | The helpers and the fake generators with their parameters; filter by `category` or `search` | | `mock_rule_create` | Creates a rule | | `mock_rule_update` | Changes a stored rule; only the given fields change | | `mock_rule_delete` | Deletes a stored rule | | `mock_rule_from_request` | Creates a rule from a captured request (e.g. one that got `404`) | | `mock_import_openapi` | Imports an OpenAPI spec, see [OpenAPI import](/config/mock-server#import-an-openapi-spec) | | `mock_group_delete` | Deletes all stored rules of a group | The last six tools change rules. Turn them off with `mcp.mock_write: false` (env `MCP_MOCK_WRITE=false`): the agent then only reads and previews. ## Rules in `buggregator.yaml` Config rules take `template` and `seed` too: ```yaml mocks: - method: GET path: /orders/{id} template: true seed: 42 headers: { Content-Type: application/json } body: '{"id": {{ path "id" }}, "customer": {{ fake "name" | json }}, "total": {{ fake "price" 5 500 }}}' ``` `GET /mock/orders/7`, twice: ```json {"id": 7, "customer": "Jessica Hills", "total": 431.73} ``` Put the body in single quotes: the template has double quotes inside. A rule whose template does not parse is skipped at startup, with the warning `mock: skipping config rule` in the log. ## Updating a rule `PUT /api/mocks/{id}` without the `template` or `seed` field keeps the stored value. Send `"template": false` to turn templates off. ::: --- # Monolog — Logs Your app writes logs — but where do they go during development? A file you `tail -f`? Docker container output you scroll through? With Buggregator, logs from all your services land in the same UI where you already see exceptions, dumps, and emails. Search by message, channel or level, read the context as JSON, and see the file and line that wrote a record when it sends them — all without setting up Elasticsearch or a separate logging stack. ![Monolog log records](/images/monolog.webp) ## Use cases - **Structured log viewer** — see context and extra fields as formatted JSON, not a raw string in a terminal. - **Multi-service logging** — collect logs from all containers in one place. - **Debug long-running apps** — workers, daemons, and queue consumers write logs that are easy to miss in stdout. Buggregator catches them all. - **All in one place** — see logs in the same UI as your exceptions and dumps. ## What you see in the UI - **Channel** — the logger channel (`app`, `security`, `database`, etc.). - **Message** — the log message. - **Severity level** — all PSR-3 levels: emergency, alert, critical, error, warning, notice, info, debug. - **Timestamp** — when the log was recorded. - **Context** — structured context data in JSON format. - **Extra fields** — additional data from Monolog processors. - **Source** — file, line, and function where the log was generated, when the record has a `source` key in its context. ## Configuration Buggregator receives logs via Monolog's `SocketHandler` on port **9913**. The formatter **must** be `JsonFormatter`. > In Docker Compose, replace `127.0.0.1` with the Buggregator service name (e.g., `buggregator:9913`). ### Laravel ```php // config/logging.php return [ // ... 'channels' => [ // ... 'socket' => [ 'driver' => 'monolog', 'level' => env('LOG_LEVEL', 'debug'), 'handler' => \Monolog\Handler\SocketHandler::class, 'formatter' => \Monolog\Formatter\JsonFormatter::class, 'handler_with' => [ 'connectionString' => env('LOG_SOCKET_URL', '127.0.0.1:9913'), ], ], ], ]; ``` ```dotenv LOG_CHANNEL=socket LOG_SOCKET_URL=127.0.0.1:9913 ``` ### Spiral Framework ```php get('MONOLOG_SOCKET_HOST'), chunkSize: 10); $handler->setFormatter(new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES)); $monolog->addHandler('socket', $handler); } } ``` ```dotenv MONOLOG_DEFAULT_CHANNEL=socket MONOLOG_SOCKET_HOST=127.0.0.1:9913 ``` ### Symfony ```php # config/packages/dev/monolog.php handler('socket') ->level('debug') ->formatter('monolog.formatter.json') ->type('socket') ->connectionString(env('MONOLOG_SOCKET_HOST')); }; ``` ```dotenv MONOLOG_SOCKET_HOST=127.0.0.1:9913 ``` > **Important:** The `monolog.formatter.json` formatter is required. Without it, Buggregator cannot parse the log records. ### Any PHP project ```bash composer require monolog/monolog ``` ```php setFormatter(new JsonFormatter()); $log->pushHandler($handler); $log->warning('Foo'); $log->error('Bar'); ``` --- # JetBrains IDE Plugin You use PhpStorm (or another JetBrains IDE) and don't want to switch to a browser to check dumps and logs. The Buggregator plugin embeds the full debug UI directly into your IDE — dumps, logs, exceptions, and profiling data appear in a panel next to your code. All IDE shortcuts keep working. No context switching. **Plugin repository:** https://github.com/buggregator/phpstorm-plugin ## How it works The plugin launches [Buggregator Trap](/trap/what-is-trap) from your project's `vendor` directory using the PHP interpreter configured in your IDE. Trap starts collecting debug data and the plugin displays it in two tabs: - **Web UI** — the full interactive Buggregator interface in the IDE's built-in browser. Same UI as the standalone server. - **Terminal** — text-based output for quick inspection. Trap opens a web interface port (configurable in settings), which works with all standard clients — VarDumper, Monolog, Sentry, Ray, and others. > **Tip:** If you have the plugin running in multiple IDE windows with the same port, both Web UIs share the same > Trap instance. A second Trap will wait until the port is free. ## Requirements - [buggregator/trap](https://github.com/buggregator/trap) installed in your project (`composer require --dev buggregator/trap`) - A PHP interpreter configured in your IDE settings ## Installation ### From JetBrains Marketplace (recommended) Go to the [plugin page](https://plugins.jetbrains.com/plugin/26344-buggregator) and click **Install to ...** ### From IDE **Settings** > **Plugins** > **Marketplace** > search for **"Buggregator"** > **Install** ### Manual 1. Download the `.jar` file from [GitHub Releases](https://github.com/buggregator/phpstorm-plugin/releases) or [JetBrains Marketplace](https://plugins.jetbrains.com/plugin/26344-buggregator/versions). 2. **Settings** > **Plugins** > **⚙️** > **Install plugin from disk...** > select the `.jar` file. 3. Restart the IDE if prompted. After installation, find the **Buggregator** button in the top right corner of the IDE window. ## Configuration Open the plugin settings to customize: - **PHP interpreter** — which PHP binary to use for running Trap. - **Path to Trap** — defaults to `vendor/bin/trap`, change if needed. - **Web UI port** — the port for the embedded web interface. Click the **🌐** button on the toolbar to open the Web UI in your system browser instead of the IDE. ## Supported IDEs The plugin works with all JetBrains IDEs that support PHP development: - PhpStorm - IntelliJ IDEA (with PHP plugin) - WebStorm - And other JetBrains products --- # Configuration — Projects Buggregator lets you use "projects" to help organize your data. Projects are useful for keeping events from different teams, applications, or environments separate. ![Project switcher in the sidebar](/images/projects-switcher.webp) **Here's why you might want to use projects:** 1. Projects help you keep data from different teams or parts of your app separate. This means it's easier to find what you're looking for and keep track of changes. 2. Teams won't get mixed up with data that isn't relevant to them, which makes their work faster and less confusing. 3. The sidebar displays a project selector dropdown, allowing you to quickly switch between projects and view only the events relevant to the selected project. ### Default Project When you start the server, Buggregator automatically sets up a default project with key `default`. All your data goes into this `default` project if a project key is not specified in the request. ## Configuration Projects are configured in `buggregator.yaml`: ```yaml projects: - key: my-app name: My Application - key: staging name: Staging Environment - key: mobile name: Mobile App ``` ### Docker Compose Example ```yaml services: buggregator: image: ghcr.io/buggregator/server:latest ports: - 127.0.0.1:8000:8000 volumes: - ./buggregator.yaml:/buggregator.yaml ``` With `buggregator.yaml`: ```yaml projects: - key: backend name: Backend API - key: frontend name: Frontend App ``` ## Sentry Configuration To use Sentry with your project, format your DSN like this: ```dotenv SENTRY_DSN=http://sentry@127.0.0.1:8000/ ``` A numeric last segment (`/1`) is the SDK's own project id and sends events to `default`. If your SDK accepts only numbers there, send both `X-Buggregator-Event: sentry` and `X-Buggregator-Project: `; the project header alone is ignored for Sentry SDK requests. > **Note:** Read more in [Sentry → Projects](/config/sentry.html#projects). ## Mock Server Rules can be limited to one project, and requests choose their project with the `X-Buggregator-Project` header or Basic Auth `mock:`. See [Mock Server → Projects](/config/mock-server.html#projects). ## Projects created on the fly A project key that is not in `buggregator.yaml` is added to the list when its first event card arrives, with the key as its name. Example: an error sent to `http://sentry@127.0.0.1:8000/billing` adds the project `billing`. Sentry traces, logs and metrics make no card, so a project that gets only those is not added: list it in `buggregator.yaml`. ## Inspector Configuration To use Inspector with your project, format your DSN like this: ```dotenv INSPECTOR_URL=http://inspector:@127.0.0.1:8000 INSPECTOR_API_KEY= ``` > **Note:** Read more about Inspector configuration [here](/config/inspector.html). ## Xhprof Profiler Configuration To set up the Profiler, use this: ```dotenv PROFILER_ENDPOINT=http://profiler:@127.0.0.1:8000 ``` > **Note:** Read more about Xhprof Profiler configuration [here](/config/xhprof.html). ## Ray Configuration For Ray, use these settings: ```dotenv RAY_HOST=ray:@127.0.0.1 RAY_PORT=8000 ``` ## VarDumper Configuration A dump goes to the project named by the `project` key of its context. A plain `dump()` has no such key, so it lands in `default`. ## Monolog Configuration A log record goes to the project named by `project` in its context: ```php $logger->error('Payment failed', ['project' => 'shop']); ``` Records without it land in `default`. --- # Installable App (PWA) You can install the Buggregator UI as an app. It then opens in its own window, without browser tabs and the address bar, and has its own icon in the dock or taskbar. When new events arrive while the window is in the background, the icon shows how many. > Available since frontend 1.35.0, bundled with server v2.6.0. ## Install 1. Open Buggregator in Chrome or Edge, e.g. `http://127.0.0.1:8000`. 2. Click the install icon at the end of the address bar, or choose **Install Buggregator** in the browser menu. 3. The app opens in its own window. Next time, start it like any other app. Other browsers may offer it in their own way, for example Safari's **Add to Dock** on macOS. ### When the browser does not offer to install Browsers offer installation only on `https://` or on `localhost` / `127.0.0.1`. Over plain `http` with a LAN address or a host name, there is no install option. | Address | Install offered | |---------|-----------------| | `http://127.0.0.1:8000` | yes | | `http://localhost:8000` | yes | | `https://buggregator.example.com` | yes | | `http://192.168.1.10:8000` | no | | `http://buggregator:8000` | no | If you run Buggregator in Docker, publish the port on your machine (`-p 127.0.0.1:8000:8000`) and open `http://127.0.0.1:8000`. ## New-events badge Each event of the current project that arrives while the app window is hidden or not focused adds one to the number on the app icon. When you focus the window, the number is cleared. The badge works in Chromium-based browsers (Chrome, Edge) on Windows and macOS. Elsewhere the app works, but shows no number. ## What it does not do - No offline mode: the app needs a running Buggregator server. - No system notifications. --- # Ray — Debug Tool [Ray](https://myray.app/) by Spatie is a popular debug tool, especially in the Laravel ecosystem. Buggregator is a free, self-hosted alternative — you get the same `ray()` calls, but the data lands in Buggregator alongside your exceptions, logs, emails, and profiling. One place for everything. ![Ray dumps](/images/ray.webp) ## Use cases - **Free Ray alternative** — no license needed. Same `ray()` function, same workflow. - **Multi-language debugging** — Ray has SDKs for PHP, JavaScript, Ruby, Go, and Bash. All output goes to Buggregator. - **Laravel debugging** — dump Eloquent models, SQL queries, jobs, mail, events, and more with type-specific rendering. - **All debug data in one UI** — don't switch between Ray app, Sentry, log files, and Mailhog. It's all in Buggregator. ## Supported payload types Buggregator renders 18 Ray payload types: | Type | What it shows | |---|---| | **Log** | Text logging | | **Custom** | Custom data dumps | | **Caller** | Call origin (file, line, function) | | **Carbon** | Carbon date/time objects | | **Trace** | Full stack trace | | **Exception** | Exception with stack trace | | **Table** | Structured data as a table | | **Measure** | Performance timing | | **Query** | SQL query with bindings | | **Eloquent** | Eloquent model data | | **Application Log** | Application log entries | | **View** | Template rendering info | | **Event** | Application events | | **Job** | Queue job details | | **Lock** | Lock status | | **Mailable** | Laravel Mail preview | | **Notify** | Notification data | | **Origin** | Call origin info | Each payload shows its origin (file, line, function). Click file paths to open in your IDE. ## Configuration ### Laravel Publish the Ray config: ```bash php artisan ray:publish-config ``` Set env variables: ```dotenv RAY_HOST=ray@127.0.0.1 RAY_PORT=8000 ``` > In Docker Compose: `RAY_HOST=ray@buggregator`, `RAY_PORT=8000`. ### PHP (any framework) Create a `ray.php` file in your project root: ```php true, 'host' => 'ray@127.0.0.1', 'port' => 8000, 'remote_path' => null, 'local_path' => null, 'always_send_raw_values' => false, ]; ``` ### Other languages - [JavaScript](https://myray.app/docs/javascript/vanilla-javascript/getting-started) - [Ruby](https://myray.app/docs/other-languages/ruby/getting-started) - [Go](https://myray.app/docs/other-languages/go/getting-started) - [Bash](https://myray.app/docs/other-languages/bash/installation) --- # Sentry — Exceptions You want to see exceptions with stack traces, breadcrumbs, and request context — but you don't want to deploy a full Sentry instance just for local development. Buggregator accepts the same Sentry SDK protocol, so you change one line in your config and get exception tracking alongside all your other debug data — logs, dumps, emails, profiling — in a single UI. No registration. No limits. No heavy infrastructure. ![Sentry exceptions](/images/sentry.webp) ## Use cases - **Long-running apps** (RoadRunner, Swoole, queue workers) — exceptions don't show in the browser, but they show in Buggregator. - **Microservices / Docker Compose** — collect exceptions from all services in one place instead of checking each container's logs. - **Frontend + Backend** — catch JavaScript errors alongside PHP exceptions in the same dashboard. - **Quick local debugging** — don't wait for errors to appear in a remote Sentry instance. See them instantly. ## What you see in the UI - **Exception** — frame-by-frame stack trace with file paths, line numbers, and code context. Click to open in your IDE. - **Breadcrumbs** — timeline of user actions and system events leading up to the error. - **Request** — HTTP method, URI, headers, cookies, POST data. - **Device** — browser, OS, device type. - **App** — application name, version, build. - **Tags & Extra** — custom key-value data attached to the event. - **Modules** — loaded packages with versions. ## Configuration Point your Sentry DSN at Buggregator. The format is the same for all platforms: ```dotenv SENTRY_DSN=http://sentry@127.0.0.1:8000/1 ``` > In Docker Compose, replace `127.0.0.1` with the Buggregator service name (e.g., `buggregator`). ### Laravel ```dotenv SENTRY_LARAVEL_DSN=http://sentry@127.0.0.1:8000/1 ``` Install the SDK: [docs.sentry.io/platforms/php/guides/laravel](https://docs.sentry.io/platforms/php/guides/laravel/) ### Spiral Framework ```dotenv SENTRY_DSN=http://sentry@127.0.0.1:8000/1 ``` Install the SDK: [spiral.dev/docs/extension-sentry](https://spiral.dev/docs/extension-sentry/3.3/en) ### Symfony ```dotenv SENTRY_DSN=http://sentry@127.0.0.1:8000/1 ``` Install the SDK: [docs.sentry.io/platforms/php/guides/symfony](https://docs.sentry.io/platforms/php/guides/symfony/) ### Magento 2 Using [justbetter/magento2-sentry](https://github.com/justbetter/magento2-sentry): ```dotenv CONFIG__SENTRY__ENVIRONMENT__DSN=http://sentry@127.0.0.1:8000/1 ``` or in `app/etc/env.php`: ```php 'sentry' => [ 'dsn' => 'http://sentry@127.0.0.1:8000/1', ... ] ``` ### WordPress > `WP_ENVIRONMENT_TYPE` must be set to `local`. [Local](https://localwp.com/) does that by default. 1. Install [WP Sentry](https://wordpress.org/plugins/wp-sentry-integration/) (no need to activate). 2. Add to `wp-config.php`: ```php if (defined('WP_ENVIRONMENT_TYPE') && 'local' === WP_ENVIRONMENT_TYPE) { define( 'WP_SENTRY_PHP_DSN', 'http://sentry@127.0.0.1:8000/1' ); define( 'WP_SENTRY_ERROR_TYPES', E_ALL & ~E_NOTICE & ~E_USER_NOTICE ); require_once __DIR__ . '/wp-content/plugins/wp-sentry-integration/wp-sentry.php'; } ``` ### JavaScript Use the official [Sentry JavaScript SDK](https://docs.sentry.io/platforms/javascript/) and point the DSN at Buggregator: ```javascript Sentry.init({ dsn: "http://sentry@127.0.0.1:8000/1", }); ``` ### Other platforms Any [Sentry SDK](https://docs.sentry.io/platforms/) works. Just set the DSN: ```dotenv SENTRY_DSN=http://sentry@127.0.0.1:8000/1 ``` ## Projects Send each app to its own [project](/config/projects), and the Sentry page shows only that project's data. Without a project, everything goes to `default`. Put the project key in the DSN path instead of the number: ```dotenv SENTRY_DSN=http://sentry@127.0.0.1:8000/shop ``` A number in the path (`/1`, `/42`) is the SDK's own project id, not a Buggregator project. Such events go to `default`. Some SDKs accept only a number there: the Sentry JavaScript SDK, for example. Then keep the number and, if your SDK lets you add HTTP headers, send two headers together: ``` X-Buggregator-Event: sentry X-Buggregator-Project: shop ``` `X-Buggregator-Project` alone is not enough: a Sentry SDK request is recognized by its `X-Sentry-Auth` header, and that path ignores `X-Buggregator-Project`. | How | Example | |-----|---------| | DSN path (wins over the headers) | `http://sentry@127.0.0.1:8000/shop` | | Headers | `X-Buggregator-Event: sentry` + `X-Buggregator-Project: shop` | A project that does not exist yet is added to the project list when its first error arrives. A project that receives only traces, logs or metrics is not added: put it in `buggregator.yaml` (see [Projects](/config/projects)). Errors, traces, logs and metrics all land in the same project, however you set it. > **Upgrading to v2.6.0:** Sentry errors sent with a numeric DSN, and traces, logs and metrics stored by > earlier versions, had no project. On first start, v2.6.0 moves them to `default`. Nothing is deleted. ## Traces, logs and metrics Besides errors, Buggregator stores what the Sentry SDK sends as traces (transactions and spans), logs and metrics. The **Sentry** page has a tab for each: - **Exceptions** — errors, as a list or grouped by fingerprint. - **Traces** — transactions with their spans. - **Logs** — Sentry structured logs. - **Metrics** — Sentry metrics. ### Filters Every tab shows the current project and the chosen period (last hour, last 24 hours, last 7 days, all time, …). Filtering happens on the server, so a filter does not miss rows past the first page. The REST API accepts more filters than the page shows: | Endpoint | Filters | |----------|---------| | `GET /api/sentry/exceptions` | `project`, `environment`, `level`, `handled`, `grouped=true`, `from`, `to`, `window` | | `GET /api/sentry/traces` | `project`, `environment`, `release`, `from`, `to`, `window` | | `GET /api/sentry/logs` | `project`, `level` (several, comma-separated), `trace_id`, `from`, `to`, `window` | | `GET /api/sentry/metrics` | `project`, `name`, `type`, `trace_id`, `search` (part of the name), `from`, `to`, `window` | | `GET /api/sentry/counts` | `project`, `from`, `to`, `window` | `window` is a period like `15m`, `24h` or `7d`. `from` and `to` take unix seconds or ISO 8601. ### Live updates The tabs refresh by themselves when new rows arrive. Example: your app writes a Sentry log, and the open **Logs** tab shows it without a reload. Each tab reloads only for its own kind of data. For clients of the WebSocket: when a request stored logs, metrics or traces, the server sends one `sentry.stored` notice on the project's channel `events.project.`: ```json {"project": "default", "kinds": ["log", "metric"]} ``` Kinds are `log`, `metric` and `trace`. An error alone sends the usual `event.received`. ## Clearing data **Clear** on the Sentry page deletes the Sentry data of the current project only: errors, traces, logs and metrics. Pinned errors stay. Other projects are not touched. The same through the API: | Call | Deletes | |------|---------| | `DELETE /api/sentry/all?project=shop` | everything Sentry stored for `shop` | | `DELETE /api/sentry/all?project=shop&keep_pinned=1` | the same, but pinned errors stay | | `DELETE /api/sentry/all` | Sentry data of **every** project | A trace can hold spans of several projects. After a project is cleared, a trace with no spans left is deleted; a trace with spans of other projects stays. `DELETE /api/sentry/all` clears the Sentry tables (traces, logs, metrics, error details). The error cards in the event feed are events: clear them with `DELETE /api/events` and the body `{"type": "sentry", "project": "shop", "keep_pinned": true}`. --- # Configuration — Server Buggregator is configured through a combination of a YAML config file, environment variables, and CLI flags. Every setting has a sensible default — no configuration file is required to get started. ## Configuration Priority Settings are resolved in this order (highest priority first): 1. **CLI flags** (e.g., `--http-addr :9000`). Available flags: `--config`, `--http-addr`, `--db`, `--smtp-addr`, `--monolog-addr`, `--vardumper-addr`, `--ui-default-limit`, `--ui-max-limit`. 2. **Environment variables** (e.g., `HTTP_ADDR=:9000`) 3. **Config file** (`buggregator.yaml`) 4. **Defaults** ## Config File Place a file named `buggregator.yaml` (or `buggregator.yml`) next to the binary, or specify a custom path: ```bash ./buggregator --config /path/to/buggregator.yaml ``` The config file supports environment variable substitution using `${VAR}` or `${VAR:default}` syntax. ### Full Example ```yaml # HTTP server server: addr: ${HTTP_ADDR::8000} cors_origins: - "*" # Database (SQLite) database: driver: sqlite dsn: ${DATABASE_DSN::memory:} # ":memory:" or file path like "data.db" max_open_conns: ${DATABASE_MAX_OPEN_CONNS:4} # SQLite connection pool; in-memory always uses 1 # Attachment storage (SMTP attachments, HTTP dump files) storage: mode: ${STORAGE_MODE:memory} # "memory" or "filesystem" path: ${STORAGE_PATH:./storage} # Directory for filesystem mode # Event lists of the UI (/api/events, /api/events/preview) ui: default_limit: ${UI_DEFAULT_LIMIT:} # Events without a limit param. Empty or 0 = unlimited max_limit: ${UI_MAX_LIMIT:5000} # Ceiling for an explicit ?limit=. 0 = no ceiling default_window: ${UI_DEFAULT_WINDOW:} # e.g. "1h", "24h", "7d". Empty = no window # TCP servers tcp: smtp: addr: ${SMTP_ADDR::1025} monolog: addr: ${MONOLOG_ADDR::9913} var-dumper: addr: ${VAR_DUMPER_ADDR::9912} proxy: addr: ${PROXY_ADDR::8080} # HTTP proxy # Xdebug proxy (off by default), see /config/xdebug # xdebug: # enabled: false # addr: 127.0.0.1:9003 # Where Xdebug connects # ide_addr: 127.0.0.1:9004 # Where the IDE listens # allow_eval: false # Let MCP clients and watches evaluate PHP # Enable/disable modules modules: sentry: true ray: true var-dump: true inspector: true monolog: true smtp: true sms: true http-dump: true profiler: true # Prometheus metrics metrics: enabled: ${METRICS_ENABLED:false} addr: ${METRICS_ADDR:} # Separate server, e.g. ":9090". Empty = serve on main HTTP server. # Authentication (OAuth2/OIDC) # auth: # enabled: false # provider: oidc # provider_url: https://xxx.us.auth0.com # client_id: xxx # client_secret: xxx # callback_url: http://localhost:8000/auth/sso/callback # scopes: openid,email,profile # jwt_secret: my-secret-key # MCP (Model Context Protocol) for AI assistants # mcp: # enabled: false # transport: socket # "socket" or "http" # socket_path: /tmp/buggregator-mcp.sock # addr: :8001 # For HTTP transport # auth_token: # Bearer token for HTTP transport # Webhooks # webhooks: # - event: "*" # url: https://slack.example.com/webhook # headers: # Authorization: "Bearer token" # verify_ssl: false # retry: true # Mock server rules (read-only in the UI), see /config/mock-server # mocks: # - method: GET # path: /users/{id} # status: 200 # headers: { Content-Type: application/json } # body: '{"id": 1}' # delay: 150ms # Pre-defined projects # projects: # - key: my-app # name: My Application ``` --- ## Environment Variables Reference ### HTTP Server | Variable | Default | Description | |----------|---------|-------------| | `HTTP_ADDR` | `:8000` | HTTP server listen address | | `CORS_ORIGINS` | `*` | Comma-separated list of allowed CORS origins | | `GOMEMLIMIT` | 90% of the container's memory limit | Go soft memory limit, e.g. `400MiB`. See [Memory Limits](#memory-limits) | ### Database | Variable | Default | Description | |----------|---------|-------------| | `DATABASE_DSN` | `:memory:` | SQLite database path. Use `:memory:` for in-memory (data lost on restart) or a file path like `data.db` for persistence. | | `DATABASE_MAX_OPEN_CONNS` | `4` | SQLite connection pool size for a file database. `1` makes reads wait behind writes, as before v2.6.0. An in-memory database always uses 1. See [Database](/config/database#connection-pool). | ### Event Lists Limits for `/api/events` and `/api/events/preview`, the lists the UI loads. There is no cap by default. | Variable | CLI flag | Default | Description | |----------|----------|---------|-------------| | `UI_DEFAULT_LIMIT` | `--ui-default-limit` | unlimited | Events returned when a request has no `limit`. `0` = unlimited | | `UI_MAX_LIMIT` | `--ui-max-limit` | `5000` | Ceiling for an explicit `limit`. `0` = no ceiling | | `UI_DEFAULT_WINDOW` | — | (empty) | Default time window when a request has no `from`/`to`, e.g. `24h`. Empty = no window | Both endpoints accept `limit`, `offset` or `page`, `from`, `to` and `window` (`15m`, `24h`, `7d`; `all` turns the default window off). Pinned events come first. ### Attachment Storage | Variable | Default | Description | |----------|---------|-------------| | `STORAGE_MODE` | `memory` | `memory` (lost on restart) or `filesystem` (persistent) | | `STORAGE_PATH` | `./storage` | Directory for filesystem storage mode | ### TCP Ports | Variable | Default | Description | |----------|---------|-------------| | `SMTP_ADDR` | `:1025` | SMTP server listen address | | `MONOLOG_ADDR` | `:9913` | Monolog TCP server listen address | | `VAR_DUMPER_ADDR` | `:9912` | VarDumper TCP server listen address | | `PROXY_ADDR` | `:8080` | [HTTP proxy](/config/http-proxy) listen address | ### Xdebug Proxy Off by default. See [Xdebug](/config/xdebug). | Variable | Default | Description | |----------|---------|-------------| | `XDEBUG_PROXY_ENABLED` | `false` | Turn the Xdebug proxy on | | `XDEBUG_PROXY_ADDR` | `127.0.0.1:9003` | Where Xdebug connects | | `XDEBUG_PROXY_IDE_ADDR` | `127.0.0.1:9004` | Where the IDE listens | | `XDEBUG_PROXY_ALLOW_EVAL` | `false` | Allow MCP clients and watches to evaluate PHP expressions | ### Mock Server Mock rules have no environment variables: define them in the `mocks` section of `buggregator.yaml`, in the UI, or through the API. See [Mock Server](/config/mock-server). ### Modules | Variable | Default | Description | |----------|---------|-------------| | `CLIENT_SUPPORTED_EVENTS` | all | Comma-separated list of enabled module types (e.g., `sentry,ray,smtp`) | ### Metrics | Variable | Default | Description | |----------|---------|-------------| | `METRICS_ENABLED` | `false` | Enable Prometheus metrics | | `METRICS_ADDR` | (empty) | Separate metrics server address (e.g., `:9090`). Leave empty to serve `/metrics` on the main HTTP server. | ### Authentication | Variable | Default | Description | |----------|---------|-------------| | `AUTH_ENABLED` | `false` | Enable OAuth2/OIDC authentication | | `AUTH_PROVIDER` | `oidc` | Provider: `auth0`, `google`, `github`, `keycloak`, `gitlab`, `oidc` | | `AUTH_PROVIDER_URL` | — | OIDC issuer URL (e.g., `https://xxx.us.auth0.com`) | | `AUTH_CLIENT_ID` | — | OAuth2 client ID | | `AUTH_CLIENT_SECRET` | — | OAuth2 client secret | | `AUTH_CALLBACK_URL` | — | Callback URL (e.g., `http://localhost:8000/auth/sso/callback`) | | `AUTH_SCOPES` | `openid,email,profile` | Comma-separated OAuth2 scopes | | `AUTH_JWT_SECRET` | — | Secret for signing internal JWT tokens (required when auth is enabled) | ### MCP (Model Context Protocol) | Variable | Default | Description | |----------|---------|-------------| | `MCP_ENABLED` | `false` | Enable MCP server for AI assistant integration | | `MCP_TRANSPORT` | `socket` | Transport type: `socket` (Unix socket) or `http` (HTTP/SSE) | | `MCP_SOCKET_PATH` | `/tmp/buggregator-mcp.sock` | Unix socket path (for socket transport) | | `MCP_ADDR` | `:8001` | HTTP listen address (for HTTP transport) | | `MCP_AUTH_TOKEN` | — | Bearer token for HTTP transport authentication | ### Other | Variable | Default | Description | |----------|---------|-------------| | `FRONTEND_DIR` | — | Serve frontend from disk instead of embedded (for development) | --- ## Docker Examples ### Using Environment Variables ```bash docker run --pull always \ -p 127.0.0.1:8000:8000 \ -p 127.0.0.1:1025:1025 \ -e DATABASE_DSN=/data/buggregator.db \ -e METRICS_ENABLED=true \ -v ./data:/data \ ghcr.io/buggregator/server:latest ``` ### Using a Config File ```bash docker run --pull always \ -p 127.0.0.1:8000:8000 \ -p 127.0.0.1:1025:1025 \ -v ./buggregator.yaml:/buggregator.yaml \ ghcr.io/buggregator/server:latest ``` ### Docker Compose with All Options ```yaml services: buggregator: image: ghcr.io/buggregator/server:latest ports: - 127.0.0.1:8000:8000 - 127.0.0.1:1025:1025 - 127.0.0.1:9912:9912 - 127.0.0.1:9913:9913 environment: DATABASE_DSN: /data/buggregator.db STORAGE_MODE: filesystem STORAGE_PATH: /data/storage METRICS_ENABLED: "true" volumes: - buggregator-data:/data volumes: buggregator-data: ``` ### Memory Limits Give the container a memory limit. Buggregator then tries to stay under it: it sets the Go runtime's soft memory limit to 90% of the container's limit. Example: a 512 MB container gets a 460 MiB limit. > Since server v2.7.0. Older versions ignore the container's limit. Set the limit with Docker: ```bash docker run --memory=512m -p 127.0.0.1:8000:8000 ghcr.io/buggregator/server:latest ``` With Docker Compose: ```yaml services: buggregator: image: ghcr.io/buggregator/server:latest mem_limit: 512m ``` With the [Helm chart](/config/helm-chart): `resources.limits.memory` in `values.yaml`. The startup log shows the limit in use: ``` time=2026-11-07T09:24:58.483Z level=INFO msg="go memory limit" mib=460 source=cgroup ``` The binary without Docker gets the same: a systemd service or slice with `MemoryMax` is a memory limit too. When several levels have one, the smallest counts. With no memory limit on the container or service, there is no such line, and Go sets no soft limit. **Set the limit yourself** with `GOMEMLIMIT`. It wins over the container's limit: ```bash docker run --memory=512m -e GOMEMLIMIT=400MiB -p 127.0.0.1:8000:8000 ghcr.io/buggregator/server:latest # time=… level=INFO msg="go memory limit" mib=400 source=GOMEMLIMIT ``` `GOMEMLIMIT=off` turns the soft limit off; the log then has no such line. It is a soft limit. Near it, the garbage collector (the part of Go that frees unused memory) works harder; memory can still go above it. The VarDumper parser runs as its own process, and its memory is not counted in the soft limit (the container's limit still counts it). A large upload, e.g. a big profiler snapshot, needs room on top of what Buggregator normally uses, so leave headroom in the container's limit. ## Disabling Modules You can disable modules you don't need. Disabled modules won't bind their TCP port and will ignore incoming events. In `buggregator.yaml`: ```yaml modules: sentry: true ray: true var-dump: false # Disable VarDumper inspector: false # Disable Inspector monolog: true smtp: true sms: false # Disable SMS http-dump: true profiler: true ``` Or via environment variable: ```bash CLIENT_SUPPORTED_EVENTS=sentry,ray,monolog,smtp,http-dump,profiler ``` --- # SMS Gateway Interceptor Your app sends SMS messages — OTP codes, delivery notifications, alerts. During development you don't want to send real messages through Twilio or Vonage. Buggregator acts as a fake SMS gateway: point your app's SMS webhook URL at Buggregator and every message shows up in the UI — with sender, recipient, message text, and detected provider. ## Use cases - **OTP testing** — verify that verification codes are generated and sent correctly. - **Notification preview** — see the exact text your users will receive. - **Provider migration** — switch between Twilio, Vonage, Plivo etc. and verify the payload format. - **Validation feedback** — use explicit provider URLs to catch missing required fields before going to production. ## How it works Buggregator exposes a single `/sms` endpoint. When your app sends an HTTP POST with SMS data, Buggregator: 1. **Auto-detects the provider** by inspecting request body fields (e.g. `MessageSid` → Twilio, `api_key`+`api_secret` → Vonage). 2. **Extracts** `from`, `to`, and `message` using provider-specific field mappings. 3. **Displays** the SMS in the UI with a colored provider badge. If the payload doesn't match any known provider, the generic fallback tries common field names (`from`/`to`/`message`/`body`/`text`). ### Explicit provider URL You can also specify the provider in the URL for stricter validation: ``` POST /sms/twilio → forces Twilio field mapping + validates required fields POST /sms/vonage → forces Vonage field mapping + validates required fields POST /sms → auto-detects provider from payload ``` When using an explicit provider URL, Buggregator validates that all required fields are present. If something is missing: - The HTTP response returns **422** with a JSON error listing missing fields. - The event is **still captured** in the UI with validation warnings highlighted in red. This way your app sees the error (like it would from a real provider), and you can inspect the full payload in Buggregator. ### Project support Append a project name as an additional URL segment: ``` POST /sms/twilio/myproject → explicit provider + project POST /sms/myproject → auto-detect + project ``` ## Supported providers Over 40 providers are auto-detected. Here are the most common ones: | Provider | Detect fields | From | To | Message | |----------|--------------|------|-----|---------| | Twilio | `MessageSid`, `Body` | `From` | `To` | `Body` | | Vonage | `api_key`, `api_secret` | `from`, `msisdn` | `to` | `text` | | Plivo | `MessageUUID` | `From`, `src` | `To`, `dst` | `Text` | | Sinch | `batch_id`, `body` | `from` | `to` | `body` | | Infobip | `messages` | `from` | `to` | `text` | | MessageBird | `originator`, `recipients` | `originator` | `recipients` | `body` | | Telnyx | `messaging_profile_id` | `from` | `to` | `text` | | Bandwidth | `applicationId`, `text` | `from` | `to` | `text` | | Brevo | `sender`, `recipient`, `content` | `sender` | `recipient` | `content` | | Clickatell | `from`, `to`, `text` | `from` | `to` | `text` | | SMS.ru | `api_id`, `msg` | `from` | `to` | `msg` | | SMSC | `login`, `psw`, `phones` | `sender` | `phones` | `mes` | | Generic | _(always matches)_ | `from`/`From`/`sender` | `to`/`To`/`recipient` | `message`/`body`/`text` | Full list: Twilio, Vonage, Plivo, Sinch, Infobip, MessageBird, Telnyx, Bandwidth, Brevo, Termii, Clickatell, MessageMedia, Lox24, Unifonic, Yunpian, Octopush, GatewayApi, SevenIo, SmsFactor, Redlink, OvhCloud, Smsc, 46elks, Mobyt, Smsapi, Sendberry, TurboSms, SimpleTextin, Isendpro, RingCentral, ClickSend, SMS.ru, SMS Aero, Devino, IQSms, MTS, Beeline, Megafon. ## Configuration ### Symfony Notifier Symfony's Notifier component uses DSN-based transport configuration. Every SMS bridge has a configurable host — change it to point at Buggregator. ```dotenv # Default (sends to real Twilio): TWILIO_DSN=twilio://SID:TOKEN@default?from=+1234567890 # Point to Buggregator (explicit provider URL for validation): TWILIO_DSN=twilio://SID:TOKEN@127.0.0.1:8000/sms/twilio?from=+1234567890 # Or use auto-detect: TWILIO_DSN=twilio://SID:TOKEN@127.0.0.1:8000/sms?from=+1234567890 ``` Same pattern for any Symfony SMS bridge: ```dotenv # Vonage VONAGE_DSN=vonage://KEY:SECRET@127.0.0.1:8000/sms/vonage?from=MyApp # Plivo PLIVO_DSN=plivo://AUTH_ID:AUTH_TOKEN@127.0.0.1:8000/sms/plivo?from=+1234567890 # Sinch SINCH_DSN=sinch://ACCOUNT_ID:AUTH_TOKEN@127.0.0.1:8000/sms/sinch?from=+1234567890 ``` > In Docker Compose, replace `127.0.0.1:8000` with the Buggregator service name (e.g., `buggregator:8000`). ### Laravel Laravel doesn't have built-in SMS, but if you use an HTTP-based SMS package, you can override the API base URL: ```php // Example: sending directly via HTTP Http::post('http://127.0.0.1:8000/sms/twilio', [ 'MessageSid' => Str::uuid(), 'From' => '+1234567890', 'To' => $user->phone, 'Body' => "Your code is {$code}", ]); ``` ### Any language / any framework Send an HTTP POST to Buggregator with the provider's payload format: ```bash # Twilio format curl -X POST http://127.0.0.1:8000/sms/twilio \ -H "Content-Type: application/json" \ -d '{"MessageSid":"SM123","From":"+1234","To":"+5678","Body":"Hello!"}' # Generic format (auto-detect) curl -X POST http://127.0.0.1:8000/sms \ -H "Content-Type: application/json" \ -d '{"from":"+1234","to":"+5678","message":"Hello!"}' # Test validation (missing required fields) curl -X POST http://127.0.0.1:8000/sms/twilio \ -H "Content-Type: application/json" \ -d '{"From":"+1234","To":"+5678"}' # Returns 422: {"error":"validation_failed","gateway":"twilio","missing_fields":["MessageSid","Body"]} # But the event is still visible in Buggregator UI with warnings! ``` Both `application/json` and `application/x-www-form-urlencoded` are accepted. --- # SMTP — Email Testing Your app sends emails — registration confirmations, password resets, notifications. You need to verify they look correct without actually delivering them. Buggregator includes a fake SMTP server: point your app's mail config at port `1025` and every email shows up in the UI. No Mailhog, no Mailtrap, no external services — just another module in the same Buggregator instance where you already see your logs and exceptions. ![A captured email with HTML preview](/images/smtp.webp) ## Use cases - **Email template testing** — preview HTML emails with a desktop/mobile viewport switcher to check responsive layouts. - **Transactional email verification** — make sure the right recipients, subject, and content are set before going to production. - **Attachment testing** — verify that attachments are generated correctly and can be downloaded. - **All in one place** — see emails in the same UI as your exceptions, logs, and dumps. ## What you see in the UI - **HTML preview** — rendered email with desktop/mobile device viewport switcher. - **Plain text** — the plain text version of the email. - **Addresses** — From, To, CC, BCC, Reply-To organized by type. - **Attachments** — download or preview any attached file. Inline images display correctly in the HTML preview. - **Raw source** — the raw MIME source for debugging encoding or header issues. ## Configuration Point your app's SMTP settings to `127.0.0.1:1025`. No authentication required. > In Docker Compose, replace `127.0.0.1` with the Buggregator service name (e.g., `buggregator`). ### Laravel ```dotenv MAIL_MAILER=smtp MAIL_HOST=127.0.0.1 MAIL_PORT=1025 ``` ### Spiral Framework ```dotenv MAILER_DSN=smtp://127.0.0.1:1025 ``` ### Symfony ```dotenv MAILER_DSN=smtp://127.0.0.1:1025 ``` ### Magento 2 ```dotenv CONFIG__DEFAULT__SYSTEM__SMTP__TRANSPORT="smtp" CONFIG__DEFAULT__SYSTEM__SMTP__HOST="127.0.0.1" CONFIG__DEFAULT__SYSTEM__SMTP__PORT="1025" ``` or via CLI: ```bash bin/magento config:set system/smtp/transport smtp bin/magento config:set system/smtp/host 127.0.0.1 bin/magento config:set system/smtp/port 1025 ``` ### WordPress Save to the [mu-plugins](https://developer.wordpress.org/advanced-administration/plugins/mu-plugins/) directory (e.g., `smtp.php`): ```php isSMTP(); $phpmailer->Host = '127.0.0.1'; $phpmailer->Port = 1025; } ); ``` ### Any other app Any application that can send email via SMTP works. Set host to `127.0.0.1` and port to `1025`. ## Testing API End-to-end tests often need to check an email: "did the reset mail arrive, and what is the code in it?" The testing API answers that over plain HTTP. Example: your test clicks "Forgot password", waits for the email to `alice@example.com`, and reads the 6-digit code from it. All routes below need the same login as the rest of `/api` when [SSO](/config/sso) is on: send the `X-Auth-Token` header (see [Calling the API from scripts](/config/sso#calling-the-api-from-scripts)). | Method | Path | Answer | |--------|------|--------| | `GET` | `/api/smtp/cursor` | `{"cursor": "2026-11-07T08:30:09.123456789Z"}`: the server time now | | `GET` | `/api/smtp/messages` | messages that match the filters: `{"data": [event, …], "meta": {"total", "limit", "offset"}}` | | `GET` | `/api/smtp/messages/wait` | the first message that matches, as soon as there is one; `408` on timeout | | `GET` | `/api/smtp/stats?project=` | `{"count": 3, "last_received_at": "2026-11-07T08:30:09Z"}`; `last_received_at` is `null` with no mail | | `DELETE` | `/api/smtp/messages?project=` | deletes the messages (of one project, or all): `{"status": true}` | | `GET` | `/api/smtp/message/{uuid}/raw` | the original message source (`Content-Type: message/rfc822`) | | `GET` | `/api/smtp/message/{uuid}/links` | links from the HTML and text parts: `{"data": [{"url", "text", "source"}]}`; `source` is `html` or `text` | | `GET` | `/api/smtp/message/{uuid}/codes?pattern=` | codes found in the text and HTML parts: `{"data": ["482913"], "pattern": "\\b\\d{4,8}\\b"}` | An `event` is a normal Buggregator event: `uuid`, `type` (`smtp`), `timestamp`, `project` and `payload`. The `payload` has `subject`, `from`, `to`, `cc`, `reply_to` (lists of `{"email", "name"}`), `bcc`, `text`, `html` and `raw`. Errors are `{"message", "code"}`. An unknown `uuid` gets `404`. ### Filters `/messages` and `/messages/wait` take the same filters. Every filter you pass must match. | Parameter | Matches when | |-----------|--------------| | `to`, `from`, `cc` | any address or name in that field contains the value, ignoring case (`to=alice` finds `Alice `) | | `subject` | the subject is exactly the value | | `subject_contains` | the subject contains the value (case matters) | | `subject_regex` | the subject matches the [Go regular expression](https://pkg.go.dev/regexp/syntax); an invalid one matches nothing | | `body_contains` | the text or the HTML part contains the value (case matters) | | `project` | the message belongs to that [project](/config/projects) | | `since`, `until` | received at or after / at or before this time: RFC 3339 (`2026-11-07T08:30:00Z`), unix seconds, or unix milliseconds. A value that does not parse is ignored | `/messages` also takes: - `order`: `desc` (newest first, the default) or `asc`. - `limit` and `offset` for pages. No `limit` returns all matches. `meta.total` counts all matches before the page. ### Waiting for an email `/messages/wait` holds the request open until a matching message arrives. It also takes `timeout`: a Go duration such as `10s` or `1m`, default `30s`, at most `60s`. A message that is already stored and matches comes back at once. So take a cursor before the action, and pass it as `since`. Otherwise an old email from an earlier test can match. Example — a password reset test: ```bash # 1. Remember "now" CURSOR=$(curl -s http://127.0.0.1:8000/api/smtp/cursor | jq -r .cursor) # 2. Your test asks the app to send the reset email to alice@example.com # 3. Wait up to 20 seconds for it UUID=$(curl -s -G http://127.0.0.1:8000/api/smtp/messages/wait \ --data-urlencode "since=$CURSOR" \ --data-urlencode "to=alice@example.com" \ --data-urlencode "subject_contains=Reset" \ --data-urlencode "timeout=20s" | jq -r .uuid) # 4. Read the code from it curl -s http://127.0.0.1:8000/api/smtp/message/$UUID/codes # {"data":["482913"],"pattern":"\\b\\d{4,8}\\b"} ``` ### Codes `/codes` looks for a regular expression in the text part and in the HTML part (tags removed). The default `pattern` finds numbers of 4 to 8 digits. Each code is listed once. Pass your own `pattern` for other codes, for example `pattern=[A-Z0-9]{6}`. An invalid pattern gets `400`. ### Attachments `GET /api/smtp/attachments/{uuid}` lists the attachments of a message: `{"data": [{"uuid", "name", "path", "size", "mime"}]}`. It needs the login like the routes above. The download (`/api/smtp/attachments/{event uuid}/{attachment uuid}`) and the preview (`/api/smtp/attachments/{event uuid}/preview/{attachment uuid}`) links stay open: they work only with both ids, which only the protected API gives out. --- # Configuration — Single Sign-On (SSO) Buggregator supports Single Sign-On (SSO) for secure user authentication via OAuth2/OIDC. Supported providers: - [Auth0](https://auth0.com/) - [Google](https://console.cloud.google.com/) - [GitHub](https://github.com/settings/developers) - [Keycloak](https://www.keycloak.org/) - [GitLab](https://gitlab.com/) - Any **generic OIDC** provider For OIDC-compatible providers (Auth0, Google, Keycloak, GitLab, generic OIDC), endpoints are auto-discovered from the provider URL via `.well-known/openid-configuration`. For GitHub, endpoints are hardcoded (GitHub does not support OIDC discovery). ## Configuration ### buggregator.yaml ```yaml auth: enabled: true provider: oidc # auth0, google, github, keycloak, gitlab, oidc provider_url: https://xxx.us.auth0.com client_id: your-client-id client_secret: your-client-secret callback_url: http://localhost:8000/auth/sso/callback scopes: openid,email,profile jwt_secret: your-jwt-signing-secret ``` ### Environment Variables | Variable | Default | Description | |----------|---------|-------------| | `AUTH_ENABLED` | `false` | Enable authentication | | `AUTH_PROVIDER` | `oidc` | Provider type: `auth0`, `google`, `github`, `keycloak`, `gitlab`, `oidc` | | `AUTH_PROVIDER_URL` | — | OIDC issuer URL (e.g., `https://xxx.us.auth0.com`) | | `AUTH_CLIENT_ID` | — | OAuth2 client ID | | `AUTH_CLIENT_SECRET` | — | OAuth2 client secret | | `AUTH_CALLBACK_URL` | — | Callback URL (e.g., `http://buggregator.example.com/auth/sso/callback`) | | `AUTH_SCOPES` | `openid,email,profile` | Comma-separated OAuth2 scopes | | `AUTH_JWT_SECRET` | — | **Required.** Secret for signing internal JWT tokens | > **Important:** `AUTH_JWT_SECRET` is required when authentication is enabled. It is used to sign the internal > session JWT tokens. ## Provider Setup ### Auth0 1. [Sign up](https://auth0.com/signup) for an Auth0 account. 2. Create a new **Regular Web Application**. 3. Note the `Domain`, `Client ID`, and `Client Secret`. 4. In application settings, set **Allowed Callback URLs** to `http:///auth/sso/callback`. 5. Configure Buggregator: ```dotenv AUTH_ENABLED=true AUTH_PROVIDER=auth0 AUTH_PROVIDER_URL=https://.auth0.com AUTH_CLIENT_ID=xxx AUTH_CLIENT_SECRET=xxx AUTH_CALLBACK_URL=http:///auth/sso/callback AUTH_SCOPES=openid,email,profile AUTH_JWT_SECRET=your-secret-key ``` ### Google 1. Go to [Google Cloud Console](https://console.cloud.google.com/apis/credentials). 2. Create a new **OAuth 2.0 Client ID** (Web application type). 3. Add `http:///auth/sso/callback` to **Authorized redirect URIs**. 4. Configure Buggregator: ```dotenv AUTH_ENABLED=true AUTH_PROVIDER=google AUTH_PROVIDER_URL=https://accounts.google.com AUTH_CLIENT_ID=xxx.apps.googleusercontent.com AUTH_CLIENT_SECRET=xxx AUTH_CALLBACK_URL=http:///auth/sso/callback AUTH_JWT_SECRET=your-secret-key ``` ### GitHub 1. Go to [GitHub Developer Settings](https://github.com/settings/developers). 2. Create a new **OAuth App**. 3. Set **Authorization callback URL** to `http:///auth/sso/callback`. 4. Configure Buggregator: ```dotenv AUTH_ENABLED=true AUTH_PROVIDER=github AUTH_CLIENT_ID=xxx AUTH_CLIENT_SECRET=xxx AUTH_CALLBACK_URL=http:///auth/sso/callback AUTH_JWT_SECRET=your-secret-key ``` > **Note:** GitHub does not support OIDC, so `AUTH_PROVIDER_URL` is not needed. ### Keycloak 1. Create a new **Client** in your Keycloak realm. 2. Set **Valid Redirect URIs** to `http:///auth/sso/callback`. 3. Configure Buggregator: ```dotenv AUTH_ENABLED=true AUTH_PROVIDER=keycloak AUTH_PROVIDER_URL=https://keycloak.example.com/realms/your-realm AUTH_CLIENT_ID=xxx AUTH_CLIENT_SECRET=xxx AUTH_CALLBACK_URL=http:///auth/sso/callback AUTH_JWT_SECRET=your-secret-key ``` ### GitLab 1. Go to **Admin Area > Applications** (or **User Settings > Applications** for self-managed). 2. Create a new application with `openid`, `email`, `profile` scopes. 3. Set **Redirect URI** to `http:///auth/sso/callback`. 4. Configure Buggregator: ```dotenv AUTH_ENABLED=true AUTH_PROVIDER=gitlab AUTH_PROVIDER_URL=https://gitlab.com AUTH_CLIENT_ID=xxx AUTH_CLIENT_SECRET=xxx AUTH_CALLBACK_URL=http:///auth/sso/callback AUTH_JWT_SECRET=your-secret-key ``` ### Generic OIDC Any OIDC-compliant provider can be used. The server will auto-discover endpoints from `/.well-known/openid-configuration`. ```dotenv AUTH_ENABLED=true AUTH_PROVIDER=oidc AUTH_PROVIDER_URL=https://your-oidc-provider.com AUTH_CLIENT_ID=xxx AUTH_CLIENT_SECRET=xxx AUTH_CALLBACK_URL=http:///auth/sso/callback AUTH_JWT_SECRET=your-secret-key ``` ## Verifying the Configuration Once you set the environment variables, start your Buggregator server. You should see a Login page with an option to sign in. If everything is set up right, clicking this option will take you to the provider's login page. ![SSO login page](/images/sso-login.webp) After logging in successfully, users will be redirected back to the Buggregator server and logged in. You will see the user's profile information in the bottom left corner of the app. ![User menu with the signed-in user](/images/sso-user-menu.webp) ## Calling the API from Scripts With SSO on, the APIs behind the UI need a login token in the `X-Auth-Token` header. Without it they answer `401`. This covers `/api/events`, Sentry (`/api/sentry/*`), the profiler, the SMTP testing API (`/api/smtp/*`), attachment lists, `/api/metrics`, mock rules (`/api/mocks*`) and Xdebug (`/api/xdebug*`). Since v2.6.0 this includes the Sentry, profiler and SMTP testing APIs. Before, they answered without a token. A test script that reads captured emails must now send the header: ```bash curl http://buggregator.example.com/api/smtp/messages \ -H "X-Auth-Token: $BUGGREGATOR_TOKEN" ``` The token is the one the UI gets after you sign in. It is valid for 30 days. To copy it, open the browser's developer tools on the Buggregator page and read `token` from Local Storage. These stay open, so your apps keep sending events without a token: - event ingestion (Sentry SDK, Ray, Inspector, profiler, SMS, HTTP dumps) and the TCP ports; - the mock server under `/mock/`; - `/api/version`, `/api/settings` and the SSO login pages; - attachment download and preview: `/api/{smtp,http-dump}/attachments/{eventUuid}/{uuid}` and `/api/{smtp,http-dump}/attachments/{eventUuid}/preview/{uuid}`. The UI opens them as plain links, which carry no token. A link needs both the event and the attachment UUID, and with SSO on only signed-in clients (the protected API and the live feed) get those; - Prometheus `GET /metrics` on the main port, when [metrics](/config/metrics) are on and `metrics.addr` is empty. It has counters only, no event content. Set `metrics.addr` to move it to its own port. The live feed needs the same token. A WebSocket client of `/connection/websocket` sends it as `token` in its Centrifugo `connect` command. Without a valid token the connect gets error `109 unauthorized`, the socket is closed with code `1008`, and no events are pushed. The UI does this by itself after you sign in. With SSO off, nothing needs a token. ### Troubleshooting If you encounter issues during the authentication process, ensure that: - All environment variables are correctly set without any typos. - The callback URL in your provider's configuration matches the `AUTH_CALLBACK_URL` you specified. - `AUTH_JWT_SECRET` is set (it is required for session management). - For OIDC providers, the `AUTH_PROVIDER_URL` points to the issuer root (e.g., `https://xxx.auth0.com`, not `https://xxx.auth0.com/authorize`). --- # VarDumper — Variable Dumps You call `dump()` or `dd()` and the output lands in the browser response, mixes with HTML, or gets lost in CLI output. With Buggregator, dumps go to a dedicated TCP server and show up in a clean UI — alongside your logs, exceptions, and everything else. No browser pollution, no output buffering issues, no lost dumps in long-running processes. ![VarDumper dumps](/images/var-dumper.webp) ## Use cases - **Long-running apps** (RoadRunner, Swoole, queue workers) — `dd()` doesn't print to a browser here, but Buggregator catches it. - **API development** — dump variables without breaking JSON responses. - **Microservices** — collect dumps from all services in one place. - **IDE integration** — click the source location to jump straight to the file in your editor. ## What you see in the UI - **Dumped value** — full variable content with type information, rendered as an interactive expandable tree. - **Source location** — file and line where `dump()` was called. Clickable — opens in your IDE. - **Variable name and label** — custom labels if provided. - **Syntax highlighting** — for text-only dumps (see below). ## Setup Install the Symfony VarDumper component: ```bash composer require --dev symfony/var-dumper ``` Set two env variables to redirect output to Buggregator: ```dotenv VAR_DUMPER_FORMAT=server VAR_DUMPER_SERVER=127.0.0.1:9912 ``` > In Docker Compose, replace `127.0.0.1` with the Buggregator service name (e.g., `VAR_DUMPER_SERVER=buggregator:9912`). That's it. Use `dump()` and `dd()` as usual — the output goes to Buggregator. If your project doesn't use `.env` files, set via PHP: ```php $_SERVER['VAR_DUMPER_FORMAT'] = 'server'; $_SERVER['VAR_DUMPER_SERVER'] = '127.0.0.1:9912'; ``` ## Performance tip Large objects with deep nesting can slow down the browser. Limit the preview depth on the events list page: ```bash docker run --pull always \ -p 127.0.0.1:8000:8000 \ -p 127.0.0.1:9912:9912 \ -e VAR_DUMPER_PREVIEW_MAX_DEPTH=3 \ ghcr.io/buggregator/server:latest ``` The full dump is still available when you open the event detail page. ## Syntax highlighting Dump a text string with syntax highlighting using [Buggregator Trap](../trap/what-is-trap.md): ```php $code = <<context(language: 'php'); ``` ![A dump with SQL code highlighting](/images/var-dumper-code-highlight.webp) ## Buggregator Trap Consider using [Buggregator Trap](../trap/what-is-trap.md) instead of raw VarDumper — it uses VarDumper under the hood but adds extra features like `trap()`, `tr()`, and `td()` helpers. --- # Configuration — Webhooks Webhooks allow Buggregator to send HTTP POST notifications to external services when events are received. This enables integration with tools like [n8n](https://n8n.io/), Slack, PagerDuty, or any custom endpoint. ## Why Use Webhooks? - **Automate Tasks:** Automatically trigger actions in other services when events happen in Buggregator. - **Integrate with Other Tools:** Connect Buggregator with messaging apps, issue tracking software, or custom apps. ## Configuration Webhooks are configured in `buggregator.yaml`: ```yaml webhooks: - event: "*" # Fire on any event type url: https://slack.example.com/webhook headers: Authorization: "Bearer token123" verify_ssl: false retry: true - event: sentry # Fire only on Sentry events url: https://pagerduty.example.com/alert - event: smtp # Fire only on SMTP events url: https://my-app.example.com/email-hook ``` **Fields:** | Field | Required | Default | Description | |-------|----------|---------|-------------| | `event` | Yes | — | Event type to trigger on, or `"*"` for all events | | `url` | Yes | — | URL to send the POST request to | | `headers` | No | — | Additional HTTP headers to include | | `verify_ssl` | No | `false` | Whether to verify SSL certificates | | `retry` | No | `true` | Retry up to 3 times with exponential backoff on failure | ### Supported Event Types - `sentry` - `monolog` - `var-dump` - `ray` - `inspector` - `http-dump` - `profiler` - `smtp` - `sms` - `*` (all events) ### Webhook Payload Each webhook sends a JSON payload with the following structure: ```json { "uuid": "event-uuid", "type": "sentry", "payload": { ... }, "timestamp": 1234567890.123, "project": "default" } ``` ## Docker Examples ### Docker Compose ```yaml services: buggregator: image: ghcr.io/buggregator/server:latest ports: - 127.0.0.1:8000:8000 volumes: - ./buggregator.yaml:/buggregator.yaml ``` With `buggregator.yaml`: ```yaml webhooks: - event: "*" url: https://hooks.slack.com/services/xxx headers: Content-Type: application/json ``` ### Docker Run with Config File ```bash docker run --pull always \ -p 127.0.0.1:8000:8000 \ -v ./buggregator.yaml:/buggregator.yaml \ ghcr.io/buggregator/server:latest ``` > **Tip:** You can test webhooks using tools like https://webhook.site. ## Delivery Tracking Buggregator tracks every webhook delivery attempt. You can view the delivery history for each webhook via the API, including the response status code and payload. This helps you diagnose issues when webhooks fail to reach their destination. --- # Xdebug Proxy — Debug PHP With or Without an IDE Buggregator receives Xdebug sessions from PHP. Two ways to use it: - **With your IDE.** Buggregator sits in the middle and passes the session to the IDE unchanged. The IDE steps and sets breakpoints. The **Xdebug** page and an AI assistant over [MCP](/config/mcp) only look at the same paused session. - **Without an IDE.** No IDE answers, so Buggregator drives the session itself. You step through the code on the **Xdebug** page in the browser. Example: a script on a test server stops at `xdebug_break()`, and you step over it line by line, with no PhpStorm set up. ``` PHP / Xdebug ──▶ Buggregator :9003 ──▶ IDE (PhpStorm, VS Code…), if one answers │ ├── Xdebug page: reads; steps when no IDE drives └── MCP tools ◀── AI assistant ``` While an IDE is attached, it drives. Buggregator then only reads where the script stopped: the stack, variables and source. > The proxy is available since server v2.6.0, off by default. Driving a session without an IDE is available since > server v2.7.0. ## Use cases - **Ask an AI assistant about a paused request** — "what is in `$order` here?", while you stay at the breakpoint. - **Show a session to a colleague** — they open the Xdebug page and see the same stack and variables. - **Keep the IDE in charge** — the proxy passes everything through, so the IDE works as before. - **Debug where there is no IDE** — a CI runner, a colleague's machine, a container: step through the code in the browser. ## Setup ### 1. Turn the proxy on ```yaml xdebug: enabled: true addr: 127.0.0.1:9003 # where Xdebug connects ide_addr: 127.0.0.1:9004 # where your IDE listens allow_eval: false # let MCP clients and watches evaluate PHP expressions mode: auto # proxy, auto or standalone; see Modes pause_on_first_line: false # without an IDE: stop at the first line idle_timeout: 10m # without an IDE: release a session paused this long; 0 = never allow_control: true # let MCP clients step, continue and stop ``` Or with environment variables: | Variable | Default | Description | |----------|---------|-------------| | `XDEBUG_PROXY_ENABLED` | `false` | Turn the proxy on (`true`, `1` or `yes`) | | `XDEBUG_PROXY_ADDR` | `127.0.0.1:9003` | Where Xdebug connects | | `XDEBUG_PROXY_IDE_ADDR` | `127.0.0.1:9004` | Where the IDE listens for debug connections | | `XDEBUG_PROXY_ALLOW_EVAL` | `false` | Allow evaluating PHP expressions (see [Eval](#eval)) | | `XDEBUG_PROXY_MODE` | `auto` | `proxy`, `auto` or `standalone` (see [Modes](#modes)). An unknown value falls back to `auto`, with a warning in the log | | `XDEBUG_PROXY_PAUSE_ON_FIRST_LINE` | `false` | A session driven by Buggregator stops at the first line. Otherwise it runs to a breakpoint or `xdebug_break()` | | `XDEBUG_PROXY_ALLOW_CONTROL` | `true` | Let MCP clients drive a session Buggregator drives (see [MCP tools](#mcp-tools)); `false` = Xdebug tools only read (except `xdebug_eval` with `allow_eval`) | | `XDEBUG_PROXY_IDLE_TIMEOUT` | `10m` | A session paused by Buggregator with no command this long is released, and the script runs to the end. A Go duration (`90s`, `10m`); `0` = never. A bad value keeps `10m`, with a warning | For the MCP tools, also turn on [MCP](/config/mcp) (`mcp.enabled: true`). ### 2. Free the port for the proxy The proxy and the IDE cannot both listen on port 9003 on one machine. Pick one of two setups. **A. Move the IDE to another port.** Xdebug stays unchanged. - IDE: set the Xdebug debug port to `9004` (PhpStorm: *Settings → PHP → Debug → Xdebug → Debug port*). - Buggregator: the defaults (`addr: 127.0.0.1:9003`, `ide_addr: 127.0.0.1:9004`). - Xdebug: unchanged (`xdebug.client_port=9003`). **B. Keep the IDE on 9003.** Point Xdebug at the proxy instead. - IDE: unchanged (port `9003`). - Buggregator: `addr: 127.0.0.1:9010`, `ide_addr: 127.0.0.1:9003`. - Xdebug: `xdebug.client_port=9010`. ### 3. Point Xdebug at Buggregator A typical `php.ini` for setup A: ```ini xdebug.mode=debug xdebug.client_host=127.0.0.1 xdebug.client_port=9003 xdebug.start_with_request=trigger ``` Then start a debug session in the IDE as usual and stop at a breakpoint. ### Docker When Buggregator runs in a container and the IDE on your machine, the proxy must listen on all interfaces inside the container and dial the host. **PHP in a container too.** PHP reaches the proxy over the Docker network, so port 9003 is not published, and the IDE can stay on port 9003: ```yaml services: buggregator: image: ghcr.io/buggregator/server:latest ports: - 127.0.0.1:8000:8000 environment: XDEBUG_PROXY_ENABLED: "true" XDEBUG_PROXY_ADDR: 0.0.0.0:9003 XDEBUG_PROXY_IDE_ADDR: host.docker.internal:9003 extra_hosts: - host.docker.internal:host-gateway # needed on Linux ``` In the PHP container, set `xdebug.client_host` to the Buggregator service name (e.g., `buggregator`). **PHP on your machine.** Then Xdebug needs the proxy on a host port, and that port cannot also be the IDE's. Publish 9003 and move the IDE to 9004: ```yaml ports: - 127.0.0.1:8000:8000 - 127.0.0.1:9003:9003 environment: XDEBUG_PROXY_ENABLED: "true" XDEBUG_PROXY_ADDR: 0.0.0.0:9003 XDEBUG_PROXY_IDE_ADDR: host.docker.internal:9004 ``` Set the IDE's Xdebug debug port to `9004`, and keep `xdebug.client_host=127.0.0.1`, `xdebug.client_port=9003`. > The proxy has no login of its own. Anyone who can reach its port can start a session. Keep it on > `127.0.0.1` or inside your Docker network. ## Modes `mode` decides what happens when a session arrives. | Mode | IDE answers | No IDE answers | |------|-------------|----------------| | `proxy` | the IDE drives | Buggregator detaches; the script runs on as if there were no debugger | | `auto` (default) | the IDE drives | Buggregator drives the session | | `standalone` | Buggregator does not call the IDE | Buggregator drives the session | Change the mode for new sessions without a restart: on the **Xdebug** page, click the **Mode: …** tag or the gear (**Debugger settings**), pick **Proxy to IDE**, **Auto** or **Standalone**, and **Save**. The same dialog has the **Pause on the first line** switch. Or use `PUT /api/xdebug/settings` (see [HTTP API](#http-api)). Sessions that already run keep how they started. The change is not written to the config: after a restart, the config value applies again. ## Debug without an IDE 1. Turn the proxy on. The default `mode: auto` is enough. No IDE needs to listen on `ide_addr`. 2. Tell the script where to stop. Any of these: - a [breakpoint](#breakpoints) on the page: type `/app/src/Cart.php:42` in **Breakpoints**, or click a line number while a session is paused; - `xdebug_break();` in the code; - **Pause on the first line** (`pause_on_first_line: true`): every session stops before its first line runs. 3. Run the request with Xdebug, e.g. `php -d xdebug.mode=debug -d xdebug.start_with_request=yes script.php`. 4. Open the **Xdebug** page. The session is **Paused**. Step with the buttons above the code. With none of these, the script runs to the end and does not stop. What the buttons do: | Button | What happens | |--------|--------------| | **Continue** | Runs to the next breakpoint or `xdebug_break()`, or to the end | | **Step over** | The next line; runs a function call without stopping in it | | **Step into** | The next line; goes into a function call | | **Step out** | Runs to the end of the current function and stops in the caller | | **Release** | Lets the script run to the end without stopping again | | **Stop** | Ends the request now. The rest of the script does not run, so work can stay half done. Asks first: **Stop this request?**, with **Stop request**, **Release instead** and **Cancel** | Step over, Step into and Step out are icons; hover one for its name. Below 1180 px wide, Continue, Release and Stop lose their labels too. While an IDE drives the session, the buttons are hidden and the page says «Driven by your IDE». ### Stop or release? - **Release** when you are done looking: the script finishes normally, as if no debugger had been there. - **Stop** when the rest must not run: e.g. the next line sends an email. A stopped request may leave work half done: a file half written, a record without its children. ### The idle guard A paused script holds resources: a PHP-FPM worker, the session lock, open database transactions. A session that Buggregator paused and nobody touched for `idle_timeout` (10 minutes by default) is released: the script runs to the end. The bar above the code counts down: «auto-release in 9:12» (on narrower screens only the clock and `9:12`). The session then closes with `closed_reason` `idle_detached`, and the page says «Released after 10 minutes without a command». Every step, and every read that reaches Xdebug, starts the timer again. Set `idle_timeout: 0` to turn the guard off. ### Who can step Anyone who can reach the API can step, stop and release sessions driven by Buggregator. Keep port 8000 on `127.0.0.1`, or turn on [SSO](/config/sso): the control routes need the same login as the rest of `/api`. ## Breakpoints A breakpoint stops a session that Buggregator drives at a line, or when an exception is thrown. Breakpoints are saved: every new session gets them before the script runs. A change while a session is paused goes to it at once; while the script runs, at its next pause (the row says **next pause**). Add one in the **Breakpoints** panel: | Type in the field | Stops | |-------------------|-------| | `/app/src/Services/CartService.php:43` | at line 43 of that file | | `RuntimeException` | when a `RuntimeException` is thrown | | `*` | on every exception | An exception breakpoint matches the thrown class and its parent classes, not interfaces: `Exception` stops on a `RuntimeException`, `Throwable` never stops. For every exception, use `*`. The path is absolute, as PHP sees it: inside the container, not on your machine. The field suggests files from earlier pauses. While a session is paused, click a line number in the code to add or remove a breakpoint there. Each row has a checkbox to turn the breakpoint off and on, a remove button, and, while a session is paused, how often it was hit (`3×`). A line breakpoint can have a condition, a PHP expression: `$total > 100` stops only when it is true. Conditions run PHP, so they need `allow_eval: true`; with eval off, adding one is refused. A breakpoint with a condition saved while eval was on is skipped after eval is turned off (the row says **skipped · eval off**). If a line has no code, Xdebug moves the breakpoint to the next line with code; the row says «Xdebug moved it: no code on line 3 → 4». A breakpoint in a loop stops on every pass. Breakpoints live in the database. With the default in-memory database they are gone after a restart; with a [database file](/config/database) they stay. Sessions an IDE drives use the IDE's breakpoints, not these. The page shows the IDE's breakpoints in the gutter, read-only. ## What happens to a session - Each PHP request with Xdebug is one session. Several requests at once each get their own session. - The IDE gets the session unchanged. It does not see what the page or the MCP tools read. - **No IDE answers when the session starts**: depends on the [mode](#modes). In `proxy` mode Buggregator detaches, and the script runs on as if there were no debugger. In `auto` and `standalone` Buggregator drives the session. - **The IDE goes away later**: Buggregator detaches in every mode (`closed_reason` `ide_closed`), and the script runs on. - A closed session stays in the list for 10 minutes with its reason, unless you dismiss it. At most the 50 newest closed sessions are kept. ## The Xdebug page The **Xdebug** item appears in the sidebar only when the proxy is on. - **Sessions** — state (Paused, Running, Released, Detached, Stopped…), the request (`GET /checkout?step=2`, or the CLI command), file and line, and who drives it: `here` (Buggregator), `IDE`, or `no IDE`. - **Controls** — Continue, Step over, Step into, Step out, Release and Stop, for a session driven by Buggregator (see [Debug without an IDE](#debug-without-an-ide)). While an IDE drives, the page says so and the buttons are hidden. - **Code** — the source around the paused line, with breakpoints in the gutter. - **Breakpoints** — the saved breakpoints, see [Breakpoints](#breakpoints). - **Variables** — locals, superglobals and user constants. Objects and arrays load when you expand them. - **Call stack** — vendor frames fold into one line. Pick a frame to see its source and variables. - **Watch** — expressions evaluated once per pause. Needs `allow_eval: true`; otherwise the page shows the setting to turn on. - **Agent activity** — the MCP calls an AI assistant made in this session, including refused ones. Values can be read only while the script is paused. While it runs, the page shows the last known line. ## MCP tools With `mcp.enabled: true`, MCP clients get these tools. These read; `xdebug_sessions` and `xdebug_breakpoints` work without a pause, the others need a paused session: | Tool | What it returns | |------|-----------------| | `xdebug_sessions` | Sessions, including ones closed in the last 10 minutes: id, entry file, state, current file and line | | `xdebug_location` | Current file and line, the function, and the source lines around it | | `xdebug_stack` | The call stack, one frame per level; 0 is the current one | | `xdebug_variables` | Variables of a frame (locals by default). Arrays and objects show their first level | | `xdebug_property` | One variable or property by its full name (`$user->address`, `$items[0]`) with its children; strings up to 64 KB | | `xdebug_eval` | The value of a PHP expression in the current frame. Present only with `allow_eval: true` | | `xdebug_breakpoints` | The saved breakpoints; with `session_id`, each one's state in that session (e.g. resolved, skipped), resolved line and hit count | These drive a session, like the buttons on the page. `xdebug_step`, `xdebug_continue` and `xdebug_stop` work only on a session Buggregator drives; while an IDE drives, they are refused. `xdebug_wait` also returns a session paused in the IDE. `xdebug_breakpoint_set` and `xdebug_breakpoint_remove` always save, but saved breakpoints never reach a session an IDE drives. On by default; `xdebug.allow_control: false` (env `XDEBUG_PROXY_ALLOW_CONTROL=false`) removes them, and the Xdebug tools only read again (except `xdebug_eval` with `allow_eval`). | Tool | What it does | |------|--------------| | `xdebug_wait` | Waits until a session pauses (or the one given by `session_id`): `timeout_seconds` 1–60, default 60. Returns at once if one already is | | `xdebug_step` | One step: `mode` `over` (default), `into` or `out`. Waits for the next pause (`timeout_seconds` 1–30, default 30); returns the file, line, function and source around it, or that the script ended | | `xdebug_continue` | Runs to the next breakpoint or `xdebug_break()`; the same wait and answer as `xdebug_step` | | `xdebug_stop` | `mode` `detach` (default): the script runs to the end. `stop`: ends the request now, work can stay half done | | `xdebug_breakpoint_set` | Saves a breakpoint: `file` (absolute path as PHP sees it) and `line`, or `exception` (a class, e.g. `RuntimeException`, or `*` for any). `condition` only with `allow_eval` | | `xdebug_breakpoint_remove` | Removes a saved breakpoint by `id` | `session_id` can be left out when exactly one session is paused. Example conversation with an assistant, while the IDE stopped at a breakpoint: - "Where did the script stop?" → `xdebug_location` - "What is in `$user`?" → `xdebug_property` with `$user` Without an IDE, an agent can debug on its own: set a breakpoint with `xdebug_breakpoint_set` (or put `xdebug_break();` in the code), send the request, then `xdebug_wait`, read with `xdebug_variables`, step with `xdebug_step`, and finish with `xdebug_stop`. ## Eval `allow_eval` is off by default. With it on, MCP clients (`xdebug_eval`) and the page's watches can evaluate PHP expressions inside the debugged request. An expression can change state: `$order->pay()` really runs. Turn it on only where you trust everyone who can reach the API and MCP. With eval off, `xdebug_eval` is not offered, and `POST /api/xdebug/sessions/{id}/eval` answers `403 eval_disabled`. ## HTTP API The page uses these routes. They need the same login as the rest of `/api` when [SSO](/config/sso) is on. Errors are `{"code", "error", "state"?}`. | Method | Path | Answer | |--------|------|--------| | `GET` | `/api/xdebug` | `{"enabled", "addr", "ide_addr", "allow_eval", "allow_control", "mode", "pause_on_first_line", "idle_timeout_seconds"}`; also answers with `"enabled": false` when the proxy is off | | `PUT` | `/api/xdebug/settings` | body `{"mode": "proxy\|auto\|standalone", "pause_on_first_line": true}`, `Content-Type: application/json`; a field left out keeps its value; applies to new sessions, not saved; answers `{"mode", "pause_on_first_line", "idle_timeout_seconds"}` | | `GET` | `/api/xdebug/sessions` | live and closed sessions | | `GET` | `/api/xdebug/sessions/{id}` | one session | | `DELETE` | `/api/xdebug/sessions/{id}` | dismiss a closed session: `204`; a live one: `409 session_live` | | `GET` | `/api/xdebug/sessions/{id}/stack` | frames | | `GET` | `/api/xdebug/sessions/{id}/contexts?frame=0` | `0` Locals, `1` Superglobals, `2` User defined constants | | `GET` | `/api/xdebug/sessions/{id}/variables?frame=0&context=0` | variables | | `GET` | `/api/xdebug/sessions/{id}/property?name=$user&frame=0&context=0&page=0` | one variable with children | | `GET` | `/api/xdebug/sessions/{id}/source?file=…&begin=1&end=120` | source lines, at most 2000 | | `GET` | `/api/xdebug/sessions/{id}/breakpoints` | an IDE session: the IDE's breakpoints. A session driven here: the saved breakpoints with `state`, `resolved_line`, `hit_count` | | `POST` | `/api/xdebug/sessions/{id}/eval` | body `{"expression": "count($items)"}`, `Content-Type: application/json`; needs `allow_eval` | | `GET` | `/api/xdebug/sessions/{id}/agent-log` | the last 200 MCP calls of the session | | `GET` | `/api/xdebug/breakpoints` | saved breakpoints: `id`, `type` (`line` or `exception`), `file` (a `file://` URI), `line`, `exception`, `condition`, `enabled`, `source` (`ui` or `mcp`), `created_at` | | `POST` | `/api/xdebug/breakpoints` | body `{"type": "line", "file": "file:///app/src/Cart.php", "line": 42}` or `{"type": "exception", "exception": "RuntimeException"}`, optional `condition`, `enabled`; `201` and the breakpoint | | `PATCH` | `/api/xdebug/breakpoints/{id}` | the same fields; a field left out keeps its value | | `DELETE` | `/api/xdebug/breakpoints/{id}` | `204` | | `GET` | `/api/xdebug/files?q=cart&limit=20` | files seen in earlier pauses and breakpoints, for suggestions | | `POST` | `/api/xdebug/sessions/{id}/run` | continue; also `step-into`, `step-over`, `step-out`, `stop`, `detach` (release). Body `{}`, `Content-Type: application/json`. Answers the session at once (state `running`); the next pause comes as `session.status` | While the script is not paused, reads and controls answer `409 not_paused`. A control on a session the IDE drives answers `409 ide_attached`. Other codes: `400 bad_request` (a missing or bad parameter, an unknown mode), `403 eval_disabled` (a breakpoint condition with eval off), `403 cross_site` (a write sent from another site), `404 not_found`, `415 unsupported_media_type` (eval, a control, settings or a breakpoint without JSON), `422 xdebug_error` (Xdebug refused the read), `502 xdebug_failed`, `504 timeout`. ```json {"code": "not_paused", "error": "session is not paused (the script is running or has not stopped at a breakpoint yet)", "state": "stopped"} {"code": "bad_request", "error": "mode must be proxy, auto or standalone, got \"nope\""} {"code": "bad_request", "error": "a line breakpoint needs file and line (>= 1)"} {"code": "eval_disabled", "error": "a breakpoint condition is PHP code: it needs xdebug.allow_eval"} ``` A session's `state` is one of `starting`, `break`, `running`, `stopping`, `stopped`, `detached`. A closed session also has `closed_reason`: `ide_unreachable`, `ide_closed`, `engine_closed`, `stopped`, `detached` (released from the page or by an agent) or `idle_detached` (released by the idle guard). Session fields for driving: `driver` (`ide` or `here`), `last_continuation_by` (`ui`, `agent` or `null`), and `idle_deadline` (when the idle guard releases a paused session; `null` otherwise). ### WebSocket Events go to the `xdebug` channel: `session.created`, `session.status`, `session.closed`, `session.idle` (a new `idle_deadline`), `breakpoints.changed` (the full list), `breakpoint.resolved` (where Xdebug set it), `agent.call.started`, `agent.call`. `session.status` carries `pause_seq`, which goes up by one on every new pause: re-read the session when it changes. --- # XHProf — Performance Profiling Your app is slow and you don't know why. Memory grows and you can't find the leak. XHProf profiling with Buggregator lets you see exactly which functions consume CPU, wall time, and memory — without setting up Blackfire or any paid profiling service. Profile data goes to the same Buggregator where you already see your exceptions and logs. Watch introduction video on [YouTube](https://www.youtube.com/watch?v=2QbgjIVnz78). ## Use cases - **Find slow functions** — the Call Graph and Top Functions table show exactly where time is spent. - **Detect memory leaks** — track memory allocation per function in long-running workers and daemons. - **Measure optimizations** — compare two profiler runs side-by-side to verify your changes actually helped. - **Profile any request** — works with web requests, CLI commands, queue jobs, and any PHP code. - **All in one place** — profiling data next to exceptions, logs, and dumps in the same dashboard. ## Analysis modes ### Call Graph Function calls as a tree. Nodes colored from white to dark red — the darker, the more resources consumed. ![XHProf call graph](/images/xhprof-callgraph.webp) ### Flame Graph Stacked function calls showing where time is spent. Useful for spotting repetitive or time-consuming operations. ![XHProf flame graph](/images/xhprof-flamegraph.webp) ### Top Functions Ranked table of the most expensive function calls — CPU time, wall time, memory, and call count. ![XHProf top functions](/images/xhprof-top-functions.webp) ### Profile Comparison Compare two profiler runs side-by-side. See performance deltas (faster/slower) for CPU time, wall clock time, and memory usage, with per-function percentage changes. ## Setup ### 1. Install the XHProf extension ```bash pear channel-update pear.php.net pecl install xhprof ``` ### 2. Install the profiler package #### Laravel ```bash composer require --dev maantje/xhprof-buggregator-laravel ``` [Package documentation](https://github.com/maantje/xhprof-buggregator-laravel) #### Spiral Framework ```bash composer require --dev spiral/profiler:^3.0 ``` [Package documentation](https://github.com/spiral/profiler/tree/3.0) #### Symfony Framework Please mind, bundle in early development stage - feedback much appreciated ```bash composer require --dev velpl/buggregator-profiler-bundle:^0.3 ``` [Package documentation](https://github.com/velPL/buggregator-profiler-bundle) #### Any PHP project ```bash composer require --dev spiral-packages/profiler ``` ```php use SpiralPackages\Profiler\Profiler; use SpiralPackages\Profiler\DriverFactory; use SpiralPackages\Profiler\Storage\WebStorage; use Symfony\Component\HttpClient\NativeHttpClient; $storage = new WebStorage( new NativeHttpClient(), 'http://127.0.0.1/api/profiler/store', ); $profiler = new Profiler( storage: $storage, driver: DriverFactory::detect(), appName: 'My app', tags: ['env' => 'local'], ); $profiler->start(); // Your code here $profiler->end(); ``` ### 3. Configure the endpoint ```dotenv PROFILER_ENDPOINT=http://profiler@127.0.0.1:8000 PROFILER_APP_NAME="My app" ``` > In Docker Compose, replace `127.0.0.1` with the Buggregator service name. ## Custom client integration If you're building a custom profiler client, there are three ways to send data: - **HTTP auth** — add `profiler` to the URL: `http://profiler@127.0.0.1:8000` - **Header** — send `X-Buggregator-Event: profiler` or `X-Profiler-Dump: true` - **Endpoint** — POST to `/api/profiler/store` --- # Contributing to Buggregator We're excited to invite you to contribute to the project! Your involvement is crucial, whether it's reporting bugs, suggesting new features, or any other form of contribution. To get started, simply [create an issue](https://github.com/buggregator/server/issues) or submit a pull request on our GitHub repository. In our repository, we categorize issues that are open for community contribution using the [`for contributors`](https://github.com/buggregator/server/issues?q=is%3Aissue+is%3Aopen+label%3A%22for+contributors%22) label. This makes it easier for you to find ways to participate. Additionally, we use labels such as `c:easy`, `c:medium`, and `c:difficult` to indicate the complexity level of issues, helping you choose tasks that match your skill level. ## Benefits Contributing to open source projects offers a wealth of benefits, particularly for junior developers. **Here's why you should consider getting involved:** 1. **Learning Through Practical Experience:** Open source projects provide a platform to work with new technologies and frameworks that you might not encounter in your regular job. It's a fantastic way to broaden your technical horizons. 2. **Building a Professional Network:** By participating in open source, you connect with a global community of developers. This network is invaluable for exchanging knowledge, learning from others' experiences, and sharing your own insights. 3. **Enhancing Your Résumé:** Contributions to open source are often highly regarded by employers. They showcase your proactive nature, technical skills, and ability to collaborate effectively in a team. 4. **Gaining Insight into Best Practices:** Engaging with open source projects exposes you to code reviews and feedback from various developers. This experience is crucial for understanding diverse coding styles and improving your own coding practices. 5. **Making a Real-World Impact:** Your contributions can significantly influence the project and its users. The satisfaction of seeing your code being used and appreciated by others is incredibly rewarding. **Help us enhance Buggregator and make a real difference!** **We appreciate any contributions to help make Buggregator better!** ## Repositories There are the following repositories in the Buggregator project: 1. [Server](https://github.com/buggregator/server). Manages and sends events to the client. It also serves as a REST API endpoint for event requests. 2. [Frontend](https://github.com/buggregator/frontend). Allows clients to view incoming events like variable dumps. 3. [Trap](https://github.com/buggregator/trap). A lightweight alternative to the full Buggregator server, designed for local debugging. 4. [Documentation](https://github.com/buggregator/docs). Contains all the documentation for the Buggregator project. 5. [Site](https://github.com/buggregator/buggregator.dev). The official website for Buggregator. 6. [PHPStorm Plugin](https://github.com/buggregator/phpstorm-plugin). A plugin for PHPStorm that integrates with Buggregator. --- # Contributing — Documentation Buggregator uses [VitePress](https://vitepress.dev/) for its documentation. This makes it easy to contribute to the project's documentation by following the steps below. ## Getting Started ### Clone the Repository First of all you need to clone the repository to your local machine. ```bash git clone git@github.com:buggregator/docs.git ``` > **Note**: If you don't have access to the repository, you can fork it and clone your forked repository. ### Install Dependencies After cloning the repository, navigate to the project directory and install the dependencies. ```bash npm install ``` ### Start the Development Server To start the development server and preview the documentation, run the following command: ```bash npm run docs:dev ``` This command will start a local development server and open the documentation in your default browser. ## Structure The documentation is structured as follows: - `docs/`: Contains the documentation files. - `docs/.vitepress/config.mts`: Site configuration and navigation. All you need is to edit the markdown files in the `docs/` directory. If you want to add a new page, create a new markdown file in the `docs/` directory and add it to the navigation in the `docs/.vitepress/config.mts` file. --- That's it! You're now ready to contribute to the Buggregator documentation. --- # Contributing — Frontend side [The Frontend Part](https://github.com/buggregator/frontend) is what users interact with. It displays the events and information processed by the server in a user-friendly way. Users can see live updates of events like errors or logs. ## Key Technologies: - [VueJs 3](https://v3.vuejs.org/) - This framework builds the interactive user interface. - [TailwindCSS](https://tailwindcss.com/) - Styles the frontend, making it look good and responsive. - [Storybook](https://storybook.js.org/) - Helps us develop and organize UI components. This architecture supports a robust system for monitoring and managing application events. As a contributor, your work in either part plays a crucial role in enhancing Buggregator's functionality and user experience. If you have any specific areas you're interested in or questions about the architecture, feel free to ask! ## Server requirements 1. NodeJS >=20.x (22.x is prefare) 2. Yarn >=1.22.x ## Installation 1. Clone repository `git clone https://github.com/buggregator/frontend.git` 2. Install dependencies `yarn install` 3. Run NodeJS server `yarn dev` 4. Open http://localhost:3000 In dev mode you are able to see Storybook components in isolation with mocked data by the link http://localhost:6006. --- ### Now you can start developing your own features and share them with the community! --- # Contributing — Server side [The Server Part](https://github.com/buggregator/server) is where all the data processing and management happen. It's crucial for handling the information that flows through Buggregator. 1. **Event Processing:** This part receives information (like errors or logs) from applications. It organizes and processes these events. 2. **API Communication:** It also communicates with clients through REST API and WebSocket, sending and receiving data as needed. ## Key Technologies Buggregator v2.0 is written in Go as a single self-contained binary: - [Go](https://go.dev/) — the server language - [SQLite](https://www.sqlite.org/) (via [modernc.org/sqlite](https://pkg.go.dev/modernc.org/sqlite)) — embedded database, no external server needed - Built-in WebSocket server implementing the [Centrifugo v5](https://centrifugal.dev/) protocol - Embedded SPA frontend (compiled into the binary via `go:embed`) ## Architecture ### Module System Every feature (Sentry, Ray, Monolog, etc.) is a **module** implementing the `module.Module` interface. Modules are either HTTP-based or TCP-based: - **HTTP modules** return an `HTTPIngestionHandler` with `Priority()`, `Match()`, and `Handle()`. Lower priority runs first. The http-dump module has priority 9999 as the catch-all. - **TCP modules** return `[]tcp.ServerConfig` with connection handlers (Monolog, VarDumper) or self-managed servers (SMTP). ### Ingestion Pipeline 1. **Detect** — extract event type/project from URI userinfo, headers, or Basic Auth 2. **Match** — try handlers in priority order; first match wins 3. **Handle** — parse request body, return `event.Incoming` 4. **Store & Broadcast** — store in SQLite, build preview, broadcast via WebSocket, notify modules ### Storage Single implementation: `SQLiteStore` using pure Go SQLite. Migrations live in each module and run automatically on startup. ## Server Requirements - Go 1.26+ - Make (for build commands) - PHP and Composer, for the first `make build` (it compiles the VarDumper parser from `php/vardumper`) ## Build & Development ```bash # Full build (downloads frontend, builds PHP parser for VarDumper, compiles binary) make build # Quick Go compilation check go build ./... # Run all tests go test ./... # Run a single test go test ./internal/server/http/ -run TestAPI_Version # Cross-compile make build-cross GOOS=darwin GOARCH=arm64 ``` ## Installation 1. **Docker:** Use the Docker Compose setup for a quick dev environment. See the [Docker development guide](../cookbook/docker-install). 2. **Manual:** Download dependencies and build from source. See the [manual installation guide](../cookbook/manual-install.md). --- # Cookbook — Dev environment using Docker Compose This guide will help you quickly set up a local development environment for Buggregator. ## 1. Clone the Repository Start by cloning the repository: ```bash git clone git@github.com:buggregator/server.git cd server ``` > **Note:** If you don't have access, fork the repository and clone your fork instead. ## 2. Start with Docker Compose The repository has a `docker-compose.yaml` with the Buggregator server and a Laravel example app that sends every kind of event. ```bash docker compose up --build ``` This will: - Build the Buggregator image from the `Dockerfile` - Start the Buggregator server - Start the example app for testing features > The example app mounts code from an `examples` checkout next to `server` (`../examples/app`, > `../examples/routes`, `../examples/resources`, `../examples/config/sentry.php`). Clone it first: > > ```bash > git clone git@github.com:buggregator/examples.git ../examples > ``` > The compose file mounts `../frontend/dist` and sets `FRONTEND_DIR`, so the server serves a frontend build > from a `frontend` checkout next to `server`. Build it there first (`yarn install && yarn build:prod`), or remove > those two lines to use the embedded UI. ## 3. Access the Application Once the server is up: - **Buggregator:** http://localhost:8000 - **Example app:** http://localhost:8080 ## 4. Development without Docker If you prefer to develop without Docker, you need: - **Go 1.26+** - **Make** - **PHP and Composer** — `make build` compiles the VarDumper parser from `php/vardumper` the first time. The server itself does not need PHP to run. ```bash # Build and run make build make run # Or just compile go build ./cmd/buggregator # Run tests go test ./... ``` ### Frontend Development The frontend is a pre-built SPA that gets embedded into the binary during the build process. To develop the frontend separately: ```bash git clone git@github.com:buggregator/frontend.git cd frontend yarn install yarn build:prod # writes the build to dist/ ``` Then let Buggregator serve that build instead of the embedded one: ```bash FRONTEND_DIR=/path/to/frontend/dist ./buggregator ``` For live reload while you work on the UI, see [Contributing → Frontend](/contributing/frontend). ## 5. Stop the Server ```bash # If using Docker Compose docker compose down # If running directly Ctrl+C ``` --- That's it! Your Buggregator dev environment is ready. --- # Cookbook — Manual Installation Buggregator is a single self-contained binary with no external dependencies. You don't need Docker, PHP, Go, or any runtime to run it. ## Download Download the latest release for your platform from [GitHub Releases](https://github.com/buggregator/server/releases): ```bash # Linux (amd64) curl -fsSL -o buggregator https://github.com/buggregator/server/releases/latest/download/buggregator-linux-amd64 chmod +x buggregator # Linux (arm64) curl -fsSL -o buggregator https://github.com/buggregator/server/releases/latest/download/buggregator-linux-arm64 chmod +x buggregator # macOS (Apple Silicon) curl -fsSL -o buggregator https://github.com/buggregator/server/releases/latest/download/buggregator-darwin-arm64 chmod +x buggregator # macOS (Intel) curl -fsSL -o buggregator https://github.com/buggregator/server/releases/latest/download/buggregator-darwin-amd64 chmod +x buggregator ``` Windows (PowerShell): ```powershell # x86-64 Invoke-WebRequest https://github.com/buggregator/server/releases/latest/download/buggregator-windows-amd64.exe -OutFile buggregator.exe # ARM64, from v2.6.0 Invoke-WebRequest https://github.com/buggregator/server/releases/latest/download/buggregator-windows-arm64.exe -OutFile buggregator.exe ``` > On Windows, the VarDumper module (port 9912) is not available. Every other module works. One command that also checks the checksum (from v2.6.0): see [Install the binary](/install#with-the-install-script). ## Run ```bash ./buggregator ``` On Windows: `.\buggregator.exe`. Open http://127.0.0.1:8000 in your browser. That's it. ## Configuration By default, Buggregator runs with in-memory storage (data is lost on restart). To persist data, create a `buggregator.yaml` file next to the binary: ```yaml database: dsn: data.db # Persist events to a SQLite file storage: mode: filesystem # Persist attachments to disk path: ./storage ``` Or specify a custom config path: ```bash ./buggregator --config /etc/buggregator/buggregator.yaml ``` See the [server configuration guide](../config/server.md) for all available options. ## Default Ports | Port | Service | |------|---------| | 8000 | HTTP (Web UI + API) | | 1025 | SMTP | | 9912 | VarDumper (TCP) | | 9913 | Monolog (TCP) | All ports are configurable via environment variables or the config file. --- # Getting Started ## Three steps. That's it. 1. **Run one command** — start Buggregator with a single command. No installation, no registration, no configuration files. 2. **Add one env variable** — change one line in your `.env` file. Your existing Sentry SDK, VarDumper, Monolog, or Ray — they all just work. 3. **Open your browser** — navigate to http://127.0.0.1:8000 and start debugging. No login required. ## Quick Start Two ways to run it. Both give the same Buggregator. - **Binary**: one file, no Docker. Good on your own machine. - **Docker**: one container. Good when your app already runs in Docker Compose. Setting it up with an AI agent? Give it [the agent setup page](/agent-setup). ### Binary Buggregator is a single binary with no dependencies. One command installs it (from v2.6.0). Linux and macOS — puts `buggregator` in `~/.local/bin`, no `sudo`, checks the checksum: ```bash curl -fsSL https://raw.githubusercontent.com/buggregator/server/master/scripts/install.sh | sh buggregator ``` Windows (PowerShell) — puts `buggregator.exe` in `%LOCALAPPDATA%\Programs\buggregator`, checks the checksum: ```powershell irm https://raw.githubusercontent.com/buggregator/server/master/scripts/install.ps1 | iex & "$env:LOCALAPPDATA\Programs\buggregator\buggregator.exe" ``` - The script picks the file for your system and CPU (Intel/AMD or ARM). - Windows: the folder is not added to `PATH`, so run it by its full path, as above. - Linux and macOS: if `~/.local/bin` is not in your `PATH`, the script says so. Then run `~/.local/bin/buggregator`. - On Windows, the VarDumper module (port 9912) is not available. Every other module works.
Download the file yourself ```bash # Linux (Intel/AMD). ARM: buggregator-linux-arm64 curl -fsSL -o buggregator https://github.com/buggregator/server/releases/latest/download/buggregator-linux-amd64 chmod +x buggregator ./buggregator # macOS (Apple Silicon). Intel: buggregator-darwin-amd64 curl -fsSL -o buggregator https://github.com/buggregator/server/releases/latest/download/buggregator-darwin-arm64 chmod +x buggregator ./buggregator ``` ```powershell # Windows (PowerShell). ARM, from v2.6.0: buggregator-windows-arm64.exe Invoke-WebRequest https://github.com/buggregator/server/releases/latest/download/buggregator-windows-amd64.exe -OutFile buggregator.exe .\buggregator.exe ``` Downloaded in a browser instead? These are the usual system prompts: - macOS blocks the file once. Run `xattr -d com.apple.quarantine buggregator`, or right-click → **Open**. `curl` and the script do not hit this. - Windows SmartScreen says «Windows protected your PC». Click **More info → Run anyway**, or run `Unblock-File .\buggregator.exe`.
Open http://127.0.0.1:8000 in your browser. Done. All systems, ports, keeping events after a restart: [Install the binary](/install). ### Only on this computer The binary listens on all network interfaces, so other machines on your network can reach it. To keep it local: ```bash HTTP_ADDR=127.0.0.1:8000 SMTP_ADDR=127.0.0.1:1025 MONOLOG_ADDR=127.0.0.1:9913 VAR_DUMPER_ADDR=127.0.0.1:9912 PROXY_ADDR=127.0.0.1:8080 buggregator ``` ```powershell $env:HTTP_ADDR="127.0.0.1:8000"; $env:SMTP_ADDR="127.0.0.1:1025"; $env:MONOLOG_ADDR="127.0.0.1:9913"; $env:PROXY_ADDR="127.0.0.1:8080"; & "$env:LOCALAPPDATA\Programs\buggregator\buggregator.exe" ``` The install scripts print the same line after they finish. The Docker samples below already publish on `127.0.0.1` only. ### Docker ```bash docker run --pull always \ -p 127.0.0.1:8000:8000 \ -p 127.0.0.1:1025:1025 \ -p 127.0.0.1:9912:9912 \ -p 127.0.0.1:9913:9913 \ ghcr.io/buggregator/server:latest ``` ### Docker Compose Add Buggregator to your `docker-compose.yml` alongside your other services: ```yaml services: buggregator: image: ghcr.io/buggregator/server:latest ports: - 127.0.0.1:8000:8000 - 127.0.0.1:1025:1025 - 127.0.0.1:9912:9912 - 127.0.0.1:9913:9913 ``` No environment configuration needed. Works out of the box. ## Just change the address If Buggregator is part of an existing Docker Compose stack, other services can reach it by its service name. Change your app's `.env` to point at the container — that's the only change you need: ```dotenv # Sentry — only the host changed. Your Sentry SDK keeps working exactly the same. SENTRY_LARAVEL_DSN=http://sentry@buggregator:8000/1 # Ray RAY_HOST=ray@buggregator RAY_PORT=8000 # VarDumper VAR_DUMPER_FORMAT=server VAR_DUMPER_SERVER=buggregator:9912 # Monolog LOG_CHANNEL=socket LOG_SOCKET_URL=buggregator:9913 # SMTP — email capture MAIL_HOST=buggregator MAIL_PORT=1025 ``` ## Ports Each port serves a specific module. You only need to expose the ports for the features you use: | Port | Protocol | Module | What it does | |------|----------|--------|-------------| | **8000** | HTTP | [Sentry](./config/sentry.md), [Ray](./config/ray.md), [Inspector](./config/inspector.md), [HTTP Dumps](./config/http-dumps.md), [XHProf](./config/xhprof.md), [SMS](./config/sms.md) | Web UI + HTTP-based event ingestion. This is the only required port. | | **1025** | SMTP | [Fake SMTP Server](./config/smtp.md) | Captures outgoing emails. Point your app's SMTP config here. | | **9912** | TCP | [Symfony VarDumper](./config/var-dumper.md) | Receives `dump()` / `dd()` output. | | **9913** | TCP | [Monolog](./config/monolog.md) | Receives log records via Monolog's `SocketHandler`. | | **8080** | HTTP | [HTTP Proxy](./config/http-proxy.md) | Forward proxy that captures request + response pairs. Optional. | | **9003** | TCP (DBGp) | [Xdebug Proxy](./config/xdebug.md) | Sits between Xdebug and your IDE. Off by default; listens on `127.0.0.1` unless you change `XDEBUG_PROXY_ADDR`. | Port 8000 also serves the [mock server](./config/mock-server.md) under `/mock/`. If you only need specific features, omit the unused ports. For example, VarDumper only: ```bash docker run --pull always \ -p 127.0.0.1:8000:8000 \ -p 127.0.0.1:9912:9912 \ ghcr.io/buggregator/server:latest ``` ## Kubernetes The recommended way to deploy Buggregator on Kubernetes is using the [Helm chart](./config/helm-chart.md): ```bash helm install buggregator oci://ghcr.io/buggregator/helm-chart/buggregator ``` See the [Helm chart documentation](./config/helm-chart.md) for SSO, Ingress, Prometheus, and more. Or deploy manually as a `Deployment` + `Service`: ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: buggregator spec: replicas: 1 selector: matchLabels: app: buggregator template: metadata: labels: app: buggregator spec: containers: - name: buggregator image: ghcr.io/buggregator/server:latest ports: - containerPort: 8000 - containerPort: 1025 - containerPort: 9912 - containerPort: 9913 --- apiVersion: v1 kind: Service metadata: name: buggregator spec: selector: app: buggregator ports: - name: http port: 8000 - name: smtp port: 1025 - name: var-dumper port: 9912 - name: monolog port: 9913 ``` ## Configuration Buggregator can be configured via a YAML config file, environment variables, or CLI flags. The priority order is: **CLI flags > Environment variables > Config file > Defaults**. See the [server configuration guide](./config/server.md) for the full reference. ### Quick example with environment variables ```bash docker run --pull always \ -p 127.0.0.1:8000:8000 \ -e DATABASE_DSN=/data/buggregator.db \ -e METRICS_ENABLED=true \ -v ./data:/data \ ghcr.io/buggregator/server:latest ``` ## Image Tags | Tag | Description | |-----|-------------| | `latest` | Latest stable release. **Recommended.** | | `X` (e.g., `2`) | Latest release of a major version. Published since v2.6.0. | | `X.Y` (e.g., `2.6`) | Latest patch of a minor version. | | `X.Y.Z` (e.g., `2.6.0`) | One exact release, pinned. | ## Security By default, all ports are bound to `127.0.0.1` (localhost only). This prevents external access. Your debug data never leaves your machine. > **Warning:** If you remove the `127.0.0.1:` prefix (e.g., `-p 8000:8000`), the port becomes accessible from > outside your machine. Only do this if you understand the implications. For team environments, consider enabling [SSO authentication](./config/sso.md) to restrict access to the UI. --- # What is Buggregator? ## Debug everything. Install nothing. One binary. One command. Exceptions, dumps, emails, profiling, logs — all in one real-time UI. Works with the SDKs you already have. No cloud account. No code changes. No runtime dependencies. **Free forever. No paid plans. No feature gates. [MIT License](https://github.com/buggregator/server/blob/master/LICENSE).** **Watch introduction video on [YouTube](https://www.youtube.com/watch?v=yKWbuw8xN_c)** **Project repository:** https://github.com/buggregator/server Buggregator ## What's new in v2.0 Buggregator v2.0 is a **complete rewrite in Go**. The result is a single ~40 MB self-contained binary with everything built in — web UI, WebSocket server, SQLite database. No PHP runtime, no external services, no infrastructure to manage. - **Single binary** — download, run, done. Docker works too. - **~40 MB** — the entire server with the embedded web UI weighs less than a typical node_modules folder. - **Zero dependencies** — no PHP, no Go runtime, no database server, no message broker. Everything is inside. - **Embedded SQLite** — in-memory by default for instant startup, or file-based for persistence. - **MCP server** — AI assistants (Claude Code, Cursor) can query your debugging data directly. ## Get started in 60 seconds ### Download and run ```bash curl -fsSL https://github.com/buggregator/server/releases/latest/download/buggregator-linux-amd64 -o buggregator \ && chmod +x buggregator \ && ./buggregator ``` Open http://127.0.0.1:8000 — that's it. No installation, no registration, no configuration files. ### Or use Docker ```bash docker run --pull always \ -p 127.0.0.1:8000:8000 \ -p 127.0.0.1:1025:1025 \ -p 127.0.0.1:9912:9912 \ -p 127.0.0.1:9913:9913 \ ghcr.io/buggregator/server:latest ``` > No Docker? No binary? Use [Buggregator Trap](./trap/what-is-trap.md) — a lightweight PHP CLI > alternative. Just `composer require --dev buggregator/trap`. ## Your app doesn't know we exist Buggregator runs **beside** your application as a standalone server — not inside it. Your codebase doesn't change. Your dependencies don't change. You already have the SDKs installed (Sentry, VarDumper, Monolog, Ray) — they just need a different address in your `.env`. **No new dependencies.** Your app's `composer.json` stays untouched. No service providers. No migrations. No Buggregator code inside your project. **One env variable.** Already using Sentry SDK, VarDumper, or Monolog? Change where they send data. That's it. Your code doesn't need to know about Buggregator. **One instance, all your apps.** Run one Buggregator container or binary. Point all your projects at it. Microservices, monorepos, multiple teams — one dashboard. ## Replaces your local dev stack — for free | Instead of | Buggregator gives you | |---|---| | Sentry (cloud) | Exceptions with full stack traces | | Mailhog / Mailtrap | Email capture and preview | | Ray (paid app) | Variable dumps with 18+ payload types | | Blackfire / XHProf UI | Performance profiling with flame graphs | | Kibana / Log viewers | Real-time application logs | | RequestBin | HTTP request inspection | | Inspector.dev | Application performance monitoring | | Twilio console | SMS gateway testing | **All of this. One command. Zero cost.** ## When you need it - You have a **long-running PHP app** (RoadRunner, FrankenPHP, Swoole, Octane, queue workers) and `dd()` is not an option. - You want to see **exceptions with stack traces** like in Sentry, but don't want to set up Sentry for local dev. - You need to **profile performance** and find memory leaks or slow functions. - You want to **test emails** your app sends without a real mail server. - You want to **capture SMS messages** without sending real ones through Twilio or Vonage. - You have **multiple services** (microservices, Docker Compose) and want all debug data in one place. - You want to **inspect HTTP requests** your app makes to external APIs. - You just need a better `dump()` — with syntax highlighting, IDE links, and no browser pollution. ## 9 debugging tools in one dashboard ### [XHProf Profiler](/config/xhprof) — Performance Find slow functions and memory leaks. Visualize profiling data as a **Call Graph**, **Flame Graph**, and **Top Functions** table. **Compare two runs** side-by-side to verify your optimizations actually helped. xhprof ### [Sentry Compatibility](/config/sentry) — Exceptions Catch unhandled exceptions with full **stack traces**, **breadcrumbs**, **request details**, **device/browser info**, tags, and context. See exactly where your code breaks. All Sentry SDKs are supported — PHP, JavaScript, Python, and more. sentry ### [Fake SMTP Server](/config/smtp) — Emails Intercept outgoing emails during development. Preview HTML (with mobile/desktop viewport switcher), plain text, all addresses, attachments, and raw source. No emails actually sent. smtp ### [SMS Gateway](/config/sms) — SMS Messages Intercept outgoing SMS during development. Auto-detects 40+ providers including Twilio, Vonage, Plivo, Sinch, and more. See every message with sender, recipient, text, and detected provider. ### [HTTP Dumps](/config/http-dumps) — Requests Capture and inspect HTTP requests: method, URI, headers, cookies, POST data, uploaded files. Get a ready-to-use **cURL command** for any captured request. http dumps ### [Monolog Server](/config/monolog) — Logs Aggregate application logs in real time. See log level, channel, message, context, extra fields, and source location. Filter by level, search by message. Supports all PSR-3 levels. monolog ### [Symfony VarDumper](/config/var-dumper) — Variable Dumps Inspect variables with `dump()`. See object properties, array contents, and types — right in the browser. Click on file paths to open them in your IDE. var-dumper ### [Spatie Ray](/config/ray) — Debug Tool Debug with `ray()` — tables, queries, models, jobs, mail, counters, and 18 more payload types. A free alternative to the Ray app. Works with PHP, JavaScript, Ruby, Go, and Bash. ray ### [Inspector Compatibility](/config/inspector) — Transactions Monitor application performance with transaction tracing, memory tracking, and timeline breakdowns to identify bottlenecks. Local APM alternative. inspector ## Works with your framework No vendor lock-in. Your existing SDK just works. Buggregator is compatible with **Laravel**, **Symfony**, **Spiral**, **WordPress**, **Yii**, **Drupal**, **Magento** — and JavaScript, Python, Ruby, Go via Sentry SDK. Works with: **RoadRunner**, **FrankenPHP**, **Swoole**, **Laravel Octane**. See [integration guides](/config/sentry) for framework-specific setup. ## The Buggregator ecosystem ### JetBrains IDE Plugin Don't want to leave your IDE? The [Buggregator plugin for JetBrains IDEs](https://plugins.jetbrains.com/plugin/26344-buggregator) brings dumps, logs, and debug data directly into PhpStorm, IntelliJ IDEA, WebStorm, and other JetBrains products. No need to switch windows — everything is in a panel next to your code. The plugin launches [Buggregator Trap](/trap/what-is-trap) from your project and provides two views: - **Web UI** — the full Buggregator interface embedded in the IDE's built-in browser. - **Terminal** — text-based output for quick inspection. Install from **Settings** > **Plugins** > **Marketplace** > search "Buggregator", or visit the [plugin page](https://plugins.jetbrains.com/plugin/26344-buggregator). Read more in the [plugin documentation](/config/phpstorm-plugin). ### Buggregator Trap No Docker? No problem. [Buggregator Trap](./trap/what-is-trap.md) is a lightweight PHP CLI alternative to the full server. Covers most debugging needs — dumps, profiler, logs, inspections — without Docker. Just a Composer package. ```bash composer require --dev buggregator/trap -W ``` ## Ready for production teams Enterprise features when you need them: - **[SSO Authentication](/config/sso)** — Auth0, Google, GitHub, Keycloak, GitLab, and generic OIDC. - **[Database](/config/database)** — SQLite with in-memory or file-based persistence. - **[Kubernetes Ready](/config/helm-chart)** — deploy as Deployment + Service with the official Helm chart. - **[Webhooks](/config/webhooks)** — trigger external actions on incoming events. - **[Prometheus Metrics](/config/metrics)** — monitor event counts with Grafana. - **[Multi-project Support](/config/projects)** — separate events by project or team. - **[MCP Server](/config/mcp)** — let AI assistants (Claude Code, Cursor) query your debugging data. - **[Mock Server](/config/mock-server)** — answer API calls with fixed responses and capture every request. - **[Xdebug Proxy](/config/xdebug)** — share a paused Xdebug session with the browser and AI assistants, read-only. ## Also included - **Event pinning** — pin important events so they don't get lost. - **Event screenshots** — export any event as an image to share with your team. - **Keyboard shortcuts** — press `?` to see all shortcuts. Navigate with `j`/`k`, switch modules with `1`-`8`, `0` for all events. Single-key shortcuts can be turned off in Settings. - **IDE integration** — click file paths to open them in VS Code, PhpStorm, or [14 other IDEs](/config/var-dumper). Custom path mappings for Docker. - **Dark / Light themes** — follows your system preference or set manually. - **[Installable app](/config/pwa)** — install the UI as a desktop app with a new-events badge on its icon. ## Tech stack - [Go programming language](https://go.dev/) (single binary, ~40 MB, no external dependencies) - [SQLite](https://www.sqlite.org/) (embedded database, in-memory or file-based) - [Vue 3](https://vuejs.org/) + [TypeScript](https://www.typescriptlang.org/) + [Vite](https://vite.dev/) - [TailwindCSS](https://tailwindcss.com/) + [Pinia](https://pinia.vuejs.org/) - Built-in WebSocket server ([Centrifugo v5](https://centrifugal.dev/) protocol) ## Open source. Built with the community. Buggregator is free forever. No paid plans, no feature gates. If it helps you, consider [starring the repo](https://github.com/buggregator/server). Contributions are welcome — bugs, features, docs. [Contribution guidelines](./contributing.md) · [GitHub](https://github.com/buggregator/server) · [Discord](https://discord.gg/vDsCD3EKUB) ### Support the project Buggregator is and will always be free. Sponsors help fund server costs, development time, and new features. - [Support on Patreon](https://patreon.com/butschster) - [Browse issues](https://github.com/buggregator/server/issues) — find something to work on - [Join Discord](https://discord.gg/vDsCD3EKUB) — ask questions, share feedback --- # Install the binary Buggregator is one file. Download it, make it executable, run it. No Docker, no PHP, no database server. > Setting it up with an AI agent (Claude Code, Cursor, Codex)? Give it [this page for agents](/agent-setup). ## 1. Download ### With the install script **Linux and macOS:** ```bash curl -fsSL https://raw.githubusercontent.com/buggregator/server/master/scripts/install.sh | sh ``` It picks the file for your system and CPU, checks it against the release's `checksums.txt`, and puts it in `~/.local/bin/buggregator`. No `sudo`. If `~/.local/bin` is not in your `PATH`, the script says so; then run `~/.local/bin/buggregator`. **Windows (PowerShell):** ```powershell irm https://raw.githubusercontent.com/buggregator/server/master/scripts/install.ps1 | iex ``` It puts `buggregator.exe` in `%LOCALAPPDATA%\Programs\buggregator`. Both scripts take these environment variables: | Variable | What it does | |----------|--------------| | `BUGGREGATOR_VERSION` | a release tag, e.g. `v2.6.0`; default: the latest release | | `BUGGREGATOR_INSTALL_DIR` | another folder for the binary | | `BUGGREGATOR_NO_VERIFY=1` | skip the checksum; only for releases without `checksums.txt` (v2.5.0 and older) | Example — a fixed version into `~/bin`: ```bash curl -fsSL https://raw.githubusercontent.com/buggregator/server/master/scripts/install.sh \ | BUGGREGATOR_VERSION=v2.6.0 BUGGREGATOR_INSTALL_DIR="$HOME/bin" sh ``` > The scripts and `checksums.txt` come with v2.6.0. To install v2.5.0 or older with the script, add > `BUGGREGATOR_NO_VERIFY=1`. ### By hand Pick the file for your system from the [latest release](https://github.com/buggregator/server/releases/latest): | System | File | |--------|------| | Linux, x86-64 | `buggregator-linux-amd64` | | Linux, ARM64 (Raspberry Pi 4/5, AWS Graviton) | `buggregator-linux-arm64` | | macOS, Apple Silicon (M1 and later) | `buggregator-darwin-arm64` | | macOS, Intel | `buggregator-darwin-amd64` | | Windows, x86-64 | `buggregator-windows-amd64.exe` | | Windows, ARM64 (since v2.6.0) | `buggregator-windows-arm64.exe` | Not sure which one? Run `uname -m`: `x86_64` means amd64, `arm64` or `aarch64` means arm64. Linux and macOS, e.g. Linux x86-64: ```bash curl -fsSL -o buggregator https://github.com/buggregator/server/releases/latest/download/buggregator-linux-amd64 chmod +x buggregator ``` Windows: ```powershell Invoke-WebRequest https://github.com/buggregator/server/releases/latest/download/buggregator-windows-amd64.exe -OutFile buggregator.exe ``` ### If your system blocks it - **macOS.** A file downloaded with `curl` (or the script) is not blocked. A file downloaded in a browser is marked as from the internet, and macOS refuses to open it. Clear the mark once: `xattr -d com.apple.quarantine buggregator`. Or right-click the file → **Open**. The binary is not notarized by Apple. - **Windows.** A file downloaded in a browser may show «Windows protected your PC». Click **More info → Run anyway**, or run `Unblock-File .\buggregator.exe` once. ## 2. Start ```bash buggregator # installed with the script, ~/.local/bin in your PATH ~/.local/bin/buggregator # installed with the script, not in PATH ./buggregator # downloaded by hand ``` On Windows: `& "$env:LOCALAPPDATA\Programs\buggregator\buggregator.exe"` after the script, or `.\buggregator.exe`. Open http://127.0.0.1:8000. The UI is empty until your app sends something. To check from the command line: ```bash curl http://127.0.0.1:8000/api/version # {"version":"2.6.0"} ``` ## 3. Point your app at it Change one address in your app. Examples are on [Getting Started → Just change the address](/getting-started#just-change-the-address), and each integration page has its own (for example [Sentry](/config/sentry) or [SMTP](/config/smtp)). ## Ports | Port | What listens | Change it with | |------|--------------|----------------| | `8000` | Web UI, HTTP events (Sentry, Ray, Inspector, XHProf, HTTP dumps, SMS), mock server | `-http-addr` or `HTTP_ADDR` | | `1025` | SMTP: captured emails | `-smtp-addr` or `SMTP_ADDR` | | `9912` | VarDumper | `-vardumper-addr` or `VAR_DUMPER_ADDR` | | `9913` | Monolog | `-monolog-addr` or `MONOLOG_ADDR` | | `8080` | HTTP proxy | `PROXY_ADDR` | If a port is already taken, Buggregator stops at start. The log names the port and says `address already in use`: `failed to start HTTP server` for `8000`, `failed to start TCP servers` for the others. Example: another mail tool holds `1025`. Move Buggregator's SMTP elsewhere: ```bash ./buggregator -smtp-addr :2525 ``` ## Listen only on this machine By default every port listens on all network interfaces (`:8000`). Other machines on your network can then reach the UI and your captured data. To keep it on your machine only: ```bash ./buggregator \ -http-addr 127.0.0.1:8000 \ -smtp-addr 127.0.0.1:1025 \ -vardumper-addr 127.0.0.1:9912 \ -monolog-addr 127.0.0.1:9913 ``` Add `PROXY_ADDR=127.0.0.1:8080` in front for the HTTP proxy: it has no flag. ## Keep events after a restart By default events live in memory: stopping Buggregator clears them. To keep them, give it a database file: ```bash ./buggregator -db ./buggregator.db ``` The file is created on the first start. More options: [Database](/config/database). ## More settings Every setting is a flag, an environment variable or a line in `buggregator.yaml` (flags win over variables, variables over the file). See [Server configuration](/config/server). Example: turn on the MCP server for AI assistants: ```bash MCP_ENABLED=true ./buggregator ``` Then connect your assistant: [MCP](/config/mcp). On Windows, use the MCP HTTP transport (`MCP_TRANSPORT=http MCP_ADDR=127.0.0.1:8001`): the default Unix socket path `/tmp/buggregator-mcp.sock` does not exist there. Without `MCP_ADDR`, the MCP server listens on `:8001`, on all network interfaces, with no token. ## Update Run the install script (or the download) again, then restart. With `-db`, your events stay. --- # Using Buggregator docs with AI assistants Buggregator documentation is available in a machine-readable format so that AI assistants (ChatGPT, Claude, Cursor, Windsurf, GitHub Copilot, and others) can read it and help you set up, configure, and debug issues. ## Quick start Give your AI assistant this URL: ``` https://docs.buggregator.dev/llms.txt ``` The assistant will read the index, understand what Buggregator is, and fetch the specific pages it needs to answer your question. ### Example prompts - "Read https://docs.buggregator.dev/llms.txt and help me set up Buggregator with my Laravel project" - "I have a Symfony app. How do I send Monolog logs to Buggregator?" - "Help me configure XHProf profiling for my PHP application" - "What's the difference between Buggregator server and Trap?" ## Available endpoints | URL | What it contains | When to use | |-----|-----------------|-------------| | [`/llms.txt`](https://docs.buggregator.dev/llms.txt) | Index with page descriptions | When the assistant supports browsing — it picks the relevant pages | | [`/llms-full.txt`](https://docs.buggregator.dev/llms-full.txt) | Complete documentation in one file | Best for most assistants — give full context in one shot | | `/.md` | Individual page without frontmatter | When you only need a specific topic | ### Per-page URLs If you only need help with a specific integration, you can point the assistant to a single page: - `https://docs.buggregator.dev/config/sentry.md` — Sentry setup - `https://docs.buggregator.dev/config/smtp.md` — SMTP / email testing - `https://docs.buggregator.dev/config/xhprof.md` — XHProf profiling - `https://docs.buggregator.dev/config/monolog.md` — Monolog logs - `https://docs.buggregator.dev/config/var-dumper.md` — Symfony VarDumper - `https://docs.buggregator.dev/config/ray.md` — Spatie Ray - `https://docs.buggregator.dev/getting-started.md` — Installation guide ## How it works These files follow the [llms.txt](https://llmstxt.org/) convention — a standard way to provide documentation to AI models. The content is the same as the regular docs, just formatted for machine consumption (plain markdown, no HTML, no navigation chrome). The files are generated automatically during the docs build, so they're always up to date with the latest documentation. --- # Trap — Commands ## `run` ### Description The `run` command starts the Trap server, which listens for debug information on specified ports and processes it using configured senders. ### Simple Example ```bash vendor/bin/trap run ``` ### Arguments and Options | Option | Short | Description | Default | |------------|-------|---------------------------------------------------------|--------------------------| | `--port` | `-p` | Port(s) to listen on (can be specified multiple times) | `1025, 8000, 9912, 9913` | | `--sender` | `-s` | Sender type(s) to use (can be specified multiple times) | `console` | | `--ui` | - | Enable web UI (with optional port specification) | `false` | ### Port Configuration Details By default, Trap runs on multiple ports simultaneously: `1025, 8000, 9912, 9913`. All ports listen for the same data, but this multi-port setup makes it compatible with various debugging tools that have their own default ports: - Port `1025`: Default SMTP port for email testing - Port `8000`: Used for HTTP dumps - Port `9912`: Default port for Symfony VarDumper - Port `9913`: Default for Monolog socket handler If you want to listen on just one specific port, you can specify it: ```bash vendor/bin/trap run -p 8000 ``` This will make Trap listen only on port `8000`. ### Examples Start with default settings: ```bash vendor/bin/trap run ``` Listen on specific ports: ```bash vendor/bin/trap run --port=8888 # or vendor/bin/trap run -p 8888 ``` Listen on multiple ports: ```bash vendor/bin/trap run --port=8888 --port=9999 # or vendor/bin/trap run -p 8888 -p 9999 ``` Enable the web UI on default port: ```bash vendor/bin/trap run --ui ``` Use environment variables for configuration: ```bash TRAP_TCP_PORTS=8888,9999 TRAP_UI_PORT=8080 vendor/bin/trap run --ui ``` ### Available Senders Trap supports multiple methods ("senders") for outputting the debug information, allowing you to choose where your debug dumps are sent: - **Console**: Outputs dumps directly in the console. - **Server**: Sends dumps to a remote Buggregator server for centralized management and review. - **File**: Saves dumps to a file, useful for auditing or detailed offline analysis. By default, dumps are displayed in the console. However, you can configure multiple senders simultaneously to suit your workflow and requirements. For example, to use the console, file, and server senders together: | Sender | Description | |----------------|--------------------------------------------------| | `console` | Outputs debug information to the console | | `file` | Writes events to files in JSON format | | `file-body` | Writes event body content to separate files | | `mail-to-file` | Stores received emails to files | | `server` | Forwards events to a Buggregator server instance | ```bash vendor/bin/trap run --sender=console --sender=file ``` ## `test` ### Description The `test` command sends various types of test data to the Trap server to verify that it's working correctly. This includes XHProf data, var dumps, emails, Sentry reports, and binary data. ### Simple Example ```bash vendor/bin/trap test ``` ### Arguments and Options The `test` command doesn't accept any arguments or options. ### Example To send test data to a running Trap instance: ```bash # First, start the trap server in one terminal vendor/bin/trap run # Then, in another terminal, run the test command vendor/bin/trap test ``` This will: 1. Send XHProf profiling data 2. Execute various `trap()` dumps 3. Send test emails (both simple and multipart) 4. Send Sentry store and envelope data 5. Send binary data --- ## `joke` ### Description The `joke` command prints a random joke using the trap framework. It's a fun addition that also demonstrates the trap functionality. ### Simple Example ```bash vendor/bin/trap joke ``` ### Arguments and Options The `joke` command doesn't accept any arguments or options. ### Example To display a random joke: ```bash vendor/bin/trap joke ``` The joke output will be displayed using the same output mechanism as other trap messages, which can be a good way to verify that your trap setup is working correctly in a lightweight manner. ## Environment Variables Trap can be configured using environment variables: | Variable | Description | Default | |-----------------------------|--------------------------------------------|-------------------------------------| | `TRAP_TCP_PORTS` | Comma-separated list of ports to listen on | `1025,8000,9912,9913` | | `TRAP_TCP_HOST` | Host interface to bind to | `127.0.0.1` | | `TRAP_TCP_POLLING_INTERVAL` | Socket polling interval in microseconds | `1000` | | `TRAP_UI_PORT` | Web UI port | `8000` | | `TRAP_UI_HOST` | Web UI host interface | `127.0.0.1` | | `TRAP_MAIN_LOOP_INTERVAL` | Main loop interval in microseconds | `100` | | `TRAP_XHPROF_PATH` | Path to XHProf files | Read from PHP's `xhprof.output_dir` | | `TRAP_XHPROF_SORT` | XHProf edges sorting algorithm (0-3) | `3` | --- # Trap — Getting Started There are several ways to get started with Trap, depending on your needs and preferences. ## Standalone Binary (No Project Dependencies) Download and extract the pre-compiled binary for your platform. This method allows you to use Trap across multiple PHP projects without modifying their dependencies. **Available for platforms:** - Linux (amd64, arm64) - macOS (amd64, arm64) - Windows (amd64) > **Note:** Binaries can be found on release page https://github.com/buggregator/trap/releases ```bash # Download (example for Linux amd64) curl -L -o trap.tar.gz https://github.com/buggregator/trap/releases/latest/download/trap-1.13.13-linux-amd64.tar.gz # Extract the archive tar -xzf trap.tar.gz rm trap.tar.gz # Make executable chmod +x trap # Run ./trap ``` This command will start the Trap server, ready to receive any debug messages. Once a debug message is trapped, you will see a convenient report about it right here in the terminal or in the browser. ## Composer Installation To use Trap into your project, simply add it as a development dependency via Composer: ```bash composer require --dev buggregator/trap -W ``` After installation, you can start the debugging server using: ```bash vendor/bin/trap ``` Once Trap is running, you can start debugging with the `trap()` function: ```php // Basic variable dump trap($user); // Named variable dumps trap(id: $userId, email: $userEmail); // Dump and continue using the value $response = trap($api->getResponse())->return(); // Set dump depth for nested objects trap($complexObject)->depth(3); ``` ## User Interface By adding the `--ui` flag when starting the Trap server, you can automatically open the web interface. This allows for a more intuitive and graphical interaction with your debug data. ```bash ./trap --ui # or vendor/bin/trap --ui ``` And just open the URL in your browser: [http://127.0.0.1:8000](http://127.0.0.1:8000). ## What's Next? - Read more about the `trap()` function in the [Usage](./usage.md) section. - Explore the [Commands](./commands.md) for additional functionality. --- # Trap — Functions Trap is not just a server; it's also a useful collection of functions that help you debug your PHP applications. ## trap() ### Description The `trap()` function is designed to capture and send variable dumps to the server. It serves as the primary entry point for debugging PHP applications, allowing developers to inspect variables, trace execution flow, and analyze application state at runtime. > **Note:** When using `trap()`, it automatically configures `$_SERVER['REMOTE_ADDR']` and `$_SERVER['REMOTE_PORT']` if > they are not already set. This ensures that the debug information is accurately captured and displayed. ### Signature ```php function trap(mixed ...$values): TrapHandle ``` The function accepts any number of arguments (named or positional) and returns a `TrapHandle` instance that provides additional debugging capabilities through method chaining. ### Usage Examples #### 1. Basic Variable Dumping ```php // Dump a simple variable trap($user); // Dump multiple variables trap($request, $response, $config); // Use named arguments for better clarity trap(user: $user, request: $request, response: $response); ``` This sends the variables to the Buggregator server where they can be inspected in the dashboard. #### 2. Stack Trace Inspection ```php // Add stack trace to your dump to see the execution flow trap()->stackTrace(); // Dump a variable along with the stack trace trap($result)->stackTrace(); ``` This adds the current stack trace to your dump, showing the execution path that led to this point in your code. #### 3. Limiting Dump Depth ```php // Limit the dump depth to 4 levels for deeply nested objects trap($complexObject)->depth(4); // Dump multiple objects with depth limit trap(user: $user, order: $order)->depth(2); ``` This is useful for complex objects where you want to limit how deep the dump will go into nested structures. #### 4. Conditional Dumping ```php // Dump only if a condition is met trap($response)->if($statusCode >= 400); // Using a callable for complex conditions trap($query)->if(fn() => $query->count() > 100); ``` This lets you add conditional logic to your dumps, only showing them when specific conditions are met. #### 5. Limiting Dump Frequency ```php // Dump only once at this location in code trap($i)->once(); // Dump only 5 times at this location trap($i)->times(5); // Dump only 3 times with full stack consideration (useful in recursion) trap($recursiveData)->times(3, true); ``` This helps when debugging loops or recursive functions by limiting how many times the dump is shown. #### 6. Getting Values Back ```php // Dump a value and return it immediately $result = trap($data)->return(); // Chain operations without breaking the flow $response = $service->process(trap($request)->return()); // Return a specific named value $name = trap(first: $firstName, last: $lastName)->return('last'); ``` This allows you to insert debugging in the middle of expressions without disrupting your code flow. #### 7. Adding Context ```php // Add execution context to help understand the dump trap($phpCode)->context(language: 'php', filename: 'Controller.php'); // Add context using an array trap($data)->context(['environment' => 'production', 'user_id' => 42]); // Shorthand for code highlighting trap($sqlQuery)->code('sql'); ``` This adds metadata to your dumps to provide more context for debugging. #### 8. Combining Multiple Features ```php // Combine multiple debugging features trap($user) ->depth(3) ->if($user->isAdmin()) ->context(role: 'admin', permissions: $user->getPermissions()) ->once(); ``` This example uses multiple features together to create a targeted debugging setup. #### 9. Working with Protobuf Messages ```php // Dump Protobuf messages with improved readability trap($protoMessage); ``` The trap function includes special handling for Protocol Buffers, making them easier to debug. #### 10. Checking Performance with Ticks ```php // First tick tr(); // Some code to measure doSomething(); // Second tick will show time elapsed since first tick tr(); ``` The `tr()` function (a short alias) can be used to measure performance between points in your code. ## tr() ### Description The `tr()` function is a shorthand alias for `trap()->return()`. When called without arguments, it works as a performance ticker, measuring time and memory usage between calls. ### Signature ```php function tr(mixed ...$values): mixed ``` ### Usage Examples #### 1. Performance Measurement ```php // Mark the starting point tr(); // Execute the code to measure $result = heavyComputation(); // Mark the endpoint and see elapsed time and memory usage tr(); ``` This shows time elapsed and memory usage between calls. #### 2. Quick Value Inspection ```php // Dump and return in one call $user = tr($repository->findUser($id)); // Chain in expressions return tr($response->withHeader('Content-Type', 'application/json')); ``` This lets you inspect values while keeping them in your execution flow. ## td() ### Description The `td()` function combines `trap()` with PHP's `die` statement, allowing you to dump values and terminate script execution. It's useful for quickly halting execution after inspecting critical values. ### Signature ```php function td(mixed ...$values): never ``` ### Usage Examples #### 1. Debug and Die ```php // Dump value and terminate execution td($error); // Dump multiple values before terminating td($request, $exception, $context); ``` This dumps the values to Buggregator and immediately terminates script execution. #### 2. Emergency Debugging ```php // When you need to stop and check what's happening if ($unexpectedCondition) { td(message: 'Unexpected condition', data: $data); } ``` This is useful during development to quickly halt execution at critical points. #### 3. Performance Check and Die ```php // Start measuring tr(); // Run code to analyze $result = complexOperation(); // Check result and terminate td($result); ``` This combines performance measurement with termination, useful for profiling. --- # Trap — What is it? Trap is a powerful, lightweight debugging tool designed to supercharge your PHP development experience. It serves as an excellent alternative to Symfony VarDumper by providing all the functionality you need for debugging with the addition of a clean, intuitive user interface built right in. **Project repository:** https://github.com/buggregator/trap > Star the project to show your support and help us grow! ⭐️ We appreciate your support! ## What Makes Trap Special Unlike traditional debugging tools that output to the console or directly into your application's response, Trap captures debugging information and presents it both in a dedicated dashboard and console. This separation keeps your application output clean while giving you a comprehensive view of all debugging data in one place. ### Key Features: - **Zero Configuration**: Works immediately after installation with sensible defaults. - **Cross-Project Compatibility**: Allows to debug multiple applications simultaneously with a single Trap instance - **Dashboard Interface:** It features the same user-friendly dashboard as the full Buggregator Server, allowing for seamless monitoring and management of debug outputs directly from the web. - **Standalone Binary**: Use without adding dependencies to your project on Windows, Linux, or MacOS. - **Console Application:** Includes a mini-server written entirely in PHP, eliminating the need for Docker or other container technology. This makes it easier to deploy and use in a variety of development environments. - **Multiple Handlers:** Trap supports various handlers for debugging such as **Symfony VarDumper**, **Monolog**,**Sentry**, **SMTP**, **HTTP dumps**, **Ray**, and more. This versatility allows developers to tailor the debugging process to their specific needs and existing development stack. - **Protobuf Debugging:** Offers an improved way to work with Google Protocol Buffers (protobuf) by providing clearer and more concise debugging outputs. ## Console Application Here's a sneak peek into the console output you can expect with Trap: ### Symfony/var-dumper (proto) ![var-dumper](https://github.com/buggregator/trap/assets/4152481/f4c855f5-87c4-4534-b72d-5b19d1aae0b0) ### Binary Data ![Binary Data](https://github.com/buggregator/trap/assets/4152481/cd8788ed-b10c-4b9a-b2e2-baa8912ea38d) ### SMTP Mail Trap ![smtp](https://github.com/buggregator/trap/assets/4152481/b11c4a7f-072a-4e66-b11d-9bbd3177bfe2) ### HTTP Dump ![http-dump](https://github.com/buggregator/trap/assets/4152481/48201ce6-7756-4402-8954-76a27489b632)