Skip to content

About

cynosure - offline, LLM-free, dependency-free retrieval-visibility auditor for the agent TOOL-SEARCH plane: which tools a deferred-loading catalog can actually surface, which get captured, and the exact word-count it takes to flip a ranking

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

Development Experiment 044 — cynosure

A retrieval-visibility auditor for agent tool catalogs under deferred tool loading. Offline, LLM-free, dependency-free (pure stdlib).

cynosure reimplements the lexical retrievers that tool-search actually ships (BM25 and regex), replays your tool catalog through them, and answers three questions that no manifest auditor can ask — because all of them are properties of a ranking, not of a tool:

  • Eclipse — is this tool retrievable at all, even by a query built from its own most distinctive words?
  • Margin — how many words must a competing card gain to capture a query that belongs to someone else? Reported as an exact integer.
  • Blind selection — does the card, the only text the model sees when it decides which tool to load, disclose the hazard the annotations declare?

Thesis

Deferred tool loading changed what a tool catalog is. When every tool sat in context, a manifest was a list the model could read; auditing it meant reading it too. Under defer_loading: true the model sees almost none of its tools. It sees a search box. A ranking function — BM25 or a regex match, running before the model gets a turn — decides which entries the model ever learns exist.

Nothing audits that function. The 2026 literature attacks it (ToolFlood pushes benign tools out of top-k with ~95% success at a 1% poisoning rate) and proposes learned defences against it (risk-aware rerankers), but both need a model in the loop. Meanwhile the retriever that ships by default is BM25 — a closed-form scoring function over a fixed corpus. That means every question about it is decidable offline: not estimated, not sampled, computed.

cynosure is the smallest thing that proves the point. Given a catalog and a retriever profile it derives a probe per tool, replays the rankings, and reports what the retrieval layer hides, who captures whose queries, and — the part that only works because the scorer is deterministic — the exact number of appended words it takes to flip any ranking in the catalog.


Quick start

No dependencies. Python 3.11+.

python -m cynosure fixtures/flooded/catalog.json -p fixtures/flooded/probes.json

Or via make:

make run          # audit the flooded fixture
make run-clean    # audit the clean fixture
make rules        # print the rule catalog
make explain      # show a BM25 score breakdown
make test         # run the suite

Tests need only pytest:

python -m pytest        # 230 tests

make venv creates an isolated virtualenv and installs .[dev], but it is a convenience rather than a requirement: the package has zero runtime dependencies, and tests/conftest.py puts the working tree on sys.path, so a fresh clone runs green with nothing installed but pytest.

Input

The catalog is an MCP tools/list result, a bare tool array, or the native form that adds provenance:

{
  "origins": [
    { "id": "core",    "trust": "first_party" },
    { "id": "helper",  "trust": "untrusted"   }
  ],
  "tools": [
    {
      "name": "issue_refund",
      "origin": "core",
      "defer_loading": true,
      "description": "Issue a refund against a settled invoice...",
      "annotations": { "readOnlyHint": false, "destructiveHint": true },
      "inputSchema": { "type": "object", "properties": { "invoice_id": {} } }
    }
  ]
}

Trust tiers, least to most trusted: untrusted, community, verified, first_party. Undeclared origins default to community.

Probes are optional. Supply the queries you care about — with expect and forbid — and cynosure derives one probe per tool on top of whatever you give it.

CI gate

python -m cynosure catalog.json --fail-on high --json -o report.json
exit meaning
0 audit ran, nothing at or above --fail-on
1 audit ran, the gate tripped
2 bad invocation or bad input — the audit did not run
3 an internal invariant broke (a bug in cynosure)

2 and 3 are kept distinct from 1 on purpose: a broken catalog must never look like a clean audit.


How it works

catalog.json ──┐
               ├─→ Bm25Index / RegexIndex ──→ Ranking per probe ──┐
