@hve-squad/mcp 0.7.0

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.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +46 -0
  3. package/README.md +233 -0
  4. package/dist/src/auth/entra.js +164 -0
  5. package/dist/src/auth/jose-verifier.js +31 -0
  6. package/dist/src/auth/scopes.js +240 -0
  7. package/dist/src/catalog/catalog.js +80 -0
  8. package/dist/src/config/operator-config.js +281 -0
  9. package/dist/src/engine/advisory-pipeline.js +367 -0
  10. package/dist/src/engine/advisory-run-store.js +31 -0
  11. package/dist/src/engine/artifact-store.js +165 -0
  12. package/dist/src/engine/auto-memory.js +207 -0
  13. package/dist/src/engine/backends/azure-blob-artifact-store.js +246 -0
  14. package/dist/src/engine/backends/azure-openai.js +69 -0
  15. package/dist/src/engine/backends/azure-table-run-state.js +319 -0
  16. package/dist/src/engine/backends/azure-table-squad-memory.js +240 -0
  17. package/dist/src/engine/backends/file-squad-memory.js +208 -0
  18. package/dist/src/engine/backends/graph-squad-memory.js +271 -0
  19. package/dist/src/engine/backends/managed-identity-credential.js +33 -0
  20. package/dist/src/engine/backends/overflow-squad-memory.js +151 -0
  21. package/dist/src/engine/backlog-contract.js +200 -0
  22. package/dist/src/engine/business-tools.js +118 -0
  23. package/dist/src/engine/consumption.js +134 -0
  24. package/dist/src/engine/coordinator-engine.js +1 -0
  25. package/dist/src/engine/council.js +204 -0
  26. package/dist/src/engine/delegated.js +190 -0
  27. package/dist/src/engine/dispatch-loop.js +84 -0
  28. package/dist/src/engine/durable-run-state.js +251 -0
  29. package/dist/src/engine/embedded-prompt.js +35 -0
  30. package/dist/src/engine/embedded-roles.js +133 -0
  31. package/dist/src/engine/embedded.js +1023 -0
  32. package/dist/src/engine/federation.js +96 -0
  33. package/dist/src/engine/field-cipher.js +84 -0
  34. package/dist/src/engine/gates.js +241 -0
  35. package/dist/src/engine/markdown-table.js +43 -0
  36. package/dist/src/engine/model-backend.js +16 -0
  37. package/dist/src/engine/persona-loader.js +132 -0
  38. package/dist/src/engine/persona.js +287 -0
  39. package/dist/src/engine/profiles.js +237 -0
  40. package/dist/src/engine/render/pptx-render-service.js +60 -0
  41. package/dist/src/engine/render/python-pptx-render-backend.js +117 -0
  42. package/dist/src/engine/render/render-backend.js +25 -0
  43. package/dist/src/engine/render-embedded.js +69 -0
  44. package/dist/src/engine/routing.js +275 -0
  45. package/dist/src/engine/run-params.js +70 -0
  46. package/dist/src/engine/run-state.js +132 -0
  47. package/dist/src/engine/run-worker.js +60 -0
  48. package/dist/src/engine/squad-history.js +136 -0
  49. package/dist/src/engine/squad-ledger.js +215 -0
  50. package/dist/src/engine/squad-memory-resources.js +218 -0
  51. package/dist/src/engine/squad-memory-state.js +57 -0
  52. package/dist/src/engine/squad-run-recorder.js +212 -0
  53. package/dist/src/engine/targeted-squad-memory.js +94 -0
  54. package/dist/src/engine/workspace.js +68 -0
  55. package/dist/src/observability/logger.js +75 -0
  56. package/dist/src/observability/redact.js +77 -0
  57. package/dist/src/paths.js +108 -0
  58. package/dist/src/router/router.js +88 -0
  59. package/dist/src/server-http.js +304 -0
  60. package/dist/src/server.js +237 -0
  61. package/dist/src/transports/http-core.js +1240 -0
  62. package/dist/src/transports/http.js +90 -0
  63. package/dist/src/transports/session-store.js +78 -0
  64. package/dist/src/transports/stdio.js +12 -0
  65. package/dist/src/worker-main.js +87 -0
  66. package/generated/copilot-studio-connector/README.md +44 -0
  67. package/generated/copilot-studio-connector/agent-instructions.md +90 -0
  68. package/generated/copilot-studio-connector/apiDefinition.swagger.json +60 -0
  69. package/generated/copilot-studio-connector/apiProperties.json +35 -0
  70. package/generated/copilot-studio-connector/connector.manifest.json +86 -0
  71. package/generated/mcp-tools.schema.json +462 -0
  72. package/package.json +61 -0
  73. package/tools.catalog.yml +397 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Peter-N91
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,46 @@
1
+ hve-squad MCP server
2
+ Copyright (c) 2026 Peter-N91
3
+
4
+ This product is licensed under the MIT License (see the LICENSE file). The MIT
5
+ License applies to the original work authored in this repository: the `src/`,
6
+ `test/`, `generators/`, `scripts/`, `host/` (excluding `host/cast/.github/`),
7
+ and `docs/` trees, together with the package metadata files.
8
+
9
+ REDISTRIBUTED CONTENT
10
+ ---------------------
11
+
12
+ `host/cast/.github/` is a SHA-pinned snapshot of the deployed hve-squad cast,
13
+ redistributed verbatim so the container image can resolve real persona bytes at
14
+ runtime without an install step. It is generated by `npm run snapshot:cast` and
15
+ must not be hand-edited. Every bundled file records its pinned upstream source
16
+ and a SHA-256 digest in `host/cast/manifest.json`.
17
+
18
+ The snapshot resolves through the hve-squad APM package (see
19
+ `host/cast/package-pin.json`), which composes content from:
20
+
21
+ - Peter-N91/hve-squad (MIT License)
22
+ - microsoft/hve-core (MIT License; some content CC BY-SA 4.0)
23
+ - github/awesome-copilot (MIT License)
24
+
25
+ Each redistributed file remains under the license of its originating project.
26
+ Consult the upstream repositories for the authoritative license text.
27
+
28
+ THIRD-PARTY DEPENDENCIES
29
+ ------------------------
30
+
31
+ Runtime and build dependencies are declared in `package.json` and fetched at
32
+ install time into `node_modules/` (git-ignored). Their source is not
33
+ redistributed here; each retains its own license.
34
+
35
+ The container image built from `host/Containerfile` additionally installs
36
+ operating-system and Python packages at build time, which retain their own
37
+ licenses and are not redistributed in this repository.
38
+
39
+ TRADEMARKS
40
+ ----------
41
+
42
+ Microsoft, Azure, Microsoft 365, Copilot, Copilot Studio, and Teams are
43
+ trademarks of the Microsoft group of companies. This project is an independent
44
+ community effort and is not endorsed by, sponsored by, or affiliated with
45
+ Microsoft. Third-party trademarks and logos are the property of their respective
46
+ owners; their use here is nominative and does not imply endorsement.
package/README.md ADDED
@@ -0,0 +1,233 @@
1
+ <p align="center">
2
+ <img src="docs/assets/logo.svg" alt="hve-squad-mcp logo" width="120" height="120" />
3
+ </p>
4
+
5
+ # hve-squad MCP server
6
+
7
+ An outbound [Model Context Protocol (MCP)](https://modelcontextprotocol.io) server that exposes the **hve-squad** as coarse, model-invocable tools (five per-role intent tools plus `squad_federate` for the opt-in federation of sub-squads) so MCP hosts can call the squad directly.
8
+
9
+ This is the outbound inverse of the squad's existing inbound MCP template (`squad-src/.github/skills/squad/mcp.template.json`, which registers servers the squad *consumes*). This package ships the squad's *own* server, which other hosts consume.
10
+
11
+ **Documentation:** <https://peter-n91.github.io/hve-squad-mcp/> · **Contributing:** [CONTRIBUTING.md](CONTRIBUTING.md) · **License:** [MIT](LICENSE)
12
+
13
+ ## Status — what works today (read this first)
14
+
15
+ This server has **two execution modes**, at different maturity levels. Be precise about which one a claim refers to.
16
+
17
+ | Mode | Host | State | Behaves as the full APM package? |
18
+ | --- | --- | --- | --- |
19
+ | **Delegated** (stdio) | VS Code GitHub Copilot (local) | Works | **Yes** — VS Code dispatches the real deployed cast. Needs the built package + `apm install` of the cast; install with `npx -y @hve-squad/mcp` or a local build. |
20
+ | **Embedded advisory hero tools** (`squad_research`, `squad_review`, `squad_plan`, `squad_architect`) | Copilot Studio (remote HTTP) | Works, deployable via [host/RUNBOOK.md](host/RUNBOOK.md) | **Advisory parity.** Each runs one server-side dispatch via Azure OpenAI, resolving the **real from-disk persona from the full bundled cast** (98 agents), under Entra auth, gates, tenant isolation and cost caps. Advisory (text) output only — no code execution or deploy. |
21
+ | **Embedded async advisory pipeline** (`squad_run`, `squad_status`) | Copilot Studio (remote HTTP) | **Works end-to-end; single-replica (file) or multi-replica (Azure Table)** | **Advisory parity — full cast, full advisory stages.** Data-driven routing runs research → plan → council → review → backlog over the real cast. Advisory (text) only; code-executing implement/deploy is a deferred execution expansion. |
22
+ | **Deterministic render** (`squad_render_pptx`) | Copilot Studio (remote HTTP) | Opt-in (`SQUAD_MCP_ENABLE_RENDER_PPTX=true`) | **First file-output tool.** Renders content YAML to a `.pptx` with in-image `python-pptx` and returns a short-lived Azure Blob **user-delegation SAS** download link (tenant-scoped path, SAS never logged, `Squad.Render` fail-closed scope, caller YAML is DATA). No model call. |
23
+
24
+ **The async pipeline (`squad_run`) runs the full advisory squad** — data-driven routing over the full bundled cast, sequencing research → plan → (council) → review → backlog-handoff and producing a finished, sectioned advisory artifact. It is **advisory parity**: finished text deliverables, not code-executing implement/deploy (that is a separate, deferred execution expansion). Specifics:
25
+
26
+ - **Off by default** (`SQUAD_MCP_REMOTE_PIPELINE_ENABLED=false`); the default remote surface is the advisory hero tools. Enabling the async pipeline requires a durable run-state backend.
27
+ - **Full cast + routing.** Requests are routed to the real roster roles (researcher → lead → council members → tester) resolved from the SHA-pinned 98-agent cast bundle; the council synthesizes a most-restrictive-wins Council Verdict (Go / Go-With-Conditions / Stop). It honors `mode` (interactive pauses per stage; `autopilot`/`autonomous` run to one compiled artifact).
28
+ - **Releasable by an operator.** `squad_run` holds at a non-bypassable Human Gate; an operator with the distinct `Squad.Operate` app role releases a held run via the out-of-band `POST /admin/approve` route (never a `tools/call`), after which a `squad_status` poll drives it to completion. Approvals are audited (approver + timestamp) and tenant-scoped.
29
+ - **Two run-state backends** (`SQUAD_MCP_RUN_STATE_BACKEND`): `file` (single-replica, local dir) or `table` (Azure Table Storage, cross-replica ETag compare-and-swap). The `table` backend + a store-backed approval channel make release visible across replicas, so a **multi-replica / scale-to-zero** deployment is supported (WI-06). Per-stage artifacts, the Council Verdict, and caller `request`/`context` are AES-256-GCM encrypted at rest when a key is configured.
30
+ - **Long runs (>240s)** are handled by an optional background **worker** (an ACA Job): with `SQUAD_MCP_WORKER_ENABLED=true` the status poll is read-only and the worker drives approved runs off the request path (WI-1b4-WORKER).
31
+
32
+ **Bottom line:** a consumer can deploy this and get the **full package locally in VS Code**, the **advisory hero tools in Copilot Studio today**, and — with the pipeline enabled — the **full advisory squad (routing + full cast + council) working end-to-end** as an async pipeline, single-replica (file) or multi-replica (Azure Table) with a background worker for long runs. Advisory scope is text deliverables only; **code-executing implement/deploy (a real tool-calling backend and a persistent workspace) is a deferred execution expansion** — do not represent that part as available.
33
+
34
+ > Distribution: local **stdio** (delegated) targets VS Code; the remote Streamable HTTP + Entra path (embedded) reaches Copilot Studio and is deployed per [host/RUNBOOK.md](host/RUNBOOK.md). M365 Copilot and Cowork are not targeted yet.
35
+
36
+ ## The tools
37
+
38
+ Each per-role tool maps 1:1 to a routing-table intent row in `squad-routing.instructions.md` (not to one of the ~200 agents); `squad_federate` maps to the Squad Federation Coordinator and drives the opt-in federation meta layer. The Squad Coordinator owns routing; these tools are shortcuts into it.
39
+
40
+ | Tool | Routing intent | Primary role | Tier |
41
+ | --- | --- | --- | --- |
42
+ | `squad_research` | research, investigate, explore | Squad Researcher | auto |
43
+ | `squad_plan` | plan, break down, sequence | Squad Lead | confirm |
44
+ | `squad_review` | review, validate, check quality (+ council go/no-go) | Squad Reviewer (+ council) | auto / confirm |
45
+ | `squad_architect` | architecture, system design, components | System Architecture Reviewer | auto |
46
+ | `squad_run` | full classify-and-dispatch pipeline (catch-all) | Squad Coordinator | confirm + gates |
47
+ | `squad_federate` | federation meta layer: route across named sub-squads (catch-all) | Squad Federation Coordinator | confirm + gates |
48
+
49
+ Every tool's input mirrors the `/squad` prompt arguments: `request` (required), plus optional `profile`, `tier`, `owner`, `mode`, and `context`. All tools also accept an optional `squad` sub-squad name to target a federation sub-squad; `squad_federate` additionally accepts `init` to build a federation (or add a sub-squad to an existing one) and `promote` to adopt an existing single squad into a federation as its first sub-squad.
50
+
51
+ `init` and `promote` are always **confirmation-gated** here: they propose, and a human confirms. The squad also has an unattended bootstrap — Watch Mode auto-promotes or auto-expands a federation and seeds an event-named sub-squad (`issue-123`, `pr-456`) without asking — but that waiver is bounded by things only a repository event supplies: a `squad/*` label or `/squad` keyword opt-in, a write-collaborator check, and a name derived purely from event metadata. This server is not that trigger, so no MCP call can take that path, and a request claiming event provenance confers nothing.
52
+
53
+ Beside these six catalog tools the remote surface serves **synthetic** tools that are not squad routing intents (so they are not in `tools.catalog.yml` and do not participate in the generator drift check). Each has its own least-privilege scope and its own operator flag:
54
+
55
+ | Tool | Scope | Enabled by | What it does |
56
+ | --- | --- | --- | --- |
57
+ | `squad_status` | `Squad.Run` | `SQUAD_MCP_REMOTE_PIPELINE_ENABLED` | Poll an async run by id. |
58
+ | `squad_render_pptx` | `Squad.Render` | `SQUAD_MCP_ENABLE_RENDER_PPTX` | Render content YAML to a `.pptx` download link. |
59
+ | `squad_memory_read` / `_write` / `_sync` | `Squad.Memory` / `Squad.MemoryWrite` | `SQUAD_MCP_ENABLE_MEMORY` | Read / CAS-write / batch-flush the project's own squad memory. |
60
+ | `squad_business_plan` | `Squad.Business` | `SQUAD_MCP_ENABLE_BUSINESS_TOOLS` | A plain-language business plan for a non-technical stakeholder. |
61
+ | `squad_backlog` | `Squad.Backlog` | `SQUAD_MCP_ENABLE_BUSINESS_TOOLS` | A **validated JSON** backlog contract for the native ADO/Jira connectors. |
62
+
63
+ ### Federation (sub-squads)
64
+
65
+ `hve-squad@0.10.x` added an opt-in **federation**: one repository can host several named sub-squads (for example a `product` sub-squad for the business team and an `azure` sub-squad for the architects), each an ordinary squad rooted at `.copilot-tracking/squad/members/<name>/`. The server surfaces this two ways:
66
+
67
+ - **`squad_federate`** maps to the **Squad Federation Coordinator**. It reads the federation registry (`federation.md`) and meta-routing (`meta-routing.md`), routes the request to the matching sub-squad(s) — or the explicit `squad=<name>` — and runs each scoped to its own root. Pass `init` to build a federation (propose → confirm → create) on a fresh project or to add a sub-squad to an existing federation (Expansion Mode: seed `members/<new>/` and register it in `federation.md` + `meta-routing.md`), or `promote` to adopt an existing single squad (a top-level `team.md`) into a federation as its first sub-squad, relocating its state intact (propose → confirm → migrate → seed → route).
68
+ - **The `squad` input** on the five coarse tools targets a single sub-squad directly (`squad_research` with `squad=azure` scopes to `members/azure/`).
69
+
70
+ Federation is additive: on a plain repository (no `federation.md`) the `squad` input is simply omitted and every tool behaves as before. Autonomy modes are forwarded to a single targeted sub-squad; with `mode=autopilot` and no `squad=` target, `squad_federate` runs a coordinated **federation-wide autopilot** meta-pipeline across sub-squads (ordered inner autopilot runs, federation-level gates attributed to the raising sub-squad, one aggregate `cost-ceiling`, and a single consolidated final-outcome validation).
71
+
72
+ **Federation over the remote boundary.** `squad_federate` is reachable from Copilot Studio when the operator enables the gated pipeline (`SQUAD_MCP_REMOTE_PIPELINE_ENABLED=true`). It is the same safety class as `squad_run` — a gated catch-all — so it inherits the same rules: it holds at the non-bypassable Human Gate, returns a run id, and is released out-of-band via `POST /admin/approve` before `squad_status` drives it to a finished federation decision. It requires its own **`Squad.Federate`** scope, deliberately separate from `Squad.Run`, and its `squad` / `init` / `promote` / `mode` inputs are persisted with the run so they survive the approve → poll cycle. Server-side it runs as a Federation Coordinator advisory stage: the routing decision, the per-sub-squad plan, dependencies, and federation-level gates as finished text. The scoping directive is composed only from validated inputs; the caller's free text stays delimited DATA.
73
+
74
+ ### Requirements intake gate
75
+
76
+ `hve-squad@0.10.3` added a conditional **intake gate**: when a run is grounded in requirement or input artifacts (a PRD, BRD, spec, user story, design doc, transcript, or a referenced file), the coordinator validates those inputs for completeness, clarity, testability, consistency, and scope **before** it plans or builds, recording an `## Intake Readiness Verdict` (`Ready`, `Ready-With-Gaps`, `Not-Ready`) in `decisions.md`. On `Not-Ready` it runs a bounded auto-remediation loop (dispatch the analyst/product-owner to fill the blocking gaps, then re-validate; capped at two cycles) and escalates when a gap needs a human decision.
77
+
78
+ The server surfaces the gate in the **delegated (local VS Code)** path: the coordinator persona's gate context now instructs the host to run the intake gate ahead of the Implementation Gate whenever a request is requirements-driven. The gate maps to a new `intake-validator` role that reuses existing agents by input type (PRD Quality Reviewer by default; BRD Quality Reviewer; Squad Challenger), shipped with the `product` and `full` profiles. The gate is conditional and additive &mdash; with no input artifacts in scope it is a silent no-op.
79
+
80
+ The **embedded/advisory pipeline** (`squad_run`) now carries the gate too: `route()` prepends an intake stage for any profile that seeds `intake-validator` (`product`, `full`), and the pipeline records an `## Intake Readiness Verdict` before dispatching a downstream role. A `Not-Ready` verdict **halts the run** (`reason: "intake_not_ready"`) rather than letting the plan and deliverable stages build on inputs the validator just rejected; an unreadable verdict line degrades to `Ready-With-Gaps` rather than to `Ready`.
81
+
82
+ ### Discovery gate
83
+
84
+ `hve-squad@0.15.0` added the intake gate's sibling, on the **inverse** trigger: the intake gate validates a requirement artifact when one exists, and the **discovery gate** fires when none does — a request that states a goal (`reduce onboarding drop-off`) rather than a settled task (`add a retry to the webhook client`). It brainstorms a **brief**, which the intake gate then validates, so the two chain rather than loop.
85
+
86
+ The gate is **offered, never automatic**. Validating a document is something an agent can do alone; ideation is not, because the value of a brainstorm is the human's ideas. So the coordinator asks once per topic, and the depth scales the session to the decision:
87
+
88
+ | `discovery=` | Dispatches | Produces |
89
+ | --- | --- | --- |
90
+ | `quick` | `analyst` | the brief (the recommended default) |
91
+ | `standard` | `designer` (DT Coach), then `analyst` | framing, solution themes, brief |
92
+ | `deep` | `designer`, then `challenger` and `experimenter`, then `analyst` | framing, themes, objections, riskiest assumption, brief |
93
+ | `skip` | nothing | a `Depth: skip` verdict recording the declination |
94
+
95
+ The server surfaces it on the two catch-all entry points — a `discovery` input on **`squad_run`** and **`squad_federate`**, mirroring the `/squad` and `/squad-federation` prompt arguments — and states the contract in the delegated gate context ahead of the Intake Gate: only `analyst` writes a file (the brief, in the `analyst` Deliverable Root, carrying every option considered **with the reason each was discarded**), every dispatched role interviews the user one question at a time and stops rather than inventing an answer it could not get, and the Scribe records a `## Discovery Verdict` in `decisions.md` **including on a decline** — which is what stops the gate re-offering the same topic.
96
+
97
+ **The embedded path never runs it.** An unattended run has nobody to interview, so no offer is made, an explicit `discovery=` is ignored rather than honored (and logged as `discovery_ignored_unattended`), and the caller's payload becomes the intake gate's input instead. The unattended path is therefore never ungated — it is gated by validation rather than by ideation, the only one of the two it can honestly perform.
98
+
99
+ ## Execution model — delegated (local VS Code)
100
+
101
+ The Step 0.1 delegated-drive spike validated this path (Question A = PASS): VS Code Copilot auto-invokes the tool and drives its own in-host dispatch loop. The spike was a disposable de-risking exercise; it is **not** shipped with the package (it is git-ignored — see `.gitignore`). In the delegated (local) mode the server runs **no model**; it returns:
102
+
103
+ - `systemPrompt` — the Squad Coordinator persona plus the squad instruction context relevant to the matched intent;
104
+ - `matchedRouting` — the routing row (role, tier, council, gates);
105
+ - `framedRequest` — the request framed as a dispatch instruction (do not answer inline; dispatch the matched role);
106
+ - `stateContext` — the squad state root and per-turn inputs.
107
+
108
+ The VS Code host ingests this and runs its own `runSubagent`/`task` loop to dispatch the cast — the same path the squad uses today, now reachable as a model-invocable tool instead of only the `/squad` slash command.
109
+
110
+ ## Execution model — embedded (remote / Copilot Studio)
111
+
112
+ Over the remote Streamable HTTP `/mcp` boundary the server runs the squad stage **server-side** (embedded) and returns a finished, `squad-guided / embedded` artifact. This is the mode a Copilot Studio agent consumes. Deploy it with [host/RUNBOOK.md](host/RUNBOOK.md).
113
+
114
+ - **Hero tools** (`squad_research`, `squad_review`) — each runs a single server-side dispatch through the operator-configured Azure OpenAI endpoint, behind Entra audience-bound auth (SEC-1), per-tool scopes (SEC-2), strict Origin allow-list (SEC-8), identity-bound sessions, a per-tenant ephemeral workspace with guaranteed teardown (SEC-4), charter-injection containment (SEC-5), and per-tenant concurrency + monthly cost caps (SEC-9 / COST-2). **This path works and is deployable.**
115
+ - **Async pipeline** (`squad_run` → held run id; `squad_status` → poll) — exposed only when the operator sets `SQUAD_MCP_REMOTE_PIPELINE_ENABLED=true` with a durable run-state backend (`file` local dir, or `table` = Azure Table Storage for multi-replica). `squad_run` holds at a non-bypassable Human Gate; an operator releases a held run out-of-band via `POST /admin/approve` (distinct `Squad.Operate` role), then `squad_status` drives it to completion. Cross-replica release uses the Table backend's ETag compare-and-swap + a store-backed approval record; long runs (>240s) are driven by an optional worker ACA Job (`SQUAD_MCP_WORKER_ENABLED=true`). See the [status section](#status--what-works-today-read-this-first) for the remaining limit (2-stage slice).
116
+
117
+ The embedded and delegated modes share the same router, tool schema, and persona source of truth behind one `CoordinatorEngine` seam; the security model is enforced in `src/transports/http-core.ts`, `src/auth/`, and `src/engine/` and proven by the conformance suites under `test/conformance/`.
118
+
119
+ ## Squad memory — automatic, and portable beyond Azure
120
+
121
+ The shared-state broker exposes the project's own `.copilot-tracking/squad/` memory as tenant-isolated MCP resources plus compare-and-swap write tools (`SQUAD_MCP_ENABLE_MEMORY=true`). Two additions make it usable by a business user in Copilot Studio.
122
+
123
+ **Automatic continuity (`SQUAD_MCP_MEMORY_AUTO_ENABLED=true`).** Memory used to work only if the agent remembered to call the memory tools with a project name it invented — unreliable under generative orchestration, and different every session. With auto-memory on, the server does it: before each embedded dispatch it reads the resolved project's `state` and `decisions` and injects them as **delimited DATA** (never authority, so memory cannot act as instructions); after a completed dispatch it writes the artifact to `history/<toolId>-<runId>` and appends a digest line to `state` under CAS with a bounded retry. The partition comes from a pinned federation sub-squad, else `SQUAD_MCP_MEMORY_DEFAULT_PROJECT` — never from caller free text, so continuity is reproducible and a caller cannot land memory in an arbitrary partition. Reads are capped so unbounded history cannot blow the context window, and a memory outage degrades the run to "no continuity" rather than failing it.
124
+
125
+ **Choose where memory lives.** `SQUAD_MCP_MEMORY_BACKEND` accepts:
126
+
127
+ | Backend | Persistence | CAS | Notes |
128
+ | --- | --- | --- | --- |
129
+ | `file` | local directory | in-file version+hash | single-replica / dev |
130
+ | `table` | Azure Table Storage | ETag | multi-replica / production |
131
+ | `graph` | **SharePoint document library or OneDrive** via Microsoft Graph | native `eTag` + `If-Match` | one readable `.md` per entry at `<rootPath>/<tenantId>/<project>/<path>.md` |
132
+
133
+ The `graph` backend keeps content **plaintext by default** — the point of a SharePoint target is that a human can open, review, and search the file — so encryption there is an explicit opt-in (`SQUAD_MCP_MEMORY_GRAPH_ENCRYPT=true`). The app identity needs an application permission on the target drive; [host/infra/graph-memory-permissions.bicep](host/infra/graph-memory-permissions.bicep) provisions it as least privilege — `Sites.Selected` (which grants no site access on its own) plus a write grant on the single designated site — so the server can reach only the library the operator chose. It is a separate, admin-run deployment so routine app deploys never need Graph admin rights.
134
+
135
+ A deployment can offer **several destinations at once** with `SQUAD_MCP_MEMORY_TARGETS` (a JSON array of named destinations) plus `SQUAD_MCP_MEMORY_DEFAULT_TARGET`. The memory tools then accept an optional `target` naming one of them. The operator owns every credential-bearing field — drive ids, storage accounts, directories — and the caller only ever sees an opaque name, the same allow-list pattern already used for model endpoints. An undeclared name is rejected before any I/O and never silently falls back to the default. Tenant isolation is unaffected: selecting a target changes *where* memory is written, never *whose* memory is reachable.
136
+
137
+ ## Business-user surface (Copilot Studio and Teams)
138
+
139
+ `SQUAD_MCP_ENABLE_BUSINESS_TOOLS=true` adds two tools aimed at non-technical users:
140
+
141
+ - **`squad_business_plan`** — turns an idea or brief into a fixed-section, plain-language business plan (summary, problem and customer, proposed solution, value and success measures, scope, go-to-market, cost outline, risks, milestones, open questions). The fixed section order means successive runs are comparable and the agent can quote a section back to the user.
142
+ - **`squad_backlog`** — turns a request, business plan, or requirements document into a **validated JSON backlog contract**: epics → user stories with Given/When/Then acceptance criteria → tasks, plus a flattened `workItems[]` carrying stable `ref` / `parentRef` ids.
143
+
144
+ `squad_backlog` is the piece that makes the Azure DevOps / Jira flow reliable. The native connector needs one call per work item with typed fields, so a prose handoff forces the orchestrator to parse English — the dominant failure mode (one giant work item, lost acceptance criteria, invented parents). With the JSON contract the agent iterates `workItems` in order, creates parents first, and links children by matching `parentRef` against the ids it recorded — no title matching, no guessing. The server validates and normalizes the model's JSON and fails cleanly if it cannot, so the agent never receives half-parsed output.
145
+
146
+ **The trust boundary is unchanged.** Neither tool writes to Azure DevOps or Jira. This server produces the plan; the certified native connector performs every write on the end user's own connection, under that connector's auth, DLP, and throttles. See [.copilot-tracking/changes/2026-07-24/scenario-a-copilot-studio-ado-jira-runbook.md](.copilot-tracking/changes/2026-07-24/scenario-a-copilot-studio-ado-jira-runbook.md) for the operator runbook, and the generated [agent-instructions.md](generated/copilot-studio-connector/README.md) for the paste-ready Copilot Studio instructions block.
147
+
148
+ ## Build and run
149
+
150
+ Requirements: Node.js >= 20 (developed on Node 24).
151
+
152
+ ```bash
153
+ cd squad-mcp
154
+ npm install
155
+ npm run build # tsc -> dist/
156
+ npm test # router + delegated + generator unit tests
157
+ npm run generate # regenerate generated/mcp-tools.schema.json (drift-fails on mismatch)
158
+ ```
159
+
160
+ To start the server manually on stdio (it speaks JSON-RPC; logs go to stderr):
161
+
162
+ ```bash
163
+ node dist/src/server.js
164
+ ```
165
+
166
+ ## Register in VS Code (delegated / local mode)
167
+
168
+ 1. Build once (`npm install && npm run build`).
169
+ 2. Copy the `servers` entry from `squad-src/.github/skills/squad/mcp-server.template.json` into your workspace `.vscode/mcp.json`.
170
+ 3. Choose the command form:
171
+ - published package: `npx -y @hve-squad/mcp`;
172
+ - local build: `node` with an absolute path to `squad-mcp/dist/src/server.js`.
173
+ 4. Reload VS Code. Ask Copilot to "research X with the squad"; the `squad_*` tools become available, and `squad_research` returns the delegated charter for Copilot to dispatch.
174
+
175
+ The package never writes your `.vscode/mcp.json` — the template is an example you copy.
176
+
177
+ ## The manifest generator (drift check)
178
+
179
+ `generators/build-manifests.ts` reads the authored catalog plus the deployed squad sources — `squad-routing.instructions.md`, `squad-roster.instructions.md`, and the `*.agent.md` personas — all **read-only**, validates them against each other, and emits the runtime descriptor `generated/mcp-tools.schema.json`.
180
+
181
+ The build **fails (exit non-zero)** when a catalog tool maps to a routing intent that is not a real routing row, or to a role/council agent that is not an installed agent. Run it with `npm run generate`; wire it into CI to catch catalog/cast drift.
182
+
183
+ ## Project layout
184
+
185
+ ```text
186
+ squad-mcp/
187
+ tools.catalog.yml # SOURCE OF TRUTH for the 5-tool surface
188
+ src/
189
+ server.ts # entrypoint: catalog -> router -> engine -> transport
190
+ paths.ts # locate package root + squad .github root
191
+ catalog/catalog.ts # parse + type the catalog
192
+ router/router.ts # tools/list + Ajv JSON Schema validation
193
+ transports/stdio.ts # stdio adapter (only per-transport code in P0)
194
+ engine/
195
+ coordinator-engine.ts # the CoordinatorEngine seam (delegated | embedded)
196
+ delegated.ts # DelegatedCoordinator (local; no model)
197
+ embedded.ts # EmbeddedCoordinator (remote; server-side execution + async run)
198
+ dispatch-loop.ts # sequential multi-role pipeline over the model backend
199
+ persona-loader.ts # from-disk *.agent.md persona loader (single-source invariant)
200
+ durable-run-state.ts # durable run-state store (async run + status; single-replica)
201
+ gates.ts # Human Gate, quota caps, auditable approval channel
202
+ persona.ts # paraphrased Coordinator persona + gate instructions
203
+ transports/
204
+ stdio.ts # stdio adapter (delegated / local mode)
205
+ http-core.ts # Streamable HTTP /mcp handler (auth, exposure, routing)
206
+ auth/ # Entra audience-bound auth + per-tool scopes
207
+ config/operator-config.ts # operator-controlled config (never caller-influenced)
208
+ host/ # remote deploy: Containerfile, ACA Bicep IaC, RUNBOOK, cast snapshot
209
+ generators/build-manifests.ts # catalog <-> cast drift check + descriptor emit
210
+ generated/ # committed, regenerable runtime descriptor + Copilot Studio connector
211
+ test/ # unit + conformance (security) suites
212
+ ```
213
+
214
+ ## Additive-only
215
+
216
+ Everything here is new. The generator reads the existing squad sources read-only and never duplicates agent logic; no existing agent, prompt, instruction, or skill is edited. The single source of truth for tool descriptions and routing remains the deployed `.agent.md` personas and the `squad-*` instructions.
217
+
218
+ ## Design references
219
+
220
+ - Remote deploy runbook: [host/RUNBOOK.md](host/RUNBOOK.md) (ACA + Entra + Copilot Studio connector).
221
+ - Dual-mode decision record: [docs/planning/adrs/0001-dual-mode-mcp-exposure-delegated-vs-embedded.md](docs/planning/adrs/0001-dual-mode-mcp-exposure-delegated-vs-embedded.md) (delegated vs embedded, trust boundary, ARCH-1/ARCH-2).
222
+ - IaC: [host/infra/main.bicep](host/infra/main.bicep) · connector: [generated/copilot-studio-connector/README.md](generated/copilot-studio-connector/README.md).
223
+ - Conformance (security) proof: `test/conformance/` (auth rejection, cross-tenant, gate carry-through, remote async, pipeline exposure).
224
+
225
+ ## Contributing
226
+
227
+ Read [CONTRIBUTING.md](CONTRIBUTING.md) first. The short version: never edit `CHANGELOG.md` or the `version` in `package.json` — add a fragment with `npm run change` instead, and CI resolves the release from the fragments on `main`.
228
+
229
+ This repository is **public**. Never commit a tenant id, subscription id, resource endpoint, or secret. Report a vulnerability privately through [GitHub Security Advisories](https://github.com/Peter-N91/hve-squad-mcp/security/advisories/new), not a public issue.
230
+
231
+ ## License
232
+
233
+ MIT — see [LICENSE](LICENSE). The bundled cast under `host/cast/.github/` is redistributed content and each file remains under the license of its originating project; see [NOTICE](NOTICE).
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Entra ID / OAuth authentication + authorization (SEC-1, SEC-2, SEC-3, SEC-10).
3
+ *
4
+ * Attached to the HTTP path only (stdio inherits the local user's trust and is
5
+ * outside the remote trust boundary). Responsibilities:
6
+ *
7
+ * * SEC-1 — no anonymous `/mcp`. Every request must carry a `Bearer` token
8
+ * whose signature, issuer, and expiry validate AND whose audience is bound
9
+ * to THIS resource server (RFC 8707 resource indicator). Tokens minted for
10
+ * another audience (pass-through / confused-deputy tokens) are rejected.
11
+ * * SEC-2 — per-tool scope authorization. `authorizeTool` denies a tool call
12
+ * unless the token carries that tool's required scope.
13
+ * * SEC-3 — tenant resolution. The resolved tenant/identity is the single root
14
+ * for all downstream authorization in the embedded engine; no ambient server
15
+ * identity satisfies a caller request.
16
+ * * SEC-10 — the raw token is registered with the logger for redaction and is
17
+ * NEVER logged or surfaced; failure reasons never echo the token or claims.
18
+ *
19
+ * The cryptographic verification (signature + issuer + expiry) is delegated to a
20
+ * pluggable {@link JwtVerifier} so this authorization logic is unit-testable
21
+ * without a live Entra endpoint or a real signed token. The production verifier
22
+ * (`jose-verifier.ts`) is wired only by the live HTTP bootstrap.
23
+ */
24
+ import { requiredScopeFor, OPERATOR_APPROVAL_SCOPE } from "./scopes.js";
25
+ /** A failed authentication/authorization, carrying the HTTP status to return. */
26
+ export class AuthError extends Error {
27
+ status;
28
+ reason;
29
+ constructor(message, status, reason) {
30
+ super(message);
31
+ this.status = status;
32
+ this.reason = reason;
33
+ this.name = "AuthError";
34
+ }
35
+ }
36
+ function audienceMatches(aud, expected) {
37
+ if (typeof aud === "string") {
38
+ return aud === expected;
39
+ }
40
+ if (Array.isArray(aud)) {
41
+ return aud.includes(expected);
42
+ }
43
+ return false;
44
+ }
45
+ function parseScopes(claims) {
46
+ const scopes = new Set();
47
+ if (typeof claims.scp === "string") {
48
+ for (const scope of claims.scp.split(/\s+/)) {
49
+ if (scope.length > 0) {
50
+ scopes.add(scope);
51
+ }
52
+ }
53
+ }
54
+ if (Array.isArray(claims.roles)) {
55
+ for (const role of claims.roles) {
56
+ if (typeof role === "string" && role.length > 0) {
57
+ scopes.add(role);
58
+ }
59
+ }
60
+ }
61
+ return [...scopes];
62
+ }
63
+ /** Extract the bearer token from an `Authorization` header value. */
64
+ export function extractBearerToken(authorizationHeader) {
65
+ if (!authorizationHeader) {
66
+ return undefined;
67
+ }
68
+ const match = authorizationHeader.match(/^Bearer\s+(.+)$/i);
69
+ return match ? match[1].trim() : undefined;
70
+ }
71
+ /** Authenticates and authorizes remote callers against Entra/OAuth tokens. */
72
+ export class EntraAuthenticator {
73
+ audience;
74
+ allowedIssuers;
75
+ allowedTenants;
76
+ verifier;
77
+ logger;
78
+ constructor(options) {
79
+ this.audience = options.audience;
80
+ this.allowedIssuers = new Set(options.allowedIssuers ?? []);
81
+ this.allowedTenants = new Set(options.allowedTenants ?? []);
82
+ this.verifier = options.verifier;
83
+ this.logger = options.logger;
84
+ }
85
+ /**
86
+ * Authenticate one request. On success returns the resolved {@link AuthContext};
87
+ * on any failure throws {@link AuthError} with the HTTP status. The token is
88
+ * registered as a secret BEFORE any other work so it can never be logged
89
+ * (SEC-10), and failure paths never include the token or claim values.
90
+ */
91
+ async authenticate(authorizationHeader) {
92
+ const token = extractBearerToken(authorizationHeader);
93
+ if (!token) {
94
+ // SEC-1: no anonymous access.
95
+ throw new AuthError("Missing bearer token.", 401, "missing_token");
96
+ }
97
+ // SEC-10: register the raw token so it is redacted everywhere, immediately.
98
+ this.logger.registerSecret(token);
99
+ let claims;
100
+ try {
101
+ claims = await this.verifier.verify(token);
102
+ }
103
+ catch {
104
+ // Never echo the token or the underlying crypto error detail.
105
+ throw new AuthError("Token verification failed.", 401, "invalid_token");
106
+ }
107
+ // SEC-1: audience must be bound to THIS resource server (RFC 8707). A token
108
+ // minted for a different resource (pass-through) is rejected outright.
109
+ if (!audienceMatches(claims.aud, this.audience)) {
110
+ throw new AuthError("Token audience is not bound to this resource.", 401, "wrong_audience");
111
+ }
112
+ if (this.allowedIssuers.size > 0 && (typeof claims.iss !== "string" || !this.allowedIssuers.has(claims.iss))) {
113
+ throw new AuthError("Token issuer is not allowed.", 401, "untrusted_issuer");
114
+ }
115
+ // SEC-3: resolve the tenant — the single identity root for downstream auth.
116
+ const tenantId = typeof claims.tid === "string" ? claims.tid : "";
117
+ if (tenantId.length === 0) {
118
+ throw new AuthError("Token has no tenant claim.", 401, "no_tenant");
119
+ }
120
+ if (this.allowedTenants.size > 0 && !this.allowedTenants.has(tenantId)) {
121
+ throw new AuthError("Tenant is not permitted.", 403, "tenant_not_allowed");
122
+ }
123
+ const subject = (typeof claims.oid === "string" && claims.oid) ||
124
+ (typeof claims.sub === "string" && claims.sub) ||
125
+ "";
126
+ if (subject.length === 0) {
127
+ throw new AuthError("Token has no subject.", 401, "no_subject");
128
+ }
129
+ return {
130
+ tenantId,
131
+ subject,
132
+ scopes: parseScopes(claims),
133
+ audience: this.audience,
134
+ };
135
+ }
136
+ /**
137
+ * Authorize a specific tool call (SEC-2). Throws {@link AuthError} 403 when the
138
+ * caller's token lacks the tool's required scope. `request`/`context` inputs
139
+ * cannot influence this decision — the required scope is fixed per tool.
140
+ */
141
+ authorizeTool(context, toolId) {
142
+ const scope = requiredScopeFor(toolId);
143
+ if (!scope) {
144
+ throw new AuthError(`Unknown tool: ${toolId}`, 403, "unknown_tool");
145
+ }
146
+ if (!context.scopes.includes(scope)) {
147
+ throw new AuthError(`Missing required scope for ${toolId}.`, 403, "missing_scope");
148
+ }
149
+ }
150
+ /**
151
+ * Authorize an out-of-band operator approval (the `/admin/approve` route). Throws
152
+ * {@link AuthError} 403 unless the caller's token carries the distinct
153
+ * high-privilege {@link OPERATOR_APPROVAL_SCOPE} — deliberately NOT `Squad.Run`,
154
+ * so a caller that may start or poll a run cannot release its Human Gate. Like
155
+ * {@link authorizeTool}, no `request`/`context` input can influence this: the
156
+ * required scope is fixed, and this method is only reached from the admin route,
157
+ * never from a `tools/call` or model output (SEC-6).
158
+ */
159
+ authorizeApproval(context) {
160
+ if (!context.scopes.includes(OPERATOR_APPROVAL_SCOPE)) {
161
+ throw new AuthError("Missing operator approval scope.", 403, "missing_operator_scope");
162
+ }
163
+ }
164
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Production JWT verifier backed by `jose` (live only).
3
+ *
4
+ * Isolated in its own module so that:
5
+ * * the `jose` dependency is loaded ONLY by the live HTTP bootstrap, and
6
+ * * the auth authorization logic in `entra.ts` stays unit-testable with a fake
7
+ * {@link JwtVerifier} (no network, no real signed token).
8
+ *
9
+ * It validates the cryptographic and temporal facts only — RS256 signature
10
+ * against the tenant's published JWKS, issuer, and expiry/not-before. Audience,
11
+ * tenant, and scope authorization remain the authenticator's responsibility
12
+ * (see `entra.ts`), so the trust decisions live in one tested place.
13
+ */
14
+ import { createRemoteJWKSet, jwtVerify } from "jose";
15
+ /**
16
+ * Build a {@link JwtVerifier} that verifies tokens against a remote JWKS. The
17
+ * JWKS is fetched and cached by `jose` (with its own rotation handling), so the
18
+ * returned verifier is safe to reuse across requests.
19
+ */
20
+ export function createJoseVerifier(options) {
21
+ const jwks = createRemoteJWKSet(new URL(options.jwksUri));
22
+ return {
23
+ async verify(token) {
24
+ const { payload } = await jwtVerify(token, jwks, {
25
+ issuer: options.issuer,
26
+ clockTolerance: options.clockToleranceSec ?? 60,
27
+ });
28
+ return payload;
29
+ },
30
+ };
31
+ }