Spaces:
Running
Running
Download core/tools/tenant_tools.py from Aynkhn/WorkPilot-AI: direct link, hf CLI and curl.
- Browser
- Download file 22.3 kB
-
https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/tools/tenant_tools.py
- Command line
-
hf download hf://spaces/Aynkhn/WorkPilot-AI/core/tools/tenant_tools.py
-
curl -L -o tenant_tools.py https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/tools/tenant_tools.py
22.3 kB
| """Tenant-scoped runtime tools (Phase 16): stored in the database, loaded per call. | |
| Pack tools live in the process-global ``ToolRegistry``. Tools a tenant adds at runtime | |
| (OpenAPI operations, MCP server tools, connectors, HTTP actions) live in ``tenant_tools`` | |
| (RLS forced) and reach the agent with **no deploy**: the gateway asks this store when a | |
| name is not in the registry (``Gateway(tenant_tools=...)``). | |
| Safety posture: | |
| * A new tool's effective tier is **T3** (every call needs a human) until an owner confirms a | |
| tier. ``suggested_tier`` (from the HTTP method or MCP annotations) is only a suggestion; a | |
| tier *below* the suggestion needs ``acknowledge_risk``. | |
| * A new tool starts in ``test`` mode: calls go to the sandbox URL if one is configured, | |
| otherwise only dry runs work. The owner switches it to ``live`` when confirming. | |
| * The confirmed definition hash is pinned. If the definition changes (MCP rug pull, | |
| re-import) the tool is blocked until an owner re-confirms (``pending`` holds the change). | |
| * Credentials: rows hold only secret *refs*. The gateway resolves them through | |
| ``credentials()`` at execution time (sandbox calls get the sandbox secret only). | |
| Built tools are cached per process keyed by ``(tenant, name, revision, hash)``; every | |
| change bumps ``revision``, so other processes pick changes up on their next call. | |
| """ | |
| from __future__ import annotations | |
| import uuid | |
| from collections import OrderedDict | |
| from collections.abc import Callable, Mapping | |
| from dataclasses import dataclass, field | |
| from datetime import UTC, datetime | |
| from typing import Any, Protocol | |
| import httpx | |
| from sqlalchemy import ( | |
| Boolean, | |
| CheckConstraint, | |
| DateTime, | |
| Index, | |
| Integer, | |
| String, | |
| Text, | |
| UniqueConstraint, | |
| delete, | |
| func, | |
| select, | |
| ) | |
| from sqlalchemy.dialects.postgresql import JSONB, UUID | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlalchemy.orm import Mapped, mapped_column | |
| from core.channels.secrets import EnvSecretStore, SecretStore | |
| from core.config import get_settings | |
| from core.db.base import Base, TenantMixin, TimestampMixin, new_id | |
| from core.tools.jsonschema_model import model_from_schema | |
| from core.tools.registry import ToolRegistry | |
| from core.tools.search import ToolIndexEntry, ToolSearch | |
| from core.tools.spec import RegisteredTool, RiskTier, ToolHandler, ToolSpec | |
| SOURCES = ("openapi", "mcp", "connector", "http") | |
| MODES = ("test", "live") | |
| class TenantTool(TenantMixin, TimestampMixin, Base): | |
| __tablename__ = "tenant_tools" | |
| __table_args__ = ( | |
| UniqueConstraint("tenant_id", "name", name="uq_tenant_tools_tenant_name"), | |
| CheckConstraint("suggested_tier BETWEEN 0 AND 3", name="suggested_tier"), | |
| CheckConstraint( | |
| "confirmed_tier IS NULL OR confirmed_tier BETWEEN 0 AND 3", name="confirmed_tier" | |
| ), | |
| CheckConstraint("mode IN ('test', 'live')", name="mode"), | |
| Index("ix_tenant_tools_source", "tenant_id", "source_id"), | |
| ) | |
| id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=new_id) | |
| name: Mapped[str] = mapped_column(String(200), nullable=False) | |
| source: Mapped[str] = mapped_column(String(20), nullable=False) | |
| source_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True) | |
| kind: Mapped[str] = mapped_column(String(30), nullable=False) # handler factory key | |
| description: Mapped[str] = mapped_column(Text, nullable=False) | |
| input_schema: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False) | |
| config: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False, default=dict) | |
| secret_ref: Mapped[str | None] = mapped_column(String(120), nullable=True) | |
| sandbox_secret_ref: Mapped[str | None] = mapped_column(String(120), nullable=True) | |
| definition_hash: Mapped[str] = mapped_column(String(64), nullable=False) | |
| pinned_hash: Mapped[str | None] = mapped_column(String(64), nullable=True) | |
| pending: Mapped[dict[str, Any] | None] = mapped_column(JSONB, nullable=True) | |
| suggested_tier: Mapped[int] = mapped_column(Integer, nullable=False) | |
| confirmed_tier: Mapped[int | None] = mapped_column(Integer, nullable=True) | |
| enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True) | |
| mode: Mapped[str] = mapped_column(String(10), nullable=False, default="test") | |
| revision: Mapped[int] = mapped_column(Integer, nullable=False, default=1) | |
| confirmed_by: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True) | |
| confirmed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) | |
| updated_at: Mapped[datetime] = mapped_column( | |
| DateTime(timezone=True), server_default=func.now(), nullable=False | |
| ) | |
| def effective_tier(self) -> int: | |
| if self.confirmed_tier is None or self.pending is not None: | |
| return int(RiskTier.T3_CRITICAL) | |
| return self.confirmed_tier | |
| def blocked_reason(self) -> str | None: | |
| if not self.enabled: | |
| return f"tool {self.name} is disabled" | |
| if self.pending is not None or ( | |
| self.pinned_hash is not None and self.pinned_hash != self.definition_hash | |
| ): | |
| return ( | |
| f"tool {self.name} changed since an owner confirmed it; " | |
| "an owner must review and re-confirm it" | |
| ) | |
| return None | |
| class TenantRegisteredTool(RegisteredTool): | |
| """A registry-compatible tool built from a ``tenant_tools`` row.""" | |
| tool_id: uuid.UUID | None = None | |
| secret_ref: str | None = None | |
| class HandlerEnv: | |
| """What handler factories get. Injectable for tests (``httpx.MockTransport``, an | |
| in-memory MCP server).""" | |
| transport: httpx.AsyncBaseTransport | None = None | |
| mcp_connect: Any = None # core.mcp.client.Connect | |
| test_mode: bool = False | |
| HandlerFactory = Callable[[TenantTool, HandlerEnv], ToolHandler] | |
| class OverlayRegistry(ToolRegistry): | |
| """A registry that keeps tenant tools as ``TenantRegisteredTool`` (with their secret ref), | |
| so a gateway using it still injects their credentials.""" | |
| def add(self, tool: TenantRegisteredTool) -> None: | |
| if self.has(tool.spec.name): | |
| raise ValueError(f"tool already registered: {tool.spec.name}") | |
| self._tools[tool.spec.name] = tool | |
| class ToolUnavailable(Exception): | |
| """A tenant tool exists but may not run (disabled, or changed since confirmation).""" | |
| class TenantToolResolver(Protocol): | |
| """What the gateway needs (``core.gateway.gateway.Gateway(tenant_tools=...)``).""" | |
| async def resolve( | |
| self, session: AsyncSession, tenant_id: uuid.UUID, name: str | |
| ) -> RegisteredTool | None: ... | |
| def owns(self, tool: RegisteredTool) -> bool: ... | |
| def credentials(self, tool: RegisteredTool) -> Mapping[str, str]: ... | |
| def default_factories() -> dict[str, HandlerFactory]: | |
| from core.connectors.service import connector_factories | |
| from core.mcp.client import mcp_handler_factory | |
| def http(row: TenantTool, env: HandlerEnv) -> ToolHandler: | |
| from core.tools.http_tool import HttpOperation, make_http_handler | |
| op = HttpOperation.model_validate(row.config["http"]) | |
| return make_http_handler(op, transport=env.transport, test_mode=env.test_mode) | |
| return {"http": http, "mcp": mcp_handler_factory, **connector_factories()} | |
| class NewTool: | |
| """A tool to import (from an OpenAPI operation, an MCP tool, a connector, ...).""" | |
| name: str | |
| description: str | |
| input_schema: dict[str, Any] | |
| kind: str | |
| config: dict[str, Any] | |
| suggested_tier: int | |
| definition_hash: str | |
| secret_ref: str | None = None | |
| sandbox_secret_ref: str | None = None | |
| meta: dict[str, Any] = field(default_factory=dict) | |
| class ImportReport: | |
| created: list[str] = field(default_factory=list) | |
| unchanged: list[str] = field(default_factory=list) | |
| changed: list[str] = field(default_factory=list) # blocked until re-confirmed | |
| removed: list[str] = field(default_factory=list) # disabled | |
| class TenantToolStore: | |
| def __init__( | |
| self, | |
| *, | |
| secrets: SecretStore | None = None, | |
| transport: httpx.AsyncBaseTransport | None = None, | |
| mcp_connect: Any = None, | |
| search: ToolSearch | None = None, | |
| factories: Mapping[str, HandlerFactory] | None = None, | |
| reserved: Callable[[str], bool] | None = None, | |
| cache_size: int | None = None, | |
| ) -> None: | |
| self.secrets: SecretStore = secrets or EnvSecretStore() | |
| self.transport = transport | |
| self.mcp_connect = mcp_connect | |
| self.search = search or ToolSearch() | |
| self._factories = dict(factories) if factories is not None else None | |
| self.reserved = reserved or (lambda name: False) | |
| self._cache: OrderedDict[tuple[Any, ...], TenantRegisteredTool] = OrderedDict() | |
| self._cache_size = cache_size or get_settings().ext_tool_cache_size | |
| def factories(self) -> Mapping[str, HandlerFactory]: | |
| if self._factories is None: | |
| self._factories = default_factories() | |
| return self._factories | |
| # ------------------------------------------------------------- gateway side | |
| async def resolve( | |
| self, session: AsyncSession, tenant_id: uuid.UUID, name: str | |
| ) -> TenantRegisteredTool | None: | |
| row = await self.get(session, name) | |
| if row is None or row.tenant_id != tenant_id: | |
| return None | |
| if (reason := row.blocked_reason) is not None: | |
| raise ToolUnavailable(reason) | |
| key = (tenant_id, name, row.revision, row.definition_hash) | |
| cached = self._cache.get(key) | |
| if cached is not None: | |
| self._cache.move_to_end(key) | |
| return cached | |
| tool = self.build(row) | |
| self._cache[key] = tool | |
| while len(self._cache) > self._cache_size: | |
| self._cache.popitem(last=False) | |
| return tool | |
| def build(self, row: TenantTool) -> TenantRegisteredTool: | |
| factory = self.factories.get(row.kind) | |
| if factory is None: | |
| raise ToolUnavailable(f"tool {row.name} has unknown kind {row.kind}") | |
| test_mode = row.mode != "live" | |
| env = HandlerEnv( | |
| transport=self.transport, mcp_connect=self.mcp_connect, test_mode=test_mode | |
| ) | |
| spec = self.spec(row) | |
| return TenantRegisteredTool( | |
| spec=spec, | |
| handler=factory(row, env), | |
| tool_id=row.id, | |
| secret_ref=row.sandbox_secret_ref if test_mode else row.secret_ref, | |
| ) | |
| def spec(row: TenantTool) -> ToolSpec: | |
| return ToolSpec( | |
| name=row.name, | |
| description=row.description, | |
| input_model=model_from_schema(row.input_schema, f"{row.name}_input"), | |
| risk_tier=RiskTier(row.effective_tier), | |
| supports_dry_run=True, | |
| pack=None, | |
| # Phase 15: tools of payment-capable MCP servers carry ``payments`` (gateway | |
| # isolation from runs started by untrusted inbound content). | |
| tags=("tenant", row.source, *(("payments",) if row.config.get("payments") else ())), | |
| ) | |
| async def overlay( | |
| self, session: AsyncSession, tenant_id: uuid.UUID, base: ToolRegistry | |
| ) -> ToolRegistry: | |
| """A registry with ``base``'s tools plus this tenant's runnable tools, for code that | |
| validates against a ``ToolRegistry`` (e.g. workflow definitions).""" | |
| reg = OverlayRegistry() | |
| reg.register_many(base.get(spec.name) for spec in base.specs()) | |
| for row in await self.list_tools(session): | |
| if row.blocked_reason is None and not base.has(row.name): | |
| reg.add(self.build(row)) | |
| return reg | |
| def owns(self, tool: RegisteredTool) -> bool: | |
| return isinstance(tool, TenantRegisteredTool) | |
| def credentials(self, tool: RegisteredTool) -> Mapping[str, str]: | |
| ref = getattr(tool, "secret_ref", None) | |
| if not ref: | |
| return {} | |
| value = self.secrets.get(ref) | |
| return {"secret": value} if value else {} | |
| def invalidate(self, tenant_id: uuid.UUID | None = None) -> None: | |
| for key in [k for k in self._cache if tenant_id is None or k[0] == tenant_id]: | |
| self._cache.pop(key, None) | |
| # --------------------------------------------------------------- management | |
| async def get(session: AsyncSession, name: str) -> TenantTool | None: | |
| return ( | |
| await session.execute(select(TenantTool).where(TenantTool.name == name)) | |
| ).scalar_one_or_none() | |
| async def list_tools( | |
| session: AsyncSession, source_id: uuid.UUID | None = None | |
| ) -> list[TenantTool]: | |
| q = select(TenantTool).order_by(TenantTool.name) | |
| if source_id is not None: | |
| q = q.where(TenantTool.source_id == source_id) | |
| return list((await session.execute(q)).scalars()) | |
| async def sync( | |
| self, | |
| session: AsyncSession, | |
| tenant_id: uuid.UUID, | |
| tools: list[NewTool], | |
| *, | |
| source: str, | |
| source_id: uuid.UUID | None, | |
| remove_missing: bool = True, | |
| ) -> ImportReport: | |
| """Create new tools, keep unchanged ones, mark changed ones ``pending`` (blocked until | |
| an owner re-confirms) and disable tools that disappeared from the source.""" | |
| if source not in SOURCES: | |
| raise ValueError(f"unknown source {source}") | |
| report = ImportReport() | |
| existing = { | |
| r.name: r | |
| for r in (await self.list_tools(session, source_id) if source_id is not None else []) | |
| } | |
| for t in tools: | |
| if self.reserved(t.name): | |
| raise ValueError(f"tool name {t.name} is reserved by an installed pack") | |
| row = existing.pop(t.name, None) or await self.get(session, t.name) | |
| if row is None: | |
| row = TenantTool( | |
| tenant_id=tenant_id, | |
| name=t.name, | |
| source=source, | |
| source_id=source_id, | |
| kind=t.kind, | |
| description=t.description, | |
| input_schema=t.input_schema, | |
| config=t.config, | |
| secret_ref=t.secret_ref, | |
| sandbox_secret_ref=t.sandbox_secret_ref, | |
| definition_hash=t.definition_hash, | |
| suggested_tier=t.suggested_tier, | |
| enabled=True, | |
| mode="test", | |
| revision=1, | |
| ) | |
| session.add(row) | |
| await session.flush() | |
| report.created.append(t.name) | |
| elif row.source_id != source_id: | |
| raise ValueError(f"tool {t.name} already exists from another source") | |
| elif row.definition_hash == t.definition_hash and row.pending is None: | |
| report.unchanged.append(t.name) | |
| if row.secret_ref != t.secret_ref or not row.enabled: | |
| row.secret_ref = t.secret_ref | |
| row.sandbox_secret_ref = t.sandbox_secret_ref | |
| row.enabled = True | |
| self._touch(row) | |
| else: | |
| if row.pinned_hash is None and row.confirmed_tier is None: | |
| # never confirmed: nothing to protect, take the new definition directly | |
| self._apply(row, t) | |
| else: | |
| row.pending = { | |
| "description": t.description, | |
| "input_schema": t.input_schema, | |
| "config": t.config, | |
| "kind": t.kind, | |
| "suggested_tier": t.suggested_tier, | |
| "definition_hash": t.definition_hash, | |
| "secret_ref": t.secret_ref, | |
| "sandbox_secret_ref": t.sandbox_secret_ref, | |
| } | |
| self._touch(row) | |
| report.changed.append(t.name) | |
| await self.reindex(session, row) | |
| if remove_missing: | |
| for row in existing.values(): | |
| if row.enabled: | |
| row.enabled = False | |
| self._touch(row) | |
| await self.reindex(session, row) | |
| report.removed.append(row.name) | |
| self.invalidate(tenant_id) | |
| return report | |
| def _apply(row: TenantTool, t: NewTool) -> None: | |
| row.description = t.description | |
| row.input_schema = t.input_schema | |
| row.config = t.config | |
| row.kind = t.kind | |
| row.suggested_tier = t.suggested_tier | |
| row.definition_hash = t.definition_hash | |
| row.secret_ref = t.secret_ref | |
| row.sandbox_secret_ref = t.sandbox_secret_ref | |
| def _touch(row: TenantTool) -> None: | |
| row.revision = (row.revision or 0) + 1 | |
| row.updated_at = datetime.now(UTC) | |
| async def confirm( | |
| self, | |
| session: AsyncSession, | |
| name: str, | |
| *, | |
| tier: int, | |
| user_id: uuid.UUID, | |
| mode: str | None = None, | |
| acknowledge_risk: bool = False, | |
| ) -> TenantTool: | |
| """Owner confirms a tier (and accepts any pending definition change): pins the hash.""" | |
| row = await self.get(session, name) | |
| if row is None: | |
| raise LookupError(name) | |
| if tier not in (0, 1, 2, 3): | |
| raise ValueError("tier must be 0..3") | |
| if row.pending is not None: | |
| p = row.pending | |
| self._apply( | |
| row, | |
| NewTool( | |
| name=row.name, | |
| description=p["description"], | |
| input_schema=p["input_schema"], | |
| kind=p["kind"], | |
| config=p["config"], | |
| suggested_tier=p["suggested_tier"], | |
| definition_hash=p["definition_hash"], | |
| secret_ref=p.get("secret_ref"), | |
| sandbox_secret_ref=p.get("sandbox_secret_ref"), | |
| ), | |
| ) | |
| row.pending = None | |
| if tier < row.suggested_tier and not acknowledge_risk: | |
| raise ValueError( | |
| f"tier T{tier} is below the suggested T{row.suggested_tier}; " | |
| "set acknowledge_risk to confirm a lower tier" | |
| ) | |
| if mode is not None: | |
| if mode not in MODES: | |
| raise ValueError("mode must be test or live") | |
| row.mode = mode | |
| row.confirmed_tier = tier | |
| row.pinned_hash = row.definition_hash | |
| row.confirmed_by = user_id | |
| row.confirmed_at = datetime.now(UTC) | |
| self._touch(row) | |
| await self.reindex(session, row) | |
| self.invalidate(row.tenant_id) | |
| return row | |
| async def set_enabled(self, session: AsyncSession, name: str, enabled: bool) -> TenantTool: | |
| row = await self.get(session, name) | |
| if row is None: | |
| raise LookupError(name) | |
| row.enabled = enabled | |
| self._touch(row) | |
| await self.reindex(session, row) | |
| self.invalidate(row.tenant_id) | |
| return row | |
| async def set_mode(self, session: AsyncSession, name: str, mode: str) -> TenantTool: | |
| row = await self.get(session, name) | |
| if row is None: | |
| raise LookupError(name) | |
| if mode not in MODES: | |
| raise ValueError("mode must be test or live") | |
| if mode == "live" and row.confirmed_tier is None: | |
| raise ValueError("confirm a tier before switching a tool to live") | |
| row.mode = mode | |
| self._touch(row) | |
| self.invalidate(row.tenant_id) | |
| return row | |
| async def reindex(self, session: AsyncSession, row: TenantTool) -> None: | |
| """Keep the tenant's ``tool_index`` rows in step: enabled, unblocked tools only.""" | |
| await session.execute( | |
| delete(ToolIndexEntry).where( | |
| ToolIndexEntry.tenant_id == row.tenant_id, ToolIndexEntry.name == row.name | |
| ) | |
| ) | |
| if row.blocked_reason is None: | |
| await self.search.index_tenant_tool(session, self.spec(row), row.tenant_id, row.source) | |
| def tool_out(row: TenantTool) -> dict[str, Any]: | |
| """API view. Secret *refs* only; never values.""" | |
| return { | |
| "id": str(row.id), | |
| "name": row.name, | |
| "source": row.source, | |
| "source_id": str(row.source_id) if row.source_id else None, | |
| "kind": row.kind, | |
| "description": row.description, | |
| "input_schema": row.input_schema, | |
| "suggested_tier": row.suggested_tier, | |
| "confirmed_tier": row.confirmed_tier, | |
| "effective_tier": row.effective_tier, | |
| "enabled": row.enabled, | |
| "mode": row.mode, | |
| "secret_ref": row.secret_ref, | |
| "definition_hash": row.definition_hash, | |
| "pinned_hash": row.pinned_hash, | |
| "pending": row.pending, | |
| "blocked_reason": row.blocked_reason, | |
| "confirmed_at": row.confirmed_at, | |
| "updated_at": row.updated_at, | |
| "config": _public_config(row.config), | |
| } | |
| def _public_config(config: dict[str, Any]) -> dict[str, Any]: | |
| http = config.get("http") | |
| if not isinstance(http, dict): | |
| return {k: v for k, v in config.items() if k != "http"} | |
| return { | |
| **{k: v for k, v in config.items() if k != "http"}, | |
| "method": http.get("method"), | |
| "path": http.get("path"), | |
| "base_url": http.get("base_url"), | |
| "sandbox_base_url": http.get("sandbox_base_url"), | |
| "auth": http.get("auth"), | |
| } | |