Coverage for app / services / skill_graph.py: 96%

181 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1""" 

2Per-node overrides on a skill graph that svc-core owns rather than forwards. 

3 

4A skill graph node may pin the model that answers it and the MCP servers whose 

5tools it can reach. Both are stored on the node's ``config_overrides``, and 

6both need svc-core in the middle: 

7 

8* **model** — ``provider``/``model`` are free strings by the time they reach 

9 svc-ai, and a pair that names nothing fails the run at the provider. They 

10 are checked against svc-ai's catalogue when the graph is saved, so a 

11 generative flow proposing a model that does not exist is refused where the 

12 user can still see why. 

13 

14* **MCP servers** — ``MCPServer.connection_config`` holds credentials, so a 

15 graph stores *ids* only. Access is enforced at save time (the same rule as 

16 attaching a server to a worker) and the ids are resolved to connection 

17 descriptors at execution time, which is also what makes deactivating a 

18 server take effect immediately rather than when the graph is next edited. 

19 

20That split mirrors how agents reach MCP servers through a toolkit: authorised 

21when the reference is made, resolved when the graph runs. 

22 

23A tool node's ``config`` can name knowledge too — ``query_knowledge_base`` 

24reads ``collection``, ``query_knowledge_graph`` reads ``knowledge_id`` — and 

25svc-ai searches whatever it names, so the graph is the only place access can 

26be enforced. A reference must be to knowledge the author may read and the 

27skill's workspace has when it is saved, and to knowledge the invocation's 

28workspace has when it runs (``KNOWLEDGE_CONFIG_KEYS``): a skill is copied, 

29inherited and run by others, and membership changes after the save. 

30""" 

31 

32from __future__ import annotations 

33 

34import logging 

35from collections.abc import Callable 

36from typing import Any 

37from uuid import UUID 

38 

39from fastapi import HTTPException, status 

40from sqlalchemy.orm import Session 

41 

42from app.db.postgres.models import CustomWorker, Knowledge, MCPServer, User 

43from app.dependency.resource_access import verify_resource_access, verify_resource_read 

44from app.services import inheritance 

45from app.services import mcp as mcp_service 

46from app.services.ai_client import AIServiceError, list_models 

47from app.services.workspace import Workspace 

48 

49logger = logging.getLogger(__name__) 

50 

51#: Prefix of a custom worker's registered name (``workers.router._definition_name``). 

52CUSTOM_WORKER_PREFIX = "cw_" 

53 

54#: Tool-node ``config`` keys that name a knowledge source, on any tool: svc-ai's 

55#: ``query_knowledge_base`` reads ``collection`` (a knowledge id, or its Qdrant 

56#: name ``kb_<id>``) and ``query_knowledge_graph`` reads ``knowledge_id`` 

57#: (svc-ai ``app/tools/registry.py``). Checked whatever the tool's name, so a 

58#: tool added later that reads one is covered before anyone remembers it. 

59KNOWLEDGE_CONFIG_KEYS = ("collection", "knowledge_id") 

60 

61 

62def _agent_nodes(graph_definition: dict[str, Any]) -> list[tuple[str, dict]]: 

63 """Every agent node of a graph as ``(node_id, node)`` pairs. 

64 

65 Tolerates a malformed blob: the schema validator has the job of rejecting 

66 one, and this is also called on stored graphs written before it existed. 

67 """ 

68 nodes = (graph_definition or {}).get("nodes") 

69 if not isinstance(nodes, dict): 

70 return [] 

71 return [ 

72 (str(node_id), node) 

73 for node_id, node in nodes.items() 

74 if isinstance(node, dict) and (node.get("type") or "agent") == "agent" 

75 ] 

76 

77 

78def _tool_knowledge_references( 

79 graph_definition: dict[str, Any], 

80) -> list[tuple[str, str, Any]]: 

81 """Every knowledge reference in a tool node's config, as 

82 ``(node_id, config key, raw value)``. Tolerates a malformed blob.""" 

83 nodes = (graph_definition or {}).get("nodes") 

84 if not isinstance(nodes, dict): 

85 return [] 

86 found: list[tuple[str, str, Any]] = [] 

87 for node_id, node in nodes.items(): 

88 tool = node.get("tool") if isinstance(node, dict) else None 

89 config = tool.get("config") if isinstance(tool, dict) else None 

90 if not isinstance(config, dict): 

91 continue 

92 for key in KNOWLEDGE_CONFIG_KEYS: 

93 if config.get(key) not in (None, ""): 

94 found.append((str(node_id), key, config[key])) 

95 return found 

96 

97 

98def _knowledge_of(db: Session, raw: Any) -> Knowledge | None: 

