MCPcopy Index your code
hub / github.com/bgpkit/monocle

github.com/bgpkit/monocle @v1.3.0

Chat with this repo
repository ↗ · DeepWiki ↗ · release v1.3.0 ↗ · + Follow
1,350 symbols 2,978 edges 76 files 586 documented · 43% updated 5d agov1.3.0 · 2026-05-27★ 1804 open issues
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Monocle

Rust Crates.io Docs.rs License

See through all Border Gateway Protocol (BGP) data with a monocle.

Table of Contents

Install

Using cargo

cargo install monocle

Using homebrew on macOS

brew install monocle

Using cargo-binstall

Install cargo-binstall first:

cargo install cargo-binstall

Then install monocle using cargo binstall

cargo binstall monocle

Using Docker

Pull the pre-built image or build locally:

# Build the image locally
docker build -t bgpkit/monocle:latest .

# Or use docker compose
docker compose build

Run monocle commands:

# Show help
docker run --rm bgpkit/monocle:latest

# Run a command (e.g., inspect an ASN)
docker run --rm bgpkit/monocle:latest inspect 13335

# Run with persistent data directory
docker run --rm -v monocle-data:/data bgpkit/monocle:latest inspect 13335

# Start the WebSocket server
docker run --rm -p 8080:8080 -v monocle-data:/data bgpkit/monocle:latest server --address 0.0.0.0 --port 8080

# Using docker compose for server mode
docker compose up -d

Library Usage

Monocle can also be used as a library in your Rust projects. Add it to your Cargo.toml:

[dependencies]
# Default: full CLI binary with all features
monocle = "1.1"

# Library only - all lenses and database operations
monocle = { version = "1.1", default-features = false, features = ["lib"] }

# Library + WebSocket server
monocle = { version = "1.1", default-features = false, features = ["server"] }

Feature Tiers

Monocle uses a simplified feature system with three options:

Feature Description Implies
lib Complete library (database + all lenses + display) -
server WebSocket server for programmatic API access lib
cli (default) Full CLI binary with all functionality lib, server

Documentation

The following documentation files are available in the repository:

File Description
README.md (this file) User-facing CLI and library overview
ARCHITECTURE.md Overall project structure and design principles
DEVELOPMENT.md Contributor guide for adding lenses and fixing bugs
AGENTS.md AI coding agent guidelines and code style
CHANGELOG.md Version history and breaking changes
src/server/README.md WebSocket API specification
src/lens/README.md Lens module patterns and conventions
src/database/README.md Database module overview
examples/README.md Usage examples by feature tier

Architecture

The library is organized into the following core modules:

  • database: All database functionality (requires lib feature)
  • core: Connection management and schema definitions
  • session: One-time storage for search results
  • monocle: Main monocle database with ASInfo, AS2Rel, RPKI, and Pfx2as caching

  • lens: High-level business logic (requires lib feature)

  • time: Time parsing and formatting lens
  • country: Country code/name lookup lens
  • ip: IP information lookup lens
  • parse: MRT file parsing lens with progress tracking
  • search: BGP message search lens with progress tracking
  • rpki: RPKI validation and data lens
  • pfx2as: Prefix-to-AS mapping types
  • as2rel: AS-level relationships lens
  • inspect: Unified AS/prefix inspection lens

  • server: WebSocket API server (requires server feature)

For detailed architecture documentation, see ARCHITECTURE.md.

Example: Using Lenses

use monocle::database::MonocleDatabase;
use monocle::lens::inspect::{InspectLens, InspectQueryOptions};

fn main() -> anyhow::Result<()> {
    // Open the monocle database
    let db = MonocleDatabase::open_in_dir("~/.local/share/monocle")?;

    // Create a lens
    let lens = InspectLens::new(&db);

    // Query AS information
    let options = InspectQueryOptions::default();
    let results = lens.query_asn(13335, &options)?;

    println!("AS{}: {}", results.asn, results.name.unwrap_or_default());

    Ok(())
}

Example: Parse MRT Files with Progress

use monocle::lens::parse::{ParseLens, ParseFilters, ParseProgress};
use std::sync::Arc;

