Coverage for app / services / mcp.py: 100%

53 statements  

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

1""" 

2MCP server descriptor resolution — shared by workers, agents, and probing. 

3 

4``MCPServer.connection_config`` holds stored credentials (URLs, headers, 

5commands), so anything that forwards a server to svc-ai must resolve it 

6through the access-checked helpers here rather than reading rows directly. 

7 

8Descriptor shape (what svc-ai's loader and probe endpoint consume):: 

9 

10 {"name": str, "transport": "stdio" | "http" | "sse", "config": {…}} 

11 

12Availability 

13------------ 

14MCP servers — and the toolkits that bundle them — are **not available in this 

15release**. ``MCP_AVAILABLE`` is off in every environment: it is a constant, 

16not a setting, so no dotenv file can turn it on. While it is off: 

17 

18* every write that would configure a server or put one in reach of an agent 

19 is refused with 403 (``require_available``) — creating or editing a server 

20 or toolkit, probing, toolkit membership and grants, a skill node or worker 

21 naming a server, and toolkits in generative setup; 

22* nothing forwards a server to svc-ai: the resolvers below return no 

23 descriptors, so stored credentials never leave svc-core; 

24* reads, history and deletes still work, so existing rows stay inspectable 

25 and removable. 

26 

27svc-ai holds its own switch (``app/mcp/__init__.py`` there) and refuses to 

28connect regardless — neither service trusts the other to be off. That module 

29lists what must change before either is turned on; ``tests/test_mcp_unavailable.py`` 

30pins this one off. 

31""" 

32 

33from __future__ import annotations 

34 

35import logging 

36from uuid import UUID 

37 

38from fastapi import HTTPException, status 

39from sqlalchemy.orm import Session 

40 

41from app.db.postgres.models import ( 

42 AgentToolkit, 

43 MCPServer, 

44 ToolkitMCPServer, 

45 User, 

46) 

47from app.dependency.resource_access import verify_resource_access 

48 

49logger = logging.getLogger(__name__) 

50 

51#: Off in every environment — see the module docstring before changing it. 

52MCP_AVAILABLE: bool = False 

53 

54#: The refusal every gated route answers with. 

55UNAVAILABLE_DETAIL = ( 

56 "MCP servers and toolkits are coming soon — they are not available in this release." 

57) 

58 

59 

60def is_available() -> bool: 

61 """Whether MCP servers may be configured and forwarded. 

62 

63 Read at call time, so a test can switch it on for the code paths kept 

64 ready for when it ships. 

65 """ 

66 return MCP_AVAILABLE 

67 

68 

69def require_available() -> None: 

70 """Refuse with 403 while MCP servers are unavailable. 

71 

72 A route dependency (``dependencies=[Depends(require_available)]``), so it 

73 runs before the body is read or a row is touched. 

74 """ 

75 if not is_available(): 

76 raise HTTPException( 

77 status_code=status.HTTP_403_FORBIDDEN, detail=UNAVAILABLE_DETAIL 

78 ) 

79 

80 

81def descriptor(server: MCPServer, config_overrides: dict | None = None) -> dict: 

82 """Build the svc-ai connection descriptor for one MCPServer row.""" 

83 config = dict(server.connection_config or {}) 

84 if config_overrides: 

85 config.update(config_overrides) 

86 return { 

87 "name": server.name, 

88 "transport": server.connection_type, 

89 "config": config, 

90 } 

91 

92 

93def refuse_references(server_ids, what: str = "") -> None: 

94 """Refuse with 403 a write that names MCP servers while they are unavailable. 

95 

96 ``what`` prefixes the detail with where the reference was found (a skill 

97 node, say), so a refused save says which part to remove. 

98 """ 

99 if server_ids and not is_available(): 

100 raise HTTPException( 

101 status_code=status.HTTP_403_FORBIDDEN, 

102 detail=f"{what} {UNAVAILABLE_DETAIL}".strip(), 

103 ) 

104 

105 

106def check_server_access( 

107 server: MCPServer, 

108 db: Session, 

109 current_user: User, 

110 owner_organisation_id: UUID | None = None, 

111 owner_project_id: UUID | None = None, 

112) -> None: 

