roiko-mcp 0.1.0__tar.gz

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 (59) hide show
  1. roiko_mcp-0.1.0/LICENSE +25 -0
  2. roiko_mcp-0.1.0/PKG-INFO +100 -0
  3. roiko_mcp-0.1.0/README.md +68 -0
  4. roiko_mcp-0.1.0/pyproject.toml +47 -0
  5. roiko_mcp-0.1.0/roiko_mcp/__init__.py +3 -0
  6. roiko_mcp-0.1.0/roiko_mcp/__main__.py +3 -0
  7. roiko_mcp-0.1.0/roiko_mcp/auth.py +241 -0
  8. roiko_mcp-0.1.0/roiko_mcp/changes.py +80 -0
  9. roiko_mcp-0.1.0/roiko_mcp/client.py +147 -0
  10. roiko_mcp-0.1.0/roiko_mcp/deadline.py +36 -0
  11. roiko_mcp-0.1.0/roiko_mcp/errors.py +113 -0
  12. roiko_mcp-0.1.0/roiko_mcp/model_data.py +105 -0
  13. roiko_mcp-0.1.0/roiko_mcp/prompts.py +74 -0
  14. roiko_mcp-0.1.0/roiko_mcp/request_context.py +45 -0
  15. roiko_mcp-0.1.0/roiko_mcp/resources.py +124 -0
  16. roiko_mcp-0.1.0/roiko_mcp/server.py +183 -0
  17. roiko_mcp-0.1.0/roiko_mcp/settings.py +147 -0
  18. roiko_mcp-0.1.0/roiko_mcp/summaries.py +1379 -0
  19. roiko_mcp-0.1.0/roiko_mcp/tools/__init__.py +81 -0
  20. roiko_mcp-0.1.0/roiko_mcp/tools/account.py +32 -0
  21. roiko_mcp-0.1.0/roiko_mcp/tools/analyse.py +680 -0
  22. roiko_mcp-0.1.0/roiko_mcp/tools/browse.py +116 -0
  23. roiko_mcp-0.1.0/roiko_mcp/tools/build.py +461 -0
  24. roiko_mcp-0.1.0/roiko_mcp/tools/deliver.py +550 -0
  25. roiko_mcp-0.1.0/roiko_mcp/tools/models.py +177 -0
  26. roiko_mcp-0.1.0/roiko_mcp/tools/patch.py +508 -0
  27. roiko_mcp-0.1.0/roiko_mcp/tools/projects.py +57 -0
  28. roiko_mcp-0.1.0/roiko_mcp.egg-info/PKG-INFO +100 -0
  29. roiko_mcp-0.1.0/roiko_mcp.egg-info/SOURCES.txt +57 -0
  30. roiko_mcp-0.1.0/roiko_mcp.egg-info/dependency_links.txt +1 -0
  31. roiko_mcp-0.1.0/roiko_mcp.egg-info/entry_points.txt +2 -0
  32. roiko_mcp-0.1.0/roiko_mcp.egg-info/requires.txt +10 -0
  33. roiko_mcp-0.1.0/roiko_mcp.egg-info/top_level.txt +1 -0
  34. roiko_mcp-0.1.0/setup.cfg +4 -0
  35. roiko_mcp-0.1.0/tests/test_account.py +30 -0
  36. roiko_mcp-0.1.0/tests/test_auth.py +246 -0
  37. roiko_mcp-0.1.0/tests/test_browse.py +55 -0
  38. roiko_mcp-0.1.0/tests/test_build.py +297 -0
  39. roiko_mcp-0.1.0/tests/test_client.py +111 -0
  40. roiko_mcp-0.1.0/tests/test_create_project.py +71 -0
  41. roiko_mcp-0.1.0/tests/test_descriptions.py +120 -0
  42. roiko_mcp-0.1.0/tests/test_http_smoke.py +197 -0
  43. roiko_mcp-0.1.0/tests/test_isolation.py +109 -0
  44. roiko_mcp-0.1.0/tests/test_model_reads.py +120 -0
  45. roiko_mcp-0.1.0/tests/test_no_src_import.py +14 -0
  46. roiko_mcp-0.1.0/tests/test_oauth_verifier.py +216 -0
  47. roiko_mcp-0.1.0/tests/test_patch.py +412 -0
  48. roiko_mcp-0.1.0/tests/test_prompts.py +61 -0
  49. roiko_mcp-0.1.0/tests/test_read_only.py +105 -0
  50. roiko_mcp-0.1.0/tests/test_resources.py +91 -0
  51. roiko_mcp-0.1.0/tests/test_sizes.py +137 -0
  52. roiko_mcp-0.1.0/tests/test_stdio.py +51 -0
  53. roiko_mcp-0.1.0/tests/test_summaries.py +396 -0
  54. roiko_mcp-0.1.0/tests/test_summaries_over_capacity.py +27 -0
  55. roiko_mcp-0.1.0/tests/test_summaries_review_t2897.py +50 -0
  56. roiko_mcp-0.1.0/tests/test_summaries_t2902_t2899.py +64 -0
  57. roiko_mcp-0.1.0/tests/test_timeouts.py +148 -0
  58. roiko_mcp-0.1.0/tests/test_tools_analyse.py +797 -0
  59. roiko_mcp-0.1.0/tests/test_tools_deliver.py +307 -0
