Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions packages/datahub-ai-service/tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,23 @@ async def test_legacy_and_modern_clients(gms: FakeGms, protocol: str) -> None:
"search_documents",
"grep_documents",
"grep_entities",
"create_tag",
"add_tags",
"remove_tags",
"add_terms",
"remove_terms",
"create_glossary_term",
"add_related_terms",
"create_domain",
"set_domains",
"remove_domains",
"add_owners",
"remove_owners",
"update_description",
"add_structured_properties",
"remove_structured_properties",
"save_document",
"update_document",
]
assert result.data["data"]["corpUser"]["urn"] == "urn:li:corpuser:bob"

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
"""The fieldPath a column-level write sends, from the column a caller names.

GMS accepts a column-level write (tags, glossary terms, a description) only when
its subResource equals a fieldPath of the dataset's own schema exactly. Many
ingested schemas use v2 field paths such as ``[version=2.0].[type=string].email``,
so the column name a caller knows is not the path GMS wants. Every column-level
write resolves the name it is given here before writing.
"""

from typing import List, Mapping

from datahub.utilities.urns.field_paths import get_simple_field_path_from_v2_field_path
from fastmcp.exceptions import ToolError

from .read_backend import get_read_backend

# Suggested near matches named in a not-found error.
_MAX_SUGGESTIONS = 5


def schema_field_paths(aspects: Mapping[str, object]) -> List[str]:
"""The fieldPaths of the ``schemaMetadata`` in ``aspects``, which may be raw
aspects or a GraphQL entity selecting ``schemaMetadata { fields { fieldPath } }``.
"""
schema = aspects.get("schemaMetadata")
fields = schema.get("fields") if isinstance(schema, dict) else None
paths = [
path
for field in (fields if isinstance(fields, list) else [])
if isinstance(field, dict) and isinstance(path := field.get("fieldPath"), str)
]
return list(dict.fromkeys(paths))


def read_schema_field_paths(urn: str, *, tool: str) -> List[str]:
"""The fieldPaths of the schema GMS checks a column-level write against: the
dataset's own current ``schemaMetadata``, not a sibling's."""
try:
aspects = get_read_backend().aspects(urn)
except Exception as e:
raise ToolError(
f"{tool}: could not read the columns of {urn}, so nothing was written: {e}"
) from e
if aspects is None:
raise ToolError(f"{tool}: {urn} does not exist in DataHub.")
return schema_field_paths(aspects)


def _simple(path: str) -> str:
return get_simple_field_path_from_v2_field_path(path)


def resolve_column_path(
field_paths: List[str], column: str, *, urn: str, tool: str
) -> str:
"""The fieldPath among ``field_paths`` that ``column`` names.

``column`` is an exact fieldPath, or a column name: the path with its v2
``[...]`` tokens dropped (``email``, or ``address.city`` for a nested field),
compared exactly and then ignoring case, as get_entities matches column names.
A name that fits several columns (e.g. the branches of a v2 union) is refused
rather than guessed.
"""
if column in field_paths:
return column
if not field_paths:
raise ToolError(
f"{tool}: column {column!r} is not in the schema of {urn}: the dataset "
"has no schema fields."
)
name = _simple(column)
simple_paths = {path: _simple(path) for path in field_paths}
matches = [path for path, simple in simple_paths.items() if simple == name] or [
path for path, simple in simple_paths.items() if simple.lower() == name.lower()
]
if len(matches) == 1:
return matches[0]
if matches:
raise ToolError(
f"{tool}: column {column!r} matches {len(matches)} columns of {urn}: "
f"{', '.join(repr(m) for m in matches)}. Pass the exact fieldPath of the "
"one you mean, as list_schema_fields returns it."
)
leaf = name.rsplit(".", 1)[-1].lower()
suggestions = [
path
for path, simple in simple_paths.items()
if simple.rsplit(".", 1)[-1].lower() == leaf
][:_MAX_SUGGESTIONS]
hint = (
f" Columns with that name: {', '.join(repr(s) for s in suggestions)}."
if suggestions
else ""
)
raise ToolError(
f"{tool}: column {column!r} is not in the schema of {urn}.{hint} Find "
"its exact path with list_schema_fields."
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
"""Host-provided rules for which fields of a document the document tools may change.

The tools call :func:`ensure_document_editable` on the document they already fetched,
naming the fields their command would change. With no provider installed every edit
is allowed. A host locks fields by registering a :class:`DocumentEditPolicy` factory
under the ``datahub.mcp.document_edit_policy`` entry point group, so host-specific
document kinds never need to be known here.
"""

import functools
import importlib.metadata
from typing import FrozenSet, Literal, Optional, Protocol

from datahub.errors import ItemNotFoundError
from datahub.sdk.document import Document
from fastmcp.exceptions import ToolError
from loguru import logger

from . import graphql_helpers

ENTRY_POINT_GROUP = "datahub.mcp.document_edit_policy"

DocumentField = Literal[
"title",
"content",
"type",
"topics",
"related_documents",
"related_assets",
"status",
"parent",
]


class DocumentEditPolicy(Protocol):
def ensure_editable(self, doc: Document, fields: FrozenSet[DocumentField]) -> None:
"""Raise ``ToolError`` with an actionable message if any field is locked."""
...


@functools.lru_cache(maxsize=1)
def _load_policy() -> Optional[DocumentEditPolicy]:
providers = list(importlib.metadata.entry_points(group=ENTRY_POINT_GROUP))
if not providers:
return None
if len(providers) > 1:
names = ", ".join(sorted(p.value for p in providers))
raise RuntimeError(f"More than one {ENTRY_POINT_GROUP} provider: {names}")
# A declared provider that fails to load raises instead of allowing every edit:
# silently dropping the host's locks would be the worse failure.
return providers[0].load()()


def ensure_document_editable(doc: Document, fields: FrozenSet[DocumentField]) -> None:
"""Raise ``ToolError`` if the installed policy locks any of ``fields`` on ``doc``."""
policy = _load_policy()
if policy is not None and fields:
policy.ensure_editable(doc, fields)


def document_edit_refusal(urn: str, fields: FrozenSet[DocumentField]) -> Optional[str]:
"""The policy's refusal for editing ``fields`` of ``urn``, or None.

For pre-approval validators, which run before a human is asked to approve the
call. Fails open when the document can't be fetched or isn't a Document: the
tool runs the same check on the document it fetches, which stays the backstop.
"""
if not fields or _load_policy() is None:
return None
try:
doc = graphql_helpers.get_datahub_client().entities.get(urn)
except ItemNotFoundError:
return None
except Exception:
logger.opt(exception=True).warning(
"Could not fetch {} to check its edit policy before approval", urn
)
return None
if not isinstance(doc, Document):
return None
try:
ensure_document_editable(doc, fields)
except ToolError as e:
return str(e)
return None


def clear_document_edit_policy_cache() -> None:
"""Drop the loaded policy. For tests that install or remove a provider."""
_load_policy.cache_clear()
Loading
Loading