mcp-proxyml 0.1.0__tar.gz

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.
@@ -0,0 +1,183 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of developing and
55
+ discussing the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as "Not a
57
+ Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any other
81
+ Contribution incorporated within the Work constitutes patent or
82
+ contributory patent infringement, then any patent licenses granted to
83
+ You under this License for that Work shall terminate as of the date
84
+ such litigation is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the
87
+ Work or Derivative Works thereof in any medium, with or without
88
+ modifications, and in Source or Object form, provided that You
89
+ meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative
92
+ Works a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works
98
+ that You distribute, all copyright, patent, trademark, and
99
+ attribution notices from the Source form of the Work,
100
+ excluding those notices that do not pertain to any part of
101
+ the Derivative Works; and
102
+
103
+ (d) If the Work includes a "NOTICE" text file as part of its
104
+ distribution, You must include a readable copy of the
105
+ attribution notices contained within such NOTICE file, in
106
+ at least one of the following places: within a NOTICE text
107
+ file distributed as part of the Derivative Works; within
108
+ the Source form or documentation, if provided along with the
109
+ Derivative Works; or, within a display generated by the
110
+ Derivative Works, if and wherever such third-party notices
111
+ normally appear. The contents of the NOTICE file are for
112
+ informational purposes only and do not modify the License.
113
+ You may add Your own attribution notices within Derivative
114
+ Works that You distribute, alongside or in addition to the
115
+ NOTICE text from the Work, provided that such additional
116
+ attribution notices cannot be construed as modifying the License.
117
+
118
+ You may add Your own license statement for Your modifications and
119
+ may provide additional grant of rights to use, copy, modify, merge,
120
+ publish, distribute, sublicense, and/or sell copies of the
121
+ Contribution and such Derivative Works.
122
+
123
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
124
+ any Contribution intentionally submitted for inclusion in the Work
125
+ by You to the Licensor shall be under the terms and conditions of
126
+ this License, without any additional terms or conditions.
127
+ Notwithstanding the above, nothing herein shall supersede or modify
128
+ the terms of any separate license agreement you may have executed
129
+ with Licensor regarding such Contributions.
130
+
131
+ 6. Trademarks. This License does not grant permission to use the trade
132
+ names, trademarks, service marks, or product names of the Licensor,
133
+ except as required for reasonable and customary use in describing the
134
+ origin of the Work and reproducing the content of the NOTICE file.
135
+
136
+ 7. Disclaimer of Warranty. Unless required by applicable law or
137
+ agreed to in writing, Licensor provides the Work (and each
138
+ Contributor provides its Contributions) on an "AS IS" BASIS,
139
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
140
+ implied, including, without limitation, any conditions of TITLE,
141
+ NONINFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR
142
+ PURPOSE. You are solely responsible for determining the
143
+ appropriateness of using or reproducing the Work and assume any
144
+ risks associated with Your exercise of permissions under this License.
145
+
146
+ 8. Limitation of Liability. In no event and under no legal theory,
147
+ whether in tort (including negligence), contract, or otherwise,
148
+ unless required by applicable law (such as deliberate and grossly
149
+ negligent acts) or agreed to in writing, shall any Contributor be
150
+ liable to You for damages, including any direct, indirect, special,
151
+ incidental, or exemplary damages of any character arising as a
152
+ result of this License or out of the use or inability to use the
153
+ Work (including but not limited to damages for loss of goodwill,
154
+ work stoppage, computer failure or malfunction, or all other
155
+ commercial damages or losses), even if such Contributor has been
156
+ advised of the possibility of such damages.
157
+
158
+ 9. Accepting Warranty or Additional Liability. While redistributing
159
+ the Work or Derivative Works thereof, You may choose to offer,
160
+ and charge a fee for, acceptance of support, warranty, indemnity,
161
+ or other liability obligations and/or rights consistent with this
162
+ License. However, in accepting such obligations, You may charge only
163
+ on Your own behalf and on Your sole responsibility, not on behalf of
164
+ any other Contributor, and only if You agree to indemnify, defend,
165
+ and hold each Contributor harmless for any liability incurred by,
166
+ or claims asserted against, such Contributor by reason of your
167
+ accepting any warranty or additional liability.
168
+
169
+ END OF TERMS AND CONDITIONS
170
+
171
+ Copyright 2026 ProxyML
172
+
173
+ Licensed under the Apache License, Version 2.0 (the "License");
174
+ you may not use this file except in compliance with the License.
175
+ You may obtain a copy of the License at
176
+
177
+ http://www.apache.org/licenses/LICENSE-2.0
178
+
179
+ Unless required by applicable law or agreed to in writing, software
180
+ distributed under the License is distributed on an "AS IS" BASIS,
181
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
182
+ See the License for the specific language governing permissions and
183
+ limitations under the License.
@@ -0,0 +1,13 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcp-proxyml
3
+ Version: 0.1.0
4
+ Summary: MCP server for the ProxyML API
5
+ Requires-Python: >=3.12
6
+ License-File: LICENSE
7
+ Requires-Dist: mcp[cli]>=1.0.0
8
+ Requires-Dist: httpx>=0.27.0
9
+ Requires-Dist: pandas>=1.5.0
10
+ Requires-Dist: numpy>=1.23.0
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
13
+ Dynamic: license-file
@@ -0,0 +1,229 @@
1
+ # mcp-proxyml
2
+
3
+ MCP server for the [ProxyML](https://proxyml.ai) API. Gives Claude (and other MCP clients) direct access to ProxyML's surrogate modelling and explainability tools.
4
+
5
+ ## Prerequisites
6
+
7
+ A ProxyML API key. Sign up at [proxyml.ai](https://proxyml.ai).
8
+
9
+ ## Installation
10
+
11
+ ### Claude Desktop
12
+
13
+ Add to your `claude_desktop_config.json`:
14
+
15
+ ```json
16
+ {
17
+ "mcpServers": {
18
+ "proxyml": {
19
+ "command": "uvx",
20
+ "args": ["mcp-proxyml"],
21
+ "env": {
22
+ "PROXYML_API_KEY": "your-api-key-here"
23
+ }
24
+ }
25
+ }
26
+ }
27
+ ```
28
+
29
+ The config file is at:
30
+ - **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
31
+ - **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
32
+
33
+ Then restart Claude Desktop.
34
+
35
+ ### Claude Code
36
+
37
+ ```bash
38
+ claude mcp add-json proxyml '{"command":"uvx","args":["mcp-proxyml"],"env":{"PROXYML_API_KEY":"your-api-key-here"}}'
39
+ ```
40
+
41
+ ### Other MCP clients
42
+
43
+ ```bash
44
+ pip install mcp-proxyml
45
+ PROXYML_API_KEY=your-key mcp-proxyml
46
+ ```
47
+
48
+ ## Environment variables
49
+
50
+ | Variable | Required | Description |
51
+ |---|---|---|
52
+ | `PROXYML_API_KEY` | Yes | Your ProxyML API key |
53
+
54
+ ## Tools
55
+
56
+ ### Schema
57
+
58
+ | Tool | Description |
59
+ |---|---|
60
+ | `proxyml_infer_schema` | Infer a feature schema from a local CSV file — no data sent to the server |
61
+ | `proxyml_get_schema` | Retrieve a stored schema by name |
62
+ | `proxyml_put_schema` | Upload or replace a feature schema |
63
+
64
+ ### Training
65
+
66
+ | Tool | Description |
67
+ |---|---|
68
+ | `proxyml_synthesize_data` | Generate synthetic samples from the stored schema |
69
+ | `proxyml_train_surrogate` | Train a linear surrogate on samples scored by your model |
70
+ | `proxyml_list_surrogates` | List trained surrogate models, newest first |
71
+ | `proxyml_predict_batch` | Get surrogate predictions for a list of instances |
72
+
73
+ ### Explainability
74
+
75
+ | Tool | Description |
76
+ |---|---|
77
+ | `proxyml_get_summary` | Feature importances and model summary |
78
+ | `proxyml_export_surrogate` | Full coefficient export for audit and governance |
79
+ | `proxyml_explain_local` | Per-feature contribution breakdown for a single instance |
80
+ | `proxyml_explain_local_batch` | Per-feature contributions for multiple instances in one call |
81
+ | `proxyml_find_counterfactual` | Find the nearest point that flips the prediction |
82
+ | `proxyml_diff_models` | Compare feature importances between two surrogate versions |
83
+
84
+ ### CI/CD
85
+
86
+ | Tool | Description |
87
+ |---|---|
88
+ | `proxyml_detect_drift` | Compare two versions and return a structured pass/fail against coefficient and fidelity thresholds |
89
+
90
+ ### Account
91
+
92
+ | Tool | Description |
93
+ |---|---|
94
+ | `proxyml_get_usage` | Current tier, request count, and quota — useful as a pre-flight check |
95
+
96
+ ## Typical workflow
97
+
98
+ ```
99
+ 1. proxyml_infer_schema — point at a CSV, get a schema back
100
+ 2. proxyml_put_schema — upload it
101
+ 3. proxyml_synthesize_data — generate synthetic samples
102
+ 4. [score samples with your model]
103
+ 5. proxyml_train_surrogate — send samples + predictions, get a surrogate
104
+ 6. proxyml_get_summary — see which features drive predictions
105
+ 7. proxyml_explain_local — explain a specific decision
106
+ 8. proxyml_find_counterfactual — find what would need to change
107
+ ```
108
+
109
+ Steps 1–2 are one-time setup. Steps 3–5 can be repeated to retrain as your model changes; use `proxyml_diff_models` to compare versions.
110
+
111
+ ## Agentic workflows
112
+
113
+ ### Drift detection in CI/CD
114
+
115
+ `proxyml_detect_drift` is designed for use in deployment pipelines. It wraps `proxyml_diff_models` and applies thresholds to produce a structured pass/fail:
116
+
117
+ ```
118
+ On model deployment:
119
+ 1. proxyml_train_surrogate — train surrogate on new model version
120
+ 2. proxyml_detect_drift(a, b) — compare against previous version
121
+ → passed: false — block deployment or flag for review
122
+ → passed: true — proceed
123
+ ```
124
+
125
+ Thresholds can be tuned per use case:
126
+
127
+ ```
128
+ proxyml_detect_drift(
129
+ version_a="<previous>",
130
+ version_b="<new>",
131
+ coefficient_threshold=0.15, # tighter for high-stakes models
132
+ fidelity_threshold=0.02
133
+ )
134
+ ```
135
+
136
+ ### Dev model validation without production data
137
+
138
+ Validate a model trained in a lower environment by comparing its predictions
139
+ against a surrogate trained on production data — no production data required
140
+ in the dev environment.
141
+
142
+ This workflow requires a step the MCP server can't do on its own (scoring
143
+ with your dev model), but works naturally in Claude Code where the agent can
144
+ execute code directly:
145
+
146
+ ```
147
+ 1. proxyml_synthesize_data(num_points=100) → synthetic samples
148
+ 2. [agent runs: dev_predictions = dev_model.predict(samples)]
149
+ 3. proxyml_predict_batch(samples) → surrogate predictions
150
+ 4. [agent computes MAE and compares to tolerance]
151
+ ```
152
+
153
+ Example prompt for Claude Code:
154
+
155
+ ```
156
+ Using ProxyML, validate my dev model against the production surrogate.
157
+ Synthesize 100 samples from the "default" schema, score them with my model
158
+ at dev_model.predict(), get surrogate predictions with proxyml_predict_batch,
159
+ then compute the mean absolute error and tell me whether it's within 0.1.
160
+ ```
161
+
162
+ The surrogate acts as a proxy for production behaviour — if the dev model
163
+ agrees with it within tolerance, it's likely behaving consistently with what
164
+ was trained on real data.
165
+
166
+ ### Counterfactual investigation
167
+
168
+ When a model makes a decision that needs explaining — a rejected loan application,
169
+ a flagged transaction, a declined insurance quote — chain `proxyml_explain_local`
170
+ and `proxyml_find_counterfactual` to answer both "why?" and "what would need to
171
+ change?":
172
+
173
+ ```
174
+ 1. proxyml_explain_local(instance) → which features drove this decision
175
+ 2. proxyml_find_counterfactual(instance, target) → nearest point that flips it
176
+ ```
177
+
178
+ Example prompt:
179
+
180
+ ```
181
+ My model rejected this application: [age=34, income=42000, loan_amount=15000, ...].
182
+ Using ProxyML, explain why it was rejected and find the minimum changes that
183
+ would result in an approval. Highlight which changes are realistic given that
184
+ age is immutable.
185
+ ```
186
+
187
+ Claude will call `proxyml_explain_local` to surface the top contributing features,
188
+ then `proxyml_find_counterfactual` with the target outcome, and interpret the
189
+ difference in plain language.
190
+
191
+ ### Iterative surrogate improvement
192
+
193
+ When `proxyml_train_surrogate` returns a low fidelity warning or other training
194
+ diagnostic, the agent can use it to guide the next iteration rather than stopping:
195
+
196
+ ```
197
+ 1. proxyml_train_surrogate(samples, predictions)
198
+ → warning: "Surrogate fidelity is low (R²=0.52)..."
199
+ 2. proxyml_synthesize_data(num_points=500) — increase sample count
200
+ 3. [re-score with model]
201
+ 4. proxyml_train_surrogate(larger_samples, predictions)
202
+ 5. proxyml_detect_drift(v1, v2) — confirm improvement, not regression
203
+ ```
204
+
205
+ Example prompt:
206
+
207
+ ```
208
+ Train a surrogate for my regression model using the "default" schema with 200
209
+ samples. If fidelity is below 0.7, keep doubling the sample count and retraining
210
+ until it passes or you reach 1600 samples. Use proxyml_detect_drift after each
211
+ retrain to confirm the model is improving rather than just changing.
212
+ ```
213
+
214
+ The training warnings (convergence, sparsity, class imbalance, high correlation)
215
+ are designed to be actionable — the agent can read them and decide whether to
216
+ adjust `num_samples`, revisit the schema, or flag for human review.
217
+
218
+ ### Governance report
219
+
220
+ Claude can generate a governance report from existing tools without a dedicated endpoint. Example prompt:
221
+
222
+ ```
223
+ Using ProxyML, generate a governance report for surrogate version <id>.
224
+ Include: task type, training date, fidelity metrics, top 5 features by importance,
225
+ any warnings from training, and a plain-English summary of what drives predictions.
226
+ Format it as a structured document suitable for attaching to a deployment ticket.
227
+ ```
228
+
229
+ Claude will call `proxyml_get_summary` (and `proxyml_list_surrogates` to find metadata) and compose the report.
File without changes
@@ -0,0 +1,73 @@
1
+ def interpret_diff(
2
+ diff: dict,
3
+ version_a: str,
4
+ version_b: str,
5
+ coefficient_threshold: float,
6
+ fidelity_threshold: float,
7
+ ) -> dict:
8
+ """Apply drift thresholds to a diff_models response and return a pass/fail result.
9
+
10
+ Pure function — no I/O. Called by proxyml_detect_drift after fetching the diff.
11
+ """
12
+ flagged_features = [
13
+ entry for entry in diff["coefficient_diff"]
14
+ if abs(entry["delta"]) > coefficient_threshold
15
+ ]
16
+
17
+ metric_changes = {
18
+ metric: {**entry, "flagged": entry["delta"] < -fidelity_threshold}
19
+ for metric, entry in diff["metric_diff"].items()
20
+ }
21
+
22
+ features_added = diff.get("features_added", [])
23
+ features_removed = diff.get("features_removed", [])
24
+
25
+ passed = (
26
+ not flagged_features
27
+ and not any(v["flagged"] for v in metric_changes.values())
28
+ and not features_added
29
+ and not features_removed
30
+ )
31
+
32
+ reasons = []
33
+ if flagged_features:
34
+ top = ", ".join(
35
+ f"{e['feature']} (Δ={e['delta']:+.3f})" for e in flagged_features[:3]
36
+ )
37
+ reasons.append(
38
+ f"{len(flagged_features)} feature(s) exceeded coefficient threshold "
39
+ f"({coefficient_threshold}): {top}"
40
+ + (" and more" if len(flagged_features) > 3 else "")
41
+ )
42
+ for metric, entry in metric_changes.items():
43
+ if entry["flagged"]:
44
+ reasons.append(
45
+ f"{metric} dropped by {abs(entry['delta']):.3f} "
46
+ f"(threshold: {fidelity_threshold})"
47
+ )
48
+ if features_added:
49
+ reasons.append(f"Features added: {', '.join(features_added)}")
50
+ if features_removed:
51
+ reasons.append(f"Features removed: {', '.join(features_removed)}")
52
+
53
+ if passed:
54
+ largest = max(
55
+ (abs(e["delta"]) for e in diff["coefficient_diff"]), default=0.0
56
+ )
57
+ summary = (
58
+ f"PASSED: No significant drift detected. "
59
+ f"Largest coefficient shift: {largest:.3f} (threshold: {coefficient_threshold})."
60
+ )
61
+ else:
62
+ summary = "FAILED: " + ". ".join(reasons) + "."
63
+
64
+ return {
65
+ "passed": passed,
66
+ "version_a": version_a,
67
+ "version_b": version_b,
68
+ "summary": summary,
69
+ "flagged_features": flagged_features,
70
+ "metric_changes": metric_changes,
71
+ "features_added": features_added,
72
+ "features_removed": features_removed,
73
+ }
@@ -0,0 +1,53 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+ from pandas.api.types import is_float_dtype, is_integer_dtype
4
+
5
+
6
+ def infer_schema(df: pd.DataFrame, immutable_cols: list[str] | None = None) -> dict:
7
+ """Infer a ProxyML feature schema from a DataFrame.
8
+
9
+ Integer columns default to 'count'. Consider switching to 'categorical_ordinal'
10
+ for ordered categories like ratings or education level.
11
+ """
12
+ features = []
13
+ for col in df.columns:
14
+ immutable = immutable_cols is not None and col in immutable_cols
15
+ if is_float_dtype(df[col]):
16
+ feature = {
17
+ "type": "continuous",
18
+ "name": col,
19
+ "mean": round(float(np.nanmean(df[col])), 6),
20
+ "std": round(float(np.nanstd(df[col])), 6),
21
+ "min": float(np.nanmin(df[col])),
22
+ "max": float(np.nanmax(df[col])),
23
+ }
24
+ elif df[col].dtype == bool:
25
+ feature = _categorical(col, df[col])
26
+ elif is_integer_dtype(df[col]):
27
+ feature = {
28
+ "type": "count",
29
+ "name": col,
30
+ "lambda": round(float(np.nanmean(df[col])), 6),
31
+ "max": float(np.nanmax(df[col])),
32
+ }
33
+ else:
34
+ feature = _categorical(col, df[col])
35
+ feature["immutable"] = immutable
36
+ features.append(feature)
37
+ return {
38
+ "features": features,
39
+ "_note": (
40
+ "Auto-generated schema. Review and adjust types as needed. "
41
+ "Integer columns default to count — consider categorical_ordinal "
42
+ "for ordered categories like ratings or class labels."
43
+ ),
44
+ }
45
+
46
+
47
+ def _categorical(col: str, series: pd.Series) -> dict:
48
+ counts = series.value_counts(normalize=True)
49
+ return {
50
+ "type": "categorical",
51
+ "name": col,
52
+ "valid_categories": {str(k): round(float(v), 6) for k, v in counts.items()},
53
+ }
@@ -0,0 +1,342 @@
1
+ import json
2
+ import os
3
+
4
+ import httpx
5
+ import pandas as pd
6
+ from mcp.server.fastmcp import FastMCP
7
+
8
+ from mcp_proxyml.drift import interpret_diff
9
+ from mcp_proxyml.schema import infer_schema
10
+
11
+ mcp = FastMCP("ProxyML")
12
+
13
+ _DEFAULT_BASE_URL = "https://api.proxyml.ai/api/v1"
14
+
15
+
16
+ def _client() -> httpx.AsyncClient:
17
+ api_key = os.environ.get("PROXYML_API_KEY", "")
18
+ if not api_key:
19
+ raise RuntimeError(
20
+ "PROXYML_API_KEY is not set. "
21
+ "Add it to the MCP server env config and restart."
22
+ )
23
+ return httpx.AsyncClient(
24
+ base_url=os.environ.get("PROXYML_BASE_URL", _DEFAULT_BASE_URL),
25
+ headers={"X-API-KEY": api_key, "Content-Type": "application/json"},
26
+ timeout=60.0,
27
+ )
28
+
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # Local tools (no API call)
32
+ # ---------------------------------------------------------------------------
33
+
34
+ @mcp.tool()
35
+ async def proxyml_infer_schema(
36
+ csv_path: str,
37
+ immutable_cols: list[str] | None = None,
38
+ ) -> dict:
39
+ """Infer a ProxyML feature schema from a local CSV file.
40
+
41
+ Reads the file locally — no data is sent to the ProxyML server.
42
+ Returns a schema dict ready to pass to proxyml_put_schema.
43
+ Integer columns default to 'count'; consider 'categorical_ordinal' for
44
+ ordered categories like ratings or education level.
45
+ """
46
+ df = pd.read_csv(csv_path)
47
+ return infer_schema(df, immutable_cols)
48
+
49
+
50
+ # ---------------------------------------------------------------------------
51
+ # Schema tools
52
+ # ---------------------------------------------------------------------------
53
+
54
+ @mcp.tool()
55
+ async def proxyml_get_schema(schema_name: str = "default") -> dict:
56
+ """Retrieve a stored feature schema by name."""
57
+ async with _client() as c:
58
+ r = await c.get(f"/schema/{schema_name}")
59
+ r.raise_for_status()
60
+ return r.json()
61
+
62
+
63
+ @mcp.tool()
64
+ async def proxyml_put_schema(schema: dict, schema_name: str = "default") -> dict:
65
+ """Upload or replace a feature schema."""
66
+ async with _client() as c:
67
+ r = await c.put(f"/schema/{schema_name}", content=json.dumps(schema))
68
+ r.raise_for_status()
69
+ return r.json()
70
+
71
+
72
+ # ---------------------------------------------------------------------------
73
+ # Synthesis
74
+ # ---------------------------------------------------------------------------
75
+
76
+ @mcp.tool()
77
+ async def proxyml_synthesize_data(
78
+ num_points: int = 100,
79
+ schema_name: str = "default",
80
+ instance: list | None = None,
81
+ ) -> dict:
82
+ """Generate synthetic samples from the stored feature schema.
83
+
84
+ If instance is provided, blends schema samples with perturbations around
85
+ that point (useful for local explanations and counterfactual search).
86
+ Returns samples, feature_names, and feature_types.
87
+ """
88
+ async with _client() as c:
89
+ if instance is None:
90
+ payload = {"n": num_points, "schema_name": schema_name}
91
+ r = await c.post("/synthesize/neighbors", content=json.dumps(payload))
92
+ else:
93
+ payload = {"n": num_points, "instance": instance, "schema_name": schema_name}
94
+ r = await c.post("/synthesize/blended", content=json.dumps(payload))
95
+ r.raise_for_status()
96
+ return r.json()
97
+
98
+
99
+ # ---------------------------------------------------------------------------
100
+ # Surrogate model tools
101
+ # ---------------------------------------------------------------------------
102
+
103
+ @mcp.tool()
104
+ async def proxyml_train_surrogate(
105
+ samples: list[list],
106
+ predictions: list,
107
+ schema_name: str = "default",
108
+ task: str = "auto",
109
+ test_size: float = 0.2,
110
+ feature_names: list[str] | None = None,
111
+ name: str | None = None,
112
+ comments: str | None = None,
113
+ ) -> dict:
114
+ """Train a linear surrogate model on samples scored by the user's model.
115
+
116
+ samples: rows returned by proxyml_synthesize_data.
117
+ predictions: your model's output for each sample, in the same order.
118
+ task: 'classification', 'regression', or 'auto' (default).
119
+ Returns version ID, fidelity metrics, and any training warnings.
120
+ """
121
+ payload: dict = {
122
+ "samples": samples,
123
+ "predictions": predictions,
124
+ "schema_name": schema_name,
125
+ "task": task,
126
+ "test_size": test_size,
127
+ }
128
+ if feature_names is not None:
129
+ payload["feature_names"] = feature_names
130
+ if name is not None:
131
+ payload["name"] = name
132
+ if comments is not None:
133
+ payload["comments"] = comments
134
+ async with _client() as c:
135
+ r = await c.post("/surrogate/train", content=json.dumps(payload))
136
+ r.raise_for_status()
137
+ return r.json()
138
+
139
+
140
+ @mcp.tool()
141
+ async def proxyml_list_surrogates(limit: int = 50, offset: int = 0) -> dict:
142
+ """List trained surrogate models, newest first.
143
+
144
+ Returns model metadata (version ID, task, metrics, name, trained_at).
145
+ Use version IDs from here with other tools.
146
+ """
147
+ async with _client() as c:
148
+ r = await c.get("/surrogate/models", params={"limit": limit, "offset": offset})
149
+ r.raise_for_status()
150
+ return r.json()
151
+
152
+
153
+ # ---------------------------------------------------------------------------
154
+ # Explanation tools
155
+ # ---------------------------------------------------------------------------
156
+
157
+ @mcp.tool()
158
+ async def proxyml_get_summary(version: str | None = None) -> dict:
159
+ """Get feature importances and model summary for a surrogate.
160
+
161
+ Omit version to use the most recently trained model.
162
+ """
163
+ async with _client() as c:
164
+ params = {"version": version} if version is not None else {}
165
+ r = await c.get("/explain/summary", params=params)
166
+ r.raise_for_status()
167
+ return r.json()
168
+
169
+
170
+ @mcp.tool()
171
+ async def proxyml_explain_local(
172
+ instance: list,
173
+ version: str | None = None,
174
+ ) -> dict:
175
+ """Per-feature contribution breakdown for a single instance.
176
+
177
+ Returns prediction, feature_contributions (sorted by abs contribution),
178
+ intercept, and optionally probabilities and per-class contributions.
179
+ """
180
+ payload: dict = {"instance": instance}
181
+ if version is not None:
182
+ payload["version"] = version
183
+ async with _client() as c:
184
+ r = await c.post("/explain/local", content=json.dumps(payload))
185
+ r.raise_for_status()
186
+ return r.json()
187
+
188
+
189
+ @mcp.tool()
190
+ async def proxyml_find_counterfactual(
191
+ instance: list,
192
+ target_label: float | str,
193
+ n_neighbors: int = 10000,
194
+ perturbation_scale: float = 0.1,
195
+ version: str | None = None,
196
+ ) -> dict:
197
+ """Find a counterfactual: the nearest point that flips the prediction to target_label.
198
+
199
+ A counterfactual is not guaranteed — check the 'counterfactual' field in the
200
+ response (None means none was found within the search budget).
201
+ """
202
+ payload: dict = {
203
+ "instance": instance,
204
+ "target_label": target_label,
205
+ "n_neighbors": n_neighbors,
206
+ "perturbation_scale": perturbation_scale,
207
+ }
208
+ if version is not None:
209
+ payload["version"] = version
210
+ async with _client() as c:
211
+ r = await c.post("/explain/counterfactual", content=json.dumps(payload))
212
+ r.raise_for_status()
213
+ return r.json()
214
+
215
+
216
+ @mcp.tool()
217
+ async def proxyml_diff_models(version_a: str, version_b: str) -> dict:
218
+ """Compare feature importances between two surrogate versions.
219
+
220
+ Both surrogates must share the same task type and at least one feature.
221
+ """
222
+ async with _client() as c:
223
+ r = await c.get("/explain/diff", params={"version_a": version_a, "version_b": version_b})
224
+ r.raise_for_status()
225
+ return r.json()
226
+
227
+
228
+ @mcp.tool()
229
+ async def proxyml_detect_drift(
230
+ version_a: str,
231
+ version_b: str,
232
+ coefficient_threshold: float = 0.1,
233
+ fidelity_threshold: float = 0.05,
234
+ ) -> dict:
235
+ """Detect behavioural drift between two surrogate versions.
236
+
237
+ Calls diff_models and applies thresholds to produce a structured pass/fail
238
+ suitable for use in CI/CD pipelines.
239
+
240
+ coefficient_threshold: flag features whose absolute coefficient delta exceeds this (default 0.1).
241
+ fidelity_threshold: flag metrics that drop by more than this amount (default 0.05).
242
+
243
+ Returns:
244
+ passed: False if any feature or metric breach a threshold, or if features were added/removed.
245
+ flagged_features: features whose |delta| exceeded coefficient_threshold, sorted by |delta| desc.
246
+ metric_changes: per-metric deltas with a 'flagged' key where the drop exceeded fidelity_threshold.
247
+ features_added / features_removed: schema changes between versions.
248
+ summary: human-readable explanation of the result.
249
+ """
250
+ async with _client() as c:
251
+ r = await c.get("/explain/diff", params={"version_a": version_a, "version_b": version_b})
252
+ r.raise_for_status()
253
+ diff = r.json()
254
+
255
+ return interpret_diff(diff, version_a, version_b, coefficient_threshold, fidelity_threshold)
256
+
257
+
258
+ # ---------------------------------------------------------------------------
259
+ # Surrogate predictions
260
+ # ---------------------------------------------------------------------------
261
+
262
+ @mcp.tool()
263
+ async def proxyml_predict_batch(
264
+ instances: list[list],
265
+ version: str | None = None,
266
+ ) -> dict:
267
+ """Get surrogate model predictions for a list of instances.
268
+
269
+ Returns predictions in the same order as instances, along with the
270
+ model version used. Useful for comparing surrogate predictions against
271
+ a dev model's output on the same synthetic samples.
272
+ """
273
+ payload: dict = {"inputs": instances}
274
+ if version is not None:
275
+ payload["version"] = version
276
+ async with _client() as c:
277
+ r = await c.post("/surrogate/predict/batch", content=json.dumps(payload))
278
+ r.raise_for_status()
279
+ return r.json()
280
+
281
+
282
+ # ---------------------------------------------------------------------------
283
+ # Account
284
+ # ---------------------------------------------------------------------------
285
+
286
+ @mcp.tool()
287
+ async def proxyml_get_usage() -> dict:
288
+ """Return current tier, request count, and quota for the authenticated account.
289
+
290
+ Useful as a pre-flight check before expensive operations like training or
291
+ large synthesis runs.
292
+ """
293
+ async with _client() as c:
294
+ r = await c.get("/account/usage")
295
+ r.raise_for_status()
296
+ return r.json()
297
+
298
+
299
+ # ---------------------------------------------------------------------------
300
+ # Surrogate export and batch explanation
301
+ # ---------------------------------------------------------------------------
302
+
303
+ @mcp.tool()
304
+ async def proxyml_export_surrogate(version: str) -> dict:
305
+ """Export the full surrogate model: coefficients, intercepts, scaler params, and classes.
306
+
307
+ Returns everything needed to reconstruct the surrogate outside ProxyML.
308
+ Richer than proxyml_get_summary — use this for audit trails and governance reports.
309
+ """
310
+ async with _client() as c:
311
+ r = await c.get(f"/surrogate/models/{version}/export")
312
+ r.raise_for_status()
313
+ return r.json()
314
+
315
+
316
+ @mcp.tool()
317
+ async def proxyml_explain_local_batch(
318
+ instances: list[list],
319
+ version: str | None = None,
320
+ ) -> dict:
321
+ """Per-feature contribution breakdown for multiple instances in one call.
322
+
323
+ Equivalent to calling proxyml_explain_local for each instance, but more
324
+ efficient. Returns a 'results' list in the same order as instances.
325
+ """
326
+ payload: dict = {"instances": instances}
327
+ if version is not None:
328
+ payload["version"] = version
329
+ async with _client() as c:
330
+ r = await c.post("/explain/local/batch", content=json.dumps(payload))
331
+ r.raise_for_status()
332
+ return r.json()
333
+
334
+
335
+ # ---------------------------------------------------------------------------
336
+
337
+ def main() -> None:
338
+ mcp.run()
339
+
340
+
341
+ if __name__ == "__main__":
342
+ main()
@@ -0,0 +1,13 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcp-proxyml
3
+ Version: 0.1.0
4
+ Summary: MCP server for the ProxyML API
5
+ Requires-Python: >=3.12
6
+ License-File: LICENSE
7
+ Requires-Dist: mcp[cli]>=1.0.0
8
+ Requires-Dist: httpx>=0.27.0
9
+ Requires-Dist: pandas>=1.5.0
10
+ Requires-Dist: numpy>=1.23.0
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
13
+ Dynamic: license-file
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ mcp_proxyml/__init__.py
5
+ mcp_proxyml/drift.py
6
+ mcp_proxyml/schema.py
7
+ mcp_proxyml/server.py
8
+ mcp_proxyml.egg-info/PKG-INFO
9
+ mcp_proxyml.egg-info/SOURCES.txt
10
+ mcp_proxyml.egg-info/dependency_links.txt
11
+ mcp_proxyml.egg-info/entry_points.txt
12
+ mcp_proxyml.egg-info/requires.txt
13
+ mcp_proxyml.egg-info/top_level.txt
14
+ tests/test_drift.py
15
+ tests/test_schema.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ mcp-proxyml = mcp_proxyml.server:main
@@ -0,0 +1,7 @@
1
+ mcp[cli]>=1.0.0
2
+ httpx>=0.27.0
3
+ pandas>=1.5.0
4
+ numpy>=1.23.0
5
+
6
+ [dev]
7
+ pytest>=8.0.0
@@ -0,0 +1 @@
1
+ mcp_proxyml
@@ -0,0 +1,26 @@
1
+ [project]
2
+ name = "mcp-proxyml"
3
+ version = "0.1.0"
4
+ description = "MCP server for the ProxyML API"
5
+ requires-python = ">=3.12"
6
+ dependencies = [
7
+ "mcp[cli]>=1.0.0",
8
+ "httpx>=0.27.0",
9
+ "pandas>=1.5.0",
10
+ "numpy>=1.23.0",
11
+ ]
12
+
13
+ [project.scripts]
14
+ mcp-proxyml = "mcp_proxyml.server:main"
15
+
16
+ [project.optional-dependencies]
17
+ dev = [
18
+ "pytest>=8.0.0",
19
+ ]
20
+
21
+ [tool.pytest.ini_options]
22
+ testpaths = ["tests"]
23
+
24
+ [build-system]
25
+ requires = ["setuptools>=68.0"]
26
+ build-backend = "setuptools.build_meta"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,160 @@
1
+ import pytest
2
+ from mcp_proxyml.drift import interpret_diff
3
+
4
+ VA = "ver-a"
5
+ VB = "ver-b"
6
+ COEFF_T = 0.1
7
+ FIDELITY_T = 0.05
8
+
9
+
10
+ def _diff(coefficient_diff=None, metric_diff=None, features_added=None, features_removed=None):
11
+ return {
12
+ "coefficient_diff": coefficient_diff or [],
13
+ "metric_diff": metric_diff or {},
14
+ "features_added": features_added or [],
15
+ "features_removed": features_removed or [],
16
+ }
17
+
18
+
19
+ def _coeff(feature, a, b):
20
+ return {"feature": feature, "a": a, "b": b, "delta": b - a}
21
+
22
+
23
+ def _metric(a, b):
24
+ return {"a": a, "b": b, "delta": b - a}
25
+
26
+
27
+ # ---------------------------------------------------------------------------
28
+ # Pass cases
29
+ # ---------------------------------------------------------------------------
30
+
31
+ def test_passes_with_no_changes():
32
+ result = interpret_diff(_diff(), VA, VB, COEFF_T, FIDELITY_T)
33
+ assert result["passed"] is True
34
+ assert result["summary"].startswith("PASSED")
35
+
36
+
37
+ def test_passes_when_deltas_within_threshold():
38
+ diff = _diff(coefficient_diff=[_coeff("age", 0.5, 0.55)]) # delta=0.05 < 0.1
39
+ result = interpret_diff(diff, VA, VB, COEFF_T, FIDELITY_T)
40
+ assert result["passed"] is True
41
+
42
+
43
+ def test_passes_when_metric_improves():
44
+ diff = _diff(metric_diff={"r2": _metric(0.8, 0.85)}) # delta=+0.05, improvement
45
+ result = interpret_diff(diff, VA, VB, COEFF_T, FIDELITY_T)
46
+ assert result["passed"] is True
47
+
48
+
49
+ def test_passes_when_metric_drops_within_fidelity_threshold():
50
+ diff = _diff(metric_diff={"r2": _metric(0.8, 0.76)}) # delta=-0.04 < 0.05
51
+ result = interpret_diff(diff, VA, VB, COEFF_T, FIDELITY_T)
52
+ assert result["passed"] is True
53
+
54
+
55
+ # ---------------------------------------------------------------------------
56
+ # Fail cases
57
+ # ---------------------------------------------------------------------------
58
+
59
+ def test_fails_on_large_coefficient_shift():
60
+ diff = _diff(coefficient_diff=[_coeff("income", 0.3, 0.45)]) # delta=0.15 > 0.1
61
+ result = interpret_diff(diff, VA, VB, COEFF_T, FIDELITY_T)
62
+ assert result["passed"] is False
63
+ assert result["summary"].startswith("FAILED")
64
+
65
+
66
+ def test_fails_on_fidelity_drop():
67
+ diff = _diff(metric_diff={"r2": _metric(0.85, 0.78)}) # delta=-0.07 > 0.05
68
+ result = interpret_diff(diff, VA, VB, COEFF_T, FIDELITY_T)
69
+ assert result["passed"] is False
70
+
71
+
72
+ def test_fails_on_features_added():
73
+ diff = _diff(features_added=["new_feature"])
74
+ result = interpret_diff(diff, VA, VB, COEFF_T, FIDELITY_T)
75
+ assert result["passed"] is False
76
+ assert "new_feature" in result["summary"]
77
+
78
+
79
+ def test_fails_on_features_removed():
80
+ diff = _diff(features_removed=["old_feature"])
81
+ result = interpret_diff(diff, VA, VB, COEFF_T, FIDELITY_T)
82
+ assert result["passed"] is False
83
+ assert "old_feature" in result["summary"]
84
+
85
+
86
+ # ---------------------------------------------------------------------------
87
+ # Flagged features
88
+ # ---------------------------------------------------------------------------
89
+
90
+ def test_flagged_features_contains_only_breaching_features():
91
+ diff = _diff(coefficient_diff=[
92
+ _coeff("age", 0.5, 0.55), # delta=0.05, within threshold
93
+ _coeff("income", 0.3, 0.45), # delta=0.15, breaches
94
+ ])
95
+ result = interpret_diff(diff, VA, VB, COEFF_T, FIDELITY_T)
96
+ assert len(result["flagged_features"]) == 1
97
+ assert result["flagged_features"][0]["feature"] == "income"
98
+
99
+
100
+ def test_exactly_at_threshold_does_not_flag():
101
+ diff = _diff(coefficient_diff=[_coeff("age", 0.0, 0.1)]) # delta == threshold
102
+ result = interpret_diff(diff, VA, VB, COEFF_T, FIDELITY_T)
103
+ assert result["passed"] is True
104
+ assert result["flagged_features"] == []
105
+
106
+
107
+ def test_negative_delta_beyond_threshold_is_flagged():
108
+ diff = _diff(coefficient_diff=[_coeff("age", 0.5, 0.35)]) # delta=-0.15
109
+ result = interpret_diff(diff, VA, VB, COEFF_T, FIDELITY_T)
110
+ assert result["passed"] is False
111
+ assert len(result["flagged_features"]) == 1
112
+
113
+
114
+ # ---------------------------------------------------------------------------
115
+ # Metric changes
116
+ # ---------------------------------------------------------------------------
117
+
118
+ def test_metric_changes_includes_flagged_key():
119
+ diff = _diff(metric_diff={"f1": _metric(0.9, 0.82)})
120
+ result = interpret_diff(diff, VA, VB, COEFF_T, FIDELITY_T)
121
+ assert "flagged" in result["metric_changes"]["f1"]
122
+ assert result["metric_changes"]["f1"]["flagged"] is True
123
+
124
+
125
+ def test_metric_changes_not_flagged_when_within_threshold():
126
+ diff = _diff(metric_diff={"f1": _metric(0.9, 0.86)}) # delta=-0.04
127
+ result = interpret_diff(diff, VA, VB, COEFF_T, FIDELITY_T)
128
+ assert result["metric_changes"]["f1"]["flagged"] is False
129
+
130
+
131
+ # ---------------------------------------------------------------------------
132
+ # Summary content
133
+ # ---------------------------------------------------------------------------
134
+
135
+ def test_passed_summary_includes_largest_shift():
136
+ diff = _diff(coefficient_diff=[_coeff("age", 0.5, 0.55)])
137
+ result = interpret_diff(diff, VA, VB, COEFF_T, FIDELITY_T)
138
+ assert "0.050" in result["summary"]
139
+
140
+
141
+ def test_failed_summary_names_flagged_features():
142
+ diff = _diff(coefficient_diff=[_coeff("income", 0.3, 0.5)])
143
+ result = interpret_diff(diff, VA, VB, COEFF_T, FIDELITY_T)
144
+ assert "income" in result["summary"]
145
+
146
+
147
+ def test_failed_summary_with_more_than_three_features():
148
+ diff = _diff(coefficient_diff=[_coeff(f"f{i}", 0.0, 0.5) for i in range(5)])
149
+ result = interpret_diff(diff, VA, VB, COEFF_T, FIDELITY_T)
150
+ assert "and more" in result["summary"]
151
+
152
+
153
+ # ---------------------------------------------------------------------------
154
+ # Version IDs passed through
155
+ # ---------------------------------------------------------------------------
156
+
157
+ def test_version_ids_in_result():
158
+ result = interpret_diff(_diff(), "v1", "v2", COEFF_T, FIDELITY_T)
159
+ assert result["version_a"] == "v1"
160
+ assert result["version_b"] == "v2"
@@ -0,0 +1,142 @@
1
+ import math
2
+ import pandas as pd
3
+ import pytest
4
+ from mcp_proxyml.schema import infer_schema
5
+
6
+
7
+ def _feature(schema: dict, name: str) -> dict:
8
+ return next(f for f in schema["features"] if f["name"] == name)
9
+
10
+
11
+ # ---------------------------------------------------------------------------
12
+ # Type inference
13
+ # ---------------------------------------------------------------------------
14
+
15
+ def test_float_column_inferred_as_continuous():
16
+ df = pd.DataFrame({"x": [1.0, 2.0, 3.0]})
17
+ f = _feature(infer_schema(df), "x")
18
+ assert f["type"] == "continuous"
19
+
20
+
21
+ def test_integer_column_inferred_as_count():
22
+ df = pd.DataFrame({"x": pd.array([1, 2, 3], dtype="int64")})
23
+ f = _feature(infer_schema(df), "x")
24
+ assert f["type"] == "count"
25
+
26
+
27
+ def test_string_column_inferred_as_categorical():
28
+ df = pd.DataFrame({"x": ["a", "b", "a"]})
29
+ f = _feature(infer_schema(df), "x")
30
+ assert f["type"] == "categorical"
31
+
32
+
33
+ def test_bool_column_inferred_as_categorical():
34
+ df = pd.DataFrame({"x": [True, False, True]})
35
+ f = _feature(infer_schema(df), "x")
36
+ assert f["type"] == "categorical"
37
+
38
+
39
+ # ---------------------------------------------------------------------------
40
+ # Continuous stats
41
+ # ---------------------------------------------------------------------------
42
+
43
+ def test_continuous_stats():
44
+ df = pd.DataFrame({"x": [1.0, 2.0, 3.0, 4.0, 5.0]})
45
+ f = _feature(infer_schema(df), "x")
46
+ assert f["min"] == 1.0
47
+ assert f["max"] == 5.0
48
+ assert math.isclose(f["mean"], 3.0)
49
+ assert math.isclose(f["std"], math.sqrt(2.0), rel_tol=1e-5)
50
+
51
+
52
+ def test_continuous_ignores_nan():
53
+ df = pd.DataFrame({"x": [1.0, float("nan"), 3.0]})
54
+ f = _feature(infer_schema(df), "x")
55
+ assert f["min"] == 1.0
56
+ assert f["max"] == 3.0
57
+ assert math.isclose(f["mean"], 2.0)
58
+
59
+
60
+ # ---------------------------------------------------------------------------
61
+ # Count stats
62
+ # ---------------------------------------------------------------------------
63
+
64
+ def test_count_stats():
65
+ df = pd.DataFrame({"x": pd.array([0, 2, 4], dtype="int64")})
66
+ f = _feature(infer_schema(df), "x")
67
+ assert f["max"] == 4.0
68
+ assert math.isclose(f["lambda"], 2.0)
69
+
70
+
71
+ # ---------------------------------------------------------------------------
72
+ # Categorical stats
73
+ # ---------------------------------------------------------------------------
74
+
75
+ def test_categorical_valid_categories_sum_to_one():
76
+ df = pd.DataFrame({"x": ["a", "b", "b", "c"]})
77
+ f = _feature(infer_schema(df), "x")
78
+ assert math.isclose(sum(f["valid_categories"].values()), 1.0, rel_tol=1e-5)
79
+
80
+
81
+ def test_categorical_proportions():
82
+ df = pd.DataFrame({"x": ["a", "a", "b"]})
83
+ f = _feature(infer_schema(df), "x")
84
+ cats = f["valid_categories"]
85
+ assert math.isclose(cats["a"], 2 / 3, rel_tol=1e-5)
86
+ assert math.isclose(cats["b"], 1 / 3, rel_tol=1e-5)
87
+
88
+
89
+ def test_categorical_keys_are_strings():
90
+ df = pd.DataFrame({"x": [1, 2, 2]}) # object dtype from mixed construction
91
+ df["x"] = df["x"].astype(str)
92
+ f = _feature(infer_schema(df), "x")
93
+ assert all(isinstance(k, str) for k in f["valid_categories"])
94
+
95
+
96
+ # ---------------------------------------------------------------------------
97
+ # Immutable flag
98
+ # ---------------------------------------------------------------------------
99
+
100
+ def test_immutable_col_is_flagged():
101
+ df = pd.DataFrame({"age": [25.0, 30.0], "income": [50000.0, 60000.0]})
102
+ schema = infer_schema(df, immutable_cols=["age"])
103
+ assert _feature(schema, "age")["immutable"] is True
104
+ assert _feature(schema, "income")["immutable"] is False
105
+
106
+
107
+ def test_no_immutable_cols_all_false():
108
+ df = pd.DataFrame({"x": [1.0], "y": [2.0]})
109
+ schema = infer_schema(df)
110
+ assert all(not f["immutable"] for f in schema["features"])
111
+
112
+
113
+ def test_empty_immutable_list_all_false():
114
+ df = pd.DataFrame({"x": [1.0]})
115
+ schema = infer_schema(df, immutable_cols=[])
116
+ assert _feature(schema, "x")["immutable"] is False
117
+
118
+
119
+ # ---------------------------------------------------------------------------
120
+ # Column ordering and schema structure
121
+ # ---------------------------------------------------------------------------
122
+
123
+ def test_column_order_preserved():
124
+ df = pd.DataFrame({"c": [1.0], "a": [2.0], "b": [3.0]})
125
+ schema = infer_schema(df)
126
+ assert [f["name"] for f in schema["features"]] == ["c", "a", "b"]
127
+
128
+
129
+ def test_schema_has_note():
130
+ df = pd.DataFrame({"x": [1.0]})
131
+ assert "_note" in infer_schema(df)
132
+
133
+
134
+ def test_mixed_types():
135
+ df = pd.DataFrame({
136
+ "score": [0.1, 0.9],
137
+ "count": pd.array([1, 5], dtype="int64"),
138
+ "label": ["pos", "neg"],
139
+ })
140
+ schema = infer_schema(df)
141
+ types = {f["name"]: f["type"] for f in schema["features"]}
142
+ assert types == {"score": "continuous", "count": "count", "label": "categorical"}