@@ -0,0 +1,25 @@
1
+ Roiko MCP server (roiko-mcp) - proprietary licence
2
+
3
+ Copyright (c) 2026 Roiko. All rights reserved.
4
+
5
+ This software is the property of Roiko. It is published so that you can connect
6
+ an MCP client (such as Claude, Cursor or another MCP-capable tool) to the Roiko
7
+ service at https://app.roiko.ai.
8
+
9
+ You may install and run this software, unmodified, for the sole purpose of
10
+ connecting to the Roiko service with your own Roiko account and API key, subject
11
+ to the Roiko terms of service.
12
+
13
+ You may not, without Roiko's prior written permission:
14
+ - copy the software, except as needed to install and run it as above;
15
+ - modify, adapt, translate or create derivative works of it;
16
+ - redistribute, sublicense, sell, rent or otherwise make it available to others;
17
+ - use it, or any part of it, with any service other than the Roiko service.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
21
+ FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL ROIKO BE LIABLE
22
+ FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION
23
+ WITH THE SOFTWARE OR ITS USE, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
24
+
25
+ Contact: https://roiko.ai
@@ -0,0 +1,100 @@
1
+ Metadata-Version: 2.4
2
+ Name: roiko-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server for ROIKO: build, analyse and check structural models through the ROIKO API from Claude, Cursor and other MCP clients.
5
+ Author: ROIKO
6
+ License-Expression: LicenseRef-Proprietary
7
+ Project-URL: Homepage, https://roiko.ai
8
+ Project-URL: App, https://app.roiko.ai
9
+ Keywords: mcp,model-context-protocol,structural-engineering,eurocode,fea,roiko
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Scientific/Engineering
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.12
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: mcp<3,>=2.3
23
+ Requires-Dist: httpx<1,>=0.28
24
+ Requires-Dist: pydantic>=2
25
+ Requires-Dist: starlette>=0.48
26
+ Requires-Dist: uvicorn>=0.31.1
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest; extra == "dev"
29
+ Requires-Dist: respx; extra == "dev"
30
+ Requires-Dist: httpx2; extra == "dev"
31
+ Dynamic: license-file
32
+
33
+ # ROIKO MCP server
34
+
35
+ This server connects an MCP client to the ROIKO API. Create a key in ROIKO settings and keep it private. Until publication, replace the path below with the absolute path to this `mcp_server` folder.
36
+
37
+ ```json
38
+ {"mcpServers":{"roiko":{"command":"uvx","args":["--from","C:/path/to/Roiko/mcp_server","roiko-mcp"],"env":{"ROIKO_API_KEY":"your key here"}}}}
39
+ ```
40
+
41
+ Add this to Claude Desktop's configuration and restart it. Call `roiko_whoami` to check the connection. `ROIKO_API_URL` selects another API endpoint. Once the package is on PyPI the `--from` part goes and the command is `uvx roiko-mcp`.
42
+
43
+ mcp-name: ai.roiko/mcp
44
+
45
+ ## Remote server — after the server is switched on
46
+
47
+ The same server runs at `https://app.roiko.ai/mcp` (Streamable HTTP). Nothing to install: send your key as a bearer. This recipe works only once ROIKO has switched the remote server on; until then the local recipe above is the one to use.
48
+
49
+ ```
50
+ claude mcp add --transport http roiko https://app.roiko.ai/mcp --header "Authorization: Bearer rk_live_…"
51
+ ```
52
+
53
+ Cursor and VS Code take the same URL and header in their `mcp.json`:
54
+
55
+ ```json
56
+ {"mcpServers":{"roiko":{"url":"https://app.roiko.ai/mcp","headers":{"Authorization":"Bearer ${env:ROIKO_API_KEY}"}}}}
57
+ ```
58
+
59
+ Each request is checked against your key (a revoked key stops working within 30 s). A request without a key, or with a key ROIKO does not know, gets a 401. The remote server never sees anything but your own key, and every call it makes to ROIKO is made with that key, so you see exactly what the key sees. Read-only mode is per server, not per request: use a key with only the `read` scope for an autonomous agent.
60
+
61
+ ### Running the remote server yourself
62
+
63
+ `roiko-mcp --transport http` listens on `ROIKO_MCP_HOST:ROIKO_MCP_PORT` (default `127.0.0.1:8001`) at `/mcp`, behind a reverse proxy that sets `Host`, `X-Real-IP` and `X-Forwarded-For` and does not buffer `text/event-stream`. It refuses to start if `ROIKO_API_KEY` is set (the key comes with each request). Variables: `ROIKO_API_URL` (the API it calls, HTTPS or HTTP on loopback), `ROIKO_MCP_ALLOWED_HOSTS` (comma list of accepted `Host` values; default the resource URL's host plus `host:port`), `ROIKO_MCP_RESOURCE_URL` (default `https://app.roiko.ai/mcp`), `ROIKO_MCP_STATE_KEYS` (one or more 32+ character secrets that seal multi-step request state across restarts; without it a fresh key is made at every start), `ROIKO_MCP_READ_ONLY`.
64
+
65
+ ## Tools
66
+
67
+ Read tools (any key): `roiko_whoami`, `roiko_list_projects`, `roiko_list_models`, `roiko_get_model_summary`, `roiko_get_model`, `roiko_get_job`, `roiko_get_results`, `roiko_get_checks`, `roiko_search_catalogue`, plus the resources `roiko://projects`, `roiko://projects/{id}/models`, `roiko://models/{id}`, `roiko://models/{id}/results`, `roiko://models/{id}/report` (markdown) and `roiko://catalogue/{name}`.
68
+
69
+ Write tools (the key needs the `write` scope; `roiko_create_model_from_text` also needs `run`):
70
+
71
+ - `roiko_create_project` — makes a new project (name, optional country, location, description, client, project number) and returns its id, to use as `project_id` below. Needs the `write` scope and an author seat.
72
+ - `roiko_create_model_from_text` — plain English in, a saved model out. Without `model_id` it creates a model (in `project_id`, else the personal workspace) and generates into it; with `model_id` it changes that model by prompt. `dry_run: true` previews without saving. Each saved version is of kind `ai`.
73
+ - When ROIKO needs more detail it asks back. A client that supports MCP elicitation gets a form and the call finishes on its own; any other client receives `status: "question"` with a `thread`, and the assistant calls again with the same `prompt` and `model_id` plus `answer` and that `thread`.
74
+ - A big model may come back `status: "partial"`: what was built is saved, the tool continues once with the API's `thread`, and if the model is still incomplete it says what is missing.
75
+ - A generation that outruns the API's 85 s budget is reported as an error that says nothing was saved; the model created for it can be reused with `model_id`.
76
+ - `roiko_edit_model` — precise, bounded edits by id (`add_member`, `update_member`, `remove_member`, `add_foundation`, `remove_foundation`, `set_release`, `set_support`, `upsert_load_case`, `remove_load_case`, `set_levels`, `set_grids`, `replace_structure`), 1 to 50 operations applied together or not at all. The server reads the full structure, applies the patch and saves with `expected_version_id` (the model's current version when none is given), so every key the assistant never named survives. If the model changed meanwhile the API answers a version conflict, nothing is saved, and the tool says to read the model again and retry. Each saved version is of kind `api`.
77
+
78
+ Both model tools return the model summary and a `resource_link` to `roiko://models/{id}`, never the structure JSON.
79
+
80
+ ## Analysis tools
81
+
82
+ - `roiko_run_analysis` (a write tool; the key needs the `run` scope) — runs the analysis and code checks on the model's latest saved version, or on `version_id`. Optional: `national_annex` (two letters), `second_order`, `include_self_weight`, `consequence_class`. It asks the API to answer at once (`Prefer: respond-async`), then checks the job every 2 s (every 3 s after 20 s) for up to `wait_seconds` (default 45, at most 60; one call never waits past 90 s). A finished run returns the results summary: the verdict line, the highest utilisations per family, the worst deflection, the reactions and the stability check. A run still going returns its `job_id` and says to call `roiko_get_job` a few seconds later. A cached result comes back at once. Each run spends the user's analysis allowance, and the API saves the result as a version of kind `analysis`.
83
+ - `roiko_get_job` — checks a job (waits up to `wait_seconds`, default 20) and returns the same summary when it is done. A failed or cancelled job is an error that says why.
84
+ - `roiko_get_results` — the saved result in slices: `kind` `summary`, `checks`, `deflections` (mm, limit, utilisation) or `reactions` (kN, kN·m, ruling combination only), with `member_ids`, `min_utilisation`, `combination`, `sort`, `limit` (up to 50) and `cursor`.
85
+ - `roiko_get_checks` — the API's check rows (`GET /models/{id}/checks`): governing check, clause, demand and capacity where the result names them, utilisation, verdict, combination. `failing_only`, `family` (`steel`, `concrete`, `foundation`, `base_plate`, `wall`, `slab`, `joint`, `deflection`), `member_ids`, `min_utilisation`, `detail` and `cursor`. `detail: "all"` gives every check row: each EN 1993 check of a steel member (§6.2.5 bending with M_Ed and M_Rd, shear, buckling, ...) under its governing combination, and each pad or plate sub-check; a row with no capacity or no ratio says why in `note`. It is on by default with `member_ids` or family `foundation` / `base_plate`; `detail: "governing"` keeps one row per member.
86
+
87
+ Every analysis reply stays under 40 000 characters and carries a `resource_link` to `roiko://models/{id}/results` for the full result. Plan limits (402), a plan without analysis (403), rate limits (429), a model with no result yet and cancelled runs each come back as one plain sentence.
88
+
89
+ ## Export and catalogue tools
90
+
91
+ - `roiko_export` (a write tool: it spends the report and export allowances; the key needs the `run` scope) — `format` `report` returns the calculation report as markdown, inline up to 40 000 characters; a longer report is cut with `truncated: true` and a `resource_link` to `roiko://models/{id}/report`, which holds it whole (the last report is kept 10 minutes, so reading it spends nothing more). `dxf`, `ifc`, `sheet-pdf` (needs `sheets`) and `mto` always come back as a download link with its expiry (about 15 minutes), never as file bytes. `mto` also returns the take-off totals (steel by profile, concrete by grade, rebar, panels) unless `mto_summary_too` is false. Until download links are switched on at the server, a file export says so in one plain sentence; `mto` still returns its totals.
92
+ - `roiko_search_catalogue` — sections (searched by the API with `query` and `family`, optionally limited to a `project_id`), steel, concrete and rebar grades, base-plate parts, grating types, slab and wall thicknesses, and jurisdictions (filtered here). Paged with `cursor`, 25 rows by default, cached 10 minutes; `response_format: "detailed"` adds the section properties.
93
+
94
+ ## Prompts
95
+
96
+ `design_review` (summary, then failing checks, then deflections), `explain_governing_check` (one member's check, clause, demand and capacity) and `size_a_beam` (the lightest section in the family under a target utilisation, at most three tries).
97
+
98
+ ## Read-only mode
99
+
100
+ `ROIKO_MCP_READ_ONLY=true` (also `1` or `yes`) hides the five write tools (`roiko_create_project`, `roiko_create_model_from_text`, `roiko_edit_model`, `roiko_run_analysis`, `roiko_export`) from the tool list, and they refuse if a client calls them anyway. `roiko_whoami` reports `read_only: true`. Use it, or a key with only the `read` scope, for autonomous agents that must not change models; a key without `write` is refused by the API with a readable message in either mode.
@@ -0,0 +1,68 @@
1
+ # ROIKO MCP server
2
+
3
+ This server connects an MCP client to the ROIKO API. Create a key in ROIKO settings and keep it private. Until publication, replace the path below with the absolute path to this `mcp_server` folder.
4
+
5
+ ```json
6
+ {"mcpServers":{"roiko":{"command":"uvx","args":["--from","C:/path/to/Roiko/mcp_server","roiko-mcp"],"env":{"ROIKO_API_KEY":"your key here"}}}}
7
+ ```
8
+
9
+ Add this to Claude Desktop's configuration and restart it. Call `roiko_whoami` to check the connection. `ROIKO_API_URL` selects another API endpoint. Once the package is on PyPI the `--from` part goes and the command is `uvx roiko-mcp`.
10
+
11
+ mcp-name: ai.roiko/mcp
12
+
13
+ ## Remote server — after the server is switched on
14
+
15
+ The same server runs at `https://app.roiko.ai/mcp` (Streamable HTTP). Nothing to install: send your key as a bearer. This recipe works only once ROIKO has switched the remote server on; until then the local recipe above is the one to use.
16
+
17
+ ```
18
+ claude mcp add --transport http roiko https://app.roiko.ai/mcp --header "Authorization: Bearer rk_live_…"
19
+ ```
20
+
21
+ Cursor and VS Code take the same URL and header in their `mcp.json`:
22
+
23
+ ```json
24
+ {"mcpServers":{"roiko":{"url":"https://app.roiko.ai/mcp","headers":{"Authorization":"Bearer ${env:ROIKO_API_KEY}"}}}}
25
+ ```
26
+
27
+ Each request is checked against your key (a revoked key stops working within 30 s). A request without a key, or with a key ROIKO does not know, gets a 401. The remote server never sees anything but your own key, and every call it makes to ROIKO is made with that key, so you see exactly what the key sees. Read-only mode is per server, not per request: use a key with only the `read` scope for an autonomous agent.
28
+
29
+ ### Running the remote server yourself
30
+
31
+ `roiko-mcp --transport http` listens on `ROIKO_MCP_HOST:ROIKO_MCP_PORT` (default `127.0.0.1:8001`) at `/mcp`, behind a reverse proxy that sets `Host`, `X-Real-IP` and `X-Forwarded-For` and does not buffer `text/event-stream`. It refuses to start if `ROIKO_API_KEY` is set (the key comes with each request). Variables: `ROIKO_API_URL` (the API it calls, HTTPS or HTTP on loopback), `ROIKO_MCP_ALLOWED_HOSTS` (comma list of accepted `Host` values; default the resource URL's host plus `host:port`), `ROIKO_MCP_RESOURCE_URL` (default `https://app.roiko.ai/mcp`), `ROIKO_MCP_STATE_KEYS` (one or more 32+ character secrets that seal multi-step request state across restarts; without it a fresh key is made at every start), `ROIKO_MCP_READ_ONLY`.
32
+
33
+ ## Tools
34
+
35
+ Read tools (any key): `roiko_whoami`, `roiko_list_projects`, `roiko_list_models`, `roiko_get_model_summary`, `roiko_get_model`, `roiko_get_job`, `roiko_get_results`, `roiko_get_checks`, `roiko_search_catalogue`, plus the resources `roiko://projects`, `roiko://projects/{id}/models`, `roiko://models/{id}`, `roiko://models/{id}/results`, `roiko://models/{id}/report` (markdown) and `roiko://catalogue/{name}`.
36
+
37
+ Write tools (the key needs the `write` scope; `roiko_create_model_from_text` also needs `run`):
38
+
39
+ - `roiko_create_project` — makes a new project (name, optional country, location, description, client, project number) and returns its id, to use as `project_id` below. Needs the `write` scope and an author seat.
40
+ - `roiko_create_model_from_text` — plain English in, a saved model out. Without `model_id` it creates a model (in `project_id`, else the personal workspace) and generates into it; with `model_id` it changes that model by prompt. `dry_run: true` previews without saving. Each saved version is of kind `ai`.
41
+ - When ROIKO needs more detail it asks back. A client that supports MCP elicitation gets a form and the call finishes on its own; any other client receives `status: "question"` with a `thread`, and the assistant calls again with the same `prompt` and `model_id` plus `answer` and that `thread`.
42
+ - A big model may come back `status: "partial"`: what was built is saved, the tool continues once with the API's `thread`, and if the model is still incomplete it says what is missing.
43
+ - A generation that outruns the API's 85 s budget is reported as an error that says nothing was saved; the model created for it can be reused with `model_id`.
44
+ - `roiko_edit_model` — precise, bounded edits by id (`add_member`, `update_member`, `remove_member`, `add_foundation`, `remove_foundation`, `set_release`, `set_support`, `upsert_load_case`, `remove_load_case`, `set_levels`, `set_grids`, `replace_structure`), 1 to 50 operations applied together or not at all. The server reads the full structure, applies the patch and saves with `expected_version_id` (the model's current version when none is given), so every key the assistant never named survives. If the model changed meanwhile the API answers a version conflict, nothing is saved, and the tool says to read the model again and retry. Each saved version is of kind `api`.
45
+
46
+ Both model tools return the model summary and a `resource_link` to `roiko://models/{id}`, never the structure JSON.
47
+
48
+ ## Analysis tools
49
+
50
+ - `roiko_run_analysis` (a write tool; the key needs the `run` scope) — runs the analysis and code checks on the model's latest saved version, or on `version_id`. Optional: `national_annex` (two letters), `second_order`, `include_self_weight`, `consequence_class`. It asks the API to answer at once (`Prefer: respond-async`), then checks the job every 2 s (every 3 s after 20 s) for up to `wait_seconds` (default 45, at most 60; one call never waits past 90 s). A finished run returns the results summary: the verdict line, the highest utilisations per family, the worst deflection, the reactions and the stability check. A run still going returns its `job_id` and says to call `roiko_get_job` a few seconds later. A cached result comes back at once. Each run spends the user's analysis allowance, and the API saves the result as a version of kind `analysis`.
51
+ - `roiko_get_job` — checks a job (waits up to `wait_seconds`, default 20) and returns the same summary when it is done. A failed or cancelled job is an error that says why.
52
+ - `roiko_get_results` — the saved result in slices: `kind` `summary`, `checks`, `deflections` (mm, limit, utilisation) or `reactions` (kN, kN·m, ruling combination only), with `member_ids`, `min_utilisation`, `combination`, `sort`, `limit` (up to 50) and `cursor`.
53
+ - `roiko_get_checks` — the API's check rows (`GET /models/{id}/checks`): governing check, clause, demand and capacity where the result names them, utilisation, verdict, combination. `failing_only`, `family` (`steel`, `concrete`, `foundation`, `base_plate`, `wall`, `slab`, `joint`, `deflection`), `member_ids`, `min_utilisation`, `detail` and `cursor`. `detail: "all"` gives every check row: each EN 1993 check of a steel member (§6.2.5 bending with M_Ed and M_Rd, shear, buckling, ...) under its governing combination, and each pad or plate sub-check; a row with no capacity or no ratio says why in `note`. It is on by default with `member_ids` or family `foundation` / `base_plate`; `detail: "governing"` keeps one row per member.
54
+
55
+ Every analysis reply stays under 40 000 characters and carries a `resource_link` to `roiko://models/{id}/results` for the full result. Plan limits (402), a plan without analysis (403), rate limits (429), a model with no result yet and cancelled runs each come back as one plain sentence.
56
+
57
+ ## Export and catalogue tools
58
+
59
+ - `roiko_export` (a write tool: it spends the report and export allowances; the key needs the `run` scope) — `format` `report` returns the calculation report as markdown, inline up to 40 000 characters; a longer report is cut with `truncated: true` and a `resource_link` to `roiko://models/{id}/report`, which holds it whole (the last report is kept 10 minutes, so reading it spends nothing more). `dxf`, `ifc`, `sheet-pdf` (needs `sheets`) and `mto` always come back as a download link with its expiry (about 15 minutes), never as file bytes. `mto` also returns the take-off totals (steel by profile, concrete by grade, rebar, panels) unless `mto_summary_too` is false. Until download links are switched on at the server, a file export says so in one plain sentence; `mto` still returns its totals.
60
+ - `roiko_search_catalogue` — sections (searched by the API with `query` and `family`, optionally limited to a `project_id`), steel, concrete and rebar grades, base-plate parts, grating types, slab and wall thicknesses, and jurisdictions (filtered here). Paged with `cursor`, 25 rows by default, cached 10 minutes; `response_format: "detailed"` adds the section properties.
61
+
62
+ ## Prompts
63
+
64
+ `design_review` (summary, then failing checks, then deflections), `explain_governing_check` (one member's check, clause, demand and capacity) and `size_a_beam` (the lightest section in the family under a target utilisation, at most three tries).
65
+
66
+ ## Read-only mode
67
+
68
+ `ROIKO_MCP_READ_ONLY=true` (also `1` or `yes`) hides the five write tools (`roiko_create_project`, `roiko_create_model_from_text`, `roiko_edit_model`, `roiko_run_analysis`, `roiko_export`) from the tool list, and they refuse if a client calls them anyway. `roiko_whoami` reports `read_only: true`. Use it, or a key with only the `read` scope, for autonomous agents that must not change models; a key without `write` is refused by the API with a readable message in either mode.
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "roiko-mcp"
7
+ version = "0.1.0"
8
+ description = "MCP server for ROIKO: build, analyse and check structural models through the ROIKO API from Claude, Cursor and other MCP clients."
9
+ readme = "README.md"
10
+ # Proprietary (user's decision 2026-10-30, T1831): the terms are in LICENSE, which
11
+ # ships in both the sdist and the wheel (PEP 639 license-files).
12
+ license = "LicenseRef-Proprietary"
13
+ license-files = ["LICENSE"]
14
+ requires-python = ">=3.12"
15
+ authors = [{ name = "ROIKO" }]
16
+ keywords = ["mcp", "model-context-protocol", "structural-engineering", "eurocode", "fea", "roiko"]
17
+ classifiers = [
18
+ "Development Status :: 3 - Alpha",
19
+ "Intended Audience :: Developers",
20
+ "Intended Audience :: Science/Research",
21
+ "Operating System :: OS Independent",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Topic :: Scientific/Engineering",
26
+ "Typing :: Typed",
27
+ ]
28
+ dependencies = [
29
+ "mcp>=2.3,<3",
30
+ "httpx>=0.28,<1",
31
+ "pydantic>=2",
32
+ "starlette>=0.48",
33
+ "uvicorn>=0.31.1",
34
+ ]
35
+
36
+ [project.optional-dependencies]
37
+ dev = ["pytest", "respx", "httpx2"]
38
+
39
+ [project.scripts]
40
+ roiko-mcp = "roiko_mcp.server:main"
41
+
42
+ [project.urls]
43
+ Homepage = "https://roiko.ai"
44
+ App = "https://app.roiko.ai"
45
+
46
+ [tool.setuptools.packages.find]
47
+ include = ["roiko_mcp*"]
@@ -0,0 +1,3 @@
1
+ """MCP client for the Roiko public API."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from .server import main
2
+
3
+ main()
@@ -0,0 +1,241 @@
1
+ """Bearer verification for the HTTP transport.
2
+
3
+ One trust domain. The remote server takes a Roiko API key as the bearer and forwards that
4
+ same key to Roiko's own API over the loopback. The MCP spec's ban on token passthrough is
5
+ about tokens issued for OTHER services; this key was issued by Roiko, for Roiko, and the
6
+ verifier accepts nothing else (plan, §Security notes, "Forwarding the caller's key").
7
+
8
+ `verify_token` dispatches on the token's prefix. Phase 5: `_verify_api_key` (`rk_live_…`,
9
+ checked against `GET /v1/me`). Phase 6 (T1832, slice A): `_verify_oauth` for `rka_…`
10
+ tokens a connected assistant holds - the token goes to the API's introspection endpoint
11
+ with the service header, and what comes back is a 5-minute internal credential `rki_…`
12
+ that the tools then send as THEIR bearer (`261029 - mcp-oauth-design-review.md` §3, "How
13
+ the sidecar verifies"). The assistant's own token is never forwarded to a tool call.
14
+
15
+ Rules kept here: no token is logged, put in an exception or stored raw in the cache
16
+ (SHA-256 only). The format check runs before any network call. A bad or unknown token
17
+ answers None, which the SDK turns into a 401 without saying why.
18
+ """
19
+ import hashlib
20
+ import hmac
21
+ import logging
22
+ import re
23
+ import time
24
+ from collections import OrderedDict
25
+ from datetime import datetime, timezone
26
+
27
+ import httpx
28
+ from mcp.server.auth.provider import AccessToken
29
+
30
+ from . import __version__
31
+ from .client import RoikoClient
32
+ from .errors import RoikoApiError
33
+ from .request_context import forwarded_headers
34
+
35
+ KEY_PREFIX = "rk_live_"
36
+ KEY_LENGTH = len(KEY_PREFIX) + 32
37
+ _KEY_BODY = re.compile(r"[A-Za-z0-9_-]{32}")
38
+ PREFIX_SHOWN = 12 # rk_live_ + 4, the part the API stores and shows
39
+ OAUTH_PREFIX = "rka_"
40
+ OAUTH_LENGTH = len(OAUTH_PREFIX) + 32
41
+ SERVICE_HEADER = "X-Roiko-Service"
42
+
43
+ DEFAULT_TTL_SECONDS = 30 # the API's own suspension cache lag (spine F21)
44
+ NEGATIVE_TTL_SECONDS = 5 # a refused key is not re-asked at once
45
+ MAX_ENTRIES = 1000
46
+ VERIFY_DEADLINE_SECONDS = 10
47
+
48
+ log = logging.getLogger("roiko_mcp.auth")
49
+
50
+
51
+ def key_looks_valid(token) -> bool:
52
+ """`rk_live_` + 32 url-safe characters. No network, no secret compared against."""
53
+ if not isinstance(token, str) or len(token) != KEY_LENGTH:
54
+ return False
55
+ # The prefix is public, so timing is not a secret here; compare_digest keeps the
56
+ # check constant-time anyway, as the plan's review asks.
57
+ if not hmac.compare_digest(token[:len(KEY_PREFIX)].encode(), KEY_PREFIX.encode()):
58
+ return False
59
+ return _KEY_BODY.fullmatch(token[len(KEY_PREFIX):]) is not None
60
+
61
+
62
+ def oauth_token_looks_valid(token) -> bool:
63
+ """`rka_` + 32 url-safe characters: an access token of a connected assistant."""
64
+ if not isinstance(token, str) or len(token) != OAUTH_LENGTH:
65
+ return False
66
+ if not hmac.compare_digest(token[:len(OAUTH_PREFIX)].encode(), OAUTH_PREFIX.encode()):
67
+ return False
68
+ return _KEY_BODY.fullmatch(token[len(OAUTH_PREFIX):]) is not None
69
+
70
+
71
+ def _fingerprint(token: str) -> str:
72
+ return hashlib.sha256(token.encode()).hexdigest()
73
+
74
+
75
+ def _expires_at(key_row) -> int | None:
76
+ value = key_row.get("expires_at") if isinstance(key_row, dict) else None
77
+ if not isinstance(value, str) or not value:
78
+ return None
79
+ try:
80
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
81
+ except ValueError:
82
+ return None
83
+ if parsed.tzinfo is None:
84
+ parsed = parsed.replace(tzinfo=timezone.utc)
85
+ return int(parsed.timestamp())
86
+
87
+
88
+ def _scopes(key_row) -> list[str]:
89
+ raw = key_row.get("scopes") if isinstance(key_row, dict) else None
90
+ if not isinstance(raw, list):
91
+ return []
92
+ return [scope for scope in raw if isinstance(scope, str) and re.fullmatch(r"[a-z_]{1,20}", scope)]
93
+
94
+
95
+ class RoikoKeyVerifier:
96
+ """TokenVerifier: an `rk_live_` bearer, checked against the API's `/v1/me`, cached 30 s."""
97
+
98
+ def __init__(self, api_url: str, resource_url: str, *, ttl: float = DEFAULT_TTL_SECONDS,
99
+ negative_ttl: float = NEGATIVE_TTL_SECONDS, max_entries: int = MAX_ENTRIES,
100
+ deadline: float = VERIFY_DEADLINE_SECONDS, transport=None, clock=time.monotonic,
101
+ introspect_url: str | None = None, service_token: str | None = None):
102
+ self._api_url = api_url
103
+ self._resource_url = resource_url
104
+ self._ttl = ttl
105
+ self._negative_ttl = negative_ttl
106
+ self._max_entries = max_entries
107
+ self._deadline = deadline
108
+ self._transport = transport
109
+ self._clock = clock
110
+ self._introspect_url = introspect_url
111
+ self._service_token = service_token
112
+ # fingerprint -> (expires_at_monotonic, AccessToken | None); an LRU
113
+ self._cache: OrderedDict[str, tuple[float, AccessToken | None]] = OrderedDict()
114
+
115
+ @property
116
+ def oauth_on(self) -> bool:
117
+ return bool(self._introspect_url and self._service_token)
118
+
119
+ # -- the TokenVerifier protocol -------------------------------------------------------
120
+
121
+ async def verify_token(self, token: str) -> AccessToken | None:
122
+ if key_looks_valid(token):
123
+ return await self._verify_api_key(token)
124
+ if self.oauth_on and oauth_token_looks_valid(token):
125
+ return await self._verify_oauth(token)
126
+ return None
127
+
128
+ # -- the OAuth branch (phase 6) -------------------------------------------------------
129
+
130
+ async def _verify_oauth(self, token: str) -> AccessToken | None:
131
+ fingerprint = _fingerprint(token)
132
+ cached = self._lookup(fingerprint)
133
+ if cached is not None:
134
+ return cached[1]
135
+ access, cacheable = await self._introspect(token)
136
+ if cacheable:
137
+ self._store(fingerprint, access)
138
+ return access
139
+
140
+ async def _introspect(self, token: str) -> tuple[AccessToken | None, bool]:
141
+ """Exchange the assistant's token for the internal credential. Same caching rule
142
+ as `_ask_api`: only a real verdict (active or not) is cached; a 5xx, a timeout or
143
+ a network fault is not."""
144
+ headers = {**forwarded_headers(), SERVICE_HEADER: self._service_token or "",
145
+ "User-Agent": f"roiko-mcp/{__version__}"}
146
+ try:
147
+ async with httpx.AsyncClient(transport=self._transport, headers=headers,
148
+ follow_redirects=False, timeout=self._deadline) as client:
149
+ response = await client.post(self._introspect_url, data={"token": token})
150
+ except Exception as error: # noqa: BLE001 - never a 500 with the token in it
151
+ log.warning("token exchange with the API failed (%s); the request is refused", type(error).__name__)
152
+ return None, False
153
+ if response.status_code != 200:
154
+ log.warning("token exchange with the API failed (status %s); the request is refused",
155
+ response.status_code)
156
+ # 401 here means OUR service header is wrong - a config fault, not a verdict.
157
+ return None, False
158
+ try:
159
+ body = response.json()
160
+ except ValueError:
161
+ return None, False
162
+ if not isinstance(body, dict):
163
+ return None, False
164
+ if body.get("active") is not True:
165
+ return None, True
166
+ internal = body.get("internal_token")
167
+ subject = body.get("sub")
168
+ if not isinstance(internal, str) or not internal.startswith("rki_") or not isinstance(subject, str):
169
+ return None, False
170
+ scopes = [s for s in str(body.get("scope") or "").split(" ") if re.fullmatch(r"[a-z_]{1,20}", s)]
171
+ now = int(time.time())
172
+ internal_ttl = body.get("internal_expires_in")
173
+ expires = now + (internal_ttl if isinstance(internal_ttl, int) and 0 < internal_ttl <= 3600 else 300)
174
+ exp = body.get("exp")
175
+ if isinstance(exp, int) and exp < expires:
176
+ expires = exp
177
+ client_id = body.get("client_id")
178
+ return AccessToken(token=internal, client_id=client_id if isinstance(client_id, str) else token[:8],
179
+ scopes=scopes, expires_at=expires, resource=self._resource_url, subject=subject), True
180
+
181
+ # -- the API-key branch ---------------------------------------------------------------
182
+
183
+ async def _verify_api_key(self, token: str) -> AccessToken | None:
184
+ fingerprint = _fingerprint(token)
185
+ cached = self._lookup(fingerprint)
186
+ if cached is not None:
187
+ return cached[1]
188
+ access, cacheable = await self._ask_api(token)
189
+ if cacheable:
190
+ self._store(fingerprint, access)
191
+ return access
192
+
193
+ async def _ask_api(self, token: str) -> tuple[AccessToken | None, bool]:
194
+ """The answer and whether it may be cached. Only a real verdict is cached: a key
195
+ the API accepted, or one it refused with 401/403. A 5xx, a timeout or a network
196
+ fault says nothing about the key, so it is never negative-cached - the next
197
+ request asks again instead of being refused for NEGATIVE_TTL_SECONDS."""
198
+ client = RoikoClient.for_key(token, self._api_url, transport=self._transport, deadline=self._deadline)
199
+ try:
200
+ me = await client.get("me")
201
+ except RoikoApiError as error:
202
+ if error.status in (401, 403):
203
+ return None, True
204
+ log.warning("key check against the API failed (status %s); the request is refused", error.status)
205
+ return None, False
206
+ except Exception as error: # noqa: BLE001 - never let an upstream surprise become a 500 with the key in it
207
+ log.warning("key check against the API failed (%s); the request is refused", type(error).__name__)
208
+ return None, False
209
+ if not isinstance(me, dict):
210
+ return None, False
211
+ key_row = me.get("key") if isinstance(me.get("key"), dict) else {}
212
+ subject = me.get("user_id")
213
+ return AccessToken(token=token, client_id=token[:PREFIX_SHOWN], scopes=_scopes(key_row),
214
+ expires_at=_expires_at(key_row), resource=self._resource_url,
215
+ subject=subject if isinstance(subject, str) else None), True
216
+
217
+ # -- the cache ------------------------------------------------------------------------
218
+
219
+ def _lookup(self, fingerprint):
220
+ entry = self._cache.get(fingerprint)
221
+ if entry is None:
222
+ return None
223
+ if entry[0] <= self._clock():
224
+ del self._cache[fingerprint]
225
+ return None
226
+ self._cache.move_to_end(fingerprint)
227
+ return entry
228
+
229
+ def _store(self, fingerprint, access):
230
+ ttl = self._ttl if access is not None else self._negative_ttl
231
+ self._cache[fingerprint] = (self._clock() + ttl, access)
232
+ self._cache.move_to_end(fingerprint)
233
+ while len(self._cache) > self._max_entries:
234
+ self._cache.popitem(last=False)
235
+
236
+ def forget(self, token: str):
237
+ """Drop one key from the cache (a test hook, and the place a revocation signal would land)."""
238
+ self._cache.pop(_fingerprint(token), None)
239
+
240
+ def __repr__(self):
241
+ return f"RoikoKeyVerifier(api_url={self._api_url!r}, oauth={self.oauth_on}, cached={len(self._cache)})"
@@ -0,0 +1,80 @@
1
+ """The change list a preview returns (T2874 P9), fitted to the tool size cap.
2
+
3
+ The API works the list out (`POST /v1/models/{id}/structure/preview`, and the
4
+ `changes` block of a generate reply); this module only keeps it small enough
5
+ for one tool result. The counts and the one-line text are always kept whole;
6
+ the element keys and the old/new values are cut first, and `cut` says so.
7
+ """
8
+ import json
9
+ from typing import Any
10
+
11
+ from pydantic import BaseModel
12
+
13
+ #: Characters the change list may take inside one tool result (the result
14
+ #: itself is capped at 40,000; the model summary needs the rest).
15
+ MAX_CHANGES_CHARS = 16_000
16
+ _LIST_STEPS = (200, 50, 20, 5, 0)
17
+
18
+
19
+ class ChangeList(BaseModel):
20
+ summary_text: str = ""
21
+ total: int = 0
22
+ counts: dict[str, dict[str, int]] = {}
23
+ groups: dict[str, Any] = {}
24
+ values: dict[str, Any] = {}
25
+ cut: bool = False
26
+ partial: bool = False
27
+ note: str | None = None
28
+
29
+
30
+ def _int(value):
31
+ return value if isinstance(value, int) and not isinstance(value, bool) else 0
32
+
33
+
34
+ def _cut_groups(groups, limit):
35
+ out = {}
36
+ for name, row in groups.items():
37
+ if not isinstance(row, dict):
38
+ continue
39
+ out[name] = {action: list(row.get(action) or [])[:limit]
40
+ for action in ("added", "removed", "changed")}
41
+ return out
42
+
43
+
44
+ def fit_changes(raw, max_chars: int = MAX_CHANGES_CHARS) -> ChangeList | None:
45
+ """The API's change list, cut to `max_chars`; None when there is none."""
46
+ if not isinstance(raw, dict):
47
+ return None
48
+ counts = {}
49
+ for name, row in (raw.get("counts") or {}).items():
50
+ if isinstance(row, dict):
51
+ counts[str(name)] = {k: _int(row.get(k)) for k in ("added", "removed", "changed")}
52
+ groups = raw.get("groups") if isinstance(raw.get("groups"), dict) else {}
53
+ values = raw.get("values") if isinstance(raw.get("values"), dict) else {}
54
+ partial = bool(raw.get("truncated") or raw.get("too_large"))
55
+ text = str(raw.get("summary_text") or "")[:2_000]
56
+ result = ChangeList(summary_text=text, total=_int(raw.get("total")), counts=counts,
57
+ groups=groups, values=values, partial=partial,
58
+ cut=bool(raw.get("capped")))
59
+
60
+ def size(item):
61
+ return len(json.dumps(item.model_dump(mode="json"), ensure_ascii=False))
62
+
63
+ if size(result) <= max_chars:
64
+ return _noted(result)
65
+ result.values, result.cut = {}, True
66
+ for limit in _LIST_STEPS:
67
+ if size(result) <= max_chars:
68
+ break
69
+ result.groups = _cut_groups(groups, limit) if limit else {}
70
+ return _noted(result)
71
+
72
+
73
+ def _noted(result: ChangeList) -> ChangeList:
74
+ if result.cut:
75
+ result.note = ("The list is shortened to fit; the counts are complete. "
76
+ "Read the full model with roiko_get_model if more detail is needed.")
77
+ if result.partial:
78
+ result.note = ((result.note + " ") if result.note else "") + \
79
+ "The model is very large, so the comparison is partial."
80
+ return result