113 """Enforce the access rules for embedding a server's credentials. 

114 

115 - the current user must have access to the server (same rule as the MCP 

116 CRUD endpoints), and 

117 - when an owning org/project scope is given (shared workers/agents), the 

118 server must be owned by that same scope — a shared resource executes 

119 on behalf of every member, so it must never embed a narrower owner's 

120 credentials. 

121 

122 Raises 403 on any violation. 

123 """ 

124 try: 

125 verify_resource_access(server, current_user, db) 

126 except HTTPException: 

127 raise HTTPException( 

128 status_code=status.HTTP_403_FORBIDDEN, 

129 detail=f"No access to MCP server '{server.id}'.", 

130 ) 

131 

132 if ( 

133 owner_organisation_id is not None 

134 and server.owner_organisation_id != owner_organisation_id 

135 ) or (owner_project_id is not None and server.owner_project_id != owner_project_id): 

136 raise HTTPException( 

137 status_code=status.HTTP_403_FORBIDDEN, 

138 detail=( 

139 f"MCP server '{server.id}' is not owned by the resource's " 

140 "organisation/project. Shared resources may only use MCP " 

141 "servers owned by the same scope." 

142 ), 

143 ) 

144 

145 

146def resolve_descriptors( 

147 server_ids: list, 

148 db: Session, 

149 current_user: User, 

150 owner_organisation_id: UUID | None = None, 

151 owner_project_id: UUID | None = None, 

152) -> list[dict]: 

153 """Resolve MCP server ids to access-checked connection descriptors. 

154 

155 Raises 403 on any access violation. Missing or inactive servers are 

156 skipped with a warning (tolerates rows deleted since the reference was 

157 saved). Returns nothing while MCP servers are unavailable. 

158 """ 

159 if not is_available(): 

160 return [] 

161 descriptors: list[dict] = [] 

162 for raw_id in server_ids or []: 

163 try: 

164 server = db.get(MCPServer, UUID(str(raw_id))) 

165 except (ValueError, TypeError): 

166 server = None 

167 if server is None or not server.is_active: 

168 logger.warning( 

169 "Reference to missing/inactive MCP server %r — skipped", raw_id 

170 ) 

171 continue 

172 check_server_access( 

173 server, db, current_user, owner_organisation_id, owner_project_id 

174 ) 

175 descriptors.append(descriptor(server)) 

176 return descriptors 

177 

178 

179def load_agent_mcp_descriptors(db: Session, agent) -> list[dict]: 

180 """Return connection descriptors for all MCP servers attached to an agent. 

181 

182 Agents only ever integrate MCP servers through an attached toolkit 

183 (never individually) — mirroring how agents only ever integrate skills 

184 through a skillset. Inference-time resolver: access is enforced when 

185 the server is added to the toolkit (see the toolkit endpoints). 

186 Inactive servers are excluded so deactivating a server immediately 

187 removes its tools from every agent whose toolkit references it. A 

188 server belonging to more than one attached toolkit is deduplicated, 

189 taking the config of whichever toolkit grant is returned first. 

190 

191 Returns nothing while MCP servers are unavailable, so no agent turn, 

192 evaluation run or dashboard tile forwards one. 

193 """ 

194 if not is_available(): 

195 return [] 

196 rows = ( 

197 db.query(MCPServer, AgentToolkit.config) 

198 .join(ToolkitMCPServer, ToolkitMCPServer.mcp_server_id == MCPServer.id) 

199 .join( 

200 AgentToolkit, 

201 AgentToolkit.toolkit_id == ToolkitMCPServer.toolkit_id, 

202 ) 

203 .filter(AgentToolkit.agent_id == agent.id, MCPServer.is_active.is_(True)) 

204 .all() 

205 ) 

206 

207 by_id: dict[UUID, tuple[MCPServer, dict | None]] = {} 

208 for server, cfg in rows: 

209 by_id.setdefault(server.id, (server, cfg)) 

210 return [descriptor(server, cfg) for server, cfg in by_id.values()]