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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ client/python/polaris/
client/python/test/
!client/python/test/test_cli_parsing.py

# Python packaging metadata
*.egg-info/

# Polaris CLI profile
.polaris.json

Expand Down
103 changes: 103 additions & 0 deletions client/python-mcp/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
<!--
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.
-->

# Apache Polaris MCP Server (Python)

This package provides a Python implementation of the [Model Context Protocol (MCP)](https://modelcontextprotocol.io) server for Apache Polaris. It wraps the Polaris REST APIs so MCP-compatible clients (IDEs, agents, chat applications) can issue structured requests via JSON-RPC on stdin/stdout.

The implementation is built on top of [FastMCP](https://gofastmcp.com) for streamlined server registration and transport handling.

## Installation

From the repository root:

```bash
cd client/python-mcp
uv sync
```

## Running

Launch the MCP server (which reads from stdin and writes to stdout):

```bash
uv run polaris-mcp
```

Example interaction:

```json
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"manual","version":"0"}}}
{"jsonrpc":"2.0","id":2,"method":"tools/list"}
```

For a `tools/call` invocation you will typically set environment variables such as `POLARIS_BASE_URL` and authentication settings before launching the server.

### Claude Desktop configuration

```json
{
"mcpServers": {
"polaris": {
"command": "uv",
"args": [
"--directory",
"/path/to/polaris/client/python-mcp",
"run",
"polaris-mcp"
],
"env": {
"POLARIS_BASE_URL": "http://localhost:8181/",
"POLARIS_CLIENT_ID": "root",
"POLARIS_CLIENT_SECRET": "s3cr3t",
"POLARIS_TOKEN_SCOPE": "PRINCIPAL_ROLE:ALL"
}
}
}
}
```

Please note: `--directory` specifies a local directory. It is not needed when we pull `polaris-mcp` from PyPI package.

## Configuration

| Variable | Description | Default |
|----------------------------------------------------------------|----------------------------------------------------------|--------------------------------------------------|
| `POLARIS_BASE_URL` | Base URL for all Polaris REST calls. | `http://localhost:8181/` |
| `POLARIS_API_TOKEN` / `POLARIS_BEARER_TOKEN` / `POLARIS_TOKEN` | Static bearer token (if supplied, overrides other auth). | _unset_ |
| `POLARIS_CLIENT_ID` | OAuth client id for client-credential flow. | _unset_ |
| `POLARIS_CLIENT_SECRET` | OAuth client secret. | _unset_ |
| `POLARIS_TOKEN_SCOPE` | OAuth scope string. | _unset_ |
| `POLARIS_TOKEN_URL` | Optional override for the token endpoint URL. | `${POLARIS_BASE_URL}api/catalog/v1/oauth/tokens` |

When OAuth variables are supplied, the server automatically acquires and refreshes tokens using the client credentials flow; otherwise a static bearer token is used if provided.

## Tools

The server exposes the following MCP tools:

* `polaris-iceberg-table` — Table operations (`list`, `get`, `create`, `update`, `delete`).
* `polaris-namespace-request` — Namespace lifecycle management.
* `polaris-policy` — Policy lifecycle management and mappings.
* `polaris-catalog-request` — Catalog lifecycle management.
* `polaris-principal-request` — Principal lifecycle helpers.
* `polaris-principal-role-request` — Principal role lifecycle and catalog-role assignments.
* `polaris-catalog-role-request` — Catalog role and grant management.

Each tool returns both a human-readable transcript of the HTTP exchange and structured metadata under `result.meta`.
24 changes: 24 additions & 0 deletions client/python-mcp/polaris_mcp/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#
# 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.
#

"""Polaris Model Context Protocol server implementation."""

from .server import create_server, main

__all__ = ["create_server", "main"]
136 changes: 136 additions & 0 deletions client/python-mcp/polaris_mcp/authorization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
#
# 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.
#

"""Authorization helpers for the Polaris MCP server."""

from __future__ import annotations

import json
import threading
import time
from abc import ABC, abstractmethod
from typing import Optional
from urllib.parse import urlencode

import urllib3


class AuthorizationProvider(ABC):
"""Return Authorization header values for outgoing requests."""

@abstractmethod
def authorization_header(self) -> Optional[str]:
...


class StaticAuthorizationProvider(AuthorizationProvider):
"""Wrap a static bearer token."""

def __init__(self, token: Optional[str]) -> None:
value = (token or "").strip()
self._header = f"Bearer {value}" if value else None

def authorization_header(self) -> Optional[str]:
return self._header


class ClientCredentialsAuthorizationProvider(AuthorizationProvider):
"""Implements the OAuth client-credentials flow with caching."""

def __init__(
self,
token_endpoint: str,
client_id: str,
client_secret: str,
scope: Optional[str],
http: urllib3.PoolManager,
) -> None:
self._token_endpoint = token_endpoint
self._client_id = client_id
self._client_secret = client_secret
self._scope = scope
self._http = http
self._lock = threading.Lock()
self._cached: Optional[tuple[str, float]] = None # (token, expires_at_epoch)

def authorization_header(self) -> Optional[str]:
token = self._current_token()
return f"Bearer {token}" if token else None

def _current_token(self) -> Optional[str]:
now = time.time()
cached = self._cached
if not cached or cached[1] - 60 <= now:
with self._lock:
cached = self._cached
if not cached or cached[1] - 60 <= time.time():
self._cached = cached = self._fetch_token()
return cached[0] if cached else None

def _fetch_token(self) -> tuple[str, float]:
payload = {
"grant_type": "client_credentials",
"client_id": self._client_id,
"client_secret": self._client_secret,
}
if self._scope:
payload["scope"] = self._scope

encoded = urlencode(payload)
response = self._http.request(
"POST",
self._token_endpoint,
body=encoded,
headers={"Content-Type": "application/x-www-form-urlencoded"},
timeout=urllib3.Timeout(connect=20.0, read=20.0),
)

if response.status != 200:
raise RuntimeError(
f"OAuth token endpoint returned {response.status}: {response.data.decode('utf-8', errors='ignore')}"
)

try:
document = json.loads(response.data.decode("utf-8"))
except json.JSONDecodeError as error:
raise RuntimeError("OAuth token endpoint returned invalid JSON") from error

token = document.get("access_token")
if not isinstance(token, str) or not token:
raise RuntimeError("OAuth token response missing access_token")

expires_in = document.get("expires_in", 3600)
try:
ttl = float(expires_in)
except (TypeError, ValueError):
ttl = 3600.0
ttl = max(ttl, 60.0)
expires_at = time.time() + ttl
return token, expires_at


class _NoneAuthorizationProvider(AuthorizationProvider):
def authorization_header(self) -> Optional[str]:
return None


def none() -> AuthorizationProvider:
"""Return an AuthorizationProvider that never supplies a header."""

return _NoneAuthorizationProvider()
55 changes: 55 additions & 0 deletions client/python-mcp/polaris_mcp/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#
# 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.
#

"""Shared protocol definitions for the Polaris MCP server."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Dict, Optional, Protocol


JSONDict = Dict[str, Any]


@dataclass(frozen=True)
class ToolExecutionResult:
"""Structured result returned from executing an MCP tool."""

text: str
is_error: bool
metadata: Optional[JSONDict] = None


class McpTool(Protocol):
"""Protocol describing the minimal surface for MCP tools."""

@property
def name(self) -> str: # pragma: no cover - simple accessor
...

@property
def description(self) -> str: # pragma: no cover - simple accessor
...

def input_schema(self) -> JSONDict:
"""Return a JSON schema describing the tool parameters."""

def call(self, arguments: Any) -> ToolExecutionResult:
"""Execute the tool with the provided JSON arguments."""
Loading