Skip to main content

MCP Protocol Specification

Version: 0.1 (Phase 0 — Spec & Design) Status: Draft Last Updated: 2026-03-02 Depends on: architecture.md, twin_schema.md, skill_spec.md Referenced by: roadmap.md, governance.md

1. Overview​

The Model Context Protocol (MCP) layer is the exclusive pathway for tool access in MetaForge. No agent, skill, or other component ever calls an engineering tool directly. All tool invocations pass through the MCP protocol, which provides:

  • Uniform interface: Every tool (KiCad, FreeCAD, CalculiX, SPICE) is accessed through the same JSON-RPC 2.0 protocol.
  • Container isolation: Tools run in Docker containers with strict resource and filesystem controls.
  • Observability: Every tool call is traced, logged, and metered via OpenTelemetry.
  • Health tracking: The tool registry monitors adapter health and routes calls to healthy instances.

Architecture Summary​

Code
Skill (handler.py)
│
▼
MCP Bridge (skill_registry/mcp_bridge.py)
│
▼
MCP Client (mcp_core/client.py)
│
▼
Wire Protocol (JSON-RPC 2.0 over stdio or HTTP)
│
▼
MCP Tool Server (tool adapter, inside Docker)
│
▼
Engineering Tool (KiCad, FreeCAD, CalculiX, SPICE)

2. Client-Server Architecture​

MCP Client​

The MCP Client lives in mcp_core/client.py and manages connections to tool adapter servers.

Python
"""MCP client for tool communication."""

from pydantic import BaseModel
from uuid import UUID, uuid4


class McpClient:
"""
Manages connections to MCP tool servers and dispatches tool calls.

Each tool adapter runs as an MCP server (inside a Docker container).
The client connects via stdio (subprocess) or HTTP, depending on config.
"""

async def connect(self, adapter_id: str) -> None:
"""Establish connection to a tool adapter server."""
...

async def disconnect(self, adapter_id: str) -> None:
"""Close connection to a tool adapter server."""
...

async def call_tool(self, request: "ToolCallRequest") -> "ToolCallResult":
"""
Send a tool/call request and wait for the result.

Handles timeout, retry (if idempotent), and error mapping.
"""
...

async def list_tools(self, adapter_id: str | None = None) -> list["ToolManifest"]:
"""
Discover available tools from one or all connected adapters.
"""
...

async def health_check(self, adapter_id: str) -> "HealthStatus":
"""Check the health of a specific adapter."""
...

MCP Tool Server​

Each tool adapter implements an MCP-compatible server. The server receives JSON-RPC requests, delegates to the underlying tool, and returns structured results.

Python
"""Base class for MCP tool servers (adapters)."""


class McpToolServer:
"""
Base class for tool adapter MCP servers.

Subclass this to create a new tool adapter. Implement:
1. register_tools() — declare available tools.
2. Tool handler methods — one per tool.
"""

def __init__(self, adapter_id: str, version: str) -> None:
self.adapter_id = adapter_id
self.version = version
self._tools: dict[str, "ToolManifest"] = {}

def register_tool(self, manifest: "ToolManifest", handler) -> None:
"""Register a tool with its manifest and handler function."""
self._tools[manifest.tool_id] = manifest
# ... bind handler

async def handle_request(self, raw_message: str) -> str:
"""Parse JSON-RPC request, dispatch to handler, return JSON-RPC response."""
...

async def start_stdio(self) -> None:
"""Start the server in stdio mode (reads stdin, writes stdout)."""
...

async def start_http(self, host: str = "0.0.0.0", port: int = 8080) -> None:
"""Start the server in HTTP mode."""
...

3. Wire Protocol​

MCP uses JSON-RPC 2.0 as the wire protocol. Messages are exchanged over stdio (for local tool containers) or HTTP (for remote tool servers).

Transport Modes​

ModeUse CaseConnection
stdioLocal Docker containers (default)Client spawns container process, communicates via stdin/stdout
HTTPRemote tool servers, shared instancesClient sends POST requests to http://<host>:<port>/rpc

Streamable HTTP on the unified sidecar​

The unified server (python -m metaforge.mcp --transport http) speaks MCP Streamable HTTP at /mcp:

RequestWhat it does
POST /mcp with a JSON-RPC requestdispatches it; the answer is application/json, or 204 for a notification. initialize issues an Mcp-Session-Id the client echoes afterwards
POST /mcp with a JSON-RPC responsethe client answering a request the server sent (elicitation/create), routed by id and acknowledged 202
GET /mcp with Mcp-Session-Ida long-lived SSE stream the server pushes requests down
DELETE /mcp with Mcp-Session-Idends the session

An Mcp-Session-Id this server process did not issue, typically one from before a restart or a deploy, is answered 404 (a JSON-RPC error, -32001, "initialize again"), on POST and on GET /mcp. The client then initialises again and re-declares what it can do; without that, a client carried across a restart was served with nothing known about it and could no longer be prompted for approvals. initialize itself is always served, and a handshake-free (2026-07-28) request, which never initialises, is never refused for its session.

A tools/call that is held for approval can also be answered as text/event-stream on its own POST. This happens only when the session declared form elicitation at initialize on revision 2025-06-18 or later, has no GET /mcp stream open, and sent the call with text/event-stream in Accept. The stream carries the elicitation/create request, then the tool result, then closes. A call that is not held keeps its JSON response, so clients that never open GET /mcp (Claude Code among them) can still be asked inline. Routing rules and outcomes are in Over HTTP: which stream carries the question.

Browser origins​

Every request to /mcp (POST, GET and DELETE) and /mcp/sse has its Origin header checked, as the Streamable HTTP transport requires. A request whose origin is not allowed gets 403 with a JSON-RPC error (-32600, "Origin not allowed", no id), a mcp_origin_rejected log line naming the origin, and a count on metaforge_mcp_origin_rejected_total, which the McpOriginRejected alert watches.

