File size: 10,017 Bytes
7fcf0b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#!/usr/bin/env python3
"""Audit effective biologically meaningful tools in the MCP graph.

The audit follows the definition used for the rebuttal:
an effective biologically meaningful tool directly contributes to a biological
workflow via biological analysis, biological database/annotation access,
biological data transformation, or biologically interpretable reporting.
Generic programming dependencies, CPAN support modules, build utilities, and
low-level package-support wrappers are excluded unless the exposed callable has
direct biological semantics.
"""

from __future__ import annotations

import argparse
import csv
import json
import re
from collections import Counter, defaultdict
from pathlib import Path


BIOLOGICAL_OPERATIONS = {
    "alignment",
    "sequence_alignment",
    "sequence_feature_extraction",
    "quality_control",
    "database_lookup",
    "single_cell_clustering",
    "primer_validation",
    "quantification",
    "gene_id_conversion",
    "variant_annotation",
    "taxonomic_classification",
    "count_normalization",
    "base_counting",
    "differential_expression",
    "orf_detection",
    "reverse_complement",
    "kozak_scoring",
    "gc_content_calculation",
    "read_counting",
    "restriction_digest",
    "variant_summary",
    "kegg_enrichment",
    "marker_gene_detection",
    "go_enrichment",
    "gene_filtering",
    "differential_abundance",
}

BIOLOGICAL_CATEGORIES = {
    "genomics",
    "transcriptomics",
    "single_cell",
    "pathway_enrichment",
    "metagenomics",
    "proteomics",
}

BIOLOGICAL_TEXT_RE = re.compile(
    r"\b("
    r"gene|genes|genome|genomic|genomics|chromosome|locus|allele|mutation|"
    r"sequence|sequences|sequencing|fastq|fasta|bam|sam|vcf|bcf|"
    r"bed|gff|gtf|contig|assembly|alignment|align|blast|hmmer|motif|orf|"
    r"variant|snp|indel|annotation|annotate|taxonomy|taxonomic|kraken|"
    r"metagenom|microbiome|rna|dna|transcript|transcriptomic|gene expression|"
    r"differential expression|single[-_ ]cell|cellranger|seurat|scanpy|"
    r"protein|proteomics|peptide|antibody|enzyme|primer|crispr|pathway|"
    r"kegg|go enrichment|ontology|clusterprofiler|deseq|edgeR|limma|"
    r"samtools|bcftools|vep|ensembl|bioperl|bioconductor|biomart|"
    r"phylo|phylogen|quality control|qc report|genome browser"
    r")\b",
    re.IGNORECASE,
)

GENERIC_DEPENDENCY_RE = re.compile(
    r"\b("
    r"json|yaml|xml|html|http|uri|url|www|soap|mime|cgi|dbi|"
    r"compress|zlib|archive|tar|zip|base64|digest|sha|md5|crypt|ssl|"
    r"module|runtime|build|makemaker|loader|autoloader|exporter|importer|"
    r"params|class|object|role|sub|test|exception|error|stacktrace|"
    r"date|time|locale|encode|unicode|font|postscript|spreadsheet|"
    r"string|regexp|parse|parser|tree|graphviz|template|config|"
    r"network|socket|client|server|driver|database driver|"
    r"coreutils|build util|dependency|support module"
    r")\b",
    re.IGNORECASE,
)


def text_for(*items: object) -> str:
    parts: list[str] = []
    for item in items:
        if item is None:
            continue
        if isinstance(item, list):
            parts.extend(map(str, item))
        else:
            parts.append(str(item))
    return " ".join(parts).lower()


def load_graph(graph_dir: Path):
    nodes = json.loads((graph_dir / "graph_nodes.json").read_text())
    edges = json.loads((graph_dir / "graph_edges.json").read_text())

    servers = {n["id"]: n for n in nodes if n.get("type") == "server"}
    tools = {n["id"]: n for n in nodes if n.get("type") == "tool"}
    tool_to_server: dict[str, str] = {}
    tool_ops: dict[str, set[str]] = defaultdict(set)

    for edge in edges:
        if edge.get("type") == "hosts":
            tool_to_server[edge["target"]] = edge["source"]
        elif edge.get("type") == "implements_operation":
            tool_ops[edge["source"]].add(edge["target"].split(":", 1)[1])

    return servers, tools, tool_to_server, tool_ops


