Coverage for src / mcp_server_langgraph / cli / init.py: 100%

33 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2025-12-03 00:43 +0000

1""" 

2Project initialization command for MCP Server CLI. 

3 

4Handles creation of new MCP Server projects with different templates. 

5""" 

6 

7from pathlib import Path 

8from typing import Literal 

9 

10ProjectTemplate = Literal["quickstart", "production", "enterprise"] 

11 

12 

13def init_project(name: str, template: ProjectTemplate = "production") -> None: 

14 """ 

15 Initialize a new MCP Server project with the specified template. 

16 

17 Args: 

18 name: Name of the project (will be used as directory name) 

19 template: Project template to use: 

20 - quickstart: Minimal in-memory setup (2-minute start) 

21 - production: Full Docker Compose stack (15-minute start) 

22 - enterprise: Kubernetes with Keycloak + OpenFGA 

23 

24 Raises: 

25 FileExistsError: If project directory already exists 

26 ValueError: If template is invalid 

27 """ 

28 if template not in ["quickstart", "production", "enterprise"]: 

29 msg = f"Invalid template: {template}. Must be one of: quickstart, production, enterprise" 

30 raise ValueError(msg) 

31 

32 project_dir = Path(name) 

33 

34 if project_dir.exists(): 

35 msg = f"Directory '{name}' already exists" 

36 raise FileExistsError(msg) 

37 

38 # Create project directory 

39 project_dir.mkdir(parents=True) 

40 

41 if template == "quickstart": 

42 _create_quickstart_project(project_dir, name) 

43 elif template == "production": 

44 _create_production_project(project_dir, name) 

45 else: # enterprise 

46 _create_enterprise_project(project_dir, name) 

47 

48 

49def _create_quickstart_project(project_dir: Path, name: str) -> None: 

50 """ 

51 Create a minimal quick-start project. 

52 

53 Features: 

54 - In-memory storage (no Docker needed) 

55 - Simple agent with basic tools 

56 - FastAPI server with minimal config 

57 - Ready to run in < 2 minutes 

58 """ 

59 # Create directory structure 

60 (project_dir / "src").mkdir() 

61 (project_dir / "tests").mkdir() 

62 

63 # Create pyproject.toml 

64 pyproject_content = f"""[project] 

65name = "{name}" 

66version = "0.1.0" 

67description = "MCP Server with LangGraph - Quick Start Project" 

68requires-python = ">=3.11" 

69dependencies = [ 

70 "mcp-server-langgraph>=2.8.0", 

71 "fastapi>=0.115.0", 

72 "uvicorn>=0.32.0", 

73 "langgraph>=1.0.0", 

74] 

75 

76[build-system] 

77requires = ["hatchling"] 

78build-backend = "hatchling.build" 

79 

80[tool.uv] 

81dev-dependencies = [ 

82 "pytest>=8.3.4", 

83 "pytest-asyncio>=0.25.0", 

84] 

85""" 

86 (project_dir / "pyproject.toml").write_text(pyproject_content) 

87 

88 # Create app.py 

89 app_content = '''""" 

90MCP Server Quick Start Application 

91 

92A minimal MCP server with in-memory storage and basic tools. 

93Ready to run in < 2 minutes! 

94""" 

95 

96from fastapi import FastAPI 

97from langgraph.graph import StateGraph 

98from langgraph.checkpoint.memory import MemorySaver 

99from typing import TypedDict, Annotated 

100 

101app = FastAPI(title="MCP Server Quick Start") 

102 

103 

104# Define agent state 

105class AgentState(TypedDict): 

106 """State for the quick-start agent.""" 

107 messages: Annotated[list[str], "The conversation messages"] 

108 query: str 

109 response: str 

110 

111 

112# Create simple agent graph 

113graph = StateGraph(AgentState) 

114 

115 

116def handle_query(state: AgentState) -> AgentState: 

117 """Handle user query with a simple response.""" 

118 query = state["query"] 

119 state["response"] = f"Echo: {query}" 

120 state["messages"].append(f"User: {query}") 

121 state["messages"].append(f"Agent: {state['response']}") 

122 return state 

123 

124 

125# Build graph 

126graph.add_node("handle", handle_query) 

127graph.set_entry_point("handle") 

128graph.set_finish_point("handle") 

129 

130# Compile with in-memory checkpointer 

131checkpointer = MemorySaver() 

132agent = graph.compile(checkpointer=checkpointer) 

133 

134 

135@app.get("/") 

136def root(): 

137 """Health check endpoint.""" 

138 return {"status": "healthy", "message": "MCP Server Quick Start is running!"} 

139 

140 

141@app.post("/chat") 

142def chat(query: str): 

143 """Chat with the agent.""" 

144 result = agent.invoke( 

145 {"query": query, "messages": [], "response": ""}, 

146 config={"configurable": {"thread_id": "quickstart"}} 

147 ) 

148 return {"response": result["response"], "messages": result["messages"]} 

149 

150 

151if __name__ == "__main__": 

152 import uvicorn 

153 print("🚀 Starting MCP Server Quick Start...") 

154 print("📝 Visit http://localhost:8000/docs for API documentation") 

155 print("💬 Try: curl -X POST http://localhost:8000/chat?query=Hello") 

156 uvicorn.run(app, host="0.0.0.0", port=8000) 

157''' 

158 (project_dir / "app.py").write_text(app_content) 

159 

160 # Create README 

