|
| 1 | +# SPDX-FileCopyrightText: 2026 JLay2026 |
| 2 | +# SPDX-License-Identifier: MIT |
| 3 | +"""Integration: full MCP tool-call round-trip. |
| 4 | +
|
| 5 | +Initialize -> partsmith_create_model (cube) -> verify geometry + |
| 6 | +preview -> partsmith_export (STL) -> verify decodable STL bytes. |
| 7 | +
|
| 8 | +This is the v0.3.2 completion of issue #5: where test_mcp_handshake |
| 9 | +proves the transport + tool inventory, this proves the tools actually |
| 10 | +*execute* end-to-end against a real build123d + trimesh stack inside |
| 11 | +the container. |
| 12 | +""" |
| 13 | + |
| 14 | +import base64 |
| 15 | +import json |
| 16 | + |
| 17 | +import requests |
| 18 | + |
| 19 | +_MCP_HEADERS = { |
| 20 | + "Content-Type": "application/json", |
| 21 | + "Accept": "application/json, text/event-stream", |
| 22 | +} |
| 23 | + |
| 24 | + |
| 25 | +def _rpc(partsmith_url, method, params=None, req_id=1): |
| 26 | + """Send a JSON-RPC request to the MCP endpoint, return the Response.""" |
| 27 | + payload = {"jsonrpc": "2.0", "id": req_id, "method": method} |
| 28 | + if params is not None: |
| 29 | + payload["params"] = params |
| 30 | + return requests.post( |
| 31 | + f"{partsmith_url}/mcp/", |
| 32 | + headers=_MCP_HEADERS, |
| 33 | + json=payload, |
| 34 | + timeout=30, # build123d execution can take a few seconds |
| 35 | + ) |
| 36 | + |
| 37 | + |
| 38 | +def _initialize(partsmith_url): |
| 39 | + return _rpc( |
| 40 | + partsmith_url, |
| 41 | + "initialize", |
| 42 | + { |
| 43 | + "protocolVersion": "2024-11-05", |
| 44 | + "capabilities": {}, |
| 45 | + "clientInfo": {"name": "ci-tools", "version": "0"}, |
| 46 | + }, |
| 47 | + req_id=1, |
| 48 | + ) |
| 49 | + |
| 50 | + |
| 51 | +def _tool_result_dict(rpc_response_body): |
| 52 | + """Extract the tool's dict result from a tools/call JSON-RPC response. |
| 53 | +
|
| 54 | + FastMCP can surface a tool's dict return as ``structuredContent`` and/or |
| 55 | + a JSON string in ``content[0].text``. Parse defensively so the test |
| 56 | + isn't coupled to one wrapping. |
| 57 | + """ |
| 58 | + result = rpc_response_body.get("result", {}) |
| 59 | + # Preferred: structuredContent (FastMCP puts dict returns here) |
| 60 | + if isinstance(result.get("structuredContent"), dict): |
| 61 | + sc = result["structuredContent"] |
| 62 | + # Some FastMCP versions wrap the dict under a "result" key |
| 63 | + if set(sc.keys()) == {"result"} and isinstance(sc["result"], dict): |
| 64 | + return sc["result"] |
| 65 | + return sc |
| 66 | + # Fallback: content[0].text as JSON |
| 67 | + content = result.get("content", []) |
| 68 | + if content and isinstance(content, list): |
| 69 | + first = content[0] |
| 70 | + text = first.get("text") if isinstance(first, dict) else None |
| 71 | + if text: |
| 72 | + try: |
| 73 | + return json.loads(text) |
| 74 | + except (json.JSONDecodeError, TypeError): |
| 75 | + pass |
| 76 | + raise AssertionError( |
| 77 | + f"Could not extract tool result dict from response: {rpc_response_body!r}" |
| 78 | + ) |
| 79 | + |
| 80 | + |
| 81 | +def test_create_model_then_export_roundtrip(partsmith_url): |
| 82 | + """create_model(cube) -> geometry + preview; export(stl) -> valid STL bytes.""" |
| 83 | + init = _initialize(partsmith_url) |
| 84 | + assert init.status_code == 200, f"initialize failed: {init.status_code}" |
| 85 | + |
| 86 | + # 1. Create a 20mm cube |
| 87 | + create = _rpc( |
| 88 | + partsmith_url, |
| 89 | + "tools/call", |
| 90 | + { |
| 91 | + "name": "partsmith_create_model", |
| 92 | + "arguments": { |
| 93 | + "code": "from build123d import *\nresult = Box(20, 20, 20)", |
| 94 | + "name": "ci-roundtrip-cube", |
| 95 | + }, |
| 96 | + }, |
| 97 | + req_id=2, |
| 98 | + ) |
| 99 | + assert create.status_code == 200, ( |
| 100 | + f"create_model call returned {create.status_code}: {create.text[:300]}" |
| 101 | + ) |
| 102 | + create_result = _tool_result_dict(create.json()) |
| 103 | + assert create_result.get("success") is True, ( |
| 104 | + f"create_model did not succeed: {create_result!r}" |
| 105 | + ) |
| 106 | + geom = create_result.get("geometry") |
| 107 | + assert geom is not None, "create_model returned no geometry" |
| 108 | + # 20mm cube => 8000 mm^3 |
| 109 | + assert abs(geom["volume_mm3"] - 8000.0) < 1.0, ( |
| 110 | + f"Expected ~8000 mm^3 for a 20mm cube, got {geom.get('volume_mm3')!r}" |
| 111 | + ) |
| 112 | + bbox = geom["bounding_box"] |
| 113 | + assert bbox["size"] == [20.0, 20.0, 20.0], ( |
| 114 | + f"Expected 20x20x20 bbox, got {bbox.get('size')!r}" |
| 115 | + ) |
| 116 | + # Preview PNG should be present + look like a PNG |
| 117 | + preview_b64 = create_result.get("preview_data_b64") |
| 118 | + assert preview_b64, "create_model returned no preview_data_b64" |
| 119 | + preview_bytes = base64.b64decode(preview_b64) |
| 120 | + assert preview_bytes[:8] == b"\x89PNG\r\n\x1a\n", "preview is not a PNG" |
| 121 | + |
| 122 | + # 2. Export to STL |
| 123 | + export = _rpc( |
| 124 | + partsmith_url, |
| 125 | + "tools/call", |
| 126 | + { |
| 127 | + "name": "partsmith_export", |
| 128 | + "arguments": {"name": "ci-roundtrip-cube", "format": "stl"}, |
| 129 | + }, |
| 130 | + req_id=3, |
| 131 | + ) |
| 132 | + assert export.status_code == 200, ( |
| 133 | + f"export call returned {export.status_code}: {export.text[:300]}" |
| 134 | + ) |
| 135 | + export_result = _tool_result_dict(export.json()) |
| 136 | + assert export_result.get("inline") is True, ( |
| 137 | + f"Expected inline STL for a tiny cube, got: {export_result!r}" |
| 138 | + ) |
| 139 | + stl_bytes = base64.b64decode(export_result["data_b64"]) |
| 140 | + assert len(stl_bytes) > 0, "exported STL is empty" |
| 141 | + # Binary STL: 80-byte header + 4-byte triangle count, then 50 bytes/tri. |
| 142 | + # A box is 12 triangles. ASCII STL starts with b"solid". Accept either. |
| 143 | + is_binary_stl = len(stl_bytes) >= 84 |
| 144 | + is_ascii_stl = stl_bytes[:5].lower() == b"solid" |
| 145 | + assert is_binary_stl or is_ascii_stl, ( |
| 146 | + f"exported bytes don't look like STL (len={len(stl_bytes)}, " |
| 147 | + f"head={stl_bytes[:16]!r})" |
| 148 | + ) |
| 149 | + |
| 150 | + |
| 151 | +def test_render_section_via_mcp(partsmith_url): |
| 152 | + """create_model -> render_section returns an inline PNG (v0.2.6 tool live).""" |
| 153 | + init = _initialize(partsmith_url) |
| 154 | + assert init.status_code == 200 |
| 155 | + |
| 156 | + _rpc( |
| 157 | + partsmith_url, |
| 158 | + "tools/call", |
| 159 | + { |
| 160 | + "name": "partsmith_create_model", |
| 161 | + "arguments": { |
| 162 | + "code": "from build123d import *\nresult = Box(30, 30, 30)", |
| 163 | + "name": "ci-section-cube", |
| 164 | + }, |
| 165 | + }, |
| 166 | + req_id=2, |
| 167 | + ) |
| 168 | + |
| 169 | + section = _rpc( |
| 170 | + partsmith_url, |
| 171 | + "tools/call", |
| 172 | + { |
| 173 | + "name": "partsmith_render_section", |
| 174 | + "arguments": {"name": "ci-section-cube", "plane": "YZ", "at": 0.0}, |
| 175 | + }, |
| 176 | + req_id=3, |
| 177 | + ) |
| 178 | + assert section.status_code == 200, ( |
| 179 | + f"render_section call returned {section.status_code}: {section.text[:300]}" |
| 180 | + ) |
| 181 | + result = _tool_result_dict(section.json()) |
| 182 | + assert result.get("inline") is True, f"Expected inline PNG, got {result!r}" |
| 183 | + png = base64.b64decode(result["data_b64"]) |
| 184 | + assert png[:8] == b"\x89PNG\r\n\x1a\n", "section render is not a PNG" |
0 commit comments