Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

**sysmod-sysmlv2-api-mcp** connects to a SysML v2 repository server and provides:

- 📄 **Single-page SYSMOD Viewer** (`web/`) — the recommended viewer: one web page, no Flask server, no Python packages. See [Single-page viewer](#single-page-viewer-web)
- 🔌 **REST API + Web UI** — interactive browser-based viewer and wizard for SYSMOD models
- 🤖 **MCP Server** — exposes all SYSMOD artifacts as tools for AI agents (Claude, Cursor, GitHub Copilot, etc.)
- 🧠 **SYSMOD AI Agent** — an LLM can autonomously query problem statements, contexts, stakeholders, requirements, feature trees, and more directly from the SysML v2 model
Expand All @@ -38,9 +39,38 @@

---

## Single-page viewer (`web/`)

The SYSMOD Viewer as **one web page**: it reads the model with the SysML v2 API directly from the browser. No Flask server, no `pip install`.

```bash
python web/serve.py # then open http://localhost:8080/

# other SysML v2 servers: name them, as for the Flask server
ALLOWED_SYSML_SERVER_ORIGINS=http://localhost:9000,http://sysml2.intercax.com:9000 python web/serve.py
```

`serve.py` uses only the Python standard library. It serves the page and **relays** its requests, read-only, to the SysML v2 API servers in `ALLOWED_SYSML_SERVER_ORIGINS` (as for the Flask server; default `http://localhost:9000`): a page alone can only read servers that allow requests from it (CORS), and a page on https may not call an http server. With the relay every allowed server works, e.g. `http://sysml2.intercax.com:9000` or Open-MBEE Flexo. The relay listens on localhost only, allows only GET of the read endpoints (`/projects`, `…/branches`, `…/commits`, `…/commits/{id}/elements`) with the paging query, follows no redirects and passes the token on without storing it. Any other static web server works too; then only servers that allow CORS can be read.

What it shows: the project cover (purpose, owner, description, the SYSMOD version from `@SYSMOD { version = … }`, the cover view), the SYSMOD Atlas, completeness checks, problem statement, system idea and objectives, stakeholders, needs, system requirements, system use cases and the context diagram of all six contexts, from the brownfield to the product architecture: actors, the system of interest with its white box parts, and the interfaces with the ports they connect. It reads **SYSMOD v5** (the project is an `occurrence def` with `#project`; the roles are found by their direct redefinition of the features of `SYSMOD::Project`). It loads a commit once (paged) and reads it in the browser. Also a `.json` file with the elements of a commit can be opened.

| File | What |
|---|---|
| `web/index.html`, `web/sysmod-viewer.css` | the page |
| `web/sysmod-viewer-core.js` | reads the SYSMOD project from the elements (pure ES module, no dependencies) |
| `web/sysmod-viewer-api.js` | the requests to the SysML v2 API server, paging, relay |
| `web/sysmod-viewer.js` | the interface; the context diagrams are SVG drawn by the page (no CDN) |
| `web/serve.py` | serves the page and relays the requests |

The same JavaScript runs on [mbse4u.com/tools/sysmod-viewer](https://mbse4u.com/tools/sysmod-viewer/), which in addition opens the Delivery Drone example and `.sysml` files with a SysML v2 engine in the browser, and reaches servers without CORS through a relay with an allowlist. Changes to the viewer belong here; the site copies them.

Read-only. Editing the problem statement, AI suggestions and the creation wizard are in the Flask server (below). Tests of `serve.py`: `python -m pytest tests/test_web_serve.py` (part of `python -m pytest`, no extra packages). The viewer's JavaScript is tested on mbse4u.com with the Delivery Drone model and `tests/test_sysmod.sysml` of this repository.

---

## Features

### SYSMOD Viewer (`project.html`)
### SYSMOD Viewer (`project.html`, Flask; for the single-page viewer see above)

| Feature | Description |
|---|---|
Expand Down Expand Up @@ -211,7 +241,7 @@ ALLOWED_SYSML_SERVER_ORIGINS=http://localhost:9000,http://127.0.0.1:9000,http://
python sysmod_api_server.py
```

Runs on `http://localhost:5000`. Open in browser to use the web UI.
Runs on `http://localhost:5000`. Open in browser to use the web UI (viewer with editing and AI, wizard). For viewing only, the [single-page viewer](#single-page-viewer-web) needs no server packages.

---

Expand Down
163 changes: 163 additions & 0 deletions tests/test_web_serve.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
"""Tests of web/serve.py: the rules of the relay and real HTTP requests against a fake SysML v2 API server.
Standard library only: python -m unittest tests/test_web_serve.py (pytest runs it too)"""
import json
import sys
import threading
import unittest
import urllib.error
import urllib.parse
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "web"))
import serve # noqa: E402


class FakeSysml(BaseHTTPRequestHandler):
"""A tiny SysML v2 API server: echoes what it received, pages elements with a Link header."""
def log_message(self, *a):
pass

def send(self, code, body, headers=None):
b = json.dumps(body).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
for k, v in (headers or {}).items():
self.send_header(k, v)
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
self.end_headers()
self.wfile.write(b)

def do_GET(self):
u = urllib.parse.urlsplit(self.path)
if u.path == "/projects":
return self.send(200, [{"@id": "p-1", "name": "P", "auth": self.headers.get("Authorization", ""), "query": u.query}])
if u.path == "/projects/p-1/commits/c/elements":
return self.send(200, [{"@id": "e-1"}], {"Link": f"<http://127.0.0.1:{self.server.server_address[1]}/projects/p-1/commits/c/elements?page%5Bafter%5D=e-1>; rel=\"next\""})
if u.path == "/projects/redirect":
self.send_response(302); self.send_header("Location", "https://example.org/"); self.end_headers(); return
if u.path == "/projects/html":
b = b"<html>oops</html>"
self.send_response(200); self.send_header("Content-Type", "text/html"); self.end_headers(); self.wfile.write(b); return
if u.path == "/projects/secret":
return self.send(401, {"error": "unauthorized"})
return self.send(404, {"error": "not found"})


def start(handler):
srv = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv


ALLOWED = "https://h.org,http://sysml2.intercax.com:9000"


class Rules(unittest.TestCase):
def setUp(self):
import os
os.environ["ALLOWED_SYSML_SERVER_ORIGINS"] = ALLOWED

def tearDown(self):
import os
os.environ.pop("ALLOWED_SYSML_SERVER_ORIGINS", None)
def ok(self, url, expected=None):
target, error = serve.check_url(url)
self.assertEqual(error, "", url)
if expected:
self.assertEqual(target, expected)

def refused(self, url, reason):
self.assertEqual(serve.check_url(url), (None, reason), url)

def test_allowed(self):
self.ok("https://h.org/projects")
self.ok("http://sysml2.intercax.com:9000/projects?page%5Bsize%5D=1000", "http://sysml2.intercax.com:9000/projects?page%5Bsize%5D=1000")
self.ok("https://h.org/projects?page[size]=10", "https://h.org/projects?page%5Bsize%5D=10")
self.ok("https://h.org/api/v1/projects/p/commits/c/elements?page%5Bafter%5D=x")
self.ok("https://h.org/projects/p/branches/b")
self.ok("https://H.org/projects", "https://h.org/projects")

def test_allowed_origins(self):
import os
self.refused("https://other.org/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)")
self.refused("http://h.org/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)")
self.refused("http://sysml2.intercax.com:9001/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)")
os.environ.pop("ALLOWED_SYSML_SERVER_ORIGINS")
self.ok("http://localhost:9000/projects") # the default, as for the Flask server
self.refused("https://h.org/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)")

def test_refused(self):
self.refused("", "invalid address")
self.refused("file:///etc/passwd", "only http and https")
self.refused("https://h.org@evil.org/projects", "invalid address")
self.refused("https://u:p@h.org/projects", "invalid address")
self.refused("https://h.org/projects#x", "invalid address")
self.refused("https://h.org/admin", "not a read endpoint of the SysML v2 API")
self.refused("https://h.org/projects/p/query-results", "not a read endpoint of the SysML v2 API")
self.refused("https://h.org/projects/../admin", "invalid path")
self.refused("https://h.org/projects/%2e%2e", "invalid path")
self.refused("https://h.org//projects", "invalid path")
self.refused("https://h.org/projects?x=1", "query not allowed")
self.refused("https://h.org/projects?page%5Bsize%5D=1&page%5Bsize%5D=2", "query not allowed")
self.refused("https://h.org/projects?page%5Bsize%5D=x", "query not allowed")


class Relay(unittest.TestCase):
@classmethod
def setUpClass(cls):
import os
cls.up = start(FakeSysml)
os.environ["ALLOWED_SYSML_SERVER_ORIGINS"] = f"http://127.0.0.1:{cls.up.server_address[1]}"
cls.viewer = start(serve.Handler)
cls.U = f"http://127.0.0.1:{cls.up.server_address[1]}"
cls.R = f"http://127.0.0.1:{cls.viewer.server_address[1]}"

@classmethod
def tearDownClass(cls):
import os
os.environ.pop("ALLOWED_SYSML_SERVER_ORIGINS", None)
cls.up.shutdown(); cls.viewer.shutdown()

def get(self, path, headers=None):
req = urllib.request.Request(self.R + path, headers=headers or {})
try:
with urllib.request.urlopen(req, timeout=10) as r:
return r.status, r.headers, r.read()
except urllib.error.HTTPError as e:
return e.code, e.headers, e.read()

def relay(self, url, headers=None):
return self.get("/relay?url=" + urllib.parse.quote(url, safe=""), headers)

def test_page_and_config(self):
status, _, body = self.get("/")
self.assertEqual(status, 200)
self.assertIn(b'id="sysmod-viewer"', body)
status, _, body = self.get("/viewer-config.json")
self.assertEqual(json.loads(body)["relay"]["servers"], [self.U])
self.assertEqual(self.get("/serve.py")[0], 404)

def test_relayed_with_token_and_paging(self):
status, _, body = self.relay(self.U + "/projects?page%5Bsize%5D=1000", {"X-Relay-Authorization": "Bearer t"})
data = json.loads(body)[0]
self.assertEqual((status, data["auth"], data["query"]), (200, "Bearer t", "page%5Bsize%5D=1000"))
status, headers, _ = self.relay(self.U + "/projects/p-1/commits/c/elements")
self.assertEqual(headers["Link"], f"<{self.U}/projects/p-1/commits/c/elements?page%5Bafter%5D=e-1>; rel=\"next\"")
self.assertIsNone(headers.get("Access-Control-Allow-Origin"))

def test_errors(self):
self.assertEqual(self.relay(self.U + "/projects/secret")[0], 401)
self.assertEqual(self.relay(self.U + "/projects/nothing")[0], 404)
self.assertEqual(self.relay(self.U + "/projects/redirect")[0], 502)
self.assertIn(b"did not answer with JSON", self.relay(self.U + "/projects/html")[2])
self.assertEqual(self.relay(self.U + "/admin")[0], 400)
self.assertEqual(self.relay("http://127.0.0.1:1/projects")[0], 400) # not on the list
self.assertEqual(self.relay("https://example.org/projects")[0], 400)
self.assertEqual(self.relay(self.U + "/projects", {"Sec-Fetch-Site": "cross-site"})[0], 403)
status, headers, _ = self.relay(self.U + "/admin")
self.assertEqual(headers["X-Relay-Error"], "1")


if __name__ == "__main__":
unittest.main()
109 changes: 109 additions & 0 deletions web/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>SYSMOD Viewer</title>
<meta name="description" content="View a SYSMOD project of a SysML v2 model: Atlas, problem statement, stakeholders, needs, requirements, use cases and system context diagrams.">
<link rel="stylesheet" href="sysmod-viewer.css">
</head>
<body>
<main>
<header>
<p class="stereo m-0">tool</p>
<h1>SYSMOD Viewer</h1>
<p class="lead">
Shows a <a href="https://sysmod.org">SYSMOD</a> project of a SysML v2 model the way the method structures it: the SYSMOD Atlas, the problem statement,
the system idea and its objectives, stakeholders, needs, system requirements, system use cases and the system context of every architecture.
It reads the model with the SysML v2 API (OMG Systems Modeling API). A single page, no server of its own: everything runs in your browser.
</p>
</header>

<div id="sysmod-viewer" class="mt-10" data-config='{"core":"./sysmod-viewer-core.js","api":"./sysmod-viewer-api.js"}'>
<noscript><p class="ui text-muted">The SYSMOD viewer needs JavaScript.</p></noscript>

<section class="sv-source" aria-labelledby="sv-source-h" hidden data-js-only>
<h2 id="sv-source-h" class="display display-md mb-4">Open a model</h2>
<div class="sv-tabs ui" role="tablist" aria-label="Source of the model">
<button type="button" role="tab" id="sv-tab-server" aria-controls="sv-panel-server" aria-selected="true" data-src-tab="server">SysML v2 API server</button>
<button type="button" role="tab" id="sv-tab-files" aria-controls="sv-panel-files" aria-selected="false" data-src-tab="files">JSON file</button>
</div>

<div class="sv-panel" role="tabpanel" id="sv-panel-server" aria-labelledby="sv-tab-server" data-src-panel="server">
<p class="m-0 mb-4 max-w-[46rem]" data-relay-note>
The address of a SysML v2 API server, e.g. the API services of the SysML v2 Pilot Implementation or Open-MBEE Flexo.
Opened directly, the page can only read servers that allow requests from it (CORS); run <code>python web/serve.py</code> to reach any server through its local relay.
</p>
<div class="sv-form">
<label class="ui font-semibold" for="sv-url">Server address</label>
<input id="sv-url" class="sv-input" type="url" inputmode="url" placeholder="http://localhost:9000" autocomplete="url" spellcheck="false" data-url>
<label class="ui font-semibold" for="sv-token">Token <span class="font-normal text-muted">(optional)</span></label>
<input id="sv-token" class="sv-input" type="password" placeholder="Bearer …" autocomplete="off" spellcheck="false" data-token>
<span></span>
<p class="m-0">
<button type="button" class="btn" data-connect>Connect</button>
<output class="ui text-muted ml-3 sv-status" data-status-server aria-live="polite"></output>
</p>
</div>
<div class="sv-form mt-4" data-proj-row hidden>
<label class="ui font-semibold" for="sv-proj-filter">Find project</label>
<input id="sv-proj-filter" class="sv-input" type="search" placeholder="Name or id" data-proj-filter>
<label class="ui font-semibold" for="sv-proj">Project</label>
<select id="sv-proj" class="sv-input" data-proj></select>
<label class="ui font-semibold" for="sv-commit">Commit</label>
<select id="sv-commit" class="sv-input" data-commit></select>
<span></span>
<p class="m-0"><button type="button" class="btn" data-load>Load the model</button></p>
</div>
<div class="mt-4" data-err-server></div>
</div>

<div class="sv-panel" role="tabpanel" id="sv-panel-files" aria-labelledby="sv-tab-files" data-src-panel="files" hidden>
<p class="m-0 mb-4 max-w-[46rem]">
A <strong>.json file</strong> with the elements of a commit, as <code>GET …/commits/{commit}/elements</code> of the SysML v2 API returns them.
To view <code>.sysml</code> files, use <a href="https://mbse4u.com/tools/sysmod-viewer/">mbse4u.com/tools/sysmod-viewer</a>, which reads them with a SysML v2 engine in the browser.
</p>
<p class="m-0">
<label class="btn sv-file-btn" for="sv-files">Choose a file</label>
<input id="sv-files" class="sr-only" type="file" accept=".json" multiple data-files>
<output class="ui text-muted ml-3 sv-status" data-status-files aria-live="polite"></output>
</p>
<div class="mt-4" data-err-files></div>
</div>

<div class="sv-form mt-6" data-pick hidden>
<label class="ui font-semibold" for="sv-pick">SYSMOD project</label>
<select id="sv-pick" class="sv-input" data-pick-select></select>
</div>
</section>

<div class="sv-out mt-10" data-out aria-live="polite"></div>
</div>

<section class="prose mt-16" aria-labelledby="sv-good-to-know">
<h2 id="sv-good-to-know">Good to know</h2>
<ul>
<li><strong>Run it:</strong> <code>python web/serve.py</code>, then open <code>http://localhost:8080/</code>. The script needs only Python 3, no packages. Browsers do not run the page from a <code>file://</code> address.</li>
<li><strong>CORS and http:</strong> a page can only read servers that allow requests from it. <code>serve.py</code> also relays the requests (read-only) to the servers in <code>ALLOWED_SYSML_SERVER_ORIGINS</code> (default <code>http://localhost:9000</code>), including plain <code>http://</code> ones and servers without CORS.</li>
<li><strong>Token:</strong> optional, passed on as header <code>Authorization</code>; it stays in the page and is never stored. The page address records server, project and commit (not the token).</li>
<li><strong>SYSMOD v5:</strong> the project is an <code>occurrence def</code> with <code>#project</code> or a specialization of <code>SYSMOD::Project</code>; the SYSMOD library must be in the same project.</li>
<li><strong>Read-only.</strong> Editing, the AI suggestions and the creation wizard are in the Flask server of this repository (<code>sysmod_api_server.py</code>).</li>
</ul>
</section>
</main>
<script type="module">
// Settings of the server that delivers this page: web/serve.py provides viewer-config.json with its relay.
const root = document.getElementById('sysmod-viewer');
try {
const r = await fetch('viewer-config.json', { cache: 'no-store' });
if (r.ok) {
const extra = await r.json();
root.dataset.config = JSON.stringify({ ...JSON.parse(root.dataset.config), ...extra });
if (extra.relay) document.querySelector('[data-relay-note]').append(` Running with serve.py: these servers are reached through its relay: ${extra.relay.servers.join(', ')} (ALLOWED_SYSML_SERVER_ORIGINS).`);
}
} catch { /* served without serve.py: no relay */ }
await import('./sysmod-viewer.js');
</script>
</body>
</html>
Loading
Loading