Coverage for app / router / app / mcp_servers / router.py: 94%

90 statements  

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

1from uuid import UUID 

2 

3from fastapi import APIRouter, Depends, HTTPException, status 

4from sqlalchemy.orm import Session 

5 

6from app.db.postgres.crud_schemas import Schema 

7from app.db.postgres.enums import HistoryEnum 

8from app.db.postgres.models import MCPServer, User 

9from app.dependency.base import get_db 

10from app.dependency.user.context import get_current_user 

11from app.dependency.resource_access import ( 

12 verify_resource_access, 

13 verify_owner_scope, 

14 verify_resource_read, 

15) 

16from app.router.app.history.router import register_history_routes 

17from app.services import history as history_service 

18from app.services import mcp as mcp_service 

19from app.services.ai_client import AIServiceError, list_mcp_templates, probe_mcp_server 

20 

21import logging 

22 

23logger = logging.getLogger(__name__) 

24 

25mcp_server_router = APIRouter(prefix="/mcp_servers", tags=["App - MCP Servers"]) 

26 

27# MCP servers are not available in this release (``app.services.mcp``): every 

28# route that would configure or connect to one answers 403. Listing, reading, 

29# deleting and the edit history stay, so existing rows can be seen and removed. 

30_AVAILABLE_ONLY = [Depends(mcp_service.require_available)] 

31 

32 

33# --------------------------------------------------------------------------- 

34# Templates — proxy to svc-ai registry 

35# --------------------------------------------------------------------------- 

36 

37 

38@mcp_server_router.get("/templates", dependencies=_AVAILABLE_ONLY) 

39def get_mcp_server_templates(): 

40 """Return all built-in MCP server templates available for users to configure.""" 

41 try: 

42 return {"templates": list_mcp_templates()} 

43 except AIServiceError as exc: 

44 logger.error("Could not fetch MCP templates from svc-ai: %s", exc) 

45 raise HTTPException( 

46 status_code=status.HTTP_502_BAD_GATEWAY, 

47 detail="Could not reach svc-ai to list MCP server templates.", 

48 ) 

49 

50 

51# --------------------------------------------------------------------------- 

52# MCP Server CRUD 

53# --------------------------------------------------------------------------- 

54 

55 

56@mcp_server_router.get("", response_model=list[Schema.MCPServer.Read]) 

57def list_mcp_servers( 

58 db: Session = Depends(get_db), 

59 current_user: User = Depends(get_current_user), 

60): 

61 """List all MCP servers owned by the current user.""" 

62 return db.query(MCPServer).filter(MCPServer.owner_user_id == current_user.id).all() 

63 

64 

65@mcp_server_router.get("/{server_id}", response_model=Schema.MCPServer.Read) 

66def get_mcp_server( 

67 server_id: UUID, 

68 db: Session = Depends(get_db), 

69 current_user: User = Depends(get_current_user), 

70): 

71 server = db.get(MCPServer, server_id) 

72 if not server: 

73 raise HTTPException( 

74 status_code=status.HTTP_404_NOT_FOUND, detail="MCP server not found" 

75 ) 

76 verify_resource_read(server, current_user, db) 

77 return server 

78 

79 

80@mcp_server_router.post( 

81 "", 

82 response_model=Schema.MCPServer.Read, 

83 status_code=status.HTTP_201_CREATED, 

84 dependencies=_AVAILABLE_ONLY, 

85) 

86def create_mcp_server( 

87 body: Schema.MCPServer.Create, 

88 db: Session = Depends(get_db), 

89 current_user: User = Depends(get_current_user), 

90): 

91 data = body.model_dump() 

92 if not data.get("owner_organisation_id") and not data.get("owner_project_id"): 

93 data["owner_user_id"] = current_user.id 

94 verify_owner_scope(data, current_user, db, model=MCPServer) 

95 

96 server = MCPServer(**data) 

97 try: 

98 db.add(server) 

99 db.commit() 

100 db.refresh(server) 

101 history_service.record_version( 

102 db, 

103 resource_type=HistoryEnum.ResourceType.mcp_server, 

104 model=MCPServer, 

105 resource=server, 

106 action=HistoryEnum.Action.created, 

107 actor=current_user, 

108 ) 

