Coverage for app / routers / toolkit_setup.py: 98%

62 statements  

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

1""" 

2One-shot generative toolkit setup. 

3 

4A narrower sibling of skillset_setup.py, scoped to recommending a bundle of 

5the tenant's EXISTING tools/MCP servers. Unlike skill generation, this flow 

6never invents a new Tool or MCPServer resource — both carry live 

7credentials (webhook URLs, connection configs, launch commands) that only a 

8human can safely configure. There is no graph generation here at all: the 

9LLM's only job is picking which existing tools/MCP servers belong together 

10for a described use case, and naming the resulting bundle. 

11 

12A toolkit bundles MCP servers, so this flow is refused while MCP is not 

13available (``app.mcp.MCP_AVAILABLE``) — before any model is called. 

14""" 

15 

16from fastapi import APIRouter, Depends, HTTPException 

17from langchain_core.messages import HumanMessage, SystemMessage 

18from pydantic import BaseModel, Field 

19from sqlalchemy.orm import Session 

20 

21from app import prompts 

22from app.services.structured_output import ModelOutput 

23from app.db.postgres.enums import InvocationEnum 

24from app.dependency.base import get_db 

25from app.mcp import UNAVAILABLE_MESSAGE, is_available 

26from app.models.spec import ModelConfig 

27from app.services.conversation import persist_llm_invocation 

28from app.services.llm import build_langchain_llm 

29from app.services.structured_generation import ( 

30 generate, 

31) 

32from app.util.logger import get_logger 

33 

34logger = get_logger(__name__) 

35 

36router = APIRouter(prefix="/toolkits", tags=["toolkit-setup"]) 

37 

38# Same budget as agent_setup/skillset_setup — must undercut svc-core's 

39# client timeout. 

40GENERATION_BUDGET_S = 100.0 

41 

42 

43# --------------------------------------------------------------------------- 

44# Request models — catalogs passed in by svc-core 

45# --------------------------------------------------------------------------- 

46 

47 

48class CatalogTool(BaseModel): 

49 id: str 

50 name: str 

51 description: str = "" 

52 

53 

54class CatalogMCPServer(BaseModel): 

55 id: str 

56 name: str 

57 description: str = "" 

58 

59 

60class ToolkitConfigGenerationRequest(BaseModel): 

61 problem_description: str = Field(min_length=1) 

62 provider: str 

63 model: str 

64 model_id: str | None = None 

65 existing_tools: list[CatalogTool] = [] 

66 existing_mcp_servers: list[CatalogMCPServer] = [] 

67 user_id: str = "system" 

68 

69 

70# --------------------------------------------------------------------------- 

71# Structured-output schema — existing-resources-only, no graph fields at all 

72# --------------------------------------------------------------------------- 

73 

74 

75class GeneratedToolkitConfig(ModelOutput): 

76 """The complete proposal the LLM must produce.""" 

77 

78 name: str 

79 description: str = "" 

80 explanation: str = Field( 

81 default="", 

82 description="Why this proposal — written to the user.", 

83 # The model fills "explanation" (a field named for its reasoning can 

84 # be refused by Claude 5.x); svc-core reads it as "reasoning". 

85 serialization_alias="reasoning", 

86 ) 

87 selected_tool_ids: list[str] = [] 

88 selected_mcp_server_ids: list[str] = [] 

89 

90 

91class GenerateToolkitConfigResponse(BaseModel): 

92 config: GeneratedToolkitConfig 

93 warnings: list[str] = [] 

94 

95 

96# --------------------------------------------------------------------------- 

97# Endpoint 

98# --------------------------------------------------------------------------- 

99 

100 

101def _build_user_content(req: ToolkitConfigGenerationRequest) -> str: 

102 def section(title: str, items: list[BaseModel]) -> str: 

103 if not items: 

104 return f"{title}: (none)" 

105 lines = "\n".join(f" - {item.model_dump_json()}" for item in items) 

106 return f"{title}:\n{lines}" 

107 

108 return ( 

109 f"Use-case description:\n{req.problem_description}\n\n" 

110 + section("Existing tools catalog", req.existing_tools) 

111 + "\n\n" 

112 + section("Existing MCP servers catalog", req.existing_mcp_servers) 

113 ) 

114 

115 

116@router.post("/generate-config", response_model=GenerateToolkitConfigResponse) 

117async def generate_toolkit_config( 

118 req: ToolkitConfigGenerationRequest, db: Session = Depends(get_db) 

119) -> GenerateToolkitConfigResponse: 

120 """Recommend a proposed toolkit configuration in one structured call.""" 

121 if not is_available(): 

122 raise HTTPException(status_code=403, detail=UNAVAILABLE_MESSAGE) 

123 system_prompt = prompts.build_toolkit_config_generator_prompt() 

124 llm = build_langchain_llm( 

125 ModelConfig( 

126 provider=req.provider, 

127 model=req.model, 

128 temperature=0.2, 

129 max_tokens=4096, 

130 ) 

131 ) 

132 messages = [ 

133 SystemMessage(content=system_prompt), 

134 HumanMessage(content=_build_user_content(req)), 

135 ] 

136 

137 outcome = await generate( 

138 llm, 

139 GeneratedToolkitConfig, 

140 messages, 

141 purpose="toolkit-setup", 

142 budget_s=GENERATION_BUDGET_S, 

143 ) 

144 config = outcome.config 

145 

146 persist_llm_invocation( 

147 db, 

148 purpose="toolkit_generation", 

149 provider=req.provider, 

150 model=req.model, 

151 user_id=req.user_id, 

152 latency_ms=outcome.latency_ms, 

153 status=InvocationEnum.Status.success 

154 if config is not None 

155 else InvocationEnum.Status.error, 

156 error_detail=outcome.failure if config is None else None, 

157 request_config={ 

158 "provider": req.provider, 

159 "model": req.model, 

160 "temperature": 0.2, 

161 "max_tokens": 4096, 

162 "flow": "toolkit_setup.generate_config", 

163 }, 

164 output_preview=config.model_dump_json(indent=2) if config else None, 

165 ) 

166 

167 if config is None: 

168 raise HTTPException( 

169 status_code=422, 

170 detail=f"Toolkit configuration generation failed: {outcome.user_message}", 

171 ) 

172 

173 return GenerateToolkitConfigResponse(config=config, warnings=[])