fn main() -> anyhow::Result<()> {
    let lens = ParseLens::new();
    let filters = ParseFilters::default();

    // Define a progress callback
    let callback = Arc::new(|progress: ParseProgress| {
        match progress {
            ParseProgress::Started { file_path } => {
                eprintln!("Started parsing: {}", file_path);
            }
            ParseProgress::Update { messages_processed, rate, .. } => {
                eprintln!("Processed {} messages ({:.0} msg/s)", 
                    messages_processed, rate.unwrap_or(0.0));
            }
            ParseProgress::Completed { total_messages, duration_secs, .. } => {
                eprintln!("Completed: {} messages in {:.2}s", total_messages, duration_secs);
            }
        }
    });

    // Parse with progress tracking
    let elems = lens.parse_with_progress(
        &filters, 
        "path/to/file.mrt", 
        Some(callback)
    )?;

    for elem in elems {
        println!("{:?}", elem);
    }

    Ok(())
}

Usage

Subcommands:

  • parse: parse individual MRT files
  • search: search for matching messages from all available public MRT files
  • rib: reconstruct final RIB state at one or more arbitrary timestamps
  • server: start a WebSocket server for programmatic access
  • inspect: unified AS and prefix information lookup
  • country: utility to look up country name and code
  • time: utility to convert time between unix timestamp and RFC3339 string
  • as2rel: AS-level relationship lookup between ASNs
  • pfx2as: prefix-to-ASN mapping lookup with RPKI validation
  • rpki: RPKI validation and ROA/ASPA listing
  • ip: IP information lookup
  • config: configuration display and database management (refresh, backup, sources)

Global Options

All commands support the following global options:

  • --format <FORMAT>: Output format (table, markdown, json, json-pretty, json-line, psv)
  • --json: Shortcut for --format json-pretty
  • --debug: Print debug information

Top-level help menu:

➜  monocle --help
A commandline application to search, parse, and process BGP information in public sources.


Usage: monocle [OPTIONS] <COMMAND>

