# AGENTS.md

## Project Name

`aieng-freecad-mcp`

## Purpose

This project implements a FreeCAD-based MCP server for controlled CAD/CAE execution, inspection, and evidence writeback for `.aieng` packages.

The MCP allows AI agents to ask FreeCAD and related CAE tools to perform bounded operations such as:

- CAD model inspection
- parametric model regeneration
- guarded CAD modification
- STEP/FCStd export
- CAE preprocessing
- mesh generation through FreeCAD-supported or external meshers where available
- CalculiX deck export
- solver execution where explicitly requested
- post-processing result extraction
- evidence and provenance writeback into `.aieng`

The MCP is an execution adapter. It is not the core engineering model format.

`.aieng` remains the semantic, evidence, provenance, and claim-tracking package.

---

## Optional `.aieng` Integration

`.aieng` is an enhancer, not a hard dependency.

FreeCAD MCP must support two modes:

### Standalone mode

When no `.aieng` package is provided, the MCP should still be useful as a direct AI-to-FreeCAD CAD/CAE interface.

In standalone mode:

- tools operate from explicit request inputs
- package-level constraints are unavailable
- evidence is returned in the tool response but not persisted to `.aieng`
- claim status is never advanced
- responses should warn when package-level context is absent for operations that would benefit from it

### `.aieng`-enhanced mode

When a `.aieng` package is provided, the MCP should use it as structured engineering context.

In `.aieng`-enhanced mode:

- read task specs, constraints, feature graph, simulation setup, evidence index, claim map, and completeness report when present
- enforce allowed operations where specified
- reject protected-region or semantic-only CAD edits where detectable
- record generated artifacts, evidence, and provenance back into `.aieng`
- do not automatically advance claims

FreeCAD MCP should be useful alone, but safer, smarter, and more auditable with `.aieng`.


## Core Product Boundary

The stable asset is the `.aieng` package.

The FreeCAD MCP is a controlled execution window into FreeCAD and CAE tools.

Use this mental model:

> `.aieng` is the house.  
> MCP tools are windows and doors into the house.  
> FreeCAD is an external CAD/CAE execution environment.

The MCP may execute FreeCAD operations.

The MCP must record what happened back into `.aieng`.

The MCP must not silently convert execution into engineering truth.

---

## What This Project Does

This project may:

- Open and inspect FreeCAD documents.
- Inspect STEP/FCStd-derived geometry where supported.
- Extract FreeCAD object trees and parametric properties.
- Apply guarded parametric edits when executable edit metadata exists.
- Recompute FreeCAD documents.
- Export modified CAD artifacts.
- Create simple FEM analysis setups.
- Generate or request meshes through FreeCAD-supported meshers.
- Export CalculiX decks.
- Run CalculiX only when explicitly requested.
- Extract deterministic numeric result observations.
- Record evidence into `results/evidence_index.json`.
- Record provenance into `provenance/tool_trace.json`.
- Link evidence to claim IDs.
- Propose claim updates.
- Explicitly update claim status only when requested and supported by traceable evidence.

---

## What This Project Does Not Do

This project must not:

- Replace `.aieng` as the source-of-truth package.
- Treat FreeCAD files as the only source of engineering meaning.
- Invent missing CAD/CAE information.
- Perform arbitrary natural-language CAD modeling.
- Execute arbitrary Python generated by an AI model.
- Execute arbitrary shell commands from tool input.
- Perform unconstrained B-rep editing.
- Guarantee topology-stable face IDs unless explicitly supported by evidence.
- Automatically advance engineering claims after import or execution.
- Declare a design safe without explicit solver evidence and claim criteria.
- Hide unsupported, missing, or uncertain information.
- Modify protected regions unless explicitly allowed by package constraints.
- Optimize designs unless a future scoped optimizer adapter is explicitly added.

---

## Relationship to `.aieng`

`.aieng` is a CAD/CAE-to-AI semantic and evidence package.

The MCP must treat structured `.aieng` resources as authoritative.

Structured JSON/YAML resources are source of truth.

Markdown summaries are derived aids only.

Important package resources include:

