flyrain commented on code in PR #39:
URL: https://github.com/apache/polaris-tools/pull/39#discussion_r2524726680


##########
mcp-server/polaris_mcp/tools/table.py:
##########
@@ -0,0 +1,245 @@
+#
+# 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.
+#
+
+"""Iceberg table MCP tool."""
+
+from __future__ import annotations
+
+import copy
+from typing import Any, Dict, Optional, Set
+
+import urllib3
+
+from ..authorization import AuthorizationProvider
+from ..base import JSONDict, McpTool, ToolExecutionResult, copy_if_object, 
require_text
+from ..rest import PolarisRestTool, encode_path_segment
+
+
+class PolarisTableTool(McpTool):
+    """Expose Polaris table REST endpoints through MCP."""
+
+    TOOL_NAME = "polaris-iceberg-table"
+    TOOL_DESCRIPTION = (
+        "Perform table-centric operations (list, get, create, commit, delete) 
using the Polaris REST API."
+    )
+    NAMESPACE_DELIMITER = "\x1f"
+
+    LIST_ALIASES: Set[str] = {"list", "ls"}
+    GET_ALIASES: Set[str] = {"get", "load", "fetch"}
+    CREATE_ALIASES: Set[str] = {"create"}
+    COMMIT_ALIASES: Set[str] = {"commit", "update"}
+    DELETE_ALIASES: Set[str] = {"delete", "drop"}
+
+    def __init__(
+        self,
+        base_url: str,
+        http: urllib3.PoolManager,
+        authorization_provider: AuthorizationProvider,
+    ) -> None:
+        self._delegate = PolarisRestTool(
+            name="polaris.table.delegate",
+            description="Internal delegate for table operations",
+            base_url=base_url,
+            default_path_prefix="api/catalog/v1/",
+            http=http,
+            authorization_provider=authorization_provider,
+        )
+
+    @property
+    def name(self) -> str:
+        return self.TOOL_NAME
+
+    @property
+    def description(self) -> str:
+        return self.TOOL_DESCRIPTION
+
+    def input_schema(self) -> JSONDict:
+        return {
+            "type": "object",
+            "properties": {
+                "operation": {
+                    "type": "string",
+                    "enum": ["list", "get", "create", "commit", "delete"],
+                    "description": (
+                        "Table operation to execute. Supported values: list, 
get (synonyms: load, fetch), "
+                        "create, commit (synonym: update), delete (synonym: 
drop)."
+                    ),
+                },
+                "catalog": {
+                    "type": "string",
+                    "description": "Polaris catalog identifier (maps to the 
{prefix} path segment).",
+                },
+                "namespace": {
+                    "anyOf": [
+                        {"type": "string"},
+                        {"type": "array", "items": {"type": "string"}},
+                    ],
+                    "description": (
+                        "Namespace that contains the target tables. Provide as 
a string that uses the ASCII Unit "
+                        'Separator (0x1F) between hierarchy levels (e.g. 
"analytics\\u001Fdaily") or as an array of '
+                        "strings."
+                    ),
+                },
+                "table": {
+                    "type": "string",
+                    "description": (
+                        "Table identifier for operations that target a 
specific table (get, commit, delete)."
+                    ),
+                },
+                "query": {
+                    "type": "object",
+                    "description": "Optional query string parameters (for 
example page-size, page-token, include-drop).",
+                    "additionalProperties": {"type": "string"},
+                },
+                "headers": {
+                    "type": "object",
+                    "description": "Optional additional HTTP headers to 
include with the request.",
+                    "additionalProperties": {"type": "string"},
+                },
+                "body": {
+                    "type": "object",
+                    "description": "Optional request body payload for create 
or commit operations.",
+                },
+            },
+            "required": ["operation", "catalog", "namespace"],
+        }
+
+    def call(self, arguments: Any) -> ToolExecutionResult:
+        if not isinstance(arguments, dict):
+            raise ValueError("Tool arguments must be a JSON object.")
+
+        operation = require_text(arguments, "operation").lower().strip()
+        normalized = self._normalize_operation(operation)
+
+        catalog = encode_path_segment(require_text(arguments, "catalog"))
+        namespace = 
encode_path_segment(self._resolve_namespace(arguments.get("namespace")))
+
+        delegate_args: JSONDict = {}
+        copy_if_object(arguments.get("query"), delegate_args, "query")
+        copy_if_object(arguments.get("headers"), delegate_args, "headers")
+
+        if normalized == "list":
+            self._handle_list(delegate_args, catalog, namespace)
+        elif normalized == "get":
+            self._handle_get(arguments, delegate_args, catalog, namespace)
+        elif normalized == "create":
+            self._handle_create(arguments, delegate_args, catalog, namespace)
+        elif normalized == "commit":
+            self._handle_commit(arguments, delegate_args, catalog, namespace)
+        elif normalized == "delete":
+            self._handle_delete(arguments, delegate_args, catalog, namespace)
+        else:  # pragma: no cover - defensive, normalize guarantees handled 
cases
+            raise ValueError(f"Unsupported operation: {operation}")
+
+        return self._delegate.call(delegate_args)
+
+    def _handle_list(self, delegate_args: JSONDict, catalog: str, namespace: 
str) -> None:
+        delegate_args["method"] = "GET"
+        delegate_args["path"] = f"{catalog}/namespaces/{namespace}/tables"
+
+    def _handle_get(
+        self,
+        arguments: Dict[str, Any],
+        delegate_args: JSONDict,
+        catalog: str,
+        namespace: str,
+    ) -> None:
+        table = encode_path_segment(
+            require_text(arguments, "table", "Table name is required for get 
operations.")
+        )
+        delegate_args["method"] = "GET"
+        delegate_args["path"] = 
f"{catalog}/namespaces/{namespace}/tables/{table}"
+
+    def _handle_create(
+        self,
+        arguments: Dict[str, Any],
+        delegate_args: JSONDict,
+        catalog: str,
+        namespace: str,
+    ) -> None:
+        body = arguments.get("body")
+        if not isinstance(body, dict):
+            raise ValueError(
+                "Create operations require a request body that matches the 
CreateTableRequest schema. See CreateTableRequest in "
+                
"https://raw.githubusercontent.com/apache/polaris/apache-polaris-1.2.0-incubating/spec/generated/bundled-polaris-catalog-service.yaml";

Review Comment:
   Filed https://github.com/apache/polaris-tools/issues/50



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to