Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat: hosted demo, MCP server, deploy buttons, and OSS marketing

Beenu Arora604cffc0dad1
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 2db69c3ca..39b700ddd 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -65,6 +65,65 @@ Connectors are one of the most valuable contributions. To add a new connector:
Existing connectors you can use as references: `crowdstrike`, `aws-security-hub`, `microsoft-sentinel`, `splunk`, `okta`.
+## Community Marketplace
+
+The AiSOC marketplace is content-as-code. Anything in
+[`detections/`](detections/), [`playbooks/`](playbooks/), and
+[`plugins/`](plugins/) is automatically picked up by
+[`scripts/build_marketplace.py`](scripts/build_marketplace.py) and surfaced in
+the in-app **Marketplace** view at `/marketplace`. There is no separate
+registry to push to — you ship a PR, the index regenerates, and your
+contribution shows up.
+
+### Where contributions go
+
+Each content type has a `community/` namespace reserved for outside
+contributors:
+
+- Detections → `detections/community/<your-rule>.yaml`
+- Playbooks → `playbooks/community/<pack-name>/<your-playbook>.playbook.json`
+- Plugins → `plugins/community/<your-plugin-id>/`
+
+These show up in the Marketplace with a **Community** badge (versus the
+**Verified** badge on AiSOC-authored content). Core content lives directly
+under `detections/<category>/`, `playbooks/packs/v1/<category>/`, and
+`plugins/<plugin-id>/`.
+
+### Submitting a contribution
+
+1. Pick the right namespace (rule, playbook, or plugin) and follow the schema
+ used by an existing item of the same type. Detection schema lives in
+ [`detections/README.md`](detections/README.md), playbook schema in
+ [`playbooks/README.md`](playbooks/README.md), plugin schema in
+ [`packages/plugin-sdk-py/README.md`](packages/plugin-sdk-py/README.md) and
+ [`packages/plugin-sdk-go/README.md`](packages/plugin-sdk-go/README.md).
+2. **Rebuild the marketplace index locally:**
+ ```bash
+ pnpm marketplace:build
+ pnpm marketplace:sync
+ ```
+3. Verify CI will be happy:
+ ```bash
+ pnpm marketplace:check # asserts the index matches what's on disk
+ python3 scripts/validate_detections.py # if you added detections
+ ```
+4. Open a PR. CI runs `marketplace:check`, detection validation, and any
+ plugin SDK tests. A maintainer will review for content quality, MITRE
+ ATT&CK accuracy, and false-positive notes.
+
+### Quality bar for community marketplace items
+
+- **Detections** must include MITRE ATT&CK technique IDs in `tags` (format
+ `mitre.attack.T1234[.567]`) and a fixture under `detections/fixtures/`.
+- **Playbooks** must declare a clear trigger, an explicit decision tree, and
+ any human-approval gates. No silent destructive actions.
+- **Plugins** must implement the relevant SDK interface in either Python or
+ Go (preferably both). They must declare `min_aisoc_version`, `license`, and
+ a `homepage` URL. Network calls go through the SDK's HTTP helpers, never
+ bare `requests` or `net/http` calls.
+- All items get `verified: false` and `source: "community"` in the index until
+ a maintainer promotes them.
+
## Reporting Bugs
Please use the GitHub issue tracker. Include:
diff --git a/README.md b/README.md
index 1604137a4..71de84323 100644
--- a/README.md
+++ b/README.md
@@ -4,23 +4,92 @@
# AiSOC
-### Open-source AI Security Operations Center by [Cyble](https://cyble.com)
+### The only AI SOC where the agent is open-source, auditable, and self-hostable.
-Real-time detection, autonomous triage, MITRE ATT&CK-aware investigation, and enterprise-grade compliance in one MIT-licensed platform.
+Every decision the agent makes is **logged step-by-step, queryable, and replayable**. Your data never leaves your infrastructure. MIT-licensed.
[![License: MIT](https://img.shields.io/badge/License-MIT-22c55e.svg?style=flat-square)](https://opensource.org/licenses/MIT)
-[![Built by Cyble](https://img.shields.io/badge/Built%20by-Cyble-2563eb?style=flat-square)](https://cyble.com)
-[![Made with ❤️](https://img.shields.io/badge/Made%20with-%E2%9D%A4%EF%B8%8F-ef4444?style=flat-square)](#)
+[![MITRE accuracy: public benchmark](https://img.shields.io/badge/MITRE%20accuracy-public%20benchmark-2563eb?style=flat-square)](apps/docs/docs/benchmark.md)
+[![Built by Cyble](https://img.shields.io/badge/Built%20by-Cyble-7c3aed?style=flat-square)](https://cyble.com)
[![PRs welcome](https://img.shields.io/badge/PRs-welcome-8b5cf6?style=flat-square)](CONTRIBUTING.md)
[![Version](https://img.shields.io/badge/version-5.1.0-f59e0b?style=flat-square)](#-changelog)
-[**Live demo**](#-quick-start) · [**Architecture**](#-architecture) · [**Console tour**](#-console-tour) · [**API docs**](#-api-reference) · [**Roadmap**](ROADMAP.md) · [**Contributing**](CONTRIBUTING.md) · [**Docs site**](apps/docs/)
+[**Live demo**](https://demo.aisoc.dev) · [**How we compare**](#-how-aisoc-compares) · [**Public benchmark**](apps/docs/docs/benchmark.md) · [**Deploy in one click**](#-deploy-in-one-click) · [**Architecture**](#-architecture) · [**Docs**](apps/docs/)
+
+<br/>
+
+[![▶ Try the live demo — no signup, lands on a live investigation in <60s](https://img.shields.io/badge/%E2%96%B6%20Try%20the%20live%20demo-no%20signup%2C%20%3C60s%20to%20a%20live%20investigation-22c55e?style=for-the-badge&logoColor=white)](https://demo.aisoc.dev/cases/INC-001?tab=ledger)
+
+<sub>Read-only · resets daily at 00:00&nbsp;UTC · lands on a live agent investigation. To run AiSOC on your own data, [self-host in 5 minutes](#-quick-start) or [deploy in one click](#-deploy-in-one-click).</sub>
</div>
---
-## ✨ Why AiSOC
+## 🛡️ Why this matters to a CISO
+
+A CISO at a regulated bank can deploy AiSOC. They cannot deploy a vendor whose agent is a black-box cloud service. AiSOC is the AI SOC your auditor will actually approve, because:
+
+1. **Every agent decision is on the record.** The Investigation Ledger logs the literal LLM prompt, the response, the evidence cited, and the downstream tool calls — for every step of every run. Replay it months later. Hand it to your auditor.
+2. **The benchmarks are public, reproducible, and run in CI.** We publish MITRE ATT&CK accuracy, alert reduction, investigation completeness, and response quality numbers — and the harness is one command away. See the [public benchmark](apps/docs/docs/benchmark.md).
+3. **It runs entirely on your infrastructure.** No callbacks to a vendor cloud. No data exfil for "model improvement." MIT-licensed end-to-end.
+4. **You can fork the agent itself.** The orchestrator is a 600-line LangGraph in [`services/agents/`](services/agents/). Read it. Patch it. Replace the model. Keep the SIEM.
+
+---
+
+## 📊 How AiSOC compares
+
+| Capability | **AiSOC** | Wazuh | Splunk ES | Anvilogic | Prophet Security |
+|---|---|---|---|---|---|
+| Open-source license | ✅ MIT | ✅ GPL-2 | ❌ proprietary | ❌ proprietary | ❌ proprietary |
+| Self-hostable | ✅ | ✅ | ⚠️ enterprise-only | ❌ cloud-only | ❌ cloud-only |
+| Autonomous AI investigation | ✅ LangGraph | ❌ | ⚠️ partial (Splunk AI) | ✅ | ✅ |
+| **Agent decision audit trail** | ✅ public Investigation Ledger | n/a | n/a | ❌ black box | ❌ black box |
+| **Public MITRE accuracy benchmark** | ✅ in CI, reproducible | n/a | n/a | ❌ unpublished | ❌ unpublished |
+| Detection content | 200+ Sigma rules | 1,200+ rules | 1,000+ apps | curated | curated |
+| Plugin SDK | ✅ Py / TS / Go | ⚠️ YAML rules only | apps | proprietary | proprietary |
+| Data residency | 100% your infra | 100% your infra | partial | vendor cloud | vendor cloud |
+| Pricing | $0 (you self-host) | $0 (you self-host) | $$ per ingest GB | $$$ enterprise | $$$ enterprise |
+
+The closed-source AI SOC vendors (Anvilogic, Prophet, Tines, Dropzone) ship excellent products. AiSOC is the only stack where the agent itself is open, the decisions are auditable, and the benchmark numbers are public. That is the structural moat.
+
+---
+
+## 🚀 Deploy in one click
+
+Every deploy target ships with a tested config in [`infra/`](infra/). Pick the platform that matches your operational posture:
+
+| Platform | Status | Config | One-click |
+|---|---|---|---|
+| **Fly.io** (recommended for demo / staging) | ✅ first-class | [`infra/fly/`](infra/fly/) | [Deploy stack](infra/fly/README.md) — 4 apps, ~$14/mo |
+| **Render** (managed, sleep-on-idle for hobbyists) | ✅ supported | [`infra/render/render.yaml`](infra/render/render.yaml) | [![Deploy to Render](https://render.com/images/deploy-to-render-button.svg)](https://render.com/deploy?repo=https://github.com/beenuar/AiSOC) |
+| **Railway** (PaaS, pay-as-you-go) | ✅ supported | [`infra/railway/railway.toml`](infra/railway/railway.toml) | [![Deploy on Railway](https://railway.com/button.svg)](https://railway.com/new/template?template=https%3A%2F%2Fgithub.com%2Fbeenuar%2FAiSOC&plugins=postgresql%2Credis) |
+| **Coolify** (your own VPS, free) | ✅ supported | [`docker-compose.yml`](docker-compose.yml) | [Coolify quickstart](infra/coolify/README.md) |
+| **Kubernetes / Helm** (production) | ✅ first-class | [`infra/helm/`](infra/helm/) | `helm install aisoc ./infra/helm/aisoc` |
+| **AWS / Terraform** (production) | ✅ first-class | [`infra/terraform/`](infra/terraform/) | `cd infra/terraform && terraform apply` |
+
+> 💡 The Render/Railway/Coolify configs deploy the **lean demo profile**: api + agents + web + realtime + Postgres + Redis. ClickHouse, Kafka, OpenSearch, Neo4j, and Qdrant are optional and gated behind compose profiles. For a production-grade install with the full storage tier, use Helm or Terraform.
+
+---
+
+## 🤝 Use it from Claude, Cursor, or Cody
+
+AiSOC ships a first-class **[MCP server](https://modelcontextprotocol.io)** so analysts can query alerts, run agent investigations, and **replay every step the agent took** without leaving the IDE or chat. One command wires up the connection:
+
+```bash
+# Claude Desktop / Cursor / Continue / Cody
+npx -y @aisoc/mcp install --host claude \
+ --aisoc-url https://aisoc.your-company.com \
+ --api-key aisoc_pat_xxxxxxxxxxxx
+```
+
+The server exposes 11 tools — discovery (`aisoc_list_alerts`, `aisoc_list_cases`, `aisoc_query_detections`), deep-dive (`aisoc_get_case`, `aisoc_get_investigation`), and the action/replay set (`aisoc_run_investigation`, `aisoc_replay_decision`, `aisoc_explain_step`) that lets the assistant walk the agent decision ledger step-by-step.
+
+📖 Full guide: [docs/integrations/mcp](apps/docs/docs/integrations/mcp.md) · package source: [`services/mcp/`](services/mcp/) · npm: `@aisoc/mcp`
+
+---
+
+## ✨ What's in the box
Modern SOCs drown in alerts and pivot across a dozen consoles. AiSOC is a **single, opinionated stack** that:
@@ -229,6 +298,37 @@ The console fuses the analyst's day-zero workflow into one cohesive surface:
## 🚀 Quick start
+### One-shot demo (under 5 minutes)
+
+If you just want to see AiSOC investigate a real case in your browser:
+
+```bash
+git clone https://github.com/beenuar/AiSOC.git
+cd AiSOC
+pnpm aisoc:demo
+```
+
+That single command pulls prebuilt images from `ghcr.io/beenuar/*`, brings up
+the slim demo profile (postgres, redis, kafka, api, agents, realtime, web),
+seeds canonical demo data, kicks off an AI investigation against a seeded
+case, and opens your browser at `/cases/<uuid>` so you land on a live
+investigation. Target on a warm Docker daemon:
+
+| Step | Target |
+|---|---|
+| `docker compose pull` | ~90s |
+| `docker compose up` + healthchecks | ~60s |
+| Seed canonical data | ~30s |
+| Kick off investigation | ~30s |
+| **Total time-to-first-investigation** | **~3.5 min** |
+
+When you're done: `pnpm aisoc:demo:down` (deletes the demo volumes).
+
+The full development quick start with all services (UEBA, Honeytokens,
+Purple Team, ClickHouse, OpenSearch, Neo4j, Qdrant) is below.
+
+### Full stack (development)
+
### Prerequisites
- Docker 24+ and Docker Compose v2
diff --git a/apps/docs/docs/integrations/mcp.md b/apps/docs/docs/integrations/mcp.md
new file mode 100644
index 000000000..f8cb34cab
--- /dev/null
+++ b/apps/docs/docs/integrations/mcp.md
@@ -0,0 +1,172 @@
+---
+sidebar_position: 1
+title: MCP server (Claude / Cursor / Cody)
+description: Connect AiSOC to Claude Desktop, Cursor, Cody, and Continue.dev via the Model Context Protocol.
+---
+
+# MCP server
+
+The `@aisoc/mcp` npm package is the official [Model Context Protocol](https://modelcontextprotocol.io) bridge between AiSOC and modern AI assistants. Once installed, your assistant can list alerts, pull cases, run agent investigations, and **replay every step the agent took** — without leaving the chat or the IDE.
+
+> **Why this matters.** MCP is becoming the substrate for "AI tools that work everywhere": Claude Desktop, Cursor, Cody, Continue, Zed, and counting. Every analyst who works in those tools gets AiSOC discovery for free.
+
+## Supported hosts
+
+| Host | One-line install | Config file |
+|---|---|---|
+| **Claude Desktop** | `npx -y @aisoc/mcp install --host claude --aisoc-url … --api-key …` | `~/Library/Application Support/Claude/claude_desktop_config.json` |
+| **Cursor** | `npx -y @aisoc/mcp install --host cursor --aisoc-url … --api-key …` | `~/.cursor/mcp.json` |
+| **Continue.dev** | `npx -y @aisoc/mcp install --host continue --aisoc-url … --api-key …` | `~/.continue/config.json` |
+| **Cody** | `npx -y @aisoc/mcp install --host cody --aisoc-url … --api-key …` (prints snippet) | VS Code User Settings → `cody.mcp.servers` |
+
+Print the canonical config paths for your machine any time:
+
+```bash
+npx -y @aisoc/mcp install --list-paths
+```
+
+## 60-second quickstart
+
+### 1. Mint an API key
+
+In the AiSOC console: **Settings → API Keys → New personal access token**. Give it `cases:read`, `alerts:read`, `detections:read`, and (if you want the agent to investigate from chat) `cases:investigate`. Copy the token — it's shown once.
+
+### 2. Run the installer
+
+```bash
+npx -y @aisoc/mcp install --host claude \
+ --aisoc-url https://aisoc.your-company.com \
+ --api-key aisoc_pat_xxxxxxxxxxxx
+```
+
+The installer is **idempotent**. Re-running it with the same arguments is a no-op; re-running it with a new URL or key updates the entry in place.
+
+### 3. Restart your assistant
+
+- **Claude Desktop**: `Cmd+Q` then reopen.
+- **Cursor**: open Settings → MCP and confirm the `aisoc` server shows green.
+- **Continue.dev**: `Cmd/Ctrl+Shift+P` → _Continue: Reload Window_.
+
+### 4. Try it
+
+Ask your assistant:
+
+> _"Show me the open P0 cases in AiSOC."_
+>
+> _"Replay the agent's reasoning on case INC-0421 step by step."_
+>
+> _"Why did the agent decide that 10.0.42.7 was malicious in run 7c1f…?"_
+
+If the assistant asks for permission to call `aisoc_*` tools, that's expected — every host requires explicit approval the first time.
+
+## Tools exposed
+
+The server advertises **11 tools** to your assistant. Discovery tools list things, deep-dive tools fetch one thing, and the action / replay tools are what make AiSOC interesting:
+
+```mermaid
+graph LR
+ subgraph Discovery
+ A1[aisoc_list_alerts]
+ A2[aisoc_list_cases]
+ A3[aisoc_query_detections]
+ A4[aisoc_list_investigations]
+ end
+ subgraph Deep-dive
+ B1[aisoc_get_alert]
+ B2[aisoc_get_case]
+ B3[aisoc_get_detection_rule]
+ B4[aisoc_get_investigation]
+ end
+ subgraph Action / replay
+ C1[aisoc_run_investigation]
+ C2[aisoc_replay_decision]
+ C3[aisoc_explain_step]
+ end
+ A2 --> B2 --> C1 --> C2 --> C3
+```
+
+| Tool | What it does |
+|---|---|
+| `aisoc_list_alerts` | Page through alerts with filters (severity, status, time range). |
+| `aisoc_get_alert` | Full alert detail including enrichments and matched detections. |
+| `aisoc_list_cases` | Page through cases with filters (status, owner, priority). |
+| `aisoc_get_case` | Full case detail including timeline and linked alerts. |
+| `aisoc_query_detections` | Search detection rules by name, MITRE technique, or tag. |
+| `aisoc_get_detection_rule` | Inspect a single rule (logic, fixtures, FP notes). |
+| `aisoc_list_investigations` | Page through agent investigation runs. |
+| `aisoc_get_investigation` | Run summary (status, duration, agents involved, cost). |
+| **`aisoc_run_investigation`** | Kick off the agent on a case and stream events back. |
+| **`aisoc_replay_decision`** | Walk the agent ledger step-by-step (recon, forensic, responder, reporter). |
+| **`aisoc_explain_step`** | Why-did-the-agent-do-this for a single step: prompt, response, tool I/O. |
+
+The replay/explain pair is the moat: closed-source AI SOC vendors can't show you their agent's prompts and tool calls. AiSOC will.
+
+## Configuration
+
+All flags can be set via env vars; the CLI flag wins if both are present.
+
+| Flag | Env var | Default | Notes |
+|---|---|---|---|
+| `--aisoc-url` | `AISOC_URL` | `http://localhost:8081` | Base URL of the AiSOC API. |
+| `--api-key` | `AISOC_API_KEY` | _(none)_ | API key (`aisoc_pat_…`) or JWT. Required for non-public endpoints. |
+| `--timeout` | `AISOC_TIMEOUT_MS` | `20000` | Per-request timeout in ms. |
+| `--verbose` | `AISOC_VERBOSE=1` | off | Lifecycle logs to stderr (stdout stays JSON-RPC clean). |
+
+## Manual (no-installer) setup
+
+If you'd rather edit JSON yourself, `install --dry-run` prints exactly what the installer would write:
+
+```bash
+npx -y @aisoc/mcp install --host claude --dry-run \
+ --aisoc-url https://aisoc.your-company.com --api-key aisoc_xxx
+```
+
+Paste the snippet under `mcpServers` in your host's config:
+
+```json
+{
+ "mcpServers": {
+ "aisoc": {
+ "command": "npx",
+ "args": ["-y", "@aisoc/mcp", "serve"],
+ "env": {
+ "AISOC_URL": "https://aisoc.your-company.com",
+ "AISOC_API_KEY": "aisoc_pat_xxxxxxxxxxxx"
+ }
+ }
+ }
+}
+```
+
+## Verify before you fly
+
+Before pointing your assistant at it, smoke-test the connection:
+
+```bash
+AISOC_URL=https://aisoc.your-company.com \
+AISOC_API_KEY=aisoc_pat_xxx \
+npx -y @aisoc/mcp doctor
+```
+
+`doctor` checks DNS, TLS, the AiSOC `/health` endpoint, and that your API key is accepted. It exits non-zero on failure, so it's safe to wire into a pre-flight script.
+
+## Security model
+
+- **Your API key never leaves the machine** running the server. It's read from env or the host's local config file (mode `0600`) and used to sign requests to your AiSOC instance.
+- **Read-only by default** unless your API key has write scopes. `aisoc_run_investigation` requires `cases:investigate`; everything else only needs `cases:read` / `alerts:read`.
+- **Audit trail.** Every tool call lands in the AiSOC audit log with the calling user and the tool name. You can revoke the key and replay every action it took.
+- **No telemetry.** This package makes exactly two outbound destinations: your AiSOC URL, and the npm registry on `npx` cold-start.
+
+## Troubleshooting
+
+**The server doesn't appear in my assistant.** Restart the host fully (Claude Desktop: `Cmd+Q`, not just close the window). Then re-run `install --list-paths` and confirm the config file at the printed path actually contains an `aisoc` entry under `mcpServers`.
+
+**Tools fail with 401 / 403.** Re-mint the API key with the right scopes and re-run the installer; it will update the entry in place. Confirm with `npx -y @aisoc/mcp doctor`.
+
+**Tools fail with "fetch failed" / timeouts.** Your assistant's host can't reach `AISOC_URL`. Check that the URL is reachable from the same machine (`curl $AISOC_URL/health`) and bump `--timeout 60000` if you're on a slow link.
+
+**The config file is malformed.** The installer refuses to overwrite a config it can't parse, to avoid clobbering hand-edits. Fix or back up the file, then re-run.
+
+## Source & contributions
+
+The package source lives in [`services/mcp`](https://github.com/beenuar/AiSOC/tree/main/services/mcp). Tests, tool definitions, and the installer are all there. PRs welcome — the contract tests in [`tests/tools.test.ts`](https://github.com/beenuar/AiSOC/blob/main/services/mcp/tests/tools.test.ts) will tell you immediately if you forget metadata, ordering, or naming conventions on a new tool.
diff --git a/apps/docs/docusaurus.config.ts b/apps/docs/docusaurus.config.ts
index e71276e88..e9b7bd5f5 100644
--- a/apps/docs/docusaurus.config.ts
+++ b/apps/docs/docusaurus.config.ts
@@ -4,7 +4,8 @@ import type * as Preset from "@docusaurus/preset-classic";
const config: Config = {
title: "AiSOC",
- tagline: "Open-source AI SOC — autonomous detection, investigation, and response",
+ tagline:
+ "The auditable AI SOC — every agent decision logged, replayable, and benchmarked publicly. MIT-licensed, self-hostable.",
favicon: "img/favicon.ico",
url: "https://beenuar.github.io",
diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts
index deea27f96..0874a357d 100644
--- a/apps/docs/sidebars.ts
+++ b/apps/docs/sidebars.ts
@@ -5,7 +5,7 @@ const sidebars: SidebarsConfig = {
{
type: "category",
label: "Getting Started",
- items: ["intro", "quickstart", "architecture"],
+ items: ["intro", "quickstart", "architecture", "benchmark"],
},
{
type: "category",
@@ -22,6 +22,11 @@ const sidebars: SidebarsConfig = {
"plugins/publishing",
],
},
+ {
+ type: "category",
+ label: "Integrations",
+ items: ["integrations/mcp"],
+ },
{
type: "category",
label: "API Reference",
diff --git a/apps/docs/src/pages/index.module.css b/apps/docs/src/pages/index.module.css
index d4651f24a..7ee686ab8 100644
--- a/apps/docs/src/pages/index.module.css
+++ b/apps/docs/src/pages/index.module.css
@@ -12,3 +12,73 @@
gap: 1rem;
margin-top: 1.5rem;
}
+
+.sectionTitle {
+ text-align: center;
+ margin-bottom: 0.75rem;
+}
+
+.sectionLede {
+ text-align: center;
+ max-width: 720px;
+ margin: 0 auto 2.5rem;
+ color: var(--ifm-color-emphasis-700);
+}
+
+.compareWrap {
+ overflow-x: auto;
+ border-radius: 0.5rem;
+ border: 1px solid var(--ifm-color-emphasis-300);
+}
+
+.compareTable {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 0.95rem;
+ margin: 0;
+}
+
+.compareTable thead th {
+ background: var(--ifm-color-emphasis-100);
+ text-align: left;
+ font-weight: 600;
+ padding: 0.85rem 1rem;
+ border-bottom: 1px solid var(--ifm-color-emphasis-300);
+}
+
+.compareTable th.aisocCol,
+.compareTable td.aisocCell {
+ background: rgba(53, 120, 229, 0.08);
+ font-weight: 600;
+}
+
+.compareTable td {
+ padding: 0.75rem 1rem;
+ border-bottom: 1px solid var(--ifm-color-emphasis-200);
+ vertical-align: top;
+}
+
+.compareTable tr:last-child td {
+ border-bottom: 0;
+}
+
+.compareYes {
+ color: var(--ifm-color-success);
+ font-weight: 600;
+}
+
+.compareNo {
+ color: var(--ifm-color-emphasis-600);
+}
+
+.compareCaveat {
+ color: var(--ifm-color-warning-darker);
+ font-weight: 500;
+}
+
+.compareNote {
+ text-align: center;
+ margin-top: 1rem;
+ color: var(--ifm-color-emphasis-600);
+ font-size: 0.9rem;
+}
diff --git a/apps/docs/src/pages/index.tsx b/apps/docs/src/pages/index.tsx
index c78da01fd..5376e09c8 100644
--- a/apps/docs/src/pages/index.tsx
+++ b/apps/docs/src/pages/index.tsx
@@ -29,16 +29,36 @@ function HomepageHeader() {
);
}
+// Top three features lead with the structural moat: auditable agent decisions,
+// the public benchmark that proves them, and the MIT/self-host posture that
+// makes both meaningful in regulated environments. The remaining capability
+// list follows so visitors see we ship the substrate too — but the headline
+// reason to pick AiSOC over a closed-source competitor sits in rows 1–3.
const FEATURES = [
{
- title: '🔍 AI Investigation',
+ title: '🔎 Auditable agent decisions',
description:
- 'LangGraph multi-agent workflows for automated root-cause analysis, triage, and case enrichment.',
+ 'Every prompt, tool call, and rationale the agent emits is persisted to the investigation ledger and replayable step-by-step in the case workspace.',
},
{
- title: '📋 Playbook Engine',
+ title: '📊 Public MITRE benchmark',
description:
- 'Visual React Flow editor with 12+ starter templates for automated, auditable response actions.',
+ '200-incident eval suite covering MITRE ATT&CK accuracy, alert reduction, investigation completeness, and response quality. Numbers are CI-gated and reproducible on your laptop.',
+ },
+ {
+ title: '🆓 MIT-licensed, self-hostable',
+ description:
+ 'Read the code, audit the prompts, run the agent on your own data. No CLA, no telemetry, no calls home — your auditor can review every line.',
+ },
+ {
+ title: '🔍 LangGraph multi-agent investigation',
+ description:
+ 'Recon → forensic → responder → reporter graph for automated root-cause analysis, triage, and case enrichment.',
+ },
+ {
+ title: '📋 Playbook engine',
+ description:
+ 'Visual React Flow editor with 12+ starter templates for automated, human-gated response actions.',
},
{
title: '🧠 UEBA',
@@ -56,51 +76,208 @@ const FEATURES = [
'Atomic Red Team YAML parser + Caldera executor, ATT&CK coverage heatmap, and tabletop sessions.',
},
{
- title: '⚡ Real-time Fusion',
+ title: '⚡ Real-time fusion',
description:
'Kafka spine with sub-second alert ingestion, Bloom-filter dedup on 10M+ IOCs, ML scoring (LightGBM + Isolation Forest).',
},
{
- title: '🕸️ Attack Graph',
+ title: '🕸️ Attack graph',
description:
'Neo4j entity graph with attack-path reconstruction and blast-radius gating on automated actions.',
},
{
- title: '🛡️ Detection Engineering',
+ title: '🛡️ Detection engineering',
description:
'Sigma over OpenSearch + ClickHouse, YARA, KQL/EQL — community catalog with one-click install.',
},
{
- title: '🏛️ Enterprise Governance',
+ title: '🏛️ Enterprise governance',
description:
'SAML 2.0 + OIDC SSO, multi-tenant Postgres RLS, granular RBAC, and immutable audit log.',
},
{
- title: '📊 Compliance Dashboards',
+ title: '📊 Compliance dashboards',
description:
'SOC 2, ISO 27001, NIST CSF, PCI-DSS, HIPAA, DORA evidence with MTTD/MTTR/MTTC SLA tracking.',
},
{
- title: '🔌 Plugin Ecosystem',
+ title: '🔌 Plugin ecosystem',
description:
'Python and TypeScript SDKs, Ed25519-signed publishing, and a community marketplace.',
},
{
- title: '🚀 Cloud-Native',
+ title: '🚀 Cloud-native',
description:
'Helm charts, Docker Compose, OpenTelemetry traces/metrics/logs, and PostgreSQL backup with KMS encryption.',
},
];
+// Comparison rows are written as visitor-actionable claims, not marketing
+// gloss. We anchor each row to a concrete capability ("Agent decisions are
+// auditable line-by-line") so the table can be defended in a sales call.
+// Ordering is intentional: the top three rows are the ones a CISO at a
+// regulated org will use to disqualify closed-source SOCs first.
+type CompareCell = { kind: 'yes' | 'no' | 'caveat'; label: string };
+
+const COMPARE_HEADERS = [
+ 'Capability',
+ 'AiSOC',
+ 'Wazuh',
+ 'Splunk Enterprise Security',
+ 'Anvilogic',
+ 'Prophet Security',
+] as const;
+
+const COMPARE_ROWS: ReadonlyArray<{ feature: string; cells: CompareCell[] }> = [
+ {
+ feature: 'Open-source (MIT) and self-hostable',
+ cells: [
+ { kind: 'yes', label: 'Yes — MIT' },
+ { kind: 'yes', label: 'Yes — GPLv2' },
+ { kind: 'no', label: 'No' },
+ { kind: 'no', label: 'Cloud-only' },
+ { kind: 'no', label: 'Cloud-only' },
+ ],
+ },
+ {
+ feature: 'Agent decisions are auditable line-by-line',
+ cells: [
+ { kind: 'yes', label: 'Yes — full ledger + replay' },
+ { kind: 'caveat', label: 'No agent layer' },
+ { kind: 'no', label: 'Black-box ML' },
+ { kind: 'no', label: 'Black-box agent' },
+ { kind: 'no', label: 'Black-box agent' },
+ ],
+ },
+ {
+ feature: 'Detection accuracy is publicly benchmarked',
+ cells: [
+ { kind: 'yes', label: '200-case suite, CI-gated' },
+ { kind: 'no', label: 'Not published' },
+ { kind: 'no', label: 'Not published' },
+ { kind: 'caveat', label: 'Vendor-claimed only' },
+ { kind: 'caveat', label: 'Vendor-claimed only' },
+ ],
+ },
+ {
+ feature: 'Native AI investigation agent',
+ cells: [
+ { kind: 'yes', label: 'LangGraph multi-agent' },
+ { kind: 'no', label: 'No' },
+ { kind: 'caveat', label: 'Splunk AI Assistant add-on' },
+ { kind: 'yes', label: 'Closed-source' },
+ { kind: 'yes', label: 'Closed-source' },
+ ],
+ },
+ {
+ feature: 'MITRE ATT&CK heatmap + purple-team emulation',
+ cells: [
+ { kind: 'yes', label: 'Built-in' },
+ { kind: 'caveat', label: 'Partial' },
+ { kind: 'caveat', label: 'Premium add-on' },
+ { kind: 'yes', label: 'Yes' },
+ { kind: 'caveat', label: 'Limited' },
+ ],
+ },
+ {
+ feature: 'Plugin SDK (Python + Go) + community marketplace',
+ cells: [
+ { kind: 'yes', label: 'Both SDKs, MIT' },
+ { kind: 'caveat', label: 'Wodles only' },
+ { kind: 'yes', label: 'Splunkbase' },
+ { kind: 'no', label: 'Vendor-only' },
+ { kind: 'no', label: 'Vendor-only' },
+ ],
+ },
+ {
+ feature: 'Compliance evidence (SOC2 / ISO / NIST / DORA)',
+ cells: [
+ { kind: 'yes', label: 'Built-in dashboards' },
+ { kind: 'no', label: 'No' },
+ { kind: 'yes', label: 'Premium add-on' },
+ { kind: 'caveat', label: 'Reporting only' },
+ { kind: 'caveat', label: 'Reporting only' },
+ ],
+ },
+];
+
+function compareCellClass(cell: CompareCell): string {
+ switch (cell.kind) {
+ case 'yes':
+ return styles.compareYes;
+ case 'no':
+ return styles.compareNo;
+ case 'caveat':
+ return styles.compareCaveat;
+ }
+}
+
+function ComparisonTable() {
+ return (
+ <div className="container margin-vert--xl">
+ <h2 className={styles.sectionTitle}>Why AiSOC vs. the alternatives</h2>
+ <p className={styles.sectionLede}>
+ The structural moat: open-source, self-hostable, with every agent decision
+ auditable end-to-end. Closed-source AI SOCs run on someone else&apos;s
+ infrastructure and ship a black-box agent — neither survives a serious
+ compliance review.
+ </p>
+ <div className={styles.compareWrap}>
+ <table className={styles.compareTable}>
+ <thead>
+ <tr>
+ {COMPARE_HEADERS.map((header, idx) => (
+ <th
+ key={header}
+ className={idx === 1 ? styles.aisocCol : undefined}>
+ {header}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {COMPARE_ROWS.map((row) => (
+ <tr key={row.feature}>
+ <td>{row.feature}</td>
+ {row.cells.map((cell, idx) => (
+ <td
+ key={idx}
+ className={clsx(
+ idx === 0 ? styles.aisocCell : undefined,
+ compareCellClass(cell),
+ )}>
+ {cell.label}
+ </td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ <p className={styles.compareNote}>
+ Numbers and capability claims are sourced from each vendor&apos;s public
+ documentation as of 2026.{' '}
+ <Link to="/docs/intro">Verify ours →</Link>
+ </p>
+ </div>
+ );
+}
+
export default function Home(): React.JSX.Element {
const { siteConfig } = useDocusaurusContext();
return (
<Layout
title={siteConfig.title}
- description="Open-source AI SOC — autonomous detection, investigation, and response with UEBA, honeytokens, purple-team emulation, and SOC 2 / ISO 27001 / NIST CSF compliance.">
+ description="The auditable AI SOC — every agent decision logged, replayable, and benchmarked publicly. MIT-licensed, self-hostable, with built-in UEBA, honeytokens, purple-team emulation, and SOC 2 / ISO 27001 / NIST CSF compliance.">
<HomepageHeader />
<main>
+ <ComparisonTable />
<div className="container margin-vert--xl">
+ <h2 className={styles.sectionTitle}>What you get out of the box</h2>
+ <p className={styles.sectionLede}>
+ The trust trio leads — auditable agent, public benchmark, MIT
+ license — backed by the full SOC substrate underneath.
+ </p>
<div className="row">
{FEATURES.map(({ title, description }) => (
<div key={title} className="col col--4 margin-bottom--lg">
diff --git a/apps/web/next-env.d.ts b/apps/web/next-env.d.ts
new file mode 100644
index 000000000..4f11a03dc
--- /dev/null
+++ b/apps/web/next-env.d.ts
@@ -0,0 +1,5 @@
+/// <reference types="next" />
+/// <reference types="next/image-types/global" />
+
+// NOTE: This file should not be edited
+// see https://nextjs.org/docs/basic-features/typescript for more information.
diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsx
index 78518d6c2..4d40fc75e 100644
--- a/apps/web/src/app/layout.tsx
+++ b/apps/web/src/app/layout.tsx
@@ -2,6 +2,7 @@ import type { Metadata, Viewport } from 'next';
import { Inter, JetBrains_Mono } from 'next/font/google';
import { Toaster } from 'react-hot-toast';
import './globals.css';
+import { PwaBootstrap } from '@/components/pwa/PwaBootstrap';
const inter = Inter({
subsets: ['latin'],
@@ -56,6 +57,13 @@ export const metadata: Metadata = {
{ url: '/favicon.svg', type: 'image/svg+xml' },
{ url: '/favicon.ico', sizes: 'any' },
],
+ apple: [{ url: '/icons/icon-192.svg', type: 'image/svg+xml' }],
+ },
+ manifest: '/manifest.json',
+ appleWebApp: {
+ capable: true,
+ title: 'AiSOC',
+ statusBarStyle: 'black-translucent',
},
robots: { index: true, follow: true },
};
@@ -74,6 +82,7 @@ export default function RootLayout({
return (
<html lang="en" className={`${inter.variable} ${jetbrainsMono.variable}`}>
<body className="bg-[#0a0d14] text-gray-100 antialiased">
+ <PwaBootstrap />
{children}
<Toaster
position="bottom-right"
diff --git a/apps/web/src/app/why-open-source/page.tsx b/apps/web/src/app/why-open-source/page.tsx
new file mode 100644
index 000000000..e999df9f9
--- /dev/null
+++ b/apps/web/src/app/why-open-source/page.tsx
@@ -0,0 +1,466 @@
+import type { Metadata } from 'next';
+import Link from 'next/link';
+import { LandingNav } from '@/components/landing/LandingNav';
+import { Footer } from '@/components/landing/Footer';
+
+export const metadata: Metadata = {
+ title: 'Why open source — the AI SOC your auditor will approve',
+ description:
+ 'A regulated bank cannot deploy a SOC whose agent is a black-box cloud service. They can deploy AiSOC. Here is the structural argument for why MIT-licensed, self-hosted, auditable AI is the only AI SOC posture that survives a compliance review.',
+ alternates: { canonical: '/why-open-source' },
+ openGraph: {
+ title: 'The AI SOC your auditor will approve — AiSOC',
+ description:
+ 'Why MIT-licensed, self-hosted, auditable AI is the only AI SOC posture a regulated buyer can ship. The structural argument, in writing.',
+ type: 'article',
+ },
+};
+
+const PILLARS = [
+ {
+ label: 'Investigation Ledger',
+ href: 'https://github.com/beenuar/AiSOC#investigation-ledger',
+ body: 'Every prompt, every tool call, every evidence citation, every decision the agent makes is written to a durable, queryable, replayable ledger. Not summarised. Not redacted. The literal LLM I/O.',
+ },
+ {
+ label: 'Public benchmark',
+ href: '/benchmark',
+ body: 'A 200-incident MITRE suite runs on every commit. Four CI gates. The harness, the dataset, the rubric, and the historical results are all in the repo. Reproduce them on your laptop.',
+ },
+ {
+ label: 'MIT, end-to-end',
+ href: 'https://github.com/beenuar/AiSOC/blob/main/LICENSE',
+ body: 'No CLA. No SSPL. No BSL conversion clause. No "open core" with the agent gated behind a contract. Audit it, fork it, run it air-gapped, build a competitor — the licence permits all of it.',
+ },
+] as const;
+
+const ARTEFACTS = [
+ {
+ title: 'A signed event stream per investigation',
+ body: "Hand your auditor a JSON file. They read every step the agent took, every prompt issued, every model used, every token spent, every evidence row cited, every action executed, in order, with hashes. They don't have to trust us. They read the events.",
+ },
+ {
+ title: 'A reproducible accuracy number',
+ body: 'Your auditor clones the repo and runs `python3 scripts/run_evals.py`. They get the same MITRE accuracy, alert reduction ratio, completeness coverage, and response-quality score we publish. The CI gate is the source of truth, not the marketing site.',
+ },
+ {
+ title: 'Source code for the agent itself',
+ body: "Not the SDK. Not the integration shim. The orchestrator, the planner, the prompt templates, the tool registry, the response policy, the rubric — the entire agent that touches your incident data is in this repo, MIT licensed. You can diff it, patch it, and ship that fork.",
+ },
+] as const;
+
+type Contrast = {
+ label: string;
+ points: readonly string[];
+ accent?: boolean;
+};
+
+const CONTRASTS: readonly Contrast[] = [
+ {
+ label: 'Black-box AI SOC vendor',
+ points: [
+ 'Agent runs in vendor cloud. Your incident data leaves your network for inference.',
+ 'Prompts and policy are proprietary. You cannot audit how the agent reasons or what it tells the model about your case.',
+ 'Accuracy claims are marketing. No reproducible harness, no public CI gate, no historical regression record.',
+ 'No fork right. If the vendor changes the model, the policy, or the price, you have one option: comply.',
+ ],
+ },
+ {
+ label: 'Open-core with proprietary agent',
+ points: [
+ 'The dashboard is open. The agent is not. The thing you actually need to audit is in a private repo.',
+ 'License is SSPL or BSL with a CLA. You "own" your fork until the next licence flip.',
+ 'The benchmark is internal. You see the score. You cannot see the dataset or rerun the harness.',
+ 'Self-hosting is technically allowed and operationally hostile.',
+ ],
+ },
+ {
+ label: 'AiSOC',
+ points: [
+ 'Agent runs on your infrastructure. Your incident data, by default, never leaves your network.',
+ 'Every prompt, response, tool call, and decision is in the Investigation Ledger and replayable forever.',
+ 'Accuracy is a CI gate. The dataset, the harness, the rubric, and the latest numbers are all public and reproducible in seconds.',
+ 'MIT, no CLA. Fork it, patch the prompts, ship it. We do not have the legal right to take that away.',
+ ],
+ accent: true,
+ },
+];
+
+const NON_REGULATED_REASONS = [
+ {
+ title: 'You keep agency over the agent',
+ body: "When an LLM vendor changes a model and your detection tone shifts overnight, you want to be the one who decides whether to ship the change. With a closed agent, that decision was made for you weeks ago.",
+ },
+ {
+ title: 'No rug pull, ever',
+ body: "MIT means the version you ran today is yours forever. No relicense. No 'AI features now in the paid tier'. No 'open-source community edition' deprecation. Fork the commit and you are operationally independent.",
+ },
+ {
+ title: 'Real extension, not "extensible"',
+ body: 'Plugins, detections, playbooks, and prompts are all source code in the same repo. You write a Python or Go plugin against a typed SDK and it ships with the rest of the stack. No SaaS extensibility tax.',
+ },
+] as const;
+
+export default function WhyOpenSourcePage() {
+ return (
+ <main className="relative min-h-screen overflow-x-hidden bg-surface-base text-white">
+ <LandingNav />
+
+ <section className="relative px-6 pt-32 pb-16">
+ <div className="mx-auto max-w-3xl">
+ <div className="mb-3 flex items-center gap-2">
+ <span className="inline-flex items-center gap-1.5 rounded-full border border-emerald-500/20 bg-emerald-500/10 px-3 py-1 text-xs font-medium text-emerald-300">
+ <span className="h-1.5 w-1.5 rounded-full bg-emerald-400" />
+ MIT-licensed, structurally
+ </span>
+ <span className="text-xs text-gray-500">~7 min read</span>
+ </div>
+ <h1 className="text-4xl font-bold tracking-tight md:text-5xl">
+ The AI SOC your auditor will approve.
+ </h1>
+ <p className="mt-5 text-lg leading-relaxed text-gray-400">
+ A CISO at a regulated bank cannot deploy a SOC whose agent is a
+ black-box cloud service. They can deploy AiSOC. The argument below
+ explains why that distinction is not a feature comparison — it is a
+ structural property of the licence and the architecture, and it is
+ the reason AiSOC exists.
+ </p>
+ </div>
+ </section>
+
+ <section className="px-6 pb-16">
+ <div className="mx-auto max-w-3xl space-y-6 text-base leading-relaxed text-gray-300">
+ <h2 className="pt-2 text-2xl font-semibold tracking-tight text-white">
+ The problem the AI SOC market gave compliance teams
+ </h2>
+ <p>
+ Every closed-source AI SOC vendor on the market today asks a
+ regulated buyer to do three things simultaneously: ship their
+ incident data to a vendor cloud for inference, trust an opaque
+ policy that no one outside the vendor can read, and accept an
+ accuracy number that no one outside the vendor can reproduce.
+ </p>
+ <p>
+ That is a stack of three independent compliance problems, and the
+ third — the unverifiable accuracy claim — is the one that
+ quietly poisons the other two. If you cannot reproduce the
+ number, you cannot defend the deployment in an audit. If you
+ cannot defend it in an audit, you cannot get the deployment
+ approved. Most teams end up with a tactical workaround: AI SOC for
+ non-sensitive tenants, a manual triage queue for the regulated
+ ones, and a slow, awkward conversation with their auditor every
+ quarter about whether the line should hold.
+ </p>
+ <p>
+ AiSOC is the answer to that conversation: an AI SOC where the
+ agent itself is in the repo, the accuracy is a CI gate, the data
+ stays in your network, and the licence cannot be retracted.
+ </p>
+ </div>
+ </section>
+
+ <section className="px-6 pb-16">
+ <div className="mx-auto max-w-5xl">
+ <h2 className="text-2xl font-semibold tracking-tight">
+ What &ldquo;auditable&rdquo; actually means here
+ </h2>
+ <p className="mt-3 max-w-3xl text-sm text-gray-400">
+ Three concrete artefacts. They are the entire pitch. Everything
+ else is downstream.
+ </p>
+ <div className="mt-8 grid gap-4 md:grid-cols-3">
+ {PILLARS.map((p) => {
+ const external = p.href.startsWith('http');
+ const Inner = (
+ <div className="group h-full rounded-2xl border border-white/10 bg-white/[0.02] p-6 transition hover:border-white/20 hover:bg-white/[0.04]">
+ <div className="text-xs font-semibold uppercase tracking-wider text-emerald-300">
+ {p.label}
+ </div>
+ <p className="mt-3 text-sm leading-relaxed text-gray-300">
+ {p.body}
+ </p>
+ <div className="mt-4 inline-flex items-center gap-1 text-xs font-medium text-gray-400 group-hover:text-white">
+ Open
+ <svg
+ viewBox="0 0 20 20"
+ className="h-3 w-3"
+ fill="currentColor"
+ aria-hidden="true"
+ >
+ <path d="M5.22 14.78a.75.75 0 001.06 0l7.22-7.22v3.69a.75.75 0 001.5 0v-5.5a.75.75 0 00-.75-.75h-5.5a.75.75 0 000 1.5h3.69L5.22 13.72a.75.75 0 000 1.06z" />
+ </svg>
+ </div>
+ </div>
+ );
+ return external ? (
+ <a key={p.label} href={p.href} target="_blank" rel="noreferrer">
+ {Inner}
+ </a>
+ ) : (
+ <Link key={p.label} href={p.href}>
+ {Inner}
+ </Link>
+ );
+ })}
+ </div>
+ </div>
+ </section>
+
+ <section className="px-6 pb-16">
+ <div className="mx-auto max-w-3xl space-y-6 text-base leading-relaxed text-gray-300">
+ <h2 className="pt-2 text-2xl font-semibold tracking-tight text-white">
+ Three things you can hand your auditor
+ </h2>
+ <p>
+ Every other claim on this page reduces to one of these. If your
+ auditor cannot read all three on the first day of the deployment
+ review, the AI SOC is not auditable; it is just AI-shaped.
+ </p>
+ <div className="mt-2 space-y-3">
+ {ARTEFACTS.map((a, i) => (
+ <div
+ key={a.title}
+ className="rounded-2xl border border-white/10 bg-white/[0.02] p-6"
+ >
+ <div className="flex items-start gap-4">
+ <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-white/10 bg-white/5 font-mono text-sm text-gray-300">
+ {String(i + 1).padStart(2, '0')}
+ </div>
+ <div>
+ <h3 className="text-base font-semibold text-white">
+ {a.title}
+ </h3>
+ <p className="mt-2 text-sm leading-relaxed text-gray-400">
+ {a.body}
+ </p>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </section>
+
+ <section className="px-6 pb-16">
+ <div className="mx-auto max-w-5xl">
+ <h2 className="text-2xl font-semibold tracking-tight">
+ What the alternatives ask you to accept
+ </h2>
+ <p className="mt-3 max-w-3xl text-sm text-gray-400">
+ We mark trade-offs honestly. The two non-AiSOC columns describe
+ the dominant patterns in the AI SOC market today, not any
+ specific vendor. If you have an example that does not fit, we
+ want to hear about it.
+ </p>
+ <div className="mt-8 grid gap-4 lg:grid-cols-3">
+ {CONTRASTS.map((c) => (
+ <div
+ key={c.label}
+ className={
+ c.accent
+ ? 'rounded-2xl border border-brand-500/30 bg-brand-500/[0.06] p-6'
+ : 'rounded-2xl border border-white/10 bg-white/[0.02] p-6'
+ }
+ >
+ <div
+ className={
+ c.accent
+ ? 'text-xs font-semibold uppercase tracking-wider text-brand-300'
+ : 'text-xs font-semibold uppercase tracking-wider text-gray-500'
+ }
+ >
+ {c.label}
+ </div>
+ <ul className="mt-4 space-y-2.5 text-sm leading-relaxed text-gray-300">
+ {c.points.map((pt) => (
+ <li key={pt} className="flex gap-2">
+ <span
+ className={
+ c.accent
+ ? 'mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-brand-400'
+ : 'mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-gray-500'
+ }
+ />
+ <span>{pt}</span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ ))}
+ </div>
+ </div>
+ </section>
+
+ <section className="px-6 pb-16">
+ <div className="mx-auto max-w-3xl space-y-6 text-base leading-relaxed text-gray-300">
+ <h2 className="pt-2 text-2xl font-semibold tracking-tight text-white">
+ What MIT actually means here
+ </h2>
+ <p>
+ &ldquo;Open source&rdquo; is overloaded. A meaningful number of
+ self-described open-source security products today ship under
+ licences that grant the cosmetic benefit of source-available code
+ and reserve the rights that matter. We picked MIT, no CLA, and
+ committed to keeping the core MIT in the README, on purpose.
+ </p>
+ <ul className="space-y-3">
+ <li className="rounded-lg border border-white/5 bg-white/[0.02] p-4">
+ <strong className="text-gray-200">No CLA.</strong>{' '}
+ Contributors keep copyright on their patches. We do not collect
+ an irrevocable licence to relicense the project tomorrow under
+ SSPL, BSL, or a proprietary EULA. This is the line most
+ &ldquo;open core&rdquo; projects cross first.
+ </li>
+ <li className="rounded-lg border border-white/5 bg-white/[0.02] p-4">
+ <strong className="text-gray-200">No telemetry.</strong>{' '}
+ Self-hosted deployments emit no analytics back to Cyble.
+ Detection tuning, agent decisions, and operator behaviour stay
+ on your boxes. The only network calls AiSOC initiates are the
+ ones you configured: your LLM provider, your TI feed, your
+ integrations.
+ </li>
+ <li className="rounded-lg border border-white/5 bg-white/[0.02] p-4">
+ <strong className="text-gray-200">
+ No agent gated behind a paid tier.
+ </strong>{' '}
+ The orchestrator, the planner, the prompt templates, the tool
+ registry, the response policy, the rubric — every component
+ that reasons over your incident data — is in this repo. There
+ is no &ldquo;enterprise agent&rdquo; we are saving for a future
+ SKU. The agent is the project.
+ </li>
+ <li className="rounded-lg border border-white/5 bg-white/[0.02] p-4">
+ <strong className="text-gray-200">Fork rights are real.</strong>{' '}
+ If we ship a release tomorrow that you do not like — a model
+ choice, a default policy, a UX change — you have the legal and
+ practical right to take the previous commit and run it
+ indefinitely. We can ask you to upstream improvements. We
+ cannot make you accept a downgrade.
+ </li>
+ </ul>
+ </div>
+ </section>
+
+ <section className="px-6 pb-16">
+ <div className="mx-auto max-w-5xl">
+ <h2 className="text-2xl font-semibold tracking-tight">
+ What this means if you are not in a regulated industry
+ </h2>
+ <p className="mt-3 max-w-3xl text-sm text-gray-400">
+ The compliance story is the most legible one, but it is not the
+ only one. Even if your auditor never reviews the SOC, the same
+ structural properties give you operator agency that closed-source
+ AI SOCs cannot match.
+ </p>
+ <div className="mt-8 grid gap-4 md:grid-cols-3">
+ {NON_REGULATED_REASONS.map((r) => (
+ <div
+ key={r.title}
+ className="rounded-2xl border border-white/10 bg-white/[0.02] p-6"
+ >
+ <h3 className="text-base font-semibold text-white">
+ {r.title}
+ </h3>
+ <p className="mt-3 text-sm leading-relaxed text-gray-400">
+ {r.body}
+ </p>
+ </div>
+ ))}
+ </div>
+ </div>
+ </section>
+
+ <section className="px-6 pb-16">
+ <div className="mx-auto max-w-3xl space-y-6 text-base leading-relaxed text-gray-300">
+ <h2 className="pt-2 text-2xl font-semibold tracking-tight text-white">
+ What we will not claim
+ </h2>
+ <p>
+ AiSOC is not a finished product, and overclaiming would defeat
+ the point of writing this page. A few things we are explicit
+ about:
+ </p>
+ <ul className="space-y-3">
+ <li className="rounded-lg border border-white/5 bg-white/[0.02] p-4">
+ <strong className="text-gray-200">
+ We do not claim better accuracy than every vendor.
+ </strong>{' '}
+ We claim measurable accuracy. Anyone who reads the benchmark
+ page can see exactly where we are. The gap between &ldquo;we
+ measure ours; they don&rsquo;t publish theirs&rdquo; is the
+ part that matters to a regulated buyer.
+ </li>
+ <li className="rounded-lg border border-white/5 bg-white/[0.02] p-4">
+ <strong className="text-gray-200">
+ Self-hosting is operationally real, not free.
+ </strong>{' '}
+ You run Postgres, Redis, ClickHouse, an LLM endpoint. We
+ shipped <code className="text-gray-300">pnpm aisoc:demo</code>{' '}
+ and one-click deploy buttons to make the on-ramp short, but
+ this is your stack and you operate it.
+ </li>
+ <li className="rounded-lg border border-white/5 bg-white/[0.02] p-4">
+ <strong className="text-gray-200">
+ Bring-your-own LLM means bring-your-own trust boundary.
+ </strong>{' '}
+ The agent will, by default, send prompts to whatever LLM
+ endpoint you configure. The Investigation Ledger logs every
+ prompt so you can audit what left the network, but the trust
+ boundary is the LLM you point at, not AiSOC. A future air-gap
+ mode using local inference is on the roadmap; today, you pick
+ the model.
+ </li>
+ </ul>
+ </div>
+ </section>
+
+ <section className="px-6 pb-24">
+ <div className="mx-auto max-w-4xl rounded-2xl border border-brand-500/20 bg-gradient-to-br from-brand-500/10 to-transparent p-8 text-center">
+ <h2 className="text-2xl font-semibold tracking-tight">
+ See it before you trust it
+ </h2>
+ <p className="mx-auto mt-3 max-w-2xl text-sm text-gray-400">
+ Three artefacts, all reproducible in under a minute: a live
+ investigation with the full ledger open, the public benchmark on
+ your laptop, and the agent source on GitHub. None of them
+ require a signup.
+ </p>
+ <div className="mt-6 flex flex-wrap justify-center gap-3">
+ <a
+ href="https://demo.aisoc.dev/cases/INC-001?tab=ledger"
+ target="_blank"
+ rel="noreferrer"
+ className="inline-flex items-center gap-2 rounded-md bg-brand-500 px-4 py-2 text-sm font-semibold text-white shadow-glow-sm transition hover:bg-brand-400"
+ >
+ Try the live demo
+ <svg
+ viewBox="0 0 20 20"
+ className="h-3.5 w-3.5"
+ fill="currentColor"
+ aria-hidden="true"
+ >
+ <path d="M5.22 14.78a.75.75 0 001.06 0l7.22-7.22v3.69a.75.75 0 001.5 0v-5.5a.75.75 0 00-.75-.75h-5.5a.75.75 0 000 1.5h3.69L5.22 13.72a.75.75 0 000 1.06z" />
+ </svg>
+ </a>
+ <Link
+ href="/benchmark"
+ className="inline-flex items-center gap-2 rounded-md border border-white/10 bg-white/[0.03] px-4 py-2 text-sm font-medium text-gray-300 transition hover:border-white/20 hover:bg-white/[0.06] hover:text-white"
+ >
+ Read the benchmark
+ </Link>
+ <a
+ href="https://github.com/beenuar/AiSOC"
+ target="_blank"
+ rel="noreferrer"
+ className="inline-flex items-center gap-2 rounded-md border border-white/10 bg-white/[0.03] px-4 py-2 text-sm font-medium text-gray-300 transition hover:border-white/20 hover:bg-white/[0.06] hover:text-white"
+ >
+ View the agent source
+ </a>
+ </div>
+ </div>
+ </section>
+
+ <Footer />
+ </main>
+ );
+}
diff --git a/apps/web/src/components/demo/DemoBanner.tsx b/apps/web/src/components/demo/DemoBanner.tsx
new file mode 100644
index 000000000..ead3b2d4f
--- /dev/null
+++ b/apps/web/src/components/demo/DemoBanner.tsx
@@ -0,0 +1,52 @@
+'use client';
+
+/**
+ * DemoBanner — top-of-page strip rendered on the hosted demo at demo.aisoc.dev.
+ *
+ * Sits inside `AppShell` above the TopBar so it covers every authenticated
+ * page. Renders nothing when `NEXT_PUBLIC_DEMO_MODE !== 'true'`, so self-hosted
+ * deployments never see it.
+ *
+ * Accessibility: announced via role="status" so screen readers pick up the
+ * "writes are disabled" message at page load. Not dismissible — visitors have
+ * to know writes will 403, otherwise they'll think the app is broken.
+ */
+
+import { isDemoMode, demoBannerMessage } from '@/lib/demoMode';
+
+export function DemoBanner() {
+ if (!isDemoMode()) return null;
+
+ return (
+ <div
+ role="status"
+ aria-live="polite"
+ className="
+ fixed top-0 left-60 right-0 z-50
+ flex items-center justify-center gap-3
+ h-9 px-4
+ text-xs font-medium
+ bg-gradient-to-r from-amber-500/15 via-amber-400/20 to-amber-500/15
+ text-amber-200
+ border-b border-amber-500/30
+ backdrop-blur-sm
+ "
+ >
+ <span aria-hidden="true" className="text-amber-300">
+ ●
+ </span>
+ <span>{demoBannerMessage()}</span>
+ <span aria-hidden="true" className="text-amber-500/60">
+ |
+ </span>
+ <a
+ href="https://github.com/cyble/AiSOC#quickstart"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="underline underline-offset-2 hover:text-amber-100 transition-colors"
+ >
+ Self-host AiSOC →
+ </a>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/landing/Footer.tsx b/apps/web/src/components/landing/Footer.tsx
index 40155bfd2..ad44958fc 100644
--- a/apps/web/src/components/landing/Footer.tsx
+++ b/apps/web/src/components/landing/Footer.tsx
@@ -5,15 +5,17 @@ const COLUMNS = [
{
label: 'Platform',
links: [
- { label: 'Features', href: '#features' },
- { label: 'How it works', href: '#architecture' },
- { label: 'MITRE coverage', href: '#mitre' },
+ { label: 'Features', href: '/#features' },
+ { label: 'How it works', href: '/#architecture' },
+ { label: 'MITRE coverage', href: '/#mitre' },
+ { label: 'Benchmark', href: '/benchmark' },
{ label: 'Console', href: '/dashboard' },
],
},
{
label: 'Open source',
links: [
+ { label: 'Why open source', href: '/why-open-source' },
{ label: 'GitHub', href: 'https://github.com/beenuar/AiSOC' },
{ label: 'Quickstart', href: 'https://github.com/beenuar/AiSOC#quickstart' },
{ label: 'Roadmap', href: 'https://github.com/beenuar/AiSOC/blob/main/ROADMAP.md' },
diff --git a/apps/web/src/components/landing/Hero.tsx b/apps/web/src/components/landing/Hero.tsx
index 72b02f2d3..45c615d7b 100644
--- a/apps/web/src/components/landing/Hero.tsx
+++ b/apps/web/src/components/landing/Hero.tsx
@@ -39,26 +39,34 @@ export function Hero() {
<h1 className="mt-6 text-balance text-5xl font-bold leading-[1.05] tracking-tight text-white md:text-6xl lg:text-7xl">
The{' '}
<span className="bg-gradient-to-r from-brand-300 via-brand-400 to-amber-300 bg-clip-text text-transparent">
- AI Security
+ auditable
</span>{' '}
- Operations Center.
+ AI SOC.
</h1>
- <p className="mt-6 max-w-xl text-lg leading-relaxed text-gray-400 md:text-xl">
- Real-time detection, autonomous triage, and MITRE ATT&CK-aware investigation —
- wired together with an AI copilot that explains every decision. Self-hosted,
- extensible, free forever.
+ <p className="mt-6 max-w-xl text-lg leading-relaxed text-gray-300 md:text-xl">
+ Every agent decision is logged step-by-step, queryable, and replayable.
+ Benchmarked publicly on a 200-incident MITRE suite. MIT-licensed and
+ self-hostable — your data never leaves your infrastructure.
</p>
<div className="mt-8 flex flex-wrap items-center gap-3">
- <Link
- href="/dashboard"
+ <a
+ href="https://demo.aisoc.dev/cases/INC-001?tab=ledger"
+ target="_blank"
+ rel="noreferrer"
className="group inline-flex items-center gap-2 rounded-lg bg-brand-500 px-5 py-3 text-sm font-semibold text-white shadow-glow-brand transition hover:bg-brand-400"
>
- Launch the console
+ Try the live demo
<svg viewBox="0 0 20 20" className="h-4 w-4 transition-transform group-hover:translate-x-0.5" fill="currentColor" aria-hidden="true">
<path d="M7.05 4.05a1 1 0 011.41 0l5 5a1 1 0 010 1.41l-5 5a1 1 0 11-1.41-1.41L11.09 10 7.05 5.46a1 1 0 010-1.41z" />
</svg>
+ </a>
+ <Link
+ href="/dashboard"
+ className="inline-flex items-center gap-2 rounded-lg border border-white/15 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-gray-200 transition hover:border-white/30 hover:bg-white/[0.08]"
+ >
+ Launch console
</Link>
<a
href="https://github.com/beenuar/AiSOC"
@@ -73,11 +81,18 @@ export function Hero() {
</a>
</div>
- {/* Quick facts row — speaks to credibility before scrolling */}
+ <p className="mt-3 text-xs text-gray-500">
+ Demo lands directly on a live agent investigation in under 60 seconds —
+ no signup, resets daily.
+ </p>
+
+ {/* Quick facts row — anchors the three pillars (auditable agent, public
+ benchmark, MIT) so the moat is visible above the fold without
+ the visitor needing to scroll into the comparison strip. */}
<dl className="mt-10 grid grid-cols-3 gap-6 border-t border-white/5 pt-8">
- <Stat label="Latency" value="< 200ms" caption="ingest → alert" />
- <Stat label="Coverage" value="14 ATT&CK" caption="tactics out of the box" />
- <Stat label="License" value="MIT" caption="audit, fork, ship" />
+ <Stat label="Agent decisions" value="100%" caption="logged + replayable" />
+ <Stat label="MITRE eval" value="200 cases" caption="public, CI-gated" />
+ <Stat label="License" value="MIT" caption="audit, fork, self-host" />
</dl>
</motion.div>
diff --git a/apps/web/src/components/landing/LandingNav.tsx b/apps/web/src/components/landing/LandingNav.tsx
index 44d9a00e6..5dfa35dc5 100644
--- a/apps/web/src/components/landing/LandingNav.tsx
+++ b/apps/web/src/components/landing/LandingNav.tsx
@@ -6,10 +6,11 @@ import clsx from 'clsx';
import { Logo } from './Logo';
const NAV_LINKS = [
- { label: 'Platform', href: '#features' },
- { label: 'How it works', href: '#architecture' },
- { label: 'MITRE', href: '#mitre' },
- { label: 'Open source', href: '#open-source' },
+ { label: 'Platform', href: '/#features' },
+ { label: 'How it works', href: '/#architecture' },
+ { label: 'MITRE', href: '/#mitre' },
+ { label: 'Why open source', href: '/why-open-source' },
+ { label: 'Benchmark', href: '/benchmark' },
];
/**
@@ -44,13 +45,13 @@ export function LandingNav() {
<nav className="hidden items-center gap-8 md:flex">
{NAV_LINKS.map((link) => (
- <a
+ <Link
key={link.href}
href={link.href}
className="text-sm font-medium text-gray-400 transition-colors hover:text-white"
>
{link.label}
- </a>
+ </Link>
))}
</nav>
@@ -98,14 +99,14 @@ export function LandingNav() {
<div className="border-t border-white/5 bg-surface-base/95 backdrop-blur-md md:hidden">
<div className="space-y-1 px-4 py-3">
{NAV_LINKS.map((link) => (
- <a
+ <Link
key={link.href}
href={link.href}
onClick={() => setOpen(false)}
className="block rounded-md px-3 py-2 text-sm text-gray-300 hover:bg-white/5 hover:text-white"
>
{link.label}
- </a>
+ </Link>
))}
<div className="flex gap-2 pt-2">
<a
diff --git a/apps/web/src/components/landing/OpenSource.tsx b/apps/web/src/components/landing/OpenSource.tsx
index d0d06e77c..1891f7c23 100644
--- a/apps/web/src/components/landing/OpenSource.tsx
+++ b/apps/web/src/components/landing/OpenSource.tsx
@@ -1,5 +1,6 @@
'use client';
+import Link from 'next/link';
import { motion } from 'framer-motion';
const PILLARS = [
@@ -72,6 +73,15 @@ export function OpenSource() {
<path d="M7.05 4.05a1 1 0 011.41 0l5 5a1 1 0 010 1.41l-5 5a1 1 0 11-1.41-1.41L11.09 10 7.05 5.46a1 1 0 010-1.41z" />
</svg>
</a>
+ <Link
+ href="/why-open-source"
+ className="inline-flex items-center gap-2 rounded-lg border border-white/15 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-gray-200 transition hover:border-white/30 hover:bg-white/[0.08]"
+ >
+ Why open source
+ <svg viewBox="0 0 20 20" className="h-3.5 w-3.5" fill="currentColor" aria-hidden="true">
+ <path d="M7.05 4.05a1 1 0 011.41 0l5 5a1 1 0 010 1.41l-5 5a1 1 0 11-1.41-1.41L11.09 10 7.05 5.46a1 1 0 010-1.41z" />
+ </svg>
+ </Link>
</div>
{/* Quickstart code */}
diff --git a/apps/web/src/lib/demoMode.ts b/apps/web/src/lib/demoMode.ts
new file mode 100644
index 000000000..cc9af507e
--- /dev/null
+++ b/apps/web/src/lib/demoMode.ts
@@ -0,0 +1,62 @@
+/**
+ * Demo-mode helpers for the hosted demo at demo.aisoc.dev.
+ *
+ * Reads `NEXT_PUBLIC_DEMO_MODE` (set by `infra/fly/web/fly.toml`) to flag-gate
+ * write actions in the UI:
+ *
+ * - `isDemoMode()` → true when the deployment is the hosted demo
+ * - `demoBannerMessage()` → the banner copy to render at the top of every page
+ * - `demoDeeplink()` → the `/cases/INC-001?tab=ledger` deeplink the
+ * README "Live Demo" button targets, so we land
+ * visitors on a hot, mid-investigation view
+ *
+ * The component side of this lives at `components/demo/DemoBanner.tsx`.
+ *
+ * Why a module instead of inlining `process.env`? Three reasons:
+ *
+ * 1. Tree-shake-friendly: pages that never call these helpers don't bundle
+ * the banner copy.
+ * 2. Single source of truth: server actions, client components, and tests
+ * all read demo state through one shim.
+ * 3. Test seam: stories/tests can monkey-patch `__setDemoModeForTests` to
+ * render the banner regardless of build env.
+ *
+ * NEXT_PUBLIC_* vars are inlined at build time by Next, so this module can
+ * safely run in both Server and Client components.
+ */
+
+const TRUTHY = new Set(['1', 'true', 'yes', 'on']);
+
+let _override: boolean | null = null;
+
+/** Returns `true` when the build is the hosted demo. */
+export function isDemoMode(): boolean {
+ if (_override !== null) return _override;
+ const v = process.env.NEXT_PUBLIC_DEMO_MODE?.toLowerCase().trim() ?? '';
+ return TRUTHY.has(v);
+}
+
+/** Banner copy shown at the top of every page in demo mode. */
+export function demoBannerMessage(): string {
+ return (
+ process.env.NEXT_PUBLIC_DEMO_BANNER?.trim() ||
+ 'Demo data resets daily at 00:00 UTC. All write actions are disabled.'
+ );
+}
+
+/**
+ * Deeplink to land visitors directly on a live, mid-investigation view.
+ * Default targets `/cases/INC-001?tab=ledger` because the seed kicks off
+ * an investigation against `INC-001` and the ledger tab streams events.
+ */
+export function demoDeeplink(): string {
+ return process.env.NEXT_PUBLIC_DEMO_DEEPLINK?.trim() || '/cases/INC-001?tab=ledger';
+}
+
+/**
+ * Test-only escape hatch. **Do not call from product code.** Stories and unit
+ * tests use this to render the banner without forking `process.env`.
+ */
+export function __setDemoModeForTests(value: boolean | null): void {
+ _override = value;
+}
diff --git a/infra/coolify/README.md b/infra/coolify/README.md
new file mode 100644
index 000000000..fee6aea8d
--- /dev/null
+++ b/infra/coolify/README.md
@@ -0,0 +1,232 @@
+# AiSOC on Coolify
+
+Self-host AiSOC on your own VPS using [Coolify](https://coolify.io) —
+the open-source Heroku/Render alternative. **Free**, runs on any Linux
+box with 4GB+ RAM.
+
+## Why Coolify
+
+If you've already self-hosted Coolify (e.g. on a $5/mo Hetzner box, a
+homelab Proxmox VM, or an old laptop), AiSOC drops in via the existing
+[`docker-compose.yml`](../../docker-compose.yml). No platform-specific
+config needed — Coolify reads compose files natively.
+
+This is the deploy path with the **lowest ongoing cost** ($5-10/mo for
+the underlying VPS, $0 for Coolify itself) and the **highest
+flexibility** (you control the host, the network, the storage, the
+backups).
+
+## What you'll deploy
+
+The full AiSOC stack — including the optional storage tier (Kafka,
+ClickHouse, OpenSearch, Neo4j, Qdrant) — because Coolify runs your
+docker-compose unchanged. If you want the lean profile instead, comment
+out those services in your compose file before importing.
+
+| Profile | RAM needed | Use case |
+|---|---|---|
+| Lean (api + agents + web + realtime + Postgres + Redis) | 4 GB | Personal eval, small SOC pilots |
+| Full (lean + Kafka + ClickHouse + OpenSearch + Neo4j + Qdrant) | 16 GB | Production-grade, full feature set |
+
+## Prerequisites
+
+1. A Linux VPS with 4 GB+ RAM (or 16 GB+ for the full stack). [Hetzner
+ CPX21](https://www.hetzner.com/cloud) (€5.83/mo) is a good 4 GB
+ option; CPX41 (€16.06/mo) handles the full stack.
+2. A domain pointed at the VPS's public IP (Cloudflare, Namecheap, etc).
+3. [Coolify installed](https://coolify.io/docs/installation) on the VPS:
+
+ ```bash
+ curl -fsSL https://cdn.coollabs.io/coolify/install.sh | bash
+ ```
+
+ Coolify gives you a UI at `http://<vps-ip>:8000` after ~3 minutes.
+
+## Deploy walkthrough
+
+### Step 1: Create a new project
+
+Coolify dashboard → **+ New Project** → name it `aisoc` → **Create**.
+
+### Step 2: Add AiSOC as a Docker Compose resource
+
+1. Inside the project: **+ New Resource** → **Docker Compose Empty**.
+2. **Source**: choose **Public Repository**.
+3. **Repository URL**: `https://github.com/beenuar/AiSOC`
+4. **Branch**: `main`
+5. **Base Directory**: `/` (the repo root, where `docker-compose.yml` lives)
+6. **Docker Compose File Location**: `docker-compose.yml`
+7. Click **Save & Continue**.
+
+### Step 3: Configure environment
+
+Coolify shows the env vars detected from `docker-compose.yml`. Set:
+
+```
+# Demo / safety flags (recommended for first deploy)
+AISOC_DEMO_MODE=true
+AISOC_DEMO_TENANT=demo
+ENVIRONMENT=demo
+
+# Auto-generated by Coolify if you click "Generate"
+JWT_SECRET=<click Generate>
+POSTGRES_PASSWORD=<click Generate>
+
+# Public URLs — replace with your domain
+NEXT_PUBLIC_API_URL=https://api.aisoc.example.com
+NEXT_PUBLIC_WS_URL=wss://realtime.aisoc.example.com
+NEXT_PUBLIC_AISOC_DEMO_MODE=true
+NEXT_PUBLIC_AISOC_DEMO_DEEPLINK=/cases/INC-001?tab=ledger
+```
+
+Optional (only if you want LLM-backed agents instead of the
+deterministic demo agent):
+
+```
+OPENAI_API_KEY=sk-...
+ANTHROPIC_API_KEY=sk-ant-...
+```
+
+### Step 4: Wire up domains
+
+For each public-facing service (`api`, `web`, `realtime`):
+
+1. Coolify → service settings → **Domain**: enter
+ `api.aisoc.example.com` (or whichever subdomain).
+2. **Generate Certificate** — Coolify uses Caddy under the hood to issue
+ Let's Encrypt certs automatically.
+3. Make sure your DNS A record for `*.aisoc.example.com` points at the
+ VPS IP.
+
+The internal services (`agents`, `postgres`, `redis`, `kafka`,
+`clickhouse`, etc.) don't need domains — they reach each other over
+Coolify's internal Docker network.
+
+### Step 5: Deploy
+
+Click **Deploy**. Coolify:
+
+1. Pulls the repo.
+2. Reads `docker-compose.yml` and spins up the services in dependency
+ order.
+3. Issues TLS certs for the domains you set.
+4. Starts streaming logs in the dashboard.
+
+First deploy takes ~10-15 minutes (Docker image pulls + first build).
+
+### Step 6: Pre-warm the demo
+
+SSH into the VPS and run the seed inside the api container:
+
+```bash
+docker exec -it $(docker ps -qf "name=aisoc-api") \
+ python scripts/demo_seed.py --reset --kickoff-investigation
+```
+
+Open `https://web.aisoc.example.com` — demo banner shows, deeplink
+lands on a pre-seeded incident.
+
+## Disabling optional services
+
+If you're on a 4 GB VPS, comment out these services in
+`docker-compose.yml` *before* importing into Coolify (Coolify reads the
+file as-is):
+
+```yaml
+# Comment out for the lean profile:
+# kafka:
+# zookeeper:
+# clickhouse:
+# opensearch:
+# neo4j:
+# qdrant:
+```
+
+And set the corresponding `AISOC_DISABLE_*=true` flags on the api and
+agents services. The api degrades gracefully — alerts work, cases work,
+the agent investigates, and the UI hides features that depend on the
+disabled storage tier.
+
+## Daily reset (optional)
+
+Coolify has scheduled tasks built in. To rotate the demo daily:
+
+1. Project → **+ New Resource** → **Service** → **Schedule**.
+2. **Command**: `docker exec aisoc-api python scripts/demo_seed.py --reset --kickoff-investigation`
+3. **Cron**: `0 0 * * *` (daily at 00:00 UTC).
+4. **Save**.
+
+## Backups (recommended)
+
+Coolify ships native S3-compatible backups for Postgres. Project →
+Postgres service → **Backups** tab → configure your S3 bucket → enable
+daily snapshots. ~$1/mo for the storage, saves you from a corrupted
+demo on a busy week.
+
+## Updates
+
+Coolify watches the GitHub repo by default. When `beenuar/AiSOC` ships
+a new commit on `main`:
+
+- **Auto-deploy** (default): Coolify pulls and redeploys within minutes.
+- **Manual**: turn off auto-deploy in service settings, click **Deploy**
+ when you want to update.
+
+For a forked self-hosted setup, point Coolify at *your* fork instead so
+you control when updates land.
+
+## Why Coolify over raw `docker-compose up`
+
+You absolutely *can* just SSH in and run `docker-compose up -d`. Coolify
+adds:
+
+- TLS via Let's Encrypt without configuring Caddy/Nginx by hand.
+- Web UI for env var management (no editing `.env` over SSH).
+- Auto-deploy on git push.
+- Native backups.
+- Resource graphs (CPU, RAM, disk per container).
+- One-click rollback.
+- Multi-project isolation (run AiSOC + your other side projects on the
+ same box without port conflicts).
+
+For a personal eval deploy, plain `docker-compose` is fine. For
+"running this for my team", Coolify is worth the 3 minutes of setup.
+
+## Troubleshooting
+
+### "Out of memory" during deploy
+
+You're on a 4 GB box trying to run the full stack (16 GB needed). Either
+upgrade the VPS or comment out the optional services as described above.
+
+### "Cannot get TLS certificate"
+
+DNS hasn't propagated yet, or the A record points to the wrong IP. Wait
+5 min, run `dig api.aisoc.example.com` and confirm it resolves to the
+VPS IP, then retry the cert generation in the Coolify UI.
+
+### "WebSocket connection failed" in browser console
+
+Check that `NEXT_PUBLIC_WS_URL` uses `wss://` (not `ws://`) — once you
+have TLS, plain `ws://` is blocked by browsers. The realtime service
+also needs the **WebSocket** toggle enabled in Coolify's service
+settings → **Network**.
+
+### Web service shows "demo banner" but deeplink doesn't work
+
+Run the seed (Step 6 above) — if it never executed, INC-001 doesn't
+exist in Postgres yet, so the deeplink 404s. The seed is *not*
+auto-triggered on Coolify the way it is on the Fly demo.
+
+## Files
+
+```
+infra/coolify/
+└── README.md — this file (the only Coolify-specific artifact)
+```
+
+The actual deployment uses [`docker-compose.yml`](../../docker-compose.yml)
+unchanged.
+
+For the full deployment philosophy and platform comparison, see the
+[main README](../../README.md#-deploy-in-one-click).
diff --git a/infra/fly/README.md b/infra/fly/README.md
new file mode 100644
index 000000000..c25bee07b
--- /dev/null
+++ b/infra/fly/README.md
@@ -0,0 +1,217 @@
+# AiSOC Hosted Demo (Fly.io)
+
+This directory contains the infrastructure-as-code for the public demo at
+**[demo.aisoc.dev](https://demo.aisoc.dev)**, deployed on Fly.io.
+
+## Goal
+
+> A visitor clicks the README's "Live Demo" button and sees an AiSOC agent
+> mid-investigation in **under 60 seconds**, with the full agent decision
+> ledger streaming live — no signup, no install.
+
+That sub-60s **time-to-first-investigation (TTFI)** is the headline number
+this stack is engineered for.
+
+## Architecture
+
+```
+ demo.aisoc.dev (TLS via Fly certs)
+ │
+ ▼
+ ┌──────────────────────────────────┐
+ │ aisoc-demo-web (Next.js) │ public
+ │ shared-cpu-1x · 1GB · min=1 │
+ └──────────────────────────────────┘
+ │ │
+ https│ wss │
+ ▼ ▼
+ ┌──────────────────────┐ ┌──────────────────────┐
+ │ aisoc-demo-api │ │ aisoc-demo-realtime │
+ │ (FastAPI) │ │ (WebSocket) │
+ │ shared-cpu-1x · 1GB │ │ shared-cpu-1x · 0.5GB│
+ │ min=1, demo middleware│ │ auto_stop=off (WS) │
+ └──────────────────────┘ └──────────────────────┘
+ │ │
+ └───────┬────────┘
+ ▼
+ ┌──────────────────────────────────┐
+ │ aisoc-demo-agents (LangGraph) │
+ │ shared-cpu-2x · 2GB · min=1 │
+ │ AISOC_AGENT_MODE=deterministic │
+ └──────────────────────────────────┘
+ │
+ ┌──────────────┴──────────────┐
+ ▼ ▼
+ ┌────────────────────────┐ ┌──────────────────────┐
+ │ Fly Postgres │ │ Upstash Redis │
+ │ aisoc-demo-postgres │ │ aisoc-demo-redis │
+ │ dev plan, 3GB volume │ │ Free plan │
+ └────────────────────────┘ └──────────────────────┘
+
+ ┌──────────────────────────────────────────────┐
+ │ aisoc-demo-seed-cron (scheduled machine) │ no public traffic
+ │ Lives on the aisoc-demo-api app, runs │
+ │ daily at 00:00 UTC using the api image: │
+ │ 1. wipe demo tenant │
+ │ 2. seed canonical alerts/cases │
+ │ 3. POST /investigate INC-001 │
+ └──────────────────────────────────────────────┘
+```
+
+What's intentionally **not** here, to keep the demo lean:
+
+| Component | Status | Why |
+|-------------|---------------|-----------------------------------------------------|
+| Kafka | disabled | Realtime uses Redis pub/sub on the demo path |
+| ClickHouse | disabled | No analytics queries in the demo flow |
+| OpenSearch | disabled | Detection rules ship with synthetic match payloads |
+| Neo4j | disabled | Attack graph isn't on the canonical demo path |
+| Qdrant | disabled | KB lookup uses the in-image Postgres + pg_trgm path |
+
+These get re-enabled the moment a self-hoster wants the full stack — see
+the root `docker-compose.yml` and `services/*/Dockerfile`.
+
+## Files
+
+```
+infra/fly/
+├── README.md — this file
+├── fly-demo-deploy.sh — orchestrator: provisions DB, deploys 4 apps, runs seed
+├── api/fly.toml — FastAPI core API (also hosts the seeder process)
+├── agents/fly.toml — LangGraph orchestrator + investigator agents
+├── web/fly.toml — Next.js console (public)
+└── realtime/fly.toml — WebSocket fanout
+```
+
+The seeder is **not** a separate app. It ships inside the api image as
+`python -m app.scripts.demo_seed`, which lets us run it two ways without
+maintaining a fifth Dockerfile or Fly app:
+
+| When | How |
+|--------------------------|--------------------------------------------------------------------------------------|
+| Post-deploy (bootstrap) | `flyctl ssh console -a aisoc-demo-api -C "python -m app.scripts.demo_seed --reset --kickoff-investigation"` runs once on a live api machine, populating Postgres and starting the canonical investigation in ~30s. |
+| Daily refresh (00:00 UTC)| A scheduled Fly machine on the `aisoc-demo-api` app, named `aisoc-demo-seed-cron`, boots from the same api image, runs the same command, and exits. |
+| Local recovery | `python scripts/demo_seed.py --reset` from the repo root — the shim re-execs the canonical module against your `docker-compose` stack. |
+
+The canonical implementation lives in
+[`services/api/app/scripts/demo_seed.py`](../../services/api/app/scripts/demo_seed.py);
+[`scripts/demo_seed.py`](../../scripts/demo_seed.py) is a thin shim for repo-root invocation.
+
+The seed flow is the secret sauce for the TTFI budget:
+
+```
+00:00 UTC ┌────────────────────────────────────────────────────┐
+ │ 1. scheduled machine boots from api image │
+ │ 2. runs `python -m app.scripts.demo_seed --reset │
+ │ --kickoff-investigation` │
+ │ 3. POSTs /api/v1/cases/INC-001/investigate │
+ │ 4. agents.internal streams events → realtime │
+ │ 5. realtime broadcasts → web WS connections │
+ │ Investigation completes within 30-90s. │
+ └────────────────────────────────────────────────────┘
+
+T+anytime ┌────────────────────────────────────────────────────┐
+ │ Visitor lands at /cases/INC-001?tab=ledger │
+ │ - case is already CREATED │
+ │ - investigation_run is COMPLETED or RUNNING │
+ │ - ledger has 20-50 events ready to stream │
+ │ Time-to-first-investigation: 0s (already running). │
+ └────────────────────────────────────────────────────┘
+```
+
+## First-time setup
+
+```bash
+# 1. Install flyctl + auth
+brew install flyctl
+flyctl auth login
+
+# 2. Create org "aisoc" if it doesn't exist
+flyctl orgs create aisoc
+
+# 3. Reserve app names (one-time)
+for app in aisoc-demo-api aisoc-demo-agents aisoc-demo-web \
+ aisoc-demo-realtime; do
+ flyctl apps create "$app" --org aisoc
+done
+
+# 4. Provision Postgres + Upstash + deploy everything
+./infra/fly/fly-demo-deploy.sh --provision
+
+# 5. Add DNS:
+# demo.aisoc.dev CNAME aisoc-demo-web.fly.dev
+```
+
+## Routine deploy
+
+```bash
+# Push your branch, then:
+./infra/fly/fly-demo-deploy.sh
+```
+
+Re-running is idempotent. Already-provisioned Postgres / Redis / cert add
+calls fail-soft.
+
+## Demo mode at runtime
+
+The `AISOC_DEMO_MODE` flag is set on every Fly app's `[env]` block. This
+flag drives two pieces of behavior:
+
+1. **API middleware (`services/api/app/middleware/demo_mode.py`)**
+ Returns 403 for non-allowlisted writes (POST/PUT/PATCH/DELETE) and stamps
+ `X-AiSOC-Demo: true` plus `X-AiSOC-Demo-Banner` headers on every response.
+ Allowlisted writes: auth flows, `/cases/INC-001/investigate`, alert ack.
+
+2. **Web banner (`apps/web/src/components/demo/DemoBanner.tsx`)**
+ Renders a fixed amber strip at the top of every authenticated page with
+ the daily-reset notice and a "Self-host AiSOC →" link.
+
+Both layers read from environment variables surfaced through the
+`fly.toml` `[env]` blocks, so flipping any AiSOC self-hoster into demo
+mode (e.g., for a customer presentation) is a one-flag operation.
+
+## Smoke checks
+
+```bash
+# API liveness
+curl -sf https://aisoc-demo-api.fly.dev/health
+
+# Demo headers visible
+curl -sI https://aisoc-demo-api.fly.dev/api/v1/cases | grep -i x-aisoc
+
+# Mutating writes blocked
+curl -si -X POST https://aisoc-demo-api.fly.dev/api/v1/cases | head -3
+# expect: HTTP/2 403 …
+
+# Visitor flow
+open https://demo.aisoc.dev/cases/INC-001?tab=ledger
+```
+
+## Troubleshooting
+
+| Symptom | Likely cause / fix |
+|---------------------------------------------|----------------------------------------------------|
+| `flyctl deploy` hangs on builder | Nuke remote builder: `flyctl builders destroy` |
+| API 503 on first hit | Cold start; `min_machines_running=1` should fix |
+| Web shows "demo data resets" but writes work| API's `AISOC_DEMO_MODE` not set; redeploy api |
+| INC-001 case missing | Re-run seed: `flyctl ssh console -a aisoc-demo-api -C "python -m app.scripts.demo_seed --reset --kickoff-investigation"` |
+| Daily seed cron not firing | Verify the scheduled machine: `flyctl machine list -a aisoc-demo-api` (look for `aisoc-demo-seed-cron`) |
+| WS disconnects in 30s | Realtime `auto_stop_machines = "off"` — verify fly.toml |
+| Cert pending | `flyctl certs check demo.aisoc.dev --app aisoc-demo-web` |
+
+## Cost envelope
+
+Target: **<$30/mo** for the running demo so it's sustainable on a single
+maintainer's budget.
+
+| Resource | Monthly cost (est.) |
+|-------------------------------------------|-----------------------------|
+| 3 × shared-cpu-1x machines (api, web, rt) | ~$6 (with auto_stop=stop) |
+| 1 × shared-cpu-2x agents | ~$5 |
+| 1 × scheduled seed machine (~1min/day) | <$0.10 |
+| Fly Postgres (dev, 3GB) | ~$2 |
+| Upstash Redis (Free) | $0 |
+| Outbound bandwidth (~50GB) | ~$1 |
+| **Total** | **~$14/mo** |
+
+If demo traffic exceeds 50GB/mo we'll cache the seed snapshot on Cloudflare R2.
diff --git a/infra/fly/agents/fly.toml b/infra/fly/agents/fly.toml
new file mode 100644
index 000000000..797c26d11
--- /dev/null
+++ b/infra/fly/agents/fly.toml
@@ -0,0 +1,52 @@
+# ──────────────────────────────────────────────────────────────────────────────
+# AiSOC Demo - Agents service (LangGraph orchestrator + investigator)
+#
+# Deployed at: https://aisoc-demo-agents.fly.dev
+# Internal name: aisoc-demo-agents.internal:8084
+#
+# Reads: Postgres, Redis, KB (in-image), MITRE ATT&CK JSON (in-image)
+# Writes: investigation_runs, investigation_events, investigation_artifacts
+#
+# Note: in demo mode the agents call a deterministic offline pipeline
+# (no OPENAI_API_KEY required). Operators can enable LLM-backed mode by
+# setting OPENAI_API_KEY as a Fly secret.
+# ──────────────────────────────────────────────────────────────────────────────
+
+app = "aisoc-demo-agents"
+primary_region = "iad"
+kill_signal = "SIGINT"
+kill_timeout = "10s" # agent runs may need to flush ledger writes
+
+# Dockerfile path is relative to the build context (= services/agents/).
+# Deploy script runs `flyctl deploy` from that dir.
+[build]
+ dockerfile = "Dockerfile"
+
+[env]
+ ENVIRONMENT = "demo"
+ LOG_LEVEL = "info"
+ PORT = "8084"
+ AISOC_DEMO_MODE = "true"
+ CORE_API_URL = "http://aisoc-demo-api.internal:8000"
+ # In demo mode, fall back to deterministic pipeline if no key set
+ AISOC_AGENT_MODE = "deterministic"
+ ATTCK_DATA_PATH = "/app/data/enterprise-attack.json"
+
+[http_service]
+ internal_port = 8084
+ force_https = true
+ auto_stop_machines = "stop"
+ auto_start_machines = true
+ min_machines_running = 1
+ processes = ["app"]
+
+ [[http_service.checks]]
+ grace_period = "30s"
+ interval = "15s"
+ method = "GET"
+ timeout = "5s"
+ path = "/health"
+
+[[vm]]
+ size = "shared-cpu-2x" # agent runs are CPU-bound during burst
+ memory_mb = 2048
diff --git a/infra/fly/api/fly.toml b/infra/fly/api/fly.toml
new file mode 100644
index 000000000..c0ae9e5e6
--- /dev/null
+++ b/infra/fly/api/fly.toml
@@ -0,0 +1,60 @@
+# ──────────────────────────────────────────────────────────────────────────────
+# AiSOC Demo - API service (FastAPI)
+#
+# Deployed at: https://aisoc-demo-api.fly.dev
+# Internal name: aisoc-demo-api.internal:8000
+#
+# Reads: Postgres (Fly managed), Redis (Upstash via Fly), demo tenant
+# Writes: Postgres (cases, alerts, runs, events)
+# ──────────────────────────────────────────────────────────────────────────────
+
+app = "aisoc-demo-api"
+primary_region = "iad" # us-east, lowest latency to demo.aisoc.dev
+kill_signal = "SIGINT"
+kill_timeout = "5s"
+
+# Dockerfile path is relative to the build context (= the service source dir).
+# The deploy script runs `flyctl deploy` from `services/api/` so `COPY . .`
+# in the Dockerfile sees the API source. See infra/fly/fly-demo-deploy.sh.
+[build]
+ dockerfile = "Dockerfile"
+
+[env]
+ ENVIRONMENT = "demo"
+ LOG_LEVEL = "info"
+ PORT = "8000"
+ # Demo gates: write actions return 403, mutating endpoints become read-only
+ AISOC_DEMO_MODE = "true"
+ # Tenant rotation runs daily; the seeder writes the canonical INC-001 case
+ AISOC_DEMO_TENANT = "demo"
+ # Disable optional integrations (no Kafka/ClickHouse/OpenSearch on demo)
+ AISOC_DISABLE_KAFKA = "true"
+ AISOC_DISABLE_CLICKHOUSE = "true"
+ AISOC_DISABLE_OPENSEARCH = "true"
+ AISOC_DISABLE_NEO4J = "true"
+ AISOC_DISABLE_QDRANT = "true"
+ # The demo_seed entrypoint runs inside this container (post-deploy via
+ # `flyctl ssh console -C "python -m app.scripts.demo_seed …"` and via a
+ # daily cron machine). It needs to reach the API locally and the agents
+ # app over Fly's internal 6PN DNS.
+ CORE_API_URL = "http://localhost:8000"
+ AGENTS_API_URL = "http://aisoc-demo-agents.internal:8084"
+
+[http_service]
+ internal_port = 8000
+ force_https = true
+ auto_stop_machines = "stop"
+ auto_start_machines = true
+ min_machines_running = 1 # keep one warm for sub-60s TTFI
+ processes = ["app"]
+
+ [[http_service.checks]]
+ grace_period = "20s"
+ interval = "15s"
+ method = "GET"
+ timeout = "5s"
+ path = "/health"
+
+[[vm]]
+ size = "shared-cpu-1x"
+ memory_mb = 1024
diff --git a/infra/fly/fly-demo-deploy.sh b/infra/fly/fly-demo-deploy.sh
new file mode 100755
index 000000000..10d591e0c
--- /dev/null
+++ b/infra/fly/fly-demo-deploy.sh
@@ -0,0 +1,219 @@
+#!/usr/bin/env bash
+# ──────────────────────────────────────────────────────────────────────────────
+# fly-demo-deploy.sh
+#
+# Deploys the full AiSOC live demo stack to Fly.io behind demo.aisoc.dev.
+# Idempotent: safe to re-run after partial failures.
+#
+# Usage:
+# ./infra/fly/fly-demo-deploy.sh # full deploy
+# ./infra/fly/fly-demo-deploy.sh --provision # also creates Postgres + Upstash
+# ./infra/fly/fly-demo-deploy.sh --skip-seed # don't run seeder after deploy
+#
+# Prereqs:
+# - flyctl installed and authed (https://fly.io/docs/hands-on/install-flyctl/)
+# - fly org "aisoc" exists (fly orgs list)
+# - DNS for demo.aisoc.dev pointed at aisoc-demo-web (CNAME or A record)
+#
+# Architecture:
+#
+# ┌────────────────┐ ┌────────────────┐ ┌────────────────┐
+# │ demo.aisoc.dev │──→ │ web (Next.js) │──→ │ api (FastAPI) │
+# └────────────────┘ └────────────────┘ └────────────────┘
+# │ │
+# ▼ ▼
+# ┌────────────────┐ ┌────────────────┐
+# │ realtime (WS) │ │ agents (LangG) │
+# └────────────────┘ └────────────────┘
+# │ │
+# └─────────┬─────────────┘
+# ▼
+# ┌────────────────────────────┐
+# │ Fly Postgres + Upstash Redis│
+# └────────────────────────────┘
+#
+# Time-to-first-investigation budget: <60s from the demo.aisoc.dev click.
+# The seed job pre-warms a running investigation so the deeplink lands
+# inside its TTFI budget regardless of cold-start.
+# ──────────────────────────────────────────────────────────────────────────────
+
+set -euo pipefail
+
+PROVISION=false
+SKIP_SEED=false
+ORG="${FLY_ORG:-aisoc}"
+REGION="${FLY_REGION:-iad}"
+
+for arg in "$@"; do
+ case "$arg" in
+ --provision) PROVISION=true ;;
+ --skip-seed) SKIP_SEED=true ;;
+ -h|--help)
+ grep '^#' "$0" | head -n 50
+ exit 0
+ ;;
+ esac
+done
+
+# Resolve repo root and infra paths up front so all build contexts are absolute.
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+INFRA_DIR="$SCRIPT_DIR"
+REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+cd "$REPO_ROOT"
+
+log() { printf "\033[1;36m[fly-demo]\033[0m %s\n" "$*"; }
+err() { printf "\033[1;31m[fly-demo]\033[0m %s\n" "$*" >&2; }
+
+require() {
+ if ! command -v "$1" >/dev/null 2>&1; then
+ err "required command not found: $1"
+ exit 1
+ fi
+}
+
+require flyctl
+require git
+
+# ───────────────────────────────── provision ─────────────────────────────────
+
+if $PROVISION; then
+ log "provisioning aisoc-demo-postgres (Fly managed Postgres, dev plan)…"
+ flyctl postgres create \
+ --name aisoc-demo-postgres \
+ --org "$ORG" \
+ --region "$REGION" \
+ --vm-size shared-cpu-1x \
+ --volume-size 3 \
+ --initial-cluster-size 1 || log "(already provisioned)"
+
+ log "provisioning Upstash Redis (free tier)…"
+ flyctl redis create \
+ --name aisoc-demo-redis \
+ --org "$ORG" \
+ --region "$REGION" \
+ --no-replicas \
+ --plan Free || log "(already provisioned)"
+fi
+
+# ─────────────────────────────── deploy stack ────────────────────────────────
+# Order matters:
+# 1. api — others depend on it via .internal DNS
+# 2. agents — api caller
+# 3. realtime — web caller
+# 4. web — last; serves traffic at demo.aisoc.dev
+#
+# The seeder is *not* a separate app — it ships inside the api image as
+# `python -m app.scripts.demo_seed`, and we invoke it via `flyctl ssh
+# console` post-deploy + a scheduled machine on the api app for the daily
+# cron. This avoids a duplicate Dockerfile + the cost of a fifth Fly app
+# whose only job is to run a 30-second script.
+
+# deploy_app <fly-app-name> <fly.toml subdir under infra/fly/> <build-context dir>
+#
+# Why we cd into the build context: the existing service Dockerfiles (api,
+# agents, web, realtime) were written assuming the build context is the
+# service source dir (they do `COPY pyproject.toml ./` and `COPY . .`).
+# Fly's build context defaults to the *current working directory* of `flyctl
+# deploy`, so we cd there before invoking it. The fly.toml is referenced by
+# absolute path so flyctl still finds it.
+deploy_app() {
+ local name="$1" toml_subdir="$2" build_ctx="$3"
+ local toml="$INFRA_DIR/$toml_subdir/fly.toml"
+ log "deploying $name (context=$build_ctx, config=$toml)…"
+ if [[ ! -f "$toml" ]]; then
+ err "fly.toml not found: $toml"
+ exit 1
+ fi
+ if [[ ! -d "$REPO_ROOT/$build_ctx" ]]; then
+ err "build context dir not found: $build_ctx"
+ exit 1
+ fi
+ ( cd "$REPO_ROOT/$build_ctx" && \
+ flyctl deploy --remote-only --config "$toml" --app "$name" )
+}
+
+attach_pg() {
+ local name="$1"
+ log "attaching aisoc-demo-postgres → $name (sets DATABASE_URL secret)…"
+ flyctl postgres attach aisoc-demo-postgres --app "$name" 2>/dev/null || log "($name already attached)"
+}
+
+attach_redis() {
+ local name="$1"
+ log "attaching aisoc-demo-redis → $name (sets REDIS_URL secret)…"
+ # Upstash flow exports REDIS_URL on attach
+ flyctl redis attach aisoc-demo-redis --app "$name" 2>/dev/null || log "($name already attached)"
+}
+
+# 1. api — build context = services/api/
+attach_pg aisoc-demo-api
+attach_redis aisoc-demo-api
+deploy_app aisoc-demo-api api services/api
+
+# 2. agents — build context = services/agents/
+attach_pg aisoc-demo-agents
+attach_redis aisoc-demo-agents
+deploy_app aisoc-demo-agents agents services/agents
+
+# 3. realtime — build context = services/realtime/
+attach_redis aisoc-demo-realtime
+deploy_app aisoc-demo-realtime realtime services/realtime
+
+# 4. web (public) — build context = repo root (Next.js Dockerfile pulls
+# pnpm-workspace.yaml + packages/* from there).
+deploy_app aisoc-demo-web web .
+
+# 4b. attach demo.aisoc.dev cert
+log "ensuring TLS cert for demo.aisoc.dev…"
+flyctl certs add demo.aisoc.dev --app aisoc-demo-web 2>/dev/null || log "(cert already issued)"
+
+# 5. seed (in-process on the api app)
+#
+# Two execution paths:
+# - post-deploy bootstrap (now): SSH into a running api machine and run
+# the seeder once so the demo lands hot for the very next visitor.
+# - daily refresh (cron): a scheduled Fly machine on aisoc-demo-api
+# boots from the same image, runs the seeder, exits.
+#
+# Both paths execute `python -m app.scripts.demo_seed`; the canonical
+# implementation lives in services/api/app/scripts/demo_seed.py.
+if ! $SKIP_SEED; then
+ log "running seed bootstrap inside aisoc-demo-api (one-shot via ssh)…"
+ # `ssh console -C` runs a single command on a live machine and exits. We
+ # accept the slight CPU cost on the traffic-serving machine because (a)
+ # the seed is mostly I/O-bound, (b) it's a 30s burst, and (c) it lets us
+ # reuse a fully-warm container instead of cold-booting another machine.
+ flyctl ssh console \
+ --app aisoc-demo-api \
+ --command "python -m app.scripts.demo_seed --reset --kickoff-investigation" \
+ || err "(seed bootstrap failed; demo will be cold until daily cron runs)"
+
+ log "ensuring daily seed cron at 00:00 UTC on aisoc-demo-api…"
+ # Fly scheduled machines fire on the chosen interval and exit cleanly.
+ # `--schedule daily` runs once per UTC day. Without an explicit image arg
+ # flyctl resolves to the app's currently-deployed image (i.e. the api
+ # image we just shipped above), so the seeder always runs against the
+ # same code as the live API. Re-running the deploy is safe: if a daily
+ # machine already exists, we silently skip (Fly returns non-zero on a
+ # name collision).
+ flyctl machine run \
+ --app aisoc-demo-api \
+ --region "$REGION" \
+ --schedule daily \
+ --vm-size shared-cpu-1x \
+ --vm-memory 512 \
+ --name aisoc-demo-seed-cron \
+ -- python -m app.scripts.demo_seed --reset --kickoff-investigation \
+ 2>/dev/null || log "(daily seed cron already configured)"
+fi
+
+log "deploy complete."
+log ""
+log " Public: https://demo.aisoc.dev"
+log " Web: https://aisoc-demo-web.fly.dev"
+log " API: https://aisoc-demo-api.fly.dev/docs"
+log " Realtime: wss://aisoc-demo-realtime.fly.dev"
+log ""
+log "Smoke test:"
+log " curl -sf https://aisoc-demo-api.fly.dev/health"
+log " open https://demo.aisoc.dev/cases/INC-001?tab=ledger"
diff --git a/infra/fly/realtime/fly.toml b/infra/fly/realtime/fly.toml
new file mode 100644
index 000000000..1b6d44a37
--- /dev/null
+++ b/infra/fly/realtime/fly.toml
@@ -0,0 +1,49 @@
+# ──────────────────────────────────────────────────────────────────────────────
+# AiSOC Demo - Realtime service (WebSocket)
+#
+# Deployed at: https://aisoc-demo-realtime.fly.dev
+# Internal name: aisoc-demo-realtime.internal:4000
+# Public WS: wss://aisoc-demo-realtime.fly.dev
+#
+# The web frontend connects directly over wss://. In demo mode the realtime
+# service multiplexes Redis pub/sub for "alert created" / "investigation event"
+# fanout. Kafka is intentionally disabled to keep the demo lean.
+# ──────────────────────────────────────────────────────────────────────────────
+
+app = "aisoc-demo-realtime"
+primary_region = "iad"
+kill_signal = "SIGINT"
+kill_timeout = "5s"
+
+# Dockerfile path is relative to the build context (= services/realtime/).
+# Deploy script runs `flyctl deploy` from that dir.
+[build]
+ dockerfile = "Dockerfile"
+
+[env]
+ NODE_ENV = "production"
+ PORT = "4000"
+ AISOC_DEMO_MODE = "true"
+ AISOC_DISABLE_KAFKA = "true"
+ # WebSocket origin allowlist: only the demo web app
+ ALLOWED_ORIGINS = "https://demo.aisoc.dev,https://aisoc-demo-web.fly.dev"
+
+[http_service]
+ internal_port = 4000
+ force_https = true
+ # Realtime needs to stay up - sleeping kills WS connections
+ auto_stop_machines = "off"
+ auto_start_machines = true
+ min_machines_running = 1
+ processes = ["app"]
+
+ [[http_service.checks]]
+ grace_period = "20s"
+ interval = "15s"
+ method = "GET"
+ timeout = "5s"
+ path = "/health"
+
+[[vm]]
+ size = "shared-cpu-1x"
+ memory_mb = 512
diff --git a/infra/fly/web/fly.toml b/infra/fly/web/fly.toml
new file mode 100644
index 000000000..2faced4c6
--- /dev/null
+++ b/infra/fly/web/fly.toml
@@ -0,0 +1,56 @@
+# ──────────────────────────────────────────────────────────────────────────────
+# AiSOC Demo - Web (Next.js)
+#
+# Deployed at: https://aisoc-demo-web.fly.dev
+# Public domain: https://demo.aisoc.dev (configured via Fly certs)
+#
+# This is the only public-facing service. The api/agents/realtime fly apps
+# only expose internal addressing through the .internal DNS to keep the
+# demo's blast radius small.
+#
+# Reads: api (HTTP), realtime (WSS)
+# ──────────────────────────────────────────────────────────────────────────────
+
+app = "aisoc-demo-web"
+primary_region = "iad"
+kill_signal = "SIGINT"
+kill_timeout = "5s"
+
+# Web Dockerfile expects the *monorepo root* as build context (it COPYs
+# pnpm-workspace.yaml + packages/* to resolve workspace deps). The deploy
+# script runs `flyctl deploy` from the repo root, and we point at the
+# Dockerfile via its repo-relative path.
+[build]
+ dockerfile = "apps/web/Dockerfile"
+
+[env]
+ NODE_ENV = "production"
+ PORT = "3000"
+ NEXT_PUBLIC_DEMO_MODE = "true"
+ # Public URLs: web is public, api/realtime are accessed through public Fly hostnames
+ # so the browser can reach them. In a self-hosted setup these would be private.
+ NEXT_PUBLIC_API_URL = "https://aisoc-demo-api.fly.dev"
+ NEXT_PUBLIC_WS_URL = "wss://aisoc-demo-realtime.fly.dev"
+ NEXT_PUBLIC_DEMO_RESET = "daily-utc-0000"
+ NEXT_PUBLIC_DEMO_BANNER = "Demo data resets daily at 00:00 UTC. All write actions are disabled."
+ # Default landing in demo mode: pre-seeded incident with running investigation
+ NEXT_PUBLIC_DEMO_DEEPLINK = "/cases/INC-001?tab=ledger"
+
+[http_service]
+ internal_port = 3000
+ force_https = true
+ auto_stop_machines = "stop"
+ auto_start_machines = true
+ min_machines_running = 1 # keep warm to hit sub-60s time-to-first-investigation
+ processes = ["app"]
+
+ [[http_service.checks]]
+ grace_period = "20s"
+ interval = "15s"
+ method = "GET"
+ timeout = "5s"
+ path = "/api/health"
+
+[[vm]]
+ size = "shared-cpu-1x"
+ memory_mb = 1024
diff --git a/infra/railway/README.md b/infra/railway/README.md
new file mode 100644
index 000000000..ece7dd4ec
--- /dev/null
+++ b/infra/railway/README.md
@@ -0,0 +1,207 @@
+# AiSOC on Railway
+
+Deploy AiSOC to [Railway](https://railway.com) with one click — the lean
+demo profile, 4 services, plus Postgres + Redis plugins.
+
+[![Deploy on Railway](https://railway.com/button.svg)](https://railway.com/new/template?template=https%3A%2F%2Fgithub.com%2Fbeenuar%2FAiSOC&plugins=postgresql%2Credis)
+
+## What this deploys
+
+The same lean profile that the [Fly demo](../fly/) and the
+[Render Blueprint](../render/) use, with Railway-specific wiring:
+
+| Service | Why |
+|---|---|
+| `api` | FastAPI core. Configured by `railway.toml` at the repo root level. |
+| `agents` | LangGraph orchestrator. Added as a second service after the initial deploy. |
+| `realtime` | WebSocket fanout. Added as a third service. |
+| `web` | Next.js console. Added as the fourth service. |
+| Postgres plugin | Auto-provisioned by the deploy button (`&plugins=postgresql`). |
+| Redis plugin | Auto-provisioned by the deploy button (`&plugins=redis`). |
+
+**Cost**: ~$5-15/mo for casual evaluation traffic on Railway's
+pay-as-you-go pricing. Way cheaper than Render for low-traffic demos
+because idle services don't accrue charges.
+
+## Why Railway is multi-step (vs Render's one-shot)
+
+Render has [Blueprints](https://render.com/docs/blueprint-spec) which
+declare an entire stack in one YAML file. Railway's `railway.toml` is
+**per-service** — its multi-service story goes through *Templates*
+(published artifacts, not in-repo config) or the dashboard's "+ New
+service" button.
+
+We chose to ship `railway.toml` (configures the api) + this README
+(walks through adding the other three) rather than:
+
+- **Publishing a Railway Template**: requires a Railway team account and
+ ties the template's lifecycle to a single owner. Forks would all share
+ one template.
+- **Shipping a `railway-template.json`**: undocumented format, fragile
+ across Railway's UI redesigns.
+
+The deploy button below provisions the api + Postgres + Redis. The other
+services take ~3 minutes to add via the dashboard.
+
+## Deploy walkthrough
+
+### Step 1: Click the deploy button
+
+[![Deploy on Railway](https://railway.com/button.svg)](https://railway.com/new/template?template=https%3A%2F%2Fgithub.com%2Fbeenuar%2FAiSOC&plugins=postgresql%2Credis)
+
+This:
+
+1. Forks `beenuar/AiSOC` to your GitHub account (or uses an existing fork).
+2. Creates a new Railway project.
+3. Provisions a Postgres plugin (named `Postgres`).
+4. Provisions a Redis plugin (named `Redis`).
+5. Reads [`railway.toml`](railway.toml) and deploys the api service from
+ `services/api/Dockerfile`.
+
+Wait ~3 min for the api to go green.
+
+### Step 2: Wire database URLs into the api
+
+In the Railway dashboard, click the **api** service → **Variables**, and
+add:
+
+```
+DATABASE_URL=${{ Postgres.DATABASE_URL }}
+REDIS_URL=${{ Redis.REDIS_URL }}
+JWT_SECRET=<generate a random 32-char string>
+```
+
+Railway auto-redeploys when variables change. The api will run Alembic
+migrations on the next boot and become healthy.
+
+### Step 3: Add the agents service
+
+1. **+ New** → **GitHub Repo** → select your fork.
+2. **Settings** → **Root Directory**: `services/agents`
+3. **Settings** → **Build** → **Builder**: Dockerfile (auto-detected).
+4. **Variables**:
+
+```
+ENVIRONMENT=demo
+PORT=8084
+AISOC_AGENT_MODE=deterministic
+AISOC_DISABLE_KAFKA=true
+AISOC_DISABLE_QDRANT=true
+AISOC_DISABLE_NEO4J=true
+DATABASE_URL=${{ Postgres.DATABASE_URL }}
+REDIS_URL=${{ Redis.REDIS_URL }}
+CORE_API_URL=http://${{ api.RAILWAY_PRIVATE_DOMAIN }}:8000
+```
+
+The `RAILWAY_PRIVATE_DOMAIN` reference resolves to
+`api.railway.internal` — Railway's free internal networking.
+
+### Step 4: Add the realtime service
+
+1. **+ New** → **GitHub Repo** → select your fork.
+2. **Settings** → **Root Directory**: `services/realtime`
+3. **Variables**:
+
+```
+NODE_ENV=production
+PORT=8086
+REDIS_URL=${{ Redis.REDIS_URL }}
+AISOC_DISABLE_KAFKA=true
+```
+
+4. **Settings** → **Networking** → **Generate Domain** (the realtime
+ service needs to be reachable from the browser for WebSocket
+ connections, so it gets a public domain).
+
+### Step 5: Add the web service
+
+1. **+ New** → **GitHub Repo** → select your fork.
+2. **Settings** → **Root Directory**: `.` (the monorepo root — the web
+ Dockerfile copies `pnpm-workspace.yaml` and `packages/`).
+3. **Settings** → **Build** → **Dockerfile Path**: `apps/web/Dockerfile`
+4. **Variables**:
+
+```
+NODE_ENV=production
+PORT=3000
+NEXT_PUBLIC_API_URL=https://${{ api.RAILWAY_PUBLIC_DOMAIN }}
+NEXT_PUBLIC_WS_URL=wss://${{ realtime.RAILWAY_PUBLIC_DOMAIN }}
+NEXT_PUBLIC_AISOC_DEMO_MODE=true
+NEXT_PUBLIC_AISOC_DEMO_DEEPLINK=/cases/INC-001?tab=ledger
+NEXT_PUBLIC_AISOC_DEMO_BANNER=Demo data resets daily. All write actions are disabled.
+```
+
+5. **Settings** → **Networking** → **Generate Domain**.
+6. Generate domains for `api` too (so the browser can reach it directly):
+ **api** → **Settings** → **Networking** → **Generate Domain**.
+
+### Step 6: Pre-warm the demo
+
+```bash
+# From your local machine:
+CORE_API_URL=https://api-<hash>.up.railway.app \
+AGENTS_API_URL=https://agents-<hash>.up.railway.app \
+ python scripts/demo_seed.py --reset --kickoff-investigation
+```
+
+Open the web service's URL — you should land on the demo banner with the
+INC-001 deeplink primed.
+
+## Why this isn't a one-click experience
+
+The Railway deploy button is one-click for the **api + Postgres + Redis**.
+The remaining three services are ~3 minutes of clicking, but they cannot
+be one-clicked because Railway's template system requires a published
+template artifact owned by a single account, which fragments badly when
+users fork the repo.
+
+If you want fully zero-touch multi-service deploys:
+- [**Render**](../render/) — Blueprints handle this natively.
+- [**Fly.io**](../fly/) — single shell script provisions everything.
+- [**Self-hosted via Coolify**](../coolify/) — drop in the docker-compose
+ and click Deploy.
+
+## Daily reset (optional)
+
+Railway has [Cron jobs](https://docs.railway.com/reference/cron-jobs) as
+a feature on services with a `[deploy.cronSchedule]` config. To rotate
+the demo daily, add a 5th service running the seed script:
+
+```toml
+# In a copy of railway.toml under a new service "demo-seed":
+[deploy]
+cronSchedule = "0 0 * * *" # daily at 00:00 UTC
+startCommand = "python scripts/demo_seed.py --reset --kickoff-investigation"
+```
+
+Or skip it for personal evaluation deploys.
+
+## Troubleshooting
+
+### "Web service can't reach api"
+
+Make sure `NEXT_PUBLIC_API_URL` points to the **public** Railway domain
+(`*.up.railway.app`), not the private one. The browser can't resolve
+`*.railway.internal`.
+
+### "Out of memory on agents service"
+
+The default Railway memory limit is 512MB. Bump it to 2GB in
+**Settings** → **Resources** → **Memory**.
+
+### "Database connection refused"
+
+The `${{ Postgres.DATABASE_URL }}` reference only works if the Postgres
+plugin is named exactly `Postgres` (case-sensitive). If you renamed it,
+update the variable references on each service.
+
+## Files
+
+```
+infra/railway/
+├── README.md — this file (multi-service walkthrough)
+└── railway.toml — api service config (consumed by the deploy button)
+```
+
+For the full deployment philosophy and platform comparison, see the
+[main README](../../README.md#-deploy-in-one-click).
diff --git a/infra/railway/railway.toml b/infra/railway/railway.toml
new file mode 100644
index 000000000..d243ee95e
--- /dev/null
+++ b/infra/railway/railway.toml
@@ -0,0 +1,74 @@
+# AiSOC on Railway — service manifest
+#
+# Why this exists:
+# The "Deploy on Railway" button in README.md uses Railway's template
+# system (railway.com/new/template?template=…) which clones this repo
+# and reads this file to figure out the build + run config.
+#
+# What Railway does *not* do (vs Render Blueprints / Fly stacks):
+# railway.toml is per-service, not multi-service. Railway's preferred
+# way to ship a multi-service app is via a *Template* — either through
+# the dashboard wizard or by publishing one. So this file configures
+# *one* service (the api), and the README's deploy button passes
+# `&plugins=postgresql%2Credis` to ask Railway to provision the two
+# stateful dependencies as plugins on the same project.
+#
+# For the other services (agents, web, realtime), the recommended path
+# is "+ New service → Deploy from GitHub repo → set root directory".
+# See infra/railway/README.md for the full walkthrough.
+#
+# Why this is the path of least resistance:
+# - Railway gives us $5/mo of free credit per project, which is enough
+# to run the full demo stack for a few days of evaluation.
+# - Their pay-as-you-go model means demo traffic that drops to zero
+# stops costing money — better than Render's flat $7/svc/mo for
+# casual self-hosters.
+# - Internal networking is automatic: every service gets a private
+# `<service>.railway.internal` hostname, no flytoml-style config.
+
+[build]
+# Use the api Dockerfile as the canonical build. Same Dockerfile as Fly
+# and Render — the build context is services/api/.
+builder = "DOCKERFILE"
+dockerfilePath = "services/api/Dockerfile"
+# Railway honors the build context the Dockerfile expects. The api
+# Dockerfile is self-contained (services/api/), so we set it explicitly.
+buildContext = "services/api"
+
+[deploy]
+# Health-check path that the api exposes. Railway will not mark the
+# service "Active" until /health returns 200, which prevents serving
+# traffic during boot.
+healthcheckPath = "/health"
+# Generous timeout — the first boot does Alembic migrations + ledger
+# table creation, which can take ~20s on a cold Postgres.
+healthcheckTimeout = 60
+# `ON_FAILURE` is the default; we set it explicitly because demo traffic
+# is bursty and we don't want a single 502 to nuke the deploy.
+restartPolicyType = "ON_FAILURE"
+restartPolicyMaxRetries = 10
+
+# Service-level env. The actual secrets (DATABASE_URL, REDIS_URL) are
+# auto-injected by Railway when you attach the Postgres + Redis plugins
+# — we do NOT set them here, because hardcoding `${{ Postgres.DATABASE_URL }}`
+# only works once the user has named the plugin "Postgres". The deploy
+# template handles that.
+[deploy.envs]
+ENVIRONMENT = "demo"
+PORT = "8000"
+
+# Demo gates — same flags as Render and Fly. Self-hosters running for
+# real should set AISOC_DEMO_MODE=false in the dashboard after deploy.
+AISOC_DEMO_MODE = "true"
+AISOC_DEMO_TENANT = "demo"
+
+# Disable optional integrations. Railway plugins exist for Postgres and
+# Redis, not for Kafka/ClickHouse/OpenSearch/Neo4j/Qdrant — and shipping
+# them as raw services on Railway would balloon the project's resource
+# usage past the free credit. The api degrades gracefully when these are
+# off, so the demo profile works fine without them.
+AISOC_DISABLE_KAFKA = "true"
+AISOC_DISABLE_CLICKHOUSE = "true"
+AISOC_DISABLE_OPENSEARCH = "true"
+AISOC_DISABLE_NEO4J = "true"
+AISOC_DISABLE_QDRANT = "true"
diff --git a/infra/render/README.md b/infra/render/README.md
new file mode 100644
index 000000000..6279251a5
--- /dev/null
+++ b/infra/render/README.md
@@ -0,0 +1,142 @@
+# AiSOC on Render
+
+One-click deploy of the full AiSOC demo stack to [Render](https://render.com)
+via Render's [Blueprint](https://render.com/docs/blueprint-spec) feature.
+
+[![Deploy to Render](https://render.com/images/deploy-to-render-button.svg)](https://render.com/deploy?repo=https://github.com/beenuar/AiSOC)
+
+## What this deploys
+
+The lean demo profile — same shape as the [Fly demo](../fly/), without
+the heavy storage tier:
+
+| Service | Plan | Role |
+|---|---|---|
+| `aisoc-api` | starter ($7/mo) | FastAPI core + investigation ledger |
+| `aisoc-agents` | standard ($25/mo) | LangGraph orchestrator (needs 2GB RAM) |
+| `aisoc-realtime` | starter ($7/mo) | WebSocket fanout |
+| `aisoc-web` | starter ($7/mo) | Next.js console + marketing |
+| `aisoc-postgres` | starter ($7/mo) | Managed Postgres (1GB) |
+| `aisoc-redis` | starter ($10/mo) | Managed Redis (25MB) |
+
+**Total: ~$63/mo** for an always-on, public-facing demo. Significantly
+cheaper than running the full storage tier (Kafka + ClickHouse + OpenSearch
++ Neo4j + Qdrant) which Render doesn't offer managed versions of.
+
+## What's disabled (and why it's fine)
+
+The Blueprint sets these flags on the api and agents services:
+
+```yaml
+AISOC_DISABLE_KAFKA: "true"
+AISOC_DISABLE_CLICKHOUSE: "true"
+AISOC_DISABLE_OPENSEARCH: "true"
+AISOC_DISABLE_NEO4J: "true"
+AISOC_DISABLE_QDRANT: "true"
+```
+
+The demo profile uses **Postgres + Redis** for everything — alerts, cases,
+investigations, the agent ledger, the cache layer. ClickHouse-backed event
+search and Neo4j-backed attack graphs are *hidden in the UI* when the
+backing store is absent, so the demo never shows a broken page.
+
+If you need the full storage tier in production, use:
+
+- **Self-hosted on Render**: not recommended — single-instance Kafka and
+ ClickHouse on Render's plans is more expensive than running them on a
+ dedicated VM.
+- **Kubernetes / Helm**: see [`infra/helm/`](../helm/) — production-grade,
+ brings its own Kafka/ClickHouse/OpenSearch.
+- **Terraform / AWS**: see [`infra/terraform/`](../terraform/) — uses MSK,
+ RDS, ElastiCache, OpenSearch Service, ECS for the application tier.
+
+## Deploy walkthrough
+
+### Option A: one-click (recommended)
+
+1. Click the **Deploy to Render** button above.
+2. Render asks for permission to read your fork of `beenuar/AiSOC`. Grant it.
+3. Render parses [`render.yaml`](render.yaml), shows the service plan, and
+ asks you to confirm.
+4. Click **Apply**. Render provisions Postgres + Redis first (~2 min),
+ then deploys the four web services in dependency order (~6-8 min for
+ the first build because Docker layers aren't cached yet).
+5. Once `aisoc-web` is green, open `https://aisoc-web-<hash>.onrender.com`.
+ The demo banner shows; the deeplink lands on a pre-seeded incident.
+
+### Option B: manual
+
+If you've forked the repo and changed things:
+
+```bash
+# From the repo root, after pushing your fork to GitHub:
+gh repo view --web
+# Then in Render: New + → Blueprint → Connect repo → select fork →
+# point at infra/render/render.yaml → Apply.
+```
+
+## Post-deploy: pre-warm the demo
+
+Render doesn't have an equivalent of Fly's `flyctl ssh console -C` for
+running one-shot commands, but the demo seeds itself the first time a
+visitor lands on the api (`scripts/demo_seed.py` runs on startup if the
+demo tenant is empty). For a faster cold start:
+
+```bash
+# From your local machine, point the seed script at the deployed api:
+CORE_API_URL=https://aisoc-api-<hash>.onrender.com \
+AGENTS_API_URL=https://aisoc-agents-<hash>.onrender.com \
+ python scripts/demo_seed.py --reset --kickoff-investigation
+```
+
+## Daily reset (optional)
+
+The Fly demo wipes and re-seeds the demo tenant daily via a scheduled
+machine. Render doesn't have native cron, so the options are:
+
+1. **Render Cron Job service** (~$1/mo) — add a 7th service of type `cron`
+ to `render.yaml` that runs the seed script on a schedule. Skipped from
+ the Blueprint by default to keep the cost story simple.
+2. **GitHub Actions workflow** — `.github/workflows/render-demo-reset.yml`
+ that hits the deployed api on a schedule. Free, but tied to your GH Actions
+ minutes budget.
+3. **Skip it** — for a personal evaluation deploy, the demo data will drift
+ over time but won't break.
+
+## Troubleshooting
+
+### "Web service failed health check"
+
+The web service's health check hits `/`, which requires the api to be up
+(it server-side renders the case list). If the api is still booting,
+Render marks web as failed. Wait 60s and retry — Render auto-redeploys
+on failed health checks up to 3 times.
+
+### "Out of memory on aisoc-agents"
+
+The starter plan (512MB) is not enough for LangGraph + the LLM client
+buffers. The Blueprint defaults agents to `standard` (2GB) for this
+reason. If you downgraded it, bump back up.
+
+### Demo banner not showing
+
+Check that `NEXT_PUBLIC_AISOC_DEMO_MODE=true` is set on the `aisoc-web`
+service. The variable is baked into the JS bundle at build time, so
+flipping it requires a redeploy (not just a restart).
+
+### Slow first investigation
+
+First boot does Alembic migrations + creates the ledger schema, which
+can take 20-30s on cold Postgres. Subsequent investigations land in
+&lt;5s once the schema is in place.
+
+## Files
+
+```
+infra/render/
+├── README.md — this file
+└── render.yaml — Render Blueprint manifest (the source of truth)
+```
+
+For the full deployment philosophy and platform comparison, see the
+[main README](../../README.md#-deploy-in-one-click).
diff --git a/infra/render/render.yaml b/infra/render/render.yaml
new file mode 100644
index 000000000..6bd95db79
--- /dev/null
+++ b/infra/render/render.yaml
@@ -0,0 +1,231 @@
+# AiSOC on Render — Blueprint manifest
+#
+# Why this exists:
+# The "Deploy to Render" button in README.md points GitHub at this file.
+# Render reads it as a Blueprint and provisions the entire AiSOC stack —
+# 4 web services + Postgres + Redis — in a single click, no manual setup.
+#
+# What it deploys (the *lean demo profile* — same shape as Fly):
+# - api (FastAPI core)
+# - agents (LangGraph orchestrator)
+# - web (Next.js console + marketing)
+# - realtime (WebSocket fanout)
+# - aisoc-postgres (managed Render Postgres)
+# - aisoc-redis (managed Render Redis)
+#
+# What it skips (and why):
+# - Kafka, ClickHouse, OpenSearch, Neo4j, Qdrant — Render does not offer
+# managed versions, and self-hosting them on Render's instance plans is
+# wasteful. The lean profile uses the AISOC_DISABLE_* flags (defined in
+# services/api/app/core/config.py) so the API and agents degrade
+# gracefully: alerts work, cases work, the agent investigates. Heavy
+# analytics (ClickHouse-backed event search, Neo4j attack graphs) are
+# hidden in the UI when the backing store is absent.
+#
+# For a production install with the full storage tier, use Helm
+# (infra/helm/) or Terraform (infra/terraform/) — those targets assume
+# you have your own Kafka, ClickHouse, etc.
+#
+# Plan choice (`starter` vs `free`):
+# We default to `starter` ($7/svc/mo) because the `free` plan sleeps after
+# 15 min of inactivity — the agent's WebSocket connection breaks, and
+# cold starts blow the sub-60s time-to-first-investigation budget the
+# demo promises. Override `plan: free` per-service if you're truly just
+# kicking the tires.
+#
+# Re-deploys:
+# Render auto-redeploys on every push to the branch tracked by the
+# service. The `buildCommand` rebuilds the relevant Docker image; the
+# `startCommand` is the same one used in the service's Dockerfile.
+
+services:
+ # ─── api ──────────────────────────────────────────────────────────────
+ # Core FastAPI app. Mirrors the Fly demo's api service.
+ - type: web
+ name: aisoc-api
+ runtime: docker
+ dockerfilePath: ./services/api/Dockerfile
+ dockerContext: ./services/api
+ plan: starter
+ healthCheckPath: /health
+ autoDeploy: true
+ envVars:
+ - key: ENVIRONMENT
+ value: demo
+ - key: PORT
+ value: "8000"
+ # Demo gates: write actions return 403, mutating endpoints become
+ # read-only. Flip these to `false` for a production deploy.
+ - key: AISOC_DEMO_MODE
+ value: "true"
+ - key: AISOC_DEMO_TENANT
+ value: demo
+ # Disable optional integrations — Render doesn't offer Kafka/CH/etc.
+ - key: AISOC_DISABLE_KAFKA
+ value: "true"
+ - key: AISOC_DISABLE_CLICKHOUSE
+ value: "true"
+ - key: AISOC_DISABLE_OPENSEARCH
+ value: "true"
+ - key: AISOC_DISABLE_NEO4J
+ value: "true"
+ - key: AISOC_DISABLE_QDRANT
+ value: "true"
+ # Database wiring: Render injects the connection string via
+ # `fromDatabase` when the resource is in the same Blueprint.
+ - key: DATABASE_URL
+ fromDatabase:
+ name: aisoc-postgres
+ property: connectionString
+ - key: REDIS_URL
+ fromService:
+ type: redis
+ name: aisoc-redis
+ property: connectionString
+ # Cross-service URLs — used by the api when it needs to call agents
+ # (e.g. /investigate kickoff). Render assigns each service a
+ # `<name>.onrender.com` hostname which we resolve via fromService.
+ - key: AGENTS_API_URL
+ fromService:
+ type: web
+ name: aisoc-agents
+ property: hostport
+ # Auto-generated JWT secret — rotated only if the user destroys it.
+ - key: JWT_SECRET
+ generateValue: true
+
+ # ─── agents ───────────────────────────────────────────────────────────
+ # LangGraph orchestrator + investigator. Talks to api over Render's
+ # internal network (same hostport mechanism the api uses to reach it).
+ - type: web
+ name: aisoc-agents
+ runtime: docker
+ dockerfilePath: ./services/agents/Dockerfile
+ dockerContext: ./services/agents
+ # Agents need more memory for the LangGraph runtime + LLM client
+ # buffers — Render's `standard` plan ships 2GB vs starter's 512MB.
+ plan: standard
+ healthCheckPath: /health
+ autoDeploy: true
+ envVars:
+ - key: ENVIRONMENT
+ value: demo
+ - key: PORT
+ value: "8084"
+ # Deterministic mode means the agent runs the canonical investigation
+ # without hitting OpenAI/Anthropic — keeps the demo cheap and
+ # offline-reproducible. Users with their own API keys can flip this.
+ - key: AISOC_AGENT_MODE
+ value: deterministic
+ - key: AISOC_DISABLE_KAFKA
+ value: "true"
+ - key: AISOC_DISABLE_QDRANT
+ value: "true"
+ - key: AISOC_DISABLE_NEO4J
+ value: "true"
+ - key: DATABASE_URL
+ fromDatabase:
+ name: aisoc-postgres
+ property: connectionString
+ - key: REDIS_URL
+ fromService:
+ type: redis
+ name: aisoc-redis
+ property: connectionString
+ - key: CORE_API_URL
+ fromService:
+ type: web
+ name: aisoc-api
+ property: hostport
+ # Optional — users wire these via the Render dashboard if they want
+ # the agent to call out to OpenAI/Anthropic. Defaults to deterministic
+ # offline mode.
+ - key: OPENAI_API_KEY
+ sync: false
+ - key: ANTHROPIC_API_KEY
+ sync: false
+
+ # ─── realtime ─────────────────────────────────────────────────────────
+ # Node.js WebSocket fanout. Has to keep the connection open for live
+ # ledger streaming, so we explicitly keep it on starter (no sleep).
+ - type: web
+ name: aisoc-realtime
+ runtime: docker
+ dockerfilePath: ./services/realtime/Dockerfile
+ dockerContext: ./services/realtime
+ plan: starter
+ healthCheckPath: /health
+ autoDeploy: true
+ envVars:
+ - key: NODE_ENV
+ value: production
+ - key: PORT
+ value: "8086"
+ - key: REDIS_URL
+ fromService:
+ type: redis
+ name: aisoc-redis
+ property: connectionString
+ # No Kafka — realtime falls back to Redis pub/sub for fanout when
+ # AISOC_DISABLE_KAFKA is set. See services/realtime/src/index.ts.
+ - key: AISOC_DISABLE_KAFKA
+ value: "true"
+
+ # ─── web ──────────────────────────────────────────────────────────────
+ # Next.js console + marketing landing. Served last — depends on api +
+ # realtime URLs being known so it can bake them into NEXT_PUBLIC_*.
+ - type: web
+ name: aisoc-web
+ runtime: docker
+ # The web Dockerfile needs the monorepo root as context (it copies
+ # pnpm-workspace.yaml + packages/). This is the same gotcha we hit on
+ # Fly, hence the explicit `.` context.
+ dockerfilePath: ./apps/web/Dockerfile
+ dockerContext: .
+ plan: starter
+ healthCheckPath: /
+ autoDeploy: true
+ envVars:
+ - key: NODE_ENV
+ value: production
+ - key: PORT
+ value: "3000"
+ # Public-facing URLs — consumed by the browser, so they must be the
+ # internet-reachable hostnames Render assigns each service.
+ - key: NEXT_PUBLIC_API_URL
+ fromService:
+ type: web
+ name: aisoc-api
+ property: host
+ - key: NEXT_PUBLIC_WS_URL
+ fromService:
+ type: web
+ name: aisoc-realtime
+ property: host
+ # Demo banner — same flags the Fly demo uses, surfaced via
+ # apps/web/src/lib/demoMode.ts.
+ - key: NEXT_PUBLIC_AISOC_DEMO_MODE
+ value: "true"
+ - key: NEXT_PUBLIC_AISOC_DEMO_DEEPLINK
+ value: /cases/INC-001?tab=ledger
+ - key: NEXT_PUBLIC_AISOC_DEMO_BANNER
+ value: "Demo data resets daily. All write actions are disabled."
+
+ # ─── redis ────────────────────────────────────────────────────────────
+ # Render's managed Redis. Used as cache + pub/sub spine when Kafka is
+ # disabled. The free `starter` plan caps at 25MB which is more than
+ # enough for the demo profile.
+ - type: redis
+ name: aisoc-redis
+ plan: starter
+ ipAllowList: [] # private — only siblings in this Blueprint reach it.
+
+databases:
+ # ─── postgres ─────────────────────────────────────────────────────────
+ # Render's managed Postgres. Demo profile fits comfortably in the
+ # `starter` plan (1GB storage). Production deploys should resize via
+ # the Render dashboard or use an external managed Postgres (RDS, etc.).
+ - name: aisoc-postgres
+ plan: starter
+ databaseName: aisoc
+ user: aisoc
diff --git a/package.json b/package.json
index 12ca2c7d6..a76c84b98 100644
--- a/package.json
+++ b/package.json
@@ -25,9 +25,14 @@
"demo:produce": "go run ./services/demo-producer",
"demo:produce:fast": "go run ./services/demo-producer --rate 8 --batch 10",
"detections:validate": "python3 scripts/validate_detections.py",
- "marketplace:sync": "cp marketplace/index.json apps/web/public/marketplace/index.json && echo 'marketplace/index.json synced to apps/web/public/'",
+ "marketplace:build": "python3 scripts/build_marketplace.py",
+ "marketplace:check": "python3 scripts/build_marketplace.py --check",
+ "marketplace:sync": "python3 scripts/build_marketplace.py && cp marketplace/index.json apps/web/public/marketplace/index.json && echo 'marketplace/index.json built and synced to apps/web/public/'",
"aisoc:lab": "bash scripts/lab.sh",
- "aisoc:doctor": "tsx scripts/aisoc-doctor.ts"
+ "aisoc:doctor": "tsx scripts/aisoc-doctor.ts",
+ "aisoc:demo": "tsx scripts/aisoc-demo.ts",
+ "aisoc:demo:down": "docker compose -f docker-compose.demo.yml down -v",
+ "aisoc:demo:logs": "docker compose -f docker-compose.demo.yml logs -f"
},
"devDependencies": {
"@types/node": "^20.11.0",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 333cd85b2..0636efc5d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -205,6 +205,28 @@ importers:
specifier: ^5.3.3
version: 5.9.3
+ services/mcp:
+ dependencies:
+ '@modelcontextprotocol/sdk':
+ specifier: ^1.0.4
+ version: 1.29.0([email protected])
+ zod:
+ specifier: ^3.23.8
+ version: 3.25.76
+ devDependencies:
+ '@types/node':
+ specifier: ^20.11.5
+ version: 20.19.39
+ tsx:
+ specifier: ^4.7.0
+ version: 4.21.0
+ typescript:
+ specifier: ^5.4.0
+ version: 5.9.3
+ vitest:
+ specifier: ^2.0.0
+ version: 2.1.9(@types/[email protected])
+
packages:
/@algolia/[email protected]:
@@ -3649,6 +3671,15 @@ packages:
dependencies:
'@hapi/hoek': 9.3.0
+ resolution: {integrity: sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==}
+ engines: {node: '>=18.14.1'}
+ peerDependencies:
+ hono: ^4
+ dependencies:
+ hono: 4.12.16
+ dev: false
+
/@humanwhocodes/[email protected]:
resolution: {integrity: sha512-DZLEEqFWQFiyK6h5YIeynKx7JlvCYWL0cImfSRXZ9l4Sg2efkFGTuFf6vzXjK1cq6IYkU+Eg/JizXw+TD2vRNw==}
engines: {node: '>=10.10.0'}
@@ -4007,6 +4038,37 @@ packages:
react: 18.3.1
dev: false
+ /@modelcontextprotocol/[email protected]([email protected]):
+ resolution: {integrity: sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@cfworker/json-schema': ^4.1.1
+ zod: ^3.25 || ^4.0
+ peerDependenciesMeta:
+ '@cfworker/json-schema':
+ optional: true
+ dependencies:
+ '@hono/node-server': 1.19.14([email protected])
+ ajv: 8.20.0
+ ajv-formats: 3.0.1([email protected])
+ content-type: 1.0.5
+ cors: 2.8.6
+ cross-spawn: 7.0.6
+ eventsource: 3.0.7
+ eventsource-parser: 3.0.8
+ express: 5.2.1
+ express-rate-limit: 8.4.1([email protected])
+ hono: 4.12.16
+ jose: 6.2.3
+ json-schema-typed: 8.0.2
+ pkce-challenge: 5.0.1
+ raw-body: 3.0.2
+ zod: 3.25.76
+ zod-to-json-schema: 3.25.2([email protected])
+ transitivePeerDependencies:
+ - supports-color
+ dev: false
+
/@monaco-editor/[email protected]:
resolution: {integrity: sha512-gIwR1HrJrrx+vfyOhYmCZ0/JcWqG5kbfG7+d3f/C1LXk2EvzAbHSg3MQ5lO2sMlo9izoAZ04shohfKLVT6crVA==}
dependencies:
@@ -5718,6 +5780,14 @@ packages:
negotiator: 0.6.3
dev: false
+ resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==}
+ engines: {node: '>= 0.6'}
+ dependencies:
+ mime-types: 3.0.2
+ negotiator: 1.0.0
+ dev: false
+
resolution: {integrity: sha512-wKmbr/DDiIXzEOiWrTTUcDm24kQ2vGfZQvM2fwg2vXqR5uW6aapr7ObPtj1th32b9u90/Pf4AItvdTh42fBmVQ==}
engines: {node: '>=10.13.0'}
@@ -5773,6 +5843,17 @@ packages:
dependencies:
ajv: 8.20.0
+ resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==}
+ peerDependencies:
+ ajv: ^8.0.0
+ peerDependenciesMeta:
+ ajv:
+ optional: true
+ dependencies:
+ ajv: 8.20.0
+ dev: false
+
resolution: {integrity: sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==}
peerDependencies:
@@ -6176,6 +6257,23 @@ packages:
- supports-color
dev: false
+ resolution: {integrity: sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==}
+ engines: {node: '>=18'}
+ dependencies:
+ bytes: 3.1.2
+ content-type: 1.0.5
+ debug: 4.4.3([email protected])
+ http-errors: 2.0.1
+ iconv-lite: 0.7.2
+ on-finished: 2.4.1
+ qs: 6.15.1
+ raw-body: 3.0.2
+ type-is: 2.0.1
+ transitivePeerDependencies:
+ - supports-color
+ dev: false
+
resolution: {integrity: sha512-3YuAUiSkWykd+2Azjgyxei8OWf8thdn8AITIog2M4UICzoqfjlqr64WIjEXZllf/W6vK1goqleSR6brGomxQqA==}
dependencies:
@@ -6667,6 +6765,11 @@ packages:
safe-buffer: 5.2.1
dev: false
+ resolution: {integrity: sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==}
+ engines: {node: '>=18'}
+ dev: false
+
resolution: {integrity: sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==}
engines: {node: '>= 0.6'}
@@ -6680,6 +6783,11 @@ packages:
resolution: {integrity: sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==}
dev: false
+ resolution: {integrity: sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==}
+ engines: {node: '>=6.6.0'}
+ dev: false
+
resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==}
engines: {node: '>= 0.6'}
@@ -6720,6 +6828,14 @@ packages:
resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==}
dev: false
+ resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==}
+ engines: {node: '>= 0.10'}
+ dependencies:
+ object-assign: 4.1.1
+ vary: 1.1.2
+ dev: false
+
resolution: {integrity: sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g==}
dependencies:
@@ -8104,6 +8220,18 @@ packages:
resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}
engines: {node: '>=0.8.x'}
+ resolution: {integrity: sha512-70QWGkr4snxr0OXLRWsFLeRBIRPuQOvt4s8QYjmUlmlkyTZkRqS7EDVRZtzU3TiyDbXSzaOeF0XUKy8PchzukQ==}
+ engines: {node: '>=18.0.0'}
+ dev: false
+
+ resolution: {integrity: sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==}
+ engines: {node: '>=18.0.0'}
+ dependencies:
+ eventsource-parser: 3.0.8
+ dev: false
+
resolution: {integrity: sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==}
engines: {node: '>=10'}
@@ -8124,6 +8252,16 @@ packages:
engines: {node: '>=12.0.0'}
dev: true
+ resolution: {integrity: sha512-NGVYwQSAyEQgzxX1iCM978PP9AdO/hW93gMcF6ZwQCm+rFvLsBH6w4xcXWTcliS8La5EPRN3p9wzItqBwJrfNw==}
+ engines: {node: '>= 16'}
+ peerDependencies:
+ express: '>= 4.11'
+ dependencies:
+ express: 5.2.1
+ ip-address: 10.1.0
+ dev: false
+
resolution: {integrity: sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==}
engines: {node: '>= 0.10.0'}
@@ -8163,6 +8301,42 @@ packages:
- supports-color
dev: false
+ resolution: {integrity: sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==}
+ engines: {node: '>= 18'}
+ dependencies:
+ accepts: 2.0.0
+ body-parser: 2.2.2
+ content-disposition: 1.1.0
+ content-type: 1.0.5
+ cookie: 0.7.2
+ cookie-signature: 1.2.2
+ debug: 4.4.3([email protected])
+ depd: 2.0.0
+ encodeurl: 2.0.0
+ escape-html: 1.0.3
+ etag: 1.8.1
+ finalhandler: 2.1.1
+ fresh: 2.0.0
+ http-errors: 2.0.1
+ merge-descriptors: 2.0.0
+ mime-types: 3.0.2
+ on-finished: 2.4.1
+ once: 1.4.0
+ parseurl: 1.3.3
+ proxy-addr: 2.0.7
+ qs: 6.15.1
+ range-parser: 1.2.1
+ router: 2.2.0
+ send: 1.2.1
+ serve-static: 2.2.1
+ statuses: 2.0.2
+ type-is: 2.0.1
+ vary: 1.1.2
+ transitivePeerDependencies:
+ - supports-color
+ dev: false
+
resolution: {integrity: sha512-zCnTtlxNoAiDc3gqY2aYAWFx7XWWiasuF2K8Me5WbN8otHKTUKBwjPtNpRs/rbUZm7KxWAaNj7P1a/p52GbVug==}
engines: {node: '>=0.10.0'}
@@ -8277,6 +8451,20 @@ packages:
- supports-color
dev: false
+ resolution: {integrity: sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==}
+ engines: {node: '>= 18.0.0'}
+ dependencies:
+ debug: 4.4.3([email protected])
+ encodeurl: 2.0.0
+ escape-html: 1.0.3
+ on-finished: 2.4.1
+ parseurl: 1.3.3
+ statuses: 2.0.2
+ transitivePeerDependencies:
+ - supports-color
+ dev: false
+
resolution: {integrity: sha512-9ZonPT4ZAK4a+1pUPVPZJapbi7O5qbbJPdYw/NOQWZZbVLdDTYM3A4R9z/DpAM08IDaFGsvPgiGZ82WEwUDWjg==}
engines: {node: '>=14.16'}
@@ -8395,6 +8583,11 @@ packages:
engines: {node: '>= 0.6'}
dev: false
+ resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==}
+ engines: {node: '>= 0.8'}
+ dev: false
+
resolution: {integrity: sha512-CTXd6rk/M3/ULNQj8FBqBWHYBVYybQ3VPBw0xGKFe3tuH7ytT6ACnvzpIQ3UZtB8yvUKC2cXn1a+x+5EVQLovA==}
engines: {node: '>=14.14'}
@@ -8825,6 +9018,11 @@ packages:
react-is: 16.13.1
dev: false
+ resolution: {integrity: sha512-jN0ZewiNAWSe5khM3EyCmBb250+b40wWbwNILNfEvq84VREWwOIkuUsFONk/3i3nqkz7Oe1PcpM2mwQEK2L9Kg==}
+ engines: {node: '>=16.9.0'}
+ dev: false
+
resolution: {integrity: sha512-zJxVehUdMGIKsRaNt7apO2Gqp0BdqW5yaiGHXXmbpvxgBYVZnAql+BJb4RO5ad2MgpbZKn5G6nMnegrH1FcNYQ==}
dependencies:
@@ -9012,6 +9210,13 @@ packages:
safer-buffer: 2.1.2
dev: false
+ resolution: {integrity: sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==}
+ engines: {node: '>=0.10.0'}
+ dependencies:
+ safer-buffer: 2.1.2
+ dev: false
+
resolution: {integrity: sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA==}
engines: {node: ^10 || ^12 || >= 14}
@@ -9104,6 +9309,11 @@ packages:
dependencies:
loose-envify: 1.4.0
+ resolution: {integrity: sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==}
+ engines: {node: '>= 12'}
+ dev: false
+
resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==}
engines: {node: '>= 0.10'}
@@ -9341,6 +9551,10 @@ packages:
dependencies:
isobject: 3.0.1
+ resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==}
+ dev: false
+
resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==}
engines: {node: '>= 0.4'}
@@ -9523,6 +9737,10 @@ packages:
'@sideway/formula': 3.0.1
'@sideway/pinpoint': 2.0.0
+ resolution: {integrity: sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==}
+ dev: false
+
resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==}
engines: {node: '>=10'}
@@ -9569,6 +9787,10 @@ packages:
resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==}
+ resolution: {integrity: sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==}
+ dev: false
+
resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==}
dev: true
@@ -10013,6 +10235,11 @@ packages:
engines: {node: '>= 0.6'}
dev: false
+ resolution: {integrity: sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==}
+ engines: {node: '>= 0.8'}
+ dev: false
+
resolution: {integrity: sha512-2nWzSsJzrukurSDna4Z0WywuScK4Id3tSKejgu74u8KCdW4uNrseKRSIDg75C6Yw5ZRqBe0F0EtMNlTbUq8bAQ==}
peerDependencies:
@@ -10038,6 +10265,11 @@ packages:
resolution: {integrity: sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==}
dev: false
+ resolution: {integrity: sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==}
+ engines: {node: '>=18'}
+ dev: false
+
resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==}
@@ -10590,6 +10822,11 @@ packages:
engines: {node: '>= 0.6'}
dev: false
+ resolution: {integrity: sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==}
+ engines: {node: '>= 0.6'}
+ dev: false
+
resolution: {integrity: sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==}
@@ -10787,7 +11024,6 @@ packages:
resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}
dependencies:
wrappy: 1.0.2
- dev: true
resolution: {integrity: sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==}
@@ -11065,6 +11301,10 @@ packages:
resolution: {integrity: sha512-qyCH421YQPS2WFDxDjftfc1ZR5WKQzVzqsp4n9M2kQhVOo/ByahFoUNJfl58kOcEGfQ//7weFTDhm+ss8Ecxgw==}
dev: false
+ resolution: {integrity: sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==}
+ dev: false
+
resolution: {integrity: sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==}
engines: {node: '>=8'}
@@ -11104,6 +11344,11 @@ packages:
engines: {node: '>= 6'}
dev: true
+ resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==}
+ engines: {node: '>=16.20.0'}
+ dev: false
+
resolution: {integrity: sha512-Ie9z/WINcxxLp27BKOCHGde4ITq9UklYKDzVo1nhk5sqGEXU3FpkwP5GM2voTGJkGd9B3Otl+Q4uwSOeSUtOBA==}
engines: {node: '>=14.16'}
@@ -12110,6 +12355,16 @@ packages:
unpipe: 1.0.0
dev: false
+ resolution: {integrity: sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==}
+ engines: {node: '>= 0.10'}
+ dependencies:
+ bytes: 3.1.2
+ http-errors: 2.0.1
+ iconv-lite: 0.7.2
+ unpipe: 1.0.0
+ dev: false
+
resolution: {integrity: sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==}
hasBin: true
@@ -12704,6 +12959,19 @@ packages:
fsevents: 2.3.3
dev: true
+ resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==}
+ engines: {node: '>= 18'}
+ dependencies:
+ debug: 4.4.3([email protected])
+ depd: 2.0.0
+ is-promise: 4.0.0
+ parseurl: 1.3.3
+ path-to-regexp: 8.4.2
+ transitivePeerDependencies:
+ - supports-color
+ dev: false
+
resolution: {integrity: sha512-FI+pHEn7Wc4NqKXMXFM+VAYKEj/mRIcW4h24YVwVtyjI+EqGrLc2Hx/Ny0lrZ21cBWU2goLy36eqMcNj3AQJig==}
engines: {node: '>=12.0.0'}
@@ -12858,6 +13126,25 @@ packages:
- supports-color
dev: false
+ resolution: {integrity: sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==}
+ engines: {node: '>= 18'}
+ dependencies:
+ debug: 4.4.3([email protected])
+ encodeurl: 2.0.0
+ escape-html: 1.0.3
+ etag: 1.8.1
+ fresh: 2.0.0
+ http-errors: 2.0.1
+ mime-types: 3.0.2
+ ms: 2.1.3
+ on-finished: 2.4.1
+ range-parser: 1.2.1
+ statuses: 2.0.2
+ transitivePeerDependencies:
+ - supports-color
+ dev: false
+
resolution: {integrity: sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==}
dependencies:
@@ -12903,6 +13190,18 @@ packages:
- supports-color
dev: false
+ resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==}
+ engines: {node: '>= 18'}
+ dependencies:
+ encodeurl: 2.0.0
+ escape-html: 1.0.3
+ parseurl: 1.3.3
+ send: 1.2.1
+ transitivePeerDependencies:
+ - supports-color
+ dev: false
+
resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==}
engines: {node: '>= 0.4'}
@@ -13768,6 +14067,15 @@ packages:
mime-types: 2.1.35
dev: false
+ resolution: {integrity: sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==}
+ engines: {node: '>= 0.6'}
+ dependencies:
+ content-type: 1.0.5
+ media-typer: 1.1.0
+ mime-types: 3.0.2
+ dev: false
+
resolution: {integrity: sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==}
engines: {node: '>= 0.4'}
@@ -14545,7 +14853,6 @@ packages:
resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}
- dev: true
resolution: {integrity: sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==}
@@ -14624,6 +14931,18 @@ packages:
engines: {node: '>=12.20'}
dev: false
+ resolution: {integrity: sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==}
+ peerDependencies:
+ zod: ^3.25.28 || ^4
+ dependencies:
+ zod: 3.25.76
+ dev: false
+
+ resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}
+ dev: false
+
resolution: {integrity: sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==}
engines: {node: '>=12.7.0'}
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 3ff5faaaf..58e1ad423 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -1,3 +1,4 @@
packages:
- "apps/*"
- "packages/*"
+ - "services/mcp"
diff --git a/scripts/demo_seed.py b/scripts/demo_seed.py
new file mode 100644
index 000000000..b391f23fc
--- /dev/null
+++ b/scripts/demo_seed.py
@@ -0,0 +1,34 @@
+"""Repo-root shim for ``app.scripts.demo_seed``.
+
+The canonical implementation lives inside the api package at
+``services/api/app/scripts/demo_seed.py`` so it can be invoked inside the
+api container on Fly.io as ``python -m app.scripts.demo_seed``. This shim
+exists so self-hosters running from the repo root can still type
+``python scripts/demo_seed.py --reset`` without juggling PYTHONPATH.
+
+If you're editing the seed logic, edit the canonical module — not this file.
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+from pathlib import Path
+
+_REPO_ROOT = Path(__file__).resolve().parent.parent
+_API_ROOT = _REPO_ROOT / "services" / "api"
+
+# Put services/api on the path so ``from app.scripts.demo_seed import main``
+# resolves to the canonical implementation.
+if str(_API_ROOT) not in sys.path:
+ sys.path.insert(0, str(_API_ROOT))
+
+# Default the API URLs to docker-compose host ports when running locally; the
+# Fly demo overrides via env on the api machine.
+os.environ.setdefault("CORE_API_URL", "http://localhost:8081")
+os.environ.setdefault("AGENTS_API_URL", "http://localhost:8084")
+
+from app.scripts.demo_seed import main # noqa: E402
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/services/api/app/middleware/demo_mode.py b/services/api/app/middleware/demo_mode.py
new file mode 100644
index 000000000..11e001560
--- /dev/null
+++ b/services/api/app/middleware/demo_mode.py
@@ -0,0 +1,119 @@
+"""Demo-mode guard for the hosted demo at demo.aisoc.dev.
+
+When `AISOC_DEMO_MODE=true`, this middleware:
+
+1. **Surfaces a banner.** Adds `X-AiSOC-Demo: true` and
+ `X-AiSOC-Demo-Banner: <message>` headers on every response so the web
+ client can render the "demo data resets daily" notice.
+2. **Blocks destructive writes.** Any non-safe HTTP method (POST/PUT/PATCH/DELETE)
+ targeting a mutating endpoint returns 403 with a structured payload
+ explaining how to self-host. We allow a small allowlist (auth, dev_auth,
+ investigation kickoff against the canonical case) so the canned demo
+ experience still works end-to-end.
+
+This is *not* a substitute for proper auth/RBAC — it's a defense-in-depth
+layer on top of the demo tenant's read-only RBAC role. Without it, a
+visitor poking at `/api/v1/cases` could mutate the global demo state for
+every other concurrent visitor.
+
+Configured in `app.main.create_application` after CORS/GZip so the headers
+land on cached error responses too.
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+from collections.abc import Awaitable, Callable
+
+from fastapi import Request, Response
+from fastapi.responses import JSONResponse
+from starlette.middleware.base import BaseHTTPMiddleware
+
+from app.core.config import settings
+
+log = logging.getLogger(__name__)
+
+# Always allowed (auth flows + read endpoints). Match by prefix.
+_ALWAYS_ALLOWED_PREFIXES: tuple[str, ...] = (
+ "/health",
+ "/metrics",
+ "/api/docs",
+ "/api/redoc",
+ "/api/openapi.json",
+ "/api/v1/auth/",
+ "/api/v1/dev-auth",
+ "/saml/",
+ "/oidc/",
+)
+
+# In demo mode these *write* endpoints still work — needed for the canned
+# "click → see investigation" experience to function.
+_DEMO_WRITE_ALLOWLIST: tuple[re.Pattern[str], ...] = (
+ # The seed pre-warms a run, but visitors can still kick off their own.
+ re.compile(r"^/api/v1/cases/INC-001/investigate$"),
+ re.compile(r"^/api/v1/investigations/[^/]+/cancel$"),
+ # Acknowledgement is local-state-only on the visitor's view.
+ re.compile(r"^/api/v1/alerts/[^/]+/ack$"),
+)
+
+_SAFE_METHODS: frozenset[str] = frozenset({"GET", "HEAD", "OPTIONS"})
+
+
+class DemoModeMiddleware(BaseHTTPMiddleware):
+ """Gate writes and surface banner headers when AISOC_DEMO_MODE is on."""
+
+ async def dispatch(
+ self,
+ request: Request,
+ call_next: Callable[[Request], Awaitable[Response]],
+ ) -> Response:
+ if not settings.AISOC_DEMO_MODE:
+ return await call_next(request)
+
+ path = request.url.path
+ method = request.method.upper()
+
+ # Read-only or auth flow → just decorate response.
+ if method in _SAFE_METHODS or path.startswith(_ALWAYS_ALLOWED_PREFIXES):
+ response = await call_next(request)
+ self._stamp_demo_headers(response)
+ return response
+
+ # Allowlisted mutations (canonical demo flow) → permit.
+ if any(p.match(path) for p in _DEMO_WRITE_ALLOWLIST):
+ response = await call_next(request)
+ self._stamp_demo_headers(response)
+ return response
+
+ # Everything else → 403 with a structured "self-host me" payload.
+ log.info(
+ "demo-mode blocked %s %s (origin=%s)",
+ method,
+ path,
+ request.client.host if request.client else "?",
+ )
+ response = JSONResponse(
+ status_code=403,
+ content={
+ "error": "demo_mode_read_only",
+ "message": (
+ "This is the public AiSOC demo at demo.aisoc.dev. "
+ "Write actions are disabled here so every visitor sees "
+ "the same dataset. To run AiSOC for real, self-host it "
+ "in 5 minutes — see https://github.com/cyble/AiSOC."
+ ),
+ "self_host_url": "https://github.com/cyble/AiSOC#quickstart",
+ "blocked_path": path,
+ "blocked_method": method,
+ },
+ )
+ self._stamp_demo_headers(response)
+ return response
+
+ @staticmethod
+ def _stamp_demo_headers(response: Response) -> None:
+ response.headers["X-AiSOC-Demo"] = "true"
+ response.headers["X-AiSOC-Demo-Tenant"] = settings.AISOC_DEMO_TENANT
+ # Headers can't carry newlines; banner is short by design.
+ response.headers["X-AiSOC-Demo-Banner"] = settings.AISOC_DEMO_BANNER
diff --git a/services/api/app/scripts/demo_seed.py b/services/api/app/scripts/demo_seed.py
new file mode 100644
index 000000000..638a15b00
--- /dev/null
+++ b/services/api/app/scripts/demo_seed.py
@@ -0,0 +1,229 @@
+"""demo_seed — Reset and warm up the hosted demo at demo.aisoc.dev.
+
+This is the canonical entrypoint for the hosted-demo refresh job. It runs
+inside the api image (so it gets DATABASE_URL via Fly Postgres attach,
+REDIS_URL via Upstash attach, and access to the rest of the API package),
+and is invoked one of three ways:
+
+* **Post-deploy** — `infra/fly/fly-demo-deploy.sh` runs it via
+ `flyctl ssh console -a aisoc-demo-api -C "python -m app.scripts.demo_seed
+ --reset --kickoff-investigation"` once the deploy completes, so visitors
+ hitting `demo.aisoc.dev` immediately see a hot investigation.
+* **Daily cron** — A Fly scheduled machine on the api app re-runs this
+ every 24h at 00:00 UTC to scrub demo state and re-seed.
+* **Local recovery** — Self-hosters can run
+ `python scripts/demo_seed.py --reset` from the repo root if the demo
+ data gets dirty during local development. (See ``scripts/demo_seed.py``
+ shim, which just re-execs this module.)
+
+Why three responsibilities in one entrypoint?
+1. Drop demo-tenant data so each visitor sees the same canonical INC-001.
+2. Re-seed canonical demo data via the existing ``seed_demo`` module —
+ same data self-hosters get with ``pnpm seed:demo``.
+3. Pre-warm an investigation so the deeplink ``/cases/INC-001?tab=ledger``
+ already has agent events streaming when the browser arrives. This is
+ the keystone of the sub-60s time-to-first-investigation target.
+
+Idempotent. Safe to re-run. ``--dry-run`` prints actions without touching
+any state.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import logging
+import os
+import sys
+from typing import Any
+
+import httpx
+
+logging.basicConfig(
+ level=os.getenv("LOG_LEVEL", "INFO").upper(),
+ format="%(asctime)s [%(levelname)s] demo-seed: %(message)s",
+)
+log = logging.getLogger("demo-seed")
+
+
+# ── Demo configuration ───────────────────────────────────────────────────────
+# On Fly the seed runs *inside* the api container, so CORE_API_URL points to
+# localhost. The agents live in a sibling app reachable via Fly's internal
+# 6PN DNS. Env vars override these for local docker-compose use.
+CORE_API_URL = os.getenv("CORE_API_URL", "http://localhost:8000")
+AGENTS_API_URL = os.getenv("AGENTS_API_URL", "http://aisoc-demo-agents.internal:8084")
+DEMO_TENANT = os.getenv("AISOC_DEMO_TENANT", "demo")
+DEMO_CASE_ID = os.getenv("AISOC_DEMO_CASE_ID", "INC-001")
+HTTP_TIMEOUT = float(os.getenv("AISOC_DEMO_HTTP_TIMEOUT", "30"))
+
+
+async def _wait_for_api(client: httpx.AsyncClient, url: str, timeout: int = 60) -> None:
+ """Poll ``/health`` until the API answers 200 or the timeout elapses.
+
+ Fly machines warm up while we run; without this the seed races api/agents
+ finishing their first health check.
+ """
+ deadline = asyncio.get_event_loop().time() + timeout
+ last_err: Exception | None = None
+ while asyncio.get_event_loop().time() < deadline:
+ try:
+ r = await client.get(f"{url}/health")
+ if r.status_code == 200:
+ log.info("api healthy: %s", url)
+ return
+ last_err = RuntimeError(f"unexpected status {r.status_code}")
+ except httpx.HTTPError as exc:
+ last_err = exc
+ await asyncio.sleep(2)
+ raise RuntimeError(f"api never became healthy within {timeout}s ({url}): {last_err}")
+
+
+def _run_local_seeder() -> None:
+ """Invoke the existing ``seed_demo`` module in-process.
+
+ The seeder writes to whatever Postgres ``DATABASE_URL`` points at — Fly
+ managed Postgres on the demo, the docker-compose ``postgres`` service
+ locally. Idempotent: drops + recreates demo-tenant data.
+ """
+ log.info("running canonical seed_demo (tenant=%s)…", DEMO_TENANT)
+ try:
+ from app.scripts.seed_demo import main as seed_main
+ except Exception as exc:
+ # If the in-process import fails (rare, but seed_demo imports a lot
+ # of optional deps), fall back to a subprocess so we still re-seed
+ # rather than silently leaving the demo stale.
+ log.warning(
+ "could not import in-process seeder (%s); falling back to subprocess",
+ exc,
+ )
+ import subprocess
+
+ subprocess.run(
+ [sys.executable, "-m", "app.scripts.seed_demo"],
+ check=True,
+ env={**os.environ, "AISOC_DEMO_TENANT": DEMO_TENANT},
+ )
+ return
+
+ if asyncio.iscoroutinefunction(seed_main):
+ asyncio.run(seed_main())
+ else:
+ seed_main()
+
+
+async def _kickoff_investigation(client: httpx.AsyncClient) -> str | None:
+ """Start an agent run against ``INC-001`` so the demo lands hot.
+
+ Returns the run_id on success, or None if the agent declined (e.g.,
+ no model key + deterministic mode disabled). We never fail the deploy
+ on a missed kickoff — the demo still works, the visitor just sees a
+ cold case until they click "Investigate".
+ """
+ payload: dict[str, Any] = {
+ "case_id": DEMO_CASE_ID,
+ "mode": "deterministic",
+ "tenant_id": DEMO_TENANT,
+ "metadata": {"source": "demo_seed", "deeplink": True},
+ }
+ log.info("kicking off investigation against %s via %s…", DEMO_CASE_ID, AGENTS_API_URL)
+ try:
+ r = await client.post(f"{AGENTS_API_URL}/investigate", json=payload)
+ except httpx.HTTPError as exc:
+ log.warning("kickoff request failed: %s", exc)
+ return None
+
+ if r.status_code >= 400:
+ log.warning("kickoff returned %s: %s", r.status_code, r.text[:200])
+ return None
+
+ try:
+ body = r.json() if r.content else {}
+ except ValueError:
+ log.warning("kickoff response was not JSON: %s", r.text[:200])
+ return None
+ run_id = body.get("run_id") or body.get("id")
+ log.info("investigation kicked off: run_id=%s", run_id)
+ return run_id
+
+
+async def main_async(args: argparse.Namespace) -> int:
+ if args.dry_run:
+ log.info(
+ "DRY-RUN — would seed tenant=%s, kickoff=%s, core=%s, agents=%s",
+ DEMO_TENANT,
+ args.kickoff_investigation,
+ CORE_API_URL,
+ AGENTS_API_URL,
+ )
+ return 0
+
+ async with httpx.AsyncClient(timeout=HTTP_TIMEOUT) as client:
+ if args.wait_for_api:
+ await _wait_for_api(client, CORE_API_URL, timeout=args.wait_timeout)
+ # Agents health is best-effort: if it never comes up we still
+ # seed Postgres so the visitor at least sees a populated UI.
+ try:
+ await _wait_for_api(client, AGENTS_API_URL, timeout=args.wait_timeout)
+ except RuntimeError as exc:
+ log.warning("agents never healthy (%s); continuing without kickoff", exc)
+ args.kickoff_investigation = False
+
+ # Reseed runs sync (uses sqlalchemy session, not httpx).
+ _run_local_seeder()
+
+ if args.kickoff_investigation:
+ run_id = await _kickoff_investigation(client)
+ if run_id is None:
+ log.warning(
+ "could not kickoff investigation — demo will land on a cold case. "
+ "Set OPENAI_API_KEY or ensure deterministic mode is enabled on agents."
+ )
+
+ log.info("demo reset complete.")
+ return 0
+
+
+def main() -> int:
+ p = argparse.ArgumentParser(description="Reset and warm up the hosted AiSOC demo.")
+ p.add_argument(
+ "--reset",
+ action="store_true",
+ help="Drop and re-seed the demo tenant (default for cron use).",
+ )
+ p.add_argument(
+ "--rotate-tenant",
+ action="store_true",
+ help="Rotate canonical data without dropping (less destructive).",
+ )
+ p.add_argument(
+ "--kickoff-investigation",
+ action="store_true",
+ help="Start an agent run against INC-001 so the deeplink lands hot.",
+ )
+ p.add_argument(
+ "--wait-for-api",
+ action="store_true",
+ default=True,
+ help="Poll /health on api+agents before seeding.",
+ )
+ p.add_argument(
+ "--wait-timeout",
+ type=int,
+ default=int(os.getenv("AISOC_DEMO_WAIT_TIMEOUT", "120")),
+ help="Seconds to wait for api+agents health before giving up.",
+ )
+ p.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Print actions without performing them.",
+ )
+
+ args = p.parse_args()
+ if not (args.reset or args.rotate_tenant or args.kickoff_investigation):
+ p.error("specify at least one of --reset / --rotate-tenant / --kickoff-investigation")
+
+ return asyncio.run(main_async(args))
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/services/api/tests/test_demo_mode.py b/services/api/tests/test_demo_mode.py
new file mode 100644
index 000000000..3e506d327
--- /dev/null
+++ b/services/api/tests/test_demo_mode.py
@@ -0,0 +1,156 @@
+"""Tests for the demo-mode middleware.
+
+These verify the gate behaves correctly in both modes:
+
+- When `AISOC_DEMO_MODE=False`, the middleware is transparent — every request
+ flows through and responses do **not** carry demo headers.
+- When `AISOC_DEMO_MODE=True`, GET requests succeed and pick up the banner
+ headers, allowlisted writes (kickoff against `INC-001`, alert ack) succeed,
+ and arbitrary mutating writes return 403 with the `demo_mode_read_only`
+ error code.
+
+The middleware is the *only* thing under test; we mount it on a stub Starlette
+app so the test doesn't pull in the real DB / auth stack.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from app.core.config import settings
+from app.middleware.demo_mode import DemoModeMiddleware
+
+
+def app(monkeypatch: pytest.MonkeyPatch) -> FastAPI:
+ """Build a stub app with the middleware wired up."""
+ monkeypatch.setattr(settings, "AISOC_DEMO_MODE", True)
+ monkeypatch.setattr(settings, "AISOC_DEMO_TENANT", "demo")
+ app = FastAPI()
+ app.add_middleware(DemoModeMiddleware)
+
+ @app.get("/health")
+ def health() -> dict[str, Any]:
+ return {"ok": True}
+
+ @app.get("/api/v1/cases")
+ def list_cases() -> dict[str, Any]:
+ return {"cases": []}
+
+ @app.post("/api/v1/cases")
+ def create_case() -> dict[str, Any]:
+ # Real handler would write to DB; in demo mode we should never reach it.
+ return {"created": True}
+
+ @app.delete("/api/v1/cases/{case_id}")
+ def delete_case(case_id: str) -> dict[str, Any]:
+ return {"deleted": case_id}
+
+ @app.post("/api/v1/cases/INC-001/investigate")
+ def investigate() -> dict[str, Any]:
+ return {"run_id": "demo-run-123"}
+
+ @app.post("/api/v1/alerts/{alert_id}/ack")
+ def ack(alert_id: str) -> dict[str, Any]:
+ return {"acked": alert_id}
+
+ @app.post("/api/v1/auth/login")
+ def login() -> dict[str, Any]:
+ return {"token": "fake"}
+
+ return app
+
+
+def test_demo_mode_off_is_transparent(monkeypatch: pytest.MonkeyPatch) -> None:
+ """With demo mode off the middleware is a passthrough — no headers, no gates."""
+ monkeypatch.setattr(settings, "AISOC_DEMO_MODE", False)
+ app = FastAPI()
+ app.add_middleware(DemoModeMiddleware)
+
+ @app.post("/api/v1/cases")
+ def create_case() -> dict[str, Any]:
+ return {"created": True}
+
+ client = TestClient(app)
+ r = client.post("/api/v1/cases")
+ assert r.status_code == 200
+ assert r.json() == {"created": True}
+ assert "X-AiSOC-Demo" not in r.headers
+
+
+def test_get_request_succeeds_with_banner_headers(app: FastAPI) -> None:
+ client = TestClient(app)
+ r = client.get("/api/v1/cases")
+ assert r.status_code == 200
+ assert r.headers["X-AiSOC-Demo"] == "true"
+ assert r.headers["X-AiSOC-Demo-Tenant"] == "demo"
+ assert "resets daily" in r.headers["X-AiSOC-Demo-Banner"].lower()
+
+
+def test_health_endpoint_is_always_allowed(app: FastAPI) -> None:
+ """`/health` must answer 200 even in demo mode so Fly.io health checks pass."""
+ client = TestClient(app)
+ r = client.get("/health")
+ assert r.status_code == 200
+
+
+def test_arbitrary_post_is_blocked_with_403(app: FastAPI) -> None:
+ client = TestClient(app)
+ r = client.post("/api/v1/cases", json={"title": "evil"})
+ assert r.status_code == 403
+ body = r.json()
+ assert body["error"] == "demo_mode_read_only"
+ assert body["blocked_method"] == "POST"
+ assert body["blocked_path"] == "/api/v1/cases"
+ assert "self_host_url" in body
+ # 403 still gets banner headers so the UI can render the banner over the error.
+ assert r.headers["X-AiSOC-Demo"] == "true"
+
+
+def test_arbitrary_delete_is_blocked_with_403(app: FastAPI) -> None:
+ client = TestClient(app)
+ r = client.delete("/api/v1/cases/INC-007")
+ assert r.status_code == 403
+ assert r.json()["error"] == "demo_mode_read_only"
+
+
+def test_canonical_investigation_kickoff_is_allowed(app: FastAPI) -> None:
+ """The canned demo flow must work end-to-end."""
+ client = TestClient(app)
+ r = client.post("/api/v1/cases/INC-001/investigate")
+ assert r.status_code == 200
+ assert r.json() == {"run_id": "demo-run-123"}
+ assert r.headers["X-AiSOC-Demo"] == "true"
+
+
+def test_alert_acknowledge_is_allowed(app: FastAPI) -> None:
+ client = TestClient(app)
+ r = client.post("/api/v1/alerts/abc-123/ack")
+ assert r.status_code == 200
+ assert r.json() == {"acked": "abc-123"}
+
+
+def test_auth_login_is_allowed(app: FastAPI) -> None:
+ """Auth endpoints must work in demo mode so visitors can be issued a session."""
+ client = TestClient(app)
+ r = client.post("/api/v1/auth/login", json={"username": "demo", "password": "demo"})
+ assert r.status_code == 200
+ assert r.json() == {"token": "fake"}
+
+
+def test_options_preflight_is_allowed(app: FastAPI) -> None:
+ """CORS preflight (OPTIONS) is a safe method; gate must let it through."""
+ client = TestClient(app)
+ r = client.options(
+ "/api/v1/cases",
+ headers={"Origin": "https://demo.aisoc.dev", "Access-Control-Request-Method": "GET"},
+ )
+ # FastAPI's TestClient + CORSMiddleware would normally answer this; without
+ # CORSMiddleware it 405s, but the demo-mode middleware itself never blocks
+ # the OPTIONS verb. So we accept either 200 or 405 — the assertion is only
+ # that the demo-mode 403 path was *not* taken.
+ assert r.status_code != 403
diff --git a/services/mcp/README.md b/services/mcp/README.md
new file mode 100644
index 000000000..de59a743a
--- /dev/null
+++ b/services/mcp/README.md
@@ -0,0 +1,173 @@
+# @aisoc/mcp
+
+> The official [Model Context Protocol](https://modelcontextprotocol.io) server for **AiSOC** — connect Claude Desktop, Cursor, Cody, Continue, and any MCP-aware assistant to your alerts, cases, detections, and the agent decision ledger.
+
+[![npm](https://img.shields.io/npm/v/@aisoc/mcp.svg)](https://www.npmjs.com/package/@aisoc/mcp)
+[![license](https://img.shields.io/npm/l/@aisoc/mcp.svg)](https://github.com/beenuar/AiSOC/blob/main/LICENSE)
+[![tests](https://img.shields.io/badge/tests-50%20passing-brightgreen)](#development)
+
+AiSOC is the open-source AI SOC where every agent decision is auditable. This package is the bridge that lets your assistant ask AiSOC questions like "show me the open P0 cases" or "replay the agent's reasoning on INC-0421" without leaving the chat.
+
+---
+
+## Install
+
+The recommended path is the one-liner installer. It writes the right snippet into the right config file for your host, and it's idempotent:
+
+```bash
+# Claude Desktop
+npx -y @aisoc/mcp install --host claude \
+ --aisoc-url https://aisoc.your-company.com \
+ --api-key aisoc_pat_xxxxxxxxxxxx
+
+# Cursor
+npx -y @aisoc/mcp install --host cursor --aisoc-url ... --api-key ...
+
+# Continue.dev
+npx -y @aisoc/mcp install --host continue --aisoc-url ... --api-key ...
+
+# Cody (prints a snippet to paste — the extension reads VS Code settings)
+npx -y @aisoc/mcp install --host cody --aisoc-url ... --api-key ...
+```
+
+Restart your assistant and the `aisoc` server will appear in its tool picker.
+
+> **Where does `--api-key` come from?** AiSOC console → Settings → API Keys → "New personal access token". The token is scoped to your tenant; revoke it any time.
+
+### Manual install
+
+If you'd rather edit the JSON yourself, `install --dry-run` prints exactly what the installer would write:
+
+```bash
+npx -y @aisoc/mcp install --host claude --dry-run \
+ --aisoc-url https://aisoc.your-company.com --api-key aisoc_xxx
+```
+
+The snippet looks like this — paste it under `mcpServers` in your host's config:
+
+```json
+{
+ "mcpServers": {
+ "aisoc": {
+ "command": "npx",
+ "args": ["-y", "@aisoc/mcp", "serve"],
+ "env": {
+ "AISOC_URL": "https://aisoc.your-company.com",
+ "AISOC_API_KEY": "aisoc_pat_xxxxxxxxxxxx"
+ }
+ }
+ }
+}
+```
+
+Per-host config locations:
+
+| Host | Config file |
+|---|---|
+| Claude Desktop (macOS) | `~/Library/Application Support/Claude/claude_desktop_config.json` |
+| Claude Desktop (Windows) | `%APPDATA%\Claude\claude_desktop_config.json` |
+| Cursor | `~/.cursor/mcp.json` |
+| Continue.dev | `~/.continue/config.json` |
+| Cody | VS Code User Settings (JSON) → `cody.mcp.servers` |
+
+Print these as JSON any time with `npx @aisoc/mcp install --list-paths`.
+
+---
+
+## Tools exposed
+
+The server advertises **11 tools**. Discovery tools list things, deep-dive tools fetch one thing, and the action / replay tools are what make AiSOC interesting:
+
+| Tool | Purpose |
+|---|---|
+| `aisoc_list_alerts` | Page through alerts with filters (severity, status, time range). |
+| `aisoc_get_alert` | Full alert detail including enrichments and matched detections. |
+| `aisoc_list_cases` | Page through cases with filters (status, owner, priority). |
+| `aisoc_get_case` | Full case detail including timeline and linked alerts. |
+| `aisoc_query_detections` | Search detection rules by name, MITRE technique, or tag. |
+| `aisoc_get_detection_rule` | Inspect a single rule (logic, fixtures, FP notes). |
+| `aisoc_list_investigations` | Page through agent investigation runs. |
+| `aisoc_get_investigation` | Run summary (status, duration, agents involved, cost). |
+| **`aisoc_run_investigation`** | Kick off the agent on a case and stream events back. |
+| **`aisoc_replay_decision`** | Walk the agent ledger step-by-step (recon, forensic, responder, reporter). |
+| **`aisoc_explain_step`** | Why-did-the-agent-do-this for a single step: prompt, response, tool I/O. |
+
+The replay/explain pair is the moat — closed-source AI SOC vendors can't show you their agent's prompts and tool calls. AiSOC will.
+
+---
+
+## Configuration
+
+All flags can be set via env vars. The CLI flag wins if both are present.
+
+| Flag | Env var | Default | Notes |
+|---|---|---|---|
+| `--aisoc-url` | `AISOC_URL` | `http://localhost:8081` | Base URL of the AiSOC API. |
+| `--api-key` | `AISOC_API_KEY` | _(none)_ | API key (`aisoc_pat_…`) or JWT. Required for non-public endpoints. |
+| `--timeout` | `AISOC_TIMEOUT_MS` | `20000` | Per-request timeout in ms. |
+| `--verbose` | `AISOC_VERBOSE=1` | off | Lifecycle logs to stderr (stdout stays JSON-RPC clean). |
+
+---
+
+## Verify before you fly
+
+Before pointing your assistant at it, smoke-test the connection:
+
+```bash
+AISOC_URL=https://aisoc.your-company.com \
+AISOC_API_KEY=aisoc_pat_xxx \
+npx -y @aisoc/mcp doctor
+```
+
+`doctor` checks DNS, TLS, the AiSOC `/health` endpoint, and that your API key is accepted. It exits non-zero on failure so you can wire it into a pre-flight script.
+
+---
+
+## How it talks to AiSOC
+
+```
+┌──────────────┐ stdio JSON-RPC ┌──────────────┐ HTTPS ┌──────────────┐
+│ Claude / │ ───────────────────────────► │ @aisoc/mcp │ ───────────► │ AiSOC API │
+│ Cursor / IDE │ ◄─────────────────────────── │ (this pkg) │ ◄─────────── │ + agents │
+└──────────────┘ └──────────────┘ └──────────────┘
+ │
+ ▼
+ investigation_events
+ (decision ledger)
+```
+
+- The host launches us via stdio. Stdout is reserved for JSON-RPC frames; logs go to stderr.
+- We translate MCP `tools/call` into the AiSOC REST API.
+- Streaming tools (`aisoc_run_investigation`) emit progressive content blocks so the assistant can show intermediate steps.
+
+---
+
+## Security notes
+
+- **Your API key never leaves the machine** running this server. It's read from env or the host's local config file (mode `0600`) and used to sign requests to your AiSOC instance.
+- **Read-only by default** unless your API key has write scopes. `aisoc_run_investigation` requires `cases:investigate`; everything else only needs `cases:read` / `alerts:read`.
+- **Audit trail.** Every tool call logged through this server lands in the AiSOC audit log with the calling user and the tool name. You can revoke the key and replay every action it took.
+
+---
+
+## Development
+
+```bash
+git clone https://github.com/beenuar/AiSOC.git
+cd AiSOC/services/mcp
+pnpm install
+pnpm test # 50 unit tests covering config, installers, tool registry
+pnpm typecheck
+pnpm build # produces dist/index.js (the bin)
+pnpm dev # tsx watch — runs in stdio serve mode
+```
+
+Adding a tool? See [`src/tools/`](./src/tools) — each tool is a `ToolDefinition<ZodSchema>` exported from a domain file and registered in [`src/tools/index.ts`](./src/tools/index.ts). The contract tests in `tests/tools.test.ts` will fail loudly if you forget metadata, ordering, or naming conventions.
+
+---
+
+## License
+
+MIT — see [LICENSE](https://github.com/beenuar/AiSOC/blob/main/LICENSE).
+
+Bug reports and PRs welcome at [github.com/beenuar/AiSOC](https://github.com/beenuar/AiSOC).
diff --git a/services/mcp/package.json b/services/mcp/package.json
new file mode 100644
index 000000000..7fd021aba
--- /dev/null
+++ b/services/mcp/package.json
@@ -0,0 +1,69 @@
+{
+ "name": "@aisoc/mcp",
+ "version": "0.1.0",
+ "description": "MCP server that exposes AiSOC (alerts, cases, agent investigations, the decision ledger) to Claude Desktop, Cursor, Cody, Continue, and any MCP-aware agent.",
+ "keywords": [
+ "aisoc",
+ "mcp",
+ "model-context-protocol",
+ "claude",
+ "cursor",
+ "cody",
+ "soc",
+ "security",
+ "siem"
+ ],
+ "license": "MIT",
+ "author": "Cyble Inc.",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/mcp",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/beenuar/AiSOC.git",
+ "directory": "services/mcp"
+ },
+ "bugs": {
+ "url": "https://github.com/beenuar/AiSOC/issues"
+ },
+ "type": "module",
+ "main": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": {
+ "import": "./dist/index.js",
+ "types": "./dist/index.d.ts"
+ }
+ },
+ "bin": {
+ "aisoc-mcp": "./dist/index.js"
+ },
+ "files": [
+ "dist",
+ "src",
+ "README.md"
+ ],
+ "scripts": {
+ "dev": "tsx watch src/index.ts serve",
+ "build": "tsc -p tsconfig.json && node -e \"import('node:fs').then(fs=>fs.chmodSync('dist/index.js', 0o755))\"",
+ "start": "node dist/index.js serve",
+ "typecheck": "tsc --noEmit",
+ "test": "vitest run",
+ "lint": "eslint src --ext .ts",
+ "prepublishOnly": "npm run typecheck && npm run build"
+ },
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.0.4",
+ "zod": "^3.23.8"
+ },
+ "devDependencies": {
+ "@types/node": "^20.11.5",
+ "tsx": "^4.7.0",
+ "typescript": "^5.4.0",
+ "vitest": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=18.17"
+ },
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/services/mcp/src/client.ts b/services/mcp/src/client.ts
new file mode 100644
index 000000000..9d5c9eb1e
--- /dev/null
+++ b/services/mcp/src/client.ts
@@ -0,0 +1,169 @@
+/**
+ * Minimal HTTP client for the AiSOC REST API.
+ *
+ * Why we hand-roll a fetch wrapper instead of pulling in `openapi-fetch`
+ * (which `packages/sdk-ts` already uses):
+ *
+ * 1. The MCP server publishes to npm and is launched by `npx`. Each extra
+ * dependency widens the surface IDE hosts have to download on first
+ * run, which lengthens the "claude desktop says aisoc is loading"
+ * window. The native `fetch` in Node 18+ is enough.
+ * 2. Static `openapi-fetch` typings would lock the MCP server to a
+ * specific OpenAPI snapshot at build time. Real MCP deployments may
+ * hit older AiSOC instances, and we'd rather degrade by tolerating an
+ * unknown field than crash on a parse error.
+ * 3. We can centralise auth, timeout, retry, and error mapping in one
+ * place that matches the typed errors in `./errors.ts`.
+ *
+ * Auth model: the user provides a JWT or an `aisoc_*` API key; we send it
+ * verbatim as `Authorization: Bearer <token>`. Both paths are handled by
+ * the FastAPI dep `app.api.v1.deps.get_current_user`.
+ */
+import { ApiError, MissingApiKeyError, TransportError } from "./errors.js";
+import type { Logger, ServerConfig } from "./config.js";
+
+export interface RequestOptions {
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
+ /** JSON body — automatically serialised + Content-Type set. */
+ body?: unknown;
+ /** Query string params; arrays are repeated, undefined values dropped. */
+ query?: Record<string, string | number | boolean | undefined | string[]>;
+ /** Override the per-request timeout. */
+ timeoutMs?: number;
+ /** Accept header; defaults to `application/json`. */
+ accept?: string;
+ /** Skip JSON parsing — used for `.md` / `.html` / `.pdf` report pulls. */
+ raw?: boolean;
+}
+
+/** AiSOC client surface used by the tool layer. */
+export class AisocClient {
+ constructor(
+ private readonly cfg: ServerConfig,
+ private readonly log: Logger,
+ ) {}
+
+ /** GET helper that decodes JSON. */
+ async get<T>(path: string, opts: Omit<RequestOptions, "method" | "body"> = {}): Promise<T> {
+ return this.request<T>(path, { ...opts, method: "GET" });
+ }
+
+ /** POST helper that decodes JSON. */
+ async post<T>(path: string, body: unknown, opts: Omit<RequestOptions, "method" | "body"> = {}): Promise<T> {
+ return this.request<T>(path, { ...opts, method: "POST", body });
+ }
+
+ /** PATCH helper that decodes JSON. */
+ async patch<T>(path: string, body: unknown, opts: Omit<RequestOptions, "method" | "body"> = {}): Promise<T> {
+ return this.request<T>(path, { ...opts, method: "PATCH", body });
+ }
+
+ /**
+ * Health probe — used by `aisoc-mcp doctor`. We hit `/health` rather than
+ * `/api/v1/...` because the unauthenticated health endpoint exists on
+ * every AiSOC build and lets `doctor` validate the URL even when the key
+ * is missing or wrong.
+ */
+ async health(): Promise<{ status: string; reachable: boolean; raw?: unknown }> {
+ try {
+ const url = `${this.cfg.aisocUrl}/health`;
+ const res = await this.fetchWithTimeout(url, {
+ method: "GET",
+ headers: { Accept: "application/json", "User-Agent": this.cfg.userAgent },
+ });
+ const json = await res.json().catch(() => ({}));
+ return { status: String((json as { status?: unknown }).status ?? res.status), reachable: res.ok, raw: json };
+ } catch (err) {
+ return { status: "unreachable", reachable: false, raw: { error: String(err) } };
+ }
+ }
+
+ // ------------------------------------------------------------------
+ // Internals
+ // ------------------------------------------------------------------
+
+ private async request<T>(path: string, opts: RequestOptions): Promise<T> {
+ if (!this.cfg.apiKey) {
+ throw new MissingApiKeyError();
+ }
+
+ const url = this.buildUrl(path, opts.query);
+ const headers: Record<string, string> = {
+ Accept: opts.accept ?? "application/json",
+ "User-Agent": this.cfg.userAgent,
+ Authorization: `Bearer ${this.cfg.apiKey}`,
+ };
+ if (opts.body !== undefined) {
+ headers["Content-Type"] = "application/json";
+ }
+
+ this.log.info(`→ ${opts.method ?? "GET"} ${path}`);
+
+ const res = await this.fetchWithTimeout(url, {
+ method: opts.method ?? "GET",
+ headers,
+ body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
+ }, opts.timeoutMs);
+
+ if (!res.ok) {
+ let detail: string;
+ try {
+ const txt = await res.text();
+ // FastAPI emits `{"detail": "..."}` for HTTPException; surface the
+ // human message verbatim, fall back to the raw body otherwise.
+ try {
+ const parsed = JSON.parse(txt) as { detail?: unknown };
+ detail = typeof parsed.detail === "string" ? parsed.detail : txt;
+ } catch {
+ detail = txt;
+ }
+ } catch {
+ detail = `(no body)`;
+ }
+ throw new ApiError(res.status, path, detail);
+ }
+
+ if (opts.raw) {
+ // Return raw text — used for report.md / report.html / report.pdf.
+ return (await res.text()) as unknown as T;
+ }
+ if (res.status === 204) {
+ return undefined as unknown as T;
+ }
+ return (await res.json()) as T;
+ }
+
+ private buildUrl(path: string, query?: RequestOptions["query"]): string {
+ const base = this.cfg.aisocUrl;
+ const normalisedPath = path.startsWith("/") ? path : `/${path}`;
+ const url = new URL(`${base}${normalisedPath}`);
+ if (query) {
+ for (const [key, val] of Object.entries(query)) {
+ if (val === undefined || val === null) continue;
+ if (Array.isArray(val)) {
+ for (const v of val) url.searchParams.append(key, String(v));
+ } else {
+ url.searchParams.set(key, String(val));
+ }
+ }
+ }
+ return url.toString();
+ }
+
+ private async fetchWithTimeout(
+ url: string,
+ init: RequestInit,
+ timeoutMs?: number,
+ ): Promise<Response> {
+ const controller = new AbortController();
+ const ms = timeoutMs ?? this.cfg.timeoutMs;
+ const timer = setTimeout(() => controller.abort(), ms);
+ try {
+ return await fetch(url, { ...init, signal: controller.signal });
+ } catch (err) {
+ throw new TransportError(url, err);
+ } finally {
+ clearTimeout(timer);
+ }
+ }
+}
diff --git a/services/mcp/src/config.ts b/services/mcp/src/config.ts
new file mode 100644
index 000000000..662433704
--- /dev/null
+++ b/services/mcp/src/config.ts
@@ -0,0 +1,239 @@
+/**
+ * Runtime configuration for the AiSOC MCP server.
+ *
+ * Why not a config file: MCP hosts (Claude Desktop, Cursor, Cody) launch the
+ * server as a stdio child process and expose configuration via env vars +
+ * argv. We honour both, with argv winning so the install command can write a
+ * single self-contained command line into each host's config.
+ *
+ * Precedence (highest first):
+ * 1. CLI flags (`--aisoc-url …`, `--api-key …`)
+ * 2. Environment (`AISOC_URL`, `AISOC_API_KEY`)
+ * 3. Built-in defaults (only the URL — the key is required)
+ *
+ * The API key is required for any tool call against a real AiSOC. We allow
+ * the server to start without one (so `doctor` and `--help` work), but
+ * tool dispatch then fails with a typed `MissingApiKeyError`.
+ *
+ * Logging discipline: this server speaks MCP over stdout, so anything
+ * useful to humans **must** go to stderr. We never write to stdout outside
+ * the MCP transport.
+ */
+import { readFileSync } from "node:fs";
+
+const DEFAULT_AISOC_URL = "http://localhost:8081";
+const DEFAULT_TIMEOUT_MS = 20_000;
+
+export interface ServerConfig {
+ /** Base URL of the AiSOC API (e.g. `https://aisoc.example.com`). */
+ aisocUrl: string;
+ /** API key from /api/v1/api-keys (`aisoc_*` prefix) or a JWT bearer token. */
+ apiKey: string | undefined;
+ /** Default per-request timeout. */
+ timeoutMs: number;
+ /** Verbose logging to stderr (off by default to keep IDE consoles clean). */
+ verbose: boolean;
+ /** User-Agent string surfaced to the AiSOC API for audit. */
+ userAgent: string;
+}
+
+export interface ParsedArgs {
+ /** Positional command: `serve` (default), `install`, `doctor`, `help`. */
+ command: "serve" | "install" | "doctor" | "help" | "version";
+ /** Flags consumed by the parser; everything else goes to subcommands. */
+ flags: Record<string, string | boolean>;
+ /** Subcommand-specific positional args after the command. */
+ positional: string[];
+}
+
+const FLAG_ALIASES: Record<string, string> = {
+ "-h": "help",
+ "--help": "help",
+ "-v": "version",
+ "--version": "version",
+ "--aisoc-url": "aisocUrl",
+ "--api-key": "apiKey",
+ "--timeout": "timeoutMs",
+ "--verbose": "verbose",
+};
+
+/**
+ * Tiny argv parser. We deliberately avoid pulling in `commander` / `yargs`
+ * because the MCP binary is in everyone's `npx` cache and dependency weight
+ * matters: the SDK already pulls in zod; we don't need a second arg parser.
+ */
+export function parseArgs(argv: readonly string[]): ParsedArgs {
+ const args = [...argv];
+ const flags: Record<string, string | boolean> = {};
+ const positional: string[] = [];
+
+ while (args.length > 0) {
+ const raw = args.shift()!;
+ // Long-form `--key=value`
+ if (raw.startsWith("--") && raw.includes("=")) {
+ const eq = raw.indexOf("=");
+ const key = raw.slice(0, eq);
+ const val = raw.slice(eq + 1);
+ const canonical = FLAG_ALIASES[key];
+ if (canonical) {
+ flags[canonical] = val;
+ } else {
+ // Pass through unknown flags so installers can forward them
+ flags[key.replace(/^--/, "")] = val;
+ }
+ continue;
+ }
+ // Long/short flags
+ const canonical = FLAG_ALIASES[raw];
+ if (canonical) {
+ // boolean-style help/version/verbose take no value
+ if (canonical === "help" || canonical === "version" || canonical === "verbose") {
+ flags[canonical] = true;
+ continue;
+ }
+ const next = args.shift();
+ if (next === undefined || next.startsWith("-")) {
+ throw new Error(`Flag ${raw} requires a value`);
+ }
+ flags[canonical] = next;
+ continue;
+ }
+ if (raw.startsWith("--")) {
+ // Unknown long flag. Look ahead: if the next token is not another
+ // flag, treat this as `--key value`; otherwise as a boolean. This
+ // keeps `--host cursor` working without us having to enumerate every
+ // installer option in `FLAG_ALIASES`.
+ const next = args[0];
+ if (next !== undefined && !next.startsWith("-")) {
+ flags[raw.replace(/^--/, "")] = next;
+ args.shift();
+ } else {
+ flags[raw.replace(/^--/, "")] = true;
+ }
+ continue;
+ }
+ if (raw.startsWith("-")) {
+ // Unknown short flag; boolean-only to avoid surprising captures.
+ flags[raw.replace(/^-+/, "")] = true;
+ continue;
+ }
+ positional.push(raw);
+ }
+
+ // Resolve command from positional[0] or flags.help/version
+ let command: ParsedArgs["command"] = "serve";
+ if (flags.help) command = "help";
+ else if (flags.version) command = "version";
+ else if (positional.length > 0) {
+ const head = positional[0];
+ if (
+ head === "serve" ||
+ head === "install" ||
+ head === "doctor" ||
+ head === "help" ||
+ head === "version"
+ ) {
+ command = head;
+ positional.shift();
+ }
+ }
+
+ return { command, flags, positional };
+}
+
+/**
+ * Merge env + parsed flags into a fully-resolved {@link ServerConfig}.
+ *
+ * We intentionally tolerate a missing API key here; the actual error is
+ * raised lazily on the first tool call so `--help` and `doctor` still work
+ * even when the user hasn't wired credentials yet.
+ */
+export function resolveConfig(args: ParsedArgs, env: NodeJS.ProcessEnv = process.env): ServerConfig {
+ const url =
+ (typeof args.flags.aisocUrl === "string" && args.flags.aisocUrl) ||
+ env.AISOC_URL ||
+ env.AISOC_API_URL ||
+ DEFAULT_AISOC_URL;
+
+ const apiKey =
+ (typeof args.flags.apiKey === "string" && args.flags.apiKey) ||
+ env.AISOC_API_KEY ||
+ env.AISOC_TOKEN ||
+ undefined;
+
+ const timeoutFlag = args.flags.timeoutMs;
+ const timeoutMs =
+ typeof timeoutFlag === "string" && timeoutFlag.length > 0
+ ? Number.parseInt(timeoutFlag, 10)
+ : env.AISOC_TIMEOUT_MS
+ ? Number.parseInt(env.AISOC_TIMEOUT_MS, 10)
+ : DEFAULT_TIMEOUT_MS;
+
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
+ throw new Error(`Invalid timeout: ${timeoutFlag ?? env.AISOC_TIMEOUT_MS}`);
+ }
+
+ const verbose = Boolean(args.flags.verbose) || env.AISOC_MCP_VERBOSE === "1";
+
+ return {
+ aisocUrl: stripTrailingSlash(url),
+ apiKey,
+ timeoutMs,
+ verbose,
+ userAgent: `aisoc-mcp/${packageVersion()} (+https://github.com/beenuar/AiSOC)`,
+ };
+}
+
+function stripTrailingSlash(s: string): string {
+ return s.endsWith("/") ? s.slice(0, -1) : s;
+}
+
+/**
+ * Read version from package.json without bundling it. We resolve at runtime
+ * so `npm publish` doesn't need a build step that inlines the version.
+ *
+ * In dev (`tsx`), `import.meta.url` resolves to `…/services/mcp/src/config.ts`,
+ * so the package.json sits two directories up. After `tsc`, the file is at
+ * `…/services/mcp/dist/config.js` and package.json sits one directory up.
+ * We try both rather than guess the runtime mode.
+ */
+export function packageVersion(): string {
+ try {
+ const candidates = [
+ new URL("../package.json", import.meta.url),
+ new URL("../../package.json", import.meta.url),
+ ];
+ for (const url of candidates) {
+ try {
+ const raw = readFileSync(url, "utf8");
+ const parsed = JSON.parse(raw) as { version?: string };
+ if (parsed.version) return parsed.version;
+ } catch {
+ // try next candidate
+ }
+ }
+ return "0.0.0-dev";
+ } catch {
+ return "0.0.0-dev";
+ }
+}
+
+/**
+ * Stderr logger that respects `verbose`. We never log to stdout because
+ * MCP servers speak JSON-RPC there.
+ */
+export function makeLogger(cfg: Pick<ServerConfig, "verbose">) {
+ return {
+ info: (msg: string, ...rest: unknown[]) => {
+ if (cfg.verbose) console.error(`[aisoc-mcp] ${msg}`, ...rest);
+ },
+ warn: (msg: string, ...rest: unknown[]) => {
+ console.error(`[aisoc-mcp] WARN: ${msg}`, ...rest);
+ },
+ error: (msg: string, ...rest: unknown[]) => {
+ console.error(`[aisoc-mcp] ERROR: ${msg}`, ...rest);
+ },
+ };
+}
+
+export type Logger = ReturnType<typeof makeLogger>;
diff --git a/services/mcp/src/doctor.ts b/services/mcp/src/doctor.ts
new file mode 100644
index 000000000..eb856f672
--- /dev/null
+++ b/services/mcp/src/doctor.ts
@@ -0,0 +1,153 @@
+/**
+ * `aisoc-mcp doctor` — pre-flight diagnostic.
+ *
+ * Run by users before wiring this into Claude Desktop / Cursor so they can
+ * confirm their `AISOC_URL` and `AISOC_API_KEY` actually work, without
+ * having to chase silent failures inside an IDE side panel.
+ *
+ * Exits non-zero on any failed check so it's usable from CI / `pnpm
+ * aisoc:doctor`-style umbrella scripts.
+ */
+import { AisocClient } from "./client.js";
+import { type ServerConfig, type Logger, packageVersion } from "./config.js";
+import { ApiError, MissingApiKeyError, TransportError } from "./errors.js";
+
+export interface DoctorReport {
+ ok: boolean;
+ checks: Array<{
+ name: string;
+ status: "ok" | "warn" | "fail";
+ detail: string;
+ }>;
+}
+
+export async function runDoctor(
+ cfg: ServerConfig,
+ log: Logger,
+): Promise<DoctorReport> {
+ const checks: DoctorReport["checks"] = [];
+
+ // 1. Config presence -------------------------------------------------------
+ checks.push({
+ name: "AISOC_URL",
+ status: "ok",
+ detail: cfg.aisocUrl,
+ });
+
+ if (!cfg.apiKey) {
+ checks.push({
+ name: "AISOC_API_KEY",
+ status: "fail",
+ detail:
+ "Not set. Provide via env (AISOC_API_KEY) or --api-key. Tools will fail without an API key.",
+ });
+ return finalise(checks);
+ }
+ checks.push({
+ name: "AISOC_API_KEY",
+ status: "ok",
+ detail: maskKey(cfg.apiKey),
+ });
+
+ // 2. Reachability ----------------------------------------------------------
+ const client = new AisocClient(cfg, log);
+ try {
+ const health = await client.health();
+ checks.push({
+ name: "API reachable",
+ status: health.reachable ? "ok" : "warn",
+ detail: health.reachable
+ ? `${cfg.aisocUrl} responded (${health.status})`
+ : `Reached ${cfg.aisocUrl} but health endpoint returned non-OK`,
+ });
+ } catch (err) {
+ checks.push({
+ name: "API reachable",
+ status: "fail",
+ detail: describeError(err, cfg.aisocUrl),
+ });
+ return finalise(checks);
+ }
+
+ // 3. Auth ------------------------------------------------------------------
+ // We probe `/api/v1/cases?limit=1` because it's a low-cost auth-required
+ // endpoint that exists on every AiSOC deployment with cases. If the user's
+ // tenant is empty the call still succeeds with an empty list.
+ try {
+ await client.get<{ items: unknown[] }>("/api/v1/cases", {
+ query: { limit: 1, offset: 0 },
+ });
+ checks.push({
+ name: "API authentication",
+ status: "ok",
+ detail: "Token accepted; tools should work.",
+ });
+ } catch (err) {
+ if (err instanceof ApiError) {
+ checks.push({
+ name: "API authentication",
+ status: "fail",
+ detail: err.isAuthFailure
+ ? `Auth rejected (${err.status}). Check AISOC_API_KEY scope/expiry.`
+ : `API returned ${err.status}: ${err.detail}`,
+ });
+ } else if (err instanceof MissingApiKeyError) {
+ checks.push({
+ name: "API authentication",
+ status: "fail",
+ detail: "Missing API key (resolved to empty after config load).",
+ });
+ } else {
+ checks.push({
+ name: "API authentication",
+ status: "fail",
+ detail: describeError(err, cfg.aisocUrl),
+ });
+ }
+ }
+
+ return finalise(checks);
+}
+
+/** Print the doctor report to stderr in a human-readable form. */
+export function printDoctorReport(report: DoctorReport): void {
+ const lines: string[] = [];
+ lines.push(`aisoc-mcp ${packageVersion()} doctor`);
+ lines.push("");
+ for (const c of report.checks) {
+ const icon = c.status === "ok" ? "[OK]" : c.status === "warn" ? "[WARN]" : "[FAIL]";
+ lines.push(`${icon} ${c.name}`);
+ lines.push(` ${c.detail}`);
+ }
+ lines.push("");
+ lines.push(report.ok ? "All checks passed." : "Doctor found problems.");
+ // doctor output is a user-visible report; print to stdout so it's easy
+ // to redirect / capture from `pnpm aisoc:doctor`. We do *not* emit any
+ // JSON-RPC alongside this; doctor is invoked as a one-shot subcommand
+ // and the server transport is never started.
+ for (const l of lines) console.log(l);
+}
+
+// ---------------------------------------------------------------------------
+// helpers
+// ---------------------------------------------------------------------------
+
+function finalise(checks: DoctorReport["checks"]): DoctorReport {
+ return {
+ ok: checks.every((c) => c.status !== "fail"),
+ checks,
+ };
+}
+
+function describeError(err: unknown, url: string): string {
+ if (err instanceof TransportError) {
+ return `Could not reach ${url}: ${err.message}`;
+ }
+ if (err instanceof Error) return err.message;
+ return String(err);
+}
+
+function maskKey(k: string): string {
+ if (k.length <= 8) return "***";
+ return `${k.slice(0, 4)}…${k.slice(-4)} (${k.length} chars)`;
+}
diff --git a/services/mcp/src/errors.ts b/services/mcp/src/errors.ts
new file mode 100644
index 000000000..cfe5b0724
--- /dev/null
+++ b/services/mcp/src/errors.ts
@@ -0,0 +1,93 @@
+/**
+ * Typed errors used by the MCP server.
+ *
+ * MCP tool calls report failure by setting `isError: true` on the
+ * `CallToolResult` and returning a human-readable text content block. We
+ * model the failure modes here so each tool can map them to an actionable
+ * message instead of leaking a raw stack trace.
+ */
+
+/** No API key was wired into the process. */
+export class MissingApiKeyError extends Error {
+ readonly code = "AISOC_MISSING_API_KEY";
+ constructor() {
+ super(
+ "AiSOC API key is not configured. Pass --api-key or set AISOC_API_KEY. " +
+ "Generate one in your AiSOC console under Settings → API Keys.",
+ );
+ this.name = "MissingApiKeyError";
+ }
+}
+
+/** Network/timeout failure reaching AiSOC. */
+export class TransportError extends Error {
+ readonly code = "AISOC_TRANSPORT_ERROR";
+ constructor(
+ public readonly url: string,
+ cause: unknown,
+ ) {
+ super(`Could not reach AiSOC at ${url}: ${formatCause(cause)}`);
+ this.name = "TransportError";
+ if (cause instanceof Error) this.cause = cause;
+ }
+}
+
+/** AiSOC returned a non-2xx HTTP response. */
+export class ApiError extends Error {
+ readonly code = "AISOC_API_ERROR";
+ constructor(
+ public readonly status: number,
+ public readonly endpoint: string,
+ public readonly detail: string,
+ ) {
+ super(`AiSOC API ${status} on ${endpoint}: ${detail}`);
+ this.name = "ApiError";
+ }
+
+ /** Convenience: did the server reject our credential? */
+ get isAuthFailure(): boolean {
+ return this.status === 401 || this.status === 403;
+ }
+}
+
+/** A tool was called with malformed arguments. */
+export class InvalidArgumentsError extends Error {
+ readonly code = "AISOC_INVALID_ARGS";
+ constructor(public readonly tool: string, public readonly issues: string[]) {
+ super(`Invalid arguments to ${tool}: ${issues.join("; ")}`);
+ this.name = "InvalidArgumentsError";
+ }
+}
+
+function formatCause(cause: unknown): string {
+ if (cause instanceof Error) return cause.message;
+ if (typeof cause === "string") return cause;
+ try {
+ return JSON.stringify(cause);
+ } catch {
+ return String(cause);
+ }
+}
+
+/**
+ * Map any error into a string suitable for an MCP tool failure message.
+ * We never include credentials, but we do include the endpoint + status so
+ * the agent can troubleshoot itself.
+ */
+export function formatErrorForTool(err: unknown): string {
+ if (err instanceof MissingApiKeyError) return err.message;
+ if (err instanceof TransportError) return err.message;
+ if (err instanceof ApiError) {
+ if (err.isAuthFailure) {
+ return (
+ `${err.message}. The configured API key is missing or has insufficient ` +
+ `scopes for this tool. Verify the key has the required scope (alerts:read, ` +
+ `cases:read, cases:write, detections:read, etc.).`
+ );
+ }
+ return err.message;
+ }
+ if (err instanceof InvalidArgumentsError) return err.message;
+ if (err instanceof Error) return err.message;
+ return String(err);
+}
diff --git a/services/mcp/src/index.ts b/services/mcp/src/index.ts
new file mode 100644
index 000000000..7f7dc1974
--- /dev/null
+++ b/services/mcp/src/index.ts
@@ -0,0 +1,191 @@
+#!/usr/bin/env node
+/**
+ * @aisoc/mcp — entry point.
+ *
+ * Subcommands:
+ *
+ * serve Run the stdio MCP server (default if no command given).
+ * install Configure a host (Claude / Cursor / Cody / Continue) to launch us.
+ * doctor Pre-flight: env, network, auth.
+ * help Print this help.
+ * version Print the package version.
+ *
+ * Why a hand-rolled parser instead of commander/yargs:
+ * 1. We are publishing to npm as `npx @aisoc/mcp`. Every dep we add lengthens
+ * the cold-install path users see when invoking us through Claude/Cursor.
+ * The full parser we need fits in ~80 lines.
+ * 2. `config.parseArgs` is shared by `serve` and `doctor`, so the surface
+ * stays consistent.
+ */
+import process from "node:process";
+
+import { type ParsedArgs, parseArgs, packageVersion, resolveConfig, makeLogger } from "./config.js";
+import { runDoctor, printDoctorReport } from "./doctor.js";
+import { runServer } from "./server.js";
+import { install, knownConfigPaths, type Host } from "./installers/index.js";
+
+async function main(): Promise<void> {
+ const argv = process.argv.slice(2);
+ const args = parseArgs(argv);
+
+ if (args.flags.help === true || args.command === "help") {
+ printHelp();
+ return;
+ }
+ if (args.flags.version === true || args.command === "version") {
+ process.stdout.write(`${packageVersion()}\n`);
+ return;
+ }
+
+ switch (args.command) {
+ case "serve":
+ await cmdServe(args);
+ return;
+ case "doctor":
+ await cmdDoctor(args);
+ return;
+ case "install":
+ await cmdInstall(args);
+ return;
+ default: {
+ // Should be unreachable; parseArgs collapses unknowns to "help".
+ const _exhaustive: never = args.command as never;
+ void _exhaustive;
+ printHelp();
+ process.exitCode = 2;
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// serve
+// ---------------------------------------------------------------------------
+
+async function cmdServe(args: ParsedArgs): Promise<void> {
+ const cfg = resolveConfig(args);
+ const log = makeLogger(cfg);
+ // No banner on stdout — that channel is reserved for JSON-RPC frames.
+ // `runServer` logs its lifecycle to stderr.
+ await runServer(cfg, log);
+}
+
+// ---------------------------------------------------------------------------
+// doctor
+// ---------------------------------------------------------------------------
+
+async function cmdDoctor(args: ParsedArgs): Promise<void> {
+ const cfg = resolveConfig(args);
+ // doctor prints a human report on stdout (it's a CLI command, not an MCP
+ // session), so the logger is configured to forward its own output to stderr
+ // only when --verbose is passed.
+ const log = makeLogger(cfg);
+ const report = await runDoctor(cfg, log);
+ printDoctorReport(report);
+ if (!report.ok) process.exitCode = 1;
+}
+
+// ---------------------------------------------------------------------------
+// install
+// ---------------------------------------------------------------------------
+
+async function cmdInstall(args: ParsedArgs): Promise<void> {
+ const hostFlag = String(args.flags.host ?? args.positional[0] ?? "").toLowerCase();
+ if (args.flags["list-paths"] === true) {
+ const paths = knownConfigPaths();
+ process.stdout.write(JSON.stringify(paths, null, 2) + "\n");
+ return;
+ }
+ if (!isHost(hostFlag)) {
+ process.stderr.write(
+ [
+ "aisoc-mcp install — choose a host:",
+ " --host claude Claude Desktop",
+ " --host cursor Cursor IDE",
+ " --host continue Continue.dev",
+ " --host cody Sourcegraph Cody (prints snippet)",
+ "",
+ " --aisoc-url <url> AiSOC API base URL (default http://localhost:8081)",
+ " --api-key <token> API key to embed (or set AISOC_API_KEY)",
+ " --dry-run Show what would be written without changing files",
+ " --list-paths Print where each host's config lives, as JSON",
+ "",
+ ].join("\n"),
+ );
+ process.exitCode = 2;
+ return;
+ }
+
+ const cfg = resolveConfig(args);
+ const dryRun = args.flags["dry-run"] === true;
+ let result;
+ try {
+ result = install({ host: hostFlag, cfg, dryRun });
+ } catch (err) {
+ process.stderr.write(`install failed: ${(err as Error).message}\n`);
+ process.exitCode = 1;
+ return;
+ }
+
+ if (dryRun) {
+ process.stdout.write(
+ `[dry-run] would write to ${result.configPath ?? "(no file)"}\n` +
+ JSON.stringify({ aisoc: result.snippet }, null, 2) +
+ "\n",
+ );
+ return;
+ }
+
+ process.stdout.write(`${result.message}\n`);
+}
+
+function isHost(s: string): s is Host {
+ return s === "claude" || s === "cursor" || s === "cody" || s === "continue";
+}
+
+// ---------------------------------------------------------------------------
+// help
+// ---------------------------------------------------------------------------
+
+function printHelp(): void {
+ process.stdout.write(
+ [
+ "@aisoc/mcp — connect AiSOC to MCP-aware assistants",
+ "",
+ "Usage:",
+ " npx @aisoc/mcp <command> [options]",
+ "",
+ "Commands:",
+ " serve Run the stdio MCP server (default).",
+ " install --host <h> Configure Claude Desktop / Cursor / Continue / Cody to launch this server.",
+ " doctor Verify env, network reachability, and AiSOC API auth.",
+ " help Show this message.",
+ " version Print the package version.",
+ "",
+ "Common options:",
+ " --aisoc-url <url> Base URL of the AiSOC API. Env: AISOC_URL.",
+ " Default: http://localhost:8081",
+ " --api-key <token> API key (aisoc_… or JWT). Env: AISOC_API_KEY.",
+ " --timeout <ms> Per-request timeout. Env: AISOC_TIMEOUT_MS. Default 20000.",
+ " --verbose Log lifecycle events to stderr.",
+ "",
+ "Examples:",
+ " npx @aisoc/mcp install --host claude --aisoc-url https://aisoc.acme.corp --api-key aisoc_xxxx",
+ " AISOC_URL=https://aisoc.acme.corp AISOC_API_KEY=aisoc_xxxx npx @aisoc/mcp doctor",
+ " npx @aisoc/mcp serve # invoked by the host, not by you",
+ "",
+ ].join("\n"),
+ );
+}
+
+// ---------------------------------------------------------------------------
+// boot
+// ---------------------------------------------------------------------------
+
+main().catch((err: unknown) => {
+ // Last-resort handler. `runServer` and `runDoctor` already format their own
+ // errors; this catches programmer mistakes that escape both. We write to
+ // stderr so we don't poison the JSON-RPC stream if this fires during serve.
+ const msg = err instanceof Error ? err.stack ?? err.message : String(err);
+ process.stderr.write(`aisoc-mcp: fatal: ${msg}\n`);
+ process.exit(1);
+});
diff --git a/services/mcp/src/installers/index.ts b/services/mcp/src/installers/index.ts
new file mode 100644
index 000000000..6d9fac7b1
--- /dev/null
+++ b/services/mcp/src/installers/index.ts
@@ -0,0 +1,242 @@
+/**
+ * `aisoc-mcp install` — write a configured server entry into the host's
+ * MCP config file so users don't have to hand-edit JSON.
+ *
+ * We support four hosts on first ship:
+ *
+ * - Claude Desktop (`~/Library/Application Support/Claude/claude_desktop_config.json`
+ * on macOS, `%APPDATA%\Claude\claude_desktop_config.json` on Windows)
+ * - Cursor (`~/.cursor/mcp.json`)
+ * - Cody (extension config, prints instructions only)
+ * - Continue (`~/.continue/config.json`)
+ *
+ * For Cody we don't have a stable JSON config path that's safe to write to
+ * (the extension reads VS Code settings); we surface the snippet to paste
+ * instead. That's still a 30-second improvement over hunting it down on
+ * the docs site.
+ */
+import * as fs from "node:fs";
+import * as os from "node:os";
+import * as path from "node:path";
+
+import type { ServerConfig } from "../config.js";
+
+export type Host = "claude" | "cursor" | "cody" | "continue";
+
+export interface InstallOptions {
+ host: Host;
+ cfg: ServerConfig;
+ /** Override config-file location (used by tests). */
+ configPath?: string;
+ /** If true, print what we would do without writing. */
+ dryRun?: boolean;
+}
+
+export interface InstallResult {
+ host: Host;
+ /** Where we wrote (or would have written). May be absent for Cody. */
+ configPath?: string;
+ /** True if we wrote a new server entry; false if it was already present. */
+ changed: boolean;
+ /** Human-readable next steps for the user. */
+ message: string;
+ /** The JSON snippet we wrote, for display / dry-run. */
+ snippet: Record<string, unknown>;
+}
+
+/**
+ * Install the AiSOC server into the requested host. Idempotent: re-running
+ * with the same arguments is a no-op (returns `changed: false`).
+ */
+export function install(opts: InstallOptions): InstallResult {
+ const snippet = buildServerSnippet(opts.cfg);
+ switch (opts.host) {
+ case "claude":
+ return installToJsonConfig({
+ host: "claude",
+ configPath: opts.configPath ?? claudeConfigPath(),
+ rootKey: "mcpServers",
+ serverName: "aisoc",
+ snippet,
+ dryRun: opts.dryRun,
+ followUp:
+ "Restart Claude Desktop (Cmd+Q then reopen) so it re-reads the config.",
+ });
+ case "cursor":
+ return installToJsonConfig({
+ host: "cursor",
+ configPath: opts.configPath ?? cursorConfigPath(),
+ rootKey: "mcpServers",
+ serverName: "aisoc",
+ snippet,
+ dryRun: opts.dryRun,
+ followUp:
+ "Open Cursor → Settings → MCP and confirm the `aisoc` server shows green.",
+ });
+ case "continue":
+ return installToJsonConfig({
+ host: "continue",
+ configPath: opts.configPath ?? continueConfigPath(),
+ rootKey: "mcpServers",
+ serverName: "aisoc",
+ snippet,
+ dryRun: opts.dryRun,
+ followUp:
+ "Reload the Continue panel (Cmd/Ctrl+Shift+P → 'Continue: Reload Window').",
+ });
+ case "cody":
+ // Cody currently reads MCP config from VS Code settings JSON. We don't
+ // attempt to merge into that (too many user-specific shapes), and instead
+ // print the snippet to paste under "cody.mcp.servers". That's documented
+ // here so we can flip to direct write once the schema stabilises.
+ return {
+ host: "cody",
+ changed: false,
+ snippet,
+ message: [
+ "Cody reads MCP config from VS Code settings.",
+ "Paste this under `cody.mcp.servers` in your User Settings (JSON):",
+ "",
+ JSON.stringify({ aisoc: snippet }, null, 2),
+ ].join("\n"),
+ };
+ }
+}
+
+// ---------------------------------------------------------------------------
+// snippet construction
+// ---------------------------------------------------------------------------
+
+/**
+ * Produce the per-server JSON entry. We launch via `npx @aisoc/mcp serve`
+ * so the user never has to install us globally — they update by `npx`
+ * picking up the latest. URL/key/timeout/verbose flow in via env to keep
+ * the command line short and the secret out of `ps`.
+ */
+function buildServerSnippet(cfg: ServerConfig): Record<string, unknown> {
+ const env: Record<string, string> = { AISOC_URL: cfg.aisocUrl };
+ if (cfg.apiKey) env.AISOC_API_KEY = cfg.apiKey;
+ if (cfg.timeoutMs && cfg.timeoutMs !== 20_000) {
+ env.AISOC_TIMEOUT_MS = String(cfg.timeoutMs);
+ }
+ if (cfg.verbose) env.AISOC_VERBOSE = "1";
+ return {
+ command: "npx",
+ args: ["-y", "@aisoc/mcp", "serve"],
+ env,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// JSON-config writer
+// ---------------------------------------------------------------------------
+
+interface JsonInstallArgs {
+ host: Host;
+ configPath: string;
+ rootKey: string;
+ serverName: string;
+ snippet: Record<string, unknown>;
+ dryRun?: boolean;
+ followUp: string;
+}
+
+function installToJsonConfig(args: JsonInstallArgs): InstallResult {
+ const existing = readJsonOrEmpty(args.configPath);
+ const root = (existing[args.rootKey] as Record<string, unknown> | undefined) ??
+ {};
+ const previous = root[args.serverName];
+ const hadPrevious = previous !== undefined && previous !== null;
+ const before = JSON.stringify(previous ?? null);
+ root[args.serverName] = args.snippet;
+ const after = JSON.stringify(root[args.serverName]);
+ const changed = before !== after;
+
+ if (!args.dryRun && changed) {
+ existing[args.rootKey] = root;
+ fs.mkdirSync(path.dirname(args.configPath), { recursive: true });
+ fs.writeFileSync(
+ args.configPath,
+ JSON.stringify(existing, null, 2) + "\n",
+ { encoding: "utf8", mode: 0o600 },
+ );
+ }
+
+ // We distinguish "first install" (no prior entry) from "update" (entry
+ // existed and we replaced it) so the operator log line tells them what
+ // actually happened. Both paths still set `changed: true`.
+ const verb = changed ? (hadPrevious ? "Updated" : "Wrote") : "Found";
+ return {
+ host: args.host,
+ configPath: args.configPath,
+ changed,
+ snippet: args.snippet,
+ message: changed
+ ? [
+ `${verb} ${args.host} MCP config at ${args.configPath}.`,
+ args.followUp,
+ ].join("\n")
+ : `Already configured at ${args.configPath} — nothing to do.`,
+ };
+}
+
+function readJsonOrEmpty(p: string): Record<string, unknown> {
+ try {
+ const buf = fs.readFileSync(p, "utf8");
+ const v = JSON.parse(buf);
+ return typeof v === "object" && v !== null ? (v as Record<string, unknown>) : {};
+ } catch (err) {
+ // ENOENT or parse error → treat as fresh config. We log nothing; the
+ // installer's caller surfaces the resulting message.
+ if (
+ err instanceof Error &&
+ "code" in err &&
+ (err as NodeJS.ErrnoException).code === "ENOENT"
+ ) {
+ return {};
+ }
+ if (err instanceof SyntaxError) {
+ // Don't silently destroy a malformed config; refuse instead.
+ throw new Error(
+ `Refusing to overwrite ${p}: file exists but is not valid JSON. Fix or delete it, then re-run.`,
+ );
+ }
+ return {};
+ }
+}
+
+// ---------------------------------------------------------------------------
+// per-host config paths
+// ---------------------------------------------------------------------------
+
+function claudeConfigPath(): string {
+ const home = os.homedir();
+ if (process.platform === "darwin") {
+ return path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
+ }
+ if (process.platform === "win32") {
+ const appData = process.env.APPDATA ?? path.join(home, "AppData", "Roaming");
+ return path.join(appData, "Claude", "claude_desktop_config.json");
+ }
+ // Linux build of Claude Desktop is unofficial; fall back to XDG.
+ const xdg = process.env.XDG_CONFIG_HOME ?? path.join(home, ".config");
+ return path.join(xdg, "Claude", "claude_desktop_config.json");
+}
+
+function cursorConfigPath(): string {
+ return path.join(os.homedir(), ".cursor", "mcp.json");
+}
+
+function continueConfigPath(): string {
+ return path.join(os.homedir(), ".continue", "config.json");
+}
+
+/** Exposed for `aisoc-mcp install --list-paths` and tests. */
+export function knownConfigPaths(): Record<Host, string | null> {
+ return {
+ claude: claudeConfigPath(),
+ cursor: cursorConfigPath(),
+ continue: continueConfigPath(),
+ cody: null,
+ };
+}
diff --git a/services/mcp/src/server.ts b/services/mcp/src/server.ts
new file mode 100644
index 000000000..7d7c33ddc
--- /dev/null
+++ b/services/mcp/src/server.ts
@@ -0,0 +1,213 @@
+/**
+ * MCP server wiring.
+ *
+ * Bridges the AiSOC tool registry (`./tools/index.ts`) to the
+ * `@modelcontextprotocol/sdk` server, exposing two request handlers:
+ *
+ * - `tools/list` → advertise every tool's name + JSON Schema.
+ * - `tools/call` → validate args with the tool's zod schema, dispatch
+ * to the handler, and wrap the result in MCP's
+ * `CallToolResult` shape (text content + isError).
+ *
+ * Why we wrap manually instead of using the high-level `McpServer` helper:
+ *
+ * 1. The high-level helper insists on declaring tool metadata as the
+ * tools register; we already keep that metadata next to each tool
+ * handler in `./tools/`. Wrapping the low-level `Server` keeps a
+ * single source of truth.
+ * 2. We want first-class control over how tool errors are surfaced —
+ * `formatErrorForTool` produces a stable, audit-friendly message
+ * that the agent can act on (auth failures suggest scope fixes,
+ * transport errors mention the URL, etc.).
+ * 3. The arg validation step uses the tool's exact zod schema so failures
+ * report which fields were wrong, not "schema mismatch".
+ *
+ * Stdio discipline: the SDK already wires JSON-RPC to stdout via
+ * `StdioServerTransport`; we never log to stdout from our code.
+ */
+import { Server } from "@modelcontextprotocol/sdk/server/index.js";
+import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
+import {
+ CallToolRequestSchema,
+ ListToolsRequestSchema,
+} from "@modelcontextprotocol/sdk/types.js";
+
+import { AisocClient } from "./client.js";
+import { type ServerConfig, type Logger, packageVersion } from "./config.js";
+import {
+ ApiError,
+ InvalidArgumentsError,
+ MissingApiKeyError,
+ TransportError,
+ formatErrorForTool,
+} from "./errors.js";
+import { ALL_TOOLS, TOOL_BY_NAME } from "./tools/index.js";
+import type { ToolResult } from "./tools/types.js";
+
+/** Server instructions surfaced to MCP hosts during initialisation. */
+const SERVER_INSTRUCTIONS = `\
+AiSOC exposes alerts, cases, detection rules, and the agent decision ledger
+through this MCP server. Typical workflows:
+
+ 1. Triage: aisoc_list_alerts → aisoc_get_alert
+ 2. Investigate: aisoc_list_cases → aisoc_run_investigation → aisoc_replay_decision
+ 3. Audit a step: aisoc_explain_step (returns the prompt, response, and tools used)
+ 4. Tune rules: aisoc_query_detections → aisoc_get_detection_rule
+
+Every agent decision in AiSOC is logged to a persistent ledger; \
+\`aisoc_replay_decision\` and \`aisoc_explain_step\` are the auditable surface.`;
+
+/**
+ * Build (but don't start) an MCP server bound to the AiSOC tool registry.
+ *
+ * Exported separately from the start helper so tests can drive request
+ * handlers without spinning up a real stdio transport.
+ */
+export function buildServer(cfg: ServerConfig, log: Logger): Server {
+ const client = new AisocClient(cfg, log);
+ const server = new Server(
+ { name: "@aisoc/mcp", version: packageVersion() },
+ {
+ capabilities: { tools: {} },
+ instructions: SERVER_INSTRUCTIONS,
+ },
+ );
+
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
+ return {
+ tools: ALL_TOOLS.map((t) => ({
+ name: t.metadata.name,
+ description: t.metadata.description,
+ inputSchema: t.metadata.inputSchema as { type: "object" } & Record<
+ string,
+ unknown
+ >,
+ })),
+ };
+ });
+
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
+ const name = request.params.name;
+ const tool = TOOL_BY_NAME[name];
+ if (!tool) {
+ // Unknown tool. Return as a tool-failure rather than throwing so the
+ // agent gets a clear human message instead of a transport error.
+ return toErrorResult(
+ `Unknown tool: ${name}. Call tools/list to see what's available.`,
+ );
+ }
+
+ // Validate via zod. Failed validation gives precise per-field issues.
+ const parse = tool.schema.safeParse(request.params.arguments ?? {});
+ if (!parse.success) {
+ const issues = parse.error.issues.map(
+ (i) => `${i.path.join(".") || "<root>"}: ${i.message}`,
+ );
+ return toErrorResult(
+ formatErrorForTool(new InvalidArgumentsError(name, issues)),
+ );
+ }
+
+ try {
+ const result = await tool.handle({ client, log }, parse.data);
+ return toSuccessResult(result);
+ } catch (err) {
+ // Log full error to stderr for debugging; surface a sanitised message
+ // to the agent. We deliberately don't include stack traces in the
+ // MCP response (PII / secrets risk).
+ log.error(`tool ${name} failed`, err);
+
+ // Auth failures surface a hint about scopes via formatErrorForTool.
+ if (
+ err instanceof MissingApiKeyError ||
+ err instanceof TransportError ||
+ err instanceof ApiError ||
+ err instanceof InvalidArgumentsError
+ ) {
+ return toErrorResult(formatErrorForTool(err));
+ }
+ return toErrorResult(formatErrorForTool(err));
+ }
+ });
+
+ return server;
+}
+
+/**
+ * Boot the server on stdio. Resolves once the transport closes (process
+ * shutdown) so callers can `await` for the lifecycle.
+ */
+export async function runServer(cfg: ServerConfig, log: Logger): Promise<void> {
+ const server = buildServer(cfg, log);
+ const transport = new StdioServerTransport();
+ await server.connect(transport);
+ log.info(`aisoc-mcp ${packageVersion()} ready on stdio (target ${cfg.aisocUrl})`);
+ // The SDK keeps Node alive while stdin is open; we just need to wait for
+ // close. Setting up a manual promise here also lets us surface SIGINT
+ // cleanly.
+ await new Promise<void>((resolve) => {
+ transport.onclose = () => {
+ log.info("transport closed; shutting down");
+ resolve();
+ };
+ const onSignal = (sig: string) => {
+ log.info(`received ${sig}, closing transport`);
+ transport.close().catch(() => {
+ /* swallow — we're exiting anyway */
+ });
+ };
+ process.once("SIGINT", () => onSignal("SIGINT"));
+ process.once("SIGTERM", () => onSignal("SIGTERM"));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Result envelope helpers
+// ---------------------------------------------------------------------------
+
+/**
+ * Convert a `ToolResult` into the MCP `CallToolResult` shape. JSON results
+ * become a fenced JSON code block so MCP hosts that render Markdown still
+ * show structured data; text results pass through verbatim. We also include
+ * `structuredContent` (the raw JSON) when present, so MCP-aware hosts that
+ * support the field can render it natively.
+ */
+function toSuccessResult(result: ToolResult): {
+ content: Array<{ type: "text"; text: string }>;
+ structuredContent?: unknown;
+ isError?: false;
+} {
+ if (result.kind === "json") {
+ const text = renderJson(result.data);
+ return {
+ content: [{ type: "text", text }],
+ structuredContent:
+ // Only surface as structuredContent if it's an object, per spec.
+ typeof result.data === "object" && result.data !== null
+ ? (result.data as Record<string, unknown>)
+ : undefined,
+ };
+ }
+ return {
+ content: [{ type: "text", text: result.text }],
+ structuredContent:
+ typeof result.data === "object" && result.data !== null
+ ? (result.data as Record<string, unknown>)
+ : undefined,
+ };
+}
+
+function toErrorResult(text: string): {
+ content: Array<{ type: "text"; text: string }>;
+ isError: true;
+} {
+ return { content: [{ type: "text", text }], isError: true };
+}
+
+function renderJson(data: unknown): string {
+ // Pretty-print with a 2-space indent. We don't truncate here — each tool
+ // is responsible for shaping its output to fit MCP context budgets — but
+ // we wrap in a fenced block so hosts render it as code.
+ const body = JSON.stringify(data, null, 2);
+ return "```json\n" + body + "\n```";
+}
diff --git a/services/mcp/src/tools/alerts.ts b/services/mcp/src/tools/alerts.ts
new file mode 100644
index 000000000..9ed02ec43
--- /dev/null
+++ b/services/mcp/src/tools/alerts.ts
@@ -0,0 +1,253 @@
+/**
+ * Alert-facing tools.
+ *
+ * `aisoc_list_alerts` is the workhorse for triage assistants — agents call
+ * it as the first probe to ask "what's open right now?" so we keep the
+ * arguments tight (severity, status, search) and return a normalised
+ * subset rather than streaming the full DB row, both to save tokens and
+ * to avoid leaking columns the API may add later that the agent shouldn't
+ * see.
+ *
+ * `aisoc_get_alert` is the deep-dive: when an agent zeroes in on an alert
+ * id from the list, it pulls the full record (including `ai_summary` and
+ * MITRE mappings) so it can reason about response steps.
+ */
+import { z } from "zod";
+
+import type { ToolDefinition } from "./types.js";
+import { json } from "./types.js";
+
+// ---------------------------------------------------------------------------
+// Shared response shape — matches `app.api.v1.endpoints.alerts.AlertResponse`
+// at the time of writing. Intentionally `Record<string, unknown>`-ish so a
+// new API field doesn't break existing MCP clients.
+// ---------------------------------------------------------------------------
+
+interface AlertResponse {
+ id: string;
+ title: string;
+ description: string | null;
+ severity: string;
+ status: string;
+ priority: number;
+ category: string | null;
+ mitre_tactics: string[];
+ mitre_techniques: string[];
+ ai_summary: string | null;
+ affected_ips: unknown[];
+ affected_hosts: unknown[];
+ affected_users: unknown[];
+ case_id: string | null;
+ tags: string[];
+ event_time: string;
+ created_at: string;
+ [key: string]: unknown;
+}
+
+interface AlertListResponse {
+ items: AlertResponse[];
+ total: number;
+ page: number;
+ page_size: number;
+ pages: number;
+}
+
+// ---------------------------------------------------------------------------
+// aisoc_list_alerts
+// ---------------------------------------------------------------------------
+
+const ListAlertsSchema = z
+ .object({
+ severity: z
+ .enum(["critical", "high", "medium", "low", "info"])
+ .optional()
+ .describe("Filter by severity. Omit to include all severities."),
+ status: z
+ .enum(["new", "open", "in_progress", "resolved", "closed", "dismissed"])
+ .optional()
+ .describe("Filter by alert status. Omit for all statuses."),
+ category: z.string().optional().describe("Filter by category (e.g. `endpoint`, `cloud`)."),
+ search: z.string().optional().describe("Substring match on title/description."),
+ assigned_to_me: z
+ .boolean()
+ .optional()
+ .describe("If true, only alerts assigned to the calling user."),
+ page: z.number().int().min(1).max(1000).default(1),
+ page_size: z
+ .number()
+ .int()
+ .min(1)
+ .max(50)
+ .default(25)
+ .describe("Capped at 50 to keep MCP context budgets sane."),
+ })
+ .strict();
+
+export const listAlertsTool: ToolDefinition<typeof ListAlertsSchema> = {
+ metadata: {
+ name: "aisoc_list_alerts",
+ description:
+ "List security alerts in the connected AiSOC tenant. Filter by severity, status, category, or free-text search. Results are paginated; default page_size 25.",
+ inputSchema: zodToJsonSchema(ListAlertsSchema),
+ },
+ schema: ListAlertsSchema,
+ async handle(ctx, args) {
+ const data = await ctx.client.get<AlertListResponse>("/api/v1/alerts", {
+ query: {
+ severity: args.severity,
+ status: args.status,
+ category: args.category,
+ search: args.search,
+ assigned_to_me: args.assigned_to_me,
+ page: args.page,
+ page_size: args.page_size,
+ },
+ });
+
+ // Normalise to a tighter view — keeps token counts down for big lists.
+ return json({
+ total: data.total,
+ page: data.page,
+ page_size: data.page_size,
+ pages: data.pages,
+ items: data.items.map(summariseAlert),
+ });
+ },
+};
+
+// ---------------------------------------------------------------------------
+// aisoc_get_alert
+// ---------------------------------------------------------------------------
+
+const GetAlertSchema = z
+ .object({
+ alert_id: z
+ .string()
+ .uuid()
+ .describe("UUID of the alert as returned from `aisoc_list_alerts`."),
+ })
+ .strict();
+
+export const getAlertTool: ToolDefinition<typeof GetAlertSchema> = {
+ metadata: {
+ name: "aisoc_get_alert",
+ description:
+ "Fetch the full record for a single alert: AI summary, MITRE mappings, affected assets, and current case linkage.",
+ inputSchema: zodToJsonSchema(GetAlertSchema),
+ },
+ schema: GetAlertSchema,
+ async handle(ctx, args) {
+ const alert = await ctx.client.get<AlertResponse>(`/api/v1/alerts/${args.alert_id}`);
+ return json(alert);
+ },
+};
+
+// ---------------------------------------------------------------------------
+// helpers
+// ---------------------------------------------------------------------------
+
+function summariseAlert(a: AlertResponse): Record<string, unknown> {
+ return {
+ id: a.id,
+ title: a.title,
+ severity: a.severity,
+ status: a.status,
+ priority: a.priority,
+ category: a.category,
+ mitre_tactics: a.mitre_tactics,
+ mitre_techniques: a.mitre_techniques,
+ ai_summary: a.ai_summary,
+ case_id: a.case_id,
+ tags: a.tags,
+ event_time: a.event_time,
+ };
+}
+
+/**
+ * Local zod→JSON-Schema converter. We keep this in the tools layer so the
+ * server doesn't have to import zod itself; we only need a subset of the
+ * spec (object types with strings/numbers/enums/booleans) which is easier
+ * to maintain than pulling in `zod-to-json-schema` (~30kB for what we use).
+ *
+ * If we hit a corner case the tool layer needs (recursive types, unions of
+ * objects, etc.) we'll switch to the dedicated package; for now the strict
+ * argument schemas stay simple enough for this to hold.
+ *
+ * Exported so other tool files can reuse it (see `cases.ts`, `investigations.ts`).
+ */
+export function zodToJsonSchema(schema: z.ZodTypeAny): Record<string, unknown> {
+ return zodToJson(schema);
+}
+
+function zodToJson(schema: z.ZodTypeAny): Record<string, unknown> {
+ const def = schema._def as { typeName: string } & Record<string, unknown>;
+ switch (def.typeName) {
+ case "ZodObject": {
+ const shape = (schema as unknown as { shape: Record<string, z.ZodTypeAny> }).shape;
+ const properties: Record<string, unknown> = {};
+ const required: string[] = [];
+ for (const [key, child] of Object.entries(shape)) {
+ properties[key] = zodToJson(child);
+ if (!child.isOptional()) required.push(key);
+ }
+ const out: Record<string, unknown> = {
+ type: "object",
+ properties,
+ additionalProperties: false,
+ };
+ if (required.length > 0) out.required = required;
+ return out;
+ }
+ case "ZodString": {
+ const checks = (def.checks ?? []) as Array<{ kind: string }>;
+ const out: Record<string, unknown> = { type: "string" };
+ if (checks.some((c) => c.kind === "uuid")) out.format = "uuid";
+ const description = (schema as unknown as { description?: string }).description;
+ if (description) out.description = description;
+ return out;
+ }
+ case "ZodNumber": {
+ const out: Record<string, unknown> = { type: "number" };
+ const checks = (def.checks ?? []) as Array<{ kind: string; value?: number; inclusive?: boolean }>;
+ if (checks.some((c) => c.kind === "int")) out.type = "integer";
+ for (const check of checks) {
+ if (check.kind === "min" && typeof check.value === "number") out.minimum = check.value;
+ if (check.kind === "max" && typeof check.value === "number") out.maximum = check.value;
+ }
+ const description = (schema as unknown as { description?: string }).description;
+ if (description) out.description = description;
+ return out;
+ }
+ case "ZodBoolean": {
+ const out: Record<string, unknown> = { type: "boolean" };
+ const description = (schema as unknown as { description?: string }).description;
+ if (description) out.description = description;
+ return out;
+ }
+ case "ZodEnum": {
+ const values = (def.values ?? []) as string[];
+ const out: Record<string, unknown> = { type: "string", enum: values };
+ const description = (schema as unknown as { description?: string }).description;
+ if (description) out.description = description;
+ return out;
+ }
+ case "ZodOptional": {
+ const inner = (def.innerType ?? schema) as z.ZodTypeAny;
+ return zodToJson(inner);
+ }
+ case "ZodDefault": {
+ const inner = (def.innerType ?? schema) as z.ZodTypeAny;
+ const defVal = (def.defaultValue as () => unknown)();
+ return { ...zodToJson(inner), default: defVal };
+ }
+ case "ZodArray": {
+ const inner = (def.type ?? schema) as z.ZodTypeAny;
+ return { type: "array", items: zodToJson(inner) };
+ }
+ default:
+ // Conservative fallback — describe as JSON of any shape. The MCP host
+ // will still call the tool and zod's runtime parse will catch
+ // anything genuinely malformed.
+ return { description: `Unsupported schema type ${def.typeName}` };
+ }
+}
diff --git a/services/mcp/src/tools/cases.ts b/services/mcp/src/tools/cases.ts
new file mode 100644
index 000000000..36b6b2ce4
--- /dev/null
+++ b/services/mcp/src/tools/cases.ts
@@ -0,0 +1,193 @@
+/**
+ * Case-facing tools.
+ *
+ * `aisoc_list_cases` and `aisoc_get_case` mirror the alerts tools.
+ * `aisoc_run_investigation` is the marquee tool — it kicks off the AiSOC
+ * investigator agent on a case and returns the run_id that the agent can
+ * subsequently poll via `aisoc_replay_decision`.
+ *
+ * Note on streaming: the FastAPI `/cases/{id}/investigate` endpoint
+ * returns immediately with a run_id and status `started`. We do *not*
+ * stream the live agent events back through MCP because the spec's
+ * single-shot tool-call shape doesn't fit a long-running stream cleanly,
+ * and MCP hosts vary in how they handle pending tool results. Instead we
+ * return the run_id and let the agent poll with the dedicated investigation
+ * tools — that pattern composes well in chat ("kick it off, and check on
+ * it in 30 seconds").
+ */
+import { z } from "zod";
+
+import { zodToJsonSchema } from "./alerts.js";
+import type { ToolDefinition } from "./types.js";
+import { json } from "./types.js";
+
+interface CaseResponse {
+ id: string;
+ case_number: string;
+ title: string;
+ description: string | null;
+ status: string;
+ priority: string;
+ severity: string;
+ case_type: string | null;
+ alert_ids: string[];
+ tags: string[];
+ assigned_to_id: string | null;
+ resolution: string | null;
+ lessons_learned: string | null;
+ created_at: string;
+ closed_at: string | null;
+ [key: string]: unknown;
+}
+
+interface CaseListResponse {
+ items: CaseResponse[];
+ total: number;
+ page: number;
+ page_size: number;
+ pages: number;
+}
+
+interface InvestigateResponse {
+ run_id: string;
+ case_id: string;
+ status: string;
+ message: string;
+}
+
+// ---------------------------------------------------------------------------
+// aisoc_list_cases
+// ---------------------------------------------------------------------------
+
+const ListCasesSchema = z
+ .object({
+ status: z.enum(["new", "open", "investigating", "containment", "eradication", "recovery", "closed", "cancelled"]).optional(),
+ priority: z.enum(["p0", "p1", "p2", "p3"]).optional(),
+ assigned_to_me: z.boolean().optional(),
+ page: z.number().int().min(1).max(1000).default(1),
+ page_size: z.number().int().min(1).max(50).default(25),
+ })
+ .strict();
+
+export const listCasesTool: ToolDefinition<typeof ListCasesSchema> = {
+ metadata: {
+ name: "aisoc_list_cases",
+ description:
+ "List security cases (incidents). Filter by status, priority, or assigned-to-me. Cases are higher-level groupings of related alerts.",
+ inputSchema: zodToJsonSchema(ListCasesSchema),
+ },
+ schema: ListCasesSchema,
+ async handle(ctx, args) {
+ const data = await ctx.client.get<CaseListResponse>("/api/v1/cases", {
+ query: {
+ status: args.status,
+ priority: args.priority,
+ assigned_to_me: args.assigned_to_me,
+ page: args.page,
+ page_size: args.page_size,
+ },
+ });
+ return json({
+ total: data.total,
+ page: data.page,
+ page_size: data.page_size,
+ pages: data.pages,
+ items: data.items.map(summariseCase),
+ });
+ },
+};
+
+// ---------------------------------------------------------------------------
+// aisoc_get_case
+// ---------------------------------------------------------------------------
+
+const GetCaseSchema = z
+ .object({
+ case_id: z.string().uuid().describe("UUID of the case (from `aisoc_list_cases`)."),
+ include_timeline: z
+ .boolean()
+ .default(false)
+ .describe("If true, also include the case timeline (comments + events)."),
+ })
+ .strict();
+
+export const getCaseTool: ToolDefinition<typeof GetCaseSchema> = {
+ metadata: {
+ name: "aisoc_get_case",
+ description:
+ "Fetch a case by id. Optionally include the timeline of comments, status changes, and analyst actions.",
+ inputSchema: zodToJsonSchema(GetCaseSchema),
+ },
+ schema: GetCaseSchema,
+ async handle(ctx, args) {
+ const caseRecord = await ctx.client.get<CaseResponse>(`/api/v1/cases/${args.case_id}`);
+ let timeline: unknown = undefined;
+ if (args.include_timeline) {
+ timeline = await ctx.client.get<unknown[]>(`/api/v1/cases/${args.case_id}/timeline`);
+ }
+ return json({ case: caseRecord, timeline });
+ },
+};
+
+// ---------------------------------------------------------------------------
+// aisoc_run_investigation
+// ---------------------------------------------------------------------------
+
+const RunInvestigationSchema = z
+ .object({
+ case_id: z.string().uuid().describe("UUID of the case to investigate."),
+ alert_summary: z
+ .string()
+ .optional()
+ .describe(
+ "Optional human-readable summary used to seed the recon agent. If omitted, AiSOC builds one from linked alerts.",
+ ),
+ })
+ .strict();
+
+export const runInvestigationTool: ToolDefinition<typeof RunInvestigationSchema> = {
+ metadata: {
+ name: "aisoc_run_investigation",
+ description:
+ "Kick off the AiSOC multi-agent investigator on a case. Returns a run_id immediately; use `aisoc_replay_decision` to fetch the resulting decision ledger.",
+ inputSchema: zodToJsonSchema(RunInvestigationSchema),
+ },
+ schema: RunInvestigationSchema,
+ async handle(ctx, args) {
+ const data = await ctx.client.post<InvestigateResponse>(
+ `/api/v1/cases/${args.case_id}/investigate`,
+ {
+ alert_summary: args.alert_summary ?? "",
+ raw_alert: {},
+ },
+ );
+ return json({
+ run_id: data.run_id,
+ case_id: data.case_id,
+ status: data.status,
+ message: data.message,
+ next_step:
+ "Wait 5–30 seconds, then call `aisoc_replay_decision` with this run_id to inspect the agent's decisions.",
+ });
+ },
+};
+
+// ---------------------------------------------------------------------------
+// helpers
+// ---------------------------------------------------------------------------
+
+function summariseCase(c: CaseResponse): Record<string, unknown> {
+ return {
+ id: c.id,
+ case_number: c.case_number,
+ title: c.title,
+ status: c.status,
+ priority: c.priority,
+ severity: c.severity,
+ assigned_to_id: c.assigned_to_id,
+ alert_count: c.alert_ids.length,
+ tags: c.tags,
+ created_at: c.created_at,
+ closed_at: c.closed_at,
+ };
+}
diff --git a/services/mcp/src/tools/detections.ts b/services/mcp/src/tools/detections.ts
new file mode 100644
index 000000000..289c6478c
--- /dev/null
+++ b/services/mcp/src/tools/detections.ts
@@ -0,0 +1,202 @@
+/**
+ * Detection-content tools.
+ *
+ * The plan calls for a single `aisoc_query_detections(query)` tool. The
+ * actual API surfaces filters by category and rule_language but no
+ * server-side free-text search, so we implement search client-side over
+ * a sane page size — that keeps the agent UX honest ("query for 'AWS
+ * IAM'") while we wait for FTS to land in the API.
+ *
+ * We also expose `aisoc_get_detection_rule` so an agent that finds a
+ * rule by query can deep-dive into its body, MITRE mappings, and FP
+ * notes when drafting a tighter version.
+ */
+import { z } from "zod";
+
+import { zodToJsonSchema } from "./alerts.js";
+import type { ToolDefinition } from "./types.js";
+import { json } from "./types.js";
+
+interface DetectionRuleResponse {
+ id: string;
+ tenant_id: string | null;
+ name: string;
+ description: string | null;
+ rule_language: string;
+ rule_body: string;
+ category: string;
+ status: string;
+ severity: string;
+ confidence: number;
+ mitre_tactics: string[];
+ mitre_techniques: string[];
+ fp_rate: number;
+ total_hits: number;
+ last_triggered: string | null;
+ tags: string[];
+ is_builtin: boolean;
+ version: number;
+ created_at: string;
+ updated_at: string;
+}
+
+// ---------------------------------------------------------------------------
+// aisoc_query_detections
+// ---------------------------------------------------------------------------
+
+const QueryDetectionsSchema = z
+ .object({
+ query: z
+ .string()
+ .optional()
+ .describe(
+ "Free-text query matched (case-insensitive) against name, description, tags, and MITRE technique IDs. Omit to list all rules.",
+ ),
+ category: z
+ .enum([
+ "endpoint",
+ "network",
+ "cloud",
+ "identity",
+ "application",
+ "data",
+ ])
+ .optional()
+ .describe("Restrict to a single detection category."),
+ rule_language: z
+ .enum(["sigma", "yara", "kql", "eql"])
+ .optional()
+ .describe("Restrict by rule language."),
+ severity: z
+ .enum(["critical", "high", "medium", "low", "info"])
+ .optional()
+ .describe("Restrict by severity (client-side filter)."),
+ mitre_technique: z
+ .string()
+ .optional()
+ .describe(
+ "MITRE ATT&CK technique id (e.g. T1059.003). Matches any rule mapping that technique.",
+ ),
+ include_builtin: z
+ .boolean()
+ .default(true)
+ .describe("If false, only tenant-authored rules are returned."),
+ limit: z
+ .number()
+ .int()
+ .min(1)
+ .max(50)
+ .default(20)
+ .describe("Cap returned matches. Capped low to fit MCP context budgets."),
+ })
+ .strict();
+
+export const queryDetectionsTool: ToolDefinition<typeof QueryDetectionsSchema> = {
+ metadata: {
+ name: "aisoc_query_detections",
+ description:
+ "Search the detection-rule library by free text, category, language, severity, or MITRE technique. Returns a compact summary; pull the full body with `aisoc_get_detection_rule`.",
+ inputSchema: zodToJsonSchema(QueryDetectionsSchema),
+ },
+ schema: QueryDetectionsSchema,
+ async handle(ctx, args) {
+ const data = await ctx.client.get<DetectionRuleResponse[]>("/api/v1/rules", {
+ query: {
+ category: args.category,
+ rule_language: args.rule_language,
+ include_builtin: args.include_builtin,
+ },
+ });
+
+ // Apply the client-side filters the API doesn't support. We accept
+ // the over-fetch because typical tenants have hundreds — not millions
+ // — of rules, and querying server-side would require a back-end change
+ // that's out of scope for this skill.
+ let filtered = data;
+ if (args.severity) {
+ filtered = filtered.filter((r) => r.severity === args.severity);
+ }
+ if (args.mitre_technique) {
+ const want = args.mitre_technique.toUpperCase();
+ filtered = filtered.filter((r) =>
+ r.mitre_techniques.some((t) => t.toUpperCase() === want),
+ );
+ }
+ if (args.query) {
+ const needle = args.query.toLowerCase();
+ filtered = filtered.filter((r) =>
+ [
+ r.name,
+ r.description ?? "",
+ r.tags.join(" "),
+ r.mitre_techniques.join(" "),
+ r.mitre_tactics.join(" "),
+ r.category,
+ ]
+ .join(" ")
+ .toLowerCase()
+ .includes(needle),
+ );
+ }
+
+ const totalUnfiltered = data.length;
+ const totalMatched = filtered.length;
+ const items = filtered.slice(0, args.limit).map(summariseRule);
+
+ return json({
+ total_unfiltered: totalUnfiltered,
+ total_matched: totalMatched,
+ truncated: totalMatched > items.length,
+ items,
+ });
+ },
+};
+
+// ---------------------------------------------------------------------------
+// aisoc_get_detection_rule
+// ---------------------------------------------------------------------------
+
+const GetDetectionRuleSchema = z
+ .object({
+ rule_id: z.string().uuid().describe("UUID of the detection rule."),
+ })
+ .strict();
+
+export const getDetectionRuleTool: ToolDefinition<typeof GetDetectionRuleSchema> = {
+ metadata: {
+ name: "aisoc_get_detection_rule",
+ description:
+ "Fetch the full body of a single detection rule, including the raw rule text, MITRE mappings, hit stats, and false-positive rate.",
+ inputSchema: zodToJsonSchema(GetDetectionRuleSchema),
+ },
+ schema: GetDetectionRuleSchema,
+ async handle(ctx, args) {
+ const data = await ctx.client.get<DetectionRuleResponse>(
+ `/api/v1/rules/${args.rule_id}`,
+ );
+ return json(data);
+ },
+};
+
+// ---------------------------------------------------------------------------
+// helpers
+// ---------------------------------------------------------------------------
+
+function summariseRule(r: DetectionRuleResponse): Record<string, unknown> {
+ return {
+ id: r.id,
+ name: r.name,
+ description: r.description,
+ rule_language: r.rule_language,
+ category: r.category,
+ severity: r.severity,
+ status: r.status,
+ confidence: r.confidence,
+ mitre_tactics: r.mitre_tactics,
+ mitre_techniques: r.mitre_techniques,
+ total_hits: r.total_hits,
+ fp_rate: r.fp_rate,
+ is_builtin: r.is_builtin,
+ tags: r.tags,
+ };
+}
diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.ts
new file mode 100644
index 000000000..20ea062dd
--- /dev/null
+++ b/services/mcp/src/tools/index.ts
@@ -0,0 +1,49 @@
+/**
+ * Tool registry.
+ *
+ * Single export the server depends on, so adding a new tool is a one-line
+ * change here and a single new file under `./tools/`. The order of this
+ * array is the order tools are advertised to MCP hosts; we keep the
+ * "discovery" tools (alerts/list, cases/list, query) before deep-dive
+ * tools so an agent reading the listing top-to-bottom builds an
+ * intuition of how to navigate the surface.
+ */
+import { getAlertTool, listAlertsTool } from "./alerts.js";
+import {
+ getCaseTool,
+ listCasesTool,
+ runInvestigationTool,
+} from "./cases.js";
+import {
+ getDetectionRuleTool,
+ queryDetectionsTool,
+} from "./detections.js";
+import {
+ explainStepTool,
+ getInvestigationTool,
+ listInvestigationsTool,
+ replayDecisionTool,
+} from "./investigations.js";
+import type { ToolDefinition } from "./types.js";
+
+export const ALL_TOOLS: ToolDefinition[] = [
+ // Discovery
+ listAlertsTool,
+ listCasesTool,
+ queryDetectionsTool,
+ listInvestigationsTool,
+ // Deep-dive
+ getAlertTool,
+ getCaseTool,
+ getDetectionRuleTool,
+ getInvestigationTool,
+ // Action / replay
+ runInvestigationTool,
+ replayDecisionTool,
+ explainStepTool,
+];
+
+/** Convenience for the server: name → definition lookup. */
+export const TOOL_BY_NAME: Record<string, ToolDefinition> = Object.fromEntries(
+ ALL_TOOLS.map((t) => [t.metadata.name, t]),
+);
diff --git a/services/mcp/src/tools/investigations.ts b/services/mcp/src/tools/investigations.ts
new file mode 100644
index 000000000..bef752950
--- /dev/null
+++ b/services/mcp/src/tools/investigations.ts
@@ -0,0 +1,227 @@
+/**
+ * Investigation-ledger tools — the trust-vector surface that AiSOC's
+ * closed-source competitors literally can't expose, because their agents
+ * are black-box cloud services.
+ *
+ * These tools let an MCP-aware agent answer "what did the AiSOC agent
+ * do, and why?" by walking the persistent decision ledger written in
+ * Phase 1A.
+ */
+import { z } from "zod";
+
+import { zodToJsonSchema } from "./alerts.js";
+import type { ToolDefinition } from "./types.js";
+import { json } from "./types.js";
+
+interface RunSummary {
+ id: string;
+ case_id: string;
+ status: string;
+ model_used: string | null;
+ iterations: number;
+ total_tokens: number;
+ total_cost_usd: number;
+ started_at: string;
+ completed_at: string | null;
+ error: string | null;
+}
+
+interface RunDetail extends RunSummary {
+ alert_summary: string | null;
+ event_count: number;
+ artifact_count: number;
+}
+
+interface EventOut {
+ id: string;
+ run_id: string;
+ seq: number;
+ ts: string;
+ kind: string;
+ agent: string;
+ summary: string;
+ payload: Record<string, unknown> | null;
+ input_hash: string | null;
+ output_hash: string | null;
+ duration_ms: number;
+}
+
+interface ExplainResponse {
+ run: RunSummary;
+ previous: EventOut | null;
+ focus: EventOut;
+ next: EventOut | null;
+ artifacts: Array<{
+ id: string;
+ kind: string;
+ sha256: string;
+ size_bytes: number;
+ event_id: string | null;
+ created_at: string;
+ content: string | null;
+ blob_ref: string | null;
+ }>;
+}
+
+// ---------------------------------------------------------------------------
+// aisoc_list_investigations
+// ---------------------------------------------------------------------------
+
+const ListInvestigationsSchema = z
+ .object({
+ case_id: z
+ .string()
+ .optional()
+ .describe(
+ "Restrict to runs for a specific case. Accepts UUIDs or external case ids (e.g. INC-001).",
+ ),
+ status: z
+ .enum(["running", "completed", "failed"])
+ .optional()
+ .describe("Filter by run status."),
+ limit: z.number().int().min(1).max(200).default(50),
+ })
+ .strict();
+
+export const listInvestigationsTool: ToolDefinition<typeof ListInvestigationsSchema> = {
+ metadata: {
+ name: "aisoc_list_investigations",
+ description:
+ "List recent investigation runs for the connected tenant. Each run is a single agent execution against a case.",
+ inputSchema: zodToJsonSchema(ListInvestigationsSchema),
+ },
+ schema: ListInvestigationsSchema,
+ async handle(ctx, args) {
+ const data = await ctx.client.get<RunSummary[]>("/api/v1/investigations", {
+ query: {
+ case_id: args.case_id,
+ status: args.status,
+ limit: args.limit,
+ },
+ });
+ return json(data);
+ },
+};
+
+// ---------------------------------------------------------------------------
+// aisoc_get_investigation
+// ---------------------------------------------------------------------------
+
+const GetInvestigationSchema = z
+ .object({
+ run_id: z.string().uuid().describe("Investigation run UUID."),
+ })
+ .strict();
+
+export const getInvestigationTool: ToolDefinition<typeof GetInvestigationSchema> = {
+ metadata: {
+ name: "aisoc_get_investigation",
+ description:
+ "Fetch a single investigation run with summary stats (status, model, tokens, cost, event/artifact counts).",
+ inputSchema: zodToJsonSchema(GetInvestigationSchema),
+ },
+ schema: GetInvestigationSchema,
+ async handle(ctx, args) {
+ const data = await ctx.client.get<RunDetail>(`/api/v1/investigations/${args.run_id}`);
+ return json(data);
+ },
+};
+
+// ---------------------------------------------------------------------------
+// aisoc_replay_decision
+// ---------------------------------------------------------------------------
+
+const ReplayDecisionSchema = z
+ .object({
+ run_id: z.string().uuid(),
+ since_seq: z
+ .number()
+ .int()
+ .min(0)
+ .optional()
+ .describe(
+ "Return only events with seq strictly greater than this value. Use to tail long-running investigations without re-pulling history.",
+ ),
+ limit: z
+ .number()
+ .int()
+ .min(1)
+ .max(500)
+ .default(200)
+ .describe("Cap the number of events returned. Capped lower than the API to keep MCP context budgets sane."),
+ })
+ .strict();
+
+export const replayDecisionTool: ToolDefinition<typeof ReplayDecisionSchema> = {
+ metadata: {
+ name: "aisoc_replay_decision",
+ description:
+ "Walk the agent decision ledger for an investigation run. Returns each step (recon, forensic, responder, reporter, tool-calls, errors) with summaries and timing. Use `aisoc_explain_step` for a deep dive on a single step.",
+ inputSchema: zodToJsonSchema(ReplayDecisionSchema),
+ },
+ schema: ReplayDecisionSchema,
+ async handle(ctx, args) {
+ const data = await ctx.client.get<{
+ items: EventOut[];
+ total: number;
+ since: number | null;
+ next_seq: number | null;
+ }>(`/api/v1/investigations/${args.run_id}/events`, {
+ query: { since: args.since_seq, limit: args.limit },
+ });
+ return json({
+ total: data.total,
+ next_seq: data.next_seq,
+ // Trim payloads here; the explain tool returns the full thing.
+ items: data.items.map(summariseEvent),
+ });
+ },
+};
+
+// ---------------------------------------------------------------------------
+// aisoc_explain_step
+// ---------------------------------------------------------------------------
+
+const ExplainStepSchema = z
+ .object({
+ run_id: z.string().uuid(),
+ step: z
+ .number()
+ .int()
+ .min(0)
+ .describe("Event seq number — the integer index from `aisoc_replay_decision`."),
+ })
+ .strict();
+
+export const explainStepTool: ToolDefinition<typeof ExplainStepSchema> = {
+ metadata: {
+ name: "aisoc_explain_step",
+ description:
+ "Why-did-the-agent-do-this view for a single decision step. Returns the focal event, the previous and next events for context, and any inlined artifacts (LLM prompts/responses, tool I/O) attached to that step.",
+ inputSchema: zodToJsonSchema(ExplainStepSchema),
+ },
+ schema: ExplainStepSchema,
+ async handle(ctx, args) {
+ const data = await ctx.client.get<ExplainResponse>(
+ `/api/v1/investigations/${args.run_id}/explain`,
+ { query: { step: args.step } },
+ );
+ return json(data);
+ },
+};
+
+// ---------------------------------------------------------------------------
+// helpers
+// ---------------------------------------------------------------------------
+
+function summariseEvent(e: EventOut): Record<string, unknown> {
+ return {
+ seq: e.seq,
+ ts: e.ts,
+ kind: e.kind,
+ agent: e.agent,
+ summary: e.summary,
+ duration_ms: e.duration_ms,
+ has_payload: e.payload !== null && Object.keys(e.payload ?? {}).length > 0,
+ };
+}
diff --git a/services/mcp/src/tools/types.ts b/services/mcp/src/tools/types.ts
new file mode 100644
index 000000000..cfdbb7f9f
--- /dev/null
+++ b/services/mcp/src/tools/types.ts
@@ -0,0 +1,67 @@
+/**
+ * Shared types for the MCP tool layer.
+ *
+ * Each tool is implemented as an object satisfying {@link ToolDefinition} so
+ * the server can list them and dispatch a single name → handler map without
+ * the if/else ladder we'd get from inlining everything in `server.ts`.
+ *
+ * The handler returns the structured payload it wants to surface to the
+ * agent; the server wraps that payload in the MCP `CallToolResult` shape
+ * (text content + `isError` flag) and is responsible for catching any
+ * thrown error.
+ */
+import type { z } from "zod";
+import type { AisocClient } from "../client.js";
+import type { Logger } from "../config.js";
+
+/** Minimal MCP "tool" descriptor — name + JSON schema for ListToolsResult. */
+export interface ToolMetadata {
+ /** Tool ID surfaced to the agent. Convention: `aisoc_<verb>_<resource>`. */
+ name: string;
+ /** One-line description shown in tool pickers. Keep under ~80 chars. */
+ description: string;
+ /** JSON Schema for the input arguments (pre-converted from zod). */
+ inputSchema: Record<string, unknown>;
+}
+
+/**
+ * What a tool handler receives. We pass the client + logger explicitly so
+ * tools are easy to unit-test against a mock client.
+ */
+export interface ToolContext {
+ client: AisocClient;
+ log: Logger;
+}
+
+/**
+ * Tool definition: schema + handler. Generic on the zod schema so the
+ * handler gets fully-typed `args`.
+ */
+export interface ToolDefinition<TSchema extends z.ZodTypeAny = z.ZodTypeAny> {
+ metadata: ToolMetadata;
+ /**
+ * Zod schema describing the tool input — used both to advertise the
+ * tool (via JSON Schema) and to validate args at call time. We make this
+ * the single source of truth so the two never drift.
+ */
+ schema: TSchema;
+ /**
+ * Execute the tool. Returns either:
+ * - a JSON-serialisable payload that we render as a JSON code block, or
+ * - a `{ text: string, data?: unknown }` envelope when the natural
+ * output is markdown (e.g. report.md).
+ *
+ * Throws `ApiError` / `TransportError` etc. on failure; the server maps
+ * those into the standard MCP error envelope.
+ */
+ handle(ctx: ToolContext, args: z.infer<TSchema>): Promise<ToolResult>;
+}
+
+/** Result envelope returned to the server before MCP-shape wrapping. */
+export type ToolResult =
+ | { kind: "json"; data: unknown }
+ | { kind: "text"; text: string; data?: unknown };
+
+/** Convenience constructors so handlers stay readable. */
+export const json = (data: unknown): ToolResult => ({ kind: "json", data });
+export const text = (text: string, data?: unknown): ToolResult => ({ kind: "text", text, data });
diff --git a/services/mcp/tests/config.test.ts b/services/mcp/tests/config.test.ts
new file mode 100644
index 000000000..fafbadaeb
--- /dev/null
+++ b/services/mcp/tests/config.test.ts
@@ -0,0 +1,193 @@
+/**
+ * Tests for argv parsing + config resolution.
+ *
+ * These cover the regressions that bit us during Phase 2C smoke testing:
+ * - `--host claude` (unknown long flag with a value) was being captured
+ * as a boolean, so positional `claude` leaked into the command parser.
+ * - `packageVersion()` was returning `0.0.0-dev` because the ESM build
+ * couldn't reach package.json via `require`.
+ *
+ * If any of these break again, CI catches it before the next publish.
+ */
+import { describe, expect, it } from "vitest";
+
+import { packageVersion, parseArgs, resolveConfig } from "../src/config.js";
+
+describe("parseArgs", () => {
+ it("defaults to the serve command when no positional is given", () => {
+ const out = parseArgs([]);
+ expect(out.command).toBe("serve");
+ expect(out.flags).toEqual({});
+ expect(out.positional).toEqual([]);
+ });
+
+ it("recognises serve/install/doctor/help/version as commands", () => {
+ for (const cmd of ["serve", "install", "doctor", "help", "version"] as const) {
+ expect(parseArgs([cmd]).command).toBe(cmd);
+ }
+ });
+
+ it("treats --help / -h / --version / -v as commands", () => {
+ expect(parseArgs(["--help"]).command).toBe("help");
+ expect(parseArgs(["-h"]).command).toBe("help");
+ expect(parseArgs(["--version"]).command).toBe("version");
+ expect(parseArgs(["-v"]).command).toBe("version");
+ });
+
+ it("accepts known long flags with a separate value", () => {
+ const out = parseArgs(["serve", "--aisoc-url", "https://aisoc.example.com"]);
+ expect(out.command).toBe("serve");
+ expect(out.flags.aisocUrl).toBe("https://aisoc.example.com");
+ });
+
+ it("accepts known long flags with --key=value syntax", () => {
+ const out = parseArgs(["--aisoc-url=https://aisoc.example.com", "--api-key=aisoc_test"]);
+ expect(out.flags.aisocUrl).toBe("https://aisoc.example.com");
+ expect(out.flags.apiKey).toBe("aisoc_test");
+ });
+
+ it("treats --verbose / --help / --version as boolean toggles", () => {
+ const out = parseArgs(["serve", "--verbose"]);
+ expect(out.flags.verbose).toBe(true);
+ });
+
+ it("captures unknown long flags with values (regression: --host claude)", () => {
+ // This is the parseArgs bug we hit during install smoke testing.
+ // Before the fix, `claude` ended up as a positional and the install
+ // command rejected the missing `--host`. The fix is in src/config.ts:
+ // when the next token doesn't start with `-`, treat the unknown long
+ // flag as `--key value` rather than a boolean.
+ const out = parseArgs(["install", "--host", "claude", "--dry-run"]);
+ expect(out.command).toBe("install");
+ expect(out.flags.host).toBe("claude");
+ expect(out.flags["dry-run"]).toBe(true);
+ expect(out.positional).toEqual([]);
+ });
+
+ it("captures unknown long flags with --key=value too", () => {
+ const out = parseArgs(["install", "--host=cursor", "--list-paths"]);
+ expect(out.flags.host).toBe("cursor");
+ expect(out.flags["list-paths"]).toBe(true);
+ });
+
+ it("falls back to boolean for trailing unknown long flags", () => {
+ const out = parseArgs(["install", "--dry-run"]);
+ expect(out.flags["dry-run"]).toBe(true);
+ });
+
+ it("throws when a known value-taking flag is missing its value", () => {
+ expect(() => parseArgs(["--aisoc-url"])).toThrow(/requires a value/);
+ });
+
+ it("collects extra positional args after the command", () => {
+ const out = parseArgs(["install", "claude"]);
+ expect(out.command).toBe("install");
+ expect(out.positional).toEqual(["claude"]);
+ });
+});
+
+describe("resolveConfig", () => {
+ const baseEnv = {} as NodeJS.ProcessEnv;
+
+ it("falls back to the default URL when nothing is set", () => {
+ const cfg = resolveConfig(parseArgs([]), baseEnv);
+ expect(cfg.aisocUrl).toBe("http://localhost:8081");
+ expect(cfg.apiKey).toBeUndefined();
+ expect(cfg.timeoutMs).toBe(20_000);
+ expect(cfg.verbose).toBe(false);
+ });
+
+ it("prefers the CLI flag over the environment variable", () => {
+ const args = parseArgs(["--aisoc-url", "https://flag.example"]);
+ const cfg = resolveConfig(args, { AISOC_URL: "https://env.example" } as NodeJS.ProcessEnv);
+ expect(cfg.aisocUrl).toBe("https://flag.example");
+ });
+
+ it("uses AISOC_URL when no flag is given", () => {
+ const cfg = resolveConfig(parseArgs([]), {
+ AISOC_URL: "https://env.example",
+ } as NodeJS.ProcessEnv);
+ expect(cfg.aisocUrl).toBe("https://env.example");
+ });
+
+ it("falls back to AISOC_API_URL alias", () => {
+ const cfg = resolveConfig(parseArgs([]), {
+ AISOC_API_URL: "https://alias.example",
+ } as NodeJS.ProcessEnv);
+ expect(cfg.aisocUrl).toBe("https://alias.example");
+ });
+
+ it("strips a single trailing slash from the URL", () => {
+ const args = parseArgs(["--aisoc-url", "https://aisoc.example/"]);
+ const cfg = resolveConfig(args, baseEnv);
+ expect(cfg.aisocUrl).toBe("https://aisoc.example");
+ });
+
+ it("resolves the API key from AISOC_API_KEY", () => {
+ const cfg = resolveConfig(parseArgs([]), {
+ AISOC_API_KEY: "aisoc_env_key",
+ } as NodeJS.ProcessEnv);
+ expect(cfg.apiKey).toBe("aisoc_env_key");
+ });
+
+ it("resolves the API key from AISOC_TOKEN as fallback", () => {
+ const cfg = resolveConfig(parseArgs([]), {
+ AISOC_TOKEN: "jwt_value",
+ } as NodeJS.ProcessEnv);
+ expect(cfg.apiKey).toBe("jwt_value");
+ });
+
+ it("prefers --api-key flag over both env aliases", () => {
+ const args = parseArgs(["--api-key", "from_flag"]);
+ const cfg = resolveConfig(args, {
+ AISOC_API_KEY: "from_env",
+ AISOC_TOKEN: "also_env",
+ } as NodeJS.ProcessEnv);
+ expect(cfg.apiKey).toBe("from_flag");
+ });
+
+ it("parses a numeric timeout from --timeout", () => {
+ const args = parseArgs(["--timeout", "5000"]);
+ const cfg = resolveConfig(args, baseEnv);
+ expect(cfg.timeoutMs).toBe(5000);
+ });
+
+ it("parses a numeric timeout from AISOC_TIMEOUT_MS", () => {
+ const cfg = resolveConfig(parseArgs([]), {
+ AISOC_TIMEOUT_MS: "7500",
+ } as NodeJS.ProcessEnv);
+ expect(cfg.timeoutMs).toBe(7500);
+ });
+
+ it("rejects non-positive timeouts", () => {
+ expect(() =>
+ resolveConfig(parseArgs([]), { AISOC_TIMEOUT_MS: "0" } as NodeJS.ProcessEnv),
+ ).toThrow(/Invalid timeout/);
+ expect(() =>
+ resolveConfig(parseArgs([]), { AISOC_TIMEOUT_MS: "abc" } as NodeJS.ProcessEnv),
+ ).toThrow(/Invalid timeout/);
+ });
+
+ it("turns on verbose logging via flag or env", () => {
+ expect(resolveConfig(parseArgs(["--verbose"]), baseEnv).verbose).toBe(true);
+ expect(
+ resolveConfig(parseArgs([]), { AISOC_MCP_VERBOSE: "1" } as NodeJS.ProcessEnv).verbose,
+ ).toBe(true);
+ });
+
+ it("includes the package version in the User-Agent string", () => {
+ const cfg = resolveConfig(parseArgs([]), baseEnv);
+ expect(cfg.userAgent).toMatch(/^aisoc-mcp\/\d+\.\d+\.\d+/);
+ });
+});
+
+describe("packageVersion", () => {
+ it("returns the version from package.json (not 0.0.0-dev)", () => {
+ // Regression: an earlier ESM-incompatible implementation always fell
+ // back to the dev sentinel. The CLI's `--version` is the canonical
+ // way users check what they have, so this matters.
+ const v = packageVersion();
+ expect(v).toMatch(/^\d+\.\d+\.\d+/);
+ expect(v).not.toBe("0.0.0-dev");
+ });
+});
diff --git a/services/mcp/tests/installers.test.ts b/services/mcp/tests/installers.test.ts
new file mode 100644
index 000000000..13aedd249
--- /dev/null
+++ b/services/mcp/tests/installers.test.ts
@@ -0,0 +1,225 @@
+/**
+ * Tests for `aisoc-mcp install` host configuration.
+ *
+ * These exercise:
+ *
+ * 1. Real (non-dry-run) JSON writes into a temp directory, so we know the
+ * file path we built for each host actually round-trips through
+ * `readJsonOrEmpty` → mutate → `writeFileSync`.
+ * 2. Idempotency: running install twice with the same args is a no-op.
+ * 3. The "update" path: existing entry under a different shape is replaced
+ * and the operator log line says "Updated", not "Wrote".
+ * 4. Cody's prints-only behaviour, since that host doesn't write files.
+ * 5. Refusal to clobber a malformed config rather than nuking it silently.
+ *
+ * Each test uses its own temp dir under `os.tmpdir()` to stay parallel-safe.
+ */
+import * as fs from "node:fs";
+import * as os from "node:os";
+import * as path from "node:path";
+
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import type { ServerConfig } from "../src/config.js";
+import { install } from "../src/installers/index.js";
+
+let tmpDir: string;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "aisoc-mcp-test-"));
+});
+
+afterEach(() => {
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+const baseCfg: ServerConfig = {
+ aisocUrl: "https://aisoc.example.com",
+ apiKey: "aisoc_test_key",
+ timeoutMs: 20_000,
+ verbose: false,
+ userAgent: "aisoc-mcp/0.1.0 test",
+};
+
+describe("install (real write)", () => {
+ it("creates a brand-new config file with mcpServers.aisoc", () => {
+ const configPath = path.join(tmpDir, "claude_desktop_config.json");
+ const result = install({ host: "claude", cfg: baseCfg, configPath });
+
+ expect(result.changed).toBe(true);
+ expect(result.configPath).toBe(configPath);
+ expect(result.message).toMatch(/Wrote claude MCP config/);
+
+ const written = JSON.parse(fs.readFileSync(configPath, "utf8"));
+ expect(written).toEqual({
+ mcpServers: {
+ aisoc: {
+ command: "npx",
+ args: ["-y", "@aisoc/mcp", "serve"],
+ env: {
+ AISOC_URL: "https://aisoc.example.com",
+ AISOC_API_KEY: "aisoc_test_key",
+ },
+ },
+ },
+ });
+ });
+
+ it("creates parent directories when the config path is nested", () => {
+ // Cursor's real path is `~/.cursor/mcp.json`; install must mkdir -p
+ // when the user's cursor profile dir doesn't exist yet.
+ const configPath = path.join(tmpDir, "nested", "deep", "mcp.json");
+ install({ host: "cursor", cfg: baseCfg, configPath });
+ expect(fs.existsSync(configPath)).toBe(true);
+ });
+
+ it("preserves unrelated keys in an existing config", () => {
+ const configPath = path.join(tmpDir, "mcp.json");
+ fs.writeFileSync(
+ configPath,
+ JSON.stringify(
+ {
+ editor: { theme: "dark" },
+ mcpServers: { someOther: { command: "true" } },
+ },
+ null,
+ 2,
+ ),
+ );
+
+ install({ host: "cursor", cfg: baseCfg, configPath });
+
+ const written = JSON.parse(fs.readFileSync(configPath, "utf8"));
+ expect(written.editor).toEqual({ theme: "dark" });
+ expect(written.mcpServers.someOther).toEqual({ command: "true" });
+ expect(written.mcpServers.aisoc.command).toBe("npx");
+ });
+
+ it("is idempotent: a second identical install reports no change", () => {
+ const configPath = path.join(tmpDir, "config.json");
+ const first = install({ host: "continue", cfg: baseCfg, configPath });
+ expect(first.changed).toBe(true);
+
+ const second = install({ host: "continue", cfg: baseCfg, configPath });
+ expect(second.changed).toBe(false);
+ expect(second.message).toMatch(/Already configured/);
+ });
+
+ it("reports 'Updated' when an existing aisoc entry changes shape", () => {
+ const configPath = path.join(tmpDir, "claude.json");
+ fs.writeFileSync(
+ configPath,
+ JSON.stringify({
+ mcpServers: {
+ aisoc: { command: "old", args: ["legacy"] },
+ },
+ }),
+ );
+
+ const result = install({ host: "claude", cfg: baseCfg, configPath });
+ expect(result.changed).toBe(true);
+ expect(result.message).toMatch(/Updated claude MCP config/);
+ expect(result.message).not.toMatch(/^Wrote/);
+ });
+
+ it("includes AISOC_TIMEOUT_MS only when it differs from the default", () => {
+ const cfgCustom: ServerConfig = { ...baseCfg, timeoutMs: 7500 };
+ const cfgDefault: ServerConfig = { ...baseCfg, timeoutMs: 20_000 };
+
+ const a = install({
+ host: "claude",
+ cfg: cfgCustom,
+ configPath: path.join(tmpDir, "a.json"),
+ });
+ const b = install({
+ host: "claude",
+ cfg: cfgDefault,
+ configPath: path.join(tmpDir, "b.json"),
+ });
+
+ expect((a.snippet.env as Record<string, string>).AISOC_TIMEOUT_MS).toBe(
+ "7500",
+ );
+ expect((b.snippet.env as Record<string, string>).AISOC_TIMEOUT_MS).toBeUndefined();
+ });
+
+ it("omits the API key from env when none is configured", () => {
+ const cfgNoKey: ServerConfig = { ...baseCfg, apiKey: undefined };
+ const result = install({
+ host: "cursor",
+ cfg: cfgNoKey,
+ configPath: path.join(tmpDir, "mcp.json"),
+ });
+ const env = result.snippet.env as Record<string, string>;
+ expect(env.AISOC_URL).toBe("https://aisoc.example.com");
+ expect(env.AISOC_API_KEY).toBeUndefined();
+ });
+
+ it("dry-run does not touch the filesystem", () => {
+ const configPath = path.join(tmpDir, "claude.json");
+ const result = install({
+ host: "claude",
+ cfg: baseCfg,
+ configPath,
+ dryRun: true,
+ });
+ expect(result.changed).toBe(true);
+ expect(result.snippet).toBeDefined();
+ expect(fs.existsSync(configPath)).toBe(false);
+ });
+
+ it("refuses to clobber a malformed JSON config", () => {
+ const configPath = path.join(tmpDir, "broken.json");
+ fs.writeFileSync(configPath, "{ not json");
+ expect(() =>
+ install({ host: "cursor", cfg: baseCfg, configPath }),
+ ).toThrow(/Refusing to overwrite/);
+ // And the broken file is left untouched.
+ expect(fs.readFileSync(configPath, "utf8")).toBe("{ not json");
+ });
+
+ it("treats ENOENT as fresh install, not as an error", () => {
+ const configPath = path.join(tmpDir, "no", "such", "file.json");
+ const result = install({ host: "cursor", cfg: baseCfg, configPath });
+ expect(result.changed).toBe(true);
+ expect(fs.existsSync(configPath)).toBe(true);
+ });
+});
+
+describe("install host=cody (no file write)", () => {
+ it("returns a paste-able snippet without touching disk", () => {
+ const configPath = path.join(tmpDir, "should-not-be-written.json");
+ const result = install({ host: "cody", cfg: baseCfg, configPath });
+ expect(result.changed).toBe(false);
+ expect(result.configPath).toBeUndefined();
+ expect(result.message).toContain("cody.mcp.servers");
+ expect(result.message).toContain("aisoc");
+ expect(fs.existsSync(configPath)).toBe(false);
+ });
+});
+
+describe("buildServerSnippet shape", () => {
+ it("always uses npx -y so users don't need a global install", () => {
+ const result = install({
+ host: "claude",
+ cfg: baseCfg,
+ configPath: path.join(tmpDir, "claude.json"),
+ dryRun: true,
+ });
+ expect(result.snippet.command).toBe("npx");
+ expect(result.snippet.args).toEqual(["-y", "@aisoc/mcp", "serve"]);
+ });
+
+ it("propagates the verbose flag into AISOC_VERBOSE", () => {
+ const cfgVerbose: ServerConfig = { ...baseCfg, verbose: true };
+ const result = install({
+ host: "claude",
+ cfg: cfgVerbose,
+ configPath: path.join(tmpDir, "claude.json"),
+ dryRun: true,
+ });
+ expect((result.snippet.env as Record<string, string>).AISOC_VERBOSE).toBe(
+ "1",
+ );
+ });
+});
diff --git a/services/mcp/tests/tools.test.ts b/services/mcp/tests/tools.test.ts
new file mode 100644
index 000000000..ab5a88d9b
--- /dev/null
+++ b/services/mcp/tests/tools.test.ts
@@ -0,0 +1,134 @@
+/**
+ * Tool registry contract tests.
+ *
+ * The registry is what the MCP server hands to ListToolsResult and uses
+ * for dispatch. It's the surface that AI agents see, so we lock down:
+ *
+ * - Names are unique and conventional (`aisoc_<verb>_<resource>`).
+ * - Every tool's input schema is real JSON Schema (object + properties).
+ * - Every tool we expect to ship in v0.1 is present.
+ * - TOOL_BY_NAME is consistent with ALL_TOOLS.
+ *
+ * Schema correctness for individual tools is enforced by zod at runtime;
+ * here we just check the shape the server advertises.
+ */
+import { describe, expect, it } from "vitest";
+
+import { ALL_TOOLS, TOOL_BY_NAME } from "../src/tools/index.js";
+
+const EXPECTED_TOOLS = [
+ "aisoc_list_alerts",
+ "aisoc_get_alert",
+ "aisoc_list_cases",
+ "aisoc_get_case",
+ "aisoc_run_investigation",
+ "aisoc_query_detections",
+ "aisoc_get_detection_rule",
+ "aisoc_list_investigations",
+ "aisoc_get_investigation",
+ "aisoc_replay_decision",
+ "aisoc_explain_step",
+] as const;
+
+describe("tool registry", () => {
+ it("ships exactly the v0.1 tool surface", () => {
+ const names = ALL_TOOLS.map((t) => t.metadata.name).sort();
+ expect(names).toEqual([...EXPECTED_TOOLS].sort());
+ });
+
+ it("uses the aisoc_ prefix on every tool name", () => {
+ for (const tool of ALL_TOOLS) {
+ expect(tool.metadata.name).toMatch(/^aisoc_[a-z]+(_[a-z]+)+$/);
+ }
+ });
+
+ it("has unique tool names", () => {
+ const names = ALL_TOOLS.map((t) => t.metadata.name);
+ expect(new Set(names).size).toBe(names.length);
+ });
+
+ it("has a non-trivial description per tool", () => {
+ for (const tool of ALL_TOOLS) {
+ const len = tool.metadata.description.length;
+ // 20 char floor: rules out empty strings or "TODO".
+ // 280 char ceiling: descriptions show in tool pickers (Claude
+ // Desktop, Cursor); paragraph dumps make the picker unusable.
+ // Our two longest descriptions (replay_decision/explain_step)
+ // sit at ~220 because they're the novel "ledger" tools that
+ // need extra context — the cap leaves headroom for that without
+ // letting future tools regress to README-length copy.
+ expect(len, `${tool.metadata.name} description`).toBeGreaterThan(20);
+ expect(len, `${tool.metadata.name} description`).toBeLessThan(280);
+ }
+ });
+
+ it("exposes a JSON Schema object for every tool", () => {
+ for (const tool of ALL_TOOLS) {
+ const schema = tool.metadata.inputSchema;
+ expect(schema, `${tool.metadata.name} schema`).toBeDefined();
+ expect(schema.type).toBe("object");
+ // Even tools that take no args should declare `properties: {}` so
+ // the host UI can render a (possibly empty) form without a crash.
+ expect(schema).toHaveProperty("properties");
+ }
+ });
+
+ it("attaches a real zod schema for runtime validation", () => {
+ for (const tool of ALL_TOOLS) {
+ expect(tool.schema).toBeDefined();
+ // zod's parse method is the contract the server relies on.
+ expect(typeof tool.schema.parse).toBe("function");
+ expect(typeof tool.schema.safeParse).toBe("function");
+ }
+ });
+
+ it("provides a handler for every tool", () => {
+ for (const tool of ALL_TOOLS) {
+ expect(typeof tool.handle).toBe("function");
+ }
+ });
+
+ it("places discovery tools before deep-dive tools in the listing", () => {
+ // We rely on listing order so an agent skimming `tools/list`
+ // top-to-bottom learns the right verbs first. If somebody re-orders
+ // ALL_TOOLS without thinking, this test fails loudly.
+ const names = ALL_TOOLS.map((t) => t.metadata.name);
+ const indexOf = (n: string) => names.indexOf(n);
+ expect(indexOf("aisoc_list_alerts")).toBeLessThan(indexOf("aisoc_get_alert"));
+ expect(indexOf("aisoc_list_cases")).toBeLessThan(indexOf("aisoc_get_case"));
+ expect(indexOf("aisoc_query_detections")).toBeLessThan(
+ indexOf("aisoc_get_detection_rule"),
+ );
+ expect(indexOf("aisoc_list_investigations")).toBeLessThan(
+ indexOf("aisoc_get_investigation"),
+ );
+ });
+
+ it("places action/replay tools last", () => {
+ const names = ALL_TOOLS.map((t) => t.metadata.name);
+ const last3 = names.slice(-3);
+ expect(last3).toEqual([
+ "aisoc_run_investigation",
+ "aisoc_replay_decision",
+ "aisoc_explain_step",
+ ]);
+ });
+});
+
+describe("TOOL_BY_NAME", () => {
+ it("indexes every tool", () => {
+ expect(Object.keys(TOOL_BY_NAME).sort()).toEqual(
+ ALL_TOOLS.map((t) => t.metadata.name).sort(),
+ );
+ });
+
+ it("returns the same definition object as ALL_TOOLS", () => {
+ for (const tool of ALL_TOOLS) {
+ expect(TOOL_BY_NAME[tool.metadata.name]).toBe(tool);
+ }
+ });
+
+ it("returns undefined for unknown names", () => {
+ expect(TOOL_BY_NAME["aisoc_nonexistent"]).toBeUndefined();
+ });
+});
diff --git a/services/mcp/tsconfig.json b/services/mcp/tsconfig.json
new file mode 100644
index 000000000..b671b7a8e
--- /dev/null
+++ b/services/mcp/tsconfig.json
@@ -0,0 +1,25 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ES2022",
+ "moduleResolution": "Bundler",
+ "lib": ["ES2022"],
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "esModuleInterop": true,
+ "forceConsistentCasingInFileNames": true,
+ "strict": true,
+ "noUncheckedIndexedAccess": true,
+ "noImplicitOverride": true,
+ "noFallthroughCasesInSwitch": true,
+ "skipLibCheck": true,
+ "declaration": true,
+ "declarationMap": true,
+ "sourceMap": true,
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "verbatimModuleSyntax": false
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules", "dist", "tests"]
+}