- `manifest.json`
- `geometry/source.step`
- `geometry/normalized.step`
- `geometry/modified_*.step`
- `geometry/topology_map.json`
- `graph/feature_graph.json`
- `graph/constraints.json`
- `simulation/setup.yaml`
- `simulation/mesh_handoff_contract.json`
- `task/task_spec.yaml`
- `task/external_tool_requirements.json`
- `results/evidence_index.json`
- `results/claim_map.json`
- `provenance/tool_trace.json`
- `validation/completeness_report.json`

The MCP may create or update evidence, trace, modified artifacts, result artifacts, and completeness resources.

The MCP must not rewrite package semantics without explicit operation scope.

---

## Global Evidence and Claim Policy

All external execution and import pathways default to evidence/artifact ingestion only.

The following layers must remain separate:

1. Artifact presence  
   An external file or generated artifact exists and is referenced.

2. Parsed facts  
   Deterministic observations are extracted from the artifact.

3. Claim linkage  
   Evidence may point to claim IDs that it could support.

4. Explicit claim status update  
   Claim status changes only when an explicit claim update operation is performed with traceable evidence IDs.

The MCP must not automatically advance claim status merely because a file was imported, a mesh was generated, or a solver was run.

Claim updates require:

- `claim_id`
- evidence IDs
- tool trace ID
- decision criteria
- explicit update operation

Unsupported means "not enough evidence attached yet."

Unsupported does not mean false.

Fail means evidence exists and violates the claim criteria.

Pass means evidence exists and satisfies the claim criteria.

---

## Execution Boundary

FreeCAD and CAE tools execute operations.

`.aieng` records state, evidence, provenance, and claims.

The MCP bridges these layers.

The MCP must always return structured results that include:

- operation name
- status
- inputs
- outputs
- artifact paths
- evidence IDs
- trace IDs
- warnings
- unsupported information
- whether claims were advanced

Claims must default to `claims_advanced: false`.

---

## FreeCAD Execution Policy

FreeCAD execution must be controlled and whitelisted.

Allowed execution pattern:

1. Receive MCP tool call.
2. Validate input against schema.
3. Create isolated job workspace.
4. Copy or reference approved input artifacts.
5. Run approved FreeCAD script or module.
6. Capture stdout, stderr, exit status, and generated files.
7. Validate expected outputs.
8. Write evidence and trace records.
9. Return structured result.

Disallowed execution pattern:

- Directly run arbitrary Python from the AI.
- Directly pass user input into shell commands.
- Write outside approved package or job directories.
- Modify source artifacts in place.
- Hide failed recompute, failed export, failed mesh, or failed solver runs.

---

## CAD Modification Policy

CAD modification is allowed only when the package provides executable edit metadata.

A CAD edit may proceed only if all of the following are true:

- The target feature exists in `graph/feature_graph.json`.
- The feature has an editable parameter.
- The parameter has an executable source.
- `editability` allows execution.
- `writeback_strategy` supports FreeCAD or parametric regeneration.
- The requested operation is allowed by `task/task_spec.yaml`.
- Protected-region constraints are not violated.
- The operation is supported by the current FreeCAD MCP capability profile.

Semantic-only parameters must not be treated as CAD writeback handles.

If a feature is semantic-only, the MCP must reject CAD modification and explain why.

---

## CAE Policy

CAE operations are external execution operations.

The MCP may support:

- static structural setup
- material assignment
- boundary condition creation
- load creation
- mesh generation
- CalculiX deck export
- CalculiX solver execution
- result import
- result metric extraction

The MCP must not claim that a model is validated merely because:

- a deck exists
- a mesh exists
- a solver ran
- a result file exists

Validation claims require explicit evidence and decision criteria.

Initial CAE scope should remain conservative:

- linear static only
- single or simple material assignment
- fixed support
- force load
- pressure load
- basic tetrahedral mesh
- CalculiX result metrics

Out of scope unless explicitly implemented:

- nonlinear analysis
- contact
- buckling
- fatigue
- CFD
- thermal-fluid coupling
- topology optimization
- manufacturing certification

---

## Security Policy

The MCP is a local execution surface and must be treated as security-sensitive.

Never implement tools that allow:

- arbitrary shell command execution
- arbitrary Python execution
- unrestricted file reads
- unrestricted file writes
- network access by default
- hidden background execution
- silent mutation of source packages
- automatic trust in generated files

All mutating operations must:

- validate input
- operate inside a controlled workspace
- log tool versions
- log command/module used
- record exit status
- record produced artifacts
- record warnings and failures

---

