Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

feat(inventory): name each MCP server's package and each skill's source repo (#1254)

Justin D'Souzaf515c12506d7
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 60639a85..1e54d3d6 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -664,6 +664,7 @@ jobs:
./internal/groksession/... `
./internal/hermessession/... `
./internal/intel/... `
+ ./internal/launchpkg/... `
./internal/learning/... `
./internal/managedprivacy/... `
./internal/mcpconnect/... `
diff --git a/CLAUDE.md b/CLAUDE.md
index bf8eca33..c4728887 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -33,7 +33,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 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.
+- 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-lookup mapping in `cli/beacon/internal/intel`; the launch-command package parser and launcher registry config in `cli/beacon/internal/launchpkg`, which the inventory scan runs so each MCP server record carries `package`/`package_registry` (the root system job runs it as the console user, in the hidden `beacon endpoint inventory resolve-packages` child from `cli/beacon/cmd/endpoint_inventory_packages*.go`, never with root's rights; config that exists but cannot be read makes the ecosystem `private`); `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` reads from the scan: 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 a skill's exact key `skill:<owner>/<repo>#<name>` from the skills CLI's `~/.agents/.skill-lock.json` (never a lock beside a repository's own skills, which could claim any source; the repository may be private, and Intel keeps nothing it is asked), 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 (`launchpkg.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), and the names of skills with no key); 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/cmd/endpoint_diagnostics.go b/cli/beacon/cmd/endpoint_diagnostics.go
index ed47400d..2e0bc83b 100644
--- a/cli/beacon/cmd/endpoint_diagnostics.go
+++ b/cli/beacon/cmd/endpoint_diagnostics.go
@@ -323,7 +323,14 @@ func runEndpointInventory(cmd *cobra.Command, args []string) error {
if name == "" {
name = server.ServerNameHash
}
- fmt.Printf("MCP: %s %s scope=%s transport=%s command_present=%t args=%d env_keys=%d\n", server.Runtime, name, server.SourceScope, server.Transport, server.CommandPresent, server.ArgsCount, server.EnvKeyCount)
+ fmt.Printf("MCP: %s %s scope=%s transport=%s command_present=%t args=%d env_keys=%d", server.Runtime, name, server.SourceScope, server.Transport, server.CommandPresent, server.ArgsCount, server.EnvKeyCount)
+ if server.PackageRegistry != "" {
+ fmt.Printf(" package_registry=%s", server.PackageRegistry)
+ }
+ if server.Package != "" {
+ fmt.Printf(" package=%s", server.Package)
+ }
+ fmt.Println()
printInventoryDefinition(server.Definition)
}
}
@@ -343,7 +350,11 @@ func runEndpointInventory(cmd *cobra.Command, args []string) error {
if path == "" {
path = skill.ManifestPathHash
}
- fmt.Printf("Skill: %s %s scope=%s status=%s path=%s\n", skill.Runtime, name, skill.SourceScope, skill.ParserStatus, path)
+ fmt.Printf("Skill: %s %s scope=%s status=%s path=%s", skill.Runtime, name, skill.SourceScope, skill.ParserStatus, path)
+ if skill.IntelKey != "" {
+ fmt.Printf(" intel_key=%s", skill.IntelKey)
+ }
+ fmt.Println()
printInventoryContent(skill.Content)
}
}
@@ -583,15 +594,16 @@ func writeInventoryHeartbeat(cfg endpointconfig.Config, settings endpointconfig.
writeSnapshot := false
next := state
release := func() {}
+ var resolvePackages packageResolver
if !scope.NoConsoleUser {
- confined, err := confineInventoryScan(scope.HomeDir)
+ confined, resolver, err := confineInventoryScan(scope.HomeDir)
if err != nil {
// Never scan a home root does not own without the confinement; the liveness heartbeat
// still goes out.
fmt.Fprintf(os.Stderr, "warning: inventory scan skipped: %v\n", err)
scope = heartbeatScope{NoConsoleUser: true}
} else {
- release = confined
+ release, resolvePackages = confined, resolver
}
}
if scope.NoConsoleUser {
@@ -607,6 +619,7 @@ func writeInventoryHeartbeat(cfg endpointconfig.Config, settings endpointconfig.
Now: func() time.Time { return now },
IncludeContents: settings.IncludeContents,
MaxContentBytes: settings.MaxContentBytes,
+ ResolvePackages: resolvePackages,
})
release()
digest = endpointinventory.SnapshotDigest(inventoryResult)
@@ -1963,21 +1976,28 @@ func syntheticEvent(destination string) schema.Event {
// scanning a home it does not own -- the system job reading the console user's home. That user can
// plant anything there: a symlink to a root-only file (whose content or hash would land in the
// world-readable system log), a FIFO that hangs the job while it holds the inventory lock, or a
-// link to /dev/zero. Confined, those read as absent. It returns the release to call after the scan.
-func confineInventoryScan(home string) (func(), error) {
+// link to /dev/zero. Confined, those read as absent. It returns the release to call after the scan
+// and, confined, the resolver the scan names MCP server packages with: the console user's own (see
+// packagesAsUser), since the launcher config it reads is wherever that user pointed it. Without
+// one, a confined scan holds every package back as private.
+func confineInventoryScan(home string) (func(), packageResolver, error) {
if strings.TrimSpace(home) == "" || os.Geteuid() != 0 {
- return func() {}, nil
+ return func() {}, nil, nil
}
uid, err := sessionfs.OwnerUID(home)
if err != nil {
- return nil, fmt.Errorf("could not read the owner of %s: %w", home, err)
+ return nil, nil, fmt.Errorf("could not read the owner of %s: %w", home, err)
}
if uid == 0 {
- return func() {}, nil
+ return func() {}, nil, nil
}
confined, err := sessionfs.Confine(home, uid, sessionfs.Options{})
if err != nil {
- return nil, err
+ return nil, nil, err
+ }
+ resolver, err := packagesAsUser(uid, home)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "warning: MCP server packages are held back as private: %v\n", err)
}
- return confined.Release, nil
+ return confined.Release, resolver, nil
}
diff --git a/cli/beacon/cmd/endpoint_inventory_packages.go b/cli/beacon/cmd/endpoint_inventory_packages.go
new file mode 100644
index 00000000..d2e1bec0
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_inventory_packages.go
@@ -0,0 +1,108 @@
+package cmd
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os/exec"
+ "time"
+
+ "github.com/spf13/cobra"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/launchpkg"
+)
+
+// packageResolver answers which package each MCP server runs; see endpointinventory.Options.
+type packageResolver = func(launchpkg.RegistryEnv, []launchpkg.Query) ([]launchpkg.Answer, error)
+
+// packageRequest is what the system inventory job asks resolve-packages.
+type packageRequest struct {
+ Env launchpkg.RegistryEnv `json:"env"`
+ Queries []launchpkg.Query `json:"queries"`
+}
+
+const (
+ // maxPackageExchangeBytes bounds a request or an answer; a snapshot's servers fit many times.
+ maxPackageExchangeBytes = 16 << 20
+ // packageResolveTimeout bounds the console user's resolver. A FIFO is opened non-blocking, but
+ // a hung network home is not, and the job holds the inventory lock while it waits.
+ packageResolveTimeout = 30 * time.Second
+ // packageResolveWaitDelay is how long the job waits, once the timeout has killed the child, for
+ // its pipes to close. The child is the console user's own process, so they can hold its stdout
+ // open from another process (/proc/<pid>/fd/1, or a child it started); without a bound the job
+ // would wait for them forever while holding the inventory lock, and no heartbeat would go out.
+ packageResolveWaitDelay = 2 * time.Second
+)
+
+// endpointInventoryResolvePackagesCmd names the package each MCP server runs, reading the launcher
+// config those servers' launchers read. The system inventory job runs it as the console user (see
+// packagesAsUser), so that config, wherever the user pointed it, is read with their rights and
+// never root's: whatever they could not read, Beacon cannot either, and holds back as private. It
+// reads a packageRequest as JSON on stdin and writes the answers as JSON on stdout.
+var endpointInventoryResolvePackagesCmd = &cobra.Command{
+ Use: "resolve-packages",
+ Short: "Internal: name MCP server packages with the current user's launcher config",
+ Hidden: true,
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, _ []string) error {
+ var req packageRequest
+ if err := json.NewDecoder(io.LimitReader(cmd.InOrStdin(), maxPackageExchangeBytes)).Decode(&req); err != nil {
+ return fmt.Errorf("read package request: %w", err)
+ }
+ return json.NewEncoder(cmd.OutOrStdout()).Encode(launchpkg.ResolveAll(req.Env, req.Queries))
+ },
+}
+
+func init() {
+ endpointInventoryCmd.AddCommand(endpointInventoryResolvePackagesCmd)
+}
+
+// packageResolverCommand is the resolver child; a var so tests can run it in the test binary.
+var packageResolverCommand = func(ctx context.Context, exe string) *exec.Cmd {
+ return exec.CommandContext(ctx, exe, "endpoint", "inventory", "resolve-packages")
+}
+
+// resolvePackagesWith runs the resolver child c and reads its answers. The child runs as the
+// console user, who may tamper with it, so its answer is bounded and checked like any input: it
+// can only mislabel that user's own servers, which their own config already decides.
+func resolvePackagesWith(c *exec.Cmd, env launchpkg.RegistryEnv, queries []launchpkg.Query) ([]launchpkg.Answer, error) {
+ in, err := json.Marshal(packageRequest{Env: env, Queries: queries})
+ if err != nil {
+ return nil, err
+ }
+ var out, stderr bytes.Buffer
+ c.Stdin = bytes.NewReader(in)
+ c.Stdout = &cappedBuffer{buf: &out, limit: maxPackageExchangeBytes}
+ c.Stderr = &cappedBuffer{buf: &stderr, limit: 4 << 10}
+ c.WaitDelay = packageResolveWaitDelay
+ if err := c.Run(); err != nil {
+ return nil, fmt.Errorf("resolve MCP server packages as the console user: %w: %s", err, bytes.TrimSpace(stderr.Bytes()))
+ }
+ var answers []launchpkg.Answer
+ if err := json.Unmarshal(out.Bytes(), &answers); err != nil {
+ return nil, fmt.Errorf("read MCP server packages: %w", err)
+ }
+ if len(answers) != len(queries) {
+ return nil, fmt.Errorf("read MCP server packages: %d answers for %d servers", len(answers), len(queries))
+ }
+ return answers, nil
+}
+
+var errExchangeTooLarge = errors.New("resolver output over the size limit")
+
+// cappedBuffer fails a write that would take buf past limit.
+type cappedBuffer struct {
+ buf *bytes.Buffer
+ limit int
+}
+
+func (w *cappedBuffer) Write(p []byte) (int, error) {
+ if w.buf.Len()+len(p) > w.limit {
+ return 0, errExchangeTooLarge
+ }
+ return w.buf.Write(p)
+}
diff --git a/cli/beacon/cmd/endpoint_inventory_packages_test.go b/cli/beacon/cmd/endpoint_inventory_packages_test.go
new file mode 100644
index 00000000..df2875e9
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_inventory_packages_test.go
@@ -0,0 +1,132 @@
+package cmd
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "os/exec"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/launchpkg"
+)
+
+// TestPackageResolverHelperProcess is the resolver child when a test runs this binary as one. It
+// is told so by its arguments: packagesAsUser gives the child an environment of its own.
+func TestPackageResolverHelperProcess(t *testing.T) {
+ i := slices.Index(os.Args, "--")
+ if i < 0 || len(os.Args) != i+2 {
+ return
+ }
+ switch os.Args[i+1] {
+ case "resolve-packages":
+ endpointInventoryResolvePackagesCmd.SetIn(os.Stdin)
+ endpointInventoryResolvePackagesCmd.SetOut(os.Stdout)
+ if err := endpointInventoryResolvePackagesCmd.RunE(endpointInventoryResolvePackagesCmd, nil); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+ case "too-few":
+ fmt.Print("[]")
+ case "too-much":
+ fmt.Print(strings.Repeat(" ", maxPackageExchangeBytes+1))
+ case "fail":
+ fmt.Fprint(os.Stderr, "boom")
+ os.Exit(3)
+ case "hold-stdout":
+ // A process the console user controls keeps the child's stdout open after it dies.
+ holder := helperResolver(context.Background(), "sleep")
+ holder.Stdout = os.Stdout
+ if err := holder.Start(); err != nil {
+ os.Exit(1)
+ }
+ time.Sleep(time.Minute)
+ case "sleep":
+ time.Sleep(30 * time.Second)
+ }
+ os.Exit(0)
+}
+
+func helperResolver(ctx context.Context, mode string) *exec.Cmd {
+ return exec.CommandContext(ctx, os.Args[0], "-test.run=^TestPackageResolverHelperProcess$", "--", mode)
+}
+
+var testQueries = []launchpkg.Query{
+ {Launch: map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "@acme/billing-mcp"}}},
+ {Launch: map[string]interface{}{"command": "node", "args": []interface{}{"server.js"}}},
+}
+
+// The child's answers come back in query order; an answer that does not fit the question, or a
+// child that fails, is an error, which the scan turns into every package held back as private.
+func TestResolvePackagesWithAChild(t *testing.T) {
+ home := t.TempDir()
+ if err := os.WriteFile(home+"/.npmrc", []byte("@acme:registry=https://npm.acme.internal/\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ answers, err := resolvePackagesWith(helperResolver(context.Background(), "resolve-packages"), launchpkg.RegistryEnv{Home: home}, testQueries)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []launchpkg.Answer{{Package: launchpkg.Package{Ref: "npm:@acme/billing-mcp", Private: true}, OK: true}, {}}
+ if !slices.Equal(answers, want) {
+ t.Fatalf("answers = %+v, want %+v", answers, want)
+ }
+
+ for _, mode := range []string{"too-few", "too-much", "fail"} {
+ if got, err := resolvePackagesWith(helperResolver(context.Background(), mode), launchpkg.RegistryEnv{Home: home}, testQueries); err == nil {
+ t.Errorf("%s: answers = %+v, want an error", mode, got)
+ }
+ }
+}
+
+// The subcommand speaks JSON both ways, and only what the request names is read.
+func TestResolvePackagesCommand(t *testing.T) {
+ work := t.TempDir()
+ if err := os.WriteFile(work+"/.npmrc", []byte("registry=https://npm.acme.internal/\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ request, err := json.Marshal(packageRequest{Env: launchpkg.RegistryEnv{Home: t.TempDir()}, Queries: []launchpkg.Query{
+ {Launch: testQueries[0].Launch},
+ {Launch: testQueries[0].Launch, ProjectDirs: []string{work}},
+ }})
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out bytes.Buffer
+ cmd := endpointInventoryResolvePackagesCmd
+ cmd.SetIn(bytes.NewReader(request))
+ cmd.SetOut(&out)
+ t.Cleanup(func() { cmd.SetIn(nil); cmd.SetOut(nil) })
+ if err := cmd.RunE(cmd, nil); err != nil {
+ t.Fatal(err)
+ }
+ var answers []launchpkg.Answer
+ if err := json.Unmarshal(out.Bytes(), &answers); err != nil {
+ t.Fatal(err)
+ }
+ want := []launchpkg.Answer{
+ {Package: launchpkg.Package{Ref: "npm:@acme/billing-mcp"}, OK: true},
+ {Package: launchpkg.Package{Ref: "npm:@acme/billing-mcp", Private: true}, OK: true},
+ }
+ if !slices.Equal(answers, want) {
+ t.Fatalf("answers = %+v, want %+v", answers, want)
+ }
+}
+
+// The child is the console user's own process, so they can hold its stdout open after the timeout
+// kills it. The job must still give up, or it would wait forever holding the inventory lock.
+func TestResolvePackagesGivesUpOnAHeldPipe(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
+ defer cancel()
+ start := time.Now()
+ if got, err := resolvePackagesWith(helperResolver(ctx, "hold-stdout"), launchpkg.RegistryEnv{}, testQueries); err == nil {
+ t.Fatalf("answers = %+v, want an error", got)
+ }
+ if elapsed := time.Since(start); elapsed > packageResolveWaitDelay+10*time.Second {
+ t.Fatalf("resolvePackagesWith took %v; a process holding the pipe kept it waiting", elapsed)
+ }
+}
diff --git a/cli/beacon/cmd/endpoint_inventory_packages_unix.go b/cli/beacon/cmd/endpoint_inventory_packages_unix.go
new file mode 100644
index 00000000..d8492d0b
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_inventory_packages_unix.go
@@ -0,0 +1,57 @@
+//go:build !windows
+
+package cmd
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "runtime"
+ "syscall"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/launchpkg"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/osuser"
+)
+
+// packagesAsUser returns a resolver that runs resolve-packages as the account uid, whose home is
+// home, with its primary and supplementary groups. The kernel then decides what that account may
+// read, so no answer depends on root's view: a lookup the child cannot make, it treats as config
+// it cannot vouch for. A group the child does not carry (one id(1) did not report, or one past
+// macOS's limit) only takes rights away, which errs the same way.
+func packagesAsUser(uid int, home string) (packageResolver, error) {
+ gids, err := osuser.GroupIDs(uid)
+ if err != nil {
+ return nil, err
+ }
+ exe, err := os.Executable()
+ if err != nil {
+ return nil, fmt.Errorf("find the beacon executable: %w", err)
+ }
+ groups := credentialGroups(gids, runtime.GOOS)
+ return func(env launchpkg.RegistryEnv, queries []launchpkg.Query) ([]launchpkg.Answer, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), packageResolveTimeout)
+ defer cancel()
+ c := packageResolverCommand(ctx, exe)
+ c.SysProcAttr = &syscall.SysProcAttr{Credential: &syscall.Credential{
+ Uid: uint32(uid), Gid: groups[0], Groups: groups,
+ }}
+ // None of root's environment: the request carries everything the child reads.
+ c.Env = []string{"HOME=" + home, "PATH=/usr/bin:/bin:/usr/sbin:/sbin"}
+ c.Dir = "/"
+ return resolvePackagesWith(c, env, queries)
+ }, nil
+}
+
+// darwinMaxGroups is macOS's NGROUPS: its setgroups(2) refuses a longer list with EINVAL, so the
+// child would never start.
+const darwinMaxGroups = 16
+
+// credentialGroups are the groups the child carries: gids, primary first. On macOS, admin and
+// directory-bound accounts often belong to more groups than setgroups takes, so the list is cut at
+// the limit, keeping the primary group.
+func credentialGroups(gids []uint32, goos string) []uint32 {
+ if goos == "darwin" && len(gids) > darwinMaxGroups {
+ return gids[:darwinMaxGroups]
+ }
+ return gids
+}
diff --git a/cli/beacon/cmd/endpoint_inventory_packages_unix_test.go b/cli/beacon/cmd/endpoint_inventory_packages_unix_test.go
new file mode 100644
index 00000000..6e125f94
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_inventory_packages_unix_test.go
@@ -0,0 +1,91 @@
+//go:build !windows
+
+package cmd
+
+import (
+ "context"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/launchpkg"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/osuser"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+)
+
+// macOS's setgroups takes at most 16 groups, and admin and directory-bound accounts often have
+// more: the child must still start, carrying the primary group. Elsewhere every group is kept.
+func TestCredentialGroupsFitSetgroups(t *testing.T) {
+ gids := make([]uint32, 20)
+ for i := range gids {
+ gids[i] = uint32(100 + i)
+ }
+ if got := credentialGroups(gids, "darwin"); len(got) != darwinMaxGroups || got[0] != 100 {
+ t.Errorf("darwin, 20 groups: %v, want the first %d, primary first", got, darwinMaxGroups)
+ }
+ if got := credentialGroups(gids[:darwinMaxGroups], "darwin"); len(got) != darwinMaxGroups {
+ t.Errorf("darwin, %d groups: %v, want all of them", darwinMaxGroups, got)
+ }
+ if got := credentialGroups(gids, "linux"); len(got) != len(gids) {
+ t.Errorf("linux, 20 groups: %v, want all of them", got)
+ }
+}
+
+// The system job resolves packages as the console user, so the kernel decides what of the config
+// they point at is read: a root-only npmrc that root would read as public is, for them, config
+// Beacon cannot vouch for. Needs root and an unprivileged account, named by
+// BEACON_TEST_RUN_AS_USER, that may run this test binary.
+func TestPackagesAsUserReadsWithTheUsersRights(t *testing.T) {
+ name := os.Getenv("BEACON_TEST_RUN_AS_USER")
+ if os.Geteuid() != 0 || name == "" {
+ t.Skip("needs root and BEACON_TEST_RUN_AS_USER")
+ }
+ testenv.RequireCommands(t, "id")
+ account, err := osuser.Lookup(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ prev := packageResolverCommand
+ t.Cleanup(func() { packageResolverCommand = prev })
+ packageResolverCommand = func(ctx context.Context, _ string) *exec.Cmd { return helperResolver(ctx, "resolve-packages") }
+
+ npmrcIn := func(mode os.FileMode) string {
+ dir, err := os.MkdirTemp("", "beacon-npmrc-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = os.RemoveAll(dir) })
+ path := filepath.Join(dir, "npmrc")
+ if err := os.WriteFile(path, []byte("registry=https://registry.npmjs.org/\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(dir, mode); err != nil {
+ t.Fatal(err)
+ }
+ return path
+ }
+ resolve, err := packagesAsUser(account.UID, account.HomeDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, tc := range []struct {
+ npmrc string
+ private bool
+ }{
+ {npmrcIn(0o755), false},
+ {npmrcIn(0o700), true},
+ } {
+ env := launchpkg.RegistryEnv{Home: account.HomeDir, Environ: []string{"npm_config_userconfig=" + tc.npmrc}}
+ if root := launchpkg.ResolveAll(env, testQueries[:1]); root[0].Package.Private {
+ t.Fatalf("root read %s as private: %+v", tc.npmrc, root)
+ }
+ answers, err := resolve(env, testQueries[:1])
+ if err != nil {
+ t.Fatal(err)
+ }
+ if answers[0].Package.Private != tc.private {
+ t.Errorf("as %s, userconfig=%s: %+v, want private %v", name, tc.npmrc, answers[0], tc.private)
+ }
+ }
+}
diff --git a/cli/beacon/cmd/endpoint_inventory_packages_windows.go b/cli/beacon/cmd/endpoint_inventory_packages_windows.go
new file mode 100644
index 00000000..a909af24
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_inventory_packages_windows.go
@@ -0,0 +1,11 @@
+//go:build windows
+
+package cmd
+
+import "errors"
+
+// packagesAsUser is never reached on Windows, where the inventory scan is never confined
+// (confineInventoryScan confines only a root process).
+func packagesAsUser(int, string) (packageResolver, error) {
+ return nil, errors.New("resolving packages as another account is not supported on Windows")
+}
diff --git a/cli/beacon/internal/endpoint/inventory/inventory.go b/cli/beacon/internal/endpoint/inventory/inventory.go
index cb6f450b..29b26f3f 100644
--- a/cli/beacon/internal/endpoint/inventory/inventory.go
+++ b/cli/beacon/internal/endpoint/inventory/inventory.go
@@ -22,6 +22,8 @@ import (
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/harness"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/hermessession"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/launchpkg"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
)
@@ -80,7 +82,26 @@ type Options struct {
IncludeContents bool
// MaxContentBytes caps retained content per file. Zero uses DefaultMaxContentBytes.
MaxContentBytes int
-}
+ // LauncherEnv is where MCP servers' launchers look for registry and index settings beyond
+ // the scanned home's own config files: the environment and working directory they inherit,
+ // and whether the system's files count. Nil reads the home's and the system's files only,
+ // which is all a scheduled job, whose environment is not the user's shell, can know. Every
+ // inventory snapshot is scanned that way, so a server's package_registry does not depend on
+ // which command took the snapshot. Its Home is always the scanned home.
+ LauncherEnv *launchpkg.RegistryEnv
+ // ResolvePackages answers which package each server runs. The answer reads the launcher
+ // config the user chose (an npmrc's userconfig, a project, a server's PATH), so it must be
+ // read with that user's rights, never root's: the system job, which scans as root, passes one
+ // that runs as the console user. Nil resolves in this process, which a confined scan never
+ // does: there every package is held back as private.
+ ResolvePackages func(launchpkg.RegistryEnv, []launchpkg.Query) ([]launchpkg.Answer, error)
+}
+
+// PackageRegistry values: where a server's launcher fetches the package it runs.
+const (
+ PackageRegistryPublic = "public"
+ PackageRegistryPrivate = "private"
+)
type Result struct {
GeneratedAt string `json:"generated_at"`
@@ -139,11 +160,25 @@ type MCPServer struct {
ParserStatus string `json:"parser_status"`
Redaction string `json:"redaction"`
Definition map[string]interface{} `json:"definition,omitempty"`
- // ProjectDirs are the directories of the projects whose entry in a runtime's own config
+ // Package is the npm or PyPI package the server's launch command runs from the public
+ // registry, as Beacon Intel looks it up (npm:<name> or pypi:<name>, no version), and
+ // PackageRegistry is "public". When the command, its env or the launcher config the scan
+ // read points that ecosystem at another registry or index, PackageRegistry is "private" and
+ // Package is left out, since the name may be private too. Both are empty for anything else
+ // (a binary, a script, a remote URL).
+ Package string `json:"package,omitempty"`
+ PackageRegistry string `json:"package_registry,omitempty"`
+ // PrivatePackage names the package when PackageRegistry is "private". In memory only, for
+ // Beacon Intel's check by name, which the caller must opt into; never serialized.
+ PrivatePackage string `json:"-"`
+ // Launch is the redacted definition, kept whether or not contents are captured, so a reader
+ // such as Beacon Intel can tell which program a server runs without the record carrying its
+ // arguments. In memory only; never serialized.
+ Launch map[string]interface{} `json:"-"`
+ // projectDirs are the directories of the projects whose entry in a runtime's own config
// declares the server (Claude Code's ~/.claude.json projects.<path>.mcpServers), which the
- // runtime starts it in. In memory only, for readers such as Beacon Intel that must read the
- // config a launcher finds there; never serialized, so the inventory record is unchanged.
- ProjectDirs []string `json:"-"`
+ // runtime starts it in, so its launcher reads the config it finds there.
+ projectDirs []string
}
type candidate struct {
@@ -185,13 +220,75 @@ func Scan(opts Options) Result {
co := contentOptions{include: opts.IncludeContents, maxBytes: opts.MaxContentBytes}
for _, item := range filterCandidates(withoutProjectScope(candidates(home, wd), wd), opts.Runtimes) {
config, servers := inspectCandidate(item, redaction, co)
+ if item.scope == ScopeProject {
+ // The runtime starts a server its project's config declares in that project, so the
+ // launcher reads the project's own registry config.
+ for i := range servers {
+ if len(servers[i].projectDirs) == 0 {
+ servers[i].projectDirs = []string{wd}
+ }
+ }
+ }
result.Configs = append(result.Configs, config)
result.MCPServers = append(result.MCPServers, servers...)
}
+ resolvePackages(result.MCPServers, home, opts)
result.Skills = scanSkills(home, wd, redaction, opts.Runtimes, co)
return result
}
+// resolvePackages names the npm or PyPI package each server runs and where its launcher fetches
+// it from, with the home Scan resolved. A resolver that fails holds every package back as private:
+// a name Beacon could not check may be a private one.
+func resolvePackages(servers []MCPServer, home string, opts Options) {
+ if len(servers) == 0 {
+ return
+ }
+ env := launchpkg.RegistryEnv{System: true}
+ if opts.LauncherEnv != nil {
+ env = *opts.LauncherEnv
+ }
+ env.Home = home
+ queries := make([]launchpkg.Query, len(servers))
+ for i, s := range servers {
+ queries[i] = launchpkg.Query{Launch: s.Launch, ProjectDirs: s.projectDirs}
+ }
+ resolve := opts.ResolvePackages
+ if resolve == nil && !sessionfs.Confined(home) {
+ resolve = func(env launchpkg.RegistryEnv, queries []launchpkg.Query) ([]launchpkg.Answer, error) {
+ return launchpkg.ResolveAll(env, queries), nil
+ }
+ }
+ var answers []launchpkg.Answer
+ if resolve != nil {
+ if got, err := resolve(env, queries); err == nil && len(got) == len(queries) {
+ answers = got
+ }
+ }
+ for i := range servers {
+ if answers != nil {
+ if answers[i].OK {
+ servers[i].RecordPackage(answers[i].Package)
+ }
+ continue
+ }
+ if p, ok := launchpkg.FromCommand(launchpkg.Command(servers[i].Launch)); ok {
+ p.Private = true
+ servers[i].RecordPackage(p)
+ }
+ }
+}
+
+// RecordPackage records the package a server runs. A package from a private registry or index
+// keeps its name in memory only (PrivatePackage): the name may be private too.
+func (s *MCPServer) RecordPackage(p launchpkg.Package) {
+ if p.Private {
+ s.Package, s.PackageRegistry, s.PrivatePackage = "", PackageRegistryPrivate, p.Ref
+ return
+ }
+ s.Package, s.PackageRegistry, s.PrivatePackage = p.Ref, PackageRegistryPublic, ""
+}
+
// withoutProjectScope drops project-scoped candidates when there is no working directory to
// scope them to; otherwise they would resolve relative to the process cwd.
func withoutProjectScope(items []candidate, wd string) []candidate {
@@ -893,8 +990,8 @@ func serversFromProjects(item candidate, projects map[string]interface{}, redact
found := serversFromNestedMCPBlocks(item, nested, redaction, co)
if filepath.IsAbs(dir) {
for i := range found {
- if len(found[i].ProjectDirs) == 0 {
- found[i].ProjectDirs = []string{dir}
+ if len(found[i].projectDirs) == 0 {
+ found[i].projectDirs = []string{dir}
}
}
}
@@ -981,6 +1078,7 @@ func serverFromDefinition(item candidate, name string, def map[string]interface{
if command != "" {
server.CommandNameHash = hashString(filepath.Base(command))
}
+ server.Launch = redactedDef
if co.include {
server.Definition = redactedDef
}
@@ -1025,7 +1123,7 @@ func dedupeServers(servers []MCPServer) []MCPServer {
key := server.Runtime + "\x00" + server.SourcePathHash + "\x00" + server.ServerNameHash + "\x00" + server.DefinitionHash
if i, ok := seen[key]; ok {
// The same definition in several projects is one entry, started in each of them.
- out[i].ProjectDirs = mergeDirs(out[i].ProjectDirs, server.ProjectDirs)
+ out[i].projectDirs = mergeDirs(out[i].projectDirs, server.projectDirs)
continue
}
seen[key] = len(out)
diff --git a/cli/beacon/internal/endpoint/inventory/inventory_test.go b/cli/beacon/internal/endpoint/inventory/inventory_test.go
index c9484b28..737b0642 100644
--- a/cli/beacon/internal/endpoint/inventory/inventory_test.go
+++ b/cli/beacon/internal/endpoint/inventory/inventory_test.go
@@ -10,6 +10,8 @@ import (
"testing"
"time"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/launchpkg"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
)
@@ -881,6 +883,91 @@ func TestSkillScanFollowsSymlinkedSkillDirectories(t *testing.T) {
}
}
+func TestSkillIntelKeyComesFromTheSkillsCLILock(t *testing.T) {
+ home := t.TempDir()
+ work := t.TempDir()
+ agents := filepath.Join(home, ".agents", "skills")
+ for _, name := range []string{"frontend-design", "local-skill", "from-git", "sneaky"} {
+ writeFile(t, filepath.Join(agents, name, "SKILL.md"), "# "+name)
+ }
+ writeFile(t, filepath.Join(home, ".agents", ".skill-lock.json"), `{"version": 3, "skills": {
+ "frontend-design": {"source": "anthropics/skills", "sourceType": "github"},
+ "from-git": {"source": "https://git.example/x.git", "sourceType": "git"},
+ "sneaky": {"source": "../../etc/passwd", "sourceType": "github"}
+ }}`)
+ linkRoot := filepath.Join(home, ".claude", "skills")
+ if err := os.MkdirAll(linkRoot, 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(filepath.Join(agents, "frontend-design"), filepath.Join(linkRoot, "frontend-design")); err != nil {
+ t.Fatal(err)
+ }
+ // A repository's own skills, beside a lock it wrote claiming a known repository for them,
+ // directly and through a link from the home.
+ forged := `{"skills": {"frontend-design": {"source": "anthropics/skills", "sourceType": "github"}, "pdf": {"source": "anthropics/skills", "sourceType": "github"}}}`
+ writeFile(t, filepath.Join(work, ".claude", "skills", "frontend-design", "SKILL.md"), "# not the real one")
+ writeFile(t, filepath.Join(work, ".claude", ".skill-lock.json"), forged)
+ writeFile(t, filepath.Join(work, "vendor", "skills", "pdf", "SKILL.md"), "# not the real one")
+ writeFile(t, filepath.Join(work, "vendor", ".skill-lock.json"), forged)
+ if err := os.Symlink(filepath.Join(work, "vendor", "skills", "pdf"), filepath.Join(linkRoot, "pdf")); err != nil {
+ t.Fatal(err)
+ }
+
+ result := Scan(Options{HomeDir: home, WorkingDir: work, Runtimes: []string{"agent_skills", "claude_code"}, Now: fixedNow})
+
+ for _, tc := range []struct{ runtime, name, manifest, want string }{
+ {"agent_skills", "frontend-design", filepath.Join(agents, "frontend-design", "SKILL.md"), "skill:anthropics/skills#frontend-design"},
+ // Claude's copy links to the CLI's, so it carries the same key.
+ {"claude_code", "frontend-design", filepath.Join(linkRoot, "frontend-design", "SKILL.md"), "skill:anthropics/skills#frontend-design"},
+ {"agent_skills", "local-skill", filepath.Join(agents, "local-skill", "SKILL.md"), ""},
+ {"agent_skills", "from-git", filepath.Join(agents, "from-git", "SKILL.md"), ""},
+ {"agent_skills", "sneaky", filepath.Join(agents, "sneaky", "SKILL.md"), ""},
+ {"claude_code", "frontend-design", filepath.Join(work, ".claude", "skills", "frontend-design", "SKILL.md"), ""},
+ {"claude_code", "pdf", filepath.Join(linkRoot, "pdf", "SKILL.md"), ""},
+ } {
+ skill := findSkill(result.Skills, tc.runtime, tc.name, tc.manifest)
+ if skill == nil {
+ t.Fatalf("%s %s not found in %#v", tc.runtime, tc.name, result.Skills)
+ }
+ if skill.IntelKey != tc.want {
+ t.Errorf("%s %s intel key = %q, want %q", tc.runtime, tc.name, skill.IntelKey, tc.want)
+ }
+ }
+}
+
+// The record names the public package a server runs, never its other arguments or env; a package
+// from a private registry is named only in memory.
+func TestMCPServerRecordNamesItsPackageAndNothingElseOfItsLaunch(t *testing.T) {
+ home := t.TempDir()
+ writeFile(t, filepath.Join(home, ".claude.json"), `{"mcpServers": {
+ "supabase": {"command": "npx", "args": ["-y", "@supabase/mcp-server-supabase@latest", "--project-ref=abc"], "env": {"SUPABASE_ACCESS_TOKEN": "secret"}},
+ "billing": {"command": "npx", "args": ["--registry=https://npm.acme.internal", "-y", "@acme/billing-mcp"]}
+ }}`)
+
+ result := Scan(Options{HomeDir: home, SkipProjectScope: true, Runtimes: []string{"claude_code"}, Now: fixedNow, LauncherEnv: &launchpkg.RegistryEnv{}})
+
+ servers := map[string]MCPServer{}
+ for _, s := range result.MCPServers {
+ servers[s.ServerName] = s
+ }
+ supabase, billing := servers["supabase"], servers["billing"]
+ if supabase.Definition != nil || supabase.Package != "npm:@supabase/mcp-server-supabase" || supabase.PackageRegistry != PackageRegistryPublic {
+ t.Fatalf("supabase = %+v", supabase)
+ }
+ if billing.Package != "" || billing.PackageRegistry != PackageRegistryPrivate || billing.PrivatePackage != "npm:@acme/billing-mcp" {
+ t.Fatalf("billing = %+v", billing)
+ }
+ data, err := json.Marshal(result.MCPServers)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, leaked := range []string{"project-ref", "secret", "acme"} {
+ if strings.Contains(string(data), leaked) {
+ t.Fatalf("record carries %q: %s", leaked, data)
+ }
+ }
+}
+
func TestInventoryLogAndStatePathsFollowRuntimeLog(t *testing.T) {
runtimeLog := filepath.Join("/tmp", "beacon", "runtime.jsonl")
if got, want := LogPath(runtimeLog, true), filepath.Join("/tmp", "beacon", "inventory_state.jsonl"); got != want {
@@ -1443,8 +1530,8 @@ func TestScanFollowsPiAgentDirForTheUserExtension(t *testing.T) {
}
// Claude Code starts a local-scope server (~/.claude.json projects.<path>.mcpServers) in its
-// project, so the scan keeps that directory for in-memory readers, and keeps it out of the record.
-func TestClaudeProjectServersCarryTheirProjectInMemoryOnly(t *testing.T) {
+// project, so the scan keeps that directory to read the launcher config there.
+func TestClaudeProjectServersCarryTheirProject(t *testing.T) {
home := t.TempDir()
a, b, c := filepath.Join(home, "work", "proj-alpha"), filepath.Join(home, "work", "proj-beta"), filepath.Join(home, "work", "proj-gamma")
config, err := json.Marshal(map[string]interface{}{
@@ -1463,19 +1550,95 @@ func TestClaudeProjectServersCarryTheirProjectInMemoryOnly(t *testing.T) {
result := Scan(Options{HomeDir: home, SkipProjectScope: true, Runtimes: []string{"claude_code"}, Now: fixedNow, IncludeContents: true})
got := map[string][]string{}
for _, s := range result.MCPServers {
- got[s.ServerName] = s.ProjectDirs
- encoded, err := json.Marshal(s)
- if err != nil {
- t.Fatal(err)
- }
- if strings.Contains(string(encoded), "proj-") || strings.Contains(strings.ToLower(string(encoded)), "projectdirs") {
- t.Errorf("project directory serialized: %s", encoded)
- }
+ got[s.ServerName] = s.projectDirs
}
want := map[string][]string{"global": nil, "tool": {a, b}, "other": {c}, "rel": nil}
for name, dirs := range want {
if !slices.Equal(got[name], dirs) {
- t.Errorf("%s ProjectDirs = %v, want %v", name, got[name], dirs)
+ t.Errorf("%s projectDirs = %v, want %v", name, got[name], dirs)
}
}
}
+
+// A local-scope server's launcher reads its project's npmrc, so a scope that npmrc sends to a
+// private registry makes the package private however the scan was started.
+func TestScanResolvesPackagesWithTheProjectAServerRunsIn(t *testing.T) {
+ home := t.TempDir()
+ project := filepath.Join(home, "work", "acme")
+ writeFile(t, filepath.Join(project, ".npmrc"), "@acme:registry=https://npm.acme.internal/\n")
+ config, err := json.Marshal(map[string]interface{}{"projects": map[string]interface{}{
+ project: map[string]interface{}{"mcpServers": map[string]interface{}{
+ "tool": map[string]interface{}{"command": "npx", "args": []string{"-y", "@acme/secret-tool"}},
+ "public": map[string]interface{}{"command": "npx", "args": []string{"-y", "@playwright/mcp"}},
+ }},
+ }})
+ if err != nil {
+ t.Fatal(err)
+ }
+ writeFile(t, filepath.Join(home, ".claude.json"), string(config))
+ result := Scan(Options{HomeDir: home, SkipProjectScope: true, Runtimes: []string{"claude_code"}, Now: fixedNow, LauncherEnv: &launchpkg.RegistryEnv{}})
+ got := map[string][3]string{}
+ for _, s := range result.MCPServers {
+ got[s.ServerName] = [3]string{s.Package, s.PackageRegistry, s.PrivatePackage}
+ }
+ if got["public"] != [3]string{"npm:@playwright/mcp", PackageRegistryPublic, ""} ||
+ got["tool"] != [3]string{"", PackageRegistryPrivate, "npm:@acme/secret-tool"} {
+ t.Fatalf("packages = %v", got)
+ }
+}
+
+// A server a project's own config declares is started in that project, so its npmrc counts
+// however the scan was started.
+func TestScanResolvesProjectScopeServersWithTheProjectsConfig(t *testing.T) {
+ home, work := t.TempDir(), t.TempDir()
+ writeFile(t, filepath.Join(work, ".npmrc"), "@acme:registry=https://npm.acme.internal/\n")
+ writeFile(t, filepath.Join(work, ".cursor", "mcp.json"), `{"mcpServers": {"billing": {"command": "npx", "args": ["-y", "@acme/billing-mcp"]}}}`)
+ result := Scan(Options{HomeDir: home, WorkingDir: work, Runtimes: []string{"cursor"}, Now: fixedNow, LauncherEnv: &launchpkg.RegistryEnv{}})
+ if len(result.MCPServers) != 1 {
+ t.Fatalf("servers = %+v", result.MCPServers)
+ }
+ if s := result.MCPServers[0]; s.Package != "" || s.PackageRegistry != PackageRegistryPrivate || s.PrivatePackage != "npm:@acme/billing-mcp" {
+ t.Fatalf("billing = %+v", s)
+ }
+}
+
+// A package Beacon could not check may have a private name, so whenever the resolver cannot
+// answer, and whenever a confined scan has none to run as the user, every package is held back.
+func TestScanHoldsPackagesBackWithoutAnAnswer(t *testing.T) {
+ home := t.TempDir()
+ writeFile(t, filepath.Join(home, ".claude.json"), `{"mcpServers": {
+ "supabase": {"command": "npx", "args": ["-y", "@supabase/mcp-server-supabase"]},
+ "local": {"command": "node", "args": ["server.js"]}
+ }}`)
+ heldBack := func(t *testing.T, result Result) {
+ t.Helper()
+ for _, s := range result.MCPServers {
+ want := [3]string{"", PackageRegistryPrivate, "npm:@supabase/mcp-server-supabase"}
+ if s.ServerName == "local" {
+ want = [3]string{}
+ }
+ if got := [3]string{s.Package, s.PackageRegistry, s.PrivatePackage}; got != want {
+ t.Errorf("%s = %q, want %q", s.ServerName, got, want)
+ }
+ }
+ }
+ options := Options{HomeDir: home, SkipProjectScope: true, Runtimes: []string{"claude_code"}, Now: fixedNow}
+
+ var asked launchpkg.RegistryEnv
+ options.ResolvePackages = func(env launchpkg.RegistryEnv, queries []launchpkg.Query) ([]launchpkg.Answer, error) {
+ asked = env
+ return nil, os.ErrDeadlineExceeded
+ }
+ heldBack(t, Scan(options))
+ if asked.Home != home || !asked.System {
+ t.Errorf("resolver asked with %+v, want the scanned home and the system's files", asked)
+ }
+
+ options.ResolvePackages = nil
+ c, err := sessionfs.Confine(home, os.Getuid(), sessionfs.Options{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.Release()
+ heldBack(t, Scan(options))
+}
diff --git a/cli/beacon/internal/endpoint/inventory/skills.go b/cli/beacon/internal/endpoint/inventory/skills.go
index 620e0b9e..1b7f2828 100644
--- a/cli/beacon/internal/endpoint/inventory/skills.go
+++ b/cli/beacon/internal/endpoint/inventory/skills.go
@@ -1,9 +1,12 @@
package inventory
import (
+ "encoding/json"
"os"
"path/filepath"
+ "regexp"
"sort"
+ "strings"
"time"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/claudesession"
@@ -29,6 +32,10 @@ type Skill struct {
ModifiedAt string `json:"modified_at,omitempty"`
Redaction string `json:"redaction"`
Content *CapturedContent `json:"content,omitempty"`
+ // IntelKey is the skill's Beacon Intel entity key, skill:<owner>/<repo>#<name>: the GitHub
+ // repository the skills CLI (npx skills add) recorded installing it from in its lock file,
+ // and the name it installed it under. Empty when nothing records one.
+ IntelKey string `json:"intel_key,omitempty"`
}
type skillRoot struct {
@@ -49,8 +56,9 @@ func scanSkills(home, wd, redaction string, runtimes []string, co contentOptions
}
roots = kept
}
+ sources := newSkillSources(home)
for _, root := range filterSkillRoots(roots, runtimes) {
- skills = append(skills, inspectSkillRoot(root, redaction, co)...)
+ skills = append(skills, inspectSkillRoot(root, redaction, co, sources)...)
}
return dedupeSkills(skills)
}
@@ -96,7 +104,7 @@ func skillRoots(home, wd string) []skillRoot {
return out
}
-func inspectSkillRoot(root skillRoot, redaction string, co contentOptions) []Skill {
+func inspectSkillRoot(root skillRoot, redaction string, co contentOptions, sources *skillSources) []Skill {
base := Skill{
Runtime: root.runtime,
RootPath: valueForPath(root.path, redaction),
@@ -137,7 +145,11 @@ func inspectSkillRoot(root skillRoot, redaction string, co contentOptions) []Ski
if _, err := statPath(manifestPath); os.IsNotExist(err) {
continue
}
- skills = append(skills, inspectSkillManifest(root, entry.Name(), manifestPath, redaction, co))
+ skill := inspectSkillManifest(root, entry.Name(), manifestPath, redaction, co)
+ if skill.Exists {
+ skill.IntelKey = sources.intelKey(filepath.Join(root.path, entry.Name()))
+ }
+ skills = append(skills, skill)
}
if len(skills) == 0 {
return nil
@@ -213,3 +225,73 @@ func dedupeSkills(skills []Skill) []Skill {
})
return out
}
+
+// skillLockFile is where the skills CLI records what it installed into ~/.agents/skills.
+const skillLockFile = ".skill-lock.json"
+
+var githubRepo = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}$`)
+
+// skillSources is what the skills CLI recorded about the skills it installed into
+// ~/.agents/skills: the GitHub repository of each, by name, in ~/.agents/.skill-lock.json.
+//
+// Only that lock counts. A lock beside any other skills directory (<repo>/.claude/.skill-lock.json
+// for <repo>/.claude/skills, say) may be written by whoever wrote the skills, a cloned repository
+// included, and could name a known artifact's repository for a skill of its own, so Beacon Intel's
+// verdict for that artifact would be shown for it.
+type skillSources struct {
+ // dir is ~/.agents/skills with symlinks resolved, as a skill directory resolves.
+ dir string
+ lock string
+ loaded bool
+ repos map[string]string
+}
+
+func newSkillSources(home string) *skillSources {
+ agents := filepath.Join(home, ".agents")
+ dir := filepath.Join(agents, "skills")
+ if real, err := filepath.EvalSymlinks(dir); err == nil {
+ dir = real
+ }
+ return &skillSources{dir: dir, lock: filepath.Join(agents, skillLockFile)}
+}
+
+// intelKey is the Beacon Intel key of the skill in dir, when it is the skills CLI's copy in
+// ~/.agents/skills and the CLI recorded the GitHub repository it installed it from. Runtimes'
+// own skill directories usually link each skill to that copy, so the link is followed to it.
+func (s *skillSources) intelKey(dir string) string {
+ real, err := filepath.EvalSymlinks(dir)
+ if err != nil || filepath.Dir(real) != s.dir {
+ return ""
+ }
+ if !s.loaded {
+ s.repos, s.loaded = readSkillLock(s.lock), true
+ }
+ name := filepath.Base(real)
+ if repo := s.repos[name]; repo != "" {
+ return "skill:" + repo + "#" + name
+ }
+ return ""
+}
+
+func readSkillLock(path string) map[string]string {
+ data, err := readFilePath(path)
+ if err != nil {
+ return nil
+ }
+ var lock struct {
+ Skills map[string]struct {
+ Source string `json:"source"`
+ SourceType string `json:"sourceType"`
+ } `json:"skills"`
+ }
+ if json.Unmarshal(data, &lock) != nil {
+ return nil
+ }
+ repos := map[string]string{}
+ for name, entry := range lock.Skills {
+ if entry.SourceType == "github" && githubRepo.MatchString(entry.Source) && !strings.Contains(entry.Source, "..") {
+ repos[name] = entry.Source
+ }
+ }
+ return repos
+}
diff --git a/cli/beacon/internal/intel/installed.go b/cli/beacon/internal/intel/installed.go
index bf750917..08aab35d 100644
--- a/cli/beacon/internal/intel/installed.go
+++ b/cli/beacon/internal/intel/installed.go
@@ -1,23 +1,25 @@
package intel
import (
- "path/filepath"
"regexp"
"sort"
"strings"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/inventory"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/launchpkg"
)
// 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.
+// By default only identifiers the inventory recorded leave the machine: an npm or PyPI package
+// in a server's launch command and fetched from the public registry, and the Intel key of a skill
+// the skills CLI installed from GitHub (skill:<owner>/<repo>#<name>; Intel keeps nothing it is
+// asked, the repository included). 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 {
@@ -49,6 +51,7 @@ const (
BasisPrivatePyPI = "PyPI package from a private index in its launch command"
BasisServerName = "configured server name"
BasisSkillName = "skill name"
+ BasisSkillSource = "repository the skill was installed from, and its 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"
@@ -58,15 +61,18 @@ const (
ReasonNoName = "no name to look up"
)
+// IsPrivateBasis reports whether a lookup names a package fetched from a private registry or
+// index, which the index can only match against the public package sharing its name.
+func IsPrivateBasis(basis string) bool {
+ return basis == BasisPrivateNPM || basis == BasisPrivatePyPI
+}
+
// 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.
+ // its command names no package, a package from a private registry or index, and the name of
+ // a skill with no Intel key. Off by default, so only public packages and skill keys 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
// BeaconSkill reports whether a skill is one Beacon installed itself (an agentskills name
// in a directory carrying Beacon's marker), never checked. A skill that only shares the
// name is checked like any other.
@@ -76,17 +82,39 @@ type FromInventoryOptions struct {
// beaconServer reports whether a configured server is Beacon's own: the local `beacon` server
// (the beacon binary) or Beacon Cloud MCP (`beacon-managed`, a URL with no command). A server
// that only takes one of the names is checked like any other.
-func beaconServer(name, command string, args []string, s inventory.MCPServer) bool {
+func beaconServer(name string, s inventory.MCPServer) bool {
switch strings.ToLower(name) {
case "beacon":
- program, _ := launcher(command, args)
- return launcherBase(program) == "beacon"
+ return launchpkg.Program(s.Launch) == "beacon"
case "beacon-managed":
+ command, _ := launchpkg.Command(s.Launch)
return s.URLPresent && !s.CommandPresent && command == ""
}
return false
}
+// serverPackage is the package the scan found a server runs, and its basis.
+func serverPackage(s inventory.MCPServer) (q, basis string, ok bool) {
+ switch s.PackageRegistry {
+ case inventory.PackageRegistryPublic:
+ q = s.Package
+ case inventory.PackageRegistryPrivate:
+ q = s.PrivatePackage
+ }
+ private := s.PackageRegistry == inventory.PackageRegistryPrivate
+ switch {
+ case strings.HasPrefix(q, "npm:") && private:
+ return q, BasisPrivateNPM, true
+ case strings.HasPrefix(q, "npm:"):
+ return q, BasisNPM, true
+ case strings.HasPrefix(q, "pypi:") && private:
+ return q, BasisPrivatePyPI, true
+ case strings.HasPrefix(q, "pypi:"):
+ return q, BasisPyPI, true
+ }
+ return "", "", false
+}
+
// 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) {
@@ -100,7 +128,7 @@ func FromInventory(res inventory.Result, opts FromInventoryOptions) ([]Installed
item = &Installed{Kind: kind, Q: q, Basis: basis}
byKey[key] = item
order = append(order, key)
- } else if basis == BasisPrivateNPM || basis == BasisPrivatePyPI {
+ } else if IsPrivateBasis(basis) {
// One source fetching the package from a private registry or index makes every
// match a match by name for that source, so the private basis wins.
item.Basis = basis
@@ -116,17 +144,12 @@ func FromInventory(res inventory.Result, opts FromInventoryOptions) ([]Installed
for _, s := range res.MCPServers {
name := strings.TrimSpace(s.ServerName)
src := InstalledSource{Runtime: s.Runtime, Name: name, Scope: s.SourceScope}
- command, args := commandOf(s.Definition)
- if beaconServer(name, command, args, s) {
+ if beaconServer(name, s) {
skipped = append(skipped, Skipped{Kind: "mcp", Runtime: s.Runtime, Name: name, Reason: ReasonBeacon})
continue
}
- if q, basis, ok := PackageFromCommand(command, args); ok {
- program, programArgs := launcher(command, args)
- if registryFromEnv(s.Definition) || opts.Registries.forServer(program, programArgs, s.Definition, s.ProjectDirs).private(q) {
- basis = privateBasis(basis)
- }
- if (basis == BasisPrivateNPM || basis == BasisPrivatePyPI) && !opts.IncludePrivateNames {
+ if q, basis, ok := serverPackage(s); ok {
+ if IsPrivateBasis(basis) && !opts.IncludePrivateNames {
skipped = append(skipped, Skipped{Kind: "mcp", Runtime: s.Runtime, Name: name, Reason: ReasonPrivatePackage})
continue
}
@@ -153,6 +176,12 @@ func FromInventory(res inventory.Result, opts FromInventoryOptions) ([]Installed
skipped = append(skipped, Skipped{Kind: "skill", Runtime: s.Runtime, Name: name, Reason: ReasonBeacon})
continue
}
+ // The repository the skills CLI installed it from names the skill exactly; a name alone
+ // may match a different skill that shares it, and may be private.
+ if s.IntelKey != "" {
+ add("skill", s.IntelKey, BasisSkillSource, InstalledSource{Runtime: s.Runtime, Name: name, Scope: s.SourceScope})
+ continue
+ }
if !validName(name) {
skipped = append(skipped, Skipped{Kind: "skill", Runtime: s.Runtime, Name: name, Reason: ReasonNoName})
continue
@@ -197,301 +226,9 @@ func FromInventory(res inventory.Result, opts FromInventoryOptions) ([]Installed
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}$`)
-)
+// A name a person might give a server or skill: no paths, URLs, or whitespace runs.
+var 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
- }
- // npm exec and npm x read npm's options after the package too, up to --.
- return npmFrom(rest[1:], true)
- 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, false)
-}
-
-// 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. With optionsAnywhere (npm exec and npm x), the launcher's options run
-// past the first plain word up to --, so they are read there too: a registry or package flag
-// after the package still counts, and an unknown option still stops the parse.
-func packageArg(args []string, packageFlags, valueFlags, boolFlags, privateFlags map[string]bool, optionsAnywhere bool) (spec string, private, ok bool) {
- found, positional := false, false
- for i := 0; i < len(args); i++ {
- a := args[i]
- if a == "--" && optionsAnywhere {
- if !found && !positional && i+1 < len(args) {
- spec, positional = args[i+1], true
- }
- break
- }
- 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
- case positional:
- // A later plain word is an argument to the command.
- default:
- // The first plain word is the package, or the command a package flag's package
- // provides; for every launcher but npm exec, the launcher's options end here.
- if !found {
- spec = a
- }
- if !optionsAnywhere {
- return spec, private, true
- }
- positional = true
- }
- }
- return spec, private, found || positional
-}
-
-func npmFrom(args []string, optionsAnywhere bool) (string, string, bool) {
- spec, private, ok := packageArg(args, npmPackageFlags, npmValueFlags, npmBoolFlags, npmPrivateFlags, optionsAnywhere)
- 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, false)
- 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.go
index 2b894f2b..271c12a2 100644
--- a/cli/beacon/internal/intel/installed_test.go
+++ b/cli/beacon/internal/intel/installed_test.go
@@ -6,92 +6,20 @@ import (
"testing"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/inventory"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/launchpkg"
"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"},
- {"npm", []string{"exec", "[email protected]", "--yes"}, "npm:w"},
- {"npm", []string{"exec", "w", "--", "--port", "3000"}, "npm:w"},
- {"npm", []string{"x", "w", "positional-arg"}, "npm:w"},
- // npm exec reads its options after the package word, so --package there names the
- // package npm installs and the plain word is the command it provides.
- {"npm", []string{"exec", "bar", "--package=@scope/foo"}, "npm:@scope/foo"},
- {"npm", []string{"exec", "bar", "-p", "@scope/foo"}, "npm:@scope/foo"},
- {"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"}},
- // npm exec would read an option after the package as its own, so one Beacon does not
- // know still stops the parse there.
- {"npm", []string{"exec", "pkg", "--mystery", "value"}},
- {"npm", []string{"exec", "pkg", "--@acme:registry=https://npm.acme.internal"}},
- {"", nil},
- } {
- if q, _, ok := PackageFromCommand(tc.command, tc.args); ok {
- t.Errorf("PackageFromCommand(%q, %q) = %q, want no package", tc.command, tc.args, q)
- }
- }
-}
-
+// server is a configured server as the inventory scan leaves it: its launch definition, and the
+// package it runs as the scan resolved it with no launcher config of the machine's own.
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}
+ s := inventory.MCPServer{Runtime: runtime, ServerName: name, SourceScope: scope, Launch: def, URLPresent: hasURL, CommandPresent: hasCommand}
+ if p, ok := launchpkg.Resolve(def, nil, launchpkg.Registries{}); ok {
+ s.RecordPackage(p)
+ }
+ return s
}
func TestFromInventorySendsOnlyPublicIdentifiers(t *testing.T) {
@@ -173,50 +101,28 @@ func TestFromInventorySendsOnlyPublicIdentifiers(t *testing.T) {
}
}
-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},
- // npm exec reads a registry or config file named after the package too, up to --.
- {"npm", []string{"exec", "@acme/internal-mcp", "--registry=https://npm.acme.internal"}, "npm:@acme/internal-mcp", BasisPrivateNPM},
- {"npm", []string{"x", "@acme/internal-mcp", "--registry", "https://npm.acme.internal"}, "npm:@acme/internal-mcp", BasisPrivateNPM},
- {"npm", []string{"exec", "@acme/internal-mcp", "--userconfig", "/x/.npmrc"}, "npm:@acme/internal-mcp", BasisPrivateNPM},
- {"npm", []string{"exec", "bar", "--package=@acme/foo", "--registry=https://npm.acme.internal"}, "npm:@acme/foo", BasisPrivateNPM},
- // After -- the words are the command's, not npm's.
- {"npm", []string{"exec", "w", "--", "--registry=https://npm.acme.internal"}, "npm:w", BasisNPM},
- // npx stops at the package word: what follows is the command's.
- {"npx", []string{"-y", "pkg", "--registry=https://elsewhere.example"}, "npm:pkg", BasisNPM},
- {"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)
- }
+// A skill the skills CLI installed from GitHub is checked by default by its exact key; a skill
+// with only a name waits for consent.
+func TestFromInventoryChecksASkillByItsKey(t *testing.T) {
+ res := inventory.Result{Skills: []inventory.Skill{
+ {Runtime: "claude_code", SkillName: "frontend-design", SourceScope: "user", Exists: true, IntelKey: "skill:anthropics/skills#frontend-design"},
+ {Runtime: "agent_skills", SkillName: "frontend-design", SourceScope: "user", Exists: true, IntelKey: "skill:anthropics/skills#frontend-design"},
+ {Runtime: "claude_code", SkillName: "local", SourceScope: "user", Exists: true},
+ }}
+ items, skipped := FromInventory(res, FromInventoryOptions{})
+ if len(items) != 1 || items[0].Q != "skill:anthropics/skills#frontend-design" || items[0].Basis != BasisSkillSource || len(items[0].Sources) != 2 {
+ t.Fatalf("without consent: items %+v", items)
}
- if _, _, ok := PackageFromCommand("cmd", []string{"/c", "node", "server.js"}); ok {
- t.Error("cmd /c node was read as a package")
+ if len(skipped) != 1 || skipped[0].Name != "local" || skipped[0].Reason != ReasonPrivateSkill {
+ t.Fatalf("without consent: skipped %+v", skipped)
}
+ items, _ = FromInventory(res, FromInventoryOptions{IncludePrivateNames: true})
+ if len(items) != 2 || items[0].Q != "local" || items[0].Basis != BasisSkillName {
+ t.Fatalf("with consent = %+v", items)
+ }
+}
+func TestFromInventoryHoldsBackPrivatePackages(t *testing.T) {
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"}}),
}}
@@ -277,95 +183,6 @@ func TestFromInventoryKeepsThePrivateBasisWhicheverSourceComesFirst(t *testing.T
}
}
-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"}}),
diff --git a/cli/beacon/internal/launchpkg/command.go b/cli/beacon/internal/launchpkg/command.go
new file mode 100644
index 00000000..d77d5ed1
--- /dev/null
+++ b/cli/beacon/internal/launchpkg/command.go
@@ -0,0 +1,349 @@
+// Package launchpkg names the npm or PyPI package an MCP server's launch command runs, and tells
+// whether its launcher may fetch that package from somewhere other than the public registry or
+// index. The inventory scan records it, so a snapshot names a server the way Beacon Intel does
+// without carrying the server's arguments, and Beacon Intel's installed check reads the record.
+package launchpkg
+
+import (
+ "path/filepath"
+ "regexp"
+ "strings"
+)
+
+// Package is the npm or PyPI package a launch command runs.
+type Package struct {
+ // Ref names it as Beacon Intel looks it up: npm:<name> or pypi:<name>, without a version.
+ Ref string `json:"ref"`
+ // Private is set when the command, the server's env or its launcher's own configuration may
+ // fetch it from a registry or index other than the public one, or when Beacon could not read
+ // that configuration. Its name may then be private too.
+ Private bool `json:"private"`
+}
+
+// Resolve names the package a server's redacted definition runs. registries is what the
+// machine's launcher configuration says, and projectDirs are the directories the runtime starts
+// the server in (Claude Code's local scope), whose project config its launcher reads too.
+func Resolve(def map[string]interface{}, projectDirs []string, registries Registries) (Package, bool) {
+ command, args := Command(def)
+ p, ok := FromCommand(command, args)
+ if !ok {
+ return Package{}, false
+ }
+ program, programArgs := launcher(command, args)
+ if registryFromEnv(def) || registries.forServer(program, programArgs, def, projectDirs).private(p.Ref) {
+ p.Private = true
+ }
+ return p, true
+}
+
+// Query is one server's question: its redacted launch definition and the directories the runtime
+// starts it in.
+type Query struct {
+ Launch map[string]interface{} `json:"launch"`
+ ProjectDirs []string `json:"project_dirs,omitempty"`
+}
+
+// Answer is a Query's package; OK is false when its command runs none.
+type Answer struct {
+ Package Package `json:"package"`
+ OK bool `json:"ok"`
+}
+
+// ResolveAll answers each query against the launcher configuration env names, read once. It reads
+// that configuration with this process's own rights, so it must run as the user whose launchers
+// read it: see the inventory scan's ResolvePackages.
+func ResolveAll(env RegistryEnv, queries []Query) []Answer {
+ if len(queries) == 0 {
+ return nil
+ }
+ registries := LocalRegistries(env)
+ answers := make([]Answer, len(queries))
+ for i, q := range queries {
+ answers[i].Package, answers[i].OK = Resolve(q.Launch, q.ProjectDirs, registries)
+ }
+ return answers
+}
+
+// Command is a definition's command and its string arguments.
+func Command(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
+}
+
+// Program is the program a definition runs, by base name: lowercased, without .exe or .cmd, a
+// whole launch line in command split and a Windows cmd /c wrapper unwrapped.
+func Program(def map[string]interface{}) string {
+ program, _ := launcher(Command(def))
+ return launcherBase(program)
+}
+
+// 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])?$`)
+)
+
+// 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")
+}
+
+// FromCommand names the npm or PyPI package a launch command runs, from the command alone: it
+// is private only when the command itself names another registry or index. ok is false for
+// anything else: a local script, a binary, a container, or a command it cannot read with
+// confidence.
+func FromCommand(command string, args []string) (Package, 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 Package{}, false
+ }
+ rest = rest[1:]
+ case "npm":
+ if len(rest) == 0 || (rest[0] != "exec" && rest[0] != "x") {
+ return Package{}, false
+ }
+ // npm exec and npm x read npm's options after the package too, up to --.
+ return npmFrom(rest[1:], true)
+ case "uvx":
+ return pypiFrom(rest)
+ case "pipx":
+ if len(rest) == 0 || rest[0] != "run" {
+ return Package{}, false
+ }
+ return pypiFrom(rest[1:])
+ case "uv":
+ if len(rest) < 2 || rest[0] != "tool" || rest[1] != "run" {
+ return Package{}, false
+ }
+ return pypiFrom(rest[2:])
+ default:
+ return Package{}, false
+ }
+ return npmFrom(rest, false)
+}
+
+// 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. With optionsAnywhere (npm exec and npm x), the launcher's options run
+// past the first plain word up to --, so they are read there too: a registry or package flag
+// after the package still counts, and an unknown option still stops the parse.
+func packageArg(args []string, packageFlags, valueFlags, boolFlags, privateFlags map[string]bool, optionsAnywhere bool) (spec string, private, ok bool) {
+ found, positional := false, false
+ for i := 0; i < len(args); i++ {
+ a := args[i]
+ if a == "--" && optionsAnywhere {
+ if !found && !positional && i+1 < len(args) {
+ spec, positional = args[i+1], true
+ }
+ break
+ }
+ 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
+ case positional:
+ // A later plain word is an argument to the command.
+ default:
+ // The first plain word is the package, or the command a package flag's package
+ // provides; for every launcher but npm exec, the launcher's options end here.
+ if !found {
+ spec = a
+ }
+ if !optionsAnywhere {
+ return spec, private, true
+ }
+ positional = true
+ }
+ }
+ return spec, private, found || positional
+}
+
+func npmFrom(args []string, optionsAnywhere bool) (Package, bool) {
+ spec, private, ok := packageArg(args, npmPackageFlags, npmValueFlags, npmBoolFlags, npmPrivateFlags, optionsAnywhere)
+ if !ok {
+ return Package{}, false
+ }
+ ref, ok := npmPackage(spec)
+ return Package{Ref: ref, Private: private}, 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, 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, true
+}
+
+func pypiFrom(args []string) (Package, bool) {
+ spec, private, ok := packageArg(args, pypiPackageFlags, pypiValueFlags, pypiBoolFlags, pypiPrivateFlags, false)
+ if !ok {
+ return Package{}, false
+ }
+ ref, ok := pypiPackage(spec)
+ return Package{Ref: ref, Private: private}, 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, 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, true
+}
diff --git a/cli/beacon/internal/launchpkg/command_test.go b/cli/beacon/internal/launchpkg/command_test.go
new file mode 100644
index 00000000..e5969c8f
--- /dev/null
+++ b/cli/beacon/internal/launchpkg/command_test.go
@@ -0,0 +1,216 @@
+package launchpkg
+
+import "testing"
+
+func TestFromCommand(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"},
+ {"npm", []string{"exec", "[email protected]", "--yes"}, "npm:w"},
+ {"npm", []string{"exec", "w", "--", "--port", "3000"}, "npm:w"},
+ {"npm", []string{"x", "w", "positional-arg"}, "npm:w"},
+ // npm exec reads its options after the package word, so --package there names the
+ // package npm installs and the plain word is the command it provides.
+ {"npm", []string{"exec", "bar", "--package=@scope/foo"}, "npm:@scope/foo"},
+ {"npm", []string{"exec", "bar", "-p", "@scope/foo"}, "npm:@scope/foo"},
+ {"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 {
+ if p, ok := FromCommand(tc.command, tc.args); !ok || p.Ref != tc.want {
+ t.Errorf("FromCommand(%q, %q) = %+v, %v; want %q", tc.command, tc.args, p, ok, tc.want)
+ }
+ }
+ 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"}},
+ // npm exec would read an option after the package as its own, so one Beacon does not
+ // know still stops the parse there.
+ {"npm", []string{"exec", "pkg", "--mystery", "value"}},
+ {"npm", []string{"exec", "pkg", "--@acme:registry=https://npm.acme.internal"}},
+ {"", nil},
+ } {
+ if p, ok := FromCommand(tc.command, tc.args); ok {
+ t.Errorf("FromCommand(%q, %q) = %+v, want no package", tc.command, tc.args, p)
+ }
+ }
+}
+
+func TestPrivateRegistriesAndWindowsShells(t *testing.T) {
+ for _, tc := range []struct {
+ command string
+ args []string
+ want string
+ private bool
+ }{
+ {"npx", []string{"--registry", "https://npm.acme.internal", "-y", "@acme/billing-mcp"}, "npm:@acme/billing-mcp", true},
+ {"npx", []string{"--registry=https://npm.acme.internal", "@acme/billing-mcp"}, "npm:@acme/billing-mcp", true},
+ {"uvx", []string{"--index-url", "https://pypi.acme.internal/simple", "acme-billing-mcp"}, "pypi:acme-billing-mcp", true},
+ {"uvx", []string{"--extra-index-url=https://x.example/simple", "srv"}, "pypi:srv", true},
+ // 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", true},
+ {"uvx", []string{"--from=acme-billing-mcp", "--index=https://pypi.acme.internal/simple", "acme-billing"}, "pypi:acme-billing-mcp", true},
+ {"npx", []string{"-p", "@acme/mcp", "--registry", "https://npm.acme.internal", "acme-mcp"}, "npm:@acme/mcp", true},
+ {"npx", []string{"--package=@acme/mcp", "--registry=https://npm.acme.internal", "acme-mcp"}, "npm:@acme/mcp", true},
+ // npm exec reads a registry or config file named after the package too, up to --.
+ {"npm", []string{"exec", "@acme/internal-mcp", "--registry=https://npm.acme.internal"}, "npm:@acme/internal-mcp", true},
+ {"npm", []string{"x", "@acme/internal-mcp", "--registry", "https://npm.acme.internal"}, "npm:@acme/internal-mcp", true},
+ {"npm", []string{"exec", "@acme/internal-mcp", "--userconfig", "/x/.npmrc"}, "npm:@acme/internal-mcp", true},
+ {"npm", []string{"exec", "bar", "--package=@acme/foo", "--registry=https://npm.acme.internal"}, "npm:@acme/foo", true},
+ // After -- the words are the command's, not npm's.
+ {"npm", []string{"exec", "w", "--", "--registry=https://npm.acme.internal"}, "npm:w", false},
+ // npx stops at the package word: what follows is the command's.
+ {"npx", []string{"-y", "pkg", "--registry=https://elsewhere.example"}, "npm:pkg", false},
+ {"uvx", []string{"--from", "mcp-server-fetch", "mcp-server-fetch"}, "pypi:mcp-server-fetch", false},
+ // A config file or pip's own arguments can name an index or registry.
+ {"npx", []string{"--userconfig", "/x/.npmrc", "@acme/mcp"}, "npm:@acme/mcp", true},
+ {"uvx", []string{"--config-file", "/x/uv.toml", "acme-mcp"}, "pypi:acme-mcp", true},
+ {"pipx", []string{"run", "--pip-args=--index-url=https://pypi.acme.internal/simple", "acme-mcp"}, "pypi:acme-mcp", true},
+ {"cmd", []string{"/c", "npx", "-y", "@playwright/mcp"}, "npm:@playwright/mcp", false},
+ {"C:\\Windows\\System32\\cmd.exe", []string{"/C", "uvx", "mcp-server-fetch"}, "pypi:mcp-server-fetch", false},
+ {"cmd /c npx -y @playwright/mcp", nil, "npm:@playwright/mcp", false},
+ {"C:\\Program Files\\nodejs\\npx.cmd", []string{"-y", "pkg"}, "npm:pkg", false},
+ } {
+ if p, ok := FromCommand(tc.command, tc.args); !ok || p != (Package{Ref: tc.want, Private: tc.private}) {
+ t.Errorf("FromCommand(%q, %q) = %+v, %v; want %q private=%v", tc.command, tc.args, p, ok, tc.want, tc.private)
+ }
+ }
+ if _, ok := FromCommand("cmd", []string{"/c", "node", "server.js"}); ok {
+ t.Error("cmd /c node was read as a package")
+ }
+}
+
+func TestFromCommandRefusesSpecsOffTheRegistry(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 p, ok := FromCommand(tc.command, tc.args); ok {
+ t.Errorf("FromCommand(%q, %q) = %+v; want no package", tc.command, tc.args, p)
+ }
+ }
+ 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 p, ok := FromCommand(tc.command, tc.args); !ok || p.Ref != tc.want {
+ t.Errorf("FromCommand(%q, %q) = %+v, %v; want %q", tc.command, tc.args, p, ok, tc.want)
+ }
+ }
+}
+
+func TestResolveHoldsBackRegistriesFromTheServersEnv(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
+ }
+ if p, ok := Resolve(def, nil, Registries{}); !ok || p != (Package{Ref: tc.want, Private: true}) {
+ t.Errorf("%s: a package from a registry set in env = %+v, %v", tc.key, p, ok)
+ }
+ }
+ // An env file Beacon does not read may set one too.
+ envFile := map[string]interface{}{"command": "uvx", "args": []interface{}{"mcp-server-fetch"}, "envFile": "${workspaceFolder}/.env"}
+ if p, _ := Resolve(envFile, nil, Registries{}); !p.Private {
+ t.Errorf("a server with an envFile was public: %+v", p)
+ }
+ // Unrelated env keys, secrets included, leave a public package public.
+ gh := map[string]interface{}{
+ "command": "npx", "args": []interface{}{"-y", "@modelcontextprotocol/server-github"},
+ "env": map[string]interface{}{"GITHUB_TOKEN": "[REDACTED]", "NODE_ENV": "production"},
+ }
+ if p, ok := Resolve(gh, nil, Registries{}); !ok || p.Private {
+ t.Fatalf("a public package was held back: %+v", p)
+ }
+ // A scope the launcher config sends elsewhere is private; other scopes are not.
+ scoped := Registries{NPMScopes: map[string]bool{"@acme": true}}
+ if p, _ := Resolve(map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "@acme/billing-mcp"}}, nil, scoped); !p.Private {
+ t.Errorf("a package in a private scope was public: %+v", p)
+ }
+ if p, _ := Resolve(map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "@playwright/mcp"}}, nil, scoped); p.Private {
+ t.Errorf("a package in a public scope was private: %+v", p)
+ }
+}
diff --git a/cli/beacon/internal/intel/registries.go b/cli/beacon/internal/launchpkg/registries.go
similarity index 83%
rename from cli/beacon/internal/intel/registries.go
rename to cli/beacon/internal/launchpkg/registries.go
index 96f38887..f958ff08 100644
--- a/cli/beacon/internal/intel/registries.go
+++ b/cli/beacon/internal/launchpkg/registries.go
@@ -1,20 +1,24 @@
-package intel
+package launchpkg
import (
"bufio"
+ "errors"
"io"
+ "io/fs"
"os"
"path/filepath"
"regexp"
+ "runtime"
"strings"
+ "syscall"
)
// 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.
+// that npm scope) may be private, so Resolve marks it private like a --registry on the command
+// line.
type Registries struct {
// NPM is set when every npm package may come from another registry.
NPM bool
@@ -33,10 +37,10 @@ type Registries struct {
// 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
+ Home string `json:"home"`
+ WorkingDir string `json:"working_dir,omitempty"`
+ Environ []string `json:"environ,omitempty"`
+ System bool `json:"system"`
}
// CurrentRegistryEnv is this process's home, environment and working directory. An agent
@@ -69,7 +73,8 @@ func projectDirs(wd string) []string {
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.
+// A file that is not there counts as absent; one that is there but cannot be read holds its
+// ecosystem back (see unreadable). 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{}}
@@ -98,13 +103,27 @@ func LocalRegistries(env RegistryEnv) Registries {
if xdg == "" {
xdg = join(home, ".config")
}
- appData := getenv("APPDATA")
+ // Windows' per-user and machine config locations. A launcher reads them whatever environment
+ // Beacon's own job has, and a snapshot is scanned with none, so they are derived as Windows
+ // lays them out when the environment does not name them.
+ appData, localAppData, programData := getenv("APPDATA"), getenv("LOCALAPPDATA"), getenv("ProgramData")
system := func(path string) string {
if !env.System {
return ""
}
return path
}
+ if runtime.GOOS == "windows" {
+ if appData == "" {
+ appData = join(home, "AppData", "Roaming")
+ }
+ if localAppData == "" {
+ localAppData = join(home, "AppData", "Local")
+ }
+ if programData == "" {
+ programData = system(os.Getenv("ProgramData"))
+ }
+ }
// A config file or prefix the environment names is resolved as npm, pip and uv resolve it
// (${VAR}, ~, an absolute path). One Beacon cannot resolve is still read by the launcher, so
@@ -131,10 +150,14 @@ func LocalRegistries(env RegistryEnv) Registries {
// ships; npm derives both from the node it runs on (nvm, fnm, Volta and system installs each
// have their own).
npmrcs = append(npmrcs, join(envPath("npm_config_prefix", &reg.NPM), "etc", "npmrc"))
- npmrcs = append(npmrcs, nodeNpmrcs(filepath.SplitList(getenv("PATH")))...)
+ nodePaths, nodeUnsure := nodeNpmrcs(filepath.SplitList(getenv("PATH")))
+ npmrcs = append(npmrcs, nodePaths...)
+ if nodeUnsure {
+ reg.NPM = true
+ }
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"),
+ join(xdg, "pnpm", "rc"), join(home, "Library", "Preferences", "pnpm", "rc"), join(localAppData, "pnpm", "config", "rc"),
system("/usr/local/etc/npmrc"), system("/opt/homebrew/etc/npmrc"), join(appData, "npm", "etc", "npmrc")) {
reg.readNpmrc(path)
}
@@ -153,14 +176,14 @@ func LocalRegistries(env RegistryEnv) Registries {
for _, path := range []string{envPath("PIP_CONFIG_FILE", &reg.PyPI), 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")} {
+ join(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{envPath("UV_CONFIG_FILE", &reg.PyPI), 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")} {
+ system("/etc/uv/uv.toml"), system("/etc/xdg/uv/uv.toml"), join(programData, "uv", "uv.toml")} {
if registryLine(path, isPyPIIndexLine) {
reg.PyPI = true
}
@@ -178,30 +201,38 @@ func LocalRegistries(env RegistryEnv) Registries {
// 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 {
+// with symlinks resolved. unsure reports a node Beacon could not look up (see unreadable), whose
+// npm config it then cannot vouch for.
+func nodeNpmrcs(dirs []string) (paths []string, unsure bool) {
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() {
+ info, err := os.Stat(node)
+ if unreadable(err) {
+ return nil, true
+ }
+ if err != nil || info.IsDir() {
continue
}
+ real, err := filepath.EvalSymlinks(node)
+ if err != nil {
+ return nil, true
+ }
prefixes := []string{filepath.Dir(dir), dir}
- if real, err := filepath.EvalSymlinks(node); err == nil && real != node {
+ if 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 paths, false
}
}
- return nil
+ return nil, false
}
// readProject reads the project config npm, yarn, bun and uv find by walking up from dir.
@@ -271,11 +302,11 @@ func (r Registries) forServer(command string, args []string, def map[string]inte
unresolved = true
}
}
- npmrcs := nodeNpmrcs(nodeDirs)
- if len(npmrcs) == 0 && len(projects) == 0 && !unresolved {
+ npmrcs, nodeUnsure := nodeNpmrcs(nodeDirs)
+ if len(npmrcs) == 0 && len(projects) == 0 && !unresolved && !nodeUnsure {
return r
}
- out := Registries{NPM: r.NPM || unresolved, PyPI: r.PyPI || unresolved, NPMScopes: map[string]bool{}, home: r.home,
+ out := Registries{NPM: r.NPM || unresolved || nodeUnsure, 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
@@ -342,8 +373,11 @@ func (r *Registries) readNpmrc(path string) {
r.NPMScopes = map[string]bool{}
}
r.read[path] = true
- lines, ok := readConfigLines(path)
- if !ok {
+ lines, err := readConfigLines(path)
+ if unreadable(err) {
+ r.NPM = true
+ }
+ if err != nil {
return
}
for _, line := range lines {
@@ -488,9 +522,9 @@ func cutKeyValue(line string) (key, value string, ok bool) {
}
func registryLine(path string, match func(string) bool) bool {
- lines, ok := readConfigLines(path)
- if !ok {
- return false
+ lines, err := readConfigLines(path)
+ if unreadable(err) {
+ return true
}
for _, line := range lines {
if match(line) {
@@ -500,18 +534,20 @@ func registryLine(path string, match func(string) bool) bool {
return false
}
-// readConfigLines returns a config file's lines without blanks or comments.
-func readConfigLines(path string) ([]string, bool) {
+// readConfigLines returns a config file's lines without blanks or comments. It reads with this
+// process's own rights, which are the launcher user's (see ResolveAll).
+func readConfigLines(path string) ([]string, error) {
if path == "" {
- return nil, false
+ return nil, os.ErrNotExist
}
- f, err := os.Open(path)
+ // Non-blocking, so a FIFO is opened and turned down rather than waited on for a writer.
+ f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NONBLOCK, 0)
if err != nil {
- return nil, false
+ return nil, err
}
defer f.Close()
if info, err := f.Stat(); err != nil || !info.Mode().IsRegular() {
- return nil, false
+ return nil, &fs.PathError{Op: "read", Path: path, Err: errNotConfig}
}
var lines []string
scanner := bufio.NewScanner(io.LimitReader(f, maxRegistryConfigBytes))
@@ -523,5 +559,16 @@ func readConfigLines(path string) ([]string, bool) {
}
lines = append(lines, line)
}
- return lines, true
+ return lines, nil
+}
+
+var errNotConfig = errors.New("not a regular file")
+
+// unreadable reports a config lookup that failed for any reason but the file not being there. A
+// missing file is missing for the launcher too; anything else (a file the user may not read, a
+// directory a group they are in may enter but Beacon's lookup of their groups missed, macOS privacy
+// protection, a FIFO or a directory where a file should be) leaves Beacon unable to tell what the
+// launcher reads, so its ecosystem is held back as private.
+func unreadable(err error) bool {
+ return err != nil && !errors.Is(err, fs.ErrNotExist) && !errors.Is(err, syscall.ENOTDIR)
}
diff --git a/cli/beacon/internal/intel/registries_test.go b/cli/beacon/internal/launchpkg/registries_test.go
similarity index 81%
rename from cli/beacon/internal/intel/registries_test.go
rename to cli/beacon/internal/launchpkg/registries_test.go
index 089ac794..0d366f25 100644
--- a/cli/beacon/internal/intel/registries_test.go
+++ b/cli/beacon/internal/launchpkg/registries_test.go
@@ -1,13 +1,10 @@
-package intel
+package launchpkg
import (
- "encoding/json"
"os"
"path/filepath"
"strings"
"testing"
-
- "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/inventory"
)
func writeConfig(t *testing.T, path, content string) {
@@ -201,9 +198,8 @@ func TestRegistriesForAServerOnItsOwnNode(t *testing.T) {
"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)
+ if p, ok := Resolve(def, nil, base); !ok || !p.Private {
+ t.Errorf("%s: a server on its own nvm node was not held back: %+v", name, p)
}
}
}
@@ -225,17 +221,17 @@ func TestRegistriesForAServerRunInAnotherDirectory(t *testing.T) {
{"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)
+ if p, ok := Resolve(tc.def, nil, base); !ok || !p.Private {
+ t.Errorf("%s: %s was not held back: %+v", tc.name, tc.q, p)
}
}
// 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)
+ if p, ok := Resolve(map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "@playwright/mcp"}, "cwd": work}, nil, base); !ok || p.Private {
+ t.Fatalf("a plain cwd held a public package back: %+v", p)
+ }
+ // The project a runtime starts the server in is read too (Claude Code's local scope).
+ if p, _ := Resolve(map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "@acme/tools"}}, []string{acme}, base); !p.Private {
+ t.Errorf("the project the server runs in was not read: %+v", p)
}
}
@@ -309,55 +305,3 @@ func TestLocalRegistriesSkipsProjectFilesWithoutAWorkingDirectory(t *testing.T)
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)
- }
-}
-
-// Claude Code starts a local-scope server in its project, so npx there reads the project's
-// npmrc whatever directory the agent asking runs in.
-func TestFromInventoryReadsTheProjectAClaudeLocalServerRunsIn(t *testing.T) {
- home := t.TempDir()
- project := filepath.Join(home, "work", "acme")
- writeConfig(t, filepath.Join(project, ".npmrc"), "@acme:registry=https://npm.acme.internal/\n")
- config, err := json.Marshal(map[string]interface{}{"projects": map[string]interface{}{
- project: map[string]interface{}{"mcpServers": map[string]interface{}{
- "tool": map[string]interface{}{"command": "npx", "args": []string{"-y", "@acme/secret-tool"}},
- "public": map[string]interface{}{"command": "npx", "args": []string{"-y", "@playwright/mcp"}},
- }},
- }})
- if err != nil {
- t.Fatal(err)
- }
- writeConfig(t, filepath.Join(home, ".claude.json"), string(config))
- inv := inventory.Scan(inventory.Options{HomeDir: home, SkipProjectScope: true, Runtimes: []string{"claude_code"}, IncludeContents: true})
- // The agent asks from somewhere else entirely.
- reg := LocalRegistries(RegistryEnv{Home: home, WorkingDir: t.TempDir()})
- items, skipped := FromInventory(inv, FromInventoryOptions{Registries: reg})
- var sent []string
- for _, item := range items {
- sent = append(sent, item.Q)
- }
- if strings.Join(sent, ",") != "npm:@playwright/mcp" {
- t.Fatalf("sent = %v, skipped = %+v", sent, skipped)
- }
- if len(skipped) != 1 || skipped[0].Name != "tool" || skipped[0].Reason != ReasonPrivatePackage {
- t.Fatalf("skipped = %+v", skipped)
- }
-}
diff --git a/cli/beacon/internal/launchpkg/registries_unix_test.go b/cli/beacon/internal/launchpkg/registries_unix_test.go
new file mode 100644
index 00000000..59d1cd1e
--- /dev/null
+++ b/cli/beacon/internal/launchpkg/registries_unix_test.go
@@ -0,0 +1,70 @@
+//go:build !windows
+
+package launchpkg
+
+import (
+ "os"
+ "path/filepath"
+ "syscall"
+ "testing"
+ "time"
+)
+
+// Launcher config is read with the launcher user's rights. A file that is not there is not there for
+// the launcher either; anything Beacon cannot read for another reason, it cannot vouch for, so the
+// ecosystem is held back as private. A FIFO is turned down without waiting for a writer.
+func TestUnreadableLauncherConfigHoldsTheEcosystemBack(t *testing.T) {
+ home, outside := t.TempDir(), t.TempDir()
+ fifo := filepath.Join(outside, "fifo")
+ if err := syscall.Mkfifo(fifo, 0o600); err != nil {
+ t.Skipf("mkfifo: %v", err)
+ }
+ public := filepath.Join(outside, "public-npmrc")
+ writeConfig(t, public, "registry=https://registry.npmjs.org/\n")
+ locked := filepath.Join(outside, "locked")
+ writeConfig(t, filepath.Join(locked, "npmrc"), "registry=https://registry.npmjs.org/\n")
+ writeConfig(t, filepath.Join(locked, "bin", "node"), "")
+ if err := os.Chmod(locked, 0); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = os.Chmod(locked, 0o700) })
+
+ read := func(npmrc string) Registries {
+ t.Helper()
+ writeConfig(t, filepath.Join(home, ".npmrc"), npmrc)
+ done := make(chan Registries, 1)
+ go func() { done <- LocalRegistries(RegistryEnv{Home: home}) }()
+ select {
+ case reg := <-done:
+ return reg
+ case <-time.After(5 * time.Second):
+ t.Fatal("reading registry config blocked on a FIFO")
+ return Registries{}
+ }
+ }
+ cases := map[string]bool{
+ fifo: true,
+ outside: true,
+ public: false,
+ filepath.Join(outside, "missing"): false,
+ }
+ if os.Geteuid() != 0 {
+ // Root enters any directory.
+ cases[filepath.Join(locked, "npmrc")] = true
+ cases[filepath.Join(locked, "missing")] = true
+ }
+ for path, private := range cases {
+ if reg := read("userconfig=" + path + "\n"); reg.NPM != private {
+ t.Errorf("userconfig=%s: npm private = %v, want %v", path, reg.NPM, private)
+ }
+ }
+
+ // A server's own node is looked up the same way.
+ reg := read("")
+ if reg.forServer(filepath.Join(outside, "nowhere", "npx"), nil, map[string]interface{}{}, nil).NPM {
+ t.Error("a server run from a directory that is not there held npm back")
+ }
+ if os.Geteuid() != 0 && !reg.forServer(filepath.Join(locked, "bin", "npx"), nil, map[string]interface{}{}, nil).NPM {
+ t.Error("a server whose node could not be looked up left npm public")
+ }
+}
diff --git a/cli/beacon/internal/launchpkg/registries_windows_test.go b/cli/beacon/internal/launchpkg/registries_windows_test.go
new file mode 100644
index 00000000..7df4c8d6
--- /dev/null
+++ b/cli/beacon/internal/launchpkg/registries_windows_test.go
@@ -0,0 +1,24 @@
+//go:build windows
+
+package launchpkg
+
+import (
+ "path/filepath"
+ "testing"
+)
+
+// A snapshot is scanned with no environment, yet the launcher still reads the user's config under
+// AppData, so Beacon derives those locations from the home; an environment that names them wins.
+func TestLocalRegistriesReadsAppDataWithoutTheEnvironment(t *testing.T) {
+ home := t.TempDir()
+ writeConfig(t, filepath.Join(home, "AppData", "Roaming", "pip", "pip.ini"), "[global]\nindex-url = https://pypi.acme.internal/simple\n")
+ writeConfig(t, filepath.Join(home, "AppData", "Local", "pnpm", "config", "rc"), "registry=https://npm.acme.internal/\n")
+ if reg := LocalRegistries(RegistryEnv{Home: home}); !reg.PyPI || !reg.NPM {
+ t.Errorf("AppData config with no environment: %+v, want npm and PyPI private", reg)
+ }
+ elsewhere := t.TempDir()
+ env := RegistryEnv{Home: home, Environ: []string{"APPDATA=" + elsewhere, "LOCALAPPDATA=" + elsewhere}}
+ if reg := LocalRegistries(env); reg.PyPI || reg.NPM {
+ t.Errorf("AppData named elsewhere by the environment: %+v, want the home's AppData unread", reg)
+ }
+}
diff --git a/cli/beacon/internal/mcpserver/intel_tools.go b/cli/beacon/internal/mcpserver/intel_tools.go
index e6787317..50bc4e1a 100644
--- a/cli/beacon/internal/mcpserver/intel_tools.go
+++ b/cli/beacon/internal/mcpserver/intel_tools.go
@@ -11,6 +11,7 @@ import (
"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/launchpkg"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/intelapi"
)
@@ -27,8 +28,11 @@ func defaultIntelClient() (*intelapi.Client, error) {
return intel.New("beacon-mcp/" + version.GetVersion() + " (+https://beacon.sh)")
}
+// defaultInventory scans what the agent asking has configured. The agent starts every launcher
+// with this process's environment and in its project, so their registry settings apply too.
func defaultInventory(includeProject bool) inventory.Result {
- opts := inventory.Options{IncludeContents: true, SkipProjectScope: !includeProject}
+ env := launchpkg.CurrentRegistryEnv()
+ opts := inventory.Options{SkipProjectScope: !includeProject, LauncherEnv: &env}
if includeProject {
if wd, err := os.Getwd(); err == nil {
opts.WorkingDir = wd
@@ -110,8 +114,8 @@ func (s *Server) registerIntelTools() {
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. " +
+ "Beacon reads each runtime's own config (Claude Code, Cursor, Codex, and the rest Beacon supports) and by default sends only identifiers it can read exactly: npm and PyPI packages, from the public registries, named in a server's launch command, and the skill:<owner>/<repo>#<name> key of a skill the skills CLI installed from GitHub. " +
+ "Names that may be private (a server's configured name, a package from a private registry or index, the name of any other skill) 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(),
@@ -121,7 +125,7 @@ func (s *Server) registerIntelTools() {
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_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 the names of skills with no GitHub source. 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)
@@ -195,13 +199,8 @@ func (s *Server) checkInstalled(ctx context.Context, args map[string]interface{}
} 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()),
BeaconSkill: beaconSkill(agentskills.Names()),
})
report := installedReport{Sent: make([]intelapi.CheckItem, len(items)), Skipped: skipped}
@@ -249,7 +248,7 @@ func (s *Server) checkInstalled(ctx context.Context, args map[string]interface{}
// A package from a private registry or index is matched against the public package
// that shares its name, which may be a different artifact too.
byName := item.Basis == intel.BasisSkillName || item.Basis == intel.BasisServerName ||
- item.Basis == intel.BasisPrivateNPM || item.Basis == intel.BasisPrivatePyPI || outcome.MatchedBy == "text"
+ intel.IsPrivateBasis(item.Basis) || outcome.MatchedBy == "text"
if outcome.Status == "matched" && byName {
result.NameOnly = true
result.Guidance = nameOnlyGuidance + result.Guidance
diff --git a/cli/beacon/internal/mcpserver/intel_tools_test.go b/cli/beacon/internal/mcpserver/intel_tools_test.go
index 53e0ee60..48d07bcb 100644
--- a/cli/beacon/internal/mcpserver/intel_tools_test.go
+++ b/cli/beacon/internal/mcpserver/intel_tools_test.go
@@ -16,6 +16,7 @@ import (
"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/launchpkg"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/intelapi"
)
@@ -52,12 +53,19 @@ func newIntelServer(t *testing.T, answer func(path, body string) (int, string))
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{} }
+// scannedServer is a configured server as the inventory scan leaves it, resolved with no launcher
+// configuration of the machine's own.
+func scannedServer(runtime, name string, def map[string]interface{}) inventory.MCPServer {
+ _, hasCommand := def["command"]
+ s := inventory.MCPServer{Runtime: runtime, ServerName: name, SourceScope: "user", CommandPresent: hasCommand, Launch: def}
+ if p, ok := launchpkg.Resolve(def, nil, launchpkg.Registries{}); ok {
+ s.RecordPackage(p)
+ }
+ return s
+}
func call(t *testing.T, s *Server, name string, args map[string]interface{}) (string, bool) {
t.Helper()
@@ -163,7 +171,6 @@ func TestIntelCheckSendsStringsAndObjects(t *testing.T) {
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}}}
}
@@ -195,16 +202,12 @@ func fakeInventory(nServers int) inventory.Result {
},
}
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"}}},
+ scannedServer("claude_code", "private-db", map[string]interface{}{"command": "node", "args": []interface{}{"/Users/me/acme/db.js"}, "env": map[string]interface{}{"DB_PASSWORD": "hunter2"}}),
+ scannedServer("cursor", "beacon", 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"}},
- })
+ res.MCPServers = append(res.MCPServers,
+ scannedServer("claude_code", fmt.Sprintf("s%d", i), map[string]interface{}{"command": "npx", "args": []interface{}{"-y", fmt.Sprintf("pkg-%02d@latest", i), "--api-key", "sk-live-secret"}}))
}
return res
}
@@ -410,19 +413,20 @@ func TestIntelCheckInstalledRefusesMalformedArguments(t *testing.T) {
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)
+ for path, content := range map[string]string{
+ ".npmrc": "@acme:registry=https://npm.acme.internal/\n",
+ ".cursor/mcp.json": `{"mcpServers": {"billing": {"command": "npx", "args": ["-y", "@acme/billing-mcp"]}, "playwright": {"command": "npx", "args": ["-y", "@playwright/mcp"]}}}`,
+ } {
+ if err := os.MkdirAll(filepath.Dir(filepath.Join(home, path)), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(home, path), []byte(content), 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.
+ return inventory.Scan(inventory.Options{HomeDir: home, SkipProjectScope: true, Runtimes: []string{"cursor"}, LauncherEnv: &launchpkg.RegistryEnv{}})
+ }
text, isErr := call(t, s, "intel_check_installed", map[string]interface{}{"dry_run": true, "include_project": false})
if isErr {
t.Fatal(text)
@@ -452,11 +456,11 @@ func TestIntelCheckInstalledMarksNameMatches(t *testing.T) {
})
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"}}},
+ MCPServers: []inventory.MCPServer{
+ scannedServer("cursor", "x", map[string]interface{}{"command": "npx", "args": []interface{}{"-y", "some-mcp"}}),
// A package from a private registry matched the public package of the same name.
- {Runtime: "cursor", ServerName: "y", SourceScope: "user", CommandPresent: true,
- Definition: map[string]interface{}{"command": "npx", "args": []interface{}{"--registry", "https://npm.corp.example", "-y", "internal-tool"}}}},
+ scannedServer("cursor", "y", map[string]interface{}{"command": "npx", "args": []interface{}{"--registry", "https://npm.corp.example", "-y", "internal-tool"}}),
+ },
Skills: []inventory.Skill{{Runtime: "claude_code", SkillName: "pdf", SourceScope: "user", Exists: true}},
}
}
diff --git a/cli/beacon/internal/mcpserver/server.go b/cli/beacon/internal/mcpserver/server.go
index d12bc02d..d0bc6b55 100644
--- a/cli/beacon/internal/mcpserver/server.go
+++ b/cli/beacon/internal/mcpserver/server.go
@@ -18,7 +18,6 @@ import (
"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"
@@ -38,11 +37,9 @@ type Server struct {
logPath string
tools map[string]Tool
order []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
+ // newIntel and inventory replace the Beacon Intel client and the inventory scan in tests.
+ newIntel func() (*intelapi.Client, error)
+ inventory func(includeProject bool) inventory.Result
}
type Tool struct {
diff --git a/cli/beacon/internal/osuser/groups_test.go b/cli/beacon/internal/osuser/groups_test.go
new file mode 100644
index 00000000..8af9f278
--- /dev/null
+++ b/cli/beacon/internal/osuser/groups_test.go
@@ -0,0 +1,42 @@
+package osuser
+
+import (
+ "context"
+ "errors"
+ "slices"
+ "testing"
+)
+
+// GroupIDs is the credential a process run as the account carries, so an answer it cannot read
+// fully must fail rather than return fewer groups than it parsed.
+func TestGroupIDs(t *testing.T) {
+ prev := runID
+ t.Cleanup(func() { runID = prev })
+ for _, tc := range []struct {
+ out string
+ err error
+ want []uint32
+ failed bool
+ }{
+ {out: "20 12 61 701\n", want: []uint32{20, 12, 61, 701}},
+ {out: "1000\n", want: []uint32{1000}},
+ {out: "4294967294\n", want: []uint32{4294967294}},
+ {out: "4294967296\n", failed: true},
+ {out: "-2\n", failed: true},
+ {out: "", failed: true},
+ {out: "20 staff\n", failed: true},
+ {err: errors.New("no such user"), failed: true},
+ } {
+ runID = func(context.Context, int) (string, error) { return tc.out, tc.err }
+ got, err := GroupIDs(501)
+ if tc.failed {
+ if err == nil {
+ t.Errorf("GroupIDs with %q, %v = %v, want an error", tc.out, tc.err, got)
+ }
+ continue
+ }
+ if err != nil || !slices.Equal(got, tc.want) {
+ t.Errorf("GroupIDs with %q = %v, %v; want %v", tc.out, got, err, tc.want)
+ }
+ }
+}
diff --git a/cli/beacon/internal/osuser/osuser.go b/cli/beacon/internal/osuser/osuser.go
index 521c91b0..d57fb4d6 100644
--- a/cli/beacon/internal/osuser/osuser.go
+++ b/cli/beacon/internal/osuser/osuser.go
@@ -138,3 +138,38 @@ func parseAccountRecord(out, want string) (Info, error) {
}
return Info{}, fmt.Errorf("no usable account record for %q", want)
}
+
+// GroupIDs are the groups of the account with uid, its primary group first, as the system's id(1)
+// reports them: id consults NSS and macOS's directory service, which the CGO-free os/user never
+// does. They are the groups a process run as that account should carry, as the kernel's 32-bit
+// ids.
+func GroupIDs(uid int) ([]uint32, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), lookupTimeout)
+ defer cancel()
+ out, err := runID(ctx, uid)
+ if err != nil {
+ return nil, fmt.Errorf("id -G %d: %w", uid, err)
+ }
+ var gids []uint32
+ for _, field := range strings.Fields(out) {
+ gid, err := strconv.ParseUint(field, 10, 32)
+ if err != nil {
+ return nil, fmt.Errorf("id -G %d printed %q", uid, strings.TrimSpace(out))
+ }
+ gids = append(gids, uint32(gid))
+ }
+ if len(gids) == 0 {
+ return nil, fmt.Errorf("id -G %d printed no groups", uid)
+ }
+ return gids, nil
+}
+
+// runID is a var for the same reason runGetent is.
+var runID = func(ctx context.Context, uid int) (string, error) {
+ path, err := exec.LookPath("id")
+ if err != nil {
+ return "", fmt.Errorf("id is not available: %w", err)
+ }
+ out, err := exec.CommandContext(ctx, path, "-G", strconv.Itoa(uid)).Output()
+ return string(out), err
+}
diff --git a/docs/changelog/cli.mdx b/docs/changelog/cli.mdx
index 9cccfaf1..f9aa9f89 100644
--- a/docs/changelog/cli.mdx
+++ b/docs/changelog/cli.mdx
@@ -13,6 +13,8 @@ Stay up to date with the latest changes to the Agent Beacon CLI.
Changes on `main` since v1.3.60. They ship in the next release.
+- **Inventory names each MCP server's package and each skill's source** · An inventory snapshot knew an MCP server or skill only by its configured name, which several Beacon Intel artifacts can share. Each MCP server record now carries `package` (`npm:<name>` or `pypi:<name>`, no version) and `package_registry` `public` when its launch command runs a package from the public registry. When the command, the server's env, or the npm, pip or uv configuration in the home, the system's locations or the project a server runs in points that ecosystem elsewhere, `package_registry` is `private` and the name stays off the record. On Windows that configuration includes the per-user `AppData` and machine `ProgramData` locations even when the scanning job's environment does not name them. A skill the skills CLI (`npx skills add`) installed from GitHub carries `intel_key`, `skill:<owner>/<repo>#<name>`, from the CLI's `~/.agents/.skill-lock.json`; a lock beside a repository's own skills is ignored, since the repository could claim any source. The system inventory job runs as root, so it reads that configuration in a short-lived child process running as the console user with their groups: what the user's own launchers cannot read, Beacon does not either, and a snapshot never reflects a file only root can see. Configuration that exists but cannot be read (a file or folder the user may not open, a folder macOS privacy protection guards, a FIFO) holds its ecosystem back as `private`. `intel_check_installed` now checks such a skill by default, by its exact key; other skills still go by name only with `include_private_names`. Every endpoint sends one fresh snapshot after upgrading.
+
## November 2026
### v1.3.60 · November 11, 2026
diff --git a/docs/cli/intel.mdx b/docs/cli/intel.mdx
index c521889d..a5f49bc1 100644
--- a/docs/cli/intel.mdx
+++ b/docs/cli/intel.mdx
@@ -160,6 +160,10 @@ Beacon does not recognize is skipped rather than guessed at, so an option's valu
as a package. `npm exec` and `npm x` read npm's options after the package too (up to `--`), so
Beacon reads them there as well. 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.
+A skill the skills CLI (`npx skills add`) installed from GitHub is sent by its exact key,
+`skill:<owner>/<repo>#<name>`, read from the CLI's `~/.agents/.skill-lock.json`. A lock beside a
+repository's own skills is ignored: the repository wrote it and could claim any source. The
+repository may be private; Beacon Intel keeps nothing it is asked.
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:
@@ -178,7 +182,7 @@ Names that may be private are held back and listed as skipped unless the agent p
`.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.
+- the names of other skills, 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: the `beacon` server that runs the `beacon` binary, the `beacon-managed`
diff --git a/docs/cli/mcp.mdx b/docs/cli/mcp.mdx
index e71cb863..66a21b50 100644
--- a/docs/cli/mcp.mdx
+++ b/docs/cli/mcp.mdx
@@ -85,9 +85,10 @@ rather 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,
+`intel_check_installed` sends only identifiers it reads exactly from each runtime's own
+config: npm and PyPI packages, from the public registries, in a server's launch command, and the
+`skill:<owner>/<repo>#<name>` key of a skill the skills CLI installed from GitHub. Server names,
+private-registry packages and other skills' 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.