99 """The knowledge a reference names, as svc-ai will read it — a UUID in 

100 any form ``UUID()`` takes, or the ``kb_<id>`` collection name — or None.""" 

101 text = str(raw).strip() 

102 if text.startswith("kb_"): 

103 text = text[3:].replace("_", "-") 

104 try: 

105 knowledge_id = UUID(text) 

106 except ValueError: 

107 return None 

108 return db.get(Knowledge, knowledge_id) 

109 

110 

111def validate_node_overrides( 

112 graph_definition: dict[str, Any], 

113 db: Session, 

114 current_user: User, 

115 owner_organisation_id: UUID | None = None, 

116 owner_project_id: UUID | None = None, 

117 new_worker_names: frozenset[str] = frozenset(), 

118 workspace: Workspace | None = None, 

119) -> None: 

120 """Check every node's model pin, worker, MCP and knowledge references 

121 before a graph is stored. 

122 

123 ``new_worker_names`` are workers being created in the same request (a 

124 generative flow's proposal names), which cannot resolve yet and belong to 

125 the caller by construction. ``workspace`` is where the skill lives — the 

126 request's (where a create lands, ``owner_for``) when not given. 

127 

128 Raises 400 for a model the catalogue does not list or knowledge that does 

129 not exist, 403 for an MCP server the user may not embed or knowledge they 

130 may not read, and 422 for knowledge the workspace does not have. A 

131 catalogue that cannot be reached is *not* a failure: refusing to save a 

132 skill because svc-ai is down would make an outage look like a validation 

133 error, and the pair is re-resolved on every run anyway. 

134 """ 

135 _check_knowledge_references(graph_definition, db, current_user, workspace) 

136 catalogue: list[dict] | None = None 

137 

138 for node_id, node in _agent_nodes(graph_definition): 

139 if node.get("agent_name") not in new_worker_names: 

140 _check_custom_worker(node_id, node, db, current_user) 

141 

142 overrides = node.get("config_overrides") 

143 if not isinstance(overrides, dict): 

144 continue 

145 

146 provider = overrides.get("provider") 

147 model = overrides.get("model") 

148 if provider and model: 

149 if catalogue is None: 

150 try: 

151 catalogue = [ 

152 row for row in list_models() or [] if isinstance(row, dict) 

153 ] 

154 except AIServiceError: 

155 logger.warning( 

156 "Could not reach svc-ai's model catalogue — node model " 

157 "pins are stored unvalidated", 

158 exc_info=True, 

159 ) 

160 catalogue = [] 

161 if catalogue and not _in_catalogue(catalogue, provider, model): 

162 raise HTTPException( 

163 status_code=status.HTTP_400_BAD_REQUEST, 

164 detail=( 

165 f"Node {node_id!r} pins model {provider}/{model}, which " 

166 "is not in the model catalogue." 

167 ), 

168 ) 

169 

170 # MCP servers are not available in this release. 

171 mcp_service.refuse_references( 

172 overrides.get("mcp_server_ids"), 

173 f"Node {node_id!r} pins MCP servers.", 

174 ) 

175 for raw_id in overrides.get("mcp_server_ids") or []: 

176 server = _get_server(db, raw_id) 

177 if server is None: 

178 raise HTTPException( 

179 status_code=status.HTTP_400_BAD_REQUEST, 

180 detail=( 

181 f"Node {node_id!r} references MCP server {raw_id!r}, " 

182 "which does not exist." 

183 ), 

184 ) 

185 mcp_service.check_server_access( 

186 server, db, current_user, owner_organisation_id, owner_project_id 

187 ) 

188 

189 

190def _check_knowledge_references( 

191 graph_definition: dict[str, Any], 

192 db: Session, 

193 current_user: User, 

194 workspace: Workspace | None, 

195) -> None: 

196 """A tool node may name only knowledge its author may read and the 

197 skill's workspace has — the rule a repository grant follows 

198 (``agents.router.add_agent_repository``). A UUID is not a secret: it is in 

199 URLs and citations, and a former member keeps the ones they saw.""" 

200 references = _tool_knowledge_references(graph_definition) 

201 if not references: 

202 return 

203 if workspace is None: 

204 from app.dependency.workspace import request_workspace 

205 

206 workspace = request_workspace(db, current_user) 

207 for node_id, key, raw in references: 

208 knowledge = _knowledge_of(db, raw) 

209 if knowledge is None: 

210 raise HTTPException( 

211 status_code=status.HTTP_400_BAD_REQUEST, 

212 detail=( 

213 f"Node {node_id!r} reads knowledge {raw!r} ({key}), which " 

214 "does not exist." 

215 ), 

216 ) 

217 verify_resource_read(knowledge, current_user, db) 

218 inheritance.require_visible(db, knowledge, workspace, "knowledge source") 

