daz-mcp-server 0.8.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.
Files changed (41) hide show
  1. daz_mcp_server/__init__.py +0 -0
  2. daz_mcp_server/_client.py +119 -0
  3. daz_mcp_server/_compat.py +105 -0
  4. daz_mcp_server/_emotions.py +134 -0
  5. daz_mcp_server/_errors.py +48 -0
  6. daz_mcp_server/_guides.py +30 -0
  7. daz_mcp_server/_mcp.py +154 -0
  8. daz_mcp_server/_profile.py +26 -0
  9. daz_mcp_server/_registry.py +9088 -0
  10. daz_mcp_server/_ui_automation.py +214 -0
  11. daz_mcp_server/dazscript_docs.json +70 -0
  12. daz_mcp_server/genesis_bones.json +104 -0
  13. daz_mcp_server/guides/actors.md +36 -0
  14. daz_mcp_server/guides/cinema.md +26 -0
  15. daz_mcp_server/guides/daz_studio.md +123 -0
  16. daz_mcp_server/guides/dazscript.md +315 -0
  17. daz_mcp_server/guides/recipe.md +111 -0
  18. daz_mcp_server/guides/scene.md +60 -0
  19. daz_mcp_server/server.py +50 -0
  20. daz_mcp_server/tools/__init__.py +22 -0
  21. daz_mcp_server/tools/animation.py +390 -0
  22. daz_mcp_server/tools/camera_light.py +698 -0
  23. daz_mcp_server/tools/cinematic.py +2553 -0
  24. daz_mcp_server/tools/content.py +443 -0
  25. daz_mcp_server/tools/figure.py +464 -0
  26. daz_mcp_server/tools/hair.py +103 -0
  27. daz_mcp_server/tools/material.py +341 -0
  28. daz_mcp_server/tools/morph.py +701 -0
  29. daz_mcp_server/tools/recipe.py +165 -0
  30. daz_mcp_server/tools/render.py +803 -0
  31. daz_mcp_server/tools/scene.py +462 -0
  32. daz_mcp_server/tools/spatial.py +446 -0
  33. daz_mcp_server/tools/transform.py +401 -0
  34. daz_mcp_server/tools/utility.py +938 -0
  35. daz_mcp_server/tools/wardrobe.py +675 -0
  36. daz_mcp_server/tools/workflow.py +179 -0
  37. daz_mcp_server-0.8.0.dist-info/METADATA +3838 -0
  38. daz_mcp_server-0.8.0.dist-info/RECORD +41 -0
  39. daz_mcp_server-0.8.0.dist-info/WHEEL +4 -0
  40. daz_mcp_server-0.8.0.dist-info/entry_points.txt +2 -0
  41. daz_mcp_server-0.8.0.dist-info/licenses/LICENSE +21 -0
