propermesh-mcp 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- propermesh_mcp/__init__.py +1 -0
- propermesh_mcp/config.py +42 -0
- propermesh_mcp/errors.py +23 -0
- propermesh_mcp/layers.py +40 -0
- propermesh_mcp/output.py +34 -0
- propermesh_mcp/parts.py +93 -0
- propermesh_mcp/report.py +187 -0
- propermesh_mcp/server.py +196 -0
- propermesh_mcp/session.py +107 -0
- propermesh_mcp/static/viewer.html +607 -0
- propermesh_mcp/summaries.py +446 -0
- propermesh_mcp/test_config.py +32 -0
- propermesh_mcp/test_errors.py +37 -0
- propermesh_mcp/test_layers.py +57 -0
- propermesh_mcp/test_output.py +49 -0
- propermesh_mcp/test_parts.py +63 -0
- propermesh_mcp/test_report.py +114 -0
- propermesh_mcp/test_server_stdio.py +109 -0
- propermesh_mcp/test_session.py +87 -0
- propermesh_mcp/test_summaries.py +253 -0
- propermesh_mcp/test_tools_integration.py +302 -0
- propermesh_mcp/test_viewer_server.py +341 -0
- propermesh_mcp/test_visualize.py +249 -0
- propermesh_mcp/tools.py +364 -0
- propermesh_mcp/viewer_server.py +403 -0
- propermesh_mcp/visualize.py +208 -0
- propermesh_mcp-0.1.0.dist-info/METADATA +159 -0
- propermesh_mcp-0.1.0.dist-info/RECORD +31 -0
- propermesh_mcp-0.1.0.dist-info/WHEEL +4 -0
- propermesh_mcp-0.1.0.dist-info/entry_points.txt +2 -0
- propermesh_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""MCP server that wraps the Propermesh API (https://propermesh.com) for AI agents"""
|
propermesh_mcp/config.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""The server's settings, read from the environment the MCP client launches it with"""
|
|
2
|
+
from collections.abc import Mapping
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
ACCESS_KEY_VAR = 'PROPERMESH_ACCESS_KEY'
|
|
6
|
+
SECRET_KEY_VAR = 'PROPERMESH_SECRET_KEY'
|
|
7
|
+
DOMAIN_VAR = 'PROPERMESH_DOMAIN'
|
|
8
|
+
DEFAULT_DOMAIN = 'https://propermesh.com'
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class Settings:
|
|
13
|
+
# Empty when the variable isn't set. The server still starts so the client can list its tools, and
|
|
14
|
+
# every tool call says which variables are missing
|
|
15
|
+
access_key: str
|
|
16
|
+
secret_key: str
|
|
17
|
+
# Without a trailing slash
|
|
18
|
+
domain: str
|
|
19
|
+
|
|
20
|
+
@property
|
|
21
|
+
def missing_variables(self) -> list[str]:
|
|
22
|
+
return [name for name, value in ((ACCESS_KEY_VAR, self.access_key), (SECRET_KEY_VAR, self.secret_key))
|
|
23
|
+
if not value]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def settings_from_env(env: Mapping[str, str]) -> Settings:
|
|
27
|
+
domain = env.get(DOMAIN_VAR, '').strip() or DEFAULT_DOMAIN
|
|
28
|
+
return Settings(
|
|
29
|
+
access_key=env.get(ACCESS_KEY_VAR, '').strip(),
|
|
30
|
+
secret_key=env.get(SECRET_KEY_VAR, '').strip(),
|
|
31
|
+
domain=domain.rstrip('/'),
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def missing_keys_message(settings: Settings) -> str | None:
|
|
36
|
+
"""The error every tool returns while the API keys aren't set, or None when they are"""
|
|
37
|
+
missing = settings.missing_variables
|
|
38
|
+
if not missing:
|
|
39
|
+
return None
|
|
40
|
+
return (f'{" and ".join(missing)} {"is" if len(missing) == 1 else "are"} not set. Set '
|
|
41
|
+
f'{ACCESS_KEY_VAR} and {SECRET_KEY_VAR} to a Propermesh API key in the MCP server\'s '
|
|
42
|
+
'environment (e.g. claude mcp add -e), then restart the server')
|
propermesh_mcp/errors.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Agent-readable messages for the errors a tool call can hit"""
|
|
2
|
+
from propermesh import ProperMeshAPIError
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class ToolFailure(Exception):
|
|
6
|
+
"""A tool call that can't return a result. The MCP server turns it into a tool error (isError) with
|
|
7
|
+
this message, which is written for the agent that called the tool"""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def api_error_message(err: ProperMeshAPIError) -> str:
|
|
11
|
+
status, detail = err.status_code, err.detail
|
|
12
|
+
if status in (401, 403):
|
|
13
|
+
return (f'Propermesh rejected the API key ({status}: {detail}). Check PROPERMESH_ACCESS_KEY and '
|
|
14
|
+
'PROPERMESH_SECRET_KEY')
|
|
15
|
+
if status == 413:
|
|
16
|
+
return f'The file is too big for your Propermesh plan: {detail}'
|
|
17
|
+
if status == 429:
|
|
18
|
+
retry = (f' Retry after {err.retry_after} seconds.' if err.retry_after is not None
|
|
19
|
+
else ' Waiting won\'t help until the limit resets or the plan changes.')
|
|
20
|
+
return f'A Propermesh usage limit was reached: {detail}.{retry}'
|
|
21
|
+
if status >= 500:
|
|
22
|
+
return f'Propermesh had a server error ({status}: {detail}). Try again in a minute'
|
|
23
|
+
return f'Propermesh refused the request ({status}): {detail}'
|
propermesh_mcp/layers.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Reads the per-face value layers the API serves and reduces them to the numbers the checks report. Pure"""
|
|
2
|
+
import math
|
|
3
|
+
import sys
|
|
4
|
+
from array import array
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
MM_PER_INCH = 25.4
|
|
8
|
+
MAX_THICKNESS_MM = 1000.0 # the API's bound on a thickness threshold
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def decode_layer(data: bytes, face_count: Optional[int] = None) -> array:
|
|
12
|
+
"""The float32 values of a layer (little-endian on the wire). Later API versions may append data after
|
|
13
|
+
the first face_count values, so only those are read when the count is given"""
|
|
14
|
+
values = array('f')
|
|
15
|
+
usable = len(data) - len(data) % values.itemsize
|
|
16
|
+
values.frombytes(data[:usable])
|
|
17
|
+
if sys.byteorder == 'big':
|
|
18
|
+
values.byteswap()
|
|
19
|
+
return values[:face_count] if face_count is not None else values
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def thinnest(values: array) -> Optional[float]:
|
|
23
|
+
"""The smallest finite value (NaN is unknown), or None when there is none"""
|
|
24
|
+
finite = [v for v in values if math.isfinite(v)]
|
|
25
|
+
return min(finite) if finite else None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def worst_overhang(values: array, critical_angle: float) -> Optional[float]:
|
|
29
|
+
"""The smallest angle below critical_angle, ignoring build-plate faces (Infinity) and unknown ones
|
|
30
|
+
(NaN). None when no face is below it"""
|
|
31
|
+
below = [v for v in values if math.isfinite(v) and v < critical_angle]
|
|
32
|
+
return min(below) if below else None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def length_to_mm(value: Optional[float], units: Optional[str]) -> Optional[float]:
|
|
36
|
+
return value * MM_PER_INCH if value is not None and units == 'inches' else value
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def area_to_mm2(value: Optional[float], units: Optional[str]) -> Optional[float]:
|
|
40
|
+
return value * MM_PER_INCH ** 2 if value is not None and units == 'inches' else value
|
propermesh_mcp/output.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Where a tool writes the STL it downloads, and the write itself"""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from propermesh_mcp.errors import ToolFailure
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def output_path_for(input_path: Optional[Path], explicit: Optional[str], suffix: str) -> Optional[Path]:
|
|
9
|
+
"""The file to write, or None to write nothing.
|
|
10
|
+
|
|
11
|
+
explicit (~ expanded) wins. Otherwise a file input gets `<stem>-<suffix>.stl` next to it, and a part_id
|
|
12
|
+
input (input_path None) gets nothing. Raises ToolFailure if the target is the input file"""
|
|
13
|
+
explicit = (explicit or '').strip() or None
|
|
14
|
+
if explicit:
|
|
15
|
+
target = Path(explicit).expanduser().resolve()
|
|
16
|
+
elif input_path is not None:
|
|
17
|
+
target = input_path.with_name(f'{input_path.stem}-{suffix}.stl')
|
|
18
|
+
else:
|
|
19
|
+
return None
|
|
20
|
+
if input_path is not None and target == input_path.resolve():
|
|
21
|
+
raise ToolFailure(f'The output path {target} is the input file. Pick another output_path: '
|
|
22
|
+
'the input is never overwritten')
|
|
23
|
+
return target
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def write_stl(target: Path, data: bytes) -> bool:
|
|
27
|
+
"""Writes data to target, creating parent directories. Returns whether it replaced an existing file"""
|
|
28
|
+
replaced = target.exists()
|
|
29
|
+
try:
|
|
30
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
31
|
+
target.write_bytes(data)
|
|
32
|
+
except OSError as e:
|
|
33
|
+
raise ToolFailure(f'Couldn\'t write {target}: {e}') from e
|
|
34
|
+
return replaced
|
propermesh_mcp/parts.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Turns a tool's path or part_id input into a part id, uploading a path once per server process"""
|
|
2
|
+
import threading
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Literal, NamedTuple, Protocol, Union
|
|
6
|
+
|
|
7
|
+
from propermesh import ProperMeshClient
|
|
8
|
+
|
|
9
|
+
from propermesh_mcp.errors import ToolFailure
|
|
10
|
+
|
|
11
|
+
UnitsName = Literal['mm', 'inches']
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class PathInput:
|
|
16
|
+
path: str
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class PartIdInput:
|
|
21
|
+
part_id: str
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
PartInput = Union[PathInput, PartIdInput]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def choose_input(path: str | None, part_id: str | None) -> PartInput:
|
|
28
|
+
"""The one input the tool was given. Raises ToolFailure for both or neither (blank counts as unset)"""
|
|
29
|
+
path = (path or '').strip() or None
|
|
30
|
+
part_id = (part_id or '').strip() or None
|
|
31
|
+
if path and part_id:
|
|
32
|
+
raise ToolFailure('Pass either path or part_id, not both')
|
|
33
|
+
if path:
|
|
34
|
+
return PathInput(path)
|
|
35
|
+
if part_id:
|
|
36
|
+
return PartIdInput(part_id)
|
|
37
|
+
raise ToolFailure('Pass path (a local STL, OBJ, 3MF or STEP file) or the part_id of an uploaded part')
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class CacheKey(NamedTuple):
|
|
41
|
+
path: str
|
|
42
|
+
size: int
|
|
43
|
+
mtime_ns: int
|
|
44
|
+
units: str
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class FileStat(Protocol):
|
|
48
|
+
"""The parts of os.stat_result the cache key reads"""
|
|
49
|
+
@property
|
|
50
|
+
def st_size(self) -> int: ...
|
|
51
|
+
@property
|
|
52
|
+
def st_mtime_ns(self) -> int: ...
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def cache_key(path: Path, stat: FileStat, units: str) -> CacheKey:
|
|
56
|
+
"""The upload cache's key for an absolute path. A file with a new size or mtime is a new key, so an
|
|
57
|
+
edited file uploads again"""
|
|
58
|
+
return CacheKey(str(path), stat.st_size, stat.st_mtime_ns, units)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def existing_file(path: str) -> Path:
|
|
62
|
+
"""The absolute path of a file input, with ~ expanded. Raises ToolFailure if it isn't a file"""
|
|
63
|
+
resolved = Path(path).expanduser().resolve()
|
|
64
|
+
if not resolved.is_file():
|
|
65
|
+
raise ToolFailure(f'No file at {resolved}' if not resolved.exists() else f'{resolved} is not a file')
|
|
66
|
+
return resolved
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class PartResolver:
|
|
70
|
+
"""Remembers the part each uploaded file became, for as long as the server runs, so the same file
|
|
71
|
+
uploads once across tool calls. Nothing is written to disk"""
|
|
72
|
+
|
|
73
|
+
def __init__(self) -> None:
|
|
74
|
+
self._parts: dict[CacheKey, str] = {}
|
|
75
|
+
self._lock = threading.Lock()
|
|
76
|
+
|
|
77
|
+
def part_id(self, client: ProperMeshClient, path: str | None, part_id: str | None,
|
|
78
|
+
units: UnitsName) -> str:
|
|
79
|
+
chosen = choose_input(path, part_id)
|
|
80
|
+
if isinstance(chosen, PartIdInput):
|
|
81
|
+
return chosen.part_id
|
|
82
|
+
|
|
83
|
+
file = existing_file(chosen.path)
|
|
84
|
+
key = cache_key(file, file.stat(), units)
|
|
85
|
+
with self._lock:
|
|
86
|
+
cached = self._parts.get(key)
|
|
87
|
+
if cached is not None:
|
|
88
|
+
return cached
|
|
89
|
+
|
|
90
|
+
uploaded = client.upload_part_file(str(file), units)
|
|
91
|
+
with self._lock:
|
|
92
|
+
self._parts[key] = uploaded
|
|
93
|
+
return uploaded
|
propermesh_mcp/report.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""The printability report: one verdict and the issues behind it, built from the four analyses. Pure: no I/O"""
|
|
2
|
+
from typing import Literal, Optional, Union
|
|
3
|
+
|
|
4
|
+
# See summaries.py for why TypedDict comes from typing_extensions
|
|
5
|
+
from typing_extensions import TypedDict, TypeIs
|
|
6
|
+
|
|
7
|
+
from propermesh_mcp.summaries import (
|
|
8
|
+
BoundingBox, GeometryDefects, GeometrySummary, OrientationSummary, OverhangSummary, ThicknessSummary,
|
|
9
|
+
analyzer_url)
|
|
10
|
+
|
|
11
|
+
Verdict = Literal['ready', 'needs_attention', 'not_printable']
|
|
12
|
+
Check = Literal['geometry', 'thickness', 'overhang', 'orientation']
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Issue(TypedDict):
|
|
16
|
+
severity: Literal['error', 'warning']
|
|
17
|
+
check: Check
|
|
18
|
+
message: str
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class SectionError(TypedDict):
|
|
22
|
+
"""A sub-analysis that failed. The report still returns the others"""
|
|
23
|
+
error: str
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ReportGeometry(TypedDict):
|
|
27
|
+
units: Optional[str]
|
|
28
|
+
volume: Optional[float]
|
|
29
|
+
surface_area: Optional[float]
|
|
30
|
+
bounding_box: BoundingBox
|
|
31
|
+
is_watertight: Optional[bool]
|
|
32
|
+
is_manifold: Optional[bool]
|
|
33
|
+
is_winding_consistent: Optional[bool]
|
|
34
|
+
num_shells: Optional[int]
|
|
35
|
+
defects: GeometryDefects
|
|
36
|
+
printable_as_is: bool
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ReportThickness(TypedDict):
|
|
40
|
+
min_thickness_mm: float
|
|
41
|
+
has_thin_walls: Optional[bool]
|
|
42
|
+
thin_surface_area: Optional[float]
|
|
43
|
+
thin_area_percent: Optional[float]
|
|
44
|
+
thinnest_wall: Optional[float]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ReportOverhang(TypedDict):
|
|
48
|
+
critical_angle_deg: float
|
|
49
|
+
needs_supports: bool
|
|
50
|
+
overhang_surface_area: Optional[float]
|
|
51
|
+
overhang_area_percent: Optional[float]
|
|
52
|
+
worst_overhang_angle_deg: Optional[float]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ReportOrientation(TypedDict):
|
|
56
|
+
rotation_matrix: Optional[list[list[float]]]
|
|
57
|
+
already_optimal: Optional[bool]
|
|
58
|
+
oriented_part_id: Optional[str]
|
|
59
|
+
oriented_stl_path: Optional[str]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class PrintabilityReport(TypedDict):
|
|
63
|
+
part_id: str
|
|
64
|
+
analyzer_url: str
|
|
65
|
+
verdict: Verdict
|
|
66
|
+
issues: list[Issue]
|
|
67
|
+
geometry: ReportGeometry
|
|
68
|
+
thickness: Union[ReportThickness, SectionError]
|
|
69
|
+
overhang: Union[ReportOverhang, SectionError]
|
|
70
|
+
orientation: Union[ReportOrientation, SectionError]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def is_error(section: object) -> TypeIs[SectionError]:
|
|
74
|
+
return isinstance(section, dict) and 'error' in section
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# The short names of the defect counts, for the issue message
|
|
78
|
+
DEFECT_NAMES: dict[str, str] = {
|
|
79
|
+
'num_boundary_edges': 'boundary edges',
|
|
80
|
+
'num_non_manifold_edges': 'non-manifold edges',
|
|
81
|
+
'num_non_manifold_vertices': 'non-manifold vertices',
|
|
82
|
+
'num_degenerate_faces': 'degenerate triangles',
|
|
83
|
+
'num_duplicate_faces': 'duplicate triangles',
|
|
84
|
+
'num_flipped_triangles': 'flipped triangles',
|
|
85
|
+
'num_intersecting_faces': 'self-intersecting triangles',
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def report_geometry(summary: GeometrySummary) -> ReportGeometry:
|
|
90
|
+
return ReportGeometry(
|
|
91
|
+
units=summary['units'], volume=summary['volume'], surface_area=summary['surface_area'],
|
|
92
|
+
bounding_box=summary['bounding_box'], is_watertight=summary['is_watertight'],
|
|
93
|
+
is_manifold=summary['is_manifold'], is_winding_consistent=summary['is_winding_consistent'],
|
|
94
|
+
num_shells=summary['num_shells'], defects=summary['defects'], printable_as_is=summary['printable_as_is'])
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def report_thickness(summary: ThicknessSummary) -> ReportThickness:
|
|
98
|
+
return ReportThickness(
|
|
99
|
+
min_thickness_mm=summary['min_thickness_mm'], has_thin_walls=summary['has_thin_walls'],
|
|
100
|
+
thin_surface_area=summary['thin_surface_area'], thin_area_percent=summary['thin_area_percent'],
|
|
101
|
+
thinnest_wall=summary['thinnest_wall'])
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def report_overhang(summary: OverhangSummary) -> ReportOverhang:
|
|
105
|
+
return ReportOverhang(
|
|
106
|
+
critical_angle_deg=summary['critical_angle_deg'], needs_supports=summary['needs_supports'],
|
|
107
|
+
overhang_surface_area=summary['overhang_surface_area'],
|
|
108
|
+
overhang_area_percent=summary['overhang_area_percent'],
|
|
109
|
+
worst_overhang_angle_deg=summary['worst_overhang_angle_deg'])
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def report_orientation(summary: OrientationSummary) -> ReportOrientation:
|
|
113
|
+
return ReportOrientation(
|
|
114
|
+
rotation_matrix=summary['rotation_matrix'], already_optimal=summary['already_optimal'],
|
|
115
|
+
oriented_part_id=summary['oriented_part_id'], oriented_stl_path=summary['oriented_stl_path'])
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def geometry_issues(geometry: ReportGeometry) -> list[Issue]:
|
|
119
|
+
issues: list[Issue] = []
|
|
120
|
+
problems = [f'{count} {DEFECT_NAMES[field]}' for field, count in geometry['defects'].items()
|
|
121
|
+
if field in DEFECT_NAMES]
|
|
122
|
+
flags = ((geometry['is_watertight'], 'not watertight'), (geometry['is_manifold'], 'not manifold'),
|
|
123
|
+
(geometry['is_winding_consistent'], 'inconsistent winding'))
|
|
124
|
+
problems = [label for value, label in flags if value is False] + problems
|
|
125
|
+
if problems:
|
|
126
|
+
issues.append(Issue(severity='error', check='geometry',
|
|
127
|
+
message=f'Mesh defects: {", ".join(problems)}. Run repair_mesh to fix them'))
|
|
128
|
+
shells = geometry['num_shells']
|
|
129
|
+
if shells and shells > 1:
|
|
130
|
+
issues.append(Issue(severity='warning', check='geometry',
|
|
131
|
+
message=f'{shells} shells: the file holds separate bodies'))
|
|
132
|
+
return issues
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def thickness_issues(thickness: Union[ReportThickness, SectionError]) -> list[Issue]:
|
|
136
|
+
if is_error(thickness):
|
|
137
|
+
return [Issue(severity='warning', check='thickness', message=f'Thickness check failed: {thickness["error"]}')]
|
|
138
|
+
if thickness['has_thin_walls'] is not True:
|
|
139
|
+
return []
|
|
140
|
+
return [Issue(severity='warning', check='thickness', message=(
|
|
141
|
+
f'Walls thinner than {thickness["min_thickness_mm"]:g} mm: thinnest_wall is '
|
|
142
|
+
f'{thickness["thinnest_wall"]} mm, {thickness["thin_area_percent"]}% of the surface'))]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def overhang_issues(overhang: Union[ReportOverhang, SectionError]) -> list[Issue]:
|
|
146
|
+
if is_error(overhang):
|
|
147
|
+
return [Issue(severity='warning', check='overhang', message=f'Overhang check failed: {overhang["error"]}')]
|
|
148
|
+
if not overhang['needs_supports']:
|
|
149
|
+
return []
|
|
150
|
+
return [Issue(severity='warning', check='overhang', message=(
|
|
151
|
+
f'Overhangs need supports: {overhang["overhang_area_percent"]}% of the surface slopes below '
|
|
152
|
+
f'{overhang["critical_angle_deg"]:g} degrees, worst {overhang["worst_overhang_angle_deg"]} degrees'))]
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def orientation_issues(orientation: Union[ReportOrientation, SectionError]) -> list[Issue]:
|
|
156
|
+
if is_error(orientation):
|
|
157
|
+
return [Issue(severity='warning', check='orientation',
|
|
158
|
+
message=f'Orientation search failed: {orientation["error"]}')]
|
|
159
|
+
return []
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def issues_from(geometry: ReportGeometry, thickness: Union[ReportThickness, SectionError],
|
|
163
|
+
overhang: Union[ReportOverhang, SectionError],
|
|
164
|
+
orientation: Union[ReportOrientation, SectionError]) -> list[Issue]:
|
|
165
|
+
"""Every problem the analyses found, errors first (they decide the verdict)"""
|
|
166
|
+
issues = (geometry_issues(geometry) + thickness_issues(thickness) + overhang_issues(overhang)
|
|
167
|
+
+ orientation_issues(orientation))
|
|
168
|
+
return sorted(issues, key=lambda issue: issue['severity'] != 'error')
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def verdict(issues: list[Issue]) -> Verdict:
|
|
172
|
+
if any(issue['severity'] == 'error' for issue in issues):
|
|
173
|
+
return 'not_printable'
|
|
174
|
+
return 'needs_attention' if issues else 'ready'
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def printability_report(part_id: str, domain: str, geometry: GeometrySummary,
|
|
178
|
+
thickness: Union[ThicknessSummary, SectionError], overhang: Union[OverhangSummary, SectionError],
|
|
179
|
+
orientation: Union[OrientationSummary, SectionError]) -> PrintabilityReport:
|
|
180
|
+
report_geo = report_geometry(geometry)
|
|
181
|
+
report_thick = thickness if is_error(thickness) else report_thickness(thickness)
|
|
182
|
+
report_over = overhang if is_error(overhang) else report_overhang(overhang)
|
|
183
|
+
report_orient = orientation if is_error(orientation) else report_orientation(orientation)
|
|
184
|
+
issues = issues_from(report_geo, report_thick, report_over, report_orient)
|
|
185
|
+
return PrintabilityReport(
|
|
186
|
+
part_id=part_id, analyzer_url=analyzer_url(domain, part_id), verdict=verdict(issues), issues=issues,
|
|
187
|
+
geometry=report_geo, thickness=report_thick, overhang=report_over, orientation=report_orient)
|
propermesh_mcp/server.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""The stdio MCP server: `propermesh-mcp`"""
|
|
2
|
+
import os
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from typing import Optional, TypeVar
|
|
5
|
+
|
|
6
|
+
import anyio.to_thread
|
|
7
|
+
from mcp.server.fastmcp import FastMCP
|
|
8
|
+
from propermesh import ProperMeshClient
|
|
9
|
+
from propermesh.client import package_version
|
|
10
|
+
|
|
11
|
+
from propermesh_mcp import tools
|
|
12
|
+
from propermesh_mcp.config import Settings, missing_keys_message, settings_from_env
|
|
13
|
+
from propermesh_mcp.errors import ToolFailure
|
|
14
|
+
from propermesh_mcp.parts import PartResolver, UnitsName
|
|
15
|
+
from propermesh_mcp.report import PrintabilityReport
|
|
16
|
+
from propermesh_mcp.session import JobCache
|
|
17
|
+
from propermesh_mcp.summaries import (
|
|
18
|
+
GeometrySummary, OrientationSummary, OverhangSummary, RepairSummary, ThicknessSummary)
|
|
19
|
+
from propermesh_mcp.viewer_server import LazyViewer
|
|
20
|
+
from propermesh_mcp.visualize import MAX_ITEMS, ViewerGroup, ViewerItem, ViewerRow, VisualizeSummary
|
|
21
|
+
|
|
22
|
+
INSTRUCTIONS = (
|
|
23
|
+
'Propermesh checks 3D models for 3D printing. Pass a tool the path of a local STL, OBJ, 3MF or STEP '
|
|
24
|
+
'file, or the part_id an earlier call returned. A path uploads once per session; reusing part_id '
|
|
25
|
+
'skips the upload. Each result links to the part in the Propermesh analyzer (analyzer_url).'
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
ANALYZE_GEOMETRY_DESCRIPTION = (
|
|
29
|
+
'Check a 3D model\'s geometry for printability: whether the mesh is watertight, manifold and '
|
|
30
|
+
'consistently wound, how many separate bodies (shells) it has, and counts of each defect (holes, '
|
|
31
|
+
'non-manifold edges and vertices, degenerate, duplicate, flipped and self-intersecting triangles). '
|
|
32
|
+
'Also returns volume, surface area and the bounding box, in the part\'s units (units cubed and '
|
|
33
|
+
'squared for volume and area). printable_as_is is true when the mesh can be sliced without repair.\n\n'
|
|
34
|
+
'Give exactly one of path (a local mesh file; ~ is expanded) or part_id (from an earlier call). '
|
|
35
|
+
'units says what a path\'s file is in, mm or inches, and only matters when uploading. '
|
|
36
|
+
'It can take a minute, longer for big files.'
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
CHECK_WALL_THICKNESS_DESCRIPTION = (
|
|
40
|
+
'Check whether any walls of a 3D model are thinner than min_thickness_mm (millimeters, greater than 0 '
|
|
41
|
+
'and at most 1000; 0.8 is typical for a 0.4 mm nozzle). Returns has_thin_walls, the area of the thin '
|
|
42
|
+
'surface and its percent of the whole, and thinnest_wall, the thinnest measured wall. All lengths and '
|
|
43
|
+
'areas are in mm and mm\u00b2, even when the part is in inches.\n\n'
|
|
44
|
+
'Give exactly one of path (a local mesh file; ~ is expanded) or part_id (from an earlier call). '
|
|
45
|
+
'units says what a path\'s file is in, mm or inches, and only matters when uploading; thickness '
|
|
46
|
+
'needs the part\'s units to be known. It can take a minute, longer for big files.'
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
CHECK_OVERHANGS_DESCRIPTION = (
|
|
50
|
+
'Check whether a 3D model needs supports, and where it overhangs. A face is an overhang when its '
|
|
51
|
+
'slope from horizontal is below critical_angle_deg (0 to 90, default 45): 0 is a flat ceiling and '
|
|
52
|
+
'90 a vertical wall, the PrusaSlicer convention and the opposite of Cura\'s, which measures from '
|
|
53
|
+
'vertical. Faces on the build plate never count. Returns needs_supports, the overhang area (mm\u00b2) '
|
|
54
|
+
'and its percent of the surface, the number of overhang faces and clusters, and '
|
|
55
|
+
'worst_overhang_angle_deg, the flattest overhang found.\n\n'
|
|
56
|
+
'Give exactly one of path (a local mesh file; ~ is expanded) or part_id (from an earlier call). '
|
|
57
|
+
'units says what a path\'s file is in, mm or inches, and only matters when uploading. '
|
|
58
|
+
'It can take a minute, longer for big files.'
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
FIND_PRINT_ORIENTATION_DESCRIPTION = (
|
|
62
|
+
'Find the best orientation to print a 3D model in (least support needed). Returns rotation_matrix, the '
|
|
63
|
+
'3x3 rotation to apply to the part\'s coordinates (the oriented mesh also sits with its lowest point at '
|
|
64
|
+
'z = 0), already_optimal when no rotation is needed, and oriented_part_id: the oriented mesh is a '
|
|
65
|
+
'part of its own, so pass it as part_id to the other tools.\n\n'
|
|
66
|
+
'Give exactly one of path (a local mesh file; ~ is expanded) or part_id (from an earlier call). '
|
|
67
|
+
'The oriented STL is written to output_path; for a path input without one it goes next to the input as '
|
|
68
|
+
'<name>-oriented.stl, and for a part_id input nothing is written. The input file is never overwritten. '
|
|
69
|
+
'units says what a path\'s file is in, mm or inches, and only matters when uploading. '
|
|
70
|
+
'It can take a minute, longer for big files.'
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
REPAIR_MESH_DESCRIPTION = (
|
|
74
|
+
'Repair a 3D model\'s mesh so it can be sliced: fills holes, merges overlapping bodies and removes bad '
|
|
75
|
+
'triangles. Returns the repaired mesh\'s is_watertight, is_manifold, is_winding_consistent and '
|
|
76
|
+
'num_shells, the method (exact, or wrapped: an approximation made when the exact repair fails), and '
|
|
77
|
+
'repaired_part_id: the repaired mesh is a part of its own, so pass it as part_id to the other tools. '
|
|
78
|
+
'A mesh that stays non-watertight is reported, not an error.\n\n'
|
|
79
|
+
'Give exactly one of path (a local mesh file; ~ is expanded) or part_id (from an earlier call). '
|
|
80
|
+
'The repaired STL is written to output_path; for a path input without one it goes next to the input as '
|
|
81
|
+
'<name>-repaired.stl, and for a part_id input nothing is written. The input file is never overwritten. '
|
|
82
|
+
'units says what a path\'s file is in, mm or inches, and only matters when uploading. '
|
|
83
|
+
'It can take a minute, longer for big files.'
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
PRINTABILITY_REPORT_DESCRIPTION = (
|
|
87
|
+
'The tool to call first for "can I print this?". Runs geometry, wall thickness, overhang and print '
|
|
88
|
+
'orientation checks on one model and returns a single verdict: ready, needs_attention (thin walls, '
|
|
89
|
+
'overhangs that need supports, several shells, or a check that failed) or not_printable (the mesh is not '
|
|
90
|
+
'watertight or manifold, or has defects: run repair_mesh). issues lists each problem with its severity '
|
|
91
|
+
'and the check that found it; geometry, thickness, overhang and orientation hold the numbers behind them '
|
|
92
|
+
'(lengths in mm, areas in mm\u00b2). A check that fails shows as {"error": ...} in its section and a warning, '
|
|
93
|
+
'and the rest still return. min_thickness_mm (default 0.8) and critical_angle_deg (default 45, measured '
|
|
94
|
+
'from horizontal) set the thresholds.\n\n'
|
|
95
|
+
'Give exactly one of path (a local mesh file; ~ is expanded) or part_id (from an earlier call). '
|
|
96
|
+
'The oriented STL is written to oriented_output_path; for a path input without one it goes next to the '
|
|
97
|
+
'input as <name>-oriented.stl, and for a part_id input nothing is written. The input is never '
|
|
98
|
+
'overwritten. units says what a path\'s file is in, mm or inches, and only matters when uploading. '
|
|
99
|
+
'It can take a minute or two, longer for big files.'
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
VISUALIZE_PARTS_DESCRIPTION = (
|
|
103
|
+
'Open an interactive view of parts in the user\'s browser. Parts can be colored by an analysis layer: '
|
|
104
|
+
'overhang (faces that need supports), thickness (thin walls) or defects (holes, non-manifold edges and '
|
|
105
|
+
'other mesh defects), with a slider or toggles the user can change. Use it to show a result, compare '
|
|
106
|
+
'revisions, or lay out a whole folder of results.\n\n'
|
|
107
|
+
'Pass exactly one of:\n'
|
|
108
|
+
f'- items: 1 to {MAX_ITEMS} parts, opened straight in 3D side by side with synced cameras. E.g. the '
|
|
109
|
+
'original next to the repaired part.\n'
|
|
110
|
+
'- groups: titled sections of thumbnail cards, for sorting many parts into categories, e.g. '
|
|
111
|
+
'[{"title": "No overhangs (12)", "items": [...]}, {"title": "Has overhangs (8)", "items": [...]}]. The '
|
|
112
|
+
f'user clicks a card to open it in 3D, or ticks 2 to {MAX_ITEMS} to compare them.\n'
|
|
113
|
+
'- rows: one row per comparison across many parts, e.g. before/after orienting or repairing each of 20 '
|
|
114
|
+
'parts: [{"label": "bracket.stl", "items": [original, oriented], "stats": ["-62% supports"]}]. Each row '
|
|
115
|
+
f'has 1 to {MAX_ITEMS} items and a button that opens them side by side in 3D.\n'
|
|
116
|
+
'groups and rows load only thumbnails until the user opens a part, so they take many parts.\n\n'
|
|
117
|
+
'Each item gives exactly one of path (a local mesh file) or part_id, and optionally layer, label and '
|
|
118
|
+
'stats (short callouts like "14.2% overhang"). A layer comes from the analysis of that kind this session '
|
|
119
|
+
'ran last on the part, else the part\'s latest; pass job_id (a summary\'s job_id) to pick one. Run the '
|
|
120
|
+
'analysis first. In groups and rows, a layer this session didn\'t run is looked up when the user opens '
|
|
121
|
+
'the part. The view is served from this machine while the MCP server runs; url is its address and '
|
|
122
|
+
'opened says whether a browser opened it (set open_browser false to only get the url).'
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
T = TypeVar('T')
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def create_server(settings: Settings) -> FastMCP:
|
|
129
|
+
client = ProperMeshClient(settings.access_key, settings.secret_key, domain=settings.domain,
|
|
130
|
+
user_agent_prefix=f'propermesh-mcp/{package_version("propermesh-mcp")}')
|
|
131
|
+
resolver = PartResolver()
|
|
132
|
+
jobs = JobCache()
|
|
133
|
+
viewer = LazyViewer(tools.asset_loader(client, jobs))
|
|
134
|
+
server = FastMCP('propermesh', instructions=INSTRUCTIONS)
|
|
135
|
+
|
|
136
|
+
async def run(call: Callable[[], T]) -> T:
|
|
137
|
+
"""Runs a tool in a worker thread, so waiting on a job doesn't block the stdio loop"""
|
|
138
|
+
missing = missing_keys_message(settings)
|
|
139
|
+
if missing:
|
|
140
|
+
raise ToolFailure(missing)
|
|
141
|
+
return await anyio.to_thread.run_sync(call)
|
|
142
|
+
|
|
143
|
+
@server.tool(description=ANALYZE_GEOMETRY_DESCRIPTION)
|
|
144
|
+
async def analyze_geometry(path: Optional[str] = None, part_id: Optional[str] = None,
|
|
145
|
+
units: UnitsName = 'mm') -> GeometrySummary:
|
|
146
|
+
return await run(lambda: tools.analyze_geometry(
|
|
147
|
+
client, resolver, settings, path, part_id, units, jobs=jobs))
|
|
148
|
+
|
|
149
|
+
@server.tool(description=CHECK_WALL_THICKNESS_DESCRIPTION)
|
|
150
|
+
async def check_wall_thickness(path: Optional[str] = None, part_id: Optional[str] = None,
|
|
151
|
+
min_thickness_mm: float = 0.8, units: UnitsName = 'mm') -> ThicknessSummary:
|
|
152
|
+
return await run(lambda: tools.check_wall_thickness(
|
|
153
|
+
client, resolver, settings, path, part_id, min_thickness_mm, units, jobs=jobs))
|
|
154
|
+
|
|
155
|
+
@server.tool(description=CHECK_OVERHANGS_DESCRIPTION)
|
|
156
|
+
async def check_overhangs(path: Optional[str] = None, part_id: Optional[str] = None,
|
|
157
|
+
critical_angle_deg: float = 45, units: UnitsName = 'mm') -> OverhangSummary:
|
|
158
|
+
return await run(lambda: tools.check_overhangs(
|
|
159
|
+
client, resolver, settings, path, part_id, critical_angle_deg, units, jobs=jobs))
|
|
160
|
+
|
|
161
|
+
@server.tool(description=FIND_PRINT_ORIENTATION_DESCRIPTION)
|
|
162
|
+
async def find_print_orientation(path: Optional[str] = None, part_id: Optional[str] = None,
|
|
163
|
+
output_path: Optional[str] = None, units: UnitsName = 'mm') -> OrientationSummary:
|
|
164
|
+
return await run(lambda: tools.find_print_orientation(
|
|
165
|
+
client, resolver, settings, path, part_id, output_path, units))
|
|
166
|
+
|
|
167
|
+
@server.tool(description=REPAIR_MESH_DESCRIPTION)
|
|
168
|
+
async def repair_mesh(path: Optional[str] = None, part_id: Optional[str] = None,
|
|
169
|
+
output_path: Optional[str] = None, units: UnitsName = 'mm') -> RepairSummary:
|
|
170
|
+
return await run(lambda: tools.repair_mesh(
|
|
171
|
+
client, resolver, settings, path, part_id, output_path, units))
|
|
172
|
+
|
|
173
|
+
@server.tool(description=PRINTABILITY_REPORT_DESCRIPTION)
|
|
174
|
+
async def printability_report(path: Optional[str] = None, part_id: Optional[str] = None,
|
|
175
|
+
min_thickness_mm: float = 0.8, critical_angle_deg: float = 45, units: UnitsName = 'mm',
|
|
176
|
+
oriented_output_path: Optional[str] = None) -> PrintabilityReport:
|
|
177
|
+
return await run(lambda: tools.printability_report(
|
|
178
|
+
client, resolver, settings, path, part_id, min_thickness_mm, critical_angle_deg, units,
|
|
179
|
+
oriented_output_path, jobs=jobs))
|
|
180
|
+
|
|
181
|
+
@server.tool(description=VISUALIZE_PARTS_DESCRIPTION)
|
|
182
|
+
async def visualize_parts(items: Optional[list[ViewerItem]] = None, groups: Optional[list[ViewerGroup]] = None,
|
|
183
|
+
rows: Optional[list[ViewerRow]] = None, title: Optional[str] = None,
|
|
184
|
+
open_browser: bool = True) -> VisualizeSummary:
|
|
185
|
+
return await run(lambda: tools.visualize_parts(
|
|
186
|
+
client, resolver, jobs, viewer, settings, items, title, open_browser, groups=groups, rows=rows))
|
|
187
|
+
|
|
188
|
+
return server
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def main() -> None:
|
|
192
|
+
create_server(settings_from_env(os.environ)).run()
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
if __name__ == '__main__':
|
|
196
|
+
main()
|