constitution.md•17.1 kB
<!--
Sync Impact Report - Version 1.0.0 (Initial Constitution)
════════════════════════════════════════════════════════
Version Change: NONE → 1.0.0
Modified Principles: N/A (initial creation)
Added Sections: All sections (initial creation)
Removed Sections: None
Templates Requiring Updates:
✅ /specs/001-project-setup/plan.md - Already aligned
✅ /specs/002-session-management/plan.md - Already aligned
✅ /specs/003-document-management/plan.md - Already aligned
✅ /specs/004-specification-management/plan.md - Already aligned
✅ /specs/005-basic-facets/plan.md - Already aligned
✅ /specs/006-advanced-facets/plan.md - Already aligned
✅ /specs/007-restrictions/plan.md - Already aligned
✅ /specs/008-validation/plan.md - Already aligned
✅ /specs/009-testing-framework/plan.md - Already aligned
Follow-up TODOs: None
════════════════════════════════════════════════════════
-->
# IDS MCP Server - Project Constitution
**Version:** 1.0.0
**Ratification Date:** 2025-11-01
**Last Amended:** 2025-11-01
**Status:** Active
---
## Preamble
This constitution establishes the foundational principles and governance for the **IDS MCP Server** project. This project enables AI agents to deterministically create buildingSMART Information Delivery Specification (IDS) files that are 100% compliant with the IDS 1.0 standard.
The principles herein are **non-negotiable** and MUST be upheld across all development activities, architectural decisions, and external contributions. Any code, documentation, or process that violates these principles is considered non-compliant and MUST be remediated.
---
## Project Identity
**Project Name:** IDS MCP Server
**Mission Statement:** Provide a reliable, deterministic, and standards-compliant MCP (Model Context Protocol) server that enables AI agents to create, validate, and manage buildingSMART IDS files with 100% compliance to the official IDS 1.0 specification.
**Primary Stakeholders:**
- AI agents (Claude, GPT, etc.) as primary users
- BIM professionals requiring IDS validation
- buildingSMART standards compliance teams
- IfcOpenShell/IfcTester community
**Repository:** https://github.com/Quasar-Consulting-Group/ifc-ids-mcp
**License:** MIT (or as specified in LICENSE file)
---
## Core Principles
### Principle 1: 100% IDS Schema Compliance
**Statement:** All IDS files generated by this server MUST validate against the official buildingSMART IDS 1.0 XSD schema without errors or warnings.
**Rationale:** The primary value proposition of this project is guaranteed compliance. Any deviation from the official schema undermines trust and renders the tool unusable for professional BIM workflows where standards compliance is mandatory.
**Rules:**
- MUST validate all exports against `https://standards.buildingsmart.org/IDS/1.0/ids.xsd`
- MUST use IfcTester's built-in XSD validation as the source of truth
- MUST include XSD validation in automated test suite (validation tests required)
- MUST NOT generate any IDS XML that fails schema validation
- MUST document any schema interpretation decisions with references to official IDS documentation
**Verification:**
- Every export operation includes optional XSD validation (default: enabled)
- Test suite includes validation against official buildingSMART example files
- Round-trip tests (create → export → load → export) verify no data loss
---
### Principle 2: Test-Driven Development (TDD)
**Statement:** All features MUST be developed using Test-Driven Development methodology with the Red-Green-Refactor cycle. Minimum code coverage: 95%.
**Rationale:** Given the critical nature of standards compliance and the complexity of the IDS specification, comprehensive automated testing is the only way to ensure correctness and prevent regressions. TDD ensures tests are written before implementation, catching issues early and serving as executable specifications.
**Rules:**
- MUST write failing tests BEFORE writing implementation code (Red phase)
- Tests MUST initially fail to prove they test something meaningful
- MUST write minimal implementation to make tests pass (Green phase)
- MUST refactor while keeping all tests passing (Refactor phase)
- MUST achieve minimum 95% code coverage across all modules
- MUST validate all IDS operations using IfcTester API in tests
- MUST include three levels of testing: unit, integration, and validation
- MUST run full test suite before every commit (enforced via pre-commit hooks)
**Verification:**
- pytest configured with `--cov-fail-under=95` in CI/CD pipeline
- Pre-commit hooks prevent commits when tests fail or coverage drops below 95%
- Code reviews verify TDD methodology was followed (tests committed before implementation)
---
### Principle 3: IfcTester Integration First
**Statement:** All IDS operations MUST use the IfcTester library from IfcOpenShell. Custom XML generation or parsing is PROHIBITED.
**Rationale:** IfcTester is the official, battle-tested, community-maintained implementation of the IDS specification. Reimplementing IDS logic introduces bugs, maintenance burden, and compliance risks. By delegating to IfcTester, we leverage thousands of hours of development and testing by the BIM community.
**Rules:**
- MUST use `ids.Ids()` for document creation
- MUST use `ids.Specification()` for specifications
- MUST use IfcTester facet classes (`ids.Entity`, `ids.Property`, etc.)
- MUST use `ids.Restriction()` for value constraints
- MUST use `ids.open()` and `ids.from_string()` for loading
- MUST use `to_xml()` and `to_string()` for exporting
- MUST NOT generate IDS XML using custom XML libraries (lxml, ElementTree, etc.)
- MUST NOT parse IDS XML manually; delegate to IfcTester
- MAY wrap IfcTester classes in helper functions but MUST NOT bypass them
**Verification:**
- Code reviews check for direct XML manipulation
- All IDS objects are instances of IfcTester classes
- Test suite validates using IfcTester API assertions
---
### Principle 4: Deterministic Generation
**Statement:** Given identical input parameters, the system MUST produce byte-identical IDS output files every time.
**Rationale:** Determinism enables version control, automated testing, reproducible builds, and trustworthy validation. Non-deterministic output makes debugging impossible and breaks round-trip testing.
**Rules:**
- MUST NOT include timestamps in generated IDS (unless explicitly provided by user)
- MUST NOT use random identifiers (UUIDs, etc.) unless seeded deterministically
- MUST maintain stable ordering of elements (specifications, facets)
- MUST produce identical XML formatting for same input
- MUST NOT depend on system state (environment variables, current directory, etc.) except explicitly configured settings
**Verification:**
- Round-trip tests verify identical output after load → export
- Integration tests run multiple times and compare outputs (must be identical)
- Snapshot testing captures expected outputs and detects unintended changes
---
### Principle 5: FastMCP Context-Based Session Management
**Statement:** All MCP tools MUST use FastMCP Context for automatic session identification and state management. Manual session ID parameters are PROHIBITED.
**Rationale:** FastMCP provides automatic session management via `Context.session_id`, eliminating error-prone manual session tracking. This creates a cleaner API, reduces bugs, and leverages framework capabilities for logging and progress reporting.
**Rules:**
- MUST accept `ctx: Context` parameter in all MCP tools (auto-injected by FastMCP)
- MUST use `ctx.session_id` for all session identification
- MUST NOT require users to pass `session_id` as a tool parameter
- MUST use `ctx.info()`, `ctx.debug()`, `ctx.error()` for all logging
- MUST use `ctx.report_progress()` for long-running operations
- MUST implement session cleanup to prevent memory leaks
- MUST maintain session state across multiple tool calls
**Verification:**
- Code reviews verify no `session_id` parameters in tool signatures
- All tools accept `Context` parameter
- Session persistence verified via integration tests (multiple tool calls in same session)
- Memory leak tests verify cleanup of abandoned sessions
---
### Principle 6: Python Best Practices and Type Safety
**Statement:** All code MUST follow Python best practices including type hints, PEP 8 compliance, and modern Python idioms (3.8+ features).
**Rationale:** Type safety catches bugs at development time, improves IDE support, and serves as documentation. Consistent style improves readability and maintainability across contributors.
**Rules:**
- MUST include type hints for all function signatures
- MUST use Pydantic models for all MCP tool parameters
- MUST comply with PEP 8 (enforced via black and ruff)
- MUST use async/await for all MCP tools and I/O operations
- MUST handle errors explicitly (no bare `except:` clauses)
- MUST use FastMCP's `ToolError` for user-facing errors
- MUST log internal errors with full context before masking in production
**Verification:**
- black formatter enforced via pre-commit hooks
- ruff linter configured and enforced
- mypy type checking (optional but recommended)
- Code reviews verify type hints present
---
## Governance
### Amendment Procedure
1. **Proposal Phase:**
- Any contributor may propose an amendment via GitHub issue tagged `constitution-amendment`
- Proposal MUST include: rationale, affected principles, impact analysis
2. **Review Phase:**
- Maintainers review proposal and gather community feedback
- Minimum 7-day comment period for non-trivial changes
3. **Approval:**
- Requires approval from project maintainers (majority consensus)
- Breaking changes (MAJOR version bump) require explicit justification
4. **Implementation:**
- Update constitution.md with new version number
- Update all affected templates and documentation
- Commit with message: `docs: amend constitution to vX.Y.Z (<summary>)`
### Versioning Policy
Constitution version follows **Semantic Versioning 2.0.0:**
- **MAJOR (X.0.0):** Backward incompatible changes
- Principle removal
- Principle redefinition that contradicts previous version
- Governance process changes that invalidate prior procedures
- **MINOR (x.Y.0):** Backward compatible additions
- New principle added
- Principle materially expanded with new requirements
- New governance section added
- **PATCH (x.y.Z):** Clarifications and non-semantic changes
- Typo fixes
- Wording clarifications that don't change meaning
- Formatting improvements
- Comment additions
### Compliance Review
**Frequency:** Every major release (1.0, 2.0, etc.) and upon principle violations
**Process:**
1. Audit codebase against all principles
2. Check test coverage meets 95% threshold
3. Validate all exports against IDS XSD schema
4. Review session management for Context usage
5. Verify TDD practices followed (test commits before implementation)
6. Document findings in `docs/compliance-report.md`
**Non-Compliance Remediation:**
- Create GitHub issue tagged `constitution-violation`
- Prioritize fix as P0 (blocking release)
- Update code to comply within 1 sprint
- Add regression tests to prevent recurrence
---
## Principle-Specific Guidance
### For Principle 1 (IDS Compliance)
**When adding new IDS features:**
1. Read official IDS documentation: https://github.com/buildingSMART/IDS/tree/development/Documentation
2. Study IfcTester implementation of the feature
3. Write tests that validate against XSD schema
4. Test against buildingSMART official examples if available
**Validation checklist:**
- [ ] Feature tested with `ids.from_string(xml, validate=True)`
- [ ] Round-trip test added (create → export → load → export)
- [ ] Tested against official buildingSMART examples (if applicable)
- [ ] XSD validation errors clearly reported to users
### For Principle 2 (TDD)
**TDD workflow:**
1. **RED:** Write failing test that defines expected behavior
2. **GREEN:** Write minimal code to make test pass
3. **REFACTOR:** Improve code while keeping tests green
4. **REPEAT:** For next feature
**Test organization:**
```
tests/
├── unit/ # Test individual functions/classes
├── component/ # Test business logic modules
├── integration/ # Test complete workflows
└── validation/ # Test IDS compliance
```
**Coverage exemptions:**
- Generated code (if any)
- Explicit `# pragma: no cover` with justification in code review
### For Principle 3 (IfcTester Integration)
**Allowed patterns:**
```python
# ✅ GOOD - Using IfcTester
from ifctester import ids
my_ids = ids.Ids(title="Project Requirements")
spec = ids.Specification(name="Walls", ifcVersion=["IFC4"])
my_ids.specifications.append(spec)
```
**Prohibited patterns:**
```python
# ❌ BAD - Custom XML generation
from lxml import etree
root = etree.Element("ids:ids")
# ...
```
### For Principle 4 (Determinism)
**Deterministic practices:**
- Use stable sort orders (e.g., alphabetical for display, insertion order for internal)
- Accept dates as strings, don't auto-generate
- If random IDs needed, accept seed parameter
**Testing determinism:**
```python
# Export twice, compare
xml1 = ids_obj.to_string()
xml2 = ids_obj.to_string()
assert xml1 == xml2 # Must be identical
```
### For Principle 5 (FastMCP Context)
**Tool signature pattern:**
```python
@mcp.tool
async def tool_name(
param1: str,
param2: int,
ctx: Context, # MUST be present
optional_param: str = None
) -> dict:
"""Tool description."""
session_id = ctx.session_id # Use this, don't ask for it
await ctx.info(f"Doing work for session {session_id}")
# ...
```
**Session access pattern:**
```python
async def get_or_create_session(ctx: Context) -> ids.Ids:
"""Get IDS for current session."""
session_id = ctx.session_id # Automatic from FastMCP
if session_id not in _session_storage:
# Create new session
pass
return _session_storage[session_id].ids_obj
```
---
## Enforcement
**Automated Enforcement:**
- Pre-commit hooks prevent commits that violate code style (black, ruff)
- Pre-commit hooks prevent commits with failing tests
- Pre-commit hooks prevent commits with <95% coverage
- CI/CD pipeline blocks PRs that fail tests or coverage
- CI/CD pipeline validates exported IDS against XSD schema
**Manual Enforcement:**
- Code reviews verify TDD methodology (test commits before implementation)
- Code reviews verify IfcTester usage (no custom XML)
- Code reviews verify Context usage (no manual session IDs)
- Release checklist includes constitution compliance review
**Violation Response:**
1. Identify violation in GitHub issue
2. Tag as `constitution-violation` with priority P0
3. Assign to contributor or maintainer
4. Fix within 1 sprint
5. Add regression test
6. Update documentation if principle was unclear
---
## Appendix A: Reference Links
**IDS Standard:**
- IDS 1.0 Specification: https://www.buildingsmart.org/standards/bsi-standards/information-delivery-specification-ids/
- IDS XSD Schema: https://standards.buildingsmart.org/IDS/1.0/ids.xsd
- IDS GitHub: https://github.com/buildingSMART/IDS
- IDS Documentation: https://github.com/buildingSMART/IDS/tree/development/Documentation
**IfcTester:**
- IfcTester Documentation: https://docs.ifcopenshell.org/ifctester.html
- IfcOpenShell: https://ifcopenshell.org/
- IfcOpenShell GitHub: https://github.com/IfcOpenShell/IfcOpenShell
**FastMCP:**
- FastMCP Framework: https://github.com/jlowin/fastmcp
- FastMCP Documentation: https://gofastmcp.com/
**Testing:**
- pytest: https://docs.pytest.org/
- pytest-asyncio: https://pytest-asyncio.readthedocs.io/
- pytest-cov: https://pytest-cov.readthedocs.io/
---
## Appendix B: Glossary
**IDS (Information Delivery Specification):** buildingSMART standard for specifying and checking information requirements from IFC models.
**IFC (Industry Foundation Classes):** Open standard for BIM data exchange.
**MCP (Model Context Protocol):** Standardized protocol for connecting AI assistants to external tools and data sources.
**IfcTester:** Official Python library from IfcOpenShell for IDS authoring and validation.
**FastMCP:** Python framework for building MCP servers.
**TDD (Test-Driven Development):** Development methodology where tests are written before implementation code.
**XSD (XML Schema Definition):** Schema language for validating XML documents.
**buildingSMART:** International standards organization for BIM and construction industry.
---
## Document History
| Version | Date | Changes | Author |
|---------|------------|----------------------------------|--------|
| 1.0.0 | 2025-11-01 | Initial constitution ratified | Claude |
---
**END OF CONSTITUTION**