pvsyst-cli-mcp 0.5.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 (121) hide show
  1. pvsyst_auto/__init__.py +4 -0
  2. pvsyst_auto/__main__.py +4 -0
  3. pvsyst_auto/api/__init__.py +1 -0
  4. pvsyst_auto/api/app.py +16 -0
  5. pvsyst_auto/api/components.py +99 -0
  6. pvsyst_auto/api/context.py +291 -0
  7. pvsyst_auto/api/engineering.py +186 -0
  8. pvsyst_auto/api/guidance.py +345 -0
  9. pvsyst_auto/api/projects.py +306 -0
  10. pvsyst_auto/api/results.py +75 -0
  11. pvsyst_auto/api/schemas.py +1055 -0
  12. pvsyst_auto/api/setup.py +40 -0
  13. pvsyst_auto/api/simulation.py +259 -0
  14. pvsyst_auto/api/storage.py +114 -0
  15. pvsyst_auto/api/weather.py +145 -0
  16. pvsyst_auto/components/__init__.py +1 -0
  17. pvsyst_auto/components/battery.py +154 -0
  18. pvsyst_auto/components/builder.py +480 -0
  19. pvsyst_auto/components/commercial.py +200 -0
  20. pvsyst_auto/components/curves.py +67 -0
  21. pvsyst_auto/components/editor.py +450 -0
  22. pvsyst_auto/components/generator.py +197 -0
  23. pvsyst_auto/components/identity.py +67 -0
  24. pvsyst_auto/components/pan.py +38 -0
  25. pvsyst_auto/components/single_diode.py +767 -0
  26. pvsyst_auto/components/store.py +1114 -0
  27. pvsyst_auto/energy/__init__.py +1 -0
  28. pvsyst_auto/energy/ac.py +223 -0
  29. pvsyst_auto/energy/ageing.py +230 -0
  30. pvsyst_auto/energy/auxiliaries.py +161 -0
  31. pvsyst_auto/energy/availability.py +57 -0
  32. pvsyst_auto/energy/dc.py +493 -0
  33. pvsyst_auto/energy/iam.py +261 -0
  34. pvsyst_auto/energy/inverter_temperature.py +105 -0
  35. pvsyst_auto/energy/load.py +181 -0
  36. pvsyst_auto/energy/mismatch.py +123 -0
  37. pvsyst_auto/energy/peak.py +260 -0
  38. pvsyst_auto/energy/power.py +222 -0
  39. pvsyst_auto/energy/power_factor.py +148 -0
  40. pvsyst_auto/energy/profiles.py +203 -0
  41. pvsyst_auto/energy/soiling.py +118 -0
  42. pvsyst_auto/energy/storage.py +823 -0
  43. pvsyst_auto/energy/system.py +249 -0
  44. pvsyst_auto/energy/tou_planner.py +259 -0
  45. pvsyst_auto/energy/transformer.py +103 -0
  46. pvsyst_auto/energy/unavailability.py +233 -0
  47. pvsyst_auto/engineering/__init__.py +1 -0
  48. pvsyst_auto/engineering/brief.py +290 -0
  49. pvsyst_auto/engineering/comparison.py +572 -0
  50. pvsyst_auto/engineering/diagnostics.py +993 -0
  51. pvsyst_auto/engineering/economics.py +1126 -0
  52. pvsyst_auto/engineering/envelope.py +573 -0
  53. pvsyst_auto/engineering/handoff.py +239 -0
  54. pvsyst_auto/engineering/inputs.py +337 -0
  55. pvsyst_auto/engineering/review.py +178 -0
  56. pvsyst_auto/engineering/sizing.py +197 -0
  57. pvsyst_auto/engineering/suggest.py +391 -0
  58. pvsyst_auto/native/__init__.py +1 -0
  59. pvsyst_auto/native/_prep.py +213 -0
  60. pvsyst_auto/native/_winlaunch.py +465 -0
  61. pvsyst_auto/native/_workspace_ini.py +234 -0
  62. pvsyst_auto/native/cli.py +1076 -0
  63. pvsyst_auto/native/dc.py +6 -0
  64. pvsyst_auto/native/grid_limit.py +98 -0
  65. pvsyst_auto/native/headless.py +1223 -0
  66. pvsyst_auto/native/horizon.py +233 -0
  67. pvsyst_auto/native/load.py +295 -0
  68. pvsyst_auto/native/p50.py +175 -0
  69. pvsyst_auto/native/project.py +183 -0
  70. pvsyst_auto/native/scene.py +1174 -0
  71. pvsyst_auto/project/__init__.py +1 -0
  72. pvsyst_auto/project/bifacial.py +483 -0
  73. pvsyst_auto/project/circuit.py +643 -0
  74. pvsyst_auto/project/domes.py +194 -0
  75. pvsyst_auto/project/fileio.py +105 -0
  76. pvsyst_auto/project/paths.py +69 -0
  77. pvsyst_auto/project/seasonal.py +153 -0
  78. pvsyst_auto/project/sheds.py +217 -0
  79. pvsyst_auto/project/synthesize.py +1730 -0
  80. pvsyst_auto/project/template.py +541 -0
  81. pvsyst_auto/project/tracking.py +339 -0
  82. pvsyst_auto/project/variant_readback.py +381 -0
  83. pvsyst_auto/project/variant_topology.py +480 -0
  84. pvsyst_auto/project/variant_updates.py +538 -0
  85. pvsyst_auto/project/variant_writer.py +156 -0
  86. pvsyst_auto/project/variants.py +1098 -0
  87. pvsyst_auto/results.py +244 -0
  88. pvsyst_auto/scene/__init__.py +1 -0
  89. pvsyst_auto/scene/author.py +1330 -0
  90. pvsyst_auto/scene/ground.py +352 -0
  91. pvsyst_auto/scene/mapping.py +1003 -0
  92. pvsyst_auto/scene/reader.py +308 -0
  93. pvsyst_auto/scene/state.py +183 -0
  94. pvsyst_auto/versions.py +35 -0
  95. pvsyst_auto/weather/__init__.py +1 -0
  96. pvsyst_auto/weather/acquisition.py +1164 -0
  97. pvsyst_auto/weather/csv.py +350 -0
  98. pvsyst_auto/weather/preparation.py +603 -0
  99. pvsyst_auto/weather/review.py +442 -0
  100. pvsyst_auto/workflows/__init__.py +1 -0
  101. pvsyst_auto/workflows/batch.py +555 -0
  102. pvsyst_auto/workflows/bess_optimize.py +807 -0
  103. pvsyst_auto/workflows/blocks.py +202 -0
  104. pvsyst_auto/workflows/delivery.py +382 -0
  105. pvsyst_auto/workflows/design.py +1129 -0
  106. pvsyst_auto/workflows/feasibility.py +377 -0
  107. pvsyst_auto/workflows/house.py +701 -0
  108. pvsyst_auto/workflows/optimize.py +455 -0
  109. pvsyst_auto/workflows/report.py +845 -0
  110. pvsyst_auto/workflows/revision.py +533 -0
  111. pvsyst_auto/workflows/simulation.py +483 -0
  112. pvsyst_auto/workflows/sourced_design.py +537 -0
  113. pvsyst_auto/workflows/sourced_house.py +353 -0
  114. pvsyst_auto/workflows/storage.py +237 -0
  115. pvsyst_auto/workflows/utility.py +708 -0
  116. pvsyst_cli_mcp-0.5.0.dist-info/METADATA +150 -0
  117. pvsyst_cli_mcp-0.5.0.dist-info/RECORD +121 -0
  118. pvsyst_cli_mcp-0.5.0.dist-info/WHEEL +5 -0
  119. pvsyst_cli_mcp-0.5.0.dist-info/entry_points.txt +2 -0
  120. pvsyst_cli_mcp-0.5.0.dist-info/licenses/LICENSE +21 -0
  121. pvsyst_cli_mcp-0.5.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,4 @@
