You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gravitino.apache.org by yu...@apache.org on 2026/06/11 08:37:57 UTC
(gravitino) branch feat/mcp-governance-task3-6 created (now 61d3bdf085)
This is an automated email from the ASF dual-hosted git repository.
yuqi1129 pushed a change to branch feat/mcp-governance-task3-6
in repository https://gitbox.apache.org/repos/asf/gravitino.git
at 61d3bdf085 Add localtest example and docs.
This branch includes the following new commits:
new 4c3570b6c0 [#11565][#11566] feat(mcp-server): add --token CLI param and inject Bearer token into Gravitino REST calls
new 8befd997c2 [#11567] feat(mcp-server): enable tag write tools protected by Gravitino authorization
new e135d011d2 [#11568] feat(mcp-server): structured per-tool-call audit logging attributed to principal
new a821a009ea [#11572] feat(mcp-server): per-request token isolation for HTTP transport
new 3b372972f2 [#11574] feat(mcp-server): implement write operations for catalog, schema, table, model, topic, fileset
new 4e27ce044d [#11575] refactor(mcp-server): forward raw Authorization header instead of assuming Bearer
new f6c011f089 [#11575] test(mcp-server): live-Gravitino authorization integration test + CI
new 031702432f [#11572] feat(mcp-server): accept streamable-http transport alias and serve endpoint over TLS
new 61d3bdf085 Add localtest example and docs.
The 9 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(gravitino) 05/09: [#11574] feat(mcp-server): implement write operations for catalog, schema, table, model, topic, fileset
Posted by yu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yuqi1129 pushed a commit to branch feat/mcp-governance-task3-6
in repository https://gitbox.apache.org/repos/asf/gravitino.git
commit 3b372972f2baba7495db7e4dddae7aa9409f25c2
Author: yuqi <yu...@datastrato.com>
AuthorDate: Wed Jun 10 21:21:13 2026 +0800
[#11574] feat(mcp-server): implement write operations for catalog, schema, table, model, topic, fileset
Add create/alter/drop (and register/link/delete for models) write tools across
all remaining resource types, following the same pattern as the tag write tools.
Write tools are exposed by default; authorization is enforced by Gravitino core.
Per resource:
- catalog: create_catalog, alter_catalog, drop_catalog
- schema: create_schema, alter_schema, drop_schema
- table: create_table, alter_table, drop_table
- topic: create_topic, alter_topic, delete_topic
- fileset: create_fileset, alter_fileset, drop_fileset
- model: register_model, delete_model, link_model_version, delete_model_version
Each adds: abstract interface method, plain REST client implementation, FastMCP
tool registration, mock implementation, and unit tests (20 new tests).
Also remove a leftover unused `contextlib` import in server.py.
---
mcp-server/mcp_server/client/catalog_operation.py | 19 ++++
mcp-server/mcp_server/client/fileset_operation.py | 29 +++++
mcp-server/mcp_server/client/model_operation.py | 36 +++++++
.../plain/plain_rest_client_catalog_operation.py | 35 ++++++
.../plain/plain_rest_client_fileset_operation.py | 56 +++++++++-
.../plain/plain_rest_client_model_operation.py | 68 +++++++++++-
.../plain/plain_rest_client_schema_operation.py | 29 +++++
.../plain/plain_rest_client_table_operation.py | 49 +++++++++
.../plain/plain_rest_client_topic_operation.py | 48 ++++++++-
mcp-server/mcp_server/client/schema_operation.py | 16 +++
mcp-server/mcp_server/client/table_operation.py | 28 +++++
mcp-server/mcp_server/client/topic_operation.py | 27 +++++
mcp-server/mcp_server/server.py | 1 -
mcp-server/mcp_server/tools/catalog.py | 75 +++++++++++++
mcp-server/mcp_server/tools/fileset.py | 94 +++++++++++++++++
mcp-server/mcp_server/tools/model.py | 117 +++++++++++++++++++++
mcp-server/mcp_server/tools/schema.py | 74 +++++++++++++
mcp-server/mcp_server/tools/table.py | 92 ++++++++++++++++
mcp-server/mcp_server/tools/topic.py | 82 +++++++++++++++
mcp-server/tests/unit/test_audit.py | 13 ++-
mcp-server/tests/unit/test_auth_flow.py | 4 +-
mcp-server/tests/unit/test_per_request_token.py | 12 ++-
mcp-server/tests/unit/tools/mock_operation.py | 115 ++++++++++++++++++++
mcp-server/tests/unit/tools/test_catalog.py | 58 ++++++++++
mcp-server/tests/unit/tools/test_fileset.py | 58 ++++++++++
mcp-server/tests/unit/tools/test_model.py | 78 ++++++++++++++
mcp-server/tests/unit/tools/test_schema.py | 50 +++++++++
mcp-server/tests/unit/tools/test_table.py | 58 ++++++++++
mcp-server/tests/unit/tools/test_topic.py | 56 ++++++++++
29 files changed, 1466 insertions(+), 11 deletions(-)
diff --git a/mcp-server/mcp_server/client/catalog_operation.py b/mcp-server/mcp_server/client/catalog_operation.py
index 08cf7a5b97..df9b1c91dc 100644
--- a/mcp-server/mcp_server/client/catalog_operation.py
+++ b/mcp-server/mcp_server/client/catalog_operation.py
@@ -32,3 +32,22 @@ class CatalogOperation(ABC):
str: JSON-formatted string containing catalog information.
"""
pass
+
+ @abstractmethod
+ async def create_catalog(
+ self,
+ name: str,
+ catalog_type: str,
+ provider: str,
+ comment: str,
+ properties: dict,
+ ) -> str:
+ pass
+
+ @abstractmethod
+ async def alter_catalog(self, catalog_name: str, updates: list) -> str:
+ pass
+
+ @abstractmethod
+ async def drop_catalog(self, catalog_name: str) -> str:
+ pass
diff --git a/mcp-server/mcp_server/client/fileset_operation.py b/mcp-server/mcp_server/client/fileset_operation.py
index a158c11cda..064e66d597 100644
--- a/mcp-server/mcp_server/client/fileset_operation.py
+++ b/mcp-server/mcp_server/client/fileset_operation.py
@@ -80,3 +80,32 @@ class FilesetOperation(ABC):
str: JSON-formatted string containing list of files in the fileset
"""
pass
+
+ @abstractmethod
+ async def create_fileset(
+ self,
+ catalog_name: str,
+ schema_name: str,
+ name: str,
+ fileset_type: str,
+ storage_location: str,
+ comment: str,
+ properties: dict,
+ ) -> str:
+ pass
+
+ @abstractmethod
+ async def alter_fileset(
+ self,
+ catalog_name: str,
+ schema_name: str,
+ fileset_name: str,
+ updates: list,
+ ) -> str:
+ pass
+
+ @abstractmethod
+ async def drop_fileset(
+ self, catalog_name: str, schema_name: str, fileset_name: str
+ ) -> str:
+ pass
diff --git a/mcp-server/mcp_server/client/model_operation.py b/mcp-server/mcp_server/client/model_operation.py
index c63eda326a..6a9aa4195e 100644
--- a/mcp-server/mcp_server/client/model_operation.py
+++ b/mcp-server/mcp_server/client/model_operation.py
@@ -106,3 +106,39 @@ class ModelOperation(ABC):
str: JSON-formatted string containing full model version metadata
"""
pass
+
+ @abstractmethod
+ async def register_model(
+ self,
+ catalog_name: str,
+ schema_name: str,
+ name: str,
+ comment: str,
+ properties: dict,
+ ) -> str:
+ pass
+
+ @abstractmethod
+ async def delete_model(
+ self, catalog_name: str, schema_name: str, model_name: str
+ ) -> str:
+ pass
+
+ @abstractmethod
+ async def link_model_version(
+ self,
+ catalog_name: str,
+ schema_name: str,
+ model_name: str,
+ uri: str,
+ aliases: list,
+ comment: str,
+ properties: dict,
+ ) -> str:
+ pass
+
+ @abstractmethod
+ async def delete_model_version(
+ self, catalog_name: str, schema_name: str, model_name: str, version: int
+ ) -> str:
+ pass
diff --git a/mcp-server/mcp_server/client/plain/plain_rest_client_catalog_operation.py b/mcp-server/mcp_server/client/plain/plain_rest_client_catalog_operation.py
index 843cf3bfe7..9aece47fc3 100644
--- a/mcp-server/mcp_server/client/plain/plain_rest_client_catalog_operation.py
+++ b/mcp-server/mcp_server/client/plain/plain_rest_client_catalog_operation.py
@@ -34,3 +34,38 @@ class PlainRESTClientCatalogOperation(CatalogOperation):
f"/api/metalakes/{encode_path_segment(self.metalake_name)}/catalogs?details=true"
)
return extract_content_from_response(response, "catalogs", [])
+
+ async def create_catalog(
+ self,
+ name: str,
+ catalog_type: str,
+ provider: str,
+ comment: str,
+ properties: dict,
+ ) -> str:
+ response = await self.rest_client.post(
+ f"/api/metalakes/{encode_path_segment(self.metalake_name)}/catalogs",
+ json={
+ "name": name,
+ "type": catalog_type,
+ "provider": provider,
+ "comment": comment,
+ "properties": properties,
+ },
+ )
+ return extract_content_from_response(response, "catalog", {})
+
+ async def alter_catalog(self, catalog_name: str, updates: list) -> str:
+ response = await self.rest_client.put(
+ f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
+ f"/catalogs/{encode_path_segment(catalog_name)}",
+ json={"updates": updates},
+ )
+ return extract_content_from_response(response, "catalog", {})
+
+ async def drop_catalog(self, catalog_name: str) -> str:
+ response = await self.rest_client.delete(
+ f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
+ f"/catalogs/{encode_path_segment(catalog_name)}"
+ )
+ return extract_content_from_response(response, "dropped", False)
diff --git a/mcp-server/mcp_server/client/plain/plain_rest_client_fileset_operation.py b/mcp-server/mcp_server/client/plain/plain_rest_client_fileset_operation.py
index 4c81eece1d..4c023157c5 100644
--- a/mcp-server/mcp_server/client/plain/plain_rest_client_fileset_operation.py
+++ b/mcp-server/mcp_server/client/plain/plain_rest_client_fileset_operation.py
@@ -16,7 +16,10 @@
# under the License.
from mcp_server.client.fileset_operation import FilesetOperation
-from mcp_server.client.plain.utils import encode_path_segment
+from mcp_server.client.plain.utils import (
+ encode_path_segment,
+ extract_content_from_response,
+)
class PlainRESTClientFilesetOperation(FilesetOperation):
@@ -62,3 +65,54 @@ class PlainRESTClientFilesetOperation(FilesetOperation):
params={"sub_path": sub_path, "location_name": location_name},
)
return response.json().get("files", [])
+
+ async def create_fileset(
+ self,
+ catalog_name: str,
+ schema_name: str,
+ name: str,
+ fileset_type: str,
+ storage_location: str,
+ comment: str,
+ properties: dict,
+ ) -> str:
+ response = await self.rest_client.post(
+ f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
+ f"/catalogs/{encode_path_segment(catalog_name)}"
+ f"/schemas/{encode_path_segment(schema_name)}/filesets",
+ json={
+ "name": name,
+ "type": fileset_type,
+ "storageLocation": storage_location,
+ "comment": comment,
+ "properties": properties,
+ },
+ )
+ return extract_content_from_response(response, "fileset", {})
+
+ async def alter_fileset(
+ self,
+ catalog_name: str,
+ schema_name: str,
+ fileset_name: str,
+ updates: list,
+ ) -> str:
+ response = await self.rest_client.put(
+ f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
+ f"/catalogs/{encode_path_segment(catalog_name)}"
+ f"/schemas/{encode_path_segment(schema_name)}"
+ f"/filesets/{encode_path_segment(fileset_name)}",
+ json={"updates": updates},
+ )
+ return extract_content_from_response(response, "fileset", {})
+
+ async def drop_fileset(
+ self, catalog_name: str, schema_name: str, fileset_name: str
+ ) -> str:
+ response = await self.rest_client.delete(
+ f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
+ f"/catalogs/{encode_path_segment(catalog_name)}"
+ f"/schemas/{encode_path_segment(schema_name)}"
+ f"/filesets/{encode_path_segment(fileset_name)}"
+ )
+ return extract_content_from_response(response, "dropped", False)
diff --git a/mcp-server/mcp_server/client/plain/plain_rest_client_model_operation.py b/mcp-server/mcp_server/client/plain/plain_rest_client_model_operation.py
index 7fce30bd91..1f36bc8359 100644
--- a/mcp-server/mcp_server/client/plain/plain_rest_client_model_operation.py
+++ b/mcp-server/mcp_server/client/plain/plain_rest_client_model_operation.py
@@ -16,7 +16,10 @@
# under the License.
from mcp_server.client import ModelOperation
-from mcp_server.client.plain.utils import encode_path_segment
+from mcp_server.client.plain.utils import (
+ encode_path_segment,
+ extract_content_from_response,
+)
class PlainRESTClientModelOperation(ModelOperation):
@@ -81,3 +84,66 @@ class PlainRESTClientModelOperation(ModelOperation):
f"/aliases/{encode_path_segment(alias)}"
)
return response.json().get("modelVersion", {})
+
+ async def register_model(
+ self,
+ catalog_name: str,
+ schema_name: str,
+ name: str,
+ comment: str,
+ properties: dict,
+ ) -> str:
+ response = await self.rest_client.post(
+ f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
+ f"/catalogs/{encode_path_segment(catalog_name)}"
+ f"/schemas/{encode_path_segment(schema_name)}/models",
+ json={"name": name, "comment": comment, "properties": properties},
+ )
+ return extract_content_from_response(response, "model", {})
+
+ async def delete_model(
+ self, catalog_name: str, schema_name: str, model_name: str
+ ) -> str:
+ response = await self.rest_client.delete(
+ f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
+ f"/catalogs/{encode_path_segment(catalog_name)}"
+ f"/schemas/{encode_path_segment(schema_name)}"
+ f"/models/{encode_path_segment(model_name)}"
+ )
+ return extract_content_from_response(response, "deleted", False)
+
+ async def link_model_version(
+ self,
+ catalog_name: str,
+ schema_name: str,
+ model_name: str,
+ uri: str,
+ aliases: list,
+ comment: str,
+ properties: dict,
+ ) -> str:
+ response = await self.rest_client.post(
+ f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
+ f"/catalogs/{encode_path_segment(catalog_name)}"
+ f"/schemas/{encode_path_segment(schema_name)}"
+ f"/models/{encode_path_segment(model_name)}/versions",
+ json={
+ "uri": uri,
+ "aliases": aliases,
+ "comment": comment,
+ "properties": properties,
+ },
+ )
+ return extract_content_from_response(response, "modelVersion", {})
+
+ async def delete_model_version(
+ self, catalog_name: str, schema_name: str, model_name: str, version: int
+ ) -> str:
+ response = await self.rest_client.delete(
+ f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
+ f"/catalogs/{encode_path_segment(catalog_name)}"
+ f"/schemas/{encode_path_segment(schema_name)}"
+ f"/models/{encode_path_segment(model_name)}"
+ f"/versions/{encode_path_segment(version)}"
+ )
+ return extract_content_from_response(response, "deleted", False)
diff --git a/mcp-server/mcp_server/client/plain/plain_rest_client_schema_operation.py b/mcp-server/mcp_server/client/plain/plain_rest_client_schema_operation.py
index 4c2c76ed44..ac6554bedb 100644
--- a/mcp-server/mcp_server/client/plain/plain_rest_client_schema_operation.py
+++ b/mcp-server/mcp_server/client/plain/plain_rest_client_schema_operation.py
@@ -35,3 +35,32 @@ class PlainRESTClientSchemaOperation(SchemaOperation):
f"/catalogs/{encode_path_segment(catalog_name)}/schemas"
)
return extract_content_from_response(response, "identifiers", [])
+
+ async def create_schema(
+ self, catalog_name: str, name: str, comment: str, properties: dict
+ ) -> str:
+ response = await self.rest_client.post(
+ f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
+ f"/catalogs/{encode_path_segment(catalog_name)}/schemas",
+ json={"name": name, "comment": comment, "properties": properties},
+ )
+ return extract_content_from_response(response, "schema", {})
+
+ async def alter_schema(
+ self, catalog_name: str, schema_name: str, updates: list
+ ) -> str:
+ response = await self.rest_client.put(
+ f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
+ f"/catalogs/{encode_path_segment(catalog_name)}"
+ f"/schemas/{encode_path_segment(schema_name)}",
+ json={"updates": updates},
+ )
+ return extract_content_from_response(response, "schema", {})
+
+ async def drop_schema(self, catalog_name: str, schema_name: str) -> str:
+ response = await self.rest_client.delete(
+ f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
+ f"/catalogs/{encode_path_segment(catalog_name)}"
+ f"/schemas/{encode_path_segment(schema_name)}"
+ )
+ return extract_content_from_response(response, "dropped", False)
diff --git a/mcp-server/mcp_server/client/plain/plain_rest_client_table_operation.py b/mcp-server/mcp_server/client/plain/plain_rest_client_table_operation.py
index e1bee62cab..0ab05d2366 100644
--- a/mcp-server/mcp_server/client/plain/plain_rest_client_table_operation.py
+++ b/mcp-server/mcp_server/client/plain/plain_rest_client_table_operation.py
@@ -50,3 +50,52 @@ class PlainRESTClientTableOperation(TableOperation):
f"/tables/{encode_path_segment(table_name)}"
)
return extract_content_from_response(response, "table", {})
+
+ async def create_table(
+ self,
+ catalog_name: str,
+ schema_name: str,
+ name: str,
+ comment: str,
+ columns: list,
+ properties: dict,
+ ) -> str:
+ response = await self.rest_client.post(
+ f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
+ f"/catalogs/{encode_path_segment(catalog_name)}"
+ f"/schemas/{encode_path_segment(schema_name)}/tables",
+ json={
+ "name": name,
+ "comment": comment,
+ "columns": columns,
+ "properties": properties,
+ },
+ )
+ return extract_content_from_response(response, "table", {})
+
+ async def alter_table(
+ self,
+ catalog_name: str,
+ schema_name: str,
+ table_name: str,
+ updates: list,
+ ) -> str:
+ response = await self.rest_client.put(
+ f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
+ f"/catalogs/{encode_path_segment(catalog_name)}"
+ f"/schemas/{encode_path_segment(schema_name)}"
+ f"/tables/{encode_path_segment(table_name)}",
+ json={"updates": updates},
+ )
+ return extract_content_from_response(response, "table", {})
+
+ async def drop_table(
+ self, catalog_name: str, schema_name: str, table_name: str
+ ) -> str:
+ response = await self.rest_client.delete(
+ f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
+ f"/catalogs/{encode_path_segment(catalog_name)}"
+ f"/schemas/{encode_path_segment(schema_name)}"
+ f"/tables/{encode_path_segment(table_name)}"
+ )
+ return extract_content_from_response(response, "dropped", False)
diff --git a/mcp-server/mcp_server/client/plain/plain_rest_client_topic_operation.py b/mcp-server/mcp_server/client/plain/plain_rest_client_topic_operation.py
index ff04720197..18bae32709 100644
--- a/mcp-server/mcp_server/client/plain/plain_rest_client_topic_operation.py
+++ b/mcp-server/mcp_server/client/plain/plain_rest_client_topic_operation.py
@@ -15,7 +15,10 @@
# specific language governing permissions and limitations
# under the License.
-from mcp_server.client.plain.utils import encode_path_segment
+from mcp_server.client.plain.utils import (
+ encode_path_segment,
+ extract_content_from_response,
+)
from mcp_server.client.topic_operation import TopicOperation
@@ -46,3 +49,46 @@ class PlainRESTClientTopicOperation(TopicOperation):
f"/topics/{encode_path_segment(topic_name)}"
)
return response.json().get("topic", {})
+
+ async def create_topic(
+ self,
+ catalog_name: str,
+ schema_name: str,
+ name: str,
+ comment: str,
+ properties: dict,
+ ) -> str:
+ response = await self.rest_client.post(
+ f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
+ f"/catalogs/{encode_path_segment(catalog_name)}"
+ f"/schemas/{encode_path_segment(schema_name)}/topics",
+ json={"name": name, "comment": comment, "properties": properties},
+ )
+ return extract_content_from_response(response, "topic", {})
+
+ async def alter_topic(
+ self,
+ catalog_name: str,
+ schema_name: str,
+ topic_name: str,
+ updates: list,
+ ) -> str:
+ response = await self.rest_client.put(
+ f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
+ f"/catalogs/{encode_path_segment(catalog_name)}"
+ f"/schemas/{encode_path_segment(schema_name)}"
+ f"/topics/{encode_path_segment(topic_name)}",
+ json={"updates": updates},
+ )
+ return extract_content_from_response(response, "topic", {})
+
+ async def delete_topic(
+ self, catalog_name: str, schema_name: str, topic_name: str
+ ) -> str:
+ response = await self.rest_client.delete(
+ f"/api/metalakes/{encode_path_segment(self.metalake_name)}"
+ f"/catalogs/{encode_path_segment(catalog_name)}"
+ f"/schemas/{encode_path_segment(schema_name)}"
+ f"/topics/{encode_path_segment(topic_name)}"
+ )
+ return extract_content_from_response(response, "dropped", False)
diff --git a/mcp-server/mcp_server/client/schema_operation.py b/mcp-server/mcp_server/client/schema_operation.py
index b90d7b96f2..6e7376d6f9 100644
--- a/mcp-server/mcp_server/client/schema_operation.py
+++ b/mcp-server/mcp_server/client/schema_operation.py
@@ -35,3 +35,19 @@ class SchemaOperation(ABC):
str: JSON-formatted string containing catalog information.
"""
pass
+
+ @abstractmethod
+ async def create_schema(
+ self, catalog_name: str, name: str, comment: str, properties: dict
+ ) -> str:
+ pass
+
+ @abstractmethod
+ async def alter_schema(
+ self, catalog_name: str, schema_name: str, updates: list
+ ) -> str:
+ pass
+
+ @abstractmethod
+ async def drop_schema(self, catalog_name: str, schema_name: str) -> str:
+ pass
diff --git a/mcp-server/mcp_server/client/table_operation.py b/mcp-server/mcp_server/client/table_operation.py
index 2d188ebf25..3f70e042bc 100644
--- a/mcp-server/mcp_server/client/table_operation.py
+++ b/mcp-server/mcp_server/client/table_operation.py
@@ -55,3 +55,31 @@ class TableOperation(ABC):
str: JSON-formatted string containing full table metadata
"""
pass
+
+ @abstractmethod
+ async def create_table(
+ self,
+ catalog_name: str,
+ schema_name: str,
+ name: str,
+ comment: str,
+ columns: list,
+ properties: dict,
+ ) -> str:
+ pass
+
+ @abstractmethod
+ async def alter_table(
+ self,
+ catalog_name: str,
+ schema_name: str,
+ table_name: str,
+ updates: list,
+ ) -> str:
+ pass
+
+ @abstractmethod
+ async def drop_table(
+ self, catalog_name: str, schema_name: str, table_name: str
+ ) -> str:
+ pass
diff --git a/mcp-server/mcp_server/client/topic_operation.py b/mcp-server/mcp_server/client/topic_operation.py
index 6bc0bc94ab..449b90207e 100644
--- a/mcp-server/mcp_server/client/topic_operation.py
+++ b/mcp-server/mcp_server/client/topic_operation.py
@@ -53,3 +53,30 @@ class TopicOperation(ABC):
str: JSON-formatted string containing full topic metadata
"""
pass
+
+ @abstractmethod
+ async def create_topic(
+ self,
+ catalog_name: str,
+ schema_name: str,
+ name: str,
+ comment: str,
+ properties: dict,
+ ) -> str:
+ pass
+
+ @abstractmethod
+ async def alter_topic(
+ self,
+ catalog_name: str,
+ schema_name: str,
+ topic_name: str,
+ updates: list,
+ ) -> str:
+ pass
+
+ @abstractmethod
+ async def delete_topic(
+ self, catalog_name: str, schema_name: str, topic_name: str
+ ) -> str:
+ pass
diff --git a/mcp-server/mcp_server/server.py b/mcp-server/mcp_server/server.py
index aea7df7f78..4280932c9e 100644
--- a/mcp-server/mcp_server/server.py
+++ b/mcp-server/mcp_server/server.py
@@ -16,7 +16,6 @@
# under the License.
import asyncio
-import contextlib
import logging
from contextlib import asynccontextmanager
from typing import AsyncIterator
diff --git a/mcp-server/mcp_server/tools/catalog.py b/mcp-server/mcp_server/tools/catalog.py
index 50115610e8..442e4ce02b 100644
--- a/mcp-server/mcp_server/tools/catalog.py
+++ b/mcp-server/mcp_server/tools/catalog.py
@@ -108,3 +108,78 @@ def load_catalog_tools(mcp: FastMCP):
"""
client = ctx.request_context.lifespan_context.rest_client()
return await client.as_catalog_operation().get_list_of_catalogs()
+
+ @mcp.tool(tags={"catalog"})
+ async def create_catalog(
+ ctx: Context,
+ name: str,
+ catalog_type: str,
+ provider: str,
+ comment: str,
+ properties: dict,
+ ) -> str:
+ """
+ Create a new catalog within the metalake.
+
+ Authorization is enforced by Gravitino: a principal without the
+ required grant receives an authorization denial.
+
+ Args:
+ ctx (Context): The request context object.
+ name (str): Name of the catalog to create.
+ catalog_type (str): Catalog type, one of "relational", "fileset",
+ "messaging", "model".
+ provider (str): Provider implementation, e.g. "hive",
+ "lakehouse-iceberg", "jdbc-postgresql", "kafka". May be empty
+ for model/fileset catalogs that have a single provider.
+ comment (str): Human-readable description.
+ properties (dict): Catalog configuration properties.
+
+ Returns:
+ str: JSON-formatted string containing the created catalog.
+ """
+ client = ctx.request_context.lifespan_context.rest_client()
+ return await client.as_catalog_operation().create_catalog(
+ name, catalog_type, provider, comment, properties
+ )
+
+ @mcp.tool(tags={"catalog"})
+ async def alter_catalog(
+ ctx: Context, catalog_name: str, updates: list
+ ) -> str:
+ """
+ Alter an existing catalog.
+
+ Args:
+ ctx (Context): The request context object.
+ catalog_name (str): Name of the catalog to alter.
+ updates (list): List of update operations. Example:
+ [
+ {"@type": "rename", "newName": "new_catalog"},
+ {"@type": "updateComment", "newComment": "updated"},
+ {"@type": "setProperty", "property": "k", "value": "v"},
+ {"@type": "removeProperty", "property": "k"}
+ ]
+
+ Returns:
+ str: JSON-formatted string containing the altered catalog.
+ """
+ client = ctx.request_context.lifespan_context.rest_client()
+ return await client.as_catalog_operation().alter_catalog(
+ catalog_name, updates
+ )
+
+ @mcp.tool(tags={"catalog"})
+ async def drop_catalog(ctx: Context, catalog_name: str) -> str:
+ """
+ Drop a catalog by its name.
+
+ Args:
+ ctx (Context): The request context object.
+ catalog_name (str): Name of the catalog to drop.
+
+ Returns:
+ str: JSON-formatted string indicating whether the catalog was dropped.
+ """
+ client = ctx.request_context.lifespan_context.rest_client()
+ return await client.as_catalog_operation().drop_catalog(catalog_name)
diff --git a/mcp-server/mcp_server/tools/fileset.py b/mcp-server/mcp_server/tools/fileset.py
index c3997ac16d..0df5070b7b 100644
--- a/mcp-server/mcp_server/tools/fileset.py
+++ b/mcp-server/mcp_server/tools/fileset.py
@@ -143,3 +143,97 @@ def load_fileset_tools(mcp: FastMCP):
return await client.as_fileset_operation().list_files_in_fileset(
catalog_name, schema_name, fileset_name, location_name, sub_path
)
+
+ # pylint:disable=too-many-positional-arguments
+ @mcp.tool(tags={"fileset"})
+ async def create_fileset(
+ ctx: Context,
+ catalog_name: str,
+ schema_name: str,
+ name: str,
+ fileset_type: str,
+ storage_location: str,
+ comment: str,
+ properties: dict,
+ ) -> str:
+ """
+ Create a new fileset within a schema.
+
+ Authorization is enforced by Gravitino: a principal without the
+ required grant receives an authorization denial.
+
+ Args:
+ ctx (Context): The request context object.
+ catalog_name (str): Name of the catalog.
+ schema_name (str): Name of the schema.
+ name (str): Name of the fileset to create.
+ fileset_type (str): Fileset type, one of "managed" or "external".
+ storage_location (str): Storage location URI, e.g. "file:/tmp/fileset1".
+ comment (str): Human-readable description.
+ properties (dict): Fileset configuration properties.
+
+ Returns:
+ str: JSON-formatted string containing the created fileset.
+ """
+ client = ctx.request_context.lifespan_context.rest_client()
+ return await client.as_fileset_operation().create_fileset(
+ catalog_name,
+ schema_name,
+ name,
+ fileset_type,
+ storage_location,
+ comment,
+ properties,
+ )
+
+ @mcp.tool(tags={"fileset"})
+ async def alter_fileset(
+ ctx: Context,
+ catalog_name: str,
+ schema_name: str,
+ fileset_name: str,
+ updates: list,
+ ) -> str:
+ """
+ Alter an existing fileset.
+
+ Args:
+ ctx (Context): The request context object.
+ catalog_name (str): Name of the catalog.
+ schema_name (str): Name of the schema.
+ fileset_name (str): Name of the fileset to alter.
+ updates (list): List of update operations. Example:
+ [
+ {"@type": "rename", "newName": "new_fileset"},
+ {"@type": "updateComment", "newComment": "updated"},
+ {"@type": "setProperty", "property": "k", "value": "v"}
+ ]
+
+ Returns:
+ str: JSON-formatted string containing the altered fileset.
+ """
+ client = ctx.request_context.lifespan_context.rest_client()
+ return await client.as_fileset_operation().alter_fileset(
+ catalog_name, schema_name, fileset_name, updates
+ )
+
+ @mcp.tool(tags={"fileset"})
+ async def drop_fileset(
+ ctx: Context, catalog_name: str, schema_name: str, fileset_name: str
+ ) -> str:
+ """
+ Drop a fileset by its name.
+
+ Args:
+ ctx (Context): The request context object.
+ catalog_name (str): Name of the catalog.
+ schema_name (str): Name of the schema.
+ fileset_name (str): Name of the fileset to drop.
+
+ Returns:
+ str: JSON-formatted string indicating whether the fileset was dropped.
+ """
+ client = ctx.request_context.lifespan_context.rest_client()
+ return await client.as_fileset_operation().drop_fileset(
+ catalog_name, schema_name, fileset_name
+ )
diff --git a/mcp-server/mcp_server/tools/model.py b/mcp-server/mcp_server/tools/model.py
index 4e5f21fdb5..655423e168 100644
--- a/mcp-server/mcp_server/tools/model.py
+++ b/mcp-server/mcp_server/tools/model.py
@@ -230,3 +230,120 @@ def load_model_tools(mcp: FastMCP):
return await client.as_model_operation().load_model_version_by_alias(
catalog_name, schema_name, model_name, alias
)
+
+ @mcp.tool(tags={"model"})
+ async def register_model(
+ ctx: Context,
+ catalog_name: str,
+ schema_name: str,
+ name: str,
+ comment: str,
+ properties: dict,
+ ) -> str:
+ """
+ Register a new model within a schema.
+
+ Authorization is enforced by Gravitino: a principal without the
+ required grant receives an authorization denial.
+
+ Args:
+ ctx (Context): The request context object.
+ catalog_name (str): Name of the catalog.
+ schema_name (str): Name of the schema.
+ name (str): Name of the model to register.
+ comment (str): Human-readable description.
+ properties (dict): Model configuration properties.
+
+ Returns:
+ str: JSON-formatted string containing the registered model.
+ """
+ client = ctx.request_context.lifespan_context.rest_client()
+ return await client.as_model_operation().register_model(
+ catalog_name, schema_name, name, comment, properties
+ )
+
+ @mcp.tool(tags={"model"})
+ async def delete_model(
+ ctx: Context, catalog_name: str, schema_name: str, model_name: str
+ ) -> str:
+ """
+ Delete a model by its name.
+
+ Args:
+ ctx (Context): The request context object.
+ catalog_name (str): Name of the catalog.
+ schema_name (str): Name of the schema.
+ model_name (str): Name of the model to delete.
+
+ Returns:
+ str: JSON-formatted string indicating whether the model was deleted.
+ """
+ client = ctx.request_context.lifespan_context.rest_client()
+ return await client.as_model_operation().delete_model(
+ catalog_name, schema_name, model_name
+ )
+
+ # pylint:disable=too-many-positional-arguments
+ @mcp.tool(tags={"model"})
+ async def link_model_version(
+ ctx: Context,
+ catalog_name: str,
+ schema_name: str,
+ model_name: str,
+ uri: str,
+ aliases: list,
+ comment: str,
+ properties: dict,
+ ) -> str:
+ """
+ Link a new version to an existing model.
+
+ Args:
+ ctx (Context): The request context object.
+ catalog_name (str): Name of the catalog.
+ schema_name (str): Name of the schema.
+ model_name (str): Name of the model.
+ uri (str): URI of the model version artifact.
+ aliases (list): List of string aliases for this version.
+ comment (str): Human-readable description.
+ properties (dict): Model version configuration properties.
+
+ Returns:
+ str: JSON-formatted string containing the linked model version.
+ """
+ client = ctx.request_context.lifespan_context.rest_client()
+ return await client.as_model_operation().link_model_version(
+ catalog_name,
+ schema_name,
+ model_name,
+ uri,
+ aliases,
+ comment,
+ properties,
+ )
+
+ @mcp.tool(tags={"model"})
+ async def delete_model_version(
+ ctx: Context,
+ catalog_name: str,
+ schema_name: str,
+ model_name: str,
+ version: int,
+ ) -> str:
+ """
+ Delete a specific version of a model.
+
+ Args:
+ ctx (Context): The request context object.
+ catalog_name (str): Name of the catalog.
+ schema_name (str): Name of the schema.
+ model_name (str): Name of the model.
+ version (int): Version number to delete.
+
+ Returns:
+ str: JSON-formatted string indicating whether the version was deleted.
+ """
+ client = ctx.request_context.lifespan_context.rest_client()
+ return await client.as_model_operation().delete_model_version(
+ catalog_name, schema_name, model_name, version
+ )
diff --git a/mcp-server/mcp_server/tools/schema.py b/mcp-server/mcp_server/tools/schema.py
index 3a37353a4b..dc5957c54d 100644
--- a/mcp-server/mcp_server/tools/schema.py
+++ b/mcp-server/mcp_server/tools/schema.py
@@ -61,3 +61,77 @@ def load_schema_tools(mcp: FastMCP):
return await client.as_schema_operation().get_list_of_schemas(
catalog_name
)
+
+ @mcp.tool(tags={"schema"})
+ async def create_schema(
+ ctx: Context,
+ catalog_name: str,
+ name: str,
+ comment: str,
+ properties: dict,
+ ) -> str:
+ """
+ Create a new schema within a catalog.
+
+ Authorization is enforced by Gravitino: a principal without the
+ required grant receives an authorization denial.
+
+ Args:
+ ctx (Context): The request context object.
+ catalog_name (str): Name of the catalog to create the schema in.
+ name (str): Name of the schema to create.
+ comment (str): Human-readable description.
+ properties (dict): Schema configuration properties.
+
+ Returns:
+ str: JSON-formatted string containing the created schema.
+ """
+ client = ctx.request_context.lifespan_context.rest_client()
+ return await client.as_schema_operation().create_schema(
+ catalog_name, name, comment, properties
+ )
+
+ @mcp.tool(tags={"schema"})
+ async def alter_schema(
+ ctx: Context, catalog_name: str, schema_name: str, updates: list
+ ) -> str:
+ """
+ Alter an existing schema.
+
+ Args:
+ ctx (Context): The request context object.
+ catalog_name (str): Name of the catalog containing the schema.
+ schema_name (str): Name of the schema to alter.
+ updates (list): List of update operations. Example:
+ [
+ {"@type": "setProperty", "property": "k", "value": "v"},
+ {"@type": "removeProperty", "property": "k"}
+ ]
+
+ Returns:
+ str: JSON-formatted string containing the altered schema.
+ """
+ client = ctx.request_context.lifespan_context.rest_client()
+ return await client.as_schema_operation().alter_schema(
+ catalog_name, schema_name, updates
+ )
+
+ @mcp.tool(tags={"schema"})
+ async def drop_schema(
+ ctx: Context, catalog_name: str, schema_name: str
+ ) -> str:
+ """
+ Drop a schema by its name.
+
+ Args:
+ ctx (Context): The request context object.
+ catalog_name (str): Name of the catalog containing the schema.
+ schema_name (str): Name of the schema to drop.
+
+ Returns:
+ str: JSON-formatted string indicating whether the schema was dropped.
+ """
+ client = ctx.request_context.lifespan_context.rest_client()
+ return await client.as_schema_operation().drop_schema(
+ catalog_name, schema_name
+ )
diff --git a/mcp-server/mcp_server/tools/table.py b/mcp-server/mcp_server/tools/table.py
index af6c62da6f..fbb3f03846 100644
--- a/mcp-server/mcp_server/tools/table.py
+++ b/mcp-server/mcp_server/tools/table.py
@@ -257,3 +257,95 @@ def load_table_tools(mcp: FastMCP):
return await client.as_table_operation().load_table(
catalog_name, schema_name, table_name
)
+
+ @mcp.tool(tags={"table"})
+ async def create_table(
+ ctx: Context,
+ catalog_name: str,
+ schema_name: str,
+ name: str,
+ comment: str,
+ columns: list,
+ properties: dict,
+ ) -> str:
+ """
+ Create a new table within a schema.
+
+ Authorization is enforced by Gravitino: a principal without the
+ required grant receives an authorization denial.
+
+ Args:
+ ctx (Context): The request context object.
+ catalog_name (str): Name of the catalog.
+ schema_name (str): Name of the schema.
+ name (str): Name of the table to create.
+ comment (str): Human-readable description.
+ columns (list): List of column definitions. Each column is a dict:
+ {
+ "name": "id",
+ "type": "integer",
+ "comment": "primary id",
+ "nullable": false,
+ "autoIncrement": false
+ }
+ properties (dict): Table configuration properties.
+
+ Returns:
+ str: JSON-formatted string containing the created table.
+ """
+ client = ctx.request_context.lifespan_context.rest_client()
+ return await client.as_table_operation().create_table(
+ catalog_name, schema_name, name, comment, columns, properties
+ )
+
+ @mcp.tool(tags={"table"})
+ async def alter_table(
+ ctx: Context,
+ catalog_name: str,
+ schema_name: str,
+ table_name: str,
+ updates: list,
+ ) -> str:
+ """
+ Alter an existing table.
+
+ Args:
+ ctx (Context): The request context object.
+ catalog_name (str): Name of the catalog.
+ schema_name (str): Name of the schema.
+ table_name (str): Name of the table to alter.
+ updates (list): List of update operations. Example:
+ [
+ {"@type": "rename", "newName": "new_table"},
+ {"@type": "updateComment", "newComment": "updated"},
+ {"@type": "setProperty", "property": "k", "value": "v"}
+ ]
+
+ Returns:
+ str: JSON-formatted string containing the altered table.
+ """
+ client = ctx.request_context.lifespan_context.rest_client()
+ return await client.as_table_operation().alter_table(
+ catalog_name, schema_name, table_name, updates
+ )
+
+ @mcp.tool(tags={"table"})
+ async def drop_table(
+ ctx: Context, catalog_name: str, schema_name: str, table_name: str
+ ) -> str:
+ """
+ Drop a table by its name.
+
+ Args:
+ ctx (Context): The request context object.
+ catalog_name (str): Name of the catalog.
+ schema_name (str): Name of the schema.
+ table_name (str): Name of the table to drop.
+
+ Returns:
+ str: JSON-formatted string indicating whether the table was dropped.
+ """
+ client = ctx.request_context.lifespan_context.rest_client()
+ return await client.as_table_operation().drop_table(
+ catalog_name, schema_name, table_name
+ )
diff --git a/mcp-server/mcp_server/tools/topic.py b/mcp-server/mcp_server/tools/topic.py
index 93d2aa57d5..82813bcaf3 100644
--- a/mcp-server/mcp_server/tools/topic.py
+++ b/mcp-server/mcp_server/tools/topic.py
@@ -132,3 +132,85 @@ def load_topic_tools(mcp: FastMCP):
return await client.as_topic_operation().load_topic(
catalog_name, schema_name, topic_name
)
+
+ @mcp.tool(tags={"topic"})
+ async def create_topic(
+ ctx: Context,
+ catalog_name: str,
+ schema_name: str,
+ name: str,
+ comment: str,
+ properties: dict,
+ ) -> str:
+ """
+ Create a new topic within a schema.
+
+ Authorization is enforced by Gravitino: a principal without the
+ required grant receives an authorization denial.
+
+ Args:
+ ctx (Context): The request context object.
+ catalog_name (str): Name of the catalog.
+ schema_name (str): Name of the schema.
+ name (str): Name of the topic to create.
+ comment (str): Human-readable description.
+ properties (dict): Topic configuration properties.
+
+ Returns:
+ str: JSON-formatted string containing the created topic.
+ """
+ client = ctx.request_context.lifespan_context.rest_client()
+ return await client.as_topic_operation().create_topic(
+ catalog_name, schema_name, name, comment, properties
+ )
+
+ @mcp.tool(tags={"topic"})
+ async def alter_topic(
+ ctx: Context,
+ catalog_name: str,
+ schema_name: str,
+ topic_name: str,
+ updates: list,
+ ) -> str:
+ """
+ Alter an existing topic.
+
+ Args:
+ ctx (Context): The request context object.
+ catalog_name (str): Name of the catalog.
+ schema_name (str): Name of the schema.
+ topic_name (str): Name of the topic to alter.
+ updates (list): List of update operations. Example:
+ [
+ {"@type": "updateComment", "newComment": "updated"},
+ {"@type": "setProperty", "property": "k", "value": "v"}
+ ]
+
+ Returns:
+ str: JSON-formatted string containing the altered topic.
+ """
+ client = ctx.request_context.lifespan_context.rest_client()
+ return await client.as_topic_operation().alter_topic(
+ catalog_name, schema_name, topic_name, updates
+ )
+
+ @mcp.tool(tags={"topic"})
+ async def delete_topic(
+ ctx: Context, catalog_name: str, schema_name: str, topic_name: str
+ ) -> str:
+ """
+ Delete a topic by its name.
+
+ Args:
+ ctx (Context): The request context object.
+ catalog_name (str): Name of the catalog.
+ schema_name (str): Name of the schema.
+ topic_name (str): Name of the topic to delete.
+
+ Returns:
+ str: JSON-formatted string indicating whether the topic was deleted.
+ """
+ client = ctx.request_context.lifespan_context.rest_client()
+ return await client.as_topic_operation().delete_topic(
+ catalog_name, schema_name, topic_name
+ )
diff --git a/mcp-server/tests/unit/test_audit.py b/mcp-server/tests/unit/test_audit.py
index 37cdef29cb..c52a09a391 100644
--- a/mcp-server/tests/unit/test_audit.py
+++ b/mcp-server/tests/unit/test_audit.py
@@ -25,7 +25,9 @@ from fastmcp import Client
from mcp_server.client.factory import RESTClientFactory
from mcp_server.client.plain.exception import GravitinoException
-from mcp_server.client.plain.plain_rest_client_operation import PlainRESTClientOperation
+from mcp_server.client.plain.plain_rest_client_operation import (
+ PlainRESTClientOperation,
+)
from mcp_server.core import audit
from mcp_server.core.setting import Setting
from mcp_server.server import GravitinoMCPServer
@@ -54,7 +56,9 @@ class TestAuditEmit(unittest.TestCase):
def test_allow_record_structure(self):
"""emit() writes a JSON record with all required fields on allow."""
- audit.emit(principal="bearer:abc12345", tool="list_catalogs", outcome="allow")
+ audit.emit(
+ principal="bearer:abc12345", tool="list_catalogs", outcome="allow"
+ )
self.assertEqual(len(self.log_records), 1)
record = json.loads(self.log_records[0])
@@ -79,7 +83,9 @@ class TestAuditEmit(unittest.TestCase):
def test_anonymous_principal(self):
"""emit() works with anonymous principal."""
- audit.emit(principal="anonymous", tool="get_list_of_catalogs", outcome="allow")
+ audit.emit(
+ principal="anonymous", tool="get_list_of_catalogs", outcome="allow"
+ )
record = json.loads(self.log_records[0])
self.assertEqual(record["principal"], "anonymous")
@@ -173,6 +179,7 @@ class TestAuditMiddlewareIntegration(unittest.TestCase):
# Helpers
# ---------------------------------------------------------------------------
+
class _CapturingHandler(logging.Handler):
"""Logging handler that stores formatted messages in a list."""
diff --git a/mcp-server/tests/unit/test_auth_flow.py b/mcp-server/tests/unit/test_auth_flow.py
index a413515bf9..ca6b59b671 100644
--- a/mcp-server/tests/unit/test_auth_flow.py
+++ b/mcp-server/tests/unit/test_auth_flow.py
@@ -45,7 +45,9 @@ class TestTokenInjection(unittest.TestCase):
def test_no_token_argument_no_authorization_header(self):
"""When token argument is omitted entirely, no Authorization header is added."""
- client = PlainRESTClientOperation("my_metalake", "http://localhost:8090")
+ client = PlainRESTClientOperation(
+ "my_metalake", "http://localhost:8090"
+ )
headers = dict(client._catalog_operation.rest_client.headers)
self.assertNotIn("authorization", headers)
diff --git a/mcp-server/tests/unit/test_per_request_token.py b/mcp-server/tests/unit/test_per_request_token.py
index c08cbeeb39..77ad709ce6 100644
--- a/mcp-server/tests/unit/test_per_request_token.py
+++ b/mcp-server/tests/unit/test_per_request_token.py
@@ -38,7 +38,9 @@ class TestExtractBearerToken(unittest.TestCase):
"""Unit tests for the token extraction helper."""
def test_well_formed_bearer_header(self):
- self.assertEqual(_extract_bearer_token("Bearer mytoken123"), "mytoken123")
+ self.assertEqual(
+ _extract_bearer_token("Bearer mytoken123"), "mytoken123"
+ )
def test_case_insensitive_bearer(self):
self.assertEqual(_extract_bearer_token("bearer MYTOKEN"), "MYTOKEN")
@@ -153,8 +155,12 @@ class TestGravitinoContextPerRequestToken(unittest.TestCase):
):
client_bob = ctx.rest_client()
- alice_headers = dict(client_alice._catalog_operation.rest_client.headers)
+ alice_headers = dict(
+ client_alice._catalog_operation.rest_client.headers
+ )
bob_headers = dict(client_bob._catalog_operation.rest_client.headers)
- self.assertEqual(alice_headers.get("authorization"), "Bearer alice-token")
+ self.assertEqual(
+ alice_headers.get("authorization"), "Bearer alice-token"
+ )
self.assertEqual(bob_headers.get("authorization"), "Bearer bob-token")
self.assertIsNot(client_alice, client_bob)
diff --git a/mcp-server/tests/unit/tools/mock_operation.py b/mcp-server/tests/unit/tools/mock_operation.py
index a985bf7912..eb6c1f2cff 100644
--- a/mcp-server/tests/unit/tools/mock_operation.py
+++ b/mcp-server/tests/unit/tools/mock_operation.py
@@ -69,11 +69,33 @@ class MockCatalogOperation(CatalogOperation):
async def get_list_of_catalogs(self) -> str:
return "mock_catalogs"
+ async def create_catalog(
+ self, name, catalog_type, provider, comment, properties
+ ) -> str:
+ return f"mock_catalog_created: {name}, {catalog_type}, {provider}"
+
+ async def alter_catalog(self, catalog_name, updates) -> str:
+ return f"mock_catalog_altered: {catalog_name} with updates {updates}"
+
+ async def drop_catalog(self, catalog_name) -> str:
+ return f"mock_catalog_dropped: {catalog_name}"
+
class MockSchemaOperation(SchemaOperation):
async def get_list_of_schemas(self, catalog_name: str) -> str:
return "mock_schemas"
+ async def create_schema(
+ self, catalog_name, name, comment, properties
+ ) -> str:
+ return f"mock_schema_created: {catalog_name}.{name}"
+
+ async def alter_schema(self, catalog_name, schema_name, updates) -> str:
+ return f"mock_schema_altered: {catalog_name}.{schema_name} with updates {updates}"
+
+ async def drop_schema(self, catalog_name, schema_name) -> str:
+ return f"mock_schema_dropped: {catalog_name}.{schema_name}"
+
class MockTableOperation(TableOperation):
async def get_list_of_tables(
@@ -86,6 +108,23 @@ class MockTableOperation(TableOperation):
) -> str:
return "mock_table"
+ # pylint: disable=R0917
+ async def create_table(
+ self, catalog_name, schema_name, name, comment, columns, properties
+ ) -> str:
+ return f"mock_table_created: {catalog_name}.{schema_name}.{name}"
+
+ async def alter_table(
+ self, catalog_name, schema_name, table_name, updates
+ ) -> str:
+ return (
+ f"mock_table_altered: {catalog_name}.{schema_name}.{table_name} "
+ f"with updates {updates}"
+ )
+
+ async def drop_table(self, catalog_name, schema_name, table_name) -> str:
+ return f"mock_table_dropped: {catalog_name}.{schema_name}.{table_name}"
+
class MockFilesetOperation(FilesetOperation):
async def list_of_filesets(
@@ -110,6 +149,34 @@ class MockFilesetOperation(FilesetOperation):
) -> str:
return "mock_files_in_fileset"
+ # pylint: disable=R0917
+ async def create_fileset(
+ self,
+ catalog_name,
+ schema_name,
+ name,
+ fileset_type,
+ storage_location,
+ comment,
+ properties,
+ ) -> str:
+ return f"mock_fileset_created: {catalog_name}.{schema_name}.{name}"
+
+ async def alter_fileset(
+ self, catalog_name, schema_name, fileset_name, updates
+ ) -> str:
+ return (
+ f"mock_fileset_altered: {catalog_name}.{schema_name}.{fileset_name} "
+ f"with updates {updates}"
+ )
+
+ async def drop_fileset(
+ self, catalog_name, schema_name, fileset_name
+ ) -> str:
+ return (
+ f"mock_fileset_dropped: {catalog_name}.{schema_name}.{fileset_name}"
+ )
+
class MockPolicyOperation(PolicyOperation):
async def associate_policy_with_metadata(
@@ -170,6 +237,38 @@ class MockModelOperation(ModelOperation):
) -> str:
return "mock_model_version_by_alias"
+ async def register_model(
+ self, catalog_name, schema_name, name, comment, properties
+ ) -> str:
+ return f"mock_model_registered: {catalog_name}.{schema_name}.{name}"
+
+ async def delete_model(self, catalog_name, schema_name, model_name) -> str:
+ return f"mock_model_deleted: {catalog_name}.{schema_name}.{model_name}"
+
+ # pylint: disable=R0917
+ async def link_model_version(
+ self,
+ catalog_name,
+ schema_name,
+ model_name,
+ uri,
+ aliases,
+ comment,
+ properties,
+ ) -> str:
+ return (
+ f"mock_model_version_linked: {catalog_name}.{schema_name}.{model_name} "
+ f"uri={uri} aliases={aliases}"
+ )
+
+ async def delete_model_version(
+ self, catalog_name, schema_name, model_name, version
+ ) -> str:
+ return (
+ f"mock_model_version_deleted: {catalog_name}.{schema_name}.{model_name} "
+ f"version={version}"
+ )
+
class MockTopicOperation(TopicOperation):
async def list_of_topics(self, catalog_name: str, schema_name: str) -> str:
@@ -180,6 +279,22 @@ class MockTopicOperation(TopicOperation):
) -> str:
return "mock_topic"
+ async def create_topic(
+ self, catalog_name, schema_name, name, comment, properties
+ ) -> str:
+ return f"mock_topic_created: {catalog_name}.{schema_name}.{name}"
+
+ async def alter_topic(
+ self, catalog_name, schema_name, topic_name, updates
+ ) -> str:
+ return (
+ f"mock_topic_altered: {catalog_name}.{schema_name}.{topic_name} "
+ f"with updates {updates}"
+ )
+
+ async def delete_topic(self, catalog_name, schema_name, topic_name) -> str:
+ return f"mock_topic_deleted: {catalog_name}.{schema_name}.{topic_name}"
+
class MockTagOperation(TagOperation):
async def list_of_tags(self) -> str:
diff --git a/mcp-server/tests/unit/tools/test_catalog.py b/mcp-server/tests/unit/tools/test_catalog.py
index ca6c03f735..bf92a9adef 100644
--- a/mcp-server/tests/unit/tools/test_catalog.py
+++ b/mcp-server/tests/unit/tools/test_catalog.py
@@ -45,3 +45,61 @@ class TestCatalogTool(unittest.TestCase):
self.assertEqual("mock_catalogs", result.content[0].text)
asyncio.run(_test_list_catalogs(self.mcp))
+
+ def test_create_catalog(self):
+ async def _test(mcp_server):
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "create_catalog",
+ {
+ "name": "cat1",
+ "catalog_type": "relational",
+ "provider": "hive",
+ "comment": "c",
+ "properties": {"k": "v"},
+ },
+ )
+ self.assertEqual(
+ "mock_catalog_created: cat1, relational, hive",
+ result.content[0].text,
+ )
+
+ asyncio.run(_test(self.mcp))
+
+ def test_alter_catalog(self):
+ async def _test(mcp_server):
+ updates = [{"@type": "rename", "newName": "cat2"}]
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "alter_catalog",
+ {"catalog_name": "cat1", "updates": updates},
+ )
+ self.assertEqual(
+ f"mock_catalog_altered: cat1 with updates {updates}",
+ result.content[0].text,
+ )
+
+ asyncio.run(_test(self.mcp))
+
+ def test_drop_catalog(self):
+ async def _test(mcp_server):
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "drop_catalog", {"catalog_name": "cat1"}
+ )
+ self.assertEqual(
+ "mock_catalog_dropped: cat1", result.content[0].text
+ )
+
+ asyncio.run(_test(self.mcp))
+
+ def test_write_tools_exposed(self):
+ """Write tools must be present (authorization enforced by Gravitino)."""
+
+ async def _test(mcp_server):
+ names = {t.name for t in await mcp_server.list_tools()}
+ self.assertIn("create_catalog", names)
+ self.assertIn("alter_catalog", names)
+ self.assertIn("drop_catalog", names)
+
+ asyncio.run(_test(self.mcp))
diff --git a/mcp-server/tests/unit/tools/test_fileset.py b/mcp-server/tests/unit/tools/test_fileset.py
index a0c0371491..7a338133d4 100644
--- a/mcp-server/tests/unit/tools/test_fileset.py
+++ b/mcp-server/tests/unit/tools/test_fileset.py
@@ -75,3 +75,61 @@ class TestFilesetTool(unittest.TestCase):
)
asyncio.run(_test_list_files_in_fileset(self.mcp))
+
+ def test_create_fileset(self):
+ async def _test(mcp_server):
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "create_fileset",
+ {
+ "catalog_name": "cat",
+ "schema_name": "sch",
+ "name": "fs",
+ "fileset_type": "managed",
+ "storage_location": "file:/tmp/fs",
+ "comment": "c",
+ "properties": {"k": "v"},
+ },
+ )
+ self.assertEqual(
+ "mock_fileset_created: cat.sch.fs", result.content[0].text
+ )
+
+ asyncio.run(_test(self.mcp))
+
+ def test_alter_fileset(self):
+ async def _test(mcp_server):
+ updates = [{"@type": "rename", "newName": "fs2"}]
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "alter_fileset",
+ {
+ "catalog_name": "cat",
+ "schema_name": "sch",
+ "fileset_name": "fs",
+ "updates": updates,
+ },
+ )
+ self.assertEqual(
+ f"mock_fileset_altered: cat.sch.fs with updates {updates}",
+ result.content[0].text,
+ )
+
+ asyncio.run(_test(self.mcp))
+
+ def test_drop_fileset(self):
+ async def _test(mcp_server):
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "drop_fileset",
+ {
+ "catalog_name": "cat",
+ "schema_name": "sch",
+ "fileset_name": "fs",
+ },
+ )
+ self.assertEqual(
+ "mock_fileset_dropped: cat.sch.fs", result.content[0].text
+ )
+
+ asyncio.run(_test(self.mcp))
diff --git a/mcp-server/tests/unit/tools/test_model.py b/mcp-server/tests/unit/tools/test_model.py
index ff27e64d3b..09d8db2b39 100644
--- a/mcp-server/tests/unit/tools/test_model.py
+++ b/mcp-server/tests/unit/tools/test_model.py
@@ -106,3 +106,81 @@ class TestModelTool(unittest.TestCase):
)
asyncio.run(_test_load_model_version_by_alias(self.mcp))
+
+ def test_register_model(self):
+ async def _test(mcp_server):
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "register_model",
+ {
+ "catalog_name": "cat",
+ "schema_name": "sch",
+ "name": "m",
+ "comment": "c",
+ "properties": {"k": "v"},
+ },
+ )
+ self.assertEqual(
+ "mock_model_registered: cat.sch.m", result.content[0].text
+ )
+
+ asyncio.run(_test(self.mcp))
+
+ def test_delete_model(self):
+ async def _test(mcp_server):
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "delete_model",
+ {
+ "catalog_name": "cat",
+ "schema_name": "sch",
+ "model_name": "m",
+ },
+ )
+ self.assertEqual(
+ "mock_model_deleted: cat.sch.m", result.content[0].text
+ )
+
+ asyncio.run(_test(self.mcp))
+
+ def test_link_model_version(self):
+ async def _test(mcp_server):
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "link_model_version",
+ {
+ "catalog_name": "cat",
+ "schema_name": "sch",
+ "model_name": "m",
+ "uri": "s3://bucket/model",
+ "aliases": ["latest"],
+ "comment": "c",
+ "properties": {"k": "v"},
+ },
+ )
+ self.assertEqual(
+ "mock_model_version_linked: cat.sch.m "
+ "uri=s3://bucket/model aliases=['latest']",
+ result.content[0].text,
+ )
+
+ asyncio.run(_test(self.mcp))
+
+ def test_delete_model_version(self):
+ async def _test(mcp_server):
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "delete_model_version",
+ {
+ "catalog_name": "cat",
+ "schema_name": "sch",
+ "model_name": "m",
+ "version": 1,
+ },
+ )
+ self.assertEqual(
+ "mock_model_version_deleted: cat.sch.m version=1",
+ result.content[0].text,
+ )
+
+ asyncio.run(_test(self.mcp))
diff --git a/mcp-server/tests/unit/tools/test_schema.py b/mcp-server/tests/unit/tools/test_schema.py
index 443c3968dc..ef6d3cd118 100644
--- a/mcp-server/tests/unit/tools/test_schema.py
+++ b/mcp-server/tests/unit/tools/test_schema.py
@@ -42,3 +42,53 @@ class TestSchemaTool(unittest.TestCase):
self.assertEqual("mock_schemas", result.content[0].text)
asyncio.run(_test_list_schemas(self.mcp))
+
+ def test_create_schema(self):
+ async def _test(mcp_server):
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "create_schema",
+ {
+ "catalog_name": "cat",
+ "name": "sch",
+ "comment": "c",
+ "properties": {"k": "v"},
+ },
+ )
+ self.assertEqual(
+ "mock_schema_created: cat.sch", result.content[0].text
+ )
+
+ asyncio.run(_test(self.mcp))
+
+ def test_alter_schema(self):
+ async def _test(mcp_server):
+ updates = [{"@type": "setProperty", "property": "k", "value": "v"}]
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "alter_schema",
+ {
+ "catalog_name": "cat",
+ "schema_name": "sch",
+ "updates": updates,
+ },
+ )
+ self.assertEqual(
+ f"mock_schema_altered: cat.sch with updates {updates}",
+ result.content[0].text,
+ )
+
+ asyncio.run(_test(self.mcp))
+
+ def test_drop_schema(self):
+ async def _test(mcp_server):
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "drop_schema",
+ {"catalog_name": "cat", "schema_name": "sch"},
+ )
+ self.assertEqual(
+ "mock_schema_dropped: cat.sch", result.content[0].text
+ )
+
+ asyncio.run(_test(self.mcp))
diff --git a/mcp-server/tests/unit/tools/test_table.py b/mcp-server/tests/unit/tools/test_table.py
index 1b426e5512..b14cd2d13b 100644
--- a/mcp-server/tests/unit/tools/test_table.py
+++ b/mcp-server/tests/unit/tools/test_table.py
@@ -57,3 +57,61 @@ class TestTableTool(unittest.TestCase):
self.assertEqual("mock_table", result.content[0].text)
asyncio.run(_test_load_table(self.mcp))
+
+ def test_create_table(self):
+ async def _test(mcp_server):
+ columns = [{"name": "id", "type": "integer", "nullable": False}]
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "create_table",
+ {
+ "catalog_name": "cat",
+ "schema_name": "sch",
+ "name": "tbl",
+ "comment": "c",
+ "columns": columns,
+ "properties": {"k": "v"},
+ },
+ )
+ self.assertEqual(
+ "mock_table_created: cat.sch.tbl", result.content[0].text
+ )
+
+ asyncio.run(_test(self.mcp))
+
+ def test_alter_table(self):
+ async def _test(mcp_server):
+ updates = [{"@type": "rename", "newName": "tbl2"}]
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "alter_table",
+ {
+ "catalog_name": "cat",
+ "schema_name": "sch",
+ "table_name": "tbl",
+ "updates": updates,
+ },
+ )
+ self.assertEqual(
+ f"mock_table_altered: cat.sch.tbl with updates {updates}",
+ result.content[0].text,
+ )
+
+ asyncio.run(_test(self.mcp))
+
+ def test_drop_table(self):
+ async def _test(mcp_server):
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "drop_table",
+ {
+ "catalog_name": "cat",
+ "schema_name": "sch",
+ "table_name": "tbl",
+ },
+ )
+ self.assertEqual(
+ "mock_table_dropped: cat.sch.tbl", result.content[0].text
+ )
+
+ asyncio.run(_test(self.mcp))
diff --git a/mcp-server/tests/unit/tools/test_topic.py b/mcp-server/tests/unit/tools/test_topic.py
index 28422d0634..6f3f915bb8 100644
--- a/mcp-server/tests/unit/tools/test_topic.py
+++ b/mcp-server/tests/unit/tools/test_topic.py
@@ -57,3 +57,59 @@ class TestTopicTool(unittest.TestCase):
self.assertEqual("mock_topic", result.content[0].text)
asyncio.run(_test_load_topic(self.mcp))
+
+ def test_create_topic(self):
+ async def _test(mcp_server):
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "create_topic",
+ {
+ "catalog_name": "cat",
+ "schema_name": "sch",
+ "name": "tp",
+ "comment": "c",
+ "properties": {"k": "v"},
+ },
+ )
+ self.assertEqual(
+ "mock_topic_created: cat.sch.tp", result.content[0].text
+ )
+
+ asyncio.run(_test(self.mcp))
+
+ def test_alter_topic(self):
+ async def _test(mcp_server):
+ updates = [{"@type": "setProperty", "property": "k", "value": "v"}]
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "alter_topic",
+ {
+ "catalog_name": "cat",
+ "schema_name": "sch",
+ "topic_name": "tp",
+ "updates": updates,
+ },
+ )
+ self.assertEqual(
+ f"mock_topic_altered: cat.sch.tp with updates {updates}",
+ result.content[0].text,
+ )
+
+ asyncio.run(_test(self.mcp))
+
+ def test_delete_topic(self):
+ async def _test(mcp_server):
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "delete_topic",
+ {
+ "catalog_name": "cat",
+ "schema_name": "sch",
+ "topic_name": "tp",
+ },
+ )
+ self.assertEqual(
+ "mock_topic_deleted: cat.sch.tp", result.content[0].text
+ )
+
+ asyncio.run(_test(self.mcp))
(gravitino) 06/09: [#11575] refactor(mcp-server): forward raw Authorization header instead of assuming Bearer
Posted by yu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yuqi1129 pushed a commit to branch feat/mcp-governance-task3-6
in repository https://gitbox.apache.org/repos/asf/gravitino.git
commit 4e27ce044d9899f615beee4837295ed3b150ccae
Author: yuqi <yu...@datastrato.com>
AuthorDate: Wed Jun 10 22:50:51 2026 +0800
[#11575] refactor(mcp-server): forward raw Authorization header instead of assuming Bearer
To support Gravitino simple authentication (Authorization: Basic base64(user:dummy))
in addition to OAuth2 Bearer tokens, the per-request HTTP path now forwards the
incoming Authorization header verbatim to Gravitino rather than extracting and
re-wrapping a Bearer token. The auth scheme is chosen by the agent and preserved.
- PlainRESTClientOperation / factory: rename `token` param to `authorization`
(full header value forwarded verbatim).
- GravitinoContext: static --token still wraps as `Bearer {token}` (OAuth2);
per-request path forwards the raw header (Basic/Bearer/Negotiate all work).
- audit._extract_principal: decode `Basic base64(user:secret)` to the username
so audit records attribute simple-auth requests to the real principal.
- Update unit tests accordingly (110 passing).
This is the prerequisite for the live-Gravitino authorization integration test.
---
mcp-server/mcp_server/client/factory.py | 8 +-
.../client/plain/plain_rest_client_operation.py | 16 +++-
mcp-server/mcp_server/core/audit.py | 22 ++++--
mcp-server/mcp_server/core/context.py | 43 +++++------
mcp-server/tests/unit/test_audit.py | 17 ++++
mcp-server/tests/unit/test_auth_flow.py | 32 +++++---
mcp-server/tests/unit/test_per_request_token.py | 90 ++++++++++------------
mcp-server/tests/unit/tools/mock_operation.py | 2 +-
8 files changed, 136 insertions(+), 94 deletions(-)
diff --git a/mcp-server/mcp_server/client/factory.py b/mcp-server/mcp_server/client/factory.py
index 2e5489d053..201625540d 100644
--- a/mcp-server/mcp_server/client/factory.py
+++ b/mcp-server/mcp_server/client/factory.py
@@ -29,7 +29,7 @@ class RESTClientFactory:
@classmethod
def create_rest_client(
- cls, metalake_name: str, uri: str, token: str = ""
+ cls, metalake_name: str, uri: str, authorization: str = ""
) -> "PlainRESTClientOperation":
"""
Create a new rest client instance with the specified parameters.
@@ -37,12 +37,14 @@ class RESTClientFactory:
Args:
metalake_name: Name of the metalake
uri: URI of the Gravitino server endpoint
- token: Bearer token for Authorization header (empty = anonymous)
+ authorization: Full Authorization header value forwarded verbatim
+ (e.g. "Bearer <token>" or "Basic <base64(user:dummy)>").
+ Empty string means anonymous.
Returns:
New instance of the configured rest client class
"""
- return cls._rest_client_class(metalake_name, uri, token)
+ return cls._rest_client_class(metalake_name, uri, authorization)
@classmethod
def set_rest_client(cls, rest_client_class: type) -> None:
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 8bb8b51aa3..6a612dd946 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
@@ -62,10 +62,20 @@ from mcp_server.client.topic_operation import TopicOperation
# pylint: disable=too-many-instance-attributes
class PlainRESTClientOperation(GravitinoOperation):
- def __init__(self, metalake_name: str, uri: str, token: str = ""):
+ def __init__(self, metalake_name: str, uri: str, authorization: str = ""):
+ """Create a REST client for one identity.
+
+ Args:
+ metalake_name: Name of the metalake.
+ uri: Gravitino server URI.
+ authorization: Full ``Authorization`` header value forwarded verbatim
+ on every request (for example ``"Bearer <token>"`` for OAuth2 or
+ ``"Basic <base64(user:dummy)>"`` for simple auth). Empty string
+ means anonymous (no header sent).
+ """
headers = {}
- if token:
- headers["Authorization"] = f"Bearer {token}"
+ if authorization:
+ headers["Authorization"] = authorization
_rest_client = httpx.AsyncClient(base_url=uri, headers=headers)
self._catalog_operation = PlainRESTClientCatalogOperation(
metalake_name, _rest_client
diff --git a/mcp-server/mcp_server/core/audit.py b/mcp-server/mcp_server/core/audit.py
index f65b71cdff..fffd3592f2 100644
--- a/mcp-server/mcp_server/core/audit.py
+++ b/mcp-server/mcp_server/core/audit.py
@@ -15,6 +15,8 @@
# specific language governing permissions and limitations
# under the License.
+import base64
+import binascii
import json
import logging
from datetime import datetime, timezone
@@ -25,15 +27,25 @@ _audit_logger = logging.getLogger("gravitino.mcp.audit")
def _extract_principal(authorization: str) -> str:
"""Derive a display principal from a raw Authorization header value.
- - "Bearer <token>" → "bearer:<first-8-chars-of-token>"
- - empty / missing → "anonymous"
+ - "Basic <base64(user:secret)>" → "<user>" (Gravitino simple auth)
+ - "Bearer <token>" → "bearer:<first-8-chars-of-token>"
+ - empty / missing / unparsable → "anonymous"
"""
if not authorization:
return "anonymous"
parts = authorization.split()
- if len(parts) == 2 and parts[0].lower() == "bearer":
- token = parts[1]
- return f"bearer:{token[:8]}"
+ if len(parts) != 2:
+ return "anonymous"
+ scheme, credential = parts[0].lower(), parts[1]
+ if scheme == "basic":
+ try:
+ decoded = base64.b64decode(credential).decode("utf-8")
+ except (binascii.Error, UnicodeDecodeError, ValueError):
+ return "anonymous"
+ user = decoded.split(":", 1)[0]
+ return user if user else "anonymous"
+ if scheme == "bearer":
+ return f"bearer:{credential[:8]}"
return "anonymous"
diff --git a/mcp-server/mcp_server/core/context.py b/mcp-server/mcp_server/core/context.py
index f2cde66692..48e4c83614 100644
--- a/mcp-server/mcp_server/core/context.py
+++ b/mcp-server/mcp_server/core/context.py
@@ -19,24 +19,18 @@ from mcp_server.client.factory import RESTClientFactory
from mcp_server.core.setting import Setting
-def _extract_bearer_token(authorization: str) -> str:
- """Parse a Bearer token from a raw Authorization header value."""
- parts = authorization.split()
- if len(parts) == 2 and parts[0].lower() == "bearer":
- return parts[1]
- return ""
+def _get_request_authorization() -> str:
+ """Return the raw ``Authorization`` header of the current HTTP request.
-
-def _get_request_token() -> str:
- """Extract the Bearer token from the current HTTP request, if any.
-
- Returns an empty string in stdio mode or when the header is absent.
+ The header is forwarded to Gravitino verbatim so the auth scheme chosen by
+ the agent (``Basic`` for simple auth, ``Bearer`` for OAuth2, ``Negotiate``
+ for Kerberos) is preserved. Returns an empty string in stdio mode or when
+ the header is absent.
"""
try:
from fastmcp.server.dependencies import get_http_request
- authorization = get_http_request().headers.get("authorization", "")
- return _extract_bearer_token(authorization)
+ return get_http_request().headers.get("authorization", "")
except Exception: # noqa: BLE001 – stdio mode or missing request context
return ""
@@ -44,28 +38,33 @@ def _get_request_token() -> str:
class GravitinoContext:
def __init__(self, setting: Setting):
self._setting = setting
- # Fallback client for stdio mode or when no per-request token is present.
+ # Static startup identity: the --token CLI value is treated as a Bearer
+ # token (OAuth2). Used in stdio mode or as the fallback when an HTTP
+ # request carries no Authorization header.
+ default_authorization = (
+ f"Bearer {setting.token}" if setting.token else ""
+ )
self._default_client = RESTClientFactory.create_rest_client(
- setting.metalake, setting.gravitino_uri, setting.token
+ setting.metalake, setting.gravitino_uri, default_authorization
)
def rest_client(self):
"""Return a REST client carrying the correct identity for this request.
- In HTTP transport mode the Bearer token from the incoming MCP request's
- Authorization header takes priority over the static startup token.
- This ensures concurrent sessions with different principals are fully
- isolated — one principal's token never leaks into another's Gravitino calls.
+ In HTTP transport mode the incoming request's ``Authorization`` header is
+ forwarded verbatim to Gravitino, taking priority over the static startup
+ token. This keeps concurrent sessions with different principals fully
+ isolated — one principal's identity never leaks into another's calls.
Falls back to the shared default client (static startup token) when:
- running in stdio mode (no HTTP request context), or
- the incoming request carries no Authorization header.
"""
- request_token = _get_request_token()
- if request_token:
+ authorization = _get_request_authorization()
+ if authorization:
return RESTClientFactory.create_rest_client(
self._setting.metalake,
self._setting.gravitino_uri,
- request_token,
+ authorization,
)
return self._default_client
diff --git a/mcp-server/tests/unit/test_audit.py b/mcp-server/tests/unit/test_audit.py
index c52a09a391..24bca0efee 100644
--- a/mcp-server/tests/unit/test_audit.py
+++ b/mcp-server/tests/unit/test_audit.py
@@ -108,6 +108,23 @@ class TestExtractPrincipal(unittest.TestCase):
def test_short_token_uses_full_token(self):
self.assertEqual(audit._extract_principal("Bearer abc"), "bearer:abc")
+ def test_basic_auth_decodes_user(self):
+ """Simple auth header 'Basic base64(alice:dummy)' -> principal 'alice'."""
+ # base64("alice:dummy") == "YWxpY2U6ZHVtbXk="
+ self.assertEqual(
+ audit._extract_principal("Basic YWxpY2U6ZHVtbXk="), "alice"
+ )
+
+ def test_basic_auth_invalid_base64_returns_anonymous(self):
+ self.assertEqual(
+ audit._extract_principal("Basic not-valid-base64!!"), "anonymous"
+ )
+
+ def test_unknown_scheme_returns_anonymous(self):
+ self.assertEqual(
+ audit._extract_principal("Negotiate abc123"), "anonymous"
+ )
+
class TestAuditMiddlewareIntegration(unittest.TestCase):
"""Integration tests: AuditMiddleware emits records via the full MCP tool path."""
diff --git a/mcp-server/tests/unit/test_auth_flow.py b/mcp-server/tests/unit/test_auth_flow.py
index ca6b59b671..174e93407f 100644
--- a/mcp-server/tests/unit/test_auth_flow.py
+++ b/mcp-server/tests/unit/test_auth_flow.py
@@ -24,27 +24,39 @@ from mcp_server.core.context import GravitinoContext
from mcp_server.core.setting import Setting
-class TestTokenInjection(unittest.TestCase):
- """Verify Bearer token is correctly injected into the httpx client."""
+class TestAuthorizationInjection(unittest.TestCase):
+ """Verify the Authorization header is forwarded verbatim to the httpx client."""
- def test_token_sets_authorization_header(self):
- """When a token is provided, the httpx client carries Authorization: Bearer."""
+ def test_bearer_authorization_header(self):
+ """A Bearer authorization value is forwarded unchanged."""
client = PlainRESTClientOperation(
- "my_metalake", "http://localhost:8090", token="my-secret-token"
+ "my_metalake",
+ "http://localhost:8090",
+ authorization="Bearer my-secret-token",
)
headers = dict(client._catalog_operation.rest_client.headers)
self.assertEqual(headers.get("authorization"), "Bearer my-secret-token")
- def test_empty_token_no_authorization_header(self):
- """When token is empty, no Authorization header is added."""
+ def test_basic_authorization_header(self):
+ """A Basic authorization value (simple auth) is forwarded unchanged."""
client = PlainRESTClientOperation(
- "my_metalake", "http://localhost:8090", token=""
+ "my_metalake",
+ "http://localhost:8090",
+ authorization="Basic YWxpY2U6ZHVtbXk=",
+ )
+ headers = dict(client._catalog_operation.rest_client.headers)
+ self.assertEqual(headers.get("authorization"), "Basic YWxpY2U6ZHVtbXk=")
+
+ def test_empty_authorization_no_header(self):
+ """When authorization is empty, no Authorization header is added."""
+ client = PlainRESTClientOperation(
+ "my_metalake", "http://localhost:8090", authorization=""
)
headers = dict(client._catalog_operation.rest_client.headers)
self.assertNotIn("authorization", headers)
- def test_no_token_argument_no_authorization_header(self):
- """When token argument is omitted entirely, no Authorization header is added."""
+ def test_no_authorization_argument_no_header(self):
+ """When authorization argument is omitted, no Authorization header is added."""
client = PlainRESTClientOperation(
"my_metalake", "http://localhost:8090"
)
diff --git a/mcp-server/tests/unit/test_per_request_token.py b/mcp-server/tests/unit/test_per_request_token.py
index 77ad709ce6..d5e0f0aef2 100644
--- a/mcp-server/tests/unit/test_per_request_token.py
+++ b/mcp-server/tests/unit/test_per_request_token.py
@@ -15,12 +15,11 @@
# specific language governing permissions and limitations
# under the License.
-"""Tests for per-request token isolation (Task 6).
+"""Tests for per-request identity isolation (Task 6).
-GravitinoContext.rest_client() must return a client carrying the token from
-the current HTTP request, not the shared startup token, when an Authorization
-header is present. This ensures concurrent multi-principal sessions are fully
-isolated in HTTP transport mode.
+GravitinoContext.rest_client() must forward the current HTTP request's raw
+Authorization header (any scheme) to Gravitino, not the shared startup token,
+so concurrent multi-principal sessions stay fully isolated in HTTP mode.
"""
import unittest
@@ -28,47 +27,38 @@ from unittest.mock import MagicMock, patch
from mcp_server.core.context import (
GravitinoContext,
- _extract_bearer_token,
- _get_request_token,
+ _get_request_authorization,
)
from mcp_server.core.setting import Setting
-class TestExtractBearerToken(unittest.TestCase):
- """Unit tests for the token extraction helper."""
+class TestGetRequestAuthorization(unittest.TestCase):
+ """Unit tests for _get_request_authorization() (HTTP context extraction)."""
- def test_well_formed_bearer_header(self):
- self.assertEqual(
- _extract_bearer_token("Bearer mytoken123"), "mytoken123"
- )
-
- def test_case_insensitive_bearer(self):
- self.assertEqual(_extract_bearer_token("bearer MYTOKEN"), "MYTOKEN")
-
- def test_empty_header_returns_empty(self):
- self.assertEqual(_extract_bearer_token(""), "")
-
- def test_non_bearer_scheme_returns_empty(self):
- self.assertEqual(_extract_bearer_token("Basic dXNlcjpwYXNz"), "")
-
- def test_only_scheme_no_token_returns_empty(self):
- self.assertEqual(_extract_bearer_token("Bearer"), "")
+ def test_returns_raw_bearer_header(self):
+ mock_request = MagicMock()
+ mock_request.headers.get.return_value = "Bearer request-token-xyz"
+ with patch(
+ "fastmcp.server.dependencies.get_http_request",
+ return_value=mock_request,
+ ):
+ authorization = _get_request_authorization()
-class TestGetRequestToken(unittest.TestCase):
- """Unit tests for _get_request_token() (HTTP context extraction)."""
+ self.assertEqual(authorization, "Bearer request-token-xyz")
- def test_returns_token_when_http_request_available(self):
+ def test_returns_raw_basic_header_verbatim(self):
+ """Basic (simple auth) headers must pass through unchanged, not be dropped."""
mock_request = MagicMock()
- mock_request.headers.get.return_value = "Bearer request-token-xyz"
+ mock_request.headers.get.return_value = "Basic YWxpY2U6ZHVtbXk="
with patch(
"fastmcp.server.dependencies.get_http_request",
return_value=mock_request,
):
- token = _get_request_token()
+ authorization = _get_request_authorization()
- self.assertEqual(token, "request-token-xyz")
+ self.assertEqual(authorization, "Basic YWxpY2U6ZHVtbXk=")
def test_returns_empty_when_no_http_context(self):
"""Simulates stdio mode where get_http_request raises LookupError."""
@@ -76,9 +66,9 @@ class TestGetRequestToken(unittest.TestCase):
"fastmcp.server.dependencies.get_http_request",
side_effect=LookupError("no request context"),
):
- token = _get_request_token()
+ authorization = _get_request_authorization()
- self.assertEqual(token, "")
+ self.assertEqual(authorization, "")
def test_returns_empty_when_no_authorization_header(self):
mock_request = MagicMock()
@@ -88,13 +78,13 @@ class TestGetRequestToken(unittest.TestCase):
"fastmcp.server.dependencies.get_http_request",
return_value=mock_request,
):
- token = _get_request_token()
+ authorization = _get_request_authorization()
- self.assertEqual(token, "")
+ self.assertEqual(authorization, "")
-class TestGravitinoContextPerRequestToken(unittest.TestCase):
- """GravitinoContext.rest_client() isolates per-request tokens."""
+class TestGravitinoContextPerRequestAuthorization(unittest.TestCase):
+ """GravitinoContext.rest_client() isolates per-request identities."""
def _make_context(self, startup_token: str = "") -> GravitinoContext:
return GravitinoContext(
@@ -105,12 +95,12 @@ class TestGravitinoContextPerRequestToken(unittest.TestCase):
)
)
- def test_per_request_token_overrides_startup_token(self):
- """When an HTTP request carries a token, it takes priority over the startup token."""
+ def test_per_request_header_overrides_startup_token(self):
+ """An HTTP request's Authorization header takes priority over the startup token."""
ctx = self._make_context(startup_token="startup-token")
mock_request = MagicMock()
- mock_request.headers.get.return_value = "Bearer request-token"
+ mock_request.headers.get.return_value = "Basic YWxpY2U6ZHVtbXk="
with patch(
"fastmcp.server.dependencies.get_http_request",
@@ -119,10 +109,10 @@ class TestGravitinoContextPerRequestToken(unittest.TestCase):
client = ctx.rest_client()
headers = dict(client._catalog_operation.rest_client.headers)
- self.assertEqual(headers.get("authorization"), "Bearer request-token")
+ self.assertEqual(headers.get("authorization"), "Basic YWxpY2U6ZHVtbXk=")
- def test_falls_back_to_default_client_when_no_request_token(self):
- """When no per-request token exists, the shared default client (startup token) is used."""
+ def test_falls_back_to_default_client_when_no_request_header(self):
+ """With no per-request header, the shared default client (startup token) is used."""
ctx = self._make_context(startup_token="startup-token")
with patch(
@@ -135,23 +125,23 @@ class TestGravitinoContextPerRequestToken(unittest.TestCase):
self.assertIs(client, ctx._default_client)
def test_two_concurrent_requests_get_different_clients(self):
- """Different request tokens must produce different client instances."""
+ """Different request identities must produce different client instances."""
ctx = self._make_context()
- def make_mock(token: str) -> MagicMock:
+ def make_mock(authorization: str) -> MagicMock:
m = MagicMock()
- m.headers.get.return_value = f"Bearer {token}"
+ m.headers.get.return_value = authorization
return m
with patch(
"fastmcp.server.dependencies.get_http_request",
- return_value=make_mock("alice-token"),
+ return_value=make_mock("Basic YWxpY2U6ZHVtbXk="),
):
client_alice = ctx.rest_client()
with patch(
"fastmcp.server.dependencies.get_http_request",
- return_value=make_mock("bob-token"),
+ return_value=make_mock("Basic Ym9iOmR1bW15"),
):
client_bob = ctx.rest_client()
@@ -160,7 +150,7 @@ class TestGravitinoContextPerRequestToken(unittest.TestCase):
)
bob_headers = dict(client_bob._catalog_operation.rest_client.headers)
self.assertEqual(
- alice_headers.get("authorization"), "Bearer alice-token"
+ alice_headers.get("authorization"), "Basic YWxpY2U6ZHVtbXk="
)
- self.assertEqual(bob_headers.get("authorization"), "Bearer bob-token")
+ self.assertEqual(bob_headers.get("authorization"), "Basic Ym9iOmR1bW15")
self.assertIsNot(client_alice, client_bob)
diff --git a/mcp-server/tests/unit/tools/mock_operation.py b/mcp-server/tests/unit/tools/mock_operation.py
index eb6c1f2cff..1f69e9afa7 100644
--- a/mcp-server/tests/unit/tools/mock_operation.py
+++ b/mcp-server/tests/unit/tools/mock_operation.py
@@ -31,7 +31,7 @@ from mcp_server.client.statistic_operation import StatisticOperation
class MockOperation(GravitinoOperation):
- def __init__(self, metalake, uri, token=""):
+ def __init__(self, metalake, uri, authorization=""):
pass
def as_table_operation(self) -> TableOperation:
(gravitino) 09/09: Add localtest example and docs.
Posted by yu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yuqi1129 pushed a commit to branch feat/mcp-governance-task3-6
in repository https://gitbox.apache.org/repos/asf/gravitino.git
commit 61d3bdf085a12e7e31602dc852b67e601ec3f77b
Author: yuqi <yu...@datastrato.com>
AuthorDate: Thu Jun 11 16:37:39 2026 +0800
Add localtest example and docs.
---
mcp-server/dev/INSPECTOR_DEMO.md | 208 ++++++++++++++++++++++++++
mcp-server/dev/start_inspector_demo.sh | 260 +++++++++++++++++++++++++++++++++
mcp-server/dev/stop_inspector_demo.sh | 77 ++++++++++
3 files changed, 545 insertions(+)
diff --git a/mcp-server/dev/INSPECTOR_DEMO.md b/mcp-server/dev/INSPECTOR_DEMO.md
new file mode 100644
index 0000000000..d3a86f9b46
--- /dev/null
+++ b/mcp-server/dev/INSPECTOR_DEMO.md
@@ -0,0 +1,208 @@
+<!--
+ 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.
+-->
+
+# Hands-on MCP Authorization Demo (with MCP Inspector)
+
+Drive the Gravitino MCP server interactively through the
+[MCP Inspector](https://github.com/modelcontextprotocol/inspector) and watch
+per-user authorization and audit work end to end, as two principals
+(`admin` and `bob`).
+
+This exercises the three governance moments:
+
+1. **Scoped discovery** — `admin` and `bob` run the same call and get different,
+ authorization-scoped results.
+2. **Write denied** — `bob` (read-only) attempts a write and is denied by
+ Gravitino authorization, surfaced as an explicit error through MCP.
+3. **Audit trail** — every call produces an audit record attributed to the
+ correct principal with an allow/deny outcome.
+
+---
+
+## 1. Prerequisites
+
+- A built Gravitino distribution. If you don't have one:
+ ```bash
+ ./gradlew compileDistribution -x test -PskipWeb=true
+ # produces distribution/package/
+ ```
+- `uv` available in the `mcp-server/` directory (the project already uses it).
+- Node.js (the start script launches the Inspector via `npx @modelcontextprotocol/inspector`).
+- If you run behind an HTTP proxy, the scripts already export
+ `NO_PROXY=localhost,127.0.0.1`; make sure your shell doesn't force the proxy
+ for loopback in some other way.
+
+---
+
+## 2. Start the demo environment
+
+From the `mcp-server/` directory:
+
+```bash
+./dev/start_inspector_demo.sh
+```
+
+This script (idempotent — safe to re-run):
+
+1. Enables `simple` auth + authorization in `distribution/package/conf/gravitino.conf`
+ (backing up the original).
+2. Starts Gravitino (or reuses a running one).
+3. Provisions demo data into metalake **`mcp_authz_it`**:
+ - `cat_allowed` and `cat_denied` (two model catalogs)
+ - user **`bob`**
+ - a reader role granting `bob` `USE_CATALOG` on `cat_allowed` **only**
+4. Starts the MCP server in HTTP mode at `http://127.0.0.1:8000/mcp`.
+5. Starts the **MCP Inspector** at `http://localhost:6274/` (with the session-token
+ requirement disabled, so the plain URL works directly).
+
+On success it prints the connection details and the two principals' tokens. You
+should see the provisioning summary confirming the different slices:
+
+```
+[demo] admin sees catalogs: ['cat_allowed', 'cat_denied']
+[demo] bob sees catalogs: ['cat_allowed']
+```
+
+> If a distribution isn't found, set `GRAVITINO_HOME=/path/to/distribution`.
+
+---
+
+## 3. Open the Inspector
+
+The start script already launched it. Just open:
+
+```
+http://localhost:6274/
+```
+
+(No session token needed — the script starts it with `DANGEROUSLY_OMIT_AUTH=true`
+for local convenience.)
+
+### Connect
+
+| Field | Value |
+|----------------|------------------------------------------|
+| Transport Type | `Streamable HTTP` |
+| URL | `http://127.0.0.1:8000/mcp` |
+| Header Name | `Authorization` |
+| Header Value | `Basic YWRtaW46ZHVtbXk=` (this is `admin`) |
+
+The two principal tokens (these are Gravitino simple-auth headers, i.e.
+`Basic base64("<user>:dummy")`):
+
+| Principal | Authorization header value |
+|-----------|--------------------------------|
+| `admin` | `Basic YWRtaW46ZHVtbXk=` |
+| `bob` | `Basic Ym9iOmR1bW15` |
+
+Click **Connect**, then **List Tools** — you should see the full read + write
+tool surface (catalogs, schemas, tables, filesets, topics, models, tags, …).
+
+> **Identity is the header.** The Inspector sends your `Authorization` header on
+> every request; the MCP server forwards it verbatim to Gravitino, which
+> authorizes against that principal. To switch principals, change the header
+> value and reconnect.
+
+---
+
+## 4. The three scenarios
+
+Keep a terminal tailing the audit log while you click:
+
+```bash
+tail -f gravitino-mcp-audit.log
+```
+
+### Scenario 1 — Scoped discovery
+
+1. Connected as **admin**, run tool **`get_list_of_catalogs`**.
+ → Returns **both** `cat_allowed` and `cat_denied`.
+2. Reconnect with the **bob** header (`Basic Ym9iOmR1bW15`), run
+ **`get_list_of_catalogs`** again.
+ → Returns **only** `cat_allowed`.
+
+Same call, different results — sourced entirely from Gravitino's list filtering,
+not from any logic in the MCP server.
+
+### Scenario 2 — Write denied by authorization
+
+Still connected as **bob**, run **`create_tag`** with arguments:
+
+```json
+{ "name": "test_tag", "comment": "x", "properties": {} }
+```
+
+→ You get an explicit error, e.g.
+`User 'bob' is not authorized to perform operation 'createTag' on metadata 'mcp_authz_it'`.
+
+It's a real authorization denial, not a hidden tool or a silent no-op. Reconnect
+as **admin** and run the same `create_tag` — it succeeds (admin owns the metalake).
+
+### Scenario 3 — Audit trail
+
+Look at the audit log you've been tailing. You should see discrete, correctly
+attributed records, for example:
+
+```json
+{"timestamp": "...", "principal": "admin", "tool": "get_list_of_catalogs", "outcome": "allow"}
+{"timestamp": "...", "principal": "bob", "tool": "get_list_of_catalogs", "outcome": "allow"}
+{"timestamp": "...", "principal": "bob", "tool": "create_tag", "outcome": "deny", "error_type": "McpError"}
+```
+
+`admin`'s reads attributed to `admin`, `bob`'s reads to `bob`, and `bob`'s denied
+write to `bob` with a `deny` outcome.
+
+---
+
+## 5. Tear down
+
+```bash
+./dev/stop_inspector_demo.sh
+```
+
+Stops the Inspector, the MCP server, and Gravitino, and restores the original
+`gravitino.conf`.
+
+---
+
+## 6. Troubleshooting
+
+**The audit log looks empty / stuck at 0 bytes.**
+The MCP server opens the audit file once at startup and holds the handle. If you
+`rm` the file while the server is running, the process keeps writing to the now
+unlinked inode and a new empty file appears at the path — so you see nothing.
+Don't delete it mid-run; truncate instead (`: > gravitino-mcp-audit.log`), or
+restart the server. The start script truncates rather than deletes for exactly
+this reason.
+
+**`HTTP 000` / `502` when curling localhost.**
+An HTTP proxy is intercepting loopback traffic. Export
+`NO_PROXY=localhost,127.0.0.1` (the scripts already do) or pass `curl --noproxy '*'`.
+
+**MCP server fails to bind (`can't assign requested address`).**
+`localhost` resolved to a non-loopback address. The scripts bind to the
+`127.0.0.1` literal to avoid this.
+
+**`ModuleNotFoundError: No module named 'mcp_server'`.**
+Launch with `uv run python -m mcp_server ...` (the scripts do); `uv run mcp_server`
+needs an editable install.
+
+**Re-running the start script.**
+It's idempotent: it reuses a running Gravitino/MCP server and drops+recreates the
+demo metalake, so you can re-run it freely.
diff --git a/mcp-server/dev/start_inspector_demo.sh b/mcp-server/dev/start_inspector_demo.sh
new file mode 100755
index 0000000000..65ac519f72
--- /dev/null
+++ b/mcp-server/dev/start_inspector_demo.sh
@@ -0,0 +1,260 @@
+#!/bin/bash
+#
+# 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.
+#
+# Bring up a persistent local demo environment for hands-on MCP authorization
+# testing with the MCP Inspector:
+#
+# 1. Gravitino server with simple auth + authorization enabled.
+# 2. Demo data: metalake + two catalogs, user "bob", a role granting bob
+# access to only one catalog (so admin and bob see different slices).
+# 3. MCP server in HTTP transport mode.
+#
+# Unlike run_authz_integration_test.sh, this script LEAVES everything running so
+# you can drive it from the Inspector. Run stop_inspector_demo.sh to tear down.
+#
+# Usage:
+# ./dev/start_inspector_demo.sh
+# GRAVITINO_HOME=/path/to/distribution ./dev/start_inspector_demo.sh
+
+set -euo pipefail
+
+# Everything is local; never route through an HTTP proxy.
+export NO_PROXY="localhost,127.0.0.1"
+export no_proxy="localhost,127.0.0.1"
+
+MCP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+REPO_ROOT="$(cd "${MCP_DIR}/.." && pwd)"
+
+GRAVITINO_PORT="${GRAVITINO_PORT:-8090}"
+GRAVITINO_URI="http://127.0.0.1:${GRAVITINO_PORT}"
+MCP_PORT="${MCP_PORT:-8000}"
+MCP_URL="http://127.0.0.1:${MCP_PORT}/mcp"
+MCP_METALAKE="${MCP_METALAKE:-mcp_authz_it}"
+MCP_PID_FILE="${MCP_DIR}/.inspector-demo-mcp.pid"
+ADMIN_AUTH="Basic $(printf '%s' 'admin:dummy' | base64)"
+
+# MCP Inspector ports (defaults baked into @modelcontextprotocol/inspector).
+INSPECTOR_UI_PORT="${INSPECTOR_UI_PORT:-6274}"
+INSPECTOR_PROXY_PORT="${INSPECTOR_PROXY_PORT:-6277}"
+INSPECTOR_PID_FILE="${MCP_DIR}/.inspector-demo-inspector.pid"
+
+log() { echo "[demo] $*"; }
+
+# ---------------------------------------------------------------------------
+# 1. Resolve the Gravitino distribution
+# ---------------------------------------------------------------------------
+if [[ -z "${GRAVITINO_HOME:-}" ]]; then
+ GRAVITINO_HOME="${REPO_ROOT}/distribution/package"
+fi
+if [[ ! -x "${GRAVITINO_HOME}/bin/gravitino.sh" ]]; then
+ log "Distribution not found at ${GRAVITINO_HOME}."
+ log "Build it first: ./gradlew compileDistribution -x test -PskipWeb=true"
+ log "Or set GRAVITINO_HOME to an existing distribution."
+ exit 1
+fi
+log "Using GRAVITINO_HOME=${GRAVITINO_HOME}"
+
+# ---------------------------------------------------------------------------
+# 2. Enable simple auth + authorization (idempotent)
+# ---------------------------------------------------------------------------
+CONF="${GRAVITINO_HOME}/conf/gravitino.conf"
+if ! grep -q "gravitino.authorization.enable = true" "${CONF}"; then
+ cp "${CONF}" "${CONF}.inspector-demo.bak"
+ sed -i.tmp \
+ -e '/^gravitino.authenticators/d' \
+ -e '/^gravitino.authorization.enable/d' \
+ -e '/^gravitino.authorization.serviceAdmins/d' \
+ "${CONF}"
+ rm -f "${CONF}.tmp"
+ cat >> "${CONF}" <<EOF
+
+# --- injected by start_inspector_demo.sh (restored on stop) ---
+gravitino.authenticators = simple
+gravitino.authorization.enable = true
+gravitino.authorization.serviceAdmins = admin
+EOF
+ log "Configured simple auth + authorization (serviceAdmins=admin)"
+else
+ log "Authorization already enabled in config"
+fi
+
+# ---------------------------------------------------------------------------
+# 3. Start Gravitino (if not already up)
+# ---------------------------------------------------------------------------
+if curl -sf --noproxy '*' -H "Authorization: ${ADMIN_AUTH}" \
+ "${GRAVITINO_URI}/api/version" >/dev/null 2>&1; then
+ log "Gravitino already running on ${GRAVITINO_PORT}"
+else
+ log "Starting Gravitino server..."
+ "${GRAVITINO_HOME}/bin/gravitino.sh" start
+ log "Waiting for Gravitino to become healthy..."
+ for i in $(seq 1 60); do
+ if curl -sf --noproxy '*' -H "Authorization: ${ADMIN_AUTH}" \
+ "${GRAVITINO_URI}/api/version" >/dev/null 2>&1; then
+ log "Gravitino is up."
+ break
+ fi
+ if [[ "${i}" == "60" ]]; then
+ log "ERROR: Gravitino did not become healthy in time"
+ exit 1
+ fi
+ sleep 2
+ done
+fi
+
+# ---------------------------------------------------------------------------
+# 4. Provision demo data (idempotent: drop + recreate the metalake)
+# ---------------------------------------------------------------------------
+log "Provisioning demo data into metalake '${MCP_METALAKE}'..."
+(
+ cd "${MCP_DIR}"
+ GRAVITINO_URI="${GRAVITINO_URI}" MCP_METALAKE="${MCP_METALAKE}" \
+ uv run python <<'PY'
+import base64
+import os
+
+import httpx
+
+from tests.integration.gravitino_setup import GravitinoFixture
+
+uri = os.environ["GRAVITINO_URI"]
+ml = os.environ["MCP_METALAKE"]
+
+
+def hdr(user):
+ return "Basic " + base64.b64encode(f"{user}:dummy".encode()).decode()
+
+
+# Drop an existing metalake so the script can be re-run cleanly.
+client = httpx.Client(
+ base_url=uri, headers={"Authorization": hdr("admin")}, timeout=30
+)
+if client.get(f"/api/metalakes/{ml}").status_code == 200:
+ client.put(
+ f"/api/metalakes/{ml}",
+ json={"updates": [{"@type": "setProperty", "property": "in-use", "value": "false"}]},
+ )
+ client.delete(f"/api/metalakes/{ml}?force=true")
+ print(f"[demo] removed existing metalake '{ml}'")
+client.close()
+
+GravitinoFixture(uri, ml).provision()
+print(f"[demo] provisioned metalake '{ml}': cat_allowed, cat_denied, user bob, reader role")
+
+# Show the resulting authorization slice.
+for user in ("admin", "bob"):
+ r = httpx.get(
+ f"{uri}/api/metalakes/{ml}/catalogs?details=true",
+ headers={"Authorization": hdr(user)},
+ )
+ names = [c["name"] for c in r.json().get("catalogs", [])]
+ print(f"[demo] {user} sees catalogs: {names}")
+PY
+)
+
+# ---------------------------------------------------------------------------
+# 5. Start the MCP server in HTTP mode (if not already up)
+# ---------------------------------------------------------------------------
+if nc -z 127.0.0.1 "${MCP_PORT}" 2>/dev/null; then
+ log "An MCP server is already listening on ${MCP_PORT}; leaving it as-is."
+else
+ log "Starting MCP server (HTTP) on ${MCP_URL}..."
+ (
+ cd "${MCP_DIR}"
+ # Truncate (not delete) the audit log so the running process keeps its handle.
+ : > gravitino-mcp-audit.log
+ nohup uv run python -m mcp_server \
+ --metalake "${MCP_METALAKE}" \
+ --gravitino-uri "${GRAVITINO_URI}" \
+ --transport http \
+ --mcp-url "${MCP_URL}" > "${MCP_DIR}/.inspector-demo-mcp.out" 2>&1 &
+ echo $! > "${MCP_PID_FILE}"
+ )
+ for i in $(seq 1 30); do
+ nc -z 127.0.0.1 "${MCP_PORT}" 2>/dev/null && break
+ sleep 1
+ done
+ if nc -z 127.0.0.1 "${MCP_PORT}" 2>/dev/null; then
+ log "MCP server is up (pid $(cat "${MCP_PID_FILE}"))."
+ else
+ log "ERROR: MCP server did not start; see ${MCP_DIR}/.inspector-demo-mcp.out"
+ exit 1
+ fi
+fi
+
+# ---------------------------------------------------------------------------
+# 6. Start the MCP Inspector (UI on :6274, proxy on :6277)
+# ---------------------------------------------------------------------------
+# DANGEROUSLY_OMIT_AUTH disables the session-token requirement so the plain
+# http://localhost:6274/ URL works without a token (fine for a local demo).
+# MCP_AUTO_OPEN_ENABLED=false keeps it from popping a browser when backgrounded.
+# The Inspector binds to "localhost" (may be IPv6 ::1), so probe via localhost.
+if nc -z localhost "${INSPECTOR_UI_PORT}" 2>/dev/null; then
+ log "An Inspector is already listening on ${INSPECTOR_UI_PORT}; leaving it as-is."
+else
+ log "Starting MCP Inspector on http://localhost:${INSPECTOR_UI_PORT} ..."
+ (
+ cd "${MCP_DIR}"
+ DANGEROUSLY_OMIT_AUTH=true \
+ MCP_AUTO_OPEN_ENABLED=false \
+ nohup npx @modelcontextprotocol/inspector \
+ > "${MCP_DIR}/.inspector-demo-inspector.out" 2>&1 &
+ echo $! > "${INSPECTOR_PID_FILE}"
+ )
+ for i in $(seq 1 60); do
+ nc -z localhost "${INSPECTOR_UI_PORT}" 2>/dev/null && break
+ sleep 1
+ done
+ if nc -z localhost "${INSPECTOR_UI_PORT}" 2>/dev/null; then
+ log "Inspector is up (pid $(cat "${INSPECTOR_PID_FILE}"))."
+ else
+ log "WARN: Inspector did not come up; see ${MCP_DIR}/.inspector-demo-inspector.out"
+ log " (You can still start it manually: npx @modelcontextprotocol/inspector)"
+ fi
+fi
+
+# ---------------------------------------------------------------------------
+# 7. Print connection details
+# ---------------------------------------------------------------------------
+cat <<EOF
+
+============================================================
+ Demo environment is ready.
+============================================================
+ Gravitino : ${GRAVITINO_URI} (simple auth + authorization)
+ MCP server: ${MCP_URL} (Streamable HTTP)
+ Metalake : ${MCP_METALAKE}
+ Audit log : ${MCP_DIR}/gravitino-mcp-audit.log
+
+ >>> Open the Inspector: http://localhost:${INSPECTOR_UI_PORT}/
+
+ In the Inspector, connect with:
+ Transport Type : Streamable HTTP
+ URL : ${MCP_URL}
+ Header Name : Authorization
+ Header Value : ${ADMIN_AUTH} <- admin
+ Basic $(printf '%s' 'bob:dummy' | base64) <- bob
+
+ Watch audit records live:
+ tail -f ${MCP_DIR}/gravitino-mcp-audit.log
+
+ Tear everything down (includes the Inspector):
+ ./dev/stop_inspector_demo.sh
+============================================================
+EOF
diff --git a/mcp-server/dev/stop_inspector_demo.sh b/mcp-server/dev/stop_inspector_demo.sh
new file mode 100755
index 0000000000..0335dac0f2
--- /dev/null
+++ b/mcp-server/dev/stop_inspector_demo.sh
@@ -0,0 +1,77 @@
+#!/bin/bash
+#
+# 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.
+#
+# Tear down the demo environment started by start_inspector_demo.sh:
+# stops the MCP server, stops Gravitino, and restores the original config.
+
+set -uo pipefail
+
+MCP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+REPO_ROOT="$(cd "${MCP_DIR}/.." && pwd)"
+
+MCP_PORT="${MCP_PORT:-8000}"
+MCP_PID_FILE="${MCP_DIR}/.inspector-demo-mcp.pid"
+INSPECTOR_UI_PORT="${INSPECTOR_UI_PORT:-6274}"
+INSPECTOR_PROXY_PORT="${INSPECTOR_PROXY_PORT:-6277}"
+INSPECTOR_PID_FILE="${MCP_DIR}/.inspector-demo-inspector.pid"
+
+log() { echo "[demo] $*"; }
+
+if [[ -z "${GRAVITINO_HOME:-}" ]]; then
+ GRAVITINO_HOME="${REPO_ROOT}/distribution/package"
+fi
+
+# 1. Stop the MCP Inspector (npx spawns child processes; free its ports too).
+if [[ -f "${INSPECTOR_PID_FILE}" ]]; then
+ INSPECTOR_PID="$(cat "${INSPECTOR_PID_FILE}")"
+ kill "${INSPECTOR_PID}" 2>/dev/null && \
+ log "Stopped Inspector (pid ${INSPECTOR_PID})" || true
+ rm -f "${INSPECTOR_PID_FILE}"
+fi
+for port in "${INSPECTOR_UI_PORT}" "${INSPECTOR_PROXY_PORT}"; do
+ lsof -ti :"${port}" 2>/dev/null | xargs kill -9 2>/dev/null && \
+ log "Freed Inspector port ${port}" || true
+done
+
+# 2. Stop the MCP server.
+if [[ -f "${MCP_PID_FILE}" ]]; then
+ MCP_PID="$(cat "${MCP_PID_FILE}")"
+ if kill "${MCP_PID}" 2>/dev/null; then
+ log "Stopped MCP server (pid ${MCP_PID})"
+ fi
+ rm -f "${MCP_PID_FILE}"
+fi
+# Belt and suspenders: free the port if anything is still bound.
+lsof -ti :"${MCP_PORT}" 2>/dev/null | xargs kill -9 2>/dev/null && \
+ log "Freed port ${MCP_PORT}" || true
+
+# 3. Stop Gravitino.
+if [[ -x "${GRAVITINO_HOME}/bin/gravitino.sh" ]]; then
+ "${GRAVITINO_HOME}/bin/gravitino.sh" stop || true
+ log "Stopped Gravitino"
+fi
+
+# 4. Restore the original config.
+CONF="${GRAVITINO_HOME}/conf/gravitino.conf"
+if [[ -f "${CONF}.inspector-demo.bak" ]]; then
+ mv "${CONF}.inspector-demo.bak" "${CONF}"
+ log "Restored original gravitino.conf"
+fi
+
+log "Teardown complete."
(gravitino) 07/09: [#11575] test(mcp-server): live-Gravitino authorization integration test + CI
Posted by yu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yuqi1129 pushed a commit to branch feat/mcp-governance-task3-6
in repository https://gitbox.apache.org/repos/asf/gravitino.git
commit f6c011f08970d7a9ea1c23cde3dad7a5534d7d04
Author: yuqi <yu...@datastrato.com>
AuthorDate: Wed Jun 10 23:52:26 2026 +0800
[#11575] test(mcp-server): live-Gravitino authorization integration test + CI
End-to-end test proving per-user authorization flows through the MCP HTTP
server against a real Gravitino with authorization enabled. Verifies the three
demo acceptance moments:
1. admin and bob run the same list-catalogs call and get different,
authorization-scoped results (admin sees both catalogs, bob sees only the
one granted to it).
2. bob (no write grant) is denied by Gravitino when creating a tag through MCP
(ForbiddenException propagated as a tool error).
3. the reads and the denied write appear as audit records attributed to the
correct principal (admin/bob) with allow/deny outcomes.
- tests/integration/gravitino_setup.py: provisions metalake, two model catalogs,
user bob, a reader role (USE_CATALOG on one catalog), and the grant — all via
REST as the simple-auth service admin.
- tests/integration/conftest.py: session fixtures; skips the suite unless
GRAVITINO_URI / MCP_URL / MCP_METALAKE are exported.
- tests/integration/test_authz_e2e.py: the three demo-moment assertions, driving
the MCP server over real Streamable HTTP transport with per-principal Basic
auth headers.
- dev/run_authz_integration_test.sh: orchestration — configures simple auth +
authorization, starts Gravitino via gravitino.sh, starts the MCP server in
HTTP mode, runs pytest, and tears everything down (restoring the config).
- .github/workflows/mcp-integration-test.yml: CI job that builds the
distribution and runs the orchestration script.
Verified locally: 3 passed; audit log shows admin=allow and bob=deny.
---
.github/workflows/mcp-integration-test.yml | 82 +++++++++++
mcp-server/dev/run_authz_integration_test.sh | 179 ++++++++++++++++++++++++
mcp-server/tests/integration/__init__.py | 0
mcp-server/tests/integration/conftest.py | 69 +++++++++
mcp-server/tests/integration/gravitino_setup.py | 140 ++++++++++++++++++
mcp-server/tests/integration/test_authz_e2e.py | 160 +++++++++++++++++++++
6 files changed, 630 insertions(+)
diff --git a/.github/workflows/mcp-integration-test.yml b/.github/workflows/mcp-integration-test.yml
new file mode 100644
index 0000000000..959d439e82
--- /dev/null
+++ b/.github/workflows/mcp-integration-test.yml
@@ -0,0 +1,82 @@
+#
+# 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.
+#
+name: mcp-integration-test
+
+on:
+ push:
+ branches: [ "main", "branch-*" ]
+ pull_request:
+ branches: [ "main", "branch-*" ]
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ changes:
+ runs-on: ubuntu-latest
+ outputs:
+ mcp_or_authz_changes: ${{ steps.filter.outputs.mcp_or_authz_changes }}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36
+ id: filter
+ with:
+ filters: |
+ mcp_or_authz_changes:
+ - 'mcp-server/**'
+ - 'server/**'
+ - 'core/src/main/java/org/apache/gravitino/authorization/**'
+ - 'server-common/src/main/java/org/apache/gravitino/server/authentication/**'
+ - '.github/workflows/mcp-integration-test.yml'
+
+ mcp-authz-integration-test:
+ runs-on: ubuntu-latest
+ timeout-minutes: 60
+ needs: changes
+ if: needs.changes.outputs.mcp_or_authz_changes == 'true'
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: ./.github/actions/setup-java-toolchains
+ with:
+ java-version: 17
+
+ - name: Install uv
+ uses: astral-sh/setup-uv@v5
+
+ - name: Build Gravitino distribution
+ run: ./gradlew compileDistribution -x test -PskipWeb=true
+
+ - name: Run MCP authorization integration test
+ env:
+ GRAVITINO_HOME: ${{ github.workspace }}/distribution/package
+ run: |
+ ./mcp-server/dev/run_authz_integration_test.sh
+
+ - name: Upload server logs on failure
+ if: failure()
+ uses: actions/upload-artifact@v4
+ with:
+ name: mcp-authz-it-logs
+ path: |
+ distribution/package/logs/**
+ mcp-server/gravitino-mcp-audit.log
+ mcp-server/gravitino-mcp.log
+ if-no-files-found: ignore
diff --git a/mcp-server/dev/run_authz_integration_test.sh b/mcp-server/dev/run_authz_integration_test.sh
new file mode 100755
index 0000000000..82673806b7
--- /dev/null
+++ b/mcp-server/dev/run_authz_integration_test.sh
@@ -0,0 +1,179 @@
+#!/bin/bash
+#
+# 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.
+#
+# End-to-end authorization integration test for the Gravitino MCP server.
+#
+# This script:
+# 1. Builds the Gravitino distribution (unless GRAVITINO_HOME is provided).
+# 2. Enables simple authentication + authorization (serviceAdmins=admin).
+# 3. Starts the Gravitino server.
+# 4. Starts the MCP server in HTTP transport mode.
+# 5. Runs the pytest integration suite (which provisions metadata as admin and
+# verifies per-user authorization through MCP).
+# 6. Tears everything down and restores the original config.
+#
+# Usage:
+# ./dev/run_authz_integration_test.sh
+# GRAVITINO_HOME=/path/to/distribution ./dev/run_authz_integration_test.sh
+
+set -euo pipefail
+
+# All services run on localhost; never route them through an HTTP proxy.
+# httpx (MCP server -> Gravitino, test client) and curl both honour NO_PROXY.
+export NO_PROXY="localhost,127.0.0.1"
+export no_proxy="localhost,127.0.0.1"
+
+MCP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+REPO_ROOT="$(cd "${MCP_DIR}/.." && pwd)"
+
+# Use the loopback literal (not "localhost") so the MCP server binds to a
+# guaranteed-assignable address; on some hosts "localhost" resolves to a LAN IP.
+GRAVITINO_PORT="${GRAVITINO_PORT:-8090}"
+GRAVITINO_URI="http://127.0.0.1:${GRAVITINO_PORT}"
+MCP_PORT="${MCP_PORT:-8000}"
+MCP_URL="http://127.0.0.1:${MCP_PORT}/mcp"
+MCP_METALAKE="${MCP_METALAKE:-mcp_authz_it}"
+MCP_AUDIT_LOG="${MCP_DIR}/gravitino-mcp-audit.log"
+
+MCP_PID=""
+GRAVITINO_STARTED="false"
+CONF_BACKUP=""
+
+log() { echo "[authz-it] $*"; }
+
+cleanup() {
+ log "Tearing down..."
+ if [[ -n "${MCP_PID}" ]] && kill -0 "${MCP_PID}" 2>/dev/null; then
+ kill "${MCP_PID}" 2>/dev/null || true
+ wait "${MCP_PID}" 2>/dev/null || true
+ fi
+ if [[ "${GRAVITINO_STARTED}" == "true" ]]; then
+ "${GRAVITINO_HOME}/bin/gravitino.sh" stop || true
+ fi
+ if [[ -n "${CONF_BACKUP}" && -f "${CONF_BACKUP}" ]]; then
+ mv "${CONF_BACKUP}" "${GRAVITINO_HOME}/conf/gravitino.conf"
+ log "Restored original gravitino.conf"
+ fi
+}
+trap cleanup EXIT
+
+# ---------------------------------------------------------------------------
+# 1. Resolve / build the Gravitino distribution
+# ---------------------------------------------------------------------------
+if [[ -z "${GRAVITINO_HOME:-}" ]]; then
+ log "GRAVITINO_HOME not set; building distribution..."
+ (cd "${REPO_ROOT}" && ./gradlew compileDistribution -x test)
+ GRAVITINO_HOME="${REPO_ROOT}/distribution/package"
+fi
+log "Using GRAVITINO_HOME=${GRAVITINO_HOME}"
+
+if [[ ! -x "${GRAVITINO_HOME}/bin/gravitino.sh" ]]; then
+ log "ERROR: ${GRAVITINO_HOME}/bin/gravitino.sh not found"
+ exit 1
+fi
+
+# ---------------------------------------------------------------------------
+# 2. Enable simple auth + authorization
+# ---------------------------------------------------------------------------
+CONF="${GRAVITINO_HOME}/conf/gravitino.conf"
+CONF_BACKUP="${CONF}.authz-it.bak"
+cp "${CONF}" "${CONF_BACKUP}"
+
+# Remove any pre-existing values for the keys we manage, then append ours.
+sed -i.tmp \
+ -e '/^gravitino.authenticators/d' \
+ -e '/^gravitino.authorization.enable/d' \
+ -e '/^gravitino.authorization.serviceAdmins/d' \
+ "${CONF}"
+rm -f "${CONF}.tmp"
+cat >> "${CONF}" <<EOF
+
+# --- injected by run_authz_integration_test.sh ---
+gravitino.authenticators = simple
+gravitino.authorization.enable = true
+gravitino.authorization.serviceAdmins = admin
+EOF
+log "Configured simple auth + authorization (serviceAdmins=admin)"
+
+# ---------------------------------------------------------------------------
+# 3. Start Gravitino
+# ---------------------------------------------------------------------------
+log "Starting Gravitino server..."
+"${GRAVITINO_HOME}/bin/gravitino.sh" start
+GRAVITINO_STARTED="true"
+
+# With simple auth enabled every request needs an Authorization header.
+ADMIN_AUTH="Basic $(printf '%s' 'admin:dummy' | base64)"
+
+log "Waiting for Gravitino to become healthy..."
+for i in $(seq 1 60); do
+ if curl -sf --noproxy '*' -H "Authorization: ${ADMIN_AUTH}" \
+ "${GRAVITINO_URI}/api/version" >/dev/null 2>&1; then
+ log "Gravitino is up."
+ break
+ fi
+ if [[ "${i}" == "60" ]]; then
+ log "ERROR: Gravitino did not become healthy in time"
+ exit 1
+ fi
+ sleep 2
+done
+
+# ---------------------------------------------------------------------------
+# 4. Start the MCP server in HTTP transport mode
+# ---------------------------------------------------------------------------
+log "Starting MCP server (HTTP) on ${MCP_URL}..."
+rm -f "${MCP_AUDIT_LOG}"
+(
+ cd "${MCP_DIR}"
+ uv run python -m mcp_server \
+ --metalake "${MCP_METALAKE}" \
+ --gravitino-uri "${GRAVITINO_URI}" \
+ --transport http \
+ --mcp-url "${MCP_URL}"
+) &
+MCP_PID=$!
+
+log "Waiting for MCP server to become reachable..."
+for i in $(seq 1 30); do
+ if nc -z localhost "${MCP_PORT}" 2>/dev/null; then
+ log "MCP server is up."
+ break
+ fi
+ if [[ "${i}" == "30" ]]; then
+ log "ERROR: MCP server did not start in time"
+ exit 1
+ fi
+ sleep 1
+done
+
+# ---------------------------------------------------------------------------
+# 5. Run the pytest integration suite
+# ---------------------------------------------------------------------------
+log "Running integration tests..."
+(
+ cd "${MCP_DIR}"
+ GRAVITINO_URI="${GRAVITINO_URI}" \
+ MCP_URL="${MCP_URL}" \
+ MCP_METALAKE="${MCP_METALAKE}" \
+ MCP_AUDIT_LOG="${MCP_AUDIT_LOG}" \
+ uv run pytest tests/integration -v
+)
+
+log "Integration tests passed."
diff --git a/mcp-server/tests/integration/__init__.py b/mcp-server/tests/integration/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/mcp-server/tests/integration/conftest.py b/mcp-server/tests/integration/conftest.py
new file mode 100644
index 0000000000..313fff509e
--- /dev/null
+++ b/mcp-server/tests/integration/conftest.py
@@ -0,0 +1,69 @@
+# 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.
+
+"""pytest fixtures for the MCP authorization integration test.
+
+The orchestration script (``dev/run_authz_integration_test.sh``) starts a real
+Gravitino server and the MCP server in HTTP mode, then exports the connection
+details below. When these env vars are absent the whole integration suite is
+skipped so a plain ``pytest`` run stays green without external services.
+
+Required environment variables:
+ GRAVITINO_URI e.g. http://localhost:8090
+ MCP_URL e.g. http://localhost:8000/mcp
+ MCP_METALAKE metalake name the MCP server was launched against
+"""
+
+import os
+
+import pytest
+
+from tests.integration.gravitino_setup import GravitinoFixture
+
+_REQUIRED_ENV = ("GRAVITINO_URI", "MCP_URL", "MCP_METALAKE")
+
+
+def _missing_env() -> list:
+ return [name for name in _REQUIRED_ENV if not os.environ.get(name)]
+
+
+@pytest.fixture(scope="session")
+def integration_env() -> dict:
+ missing = _missing_env()
+ if missing:
+ pytest.skip(
+ "Integration test requires a running Gravitino + MCP server. "
+ f"Missing env: {', '.join(missing)}. "
+ "Run via dev/run_authz_integration_test.sh."
+ )
+ return {
+ "gravitino_uri": os.environ["GRAVITINO_URI"],
+ "mcp_url": os.environ["MCP_URL"],
+ "metalake": os.environ["MCP_METALAKE"],
+ }
+
+
+@pytest.fixture(scope="session")
+def gravitino_fixture(integration_env: dict) -> GravitinoFixture:
+ """Provision metalake/catalogs/user/role/grant once for the whole suite."""
+ fixture = GravitinoFixture(
+ gravitino_uri=integration_env["gravitino_uri"],
+ metalake=integration_env["metalake"],
+ )
+ fixture.provision()
+ yield fixture
+ fixture.close()
diff --git a/mcp-server/tests/integration/gravitino_setup.py b/mcp-server/tests/integration/gravitino_setup.py
new file mode 100644
index 0000000000..688dacfae2
--- /dev/null
+++ b/mcp-server/tests/integration/gravitino_setup.py
@@ -0,0 +1,140 @@
+# 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.
+
+"""Provision Gravitino metadata and authorization fixtures for the integration test.
+
+All requests are issued as the service admin using Gravitino simple
+authentication (``Authorization: Basic base64(user:dummy)``). The fixture
+creates a metalake with two model catalogs, a non-admin user ``bob``, and a role
+that grants ``bob`` access to only one of the two catalogs. This produces a
+visibly different authorization slice between the admin and ``bob`` principals.
+"""
+
+import base64
+
+import httpx
+
+
+def basic_auth_header(user: str) -> str:
+ """Build a Gravitino simple-auth header value for ``user``."""
+ credential = base64.b64encode(f"{user}:dummy".encode("utf-8")).decode(
+ "ascii"
+ )
+ return f"Basic {credential}"
+
+
+class GravitinoFixture:
+ """Sets up metalake/catalogs/user/role/grant via the Gravitino REST API."""
+
+ def __init__(
+ self,
+ gravitino_uri: str,
+ metalake: str,
+ admin_user: str = "admin",
+ granted_user: str = "bob",
+ catalog_allowed: str = "cat_allowed",
+ catalog_denied: str = "cat_denied",
+ role_name: str = "reader_role",
+ ):
+ self.gravitino_uri = gravitino_uri.rstrip("/")
+ self.metalake = metalake
+ self.admin_user = admin_user
+ self.granted_user = granted_user
+ self.catalog_allowed = catalog_allowed
+ self.catalog_denied = catalog_denied
+ self.role_name = role_name
+ self._client = httpx.Client(
+ base_url=self.gravitino_uri,
+ headers={"Authorization": basic_auth_header(admin_user)},
+ timeout=30.0,
+ )
+
+ def _post(self, path: str, body: dict) -> httpx.Response:
+ response = self._client.post(path, json=body)
+ response.raise_for_status()
+ return response
+
+ def _put(self, path: str, body: dict) -> httpx.Response:
+ response = self._client.put(path, json=body)
+ response.raise_for_status()
+ return response
+
+ def provision(self) -> None:
+ """Create all metadata and authorization fixtures (idempotent-ish)."""
+ self._create_metalake()
+ self._create_model_catalog(self.catalog_allowed)
+ self._create_model_catalog(self.catalog_denied)
+ self._add_user(self.granted_user)
+ self._create_reader_role()
+ self._grant_role_to_user()
+
+ def _create_metalake(self) -> None:
+ self._post(
+ "/api/metalakes",
+ {
+ "name": self.metalake,
+ "comment": "MCP authz integration test metalake",
+ "properties": {},
+ },
+ )
+
+ def _create_model_catalog(self, name: str) -> None:
+ self._post(
+ f"/api/metalakes/{self.metalake}/catalogs",
+ {
+ "name": name,
+ "type": "MODEL",
+ "provider": "model",
+ "comment": "model catalog for authz test",
+ "properties": {},
+ },
+ )
+
+ def _add_user(self, user: str) -> None:
+ self._post(
+ f"/api/metalakes/{self.metalake}/users",
+ {"name": user},
+ )
+
+ def _create_reader_role(self) -> None:
+ # Grant bob USE_CATALOG on the allowed catalog only.
+ self._post(
+ f"/api/metalakes/{self.metalake}/roles",
+ {
+ "name": self.role_name,
+ "properties": {},
+ "securableObjects": [
+ {
+ "fullName": self.catalog_allowed,
+ "type": "CATALOG",
+ "privileges": [
+ {"name": "USE_CATALOG", "condition": "ALLOW"}
+ ],
+ }
+ ],
+ },
+ )
+
+ def _grant_role_to_user(self) -> None:
+ self._put(
+ f"/api/metalakes/{self.metalake}/permissions"
+ f"/users/{self.granted_user}/grant/",
+ {"roleNames": [self.role_name]},
+ )
+
+ def close(self) -> None:
+ self._client.close()
diff --git a/mcp-server/tests/integration/test_authz_e2e.py b/mcp-server/tests/integration/test_authz_e2e.py
new file mode 100644
index 0000000000..7c4933e62d
--- /dev/null
+++ b/mcp-server/tests/integration/test_authz_e2e.py
@@ -0,0 +1,160 @@
+# 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.
+
+"""End-to-end authorization integration test through the live MCP HTTP server.
+
+Validates the three demo acceptance moments against a real Gravitino with
+authorization enabled:
+
+ 1. Two principals run the same discovery call and get correctly different,
+ authorization-scoped results.
+ 2. A read-only principal attempts a write through MCP and is denied by
+ Gravitino authorization.
+ 3. Both the reads and the denied write appear as audit records attributed to
+ the correct principal.
+
+These tests only run when GRAVITINO_URI / MCP_URL / MCP_METALAKE are set (see
+conftest.py); otherwise the suite is skipped.
+"""
+
+import asyncio
+import json
+import os
+import time
+
+import pytest
+from fastmcp import Client
+from fastmcp.client.transports import StreamableHttpTransport
+
+from tests.integration.gravitino_setup import basic_auth_header
+
+ADMIN = "admin"
+BOB = "bob"
+CATALOG_ALLOWED = "cat_allowed"
+CATALOG_DENIED = "cat_denied"
+
+
+def _client_for(principal: str, mcp_url: str) -> Client:
+ """Build an MCP client that authenticates as ``principal`` (simple auth)."""
+ transport = StreamableHttpTransport(
+ url=mcp_url,
+ headers={"Authorization": basic_auth_header(principal)},
+ )
+ return Client(transport)
+
+
+async def _list_catalog_names(principal: str, mcp_url: str) -> set:
+ async with _client_for(principal, mcp_url) as client:
+ result = await client.call_tool("get_list_of_catalogs")
+ payload = json.loads(result.content[0].text)
+ return {entry["name"] for entry in payload}
+
+
+def test_moment1_authorization_scoped_discovery(
+ gravitino_fixture, integration_env
+):
+ """Moment 1: admin and bob get different, correctly scoped catalog lists."""
+ mcp_url = integration_env["mcp_url"]
+
+ admin_catalogs = asyncio.run(_list_catalog_names(ADMIN, mcp_url))
+ bob_catalogs = asyncio.run(_list_catalog_names(BOB, mcp_url))
+
+ # Admin owns the metalake and sees both catalogs.
+ assert CATALOG_ALLOWED in admin_catalogs
+ assert CATALOG_DENIED in admin_catalogs
+
+ # Bob was granted USE_CATALOG on the allowed catalog only.
+ assert CATALOG_ALLOWED in bob_catalogs
+ assert CATALOG_DENIED not in bob_catalogs
+
+ # The two principals must receive different results.
+ assert admin_catalogs != bob_catalogs
+
+
+def test_moment2_write_denied_for_readonly_principal(
+ gravitino_fixture, integration_env
+):
+ """Moment 2: bob (no write grant) is denied when creating a tag through MCP."""
+ mcp_url = integration_env["mcp_url"]
+
+ async def _attempt_write():
+ async with _client_for(BOB, mcp_url) as client:
+ await client.call_tool(
+ "create_tag",
+ {
+ "name": "denied_tag",
+ "comment": "should be denied",
+ "properties": {},
+ },
+ )
+
+ with pytest.raises(Exception): # noqa: B017 – any tool error means denial
+ asyncio.run(_attempt_write())
+
+
+def test_moment3_audit_trail_attribution(gravitino_fixture, integration_env):
+ """Moment 3: audit log records reads/writes attributed to the right principal."""
+ audit_log = os.environ.get("MCP_AUDIT_LOG")
+ if not audit_log or not os.path.exists(audit_log):
+ pytest.skip("MCP_AUDIT_LOG not set or file missing")
+
+ mcp_url = integration_env["mcp_url"]
+
+ async def _attempt_write():
+ async with _client_for(BOB, mcp_url) as client:
+ await client.call_tool(
+ "create_tag",
+ {"name": "audit_tag", "comment": "", "properties": {}},
+ )
+
+ # Generate one allowed read (admin) and one denied write (bob).
+ asyncio.run(_list_catalog_names(ADMIN, mcp_url))
+ try:
+ asyncio.run(_attempt_write())
+ except Exception: # noqa: BLE001 – expected denial
+ pass
+
+ # Give the server a moment to flush the audit handler.
+ time.sleep(1.0)
+
+ records = []
+ with open(audit_log, "r", encoding="utf-8") as fh:
+ for line in fh:
+ line = line.strip()
+ if line:
+ try:
+ records.append(json.loads(line))
+ except json.JSONDecodeError:
+ continue
+
+ admin_allows = [
+ r
+ for r in records
+ if r.get("principal") == ADMIN
+ and r.get("tool") == "get_list_of_catalogs"
+ and r.get("outcome") == "allow"
+ ]
+ bob_denies = [
+ r
+ for r in records
+ if r.get("principal") == BOB
+ and r.get("tool") == "create_tag"
+ and r.get("outcome") == "deny"
+ ]
+
+ assert admin_allows, "expected an allow record attributed to admin"
+ assert bob_denies, "expected a deny record attributed to bob"
(gravitino) 03/09: [#11568] feat(mcp-server): structured per-tool-call audit logging attributed to principal
Posted by yu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yuqi1129 pushed a commit to branch feat/mcp-governance-task3-6
in repository https://gitbox.apache.org/repos/asf/gravitino.git
commit e135d011d20ab2717e6ddf9f0d40f49a0c518409
Author: yuqi <yu...@datastrato.com>
AuthorDate: Wed Jun 10 20:30:52 2026 +0800
[#11568] feat(mcp-server): structured per-tool-call audit logging attributed to principal
- core/audit.py: AuditLogger with emit() writing JSON records to gravitino.mcp.audit logger.
Fields: timestamp, principal (bearer:<8-char-prefix> or anonymous), tool, outcome, error_type.
- server.py: AuditMiddleware overrides on_call_tool; extracts principal from HTTP
Authorization header via get_http_request() (falls back to anonymous in stdio mode);
emits allow on success and deny on exception.
- main.py: configure gravitino-mcp-audit.log file handler for the audit logger.
- tests/unit/test_audit.py: 9 tests covering emit structure, principal extraction,
middleware allow/deny integration.
---
mcp-server/mcp_server/core/audit.py | 64 ++++++++++++
mcp-server/mcp_server/main.py | 6 ++
mcp-server/mcp_server/server.py | 50 +++++++++-
mcp-server/tests/unit/test_audit.py | 189 ++++++++++++++++++++++++++++++++++++
4 files changed, 308 insertions(+), 1 deletion(-)
diff --git a/mcp-server/mcp_server/core/audit.py b/mcp-server/mcp_server/core/audit.py
new file mode 100644
index 0000000000..f65b71cdff
--- /dev/null
+++ b/mcp-server/mcp_server/core/audit.py
@@ -0,0 +1,64 @@
+# 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.
+
+import json
+import logging
+from datetime import datetime, timezone
+
+_audit_logger = logging.getLogger("gravitino.mcp.audit")
+
+
+def _extract_principal(authorization: str) -> str:
+ """Derive a display principal from a raw Authorization header value.
+
+ - "Bearer <token>" → "bearer:<first-8-chars-of-token>"
+ - empty / missing → "anonymous"
+ """
+ if not authorization:
+ return "anonymous"
+ parts = authorization.split()
+ if len(parts) == 2 and parts[0].lower() == "bearer":
+ token = parts[1]
+ return f"bearer:{token[:8]}"
+ return "anonymous"
+
+
+def emit(
+ *,
+ principal: str,
+ tool: str,
+ outcome: str,
+ error_type: str = "",
+) -> None:
+ """Write one structured JSON audit record to the audit logger.
+
+ Args:
+ principal: Identity derived from the request (e.g. "bearer:abc12345" or "anonymous").
+ tool: MCP tool name that was invoked.
+ outcome: "allow" for successful calls, "deny" for authorization failures.
+ error_type: Exception class name when outcome is "deny", empty otherwise.
+ """
+ record = {
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ "principal": principal,
+ "tool": tool,
+ "outcome": outcome,
+ }
+ if error_type:
+ record["error_type"] = error_type
+
+ _audit_logger.info(json.dumps(record))
diff --git a/mcp-server/mcp_server/main.py b/mcp-server/mcp_server/main.py
index b1200b3180..ca60d8930f 100644
--- a/mcp-server/mcp_server/main.py
+++ b/mcp-server/mcp_server/main.py
@@ -46,6 +46,12 @@ def _init_logging(setting: Setting):
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
+ # Separate file handler for structured audit records (one JSON line per entry).
+ audit_handler = logging.FileHandler("gravitino-mcp-audit.log")
+ audit_handler.setLevel(logging.INFO)
+ audit_handler.setFormatter(logging.Formatter("%(message)s"))
+ logging.getLogger("gravitino.mcp.audit").addHandler(audit_handler)
+ logging.getLogger("gravitino.mcp.audit").propagate = False
def _comma_separated_set(value) -> set:
diff --git a/mcp-server/mcp_server/server.py b/mcp-server/mcp_server/server.py
index 9cce5f556b..8d66fec936 100644
--- a/mcp-server/mcp_server/server.py
+++ b/mcp-server/mcp_server/server.py
@@ -16,23 +16,71 @@
# under the License.
import asyncio
+import contextlib
import logging
from contextlib import asynccontextmanager
from typing import AsyncIterator
from urllib.parse import urlparse
+import mcp.types as mt
from fastmcp import FastMCP
from fastmcp.server.middleware.error_handling import ErrorHandlingMiddleware
from fastmcp.server.middleware.logging import (
LoggingMiddleware,
)
+from fastmcp.server.middleware.middleware import (
+ CallNext,
+ Middleware,
+ MiddlewareContext,
+)
from fastmcp.server.middleware.timing import TimingMiddleware
+from fastmcp.tools.base import ToolResult
+from mcp_server.core import audit
from mcp_server.core.context import GravitinoContext
from mcp_server.core.setting import Setting
from mcp_server.tools import load_tools
+def _get_principal_from_request() -> str:
+ """Extract the principal from the current HTTP request's Authorization header.
+
+ Returns "anonymous" in stdio mode (no HTTP request) or when no token is present.
+ """
+ try:
+ from fastmcp.server.dependencies import get_http_request
+
+ request = get_http_request()
+ authorization = request.headers.get("authorization", "")
+ return audit._extract_principal(authorization)
+ except Exception: # noqa: BLE001 – stdio mode or no request context
+ return "anonymous"
+
+
+class AuditMiddleware(Middleware):
+ """Emit a structured audit record for every tool invocation."""
+
+ async def on_call_tool(
+ self,
+ context: MiddlewareContext[mt.CallToolRequestParams],
+ call_next: CallNext[mt.CallToolRequestParams, ToolResult],
+ ) -> ToolResult:
+ tool_name = context.message.name if context.message else "unknown"
+ principal = _get_principal_from_request()
+ try:
+ result = await call_next(context)
+ audit.emit(principal=principal, tool=tool_name, outcome="allow")
+ return result
+ except Exception as exc:
+ audit.emit(
+ principal=principal,
+ tool=tool_name,
+ outcome="deny",
+ error_type=type(exc).__name__,
+ )
+ raise
+
+
def _create_lifespan_manager(gravitino_context: GravitinoContext):
@asynccontextmanager
@@ -56,10 +104,10 @@ def _create_gravitino_mcp(setting: Setting) -> FastMCP:
lifespan=_create_lifespan_manager(GravitinoContext(setting)),
)
+ mcp.add_middleware(AuditMiddleware())
mcp.add_middleware(
LoggingMiddleware(include_payloads=True, max_payload_length=1000)
)
-
mcp.add_middleware(TimingMiddleware())
mcp.add_middleware(
ErrorHandlingMiddleware(
diff --git a/mcp-server/tests/unit/test_audit.py b/mcp-server/tests/unit/test_audit.py
new file mode 100644
index 0000000000..37cdef29cb
--- /dev/null
+++ b/mcp-server/tests/unit/test_audit.py
@@ -0,0 +1,189 @@
+# 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.
+
+import asyncio
+import json
+import logging
+import unittest
+from unittest.mock import patch
+
+from fastmcp import Client
+
+from mcp_server.client.factory import RESTClientFactory
+from mcp_server.client.plain.exception import GravitinoException
+from mcp_server.client.plain.plain_rest_client_operation import PlainRESTClientOperation
+from mcp_server.core import audit
+from mcp_server.core.setting import Setting
+from mcp_server.server import GravitinoMCPServer
+from tests.unit.tools import MockOperation
+
+
+class TestAuditEmit(unittest.TestCase):
+ """Unit tests for the audit.emit() function."""
+
+ def setUp(self):
+ # tests/unit/tools/__init__.py calls logging.disable(logging.INFO).
+ # Re-enable here so audit records flow through; restore on teardown.
+ logging.disable(logging.NOTSET)
+ self.log_records = []
+ self.handler = _CapturingHandler(self.log_records)
+ audit_logger = logging.getLogger("gravitino.mcp.audit")
+ audit_logger.addHandler(self.handler)
+ audit_logger.setLevel(logging.INFO)
+ audit_logger.propagate = False
+
+ def tearDown(self):
+ logging.disable(logging.INFO)
+ audit_logger = logging.getLogger("gravitino.mcp.audit")
+ audit_logger.removeHandler(self.handler)
+ audit_logger.propagate = True
+
+ def test_allow_record_structure(self):
+ """emit() writes a JSON record with all required fields on allow."""
+ audit.emit(principal="bearer:abc12345", tool="list_catalogs", outcome="allow")
+
+ self.assertEqual(len(self.log_records), 1)
+ record = json.loads(self.log_records[0])
+ self.assertEqual(record["principal"], "bearer:abc12345")
+ self.assertEqual(record["tool"], "list_catalogs")
+ self.assertEqual(record["outcome"], "allow")
+ self.assertIn("timestamp", record)
+ self.assertNotIn("error_type", record)
+
+ def test_deny_record_includes_error_type(self):
+ """emit() includes error_type in the record when outcome is deny."""
+ audit.emit(
+ principal="bearer:xyz99999",
+ tool="create_tag",
+ outcome="deny",
+ error_type="GravitinoException",
+ )
+
+ record = json.loads(self.log_records[0])
+ self.assertEqual(record["outcome"], "deny")
+ self.assertEqual(record["error_type"], "GravitinoException")
+
+ def test_anonymous_principal(self):
+ """emit() works with anonymous principal."""
+ audit.emit(principal="anonymous", tool="get_list_of_catalogs", outcome="allow")
+ record = json.loads(self.log_records[0])
+ self.assertEqual(record["principal"], "anonymous")
+
+
+class TestExtractPrincipal(unittest.TestCase):
+ """Unit tests for audit._extract_principal()."""
+
+ def test_bearer_token_truncated_to_8_chars(self):
+ self.assertEqual(
+ audit._extract_principal("Bearer abcdefghijklmnop"),
+ "bearer:abcdefgh",
+ )
+
+ def test_empty_header_returns_anonymous(self):
+ self.assertEqual(audit._extract_principal(""), "anonymous")
+
+ def test_none_like_empty_returns_anonymous(self):
+ self.assertEqual(audit._extract_principal(None), "anonymous")
+
+ def test_short_token_uses_full_token(self):
+ self.assertEqual(audit._extract_principal("Bearer abc"), "bearer:abc")
+
+
+class TestAuditMiddlewareIntegration(unittest.TestCase):
+ """Integration tests: AuditMiddleware emits records via the full MCP tool path."""
+
+ def setUp(self):
+ logging.disable(logging.NOTSET)
+ self.log_records = []
+ self.handler = _CapturingHandler(self.log_records)
+ audit_logger = logging.getLogger("gravitino.mcp.audit")
+ audit_logger.addHandler(self.handler)
+ audit_logger.setLevel(logging.INFO)
+ audit_logger.propagate = False
+
+ RESTClientFactory.set_rest_client(MockOperation)
+ server = GravitinoMCPServer(Setting("mock_metalake"))
+ self.mcp = server.mcp
+
+ def tearDown(self):
+ logging.disable(logging.INFO)
+ audit_logger = logging.getLogger("gravitino.mcp.audit")
+ audit_logger.removeHandler(self.handler)
+ audit_logger.propagate = True
+ # Restore original REST client so other tests are not affected.
+ RESTClientFactory.set_rest_client(PlainRESTClientOperation)
+
+ def test_successful_tool_call_emits_allow_record(self):
+ """A successful tool call produces an audit record with outcome=allow."""
+
+ async def _run():
+ async with Client(self.mcp) as client:
+ await client.call_tool("get_list_of_catalogs")
+
+ asyncio.run(_run())
+
+ self.assertEqual(len(self.log_records), 1)
+ record = json.loads(self.log_records[0])
+ self.assertEqual(record["tool"], "get_list_of_catalogs")
+ self.assertEqual(record["outcome"], "allow")
+ self.assertEqual(record["principal"], "anonymous")
+
+ def test_failed_tool_call_emits_deny_record(self):
+ """A tool call that raises an exception produces an audit record with outcome=deny."""
+
+ class FailingOperation(MockOperation):
+ def as_catalog_operation(self):
+ return _FailingCatalogOperation()
+
+ RESTClientFactory.set_rest_client(FailingOperation)
+ server = GravitinoMCPServer(Setting("mock_metalake"))
+
+ async def _run():
+ async with Client(server.mcp) as client:
+ try:
+ await client.call_tool("get_list_of_catalogs")
+ except Exception:
+ pass
+
+ asyncio.run(_run())
+
+ deny_records = [
+ json.loads(r) for r in self.log_records if '"deny"' in r
+ ]
+ self.assertTrue(len(deny_records) >= 1)
+ self.assertEqual(deny_records[0]["tool"], "get_list_of_catalogs")
+ self.assertEqual(deny_records[0]["outcome"], "deny")
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+class _CapturingHandler(logging.Handler):
+ """Logging handler that stores formatted messages in a list."""
+
+ def __init__(self, records: list):
+ super().__init__()
+ self._records = records
+
+ def emit(self, record: logging.LogRecord) -> None:
+ self._records.append(self.format(record))
+
+
+class _FailingCatalogOperation:
+ async def get_list_of_catalogs(self) -> str:
+ raise GravitinoException("Error code: 1003, Error type: FORBIDDEN")
(gravitino) 08/09: [#11572] feat(mcp-server): accept streamable-http transport alias and serve endpoint over TLS
Posted by yu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yuqi1129 pushed a commit to branch feat/mcp-governance-task3-6
in repository https://gitbox.apache.org/repos/asf/gravitino.git
commit 031702432fda09005f91ceb2f0ea45e2b4f7ed8c
Author: yuqi <yu...@datastrato.com>
AuthorDate: Thu Jun 11 14:34:18 2026 +0800
[#11572] feat(mcp-server): accept streamable-http transport alias and serve endpoint over TLS
Closes the remaining transport-surface gaps so the PRD demo command runs as-is:
uv run mcp_server --metalake <ml> --gravitino-uri https://<host>:8090 \
--transport streamable-http --mcp-url https://<mcp-host>:<port> \
--tls-cert <cert.pem> --tls-key <key.pem>
- main.py: accept `streamable-http` as a --transport choice (equivalent to
`http`); add --tls-cert / --tls-key options.
- setting.py: add tls_cert / tls_key fields.
- server.py: _parse_mcp_url now accepts https:// (default port 443) and rejects
non-http(s) schemes; _run_http maps the transport name and forwards
ssl_certfile/ssl_keyfile to uvicorn via FastMCP's uvicorn_config when both
cert and key are set.
- tests/unit/test_transport_tls.py: 9 tests for URL parsing, the streamable-http
alias, and TLS config wiring.
Verified manually: server starts as `Uvicorn running on https://...`, an HTTPS
initialize request returns 200, and plain HTTP to the TLS port is refused.
---
mcp-server/mcp_server/core/setting.py | 7 +-
mcp-server/mcp_server/main.py | 26 +++++-
mcp-server/mcp_server/server.py | 38 +++++++--
mcp-server/tests/unit/test_transport_tls.py | 124 ++++++++++++++++++++++++++++
4 files changed, 184 insertions(+), 11 deletions(-)
diff --git a/mcp-server/mcp_server/core/setting.py b/mcp-server/mcp_server/core/setting.py
index 4d159d6c90..65427a9507 100644
--- a/mcp-server/mcp_server/core/setting.py
+++ b/mcp-server/mcp_server/core/setting.py
@@ -36,11 +36,16 @@ class Setting:
# Bearer token forwarded to Gravitino on every request.
# Empty string means anonymous (no Authorization header sent).
token: str = ""
+ # TLS certificate/key paths for serving the HTTP endpoint over HTTPS.
+ # Both must be set to enable TLS; empty means plain HTTP.
+ tls_cert: str = ""
+ tls_key: str = ""
def __str__(self) -> str:
token_display = "***" if self.token else ""
return (
f"Setting(metalake={self.metalake}, gravitino_uri={self.gravitino_uri}, "
f"tags={self.tags}, transport={self.transport}, mcp_url={self.mcp_url}, "
- f"token={token_display})"
+ f"token={token_display}, tls_cert={self.tls_cert}, "
+ f"tls_key={self.tls_key})"
)
diff --git a/mcp-server/mcp_server/main.py b/mcp-server/mcp_server/main.py
index ca60d8930f..fa459dd316 100644
--- a/mcp-server/mcp_server/main.py
+++ b/mcp-server/mcp_server/main.py
@@ -32,6 +32,8 @@ def do_main():
transport=args.transport,
mcp_url=args.mcp_url,
token=args.token,
+ tls_cert=args.tls_cert,
+ tls_key=args.tls_key,
)
_init_logging(setting)
logging.info("Gravitino MCP server setting: %s", setting)
@@ -91,9 +93,10 @@ def _parse_args():
parser.add_argument(
"--transport",
type=str,
- choices=["stdio", "http"],
+ choices=["stdio", "http", "streamable-http"],
default=DefaultSetting.default_transport,
- help=f"Transport protocol type: stdio (local), http (Streamable HTTP). "
+ help="Transport protocol type: stdio (local), http / streamable-http "
+ "(networked Streamable HTTP; the two names are equivalent). "
f"(default: {DefaultSetting.default_transport})",
)
@@ -101,7 +104,8 @@ def _parse_args():
"--mcp-url",
type=str,
default=DefaultSetting.default_mcp_url,
- help=f"The url of MCP server if using http transport. (default: {DefaultSetting.default_mcp_url})",
+ help="The url of MCP server if using http transport, http:// or https://. "
+ f"(default: {DefaultSetting.default_mcp_url})",
)
parser.add_argument(
@@ -113,6 +117,22 @@ def _parse_args():
"When omitted, requests are sent without authentication.",
)
+ parser.add_argument(
+ "--tls-cert",
+ type=str,
+ default="",
+ help="Path to the TLS certificate (PEM) for serving the HTTP endpoint "
+ "over HTTPS. Requires --tls-key. When omitted, the endpoint serves plain HTTP.",
+ )
+
+ parser.add_argument(
+ "--tls-key",
+ type=str,
+ default="",
+ help="Path to the TLS private key (PEM) for serving the HTTP endpoint "
+ "over HTTPS. Requires --tls-cert.",
+ )
+
args = parser.parse_args()
return args
diff --git a/mcp-server/mcp_server/server.py b/mcp-server/mcp_server/server.py
index 4280932c9e..a6c1558948 100644
--- a/mcp-server/mcp_server/server.py
+++ b/mcp-server/mcp_server/server.py
@@ -119,14 +119,17 @@ def _create_gravitino_mcp(setting: Setting) -> FastMCP:
def _parse_mcp_url(url: str) -> ():
try:
parsed = urlparse(url)
- if parsed.scheme.lower() != "http":
- raise ValueError(f"Not support: {parsed.scheme},only support HTTP")
+ scheme = parsed.scheme.lower()
+ if scheme not in ("http", "https"):
+ raise ValueError(
+ f"Not supported: {parsed.scheme}, only http/https are supported"
+ )
host = parsed.hostname or "0.0.0.0"
port = parsed.port
if port is None:
- port = 80
+ port = 443 if scheme == "https" else 80
path = parsed.path
if not path.startswith("/"):
@@ -155,8 +158,29 @@ class GravitinoMCPServer:
def _run_http(self):
_host, _port, _path = _parse_mcp_url(self.setting.mcp_url)
- asyncio.run(
- self.mcp.run_async(
- transport="http", host=_host, port=_port, path=_path
- )
+ # FastMCP accepts "http" and "streamable-http" as equivalent aliases.
+ transport = (
+ "streamable-http"
+ if self.setting.transport == "streamable-http"
+ else "http"
)
+
+ run_kwargs = {
+ "transport": transport,
+ "host": _host,
+ "port": _port,
+ "path": _path,
+ }
+
+ # Serve over TLS when both certificate and key are provided. FastMCP
+ # forwards uvicorn_config to the underlying uvicorn server.
+ if self.setting.tls_cert and self.setting.tls_key:
+ run_kwargs["uvicorn_config"] = {
+ "ssl_certfile": self.setting.tls_cert,
+ "ssl_keyfile": self.setting.tls_key,
+ }
+ logging.info(
+ "Serving MCP endpoint over TLS (cert=%s)", self.setting.tls_cert
+ )
+
+ asyncio.run(self.mcp.run_async(**run_kwargs))
diff --git a/mcp-server/tests/unit/test_transport_tls.py b/mcp-server/tests/unit/test_transport_tls.py
new file mode 100644
index 0000000000..ac1eab3249
--- /dev/null
+++ b/mcp-server/tests/unit/test_transport_tls.py
@@ -0,0 +1,124 @@
+# 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.
+
+"""Tests for HTTP transport URL parsing, the streamable-http alias, and TLS wiring."""
+
+import unittest
+from unittest.mock import patch
+
+from mcp_server.client.factory import RESTClientFactory
+from mcp_server.core.setting import Setting
+from mcp_server.server import GravitinoMCPServer, _parse_mcp_url
+from tests.unit.tools import MockOperation
+
+
+class TestParseMcpUrl(unittest.TestCase):
+ """_parse_mcp_url accepts http and https and rejects other schemes."""
+
+ def test_http_url(self):
+ self.assertEqual(
+ _parse_mcp_url("http://127.0.0.1:8000/mcp"),
+ ("127.0.0.1", 8000, "/mcp"),
+ )
+
+ def test_https_url(self):
+ self.assertEqual(
+ _parse_mcp_url("https://mcphost:9443/mcp"),
+ ("mcphost", 9443, "/mcp"),
+ )
+
+ def test_https_default_port(self):
+ host, port, path = _parse_mcp_url("https://mcphost/mcp")
+ self.assertEqual(port, 443)
+
+ def test_http_default_port(self):
+ host, port, path = _parse_mcp_url("http://mcphost/mcp")
+ self.assertEqual(port, 80)
+
+ def test_unsupported_scheme_rejected(self):
+ with self.assertRaises(ValueError):
+ _parse_mcp_url("ftp://mcphost/mcp")
+
+
+class TestRunHttpTransport(unittest.TestCase):
+ """GravitinoMCPServer.run() wires transport name and TLS config correctly."""
+
+ def setUp(self):
+ RESTClientFactory.set_rest_client(MockOperation)
+
+ def _run_and_capture(self, setting: Setting) -> dict:
+ """Run the server with run_async patched; return the kwargs it was called with."""
+ server = GravitinoMCPServer(setting)
+ captured = {}
+
+ async def fake_run_async(**kwargs):
+ captured.update(kwargs)
+
+ with patch.object(server.mcp, "run_async", side_effect=fake_run_async):
+ server.run()
+ return captured
+
+ def test_http_transport(self):
+ setting = Setting(
+ metalake="ml",
+ transport="http",
+ mcp_url="http://127.0.0.1:8000/mcp",
+ )
+ kwargs = self._run_and_capture(setting)
+ self.assertEqual(kwargs["transport"], "http")
+ self.assertEqual(kwargs["host"], "127.0.0.1")
+ self.assertEqual(kwargs["port"], 8000)
+ self.assertEqual(kwargs["path"], "/mcp")
+ self.assertNotIn("uvicorn_config", kwargs)
+
+ def test_streamable_http_alias(self):
+ setting = Setting(
+ metalake="ml",
+ transport="streamable-http",
+ mcp_url="http://127.0.0.1:8000/mcp",
+ )
+ kwargs = self._run_and_capture(setting)
+ self.assertEqual(kwargs["transport"], "streamable-http")
+
+ def test_tls_config_wired_when_cert_and_key_set(self):
+ setting = Setting(
+ metalake="ml",
+ transport="streamable-http",
+ mcp_url="https://127.0.0.1:8443/mcp",
+ tls_cert="/path/to/cert.pem",
+ tls_key="/path/to/key.pem",
+ )
+ kwargs = self._run_and_capture(setting)
+ self.assertEqual(
+ kwargs["uvicorn_config"],
+ {
+ "ssl_certfile": "/path/to/cert.pem",
+ "ssl_keyfile": "/path/to/key.pem",
+ },
+ )
+
+ def test_no_tls_when_only_cert_set(self):
+ """TLS requires both cert and key; a lone cert does not enable it."""
+ setting = Setting(
+ metalake="ml",
+ transport="http",
+ mcp_url="http://127.0.0.1:8000/mcp",
+ tls_cert="/path/to/cert.pem",
+ tls_key="",
+ )
+ kwargs = self._run_and_capture(setting)
+ self.assertNotIn("uvicorn_config", kwargs)
(gravitino) 04/09: [#11572] feat(mcp-server): per-request token isolation for HTTP transport
Posted by yu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yuqi1129 pushed a commit to branch feat/mcp-governance-task3-6
in repository https://gitbox.apache.org/repos/asf/gravitino.git
commit a821a009ea0f1246e788aba46a7857a168bb8ac1
Author: yuqi <yu...@datastrato.com>
AuthorDate: Wed Jun 10 20:36:40 2026 +0800
[#11572] feat(mcp-server): per-request token isolation for HTTP transport
GravitinoContext.rest_client() now extracts the Bearer token from the current
HTTP request's Authorization header via fastmcp.server.dependencies.get_http_request().
A per-request token creates a fresh httpx client carrying that token, ensuring
concurrent multi-principal sessions are fully isolated — one principal's token
never leaks into another's Gravitino calls.
Falls back to the shared default client (startup token) in stdio mode or when no
Authorization header is present.
Also add _extract_bearer_token() and _get_request_token() as testable helpers.
tests/unit/test_per_request_token.py: 11 tests covering token extraction,
stdio fallback, per-request override, and concurrent session isolation.
---
mcp-server/mcp_server/core/context.py | 46 ++++++-
mcp-server/mcp_server/server.py | 7 +-
mcp-server/tests/unit/test_per_request_token.py | 160 ++++++++++++++++++++++++
3 files changed, 207 insertions(+), 6 deletions(-)
diff --git a/mcp-server/mcp_server/core/context.py b/mcp-server/mcp_server/core/context.py
index 83350a7d10..f2cde66692 100644
--- a/mcp-server/mcp_server/core/context.py
+++ b/mcp-server/mcp_server/core/context.py
@@ -19,11 +19,53 @@ from mcp_server.client.factory import RESTClientFactory
from mcp_server.core.setting import Setting
+def _extract_bearer_token(authorization: str) -> str:
+ """Parse a Bearer token from a raw Authorization header value."""
+ parts = authorization.split()
+ if len(parts) == 2 and parts[0].lower() == "bearer":
+ return parts[1]
+ return ""
+
+
+def _get_request_token() -> str:
+ """Extract the Bearer token from the current HTTP request, if any.
+
+ Returns an empty string in stdio mode or when the header is absent.
+ """
+ try:
+ from fastmcp.server.dependencies import get_http_request
+
+ authorization = get_http_request().headers.get("authorization", "")
+ return _extract_bearer_token(authorization)
+ except Exception: # noqa: BLE001 – stdio mode or missing request context
+ return ""
+
+
class GravitinoContext:
def __init__(self, setting: Setting):
- self.gravitino_client = RESTClientFactory.create_rest_client(
+ self._setting = setting
+ # Fallback client for stdio mode or when no per-request token is present.
+ self._default_client = RESTClientFactory.create_rest_client(
setting.metalake, setting.gravitino_uri, setting.token
)
def rest_client(self):
- return self.gravitino_client
+ """Return a REST client carrying the correct identity for this request.
+
+ In HTTP transport mode the Bearer token from the incoming MCP request's
+ Authorization header takes priority over the static startup token.
+ This ensures concurrent sessions with different principals are fully
+ isolated — one principal's token never leaks into another's Gravitino calls.
+
+ Falls back to the shared default client (static startup token) when:
+ - running in stdio mode (no HTTP request context), or
+ - the incoming request carries no Authorization header.
+ """
+ request_token = _get_request_token()
+ if request_token:
+ return RESTClientFactory.create_rest_client(
+ self._setting.metalake,
+ self._setting.gravitino_uri,
+ request_token,
+ )
+ return self._default_client
diff --git a/mcp-server/mcp_server/server.py b/mcp-server/mcp_server/server.py
index 8d66fec936..aea7df7f78 100644
--- a/mcp-server/mcp_server/server.py
+++ b/mcp-server/mcp_server/server.py
@@ -43,15 +43,14 @@ from mcp_server.tools import load_tools
def _get_principal_from_request() -> str:
- """Extract the principal from the current HTTP request's Authorization header.
+ """Derive a display principal from the current HTTP request's Authorization header.
- Returns "anonymous" in stdio mode (no HTTP request) or when no token is present.
+ Returns "anonymous" in stdio mode or when no token is present.
"""
try:
from fastmcp.server.dependencies import get_http_request
- request = get_http_request()
- authorization = request.headers.get("authorization", "")
+ authorization = get_http_request().headers.get("authorization", "")
return audit._extract_principal(authorization)
except Exception: # noqa: BLE001 – stdio mode or no request context
return "anonymous"
diff --git a/mcp-server/tests/unit/test_per_request_token.py b/mcp-server/tests/unit/test_per_request_token.py
new file mode 100644
index 0000000000..c08cbeeb39
--- /dev/null
+++ b/mcp-server/tests/unit/test_per_request_token.py
@@ -0,0 +1,160 @@
+# 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.
+
+"""Tests for per-request token isolation (Task 6).
+
+GravitinoContext.rest_client() must return a client carrying the token from
+the current HTTP request, not the shared startup token, when an Authorization
+header is present. This ensures concurrent multi-principal sessions are fully
+isolated in HTTP transport mode.
+"""
+
+import unittest
+from unittest.mock import MagicMock, patch
+
+from mcp_server.core.context import (
+ GravitinoContext,
+ _extract_bearer_token,
+ _get_request_token,
+)
+from mcp_server.core.setting import Setting
+
+
+class TestExtractBearerToken(unittest.TestCase):
+ """Unit tests for the token extraction helper."""
+
+ def test_well_formed_bearer_header(self):
+ self.assertEqual(_extract_bearer_token("Bearer mytoken123"), "mytoken123")
+
+ def test_case_insensitive_bearer(self):
+ self.assertEqual(_extract_bearer_token("bearer MYTOKEN"), "MYTOKEN")
+
+ def test_empty_header_returns_empty(self):
+ self.assertEqual(_extract_bearer_token(""), "")
+
+ def test_non_bearer_scheme_returns_empty(self):
+ self.assertEqual(_extract_bearer_token("Basic dXNlcjpwYXNz"), "")
+
+ def test_only_scheme_no_token_returns_empty(self):
+ self.assertEqual(_extract_bearer_token("Bearer"), "")
+
+
+class TestGetRequestToken(unittest.TestCase):
+ """Unit tests for _get_request_token() (HTTP context extraction)."""
+
+ def test_returns_token_when_http_request_available(self):
+ mock_request = MagicMock()
+ mock_request.headers.get.return_value = "Bearer request-token-xyz"
+
+ with patch(
+ "fastmcp.server.dependencies.get_http_request",
+ return_value=mock_request,
+ ):
+ token = _get_request_token()
+
+ self.assertEqual(token, "request-token-xyz")
+
+ def test_returns_empty_when_no_http_context(self):
+ """Simulates stdio mode where get_http_request raises LookupError."""
+ with patch(
+ "fastmcp.server.dependencies.get_http_request",
+ side_effect=LookupError("no request context"),
+ ):
+ token = _get_request_token()
+
+ self.assertEqual(token, "")
+
+ def test_returns_empty_when_no_authorization_header(self):
+ mock_request = MagicMock()
+ mock_request.headers.get.return_value = ""
+
+ with patch(
+ "fastmcp.server.dependencies.get_http_request",
+ return_value=mock_request,
+ ):
+ token = _get_request_token()
+
+ self.assertEqual(token, "")
+
+
+class TestGravitinoContextPerRequestToken(unittest.TestCase):
+ """GravitinoContext.rest_client() isolates per-request tokens."""
+
+ def _make_context(self, startup_token: str = "") -> GravitinoContext:
+ return GravitinoContext(
+ Setting(
+ metalake="ml",
+ gravitino_uri="http://localhost:8090",
+ token=startup_token,
+ )
+ )
+
+ def test_per_request_token_overrides_startup_token(self):
+ """When an HTTP request carries a token, it takes priority over the startup token."""
+ ctx = self._make_context(startup_token="startup-token")
+
+ mock_request = MagicMock()
+ mock_request.headers.get.return_value = "Bearer request-token"
+
+ with patch(
+ "fastmcp.server.dependencies.get_http_request",
+ return_value=mock_request,
+ ):
+ client = ctx.rest_client()
+
+ headers = dict(client._catalog_operation.rest_client.headers)
+ self.assertEqual(headers.get("authorization"), "Bearer request-token")
+
+ def test_falls_back_to_default_client_when_no_request_token(self):
+ """When no per-request token exists, the shared default client (startup token) is used."""
+ ctx = self._make_context(startup_token="startup-token")
+
+ with patch(
+ "fastmcp.server.dependencies.get_http_request",
+ side_effect=LookupError,
+ ):
+ client = ctx.rest_client()
+
+ # Must be the exact same object as the cached default client.
+ self.assertIs(client, ctx._default_client)
+
+ def test_two_concurrent_requests_get_different_clients(self):
+ """Different request tokens must produce different client instances."""
+ ctx = self._make_context()
+
+ def make_mock(token: str) -> MagicMock:
+ m = MagicMock()
+ m.headers.get.return_value = f"Bearer {token}"
+ return m
+
+ with patch(
+ "fastmcp.server.dependencies.get_http_request",
+ return_value=make_mock("alice-token"),
+ ):
+ client_alice = ctx.rest_client()
+
+ with patch(
+ "fastmcp.server.dependencies.get_http_request",
+ return_value=make_mock("bob-token"),
+ ):
+ client_bob = ctx.rest_client()
+
+ alice_headers = dict(client_alice._catalog_operation.rest_client.headers)
+ bob_headers = dict(client_bob._catalog_operation.rest_client.headers)
+ self.assertEqual(alice_headers.get("authorization"), "Bearer alice-token")
+ self.assertEqual(bob_headers.get("authorization"), "Bearer bob-token")
+ self.assertIsNot(client_alice, client_bob)
(gravitino) 01/09: [#11565][#11566] feat(mcp-server): add --token CLI param and inject Bearer token into Gravitino REST calls
Posted by yu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yuqi1129 pushed a commit to branch feat/mcp-governance-task3-6
in repository https://gitbox.apache.org/repos/asf/gravitino.git
commit 4c3570b6c0ebae3effb0618ae8c9d1ecbeb25e07
Author: yuqi <yu...@datastrato.com>
AuthorDate: Wed Jun 10 20:11:48 2026 +0800
[#11565][#11566] feat(mcp-server): add --token CLI param and inject Bearer token into Gravitino REST calls
- Setting: add `token` field; mask value in __str__ to avoid log leakage
- main.py: add `--token` CLI arg (fallback to GRAVITINO_TOKEN env var)
- PlainRESTClientOperation: accept token; set Authorization: Bearer header on httpx client when non-empty
- RESTClientFactory.create_rest_client: pass token through
- GravitinoContext: propagate setting.token to factory
- MockOperation: accept token param (test compatibility)
- tests/unit/test_auth_flow.py: 7 new tests covering token injection, masking, and context propagation
---
mcp-server/mcp_server/client/factory.py | 5 +-
.../client/plain/plain_rest_client_operation.py | 7 +-
mcp-server/mcp_server/core/context.py | 2 +-
mcp-server/mcp_server/core/setting.py | 11 +++
mcp-server/mcp_server/main.py | 11 +++
mcp-server/tests/unit/test_auth_flow.py | 93 ++++++++++++++++++++++
mcp-server/tests/unit/tools/mock_operation.py | 2 +-
7 files changed, 125 insertions(+), 6 deletions(-)
diff --git a/mcp-server/mcp_server/client/factory.py b/mcp-server/mcp_server/client/factory.py
index d990284d28..2e5489d053 100644
--- a/mcp-server/mcp_server/client/factory.py
+++ b/mcp-server/mcp_server/client/factory.py
@@ -29,7 +29,7 @@ class RESTClientFactory:
@classmethod
def create_rest_client(
- cls, metalake_name: str, uri: str
+ cls, metalake_name: str, uri: str, token: str = ""
) -> "PlainRESTClientOperation":
"""
Create a new rest client instance with the specified parameters.
@@ -37,11 +37,12 @@ class RESTClientFactory:
Args:
metalake_name: Name of the metalake
uri: URI of the Gravitino server endpoint
+ token: Bearer token for Authorization header (empty = anonymous)
Returns:
New instance of the configured rest client class
"""
- return cls._rest_client_class(metalake_name, uri)
+ return cls._rest_client_class(metalake_name, uri, token)
@classmethod
def set_rest_client(cls, rest_client_class: type) -> None:
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 205562b6d8..8bb8b51aa3 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
@@ -62,8 +62,11 @@ from mcp_server.client.topic_operation import TopicOperation
# pylint: disable=too-many-instance-attributes
class PlainRESTClientOperation(GravitinoOperation):
- def __init__(self, metalake_name: str, uri: str):
- _rest_client = httpx.AsyncClient(base_url=uri)
+ def __init__(self, metalake_name: str, uri: str, token: str = ""):
+ headers = {}
+ if token:
+ headers["Authorization"] = f"Bearer {token}"
+ _rest_client = httpx.AsyncClient(base_url=uri, headers=headers)
self._catalog_operation = PlainRESTClientCatalogOperation(
metalake_name, _rest_client
)
diff --git a/mcp-server/mcp_server/core/context.py b/mcp-server/mcp_server/core/context.py
index 6e540a0b51..83350a7d10 100644
--- a/mcp-server/mcp_server/core/context.py
+++ b/mcp-server/mcp_server/core/context.py
@@ -22,7 +22,7 @@ from mcp_server.core.setting import Setting
class GravitinoContext:
def __init__(self, setting: Setting):
self.gravitino_client = RESTClientFactory.create_rest_client(
- setting.metalake, setting.gravitino_uri
+ setting.metalake, setting.gravitino_uri, setting.token
)
def rest_client(self):
diff --git a/mcp-server/mcp_server/core/setting.py b/mcp-server/mcp_server/core/setting.py
index 474fdbc6b4..4d159d6c90 100644
--- a/mcp-server/mcp_server/core/setting.py
+++ b/mcp-server/mcp_server/core/setting.py
@@ -33,3 +33,14 @@ class Setting:
tags: Set[str] = field(default_factory=set)
transport: str = DefaultSetting.default_transport
mcp_url: str = DefaultSetting.default_mcp_url
+ # Bearer token forwarded to Gravitino on every request.
+ # Empty string means anonymous (no Authorization header sent).
+ token: str = ""
+
+ def __str__(self) -> str:
+ token_display = "***" if self.token else ""
+ return (
+ f"Setting(metalake={self.metalake}, gravitino_uri={self.gravitino_uri}, "
+ f"tags={self.tags}, transport={self.transport}, mcp_url={self.mcp_url}, "
+ f"token={token_display})"
+ )
diff --git a/mcp-server/mcp_server/main.py b/mcp-server/mcp_server/main.py
index 73a5aa265f..b1200b3180 100644
--- a/mcp-server/mcp_server/main.py
+++ b/mcp-server/mcp_server/main.py
@@ -17,6 +17,7 @@
import argparse
import logging
+import os
from mcp_server.core.setting import DefaultSetting, Setting
from mcp_server.server import GravitinoMCPServer
@@ -30,6 +31,7 @@ def do_main():
tags=args.include_tool_tags,
transport=args.transport,
mcp_url=args.mcp_url,
+ token=args.token,
)
_init_logging(setting)
logging.info("Gravitino MCP server setting: %s", setting)
@@ -96,6 +98,15 @@ def _parse_args():
help=f"The url of MCP server if using http transport. (default: {DefaultSetting.default_mcp_url})",
)
+ parser.add_argument(
+ "--token",
+ type=str,
+ default=os.environ.get("GRAVITINO_TOKEN", ""),
+ help="Bearer token forwarded as Authorization header to Gravitino on every request. "
+ "Can also be set via the GRAVITINO_TOKEN environment variable. "
+ "When omitted, requests are sent without authentication.",
+ )
+
args = parser.parse_args()
return args
diff --git a/mcp-server/tests/unit/test_auth_flow.py b/mcp-server/tests/unit/test_auth_flow.py
new file mode 100644
index 0000000000..a413515bf9
--- /dev/null
+++ b/mcp-server/tests/unit/test_auth_flow.py
@@ -0,0 +1,93 @@
+# 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.
+
+import unittest
+
+from mcp_server.client.plain.plain_rest_client_operation import (
+ PlainRESTClientOperation,
+)
+from mcp_server.core.context import GravitinoContext
+from mcp_server.core.setting import Setting
+
+
+class TestTokenInjection(unittest.TestCase):
+ """Verify Bearer token is correctly injected into the httpx client."""
+
+ def test_token_sets_authorization_header(self):
+ """When a token is provided, the httpx client carries Authorization: Bearer."""
+ client = PlainRESTClientOperation(
+ "my_metalake", "http://localhost:8090", token="my-secret-token"
+ )
+ headers = dict(client._catalog_operation.rest_client.headers)
+ self.assertEqual(headers.get("authorization"), "Bearer my-secret-token")
+
+ def test_empty_token_no_authorization_header(self):
+ """When token is empty, no Authorization header is added."""
+ client = PlainRESTClientOperation(
+ "my_metalake", "http://localhost:8090", token=""
+ )
+ headers = dict(client._catalog_operation.rest_client.headers)
+ self.assertNotIn("authorization", headers)
+
+ def test_no_token_argument_no_authorization_header(self):
+ """When token argument is omitted entirely, no Authorization header is added."""
+ client = PlainRESTClientOperation("my_metalake", "http://localhost:8090")
+ headers = dict(client._catalog_operation.rest_client.headers)
+ self.assertNotIn("authorization", headers)
+
+
+class TestSettingTokenMasking(unittest.TestCase):
+ """Verify that the token is not exposed in Setting string representation."""
+
+ def test_token_masked_in_str(self):
+ """Token value must not appear in Setting.__str__."""
+ setting = Setting(metalake="ml", token="super-secret-token-value")
+ self.assertNotIn("super-secret-token-value", str(setting))
+ self.assertIn("***", str(setting))
+
+ def test_empty_token_shows_empty_in_str(self):
+ """When no token is set, __str__ shows empty placeholder."""
+ setting = Setting(metalake="ml", token="")
+ self.assertNotIn("***", str(setting))
+
+
+class TestGravitinoContextTokenPropagation(unittest.TestCase):
+ """Verify GravitinoContext passes token from Setting to the REST client."""
+
+ def test_context_propagates_token(self):
+ """Token from Setting reaches the httpx client Authorization header."""
+ setting = Setting(
+ metalake="ml",
+ gravitino_uri="http://localhost:8090",
+ token="ctx-token-xyz",
+ )
+ ctx = GravitinoContext(setting)
+ rest_client = ctx.rest_client()
+ headers = dict(rest_client._catalog_operation.rest_client.headers)
+ self.assertEqual(headers.get("authorization"), "Bearer ctx-token-xyz")
+
+ def test_context_anonymous_when_no_token(self):
+ """Empty token in Setting → no Authorization header in REST calls."""
+ setting = Setting(
+ metalake="ml",
+ gravitino_uri="http://localhost:8090",
+ token="",
+ )
+ ctx = GravitinoContext(setting)
+ rest_client = ctx.rest_client()
+ headers = dict(rest_client._catalog_operation.rest_client.headers)
+ self.assertNotIn("authorization", headers)
diff --git a/mcp-server/tests/unit/tools/mock_operation.py b/mcp-server/tests/unit/tools/mock_operation.py
index d76ba94b60..a985bf7912 100644
--- a/mcp-server/tests/unit/tools/mock_operation.py
+++ b/mcp-server/tests/unit/tools/mock_operation.py
@@ -31,7 +31,7 @@ from mcp_server.client.statistic_operation import StatisticOperation
class MockOperation(GravitinoOperation):
- def __init__(self, metalake, uri):
+ def __init__(self, metalake, uri, token=""):
pass
def as_table_operation(self) -> TableOperation:
(gravitino) 02/09: [#11567] feat(mcp-server): enable tag write tools protected by Gravitino authorization
Posted by yu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yuqi1129 pushed a commit to branch feat/mcp-governance-task3-6
in repository https://gitbox.apache.org/repos/asf/gravitino.git
commit 8befd997c277b412ac39e5c7dc06da4750a7fdcd
Author: yuqi <yu...@datastrato.com>
AuthorDate: Wed Jun 10 20:23:46 2026 +0800
[#11567] feat(mcp-server): enable tag write tools protected by Gravitino authorization
Remove mcp.disable() call that hid create_tag/alter_tag/delete_tag.
Write operations are now exposed and enforced by Gravitino authz —
a principal without the required grant receives an explicit denial,
which is a stronger governance story than tool-level hiding.
Update test to assert the three write tools are present in the tool list.
---
mcp-server/mcp_server/tools/tag.py | 5 -----
mcp-server/tests/unit/tools/test_tag.py | 17 ++++++++---------
2 files changed, 8 insertions(+), 14 deletions(-)
diff --git a/mcp-server/mcp_server/tools/tag.py b/mcp-server/mcp_server/tools/tag.py
index f6daafa678..9bbf8cec4b 100644
--- a/mcp-server/mcp_server/tools/tag.py
+++ b/mcp-server/mcp_server/tools/tag.py
@@ -364,8 +364,3 @@ def load_tag_tool(mcp: FastMCP):
"""
client = ctx.request_context.lifespan_context.rest_client()
return await client.as_tag_operation().list_metadata_by_tag(tag_name)
-
- mcp.disable(
- names={"create_tag", "alter_tag", "delete_tag"},
- components={"tool"},
- )
diff --git a/mcp-server/tests/unit/tools/test_tag.py b/mcp-server/tests/unit/tools/test_tag.py
index 1bb7046f4c..7353bba032 100644
--- a/mcp-server/tests/unit/tools/test_tag.py
+++ b/mcp-server/tests/unit/tools/test_tag.py
@@ -99,14 +99,13 @@ class TestTagTool(unittest.TestCase):
asyncio.run(_test_disassociate_tag_from_metadata(self.mcp))
- def test_destructive_tag_tools_disabled_by_default(self):
- async def _test_destructive_tag_tools_disabled_by_default(mcp_server):
- tool_names = {tool.name for tool in await mcp_server.list_tools()}
+ def test_write_tag_tools_enabled_and_protected_by_authz(self):
+ """Write tools are exposed; authorization is enforced by Gravitino, not by hiding."""
- self.assertIn("get_tag_by_name", tool_names)
- self.assertIn("list_of_tags", tool_names)
- self.assertNotIn("create_tag", tool_names)
- self.assertNotIn("alter_tag", tool_names)
- self.assertNotIn("delete_tag", tool_names)
+ async def _test(mcp_server):
+ tool_names = {tool.name for tool in await mcp_server.list_tools()}
+ self.assertIn("create_tag", tool_names)
+ self.assertIn("alter_tag", tool_names)
+ self.assertIn("delete_tag", tool_names)
- asyncio.run(_test_destructive_tag_tools_disabled_by_default(self.mcp))
+ asyncio.run(_test(self.mcp))