# MCP + A2A — Execution Checklist

This is the “ready to start building” checklist that turns the docs in this folder into an executable plan.

## 1) Decisions to make (30–60 minutes)

- **MCP server placement** ✅ — `services/mcp-server/` (standalone Fastify service, port 4006)
- **Integration mode** ✅ — REST-only calls to `platform-service` and `extraction-service` for Phase 1
- **Auth strategy** ✅ — platform-service JWT (same `JWT_SECRET`), role-gated per tool
- **Where to store A2A handoffs** ✅ — Phase 1: structured log entries via `req.log`; Phase 2: Cosmos container

## 2) Must-fix dependency before MVP

- **Diagnostics client/server route mismatch** ✅ VERIFIED — `@bytelyst/diagnostics-client` already
  flushes to session-scoped endpoints (`/api/diagnostics/sessions/:id/logs|traces`). No change needed.
  - Confirmed in `packages/diagnostics-client/src/client.ts` flush() method, lines 430–453

## 3) Phase 1 build steps

### Milestone A + C (P0 slice) ✅ — [027e216](https://github.com/saravanakumardb1/learning_ai_common_plat/commit/027e216)

- [x] `platform.telemetry.*` — query, clusters, metrics (3 tools)
- [x] `platform.diagnostics.*` — sessions.list/create/get/update/getLogs/getTraces (6 tools)
- [x] `extraction.*` — run, models, cacheStats (3 tools)
- [x] `support.createDebugPack(productId, targetUserId?, from?, to?, reason?)`

### Milestone B (mutating tools + expiry + cluster status) ✅ — [26d3403](https://github.com/saravanakumardb1/learning_ai_common_plat/commit/26d3403)

- [x] `platform.telemetry.policies.*` — list, preview, create (expiresAt required), update, delete (5 tools)
- [x] `platform.telemetry.clusters.updateStatus` — resolve/ignore/reopen clusters
- [x] `platform.diagnostics.sessions.cancel` — dedicated cancel tool
- [x] `extraction.sidecarHealth` — Python sidecar health check
- [x] `expiresAt` enforced as **required** field on `telemetry.policies.create` at MCP layer
- [x] `productId` required in all query tools, forwarded as `x-product-id`
- [x] `x-request-id` propagated via `req.id` on every upstream call
- [x] default query caps (`QUERY_DEFAULT_LIMIT=20`) + hard caps (`QUERY_MAX_LIMIT=100`)
- [x] role gating (`viewer` / `admin` / `super_admin`) enforced in `requireRole()`
- [x] expiry for diagnostics sessions delegated to platform-service `maxDurationMinutes`

## 4) Phase 1 definition of done ✅ COMPLETE

- [x] Read-only tools work end-to-end against real services (proxy to platform-service + extraction-service)
- [x] Mutating tools are role-gated (`admin` minimum) and log audit entries via `req.log`
- [x] Compound debug pack produces a single structured artifact with cluster refs, session ref, markdown summary
- [x] Telemetry policy CRUD with mandatory `expiresAt` guardrail
- [x] Error cluster triage (resolve / ignore / reopen)
- [x] Python sidecar health visible via `extraction.sidecarHealth`
- [ ] End-to-end integration test with real platform-service (Phase 2)

## 5) Phase 2 — A2A orchestration ✅ COMPLETE

### Milestone D (A2A runner + handoff schemas) ✅ — d1d643f+

- [x] Handoff artifact schemas (Zod): `SupportIncidentBrief`, `TelemetryFindings`, `DiagnosticsSessionResult`, `FinalIncidentReport`
- [x] `DispatcherAgent` — validates brief, fills default 24h time window, decides which steps to run
- [x] `TelemetryAnalystAgent` — queries clusters, filters by platform, derives hypotheses + actions
- [x] `DiagnosticsOrchestratorAgent` — conditionally creates expiring session based on findings severity
- [x] `ReportWriterAgent` — assembles structured `FinalIncidentReport` + full markdown report
- [x] `runIncidentPipeline` runner — logs every step with stable `runId` + `stepId` (audit tracing)
- [x] `support.runIncidentPipeline` MCP tool — single callable entry point for the pipeline
- [x] `McpToolRequest.log` — structured logger added; `routes.ts` passes `req.log` to all tool calls
- [x] 6 Vitest tests covering: no-session run, session creation, skip when no target, upstream failure, log audit, time window defaulting

