# ClaudeTools API — Tech Stack

## Purpose

ClaudeTools is an MSP work-tracking and internal tooling platform built by Arizona Computer Guru LLC. It provides a REST API for tracking clients, projects, work sessions, billable time, infrastructure inventory, and encrypted credentials — plus a real-time coordination subsystem that multiple Claude Code sessions use to avoid clobbering each other. The API is production-stable with 95+ endpoints and 38 database tables.

---

## Components

### API Server

- **Framework:** Python, FastAPI
- **ASGI server:** Uvicorn
- **ORM/query layer:** SQLAlchemy (models in `api/models/`), Pydantic schemas (in `api/schemas/`)
- **Host:** 172.16.3.30, port 8001 (production)
- **Deployment:** <!-- TODO: verify — systemd unit or direct process? auto-deploy via Gitea webhook is planned but not confirmed active -->
- **OpenAPI docs:** http://172.16.3.30:8001/api/docs (also `http://localhost:8000/api/docs` in dev)
- **Repo path:** `api/` directory in `azcomputerguru/claudetools` on Gitea (http://172.16.3.20:3000)

**Repo layout:**
```
api/
├── main.py          # Entry point
├── models/          # SQLAlchemy models (38 tables)
├── routers/         # Endpoint handlers (95+ endpoints across ~10 router files)
├── schemas/         # Pydantic request/response schemas
├── services/        # Business logic layer
├── middleware/      # Auth and error handling
└── utils/           # Crypto utilities (AES-256-GCM)
```

Key endpoint groups:
- `/api/machines`, `/api/clients`, `/api/projects`, `/api/sessions`, `/api/tags` — core entities
- `/api/work-items`, `/api/tasks`, `/api/billable-time` — MSP work tracking
- `/api/sites`, `/api/infrastructure`, `/api/services`, `/api/networks`, `/api/firewall-rules`, `/api/m365-tenants` — infrastructure inventory
- `/api/credentials`, `/api/credential-audit-logs`, `/api/security-incidents` — encrypted credential storage and audit
- `/api/auth/token` — JWT issuance
- `/api/coord/*` — coordination subsystem (no auth required; see below)

---

### Database

- **Engine:** MariaDB 10.6.22
- **Host:** 172.16.3.30:3306, database `claudetools`
- **Tables:** 38 (as of last audit)
- **Sensitive field encryption:** AES-256-GCM (Fernet) — applied at the service layer before write, decrypted on read. Credential passwords are the primary encrypted fields.
- **Audit logging:** All credential read/write operations logged to `credential_audit_logs` table automatically.
- **Migration approach:** Alembic. Migrations in `migrations/` directory. Commands: `alembic current`, `alembic upgrade head`.
- **Credentials:** Stored in SOPS vault at `projects/claudetools/database.sops.yaml`. Retrieve with:
  ```bash
  bash $CLAUDETOOLS_ROOT/.claude/scripts/vault.sh get-field projects/claudetools/database.sops.yaml credentials.password
  ```
  1Password fallback: `op read "op://Projects/ClaudeTools Database/password"`

---

### Authentication

- **Mechanism:** JWT tokens issued by `POST /api/auth/token` (email + password)
- **Password hashing:** Argon2
- **API key encryption:** AES-256-GCM (Fernet) applied to stored credential values
- **Coordination API:** No auth required — it is an internal-network-only subsystem

---

### Coordination Subsystem (`/api/coord`)

The coordination API is a first-class subsystem used by all Claude Code sessions (across machines and users) to prevent concurrent writes to the same resource. It requires no authentication and is intended for internal LAN use only.

Key endpoints:
- `GET /api/coord/status` — current component states for all projects
- `GET /api/coord/messages` — inter-session messages (filtered by `to_session`, `unread_only`)
- `PUT /api/coord/messages/<id>/read` — mark message read
- `POST /api/coord/locks` — claim a work lock on a resource (with TTL)
- `DELETE /api/coord/locks/<id>` — release a lock
- `PUT /api/coord/components/<project_key>/<component>` — update component state

Project keys: `gururmm`, `claudetools`, `dataforth-dos`, `clients/<name>`

Component states tracked per project:
- `gururmm`: `server`, `agents`, `dashboard`, `db_migrations` — states: `building`, `built`, `deploying`, `deployed`, `degraded`
- `claudetools`: `api`, `db_migrations`, `coord_api` — states: `deploying`, `deployed`, `degraded`

Softfail behavior: if the coord API is unreachable, sessions log failed calls to `.claude/coord-queue.jsonl` and drain on next `/sync`.

---

### Build / Deploy Pipeline

- **Trigger:** Gitea webhook on push to main — auto-deploy is planned but not confirmed active <!-- TODO: verify current deploy mechanism -->
- **Dev start:**
  ```bash
  api\venv\Scripts\activate
  uvicorn api.main:app --reload --host 0.0.0.0 --port 8000
  ```
- **Environment:** `.env` file for local dev; production environment variables managed separately

---

### MCP Servers

Custom MCP servers live in `mcp-servers/`:
- `mcp-servers/feature-management/` — feature tracking MCP server (used by Claude Code to manage GuruRMM feature requests)

Config: `.mcp.json` at repo root.

---

## Key Architecture Decisions

- **FastAPI + SQLAlchemy** — standard Python async API stack. FastAPI chosen for automatic OpenAPI generation and Pydantic validation; SQLAlchemy for ORM flexibility across 38 tables.
- **MariaDB, not PostgreSQL** — chosen for the ClaudeTools API (GuruRMM uses PostgreSQL on the same host). Both run on 172.16.3.30.
- **AES-256-GCM at the service layer, not the DB layer** — credentials are encrypted before write in `api/utils/`, not via DB-native encryption. Allows key rotation and audit without DB-level access.
- **Coordination API with no auth** — deliberately unauthenticated; scoped to internal LAN. Simplifies cross-session coordination without requiring Claude sessions to manage API tokens.
- **Alembic for migrations** — standard SQLAlchemy migration tooling; migration history tracked in DB. All schema changes go through migration files.
- **SOPS vault for credentials** — no plaintext credentials in any checked-in file. Vault wrapper reads `vault_path` from per-machine `identity.json`; no hardcoded paths in shared files.
- **Agents do not run code** — Claude Code coordinator delegates all DB queries, code writes, and git operations to specialized sub-agents. The coordinator only reads 1–2 files directly.

---

## Development Workflow

1. Changes developed locally on developer machine (Windows: `D:\claudetools`; Mac: `~/claudetools`).
2. `api\venv\Scripts\activate` + `uvicorn api.main:app --reload` for local dev server on port 8000.
3. DB migrations: `alembic upgrade head` — must be applied before testing new schema.
4. Code reviewed via Code Review Agent (mandatory before merge).
5. Push to `azcomputerguru/claudetools` on Gitea (http://172.16.3.20:3000); production deploy to 172.16.3.30:8001.
6. Coordination API on prod (port 8001) is always-on; dev sessions can point to it directly for lock/message coordination.

---

## Current Version

- **API:** Production-stable, 95+ endpoints, 38 tables. No explicit version number tracked in the codebase. <!-- TODO: verify if there is a version field in main.py -->
- **Last context update:** 2026-04-14 (CONTEXT.md timestamp)