def classify(server: dict, tool: dict, operations: set[str]) -> tuple[bool, bool, str]:
    """Return effective, high_level, reason."""
    server_label = server.get("label", "")
    category = server.get("category", "")
    tool_text = text_for(
        server_label,
        tool.get("label", ""),
        tool.get("description", ""),
        tool.get("keywords", []),
    )
    server_context = text_for(
        server_label,
        server.get("summary", ""),
        server.get("keywords", []),
    )

    has_bio_operation = bool(operations & BIOLOGICAL_OPERATIONS)
    # Use tool-facing text for positive biological evidence. Server summaries
    # contain broad auto-generated context and can leak noisy category labels.
    has_bio_text = bool(BIOLOGICAL_TEXT_RE.search(tool_text))
    has_bio_category = category in BIOLOGICAL_CATEGORIES
    has_generic_dependency_text = bool(GENERIC_DEPENDENCY_RE.search(tool_text))
    server_label_has_bio = bool(BIOLOGICAL_TEXT_RE.search(server_label))

    # Perl/CPAN and generic utility wrappers need positive biological evidence.
    looks_like_language_dependency = (
        server_label.startswith("perl-")
        or server_label.startswith("python-")
        or server_label.startswith("r-")
        or "cpan" in server_context
        or "support module" in server_context
        or "dependency" in server_context
    )
    looks_like_generic_language_dependency = looks_like_language_dependency and not server_label_has_bio
    looks_like_generic_utility = category in {"utility", "general"} or (
        has_generic_dependency_text and not has_bio_text and not has_bio_operation
    )

    # Explicit biological text is sufficient. Biological operations are accepted
    # unless the callable looks like a generic language dependency; this guards
    # against noisy auto-annotations such as URI normalization being mapped to
    # count_normalization.
    effective = has_bio_text or (
        has_bio_operation and not looks_like_generic_language_dependency
    )

    # High-level biological analysis excludes pure transformation/reporting-style
    # evidence and requires an explicit biological analysis/database operation.
    high_level_ops = BIOLOGICAL_OPERATIONS - {
        "gc_content_calculation",
        "base_counting",
        "reverse_complement",
        "csv_export",
    }
    high_level = effective and bool(operations & high_level_ops)

    reason_bits = []
    if has_bio_operation:
        reason_bits.append("bio_operation=" + ",".join(sorted(operations & BIOLOGICAL_OPERATIONS)))
    if has_bio_text:
        reason_bits.append("bio_text")
    if has_bio_category:
        reason_bits.append(f"bio_category={category}")
    if looks_like_language_dependency:
        reason_bits.append("language_dependency_like")
    if looks_like_generic_utility:
        reason_bits.append("generic_utility_like")
    if not reason_bits:
        reason_bits.append("no_direct_biological_evidence")
    return effective, high_level, ";".join(reason_bits)


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--graph-dir",
        type=Path,
        default=Path("Biomanus/graph_outputs/mcp_generated_graph_all_20260522_124110"),
    )
    parser.add_argument(
        "--out",
        type=Path,
        default=Path("effective_biologically_meaningful_tools_audit.csv"),
    )
    parser.add_argument(
        "--summary-out",
        type=Path,
        default=Path("effective_biologically_meaningful_tools_summary.tsv"),
    )
    args = parser.parse_args()

    servers, tools, tool_to_server, tool_ops = load_graph(args.graph_dir)

    rows = []
    counts = Counter()
    by_category = Counter()
    high_by_category = Counter()

    for tool_id, tool in sorted(tools.items()):
        server_id = tool_to_server.get(tool_id)
        server = servers.get(server_id, {})
        operations = tool_ops.get(tool_id, set())
        effective, high_level, reason = classify(server, tool, operations)

        counts["raw_callable_mcp_interfaces"] += 1
        if effective:
            counts["effective_biologically_meaningful_tools"] += 1
            by_category[server.get("category", "unknown")] += 1
        if high_level:
            counts["high_level_biological_analysis_tools"] += 1
            high_by_category[server.get("category", "unknown")] += 1

        rows.append(
            {
                "tool_id": tool_id,
                "server": server.get("label", ""),
                "category": server.get("category", ""),
                "tool": tool.get("label", ""),
                "description": tool.get("description", ""),
                "operations": ",".join(sorted(operations)),
                "effective_biologically_meaningful": effective,
                "high_level_biological_analysis": high_level,
                "reason": reason,
            }
        )

    with args.out.open("w", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
        writer.writeheader()
        writer.writerows(rows)

    with args.summary_out.open("w") as f:
        f.write("metric\tcount\n")
        for key in [
            "raw_callable_mcp_interfaces",
            "effective_biologically_meaningful_tools",
            "high_level_biological_analysis_tools",
        ]:
            f.write(f"{key}\t{counts[key]}\n")
        f.write("\ncategory\teffective_biologically_meaningful_tools\n")
        for category, count in by_category.most_common():
            f.write(f"{category}\t{count}\n")
        f.write("\ncategory\thigh_level_biological_analysis_tools\n")
        for category, count in high_by_category.most_common():
            f.write(f"{category}\t{count}\n")

    print(f"Wrote {args.out}")
    print(f"Wrote {args.summary_out}")
    for key in [
        "raw_callable_mcp_interfaces",
        "effective_biologically_meaningful_tools",
        "high_level_biological_analysis_tools",
    ]:
        print(f"{key}: {counts[key]}")


if __name__ == "__main__":
    main()