219 

220 

221def _check_custom_worker( 

222 node_id: str, node: dict, db: Session, current_user: User 

223) -> None: 

224 """Refuse a node that runs somebody else's custom worker. 

225 

226 svc-ai's agent-definition registry is global, so a ``cw_<id>`` name 

227 resolves whoever owns it — and a worker carries its own prompt and MCP 

228 connections. The id is not discoverable through the API, but secrecy of 

229 an id is not access control: a node may only name a worker its author 

230 could open. 

231 """ 

232 name = str(node.get("agent_name") or "") 

233 if not name.startswith(CUSTOM_WORKER_PREFIX): 

234 return 

235 worker = db.query(CustomWorker).filter(CustomWorker.definition_name == name).first() 

236 if worker is None: 

237 raise HTTPException( 

238 status_code=status.HTTP_400_BAD_REQUEST, 

239 detail=f"Node {node_id!r} runs worker {name!r}, which does not exist.", 

240 ) 

241 verify_resource_access(worker, current_user, db) 

242 

243 

244def _in_catalogue(catalogue: list[dict], provider: str, model: str) -> bool: 

245 for row in catalogue: 

246 row_provider = row.get("provider") 

247 name = ( 

248 row_provider.get("name") if isinstance(row_provider, dict) else row_provider 

249 ) 

250 if str(name) == str(provider) and str(row.get("model_name")) == str(model): 

251 return True 

252 return False 

253 

254 

255def _get_server(db: Session, raw_id: Any) -> MCPServer | None: 

256 try: 

257 return db.get(MCPServer, UUID(str(raw_id))) 

258 except (ValueError, TypeError): 

259 return None 

260 

261 

262def _runnable_catalogue() -> list[dict] | None: 

263 """Every model this deployment can run now, or None when svc-ai could not 

264 be asked (and nothing can be said about a pin).""" 

265 try: 

266 return [ 

267 row for row in list_models(is_available=True) or [] if isinstance(row, dict) 

268 ] 

269 except AIServiceError: 

270 logger.warning( 

271 "Could not reach svc-ai's model catalogue — node model pins run unchecked", 

272 exc_info=True, 

273 ) 

274 return None 

275 

276 

277def resolve_for_execution( 

278 graph_definition: dict[str, Any], 

279 db: Session, 

280 *, 

281 workspace: Workspace | None, 

282 notes: list[str] | None = None, 

283 runnable: Callable[[], list[dict] | None] = _runnable_catalogue, 

284) -> dict[str, Any]: 

285 """A copy of the graph as svc-ai should run it. 

286 

287 * **Node MCP ids become connection descriptors.** svc-ai's 

288 ``from_definition`` reads ``config_overrides["mcp_servers"]`` — the 

289 descriptor list — and knows nothing about svc-core's ids, so the swap 

290 has to happen here. Access was enforced when the reference was saved, 

291 so this is a resolver and not a second gate; a server that has since 

292 been deleted or deactivated is dropped, which is the same tolerance 

293 ``load_agent_mcp_descriptors`` applies to a toolkit's servers. While MCP 

294 servers are unavailable no id is resolved: a node that pins servers 

295 still gets the key, empty, so it reaches none. 

296 * **A model pin this deployment cannot run is dropped**, so the node runs 

297 on the agent's model (or the deployment's default) instead of refusing 

298 the whole turn. A pin is checked against the catalogue when it is saved, 

299 but the catalogue changes under it: GPT-4o was valid on the vendors' 

300 APIs and has no route on Bedrock. Each dropped pin adds a line to 

301 ``notes`` for the person. The catalogue is read only when a node pins a 

302 model, and a pin is kept when it cannot be read. 

303 * **A tool node reads only knowledge ``workspace`` has** — the 

304 invocation's: where a standalone run was started, or the agent's home 

305 for a turn (``agents.transformers._reachable_by``); None, a built-in 

306 agent, has the built-ins only. This *is* a second gate: the save-time 

307 check saw the author and the skill's workspace, and a copied or 

308 inherited skill runs elsewhere, for others, after memberships change. 

309 A reference that fails it is dropped with a note (the tool then has no 

310 source), and one that passes is rewritten to the knowledge's id, so 

311 svc-ai reads exactly what was checked. 

312 

313 The input is never mutated: the stored graph must keep the ids and pins, 

314 or the next save would write resolved credentials back into the skill. 

315 """ 

316 nodes = (graph_definition or {}).get("nodes") 

317 if not isinstance(nodes, dict): 

318 return graph_definition 

319 

320 catalogue: list[dict] | None = None 

321 catalogue_read = False 

322 touched = False 

323 resolved_nodes: dict[str, Any] = {} 

324 for node_id, node in nodes.items(): 