161 readme_content = f"""# {name} 

162 

163MCP Server with LangGraph - Quick Start Project 

164 

165## Quick Start (< 2 minutes) 

166 

1671. **Install dependencies:** 

168 ```bash 

169 uv sync 

170 ``` 

171 

1722. **Run the server:** 

173 ```bash 

174 uv run python app.py 

175 ``` 

176 

1773. **Test the agent:** 

178 ```bash 

179 curl -X POST "http://localhost:8000/chat?query=Hello" 

180 ``` 

181 

1824. **View API docs:** 

183 Open http://localhost:8000/docs in your browser 

184 

185## Next Steps 

186 

187- 📖 [Add more tools](https://docs.mcp-server-langgraph.com/guides/adding-tools) 

188- 🧪 [Write tests](https://docs.mcp-server-langgraph.com/advanced/testing) 

189- 🚀 [Deploy to production](https://docs.mcp-server-langgraph.com/deployment/overview) 

190 

191## Features 

192 

193✅ In-memory storage (no Docker needed) 

194✅ Simple agent with basic echo functionality 

195✅ FastAPI server with auto-generated docs 

196✅ Ready to extend with custom tools and logic 

197 

198## Upgrade to Production 

199 

200When you're ready for production features: 

201 

202```bash 

203# Add authentication, observability, and more 

204mcpserver init --template production --name {name}-production 

205``` 

206 

207See [Production vs Quick Start](https://docs.mcp-server-langgraph.com/comparisons/choosing-framework) for comparison. 

208""" 

209 (project_dir / "README.md").write_text(readme_content) 

210 

211 # Create .gitignore 

212 gitignore_content = """# Python 

213__pycache__/ 

214*.py[cod] 

215*$py.class 

216*.so 

217.Python 

218.venv/ 

219venv/ 

220ENV/ 

221env/ 

222 

223# IDE 

224.vscode/ 

225.idea/ 

226*.swp 

227*.swo 

228 

229# Tests 

230.pytest_cache/ 

231.coverage 

232htmlcov/ 

233""" 

234 (project_dir / ".gitignore").write_text(gitignore_content) 

235 

236 

237def _create_production_project(project_dir: Path, name: str) -> None: 

238 """ 

239 Create a full production project with Docker Compose. 

240 

241 Features: 

242 - Docker Compose stack (Redis, PostgreSQL) 

243 - Complete observability (LangSmith, Prometheus, Grafana) 

244 - Environment-based configuration 

245 - Production-ready structure 

246 """ 

247 # TODO: Implement cookiecutter-based generation 

248 # For now, create a placeholder with instructions 

249 readme_content = f"""# {name} 

250 

251MCP Server with LangGraph - Production Project 

252 

253## Production Setup (15 minutes) 

254 

255This project template will be generated using our production Cookiecutter template. 

256 

257**Coming Soon:** Full cookiecutter integration 

258 

259For now, use our existing setup: 

260 

261```bash 

262# Clone the repository 

263git clone https://github.com/vishnu2kmohan/mcp-server-langgraph.git {name} 

264cd {name} 

265 

266# Start the stack 

267docker compose up -d 

268 

269# Run setup scripts 

270make setup 

271``` 

272 

273## Features 

274 

275✅ Docker Compose stack (Redis, PostgreSQL, Jaeger, Prometheus, Grafana) 

276✅ JWT authentication with Keycloak 

277✅ OpenFGA authorization 

278✅ LangSmith + OpenTelemetry observability 

279✅ Infisical secrets management 

280✅ Production-ready configuration 

281 

282See [Documentation](https://docs.mcp-server-langgraph.com/deployment/docker) for full setup. 

283""" 

284 (project_dir / "README.md").write_text(readme_content) 

285 

286 

287def _create_enterprise_project(project_dir: Path, name: str) -> None: 

288 """ 

289 Create an enterprise project with Kubernetes manifests. 

290 

291 Features: 

292 - Kubernetes manifests (Helm charts) 

293 - Terraform modules (GKE: Complete, EKS: Modules ready, AKS: In development) 

294 - GitOps ready (ArgoCD) 

295 - Multi-region support 

296 

297 Platform Maturity: 

298 - GKE: Production Ready (full automation, dev/staging/prod) 

299 - EKS: Beta (modules complete, prod environment ready) 

300 - AKS: Alpha (manual deployment only) 

301 """ 

302 # TODO: Implement full enterprise template generation 

303 readme_content = f"""# {name} 

304 

305MCP Server with LangGraph - Enterprise Project 

306 

307## Enterprise Setup (1-2 hours) 

308 

309This project template includes Kubernetes manifests for enterprise deployment. 

310 

311**Coming Soon:** Full enterprise template with Terraform + Helm 

312 

313For now, use our enterprise deployment guides: 

314 

315- [GKE Deployment](https://docs.mcp-server-langgraph.com/deployment/kubernetes/gke) 

316- [EKS Deployment](https://docs.mcp-server-langgraph.com/deployment/kubernetes/eks) 

317- [AKS Deployment](https://docs.mcp-server-langgraph.com/deployment/kubernetes/aks) 

318 

319## Features 

320 

321✅ Helm charts for Kubernetes 

322✅ Terraform modules (GCP, AWS, Azure) 

323✅ GitOps with ArgoCD 

324✅ Multi-region deployment 

325✅ Complete compliance (GDPR, HIPAA, SOC 2) 

326✅ Enterprise security (Keycloak, OpenFGA, Binary Authorization) 

327 

328See [Enterprise Documentation](https://docs.mcp-server-langgraph.com/deployment/kubernetes) for full setup. 

329""" 

330 (project_dir / "README.md").write_text(readme_content)