@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
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Server entrypoint for the hve-squad MCP server (Phase 0: stdio, delegated).
3
+ *
4
+ * Wires the authored catalog -> router (JSON Schema validation) -> the
5
+ * CoordinatorEngine seam -> a transport. Uses the low-level MCP `Server` so the
6
+ * raw JSON Schema authored in `tools.catalog.yml` is advertised verbatim on
7
+ * `tools/list` and validated with Ajv on `tools/call`.
8
+ */
9
+ import { pathToFileURL } from "node:url";
10
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
11
+ import { CallToolRequestSchema, ErrorCode, ListResourcesRequestSchema, ListResourceTemplatesRequestSchema, ListToolsRequestSchema, McpError, ReadResourceRequestSchema, SubscribeRequestSchema, UnsubscribeRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
12
+ import { loadCatalog } from "./catalog/catalog.js";
13
+ import { DelegatedCoordinator } from "./engine/delegated.js";
14
+ import { FileSquadMemoryStore } from "./engine/backends/file-squad-memory.js";
15
+ import { LOCAL_MEMORY_TENANT, SQUAD_MEMORY_URI_SCHEME, SquadMemoryResourceProvider, SquadMemorySubscriptionRegistry, } from "./engine/squad-memory-resources.js";
16
+ import { isSafeMemoryPath, isSafeMemorySegment, } from "./engine/squad-memory-state.js";
17
+ import { SQUAD_MEMORY_SYNC_TOOL } from "./auth/scopes.js";
18
+ import { SQUAD_MEMORY_SYNC_DESCRIPTOR } from "./transports/http-core.js";
19
+ import { ToolInputError, ToolRouter } from "./router/router.js";
20
+ import { createStdioTransport } from "./transports/stdio.js";
21
+ export const SERVER_NAME = "hve-squad-mcp";
22
+ /**
23
+ * The version reported in the MCP `initialize` handshake (`serverInfo.version`).
24
+ *
25
+ * Kept in step with `package.json` by a drift check in `test/generator.test.ts`
26
+ * rather than read from disk at runtime: the runtime container image copies only
27
+ * `dist/`, `tools.catalog.yml`, `generated/`, and the cast bundle — there is no
28
+ * `package.json` beside them — so a runtime read would resolve differently in the
29
+ * image than in development. A constant plus a failing test is the cheaper and
30
+ * more honest guarantee.
31
+ */
32
+ export const SERVER_VERSION = "0.7.0";
33
+ /**
34
+ * Render an engine result into MCP tool-call content. For delegated execution
35
+ * this is the "charter contract": the persona to adopt, the matched routing,
36
+ * the framed dispatch request, and the state context — plus a machine-readable
37
+ * JSON block and a required-next-action footer that reinforces Dispatch
38
+ * Discipline (do not answer inline; dispatch the matched role).
39
+ */
40
+ export function renderEngineResult(result) {
41
+ const routing = result.matchedRouting;
42
+ const machine = JSON.stringify({
43
+ mode: result.kind,
44
+ matchedRouting: routing,
45
+ framedRequest: result.framedRequest,
46
+ stateContext: result.stateContext,
47
+ }, null, 2);
48
+ const councilLine = routing.council.length > 0 ? routing.council.join(", ") : "(none)";
49
+ const text = [
50
+ "<!-- hve-squad MCP delegated charter. This is NOT a finished answer. -->",
51
+ "",
52
+ "## systemPrompt (adopt this persona now)",
53
+ "",
54
+ result.systemPrompt,
55
+ "",
56
+ "## matchedRouting",
57
+ "",
58
+ `- intent: ${routing.routingIntent}`,
59
+ `- role: ${routing.role}`,
60
+ `- tier: ${routing.tier}`,
61
+ `- parallel-eligible: ${routing.parallelEligible ? "yes" : "no"}`,
62
+ `- council: ${councilLine}`,
63
+ `- catch-all pipeline: ${routing.catchAll ? "yes" : "no"}`,
64
+ `- gates: ${routing.gates ? "yes" : "no"}`,
65
+ "",
66
+ "## framedRequest",
67
+ "",
68
+ result.framedRequest,
69
+ "",
70
+ "## stateContext",
71
+ "",
72
+ result.stateContext,
73
+ "",
74
+ "## machine-readable",
75
+ "",
76
+ "```json",
77
+ machine,
78
+ "```",
79
+ "",
80
+ "## REQUIRED NEXT ACTION",
81
+ "",
82
+ "Do NOT answer the request yourself. Acting as the Squad Coordinator above,",
83
+ "DISPATCH the matched role via your `runSubagent`/`task` tool against the",
84
+ "framed request, then report back only after the subagent returns.",
85
+ ].join("\n");
86
+ return { content: [{ type: "text", text }] };
87
+ }
88
+ /** Build the server, router, and engine without binding a transport. */
89
+ export function createSquadServer(options = {}) {
90
+ const catalog = options.catalog ?? loadCatalog();
91
+ const router = new ToolRouter(catalog);
92
+ // Inject the optional memory broker into the delegated engine so the charter's
93
+ // stateContext carries a bounded prior-context digest (Step 4.1). With no store
94
+ // this is `{ memoryStore: undefined }` — byte-identical to the Phase 0 default.
95
+ const engine = options.engine ?? new DelegatedCoordinator({ memoryStore: options.memoryStore });
96
+ // The resource read surface is advertised + registered ONLY when a memory store
97
+ // is injected (DR-10: never advertise an unbacked resource surface). With no
98
+ // store the capabilities + handlers are byte-identical to the advisory default.
99
+ // When a store IS injected on THIS (stdio) path, we additionally advertise
100
+ // `resources.subscribe` (WI-01, stdio ONLY) so a duplex client (VS Code) can
101
+ // watch a memory URI and receive `notifications/resources/updated` on a write.
102
+ // The HTTP transport (`http-core.ts`) is POST-only and NEVER advertises this
103
+ // (CON-1: Copilot Studio cannot consume a server stream — it stays poll-on-read).
104
+ const server = new Server({ name: SERVER_NAME, version: SERVER_VERSION }, {
105
+ capabilities: options.memoryStore
106
+ ? { tools: {}, resources: { subscribe: true } }
107
+ : { tools: {} },
108
+ });
109
+ // The stdio write-back tool (WI-02, Phase 4) + its live-push registry are wired
110
+ // ONLY when a memory store is injected. `memorySubscriptions` is declared up
111
+ // front so the CallTool handler below can call its `onWrite` hook after a
112
+ // successful sync item; the resource block further down assigns it.
113
+ const memoryStore = options.memoryStore;
114
+ let memorySubscriptions;
115
+ server.setRequestHandler(ListToolsRequestSchema, () => ({
116
+ // The synthetic `squad_memory_sync` batch write-back tool is advertised ONLY
117
+ // when a store is injected (DR-10: never advertise an unbacked tool); with no
118
+ // store the list is byte-identical to the advisory-only default.
119
+ tools: [
120
+ ...router.listToolDescriptors(),
121
+ ...(memoryStore ? [SQUAD_MEMORY_SYNC_DESCRIPTOR] : []),
122
+ ],
123
+ }));
124
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
125
+ const { name, arguments: args } = request.params;
126
+ // squad_memory_sync is the stdio batch write-back (WI-02). stdio is inside the
127
+ // local trust boundary (no Entra token / scope check — the scope model is the
128
+ // HTTP surface's), so it applies each item's CAS write keyed on the local
129
+ // tenant sentinel and, after each SUCCESSFUL item, calls the subscription
130
+ // registry's `onWrite` so a duplex subscriber gets exactly one
131
+ // `notifications/resources/updated` per written entry. A stale expectedEtag on
132
+ // one item is a per-item conflict that never aborts the rest of the batch.
133
+ if (memoryStore && name === SQUAD_MEMORY_SYNC_TOOL) {
134
+ const record = args ?? {};
135
+ const project = typeof record.project === "string" ? record.project : "";
136
+ if (!isSafeMemorySegment(project)) {
137
+ throw new McpError(ErrorCode.InvalidParams, "squad_memory_sync requires a safe 'project'.");
138
+ }
139
+ const items = Array.isArray(record.items) ? record.items : undefined;
140
+ if (!items) {
141
+ throw new McpError(ErrorCode.InvalidParams, "squad_memory_sync requires an 'items' array.");
142
+ }
143
+ const results = [];
144
+ for (const raw of items) {
145
+ const item = raw ?? {};
146
+ const itemPath = typeof item.path === "string" ? item.path : "";
147
+ const content = typeof item.content === "string" ? item.content : undefined;
148
+ const expectedEtag = typeof item.expectedEtag === "string" ? item.expectedEtag : undefined;
149
+ // SEC-4 traversal guard + shape-check BEFORE the store; a bad item fails
150
+ // that ONE item only and never aborts the rest of the batch.
151
+ if (!isSafeMemoryPath(itemPath) || content === undefined) {
152
+ results.push({ path: itemPath, ok: false });
153
+ continue;
154
+ }
155
+ const result = await memoryStore.write(LOCAL_MEMORY_TENANT, project, itemPath, content, expectedEtag);
156
+ if (result.ok) {
157
+ results.push({ path: itemPath, ok: true, etag: result.etag });
158
+ // Exactly one update notification per successfully-written entry, only
159
+ // for a subscribed URI (the registry no-ops an unwatched URI).
160
+ await memorySubscriptions?.onWrite(`${SQUAD_MEMORY_URI_SCHEME}://${project}/${itemPath}`);
161
+ }
162
+ else {
163
+ results.push({ path: itemPath, ok: false, conflict: true });
164
+ }
165
+ }
166
+ return { content: [{ type: "text", text: JSON.stringify({ project, results }, null, 2) }] };
167
+ }
168
+ const tool = router.getTool(name);
169
+ if (!tool) {
170
+ throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
171
+ }
172
+ try {
173
+ router.validateInput(name, args);
174
+ }
175
+ catch (error) {
176
+ if (error instanceof ToolInputError) {
177
+ throw new McpError(ErrorCode.InvalidParams, error.message);
178
+ }
179
+ throw error;
180
+ }
181
+ const coordinatorRequest = router.toCoordinatorRequest(tool, args);
182
+ const result = await engine.handle(tool, coordinatorRequest);
183
+ return renderEngineResult(result);
184
+ });
185
+ // Shared read surface: the SAME provider serves stdio here and HTTP in
186
+ // `http-core.ts`. stdio is inside the local trust boundary, so the tenant is the
187
+ // local sentinel (no Entra token to resolve one from); the write-back tools are
188
+ // the synthetic `squad_memory_sync` above (MCP resources themselves are read-only).
189
+ if (memoryStore) {
190
+ const resources = new SquadMemoryResourceProvider(memoryStore);
191
+ server.setRequestHandler(ListResourcesRequestSchema, async () => ({
192
+ resources: await resources.list(LOCAL_MEMORY_TENANT),
193
+ }));
194
+ server.setRequestHandler(ReadResourceRequestSchema, async (request) => ({
195
+ contents: (await resources.read(LOCAL_MEMORY_TENANT, request.params.uri)).contents,
196
+ }));
197
+ server.setRequestHandler(ListResourceTemplatesRequestSchema, () => ({
198
+ resourceTemplates: resources.templates(),
199
+ }));
200
+ // Live resource push (WI-01, stdio ONLY). The registry tracks watched URIs;
201
+ // its `onWrite(uri)` hook (called by a memory write path — a future stdio
202
+ // write tool / the Phase 4 `squad_memory_sync`) emits a single
203
+ // `notifications/resources/updated` over the duplex stdio transport for a
204
+ // subscribed URI. `sendResourceUpdated` is the SDK helper for exactly that
205
+ // method; the advertised `resources.subscribe` capability authorizes it.
206
+ memorySubscriptions = new SquadMemorySubscriptionRegistry((uri) => server.sendResourceUpdated({ uri }));
207
+ server.setRequestHandler(SubscribeRequestSchema, (request) => {
208
+ memorySubscriptions?.subscribe(request.params.uri);
209
+ return {};
210
+ });
211
+ server.setRequestHandler(UnsubscribeRequestSchema, (request) => {
212
+ memorySubscriptions?.unsubscribe(request.params.uri);
213
+ return {};
214
+ });
215
+ }
216
+ return { server, router, engine, memorySubscriptions };
217
+ }
218
+ /** Start the server on stdio. */
219
+ export async function main() {
220
+ // Optional local memory broker: when `SQUAD_MCP_MEMORY_DIR` is set, back the
221
+ // stdio read surface with a file store; when unset, stdio stays a no-op (no
222
+ // `resources` advertised) — DR-10 (no unbacked resource surface).
223
+ const memoryDir = (process.env.SQUAD_MCP_MEMORY_DIR ?? "").trim();
224
+ const memoryStore = memoryDir.length > 0 ? new FileSquadMemoryStore({ baseDir: memoryDir }) : undefined;
225
+ const { server, router, engine } = createSquadServer({ memoryStore });
226
+ await server.connect(createStdioTransport());
227
+ process.stderr.write(`[${SERVER_NAME}] running on stdio (mode=${engine.mode}); ` +
228
+ `tools: ${router.toolIds.join(", ")}` +
229
+ `${memoryStore ? "; resources: squad-memory" : ""}\n`);
230
+ }
231
+ // Run only when executed directly (not when imported by tests).
232
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
233
+ main().catch((error) => {
234
+ process.stderr.write(`[${SERVER_NAME}] fatal: ${String(error)}\n`);
235
+ process.exit(1);
236
+ });
237
+ }