## Tool Design Principles

Prefer many narrow tools over one broad tool.

Good tools:

- `freecad_get_capabilities`
- `freecad_inspect_model`
- `freecad_extract_parametric_tree`
- `freecad_apply_parameter_edit`
- `freecad_export_step`
- `freecad_create_static_structural_analysis`
- `freecad_generate_mesh`
- `freecad_export_calculix_deck`
- `freecad_run_calculix`
- `freecad_extract_solver_metrics`
- `freecad_record_evidence`
- `freecad_record_trace`

Bad tools:

- `do_cad_task`
- `run_python`
- `execute_command`
- `fix_model`
- `optimize_design`
- `make_it_work`
- `validate_design_automatically`

Every tool must have a JSON input schema and a JSON output schema.

---

## Standard Tool Result Shape

All mutating tools should return a result with this shape:

```json
{
  "status": "success | failed | unsupported | rejected",
  "operation": "operation_name",
  "inputs": {},
  "outputs": {},
  "artifacts_written": [],
  "evidence": {
    "evidence_ids": [],
    "claim_ids_possibly_supported": []
  },
  "claim_policy": {
    "claims_advanced": false,
    "requires_explicit_update_claim": true
  },
  "trace": {
    "tool_trace_id": null,
    "producer": "freecad_mcp",
    "exit_status": null
  },
  "warnings": [],
  "unsupported": [],
  "errors": []
}
```

Never omit claim policy from mutating tool results.

---

## Testing Requirements

Every new tool must include tests for:

- valid input
- invalid input
- missing file
- unsupported operation
- evidence writeback
- trace writeback
- no automatic claim advancement
- path safety
- deterministic output where possible

CAD modification tools must additionally test:

- semantic-only feature rejection
- protected-region rejection
- successful executable parameter edit
- failed FreeCAD recompute
- source artifact immutability

CAE tools must additionally test:

- missing solver
- missing mesher
- failed mesh
- failed solver
- metric extraction with `not_found`
- no validation claim auto-advance

---

## Documentation Requirements

When adding a feature, update:

- `README.md` for user-facing behavior
- `docs/tool_contract.md` for MCP tool schema
- `docs/evidence_and_claim_policy.md` if evidence behavior changes
- `docs/freecad_execution_policy.md` if execution behavior changes
- `docs/roadmap.md` if milestone status changes
- tests and examples

Do not document aspirational behavior as implemented behavior.

Use these status labels:

- Implemented
- Implemented scaffold
- Experimental
- Planned
- External responsibility
- Unsupported

---

## Development Priorities

Priority order:

1. Correct boundary discipline.
2. Safe execution.
3. Deterministic evidence writeback.
4. FreeCAD inspection.
5. Parametric regeneration.
6. CAE preprocessing.
7. Solver execution.
8. Post-processing.
9. Visualization.
10. Advanced modeling.

Do not prioritize impressive demos over auditability.

---

## First Milestone

The first milestone is:

> FreeCAD MCP can safely inspect and regenerate a parametric bracket.

Acceptance criteria:

1. MCP starts and reports FreeCAD capabilities.
2. MCP opens an FCStd fixture in headless FreeCAD.
3. MCP extracts object tree and editable parameters.
4. MCP reads a `.aieng` package feature graph.
5. MCP applies one allowed parameter edit.
6. MCP recomputes the FreeCAD document.
7. MCP exports modified FCStd and STEP artifacts.
8. MCP records an evidence entry.
9. MCP records a tool trace entry.
10. MCP does not advance claims automatically.
11. `aieng validate` passes after writeback.

---

## Non-Negotiable Rule

When in doubt, preserve honesty over usefulness.

It is better for the MCP to return:

```json
{
  "status": "unsupported",
  "reason": "Required executable edit metadata is missing."
}
```

than to guess, fabricate, or silently perform an unsafe operation.

The project exists to make CAD/CAE state legible and auditable for AI.

It must not become an unverifiable CAD/CAE automation black box.


CAD and CAE workflows are independent first-class capabilities.

The MCP must not assume that CAD modification requires CAE execution.

The MCP must not assume that CAE execution requires a preceding CAD modification.

Combined CAD→CAE sequences are optional explicit orchestrations requested by the caller.

Each stage produces evidence and provenance independently.

Claim updates remain explicit and evidence-backed.