Commands:
  parse    Parse individual MRT files given a file path, local or remote
  search   Search BGP messages from all available public MRT files
  rib      Reconstruct final RIB state at one or more arbitrary timestamps
  server   Start the WebSocket server (ws://<address>:<port>/ws, health: http://<address>:<port>/health)
  inspect  Unified AS and prefix information lookup
  country  Country name and code lookup utilities
  time     Time conversion utilities
  rpki     RPKI utilities
  ip       IP information lookup
  as2rel   AS-level relationship lookup between ASNs
  pfx2as   Prefix-to-ASN mapping lookup
  config   Show monocle configuration, data paths, and database management
  help     Print this message or the help of the given subcommand(s)

Options:
  -c, --config <CONFIG>  configuration file path (default: $XDG_CONFIG_HOME/monocle/monocle.toml)
      --debug            Print debug information
      --format <FORMAT>  Output format: table, markdown, json, json-pretty, json-line, psv (default varies by command)
      --json             Output as JSON objects (shortcut for --format json-pretty)
      --no-update        Disable automatic database updates (use existing cached data only)
  -h, --help             Print help
  -V, --version          Print version

monocle parse

Parsing a single MRT file given a local path or a remote URL.

➜  monocle parse --help
Parse individual MRT files given a file path, local or remote

Usage: monocle parse [OPTIONS] <FILE>

Arguments:
  <FILE>
          File path to an MRT file, local or remote

Options:
      --pretty
          Pretty-print JSON output

      --debug
          Print debug information

  -M, --mrt-path <MRT_PATH>
          MRT output file path

  -f, --fields <FIELDS>
          Comma-separated list of fields to output. Available fields: type, timestamp, peer_ip, peer_asn, prefix, as_path, origin, next_hop, local_pref, med, communities, atomic, aggr_asn, aggr_ip, collector

      --format <FORMAT>
          Output format: table, markdown, json, json-pretty, json-line, psv (default varies by command)

      --json
          Output as JSON objects (shortcut for --format json-pretty)

      --order-by <ORDER_BY>
          Order output by field (enables buffering)

          Possible values:
          - timestamp: Order by timestamp (default)
          - prefix:    Order by network prefix
          - peer_ip:   Order by peer IP address
          - peer_asn:  Order by peer AS number
          - as_path:   Order by AS path (string comparison)
          - next_hop:  Order by next hop IP address

      --no-update
          Disable automatic database updates (use existing cached data only)

      --order <ORDER>
          Order direction (asc or desc, default: asc)

          Possible values:
          - asc:  Ascending order (smallest/oldest first)
          - desc: Descending order (largest/newest first)

          [default: asc]

      --time-format <TIME_FORMAT>
          Timestamp output format for non-JSON output (unix or rfc3339)

          Possible values:
          - unix:    Unix timestamp (integer or float) - default for backward compatibility
          - rfc3339: RFC3339/ISO 8601 format (e.g., "2023-10-11T15:00:00Z")

          [default: unix]

  -o, --origin-asn <ORIGIN_ASN>
          Filter by origin AS Number(s), comma-separated. Prefix with ! to exclude

  -p, --prefix <PREFIX>
          Filter by network prefix(es), comma-separated. Prefix with ! to exclude

  -s, --include-super
          Include super-prefixes when filtering

  -S, --include-sub
          Include sub-prefixes when filtering

  -j, --peer-ip <PEER_IP>
          Filter by peer IP address(es)

  -J, --peer-asn <PEER_ASN>
          Filter by peer ASN(s), comma-separated. Prefix with ! to exclude

  -C, --community <COMMUNITIES>
          Filter by BGP community value(s), comma-separated (`A:B` or `A:B:C`). Each part can be a number or `*` wildcard (e.g., `*:100`, `13335:*`, `57866:104:31`). Prefix with ! to exclude

          [aliases: --communities]

  -m, --elem-type <ELEM_TYPE>
          Filter by elem type: announce (a) or withdraw (w)

          Possible values:
          - a: BGP announcement
          - w: BGP withdrawal

  -t, --start-ts <START_TS>
          Filter by start unix timestamp inclusive

  -T, --end-ts <END_TS>
          Filter by end unix timestamp inclusive

  -d, --duration <DURATION>
          Duration from the start-ts or end-ts, e.g. 1h

  -a, --as-path <AS_PATH>
          Filter by AS path regex string

  -h, --help
          Print help (see a summary with '-h')

  -V, --version
          Print version

Multi-value Filters

The parse and search commands support filtering by multiple values with OR logic:

# Match elements from ANY of the specified origin ASNs
monocle parse file.mrt -o 13335,15169,8075

# Match ANY of the specified prefixes
monocle parse file.mrt -p 1.1.1.0/24,8.8.8.0/24

# Match elements from ANY of the specified peer ASNs
monocle parse file.mrt -J 174,2914

Negative Filters

Use the ! prefix to exclude values:

# Exclude elements from AS13335
monocle parse file.mrt -o '!13335'

# Exclude elements from AS13335 AND AS15169
monocle parse file.mrt -o '!13335,!15169'

Note: Cannot mix positive and negative values in the same filter.

Field Selection

Use -f or --fields to select which columns to display:

# Show only prefix, as_path, and origin
monocle parse file.mrt -f prefix,as_path,origin

# Available fields: type, timestamp, peer_ip, peer_asn, prefix, as_path, origin,
#   next_hop, local_pref, med, communities, atomic, aggr_asn, aggr_ip, collector

Output Sorting

Use --order-by and --order to sort the output:

```bash

Sort by timestamp ascending (default)

monocle parse file.mrt --orde

Extension points exported contracts — how you extend this code

WsMethod (Interface)
(no doc) [16 implementers]
src/server/handler.rs

Core symbols most depended-on inside this repo

get
called by 195
src/server/operations.rs
execute
called by 124
src/database/core/connection.rs
is_empty
called by 116
src/lens/rpki/mod.rs
rpki
called by 33
src/database/monocle/mod.rs
pfx2as
called by 32
src/database/monocle/mod.rs
add
called by 32
src/lens/inspect/mod.rs
asinfo
called by 27
src/database/monocle/mod.rs
parse
called by 25
src/lens/time/mod.rs

Shape

Method 620
Function 432
Class 251
Enum 46
Interface 1

Languages

Rust99%
TypeScript1%

Modules by API surface

src/utils.rs78 symbols
src/lens/inspect/mod.rs68 symbols
src/lens/pfx2as/mod.rs55 symbols
src/lens/rpki/mod.rs53 symbols
src/database/monocle/rpki.rs52 symbols
src/lens/search/query_builder.rs49 symbols
src/database/monocle/asinfo.rs46 symbols
src/lens/inspect/types.rs44 symbols
src/database/monocle/pfx2as.rs43 symbols
src/lens/rib/mod.rs40 symbols
src/config.rs39 symbols
src/lens/as2rel/args.rs37 symbols

For agents

$ claude mcp add monocle \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact