secufusion-mcp 2.2.1 → 2.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,1017 +1,1017 @@
1
- # SecuFusion MCP Server
2
-
3
- > **Project-level spec driven AI workflow tooling for the SecuFusion platform** — loads full project DNA at session start, enforces zero-trust architecture standards, tracks task specs, and gates PRs with automated guardrail checks.
4
-
5
- [![npm version](https://img.shields.io/npm/v/secufusion-mcp)](https://www.npmjs.com/package/secufusion-mcp)
6
- [![license](https://img.shields.io/npm/l/secufusion-mcp)](./LICENSE)
7
- [![node](https://img.shields.io/node/v/secufusion-mcp)](https://nodejs.org)
8
-
9
- ---
10
-
11
- ## What is this?
12
-
13
- `secufusion-mcp` is a [Model Context Protocol (MCP)](https://modelcontextprotocol.io) server that plugs into AI coding assistants (Claude Desktop, Cursor, Cline, etc.) and gives them **ten powerful tools** to enforce SecuFusion's engineering standards throughout the development lifecycle:
14
-
15
- | Tool | Phase | What it does |
16
- |---|---|---|
17
- | `manage_project_spec` | **Phase 00** — Session Start | Loads `.secufusion-project-spec.json` — full project DNA (ports, repos, domains, coding patterns, golden rules) |
18
- | `manage_task` | **Phase 0.7 / 1 / 2 / 4** — Task Lifecycle | Creates dynamically named `.secufusion/tasks/{id}-{slug}/` folder (the HOW layer: spec, progress, decisions, files-touched). |
19
- | `spec_create_intent` | **Phase 1** — Planning | **NEW in v2.1** — Creates the Markdown intent file (the WHY layer: business goal, PM, ACs, polyglot service map). |
20
- | `spec_read_intent` | **Phase 0 / 1** — Session Start | **NEW in v2.1** — Reads the Markdown intent file and ticks AC checkboxes. |
21
- | `spec_next_number` | **Phase 1** — Planning | **NEW in v2.1** — Generates the next sequential ID for intent files. |
22
- | `get_task_history` | **Phase 0 / 1** — Cross-Task Intelligence | Retrieves the full history of a past task before starting similar work |
23
- | `search_tasks` | **Phase 0 / 1** — Cross-Task Intelligence | Keyword search across all past task files — prevents re-solving solved problems |
24
- | `get_pattern_from_task` | **Phase 1** — Cross-Task Intelligence | Extracts reusable decisions, file patterns, and test scenarios from a completed task |
25
- | `manage_branch_state` | Legacy — Branch State | Backward-compatible branch-scoped JSON state tracker (for tasks before `manage_task`) |
26
- | `log_rejected_pattern` | **Phase 3** — Course Correction | Records bad patterns to `.rejected-patterns.json` so they are never repeated |
27
- | `get_secufusion_rules` | **Setup** | Returns the `AGENTS.md` rules for AI clients that don't natively support MCP Resources |
28
- | `classify_task` | **Phase 0.5** — Task Classification | **NEW** — Deep multi-pass analysis engine. Classifies any task as `BACKEND_ONLY`, `FRONTEND_ONLY`, etc. based on root cause. |
29
- | `prime_session` | **Phase 0** — Session Start | **NEW** — Hyper-efficient session startup. Combines Phase 00 (spec) and Phase 0 (task) into one call using Thin Indexes to optimize context tokens. |
30
- | `skill_recommend` | **Phase 1** — Planning | **NEW** — Dynamically recommends and retrieves domain-specific coding skills from `skills-catalog.json`. |
31
-
32
- ---
33
-
34
- ## 🚀 What's New: MLMCPS Architecture Alignment
35
-
36
- The SecuFusion MCP has been refactored to align with the advanced MLMCPS framework principles, bringing massive efficiency and UX improvements:
37
-
38
- 1. **5 High-Impact Slash Commands**: The monolithic agent prompt and fragmented utility scripts are consolidated into 5 clean, focused commands: `/sfn-init`, `/sfn-plan`, `/sfn-code`, `/sfn-review`, and `/sfn-explore`.
39
- 2. **Subprocess PR Checks**: Tier 1 mechanical checks (`TENANT_ISOLATION`, `N_PLUS_ONE`, etc.) are now extracted into a standalone CLI script (`scripts/sfn-pr-check.js`), allowing them to be run by the AI *or* natively within your CI/CD pipelines.
40
- 3. **Thin Index Token Discipline**: Context bloat is gone. Tools like `manage_task(read)` and `prime_session` now return lightweight "Thin Indexes"—compact Markdown summaries with absolute file paths—so the AI only reads the full JSON via `view_file` when truly necessary.
41
- 4. **Dynamic Skill Registry**: A new `skill_recommend` tool allows the AI to dynamically discover domain-specific architectural skills without bloating the base prompt.
42
- 5. **Phase -1 Philosophy Engine**: An invisible gate that checks the WHY, WHO, WHAT, and RISK of every task (including bugs and hotfixes) before any planning starts. If the business intent or blast radius is unsafe, it stops the AI from writing a single line of code.
43
- 6. **Built-in Poly-Repo DNA Discovery**: Built directly into `secufusion-mcp`. The AI dynamically analyzes the entire poly-repo workspace at session start, mapping microservices, API contracts, Kafka topologies, frontend repos, and browser extensions into a living knowledge graph (`.secufusion/dna.json`) with an auto-generated Mermaid architecture diagram.
44
- 7. **Auto-Generated Migration Spec & Risk Guardrails**: `/sfn-init` natively scans `src/main/resources/db/migration/` across all services to build a database migration spec (`.secufusion-migrations.json`). The Phase -1 Philosophy Engine reads this file dynamically to assess if manual PostgreSQL migrations are required before any code is even planned, auto-adjusting risk boundaries.
45
- 8. **Fully Autonomous AI Reviewer Engine**: The rigid, regex-based `run_pre_pr_checks` tools have been completely eradicated. `/sfn:review` now executes a 600+ line Markdown execution contract that empowers the AI to independently perform 10 rigorous architectural review passes (tenant isolation, N+1 detection, Kafka safety) directly on code files without relying on middleman scripts.
46
- 9. **Smart Spec Merging & Auto-Sync**: The project specification (`.secufusion-project-spec.json`) now seamlessly syncs with the active MCP plugin version. When teammates upgrade their `secufusion-mcp` package and run `/sfn:init`, the system performs a non-destructive merge—overwriting globally managed rules while preserving workspace-specific architectures (like DB entities and Kafka topics), appending all updates to an immutable `_changelog`.
47
-
48
- ---
49
-
50
- ## 🧬 Built-In DNA Discovery & Architecture Exploration
51
-
52
- `secufusion-mcp` includes native ecosystem-wide discovery tools:
53
-
54
- - **Dynamic Stack Analysis:** Identifies Java/Spring, Node, Docker, and other frameworks on the fly.
55
- - **Automated Dependency Mapping:** Generates cross-service dependency maps and evaluates the blast radius of potential changes.
56
- - **Interactive Commands:** Use `/sfn-init` to map your entire workspace and launch the watcher, and `/sfn-explore` on-demand to render Mermaid architecture graphs or analyze component blast radius.
57
-
58
- ---
59
-
60
- ## ⚡ The Shift: "WHY before HOW" Spec-Driven Workflow (v2.1)
61
-
62
- This is the biggest architectural upgrade to the SecuFusion MCP, fundamentally changing how the AI approaches a new task.
63
-
64
- ### The Problem
65
- Previously, the AI acted as a blind code-generator. When given a task (e.g. "Add MFA"), it would immediately jump into writing code or initializing tracking infrastructure (`.secufusion/tasks/`), without understanding **why** the feature was being built, who requested it, or the business risk. Furthermore, its AST parsers were limited to Java/TypeScript, leaving Go, Python, or Rust services completely invisible.
66
-
67
- ### The v2.1 Solution: The Two-Layer Architecture
68
- Every task now requires **two complementary files** that the AI reads together:
69
-
70
- ```
71
- .secufusion/
72
- ├── intents/ ← WHY layer (business truth, human-driven, Markdown)
73
- │ └── 0001-WI-2847-add-mfa-enforcement.md
74
- │ ├── Business Goal ← why is this being built?
75
- │ ├── PM Owner ← who owns it?
76
- │ ├── Acceptance Criteria ← tickable checkboxes
77
- │ ├── Service Map ← polyglot bridge (Go, Python, Rust...)
78
- │ └── Risk Assessment ← what breaks if we don't ship?
79
- │
80
- └── tasks/WI-2847/ ← HOW layer (code truth, AST-driven, JSON)
81
- ├── progress.json ← pending/completed ACs
82
- └── decisions.json ← architectural decisions log
83
- ```
84
-
85
- ### The Polyglot Bridge
86
- The new `spec_create_intent` tool captures a `services_involved` array that is **language-agnostic**. You can list a Go microservice, a Python Lambda, or a COBOL batch job. The AI reads this declaration and knows those services are in scope without needing a custom AST parser.
87
-
88
- ### The New `/sfn-plan` Flow
89
- When you type `/sfn-plan WI-2847 Add MFA`:
90
- 1. **The Guard (Phase -1):** The AI silently runs a `philosophy_check` against your Project DNA. It evaluates the WHY, WHO, WHAT, and RISK of the task. (Note: Bugs and hotfixes still undergo this check, though with slightly relaxed sensing).
91
- 2. **The Pushback (Phase 1):** If the Philosophy Engine fails the request (e.g. unclear business intent or high risk), the AI will **NOT** plan. It will stop and ask you for clarity: *"Why are we building this? Who confirmed it?"*
92
- 3. **The WHY (Phase 1.5):** You answer, and the AI generates the Markdown intent file (`spec_create_intent`).
93
- 4. **The HOW (Phase 2):** Only then does it initialize the code tracking infrastructure (`manage_task`).
94
- 5. **Context & Classify (Phase 3/4):** The AI loads the AST (`prime_session`), flags architectural risks (`classify_task`), and yields for your approval.
95
- 6. **The Plan (Phase 5):** The AI outputs the strict implementation plan.
96
-
97
- ---
98
-
99
- ## ⚡ The Shift: Problem-Statement Driven → Project-Level Spec Driven
100
-
101
- ### Before (problem-statement driven)
102
- The AI started every session **cold**. It had zero knowledge of the codebase and relied entirely on the developer feeding context through a work item description. Every session began with implicit questions:
103
- - *"Which port does sfn-iam-api run on?"*
104
- - *"How do you extract tenantId from the JWT?"*
105
- - *"What's the coding pattern for DTO mapping?"*
106
-
107
- The AI was **reactive** — it knew only what you told it about the current task.
108
-
109
- ### After (project-level spec driven)
110
- The AI starts every session by reading `.secufusion-project-spec.json` — a single file containing the **entire project's DNA**:
111
-
112
- ```
113
- ✅ All microservice ports, repos, Eureka names, domains
114
- ✅ Table ownership per service
115
- ✅ Inter-service call graph
116
- ✅ Kafka topics produced/consumed per service
117
- ✅ Keycloak realm + client config per service
118
- ✅ Coding patterns (DTO mapping, @Transactional style, tenant passing)
119
- ✅ Golden rules (tenant isolation layers, authority rules, banned patterns)
120
- ✅ Flyway migration state per service
121
- ```
122
-
123
- The AI is now **proactively context-aware** — it knows your entire architecture before you say a single word about the task:
124
-
125
- | Before | After |
126
- |---|---|
127
- | You explain the service every session | AI already knows all services |
128
- | You describe the coding pattern | AI reads it from the spec |
129
- | AI asks which port to use | AI looks it up from the spec |
130
- | Context resets between sessions | Project knowledge is permanent |
131
- | Spec is task-scoped | Spec is project-scoped |
132
-
133
- > **One-time setup:** Generate `.secufusion-project-spec.json` once using the extraction prompt. From that point, every AI session starts fully informed.
134
-
135
- ---
136
-
137
- ## 🤖 The Autonomous AI Reviewer Engine (v2.2.0)
138
-
139
- Version 2.2.0 removes the legacy, rigid TypeScript tools (`run_pre_pr_checks`) and replaces them with a fully standalone, AI-driven markdown execution contract (`/sfn:review`).
140
-
141
- ### Why is this significant?
142
- 1. **Context-Aware, Not Regex-Bound**: The old tools blindly searched for regex patterns (like `@TenantScopeException`). The new AI reviewer genuinely reads the file, understands *how* the `tenantId` is flowing through the thread context, and makes intelligent architectural judgments.
143
- 2. **Zero Dependencies**: You no longer need to rely on the MCP server executing heavy AST-parsing scripts under the hood. The AI handles the review completely independently.
144
- 3. **10 Strict Passes**: The reviewer is contractually bound to execute 10 precise checks before it can output a verdict, including Kafka blocking detection, Acceptance Criteria coverage, Decision Drift (did you write code you didn't plan?), and Rejected Pattern enforcement.
145
- 4. **Ruthless Persona**: We injected a specific persona into the reviewer. It is explicitly forbidden from saying "Looks good to me!" to be polite. It operates as a senior architect with a zero-tolerance policy for guardrail violations.
146
-
147
- ---
148
-
149
- ## Installation
150
-
151
- [![Claude Marketplace](https://img.shields.io/badge/Download_from-Claude_Marketplace-blue?logo=anthropic)](https://claude.ai/marketplace/secufusion-mcp)
152
-
153
- ### Option 1 — `npx` (no install required)
154
-
155
- ```bash
156
- npx secufusion-mcp
157
- ```
158
-
159
- ### Option 2 — Global install
160
-
161
- ```bash
162
- npm install -g secufusion-mcp@2.2.0
163
- ```
164
-
165
- ### Option 3 — Local project install
166
-
167
- ```bash
168
- npm install --save-dev secufusion-mcp@2.2.0
169
- ```
170
-
171
- ---
172
-
173
- ## Setup: Add to Your MCP Client
174
-
175
- ### Claude Desktop
176
-
177
- Edit `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or
178
- `%APPDATA%\Claude\claude_desktop_config.json` (Windows):
179
-
180
- ```json
181
- {
182
- "mcpServers": {
183
- "secufusion-mcp": {
184
- "command": "npx",
185
- "args": ["-y", "secufusion-mcp"]
186
- }
187
- }
188
- }
189
- ```
190
-
191
- ### Cursor
192
-
193
- Open **Settings → MCP** and add:
194
-
195
- ```json
196
- {
197
- "secufusion-mcp": {
198
- "command": "npx",
199
- "args": ["-y", "secufusion-mcp"]
200
- }
201
- }
202
- ```
203
-
204
- ### Cline (VS Code Extension)
205
-
206
- Open Cline settings → MCP Servers → Add:
207
-
208
- ```json
209
- {
210
- "secufusion-mcp": {
211
- "command": "npx",
212
- "args": ["-y", "secufusion-mcp"],
213
- "disabled": false
214
- }
215
- }
216
- ```
217
-
218
- ### Using a local build (development)
219
-
220
- ```json
221
- {
222
- "secufusion-mcp": {
223
- "command": "node",
224
- "args": ["C:/path/to/secufusion-mcp/index.js"]
225
- }
226
- }
227
- ```
228
-
229
- ---
230
-
231
- ## Tools Reference
232
-
233
- ### 1. manage_branch_state
234
-
235
- Manages a structured JSON state file (`.secufusion-state.json`) keyed to the current Git branch. This replaces unstructured Markdown parsing and ensures the AI can resume perfectly.
236
-
237
- **Parameters:**
238
-
239
- | Parameter | Type | Required | Description |
240
- |---|---|---|---|
241
- | `action` | string | Yes | `initialize`, `read`, or `update` |
242
- | `task_description` | string | No | (For `initialize`) Summary of the work |
243
- | `pending_acs` | array | No | Array of strings for pending tasks (For `initialize`/`update`) |
244
- | `completed_acs` | array | No | Array of completed AC strings (For `update`) |
245
- | `next_step` | string | No | **CRITICAL for `update`**: A clear instruction on what to do next to allow instant resumption. |
246
- | `reference_file_path` | string | No | Path to a reference file with standard coding patterns (auto-compressed to save tokens) |
247
-
248
- **Example — Starting a new task:**
249
- ```json
250
- {
251
- "action": "initialize",
252
- "task_description": "Implement DeviceActivitySummaryDTO with browserUsage map.",
253
- "pending_acs": ["Add browserUsage map", "Add unit tests", "Update OpenAPI"]
254
- }
255
- ```
256
-
257
- **Example — Updating progress:**
258
- ```json
259
- {
260
- "action": "update",
261
- "pending_acs": ["Update OpenAPI"],
262
- "completed_acs": ["Add browserUsage map", "Add unit tests"],
263
- "next_step": "Generate the OpenAPI YAML for DeviceActivitySummaryDTO and test generation."
264
- }
265
- ```
266
-
267
- ---
268
-
269
- ### 2. `log_rejected_pattern`
270
-
271
- Appends a rejected code pattern to `.rejected-patterns.json`. The AI checks this file implicitly before every architectural suggestion to avoid repeating past mistakes.
272
-
273
- **Parameters:**
274
-
275
- | Parameter | Type | Required | Description |
276
- |---|---|---|---|
277
- | `pattern` | string | Yes | The bad pattern or approach |
278
- | `reason` | string | Yes | Why it was rejected and what to do instead |
279
- | `category` | enum | No | `architecture` \| `security` \| `database` \| `logging` \| `api-design` \| `testing` \| `other` |
280
- | `file_context` | string | No | File or area where the pattern was observed |
281
-
282
- **Example:**
283
-
284
- ```
285
- Tell your AI: "Never use a global @Repository bean without tenantId scoping again.
286
- It was leaking cross-tenant data."
287
- ```
288
-
289
- The AI will call:
290
- ```json
291
- {
292
- "pattern": "Injecting global @Repository bean and querying without tenantId filter",
293
- "reason": "Causes cross-tenant data leakage. Always add .where(tenantId = :tenantId) or use TenantAwareRepository base class.",
294
- "category": "security",
295
- "file_context": "src/repositories/AuditLogRepository.java"
296
- }
297
- ```
298
-
299
- This writes to `.rejected-patterns.json`:
300
- ```json
301
- [
302
- {
303
- "id": 1,
304
- "timestamp": "2026-08-26T14:35:00.000Z",
305
- "category": "security",
306
- "pattern": "Injecting global @Repository bean...",
307
- "reason": "Causes cross-tenant data leakage...",
308
- "file_context": "src/repositories/AuditLogRepository.java"
309
- }
310
- ]
311
- ```
312
-
313
- ---
314
-
315
- ### 3. generate_ado_comments
316
- ### 3. Native Document Generation (v1.0.58+)
317
-
318
- Instead of using a generic tool, the agent natively generates two highly structured files based on strict `AGENTS.md` templates:
319
- - **`ado-comments.md`**: For the Azure DevOps board (Layman summary + Technical Deep-Dive).
320
- - **`pr-comment.md`**: For the PR Description (Changes, Impact, Scenarios, Guardrails).
321
-
322
- The AI constructs these dynamically by reading `scenarios.json`, `decisions.json`, and `files-touched.json`, and presents them to the developer.
323
-
324
- ---
325
-
326
- ### 4. `manage_project_spec`
327
-
328
- Loads and manages `.secufusion-project-spec.json` — the permanent project memory file. **Called automatically at the start of every session (Phase 00)** before any task begins.
329
-
330
- **Parameters:**
331
-
332
- | Parameter | Type | Required | Description |
333
- |---|---|---|---|
334
- | `action` | enum | Yes | `read` \| `get_service` \| `get_golden_rules` \| `get_coding_patterns` \| `update` |
335
- | `service_name` | string | No | **(For `get_service`)** Name of the microservice, e.g. `sfn-events-api` |
336
- | `update_path` | string | No | **(For `update`)** Dot-notation path, e.g. `microservices.sfn-iam-api.port` |
337
- | `update_value` | any | No | **(For `update`)** New value to set at `update_path` |
338
-
339
- **Actions:**
340
-
341
- | Action | Returns | Token cost |
342
- |---|---|---|
343
- | `read` | Full spec (all services, all patterns, all rules) | High — use once at session start |
344
- | `get_service` | Only the block for the requested microservice | Low — use when focused on one service |
345
- | `get_golden_rules` | `golden_rules` block + `rejected_patterns` | Low — use before any architectural decision |
346
- | `get_coding_patterns` | `coding_patterns` block | Low — use before writing any new class |
347
- | `update` | Confirmation of surgical dot-notation write | Low — never overwrites the full file |
348
-
349
- **Example — Session start (reads full project context):**
350
- ```json
351
- { "action": "read" }
352
- ```
353
-
354
- **Example — Focused lookup before writing a service:**
355
- ```json
356
- { "action": "get_service", "service_name": "sfn-iam-api" }
357
- ```
358
-
359
- **Example — Check golden rules before an architectural decision:**
360
- ```json
361
- { "action": "get_golden_rules" }
362
- ```
363
-
364
- **Example — Surgical port update (never overwrites the full file):**
365
- ```json
366
- {
367
- "action": "update",
368
- "update_path": "microservices.sfn-iam-api.port",
369
- "update_value": 9005
370
- }
371
- ```
372
-
373
- **File location resolution order:**
374
- 1. Same directory as `index.js`
375
- 2. `process.cwd()`
376
- 3. Walk up from `cwd` (up to 5 levels)
377
- 4. The global MCP package installation directory (bundled spec fallback)
378
-
379
- ---
380
-
381
- ### 5. `get_secufusion_rules`
382
-
383
- A simple utility tool that returns the raw text of the `AGENTS.md` workflow rules. This is designed as a workaround for AI clients (like older versions of Cline or Claude Code) that do not support the MCP **Resources** capability.
384
-
385
- By calling this tool, the AI can read the globally bundled rules without you needing to copy the `.agents` folder into your local repository.
386
-
387
- **Example:**
388
- > "Call the get_secufusion_rules tool and read the rules before we begin."
389
-
390
-
391
- ---
392
-
393
- ## Guardrails Summary
394
-
395
- These rules are enforced automatically — the AI will never violate them:
396
-
397
- ```
398
- ✅ All DB queries and event payloads scoped with tenantId
399
- ✅ No console.log() or System.out.println() in any source file
400
- ✅ No hardcoded UAT/Prod IPs or environment URLs
401
- ✅ Every JPA @Entity change accompanied by a Flyway .sql migration
402
- ✅ State in .secufusion-state.json must be fully resolved before PR is raised
403
- ✅ Token Efficiency: Every tool response includes a 📊 Telemetry receipt tracking input/output tokens, cost, and the Session Total
404
- ```
405
-
406
- **Performance Guardrails** (enforced whenever writing queries, Kafka consumers, or cross-service calls):
407
- ```
408
- ✅ All GET service methods use @Transactional(readOnly = true)
409
- ✅ No repository method called inside a for/forEach loop — batch with findAllById/saveAll
410
- ✅ Every new query column that is filtered/sorted has a CREATE INDEX in the Flyway migration
411
- ✅ Kafka listeners never do synchronous DB writes or REST calls — offload to @Async
412
- ✅ Every RestTemplate/WebClient call has an explicit timeout and fallback
413
- ```
414
-
415
- **Rollback Guardrails** (enforced on every Flyway migration, API contract change, Kafka schema change):
416
- ```
417
- ✅ SAFE migration (additive) — safe to roll back by reverting code
418
- ⚠️ RISKY migration (NOT NULL without DEFAULT) — requires compensating migration
419
- 🚫 DANGEROUS migration (DROP/RENAME) — requires explicit developer confirmation before writing
420
- ✅ API hard cutover (removing /v1/ or a field) — requires confirmation; prefer /v2/ + deprecation first
421
- ✅ Kafka schema change — coordinated deployment of producer + all consumers; flagged in rollback plan
422
- ✅ Every manage_task initialize logs a rollback strategy starter entry in decisions.json
423
- ```
424
-
425
- **Breaking Change Detection** (run as Step 4 in Phase 0.5 before any plan is written):
426
- ```
427
- ✅ Check 1: Endpoint consumers — who calls this endpoint? Flag if response shape changes
428
- ✅ Check 2: Entity/table consumers — @Query annotations across all repos for this column
429
- ✅ Check 3: Kafka topic consumers — coordinated deployment required if schema changes
430
- ✅ Check 4: Chrome extension — silent breaks invisible until users report them
431
- ✅ Over-flag > under-flag: always present a breaking change report if in doubt
432
- ```
433
-
434
- **classify_task — Deep Analysis Engine** (runs first on every task, before anything else):
435
- ```
436
- ✅ Weighted signal tiers: service names = 10pts, tech constructs = 5pts, generic = 1pt
437
- ✅ Root-cause extraction: classifies by WHERE THE FIX LIVES, not where the symptom appears
438
- ✅ Negation detection: "not a UI issue" removes frontend signal weight
439
- ✅ Bug disambiguation: data-correctness/exception/auth/CRUD/performance bugs → +backend
440
- ✅ Confidence gate: HIGH only when score ratio ≥ 1.8× AND Tier 1/2 signal matched
441
- ✅ Persists to .secufusion/classifications/{id}.json — no re-classification on resume
442
- ```
443
-
444
- ---
445
-
446
- ## File Outputs
447
-
448
- | File | Description | Commit? |
449
- |---|---|---|
450
- | `.secufusion-project-spec.json` | **Project DNA** — all services, ports, patterns, golden rules. Generated once, read every session | ✅ Yes |
451
- | `.secufusion/registry.json` | Index of all initialized work items and their exact dynamic folder names — used by `search_tasks` | ✅ Yes |
452
- | `.secufusion/tasks/{id}-{slug}/spec.json` | Task spec — title, description, ACs, tags, status | ✅ Yes |
453
- | `.secufusion/tasks/{id}-{slug}/progress.json` | AC tracking — pending, completed, next_step | ✅ Yes |
454
- | `.secufusion/tasks/{id}-{slug}/decisions.json` | Architectural decisions log (including rollback strategy) | ✅ Yes |
455
- | `.secufusion/tasks/{id}-{slug}/files-touched.json` | All files modified with change summaries | ✅ Yes |
456
- | `.secufusion/tasks/{id}-{slug}/scenarios.json` | Test scenarios (unit / integration / e2e / manual) | ✅ Yes |
457
- | `.secufusion/tasks/{id}-{slug}/pr-summary.md` | Auto-generated PR summary on `manage_task complete` | ✅ Yes |
458
- | `.secufusion-state.json` | **Legacy** branch-scoped state — still works via `manage_branch_state` | ✅ Yes |
459
- | `.rejected-patterns.json` | Cumulative log of all rejected patterns across sessions | ✅ Yes |
460
- | `.secufusion-tokens.json` | Persistent tracking of session-wide LLM token usage and cost | ❌ No |
461
-
462
- > **Tip:** Commit the entire `.secufusion/` folder and `.rejected-patterns.json` to your repo. Do **not** commit `.secufusion-tokens.json`.
463
-
464
- ---
465
-
466
- ## Workflow Overview
467
-
468
- ```
469
- ┌──────────────┬──────────────────────────────────────────────────────────────┐
470
- │ Phase 00 │ manage_project_spec (action=read + get_golden_rules) │
471
- │ Project DNA │ → FIRST step — runs before ANY problem statement is read │
472
- │ (Session │ → AI loaded with ALL services, ports, coding patterns, │
473
- │ Start) │ Kafka topics, golden rules, and tenant isolation config │
474
- ├──────────────┼──────────────────────────────────────────────────────────────┤
475
- │ Phase 0.5 │ Ultimate Reasoning (ReAct) → classify_task │
476
- │ Task │ Step 1: AI outputs ### Ultimate Reasoning block │
477
- │ Classification Deconstruction / Observation / Root Cause / Hypothesis │
478
- │ │ Step 2: classify_task → 5-pass deep analysis engine │
479
- │ │ Pass 1: Weighted signal scoring (Tier 1-4) │
480
- │ │ Pass 2: Negation detection per sentence │
481
- │ │ Pass 3: Root-cause phrase extraction │
482
- │ │ Pass 4: Bug disambiguation matrix │
483
- │ │ Pass 5: Confidence gate (≥ 1.8× + Tier 1/2 required) │
484
- │ │ → allowed_next_action: PROCEED / CONFIRM / STOP │
485
- ├──────────────┼──────────────────────────────────────────────────────────────┤
486
- │ Phase 0.6.6 │ manage_task (action=read_summary) OR search_tasks │
487
- │ Resume │ → Token-efficient status view → resume next_step instantly │
488
- ├──────────────┼──────────────────────────────────────────────────────────────┤
489
- │ Phase 0.7 │ Present full plan (scope, files, ACs, perf, rollback) │
490
- │ Plan Gate │ → STOP and wait for "proceed" / "adjust" / "cancel" │
491
- │ │ → manage_task (action=initialize) only after proceed │
492
- ├──────────────┼──────────────────────────────────────────────────────────────┤
493
- │ Phase -1 │ philosophy_check (Silently validates WHY/WHO/WHAT/RISK) │
494
- │ Philosophy │ → Blocks planning if intent or safety is unclear (ALL TASKS) │
495
- ├──────────────┼──────────────────────────────────────────────────────────────┤
496
- │ Phase 1 │ search_tasks → get_task_history → manage_task initialize │
497
- │ Planning │ → Creates .secufusion/tasks/{id}-{slug}/ with all 5 files │
498
- ├──────────────┼──────────────────────────────────────────────────────────────┤
499
- │ Phase 2 │ manage_task: update_spec / log_file_touched / │
500
- │ Execution │ log_decision / add_scenario │
501
- ├──────────────┼──────────────────────────────────────────────────────────────┤
502
- │ Phase 3 │ log_rejected_pattern │
503
- │ Correction │ → Record mistakes permanently to avoid repeat │
504
- ├──────────────┼──────────────────────────────────────────────────────────────┤
505
- │ Phase 4 │ /sfn:review (Standalone AI Reviewer Engine) │
506
- │ PR Handoff │ → Enforces 10 strict architecture passes directly on code │
507
- │ │ → manage_task (action=complete) → pr-summary.md generated │
508
- │ │ → Document Generation (ado-comments.md, pr-comment.md) │
509
- └──────────────┴──────────────────────────────────────────────────────────────┘
510
- ```
511
-
512
- ---
513
-
514
- ## Real-World Walkthrough
515
-
516
- A complete end-to-end example of what you actually type and what happens at each phase.
517
-
518
- ---
519
-
520
- ### Step 1 — Integrate (one-time setup)
521
-
522
- Add this to your MCP client config and restart. That's it.
523
-
524
- **Antigravity / Claude Desktop / Cline — if you have the source on disk:**
525
- ```json
526
- {
527
- "mcpServers": {
528
- "secufusion-mcp": {
529
- "command": "node",
530
- "args": ["C:\\Users\\YourName\\Desktop\\mcp\\secufusion-mcp\\index.js"],
531
- "type": "stdio"
532
- }
533
- }
534
- }
535
- ```
536
-
537
- **Teammates / fresh machines — pulls from npm, cached after first run:**
538
- ```json
539
- {
540
- "mcpServers": {
541
- "secufusion-mcp": {
542
- "command": "npx",
543
- "args": ["-y", "secufusion-mcp"],
544
- "type": "stdio"
545
- }
546
- }
547
- }
548
- ```
549
-
550
- > **Why two options?** If you have the compiled `index.js` on disk, `node` starts instantly and works fully offline. Teammates who don't have the source use `npx` — it downloads from npm once (~3s), then caches it locally so every subsequent run is instant with no network needed.
551
-
552
- ---
553
-
554
- ### Step 2 — Start a new task (Classification phase)
555
-
556
- Just paste your Azure DevOps work item ID and description directly into the chat. No special syntax needed.
557
-
558
- Before analyzing the problem statement, the AI has already loaded the Project DNA from Phase 00. It now outputs an **Ultimate Reasoning block** — a structured, spec-grounded analysis of the problem — then calls `classify_task`.
559
-
560
- **You type:**
561
- ```
562
- WI-2847: Add MFA enforcement for admin users on login
563
-
564
- **User Story:**
565
- As a security administrator,
566
- I want to enforce TOTP-based Multi-Factor Authentication (MFA) for all users with the ADMIN role,
567
- So that sensitive dashboard actions are protected against compromised credentials.
568
-
569
- **Acceptance Criteria:**
570
- 1. Any user with the ADMIN role attempting to log in must be prompted for a TOTP token after password verification.
571
- 2. The system must validate the TOTP token against the user's registered MFA device.
572
- 3. Service accounts (role = SERVICE_ACCOUNT) are exempt from MFA, even if they possess admin privileges.
573
- 4. If MFA fails 3 times, the account should be temporarily locked for 15 minutes.
574
- ```
575
-
576
- **The AI outputs:**
577
- ```
578
- ### Ultimate Reasoning
579
- - **Deconstruction:** TOTP enforcement is an auth-layer concern. sfn-iam-api owns the login flow.
580
- - **Observation:** AuthService.java contains the password verification step (line 112). No MFA interceptor exists yet. sfn-iam-api runs on port 9001 per project spec.
581
- - **Root Cause:** No MFA gate exists between password verification and JWT issuance.
582
- - **Hypothesis:** Add a MfaVerificationService that validates TOTP after password passes, blocks JWT issuance on failure, and records attempts for lockout logic.
583
- ```
584
-
585
- **Then classifies and upon approval initializes:**
586
- ```json
587
- {
588
- "action": "initialize",
589
- "work_item_id": "2847",
590
- "title": "Add MFA enforcement for admin users on login",
591
- "description": "Enforce TOTP-based MFA for ADMIN roles, exempting service accounts, with account lockout on 3 failed attempts.",
592
- "acceptance_criteria": [
593
- "Prompt ADMIN users for TOTP token post-password",
594
- "Validate TOTP token",
595
- "Exempt SERVICE_ACCOUNT role",
596
- "Lock account for 15m after 3 failed attempts"
597
- ],
598
- "tags": ["security", "auth", "mfa"]
599
- }
600
- ```
601
-
602
- ---
603
-
604
- ### Step 3 — Write code normally
605
-
606
- Just code as usual. With the MCP server active, the AI automatically:
607
-
608
- - Adds `tenantId` scoping to every DB query it writes
609
- - Uses a proper logger (e.g., `log.info()`) — never `console.log`
610
- - Reads `.rejected-patterns.json` before making any architectural suggestion
611
- - Reminds you to create a Flyway migration if it touches a `@Entity`
612
- - References any `reference_file_path` you provided to match your coding style
613
-
614
- ---
615
-
616
- ### Step 4 — Tick off completed work (Execution phase)
617
-
618
- As you finish pieces of the feature, tell the AI:
619
-
620
- ```
621
- I've finished the tenantId scoping on all queries and written the unit tests.
622
- Update the state.
623
- ```
624
-
625
- The AI calls `manage_task` with `action=update_spec` and the state updates:
626
-
627
- ```json
628
- {
629
- "action": "update_spec",
630
- "work_item_id": "2847",
631
- "pending_acs": ["Exempt SERVICE_ACCOUNT role", "Lock account for 15m after 3 failed attempts"],
632
- "completed_acs": ["Prompt ADMIN users for TOTP token post-password", "Validate TOTP token"],
633
- "next_step": "Implement exemption logic for service accounts in AuthController"
634
- }
635
- ```
636
-
637
-
638
- ---
639
-
640
- ### Step 5 — Course correction (if the AI does something wrong)
641
-
642
- Say the AI used a hardcoded URL or proposed a pattern your team has banned:
643
-
644
- ```
645
- Stop using hardcoded staging URLs like https://staging.secufusion.io.
646
- All env URLs must come from application.properties. Never hardcode them.
647
- ```
648
-
649
- The AI **immediately** calls `log_rejected_pattern`:
650
-
651
- ```json
652
- {
653
- "pattern": "Hardcoded staging URL https://staging.secufusion.io in source files",
654
- "reason": "Must use @Value('${app.base-url}') from application.properties. Hardcoded URLs break environment parity and expose internal topology.",
655
- "category": "security",
656
- "file_context": "src/services/NotificationService.java"
657
- }
658
- ```
659
-
660
- ---
661
-
662
- ### Step 6 — Complete the task (PR Handoff phase)
663
-
664
- When you're done, say:
665
-
666
- ```
667
- I'm done with WI-2847. Please complete the task and generate the ADO comments.
668
- ```
669
-
670
- The AI marks the task complete, auto-generates a PR summary locally, and then outputs two Azure DevOps comments for you to paste into the ticket:
671
-
672
- **✅ Passing output:**
673
- ```
674
- Here are the comments for your ADO ticket:
675
-
676
- **Layman Summary:**
677
- The problem where some devices weren't accurately appearing on the admin dashboard has been resolved. The fix ensures that the system accurately tallies the registered hardware without throwing silent errors.
678
-
679
- **Technical Deep-Dive:**
680
- The `DeviceActivitySummaryDTO` was throwing a NullPointerException because the `browserUsage` map was uninitialized when `deviceList` was empty. I added an explicit `ConcurrentHashMap` initialization and scoped the iteration inside a `tenantId` check to preserve cross-tenant boundaries.
681
- ```
682
-
683
- ---
684
-
685
- ## How It Works (The 3 Layers)
686
-
687
- The SecuFusion MCP operates across three complementary layers to prevent AI amnesia, enforce architecture standards, and gate code quality:
688
-
689
- **Layer 1 — Project Spec (permanent, project-scoped):** `.secufusion-project-spec.json` — loaded once per session via `manage_project_spec`. The AI never needs to be told what port a service runs on, what pattern to use for DTO mapping, or how tenantId flows through the system.
690
-
691
- **Layer 2 — Task Memory (persistent, work-item-scoped):** `.secufusion/tasks/{id}-{slug}/` — one dynamically named folder per work item, initialized via `manage_task`. Tracks spec, progress, decisions, files touched, scenarios, and generates a `pr-summary.md` on completion. Cross-task intelligence via `search_tasks`, `get_task_history`, and `get_pattern_from_task` prevents re-solving solved problems.
692
-
693
- **Layer 3 — AST Guardrails (automated, quality-gating):** ESLint, Maven Checkstyle, tenant isolation scanner, Flyway checker, performance rules, rollback classification, and breaking change detection run at PR time. Cannot be bypassed without explicit `skip_checks`.
694
-
695
- ### How it all wires together
696
-
697
- ```
698
- mcp_config.json → starts the server (tools available)
699
- +
700
- .agents/AGENTS.md → tells AI when to invoke each tool
701
- ↓
702
- ★ SESSION STARTS
703
- ↓
704
- Phase 00: manage_project_spec (read + get_golden_rules)
705
- → AI's brain loaded with full Project DNA BEFORE any task is read
706
- → knows all ports, services, patterns, tenant rules from spec
707
- ↓
708
- You say: "WI-1042: Add audit log export"
709
- ↓
710
- Phase 0.5: ### Ultimate Reasoning (spec-grounded ReAct)
711
- → Deconstruction / Observation / Root Cause / Hypothesis (written to chat)
712
- → classify_task: 5-pass deep analysis
713
- weighted scores + root-cause phrases + negation + bug heuristics
714
- allowed_next_action: PROCEED (backend) / CONFIRM (mixed) / STOP (frontend)
715
- + performance risk scan (GREEN/AMBER/RED)
716
- + breaking change scan (endpoints/entities/Kafka/extension)
717
- ↓
718
- Phase 0.7: full plan presented → developer approves ("proceed")
719
- ↓
720
- Phase 1: search_tasks (always) → get_task_history → manage_task initialize
721
- → .secufusion/tasks/1042-add-audit-log-export/ created
722
- ↓
723
- Phase 2: code + log_file_touched + log_decision + add_scenario (ALL mandatory)
724
- ↓
725
- Phase 4: /sfn:review → APPROVED / DISCUSS
726
- → manage_task complete → pr-summary.md generated
727
- → Generate PR & ADO Documents natively using templates
728
- ```
729
-
730
- ### Reusing across projects (Global Bundling)
731
-
732
- As of version **1.0.13+**, `secufusion-mcp` globally bundles both `.secufusion-project-spec.json` and `AGENTS.md`. You **no longer need to copy these files** into every single repository!
733
-
734
- When you install globally (`npm install -g secufusion-mcp@2.2.0`), the AI can automatically read your rules and project spec on the fly from the global installation.
735
-
736
- **How to load the Rules in a new project:**
737
- Depending on your AI client's capabilities, you can load the rules instantly by telling the AI:
738
- - **"Use the `secufusion_developer` prompt"** (if Prompts are supported)
739
- - **"Read the `secufusion://rules` resource"** (if Resources are supported)
740
- - **"Call the `get_secufusion_rules` tool"** (if only Tools are supported)
741
-
742
- *(If you prefer the legacy method, you can still copy `.agents/AGENTS.md` and `.secufusion-project-spec.json` into your project root).*
743
-
744
- ### Dynamic Task Folders (v1.0.17+)
745
-
746
- As of version **1.0.17**, the MCP server automatically generates human-readable, safe folder names for all new tasks using the task's title.
747
-
748
- When you pass a title like `"BUG-1140: Tenant deletion reports failure"` to `manage_task initialize`, the server strips bad characters, truncates the string safely, and generates a perfect folder name:
749
- `.secufusion/tasks/BUG-1140-tenant-deletion-reports-failure/`
750
-
751
- - **Backward Compatible:** The AI only ever needs to supply the `work_item_id` (e.g. `BUG-1140`) for subsequent updates. The server instantly finds the correct folder via `registry.json` (O(1) lookup) or falls back to a prefix scan for legacy `WI-{id}` folders.
752
- - **OS Safe:** Automatically trims trailing dashes and clamps lengths to prevent Windows `MAX_PATH` errors.
753
-
754
- ### Dynamic Architecture Validation (v1.0.23+)
755
-
756
- As of version **1.0.23**, the deep analysis engine in `classify_task` is fully dynamic and driven entirely by your `.secufusion-project-spec.json`:
757
- - Validation dynamically cross-references explicit microservices, frontend repos, and Chrome extensions.
758
- - Explicit frontend overrides (e.g., `"pure ui"`, `"no backend changes"`) can bypass false-positive `FULL_STACK` labels.
759
- - The Breaking Change Pre-Scan safely checks for exact table names and Kafka topics derived from your architecture.
760
- - `coding_patterns` defined in the spec are injected seamlessly into `secufusionFlags` validation.
761
-
762
- ### Retrospective Intelligence (v1.0.24+)
763
-
764
- As of version **1.0.24**, the MCP server introduces a fully automated **Retrospective Layer**:
765
- - **Auto-Retrospective Trigger**: `manage_task complete` now automatically generates a partial retrospective and asks the developer 7 targeted questions.
766
- - **record_retrospective**: A new tool that saves retrospective insights, tracking plan accuracy, classification accuracy, and pre-PR check attempts.
767
- - **Dynamic Learning (Pass 0)**: `classify_task` now includes a Pass 0 that injects learned signals from past retrospectives into the active classification logic.
768
-
769
- ### Rule 0 Enforcement & Frontend Fallbacks (v1.0.50+)
770
-
771
- As of version **1.0.50**, the MCP server strictly enforces **Rule 0** and adds intelligent fallbacks:
772
- - **Rule 0 (DNA Load First)**: Agents are now strictly forbidden from reasoning, classifying, or planning until they have called `manage_project_spec` to load the project DNA.
773
- - **Auto-Syncing AGENTS.md**: The package now automatically syncs the workspace rules before publishing, guaranteeing AI agents always run the latest constraints.
774
- - **Frontend Service Resolution**: `get_service` now intelligently resolves frontend and extension repositories (like `sfn-web-ui`) even when they aren't explicitly keyed as backend microservices.
775
- - **Explicit AC Recognition**: `classify_task` now overrides `VAGUE` completeness warnings if it detects explicit Acceptance Criteria in the task description.
776
-
777
- ### Strict Comment Guardrails & Slugification Fixes (v1.0.55+)
778
-
779
- As of version **1.0.55**, the MCP server introduces two new quality-of-life and enforcement updates:
780
- - **No Ticket IDs in Comments**: A strict rule has been added to `AGENTS.md` and the Tier 2 AI Reviewer now explicitly flags any inline ticket IDs (e.g., `// WI-1097`) inside code comments as a CRITICAL violation. Comments must explain the durable WHY, not point to decaying tracking tickets.
781
- - **Clean Task Slugs**: `manage_task initialize` now automatically strips leading ticket prefixes (like `BUG-1173: `) from the title before generating the folder slug, preventing duplicated IDs in the folder path (e.g., no more `1173-bug-1173-`).
782
-
783
- ---
784
-
785
- ## Talking to the AI — What You'll Ever Say
786
-
787
- Once all three layers are in place, you interact completely naturally:
788
-
789
- | Situation | What you say |
790
- |---|---|
791
- | 🆕 New task | `WI-XXXX: [paste description from Azure]` |
792
- | ✅ Done a chunk | `Done with the tenantId scoping, update the state` |
793
- | ❌ AI did something wrong | `Don't do X, do Y instead` |
794
- | 🚀 Ready for PR | `Run checks for WI-XXXX` or `Prepare PR` |
795
- | 🔄 Resuming after a break | `What's left?` or `Resume the current task` |
796
- | 🔍 Starting similar work | `Has this been done before?` — AI calls `search_tasks` |
797
- | 📋 Want the full plan first | AI automatically presents plan in Phase 0.7 — type `proceed` to start |
798
-
799
- **Before `manage_project_spec`:** The AI started cold every session. You explained ports, coding patterns, and tenantId flow every single time.
800
-
801
- **After `manage_project_spec`:** The AI reads `.secufusion-project-spec.json` at session start and **already knows your entire architecture**. You just describe the work.
802
-
803
- **Before `manage_task`:** The AI used a flat branch-state file with no cross-task memory.
804
-
805
- **After `manage_task`:** Every work item has its own structured folder. The AI tracks decisions, files, and scenarios per task. `search_tasks` finds related past work. `get_pattern_from_task` reuses proven approaches.
806
-
807
- **Before Phase 0.5 + 0.7:** The AI started coding immediately with no ownership check or explicit plan.
808
-
809
- **After Phase 0.5 + 0.7:** The AI performs deep code investigation, writes an **Ultimate Reasoning** block to prove its root-cause understanding, and then calls `classify_task`. The deep analysis engine confirms the classification, runs a performance risk and breaking change scan, presents a complete plan with rollback strategy, and **waits for your approval before writing a single line of code**.
810
-
811
- **Before strict AGENTS.md:** Each phase was a soft bullet list with suggestions. The AI could skip steps.
812
-
813
- **After strict AGENTS.md:** Every phase has a MANDATORY tool-call sequence in code-block format, an explicit ❌ prohibition list, and a hard gate. Skipping any step is a named violation.
814
-
815
- ---
816
-
817
- ## Tool 10: `classify_task` — Deep Analysis Engine
818
-
819
- The **mandatory first step** for every task without exception. Classifies a task as `BACKEND_ONLY`, `FRONTEND_ONLY`, `FULL_STACK`, or `EXTENSION_ONLY` using a 5-pass deep analysis pipeline.
820
-
821
- > **Core principle:** Classifies by **where the fix lives** — not where the symptom appears.
822
- > `"Dashboard shows wrong device count"` → fix is in the API/DB query → **BACKEND_ONLY**
823
- > `"Button layout is broken"` → fix is in the React component → **FRONTEND_ONLY**
824
-
825
- **Parameters:**
826
-
827
- | Parameter | Type | Required | Description |
828
- |---|---|---|---|
829
- | `work_item_id` | string | Yes | Azure DevOps work item ID, e.g. `BUG-1140` or `2847` |
830
- | `title` | string | Yes | Full task title from Azure DevOps |
831
- | `description` | string | Yes | Full task description / problem statement — paste everything |
832
- | `task_type` | enum | Yes | `bug` \| `user_story` \| `feature` \| `hotfix` \| `refactor` \| `chore` |
833
-
834
- **The analysis passes:**
835
-
836
- | Pass | What it does |
837
- |---|---|
838
- | **Pass 1 — Weighted signal tiers** | Tier 1: service names = 10pts each (dynamically populated from `project-spec.json`). Tier 2: tech constructs = 5pts. Tier 3: domain terms = 2-3pts. Tier 4: generic words = 1pt. |
839
- | **Pass 2 — Negation detection** | Scans each sentence. `"not a UI issue"` → frontend penalty. Explicit overrides (e.g. `"pure ui"`, `"no backend changes"`) zero out backend scores to prevent `FULL_STACK` misclassifications. |
840
- | **Pass 3 — Root-cause phrase extraction** | 25 backend patterns + 9 frontend patterns matched via regex. |
841
- | **Pass 4 — Bug disambiguation matrix** | For `task_type: bug`: data-correctness → +15 backend, exception/crash → +15 backend, auth/permission → +12 backend. |
842
- | **Pass 4.5 — Problem Statement Validation** | **NEW (v1.0.19+)**: Validates Title, Scope, and Task Type. Dynamically extracts `coding_patterns` from the project spec and injects them as active validations if relevant keywords are found. |
843
- | **Pass 5 — Confidence & Breaking Change Gate** | `HIGH` only when dominant score ≥ 1.8× second-place **AND** at least one Tier 1/2 signal matched. Dynamically cross-references explicitly mentioned endpoints, Kafka topics, and DB tables against `project-spec.json` to accurately flag breaking change risks. |
844
-
845
- **Output — `allowed_next_action`:**
846
-
847
- | Value | Meaning | What the AI does |
848
- |---|---|---|
849
- | `PROCEED` | `BACKEND_ONLY` HIGH confidence | Moves directly to Phase 0.7 plan presentation |
850
- | `CONFIRM` | Mixed / LOW / extension | Presents analysis report, waits for developer YES |
851
- | `STOP` | `FRONTEND_ONLY` | Hard stop — routes to frontend team, no code written |
852
-
853
- **Mixed signal resolution:** Backend dominates only when `backendScore ≥ 2.5× frontendScore`. Below that threshold → `FULL_STACK` (requires confirmation).
854
-
855
- **Persistence:** Result saved to `.secufusion/classifications/{work_item_id}.json`. Resuming a classified task skips re-classification and loads the prior result.
856
-
857
- **Example output for a bug:**
858
- ```
859
- ✅ BACKEND_ONLY (HIGH confidence)
860
-
861
- Weighted scores: Backend=47 | Frontend=3 | Extension=0
862
- Score ratio: 15.7x dominant
863
- Root-cause evidence: [BE+12] data correctness → backend query | [BE+12] persistence failure → backend
864
- Bug heuristic: data-correctness bug → +15 backend (API/DB likely source)
865
- Classification reason: Backend dominates (47 vs FE:3 EXT:0) — frontend signals are noise
866
-
867
- Proceeding to plan presentation. No developer confirmation needed.
868
- ```
869
-
870
- ---
871
-
872
- ## What Changed — Strict Enforcement Update
873
-
874
- ### `classify_task` — Deep analysis engine (replaces keyword counting)
875
-
876
- | Before | After |
877
- |---|---|
878
- | Flat keyword counting — every word scored equally | 4-tier weighted scoring — service names = 10× generic words (dynamically loaded from `project-spec.json`) |
879
- | `"dashboard"` → scored as frontend | Root-cause phrases — `"shows wrong count on dashboard"` → backend +12 |
880
- | No negation awareness | Sentence-level negation — `"not a UI issue"` removes frontend weight. Explicit overrides (e.g. `"pure ui"`) safely force `FRONTEND_ONLY`. |
881
- | Bug heuristic: default to backend only on LOW confidence | 5-category bug disambiguation matrix (+12–15pts per category) |
882
- | HIGH confidence even on equal scores | HIGH only when ratio ≥ 1.8× AND Tier 1/2 signal matched |
883
- | Mixed signals → always FULL_STACK | Backend dominates at 2.5× → classified BACKEND_ONLY, frontend treated as noise |
884
- | Validation / Breaking Changes hardcoded | Validation rules, endpoints, DB tables, and Kafka topics dynamically extracted from `project-spec.json` |
885
-
886
- ### `AGENTS.md` — All phases rewritten to strict enforcement
887
-
888
- | Phase | Before | After |
889
- |---|---|---|
890
- | **Phase 00** | Bullet list, no gate | MANDATORY 3-step sequence + ❌ prohibition list |
891
- | **Phase 0 (Resume)** | `"Call read_summary, begin executing"` | Explicit STEP 1/2/3 + ❌ list (no guessing, no re-reading) |
892
- | **Phase 0.7 (Plan Gate)** | `"Build a plan"`, soft suggestions | Every plan section is **mandatory** — omitting any = violation. Explicit proceed/adjust/cancel contract. |
893
- | **Phase 1 (Planning)** | `"Call search_tasks if relevant"` | `search_tasks` is **unconditional** — STEP 1 always, even if "sure" there's no prior work |
894
- | **Phase 2 (Execution)** | Bullet suggestions | MANDATORY code block for all 4 tool calls + `next_step` contract with explicit VIOLATION labels |
895
- | **Phase 3 (Correction)** | `"Immediately call log_rejected_pattern"` | Explicit STEP 1/2/3 + ❌ list — log immediately, not end of session |
896
- | **Phase 4 (PR Handoff)** | `"Call complete → run checks → fix if error"` | Explicit STEP 1-3 **fix → recheck loop** until ZERO errors (Unified 3-tier check) |
897
- | **Guardrails** | Mixed soft/hard language | All `should` → `MUST`, all `avoid` → `FORBIDDEN`, linter errors explicitly blocking |
898
- | **Cross-Task Intelligence** | Prose bullets | MANDATORY STEP 1-4 sequence + ❌ list |
899
-
900
-
901
- ---
902
-
903
- ## 🏗️ v2.0.0 — Native Claude Plugin Architecture
904
-
905
- `secufusion-mcp@2.0.0` is a **complete architectural rebuild** of the MCP server into a native Claude Plugin. It unifies the MCP server, slash commands, personas, and hooks into a single self-contained, portable package following the enterprise-grade `ml-specs` plugin standard.
906
-
907
- ### What Changed
908
-
909
- | Area | Before (≤ 1.2.8) | After (2.0.0) |
910
- |---|---|---|
911
- | **Plugin type** | Standalone MCP server only | Native Claude Plugin (`.claude-plugin/plugin.json` + `.mcp.json`) |
912
- | **Slash commands** | Disconnected — no wiring to server | Natively registered — appear in Claude IDE `/` command menu |
913
- | **Agent personas** | Scattered globally in `.agents/` | Self-contained inside `agents/` within the plugin package |
914
- | **Path portability** | Hardcoded absolute paths | Fully portable via `${CLAUDE_PLUGIN_ROOT}` |
915
- | **DNA plugin** | Separate `secufusion-dna-plugin` package | Fully merged into `secufusion-mcp` |
916
- | **TypeScript build** | Root-level compile | Isolated in `mcp/src/` → compiles to `mcp/dist/` |
917
- | **Repo validation** | Not present | Reads `.secufusion-project-spec.json` to verify all mandatory repos are cloned |
918
- | **Frontend/ext validation** | Not present | Checks `frontend.repo` and `chrome_extension.repo` from project spec |
919
-
920
- ### New Package Structure
921
-
922
- ```
923
- secufusion-mcp/
924
- ├── .claude-plugin/
925
- │ └── plugin.json ← Claude registers this as a native plugin
926
- ├── .mcp.json ← MCP server wired into the plugin (${CLAUDE_PLUGIN_ROOT} relative)
927
- ├── agents/ ← All agent personas (planner, coder, reviewer, claude, AGENTS.md)
928
- ├── commands/ ← All slash command definitions (markdown)
929
- ├── hooks/ ← Lifecycle hooks (knowledge-drift.sh)
930
- ├── mcp/
931
- │ ├── src/
932
- │ │ ├── server.ts ← Main MCP server logic
933
- │ │ └── parsers/ ← Polyglot AST parsers (Java, TS, React, Config, Infra...)
934
- │ ├── dist/ ← Compiled output (what npm ships)
935
- │ └── tsconfig.json ← Isolated TypeScript config
936
- ├── scripts/
937
- │ ├── sfn-pr-check.js ← Pre-PR mechanical guardrail runner
938
- │ └── utils.js
939
- └── package.json
940
- ```
941
-
942
- ### Merged: SecuFusion DNA Plugin
943
-
944
- The previously separate `secufusion-dna-plugin` is now fully merged into `secufusion-mcp`. There is no longer a need to install or configure it separately. All DNA discovery tools are available natively:
945
-
946
- - `scan_repository_stack` — discovers framework/stack and validates repos vs project spec
947
- - `extract_domain_models` — maps JPA entities and domain objects via AST
948
- - `extract_api_endpoints` — maps REST/GraphQL endpoints across all services
949
- - `extract_event_topics` — maps Kafka producers and consumers
950
- - `start_dna_watcher` — starts continuous background file watcher
951
-
952
- ### Mandatory Repository Validation
953
-
954
- During `scan_repository_stack`, the server reads `.secufusion-project-spec.json` and cross-references:
955
- - All keys under `"microservices"` (e.g., `sfn-auth-api`, `sfn-events-api`)
956
- - The `"frontend.repo"` value (e.g., `sfn-web-ui`)
957
- - The `"chrome_extension.repo"` or `"snf-browser-extn"` value (e.g., `snf-browser-extn`)
958
-
959
- If any of these are physically missing from your local workspace folder, a `[WARNING]` is emitted listing exactly which core pillars need to be cloned before a complete DNA map can be built.
960
-
961
- ---
962
-
963
- ## ⚡ End-to-End Slash Command Workflow
964
-
965
- All commands are natively registered as Claude Plugins and appear directly in the Claude IDE `/` command picker. The workflow is streamlined into **5 core commands** with zero redundancy:
966
-
967
- | # | Command | Persona / Role | When to run | What it does |
968
- |---|---|---|---|---|
969
- | **1** | `/sfn-init` | Ecosystem Architect | First thing in morning, on new machine, or new clone | Bootstraps workspace, validates mandatory repos against `.secufusion-project-spec.json`, extracts domain models, API endpoints, Kafka topics, generates `.secufusion/dna.json`, builds full Mermaid architecture diagram, and launches continuous background file watcher (`chokidar`). |
970
- | **2** | `/sfn-plan <ticket-id or desc>` | `planner.md` | When starting any story, chore, feature, bug, or hotfix | Evaluates Phase -1 Philosophy gate (WHY/WHO/WHAT/RISK), creates Markdown business intent (`spec_create_intent`), primes session AST context (`prime_session`), classifies task boundaries (`classify_task`), enforces **Rule 5 STRICT YIELD** for your green light, then generates structured `plan.md`. |
971
- | **3** | `/sfn-code` | `coder.md` | After you approve the plan | Implements strictly according to the approved plan. Enforces zero-trust standards: mandatory tenant isolation on DB operations, proper `@Transactional` scoping, DTO mapping rules, and logs anti-patterns to `.rejected-patterns.json`. |
972
- | **4** | `/sfn-review` | `reviewer.md` | After coding is done, before opening a PR | Adversarial PR gate running 3 tiers in a single pass: (1) Mechanical AST guardrails (tenant isolation, N+1 queries, hardcoded endpoints), (2) AI file-by-file code review, (3) Context-aware task evaluation against spec. Blocks PR if Tier 1 violations exist. |
973
- | **5** | `/sfn-explore [map \| <component>]` | Architecture Explorer | On-demand for cross-service impact & system maps | Dual-mode architecture query: `/sfn-explore map` renders the full cross-service Mermaid architecture diagram; `/sfn-explore <component-or-path>` calculates blast radius and affected downstream consumers before making breaking changes. |
974
-
975
- ---
976
-
977
- ### 📊 The 5-Command SDLC Flow at a Glance
978
-
979
- ```
980
- Morning / First Setup
981
- │
982
- ▼
983
- /sfn-init ← Scans workspace, writes dna.json, draws Mermaid diagram, starts watcher
984
- │
985
- ├─► /sfn-explore map (Optional on-demand: view ecosystem graph)
986
- │
987
- Ticket Arrives (Feature / Bug / Hotfix)
988
- │
989
- ▼
990
- /sfn-plan WI-XXXX ← Phase -1 Philosophy check → Intent WHY → Prime → Classify → STRICT YIELD
991
- │
992
- ├─► User Approves Plan ✅
993
- │
994
- ▼
995
- /sfn-code ← Implement approved plan with zero-trust guardrails
996
- │
997
- ├─► /sfn-explore <comp> (Optional: verify blast radius if touching shared interfaces)
998
- │
999
- ▼
1000
- /sfn-review ← 3-Tier PR Gate: mechanical AST checks + AI review + spec matching
1001
- │
1002
- ▼
1003
- PR Ready to Merge 🚀
1004
- ```
1005
-
1006
- ---
1007
-
1008
- ## Requirements
1009
-
1010
- - **Node.js** >= 18.0.0
1011
- - An MCP-compatible AI client (Antigravity IDE, Claude Desktop, Cursor, Cline, etc.)
1012
-
1013
- ---
1014
-
1015
- ## License
1016
-
1017
- ISC © SecuFusion
1
+ # SecuFusion MCP Server
2
+
3
+ > **Project-level spec driven AI workflow tooling for the SecuFusion platform** — loads full project DNA at session start, enforces zero-trust architecture standards, tracks task specs, and gates PRs with automated guardrail checks.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/secufusion-mcp)](https://www.npmjs.com/package/secufusion-mcp)
6
+ [![license](https://img.shields.io/npm/l/secufusion-mcp)](./LICENSE)
7
+ [![node](https://img.shields.io/node/v/secufusion-mcp)](https://nodejs.org)
8
+
9
+ ---
10
+
11
+ ## What is this?
12
+
13
+ `secufusion-mcp` is a [Model Context Protocol (MCP)](https://modelcontextprotocol.io) server that plugs into AI coding assistants (Claude Desktop, Cursor, Cline, etc.) and gives them **ten powerful tools** to enforce SecuFusion's engineering standards throughout the development lifecycle:
14
+
15
+ | Tool | Phase | What it does |
16
+ |---|---|---|
17
+ | `manage_project_spec` | **Phase 00** — Session Start | Loads `.secufusion-project-spec.json` — full project DNA (ports, repos, domains, coding patterns, golden rules) |
18
+ | `manage_task` | **Phase 0.7 / 1 / 2 / 4** — Task Lifecycle | Creates dynamically named `.secufusion/tasks/{id}-{slug}/` folder (the HOW layer: spec, progress, decisions, files-touched). |
19
+ | `spec_create_intent` | **Phase 1** — Planning | **NEW in v2.1** — Creates the Markdown intent file (the WHY layer: business goal, PM, ACs, polyglot service map). |
20
+ | `spec_read_intent` | **Phase 0 / 1** — Session Start | **NEW in v2.1** — Reads the Markdown intent file and ticks AC checkboxes. |
21
+ | `spec_next_number` | **Phase 1** — Planning | **NEW in v2.1** — Generates the next sequential ID for intent files. |
22
+ | `get_task_history` | **Phase 0 / 1** — Cross-Task Intelligence | Retrieves the full history of a past task before starting similar work |
23
+ | `search_tasks` | **Phase 0 / 1** — Cross-Task Intelligence | Keyword search across all past task files — prevents re-solving solved problems |
24
+ | `get_pattern_from_task` | **Phase 1** — Cross-Task Intelligence | Extracts reusable decisions, file patterns, and test scenarios from a completed task |
25
+ | `manage_branch_state` | Legacy — Branch State | Backward-compatible branch-scoped JSON state tracker (for tasks before `manage_task`) |
26
+ | `log_rejected_pattern` | **Phase 3** — Course Correction | Records bad patterns to `.rejected-patterns.json` so they are never repeated |
27
+ | `get_secufusion_rules` | **Setup** | Returns the `AGENTS.md` rules for AI clients that don't natively support MCP Resources |
28
+ | `classify_task` | **Phase 0.5** — Task Classification | **NEW** — Deep multi-pass analysis engine. Classifies any task as `BACKEND_ONLY`, `FRONTEND_ONLY`, etc. based on root cause. |
29
+ | `prime_session` | **Phase 0** — Session Start | **NEW** — Hyper-efficient session startup. Combines Phase 00 (spec) and Phase 0 (task) into one call using Thin Indexes to optimize context tokens. |
30
+ | `skill_recommend` | **Phase 1** — Planning | **NEW** — Dynamically recommends and retrieves domain-specific coding skills from `skills-catalog.json`. |
31
+
32
+ ---
33
+
34
+ ## 🚀 What's New: MLMCPS Architecture Alignment
35
+
36
+ The SecuFusion MCP has been refactored to align with the advanced MLMCPS framework principles, bringing massive efficiency and UX improvements:
37
+
38
+ 1. **5 High-Impact Slash Commands**: The monolithic agent prompt and fragmented utility scripts are consolidated into 5 clean, focused commands: `/sfn-init`, `/sfn-plan`, `/sfn-code`, `/sfn-review`, and `/sfn-explore`.
39
+ 2. **Subprocess PR Checks**: Tier 1 mechanical checks (`TENANT_ISOLATION`, `N_PLUS_ONE`, etc.) are now extracted into a standalone CLI script (`scripts/sfn-pr-check.js`), allowing them to be run by the AI *or* natively within your CI/CD pipelines.
40
+ 3. **Thin Index Token Discipline**: Context bloat is gone. Tools like `manage_task(read)` and `prime_session` now return lightweight "Thin Indexes"—compact Markdown summaries with absolute file paths—so the AI only reads the full JSON via `view_file` when truly necessary.
41
+ 4. **Dynamic Skill Registry**: A new `skill_recommend` tool allows the AI to dynamically discover domain-specific architectural skills without bloating the base prompt.
42
+ 5. **Phase -1 Philosophy Engine**: An invisible gate that checks the WHY, WHO, WHAT, and RISK of every task (including bugs and hotfixes) before any planning starts. If the business intent or blast radius is unsafe, it stops the AI from writing a single line of code.
43
+ 6. **Built-in Poly-Repo DNA Discovery**: Built directly into `secufusion-mcp`. The AI dynamically analyzes the entire poly-repo workspace at session start, mapping microservices, API contracts, Kafka topologies, frontend repos, and browser extensions into a living knowledge graph (`.secufusion/dna.json`) with an auto-generated Mermaid architecture diagram.
44
+ 7. **Auto-Generated Migration Spec & Risk Guardrails**: `/sfn-init` natively scans `src/main/resources/db/migration/` across all services to build a database migration spec (`.secufusion-migrations.json`). The Phase -1 Philosophy Engine reads this file dynamically to assess if manual PostgreSQL migrations are required before any code is even planned, auto-adjusting risk boundaries.
45
+ 8. **Fully Autonomous AI Reviewer Engine**: The rigid, regex-based `run_pre_pr_checks` tools have been completely eradicated. `/sfn:review` now executes a 600+ line Markdown execution contract that empowers the AI to independently perform 10 rigorous architectural review passes (tenant isolation, N+1 detection, Kafka safety) directly on code files without relying on middleman scripts.
46
+ 9. **Smart Spec Merging & Auto-Sync**: The project specification (`.secufusion-project-spec.json`) now seamlessly syncs with the active MCP plugin version. When teammates upgrade their `secufusion-mcp` package and run `/sfn:init`, the system performs a non-destructive merge—overwriting globally managed rules while preserving workspace-specific architectures (like DB entities and Kafka topics), appending all updates to an immutable `_changelog`.
47
+
48
+ ---
49
+
50
+ ## 🧬 Built-In DNA Discovery & Architecture Exploration
51
+
52
+ `secufusion-mcp` includes native ecosystem-wide discovery tools:
53
+
54
+ - **Dynamic Stack Analysis:** Identifies Java/Spring, Node, Docker, and other frameworks on the fly.
55
+ - **Automated Dependency Mapping:** Generates cross-service dependency maps and evaluates the blast radius of potential changes.
56
+ - **Interactive Commands:** Use `/sfn-init` to map your entire workspace and launch the watcher, and `/sfn-explore` on-demand to render Mermaid architecture graphs or analyze component blast radius.
57
+
58
+ ---
59
+
60
+ ## ⚡ The Shift: "WHY before HOW" Spec-Driven Workflow (v2.1)
61
+
62
+ This is the biggest architectural upgrade to the SecuFusion MCP, fundamentally changing how the AI approaches a new task.
63
+
64
+ ### The Problem
65
+ Previously, the AI acted as a blind code-generator. When given a task (e.g. "Add MFA"), it would immediately jump into writing code or initializing tracking infrastructure (`.secufusion/tasks/`), without understanding **why** the feature was being built, who requested it, or the business risk. Furthermore, its AST parsers were limited to Java/TypeScript, leaving Go, Python, or Rust services completely invisible.
66
+
67
+ ### The v2.1 Solution: The Two-Layer Architecture
68
+ Every task now requires **two complementary files** that the AI reads together:
69
+
70
+ ```
71
+ .secufusion/
72
+ ├── intents/ ← WHY layer (business truth, human-driven, Markdown)
73
+ │ └── 0001-WI-2847-add-mfa-enforcement.md
74
+ │ ├── Business Goal ← why is this being built?
75
+ │ ├── PM Owner ← who owns it?
76
+ │ ├── Acceptance Criteria ← tickable checkboxes
77
+ │ ├── Service Map ← polyglot bridge (Go, Python, Rust...)
78
+ │ └── Risk Assessment ← what breaks if we don't ship?
79
+ │
80
+ └── tasks/WI-2847/ ← HOW layer (code truth, AST-driven, JSON)
81
+ ├── progress.json ← pending/completed ACs
82
+ └── decisions.json ← architectural decisions log
83
+ ```
84
+
85
+ ### The Polyglot Bridge
86
+ The new `spec_create_intent` tool captures a `services_involved` array that is **language-agnostic**. You can list a Go microservice, a Python Lambda, or a COBOL batch job. The AI reads this declaration and knows those services are in scope without needing a custom AST parser.
87
+
88
+ ### The New `/sfn-plan` Flow
89
+ When you type `/sfn-plan WI-2847 Add MFA`:
90
+ 1. **The Guard (Phase -1):** The AI silently runs a `philosophy_check` against your Project DNA. It evaluates the WHY, WHO, WHAT, and RISK of the task. (Note: Bugs and hotfixes still undergo this check, though with slightly relaxed sensing).
91
+ 2. **The Pushback (Phase 1):** If the Philosophy Engine fails the request (e.g. unclear business intent or high risk), the AI will **NOT** plan. It will stop and ask you for clarity: *"Why are we building this? Who confirmed it?"*
92
+ 3. **The WHY (Phase 1.5):** You answer, and the AI generates the Markdown intent file (`spec_create_intent`).
93
+ 4. **The HOW (Phase 2):** Only then does it initialize the code tracking infrastructure (`manage_task`).
94
+ 5. **Context & Classify (Phase 3/4):** The AI loads the AST (`prime_session`), flags architectural risks (`classify_task`), and yields for your approval.
95
+ 6. **The Plan (Phase 5):** The AI outputs the strict implementation plan.
96
+
97
+ ---
98
+
99
+ ## ⚡ The Shift: Problem-Statement Driven → Project-Level Spec Driven
100
+
101
+ ### Before (problem-statement driven)
102
+ The AI started every session **cold**. It had zero knowledge of the codebase and relied entirely on the developer feeding context through a work item description. Every session began with implicit questions:
103
+ - *"Which port does sfn-iam-api run on?"*
104
+ - *"How do you extract tenantId from the JWT?"*
105
+ - *"What's the coding pattern for DTO mapping?"*
106
+
107
+ The AI was **reactive** — it knew only what you told it about the current task.
108
+
109
+ ### After (project-level spec driven)
110
+ The AI starts every session by reading `.secufusion-project-spec.json` — a single file containing the **entire project's DNA**:
111
+
112
+ ```
113
+ ✅ All microservice ports, repos, Eureka names, domains
114
+ ✅ Table ownership per service
115
+ ✅ Inter-service call graph
116
+ ✅ Kafka topics produced/consumed per service
117
+ ✅ Keycloak realm + client config per service
118
+ ✅ Coding patterns (DTO mapping, @Transactional style, tenant passing)
119
+ ✅ Golden rules (tenant isolation layers, authority rules, banned patterns)
120
+ ✅ Flyway migration state per service
121
+ ```
122
+
123
+ The AI is now **proactively context-aware** — it knows your entire architecture before you say a single word about the task:
124
+
125
+ | Before | After |
126
+ |---|---|
127
+ | You explain the service every session | AI already knows all services |
128
+ | You describe the coding pattern | AI reads it from the spec |
129
+ | AI asks which port to use | AI looks it up from the spec |
130
+ | Context resets between sessions | Project knowledge is permanent |
131
+ | Spec is task-scoped | Spec is project-scoped |
132
+
133
+ > **One-time setup:** Generate `.secufusion-project-spec.json` once using the extraction prompt. From that point, every AI session starts fully informed.
134
+
135
+ ---
136
+
137
+ ## 🤖 The Autonomous AI Reviewer Engine (v2.2.4)
138
+
139
+ Version 2.2.0 removes the legacy, rigid TypeScript tools (`run_pre_pr_checks`) and replaces them with a fully standalone, AI-driven markdown execution contract (`/sfn:review`).
140
+
141
+ ### Why is this significant?
142
+ 1. **Context-Aware, Not Regex-Bound**: The old tools blindly searched for regex patterns (like `@TenantScopeException`). The new AI reviewer genuinely reads the file, understands *how* the `tenantId` is flowing through the thread context, and makes intelligent architectural judgments.
143
+ 2. **Zero Dependencies**: You no longer need to rely on the MCP server executing heavy AST-parsing scripts under the hood. The AI handles the review completely independently.
144
+ 3. **10 Strict Passes**: The reviewer is contractually bound to execute 10 precise checks before it can output a verdict, including Kafka blocking detection, Acceptance Criteria coverage, Decision Drift (did you write code you didn't plan?), and Rejected Pattern enforcement.
145
+ 4. **Ruthless Persona**: We injected a specific persona into the reviewer. It is explicitly forbidden from saying "Looks good to me!" to be polite. It operates as a senior architect with a zero-tolerance policy for guardrail violations.
146
+
147
+ ---
148
+
149
+ ## Installation
150
+
151
+ [![Claude Marketplace](https://img.shields.io/badge/Download_from-Claude_Marketplace-blue?logo=anthropic)](https://claude.ai/marketplace/secufusion-mcp)
152
+
153
+ ### Option 1 — `npx` (no install required)
154
+
155
+ ```bash
156
+ npx secufusion-mcp
157
+ ```
158
+
159
+ ### Option 2 — Global install
160
+
161
+ ```bash
162
+ npm install -g secufusion-mcp@2.2.4
163
+ ```
164
+
165
+ ### Option 3 — Local project install
166
+
167
+ ```bash
168
+ npm install --save-dev secufusion-mcp@2.2.4
169
+ ```
170
+
171
+ ---
172
+
173
+ ## Setup: Add to Your MCP Client
174
+
175
+ ### Claude Desktop
176
+
177
+ Edit `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or
178
+ `%APPDATA%\Claude\claude_desktop_config.json` (Windows):
179
+
180
+ ```json
181
+ {
182
+ "mcpServers": {
183
+ "secufusion-mcp": {
184
+ "command": "npx",
185
+ "args": ["-y", "secufusion-mcp"]
186
+ }
187
+ }
188
+ }
189
+ ```
190
+
191
+ ### Cursor
192
+
193
+ Open **Settings → MCP** and add:
194
+
195
+ ```json
196
+ {
197
+ "secufusion-mcp": {
198
+ "command": "npx",
199
+ "args": ["-y", "secufusion-mcp"]
200
+ }
201
+ }
202
+ ```
203
+
204
+ ### Cline (VS Code Extension)
205
+
206
+ Open Cline settings → MCP Servers → Add:
207
+
208
+ ```json
209
+ {
210
+ "secufusion-mcp": {
211
+ "command": "npx",
212
+ "args": ["-y", "secufusion-mcp"],
213
+ "disabled": false
214
+ }
215
+ }
216
+ ```
217
+
218
+ ### Using a local build (development)
219
+
220
+ ```json
221
+ {
222
+ "secufusion-mcp": {
223
+ "command": "node",
224
+ "args": ["C:/path/to/secufusion-mcp/index.js"]
225
+ }
226
+ }
227
+ ```
228
+
229
+ ---
230
+
231
+ ## Tools Reference
232
+
233
+ ### 1. manage_branch_state
234
+
235
+ Manages a structured JSON state file (`.secufusion-state.json`) keyed to the current Git branch. This replaces unstructured Markdown parsing and ensures the AI can resume perfectly.
236
+
237
+ **Parameters:**
238
+
239
+ | Parameter | Type | Required | Description |
240
+ |---|---|---|---|
241
+ | `action` | string | Yes | `initialize`, `read`, or `update` |
242
+ | `task_description` | string | No | (For `initialize`) Summary of the work |
243
+ | `pending_acs` | array | No | Array of strings for pending tasks (For `initialize`/`update`) |
244
+ | `completed_acs` | array | No | Array of completed AC strings (For `update`) |
245
+ | `next_step` | string | No | **CRITICAL for `update`**: A clear instruction on what to do next to allow instant resumption. |
246
+ | `reference_file_path` | string | No | Path to a reference file with standard coding patterns (auto-compressed to save tokens) |
247
+
248
+ **Example — Starting a new task:**
249
+ ```json
250
+ {
251
+ "action": "initialize",
252
+ "task_description": "Implement DeviceActivitySummaryDTO with browserUsage map.",
253
+ "pending_acs": ["Add browserUsage map", "Add unit tests", "Update OpenAPI"]
254
+ }
255
+ ```
256
+
257
+ **Example — Updating progress:**
258
+ ```json
259
+ {
260
+ "action": "update",
261
+ "pending_acs": ["Update OpenAPI"],
262
+ "completed_acs": ["Add browserUsage map", "Add unit tests"],
263
+ "next_step": "Generate the OpenAPI YAML for DeviceActivitySummaryDTO and test generation."
264
+ }
265
+ ```
266
+
267
+ ---
268
+
269
+ ### 2. `log_rejected_pattern`
270
+
271
+ Appends a rejected code pattern to `.rejected-patterns.json`. The AI checks this file implicitly before every architectural suggestion to avoid repeating past mistakes.
272
+
273
+ **Parameters:**
274
+
275
+ | Parameter | Type | Required | Description |
276
+ |---|---|---|---|
277
+ | `pattern` | string | Yes | The bad pattern or approach |
278
+ | `reason` | string | Yes | Why it was rejected and what to do instead |
279
+ | `category` | enum | No | `architecture` \| `security` \| `database` \| `logging` \| `api-design` \| `testing` \| `other` |
280
+ | `file_context` | string | No | File or area where the pattern was observed |
281
+
282
+ **Example:**
283
+
284
+ ```
285
+ Tell your AI: "Never use a global @Repository bean without tenantId scoping again.
286
+ It was leaking cross-tenant data."
287
+ ```
288
+
289
+ The AI will call:
290
+ ```json
291
+ {
292
+ "pattern": "Injecting global @Repository bean and querying without tenantId filter",
293
+ "reason": "Causes cross-tenant data leakage. Always add .where(tenantId = :tenantId) or use TenantAwareRepository base class.",
294
+ "category": "security",
295
+ "file_context": "src/repositories/AuditLogRepository.java"
296
+ }
297
+ ```
298
+
299
+ This writes to `.rejected-patterns.json`:
300
+ ```json
301
+ [
302
+ {
303
+ "id": 1,
304
+ "timestamp": "2026-08-26T14:35:00.000Z",
305
+ "category": "security",
306
+ "pattern": "Injecting global @Repository bean...",
307
+ "reason": "Causes cross-tenant data leakage...",
308
+ "file_context": "src/repositories/AuditLogRepository.java"
309
+ }
310
+ ]
311
+ ```
312
+
313
+ ---
314
+
315
+ ### 3. generate_ado_comments
316
+ ### 3. Native Document Generation (v1.0.58+)
317
+
318
+ Instead of using a generic tool, the agent natively generates two highly structured files based on strict `AGENTS.md` templates:
319
+ - **`ado-comments.md`**: For the Azure DevOps board (Layman summary + Technical Deep-Dive).
320
+ - **`pr-comment.md`**: For the PR Description (Changes, Impact, Scenarios, Guardrails).
321
+
322
+ The AI constructs these dynamically by reading `scenarios.json`, `decisions.json`, and `files-touched.json`, and presents them to the developer.
323
+
324
+ ---
325
+
326
+ ### 4. `manage_project_spec`
327
+
328
+ Loads and manages `.secufusion-project-spec.json` — the permanent project memory file. **Called automatically at the start of every session (Phase 00)** before any task begins.
329
+
330
+ **Parameters:**
331
+
332
+ | Parameter | Type | Required | Description |
333
+ |---|---|---|---|
334
+ | `action` | enum | Yes | `read` \| `get_service` \| `get_golden_rules` \| `get_coding_patterns` \| `update` |
335
+ | `service_name` | string | No | **(For `get_service`)** Name of the microservice, e.g. `sfn-events-api` |
336
+ | `update_path` | string | No | **(For `update`)** Dot-notation path, e.g. `microservices.sfn-iam-api.port` |
337
+ | `update_value` | any | No | **(For `update`)** New value to set at `update_path` |
338
+
339
+ **Actions:**
340
+
341
+ | Action | Returns | Token cost |
342
+ |---|---|---|
343
+ | `read` | Full spec (all services, all patterns, all rules) | High — use once at session start |
344
+ | `get_service` | Only the block for the requested microservice | Low — use when focused on one service |
345
+ | `get_golden_rules` | `golden_rules` block + `rejected_patterns` | Low — use before any architectural decision |
346
+ | `get_coding_patterns` | `coding_patterns` block | Low — use before writing any new class |
347
+ | `update` | Confirmation of surgical dot-notation write | Low — never overwrites the full file |
348
+
349
+ **Example — Session start (reads full project context):**
350
+ ```json
351
+ { "action": "read" }
352
+ ```
353
+
354
+ **Example — Focused lookup before writing a service:**
355
+ ```json
356
+ { "action": "get_service", "service_name": "sfn-iam-api" }
357
+ ```
358
+
359
+ **Example — Check golden rules before an architectural decision:**
360
+ ```json
361
+ { "action": "get_golden_rules" }
362
+ ```
363
+
364
+ **Example — Surgical port update (never overwrites the full file):**
365
+ ```json
366
+ {
367
+ "action": "update",
368
+ "update_path": "microservices.sfn-iam-api.port",
369
+ "update_value": 9005
370
+ }
371
+ ```
372
+
373
+ **File location resolution order:**
374
+ 1. Same directory as `index.js`
375
+ 2. `process.cwd()`
376
+ 3. Walk up from `cwd` (up to 5 levels)
377
+ 4. The global MCP package installation directory (bundled spec fallback)
378
+
379
+ ---
380
+
381
+ ### 5. `get_secufusion_rules`
382
+
383
+ A simple utility tool that returns the raw text of the `AGENTS.md` workflow rules. This is designed as a workaround for AI clients (like older versions of Cline or Claude Code) that do not support the MCP **Resources** capability.
384
+
385
+ By calling this tool, the AI can read the globally bundled rules without you needing to copy the `.agents` folder into your local repository.
386
+
387
+ **Example:**
388
+ > "Call the get_secufusion_rules tool and read the rules before we begin."
389
+
390
+
391
+ ---
392
+
393
+ ## Guardrails Summary
394
+
395
+ These rules are enforced automatically — the AI will never violate them:
396
+
397
+ ```
398
+ ✅ All DB queries and event payloads scoped with tenantId
399
+ ✅ No console.log() or System.out.println() in any source file
400
+ ✅ No hardcoded UAT/Prod IPs or environment URLs
401
+ ✅ Every JPA @Entity change accompanied by a Flyway .sql migration
402
+ ✅ State in .secufusion-state.json must be fully resolved before PR is raised
403
+ ✅ Token Efficiency: Every tool response includes a 📊 Telemetry receipt tracking input/output tokens, cost, and the Session Total
404
+ ```
405
+
406
+ **Performance Guardrails** (enforced whenever writing queries, Kafka consumers, or cross-service calls):
407
+ ```
408
+ ✅ All GET service methods use @Transactional(readOnly = true)
409
+ ✅ No repository method called inside a for/forEach loop — batch with findAllById/saveAll
410
+ ✅ Every new query column that is filtered/sorted has a CREATE INDEX in the Flyway migration
411
+ ✅ Kafka listeners never do synchronous DB writes or REST calls — offload to @Async
412
+ ✅ Every RestTemplate/WebClient call has an explicit timeout and fallback
413
+ ```
414
+
415
+ **Rollback Guardrails** (enforced on every Flyway migration, API contract change, Kafka schema change):
416
+ ```
417
+ ✅ SAFE migration (additive) — safe to roll back by reverting code
418
+ ⚠️ RISKY migration (NOT NULL without DEFAULT) — requires compensating migration
419
+ 🚫 DANGEROUS migration (DROP/RENAME) — requires explicit developer confirmation before writing
420
+ ✅ API hard cutover (removing /v1/ or a field) — requires confirmation; prefer /v2/ + deprecation first
421
+ ✅ Kafka schema change — coordinated deployment of producer + all consumers; flagged in rollback plan
422
+ ✅ Every manage_task initialize logs a rollback strategy starter entry in decisions.json
423
+ ```
424
+
425
+ **Breaking Change Detection** (run as Step 4 in Phase 0.5 before any plan is written):
426
+ ```
427
+ ✅ Check 1: Endpoint consumers — who calls this endpoint? Flag if response shape changes
428
+ ✅ Check 2: Entity/table consumers — @Query annotations across all repos for this column
429
+ ✅ Check 3: Kafka topic consumers — coordinated deployment required if schema changes
430
+ ✅ Check 4: Chrome extension — silent breaks invisible until users report them
431
+ ✅ Over-flag > under-flag: always present a breaking change report if in doubt
432
+ ```
433
+
434
+ **classify_task — Deep Analysis Engine** (runs first on every task, before anything else):
435
+ ```
436
+ ✅ Weighted signal tiers: service names = 10pts, tech constructs = 5pts, generic = 1pt
437
+ ✅ Root-cause extraction: classifies by WHERE THE FIX LIVES, not where the symptom appears
438
+ ✅ Negation detection: "not a UI issue" removes frontend signal weight
439
+ ✅ Bug disambiguation: data-correctness/exception/auth/CRUD/performance bugs → +backend
440
+ ✅ Confidence gate: HIGH only when score ratio ≥ 1.8× AND Tier 1/2 signal matched
441
+ ✅ Persists to .secufusion/classifications/{id}.json — no re-classification on resume
442
+ ```
443
+
444
+ ---
445
+
446
+ ## File Outputs
447
+
448
+ | File | Description | Commit? |
449
+ |---|---|---|
450
+ | `.secufusion-project-spec.json` | **Project DNA** — all services, ports, patterns, golden rules. Generated once, read every session | ✅ Yes |
451
+ | `.secufusion/registry.json` | Index of all initialized work items and their exact dynamic folder names — used by `search_tasks` | ✅ Yes |
452
+ | `.secufusion/tasks/{id}-{slug}/spec.json` | Task spec — title, description, ACs, tags, status | ✅ Yes |
453
+ | `.secufusion/tasks/{id}-{slug}/progress.json` | AC tracking — pending, completed, next_step | ✅ Yes |
454
+ | `.secufusion/tasks/{id}-{slug}/decisions.json` | Architectural decisions log (including rollback strategy) | ✅ Yes |
455
+ | `.secufusion/tasks/{id}-{slug}/files-touched.json` | All files modified with change summaries | ✅ Yes |
456
+ | `.secufusion/tasks/{id}-{slug}/scenarios.json` | Test scenarios (unit / integration / e2e / manual) | ✅ Yes |
457
+ | `.secufusion/tasks/{id}-{slug}/pr-summary.md` | Auto-generated PR summary on `manage_task complete` | ✅ Yes |
458
+ | `.secufusion-state.json` | **Legacy** branch-scoped state — still works via `manage_branch_state` | ✅ Yes |
459
+ | `.rejected-patterns.json` | Cumulative log of all rejected patterns across sessions | ✅ Yes |
460
+ | `.secufusion-tokens.json` | Persistent tracking of session-wide LLM token usage and cost | ❌ No |
461
+
462
+ > **Tip:** Commit the entire `.secufusion/` folder and `.rejected-patterns.json` to your repo. Do **not** commit `.secufusion-tokens.json`.
463
+
464
+ ---
465
+
466
+ ## Workflow Overview
467
+
468
+ ```
469
+ ┌──────────────┬──────────────────────────────────────────────────────────────┐
470
+ │ Phase 00 │ manage_project_spec (action=read + get_golden_rules) │
471
+ │ Project DNA │ → FIRST step — runs before ANY problem statement is read │
472
+ │ (Session │ → AI loaded with ALL services, ports, coding patterns, │
473
+ │ Start) │ Kafka topics, golden rules, and tenant isolation config │
474
+ ├──────────────┼──────────────────────────────────────────────────────────────┤
475
+ │ Phase 0.5 │ Ultimate Reasoning (ReAct) → classify_task │
476
+ │ Task │ Step 1: AI outputs ### Ultimate Reasoning block │
477
+ │ Classification Deconstruction / Observation / Root Cause / Hypothesis │
478
+ │ │ Step 2: classify_task → 5-pass deep analysis engine │
479
+ │ │ Pass 1: Weighted signal scoring (Tier 1-4) │
480
+ │ │ Pass 2: Negation detection per sentence │
481
+ │ │ Pass 3: Root-cause phrase extraction │
482
+ │ │ Pass 4: Bug disambiguation matrix │
483
+ │ │ Pass 5: Confidence gate (≥ 1.8× + Tier 1/2 required) │
484
+ │ │ → allowed_next_action: PROCEED / CONFIRM / STOP │
485
+ ├──────────────┼──────────────────────────────────────────────────────────────┤
486
+ │ Phase 0.6.6 │ manage_task (action=read_summary) OR search_tasks │
487
+ │ Resume │ → Token-efficient status view → resume next_step instantly │
488
+ ├──────────────┼──────────────────────────────────────────────────────────────┤
489
+ │ Phase 0.7 │ Present full plan (scope, files, ACs, perf, rollback) │
490
+ │ Plan Gate │ → STOP and wait for "proceed" / "adjust" / "cancel" │
491
+ │ │ → manage_task (action=initialize) only after proceed │
492
+ ├──────────────┼──────────────────────────────────────────────────────────────┤
493
+ │ Phase -1 │ philosophy_check (Silently validates WHY/WHO/WHAT/RISK) │
494
+ │ Philosophy │ → Blocks planning if intent or safety is unclear (ALL TASKS) │
495
+ ├──────────────┼──────────────────────────────────────────────────────────────┤
496
+ │ Phase 1 │ search_tasks → get_task_history → manage_task initialize │
497
+ │ Planning │ → Creates .secufusion/tasks/{id}-{slug}/ with all 5 files │
498
+ ├──────────────┼──────────────────────────────────────────────────────────────┤
499
+ │ Phase 2 │ manage_task: update_spec / log_file_touched / │
500
+ │ Execution │ log_decision / add_scenario │
501
+ ├──────────────┼──────────────────────────────────────────────────────────────┤
502
+ │ Phase 3 │ log_rejected_pattern │
503
+ │ Correction │ → Record mistakes permanently to avoid repeat │
504
+ ├──────────────┼──────────────────────────────────────────────────────────────┤
505
+ │ Phase 4 │ /sfn:review (Standalone AI Reviewer Engine) │
506
+ │ PR Handoff │ → Enforces 10 strict architecture passes directly on code │
507
+ │ │ → manage_task (action=complete) → pr-summary.md generated │
508
+ │ │ → Document Generation (ado-comments.md, pr-comment.md) │
509
+ └──────────────┴──────────────────────────────────────────────────────────────┘
510
+ ```
511
+
512
+ ---
513
+
514
+ ## Real-World Walkthrough
515
+
516
+ A complete end-to-end example of what you actually type and what happens at each phase.
517
+
518
+ ---
519
+
520
+ ### Step 1 — Integrate (one-time setup)
521
+
522
+ Add this to your MCP client config and restart. That's it.
523
+
524
+ **Antigravity / Claude Desktop / Cline — if you have the source on disk:**
525
+ ```json
526
+ {
527
+ "mcpServers": {
528
+ "secufusion-mcp": {
529
+ "command": "node",
530
+ "args": ["C:\\Users\\YourName\\Desktop\\mcp\\secufusion-mcp\\index.js"],
531
+ "type": "stdio"
532
+ }
533
+ }
534
+ }
535
+ ```
536
+
537
+ **Teammates / fresh machines — pulls from npm, cached after first run:**
538
+ ```json
539
+ {
540
+ "mcpServers": {
541
+ "secufusion-mcp": {
542
+ "command": "npx",
543
+ "args": ["-y", "secufusion-mcp"],
544
+ "type": "stdio"
545
+ }
546
+ }
547
+ }
548
+ ```
549
+
550
+ > **Why two options?** If you have the compiled `index.js` on disk, `node` starts instantly and works fully offline. Teammates who don't have the source use `npx` — it downloads from npm once (~3s), then caches it locally so every subsequent run is instant with no network needed.
551
+
552
+ ---
553
+
554
+ ### Step 2 — Start a new task (Classification phase)
555
+
556
+ Just paste your Azure DevOps work item ID and description directly into the chat. No special syntax needed.
557
+
558
+ Before analyzing the problem statement, the AI has already loaded the Project DNA from Phase 00. It now outputs an **Ultimate Reasoning block** — a structured, spec-grounded analysis of the problem — then calls `classify_task`.
559
+
560
+ **You type:**
561
+ ```
562
+ WI-2847: Add MFA enforcement for admin users on login
563
+
564
+ **User Story:**
565
+ As a security administrator,
566
+ I want to enforce TOTP-based Multi-Factor Authentication (MFA) for all users with the ADMIN role,
567
+ So that sensitive dashboard actions are protected against compromised credentials.
568
+
569
+ **Acceptance Criteria:**
570
+ 1. Any user with the ADMIN role attempting to log in must be prompted for a TOTP token after password verification.
571
+ 2. The system must validate the TOTP token against the user's registered MFA device.
572
+ 3. Service accounts (role = SERVICE_ACCOUNT) are exempt from MFA, even if they possess admin privileges.
573
+ 4. If MFA fails 3 times, the account should be temporarily locked for 15 minutes.
574
+ ```
575
+
576
+ **The AI outputs:**
577
+ ```
578
+ ### Ultimate Reasoning
579
+ - **Deconstruction:** TOTP enforcement is an auth-layer concern. sfn-iam-api owns the login flow.
580
+ - **Observation:** AuthService.java contains the password verification step (line 112). No MFA interceptor exists yet. sfn-iam-api runs on port 9001 per project spec.
581
+ - **Root Cause:** No MFA gate exists between password verification and JWT issuance.
582
+ - **Hypothesis:** Add a MfaVerificationService that validates TOTP after password passes, blocks JWT issuance on failure, and records attempts for lockout logic.
583
+ ```
584
+
585
+ **Then classifies and upon approval initializes:**
586
+ ```json
587
+ {
588
+ "action": "initialize",
589
+ "work_item_id": "2847",
590
+ "title": "Add MFA enforcement for admin users on login",
591
+ "description": "Enforce TOTP-based MFA for ADMIN roles, exempting service accounts, with account lockout on 3 failed attempts.",
592
+ "acceptance_criteria": [
593
+ "Prompt ADMIN users for TOTP token post-password",
594
+ "Validate TOTP token",
595
+ "Exempt SERVICE_ACCOUNT role",
596
+ "Lock account for 15m after 3 failed attempts"
597
+ ],
598
+ "tags": ["security", "auth", "mfa"]
599
+ }
600
+ ```
601
+
602
+ ---
603
+
604
+ ### Step 3 — Write code normally
605
+
606
+ Just code as usual. With the MCP server active, the AI automatically:
607
+
608
+ - Adds `tenantId` scoping to every DB query it writes
609
+ - Uses a proper logger (e.g., `log.info()`) — never `console.log`
610
+ - Reads `.rejected-patterns.json` before making any architectural suggestion
611
+ - Reminds you to create a Flyway migration if it touches a `@Entity`
612
+ - References any `reference_file_path` you provided to match your coding style
613
+
614
+ ---
615
+
616
+ ### Step 4 — Tick off completed work (Execution phase)
617
+
618
+ As you finish pieces of the feature, tell the AI:
619
+
620
+ ```
621
+ I've finished the tenantId scoping on all queries and written the unit tests.
622
+ Update the state.
623
+ ```
624
+
625
+ The AI calls `manage_task` with `action=update_spec` and the state updates:
626
+
627
+ ```json
628
+ {
629
+ "action": "update_spec",
630
+ "work_item_id": "2847",
631
+ "pending_acs": ["Exempt SERVICE_ACCOUNT role", "Lock account for 15m after 3 failed attempts"],
632
+ "completed_acs": ["Prompt ADMIN users for TOTP token post-password", "Validate TOTP token"],
633
+ "next_step": "Implement exemption logic for service accounts in AuthController"
634
+ }
635
+ ```
636
+
637
+
638
+ ---
639
+
640
+ ### Step 5 — Course correction (if the AI does something wrong)
641
+
642
+ Say the AI used a hardcoded URL or proposed a pattern your team has banned:
643
+
644
+ ```
645
+ Stop using hardcoded staging URLs like https://staging.secufusion.io.
646
+ All env URLs must come from application.properties. Never hardcode them.
647
+ ```
648
+
649
+ The AI **immediately** calls `log_rejected_pattern`:
650
+
651
+ ```json
652
+ {
653
+ "pattern": "Hardcoded staging URL https://staging.secufusion.io in source files",
654
+ "reason": "Must use @Value('${app.base-url}') from application.properties. Hardcoded URLs break environment parity and expose internal topology.",
655
+ "category": "security",
656
+ "file_context": "src/services/NotificationService.java"
657
+ }
658
+ ```
659
+
660
+ ---
661
+
662
+ ### Step 6 — Complete the task (PR Handoff phase)
663
+
664
+ When you're done, say:
665
+
666
+ ```
667
+ I'm done with WI-2847. Please complete the task and generate the ADO comments.
668
+ ```
669
+
670
+ The AI marks the task complete, auto-generates a PR summary locally, and then outputs two Azure DevOps comments for you to paste into the ticket:
671
+
672
+ **✅ Passing output:**
673
+ ```
674
+ Here are the comments for your ADO ticket:
675
+
676
+ **Layman Summary:**
677
+ The problem where some devices weren't accurately appearing on the admin dashboard has been resolved. The fix ensures that the system accurately tallies the registered hardware without throwing silent errors.
678
+
679
+ **Technical Deep-Dive:**
680
+ The `DeviceActivitySummaryDTO` was throwing a NullPointerException because the `browserUsage` map was uninitialized when `deviceList` was empty. I added an explicit `ConcurrentHashMap` initialization and scoped the iteration inside a `tenantId` check to preserve cross-tenant boundaries.
681
+ ```
682
+
683
+ ---
684
+
685
+ ## How It Works (The 3 Layers)
686
+
687
+ The SecuFusion MCP operates across three complementary layers to prevent AI amnesia, enforce architecture standards, and gate code quality:
688
+
689
+ **Layer 1 — Project Spec (permanent, project-scoped):** `.secufusion-project-spec.json` — loaded once per session via `manage_project_spec`. The AI never needs to be told what port a service runs on, what pattern to use for DTO mapping, or how tenantId flows through the system.
690
+
691
+ **Layer 2 — Task Memory (persistent, work-item-scoped):** `.secufusion/tasks/{id}-{slug}/` — one dynamically named folder per work item, initialized via `manage_task`. Tracks spec, progress, decisions, files touched, scenarios, and generates a `pr-summary.md` on completion. Cross-task intelligence via `search_tasks`, `get_task_history`, and `get_pattern_from_task` prevents re-solving solved problems.
692
+
693
+ **Layer 3 — AST Guardrails (automated, quality-gating):** ESLint, Maven Checkstyle, tenant isolation scanner, Flyway checker, performance rules, rollback classification, and breaking change detection run at PR time. Cannot be bypassed without explicit `skip_checks`.
694
+
695
+ ### How it all wires together
696
+
697
+ ```
698
+ mcp_config.json → starts the server (tools available)
699
+ +
700
+ .agents/AGENTS.md → tells AI when to invoke each tool
701
+ ↓
702
+ ★ SESSION STARTS
703
+ ↓
704
+ Phase 00: manage_project_spec (read + get_golden_rules)
705
+ → AI's brain loaded with full Project DNA BEFORE any task is read
706
+ → knows all ports, services, patterns, tenant rules from spec
707
+ ↓
708
+ You say: "WI-1042: Add audit log export"
709
+ ↓
710
+ Phase 0.5: ### Ultimate Reasoning (spec-grounded ReAct)
711
+ → Deconstruction / Observation / Root Cause / Hypothesis (written to chat)
712
+ → classify_task: 5-pass deep analysis
713
+ weighted scores + root-cause phrases + negation + bug heuristics
714
+ allowed_next_action: PROCEED (backend) / CONFIRM (mixed) / STOP (frontend)
715
+ + performance risk scan (GREEN/AMBER/RED)
716
+ + breaking change scan (endpoints/entities/Kafka/extension)
717
+ ↓
718
+ Phase 0.7: full plan presented → developer approves ("proceed")
719
+ ↓
720
+ Phase 1: search_tasks (always) → get_task_history → manage_task initialize
721
+ → .secufusion/tasks/1042-add-audit-log-export/ created
722
+ ↓
723
+ Phase 2: code + log_file_touched + log_decision + add_scenario (ALL mandatory)
724
+ ↓
725
+ Phase 4: /sfn:review → APPROVED / DISCUSS
726
+ → manage_task complete → pr-summary.md generated
727
+ → Generate PR & ADO Documents natively using templates
728
+ ```
729
+
730
+ ### Reusing across projects (Global Bundling)
731
+
732
+ As of version **1.0.13+**, `secufusion-mcp` globally bundles both `.secufusion-project-spec.json` and `AGENTS.md`. You **no longer need to copy these files** into every single repository!
733
+
734
+ When you install globally (`npm install -g secufusion-mcp@2.2.4`), the AI can automatically read your rules and project spec on the fly from the global installation.
735
+
736
+ **How to load the Rules in a new project:**
737
+ Depending on your AI client's capabilities, you can load the rules instantly by telling the AI:
738
+ - **"Use the `secufusion_developer` prompt"** (if Prompts are supported)
739
+ - **"Read the `secufusion://rules` resource"** (if Resources are supported)
740
+ - **"Call the `get_secufusion_rules` tool"** (if only Tools are supported)
741
+
742
+ *(If you prefer the legacy method, you can still copy `.agents/AGENTS.md` and `.secufusion-project-spec.json` into your project root).*
743
+
744
+ ### Dynamic Task Folders (v1.0.17+)
745
+
746
+ As of version **1.0.17**, the MCP server automatically generates human-readable, safe folder names for all new tasks using the task's title.
747
+
748
+ When you pass a title like `"BUG-1140: Tenant deletion reports failure"` to `manage_task initialize`, the server strips bad characters, truncates the string safely, and generates a perfect folder name:
749
+ `.secufusion/tasks/BUG-1140-tenant-deletion-reports-failure/`
750
+
751
+ - **Backward Compatible:** The AI only ever needs to supply the `work_item_id` (e.g. `BUG-1140`) for subsequent updates. The server instantly finds the correct folder via `registry.json` (O(1) lookup) or falls back to a prefix scan for legacy `WI-{id}` folders.
752
+ - **OS Safe:** Automatically trims trailing dashes and clamps lengths to prevent Windows `MAX_PATH` errors.
753
+
754
+ ### Dynamic Architecture Validation (v1.0.23+)
755
+
756
+ As of version **1.0.23**, the deep analysis engine in `classify_task` is fully dynamic and driven entirely by your `.secufusion-project-spec.json`:
757
+ - Validation dynamically cross-references explicit microservices, frontend repos, and Chrome extensions.
758
+ - Explicit frontend overrides (e.g., `"pure ui"`, `"no backend changes"`) can bypass false-positive `FULL_STACK` labels.
759
+ - The Breaking Change Pre-Scan safely checks for exact table names and Kafka topics derived from your architecture.
760
+ - `coding_patterns` defined in the spec are injected seamlessly into `secufusionFlags` validation.
761
+
762
+ ### Retrospective Intelligence (v1.0.24+)
763
+
764
+ As of version **1.0.24**, the MCP server introduces a fully automated **Retrospective Layer**:
765
+ - **Auto-Retrospective Trigger**: `manage_task complete` now automatically generates a partial retrospective and asks the developer 7 targeted questions.
766
+ - **record_retrospective**: A new tool that saves retrospective insights, tracking plan accuracy, classification accuracy, and pre-PR check attempts.
767
+ - **Dynamic Learning (Pass 0)**: `classify_task` now includes a Pass 0 that injects learned signals from past retrospectives into the active classification logic.
768
+
769
+ ### Rule 0 Enforcement & Frontend Fallbacks (v1.0.50+)
770
+
771
+ As of version **1.0.50**, the MCP server strictly enforces **Rule 0** and adds intelligent fallbacks:
772
+ - **Rule 0 (DNA Load First)**: Agents are now strictly forbidden from reasoning, classifying, or planning until they have called `manage_project_spec` to load the project DNA.
773
+ - **Auto-Syncing AGENTS.md**: The package now automatically syncs the workspace rules before publishing, guaranteeing AI agents always run the latest constraints.
774
+ - **Frontend Service Resolution**: `get_service` now intelligently resolves frontend and extension repositories (like `sfn-web-ui`) even when they aren't explicitly keyed as backend microservices.
775
+ - **Explicit AC Recognition**: `classify_task` now overrides `VAGUE` completeness warnings if it detects explicit Acceptance Criteria in the task description.
776
+
777
+ ### Strict Comment Guardrails & Slugification Fixes (v1.0.55+)
778
+
779
+ As of version **1.0.55**, the MCP server introduces two new quality-of-life and enforcement updates:
780
+ - **No Ticket IDs in Comments**: A strict rule has been added to `AGENTS.md` and the Tier 2 AI Reviewer now explicitly flags any inline ticket IDs (e.g., `// WI-1097`) inside code comments as a CRITICAL violation. Comments must explain the durable WHY, not point to decaying tracking tickets.
781
+ - **Clean Task Slugs**: `manage_task initialize` now automatically strips leading ticket prefixes (like `BUG-1173: `) from the title before generating the folder slug, preventing duplicated IDs in the folder path (e.g., no more `1173-bug-1173-`).
782
+
783
+ ---
784
+
785
+ ## Talking to the AI — What You'll Ever Say
786
+
787
+ Once all three layers are in place, you interact completely naturally:
788
+
789
+ | Situation | What you say |
790
+ |---|---|
791
+ | 🆕 New task | `WI-XXXX: [paste description from Azure]` |
792
+ | ✅ Done a chunk | `Done with the tenantId scoping, update the state` |
793
+ | ❌ AI did something wrong | `Don't do X, do Y instead` |
794
+ | 🚀 Ready for PR | `Run checks for WI-XXXX` or `Prepare PR` |
795
+ | 🔄 Resuming after a break | `What's left?` or `Resume the current task` |
796
+ | 🔍 Starting similar work | `Has this been done before?` — AI calls `search_tasks` |
797
+ | 📋 Want the full plan first | AI automatically presents plan in Phase 0.7 — type `proceed` to start |
798
+
799
+ **Before `manage_project_spec`:** The AI started cold every session. You explained ports, coding patterns, and tenantId flow every single time.
800
+
801
+ **After `manage_project_spec`:** The AI reads `.secufusion-project-spec.json` at session start and **already knows your entire architecture**. You just describe the work.
802
+
803
+ **Before `manage_task`:** The AI used a flat branch-state file with no cross-task memory.
804
+
805
+ **After `manage_task`:** Every work item has its own structured folder. The AI tracks decisions, files, and scenarios per task. `search_tasks` finds related past work. `get_pattern_from_task` reuses proven approaches.
806
+
807
+ **Before Phase 0.5 + 0.7:** The AI started coding immediately with no ownership check or explicit plan.
808
+
809
+ **After Phase 0.5 + 0.7:** The AI performs deep code investigation, writes an **Ultimate Reasoning** block to prove its root-cause understanding, and then calls `classify_task`. The deep analysis engine confirms the classification, runs a performance risk and breaking change scan, presents a complete plan with rollback strategy, and **waits for your approval before writing a single line of code**.
810
+
811
+ **Before strict AGENTS.md:** Each phase was a soft bullet list with suggestions. The AI could skip steps.
812
+
813
+ **After strict AGENTS.md:** Every phase has a MANDATORY tool-call sequence in code-block format, an explicit ❌ prohibition list, and a hard gate. Skipping any step is a named violation.
814
+
815
+ ---
816
+
817
+ ## Tool 10: `classify_task` — Deep Analysis Engine
818
+
819
+ The **mandatory first step** for every task without exception. Classifies a task as `BACKEND_ONLY`, `FRONTEND_ONLY`, `FULL_STACK`, or `EXTENSION_ONLY` using a 5-pass deep analysis pipeline.
820
+
821
+ > **Core principle:** Classifies by **where the fix lives** — not where the symptom appears.
822
+ > `"Dashboard shows wrong device count"` → fix is in the API/DB query → **BACKEND_ONLY**
823
+ > `"Button layout is broken"` → fix is in the React component → **FRONTEND_ONLY**
824
+
825
+ **Parameters:**
826
+
827
+ | Parameter | Type | Required | Description |
828
+ |---|---|---|---|
829
+ | `work_item_id` | string | Yes | Azure DevOps work item ID, e.g. `BUG-1140` or `2847` |
830
+ | `title` | string | Yes | Full task title from Azure DevOps |
831
+ | `description` | string | Yes | Full task description / problem statement — paste everything |
832
+ | `task_type` | enum | Yes | `bug` \| `user_story` \| `feature` \| `hotfix` \| `refactor` \| `chore` |
833
+
834
+ **The analysis passes:**
835
+
836
+ | Pass | What it does |
837
+ |---|---|
838
+ | **Pass 1 — Weighted signal tiers** | Tier 1: service names = 10pts each (dynamically populated from `project-spec.json`). Tier 2: tech constructs = 5pts. Tier 3: domain terms = 2-3pts. Tier 4: generic words = 1pt. |
839
+ | **Pass 2 — Negation detection** | Scans each sentence. `"not a UI issue"` → frontend penalty. Explicit overrides (e.g. `"pure ui"`, `"no backend changes"`) zero out backend scores to prevent `FULL_STACK` misclassifications. |
840
+ | **Pass 3 — Root-cause phrase extraction** | 25 backend patterns + 9 frontend patterns matched via regex. |
841
+ | **Pass 4 — Bug disambiguation matrix** | For `task_type: bug`: data-correctness → +15 backend, exception/crash → +15 backend, auth/permission → +12 backend. |
842
+ | **Pass 4.5 — Problem Statement Validation** | **NEW (v1.0.19+)**: Validates Title, Scope, and Task Type. Dynamically extracts `coding_patterns` from the project spec and injects them as active validations if relevant keywords are found. |
843
+ | **Pass 5 — Confidence & Breaking Change Gate** | `HIGH` only when dominant score ≥ 1.8× second-place **AND** at least one Tier 1/2 signal matched. Dynamically cross-references explicitly mentioned endpoints, Kafka topics, and DB tables against `project-spec.json` to accurately flag breaking change risks. |
844
+
845
+ **Output — `allowed_next_action`:**
846
+
847
+ | Value | Meaning | What the AI does |
848
+ |---|---|---|
849
+ | `PROCEED` | `BACKEND_ONLY` HIGH confidence | Moves directly to Phase 0.7 plan presentation |
850
+ | `CONFIRM` | Mixed / LOW / extension | Presents analysis report, waits for developer YES |
851
+ | `STOP` | `FRONTEND_ONLY` | Hard stop — routes to frontend team, no code written |
852
+
853
+ **Mixed signal resolution:** Backend dominates only when `backendScore ≥ 2.5× frontendScore`. Below that threshold → `FULL_STACK` (requires confirmation).
854
+
855
+ **Persistence:** Result saved to `.secufusion/classifications/{work_item_id}.json`. Resuming a classified task skips re-classification and loads the prior result.
856
+
857
+ **Example output for a bug:**
858
+ ```
859
+ ✅ BACKEND_ONLY (HIGH confidence)
860
+
861
+ Weighted scores: Backend=47 | Frontend=3 | Extension=0
862
+ Score ratio: 15.7x dominant
863
+ Root-cause evidence: [BE+12] data correctness → backend query | [BE+12] persistence failure → backend
864
+ Bug heuristic: data-correctness bug → +15 backend (API/DB likely source)
865
+ Classification reason: Backend dominates (47 vs FE:3 EXT:0) — frontend signals are noise
866
+
867
+ Proceeding to plan presentation. No developer confirmation needed.
868
+ ```
869
+
870
+ ---
871
+
872
+ ## What Changed — Strict Enforcement Update
873
+
874
+ ### `classify_task` — Deep analysis engine (replaces keyword counting)
875
+
876
+ | Before | After |
877
+ |---|---|
878
+ | Flat keyword counting — every word scored equally | 4-tier weighted scoring — service names = 10× generic words (dynamically loaded from `project-spec.json`) |
879
+ | `"dashboard"` → scored as frontend | Root-cause phrases — `"shows wrong count on dashboard"` → backend +12 |
880
+ | No negation awareness | Sentence-level negation — `"not a UI issue"` removes frontend weight. Explicit overrides (e.g. `"pure ui"`) safely force `FRONTEND_ONLY`. |
881
+ | Bug heuristic: default to backend only on LOW confidence | 5-category bug disambiguation matrix (+12–15pts per category) |
882
+ | HIGH confidence even on equal scores | HIGH only when ratio ≥ 1.8× AND Tier 1/2 signal matched |
883
+ | Mixed signals → always FULL_STACK | Backend dominates at 2.5× → classified BACKEND_ONLY, frontend treated as noise |
884
+ | Validation / Breaking Changes hardcoded | Validation rules, endpoints, DB tables, and Kafka topics dynamically extracted from `project-spec.json` |
885
+
886
+ ### `AGENTS.md` — All phases rewritten to strict enforcement
887
+
888
+ | Phase | Before | After |
889
+ |---|---|---|
890
+ | **Phase 00** | Bullet list, no gate | MANDATORY 3-step sequence + ❌ prohibition list |
891
+ | **Phase 0 (Resume)** | `"Call read_summary, begin executing"` | Explicit STEP 1/2/3 + ❌ list (no guessing, no re-reading) |
892
+ | **Phase 0.7 (Plan Gate)** | `"Build a plan"`, soft suggestions | Every plan section is **mandatory** — omitting any = violation. Explicit proceed/adjust/cancel contract. |
893
+ | **Phase 1 (Planning)** | `"Call search_tasks if relevant"` | `search_tasks` is **unconditional** — STEP 1 always, even if "sure" there's no prior work |
894
+ | **Phase 2 (Execution)** | Bullet suggestions | MANDATORY code block for all 4 tool calls + `next_step` contract with explicit VIOLATION labels |
895
+ | **Phase 3 (Correction)** | `"Immediately call log_rejected_pattern"` | Explicit STEP 1/2/3 + ❌ list — log immediately, not end of session |
896
+ | **Phase 4 (PR Handoff)** | `"Call complete → run checks → fix if error"` | Explicit STEP 1-3 **fix → recheck loop** until ZERO errors (Unified 3-tier check) |
897
+ | **Guardrails** | Mixed soft/hard language | All `should` → `MUST`, all `avoid` → `FORBIDDEN`, linter errors explicitly blocking |
898
+ | **Cross-Task Intelligence** | Prose bullets | MANDATORY STEP 1-4 sequence + ❌ list |
899
+
900
+
901
+ ---
902
+
903
+ ## 🏗️ v2.0.0 — Native Claude Plugin Architecture
904
+
905
+ `secufusion-mcp@2.0.0` is a **complete architectural rebuild** of the MCP server into a native Claude Plugin. It unifies the MCP server, slash commands, personas, and hooks into a single self-contained, portable package following the enterprise-grade `ml-specs` plugin standard.
906
+
907
+ ### What Changed
908
+
909
+ | Area | Before (≤ 1.2.8) | After (2.0.0) |
910
+ |---|---|---|
911
+ | **Plugin type** | Standalone MCP server only | Native Claude Plugin (`.claude-plugin/plugin.json` + `.mcp.json`) |
912
+ | **Slash commands** | Disconnected — no wiring to server | Natively registered — appear in Claude IDE `/` command menu |
913
+ | **Agent personas** | Scattered globally in `.agents/` | Self-contained inside `agents/` within the plugin package |
914
+ | **Path portability** | Hardcoded absolute paths | Fully portable via `${CLAUDE_PLUGIN_ROOT}` |
915
+ | **DNA plugin** | Separate `secufusion-dna-plugin` package | Fully merged into `secufusion-mcp` |
916
+ | **TypeScript build** | Root-level compile | Isolated in `mcp/src/` → compiles to `mcp/dist/` |
917
+ | **Repo validation** | Not present | Reads `.secufusion-project-spec.json` to verify all mandatory repos are cloned |
918
+ | **Frontend/ext validation** | Not present | Checks `frontend.repo` and `chrome_extension.repo` from project spec |
919
+
920
+ ### New Package Structure
921
+
922
+ ```
923
+ secufusion-mcp/
924
+ ├── .claude-plugin/
925
+ │ └── plugin.json ← Claude registers this as a native plugin
926
+ ├── .mcp.json ← MCP server wired into the plugin (${CLAUDE_PLUGIN_ROOT} relative)
927
+ ├── agents/ ← All agent personas (planner, coder, reviewer, claude, AGENTS.md)
928
+ ├── commands/ ← All slash command definitions (markdown)
929
+ ├── hooks/ ← Lifecycle hooks (knowledge-drift.sh)
930
+ ├── mcp/
931
+ │ ├── src/
932
+ │ │ ├── server.ts ← Main MCP server logic
933
+ │ │ └── parsers/ ← Polyglot AST parsers (Java, TS, React, Config, Infra...)
934
+ │ ├── dist/ ← Compiled output (what npm ships)
935
+ │ └── tsconfig.json ← Isolated TypeScript config
936
+ ├── scripts/
937
+ │ ├── sfn-pr-check.js ← Pre-PR mechanical guardrail runner
938
+ │ └── utils.js
939
+ └── package.json
940
+ ```
941
+
942
+ ### Merged: SecuFusion DNA Plugin
943
+
944
+ The previously separate `secufusion-dna-plugin` is now fully merged into `secufusion-mcp`. There is no longer a need to install or configure it separately. All DNA discovery tools are available natively:
945
+
946
+ - `scan_repository_stack` — discovers framework/stack and validates repos vs project spec
947
+ - `extract_domain_models` — maps JPA entities and domain objects via AST
948
+ - `extract_api_endpoints` — maps REST/GraphQL endpoints across all services
949
+ - `extract_event_topics` — maps Kafka producers and consumers
950
+ - `start_dna_watcher` — starts continuous background file watcher
951
+
952
+ ### Mandatory Repository Validation
953
+
954
+ During `scan_repository_stack`, the server reads `.secufusion-project-spec.json` and cross-references:
955
+ - All keys under `"microservices"` (e.g., `sfn-auth-api`, `sfn-events-api`)
956
+ - The `"frontend.repo"` value (e.g., `sfn-web-ui`)
957
+ - The `"chrome_extension.repo"` or `"snf-browser-extn"` value (e.g., `snf-browser-extn`)
958
+
959
+ If any of these are physically missing from your local workspace folder, a `[WARNING]` is emitted listing exactly which core pillars need to be cloned before a complete DNA map can be built.
960
+
961
+ ---
962
+
963
+ ## ⚡ End-to-End Slash Command Workflow
964
+
965
+ All commands are natively registered as Claude Plugins and appear directly in the Claude IDE `/` command picker. The workflow is streamlined into **5 core commands** with zero redundancy:
966
+
967
+ | # | Command | Persona / Role | When to run | What it does |
968
+ |---|---|---|---|---|
969
+ | **1** | `/sfn-init` | Ecosystem Architect | First thing in morning, on new machine, or new clone | Bootstraps workspace, validates mandatory repos against `.secufusion-project-spec.json`, extracts domain models, API endpoints, Kafka topics, generates `.secufusion/dna.json`, builds full Mermaid architecture diagram, and launches continuous background file watcher (`chokidar`). |
970
+ | **2** | `/sfn-plan <ticket-id or desc>` | `planner.md` | When starting any story, chore, feature, bug, or hotfix | Evaluates Phase -1 Philosophy gate (WHY/WHO/WHAT/RISK), creates Markdown business intent (`spec_create_intent`), primes session AST context (`prime_session`), classifies task boundaries (`classify_task`), enforces **Rule 5 STRICT YIELD** for your green light, then generates structured `plan.md`. |
971
+ | **3** | `/sfn-code` | `coder.md` | After you approve the plan | Implements strictly according to the approved plan. Enforces zero-trust standards: mandatory tenant isolation on DB operations, proper `@Transactional` scoping, DTO mapping rules, and logs anti-patterns to `.rejected-patterns.json`. |
972
+ | **4** | `/sfn-review` | `reviewer.md` | After coding is done, before opening a PR | Adversarial PR gate running 3 tiers in a single pass: (1) Mechanical AST guardrails (tenant isolation, N+1 queries, hardcoded endpoints), (2) AI file-by-file code review, (3) Context-aware task evaluation against spec. Blocks PR if Tier 1 violations exist. |
973
+ | **5** | `/sfn-explore [map \| <component>]` | Architecture Explorer | On-demand for cross-service impact & system maps | Dual-mode architecture query: `/sfn-explore map` renders the full cross-service Mermaid architecture diagram; `/sfn-explore <component-or-path>` calculates blast radius and affected downstream consumers before making breaking changes. |
974
+
975
+ ---
976
+
977
+ ### 📊 The 5-Command SDLC Flow at a Glance
978
+
979
+ ```
980
+ Morning / First Setup
981
+ │
982
+ ▼
983
+ /sfn-init ← Scans workspace, writes dna.json, draws Mermaid diagram, starts watcher
984
+ │
985
+ ├─► /sfn-explore map (Optional on-demand: view ecosystem graph)
986
+ │
987
+ Ticket Arrives (Feature / Bug / Hotfix)
988
+ │
989
+ ▼
990
+ /sfn-plan WI-XXXX ← Phase -1 Philosophy check → Intent WHY → Prime → Classify → STRICT YIELD
991
+ │
992
+ ├─► User Approves Plan ✅
993
+ │
994
+ ▼
995
+ /sfn-code ← Implement approved plan with zero-trust guardrails
996
+ │
997
+ ├─► /sfn-explore <comp> (Optional: verify blast radius if touching shared interfaces)
998
+ │
999
+ ▼
1000
+ /sfn-review ← 3-Tier PR Gate: mechanical AST checks + AI review + spec matching
1001
+ │
1002
+ ▼
1003
+ PR Ready to Merge 🚀
1004
+ ```
1005
+
1006
+ ---
1007
+
1008
+ ## Requirements
1009
+
1010
+ - **Node.js** >= 18.0.0
1011
+ - An MCP-compatible AI client (Antigravity IDE, Claude Desktop, Cursor, Cline, etc.)
1012
+
1013
+ ---
1014
+
1015
+ ## License
1016
+
1017
+ ISC © SecuFusion