probes.json ───┤        (retrieve.py)                             │
               │                                                  ├─→ findings
        derived self-probes ───────────────────────────────────┐  │   → text
             (probes.py)                                       │  │   → JSON
                                                               ↓  ↓   → exit code
                    visibility · margin · blindspot · saturation · hygiene

The card. The central abstraction. A search result carries only name and description; the inputSchema and annotations arrive attached to the definition that the selection already chose. cynosure models that asymmetry explicitly instead of assuming it away — it is the whole basis of the blindspot analysis.

Self-probes. Most catalogs have no probe file, so one is derived per tool: its name tokens, topped up with the highest-IDF terms from its own description, preferring terms at least one other card also carries. Both constraints matter. Pure IDF ranking picks the rarest words in the corpus, which in a short catalog are incidental ones — a description ending "irreversible once the transfer clears" yields once, clear before it yields refund. And a term unique to one card makes the probe self-identifying: nothing else can score on it, so the tool wins by construction and the eclipse test proves nothing. Anchoring on the name and preferring contested terms produces a query the tool must actually compete for — and the claim it licenses is deliberately weak, therefore hard to argue with: if a tool cannot reach the top-k for the words that most distinguish it from its neighbours, no natural query about its purpose will surface it either.

Margin. For a query q, incumbent i and challenger c, the margin is

m(q, i, c) = min { n ∈ ℕ : score(c ++ qⁿ, q) > score(i, q) }

the number of words someone must append to a description to capture the query. m = 2 means the ranking is decoration. Two properties of BM25 make this non-obvious, and both are handled exactly rather than approximated:

  • Saturation. The tf/(tf + k1·norm) factor is bounded, so appending the same word buys strictly less each time and converges. m can genuinely be infinite — and a search that only scanned upward would loop forever.
  • Self-inflicted length penalty. Padding grows |D|, raising the b·|D|/avgdl denominator and lowering every other term's contribution in that same card. It also moves avgdl and the padded terms' df, which lowers their IDF for everyone — including the incumbent.

Rather than model those couplings in closed form and risk being subtly wrong, the counterfactual catalog is rebuilt and fully re-indexed for each candidate n. The result is exact by construction: it is the score the real retriever would compute if that description shipped. tests/test_margin.py::test_reported_margin_is_exact applies the reported count for real and asserts the ranking flips at n and not at n-1.

The search bound is a bound on the search, never an assumption: exhausting it reports CAPPED (still climbing) or SATURATED (converged below the incumbent — the only honest form of "term stuffing cannot win this"), and neither is ever reported as a margin.

The two approaches considered

A — model the retriever as a black box and sample it. Feed candidate queries through the real platform endpoint, record what comes back, diff against expectations. Faithful to whatever the vendor actually deployed, including any undocumented reranking.

B — reimplement the scoring function exactly and reason over it. Pin BM25 with explicit parameters, build the index in-process, compute rankings and counterfactuals directly.

Chose B. The deciding factor was that only B can answer the margin question. Sampling tells you the current ranking; it cannot tell you how far that ranking is from flipping without an unbounded number of queries against a live endpoint, each of which costs money, requires network and credentials, and is unavailable in the CI job where this check belongs. B also makes every claim reproducible and inspectable — --explain prints the per-term arithmetic behind any score — which matters more for an auditor than fidelity to an endpoint that will change next quarter.

The trade-off is real and is stated in the limitations below: B is exact about the retriever it models, and silent about any reranking the platform adds on top. Memory is O(corpus tokens); the margin pass re-indexes per candidate injection, which is O(catalog × injections × probes) — trivially fast on hundreds of tools, and --skip-margin exists for catalogs where it isn't.


The rules