### Acceptance criteria ✅

- [x] "Support Debug Pack" runs end-to-end via Dispatcher → Telemetry Analyst → Diagnostics Orchestrator → Report Writer
- [x] Every handoff is logged with stable `runId` + `stepId` (Phase 1: logs; Phase 2+: Cosmos container)

## 6) Phase 3 — Product-specific MCP namespaces ✅ COMPLETE

### Milestone E (all 6 product backends) ✅ — f780f0b + fcb3bef

New files per product: `src/lib/<product>-client.ts` + `src/modules/<product>/<product>-tools.ts`

**MindLyst (port 4014) — 9 tools** ✅

- [x] `mindlyst.memory.list` — list memory items (brainId/filter/pagination)
- [x] `mindlyst.memory.retriage` — re-run extraction on item (updates triageResult)
- [x] `mindlyst.memory.patch` — mark_done / mark_undone / increment_nudge / set_reminder
- [x] `mindlyst.memory.reassign` — reassign item to different Brain
- [x] `mindlyst.brains.list` — list role-based brains
- [x] `mindlyst.briefs.getToday` — get today's Daily Brief
- [x] `mindlyst.briefs.list` — list past Daily Briefs
- [x] `mindlyst.streaks.get` — current/longest streak, freeze status
- [x] `mindlyst.reflections.list` — list reflection journal entries
- [x] `mindlyst.extractions.run` — run text through triage/memory-insight/reflection-enrichment

**LysnrAI (port 4015) — 7 tools** ✅

- [x] `lysnrai.transcripts.list` — list dictation transcripts
- [x] `lysnrai.transcripts.runExtraction` — populate extractions[] on a transcript
- [x] `lysnrai.stt.getBackendStatus` — azure/whisper/none health check
- [x] `lysnrai.sessions.list` — list dictation sessions (filter by status)
- [x] `lysnrai.orgs.list` — list organisations
- [x] `lysnrai.apiTokens.list` — list API tokens
- [x] `lysnrai.apiTokens.rotate` — rotate API token (returns new plaintext token once)

**JarvisJr (port 4012) — 7 tools** ✅

- [x] `jarvis.agents.list` — list coaching agents
- [x] `jarvis.agents.duplicate` — duplicate agent with (Copy) suffix
- [x] `jarvis.sessions.list` — list coaching sessions (filter by agentId)
- [x] `jarvis.sessions.stats` — total sessions, streak, per-agent breakdown
- [x] `jarvis.memory.list` — list agent memories (filter by type/minImportance)
- [x] `jarvis.memory.prune` — prune expired memories for an agent
- [x] `jarvis.memory.getContext` — top-N memories for session context

**ChronoMind (port 4011) — 4 tools** ✅

- [x] `chronomind.timers.list` — list cloud-synced timers (filter type/state)
- [x] `chronomind.timers.delete` — delete a timer
- [x] `chronomind.routines.list` — list routines (filter isTemplate)
- [x] `chronomind.syncStatus` — instant sync health (active/pending/unsynced counts)

**NomGap (port 4013) — 6 tools** ✅

- [x] `nomgap.fasting.sessions.list` — list fasting sessions (filter status/date range)
- [x] `nomgap.fasting.stats` — aggregated stats (streak, longestFast, completionRate)
- [x] `nomgap.fasting.stats.weekly` — this week's fasting summary
- [x] `nomgap.push.fire` — fire push notification (7 trigger types)
- [x] `nomgap.push.stats` — delivery stats by trigger type
- [x] `nomgap.push.pending` — list pending delivery backlog

**PeakPulse (port 4010) — 4 tools** ✅

- [x] `peakpulse.sessions.list` — list adventure sessions (filter activityType/status)
- [x] `peakpulse.sessions.export` — export session as portable JSON summary
- [x] `peakpulse.stats` — aggregated stats (distance, elevation, per-activity)
- [x] `peakpulse.routes.get` — GPS track points + haptic events for a session

