sdcmodeler 4.0.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.
sdcmodeler/__init__.py ADDED
@@ -0,0 +1,39 @@
1
+ """
2
+ sdcmodeler: the modeler's client for SDCStudio.
3
+
4
+ Three layers in one package (SDCStudio's agent-path PRD, decision D1):
5
+
6
+ - ``sdcmodeler.client``: a framework-free client for the SDCStudio API, httpx
7
+ and nothing else. Search the catalog, estimate, assemble and publish a data
8
+ model, generate the package and an application, read the wallet and the
9
+ key's policy.
10
+ - ``sdcmodeler.cli``: the same client at a terminal.
11
+ - ``sdcmodeler.mcp_server``: ``sdcmodeler mcp``, a JSON-RPC 2.0 stdio server
12
+ over the client for any MCP-capable agent, carrying the product policy: no
13
+ spend without an estimate shown, stop at the key's limit, never pay.
14
+
15
+ The name follows the role-name pattern of the other Semantic Data Charter
16
+ servers: sdcvalidator validates, sdcgovernance governs, sdcreader reads,
17
+ sdcmodeler models. It also names the concept SDCStudio already has: every user
18
+ is a Modeler, and the Modeler's projects scope every call.
19
+ """
20
+ __version__ = "4.0.0"
21
+
22
+ from sdcmodeler.client import ( # noqa: E402
23
+ AssemblyRefused,
24
+ InsufficientCredits,
25
+ KeyPolicyRefused,
26
+ SDCStudioClient,
27
+ SDCStudioError,
28
+ )
29
+ from sdcmodeler.pricing import estimate_tree # noqa: E402
30
+
31
+ __all__ = [
32
+ "__version__",
33
+ "SDCStudioClient",
34
+ "SDCStudioError",
35
+ "InsufficientCredits",
36
+ "KeyPolicyRefused",
37
+ "AssemblyRefused",
38
+ "estimate_tree",
39
+ ]
sdcmodeler/cli.py ADDED
@@ -0,0 +1,102 @@
1
+ """``sdcmodeler``: the client at a terminal. ``sdcmodeler mcp`` starts the MCP server."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from sdcmodeler import __version__
10
+ from sdcmodeler.client import SDCStudioClient, SDCStudioError
11
+
12
+
13
+ def _print(data) -> None:
14
+ sys.stdout.write(json.dumps(data, indent=2, default=str) + "\n")
15
+
16
+
17
+ def _load_tree(path: str) -> dict:
18
+ return json.loads(Path(path).read_text(encoding="utf-8"))
19
+
20
+
21
+ def build_parser() -> argparse.ArgumentParser:
22
+ p = argparse.ArgumentParser(
23
+ prog="sdcmodeler",
24
+ description="The modeler's client for SDCStudio: search, estimate, build, generate; `sdcmodeler mcp` runs the MCP server.",
25
+ epilog="The key is read from $SDCSTUDIO_API_KEY, the deployment from $SDCSTUDIO_URL.",
26
+ )
27
+ p.add_argument("--version", action="version", version=f"sdcmodeler {__version__}")
28
+ p.add_argument("--url", default=None, help="SDCStudio base URL.")
29
+ sub = p.add_subparsers(dest="command")
30
+
31
+ s = sub.add_parser("search", help="search the public catalog of published components")
32
+ s.add_argument("query"); s.add_argument("--type"); s.add_argument("--project"); s.add_argument("--page-size", type=int, default=25)
33
+ s.set_defaults(func=lambda c, a: c.search_components(a.query, type=a.type, project=a.project, page_size=a.page_size))
34
+
35
+ s = sub.add_parser("models", help="published models in the public catalog")
36
+ s.add_argument("query", nargs="?", default="")
37
+ s.set_defaults(func=lambda c, a: c.list_models(a.query))
38
+
39
+ s = sub.add_parser("model", help="one published model, with its artifact routes")
40
+ s.add_argument("ct_id")
41
+ s.set_defaults(func=lambda c, a: c.get_model(a.ct_id))
42
+
43
+ s = sub.add_parser("artifact", help="download one artifact of a published model (xsd, xml, json, jsonld, html, ttl, shacl, gql, zip)")
44
+ s.add_argument("ct_id"); s.add_argument("kind"); s.add_argument("--dir", default=".")
45
+ s.set_defaults(func=lambda c, a: {"path": str(c.download_artifact(a.ct_id, a.kind, a.dir))})
46
+
47
+ s = sub.add_parser("estimate", help="what an assembly tree would reuse, mint and cost (no call that spends)")
48
+ s.add_argument("tree", help="JSON file: {label, components: [...], clusters: [...]}"); s.add_argument("--title", default="")
49
+ s.set_defaults(func=lambda c, a: c.estimate(_load_tree(a.tree), a.title))
50
+
51
+ s = sub.add_parser("build", help="assemble (and, with every leaf existing, publish and generate) a model; spends credits")
52
+ s.add_argument("tree"); s.add_argument("--title", required=True); s.add_argument("--description", default="")
53
+ s.set_defaults(func=lambda c, a: c.assemble(a.title, _load_tree(a.tree), description=a.description))
54
+
55
+ s = sub.add_parser("job", help="status of a mixed build or an upload")
56
+ s.add_argument("data_source_ct_id")
57
+ s.set_defaults(func=lambda c, a: c.job_status(a.data_source_ct_id))
58
+
59
+ s = sub.add_parser("package", help="generate a published model's package and download it")
60
+ s.add_argument("ct_id"); s.add_argument("--dir", default=".")
61
+ s.set_defaults(func=lambda c, a: {"generated": c.generate_package(a.ct_id), "path": str(c.download_package(a.ct_id, a.dir))})
62
+
63
+ s = sub.add_parser("app", help="generate and download a published model's application (1,500 credits the first time)")
64
+ s.add_argument("ct_id"); s.add_argument("--profile", choices=["lightweight", "enterprise"], default="lightweight"); s.add_argument("--dir", default=".")
65
+ def _app(c, a):
66
+ generated = c.generate_app(a.ct_id, a.profile)
67
+ path, charged = c.download_app(a.ct_id, a.dir, a.profile)
68
+ return {"generated": generated, "path": str(path), "charged": charged}
69
+ s.set_defaults(func=_app)
70
+
71
+ s = sub.add_parser("wallet", help="the wallet balance in credits and this key's policy")
72
+ s.set_defaults(func=lambda c, a: {"wallet": c.wallet(), "key": c.key_policy()})
73
+
74
+ sub.add_parser("mcp", help="run the MCP stdio server (options after `mcp` belong to the server)")
75
+ return p
76
+
77
+
78
+ def main(argv: list[str] | None = None) -> int:
79
+ argv = list(sys.argv[1:]) if argv is None else list(argv)
80
+ if argv[:1] == ["mcp"]:
81
+ # The registry launches `sdcmodeler mcp [server options]`; the server owns those options.
82
+ from sdcmodeler.mcp_server import main as mcp_main
83
+ mcp_main(argv[1:])
84
+ return 0
85
+ parser = build_parser()
86
+ args = parser.parse_args(argv)
87
+ if not args.command:
88
+ parser.print_help()
89
+ return 0
90
+ client = SDCStudioClient(base_url=args.url)
91
+ try:
92
+ _print(args.func(client, args))
93
+ return 0
94
+ except SDCStudioError as exc:
95
+ sys.stderr.write(f"{exc}\n")
96
+ return 1
97
+ finally:
98
+ client.close()
99
+
100
+
101
+ if __name__ == "__main__":
102
+ sys.exit(main())
sdcmodeler/client.py ADDED
@@ -0,0 +1,273 @@
1
+ """
2
+ A framework-free client for the SDCStudio API.
3
+
4
+ httpx and nothing else. Authentication is ``Authorization: Token sdcs_...``
5
+ (an API key from Settings, API Keys), read from ``SDCSTUDIO_API_KEY`` when not
6
+ given. The public catalog needs no key. Every money-spending call goes through
7
+ the server's wallet and key policy, which the client reports faithfully: a 402
8
+ is ``InsufficientCredits`` with the numbers in credits, a 403 with
9
+ ``error_type`` ``key_scope`` or ``key_spend_limit`` is ``KeyPolicyRefused``, a
10
+ 409 on assembly (a retired component) is ``AssemblyRefused``. The client never
11
+ funds a wallet: that is a person's act at the wallet page.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ import httpx
21
+
22
+ from sdcmodeler import pricing
23
+
24
+ DEFAULT_BASE_URL = "https://sdcstudio.axius-sdc.com"
25
+ KEY_PREFIX_SHOWN = 12 # "sdcs_" and the first seven hex characters, as the key list shows them
26
+
27
+
28
+ class SDCStudioError(Exception):
29
+ """An SDCStudio response the client could not use; ``status`` and ``body`` carry what the server said."""
30
+
31
+ def __init__(self, status: int, body: Any, message: str = ""):
32
+ self.status = status
33
+ self.body = body
34
+ super().__init__(message or f"SDCStudio answered {status}: {_short(body)}")
35
+
36
+
37
+ class InsufficientCredits(SDCStudioError):
38
+ """402: the wallet cannot pay. ``estimated_cost_credits`` and ``balance_credits`` are what to tell the person."""
39
+
40
+ def __init__(self, status: int, body: Any):
41
+ b = body if isinstance(body, dict) else {}
42
+ self.estimated_cost_credits = b.get("estimated_cost_credits")
43
+ self.balance_credits = b.get("balance_credits")
44
+ super().__init__(status, body, b.get("error") or "Insufficient credits.")
45
+
46
+
47
+ class KeyPolicyRefused(SDCStudioError):
48
+ """403 with ``error_type`` ``key_scope`` or ``key_spend_limit``: the key, not the wallet, said no."""
49
+
50
+ def __init__(self, status: int, body: Any):
51
+ b = body if isinstance(body, dict) else {}
52
+ self.error_type = b.get("error_type", "")
53
+ super().__init__(status, body, b.get("error") or "The API key may not make this call.")
54
+
55
+
56
+ class AssemblyRefused(SDCStudioError):
57
+ """409 on assembly: a retired component in the tree; the message names it."""
58
+
59
+
60
+ def _short(body: Any, n: int = 200) -> str:
61
+ text = body if isinstance(body, str) else json.dumps(body, default=str)
62
+ return text[:n]
63
+
64
+
65
+ def _body(resp: httpx.Response) -> Any:
66
+ try:
67
+ return resp.json()
68
+ except ValueError:
69
+ return resp.text
70
+
71
+
72
+ class SDCStudioClient:
73
+ """One SDCStudio, one key (or none), one httpx client."""
74
+
75
+ def __init__(
76
+ self,
77
+ base_url: str | None = None,
78
+ api_key: str | None = None,
79
+ *,
80
+ http: httpx.Client | None = None,
81
+ timeout: float = 120.0,
82
+ ):
83
+ self.base_url = (base_url or os.environ.get("SDCSTUDIO_URL") or DEFAULT_BASE_URL).rstrip("/")
84
+ self.api_key = api_key if api_key is not None else os.environ.get("SDCSTUDIO_API_KEY")
85
+ headers = {"Accept": "application/json"}
86
+ if self.api_key:
87
+ headers["Authorization"] = f"Token {self.api_key}"
88
+ self._http = http or httpx.Client(base_url=self.base_url, headers=headers, timeout=timeout)
89
+ if http is not None and self.api_key and "Authorization" not in http.headers:
90
+ http.headers["Authorization"] = f"Token {self.api_key}"
91
+
92
+ def close(self) -> None:
93
+ self._http.close()
94
+
95
+ # ------------------------------------------------------------------ plumbing
96
+
97
+ def _raise(self, resp: httpx.Response) -> None:
98
+ if resp.is_success:
99
+ return
100
+ body = _body(resp)
101
+ if resp.status_code == 402:
102
+ raise InsufficientCredits(resp.status_code, body)
103
+ if resp.status_code == 403 and isinstance(body, dict) and body.get("error_type") in ("key_scope", "key_spend_limit"):
104
+ raise KeyPolicyRefused(resp.status_code, body)
105
+ raise SDCStudioError(resp.status_code, body)
106
+
107
+ def _get(self, path: str, **params: Any) -> Any:
108
+ resp = self._http.get(path, params={k: v for k, v in params.items() if v not in (None, "")})
109
+ self._raise(resp)
110
+ return _body(resp)
111
+
112
+ def _post(self, path: str, payload: dict | None = None) -> Any:
113
+ resp = self._http.post(path, json=payload or {})
114
+ self._raise(resp)
115
+ return _body(resp)
116
+
117
+ def _fetch_bytes(self, path: str) -> tuple[bytes, str]:
118
+ """GET a file route; follow the ``{"download_url"}`` pointer production answers for cloud storage, without the key."""
119
+ resp = self._http.get(path)
120
+ self._raise(resp)
121
+ if resp.headers.get("content-type", "").startswith("application/json"):
122
+ data = _body(resp)
123
+ if isinstance(data, dict) and data.get("download_url"):
124
+ request = self._http.build_request("GET", data["download_url"])
125
+ request.headers.pop("authorization", None)
126
+ stored = self._http.send(request, follow_redirects=True)
127
+ stored.raise_for_status()
128
+ return stored.content, data.get("filename") or Path(str(data["download_url"])).name
129
+ raise SDCStudioError(resp.status_code, data, "Expected a file, got JSON without a download_url.")
130
+ disposition = resp.headers.get("content-disposition", "")
131
+ name = disposition.split("filename=")[-1].strip('"; ') if "filename=" in disposition else Path(path.rstrip("/")).name
132
+ return resp.content, name
133
+
134
+ # ------------------------------------------------------------------ catalog (public)
135
+
136
+ def search_components(self, query: str = "", *, type: str | None = None, project: str | None = None,
137
+ page: int = 1, page_size: int = 50) -> dict[str, Any]:
138
+ """Published components in the public catalog: ``{"count", "results": [{ct_id, label, description, component_type, project_name, reuse_ref, ...}]}``."""
139
+ return self._get("/api/v1/catalog/components/", search=query, type=type, project=project, page=page, page_size=page_size)
140
+
141
+ def list_models(self, query: str = "", *, page: int = 1, page_size: int = 50) -> dict[str, Any]:
142
+ """Published models in the public catalog."""
143
+ return self._get("/api/v1/catalog/dms/", search=query, page=page, page_size=page_size)
144
+
145
+ def get_model(self, ct_id: str) -> dict[str, Any]:
146
+ """One published model: title, description, project, its components, and ``artifacts`` (type to route)."""
147
+ return self._get(f"/api/v1/catalog/dm/{ct_id}/")
148
+
149
+ def download_artifact(self, ct_id: str, kind: str, dest_dir: str | Path) -> Path:
150
+ """Save one artifact of a published model (``xsd``, ``xml``, ``json``, ``jsonld``, ``html``, ``ttl``, ``shacl``, ``gql``, ``zip``) and return its path."""
151
+ content, name = self._fetch_bytes(f"/api/v1/catalog/dm/{ct_id}/{kind}/")
152
+ dest = Path(dest_dir); dest.mkdir(parents=True, exist_ok=True)
153
+ path = dest / name
154
+ path.write_bytes(content)
155
+ return path
156
+
157
+ # ------------------------------------------------------------------ the modeler (key)
158
+
159
+ def modeler(self) -> dict[str, Any]:
160
+ """The key's Modeler: ``project_ct_id`` (the default project), ``projects``, preferences."""
161
+ return self._get("/api/v1/auth/modeler/")
162
+
163
+ def set_default_project(self, project_ct_id: str) -> dict[str, Any]:
164
+ resp = self._http.patch("/api/v1/auth/modeler/update/", json={"project_ct_id": project_ct_id})
165
+ self._raise(resp)
166
+ return _body(resp)
167
+
168
+ def create_project(self, name: str, description: str = "") -> dict[str, Any]:
169
+ return self._post("/api/v1/dmgen/projects/", {"name": name, "description": description})
170
+
171
+ def ensure_default_project(self, name: str = "Agent models") -> str:
172
+ """The Modeler's default project id, creating one when there is none (the PRD's 3.1.4, done client-side)."""
173
+ m = self.modeler()
174
+ if m.get("project_ct_id"):
175
+ return m["project_ct_id"]
176
+ project = self.create_project(name, "Models assembled by an agent through sdcmodeler.")
177
+ self.set_default_project(project["ct_id"])
178
+ return project["ct_id"]
179
+
180
+ def wallet(self) -> dict[str, Any]:
181
+ """``balance_credits`` and the auto-reload settings. Credits, at 1,000 per dollar."""
182
+ return self._get("/api/v1/wallet/")
183
+
184
+ def key_policy(self) -> dict[str, Any] | None:
185
+ """This key's own row from the key list (scopes, spend_limit_credits, spent_credits, expires_at), or None without a key."""
186
+ if not self.api_key:
187
+ return None
188
+ prefix = self.api_key[:KEY_PREFIX_SHOWN]
189
+ for row in self._get("/api/v1/auth/api-tokens/").get("tokens", []):
190
+ if row.get("prefix") == prefix:
191
+ return row
192
+ return None
193
+
194
+ # ------------------------------------------------------------------ building
195
+
196
+ def estimate(self, tree: dict[str, Any], title: str = "") -> dict[str, Any]:
197
+ """What the assembly would reuse, mint and cost, computed locally (``sdcmodeler.pricing``)."""
198
+ return pricing.estimate_tree(tree, title)
199
+
200
+ def assemble(self, title: str, tree: dict[str, Any], *, description: str = "",
201
+ contextual: dict | None = None, allow_retired: bool = False) -> dict[str, Any]:
202
+ """
203
+ POST ``/api/v1/dmgen/assemble/``.
204
+
205
+ Every leaf existing: the server assembles, publishes and generates
206
+ synchronously and answers 200 with the model (``mode`` ``"reuse"``).
207
+ Some leaves new: 202 with ``task_id`` and ``data_source_ct_id`` to poll
208
+ with ``job_status`` (``mode`` ``"mixed"``; the result is a draft model).
209
+ """
210
+ payload: dict[str, Any] = {"title": title, "description": description, "data": tree}
211
+ if contextual:
212
+ payload["contextual"] = contextual
213
+ if allow_retired:
214
+ payload["allow_retired"] = True
215
+ resp = self._http.post("/api/v1/dmgen/assemble/", json=payload)
216
+ if resp.status_code == 409:
217
+ raise AssemblyRefused(409, _body(resp), (_body(resp) or {}).get("error", "Assembly refused.") if isinstance(_body(resp), dict) else "Assembly refused.")
218
+ self._raise(resp)
219
+ data = _body(resp)
220
+ data = dict(data) if isinstance(data, dict) else {"result": data}
221
+ data["mode"] = "mixed" if resp.status_code == 202 else "reuse"
222
+ return data
223
+
224
+ def job_status(self, data_source_ct_id: str) -> dict[str, Any]:
225
+ """The pipeline's status for a mixed assembly or an upload (``status``: uploaded, parsing, parsed, agent_processing, modeling, completed, error, agent_error)."""
226
+ return self._get(f"/api/v1/uploader/api/data-sources/{data_source_ct_id}/workflow_status/")
227
+
228
+ def publish_model(self, ct_id: str) -> dict[str, Any]:
229
+ return self._post(f"/api/v1/dmgen/dms/{ct_id}/publish/")
230
+
231
+ def generate_package(self, ct_id: str) -> dict[str, Any]:
232
+ """Build the published model's package (free; synchronous)."""
233
+ return self._post(f"/api/v1/dmgen/dms/{ct_id}/generate/")
234
+
235
+ def download_package(self, ct_id: str, dest_dir: str | Path) -> Path:
236
+ content, name = self._fetch_bytes(f"/api/v1/dmgen/dms/{ct_id}/download_package/")
237
+ dest = Path(dest_dir); dest.mkdir(parents=True, exist_ok=True)
238
+ path = dest / name
239
+ path.write_bytes(content)
240
+ return path
241
+
242
+ def generate_app(self, ct_id: str, profile: str = "lightweight") -> dict[str, Any]:
243
+ """Generate the application (free; synchronous). ``profile`` is ``lightweight`` or ``enterprise``."""
244
+ if profile not in ("lightweight", "enterprise"):
245
+ raise ValueError("profile must be 'lightweight' or 'enterprise'")
246
+ return self._post(f"/api/v1/dmgen/dms/{ct_id}/generate_app/", {"profile": profile})
247
+
248
+ def download_app(self, ct_id: str, dest_dir: str | Path, profile: str = "lightweight") -> tuple[Path, bool | None]:
249
+ """
250
+ Save the generated application and return ``(path, charged)``.
251
+
252
+ The first download of a model by a user costs 1,500 credits; later
253
+ downloads of the same model are free (SDCStudio 4.16.0). ``charged`` is
254
+ what the server reported, or None when it streamed the file without saying.
255
+ """
256
+ route = "download_app" if profile == "lightweight" else "download_enterprise_app"
257
+ resp = self._http.get(f"/api/v1/dmgen/dms/{ct_id}/{route}/")
258
+ self._raise(resp)
259
+ charged: bool | None = None
260
+ if resp.headers.get("content-type", "").startswith("application/json"):
261
+ data = _body(resp)
262
+ charged = data.get("charged") if isinstance(data, dict) else None
263
+ request = self._http.build_request("GET", data["download_url"])
264
+ request.headers.pop("authorization", None)
265
+ stored = self._http.send(request, follow_redirects=True)
266
+ stored.raise_for_status()
267
+ content, name = stored.content, data.get("filename") or f"app-{ct_id}.zip"
268
+ else:
269
+ content, name = resp.content, f"app-{ct_id}-{profile}.zip"
270
+ dest = Path(dest_dir); dest.mkdir(parents=True, exist_ok=True)
271
+ path = dest / name
272
+ path.write_bytes(content)
273
+ return path, charged
@@ -0,0 +1,416 @@
1
+ """
2
+ ``sdcmodeler mcp``: an MCP stdio server over the SDCStudio client.
3
+
4
+ JSON-RPC 2.0 over stdio, one object per line, no MCP SDK, the way sdcvalidator,
5
+ sdcgovernance and sdcreceipt are built. The server carries the product policy
6
+ the client deliberately does not (SDCStudio's agent-path PRD, 3.2):
7
+
8
+ - **No spend without an estimate shown.** ``build_model`` takes the
9
+ ``estimate_id`` that ``estimate_model`` returned for the same title and tree
10
+ in this process; without it, or with a stale one, it refuses. The agent has
11
+ to put the number in front of the person before anything is built.
12
+ - **Stop at the key's limit.** When the key carries a spending limit, a build
13
+ whose estimate exceeds what the key may still spend is refused here, before
14
+ the server is asked.
15
+ - **Never pay.** A 402 is reported with the wallet page's address and the tool
16
+ stops. No tool takes a URL or a payment method.
17
+
18
+ Configuration is the environment the server starts with: ``SDCSTUDIO_API_KEY``
19
+ (the key from Settings, API Keys) and ``SDCSTUDIO_URL`` (the deployment; the
20
+ production service by default). The key never travels through a tool argument.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import os
26
+ import sys
27
+ from pathlib import Path
28
+ from typing import Any
29
+
30
+ from sdcmodeler import __version__
31
+ from sdcmodeler.client import (
32
+ AssemblyRefused,
33
+ InsufficientCredits,
34
+ KeyPolicyRefused,
35
+ SDCStudioClient,
36
+ SDCStudioError,
37
+ )
38
+ from sdcmodeler.pricing import DOWNLOAD_APP_CREDITS
39
+
40
+ JSONRPC_VERSION = "2.0"
41
+ SUPPORTED_PROTOCOL_VERSIONS = ("2025-06-18", "2025-11-25")
42
+ MCP_PROTOCOL_VERSION = SUPPORTED_PROTOCOL_VERSIONS[-1]
43
+ SERVER_NAME = "sdcmodeler"
44
+ SERVER_VERSION = __version__
45
+
46
+ _client: SDCStudioClient | None = None
47
+ #: estimate_id -> the estimate, for this process: a build must follow an estimate the person saw.
48
+ _estimates: dict[str, dict[str, Any]] = {}
49
+ _output_dir: Path = Path(os.environ.get("SDCMODELER_OUTPUT_DIR", ".")).resolve()
50
+
51
+
52
+ def configure(client: SDCStudioClient | None = None, output_dir: str | Path | None = None) -> SDCStudioClient:
53
+ """Bind the client (and where downloads land) for this process; tests pass their own."""
54
+ global _client, _output_dir
55
+ _client = client or SDCStudioClient()
56
+ if output_dir is not None:
57
+ _output_dir = Path(output_dir).resolve()
58
+ _estimates.clear()
59
+ return _client
60
+
61
+
62
+ def get_client() -> SDCStudioClient:
63
+ return _client if _client is not None else configure()
64
+
65
+
66
+ TOOLS: list[dict[str, Any]] = [
67
+ {
68
+ "name": "search_components",
69
+ "description": (
70
+ "Search SDCStudio's public catalog of published components by label, with optional "
71
+ "type (xdstring, xdcount, xdquantity, xdtemporal, cluster, party, ...) and project. "
72
+ "Reuse first: a published component that fits is free to assemble; minting a new one "
73
+ "costs 100 credits. Returns ct_id, label, description, component_type, project_name "
74
+ "and reuse_ref for each result. Free; no key needed."
75
+ ),
76
+ "inputSchema": {
77
+ "type": "object",
78
+ "properties": {
79
+ "query": {"type": "string", "description": "Words from the label or description."},
80
+ "type": {"type": "string", "description": "Optional component type to filter by."},
81
+ "project": {"type": "string", "description": "Optional project name to filter by, e.g. a public library."},
82
+ "page": {"type": "integer", "default": 1},
83
+ "page_size": {"type": "integer", "default": 25},
84
+ },
85
+ "required": ["query"],
86
+ },
87
+ },
88
+ {
89
+ "name": "list_models",
90
+ "description": "Published data models in the public catalog, by words in the title. Free.",
91
+ "inputSchema": {
92
+ "type": "object",
93
+ "properties": {"query": {"type": "string", "default": ""}, "page": {"type": "integer", "default": 1},
94
+ "page_size": {"type": "integer", "default": 25}},
95
+ },
96
+ },
97
+ {
98
+ "name": "get_model",
99
+ "description": (
100
+ "One published data model: title, description, project, its components, and the artifact "
101
+ "routes (xsd, xml, json, jsonld, html, ttl, shacl, gql, zip). The XSD is the contract every "
102
+ "record validates against. Free."
103
+ ),
104
+ "inputSchema": {"type": "object", "properties": {"ct_id": {"type": "string"}}, "required": ["ct_id"]},
105
+ },
106
+ {
107
+ "name": "estimate_model",
108
+ "description": (
109
+ "What assembling this model would reuse, mint and cost, in credits, computed before any "
110
+ "money moves. Takes the title and the assembly tree ({label, components: [{ct_id} to reuse "
111
+ "or {label, data_type} to mint], clusters: [...]}). Returns estimate_id, the reused and "
112
+ "minted leaves, problems in the tree, and total_credits (500 for the model plus 100 per "
113
+ "mint). Show the result to the person; build_model needs the estimate_id. Free."
114
+ ),
115
+ "inputSchema": {
116
+ "type": "object",
117
+ "properties": {
118
+ "title": {"type": "string"},
119
+ "tree": {"type": "object", "description": "The assembly tree."},
120
+ },
121
+ "required": ["title", "tree"],
122
+ },
123
+ },
124
+ {
125
+ "name": "build_model",
126
+ "description": (
127
+ "Assemble and publish the model the person estimated and approved. Needs the estimate_id "
128
+ "from estimate_model for the same title and tree; refuses otherwise, and refuses when the "
129
+ "estimate exceeds what the key may still spend. Spends credits: 500 for the model plus "
130
+ "100 per minted component. With every leaf existing the model is published and its "
131
+ "package generated at once (result has ct_id and artifacts); with new leaves the "
132
+ "pipeline runs and the result has a data_source_ct_id to poll with job_status. A 402 "
133
+ "means the wallet needs funding at the wallet page; report it and stop."
134
+ ),
135
+ "inputSchema": {
136
+ "type": "object",
137
+ "properties": {
138
+ "estimate_id": {"type": "string"},
139
+ "title": {"type": "string"},
140
+ "tree": {"type": "object"},
141
+ "description": {"type": "string", "default": ""},
142
+ "contextual": {"type": "object", "description": "Optional contextual component references (audit, attestation, party, subject, provider, participation, protocol, workflow, acs)."},
143
+ },
144
+ "required": ["estimate_id", "title", "tree"],
145
+ },
146
+ },
147
+ {
148
+ "name": "job_status",
149
+ "description": "The pipeline status of a mixed build (data_source_ct_id from build_model): uploaded, parsing, parsed, agent_processing, modeling, completed, error, agent_error. Free.",
150
+ "inputSchema": {"type": "object", "properties": {"data_source_ct_id": {"type": "string"}}, "required": ["data_source_ct_id"]},
151
+ },
152
+ {
153
+ "name": "generate_app",
154
+ "description": (
155
+ "Generate a published model's application (lightweight or enterprise profile; a Django "
156
+ "stack on the model package, one example of implementing on it) and download it into the "
157
+ "server's output directory. The first download of a model by this user costs 1,500 "
158
+ "credits; later downloads of the same model are free. Needs confirm_charge true, after the "
159
+ "person has agreed. Prefer the model package (get_model's artifacts) when the feature "
160
+ "lives inside an existing application."
161
+ ),
162
+ "inputSchema": {
163
+ "type": "object",
164
+ "properties": {
165
+ "ct_id": {"type": "string"},
166
+ "profile": {"type": "string", "enum": ["lightweight", "enterprise"], "default": "lightweight"},
167
+ "confirm_charge": {"type": "boolean", "default": False},
168
+ },
169
+ "required": ["ct_id"],
170
+ },
171
+ },
172
+ {
173
+ "name": "wallet",
174
+ "description": "The wallet balance in credits and this key's policy: scopes, spending limit, what it has spent, expiry. Free.",
175
+ "inputSchema": {"type": "object", "properties": {}},
176
+ },
177
+ ]
178
+
179
+
180
+ def _string(args: dict, name: str, *, required: bool = False, default: str = "") -> str:
181
+ value = args.get(name, default)
182
+ if value is None:
183
+ value = default
184
+ if not isinstance(value, str):
185
+ raise ValueError(f"`{name}` must be a string.")
186
+ if required and not value.strip():
187
+ raise ValueError(f"`{name}` is required.")
188
+ return value
189
+
190
+
191
+ def _object(args: dict, name: str, *, required: bool = False) -> dict | None:
192
+ value = args.get(name)
193
+ if value is None:
194
+ if required:
195
+ raise ValueError(f"`{name}` is required.")
196
+ return None
197
+ if not isinstance(value, dict):
198
+ raise ValueError(f"`{name}` must be an object.")
199
+ return value
200
+
201
+
202
+ def _handle_search_components(args: dict) -> Any:
203
+ c = get_client()
204
+ return c.search_components(_string(args, "query", required=True), type=_string(args, "type") or None,
205
+ project=_string(args, "project") or None, page=int(args.get("page") or 1),
206
+ page_size=int(args.get("page_size") or 25))
207
+
208
+
209
+ def _handle_list_models(args: dict) -> Any:
210
+ return get_client().list_models(_string(args, "query"), page=int(args.get("page") or 1), page_size=int(args.get("page_size") or 25))
211
+
212
+
213
+ def _handle_get_model(args: dict) -> Any:
214
+ return get_client().get_model(_string(args, "ct_id", required=True))
215
+
216
+
217
+ def _handle_estimate_model(args: dict) -> Any:
218
+ tree = _object(args, "tree", required=True)
219
+ estimate = get_client().estimate(tree, _string(args, "title", required=True))
220
+ _estimates[estimate["estimate_id"]] = estimate
221
+ policy = _policy_or_none()
222
+ if policy and policy.get("spend_limit_credits") is not None:
223
+ remaining = max(0, policy["spend_limit_credits"] - policy.get("spent_credits", 0))
224
+ estimate["key_remaining_credits"] = remaining
225
+ estimate["within_key_limit"] = estimate["total_credits"] <= remaining
226
+ return estimate
227
+
228
+
229
+ def _policy_or_none() -> dict | None:
230
+ try:
231
+ return get_client().key_policy()
232
+ except SDCStudioError:
233
+ return None
234
+
235
+
236
+ def _handle_build_model(args: dict) -> Any:
237
+ estimate_id = _string(args, "estimate_id", required=True)
238
+ title = _string(args, "title", required=True)
239
+ tree = _object(args, "tree", required=True)
240
+ current = get_client().estimate(tree, title)
241
+ shown = _estimates.get(estimate_id)
242
+ if shown is None or current["estimate_id"] != estimate_id:
243
+ raise ValueError(
244
+ "build_model needs the estimate_id that estimate_model returned for this exact title and tree "
245
+ "in this session; run estimate_model, show the person the cost, then build."
246
+ )
247
+ if current["problems"]:
248
+ raise ValueError("The tree has problems: " + "; ".join(current["problems"]))
249
+ policy = _policy_or_none()
250
+ if policy and policy.get("spend_limit_credits") is not None:
251
+ remaining = max(0, policy["spend_limit_credits"] - policy.get("spent_credits", 0))
252
+ if current["total_credits"] > remaining:
253
+ raise ValueError(
254
+ f"This key may still spend {remaining} credits and the build needs {current['total_credits']}. "
255
+ "Ask the person for a key with a higher limit, or to run the build themselves."
256
+ )
257
+ result = get_client().assemble(title, tree, description=_string(args, "description"), contextual=_object(args, "contextual"))
258
+ result["estimate"] = current
259
+ return result
260
+
261
+
262
+ def _handle_job_status(args: dict) -> Any:
263
+ return get_client().job_status(_string(args, "data_source_ct_id", required=True))
264
+
265
+
266
+ def _handle_generate_app(args: dict) -> Any:
267
+ ct_id = _string(args, "ct_id", required=True)
268
+ profile = _string(args, "profile", default="lightweight") or "lightweight"
269
+ if not args.get("confirm_charge"):
270
+ raise ValueError(
271
+ f"generate_app downloads the application, which costs {DOWNLOAD_APP_CREDITS} credits the first time "
272
+ "this user downloads this model (free after that). Tell the person, and call again with confirm_charge true."
273
+ )
274
+ c = get_client()
275
+ generated = c.generate_app(ct_id, profile)
276
+ path, charged = c.download_app(ct_id, _output_dir, profile)
277
+ return {"generated": generated, "path": str(path), "charged": charged, "profile": profile}
278
+
279
+
280
+ def _handle_wallet(args: dict) -> Any:
281
+ c = get_client()
282
+ return {"wallet": c.wallet(), "key": c.key_policy()}
283
+
284
+
285
+ TOOL_HANDLERS = {
286
+ "search_components": _handle_search_components,
287
+ "list_models": _handle_list_models,
288
+ "get_model": _handle_get_model,
289
+ "estimate_model": _handle_estimate_model,
290
+ "build_model": _handle_build_model,
291
+ "job_status": _handle_job_status,
292
+ "generate_app": _handle_generate_app,
293
+ "wallet": _handle_wallet,
294
+ }
295
+
296
+
297
+ def _jsonrpc_response(id: Any, result: Any) -> dict:
298
+ return {"jsonrpc": JSONRPC_VERSION, "id": id, "result": result}
299
+
300
+
301
+ def _jsonrpc_error(id: Any, code: int, message: str, data: Any = None) -> dict:
302
+ err: dict[str, Any] = {"code": code, "message": message}
303
+ if data is not None:
304
+ err["data"] = data
305
+ return {"jsonrpc": JSONRPC_VERSION, "id": id, "error": err}
306
+
307
+
308
+ def _tool_error(req_id: Any, text: str) -> dict:
309
+ # SEP-1303: execution and input-validation failures are tool errors, not
310
+ # protocol errors, so the calling model sees them and can correct itself.
311
+ return _jsonrpc_response(req_id, {"content": [{"type": "text", "text": text}], "isError": True})
312
+
313
+
314
+ def _handle_request(request: Any) -> dict | None:
315
+ """One JSON-RPC 2.0 request; a response, or None for a notification. Malformed input is answered, never fatal."""
316
+ if not isinstance(request, dict):
317
+ return _jsonrpc_error(None, -32600, "Invalid Request: a JSON-RPC request is an object")
318
+ req_id = request.get("id")
319
+ if not isinstance(req_id, (str, int, type(None))):
320
+ return _jsonrpc_error(None, -32600, "Invalid Request: id must be a string, a number or null")
321
+ method = request.get("method", "")
322
+ if not isinstance(method, str):
323
+ return _jsonrpc_error(req_id, -32600, "Invalid Request: method must be a string")
324
+ params = request.get("params") or {}
325
+ if not isinstance(params, dict):
326
+ return _jsonrpc_error(req_id, -32600, "Invalid Request: params must be an object")
327
+
328
+ if method == "initialize":
329
+ requested = params.get("protocolVersion")
330
+ negotiated = requested if requested in SUPPORTED_PROTOCOL_VERSIONS else MCP_PROTOCOL_VERSION
331
+ has_key = bool(get_client().api_key)
332
+ return _jsonrpc_response(req_id, {
333
+ "protocolVersion": negotiated,
334
+ "capabilities": {"tools": {"listChanged": False}},
335
+ "serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION},
336
+ "instructions": (
337
+ "The modeler's client for SDCStudio. Search the public catalog first and reuse published "
338
+ "components; estimate before you build and show the person the cost; build only with the "
339
+ "estimate_id you showed; prefer the model package over the generated application when the "
340
+ "feature lives inside an existing application. A 402 means the person funds the wallet at "
341
+ f"{get_client().base_url}/app/wallet; never try to pay. "
342
+ + ("A key is configured, so building and downloading are available within its policy."
343
+ if has_key else "No key is configured: the catalog and estimates work; building needs SDCSTUDIO_API_KEY.")
344
+ ),
345
+ })
346
+ if method == "notifications/initialized":
347
+ return None
348
+ if method == "tools/list":
349
+ return _jsonrpc_response(req_id, {"tools": TOOLS})
350
+ if method == "tools/call":
351
+ tool_name = params.get("name", "")
352
+ tool_args = params.get("arguments") or {}
353
+ if not isinstance(tool_name, str) or not isinstance(tool_args, dict):
354
+ return _jsonrpc_error(req_id, -32602, "Invalid params: name must be a string and arguments an object")
355
+ handler = TOOL_HANDLERS.get(tool_name)
356
+ if handler is None:
357
+ return _jsonrpc_error(req_id, -32601, f"Unknown tool: {tool_name}")
358
+ try:
359
+ result = handler(tool_args)
360
+ return _jsonrpc_response(req_id, {"content": [{"type": "text", "text": json.dumps(result, default=str)}]})
361
+ except InsufficientCredits as exc:
362
+ return _tool_error(req_id, (
363
+ f"Insufficient credits: this needs {exc.estimated_cost_credits} credits and the wallet has "
364
+ f"{exc.balance_credits}. The person funds the wallet at {get_client().base_url}/app/wallet; stop here."
365
+ ))
366
+ except KeyPolicyRefused as exc:
367
+ return _tool_error(req_id, f"The API key refused this ({exc.error_type}): {exc}")
368
+ except (AssemblyRefused, SDCStudioError, ValueError) as exc:
369
+ return _tool_error(req_id, f"Tool execution error: {exc}")
370
+ except Exception as exc: # a defect in this server, not in the caller's input
371
+ return _tool_error(req_id, (
372
+ f"Tool execution error: the server could not process this input ({type(exc).__name__}). "
373
+ "This is a defect worth reporting at https://github.com/Axius-SDC/sdcmodeler/issues"
374
+ ))
375
+ if method == "ping":
376
+ return _jsonrpc_response(req_id, {})
377
+ if req_id is not None:
378
+ return _jsonrpc_error(req_id, -32601, f"Method not found: {method}")
379
+ return None
380
+
381
+
382
+ def run_stdio() -> None:
383
+ """Read JSON-RPC 2.0 messages from stdin, one per line; write responses to stdout."""
384
+ for line in sys.stdin:
385
+ line = line.strip()
386
+ if not line:
387
+ continue
388
+ try:
389
+ request = json.loads(line)
390
+ except json.JSONDecodeError as exc:
391
+ sys.stdout.write(json.dumps(_jsonrpc_error(None, -32700, f"Parse error: {exc}")) + "\n")
392
+ sys.stdout.flush()
393
+ continue
394
+ response = _handle_request(request)
395
+ if response is not None:
396
+ sys.stdout.write(json.dumps(response) + "\n")
397
+ sys.stdout.flush()
398
+
399
+
400
+ def main(argv: list[str] | None = None) -> None:
401
+ """Entry point of ``sdcmodeler mcp``: start the stdio server with the environment's key and URL."""
402
+ import argparse
403
+
404
+ parser = argparse.ArgumentParser(prog="sdcmodeler mcp", description="MCP stdio server over the SDCStudio client.")
405
+ parser.add_argument("--url", default=None, help="SDCStudio base URL (default: $SDCSTUDIO_URL or the production service).")
406
+ parser.add_argument("--output-dir", default=None, help="Where downloads land (default: $SDCMODELER_OUTPUT_DIR or the current directory).")
407
+ args = parser.parse_args(argv)
408
+ configure(SDCStudioClient(base_url=args.url), output_dir=args.output_dir)
409
+ if sys.stdin.isatty():
410
+ sys.stderr.write("sdcmodeler mcp: reading JSON-RPC 2.0 on stdin (Ctrl-D to stop)\n")
411
+ sys.stderr.flush()
412
+ run_stdio()
413
+
414
+
415
+ if __name__ == "__main__":
416
+ main()
sdcmodeler/pricing.py ADDED
@@ -0,0 +1,71 @@
1
+ """
2
+ What a model costs, computed locally before any call that spends.
3
+
4
+ SDCStudio's prices (Terms of Service, section 6; ``docs/user-guides/wallet-billing.md``):
5
+ 1,000 credits per dollar; minting a component 100 credits; assembling a model
6
+ 500; downloading an application 1,500, once per user per model since 4.16.0;
7
+ settling a record 1,000. The estimate below resolves an assembly tree the way
8
+ the server does: a leaf with ``ct_id`` is reused and free, a leaf with ``label``
9
+ and ``data_type`` is minted and billable. The server's own estimate endpoint,
10
+ when it exists, confirms this; until then this is the number an agent shows
11
+ the person before it builds.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import json
17
+ from typing import Any
18
+
19
+ CREDITS_PER_USD = 1000
20
+ MINT_COMPONENT_CREDITS = 100
21
+ ASSEMBLE_MODEL_CREDITS = 500
22
+ DOWNLOAD_APP_CREDITS = 1500
23
+ SETTLE_CREDITS = 1000
24
+
25
+
26
+ def _walk(node: dict[str, Any], path: str, reuse: list, mint: list, problems: list) -> None:
27
+ for comp in node.get("components", []) or []:
28
+ label = comp.get("label", "")
29
+ if comp.get("ct_id"):
30
+ reuse.append({"path": f"{path}/{label or comp['ct_id']}", "ct_id": comp["ct_id"], "label": label})
31
+ elif label and comp.get("data_type"):
32
+ mint.append({"path": f"{path}/{label}", "label": label, "data_type": comp["data_type"]})
33
+ else:
34
+ problems.append(f"{path}: a component needs ct_id (reuse) or label and data_type (mint): {comp!r}")
35
+ for cluster in node.get("clusters", []) or []:
36
+ name = cluster.get("label", "")
37
+ if cluster.get("ct_id"):
38
+ reuse.append({"path": f"{path}/{name or cluster['ct_id']}", "ct_id": cluster["ct_id"], "label": name, "cluster": True})
39
+ continue
40
+ if not name:
41
+ problems.append(f"{path}: a cluster needs a label")
42
+ _walk(cluster, f"{path}/{name}", reuse, mint, problems)
43
+
44
+
45
+ def estimate_tree(tree: dict[str, Any], title: str = "") -> dict[str, Any]:
46
+ """
47
+ Resolve an assembly tree into what is reused, what would be minted, and the cost in credits.
48
+
49
+ Returns ``{"estimate_id", "reuse", "mint", "problems", "model_credits",
50
+ "mint_credits", "total_credits", "mode"}``. ``estimate_id`` is the first
51
+ twelve hex characters of the SHA-256 of the canonical tree and title; the
52
+ MCP server's ``build_model`` requires it, so a build always follows the
53
+ estimate the person saw.
54
+ """
55
+ reuse: list = []
56
+ mint: list = []
57
+ problems: list = []
58
+ _walk(tree, tree.get("label", "root"), reuse, mint, problems)
59
+ mint_credits = MINT_COMPONENT_CREDITS * len(mint)
60
+ canonical = json.dumps({"title": title, "tree": tree}, sort_keys=True, separators=(",", ":"), default=str)
61
+ return {
62
+ "estimate_id": hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:12],
63
+ "title": title,
64
+ "reuse": reuse,
65
+ "mint": mint,
66
+ "problems": problems,
67
+ "model_credits": ASSEMBLE_MODEL_CREDITS,
68
+ "mint_credits": mint_credits,
69
+ "total_credits": ASSEMBLE_MODEL_CREDITS + mint_credits,
70
+ "mode": "mixed" if mint else "reuse",
71
+ }
@@ -0,0 +1,130 @@
1
+ Metadata-Version: 2.4
2
+ Name: sdcmodeler
3
+ Version: 4.0.0
4
+ Summary: The modeler's client for SDCStudio: search the catalog, estimate, assemble and publish SDC4 data models, generate applications; a CLI and an MCP server over one client
5
+ Author: Axius SDC, Inc.
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Repository, https://github.com/Axius-SDC/sdcmodeler
8
+ Project-URL: Documentation, https://axius-sdc.com/docs/
9
+ Project-URL: Issues, https://github.com/Axius-SDC/sdcmodeler/issues
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Software Development :: Libraries
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: httpx>=0.27
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest>=8; extra == "dev"
24
+ Requires-Dist: pytest-cov; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # sdcmodeler
28
+
29
+ <!-- mcp-name: io.github.Axius-SDC/sdcmodeler -->
30
+
31
+ **The modeler's client for SDCStudio.** Search the public catalog, estimate, assemble and publish an SDC4 data model, generate its package and an application. A Python client with httpx as its only dependency, a CLI, and `sdcmodeler mcp`, an MCP server for any agent.
32
+
33
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
34
+ [![Python](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
35
+
36
+ ## Why
37
+
38
+ An agent that builds a feature decides a data model at that moment. With sdcmodeler the data is modeled in SDC by default: the agent searches the catalog first, reuses published components wherever one fits, mints only what is new, publishes the model, and takes the package. The result is interoperable because it is composed from shared, published components, and verifiable because every record validates against a published schema.
39
+
40
+ The name follows the role pattern of the other Semantic Data Charter servers: sdcvalidator validates, sdcgovernance governs, sdcreader reads, sdcmodeler models. It also names what SDCStudio calls every user: a Modeler.
41
+
42
+ ## Install
43
+
44
+ ```bash
45
+ pip install sdcmodeler
46
+ ```
47
+
48
+ The catalog and estimates need no account. Building needs an SDCStudio API key, created in Settings, API Keys, with the scopes and spending limit the holder should have:
49
+
50
+ ```bash
51
+ export SDCSTUDIO_API_KEY=sdcs_...
52
+ ```
53
+
54
+ ## The three layers
55
+
56
+ ### The client
57
+
58
+ ```python
59
+ from sdcmodeler import SDCStudioClient
60
+
61
+ c = SDCStudioClient() # key from $SDCSTUDIO_API_KEY, URL from $SDCSTUDIO_URL
62
+ hits = c.search_components("blood pressure", type="xdquantity")
63
+ tree = {
64
+ "label": "Vitals",
65
+ "components": [
66
+ {"ct_id": hits["results"][0]["ct_id"]}, # reuse: free
67
+ {"label": "Pulse", "data_type": "XdCount"}, # mint: 100 credits
68
+ ],
69
+ "clusters": [],
70
+ }
71
+ print(c.estimate(tree, "Vitals")) # reuse, mint, total_credits, estimate_id; no call that spends
72
+ result = c.assemble("Vitals", tree) # 500 credits plus the mints
73
+ ```
74
+
75
+ Every leaf existing: the server assembles, publishes and generates the package in one call (`result["mode"] == "reuse"`). Some leaves new: the pipeline runs and `result["data_source_ct_id"]` is polled with `c.job_status(...)`.
76
+
77
+ A 402 is `InsufficientCredits` with the numbers in credits. A 403 from the key's policy (no `spend` scope, or past its limit) is `KeyPolicyRefused`. The client never funds a wallet; a person does that at the wallet page.
78
+
79
+ ### The CLI
80
+
81
+ ```bash
82
+ sdcmodeler search "blood pressure" --type xdquantity
83
+ sdcmodeler models "patient"
84
+ sdcmodeler model <ct_id>
85
+ sdcmodeler artifact <ct_id> xsd --dir ./schemas
86
+ sdcmodeler estimate tree.json --title "Vitals"
87
+ sdcmodeler build tree.json --title "Vitals"
88
+ sdcmodeler app <ct_id> --profile lightweight --dir ./apps
89
+ sdcmodeler wallet
90
+ ```
91
+
92
+ ### The MCP server
93
+
94
+ ```bash
95
+ sdcmodeler mcp
96
+ ```
97
+
98
+ A JSON-RPC 2.0 stdio server, no SDK, the way sdcvalidator and sdcgovernance are built. A client configuration needs only:
99
+
100
+ ```json
101
+ {"command": "uvx", "args": ["sdcmodeler", "mcp"], "env": {"SDCSTUDIO_API_KEY": "sdcs_..."}}
102
+ ```
103
+
104
+ | Tool | Does | Spends |
105
+ |---|---|---|
106
+ | `search_components` | the public catalog by label, type and project | no |
107
+ | `list_models`, `get_model` | published models and their artifact routes | no |
108
+ | `estimate_model` | what a tree would reuse, mint and cost; returns `estimate_id` | no |
109
+ | `build_model` | assemble and publish; needs the `estimate_id` the person saw; refuses past the key's limit | yes |
110
+ | `job_status` | the pipeline for a mixed build | no |
111
+ | `generate_app` | generate and download the application; needs `confirm_charge`; 1,500 credits the first time, free after | yes |
112
+ | `wallet` | balance in credits and the key's policy | no |
113
+
114
+ **The policy lives in the server.** No spend without an estimate shown: `build_model` takes the `estimate_id` that `estimate_model` returned for the same title and tree in this process. Stop at the key's limit: a build whose estimate exceeds what the key may still spend is refused before the server is asked. Never pay: a 402 is reported with the wallet page's address and the tool stops. No tool takes a URL, a key or a payment method as an argument; the key is the environment the server starts with.
115
+
116
+ ## The package or the application
117
+
118
+ `get_model` names the artifacts: the XSD 1.1 schema, the instance template, JSON, JSON-LD, SHACL, HTML, GraphQL. The package is a contract with no runtime attached; a feature inside an existing application implements on it, in any language, validating every record locally with [sdcvalidator](https://pypi.org/project/sdcvalidator/). The generated application (lightweight or enterprise profile) is a Django implementation on the same package, right when the feature is a new service. [CordovaOS](https://github.com/Axius-SDC/CordovaOS) is ten of them sharing data with zero integration code.
119
+
120
+ ## What is not here
121
+
122
+ Validation (sdcvalidator's server), governance (sdcgovernance's), receipt verification (sdcreceipt's) and bringing existing data across (sdc-agents) are their own registered servers. sdcmodeler composes with them; it does not re-implement them.
123
+
124
+ ## Release
125
+
126
+ Two steps: merge to `main`, then push the tag `v<version>` matching `pyproject.toml`. `release.yml` runs the tests, builds, publishes to PyPI by trusted publisher and to the MCP registry.
127
+
128
+ ## License
129
+
130
+ Apache License 2.0. Copyright Axius SDC, Inc.
@@ -0,0 +1,11 @@
1
+ sdcmodeler/__init__.py,sha256=nDIW-1X4muBzJedH3s8xds5TtSPK_RSEHvm9d7vNnks,1352
2
+ sdcmodeler/cli.py,sha256=5OlusbAZi-PuF9D_SZhiMhBn6OIt7pYP6YqIlo4x6t8,4806
3
+ sdcmodeler/client.py,sha256=qcjVNtYP-7Fhp62XWBVb9VeiqHuXAvpp9wj0Urs_Z7I,13320
4
+ sdcmodeler/mcp_server.py,sha256=_Oq5IjuTu_TufBYyVkSvT7jTO8vPNc8RoUdSrjiq7xM,19247
5
+ sdcmodeler/pricing.py,sha256=n-gGIdNISAEiSY3L954lm5tb2PztA15reR5-wwuF334,3126
6
+ sdcmodeler-4.0.0.dist-info/licenses/LICENSE,sha256=k6ZwWK2J5euOr72Qnt44l_-rfytPgOD-sP-MadaxbQI,10783
7
+ sdcmodeler-4.0.0.dist-info/METADATA,sha256=YvN2GIJIw-AcoFe_nX5abVjNl0R_xyzAKdLisM6E0hQ,6640
8
+ sdcmodeler-4.0.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
9
+ sdcmodeler-4.0.0.dist-info/entry_points.txt,sha256=-gI70_fBFecDUd3E-scBxBl1ahEpLZXH7Nmv_j2f9t4,51
10
+ sdcmodeler-4.0.0.dist-info/top_level.txt,sha256=6c7japq5hRWIG0xX8ltQGtFpp6U9F8-70-iF2aOPO7k,11
11
+ sdcmodeler-4.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ sdcmodeler = sdcmodeler.cli:main
@@ -0,0 +1,190 @@
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, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 Semantic Data Charter Foundation
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1 @@
1
+ sdcmodeler