← Files Dataiku HeadlessARCHIVED FILE

dataiku_mcp/config/stdio.py

13.8 KB · Nov 27, 2026 · 19:32 UTC

↓ Download file

# Copyright 2026 Dataiku SAS
#
# Licensed 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.

"""Local stdio configuration from environment variables and profile files."""

import atexit
import logging
import os
import ssl
import tempfile
import threading
from pathlib import Path

from pydantic import ValidationError

from .files import read_json_object, write_json_atomic
from .models import DSSInstance, InstanceType, StdioConfig, StdioDSSInstanceConfig


DEFAULT_SETTINGS_PATH = Path.home() / ".dataiku" / "stdio-config.json"

logger = logging.getLogger("dataiku-mcp")

_settings_path: Path | None = None
_settings_lock = threading.Lock()
_config: StdioConfig | None = None
_environment_instances: list[DSSInstance] = []
_current_instance: DSSInstance | None = None


def _resolve_default_settings_path() -> Path:
    cwd_settings_path = Path.cwd() / ".dataiku" / DEFAULT_SETTINGS_PATH.name
    return cwd_settings_path if cwd_settings_path.exists() else DEFAULT_SETTINGS_PATH


def set_settings_path(path: Path | None) -> Path:
    """Select the stdio profile file for this server process."""
    global _config, _current_instance, _environment_instances, _settings_path
    if path is not None:
        _settings_path = path.expanduser()
    else:
        _settings_path = _resolve_default_settings_path()
    _config = None
    _environment_instances = []
    _current_instance = None
    return _settings_path


def get_settings_path() -> Path:
    """Return the profile file selected for this server process."""
    return _settings_path if _settings_path is not None else set_settings_path(None)


def _write_encrypted_rpc_certificate(certificate: str) -> str:
    """Keep a validated PEM certificate available until process shutdown."""
    try:
        ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT).load_verify_locations(
            cadata=certificate
        )
    except (ssl.SSLError, ValueError):
        raise ValueError(
            "Invalid Code Studio DKU_SERVER_CERT: expected a PEM certificate"
        ) from None
    with tempfile.NamedTemporaryFile(
        "w",
        encoding="utf-8",
        prefix="dataiku-rpc-",
        suffix=".pem",
        delete=False,
    ) as certificate_file:
        atexit.register(Path(certificate_file.name).unlink, missing_ok=True)
        certificate_file.write(certificate)
        return certificate_file.name


def _load_instances_from_env_vars() -> list[DSSInstance]:
    """Load the explicit target first, followed by the hosting Code Studio DSS."""
    instances = []
    if os.environ.get("DKU_DSS_URL"):
        no_check_certificate = os.environ.get("DKU_NO_CHECK_CERTIFICATE", "").strip()
        try:
            instance = StdioDSSInstanceConfig.model_validate(
                {
                    "url": os.environ["DKU_DSS_URL"],
                    "api_key": os.environ["DKU_API_KEY"],
                    "instance_type": os.environ["DKU_INSTANCE_TYPE"],
                    "no_check_certificate": (
                        bool(no_check_certificate)
                        and no_check_certificate.lower() != "false"
                    ),
                }
            )
        except KeyError as err:
            raise ValueError(
                f"Missing stdio environment setting: {err.args[0]}"
            ) from None
        except ValidationError as err:
            raise ValueError(f"Invalid stdio environment settings: {err}") from None
        instances.append(
            instance.to_instance(
                name=os.environ.get("DKU_INSTANCE_NAME", "dataiku-from-env"),
                source="environment",
            )
        )

    if os.environ.get("DKU_IS_CODE_STUDIO"):
        if any(instance.name == "dataiku-from-code-studio" for instance in instances):
            raise ValueError(
                "Duplicate environment instance name 'dataiku-from-code-studio': change "
                "DKU_INSTANCE_NAME to distinguish the explicit instance from the Code Studio instance."
            )
        try:
            backend_url = (
                f"{os.environ['DKU_BACKEND_PROTOCOL']}://"
                f"{os.environ['DKU_BACKEND_HOST']}:{os.environ['DKU_BACKEND_PORT']}"
            )
            instance = StdioDSSInstanceConfig.model_validate(
                {
                    "url": backend_url,
                    "api_ticket": os.environ["DKU_API_TICKET"],
                    "instance_type": os.environ["DKU_NODE_TYPE"],
                }
            )
        except KeyError as err:
            raise ValueError(
                f"Missing Code Studio environment setting: {err.args[0]}"
            ) from None
        except ValidationError as err:
            raise ValueError(
                f"Invalid stdio environment settings in Code Studio: {err}"
            ) from None
        certificate = os.environ.get("DKU_SERVER_CERT")
        certificate_path = (
            _write_encrypted_rpc_certificate(certificate) if certificate else None
        )
        instances.append(
            instance.to_instance(
                name="dataiku-from-code-studio",
                source="code-studio-environment",
                encrypted_rpc_cert_path=certificate_path,
            )
        )
    return instances


