mirror of
https://github.com/MeshCore-Beacon/beacon-server.git
synced 2026-12-06 05:04:31 +00:00
298 lines
12 KiB
Go
298 lines
12 KiB
Go
// Copyright 2026 Beacon Contributors
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package mcp
|
|
|
|
import (
|
|
"context"
|
|
"net/url"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/MeshCore-Beacon/beacon-server/internal/iatadb"
|
|
)
|
|
|
|
var countryCode = regexp.MustCompile(`^[A-Z]{2}$`)
|
|
|
|
// rowContains reports whether any of the named string fields contains text, ignoring case.
|
|
func rowContains(row map[string]any, text string, keys ...string) bool {
|
|
for _, k := range keys {
|
|
if v, _ := row[k].(string); v != "" && strings.Contains(strings.ToLower(v), text) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// maxAreas bounds the area list. A server that imports a full airport catalogue has several hundred.
|
|
const maxAreas = 1000
|
|
|
|
func networkTools() []*tool {
|
|
return []*tool{
|
|
{
|
|
name: "beacon_get_server_info", title: "Server info",
|
|
desc: "What this Beacon server is and supports: version, enabled features, display units, and the limits that apply to these tools. Call it once if you need to know what is available.",
|
|
args: []arg{argDetail},
|
|
run: func(ctx context.Context, s *service, a args) (*envelope, error) {
|
|
raw, err := s.get(ctx, "/info", nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
sh, err := shape(raw, a.detailed())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
names := make([]string, 0, len(s.tools))
|
|
for _, t := range s.tools {
|
|
names = append(names, t.name)
|
|
}
|
|
return &envelope{Summary: "Beacon server " + s.version + ", read-only access.", Data: map[string]any{
|
|
"server": sh.value,
|
|
"mcp": map[string]any{
|
|
"access": "read-only public data; no accounts, no writes",
|
|
"defaultLimit": defaultLimit,
|
|
"maxLimit": maxLimit,
|
|
"lookupsPerCall": callMaxReads,
|
|
"callTimeoutSecs": int(callDeadline / time.Second),
|
|
"operations": len(s.ops),
|
|
"tools": names,
|
|
"liveSubscription": s.subscriptionsOn(),
|
|
},
|
|
}}, nil
|
|
},
|
|
},
|
|
{
|
|
name: "beacon_list_areas", title: "List areas",
|
|
desc: "The areas this server covers: IATA codes with display name, country and continent, and regions (named groups of IATA codes). Call this when a question names a place, to find the code to pass as iata or region. Servers can have hundreds of codes, so filter with country or search when you can.",
|
|
args: []arg{
|
|
{name: "country", kind: "string", desc: "Only IATA codes in this country: ISO 3166-1 two-letter code, e.g. CA or US."},
|
|
{name: "search", kind: "string", desc: "Only IATA codes or regions whose code, slug or name contains this text."},
|
|
argDetail},
|
|
run: func(ctx context.Context, s *service, a args) (*envelope, error) {
|
|
country, search := strings.ToUpper(a.str("country")), strings.ToLower(a.str("search"))
|
|
if country != "" && !countryCode.MatchString(country) {
|
|
return nil, errInvalid("country must be a two-letter ISO code such as CA.")
|
|
}
|
|
scope := map[string]any{}
|
|
if country != "" {
|
|
scope["country"] = country
|
|
}
|
|
if search != "" {
|
|
scope["search"] = search
|
|
}
|
|
out := map[string]any{}
|
|
var notes []string
|
|
for _, key := range []string{"iatas", "regions"} {
|
|
raw, err := s.get(ctx, "/"+key, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
sh, err := shape(raw, a.detailed())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
rows, _ := sh.value.([]any)
|
|
kept := make([]any, 0, len(rows))
|
|
for _, r := range rows {
|
|
row, ok := r.(map[string]any)
|
|
if !ok {
|
|
continue
|
|
}
|
|
if key == "iatas" {
|
|
code, _ := row["iata"].(string)
|
|
// The airport table ships with the server; an unknown code just has no country.
|
|
if e, ok := iatadb.Lookup(strings.ToUpper(code)); ok {
|
|
row["country"], row["continent"] = e.Country, e.Continent
|
|
}
|
|
if country != "" && row["country"] != country {
|
|
continue
|
|
}
|
|
} else if country != "" {
|
|
// Regions span codes and have no single country.
|
|
continue
|
|
}
|
|
if search != "" && !rowContains(row, search, "iata", "displayName", "slug", "name") {
|
|
continue
|
|
}
|
|
kept = append(kept, row)
|
|
}
|
|
list, page := truncateList(any(kept), maxAreas)
|
|
if page != nil {
|
|
notes = append(notes, "Only the first "+strconv.Itoa(maxAreas)+" of "+strconv.Itoa(len(kept))+" "+key+" are listed. Filter with country or search.")
|
|
}
|
|
out[key] = list
|
|
}
|
|
if count(out["iatas"])+count(out["regions"]) == 0 {
|
|
return &envelope{Status: "not_found", Scope: scope, Summary: "No area matches. Call beacon_list_areas without filters to see them all."}, nil
|
|
}
|
|
return &envelope{Data: out, Scope: scope, Notes: notes,
|
|
Summary: strconv.Itoa(count(out["iatas"])) + " IATA area(s) and " + strconv.Itoa(count(out["regions"])) + " region(s). country and continent come from the airport code, not from where traffic was heard."}, nil
|
|
},
|
|
},
|
|
{
|
|
name: "beacon_get_network_overview", title: "Network overview",
|
|
desc: "A snapshot of an area over the last 24 rolled hours: packets, observations, active observers, plus the mix of node types and payload types. Use it for \"how busy is the mesh\" or \"what is on the network\" questions.",
|
|
args: with(areaArgs, argDetail),
|
|
run: func(ctx context.Context, s *service, a args) (*envelope, error) {
|
|
q, scope := url.Values{}, map[string]any{}
|
|
if err := area(a, q, scope); err != nil {
|
|
return nil, err
|
|
}
|
|
out := map[string]any{}
|
|
for _, part := range [][2]string{{"overview", "/stats/overview"}, {"nodeTypes", "/stats/node-types"}, {"payloadTypes", "/stats/payload-breakdown"}} {
|
|
raw, err := s.get(ctx, part[1], q)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
sh, err := shape(raw, a.detailed())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out[part[0]] = sh.value
|
|
}
|
|
return &envelope{Data: out, Scope: scope,
|
|
Summary: "Last 24 rolled hours. Packets are distinct transmissions; observations count every time an observer heard one."}, nil
|
|
},
|
|
},
|
|
{
|
|
name: "beacon_get_rankings", title: "Rankings",
|
|
desc: "Top lists for an area: most-heard nodes, busiest observers, most active chat senders, top advertisers, or repeaters with the worst clock drift.",
|
|
args: with(areaArgs,
|
|
arg{name: "metric", kind: "string", required: true,
|
|
enum: []string{"nodes", "observers", "talkers", "advertisers_flood", "advertisers_direct", "clock_drift"},
|
|
desc: "nodes: by advert hearings (default last 7d). observers: by observations (24h). talkers: by decrypted channel messages (24h). advertisers_flood / advertisers_direct: by advert packets sent (24h). clock_drift: repeaters and room servers whose clock is off, worst first."},
|
|
argSince, argLimit, argDetail),
|
|
run: func(ctx context.Context, s *service, a args) (*envelope, error) {
|
|
q, scope := url.Values{"limit": {strconv.Itoa(a.limit())}}, map[string]any{"metric": a.str("metric")}
|
|
if err := area(a, q, scope); err != nil {
|
|
return nil, err
|
|
}
|
|
path := map[string]string{
|
|
"nodes": "/stats/top-nodes", "observers": "/stats/top-observers", "talkers": "/stats/top-talkers",
|
|
"advertisers_flood": "/stats/top-advertisers", "advertisers_direct": "/stats/top-advertisers",
|
|
"clock_drift": "/stats/clock-drift",
|
|
}[a.str("metric")]
|
|
switch a.str("metric") {
|
|
case "advertisers_flood":
|
|
q.Set("sort", "flood")
|
|
case "advertisers_direct":
|
|
q.Set("sort", "direct")
|
|
}
|
|
if a.str("metric") != "clock_drift" {
|
|
if err := window(a, q, scope, 0, false); err != nil {
|
|
return nil, err
|
|
}
|
|
} else if a.has("since") {
|
|
return nil, errInvalid("clock_drift takes no time window.")
|
|
}
|
|
raw, err := s.get(ctx, path, q)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return respondList(raw, a, scope, "row(s)")
|
|
},
|
|
},
|
|
{
|
|
name: "beacon_get_stats_series", title: "Activity over time",
|
|
desc: "Hourly network activity for an area between two times: packets and observations per hour. Use it for trends and \"how did activity change\" questions. Hours are whole and history goes back about 90 days.",
|
|
args: with(areaArgs, argSince, argUntil, argDetail),
|
|
run: func(ctx context.Context, s *service, a args) (*envelope, error) {
|
|
return statWindow(ctx, s, a, "/stats/series", "Hourly activity.")
|
|
},
|
|
},
|
|
{
|
|
name: "beacon_get_reception_stats", title: "Reception statistics",
|
|
desc: "How well packets are received in an area between two times. kind=signal gives SNR and RSSI distributions and hourly trends. kind=paths gives hop-count and path hash-width distributions.",
|
|
args: with(areaArgs,
|
|
arg{name: "kind", kind: "string", required: true, enum: []string{"signal", "paths"}, desc: "signal or paths."},
|
|
argSince, argUntil, argDetail),
|
|
run: func(ctx context.Context, s *service, a args) (*envelope, error) {
|
|
return statWindow(ctx, s, a, "/stats/"+a.str("kind"), "Reception statistics ("+a.str("kind")+").")
|
|
},
|
|
},
|
|
{
|
|
name: "beacon_get_network_breakdown", title: "Network breakdown",
|
|
desc: "Counts for an area split one way: by payload type, node type, radio preset, transport scope, or observations per hour per IATA.",
|
|
args: with(areaArgs,
|
|
arg{name: "by", kind: "string", required: true,
|
|
enum: []string{"payload_type", "node_type", "radio_preset", "scope", "hourly_observations"},
|
|
desc: "What to split by."},
|
|
argSince, argLimit, argDetail),
|
|
run: func(ctx context.Context, s *service, a args) (*envelope, error) {
|
|
q, scope := url.Values{}, map[string]any{"by": a.str("by")}
|
|
if err := area(a, q, scope); err != nil {
|
|
return nil, err
|
|
}
|
|
by := a.str("by")
|
|
path := map[string]string{
|
|
"payload_type": "/stats/payload-breakdown", "node_type": "/stats/node-types", "radio_preset": "/stats/radio-presets",
|
|
"scope": "/stats/scopes", "hourly_observations": "/stats/observations",
|
|
}[by]
|
|
if by == "node_type" || by == "radio_preset" {
|
|
if a.has("since") {
|
|
return nil, errInvalid("%s takes no time window.", by)
|
|
}
|
|
} else if err := window(a, q, scope, 0, false); err != nil {
|
|
return nil, err
|
|
}
|
|
raw, err := s.get(ctx, path, q)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !a.has("limit") {
|
|
a["limit"] = maxLimit
|
|
}
|
|
return respondList(raw, a, scope, "row(s)")
|
|
},
|
|
},
|
|
{
|
|
name: "beacon_compare_observers", title: "Compare two observers",
|
|
desc: "Compare the flood packets two observers reported over the same window: how many each heard, how many both heard, and what each missed. Use it to judge relative coverage of two stations.",
|
|
args: with(areaArgs,
|
|
arg{name: "observerA", kind: "string", required: true, desc: "First observer: UUID or display name."},
|
|
arg{name: "observerB", kind: "string", required: true, desc: "Second observer: UUID or display name."},
|
|
argSince, argUntil, argDetail),
|
|
run: func(ctx context.Context, s *service, a args) (*envelope, error) {
|
|
q, scope := url.Values{}, map[string]any{}
|
|
if err := area(a, q, scope); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := window(a, q, scope, 24*time.Hour, true); err != nil {
|
|
return nil, err
|
|
}
|
|
for _, side := range []string{"observerA", "observerB"} {
|
|
e, env, err := s.resolveObserver(ctx, a.str(side), nil)
|
|
if e == nil {
|
|
return choice(env, side), err
|
|
}
|
|
q.Set(side, e.ID)
|
|
scope[side] = e.ID
|
|
}
|
|
raw, err := s.get(ctx, "/stats/observer-comparison", q)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return respondOne(raw, a, scope, "Observer comparison. A packet one side missed says nothing about why.")
|
|
},
|
|
},
|
|
}
|
|
}
|
|
|
|
// statWindow answers the stats reads that need both ends of a time window; since defaults to 24h ago.
|
|
func statWindow(ctx context.Context, s *service, a args, path, summary string) (*envelope, error) {
|
|
q, scope := url.Values{}, map[string]any{}
|
|
if err := area(a, q, scope); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := window(a, q, scope, 24*time.Hour, true); err != nil {
|
|
return nil, err
|
|
}
|
|
raw, err := s.get(ctx, path, q)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return respondOne(raw, a, scope, summary)
|
|
}
|