mirror of
https://github.com/MeshCore-Beacon/beacon-server.git
synced 2026-12-06 09:44:41 +00:00
Serves the public read API to AI assistants at /mcp. Off by default; private when mcp.keys are set, public otherwise. Tools call the REST handlers in-process, so validation, guards and errors match REST.
143 lines
5.9 KiB
Go
143 lines
5.9 KiB
Go
// Copyright 2026 Beacon Contributors
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package mcp
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/url"
|
|
"regexp"
|
|
"strings"
|
|
|
|
sdk "github.com/modelcontextprotocol/go-sdk/mcp"
|
|
)
|
|
|
|
const (
|
|
id36 = `([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})`
|
|
jsonT = "application/json"
|
|
)
|
|
|
|
// resourceRoute maps one URI shape to a public read. The patterns are anchored and take only the
|
|
// characters an identifier can hold, so a URI cannot reach any other path.
|
|
type resourceRoute struct {
|
|
template string
|
|
name string
|
|
title string
|
|
desc string
|
|
pattern *regexp.Regexp
|
|
path func(m []string) (string, url.Values)
|
|
}
|
|
|
|
func route(template, name, title, desc, pattern string, path func(m []string) (string, url.Values)) resourceRoute {
|
|
return resourceRoute{template: template, name: name, title: title, desc: desc, pattern: regexp.MustCompile("^" + pattern + "$"), path: path}
|
|
}
|
|
|
|
func plain(prefix, suffix string) func(m []string) (string, url.Values) {
|
|
return func(m []string) (string, url.Values) { return prefix + strings.ToLower(m[1]) + suffix, nil }
|
|
}
|
|
|
|
var resourceRoutes = []resourceRoute{
|
|
route("beacon://nodes/{id}", "node", "Node", "One node's details. Supports live update notices.",
|
|
`beacon://nodes/`+id36, plain("/nodes/", "")),
|
|
route("beacon://nodes/{id}/polling", "node-polling", "Node polling", "Who polls a node for telemetry.",
|
|
`beacon://nodes/`+id36+`/polling`, plain("/nodes/", "/polling")),
|
|
route("beacon://nodes/{id}/telemetry", "node-telemetry", "Node telemetry", "A polled node's readings over the last 7 days.",
|
|
`beacon://nodes/`+id36+`/telemetry`, plain("/nodes/", "/telemetry")),
|
|
route("beacon://nodes/{id}/neighbors", "node-neighbors", "Node neighbors", "Nodes heard next to this one.",
|
|
`beacon://nodes/`+id36+`/neighbors`, plain("/nodes/", "/neighbors")),
|
|
route("beacon://nodes/{id}/activity", "node-activity", "Node activity", "Hourly heard-activity for the last 24 hours.",
|
|
`beacon://nodes/`+id36+`/activity`, plain("/nodes/", "/activity")),
|
|
route("beacon://observers/{id}", "observer", "Observer", "One observer's details. Supports live update notices.",
|
|
`beacon://observers/`+id36, plain("/observers/", "")),
|
|
route("beacon://packets/{hash}", "packet", "Packet", "One packet with its observations.",
|
|
`beacon://packets/([0-9a-fA-F]{8,64})`, plain("/packets/", "")),
|
|
route("beacon://channels/{id}", "channel", "Channel", "One public channel.",
|
|
`beacon://channels/([0-9]{1,9})`, plain("/channels/", "")),
|
|
route("beacon://traces/{tag}", "trace", "Trace", "One trace run.",
|
|
`beacon://traces/([0-9a-fA-F]{1,32})`, plain("/traces/", "")),
|
|
route("beacon://regions/{id}", "region", "Region", "One region and its IATA codes.",
|
|
`beacon://regions/([0-9]{1,9})`, plain("/regions/", "")),
|
|
route("beacon://iatas/{iata}", "iata", "IATA area", "One IATA area.",
|
|
`beacon://iatas/([A-Za-z0-9]{2,8})`, func(m []string) (string, url.Values) { return "/iatas/" + strings.ToUpper(m[1]), nil }),
|
|
route("beacon://iatas/{iata}/overview", "iata-overview", "IATA area overview", "Activity in one IATA area over the last 24 rolled hours.",
|
|
`beacon://iatas/([A-Za-z0-9]{2,8})/overview`, func(m []string) (string, url.Values) {
|
|
return "/stats/overview", url.Values{"iatas": {strings.ToUpper(m[1])}}
|
|
}),
|
|
}
|
|
|
|
func (s *service) registerResources() {
|
|
for _, r := range resourceRoutes {
|
|
s.server.AddResourceTemplate(&sdk.ResourceTemplate{
|
|
URITemplate: r.template, Name: r.name, Title: r.title, Description: r.desc, MIMEType: jsonT,
|
|
}, s.readResource)
|
|
}
|
|
s.server.AddResource(&sdk.Resource{
|
|
URI: "beacon://server/info", Name: "server-info", Title: "Server info", MIMEType: jsonT,
|
|
Description: "Server version, features and display units.",
|
|
}, s.readResource)
|
|
s.server.AddResource(&sdk.Resource{
|
|
URI: "beacon://docs/overview", Name: "overview", Title: "How to use this server", MIMEType: "text/markdown",
|
|
Description: "MeshCore concepts and the tools this server offers.",
|
|
}, s.readResource)
|
|
}
|
|
|
|
// readResource answers every resource. The budget and concurrency slot come from limitMiddleware.
|
|
func (s *service) readResource(ctx context.Context, req *sdk.ReadResourceRequest) (*sdk.ReadResourceResult, error) {
|
|
uri := req.Params.URI
|
|
if len(uri) > 200 {
|
|
return nil, sdk.ResourceNotFoundError("")
|
|
}
|
|
switch uri {
|
|
case "beacon://docs/overview":
|
|
return textResource(uri, "text/markdown", s.overview()), nil
|
|
case "beacon://server/info":
|
|
return s.jsonResource(ctx, uri, "/info", nil)
|
|
}
|
|
for _, r := range resourceRoutes {
|
|
if m := r.pattern.FindStringSubmatch(uri); m != nil {
|
|
path, q := r.path(m)
|
|
return s.jsonResource(ctx, uri, path, q)
|
|
}
|
|
}
|
|
if body, mime, ok := s.skillResource(uri); ok {
|
|
return textResource(uri, mime, body), nil
|
|
}
|
|
return nil, sdk.ResourceNotFoundError(uri)
|
|
}
|
|
|
|
func (s *service) jsonResource(ctx context.Context, uri, path string, q url.Values) (*sdk.ReadResourceResult, error) {
|
|
raw, err := s.get(ctx, path, q)
|
|
if err != nil {
|
|
if ce, ok := err.(*callError); ok && ce.Code == codeNotFound {
|
|
return nil, sdk.ResourceNotFoundError(uri)
|
|
}
|
|
return nil, publicError(err)
|
|
}
|
|
sh, err := shape(raw, false)
|
|
if err != nil {
|
|
return nil, publicError(err)
|
|
}
|
|
body, err := json.Marshal(sh.value)
|
|
if err != nil || len(body) > resultMaxBytes {
|
|
return nil, publicError(&callError{Code: codeTooLarge, Message: "This resource is too large to read. Use the matching tool with a limit."})
|
|
}
|
|
return textResource(uri, jsonT, string(body)), nil
|
|
}
|
|
|
|
func textResource(uri, mime, text string) *sdk.ReadResourceResult {
|
|
return &sdk.ReadResourceResult{Contents: []*sdk.ResourceContents{{URI: uri, MIMEType: mime, Text: text}}}
|
|
}
|
|
|
|
// overview is the server guide as a readable document.
|
|
func (s *service) overview() string {
|
|
var b strings.Builder
|
|
b.WriteString("# MeshCore Beacon\n\n")
|
|
b.WriteString(instructions)
|
|
b.WriteString("\n\n## Tools\n\n")
|
|
for _, t := range s.tools {
|
|
b.WriteString("- `" + t.name + "`: " + t.desc + "\n")
|
|
}
|
|
return b.String()
|
|
}
|