Jeremy Live commited on
Commit
c8124d9
·
1 Parent(s): 700bd36

mcp int v1

Browse files
Files changed (3) hide show
  1. app.py +53 -7
  2. mcp_server.py +35 -4
  3. requirements-mcp.txt +5 -0
app.py CHANGED
@@ -336,18 +336,62 @@ class MCPServer:
336
 
337
  def start(self):
338
  """Start the MCP server in a separate process"""
 
 
 
 
339
  try:
340
  import subprocess
 
 
 
 
 
 
 
341
  self.process = subprocess.Popen(
342
- ["python", "mcp_server.py"],
343
  stdout=subprocess.PIPE,
344
- stderr=subprocess.PIPE
 
 
 
345
  )
346
- # Give it a moment to start
347
- time.sleep(2)
348
- return True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349
  except Exception as e:
350
- logger.error(f"Failed to start MCP server: {str(e)}")
351
  return False
352
 
353
  def stop(self):
@@ -359,9 +403,11 @@ class MCPServer:
359
  def is_running(self) -> bool:
360
  """Check if MCP server is running"""
361
  try:
 
362
  response = requests.get(f"{self.base_url}/health", timeout=2)
363
  return response.status_code == 200
364
- except:
 
365
  return False
366
 
367
  # Initialize MCP server
 
336
 
337
  def start(self):
338
  """Start the MCP server in a separate process"""
339
+ if self.is_running():
340
+ logger.info("MCP server is already running")
341
+ return True
342
+
343
  try:
344
  import subprocess
345
+ import sys
346
+
347
+ # Use the same Python executable that's running this script
348
+ python_exec = sys.executable
349
+
350
+ logger.info(f"Starting MCP server with: {python_exec} mcp_server.py")
351
+
352
  self.process = subprocess.Popen(
353
+ [python_exec, "mcp_server.py"],
354
  stdout=subprocess.PIPE,
355
+ stderr=subprocess.PIPE,
356
+ text=True,
357
+ bufsize=1,
358
+ universal_newlines=True
359
  )
360
+
361
+ # Log the output in real-time
362
+ def log_output(pipe, logger_func):
363
+ for line in iter(pipe.readline, ''):
364
+ if line:
365
+ logger_func(line.strip())
366
+
367
+ # Start logging threads
368
+ import threading
369
+ threading.Thread(
370
+ target=log_output,
371
+ args=(self.process.stdout, logger.info),
372
+ daemon=True
373
+ ).start()
374
+
375
+ threading.Thread(
376
+ target=log_output,
377
+ args=(self.process.stderr, logger.error),
378
+ daemon=True
379
+ ).start()
380
+
381
+ # Wait for server to be ready
382
+ import time
383
+ max_attempts = 10
384
+ for _ in range(max_attempts):
385
+ if self.is_running():
386
+ logger.info("MCP server started successfully")
387
+ return True
388
+ time.sleep(0.5)
389
+
390
+ logger.error("MCP server failed to start within the expected time")
391
+ return False
392
+
393
  except Exception as e:
394
+ logger.error(f"Failed to start MCP server: {str(e)}", exc_info=True)
395
  return False
396
 
397
  def stop(self):
 
403
  def is_running(self) -> bool:
404
  """Check if MCP server is running"""
405
  try:
406
+ import requests
407
  response = requests.get(f"{self.base_url}/health", timeout=2)
408
  return response.status_code == 200
409
+ except Exception as e:
410
+ logger.debug(f"MCP server health check failed: {str(e)}")
411
  return False
412
 
413
  # Initialize MCP server
mcp_server.py CHANGED
@@ -1,16 +1,27 @@
1
  import os
2
  import json
 
3
  from fastapi import FastAPI, HTTPException
4
  from fastapi.middleware.cors import CORSMiddleware
5
  from pydantic import BaseModel
6
  from typing import Dict, List, Optional
7
- import logging
8
 
9
  # Set up logging
10
- logging.basicConfig(level=logging.INFO)
 
 
 
 
 
 
 
11
  logger = logging.getLogger(__name__)
12
 
13
- app = FastAPI(title="Content Creation Agent MCP Server")
 
 
 
 
14
 
15
  # Enable CORS for all origins
16
  app.add_middleware(
@@ -88,4 +99,24 @@ async def health_check():
88
 
89
  if __name__ == "__main__":
90
  import uvicorn
91
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import json
3
+ import logging
4
  from fastapi import FastAPI, HTTPException
5
  from fastapi.middleware.cors import CORSMiddleware
6
  from pydantic import BaseModel
7
  from typing import Dict, List, Optional
 
8
 
9
  # Set up logging
10
+ logging.basicConfig(
11
+ level=logging.INFO,
12
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
13
+ handlers=[
14
+ logging.StreamHandler(),
15
+ logging.FileHandler('mcp_server.log')
16
+ ]
17
+ )
18
  logger = logging.getLogger(__name__)
19
 
20
+ app = FastAPI(
21
+ title="Content Creation Agent MCP Server",
22
+ description="MCP Server for Content Creation Agent",
23
+ version="1.0.0"
24
+ )
25
 
26
  # Enable CORS for all origins
27
  app.add_middleware(
 
99
 
100
  if __name__ == "__main__":
101
  import uvicorn
102
+ import sys
103
+
104
+ port = 8000
105
+ host = "0.0.0.0"
106
+
107
+ logger.info(f"Starting MCP server on {host}:{port}")
108
+ logger.info(f"Python version: {sys.version}")
109
+ logger.info(f"FastAPI version: {FastAPI.__version__ if hasattr(FastAPI, '__version__') else 'unknown'}")
110
+
111
+ try:
112
+ uvicorn.run(
113
+ app,
114
+ host=host,
115
+ port=port,
116
+ log_level="info",
117
+ access_log=True,
118
+ reload=False
119
+ )
120
+ except Exception as e:
121
+ logger.exception("Failed to start MCP server")
122
+ sys.exit(1)
requirements-mcp.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ fastapi>=0.68.0,<0.69.0
2
+ uvicorn[standard]>=0.15.0,<0.16.0
3
+ pydantic>=1.8.0,<2.0.0
4
+ python-multipart>=0.0.5,<0.1.0
5
+ requests>=2.26.0,<3.0.0