1
+ """Public Python adapter for installed PVsyst; no bundled simulator."""
2
+ from .native.cli import PVsystCLI, PVsystError
3
+
4
+ __all__ = ["PVsystCLI", "PVsystError"]
@@ -0,0 +1,4 @@
1
+ from .api.app import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1 @@
1
+ """PVsyst api operations."""
pvsyst_auto/api/app.py ADDED
@@ -0,0 +1,16 @@
1
+ """Compose selected tool groups and launch the stdio server."""
2
+ from importlib import import_module
3
+
4
+ from .context import (ACTIVE_TOOL_GROUPS, ACTIVE_TOOL_NAMES, STRICT_ARGUMENT_TOOLS,
5
+ _strict_arguments, create_mcp_server, import_modules_for_groups, mcp)
6
+
7
+ for module in import_modules_for_groups(ACTIVE_TOOL_GROUPS):
8
+ import_module(f".{module}", __package__)
9
+
10
+ _expected_strict = set(STRICT_ARGUMENT_TOOLS) & ACTIVE_TOOL_NAMES
11
+ if set(_strict_arguments) != _expected_strict:
12
+ raise RuntimeError(f"Unregistered strict entry points: {sorted(_expected_strict - set(_strict_arguments))}")
13
+
14
+
15
+ def main():
16
+ mcp.run(transport="stdio")
@@ -0,0 +1,99 @@
1
+ """Components MCP operations; native and domain behavior stays in the existing modules."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Annotated, Literal
5
+ from pydantic import Field, StrictBool, StrictInt, StrictStr
6
+ from pvsyst_auto.components.builder import build_sourced_component
7
+ from pvsyst_auto.api.schemas import SourceDeclarationRequest, SourceTextRequest, StrictNum
8
+ from pvsyst_auto.api.context import categorized_tool, component_call, components
9
+
10
+
11
+ @categorized_tool()
12
+ def pvsyst_list_components(component_type: str, library: str = "workspace",
13
+ query: str = "", offset: StrictInt = 0, limit: StrictInt = 100,
14
+ min_power_w: StrictNum | None = None,
15
+ max_power_w: StrictNum | None = None,
16
+ bifacial: StrictBool | None = None,
17
+ min_system_voltage_v: StrictNum | None = None,
18
+ min_mppt: StrictInt | None = None,
19
+ manufacturer: StrictStr | None = None) -> dict:
20
+ """List PAN, OND, BTR, GEN or REV loose files in workspace or installed DataRO with
21
+ optional electrical filtering (power range, bifaciality, system voltage, MPPT count,
22
+ manufacturer) backed by an mtime-keyed metadata cache."""
23
+ return components().list(
24
+ component_type, library, query, offset, limit,
25
+ min_power_w=min_power_w, max_power_w=max_power_w,
26
+ bifacial=bifacial, min_system_voltage_v=min_system_voltage_v,
27
+ min_mppt=min_mppt, manufacturer=manufacturer,
28
+ )
29
+
30
+ @categorized_tool()
31
+ def pvsyst_get_component(component_type: str, filename: str,
32
+ library: str = "workspace", offset: StrictInt = 0,
33
+ limit: StrictInt = 100, include_curve_csv: StrictBool = False) -> dict:
34
+ """Read paged UTF-8 text, editable scalar allowlist, SHA-256, OND/BTR curves,
35
+ commercial fields, and remarks for a PAN, OND, BTR, GEN, or REV component."""
36
+ return component_call("inspect", component_type, filename, library, offset, limit, include_curve_csv)
37
+
38
+ @categorized_tool()
39
+ def pvsyst_validate_component(component_type: str, filename: str,
40
+ library: str = "workspace") -> dict:
41
+ """Validate structure, required fields, and numeric bounds of a component file."""
42
+ return component_call("validate", component_type, filename, library)
43
+
44
+ @categorized_tool()
45
+ def pvsyst_create_component(component_type: str, filename: str, content: str) -> dict:
46
+ """Create a new PAN, OND, BTR, GEN, or REV file in the workspace from UTF-8 PVObject_ text."""
47
+ return component_call("create", component_type, filename, content)
48
+
49
+ @categorized_tool()
50
+ def pvsyst_update_component(component_type: str, filename: str,
51
+ updates: dict[str, str],
52
+ expected_sha256: str | None = None, dry_run: StrictBool = False,
53
+ curve_updates: dict[str, list[list[StrictNum]]] | None = None,
54
+ use_file_curve: StrictBool = False,
55
+ commercial_updates: dict[str, str] | None = None,
56
+ remarks: list[str] | None = None,
57
+ curve_csv: dict[str, str] | None = None,
58
+ refit_single_diode: StrictBool = False) -> dict:
59
+ """Update allowlisted scalar fields, commercial metadata, remarks (up to 5 lines),
60
+ or Mode 1 OND (single- or 3-voltage ProfilPIOV1..3) / BTR curve tables (4..256 points
61
+ via curve_updates or curve_csv) in a workspace component with SHA-256 optimistic locking
62
+ and automatic backup. Set refit_single_diode=true on PAN STC edits to refit single-diode params."""
63
+ return component_call("update", component_type, filename, updates,
64
+ expected_sha256, dry_run, curve_updates, use_file_curve,
65
+ commercial_updates, remarks, curve_csv, refit_single_diode)
66
+
67
+ @categorized_tool()
68
+ def pvsyst_compare_components(component_type: str, first: str, second: str,
69
+ second_library: str = "workspace") -> dict:
70
+ """Compare two same-type components by text diff or binary SHA-256."""
71
+ return component_call("compare", component_type, first, second, second_library)
72
+
73
+ @categorized_tool()
74
+ def pvsyst_project_components(project: str, variant: str) -> dict:
75
+ """List PAN, OND, BTR, and GEN references used by a project variant."""
76
+ return component_call("dependencies", project, variant)
77
+
78
+ @categorized_tool()
79
+ def pvsyst_build_sourced_component(
80
+ component_type: Literal["PAN", "OND", "BTR"], new_name: StrictStr,
81
+ manufacturer: StrictStr, model: StrictStr,
82
+ sources: Annotated[dict[str, SourceTextRequest], Field(min_length=1, max_length=16)],
83
+ declarations: Annotated[list[SourceDeclarationRequest], Field(min_length=1, max_length=32)],
84
+ template_name: StrictStr | None = None,
85
+ chemistry: Literal["LFP", "NMC"] = "LFP",
86
+ source_library: Literal["workspace", "builtin"] = "workspace", dry_run: StrictBool = True,
87
+ acknowledge_inherited_model: StrictBool = False) -> dict:
88
+ """Build a new user-defined PAN, OND, or Li-ion BTR from cited datasheet values: either derived
89
+ from a template (template_name set) or synthesized zero-template with single-diode / single- or
90
+ 3-voltage Mode-1 OND / Li-ion LFP-NMC BTR derivation (template_name omitted). Requires
91
+ acknowledge_inherited_model=true when dry_run=false."""
92
+ return build_sourced_component(
93
+ components(), component_type=component_type, template_name=template_name, new_name=new_name,
94
+ manufacturer=manufacturer, model=model,
95
+ sources={key: entry.model_dump(exclude_none=True) for key, entry in sources.items()},
96
+ declarations=[entry.model_dump(exclude_none=True) for entry in declarations],
97
+ chemistry=chemistry,
98
+ source_library=source_library, dry_run=dry_run,
99
+ acknowledge_inherited_model=acknowledge_inherited_model)
@@ -0,0 +1,291 @@
1
+ """Shared MCP registration, strict arguments and workspace-scoped clients."""
2
+ from __future__ import annotations
3
+
4
+ import inspect
5
+ import os
6
+ from collections.abc import Mapping
7
+ from importlib import import_module
8
+ from threading import Lock
9
+ from typing import Any
10
+ from functools import wraps
11
+ from pathlib import Path
12
+ from mcp.server.context import CallNext, HandlerResult, ServerRequestContext
13
+ from mcp.server.mcpserver import MCPServer
14
+ from mcp.server.mcpserver.exceptions import ToolError
15
+ from mcp.types import CallToolResult, TextContent
16
+ from pvsyst_auto.native.cli import PVsystCLI, PVsystError
17
+ from pvsyst_auto.components.store import ComponentStore
18
+ from pvsyst_auto.project.variants import VariantStore
19
+ from pvsyst_auto.project.paths import workspace_file
20
+ from pvsyst_auto.api.guidance import SERVER_INSTRUCTIONS, register_guidance
21
+
22
+
23
+ mcp = MCPServer("pvsyst-cli", instructions=SERVER_INSTRUCTIONS)
24
+ register_guidance(mcp)
25
+
26
+ _cli: PVsystCLI | None = None
27
+ _cli_key: tuple[str | None, str | None] | None = None
28
+ _cli_owner: PVsystCLI | None = None
29
+
30
+ _cli_init_lock = Lock()
31
+
32
+ TOOL_GROUPS = {
33
+ "Setup & License": ("pvsyst_capabilities", "pvsyst_license_info"),
34
+ "Admin & Diagnostics": (
35
+ "pvsyst_license_activate", "pvsyst_license_deactivate",
36
+ "pvsyst_license_sync", "pvsyst_export_logs",
37
+ ),
38
+ "Projects & Variants": (
39
+ "pvsyst_list_projects", "pvsyst_inspect_project", "pvsyst_prepare_design_project",
40
+ "pvsyst_clone_variant", "pvsyst_get_variant_parameters", "pvsyst_update_variant_parameters",
41
+ "pvsyst_create_tracking_variant", "pvsyst_create_shed_geometry_variant",
42
+ "pvsyst_create_ac_cabling_variant", "pvsyst_create_dc_cabling_variant",
43
+ ),
44
+ "Components": (
45
+ "pvsyst_list_components", "pvsyst_get_component",
46
+ "pvsyst_create_component", "pvsyst_update_component", "pvsyst_build_sourced_component",
47
+ ),
48
+ "Sites & Weather": (
49
+ "pvsyst_resolve_location", "pvsyst_acquire_weather",
50
+ "pvsyst_prepare_weather", "pvsyst_review_weather",
51
+ ),
52
+ "Loads & Storage": (
53
+ "pvsyst_prepare_load_profile", "pvsyst_create_native_load_variant",
54
+ "pvsyst_create_grid_storage_variant", "pvsyst_create_grid_storage_system",
55
+ "pvsyst_plan_tou_storage_schedule",
56
+ ),
57
+ "Simulation": (
58
+ "pvsyst_build_sfi", "pvsyst_run_simulation", "pvsyst_run_batch_sweep",
59
+ "pvsyst_simulate_design", "pvsyst_prepare_sourced_design", "pvsyst_run_house_task",
60
+ "pvsyst_optimize_variant", "pvsyst_optimize_bess_sizing",
61
+ ),
62
+ "Results": ("pvsyst_read_results", "pvsyst_read_rows", "pvsyst_read_batch_results", "pvsyst_diagnose_results"),
63
+ "Engineering": (
64
+ "pvsyst_suggest_sizing", "pvsyst_project_handoff",
65
+ "pvsyst_run_engineering_task", "pvsyst_compare_engineering_scenarios",
66
+ "pvsyst_evaluate_economics", "pvsyst_generate_report",
67
+ "pvsyst_export_engineering_delivery", "pvsyst_run_feasibility_study",
68
+ ),
69
+ "Expert & Low-Level": (
70
+ "pvsyst_list_variants", "pvsyst_create_project", "pvsyst_update_project_parameters",
71
+ "pvsyst_update_project_sources", "pvsyst_get_variant_components",
72
+ "pvsyst_update_variant_components", "pvsyst_validate_variant_structure",
73
+ "pvsyst_clone_subarray", "pvsyst_remove_subarray", "pvsyst_review_project_inputs",
74
+ "pvsyst_create_mv_night_disconnect_variant", "pvsyst_create_dome_allocation_variant",
75
+ "pvsyst_create_house_pv_scene", "pvsyst_read_house_pv_scene", "pvsyst_import_house_pv_scene",
76
+ "pvsyst_validate_component", "pvsyst_compare_components", "pvsyst_project_components",
77
+ "pvsyst_inspect_weather_csv", "pvsyst_build_monthly_weather",
78
+ "pvsyst_create_site", "pvsyst_convert_meteo",
79
+ "pvsyst_run_sourced_house_task",
80
+ "pvsyst_prepare_block_project", "pvsyst_review_engineering_brief",
81
+ ),
82
+ }
83
+
84
+ TOOL_CATEGORY = {name: category for category, names in TOOL_GROUPS.items() for name in names}
85
+
86
+ if len(TOOL_CATEGORY) != sum(map(len, TOOL_GROUPS.values())):
87
+ raise RuntimeError("Duplicate tool category assignment")
88
+
89
+ # Every tool rejects unknown arguments: a misspelt option must never be dropped before a write.
90
+ STRICT_ARGUMENT_TOOLS = tuple(TOOL_CATEGORY)
91
+
92
+ GROUP_MODULES = {
93
+ "setup": "Setup & License",
94
+ "projects": "Projects & Variants",
95
+ "components": "Components",
96
+ "weather": "Sites & Weather",
97
+ "storage": "Loads & Storage",
98
+ "simulation": "Simulation",
99
+ "results": "Results",
100
+ "engineering": "Engineering",
101
+ "admin": "Admin & Diagnostics",
102
+ "expert": "Expert & Low-Level",
103
+ }
104
+ DEFAULT_TOOL_GROUPS = (
105
+ "setup", "projects", "components", "weather",
106
+ "storage", "simulation", "results", "engineering",
107
+ )
108
+ GROUP_IMPORT_MODULES = {
109
+ "setup": ("setup",),
110
+ "admin": ("setup",),
111
+ "projects": ("projects",),
112
+ "components": ("components",),
113
+ "weather": ("weather",),
114
+ "storage": ("storage",),
115
+ "simulation": ("simulation",),
116
+ "results": ("results",),
117
+ "engineering": ("engineering",),
118
+ "expert": ("projects", "components", "weather", "simulation", "engineering"),
119
+ }
120
+
121
+
122
+ def resolve_tool_groups(requested: str | None) -> tuple[str, ...]:
123
+ if requested is None:
124
+ return DEFAULT_TOOL_GROUPS
125
+ groups = [group.strip() for group in requested.split(",")]
126
+ if groups == ["all"]:
127
+ return tuple(GROUP_MODULES)
128
+ if (any(group not in GROUP_MODULES for group in groups)
129
+ or len(set(groups)) != len(groups)):
130
+ raise ValueError("PVSYST_TOOL_GROUPS requires 'all' or distinct nonempty keys from: "
131
+ + ", ".join(GROUP_MODULES))
132
+ return tuple(group for group in GROUP_MODULES if group in groups)
133
+
134
+
135
+ def tool_names_for_groups(groups: tuple[str, ...]) -> frozenset[str]:
136
+ return frozenset(name for group in groups for name in TOOL_GROUPS[GROUP_MODULES[group]])
137
+
138
+
139
+ def import_modules_for_groups(groups: tuple[str, ...]) -> tuple[str, ...]:
140
+ return tuple(dict.fromkeys(mod for group in groups for mod in GROUP_IMPORT_MODULES[group]))
141
+
142
+
143
+ ACTIVE_TOOL_GROUPS = resolve_tool_groups(os.environ.get("PVSYST_TOOL_GROUPS"))
144
+ ACTIVE_TOOL_NAMES = tool_names_for_groups(ACTIVE_TOOL_GROUPS)
145
+
146
+ _strict_arguments: dict[str, frozenset[str]] = {}
147
+ _tool_registry: dict[str, tuple[str, Any, frozenset[str]]] = {}
148
+
149
+
150
+ def make_strict_middleware(strict_map: Mapping[str, frozenset[str]]):
151
+ async def reject_unknown_tool_arguments(ctx: ServerRequestContext[Any, Any],
152
+ call_next: CallNext) -> HandlerResult:
153
+ """Refuse unknown top-level arguments for every registered tool."""
154
+ if ctx.method == "tools/call" and isinstance(ctx.params, Mapping):
155
+ name = ctx.params.get("name")
156
+ arguments = ctx.params.get("arguments")
157
+ # A malformed name/arguments value is left to the SDK's own params validation.
158
+ accepted = strict_map.get(name) if isinstance(name, str) else None
159
+ if accepted is not None and isinstance(arguments, Mapping):
160
+ unknown = sorted(set(arguments) - accepted, key=str)
161
+ if unknown:
162
+ text = (f"Unknown argument(s) for {name}: {', '.join(map(str, unknown))}. "
163
+ f"Accepted arguments: {', '.join(sorted(accepted))}")
164
+ return CallToolResult(content=[TextContent(type="text", text=text)], is_error=True)
165
+ return await call_next(ctx)
166
+
167
+ return reject_unknown_tool_arguments
168
+
169
+
170
+ reject_unknown_tool_arguments = make_strict_middleware(_strict_arguments)
171
+ mcp.middleware.append(reject_unknown_tool_arguments)
172
+
173
+ # Failures whose message is returned verbatim, as before.
174
+ _VERBATIM_ERRORS = (ValueError, FileNotFoundError, FileExistsError, PVsystError)
175
+ # Everything mapped to a ToolError. Any other OSError (a CSV/PDF locked by another program,
176
+ # a full disk, a launcher failure) would otherwise reach the client as the SDK's bare
177
+ # "Error executing tool" with its message dropped.
178
+ _REPORTED_ERRORS = (ValueError, OSError, PVsystError)
179
+
180
+
181
+ def _tool_error(exc: Exception) -> ToolError:
182
+ if isinstance(exc, _VERBATIM_ERRORS):
183
+ return ToolError(str(exc))
184
+ return ToolError(f"{type(exc).__name__}: {exc}")
185
+
186
+
187
+ def categorized_tool():
188
+ """Label MCP descriptions without changing established wire-level tool names."""
189
+ def register(func):
190
+ category = TOOL_CATEGORY[func.__name__]
191
+ params = frozenset(inspect.signature(func).parameters)
192
+ @wraps(func)
193
+ def guarded(*args, **kwargs):
194
+ try:
195
+ return func(*args, **kwargs)
196
+ except _REPORTED_ERRORS as exc:
197
+ raise _tool_error(exc) from None
198
+ description = f"[{category}] {inspect.getdoc(func)}"
199
+ _tool_registry[func.__name__] = (description, guarded, params)
200
+ if func.__name__ in ACTIVE_TOOL_NAMES:
201
+ if func.__name__ in STRICT_ARGUMENT_TOOLS:
202
+ # Typos are rejected against the published signature, so the whitelist cannot drift.
203
+ _strict_arguments[func.__name__] = params
204
+ mcp.tool(description=description)(guarded)
205
+ return func
206
+ return register
207
+
208
+
209
+ def create_mcp_server(tool_groups: str | None = None) -> MCPServer:
210
+ """Create an isolated MCPServer populated for the requested PVSYST_TOOL_GROUPS spec."""
211
+ groups = resolve_tool_groups(tool_groups)
212
+ names = tool_names_for_groups(groups)
213
+ for mod in import_modules_for_groups(groups):
214
+ import_module(f".{mod}", __package__)
215
+ missing = sorted((set(STRICT_ARGUMENT_TOOLS) & names) - set(_tool_registry))
216
+ if missing:
217
+ raise RuntimeError(f"Unregistered strict entry points: {missing}")
218
+ server = MCPServer("pvsyst-cli", instructions=SERVER_INSTRUCTIONS)
219
+ register_guidance(server)
220
+ strict_map: dict[str, frozenset[str]] = {}
221
+ server.middleware.append(make_strict_middleware(strict_map))
222
+ for name in sorted(names):
223
+ description, guarded, params = _tool_registry[name]
224
+ if name in STRICT_ARGUMENT_TOOLS:
225
+ strict_map[name] = params
226
+ server.tool(description=description)(guarded)
227
+ return server
228
+
229
+ def cli() -> PVsystCLI:
230
+ global _cli, _cli_key, _cli_owner
231
+ with _cli_init_lock:
232
+ key = (os.environ.get("PVSYST_CLI"), os.environ.get("PVSYST_WORKSPACE"))
233
+ if _cli is None or (_cli is _cli_owner and _cli_key != key):
234
+ _cli = _cli_owner = None
235
+ _cli_key = None
236
+ _cli = _cli_owner = PVsystCLI(*key)
237
+ _cli_key = key
238
+ return _cli
239
+
240
+ def components() -> ComponentStore:
241
+ current = cli()
242
+ configured = os.environ.get("PVSYST_BUILTIN_COMPONENTS")
243
+ if configured:
244
+ builtin = Path(configured).resolve(strict=True)
245
+ if not builtin.is_dir() or builtin.name != "ComposPV":
246
+ raise ValueError("PVSYST_BUILTIN_COMPONENTS must be a ComposPV directory")
247
+ else:
248
+ data_ro = current.cli.parent / "DataRO"
249
+ candidates = (sorted(path / "ComposPV" for path in data_ro.iterdir()
250
+ if path.is_dir() and (path / "ComposPV").is_dir())
251
+ if data_ro.is_dir() else [])
252
+ if len(candidates) > 1:
253
+ raise ValueError("Multiple DataRO component libraries; set PVSYST_BUILTIN_COMPONENTS")
254
+ builtin = candidates[0] if candidates else None
255
+ return ComponentStore(current.workspace, builtin, current._lock)
256
+
257
+ def component_call(method: str, *args, **kwargs) -> dict:
258
+ try:
259
+ return getattr(components(), method)(*args, **kwargs)
260
+ except _REPORTED_ERRORS as exc:
261
+ raise _tool_error(exc) from None
262
+
263
+ def variant_store() -> VariantStore:
264
+ store = components()
265
+ return VariantStore(store.workspace, store, store.lock)
266
+
267
+ def variant_call(method: str, *args, **kwargs) -> dict:
268
+ try:
269
+ return getattr(variant_store(), method)(*args, **kwargs)
270
+ except _REPORTED_ERRORS as exc:
271
+ raise _tool_error(exc) from None
272
+
273
+ def workspace_path(folder: str, filename: str, extension: str) -> Path:
274
+ """Allow a filename only within a named directory of the configured workspace."""
275
+ return workspace_file(cli().workspace, folder, filename, extension)
276
+
277
+ def optional_path(folder: str, filename: str, extension: str) -> Path | None:
278
+ return workspace_path(folder, filename, extension) if filename else None
279
+
280
+ def simulation_csv_path(filename: str) -> Path | None:
281
+ """Accept a bare single-run output name while preserving workspace checks."""
282
+ if not filename:
283
+ return None
284
+ if filename not in (".", "..") and not filename.endswith(".") and not Path(filename).suffix:
285
+ filename += ".csv"
286
+ return workspace_path("Results", filename, ".csv")
287
+
288
+ def result_path(folder: str, csv_name: str) -> Path:
289
+ if folder not in ("Results", "UserHourly"):
290
+ raise ValueError("Results folder must be Results or UserHourly")
291
+ return workspace_path(folder, csv_name, ".csv")
@@ -0,0 +1,186 @@
1
+ """Engineering MCP operations; native and domain behavior stays in the existing modules."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Annotated, Any, Literal
5
+ from pydantic import Field, StrictBool, StrictStr
6
+ from pvsyst_auto.engineering.brief import EngineeringBriefRequest, review_engineering_brief
7
+ from pvsyst_auto.engineering.suggest import suggest_sizing
8
+ from pvsyst_auto.api.schemas import (
9
+ EconomicsFinancialConfig,
10
+ EconomicsScenarioInput,
11
+ EconomicsSensitivityConfig,
12
+ EconomicsTariffConfig,
13
+ EngineeringBlock,
14
+ EngineeringRevisionRequest,
15
+ EngineeringScenario,
16
+ FeasibilityStudyRequest,
17
+ ReportScenarioInput,
18
+ StrictNum,
19
+ )
20
+ from pvsyst_auto.api.context import categorized_tool, cli, variant_store
21
+
22
+
23
+ @categorized_tool()
24
+ def pvsyst_suggest_sizing(
25
+ pan_name: StrictStr, ond_name: StrictStr, target_dc_kw: StrictNum,
26
+ voltage_standard: Literal["IEC", "UL"] = "IEC",
27
+ min_ambient_c: StrictNum = -10.0,
28
+ min_operating_c: StrictNum = 0.0,
29
+ max_operating_c: StrictNum = 65.0,
30
+ min_dc_ac_ratio: StrictNum = 0.85,
31
+ max_dc_ac_ratio: StrictNum = 1.25,
32
+ capacity_tolerance_pct: StrictNum = 8.0,
33
+ beta_voc_pct_per_c: StrictNum | None = None,
34
+ beta_vmp_pct_per_c: StrictNum | None = None,
35
+ alpha_isc_pct_per_c: StrictNum | None = None) -> dict:
36
+ """Read-only sizing assistant: derive recommended series/parallel/inverter counts and a drop-in
37
+ capacity envelope from readable PAN/OND files with explicit assumptions (requires engineering review)."""
38
+ return suggest_sizing(
39
+ variant_store(),
40
+ pan_name=pan_name, ond_name=ond_name, target_dc_kw=target_dc_kw,
41
+ voltage_standard=voltage_standard,
42
+ min_ambient_c=min_ambient_c, min_operating_c=min_operating_c, max_operating_c=max_operating_c,
43
+ min_dc_ac_ratio=min_dc_ac_ratio, max_dc_ac_ratio=max_dc_ac_ratio,
44
+ capacity_tolerance_pct=capacity_tolerance_pct,
45
+ beta_voc_pct_per_c=beta_voc_pct_per_c,
46
+ beta_vmp_pct_per_c=beta_vmp_pct_per_c,
47
+ alpha_isc_pct_per_c=alpha_isc_pct_per_c,
48
+ )
49
+
50
+
51
+ @categorized_tool()
52
+ def pvsyst_prepare_block_project(source_project: StrictStr, source_variant: StrictStr,
53
+ new_project: StrictStr,
54
+ blocks: Annotated[list[EngineeringBlock], Field(min_length=1, max_length=100)],
55
+ dry_run: StrictBool = True) -> dict:
56
+ """Assemble a new project by repeating fixed subarray blocks from a template project
57
+ by integer counts (1..100 total blocks covering every source subarray)."""
58
+ from pvsyst_auto.workflows.blocks import prepare_block_project
59
+ return prepare_block_project(variant_store(), source_project=source_project, source_variant=source_variant,
60
+ new_project=new_project, blocks=[block.model_dump() for block in blocks], dry_run=dry_run)
61
+
62
+ @categorized_tool()
63
+ def pvsyst_review_engineering_brief(brief: EngineeringBriefRequest) -> dict:
64
+ """Check structured feasibility claims (module/inverter counts, strings, block schedules,
65
+ and required PAN/OND/weather filenames) for internal consistency and missing inputs."""
66
+ return review_engineering_brief(brief)
67
+
68
+ @categorized_tool()
69
+ def pvsyst_project_handoff(project: StrictStr, variant: StrictStr,
70
+ declarations: dict[StrictStr, Any] | None = None) -> dict:
71
+ """Read saved equipment, counts, orientation/circuit relationships, weather, load,
72
+ and storage settings alongside caller declarations and missing inputs."""
73
+ from pvsyst_auto.engineering.handoff import build_project_handoff
74
+ return build_project_handoff(variant_store(), project=project, variant=variant, declarations=declarations)
75
+
76
+ @categorized_tool()
77
+ def pvsyst_run_engineering_task(spec: EngineeringRevisionRequest, dry_run: StrictBool = True) -> dict:
78
+ """Apply an isolated revision (fixed angles/losses, UnlimTracking controls, or AC-coupled
79
+ storage with hourly load) in a new project and run a full-year simulation."""
80
+ from pvsyst_auto.workflows.revision import run_engineering_task
81
+ return run_engineering_task(cli(), variant_store(), **spec.model_dump(exclude_none=True), dry_run=dry_run)
82
+
83
+ @categorized_tool()
84
+ def pvsyst_compare_engineering_scenarios(objective: StrictStr, scenarios: list[EngineeringScenario],
85
+ output_name: StrictStr, dry_run: StrictBool = True) -> dict:
86
+ """Compare two or three completed simulation runs against a baseline scenario and write
87
+ JSON, CSV, and Markdown comparison reports under workspace/Results."""
88
+ from pvsyst_auto.engineering.comparison import compare_engineering_scenarios
89
+ return compare_engineering_scenarios(variant_store(), objective=objective,
90
+ scenarios=[scenario.model_dump(exclude_none=True) for scenario in scenarios],
91
+ output_name=output_name, dry_run=dry_run)
92
+
93
+ @categorized_tool()
94
+ def pvsyst_evaluate_economics(
95
+ scenarios: list[EconomicsScenarioInput] | None = None,
96
+ batch_summary_csv: StrictStr | None = None,
97
+ financial: EconomicsFinancialConfig | None = None,
98
+ tariff: EconomicsTariffConfig | None = None,
99
+ sensitivity: EconomicsSensitivityConfig | None = None,
100
+ rank_by: Literal[
101
+ "npv", "irr", "lcoe", "simple_payback_years",
102
+ "discounted_payback_years", "year1_net_benefit",
103
+ ] = "npv",
104
+ include_cashflow_schedule: StrictBool = True) -> dict:
105
+ """Pure-Python PV and PV+BESS financial evaluator: streams hourly or sub-hourly SFI CSVs
106
+ (or UserBatch summary CSVs) under fixed, time-of-use (TOU), or two-part demand-charge tariffs
107
+ to compute LCOE, NPV, IRR, simple/discounted payback, battery replacement cashflows,
108
+ one-at-a-time sensitivity sweeps, and scenario rankings."""
109
+ from pvsyst_auto.engineering.economics import evaluate_economics
110
+ return evaluate_economics(
111
+ workspace=cli().workspace,
112
+ scenarios=[s.model_dump(exclude_none=True) for s in scenarios] if scenarios is not None else None,
113
+ batch_summary_csv=batch_summary_csv,
114
+ financial=financial.model_dump(exclude_none=True) if financial is not None else None,
115
+ tariff=tariff.model_dump(exclude_none=True) if tariff is not None else None,
116
+ sensitivity=sensitivity.model_dump(exclude_none=True) if sensitivity is not None else None,
117
+ rank_by=rank_by,
118
+ include_cashflow_schedule=include_cashflow_schedule,
119
+ )
120
+
121
+
122
+ @categorized_tool()
123
+ def pvsyst_generate_report(
124
+ title: StrictStr,
125
+ output_name: StrictStr,
126
+ scenarios: Annotated[list[ReportScenarioInput], Field(min_length=1, max_length=20)],
127
+ financial: EconomicsFinancialConfig | None = None,
128
+ tariff: EconomicsTariffConfig | None = None,
129
+ sensitivity: EconomicsSensitivityConfig | None = None,
130
+ bess_optimization: dict[StrictStr, Any] | None = None,
131
+ language: Literal["zh", "en"] = "zh",
132
+ plotlyjs: Literal["cdn", "embed"] = "cdn",
133
+ thresholds: dict[StrictStr, StrictNum] | None = None,
134
+ overwrite: StrictBool = False,
135
+ dry_run: StrictBool = False) -> dict:
136
+ """Generate a single-scenario or multi-scenario interactive Plotly HTML engineering report
137
+ under workspace/Results (monthly yield/PR combo, loss waterfall, typical 24h PV/load/BESS/TOU
138
+ profile, monthly peak demand shaving, 25-year cumulative cashflow, sensitivity tornado chart,
139
+ optional BESS sizing heatmap/Pareto frontier, diagnostics table, and print-ready CSS)."""
140
+ from pvsyst_auto.workflows.report import generate_report
141
+ return generate_report(
142
+ workspace=cli().workspace,
143
+ store=variant_store(),
144
+ title=title,
145
+ output_name=output_name,
146
+ scenarios=[s.model_dump(exclude_none=True) for s in scenarios],
147
+ financial=financial.model_dump(exclude_none=True) if financial is not None else None,
148
+ tariff=tariff.model_dump(exclude_none=True) if tariff is not None else None,
149
+ sensitivity=sensitivity.model_dump(exclude_none=True) if sensitivity is not None else None,
150
+ bess_optimization=bess_optimization,
151
+ language=language,
152
+ plotlyjs=plotlyjs,
153
+ thresholds=thresholds,
154
+ overwrite=overwrite,
155
+ dry_run=dry_run,
156
+ )
157
+
158
+
159
+ @categorized_tool()
160
+ def pvsyst_export_engineering_delivery(manifest_name: StrictStr, output_name: StrictStr,
161
+ dry_run: StrictBool = True, comparison_name: StrictStr = "") -> dict:
162
+ """Bundle a completed engineering run (and optional scenario comparison) with its PRJ/VC,
163
+ result CSV/PDF, and Markdown handoff summary into a ZIP archive under workspace/Results."""
164
+ from pvsyst_auto.workflows.delivery import export_engineering_delivery
165
+ return export_engineering_delivery(variant_store(), manifest_name=manifest_name,
166
+ output_name=output_name, dry_run=dry_run, comparison_name=comparison_name)
167
+
168
+
169
+ @categorized_tool()
170
+ def pvsyst_run_feasibility_study(
171
+ spec: FeasibilityStudyRequest,
172
+ dry_run: StrictBool = True,
173
+ confirm: StrictBool = False) -> dict:
174
+ """One-shot end-to-end PV & PV+BESS feasibility study orchestrator: chains optional
175
+ zero-template PAN/OND/BTR synthesis, PV simulation (or reuse of existing_csv), physics
176
+ diagnostics, TOU PowerShift 48-slot planning, two-stage hybrid BESS sizing optimization,
177
+ two-part demand/TOU economics with sensitivity tornado analysis, and bilingual Plotly HTML
178
+ report generation. Defaults to dry_run=true; requires dry_run=false and confirm=true to write."""
179
+ from pvsyst_auto.workflows.feasibility import run_feasibility_study
180
+ return run_feasibility_study(
181
+ cli(),
182
+ variant_store(),
183
+ spec=spec.model_dump(exclude_none=True),
184
+ dry_run=dry_run,
185
+ confirm=confirm,
186
+ )