Spaces:
Running
Running
File size: 5,568 Bytes
fd5dd94 | 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 | """Hybrid tool search over an indexed registry (Postgres full-text + pgvector).
Accuracy drops once more than ~30-50 tool definitions are loaded at once, so agents get a
small always-loaded set and discover the rest here. Global (pack) tools have
``tenant_id IS NULL``; tenant-registered tools are scoped by RLS.
"""
from __future__ import annotations
import hashlib
import itertools
import math
import re
import uuid
from typing import Protocol
from pgvector.sqlalchemy import Vector
from sqlalchemy import Integer, String, Text, delete, func, literal_column, select
from sqlalchemy.dialects.postgresql import JSONB, TSVECTOR, UUID
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Mapped, mapped_column
from core.db.base import Base, TimestampMixin, new_id
from core.tools.preview import canonical_json, sha256_hex
from core.tools.spec import ToolSpec
EMBED_DIM = 256
class Embedder(Protocol):
dim: int
def embed(self, text: str) -> list[float]: ...
class HashingEmbedder:
"""Deterministic feature-hashing embedder: no network, no API key.
Good enough for tool names/descriptions; swap for a real embedding model in production.
"""
dim = EMBED_DIM
def embed(self, text: str) -> list[float]:
vec = [0.0] * self.dim
tokens = re.findall(r"[a-z0-9]+", text.lower())
grams = tokens + [f"{a}_{b}" for a, b in itertools.pairwise(tokens)]
for g in grams:
h = int.from_bytes(hashlib.blake2b(g.encode(), digest_size=8).digest(), "big")
vec[h % self.dim] += 1.0 if (h >> 63) == 0 else -1.0
norm = math.sqrt(sum(v * v for v in vec)) or 1.0
return [v / norm for v in vec]
class ToolIndexEntry(TimestampMixin, Base):
__tablename__ = "tool_index"
__rls__ = True # custom policy: global rows visible to all, writes need owner role
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=new_id)
tenant_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)
name: Mapped[str] = mapped_column(String(200), nullable=False)
description: Mapped[str] = mapped_column(Text, nullable=False)
risk_tier: Mapped[int] = mapped_column(Integer, nullable=False)
source: Mapped[str] = mapped_column(String(20), nullable=False, default="pack")
spec: Mapped[dict] = mapped_column(JSONB, nullable=False)
definition_hash: Mapped[str] = mapped_column(String(64), nullable=False)
search_doc: Mapped[str] = mapped_column(TSVECTOR, nullable=False)
embedding: Mapped[list[float]] = mapped_column(Vector(EMBED_DIM), nullable=False)
def spec_document(spec: ToolSpec) -> dict:
return {
"name": spec.name,
"description": spec.description,
"risk_tier": int(spec.risk_tier),
"input_schema": spec.json_schema(),
"sensitive_args": list(spec.sensitive_args),
"tags": list(spec.tags),
}
def definition_hash(spec: ToolSpec) -> str:
"""Pinned per tool; a changed definition is detectable (MCP rug-pull defense)."""
return sha256_hex(canonical_json(spec_document(spec)))
def _search_text(spec: ToolSpec) -> str:
return " ".join([spec.name.replace(".", " ").replace("_", " "), spec.description, *spec.tags])
class ToolSearch:
def __init__(self, embedder: Embedder | None = None) -> None:
self.embedder = embedder or HashingEmbedder()
async def sync_global(self, session: AsyncSession, specs: list[ToolSpec]) -> int:
"""Replace the global (tenant_id IS NULL) index. Must run as the owner role."""
await session.execute(delete(ToolIndexEntry).where(ToolIndexEntry.tenant_id.is_(None)))
for spec in specs:
await self._insert(session, spec, tenant_id=None, source="pack")
return len(specs)
async def index_tenant_tool(
self, session: AsyncSession, spec: ToolSpec, tenant_id: uuid.UUID, source: str
) -> None:
await self._insert(session, spec, tenant_id=tenant_id, source=source)
async def _insert(
self, session: AsyncSession, spec: ToolSpec, tenant_id: uuid.UUID | None, source: str
) -> None:
text = _search_text(spec)
session.add(
ToolIndexEntry(
tenant_id=tenant_id,
name=spec.name,
description=spec.description,
risk_tier=int(spec.risk_tier),
source=source,
spec=spec_document(spec),
definition_hash=definition_hash(spec),
search_doc=func.to_tsvector("simple", text),
embedding=self.embedder.embed(text),
)
)
await session.flush()
async def search(self, session: AsyncSession, query: str, k: int = 5) -> list[str]:
"""Top-k tool names by 0.5 * normalized text rank + 0.5 * cosine similarity."""
qvec = self.embedder.embed(query)
terms = " | ".join(re.findall(r"[a-z0-9]+", query.lower())) or "''"
tsq = func.to_tsquery("simple", terms)
text_rank = func.ts_rank_cd(ToolIndexEntry.search_doc, tsq, 32)
cosine = literal_column("1") - ToolIndexEntry.embedding.cosine_distance(qvec)
score = (0.5 * text_rank + 0.5 * cosine).label("score")
rows = await session.execute(
select(ToolIndexEntry.name, score).order_by(score.desc()).limit(k)
)
return [r.name for r in rows]
|