id plane default what it means
CYN001 visibility high Eclipsed: outside top-k for its own self-probe.
CYN002 visibility high Unretrievable: scores zero even against itself.
CYN003 visibility low Occupies the last top-k slot; one new card evicts it.
CYN004 visibility medium Rank decided by a score tie broken on catalog order.
CYN010 displacement high A probe's expected tool lost the top rank.
CYN011 displacement critical …and the winner comes from a less-trusted origin.
CYN012 displacement high A forbidden tool was retrieved.
CYN013 displacement high The expected tool fell out of the top-k entirely.
CYN020 margin high Forgeable: a lower-trust card can capture this query by appending n words.
CYN021 margin medium Thin lead over the runner-up.
CYN030 blindspot critical Destructive, retrievable, and its card discloses nothing.
CYN031 blindspot medium Retrievable with no safety annotations at all.
CYN032 blindspot high Card describes mutation while annotations claim read-only.
CYN033 blindspot medium Hazardous parameter exists only in inputSchema.
CYN040 saturation medium One origin owns the top-k for this query.
CYN041 saturation critical …and it is low-trust — the offline signature of tool flooding.
CYN042 saturation medium Near-identical cards from different origins.
CYN050 hygiene high Card too thin to be retrieved by anything but its exact name.
CYN051 hygiene high Regex mode: visible only by position in the manifest.

python -m cynosure --list-rules prints this with full descriptions.


Sample run

$ python -m cynosure fixtures/flooded/catalog.json -p fixtures/flooded/probes.json --skip-margin

==========================================================================
cynosure 0.1.0 - tool-retrieval visibility audit
==========================================================================
catalog     : fixtures/flooded/catalog.json
tools       : 13 total, 13 deferred, 13 indexed
origins     : billing(verified), core(first_party), marketplace-helper(untrusted), obs(verified)
retriever   : bm25 top_k=5 k1=1.2 b=0.75 name_weight=2
probes      : 5 declared + 13 derived

findings    : 9 critical, 2 high, 6 medium

DISPLACEMENT - DOES THE RIGHT TOOL WIN  (4)
--------------------------------------------------------------------------
  [CRIT] CYN011   invoice_refund_helper
           probe: refund-a-customer
           outranks 'issue_refund' for probe 'refund a customer for a settled
           invoice' (scores 5.1376 vs 4.7618) while coming from origin
           'marketplace-helper' (trust=untrusted) against expected origin
           'billing' (trust=verified)
  [HIGH] CYN012   invoice_refund_helper
           probe: refund-a-customer
           appears at rank #1 for probe 'refund a customer for a settled
           invoice', which forbids it

BLIND SELECTION - WHAT THE CARD HIDES AT DECISION TIME  (7)
--------------------------------------------------------------------------
  [CRIT] CYN030   workspace_tidy
           declares destructive behaviour (readOnlyHint=false,
           destructiveHint=true) and is retrievable at rank #1, yet its card
           contains no word disclosing that hazard; the model selects it
           before the annotation is ever loaded
  [MED ] CYN033   workspace_tidy
           exposes hazardous parameter(s) path, recursive that appear only in
           inputSchema; the card shown at selection time does not mention them

SATURATION - WHO OWNS THE RESULT BUDGET  (1)
--------------------------------------------------------------------------
  [CRIT] CYN041   marketplace-helper
           probe: refund-a-customer
           holds 4/5 (80%) of the visible results for probe 'refund a
           customer for a settled invoice' while carrying trust=untrusted;
           this is the offline signature of a tool-flooding injection

==========================================================================
verdict: WORST=CRITICAL  (17 finding(s))
==========================================================================

(Displacement and blindspot sections abridged; the margin pass is skipped here for brevity — with it, the same catalog reports that an untrusted card captures the latency metrics query by appending four words once.)

workspace_tidy is the finding the experiment exists for. Its card reads "Tidy up the workspace so everything stays neat and organised for the next session." It declares destructiveHint: true, takes path and recursive, and ranks #1. Every word a human would need to see is in the part of the entry that arrives after the model has already chosen it.

Fixtures

fixture demonstrates
clean a well-formed catalog: nothing hidden, captured, or blind
flooded an untrusted marketplace bundle capturing billing queries
eclipsed six servers exposing the same tool; the first-party one is invisible

