The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
Give agents Beacon Intel tools in the local MCP server
Claude87c4e8ec9021
diff --git a/CLAUDE.md b/CLAUDE.mdindex 772b410c..1c4f3b71 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -32,7 +32,7 @@ Do not recreate or depend on removed `asymptote` mirror trees. Keep new work foc- Session backfill (`cli/beacon/cmd/endpoint_backfill.go`; docs in `docs/cli/endpoint-install.mdx#session-backfill` and `docs/cli/endpoint-connect.mdx#session-backfill`): after every successful install (user or system mode), every session-store collector runs once with `CollectOptions.Since` (30 days; `sessionwindow.Recent` keeps those sessions, newest first, and never touches the cursors of the rest) and a shared `writer.Budget` (24 MiB, at most 12 MiB per runtime through `Budget.Sub`; a refused append returns `writer.ErrBudgetSpent`, the collector stops with cursors past only what was written, and a manual sync reads the rest). A new session-store collector takes both fields, reads its store only through `internal/sessionfs` (a test parses every collector package to enforce it), and joins `endpointBackfillRunners` and that test's list. Every connect, first or re-connect, user or system, runs the same sweep before enrollment (skipped when install just ran it) and, before the forwarder starts, `asymptote.StageBackfill` copies the window's `harness.collection_method=poll` lines into `cloud-backfill.jsonl` beside the runtime log, which the `beacon_backfill` Vector source (fingerprinted `device_and_inode`, so each atomically restaged copy is a new file) reads from the beginning into the runtime sink through the same privacy transform. Live hook/OTLP/plugin history before the connection point stays local. Re-connects restage, so a resend of already-shipped lines is expected and rests on the deterministic `event.id`; a privacy-mode change clears the checkpoints and the restage renames the new-mode copy over the old one (kept until then so the copy is always a new inode; deleted instead when nothing restages), and `disconnect` removes it. System mode runs the collectors under `withUserHome` for the active console user (`activeConsoleUser`), with cursors under the system base directory, and reports a skip when nobody is logged in; root is reading a home the console user controls, so the sweep runs under `sessionfs.Confine` (an `os.Root` on that home, files owned by the home's owner only, non-blocking opens that refuse FIFOs/devices, SQLite read from a private snapshot under `<SystemBaseDir>/state/backfill-snapshots`, retried until the database size/change counter and WAL header are unchanged across the copy, and refused past `sessionfs.MaxSnapshotBytes` (512 MiB with its WAL) with the runtime's sync command named in the report), and refused paths read as absent and are listed in the report. User-mode sync and backfill stay unconfined. The wizard's confirm screen names the upload (`WizardOptions.BackfillDays`). Dry-run, `--no-backfill` and `BEACON_BACKFILL=0` skip all of it; the cmd tests run with `BEACON_BACKFILL=0` set in `TestMain`.- `beacon endpoint install` has a full-screen onboarding wizard on interactive user TTYs. It signs in, preselects Beacon Cloud, requires an explicit choice to opt out to Local, and asks Managed users to choose Standard or Metadata-only privacy. Signing in alone still moves no telemetry. Confirming Beacon Cloud does: the confirm screen states that it installs Beacon and starts forwarding, and names what the selected privacy mode sends, so that screen is the consent point. The managed destination is recorded only after enrollment succeeds, so a failed enrollment leaves a working local install, prints `beacon endpoint connect` as the retry, and re-offers the question on the next install. The onboarding record is written only after `lifecycle.Install` returns, because a profile written first left a failed install looking onboarded and silently skipped the wizard on the retry. Explicit `install --connect` is unchanged. The wizard is skipped for system/root/CI/piped-stdin/dry-run or `BEACON_ONBOARDING=0`; those unattended paths must never gain an account or browser dependency. Legacy `BEACON_ONBOARDING_EMAIL`/`USAGE` submissions remain only for fleet compatibility. After the destination, the wizard shows an agent tools screen; every row is preselected (opt-out, space toggles). Beacon Cloud MCP is offered only with Beacon Cloud and runs the `beacon mcp connect` flow (`connectCloudMCP` with `yes`, OAuth, detected harnesses) only after the endpoint is connected (or already was), via `finishCloudSetup`; a failed enrollment skips it and names the retry. The Beacon Agent Skills are offered for either destination and installed user-wide into `~/.agents/skills` and, when Claude Code is set up, `~/.claude/skills` (`cli/beacon/internal/agentskills`, `beacon skills install|uninstall`; a `.beacon-managed` marker decides what Beacon may replace or remove; install and repair refresh only copies Beacon already wrote). Both run after `lifecycle.Install` returns and warn rather than fail. The answers are recorded as `onboarding.cloud_mcp`/`agent_skills`. Implementation lives in `cli/beacon/internal/onboarding`, `cli/beacon/cmd/endpoint_onboarding.go`, `cli/beacon/cmd/endpoint_install.go` and `cli/beacon/cmd/agent_tools.go`; keep `docs/cli/endpoint-onboarding.mdx` and `docs/cli/skills.mdx` in sync.- The update notice on bare interactive `beacon` (`cli/beacon/cmd/root.go`, cache in `cli/beacon/internal/updatecheck/cache.go`; docs in `docs/cli/version.mdx`) follows the Codex/Claude Code pattern: it reads `~/.beacon/endpoint/update-check.json` and never waits on the network, and only when that cache is a day old does it start a detached `beacon version refresh` (hidden) that asks GitHub for the latest release and rewrites the cache, failures included. It is the CLI's one background network call; it never runs from hooks, other commands, non-TTY output, CI or dev builds, and `BEACON_UPDATE_CHECK=0` turns it off. Installs other than Homebrew and the system package get the release download, because `beacon endpoint update` applies only to the system package.-- Beacon Intel (client, request hardening, MCP tool specs and argument parsing in `pkg/asymptoteobserve/intelapi`, shared with Beacon Cloud MCP so both servers offer one contract; the CLI's environment handling in `cli/beacon/internal/intel`; `cli/beacon/cmd/intel.go`; docs in `docs/cli/intel.mdx`) reads the free public index at `https://intel.beacon.sh` (the `intel/` app in ai-supply-chain-oracle, API `intel.v1`: `/api/v1/lookup`, `/artifact`, `/check`, `/status`) so a person or agent can check an MCP server or skill before installing or running it. It needs no account and sends no token, key or telemetry: only what the caller names and the User-Agent. Only an explicit `beacon intel` command reaches it; hooks, plugins and background jobs never do. Requests refuse redirects, cap the answer at 4 MiB, and accept only answers marked `intel.v1`. `BEACON_INTEL=0` turns it off and `BEACON_INTEL_URL` names another host (https, or http on loopback). Everything printed from an answer goes through `termLine` (one line, no control or escape characters, bounded), and not found never reads as safe. `pkg/asymptoteobserve/intelapi/contract_test.go` runs the client against a real intel serving its `tests/api/seed.sql` when `BEACON_TEST_INTEL_URL` is set; run it when either side changes a field.+- Beacon Intel (client, request hardening, MCP tool specs and argument parsing in `pkg/asymptoteobserve/intelapi`, shared with Beacon Cloud MCP so both servers offer one contract; the CLI's environment handling and the inventory-to-identifier mapping in `cli/beacon/internal/intel`; `cli/beacon/cmd/intel.go`; docs in `docs/cli/intel.mdx`) reads the free public index at `https://intel.beacon.sh` (the `intel/` app in ai-supply-chain-oracle, API `intel.v1`: `/api/v1/lookup`, `/artifact`, `/check`, `/status`) so a person or agent can check an MCP server or skill before installing or running it. It needs no account and sends no token, key or telemetry: only what the caller names and the User-Agent. Only an explicit `beacon intel` command or an agent's call to one of the local MCP server's `intel_*` tools (`cli/beacon/internal/mcpserver/intel_tools.go`) reaches it; hooks, plugins and background jobs never do. `intel_check_installed` scans inventory in memory and sends only identifiers `intel.FromInventory` derives: by default npm/PyPI packages from the public registries named in a server's launch command (`cmd /c` unwrapped; an unrecognized launcher option stops the parse rather than guessing which word is the package), and only with `include_private_names` the names that may be private (configured server names, packages that may come from a registry or index other than the public one, as named by the command (`--registry`, `--index-url`, a config file), the server's `env`/`envFile`, or what the launcher itself reads (`intel.LocalRegistries`: inherited `npm_config_*`/`UV_*`/`PIP_*` and the user, system and working-directory `.npmrc`, `.yarnrc.yml`, `bunfig.toml`, `pip.conf`, `uv.toml`, `pyproject.toml`; a private npm scope holds back only that scope), skill names); never paths, URLs, env or other args. A match made by name, including a package the index could only match by name, is marked `name_only`; `dry_run` sends nothing, and the tests assert no secret, path or argument reaches a request. Requests refuse redirects, cap the answer at 4 MiB, and accept only answers marked `intel.v1`. `BEACON_INTEL=0` turns it off and `BEACON_INTEL_URL` names another host (https, or http on loopback). Everything printed from an answer goes through `termLine` (one line, no control or escape characters, bounded), and not found never reads as safe. `pkg/asymptoteobserve/intelapi/contract_test.go` runs the client against a real intel serving its `tests/api/seed.sql` when `BEACON_TEST_INTEL_URL` is set; run it when either side changes a field.- Do not add dependency vulnerability scanning, OSV/GHSA lookups, package remediation, or other vulnerability-enforcement flows to the public hook path.- Do not add broad runtime enforcement unless explicitly requested. Current control behavior is limited to hook-native approvals/denials exposed by supported agent runtimes.- Keep destination support shaped like the existing local JSONL and customer-managed forwarding paths. Beacon may render supported packs or token-based endpoint forwarders, but should not add hosted SIEM dependencies or store third-party service credentials beyond the explicit supported configs. Elastic remains a file-tailing pack over local JSONL.diff --git a/cli/beacon/internal/intel/installed.go b/cli/beacon/internal/intel/installed.gonew file mode 100644index 00000000..62e59786--- /dev/null+++ b/cli/beacon/internal/intel/installed.go@@ -0,0 +1,469 @@+package intel++import (+ "path/filepath"+ "regexp"+ "sort"+ "strings"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/inventory"+)++// What a machine has installed, as Beacon Intel lookups. Like cve.now's check_stack reads a+// lockfile, this reads the MCP servers and skills Beacon's inventory finds in each runtime's+// own config, and names each the way the index does.+//+// By default only a public identifier derived here leaves the machine: an npm or PyPI package+// named in a server's launch command and fetched from the public registry. Names that may be+// private (a server's configured name, a package from a registry or index named by the command,+// the server's env, or the launcher's own config and environment, a skill's name) are sent only when the caller opts in. Paths, URLs, environment, other arguments and+// the rest of a definition are never sent.++// Installed is one lookup and every place it was found.+type Installed struct {+ Kind string `json:"kind"`+ Q string `json:"q"`+ Basis string `json:"basis"`+ Sources []InstalledSource `json:"found_in"`+}++// InstalledSource is one configured MCP server or skill.+type InstalledSource struct {+ Runtime string `json:"runtime"`+ Name string `json:"name"`+ Scope string `json:"scope"`+}++// Skipped is a configured server or skill nothing was sent for, and why.+type Skipped struct {+ Kind string `json:"kind"`+ Runtime string `json:"runtime"`+ Name string `json:"name"`+ Reason string `json:"reason"`+}++const (+ BasisNPM = "npm package in its launch command"+ BasisPyPI = "PyPI package in its launch command"+ BasisPrivateNPM = "npm package from a private registry in its launch command"+ BasisPrivatePyPI = "PyPI package from a private index in its launch command"+ BasisServerName = "configured server name"+ BasisSkillName = "skill name"++ ReasonBeacon = "Beacon's own"+ ReasonNoPackage = "no npm or PyPI package Beacon can read with confidence in its launch command; pass include_private_names to look it up by its configured name"+ ReasonRemote = "a remote URL; pass include_private_names to look it up by its configured name"+ ReasonPrivatePackage = "its package comes from a private registry or index, so its name may be private; pass include_private_names to send it"+ ReasonPrivateSkill = "a skill's name may be one a person gave a private skill; pass include_private_names to check skills by name"+ ReasonNoName = "no name to look up"+)++// FromInventoryOptions tunes FromInventory.+type FromInventoryOptions struct {+ // IncludePrivateNames also sends names that may be private: a server's configured name when+ // its command names no package, a package from a private registry or index, and skill+ // names. Off by default, so only packages from the public npm and PyPI registries leave.+ IncludePrivateNames bool+ // Registries is what the machine's launcher configuration says about registries and+ // indexes (LocalRegistries); a package it may route elsewhere is held back as private.+ Registries Registries+ // BeaconSkills are skill names Beacon installs itself (agentskills.Names), never checked.+ BeaconSkills []string+}++var beaconServers = map[string]bool{"beacon": true, "beacon-managed": true}++// FromInventory turns an inventory scan into deduplicated lookups, servers first, each list in+// a stable order.+func FromInventory(res inventory.Result, opts FromInventoryOptions) ([]Installed, []Skipped) {+ beaconSkills := map[string]bool{}+ for _, name := range opts.BeaconSkills {+ beaconSkills[name] = true+ }+ byKey := map[string]*Installed{}+ var order []string+ var skipped []Skipped+ add := func(kind, q, basis string, src InstalledSource) {+ key := kind + "\x00" + q+ item, ok := byKey[key]+ if !ok {+ item = &Installed{Kind: kind, Q: q, Basis: basis}+ byKey[key] = item+ order = append(order, key)+ }+ for _, s := range item.Sources {+ if s == src {+ return+ }+ }+ item.Sources = append(item.Sources, src)+ }++ for _, s := range res.MCPServers {+ name := strings.TrimSpace(s.ServerName)+ src := InstalledSource{Runtime: s.Runtime, Name: name, Scope: s.SourceScope}+ if beaconServers[strings.ToLower(name)] {+ skipped = append(skipped, Skipped{Kind: "mcp", Runtime: s.Runtime, Name: name, Reason: ReasonBeacon})+ continue+ }+ command, args := commandOf(s.Definition)+ if q, basis, ok := PackageFromCommand(command, args); ok {+ program, programArgs := launcher(command, args)+ if registryFromEnv(s.Definition) || opts.Registries.forServer(program, programArgs, s.Definition).private(q) {+ basis = privateBasis(basis)+ }+ if (basis == BasisPrivateNPM || basis == BasisPrivatePyPI) && !opts.IncludePrivateNames {+ skipped = append(skipped, Skipped{Kind: "mcp", Runtime: s.Runtime, Name: name, Reason: ReasonPrivatePackage})+ continue+ }+ add("mcp", q, basis, src)+ continue+ }+ switch {+ case opts.IncludePrivateNames && validName(name):+ add("mcp", name, BasisServerName, src)+ case name == "" || !validName(name):+ skipped = append(skipped, Skipped{Kind: "mcp", Runtime: s.Runtime, Name: name, Reason: ReasonNoName})+ case s.URLPresent && !s.CommandPresent:+ skipped = append(skipped, Skipped{Kind: "mcp", Runtime: s.Runtime, Name: name, Reason: ReasonRemote})+ default:+ skipped = append(skipped, Skipped{Kind: "mcp", Runtime: s.Runtime, Name: name, Reason: ReasonNoPackage})+ }+ }+ for _, s := range res.Skills {+ name := strings.TrimSpace(s.SkillName)+ if !s.Exists {+ continue+ }+ if beaconSkills[name] {+ skipped = append(skipped, Skipped{Kind: "skill", Runtime: s.Runtime, Name: name, Reason: ReasonBeacon})+ continue+ }+ if !validName(name) {+ skipped = append(skipped, Skipped{Kind: "skill", Runtime: s.Runtime, Name: name, Reason: ReasonNoName})+ continue+ }+ if !opts.IncludePrivateNames {+ skipped = append(skipped, Skipped{Kind: "skill", Runtime: s.Runtime, Name: name, Reason: ReasonPrivateSkill})+ continue+ }+ add("skill", name, BasisSkillName, InstalledSource{Runtime: s.Runtime, Name: name, Scope: s.SourceScope})+ }++ out := make([]Installed, 0, len(order))+ for _, key := range order {+ item := byKey[key]+ sort.Slice(item.Sources, func(i, j int) bool {+ a, b := item.Sources[i], item.Sources[j]+ if a.Runtime != b.Runtime {+ return a.Runtime < b.Runtime+ }+ if a.Name != b.Name {+ return a.Name < b.Name+ }+ return a.Scope < b.Scope+ })+ out = append(out, *item)+ }+ sort.SliceStable(out, func(i, j int) bool {+ if out[i].Kind != out[j].Kind {+ return out[i].Kind == "mcp"+ }+ return out[i].Q < out[j].Q+ })+ sort.SliceStable(skipped, func(i, j int) bool {+ if skipped[i].Kind != skipped[j].Kind {+ return skipped[i].Kind == "mcp"+ }+ if skipped[i].Runtime != skipped[j].Runtime {+ return skipped[i].Runtime < skipped[j].Runtime+ }+ return skipped[i].Name < skipped[j].Name+ })+ return out, skipped+}++func commandOf(def map[string]interface{}) (string, []string) {+ if def == nil {+ return "", nil+ }+ command, _ := def["command"].(string)+ var args []string+ if raw, ok := def["args"].([]interface{}); ok {+ for _, a := range raw {+ if s, ok := a.(string); ok {+ args = append(args, s)+ }+ }+ }+ return command, args+}++// privateBasis is the basis of a package fetched from a registry or index other than the+// public one.+func privateBasis(basis string) string {+ switch basis {+ case BasisNPM:+ return BasisPrivateNPM+ case BasisPyPI:+ return BasisPrivatePyPI+ }+ return basis+}++// registryFromEnv reports whether a server's own definition can point its launcher at a+// registry, index or config file: a registry variable in its env block, or an env file Beacon+// does not read. Only the keys are read; their values never leave here.+func registryFromEnv(def map[string]interface{}) bool {+ if _, ok := def["envFile"]; ok {+ return true+ }+ if _, ok := def["env_file"]; ok {+ return true+ }+ env, _ := def["env"].(map[string]interface{})+ for key := range env {+ if npm, pypi := registryEnvKey(key); npm || pypi {+ return true+ }+ }+ return false+}++var (+ npmName = regexp.MustCompile(`^(@[a-z0-9][a-z0-9._~-]*/)?[a-z0-9][a-z0-9._~-]*$`)+ pypiName = regexp.MustCompile(`^[a-z0-9]([a-z0-9._-]*[a-z0-9])?$`)+ // A name a person might give a server or skill: no paths, URLs, or whitespace runs.+ plainName = regexp.MustCompile(`^[A-Za-z0-9@][A-Za-z0-9 ._@/+-]{0,99}$`)+)++func validName(name string) bool {+ return plainName.MatchString(name) && !strings.Contains(name, "//") && !strings.Contains(name, "..")+}++// launcher is the program a launch command runs and its arguments: a whole launch line in+// command is split, and Windows' cmd /c or /k wrapper (cmd /c npx -y <package>) is unwrapped.+func launcher(command string, args []string) (string, []string) {+ for {+ if len(args) == 0 && strings.ContainsAny(strings.TrimSpace(command), " \t") {+ fields := strings.Fields(command)+ command, args = fields[0], fields[1:]+ }+ if launcherBase(command) == "cmd" && len(args) >= 2 && (strings.EqualFold(args[0], "/c") || strings.EqualFold(args[0], "/k")) {+ command, args = args[1], args[2:]+ continue+ }+ return command, args+ }+}++func launcherBase(command string) string {+ base := strings.ToLower(filepath.Base(strings.ReplaceAll(strings.TrimSpace(command), `\`, "/")))+ return strings.TrimSuffix(strings.TrimSuffix(base, ".exe"), ".cmd")+}++// PackageFromCommand names the npm or PyPI package a launch command runs, as a lookup+// (npm:<name> or pypi:<name>) without its version. ok is false for anything else: a local+// script, a binary, a container, or a command it cannot read with confidence.+func PackageFromCommand(command string, args []string) (q, basis string, ok bool) {+ command, args = launcher(command, args)+ base := launcherBase(command)+ rest := args+ switch base {+ case "npx", "bunx", "pnpx":+ case "pnpm", "yarn", "bun":+ if len(rest) == 0 || (rest[0] != "dlx" && rest[0] != "x") {+ return "", "", false+ }+ rest = rest[1:]+ case "npm":+ if len(rest) == 0 || (rest[0] != "exec" && rest[0] != "x") {+ return "", "", false+ }+ rest = rest[1:]+ case "uvx":+ return pypiFrom(rest)+ case "pipx":+ if len(rest) == 0 || rest[0] != "run" {+ return "", "", false+ }+ return pypiFrom(rest[1:])+ case "uv":+ if len(rest) < 2 || rest[0] != "tool" || rest[1] != "run" {+ return "", "", false+ }+ return pypiFrom(rest[2:])+ default:+ return "", "", false+ }+ return npmFrom(rest)+}++// The options a launcher takes before the package it runs. A flag in neither list stops the+// parse: whether it takes a value decides which word is the package, and guessing wrong sends+// a file name or a workspace for a package and leaves the real one unchecked. A package+// fetched from a registry or index the command names is not a public package, and its name+// may be private.+var (+ // A config file or pip's own arguments can name a registry or index too, so they count.+ npmPrivateFlags = flagSet("--registry", "--userconfig")+ pypiPrivateFlags = flagSet("--index", "--index-url", "--extra-index-url", "--default-index", "-f", "--find-links",+ "--config-file", "--pip-args")++ npmPackageFlags = flagSet("-p", "--package")+ npmValueFlags = flagSet("--registry", "--cache", "--userconfig", "-w", "--workspace", "--node-options", "--loglevel", "--allow-build")+ npmBoolFlags = flagSet("-y", "--yes", "--no", "--no-install", "-q", "--quiet", "-s", "--silent", "--prefer-offline", "--prefer-online", "--offline", "--ignore-existing", "--bun")++ pypiPackageFlags = flagSet("--from", "--spec")+ pypiValueFlags = flagSet("-p", "--python", "--with", "--with-editable", "--with-requirements", "--index", "--index-url",+ "--extra-index-url", "--default-index", "-f", "--find-links", "--refresh-package", "-P", "--upgrade-package",+ "--reinstall-package", "--prerelease", "--resolution", "-c", "--constraints", "--overrides", "--env-file",+ "--directory", "--project", "--cache-dir", "--color", "--python-preference", "--exclude-newer", "--link-mode",+ "--keyring-provider", "--index-strategy", "--config-file", "--pip-args")+ pypiBoolFlags = flagSet("-q", "--quiet", "-v", "--verbose", "--offline", "-n", "--no-cache", "--isolated", "--refresh",+ "--system", "--native-tls", "--no-progress", "-U", "--upgrade", "--reinstall", "--no-build", "--system-site-packages")+)++func flagSet(flags ...string) map[string]bool {+ set := make(map[string]bool, len(flags))+ for _, f := range flags {+ set[f] = true+ }+ return set+}++// packageArg finds the package a launcher runs: the value of a package flag, or else the first+// argument that is not an option. ok is false when an unknown option makes that uncertain.+// private reports whether a flag in privateFlags appeared anywhere among the launcher's own+// options, including after a package flag: `uvx --from pkg --index-url <url> cmd` fetches pkg+// from that index too.+func packageArg(args []string, packageFlags, valueFlags, boolFlags, privateFlags map[string]bool) (spec string, private, ok bool) {+ found := false+ for i := 0; i < len(args); i++ {+ a := args[i]+ name, value, hasValue := strings.Cut(a, "=")+ if !strings.HasPrefix(a, "-") {+ hasValue = false+ }+ if privateFlags[name] {+ private = true+ }+ switch {+ case a == "--":+ continue+ case packageFlags[a]:+ if i+1 >= len(args) {+ return "", private, false+ }+ i+++ if !found {+ spec, found = args[i], true+ }+ case hasValue:+ if packageFlags[name] {+ if !found {+ spec, found = value, true+ }+ continue+ }+ if !valueFlags[name] && !boolFlags[name] {+ return "", private, false+ }+ case valueFlags[a]:+ i+++ case boolFlags[a]:+ case strings.HasPrefix(a, "-"):+ return "", private, false+ default:+ // The first plain word is the package, or the command a package flag's package+ // provides; either way the launcher's options end here.+ if !found {+ spec = a+ }+ return spec, private, true+ }+ }+ return spec, private, found+}++func npmFrom(args []string) (string, string, bool) {+ spec, private, ok := packageArg(args, npmPackageFlags, npmValueFlags, npmBoolFlags, npmPrivateFlags)+ if !ok {+ return "", "", false+ }+ q, basis, ok := npmPackage(spec)+ if ok && private {+ basis = BasisPrivateNPM+ }+ return q, basis, ok+}++// archiveSuffixes name a local package file rather than a registry package.+var archiveSuffixes = []string{".tgz", ".tar.gz", ".tar.bz2", ".tar.xz", ".zip", ".whl", ".egg"}++func isArchive(spec string) bool {+ for _, suffix := range archiveSuffixes {+ if strings.HasSuffix(spec, suffix) {+ return true+ }+ }+ return false+}++// npmPackage reads a registry spec, <name> or <name>@<version, range or tag>. A spec that+// fetches from anywhere else (a git or tarball URL, a file, an npm: alias) is not a public+// registry package, and its name may be private, so ok is false.+func npmPackage(spec string) (string, string, bool) {+ spec = strings.ToLower(strings.TrimSpace(spec))+ name, version := spec, ""+ if strings.HasPrefix(spec, "@") {+ if at := strings.Index(spec[1:], "@"); at >= 0 {+ name, version = spec[:at+1], spec[at+2:]+ }+ } else if at := strings.Index(spec, "@"); at >= 0 {+ name, version = spec[:at], spec[at+1:]+ }+ if strings.ContainsAny(version, ":/\\") || isArchive(name) || isArchive(version) {+ return "", "", false+ }+ if !npmName.MatchString(name) || len(name) > 214 {+ return "", "", false+ }+ return "npm:" + name, BasisNPM, true+}++func pypiFrom(args []string) (string, string, bool) {+ spec, private, ok := packageArg(args, pypiPackageFlags, pypiValueFlags, pypiBoolFlags, pypiPrivateFlags)+ if !ok {+ return "", "", false+ }+ q, basis, ok := pypiPackage(spec)+ if ok && private {+ basis = BasisPrivatePyPI+ }+ return q, basis, ok+}++// pypiPackage reads a PEP 508 requirement for a registry package, or uv's <name>@<version>+// (and @latest). A direct reference (name @ url), a URL, a path or a local wheel or sdist is+// not a public PyPI package, and its name may be private, so ok is false.+func pypiPackage(spec string) (string, string, bool) {+ spec = strings.ToLower(strings.TrimSpace(spec))+ if name, version, ok := strings.Cut(spec, "@"); ok {+ if version == "" || strings.ContainsAny(name, " \t") || strings.ContainsAny(version, ":/\\ \t@") {+ return "", "", false+ }+ spec = name+ }+ if strings.ContainsAny(spec, "/\\") || strings.Contains(spec, "://") || strings.HasPrefix(spec, "git+") || isArchive(spec) {+ return "", "", false+ }+ if cut := strings.IndexAny(spec, "[=<>!~; "); cut >= 0 {+ spec = spec[:cut]+ }+ // Lowercased only, as the index keys packages: registries list a name as it was published.+ if !pypiName.MatchString(spec) || len(spec) > 100 {+ return "", "", false+ }+ return "pypi:" + spec, BasisPyPI, true+}diff --git a/cli/beacon/internal/intel/installed_test.go b/cli/beacon/internal/intel/installed_test.gonew file mode 100644index 00000000..5601db93--- /dev/null+++ b/cli/beacon/internal/intel/installed_test.go@@ -0,0 +1,339 @@+package intel++import (+ "encoding/json"+ "strings"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/inventory"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/intelapi"+)++func TestPackageFromCommand(t *testing.T) {+ cases := []struct {+ command string+ args []string+ want string+ }{+ {"npx", []string{"-y", "@playwright/mcp@latest"}, "npm:@playwright/mcp"},+ {"npx", []string{"--yes", "@Modelcontextprotocol/Server-GitHub"}, "npm:@modelcontextprotocol/server-github"},+ {"/usr/local/bin/npx", []string{"[email protected]", "https://example.test/sse"}, "npm:mcp-remote"},+ {"npx.cmd", []string{"-y", "@scope/pkg"}, "npm:@scope/pkg"},+ {"npx", []string{"-p", "@scope/server", "server-bin"}, "npm:@scope/server"},+ {"npx", []string{"--package=tool@1", "tool"}, "npm:tool"},+ {"bunx", []string{"some-mcp"}, "npm:some-mcp"},+ {"pnpm", []string{"dlx", "@x/y@2"}, "npm:@x/y"},+ {"yarn", []string{"dlx", "z"}, "npm:z"},+ {"npm", []string{"exec", "--", "[email protected]"}, "npm:w"},+ {"uvx", []string{"mcp-server-fetch"}, "pypi:mcp-server-fetch"},+ {"uvx", []string{"--python", "3.12", "Mcp_Server.Time==1.2"}, "pypi:mcp_server.time"},+ {"uvx", []string{"--from", "awslabs.aws-docs-mcp-server[cli]>=1", "aws-docs"}, "pypi:awslabs.aws-docs-mcp-server"},+ {"pipx", []string{"run", "mcp-git"}, "pypi:mcp-git"},+ {"uv", []string{"tool", "run", "--from=serena", "serena"}, "pypi:serena"},+ {"npx -y @playwright/mcp", nil, "npm:@playwright/mcp"},+ {"npx", []string{"--registry", "https://r.example", "-y", "pkg-a"}, "npm:pkg-a"},+ {"npx", []string{"--workspace=api", "pkg-b@2"}, "npm:pkg-b"},+ {"npx", []string{"-w", "api", "pkg-c"}, "npm:pkg-c"},+ {"uvx", []string{"--with-requirements", "requirements.txt", "real-server"}, "pypi:real-server"},+ {"uvx", []string{"-q", "--index-url=https://i.example/simple", "--with", "extra", "srv"}, "pypi:srv"},+ {"pipx", []string{"run", "--spec", "mcp-thing==1", "thing"}, "pypi:mcp-thing"},+ }+ for _, tc := range cases {+ q, basis, ok := PackageFromCommand(tc.command, tc.args)+ if !ok || q != tc.want {+ t.Errorf("PackageFromCommand(%q, %q) = %q, %v; want %q", tc.command, tc.args, q, ok, tc.want)+ }+ if ok && basis != BasisNPM && basis != BasisPyPI && basis != BasisPrivateNPM && basis != BasisPrivatePyPI {+ t.Errorf("basis = %q", basis)+ }+ }+ for _, tc := range []struct {+ command string+ args []string+ }{+ {"node", []string{"/home/me/server.js"}},+ {"python", []string{"-m", "my_server"}},+ {"docker", []string{"run", "-i", "mcp/github"}},+ {"npx", []string{"-y"}},+ {"npx", []string{"./local/pkg"}},+ {"npx", []string{"/abs/path"}},+ {"npx", []string{"https://example.test/x.tgz"}},+ {"npx", []string{"[REDACTED]"}},+ {"npm", []string{"run", "start"}},+ {"pnpm", []string{"start"}},+ {"pipx", []string{"install", "x"}},+ {"uv", []string{"run", "server.py"}},+ {"uvx", []string{"--from", "git+https://github.com/a/b", "b"}},+ // An option Beacon does not know may take a value, so nothing is guessed.+ {"uvx", []string{"--some-new-flag", "requirements.txt", "srv"}},+ {"npx", []string{"--mystery", "value", "pkg"}},+ {"npx", []string{"--mystery=value", "pkg"}},+ {"npx", []string{"-c", "echo hi"}},+ {"", nil},+ } {+ if q, _, ok := PackageFromCommand(tc.command, tc.args); ok {+ t.Errorf("PackageFromCommand(%q, %q) = %q, want no package", tc.command, tc.args, q)+ }+ }+}++func server(runtime, name, scope string, def map[string]interface{}) inventory.MCPServer {+ _, hasURL := def["url"]+ _, hasCommand := def["command"]+ return inventory.MCPServer{Runtime: runtime, ServerName: name, SourceScope: scope, Definition: def, URLPresent: hasURL, CommandPresent: hasCommand}+}++func TestFromInventorySendsOnlyPublicIdentifiers(t *testing.T) {+ secret := "ghp_supersecrettoken123"+ res := inventory.Result{+ MCPServers: []inventory.MCPServer{+ server("claude_code", "playwright", "user", map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "@playwright/mcp@latest", "--token", secret}, "env": map[string]interface{}{"TOKEN": secret}}),+ server("cursor", "pw", "project", map[string]interface{}{"command": "npx", "args": []interface{}{"@playwright/mcp"}}),+ server("cursor", "playwright", "user", map[string]interface{}{"command": "npx", "args": []interface{}{"@playwright/mcp"}}),+ server("codex", "fetch", "user", map[string]interface{}{"command": "uvx", "args": []interface{}{"mcp-server-fetch"}}),+ server("claude_code", "internal-db", "user", map[string]interface{}{"command": "node", "args": []interface{}{"/home/me/company/secret-server.js"}}),+ server("claude_code", "remote", "user", map[string]interface{}{"url": "https://mcp.internal.example/" + secret}),+ server("claude_code", "beacon", "user", map[string]interface{}{"command": "beacon", "args": []interface{}{"mcp", "serve"}}),+ server("claude_code", "Beacon-Managed", "user", map[string]interface{}{"url": "https://beacon.sh/mcp"}),+ server("claude_code", "../../etc/passwd", "user", map[string]interface{}{"command": "node"}),+ },+ Skills: []inventory.Skill{+ {Runtime: "claude_code", SkillName: "pdf", SourceScope: "user", Exists: true},+ {Runtime: "codex", SkillName: "pdf", SourceScope: "user", Exists: true},+ {Runtime: "claude_code", SkillName: "beacon-memory-recall", SourceScope: "user", Exists: true},+ {Runtime: "claude_code", SkillName: "gone", SourceScope: "user", Exists: false},+ {Runtime: "claude_code", SkillName: "/Users/me/skills/x", SourceScope: "user", Exists: true},+ },+ }+ items, skipped := FromInventory(res, FromInventoryOptions{BeaconSkills: []string{"beacon-memory-recall"}})++ var got []string+ for _, item := range items {+ got = append(got, item.Kind+" "+item.Q)+ }+ if strings.Join(got, ", ") != "mcp npm:@playwright/mcp, mcp pypi:mcp-server-fetch" {+ t.Fatalf("items = %v", got)+ }+ if n := len(items[0].Sources); n != 3 || items[0].Sources[0].Runtime != "claude_code" || items[0].Basis != BasisNPM {+ t.Fatalf("playwright sources = %+v", items[0])+ }++ reasons := map[string]string{}+ for _, s := range skipped {+ reasons[s.Kind+" "+s.Name] = s.Reason+ }+ want := map[string]string{+ "mcp internal-db": ReasonNoPackage,+ "mcp remote": ReasonRemote,+ "mcp beacon": ReasonBeacon,+ "mcp Beacon-Managed": ReasonBeacon,+ "mcp ../../etc/passwd": ReasonNoName,+ "skill pdf": ReasonPrivateSkill,+ "skill beacon-memory-recall": ReasonBeacon,+ "skill /Users/me/skills/x": ReasonNoName,+ }+ for k, v := range want {+ if reasons[k] != v {+ t.Errorf("skipped[%q] = %q, want %q", k, reasons[k], v)+ }+ }+ if len(skipped) != len(want)+1 { // pdf is skipped once per runtime+ t.Errorf("skipped = %+v", skipped)+ }++ // With consent, skills go by name, once for every runtime they are in.+ withNames, _ := FromInventory(res, FromInventoryOptions{IncludePrivateNames: true, BeaconSkills: []string{"beacon-memory-recall"}})+ last := withNames[len(withNames)-1]+ if last.Kind != "skill" || last.Q != "pdf" || len(last.Sources) != 2 || last.Basis != BasisSkillName {+ t.Fatalf("pdf with consent = %+v", last)+ }++ // The lookups that would be sent carry none of the definition.+ var sent []intelapi.CheckItem+ for _, item := range items {+ sent = append(sent, intelapi.CheckItem{Q: item.Q, Kind: item.Kind})+ }+ body, _ := json.Marshal(sent)+ for _, leak := range []string{secret, "/home/me", "company", "internal", "mcp.internal.example", "--token", "TOKEN", "latest"} {+ if strings.Contains(string(body), leak) {+ t.Errorf("what would be sent contains %q: %s", leak, body)+ }+ }+}++func TestPrivateRegistriesAndWindowsShells(t *testing.T) {+ for _, tc := range []struct {+ command string+ args []string+ want string+ basis string+ }{+ {"npx", []string{"--registry", "https://npm.acme.internal", "-y", "@acme/billing-mcp"}, "npm:@acme/billing-mcp", BasisPrivateNPM},+ {"npx", []string{"--registry=https://npm.acme.internal", "@acme/billing-mcp"}, "npm:@acme/billing-mcp", BasisPrivateNPM},+ {"uvx", []string{"--index-url", "https://pypi.acme.internal/simple", "acme-billing-mcp"}, "pypi:acme-billing-mcp", BasisPrivatePyPI},+ {"uvx", []string{"--extra-index-url=https://x.example/simple", "srv"}, "pypi:srv", BasisPrivatePyPI},+ // A private index or registry named after the package flag still applies to that package.+ {"uvx", []string{"--from", "acme-billing-mcp", "--index-url", "https://pypi.acme.internal/simple", "acme-billing"}, "pypi:acme-billing-mcp", BasisPrivatePyPI},+ {"uvx", []string{"--from=acme-billing-mcp", "--index=https://pypi.acme.internal/simple", "acme-billing"}, "pypi:acme-billing-mcp", BasisPrivatePyPI},+ {"npx", []string{"-p", "@acme/mcp", "--registry", "https://npm.acme.internal", "acme-mcp"}, "npm:@acme/mcp", BasisPrivateNPM},+ {"npx", []string{"--package=@acme/mcp", "--registry=https://npm.acme.internal", "acme-mcp"}, "npm:@acme/mcp", BasisPrivateNPM},+ {"uvx", []string{"--from", "mcp-server-fetch", "mcp-server-fetch"}, "pypi:mcp-server-fetch", BasisPyPI},+ // A config file or pip's own arguments can name an index or registry.+ {"npx", []string{"--userconfig", "/x/.npmrc", "@acme/mcp"}, "npm:@acme/mcp", BasisPrivateNPM},+ {"uvx", []string{"--config-file", "/x/uv.toml", "acme-mcp"}, "pypi:acme-mcp", BasisPrivatePyPI},+ {"pipx", []string{"run", "--pip-args=--index-url=https://pypi.acme.internal/simple", "acme-mcp"}, "pypi:acme-mcp", BasisPrivatePyPI},+ {"cmd", []string{"/c", "npx", "-y", "@playwright/mcp"}, "npm:@playwright/mcp", BasisNPM},+ {"C:\\Windows\\System32\\cmd.exe", []string{"/C", "uvx", "mcp-server-fetch"}, "pypi:mcp-server-fetch", BasisPyPI},+ {"cmd /c npx -y @playwright/mcp", nil, "npm:@playwright/mcp", BasisNPM},+ {"C:\\Program Files\\nodejs\\npx.cmd", []string{"-y", "pkg"}, "npm:pkg", BasisNPM},+ } {+ q, basis, ok := PackageFromCommand(tc.command, tc.args)+ if !ok || q != tc.want || basis != tc.basis {+ t.Errorf("PackageFromCommand(%q, %q) = %q, %q, %v; want %q, %q", tc.command, tc.args, q, basis, ok, tc.want, tc.basis)+ }+ }+ if _, _, ok := PackageFromCommand("cmd", []string{"/c", "node", "server.js"}); ok {+ t.Error("cmd /c node was read as a package")+ }++ res := inventory.Result{MCPServers: []inventory.MCPServer{+ server("cursor", "billing", "user", map[string]interface{}{"command": "uvx", "args": []interface{}{"--index-url", "https://pypi.acme.internal/simple", "acme-billing-mcp"}}),+ }}+ items, skipped := FromInventory(res, FromInventoryOptions{})+ if len(items) != 0 || len(skipped) != 1 || skipped[0].Reason != ReasonPrivatePackage {+ t.Fatalf("a private-index package was not held back: %+v %+v", items, skipped)+ }+ items, _ = FromInventory(res, FromInventoryOptions{IncludePrivateNames: true})+ if len(items) != 1 || items[0].Q != "pypi:acme-billing-mcp" || items[0].Basis != BasisPrivatePyPI {+ t.Fatalf("with consent = %+v", items)+ }+}++func TestPackageFromCommandRefusesSpecsOffTheRegistry(t *testing.T) {+ for _, tc := range []struct {+ command string+ args []string+ }{+ {"uvx", []string{"--from", "acme-internal-tool @ git+https://git.acme.internal/x.git", "acme"}},+ {"uvx", []string{"--from", "acme-internal-tool@git+https://git.acme.internal/x.git", "acme"}},+ {"uvx", []string{"--from", "acme_tool-1.0-py3-none-any.whl", "acme"}},+ {"uvx", []string{"--from", "acme-tool@", "acme"}},+ {"uvx", []string{"acme-tool@file:///src/acme"}},+ {"uvx", []string{"--from", "acme-tool-1.0.tar.gz", "acme"}},+ {"uvx", []string{"--from", "git+https://git.acme.internal/x.git", "acme"}},+ {"uvx", []string{"--from", "./tools/acme", "acme"}},+ {"pipx", []string{"run", "--spec", "https://files.acme.internal/acme-1.0.zip", "acme"}},+ {"npx", []string{"-y", "acme-tool@git+https://git.acme.internal/x.git"}},+ {"npx", []string{"-y", "acme-tool@github:acme/tool"}},+ {"npx", []string{"-y", "@acme/tool@https://files.acme.internal/tool.tgz"}},+ {"npx", []string{"-y", "acme-tool@npm:@acme/real-tool"}},+ {"npx", []string{"-y", "acme-tool@file:../tool"}},+ {"npx", []string{"-y", "acme-tool.tgz"}},+ } {+ if q, basis, ok := PackageFromCommand(tc.command, tc.args); ok {+ t.Errorf("PackageFromCommand(%q, %q) = %q, %q; want no package", tc.command, tc.args, q, basis)+ }+ }+ for _, tc := range []struct {+ command string+ args []string+ want string+ }{+ {"uvx", []string{"--from", "mcp-server-fetch==0.6.2", "mcp-server-fetch"}, "pypi:mcp-server-fetch"},+ {"uvx", []string{"mcp-server-fetch@latest"}, "pypi:mcp-server-fetch"},+ {"uvx", []string{"[email protected]"}, "pypi:ruff"},+ {"uvx", []string{"awslabs.aws-documentation-mcp-server@latest"}, "pypi:awslabs.aws-documentation-mcp-server"},+ {"pipx", []string{"run", "--spec", "[email protected]", "pkg"}, "pypi:pkg"},+ {"uvx", []string{"--from", "[email protected]", "mcp-server-fetch"}, "pypi:mcp-server-fetch"},+ {"uvx", []string{"--from", "mcp-server-fetch[cli]>=0.6 ; python_version >= '3.10'", "x"}, "pypi:mcp-server-fetch"},+ {"npx", []string{"-y", "@playwright/mcp@latest"}, "npm:@playwright/mcp"},+ {"npx", []string{"-y", "pkg@^1.2.3"}, "npm:pkg"},+ } {+ if q, _, ok := PackageFromCommand(tc.command, tc.args); !ok || q != tc.want {+ t.Errorf("PackageFromCommand(%q, %q) = %q, %v; want %q", tc.command, tc.args, q, ok, tc.want)+ }+ }+}++func TestFromInventoryHoldsBackRegistriesFromEnv(t *testing.T) {+ for _, tc := range []struct {+ key string+ def map[string]interface{}+ want string+ }{+ {"npm_config_registry", map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "@acme/internal-mcp"}}, "npm:@acme/internal-mcp"},+ {"NPM_CONFIG_REGISTRY", map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "@acme/internal-mcp"}}, "npm:@acme/internal-mcp"},+ {"npm_config_@acme:registry", map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "@acme/internal-mcp"}}, "npm:@acme/internal-mcp"},+ {"NPM_CONFIG_USERCONFIG", map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "@acme/internal-mcp"}}, "npm:@acme/internal-mcp"},+ {"UV_INDEX_URL", map[string]interface{}{"command": "uvx", "args": []interface{}{"acme-billing-mcp"}}, "pypi:acme-billing-mcp"},+ {"UV_DEFAULT_INDEX", map[string]interface{}{"command": "uvx", "args": []interface{}{"acme-billing-mcp"}}, "pypi:acme-billing-mcp"},+ {"UV_EXTRA_INDEX_URL", map[string]interface{}{"command": "uvx", "args": []interface{}{"acme-billing-mcp"}}, "pypi:acme-billing-mcp"},+ {"PIP_INDEX_URL", map[string]interface{}{"command": "pipx", "args": []interface{}{"run", "acme-billing-mcp"}}, "pypi:acme-billing-mcp"},+ {"PIP_EXTRA_INDEX_URL", map[string]interface{}{"command": "pipx", "args": []interface{}{"run", "acme-billing-mcp"}}, "pypi:acme-billing-mcp"},+ {"NPM_CONFIG_PREFIX", map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "@acme/internal-mcp"}}, "npm:@acme/internal-mcp"},+ } {+ def := map[string]interface{}{"env": map[string]interface{}{tc.key: "https://registry.acme.internal"}}+ for k, v := range tc.def {+ def[k] = v+ }+ res := inventory.Result{MCPServers: []inventory.MCPServer{server("cursor", "internal-tool", "user", def)}}+ items, skipped := FromInventory(res, FromInventoryOptions{})+ if len(items) != 0 || len(skipped) != 1 || skipped[0].Reason != ReasonPrivatePackage {+ t.Errorf("%s: a package from a registry set in env was not held back: %+v %+v", tc.key, items, skipped)+ }+ items, _ = FromInventory(res, FromInventoryOptions{IncludePrivateNames: true})+ if len(items) != 1 || items[0].Q != tc.want || (items[0].Basis != BasisPrivateNPM && items[0].Basis != BasisPrivatePyPI) {+ t.Errorf("%s: with consent = %+v", tc.key, items)+ }+ }++ // Unrelated env keys, secrets included, leave a public package public.+ res := inventory.Result{MCPServers: []inventory.MCPServer{server("cursor", "gh", "user", map[string]interface{}{+ "command": "npx", "args": []interface{}{"-y", "@modelcontextprotocol/server-github"},+ "env": map[string]interface{}{"GITHUB_TOKEN": "[REDACTED]", "NODE_ENV": "production"},+ })}}+ items, skipped := FromInventory(res, FromInventoryOptions{})+ if len(items) != 1 || items[0].Basis != BasisNPM || len(skipped) != 0 {+ t.Fatalf("a public package was held back: %+v %+v", items, skipped)+ }+}++func TestFromInventoryServerNamesAreOptIn(t *testing.T) {+ res := inventory.Result{MCPServers: []inventory.MCPServer{+ server("claude_code", "Desktop Commander", "user", map[string]interface{}{"command": "node", "args": []interface{}{"/x/dc.js"}}),+ server("claude_code", "linear", "user", map[string]interface{}{"url": "https://mcp.linear.app/sse"}),+ server("claude_code", "https://evil.example", "user", map[string]interface{}{"command": "node"}),+ }}+ items, skipped := FromInventory(res, FromInventoryOptions{})+ if len(items) != 0 || len(skipped) != 3 {+ t.Fatalf("without opt-in: items %+v, skipped %+v", items, skipped)+ }+ items, skipped = FromInventory(res, FromInventoryOptions{IncludePrivateNames: true})+ if len(items) != 2 || items[0].Q != "Desktop Commander" || items[1].Q != "linear" || items[0].Basis != BasisServerName {+ t.Fatalf("with opt-in: %+v", items)+ }+ if len(skipped) != 1 || skipped[0].Reason != ReasonNoName {+ t.Fatalf("a URL-shaped name was sent: %+v", skipped)+ }+}++func TestFromInventoryIsStable(t *testing.T) {+ res := inventory.Result{+ MCPServers: []inventory.MCPServer{+ server("b", "z", "user", map[string]interface{}{"command": "npx", "args": []interface{}{"zz"}}),+ server("a", "y", "user", map[string]interface{}{"command": "npx", "args": []interface{}{"aa"}}),+ },+ Skills: []inventory.Skill{{Runtime: "a", SkillName: "s", Exists: true}},+ }+ first, _ := FromInventory(res, FromInventoryOptions{IncludePrivateNames: true})+ res.MCPServers[0], res.MCPServers[1] = res.MCPServers[1], res.MCPServers[0]+ second, _ := FromInventory(res, FromInventoryOptions{IncludePrivateNames: true})+ a, _ := json.Marshal(first)+ b, _ := json.Marshal(second)+ if string(a) != string(b) {+ t.Fatalf("order depends on input order:\n%s\n%s", a, b)+ }+ if first[0].Q != "npm:aa" || first[2].Kind != "skill" {+ t.Fatalf("order = %+v", first)+ }+}diff --git a/cli/beacon/internal/intel/registries.go b/cli/beacon/internal/intel/registries.gonew file mode 100644index 00000000..51196565--- /dev/null+++ b/cli/beacon/internal/intel/registries.go@@ -0,0 +1,509 @@+package intel++import (+ "bufio"+ "io"+ "os"+ "path/filepath"+ "regexp"+ "strings"+)++// Registries is what the machine's own launcher configuration says about where packages come+// from. A launcher reads more than its command line: npm reads .npmrc and npm_config_*, yarn and+// bun their own files, pip pip.conf and PIP_*, uv uv.toml and UV_*. When any of them points npm+// or PyPI at a registry or index other than the public one, a package of that ecosystem (or of+// that npm scope) may be private, so FromInventory holds it back like a --registry on the+// command line.+type Registries struct {+ // NPM is set when every npm package may come from another registry.+ NPM bool+ // NPMScopes are the npm scopes (as "@scope") set to another registry.+ NPMScopes map[string]bool+ // PyPI is set when a PyPI package may come from another index.+ PyPI bool++ home string // for ~ in an npmrc's userconfig, globalconfig or prefix+ yarnrc string // the rc file name yarn looks for in a project+ vars map[string]string // the environment, by lowercased name, for ${VAR} in an npmrc+ read map[string]bool // npmrc files already read, so a cycle of them ends+}++// RegistryEnv is where LocalRegistries looks: the user's home, the working directory a launcher+// would run in (empty to skip project files), the environment the launcher inherits, and+// whether to read the system-wide files under /etc and the package managers' prefixes.+type RegistryEnv struct {+ Home string+ WorkingDir string+ Environ []string+ System bool+}++// CurrentRegistryEnv is this process's home, environment and working directory. An agent+// starts every launcher, user-scoped servers' included, with the same environment and in the+// same project, so the project's config applies whether or not project servers are listed.+func CurrentRegistryEnv() RegistryEnv {+ env := RegistryEnv{Environ: os.Environ(), System: true}+ env.Home, _ = os.UserHomeDir()+ env.WorkingDir, _ = os.Getwd()+ return env+}++// projectDirs are the working directory and every directory above it: npm, yarn, bun and uv+// each find a project's config by walking up from where they run.+func projectDirs(wd string) []string {+ if wd == "" {+ return nil+ }+ var dirs []string+ for dir := filepath.Clean(wd); ; {+ dirs = append(dirs, dir)+ parent := filepath.Dir(dir)+ if parent == dir {+ return dirs+ }+ dir = parent+ }+}++const maxRegistryConfigBytes = 1 << 20++// LocalRegistries reads the registry and index settings npm, yarn, bun, pip and uv would read.+// A file it cannot read counts as absent. Settings that name the public registry do not count.+func LocalRegistries(env RegistryEnv) Registries {+ vars, lower := map[string]string{}, map[string]string{}+ reg := Registries{NPMScopes: map[string]bool{}, home: env.Home, vars: lower, read: map[string]bool{}}+ for _, kv := range env.Environ {+ if k, v, ok := strings.Cut(kv, "="); ok {+ vars[k] = v+ lower[strings.ToLower(k)] = v+ reg.addEnv(k, v)+ }+ }+ // npm reads npm_config_* in any case, and Windows names variables without regard to case.+ getenv := func(k string) string {+ if v, ok := vars[k]; ok {+ return v+ }+ return lower[strings.ToLower(k)]+ }+ home := env.Home+ join := func(base string, parts ...string) string {+ if base == "" {+ return ""+ }+ return filepath.Join(append([]string{base}, parts...)...)+ }+ xdg := getenv("XDG_CONFIG_HOME")+ if xdg == "" {+ xdg = join(home, ".config")+ }+ appData := getenv("APPDATA")+ system := func(path string) string {+ if !env.System {+ return ""+ }+ return path+ }++ // npm and pnpm: user, project and global npmrc.+ userNpmrc := getenv("npm_config_userconfig")+ if userNpmrc == "" {+ userNpmrc = join(home, ".npmrc")+ }+ npmrcs := []string{userNpmrc, getenv("npm_config_globalconfig")}+ // The global npmrc lives under npm's prefix, and npm's builtin npmrc beside the npm the node+ // ships; npm derives both from the node it runs on (nvm, fnm, Volta and system installs each+ // have their own).+ npmrcs = append(npmrcs, join(getenv("npm_config_prefix"), "etc", "npmrc"))+ npmrcs = append(npmrcs, nodeNpmrcs(filepath.SplitList(getenv("PATH")))...)+ for _, path := range append(npmrcs, system("/etc/npmrc"),+ // pnpm's global config (pnpm config set --location=global), npmrc format.+ join(xdg, "pnpm", "rc"), join(home, "Library", "Preferences", "pnpm", "rc"), join(getenv("LOCALAPPDATA"), "pnpm", "config", "rc"),+ system("/usr/local/etc/npmrc"), system("/opt/homebrew/etc/npmrc"), join(appData, "npm", "etc", "npmrc")) {+ reg.readNpmrc(path)+ }+ // yarn and bun keep their registries in their own files.+ // YARN_RC_FILENAME renames the rc file yarn looks for in the project and home directories.+ reg.yarnrc = ".yarnrc.yml"+ if name := getenv("YARN_RC_FILENAME"); name != "" && !strings.ContainsAny(name, `/\`) {+ reg.yarnrc = name+ }+ for _, path := range []string{join(home, reg.yarnrc), join(home, ".bunfig.toml"), join(xdg, ".bunfig.toml")} {+ if registryLine(path, isNPMRegistryLine) {+ reg.NPM = true+ }+ }+ // pip (and pipx, which runs pip): every config file pip reads.+ for _, path := range []string{getenv("PIP_CONFIG_FILE"), join(home, ".pip", "pip.conf"), join(xdg, "pip", "pip.conf"),+ join(home, "Library", "Application Support", "pip", "pip.conf"), join(appData, "pip", "pip.ini"), join(home, "pip", "pip.ini"),+ system("/etc/pip.conf"), system("/etc/xdg/pip/pip.conf"), system("/Library/Application Support/pip/pip.conf"),+ join(getenv("ProgramData"), "pip", "pip.ini"), join(getenv("VIRTUAL_ENV"), "pip.conf")} {+ if registryLine(path, isPyPIIndexLine) {+ reg.PyPI = true+ }+ }+ // uv: user, system and project configuration.+ for _, path := range []string{getenv("UV_CONFIG_FILE"), join(xdg, "uv", "uv.toml"), join(appData, "uv", "uv.toml"),+ system("/etc/uv/uv.toml"), system("/etc/xdg/uv/uv.toml"), join(getenv("ProgramData"), "uv", "uv.toml")} {+ if registryLine(path, isPyPIIndexLine) {+ reg.PyPI = true+ }+ }+ // Project config: npm, yarn, bun and uv walk up from where they run.+ reg.readProject(env.WorkingDir)+ // Site-wide pip and uv files in each $XDG_CONFIG_DIRS directory.+ for _, dir := range filepath.SplitList(getenv("XDG_CONFIG_DIRS")) {+ if registryLine(join(dir, "pip", "pip.conf"), isPyPIIndexLine) || registryLine(join(dir, "uv", "uv.toml"), isPyPIIndexLine) {+ reg.PyPI = true+ }+ }+ return reg+}++// nodeNpmrcs are the global and builtin npmrc files of the first node in dirs: its install+// prefix is its directory's parent on Unix and its own directory on Windows, both as found and+// with symlinks resolved.+func nodeNpmrcs(dirs []string) []string {+ for _, dir := range dirs {+ if dir == "" {+ continue+ }+ for _, name := range []string{"node", "node.exe"} {+ node := filepath.Join(dir, name)+ if info, err := os.Stat(node); err != nil || info.IsDir() {+ continue+ }+ prefixes := []string{filepath.Dir(dir), dir}+ if real, err := filepath.EvalSymlinks(node); err == nil && real != node {+ prefixes = append(prefixes, filepath.Dir(filepath.Dir(real)), filepath.Dir(real))+ }+ var paths []string+ for _, prefix := range prefixes {+ paths = append(paths, filepath.Join(prefix, "etc", "npmrc"), filepath.Join(prefix, "lib", "node_modules", "npm", "npmrc"),+ filepath.Join(prefix, "node_modules", "npm", "npmrc"))+ }+ return paths+ }+ }+ return nil+}++// readProject reads the project config npm, yarn, bun and uv find by walking up from dir.+func (r *Registries) readProject(dir string) {+ yarnrc := r.yarnrc+ if yarnrc == "" {+ yarnrc = ".yarnrc.yml"+ }+ for _, d := range projectDirs(dir) {+ r.readNpmrc(filepath.Join(d, ".npmrc"))+ if registryLine(filepath.Join(d, yarnrc), isNPMRegistryLine) || registryLine(filepath.Join(d, "bunfig.toml"), isNPMRegistryLine) {+ r.NPM = true+ }+ if registryLine(filepath.Join(d, "uv.toml"), isPyPIIndexLine) || registryLine(filepath.Join(d, "pyproject.toml"), isPyPIIndexLine) {+ r.PyPI = true+ }+ }+}++// forServer adds what a server's launcher reads beyond the machine-wide config:+// - the npm config of a node of its own, beside an absolute launcher or first on a PATH set in+// the server's env (a runtime with a short PATH, a desktop app say, is often pointed at an+// nvm, fnm or Volta node this way);+// - the project config of the directory it runs in, when its definition names one (cwd) or+// uv is told to use one (--directory, --project). A directory Beacon cannot resolve (a+// relative path, ${workspaceFolder}) leaves it unable to tell, so both ecosystems are held+// back for that server.+func (r Registries) forServer(command string, args []string, def map[string]interface{}) Registries {+ var nodeDirs, projects []string+ unresolved := false+ if command = strings.TrimSpace(command); command != "" && strings.ContainsAny(command, `/\`) {+ nodeDirs = append(nodeDirs, filepath.Dir(command))+ }+ if env, ok := def["env"].(map[string]interface{}); ok {+ for key, value := range env {+ if path, ok := value.(string); ok && strings.EqualFold(key, "PATH") {+ nodeDirs = append(nodeDirs, filepath.SplitList(path)...)+ }+ }+ }+ var dirValues []string+ for _, key := range []string{"cwd", "workingDirectory", "working_directory"} {+ if v, ok := def[key].(string); ok && strings.TrimSpace(v) != "" {+ dirValues = append(dirValues, strings.TrimSpace(v))+ }+ }+ if base := launcherBase(command); base == "uvx" || base == "uv" {+ for i := 0; i < len(args); i++ {+ name, value, hasValue := strings.Cut(args[i], "=")+ if name != "--directory" && name != "--project" {+ continue+ }+ if !hasValue && i+1 < len(args) {+ i+++ value = args[i]+ }+ dirValues = append(dirValues, value)+ }+ }+ for _, v := range dirValues {+ if dir, ok := r.expandPath(v); ok {+ projects = append(projects, dir)+ } else {+ unresolved = true+ }+ }+ npmrcs := nodeNpmrcs(nodeDirs)+ if len(npmrcs) == 0 && len(projects) == 0 && !unresolved {+ return r+ }+ out := Registries{NPM: r.NPM || unresolved, PyPI: r.PyPI || unresolved, NPMScopes: map[string]bool{}, home: r.home,+ yarnrc: r.yarnrc, vars: r.vars, read: map[string]bool{}}+ for scope := range r.NPMScopes {+ out.NPMScopes[scope] = true+ }+ for path := range r.read {+ out.read[path] = true+ }+ for _, path := range npmrcs {+ out.readNpmrc(path)+ }+ for _, dir := range projects {+ out.readProject(dir)+ }+ return out+}++// private reports whether a package lookup (npm:<name> or pypi:<name>) may come from another+// registry or index.+func (r Registries) private(q string) bool {+ switch {+ case strings.HasPrefix(q, "npm:"):+ if r.NPM {+ return true+ }+ name := strings.TrimPrefix(q, "npm:")+ if scope, _, ok := strings.Cut(name, "/"); ok && strings.HasPrefix(scope, "@") {+ return r.NPMScopes[scope]+ }+ case strings.HasPrefix(q, "pypi:"):+ return r.PyPI+ }+ return false+}++// addEnv records an inherited environment variable that sets a registry or index.+func (r *Registries) addEnv(key, value string) {+ switch strings.ToLower(key) {+ case "npm_config_userconfig", "npm_config_globalconfig", "npm_config_prefix", "yarn_rc_filename", "uv_config_file", "pip_config_file":+ // Names a config file, which LocalRegistries reads like the default one.+ return+ }+ npm, pypi := registryEnvKey(key)+ switch {+ case npm && !publicRegistry(value):+ k := strings.ToLower(key)+ if scope, ok := strings.CutSuffix(strings.TrimPrefix(k, "npm_config_"), ":registry"); ok && strings.HasPrefix(scope, "@") {+ r.NPMScopes[scope] = true+ } else {+ r.NPM = true+ }+ case pypi && !publicRegistry(value):+ r.PyPI = true+ }+}++func (r *Registries) readNpmrc(path string) {+ if path == "" || r.read[path] {+ return+ }+ if r.read == nil {+ r.read = map[string]bool{}+ }+ if r.NPMScopes == nil {+ r.NPMScopes = map[string]bool{}+ }+ r.read[path] = true+ lines, ok := readConfigLines(path)+ if !ok {+ return+ }+ for _, line := range lines {+ key, value, ok := strings.Cut(line, "=")+ if !ok {+ continue+ }+ key = strings.ToLower(strings.TrimSpace(key))+ value = strings.Trim(strings.TrimSpace(value), `"'`)+ switch {+ case key == "registry":+ if !publicRegistry(value) {+ r.NPM = true+ }+ case strings.HasPrefix(key, "@") && strings.HasSuffix(key, ":registry"):+ if !publicRegistry(value) {+ r.NPMScopes[strings.TrimSuffix(key, ":registry")] = true+ }+ case key == "userconfig" || key == "globalconfig" || key == "prefix":+ // Another config file npm reads (a distro's builtin npmrc names /etc/npmrc this+ // way), or the prefix whose global npmrc it reads: follow it. A value Beacon cannot+ // resolve leaves it unable to tell where packages come from.+ target, ok := r.expandPath(value)+ switch {+ case !ok:+ r.NPM = true+ case key == "prefix":+ r.readNpmrc(filepath.Join(target, "etc", "npmrc"))+ default:+ r.readNpmrc(target)+ }+ }+ }+}++// npmrcVar is npm's ${NAME} reference to an environment variable in an npmrc value.+var npmrcVar = regexp.MustCompile(`\$\{([^${}]+)\}`)++// expandPath resolves an npmrc path value as npm does: ${VAR} from the environment (Windows'+// own installer writes prefix=${APPDATA}\npm), then an absolute path or one under ~. A value+// naming an unset variable, or a relative path, is not resolved.+func (r *Registries) expandPath(value string) (string, bool) {+ resolved := true+ value = npmrcVar.ReplaceAllStringFunc(value, func(ref string) string {+ v, ok := r.vars[strings.ToLower(ref[2:len(ref)-1])]+ if !ok || v == "" {+ resolved = false+ }+ return v+ })+ if !resolved || strings.Contains(value, "$") || value == "" {+ return "", false+ }+ if rest, ok := strings.CutPrefix(value, "~"); ok && (rest == "" || rest[0] == '/' || rest[0] == '\\') {+ if r.home == "" {+ return "", false+ }+ return filepath.Join(r.home, rest), true+ }+ if !filepath.IsAbs(value) {+ return "", false+ }+ return value, true+}++// registryEnvKey reports whether an environment variable can point npm-family launchers (npm)+// or pip-family launchers (pypi) at a registry, index or config file of its own.+func registryEnvKey(key string) (npm, pypi bool) {+ k := strings.ToLower(strings.TrimSpace(key))+ switch {+ // npm_config_registry, npm_config_@scope:registry, and the variables that change which+ // npmrc files npm reads.+ case strings.HasPrefix(k, "npm_config_") && (strings.HasSuffix(k, "registry") || k == "npm_config_userconfig" ||+ k == "npm_config_globalconfig" || k == "npm_config_prefix"):+ return true, false+ case k == "yarn_npm_registry_server" || k == "yarn_rc_filename" || k == "bun_config_registry":+ return true, false+ case k == "uv_index" || k == "uv_index_url" || k == "uv_default_index" || k == "uv_extra_index_url" ||+ k == "uv_find_links" || k == "uv_config_file":+ return false, true+ case k == "pip_index_url" || k == "pip_extra_index_url" || k == "pip_find_links" || k == "pip_config_file" ||+ k == "pipx_default_index_url":+ return false, true+ }+ return false, false+}++// publicRegistry reports whether a setting names the public npm registry or PyPI index, which+// leaves packages public. Anything else, including a value Beacon cannot read, does not.+func publicRegistry(value string) bool {+ v := strings.ToLower(strings.TrimSpace(strings.Trim(strings.TrimSpace(value), `"'`)))+ v = strings.TrimRight(v, "/")+ switch v {+ case "https://registry.npmjs.org", "https://registry.yarnpkg.com", "https://pypi.org/simple", "https://pypi.python.org/simple":+ return true+ }+ return false+}++func isNPMRegistryLine(line string) bool {+ if strings.HasPrefix(strings.TrimSpace(line), "[install.scopes") {+ return true+ }+ key, value, ok := cutKeyValue(line)+ if !ok {+ return false+ }+ switch strings.ToLower(key) {+ case "npmregistryserver", "registry":+ return !publicRegistry(value)+ case "npmscopes":+ return true+ }+ return false+}++func isPyPIIndexLine(line string) bool {+ trimmed := strings.TrimSpace(line)+ if trimmed == "[[index]]" || trimmed == "[[tool.uv.index]]" {+ return true+ }+ key, value, ok := cutKeyValue(line)+ if !ok {+ return false+ }+ switch strings.ReplaceAll(strings.ToLower(key), "_", "-") {+ case "index-url", "extra-index-url", "default-index", "index":+ return !publicRegistry(value)+ case "find-links":+ return true+ }+ return false+}++// cutKeyValue splits an ini, TOML or YAML line at its first '=' or ':'.+func cutKeyValue(line string) (key, value string, ok bool) {+ i := strings.IndexAny(line, "=:")+ if i <= 0 {+ return "", "", false+ }+ return strings.TrimSpace(line[:i]), strings.TrimSpace(line[i+1:]), true+}++func registryLine(path string, match func(string) bool) bool {+ lines, ok := readConfigLines(path)+ if !ok {+ return false+ }+ for _, line := range lines {+ if match(line) {+ return true+ }+ }+ return false+}++// readConfigLines returns a config file's lines without blanks or comments.+func readConfigLines(path string) ([]string, bool) {+ if path == "" {+ return nil, false+ }+ f, err := os.Open(path)+ if err != nil {+ return nil, false+ }+ defer f.Close()+ if info, err := f.Stat(); err != nil || !info.Mode().IsRegular() {+ return nil, false+ }+ var lines []string+ scanner := bufio.NewScanner(io.LimitReader(f, maxRegistryConfigBytes))+ scanner.Buffer(make([]byte, 64*1024), maxRegistryConfigBytes)+ for scanner.Scan() {+ line := strings.TrimSpace(scanner.Text())+ if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") {+ continue+ }+ lines = append(lines, line)+ }+ return lines, true+}diff --git a/cli/beacon/internal/intel/registries_test.go b/cli/beacon/internal/intel/registries_test.gonew file mode 100644index 00000000..53dee041--- /dev/null+++ b/cli/beacon/internal/intel/registries_test.go@@ -0,0 +1,296 @@+package intel++import (+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/inventory"+)++func writeConfig(t *testing.T, path, content string) {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte(content), 0o600); err != nil {+ t.Fatal(err)+ }+}++func TestLocalRegistries(t *testing.T) {+ for _, tc := range []struct {+ name string+ file string // relative to home, or "wd/..." for the working directory+ content string+ environ []string+ private []string+ public []string+ }{+ {name: "nothing configured", public: []string{"npm:@acme/x", "npm:x", "pypi:x"}},+ {name: "scope in user npmrc", file: ".npmrc", content: "; comment\n@acme:registry=https://npm.acme.internal/\n//npm.acme.internal/:_authToken=${TOKEN}\n",+ private: []string{"npm:@acme/billing-mcp"}, public: []string{"npm:@playwright/mcp", "npm:plain", "pypi:x"}},+ {name: "registry in project npmrc", file: "wd/.npmrc", content: "registry = \"https://npm.acme.internal\"\n",+ private: []string{"npm:@playwright/mcp", "npm:plain"}, public: []string{"pypi:x"}},+ {name: "public registry in npmrc", file: ".npmrc", content: "registry=https://registry.npmjs.org/\n@x:registry=https://registry.npmjs.org\n",+ public: []string{"npm:@x/y", "npm:plain"}},+ {name: "npmrc naming a config Beacon cannot resolve", file: ".npmrc", content: "globalconfig=${NPM_HOME}/npmrc\n", private: []string{"npm:plain"}},+ {name: "npmrc naming a missing config", file: ".npmrc", content: "globalconfig=~/nonexistent/npmrc\n", public: []string{"npm:plain"}},+ {name: "scope in pnpm global rc", file: ".config/pnpm/rc", content: "@acme:registry=https://npm.acme.internal/\n",+ private: []string{"npm:@acme/internal-mcp"}, public: []string{"npm:@playwright/mcp"}},+ {name: "registry in macOS pnpm rc", file: "Library/Preferences/pnpm/rc", content: "registry=https://npm.acme.internal/\n", private: []string{"npm:plain"}},+ {name: "global npmrc under a lowercase npm_config_prefix", file: "npm-global/etc/npmrc", content: "registry=https://npm.acme.internal\n",+ environ: []string{"npm_config_prefix=HOME/npm-global"}, private: []string{"npm:plain"}},+ {name: "renamed yarn rc", file: ".acmerc.yml", content: "npmRegistryServer: https://npm.acme.internal\n",+ environ: []string{"YARN_RC_FILENAME=.acmerc.yml"}, private: []string{"npm:plain"}},+ {name: "site-wide pip in XDG_CONFIG_DIRS", file: "xdg-site/pip/pip.conf", content: "[global]\nindex-url = https://pypi.acme.internal/simple\n",+ environ: []string{"XDG_CONFIG_DIRS=HOME/xdg-site"}, private: []string{"pypi:x"}},+ {name: "Windows ProgramData uv", file: "ProgramData/uv/uv.toml", content: "index-url = \"https://pypi.acme.internal/simple\"\n",+ environ: []string{"ProgramData=HOME/ProgramData"}, private: []string{"pypi:x"}},+ {name: "yarn registry", file: ".yarnrc.yml", content: "npmRegistryServer: \"https://npm.acme.internal\"\n", private: []string{"npm:plain"}},+ {name: "yarn public registry", file: ".yarnrc.yml", content: "npmRegistryServer: \"https://registry.yarnpkg.com\"\n", public: []string{"npm:plain"}},+ {name: "yarn scopes", file: ".yarnrc.yml", content: "npmScopes:\n acme:\n npmRegistryServer: https://npm.acme.internal\n", private: []string{"npm:plain"}},+ {name: "bun scopes", file: ".bunfig.toml", content: "[install.scopes]\nacme = \"https://npm.acme.internal\"\n", private: []string{"npm:plain"}},+ {name: "pip.conf index", file: ".config/pip/pip.conf", content: "[global]\nindex-url = https://pypi.acme.internal/simple\n",+ private: []string{"pypi:acme-billing-mcp"}, public: []string{"npm:plain"}},+ {name: "legacy pip.conf extra index", file: ".pip/pip.conf", content: "[global]\nextra_index_url=https://pypi.acme.internal/simple\n", private: []string{"pypi:x"}},+ {name: "pip.conf public index", file: ".config/pip/pip.conf", content: "[global]\nindex-url = https://pypi.org/simple\ntimeout = 60\n", public: []string{"pypi:x"}},+ {name: "uv.toml index table", file: ".config/uv/uv.toml", content: "[[index]]\nname = \"acme\"\nurl = \"https://pypi.acme.internal/simple\"\n", private: []string{"pypi:x"}},+ {name: "project pyproject uv index", file: "wd/pyproject.toml", content: "[project]\nname = \"x\"\n[[tool.uv.index]]\nurl = \"https://pypi.acme.internal/simple\"\n", private: []string{"pypi:x"}},+ {name: "inherited npm scope", environ: []string{"npm_config_@acme:registry=https://npm.acme.internal"},+ private: []string{"npm:@acme/x"}, public: []string{"npm:@other/x", "npm:plain"}},+ {name: "inherited npm registry", environ: []string{"NPM_CONFIG_REGISTRY=https://npm.acme.internal"}, private: []string{"npm:plain"}},+ {name: "inherited public npm registry", environ: []string{"npm_config_registry=https://registry.npmjs.org/"}, public: []string{"npm:plain"}},+ {name: "inherited uv index", environ: []string{"UV_INDEX_URL=https://pypi.acme.internal/simple"}, private: []string{"pypi:x"}, public: []string{"npm:plain"}},+ {name: "inherited pip index", environ: []string{"PIP_EXTRA_INDEX_URL=https://pypi.acme.internal/simple"}, private: []string{"pypi:x"}},+ {name: "a config file named in the environment is read, not counted", file: "elsewhere/npmrc", content: "registry=https://registry.npmjs.org/\n",+ environ: []string{"NPM_CONFIG_USERCONFIG=HOME/elsewhere/npmrc"}, public: []string{"npm:plain"}},+ {name: "unrelated environment", environ: []string{"GITHUB_TOKEN=ghp_x", "NODE_ENV=production"}, public: []string{"npm:plain", "pypi:x"}},+ } {+ t.Run(tc.name, func(t *testing.T) {+ home, wd := t.TempDir(), t.TempDir()+ if tc.file != "" {+ path := filepath.Join(home, tc.file)+ if rel, ok := strings.CutPrefix(tc.file, "wd/"); ok {+ path = filepath.Join(wd, rel)+ }+ writeConfig(t, path, tc.content)+ }+ var environ []string+ for _, kv := range tc.environ {+ environ = append(environ, strings.ReplaceAll(kv, "HOME/", home+string(filepath.Separator)))+ }+ reg := LocalRegistries(RegistryEnv{Home: home, WorkingDir: wd, Environ: environ})+ for _, q := range tc.private {+ if !reg.private(q) {+ t.Errorf("%s was not private: %+v", q, reg)+ }+ }+ for _, q := range tc.public {+ if reg.private(q) {+ t.Errorf("%s was private: %+v", q, reg)+ }+ }+ })+ }+}++func TestLocalRegistriesReadsTheGlobalNpmrcOfTheNodeOnPath(t *testing.T) {+ home := t.TempDir()+ install := filepath.Join(home, ".nvm", "versions", "node", "v20.1.0")+ writeConfig(t, filepath.Join(install, "bin", "node"), "")+ writeConfig(t, filepath.Join(install, "etc", "npmrc"), "@acme:registry=https://npm.acme.internal\n")+ reg := LocalRegistries(RegistryEnv{Home: home, Environ: []string{"PATH=" + filepath.Join(home, "empty") + string(filepath.ListSeparator) + filepath.Join(install, "bin")}})+ if !reg.private("npm:@acme/x") || reg.private("npm:plain") {+ t.Fatalf("the nvm global npmrc was not read: %+v", reg)+ }++ // npm's builtin npmrc, beside the npm the node ships.+ writeConfig(t, filepath.Join(install, "etc", "npmrc"), "")+ writeConfig(t, filepath.Join(install, "lib", "node_modules", "npm", "npmrc"), "registry=https://npm.acme.internal\n")+ if reg := LocalRegistries(RegistryEnv{Home: home, Environ: []string{"PATH=" + filepath.Join(install, "bin")}}); !reg.private("npm:plain") {+ t.Fatalf("npm's builtin npmrc was not read: %+v", reg)+ }+}++func TestNpmrcFollowsTheConfigFilesAndPrefixItNames(t *testing.T) {+ home := t.TempDir()+ // A distro's builtin npmrc names /etc/npmrc; one naming only the public registry leaves+ // packages public.+ writeConfig(t, filepath.Join(home, "etc-npmrc"), "registry=https://registry.npmjs.org/\n")+ writeConfig(t, filepath.Join(home, ".npmrc"), "globalconfig="+filepath.Join(home, "etc-npmrc")+"\n")+ if reg := LocalRegistries(RegistryEnv{Home: home}); reg.private("npm:plain") || reg.private("npm:@x/y") {+ t.Fatalf("a globalconfig naming the public registry held packages back: %+v", reg)+ }+ // One naming a private scope holds that scope back, by ~ too.+ writeConfig(t, filepath.Join(home, "etc-npmrc"), "@acme:registry=https://npm.acme.internal\n")+ writeConfig(t, filepath.Join(home, ".npmrc"), "globalconfig=~/etc-npmrc\n")+ if reg := LocalRegistries(RegistryEnv{Home: home}); !reg.private("npm:@acme/x") || reg.private("npm:plain") {+ t.Fatalf("the named globalconfig was not followed: %+v", reg)+ }+ // prefix= in ~/.npmrc moves the global npmrc.+ writeConfig(t, filepath.Join(home, "npm-global", "etc", "npmrc"), "registry=https://npm.acme.internal\n")+ writeConfig(t, filepath.Join(home, ".npmrc"), "prefix=~/npm-global\n")+ if reg := LocalRegistries(RegistryEnv{Home: home}); !reg.private("npm:plain") {+ t.Fatalf("the prefix's global npmrc was not read: %+v", reg)+ }+ // A cycle of config files ends.+ writeConfig(t, filepath.Join(home, ".npmrc"), "userconfig=~/.npmrc\n")+ LocalRegistries(RegistryEnv{Home: home})+}++func TestNpmrcExpandsEnvironmentVariablesAsNpmDoes(t *testing.T) {+ home := t.TempDir()+ appData := filepath.Join(home, "AppData", "Roaming")+ install := filepath.Join(home, "nodejs")+ writeConfig(t, filepath.Join(install, "bin", "node"), "")+ // The official Windows installer's builtin npmrc.+ writeConfig(t, filepath.Join(install, "lib", "node_modules", "npm", "npmrc"), "prefix=${APPDATA}/npm\n")+ env := RegistryEnv{Home: home, Environ: []string{"APPDATA=" + appData, "PATH=" + filepath.Join(install, "bin")}}+ if reg := LocalRegistries(env); reg.private("npm:plain") || reg.private("npm:@x/y") {+ t.Fatalf("prefix=${APPDATA}/npm held every npm package back: %+v", reg)+ }+ writeConfig(t, filepath.Join(appData, "npm", "etc", "npmrc"), "@acme:registry=https://npm.acme.internal\n")+ if reg := LocalRegistries(env); !reg.private("npm:@acme/x") || reg.private("npm:plain") {+ t.Fatalf("the expanded prefix's global npmrc was not read: %+v", reg)+ }+ // An unset variable leaves Beacon unable to tell, so npm is held back.+ env.Environ = []string{"PATH=" + filepath.Join(install, "bin")}+ if reg := LocalRegistries(env); !reg.private("npm:plain") {+ t.Fatalf("an unset ${APPDATA} did not hold npm back: %+v", reg)+ }+}++func TestLocalRegistriesReadsTheBuiltinNpmrcAlongsideAnExportedPrefix(t *testing.T) {+ home := t.TempDir()+ install := filepath.Join(home, "node")+ writeConfig(t, filepath.Join(install, "bin", "node"), "")+ writeConfig(t, filepath.Join(install, "lib", "node_modules", "npm", "npmrc"), "registry=https://npm.acme.internal\n")+ reg := LocalRegistries(RegistryEnv{Home: home, Environ: []string{"npm_config_prefix=" + filepath.Join(home, "global"), "PATH=" + filepath.Join(install, "bin")}})+ if !reg.private("npm:plain") {+ t.Fatalf("the builtin npmrc was skipped once a prefix was exported: %+v", reg)+ }+}++func TestRegistriesForAServerOnItsOwnNode(t *testing.T) {+ home := t.TempDir()+ nvm := filepath.Join(home, ".nvm", "versions", "node", "v20.11.0")+ writeConfig(t, filepath.Join(nvm, "bin", "node"), "")+ writeConfig(t, filepath.Join(nvm, "bin", "npx"), "")+ writeConfig(t, filepath.Join(nvm, "etc", "npmrc"), "@acme:registry=https://npm.acme.internal\n")+ base := LocalRegistries(RegistryEnv{Home: home})+ if base.private("npm:@acme/x") {+ t.Fatal("the nvm node is not on Beacon's PATH in this test")+ }+ byCommand := base.forServer(filepath.Join(nvm, "bin", "npx"), nil, map[string]interface{}{})+ byPath := base.forServer("npx", nil, map[string]interface{}{"env": map[string]interface{}{"PATH": filepath.Join(nvm, "bin") + string(filepath.ListSeparator) + "/usr/bin"}})+ for name, reg := range map[string]Registries{"absolute command": byCommand, "env PATH": byPath} {+ if !reg.private("npm:@acme/x") || reg.private("npm:@playwright/mcp") {+ t.Errorf("%s: %+v", name, reg)+ }+ }+ if base.private("npm:@acme/x") {+ t.Fatal("forServer changed the machine-wide registries")+ }++ npx := filepath.Join(nvm, "bin", "npx")+ for name, def := range map[string]map[string]interface{}{+ "absolute command": {"command": npx, "args": []interface{}{"-y", "@acme/billing-mcp"}},+ "whole launch line": {"command": npx + " -y @acme/billing-mcp"},+ "cmd /c wrapper": {"command": "cmd", "args": []interface{}{"/c", npx, "-y", "@acme/billing-mcp"}},+ } {+ res := inventory.Result{MCPServers: []inventory.MCPServer{server("claude_desktop", "billing", "user", def)}}+ if items, skipped := FromInventory(res, FromInventoryOptions{Registries: base}); len(items) != 0 || len(skipped) != 1 || skipped[0].Reason != ReasonPrivatePackage {+ t.Errorf("%s: a server on its own nvm node was not held back: %+v %+v", name, items, skipped)+ }+ }+}++func TestRegistriesForAServerRunInAnotherDirectory(t *testing.T) {+ home, work := t.TempDir(), t.TempDir()+ acme := filepath.Join(work, "acme")+ writeConfig(t, filepath.Join(acme, "uv.toml"), "index-url = \"https://pypi.acme.internal/simple\"\n")+ writeConfig(t, filepath.Join(acme, ".npmrc"), "@acme:registry=https://npm.acme.internal\n")+ base := LocalRegistries(RegistryEnv{Home: home})+ for _, tc := range []struct {+ name string+ def map[string]interface{}+ q string+ }{+ {"uvx --directory", map[string]interface{}{"command": "uvx", "args": []interface{}{"--directory", acme, "acme-internal-mcp"}}, "pypi:acme-internal-mcp"},+ {"uv tool run --project=", map[string]interface{}{"command": "uv", "args": []interface{}{"tool", "run", "--project=" + acme, "acme-internal-mcp"}}, "pypi:acme-internal-mcp"},+ {"cwd", map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "@acme/tools"}, "cwd": acme}, "npm:@acme/tools"},+ {"cwd below the project", map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "@acme/tools"}, "cwd": filepath.Join(acme, "sub")}, "npm:@acme/tools"},+ {"unresolvable cwd", map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "@playwright/mcp"}, "cwd": "${workspaceFolder}"}, "npm:@playwright/mcp"},+ } {+ res := inventory.Result{MCPServers: []inventory.MCPServer{server("vscode", "srv", "user", tc.def)}}+ items, skipped := FromInventory(res, FromInventoryOptions{Registries: base})+ if len(items) != 0 || len(skipped) != 1 || skipped[0].Reason != ReasonPrivatePackage {+ t.Errorf("%s: %s was not held back: %+v %+v", tc.name, tc.q, items, skipped)+ }+ }+ // A cwd with nothing private in it leaves a public package public.+ res := inventory.Result{MCPServers: []inventory.MCPServer{server("vscode", "srv", "user",+ map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "@playwright/mcp"}, "cwd": work})}}+ if items, _ := FromInventory(res, FromInventoryOptions{Registries: base}); len(items) != 1 || items[0].Basis != BasisNPM {+ t.Fatalf("a plain cwd held a public package back: %+v", items)+ }+}++func TestLocalRegistriesFollowsAConfigFileNamedInTheEnvironment(t *testing.T) {+ home := t.TempDir()+ path := filepath.Join(home, "ci", "pip.conf")+ writeConfig(t, path, "[global]\nindex-url = https://pypi.acme.internal/simple\n")+ if reg := LocalRegistries(RegistryEnv{Home: home, Environ: []string{"PIP_CONFIG_FILE=" + path}}); !reg.private("pypi:x") {+ t.Fatalf("PIP_CONFIG_FILE was not read: %+v", reg)+ }+}++func TestCurrentRegistryEnvReadsSystemAndProjectFiles(t *testing.T) {+ if env := CurrentRegistryEnv(); !env.System || env.WorkingDir == "" {+ t.Fatalf("CurrentRegistryEnv() = %+v", env)+ }+}++func TestLocalRegistriesReadsProjectConfigAboveTheWorkingDirectory(t *testing.T) {+ root := t.TempDir()+ wd := filepath.Join(root, "repo", "packages", "app")+ writeConfig(t, filepath.Join(root, "repo", ".npmrc"), "@acme:registry=https://npm.acme.internal\n")+ writeConfig(t, filepath.Join(root, "repo", "pyproject.toml"), "[[tool.uv.index]]\nurl = \"https://pypi.acme.internal/simple\"\n")+ if err := os.MkdirAll(wd, 0o700); err != nil {+ t.Fatal(err)+ }+ reg := LocalRegistries(RegistryEnv{Home: t.TempDir(), WorkingDir: wd})+ if !reg.private("npm:@acme/x") || !reg.private("pypi:x") || reg.private("npm:plain") {+ t.Fatalf("project config above the working directory was not read: %+v", reg)+ }+}++func TestLocalRegistriesSkipsProjectFilesWithoutAWorkingDirectory(t *testing.T) {+ home := t.TempDir()+ writeConfig(t, filepath.Join(home, "uv.toml"), "index-url = \"https://pypi.acme.internal/simple\"\n")+ if reg := LocalRegistries(RegistryEnv{Home: home}); reg.private("pypi:x") {+ t.Fatalf("a file outside every config location counted: %+v", reg)+ }+}++func TestFromInventoryHoldsBackLauncherConfigAndEnvFiles(t *testing.T) {+ res := inventory.Result{MCPServers: []inventory.MCPServer{+ server("cursor", "billing", "user", map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "@acme/billing-mcp"}}),+ server("cursor", "pw", "user", map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "@playwright/mcp"}}),+ server("vscode", "fetch", "user", map[string]interface{}{"command": "uvx", "args": []interface{}{"mcp-server-fetch"}, "envFile": "${workspaceFolder}/.env"}),+ }}+ reg := Registries{NPMScopes: map[string]bool{"@acme": true}}+ items, skipped := FromInventory(res, FromInventoryOptions{Registries: reg})+ if len(items) != 1 || items[0].Q != "npm:@playwright/mcp" || items[0].Basis != BasisNPM {+ t.Fatalf("items = %+v", items)+ }+ if len(skipped) != 2 || skipped[0].Reason != ReasonPrivatePackage || skipped[1].Reason != ReasonPrivatePackage {+ t.Fatalf("skipped = %+v", skipped)+ }+ items, _ = FromInventory(res, FromInventoryOptions{Registries: reg, IncludePrivateNames: true})+ if len(items) != 3 {+ t.Fatalf("with consent = %+v", items)+ }+}diff --git a/cli/beacon/internal/mcpserver/intel_tools.go b/cli/beacon/internal/mcpserver/intel_tools.gonew file mode 100644index 00000000..b1e2374c--- /dev/null+++ b/cli/beacon/internal/mcpserver/intel_tools.go@@ -0,0 +1,267 @@+package mcpserver++import (+ "context"+ "encoding/json"+ "fmt"+ "os"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/agentskills"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/inventory"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/intel"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/intelapi"+)++// Beacon Intel tools: check an MCP server or skill against the free public index at+// intel.beacon.sh before installing or running it. These are the local server's only tools+// that reach the network, and only when an agent calls one; each sends just what it names+// (intel_check_installed: the public identifiers internal/intel derives from inventory).++// intelInstalledMatches is how many matches intel_check_installed keeps per artifact.+const intelInstalledMatches = 3++func defaultIntelClient() (*intelapi.Client, error) {+ return intel.New("beacon-mcp/" + version.GetVersion() + " (+https://beacon.sh)")+}++func defaultInventory(includeProject bool) inventory.Result {+ opts := inventory.Options{IncludeContents: true, SkipProjectScope: !includeProject}+ if includeProject {+ if wd, err := os.Getwd(); err == nil {+ opts.WorkingDir = wd+ }+ }+ return inventory.Scan(opts)+}++func (s *Server) intelClient() (*intelapi.Client, error) {+ if s.newIntel != nil {+ return s.newIntel()+ }+ return defaultIntelClient()+}++// intelToolNames is what this server calls the tools intelapi defines for every Beacon server;+// Beacon Cloud MCP names the same tools beacon_intel_*.+var intelToolNames = intelapi.ToolNames{Lookup: "intel_lookup", GetArtifact: "intel_get_artifact", Check: "intel_check"}++func (s *Server) registerIntelTools() {+ // Each tool parses its arguments into the one request it makes. Arguments are checked before+ // the client is made, so a bad call says what is wrong with it even when BEACON_INTEL=0.+ type request func(context.Context, *intelapi.Client) ([]byte, error)+ parse := map[string]func(intelapi.Args) (request, error){+ intelToolNames.Lookup: func(a intelapi.Args) (request, error) {+ req, err := intelapi.ParseLookupArgs(a)+ return func(ctx context.Context, c *intelapi.Client) ([]byte, error) {+ _, raw, err := c.Lookup(ctx, req.Q, req.Kind, req.Limit)+ return raw, err+ }, err+ },+ intelToolNames.GetArtifact: func(a intelapi.Args) (request, error) {+ key, err := intelapi.ParseArtifactArgs(a)+ return func(ctx context.Context, c *intelapi.Client) ([]byte, error) {+ _, raw, err := c.Artifact(ctx, key)+ if intelapi.NotFound(err) {+ return nil, fmt.Errorf("no artifact in Beacon Intel has that key; find one with %s", intelToolNames.Lookup)+ }+ return raw, err+ }, err+ },+ intelToolNames.Check: func(a intelapi.Args) (request, error) {+ items, err := intelapi.ParseCheckArgs(a)+ return func(ctx context.Context, c *intelapi.Client) ([]byte, error) {+ _, raw, err := c.Check(ctx, items)+ return raw, err+ }, err+ },+ }+ for _, spec := range intelapi.Tools(intelToolNames) {+ parseArgs := parse[spec.Name]+ schema := objectSchema(spec.Properties, spec.Required)+ schema["additionalProperties"] = false+ s.register(Tool{+ Name: spec.Name,+ Description: spec.Description,+ InputSchema: schema,+ handler: func(ctx context.Context, args map[string]interface{}) (interface{}, error) {+ a, err := intelapi.ArgsFromMap(args)+ if err != nil {+ return nil, err+ }+ send, err := parseArgs(a)+ if err != nil {+ return nil, err+ }+ client, err := s.intelClient()+ if err != nil {+ return nil, err+ }+ raw, err := send(ctx, client)+ if err != nil {+ return nil, err+ }+ return json.RawMessage(raw), nil+ },+ })+ }+ s.register(Tool{+ Name: "intel_check_installed",+ Description: "Check the MCP servers and skills configured on this machine against Beacon Intel, the way a dependency audit checks a lockfile. " ++ "Beacon reads each runtime's own config (Claude Code, Cursor, Codex, and the rest Beacon supports) and by default sends only public identifiers: npm and PyPI packages, from the public registries, named in a server's launch command. " ++ "Names that may be private (a server's configured name, a package from a private registry or index, skill names) are listed as skipped unless the user agrees to include_private_names. " ++ "Paths, URLs, environment and other arguments never leave the machine. " ++ fmt.Sprintf("Use dry_run to see exactly what would be sent without sending it. Read a concerning result in full with %s.", intelToolNames.GetArtifact),+ InputSchema: checkInstalledSchema(),+ handler: s.checkInstalled,+ })+}++func checkInstalledSchema() map[string]interface{} {+ schema := objectSchema(map[string]interface{}{+ "include_private_names": map[string]interface{}{"type": "boolean", "description": "Also send names that may be private: servers' configured names, packages from a private registry or index, and skill names. Off by default; set it only when the user agrees."},+ "include_project": map[string]interface{}{"type": "boolean", "description": "Also read project-scoped config in the server's working directory (default true)."},+ "dry_run": map[string]interface{}{"type": "boolean", "description": "List what would be sent, and send nothing."},+ }, nil)+ schema["additionalProperties"] = false+ return schema+}++type checkInstalledArgs struct {+ includePrivateNames, includeProject, dryRun bool+}++// parseCheckInstalledArgs refuses an argument the tool does not take and a value that is not a+// JSON bool, rather than falling back to a default: {"dry_run": "true"} must never become a+// live send.+func parseCheckInstalledArgs(args map[string]interface{}) (checkInstalledArgs, error) {+ out := checkInstalledArgs{includeProject: true}+ for key, raw := range args {+ var dst *bool+ switch key {+ case "include_private_names":+ dst = &out.includePrivateNames+ case "include_project":+ dst = &out.includeProject+ case "dry_run":+ dst = &out.dryRun+ default:+ return out, fmt.Errorf("intel_check_installed does not take %q", key)+ }+ value, ok := raw.(bool)+ if !ok {+ return out, fmt.Errorf("%s must be true or false", key)+ }+ *dst = value+ }+ return out, nil+}++type installedResult struct {+ Kind string `json:"kind"`+ Q string `json:"q"`+ Basis string `json:"basis"`+ FoundIn []intel.InstalledSource `json:"found_in"`+ Status string `json:"status"`+ Risk string `json:"risk,omitempty"`+ Guidance string `json:"guidance,omitempty"`+ // NameOnly marks a match made on a name alone: it may be a different artifact that+ // happens to share the name, so its risk is a lead to confirm, not a verdict on this one.+ NameOnly bool `json:"name_only,omitempty"`+ Matches []intelapi.Summary `json:"matches,omitempty"`+}++const nameOnlyGuidance = "Matched by name only: confirm the installed one comes from the matched repository before relying on this. "++type installedReport struct {+ DryRun bool `json:"dry_run,omitempty"`+ Sent []intelapi.CheckItem `json:"sent"`+ Results []installedResult `json:"results,omitempty"`+ Counts map[string]int `json:"counts,omitempty"`+ Skipped []intel.Skipped `json:"skipped"`+ Note string `json:"note"`+}++func (s *Server) checkInstalled(ctx context.Context, args map[string]interface{}) (interface{}, error) {+ a, err := parseCheckInstalledArgs(args)+ if err != nil {+ return nil, err+ }+ var inv inventory.Result+ if s.inventory != nil {+ inv = s.inventory(a.includeProject)+ } else {+ inv = defaultInventory(a.includeProject)+ }+ registryEnv := s.registryEnv+ if registryEnv == nil {+ registryEnv = intel.CurrentRegistryEnv+ }+ items, skipped := intel.FromInventory(inv, intel.FromInventoryOptions{+ IncludePrivateNames: a.includePrivateNames,+ Registries: intel.LocalRegistries(registryEnv()),+ BeaconSkills: agentskills.Names(),+ })+ report := installedReport{Sent: make([]intelapi.CheckItem, len(items)), Skipped: skipped}+ if report.Skipped == nil {+ report.Skipped = []intel.Skipped{}+ }+ for i, item := range items {+ report.Sent[i] = intelapi.CheckItem{Q: item.Q, Kind: item.Kind}+ }+ if a.dryRun {+ report.DryRun = true+ report.Note = "Nothing was sent. These lookups would go to Beacon Intel; skipped entries would not."+ return report, nil+ }+ if len(items) == 0 {+ report.Note = "No MCP server or skill on this machine has a public identifier to check; see skipped."+ return report, nil+ }+ client, err := s.intelClient()+ if err != nil {+ return nil, err+ }+ report.Counts = map[string]int{}+ for start := 0; start < len(items); start += intelapi.MaxCheck {+ end := min(start+intelapi.MaxCheck, len(items))+ res, _, err := client.Check(ctx, report.Sent[start:end])+ if err != nil {+ return nil, err+ }+ if len(res.Results) != end-start {+ return nil, fmt.Errorf("Beacon Intel answered %d results for %d artifacts", len(res.Results), end-start)+ }+ for i, outcome := range res.Results {+ item := items[start+i]+ matches := outcome.Matches+ if len(matches) > intelInstalledMatches {+ matches = matches[:intelInstalledMatches]+ }+ result := installedResult{+ Kind: item.Kind, Q: item.Q, Basis: item.Basis, FoundIn: item.Sources,+ Status: outcome.Status, Risk: outcome.Risk, Guidance: outcome.Guidance, Matches: matches,+ }+ // A name, or a package or repository the index fell back to matching as a name, may+ // be a different artifact that shares it.+ byName := item.Basis == intel.BasisSkillName || item.Basis == intel.BasisServerName || outcome.MatchedBy == "text"+ if outcome.Status == "matched" && byName {+ result.NameOnly = true+ result.Guidance = nameOnlyGuidance + result.Guidance+ }+ report.Results = append(report.Results, result)+ key := outcome.Status+ if outcome.Status == "matched" && outcome.Risk != "" {+ key = outcome.Risk+ }+ report.Counts[key]+++ }+ }+ report.Note = "not_found means never checked, not safe. ambiguous claims no risk: check a candidate with intel_get_artifact. " + intelapi.UntrustedNote+ return report, nil+}++// intelTools lists the Beacon Intel tools, for doctor and tests.+func intelTools() []string {+ return []string{intelToolNames.Lookup, intelToolNames.GetArtifact, intelToolNames.Check, "intel_check_installed"}+}diff --git a/cli/beacon/internal/mcpserver/intel_tools_test.go b/cli/beacon/internal/mcpserver/intel_tools_test.gonew file mode 100644index 00000000..720b902c--- /dev/null+++ b/cli/beacon/internal/mcpserver/intel_tools_test.go@@ -0,0 +1,465 @@+package mcpserver++import (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/inventory"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/intel"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/intelapi"+)++type intelFake struct {+ mu sync.Mutex+ urls []string+ bodies []string+ answer func(path, body string) (int, string)+}++func (f *intelFake) count() int {+ f.mu.Lock()+ defer f.mu.Unlock()+ return len(f.urls)+}++// newIntelServer returns a server whose Beacon Intel client talks to a fake API.+func newIntelServer(t *testing.T, answer func(path, body string) (int, string)) (*Server, *intelFake) {+ t.Helper()+ f := &intelFake{answer: answer}+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body, _ := io.ReadAll(r.Body)+ f.mu.Lock()+ f.urls = append(f.urls, r.Method+" "+r.URL.String())+ f.bodies = append(f.bodies, string(body))+ f.mu.Unlock()+ status, out := f.answer(r.URL.Path, string(body))+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(status)+ _, _ = io.WriteString(w, out)+ }))+ t.Cleanup(srv.Close)+ s := New(Options{LogPath: filepath.Join(t.TempDir(), "runtime.jsonl")})+ s.newIntel = func() (*intelapi.Client, error) {+ return &intelapi.Client{BaseURL: srv.URL, HTTPClient: srv.Client(), UserAgent: "beacon-mcp/test"}, nil+ }+ s.registryEnv = noRegistryEnv+ return s, f+}++// noRegistryEnv keeps a test from reading the machine's own npm, pip and uv configuration.+func noRegistryEnv() intel.RegistryEnv { return intel.RegistryEnv{} }++func call(t *testing.T, s *Server, name string, args map[string]interface{}) (string, bool) {+ t.Helper()+ res, err := s.callTool(context.Background(), callToolParams{Name: name, Arguments: args})+ if err != nil {+ t.Fatalf("%s: %v", name, err)+ }+ if len(res.Content) != 1 {+ t.Fatalf("%s content = %+v", name, res.Content)+ }+ return res.Content[0].Text, res.IsError+}++func TestIntelToolsAreListedWithSchemas(t *testing.T) {+ s := New(Options{LogPath: filepath.Join(t.TempDir(), "runtime.jsonl")})+ if err := s.HasExpectedTools(); err != nil {+ t.Fatal(err)+ }+ listed := map[string]Tool{}+ for _, tool := range s.listTools() {+ listed[tool.Name] = tool+ }+ for _, name := range intelTools() {+ tool, ok := listed[name]+ if !ok {+ t.Fatalf("%s not listed", name)+ }+ if tool.InputSchema["type"] != "object" || len(tool.Description) < 80 {+ t.Fatalf("%s: schema %v, description %q", name, tool.InputSchema, tool.Description)+ }+ }+ if !strings.Contains(listed["intel_lookup"].Description, "never that it is safe") {+ t.Fatal("intel_lookup must say no result is not safe")+ }+ if !strings.Contains(listed["intel_check_installed"].Description, "never leave the machine") {+ t.Fatal("intel_check_installed must say what stays local")+ }+}++func TestIntelLookupPassesTheAnswerThrough(t *testing.T) {+ answer := `{"api":"intel.v1","query":{"q":"evil","matched_by":"text"},"results":[{"entity_key":"mcp:evil/server","risk":"malicious"}],"more":false,"note":"n"}`+ s, f := newIntelServer(t, func(string, string) (int, string) { return 200, answer })+ text, isErr := call(t, s, "intel_lookup", map[string]interface{}{"q": "evil", "kind": "mcp", "limit": float64(3)})+ if isErr {+ t.Fatal(text)+ }+ if f.urls[0] != "GET /api/v1/lookup?kind=mcp&limit=3&q=evil" {+ t.Fatalf("request = %s", f.urls[0])+ }+ var got map[string]interface{}+ if err := json.Unmarshal([]byte(text), &got); err != nil || got["api"] != "intel.v1" {+ t.Fatalf("text = %s (%v)", text, err)+ }+}++func TestIntelToolErrorsAreToolErrors(t *testing.T) {+ s, f := newIntelServer(t, func(path, _ string) (int, string) {+ return 404, `{"api":"intel.v1","error":"not_found","message":"No artifact has that key."}`+ })+ text, isErr := call(t, s, "intel_get_artifact", map[string]interface{}{"key": "mcp:nope/nope"})+ if !isErr || !strings.Contains(text, "intel_lookup") {+ t.Fatalf("not found = %q, %v", text, isErr)+ }+ for _, tc := range []struct {+ name string+ args map[string]interface{}+ }{+ {"intel_lookup", map[string]interface{}{}},+ {"intel_lookup", map[string]interface{}{"q": "x", "kind": "plugin"}},+ {"intel_get_artifact", map[string]interface{}{"key": "evil/server"}},+ {"intel_check", map[string]interface{}{}},+ {"intel_check", map[string]interface{}{"artifacts": []interface{}{}}},+ {"intel_check", map[string]interface{}{"artifacts": []interface{}{float64(3)}}},+ {"intel_check", map[string]interface{}{"artifacts": []interface{}{map[string]interface{}{"q": "x", "kind": float64(1)}}}},+ {"intel_check", map[string]interface{}{"artifacts": []interface{}{map[string]interface{}{"q": "x", "kind": "plugin"}}}},+ {"intel_check", map[string]interface{}{"artifacts": []interface{}{""}}},+ } {+ text, isErr := call(t, s, tc.name, tc.args)+ if !isErr {+ t.Errorf("%s %v succeeded: %s", tc.name, tc.args, text)+ }+ }+ if f.count() != 1 {+ t.Fatalf("%d requests; only the valid artifact call should be sent", f.count())+ }+}++func TestIntelCheckSendsStringsAndObjects(t *testing.T) {+ s, f := newIntelServer(t, func(string, string) (int, string) {+ return 200, `{"api":"intel.v1","results":[],"counts":{}}`+ })+ _, isErr := call(t, s, "intel_check", map[string]interface{}{"artifacts": []interface{}{+ "@playwright/mcp", map[string]interface{}{"q": "anthropics/skills", "kind": "skill"}, map[string]interface{}{"q": "x", "kind": nil},+ }})+ if isErr {+ t.Fatal("check failed")+ }+ if f.bodies[0] != `{"artifacts":[{"q":"@playwright/mcp"},{"q":"anthropics/skills","kind":"skill"},{"q":"x"}]}` {+ t.Fatalf("body = %s", f.bodies[0])+ }+}++func TestIntelToolsAreOffWithBeaconIntel0(t *testing.T) {+ t.Setenv(intel.EnvDisabled, "0")+ s := New(Options{LogPath: filepath.Join(t.TempDir(), "runtime.jsonl")})+ s.registryEnv = noRegistryEnv+ s.inventory = func(bool) inventory.Result {+ return inventory.Result{Skills: []inventory.Skill{{Runtime: "claude_code", SkillName: "pdf", Exists: true}}}+ }+ for _, tc := range []struct {+ name string+ args map[string]interface{}+ }{+ {"intel_lookup", map[string]interface{}{"q": "x"}},+ {"intel_get_artifact", map[string]interface{}{"key": "mcp:a/b"}},+ {"intel_check", map[string]interface{}{"artifacts": []interface{}{"x"}}},+ {"intel_check_installed", map[string]interface{}{"include_private_names": true}},+ } {+ text, isErr := call(t, s, tc.name, tc.args)+ if !isErr || !strings.Contains(text, "BEACON_INTEL=0") {+ t.Errorf("%s = %q, %v", tc.name, text, isErr)+ }+ }+ // A dry run sends nothing, so it still works.+ if text, isErr := call(t, s, "intel_check_installed", map[string]interface{}{"dry_run": true}); isErr {+ t.Errorf("dry run while off: %s", text)+ }+}++func fakeInventory(nServers int) inventory.Result {+ res := inventory.Result{+ Skills: []inventory.Skill{+ {Runtime: "claude_code", SkillName: "pdf", SourceScope: "user", Exists: true},+ {Runtime: "claude_code", SkillName: "beacon-memory-recall", SourceScope: "user", Exists: true},+ },+ }+ res.MCPServers = append(res.MCPServers,+ inventory.MCPServer{Runtime: "claude_code", ServerName: "private-db", SourceScope: "user", CommandPresent: true,+ Definition: map[string]interface{}{"command": "node", "args": []interface{}{"/Users/me/acme/db.js"}, "env": map[string]interface{}{"DB_PASSWORD": "hunter2"}}},+ inventory.MCPServer{Runtime: "cursor", ServerName: "beacon", SourceScope: "user", CommandPresent: true,+ Definition: map[string]interface{}{"command": "beacon", "args": []interface{}{"mcp", "serve"}}},+ )+ for i := 0; i < nServers; i++ {+ res.MCPServers = append(res.MCPServers, inventory.MCPServer{+ Runtime: "claude_code", ServerName: fmt.Sprintf("s%d", i), SourceScope: "user", CommandPresent: true,+ Definition: map[string]interface{}{"command": "npx", "args": []interface{}{"-y", fmt.Sprintf("pkg-%02d@latest", i), "--api-key", "sk-live-secret"}},+ })+ }+ return res+}++func TestIntelCheckInstalledDryRunSendsNothing(t *testing.T) {+ s, f := newIntelServer(t, func(string, string) (int, string) { return 500, "" })+ s.inventory = func(includeProject bool) inventory.Result {+ if includeProject {+ t.Error("include_project false was not passed through")+ }+ return fakeInventory(2)+ }+ text, isErr := call(t, s, "intel_check_installed", map[string]interface{}{"dry_run": true, "include_project": false})+ if isErr {+ t.Fatal(text)+ }+ if f.count() != 0 {+ t.Fatalf("a dry run sent %d requests", f.count())+ }+ var report installedReport+ if err := json.Unmarshal([]byte(text), &report); err != nil {+ t.Fatal(err)+ }+ var sent []string+ for _, item := range report.Sent {+ sent = append(sent, item.Kind+":"+item.Q)+ }+ if strings.Join(sent, " ") != "mcp:npm:pkg-00 mcp:npm:pkg-01" || !report.DryRun {+ t.Fatalf("sent = %v", sent)+ }+ reasons := map[string]string{}+ for _, sk := range report.Skipped {+ reasons[sk.Name] = sk.Reason+ }+ if reasons["private-db"] != intel.ReasonNoPackage || reasons["beacon"] != intel.ReasonBeacon || reasons["beacon-memory-recall"] != intel.ReasonBeacon ||+ reasons["pdf"] != intel.ReasonPrivateSkill {+ t.Fatalf("skipped = %+v", report.Skipped)+ }+}++func TestIntelCheckInstalledChecksInBatchesAndMapsResultsBack(t *testing.T) {+ s, f := newIntelServer(t, func(path, body string) (int, string) {+ var req struct {+ Artifacts []intelapi.CheckItem `json:"artifacts"`+ }+ _ = json.Unmarshal([]byte(body), &req)+ var results []string+ for _, a := range req.Artifacts {+ switch {+ case a.Q == "npm:pkg-07":+ results = append(results, fmt.Sprintf(`{"q":%q,"status":"matched","risk":"malicious","guidance":"Do not install or run it.","matches":[{"entity_key":"mcp:npm:pkg-07"},{"entity_key":"b"},{"entity_key":"c"},{"entity_key":"d"}]}`, a.Q))+ default:+ results = append(results, fmt.Sprintf(`{"q":%q,"status":"not_found","risk":null,"matches":[]}`, a.Q))+ }+ }+ return 200, `{"api":"intel.v1","results":[` + strings.Join(results, ",") + `],"counts":{}}`+ })+ s.inventory = func(bool) inventory.Result { return fakeInventory(60) }+ text, isErr := call(t, s, "intel_check_installed", map[string]interface{}{})+ if isErr {+ t.Fatal(text)+ }+ if f.count() != 2 {+ t.Fatalf("%d requests, want 2 batches for 60 artifacts", f.count())+ }+ var first, second struct {+ Artifacts []intelapi.CheckItem `json:"artifacts"`+ }+ _ = json.Unmarshal([]byte(f.bodies[0]), &first)+ _ = json.Unmarshal([]byte(f.bodies[1]), &second)+ if len(first.Artifacts) != intelapi.MaxCheck || len(second.Artifacts) != 10 {+ t.Fatalf("batches = %d + %d", len(first.Artifacts), len(second.Artifacts))+ }+ for _, body := range f.bodies {+ for _, leak := range []string{"sk-live-secret", "--api-key", "hunter2", "DB_PASSWORD", "/Users/me", "acme", "private-db", "latest", "beacon-memory-recall", `"beacon"`, "pdf"} {+ if strings.Contains(body, leak) {+ t.Fatalf("a request carried %q: %s", leak, body)+ }+ }+ }+ var report installedReport+ if err := json.Unmarshal([]byte(text), &report); err != nil {+ t.Fatal(err)+ }+ if len(report.Results) != 60 || report.Counts["malicious"] != 1 || report.Counts["not_found"] != 59 {+ t.Fatalf("results %d, counts %v", len(report.Results), report.Counts)+ }+ var evil installedResult+ for _, r := range report.Results {+ if r.Q == "npm:pkg-07" {+ evil = r+ }+ }+ if evil.Risk != "malicious" || len(evil.FoundIn) != 1 || evil.FoundIn[0].Name != "s7" || evil.FoundIn[0].Runtime != "claude_code" ||+ evil.Basis != intel.BasisNPM || len(evil.Matches) != intelInstalledMatches {+ t.Fatalf("pkg-07 = %+v", evil)+ }+ if evil.NameOnly {+ t.Fatal("a package match was marked name_only")+ }+ if !strings.Contains(report.Note, "not safe") {+ t.Fatalf("note = %q", report.Note)+ }+}++func TestIntelCheckInstalledRefusesAMismatchedAnswer(t *testing.T) {+ s, _ := newIntelServer(t, func(string, string) (int, string) {+ return 200, `{"api":"intel.v1","results":[],"counts":{}}`+ })+ s.inventory = func(bool) inventory.Result { return fakeInventory(1) }+ text, isErr := call(t, s, "intel_check_installed", map[string]interface{}{})+ if !isErr || !strings.Contains(text, "0 results for 1 artifacts") {+ t.Fatalf("= %q, %v", text, isErr)+ }+}++func TestIntelCheckInstalledWithNothingToSend(t *testing.T) {+ s, f := newIntelServer(t, func(string, string) (int, string) { return 500, "" })+ s.inventory = func(bool) inventory.Result {+ return inventory.Result{MCPServers: fakeInventory(0).MCPServers}+ }+ text, isErr := call(t, s, "intel_check_installed", map[string]interface{}{})+ if isErr || f.count() != 0 || !strings.Contains(text, "No MCP server or skill on this machine has a public identifier") {+ t.Fatalf("= %q, %v, %d requests", text, isErr, f.count())+ }+}++func TestIntelToolsOverStdio(t *testing.T) {+ s, _ := newIntelServer(t, func(string, string) (int, string) {+ return 200, `{"api":"intel.v1","index":{},"results":[{"entity_key":"mcp:a/b","risk":"benign"}],"query":{"matched_by":"repository"}}`+ })+ input := `{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"intel_lookup","arguments":{"q":"a/b"}}}` + "\n"+ var out strings.Builder+ if err := s.ServeStdio(t.Context(), strings.NewReader(input), &out); err != nil {+ t.Fatal(err)+ }+ var resp struct {+ ID int `json:"id"`+ Result toolResult `json:"result"`+ }+ if err := json.Unmarshal([]byte(out.String()), &resp); err != nil || resp.ID != 7 || resp.Result.IsError ||+ !strings.Contains(resp.Result.Content[0].Text, `"mcp:a/b"`) {+ t.Fatalf("response = %s (%v)", out.String(), err)+ }+}++func TestIntelToolsShareTheCloudContract(t *testing.T) {+ s := New(Options{LogPath: filepath.Join(t.TempDir(), "runtime.jsonl")})+ listed := map[string]Tool{}+ for _, tool := range s.listTools() {+ listed[tool.Name] = tool+ }+ for _, spec := range intelapi.Tools(intelToolNames) {+ tool := listed[spec.Name]+ if tool.Description != spec.Description || tool.InputSchema["additionalProperties"] != false {+ t.Errorf("%s does not carry the shared spec: %+v", spec.Name, tool.InputSchema)+ }+ }+}++func TestIntelToolArgumentErrorsComeFirst(t *testing.T) {+ t.Setenv(intel.EnvDisabled, "0")+ s := New(Options{LogPath: filepath.Join(t.TempDir(), "runtime.jsonl")})+ for name, args := range map[string]map[string]interface{}{+ "intel_lookup": {"q": "x", "user": "someone"},+ "intel_get_artifact": {"key": "evil/server"},+ "intel_check": {"artifacts": []interface{}{}},+ "intel_check_installed": {"dry_run": "true"},+ } {+ text, isErr := call(t, s, name, args)+ if !isErr || strings.Contains(text, "BEACON_INTEL=0") {+ t.Errorf("%s = %q; want the argument error, not the off switch", name, text)+ }+ }+}++func TestIntelCheckInstalledRefusesMalformedArguments(t *testing.T) {+ s, f := newIntelServer(t, func(string, string) (int, string) { return 500, "" })+ s.inventory = func(bool) inventory.Result { return fakeInventory(2) }+ for _, args := range []map[string]interface{}{+ {"dry_run": "true"},+ {"dry_run": 1},+ {"dry_run": nil},+ {"include_private_names": "yes", "dry_run": true},+ {"include_project": "false"},+ {"dryrun": true},+ } {+ text, isErr := call(t, s, "intel_check_installed", args)+ if !isErr {+ t.Errorf("%v was accepted: %s", args, text)+ }+ }+ if f.count() != 0 {+ t.Fatalf("malformed arguments sent %d requests", f.count())+ }+}++func TestIntelCheckInstalledHoldsBackAScopeFromTheUsersNpmrc(t *testing.T) {+ s, f := newIntelServer(t, func(string, string) (int, string) { return 500, "" })+ home := t.TempDir()+ if err := os.WriteFile(filepath.Join(home, ".npmrc"), []byte("@acme:registry=https://npm.acme.internal/\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ s.registryEnv = func() intel.RegistryEnv { return intel.RegistryEnv{Home: home} }+ s.inventory = func(bool) inventory.Result {+ return inventory.Result{MCPServers: []inventory.MCPServer{+ {Runtime: "cursor", ServerName: "billing", SourceScope: "user", CommandPresent: true,+ Definition: map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "@acme/billing-mcp"}}},+ {Runtime: "cursor", ServerName: "playwright", SourceScope: "user", CommandPresent: true,+ Definition: map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "@playwright/mcp"}}},+ }}+ }+ // include_project only picks which servers are listed: the scope still applies.+ text, isErr := call(t, s, "intel_check_installed", map[string]interface{}{"dry_run": true, "include_project": false})+ if isErr {+ t.Fatal(text)+ }+ var report installedReport+ if err := json.Unmarshal([]byte(text), &report); err != nil {+ t.Fatal(err)+ }+ if len(report.Sent) != 1 || report.Sent[0].Q != "npm:@playwright/mcp" || len(report.Skipped) != 1 || report.Skipped[0].Reason != intel.ReasonPrivatePackage {+ t.Fatalf("report = %+v", report)+ }+ if strings.Contains(text, "acme.internal") || f.count() != 0 {+ t.Fatalf("the registry leaked or a request was sent: %s", text)+ }+}++func TestIntelCheckInstalledMarksNameMatches(t *testing.T) {+ s, f := newIntelServer(t, func(path, body string) (int, string) {+ // The package matched nothing, so the index matched its text against names; the skill+ // matched by name.+ return 200, `{"api":"intel.v1","results":[+ {"q":"npm:some-mcp","matched_by":"text","status":"matched","risk":"benign","guidance":"No issues found.","matches":[{"entity_key":"mcp:other/some-mcp"}]},+ {"q":"pdf","matched_by":"text","status":"matched","risk":"benign","guidance":"No issues found.","matches":[{"entity_key":"skill:a/b#pdf"}]}+ ],"counts":{}}`+ })+ s.inventory = func(bool) inventory.Result {+ return inventory.Result{+ MCPServers: []inventory.MCPServer{{Runtime: "cursor", ServerName: "x", SourceScope: "user", CommandPresent: true,+ Definition: map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "some-mcp"}}}},+ Skills: []inventory.Skill{{Runtime: "claude_code", SkillName: "pdf", SourceScope: "user", Exists: true}},+ }+ }+ text, isErr := call(t, s, "intel_check_installed", map[string]interface{}{"include_private_names": true})+ if isErr || f.count() != 1 {+ t.Fatalf("= %q, %v", text, isErr)+ }+ var report installedReport+ if err := json.Unmarshal([]byte(text), &report); err != nil {+ t.Fatal(err)+ }+ for _, r := range report.Results {+ if !r.NameOnly || !strings.HasPrefix(r.Guidance, "Matched by name only") || !strings.HasSuffix(r.Guidance, "No issues found.") {+ t.Errorf("%s = %+v, want name_only", r.Q, r)+ }+ }+}diff --git a/cli/beacon/internal/mcpserver/server.go b/cli/beacon/internal/mcpserver/server.goindex d4a82128..1cd5a6c4 100644--- a/cli/beacon/internal/mcpserver/server.go+++ b/cli/beacon/internal/mcpserver/server.go@@ -1,5 +1,5 @@// Package mcpserver implements the small local MCP server surface Beacon needs-// for activity querying. It intentionally supports the server methods exercised+// for activity querying, approved memory, and Beacon Intel checks (intel_tools.go). It intentionally supports the server methods exercised// by current desktop clients and tests: initialize, tools/list, tools/call, and// notifications without responses.package mcpserver@@ -16,9 +16,12 @@ import ("time""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/activity"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/inventory"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/intel""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/learning""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version""github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/intelapi")const (@@ -34,6 +37,11 @@ type Server struct {logPath stringtools map[string]Toolorder []string+ // newIntel, inventory and registryEnv replace the Beacon Intel client, the inventory scan+ // and where launcher registry settings are read in tests.+ newIntel func() (*intelapi.Client, error)+ inventory func(includeProject bool) inventory.Result+ registryEnv func() intel.RegistryEnv}type Tool struct {@@ -123,7 +131,7 @@ func (s *Server) ToolNames() []string {}func (s *Server) HasExpectedTools() error {- expected := []string{"search_activity", "summarize_activity", "get_activity_event", "list_activity_filters", "search_memory", "get_memory", "get_memory_context"}+ expected := append([]string{"search_activity", "summarize_activity", "get_activity_event", "list_activity_filters", "search_memory", "get_memory", "get_memory_context"}, intelTools()...)for _, name := range expected {if _, ok := s.tools[name]; !ok {return fmt.Errorf("missing MCP tool %q", name)@@ -377,6 +385,7 @@ func (s *Server) registerTools() {return memoryContextResult{Context: memorySummaries(memories), Returned: len(memories), Limit: query.Limit}, nil},})+ s.registerIntelTools()}func (s *Server) memoryStore() *learning.Store {diff --git a/cli/beacon/internal/mcpserver/server_test.go b/cli/beacon/internal/mcpserver/server_test.goindex cac87734..6580fd10 100644--- a/cli/beacon/internal/mcpserver/server_test.go+++ b/cli/beacon/internal/mcpserver/server_test.go@@ -73,7 +73,7 @@ func TestExpectedToolsRegistered(t *testing.T) {if err := server.HasExpectedTools(); err != nil {t.Fatalf("HasExpectedTools returned error: %v", err)}- if got := strings.Join(server.ToolNames(), ","); got != "search_activity,summarize_activity,get_activity_event,list_activity_filters,search_memory,get_memory,get_memory_context" {+ if got := strings.Join(server.ToolNames(), ","); got != "search_activity,summarize_activity,get_activity_event,list_activity_filters,search_memory,get_memory,get_memory_context,intel_lookup,intel_get_artifact,intel_check,intel_check_installed" {t.Fatalf("ToolNames = %s", got)}}diff --git a/docs/cli/intel.mdx b/docs/cli/intel.mdxindex 559ee483..08e767ca 100644--- a/docs/cli/intel.mdx+++ b/docs/cli/intel.mdx@@ -103,12 +103,61 @@ fail it, because they claim no risk.It also shows when the newest verdict and registry update arrived. The index is refreshedhourly.+## For agents++The local `beacon` MCP server ([`beacon mcp serve`](/cli/mcp)) gives agents the same checks as+tools, so an agent can check an MCP server or skill before it installs or runs it:++| Tool | Does |+|------|------|+| `intel_lookup` | `beacon intel lookup` |+| `intel_get_artifact` | `beacon intel show` |+| `intel_check` | `beacon intel check` |+| `intel_check_installed` | Checks every MCP server and skill configured on this machine |++[Beacon Cloud MCP](/deployment/managed-mcp) has the first three as `beacon_intel_lookup`,+`beacon_intel_get_artifact` and `beacon_intel_check`, free on every plan. Checking what is+installed needs the machine's own config, so `intel_check_installed` is local only.++`intel_check_installed` works like a dependency audit over a lockfile. Beacon reads each+runtime's own MCP and skill configuration (the same files `beacon endpoint inventory` reads).+By default it sends only public identifiers: the npm or PyPI package, from the public registry,+in a server's launch command, without its version. For example, `npx -y @playwright/mcp@latest`+is sent as `npm:@playwright/mcp`, `uvx mcp-server-fetch` as `pypi:mcp-server-fetch`, and the+Windows form `cmd /c npx -y @playwright/mcp` the same way. A launch command with an option+Beacon does not recognize is skipped rather than guessed at, so an option's value is never sent+as a package. So is a package that does not come from a registry: a git or tarball URL, a direct+reference such as `name @ git+https://…`, an `npm:` alias, a path or a local wheel or tarball.++Names that may be private are held back and listed as skipped unless the agent passes+`include_private_names`, which it should do only when you agree:++- the configured name of a server with no package in its command, such as a local script, a+ binary, a container or a remote URL;+- a package that may come from a registry or index other than the public one. Beacon checks+ where launchers usually find one: the launch command (`--registry`, `--index-url`, a config+ file and the like), the server's `env` or `envFile`, the environment it inherits+ (`npm_config_registry`, `npm_config_@scope:registry`, `UV_INDEX_URL`, `PIP_INDEX_URL` and the+ like), and the npm, yarn, bun, pip and uv configuration files in your home directory, the system+ locations, and the working directory and those above it, whether or not `include_project` is set+ (`.npmrc`, including the global and builtin ones under npm's prefix, pnpm's global `rc`,+ `.yarnrc.yml`, `bunfig.toml`, `pip.conf`, `uv.toml`, `pyproject.toml`). A private npm scope holds back only that scope's packages.+ Settings that name the public registry don't count. A registry configured anywhere else (a+ shell profile the agent did not inherit, say) is not seen, so check with `dry_run` first;+- skill names, since a skill may be one you wrote.++Paths, URLs, environment variables and other arguments are never sent. Beacon's own server and+skills are skipped. A result matched only by a name, including a package the index could only+match by name, is marked `name_only`: it may be a different artifact with the same name, so+confirm the repository before relying on it. `dry_run` returns exactly what would be sent and+sends nothing. Results map back to every runtime and config where each artifact was found.+## Network and privacyEvery `beacon intel` command makes one HTTPS request to `https://intel.beacon.sh`. The requestcarries only what you named, plus Beacon's version in the `User-Agent`. No account token,device key or telemetry is sent, and redirects are refused. Hooks, plugins and background jobs-never make this request.+never make this request; the MCP tools above make it only when an agent calls one.| Variable | Effect ||----------|--------|diff --git a/docs/cli/mcp-doctor.mdx b/docs/cli/mcp-doctor.mdxindex 36c49d93..a0ed1e73 100644--- a/docs/cli/mcp-doctor.mdx+++ b/docs/cli/mcp-doctor.mdx@@ -30,8 +30,9 @@ Doctor reports:- Registered MCP toolsThe expected tool set is `search_activity`, `summarize_activity`,-`get_activity_event`, `list_activity_filters`, `search_memory`, `get_memory`, and-`get_memory_context`.+`get_activity_event`, `list_activity_filters`, `search_memory`, `get_memory`,+`get_memory_context`, `intel_lookup`, `intel_get_artifact`, `intel_check`, and+`intel_check_installed`.If the runtime log does not exist yet, doctor reports that Beacon MCP can still start, but activity answers will be empty until endpoint telemetry writes events.diff --git a/docs/cli/mcp.mdx b/docs/cli/mcp.mdxindex 2d2afb40..e71cb863 100644--- a/docs/cli/mcp.mdx+++ b/docs/cli/mcp.mdx@@ -67,6 +67,10 @@ The local `beacon` server exposes these MCP tools:| `search_memory` | Search approved Beacon project memory and return compact summaries. || `get_memory` | Fetch one approved memory item by ID. || `get_memory_context` | Return a small approved-memory context set for the current task. |+| `intel_lookup` | Look up an MCP server or skill in [Beacon Intel](/cli/intel) and get its risk. |+| `intel_get_artifact` | Get one Beacon Intel artifact in full: verdict, findings, lineage, advisories. |+| `intel_check` | Check up to 50 MCP servers and skills in one call. |+| `intel_check_installed` | Check the MCP servers and skills configured on this machine. |Search and summary tools accept filters such as `since`, `until`, `limit`, `q`, `harness`, `model`, `action`, `severity`, `category`, `repository`, `session`, `file`, `command`, `mcp`, `approval`, `decision`, `policy`, `review`, and `wazuh_level`.@@ -78,6 +82,16 @@ projects the memory store already holds records for; Beacon does not read gitmetadata from a path a client supplies, so an unrecognized path returns nothingrather than widening the search.+The `intel_*` tools let an agent check an MCP server or skill before installing or running+it. They are free and need no Beacon account. They are the only local tools that reach the+network, and only when an agent calls one: each sends what it names to `intel.beacon.sh`.+`intel_check_installed` sends only public identifiers it derives from each runtime's own+config: npm and PyPI packages, from the public registries, in a server's launch command. Server+names, private-registry packages and skill names go only with `include_private_names`. Paths, URLs,+environment and other arguments stay on the machine, and `dry_run` shows what would be sent.+`BEACON_INTEL=0` turns these tools off. See [`beacon intel`](/cli/intel) for risks and what+each answer means.+## FlagsThese flags apply to `serve` and `doctor`. For the flags of `connect`, `disconnect` and `status`,diff --git a/docs/deployment/managed-mcp.mdx b/docs/deployment/managed-mcp.mdxindex 3932d601..8d912e80 100644--- a/docs/deployment/managed-mcp.mdx+++ b/docs/deployment/managed-mcp.mdx@@ -148,6 +148,9 @@ anyone else's data. A tool that needs write access is hidden from read-only conn| `beacon_memory_search` | Searches your approved memory; every word must match | Pro || `beacon_memory_get` | Returns one approved memory in full | Pro || `beacon_memory_skill` | Renders an approved memory as an Agent Skill (`SKILL.md`) for the agent to save in your repository | Pro |+| `beacon_intel_lookup` | Looks up an MCP server or skill in [Beacon Intel](/cli/intel) and returns its risk | All |+| `beacon_intel_get_artifact` | Returns one Beacon Intel artifact in full: verdict, findings, repository lineage, advisories | All |+| `beacon_intel_check` | Checks up to 50 MCP servers and skills in one call | All |Time filters accept a relative window such as `24h`, `7d` or `2w`, or exact `after` and `before`dates. `beacon_read_session` also accepts a dashboard session URL.