File without changes
@@ -0,0 +1,119 @@
1
+ """Singleton accessors for dazpy clients and the separate content browser."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import os
6
+ from typing import Callable, TypeVar
7
+
8
+ import httpx
9
+ from dazpy import DazClient, DazScene
10
+ from dazpy.aio import AsyncDazClient
11
+
12
+ _T = TypeVar("_T")
13
+
14
+ # ---------------------------------------------------------------------------
15
+ # Configuration
16
+ # ---------------------------------------------------------------------------
17
+
18
+ DAZ_HOST: str = os.environ.get("DAZ_HOST", "localhost")
19
+ DAZ_PORT: int = int(os.environ.get("DAZ_PORT", "18811"))
20
+ DAZ_TIMEOUT: float = float(os.environ.get("DAZ_TIMEOUT", "30.0"))
21
+
22
+ CONTENT_BROWSER_URL: str = os.environ.get("DAZ_CONTENT_BROWSER_URL", "http://localhost:8080")
23
+
24
+ TOKEN_FILE: str = os.path.join(os.path.expanduser("~"), ".daz3d", "dazscriptserver_token.txt")
25
+
26
+
27
+ def _load_token_from_file() -> str:
28
+ try:
29
+ with open(TOKEN_FILE) as f:
30
+ return f.read().strip()
31
+ except OSError:
32
+ return ""
33
+
34
+
35
+ DAZ_API_TOKEN: str = os.environ.get("DAZ_API_TOKEN") or _load_token_from_file()
36
+
37
+ # ---------------------------------------------------------------------------
38
+ # Shared protocol/content clients — set/cleared by the server lifespan
39
+ # ---------------------------------------------------------------------------
40
+
41
+ # Mutable singleton state reassigned via `global` in set_async_daz_client()/
42
+ # set_content_browser_client() below, not a real constant; pylint's naming checker
43
+ # treats any module-scope scalar assignment as one regardless of case.
44
+ _async_daz_client: AsyncDazClient | None = None # pylint: disable=invalid-name
45
+ _content_browser_client: httpx.AsyncClient | None = None # pylint: disable=invalid-name
46
+
47
+
48
+ def set_async_daz_client(client: AsyncDazClient | None) -> None:
49
+ """Set or clear the sole async Daz Script Server protocol client."""
50
+ global _async_daz_client # pylint: disable=global-statement
51
+ _async_daz_client = client
52
+
53
+
54
+ def set_content_browser_client(client: httpx.AsyncClient | None) -> None:
55
+ """Set (or clear) the shared content-browser httpx client."""
56
+ global _content_browser_client # pylint: disable=global-statement
57
+ _content_browser_client = client
58
+
59
+
60
+ def get_async_daz_client() -> AsyncDazClient:
61
+ """Return the shared async dazpy client once lifespan has initialized it."""
62
+ if _async_daz_client is None:
63
+ raise RuntimeError("AsyncDazClient not initialised — server lifespan not running")
64
+ return _async_daz_client
65
+
66
+
67
+ def get_content_browser_client() -> httpx.AsyncClient:
68
+ """Return the shared content-browser httpx client, once the server lifespan has set it."""
69
+ if _content_browser_client is None:
70
+ raise RuntimeError("Content browser client not initialised — server lifespan not running")
71
+ return _content_browser_client
72
+
73
+
74
+ # ---------------------------------------------------------------------------
75
+ # dazpy singletons — created lazily on first access
76
+ # ---------------------------------------------------------------------------
77
+
78
+ _daz_client: DazClient | None = None # pylint: disable=invalid-name
79
+ _daz_scene: DazScene | None = None # pylint: disable=invalid-name
80
+
81
+
82
+ def get_daz_client() -> DazClient:
83
+ """Return the singleton DazClient, creating it on first access."""
84
+ global _daz_client # pylint: disable=global-statement
85
+ if _daz_client is None:
86
+ from ._compat import record # pylint: disable=import-outside-toplevel # _compat imports this module
87
+
88
+ _daz_client = DazClient(
89
+ host=DAZ_HOST,
90
+ port=DAZ_PORT,
91
+ token=DAZ_API_TOKEN or None,
92
+ timeout=DAZ_TIMEOUT,
93
+ on_version_check=record,
94
+ )
95
+ return _daz_client
96
+
97
+
98
+ def get_scene() -> DazScene:
99
+ """Return the singleton DazScene, creating it on first access."""
100
+ global _daz_scene # pylint: disable=global-statement
101
+ if _daz_scene is None:
102
+ _daz_scene = DazScene(get_daz_client())
103
+ return _daz_scene
104
+
105
+
106
+ def set_scene(scene: DazScene | None) -> None:
107
+ """Override the DazScene singleton — for injecting a test double.
108
+
109
+ Without this, tests that mock only the httpx client (e.g. via respx) can
110
+ silently fall through to a real DazScene/DazClient connection for any tool
111
+ that uses get_scene()/run_dazpy(), reaching a live DAZ Studio instance.
112
+ """
113
+ global _daz_scene # pylint: disable=global-statement
114
+ _daz_scene = scene
115
+
116
+
117
+ async def run_dazpy(fn: Callable[[], _T]) -> _T:
118
+ """Run a synchronous dazpy call in a thread pool to avoid blocking the event loop."""
119
+ return await asyncio.to_thread(fn)
@@ -0,0 +1,105 @@
1
+ """Daz Studio plugin compatibility, as reported by dazpy's version checks.
2
+
3
+ Both dazpy clients call :func:`record` after every completed check (dazpy's
4
+ ``on_version_check``). Tools read the result: ``daz_status`` always reports it,
5
+ ``daz_inspect_scene`` and 404-type tool errors mention it when the plugin is too
6
+ old, and :class:`CompatibilityMiddleware` sends one MCP log warning per too-old
7
+ running plugin.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import sys
12
+ import threading
13
+ from typing import Any
14
+
15
+ import dazpy
16
+ from dazpy import VersionCheck
17
+ from fastmcp.server.middleware import Middleware
18
+
19
+ from ._client import DAZ_HOST, DAZ_PORT
20
+
21
+ _RELEASES_URL = "https://github.com/bluemoonfoundry/daz-script-server/releases"
22
+
23
+ _lock = threading.Lock()
24
+ _latest: VersionCheck | None = None # pylint: disable=invalid-name
25
+ _printed: set[tuple] = set()
26
+ _announced: set[tuple] = set()
27
+
28
+
29
+ def _key(check: VersionCheck) -> tuple:
30
+ return (check.server_url, check.server_instance_id, check.server_version)
31
+
32
+
33
+ def record(check: VersionCheck) -> None:
34
+ """dazpy ``on_version_check`` callback: store the latest check."""
35
+ global _latest # pylint: disable=global-statement
36
+ with _lock:
37
+ _latest = check
38
+ first = check.compatible is False and _key(check) not in _printed
39
+ if first:
40
+ _printed.add(_key(check))
41
+ if first:
42
+ print(f"daz-mcp-server: {check.message}", file=sys.stderr, flush=True)
43
+
44
+
45
+ def latest() -> VersionCheck | None:
46
+ """The most recent completed check, or ``None``."""
47
+ return _latest
48
+
49
+
50
+ def summary() -> dict[str, Any]:
51
+ """Plugin compatibility as reported to tools."""
52
+ check = _latest
53
+ return {
54
+ "target": f"{DAZ_HOST}:{DAZ_PORT}",
55
+ "plugin_version": check.server_version if check else None,
56
+ "min_plugin_version": dazpy.MIN_SERVER_VERSION,
57
+ "dazpy_version": dazpy.__version__,
58
+ "compatible": check.compatible if check else None,
59
+ "message": incompatible_note(),
60
+ }
61
+
62
+
63
+ def incompatible_note() -> str | None:
64
+ """Upgrade advice when the latest check found the plugin too old."""
65
+ check = _latest
66
+ if check is None or check.compatible is not False:
67
+ return None
68
+ return (
69
+ f"The Daz Studio plugin at {DAZ_HOST}:{DAZ_PORT} is {check.server_version}, "
70
+ f"older than the required {check.min_server_version}; upgrade it ({_RELEASES_URL})."
71
+ )
72
+
73
+
74
+ def take_unannounced() -> VersionCheck | None:
75
+ """The latest incompatible check, once per running plugin (for the MCP log)."""
76
+ with _lock:
77
+ check = _latest
78
+ if check is None or check.compatible is not False or _key(check) in _announced:
79
+ return None
80
+ _announced.add(_key(check))
81
+ return check
82
+
83
+
84
+ def reset() -> None:
85
+ """Forget everything (tests)."""
86
+ global _latest # pylint: disable=global-statement
87
+ with _lock:
88
+ _latest = None
89
+ _printed.clear()
90
+ _announced.clear()
91
+
92
+
93
+ class CompatibilityMiddleware(Middleware):
94
+ """After each tool call, log a too-old plugin to the MCP client once."""
95
+
96
+ async def on_call_tool(self, context, call_next):
97
+ try:
98
+ return await call_next(context)
99
+ finally:
100
+ check = take_unannounced()
101
+ if check is not None:
102
+ try:
103
+ await context.fastmcp_context.warning(check.message)
104
+ except Exception: # pylint: disable=broad-exception-caught
105
+ pass # logging must never break a tool call
@@ -0,0 +1,134 @@
1
+ """Shared emotion → morph/body-language definitions.
2
+
3
+ Used by tools/morph.py (daz_set_emotion) and tools/cinematic.py (shot/story
4
+ tools that need to reason about emotional expression) — previously defined
5
+ identically in both modules; centralized here to avoid drift between copies.
6
+
7
+ Emotion → list of {names: [...], value: float} (first match per list wins).
8
+ Multiple candidate names handle morph naming differences across figure generations.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ _EMOTION_DEFINITIONS: dict[str, dict] = {
13
+ "happy": {
14
+ "morphs": [
15
+ {
16
+ "names": ["PHMSmile", "Smile", "CTRLSmile", "MouthSmile", "SmileSimple"],
17
+ "value": 0.85,
18
+ },
19
+ {"names": ["PHMEyesSquint", "EyesSquint", "EyeSquintL", "SquintEyes"], "value": 0.25},
20
+ ],
21
+ "body": [{"bone": "chestUpper", "property": "XRotate", "value": 3.0}],
22
+ },
23
+ "sad": {
24
+ "morphs": [
25
+ {
26
+ "names": ["PHMFrown", "Frown", "MouthFrown", "CTRLFrown", "FrownSimple"],
27
+ "value": 0.75,
28
+ },
29
+ {
30
+ "names": [
31
+ "PHMBrowInnerDown", "BrowDownL", "BrowDown", "CTRLBrowDown", "BrowInnerDown",
32
+ ],
33
+ "value": 0.6,
34
+ },
35
+ {"names": ["PHMEyesSquint", "EyesSquint", "EyeSquintL"], "value": 0.3},
36
+ ],
37
+ "body": [{"bone": "chestUpper", "property": "XRotate", "value": -6.0}],
38
+ },
39
+ "angry": {
40
+ "morphs": [
41
+ {"names": ["PHMFrown", "Frown", "MouthFrown", "CTRLFrown"], "value": 0.5},
42
+ {
43
+ "names": ["PHMBrowDown", "BrowDown", "BrowDownLeft", "CTRLBrowDown", "BrowDownR"],
44
+ "value": 0.85,
45
+ },
46
+ {"names": ["PHMNoseWrinkle", "NoseWrinkle", "NoseSneerL", "NoseSneer"], "value": 0.4},
47
+ {
48
+ "names": ["PHMEyesTighten", "EyesTighten", "EyeSquintL", "CheekSquintL"],
49
+ "value": 0.4,
50
+ },
51
+ ],
52
+ "body": [{"bone": "chestUpper", "property": "XRotate", "value": -3.0}],
53
+ },
54
+ "surprised": {
55
+ "morphs": [
56
+ {
57
+ "names": ["PHMBrowUp", "BrowUp", "BrowInnerUpL", "CTRLBrowUp", "BrowsUp"],
58
+ "value": 0.85,
59
+ },
60
+ {"names": ["PHMEyesWide", "EyesWide", "EyeOpenL", "EyeWideL"], "value": 0.75},
61
+ {"names": ["PHMMouthOpen", "MouthOpen", "CTRLMouthOpen", "JawOpen"], "value": 0.6},
62
+ ],
63
+ "body": [],
64
+ },
65
+ "fearful": {
66
+ "morphs": [
67
+ {"names": ["PHMBrowUp", "BrowUp", "BrowInnerUpL", "CTRLBrowUp"], "value": 0.7},
68
+ {"names": ["PHMEyesWide", "EyesWide", "EyeOpenL", "EyeWideL"], "value": 0.6},
69
+ {"names": ["PHMMouthOpen", "MouthOpen", "CTRLMouthOpen", "JawOpen"], "value": 0.3},
70
+ ],
71
+ "body": [{"bone": "chestUpper", "property": "XRotate", "value": -4.0}],
72
+ },
73
+ "disgusted": {
74
+ "morphs": [
75
+ {"names": ["PHMNoseWrinkle", "NoseWrinkle", "NoseSneerL", "NoseSneer"], "value": 0.75},
76
+ {"names": ["PHMFrown", "Frown", "MouthFrown", "CTRLFrown"], "value": 0.4},
77
+ {
78
+ "names": ["PHMUpperLipUp", "UpperLipUp", "MouthUpperUp_L", "LipUpperUp_L"],
79
+ "value": 0.3,
80
+ },
81
+ ],
82
+ "body": [],
83
+ },
84
+ "neutral": {
85
+ "morphs": [],
86
+ "body": [],
87
+ },
88
+ "excited": {
89
+ "morphs": [
90
+ {"names": ["PHMSmile", "Smile", "CTRLSmile", "MouthSmile"], "value": 1.0},
91
+ {"names": ["PHMBrowUp", "BrowUp", "CTRLBrowUp", "BrowsUp"], "value": 0.5},
92
+ {"names": ["PHMEyesWide", "EyesWide", "EyeOpenL"], "value": 0.4},
93
+ {"names": ["PHMMouthOpen", "MouthOpen", "CTRLMouthOpen", "JawOpen"], "value": 0.4},
94
+ ],
95
+ "body": [{"bone": "chestUpper", "property": "XRotate", "value": 5.0}],
96
+ },
97
+ "bored": {
98
+ "morphs": [
99
+ {
100
+ "names": ["PHMEyesClosed", "EyesClosed", "EyeClosedL", "CTRLEyesClosed"],
101
+ "value": 0.4,
102
+ },
103
+ {"names": ["PHMFrown", "Frown", "MouthFrown"], "value": 0.2},
104
+ ],
105
+ "body": [{"bone": "chestUpper", "property": "XRotate", "value": -4.0}],
106
+ },
107
+ "confident": {
108
+ "morphs": [
109
+ {"names": ["PHMSmile", "Smile", "MouthSmile", "CTRLSmile"], "value": 0.3},
110
+ ],
111
+ "body": [{"bone": "chestUpper", "property": "XRotate", "value": 4.0}],
112
+ },
113
+ "shy": {
114
+ "morphs": [
115
+ {"names": ["PHMSmile", "Smile", "MouthSmile"], "value": 0.2},
116
+ {"names": ["PHMEyesSquint", "EyesSquint", "EyeSquintL"], "value": 0.15},
117
+ ],
118
+ "body": [{"bone": "chestUpper", "property": "XRotate", "value": -5.0}],
119
+ },
120
+ "loving": {
121
+ "morphs": [
122
+ {"names": ["PHMSmile", "Smile", "MouthSmile", "CTRLSmile"], "value": 0.6},
123
+ {"names": ["PHMEyesSquint", "EyesSquint", "EyeSquintL"], "value": 0.35},
124
+ ],
125
+ "body": [{"bone": "chestUpper", "property": "XRotate", "value": 2.0}],
126
+ },
127
+ "contemptuous": {
128
+ "morphs": [
129
+ {"names": ["PHMSmileR", "SmileR", "MouthSmileR", "MouthSmile_R"], "value": 0.5},
130
+ {"names": ["PHMFrownL", "FrownL", "MouthFrownL", "MouthFrown_L"], "value": 0.3},
131
+ ],
132
+ "body": [],
133
+ },
134
+ }
@@ -0,0 +1,48 @@
1
+ """Map dazpy and httpx exceptions to FastMCP ToolError."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+
6
+ from fastmcp.exceptions import ToolError
7
+
8
+ import dazpy.exceptions as daz_exc
9
+
10
+ from ._client import DAZ_TIMEOUT, TOKEN_FILE
11
+ from ._compat import incompatible_note
12
+
13
+
14
+ def handle_dazpy_error(exc: Exception) -> None:
15
+ """Re-raise a dazpy exception as a ToolError with a helpful message.
16
+
17
+ Call this inside an except block: handle_dazpy_error(exc)
18
+ The function always raises; it never returns normally.
19
+ """
20
+ if isinstance(exc, daz_exc.ConnectionError):
21
+ raise ToolError(
22
+ "Cannot connect to DAZ Studio. Ensure DAZ Studio is running with "
23
+ "the DazScriptServer plugin active."
24
+ ) from exc
25
+ if isinstance(exc, daz_exc.TimeoutError):
26
+ raise ToolError(
27
+ f"Request timed out after {DAZ_TIMEOUT}s. "
28
+ "Increase the timeout by setting the DAZ_TIMEOUT environment variable."
29
+ ) from exc
30
+ if isinstance(exc, daz_exc.AuthenticationError):
31
+ source = (
32
+ "DAZ_API_TOKEN environment variable" if os.environ.get("DAZ_API_TOKEN") else TOKEN_FILE
33
+ )
34
+ raise ToolError(
35
+ f"Authentication failed. Verify the API token in: {source}"
36
+ ) from exc
37
+ if isinstance(exc, daz_exc.NodeNotFoundError):
38
+ raise ToolError(str(exc)) from exc
39
+ if isinstance(exc, daz_exc.DazBusyError):
40
+ raise ToolError(
41
+ f"DAZ Studio is busy ({exc.reason}). Try again in a few seconds."
42
+ ) from exc
43
+ if isinstance(exc, (daz_exc.ScriptRuntimeError, daz_exc.ScriptSyntaxError)):
44
+ raise ToolError(exc.diagnostic) from exc
45
+ if isinstance(exc, daz_exc.ServerResponseError):
46
+ note = incompatible_note() if exc.status_code == 404 else None
47
+ raise ToolError(f"{exc}\n{note}" if note else str(exc)) from exc
48
+ raise exc
@@ -0,0 +1,30 @@
1
+ """Agent guides bundled with the package (``guides/*.md``).
2
+
3
+ Served to the AI as the ``daz://guides`` / ``daz://guide/{name}`` resources and
4
+ through ``daz_script_help("guide:<name>")`` for clients that don't surface
5
+ resources.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from importlib.resources import files
10
+
11
+ GUIDE_NAMES: tuple[str, ...] = ("actors", "cinema", "daz_studio", "dazscript", "recipe", "scene")
12
+
13
+
14
+ def read_guide(name: str) -> str:
15
+ """Return the text of guide *name*; ``KeyError`` for an unknown name."""
16
+ if name not in GUIDE_NAMES:
17
+ raise KeyError(name)
18
+ return files(__package__).joinpath("guides", f"{name}.md").read_text(encoding="utf-8")
19
+
20
+
21
+ def _title(name: str) -> str:
22
+ for line in read_guide(name).splitlines():
23
+ if line.startswith("#"):
24
+ return line.lstrip("#").strip()
25
+ return name
26
+
27
+
28
+ def guide_index() -> str:
29
+ """One line per guide: its resource URI and title."""
30
+ return "\n".join(f"daz://guide/{name} — {_title(name)}" for name in GUIDE_NAMES)
daz_mcp_server/_mcp.py ADDED
@@ -0,0 +1,154 @@
1
+ """Shared FastMCP instance, lifespan, and DazScriptServer execution helpers.
2
+
3
+ All tool modules import ``mcp`` from here to register ``@mcp.tool()`` functions
4
+ without creating circular imports with ``server.py``.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from contextlib import asynccontextmanager
9
+ from importlib.metadata import version as _package_version
10
+ from typing import Any
11
+
12
+ import httpx
13
+ from dazpy.aio import AsyncDazClient
14
+ import dazpy.exceptions as daz_exc
15
+ from fastmcp import FastMCP
16
+
17
+ from ._client import (
18
+ DAZ_API_TOKEN,
19
+ CONTENT_BROWSER_URL,
20
+ DAZ_HOST,
21
+ DAZ_PORT,
22
+ DAZ_TIMEOUT,
23
+ get_async_daz_client,
24
+ set_async_daz_client,
25
+ set_content_browser_client,
26
+ )
27
+ from . import _compat
28
+ from ._errors import handle_dazpy_error
29
+ from ._registry import _register_scripts
30
+
31
+
32
+ # ---------------------------------------------------------------------------
33
+ # Execute helpers — used by all tool modules
34
+ # ---------------------------------------------------------------------------
35
+
36
+ def _execution_payload(result: Any) -> dict[str, Any]:
37
+ """Preserve the public diagnostic shape for any dazpy execution result."""
38
+ return {
39
+ "success": result.success,
40
+ "result": result.value,
41
+ "output": result.output,
42
+ "error": result.error or None,
43
+ "request_id": result.request_id,
44
+ "duration_ms": result.duration_ms,
45
+ }
46
+
47
+
48
+ async def _execute_raw(script: str, args: dict[str, Any] | None = None) -> dict[str, Any]:
49
+ """Execute inline source through dazpy and preserve the diagnostic shape."""
50
+ try:
51
+ result = await get_async_daz_client().execute(script, args)
52
+ except daz_exc.DazError as exc:
53
+ handle_dazpy_error(exc)
54
+ return _execution_payload(result)
55
+
56
+
57
+ async def _execute(script: str, args: dict[str, Any] | None = None) -> Any:
58
+ """Execute inline DazScript and unwrap its result value."""
59
+ data = await _execute_raw(script, args)
60
+ return data.get("result")
61
+
62
+
63
+ async def _execute_by_id(script_id: str, args: dict[str, Any] | None = None) -> Any:
64
+ """Call a registered script by ID; re-registers once on 404 (DAZ Studio restart)."""
65
+ client = get_async_daz_client()
66
+ try:
67
+ result = await client.execute_registered(script_id, args)
68
+ except daz_exc.ServerResponseError as exc:
69
+ if exc.status_code != 404:
70
+ handle_dazpy_error(exc)
71
+ await _register_scripts(client)
72
+ try:
73
+ result = await client.execute_registered(script_id, args)
74
+ except daz_exc.DazError as retry_exc:
75
+ handle_dazpy_error(retry_exc)
76
+ except daz_exc.DazError as exc:
77
+ handle_dazpy_error(exc)
78
+ return result.value
79
+
80
+
81
+ async def _execute_by_id_async(
82
+ script_id: str,
83
+ args: dict[str, Any] | None = None,
84
+ ) -> dict[str, Any]:
85
+ """Submit a registered script for async execution; returns immediately with request_id."""
86
+ client = get_async_daz_client()
87
+ try:
88
+ request_id = await client.execute_registered_async_submit(script_id, args)
89
+ except daz_exc.ServerResponseError as exc:
90
+ if exc.status_code != 404:
91
+ handle_dazpy_error(exc)
92
+ await _register_scripts(client)
93
+ try:
94
+ request_id = await client.execute_registered_async_submit(script_id, args)
95
+ except daz_exc.DazError as retry_exc:
96
+ handle_dazpy_error(retry_exc)
97
+ except daz_exc.DazError as exc:
98
+ handle_dazpy_error(exc)
99
+ return {"request_id": request_id, "status": "queued"}
100
+
101
+
102
+ async def _execute_render(params: dict[str, Any]) -> dict[str, Any]:
103
+ """Submit a render through dazpy's typed protocol surface."""
104
+ try:
105
+ return await get_async_daz_client().render_submit(
106
+ params["output_path"],
107
+ width=params.get("width", 0),
108
+ height=params.get("height", 0),
109
+ camera=params.get("camera", ""),
110
+ engine=params.get("engine", ""),
111
+ iray_samples=params.get("iray_samples", 0),
112
+ )
113
+ except daz_exc.DazError as exc:
114
+ handle_dazpy_error(exc)
115
+
116
+
117
+ async def _execute_render_batch(body: dict[str, Any]) -> dict[str, Any]:
118
+ """Submit a render batch through dazpy's typed protocol surface."""
119
+ try:
120
+ return await get_async_daz_client().render_batch_submit(
121
+ body["variants"], body.get("base")
122
+ )
123
+ except daz_exc.DazError as exc:
124
+ handle_dazpy_error(exc)
125
+
126
+
127
+ # ---------------------------------------------------------------------------
128
+ # Lifespan and shared FastMCP instance
129
+ # ---------------------------------------------------------------------------
130
+
131
+ @asynccontextmanager
132
+ async def _lifespan(server: FastMCP): # pylint: disable=unused-argument
133
+ # `server` is required by FastMCP's lifespan callback signature.
134
+ async with AsyncDazClient(
135
+ host=DAZ_HOST,
136
+ port=DAZ_PORT,
137
+ token=DAZ_API_TOKEN,
138
+ timeout=DAZ_TIMEOUT,
139
+ on_version_check=_compat.record,
140
+ ) as client:
141
+ set_async_daz_client(client)
142
+ await _register_scripts(client)
143
+ async with httpx.AsyncClient(
144
+ base_url=CONTENT_BROWSER_URL, timeout=DAZ_TIMEOUT
145
+ ) as cb_client:
146
+ set_content_browser_client(cb_client)
147
+ yield
148
+ set_content_browser_client(None)
149
+ set_async_daz_client(None)
150
+
151
+
152
+ # version: what MCP clients see in serverInfo (without it FastMCP reports its own version).
153
+ mcp = FastMCP("daz-mcp-server", version=_package_version("daz-mcp-server"), lifespan=_lifespan)
154
+ mcp.add_middleware(_compat.CompatibilityMiddleware())
@@ -0,0 +1,26 @@
1
+ """Select the model-facing MCP component profile."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+
6
+ from fastmcp import FastMCP
7
+
8
+
9
+ PROFILE_ENV = "DAZ_MCP_PROFILE"
10
+ DEFAULT_PROFILE = "compact"
11
+ VALID_PROFILES = {"compact", "expert"}
12
+
13
+
14
+ def configure_profile(server: FastMCP) -> str:
15
+ """Apply the configured tool visibility profile and return its name."""
16
+ profile = os.getenv(PROFILE_ENV, DEFAULT_PROFILE).strip().lower()
17
+ if profile not in VALID_PROFILES:
18
+ choices = ", ".join(sorted(VALID_PROFILES))
19
+ raise RuntimeError(f"{PROFILE_ENV} must be one of: {choices}")
20
+ if profile == "compact":
21
+ server.enable(tags={"default"}, components={"tool"}, only=True)
22
+ # ``only=True`` begins with a global deny transform. Static guidance is
23
+ # intentionally available in both profiles and does not consume tool
24
+ # selection context, so re-enable resources after the tool allowlist.
25
+ server.enable(components={"resource", "template"})
26
+ return profile