Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

fix(studio): wire the configurable engine port through every consumer

FABIOTESSf7efcefd3f3d
diff --git a/studio/.env b/studio/.env
deleted file mode 100644
index f7a6d786..00000000
--- a/studio/.env
+++ /dev/null
@@ -1 +0,0 @@
-VITE_ENGINE_PORT=8137
diff --git a/studio/README.md b/studio/README.md
index d3da6c44..e054b68c 100644
--- a/studio/README.md
+++ b/studio/README.md
@@ -35,7 +35,7 @@ Natural language ontology engineering via the Claude Agent SDK.
**How it works:**
- The agent runs as a Node.js sidecar process (`src-tauri/sidecars/agent/`), spawned by Tauri 3 seconds after the engine starts.
-- The sidecar connects Claude to the Open Ontologies engine via its MCP endpoint (`http://localhost:8080/mcp`), giving Claude access to all 42 ontology tools (`onto_load`, `onto_query`, `onto_validate`, `onto_lint`, `onto_reason`, `onto_enforce`, `onto_plan`, `onto_apply`, `onto_save`, `onto_diff`, `onto_align`, `onto_embed`, `onto_search`, and more).
+- The sidecar connects Claude to the Open Ontologies engine via its MCP endpoint (`http://localhost:<port>/mcp`, port 8137 by default, passed down from the Rust host), giving Claude access to all 42 ontology tools (`onto_load`, `onto_query`, `onto_validate`, `onto_lint`, `onto_reason`, `onto_enforce`, `onto_plan`, `onto_apply`, `onto_save`, `onto_diff`, `onto_align`, `onto_embed`, `onto_search`, and more).
- The Tauri Rust backend communicates with the sidecar over stdin/stdout using a simple JSON protocol (`{ type: 'chat', message }` in, `{ type: 'text' | 'tool_call' | 'done' | 'error' }` out).
- Multi-turn sessions are maintained in-memory within the sidecar process (not persisted to disk).
- After any mutation tool call (`onto_load`, `onto_apply`, `onto_reason`, etc.), the frontend detects `mutated: true` in the `done` message and triggers a graph refresh.
@@ -150,7 +150,7 @@ Tauri will:
1. Compile the Rust shell (first run takes ~1 min, subsequent runs are fast)
2. Start the Vite dev server on `localhost:1420` with HMR
3. Open the app window
-4. Spawn the engine sidecar (`open-ontologies serve-http --port 8080`)
+4. Spawn the engine sidecar (`open-ontologies serve-http --port 8137` by default, configurable via `OPEN_ONTOLOGIES_STUDIO_PORT`)
5. Spawn the agent sidecar (Node.js, after a 3s delay)
## Development
diff --git a/studio/src-tauri/sidecars/agent/dist/index.js b/studio/src-tauri/sidecars/agent/dist/index.js
index b6cf197d..8d1dd377 100644
--- a/studio/src-tauri/sidecars/agent/dist/index.js
+++ b/studio/src-tauri/sidecars/agent/dist/index.js
@@ -9197,7 +9197,13 @@ function tokeniseInbound(text) {
// index.ts
import * as readline from "readline";
-var ENGINE_URL = "http://localhost:8080/mcp";
+var DEFAULT_ENGINE_PORT = 8137;
+function resolveEnginePort() {
+ const raw = process.env.OPEN_ONTOLOGIES_STUDIO_PORT;
+ const parsed = raw ? Number.parseInt(raw, 10) : NaN;
+ return Number.isInteger(parsed) && parsed > 0 && parsed < 65536 ? parsed : DEFAULT_ENGINE_PORT;
+}
+var ENGINE_URL = `http://localhost:${resolveEnginePort()}/mcp`;
var SYSTEM_PROMPT = `You are an ontology engineering assistant with MCP tools for the Open Ontologies engine.
No emoji. Plain text and markdown only.
diff --git a/studio/src-tauri/sidecars/agent/index.ts b/studio/src-tauri/sidecars/agent/index.ts
index e58c82ca..9a00e3cd 100644
--- a/studio/src-tauri/sidecars/agent/index.ts
+++ b/studio/src-tauri/sidecars/agent/index.ts
@@ -3,7 +3,18 @@ import { tokeniseInbound } from './tokenise.js';
import type { Query } from '@anthropic-ai/claude-agent-sdk';
import * as readline from 'readline';
-const ENGINE_URL = 'http://localhost:8080/mcp';
+const DEFAULT_ENGINE_PORT = 8137;
+
+// Set by chat::spawn_agent_sidecar in the Rust host, which is the single
+// place that resolves the engine's actual port. The fallback here only
+// matters if the sidecar is ever run standalone outside that host.
+function resolveEnginePort(): number {
+ const raw = process.env.OPEN_ONTOLOGIES_STUDIO_PORT;
+ const parsed = raw ? Number.parseInt(raw, 10) : NaN;
+ return Number.isInteger(parsed) && parsed > 0 && parsed < 65536 ? parsed : DEFAULT_ENGINE_PORT;
+}
+
+const ENGINE_URL = `http://localhost:${resolveEnginePort()}/mcp`;
const SYSTEM_PROMPT = `You are an ontology engineering assistant with MCP tools for the Open Ontologies engine.
diff --git a/studio/src-tauri/src/chat.rs b/studio/src-tauri/src/chat.rs
index 8cfab00d..53f22ca2 100644
--- a/studio/src-tauri/src/chat.rs
+++ b/studio/src-tauri/src/chat.rs
@@ -5,6 +5,8 @@ use std::process::{Child, Command, Stdio};
use std::sync::Mutex;
use tauri::{Emitter, Manager};
+use crate::engine;
+
pub struct ChatState {
pub process: Mutex<Option<Child>>,
}
@@ -118,12 +120,18 @@ pub fn spawn_agent_sidecar(app: &tauri::AppHandle) -> Result<(), String> {
let entry = sidecar_entry(app)?;
let node = resolve_node_binary();
+ // Same port the engine itself was spawned with (see engine::engine_port,
+ // the single place that resolves it). Passed through the environment
+ // rather than re-resolved here so the sidecar can't drift from it.
+ let port = engine::engine_port();
+
let mut child = Command::new(&node)
.arg(&entry)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.env("PATH", augmented_path())
+ .env("OPEN_ONTOLOGIES_STUDIO_PORT", port.to_string())
.spawn()
.map_err(|e| format!("Failed to spawn agent sidecar: {e}"))?;
diff --git a/studio/src-tauri/src/engine.rs b/studio/src-tauri/src/engine.rs
index 9bffe139..a4c40ef6 100644
--- a/studio/src-tauri/src/engine.rs
+++ b/studio/src-tauri/src/engine.rs
@@ -126,11 +126,23 @@ fn parse_port(raw: Option<&str>) -> u16 {
.unwrap_or(DEFAULT_ENGINE_PORT)
}
-fn engine_port() -> u16 {
+/// Single source of truth for the engine's HTTP port. Every consumer of the
+/// port (the REST base URL handed to the frontend, the MCP endpoint the
+/// backend calls, and the environment variable passed to the agent sidecar)
+/// derives its value from this function rather than resolving it again.
+pub(crate) fn engine_port() -> u16 {
let raw = std::env::var("OPEN_ONTOLOGIES_STUDIO_PORT").ok();
parse_port(raw.as_deref())
}
+/// Exposes the resolved engine port to the frontend so it does not need its
+/// own copy of the port-resolution logic (and cannot drift from Rust's view
+/// of it).
+#[tauri::command]
+pub fn get_engine_port() -> u16 {
+ engine_port()
+}
+
pub fn spawn_engine(app: &tauri::AppHandle) -> Result<(), String> {
let binary = resolve_engine_binary()?;
let port = engine_port();
diff --git a/studio/src-tauri/src/lib.rs b/studio/src-tauri/src/lib.rs
index 9f36d210..42d75915 100644
--- a/studio/src-tauri/src/lib.rs
+++ b/studio/src-tauri/src/lib.rs
@@ -50,6 +50,7 @@ pub fn run() {
})
.invoke_handler(tauri::generate_handler![
engine_status,
+ engine::get_engine_port,
mcp::mcp_call,
mcp::set_mcp_session,
chat::send_chat_message,
diff --git a/studio/src-tauri/src/mcp.rs b/studio/src-tauri/src/mcp.rs
index 83ea2c0f..c947f4b4 100644
--- a/studio/src-tauri/src/mcp.rs
+++ b/studio/src-tauri/src/mcp.rs
@@ -1,5 +1,14 @@
use std::sync::Mutex;
+use crate::engine;
+
+/// Pure construction of the MCP endpoint URL from a port, kept separate from
+/// port resolution so it can be unit-tested without touching the network or
+/// environment variables.
+fn mcp_endpoint(port: u16) -> String {
+ format!("http://127.0.0.1:{port}/mcp")
+}
+
pub struct McpState {
pub session_id: Mutex<Option<String>>,
pub client: reqwest::Client,
@@ -61,7 +70,7 @@ async fn do_mcp_call(
};
let mut req = client
- .post("http://127.0.0.1:8080/mcp")
+ .post(mcp_endpoint(engine::engine_port()))
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream")
.json(&body);
@@ -137,3 +146,17 @@ fn rand_id() -> u64 {
.map(|d| d.subsec_nanos() as u64)
.unwrap_or(1)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn mcp_endpoint_tracks_the_configured_port_not_a_literal() {
+ assert_eq!(mcp_endpoint(8137), "http://127.0.0.1:8137/mcp");
+ assert_eq!(mcp_endpoint(9001), "http://127.0.0.1:9001/mcp");
+ // The regression this guards against: the engine's default port
+ // changed away from 8080, but this call site kept the old literal.
+ assert_ne!(mcp_endpoint(8137), "http://127.0.0.1:8080/mcp");
+ }
+}
diff --git a/studio/src/lib/mcp-client.ts b/studio/src/lib/mcp-client.ts
index 5b904c6c..ecd53150 100644
--- a/studio/src/lib/mcp-client.ts
+++ b/studio/src/lib/mcp-client.ts
@@ -3,7 +3,18 @@ import { invoke } from '@tauri-apps/api/core';
// All MCP calls go through the Tauri backend (Rust → localhost, configurable port)
// This avoids webview fetch restrictions and handles SSE parsing in Rust
-const ENGINE_PORT = import.meta.env.VITE_ENGINE_PORT ?? '8137';
+// Rust (engine::engine_port) is the single source of truth for the port:
+// asked for once via a Tauri command and cached, rather than duplicated in
+// a frontend env var that could disagree with what the engine actually
+// bound to.
+let cachedPort: string | null = null;
+
+async function enginePort(): Promise<string> {
+ if (cachedPort === null) {
+ cachedPort = String(await invoke<number>('get_engine_port'));
+ }
+ return cachedPort;
+}
async function mcpCall(method: string, params: Record<string, unknown> = {}): Promise<unknown> {
try {
@@ -29,15 +40,17 @@ async function mcpCall(method: string, params: Record<string, unknown> = {}): Pr
}
// Sessionless REST API — direct access to shared graph store, no MCP session required
-const API = `http://127.0.0.1:${ENGINE_PORT}/api`;
+async function apiBase(): Promise<string> {
+ return `http://127.0.0.1:${await enginePort()}/api`;
+}
async function apiGet(path: string): Promise<unknown> {
- const resp = await fetch(`${API}${path}`);
+ const resp = await fetch(`${await apiBase()}${path}`);
return resp.json();
}
async function apiPost(path: string, body: Record<string, unknown>): Promise<unknown> {
- const resp = await fetch(`${API}${path}`, {
+ const resp = await fetch(`${await apiBase()}${path}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),