Files

346 lines
12 KiB
Go

// Copyright 2026 Beacon Contributors
// SPDX-License-Identifier: AGPL-3.0-or-later
package mcp
import (
"context"
"encoding/base64"
"encoding/json"
"net/url"
"strconv"
"strings"
)
// areaQuery works out whether a value is an IATA code or a region slug, using the server's own list.
func areaQuery(ctx context.Context, s *service, value string) (url.Values, string, error) {
raw, err := s.get(ctx, "/iatas", nil)
if err != nil {
return nil, "", err
}
var rows []struct {
IATA string `json:"iata"`
}
_ = json.Unmarshal(raw, &rows)
code := strings.ToUpper(value)
for _, r := range rows {
if r.IATA == code {
return url.Values{"iatas": {code}}, code, nil
}
}
if len(value) > 64 || strings.ContainsAny(value, "/?#&= ") {
return nil, "", errInvalid("%q is not an IATA code or a region slug. Use beacon_list_areas.", value)
}
raw, err = s.get(ctx, "/regions", nil)
if err != nil {
return nil, "", err
}
var regions []struct {
Slug string `json:"slug"`
}
_ = json.Unmarshal(raw, &regions)
for _, r := range regions {
if strings.EqualFold(r.Slug, value) {
return url.Values{"region": {r.Slug}}, r.Slug, nil
}
}
return nil, "", &callError{Code: codeNotFound, Message: "No area matches " + quote(value) + ". Use beacon_list_areas to see the codes and regions."}
}
func moreTools() []*tool {
return []*tool{
{
name: "beacon_compare_areas", title: "Compare two areas",
desc: "Two areas side by side over the last 24 rolled hours: packets, observations, active observers and node types. Each area is an IATA code or a region slug. More observers means more coverage, so compare packets, not observations.",
args: []arg{
{name: "areaA", kind: "string", required: true, desc: "First area: IATA code or region slug."},
{name: "areaB", kind: "string", required: true, desc: "Second area: IATA code or region slug."},
argDetail},
run: func(ctx context.Context, s *service, a args) (*envelope, error) {
out := map[string]any{}
scope := map[string]any{}
for _, side := range []string{"areaA", "areaB"} {
q, label, err := areaQuery(ctx, s, a.str(side))
if err != nil {
return nil, err
}
part := map[string]any{"area": label}
for _, read := range [][2]string{{"overview", "/stats/overview"}, {"nodeTypes", "/stats/node-types"}} {
raw, err := s.get(ctx, read[1], q)
if err != nil {
return nil, err
}
sh, err := shape(raw, a.detailed())
if err != nil {
return nil, err
}
part[read[0]] = sh.value
}
out[side], scope[side] = part, label
}
return &envelope{Data: out, Scope: scope,
Summary: "Two independent snapshots of the last 24 rolled hours. Coverage differs between areas, so read observation counts with care."}, nil
},
},
{
name: "beacon_compare_nodes", title: "Compare two nodes",
desc: "Two nodes side by side: type, last seen, clock state, neighbor count and how often their packets were heard in the last 24h or 7d. Use it to see which of two repeaters is more active or better heard.",
args: []arg{
{name: "nodeA", kind: "string", required: true, desc: "First node: UUID, name or public key."},
{name: "nodeB", kind: "string", required: true, desc: "Second node: UUID, name or public key."},
{name: "range", kind: "string", enum: []string{"24h", "168h"}, desc: "Activity window. Default 24h."}},
run: func(ctx context.Context, s *service, a args) (*envelope, error) {
rng := a.str("range")
if rng == "" {
rng = "24h"
}
out, scope := map[string]any{}, map[string]any{"range": rng}
for _, side := range []string{"nodeA", "nodeB"} {
e, env, err := s.resolveNode(ctx, a.str(side), nil)
if e == nil {
return choice(env, side), err
}
part := map[string]any{}
for _, read := range []struct {
key, path string
q url.Values
}{{"node", "", nil}, {"activity", "/activity", url.Values{"range": {rng}}}} {
raw, err := s.get(ctx, "/nodes/"+e.ID+read.path, read.q)
if err != nil {
return nil, err
}
sh, err := shape(raw, false)
if err != nil {
return nil, err
}
part[read.key] = trimDiagnosis(read.key, sh.value)
}
if node, ok := part["node"].(map[string]any); ok {
delete(node, "neighbors")
delete(node, "neighborsShown")
}
out[side], scope[side+"Id"] = part, e.ID
}
return &envelope{Data: out, Scope: scope, Notes: []string{untrustedNote},
Summary: "Two nodes over the same window. Heard counts depend on which observers are near each node."}, nil
},
},
{
name: "beacon_list_observer_directory", title: "Observer directory with traffic",
desc: "Observers ranked by how much traffic each reported in a time window (default the last 7 days, 31 days at most). Use it to find the busiest or quietest observers, or to check coverage across an area.",
args: with(areaArgs,
arg{name: "name", kind: "string", desc: "Partial, case-insensitive display name."},
arg{name: "status", kind: "string", enum: []string{"online", "offline"}, desc: "Reported status."},
arg{name: "type", kind: "string", desc: "Observer software type."},
arg{name: "broker", kind: "string", desc: "MQTT broker name."},
arg{name: "scope", kind: "string", desc: "Transport scope name, e.g. #bc."},
arg{name: "sort", kind: "string", enum: []string{"traffic", "name"}, desc: "Order. Default traffic."},
argSince, argUntil, argLimit, argCursor, argDetail),
run: func(ctx context.Context, s *service, a args) (*envelope, error) {
q, scope := url.Values{"limit": {strconv.Itoa(a.limit())}}, map[string]any{}
if err := area(a, q, scope); err != nil {
return nil, err
}
// The REST cursor is only valid with the window of the page it came from, so this
// tool's cursor carries the window with it.
if a.has("cursor") {
if err := applyDirectoryCursor(a.str("cursor"), q); err != nil {
return nil, err
}
} else if err := window(a, q, scope, 0, false); err != nil {
return nil, err
}
for _, n := range []string{"name", "status", "type", "broker", "scope", "sort"} {
setStr(a, q, n, n)
}
raw, err := s.get(ctx, "/observers/directory", q)
if err != nil {
return nil, err
}
sh, err := shape(raw, a.detailed())
if err != nil {
return nil, err
}
items, page, _ := splitPage(sh.value)
if page != nil && page.HasMore {
page.NextCursor = directoryCursor(raw)
page.HasMore = page.NextCursor != ""
}
if m, ok := sh.value.(map[string]any); ok {
for _, k := range []string{"windowStart", "windowEnd", "coverage"} {
if v, ok := m[k]; ok {
scope[k] = v
}
}
}
return &envelope{Data: items, Page: page, Scope: scope, Notes: []string{untrustedNote},
Summary: strconv.Itoa(count(items)) + " observer(s) with their traffic in the window."}, nil
},
},
{
name: "beacon_list_observer_adverts", title: "Adverts heard by an observer",
desc: "Advert packets one observer heard, newest first: which nodes it hears directly or through repeaters, with signal. Use it to see what is in range of a station.",
args: with(observerArgs, argLimit, argCursor),
run: func(ctx context.Context, s *service, a args) (*envelope, error) {
e, env, err := observerFor(ctx, s, a)
if e == nil {
return env, err
}
q := url.Values{"limit": {strconv.Itoa(a.limit())}}
if err := applyCursor(a, q); err != nil {
return nil, err
}
raw, err := s.get(ctx, "/observers/"+e.ID+"/adverts", q)
if err != nil {
return nil, err
}
return respondList(raw, a, entityScope("observer", e), "advert(s)")
},
},
{
name: "beacon_list_brokers", title: "List MQTT brokers",
desc: "The MQTT brokers this server ingests from. kind=connections (default) shows each broker and whether it is connected. kind=sources shows the original broker names observers were seen on in the last 30 days, for servers fed by a rebroadcaster. Brokers are how reports arrive, not radio hops.",
args: []arg{{name: "kind", kind: "string", enum: []string{"connections", "sources"}, desc: "connections or sources."}, argLimit},
run: func(ctx context.Context, s *service, a args) (*envelope, error) {
path := "/brokers"
if a.str("kind") == "sources" {
path = "/brokers/sources"
}
raw, err := s.get(ctx, path, nil)
if err != nil {
return nil, err
}
if !a.has("limit") {
a["limit"] = maxLimit
}
return respondList(raw, a, map[string]any{"kind": orDefault(a.str("kind"), "connections")}, "broker(s)")
},
},
{
name: "beacon_list_scopes", title: "Transport scopes",
desc: "Transport scopes known in an area, or one scope's details when name is given. A scope such as #bc limits how far a flood packet travels. Names are case-sensitive.",
args: with(areaArgs, arg{name: "name", kind: "string", desc: "A scope name, e.g. #bc, to get its details."}, argLimit, argDetail),
run: func(ctx context.Context, s *service, a args) (*envelope, error) {
if name := a.str("name"); name != "" {
if strings.ContainsAny(name, "/?") || len(name) > 64 {
return nil, errInvalid("%q is not a scope name.", name)
}
raw, err := s.get(ctx, "/scopes/"+url.PathEscape(name), nil)
if err != nil {
return nil, err
}
return respondOne(raw, a, map[string]any{"scope": name}, "Scope detail.")
}
q, scope := url.Values{}, map[string]any{}
if err := area(a, q, scope); err != nil {
return nil, err
}
raw, err := s.get(ctx, "/scopes", q)
if err != nil {
return nil, err
}
if !a.has("limit") {
a["limit"] = maxLimit
}
return respondList(raw, a, scope, "scope(s)")
},
},
}
}
// pickTelemetry narrows telemetry points to one field and/or one sensor channel, so a question
// about humidity on channel 2 does not pull every reading into the conversation.
func pickTelemetry(v any, metric string, channel int) (any, bool) {
m, ok := v.(map[string]any)
if !ok {
return v, false
}
points, ok := m["points"].([]any)
if !ok {
return v, false
}
found := false
kept := make([]any, 0, len(points))
for _, p := range points {
point, ok := p.(map[string]any)
if !ok {
continue
}
out := map[string]any{}
for _, k := range []string{"t", "readings"} {
if val, ok := point[k]; ok {
out[k] = val
}
}
if metric == "" {
for k, val := range point {
if k != "sensors" {
out[k] = val
}
}
} else if val, ok := point[metric]; ok && metric != "sensors" {
out[metric], found = val, true
}
var sensors []any
list, _ := point["sensors"].([]any)
for _, sv := range list {
sensor, ok := sv.(map[string]any)
if !ok {
continue
}
if channel > 0 {
if n, _ := sensor["channel"].(json.Number); n.String() != strconv.Itoa(channel) {
continue
}
}
if metric == "" {
sensors, found = append(sensors, sensor), true
continue
}
if val, ok := sensor[metric]; ok {
sensors, found = append(sensors, map[string]any{"channel": sensor["channel"], metric: val}), true
}
}
if len(sensors) > 0 {
out["sensors"] = sensors
}
if len(out) > 2 {
kept = append(kept, out)
}
}
m["points"] = kept
return m, found
}
// directoryCursor packs the next cursor with the exact window it belongs to.
func directoryCursor(raw json.RawMessage) string {
var p struct {
NextCursor int64 `json:"nextCursor"`
WindowStart int64 `json:"windowStart"`
WindowEnd int64 `json:"windowEnd"`
}
if json.Unmarshal(raw, &p) != nil || p.NextCursor <= 0 || p.WindowStart <= 0 || p.WindowEnd <= 0 {
return ""
}
return encodeCursor("dir", strconv.FormatInt(p.NextCursor, 10)+","+strconv.FormatInt(p.WindowStart, 10)+","+strconv.FormatInt(p.WindowEnd, 10))
}
func applyDirectoryCursor(token string, q url.Values) error {
bad := errInvalid("cursor is not valid. Pass page.nextCursor from the previous call unchanged.")
raw, err := base64.RawURLEncoding.DecodeString(token)
key, value, ok := strings.Cut(string(raw), "=")
parts := strings.Split(value, ",")
if err != nil || !ok || key != "dir" || len(parts) != 3 {
return bad
}
for _, p := range parts {
if n, err := strconv.ParseInt(p, 10, 64); err != nil || n <= 0 {
return bad
}
}
q.Set("cursor", parts[0])
q.Set("since", parts[1])
q.Set("until", parts[2])
return nil
}