import os
import json
import asyncio
import uuid
import sys
import subprocess
import base64
import shutil
import tempfile
import textwrap
import hashlib
import re
import html
from urllib import error as urllib_error
from urllib import request as urllib_request
from urllib.parse import quote as url_quote, urlparse
from contextlib import asynccontextmanager
from dataclasses import dataclass
from datetime import datetime
from mcp.server import Server, NotificationOptions
from mcp.server.lowlevel.helper_types import ReadResourceContents
from mcp.server.stdio import stdio_server
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
import mcp.types as mcp_types
from lxml import etree
from colorama import init, Fore, Style
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse, Response
from starlette.routing import Route
import uvicorn
# Initialize colorama
init(autoreset=True)
SERVER_VERSION = "1.0.4"
POLL_WORKER_IDLE_SECONDS = 5.0
POLL_WORKER_STARTUP_TIMEOUT_SECONDS = 20.0
VALIDATION_CACHE_LIMIT = 64
ASYNC_VALIDATION_BRIEF_WAIT_SECONDS = 1.0
DEFAULT_VALIDATION_TIMEOUT_SECONDS = 120.0
EXPOSE_INTERNAL_VALIDATION_DETAILS = os.environ.get("XCOS_DEBUG_TOOL_OUTPUT", "").strip().lower() in {"1", "true", "yes", "on"}
VALIDATION_MODES = {"subprocess", "poll", "remote"}
REMOTE_SCILAB_DEFAULT_TRUSTED_UPSTREAM_ID = "xcos-mcp-space"
REMOTE_SCILAB_DEFAULT_POLL_INTERVAL_SECONDS = 1.0
REMOTE_SCILAB_DEFAULT_POLL_TIMEOUT_SECONDS = 120.0
REMOTE_SCILAB_DEFAULT_REQUEST_TIMEOUT_SECONDS = 20.0
# Shared State
class SharedState:
def __init__(self):
self.task_queue = asyncio.Queue()
self.results = {} # task_id -> {"success": bool, "error": str, "event": asyncio.Event}
self.validation_cache = {} # xml_sha256 -> raw validation result
self.last_poll_time = None
self.status_lock = asyncio.Lock()
self.drafts = {} # session_id -> DraftDiagram
self.phase_plans = {} # session_id -> {"phases": list[str], "completed": list[str]}
self.workflows = {} # workflow_id -> WorkflowSession
self.draft_to_workflow = {} # session_id -> workflow_id
self.validation_jobs = {} # job_id -> ValidationJob
self.validation_tasks = {} # job_id -> asyncio.Task
self.poll_worker_process = None
self.poll_worker_log_handle = None
self.poll_worker_log_path = None
self.poll_worker_script_path = None
self.poll_worker_lock = asyncio.Lock()
state = SharedState()
# Absolute pathing for data directory
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(BASE_DIR, "data")
UI_DIR = os.path.join(BASE_DIR, "ui")
ICONS_DIR = os.path.join(BASE_DIR, "icons")
BLOCK_IMAGES_DIR = os.path.join(BASE_DIR, "block_images")
PORT_REGISTRY_PATH = os.path.join(DATA_DIR, "blocks", "port_registry.json")
TEMP_OUTPUT_DIR = os.environ.get("XCOS_TEMP_OUTPUT_DIR", os.path.join(DATA_DIR, "temp"))
SESSION_OUTPUT_DIR = os.environ.get("XCOS_SESSION_OUTPUT_DIR", os.path.join(BASE_DIR, "sessions"))
STATE_DIR = os.environ.get("XCOS_STATE_DIR", os.path.join(BASE_DIR, "state"))
DRAFT_STATE_DIR = os.path.join(STATE_DIR, "drafts")
WORKFLOW_STATE_DIR = os.path.join(STATE_DIR, "workflows")
VALIDATION_JOB_STATE_DIR = os.path.join(STATE_DIR, "validation_jobs")
SERVER_PORT = int(os.environ.get("PORT", os.environ.get("XCOS_SERVER_PORT", "8000")))
MCP_HTTP_PATH = os.environ.get("XCOS_MCP_HTTP_PATH", "/mcp")
MCP_APP_MIME_TYPE = "text/html;profile=mcp-app"
WORKFLOW_UI_RESOURCE_VERSION = "20260406.1"
WORKFLOW_UI_RESOURCE_URI = f"ui://xcos/index.html?v={WORKFLOW_UI_RESOURCE_VERSION}"
DEFAULT_UI_RESOURCE_DOMAINS = [
"https://unpkg.com",
"https://cdn.jsdelivr.net",
"https://esm.sh",
]
WIDGET_TOOL_NAMES = {
"xcos_get_status_widget",
"xcos_get_workflow_widget",
"xcos_get_validation_widget",
"xcos_get_block_catalogue_widget",
"xcos_get_topology_widget",
}
TOOL_DESCRIPTOR_OVERRIDES = {
"xcos_get_status_widget": {"title": "Get Xcos Status Widget", "read_only": True, "idempotent": True, "render_widget": True},
"xcos_get_workflow_widget": {"title": "Get Workflow Widget", "read_only": True, "idempotent": True, "render_widget": True},
"xcos_get_validation_widget": {"title": "Get Validation Widget", "read_only": True, "idempotent": True, "render_widget": True},
"xcos_get_block_catalogue_widget": {"title": "Get Block Catalogue Widget", "read_only": True, "idempotent": True, "render_widget": True},
"xcos_get_topology_widget": {"title": "Get Topology Widget", "read_only": True, "idempotent": True, "render_widget": True},
"xcos_create_workflow": {"title": "Create Workflow", "read_only": False, "destructive": True, "idempotent": False},
"xcos_list_workflows": {"title": "List Workflows", "read_only": True, "idempotent": True},
"xcos_get_workflow": {"title": "Get Workflow", "read_only": True, "idempotent": True},
"xcos_submit_phase": {"title": "Submit Workflow Phase", "read_only": False, "destructive": True, "idempotent": False},
"xcos_review_phase": {"title": "Review Workflow Phase", "read_only": False, "destructive": True, "idempotent": False},
"get_xcos_block_data": {"title": "Get Xcos Block Data", "read_only": True, "idempotent": True},
"get_xcos_block_source": {"title": "Get Xcos Block Source", "read_only": True, "idempotent": True},
"search_related_xcos_files": {"title": "Search Related Xcos Files", "read_only": True, "idempotent": True},
"verify_xcos_xml": {"title": "Verify Xcos XML", "read_only": True, "idempotent": True},
"xcos_start_draft": {"title": "Start Draft Session", "read_only": False, "destructive": True, "idempotent": False},
"xcos_add_blocks": {"title": "Add Blocks To Draft", "read_only": False, "destructive": True, "idempotent": False},
"xcos_add_links": {"title": "Add Links To Draft", "read_only": False, "destructive": True, "idempotent": False},
"xcos_start_validation": {"title": "Start Draft Validation", "read_only": False, "destructive": True, "idempotent": False},
"xcos_get_validation_status": {"title": "Get Validation Status", "read_only": True, "idempotent": True},
"xcos_verify_draft": {"title": "Verify Draft", "read_only": False, "destructive": True, "idempotent": False},
"xcos_commit_phase": {"title": "Commit Workflow Phase", "read_only": False, "destructive": True, "idempotent": False},
"xcos_get_draft_xml": {"title": "Get Draft XML", "read_only": True, "idempotent": True},
"xcos_get_file_path": {"title": "Get Session File Path", "read_only": True, "idempotent": True},
"xcos_get_file_content": {"title": "Get Session File Content", "read_only": True, "idempotent": True},
"xcos_list_sessions": {"title": "List Sessions", "read_only": True, "idempotent": True},
"ping": {"title": "Ping Server", "read_only": True, "idempotent": True},
}
WIDGET_TOOL_OUTPUT_SCHEMA = {
"type": "object",
"properties": {
"widget_type": {"type": "string"},
"payload": {"type": "object"},
},
"required": ["widget_type", "payload"],
"additionalProperties": True,
}
GENERIC_OBJECT_OUTPUT_SCHEMA = {
"type": "object",
"additionalProperties": True,
}
TOOL_OUTPUT_SCHEMA_OVERRIDES = {
"xcos_create_workflow": GENERIC_OBJECT_OUTPUT_SCHEMA,
"xcos_list_workflows": GENERIC_OBJECT_OUTPUT_SCHEMA,
"xcos_get_workflow": GENERIC_OBJECT_OUTPUT_SCHEMA,
"xcos_submit_phase": GENERIC_OBJECT_OUTPUT_SCHEMA,
"xcos_review_phase": GENERIC_OBJECT_OUTPUT_SCHEMA,
"xcos_start_draft": GENERIC_OBJECT_OUTPUT_SCHEMA,
"xcos_add_blocks": GENERIC_OBJECT_OUTPUT_SCHEMA,
"xcos_add_links": GENERIC_OBJECT_OUTPUT_SCHEMA,
"xcos_start_validation": GENERIC_OBJECT_OUTPUT_SCHEMA,
"xcos_get_validation_status": GENERIC_OBJECT_OUTPUT_SCHEMA,
"xcos_verify_draft": GENERIC_OBJECT_OUTPUT_SCHEMA,
"xcos_commit_phase": GENERIC_OBJECT_OUTPUT_SCHEMA,
"xcos_get_file_path": GENERIC_OBJECT_OUTPUT_SCHEMA,
"xcos_list_sessions": GENERIC_OBJECT_OUTPUT_SCHEMA,
"ping": GENERIC_OBJECT_OUTPUT_SCHEMA,
}
WORKFLOW_PHASE_ORDER = [
"phase1_math_model",
"phase2_architecture",
"phase3_implementation",
]
WORKFLOW_PHASE_LABELS = {
"phase1_math_model": "Phase 1: Mathematical Analysis & Calculus",
"phase2_architecture": "Phase 2: Architectural Graph & Parameter Plan",
"phase3_implementation": "Phase 3: Implementation & Validation",
}
REVIEWABLE_PHASES = {"phase1_math_model", "phase2_architecture"}
BUILD_XCOS_DIAGRAM_PROMPT_NAME = "build_xcos_diagram"
BUILD_XCOS_DIAGRAM_PROMPT_TITLE = "Build Xcos Diagram"
BUILD_XCOS_DIAGRAM_PROMPT_DESCRIPTION = (
"Guides an MCP-compatible assistant through a 3-phase gated workflow to model, plan, and build "
"a Scilab Xcos diagram. Each phase requires explicit user approval before proceeding."
)
BUILD_XCOS_DIAGRAM_PROMPT_RESULT_DESCRIPTION = (
"3-phase gated Xcos diagram builder with user approval gates"
)
BUILD_XCOS_DIAGRAM_PROMPT_ARGUMENT = mcp_types.PromptArgument(
name="problem_statement",
description=(
"Description of the physical or mathematical system to model "
"(e.g. 'simple pendulum with g=9.8, L=2m')"
),
required=True,
)
BUILD_XCOS_DIAGRAM_PROMPT_TEMPLATE = textwrap.dedent(
"""\
Build an Xcos diagram for the following system:
{{problem_statement}}
Follow this exact process. Never skip a step. Never proceed past an approval gate without the user explicitly typing 'approve'.
---
## PHASE 1 — Math model
**Step 1.** Call `xcos_get_status_widget`. Display the widget. If the server is not connected, stop and tell the user before doing anything else.
**Step 2.** Call `xcos_get_block_catalogue_widget` with a relevant category (e.g. 'Continuous', 'Sources', 'Sinks'). Display the widget so the user can see which blocks are available.
**Step 3.** Call `xcos_create_workflow` with the problem statement. Store the returned `workflow_id` — you will need it for every subsequent phase call.
**Step 4.** Derive the governing equations step by step in plain text. Show all algebra. Define every variable and parameter with units and numeric values.
**Step 5.** Generate a custom visual diagram showing the signal flow: blocks for each operation with their Xcos name and numeric parameters (e.g. GAIN[-4.9]), and arrows showing how signals connect. Ensure the layout is clean and spacious with no overlapping text.
**Step 6.** Call `xcos_submit_phase` with `phase='phase1_math_model'`, `workflow_id`, and the full math derivation as content.
**Step 7.** Call `xcos_get_workflow_widget` with the `workflow_id`. Display the widget.
**Step 8.** STOP. Ask: 'Does the math and signal flow look correct? Reply **approve** or describe what to change.'
**Step 9.** If the user requests changes: revise steps 4–5, call `xcos_submit_phase` again, display the widget again, ask again. Repeat until approved. Only call `xcos_review_phase` with `phase='phase1_math_model'` and `decision='approve'` after the user explicitly approves. Then call `xcos_get_workflow_widget` and display it.
---
## PHASE 2 — Architecture plan
**Step 10.** Call `get_xcos_block_data` for every single block you plan to use. Never write block XML from memory or examples — always use the returned XML as the authoritative template. This gives you the correct port IDs, parameter structure, simulation function name, and blockType.
**Step 11.** If you need to understand a block's internal behaviour or parameters more deeply, call `get_xcos_block_source` for that block. Use `search_related_xcos_files` to find any related configuration files if the block has complex dependencies.
**Step 12.** Write out the full architecture plan: every block (Xcos name, simulation function, parameters with values), and every link (source block + port ID → target block + port ID). Be explicit about clock/activation links vs data links.
**Step 13.** Generate a custom visual diagram showing the actual Xcos block architecture. Use simple block shapes with the exact Xcos name and key parameter (e.g. GAIN[k=-5]). Use solid arrows for data/signal links and dashed arrows for clock/activation links. Ensure the layout is extremely clean and spacious, with distinct inputs/outputs and NO overlapping text or arrows pointing to nowhere. The diagram must match the architecture plan perfectly.
**Step 14.** Call `xcos_submit_phase` with `phase='phase2_architecture'`, `workflow_id`, and the full block + link plan as content.
**Step 15.** Call `xcos_get_workflow_widget` with the `workflow_id`. Display the widget.
**Step 16.** STOP. Ask: 'Does this block layout look right? Reply **approve** or describe what to change.'
**Step 17.** If the user requests changes: revise steps 10–14, resubmit, display widget, ask again. Repeat until approved. Only call `xcos_review_phase` with `phase='phase2_architecture'` and `decision='approve'` after the user explicitly approves. Then call `xcos_get_workflow_widget` and display it.
---
## PHASE 3 — Build and verify
**Step 18.** Call `xcos_start_draft` with the `workflow_id`. Store the returned `session_id` — you will need it for all remaining steps.
**Step 19.** Call `xcos_add_blocks` with `session_id`. Use only XML retrieved from `get_xcos_block_data` — never from memory.
**Step 20.** Call `xcos_get_topology_widget` with `session_id`. Display the widget. The user should see all blocks appear in the graph before any links are added.
**Step 21.** Call `xcos_add_links` with `session_id`. Use port IDs exactly as returned by `get_xcos_block_data`.
**Step 22.** Call `xcos_get_topology_widget` with `session_id` again. Display the widget. Check for missing links or disconnected ports — fix before continuing.
**Step 23.** Call `xcos_get_draft_xml` with `session_id` and `pretty_print=true`. Show a brief summary of the XML structure to the user.
**Step 24.** STOP. Ask: 'Ready to validate? Reply **approve** to run verification.'
**Step 25.** After approval: call `xcos_verify_draft` with `session_id`.
**Step 26.** Call `xcos_get_validation_widget` with the current draft XML. Display the widget.
- If `success=true`: proceed to step 27.
- If `success=false`: read the error carefully. Call `xcos_get_draft_xml` to inspect the current XML. Fix the specific block or link causing the error. Call `xcos_add_blocks` or `xcos_add_links` to rebuild, then repeat from step 25. Use `verify_xcos_xml` directly on fixed XML snippets if you want to spot-check a repair before rebuilding the full session. Never stop after one failure — keep iterating until `success=true`.
If validation still fails after 3 repair attempts: stop the repair loop. Call xcos_get_draft_xml with pretty_print=true and show the full XML to the user. Call xcos_get_validation_widget and display it. Ask: "I was unable to fix this automatically after 3 attempts. Here is the current XML and the error. Would you like to guide the fix, or should I start phase 3 over?"
**Step 27.** Call `xcos_commit_phase` with `session_id` and `phase_label='phase3_implementation'` to commit the verified XML to file.
**Step 28.** Call `xcos_submit_phase` with `phase='phase3_implementation'`, `workflow_id`, and a summary confirming the file path and validation result as content.
**Step 29.** Call `xcos_get_file_path` with `session_id`. Present the .xcos file to the user for download.
**Step 30a.** If the user asks to inspect the final file content, call `xcos_get_file_content` with `session_id` and `source='last_verified'`. If the user asks to recover content from a previous session, call `xcos_list_sessions` to find it first.
**Step 30.** Call `xcos_get_workflow_widget` with the `workflow_id` one final time. Display the completed 3-phase summary so the user can confirm everything is done.
---
## Rules that apply throughout all phases
- Never proceed past a STOP gate without the user explicitly typing 'approve'.
- Never write block XML from memory — always call `get_xcos_block_data` first.
- Never skip `get_xcos_block_source` or `search_related_xcos_files` if a block's parameters or dependencies are unclear.
- Every diagram must be generated as a clean visual layout. Avoid overlapping text, broken arrow paths, or ASCII art.
- Always call `xcos_get_workflow_widget` after every `xcos_submit_phase` call.
- Always display every widget inline immediately after it is returned.
- If the user requests changes at any approval gate, go back and revise — never push forward.
- A diagram is only done when `xcos_verify_draft` returns `success=true`. Never declare it done before that.
- Use `xcos_list_sessions` and `xcos_list_workflows` at any point if you lose track of active sessions or workflows.
- Use `xcos_get_file_content` with `source='last_verified'` if the user asks to inspect or download the final file content after verification.
- If you ever lose track of the active session_id or workflow_id, call `xcos_list_sessions` and `xcos_list_workflows` to recover them before doing anything else.
- After phases 1 and 2 approval, check if `xcos_commit_phase` needs to be called — consult the tool description for the current phase label convention.
- `verify_xcos_xml` is for spot-checking raw XML snippets during repair. `xcos_verify_draft` is for full session validation. Never confuse the two.
"""
)
BUILD_XCOS_DIAGRAM_PROMPT_TEMPLATE = textwrap.dedent(
"""\
Build an Xcos diagram for the following system:
{{problem_statement}}
Use the 3-phase workflow below. Never continue past an approval gate until the user explicitly types `approve`.
Phase 1: Math model
1. Call `xcos_get_status_widget` and stop if the server is unavailable.
2. Call `xcos_get_block_catalogue_widget` for a relevant category.
3. Call `xcos_create_workflow` and store `workflow_id`.
4. Derive the governing equations with variables, units, and numeric values.
5. Draw a clean signal-flow diagram using Xcos block names and key parameters.
6. Call `xcos_submit_phase(phase1_math_model)` and `xcos_get_workflow_widget`.
7. Ask for approval. If changes are requested, revise and resubmit until approved, then call `xcos_review_phase(approve, phase1_math_model)` and `xcos_get_workflow_widget`.
Phase 2: Architecture plan
8. Call `get_xcos_block_data` for every block before writing XML.
9. Use `get_xcos_block_source` and `search_related_xcos_files` only when parameters or dependencies are unclear.
10. Write the full block plan: block name, simulation function, parameters, and every source-port to target-port link, including event links.
11. Draw a clean Xcos architecture diagram that matches the plan exactly.
12. Call `xcos_submit_phase(phase2_architecture)` and `xcos_get_workflow_widget`.
13. Ask for approval. If changes are requested, revise and resubmit until approved, then call `xcos_review_phase(approve, phase2_architecture)` and `xcos_get_workflow_widget`.
Phase 3: Build and verify
14. Call `xcos_start_draft` and store `session_id`.
15. Call `xcos_add_blocks`, then `xcos_get_topology_widget`.
16. Call `xcos_add_links`, then `xcos_get_topology_widget` again.
17. Call `xcos_get_draft_xml(pretty_print=true)` and summarize the XML briefly.
18. Ask for approval before validation.
19. Call `xcos_verify_draft`, then `xcos_get_validation_widget`.
20. If validation fails, inspect the XML, fix the diagram, rebuild, and retry. Stop after 3 failed repair attempts and ask the user whether to guide the fix or restart phase 3.
21. If validation succeeds, call `xcos_commit_phase(phase3_implementation)`, `xcos_submit_phase(phase3_implementation)`, `xcos_get_file_path`, and `xcos_get_workflow_widget`.
22. Use `xcos_get_file_content(source='last_verified')` only if the user asks to inspect the final XML.
Rules
- Never write block XML from memory.
- Always display returned widgets.
- Always ask for approval at the phase gates.
- A diagram is only done when `xcos_verify_draft` returns `success=true`.
- Use `xcos_list_sessions` and `xcos_list_workflows` if you lose track of IDs.
"""
)
def build_xcos_prompt_text(problem_statement: str) -> str:
cleaned_problem_statement = problem_statement.strip()
if not cleaned_problem_statement:
raise ValueError(
f"Prompt '{BUILD_XCOS_DIAGRAM_PROMPT_NAME}' requires a non-empty 'problem_statement' argument."
)
return BUILD_XCOS_DIAGRAM_PROMPT_TEMPLATE.replace(
"{{problem_statement}}",
cleaned_problem_statement,
)
def file_to_data_uri(path: str, mime_type: str) -> str | None:
if not os.path.exists(path):
return None
with open(path, "rb") as handle:
encoded = base64.b64encode(handle.read()).decode("ascii")
return f"data:{mime_type};base64,{encoded}"
def icon_data_uri(filename: str, mime_type: str) -> str | None:
return file_to_data_uri(os.path.join(ICONS_DIR, filename), mime_type)
def normalize_block_asset_key(value: str) -> str:
return re.sub(r"[^a-z0-9]+", "", (value or "").lower())
def block_image_mime_type(extension: str) -> str | None:
return {
".svg": "image/svg+xml",
".png": "image/png",
}.get(extension.lower())
def build_generated_block_image(block_name: str) -> dict[str, str]:
label = get_block_label(block_name)
safe_label = html.escape(label)
safe_name = html.escape(block_name or "Unknown")
svg = f"""
""".strip()
encoded = base64.b64encode(svg.encode("utf-8")).decode("ascii")
return {
"file_name": f"{block_name or 'generated'}.generated.svg",
"label": label,
"src": f"data:image/svg+xml;base64,{encoded}",
"source": "generated",
}
def build_block_image_catalog() -> dict[str, dict[str, str]]:
catalog = {}
if not os.path.isdir(BLOCK_IMAGES_DIR):
return catalog
for filename in sorted(os.listdir(BLOCK_IMAGES_DIR)):
stem, extension = os.path.splitext(filename)
mime_type = block_image_mime_type(extension)
if not mime_type:
continue
src = file_to_data_uri(os.path.join(BLOCK_IMAGES_DIR, filename), mime_type)
if not src:
continue
key = normalize_block_asset_key(stem)
current = catalog.get(key)
should_replace = current is None or (
current.get("source") != "svg" and extension.lower() == ".svg"
)
if not should_replace:
continue
catalog[key] = {
"file_name": filename,
"label": stem,
"src": src,
"source": extension.lower().lstrip("."),
}
return catalog
def build_block_image_file_index() -> dict[str, dict[str, str]]:
file_index: dict[str, dict[str, str]] = {}
if not os.path.isdir(BLOCK_IMAGES_DIR):
return file_index
for filename in sorted(os.listdir(BLOCK_IMAGES_DIR)):
stem, extension = os.path.splitext(filename)
extension_key = extension.lower().lstrip(".")
if extension_key not in {"svg", "png"}:
continue
key = normalize_block_asset_key(stem)
if not key:
continue
variants = file_index.setdefault(key, {})
if extension_key not in variants:
variants[extension_key] = filename
return file_index
BLOCK_IMAGE_ALIASES = {
"BIGSOM_f": ["SUM"],
"CANIMXY3D": ["3DSCOPE"],
"CEVENTSCOPE": ["DSCOPE"],
"CFSCOPE": ["DSCOPE"],
"CMSCOPE": ["DSCOPE"],
"CMAT3D": ["3DSCOPE"],
"CSCOPE": ["ASCOPE"],
"GENSIN_f": ["SINUS_f"],
"GENSQR_f": ["SQUARE_WAVE_f"],
"NRMSOM_f": ["SUM"],
"SCALE_CMSCOPE": ["SCALE_ASCOPE"],
"SCALE_CSCOPE": ["SCALE_ASCOPE"],
"SOM_f": ["SUM"],
"SUMMATION": ["SUM"],
}
def block_image_candidates(block_name: str) -> list[str]:
candidates = [block_name]
for suffix in ("_f", "_m", "_c"):
if block_name.endswith(suffix):
candidates.append(block_name[: -len(suffix)])
candidates.extend(BLOCK_IMAGE_ALIASES.get(block_name, []))
seen = set()
ordered = []
for candidate in candidates:
key = normalize_block_asset_key(candidate)
if key and key not in seen:
seen.add(key)
ordered.append(key)
return ordered
def get_block_label(block_name: str) -> str:
compact = re.sub(r"[_-]+", " ", (block_name or "")).strip().split()
if not compact:
return "?"
if len(compact) == 1:
return compact[0][:2].upper()
return f"{compact[0][:1]}{compact[1][:1]}".upper()
def resolve_block_image(block_name: str) -> dict[str, str] | None:
for key in block_image_candidates(block_name):
image = BLOCK_IMAGE_CATALOG.get(key)
if image:
return image
return build_generated_block_image(block_name)
def resolve_block_image_files(block_name: str) -> dict[str, str]:
resolved: dict[str, str] = {}
for key in block_image_candidates(block_name):
variants = BLOCK_IMAGE_FILE_INDEX.get(key)
if not variants:
continue
for extension_key in ("svg", "png"):
if extension_key in resolved:
continue
file_name = variants.get(extension_key)
if file_name:
resolved[extension_key] = file_name
if "svg" in resolved and "png" in resolved:
break
return resolved
def build_block_image_candidate_urls(block_name: str, *, base_url: str | None = None) -> list[str]:
variants = resolve_block_image_files(block_name)
origin = (base_url or get_public_base_url()).rstrip("/")
candidates: list[str] = []
for extension_key in ("svg", "png"):
file_name = variants.get(extension_key)
if not file_name:
continue
candidates.append(f"{origin}/block_images/{url_quote(file_name)}")
return candidates
def load_server_icons() -> list[mcp_types.Icon]:
icons: list[mcp_types.Icon] = []
for filename, size in [
("scilab_xcos_mcp_48.png", "48x48"),
("scilab_xcos_mcp_96.png", "96x96"),
("scilab_xcos_mcp_512.png", "512x512"),
]:
src = icon_data_uri(filename, "image/png")
if src:
icons.append(
mcp_types.Icon(
src=src,
mimeType="image/png",
sizes=[size],
)
)
return icons
SERVER_ICONS = load_server_icons()
BLOCK_IMAGE_CATALOG = build_block_image_catalog()
BLOCK_IMAGE_FILE_INDEX = build_block_image_file_index()
def now_iso() -> str:
return datetime.now().isoformat()
@dataclass
class WorkflowPhase:
key: str
label: str
status: str = "pending"
content: str = ""
artifact_type: str = "markdown"
submitted_at: str | None = None
reviewed_at: str | None = None
feedback: str = ""
last_error: str | None = None
def to_dict(self, view: str = "full") -> dict:
payload = {
"key": self.key,
"label": self.label,
"status": self.status,
"submitted_at": self.submitted_at,
"reviewed_at": self.reviewed_at,
"last_error": self.last_error,
}
if view == "summary":
return payload
payload.update({
"content": self.content,
"artifact_type": self.artifact_type,
"feedback": self.feedback,
})
return payload
@classmethod
def from_dict(cls, payload: dict) -> "WorkflowPhase":
return cls(
key=payload["key"],
label=payload["label"],
status=payload.get("status", "pending"),
content=payload.get("content", ""),
artifact_type=payload.get("artifact_type", "markdown"),
submitted_at=payload.get("submitted_at"),
reviewed_at=payload.get("reviewed_at"),
feedback=payload.get("feedback", ""),
last_error=payload.get("last_error"),
)
@dataclass
class WorkflowSession:
workflow_id: str
problem_statement: str
created_at: str
updated_at: str
current_phase: str
phases: dict[str, WorkflowPhase]
draft_session_id: str | None = None
last_verified: dict | None = None
def to_dict(self, view: str = "full") -> dict:
return {
"workflow_id": self.workflow_id,
"problem_statement": self.problem_statement,
"created_at": self.created_at,
"updated_at": self.updated_at,
"current_phase": self.current_phase,
"current_phase_label": WORKFLOW_PHASE_LABELS[self.current_phase],
"draft_session_id": self.draft_session_id,
"last_verified": self.last_verified,
"phases": {
key: phase.to_dict(view=view)
for key, phase in self.phases.items()
},
}
@classmethod
def from_dict(cls, payload: dict) -> "WorkflowSession":
return cls(
workflow_id=payload["workflow_id"],
problem_statement=payload["problem_statement"],
created_at=payload["created_at"],
updated_at=payload["updated_at"],
current_phase=payload["current_phase"],
phases={
key: WorkflowPhase.from_dict(value)
for key, value in payload.get("phases", {}).items()
},
draft_session_id=payload.get("draft_session_id"),
last_verified=payload.get("last_verified"),
)
@dataclass
class ValidationJob:
job_id: str
session_id: str
workflow_id: str | None
status: str
created_at: str
started_at: str | None = None
finished_at: str | None = None
timeout_seconds: float = DEFAULT_VALIDATION_TIMEOUT_SECONDS
result: dict | None = None
error: str | None = None
def to_dict(self) -> dict:
return {
"job_id": self.job_id,
"session_id": self.session_id,
"workflow_id": self.workflow_id,
"status": self.status,
"created_at": self.created_at,
"started_at": self.started_at,
"finished_at": self.finished_at,
"timeout_seconds": self.timeout_seconds,
"result": self.result,
"error": self.error,
}
@classmethod
def from_dict(cls, payload: dict) -> "ValidationJob":
return cls(
job_id=payload["job_id"],
session_id=payload["session_id"],
workflow_id=payload.get("workflow_id"),
status=payload.get("status", "queued"),
created_at=payload.get("created_at", now_iso()),
started_at=payload.get("started_at"),
finished_at=payload.get("finished_at"),
timeout_seconds=float(payload.get("timeout_seconds", DEFAULT_VALIDATION_TIMEOUT_SECONDS)),
result=payload.get("result"),
error=payload.get("error"),
)
def ensure_state_dirs():
for path in [
TEMP_OUTPUT_DIR,
SESSION_OUTPUT_DIR,
STATE_DIR,
DRAFT_STATE_DIR,
WORKFLOW_STATE_DIR,
VALIDATION_JOB_STATE_DIR,
]:
os.makedirs(path, exist_ok=True)
def atomic_write_json(path: str, payload: dict):
directory = os.path.dirname(path)
if directory:
os.makedirs(directory, exist_ok=True)
temp_path = f"{path}.tmp"
with open(temp_path, "w", encoding="utf-8") as f:
json.dump(payload, f, indent=2, ensure_ascii=True)
os.replace(temp_path, path)
def load_json_records(directory: str) -> list[dict]:
if not os.path.exists(directory):
return []
records = []
for file_name in sorted(os.listdir(directory)):
if not file_name.endswith(".json"):
continue
path = os.path.join(directory, file_name)
try:
with open(path, "r", encoding="utf-8") as f:
records.append(json.load(f))
except Exception:
continue
return records
def get_draft_state_path(session_id: str) -> str:
return os.path.join(DRAFT_STATE_DIR, f"{session_id}.json")
def get_workflow_state_path(workflow_id: str) -> str:
return os.path.join(WORKFLOW_STATE_DIR, f"{workflow_id}.json")
def get_validation_job_state_path(job_id: str) -> str:
return os.path.join(VALIDATION_JOB_STATE_DIR, f"{job_id}.json")
def delete_json_file(path: str):
if os.path.exists(path):
os.remove(path)
def persist_draft_session(session_id: str):
draft = state.drafts.get(session_id)
if not draft:
return
draft.session_id = session_id
draft.workflow_id = state.draft_to_workflow.get(session_id) or draft.workflow_id
draft.phase_plan = state.phase_plans.get(session_id) or draft.phase_plan
atomic_write_json(get_draft_state_path(session_id), draft.to_persisted_dict())
def persist_workflow_session(workflow_id: str):
workflow = state.workflows.get(workflow_id)
if not workflow:
return
atomic_write_json(get_workflow_state_path(workflow_id), workflow.to_dict(view="full"))
def persist_validation_job(job_id: str):
job = state.validation_jobs.get(job_id)
if not job:
return
atomic_write_json(get_validation_job_state_path(job_id), job.to_dict())
def delete_draft_session(session_id: str):
state.drafts.pop(session_id, None)
state.phase_plans.pop(session_id, None)
state.draft_to_workflow.pop(session_id, None)
delete_json_file(get_draft_state_path(session_id))
def build_session_last_verified(draft: "DraftDiagram") -> dict | None:
if not any([
draft.last_verified_at,
draft.last_verified_task_id,
draft.last_verified_file_path,
]):
return None
return {
"at": draft.last_verified_at,
"success": draft.last_verified_success,
"task_id": draft.last_verified_task_id,
"file_path": draft.last_verified_file_path,
"file_size_bytes": draft.last_verified_file_size,
"error": draft.last_verified_error,
"origin": draft.last_verified_origin,
}
def hydrate_persistent_state():
ensure_state_dirs()
state.drafts.clear()
state.phase_plans.clear()
state.workflows.clear()
state.draft_to_workflow.clear()
state.validation_jobs.clear()
state.validation_tasks.clear()
for payload in load_json_records(DRAFT_STATE_DIR):
session_id = payload.get("session_id")
if not session_id:
continue
draft = DraftDiagram.from_persisted_dict(payload)
draft.restored_from_disk = True
state.drafts[session_id] = draft
if draft.phase_plan:
state.phase_plans[session_id] = draft.phase_plan
if draft.workflow_id:
state.draft_to_workflow[session_id] = draft.workflow_id
for payload in load_json_records(WORKFLOW_STATE_DIR):
workflow_id = payload.get("workflow_id")
if not workflow_id:
continue
workflow = WorkflowSession.from_dict(payload)
if workflow.draft_session_id and workflow.draft_session_id not in state.drafts:
workflow.draft_session_id = None
state.workflows[workflow_id] = workflow
for payload in load_json_records(VALIDATION_JOB_STATE_DIR):
job_id = payload.get("job_id")
if not job_id:
continue
job = ValidationJob.from_dict(payload)
if job.status in {"queued", "running"}:
job.status = "failed"
job.finished_at = now_iso()
job.error = "Validation interrupted by server restart."
persist_payload = job.to_dict()
atomic_write_json(get_validation_job_state_path(job_id), persist_payload)
state.validation_jobs[job_id] = job
def create_workflow_session(problem_statement: str) -> WorkflowSession:
workflow_id = str(uuid.uuid4())
timestamp = now_iso()
phases = {
key: WorkflowPhase(key=key, label=WORKFLOW_PHASE_LABELS[key])
for key in WORKFLOW_PHASE_ORDER
}
workflow = WorkflowSession(
workflow_id=workflow_id,
problem_statement=problem_statement.strip(),
created_at=timestamp,
updated_at=timestamp,
current_phase=WORKFLOW_PHASE_ORDER[0],
phases=phases,
)
state.workflows[workflow_id] = workflow
persist_workflow_session(workflow_id)
return workflow
def get_workflow(workflow_id: str) -> WorkflowSession | None:
return state.workflows.get(workflow_id)
def workflow_phase_index(phase_key: str) -> int:
return WORKFLOW_PHASE_ORDER.index(phase_key)
def next_workflow_phase(phase_key: str) -> str | None:
index = workflow_phase_index(phase_key)
if index + 1 >= len(WORKFLOW_PHASE_ORDER):
return None
return WORKFLOW_PHASE_ORDER[index + 1]
def reset_workflow_phase(phase: WorkflowPhase):
phase.status = "pending"
phase.content = ""
phase.artifact_type = "markdown"
phase.submitted_at = None
phase.reviewed_at = None
phase.feedback = ""
phase.last_error = None
def reset_workflow_downstream(workflow: WorkflowSession, phase_key: str):
index = workflow_phase_index(phase_key)
for downstream in WORKFLOW_PHASE_ORDER[index + 1:]:
reset_workflow_phase(workflow.phases[downstream])
if workflow.draft_session_id:
delete_draft_session(workflow.draft_session_id)
workflow.draft_session_id = None
workflow.last_verified = None
def list_workflow_payloads(view: str = "full") -> list[dict]:
return [
workflow.to_dict(view=view)
for workflow in sorted(
state.workflows.values(),
key=lambda item: item.created_at,
reverse=True,
)
]
def submit_workflow_phase(
workflow_id: str,
phase_key: str,
content: str,
artifact_type: str = "markdown",
) -> tuple[dict | None, str | None]:
workflow = get_workflow(workflow_id)
if not workflow:
return None, f"Workflow {workflow_id} not found"
if phase_key not in WORKFLOW_PHASE_ORDER:
return None, f"Invalid phase '{phase_key}'. Valid phases: {', '.join(WORKFLOW_PHASE_ORDER)}"
if not content.strip():
return None, "Phase content cannot be empty"
index = workflow_phase_index(phase_key)
if index > 0:
previous_phase = WORKFLOW_PHASE_ORDER[index - 1]
if workflow.phases[previous_phase].status != "approved":
return None, f"{WORKFLOW_PHASE_LABELS[previous_phase]} must be approved before submitting {WORKFLOW_PHASE_LABELS[phase_key]}."
reset_workflow_downstream(workflow, phase_key)
phase = workflow.phases[phase_key]
phase.content = content.strip()
phase.artifact_type = artifact_type
phase.submitted_at = now_iso()
phase.reviewed_at = None
phase.feedback = ""
phase.last_error = None
phase.status = "awaiting_approval" if phase_key in REVIEWABLE_PHASES else "in_progress"
workflow.current_phase = phase_key
workflow.updated_at = now_iso()
persist_workflow_session(workflow_id)
return workflow.to_dict(), None
def review_workflow_phase(
workflow_id: str,
phase_key: str,
decision: str,
feedback: str = "",
) -> tuple[dict | None, str | None]:
workflow = get_workflow(workflow_id)
if not workflow:
return None, f"Workflow {workflow_id} not found"
if phase_key not in REVIEWABLE_PHASES:
return None, f"Only Phase 1 and Phase 2 can be reviewed. Received '{phase_key}'."
phase = workflow.phases[phase_key]
normalized_decision = decision.strip().lower()
if normalized_decision not in {"approve", "request_changes"}:
return None, "Decision must be either 'approve' or 'request_changes'."
# Idempotent: if phase is already approved and caller sends 'approve', succeed gracefully.
# Guards against race conditions where the server auto-approves before the manual call.
if phase.status == "approved" and normalized_decision == "approve":
return workflow.to_dict(), None
if phase.status != "awaiting_approval":
return None, f"{WORKFLOW_PHASE_LABELS[phase_key]} is not awaiting approval. Current status: {phase.status}."
phase.reviewed_at = now_iso()
phase.feedback = feedback.strip()
phase.last_error = None
if normalized_decision == "approve":
phase.status = "approved"
next_phase = next_workflow_phase(phase_key)
if next_phase:
workflow.current_phase = next_phase
else:
phase.status = "changes_requested"
workflow.current_phase = phase_key
reset_workflow_downstream(workflow, phase_key)
workflow.updated_at = now_iso()
persist_workflow_session(workflow_id)
return workflow.to_dict(), None
# --- Incremental Draft Management ---
class DraftDiagram:
def __init__(self, schema_version="1.1", session_id: str | None = None, created_at: datetime | None = None):
self.session_id = session_id
self.schema_version = schema_version
self.blocks = []
self.links = []
self.created_at = created_at or datetime.now()
self.phase_plan = None
self.workflow_id = None
self.restored_from_disk = False
self.last_verified_at = None
self.last_verified_success = None
self.last_verified_task_id = None
self.last_verified_file_path = None
self.last_verified_file_size = None
self.last_verified_error = None
self.last_verified_origin = None
def add_blocks(self, xml_chunk):
self.blocks.append(xml_chunk)
def add_links(self, xml_chunk):
self.links.append(xml_chunk)
def to_persisted_dict(self) -> dict:
return {
"session_id": self.session_id,
"schema_version": self.schema_version,
"created_at": self.created_at.isoformat(),
"blocks": list(self.blocks),
"links": list(self.links),
"phase_plan": self.phase_plan,
"workflow_id": self.workflow_id,
"restored_from_disk": self.restored_from_disk,
"last_verified": {
"at": self.last_verified_at,
"success": self.last_verified_success,
"task_id": self.last_verified_task_id,
"file_path": self.last_verified_file_path,
"file_size_bytes": self.last_verified_file_size,
"error": self.last_verified_error,
"origin": self.last_verified_origin,
},
}
@classmethod
def from_persisted_dict(cls, payload: dict) -> "DraftDiagram":
created_at_raw = payload.get("created_at")
created_at = datetime.fromisoformat(created_at_raw) if created_at_raw else datetime.now()
draft = cls(
schema_version=payload.get("schema_version", "1.1"),
session_id=payload.get("session_id"),
created_at=created_at,
)
draft.blocks = list(payload.get("blocks", []))
draft.links = list(payload.get("links", []))
draft.phase_plan = payload.get("phase_plan")
draft.workflow_id = payload.get("workflow_id")
draft.restored_from_disk = bool(payload.get("restored_from_disk", True))
last_verified = payload.get("last_verified") or {}
draft.last_verified_at = last_verified.get("at")
draft.last_verified_success = last_verified.get("success")
draft.last_verified_task_id = last_verified.get("task_id")
draft.last_verified_file_path = last_verified.get("file_path")
draft.last_verified_file_size = last_verified.get("file_size_bytes")
draft.last_verified_error = last_verified.get("error")
draft.last_verified_origin = last_verified.get("origin")
return draft
def to_xml(self):
"""Assembles the full Xcos XML from parts compatible with Scilab 2026.0.1."""
# Skeleton boilerplate based on Scilab 2026 empty.xcos
full_xml = f'\n'
full_xml += '
Server is running. Please connect via MCP at /mcp or check /healthz.
" with open(ui_path, "r", encoding="utf-8") as f: return inject_ui_base_href(f.read()) def detect_validation_mode() -> str: explicit = (os.environ.get("XCOS_VALIDATION_MODE") or "").strip().lower() if explicit in VALIDATION_MODES: return explicit if os.environ.get("XCOS_SCILAB_SERVICE_URL", "").strip(): return "remote" if os.environ.get("SCILAB_BIN"): return "subprocess" if os.name != "nt": return "subprocess" return "poll" @dataclass(frozen=True) class RemoteScilabConfig: base_url: str bearer_token: str trusted_upstream_id: str poll_interval_seconds: float poll_timeout_seconds: float request_timeout_seconds: float def get_remote_scilab_config() -> RemoteScilabConfig: trusted_upstream_id = ( os.environ.get("XCOS_SCILAB_TRUSTED_UPSTREAM_ID", REMOTE_SCILAB_DEFAULT_TRUSTED_UPSTREAM_ID) .strip() or REMOTE_SCILAB_DEFAULT_TRUSTED_UPSTREAM_ID ) return RemoteScilabConfig( base_url=os.environ.get("XCOS_SCILAB_SERVICE_URL", "").strip().rstrip("/"), bearer_token=os.environ.get("XCOS_SCILAB_BEARER_TOKEN", "").strip(), trusted_upstream_id=trusted_upstream_id, poll_interval_seconds=parse_float_env( "XCOS_SCILAB_POLL_INTERVAL_SECONDS", REMOTE_SCILAB_DEFAULT_POLL_INTERVAL_SECONDS, minimum=0.2, ), poll_timeout_seconds=parse_float_env( "XCOS_SCILAB_POLL_TIMEOUT_SECONDS", REMOTE_SCILAB_DEFAULT_POLL_TIMEOUT_SECONDS, minimum=5.0, ), request_timeout_seconds=parse_float_env( "XCOS_SCILAB_REQUEST_TIMEOUT_SECONDS", REMOTE_SCILAB_DEFAULT_REQUEST_TIMEOUT_SECONDS, minimum=1.0, ), ) def build_remote_auth_headers(config: RemoteScilabConfig, correlation_id: str) -> dict[str, str]: return { "Accept": "application/json", "Content-Type": "application/json", "Authorization": f"Bearer {config.bearer_token}", "X-From-Service": config.trusted_upstream_id, "X-Correlation-Id": correlation_id, } def extract_remote_error_message(payload: dict | None, fallback: str) -> str: if isinstance(payload, dict): error_payload = payload.get("error") if isinstance(error_payload, dict): code = error_payload.get("code") message = error_payload.get("message") if code and message: return f"{message} [{code}]" if message: return str(message) message = payload.get("message") if message: return str(message) return fallback def _sync_http_json_request( method: str, url: str, *, headers: dict[str, str] | None = None, payload: dict | None = None, timeout_seconds: float = REMOTE_SCILAB_DEFAULT_REQUEST_TIMEOUT_SECONDS, ) -> tuple[int, dict | None]: body = None request_headers = dict(headers or {}) if payload is not None: body = json.dumps(payload).encode("utf-8") request_headers.setdefault("Content-Type", "application/json") request = urllib_request.Request(url=url, data=body, headers=request_headers, method=method.upper()) try: with urllib_request.urlopen(request, timeout=timeout_seconds) as response: raw = response.read() text = raw.decode("utf-8", errors="replace") if raw else "" parsed = None if text: try: parsed = json.loads(text) except json.JSONDecodeError: parsed = {"raw": text} return int(getattr(response, "status", response.getcode())), parsed except urllib_error.HTTPError as exc: raw = exc.read() text = raw.decode("utf-8", errors="replace") if raw else "" parsed = None if text: try: parsed = json.loads(text) except json.JSONDecodeError: parsed = {"raw": text} return int(exc.code), parsed except Exception as exc: raise RuntimeError(f"HTTP request failed for {method.upper()} {url}: {exc}") from exc async def http_json_request( method: str, url: str, *, headers: dict[str, str] | None = None, payload: dict | None = None, timeout_seconds: float = REMOTE_SCILAB_DEFAULT_REQUEST_TIMEOUT_SECONDS, ) -> tuple[int, dict | None]: return await asyncio.to_thread( _sync_http_json_request, method, url, headers=headers, payload=payload, timeout_seconds=timeout_seconds, ) async def check_remote_scilab_service_health() -> dict: config = get_remote_scilab_config() if not config.base_url: return { "ok": False, "error": "XCOS_SCILAB_SERVICE_URL is not configured.", "url": None, } health_url = f"{config.base_url}/healthz" try: status_code, payload = await http_json_request( "GET", health_url, timeout_seconds=config.request_timeout_seconds, ) except Exception as exc: return { "ok": False, "error": f"Remote Scilab health check failed: {exc}", "url": health_url, } if status_code >= 400: return { "ok": False, "error": extract_remote_error_message(payload, f"Remote Scilab health check HTTP {status_code}."), "url": health_url, "status_code": status_code, "payload": payload, } return { "ok": True, "url": health_url, "status_code": status_code, "payload": payload if isinstance(payload, dict) else None, } def resolve_windows_scilab_from_registry_file() -> str | None: path_file = os.path.join(BASE_DIR, ".scilab_path") if not os.path.exists(path_file): return None with open(path_file, "r", encoding="utf-8") as f: raw_root = f.read().strip() root = os.path.abspath(os.path.join(BASE_DIR, raw_root)) candidates = [ os.path.join(root, "bin", "WScilex-cli.exe"), os.path.join(root, "bin", "scilab-cli.exe"), os.path.join(root, "bin", "scilab-cli"), os.path.join(root, "bin", "scilab.bat"), ] for candidate in candidates: if os.path.exists(candidate): return candidate return None _scilab_bin_cache = None _scilab_gui_bin_cache = None def resolve_scilab_binary() -> str | None: global _scilab_bin_cache if _scilab_bin_cache is not None: return _scilab_bin_cache env_bin = os.environ.get("SCILAB_BIN") if env_bin: return env_bin if os.name == "nt": from_registry = resolve_windows_scilab_from_registry_file() if from_registry: return from_registry # Search for the full GUI binary first ("scilab") because xcosDiagramToScilab # requires Java GUI packages which are stripped from "scilab-cli" / "scilab-adv-cli". for command in ("scilab", "scilab-adv-cli", "scilab-cli"): resolved = shutil.which(command) if resolved: _scilab_bin_cache = resolved return resolved return None def resolve_scilab_gui_binary() -> str | None: global _scilab_gui_bin_cache if _scilab_gui_bin_cache is not None: return _scilab_gui_bin_cache env_gui_bin = os.environ.get("SCILAB_GUI_BIN") if env_gui_bin: _scilab_gui_bin_cache = env_gui_bin return env_gui_bin env_bin = os.environ.get("SCILAB_BIN") if env_bin: env_dir = os.path.dirname(env_bin) gui_name = "scilab.exe" if os.name == "nt" else "scilab" sibling_gui = os.path.join(env_dir, gui_name) if os.path.exists(sibling_gui): _scilab_gui_bin_cache = sibling_gui return sibling_gui if os.name == "nt": from_registry = resolve_windows_scilab_from_registry_file() if from_registry: env_dir = os.path.dirname(from_registry) sibling_gui = os.path.join(env_dir, "scilab.exe") if os.path.exists(sibling_gui): _scilab_gui_bin_cache = sibling_gui return sibling_gui resolved = shutil.which("scilab") if resolved: _scilab_gui_bin_cache = resolved return resolved return None def scilab_string_literal(path: str) -> str: return path.replace("\\", "/").replace('"', '""') def poll_worker_is_active(max_idle_seconds: float = POLL_WORKER_IDLE_SECONDS) -> bool: if not state.last_poll_time: return False return (datetime.now() - state.last_poll_time).total_seconds() < max_idle_seconds def read_text_tail(path: str | None, max_chars: int = 4000) -> str | None: if not path or not os.path.exists(path): return None try: with open(path, "r", encoding="utf-8", errors="replace") as f: text = f.read() return text[-max_chars:] except Exception: return None def build_poll_worker_launcher_script() -> str: script_path = os.path.join(TEMP_OUTPUT_DIR, f"poll_worker_{SERVER_PORT}.sce") poll_loop_path = scilab_string_literal(os.path.join(DATA_DIR, "xcosai_poll_loop.sci")) script = textwrap.dedent( f""" mode(-1); lines(0); global XCOSAI_SERVER_PORT; XCOSAI_SERVER_PORT = {SERVER_PORT}; exec("{poll_loop_path}", -1); xcosai_poll_loop(); """ ).strip() + "\n" with open(script_path, "w", encoding="utf-8") as f: f.write(script) return os.path.abspath(script_path) async def stop_poll_worker(): async with state.poll_worker_lock: proc = state.poll_worker_process if proc and proc.returncode is None: try: proc.kill() except ProcessLookupError: pass except Exception: pass try: await asyncio.wait_for(proc.wait(), timeout=10.0) except Exception: pass state.poll_worker_process = None if state.poll_worker_log_handle: try: state.poll_worker_log_handle.close() except Exception: pass state.poll_worker_log_handle = None async def ensure_poll_worker_running() -> dict: async with state.poll_worker_lock: proc = state.poll_worker_process if proc and proc.returncode is None: existing_worker = { "pid": proc.pid, "log_path": state.poll_worker_log_path, "script_path": state.poll_worker_script_path, } else: existing_worker = None if state.poll_worker_log_handle: try: state.poll_worker_log_handle.close() except Exception: pass state.poll_worker_log_handle = None scilab_gui_bin = resolve_scilab_gui_binary() if not scilab_gui_bin: return { "active": False, "error": "Scilab GUI binary not found for poll fallback.", } launcher_script_path = build_poll_worker_launcher_script() log_path = os.path.join(TEMP_OUTPUT_DIR, f"poll_worker_{SERVER_PORT}.log") log_handle = open(log_path, "ab") scilab_args = ["-nb", "-f", launcher_script_path] if os.name != "nt" and shutil.which("xvfb-run"): cmd = ["xvfb-run", "-a", scilab_gui_bin] + scilab_args else: cmd = [scilab_gui_bin] + scilab_args try: proc = await asyncio.create_subprocess_exec( *cmd, stdout=log_handle, stderr=log_handle, env={**os.environ, "HOME": os.environ.get("HOME", "/tmp")}, ) except Exception as exc: log_handle.close() return { "active": False, "error": f"Failed to launch Scilab poll worker: {exc}", "log_path": log_path, "script_path": launcher_script_path, } state.poll_worker_process = proc state.poll_worker_log_handle = log_handle state.poll_worker_log_path = os.path.abspath(log_path) state.poll_worker_script_path = launcher_script_path existing_worker = { "pid": proc.pid, "log_path": log_path, "script_path": launcher_script_path, } deadline = asyncio.get_running_loop().time() + POLL_WORKER_STARTUP_TIMEOUT_SECONDS while asyncio.get_running_loop().time() < deadline: if poll_worker_is_active(): return { "active": True, "pid": state.poll_worker_process.pid if state.poll_worker_process else None, "log_path": state.poll_worker_log_path, "script_path": state.poll_worker_script_path, } proc = state.poll_worker_process if not proc or proc.returncode is not None: break await asyncio.sleep(1.0) proc = state.poll_worker_process return { "active": False, "pid": proc.pid if proc else None, "returncode": proc.returncode if proc else None, "log_path": state.poll_worker_log_path, "script_path": state.poll_worker_script_path, "log_tail": read_text_tail(state.poll_worker_log_path), "error": "Scilab poll worker did not become active within the startup timeout.", "existing_worker": existing_worker, } def build_headless_verification_script(xcos_path: str) -> str: escaped_xcos_path = scilab_string_literal(os.path.abspath(xcos_path)) return textwrap.dedent( f""" mode(-1); lines(0); function block=xcosai_nop_sim(block, flag) endfunction function xcosai_fail(msg) mprintf("XCOSAI_VERIFY_ERROR:%s\\n", string(msg)); exit(1); endfunction try loadXcosLibs(); loadScicos(); mprintf("XCOSAI_VERIFY_INPUT_PATH:%s\\n", "{escaped_xcos_path}"); try xcosai_file_info = fileinfo("{escaped_xcos_path}"); mprintf("XCOSAI_VERIFY_FILEINFO:%s\\n", sci2exp(xcosai_file_info)); catch [xcosai_fileinfo_error, xcosai_fileinfo_id] = lasterror(); mprintf("XCOSAI_VERIFY_FILEINFO_ERROR:%s\\n", string(xcosai_fileinfo_error)); end try xcosai_lines = mgetl("{escaped_xcos_path}"); mprintf("XCOSAI_VERIFY_TEXT_LINE_COUNT:%d\\n", size(xcosai_lines, "*")); if size(xcosai_lines, "*") > 0 then mprintf("XCOSAI_VERIFY_TEXT_LAST_LINE:%s\\n", xcosai_lines($)); end catch [xcosai_text_error, xcosai_text_id] = lasterror(); mprintf("XCOSAI_VERIFY_TEXT_READ_ERROR:%s\\n", string(xcosai_text_error)); end importXcosDiagram("{escaped_xcos_path}"); scs_m.props.tf = 0.1; n_objs = length(scs_m.objs); n_blocks_found = 0; replaced_list = ""; for i = 1:n_objs try if typeof(scs_m.objs(i)) == "Block" then n_blocks_found = n_blocks_found + 1; if scs_m.objs(i).model.sim(2) == 5 then gui_name = scs_m.objs(i).gui; scs_m.objs(i).model.sim(1) = "xcosai_nop_sim"; if replaced_list == "" then replaced_list = gui_name; elseif isempty(strindex(replaced_list, gui_name)) then replaced_list = replaced_list + ", " + gui_name; end end end catch end end if n_blocks_found == 0 then xcosai_fail("Empty diagram after importXcosDiagram; Scilab found no Block objects."); end if replaced_list <> "" then mprintf("XCOSAI_VERIFY_WARN:Graphical blocks substituted for headless validation: %s\\n", replaced_list); end scicos_simulate(scs_m, list(), "nw"); mprintf("XCOSAI_VERIFY_OK\\n"); exit(0); catch [catch_msg, catch_id] = lasterror(); xcosai_fail(catch_msg); end """ ).strip() + "\n" IGNORABLE_SCILAB_LOG_SNIPPETS = ( "Gtk-WARNING:", "Locale not supported by C library. Using the fallback 'C' locale.", "Using the fallback 'C' locale.", ) SCILAB_VERIFICATION_INFO_PREFIXES = ( "XCOSAI_VERIFY_INPUT_PATH:", "XCOSAI_VERIFY_FILEINFO:", "XCOSAI_VERIFY_FILEINFO_ERROR:", "XCOSAI_VERIFY_TEXT_LINE_COUNT:", "XCOSAI_VERIFY_TEXT_LAST_LINE:", "XCOSAI_VERIFY_TEXT_READ_ERROR:", ) def is_ignorable_scilab_log_line(line: str) -> bool: stripped = (line or "").strip() if not stripped: return True return any(snippet in stripped for snippet in IGNORABLE_SCILAB_LOG_SNIPPETS) def analyze_scilab_verification_output(scilab_log: str, returncode: int) -> dict: warnings: list[str] = [] info_lines: list[str] = [] unexpected_lines: list[str] = [] explicit_error: str | None = None found_ok = False for raw_line in (scilab_log or "").splitlines(): line = raw_line.strip() if is_ignorable_scilab_log_line(line): continue if line == "XCOSAI_VERIFY_OK": found_ok = True continue if line.startswith("XCOSAI_VERIFY_WARN:"): warning = line[len("XCOSAI_VERIFY_WARN:"):].strip() if warning and warning not in warnings: warnings.append(warning) continue if line.startswith("XCOSAI_VERIFY_ERROR:"): explicit_error = line[len("XCOSAI_VERIFY_ERROR:"):].strip() continue if line.startswith(SCILAB_VERIFICATION_INFO_PREFIXES): info_lines.append(line) continue unexpected_lines.append(line) if found_ok and returncode == 0: return {"success": True, "warnings": warnings if warnings else None} if returncode == 0 and explicit_error is None and not unexpected_lines: return {"success": True, "warnings": warnings if warnings else None} error = explicit_error or f"Scilab exited with code {returncode}." tail_source = unexpected_lines or info_lines if tail_source and explicit_error is None: tail_err = "\n".join(tail_source[-15:]) error += f"\n\n--- Last 15 lines of Scilab output ---\n{tail_err}\n---------------------------------------" return { "success": False, "error": error, "warnings": warnings if warnings else None, } def build_remote_job_error_message(job_status: str, job_payload: dict) -> str: diagnostics = job_payload.get("diagnostics") message = str(job_payload.get("message") or "").strip() reason = None code = None if isinstance(diagnostics, dict): code = diagnostics.get("error_code") reason = diagnostics.get("reason") or diagnostics.get("message") nested_error = diagnostics.get("error") if not reason and isinstance(nested_error, dict): reason = nested_error.get("message") fallback = { "error": "Remote Scilab service reported a validation failure.", "timeout": "Remote Scilab service timed out while validating.", "cancelled": "Remote Scilab service cancelled the validation job.", }.get(job_status, f"Remote Scilab job ended with status '{job_status or 'unknown'}'.") parts: list[str] = [] if message: parts.append(message) if reason: reason_text = str(reason) if reason_text not in parts: parts.append(reason_text) error_message = " ".join(parts).strip() or fallback if code: error_message = f"{error_message} [{code}]" return error_message async def cancel_remote_scilab_job( config: RemoteScilabConfig, job_id: str, headers: dict[str, str], ) -> None: if not config.base_url or not job_id: return try: await http_json_request( "POST", f"{config.base_url}/cancel/{job_id}", headers=headers, timeout_seconds=config.request_timeout_seconds, ) except Exception: return def build_remote_terminal_result( *, config: RemoteScilabConfig, request_id: str, job_payload: dict, auto_fixed: bool, ) -> dict: job_id = str(job_payload.get("job_id") or "").strip() job_status = str(job_payload.get("status") or "").strip().lower() diagnostics = job_payload.get("diagnostics") if isinstance(job_payload.get("diagnostics"), dict) else None base_payload = { "origin": "scilab-remote-service", "validator_mode": "remote", "auto_fixed_mux_to_scalar": auto_fixed, "task_id": job_id, "remote_job_id": job_id, "remote_request_id": request_id, "remote_status": job_status, "remote_service_url": config.base_url, "remote_diagnostics": diagnostics, } if job_status == "success": warnings = None if diagnostics and isinstance(diagnostics.get("warnings"), list): warnings = diagnostics.get("warnings") return { **base_payload, "success": True, "warnings": warnings, } return { **base_payload, "success": False, "error": build_remote_job_error_message(job_status, job_payload), } async def run_remote_scilab_validation(xml_content: str, auto_fixed: bool) -> dict: config = get_remote_scilab_config() if not config.base_url: return { "success": False, "origin": "scilab-remote-service", "validator_mode": "remote", "auto_fixed_mux_to_scalar": auto_fixed, "error": ( "Remote validation mode is enabled but XCOS_SCILAB_SERVICE_URL is not configured." ), } if (not config.bearer_token) or config.bearer_token.startswith("CHANGE_ME"): return { "success": False, "origin": "scilab-remote-service", "validator_mode": "remote", "auto_fixed_mux_to_scalar": auto_fixed, "error": ( "Remote validation mode requires XCOS_SCILAB_BEARER_TOKEN to be set to a real secret." ), } request_id = str(uuid.uuid4()) headers = build_remote_auth_headers(config, request_id) submit_payload = { "workflow_id": "mcp-remote-validation", "request_id": request_id, "diagram_xml": xml_content, "timeout_seconds": int(max(5.0, round(config.poll_timeout_seconds))), "simulated_duration_seconds": 0.0, "metadata": { "source": "xcos-mcp-server", "validation_mode": "remote", }, } submit_url = f"{config.base_url}/validate" try: submit_status, submit_result = await http_json_request( "POST", submit_url, headers=headers, payload=submit_payload, timeout_seconds=config.request_timeout_seconds, ) except Exception as exc: return { "success": False, "origin": "scilab-remote-service", "validator_mode": "remote", "auto_fixed_mux_to_scalar": auto_fixed, "error": f"Failed to submit validation to remote Scilab service: {exc}", "remote_service_url": config.base_url, "remote_request_id": request_id, } if submit_status >= 400: return { "success": False, "origin": "scilab-remote-service", "validator_mode": "remote", "auto_fixed_mux_to_scalar": auto_fixed, "error": extract_remote_error_message( submit_result, f"Remote Scilab service rejected validation request with HTTP {submit_status}.", ), "remote_service_url": config.base_url, "remote_request_id": request_id, } if not isinstance(submit_result, dict): return { "success": False, "origin": "scilab-remote-service", "validator_mode": "remote", "auto_fixed_mux_to_scalar": auto_fixed, "error": "Remote Scilab service returned an invalid response to /validate.", "remote_service_url": config.base_url, "remote_request_id": request_id, } job_id = str(submit_result.get("job_id") or "").strip() if not job_id: return { "success": False, "origin": "scilab-remote-service", "validator_mode": "remote", "auto_fixed_mux_to_scalar": auto_fixed, "error": "Remote Scilab service did not return a job_id.", "remote_service_url": config.base_url, "remote_request_id": request_id, "remote_submit_response": submit_result, } poll_url = f"{config.base_url}/jobs/{job_id}" terminal_statuses = {"success", "error", "timeout", "cancelled"} loop = asyncio.get_running_loop() deadline = loop.time() + config.poll_timeout_seconds last_status = "queued" last_poll_error = None while loop.time() < deadline: try: poll_status_code, poll_payload = await http_json_request( "GET", poll_url, headers=headers, timeout_seconds=config.request_timeout_seconds, ) except Exception as exc: last_poll_error = str(exc) await asyncio.sleep(config.poll_interval_seconds) continue if poll_status_code >= 400: return { "success": False, "origin": "scilab-remote-service", "validator_mode": "remote", "auto_fixed_mux_to_scalar": auto_fixed, "task_id": job_id, "remote_job_id": job_id, "remote_request_id": request_id, "remote_service_url": config.base_url, "error": extract_remote_error_message( poll_payload, f"Remote Scilab service job polling failed with HTTP {poll_status_code}.", ), } if not isinstance(poll_payload, dict): return { "success": False, "origin": "scilab-remote-service", "validator_mode": "remote", "auto_fixed_mux_to_scalar": auto_fixed, "task_id": job_id, "remote_job_id": job_id, "remote_request_id": request_id, "remote_service_url": config.base_url, "error": "Remote Scilab service returned malformed job status payload.", } current_status = str(poll_payload.get("status") or "").strip().lower() if current_status in {"queued", "running"}: last_status = current_status await asyncio.sleep(config.poll_interval_seconds) continue if current_status in terminal_statuses: return build_remote_terminal_result( config=config, request_id=request_id, job_payload=poll_payload, auto_fixed=auto_fixed, ) return { "success": False, "origin": "scilab-remote-service", "validator_mode": "remote", "auto_fixed_mux_to_scalar": auto_fixed, "task_id": job_id, "remote_job_id": job_id, "remote_request_id": request_id, "remote_service_url": config.base_url, "error": f"Remote Scilab service returned unknown job status '{current_status or 'empty'}'.", } await cancel_remote_scilab_job(config, job_id, headers) timeout_message = ( f"Remote Scilab validation timed out after {config.poll_timeout_seconds:.0f} seconds. " f"Last known remote status: {last_status}." ) if last_poll_error: timeout_message += f" Last poll error: {last_poll_error}" return { "success": False, "origin": "scilab-remote-service", "validator_mode": "remote", "auto_fixed_mux_to_scalar": auto_fixed, "task_id": job_id, "remote_job_id": job_id, "remote_request_id": request_id, "remote_service_url": config.base_url, "remote_status": last_status, "error": timeout_message, } async def run_headless_scilab_validation(xml_content: str, auto_fixed: bool) -> dict: """Runs a real Scilab compilation headlessly (subprocess mode). Uses xvfb-run on Linux so that the GUI subsystem is satisfied without a physical display. Falls back to running scilab-adv-cli directly when xvfb-run is not available (e.g. during local Windows testing with SCILAB_BIN set explicitly). Timeout: 90 seconds. Full Scilab stdout/stderr is captured and returned on failure so the caller can debug without re-running manually. """ scilab_bin = resolve_scilab_binary() memory_diag = build_xml_text_diagnostics(xml_content) if not scilab_bin: return { "success": False, "origin": "scilab-subprocess", "error": "Scilab binary not found. Set SCILAB_BIN or install scilab-cli in the runtime image.", "auto_fixed_mux_to_scalar": auto_fixed, "scilab_log": None, "xml_diagnostics": { "memory": memory_diag, "disk": None, "verification_script_path": None, }, } task_id = str(uuid.uuid4()) temp_path = os.path.join(TEMP_OUTPUT_DIR, f"{task_id}.xcos") with open(temp_path, "w", encoding="utf-8") as f: f.write(xml_content) temp_meta = get_file_metadata(temp_path) disk_diag = build_xml_file_diagnostics(temp_path) disk_diag["matches_memory_sha256"] = disk_diag.get("sha256") == memory_diag.get("sha256") disk_diag["matches_memory_byte_length"] = disk_diag.get("byte_length") == memory_diag.get("byte_length") verify_script_path = os.path.join(TEMP_OUTPUT_DIR, f"{task_id}.sce") with open(verify_script_path, "w", encoding="utf-8") as f: f.write(build_headless_verification_script(temp_path)) xml_diagnostics = { "memory": memory_diag, "disk": disk_diag, "verification_script_path": os.path.abspath(verify_script_path), } # Flags depend on which Scilab binary is available: # - scilab-adv-cli / scilab-cli : already headless, no -nw/-nb supported # - scilab (GUI) : needs to load GUI for xcosDiagramToScilab, so NO -nw bin_name = os.path.basename(scilab_bin).lower() is_cli_binary = any(k in bin_name for k in ("adv-cli", "scilab-cli", "-cli")) if is_cli_binary: scilab_args = ["-f", verify_script_path] else: # We only pass -nb (no banner). -nw disables Java GUI, which breaks importXcosDiagram. scilab_args = ["-nb", "-f", verify_script_path] # On Linux, wrap with xvfb-run so the Java/Swing GUI init doesn't fail if os.name != "nt" and shutil.which("xvfb-run"): cmd = ["xvfb-run", "-a", scilab_bin] + scilab_args else: cmd = [scilab_bin] + scilab_args try: proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, env={ **os.environ, "HOME": os.environ.get("HOME", "/tmp"), "LC_ALL": "C", "LANG": "C", "LANGUAGE": "C", }, ) try: stdout_bytes, _ = await asyncio.wait_for(proc.communicate(), timeout=90.0) except asyncio.TimeoutError: try: proc.kill() except Exception: pass return { "success": False, "origin": "scilab-subprocess", "error": "Scilab headless validation timed out after 90 seconds.", "auto_fixed_mux_to_scalar": auto_fixed, "scilab_log": None, "file_path": temp_meta["path"], "file_size_bytes": temp_meta["size_bytes"], "xml_diagnostics": xml_diagnostics, } scilab_log = stdout_bytes.decode("utf-8", errors="replace").strip() returncode = proc.returncode log_analysis = analyze_scilab_verification_output(scilab_log, returncode) if log_analysis["success"]: return { "success": True, "origin": "scilab-subprocess", "warnings": log_analysis.get("warnings"), "auto_fixed_mux_to_scalar": auto_fixed, "scilab_log": scilab_log, "file_path": temp_meta["path"], "file_size_bytes": temp_meta["size_bytes"], "xml_diagnostics": xml_diagnostics, } return { "success": False, "origin": "scilab-subprocess", "error": log_analysis["error"], "auto_fixed_mux_to_scalar": auto_fixed, "warnings": log_analysis.get("warnings"), "scilab_log": scilab_log, "file_path": temp_meta["path"], "file_size_bytes": temp_meta["size_bytes"], "xml_diagnostics": xml_diagnostics, "hint": ( "Full Scilab output is available in 'scilab_log'. " "Common causes: unsupported block GUI in headless mode, " "parameter size mismatches, or missing SplitBlocks." ), } except Exception as exc: return { "success": False, "origin": "scilab-subprocess", "error": f"Failed to launch Scilab subprocess: {exc}", "auto_fixed_mux_to_scalar": auto_fixed, "scilab_log": None, "xml_diagnostics": xml_diagnostics if "xml_diagnostics" in locals() else { "memory": memory_diag, "disk": None, "verification_script_path": None, }, } def should_retry_with_poll_fallback(scilab_result: dict) -> bool: error_text = "\n".join([ str(scilab_result.get("error") or ""), str(scilab_result.get("scilab_log") or ""), ]) lowered = error_text.lower() return ( not scilab_result.get("success") and ("premature end of file" in lowered or "fatal error" in lowered) ) async def run_poll_validation(xml_content: str, auto_fixed: bool) -> dict: worker_state = await ensure_poll_worker_running() if not worker_state.get("active"): return { "success": False, "origin": "scilab-poll-fallback", "error": worker_state.get("error", "Scilab poll worker is unavailable."), "auto_fixed_mux_to_scalar": auto_fixed, "poll_worker": worker_state, } task_id = str(uuid.uuid4()) temp_path = os.path.join(TEMP_OUTPUT_DIR, f"{task_id}.xcos") with open(temp_path, "w", encoding="utf-8") as f: f.write(xml_content) temp_meta = get_file_metadata(temp_path) event = asyncio.Event() state.results[task_id] = {"success": False, "error": "", "details": {}, "event": event} await state.task_queue.put({"task_id": task_id, "zcos_path": temp_path}) try: await asyncio.wait_for(event.wait(), timeout=120.0) res = state.results.pop(task_id) result_payload = { "success": res["success"], "task_id": task_id, "file_path": temp_meta["path"], "file_size_bytes": temp_meta["size_bytes"], "auto_fixed_mux_to_scalar": auto_fixed, "validator_mode": "poll", "origin": "scilab-poll-fallback", "poll_worker": worker_state, } details = res.get("details") or {} result_payload.update(details) if res["success"]: result_payload["scilab_verdict"] = "Scilab import and simulation passed via long-lived poll worker." else: result_payload["scilab_verdict"] = "Scilab poll fallback reported a validation failure." if not res["success"]: result_payload["error"] = res["error"] result_payload["hint"] = "Use xcos_get_draft_xml(session_id) to inspect the final XML. Scilab errors often relate to parameter size mismatches or missing SplitBlocks." return result_payload except asyncio.TimeoutError: state.results.pop(task_id, None) return { "success": False, "task_id": task_id, "file_path": temp_meta["path"], "file_size_bytes": temp_meta["size_bytes"], "error": f"Scilab verification timed out for {task_id}", "origin": "scilab-poll-fallback", "poll_worker": worker_state, } def validate_diagram_structure(tree: etree._Element, auto_fixed: bool) -> dict: """Performs structural audit of Xcos XML without needing Scilab.""" errors = [] warnings = [] # All IDs in diagram all_id_nodes = tree.xpath("//*[@id]") all_ids = {n.get("id") for n in all_id_nodes} # Blocks and their ports blocks = tree.xpath(XCOS_BLOCK_XPATH) block_ids = {b.get("id") for b in blocks} ports = tree.xpath(".//*[contains(local-name(), 'Port')]") port_ids = {p.get("id") for p in ports} # 1. Check Links links = tree.xpath(XCOS_LINK_XPATH) for l in links: lid = l.get("id", "unknown") src_id = l.get("source") or l.xpath("string(./*[@as='source']/@reference)") dst_id = l.get("target") or l.xpath("string(./*[@as='target']/@reference)") if not src_id: errors.append(f"Link {lid}: Missing source endpoint.") elif src_id not in all_ids: errors.append(f"Link {lid}: Source endpoint {src_id} does not exist.") elif src_id not in port_ids and src_id not in block_ids: warnings.append(f"Link {lid}: Source {src_id} exists but is not a port or block.") if not dst_id: errors.append(f"Link {lid}: Missing target endpoint.") elif dst_id not in all_ids: errors.append(f"Link {lid}: Target endpoint {dst_id} does not exist.") # 2. Check for missing SplitBlocks (Fan-out) # If a port is used as source in multiple links, it must be a SplitBlock or have a SplitBlock edge_sources = [] for l in links: sid = l.get("source") or l.xpath("string(./*[@as='source']/@reference)") if sid: edge_sources.append(sid) from collections import Counter counts = Counter(edge_sources) for pid, count in counts.items(): if count > 1: # Check if pid belongs to a SplitBlock parent_block = tree.xpath(f"//*[@id='{pid}']/parent::*") if parent_block and parent_block[0].tag != "SplitBlock": errors.append(f"Port {pid} has fan-out {count} but parent is not a SplitBlock. Added a CLKSPLIT_f or SplitBlock.") success = len(errors) == 0 return { "success": success, "origin": "structural-validator", "errors": errors if errors else None, "warnings": warnings, "auto_fixed_mux_to_scalar": auto_fixed, "validator_mode": "structural-python" } # --- MCP Tool Implementations --- async def get_xcos_block_source(name: str): # Recursive search for {name}.sci in ./data/macros/ macros_dir = os.path.join(DATA_DIR, "macros") for root, dirs, files in os.walk(macros_dir): if f"{name}.sci" in files: path = os.path.join(root, f"{name}.sci") with open(path, 'r', encoding='utf-8') as f: return [mcp_types.TextContent(type="text", text=f.read())] return [mcp_types.TextContent(type="text", text=f"Error: Source for '{name}' not found in {macros_dir}")] def build_compact_reference_payload(xml_text: str | None) -> dict | None: if not xml_text: return None try: parser = etree.XMLParser(remove_blank_text=True) tree = etree.fromstring(xml_text.encode("utf-8"), parser) block = tree.xpath(XCOS_BLOCK_XPATH) if not block: return None block_node = block[0] block_id = block_node.get("id") port_nodes = tree.xpath(f"//*[@parent='{block_id}'][contains(local-name(), 'Port')]") compact_nodes = [block_node] + port_nodes fragment = "\n".join( etree.tostring(node, encoding="unicode", pretty_print=True).strip() for node in compact_nodes ) port_ids = [node.get("id") for node in port_nodes if node.get("id")] parameter_fields = [] for child in block_node: child_tag = child.tag if isinstance(child.tag, str) else "" if child_tag in {"mxGeometry"}: continue child_as = child.get("as") if child_as: parameter_fields.append(child_as) return { "template_xml": fragment, "block_id": block_id, "port_ids": port_ids, "parameter_fields": parameter_fields, } except Exception: return None async def get_xcos_block_data( name: str, include_help: bool = False, include_extra_examples: bool = False, include_reference_xml: bool = False, ): """Returns compact block metadata and optional reference XML for an Xcos block.""" data = { "name": name, "info": None, "warnings": [], "has_example": False, "has_help": False, "has_extra_examples": False, "compact_reference": None, "reference_xml": None, } # 1. INFO info_path = os.path.join(DATA_DIR, "blocks", f"{name}.json") if os.path.exists(info_path): with open(info_path, 'r', encoding='utf-8') as f: try: data["info"] = json.loads(f.read()) except json.JSONDecodeError: data["info"] = f.read() else: data["warnings"].append(f"Block info for '{name}' not found at data/blocks/{name}.json") # 2. EXAMPLE example_path = os.path.join(DATA_DIR, "reference_blocks", f"{name}.xcos") example_xml = None if os.path.exists(example_path): data["has_example"] = True with open(example_path, 'r', encoding='utf-8') as f: example_xml = f.read() data["compact_reference"] = build_compact_reference_payload(example_xml) if include_reference_xml: data["reference_xml"] = example_xml else: data["warnings"].append(f"Reference block '{name}' not found at data/reference_blocks/{name}.xcos") if include_extra_examples: data["extra_examples"] = {} extra_example_prefix = f"{name}__" reference_dir = os.path.join(DATA_DIR, "reference_blocks") if os.path.exists(reference_dir): extra_example_files = sorted( file_name for file_name in os.listdir(reference_dir) if file_name.startswith(extra_example_prefix) and file_name.endswith(".xcos") ) for extra_file_name in extra_example_files: label = os.path.splitext(extra_file_name)[0].split("__", 1)[1].replace("_", " ") extra_path = os.path.join(reference_dir, extra_file_name) with open(extra_path, "r", encoding="utf-8") as f: data["extra_examples"][label] = f.read() data["has_extra_examples"] = bool(data["extra_examples"]) # 3. HELP help_file = None search_dir = os.path.join(DATA_DIR, "help") if os.path.exists(search_dir): for root, dirs, files in os.walk(search_dir): if f"{name}.xml" in files: help_file = os.path.join(root, f"{name}.xml") break data["has_help"] = bool(help_file) if include_help: data["help"] = None if not help_file: data["warnings"].append(f"Help file for '{name}' not found. Attempting to extract from MACRO source...") macros_dir = os.path.join(DATA_DIR, "macros") sci_path = None if os.path.exists(macros_dir): for root, dirs, files in os.walk(macros_dir): if f"{name}.sci" in files: sci_path = os.path.join(root, f"{name}.sci") break if sci_path: try: with open(sci_path, 'r', encoding='utf-8') as f: lines = f.readlines() preview = "".join(lines[:100]) data["help"] = f"--- AUTO-EXTRACTED FROM {name}.sci (First 100 lines) ---\n{preview}\n..." except Exception as e: data["warnings"].append(f"Could not read macro file: {str(e)}") else: data["warnings"].append(f"Macro source for '{name}' not found either.") else: try: parser = etree.XMLParser(remove_blank_text=True) tree = etree.parse(help_file, parser) sections = tree.xpath("//*[local-name()='refsection']") extracted_text = [] for section in sections: sec_id = section.get("{http://www.w3.org/XML/1998/namespace}id") or section.get("id") if sec_id and (sec_id.startswith("Dialogbox_") or sec_id.startswith("Defaultproperties_")): title = section.xpath("string(.)").strip() extracted_text.append(f"--- Section: {sec_id} ---\n{title}") if not extracted_text: data["warnings"].append(f"No parameter sections found in {os.path.basename(help_file)}") else: data["help"] = "\n\n".join(extracted_text) except Exception as e: data["warnings"].append(f"Error parsing help XML: {str(e)}") return make_json_response(data) async def search_related_xcos_files(query: str): results = [] for root, dirs, files in os.walk(DATA_DIR): for file in files: if query.lower() in file.lower(): results.append(os.path.join(root, file)) if not results: return make_text_response(f"No files matching '{query}' found in {DATA_DIR}") return make_text_response("\n".join(results)) async def run_verification(xml_content: str): # --- Integration of Auto-fix and Validator --- try: parser = etree.XMLParser(remove_blank_text=True) tree = etree.fromstring(xml_content.encode('utf-8'), parser) # 1. Auto-fix auto_fixed = auto_fix_mux_to_scalar(tree) if auto_fixed: xml_content = etree.tostring(tree, encoding='unicode', pretty_print=True) # 2. Pre-simulation Validation val_errors = validate_port_sizes(tree) if val_errors: return { "success": False, "origin": "pre-sim-validator", "errors": val_errors, "auto_fixed_mux_to_scalar": auto_fixed, } except Exception as e: return { "success": False, "origin": "pre-sim-validator", "error": f"Error during pre-validation: {str(e)}", } validation_mode = detect_validation_mode() if validation_mode in {"subprocess", "remote"}: # Stage 1 — fast Python structural audit (catches broken IDs, fan-outs, etc.) python_result = validate_diagram_structure(tree, auto_fixed) if not python_result["success"]: # Fail immediately - no point spawning Scilab if the XML is broken. return python_result if validation_mode == "subprocess": # Stage 2 — deep Scilab compilation check (catches parameter mismatches, # missing functions, simulation-time type errors, etc.) scilab_result = await run_headless_scilab_validation(xml_content, auto_fixed) poll_fallback_result = None if should_retry_with_poll_fallback(scilab_result): poll_fallback_result = await run_poll_validation(xml_content, auto_fixed) if poll_fallback_result.get("success"): merged_warnings = (python_result.get("warnings") or []) + (poll_fallback_result.get("warnings") or []) return { **poll_fallback_result, "fallback_used": True, "fallback_reason": "Subprocess validator reported premature EOF; retried with long-lived Scilab poll worker.", "subprocess_result": scilab_result, "structural_check": { "success": python_result["success"], "warnings": python_result.get("warnings"), }, "warnings": merged_warnings if merged_warnings else None, "origin": "hybrid (structural-python + scilab-subprocess + scilab-poll-fallback)", } # Merge warnings from both stages merged_warnings = (python_result.get("warnings") or []) + (scilab_result.get("warnings") or []) result = { **scilab_result, # Surface both validator results so the caller has full context "structural_check": { "success": python_result["success"], "warnings": python_result.get("warnings"), }, "warnings": merged_warnings if merged_warnings else None, "origin": "hybrid (structural-python + scilab-subprocess)", } if poll_fallback_result: result["fallback_used"] = True result["fallback_reason"] = "Subprocess validator reported premature EOF; poll fallback did not clear the failure." result["poll_fallback_result"] = poll_fallback_result return result if validation_mode == "remote": remote_result = await run_remote_scilab_validation(xml_content, auto_fixed) merged_warnings = (python_result.get("warnings") or []) + (remote_result.get("warnings") or []) return { **remote_result, "structural_check": { "success": python_result["success"], "warnings": python_result.get("warnings"), }, "warnings": merged_warnings if merged_warnings else None, "origin": "hybrid (structural-python + scilab-remote-service)", } return await run_poll_validation(xml_content, auto_fixed) async def verify_xcos_xml(xml_content: str): result = await run_verification(xml_content) remember_validation_result(xml_content, result) return make_json_response(make_public_validation_payload(result)) def _schedule_validation_job(job_id: str): task = asyncio.create_task(_run_validation_job(job_id)) state.validation_tasks[job_id] = task def _cleanup(_: asyncio.Task): state.validation_tasks.pop(job_id, None) task.add_done_callback(_cleanup) return task async def _run_validation_job(job_id: str): job = state.validation_jobs.get(job_id) if not job: return job.status = "running" job.started_at = now_iso() job.error = None persist_validation_job(job_id) session_meta = None try: if job.session_id not in state.drafts: job.status = "failed" job.finished_at = now_iso() job.error = f"Session {job.session_id} not found" persist_validation_job(job_id) return xml_content = state.drafts[job.session_id].to_xml() session_meta = write_session_snapshot(job.session_id) result = await asyncio.wait_for(run_verification(xml_content), timeout=job.timeout_seconds) remember_validation_result(xml_content, result) record_validation_outcome(job.session_id, result, session_meta) job.status = "succeeded" if result.get("success") else "failed" job.finished_at = now_iso() job.result = result job.error = result.get("error") persist_validation_job(job_id) except asyncio.TimeoutError: timeout_result = { "success": False, "task_id": job.job_id, "error": f"Validation timed out after {job.timeout_seconds:.0f} seconds.", "origin": "validation-job", "file_path": session_meta["path"] if session_meta else None, "file_size_bytes": session_meta["size_bytes"] if session_meta else None, } record_validation_outcome(job.session_id, timeout_result, session_meta) job.status = "timed_out" job.finished_at = now_iso() job.result = timeout_result job.error = timeout_result["error"] persist_validation_job(job_id) except Exception as exc: error_result = { "success": False, "task_id": job.job_id, "error": f"Validation job failed: {exc}", "origin": "validation-job", "file_path": session_meta["path"] if session_meta else None, "file_size_bytes": session_meta["size_bytes"] if session_meta else None, } record_validation_outcome(job.session_id, error_result, session_meta) job.status = "failed" job.finished_at = now_iso() job.result = error_result job.error = error_result["error"] persist_validation_job(job_id) async def xcos_start_validation(session_id: str, timeout_seconds: float = DEFAULT_VALIDATION_TIMEOUT_SECONDS): if session_id not in state.drafts: return make_text_response(f"Error: Session {session_id} not found") if timeout_seconds <= 0: return make_text_response("Error: timeout_seconds must be greater than 0") session_meta = write_session_snapshot(session_id) job_id = str(uuid.uuid4()) workflow_id = state.draft_to_workflow.get(session_id) job = ValidationJob( job_id=job_id, session_id=session_id, workflow_id=workflow_id, status="queued", created_at=now_iso(), timeout_seconds=float(timeout_seconds), ) state.validation_jobs[job_id] = job persist_validation_job(job_id) _schedule_validation_job(job_id) payload = make_validation_job_public_payload(job) payload["message"] = f"Validation job {job_id} queued for session {session_id}." payload["session_file_path"] = session_meta["path"] payload["session_file_size_bytes"] = session_meta["size_bytes"] return make_json_response(payload) async def xcos_get_validation_status(job_id: str): job = state.validation_jobs.get(job_id) if not job: return make_text_response(f"Error: Validation job {job_id} not found") return make_json_response(make_validation_job_public_payload(job)) # --- Incremental Tool Implementations --- async def xcos_create_workflow(problem_statement: str): if not problem_statement.strip(): return make_text_response("Error: problem_statement cannot be empty") workflow = create_workflow_session(problem_statement) return make_json_response({ "status": "success", "workflow_id": workflow.workflow_id, "workflow": workflow.to_dict(), "phase_order": WORKFLOW_PHASE_ORDER, "approval_required_phases": [ phase_key for phase_key in WORKFLOW_PHASE_ORDER if phase_key in REVIEWABLE_PHASES ], "phase_start_requirements": { "phase3_implementation": { "tool": "xcos_start_draft", "requires_approved_phases": WORKFLOW_PHASE_ORDER[:2], "message": "Phase 2 must be approved before Phase 3 implementation can start.", } }, "next_required_action": ( f"Submit {WORKFLOW_PHASE_LABELS[workflow.current_phase]} and wait for approval " "before starting implementation." ), }) async def xcos_list_workflows(view: str = "summary"): return make_json_response({"workflows": list_workflow_payloads(view=view)}) async def xcos_get_workflow(workflow_id: str, view: str = "summary"): workflow = get_workflow(workflow_id) if not workflow: return make_text_response(f"Error: Workflow {workflow_id} not found") return make_json_response({"workflow": workflow.to_dict(view=view)}) async def xcos_get_status_widget(): mode = detect_validation_mode() version = "Unknown" connection_status = "Disconnected" remote_service_url = None if mode == "remote": remote_config = get_remote_scilab_config() remote_service_url = remote_config.base_url or None health = await check_remote_scilab_service_health() connection_status = "Connected" if health.get("ok") else "Disconnected" if health.get("ok"): health_payload = health.get("payload") if isinstance(health.get("payload"), dict) else {} service_name = health_payload.get("service", "Remote Scilab service") startup_phase = health_payload.get("startup_phase") queue_depth = health_payload.get("queue_depth") version = f"{service_name} ({startup_phase})" if startup_phase else str(service_name) if queue_depth is not None: version = f"{version} | queue={queue_depth}" else: version = health.get("error") or "Remote Scilab service unavailable" else: scilab_bin = resolve_scilab_binary() polling_active = False if state.last_poll_time and (datetime.now() - state.last_poll_time).total_seconds() < 5: polling_active = True connection_status = "Connected" if (polling_active or mode == "subprocess") else "Disconnected" if scilab_bin: # On Windows, WScilex-cli.exe requires full GUI initialisation and hangs # when spawned as a short-lived subprocess. Read version metadata from # the install directory instead. if os.name == "nt": scilab_root = os.path.dirname(os.path.dirname(os.path.abspath(scilab_bin))) version_incl = os.path.join(scilab_root, "Version.incl") if os.path.exists(version_incl): try: with open(version_incl, "r", encoding="utf-8") as vf: for vline in vf: if "SCIVERSION=" in vline: version = vline.split("=", 1)[1].strip() break except Exception: pass else: # Linux local mode: spawn Scilab with a correctly formatted script. # Statements are separated by real newlines; \n inside mprintf strings # is the two-char Scilab escape that produces a newline in output. import textwrap as _tw status_script = _tw.dedent("""\ mode(-1); lines(0); mprintf("XCOS_STATUS_START\\n"); mprintf("%s\\n", getversion()); mprintf("%s\\n", string(with_module("xcos"))); mprintf("%s\\n", TMPDIR); mprintf("XCOS_STATUS_END\\n"); exit(0); """) task_id = str(uuid.uuid4()) script_path = os.path.join(TEMP_OUTPUT_DIR, f"status_{task_id}.sce") with open(script_path, "w", encoding="utf-8") as f: f.write(status_script) command = [scilab_bin] if shutil.which("xvfb-run"): command = ["xvfb-run", "-a", scilab_bin] lower_bin = scilab_bin.lower() if "scilab-cli" in lower_bin: command.extend(["-nb", "-f", script_path]) else: command.extend(["-nw", "-nb", "-f", script_path]) try: process = await asyncio.create_subprocess_exec( *command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, cwd=BASE_DIR, ) stdout, _ = await asyncio.wait_for(process.communicate(), timeout=20.0) out_str = stdout.decode("utf-8", errors="replace") if "XCOS_STATUS_START" in out_str and "XCOS_STATUS_END" in out_str: raw = out_str.split("XCOS_STATUS_START")[1].split("XCOS_STATUS_END")[0] parts = [p.strip() for p in raw.splitlines() if p.strip()] if parts: version = parts[0] except Exception: try: process.kill() except Exception: pass payload = { "widget_type": "status", "payload": { "scilab_success": connection_status == "Connected", "scilab_output": version, "env_context": mode, "active_drafts": len(state.drafts), "remote_service_url": remote_service_url, } } return make_json_response(payload) async def xcos_get_workflow_widget(workflow_id: str = None): try: if workflow_id: payload = parse_mcp_text_json_response(await xcos_get_workflow(workflow_id)) workflows = [payload["workflow"]] else: payload = parse_mcp_text_json_response(await xcos_list_workflows()) workflows = payload["workflows"] except ValueError as exc: return make_json_response({ "widget_type": "workflow", "payload": { "error": str(exc) } }) phases = [] if workflow_id and workflows: workflow = workflows[0] # Build phases array for frontend for phase_key in WORKFLOW_PHASE_ORDER: phase = workflow["phases"][phase_key] phases.append({ "label": phase["label"], "status": phase["status"], "submitted_at": phase["submitted_at"], "reviewed_at": phase["reviewed_at"], "feedback": getattr(phase, 'feedback', phase.get("feedback", "")) }) return make_json_response({ "widget_type": "workflow", "payload": { "workflow_id": workflow_id or "All", "phases": phases if workflow_id else [], "all_workflows": workflows if not workflow_id else [] } }) async def _legacy_xcos_get_validation_widget(xml_content: str): try: result = await run_verification(xml_content) except Exception as e: result = { "success": False, "error": f"Validator internal error: {str(e)}", "origin": "internal-error", } error_msgs = [] if result.get("auto_fixed_mux_to_scalar"): error_msgs.append("⚠Auto-fixed MUX to scalar connections") if "errors" in result and result["errors"]: for e in result["errors"]: if e["type"] == "REGISTRY_SIZE_MISMATCH": error_msgs.append(f"Block {e.get('blockId')} ({e.get('block')}): expected {e.get('expectedSize')}, got {e.get('actualSize')} on port {e.get('portIndex')}") elif e["type"] == "PORT_SIZE_MISMATCH": error_msgs.append(f"Link {e.get('linkId')}: size mismatch between {e.get('srcBlock')} {e.get('srcSize')} and {e.get('dstBlock')} {e.get('dstSize')}") elif e["type"] == "FANOUT_WITHOUT_SPLIT": error_msgs.append(f"Block {e.get('blockId')}: {e.get('message', 'fanout without SplitBlock')}") else: error_msgs.append(f"{e.get('type')}: {e.get('message', '')}") if result.get("error"): error_msgs.append(str(result["error"])) if result.get("warnings"): for w in result["warnings"]: error_msgs.append(str(w)) return make_json_response({ "widget_type": "validation", "payload": { "success": result.get("success", False), "error": "\n".join(error_msgs) if error_msgs else None } }) async def xcos_get_validation_widget(xml_content: str): result = get_cached_validation_result(xml_content) if result is None: try: result = await run_verification(xml_content) remember_validation_result(xml_content, result) except Exception as e: result = { "success": False, "error": f"Validator internal error: {str(e)}", "origin": "internal-error", } public_result = make_public_validation_payload(result) return make_json_response({ "widget_type": "validation", "payload": { "success": public_result.get("success", False), "error": None if public_result.get("success") else public_result.get("message") } }) async def xcos_get_block_catalogue_widget(category: str = None): index_path = os.path.join(DATA_DIR, "blocks", "_index.json") blocks = [] if os.path.exists(index_path): with open(index_path, "r", encoding="utf-8") as f: try: data = json.load(f) blocks = data.get("block_files", []) except Exception: pass categories = [] if category: categories = [part.strip() for part in category.split(",") if part.strip()] lowered_categories = [part.lower() for part in categories] blocks = [ b for b in blocks if any(cat in b.get("category", "").lower() for cat in lowered_categories) ] formatted_blocks = [] public_base_url = get_public_base_url() for b in blocks: block_name = b.get("name", "") image = resolve_block_image(block_name) formatted_blocks.append({ "name": block_name, "type": b.get("category", ""), "description": b.get("description", ""), "image_candidates": build_block_image_candidate_urls( block_name, base_url=public_base_url, ), "image_data_uri": image.get("src") if image else None, "image_file_name": image.get("file_name") if image else None, }) return make_json_response({ "widget_type": "catalogue", "payload": { "category": category, "categories": categories, "blocks": formatted_blocks } }) def generate_topology_svg(session_id: str) -> tuple[str, int, int]: """Returns (svg_string, block_count, link_count) or raises ValueError""" if session_id not in state.drafts: raise ValueError(f"Session {session_id} not found") draft = state.drafts[session_id] xml_content = draft.to_xml() try: parser = etree.XMLParser(remove_blank_text=True) tree = etree.fromstring(xml_content.encode("utf-8"), parser) except Exception as e: raise ValueError(f"Error parsing XML: {str(e)}") blocks = tree.xpath(XCOS_BLOCK_XPATH) links = tree.xpath(XCOS_LINK_XPATH) block_map = {} for b in blocks: bid = b.get("id") name = b.get("interfaceFunctionName", b.tag) block_map[bid] = {"name": name, "in_ports": [], "out_ports": []} # Build ports_map: map every port id -> {block_id, type} # # In Xcos XML, ports are NOT nested inside their block element — they are # siblings under