Skip to content
Merged
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
75 changes: 75 additions & 0 deletions .github/workflows/mcp-server.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#
# 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.
#

# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.
# This workflow will build a Python project with Poetry and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://docs.github.com/en/actions/use-cases-and-examples/building-and-testing/building-and-testing-python

name: MCP Server CI

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

env:
GRADLE_TOS_ACCEPTED: ${{ vars.GRADLE_TOS_ACCEPTED }}
DEVELOCITY_SERVER: ${{ vars.DEVELOCITY_SERVER }}
DEVELOCITY_PROJECT_ID: ${{ vars.DEVELOCITY_PROJECT_ID }}

jobs:
build:

runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]

steps:
- name: Checkout Polaris Tools project
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5

- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@e797f83bcb11b83ae66e0230d6156d7c80228e7c # v6
with:
python-version: ${{ matrix.python-version }}

- name: Install uv
run: |
curl -LsSf https://astral.sh/uv/install.sh | sh
echo "${HOME}/.local/bin" >> "${GITHUB_PATH}"

- name: Sync dependencies
working-directory: mcp-server
run: |
uv sync --extra test --extra dev

- name: Lint
working-directory: mcp-server
run: |
uv run pre-commit run --all-files

- name: Unit Tests
working-directory: mcp-server
run: |
uv run pytest
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ version.txt

# Python venv
venv/
mcp-server/polaris_mcp.egg-info/
mcp-server/polaris_mcp/__pycache__/
mcp-server/polaris_mcp/tools/__pycache__/
mcp-server/tests/__pycache__/

# Maven flatten plugin
.flattened-pom.xml
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,4 @@ There are three tools:
1. [Benchmarks](/benchmarks/README.md): Performance benchmarks for Polaris.
2. [Iceberg Catalog Migrator](/iceberg-catalog-migrator/README.md): A command-line tool to migrate Iceberg tables from one Iceberg catalog to another.
3. [Polaris Synchronizer](/polaris-synchronizer/README.md): A tool to migrate entities from one Polaris instance to another.
4. [Polaris MCP Server](/mcp-server/README.md): A Polaris MCP server implementation.
37 changes: 37 additions & 0 deletions mcp-server/.pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# 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.

repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: trailing-whitespace
files: ^mcp-server/
- id: end-of-file-fixer
files: ^mcp-server/
- id: debug-statements
files: ^mcp-server/
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.12.1
hooks:
# Run the linter.
- id: ruff-check
files: ^mcp-server/
args: [ --fix, --exit-non-zero-on-fix ]
# Run the formatter.
- id: ruff-format
files: ^mcp-server/
91 changes: 91 additions & 0 deletions mcp-server/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
<!--
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

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.

## Prerequisites
- Python 3.10 or later
- [uv](https://docs.astral.sh/uv/) 0.9.7 or later

## Building and Running
Run the following commands from the `mcp-server` directory:
- `uv sync` — install runtime dependencies
- `uv run polaris-mcp` — start the MCP server (stdin/stdout transport)
- `uv sync --extra test --extra dev` — install runtime, test and dev dependencies
- `uv run pytest` — run the test suite
- `uv run pre-commit run --all-files` — lint all files

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-tools/mcp-server",
"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 mcp-server/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"]
135 changes: 135 additions & 0 deletions mcp-server/polaris_mcp/authorization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
#
# 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()
Loading