109 db.commit() 

110 return server 

111 except Exception: 

112 db.rollback() 

113 logger.exception("Failed to create MCP server") 

114 raise 

115 

116 

117@mcp_server_router.patch( 

118 "/{server_id}", 

119 response_model=Schema.MCPServer.Read, 

120 dependencies=_AVAILABLE_ONLY, 

121) 

122def update_mcp_server( 

123 server_id: UUID, 

124 body: Schema.MCPServer.Update, 

125 db: Session = Depends(get_db), 

126 current_user: User = Depends(get_current_user), 

127): 

128 server = db.get(MCPServer, server_id) 

129 if not server: 

130 raise HTTPException( 

131 status_code=status.HTTP_404_NOT_FOUND, detail="MCP server not found" 

132 ) 

133 verify_resource_access(server, current_user, db) 

134 for field, value in body.model_dump(exclude_none=True).items(): 

135 setattr(server, field, value) 

136 history_service.record_version( 

137 db, 

138 resource_type=HistoryEnum.ResourceType.mcp_server, 

139 model=MCPServer, 

140 resource=server, 

141 action=HistoryEnum.Action.updated, 

142 actor=current_user, 

143 ) 

144 db.commit() 

145 db.refresh(server) 

146 return server 

147 

148 

149@mcp_server_router.delete("/{server_id}", status_code=status.HTTP_204_NO_CONTENT) 

150def delete_mcp_server( 

151 server_id: UUID, 

152 db: Session = Depends(get_db), 

153 current_user: User = Depends(get_current_user), 

154): 

155 server = db.get(MCPServer, server_id) 

156 if not server: 

157 raise HTTPException( 

158 status_code=status.HTTP_404_NOT_FOUND, detail="MCP server not found" 

159 ) 

160 verify_resource_access(server, current_user, db) 

161 history_service.record_version( 

162 db, 

163 resource_type=HistoryEnum.ResourceType.mcp_server, 

164 model=MCPServer, 

165 resource=server, 

166 action=HistoryEnum.Action.deleted, 

167 actor=current_user, 

168 ) 

169 db.delete(server) 

170 db.commit() 

171 

172 

173# --------------------------------------------------------------------------- 

174# Edit history (audit trail) 

175# --------------------------------------------------------------------------- 

176 

177register_history_routes( 

178 mcp_server_router, 

179 resource_type=HistoryEnum.ResourceType.mcp_server, 

180 model=MCPServer, 

181 not_found_detail="MCP server not found", 

182) 

183 

184 

185# --------------------------------------------------------------------------- 

186# Probe — connection test + tool discovery 

187# --------------------------------------------------------------------------- 

188 

189 

190@mcp_server_router.post("/{server_id}/probe", dependencies=_AVAILABLE_ONLY) 

191def probe_server( 

192 server_id: UUID, 

193 db: Session = Depends(get_db), 

194 current_user: User = Depends(get_current_user), 

195): 

196 """Test the server's connection via svc-ai and refresh its tools_cache. 

197 

198 Returns {"ok", "tools", "error"} straight from svc-ai's probe. On a 

199 successful probe the discovered tool names are persisted to 

200 ``tools_cache`` so the UI can show real capabilities instead of the 

201 template preview; a failed probe leaves the cache untouched. 

202 """ 

203 server = db.get(MCPServer, server_id) 

204 if not server: 

205 raise HTTPException( 

206 status_code=status.HTTP_404_NOT_FOUND, detail="MCP server not found" 

207 ) 

208 verify_resource_access(server, current_user, db) 

209 

210 try: 

211 result = probe_mcp_server(mcp_service.descriptor(server)) 

212 except AIServiceError as exc: 

213 logger.error("Could not probe MCP server %s via svc-ai: %s", server_id, exc) 

214 raise HTTPException( 

215 status_code=status.HTTP_502_BAD_GATEWAY, 

216 detail="Could not reach svc-ai to probe the MCP server.", 

217 ) 

218 

219 if result.get("ok"): 

220 server.tools_cache = [t["name"] for t in result.get("tools", [])] 

221 db.commit() 

222 db.refresh(server) 

223 return result