This is an automated email from the ASF dual-hosted git repository.

jerryshao pushed a commit to branch branch-domain-dev
in repository https://gitbox.apache.org/repos/asf/gravitino.git


The following commit(s) were added to refs/heads/branch-domain-dev by this push:
     new d9a80b6251 [#14892] feat(mcp): Add read-only Domain tools (#14893)
d9a80b6251 is described below

commit d9a80b6251e69d6e6b13c073545777d595ec4820
Author: Jerry Shao <[email protected]>
AuthorDate: Thu Nov 12 09:53:33 2026 +0800

    [#14892] feat(mcp): Add read-only Domain tools (#14893)
    
    ### What changes were proposed in this pull request?
    
    Add five read-only Domain MCP tools, REST client wiring,
    tool annotations, tests and documentation. Preserve complete
    relations, repeated domain filters and encoded paths.
    
    ### Why are the changes needed?
    
    Allow agents to discover Domain metadata using the caller's
    Gravitino identity and permissions.
    
    Fixes #14892
    
    ### Does this PR introduce _any_ user-facing change?
    
    Adds the domain tool group. No Domain write tools are exposed.
    
    ### How was this patch tested?
    
    Formatting checks, pylint (10/10), and all 307 MCP tests passed.
    An isolated H2 smoke test exercised all five tools and the
    three relation types.
---
 docs/gravitino-mcp-server.md                       |  45 +++
 mcp-server/mcp_server/client/__init__.py           |   1 +
 mcp-server/mcp_server/client/domain_operation.py   |  61 +++
 .../mcp_server/client/gravitino_operation.py       |   6 +
 .../plain/plain_rest_client_domain_operation.py    | 107 ++++++
 .../client/plain/plain_rest_client_operation.py    |  10 +
 mcp-server/mcp_server/tools/__init__.py            |   3 +
 mcp-server/mcp_server/tools/domain.py              | 121 ++++++
 mcp-server/tests/unit/tools/mock_operation.py      |  31 ++
 mcp-server/tests/unit/tools/test_domain.py         | 415 +++++++++++++++++++++
 10 files changed, 800 insertions(+)

diff --git a/docs/gravitino-mcp-server.md b/docs/gravitino-mcp-server.md
index 086e744a6a..85f032903a 100644
--- a/docs/gravitino-mcp-server.md
+++ b/docs/gravitino-mcp-server.md
@@ -193,6 +193,51 @@ an ordered, non-empty `updates` array. Supported `@type` 
values are `rename`,
 `drop_semantic_model` takes the model's catalog, schema, and name and returns 
a JSON boolean
 indicating whether it was dropped. It removes semantic metadata without 
deleting source tables or data.
 
+### Domains (read-only)
+
+Use `--include-tool-tags domain` to expose the five Domain tools.
+All are annotated as read-only and idempotent and issue only GET requests.
+
+| Tool | Arguments | Result |
+|------|-----------|--------|
+| `list_of_domains` | `details=true` | Domain snapshots, or names when false |
+| `get_domain_by_name` | `domain_name` | A complete domain snapshot |
+| `list_subdomains` | `domain_name`, `details=true` | Immediate subdomain 
snapshots or names |
+| `list_domain_members` | `domain_name`, optional `types`, `domains`, 
`name_contains` | Recorded leaf members with all applicable relations |
+| `list_domains_for_metadata` | `metadata_type`, `metadata_full_name`, 
`details=true` | Domains of a leaf object, including all relations when details 
is true |
+
+Results follow the existing MCP JSON-string convention; empty lists return 
`[]`.
+Snapshots retain the server's backing tag, status, parent, properties, audit 
and
+relation information. Relations can be `direct`, `inherited` (with the catalog 
or
+schema source), or `via_subdomain` (with the source domain). Multiple relations
+for the same member or domain remain intact. Names-only results omit relations.
+
+For example, call `list_domain_members` with:
+
+```json
+{
+  "domain_name": "sales",
+  "types": ["TABLE", "TOPIC"],
+  "domains": ["regional,sales", "online"],
+  "name_contains": "orders"
+}
+```
+
+`types` is a list of leaf object types; `domains` filters source domain names
+using repeated query parameters, preserving commas inside names.
+`name_contains` is passed as the REST `nameContains` substring filter.
+Omitted or empty type/domain lists leave those filters unset.
+Leaf lookups support tables, filesets, topics, models, views and semantic 
models;
+use the REST object type spelling (for example `table` or `semantic_model`).
+Paths and filter values are URL encoded. Requests use the caller's existing
+Gravitino authentication, and server authorization, validation and not-found
+errors propagate through the standard MCP error handling. Results reflect the
+caller's visibility; no client-side hierarchy expansion or relation inference
+is performed.
+
+No Domain creation, modification, deletion, publishing, parent changes or
+binding changes are exposed. Existing tools in other groups retain their 
behavior.
+
 ## Configuration
 
 You could config Gravitino MCP server by arguments, `uv run mcp_server -h` 
shows the detailed information.
diff --git a/mcp-server/mcp_server/client/__init__.py 
b/mcp-server/mcp_server/client/__init__.py
index 3565de2007..60af781e67 100644
--- a/mcp-server/mcp_server/client/__init__.py
+++ b/mcp-server/mcp_server/client/__init__.py
@@ -16,6 +16,7 @@
 # under the License.
 
 from mcp_server.client.catalog_operation import CatalogOperation
+from mcp_server.client.domain_operation import DomainOperation
 from mcp_server.client.gravitino_operation import GravitinoOperation
 from mcp_server.client.job_operation import JobOperation
 from mcp_server.client.metalake_operation import MetalakeOperation
diff --git a/mcp-server/mcp_server/client/domain_operation.py 
b/mcp-server/mcp_server/client/domain_operation.py
new file mode 100644
index 0000000000..50086b541e
--- /dev/null
+++ b/mcp-server/mcp_server/client/domain_operation.py
@@ -0,0 +1,61 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from abc import ABC, abstractmethod
+
+
+class DomainOperation(ABC):
+    """Read-only domain operations."""
+
+    @abstractmethod
+    async def list_of_domains(self, details: bool = True) -> str:
+        """List domains; details includes backingTag, status, parent and 
audit."""
+
+    @abstractmethod
+    async def get_domain_by_name(self, domain_name: str) -> str:
+        """Load a domain snapshot by name."""
+
+    @abstractmethod
+    async def list_subdomains(
+        self, domain_name: str, details: bool = True
+    ) -> str:
+        """List immediate subdomains, as names or complete snapshots."""
+
+    @abstractmethod
+    async def list_domain_members(
+        self,
+        domain_name: str,
+        types: list[str] | None = None,
+        domains: list[str] | None = None,
+        name_contains: str | None = None,
+    ) -> str:
+        """List recorded leaf members and all applicable relations.
+
+        types filters leaf object types (for example TABLE and TOPIC).
+        domains filters source domain names; name_contains is a literal 
substring.
+        """
+
+    @abstractmethod
+    async def list_domains_for_metadata(
+        self, metadata_full_name: str, metadata_type: str, details: bool = True
+    ) -> str:
+        """List domains for a leaf metadata object.
+
+        metadata_type supports table, fileset, topic, model, view and 
semantic_model.
+        metadata_full_name is the qualified object name, such as 
catalog.schema.table.
+        details preserves all relations and their sources; false returns names 
only.
+        """
diff --git a/mcp-server/mcp_server/client/gravitino_operation.py 
b/mcp-server/mcp_server/client/gravitino_operation.py
index 15114c2d68..8c4bd3c025 100644
--- a/mcp-server/mcp_server/client/gravitino_operation.py
+++ b/mcp-server/mcp_server/client/gravitino_operation.py
@@ -18,6 +18,7 @@
 from abc import ABC, abstractmethod
 
 from mcp_server.client.catalog_operation import CatalogOperation
+from mcp_server.client.domain_operation import DomainOperation
 from mcp_server.client.fileset_operation import FilesetOperation
 from mcp_server.client.job_operation import JobOperation
 from mcp_server.client.metalake_operation import MetalakeOperation
@@ -171,3 +172,8 @@ class GravitinoOperation(ABC):
             MetalakeOperation: Interface for metalake-level operations
         """
         pass
+
+    @abstractmethod
+    def as_domain_operation(self) -> DomainOperation:
+        """Access the read-only domain operation interface."""
+        pass
diff --git 
a/mcp-server/mcp_server/client/plain/plain_rest_client_domain_operation.py 
b/mcp-server/mcp_server/client/plain/plain_rest_client_domain_operation.py
new file mode 100644
index 0000000000..4193f2858b
--- /dev/null
+++ b/mcp-server/mcp_server/client/plain/plain_rest_client_domain_operation.py
@@ -0,0 +1,107 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from mcp_server.client.domain_operation import DomainOperation
+from mcp_server.client.plain.utils import (
+    encode_path_segment,
+    extract_content_from_response,
+)
+
+
+class PlainRESTClientDomainOperation(DomainOperation):
+    """Read domain snapshots without projecting away governance information."""
+
+    def __init__(self, metalake_name: str, rest_client):
+        self._metalake_name = metalake_name
+        self._rest_client = rest_client
+
+    @property
+    def _path(self) -> str:
+        # Metalake discovery can construct a client without a selected 
metalake.
+        # Validate the scope only when a domain request actually needs it.
+        return (
+            
f"/api/metalakes/{encode_path_segment(self._metalake_name)}/domains"
+        )
+
+    @property
+    def _object_path(self) -> str:
+        return (
+            
f"/api/metalakes/{encode_path_segment(self._metalake_name)}/objects"
+        )
+
+    async def _list(self, path: str, details: bool) -> str:
+        response = await self._rest_client.get(
+            path, params={"details": str(details).lower()}
+        )
+        return self._extract(response, "domains" if details else "names", [])
+
+    async def list_of_domains(self, details: bool = True) -> str:
+        return await self._list(self._path, details)
+
+    async def get_domain_by_name(self, domain_name: str) -> str:
+        response = await self._rest_client.get(
+            f"{self._path}/{encode_path_segment(domain_name)}"
+        )
+        return self._extract(response, "domain", {})
+
+    async def list_subdomains(
+        self, domain_name: str, details: bool = True
+    ) -> str:
+        return await self._list(
+            f"{self._path}/{encode_path_segment(domain_name)}/subdomains",
+            details,
+        )
+
+    async def list_domain_members(
+        self,
+        domain_name: str,
+        types: list[str] | None = None,
+        domains: list[str] | None = None,
+        name_contains: str | None = None,
+    ) -> str:
+        # Repeated query parameters preserve commas and other characters in 
domain names.
+        params = []
+        if types:
+            params.append(("types", ",".join(types)))
+        if domains:
+            params.extend(("domains", domain) for domain in domains)
+        if name_contains is not None:
+            params.append(("nameContains", name_contains))
+
+        response = await self._rest_client.get(
+            f"{self._path}/{encode_path_segment(domain_name)}/objects",
+            params=params,
+        )
+        return self._extract(response, "members", [])
+
+    async def list_domains_for_metadata(
+        self, metadata_full_name: str, metadata_type: str, details: bool = True
+    ) -> str:
+        return await self._list(
+            f"{self._object_path}/{encode_path_segment(metadata_type)}"
+            f"/{encode_path_segment(metadata_full_name)}/domains",
+            details,
+        )
+
+    @staticmethod
+    def _extract(response, field: str, default) -> str:
+        # Preserve structured Gravitino errors before checking HTTP status.
+        # Gateways may return JSON without a Gravitino error code; these must
+        # never turn authentication failures into successful empty results.
+        content = extract_content_from_response(response, field, default)
+        response.raise_for_status()
+        return content
diff --git a/mcp-server/mcp_server/client/plain/plain_rest_client_operation.py 
b/mcp-server/mcp_server/client/plain/plain_rest_client_operation.py
index 74afefdac2..16e0c7a664 100644
--- a/mcp-server/mcp_server/client/plain/plain_rest_client_operation.py
+++ b/mcp-server/mcp_server/client/plain/plain_rest_client_operation.py
@@ -29,10 +29,14 @@ from mcp_server.client import (
     TableOperation,
     TagOperation,
 )
+from mcp_server.client.domain_operation import DomainOperation
 from mcp_server.client.job_operation import JobOperation
 from mcp_server.client.plain.plain_rest_client_catalog_operation import (
     PlainRESTClientCatalogOperation,
 )
+from mcp_server.client.plain.plain_rest_client_domain_operation import (
+    PlainRESTClientDomainOperation,
+)
 from mcp_server.client.plain.plain_rest_client_fileset_operation import (
     PlainRESTClientFilesetOperation,
 )
@@ -121,6 +125,9 @@ class PlainRESTClientOperation(GravitinoOperation):
         self._model_operation = PlainRESTClientModelOperation(
             metalake_name, _rest_client
         )
+        self._domain_operation = PlainRESTClientDomainOperation(
+            metalake_name, _rest_client
+        )
         self._tag_operation = PlainRESTClientTagOperation(
             metalake_name, _rest_client
         )
@@ -195,3 +202,6 @@ class PlainRESTClientOperation(GravitinoOperation):
 
     def as_semantic_model_operation(self) -> SemanticModelOperation:
         return self._semantic_model_operation
+
+    def as_domain_operation(self) -> DomainOperation:
+        return self._domain_operation
diff --git a/mcp-server/mcp_server/tools/__init__.py 
b/mcp-server/mcp_server/tools/__init__.py
index 86562bdf12..e02ae8ed69 100644
--- a/mcp-server/mcp_server/tools/__init__.py
+++ b/mcp-server/mcp_server/tools/__init__.py
@@ -18,6 +18,7 @@
 from fastmcp import FastMCP
 
 from mcp_server.tools.catalog import load_catalog_tools
+from mcp_server.tools.domain import load_domain_tools
 from mcp_server.tools.fileset import load_fileset_tools
 from mcp_server.tools.job import load_job_tool
 from mcp_server.tools.metadata import load_metadata_tool
@@ -37,6 +38,7 @@ from mcp_server.tools.view import load_view_tools
 SUPPORTED_TOOL_TAGS = frozenset(
     {
         "catalog",
+        "domain",
         "fileset",
         "job",
         "metalake",
@@ -55,6 +57,7 @@ SUPPORTED_TOOL_TAGS = frozenset(
 
 
 def load_tools(mcp: FastMCP):
+    load_domain_tools(mcp)
     load_job_tool(mcp)
     load_catalog_tools(mcp)
     load_schema_tools(mcp)
diff --git a/mcp-server/mcp_server/tools/domain.py 
b/mcp-server/mcp_server/tools/domain.py
new file mode 100644
index 0000000000..eafa4afdc6
--- /dev/null
+++ b/mcp-server/mcp_server/tools/domain.py
@@ -0,0 +1,121 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from fastmcp import Context, FastMCP
+
+_READONLY_TOOL_ANNOTATIONS = {
+    "readOnlyHint": True,
+    "destructiveHint": False,
+    "idempotentHint": True,
+}
+
+
+def load_domain_tools(mcp: FastMCP):
+    """Register only read-only domain tools."""
+
+    @mcp.tool(
+        tags={"domain"},
+        annotations=_READONLY_TOOL_ANNOTATIONS,
+    )
+    async def list_of_domains(ctx: Context, details: bool = True) -> str:
+        """List domains; details includes backingTag, status, parent and audit.
+
+        Returns a JSON string; empty lists are returned as [].
+        Authorization and errors are enforced by the Gravitino server.
+        """
+        client = ctx.request_context.lifespan_context.rest_client()
+        return await client.as_domain_operation().list_of_domains(details)
+
+    @mcp.tool(
+        tags={"domain"},
+        annotations=_READONLY_TOOL_ANNOTATIONS,
+    )
+    async def get_domain_by_name(ctx: Context, domain_name: str) -> str:
+        """Load a domain snapshot by name.
+
+        Returns a JSON string containing the complete domain snapshot.
+        Authorization and errors are enforced by the Gravitino server.
+        """
+        client = ctx.request_context.lifespan_context.rest_client()
+        return await client.as_domain_operation().get_domain_by_name(
+            domain_name
+        )
+
+    @mcp.tool(
+        tags={"domain"},
+        annotations=_READONLY_TOOL_ANNOTATIONS,
+    )
+    async def list_subdomains(
+        ctx: Context, domain_name: str, details: bool = True
+    ) -> str:
+        """List immediate subdomains, as names or complete snapshots.
+
+        Returns a JSON string; empty lists are returned as [].
+        Authorization and errors are enforced by the Gravitino server.
+        """
+        client = ctx.request_context.lifespan_context.rest_client()
+        return await client.as_domain_operation().list_subdomains(
+            domain_name, details
+        )
+
+    @mcp.tool(
+        tags={"domain"},
+        annotations=_READONLY_TOOL_ANNOTATIONS,
+    )
+    async def list_domain_members(
+        ctx: Context,
+        domain_name: str,
+        types: list[str] | None = None,
+        domains: list[str] | None = None,
+        name_contains: str | None = None,
+    ) -> str:
+        """List recorded leaf members and all applicable relations.
+
+        types filters leaf object types (for example TABLE and TOPIC).
+        domains filters source domain names; name_contains is a literal 
substring.
+
+        Returns a JSON string; empty lists are returned as [].
+        Authorization and errors are enforced by the Gravitino server.
+        """
+        client = ctx.request_context.lifespan_context.rest_client()
+        return await client.as_domain_operation().list_domain_members(
+            domain_name, types, domains, name_contains
+        )
+
+    @mcp.tool(
+        tags={"domain"},
+        annotations=_READONLY_TOOL_ANNOTATIONS,
+    )
+    async def list_domains_for_metadata(
+        ctx: Context,
+        metadata_full_name: str,
+        metadata_type: str,
+        details: bool = True,
+    ) -> str:
+        """List domains for a leaf metadata object.
+
+        metadata_type supports table, fileset, topic, model, view and 
semantic_model.
+        metadata_full_name is the qualified object name, such as 
catalog.schema.table.
+        details preserves all relations and their sources; false returns names 
only.
+
+        Returns a JSON string; empty lists are returned as [].
+        Authorization and errors are enforced by the Gravitino server.
+        """
+        client = ctx.request_context.lifespan_context.rest_client()
+        return await client.as_domain_operation().list_domains_for_metadata(
+            metadata_full_name, metadata_type, details
+        )
diff --git a/mcp-server/tests/unit/tools/mock_operation.py 
b/mcp-server/tests/unit/tools/mock_operation.py
index 48737da652..01088e2f92 100644
--- a/mcp-server/tests/unit/tools/mock_operation.py
+++ b/mcp-server/tests/unit/tools/mock_operation.py
@@ -19,6 +19,7 @@ from typing import Optional
 
 from mcp_server.client import (
     CatalogOperation,
+    DomainOperation,
     GravitinoOperation,
     ModelOperation,
     PolicyOperation,
@@ -58,6 +59,9 @@ class MockOperation(GravitinoOperation):
     def as_model_operation(self) -> ModelOperation:
         return MockModelOperation()
 
+    def as_domain_operation(self) -> DomainOperation:
+        return MockDomainOperation()
+
     def as_tag_operation(self) -> TagOperation:
         return MockTagOperation()
 
@@ -527,3 +531,30 @@ class MockSemanticModelOperation(SemanticModelOperation):
         self, catalog_name: str, schema_name: str, semantic_model_name: str
     ) -> str:
         return "true"
+
+
+class MockDomainOperation(DomainOperation):
+    async def list_of_domains(self, details: bool = True) -> str:
+        return "[]"
+
+    async def get_domain_by_name(self, domain_name: str) -> str:
+        return "{}"
+
+    async def list_subdomains(
+        self, domain_name: str, details: bool = True
+    ) -> str:
+        return "[]"
+
+    async def list_domain_members(
+        self,
+        domain_name: str,
+        types: list[str] | None = None,
+        domains: list[str] | None = None,
+        name_contains: str | None = None,
+    ) -> str:
+        return "[]"
+
+    async def list_domains_for_metadata(
+        self, metadata_full_name: str, metadata_type: str, details: bool = True
+    ) -> str:
+        return "[]"
diff --git a/mcp-server/tests/unit/tools/test_domain.py 
b/mcp-server/tests/unit/tools/test_domain.py
new file mode 100644
index 0000000000..681a54d2d7
--- /dev/null
+++ b/mcp-server/tests/unit/tools/test_domain.py
@@ -0,0 +1,415 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Read-only Domain tools exercised through FastMCP and the REST client."""
+
+import json
+import unittest
+from unittest.mock import patch
+
+import httpx
+from fastmcp import Client
+from fastmcp.exceptions import ToolError
+
+from mcp_server.client.factory import RESTClientFactory
+from mcp_server.client.plain.plain_rest_client_operation import (
+    PlainRESTClientOperation,
+)
+from mcp_server.core import Setting
+from mcp_server.server import GravitinoMCPServer
+from tests.unit.tools import MockOperation
+
+
+class TestDomainTool(unittest.IsolatedAsyncioTestCase):
+    def setUp(self):
+        self.relations = [
+            {"relation": "direct"},
+            {
+                "relation": "inherited",
+                "source": {"fullName": "cat.schema", "type": "schema"},
+            },
+            {
+                "relation": "via_subdomain",
+                "source": {"fullName": "child", "type": "domain"},
+            },
+        ]
+        self.domain = {
+            "name": "sales",
+            "status": "draft",
+            "parent": "root",
+            "backingTag": {"name": "sales_tag"},
+            "relations": self.relations,
+            "audit": {"creator": "admin"},
+            "properties": {},
+            "comment": "Sales",
+        }
+        self.response = {"code": 0}
+        self.status = 200
+        self.requests = []
+        self.http_clients = []
+        factory_patch = patch.object(
+            RESTClientFactory, "_rest_client_class", self._create_client
+        )
+        factory_patch.start()
+        self.addCleanup(factory_patch.stop)
+        self.mcp = GravitinoMCPServer(
+            Setting("test_metalake", token="domain-test-token", 
tags={"domain"})
+        ).mcp
+
+    async def asyncTearDown(self):
+        for client in self.http_clients:
+            await client.aclose()
+
+    def _respond(self, request):
+        self.requests.append(request)
+        if isinstance(self.response, Exception):
+            raise self.response
+        return httpx.Response(self.status, json=self.response)
+
+    def _create_client(self, *args, **kwargs):
+        # Keep the production factory/client wiring and inject only transport.
+        async_client_type = httpx.AsyncClient
+
+        def create_http_client(*client_args, **client_kwargs):
+            client = async_client_type(
+                *client_args,
+                transport=httpx.MockTransport(self._respond),
+                **client_kwargs,
+            )
+            self.http_clients.append(client)
+            return client
+
+        with patch(
+            
"mcp_server.client.plain.plain_rest_client_operation.httpx.AsyncClient",
+            side_effect=create_http_client,
+        ):
+            return PlainRESTClientOperation(*args, **kwargs)
+
+    async def _call(self, name, arguments):
+        async with Client(self.mcp) as client:
+            result = await client.call_tool(name, arguments)
+            return json.loads(result.content[0].text)
+
+    async def test_registration_and_readonly_annotations(self):
+        async with Client(self.mcp) as client:
+            tools = await client.list_tools()
+        self.assertEqual(
+            {tool.name for tool in tools},
+            {
+                "list_of_domains",
+                "get_domain_by_name",
+                "list_subdomains",
+                "list_domain_members",
+                "list_domains_for_metadata",
+            },
+        )
+        for tool in tools:
+            self.assertTrue(tool.annotations.readOnlyHint)
+            self.assertFalse(tool.annotations.destructiveHint)
+            self.assertTrue(tool.annotations.idempotentHint)
+
+    async def test_snapshots_and_names(self):
+        for name, args in (
+            ("list_of_domains", {}),
+            ("list_subdomains", {"domain_name": "sales"}),
+            (
+                "list_domains_for_metadata",
+                {
+                    "metadata_full_name": "cat.schema.table",
+                    "metadata_type": "table",
+                },
+            ),
+        ):
+            for details in (True, False):
+                with self.subTest(name=name, details=details):
+                    expected = [self.domain] if details else ["sales"]
+                    field = "domains" if details else "names"
+                    self.response = {"code": 0, field: expected}
+                    self.assertEqual(
+                        await self._call(name, {**args, "details": details}),
+                        expected,
+                    )
+                    self.assertEqual(
+                        self.requests[-1].url.params["details"],
+                        str(details).lower(),
+                    )
+        self.response = {"code": 0, "domain": self.domain}
+        self.assertEqual(
+            await self._call("get_domain_by_name", {"domain_name": "sales"}),
+            self.domain,
+        )
+
+    async def test_members_filters_and_relations(self):
+        members = [
+            {
+                "object": {"fullName": "cat.sch.table", "type": "table"},
+                "relations": self.relations,
+            }
+        ]
+        self.response = {"code": 0, "members": members}
+        self.assertEqual(
+            await self._call(
+                "list_domain_members",
+                {
+                    "domain_name": "sales",
+                    "types": ["TABLE", "TOPIC"],
+                    "domains": ["child,one", "child & 二"],
+                    "name_contains": "a&b + %/?",
+                },
+            ),
+            members,
+        )
+        query = self.requests[-1].url.params
+        self.assertEqual(query["types"], "TABLE,TOPIC")
+        self.assertEqual(query.get_list("domains"), ["child,one", "child & 二"])
+        self.assertEqual(query["nameContains"], "a&b + %/?")
+
+    async def test_encoded_paths_and_authorization(self):
+        value = "a/b ?#%,二"
+        for name, args, suffix in (
+            ("list_of_domains", {}, "/api/metalakes/test_metalake/domains"),
+            ("get_domain_by_name", {"domain_name": value}, "/domains/"),
+            ("list_subdomains", {"domain_name": value}, "/domains/"),
+            ("list_domain_members", {"domain_name": value}, "/domains/"),
+            (
+                "list_domains_for_metadata",
+                {"metadata_type": "table", "metadata_full_name": value},
+                "/objects/table/",
+            ),
+        ):
+            await self._call(name, args)
+            request = self.requests[-1]
+            expected = (
+                suffix
+                if name == "list_of_domains"
+                else (suffix + "a%2Fb%20%3F%23%25%2C%E4%BA%8C")
+            )
+            self.assertIn(expected.encode(), request.url.raw_path)
+            self.assertEqual(
+                request.headers["Authorization"], "Bearer domain-test-token"
+            )
+            self.assertEqual(request.method, "GET")
+            self.assertEqual(request.content, b"")
+
+    async def test_empty_results_and_errors(self):
+        calls = [
+            ("list_of_domains", {}),
+            ("list_subdomains", {"domain_name": "sales"}),
+            ("list_domain_members", {"domain_name": "sales"}),
+            (
+                "list_domains_for_metadata",
+                {"metadata_type": "table", "metadata_full_name": "c.s.t"},
+            ),
+            ("get_domain_by_name", {"domain_name": "sales"}),
+        ]
+        for name, args in calls:
+            self.response = {"code": 0}
+            self.assertEqual(
+                await self._call(name, args),
+                {} if name == "get_domain_by_name" else [],
+            )
+            for code, error in (
+                (401, "UnauthorizedException"),
+                (403, "ForbiddenException"),
+                (404, "NoSuchDomainException"),
+                (400, "IllegalArgumentException"),
+            ):
+                self.response = {
+                    "code": code,
+                    "type": error,
+                    "message": "denied",
+                }
+                self.status = code
+                with self.assertRaisesRegex(ToolError, error):
+                    await self._call(name, args)
+            self.status = 200
+
+    async def test_unfiltered_members(self):
+        await self._call("list_domain_members", {"domain_name": "sales"})
+        self.assertFalse(self.requests[-1].url.query)
+        await self._call(
+            "list_domain_members",
+            {
+                "domain_name": "sales",
+                "types": [],
+                "domains": [],
+                "name_contains": "",
+            },
+        )
+        self.assertEqual(self.requests[-1].url.params["nameContains"], "")
+
+    async def test_leaf_object_types(self):
+        self.response = {"code": 0, "domains": [self.domain]}
+        for metadata_type in (
+            "table",
+            "topic",
+            "fileset",
+            "model",
+            "view",
+            "semantic_model",
+        ):
+            self.assertEqual(
+                await self._call(
+                    "list_domains_for_metadata",
+                    {
+                        "metadata_type": metadata_type,
+                        "metadata_full_name": "c.s.leaf",
+                    },
+                ),
+                [self.domain],
+            )
+            self.assertEqual(
+                self.requests[-1].url.path,
+                
f"/api/metalakes/test_metalake/objects/{metadata_type}/c.s.leaf/domains",
+            )
+
+    async def test_invalid_path_segments(self):
+        for value in ("", ".", ".."):
+            for name, args in (
+                ("get_domain_by_name", {"domain_name": value}),
+                ("list_subdomains", {"domain_name": value}),
+                ("list_domain_members", {"domain_name": value}),
+                (
+                    "list_domains_for_metadata",
+                    {"metadata_type": "table", "metadata_full_name": value},
+                ),
+                (
+                    "list_domains_for_metadata",
+                    {"metadata_type": value, "metadata_full_name": "c.s.t"},
+                ),
+            ):
+                with self.assertRaisesRegex(ToolError, "REST path names"):
+                    await self._call(name, args)
+        self.assertFalse(self.requests)
+
+    async def test_network_failure(self):
+        self.response = httpx.ConnectError("server unavailable")
+        with self.assertRaisesRegex(ToolError, "server unavailable"):
+            await self._call("get_domain_by_name", {"domain_name": "sales"})
+
+    async def test_encoded_metalake(self):
+        operation = self._create_client(
+            "lake /#二", "http://localhost:8090";, authorization="Bearer other"
+        )
+        try:
+            await operation.as_domain_operation().list_of_domains()
+            request = self.requests[-1]
+            self.assertEqual(
+                request.url.raw_path,
+                b"/api/metalakes/lake%20%2F%23%E4%BA%8C/domains?details=true",
+            )
+            self.assertEqual(request.headers["Authorization"], "Bearer other")
+        finally:
+            await operation.close()
+
+    async def test_http_errors_without_gravitino_envelope(self):
+        for status in (401, 403, 500):
+            self.status = status
+            self.response = {"detail": "Gateway rejected the request"}
+            for name, args in (
+                ("list_of_domains", {}),
+                ("get_domain_by_name", {"domain_name": "sales"}),
+                ("list_subdomains", {"domain_name": "sales"}),
+                ("list_domain_members", {"domain_name": "sales"}),
+                (
+                    "list_domains_for_metadata",
+                    {
+                        "metadata_type": "table",
+                        "metadata_full_name": "c.s.t",
+                    },
+                ),
+            ):
+                with self.subTest(status=status, tool=name):
+                    with self.assertRaisesRegex(ToolError, str(status)):
+                        await self._call(name, args)
+
+    async def test_identity_and_metalake_are_resolved_per_call(self):
+        self.response = {"code": 0, "domains": [self.domain]}
+        async with Client(self.mcp) as client:
+            for authorization, metalake in (
+                ("Basic YWxpY2U6ZHVtbXk=", "other/lake"),
+                ("Bearer bob-token", "second"),
+                ("", None),
+            ):
+                args = {} if metalake is None else {"metalake": metalake}
+                with patch(
+                    "mcp_server.core.context._get_request_authorization",
+                    return_value=authorization,
+                ):
+                    await client.call_tool("list_of_domains", args)
+                request = self.requests[-1]
+                self.assertEqual(
+                    request.headers["Authorization"],
+                    authorization or "Bearer domain-test-token",
+                )
+                expected_path = {
+                    "other/lake": 
b"/api/metalakes/other%2Flake/domains?details=true",
+                    "second": b"/api/metalakes/second/domains?details=true",
+                    None: b"/api/metalakes/test_metalake/domains?details=true",
+                }[metalake]
+                self.assertEqual(request.url.raw_path, expected_path)
+                self.assertEqual(request.method, "GET")
+                self.assertEqual(request.content, b"")
+
+    async def test_disabled_service_identity_fallback(self):
+        self.mcp = GravitinoMCPServer(
+            Setting(
+                "test_metalake",
+                token="service-token",
+                tags={"domain"},
+                no_service_identity_fallback=True,
+            )
+        ).mcp
+        with (
+            patch(
+                "mcp_server.core.context._get_request_authorization",
+                return_value="",
+            ),
+            patch(
+                "mcp_server.core.context._in_http_request", return_value=True
+            ),
+        ):
+            with self.assertRaisesRegex(
+                ToolError, "HTTP request omitted Authorization"
+            ):
+                await self._call("list_of_domains", {})
+        self.assertFalse(self.requests)
+
+    async def test_mock_client_implements_domain_facet(self):
+        with patch.object(
+            RESTClientFactory, "_rest_client_class", MockOperation
+        ):
+            self.mcp = GravitinoMCPServer(
+                Setting("test_metalake", tags={"domain"})
+            ).mcp
+            for name, args in (
+                ("list_of_domains", {}),
+                ("get_domain_by_name", {"domain_name": "sales"}),
+                ("list_subdomains", {"domain_name": "sales"}),
+                ("list_domain_members", {"domain_name": "sales"}),
+                (
+                    "list_domains_for_metadata",
+                    {
+                        "metadata_type": "table",
+                        "metadata_full_name": "c.s.t",
+                    },
+                ),
+            ):
+                self.assertEqual(
+                    await self._call(name, args),
+                    {} if name == "get_domain_by_name" else [],
+                )

Reply via email to