Allowed:

  • requests with no Origin at all. Only browsers send one, so Claude Code, Codex, the design-flow worker and other servers are unaffected;
  • loopback origins (localhost, *.localhost, 127.0.0.0/8, [::1]), any port;
  • https://claude.ai and https://claude.com, for the web connector;
  • this server's public origin, when METAFORGE_OAUTH_ISSUER names it;
  • anything listed in METAFORGE_MCP_ALLOWED_ORIGINS (comma separated, for example https://ui.example.com:8443). * turns the check off and the server logs that at start-up.

The origin is not compared with the Host header. That is the check DNS rebinding defeats: a page re-points its own name at this machine, and its Origin and the request's Host then agree. /health, the OAuth pages and /.well-known/* are not checked.

Redirect URIs​

/authorize accepts only a redirect_uri the client registered. A loopback redirect (http://127.0.0.1, http://[::1] or http://localhost) may use any port, as RFC 8252 section 7.3 asks: a native client such as opencode listens on whichever local port is free, so a later sign-in can use a different port from the one it registered. Scheme, host, path and query must still match, and every other redirect must match exactly.

Signed-in accounts and project scope​

When the OAuth sign-in binds each token to a person (an auth provider that implements PasswordLogin) and that provider also implements ProjectAuthorizer, every tools/call and resources/read from that person is checked against their projects before it runs, the approval hold included (metaforge/mcp/project_scope.py). Each tool has a tenancy: project, entity, account_list, account_create, shared_read, tenant_library, stateless, adapter_workspace or blocked, and a tool with none is refused. A refusal is a JSON-RPC error (-32001) whose data carries tool_id, code and retryable:

codeMeaning
not_founda project or entity outside the account's projects, worded exactly as one that does not exist
project_required / entity_requiredthe tool needs a project (or the id it names) on a shared server
tool_not_scopedthe tool, or one of its arguments, cannot be traced to a project and is refused
library_read_onlythe account cannot add to the library (its scope names no account). A library served by the gateway is no longer refused: the account's view is forwarded with each call
not_signed_ina token not bound to a person, such as one issued before the identity login
scope_unavailablethe provider or an owner lookup could not answer; retryable
registration_failedproject.create could not register the project to the account; nothing was created

Tool calls from a local install, an API key, the shared-secret login or the design-flow service are not affected. The tenancy of every tool and the limits are in Authentication.

Protocol revisions​

The server speaks the handshake revisions 2024-11-05, 2025-06-18 and 2025-11-25, and the handshake-free revision 2026-07-28. initialize echoes the handshake revision a client asks for when it is one of these; a client ahead of us gets 2025-11-25. The lists live in mcp_core/protocol_versions.py.

Revision 2026-07-28 drops the handshake: each request names its revision in params._meta["io.modelcontextprotocol/protocolVersion"] and, over HTTP, in the MCP-Protocol-Version header. The server handles both shapes on the same endpoint:

  • initialize takes the handshake path, exactly as before.
  • A request whose _meta names a revision we speak is served as before.
  • A request whose _meta names any other revision is refused with the spec's UnsupportedProtocolVersionError (-32022, and HTTP 400), whose data.supported lists our revisions newest first.
  • Over HTTP, a MCP-Protocol-Version header that disagrees with the _meta revision is refused with HeaderMismatch (-32020, HTTP 400). A header with no _meta revision (a 2025-06-18 client) is not a mismatch.

2026-07-28 is served by default. METAFORGE_MCP_MODERN=off on the sidecar stops serving it (a rollback switch); a client asking for it then gets the error above and a dual-era client falls back to the handshake. The preview switch, METAFORGE_MCP_MODERN_PREVIEW, no longer changes anything.

A 2026-07-28 request is served on its own, without a session:

  • params._meta must carry io.modelcontextprotocol/protocolVersion and io.modelcontextprotocol/clientCapabilities; a request without the capabilities is refused with -32602 (HTTP 400). The client's revision and capabilities hold for that request only and never replace what a handshake client declared.
  • server/discover answers with supportedVersions (newest first), capabilities and instructions.
  • Every result carries resultType: "complete" and _meta["io.modelcontextprotocol/serverInfo"]. server/discover, the */list methods and resources/read also carry ttlMs and cacheScope (private: lists depend on the connection's profile and caller; reads are never fresh).
  • Resource not found is -32602; the handshake revisions keep -32002.
  • Over HTTP the request must carry MCP-Protocol-Version and Mcp-Method, and Mcp-Name for tools/call, prompts/get and resources/read (base64 values in the =?base64?...?= form are decoded), each matching the body; otherwise HeaderMismatch (-32020, HTTP 400). An unknown method is HTTP 404 with -32601. No Mcp-Session-Id is issued.
  • The server never sends such a request a question of its own; that revision forbids server-initiated requests. The question comes back inside the result instead (below).

Session handles instead of Mcp-Session-Id​

2026-07-28 has no protocol session, so nothing ties one call to the next. Two things used to ride on the session: the project project.open scopes later calls to, and the record session.start opens. For a 2026-07-28 caller they ride on a handle instead:

  • project.open and session.start mint a handle when the caller passes none, report it in the result's _meta["com.metaforge/sessionHandle"], and add a line to the result text saying to pass it on.
  • Every tool lists an optional metaforge_session argument for these callers. A call that passes the handle runs as that session: its project scope and session record apply. The argument is taken out before the tool sees it. A value that is not a handle is refused with -32602.
  • The handle's project is the call's project, ahead of the transport session's scope; only an explicit project_id argument outranks it. The tool, the approval policy, a delegated decision and the approval key all see that project, so a tool with no project_id argument is decided by the policy of the project the handle names. A handshake client that does not keep Mcp-Session-Id may pass a handle the same way; it is taken out and honoured, though only 2026-07-28 callers are minted one.
  • A handle is a session id, not a credential: it carries scope, never authority, exactly as X-MetaForge-Session does. That header still works for any client that sends it, and handshake clients keep Mcp-Session-Id.

subscriptions/listen​

2026-07-28 replaced the GET /mcp stream and resources/subscribe with subscriptions/listen. Nothing this server offers changes while it is up: the tool, prompt and resource lists are fixed once it starts, and it does not report per-resource updates. So it honours none of the notification types. It answers with notifications/subscriptions/acknowledged carrying an empty notifications filter (which tells the client nothing it asked for is supported), then closes the subscription gracefully with a resultType: "complete" result. Both carry _meta["io.modelcontextprotocol/subscriptionId"]. Over HTTP the two arrive as one text/event-stream response; on stdio the acknowledgement is written first. A malformed filter is -32602.

Error codes for 2026-07-28​

2026-07-28 marks -32000 to -32019 as legacy, and this server's own codes all sit there: tool execution -32001, unavailable -32003, read error -32005, timeout -32006, auth -32007. A 2026-07-28 caller never gets them:

  • A tools/call refused that way (a held write rejected or with no gate, a tool that failed, the approval ledger down) is a normal result with isError: true, as the spec recommends for a tool failure. The reason is the result text, which is what a model reads, and the code and details are in _meta["com.metaforge/error"] (code, legacyCode, data).
  • Any other method's code moves out of the reserved range by 1000 (-32001 becomes -31001), with the original in error.data.legacyCode.
  • Resource not found is still -32602.

Handshake clients keep the codes in the table above.

Questions returned inside results​

For a 2026-07-28 tools/call, prompts/get or resources/read that needs a person, the call returns early with resultType: "input_required":

JSON
{"resultType": "input_required",
"inputRequests": {"q1": {"method": "elicitation/create",
"params": {"mode": "form", "message": "...", "requestedSchema": {...}}}},
"requestState": "<opaque>"}

The client asks the person and retries the same call (a new JSON-RPC id) with their answers in params.inputResponses (keyed q1, q2, ... in the order asked) and params.requestState echoed unchanged. The retry runs the call again from the start; each question finds its answer.

  • Held writes. The approval entry is opened on the first pass, before the question, as for any inline approval. The retry closes the same entry with the person's answer and an approver, then runs or refuses the write. A decision made in the dashboard in between wins. A retry without the answer asks again on the same entry.
  • Design-flow gates. flow.await_gate asks through the same mechanism, so a 2026-07-28 client decides a gate in its chat as a handshake client does.
  • requestState is HMAC-signed and bound to the caller, the method, a digest of the call's own parameters and a 15 minute expiry. A forged, expired or mismatched state, inputResponses without a state, or an approval used a second time is refused with -32602, and nothing runs. Set METAFORGE_MCP_STATE_KEY to keep outstanding questions answerable across a restart; without it a random per-process key is used.
  • A client that does not declare form elicitation in the request's clientCapabilities, or a sidecar with no approval ledger, gets no question: the held write waits in the dashboard and forge approvals.

From 2025-11-25 a client can declare elicitation as {"form": {}}, {"url": {}} or both; an empty {} still means form. Every question this server asks is a form, so a client that declares only url is not asked inline and its held calls go to the dashboard.

Held calls report themselves​

A tools/call held for the dashboard (the client cannot be asked inline) is not silent until it ends:

  • Early signal. If the call carries params._meta.progressToken and the transport can reach the client for that call, the server sends notifications/progress as soon as the hold exists. message names the approval id and the dashboard Approvals page (a link when METAFORGE_DASHBOARD_URL is set); total is the hold window in seconds. It repeats every METAFORGE_APPROVAL_PROGRESS_INTERVAL_SECONDS (default 10) with progress increasing, so a client that resets its timeout on progress keeps waiting. Over HTTP, a call with a progressToken and text/event-stream in Accept is eligible for its own SSE stream whether or not the session declared elicitation; the response switches to SSE only once something is sent. Over stdio the notification is written to stdout like any other message.
  • Durable hold. With an approval ledger (both the sidecar and the in-gateway server have one) a held call is not waited on. The approval is recorded with a lifetime of METAFORGE_TOOL_APPROVAL_TTL_S (default 3600, the maximum), asked in the client's prompt or waited on for 20 seconds, and then the call returns a result with isError: true and _meta.approval.held = true, approval_id, expires_at and next_step: "retry this exact call once it is approved". The same session calling the same tool with the same arguments after the approval runs once. Lifecycle, deciding from anywhere and project policy: Held tool calls.
  • Window. Without a ledger the hold is waited on: with a progress channel for METAFORGE_APPROVAL_HOLD_PROGRESS_SECONDS (default 180), without one for METAFORGE_APPROVAL_HOLD_SECONDS (default 100), below common client tool timeouts (Claude Code: 120). The window travels on the approval ask and sets the hold's ledger deadline. A gate constructed with an explicit timeout_seconds caps it.
  • Outcome. A held tools/call is the result above. A refused call is a JSON-RPC error with data.code = "approval_required" and data.outcome one of rejected, timed_out, cancelled or not_configured, plus approval_id, route (dashboard, elicitation, retry or policy), where, held_seconds and window_seconds when known. message states the same facts, because it is what a client shows the model. The legacy tool/call dialect also gets a held call as such an error, with data.outcome = "awaiting_person".

Expired inline questions are withdrawn​

A durable inline hold waits up to 20 seconds for the answer inside the call and states the approval's lifetime in the elicitation/create message. The question is then not withdrawn: it stays open until the approval is decided on any surface (withdrawn with the reason approval decided elsewhere) or expires (approval expired), at most an hour. Over HTTP this holds only for a question on the session's GET /mcp stream: a call's own stream ends with its result, which withdraws a question still open on it. See The prompt outlives the call. Without an approval ledger an inline hold uses the same window rule as a dashboard hold: METAFORGE_APPROVAL_HOLD_SECONDS (default 100) without a progress channel, METAFORGE_APPROVAL_HOLD_PROGRESS_SECONDS (default 180) with one, in which case progress is sent while the prompt is open. The window is logged as window_seconds on mcp_tool_call_held_for_approval.

The form has no checkbox: requestedSchema holds only an optional note, and accept approves, decline refuses, cancel decides nothing. An accept is an approval whatever its content.

  • Withdrawal. When the server stops waiting on an elicitation/create for any reason (window ended, approval decided elsewhere or expired, call cancelled, call stream closed), it sends notifications/cancelled with params.requestId set to that request's id and a reason. Over HTTP it goes on the call's own stream while that is open, before the result, else on an open GET /mcp; over stdio it is written to stdout. The server logs mcp_elicitation_withdrawn with delivered.
  • Late answers. A response to a withdrawn request is acknowledged (202 over HTTP). For a durable hold it is recorded on the approval (mcp_elicitation_late_answer_to_record, then elicitation_late_answer_recorded): an accept approves it and the identical retry runs. It never runs the call itself. Otherwise it is logged as mcp_elicitation_late_response_ignored and never applied.

An answer nobody read is not an answer​

A decline or cancel returned faster than a person could have read the prompt (one second) is treated as the client answering for them, not as a refusal: a durable hold stays pending for the dashboard and approvals.decide, and the connection stops being asked for the rest of the session. An accept is always an answer. Logged as elicitation_unattended and mcp_elicitation_unattended_fallback; the reasoning is in the approvals notes.

Message Format​

All messages follow the JSON-RPC 2.0 specification:

JSON
{
"jsonrpc": "2.0",
"id": "<request-id>",
"method": "<method-name>",
"params": { ... }
}

4. Message Types​

4.1 tool/list — Discover Available Tools​

Request:

JSON
{
"jsonrpc": "2.0",
"id": "req-001",
"method": "tool/list",
"params": {
"capability": "stress_analysis"
}
}

Response:

JSON
{
"jsonrpc": "2.0",
"id": "req-001",
"result": {
"tools": [
{
"tool_id": "calculix.run_fea",
"adapter_id": "calculix",
"name": "Run FEA Analysis",
"description": "Execute finite element analysis using CalculiX solver",
"capability": "stress_analysis",
"input_schema": { ... },
"output_schema": { ... },
"phase": 1,
"resource_limits": {
"max_memory_mb": 2048,
"max_cpu_seconds": 600,
"max_disk_mb": 512
}
}
]
}
}

4.2 tool/call — Invoke a Tool​

Request:

JSON
{
"jsonrpc": "2.0",
"id": "req-002",
"method": "tool/call",
"params": {
"tool_id": "calculix.run_fea",
"arguments": {
"mesh_file": "/workspace/mesh/bracket.inp",
"load_case": "static_load_1",
"analysis_type": "static_stress"
},
"timeout_seconds": 300,
"trace_id": "abc-123-def"
}
}

Response (success):

JSON
{
"jsonrpc": "2.0",
"id": "req-002",
"result": {
"tool_id": "calculix.run_fea",
"status": "success",
"data": {
"max_von_mises": {
"bracket_body": 145.2,
"bracket_mount": 89.7
},
"solver_time": 12.5,
"mesh_elements": 45000
},
"duration_ms": 12832,
"output_files": [
"/workspace/results/stress_output.frd"
]
}
}

4.3 tool/result — Streaming Results (Optional)​

For long-running tools, the server can send progress updates:

JSON
{
"jsonrpc": "2.0",
"method": "tool/result",
"params": {
"request_id": "req-002",
"progress": 0.65,
"message": "Solving step 3/5..."
}
}

4.3.1 Slow tools return a job​

A client gives up on a call after a fixed time (Claude Code after 120 s), and some tools take longer: a paid concept mesh (twin.generate_concept_mesh) takes about 150 s. Such a tool starts its work as a job and replies at once:

JSON
{
"job_id": "5f0c...",
"status": "running",
"poll": "twin.job_status",
"expected_seconds": 150,
"tool_id": "twin.generate_concept_mesh",
"reused": false
}

The work runs as a background task in the server that took the call, and its result (or error) is stored on the job. twin.job_status (job_id, read-only, never held) returns the job record: status (queued, running, succeeded, failed or interrupted), started_at, finished_at, elapsed_seconds, expected_seconds, and result or error. The next reply to the same session after a job of its own finishes carries one more text block saying so, and _meta.finishedJobs lists {jobId, tool, status}; each job is said once, and one already read with twin.job_status is not repeated.

The default depends on the caller. A client gets a job. A service caller (the design-flow worker, a call claiming a run, or an in-process call with no MCP context) waits for the result as before. wait: true or wait: false on the call chooses explicitly. A call that would be refused (bad arguments, a source image that cannot be read, no provider configured) is refused at once and starts no job.

An identical call (same tool, same arguments, same session and project) while its job runs, or up to 10 minutes after it succeeded, returns that job with reused: true (and, once succeeded, its result) instead of starting a second paid run. A failed or interrupted job is not reused.

Jobs are kept in SQLite, one store per process: the gateway's at ~/.metaforge/tool_jobs.db and the sidecar's on its own volume (both set by METAFORGE_TOOL_JOBS_PATH). Opening a store marks every job it holds as still queued or running interrupted, since its task died with the process; a client then calls the tool again. A job is read back through the server that started it. Each state change is a tool_job_state log event and a count of metaforge_tool_job_total{tool, status}. The runner (tool_registry/jobs.py) is generic: another slow tool adopts it by returning JobRunner.reply(...) from JobRunner.start(...).

4.4 tool/error — Error Response​

On the MCP dialect (tools/call), a tool that ran and refused is not an error response at all. It comes back as a normal result with isError: true, the reason as text content, and _meta.error carrying toolId / details / durationMs — plus _meta.callId, so a failed call stays as citable as a successful one. See §4.4.1. The envelope below is the legacy tool/call dialect, whose callers already read data.details.

JSON
{
"jsonrpc": "2.0",
"id": "req-002",
"error": {
"code": -32001,
"message": "Tool execution failed",
"data": {
"error_type": "TOOL_EXECUTION_ERROR",
"tool_id": "calculix.run_fea",
"details": "CalculiX solver exited with code 1: mesh file not found",
"duration_ms": 450
}
}
}

4.4.1 tools/call — a tool that ran and refused​

JSON
{
"jsonrpc": "2.0",
"id": "req-002",
"result": {
"content": [
{
"type": "text",
"text": "twin.query_cypher failed: call context is scoped to project 7b8a but no 'project_id' parameter was bound. Add WHERE n.project_id = $project_id and pass {'project_id': ...}"
}
],
"isError": true,
"_meta": {
"callId": "3cb7ee97145e4726",
"error": {
"toolId": "twin.query_cypher",
"details": "call context is scoped to project 7b8a but no 'project_id' parameter was bound. …",
"durationMs": 4.1
}
}
}
}

This is the MCP-recommended shape, and the reason it changed is concrete. The refusal above says exactly how to fix the query. It used to live only in JSON-RPC error.data.details, and Claude Code shows error.message — the constant string "Tool execution failed". The agent retried blind, failed the same way, gave up, and reported the tool as broken.

Protocol errors stay JSON-RPC errors. An unknown method or unknown tool is not something the model can fix by changing its arguments, and the unknown-tool error already carries a did-you-mean. The split is "did the tool run?", not "was there a problem".

4.4.2 Next-step hints and missing-field errors​

twin.stage_work_product_file returns its staged file_path plus a next_step string naming freecad.import_step (with that file_path) and freecad.describe_step_file, so a model loads the stored part instead of recreating it. twin.commit_geometry called with no geometry fails with Missing: session_id, obj_id, step_base64 listing exactly the absent fields and what to pass.

4.5 health/check — Adapter Health​

Request:

JSON
{
"jsonrpc": "2.0",
"id": "req-003",
"method": "health/check",
"params": {}
}

Response:

JSON
{
"jsonrpc": "2.0",
"id": "req-003",
"result": {
"adapter_id": "calculix",
"status": "healthy",
"version": "0.1.0",
"tools_available": 3,
"uptime_seconds": 3600,
"last_invocation": "2026-03-02T10:15:00Z"
}
}

Roll-up on the unified server​

Sent to the unified server rather than to one adapter, health/check returns an aggregate. The server answers it by sending this same request to every adapter it has loaded, with a three-second timeout each, and reporting what came back:

JSON
{
"service": "metaforge-mcp",
"status": "degraded",
"version": "0.3.797",
"uptime_seconds": 3600.0,
"adapter_count": 3,
"tool_count": 100,
"unreachable_adapters": ["calculix"],
"detail": "1 of 3 adapters did not answer: calculix. Their tools are registered but calls to them will fail.",
"adapters": [
{"adapter_id": "twin", "version": "0.1.0", "tools_registered": 12, "reachable": true},
{"adapter_id": "calculix", "version": "0.1.0", "tools_registered": 5, "reachable": false,
"error": "adapter container is down (-32001)"}
]
}

version is the release the server was installed as, the same number the gateway's /health reports: the release workflow stamps it into the package before building the image, so a released image says 0.3.797 and a build after a release says 0.3.797+g1a2b3c4. The initialize result's serverInfo.version carries it too. A checkout run without installing says 0.0.0+unknown. Each adapter's own version is separate and unchanged.

The same report carries client.can_elicit (see Answering in the harness), auth (what the transport in front of the server enforces: open, api_key, oauth, api_key+oauth, or unknown when the transport declared nothing) and client (the clientInfo from the initialize handshake, or from the request itself for a handshake-free 2026-07-28 client, plus protocol_skew when the revision the client asked for is not the one the server pinned). Both are described under What is protecting this connection.

The report also carries llm_usage_24h: calls, prompt, completion and cached-input tokens and cost over the trailing 24 hours, with by_phase, by_role and by_model breakdowns. available: false plus a reason means the usage store could not be read, which is not the same as nothing having been spent; a non-zero calls_unpriced means cost_usd is a lower bound. Details are in Token and cost accounting.

status is healthy only if every adapter answered, degraded otherwise. tools_registered is a registry count and does not shrink when an adapter goes down — reachable is the field that says whether those tools can actually be called. unreachable_adapters and detail are present only when something is wrong, so their absence is itself the healthy signal.

Over HTTP this is a 200 in both states: the MCP server is up and reporting accurately on its dependencies. See Health is measured, not asserted.


5. Pydantic Message Schemas​

All MCP messages are validated using Pydantic models in mcp_core/schemas.py.

Python
"""Pydantic schemas for MCP protocol messages."""

from datetime import datetime
from pydantic import BaseModel, Field
from typing import Any


# --- Requests ---

class ToolListRequest(BaseModel):
capability: str | None = None


class ToolCallRequest(BaseModel):
tool_id: str = Field(..., description="Tool identifier (e.g., 'calculix.run_fea')")
arguments: dict[str, Any] = Field(default_factory=dict, description="Tool parameters")
timeout_seconds: int = Field(default=120, ge=1, le=3600)
trace_id: str | None = Field(default=None, description="OpenTelemetry trace ID")


class HealthCheckRequest(BaseModel):
pass


# --- Responses ---

class ResourceLimits(BaseModel):
max_memory_mb: int = 1024
max_cpu_seconds: int = 300
max_disk_mb: int = 256


class ToolManifest(BaseModel):
tool_id: str
adapter_id: str
name: str
description: str
capability: str
input_schema: dict = Field(default_factory=dict)
output_schema: dict = Field(default_factory=dict)
phase: int = 1
resource_limits: ResourceLimits = Field(default_factory=ResourceLimits)


class ToolListResult(BaseModel):
tools: list[ToolManifest]


class ToolCallResult(BaseModel):
tool_id: str
status: str # "success" or "error"
data: dict[str, Any] = Field(default_factory=dict)
duration_ms: float = 0
output_files: list[str] = Field(default_factory=list)


class ToolProgress(BaseModel):
request_id: str
progress: float = Field(ge=0.0, le=1.0)
message: str = ""


class HealthStatus(BaseModel):
adapter_id: str
status: str # "healthy", "degraded", "unhealthy"
version: str
tools_available: int
uptime_seconds: float
last_invocation: datetime | None = None


# --- Errors ---

class McpErrorData(BaseModel):
error_type: str
tool_id: str
details: str
duration_ms: float = 0


# --- JSON-RPC envelope ---

class JsonRpcRequest(BaseModel):
jsonrpc: str = "2.0"
id: str
method: str
params: dict[str, Any] = Field(default_factory=dict)


class JsonRpcSuccessResponse(BaseModel):
jsonrpc: str = "2.0"
id: str
result: dict[str, Any]


class JsonRpcErrorResponse(BaseModel):
jsonrpc: str = "2.0"
id: str
error: dict[str, Any]

6. Tool Manifest​

Every tool adapter publishes a manifest describing its capabilities. The manifest is returned by tool/list and cached by the Tool Registry.

Manifest Fields​

FieldTypeDescription
tool_idstrUnique tool identifier: <adapter_id>.<method_name>
adapter_idstrAdapter that provides this tool
namestrHuman-readable tool name
descriptionstrWhat the tool does
capabilitystrCapability category (e.g., "stress_analysis", "erc_check")
input_schemadictJSON Schema for tool parameters
output_schemadictJSON Schema for tool results
phaseintMinimum phase where this tool is available
resource_limitsResourceLimitsCPU, memory, and disk limits for the container

7. Tool Registry​

The Tool Registry (tool_registry/registry.py) maintains a catalog of all available tools and their health status.

Python
class ToolRegistry:
"""Central catalog of available MCP tools with health tracking."""

async def register_adapter(self, adapter_id: str, config: "AdapterConfig") -> None:
"""Register a tool adapter and discover its tools."""
...

async def get_tool(self, tool_id: str) -> ToolManifest | None:
"""Look up a tool by ID."""
...

async def list_tools(
self,
adapter_id: str | None = None,
capability: str | None = None,
phase: int | None = None,
) -> list[ToolManifest]:
"""Query available tools with optional filters."""
...

async def health_check(self, adapter_id: str) -> HealthStatus:
"""Check adapter health and update internal status."""
...

async def health_check_all(self) -> dict[str, HealthStatus]:
"""Check health of all registered adapters."""
...

async def get_healthy_adapter(self, tool_id: str) -> str | None:
"""Get a healthy adapter that provides the given tool. Returns None if unavailable."""
...

Adapter Configuration​

Python
class AdapterConfig(BaseModel):
adapter_id: str
image: str # Docker image name
transport: str = "stdio" # "stdio" or "http"
host: str = "localhost"
port: int = 8080
workspace_mount: str = "/workspace"
resource_limits: ResourceLimits = Field(default_factory=ResourceLimits)
environment: dict[str, str] = Field(default_factory=dict)
health_interval_seconds: int = 30

8. Execution Engine​

The Execution Engine (tool_registry/execution_engine.py) manages the lifecycle of tool invocations.

Invocation Lifecycle​

Code
Tool call received from MCP Client
│
▼
Resolve tool_id → adapter_id via Tool Registry
│
▼
Check adapter health
├── Unhealthy → return TOOL_UNAVAILABLE error
└── Healthy → continue
│
▼
Start Docker container (if stdio) or reuse connection (if HTTP)
│
▼
Mount workspace directory (read-only or read-write per config)
│
▼
Send JSON-RPC request to container
│
▼
Wait for response (with timeout)
├── Timeout → TOOL_TIMEOUT error, kill container
├── Container crash → TOOL_EXECUTION_ERROR
└── Success → parse and return result
│
▼
Record metrics (OpenTelemetry span + Prometheus counter)
│
▼
Cleanup container (if ephemeral)
│
▼
Return ToolCallResult to MCP Client

Execution Engine Interface​

Python
class ExecutionEngine:
"""Manages tool invocation lifecycle."""

async def invoke(
self,
tool_id: str,
arguments: dict,
timeout_seconds: int = 120,
trace_id: str | None = None,
) -> ToolCallResult:
"""
Execute a tool call with full lifecycle management.

1. Resolve adapter from registry.
2. Start/connect to container.
3. Send request, wait for result.
4. Handle timeout, retry if idempotent.
5. Record telemetry.
6. Cleanup.
"""
...

async def cancel(self, request_id: str) -> bool:
"""Cancel a running tool invocation."""
...

Retry Policy​

ConditionAction
Tool returns error, skill is idempotent: trueRetry up to retries times (from definition.json)
Tool returns error, skill is idempotent: falseNo retry, propagate error
TimeoutKill container, return TOOL_TIMEOUT error. Retry only if idempotent.
Container crashReturn TOOL_EXECUTION_ERROR. Retry only if idempotent.
Adapter unhealthyReturn TOOL_UNAVAILABLE immediately (no retry).

9. Tool Adapter SDK​

To create a new tool adapter, subclass McpToolServer and implement tool handlers.

Step-by-Step Guide​

1. Create the adapter directory:

Code
tool_registry/tools/<adapter_name>/
├── server.py # McpToolServer subclass
├── Dockerfile # Container image definition
├── requirements.txt # Python dependencies
└── tests/
└── test_server.py

2. Implement the server:

Python
"""CalculiX FEA tool adapter."""

from tool_registry.mcp_server.base import McpToolServer, ToolManifest, ResourceLimits


class CalculixServer(McpToolServer):
def __init__(self):
super().__init__(adapter_id="calculix", version="0.1.0")
self._register_tools()

def _register_tools(self):
self.register_tool(
manifest=ToolManifest(
tool_id="calculix.run_fea",
adapter_id="calculix",
name="Run FEA Analysis",
description="Execute finite element analysis using CalculiX solver",
capability="stress_analysis",
input_schema={
"type": "object",
"properties": {
"mesh_file": {"type": "string", "description": "Path to .inp mesh file"},
"load_case": {"type": "string"},
"analysis_type": {"type": "string", "enum": ["static_stress", "thermal", "modal"]},
},
"required": ["mesh_file", "load_case", "analysis_type"],
},
output_schema={
"type": "object",
"properties": {
"max_von_mises": {"type": "object"},
"solver_time": {"type": "number"},
"mesh_elements": {"type": "integer"},
},
},
phase=1,
resource_limits=ResourceLimits(max_memory_mb=2048, max_cpu_seconds=600, max_disk_mb=512),
),
handler=self.run_fea,
)

async def run_fea(self, arguments: dict) -> dict:
"""Execute CalculiX FEA analysis."""
import subprocess

mesh_file = arguments["mesh_file"]
analysis_type = arguments["analysis_type"]

# Run CalculiX solver
result = subprocess.run(
["ccx", "-i", mesh_file.replace(".inp", "")],
capture_output=True,
text=True,
timeout=600,
)

if result.returncode != 0:
raise RuntimeError(f"CalculiX failed: {result.stderr}")

# Parse results from .frd output file
# ... (parsing logic specific to CalculiX output format)

return {
"max_von_mises": parsed_stresses,
"solver_time": elapsed,
"mesh_elements": element_count,
}


if __name__ == "__main__":
import asyncio
server = CalculixServer()
asyncio.run(server.start_stdio())

3. Write the Dockerfile:

Dockerfile
FROM python:3.11-slim

# Install CalculiX
RUN apt-get update && apt-get install -y calculix-ccx && rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY server.py .

# Workspace mount point
VOLUME ["/workspace"]

# No network access by default
# Network is controlled by Docker run flags

ENTRYPOINT ["python", "server.py"]

10. Phase 1 Adapters​

CalculiX Adapter (tool_registry/tools/calculix/)​

PropertyDetails
Docker Imageghcr.io/fidelodok/metaforge-calculix-adapter, published by CI
Base Imagepython:3.11-slim + calculix-ccx
Transportstdio
Toolscalculix.run_fea, calculix.run_thermal, calculix.validate_mesh

Tools provided:

Tool IDCapabilityDescription
calculix.run_feastress_analysisStatic stress FEA using CalculiX solver
calculix.run_thermalthermal_analysisThermal analysis (steady-state and transient)
calculix.validate_meshmesh_validationValidate mesh quality (aspect ratio, element types)

CadQuery Adapter (tool_registry/tools/cadquery/)​

PropertyDetails
Docker Imageghcr.io/fidelodok/metaforge-cadquery-adapter, published by CI
Base Imagepython:3.11-slim (multi-stage)
Transportstdio
Toolscadquery.create_parametric, cadquery.boolean_operation, cadquery.get_properties, cadquery.export_geometry, cadquery.execute_script, cadquery.create_assembly, cadquery.generate_enclosure

Tools provided:

Tool IDCapabilityDescription
cadquery.create_parametriccad_generationGenerate parametric CAD geometry from shape type and dimensions
cadquery.boolean_operationcad_operationsCSG boolean operations (union, subtract, intersect)
cadquery.get_propertiescad_analysisGeometric properties (volume, area, center of mass, bounding box, inertia)
cadquery.export_geometrycad_exportExport to STEP/STL/OBJ/BREP/AMF/SVG
cadquery.execute_scriptcad_scriptingRun a CadQuery Python script in an OS-isolated child process (see below)
cadquery.create_assemblycad_assemblyMulti-part assembly from STEP files with constraints. Without output_path it writes into a new folder under its work folder and returns the path as assembly_file; a named path must be inside the work folder. Fails if the file is not written. A part may be a shape (a screw, pin, washer or nut from its standard's dimensions) instead of a file, left out of the interference list
cadquery.generate_enclosurecad_enclosurePCB enclosure from board dimensions and connector cutouts

Script isolation​

cadquery.execute_script runs each script in a fresh, throwaway child process, never in the adapter (script_runner.py starts script_child.py). Before the script runs, and before any thread exists, the child is confined by the kernel: a uid of its own from CADQUERY_RUNNER_UIDS, setrlimit limits (resident memory, an address-space backstop, CPU, file size, open files, processes), Landlock (writes only its private folder under /run/cadquery-runner, reads only system and Python paths, never /workspace, runs no program, opens no TCP connection) and a seccomp filter on every thread (no network socket, no new process, no execve, ptrace or io_uring). Its environment caps glibc malloc arenas (MALLOC_ARENA_MAX=2) and OpenMP and OpenBLAS at one thread, so the address space it reserves stays close to what it uses. The adapter kills every process of the run at its deadline and removes the folder. The result comes back as bytes on a pipe; the adapter writes it to the work folder itself.

VariableDefaultMeaning
CADQUERY_RUNNER_ROOT/run/cadquery-runnerWhere each run's private folder is made (a tmpfs under compose)
CADQUERY_RUNNER_UIDS61000-61003The uid pool: one uid per concurrent run; concurrency is the smaller of the pool and CADQUERY_RUNNER_MAX_CONCURRENT
CADQUERY_RUNNER_MAX_CONCURRENT2Script children running at once; the container's 6G memory limit is sized for two
CADQUERY_RUNNER_REQUIREuid,landlock,seccompLayers that must hold; a missing one refuses the run
CADQUERY_RUNNER_MEMORY_MB2048Memory one child may really use: private writable memory on RLIMIT_DATA, not address space. Falls back to address space on a kernel whose RLIMIT_DATA does not count mmap
CADQUERY_RUNNER_ADDRESS_SPACE_MB16384Address-space backstop (RLIMIT_AS) of one child. OCCT and glibc reserve address space they never touch, so it is set far above the memory budget
CADQUERY_RUNNER_MAX_FILE_MB64Largest file the child may write (its console log included)
CADQUERY_RUNNER_MAX_OUTPUT_MB64Largest result the adapter accepts
CADQUERY_RUNNER_STARTUP_GRACE_S15Added to the script's timeout for interpreter and CadQuery start-up
CADQUERY_SCRIPT_ISOLATIONprocessin_process runs scripts unisolated, for development and unit tests only

The compose service runs read-only with cap_drop: [ALL], only SETUID and SETGID added back (the image drops to uid 1000 keeping just those two, so it can start a child as another uid) and no-new-privileges. See CadQuery writes under a policy for what each layer stops, how it was verified, and what is not isolated.

FreeCAD Adapter (tool_registry/tools/freecad/)​

PropertyDetails
Docker Imageghcr.io/fidelodok/metaforge-freecad-adapter, published by CI (see below)
Base ImageDebian system Python 3 (FreeCAD's compiled extension requires it, not a python.org image)
Transportstdio
ToolsStateful session API (open_session, create_body, create_sketch, pad_sketch, execute_code, measure, export_model, assembly joints, and more — 27 tools) plus a separate stateless legacy file-based surface (export_geometry, generate_mesh, boolean_operation, get_properties, describe_step_file, create_parametric — 6 tools)

Adapter images are built in CI​

The tool adapters copy the shared modules they import from mcp_core/, tool_registry/ and observability/ into their images, so a fix in those modules reaches an adapter only after a rebuild. The adapter-images workflow rebuilds an adapter on a push to main that changes its own folder or a shared module it copies (and on manual dispatch), and publishes ghcr.io/fidelodok/metaforge-<adapter>-adapter:latest and :<commit sha>. Which change rebuilds which image is set out in When an image is rebuilt. docker-compose.yml names those images directly, so a dev host pulls them:

Terminal
docker compose pull freecad-adapter calculix-adapter
docker compose up -d --no-build freecad-adapter calculix-adapter
docker compose restart mcp-http

Building these images on the dev host itself has taken it offline, so prefer the published ones. METAFORGE_ADAPTER_TAG pins a commit SHA instead of latest when you need a specific build.

This used to need a manual retag

The compose file used to name metaforge/<adapter>-adapter, which nothing published, so every host built locally — including the dev host whose load this workflow exists to remove. The documented fix was to docker tag the pulled image to the name compose expected. That step is gone: the names match now, and docker compose pull is enough.

Corrected from a stale table that listed freecad.export_mesh/freecad.export_step/freecad.measure — those tool ids don't exist in the current adapter. See capability-matrix.md for the 5-capability contract shared with CadQuery, and tool_registry/tools/freecad/adapter.py for the full tool list; it's large enough (33 tools across both surfaces) that duplicating it here would drift again.

Committing authored geometry: the stash is authoritative​

freecad.export_model returns a multi-KB base64 STEP, and twin.commit_geometry needs those bytes. Agents cannot reliably thread a value that large between two tool calls, so both MCP dispatch seams — the unified sidecar and the in-process registry bridge the gateway chat uses — keep a bounded LRU of each export's blob keyed by (session_id, obj_id) (skill_registry/geometry_stash.py). A commit that names those two ids gets the blob filled in server-side.

When the stash has an entry for the named export, its copy is used even if the call also carried a step_base64. The stashed value came straight off the adapter; anything carried back in is a copy of it, and a copy can only be equal or wrong. This precedence used to be the other way round, which let a single mistyped character in a 30,000-character base64 string silently replace a pristine blob: a committed STEP contained NAMED_URIT(*) where the fixed OCCT boilerplate reads NAMED_UNIT(*), and the OCCT converter crashed parsing it. A divergence is repaired and logged as geometry_commit_blob_diverged, never silently.

A stash miss leaves a supplied step_base64 untouched — geometry produced some other way (a raw CadQuery script, an upload) has no export to reference and must still commit.

Stateless tools (freecad.create_parametric, cadquery.create_parametric/ execute_script/generate_enclosure, ...) have no session_id/obj_id at all — they just return a cad_file path on the shared adapter workspace both the gateway process and the adapter container mount. For these, pass that same path as twin.commit_geometry's file_path argument instead: the server reads it directly off disk and base64-encodes it itself, mirroring domain_agents.shared.commit_geometry.commit_geometry's own relative-path resolution (against ADAPTER_WORKSPACE_DIR, default /workspace) that the skill layer already used internally — this just makes the same ergonomics available to a model calling twin.commit_geometry directly. step_base64 still wins when given alongside file_path, same precedence as the session/obj_id path.

Twin adapter: item keys and revision history​

The definition write tools (twin.commit_geometry, twin.record_constraint_set, twin.record_engineering_entity for intent/stakeholder_need/objective, and twin.record_component_selection) write each call as the next revision of an item (see twin_schema.md section 2.30). They accept three optional arguments, none of which the normal path needs. Each is a string or null; null or an empty string means not given.

ArgumentMeaning
item_keyThe item to revise, as an earlier result returned it (CAD-BRACKET). KEY@n also asserts the head is still revision n; a stale @n fails with nothing written. A bare key no item has yet names a new item.
supersedesNode id of an earlier revision; the write revises that node's item.
change_reasonWhy this revision differs from the previous one; stored on the REVISION_OF edge.

With none given, the same name in the same project is the same item. Pass item_key when a part keeps its identity under a new name. Every result carries item_key, revision and item_ref (KEY@n). The revision's author is the call context's actor_id and its run_id the context's design-flow run; agents never number revisions themselves.

Inside a design-flow run a definition write is a draft in the run's change set: its result adds revision_status: "draft" and a one-line draft_note, and the item's head does not move until the run's gate approves. The run's own reads see its drafts; other callers see approved heads only (see twin_schema.md, Drafts, approval and closed drafts).

twin.item_history (read-only, registered when the gateway or sidecar injects item_history_reader) takes item_key or the node_id of any revision, plus an optional project_id when a key exists in several projects, and returns:

JSON
{
"item": {"key": "CAD-LEG", "item_type": "cad_model", "name": "Leg, front left",
"project_id": "...", "head_revision": 2, "head_node_id": "...",
"head_ref": "CAD-LEG@2", "created_at": "...", "updated_at": "..."},
"revisions": [
{"revision": 1, "node_id": "...", "name": "Leg", "change_reason": null,
"run_id": null, "author": "agent:mechanical", "is_head": false, "adopted": false},
{"revision": 2, "node_id": "...", "name": "Leg, front left",
"change_reason": "renamed and lengthened", "is_head": true, "adopted": false}
]
}

An unknown key, or a node that is not a revision of any item (a record, or an unclassified type), is a tool error naming the reference.

Read semantics. Both reads follow the calling run (the call context's run_id):

  • twin.item_history lists the caller's own open drafts and never another run's; closed drafts are always listed. Every revision carries status (committed, draft, approved, rejected, abandoned), change_set, phase, gate and status_reason. The result adds current ({"revision", "node_id", "ref"}), what this caller reads as current: its run's draft if it has one, else the head. item adds draft_revision, draft_node_id and draft_ref when the caller's run has a draft; head_* is always the approved head (null for an item that only has drafts).
  • twin.get_node accepts item_key instead of node_id: a bare KEY returns the node current names, KEY@n that revision (only if the caller can see it), with an optional project_id when the key exists in several projects. node_id is no longer required when item_key is given.

Twin adapter: the Imagine studio​

Three tools, registered when the gateway or sidecar injects imagine_studio (an api_gateway.imagine.service.ImagineService), let an agent write the per-product formgraph config for Create's Imagine stage (The Imagine stage). Each takes an optional project_id (UUID), defaulting to the call context's project.

  • twin.imagine_get_studio (read-only): {project_id, status, revision, config_ref, engine_url, studio_url, engine_page_url, config, updated_at, handover, collections, warnings}. collections is what the person did in the browser, keyed by collection and document id; read it before writing a new config. studio_url is the absolute dashboard link to the studio (<METAFORGE_DASHBOARD_URL>/create/<id>?stage=imagine), the one to give a person; engine_page_url is the bare engine page (<METAFORGE_GATEWAY_PUBLIC_URL> plus engine_url, falling back to METAFORGE_PUBLIC_URL), whose token expires after ten minutes. Each is null when its host is not configured. twin.imagine_put_studio returns the same two links.
  • twin.imagine_put_studio (additive): takes config, checks it with the merged formgraph rules and writes it as the next IMG-STUDIO revision. The product context goes inline as config.context; a context folder path or a reference file is refused. A config that fails the checks is a tool error listing every error; a handed-over studio is a tool error until a person reworks it.
  • twin.component_thread (read-only): {project_id, studio, threads, summary, warnings}. One thread per component, keyed part:<studio part id>, selection:<node id>, board-part:<order code> or board:<name>, with relation (same, refined, replaced, develop_only, imagine_only) and one object per stage (imagine, develop, check, make); adopt is set when Develop's part can be taken into the studio. See Components across the stages.
  • twin.form_thread (read-only): {project_id, studio, rows, summary, warnings, limitations}. One row per part the studio draws, keyed by the studio part id, with status (same, differs, accepted, unmeasured, unpaired), studio {part_id, size_mm}, develop {item_ref, node_id, name, size_mm} and delta_mm (Develop minus studio, studio axes). See Form changes from Develop.
  • twin.imagine_accept_form (additive): takes base_revision, a row key as row and optional changes (each {op: replace, path: /form/params/<name>, value}), and writes the next studio revision with the part stamped by the item revision it took. Allowed on a handed-over studio, which stays handed over. Refused for an unknown row, a row that does not differ, a moved head or a change outside the form's parameters.
  • twin.imagine_adopt (additive): takes base_revision and a thread key as thread and writes Develop's part into the studio as the next revision, checked as any studio write is. Refused for an unknown key, a thread with nothing to adopt, a moved head, a handed-over studio or a board.
  • twin.imagine_patch_studio (additive): takes base_revision and changes (1 to 64), each {op, path, value} in the style of JSON Patch (RFC 6902): add, replace or remove at a JSON Pointer. In a list of objects with an id, a path segment may name an item by its id (/form/authored/parts/display/code) as well as by its index; - appends with add. The changes apply in order to the head's config and the result is checked and written exactly as twin.imagine_put_studio writes a config, as the next revision. A head that is no longer base_revision, a change that names something that does not exist, and a result that fails the checks are tool errors, and nothing is written. Returns {project_id, status, revision, config_ref, engine_url, applied, warnings}, not the config. REST: PATCH /v1/twin/projects/{id}/imagine/studio with {base_revision, changes} (409, 400 and 422 as above).
  • twin.imagine_add_mesh_reference (additive): puts a twin model in the studio as a see-through mesh reference. Takes work_product_id (a STEP, GLB, STL or OBJ in the twin), id (a slug), title, role (context by default, envelope, target or look), and optionally note, units, up, at (mm), rotate (degrees about X, Y, Z), color (hex) and opacity (0.05 to 1). The studio centres the mesh on X and Z with its lowest point at Y = 0, then moves it to at; the stored origin is the file point that lands there, in studio axes, so at = W - (P - origin) puts file point P at W. twin.imagine_patch_studio changes any of these later. A STEP goes through the OCCT converter the viewer uses (millimetres, Z up). The mesh is reduced for display and written into context.references with its full size in stats, as the next revision; a reference with the same id is replaced. Returns {project_id, revision, config_ref, engine_url, studio_url, engine_page_url, reference, warnings}, the reference without its mesh. Not in the Imagine stage's in-app tool set, which is at its cap.
  • twin.imagine_handover_status (read-only): {ready, items: [{id, label, status, detail}]}, the checklist that gates Imagine to Develop.
  • twin.imagine_validate (read-only, never held for approval): a dry run of every Imagine gate. Takes config (a draft to check), scope (refs to re-check, {kind, id}), revision (the head revision; after a write, name the revision it returned, because the chat answers an identical repeat of an earlier call from that call's result, so a plain repeat would show the report from before the fix) and gates. Returns the verification service's report: verdict (invalid, needs_agent, blocked_external, needs_person, ready_for_handover), level (V0 to V2), gates and findings, each with a target, a status, a resolver (agent, person or external) and, for the agent's, a fix that names what is needed and never a value. The report comes back as a result, including invalid and blocked_external; when the service cannot be reached the result is blocked_external with one verification.service finding. The tool never decides the verdict itself. See docs/imagine-stage.md.

There is deliberately no handover or rework tool: both are a person's decisions, taken in the dashboard (POST .../imagine/handover, POST .../imagine/rework, refused to an agent surface).

Twin adapter: the release path​

These tools let an agent take a validated design to a release without handling file bytes. Each takes project_id.

  • twin.imagine_resolve_part (read-only, never held for approval): give one real part a 3D body. Takes part (the object as it goes in context.components.parts: id, role, name, mpn, optionally geometry and kicad.symbol, and optionally package_text) and returns rung (existing, exact, approximation or placeholder), geometry (envelope, body, fidelity, fidelity_basis, source), tried (each rung and why it was or was not used) and message. exact means a CAD kernel measured the KiCad library's own model; a size only estimated from the file is an approximation. Pass package_text (the package outline section of the datasheet, at most 30000 characters) and a rule-based parser reads the size from it: standard IC outlines in the TI/JEDEC millimetre format, an approximation whose size is read (size_basis read); text it does not recognise is skipped with a reason. The KiCad rung reads the folder named by METAFORGE_KICAD_LIBRARY_DIR (holding symbols, footprints and 3dmodels) and is skipped with a reason when it is unset. Nothing is written: copy geometry into the part.

  • twin.imagine_look (read-only, never held for approval): look at an authored form. Renders the stored studio's engine page in headless Chromium and returns status (ready, error, none, not_authored or unavailable), each part's kind, size, triangles and error, and the screenshots as image blocks. Takes revision (the head; after a write, name the revision it returned, for the same reason as twin.imagine_validate) and set ({parameter: number}, moved in the page and never saved, then it looks again and adds after, compare and requests_after_change). A part that fails is named and the rest is still drawn. It also returns measured: overhang_share (an upper bound), support (margin_mm and tip_angle_deg of the centre of mass against the flat base, negative when it would tip over, null with no flat base), overlaps (component boxes that overlap) and notes, and compare.measured_changed after a set. V2 screening, never a verification. fails is named and the rest is still drawn. unavailable carries install: the playwright package and a Chromium build are not part of MetaForge, and the agent must say it could not look rather than claim the form is right.

  • twin.measure_dfm (additive, registered with the DFM tools): {item_key | node_id, build_direction?}. The gateway reads the committed revision's STEP from the twin and calls cadquery.dfm_measure itself, then stores the exact dfm_finding_set. Returns {measured, item_ref, component_id, status, complete, findings, not_assessed, finding_set_id}, or measured: false with reason. twin.evaluate_dfm takes measure (default true) and does the same for every validated part that has no exact analysis yet, listing them under measured. cadquery.dfm_measure still takes step_base64 for a STEP that is not in the twin.

  • twin.resolve_concept_component (additive, registered when the gateway injects release_path_service): {component_id, action: realised_by | retired | restored, item_keys?, reason}. Records a design decision; the maturity and the release checklist read the newest one. Returns the resolution, its decision_node_id and the checklist's components_exact status. See resolving concept components.

  • twin.run_item_fea (producing, same injection): {item_key | node_id, load_case: {name, analysis_type: static_stress | modal, material, fixed, loaded, force_n, num_modes}, element_size?, element_order?}. Reads the STEP, meshes it with freecad.generate_mesh and solves with calculix.run_fea, both over MCP. fixed and loaded are a surface set name or {axis, side} (the largest flat surface at that end). Returns the mesh and its surfaces, the surfaces used, the solver result and record_with, the twin.record_document arguments that pin it to the revision.

  • twin.create_baseline and twin.create_release_package close the path. The package now pins a design_files manifest with a manifest_sha256 (release packages). The baseline is destructive (it advances existing records) and the release approval it needs (twin.record_engineering_entity, entity_type: release_approval) is approved by a person, so both wait for one, unless the owner delegates the release.

  • twin.approve_release (destructive, delegated only): {project_id, reason, entity_id?}. Approves the newest unapproved release_approval as the agent acting for the person. It runs only when the owner sets METAFORGE_ALLOW_AGENT_RELEASE=true and the request carries X-MetaForge-Agent and X-MetaForge-On-Behalf-Of; then twin.create_baseline also runs without a hold, recorded as agent:<agent> on behalf of <person>. Otherwise it is refused at once with human_authority_required, and refused with the blockers named while another release checklist item is open. No policy approves either tool. See delegating a release to an agent.

  • files.decide_upload (destructive, delegated only): {upload_id, decision: approve | reject, reason?}. Decides an upload the calling agent staged itself (files.import, files.request_upload; the upload keeps the X-MetaForge-Agent it was staged with), as that agent for the person. It runs only when the owner sets METAFORGE_ALLOW_AGENT_HUMAN_AUTHORITY=true and the request carries both agent headers; otherwise it is refused at once with human_authority_required, and an upload another agent or a person staged is refused by name. Under the same flag and headers, library.register_* and library.update_* run without the hold and the entry records agent <agent> on behalf of <person> with an authority of delegated, never verified by the person. library.dispatch_job and vendor.place_order are never delegated, and no policy approves any of these. See an agent's own uploads and library entries.

  • twin.build_assembly (producing, same injection): {project_id, name, parts: [{item_key, name?, location?: {x, y, z, rx, ry, rz}, board_ref?}], joints?: [{name, type: revolute | fixed | slider, parent?, child | moving, axis_point, axis_dir, min_deg?, max_deg?, steps?, retention?}], fasteners?: [{designation, name?, location, holes?: [{part, diameter_mm, fit?: clearance | tapped | thread_forming | press, length_mm?, depth_mm?, center?, axis?, counterbore?: {diameter_mm, depth_mm}, face_diameter_mm?, flush?}], washers?, nut?, min_engagement_mm?}], material?, item_key?, change_reason?}. A fastener's designation is read the way library.standard_part reads it (ISO 4762 M4x25, M2.5x6, ISO 2338 4x30); it goes into the STEP as a shape part of cadquery.create_assembly ({generator, params, z_offset}, made from the standard's dimensions) and into layout.fasteners. Stages each part revision's STEP, builds the assembly with cadquery.create_assembly over MCP (no output_path: the adapter writes into a folder of its own and returns assembly_file, which the gateway reads) and commits it through the geometry recorder as the next revision of an assembly item, keeping the layout (metadata.assembly_layout). Returns the commit result with item_ref, the layout and the build's interferences. A board is placed as the cad_model kicad.export_3d made of it (committed with twin.commit_geometry, source_tool: kicad.export_3d), which records its board_ref.

  • twin.check_assembly (additive, same injection): {project_id, assembly: ASM-... | ASM-...@n | node id, checks?: {clearances, hole_patterns (with retention?), outlines, connectors: [{board, name?, reference? | footprint, rotation_deg?, side?, mating_side? | mating_axis, face?, board_outline? | edge_setback_mm?, slot_part?, slot_center?, slot_normal?, slot_size_mm?, plug?, plug_envelope_mm?, plug_shell_mm?, max_gap_mm?}], stacks, fasteners, seats, joints, allowed_overlaps, interference_tolerance_mm3, fastener_tolerance_mm}}. fasteners and joints default to the assembly's own. A connector named by reference takes its footprint, rotation and side from the board file; with no connectors given, a USB-C receptacle in the board file makes the connector check required, its slot read from a part's connector_slots. A mating axis more than 5 degrees off the slot's opening, or a plug that cannot pass the slot to seat, is high; a hole pattern or revolute joint with no fastener is a medium "unfastened joint". Measures the placed parts with cadquery.check_interference (read only) and records an assembly_check pinned to the assembly and every part revision. Returns {node_id, assembly_ref, outcome: passed | issues_found | incomplete, counts, open_findings, checks, derived, checklist_item, depends_on}; each finding has a stable id, a severity and the parts involved. See design for assembly.

  • twin.accept_release_finding (destructive, human authority, release delegated): {project_id, item: eda_checks | assembly_dfa | design_files_released, targets, reason}. Accepts a failing ERC or DRC (PCB-...@n:drc, SCH-...@n:erc), open assembly findings (their ids) or leaving a stray board or schematic (its node id) out of the package for the release, as an approved waiver pinned to the revisions it is about. Held for a person, whose approval names the approver; with METAFORGE_ALLOW_AGENT_RELEASE=true and the agent and person headers it runs as the agent's decision for the person (approved_by: agent:<name>, on_behalf_of). A caller cannot name the approver; an unknown or no longer failing target is refused. No policy approves it.

  • twin.record_design_files takes source_ref (CAD-...@n, PCB-...@n, FW-...@n; a bare key pins the current revision) and returns the pin it recorded as source_ref. Without it the pin comes from the sources, or for G-code from the source.json slicer.slice writes beside it. The release checklist's outputs_current and twin.create_release_package refuse an output made from an older revision or with no source (output source pins). work_product_type: bom records a BOM file (CSV, TSV or JSON): the board's with source_ref the PCB-...@n, the assembly's with the ASM-...@n; it returns line_items and bom_scope and keeps the lines in metadata.bom_lines (BOM files).

  • library.standard_part takes designation alone (ISO 4762 M4x25, M2.5x6, ISO 7089 M4, ISO 2338 4x30) as well as family and size, and knows iso2338 parallel pins.

  • cadquery.create_assembly takes a part as shape: {generator: socket_head_cap_screw | parallel_pin | washer | hex_nut, params, z_offset} in place of file, made from a standard's dimensions and left out of the interference list.

  • twin.render_work_product records nothing unless store: true: looking at a part never changes the twin.

The release checklist (twin.get_release_checklist) now also holds eda_checks, assembly_dfa, outputs_current, bom_complete and design_files_released, and G8 requires them (the release checklist). twin.create_release_package leaves out any board or schematic that is not its item's head revision, lists them in excluded_design_files, and refuses while one is no item's revision at all and not accepted.

Observability: metaforge_release_path_call_total{tool, outcome}, metaforge_assembly_build_total{outcome}, metaforge_assembly_check_total{outcome}, metaforge_assembly_finding_total{check, severity}, metaforge_release_finding_accepted_total{item, route} and metaforge_release_design_file_excluded_total{kind, reason}; the ItemFeaFailures and AssemblyCheckFailures alerts; and spans twin.measure_dfm, twin.dfm.exact.measure, twin.resolve_concept_component, twin.run_item_fea, twin.build_assembly, twin.check_assembly and twin.accept_release_finding.

Twin adapter: one home for requirements​

Requirement values live only in the constraint set (twin.record_constraint_set). No tool name or required argument changed; two tools behave differently (see twin_schema.md, One home for requirements).

twin.record_document with document_type='prd' records the text as the prd's prose (background, scope, what is out of scope), as the next revision of the project's one prd item (PRD-...; a new title does not start a second prd). Nothing in the text is dropped and the write is never refused for its content. Numbers written with a unit that no requirement in the current constraint set states are reported. The result adds:

FieldMeaning
item_key, revision, item_refThe prd prose revision, as for every definition write.
requirements_homeOne sentence: requirement values go in twin.record_constraint_set, and the prd is rendered from the prose plus the current constraint set (GET /v1/twin/projects/{project_id}/prd).
requirement_refsThe constraint set revisions the text was checked against (["CS-WIDGET@2"]).
stray_requirement_valuesOnly when there are some: the values as written (["2 W", "$20"], at most 20).
requirement_warningOnly with stray values: names them and says to record them with twin.record_constraint_set if they are requirements.

Every other document_type is unchanged.

twin.record_decision accepts an optional depends_on: an array of item refs (KEY@n, or a bare KEY for the current revision; null means not given). Each is pinned to an exact revision and linked with a depends_on edge; the result echoes the pinned refs as depends_on. An unknown item or revision is a tool error and nothing is written. Use it for a decision that rests on the requirements: link CS-...@n instead of restating its values in the rationale.

KiCad Adapter (tool_registry/tools/kicad/)​

PropertyDetails
Docker Imageghcr.io/fidelodok/metaforge-kicad-adapter, published by CI
Base Imagepython:3.11-slim (Debian trixie) + KiCad 9 (kicad, kicad-symbols, kicad-footprints, STEP models for the common families from kicad-packages3d), OpenJDK 25, Freerouting 2.5.0 (pinned, checksummed)
TransportHTTP JSON-RPC on port 8103 (POST /mcp, GET /health); the gateway and sidecar reach it through METAFORGE_ADAPTER_KICAD_URL
Phase 1 ToolsRead-only: kicad.run_erc, kicad.run_drc, kicad.export_bom, kicad.export_netlist, kicad.get_pin_mapping, kicad.export_gerber, kicad.export_drill, kicad.export_pos
Phase 2 ToolsWrite (a new project folder each, never the caller's files): kicad.generate_schematic, kicad.generate_pcb, kicad.edit_pcb, kicad.autoroute_pcb, kicad.export_3d, kicad.render_pcb, kicad.update_components

Phase 1 tools (read-only):

Tool IDCapabilityDescription
kicad.run_ercerc_checkElectrical rules check on schematic
kicad.run_drcdrc_checkDesign rules check on PCB layout
kicad.export_bombom_exportExport BOM from schematic
kicad.export_gerbergerber_exportExport Gerber manufacturing files

Phase 2 tools (write):

Tool IDCapabilityDescription
kicad.generate_schematicschematic_generationCircuit (components as KiCad symbol and footprint lib_ids, nets as REF.PIN) to a schematic of library symbols joined by global labels; then ERC and KiCad's exported netlist compared with the circuit. Returns verdict, erc, netlist_check, power_flags, no_connects, the file
kicad.generate_pcbpcb_generationCircuit with a board to a placed .kicad_pcb (pcbnew worker), pad nets from the schematic's netlist, footprints linked to symbols. A 4-layer board may name inner_planes (In1/In2); any board may set hole_clearance_mm and edge_clearance_mm (copper to board edge, KiCad's 0.5 mm when omitted) to what its fab allows; a component may name its own 3D model. board.power_zones [{net, refs or points, layer, margin_mm}] pours a high-current net (a buck stage's input, switch node and output) over the hull of its pads on the named parts, or inside an outline given as points when that hull would reach over another net's pins, in priority order; the router reaches it as a plane, and kicad.edit_pcb's strip_routing keeps it. A component's placement is honoured (see below), and board.mounting_holes puts holes where given. Returns placements, unplaced, placement_warnings
kicad.edit_pcbpcb_generationAn existing board, copied with its project to a new folder and changed by an ordered list of operations, then re-routed and checked by DRC as kicad.autoroute_pcb does (reroute, default true). Returns applied, placements, overlaps, beyond_board_edge, routing_stripped, routed, verdict
kicad.autoroute_pcbpcb_autoroutePlane-net pads fanned out to locked vias first, then Freerouting over Specctra DSN/SES on a copy, ground pour, then DRC with schematic parity. Returns unrouted, drc, schematic_parity, tracks, vias; pass only when all are zero
kicad.export_3dpcb_3d_exportBoard as STEP or GLB with the library's 3D models; missing_models lists components left out, complete false then
kicad.render_pcbpcb_renderRay-traced PNG, view top, bottom or iso; inline returns base64

Board placement. Positions are in mm from the board outline's top-left corner, x to the right and y down (KiCad's frame), so edge -y is the top edge as the board is drawn and +y the bottom one. A component's placement in kicad.generate_pcb, and a place operation in kicad.edit_pcb, take:

FieldMeaning
position{x_mm, y_mm}: the footprint's anchor. With edge_mount, only the coordinate along that edge is used; without it the part is centred on the edge
rotation_degKiCad orientation, counter-clockwise as drawn. With edge_mount, it overrides the rotation worked out from the footprint
sidetop (default) or bottom (the footprint is flipped)
edge_mount{edge: +x, -x, +y or -y, overhang_mm}: the footprint is turned so its mating side faces that edge, and its fab outline (else its courtyard) reaches overhang_mm beyond it: 0 flush, positive proud, negative set back. The mating side is the side nearest the footprint's "PCB Edge" marker on a user layer (KiCad's USB-C, USB and other edge receptacles carry one), else the side the body reaches furthest beyond its pads. The result is measured on the turned footprint, and a part whose mating side cannot be told is refused by name: give rotation_deg

A part with no position or edge_mount is auto-placed, at the side and rotation given. Fixed parts are placed where they were put even when they overlap, and the overlap is listed.

kicad.edit_pcb operations, applied in order:

opFieldsEffect
moveref, position, optional rotation_degMoves the footprint's anchor
rotateref, rotation_degSets its orientation
placeref, any of position, rotation_deg, side, edge_mountAs a placement above
set_mounting_holeoptional ref, position, optional drill_mmMoves H<n>, or adds the next hole; a new drill replaces the hole
remove_mounting_holerefRemoves a mounting hole (never a part with a net)
set_modelref, model (a .step, .stp or .wrl path)Points the footprint's 3D model at that file, for a footprint KiCad ships without a model; copper and placement are unchanged
strip_routingRemoves every track and via and the outer-layer pours; inner planes stay

The edited board is a new file; record it with twin.record_design_files (work_product_type: pcb_layout, the board's item_key) to make it the next PCB-...@n. | kicad.update_components | component_update | Value, footprint, fields by reference into a new revision, then ERC; a footprint change sets board_stale |

SPICE Adapter (tool_registry/tools/spice/)​

PropertyDetails
Docker Imageghcr.io/fidelodok/metaforge-spice-adapter, published by CI (tool_registry/tools/spice/Dockerfile)
Base Imagepython:3.11-slim + Debian ngspice
TransportHTTP JSON-RPC on port 8104 (POST /mcp, GET /health); the gateway and sidecar reach it through METAFORGE_ADAPTER_SPICE_URL
WorkspaceShares adapter-workspace with the KiCad adapter, so a netlist from kicad.export_netlist is simulated by path
Toolsspice.run_simulation

Tools provided:

Tool IDCapabilityDescription
spice.run_simulationcircuit_simulationRun ngspice in batch mode on netlist text or a netlist_path, with one analysis card built from analysis_type (op, dc, ac, transient) and params. Parses ngspice's ASCII rawfile: per vector final/min/max (AC: magnitude in dB and phase), a decimated waveform keyed with the scale, convergence, and ngspice's errors in log when it fails

Slicer Adapter (tool_registry/tools/slicer/)​

PropertyDetails
Docker Imageghcr.io/fidelodok/metaforge-slicer-adapter, published by CI (tool_registry/tools/slicer/Dockerfile)
Base Imagepython:3.11-slim-trixie + Debian prusa-slicer (2.9.2); PrusaSlicer is AGPL-3.0 and runs as a separate program
TransportHTTP JSON-RPC on port 8106 (POST /mcp, GET /health); the gateway and sidecar reach it through METAFORGE_ADAPTER_SLICER_URL
WorkspaceShares adapter-workspace with the CAD adapters; a model is read by path and each run writes output/slicer/<run id>/ (the G-code and config.ini)
ComposeRuns by default; limited to 2 CPUs and 2 GB, two slices at a time, SLICER_MAX_OPERATION_TIME (600 s) each
Toolsslicer.slice, slicer.list_profiles

Tools provided:

Tool IDCapabilityDescription
slicer.sliceslicingRun prusa-slicer --export-gcode on a workspace .stl, .3mf, .obj, .step or .stp. Loads config_path (a PrusaSlicer config export) when given, then a generated config with the chosen printer and material presets and the per-call overrides. Returns gcode_path, print_time_s, filament_mm, filament_cm3, filament_g, layers, height_mm and the effective settings, all read from the G-code; filament_cost when filament_cost_per_kg is given. A slicer failure is a JSON-RPC error carrying PrusaSlicer's own reason, such as "All objects are outside of the print volume."
slicer.list_profilesslicingThe built-in printer and material presets and the defaults

No configuration may run a program. A config_path or a 3MF project that sets post_process is refused before PrusaSlicer starts, the config loaded last always sets post_process empty and binary_gcode off, and PrusaSlicer runs with no stdin, so its own prompt before running a script reads no.


Render Adapter (tool_registry/tools/render/)​

PropertyDetails
Docker Imageghcr.io/fidelodok/metaforge-render-adapter, published by CI (tool_registry/tools/render/Dockerfile)
Base Imagemcr.microsoft.com/playwright/python:v1.49.1-noble, pinned by digest (Chromium and its libraries); three.js r169 fetched at build time, checked against its SHA-256 and kept in the image
TransportHTTP JSON-RPC on port 8107 (POST /mcp, GET /health); the gateway and sidecar reach it through METAFORGE_ADAPTER_RENDER_URL
ComposeRuns by default; limited to 2 CPUs and 2 GB, two renders at a time, RENDER_MAX_OPERATION_TIME (120 s) each
Toolsrender.model_views

Tools provided:

Tool IDCapabilityDescription
render.model_viewsrenderLoad a GLB (glb_base64, or input_file in the adapter workspace) into a local three.js page in headless Chromium and render the requested views (iso, front, side, back, left, top, bottom, section with an axis and offset). Returns views (one PNG each with its projection, section and mm per pixel), sheet_png_base64 (every view on one image), bbox_mm and the renderer. Read-only

The page and its scripts are answered from local files by Playwright's request routing; any other request is aborted, so a render never reaches a network. In-process (the gateway or sidecar images, which have no browser) a call fails with a message naming the render-adapter container.


OpenFOAM Adapter (tool_registry/tools/openfoam/)​

PropertyDetails
Docker Imageghcr.io/fidelodok/metaforge-openfoam-adapter, published by CI (tool_registry/tools/openfoam/Dockerfile)
Base Imageopenfoam/openfoam11-paraview510 (OpenFOAM Foundation, Ubuntu 20.04), pinned by digest; Python 3.11 added with uv
TransportHTTP JSON-RPC on port 8300 (POST /mcp, GET /health); the gateway and sidecar reach it through METAFORGE_ADAPTER_OPENFOAM_URL
WorkspaceShares adapter-workspace with the CAD adapters; surfaces are read by path and cases are written under openfoam/<run id>/case
ComposeOpt-in under the cfd profile; limited to 8 CPUs and 12 GB, one run at a time
Toolsopenfoam.run_internal_flow

Tools provided:

Tool IDCapabilityDescription
openfoam.run_internal_flowflow_simulationSteady incompressible internal flow through a domain bounded by inlet_stl, outlet_stl and wall_stls (units stl_units, a point inside_point in the fluid). Requires the fluid (density and kinematic viscosity), inlet_velocity_m_s and turbulence (laminar, or kOmegaSST with turbulence_intensity and turbulence_length_scale_m). Runs blockMesh, snappyHexMesh, checkMesh and foamRun (decomposed under mpirun when solver.n_procs is above 1). Returns pressure_drop_pa, inlet and outlet flow, mesh quality, residuals, converged, solution_stable, y_plus and warnings; a failed run returns completed: false with stage_failed, OpenFOAM's reason and a log tail. Invalid input is a JSON-RPC error.

Firmware Adapter (tool_registry/tools/firmware/)​

PropertyDetails
Docker Imageghcr.io/fidelodok/metaforge-firmware-adapter, published by CI (tool_registry/tools/firmware/Dockerfile)
Base Imagepython:3.11-slim, with PlatformIO 6.2.0 and its ST STM32 20.0.0 (STM32Cube for F4, F7, H7) and Espressif 32 7.1.3 (ESP-IDF) platforms installed at image build by building seed projects, and cppcheck and clang-tidy by checking one; Renode 1.17.0 (portable); Espressif QEMU 9.2.2 (xtensa); FreeRTOS-Kernel V11.3.1 sources
TransportHTTP JSON-RPC on port 8105 (POST /mcp, GET /health); the gateway and sidecar reach it through METAFORGE_ADAPTER_FIRMWARE_URL
WorkspaceShares adapter-workspace; a project is copied to firmware/<run id>/project and built there, and emulator runs write under firmware/emulation/<run id>
ComposeOpt-in under the firmware profile; limited to 4 CPUs and 4 GB, one build at a time
NetworkNone needed at run time: toolchains, frameworks and Renode's SVD files are in the image, board data is read from the platforms' manifests, and PlatformIO's upgrade check is pushed out (offline it otherwise waits a minute per call). A build needing a package that is not in the image is not_established, naming the package
Toolsfirmware.build, firmware.static_check, firmware.run_emulated

Tools provided:

Tool IDCapabilityDescription
firmware.buildfirmware_buildCompile project_path (a PlatformIO project) or files with board and framework (stm32cube, espidf). Adds the FreeRTOS kernel to an STM32 project carrying a FreeRTOSConfig.h. Returns verdict (pass, fail, not_established on timeout), error_count, warning_count, diagnostics (file, line, column, severity, message), flash and ram (used_bytes, total_bytes, used_pct), toolchain, elf_path, log_path, and log_tail on failure. A board outside the installed platforms is a JSON-RPC error.
firmware.static_checkfirmware_static_analysispio check on the same project input as firmware.build, with tools (cppcheck default, clangtidy), fail_on (high default) and suppressions ({id, file?, reason}, cppcheck). Returns verdict, passed, findings (tool, severity, category, id, cwe, file, line, column, message), counts per severity, runs (each checker and whether it completed) and log_path.
firmware.run_emulatedfirmware_emulationRun elf_path for board for sim_time_s emulated seconds on Renode (STM32F4-Discovery, Nucleo-F767ZI, Nucleo-H753ZI) or Espressif QEMU (ESP32), and check uart_expect (in order), uart_forbid and, on Renode, memory_expect. On Renode, SysTick follows the firmware's SystemCoreClock, or core_clock_hz when given. Returns verdict, the emulator and its version, each assertion with its status, systick_clock (the clock SysTick ran from and its source), and the UART log. An unmodelled board is not_established with the list of modelled boards.

11. Container Isolation Model​

All tool adapters run in Docker containers with strict security controls.

Docker Run Configuration​

Python
CONTAINER_CONFIG = {
"network_mode": "none", # No external network access
"read_only": True, # Read-only root filesystem
"tmpfs": {"/tmp": "size=256m"}, # Writable temp directory
"mem_limit": "2g", # Memory limit
"cpu_period": 100000, # CPU throttling
"cpu_quota": 200000, # 2 CPU cores max
"pids_limit": 100, # Process limit
"security_opt": ["no-new-privileges:true"],
}

Volume Mounts​

MountContainer PathModePurpose
Project workspace/workspacero (default) or rw (Phase 2 write tools)Design files
Tool output/outputrwTool results and generated files
Temp/tmprw (tmpfs)Scratch space for solver intermediates

Lifecycle​

  1. Create: Container is created from the adapter's Docker image.
  2. Mount: Workspace and output volumes are mounted.
  3. Execute: JSON-RPC request is sent via stdin, response read from stdout.
  4. Collect: Output files are collected from /output.
  5. Destroy: Container is removed after the tool call completes.

For frequently-used tools, a warm pool of pre-started containers can be maintained (configured per adapter). Warm containers are reused for subsequent calls but still have the same isolation properties.


12. Error Taxonomy​

All MCP errors use standard JSON-RPC 2.0 error codes plus MetaForge-specific application codes.

CodeNameDescription
-32600INVALID_REQUESTMalformed JSON-RPC request
-32601METHOD_NOT_FOUNDUnknown method (e.g., tool/call with invalid tool_id)
-32602INVALID_PARAMSTool arguments fail schema validation
-32001TOOL_EXECUTION_ERRORTool ran but produced an error (solver crash, invalid input). Legacy tool/call only — on tools/call this is an isError result instead (§4.4.1)
-32002RESOURCE_NOT_FOUNDNo such resource. The code the MCP spec assigns, so a spec-aware client reads it this way whatever we intend
-32003TOOL_UNAVAILABLETool adapter is unhealthy or not registered
-32005RESOURCE_READ_ERRORThe resource exists and could not be read
-32006TOOL_TIMEOUTTool exceeded its timeout limit
-32007AUTH_DENIEDA credential was rejected

These live in one place, mcp_core/protocol.py, and every module imports them. Three tables once disagreed: -32002 meant TOOL_TIMEOUT in one, auth-denied in another, and the adapters emitted -32004 for a missing resource — while the spec reserves -32002 for exactly that. A client branching on -32002 could not tell a missing resource from a timeout from a rejected credential, which is the whole purpose of a numeric code.

TOOL_TIMEOUT and AUTH_DENIED moved to free codes rather than the spec-assigned one. Both are MetaForge-specific, so no client outside this repo was reading them.

Error Response Format​

Python
class McpError(Exception):
"""Base exception for MCP protocol errors."""

def __init__(self, code: int, message: str, data: McpErrorData | None = None):
self.code = code
self.message = message
self.data = data
super().__init__(message)


class ToolExecutionError(McpError):
def __init__(self, tool_id: str, details: str, duration_ms: float = 0):
super().__init__(
code=-32001,
message="Tool execution failed",
data=McpErrorData(
error_type="TOOL_EXECUTION_ERROR",
tool_id=tool_id,
details=details,
duration_ms=duration_ms,
),
)


class ToolTimeoutError(McpError):
def __init__(self, tool_id: str, timeout_seconds: int):
super().__init__(
code=-32006,
message=f"Tool exceeded timeout of {timeout_seconds}s",
data=McpErrorData(
error_type="TOOL_TIMEOUT",
tool_id=tool_id,
details=f"Execution exceeded {timeout_seconds} second limit",
),
)


class ToolUnavailableError(McpError):
def __init__(self, tool_id: str):
super().__init__(
code=-32003,
message="Tool adapter is unavailable",
data=McpErrorData(
error_type="TOOL_UNAVAILABLE",
tool_id=tool_id,
details="Adapter is unhealthy or not registered",
),
)

Session edits persist; tool results​

A session is one live FreeCAD document, so an edit made in one call is visible to the next.

  • freecad.transform_object now returns the verified placement (position in mm, rotation as axis plus angle_deg) and the measured volume_mm3, surface_area_mm2 and global bounding_box. It raises instead of reporting success if the placement did not stick.
  • freecad.measure, describe_model and the bounding box above are measured in the global frame (own placement plus parent App::Part placements), so moving an assembly container is visible when a child is measured, and the reverse.
  • freecad.execute_code returns the script's result variable as plain data under result: Vectors, Placements, bounding boxes and document objects are converted, anything else falls back to repr, and the value is capped at 20000 serialized characters (result_truncated: true when cut). When result is a document object it is still registered and returned as obj_id.
  • A script that assigns obj.Shape on a parametric object (for example a Part::Box primitive) used to lose the edit to the recompute that follows. The new shape is now pinned, and survives later transform_object calls.

Mesh coordinate frame​

freecad.generate_mesh returns a mesh in the Digital Twin's coordinate frame: node coordinates equal the committed work product's bounding_box axes. If the STEP carries a Placement as an assembly transform (a part authored on a rotated plane), which gmsh's reader drops, the placement is baked into the geometry before meshing (placement_baked: true). The result also carries surface_sets (named surface set to bbox_mm, centroid_mm, area_mm2, normal), mesh_bbox_mm and coordinate_frame: "twin", so a caller picks fixed and load faces by position. calculix.run_fea's load_force_n is expressed in this same frame.

freecad.export_model keeps the stored STEP in the same frame the twin records. Import.export stores an object's Placement (from transform_object, or a sketch on a rotated plane) as an assembly transform that gmsh and Part.Shape.read drop, so the stored file's own axes used to differ from the committed bounding_box (cycled axes). Export now checks the file read placement-blind against the live placed bounding box and, on a mismatch, re-exports with placements baked into the geometry (Labels kept). The volume_mm3, surface_area_mm2 and bounding_box it returns are measured from the exported bytes. The mesh-time bake above still covers STEPs stored before this fix.

freecad.export_model can write part colours into the STEP. Headless FreeCAD has no ViewObject, so Import.export writes no colours and parts rendered uniform grey, while the viewer takes colours only from the model's STEP (no render-time palette). Pass material (a recorded material string such as 18 mm birch plywood or PETG), color ([r, g, b], 0-1 or 0-255) or part_materials (an assembly part Label mapped to its material, for per-part colours). The colour is authored into the final STEP bytes as COLOUR_RGB / STYLED_ITEM entities, after the placement bake, so the bake's re-export cannot drop it. An explicit color wins over material; an unknown material (or none) leaves the part uncoloured, since no colour is invented. The table lives in tool_registry/tools/freecad/materials_appearance.py (case-insensitive whole-word match, first row wins, so birch plywood is matched before plywood) and is meant to move into the materials library. The STEP-to-GLB converter keeps these colours (it reads them through XCAF), and the viewer renders the GLB's own materials. The colour chain is STEP COLOUR_RGB (sRGB, the table value) to GLB baseColorFactor (linear, as glTF requires; OCCT returns linear, so 0.87 is stored as about 0.73, which is correct and not a darkening) to renderer output (sRGB). The viewer pins outputColorSpace to sRGB and uses Neutral tone mapping (dashboard/src/components/viewer/viewerColor.ts) instead of ACES Filmic, which had been darkening and desaturating flat part colours, so a 0.87 table value displays as about 0.87. A converter test (tools/occt-converter/test_convert.py, TestColourChain) and a viewer test pin the chain.

freecad.import_step keeps each part's STEP colour. Headless Import.insert keeps geometry and Labels but drops colours, so a coloured part imported and exported again used to come out grey. The import reads the source file's colours per PRODUCT name (read_step_colours in materials_appearance.py, following STYLED_ITEM through the presentation style chain to COLOUR_RGB), records each component's colour on its session object (metadata.color, metadata.color_source: imported_step), and returns it per part as parts[].color ([r, g, b] 0-1, or null when the file has none). A component matches its product by Label (FreeCAD's 001 de-duplication suffix allowed); a single-component import whose file has exactly one colour takes that colour. freecad.export_model then uses the recorded colour as the lowest-priority source: part_materials first, then color / material, then the imported colour. A single imported part exports in its own colour, and an assembly built from imported parts gives each part (matched by its live Label) its recorded colour, so no colour arguments are needed to keep them.

freecad.export_model also returns stored_properties (volume_mm3, surface_area_mm2, center_of_mass, bounding_box), measured from the exact STEP it wrote. The geometry stash threads it into twin.commit_geometry, which records it in preference to the session object's measurement (bbox_mm, volume_mm3, surface_area_mm2, center_of_mass_mm). If the session's bounding box differs from the stored one by more than 0.01 mm, a commit_geometry_session_stored_bbox_diverge warning is logged and the session values are kept as metadata.session_properties.

twin.commit_geometry takes a material string (what the part is made of, normally the material chosen at the route gate) and stores it as the node's material; when it is not given, a material inside properties is used, which is what a FreeCAD or CadQuery result carries. The design gate's material requirement reads that value, so a part committed without one fails it with "records no material".

MetaForge documentationGateway schema