package eaxmi
import (
"bytes"
"fmt"
"sort"
"strings"
"github.com/beevik/etree"
)
// CopyPackage deep-copies the package srcPkgID (from src, which may be d itself)
// into d as a child of destParentID. Every id that belongs to the copied subtree
// — packages, elements, connectors, diagrams, association ends, packed <xrefs>
// GUIDs — is regenerated, so the copy is identity-disjoint from the original and
// from everything already in d. References that point OUT of the subtree (a
// connector end or a diagram object that names an element in another package)
// are left untouched, exactly as EA exports them (see example/side1.xml).
//
// Returns the new package.
func (d *Document) CopyPackage(src *Document, srcPkgID, destParentID string) (*Package, error) {
srcPE := src.doc.FindElement("//packagedElement[@xmi:id='" + srcPkgID + "']")
if srcPE == nil {
return nil, fmt.Errorf("eaxmi: no package %q in the source model", srcPkgID)
}
destPE := d.doc.FindElement("//packagedElement[@xmi:id='" + destParentID + "']")
if destPE == nil {
return nil, fmt.Errorf("eaxmi: no destination package %q", destParentID)
}
// 1. ids defined inside the subtree
ownBody := map[string]bool{} // "A_B_C_D_E" GUID bodies
ownEnd := map[string]bool{} // whole "EAID_src…" / "EAID_dst…" tokens
ownPkgID := map[string]bool{} // "EAPK_…" of packages in the subtree
for _, e := range append([]*etree.Element{srcPE}, srcPE.FindElements(".//*")...) {
id := e.SelectAttrValue("xmi:id", "")
if id == "" {
continue
}
if isEndToken(id) {
ownEnd[id] = true
continue
}
if b := guidBody(id); b != "" {
ownBody[b] = true
if strings.HasPrefix(id, "EAPK_") ||
(e.Tag == "packagedElement" && e.SelectAttrValue("xmi:type", "") == "uml:Package") {
ownPkgID[id] = true
}
}
}
// diagrams whose owning package is in the subtree
var srcDiagrams []*etree.Element
if sExt := src.doc.FindElement("//Extension"); sExt != nil {
for _, dg := range sExt.FindElements(".//diagram") {
m := dg.FindElement("model")
if m == nil {
continue
}
if ownPkgID[m.SelectAttrValue("package", "")] || m.SelectAttrValue("package", "") == srcPkgID {
srcDiagrams = append(srcDiagrams, dg)
if b := guidBody(dg.SelectAttrValue("xmi:id", "")); b != "" {
ownBody[b] = true
}
}
}
}
// 2. remap table
rm := map[string]string{}
for b := range ownBody {
nb := underscoreBody(NewGUID())
rm["EAID_"+b] = "EAID_" + nb
rm["EAPK_"+b] = "EAPK_" + nb
rm["{"+dash(b)+"}"] = "{" + dash(nb) + "}"
}
for t := range ownEnd {
rm[t] = xmiIDFromGUID(NewGUID(), "EAID_")
}
// 3. model subtree
newPE, err := remapFragment(srcPE, rm)
if err != nil {
return nil, err
}
newID := newPE.SelectAttrValue("xmi:id", "")
destPE.AddChild(newPE)
// 4. ArchiMate profile applications that reference the subtree
if sModel := src.doc.FindElement("//Model"); sModel != nil {
dModel := d.doc.FindElement("//Model")
for _, pa := range sModel.ChildElements() {
if pa.Space != "ArchiMate3" {
continue
}
hit := false
for _, a := range pa.Attr {
if b := guidBody(a.Value); b != "" && ownBody[b] {
hit = true
}
}
if !hit {
continue
}
c, err := remapFragment(pa, rm)
if err != nil {
return nil, err
}
dModel.AddChild(c)
}
}
// 5. <xmi:Extension> records
dExt := d.doc.FindElement("//Extension")
sExt := src.doc.FindElement("//Extension")
if dExt != nil && sExt != nil {
copyRecs := func(block string, keep func(*etree.Element) bool) error {
s := sExt.FindElement(block)
if s == nil {
return nil
}
dst := dExt.FindElement(block)
if dst == nil {
dst = dExt.CreateElement(block)
}
for _, rec := range s.ChildElements() {
if !keep(rec) {
continue
}
c, err := remapFragment(rec, rm)
if err != nil {
return err
}
dst.AddChild(c)
}
return nil
}
inSubtree := func(rec *etree.Element) bool {
b := guidBody(rec.SelectAttrValue("xmi:idref", ""))
return b != "" && ownBody[b]
}
if err := copyRecs("elements", inSubtree); err != nil {
return nil, err
}
if err := copyRecs("connectors", inSubtree); err != nil {
return nil, err
}
if dst := dExt.FindElement("diagrams"); dst != nil || len(srcDiagrams) > 0 {
if dst == nil {
dst = dExt.CreateElement("diagrams")
}
for _, dg := range srcDiagrams {
c, err := remapFragment(dg, rm)
if err != nil {
return nil, err
}
dst.AddChild(c)
}
}
// 6. the copied top package now reads as a child of destParentID
if m := dExt.FindElement(".//element[@xmi:idref='" + newID + "']/model"); m != nil {
m.CreateAttr("package", destParentID)
}
// nothing in the copy is a model root any more — a copied package always
// lands under a parent. Strip isModel / Recurse from every package record.
copiedPkgIDs := map[string]bool{newID: true}
for _, pe := range newPE.FindElements(".//packagedElement[@xmi:type='uml:Package']") {
copiedPkgIDs[pe.SelectAttrValue("xmi:id", "")] = true
}
for id := range copiedPkgIDs {
if fl := dExt.FindElement(".//element[@xmi:idref='" + id + "']/flags"); fl != nil {
pf := fl.SelectAttrValue("packageFlags", "")
pf = strings.ReplaceAll(pf, "isModel=1;", "")
pf = strings.ReplaceAll(pf, "Recurse=1;", "")
fl.CreateAttr("packageFlags", pf)
}
}
}
if err := d.reparse(); err != nil {
return nil, err
}
np, ok := d.packageByID[newID]
if !ok {
return nil, fmt.Errorf("eaxmi: copied package %q not found after reparse", newID)
}
return np, nil
}
// CopyProfileDefinitions copies the <xmi:Extension>/<profiles> block (the MDG /
// ArchiMate profile *definitions*, not applications) from other into d, unless d
// already has one. EA needs it to recognise the stereotypes an imported package
// carries. It is static, so no id remapping.
func (d *Document) CopyProfileDefinitions(other *Document) error {
dExt := d.doc.FindElement("//Extension")
oExt := other.doc.FindElement("//Extension")
if dExt == nil || oExt == nil {
return nil
}
if dExt.FindElement("profiles") != nil {
return nil
}
src := oExt.FindElement("profiles")
if src == nil {
return nil
}
dExt.AddChild(src.Copy())
return d.reparse()
}
// remapFragment serialises el, rewrites every id token per rm (longest key
// first, so "EAID_x" is not clobbered by a shorter prefix), and parses it back.
func remapFragment(el *etree.Element, rm map[string]string) (*etree.Element, error) {
doc := etree.NewDocument()
doc.SetRoot(el.Copy())
var buf bytes.Buffer
if _, err := doc.WriteTo(&buf); err != nil {
return nil, fmt.Errorf("eaxmi: copy serialise: %w", err)
}
s := buf.String()
keys := make([]string, 0, len(rm))
for k := range rm {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool { return len(keys[i]) > len(keys[j]) })
for _, k := range keys {
s = strings.ReplaceAll(s, k, rm[k])
}
nd := etree.NewDocument()
if err := nd.ReadFromString(s); err != nil {
return nil, fmt.Errorf("eaxmi: copy re-parse: %w", err)
}
return nd.Root().Copy(), nil
}
// guidBody returns the "A_B_C_D_E" body of an EAID_/EAPK_ id, or "" if id is not
// GUID-shaped (5 underscore-separated hex groups of 8-4-4-4-12).
func guidBody(id string) string {
body := strings.TrimPrefix(strings.TrimPrefix(id, "EAID_"), "EAPK_")
if body == id && !strings.HasPrefix(id, "EAID_") && !strings.HasPrefix(id, "EAPK_") {
// braced GUID?
if strings.HasPrefix(id, "{") && strings.HasSuffix(id, "}") {
body = strings.ReplaceAll(strings.Trim(id, "{}"), "-", "_")
} else {
return ""
}
}
parts := strings.Split(body, "_")
if len(parts) != 5 || len(parts[0]) != 8 {
return ""
}
return body
}
func isEndToken(id string) bool {
return strings.HasPrefix(id, "EAID_src") || strings.HasPrefix(id, "EAID_dst")
}
// reparse rebuilds the parsed model view from the (edited) etree document.
func (d *Document) reparse() error {
var buf bytes.Buffer
if _, err := d.doc.WriteTo(&buf); err != nil {
return fmt.Errorf("eaxmi: reparse serialise: %w", err)
}
nd := etree.NewDocument()
nd.ReadSettings = d.doc.ReadSettings
if err := nd.ReadFromBytes(buf.Bytes()); err != nil {
return fmt.Errorf("eaxmi: reparse: %w", err)
}
np, err := parse(nd)
if err != nil {
return err
}
path := d.Path
*d = *np
d.Path = path
return nil
}
package eaxmi
import (
"fmt"
"strings"
"github.com/beevik/etree"
)
// Creation of diagrams. A diagram is an <xmi:Extension>/<diagrams>/<diagram>
// record; EA holds no <packagedElement> for it. AddDiagramObject then fills it
// with element placements. The shape follows a real EA "Export Package to XMI"
// (client/eaxmi/test/testdata/CyrillicProject.xml); whether EA's importer needs
// every child is confirmed by round-tripping through EA.
// diagramsBlock returns <xmi:Extension>/<diagrams>, creating it if the export
// (or a from-scratch model) does not carry one yet.
func (d *Document) diagramsBlock() *etree.Element {
ext := d.extension()
if b := ext.FindElement("diagrams"); b != nil {
return b
}
return ext.CreateElement("diagrams")
}
// AddDiagram creates an empty diagram named name inside package pkgID and
// returns it. mdgType, when non-empty, is written into the diagram style as
// "MDGDgm=<mdgType>" (e.g. "ArchiMate3::Motivation") so EA opens the diagram
// with the matching ArchiMate toolbox; the diagram's <properties type> stays
// "Logical", as EA exports every extended diagram. Populate it with
// AddDiagramObject.
func (d *Document) AddDiagram(pkgID, name, mdgType string) (*Diagram, error) {
pkg, ok := d.packageByID[pkgID]
if !ok {
return nil, fmt.Errorf("eaxmi: no package %q", pkgID)
}
for _, g := range pkg.Diagrams {
if g.Name == name {
return nil, fmt.Errorf("eaxmi: package %q already has a diagram named %q", pkg.Name, name)
}
}
guid := NewGUID()
id := xmiIDFromGUID(guid, "EAID_")
dg := d.diagramsBlock().CreateElement("diagram")
dg.CreateAttr("xmi:id", id)
m := dg.CreateElement("model")
m.CreateAttr("package", pkgID)
m.CreateAttr("owner", pkgID)
m.CreateAttr("localID", "0")
pr := dg.CreateElement("properties")
pr.CreateAttr("name", name)
pr.CreateAttr("type", "Logical")
pr.CreateAttr("documentation", "")
proj := dg.CreateElement("project")
proj.CreateAttr("author", genAuthor)
proj.CreateAttr("version", "1.0")
style := "ExcludeRTF=0;DocAll=0;HideQuals=0;AttPkg=1;ShowTests=0;ShowMaint=0;" +
"AdvancedElementProps=1;AdvancedFeatureProps=1;AdvancedConnectorProps=1;" +
"m_bElementClassifier=1;SPT=1;ShowNotes=0;SuppressBrackets=0;SuppConnectorLabels=0;"
if mdgType != "" {
style += "MDGDgm=" + mdgType + ";"
}
dg.CreateElement("style2").CreateAttr("value", style)
dg.CreateElement("elements")
g := &Diagram{XMIID: id, GUID: guid, Name: name, Type: "Logical", Package: pkg}
pkg.Diagrams = append(pkg.Diagrams, g)
d.diagramByID[id] = g
return g, nil
}
// AddDiagramLink shows connectorID on diagramID. EA auto-routes the line as long
// as both of the connector's endpoint elements are placed on the diagram; it is
// stored as an <element> with an "SX=" geometry (the shape the parser reads back
// as a DiagramLink). A no-op if the connector is already shown.
func (d *Document) AddDiagramLink(diagramID, connectorID string) error {
g, ok := d.diagramByID[diagramID]
if !ok {
return fmt.Errorf("eaxmi: no diagram %q", diagramID)
}
for _, l := range g.Links {
if l.ConnectorID == connectorID {
return nil
}
}
dg := d.extension().FindElement("//diagram[@xmi:id='" + diagramID + "']")
if dg == nil {
return fmt.Errorf("eaxmi: diagram node %q not found", diagramID)
}
els := dg.FindElement("elements")
if els == nil {
els = dg.CreateElement("elements")
}
o := els.CreateElement("element")
o.CreateAttr("geometry", "SX=0;SY=0;EX=0;EY=0;EDGE=1;$LLB=;LLT=;LMT=;LMB=;LRT=;LRB=;IRHS=;ILHS=;Path=;")
o.CreateAttr("subject", connectorID)
o.CreateAttr("style", "Mode=3;Color=-1;LWidth=0;Hidden=0;")
g.Links = append(g.Links, &DiagramLink{ConnectorID: connectorID})
return nil
}
// RemoveDiagramLink hides connectorID on diagramID. A no-op if it is not shown.
func (d *Document) RemoveDiagramLink(diagramID, connectorID string) {
g, ok := d.diagramByID[diagramID]
if !ok {
return
}
if dg := d.extension().FindElement("//diagram[@xmi:id='" + diagramID + "']"); dg != nil {
if els := dg.FindElement("elements"); els != nil {
for _, o := range els.ChildElements() {
if o.SelectAttrValue("subject", "") == connectorID &&
strings.HasPrefix(o.SelectAttrValue("geometry", ""), "SX=") {
els.RemoveChild(o)
}
}
}
}
kept := g.Links[:0]
for _, l := range g.Links {
if l.ConnectorID != connectorID {
kept = append(kept, l)
}
}
g.Links = kept
}
// Package eaxmi reads (and, later, writes) Sparx Enterprise Architect
// "Export Package to XMI" files — EA's XMI 2.1 dialect, in which every element
// appears both in the <uml:Model> semantic tree and in an EA-specific
// <xmi:Extension> block.
//
// This package is a codec: it exposes the model as plain Go structs (see
// model.go) and keeps the underlying document so edits can be written back
// without losing the parts it does not model. It knows nothing about ArchiMate
// — that lives in internal/service/sparx.
package eaxmi
import (
"fmt"
"io"
"os"
"strings"
"github.com/beevik/etree"
"golang.org/x/text/encoding/charmap"
)
// Document is a parsed XMI file.
type Document struct {
Path string
ExporterVersion string
// Root is the <uml:Model> node as a Package (its XMIID is "").
Root *Package
doc *etree.Document // the full document, for round-tripping
elementByID map[string]*Element
connectorAll []*Connector
diagramByID map[string]*Diagram
packageByID map[string]*Package
}
// Open parses the XMI file at path.
func Open(path string) (*Document, error) {
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("eaxmi: %w", err)
}
defer f.Close()
d, err := Read(f)
if err != nil {
return nil, err
}
d.Path = path
return d, nil
}
// Read parses XMI from r.
func Read(r io.Reader) (*Document, error) {
doc := etree.NewDocument()
doc.ReadSettings = etree.ReadSettings{
CharsetReader: func(charset string, input io.Reader) (io.Reader, error) {
switch strings.ToLower(charset) {
case "windows-1252", "cp1252":
return charmap.Windows1252.NewDecoder().Reader(input), nil
case "windows-1251", "cp1251":
return charmap.Windows1251.NewDecoder().Reader(input), nil
case "utf-8", "":
return input, nil
default:
return nil, fmt.Errorf("eaxmi: unsupported charset %q", charset)
}
},
}
if _, err := doc.ReadFrom(r); err != nil {
return nil, fmt.Errorf("eaxmi: parse: %w", err)
}
return parse(doc)
}
// Connectors returns every relationship in the document.
func (d *Document) Connectors() []*Connector { return d.connectorAll }
// ElementByID looks up an element by its xmi:id (e.g. "EAID_..."). For a lookup
// by id, GUID or path, use ResolveElement (navigate.go).
func (d *Document) ElementByID(id string) (*Element, bool) {
e, ok := d.elementByID[id]
return e, ok
}
// guidFromXMIID converts an EA xmi:id ("EAID_A_B_C_D_E" / "EAPK_…") to the
// braced GUID EA stores in the database ("{A-B-C-D-E}"). A value that does not
// match the shape is returned unchanged.
func guidFromXMIID(id string) string {
body := id
for _, p := range []string{"EAID_", "EAPK_", "EAID", "EAPK"} {
if strings.HasPrefix(body, p) {
body = body[len(p):]
break
}
}
parts := strings.Split(body, "_")
if len(parts) != 5 {
return id
}
return "{" + strings.Join(parts, "-") + "}"
}
package eaxmi
import (
"bytes"
"fmt"
"regexp"
"sort"
"strings"
"github.com/beevik/etree"
)
// idTokenRe matches an EA xmi:id / xmi:idref token: EAID_ or EAPK_ followed by a
// GUID with "_" separators, or an association-end token (…_src<6hex>… / …_dst…).
var idTokenRe = regexp.MustCompile(
`EA(?:ID|PK)_(?:[0-9A-Fa-f]{8}|(?:src|dst)[0-9A-Fa-f]{6})(?:_[0-9A-Fa-f]{4}){3}_[0-9A-Fa-f]{12}`)
// bracedGUIDRe matches "{A-B-C-D-E}" as it appears inside <xrefs value="…">.
var bracedGUIDRe = regexp.MustCompile(
`\{[0-9A-Fa-f]{8}-(?:[0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}\}`)
// RemapIdentity regenerates the GUID of every package, element, connector,
// diagram and cross-reference in the document, keeping all internal references
// consistent. After it the model is identity-disjoint from the file it was
// loaded from, so both can be imported into the same EA project side by side
// (an XMI import matches by GUID — without this, the second import moves the
// shared content out of the first).
//
// It works on the serialised form (every reference, in any attribute or in the
// packed <xrefs> strings, is a plain substring) and then re-parses.
func (d *Document) RemapIdentity() error {
var buf bytes.Buffer
if _, err := d.doc.WriteTo(&buf); err != nil {
return fmt.Errorf("eaxmi: remap serialise: %w", err)
}
s := buf.String()
// old GUID body ("A_B_C_D_E") -> new body; keyed on the body so EAID_x and
// EAPK_x for the same package map to the same new GUID.
newBody := map[string]string{}
// association-end tokens are remapped whole (their body is not a real GUID).
endTok := map[string]string{}
for _, tok := range idTokenRe.FindAllString(s, -1) {
body := tok[5:] // strip "EAID_" / "EAPK_"
if strings.HasPrefix(body, "src") || strings.HasPrefix(body, "dst") {
if _, ok := endTok[tok]; !ok {
endTok[tok] = xmiIDFromGUID(NewGUID(), tok[:5])
}
continue
}
if _, ok := newBody[body]; !ok {
newBody[body] = underscoreBody(NewGUID())
}
}
for _, b := range bracedGUIDRe.FindAllString(s, -1) {
body := strings.ReplaceAll(strings.Trim(b, "{}"), "-", "_")
if _, ok := newBody[body]; !ok {
newBody[body] = underscoreBody(NewGUID())
}
}
type rep struct{ from, to string }
var reps []rep
for old, nw := range newBody {
reps = append(reps,
rep{"EAID_" + old, "EAID_" + nw},
rep{"EAPK_" + old, "EAPK_" + nw},
rep{"{" + dash(old) + "}", "{" + dash(nw) + "}"},
)
}
for old, nw := range endTok {
reps = append(reps, rep{old, nw})
}
sort.Slice(reps, func(i, j int) bool { return len(reps[i].from) > len(reps[j].from) })
for _, r := range reps {
s = strings.ReplaceAll(s, r.from, r.to)
}
nd := etree.NewDocument()
nd.ReadSettings = d.doc.ReadSettings
if err := nd.ReadFromString(s); err != nil {
return fmt.Errorf("eaxmi: remap re-parse: %w", err)
}
np, err := parse(nd)
if err != nil {
return err
}
path := d.Path
*d = *np
d.Path = path
return nil
}
func underscoreBody(guid string) string {
return strings.ReplaceAll(strings.Trim(guid, "{}"), "-", "_")
}
func dash(underscoreBody string) string {
return strings.ReplaceAll(underscoreBody, "_", "-")
}
package eaxmi
import "strings"
// Navigation over the parsed model. A ref is one of:
// - an EA xmi:id "EAID_F3C2209E_B146_4328_863E_622BABD2B43E" / "EAPK_…"
// - a braced GUID "{F3C2209E-B146-4328-863E-622BABD2B43E}"
// - a slash path "Model/Motivation_Package/Goal1" (from an EA root package)
// IsRefID reports whether ref is an id/GUID rather than a path.
func IsRefID(ref string) bool {
return strings.HasPrefix(ref, "EAID_") || strings.HasPrefix(ref, "EAPK_") ||
(strings.HasPrefix(ref, "{") && strings.HasSuffix(ref, "}"))
}
// SplitPath splits "A/B/C" into non-empty, trimmed segments.
func SplitPath(ref string) []string {
var out []string
for _, seg := range strings.Split(ref, "/") {
if seg = strings.TrimSpace(seg); seg != "" {
out = append(out, seg)
}
}
return out
}
// ResolveElement returns the element identified by ref, or nil.
func (d *Document) ResolveElement(ref string) *Element {
if IsRefID(ref) {
for _, e := range d.AllElements() {
if e.XMIID == ref || strings.EqualFold(e.GUID, ref) {
return e
}
}
return nil
}
segs := SplitPath(ref)
if len(segs) == 0 {
return nil
}
pkg := d.walkPackages(segs[:len(segs)-1])
if pkg == nil {
return nil
}
for _, e := range pkg.Elements {
if e.Name == segs[len(segs)-1] {
return e
}
}
return nil
}
// ResolveDiagram returns the diagram identified by ref, or nil.
func (d *Document) ResolveDiagram(ref string) *Diagram {
if IsRefID(ref) {
for _, p := range d.AllPackages() {
for _, g := range p.Diagrams {
if g.XMIID == ref || strings.EqualFold(g.GUID, ref) {
return g
}
}
}
return nil
}
segs := SplitPath(ref)
if len(segs) == 0 {
return nil
}
pkg := d.walkPackages(segs[:len(segs)-1])
if pkg == nil {
return nil
}
for _, g := range pkg.Diagrams {
if g.Name == segs[len(segs)-1] {
return g
}
}
return nil
}
// ResolvePackage returns the package identified by ref, or nil.
func (d *Document) ResolvePackage(ref string) *Package {
if IsRefID(ref) {
for _, p := range d.AllPackages() {
if p.XMIID == ref || strings.EqualFold(p.GUID, ref) {
return p
}
}
return nil
}
return d.walkPackages(SplitPath(ref))
}
// walkPackages follows package-name segments down from the synthetic model root.
func (d *Document) walkPackages(segs []string) *Package {
cur := d.Root
for _, seg := range segs {
var next *Package
for _, p := range cur.Packages {
if p.Name == seg {
next = p
break
}
}
if next == nil {
return nil
}
cur = next
}
return cur
}
// AllPackages returns every package below the model root (depth-first).
func (d *Document) AllPackages() []*Package {
var out []*Package
var rec func(p *Package)
rec = func(p *Package) {
for _, sub := range p.Packages {
out = append(out, sub)
rec(sub)
}
}
rec(d.Root)
return out
}
// AllElements returns every element in the model.
func (d *Document) AllElements() []*Element {
var out []*Element
for _, p := range d.AllPackages() {
out = append(out, p.Elements...)
}
return out
}
// PathOfPackage returns "A/B/C" from an EA root package down to p.
func (d *Document) PathOfPackage(p *Package) string {
var segs []string
for cur := p; cur != nil && cur != d.Root; cur = cur.Parent {
segs = append([]string{cur.Name}, segs...)
}
return strings.Join(segs, "/")
}
// PathOfElement returns the slash path to e.
func (d *Document) PathOfElement(e *Element) string {
if e == nil {
return ""
}
return joinSeg(d.PathOfPackage(e.Package), e.Name)
}
// PathOfDiagram returns the slash path to g.
func (d *Document) PathOfDiagram(g *Diagram) string {
if g == nil {
return ""
}
return joinSeg(d.PathOfPackage(g.Package), g.Name)
}
func joinSeg(parent, name string) string {
if parent == "" {
return name
}
return parent + "/" + name
}
package eaxmi
import (
_ "embed"
"fmt"
"strings"
)
// archimate3Profiles is the <profiles> block (the ArchiMate3 MDG stereotype
// definitions) EA needs to recognise the stereotypes an imported package
// carries. It is static MDG content — the same in every EA ArchiMate export —
// so it is embedded verbatim and carried by every from-scratch model.
//
//go:embed archimate3_profile.xml
var archimate3Profiles string
// NewModel builds a valid EA "Export Package to XMI" document from scratch — not
// a copy of a fixture. It contains one root package named rootName (marked as an
// EA model root), ready for AddPackage / AddElement. Save writes it like any
// working copy.
//
// It carries the ArchiMate3 profile definitions, so ArchiMate elements added to
// it import into EA with their stereotypes recognised.
func NewModel(rootName string) (*Document, error) {
rootName = strings.TrimSpace(rootName)
if rootName == "" {
return nil, fmt.Errorf("eaxmi: root name is required")
}
body := underscoreBody(NewGUID())
n := escapeXMLAttr(rootName)
xml := `<?xml version="1.0" encoding="UTF-8"?>
<xmi:XMI xmi:version="2.1" xmlns:uml="http://schema.omg.org/spec/UML/2.1" xmlns:xmi="http://schema.omg.org/spec/XMI/2.1" xmlns:ArchiMate3="http://www.sparxsystems.com/profiles/ArchiMate3/1.0">
<xmi:Documentation exporter="Enterprise Architect" exporterVersion="6.5"/>
<uml:Model xmi:type="uml:Model" name="EA_Model" visibility="public">
<packagedElement xmi:type="uml:Package" xmi:id="EAPK_` + body + `" name="` + n + `" visibility="public"/>
</uml:Model>
<xmi:Extension extender="Enterprise Architect" extenderID="6.5">
<elements>
<element xmi:idref="EAPK_` + body + `" xmi:type="uml:Package" name="` + n + `" scope="public">
<model package2="EAID_` + body + `" tpos="0" ea_localid="1" ea_eleType="package"/>
<properties isSpecification="false" sType="Package" nType="0" scope="public"/>
<project author="` + genAuthor + `" version="1.0" phase="1.0" status="Proposed"/>
<style appearance="BackColor=-1;BorderColor=-1;BorderWidth=-1;FontColor=-1;VSwimLanes=1;HSwimLanes=1;BorderStyle=0;"/>
<extendedProperties tagged="0"/>
<flags iscontrolled="FALSE" isprotected="FALSE" batchsave="1" batchload="1" usedtd="FALSE" logxml="FALSE" packageFlags="Recurse=1;isModel=1;"/>
</element>
</elements>
<connectors/>
<primitivetypes>
<packagedElement xmi:type="uml:Package" xmi:id="EAPrimitiveTypesPackage" name="EA_PrimitiveTypes_Package" visibility="public"/>
</primitivetypes>
` + strings.TrimSpace(archimate3Profiles) + `
<diagrams/>
</xmi:Extension>
</xmi:XMI>`
return Read(strings.NewReader(xml))
}
// AddRootPackage adds a package named name directly under <uml:Model> — a new
// top-level package alongside the model root (not marked as a model). Returns it.
func (d *Document) AddRootPackage(name string) (*Package, error) {
name = strings.TrimSpace(name)
if name == "" {
return nil, fmt.Errorf("eaxmi: package name is required")
}
for _, p := range d.Root.Packages {
if p.Name == name {
return nil, fmt.Errorf("eaxmi: a root package named %q already exists", name)
}
}
umlModel := d.doc.FindElement("//Model")
if umlModel == nil {
return nil, fmt.Errorf("eaxmi: no <uml:Model>")
}
guid := NewGUID()
id := xmiIDFromGUID(guid, "EAPK_")
pe := umlModel.CreateElement("packagedElement")
pe.CreateAttr("xmi:type", "uml:Package")
pe.CreateAttr("xmi:id", id)
pe.CreateAttr("name", name)
pe.CreateAttr("visibility", "public")
el := d.extensionElementsBlock().CreateElement("element")
el.CreateAttr("xmi:idref", id)
el.CreateAttr("xmi:type", "uml:Package")
el.CreateAttr("name", name)
el.CreateAttr("scope", "public")
m := el.CreateElement("model")
m.CreateAttr("package2", "EAID_"+underscoreBody(guid))
m.CreateAttr("tpos", "0")
m.CreateAttr("ea_localid", "0")
m.CreateAttr("ea_eleType", "package")
pr := el.CreateElement("properties")
pr.CreateAttr("isSpecification", "false")
pr.CreateAttr("sType", "Package")
pr.CreateAttr("nType", "0")
pr.CreateAttr("scope", "public")
proj := el.CreateElement("project")
proj.CreateAttr("author", genAuthor)
proj.CreateAttr("version", "1.0")
proj.CreateAttr("phase", "1.0")
proj.CreateAttr("status", "Proposed")
el.CreateElement("style").CreateAttr("appearance", "BackColor=-1;BorderColor=-1;BorderWidth=-1;FontColor=-1;VSwimLanes=1;HSwimLanes=1;BorderStyle=0;")
el.CreateElement("extendedProperties").CreateAttr("tagged", "0")
np := &Package{XMIID: id, GUID: guid, Name: name, Parent: d.Root}
d.Root.Packages = append(d.Root.Packages, np)
d.packageByID[id] = np
return np, nil
}
func escapeXMLAttr(s string) string {
return strings.NewReplacer("&", "&", "<", "<", ">", ">", `"`, """).Replace(s)
}
package eaxmi
import "fmt"
// RootPackages returns the names of the EA root packages (the direct children
// of <uml:Model>).
func (d *Document) RootPackages() []string {
out := make([]string, 0, len(d.Root.Packages))
for _, p := range d.Root.Packages {
out = append(out, p.Name)
}
return out
}
// SetPackageName renames a package (model-tree name attribute, and the
// package_name back-reference on its child elements).
func (d *Document) SetPackageName(id, newName string) error {
pkg, ok := d.packageByID[id]
if !ok {
return fmt.Errorf("eaxmi: no package %q", id)
}
old := pkg.Name
if pe := d.doc.FindElement("//packagedElement[@xmi:id='" + id + "']"); pe != nil {
pe.CreateAttr("name", newName)
}
// the <xmi:Extension> record for a package carries the name too — EA's XMI
// import treats it as authoritative, so it must move in step.
if e := d.extension().FindElement("//element[@xmi:idref='" + id + "']"); e != nil {
e.CreateAttr("name", newName)
}
for _, ep := range d.extension().FindElements("//extendedProperties[@package_name='" + old + "']") {
ep.CreateAttr("package_name", newName)
}
pkg.Name = newName
return nil
}
// RenameRoot renames the single EA root package. With freshIdentity=true it
// first regenerates every GUID in the model (RemapIdentity), so the Saved copy
// imports into EA as a fully independent package next to the original;
// otherwise only the root package gets a fresh id.
func (d *Document) RenameRoot(newName string, freshIdentity bool) error {
if len(d.Root.Packages) != 1 {
return fmt.Errorf("eaxmi: expected exactly one root package, found %d", len(d.Root.Packages))
}
if freshIdentity {
if err := d.RemapIdentity(); err != nil {
return err
}
return d.SetPackageName(d.Root.Packages[0].XMIID, newName)
}
return d.renameRootWithFreshRootID(newName)
}
// renameRootWithFreshRootID gives just the root package a new name and id and
// repoints its direct children.
func (d *Document) renameRootWithFreshRootID(newName string) error {
root := d.Root.Packages[0]
oldID, oldName := root.XMIID, root.Name
newGUID := NewGUID()
newID := xmiIDFromGUID(newGUID, "EAPK_")
oldBody := underscoreBody(root.GUID)
pe := d.doc.FindElement("//packagedElement[@xmi:id='" + oldID + "']")
if pe == nil {
return fmt.Errorf("eaxmi: root package node %q not found", oldID)
}
pe.CreateAttr("xmi:id", newID)
pe.CreateAttr("name", newName)
if el := d.extension().FindElement("//element[@xmi:idref='" + oldID + "']"); el != nil {
el.CreateAttr("xmi:idref", newID)
el.CreateAttr("name", newName)
}
// direct children reference the root by id in several attributes
for _, attr := range []string{"package", "package2", "owner"} {
for _, m := range d.doc.FindElements("//*[@" + attr + "='" + oldID + "']") {
m.CreateAttr(attr, newID)
}
for _, m := range d.doc.FindElements("//*[@" + attr + "='EAID_" + oldBody + "']") {
m.CreateAttr(attr, "EAID_"+underscoreBody(newGUID))
}
}
for _, ep := range d.extension().FindElements("//extendedProperties[@package_name='" + oldName + "']") {
ep.CreateAttr("package_name", newName)
}
delete(d.packageByID, oldID)
root.XMIID, root.GUID, root.Name = newID, newGUID, newName
d.packageByID[newID] = root
return nil
}
package eaxmi
import "fmt"
// Mutation of packages: create, move (re-parent) and remove (recursively). The
// model-tree <packagedElement xmi:type="uml:Package"> and the matching
// <xmi:Extension>/<elements>/<element ea_eleType="package"> record are kept in
// step, as is the parsed model.
// AddPackage creates a package named name inside parentID and returns it.
func (d *Document) AddPackage(parentID, name string) (*Package, error) {
parent, ok := d.packageByID[parentID]
if !ok {
return nil, fmt.Errorf("eaxmi: no package %q", parentID)
}
host := d.doc.FindElement("//packagedElement[@xmi:id='" + parentID + "']")
if host == nil {
return nil, fmt.Errorf("eaxmi: package node %q not found", parentID)
}
guid := NewGUID()
id := xmiIDFromGUID(guid, "EAPK_")
// 1. model tree
pe := host.CreateElement("packagedElement")
pe.CreateAttr("xmi:type", "uml:Package")
pe.CreateAttr("xmi:id", id)
pe.CreateAttr("name", name)
pe.CreateAttr("visibility", "public")
// 2. extension record
els := d.extensionElementsBlock()
el := els.CreateElement("element")
el.CreateAttr("xmi:idref", id)
el.CreateAttr("xmi:type", "uml:Package")
el.CreateAttr("name", name)
el.CreateAttr("scope", "public")
m := el.CreateElement("model")
m.CreateAttr("package2", "EAID_"+underscoreBody(guid))
m.CreateAttr("package", parentID)
m.CreateAttr("tpos", "0")
m.CreateAttr("ea_localid", "0")
m.CreateAttr("ea_eleType", "package")
pr := el.CreateElement("properties")
pr.CreateAttr("isSpecification", "false")
pr.CreateAttr("sType", "Package")
pr.CreateAttr("nType", "0")
pr.CreateAttr("scope", "public")
proj := el.CreateElement("project")
proj.CreateAttr("author", genAuthor)
proj.CreateAttr("version", "1.0")
proj.CreateAttr("phase", "1.0")
proj.CreateAttr("status", "Proposed")
st := el.CreateElement("style")
st.CreateAttr("appearance", "BackColor=-1;BorderColor=-1;BorderWidth=1;FontColor=-1;VSwimLanes=1;HSwimLanes=1;BorderStyle=0;")
// 3. parsed model
np := &Package{XMIID: id, GUID: guid, Name: name, Parent: parent}
parent.Packages = append(parent.Packages, np)
d.packageByID[id] = np
return np, nil
}
// MovePackage re-parents pkgID under newParentID.
func (d *Document) MovePackage(pkgID, newParentID string) error {
pkg, ok := d.packageByID[pkgID]
if !ok {
return fmt.Errorf("eaxmi: no package %q", pkgID)
}
newParent, ok := d.packageByID[newParentID]
if !ok {
return fmt.Errorf("eaxmi: no package %q", newParentID)
}
pe := d.doc.FindElement("//packagedElement[@xmi:id='" + pkgID + "']")
newHost := d.doc.FindElement("//packagedElement[@xmi:id='" + newParentID + "']")
if pe == nil || newHost == nil {
return fmt.Errorf("eaxmi: package node not found")
}
if p := pe.Parent(); p != nil {
p.RemoveChild(pe)
}
newHost.AddChild(pe)
if m := d.extension().FindElement("//element[@xmi:idref='" + pkgID + "']/model"); m != nil {
m.CreateAttr("package", newParentID)
}
if pkg.Parent != nil {
pkg.Parent.Packages = removePackage(pkg.Parent.Packages, pkg)
}
newParent.Packages = append(newParent.Packages, pkg)
pkg.Parent = newParent
return nil
}
// RemovePackage removes pkgID and everything under it: sub-packages, elements
// (with every relationship attached to them) and diagrams. It returns the number
// of model objects removed, the package itself included.
func (d *Document) RemovePackage(pkgID string) (int, error) {
pkg, ok := d.packageByID[pkgID]
if !ok {
return 0, fmt.Errorf("eaxmi: no package %q", pkgID)
}
removed := 0
var rec func(p *Package)
rec = func(p *Package) {
for _, e := range append([]*Element(nil), p.Elements...) {
if err := d.RemoveElement(e.XMIID); err == nil {
removed++
}
}
for _, g := range append([]*Diagram(nil), p.Diagrams...) {
d.removeDiagram(g)
removed++
}
for _, sub := range append([]*Package(nil), p.Packages...) {
rec(sub)
}
d.deleteByID("packagedElement", p.XMIID)
d.deleteExtByIDRef("element", p.XMIID)
delete(d.packageByID, p.XMIID)
removed++
}
rec(pkg)
if pkg.Parent != nil {
pkg.Parent.Packages = removePackage(pkg.Parent.Packages, pkg)
}
return removed, nil
}
// removeDiagram drops a diagram's <xmi:Extension> record and detaches it from
// its package.
func (d *Document) removeDiagram(g *Diagram) {
for _, dg := range d.extension().FindElements("//diagram[@xmi:id='" + g.XMIID + "']") {
if p := dg.Parent(); p != nil {
p.RemoveChild(dg)
}
}
delete(d.diagramByID, g.XMIID)
if g.Package != nil {
g.Package.Diagrams = removeDiagramFrom(g.Package.Diagrams, g)
}
}
func removePackage(s []*Package, x *Package) []*Package {
out := s[:0]
for _, p := range s {
if p != x {
out = append(out, p)
}
}
return out
}
func removeDiagramFrom(s []*Diagram, x *Diagram) []*Diagram {
out := s[:0]
for _, g := range s {
if g != x {
out = append(out, g)
}
}
return out
}
package eaxmi
import (
"fmt"
"strconv"
"strings"
"github.com/beevik/etree"
)
// connectorUMLTypes are the xmi:type values that denote a relationship rather
// than a model element when they appear as <packagedElement>.
var connectorUMLTypes = map[string]bool{
"uml:Dependency": true, "uml:Association": true, "uml:Realization": true,
"uml:Abstraction": true, "uml:Usage": true, "uml:Generalization": true,
"uml:ControlFlow": true, "uml:ObjectFlow": true, "uml:InformationFlow": true,
"uml:Deployment": true, "uml:Aggregation": true, "uml:NestingLink": true,
"uml:PackageMerge": true, "uml:PackageImport": true,
}
func parse(doc *etree.Document) (*Document, error) {
xmi := doc.SelectElement("XMI")
if xmi == nil {
return nil, fmt.Errorf("eaxmi: no <xmi:XMI> root element")
}
umlModel := xmi.FindElement("Model")
if umlModel == nil {
return nil, fmt.Errorf("eaxmi: no <uml:Model> element")
}
d := &Document{
doc: doc,
elementByID: map[string]*Element{},
diagramByID: map[string]*Diagram{},
packageByID: map[string]*Package{},
}
if docEl := xmi.FindElement("Documentation"); docEl != nil {
d.ExporterVersion = docEl.SelectAttrValue("exporterVersion", "")
}
root := &Package{Name: umlModel.SelectAttrValue("name", "EA_Model")}
d.Root = root
d.parseModelTree(umlModel, root)
if ext := xmi.FindElement("Extension"); ext != nil {
d.enrichElements(ext)
d.enrichConnectors(ext)
d.parseDiagrams(ext)
}
return d, nil
}
// parseModelTree walks a package's <packagedElement> children.
func (d *Document) parseModelTree(node *etree.Element, pkg *Package) {
for _, child := range node.ChildElements() {
tag := child.Tag
typ := child.SelectAttrValue("xmi:type", "")
switch {
case tag == "packagedElement" && typ == "uml:Package":
sub := &Package{
XMIID: child.SelectAttrValue("xmi:id", ""),
Name: child.SelectAttrValue("name", ""),
Parent: pkg,
}
sub.GUID = guidFromXMIID(sub.XMIID)
pkg.Packages = append(pkg.Packages, sub)
if sub.XMIID != "" {
d.packageByID[sub.XMIID] = sub
}
d.parseModelTree(child, sub)
case tag == "edge" || connectorUMLTypes[typ] ||
child.SelectAttr("source") != nil || child.SelectAttr("supplier") != nil:
// Relationship. The authoritative record is in <xmi:Extension>;
// here we only register its id so connectors declared solely in the
// model tree are not lost.
id := child.SelectAttrValue("xmi:id", "")
if id != "" && d.connectorByID(id) == nil {
d.connectorAll = append(d.connectorAll, &Connector{
XMIID: id,
GUID: guidFromXMIID(id),
Name: child.SelectAttrValue("name", ""),
EAType: strings.TrimPrefix(typ, "uml:"),
SourceID: firstNonEmpty(
child.SelectAttrValue("source", ""),
child.SelectAttrValue("client", ""),
),
TargetID: firstNonEmpty(
child.SelectAttrValue("target", ""),
child.SelectAttrValue("supplier", ""),
),
})
}
case tag == "packagedElement" && typ != "":
el := &Element{
XMIID: child.SelectAttrValue("xmi:id", ""),
Name: child.SelectAttrValue("name", ""),
UMLType: typ,
Package: pkg,
}
el.GUID = guidFromXMIID(el.XMIID)
pkg.Elements = append(pkg.Elements, el)
if el.XMIID != "" {
d.elementByID[el.XMIID] = el
}
}
}
}
func (d *Document) enrichElements(ext *etree.Element) {
for _, elsBlock := range ext.SelectElements("elements") {
for _, e := range elsBlock.SelectElements("element") {
id := e.SelectAttrValue("xmi:idref", "")
if strings.HasPrefix(id, "EAPK") {
if pkg := d.packageByID[id]; pkg != nil {
if m := e.SelectElement("model"); m != nil {
pkg.EALocalID = m.SelectAttrValue("ea_localid", "")
}
}
continue
}
el := d.elementByID[id]
if el == nil {
continue
}
if m := e.SelectElement("model"); m != nil {
el.EALocalID = m.SelectAttrValue("ea_localid", "")
}
if p := e.SelectElement("properties"); p != nil {
el.Stereotype = p.SelectAttrValue("stereotype", "")
el.Documentation = p.SelectAttrValue("documentation", "")
}
if pr := e.SelectElement("project"); pr != nil {
el.Author = pr.SelectAttrValue("author", "")
}
}
}
}
func (d *Document) enrichConnectors(ext *etree.Element) {
for _, consBlock := range ext.SelectElements("connectors") {
for _, c := range consBlock.SelectElements("connector") {
id := c.SelectAttrValue("xmi:idref", "")
conn := d.connectorByID(id)
if conn == nil {
conn = &Connector{XMIID: id, GUID: guidFromXMIID(id)}
d.connectorAll = append(d.connectorAll, conn)
}
if n := c.SelectAttrValue("name", ""); n != "" {
conn.Name = n
}
if s := c.SelectElement("source"); s != nil {
conn.SourceID = s.SelectAttrValue("xmi:idref", "")
}
if t := c.SelectElement("target"); t != nil {
conn.TargetID = t.SelectAttrValue("xmi:idref", "")
}
if m := c.SelectElement("model"); m != nil {
conn.EALocalID = m.SelectAttrValue("ea_localid", "")
}
if p := c.SelectElement("properties"); p != nil {
if v := p.SelectAttrValue("ea_type", ""); v != "" {
conn.EAType = v
}
conn.Stereotype = p.SelectAttrValue("stereotype", "")
conn.Direction = p.SelectAttrValue("direction", "")
}
if doc := c.SelectElement("documentation"); doc != nil {
conn.Documentation = doc.SelectAttrValue("value", "")
}
}
}
}
func (d *Document) parseDiagrams(ext *etree.Element) {
for _, diasBlock := range ext.SelectElements("diagrams") {
for _, dg := range diasBlock.SelectElements("diagram") {
g := &Diagram{
XMIID: dg.SelectAttrValue("xmi:id", ""),
}
g.GUID = guidFromXMIID(g.XMIID)
if m := dg.SelectElement("model"); m != nil {
g.EALocalID = m.SelectAttrValue("localID", "")
owner := firstNonEmpty(m.SelectAttrValue("owner", ""), m.SelectAttrValue("package", ""))
if pkg := d.packageByID[owner]; pkg != nil {
g.Package = pkg
pkg.Diagrams = append(pkg.Diagrams, g)
}
}
if p := dg.SelectElement("properties"); p != nil {
g.Name = p.SelectAttrValue("name", "")
g.Type = p.SelectAttrValue("type", "")
g.Documentation = p.SelectAttrValue("documentation", "")
}
if elsBlock := dg.SelectElement("elements"); elsBlock != nil {
for _, e := range elsBlock.SelectElements("element") {
subj := e.SelectAttrValue("subject", "")
geo := e.SelectAttrValue("geometry", "")
if strings.HasPrefix(geo, "SX=") || strings.HasPrefix(geo, "SX =") {
// connector placement (EA auto-routes; no rectangle)
g.Links = append(g.Links, &DiagramLink{ConnectorID: subj})
continue
}
obj := &DiagramObject{
SubjectID: subj,
Seq: atoiOr(e.SelectAttrValue("seqno", ""), 0),
}
obj.Left, obj.Top, obj.Right, obj.Bottom = parseGeometry(geo)
g.Objects = append(g.Objects, obj)
}
}
if g.XMIID != "" {
d.diagramByID[g.XMIID] = g
}
}
}
}
func (d *Document) connectorByID(id string) *Connector {
for _, c := range d.connectorAll {
if c.XMIID == id {
return c
}
}
return nil
}
// parseGeometry parses "Left=520;Top=680;Right=610;Bottom=750;".
func parseGeometry(s string) (left, top, right, bottom int) {
for _, kv := range strings.Split(s, ";") {
k, v, ok := strings.Cut(kv, "=")
if !ok {
continue
}
n := atoiOr(v, 0)
switch k {
case "Left":
left = n
case "Top":
top = n
case "Right":
right = n
case "Bottom":
bottom = n
}
}
return
}
func atoiOr(s string, def int) int {
if n, err := strconv.Atoi(strings.TrimSpace(s)); err == nil {
return n
}
return def
}
func firstNonEmpty(vs ...string) string {
for _, v := range vs {
if v != "" {
return v
}
}
return ""
}
package eaxmi
import (
"crypto/rand"
"fmt"
"strings"
"github.com/beevik/etree"
)
// This file adds mutation to the codec. Edits are applied to the underlying
// etree document so the parts eaxmi does not model are preserved; WriteFile
// serialises the whole thing back. The generated shape follows a real EA
// "Export Package to XMI" (see example/TestProject2-Model.xml); whether EA's
// importer needs every detail is confirmed by round-tripping through EA.
// NewGUID returns a fresh EA-style GUID, e.g. "{A0D485C0-C57E-4A4D-8FF1-66D594FA6778}".
func NewGUID() string {
var b [16]byte
_, _ = rand.Read(b[:])
b[6] = (b[6] & 0x0f) | 0x40
b[8] = (b[8] & 0x3f) | 0x80
return fmt.Sprintf("{%X-%X-%X-%X-%X}", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
}
// xmiIDFromGUID converts "{A-B-C-D-E}" to "EAID_A_B_C_D_E" (or the EAPK_ form).
func xmiIDFromGUID(guid, prefix string) string {
body := strings.TrimSuffix(strings.TrimPrefix(guid, "{"), "}")
return prefix + strings.ReplaceAll(body, "-", "_")
}
// ElementSpec describes an element to create.
type ElementSpec struct {
Name string
UMLType string // "uml:Class" / "uml:Activity"
Stereotype string // "ArchiMate_Goal"
Documentation string
Author string
}
// ConnectorSpec describes a relationship to create.
type ConnectorSpec struct {
SourceID string
TargetID string
Name string
EAType string // "Association" / "ControlFlow" / "Dependency" / "Generalization"
ModelRepr string // "association" / "controlflow" / "dependency" / "generalization"
Stereotype string // "ArchiMate_Composition"
Direction string
Documentation string
Author string
}
const genAuthor = "mcp-server-sparx-ea"
// modelPackageElement returns the <packagedElement xmi:type="uml:Package"> node
// for a package id, or the <uml:Model> node for the root.
func (d *Document) modelPackageElement(pkgID string) *etree.Element {
umlModel := d.doc.FindElement("//Model")
if pkgID == "" {
return umlModel
}
return umlModel.FindElement("//packagedElement[@xmi:id='" + pkgID + "']")
}
func (d *Document) extension() *etree.Element {
return d.doc.FindElement("//Extension")
}
// umlModel is <uml:Model>, the semantic tree. EA puts the ArchiMate profile
// applications (<ArchiMate3:ArchiMate_Goal base_Class="…"/> …) here, as direct
// children of the model — not in <xmi:Extension>.
func (d *Document) umlModel() *etree.Element {
return d.doc.FindElement("//Model")
}
// AddElement creates an element in the package pkgID (an "" pkgID means the
// model root). It updates both the model tree and the <xmi:Extension> block and
// returns the new Element.
func (d *Document) AddElement(pkgID string, spec ElementSpec) (*Element, error) {
host := d.modelPackageElement(pkgID)
if host == nil {
return nil, fmt.Errorf("eaxmi: no package %q", pkgID)
}
pkg := d.packageByID[pkgID]
if pkgID == "" {
pkg = d.Root
}
guid := NewGUID()
id := xmiIDFromGUID(guid, "EAID_")
author := spec.Author
if author == "" {
author = genAuthor
}
// 1. model tree
pe := host.CreateElement("packagedElement")
pe.CreateAttr("xmi:type", spec.UMLType)
pe.CreateAttr("xmi:id", id)
pe.CreateAttr("name", spec.Name)
pe.CreateAttr("visibility", "public")
if spec.UMLType == "uml:Interface" {
pe.CreateAttr("isAbstract", "true")
}
// 2. extension <elements><element>
els := d.extensionElementsBlock()
el := els.CreateElement("element")
el.CreateAttr("xmi:idref", id)
el.CreateAttr("xmi:type", spec.UMLType)
el.CreateAttr("name", spec.Name)
el.CreateAttr("scope", "public")
m := el.CreateElement("model")
m.CreateAttr("package", pkgID)
m.CreateAttr("tpos", "0")
m.CreateAttr("ea_localid", "0")
m.CreateAttr("ea_eleType", "element")
pr := el.CreateElement("properties")
if spec.Documentation != "" {
pr.CreateAttr("documentation", spec.Documentation)
}
pr.CreateAttr("isSpecification", "false")
pr.CreateAttr("sType", strings.TrimPrefix(spec.UMLType, "uml:"))
pr.CreateAttr("nType", "0")
pr.CreateAttr("scope", "public")
if spec.Stereotype != "" {
pr.CreateAttr("stereotype", spec.Stereotype)
}
pr.CreateAttr("isRoot", "false")
pr.CreateAttr("isLeaf", "false")
if spec.UMLType == "uml:Interface" {
pr.CreateAttr("isAbstract", "true")
} else {
pr.CreateAttr("isAbstract", "false")
}
pr.CreateAttr("isActive", "false")
proj := el.CreateElement("project")
proj.CreateAttr("author", author)
proj.CreateAttr("version", "1.0")
proj.CreateAttr("phase", "1.0")
proj.CreateAttr("status", "Proposed")
st := el.CreateElement("style")
st.CreateAttr("appearance", "BackColor=-1;BorderColor=-1;BorderWidth=1;FontColor=-1;VSwimLanes=1;HSwimLanes=1;BorderStyle=0;")
ep := el.CreateElement("extendedProperties")
ep.CreateAttr("tagged", "0")
if pkg != nil {
ep.CreateAttr("package_name", pkg.Name)
}
el.CreateElement("links")
// 3. profile application
if spec.Stereotype != "" {
d.addProfileApplication(spec.Stereotype, "base_"+strings.TrimPrefix(spec.UMLType, "uml:"), id)
}
// 4. update the parsed model
newEl := &Element{
XMIID: id, GUID: guid, Name: spec.Name, UMLType: spec.UMLType,
Stereotype: spec.Stereotype, Documentation: spec.Documentation,
Author: author, Package: pkg,
}
d.elementByID[id] = newEl
if pkg != nil {
pkg.Elements = append(pkg.Elements, newEl)
}
return newEl, nil
}
// AddConnector creates a relationship. It returns the new Connector.
func (d *Document) AddConnector(spec ConnectorSpec) (*Connector, error) {
src, ok := d.elementByID[spec.SourceID]
if !ok {
return nil, fmt.Errorf("eaxmi: no source element %q", spec.SourceID)
}
if _, ok := d.elementByID[spec.TargetID]; !ok {
return nil, fmt.Errorf("eaxmi: no target element %q", spec.TargetID)
}
guid := NewGUID()
id := xmiIDFromGUID(guid, "EAID_")
author := spec.Author
if author == "" {
author = genAuthor
}
hostPkgID := ""
if src.Package != nil {
hostPkgID = src.Package.XMIID
}
host := d.modelPackageElement(hostPkgID)
// 1. model tree representation
switch spec.ModelRepr {
case "controlflow":
e := host.CreateElement("edge")
e.CreateAttr("xmi:type", "uml:"+spec.EAType)
e.CreateAttr("xmi:id", id)
if spec.Name != "" {
e.CreateAttr("name", spec.Name)
}
e.CreateAttr("visibility", "public")
e.CreateAttr("source", spec.SourceID)
e.CreateAttr("target", spec.TargetID)
case "dependency":
pe := host.CreateElement("packagedElement")
pe.CreateAttr("xmi:type", "uml:Dependency")
pe.CreateAttr("xmi:id", id)
if spec.Name != "" {
pe.CreateAttr("name", spec.Name)
}
pe.CreateAttr("visibility", "public")
pe.CreateAttr("supplier", spec.TargetID)
pe.CreateAttr("client", spec.SourceID)
case "generalization":
srcPE := d.modelPackageElement(hostPkgID).FindElement("packagedElement[@xmi:id='" + spec.SourceID + "']")
if srcPE == nil {
return nil, fmt.Errorf("eaxmi: source element node not found for generalization")
}
g := srcPE.CreateElement("generalization")
g.CreateAttr("xmi:type", "uml:Generalization")
g.CreateAttr("xmi:id", id)
g.CreateAttr("general", spec.TargetID)
default: // "association"
pe := host.CreateElement("packagedElement")
pe.CreateAttr("xmi:type", "uml:Association")
pe.CreateAttr("xmi:id", id)
if spec.Name != "" {
pe.CreateAttr("name", spec.Name)
}
pe.CreateAttr("visibility", "public")
srcEnd := "EAID_src" + strings.TrimPrefix(id, "EAID_")[2:]
dstEnd := "EAID_dst" + strings.TrimPrefix(id, "EAID_")[2:]
pe.CreateElement("memberEnd").CreateAttr("xmi:idref", dstEnd)
pe.CreateElement("memberEnd").CreateAttr("xmi:idref", srcEnd)
d.ownedEnd(pe, srcEnd, id, spec.SourceID)
d.ownedEnd(pe, dstEnd, id, spec.TargetID)
}
// 2. extension <connectors><connector>
cons := d.extensionConnectorsBlock()
c := cons.CreateElement("connector")
c.CreateAttr("xmi:idref", id)
if spec.Name != "" {
c.CreateAttr("name", spec.Name)
}
s := c.CreateElement("source")
s.CreateAttr("xmi:idref", spec.SourceID)
d.connEndModel(s, spec.SourceID)
t := c.CreateElement("target")
t.CreateAttr("xmi:idref", spec.TargetID)
d.connEndModel(t, spec.TargetID)
c.CreateElement("model").CreateAttr("ea_localid", "0")
p := c.CreateElement("properties")
p.CreateAttr("ea_type", spec.EAType)
if spec.Stereotype != "" {
p.CreateAttr("stereotype", spec.Stereotype)
}
if spec.Direction != "" {
p.CreateAttr("direction", spec.Direction)
}
ap := c.CreateElement("appearance")
ap.CreateAttr("linemode", "3")
ap.CreateAttr("linecolor", "-1")
ap.CreateAttr("linewidth", "0")
ap.CreateAttr("seqno", "0")
ap.CreateAttr("headStyle", "0")
ap.CreateAttr("lineStyle", "0")
if spec.Documentation != "" {
c.CreateElement("documentation").CreateAttr("value", spec.Documentation)
}
// 3. profile application
if spec.Stereotype != "" {
d.addProfileApplication(spec.Stereotype, "base_"+spec.EAType, id)
}
// 4. source element <links>
if links := d.extension().FindElement("//element[@xmi:idref='" + spec.SourceID + "']/links"); links != nil {
l := links.CreateElement(spec.EAType)
l.CreateAttr("xmi:id", id)
l.CreateAttr("start", spec.SourceID)
l.CreateAttr("end", spec.TargetID)
}
conn := &Connector{
XMIID: id, GUID: guid, Name: spec.Name, Documentation: spec.Documentation,
EAType: spec.EAType, Stereotype: spec.Stereotype, Direction: spec.Direction,
SourceID: spec.SourceID, TargetID: spec.TargetID,
}
d.connectorAll = append(d.connectorAll, conn)
return conn, nil
}
func (d *Document) ownedEnd(assoc *etree.Element, endID, assocID, typeID string) {
oe := assoc.CreateElement("ownedEnd")
oe.CreateAttr("xmi:type", "uml:Property")
oe.CreateAttr("xmi:id", endID)
oe.CreateAttr("visibility", "public")
oe.CreateAttr("association", assocID)
oe.CreateAttr("aggregation", "none")
oe.CreateElement("type").CreateAttr("xmi:idref", typeID)
}
func (d *Document) connEndModel(end *etree.Element, elemID string) {
m := end.CreateElement("model")
if el, ok := d.elementByID[elemID]; ok {
m.CreateAttr("type", strings.TrimPrefix(el.UMLType, "uml:"))
m.CreateAttr("name", el.Name)
}
r := end.CreateElement("role")
r.CreateAttr("visibility", "Public")
r.CreateAttr("targetScope", "instance")
end.CreateElement("type").CreateAttr("containment", "Unspecified")
}
// MoveElement re-parents an element into newPkgID.
func (d *Document) MoveElement(id, newPkgID string) error {
el, ok := d.elementByID[id]
if !ok {
return fmt.Errorf("eaxmi: no element %q", id)
}
newPkg, ok := d.packageByID[newPkgID]
if !ok {
return fmt.Errorf("eaxmi: no package %q", newPkgID)
}
pe := d.doc.FindElement("//packagedElement[@xmi:id='" + id + "']")
newHost := d.doc.FindElement("//packagedElement[@xmi:id='" + newPkgID + "']")
if pe == nil || newHost == nil {
return fmt.Errorf("eaxmi: element or package node not found")
}
if p := pe.Parent(); p != nil {
p.RemoveChild(pe)
}
newHost.AddChild(pe)
if m := d.extension().FindElement("//element[@xmi:idref='" + id + "']/model"); m != nil {
m.CreateAttr("package", newPkgID)
}
if ep := d.extension().FindElement("//element[@xmi:idref='" + id + "']/extendedProperties"); ep != nil {
ep.CreateAttr("package_name", newPkg.Name)
}
if el.Package != nil {
el.Package.Elements = removeElement(el.Package.Elements, el)
}
newPkg.Elements = append(newPkg.Elements, el)
el.Package = newPkg
return nil
}
// RemoveElement deletes an element and every connector that touches it.
func (d *Document) RemoveElement(id string) error {
el, ok := d.elementByID[id]
if !ok {
return fmt.Errorf("eaxmi: no element %q", id)
}
for _, c := range append([]*Connector(nil), d.connectorAll...) {
if c.SourceID == id || c.TargetID == id {
_ = d.RemoveConnector(c.XMIID)
}
}
d.deleteByID("packagedElement", id)
d.deleteExtByIDRef("element", id)
d.deleteProfileApplication(id)
d.removeDiagramReferences(id)
delete(d.elementByID, id)
if el.Package != nil {
el.Package.Elements = removeElement(el.Package.Elements, el)
}
return nil
}
// RemoveConnector deletes a relationship.
func (d *Document) RemoveConnector(id string) error {
var conn *Connector
for _, c := range d.connectorAll {
if c.XMIID == id {
conn = c
break
}
}
if conn == nil {
return fmt.Errorf("eaxmi: no connector %q", id)
}
d.deleteByID("packagedElement", id)
d.deleteByID("edge", id)
d.deleteByID("generalization", id)
d.deleteExtByIDRef("connector", id)
d.deleteProfileApplication(id)
d.removeDiagramReferences(id)
for _, links := range d.doc.FindElements("//links") {
for _, l := range links.ChildElements() {
if l.SelectAttrValue("xmi:id", "") == id {
links.RemoveChild(l)
}
}
}
d.connectorAll = removeConnector(d.connectorAll, conn)
return nil
}
// SetElementName / SetElementDocumentation change one basic property.
func (d *Document) SetElementName(id, name string) error {
el, ok := d.elementByID[id]
if !ok {
return fmt.Errorf("eaxmi: no element %q", id)
}
if pe := d.doc.FindElement("//packagedElement[@xmi:id='" + id + "']"); pe != nil {
pe.CreateAttr("name", name)
}
if e := d.extension().FindElement("//element[@xmi:idref='" + id + "']"); e != nil {
e.CreateAttr("name", name)
}
el.Name = name
return nil
}
func (d *Document) SetElementDocumentation(id, doc string) error {
el, ok := d.elementByID[id]
if !ok {
return fmt.Errorf("eaxmi: no element %q", id)
}
e := d.extension().FindElement("//element[@xmi:idref='" + id + "']/properties")
if e != nil {
e.CreateAttr("documentation", doc)
}
el.Documentation = doc
return nil
}
// AddDiagramObject places an element on a diagram.
func (d *Document) AddDiagramObject(diagramID, elementID string, left, top, right, bottom int) error {
g, ok := d.diagramByID[diagramID]
if !ok {
return fmt.Errorf("eaxmi: no diagram %q", diagramID)
}
if _, ok := d.elementByID[elementID]; !ok {
return fmt.Errorf("eaxmi: no element %q", elementID)
}
dg := d.extension().FindElement("//diagram[@xmi:id='" + diagramID + "']")
if dg == nil {
return fmt.Errorf("eaxmi: diagram node %q not found", diagramID)
}
els := dg.FindElement("elements")
if els == nil {
els = dg.CreateElement("elements")
}
seq := len(g.Objects) + 1
o := els.CreateElement("element")
o.CreateAttr("geometry", fmt.Sprintf("Left=%d;Top=%d;Right=%d;Bottom=%d;", left, top, right, bottom))
o.CreateAttr("subject", elementID)
o.CreateAttr("seqno", fmt.Sprintf("%d", seq))
o.CreateAttr("style", "DUID="+strings.ToUpper(strings.TrimPrefix(NewGUID(), "{")[:8])+";UCRect=1;HideIcon=0;")
g.Objects = append(g.Objects, &DiagramObject{
SubjectID: elementID, Seq: seq,
Left: left, Top: top, Right: right, Bottom: bottom,
})
return nil
}
// RemoveDiagramObject removes an element's placement from a diagram (the element
// itself is untouched).
func (d *Document) RemoveDiagramObject(diagramID, elementID string) error {
g, ok := d.diagramByID[diagramID]
if !ok {
return fmt.Errorf("eaxmi: no diagram %q", diagramID)
}
dg := d.extension().FindElement("//diagram[@xmi:id='" + diagramID + "']")
if dg == nil {
return fmt.Errorf("eaxmi: diagram node %q not found", diagramID)
}
removed := false
if els := dg.FindElement("elements"); els != nil {
for _, o := range els.ChildElements() {
if o.SelectAttrValue("subject", "") == elementID && !strings.HasPrefix(o.SelectAttrValue("geometry", ""), "SX=") {
els.RemoveChild(o)
removed = true
}
}
}
if !removed {
return fmt.Errorf("eaxmi: element %q is not on diagram %q", elementID, diagramID)
}
var kept []*DiagramObject
for _, o := range g.Objects {
if o.SubjectID != elementID {
kept = append(kept, o)
}
}
g.Objects = kept
return nil
}
// WriteFile serialises the (possibly edited) document to path. etree writes
// UTF-8, so the XML declaration is normalised to UTF-8 (EA reads either, and
// keeping a windows-1252 declaration on UTF-8 bytes would corrupt Cyrillic).
func (d *Document) WriteFile(path string) error {
for _, tok := range d.doc.Child {
if pi, ok := tok.(*etree.ProcInst); ok && pi.Target == "xml" {
pi.Inst = `version="1.0" encoding="UTF-8"`
}
}
d.doc.Indent(2)
return d.doc.WriteToFile(path)
}
// ---------- low-level helpers ----------
func (d *Document) extensionElementsBlock() *etree.Element {
ext := d.extension()
if b := ext.FindElement("elements"); b != nil {
return b
}
return ext.CreateElement("elements")
}
func (d *Document) extensionConnectorsBlock() *etree.Element {
ext := d.extension()
if b := ext.FindElement("connectors"); b != nil {
return b
}
return ext.CreateElement("connectors")
}
func (d *Document) addProfileApplication(stereotype, baseAttr, id string) {
m := d.umlModel()
if m == nil {
return
}
pa := m.CreateElement("ArchiMate3:" + stereotype)
pa.CreateAttr(baseAttr, id)
}
// deleteProfileApplication removes every <ArchiMate3:*> profile application that
// points at id (its base_Class / base_Dependency / base_ControlFlow / … equals
// id). EA keeps these under <uml:Model>; older exports may also carry some in
// <xmi:Extension>, so both are swept.
func (d *Document) deleteProfileApplication(id string) {
for _, parent := range []*etree.Element{d.umlModel(), d.extension()} {
if parent == nil {
continue
}
for _, pa := range parent.ChildElements() {
if pa.Space != "ArchiMate3" {
continue
}
for _, a := range pa.Attr {
if a.Value == id {
parent.RemoveChild(pa)
break
}
}
}
}
}
// removeDiagramReferences drops every on-diagram entry (element box or connector
// line) whose subject is id, across all diagrams, and keeps the in-memory model
// in sync. EA's XMI importer rejects a diagram that references an element or
// connector the import does not contain.
func (d *Document) removeDiagramReferences(id string) {
for _, els := range d.extension().FindElements("//diagram/elements") {
for _, o := range els.ChildElements() {
if o.SelectAttrValue("subject", "") == id {
els.RemoveChild(o)
}
}
}
for _, g := range d.diagramByID {
objs := g.Objects[:0]
for _, o := range g.Objects {
if o.SubjectID != id {
objs = append(objs, o)
}
}
g.Objects = objs
links := g.Links[:0]
for _, l := range g.Links {
if l.ConnectorID != id {
links = append(links, l)
}
}
g.Links = links
}
}
func (d *Document) deleteByID(tag, id string) {
for _, e := range d.doc.FindElements("//" + tag + "[@xmi:id='" + id + "']") {
if e.Parent() != nil {
e.Parent().RemoveChild(e)
}
}
}
func (d *Document) deleteExtByIDRef(tag, id string) {
for _, e := range d.extension().FindElements("//" + tag + "[@xmi:idref='" + id + "']") {
if e.Parent() != nil {
e.Parent().RemoveChild(e)
}
}
}
func removeElement(s []*Element, x *Element) []*Element {
out := s[:0]
for _, e := range s {
if e != x {
out = append(out, e)
}
}
return out
}
func removeConnector(s []*Connector, x *Connector) []*Connector {
out := s[:0]
for _, c := range s {
if c != x {
out = append(out, c)
}
}
return out
}
// Package mcpserver exposes the ArchiMate service over an MCP server (stdio).
//
// ea_model_tree / ea_element / read an exported .xml model
// ea_package / ea_diagram
// ea_archimate_types the type vocabulary
// ea_new_model / … build a model from scratch, add / rename the root
// ea_create_element / … edit a copy of the model and save it
//
// Tool handlers depend on the Model interface; New(nil) wires the real XMI
// service, tests pass a fake through Options.
package mcpserver
import (
"github.com/mark3labs/mcp-go/server"
)
// Version is reported to MCP clients during initialization.
const Version = "0.8.2"
// Options overrides the tool handlers' dependencies. A nil *Options (or a nil
// field) uses the real XMI service.
type Options struct {
Sparx SparxOpener // path -> Model (open an existing export)
NewModel ModelFactory // root name -> Model (build from scratch)
}
func (o *Options) sparx() SparxOpener {
if o != nil && o.Sparx != nil {
return o.Sparx
}
return defaultSparxOpener
}
func (o *Options) newModel() ModelFactory {
if o != nil && o.NewModel != nil {
return o.NewModel
}
return defaultModelFactory
}
// New builds the MCP server with every tool registered. Pass nil for the real
// implementation.
func New(o *Options) *server.MCPServer {
s := server.NewMCPServer(
"mcp-server-sparx-ea",
Version,
server.WithToolCapabilities(false),
server.WithRecovery(),
)
registerSparxTools(s, deps{open: o.sparx(), newModel: o.newModel()})
return s
}
package mcpserver
import "github.com/InsonusK/mcp-server-sparx-ea/internal/service/sparx"
// Model is the slice of the ArchiMate service the sparx tool handlers use.
// *sparx.Service satisfies it; tests supply a fake so the MCP layer can be
// exercised without touching an XMI file.
type Model interface {
Tree() *sparx.Node
Element(ref string) (*sparx.ElementInfo, error)
Package(ref string) (*sparx.PackageInfo, error)
Diagram(ref string) (*sparx.DiagramInfo, error)
CreateRootPackage(name string) (*sparx.PackageInfo, error)
SetRootName(newName string, freshIdentity bool) (string, error)
CreateElement(parentRef, archimateType, name, documentation string) (*sparx.ElementInfo, error)
RenameElement(ref, newName string) (*sparx.ElementInfo, error)
SetElementDocumentation(ref, documentation string) (*sparx.ElementInfo, error)
MoveElement(ref, newParentRef string) (*sparx.ElementInfo, error)
DeleteElement(ref string) error
CreateRelationship(sourceRef, targetRef, archimateRelType, name, documentation string) (*sparx.Relation, error)
DeleteRelationship(id string) error
DeleteRelationshipsBetween(sourceRef, targetRef string) (int, error)
CreatePackage(parentRef, name string) (*sparx.PackageInfo, error)
RenamePackage(ref, newName string) (*sparx.PackageInfo, error)
MovePackage(ref, newParentRef string) (*sparx.PackageInfo, error)
CopyPackage(ref, destParentRef string) (*sparx.PackageInfo, error)
DeletePackage(ref string, cascadeDelete bool) (int, error)
CreateDiagram(parentRef, name, layer string) (*sparx.DiagramInfo, error)
AddToDiagram(diagramRef, elementRef string, at sparx.Rect) error
MoveOnDiagram(diagramRef, elementRef string, at sparx.Rect) error
RemoveFromDiagram(diagramRef, elementRef string) error
Save(path string) error
}
// SparxOpener resolves a model-file path to a Model. Options.Sparx overrides it;
// the default opens the real XMI service.
type SparxOpener func(path string) (Model, error)
func defaultSparxOpener(path string) (Model, error) { return sparx.Open(path) }
// ModelFactory builds a new, empty Model from a root package name.
// Options.NewModel overrides it; the default builds the real XMI service.
type ModelFactory func(rootName string) (Model, error)
func defaultModelFactory(rootName string) (Model, error) {
m, err := sparx.NewModel(rootName)
if err != nil {
return nil, err
}
return m, nil
}
package mcpserver
import (
"context"
"encoding/json"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
// The ArchiMate tools, one file per model concept:
//
// tools_model.go the model tree, the type vocabulary, model lifecycle
// tools_element.go elements: read + create / rename / re-note / move / delete
// tools_relationship.go relationships: create / delete
// tools_package.go packages: read + create / rename / move / copy / delete
// tools_diagram.go diagrams: read + place / move / remove an element
//
// Read tools take a "file" (an exported .xml model). Write tools also take
// "output" and save the edited copy there, never overwriting "file".
// ea_new_model takes no "file" — it builds a model from scratch.
// deps is what the tool registrars need: how to open an existing model and how
// to build a new one.
type deps struct {
open SparxOpener
newModel ModelFactory
}
// registerSparxTools adds every ArchiMate tool, grouped by model concept.
func registerSparxTools(s *server.MCPServer, d deps) {
h := sparxTools{open: d.open, newModel: d.newModel}
registerModelTools(s, h)
registerElementTools(s, h)
registerRelationshipTools(s, h)
registerPackageTools(s, h)
registerDiagramTools(s, h)
}
// ---------- plumbing ----------
type sparxTools struct {
open SparxOpener
newModel ModelFactory
}
type toolFn func(Model, mcp.CallToolRequest) (any, error)
// read wires a read-only tool: open the file, run fn, return its JSON.
func (h sparxTools) read(fn toolFn) server.ToolHandlerFunc {
return func(_ context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
file, err := req.RequireString("file")
if err != nil {
return mcp.NewToolResultError("missing required argument: file"), nil
}
m, err := h.open(file)
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
res, err := fn(m, req)
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
return jsonResult(res)
}
}
// write wires an editing tool: open the file, run fn, save to "output".
func (h sparxTools) write(fn toolFn) server.ToolHandlerFunc {
return func(_ context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
file, err := req.RequireString("file")
if err != nil {
return mcp.NewToolResultError("missing required argument: file"), nil
}
output, err := req.RequireString("output")
if err != nil {
return mcp.NewToolResultError("missing required argument: output"), nil
}
if output == file {
return mcp.NewToolResultError("output must be a different path from file"), nil
}
m, err := h.open(file)
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
res, err := fn(m, req)
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
if err := m.Save(output); err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
return jsonResult(map[string]any{"result": res, "saved": output})
}
}
// create wires a from-scratch tool: build a new model from "root", run fn, save
// to "output". There is no "file" — nothing is opened.
func (h sparxTools) create(fn toolFn) server.ToolHandlerFunc {
return func(_ context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
root, err := req.RequireString("root")
if err != nil {
return mcp.NewToolResultError("missing required argument: root"), nil
}
output, err := req.RequireString("output")
if err != nil {
return mcp.NewToolResultError("missing required argument: output"), nil
}
m, err := h.newModel(root)
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
res, err := fn(m, req)
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
if err := m.Save(output); err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
return jsonResult(map[string]any{"result": res, "saved": output})
}
}
func jsonResult(v any) (*mcp.CallToolResult, error) {
b, err := json.Marshal(v)
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
return mcp.NewToolResultText(string(b)), nil
}
func deleted(err error) (any, error) {
if err != nil {
return nil, err
}
return map[string]any{"deleted": true}, nil
}
func mustInt(r mcp.CallToolRequest, key string) int {
n, _ := r.RequireInt(key)
return n
}
// ---------- tool-arg shorthands ----------
func fileArg() mcp.ToolOption {
return mcp.WithString("file", mcp.Required(), mcp.Description("path to the exported .xml model on the server's filesystem"))
}
func outputArg() mcp.ToolOption {
return mcp.WithString("output", mcp.Required(), mcp.Description("path to write the edited copy to (must differ from 'file'); import it into EA"))
}
func refArg(what string) mcp.ToolOption {
return mcp.WithString("ref", mcp.Required(), mcp.Description(what))
}
package mcpserver
import (
"github.com/InsonusK/mcp-server-sparx-ea/internal/service/sparx"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
// registerDiagramTools adds the diagram tools: read one diagram, create a
// diagram, and place / move / remove an element on it.
func registerDiagramTools(s *server.MCPServer, h sparxTools) {
s.AddTool(mcp.NewTool("ea_diagram",
mcp.WithDescription("One diagram by id, GUID or slash path: its type and the elements placed on it with coordinates."),
fileArg(), refArg("the diagram"),
), h.read(func(m Model, r mcp.CallToolRequest) (any, error) { return m.Diagram(r.GetString("ref", "")) }))
s.AddTool(mcp.NewTool("ea_create_diagram",
mcp.WithDescription("Add an empty diagram to a package, then fill it with ea_place_on_diagram. "+
"'layer' is an optional ArchiMate viewpoint (Motivation, Strategy, Business, Application, "+
"Technology, Physical, Implementation_Migration) that picks EA's toolbox; omit it for a plain diagram."),
fileArg(), outputArg(),
mcp.WithString("parent", mcp.Required(), mcp.Description("the package to add the diagram to (id, GUID or path)")),
mcp.WithString("name", mcp.Required()),
mcp.WithString("layer", mcp.Description("ArchiMate viewpoint / EA toolbox (optional)")),
), h.write(func(m Model, r mcp.CallToolRequest) (any, error) {
return m.CreateDiagram(r.GetString("parent", ""), r.GetString("name", ""), r.GetString("layer", ""))
}))
place := func(op func(m Model, d, e string, at sparx.Rect) error) toolFn {
return func(m Model, r mcp.CallToolRequest) (any, error) {
at := sparx.Rect{Left: mustInt(r, "left"), Top: mustInt(r, "top"), Right: mustInt(r, "right"), Bottom: mustInt(r, "bottom")}
if err := op(m, r.GetString("diagram", ""), r.GetString("element", ""), at); err != nil {
return nil, err
}
return m.Diagram(r.GetString("diagram", ""))
}
}
s.AddTool(diagramTool("ea_place_on_diagram",
"Place an element on a diagram at a rectangle (EA coordinates: origin top-left).", true),
h.write(place(func(m Model, d, e string, at sparx.Rect) error { return m.AddToDiagram(d, e, at) })))
s.AddTool(diagramTool("ea_move_on_diagram",
"Move an element already on a diagram to a new rectangle.", true),
h.write(place(func(m Model, d, e string, at sparx.Rect) error { return m.MoveOnDiagram(d, e, at) })))
s.AddTool(diagramTool("ea_remove_from_diagram",
"Remove an element's placement from a diagram (the element itself stays in the model).", false),
h.write(func(m Model, r mcp.CallToolRequest) (any, error) {
if err := m.RemoveFromDiagram(r.GetString("diagram", ""), r.GetString("element", "")); err != nil {
return nil, err
}
return m.Diagram(r.GetString("diagram", ""))
}))
}
func diagramTool(name, desc string, rect bool) mcp.Tool {
opts := []mcp.ToolOption{
mcp.WithDescription(desc),
mcp.WithString("file", mcp.Required(), mcp.Description("path to the exported .xml model")),
mcp.WithString("output", mcp.Required(), mcp.Description("path to write the edited copy to (must differ from 'file')")),
mcp.WithString("diagram", mcp.Required(), mcp.Description("the diagram (id, GUID or path)")),
mcp.WithString("element", mcp.Required(), mcp.Description("the element")),
}
if rect {
opts = append(opts,
mcp.WithNumber("left", mcp.Required()),
mcp.WithNumber("top", mcp.Required()),
mcp.WithNumber("right", mcp.Required()),
mcp.WithNumber("bottom", mcp.Required()),
)
}
return mcp.NewTool(name, opts...)
}
package mcpserver
import (
"github.com/InsonusK/mcp-server-sparx-ea/internal/service/sparx"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
// registerElementTools adds the element tools: read one element, and
// create / rename / re-note / move / delete.
func registerElementTools(s *server.MCPServer, h sparxTools) {
s.AddTool(mcp.NewTool("ea_element",
mcp.WithDescription("One element by id, GUID or slash path: its ArchiMate type, note and every relationship."),
fileArg(), refArg("the element (id, GUID or 'Model/Package/Element')"),
), h.read(func(m Model, r mcp.CallToolRequest) (any, error) { return m.Element(r.GetString("ref", "")) }))
s.AddTool(mcp.NewTool("ea_create_element",
mcp.WithDescription("Add an ArchiMate element (e.g. 'ArchiMate.Goal') to a package."),
fileArg(), outputArg(),
mcp.WithString("parent", mcp.Required(), mcp.Description("the package to add it to (id, GUID or path)")),
mcp.WithString("type", mcp.Required(), mcp.Description("ArchiMate element type, e.g. 'ArchiMate.Requirement'")),
mcp.WithString("name", mcp.Required()),
mcp.WithString("note", mcp.Description("documentation")),
), h.write(func(m Model, r mcp.CallToolRequest) (any, error) {
return m.CreateElement(r.GetString("parent", ""), r.GetString("type", ""), r.GetString("name", ""), r.GetString("note", ""))
}))
s.AddTool(mcp.NewTool("ea_update_element",
mcp.WithDescription("Rename an element, change its note and/or move it to another package. Only the fields you pass are changed."),
fileArg(), outputArg(), refArg("the element"),
mcp.WithString("name", mcp.Description("new name")),
mcp.WithString("note", mcp.Description("new documentation")),
mcp.WithString("parent", mcp.Description("move it into this package")),
), h.write(func(m Model, r mcp.CallToolRequest) (any, error) {
ref := r.GetString("ref", "")
var info *sparx.ElementInfo
var err error
if v := r.GetString("name", ""); v != "" {
if info, err = m.RenameElement(ref, v); err != nil {
return nil, err
}
ref = info.Path
}
if _, ok := r.GetArguments()["note"]; ok {
if info, err = m.SetElementDocumentation(ref, r.GetString("note", "")); err != nil {
return nil, err
}
}
if v := r.GetString("parent", ""); v != "" {
if info, err = m.MoveElement(ref, v); err != nil {
return nil, err
}
}
if info == nil {
return m.Element(ref)
}
return info, nil
}))
s.AddTool(mcp.NewTool("ea_delete_element",
mcp.WithDescription("Remove an element and every relationship attached to it."),
fileArg(), outputArg(), refArg("the element"),
), h.write(func(m Model, r mcp.CallToolRequest) (any, error) {
return deleted(m.DeleteElement(r.GetString("ref", "")))
}))
}
package mcpserver
import (
"context"
"github.com/InsonusK/mcp-server-sparx-ea/internal/service/sparx"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
// registerModelTools adds the whole-model tools: the navigator tree, the type
// vocabulary, and the model-lifecycle tools (create from scratch, add / rename
// the root package).
func registerModelTools(s *server.MCPServer, h sparxTools) {
// ---------- read ----------
s.AddTool(mcp.NewTool("ea_model_tree",
mcp.WithDescription("The whole model as a tree of packages, diagrams and elements with ids — like the Sparx EA project browser."),
fileArg(),
), h.read(func(m Model, _ mcp.CallToolRequest) (any, error) { return m.Tree(), nil }))
s.AddTool(mcp.NewTool("ea_archimate_types",
mcp.WithDescription("The ArchiMate element and relationship type names this server accepts."),
), func(_ context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return jsonResult(map[string]any{
"elementTypes": sparx.ElementTypes(),
"relationshipTypes": sparx.RelationshipTypes(),
})
})
// ---------- lifecycle ----------
s.AddTool(mcp.NewTool("ea_new_model",
mcp.WithDescription("Build a model from scratch (not a copy of an export): one ArchiMate-ready root package named 'root', saved to 'output' for import into EA."),
mcp.WithString("root", mcp.Required(), mcp.Description("the name of the single EA root package")),
mcp.WithString("output", mcp.Required(), mcp.Description("path to write the new model to; import it into EA")),
), h.create(func(m Model, _ mcp.CallToolRequest) (any, error) { return m.Tree(), nil }))
s.AddTool(mcp.NewTool("ea_create_root_package",
mcp.WithDescription("Add a new top-level package alongside the model root."),
fileArg(), outputArg(),
mcp.WithString("name", mcp.Required()),
), h.write(func(m Model, r mcp.CallToolRequest) (any, error) {
return m.CreateRootPackage(r.GetString("name", ""))
}))
s.AddTool(mcp.NewTool("ea_set_root_name",
mcp.WithDescription("Rename the single EA root package. With fresh_identity it also regenerates every GUID, so the saved copy imports into EA as an independent package that can sit next to the original."),
fileArg(), outputArg(),
mcp.WithString("name", mcp.Required(), mcp.Description("the new root package name")),
mcp.WithBoolean("fresh_identity", mcp.Description("also regenerate every GUID in the model")),
), h.write(func(m Model, r mcp.CallToolRequest) (any, error) {
name, err := m.SetRootName(r.GetString("name", ""), r.GetBool("fresh_identity", false))
if err != nil {
return nil, err
}
return map[string]any{"rootName": name}, nil
}))
}
package mcpserver
import (
"github.com/InsonusK/mcp-server-sparx-ea/internal/service/sparx"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
// registerPackageTools adds the package tools: read one package, and
// create / rename / move / deep-copy / delete.
func registerPackageTools(s *server.MCPServer, h sparxTools) {
s.AddTool(mcp.NewTool("ea_package",
mcp.WithDescription("One package by id, GUID or slash path: its parent and immediate children."),
fileArg(), refArg("the package"),
), h.read(func(m Model, r mcp.CallToolRequest) (any, error) { return m.Package(r.GetString("ref", "")) }))
s.AddTool(mcp.NewTool("ea_create_package",
mcp.WithDescription("Add a package inside another package."),
fileArg(), outputArg(),
mcp.WithString("parent", mcp.Required()),
mcp.WithString("name", mcp.Required()),
), h.write(func(m Model, r mcp.CallToolRequest) (any, error) {
return m.CreatePackage(r.GetString("parent", ""), r.GetString("name", ""))
}))
s.AddTool(mcp.NewTool("ea_update_package",
mcp.WithDescription("Rename a package and/or move it to another parent."),
fileArg(), outputArg(), refArg("the package"),
mcp.WithString("name", mcp.Description("new name")),
mcp.WithString("parent", mcp.Description("move it into this package")),
), h.write(func(m Model, r mcp.CallToolRequest) (any, error) {
ref := r.GetString("ref", "")
var info *sparx.PackageInfo
var err error
if v := r.GetString("name", ""); v != "" {
if info, err = m.RenamePackage(ref, v); err != nil {
return nil, err
}
ref = info.Path
}
if v := r.GetString("parent", ""); v != "" {
if info, err = m.MovePackage(ref, v); err != nil {
return nil, err
}
}
if info == nil {
return m.Package(ref)
}
return info, nil
}))
s.AddTool(mcp.NewTool("ea_copy_package",
mcp.WithDescription("Deep-copy a package (with a fresh identity) into another package."),
fileArg(), outputArg(), refArg("the package to copy"),
mcp.WithString("dest", mcp.Required(), mcp.Description("the package to copy it into")),
), h.write(func(m Model, r mcp.CallToolRequest) (any, error) {
return m.CopyPackage(r.GetString("ref", ""), r.GetString("dest", ""))
}))
s.AddTool(mcp.NewTool("ea_delete_package",
mcp.WithDescription("Remove a package. Without cascade it refuses a non-empty package."),
fileArg(), outputArg(), refArg("the package"),
mcp.WithBoolean("cascade", mcp.Description("also delete every sub-package, element and diagram inside it")),
), h.write(func(m Model, r mcp.CallToolRequest) (any, error) {
n, err := m.DeletePackage(r.GetString("ref", ""), r.GetBool("cascade", false))
if err != nil {
return nil, err
}
return map[string]any{"removed": n}, nil
}))
}
package mcpserver
import (
"errors"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
// registerRelationshipTools adds the relationship tools: create one (with
// ArchiMate validation) and delete by id or by endpoints.
func registerRelationshipTools(s *server.MCPServer, h sparxTools) {
s.AddTool(mcp.NewTool("ea_create_relationship",
mcp.WithDescription("Add an ArchiMate relationship between two elements. Fails if ArchiMate does not permit it or an identical one already exists."),
fileArg(), outputArg(),
mcp.WithString("source", mcp.Required(), mcp.Description("source element (id, GUID or path)")),
mcp.WithString("target", mcp.Required(), mcp.Description("target element")),
mcp.WithString("type", mcp.Required(), mcp.Description("ArchiMate relationship type, e.g. 'ArchiMate.Realization'")),
mcp.WithString("name", mcp.Description("connector name")),
mcp.WithString("note", mcp.Description("documentation")),
), h.write(func(m Model, r mcp.CallToolRequest) (any, error) {
return m.CreateRelationship(r.GetString("source", ""), r.GetString("target", ""),
r.GetString("type", ""), r.GetString("name", ""), r.GetString("note", ""))
}))
s.AddTool(mcp.NewTool("ea_delete_relationship",
mcp.WithDescription("Remove a relationship by id, or every relationship between two elements."),
fileArg(), outputArg(),
mcp.WithString("id", mcp.Description("the relationship id or GUID")),
mcp.WithString("source", mcp.Description("with 'target': delete every relationship from source to target")),
mcp.WithString("target", mcp.Description("with 'source'")),
), h.write(func(m Model, r mcp.CallToolRequest) (any, error) {
if id := r.GetString("id", ""); id != "" {
return deleted(m.DeleteRelationship(id))
}
src, tgt := r.GetString("source", ""), r.GetString("target", "")
if src == "" || tgt == "" {
return nil, errors.New("pass either 'id' or both 'source' and 'target'")
}
n, err := m.DeleteRelationshipsBetween(src, tgt)
if err != nil {
return nil, err
}
return map[string]any{"deleted": n}, nil
}))
}
package sparx
import (
"sort"
"strings"
)
// The service speaks ArchiMate: an element has one Type ("ArchiMate.Goal"), not
// a (uml:Class, stereotype) pair. This file is the ArchiMate 3.2 vocabulary,
// the conversion to/from EA's representation, and the relationship rules used to
// validate a mutation before it is written.
type elementTypeName = string
// archimateElements is the full ArchiMate 3.2 element vocabulary — the hard-coded
// whitelist: the service refuses to create anything outside this set.
var archimateElements = toSet(
// Motivation
"Stakeholder", "Driver", "Assessment", "Goal", "Outcome",
"Principle", "Requirement", "Constraint", "Meaning", "Value",
// Strategy
"Resource", "Capability", "CourseOfAction", "ValueStream",
// Business
"BusinessActor", "BusinessRole", "BusinessCollaboration", "BusinessInterface",
"BusinessProcess", "BusinessFunction", "BusinessInteraction", "BusinessEvent",
"BusinessService", "BusinessObject", "Contract", "Representation", "Product",
// Application
"ApplicationComponent", "ApplicationCollaboration", "ApplicationInterface",
"ApplicationFunction", "ApplicationInteraction", "ApplicationProcess",
"ApplicationEvent", "ApplicationService", "DataObject",
// Technology
"Node", "Device", "SystemSoftware", "TechnologyCollaboration",
"TechnologyInterface", "Path", "CommunicationNetwork", "TechnologyFunction",
"TechnologyProcess", "TechnologyInteraction", "TechnologyEvent",
"TechnologyService", "Artifact",
// Physical
"Equipment", "Facility", "DistributionNetwork", "Material",
// Implementation & Migration
"WorkPackage", "Deliverable", "ImplementationEvent", "Plateau", "Gap",
// Other
"Location", "Grouping",
)
// archimateRelationships is the full ArchiMate 3.2 relationship vocabulary.
var archimateRelationships = toSet(
"Composition", "Aggregation", "Assignment", "Realization", "Serving",
"Access", "Influence", "Triggering", "Flow", "Specialization", "Association",
)
// behaviorTypes is the ArchiMate behaviour vocabulary — the elements EA exports
// as uml:Activity rather than uml:Class (events included).
var behaviorTypes = toSet(
"BusinessProcess", "BusinessFunction", "BusinessInteraction", "BusinessEvent", "BusinessService",
"ApplicationFunction", "ApplicationInteraction", "ApplicationProcess", "ApplicationEvent", "ApplicationService",
"TechnologyFunction", "TechnologyProcess", "TechnologyInteraction", "TechnologyEvent", "TechnologyService",
"ImplementationEvent", "ValueStream",
)
// interfaceTypes are the ArchiMate elements EA exports as uml:Interface rather
// than uml:Class: the exposed-behaviour "interface" element of each active
// layer. Confirmed against a real EA export (tmp/examples/sandbox.xml) — EA
// only recognises the ArchiMate_*Interface stereotype on a uml:Interface base
// (base_Interface); applied to a uml:Class it renders as an anonymous class.
var interfaceTypes = toSet("ApplicationInterface", "BusinessInterface", "TechnologyInterface")
// componentTypes are the ArchiMate elements EA exports as uml:Component rather
// than uml:Class.
var componentTypes = toSet("ApplicationComponent")
// ---------- EA representation ----------
// eaRelation is how EA serialises an ArchiMate relationship in an XMI export.
type eaRelation struct {
EAType string // <properties ea_type="…">
ModelRepr string // "association" | "controlflow" | "dependency" | "generalization"
Direction string // <properties direction="…">
verified bool // confirmed against a real EA export?
}
// relEA maps an ArchiMate relationship type to its EA serialisation. The
// verified entries come from real EA "Export Package to XMI" files
// (example/TestProject*-Model.xml); the rest follow EA's ArchiMate3 MDG
// conventions and are confirmed on the first import round-trip.
var relEA = map[elementTypeName]eaRelation{
"Association": {EAType: "Association", ModelRepr: "association", Direction: "Unspecified", verified: true},
"Composition": {EAType: "Association", ModelRepr: "association", Direction: "Unspecified", verified: true},
"Aggregation": {EAType: "Association", ModelRepr: "association", Direction: "Unspecified", verified: true},
"Assignment": {EAType: "Association", ModelRepr: "association", Direction: "Unspecified", verified: false},
"Influence": {EAType: "ControlFlow", ModelRepr: "controlflow", Direction: "Source -> Destination", verified: true},
"Triggering": {EAType: "ControlFlow", ModelRepr: "controlflow", Direction: "Source -> Destination", verified: false},
"Flow": {EAType: "ControlFlow", ModelRepr: "controlflow", Direction: "Source -> Destination", verified: false},
"Realization": {EAType: "Dependency", ModelRepr: "dependency", Direction: "Source -> Destination", verified: true},
"Serving": {EAType: "Dependency", ModelRepr: "dependency", Direction: "Source -> Destination", verified: false},
"Access": {EAType: "Dependency", ModelRepr: "dependency", Direction: "Source -> Destination", verified: false},
"Specialization": {EAType: "Generalization", ModelRepr: "generalization", Direction: "", verified: true},
}
// EARelationship returns EA's serialisation of a bare ArchiMate relationship
// name ("Realization"): the EA connector type, the model representation and the
// direction. Exported for tooling that writes connectors directly via the eaxmi
// codec (see tools/relexamples).
func EARelationship(relBare string) (eaType, modelRepr, direction string, ok bool) {
e, ok := relEA[relBare]
return e.EAType, e.ModelRepr, e.Direction, ok
}
// EAElementForType returns EA's (uml type, stereotype) pair for a bare ArchiMate
// element type ("Goal"). Exported for tooling (see tools/relexamples).
func EAElementForType(typeBare string) (umlType, stereotype string) {
e := eaForElement(typeBare)
return e.UMLType, e.Stereotype
}
// eaElement is how EA serialises an ArchiMate element.
type eaElement struct {
UMLType string // <packagedElement xmi:type="…">
Stereotype string // "ArchiMate_Goal"
}
// eaForElement returns EA's (uml type, stereotype) for an ArchiMate type. Most
// ArchiMate elements are uml:Class; behaviour elements are uml:Activity, the
// three ArchiMate "interface" elements are uml:Interface, and
// ApplicationComponent is uml:Component.
func eaForElement(t elementTypeName) eaElement {
umlType := "uml:Class"
switch {
case behaviorTypes[t]:
umlType = "uml:Activity"
case interfaceTypes[t]:
umlType = "uml:Interface"
case componentTypes[t]:
umlType = "uml:Component"
}
return eaElement{UMLType: umlType, Stereotype: "ArchiMate_" + t}
}
// ---------- name <-> EA stereotype ----------
func archimateTypeFromStereotype(stereotype string) (name string, ok bool) {
const p = "ArchiMate_"
if !strings.HasPrefix(stereotype, p) {
return stereotype, false
}
return stereotype[len(p):], true
}
func qualify(name string) string { return "ArchiMate." + name }
func unqualify(qualified string) (string, bool) {
const p = "ArchiMate."
if !strings.HasPrefix(qualified, p) {
return qualified, false
}
return qualified[len(p):], true
}
// IsKnownElementType reports whether qualified ("ArchiMate.Goal") is in the
// hard-coded ArchiMate element vocabulary.
func IsKnownElementType(qualified string) bool {
name, ok := unqualify(qualified)
return ok && archimateElements[name]
}
// IsKnownRelationshipType reports whether qualified ("ArchiMate.Realization") is
// in the hard-coded ArchiMate relationship vocabulary.
func IsKnownRelationshipType(qualified string) bool {
name, ok := unqualify(qualified)
return ok && archimateRelationships[name]
}
// RelationshipAllowed reports whether ea_create_relationship would accept an
// ArchiMate relationship of the qualified type relType ("ArchiMate.Realization")
// from sourceType to targetType — i.e. the verdict is not Deny. Any unknown name
// yields false. See RelationshipVerdict for the three-way answer.
func RelationshipAllowed(relType, sourceType, targetType string) bool {
return RelationshipVerdictQualified(relType, sourceType, targetType) != VerdictDeny
}
// ElementTypes returns the qualified names of every ArchiMate element type the
// service accepts ("ArchiMate.Goal", …), sorted.
func ElementTypes() []string { return qualifiedSorted(archimateElements) }
// RelationshipTypes returns the qualified names of every ArchiMate relationship
// type the service accepts ("ArchiMate.Realization", …), sorted.
func RelationshipTypes() []string { return qualifiedSorted(archimateRelationships) }
func qualifiedSorted(set map[string]bool) []string {
out := make([]string, 0, len(set))
for name := range set {
out = append(out, qualify(name))
}
sort.Strings(out)
return out
}
func toSet(vs ...string) map[string]bool {
m := make(map[string]bool, len(vs))
for _, v := range vs {
m[v] = true
}
return m
}
package sparx
import (
"fmt"
"sort"
"strings"
"github.com/InsonusK/mcp-server-sparx-ea/client/eaxmi"
)
// Diagrams: read contents and layout (method 3), create a diagram (method 6),
// and place / move / remove an element on a diagram (method 6).
// archimateDiagramLayers is the set of ArchiMate viewpoints CreateDiagram
// accepts as its layer argument. Each maps to an EA ArchiMate3 MDG diagram
// profile ("Motivation" -> "ArchiMate3::Motivation"), which selects the toolbox
// EA shows when the diagram is opened. The empty layer is also allowed — a
// plain logical diagram, on which ArchiMate elements still render with their
// stereotyped shapes.
var archimateDiagramLayers = map[string]bool{
"Motivation": true,
"Strategy": true,
"Business": true,
"Application": true,
"Technology": true,
"Physical": true,
"Implementation_Migration": true,
}
// DiagramLayers returns the accepted CreateDiagram layer names, sorted.
func DiagramLayers() []string {
out := make([]string, 0, len(archimateDiagramLayers))
for name := range archimateDiagramLayers {
out = append(out, name)
}
sort.Strings(out)
return out
}
// mdgForLayer validates a layer argument and returns the EA MDG diagram type to
// store. "" is valid and yields "" (a plain logical diagram).
func mdgForLayer(layer string) (string, error) {
layer = strings.TrimSpace(layer)
if layer == "" {
return "", nil
}
if !archimateDiagramLayers[layer] {
return "", fmt.Errorf("sparx: %q is not a known ArchiMate diagram layer; use one of %s (or omit it)",
layer, strings.Join(DiagramLayers(), ", "))
}
return "ArchiMate3::" + layer, nil
}
// Rect is an element's rectangle on a diagram (EA coordinates: origin top-left,
// y downward).
type Rect struct {
Left, Top, Right, Bottom int
}
// DiagramInfo lists what is placed on a diagram and where.
type DiagramInfo struct {
ID string `json:"id"`
GUID string `json:"guid"`
Name string `json:"name"`
Path string `json:"path"`
DiagramType string `json:"diagramType"`
Objects []PlacedElement `json:"objects"`
Links []PlacedLink `json:"links"`
}
// PlacedElement is an element shown on a diagram, with its rectangle.
type PlacedElement struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Seq int `json:"seq"`
Left int `json:"left"`
Top int `json:"top"`
Right int `json:"right"`
Bottom int `json:"bottom"`
}
// PlacedLink is a connector shown on a diagram (EA auto-routes it).
type PlacedLink struct {
ID string `json:"id"`
Type string `json:"type"`
Name string `json:"name,omitempty"`
Verdict string `json:"verdict,omitempty"` // "warn" | "deny" per the ArchiMate rules
Warning string `json:"warning,omitempty"`
}
// Diagram resolves ref (an ID, a GUID, or a slash path) and returns its contents.
func (s *Service) Diagram(ref string) (*DiagramInfo, error) {
d, path := s.resolveDiagram(ref)
if d == nil {
return nil, fmt.Errorf("sparx: no diagram for %q", ref)
}
info := &DiagramInfo{
ID: d.XMIID, GUID: d.GUID, Name: d.Name, Path: path, DiagramType: d.Type,
Objects: []PlacedElement{}, Links: []PlacedLink{},
}
for _, o := range d.Objects {
pe := PlacedElement{
ID: o.SubjectID, Seq: o.Seq,
Left: o.Left, Top: o.Top, Right: o.Right, Bottom: o.Bottom,
}
if el, ok := s.doc.ElementByID(o.SubjectID); ok {
pe.Name = el.Name
pe.Type = elementType(el)
}
info.Objects = append(info.Objects, pe)
}
for _, l := range d.Links {
pl := PlacedLink{ID: l.ConnectorID}
for _, c := range s.doc.Connectors() {
if c.XMIID == l.ConnectorID {
pl.Type = relationType(c)
pl.Name = c.Name
v, rn, sn, tn := s.connectorVerdict(c)
annotateVerdict(&pl.Verdict, &pl.Warning, v, rn, sn, tn)
break
}
}
info.Links = append(info.Links, pl)
}
return info, nil
}
// CreateDiagram adds an empty diagram named name inside the package at
// parentRef. layer, when given, is an ArchiMate viewpoint (see DiagramLayers)
// that selects EA's toolbox for the diagram; omit it for a plain logical
// diagram. Populate the diagram with AddToDiagram.
func (s *Service) CreateDiagram(parentRef, name, layer string) (*DiagramInfo, error) {
name = strings.TrimSpace(name)
if name == "" {
return nil, fmt.Errorf("sparx: diagram name is required")
}
mdg, err := mdgForLayer(layer)
if err != nil {
return nil, err
}
parent := s.resolvePackage(parentRef)
if parent == nil {
return nil, fmt.Errorf("sparx: no package for %q", parentRef)
}
for _, g := range parent.Diagrams {
if g.Name == name {
return nil, fmt.Errorf("sparx: package %q already has a diagram named %q", parent.Name, name)
}
}
g, err := s.doc.AddDiagram(parent.XMIID, name, mdg)
if err != nil {
return nil, errWrap(err)
}
return s.Diagram(g.XMIID)
}
// AddToDiagram places an element on a diagram at the given rectangle.
func (s *Service) AddToDiagram(diagramRef, elementRef string, at Rect) error {
d, _ := s.resolveDiagram(diagramRef)
if d == nil {
return fmt.Errorf("sparx: no diagram for %q", diagramRef)
}
el, _ := s.resolveElement(elementRef)
if el == nil {
return fmt.Errorf("sparx: no element for %q", elementRef)
}
for _, o := range d.Objects {
if o.SubjectID == el.XMIID {
return fmt.Errorf("sparx: %s is already on diagram %s", el.Name, d.Name)
}
}
if !validRect(at) {
return fmt.Errorf("sparx: invalid rectangle %+v (need right>left, bottom>top)", at)
}
if err := s.doc.AddDiagramObject(d.XMIID, el.XMIID, at.Left, at.Top, at.Right, at.Bottom); err != nil {
return errWrap(err)
}
s.showRelatedConnectors(d, el.XMIID)
return nil
}
// showRelatedConnectors adds a diagram line for every connector between the
// just-placed element newID and an element already on the diagram, so dropping
// two connected elements on a diagram shows the relationship between them.
func (s *Service) showRelatedConnectors(d *eaxmi.Diagram, newID string) {
placed := map[string]bool{}
for _, o := range d.Objects {
placed[o.SubjectID] = true
}
for _, c := range s.doc.Connectors() {
var other string
switch newID {
case c.SourceID:
other = c.TargetID
case c.TargetID:
other = c.SourceID
default:
continue
}
if placed[other] {
_ = s.doc.AddDiagramLink(d.XMIID, c.XMIID)
}
}
}
// RemoveFromDiagram removes an element's placement from a diagram.
func (s *Service) RemoveFromDiagram(diagramRef, elementRef string) error {
d, _ := s.resolveDiagram(diagramRef)
if d == nil {
return fmt.Errorf("sparx: no diagram for %q", diagramRef)
}
el, _ := s.resolveElement(elementRef)
if el == nil {
return fmt.Errorf("sparx: no element for %q", elementRef)
}
if err := s.doc.RemoveDiagramObject(d.XMIID, el.XMIID); err != nil {
return errWrap(err)
}
// Drop any connector lines that can no longer be drawn (one end just left).
for _, c := range s.doc.Connectors() {
if c.SourceID == el.XMIID || c.TargetID == el.XMIID {
s.doc.RemoveDiagramLink(d.XMIID, c.XMIID)
}
}
return nil
}
// MoveOnDiagram changes an element's rectangle on a diagram (remove + re-add).
func (s *Service) MoveOnDiagram(diagramRef, elementRef string, at Rect) error {
if !validRect(at) {
return fmt.Errorf("sparx: invalid rectangle %+v", at)
}
if err := s.RemoveFromDiagram(diagramRef, elementRef); err != nil {
return err
}
return s.AddToDiagram(diagramRef, elementRef, at)
}
func validRect(r Rect) bool { return r.Right > r.Left && r.Bottom > r.Top }
package sparx
import (
"fmt"
"strings"
"github.com/InsonusK/mcp-server-sparx-ea/client/eaxmi"
)
// Elements: read (method 2) and the create / rename / re-note / move / delete
// mutations (method 4). Every mutation validates against the ArchiMate
// vocabulary before it touches the document.
// ElementInfo is the answer to "tell me about this element".
type ElementInfo struct {
ID string `json:"id"`
GUID string `json:"guid"`
Name string `json:"name"`
Type string `json:"type"` // "ArchiMate.Goal", or "unknown:<stereotype>"
Path string `json:"path"`
Documentation string `json:"documentation,omitempty"`
Relations []Relation `json:"relations"`
}
// Relation is one connector as seen from a particular element.
type Relation struct {
ID string `json:"id"`
Type string `json:"type"` // "ArchiMate.Realization", or "unknown:<stereotype>"
Name string `json:"name,omitempty"`
Direction string `json:"direction"` // "outgoing" | "incoming"
OtherName string `json:"otherName"`
OtherID string `json:"otherId"`
OtherType string `json:"otherType"`
// Verdict is "warn" or "deny" when the ArchiMate rules classify this
// (type, source, target) triple as discouraged or not permitted; empty for
// an allowed relationship or a non-ArchiMate connector. Warning is the
// human-readable reason (set alongside Verdict).
Verdict string `json:"verdict,omitempty"`
Warning string `json:"warning,omitempty"`
}
// Element resolves ref (an ID, a GUID, or a slash path) and returns its details.
func (s *Service) Element(ref string) (*ElementInfo, error) {
el, path := s.resolveElement(ref)
if el == nil {
return nil, fmt.Errorf("sparx: no element for %q", ref)
}
info := &ElementInfo{
ID: el.XMIID, GUID: el.GUID, Name: el.Name, Type: elementType(el),
Path: path, Documentation: el.Documentation,
Relations: []Relation{},
}
for _, c := range s.doc.Connectors() {
var dir, otherID string
switch el.XMIID {
case c.SourceID:
dir, otherID = "outgoing", c.TargetID
case c.TargetID:
dir, otherID = "incoming", c.SourceID
default:
continue
}
other, _ := s.doc.ElementByID(otherID)
rel := Relation{
ID: c.XMIID, Type: relationType(c), Name: c.Name, Direction: dir,
OtherID: otherID,
}
if other != nil {
rel.OtherName = other.Name
rel.OtherType = elementType(other)
}
v, rn, sn, tn := s.connectorVerdict(c)
annotateVerdict(&rel.Verdict, &rel.Warning, v, rn, sn, tn)
info.Relations = append(info.Relations, rel)
}
return info, nil
}
// connectorVerdict returns the ArchiMate rule verdict for a connector, and the
// bare (relation, source, target) names — ("", …) when it is not an ArchiMate
// relationship between two ArchiMate elements.
func (s *Service) connectorVerdict(c *eaxmi.Connector) (v Verdict, rel, src, tgt string) {
relBare, ok := archimateTypeFromStereotype(c.Stereotype)
if !ok || !archimateRelationships[relBare] {
return VerdictAllow, "", "", ""
}
srcEl, _ := s.doc.ElementByID(c.SourceID)
tgtEl, _ := s.doc.ElementByID(c.TargetID)
if srcEl == nil || tgtEl == nil {
return VerdictAllow, "", "", ""
}
srcBare, sok := archimateTypeFromStereotype(srcEl.Stereotype)
tgtBare, tok := archimateTypeFromStereotype(tgtEl.Stereotype)
if !sok || !tok {
return VerdictAllow, "", "", ""
}
return RelationshipVerdict(relBare, srcBare, tgtBare), relBare, srcBare, tgtBare
}
// annotateVerdict fills the verdict / warning fields of a read relationship or
// diagram link from connectorVerdict's result.
func annotateVerdict(verdict, warning *string, v Verdict, rel, src, tgt string) {
if rel == "" {
return
}
switch v {
case VerdictDeny:
*verdict = "deny"
*warning = fmt.Sprintf("%s from %s to %s is not permitted by the ArchiMate rules", rel, qualify(src), qualify(tgt))
case VerdictWarn:
*verdict = "warn"
*warning = fmt.Sprintf("%s from %s to %s is discouraged by the ArchiMate rules", rel, qualify(src), qualify(tgt))
}
}
// CreateElement adds an element of ArchiMate type archimateType (e.g.
// "ArchiMate.Goal") named name into the package at parentRef (an id or a path).
func (s *Service) CreateElement(parentRef, archimateType, name, documentation string) (*ElementInfo, error) {
name = strings.TrimSpace(name)
if name == "" {
return nil, fmt.Errorf("sparx: element name is required")
}
bare, ok := unqualify(archimateType)
if !ok || !archimateElements[bare] {
return nil, fmt.Errorf("sparx: %q is not a known ArchiMate element type", archimateType)
}
pkg := s.resolvePackage(parentRef)
if pkg == nil {
return nil, fmt.Errorf("sparx: no package for %q", parentRef)
}
if s.childElement(pkg, name) != nil {
return nil, fmt.Errorf("sparx: package %q already has an element named %q", pkg.Name, name)
}
ea := eaForElement(bare)
el, err := s.doc.AddElement(pkg.XMIID, eaxmi.ElementSpec{
Name: name, UMLType: ea.UMLType, Stereotype: ea.Stereotype,
Documentation: documentation,
})
if err != nil {
return nil, fmt.Errorf("sparx: %w", err)
}
return s.Element(el.XMIID)
}
// RenameElement changes an element's name.
func (s *Service) RenameElement(ref, newName string) (*ElementInfo, error) {
newName = strings.TrimSpace(newName)
if newName == "" {
return nil, fmt.Errorf("sparx: new name is required")
}
el, _ := s.resolveElement(ref)
if el == nil {
return nil, fmt.Errorf("sparx: no element for %q", ref)
}
if err := s.doc.SetElementName(el.XMIID, newName); err != nil {
return nil, fmt.Errorf("sparx: %w", err)
}
return s.Element(el.XMIID)
}
// SetElementDocumentation changes an element's note.
func (s *Service) SetElementDocumentation(ref, documentation string) (*ElementInfo, error) {
el, _ := s.resolveElement(ref)
if el == nil {
return nil, fmt.Errorf("sparx: no element for %q", ref)
}
if err := s.doc.SetElementDocumentation(el.XMIID, documentation); err != nil {
return nil, fmt.Errorf("sparx: %w", err)
}
return s.Element(el.XMIID)
}
// MoveElement re-parents an element into the package at newParentRef.
func (s *Service) MoveElement(ref, newParentRef string) (*ElementInfo, error) {
el, _ := s.resolveElement(ref)
if el == nil {
return nil, fmt.Errorf("sparx: no element for %q", ref)
}
pkg := s.resolvePackage(newParentRef)
if pkg == nil {
return nil, fmt.Errorf("sparx: no package for %q", newParentRef)
}
if el.Package != nil && el.Package.XMIID == pkg.XMIID {
return s.Element(el.XMIID)
}
if other := s.childElement(pkg, el.Name); other != nil {
return nil, fmt.Errorf("sparx: package %q already has an element named %q", pkg.Name, el.Name)
}
if err := s.doc.MoveElement(el.XMIID, pkg.XMIID); err != nil {
return nil, fmt.Errorf("sparx: %w", err)
}
return s.Element(el.XMIID)
}
// DeleteElement removes an element and every relationship attached to it.
func (s *Service) DeleteElement(ref string) error {
el, _ := s.resolveElement(ref)
if el == nil {
return fmt.Errorf("sparx: no element for %q", ref)
}
if err := s.doc.RemoveElement(el.XMIID); err != nil {
return fmt.Errorf("sparx: %w", err)
}
return nil
}
func (s *Service) childElement(p *eaxmi.Package, name string) *eaxmi.Element {
for _, e := range p.Elements {
if e.Name == name {
return e
}
}
return nil
}
package sparx
import (
"fmt"
"strings"
"github.com/InsonusK/mcp-server-sparx-ea/client/eaxmi"
)
// Packages: read a package's contents, and create / rename / move / delete a
// package. Packages are the model's containers, so they get their own method
// set even where the shape overlaps with elements.
// PackageInfo is the answer to "tell me about this package".
type PackageInfo struct {
ID string `json:"id"`
GUID string `json:"guid"`
Name string `json:"name"`
Path string `json:"path"`
Parent string `json:"parent,omitempty"` // path of the parent package ("" for a root package)
Packages []string `json:"packages"` // child package names
Elements []string `json:"elements"` // child element names
Diagrams []string `json:"diagrams"` // child diagram names
}
// Package resolves ref (an id, a GUID, or a slash path) and returns its contents.
func (s *Service) Package(ref string) (*PackageInfo, error) {
p := s.resolvePackage(ref)
if p == nil {
return nil, fmt.Errorf("sparx: no package for %q", ref)
}
info := &PackageInfo{
ID: p.XMIID, GUID: p.GUID, Name: p.Name, Path: s.doc.PathOfPackage(p),
Packages: []string{}, Elements: []string{}, Diagrams: []string{},
}
if p.Parent != nil && p.Parent != s.doc.Root {
info.Parent = s.doc.PathOfPackage(p.Parent)
}
for _, sub := range p.Packages {
info.Packages = append(info.Packages, sub.Name)
}
for _, e := range p.Elements {
info.Elements = append(info.Elements, e.Name)
}
for _, g := range p.Diagrams {
info.Diagrams = append(info.Diagrams, g.Name)
}
return info, nil
}
// CreatePackage adds a package named name inside the package at parentRef.
func (s *Service) CreatePackage(parentRef, name string) (*PackageInfo, error) {
name = strings.TrimSpace(name)
if name == "" {
return nil, fmt.Errorf("sparx: package name is required")
}
parent := s.resolvePackage(parentRef)
if parent == nil {
return nil, fmt.Errorf("sparx: no package for %q", parentRef)
}
if childPackage(parent, name) != nil {
return nil, fmt.Errorf("sparx: package %q already has a sub-package named %q", parent.Name, name)
}
p, err := s.doc.AddPackage(parent.XMIID, name)
if err != nil {
return nil, fmt.Errorf("sparx: %w", err)
}
return s.Package(p.XMIID)
}
// RenamePackage renames a package (by id or path). It keeps the package identity
// (use SetRootName to rename the EA root package with a fresh identity).
func (s *Service) RenamePackage(ref, newName string) (*PackageInfo, error) {
newName = strings.TrimSpace(newName)
if newName == "" {
return nil, fmt.Errorf("sparx: new name is required")
}
p := s.resolvePackage(ref)
if p == nil {
return nil, fmt.Errorf("sparx: no package for %q", ref)
}
if p.Parent != nil {
if other := childPackage(p.Parent, newName); other != nil && other != p {
return nil, fmt.Errorf("sparx: package %q already has a sub-package named %q", p.Parent.Name, newName)
}
}
if err := s.doc.SetPackageName(p.XMIID, newName); err != nil {
return nil, fmt.Errorf("sparx: %w", err)
}
return s.Package(p.XMIID)
}
// MovePackage re-parents a package into the package at newParentRef.
func (s *Service) MovePackage(ref, newParentRef string) (*PackageInfo, error) {
p := s.resolvePackage(ref)
if p == nil {
return nil, fmt.Errorf("sparx: no package for %q", ref)
}
parent := s.resolvePackage(newParentRef)
if parent == nil {
return nil, fmt.Errorf("sparx: no package for %q", newParentRef)
}
if p == parent {
return nil, fmt.Errorf("sparx: cannot move a package into itself")
}
for a := parent; a != nil; a = a.Parent {
if a == p {
return nil, fmt.Errorf("sparx: cannot move a package into its own descendant")
}
}
if p.Parent == parent {
return s.Package(p.XMIID)
}
if other := childPackage(parent, p.Name); other != nil {
return nil, fmt.Errorf("sparx: package %q already has a sub-package named %q", parent.Name, p.Name)
}
if err := s.doc.MovePackage(p.XMIID, parent.XMIID); err != nil {
return nil, fmt.Errorf("sparx: %w", err)
}
return s.Package(p.XMIID)
}
// CopyPackage deep-copies a package (with a fresh identity, so nothing collides)
// into the package at destParentRef — anywhere in the same model, including
// under a different root package. Returns the new package.
func (s *Service) CopyPackage(ref, destParentRef string) (*PackageInfo, error) {
src := s.resolvePackage(ref)
if src == nil {
return nil, fmt.Errorf("sparx: no package for %q", ref)
}
dest := s.resolvePackage(destParentRef)
if dest == nil {
return nil, fmt.Errorf("sparx: no package for %q", destParentRef)
}
for a := dest; a != nil; a = a.Parent {
if a == src {
return nil, fmt.Errorf("sparx: cannot copy a package into itself or its own descendant")
}
}
if other := childPackage(dest, src.Name); other != nil {
return nil, fmt.Errorf("sparx: package %q already has a sub-package named %q", dest.Name, src.Name)
}
np, err := s.doc.CopyPackage(s.doc, src.XMIID, dest.XMIID)
if err != nil {
return nil, errWrap(err)
}
return s.Package(np.XMIID)
}
// DeletePackage removes a package. With cascadeDelete=false it refuses a package
// that still contains sub-packages, elements or diagrams. With cascadeDelete=true
// it removes the whole subtree (and every relationship attached to a deleted
// element). It never deletes an EA root package. Returns the number of model
// objects removed (the package itself included).
func (s *Service) DeletePackage(ref string, cascadeDelete bool) (int, error) {
p := s.resolvePackage(ref)
if p == nil {
return 0, fmt.Errorf("sparx: no package for %q", ref)
}
if p.Parent == nil || p.Parent == s.doc.Root {
return 0, fmt.Errorf("sparx: %q is an EA root package; rename it instead of deleting", p.Name)
}
if !cascadeDelete && (len(p.Packages) > 0 || len(p.Elements) > 0 || len(p.Diagrams) > 0) {
return 0, fmt.Errorf("sparx: package %q is not empty; pass cascadeDelete to remove its contents", p.Name)
}
n, err := s.doc.RemovePackage(p.XMIID)
if err != nil {
return 0, fmt.Errorf("sparx: %w", err)
}
return n, nil
}
func childPackage(p *eaxmi.Package, name string) *eaxmi.Package {
for _, sub := range p.Packages {
if sub.Name == name {
return sub
}
}
return nil
}
package sparx
import (
"fmt"
"strings"
"github.com/InsonusK/mcp-server-sparx-ea/client/eaxmi"
)
// Relationships (method 5): create / delete, with ArchiMate validation. A
// relationship is refused if ArchiMate does not permit it between the two
// element types, or if one of the same (type, source, target) already exists.
// CreateRelationship adds a relationship of ArchiMate type archimateRelType
// (e.g. "ArchiMate.Serving") from sourceRef to targetRef. It fails if the
// relationship is not permitted between the two element types.
func (s *Service) CreateRelationship(sourceRef, targetRef, archimateRelType, name, documentation string) (*Relation, error) {
relBare, ok := unqualify(archimateRelType)
if !ok || !archimateRelationships[relBare] {
return nil, fmt.Errorf("sparx: %q is not a known ArchiMate relationship type", archimateRelType)
}
src, _ := s.resolveElement(sourceRef)
tgt, _ := s.resolveElement(targetRef)
if src == nil {
return nil, fmt.Errorf("sparx: no source element for %q", sourceRef)
}
if tgt == nil {
return nil, fmt.Errorf("sparx: no target element for %q", targetRef)
}
srcBare, sok := archimateTypeFromStereotype(src.Stereotype)
tgtBare, tok := archimateTypeFromStereotype(tgt.Stereotype)
if !sok || !tok {
return nil, fmt.Errorf("sparx: %s or %s is not an ArchiMate element; refusing to add a relationship", src.Name, tgt.Name)
}
verdict := RelationshipVerdict(relBare, srcBare, tgtBare)
if verdict == VerdictDeny {
return nil, fmt.Errorf("sparx: %s from %s (%s) to %s (%s) is not allowed by the ArchiMate relationship rules",
relBare, src.Name, qualify(srcBare), tgt.Name, qualify(tgtBare))
}
// (type, source, target) is unique: no duplicate relationship.
stereo := "ArchiMate_" + relBare
for _, c := range s.doc.Connectors() {
if c.SourceID == src.XMIID && c.TargetID == tgt.XMIID && c.Stereotype == stereo {
return nil, fmt.Errorf("sparx: a %s relationship from %s to %s already exists (%s)",
relBare, src.Name, tgt.Name, c.XMIID)
}
}
ea := relEA[relBare]
conn, err := s.doc.AddConnector(eaxmi.ConnectorSpec{
SourceID: src.XMIID, TargetID: tgt.XMIID, Name: strings.TrimSpace(name),
EAType: ea.EAType, ModelRepr: ea.ModelRepr,
Stereotype: stereo, Direction: ea.Direction,
Documentation: documentation,
})
if err != nil {
return nil, fmt.Errorf("sparx: %w", err)
}
rel := &Relation{
ID: conn.XMIID, Type: qualify(relBare), Name: conn.Name, Direction: "outgoing",
OtherID: tgt.XMIID, OtherName: tgt.Name, OtherType: qualify(tgtBare),
}
if verdict == VerdictWarn {
rel.Verdict = "warn"
rel.Warning = fmt.Sprintf("%s from %s to %s is discouraged by the ArchiMate rules — verify it against ArchiMate 3.2 / Sparx EA",
relBare, qualify(srcBare), qualify(tgtBare))
}
return rel, nil
}
// DeleteRelationshipsBetween removes every relationship whose source is
// sourceRef and target is targetRef. Returns how many were removed; it is an
// error if there were none.
func (s *Service) DeleteRelationshipsBetween(sourceRef, targetRef string) (int, error) {
src, _ := s.resolveElement(sourceRef)
tgt, _ := s.resolveElement(targetRef)
if src == nil {
return 0, fmt.Errorf("sparx: no source element for %q", sourceRef)
}
if tgt == nil {
return 0, fmt.Errorf("sparx: no target element for %q", targetRef)
}
var ids []string
for _, c := range s.doc.Connectors() {
if c.SourceID == src.XMIID && c.TargetID == tgt.XMIID {
ids = append(ids, c.XMIID)
}
}
if len(ids) == 0 {
return 0, fmt.Errorf("sparx: no relationship from %s to %s", src.Name, tgt.Name)
}
for _, id := range ids {
if err := s.doc.RemoveConnector(id); err != nil {
return 0, fmt.Errorf("sparx: %w", err)
}
}
return len(ids), nil
}
// DeleteRelationship removes a relationship by its id.
func (s *Service) DeleteRelationship(id string) error {
for _, c := range s.doc.Connectors() {
if c.XMIID == id || strings.EqualFold(c.GUID, id) {
if err := s.doc.RemoveConnector(c.XMIID); err != nil {
return fmt.Errorf("sparx: %w", err)
}
return nil
}
}
return fmt.Errorf("sparx: no relationship %q", id)
}
package sparx
import (
_ "embed"
"fmt"
"strings"
)
// The ArchiMate relationship rules. archimate_relationships.csv holds one row
// per (source, target, relation) — every element type × every element type ×
// every relationship type — with a status of deny / warn / allow. It is
// generated once by tools/reltable -seed and then hand-maintained as Sparx EA
// behaviour is confirmed.
//
// deny → ea_create_relationship refuses the relationship
// warn → it is created, but the result carries a warning; a model that already
// contains such a relationship is flagged when read
// allow → created silently
//
// A (source, target, relation) triple missing from the file is treated as deny.
//go:embed archimate_relationships.csv
var relationshipRulesCSV string
// Verdict is how the rules classify one (relation, source, target) triple.
type Verdict int
const (
VerdictDeny Verdict = iota
VerdictWarn
VerdictAllow
)
func (v Verdict) String() string {
switch v {
case VerdictAllow:
return "allow"
case VerdictWarn:
return "warn"
default:
return "deny"
}
}
var relationshipRules = mustParseRelationshipRules(relationshipRulesCSV)
func relRuleKey(rel, src, tgt string) string { return rel + "\x00" + src + "\x00" + tgt }
func mustParseRelationshipRules(s string) map[string]Verdict {
out := map[string]Verdict{}
for i, line := range strings.Split(s, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, "source,") {
continue
}
f := strings.Split(line, ",")
if len(f) != 4 {
panic(fmt.Sprintf("archimate_relationships.csv:%d: want 4 fields, got %d (%q)", i+1, len(f), line))
}
src, tgt, rel, status := f[0], f[1], f[2], f[3]
var v Verdict
//# ArchiMate relationship rules — status is deny | warn | allow.
//# Seeded by tools/reltable; edit directly as Sparx EA behaviour is confirmed.
switch status {
case "allow":
// # allow = created silently
v = VerdictAllow
case "warn":
//# warn = created, but the tool returns a warning; flagged when a model is read
v = VerdictWarn
case "deny":
//# deny = ea_create_relationship refuses it
v = VerdictDeny
default:
panic(fmt.Sprintf("archimate_relationships.csv:%d: unknown status %q", i+1, status))
}
out[relRuleKey(rel, src, tgt)] = v
}
return out
}
// RelationshipVerdict classifies an ArchiMate relationship between two element
// types. All names are bare ("Realization", "ApplicationComponent",
// "ApplicationService"). An unlisted triple is VerdictDeny.
func RelationshipVerdict(rel, source, target string) Verdict {
if v, ok := relationshipRules[relRuleKey(rel, source, target)]; ok {
return v
}
return VerdictDeny
}
// RelationshipVerdictQualified is RelationshipVerdict for qualified names
// ("ArchiMate.Realization"). An unknown name yields VerdictDeny.
func RelationshipVerdictQualified(relType, sourceType, targetType string) Verdict {
rel, okR := unqualify(relType)
src, okS := unqualify(sourceType)
tgt, okT := unqualify(targetType)
if !okR || !okS || !okT {
return VerdictDeny
}
return RelationshipVerdict(rel, src, tgt)
}
// RelationshipVerdictName is RelationshipVerdictQualified as a string
// ("allow" / "warn" / "deny"). Exported for tooling and tests.
func RelationshipVerdictName(relType, sourceType, targetType string) string {
return RelationshipVerdictQualified(relType, sourceType, targetType).String()
}
package sparx
import (
"fmt"
"github.com/InsonusK/mcp-server-sparx-ea/client/eaxmi"
)
// ReportRootName is the single root package of an assembled report.
const ReportRootName = "Sparx Service Test Report"
// AssembleReport combines several XMI files into one importable file, built from
// scratch so it carries none of the sources' model-root flags:
//
// 1. start an empty model whose one root package is ReportRootName
// 2. for each source, deep-copy its root package (with all its sub-packages) in
// as a child of the report root, regenerating every id the subtree owns so
// nothing collides and cross-references inside the source stay intact
// (eaxmi.CopyPackage — it also strips the copied package's model-root flags)
//
// EA's "Import Package from XMI" processes a single root, so the report has
// exactly one. If it turns out broken, the individual sources say which one.
func AssembleReport(outPath string, sourcePaths []string) error {
if len(sourcePaths) == 0 {
return fmt.Errorf("sparx: no sources for the report")
}
base, err := eaxmi.NewModel(ReportRootName)
if err != nil {
return fmt.Errorf("sparx: report shell: %w", err)
}
rootID := base.Root.Packages[0].XMIID
// carry the ArchiMate profile definitions so EA recognises the stereotypes
if first, err := eaxmi.Open(sourcePaths[0]); err == nil {
_ = base.CopyProfileDefinitions(first)
}
var failed []string
for _, p := range sourcePaths {
src, err := eaxmi.Open(p)
if err != nil {
failed = append(failed, fmt.Sprintf("%s: %v", p, err))
continue
}
if len(src.Root.Packages) == 0 {
failed = append(failed, p+": no root package")
continue
}
if _, err := base.CopyPackage(src, src.Root.Packages[0].XMIID, rootID); err != nil {
failed = append(failed, fmt.Sprintf("%s: %v", p, err))
}
}
if err := base.WriteFile(outPath); err != nil {
return errWrap(err)
}
if len(failed) > 0 {
return fmt.Errorf("sparx: report written, but %d part(s) failed: %v", len(failed), failed)
}
return nil
}
package sparx
import "github.com/InsonusK/mcp-server-sparx-ea/client/eaxmi"
// Thin wrappers over eaxmi navigation (client/eaxmi/navigate.go). A ref is an
// xmi:id, a braced GUID, or a slash path from an EA root package.
func looksLikeID(ref string) bool { return eaxmi.IsRefID(ref) }
func splitPath(ref string) []string { return eaxmi.SplitPath(ref) }
func (s *Service) resolveElement(ref string) (*eaxmi.Element, string) {
e := s.doc.ResolveElement(ref)
if e == nil {
return nil, ""
}
return e, s.doc.PathOfElement(e)
}
func (s *Service) resolveDiagram(ref string) (*eaxmi.Diagram, string) {
g := s.doc.ResolveDiagram(ref)
if g == nil {
return nil, ""
}
return g, s.doc.PathOfDiagram(g)
}
func (s *Service) resolvePackage(ref string) *eaxmi.Package {
return s.doc.ResolvePackage(ref)
}
func (s *Service) allPackages() []*eaxmi.Package { return s.doc.AllPackages() }
package sparx
import (
"fmt"
"strings"
"github.com/InsonusK/mcp-server-sparx-ea/client/eaxmi"
)
// The EA root package (the XMI export's top node). RootNodeNameChange: renaming
// it — optionally with a fresh identity — lets many working copies import into
// one Sparx EA project side by side.
// NewModel starts an empty model from scratch (not a copy of a fixture): one
// root package named rootName, ready for CreatePackage / CreateElement. Save
// writes it as a normal working copy.
func NewModel(rootName string) (*Service, error) {
doc, err := eaxmi.NewModel(rootName)
if err != nil {
return nil, errWrap(err)
}
return &Service{doc: doc}, nil
}
// RootPackages returns the names of the EA root packages in this model (usually
// one).
func (s *Service) RootPackages() []string { return s.doc.RootPackages() }
// CreateRootPackage adds a new top-level package alongside the model root.
func (s *Service) CreateRootPackage(name string) (*PackageInfo, error) {
name = strings.TrimSpace(name)
if name == "" {
return nil, fmt.Errorf("sparx: package name is required")
}
p, err := s.doc.AddRootPackage(name)
if err != nil {
return nil, errWrap(err)
}
return s.Package(p.XMIID)
}
// SetRootName renames the single EA root package. With freshIdentity=true it
// also regenerates every GUID in the model, so a Saved copy imports into EA as
// a fully independent package that can sit next to the original (an XMI import
// matches by GUID). Returns the new root name.
func (s *Service) SetRootName(newName string, freshIdentity bool) (string, error) {
newName = strings.TrimSpace(newName)
if newName == "" {
return "", fmt.Errorf("sparx: root name is required")
}
if err := s.doc.RenameRoot(newName, freshIdentity); err != nil {
return "", fmt.Errorf("sparx: %w", err)
}
return newName, nil
}
package sparx
import "fmt"
// Save writes the edited model to path. It refuses to overwrite the file the
// service was opened from — a working copy is always a separate file the user
// imports back into EA.
func (s *Service) Save(path string) error {
if path == s.doc.Path {
return fmt.Errorf("sparx: refusing to overwrite the source file %q", path)
}
return errWrap(s.doc.WriteFile(path))
}
// Package sparx is the ArchiMate-facing service over an EA XMI file. It gives
// the MCP server simple, validated operations instead of raw SQL / raw XML:
// element types are ArchiMate types (the uml:Class + stereotype pair is hidden),
// and every mutation is validated before it touches the file.
//
// It reads (and, iteratively, writes) EA "Export Package to XMI" files via
// client/eaxmi.
//
// The API is split by model concept, one file each:
//
// tree.go the model navigator tree
// rootnode.go the EA root package (name / identity)
// package.go packages: read + create / rename / move / delete
// element.go elements: read + create / rename / re-note / move / delete
// relationship.go relationships: create / delete, with ArchiMate validation
// diagram.go diagrams: read + place / move / remove an element
// save.go writing the working copy back out
// resolve.go ref (id / GUID / path) -> model object
// archimate.go the ArchiMate 3.2 vocabulary and relationship rules
package sparx
import (
"fmt"
"strings"
"github.com/InsonusK/mcp-server-sparx-ea/client/eaxmi"
)
// Service is bound to one XMI file.
type Service struct {
doc *eaxmi.Document
}
// Open loads the XMI file at path.
func Open(path string) (*Service, error) {
doc, err := eaxmi.Open(path)
if err != nil {
return nil, err
}
return &Service{doc: doc}, nil
}
// ---------- shared helpers ----------
func elementType(e *eaxmi.Element) string {
name, ok := archimateTypeFromStereotype(e.Stereotype)
if !ok || !archimateElements[name] {
if e.Stereotype == "" {
return "unknown:" + strings.TrimPrefix(e.UMLType, "uml:")
}
return "unknown:" + e.Stereotype
}
return qualify(name)
}
func relationType(c *eaxmi.Connector) string {
name, ok := archimateTypeFromStereotype(c.Stereotype)
if !ok || !archimateRelationships[name] {
if c.Stereotype == "" {
return "unknown:" + c.EAType
}
return "unknown:" + c.Stereotype
}
return qualify(name)
}
func joinPath(parent, name string) string {
if parent == "" {
return name
}
return parent + "/" + name
}
func errWrap(err error) error {
if err == nil {
return nil
}
return fmt.Errorf("sparx: %w", err)
}
package sparx
import (
"fmt"
"github.com/InsonusK/mcp-server-sparx-ea/client/eaxmi"
)
// Method 1: the model navigator tree — packages, diagrams and elements with
// their EA ids, like the Sparx EA project browser.
// NodeKind is "package", "diagram" or "element".
type NodeKind string
const (
KindPackage NodeKind = "package"
KindDiagram NodeKind = "diagram"
KindElement NodeKind = "element"
)
// Node is one entry in the model navigator tree.
type Node struct {
Kind NodeKind `json:"kind"`
Name string `json:"name"`
ID string `json:"id"` // EA xmi:id (EAPK_/EAID_)
GUID string `json:"guid"` // {…}
Type string `json:"type,omitempty"` // ArchiMate type for elements, e.g. "ArchiMate.Goal"
Path string `json:"path"`
Children []*Node `json:"children,omitempty"`
// Notices, on the root node only, flags relationships in the model that the
// ArchiMate rules classify as deny / warn — a heads-up on an imported model.
Notices []string `json:"notices,omitempty"`
}
// Tree returns the whole model as a navigator tree, rooted at the EA root
// package (skipping the synthetic "EA_Model" wrapper).
func (s *Service) Tree() *Node {
root := &Node{Kind: KindPackage, Name: s.doc.Root.Name, Path: ""}
for _, p := range s.doc.Root.Packages {
root.Children = append(root.Children, s.packageNode(p, ""))
}
root.Notices = s.ruleNotices()
return root
}
// ruleNotices summarises every relationship in the model whose (type, source,
// target) the ArchiMate rules classify as deny or warn.
func (s *Service) ruleNotices() []string {
var deny, warn int
for _, c := range s.doc.Connectors() {
switch v, rn, _, _ := s.connectorVerdict(c); {
case rn == "":
continue
case v == VerdictDeny:
deny++
case v == VerdictWarn:
warn++
}
}
var out []string
if deny > 0 {
out = append(out, fmt.Sprintf("%d relationship(s) violate the ArchiMate rules (verdict deny) — read the elements to see which", deny))
}
if warn > 0 {
out = append(out, fmt.Sprintf("%d relationship(s) are discouraged by the ArchiMate rules (verdict warn)", warn))
}
return out
}
func (s *Service) packageNode(p *eaxmi.Package, parentPath string) *Node {
path := joinPath(parentPath, p.Name)
n := &Node{Kind: KindPackage, Name: p.Name, ID: p.XMIID, GUID: p.GUID, Path: path}
for _, sub := range p.Packages {
n.Children = append(n.Children, s.packageNode(sub, path))
}
for _, d := range p.Diagrams {
n.Children = append(n.Children, &Node{
Kind: KindDiagram, Name: d.Name, ID: d.XMIID, GUID: d.GUID,
Path: joinPath(path, d.Name),
})
}
for _, e := range p.Elements {
n.Children = append(n.Children, &Node{
Kind: KindElement, Name: e.Name, ID: e.XMIID, GUID: e.GUID,
Type: elementType(e), Path: joinPath(path, e.Name),
})
}
return n
}