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.mdReferenced 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
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.
"""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.
"""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
| Mode | Use Case | Connection |
|---|---|---|
| stdio | Local Docker containers (default) | Client spawns container process, communicates via stdin/stdout |
| HTTP | Remote tool servers, shared instances | Client 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:
| Request | What it does |
|---|---|
POST /mcp with a JSON-RPC request | dispatches 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 response | the client answering a request the server sent (elicitation/create), routed by id and acknowledged 202 |
GET /mcp with Mcp-Session-Id | a long-lived SSE stream the server pushes requests down |
DELETE /mcp with Mcp-Session-Id | ends 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
Originat 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.aiandhttps://claude.com, for the web connector;- this server's public origin, when
METAFORGE_OAUTH_ISSUERnames it; - anything listed in
METAFORGE_MCP_ALLOWED_ORIGINS(comma separated, for examplehttps://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:
code | Meaning |
|---|---|
not_found | a project or entity outside the account's projects, worded exactly as one that does not exist |
project_required / entity_required | the tool needs a project (or the id it names) on a shared server |
tool_not_scoped | the tool, or one of its arguments, cannot be traced to a project and is refused |
library_read_only | the 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_in | a token not bound to a person, such as one issued before the identity login |
scope_unavailable | the provider or an owner lookup could not answer; retryable |
registration_failed | project.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:
initializetakes the handshake path, exactly as before.- A request whose
_metanames a revision we speak is served as before. - A request whose
_metanames any other revision is refused with the spec'sUnsupportedProtocolVersionError(-32022, and HTTP400), whosedata.supportedlists our revisions newest first. - Over HTTP, a
MCP-Protocol-Versionheader that disagrees with the_metarevision is refused withHeaderMismatch(-32020, HTTP400). A header with no_metarevision (a2025-06-18client) 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._metamust carryio.modelcontextprotocol/protocolVersionandio.modelcontextprotocol/clientCapabilities; a request without the capabilities is refused with-32602(HTTP400). The client's revision and capabilities hold for that request only and never replace what a handshake client declared.server/discoveranswers withsupportedVersions(newest first),capabilitiesandinstructions.- Every result carries
resultType: "complete"and_meta["io.modelcontextprotocol/serverInfo"].server/discover, the*/listmethods andresources/readalso carryttlMsandcacheScope(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-VersionandMcp-Method, andMcp-Namefortools/call,prompts/getandresources/read(base64 values in the=?base64?...?=form are decoded), each matching the body; otherwiseHeaderMismatch(-32020, HTTP400). An unknown method is HTTP404with-32601. NoMcp-Session-Idis 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.openandsession.startmint 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_sessionargument 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_idargument outranks it. The tool, the approval policy, a delegated decision and the approval key all see that project, so a tool with noproject_idargument is decided by the policy of the project the handle names. A handshake client that does not keepMcp-Session-Idmay pass a handle the same way; it is taken out and honoured, though only2026-07-28callers are minted one. - A handle is a session id, not a credential: it carries scope, never
authority, exactly as
X-MetaForge-Sessiondoes. That header still works for any client that sends it, and handshake clients keepMcp-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/callrefused that way (a held write rejected or with no gate, a tool that failed, the approval ledger down) is a normal result withisError: 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
(
-32001becomes-31001), with the original inerror.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":
{"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_gateasks through the same mechanism, so a2026-07-28client decides a gate in its chat as a handshake client does. requestStateis 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,inputResponseswithout a state, or an approval used a second time is refused with-32602, and nothing runs. SetMETAFORGE_MCP_STATE_KEYto 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 andforge 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.progressTokenand the transport can reach the client for that call, the server sendsnotifications/progressas soon as the hold exists.messagenames the approval id and the dashboard Approvals page (a link whenMETAFORGE_DASHBOARD_URLis set);totalis the hold window in seconds. It repeats everyMETAFORGE_APPROVAL_PROGRESS_INTERVAL_SECONDS(default 10) withprogressincreasing, so a client that resets its timeout on progress keeps waiting. Over HTTP, a call with aprogressTokenandtext/event-streaminAcceptis eligible for its own SSE stream whether or not the session declaredelicitation; 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 withisError: trueand_meta.approval.held = true,approval_id,expires_atandnext_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 forMETAFORGE_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 explicittimeout_secondscaps it. - Outcome. A held
tools/callis the result above. A refused call is a JSON-RPC error withdata.code = "approval_required"anddata.outcomeone ofrejected,timed_out,cancelledornot_configured, plusapproval_id,route(dashboard,elicitation,retryorpolicy),where,held_secondsandwindow_secondswhen known.messagestates the same facts, because it is what a client shows the model. The legacytool/calldialect also gets a held call as such an error, withdata.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/createfor any reason (window ended, approval decided elsewhere or expired, call cancelled, call stream closed), it sendsnotifications/cancelledwithparams.requestIdset to that request's id and areason. Over HTTP it goes on the call's own stream while that is open, before the result, else on an openGET /mcp; over stdio it is written to stdout. The server logsmcp_elicitation_withdrawnwithdelivered. - Late answers. A response to a withdrawn request is acknowledged
(
202over HTTP). For a durable hold it is recorded on the approval (mcp_elicitation_late_answer_to_record, thenelicitation_late_answer_recorded): an accept approves it and the identical retry runs. It never runs the call itself. Otherwise it is logged asmcp_elicitation_late_response_ignoredand 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:
{
"jsonrpc": "2.0",
"id": "<request-id>",
"method": "<method-name>",
"params": { ... }
}
4. Message Types
4.1 tool/list — Discover Available Tools
Request:
{
"jsonrpc": "2.0",
"id": "req-001",
"method": "tool/list",
"params": {
"capability": "stress_analysis"
}
}
Response:
{
"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:
{
"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):
{
"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:
{
"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:
{
"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 withisError: true, the reason as text content, and_meta.errorcarryingtoolId / 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 legacytool/calldialect, whose callers already readdata.details.
{
"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
{
"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:
{
"jsonrpc": "2.0",
"id": "req-003",
"method": "health/check",
"params": {}
}
Response:
{
"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:
{
"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.
"""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
| Field | Type | Description |
|---|---|---|
tool_id | str | Unique tool identifier: <adapter_id>.<method_name> |
adapter_id | str | Adapter that provides this tool |
name | str | Human-readable tool name |
description | str | What the tool does |
capability | str | Capability category (e.g., "stress_analysis", "erc_check") |
input_schema | dict | JSON Schema for tool parameters |
output_schema | dict | JSON Schema for tool results |
phase | int | Minimum phase where this tool is available |
resource_limits | ResourceLimits | CPU, 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.
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
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
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
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
| Condition | Action |
|---|---|
Tool returns error, skill is idempotent: true | Retry up to retries times (from definition.json) |
Tool returns error, skill is idempotent: false | No retry, propagate error |
| Timeout | Kill container, return TOOL_TIMEOUT error. Retry only if idempotent. |
| Container crash | Return TOOL_EXECUTION_ERROR. Retry only if idempotent. |
| Adapter unhealthy | Return 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:
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:
"""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:
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/)
| Property | Details |
|---|---|
| Docker Image | ghcr.io/fidelodok/metaforge-calculix-adapter, published by CI |
| Base Image | python:3.11-slim + calculix-ccx |
| Transport | stdio |
| Tools | calculix.run_fea, calculix.run_thermal, calculix.validate_mesh |
Tools provided:
| Tool ID | Capability | Description |
|---|---|---|
calculix.run_fea | stress_analysis | Static stress FEA using CalculiX solver |
calculix.run_thermal | thermal_analysis | Thermal analysis (steady-state and transient) |
calculix.validate_mesh | mesh_validation | Validate mesh quality (aspect ratio, element types) |
CadQuery Adapter (tool_registry/tools/cadquery/)
| Property | Details |
|---|---|
| Docker Image | ghcr.io/fidelodok/metaforge-cadquery-adapter, published by CI |
| Base Image | python:3.11-slim (multi-stage) |
| Transport | stdio |
| Tools | cadquery.create_parametric, cadquery.boolean_operation, cadquery.get_properties, cadquery.export_geometry, cadquery.execute_script, cadquery.create_assembly, cadquery.generate_enclosure |
Tools provided:
| Tool ID | Capability | Description |
|---|---|---|
cadquery.create_parametric | cad_generation | Generate parametric CAD geometry from shape type and dimensions |
cadquery.boolean_operation | cad_operations | CSG boolean operations (union, subtract, intersect) |
cadquery.get_properties | cad_analysis | Geometric properties (volume, area, center of mass, bounding box, inertia) |
cadquery.export_geometry | cad_export | Export to STEP/STL/OBJ/BREP/AMF/SVG |
cadquery.execute_script | cad_scripting | Run a CadQuery Python script in an OS-isolated child process (see below) |
cadquery.create_assembly | cad_assembly | Multi-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_enclosure | cad_enclosure | PCB 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.
| Variable | Default | Meaning |
|---|---|---|
CADQUERY_RUNNER_ROOT | /run/cadquery-runner | Where each run's private folder is made (a tmpfs under compose) |
CADQUERY_RUNNER_UIDS | 61000-61003 | The uid pool: one uid per concurrent run; concurrency is the smaller of the pool and CADQUERY_RUNNER_MAX_CONCURRENT |
CADQUERY_RUNNER_MAX_CONCURRENT | 2 | Script children running at once; the container's 6G memory limit is sized for two |
CADQUERY_RUNNER_REQUIRE | uid,landlock,seccomp | Layers that must hold; a missing one refuses the run |
CADQUERY_RUNNER_MEMORY_MB | 2048 | Memory 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_MB | 16384 | Address-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_MB | 64 | Largest file the child may write (its console log included) |
CADQUERY_RUNNER_MAX_OUTPUT_MB | 64 | Largest result the adapter accepts |
CADQUERY_RUNNER_STARTUP_GRACE_S | 15 | Added to the script's timeout for interpreter and CadQuery start-up |
CADQUERY_SCRIPT_ISOLATION | process | in_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/)
| Property | Details |
|---|---|
| Docker Image | ghcr.io/fidelodok/metaforge-freecad-adapter, published by CI (see below) |
| Base Image | Debian system Python 3 (FreeCAD's compiled extension requires it, not a python.org image) |
| Transport | stdio |
| Tools | Stateful 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:
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.
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.
| Argument | Meaning |
|---|---|
item_key | The 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. |
supersedes | Node id of an earlier revision; the write revises that node's item. |
change_reason | Why 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:
{
"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_historylists the caller's own open drafts and never another run's; closed drafts are always listed. Every revision carriesstatus(committed,draft,approved,rejected,abandoned),change_set,phase,gateandstatus_reason. The result addscurrent({"revision", "node_id", "ref"}), what this caller reads as current: its run's draft if it has one, else the head.itemaddsdraft_revision,draft_node_idanddraft_refwhen the caller's run has a draft;head_*is always the approved head (null for an item that only has drafts).twin.get_nodeacceptsitem_keyinstead ofnode_id: a bareKEYreturns the nodecurrentnames,KEY@nthat revision (only if the caller can see it), with an optionalproject_idwhen the key exists in several projects.node_idis no longer required whenitem_keyis 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}.collectionsis what the person did in the browser, keyed by collection and document id; read it before writing a new config.studio_urlis the absolute dashboard link to the studio (<METAFORGE_DASHBOARD_URL>/create/<id>?stage=imagine), the one to give a person;engine_page_urlis the bare engine page (<METAFORGE_GATEWAY_PUBLIC_URL>plusengine_url, falling back toMETAFORGE_PUBLIC_URL), whose token expires after ten minutes. Each isnullwhen its host is not configured.twin.imagine_put_studioreturns the same two links.twin.imagine_put_studio(additive): takesconfig, checks it with the merged formgraph rules and writes it as the nextIMG-STUDIOrevision. The product context goes inline asconfig.context; a context folder path or a referencefileis 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, keyedpart:<studio part id>,selection:<node id>,board-part:<order code>orboard:<name>, withrelation(same,refined,replaced,develop_only,imagine_only) and one object per stage (imagine,develop,check,make);adoptis 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, withstatus(same,differs,accepted,unmeasured,unpaired),studio{part_id, size_mm},develop{item_ref, node_id, name, size_mm}anddelta_mm(Develop minus studio, studio axes). See Form changes from Develop.twin.imagine_accept_form(additive): takesbase_revision, a row key asrowand optionalchanges(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): takesbase_revisionand a thread key asthreadand 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): takesbase_revisionandchanges(1 to 64), each{op, path, value}in the style of JSON Patch (RFC 6902):add,replaceorremoveat a JSON Pointer. In a list of objects with anid, a path segment may name an item by itsid(/form/authored/parts/display/code) as well as by its index;-appends withadd. The changes apply in order to the head's config and the result is checked and written exactly astwin.imagine_put_studiowrites a config, as the next revision. A head that is no longerbase_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/studiowith{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. Takeswork_product_id(a STEP, GLB, STL or OBJ in the twin),id(a slug),title,role(contextby default,envelope,targetorlook), and optionallynote,units,up,at(mm),rotate(degrees about X, Y, Z),color(hex) andopacity(0.05 to 1). The studio centres the mesh on X and Z with its lowest point at Y = 0, then moves it toat; the storedoriginis the file point that lands there, in studio axes, soat = W - (P - origin)puts file point P at W.twin.imagine_patch_studiochanges 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 intocontext.referenceswith its full size instats, 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. Takesconfig(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) andgates. Returns the verification service's report:verdict(invalid,needs_agent,blocked_external,needs_person,ready_for_handover),level(V0 to V2),gatesandfindings, each with atarget, astatus, aresolver(agent,personorexternal) and, for the agent's, afixthat names what is needed and never a value. The report comes back as a result, includinginvalidandblocked_external; when the service cannot be reached the result isblocked_externalwith oneverification.servicefinding. The tool never decides the verdict itself. Seedocs/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. Takespart(the object as it goes incontext.components.parts:id,role,name,mpn, optionallygeometryandkicad.symbol, and optionallypackage_text) and returnsrung(existing,exact,approximationorplaceholder),geometry(envelope, body,fidelity,fidelity_basis,source),tried(each rung and why it was or was not used) andmessage.exactmeans a CAD kernel measured the KiCad library's own model; a size only estimated from the file is anapproximation. Passpackage_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, anapproximationwhose size is read (size_basisread); text it does not recognise is skipped with a reason. The KiCad rung reads the folder named byMETAFORGE_KICAD_LIBRARY_DIR(holdingsymbols,footprintsand3dmodels) and is skipped with a reason when it is unset. Nothing is written: copygeometryinto 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 returnsstatus(ready,error,none,not_authoredorunavailable), each part'skind,size,trianglesanderror, and the screenshots as image blocks. Takesrevision(the head; after a write, name the revision it returned, for the same reason astwin.imagine_validate) andset({parameter: number}, moved in the page and never saved, then it looks again and addsafter,compareandrequests_after_change). A part that fails is named and the rest is still drawn. It also returnsmeasured:overhang_share(an upper bound),support(margin_mmandtip_angle_degof the centre of mass against the flat base, negative when it would tip over,nullwith no flat base),overlaps(component boxes that overlap) andnotes, andcompare.measured_changedafter aset. V2 screening, never a verification. fails is named and the rest is still drawn.unavailablecarriesinstall: theplaywrightpackage 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 callscadquery.dfm_measureitself, then stores the exactdfm_finding_set. Returns{measured, item_ref, component_id, status, complete, findings, not_assessed, finding_set_id}, ormeasured: falsewithreason.twin.evaluate_dfmtakesmeasure(default true) and does the same for every validated part that has no exact analysis yet, listing them undermeasured.cadquery.dfm_measurestill takesstep_base64for a STEP that is not in the twin. -
twin.resolve_concept_component(additive, registered when the gateway injectsrelease_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, itsdecision_node_idand the checklist'scomponents_exactstatus. 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 withfreecad.generate_meshand solves withcalculix.run_fea, both over MCP.fixedandloadedare 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 andrecord_with, thetwin.record_documentarguments that pin it to the revision. -
twin.create_baselineandtwin.create_release_packageclose the path. The package now pins adesign_filesmanifest with amanifest_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 unapprovedrelease_approvalas the agent acting for the person. It runs only when the owner setsMETAFORGE_ALLOW_AGENT_RELEASE=trueand the request carriesX-MetaForge-AgentandX-MetaForge-On-Behalf-Of; thentwin.create_baselinealso runs without a hold, recorded asagent:<agent> on behalf of <person>. Otherwise it is refused at once withhuman_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 theX-MetaForge-Agentit was staged with), as that agent for the person. It runs only when the owner setsMETAFORGE_ALLOW_AGENT_HUMAN_AUTHORITY=trueand the request carries both agent headers; otherwise it is refused at once withhuman_authority_required, and an upload another agent or a person staged is refused by name. Under the same flag and headers,library.register_*andlibrary.update_*run without the hold and the entry recordsagent <agent> on behalf of <person>with anauthorityofdelegated, never verified by the person.library.dispatch_jobandvendor.place_orderare 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'sdesignationis read the waylibrary.standard_partreads it (ISO 4762 M4x25,M2.5x6,ISO 2338 4x30); it goes into the STEP as ashapepart ofcadquery.create_assembly({generator, params, z_offset}, made from the standard's dimensions) and intolayout.fasteners. Stages each part revision's STEP, builds the assembly withcadquery.create_assemblyover MCP (nooutput_path: the adapter writes into a folder of its own and returnsassembly_file, which the gateway reads) and commits it through the geometry recorder as the next revision of anassemblyitem, keeping the layout (metadata.assembly_layout). Returns the commit result withitem_ref, thelayoutand the build'sinterferences. A board is placed as the cad_modelkicad.export_3dmade of it (committed withtwin.commit_geometry,source_tool: kicad.export_3d), which records itsboard_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}}.fastenersandjointsdefault to the assembly's own. A connector named byreferencetakes 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'sconnector_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 withcadquery.check_interference(read only) and records anassembly_checkpinned 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 stableid, aseverityand thepartsinvolved. 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 approvedwaiverpinned to the revisions it is about. Held for a person, whose approval names the approver; withMETAFORGE_ALLOW_AGENT_RELEASE=trueand 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_filestakessource_ref(CAD-...@n,PCB-...@n,FW-...@n; a bare key pins the current revision) and returns the pin it recorded assource_ref. Without it the pin comes from the sources, or for G-code from thesource.jsonslicer.slicewrites beside it. The release checklist'soutputs_currentandtwin.create_release_packagerefuse an output made from an older revision or with no source (output source pins).work_product_type: bomrecords a BOM file (CSV, TSV or JSON): the board's withsource_refthePCB-...@n, the assembly's with theASM-...@n; it returnsline_itemsandbom_scopeand keeps the lines inmetadata.bom_lines(BOM files). -
library.standard_parttakesdesignationalone (ISO 4762 M4x25,M2.5x6,ISO 7089 M4,ISO 2338 4x30) as well asfamilyandsize, and knowsiso2338parallel pins. -
cadquery.create_assemblytakes a part asshape: {generator: socket_head_cap_screw | parallel_pin | washer | hex_nut, params, z_offset}in place offile, made from a standard's dimensions and left out of the interference list. -
twin.render_work_productrecords nothing unlessstore: 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:
| Field | Meaning |
|---|---|
item_key, revision, item_ref | The prd prose revision, as for every definition write. |
requirements_home | One 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_refs | The constraint set revisions the text was checked against (["CS-WIDGET@2"]). |
stray_requirement_values | Only when there are some: the values as written (["2 W", "$20"], at most 20). |
requirement_warning | Only 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/)
| Property | Details |
|---|---|
| Docker Image | ghcr.io/fidelodok/metaforge-kicad-adapter, published by CI |
| Base Image | python: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) |
| Transport | HTTP JSON-RPC on port 8103 (POST /mcp, GET /health); the gateway and sidecar reach it through METAFORGE_ADAPTER_KICAD_URL |
| Phase 1 Tools | Read-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 Tools | Write (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 ID | Capability | Description |
|---|---|---|
kicad.run_erc | erc_check | Electrical rules check on schematic |
kicad.run_drc | drc_check | Design rules check on PCB layout |
kicad.export_bom | bom_export | Export BOM from schematic |
kicad.export_gerber | gerber_export | Export Gerber manufacturing files |
Phase 2 tools (write):
| Tool ID | Capability | Description |
|---|---|---|
kicad.generate_schematic | schematic_generation | Circuit (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_pcb | pcb_generation | Circuit 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_pcb | pcb_generation | An 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_pcb | pcb_autoroute | Plane-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_3d | pcb_3d_export | Board as STEP or GLB with the library's 3D models; missing_models lists components left out, complete false then |
kicad.render_pcb | pcb_render | Ray-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:
| Field | Meaning |
|---|---|
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_deg | KiCad orientation, counter-clockwise as drawn. With edge_mount, it overrides the rotation worked out from the footprint |
side | top (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:
op | Fields | Effect |
|---|---|---|
move | ref, position, optional rotation_deg | Moves the footprint's anchor |
rotate | ref, rotation_deg | Sets its orientation |
place | ref, any of position, rotation_deg, side, edge_mount | As a placement above |
set_mounting_hole | optional ref, position, optional drill_mm | Moves H<n>, or adds the next hole; a new drill replaces the hole |
remove_mounting_hole | ref | Removes a mounting hole (never a part with a net) |
set_model | ref, 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_routing | Removes 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/)
| Property | Details |
|---|---|
| Docker Image | ghcr.io/fidelodok/metaforge-spice-adapter, published by CI (tool_registry/tools/spice/Dockerfile) |
| Base Image | python:3.11-slim + Debian ngspice |
| Transport | HTTP JSON-RPC on port 8104 (POST /mcp, GET /health); the gateway and sidecar reach it through METAFORGE_ADAPTER_SPICE_URL |
| Workspace | Shares adapter-workspace with the KiCad adapter, so a netlist from kicad.export_netlist is simulated by path |
| Tools | spice.run_simulation |
Tools provided:
| Tool ID | Capability | Description |
|---|---|---|
spice.run_simulation | circuit_simulation | Run 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/)
| Property | Details |
|---|---|
| Docker Image | ghcr.io/fidelodok/metaforge-slicer-adapter, published by CI (tool_registry/tools/slicer/Dockerfile) |
| Base Image | python:3.11-slim-trixie + Debian prusa-slicer (2.9.2); PrusaSlicer is AGPL-3.0 and runs as a separate program |
| Transport | HTTP JSON-RPC on port 8106 (POST /mcp, GET /health); the gateway and sidecar reach it through METAFORGE_ADAPTER_SLICER_URL |
| Workspace | Shares 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) |
| Compose | Runs by default; limited to 2 CPUs and 2 GB, two slices at a time, SLICER_MAX_OPERATION_TIME (600 s) each |
| Tools | slicer.slice, slicer.list_profiles |
Tools provided:
| Tool ID | Capability | Description |
|---|---|---|
slicer.slice | slicing | Run 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_profiles | slicing | The 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/)
| Property | Details |
|---|---|
| Docker Image | ghcr.io/fidelodok/metaforge-render-adapter, published by CI (tool_registry/tools/render/Dockerfile) |
| Base Image | mcr.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 |
| Transport | HTTP JSON-RPC on port 8107 (POST /mcp, GET /health); the gateway and sidecar reach it through METAFORGE_ADAPTER_RENDER_URL |
| Compose | Runs by default; limited to 2 CPUs and 2 GB, two renders at a time, RENDER_MAX_OPERATION_TIME (120 s) each |
| Tools | render.model_views |
Tools provided:
| Tool ID | Capability | Description |
|---|---|---|
render.model_views | render | Load 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/)
| Property | Details |
|---|---|
| Docker Image | ghcr.io/fidelodok/metaforge-openfoam-adapter, published by CI (tool_registry/tools/openfoam/Dockerfile) |
| Base Image | openfoam/openfoam11-paraview510 (OpenFOAM Foundation, Ubuntu 20.04), pinned by digest; Python 3.11 added with uv |
| Transport | HTTP JSON-RPC on port 8300 (POST /mcp, GET /health); the gateway and sidecar reach it through METAFORGE_ADAPTER_OPENFOAM_URL |
| Workspace | Shares adapter-workspace with the CAD adapters; surfaces are read by path and cases are written under openfoam/<run id>/case |
| Compose | Opt-in under the cfd profile; limited to 8 CPUs and 12 GB, one run at a time |
| Tools | openfoam.run_internal_flow |
Tools provided:
| Tool ID | Capability | Description |
|---|---|---|
openfoam.run_internal_flow | flow_simulation | Steady 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/)
| Property | Details |
|---|---|
| Docker Image | ghcr.io/fidelodok/metaforge-firmware-adapter, published by CI (tool_registry/tools/firmware/Dockerfile) |
| Base Image | python: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 |
| Transport | HTTP JSON-RPC on port 8105 (POST /mcp, GET /health); the gateway and sidecar reach it through METAFORGE_ADAPTER_FIRMWARE_URL |
| Workspace | Shares adapter-workspace; a project is copied to firmware/<run id>/project and built there, and emulator runs write under firmware/emulation/<run id> |
| Compose | Opt-in under the firmware profile; limited to 4 CPUs and 4 GB, one build at a time |
| Network | None 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 |
| Tools | firmware.build, firmware.static_check, firmware.run_emulated |
Tools provided:
| Tool ID | Capability | Description |
|---|---|---|
firmware.build | firmware_build | Compile 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_check | firmware_static_analysis | pio 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_emulated | firmware_emulation | Run 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.