def _migrate_missing_instance_types(path: Path, document: dict) -> None:
    """Persist the default type for older stdio profiles before validation."""
    # Temporary migration logic; to be deprecated by 0.9.0.
    instances = document.get("dss_instances")
    if not isinstance(instances, dict):
        return
    changed = False
    for instance in instances.values():
        if isinstance(instance, dict) and "instance_type" not in instance:
            instance["instance_type"] = "design"
            changed = True
    if changed:
        write_json_atomic(path, document)


def _load_config() -> StdioConfig:
    path = get_settings_path()
    try:
        document = read_json_object(path, description="Stdio instance configuration")
    except FileNotFoundError:
        return StdioConfig()
    _migrate_missing_instance_types(path, document)
    try:
        return StdioConfig.model_validate(document)
    except ValidationError as err:
        raise ValueError(f"Invalid stdio settings at '{path}': {err}") from None


def _save_config(config: StdioConfig) -> None:
    write_json_atomic(
        get_settings_path(),
        config.model_dump(mode="json", exclude_none=True, exclude_defaults=True),
    )


def _get_config() -> StdioConfig:
    if _config is None:
        raise RuntimeError("Stdio configuration has not been initialized.")
    return _config


def initialize_config() -> None:
    """Load and cache stdio profiles and the active instance."""
    global _config, _current_instance, _environment_instances
    # Resolve the path before loading environment state: path selection resets caches.
    get_settings_path()
    _environment_instances = _load_instances_from_env_vars()
    _config = _load_config()
    if _environment_instances:
        _current_instance = _environment_instances[0]
    elif _config.default_instance:
        _current_instance = _config.dss_instances[_config.default_instance].to_instance(
            _config.default_instance
        )
    else:
        _current_instance = None


def get_instances() -> dict[str, DSSInstance]:
    """Return cached instances, with environment instances taking precedence."""
    instances = {
        name: instance.to_instance(name)
        for name, instance in _get_config().dss_instances.items()
    }
    return instances | {instance.name: instance for instance in _environment_instances}


def get_current_instance() -> DSSInstance | None:
    return _current_instance


def set_current_instance(instance: DSSInstance) -> None:
    global _current_instance
    _current_instance = instance


def get_profile_config() -> StdioConfig:
    """Refresh cached profiles and return a detached manager snapshot."""
    global _config, _current_instance
    with _settings_lock:
        config = _load_config()
        _config = config
        if _current_instance is not None and _current_instance.source == "config":
            _current_instance = get_instances().get(_current_instance.name)
        return config.model_copy(deep=True)


def _require_editable_name(name: str) -> None:
    if any(instance.name == name for instance in _environment_instances):
        raise ValueError("Environment instances must be changed in their environment.")


