|
| 1 | +"""Configuration for the osw-mcp server. |
| 2 | +
|
| 3 | +Loads settings from the environment (optionally via a ``.env`` file) and |
| 4 | +validates that connection credentials are present *before* the server ever |
| 5 | +touches the osw library. This matters because ``OswExpress`` / ``SmwSparqlClient`` |
| 6 | +fall back to an interactive ``input()`` / ``getpass`` prompt when credentials are |
| 7 | +missing, which would hang a stdio MCP server (it would read the JSON-RPC stream |
| 8 | +as a password). We therefore fail fast with a clear error instead. |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +import os |
| 14 | +from dataclasses import dataclass, field |
| 15 | +from typing import Optional |
| 16 | + |
| 17 | +# python-dotenv is part of the [mcp] extra |
| 18 | +from dotenv import load_dotenv |
| 19 | + |
| 20 | +_TRUTHY = {"1", "true", "yes", "on"} |
| 21 | + |
| 22 | +# Environment variable names (OSL_* are accepted as fallbacks, matching osw). |
| 23 | +ENV_DOMAIN = ("OSW_DOMAIN", "OSL_DOMAIN") |
| 24 | +ENV_USERNAME = ("OSW_USERNAME", "OSL_USERNAME") |
| 25 | +ENV_PASSWORD = ("OSW_PASSWORD", "OSL_PASSWORD") |
| 26 | + |
| 27 | + |
| 28 | +def _first_env(names: tuple[str, ...]) -> Optional[str]: |
| 29 | + """Return the first non-empty environment value among ``names``.""" |
| 30 | + for name in names: |
| 31 | + value = os.getenv(name) |
| 32 | + if value: |
| 33 | + return value |
| 34 | + return None |
| 35 | + |
| 36 | + |
| 37 | +@dataclass(frozen=True) |
| 38 | +class Settings: |
| 39 | + """Resolved, validated server settings.""" |
| 40 | + |
| 41 | + domain: str |
| 42 | + username: str |
| 43 | + # kept only to build the SPARQL client; never returned by any tool |
| 44 | + password: str = field(repr=False) |
| 45 | + sparql_endpoint: Optional[str] = None |
| 46 | + read_only: bool = False |
| 47 | + state_dir: Optional[str] = None |
| 48 | + max_results: int = 100 |
| 49 | + max_chars: int = 100_000 |
| 50 | + |
| 51 | + def redacted(self) -> dict: |
| 52 | + """A dict view safe for logging / the status tool (no password).""" |
| 53 | + return { |
| 54 | + "domain": self.domain, |
| 55 | + "username": self.username, |
| 56 | + "read_only": self.read_only, |
| 57 | + "sparql_endpoint_configured": bool(self.sparql_endpoint), |
| 58 | + } |
| 59 | + |
| 60 | + |
| 61 | +def _int_env(name: str, default: int) -> int: |
| 62 | + raw = os.getenv(name) |
| 63 | + if raw is None or raw.strip() == "": |
| 64 | + return default |
| 65 | + try: |
| 66 | + return int(raw) |
| 67 | + except ValueError: |
| 68 | + raise RuntimeError( |
| 69 | + f"Environment variable {name}={raw!r} is not a valid integer." |
| 70 | + ) |
| 71 | + |
| 72 | + |
| 73 | +def load() -> Settings: |
| 74 | + """Load and validate settings from the environment. |
| 75 | +
|
| 76 | + Loads a ``.env`` file first: the path in ``OSW_MCP_ENV_FILE`` if set, |
| 77 | + otherwise dotenv's default search from the current working directory upward. |
| 78 | +
|
| 79 | + Raises |
| 80 | + ------ |
| 81 | + RuntimeError |
| 82 | + If any of domain / username / password is missing, so the osw |
| 83 | + interactive credential prompt is never reached. |
| 84 | + """ |
| 85 | + env_file = os.getenv("OSW_MCP_ENV_FILE") |
| 86 | + if env_file: |
| 87 | + load_dotenv(env_file) |
| 88 | + else: |
| 89 | + load_dotenv() |
| 90 | + |
| 91 | + domain = _first_env(ENV_DOMAIN) |
| 92 | + username = _first_env(ENV_USERNAME) |
| 93 | + password = _first_env(ENV_PASSWORD) |
| 94 | + |
| 95 | + missing = [ |
| 96 | + names[0] |
| 97 | + for names, value in ( |
| 98 | + (ENV_DOMAIN, domain), |
| 99 | + (ENV_USERNAME, username), |
| 100 | + (ENV_PASSWORD, password), |
| 101 | + ) |
| 102 | + if not value |
| 103 | + ] |
| 104 | + if missing: |
| 105 | + raise RuntimeError( |
| 106 | + "Missing required OSW credential environment variables: " |
| 107 | + + ", ".join(missing) |
| 108 | + + ". Set them in your environment or a .env file " |
| 109 | + "(pointed to by OSW_MCP_ENV_FILE). The server refuses to start " |
| 110 | + "without them to avoid an interactive credential prompt that would " |
| 111 | + "hang the stdio transport." |
| 112 | + ) |
| 113 | + |
| 114 | + return Settings( |
| 115 | + domain=domain, |
| 116 | + username=username, |
| 117 | + password=password, |
| 118 | + sparql_endpoint=os.getenv("OSW_SPARQL_ENDPOINT") or None, |
| 119 | + read_only=(os.getenv("OSW_MCP_READ_ONLY", "").lower() in _TRUTHY), |
| 120 | + state_dir=os.getenv("OSW_MCP_STATE_DIR") or None, |
| 121 | + max_results=_int_env("OSW_MCP_MAX_RESULTS", 100), |
| 122 | + max_chars=_int_env("OSW_MCP_MAX_CHARS", 100_000), |
| 123 | + ) |
| 124 | + |
| 125 | + |
| 126 | +_settings: Optional[Settings] = None |
| 127 | + |
| 128 | + |
| 129 | +def get_settings() -> Settings: |
| 130 | + """Return cached settings, loading (and validating) them on first use.""" |
| 131 | + global _settings |
| 132 | + if _settings is None: |
| 133 | + _settings = load() |
| 134 | + return _settings |
| 135 | + |
| 136 | + |
| 137 | +def reset() -> None: |
| 138 | + """Drop cached settings (used by tests).""" |
| 139 | + global _settings |
| 140 | + _settings = None |
0 commit comments