File size: 7,352 Bytes
673d45d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
"""A rule-compliant view of ToolUniverse for BioMysteryBench agents.

ToolUniverse ships 2,315 scientific tools, and **422 of them would break this benchmark's
one hard rule**. Anthropic's terms permit "gene ID lookup, sequence annotation, reference
genome download, BLAST" and forbid "looking up GEO/SRA/ENA/BioProject accession IDs to
identify the original dataset, source publication, or study metadata". ToolUniverse
contains `GEO_get_dataset_details` ("by its accession"), `GEO_search_chipseq_datasets`,
`ENCODE_search_histone_experiments` and hundreds more of exactly that shape. An agent
handed the unfiltered library could identify the source study instead of analysing the
data, which would invalidate every result and breach the access terms.

So this module never exposes ToolUniverse directly. Two independent layers must both pass:

1. **Category whitelist** -- only categories whose purpose is annotation, sequence or
   structure lookup. Anything not named is excluded, so a new upstream category cannot
   silently become reachable.
2. **Pattern scan** -- a per-tool check on name and description, applied *again* at call
   time. Filtering only at listing time would leave the door open to an agent naming a
   tool directly.

Defence in depth is deliberate: the whitelist is the policy and the scan is the backstop,
and either alone has failed for us before.
"""

from __future__ import annotations

import json
import os
import re
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path

# Categories whose tools annotate sequence, genes, proteins or structures. Chosen against
# the benchmark's own wording. Everything else is excluded by omission.
ALLOWED_CATEGORIES = frozenset({
    "ensembl", "uniprot", "rcsb_pdb", "software_bioinformatics",
    "alliance_genome", "ucsc_genome", "reactome", "gene_ontology",
})

# Second layer. Matches the provenance-lookup shapes the rule names, plus the literature
# and dataset-search shapes that reach the same answer by another route.
FORBIDDEN_PATTERN = re.compile(
    r"\b(GEO|SRA|ENA|BioProject|BioSample|ArrayExpress|dbGaP|EGA|PRIDE|MassIVE"
    r"|MetaboLights|ENCODE|GTEx|TCGA|ICGC|Recount)\b"
    r"|accession"
    r"|dataset[^.]{0,24}(search|detail|metadata)"
    r"|search[^.]{0,24}(dataset|experiment|stud(y|ies)|sample|assay)"
    r"|publication|literature|pubmed|citation|study[ _-]metadata",
    re.I,
)


@dataclass(frozen=True)
class Tool:
    """One tool cleared for use.

    Attributes:
        name: ToolUniverse tool name, used to invoke it.
        category: Config file it came from, minus the ``_tools.json`` suffix.
        description: Upstream description, shown to the agent.
    """

    name: str
    category: str
    description: str


def is_compliant(name: str, description: str) -> bool:
    """Whether a tool may be exposed, on name and description alone.

    Pure so it can be tested directly and reused at both listing and call time. A tool is
    compliant only if neither field matches `FORBIDDEN_PATTERN`; the description matters
    as much as the name, because `ADA_get_standards_section` reveals nothing until read.
    """
    return not FORBIDDEN_PATTERN.search(f"{name} {description or ''}")


def _data_dir() -> Path | None:
    """Directory holding ToolUniverse's tool definitions, or None if not installed."""
    try:
        import tooluniverse  # noqa: PLC0415
    except ImportError:
        return None
    path = Path(tooluniverse.__file__).parent / "data"
    return path if path.is_dir() else None


@lru_cache(maxsize=1)
def allowed_tools() -> tuple[Tool, ...]:
    """Every ToolUniverse tool that passes both layers.

    Returns:
        Compliant tools, sorted by name. Empty when ToolUniverse is not installed, so a
        caller degrades to shell-only rather than failing.
    """
    data = _data_dir()
    if data is None:
        return ()
    out: list[Tool] = []
    for path in sorted(data.glob("*_tools.json")):
        category = path.name[: -len("_tools.json")]
        if category not in ALLOWED_CATEGORIES:
            continue
        try:
            entries = json.loads(path.read_text(errors="replace"))
        except (OSError, json.JSONDecodeError):
            continue
        if not isinstance(entries, list):
            continue
        for entry in entries:
            if not isinstance(entry, dict):
                continue
            name = entry.get("name", "")
            desc = entry.get("description") or ""
            if name and is_compliant(name, desc):
                out.append(Tool(name, category, desc.strip()))
    return tuple(sorted(out, key=lambda t: t.name))


@lru_cache(maxsize=1)
def _by_name() -> dict[str, Tool]:
    return {t.name: t for t in allowed_tools()}


class ToolNotPermitted(RuntimeError):
    """Raised when a caller names a tool outside the compliant set."""


def check_permitted(name: str) -> Tool:
    """Resolve a tool name, refusing anything not cleared.

    Enforced at call time on purpose. Filtering the *listing* only would still let an
    agent invoke `GEO_get_dataset_details` by naming it, and the agent writes its own
    commands.

    Raises:
        ToolNotPermitted: If the name is unknown or outside the compliant set.
    """
    tool = _by_name().get(name)
    if tool is None:
        raise ToolNotPermitted(
            f"{name!r} is not in the permitted tool set. This benchmark forbids "
            f"identifying the source dataset; sequence, gene and structure annotation "
            f"tools are available via `biotool list`.")
    return tool


def call_tool(name: str, arguments: dict) -> object:
    """Invoke a permitted ToolUniverse tool.

    Args:
        name: Tool name, which must be in the compliant set.
        arguments: Tool arguments, passed through unchanged.

    Returns:
        Whatever ToolUniverse returns.

    Raises:
        ToolNotPermitted: If the tool is not cleared.
        RuntimeError: If ToolUniverse is unavailable.
    """
    check_permitted(name)
    try:
        from tooluniverse import ToolUniverse  # noqa: PLC0415
    except ImportError as exc:  # pragma: no cover - environment-dependent
        raise RuntimeError("tooluniverse is not installed") from exc
    engine = _engine()
    return engine.run({"name": name, "arguments": arguments})


@lru_cache(maxsize=1)
def _engine():
    """Load ToolUniverse once. Startup is seconds, so it must not be per-call."""
    from tooluniverse import ToolUniverse  # noqa: PLC0415
    tu = ToolUniverse()
    tu.load_tools()
    return tu


def describe(limit: int = 40) -> str:
    """Render the permitted tools for an agent prompt, grouped by category."""
    tools = allowed_tools()
    if not tools:
        return "(no structured tools available; use the shell)"
    lines = [f"{len(tools)} tools are available via `biotool call <name> '<json args>'`.",
             "Dataset, accession and literature lookups are NOT available: this benchmark "
             "requires you to solve the problem from the data you were given.", ""]
    by_cat: dict[str, list[Tool]] = {}
    for tool in tools:
        by_cat.setdefault(tool.category, []).append(tool)
    for cat, group in sorted(by_cat.items()):
        lines.append(f"[{cat}] " + ", ".join(t.name for t in group[:limit]))
    return "\n".join(lines)