def save_instance_profile(
    name: str,
    instance: StdioDSSInstanceConfig,
    *,
    original_name: str | None,
    expected_instance: StdioDSSInstanceConfig | None,
    set_default: bool,
    activate: bool,
) -> None:
    """Create or explicitly edit a profile without losing its active/default identity."""
    global _config, _current_instance
    with _settings_lock:
        config = _load_config()
        _require_editable_name(name)
        if original_name is not None:
            _require_editable_name(original_name)
            if (
                original_name not in config.dss_instances
                or config.dss_instances[original_name] != expected_instance
            ):
                raise ValueError(
                    "This instance changed. Reopen the editor and test again."
                )
        if name != original_name and name in config.dss_instances:
            raise ValueError("An instance with this name already exists.")
        if original_name is not None:
            del config.dss_instances[original_name]
        config.dss_instances[name] = instance
        if set_default:
            config.default_instance = name
        elif config.default_instance == original_name:
            config.default_instance = None
        was_current = (
            _current_instance is not None
            and _current_instance.source == "config"
            and _current_instance.name == original_name
        )
        _save_config(config)
        _config = config
        if activate or was_current:
            _current_instance = instance.to_instance(name)


def set_default_instance(name: str) -> None:
    """Choose the saved profile used at startup when no environment target exists."""
    global _config
    with _settings_lock:
        config = _load_config()
        _require_editable_name(name)
        if name not in config.dss_instances:
            raise ValueError("This saved instance no longer exists. Refresh the list.")
        config.default_instance = name
        _save_config(config)
        _config = config


def add_instance_to_config(
    name: str,
    url: str,
    api_key: str,
    *,
    description: str = "",
    instance_type: InstanceType,
    no_check_certificate: bool = False,
    set_default: bool = False,
) -> dict:
    """Add an instance to the resolved local profile file."""
    global _config
    with _settings_lock:
        instance = StdioDSSInstanceConfig(
            url=url,
            api_key=api_key,
            description=description,
            instance_type=instance_type,
            no_check_certificate=no_check_certificate,
        )
        config = _load_config()
        config.dss_instances[name] = instance
        if set_default:
            config.default_instance = name
        _save_config(config)
        _config = config
        return {
            "name": name,
            "url": url,
            "description": description,
            "instance_type": instance.instance_type,
            "path": str(get_settings_path()),
            "default_instance": config.default_instance,
        }


def delete_instance_from_config(
    name: str,
    *,
    replacement: str | None = None,
    expected_instance: StdioDSSInstanceConfig | None = None,
) -> dict:
    """Remove a profile-file instance and update the active/default selection."""
    global _config, _current_instance
    with _settings_lock:
        config = _load_config()
        instances = config.dss_instances
        _require_editable_name(name)
        if name not in instances:
            raise ValueError(
                f"Instance '{name}' not found in config file. Available: {list(instances)}"
            )
        if expected_instance is not None and instances[name] != expected_instance:
            raise ValueError("This instance changed. Review it again before deleting.")
        if replacement is not None:
            _require_editable_name(replacement)
            if replacement == name or replacement not in instances:
                raise ValueError("Choose another saved instance as the replacement.")

        was_current = (
            _current_instance is not None
            and _current_instance.source == "config"
            and _current_instance.name == name
        )
        instances.pop(name)
        environment_names = {instance.name for instance in _environment_instances}
        if config.default_instance == name:
            config.default_instance = replacement or next(
                (name for name in instances if name not in environment_names), None
            )
        _save_config(config)
        _config = config
        if was_current:
            next_name = replacement or config.default_instance
            if next_name in environment_names:
                next_name = None
            _current_instance = (
                instances[next_name].to_instance(next_name) if next_name else None
            )
        return {
            "deleted": name,
            "path": str(get_settings_path()),
            "default_instance": config.default_instance,
            "remaining": list(instances),
        }

SHA-256: 1de4adbc3887895dabd136feebf47391e0885e6863980feefe7c7605ea37ba5a