325 if not isinstance(node, dict): 

326 resolved_nodes[node_id] = node 

327 continue 

328 resolved = node 

329 

330 tool = _tool_for_workspace(node_id, node, db, workspace, notes) 

331 if tool is not None: 

332 resolved = {**resolved, "tool": tool} 

333 

334 overrides = node.get("config_overrides") 

335 if isinstance(overrides, dict): 

336 new_overrides = dict(overrides) 

337 

338 provider, model = overrides.get("provider"), overrides.get("model") 

339 if provider and model: 

340 if not catalogue_read: 

341 catalogue, catalogue_read = runnable(), True 

342 if catalogue is not None and not _in_catalogue( 

343 catalogue, provider, model 

344 ): 

345 logger.warning( 

346 "Node %r pins %s/%s, which this deployment cannot run — " 

347 "the node runs on the agent's model", 

348 node_id, 

349 provider, 

350 model, 

351 ) 

352 new_overrides.pop("provider", None) 

353 new_overrides.pop("model", None) 

354 if notes is not None: 

355 notes.append( 

356 f"Step {node_id!r} is set to {model}, which is not " 

357 "available here; it runs on the agent's model." 

358 ) 

359 

360 ids = overrides.get("mcp_server_ids") 

361 if ids: 

362 descriptors: list[dict] = [] 

363 for raw_id in ids if mcp_service.is_available() else []: 

364 server = _get_server(db, raw_id) 

365 if server is None or not server.is_active: 

366 logger.warning( 

367 "Node %r references missing/inactive MCP server %r " 

368 "— skipped", 

369 node_id, 

370 raw_id, 

371 ) 

372 continue 

373 descriptors.append(mcp_service.descriptor(server)) 

374 new_overrides.pop("mcp_server_ids", None) 

375 # Always set the key, even when empty: svc-ai treats a present 

376 # ``mcp_servers`` as *replacing* the definition's own list, and 

377 # a node whose servers have all been deactivated must reach no 

378 # servers rather than silently fall back to the worker's 

379 # defaults. 

380 new_overrides["mcp_servers"] = descriptors 

381 

382 if new_overrides != overrides: 

383 resolved = {**resolved, "config_overrides": new_overrides} 

384 

385 if resolved is not node: 

386 touched = True 

387 resolved_nodes[node_id] = resolved 

388 

389 if not touched: 

390 return graph_definition 

391 return {**graph_definition, "nodes": resolved_nodes} 

392 

393 

394def _tool_for_workspace( 

395 node_id: str, 

396 node: dict, 

397 db: Session, 

398 workspace: Workspace | None, 

399 notes: list[str] | None, 

400) -> dict | None: 

401 """The node's ``tool`` with its knowledge references checked against 

402 ``workspace``, or None when it names no knowledge (or nothing changed).""" 

403 tool = node.get("tool") 

404 config = tool.get("config") if isinstance(tool, dict) else None 

405 if not isinstance(config, dict): 

406 return None 

407 new_config = scope_tool_config( 

408 config, db, workspace, label=f"Step {node_id!r}", notes=notes 

409 ) 

410 if new_config == config: 

411 return None 

412 return {**tool, "config": new_config} 

413 

414 

415def scope_tool_config( 

416 config: dict[str, Any], 

417 db: Session, 

418 workspace: Workspace | None, 

419 *, 

420 label: str, 

421 notes: list[str] | None = None, 

422) -> dict[str, Any]: 

423 """A copy of a tool's ``config`` whose knowledge references 

424 (``KNOWLEDGE_CONFIG_KEYS``) name only knowledge ``workspace`` has — or, 

425 for None (a built-in), the built-ins. A reference that passes is 

426 rewritten to the knowledge's id; one that fails is dropped, with a line 

427 in ``notes`` beginning ``label``.""" 

428 new_config = dict(config) 

429 for key in KNOWLEDGE_CONFIG_KEYS: 

430 raw = config.get(key) 

431 if raw in (None, ""): 

432 continue 

433 knowledge = _knowledge_of(db, raw) 

434 if knowledge is not None and ( 

435 knowledge.is_system is True 

436 or (workspace is not None and inheritance.visible(db, knowledge, workspace)) 

437 ): 

438 new_config[key] = str(knowledge.id) 

439 continue 

440 logger.warning( 

441 "%s reads knowledge %r (%s), which workspace %s does not have — the " 

442 "reference is dropped", 

443 label, 

444 raw, 

445 key, 

446 workspace.key if workspace is not None else "(built-in)", 

447 ) 

448 new_config.pop(key) 

449 if notes is not None: 

450 notes.append( 

451 f"{label} reads a knowledge source this workspace doesn't have; " 

452 "it runs without it." 

453 ) 

454 return new_config