### Config additions

- [x] 6 new env vars in `config.ts` + `.env.example`: `MINDLYST/LYSNRAI/JARVISJR/CHRONOMIND/NOMGAP/PEAKPULSE_BACKEND_URL`

## 7) Phase 3 Post-Audit — Bug Fixes & Gap Fill ✅ COMPLETE

### Commit c902266 — Critical bug fixes

- [x] **`/api` prefix missing on ALL 6 product clients** — every route was 404 in production
  - Root cause: all backends register routes with `{ prefix: '/api' }` but clients called paths without it
  - Fix: single-line change per client — `${BASE_URL}/api${path}` in all 6 fetch helpers
- [x] **LysnrAI client path `/organizations` → `/orgs`** — backend route is `GET /orgs` not `/organizations`
- [x] **LysnrAI `lysnraiOrgsList` / `lysnraiApiTokensList` had fake `total` field** — backend doesn't return it
- [x] **`lysnraiApiTokenRotate` calls non-existent endpoint** — `/api-tokens/:id/rotate` doesn't exist in backend; function and `lysnrai.apiTokens.rotate` tool both removed
- [x] **`server.ts` description** — updated to include chronomind/nomgap/peakpulse namespaces

### Commit 481760f — DOMAIN_PRODUCTS.md gap fill (+17 tools, total now 52)

| Product        | New tools                                                                                                                                          |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| **MindLyst**   | `mindlyst.memory.get` — single item + full TriageResult                                                                                            |
| **LysnrAI**    | `lysnrai.transcripts.get`, `lysnrai.orgs.get`                                                                                                      |
| **JarvisJr**   | `jarvis.agents.create`, `jarvis.marketplace.listPending`, `jarvis.marketplace.certify`, `jarvis.marketplace.suspend`, `jarvis.marketplace.feature` |
| **ChronoMind** | `chronomind.timers.create`, `chronomind.households.list`                                                                                           |
| **NomGap**     | `nomgap.protocols.list`, `nomgap.bodyStages.list`                                                                                                  |
| **PeakPulse**  | `peakpulse.sessions.get`                                                                                                                           |

All new client functions verified against actual backend route files before addition.

## 9) Phase 4 — Tracker namespace ✅ COMPLETE (commit 33dd530)

Added **tracker.\*** namespace (13 tools) backed by platform-service items/votes/comments/public modules.
Client functions appended to `platform-client.ts` (no new client file — tracker lives in platform-service).

| Namespace            | Tools                                          |
| -------------------- | ---------------------------------------------- |
| `tracker.items.*`    | stats, list, get, create, updateStatus, delete |
| `tracker.votes.*`    | toggle, list                                   |
| `tracker.comments.*` | list, add, delete                              |
| `tracker.public.*`   | roadmap, stats                                 |

MCP server total after this commit: **65 tools** across 12 namespaces.

## 10) Phase 5 — Platform ops namespaces ✅ COMPLETE (commit 0f57a48)

Added **19 tools** across 5 new namespaces, all backed by existing platform-service endpoints.

| Namespace       | Tools                                                                              | Count |
| --------------- | ---------------------------------------------------------------------------------- | ----- |
| `flags.*`       | list, get, upsert (create-or-update), delete, killSwitch                           | 5     |
| `jobs.*`        | list, get, trigger, listRuns                                                       | 4     |
| `maintenance.*` | getCurrent (admin full), set, scheduleWindow                                       | 3     |
| `settings.*`    | get, update, checkKillSwitch                                                       | 3     |
| `webhooks.*`    | listSubscriptions, create, get, update, delete, listDeliveries, test, rotateSecret | 8     |

**Note on flags.upsert**: tries PUT first, falls back to POST on 404 — true upsert semantic.
**Note on webhooks.rotateSecret**: new secret returned once — same as creation behavior.

MCP server total after this commit: **84 tools** across 16 namespaces.

## 11) Phase 5+ quick sanity checks

- If you make telemetry policy-aware clients:
  - ensure `GET /api/telemetry/config` consumption is cached (ETag) and privacy-safe.
- If you add direct Cosmos reads:
  - enforce product scoping at query layer and add explicit auditing for sensitive reads.
