A production-ready HTTP REST API server that runs inside Archi, exposing your ArchiMate models for automation, integration, and programmatic access.
- Features
- Installation
- Project Structure
- Usage
- CLI (archicli)
- MCP Server (archi-mcp)
- API Reference
- Configuration
- Security
- Examples
- Troubleshooting
- AI Agent Skills
- Development
- Documentation
- Contributing
- License
- 🖥️ CLI (archicli) - TypeScript command-line tool for scripted and agent-driven workflows
- 🧠 MCP Server (archi-mcp) - TypeScript Model Context Protocol server for AI agent integration
- 🔄 Model Automation - Create, query, and modify elements programmatically
- 🔌 External Integration - Connect with Python, Node.js, or any HTTP client
- 📊 View Generation - Dynamically create and layout ArchiMate views
- 🎯 API-First Design - RESTful endpoints with JSON responses
- ✅ Full Undo Support - All operations are fully undoable (Ctrl+Z)
- 🔒 Production Hardened - Rate limiting, validation, and timeout protection
- 🚀 Zero Dependencies - Pure JArchi implementation with GraalVM JS
- 🤖 AI Agent Skills - Built-in skills for Claude Code and GitHub Copilot following the Agent Skills standard
Clone this repository into your Archi scripts directory:
# Windows
git clone https://github.com/ThomasRohde/archi-server.git "%USERPROFILE%\Documents\Archi\scripts\archi-server"
# macOS/Linux
git clone https://github.com/ThomasRohde/archi-server.git ~/Documents/Archi/scripts/archi-serverOr download and extract the latest release to your Archi scripts folder.
archicli is a TypeScript CLI in the archicli/ directory that provides a structured interface to the API server — designed for scripted workflows, AI agents, and CI/CD pipelines.
cd archicli
npm install
npm run build
npm link # makes `archicli` available globallyarchicli health # verify server is running
archicli model query --show-relationships # inspect model + relationship sample
archicli model search --type application-component
archicli model search --type application-component --strict-types
archicli model search --name ".*Service.*" --no-relationships
archicli verify changes.json # validate a BOM file
archicli verify changes.json --semantic # semantic tempId checks
archicli batch apply changes.json # apply atomically with polling + validation
archicli batch apply changes.json --fast # fast mode: chunk-size 20
archicli batch apply changes.json --duplicate-strategy reuse --idempotency-key run-20260213
archicli view create "Application Overview" --viewpoint application_cooperation
archicli view delete id-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
archicli ops list # list recent operation IDsUse these commands when starting from an empty directory/model:
archicli init ./starter-bom
cd starter-bom
archicli doctor
archicli verify 01-elements.json --semantic
archicli batch apply 01-elements.json
archicli verify 02-view.json --semantic
archicli batch apply 02-view.json --layout
archicli view export --all --dir exportsChanges are described in JSON BOM files. The batch apply command handles validation, chunking (default chunk-size 8 for reliability), polling, connection cross-validation, and tempId→realId persistence automatically. Use --fast for larger chunk sizes when speed matters.
Validation is strict: unknown top-level and operation fields are rejected. For archicli verify auto-detection, BOM files should include version: "1.0" and either a changes array or an includes array.
Numeric CLI options are also strict: invalid integers/floats are rejected (no silent coercion).
Examples: --limit 1.5, --chunk-size -1, --margin abc.
Use archicli verify --semantic for tempId preflight checks, and add --resolve-names to mirror batch apply --resolve-names behavior against a running server.
--resolve-names is concept-name lookup only; it cannot reconstruct visual IDs (sourceVisualId, targetVisualId).
By default, verify --semantic and batch apply fail when declared idFiles are missing/malformed; use
--allow-incomplete-idfiles only when you intentionally want best-effort behavior.
Example:
{
"version": "1.0",
"description": "Create application layer",
"includes": ["parts/elements.json"],
"idFiles": ["previous.ids.json"],
"changes": [
{ "op": "createElement", "type": "application-component", "name": "My Server", "tempId": "my-server" },
{ "op": "setProperty", "id": "my-server", "key": "status", "value": "active" },
{ "op": "createRelationship", "type": "serving-relationship", "sourceId": "my-server", "targetId": "other-element" },
{ "op": "createView", "name": "Application Overview", "tempId": "app-view", "viewpoint": "application_cooperation" }
]
}After apply completes, changes.ids.json is written containing all tempId→realId mappings for use in subsequent BOM files.
You can choose a custom output path with --save-ids <path>, for example:
archicli batch apply changes.json --save-ids out/my-mappings.ids.jsonTo skip polling and ID tracking, use --no-poll (not recommended for most workflows).
For idempotent re-runs, prefer --idempotency-key with --duplicate-strategy reuse or --duplicate-strategy rename.
--skip-existing is still supported for compatibility, but deprecated.
| Concept | Description |
|---|---|
| tempId | Friendly name assigned at authoring time (e.g. "my-server"). Resolved to a real Archi ID at runtime. Later ops in the same batch can reference earlier tempIds. |
| Async mutations | /model/apply is async — archicli polls automatically (use --no-poll to skip). |
| Views vs elements | Elements exist in the model tree independently. Views are diagrams; use addToView + addConnectionToView to populate them. |
| Visual IDs | addToView returns a visualId (diagram object) distinct from the element conceptId. addConnectionToView needs visual IDs. |
| Nesting | For compound elements (parent containing children), use parentVisualId on addToView to nest children inside a parent visual, or nestInView to reparent after placement. |
archicli health Check server connectivity and model stats
archicli doctor Run preflight diagnostics (server/model/view readiness)
archicli init [dir] Bootstrap starter BOM templates in a target directory
archicli verify <file> Validate BOM JSON before sending
archicli model query Model overview: counts + sample elements (optional relationship sample)
archicli model apply <file> Submit a single apply payload (optionally poll)
archicli model search [options] Search by type, name, or property (--strict-types available)
archicli model element <id> Full detail for one element
archicli model save [--path <file>] Save the current model to disk
archicli model stats Get model statistics by type
archicli batch apply <file> Apply BOM in reliable chunks (default chunk-size 8, polls, validates connections)
archicli batch apply <file> --fast Apply BOM in fast mode (chunk-size 20, no validation)
archicli batch split <file> Split large BOM into linked chunk files (--chunk-size)
archicli view list List all views
archicli view get <id> View detail with visual object IDs
archicli view create <name> [options] Create view synchronously (invalid --viewpoint values are rejected)
archicli view export <id> Export view as PNG/JPEG (--file or --output-file)
archicli view layout <id> Auto-layout a view
archicli view delete <id> Delete a view
archicli ops list List recent async operations
archicli ops status <opId> --poll Poll async operation to completion
archicli folder list List model folders
archicli ids lookup <tempId> Resolve tempId values from .ids.json files
archicli completion <shell> Generate completion script (bash|zsh|fish|pwsh)
Use archicli view create --help for the full valid viewpoint list and examples.
# Bash
archicli completion bash --raw > ~/.local/share/bash-completion/completions/archicli
# Zsh
archicli completion zsh --raw > ~/.zfunc/_archicli
# Fish
archicli completion fish --raw > ~/.config/fish/completions/archicli.fish
# PowerShell
archicli completion pwsh --raw > archicli-completion.ps1Completion scripts include model search --type ArchiMate type value suggestions.
In --output json mode, command/usage errors (unknown command/flag, missing args, invalid global options) are emitted as JSON envelopes.
--output yaml is also supported. --quiet / -q prints data-only success payloads (no { success, data, metadata } envelope).
Representative --output json --quiet shapes:
archicli health->{ "status": "ok" }archicli batch apply <file>->{ "operationIds": ["op_..."] }archicli ops status <opId>->{ "operationId": "op_...", "status": "complete" }
archi-mcp is a TypeScript Model Context Protocol server in the archi-mcp/ directory. It uses the local openapi.yaml with @hey-api/openapi-ts generated client code and exposes the Archi API as MCP tools for AI agents — compatible with GitHub Copilot, Claude Desktop, Codex, and any MCP client.
cd archi-mcp
npm install
npm run build
npm install -g .This installs:
archi-mcp-serverarchi-mcp
GitHub Copilot (VS Code) — add to .vscode/mcp.json in your workspace:
{
"servers": {
"archi": {
"type": "stdio",
"command": "archi-mcp-server"
}
}
}Claude Desktop — add to claude_desktop_config.json:
{
"mcpServers": {
"archi": {
"command": "archi-mcp-server"
}
}
}Codex — add to ~/.codex/config.toml (Windows: C:\Users\<you>\.codex\config.toml):
[mcp_servers.archi]
command = "archi-mcp-server"Restart your client after configuration.
- Transport:
stdio(default). - Input validation: Zod schemas for all tool inputs.
- Tool annotations: Uses
readOnlyHint,destructiveHint,idempotentHint,openWorldHint. - Structured responses: Tools return both text content and structured content payloads.
- Response safety: Large responses are truncated with guidance to narrow filters.
- Error handling: Consistent API error envelopes with HTTP status/code context when available.
Read-only tools (17):
archi_get_health— server health, uptime, queue stats, model summaryarchi_get_test— verify UI thread handlerarchi_get_model_diagnostics— orphan/ghost object checksarchi_query_model— model summary with sampled elements and relationshipsarchi_plan_model_changes— dry-run plan preview without mutationsarchi_search_model— search by type, name pattern, or propertiesarchi_get_element— full element detail with relationships and viewsarchi_get_model_stats— type-level counts for elements, relationships, viewsarchi_get_relationships_between_elements— relationships within an element setarchi_list_folders— full model folder hierarchyarchi_get_operation_status— check async operation statusarchi_wait_for_operation— poll until complete/error/timeoutarchi_list_operations— list recent operations with optional status/cursor/summary filterarchi_list_views— filtered, sorted, paginated view listingarchi_get_view— full view detail with visual elements and connectionsarchi_get_view_summary— compact view summary for faster agent reasoningarchi_validate_view— connection integrity checks with violation details
Mutation/destructive tools (11):
archi_apply_model_changes— create/update/delete elements, relationships, views (auto-chunks >20 ops)archi_populate_view— add elements to a view with auto-connectarchi_save_model— persist model to diskarchi_run_script— execute JavaScript inside Archi (GraalVM)archi_create_view— create a new viewarchi_delete_view— delete a view by IDarchi_export_view— export view as PNG/JPEGarchi_duplicate_view— duplicate an existing viewarchi_set_view_router— set connection routing (bendpoint/manhattan)archi_layout_view— auto-layout with Dagre or Sugiyamaarchi_shutdown_server— graceful server shutdown
archi_server_defaults(archi://server/defaults) — runtime defaults (API base URL and timeout)archi_agent_quickstart(archi://agent/quickstart) — recommended read-first workflow and ID-handling tips
Reusable prompt templates for common ArchiMate modeling workflows. Prompts are guidance templates — model mutations still happen through explicit tool calls.
archi_assess_current_state— baseline health, structure, and diagnosticsarchi_general_archimate_modeling— general-purpose scoped modeling workflowarchi_design_capability_map— capability maps with strategy traceabilityarchi_model_business_application_alignment— business-to-application alignmentarchi_model_application_integration— application integration patternsarchi_map_technology_deployment— infrastructure and deployment mappingarchi_plan_gap_analysis_roadmap— baseline-target gap analysis with roadmaparchi_run_model_quality_audit— read-only quality auditarchi_curate_and_export_view— validate, layout, and export views
The server is organized as follows:
archi-server/
├── scripts/
│ ├── Model API Server.ajs # Main entry point
│ └── lib/
│ ├── core/ # Core infrastructure
│ │ ├── requireModel.js
│ │ ├── serverCore.js
│ │ ├── swtImports.js
│ │ └── undoableCommands.js
│ ├── server/ # Server modules
│ │ ├── apiEndpoints.js
│ │ ├── folderCache.js
│ │ ├── layoutDagreHeadless.js
│ │ ├── layoutSugiyamaHeadless.js
│ │ ├── loggingQueue.js
│ │ ├── modelSnapshot.js
│ │ ├── monitorUI.js
│ │ ├── operationQueue.js
│ │ ├── operationValidation.js
│ │ ├── serverConfig.js
│ │ └── endpoints/
│ │ ├── healthEndpoints.js
│ │ ├── modelEndpoints.js
│ │ ├── operationEndpoints.js
│ │ ├── scriptEndpoints.js
│ │ └── viewEndpoints.js
│ └── vendor/
│ └── dagre.min.js # Layout engine
├── archicli/ # TypeScript CLI (Node.js, npm install)
│ ├── src/
│ │ ├── cli.ts # Entry point
│ │ ├── index.ts # Program factory
│ │ ├── commands/ # health, verify, batch, model, view, ops
│ │ ├── schemas/ # BOM JSON schema + validator
│ │ └── utils/ # api, config, output, poll helpers
│ ├── package.json
│ └── tsconfig.json
├── archi-mcp/ # TypeScript MCP server (stdio)
│ ├── src/
│ │ ├── index.ts # MCP stdio bootstrap
│ │ ├── server.ts # MCP tool/resource/prompt registration
│ │ ├── archi-api.ts # API client wrapper
│ │ ├── config.ts # Environment config
│ │ ├── prompts.ts # 9 modeling prompt templates
│ │ └── client/ # Generated OpenAPI client
│ ├── package.json
│ └── README.md
├── openapi.yaml # API specification
└── README.md
-
Open Archi with an ArchiMate model
-
Open at least one view from your model (required for undo support)
-
Navigate to Scripts menu → Model API Server
-
A monitor dialog appears showing server status and real-time logs
-
The API is now available at
http://localhost:8765
Verify the server is running:
# Using the CLI (recommended for scripting and agents)
archicli health
archicli model query
archicli model search --type application-component
# Or using curl directly
curl http://localhost:8765/health
curl -X POST http://localhost:8765/model/query \
-H "Content-Type: application/json" \
-d '{}'
curl http://localhost:8765/viewsThe server exposes a comprehensive REST API:
GET /health- Server health and diagnosticsPOST /model/query- Query model elements/relationshipsPOST /model/apply- Modify model (create, update, delete)- Supports
idempotencyKey(caller-provided, 24h in-memory replay window) and request-levelduplicateStrategy(error|reuse|rename) - Supports upsert ops:
createOrGetElement,createOrGetRelationship(relationshiprenameis invalid)
- Supports
POST /model/search- Search by name, type, or properties (includeRelationshipssupported)
GET /views- List all viewsPOST /views- Create new viewGET /views/{id}- Get view details with all elementsDELETE /views/{id}- Delete viewPOST /views/{id}/layout- Apply layout (dagreorsugiyama)POST /views/{id}/export- Export as PNG/JPEG
POST /scripts/run- Execute custom JArchi code
GET /ops/status?opId=...- Check operation status (summaryOnly,cursor,pageSizesupported)GET /ops/list- List recent operations (status,cursor,summaryOnlysupported)POST /model/save- Save model to diskPOST /shutdown- Gracefully stop server
Operation status/list responses include additive metadata blocks: digest, timeline, tempIdMap, tempIdMappings, and retryHints (when available), plus paging fields hasMore and nextCursor.
Full API documentation available in openapi.yaml.
Customize server behavior by editing scripts/lib/server/serverConfig.js:
{
port: 8765, // Server port
host: "127.0.0.1", // Localhost only (security)
rateLimitRpm: 200, // Requests per minute per IP
maxBodySizeBytes: 1048576, // 1MB max request size
operationTimeoutMs: 60000, // 60s operation timeout
corsOrigins: ["http://localhost:3000"], // CORS allowlist
enableDetailedErrors: true // Include stack traces in errors
}✅ Localhost Only - Binds to 127.0.0.1 by default (not accessible from network)
🔒 Local Development - Designed for local automation and development workflows
Built-in Protection:
- Rate limiting (200 requests/minute)
- Request size limits (1MB maximum)
- Operation timeouts (60 seconds)
- Input validation and type checking
- CORS origin controls
For Production Use: Add authentication middleware or run behind a reverse proxy with auth.
Update element properties from external data sources:
await fetch('http://localhost:8765/model/apply', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
changes: [{
op: 'updateElement',
id: 'element-id',
properties: { 'Status': 'Active', 'Owner': 'IT Team' }
}]
})
});Create a new view with elements:
const response = await fetch('http://localhost:8765/views', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'Generated Infrastructure View',
type: 'archimate-diagram-model',
folderId: 'folder-id'
})
});Find elements by type and properties:
const response = await fetch('http://localhost:8765/model/search', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
type: 'capability',
properties: { 'Domain': 'Finance' }
})
});
const capabilities = await response.json();import requests
BASE_URL = "http://localhost:8765"
# Health check
health = requests.get(f"{BASE_URL}/health").json()
print(f"Server status: {health['status']}")
# Query all capabilities
response = requests.post(
f"{BASE_URL}/model/query",
json={"query": "elements", "type": "capability"}
)
capabilities = response.json()['result']
for cap in capabilities:
print(f"- {cap['name']} ({cap['id']})")const fetch = require('node-fetch');
const BASE_URL = 'http://localhost:8765';
async function queryModel() {
const response = await fetch(`${BASE_URL}/model/query`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query: 'elements',
type: 'application-component'
})
});
const data = await response.json();
console.log(`Found ${data.result.length} application components`);
return data.result;
}
queryModel();| Problem | Solution |
|---|---|
| "No model is open" | Open an ArchiMate model in Archi first |
| "No view is open" | Open at least one view (required for undo support) |
| "Port 8765 already in use" | Stop other server or change port in serverConfig.js |
| Script not in menu | Restart Archi or use Scripts → Refresh Scripts |
| Error Code | Cause | Solution |
|---|---|---|
| 429 | Rate limit exceeded | Add delays between requests (max 200/min) |
| 413 | Request too large | Split operation or increase maxBodySizeBytes |
| 504 | Operation timeout | Optimize query or increase operationTimeoutMs |
| 400 | Invalid input | Check request format against API specification |
Problem: "Cannot find lib/..." errors
Solution: Verify all files are in correct relative paths. The lib/ folder must be at scripts/lib/.
This project includes reusable agent skills following the Agent Skills open standard. Skills enable AI agents to perform complex modeling workflows, select correct ArchiMate element types, and apply established architecture patterns.
You can add skills to your AI agent environment using the Agent Skills registry:
# Install the ArchiMate modeling skill
npx skills add ThomasRohde/archi-server --skill archi-mcp-modelingOnce installed, skills are auto-discovered by both Claude Code and GitHub Copilot.
| Skill | Description |
|---|---|
| archi-mcp-modeling | Model and evolve ArchiMate architectures through the local Archi MCP server with semantically correct element and relationship choices |
| mcp-builder | Guide for creating high-quality MCP servers that enable LLMs to interact with external services |
Skills are located in .agents/skills/ and contain structured prompts, examples, and domain-specific guidance that help AI agents make correct modeling decisions.
- Server Core (
serverCore.js) - HTTP server and routing - Operation Queue (
operationQueue.js) - Thread-safe operation execution - Undo Support (
undoableCommands.js) - SWT command wrapping - Model Snapshot (
modelSnapshot.js) - Efficient model serialization - API Endpoints (
endpoints/*.js) - Modular endpoint handlers
See context/ folder for detailed technical documentation.
Contributions are welcome! Please see CONTRIBUTING.md for detailed guidelines.
Quick start:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- API Specification: openapi.yaml
- Changelog: CHANGELOG.md
- Contributing Guide: CONTRIBUTING.md
- Script Development Guide: context/Script Development Guide for Agents.md
- jArchi API Reference: context/jarchi-1.11-api-reference.md
- GraalJS Compatibility: context/graalJS-compatibility.md
- MCP Agent Experience Report: MCP.md
- Agent Skills Standard: agentskills.io
MIT License - See LICENSE for details.
- Issues: GitHub Issues
- Discussions: Archi Forum
- jArchi Plugin: Official Documentation
- Built for Archi - Open Source ArchiMate Modelling Tool
- Powered by jArchi scripting plugin
- Layout engines: Dagre and a built-in Sugiyama layered layouter
Made with ❤️ for the ArchiMate community