ectype-mcp 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ectype_mcp/__init__.py +3 -0
- ectype_mcp/__main__.py +27 -0
- ectype_mcp/config.py +147 -0
- ectype_mcp/engine.py +377 -0
- ectype_mcp/errors.py +66 -0
- ectype_mcp/py.typed +0 -0
- ectype_mcp/results.py +43 -0
- ectype_mcp/sandbox.py +426 -0
- ectype_mcp/server.py +95 -0
- ectype_mcp/spec.py +1399 -0
- ectype_mcp/summaries.py +542 -0
- ectype_mcp/tools.py +774 -0
- ectype_mcp-0.1.0.dist-info/METADATA +556 -0
- ectype_mcp-0.1.0.dist-info/RECORD +18 -0
- ectype_mcp-0.1.0.dist-info/WHEEL +4 -0
- ectype_mcp-0.1.0.dist-info/entry_points.txt +2 -0
- ectype_mcp-0.1.0.dist-info/licenses/LICENSE +192 -0
- ectype_mcp-0.1.0.dist-info/licenses/NOTICE +5 -0
ectype_mcp/__init__.py
ADDED
ectype_mcp/__main__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Command-line entry point: ``ectype-mcp`` / ``python -m ectype_mcp``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
|
|
9
|
+
from ectype_mcp.config import parse_args
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
13
|
+
settings = parse_args(argv)
|
|
14
|
+
# stdout carries the protocol; logs go to stderr only.
|
|
15
|
+
logging.basicConfig(
|
|
16
|
+
stream=sys.stderr,
|
|
17
|
+
level=settings.log_level,
|
|
18
|
+
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
|
19
|
+
)
|
|
20
|
+
from ectype_mcp.server import build_server
|
|
21
|
+
|
|
22
|
+
build_server(settings).run("stdio")
|
|
23
|
+
return 0
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
if __name__ == "__main__":
|
|
27
|
+
raise SystemExit(main())
|
ectype_mcp/config.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Server configuration: limits, settings and command-line parsing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from ectype_mcp import __version__
|
|
12
|
+
|
|
13
|
+
__all__ = ["Limits", "Settings", "parse_args"]
|
|
14
|
+
|
|
15
|
+
_MB = 1024 * 1024
|
|
16
|
+
_LOG_LEVELS = ("DEBUG", "INFO", "WARNING", "ERROR")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class Limits:
|
|
21
|
+
max_rows: int = 1_000_000 # rows per call
|
|
22
|
+
max_cells: int = 50_000_000 # rows x columns per call
|
|
23
|
+
max_input_bytes: int = 256 * _MB # a table file we read
|
|
24
|
+
max_fingerprint_bytes: int = 64 * _MB # a .dfp file we load
|
|
25
|
+
max_spec_bytes: int = 256 * 1024 # a spec (inline JSON or spec file)
|
|
26
|
+
max_spec_columns: int = 500
|
|
27
|
+
max_result_chars: int = 16_000 # one tool result, serialised
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class Settings:
|
|
32
|
+
roots: tuple[Path, ...] # absolute, resolved, existing directories; never empty
|
|
33
|
+
limits: Limits = field(default_factory=Limits)
|
|
34
|
+
log_level: str = "WARNING"
|
|
35
|
+
|
|
36
|
+
def __post_init__(self) -> None:
|
|
37
|
+
if not self.roots:
|
|
38
|
+
raise ValueError("Settings.roots must not be empty")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _positive_int(text: str) -> int:
|
|
42
|
+
try:
|
|
43
|
+
value = int(text)
|
|
44
|
+
except ValueError:
|
|
45
|
+
raise argparse.ArgumentTypeError(f"expected a positive whole number, got {text!r}") from None
|
|
46
|
+
if value <= 0:
|
|
47
|
+
raise argparse.ArgumentTypeError(f"expected a positive whole number, got {text!r}")
|
|
48
|
+
return value
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
52
|
+
defaults = Limits()
|
|
53
|
+
parser = argparse.ArgumentParser(
|
|
54
|
+
prog="ectype-mcp",
|
|
55
|
+
description=(
|
|
56
|
+
"An MCP server for Ectype: create and check realistic synthetic tables locally. "
|
|
57
|
+
"It speaks the Model Context Protocol over stdio (stdin/stdout) and opens no port."
|
|
58
|
+
),
|
|
59
|
+
epilog=(
|
|
60
|
+
"All file access is confined to the --root folders (default: the current working "
|
|
61
|
+
"directory); relative paths resolve against the first root. Logs go to stderr."
|
|
62
|
+
),
|
|
63
|
+
)
|
|
64
|
+
parser.add_argument(
|
|
65
|
+
"--root",
|
|
66
|
+
dest="roots",
|
|
67
|
+
action="append",
|
|
68
|
+
metavar="DIR",
|
|
69
|
+
help="a folder the server may read and write (repeatable; default: the current directory)",
|
|
70
|
+
)
|
|
71
|
+
parser.add_argument(
|
|
72
|
+
"--max-rows",
|
|
73
|
+
type=_positive_int,
|
|
74
|
+
default=defaults.max_rows,
|
|
75
|
+
metavar="N",
|
|
76
|
+
help=f"most rows per call (default: {defaults.max_rows:,})",
|
|
77
|
+
)
|
|
78
|
+
parser.add_argument(
|
|
79
|
+
"--max-cells",
|
|
80
|
+
type=_positive_int,
|
|
81
|
+
default=defaults.max_cells,
|
|
82
|
+
metavar="N",
|
|
83
|
+
help=f"most cells (rows x columns) per call (default: {defaults.max_cells:,})",
|
|
84
|
+
)
|
|
85
|
+
parser.add_argument(
|
|
86
|
+
"--max-input-mb",
|
|
87
|
+
type=_positive_int,
|
|
88
|
+
default=defaults.max_input_bytes // _MB,
|
|
89
|
+
metavar="N",
|
|
90
|
+
help=f"largest table file read, in MB (default: {defaults.max_input_bytes // _MB})",
|
|
91
|
+
)
|
|
92
|
+
parser.add_argument(
|
|
93
|
+
"--max-fingerprint-mb",
|
|
94
|
+
type=_positive_int,
|
|
95
|
+
default=defaults.max_fingerprint_bytes // _MB,
|
|
96
|
+
metavar="N",
|
|
97
|
+
help=(
|
|
98
|
+
"largest fingerprint (.dfp) file loaded, in MB "
|
|
99
|
+
f"(default: {defaults.max_fingerprint_bytes // _MB})"
|
|
100
|
+
),
|
|
101
|
+
)
|
|
102
|
+
parser.add_argument(
|
|
103
|
+
"--log-level",
|
|
104
|
+
choices=_LOG_LEVELS,
|
|
105
|
+
default="WARNING",
|
|
106
|
+
help="stderr log level (default: WARNING)",
|
|
107
|
+
)
|
|
108
|
+
parser.add_argument("--version", action="version", version=f"ectype-mcp {__version__}")
|
|
109
|
+
return parser
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _resolve_roots(parser: argparse.ArgumentParser, raw_roots: Sequence[str] | None) -> tuple[Path, ...]:
|
|
113
|
+
if not raw_roots:
|
|
114
|
+
return (Path.cwd().resolve(),)
|
|
115
|
+
roots: list[Path] = []
|
|
116
|
+
seen: set[str] = set()
|
|
117
|
+
for raw in raw_roots:
|
|
118
|
+
if not raw.strip():
|
|
119
|
+
parser.error("--root must not be empty")
|
|
120
|
+
try:
|
|
121
|
+
path = Path(raw).resolve()
|
|
122
|
+
except (OSError, RuntimeError, ValueError) as exc:
|
|
123
|
+
parser.error(f"--root '{raw}' could not be resolved: {exc}")
|
|
124
|
+
if not path.exists():
|
|
125
|
+
parser.error(f"--root '{raw}' does not exist; create the folder or pass another one")
|
|
126
|
+
if not path.is_dir():
|
|
127
|
+
parser.error(f"--root '{raw}' is not a folder; pass a directory")
|
|
128
|
+
key = os.path.normcase(str(path))
|
|
129
|
+
if key in seen:
|
|
130
|
+
continue
|
|
131
|
+
seen.add(key)
|
|
132
|
+
roots.append(path)
|
|
133
|
+
return tuple(roots)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def parse_args(argv: Sequence[str] | None = None) -> Settings:
|
|
137
|
+
"""Parse command-line arguments into :class:`Settings` (exits with status 2 on errors)."""
|
|
138
|
+
parser = _build_parser()
|
|
139
|
+
ns = parser.parse_args(None if argv is None else list(argv))
|
|
140
|
+
roots = _resolve_roots(parser, ns.roots)
|
|
141
|
+
limits = Limits(
|
|
142
|
+
max_rows=ns.max_rows,
|
|
143
|
+
max_cells=ns.max_cells,
|
|
144
|
+
max_input_bytes=ns.max_input_mb * _MB,
|
|
145
|
+
max_fingerprint_bytes=ns.max_fingerprint_mb * _MB,
|
|
146
|
+
)
|
|
147
|
+
return Settings(roots=roots, limits=limits, log_level=ns.log_level)
|
ectype_mcp/engine.py
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
"""The engine adapter: the only module of ectype-mcp that imports ``ectype``.
|
|
2
|
+
|
|
3
|
+
Everything the server asks of the Ectype engine goes through the functions here, and they use
|
|
4
|
+
only the engine's public API: names in ``ectype.__all__`` plus the documented
|
|
5
|
+
``ectype.authoring.build_from_spec``. Attribute access on returned objects (``fp.manifest``,
|
|
6
|
+
``report.sections`` ...) is pinned by ``tests/test_engine_contract.py``, so an engine change that
|
|
7
|
+
breaks the server fails one file and one test, loudly.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
import time
|
|
14
|
+
from collections.abc import Mapping, Sequence
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Literal, cast
|
|
18
|
+
|
|
19
|
+
import ectype
|
|
20
|
+
import polars as pl
|
|
21
|
+
from ectype.authoring import build_from_spec
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"ENGINE_VERSION",
|
|
25
|
+
"FORMAT_VERSION",
|
|
26
|
+
"SUPPORTED_ENGINE",
|
|
27
|
+
"DriftReport",
|
|
28
|
+
"EngineFailure",
|
|
29
|
+
"Fingerprint",
|
|
30
|
+
"GenerationStats",
|
|
31
|
+
"ValidationReport",
|
|
32
|
+
"author",
|
|
33
|
+
"authored_spec",
|
|
34
|
+
"column_count",
|
|
35
|
+
"compare",
|
|
36
|
+
"engine_supported",
|
|
37
|
+
"error_message",
|
|
38
|
+
"generate",
|
|
39
|
+
"generate_to",
|
|
40
|
+
"is_supported_engine",
|
|
41
|
+
"load_fingerprint",
|
|
42
|
+
"origin",
|
|
43
|
+
"output_columns",
|
|
44
|
+
"output_dtypes",
|
|
45
|
+
"profile",
|
|
46
|
+
"read_table",
|
|
47
|
+
"rule_count",
|
|
48
|
+
"save_fingerprint",
|
|
49
|
+
"targets_count",
|
|
50
|
+
"validate",
|
|
51
|
+
"write_table",
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
ENGINE_VERSION: str = ectype.__version__
|
|
55
|
+
FORMAT_VERSION: str = ectype.FORMAT_VERSION
|
|
56
|
+
SUPPORTED_ENGINE: str = ">=0.1.0,<0.3"
|
|
57
|
+
|
|
58
|
+
Fingerprint = ectype.Fingerprint
|
|
59
|
+
ValidationReport = ectype.ValidationReport
|
|
60
|
+
DriftReport = ectype.DriftReport
|
|
61
|
+
EngineFailure = ectype.EctypeError
|
|
62
|
+
|
|
63
|
+
_MESSAGE_LIMIT = 1500
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def is_supported_engine(version: str = ENGINE_VERSION) -> bool:
|
|
67
|
+
"""True when ``version`` lies in :data:`SUPPORTED_ENGINE` (``>=0.1.0,<0.3``)."""
|
|
68
|
+
m = re.match(r"(\d+)\.(\d+)\.(\d+)", version)
|
|
69
|
+
if m is None:
|
|
70
|
+
return False
|
|
71
|
+
parts = tuple(int(x) for x in m.groups())
|
|
72
|
+
return (0, 1, 0) <= parts < (0, 3, 0)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def engine_supported() -> bool:
|
|
76
|
+
"""True when the installed engine (:data:`ENGINE_VERSION`) is inside SUPPORTED_ENGINE."""
|
|
77
|
+
return is_supported_engine(ENGINE_VERSION)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def rule_count(fp: Fingerprint) -> int:
|
|
81
|
+
"""Number of confirmed hard constraints."""
|
|
82
|
+
return sum(1 for c in fp.manifest.constraints.confirmed if c.severity.value == "hard")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
# ---------------------------------------------------------------------------------------------
|
|
86
|
+
# Fingerprints
|
|
87
|
+
# ---------------------------------------------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def author(spec: Mapping[str, Any]) -> Fingerprint:
|
|
91
|
+
"""Build a fingerprint from an authoring spec (no data)."""
|
|
92
|
+
return build_from_spec(spec)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def profile(
|
|
96
|
+
df: pl.DataFrame,
|
|
97
|
+
*,
|
|
98
|
+
name: str,
|
|
99
|
+
policy: str = "standard",
|
|
100
|
+
joint: str = "gaussian_copula",
|
|
101
|
+
constraints: Sequence[str] = (),
|
|
102
|
+
derived: Mapping[str, str] | None = None,
|
|
103
|
+
overrides: Mapping[str, Mapping[str, str]] | None = None,
|
|
104
|
+
) -> Fingerprint:
|
|
105
|
+
"""Fit a fingerprint to a real table."""
|
|
106
|
+
profiler = ectype.Profiler(
|
|
107
|
+
policy=policy,
|
|
108
|
+
joint=joint,
|
|
109
|
+
name=name,
|
|
110
|
+
constraints=list(constraints) or None,
|
|
111
|
+
derived=dict(derived) if derived else None,
|
|
112
|
+
overrides={k: dict(v) for k, v in overrides.items()} if overrides else None,
|
|
113
|
+
)
|
|
114
|
+
return profiler.fit(df)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def read_table(path: Path) -> pl.DataFrame:
|
|
118
|
+
"""Read a table file (format from the extension). Parser errors are not engine errors."""
|
|
119
|
+
return cast(pl.DataFrame, ectype.read_table(str(path)))
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def load_fingerprint(path: Path) -> Fingerprint:
|
|
123
|
+
"""Load a ``.dfp`` with the engine's full integrity checks."""
|
|
124
|
+
return ectype.load(str(path))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def save_fingerprint(fp: Fingerprint, path: Path) -> None:
|
|
128
|
+
"""Write a deterministic ``.dfp``."""
|
|
129
|
+
fp.save(path)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def origin(fp: Fingerprint) -> Literal["authored", "fitted"]:
|
|
133
|
+
"""``authored`` for a fingerprint built from a spec (no real data), else ``fitted``."""
|
|
134
|
+
config = fp.manifest.provenance.config
|
|
135
|
+
return "authored" if isinstance(config, Mapping) and config.get("mode") == "schema_driven" \
|
|
136
|
+
else "fitted"
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def authored_spec(fp: Fingerprint) -> dict[str, Any] | None:
|
|
140
|
+
"""The normalised spec stored in an authored fingerprint, else ``None``."""
|
|
141
|
+
if origin(fp) != "authored":
|
|
142
|
+
return None
|
|
143
|
+
spec = fp.manifest.provenance.config.get("spec")
|
|
144
|
+
return dict(spec) if isinstance(spec, Mapping) else None
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def output_columns(fp: Fingerprint) -> list[str]:
|
|
148
|
+
"""The columns a generated table has, in order (excluded columns are left out)."""
|
|
149
|
+
m = fp.manifest
|
|
150
|
+
kept = {c.name for c in m.columns if c.role.value != "excluded"}
|
|
151
|
+
order = [c for c in m.model.column_order if c in kept]
|
|
152
|
+
order += [c.name for c in m.columns if c.name in kept and c.name not in order]
|
|
153
|
+
# a derived column that is new to the source has no ColumnSchema and is not in
|
|
154
|
+
# column_order: the engine appends it to the output in declaration order
|
|
155
|
+
order += [d.column for d in m.model.derived if d.column not in order]
|
|
156
|
+
return order
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def output_dtypes(fp: Fingerprint) -> dict[str, str]:
|
|
160
|
+
"""Output column -> manifest physical dtype string, in output order.
|
|
161
|
+
|
|
162
|
+
A derived column that is new to the source has no ColumnSchema; its dtype is then read from
|
|
163
|
+
a small generated sample (only in that case).
|
|
164
|
+
"""
|
|
165
|
+
known = {c.name: str(c.physical_dtype) for c in fp.manifest.columns}
|
|
166
|
+
names = output_columns(fp)
|
|
167
|
+
missing = [n for n in names if n not in known]
|
|
168
|
+
if missing:
|
|
169
|
+
sample = ectype.Generator(fp).generate(20, seed=0)
|
|
170
|
+
known.update({n: str(sample.schema[n]) for n in missing if n in sample.columns})
|
|
171
|
+
return {n: known.get(n, "String") for n in names}
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def column_count(fp: Fingerprint) -> int:
|
|
175
|
+
"""Number of output columns."""
|
|
176
|
+
return len(output_columns(fp))
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
# ---------------------------------------------------------------------------------------------
|
|
180
|
+
# Generation, validation, drift
|
|
181
|
+
# ---------------------------------------------------------------------------------------------
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@dataclass(frozen=True)
|
|
185
|
+
class GenerationStats:
|
|
186
|
+
"""What a generation run achieved."""
|
|
187
|
+
|
|
188
|
+
rows: int
|
|
189
|
+
seed: int
|
|
190
|
+
acceptance_rate: float # share of drawn candidate rows that passed the rules (1.0 = none redrawn)
|
|
191
|
+
rule_rejections: dict[str, int] = field(default_factory=dict) # constraint id -> rows rejected
|
|
192
|
+
notes: list[str] = field(default_factory=list)
|
|
193
|
+
seconds: float = 0.0
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def generate_to(
|
|
197
|
+
fp: Fingerprint, path: Path, *, rows: int, seed: int, fmt: Literal["csv", "parquet"]
|
|
198
|
+
) -> GenerationStats:
|
|
199
|
+
"""Stream ``rows`` rows to ``path`` (CSV or Parquet). Same seed, same file."""
|
|
200
|
+
started = time.perf_counter()
|
|
201
|
+
manifest = ectype.Generator(fp).generate_to(path, rows, seed=seed, format=fmt)
|
|
202
|
+
return _stats(manifest, time.perf_counter() - started)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def generate(fp: Fingerprint, *, rows: int, seed: int) -> tuple[pl.DataFrame, GenerationStats]:
|
|
206
|
+
"""Generate exactly ``rows`` rows in memory. Same seed, same frame."""
|
|
207
|
+
started = time.perf_counter()
|
|
208
|
+
gen = ectype.Generator(fp)
|
|
209
|
+
df = gen.generate(rows, seed=seed)
|
|
210
|
+
manifest = gen.last_manifest
|
|
211
|
+
if manifest is None: # pragma: no cover - the engine always sets it after generate
|
|
212
|
+
raise RuntimeError("the engine did not record a generation manifest")
|
|
213
|
+
return df, _stats(manifest, time.perf_counter() - started)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def write_table(df: pl.DataFrame, path: Path, *, fmt: Literal["csv", "parquet"]) -> None:
|
|
217
|
+
"""Write a frame as CSV or Parquet."""
|
|
218
|
+
ectype.write_table(df, path, format=fmt)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def targets_count(fp: Fingerprint) -> tuple[int, int]:
|
|
222
|
+
"""(calibration, sealed) target counts recorded in the manifest."""
|
|
223
|
+
t = fp.manifest.targets
|
|
224
|
+
return int(t.n_calibration), int(t.n_sealed)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _stats(manifest: Any, elapsed: float) -> GenerationStats:
|
|
228
|
+
rejections = {str(cid): int(stats.violations) for cid, stats in manifest.constraints.items()}
|
|
229
|
+
return GenerationStats(
|
|
230
|
+
rows=int(manifest.n_rows),
|
|
231
|
+
seed=int(manifest.seed),
|
|
232
|
+
acceptance_rate=float(manifest.acceptance_rate),
|
|
233
|
+
rule_rejections=rejections,
|
|
234
|
+
notes=[str(n) for n in manifest.notes],
|
|
235
|
+
seconds=float(manifest.wall_time_s or elapsed),
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def validate(
|
|
240
|
+
fp: Fingerprint,
|
|
241
|
+
table: pl.DataFrame,
|
|
242
|
+
*,
|
|
243
|
+
holdout: pl.DataFrame | None = None,
|
|
244
|
+
sensitivity: str = "standard",
|
|
245
|
+
) -> ValidationReport:
|
|
246
|
+
"""Validate a table against a fingerprint (optionally with real holdout rows)."""
|
|
247
|
+
return ectype.validate(fp, table, holdout=holdout, sensitivity=sensitivity)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def compare(a: Fingerprint, b: Fingerprint, *, sensitivity: str = "standard") -> DriftReport:
|
|
251
|
+
"""Drift of ``b`` (candidate) against ``a`` (reference), from the fingerprints alone."""
|
|
252
|
+
return ectype.compare(a, b, sensitivity=sensitivity)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
# ---------------------------------------------------------------------------------------------
|
|
256
|
+
# Engine errors -> one actionable message
|
|
257
|
+
# ---------------------------------------------------------------------------------------------
|
|
258
|
+
|
|
259
|
+
# Real-data rule (read from the engine source, ectype 0.1.0):
|
|
260
|
+
#
|
|
261
|
+
# * PolicyError messages name the policy argument and the known policies; no data.
|
|
262
|
+
# * ProfilingError messages name columns, dtypes, row counts and override fields. A few embed
|
|
263
|
+
# text we cannot vouch for (``invalid override ...: {pydantic error}`` echoes the override
|
|
264
|
+
# value; the entity-group messages embed detector reasons). Only the templates listed in
|
|
265
|
+
# _SAFE_PROFILING below are kept; any other ProfilingError gets the generic message.
|
|
266
|
+
# * ExpressionError / ConstraintError raised while profiling come from the expressions the
|
|
267
|
+
# caller passed (constraints, derived). Their first line names the offending token or column;
|
|
268
|
+
# the following lines echo the whole expression with a caret. The profiler also writes
|
|
269
|
+
# expressions of its own from the data (computed columns carry category labels and cut
|
|
270
|
+
# points), so if one of those ever failed the echo would quote cell values: with real data we
|
|
271
|
+
# keep only the first line, clipped, and never the echo.
|
|
272
|
+
# * Every other engine error on a real-data path (GenerationError, FingerprintError,
|
|
273
|
+
# ScenarioError ...) is not expected there and gets the generic message.
|
|
274
|
+
# * Non-engine exceptions (parser errors from reading a table, which do quote cells) return
|
|
275
|
+
# None: the caller treats them as unreadable input or internal errors.
|
|
276
|
+
_SAFE_PROFILING = (
|
|
277
|
+
re.compile(r"^cannot fit a fingerprint to (an empty table|a table with \d+ row\(s\))"),
|
|
278
|
+
re.compile(r"^cannot profile an empty frame \(shape \(\d+, \d+\)\)$"),
|
|
279
|
+
re.compile(r"^column '[^']*' has no non-null values to model$"),
|
|
280
|
+
re.compile(r"^override for unknown column '[^']*'; columns are \[.*\]$"),
|
|
281
|
+
re.compile(r"^override for '[^']*' must be a dict, got \w+$"),
|
|
282
|
+
re.compile(r"^override for '[^']*' has unknown or forbidden fields \[.*\]; allowed: \[.*\]$"),
|
|
283
|
+
re.compile(r"^overrides must be a dict of column name -> dict of fields$"),
|
|
284
|
+
re.compile(r"^invalid override for column '[^']*': (a|the role|an?) [^:]*$"),
|
|
285
|
+
re.compile(r"^cannot pseudonymise column '[^']*': "),
|
|
286
|
+
re.compile(r"^column '[^']*' (\(\w+\) )?cannot have the role '(pseudonym|reference)'"),
|
|
287
|
+
re.compile(r"^duplicate column names: \[.*\]$"),
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
_GENERIC_REAL = "{label} Details are withheld because they can quote cell values of your table."
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _label(exc: BaseException) -> str:
|
|
294
|
+
kind = type(exc).__name__
|
|
295
|
+
if kind == "AuthoringError":
|
|
296
|
+
return "Spec error:"
|
|
297
|
+
if isinstance(exc, ectype.ExpressionError):
|
|
298
|
+
return "Expression error:"
|
|
299
|
+
if isinstance(exc, ectype.ConstraintError):
|
|
300
|
+
return "Rule error:"
|
|
301
|
+
if isinstance(exc, ectype.GenerationError):
|
|
302
|
+
return "Generation failed:"
|
|
303
|
+
if isinstance(exc, ectype.VersionError):
|
|
304
|
+
return "Unsupported fingerprint version:"
|
|
305
|
+
if isinstance(exc, ectype.FingerprintError):
|
|
306
|
+
return "Not a valid fingerprint:"
|
|
307
|
+
if isinstance(exc, ectype.PolicyError):
|
|
308
|
+
return "Policy error:"
|
|
309
|
+
if isinstance(exc, ectype.ProfilingError):
|
|
310
|
+
return "Profiling failed:"
|
|
311
|
+
if isinstance(exc, ectype.ScenarioError):
|
|
312
|
+
return "Scenario error:"
|
|
313
|
+
return "Engine error:"
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _fix(exc: BaseException, text: str) -> str:
|
|
317
|
+
"""The obvious next step for a known failure, or ''."""
|
|
318
|
+
if "rejection rounds" in text and "acceptance rate" in text:
|
|
319
|
+
return ("The rules reject almost every drawn row; loosen or remove the rule named "
|
|
320
|
+
"above, or check that it agrees with the column's range.")
|
|
321
|
+
if "contradictory correlation" in text:
|
|
322
|
+
return "Weaken or remove one of the conflicting correlations named above."
|
|
323
|
+
if isinstance(exc, ectype.VersionError):
|
|
324
|
+
return (f"This engine (ectype {ENGINE_VERSION}) reads fingerprint format "
|
|
325
|
+
f"{FORMAT_VERSION}; re-create the fingerprint with this engine.")
|
|
326
|
+
if isinstance(exc, ectype.FingerprintError):
|
|
327
|
+
if "not found" in text:
|
|
328
|
+
return "Check the path."
|
|
329
|
+
return ("The file is not a valid .dfp or was changed after it was written; re-create "
|
|
330
|
+
"it with profile_table or create_table_from_spec.")
|
|
331
|
+
if isinstance(exc, ectype.ExpressionError) or (
|
|
332
|
+
not isinstance(exc, ectype.ProfilingError) and "unknown column" in text):
|
|
333
|
+
return "Fix the expression: use column names of the table and the documented functions."
|
|
334
|
+
return ""
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _flat(text: str) -> str:
|
|
338
|
+
return " ".join(text.split())
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _clip(text: str, limit: int = _MESSAGE_LIMIT) -> str:
|
|
342
|
+
return text if len(text) <= limit else text[: limit - 1].rstrip() + "…"
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def error_message(exc: BaseException, *, real_data: bool) -> str | None:
|
|
346
|
+
"""One actionable message for an engine exception, or ``None`` for any other exception.
|
|
347
|
+
|
|
348
|
+
``real_data=True`` when the error arose while reading or profiling a user's real table: the
|
|
349
|
+
message is then built so that it cannot quote cell values (see the rules above).
|
|
350
|
+
"""
|
|
351
|
+
if not isinstance(exc, ectype.EctypeError):
|
|
352
|
+
return None
|
|
353
|
+
label = _label(exc)
|
|
354
|
+
raw = str(exc)
|
|
355
|
+
if real_data:
|
|
356
|
+
first = raw.strip().splitlines()[0].strip() if raw.strip() else ""
|
|
357
|
+
if isinstance(exc, ectype.PolicyError):
|
|
358
|
+
body = _flat(raw)
|
|
359
|
+
elif isinstance(exc, ectype.ProfilingError) and any(p.search(first)
|
|
360
|
+
for p in _SAFE_PROFILING):
|
|
361
|
+
body = first
|
|
362
|
+
elif isinstance(exc, (ectype.ExpressionError, ectype.ConstraintError)):
|
|
363
|
+
body = _clip(re.sub(r"\s*\(at position \d+\)\s*$", "", first), 300)
|
|
364
|
+
body += " (the expression itself is not repeated)"
|
|
365
|
+
else:
|
|
366
|
+
generic = _GENERIC_REAL.format(label=f"{label[:-1]} ({type(exc).__name__}).")
|
|
367
|
+
fix = _fix(exc, "") # fixes that do not depend on the message text are safe
|
|
368
|
+
return generic + (f" {fix}" if fix else "")
|
|
369
|
+
fix = _fix(exc, body)
|
|
370
|
+
return _clip(f"{label} {body}" + (f" {fix}" if fix else ""))
|
|
371
|
+
body = raw.strip() or type(exc).__name__
|
|
372
|
+
# keep the expression echo and caret on their own lines (they point at the mistake)
|
|
373
|
+
lines = [ln.rstrip() for ln in body.splitlines() if ln.strip()]
|
|
374
|
+
body = lines[0] if len(lines) == 1 else "\n".join([lines[0], *lines[1:3]])
|
|
375
|
+
fix = _fix(exc, raw)
|
|
376
|
+
return _clip(f"{label} {body}" + (f"\n{fix}" if fix and "\n" in body else
|
|
377
|
+
f" {fix}" if fix else ""))
|
ectype_mcp/errors.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""User-facing error types and message helpers.
|
|
2
|
+
|
|
3
|
+
Every error a model can act on is a :class:`UserFacingError`. Its message is safe to show (it never
|
|
4
|
+
quotes cell values) and says what is wrong, then what to do. This module is engine-agnostic: it
|
|
5
|
+
imports neither ``ectype`` nor ``mcp``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"EngineError",
|
|
12
|
+
"InputError",
|
|
13
|
+
"LimitError",
|
|
14
|
+
"PathError",
|
|
15
|
+
"SpecError",
|
|
16
|
+
"UserFacingError",
|
|
17
|
+
"clip",
|
|
18
|
+
"unreadable_table",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class UserFacingError(Exception):
|
|
23
|
+
"""Message is safe and useful to show to the model: what is wrong, then what to do."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class PathError(UserFacingError):
|
|
27
|
+
"""A path is outside the allowed roots, missing, of the wrong kind, or already exists."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class LimitError(UserFacingError):
|
|
31
|
+
"""A request or file is over a configured limit."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class InputError(UserFacingError):
|
|
35
|
+
"""A bad argument or argument combination."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class SpecError(UserFacingError):
|
|
39
|
+
"""A problem in a table spec."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class EngineError(UserFacingError):
|
|
43
|
+
"""The engine refused the request."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def unreadable_table(label: str) -> UserFacingError:
|
|
47
|
+
"""The error for a table that could not be parsed.
|
|
48
|
+
|
|
49
|
+
The parser's own message is deliberately dropped: parsers quote cell values, which may be
|
|
50
|
+
personal data. Log the detail to stderr instead.
|
|
51
|
+
"""
|
|
52
|
+
return InputError(
|
|
53
|
+
f"Could not read {label} as a table. The parser's message is not shown because it can "
|
|
54
|
+
"quote cell values; check that the file's format matches its extension and that it is "
|
|
55
|
+
"UTF-8."
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def clip(text: str, limit: int = 300) -> str:
|
|
60
|
+
"""Collapse all whitespace to single spaces and clip to ``limit`` characters with an ellipsis."""
|
|
61
|
+
if limit < 1:
|
|
62
|
+
raise ValueError("limit must be at least 1")
|
|
63
|
+
flat = " ".join(text.split())
|
|
64
|
+
if len(flat) <= limit:
|
|
65
|
+
return flat
|
|
66
|
+
return flat[: limit - 1].rstrip() + "…"
|
ectype_mcp/py.typed
ADDED
|
File without changes
|
ectype_mcp/results.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Tool results: compact JSON text plus structured content, with a hard size cap."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from typing import TypeVar
|
|
8
|
+
|
|
9
|
+
import pydantic
|
|
10
|
+
from mcp.types import CallToolResult, TextContent
|
|
11
|
+
|
|
12
|
+
__all__ = ["ResultTooLarge", "capped", "tool_result"]
|
|
13
|
+
|
|
14
|
+
T = TypeVar("T")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ResultTooLarge(RuntimeError):
|
|
18
|
+
"""A serialised result is over the cap. This is a bug in the caller: summaries must cap lists."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, size: int, limit: int) -> None:
|
|
21
|
+
super().__init__(f"tool result is {size} characters, over the cap of {limit}")
|
|
22
|
+
self.size = size
|
|
23
|
+
self.limit = limit
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def tool_result(payload: pydantic.BaseModel, *, max_chars: int) -> CallToolResult:
|
|
27
|
+
"""Serialise ``payload`` as compact JSON text and as structured content.
|
|
28
|
+
|
|
29
|
+
Raises :class:`ResultTooLarge` if the JSON text is longer than ``max_chars``.
|
|
30
|
+
"""
|
|
31
|
+
data = payload.model_dump(mode="json")
|
|
32
|
+
text = json.dumps(data, ensure_ascii=False, separators=(",", ":"))
|
|
33
|
+
if len(text) > max_chars:
|
|
34
|
+
raise ResultTooLarge(len(text), max_chars)
|
|
35
|
+
return CallToolResult(content=[TextContent(type="text", text=text)], structured_content=data)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def capped(items: Sequence[T], limit: int) -> tuple[list[T], int]:
|
|
39
|
+
"""Return the first ``limit`` items and the number of items left out."""
|
|
40
|
+
if limit < 0:
|
|
41
|
+
raise ValueError("limit must not be negative")
|
|
42
|
+
kept = list(items[:limit])
|
|
43
|
+
return kept, len(items) - len(kept)
|