@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.
- package/LICENSE +21 -0
- package/NOTICE +46 -0
- package/README.md +233 -0
- package/dist/src/auth/entra.js +164 -0
- package/dist/src/auth/jose-verifier.js +31 -0
- package/dist/src/auth/scopes.js +240 -0
- package/dist/src/catalog/catalog.js +80 -0
- package/dist/src/config/operator-config.js +281 -0
- package/dist/src/engine/advisory-pipeline.js +367 -0
- package/dist/src/engine/advisory-run-store.js +31 -0
- package/dist/src/engine/artifact-store.js +165 -0
- package/dist/src/engine/auto-memory.js +207 -0
- package/dist/src/engine/backends/azure-blob-artifact-store.js +246 -0
- package/dist/src/engine/backends/azure-openai.js +69 -0
- package/dist/src/engine/backends/azure-table-run-state.js +319 -0
- package/dist/src/engine/backends/azure-table-squad-memory.js +240 -0
- package/dist/src/engine/backends/file-squad-memory.js +208 -0
- package/dist/src/engine/backends/graph-squad-memory.js +271 -0
- package/dist/src/engine/backends/managed-identity-credential.js +33 -0
- package/dist/src/engine/backends/overflow-squad-memory.js +151 -0
- package/dist/src/engine/backlog-contract.js +200 -0
- package/dist/src/engine/business-tools.js +118 -0
- package/dist/src/engine/consumption.js +134 -0
- package/dist/src/engine/coordinator-engine.js +1 -0
- package/dist/src/engine/council.js +204 -0
- package/dist/src/engine/delegated.js +190 -0
- package/dist/src/engine/dispatch-loop.js +84 -0
- package/dist/src/engine/durable-run-state.js +251 -0
- package/dist/src/engine/embedded-prompt.js +35 -0
- package/dist/src/engine/embedded-roles.js +133 -0
- package/dist/src/engine/embedded.js +1023 -0
- package/dist/src/engine/federation.js +96 -0
- package/dist/src/engine/field-cipher.js +84 -0
- package/dist/src/engine/gates.js +241 -0
- package/dist/src/engine/markdown-table.js +43 -0
- package/dist/src/engine/model-backend.js +16 -0
- package/dist/src/engine/persona-loader.js +132 -0
- package/dist/src/engine/persona.js +287 -0
- package/dist/src/engine/profiles.js +237 -0
- package/dist/src/engine/render/pptx-render-service.js +60 -0
- package/dist/src/engine/render/python-pptx-render-backend.js +117 -0
- package/dist/src/engine/render/render-backend.js +25 -0
- package/dist/src/engine/render-embedded.js +69 -0
- package/dist/src/engine/routing.js +275 -0
- package/dist/src/engine/run-params.js +70 -0
- package/dist/src/engine/run-state.js +132 -0
- package/dist/src/engine/run-worker.js +60 -0
- package/dist/src/engine/squad-history.js +136 -0
- package/dist/src/engine/squad-ledger.js +215 -0
- package/dist/src/engine/squad-memory-resources.js +218 -0
- package/dist/src/engine/squad-memory-state.js +57 -0
- package/dist/src/engine/squad-run-recorder.js +212 -0
- package/dist/src/engine/targeted-squad-memory.js +94 -0
- package/dist/src/engine/workspace.js +68 -0
- package/dist/src/observability/logger.js +75 -0
- package/dist/src/observability/redact.js +77 -0
- package/dist/src/paths.js +108 -0
- package/dist/src/router/router.js +88 -0
- package/dist/src/server-http.js +304 -0
- package/dist/src/server.js +237 -0
- package/dist/src/transports/http-core.js +1240 -0
- package/dist/src/transports/http.js +90 -0
- package/dist/src/transports/session-store.js +78 -0
- package/dist/src/transports/stdio.js +12 -0
- package/dist/src/worker-main.js +87 -0
- package/generated/copilot-studio-connector/README.md +44 -0
- package/generated/copilot-studio-connector/agent-instructions.md +90 -0
- package/generated/copilot-studio-connector/apiDefinition.swagger.json +60 -0
- package/generated/copilot-studio-connector/apiProperties.json +35 -0
- package/generated/copilot-studio-connector/connector.manifest.json +86 -0
- package/generated/mcp-tools.schema.json +462 -0
- package/package.json +61 -0
- package/tools.catalog.yml +397 -0
|
@@ -0,0 +1,1240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streamable HTTP `/mcp` core handler (SEC-8, SEC-1, SEC-2, PROD-1).
|
|
3
|
+
*
|
|
4
|
+
* A transport-pure handler: it takes a plain request shape and returns a plain
|
|
5
|
+
* response shape, so the entire remote surface — Origin/CORS handling, Entra
|
|
6
|
+
* auth, identity-bound sessions, per-tool scope gating, the hero-tool filter, and
|
|
7
|
+
* JSON-RPC routing into the embedded engine — is unit-testable in-process with no
|
|
8
|
+
* socket, no network, and no live Azure. The socket binding (`http.ts`) is a thin
|
|
9
|
+
* adapter over this.
|
|
10
|
+
*
|
|
11
|
+
* Security ordering (each gate runs before the next does any work):
|
|
12
|
+
* 1. Path + method shape.
|
|
13
|
+
* 2. SEC-8 — Origin allow-list (strict; never `*`) and CORS (echoes the specific
|
|
14
|
+
* Origin, never wildcard-with-credentials).
|
|
15
|
+
* 3. SEC-1 — Entra auth: no anonymous `/mcp`; audience-bound token.
|
|
16
|
+
* 4. SEC-8 — identity-bound session id for every non-initialize request.
|
|
17
|
+
* 5. PROD-1 — only the hero tools are listed/callable over HTTP.
|
|
18
|
+
* 6. SEC-2 — per-tool scope authorization before dispatch.
|
|
19
|
+
*
|
|
20
|
+
* HTTPS is assumed to be terminated at the Container App ingress (the deployment
|
|
21
|
+
* is HTTPS-only); this handler never serves plaintext and emits no protocol over
|
|
22
|
+
* a non-TLS listener (see `http.ts`).
|
|
23
|
+
*/
|
|
24
|
+
import { isAdvisoryExposed, isRemotelyExposed, isMemoryExposed, SQUAD_STATUS_TOOL, SQUAD_RENDER_PPTX_TOOL, SQUAD_MEMORY_READ_TOOL, SQUAD_HISTORY_TOOL, SQUAD_MEMORY_WRITE_TOOL, SQUAD_MEMORY_SYNC_TOOL, SQUAD_FEDERATE_TOOL, SQUAD_BUSINESS_PLAN_TOOL, SQUAD_BACKLOG_TOOL, isBusinessExposed, } from "../auth/scopes.js";
|
|
25
|
+
import { AuthError } from "../auth/entra.js";
|
|
26
|
+
import { McpError } from "@modelcontextprotocol/sdk/types.js";
|
|
27
|
+
import { ToolInputError } from "../router/router.js";
|
|
28
|
+
import { renderEmbeddedResult } from "../engine/render-embedded.js";
|
|
29
|
+
import { SERVER_NAME, SERVER_VERSION } from "../server.js";
|
|
30
|
+
import { SquadMemoryResourceProvider } from "../engine/squad-memory-resources.js";
|
|
31
|
+
import { isSafeMemoryPath } from "../engine/squad-memory-state.js";
|
|
32
|
+
import { MemoryBackedArtifactStore } from "../engine/artifact-store.js";
|
|
33
|
+
import { SquadHistory } from "../engine/squad-history.js";
|
|
34
|
+
import { asTargetedStore, UnknownMemoryTargetError, } from "../engine/targeted-squad-memory.js";
|
|
35
|
+
import { businessToolSpec } from "../engine/business-tools.js";
|
|
36
|
+
import { BacklogContractError, parseBacklog } from "../engine/backlog-contract.js";
|
|
37
|
+
/** The MCP protocol revision this server speaks. */
|
|
38
|
+
export const MCP_PROTOCOL_VERSION = "2025-06-18";
|
|
39
|
+
/**
|
|
40
|
+
* Synthetic `tools/list` descriptor for the status-poll utility. `squad_status`
|
|
41
|
+
* is a transport-level utility (poll a run by id), not a squad routing intent, so
|
|
42
|
+
* it lives here rather than in `tools.catalog.yml` (keeping the catalog = the five
|
|
43
|
+
* routing tools and the generator drift-check clean).
|
|
44
|
+
*/
|
|
45
|
+
const SQUAD_STATUS_DESCRIPTOR = {
|
|
46
|
+
name: SQUAD_STATUS_TOOL,
|
|
47
|
+
title: "Squad Status",
|
|
48
|
+
description: "Poll an async squad run by its run id and return its status; when the run " +
|
|
49
|
+
"is complete, return the finished squad-guided artifact.",
|
|
50
|
+
inputSchema: {
|
|
51
|
+
type: "object",
|
|
52
|
+
additionalProperties: false,
|
|
53
|
+
required: ["runId"],
|
|
54
|
+
properties: {
|
|
55
|
+
runId: {
|
|
56
|
+
type: "string",
|
|
57
|
+
description: "The server-allocated run id returned by squad_run.",
|
|
58
|
+
},
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Synthetic `tools/list` descriptor for the deterministic render tool. Like
|
|
64
|
+
* `squad_status`, `squad_render_pptx` is a transport-level utility rather than a
|
|
65
|
+
* squad routing intent, so it lives here rather than in `tools.catalog.yml`
|
|
66
|
+
* (keeping the catalog = the five routing tools and the generator drift-check
|
|
67
|
+
* clean). Served only when the operator enabled the render feature.
|
|
68
|
+
*/
|
|
69
|
+
const SQUAD_RENDER_PPTX_DESCRIPTOR = {
|
|
70
|
+
name: SQUAD_RENDER_PPTX_TOOL,
|
|
71
|
+
title: "Squad Render PPTX",
|
|
72
|
+
description: "Render a PowerPoint deck from content YAML and style YAML and return a " +
|
|
73
|
+
"short-lived download link to the generated .pptx file. Deterministic: no " +
|
|
74
|
+
"model call, no impactful action.",
|
|
75
|
+
inputSchema: {
|
|
76
|
+
type: "object",
|
|
77
|
+
additionalProperties: false,
|
|
78
|
+
required: ["contentYaml", "styleYaml"],
|
|
79
|
+
properties: {
|
|
80
|
+
contentYaml: {
|
|
81
|
+
type: "string",
|
|
82
|
+
description: "A YAML document with a top-level 'slides:' array; each item is one " +
|
|
83
|
+
"slide's content definition.",
|
|
84
|
+
},
|
|
85
|
+
styleYaml: {
|
|
86
|
+
type: "string",
|
|
87
|
+
description: "The global style.yaml body (dimensions, layouts, defaults).",
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* Shape guard for the `project` partition input (a single lowercase dns-ish
|
|
94
|
+
* label). It is the single source of truth for BOTH the synthetic descriptors'
|
|
95
|
+
* JSON Schema `pattern` (via `.source`) and the runtime shape-check in
|
|
96
|
+
* {@link HttpMcpHandler.handleToolCall}, so a caller-supplied `project` can never
|
|
97
|
+
* escape its `tenantId:project` partition (SEC-3 / SEC-4).
|
|
98
|
+
*/
|
|
99
|
+
const MEMORY_PROJECT_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
|
|
100
|
+
/**
|
|
101
|
+
* The optional named-destination selector shared by every memory tool descriptor.
|
|
102
|
+
*
|
|
103
|
+
* Trust model: the caller may only SELECT among destinations the operator
|
|
104
|
+
* declared (`SQUAD_MCP_MEMORY_TARGETS`) — it can never supply a drive id, a
|
|
105
|
+
* storage account, or a path root. An unknown name is rejected before any I/O.
|
|
106
|
+
* On a deployment that declared no targets the input is accepted and ignored, so
|
|
107
|
+
* the same connector works against both shapes.
|
|
108
|
+
*/
|
|
109
|
+
const MEMORY_TARGET_PROPERTY = {
|
|
110
|
+
type: "string",
|
|
111
|
+
pattern: "^[a-z0-9][a-z0-9-]{0,63}$",
|
|
112
|
+
description: "Optional operator-declared storage destination to use (for example a SharePoint " +
|
|
113
|
+
"library). Omit to use the deployment's default destination.",
|
|
114
|
+
};
|
|
115
|
+
/**
|
|
116
|
+
* The JSON-RPC error code returned when `squad_memory_write` loses a
|
|
117
|
+
* compare-and-swap race. It sits in the application-defined JSON-RPC server range
|
|
118
|
+
* (-32000..-32099), deliberately away from the SDK's reserved -32000
|
|
119
|
+
* (ConnectionClosed) / -32001 (RequestTimeout). The error `data` carries the
|
|
120
|
+
* current etag so the caller can re-read and retry rather than silently clobber a
|
|
121
|
+
* concurrent writer (DR-01).
|
|
122
|
+
*/
|
|
123
|
+
const MEMORY_CAS_CONFLICT_CODE = -32010;
|
|
124
|
+
/**
|
|
125
|
+
* Synthetic `tools/list` descriptor for the shared-state broker WRITE-back tool
|
|
126
|
+
* (DR-01). Like `squad_status` / `squad_render_pptx`, `squad_memory_write` is a
|
|
127
|
+
* transport-level utility rather than a squad routing intent, so it lives here
|
|
128
|
+
* (not in `tools.catalog.yml`, keeping the catalog = the five routing tools and
|
|
129
|
+
* the generator drift-check clean). It performs a compare-and-swap write of the
|
|
130
|
+
* caller's own `tenantId:project` memory and is served only when the operator
|
|
131
|
+
* enabled the memory feature. Deterministic: no model call, no impactful action.
|
|
132
|
+
*/
|
|
133
|
+
const SQUAD_MEMORY_WRITE_DESCRIPTOR = {
|
|
134
|
+
name: SQUAD_MEMORY_WRITE_TOOL,
|
|
135
|
+
title: "Squad Memory Write",
|
|
136
|
+
description: "Write (create or replace) one entry of the project's own squad memory under " +
|
|
137
|
+
"compare-and-swap and return the new etag. Pass the prior etag as expectedEtag " +
|
|
138
|
+
"to guard against clobbering a concurrent writer; omit it for a first write. " +
|
|
139
|
+
"Deterministic: no model call, no impactful action.",
|
|
140
|
+
inputSchema: {
|
|
141
|
+
type: "object",
|
|
142
|
+
additionalProperties: false,
|
|
143
|
+
required: ["project", "path", "content"],
|
|
144
|
+
properties: {
|
|
145
|
+
project: {
|
|
146
|
+
type: "string",
|
|
147
|
+
pattern: MEMORY_PROJECT_PATTERN.source,
|
|
148
|
+
description: "The project namespace within your tenant (lowercase dns-ish label).",
|
|
149
|
+
},
|
|
150
|
+
path: {
|
|
151
|
+
type: "string",
|
|
152
|
+
description: "The logical memory path (e.g. 'state', 'decisions', 'history/<agent>').",
|
|
153
|
+
},
|
|
154
|
+
content: {
|
|
155
|
+
type: "string",
|
|
156
|
+
description: "The full new content to persist at 'path'.",
|
|
157
|
+
},
|
|
158
|
+
expectedEtag: {
|
|
159
|
+
type: "string",
|
|
160
|
+
description: "The etag from the prior read/write; the write applies only if it still matches.",
|
|
161
|
+
},
|
|
162
|
+
target: MEMORY_TARGET_PROPERTY,
|
|
163
|
+
},
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
/**
|
|
167
|
+
* Synthetic `tools/list` descriptor for the shared-state broker READ tool. It is
|
|
168
|
+
* the tool-shaped read of a single memory entry (the `resources/read` surface
|
|
169
|
+
* reads the same store; the tool exists so connectors that only speak tools/call
|
|
170
|
+
* can read too). Same synthetic posture and feature-gating as
|
|
171
|
+
* {@link SQUAD_MEMORY_WRITE_DESCRIPTOR}.
|
|
172
|
+
*/
|
|
173
|
+
const SQUAD_MEMORY_READ_DESCRIPTOR = {
|
|
174
|
+
name: SQUAD_MEMORY_READ_TOOL,
|
|
175
|
+
title: "Squad Memory Read",
|
|
176
|
+
description: "Read one entry of the project's own squad memory and return its content and " +
|
|
177
|
+
"etag (the etag to pass as expectedEtag on a subsequent write). Deterministic: " +
|
|
178
|
+
"no model call, no impactful action.",
|
|
179
|
+
inputSchema: {
|
|
180
|
+
type: "object",
|
|
181
|
+
additionalProperties: false,
|
|
182
|
+
required: ["project", "path"],
|
|
183
|
+
properties: {
|
|
184
|
+
project: {
|
|
185
|
+
type: "string",
|
|
186
|
+
pattern: MEMORY_PROJECT_PATTERN.source,
|
|
187
|
+
description: "The project namespace within your tenant (lowercase dns-ish label).",
|
|
188
|
+
},
|
|
189
|
+
path: {
|
|
190
|
+
type: "string",
|
|
191
|
+
description: "The logical memory path (e.g. 'state', 'decisions', 'history/<agent>').",
|
|
192
|
+
},
|
|
193
|
+
target: MEMORY_TARGET_PROPERTY,
|
|
194
|
+
},
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
/**
|
|
198
|
+
* Synthetic `tools/list` descriptor for reading a run's own history back.
|
|
199
|
+
*
|
|
200
|
+
* The memory tools read KEYS a caller must already know. This reads the TREE a
|
|
201
|
+
* run wrote — the plans, the PRD, the deck pointer, the backlog, the per-agent
|
|
202
|
+
* history — which is what makes a run auditable after the fact rather than only
|
|
203
|
+
* resumable. Deterministic: no model call, no impactful action.
|
|
204
|
+
*/
|
|
205
|
+
const SQUAD_HISTORY_DESCRIPTOR = {
|
|
206
|
+
name: SQUAD_HISTORY_TOOL,
|
|
207
|
+
title: "Squad History",
|
|
208
|
+
description: "Browse and open what previous squad runs produced for a project: the squad " +
|
|
209
|
+
"state, each role's deliverables, and the per-agent history. Use op='index' for " +
|
|
210
|
+
"a compact picture of what exists, op='list' to enumerate a directory, and " +
|
|
211
|
+
"op='read' to open one artifact. Deterministic: no model call, no impactful action.",
|
|
212
|
+
inputSchema: {
|
|
213
|
+
type: "object",
|
|
214
|
+
additionalProperties: false,
|
|
215
|
+
required: ["project"],
|
|
216
|
+
properties: {
|
|
217
|
+
project: {
|
|
218
|
+
type: "string",
|
|
219
|
+
pattern: MEMORY_PROJECT_PATTERN.source,
|
|
220
|
+
description: "The project namespace within your tenant (lowercase dns-ish label).",
|
|
221
|
+
},
|
|
222
|
+
op: {
|
|
223
|
+
type: "string",
|
|
224
|
+
enum: ["index", "list", "read"],
|
|
225
|
+
description: "index (default) summarizes; list enumerates a prefix; read opens one path.",
|
|
226
|
+
},
|
|
227
|
+
prefix: {
|
|
228
|
+
type: "string",
|
|
229
|
+
description: "For op='list': a directory such as '.copilot-tracking/plans'.",
|
|
230
|
+
},
|
|
231
|
+
path: {
|
|
232
|
+
type: "string",
|
|
233
|
+
description: "For op='read': the artifact path from a list result.",
|
|
234
|
+
},
|
|
235
|
+
},
|
|
236
|
+
},
|
|
237
|
+
};
|
|
238
|
+
/**
|
|
239
|
+
* Synthetic `tools/list` descriptor for the shared-state broker BATCH write-back
|
|
240
|
+
* tool (WI-02 — assisted delegated write-back). Like `squad_memory_write` it is a
|
|
241
|
+
* transport-level utility (not a squad routing intent), served only when the
|
|
242
|
+
* operator enabled the memory feature, and carries the SAME Squad.MemoryWrite
|
|
243
|
+
* scope. It applies each item under its OWN compare-and-swap: a stale
|
|
244
|
+
* `expectedEtag` on one item is reported as a per-item conflict WITHOUT aborting
|
|
245
|
+
* the rest, so a delegated host can flush a whole run's `.copilot-tracking/squad/`
|
|
246
|
+
* artifacts in one call and reconcile only the entries that lost a race.
|
|
247
|
+
* Deterministic: no model call, no impactful action.
|
|
248
|
+
*/
|
|
249
|
+
export const SQUAD_MEMORY_SYNC_DESCRIPTOR = {
|
|
250
|
+
name: SQUAD_MEMORY_SYNC_TOOL,
|
|
251
|
+
title: "Squad Memory Sync",
|
|
252
|
+
description: "Flush a batch of the project's own squad-memory entries in one call. Each item " +
|
|
253
|
+
"is written under its own compare-and-swap; pass the prior etag as expectedEtag to " +
|
|
254
|
+
"guard against clobbering a concurrent writer (omit it for a first write). A stale " +
|
|
255
|
+
"expectedEtag on one item is reported as a conflict in the results without aborting " +
|
|
256
|
+
"the others. Returns a per-item result array. Deterministic: no model call, no " +
|
|
257
|
+
"impactful action.",
|
|
258
|
+
inputSchema: {
|
|
259
|
+
type: "object",
|
|
260
|
+
additionalProperties: false,
|
|
261
|
+
required: ["project", "items"],
|
|
262
|
+
properties: {
|
|
263
|
+
project: {
|
|
264
|
+
type: "string",
|
|
265
|
+
pattern: MEMORY_PROJECT_PATTERN.source,
|
|
266
|
+
description: "The project namespace within your tenant (lowercase dns-ish label).",
|
|
267
|
+
},
|
|
268
|
+
items: {
|
|
269
|
+
type: "array",
|
|
270
|
+
description: "The batch of memory entries to write; each is applied under its own CAS.",
|
|
271
|
+
items: {
|
|
272
|
+
type: "object",
|
|
273
|
+
additionalProperties: false,
|
|
274
|
+
required: ["path", "content"],
|
|
275
|
+
properties: {
|
|
276
|
+
path: {
|
|
277
|
+
type: "string",
|
|
278
|
+
description: "The logical memory path (e.g. 'state', 'decisions', 'history/<agent>').",
|
|
279
|
+
},
|
|
280
|
+
content: {
|
|
281
|
+
type: "string",
|
|
282
|
+
description: "The full new content to persist at 'path'.",
|
|
283
|
+
},
|
|
284
|
+
expectedEtag: {
|
|
285
|
+
type: "string",
|
|
286
|
+
description: "The etag from the prior read/write; this item applies only if it still matches.",
|
|
287
|
+
},
|
|
288
|
+
},
|
|
289
|
+
},
|
|
290
|
+
},
|
|
291
|
+
target: MEMORY_TARGET_PROPERTY,
|
|
292
|
+
},
|
|
293
|
+
},
|
|
294
|
+
};
|
|
295
|
+
/**
|
|
296
|
+
* Synthetic `tools/list` descriptor for the BUSINESS-PLAN tool. Business-facing
|
|
297
|
+
* counterpart of the engineering advisory tools: one embedded dispatch against the
|
|
298
|
+
* BRD Builder persona, returning a fixed-section business plan written
|
|
299
|
+
* for a non-technical stakeholder. Advisory only — no impactful action.
|
|
300
|
+
*/
|
|
301
|
+
const SQUAD_BUSINESS_PLAN_DESCRIPTOR = {
|
|
302
|
+
name: SQUAD_BUSINESS_PLAN_TOOL,
|
|
303
|
+
title: "Squad Business Plan",
|
|
304
|
+
description: "Turn an idea, brief, or opportunity into a decision-ready business plan written " +
|
|
305
|
+
"in plain language for a non-technical stakeholder: summary, problem and customer, " +
|
|
306
|
+
"proposed solution, value and success measures, scope, go-to-market, cost outline, " +
|
|
307
|
+
"risks, milestones, and open questions. Advisory text only — nothing is created or " +
|
|
308
|
+
"changed in any system.",
|
|
309
|
+
inputSchema: {
|
|
310
|
+
type: "object",
|
|
311
|
+
additionalProperties: false,
|
|
312
|
+
required: ["request"],
|
|
313
|
+
properties: {
|
|
314
|
+
request: {
|
|
315
|
+
type: "string",
|
|
316
|
+
minLength: 1,
|
|
317
|
+
description: "The idea, brief, or opportunity to turn into a business plan.",
|
|
318
|
+
},
|
|
319
|
+
context: {
|
|
320
|
+
type: "string",
|
|
321
|
+
description: "Optional background: constraints, budget, audience, prior decisions.",
|
|
322
|
+
},
|
|
323
|
+
squad: {
|
|
324
|
+
type: "string",
|
|
325
|
+
pattern: MEMORY_PROJECT_PATTERN.source,
|
|
326
|
+
description: "Optional federation sub-squad / workstream name; also scopes squad memory.",
|
|
327
|
+
},
|
|
328
|
+
},
|
|
329
|
+
},
|
|
330
|
+
};
|
|
331
|
+
/**
|
|
332
|
+
* Synthetic `tools/list` descriptor for the STRUCTURED BACKLOG tool. Its result is
|
|
333
|
+
* a validated JSON contract (`epics → stories → tasks` plus a flattened
|
|
334
|
+
* `workItems[]` with stable `ref` / `parentRef`), designed to be looped ONE ITEM
|
|
335
|
+
* PER CALL into the native Azure DevOps / Jira connector. This server performs no
|
|
336
|
+
* ADO/Jira write itself (ADR-0001) — it produces the plan the certified connector
|
|
337
|
+
* executes on the end user's own connection.
|
|
338
|
+
*/
|
|
339
|
+
const SQUAD_BACKLOG_DESCRIPTOR = {
|
|
340
|
+
name: SQUAD_BACKLOG_TOOL,
|
|
341
|
+
title: "Squad Backlog",
|
|
342
|
+
description: "Turn a request, business plan, or requirements document into a structured delivery " +
|
|
343
|
+
"backlog and return it as JSON: epics, user stories with Given/When/Then acceptance " +
|
|
344
|
+
"criteria, and tasks, plus a flattened 'workItems' array with stable 'ref'/'parentRef' " +
|
|
345
|
+
"ids. Create the items by calling the Azure DevOps or Jira connector once per element " +
|
|
346
|
+
"of 'workItems', parents first, linking children by 'parentRef'. This tool only plans — " +
|
|
347
|
+
"it writes nothing to Azure DevOps or Jira.",
|
|
348
|
+
inputSchema: {
|
|
349
|
+
type: "object",
|
|
350
|
+
additionalProperties: false,
|
|
351
|
+
required: ["request"],
|
|
352
|
+
properties: {
|
|
353
|
+
request: {
|
|
354
|
+
type: "string",
|
|
355
|
+
minLength: 1,
|
|
356
|
+
description: "The work, business plan, or requirements to break down into a backlog.",
|
|
357
|
+
},
|
|
358
|
+
context: {
|
|
359
|
+
type: "string",
|
|
360
|
+
description: "Optional background: existing backlog, constraints, definition of done.",
|
|
361
|
+
},
|
|
362
|
+
squad: {
|
|
363
|
+
type: "string",
|
|
364
|
+
pattern: MEMORY_PROJECT_PATTERN.source,
|
|
365
|
+
description: "Optional federation sub-squad / workstream name; also scopes squad memory.",
|
|
366
|
+
},
|
|
367
|
+
},
|
|
368
|
+
},
|
|
369
|
+
};
|
|
370
|
+
function rpcResult(id, result) {
|
|
371
|
+
return { jsonrpc: "2.0", id: id ?? null, result };
|
|
372
|
+
}
|
|
373
|
+
function rpcError(id, code, message, data) {
|
|
374
|
+
const error = { code, message };
|
|
375
|
+
if (data !== undefined) {
|
|
376
|
+
error.data = data;
|
|
377
|
+
}
|
|
378
|
+
return { jsonrpc: "2.0", id: id ?? null, error };
|
|
379
|
+
}
|
|
380
|
+
function asJsonRpc(body) {
|
|
381
|
+
if (!body || typeof body !== "object") {
|
|
382
|
+
return undefined;
|
|
383
|
+
}
|
|
384
|
+
const candidate = body;
|
|
385
|
+
if (candidate.jsonrpc !== "2.0" || typeof candidate.method !== "string") {
|
|
386
|
+
return undefined;
|
|
387
|
+
}
|
|
388
|
+
return candidate;
|
|
389
|
+
}
|
|
390
|
+
export class HttpMcpHandler {
|
|
391
|
+
router;
|
|
392
|
+
authenticator;
|
|
393
|
+
embedded;
|
|
394
|
+
sessions;
|
|
395
|
+
allowedOrigins;
|
|
396
|
+
logger;
|
|
397
|
+
pipelineExposed;
|
|
398
|
+
renderService;
|
|
399
|
+
memoryStore;
|
|
400
|
+
businessToolsExposed;
|
|
401
|
+
/**
|
|
402
|
+
* The named-destination view of {@link memoryStore}, present only when the
|
|
403
|
+
* operator declared a target allow-list. When absent the memory tools' `target`
|
|
404
|
+
* input is simply ignored (a single-destination deployment).
|
|
405
|
+
*/
|
|
406
|
+
memoryTargets;
|
|
407
|
+
/**
|
|
408
|
+
* The shared read surface over {@link memoryStore}. Constructed only when a
|
|
409
|
+
* store was injected, so it is the single source of truth for
|
|
410
|
+
* `memoryBrokerEnabled` and the `resources/*` cases (same provider the stdio
|
|
411
|
+
* transport uses in `server.ts`).
|
|
412
|
+
*/
|
|
413
|
+
memoryResources;
|
|
414
|
+
/**
|
|
415
|
+
* Read-only browsing over the `.copilot-tracking` tree a run wrote. Present
|
|
416
|
+
* only when the operator enabled the artifact ledger — without it there is no
|
|
417
|
+
* tree to browse, and advertising the tool would promise an empty answer.
|
|
418
|
+
*/
|
|
419
|
+
history;
|
|
420
|
+
constructor(deps) {
|
|
421
|
+
this.router = deps.router;
|
|
422
|
+
this.authenticator = deps.authenticator;
|
|
423
|
+
this.embedded = deps.embedded;
|
|
424
|
+
this.sessions = deps.sessions;
|
|
425
|
+
this.allowedOrigins = new Set(deps.allowedOrigins);
|
|
426
|
+
this.logger = deps.logger;
|
|
427
|
+
this.pipelineExposed = deps.pipelineExposed ?? false;
|
|
428
|
+
this.renderService = deps.renderService;
|
|
429
|
+
this.memoryStore = deps.memoryStore;
|
|
430
|
+
this.businessToolsExposed = deps.businessToolsExposed ?? false;
|
|
431
|
+
this.memoryTargets = asTargetedStore(deps.memoryStore);
|
|
432
|
+
this.memoryResources = deps.memoryStore
|
|
433
|
+
? new SquadMemoryResourceProvider(deps.memoryStore)
|
|
434
|
+
: undefined;
|
|
435
|
+
this.history =
|
|
436
|
+
deps.artifactsEnabled && deps.memoryStore
|
|
437
|
+
? new SquadHistory(new MemoryBackedArtifactStore(deps.memoryStore))
|
|
438
|
+
: undefined;
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Whether the shared-state memory broker is active on this handler. True only
|
|
442
|
+
* when the operator enabled the feature and a backing store was injected; later
|
|
443
|
+
* phases serve the resource read surface and the `squad_memory_*` tools when
|
|
444
|
+
* this is true (advisory-only default when false).
|
|
445
|
+
*/
|
|
446
|
+
get memoryBrokerEnabled() {
|
|
447
|
+
return this.memoryStore !== undefined;
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Whether a tool is reachable over HTTP. The advisory tools (the hero tools
|
|
451
|
+
* plus `squad_plan` / `squad_architect`) are always exposed; the gated pipeline
|
|
452
|
+
* (`squad_run`/`squad_status`) only when `pipelineExposed` (the operator opted
|
|
453
|
+
* in with a durable backend). Default posture is advisory-only.
|
|
454
|
+
*/
|
|
455
|
+
isExposed(name) {
|
|
456
|
+
return this.pipelineExposed ? isRemotelyExposed(name) : isAdvisoryExposed(name);
|
|
457
|
+
}
|
|
458
|
+
originAllowed(origin) {
|
|
459
|
+
// No Origin header => non-browser caller (e.g. a cloud connector); allowed.
|
|
460
|
+
// An Origin header present must be on the strict allow-list (DNS-rebinding defense).
|
|
461
|
+
return origin === undefined || this.allowedOrigins.has(origin);
|
|
462
|
+
}
|
|
463
|
+
corsHeaders(origin) {
|
|
464
|
+
if (origin === undefined || !this.allowedOrigins.has(origin)) {
|
|
465
|
+
return {};
|
|
466
|
+
}
|
|
467
|
+
// Echo the specific Origin (never `*`), and do NOT set Allow-Credentials —
|
|
468
|
+
// auth is a bearer header, not a cookie, so wildcard-with-credentials is avoided.
|
|
469
|
+
return {
|
|
470
|
+
"Access-Control-Allow-Origin": origin,
|
|
471
|
+
"Access-Control-Allow-Methods": "POST, GET, DELETE, OPTIONS",
|
|
472
|
+
"Access-Control-Allow-Headers": "Authorization, Content-Type, Mcp-Session-Id, MCP-Protocol-Version",
|
|
473
|
+
Vary: "Origin",
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
async handle(req) {
|
|
477
|
+
const origin = req.headers["origin"];
|
|
478
|
+
const cors = this.corsHeaders(origin);
|
|
479
|
+
// Out-of-band operator approval route (SEC-6). It is deliberately OFF the MCP
|
|
480
|
+
// JSON-RPC surface — not in tools/list, not a tools/call — so neither a caller
|
|
481
|
+
// nor model output can reach it; only an operator with the distinct approval
|
|
482
|
+
// scope may release a held run through it.
|
|
483
|
+
if (req.path === "/admin/approve") {
|
|
484
|
+
return this.handleAdminApprove(req, origin, cors);
|
|
485
|
+
}
|
|
486
|
+
if (req.path !== "/mcp") {
|
|
487
|
+
return { status: 404, headers: { "content-type": "application/json" }, body: { error: "not_found" } };
|
|
488
|
+
}
|
|
489
|
+
// CORS preflight.
|
|
490
|
+
if (req.method === "OPTIONS") {
|
|
491
|
+
if (!this.originAllowed(origin)) {
|
|
492
|
+
return { status: 403, headers: {}, body: { error: "origin_not_allowed" } };
|
|
493
|
+
}
|
|
494
|
+
return { status: 204, headers: cors };
|
|
495
|
+
}
|
|
496
|
+
// SEC-8: strict Origin allow-list for actual requests.
|
|
497
|
+
if (!this.originAllowed(origin)) {
|
|
498
|
+
return { status: 403, headers: cors, body: { error: "origin_not_allowed" } };
|
|
499
|
+
}
|
|
500
|
+
// SEC-1: authenticate every request (no anonymous /mcp).
|
|
501
|
+
let auth;
|
|
502
|
+
try {
|
|
503
|
+
auth = await this.authenticator.authenticate(req.headers["authorization"]);
|
|
504
|
+
}
|
|
505
|
+
catch (error) {
|
|
506
|
+
if (error instanceof AuthError) {
|
|
507
|
+
return { status: error.status, headers: cors, body: { error: error.reason } };
|
|
508
|
+
}
|
|
509
|
+
throw error;
|
|
510
|
+
}
|
|
511
|
+
const baseHeaders = {
|
|
512
|
+
"content-type": "application/json",
|
|
513
|
+
"MCP-Protocol-Version": MCP_PROTOCOL_VERSION,
|
|
514
|
+
...cors,
|
|
515
|
+
};
|
|
516
|
+
if (req.method === "DELETE") {
|
|
517
|
+
this.sessions.delete(req.headers["mcp-session-id"]);
|
|
518
|
+
return { status: 204, headers: baseHeaders };
|
|
519
|
+
}
|
|
520
|
+
if (req.method === "GET") {
|
|
521
|
+
// The thin slice's hero tools are request/response; no server-initiated SSE stream.
|
|
522
|
+
return {
|
|
523
|
+
status: 405,
|
|
524
|
+
headers: { ...baseHeaders, Allow: "POST, DELETE, OPTIONS" },
|
|
525
|
+
body: rpcError(null, -32601, "Server-initiated streaming is not offered in the thin slice."),
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
if (req.method !== "POST") {
|
|
529
|
+
return { status: 405, headers: { ...baseHeaders, Allow: "POST, DELETE, OPTIONS" } };
|
|
530
|
+
}
|
|
531
|
+
const message = asJsonRpc(req.body);
|
|
532
|
+
if (!message) {
|
|
533
|
+
return { status: 400, headers: baseHeaders, body: rpcError(null, -32700, "Invalid JSON-RPC request.") };
|
|
534
|
+
}
|
|
535
|
+
// Notifications carry no id and expect no response body.
|
|
536
|
+
if (message.id === undefined && message.method.startsWith("notifications/")) {
|
|
537
|
+
return { status: 202, headers: baseHeaders };
|
|
538
|
+
}
|
|
539
|
+
if (message.method === "initialize") {
|
|
540
|
+
const session = this.sessions.create(auth);
|
|
541
|
+
return {
|
|
542
|
+
status: 200,
|
|
543
|
+
headers: { ...baseHeaders, "Mcp-Session-Id": session.id },
|
|
544
|
+
body: rpcResult(message.id, {
|
|
545
|
+
protocolVersion: MCP_PROTOCOL_VERSION,
|
|
546
|
+
// Advertise `resources` ONLY when the memory broker is active; the
|
|
547
|
+
// advisory-only default is byte-identical to before (DR-01 / DR-10).
|
|
548
|
+
capabilities: this.memoryBrokerEnabled ? { tools: {}, resources: {} } : { tools: {} },
|
|
549
|
+
serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },
|
|
550
|
+
}),
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
// Every non-initialize request requires a valid, identity-bound session (SEC-8).
|
|
554
|
+
if (!this.sessions.validate(req.headers["mcp-session-id"], auth)) {
|
|
555
|
+
return {
|
|
556
|
+
status: 404,
|
|
557
|
+
headers: baseHeaders,
|
|
558
|
+
body: rpcError(message.id, -32600, "Missing or invalid session; re-initialize."),
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
switch (message.method) {
|
|
562
|
+
case "ping":
|
|
563
|
+
return { status: 200, headers: baseHeaders, body: rpcResult(message.id, {}) };
|
|
564
|
+
case "tools/list":
|
|
565
|
+
return {
|
|
566
|
+
status: 200,
|
|
567
|
+
headers: baseHeaders,
|
|
568
|
+
body: rpcResult(message.id, {
|
|
569
|
+
// PROD-1: the advisory tools always; the gated async pipeline (squad_run +
|
|
570
|
+
// squad_status) only when the operator enabled it (pipelineExposed).
|
|
571
|
+
tools: [
|
|
572
|
+
...this.router.listToolDescriptors().filter((descriptor) => this.isExposed(descriptor.name)),
|
|
573
|
+
...(this.pipelineExposed ? [SQUAD_STATUS_DESCRIPTOR] : []),
|
|
574
|
+
...(this.renderService ? [SQUAD_RENDER_PPTX_DESCRIPTOR] : []),
|
|
575
|
+
// The memory broker tools appear ONLY when the operator enabled the
|
|
576
|
+
// feature (a backing store injected); `isMemoryExposed` keeps the
|
|
577
|
+
// projection to the classified memory tools (advisory-only default
|
|
578
|
+
// is byte-identical to before).
|
|
579
|
+
...(this.memoryBrokerEnabled
|
|
580
|
+
? [
|
|
581
|
+
SQUAD_MEMORY_READ_DESCRIPTOR,
|
|
582
|
+
SQUAD_MEMORY_WRITE_DESCRIPTOR,
|
|
583
|
+
SQUAD_MEMORY_SYNC_DESCRIPTOR,
|
|
584
|
+
...(this.history ? [SQUAD_HISTORY_DESCRIPTOR] : []),
|
|
585
|
+
].filter((descriptor) => isMemoryExposed(descriptor.name))
|
|
586
|
+
: []),
|
|
587
|
+
// The business-facing tools appear ONLY when the operator enabled
|
|
588
|
+
// them; the default remote surface is unchanged.
|
|
589
|
+
...(this.businessToolsExposed
|
|
590
|
+
? [SQUAD_BUSINESS_PLAN_DESCRIPTOR, SQUAD_BACKLOG_DESCRIPTOR].filter((descriptor) => isBusinessExposed(descriptor.name))
|
|
591
|
+
: []),
|
|
592
|
+
],
|
|
593
|
+
}),
|
|
594
|
+
};
|
|
595
|
+
case "tools/call":
|
|
596
|
+
return this.handleToolCall(message, auth, baseHeaders);
|
|
597
|
+
case "resources/list":
|
|
598
|
+
case "resources/read":
|
|
599
|
+
case "resources/templates/list":
|
|
600
|
+
return this.handleResources(message, auth, baseHeaders);
|
|
601
|
+
default:
|
|
602
|
+
return {
|
|
603
|
+
status: 200,
|
|
604
|
+
headers: baseHeaders,
|
|
605
|
+
body: rpcError(message.id, -32601, `Method not found: ${message.method}`),
|
|
606
|
+
};
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* Out-of-band operator approval endpoint (`POST /admin/approve`). Releases a HELD
|
|
611
|
+
* run so the async pipeline can proceed. This is the production caller of the
|
|
612
|
+
* approval channel and the keystone that makes a deployed held `squad_run`
|
|
613
|
+
* releasable. Security posture:
|
|
614
|
+
*
|
|
615
|
+
* * SEC-6 — off the model/caller surface. It is not an MCP tool, not listed in
|
|
616
|
+
* tools/list, and not in the connector manifest; no `request`/`context` or
|
|
617
|
+
* model output can reach it. Only served when the operator enabled the gated
|
|
618
|
+
* pipeline (`pipelineExposed`); otherwise it 404s (the route is not revealed).
|
|
619
|
+
* * SEC-1 — authenticated (no anonymous release); SEC-8 — strict Origin
|
|
620
|
+
* allow-list. It requires NO MCP session (an operator action, not a caller
|
|
621
|
+
* conversation).
|
|
622
|
+
* * Distinct operator scope — `authorizeApproval` requires `Squad.Operate`, not
|
|
623
|
+
* `Squad.Run`, so a caller that may start/poll a run still cannot approve it.
|
|
624
|
+
* * Tenant-scoped — the engine releases only a run owned by the operator's
|
|
625
|
+
* tenant; an unknown or cross-tenant run id is denied with no leakage.
|
|
626
|
+
*/
|
|
627
|
+
async handleAdminApprove(req, origin, cors) {
|
|
628
|
+
// Route exists only when the gated pipeline is exposed; otherwise do not reveal it.
|
|
629
|
+
if (!this.pipelineExposed) {
|
|
630
|
+
return { status: 404, headers: { "content-type": "application/json" }, body: { error: "not_found" } };
|
|
631
|
+
}
|
|
632
|
+
// SEC-8: strict Origin allow-list (CORS preflight answered without auth).
|
|
633
|
+
if (req.method === "OPTIONS") {
|
|
634
|
+
if (!this.originAllowed(origin)) {
|
|
635
|
+
return { status: 403, headers: {}, body: { error: "origin_not_allowed" } };
|
|
636
|
+
}
|
|
637
|
+
return { status: 204, headers: { ...cors, "Access-Control-Allow-Methods": "POST, OPTIONS" } };
|
|
638
|
+
}
|
|
639
|
+
if (!this.originAllowed(origin)) {
|
|
640
|
+
return { status: 403, headers: cors, body: { error: "origin_not_allowed" } };
|
|
641
|
+
}
|
|
642
|
+
if (req.method !== "POST") {
|
|
643
|
+
return { status: 405, headers: { ...cors, Allow: "POST, OPTIONS" }, body: { error: "method_not_allowed" } };
|
|
644
|
+
}
|
|
645
|
+
const baseHeaders = { "content-type": "application/json", ...cors };
|
|
646
|
+
// SEC-1: authenticate the operator (no anonymous release).
|
|
647
|
+
let auth;
|
|
648
|
+
try {
|
|
649
|
+
auth = await this.authenticator.authenticate(req.headers["authorization"]);
|
|
650
|
+
}
|
|
651
|
+
catch (error) {
|
|
652
|
+
if (error instanceof AuthError) {
|
|
653
|
+
return { status: error.status, headers: baseHeaders, body: { error: error.reason } };
|
|
654
|
+
}
|
|
655
|
+
throw error;
|
|
656
|
+
}
|
|
657
|
+
// Distinct high-privilege operator scope (NOT Squad.Run).
|
|
658
|
+
try {
|
|
659
|
+
this.authenticator.authorizeApproval(auth);
|
|
660
|
+
}
|
|
661
|
+
catch (error) {
|
|
662
|
+
if (error instanceof AuthError) {
|
|
663
|
+
return { status: error.status, headers: baseHeaders, body: { error: error.reason } };
|
|
664
|
+
}
|
|
665
|
+
throw error;
|
|
666
|
+
}
|
|
667
|
+
const runId = typeof req.body?.runId === "string"
|
|
668
|
+
? req.body.runId
|
|
669
|
+
: "";
|
|
670
|
+
if (runId.length === 0) {
|
|
671
|
+
return { status: 400, headers: baseHeaders, body: { error: "invalid_run_id" } };
|
|
672
|
+
}
|
|
673
|
+
try {
|
|
674
|
+
// Tenant-scoped release; records approver + timestamp via the auditable channel.
|
|
675
|
+
const result = await this.embedded.approveRun(runId, { auth });
|
|
676
|
+
if (!result.ok) {
|
|
677
|
+
// No leakage: unknown vs cross-tenant are indistinguishable to the operator.
|
|
678
|
+
return { status: 404, headers: baseHeaders, body: { error: result.reason } };
|
|
679
|
+
}
|
|
680
|
+
return {
|
|
681
|
+
status: 200,
|
|
682
|
+
headers: baseHeaders,
|
|
683
|
+
body: { approved: true, runId, approver: result.record.approver, at: result.record.at },
|
|
684
|
+
};
|
|
685
|
+
}
|
|
686
|
+
catch (error) {
|
|
687
|
+
this.logger.error("operator approval failed", { error: String(error) });
|
|
688
|
+
return { status: 500, headers: baseHeaders, body: { error: "internal_error" } };
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
/**
|
|
692
|
+
* Handle the read-only `resources/*` surface (shared-state broker — DR-01 /
|
|
693
|
+
* DR-04). Security ordering mirrors `tools/call`:
|
|
694
|
+
* 1. Method-not-found when the broker is off (advisory-only default), so a
|
|
695
|
+
* token that never enabled memory sees NO resource surface at all.
|
|
696
|
+
* 2. SEC-2 default-deny — require the `Squad.Memory` read scope BEFORE any
|
|
697
|
+
* store read (a token missing it is denied via the existing authorizer).
|
|
698
|
+
* 3. Delegate to the shared {@link SquadMemoryResourceProvider}, keyed on
|
|
699
|
+
* `auth.tenantId` from the validated Entra token — NEVER caller input
|
|
700
|
+
* (SEC-3 tenant isolation).
|
|
701
|
+
*
|
|
702
|
+
* An unknown/malformed URI or a missing entry surfaces the provider's single
|
|
703
|
+
* generic {@link McpError} (no leakage); any other failure is logged scrubbed
|
|
704
|
+
* and returned as a generic internal error.
|
|
705
|
+
*/
|
|
706
|
+
async handleResources(message, auth, baseHeaders) {
|
|
707
|
+
if (!this.memoryResources) {
|
|
708
|
+
return {
|
|
709
|
+
status: 200,
|
|
710
|
+
headers: baseHeaders,
|
|
711
|
+
body: rpcError(message.id, -32601, `Method not found: ${message.method}`),
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
// SEC-2: fail-closed on the Squad.Memory read scope BEFORE any store read.
|
|
715
|
+
try {
|
|
716
|
+
this.authenticator.authorizeTool(auth, SQUAD_MEMORY_READ_TOOL);
|
|
717
|
+
}
|
|
718
|
+
catch (error) {
|
|
719
|
+
if (error instanceof AuthError) {
|
|
720
|
+
return { status: error.status, headers: baseHeaders, body: { error: error.reason } };
|
|
721
|
+
}
|
|
722
|
+
throw error;
|
|
723
|
+
}
|
|
724
|
+
try {
|
|
725
|
+
switch (message.method) {
|
|
726
|
+
case "resources/list": {
|
|
727
|
+
const resources = await this.memoryResources.list(auth.tenantId);
|
|
728
|
+
return { status: 200, headers: baseHeaders, body: rpcResult(message.id, { resources }) };
|
|
729
|
+
}
|
|
730
|
+
case "resources/templates/list": {
|
|
731
|
+
const resourceTemplates = this.memoryResources.templates();
|
|
732
|
+
return { status: 200, headers: baseHeaders, body: rpcResult(message.id, { resourceTemplates }) };
|
|
733
|
+
}
|
|
734
|
+
case "resources/read": {
|
|
735
|
+
const uri = typeof message.params?.uri === "string"
|
|
736
|
+
? message.params.uri
|
|
737
|
+
: "";
|
|
738
|
+
const result = await this.memoryResources.read(auth.tenantId, uri);
|
|
739
|
+
return { status: 200, headers: baseHeaders, body: rpcResult(message.id, result) };
|
|
740
|
+
}
|
|
741
|
+
default:
|
|
742
|
+
return {
|
|
743
|
+
status: 200,
|
|
744
|
+
headers: baseHeaders,
|
|
745
|
+
body: rpcError(message.id, -32601, `Method not found: ${message.method}`),
|
|
746
|
+
};
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
catch (error) {
|
|
750
|
+
if (error instanceof McpError) {
|
|
751
|
+
// Provider errors are already generic (no-leakage) — pass code + message.
|
|
752
|
+
return { status: 200, headers: baseHeaders, body: rpcError(message.id, error.code, error.message) };
|
|
753
|
+
}
|
|
754
|
+
this.logger.error("resource dispatch failed", { method: message.method, error: String(error) });
|
|
755
|
+
return {
|
|
756
|
+
status: 200,
|
|
757
|
+
headers: baseHeaders,
|
|
758
|
+
body: rpcError(message.id, -32603, "The squad encountered an internal error handling this request."),
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
async handleToolCall(message, auth, baseHeaders) {
|
|
763
|
+
const params = message.params ?? {};
|
|
764
|
+
const name = typeof params.name === "string" ? params.name : "";
|
|
765
|
+
const args = params.arguments;
|
|
766
|
+
// squad_memory_read / squad_memory_write are the synthetic shared-state broker
|
|
767
|
+
// tools (not catalog tools). They are served only when the operator enabled
|
|
768
|
+
// the memory feature (a backing store injected), are fail-closed on their own
|
|
769
|
+
// dedicated scopes (Squad.Memory for read, Squad.MemoryWrite for write —
|
|
770
|
+
// checked BEFORE any store access, default-deny), and land NO impactful action
|
|
771
|
+
// (no model call, no gate, no run state — the same posture as squad_render_pptx).
|
|
772
|
+
// The store key is ALWAYS <auth.tenantId>:<project> with tenantId from the
|
|
773
|
+
// validated token (never caller input) and project shape-checked, so a caller
|
|
774
|
+
// can never escape its own partition (SEC-3 tenant isolation, SEC-4 traversal).
|
|
775
|
+
if (isMemoryExposed(name)) {
|
|
776
|
+
if (!this.memoryStore) {
|
|
777
|
+
return {
|
|
778
|
+
status: 200,
|
|
779
|
+
headers: baseHeaders,
|
|
780
|
+
body: rpcError(message.id, -32601, `Unknown or unavailable tool: ${name}`),
|
|
781
|
+
};
|
|
782
|
+
}
|
|
783
|
+
// SEC-2: fail-closed on the tool's dedicated scope BEFORE any store access.
|
|
784
|
+
try {
|
|
785
|
+
this.authenticator.authorizeTool(auth, name);
|
|
786
|
+
}
|
|
787
|
+
catch (error) {
|
|
788
|
+
if (error instanceof AuthError) {
|
|
789
|
+
return { status: error.status, headers: baseHeaders, body: { error: error.reason } };
|
|
790
|
+
}
|
|
791
|
+
throw error;
|
|
792
|
+
}
|
|
793
|
+
const record = args ?? {};
|
|
794
|
+
const project = typeof record.project === "string" ? record.project : "";
|
|
795
|
+
const path = typeof record.path === "string" ? record.path : "";
|
|
796
|
+
// Resolve the operator-declared destination BEFORE any I/O. A caller may
|
|
797
|
+
// only select among declared targets; an unknown name is rejected here and
|
|
798
|
+
// never falls back silently to the default (which would write a caller's
|
|
799
|
+
// memory somewhere it did not ask for). On a deployment with no declared
|
|
800
|
+
// targets `memoryTargets` is undefined and the input is ignored.
|
|
801
|
+
const requestedTarget = typeof record.target === "string" ? record.target : undefined;
|
|
802
|
+
let store = this.memoryStore;
|
|
803
|
+
if (this.memoryTargets) {
|
|
804
|
+
try {
|
|
805
|
+
store = this.memoryTargets.resolve(requestedTarget);
|
|
806
|
+
}
|
|
807
|
+
catch (error) {
|
|
808
|
+
if (error instanceof UnknownMemoryTargetError) {
|
|
809
|
+
return {
|
|
810
|
+
status: 200,
|
|
811
|
+
headers: baseHeaders,
|
|
812
|
+
body: rpcError(message.id, -32602, `Unknown memory target. Available targets: ${this.memoryTargets.targetNames().join(", ")}.`),
|
|
813
|
+
};
|
|
814
|
+
}
|
|
815
|
+
throw error;
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
// Shape-check `project` (a single partition segment) and `path` (the SEC-4
|
|
819
|
+
// traversal guard) BEFORE the store — a bad value never reaches a foreign
|
|
820
|
+
// partition or the filesystem.
|
|
821
|
+
if (!MEMORY_PROJECT_PATTERN.test(project)) {
|
|
822
|
+
return {
|
|
823
|
+
status: 200,
|
|
824
|
+
headers: baseHeaders,
|
|
825
|
+
body: rpcError(message.id, -32602, `${name} requires a 'project' matching ${MEMORY_PROJECT_PATTERN.source}.`),
|
|
826
|
+
};
|
|
827
|
+
}
|
|
828
|
+
// squad_memory_sync is the BATCH write-back (WI-02): apply each item under
|
|
829
|
+
// its OWN compare-and-swap and return a per-item result. A stale
|
|
830
|
+
// `expectedEtag` on one item is reported as a conflict WITHOUT aborting the
|
|
831
|
+
// others (a delegated host reconciles only the losers), and a structurally
|
|
832
|
+
// invalid item (unsafe path / non-string content) fails that ONE item too.
|
|
833
|
+
// It shares the write scope + tenant-isolation posture of the single write
|
|
834
|
+
// above; the whole call is rejected only when `items` itself is not an array.
|
|
835
|
+
if (name === SQUAD_MEMORY_SYNC_TOOL) {
|
|
836
|
+
const items = Array.isArray(record.items) ? record.items : undefined;
|
|
837
|
+
if (!items) {
|
|
838
|
+
return {
|
|
839
|
+
status: 200,
|
|
840
|
+
headers: baseHeaders,
|
|
841
|
+
body: rpcError(message.id, -32602, "squad_memory_sync requires an 'items' array."),
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
const results = [];
|
|
845
|
+
for (const raw of items) {
|
|
846
|
+
const item = raw ?? {};
|
|
847
|
+
const itemPath = typeof item.path === "string" ? item.path : "";
|
|
848
|
+
const content = typeof item.content === "string" ? item.content : undefined;
|
|
849
|
+
const expectedEtag = typeof item.expectedEtag === "string" ? item.expectedEtag : undefined;
|
|
850
|
+
// SEC-4 traversal guard + shape-check BEFORE the store; a bad item is
|
|
851
|
+
// marked failed (not a conflict) and never aborts the rest of the batch.
|
|
852
|
+
if (!isSafeMemoryPath(itemPath) || content === undefined) {
|
|
853
|
+
results.push({ path: itemPath, ok: false });
|
|
854
|
+
continue;
|
|
855
|
+
}
|
|
856
|
+
try {
|
|
857
|
+
const result = await store.write(auth.tenantId, project, itemPath, content, expectedEtag);
|
|
858
|
+
if (result.ok) {
|
|
859
|
+
results.push({ path: itemPath, ok: true, etag: result.etag });
|
|
860
|
+
}
|
|
861
|
+
else {
|
|
862
|
+
// Lost the CAS race: a per-item conflict the caller re-reads and retries.
|
|
863
|
+
results.push({ path: itemPath, ok: false, conflict: true });
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
catch (error) {
|
|
867
|
+
// Never surface raw error text (could echo content/a secret); log scrubbed.
|
|
868
|
+
this.logger.error("memory sync item failed", { tool: name, error: String(error) });
|
|
869
|
+
results.push({ path: itemPath, ok: false });
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
return {
|
|
873
|
+
status: 200,
|
|
874
|
+
headers: baseHeaders,
|
|
875
|
+
body: rpcResult(message.id, { project, results }),
|
|
876
|
+
};
|
|
877
|
+
}
|
|
878
|
+
// squad_history reads the TREE rather than a key, so it is handled before
|
|
879
|
+
// the single-path guard below: `index` and `list` carry no `path` at all.
|
|
880
|
+
if (name === SQUAD_HISTORY_TOOL) {
|
|
881
|
+
if (!this.history) {
|
|
882
|
+
return {
|
|
883
|
+
status: 200,
|
|
884
|
+
headers: baseHeaders,
|
|
885
|
+
body: rpcError(message.id, -32601, `Unknown or unavailable tool: ${name}`),
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
const op = typeof record.op === "string" ? record.op : "index";
|
|
889
|
+
try {
|
|
890
|
+
if (op === "read") {
|
|
891
|
+
const artifact = await this.history.read(auth.tenantId, project, path);
|
|
892
|
+
return {
|
|
893
|
+
status: 200,
|
|
894
|
+
headers: baseHeaders,
|
|
895
|
+
body: artifact
|
|
896
|
+
? rpcResult(message.id, { project, ...artifact })
|
|
897
|
+
: rpcError(message.id, -32602, `No artifact at '${path}' in project '${project}'.`),
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
if (op === "list") {
|
|
901
|
+
const prefix = typeof record.prefix === "string" ? record.prefix : undefined;
|
|
902
|
+
const entries = await this.history.list(auth.tenantId, project, prefix);
|
|
903
|
+
return {
|
|
904
|
+
status: 200,
|
|
905
|
+
headers: baseHeaders,
|
|
906
|
+
body: rpcResult(message.id, { project, prefix: prefix ?? null, entries }),
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
const index = await this.history.index(auth.tenantId, project);
|
|
910
|
+
return { status: 200, headers: baseHeaders, body: rpcResult(message.id, { project, ...index }) };
|
|
911
|
+
}
|
|
912
|
+
catch (error) {
|
|
913
|
+
// An unsafe path is rejected by the store; never echo raw error text.
|
|
914
|
+
this.logger.error("squad history failed", { tool: name, op, error: String(error) });
|
|
915
|
+
return {
|
|
916
|
+
status: 200,
|
|
917
|
+
headers: baseHeaders,
|
|
918
|
+
body: rpcError(message.id, -32602, `${name} rejected the request (check 'path'/'prefix').`),
|
|
919
|
+
};
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
if (!isSafeMemoryPath(path)) {
|
|
923
|
+
return {
|
|
924
|
+
status: 200,
|
|
925
|
+
headers: baseHeaders,
|
|
926
|
+
body: rpcError(message.id, -32602, `${name} requires a safe 'path' (no traversal).`),
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
if (name === SQUAD_MEMORY_WRITE_TOOL) {
|
|
930
|
+
const content = typeof record.content === "string" ? record.content : undefined;
|
|
931
|
+
if (content === undefined) {
|
|
932
|
+
return {
|
|
933
|
+
status: 200,
|
|
934
|
+
headers: baseHeaders,
|
|
935
|
+
body: rpcError(message.id, -32602, "squad_memory_write requires string 'content'."),
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
const expectedEtag = typeof record.expectedEtag === "string" ? record.expectedEtag : undefined;
|
|
939
|
+
try {
|
|
940
|
+
// CAS read-modify-write: pass `expectedEtag` through; on a lost race the
|
|
941
|
+
// store reports the conflict (never a silent clobber — DR-01).
|
|
942
|
+
const result = await store.write(auth.tenantId, project, path, content, expectedEtag);
|
|
943
|
+
if (result.ok) {
|
|
944
|
+
return {
|
|
945
|
+
status: 200,
|
|
946
|
+
headers: baseHeaders,
|
|
947
|
+
body: rpcResult(message.id, { project, path, etag: result.etag }),
|
|
948
|
+
};
|
|
949
|
+
}
|
|
950
|
+
// Lost the CAS race: a retryable conflict error carrying the current
|
|
951
|
+
// etag so the caller can re-read and retry with a fresh token.
|
|
952
|
+
return {
|
|
953
|
+
status: 200,
|
|
954
|
+
headers: baseHeaders,
|
|
955
|
+
body: rpcError(message.id, MEMORY_CAS_CONFLICT_CODE, "squad_memory_write lost a compare-and-swap race; re-read and retry with the current etag.", { conflict: true, currentEtag: result.current?.etag }),
|
|
956
|
+
};
|
|
957
|
+
}
|
|
958
|
+
catch (error) {
|
|
959
|
+
// Never surface raw error text (could echo content/a secret); log scrubbed.
|
|
960
|
+
this.logger.error("memory write failed", { tool: name, error: String(error) });
|
|
961
|
+
return {
|
|
962
|
+
status: 200,
|
|
963
|
+
headers: baseHeaders,
|
|
964
|
+
body: rpcResult(message.id, {
|
|
965
|
+
isError: true,
|
|
966
|
+
content: [{ type: "text", text: "The squad encountered an internal error handling this request." }],
|
|
967
|
+
}),
|
|
968
|
+
};
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
// squad_memory_read: return the entry content (and its etag for the next
|
|
972
|
+
// write) scoped to the caller's tenantId:project.
|
|
973
|
+
try {
|
|
974
|
+
const entry = await store.read(auth.tenantId, project, path);
|
|
975
|
+
if (!entry) {
|
|
976
|
+
return {
|
|
977
|
+
status: 200,
|
|
978
|
+
headers: baseHeaders,
|
|
979
|
+
body: rpcError(message.id, -32602, `No memory entry at '${path}'.`),
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
return {
|
|
983
|
+
status: 200,
|
|
984
|
+
headers: baseHeaders,
|
|
985
|
+
body: rpcResult(message.id, {
|
|
986
|
+
project: entry.project,
|
|
987
|
+
path: entry.path,
|
|
988
|
+
content: entry.content,
|
|
989
|
+
etag: entry.etag,
|
|
990
|
+
updatedAt: entry.updatedAt,
|
|
991
|
+
}),
|
|
992
|
+
};
|
|
993
|
+
}
|
|
994
|
+
catch (error) {
|
|
995
|
+
this.logger.error("memory read failed", { tool: name, error: String(error) });
|
|
996
|
+
return {
|
|
997
|
+
status: 200,
|
|
998
|
+
headers: baseHeaders,
|
|
999
|
+
body: rpcResult(message.id, {
|
|
1000
|
+
isError: true,
|
|
1001
|
+
content: [{ type: "text", text: "The squad encountered an internal error handling this request." }],
|
|
1002
|
+
}),
|
|
1003
|
+
};
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
// squad_business_plan / squad_backlog are the synthetic BUSINESS tools (not
|
|
1007
|
+
// catalog tools). They are served only when the operator enabled the feature,
|
|
1008
|
+
// are fail-closed on their own least-privilege scopes (Squad.Business /
|
|
1009
|
+
// Squad.Backlog), and land NO impactful action: each runs ONE embedded
|
|
1010
|
+
// advisory dispatch and returns text (or, for the backlog, a validated JSON
|
|
1011
|
+
// contract). The ADO/Jira WRITE remains the native certified connector's job
|
|
1012
|
+
// on the end user's own connection (ADR-0001 trust boundary).
|
|
1013
|
+
if (isBusinessExposed(name)) {
|
|
1014
|
+
const spec = this.businessToolsExposed ? businessToolSpec(name) : undefined;
|
|
1015
|
+
if (!spec) {
|
|
1016
|
+
return {
|
|
1017
|
+
status: 200,
|
|
1018
|
+
headers: baseHeaders,
|
|
1019
|
+
body: rpcError(message.id, -32601, `Unknown or unavailable tool: ${name}`),
|
|
1020
|
+
};
|
|
1021
|
+
}
|
|
1022
|
+
// SEC-2: fail-closed scope BEFORE any model call.
|
|
1023
|
+
try {
|
|
1024
|
+
this.authenticator.authorizeTool(auth, name);
|
|
1025
|
+
}
|
|
1026
|
+
catch (error) {
|
|
1027
|
+
if (error instanceof AuthError) {
|
|
1028
|
+
return { status: error.status, headers: baseHeaders, body: { error: error.reason } };
|
|
1029
|
+
}
|
|
1030
|
+
throw error;
|
|
1031
|
+
}
|
|
1032
|
+
const record = args ?? {};
|
|
1033
|
+
const requestText = typeof record.request === "string" ? record.request.trim() : "";
|
|
1034
|
+
if (requestText.length === 0) {
|
|
1035
|
+
return {
|
|
1036
|
+
status: 200,
|
|
1037
|
+
headers: baseHeaders,
|
|
1038
|
+
body: rpcError(message.id, -32602, `${name} requires a non-empty 'request'.`),
|
|
1039
|
+
};
|
|
1040
|
+
}
|
|
1041
|
+
const coordinatorRequest = {
|
|
1042
|
+
toolId: name,
|
|
1043
|
+
request: requestText,
|
|
1044
|
+
context: typeof record.context === "string" ? record.context : undefined,
|
|
1045
|
+
squad: typeof record.squad === "string" ? record.squad : undefined,
|
|
1046
|
+
};
|
|
1047
|
+
try {
|
|
1048
|
+
const result = await this.embedded.handleBusiness(spec, coordinatorRequest, { auth });
|
|
1049
|
+
if (!spec.structured || result.outcome !== "completed" || !result.artifact) {
|
|
1050
|
+
return { status: 200, headers: baseHeaders, body: rpcResult(message.id, renderEmbeddedResult(result)) };
|
|
1051
|
+
}
|
|
1052
|
+
// The structured tool's whole value is a machine-readable result, so the
|
|
1053
|
+
// server validates the model's JSON rather than handing prose to the agent.
|
|
1054
|
+
// A malformed payload is an explicit, retryable error — never half-parsed
|
|
1055
|
+
// JSON the orchestrator would turn into malformed work items.
|
|
1056
|
+
try {
|
|
1057
|
+
const backlog = parseBacklog(result.artifact);
|
|
1058
|
+
return { status: 200, headers: baseHeaders, body: rpcResult(message.id, backlog) };
|
|
1059
|
+
}
|
|
1060
|
+
catch (error) {
|
|
1061
|
+
if (error instanceof BacklogContractError) {
|
|
1062
|
+
this.logger.error("backlog contract invalid", { tool: name, reason: error.message });
|
|
1063
|
+
return {
|
|
1064
|
+
status: 200,
|
|
1065
|
+
headers: baseHeaders,
|
|
1066
|
+
body: rpcResult(message.id, {
|
|
1067
|
+
isError: true,
|
|
1068
|
+
content: [
|
|
1069
|
+
{
|
|
1070
|
+
type: "text",
|
|
1071
|
+
text: "The backlog could not be produced in a structured form. Ask again with " +
|
|
1072
|
+
"a more specific request, or narrow the scope.",
|
|
1073
|
+
},
|
|
1074
|
+
],
|
|
1075
|
+
}),
|
|
1076
|
+
};
|
|
1077
|
+
}
|
|
1078
|
+
throw error;
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
catch (error) {
|
|
1082
|
+
// Never surface raw error text (could echo a prompt); log scrubbed.
|
|
1083
|
+
this.logger.error("business dispatch failed", { tool: name, error: String(error) });
|
|
1084
|
+
return {
|
|
1085
|
+
status: 200,
|
|
1086
|
+
headers: baseHeaders,
|
|
1087
|
+
body: rpcResult(message.id, {
|
|
1088
|
+
isError: true,
|
|
1089
|
+
content: [{ type: "text", text: "The squad encountered an internal error handling this request." }],
|
|
1090
|
+
}),
|
|
1091
|
+
};
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
// squad_render_pptx is the synthetic deterministic render utility (not a
|
|
1095
|
+
// catalog tool). It is served only when the operator enabled render, is
|
|
1096
|
+
// fail-closed on its own Squad.Render scope, and lands NO impactful action
|
|
1097
|
+
// (no gate, no run state). The caller's tenant scopes the blob path.
|
|
1098
|
+
if (name === SQUAD_RENDER_PPTX_TOOL) {
|
|
1099
|
+
if (!this.renderService) {
|
|
1100
|
+
return {
|
|
1101
|
+
status: 200,
|
|
1102
|
+
headers: baseHeaders,
|
|
1103
|
+
body: rpcError(message.id, -32601, `Unknown or unavailable tool: ${name}`),
|
|
1104
|
+
};
|
|
1105
|
+
}
|
|
1106
|
+
// SEC-2: fail-closed scope BEFORE any render work.
|
|
1107
|
+
try {
|
|
1108
|
+
this.authenticator.authorizeTool(auth, name);
|
|
1109
|
+
}
|
|
1110
|
+
catch (error) {
|
|
1111
|
+
if (error instanceof AuthError) {
|
|
1112
|
+
return { status: error.status, headers: baseHeaders, body: { error: error.reason } };
|
|
1113
|
+
}
|
|
1114
|
+
throw error;
|
|
1115
|
+
}
|
|
1116
|
+
const record = args ?? {};
|
|
1117
|
+
const contentYaml = typeof record.contentYaml === "string" ? record.contentYaml : "";
|
|
1118
|
+
const styleYaml = typeof record.styleYaml === "string" ? record.styleYaml : "";
|
|
1119
|
+
if (contentYaml.length === 0 || styleYaml.length === 0) {
|
|
1120
|
+
return {
|
|
1121
|
+
status: 200,
|
|
1122
|
+
headers: baseHeaders,
|
|
1123
|
+
body: rpcError(message.id, -32602, "squad_render_pptx requires string contentYaml and styleYaml."),
|
|
1124
|
+
};
|
|
1125
|
+
}
|
|
1126
|
+
try {
|
|
1127
|
+
const result = await this.renderService.render({ contentYaml, styleYaml }, { tenantId: auth.tenantId });
|
|
1128
|
+
return { status: 200, headers: baseHeaders, body: rpcResult(message.id, result) };
|
|
1129
|
+
}
|
|
1130
|
+
catch (error) {
|
|
1131
|
+
// Never surface raw error text (could echo a header/secret); log scrubbed.
|
|
1132
|
+
this.logger.error("render dispatch failed", { tool: name, error: String(error) });
|
|
1133
|
+
return {
|
|
1134
|
+
status: 200,
|
|
1135
|
+
headers: baseHeaders,
|
|
1136
|
+
body: rpcResult(message.id, {
|
|
1137
|
+
isError: true,
|
|
1138
|
+
content: [{ type: "text", text: "The squad encountered an internal error handling this request." }],
|
|
1139
|
+
}),
|
|
1140
|
+
};
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
// squad_status is the synthetic poll utility (not a catalog tool). It is
|
|
1144
|
+
// tenant-scoped and read/advance-only; it never starts new work of its own.
|
|
1145
|
+
// Only served when the operator enabled the pipeline surface (HIGH-1).
|
|
1146
|
+
if (name === SQUAD_STATUS_TOOL && this.pipelineExposed) {
|
|
1147
|
+
try {
|
|
1148
|
+
this.authenticator.authorizeTool(auth, name);
|
|
1149
|
+
}
|
|
1150
|
+
catch (error) {
|
|
1151
|
+
if (error instanceof AuthError) {
|
|
1152
|
+
return { status: error.status, headers: baseHeaders, body: { error: error.reason } };
|
|
1153
|
+
}
|
|
1154
|
+
throw error;
|
|
1155
|
+
}
|
|
1156
|
+
const runId = typeof args?.runId === "string"
|
|
1157
|
+
? args.runId
|
|
1158
|
+
: "";
|
|
1159
|
+
if (runId.length === 0) {
|
|
1160
|
+
return { status: 200, headers: baseHeaders, body: rpcError(message.id, -32602, "squad_status requires a string runId.") };
|
|
1161
|
+
}
|
|
1162
|
+
try {
|
|
1163
|
+
const result = await this.embedded.pollRun(runId, { auth });
|
|
1164
|
+
return { status: 200, headers: baseHeaders, body: rpcResult(message.id, renderEmbeddedResult(result)) };
|
|
1165
|
+
}
|
|
1166
|
+
catch (error) {
|
|
1167
|
+
this.logger.error("status poll failed", { tool: name, error: String(error) });
|
|
1168
|
+
return {
|
|
1169
|
+
status: 200,
|
|
1170
|
+
headers: baseHeaders,
|
|
1171
|
+
body: rpcResult(message.id, {
|
|
1172
|
+
isError: true,
|
|
1173
|
+
content: [{ type: "text", text: "The squad encountered an internal error handling this request." }],
|
|
1174
|
+
}),
|
|
1175
|
+
};
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
const tool = this.router.getTool(name);
|
|
1179
|
+
// PROD-1: only exposed/known tools are callable over HTTP.
|
|
1180
|
+
if (!tool || !this.isExposed(name)) {
|
|
1181
|
+
return {
|
|
1182
|
+
status: 200,
|
|
1183
|
+
headers: baseHeaders,
|
|
1184
|
+
body: rpcError(message.id, -32601, `Unknown or unavailable tool: ${name}`),
|
|
1185
|
+
};
|
|
1186
|
+
}
|
|
1187
|
+
// SEC-2: per-tool scope authorization.
|
|
1188
|
+
try {
|
|
1189
|
+
this.authenticator.authorizeTool(auth, name);
|
|
1190
|
+
}
|
|
1191
|
+
catch (error) {
|
|
1192
|
+
if (error instanceof AuthError) {
|
|
1193
|
+
return { status: error.status, headers: baseHeaders, body: { error: error.reason } };
|
|
1194
|
+
}
|
|
1195
|
+
throw error;
|
|
1196
|
+
}
|
|
1197
|
+
// Input validation against the authored JSON Schema.
|
|
1198
|
+
try {
|
|
1199
|
+
this.router.validateInput(name, args);
|
|
1200
|
+
}
|
|
1201
|
+
catch (error) {
|
|
1202
|
+
if (error instanceof ToolInputError) {
|
|
1203
|
+
return { status: 200, headers: baseHeaders, body: rpcError(message.id, -32602, error.message) };
|
|
1204
|
+
}
|
|
1205
|
+
throw error;
|
|
1206
|
+
}
|
|
1207
|
+
const coordinatorRequest = this.router.toCoordinatorRequest(tool, args);
|
|
1208
|
+
try {
|
|
1209
|
+
// Dispatch by tool class:
|
|
1210
|
+
// * squad_run / squad_federate — the gated async ADVISORY pipelines: START
|
|
1211
|
+
// them (returns a held run id); the pipeline proceeds only after
|
|
1212
|
+
// out-of-band approval, driven by squad_status. Both are catch-all tools
|
|
1213
|
+
// with `gates: true`, so the human gate carries across the boundary
|
|
1214
|
+
// identically; squad_federate additionally persists its federation inputs
|
|
1215
|
+
// (squad / init / promote) so they survive approve -> poll.
|
|
1216
|
+
// * squad_plan / squad_architect — advisory tools: a single-stage embedded
|
|
1217
|
+
// advisory dispatch (no impactful action, no gate), returned synchronously.
|
|
1218
|
+
// * the hero tools (squad_research / squad_review) — synchronous single
|
|
1219
|
+
// embedded dispatch, unchanged.
|
|
1220
|
+
const result = tool.id === "squad_run" || tool.id === SQUAD_FEDERATE_TOOL
|
|
1221
|
+
? await this.embedded.startHttpRun(tool, coordinatorRequest, { auth })
|
|
1222
|
+
: tool.id === "squad_plan" || tool.id === "squad_architect"
|
|
1223
|
+
? await this.embedded.handleAdvisory(tool, coordinatorRequest, { auth })
|
|
1224
|
+
: await this.embedded.handle(tool, coordinatorRequest, { auth });
|
|
1225
|
+
return { status: 200, headers: baseHeaders, body: rpcResult(message.id, renderEmbeddedResult(result)) };
|
|
1226
|
+
}
|
|
1227
|
+
catch (error) {
|
|
1228
|
+
// Never surface the raw error text (could echo a prompt); log scrubbed, return generic.
|
|
1229
|
+
this.logger.error("embedded dispatch failed", { tool: name, error: String(error) });
|
|
1230
|
+
return {
|
|
1231
|
+
status: 200,
|
|
1232
|
+
headers: baseHeaders,
|
|
1233
|
+
body: rpcResult(message.id, {
|
|
1234
|
+
isError: true,
|
|
1235
|
+
content: [{ type: "text", text: "The squad encountered an internal error handling this request." }],
|
|
1236
|
+
}),
|
|
1237
|
+
};
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
}
|