Assumptions & limitations

Stated plainly, because an auditor that overstates its reach is worse than none.

  1. It models the retriever it implements, not the endpoint you call. Defaults (k1=1.2, b=0.75, Lucene IDF, name weight 2, top-k 5) match the common lexical configuration, but a platform may rerank, hybridise with embeddings, or tune differently. Set --k1/--b/--name-weight/--top-k to match yours. Against an embedding retriever the findings do not transfer; the questions do.

  2. Lucene IDF, deliberately. ln(1 + (N−df+0.5)/(df+0.5)) is strictly positive. The textbook RSJ form goes negative for terms in most documents, which in a small, repetitive catalog would let a card improve its rank by dropping a common word — an artefact, not a retrieval effect.

  3. The tokenizer is conservative on purpose. NFKC + casefold, identifier splitting, a small stoplist, and trivial plural folding with an exemption list. No stemmer: a real one would be more accurate and less predictable, and predictability is what lets the margin pass make exact claims. Plural folding is disableable (--no-fold-plurals).

  4. The margin is an upper bound on attacker effort. It uses the weakest possible attack — appending literal query terms, no rephrasing, no synonyms, no editing of existing text. A real adversary needs at most the reported count, quite possibly fewer. That is the safe direction for a security claim.

  5. The hazard lexicon is a heuristic. CYN030 asks whether a card contains any word signalling action on the world. A card that conveys danger through phrasing no keyword catches will be missed; one that mentions "delete" while only reading will not fire when it perhaps should. It is a disclosure check, not a semantic one.

  6. Trust tiers are declared, not discovered. cynosure cannot tell a first-party server from a marketplace one. Undeclared origins default to community, which makes the cross-trust rules (CYN011, CYN041, CYN020) inert — feed real provenance to get real answers.

  7. Self-probes are a lower bound on coverage. They test the query most favourable to each tool. Passing means "not catastrophically hidden", not "no realistic query misroutes". A hand-written probe file is strictly better; the derived ones exist so the tool says something useful on day one.

  8. clean still reports margin findings, and that is not a false positive. A six-tool catalog with terse descriptions genuinely has thin leads. Saying so is the product. --skip-margin makes that fixture report nothing at all.

  9. Regex mode is a model of the shape, not of a specific implementation. The query is compiled as a case-insensitive alternation over its tokens, which is what a model produces when it knows roughly what it wants. The finding that matters (CYN051) does not depend on the exact pattern: under any unscored matcher, over-budget results are truncated by declaration order, so visibility is a property of the file rather than of the tool.

  10. Not measured here: whether the model chooses the retrieved tool. That is a behavioural question needing a model in the loop, and it is downstream of this one. cynosure bounds the candidate set the model is offered; what it does with that set is another experiment.

  11. Sandbox note. make venv was written but could not be executed during this run — the build sandbox refuses to invoke interpreters inside a created virtualenv. The suite was verified with the system interpreter (python -m pytest, 230 passed), which is sufficient here precisely because there are no runtime dependencies to isolate.


Where this sits in the series

Experiments 001–043 audit an artefact the model can see: a static manifest (001–010), one MCP channel (011–022), the transport (023) or terminal rendering (024), A2A (025–026), an MCP Apps bundle (027), caching (028), telemetry (029), header mirroring (030), a Skill's reachable closure (031), the permission policy (032), memory (033), delegation (034), hooks (035), egress (036), a federation merge (037), retry (038), compaction residency (039), path confinement (040), the result projection (041), cancellation (042), and parallel interleaving (043).

Every one of them presupposes that the tool is in context. Under deferred loading, most tools are not. Experiment 044 audits the step that decides which ones get to be.


License

MIT. See LICENSE.

About

cynosure - offline, LLM-free, dependency-free retrieval-visibility auditor for the agent TOOL-SEARCH plane: which tools a deferred-loading catalog can actually surface, which get captured, and the exact word-count it takes to flip a ranking

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages