BackScatteR
README.md
# backscatter-api
A tech uploads an OTDR `.sor` file. (An OTDR, optical time-domain reflectometer, is the test instrument that sends light down a fiber and records what comes back; a `.sor` file is the instrument's saved trace.) BackScatteR reads the file, finds the fault event, and says how far along the fiber it is: the distance on the instrument's display, the distance past the launch cable (the known-good cable between the instrument and the fiber under test), the plus or minus on that distance, the event's loss and reflectance, a pass / fail verdict and the next steps to take.
It has three front doors onto the same deterministic core (code that always gives the same answer for the same file):
- a **REST API** and a small **web page** for people (drop one or many files, see the trace and the answer);
- an **MCP server** (stdio and Streamable HTTP) for AI clients such as Claude Desktop, Claude Code and Open WebUI;
- an optional **AI agent** on Amazon Bedrock Mantle (`openai.gpt-oss-20b` by default) or the Anthropic API (`claude-sonnet-5-5` by default) that reads the tech's note and drives the same tools.
**The math is code, not the model.** Parsing, event detection, distances, grading and comparisons are deterministic. The model only reads the note, calls tools, chooses between candidates the tools return, and explains the answer. Its final report must equal a tool result, and is then checked against the deterministic answer; if it does not match, disagrees, or the model does not finish, the service returns the deterministic answer first and says so (`fallback: true`, and `disagreement: true` with the model's pick as `alternative`). The answer text always comes from the tools; the model's own words are a separate, labelled `modelNote`.
All sample data in this repo is fictional (eight training scenarios on a made-up Maine network, Northline Fiber). Files are local uploads only.
## What it does
- **Finds the fault and says what kind of answer it is.** Each answer has an outcome (`break`, `end_of_fiber`, `reaches_expected`, `event_of_concern`, `marked_fault` or `no_clear_fault`). It claims a break only when you give the expected fiber length and the light ends short of it. A healthy fiber gets "No break found", never a made-up break ([docs/api.md](docs/api.md#post-v1ask)).
- **Feet or meters everywhere.** `DEFAULT_UNITS` (feet unless you change it) sets the unit for the words, CSV headers, reports and CLI output; any request can ask for the other with `units=ft|m`. JSON numbers stay in meters (`*_m`).
- **Many files at once.** The web page uploads several files in parallel, retries the ones that fail, lets you cancel, and keeps up to 200 traces per key (`TRACE_MAX_PER_KEY`).
- **AI second opinion (optional, off by default).** A Claude model looks at pictures of the trace and points at things worth a second look. It is advice only and never changes the answer ([below](#ai-second-opinion-optional)).
- **Labels**: a person says what an event is (launch cable end, connector, splice, splitter, bend, fault, far end, ghost), and the analysis uses it: loss limits, launch offset, far end, fault pick, pass / fail. The measured values never change; clearing a label restores the engine's reading. A person can also add an event the table missed, measured at a cursor. Only a person does this, never the AI ([docs/labels.md](docs/labels.md)).
- **Cursor measurements**: level, two-point loss, LSA dB/km (least-squares attenuation), 5-point splice loss, reflectance, ORL (optical return loss, the total light reflected back), each with its worked steps ([docs/measurements.md](docs/measurements.md)).
- **Span and pass / fail** against cited limit profiles (TIA-568.3-E, ISO/IEC 14763-3, or the job's own), and **shot-quality checks** that say how to shoot again ([docs/pass-fail.md](docs/pass-fail.md)).
- **Several traces**: bidirectional average (shots from both ends), two-wavelength bend check, baseline comparison, whole-cable batch. Comparing two traces that are not the same fiber is refused with `422 not_same_fiber` ([docs/multi-trace.md](docs/multi-trace.md)).
- **Multimode** 850 / 1300 nm as well as single-mode ([docs/multimode.md](docs/multimode.md)).
- **Reports and exports**: fiber and cable PDFs, CSVs, and the `.sor` with the corrected event table ([docs/reports.md](docs/reports.md)).
- **Plain-language errors.** Every error says what went wrong and what to do; `429` and `503` carry a `Retry-After` header (seconds to wait).
## Quick start
### With Docker (recommended)
Needs Docker. This runs the hardened image on your own computer.
```sh
git clone <this repository> && cd backscatter-api
cp .env.example .env # optional: every setting has a default
mkdir -p secrets # key files go here (never committed)
docker compose up -d --build
open http://127.0.0.1:8080 # no key needed: Compose runs AUTH_MODE=local, this computer only
```
Or without Compose:
```sh
docker build -t backscatter-api .
docker run --rm -p 127.0.0.1:8080:8080 --read-only --tmpfs /tmp -e API_KEYS=$(openssl rand -hex 24) backscatter-api
```
The image runs as user `bsapi` (uid 10001, not root), works with a read-only root filesystem, has no `npm` in it, and writes nothing unless `PERSIST_DIR` points at a volume. Put TLS (HTTPS) in front of it for anything beyond your own computer. Details, secrets and the CLI in the container: [docs/docker.md](docs/docker.md).
### From source
Needs Node 22.
```sh
npm ci
npx tsx src/cli.ts eval make # writes 44 simulated .sor files to eval/out/cases/
AUTH_MODE=disabled npm run dev # http://127.0.0.1:8080 (auth off is allowed on loopback only)
```
Open http://127.0.0.1:8080 and drop `eval/out/cases/plowed-under-s1-1550-ideal.sor` on the page. You get the trace, the event table, the fault and the verdict.
Or from the command line (`bsx`):
```sh
npx tsx src/cli.ts analyze test/fixtures/sor/demo_ab.sor
npx tsx src/cli.ts ask eval/out/cases/plowed-under-s1-1550-ideal.sor "customers down on Rt 186" --expected 8000 --units ft
npx tsx src/cli.ts plot eval/out/cases/plowed-under-s1-1550-ideal.sor --view both
```
For anything other than your own laptop, use keys:
```sh
cp .env.example .env
# set API_KEYS=<output of: openssl rand -hex 24> in .env
npm run dev
curl -s -H "Authorization: Bearer $KEY" http://127.0.0.1:8080/v1/status
```
## REST API
Auth: `Authorization: Bearer <key>` or `X-API-Key: <key>` on everything except `GET /healthz`, the page shell `GET /`, the favicon and the page's brand and font files. Online, put it behind Entra ID or Google sign-in (an AWS load balancer, Cloudflare Access, Google IAP or oauth2-proxy) with `AUTH_MODE=proxy`: no key box, the page shows who is signed in, and API keys stay optional for scripts ([docs/auth.md](docs/auth.md)). On AWS EKS behind an ALB with Entra ID sign-in: `deploy/eks/` and [docs/eks.md](docs/eks.md). Docker on your own computer runs `AUTH_MODE=local`: no key, this computer only. Errors are always `{"error": {"code", "message", "request_id"}}`. Full reference: [docs/api.md](docs/api.md); machine-readable: `GET /openapi.json`.
| Method | Path | What it does |
|---|---|---|
| GET | `/healthz` | liveness (no auth) |
| GET | `/` | the web page (no auth for the shell; its API calls authenticate like any other request) |
| GET | `/v1/status` | version, AI provider and model, whether the second opinion is available, limits, how many traces this key holds |
| POST | `/v1/traces` | upload a `.sor` (multipart field `file`, or `application/octet-stream`); returns the analyzed trace and the fault pick |
| GET | `/v1/traces` | your own stored traces (to rebuild the page's list after a reload) |
| GET | `/v1/traces/:id` | the analyzed trace |
| GET | `/v1/traces/:id/samples?max=4000` | min/max-decimated samples for plotting |
| GET | `/v1/traces/:id/plot.png?view=overview\|ends` | the trace as a PNG picture, drawn by the code |
| DELETE | `/v1/traces/:id` | delete now (memory and disk) |
| POST | `/v1/ask` | multipart (`file`, `note`, `expected_length_m`) or JSON (`trace_id`, `note`, `expected_length_m`, `deterministic_only`): the agent when AI is on, otherwise the deterministic answer |
| POST | `/v1/traces/:id/review` | the AI second opinion (opt-in, Anthropic only) |
| POST, DELETE | `/v1/traces/:id/labels` | say what an event is (`{event_id, role}`, `role: null` clears it); `DELETE` clears every label. Scope `locate`, audited |
| POST | `/v1/traces/:id/events` | add an event at a cursor (`{x_m}`), measured from the samples; `DELETE /v1/traces/:id/events/:eventId` removes one. Scope `locate`, audited |
| POST | `/v1/traces/:id/measure` | cursor tools: level, two-point loss, LSA dB/km, 5-point splice loss, reflectance, ORL |
| POST | `/v1/traces/:id/grade` | span and pass / fail against a limit profile, with shot-quality findings |
| GET | `/v1/traces/:id/quality`, `/v1/profiles` | shot-quality findings; the limit profiles and their sources |
| POST | `/v1/compare` | two traces of one fiber: `bidirectional`, `wavelengths` (bend check) or `baseline` |
| POST | `/v1/cable` | many fibers of one cable: rows with pass / fail, clusters, outliers |
| GET | `/v1/traces/:id/report.pdf`, `events.csv`, `labeled.sor` | fiber report, event table, the `.sor` with the corrected event table (audited) |
| POST | `/v1/cable/report.pdf`, `/v1/cable/report.csv` | cable report and table (audited) |
| GET | `/openapi.json` | OpenAPI 3.1, generated from the zod schemas |
| POST | `/mcp` | MCP Streamable HTTP (stateless, same API keys) |
```sh
ID=$(curl -s -H "Authorization: Bearer $KEY" -F file=@shot.sor http://127.0.0.1:8080/v1/traces | jq -r .id)
curl -s -H "Authorization: Bearer $KEY" -H 'content-type: application/json' \
-d "{\"trace_id\":\"$ID\",\"expected_length_m\":8000,\"units\":\"ft\"}" http://127.0.0.1:8080/v1/ask | jq '.outcome, .headline'
```
## Tools (MCP and agent)
One set of tool definitions (`src/tools/defs.ts`), shared by MCP and the agent. Outputs are compact JSON with a one-paragraph `summary`; text from the file is always inside `untrusted_file_text`, marked as data. Every tool takes an optional `units` (`ft` or `m`) for the distances in its text.
| Tool | Use |
|---|---|
| `find_fault {trace_id, expected_length_m?}` | one-shot answer: outcome, the picked event (display distance, distance past the launch cable, plus or minus), loss, reflectance, verdict, next steps, alternatives, `report_finding_args` |
| `describe_event {trace_id, event_id, expected_length_m?}` | the same view for one event the tech names |
| `analyze_trace {trace_id \| sor_base64 \| file_path}` | events, fiber end, preliminary fault pick (`file_path` only over stdio MCP and only inside `MCP_FILE_ROOT`) |
| `report_finding {...}` | agent only: the required final answer, checked against the tool results |
| `grade_trace {trace_id, profile?, launch_end?, receive_start?, connector_kind?}` | MCP only: span and pass / fail, with shot-quality findings |
| `trace_quality {trace_id, expected_length_m?}` | MCP only: can this shot be trusted, and what to change |
| `measure_trace {trace_id, tool, x_m?, a_m?, b_m?}` | MCP only: one cursor measurement with its steps; stores nothing |
| `compare_traces {kind, a, b}` | MCP only: bidirectional, two wavelengths or baseline |
| `cable_summary {trace_ids, expected_length_m?, profile?}` | MCP only: the whole-cable batch |
| `trace_plot {trace_id, view?}` | MCP only: the trace picture as an image (`overview` or `ends`) |
The workbench tools read and grade what is stored. No tool sets labels or adds events: those are a person's decisions, made through REST ([docs/labels.md](docs/labels.md)).
## MCP setup
Build once (`npm run build`), or point at `src/mcp/main.ts` through `tsx`.
**Claude Code** (stdio, reads `.sor` files from one folder):
```sh
claude mcp add backscatter -e MCP_FILE_ROOT=$HOME/OTDR -- npx --prefix /path/to/backscatter-api tsx /path/to/backscatter-api/src/mcp/main.ts
```
Or over HTTP against a running service:
```sh
claude mcp add --transport http backscatter https://bsx.example.net/mcp --header "Authorization: Bearer $KEY"
```
**Claude Desktop** (`claude_desktop_config.json`):
```json
{
"mcpServers": {
"backscatter": {
"command": "npx",
"args": ["--prefix", "/path/to/backscatter-api", "tsx", "/path/to/backscatter-api/src/mcp/main.ts"],
"env": { "MCP_FILE_ROOT": "/Users/you/OTDR" }
}
}
}
```
Then ask: "Analyze break-shot.sor and tell me where the break is."
**Open WebUI via mcpo** (exposes the stdio server as an OpenAPI tool server):
```sh
MCP_FILE_ROOT=/srv/otdr uvx mcpo --port 8000 --api-key "$MCPO_KEY" -- \
npx --prefix /opt/backscatter-api tsx /opt/backscatter-api/src/mcp/main.ts
```
In Open WebUI: Settings, Tools, add `http://<host>:8000` with the mcpo key. Keep mcpo on a private network; its key is the only gate in front of the tools.
## AI on Amazon Bedrock Mantle (optional)
1. In the Bedrock console for your region, enable access to `openai.gpt-oss-20b` (and `openai.gpt-oss-120b` if you want the comparison).
2. Create a Bedrock API key (short-term keys expire; long-term keys should be scoped to Bedrock and rotated).
3. Set in `.env`:
```sh
AI_PROVIDER=bedrock_mantle
BEDROCK_MANTLE_BASE_URL=https://bedrock-mantle.us-east-1.api.aws/v1
BEDROCK_API_KEY=...
BEDROCK_MODEL=openai.gpt-oss-20b
AGENT_API=chat # or responses (store:false, transcript re-sent each turn)
```
The base URL must be `https://bedrock-mantle.<region>.api.aws/v1`; anything else is refused unless `AGENT_ALLOW_NON_AWS=true` (local test doubles only, refused in production). With `AI_PROVIDER=off` (the default) `/v1/ask` answers deterministically. Why a 20B model is enough, and what it costs per call: [docs/models.md](docs/models.md). The second opinion does not work with Bedrock Mantle.
## AI on the Anthropic API (optional)
The same agent, the same tools and the same checks (the AI stays non-authoritative), over the Anthropic Messages API with the official `@anthropic-ai/sdk`.
| Variable | Default | |
|---|---|---|
| `AI_PROVIDER` | `off` | `anthropic` selects this provider |
| `ANTHROPIC_API_KEY` | | the API key; required when selected (startup fails without it, or without `ANTHROPIC_API_KEY_FILE`) |
| `ANTHROPIC_API_KEY_FILE` | | a file holding the key (a mounted secret), read when `ANTHROPIC_API_KEY` is empty |
| `ANTHROPIC_MODEL` | `claude-sonnet-5-5` | the model for fault finding (`/v1/ask`); any Claude model with adaptive thinking and effort |
| `ANTHROPIC_BASE_URL` | `https://api.anthropic.com` | https only |
`AGENT_MAX_STEPS`, `AGENT_TIMEOUT_MS` (per call), `AGENT_RETRIES` (429, 529 overloaded, other 5xx, network), `AGENT_DEADLINE_MS`, `AGENT_MAX_OUTPUT_TOKENS` (`max_tokens`, thinking included) and `AGENT_REASONING_EFFORT` (`output_config.effort`) apply as for Bedrock; `AGENT_API` does not. The key is never logged and never returned: `/v1/status` reports only `keySet`.
**Local development**: put the key in the environment (or in `.env`, which is gitignored):
```sh
AI_PROVIDER=anthropic
ANTHROPIC_API_KEY=... # from the Claude Console
# ANTHROPIC_MODEL=claude-sonnet-5-5
```
**Production**: do not bake the key into the image or a committed file. Keep it in AWS Secrets Manager (or another secrets manager) and let the platform inject it, either as the `ANTHROPIC_API_KEY` environment variable (on EKS, the External Secrets Operator or the Secrets Store CSI driver syncing it into the `backscatter-secrets` Secret the pod already reads; on ECS, a task definition `secrets` entry) or as a file on the existing `/run/secrets` mount with `ANTHROPIC_API_KEY_FILE=/run/secrets/anthropic-key`. No code change either way. Details: [docs/models.md](docs/models.md#anthropic-api).
## AI second opinion (optional)
A second pair of eyes on the trace. When the server has it turned on, the web page shows an "AI second opinion" section under the fault answer with a button. Press it and a Claude vision model looks at two pictures of the trace (the whole trace, and the launch and far ends zoomed) and points at spots worth checking, as advisory cards and dashed AI markers on the chart. It never runs by itself, and it never changes the fault, the pass / fail verdict or the next steps. The model only points; the code snaps each pointer to a real event or sample and measures there, and the model writes no distances or verdict.
It is off by default. To turn it on you need `AI_PROVIDER=anthropic`, an Anthropic key and `REVIEW_ENABLED=true`:
| Variable | Default | |
|---|---|---|
| `REVIEW_ENABLED` | `false` | turns on the button and `POST /v1/traces/:id/review` (otherwise `409 review_unavailable`) |
| `ANTHROPIC_REVIEW_MODEL` | `claude-opus-5-5` | the model for the second opinion only; fault finding keeps `ANTHROPIC_MODEL` |
| `REVIEW_EFFORT` | `medium` | `low`, `medium` or `high`: how hard the model thinks |
| `REVIEW_DEADLINE_MS` | `60000` | the longest one second opinion may take, retries included |
**What it costs.** Every press of the button is one call to Claude Opus with two images, billed to your Anthropic account. One sample run used about 5,200 input tokens (the pictures and the trace data) and 640 output tokens; see [docs/models.md](docs/models.md#ai-second-opinion) for the measured numbers and the accuracy results. The review shares the `/v1/ask` limits (`ASK_MAX_CONCURRENT`, `ASK_MAX_PER_KEY`) and costs 6 rate-limit tokens. From the command line: `bsx review <file.sor>`; the pictures alone, which cost nothing: `bsx plot`, `GET /v1/traces/:id/plot.png` and the MCP `trace_plot` tool.
## Eval
Build once, then run the compiled command line tool (Node 22):
```sh
npm run build # compiles src/ into dist/
node dist/src/cli.js eval make # 44 cases from the 8 scenarios (ideal + variants + traps)
node dist/src/cli.js eval baseline # deterministic find_fault, no model
node dist/src/cli.js eval mock # scripted fake model (no real AI calls) through the real tool loop, used in CI (automated checks on each change)
node dist/src/cli.js eval mock --provider anthropic # the same over the Anthropic Messages API
node dist/src/cli.js eval review mock # the AI second opinion against scripted adversarial models
BEDROCK_API_KEY=... node dist/src/cli.js eval run openai.gpt-oss-20b openai.gpt-oss-120b
ANTHROPIC_API_KEY=... node dist/src/cli.js eval run --provider anthropic claude-sonnet-5-5
ANTHROPIC_API_KEY=... node dist/src/cli.js eval review run claude-sonnet-5-5 claude-opus-5-5
```
Reports land in `eval/out/` (JSON and a markdown table). A case is a hit when both the display distance and the distance past the launch cable are within the tolerance (the largest of 10 m, the pulse width and 0.5% of the distance). The baseline hits 39 of 44; the 5 misses are one-way "gainer" shots (a splice hidden behind a fiber-type change, seen from one end), and each is flagged "Possible gainer" at low confidence with the advice to shoot from the other end.
## Docker
See [Quick start](#with-docker-recommended) above and [docs/docker.md](docs/docker.md). The runtime image is based on `node:22-alpine`, has no `npm`, `npx` or `yarn`, and runs as uid 10001.
## Configuration
Everything is an environment variable, validated at startup (the service refuses to start on a bad value and says which). See [.env.example](.env.example) for every setting with a safe placeholder and a one-line comment. Highlights:
| Setting | What it does |
|---|---|
| `AUTH_MODE` | `apikey`, `proxy` (behind a sign-in gate, [docs/auth.md](docs/auth.md)), `local` (Docker on this computer), `lan` (a server on a home network, no key; needs `LAN_HOSTS`) or `disabled` (refused in production and off loopback) |
| `LAN_HOSTS` | `AUTH_MODE=lan` only: the addresses people open, e.g. `10.0.0.43,backscatter.lan` |
| `API_KEYS` | compared as sha256 digests in constant time; can carry scopes (`key:read+locate`; scopes `read`, `locate`, `ask`) |
| `DEFAULT_UNITS` | `ft` (default) or `m` for server-written text, CSV headers and reports |
| `TRACE_TTL_MIN`, `TRACE_MAX`, `TRACE_MAX_MB`, `TRACE_MAX_PER_KEY` | how long traces live (memory, unless `PERSIST_DIR` is set) and how many are kept; `TRACE_MAX_PER_KEY` defaults to 200 |
| `MAX_UPLOAD_MB`, `ANALYZE_WORKERS`, `ANALYZE_PER_KEY` | upload size and how many files are analyzed at once |
| `AI_PROVIDER`, `REVIEW_ENABLED` | the AI agent and the second opinion (both off by default) |
| `CORS_ORIGINS` | exact origins only |
| `PUBLIC_URL` | the https origin people open, e.g. `https://backscatter.example.com`; adds the Canonical line to `/.well-known/security.txt` (the EKS deploy sets it) |
| `AUDIT_LOG` | an append-only JSON-lines record of who uploaded, asked, labeled and exported what (no file text) |
## Layout
```
src/config.ts env validation, key checks
src/store.ts TTL/LRU trace store (per API key)
src/units.ts feet or meters for server-written text
src/tools/ tool definitions, service layer, the workbench (workbench.ts), finding.ts (the fault answer), plot.ts, sanitizing, compact views, real wiring (deps.ts)
src/http/ Fastify app (app.ts), entry (main.ts), OpenAPI, security helpers
src/mcp/ MCP server (stdio main.ts; HTTP mounted at /mcp)
src/agent/ tool loop and driver seam, Bedrock Mantle and Anthropic drivers, prompt, deterministic answer, the AI second opinion (review.ts), mock servers
src/eval/ case builder and runner
src/web/ the page (static/ is inlined at startup), the Legal dialog's server facts (legal.ts)
src/cli.ts bsx
src/sor, src/trace .sor parsing and trace analysis, event labels (trace/labels.ts)
src/measure cursor measurements
src/span, src/quality span, pass / fail against limit profiles, shot quality
src/multi bidirectional, bend check, baseline, cable batch
src/report PDFs, CSVs, the .sor export, the PNG trace pictures
```
## Legal
- The page's footer links **Legal** and **Security** open one dialog: terms of use, privacy notice, security
(how to report a problem privately, and a plain summary of the controls in [SECURITY.md](SECURITY.md)),
open-source credits and copyright. It is filled from the running settings: how long traces are kept
(`TRACE_TTL_MIN`), whether they are written to disk (`PERSIST_DIR`), which AI service receives data
(`AI_PROVIDER`, `REVIEW_ENABLED`), and who can get in (`AUTH_MODE`). Open it directly with `/#legal` or
`/#security`.
- `/.well-known/security.txt` (RFC 9116) publishes the security contact without sign-in, the standard place
security researchers look. Its `Expires` date must be moved forward yearly (`SECURITY_TXT_EXPIRES` in
`src/web/security-txt.ts`); the tests fail and the server warns 30 days before.
- No cookie banner is needed: the page sets no cookies and keeps only the unit and theme the user picked in
local storage. Adding analytics, ads, third-party content or another cookie would change that, and the
privacy notice with it.
- The code is proprietary: [LICENSE](LICENSE) (all rights reserved; `package.json` says `UNLICENSED`).
- [THIRD-PARTY-NOTICES.txt](THIRD-PARTY-NOTICES.txt) lists every runtime package with its license text, plus the
IBM Plex fonts (SIL Open Font License 1.1). After a dependency change run `npm run notices`;
`test/legal.test.ts` fails when a runtime package or license is missing from it. The Docker build writes its
own copy after `npm prune --omit=dev`, so the image's `/app/THIRD-PARTY-NOTICES.txt` lists exactly what ships.
Security model and data retention: [SECURITY.md](SECURITY.md). Maintainer notes: [CLAUDE.md](CLAUDE.md).
This server cannot be deployed
Maintenance
ActivitySlowing
ResponsivenessNo recent community issues