Spaces:
Running

WorkPilot-AI / core /api /routes /extensibility.py
Aynkhn's picture
Deploy WorkPilot demo
fd5dd94 verified
Raw History Blame Contribute Delete
24.3 kB
"""Runtime extensibility API (Phase 16): tenant tools, OpenAPI import, MCP servers,
connectors, mapped webhooks and natural-language rules.
Reads need manager; anything that changes what the agent may do (imports, tier
confirmations, enabling tools, connecting servers, confirming rules) is **owner-only**.
Secrets are never accepted or returned here: requests name a secret *ref* that resolves
from the secret store (``WP_SECRET_<REF>``) at execution time.
Injectable for tests (``app.state``): ``spec_fetcher`` (OpenAPI URL fetcher), ``rules_llm``
(planner model for rule compilation); ``services.tenant_tools.transport`` /
``.mcp_connect`` for HTTP and MCP traffic.
"""
from __future__ import annotations
import base64
import binascii
import json
import uuid
from typing import Any, Literal
from fastapi import APIRouter, Depends, HTTPException, Request, status
from pydantic import BaseModel, Field, field_validator
from sqlalchemy import select
from core.agent.models import LLM, ModelTiers
from core.api.routes.events import _endpoint, _ingest, dispatcher
from core.api.routes.runs import services
from core.auth.deps import Principal, require_role
from core.channels.secrets import valid_ref
from core.connectors.models import ConnectorConfig
from core.connectors.service import ConnectorError, ConnectorService, map_webhook
from core.connectors.tables import TableError
from core.events.intake import PayloadError, SignatureError, normalize_generic, verify_webhook
from core.events.workers import Dispatcher
from core.gateway.gateway import ToolCall
from core.mcp.client import McpError, McpService
from core.mcp.models import McpConnection
from core.rules.models import PolicyRule
from core.rules.service import RuleError, RuleService, build_catalog, rule_out
from core.services import Services
from core.tenancy.models import Role
from core.tools.http_tool import HttpAuth, UnsafeURL, check_url
from core.tools.openapi_import import (
OpenAPIImportError,
fetch_spec,
import_operations,
parse_spec,
)
from core.tools.tenant_tools import ImportReport, NewTool, TenantToolStore, tool_out
router = APIRouter(tags=["extensibility"])
MAX_WEBHOOK_BYTES = 1_000_000
def _store(svc: Services) -> TenantToolStore:
if svc.tenant_tools is None:
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, "tenant tools are not enabled")
return svc.tenant_tools
def _ref(value: str | None) -> str | None:
if value is not None and not valid_ref(value):
raise ValueError("invalid secret ref (letters, digits and . _ : / - only)")
return value
def _report(r: ImportReport) -> dict[str, list[str]]:
return {
"created": r.created,
"changed": r.changed,
"removed": r.removed,
"unchanged": r.unchanged,
}
def _bad(exc: Exception) -> HTTPException:
return HTTPException(422, str(exc))
# ------------------------------------------------------------------------- tools
@router.get("/ext/tools")
async def list_tenant_tools(
p: Principal = Depends(require_role(Role.MANAGER)), svc: Services = Depends(services)
) -> list[dict[str, Any]]:
store = _store(svc)
async with svc.db.session(tenant_id=p.tenant_id) as s:
return [tool_out(r) for r in await store.list_tools(s)]
class ConfirmIn(BaseModel):
tier: int = Field(ge=0, le=3)
mode: Literal["test", "live"] | None = None
acknowledge_risk: bool = False
@router.post("/ext/tools/{name}/confirm")
async def confirm_tool(
name: str,
body: ConfirmIn,
p: Principal = Depends(require_role(Role.OWNER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
store = _store(svc)
async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
try:
row = await store.confirm(
s,
name,
tier=body.tier,
user_id=p.user_id,
mode=body.mode,
acknowledge_risk=body.acknowledge_risk,
)
except LookupError as exc:
raise HTTPException(status.HTTP_404_NOT_FOUND, "unknown tool") from exc
except ValueError as exc:
raise _bad(exc) from exc
return tool_out(row)
class ToggleIn(BaseModel):
enabled: bool | None = None
mode: Literal["test", "live"] | None = None
@router.post("/ext/tools/{name}/settings")
async def update_tool(
name: str,
body: ToggleIn,
p: Principal = Depends(require_role(Role.OWNER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
store = _store(svc)
async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
try:
row = None
if body.enabled is not None:
row = await store.set_enabled(s, name, body.enabled)
if body.mode is not None:
row = await store.set_mode(s, name, body.mode)
row = row or await store.get(s, name)
except LookupError as exc:
raise HTTPException(status.HTTP_404_NOT_FOUND, "unknown tool") from exc
except ValueError as exc:
raise _bad(exc) from exc
if row is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "unknown tool")
return tool_out(row)
class TestCallIn(BaseModel):
args: dict[str, Any] = Field(default_factory=dict)
@router.post("/ext/tools/{name}/test")
async def test_tool(
name: str,
body: TestCallIn,
p: Principal = Depends(require_role(Role.MANAGER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
"""Dry run through the gateway: validation, policy and the would-be request; no effect."""
outcome = await svc.gateway.execute(
ToolCall(tenant_id=p.tenant_id, actor=p.actor, tool=name, args=body.args, dry_run=True)
)
return outcome.model_dump(mode="json")
# ----------------------------------------------------------------------- OpenAPI
class OpenAPIImportIn(BaseModel):
name: str = Field(pattern=r"^[a-z][a-z0-9_]{1,39}$", description="tool name prefix")
spec: str | dict[str, Any] | None = None
url: str | None = Field(default=None, max_length=500)
base_url: str | None = Field(default=None, max_length=500)
sandbox_base_url: str | None = Field(default=None, max_length=500)
secret_ref: str | None = None
sandbox_secret_ref: str | None = None
auth: HttpAuth | None = None
@field_validator("secret_ref", "sandbox_secret_ref")
@classmethod
def check_refs(cls, v: str | None) -> str | None:
return _ref(v)
def _new_tools(body: OpenAPIImportIn, doc: dict[str, Any]) -> list[NewTool]:
ops = import_operations(
doc,
prefix=body.name,
base_url=body.base_url,
sandbox_base_url=body.sandbox_base_url,
auth=body.auth,
)
if body.secret_ref is None: # no credential: don't present one
ops = [o.model_copy(update={"http": o.http.model_copy(update={"auth": None})}) for o in ops]
return [
NewTool(
name=o.name,
description=o.description,
input_schema=o.input_schema,
kind="http",
config={"http": o.http.model_dump(mode="json"), "operation_id": o.operation_id},
suggested_tier=o.suggested_tier,
definition_hash=o.definition_hash(),
secret_ref=body.secret_ref,
sandbox_secret_ref=body.sandbox_secret_ref,
)
for o in ops
]
@router.post("/ext/openapi/import")
async def import_openapi(
body: OpenAPIImportIn,
request: Request,
p: Principal = Depends(require_role(Role.OWNER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
"""Each operation becomes a tool ``<name>.<operation>``: T3 and test mode until an owner
confirms it. Re-importing the same name updates the set (changes need re-confirmation)."""
store = _store(svc)
if (body.spec is None) == (body.url is None):
raise HTTPException(422, "give exactly one of spec, url")
try:
if body.url is not None:
doc = await fetch_spec(body.url, getattr(request.app.state, "spec_fetcher", None))
else:
assert body.spec is not None
doc = parse_spec(body.spec)
tools = _new_tools(body, doc)
except (OpenAPIImportError, UnsafeURL, ValueError) as exc:
raise _bad(exc) from exc
source_id = uuid.uuid5(uuid.NAMESPACE_URL, f"openapi:{p.tenant_id}:{body.name}")
async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
try:
report = await store.sync(s, p.tenant_id, tools, source="openapi", source_id=source_id)
except ValueError as exc:
raise HTTPException(status.HTTP_409_CONFLICT, str(exc)) from exc
rows = await store.list_tools(s, source_id)
return {"report": _report(report), "tools": [tool_out(r) for r in rows]}
# --------------------------------------------------------------------------- MCP
class McpConnectIn(BaseModel):
name: str = Field(pattern=r"^[a-z][a-z0-9_]{1,39}$")
url: str = Field(max_length=500)
auth_type: Literal["none", "bearer"] = "none"
secret_ref: str | None = None
payment_capable: bool = False # Phase 15: isolate from inbox-reading runs
@field_validator("secret_ref")
@classmethod
def check_refs(cls, v: str | None) -> str | None:
return _ref(v)
def _conn_out(c: McpConnection) -> dict[str, Any]:
return {
"id": str(c.id),
"name": c.name,
"url": c.url,
"auth_type": c.auth_type,
"secret_ref": c.secret_ref,
"enabled": c.enabled,
"payment_capable": c.payment_capable,
"status": c.status,
"last_refreshed_at": c.last_refreshed_at,
"last_diff": c.last_diff,
}
@router.get("/ext/mcp")
async def list_mcp(
p: Principal = Depends(require_role(Role.MANAGER)), svc: Services = Depends(services)
) -> list[dict[str, Any]]:
async with svc.db.session(tenant_id=p.tenant_id) as s:
rows = (await s.execute(select(McpConnection).order_by(McpConnection.name))).scalars()
return [_conn_out(c) for c in rows]
@router.post("/ext/mcp")
async def connect_mcp(
body: McpConnectIn,
p: Principal = Depends(require_role(Role.OWNER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
mcp = McpService(_store(svc))
try:
check_url(body.url)
listed = await mcp.list_remote(body.url, body.auth_type, body.secret_ref)
except (UnsafeURL, McpError) as exc:
raise _bad(exc) from exc
async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
if await mcp.by_name(s, body.name) is not None:
raise HTTPException(status.HTTP_409_CONFLICT, "a connection with this name exists")
try:
await mcp.check_secret_scope(s, body.secret_ref, body.url, body.name)
except McpError as exc:
raise HTTPException(status.HTTP_409_CONFLICT, str(exc)) from exc
conn = McpConnection(
tenant_id=p.tenant_id,
name=body.name,
url=body.url,
auth_type=body.auth_type,
secret_ref=body.secret_ref,
enabled=True,
payment_capable=body.payment_capable,
status="new",
last_diff={},
)
s.add(conn)
await s.flush()
try:
report = await mcp.sync(s, conn, listed)
except ValueError as exc:
raise HTTPException(status.HTTP_409_CONFLICT, str(exc)) from exc
return {"connection": _conn_out(conn), "report": _report(report)}
@router.post("/ext/mcp/{name}/refresh")
async def refresh_mcp(
name: str,
p: Principal = Depends(require_role(Role.OWNER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
"""Re-list the server's tools. Changed definitions are blocked until re-confirmed."""
mcp = McpService(_store(svc))
async with svc.db.session(tenant_id=p.tenant_id) as s:
conn = await mcp.by_name(s, name)
if conn is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "unknown connection")
url, auth_type, ref = conn.url, conn.auth_type, conn.secret_ref
try:
listed = await mcp.list_remote(url, auth_type, ref)
except McpError as exc:
raise _bad(exc) from exc
async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
conn = await mcp.by_name(s, name)
assert conn is not None
report = await mcp.sync(s, conn, listed)
changed = []
for tool_name in report.changed:
row = await _store(svc).get(s, tool_name)
if row is not None and row.pending is not None:
changed.append(
{
"name": tool_name,
"pinned_hash": row.pinned_hash,
"new_hash": row.pending.get("definition_hash"),
"before": {
"description": row.description,
"input_schema": row.input_schema,
},
"after": {
"description": row.pending.get("description"),
"input_schema": row.pending.get("input_schema"),
},
}
)
return {"connection": _conn_out(conn), "report": _report(report), "changes": changed}
# -------------------------------------------------------------------- connectors
class ConnectorIn(BaseModel):
kind: Literal["google_sheets", "table", "webhook", "http_action"]
name: str = Field(pattern=r"^[a-z][a-z0-9_]{1,39}$")
config: dict[str, Any] = Field(default_factory=dict)
secret_ref: str | None = None
@field_validator("secret_ref")
@classmethod
def check_refs(cls, v: str | None) -> str | None:
return _ref(v)
def _connector_out(c: ConnectorConfig) -> dict[str, Any]:
return {
"id": str(c.id),
"kind": c.kind,
"name": c.name,
"config": c.config,
"secret_ref": c.secret_ref,
"enabled": c.enabled,
"updated_at": c.updated_at,
}
async def _connector(s: Any, name: str) -> ConnectorConfig:
c = (
await s.execute(select(ConnectorConfig).where(ConnectorConfig.name == name))
).scalar_one_or_none()
if c is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "unknown connector")
return c
@router.get("/ext/connectors")
async def list_connectors(
p: Principal = Depends(require_role(Role.MANAGER)), svc: Services = Depends(services)
) -> list[dict[str, Any]]:
async with svc.db.session(tenant_id=p.tenant_id) as s:
rows = (await s.execute(select(ConnectorConfig).order_by(ConnectorConfig.name))).scalars()
return [_connector_out(c) for c in rows]
@router.post("/ext/connectors")
async def create_connector(
body: ConnectorIn,
p: Principal = Depends(require_role(Role.OWNER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
service = ConnectorService(_store(svc))
async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
existing = (
await s.execute(select(ConnectorConfig).where(ConnectorConfig.name == body.name))
).scalar_one_or_none()
if existing is not None:
raise HTTPException(status.HTTP_409_CONFLICT, "a connector with this name exists")
try:
conn, report = await service.create(
s,
p.tenant_id,
kind=body.kind,
name=body.name,
config=body.config,
secret_ref=body.secret_ref,
)
except (ConnectorError, UnsafeURL, ValueError) as exc:
raise _bad(exc) from exc
return {"connector": _connector_out(conn), "report": _report(report)}
class UploadIn(BaseModel):
filename: str = Field(default="upload.csv", max_length=200)
content_base64: str = Field(max_length=7_000_000)
replace: bool = True
@router.post("/ext/connectors/{name}/upload")
async def upload_table(
name: str,
body: UploadIn,
p: Principal = Depends(require_role(Role.OWNER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
try:
content = base64.b64decode(body.content_base64, validate=True)
except (binascii.Error, ValueError) as exc:
raise _bad(ValueError("content_base64 is not valid base64")) from exc
service = ConnectorService(_store(svc))
async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
conn = await _connector(s, name)
try:
return await service.upload(s, conn, content, body.filename, replace=body.replace)
except (ConnectorError, TableError, ValueError) as exc:
raise _bad(exc) from exc
@router.delete("/ext/connectors/{name}")
async def delete_connector(
name: str,
p: Principal = Depends(require_role(Role.OWNER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
store = _store(svc)
async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
conn = await _connector(s, name)
report = await store.sync(s, p.tenant_id, [], source="connector", source_id=conn.id)
await s.delete(conn)
return {"deleted": name, "disabled_tools": report.removed}
@router.post("/ext/webhooks/{token}")
async def receive_mapped_webhook(
token: str,
request: Request,
svc: Services = Depends(services),
d: Dispatcher = Depends(dispatcher),
) -> dict[str, Any]:
"""A tenant's own webhook format: verified with the generic endpoint's HMAC secret, then
mapped to ``{type, text, payload, id}`` by the tenant's ``webhook`` connector and fed to
the same intake as ``/webhooks/generic/<token>`` (dedupe, durable dispatch)."""
ep = await _endpoint(svc, "generic", token)
body = await request.body()
if len(body) > MAX_WEBHOOK_BYTES:
raise HTTPException(status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, "body too large")
headers = {k.lower(): v for k, v in request.headers.items()}
try:
verify_webhook("generic", ep.secret, body, headers)
except SignatureError as exc:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "bad signature") from exc
async with svc.db.session(tenant_id=ep.tenant_id) as s:
mapping = next(
(
c
for c in (
await s.execute(
select(ConnectorConfig).where(
ConnectorConfig.kind == "webhook", ConnectorConfig.enabled.is_(True)
)
)
).scalars()
if c.config.get("endpoint_id") == str(ep.id)
),
None,
)
if mapping is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "no mapping for this webhook")
try:
data = json.loads(body or b"{}")
if not isinstance(data, dict):
raise PayloadError("payload must be a JSON object")
mapped = map_webhook(mapping.config, data)
events = normalize_generic(json.dumps(mapped).encode(), headers)
except (ValueError, PayloadError) as exc:
raise HTTPException(status.HTTP_400_BAD_REQUEST, str(exc)) from exc
recorded = await _ingest(svc, d, ep.tenant_id, events)
return {
"type": mapped["type"],
"accepted": sum(not r.duplicate for r in recorded),
"events": [{"event_id": str(r.event_id), "duplicate": r.duplicate} for r in recorded],
}
# ------------------------------------------------------------------------- rules
def rules_llm(request: Request) -> LLM:
llm: LLM | None = getattr(request.app.state, "rules_llm", None)
if llm is not None:
return llm
svc: Services = request.app.state.services
if svc.runtime is not None:
return svc.runtime.models.planner
return ModelTiers.from_settings().planner
class CompileIn(BaseModel):
text: str = Field(min_length=3, max_length=500)
rule_key: uuid.UUID | None = None # a new version of an existing rule
samples: list[dict[str, Any]] = Field(default_factory=list, max_length=20)
@router.get("/ext/rules")
async def list_rules(
p: Principal = Depends(require_role(Role.MANAGER)), svc: Services = Depends(services)
) -> list[dict[str, Any]]:
async with svc.db.session(tenant_id=p.tenant_id) as s:
rows = (
await s.execute(
select(PolicyRule).order_by(PolicyRule.created_at.desc(), PolicyRule.version.desc())
)
).scalars()
return [rule_out(r) for r in rows]
@router.post("/ext/rules/compile")
async def compile_rule(
body: CompileIn,
p: Principal = Depends(require_role(Role.MANAGER)),
svc: Services = Depends(services),
llm: LLM = Depends(rules_llm),
) -> dict[str, Any]:
"""Compile to a *draft* (no effect until an owner confirms it)."""
rules = RuleService(svc.policy)
async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
catalog = await build_catalog(s, svc.registry, svc.tenant_tools)
try:
row = await rules.compile(
s,
p.tenant_id,
text=body.text,
llm=llm,
catalog=catalog,
user_id=p.user_id,
rule_key=body.rule_key,
samples=body.samples,
)
except RuleError as exc:
raise HTTPException(
422,
{"message": str(exc), "errors": exc.errors, "question": exc.question},
) from exc
return rule_out(row)
class RuleConfirmIn(BaseModel):
allow_permit: bool = False
@router.post("/ext/rules/{rule_id}/confirm")
async def confirm_rule(
rule_id: uuid.UUID,
body: RuleConfirmIn,
p: Principal = Depends(require_role(Role.OWNER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
rules = RuleService(svc.policy)
async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
catalog = await build_catalog(s, svc.registry, svc.tenant_tools)
try:
row = await rules.confirm(
s, rule_id, user_id=p.user_id, allow_permit=body.allow_permit, catalog=catalog
)
except LookupError as exc:
raise HTTPException(status.HTTP_404_NOT_FOUND, "unknown rule") from exc
except RuleError as exc:
raise HTTPException(422, {"message": str(exc), "errors": exc.errors}) from exc
return rule_out(row)
@router.post("/ext/rules/{rule_key}/rollback")
async def rollback_rule(
rule_key: uuid.UUID,
p: Principal = Depends(require_role(Role.OWNER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
rules = RuleService(svc.policy)
async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
try:
previous = await rules.rollback(s, rule_key)
except RuleError as exc:
raise HTTPException(status.HTTP_409_CONFLICT, str(exc)) from exc
return {"active": rule_out(previous) if previous is not None else None}
@router.post("/ext/rules/{rule_key}/disable")
async def disable_rule(
rule_key: uuid.UUID,
p: Principal = Depends(require_role(Role.OWNER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
rules = RuleService(svc.policy)
async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
await rules.disable(s, rule_key)
return {"disabled": str(rule_key)}