Implement token transmission
Browse filesFiles changed (4)
1234567891011124 unmodified lines171819202122232425262728293031323334353637383 unmodified lines424344454647484932 unmodified lines828384858687122 unmodified lines210211212213214215216217218208 unmodified lines42742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148254 unmodified lines537538539540import osimport asynciofrom typing import Any, Dict, List, Optionalfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.responses import HTMLResponsefrom pydantic import BaseModel, Fieldimport uvicornfrom contextlib import asynccontextmanager# Import local MCP clientfrom prestashop_mcp.client import get_mcp_client, close_mcp_client4 unmodified linesasync def lifespan(app: FastAPI):"""Manage application lifespan - better for HF Spaces"""global mcp_client# Startuptry:mcp_client = await get_mcp_client()print("β MCP client initialized successfully")except Exception as e:print(f"β οΈ Failed to initialize MCP client: {e}")mcp_client = Noneyield # App runs here# Shutdowntry:await close_mcp_client()print("β MCP client closed")except Exception as e:print(f"β οΈ Error closing MCP client: {e}")# Create FastAPI app with modern lifespan managementapp = FastAPI(3 unmodified lineslifespan=lifespan)# ConfigurationDEFAULT_PRESTASHOP_URL = os.getenv("PRESTASHOP_API_URL", "https://shop.mcp.integration.ambris.com")# Pydantic models for inference endpointclass InferenceInput(BaseModel):32 unmodified linesmessage: str = Field(..., description="User message/query")conversation_history: List[ChatMessage] = Field(default_factory=list, description="Previous messages")session_id: Optional[str] = Field(default=None, description="Session identifier")class ChatOutput(BaseModel):"""Output from chat interface"""122 unmodified lines# Use MCP tools for product-related queriestool_name, arguments = self._extract_tool_from_message(chat_input.message)# Add default PrestaShop URL if not providedif "api_base_url" not in arguments:arguments["api_base_url"] = DEFAULT_PRESTASHOP_URLif not mcp_client:response = "I'm sorry, but I'm currently unable to access the PrestaShop system. The service appears to be unavailable. Please try again later."208 unmodified lines- Tool-based: {"tool": "tool_name", "arguments": {...}}- Prompt-based: {"prompt": "user question", "session_id": "...", "context": {...}}"""# Check if this is a prompt-based requestif "prompt" in data:print(f"\nπ€ Received prompt request: {data.get('prompt', '')[:100]}...")try:prompt = data.get('prompt', '')session_id = data.get('session_id', '')context = data.get('context', {})# Use the chat handler to process the prompt naturallychat_input = ChatInput(message=prompt,conversation_history=context.get('history', []),session_id=session_id)chat_result = await chat_handler.process_message(chat_input)return InferenceOutput(ok=True,response=chat_result.response,tool=chat_result.tool_used if hasattr(chat_result, 'tool_used') else None)except Exception as e:print(f"β Prompt processing error: {e}")return InferenceOutput(ok=False,error=f"Failed to process prompt: {str(e)}")else:# Handle traditional MCP tool requestprint(f"\nπ§ Received tool request: {data.get('tool', 'unknown')}")result = await handler(data)return InferenceOutput(**result)@app.get("/health", response_model=HealthResponse)async def health_check():"""Health check endpoint"""global mcp_clientmcp_available = mcp_client is not Noneavailable_tools = ["get_product_details", "get_product_features", "get_product_images", "search_products"]return HealthResponse(status="healthy",mcp_available=mcp_available,available_tools=available_tools)@app.get("/tools")async def list_tools():54 unmodified linesif __name__ == "__main__":port = int(os.getenv("PORT", "7860")) # HF Spaces default portuvicorn.run(app, host="0.0.0.0", port=port)123456789101112131415161718192021222324252627282930313233344 unmodified lines39404142434445464748495051525354555657585960616263646566676869707172733 unmodified lines777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612732 unmodified lines160161162163164165166122 unmodified lines289290291292293294295296297298299300301208 unmodified lines51051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064154 unmodified lines696697698699700701702703704705706707708709710711712713714715716717718719import osimport asyncioimport loggingimport sysimport timeimport jsonfrom datetime import datetimefrom typing import Any, Dict, List, Optionalfrom fastapi import FastAPI, HTTPException, Requestfrom fastapi.responses import HTMLResponsefrom pydantic import BaseModel, Fieldimport uvicornfrom contextlib import asynccontextmanager# Configure comprehensive logginglogging.basicConfig(level=logging.DEBUG,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',handlers=[logging.StreamHandler(sys.stdout),logging.FileHandler('inference_app.log', mode='a')])logger = logging.getLogger(__name__)logger.setLevel(logging.DEBUG)# Also create a request logger for detailed request trackingrequest_logger = logging.getLogger('requests')request_logger.setLevel(logging.DEBUG)# Import local MCP clientfrom prestashop_mcp.client import get_mcp_client, close_mcp_client4 unmodified linesasync def lifespan(app: FastAPI):"""Manage application lifespan - better for HF Spaces"""global mcp_clientlogger.info("π Starting HF Inference Point application")logger.info(f"π¦ Environment: {os.getenv('ENVIRONMENT', 'unknown')}")logger.info(f"π Default PrestaShop URL: {DEFAULT_PRESTASHOP_URL}")# Startuptry:logger.info("π§ Attempting to initialize MCP client...")start_time = time.time()mcp_client = await get_mcp_client()init_time = time.time() - start_timelogger.info(f"β MCP client initialized successfully in {init_time:.2f}s")logger.info(f"π οΈ MCP client type: {type(mcp_client)}")except Exception as e:logger.error(f"β Failed to initialize MCP client: {e}")logger.error(f"π Exception details: {type(e).__name__}: {str(e)}")logger.error(f"π MCP client will be None, falling back to graceful degradation")mcp_client = Nonelogger.info("π― Application startup complete, ready to serve requests")yield # App runs here# Shutdownlogger.info("π Application shutdown initiated")try:await close_mcp_client()logger.info("β MCP client closed successfully")except Exception as e:logger.error(f"β οΈ Error closing MCP client: {e}")logger.info("π Application shutdown complete")# Create FastAPI app with modern lifespan managementapp = FastAPI(3 unmodified lineslifespan=lifespan)# Request logging middleware@app.middleware("http")async def log_requests(request: Request, call_next):"""Log all incoming requests and responses"""start_time = time.time()request_id = f"req_{int(time.time() * 1000)}_{hash(str(request.url)) % 10000}"# Log incoming requestrequest_logger.info(f"π₯ [{request_id}] {request.method} {request.url}")request_logger.info(f"π [{request_id}] Headers: {dict(request.headers)}")request_logger.info(f"π [{request_id}] Client: {request.client.host if request.client else 'unknown'}")# Get request body if presentif request.method in ["POST", "PUT", "PATCH"]:try:body = await request.body()if body:try:body_json = json.loads(body.decode())request_logger.info(f"π [{request_id}] Body: {json.dumps(body_json, indent=2)}")except:request_logger.info(f"π [{request_id}] Body (raw): {body.decode()[:500]}...")# Reset body for the actual handlerasync def receive():return {"type": "http.request", "body": body}request._receive = receiveexcept Exception as e:request_logger.warning(f"β οΈ [{request_id}] Could not read request body: {e}")# Process requesttry:response = await call_next(request)duration = time.time() - start_timerequest_logger.info(f"π€ [{request_id}] Response: {response.status_code} in {duration:.3f}s")return responseexcept Exception as e:duration = time.time() - start_timerequest_logger.error(f"π₯ [{request_id}] Request failed after {duration:.3f}s: {e}")raise# ConfigurationDEFAULT_PRESTASHOP_URL = os.getenv("PRESTASHOP_API_URL", "https://shop.mcp.integration.ambris.com")HUB_SERVER_URL = "https://hub.mcp.integration.ambris.com"# Pydantic models for inference endpointclass InferenceInput(BaseModel):32 unmodified linesmessage: str = Field(..., description="User message/query")conversation_history: List[ChatMessage] = Field(default_factory=list, description="Previous messages")session_id: Optional[str] = Field(default=None, description="Session identifier")client_token: Optional[str] = Field(default=None, description="Client authentication token")class ChatOutput(BaseModel):"""Output from chat interface"""122 unmodified lines# Use MCP tools for product-related queriestool_name, arguments = self._extract_tool_from_message(chat_input.message)# Add client token for authentication if availableif chat_input.client_token:arguments["client_token"] = chat_input.client_token# Set api_base_url to hub (which will route based on client_token)if "api_base_url" not in arguments:arguments["api_base_url"] = HUB_SERVER_URLif not mcp_client:response = "I'm sorry, but I'm currently unable to access the PrestaShop system. The service appears to be unavailable. Please try again later."208 unmodified lines- Tool-based: {"tool": "tool_name", "arguments": {...}}- Prompt-based: {"prompt": "user question", "session_id": "...", "context": {...}}"""request_start = time.time()request_type = "prompt" if "prompt" in data else "tool"logger.info(f"π― API Inference Request - Type: {request_type}")logger.info(f"π Request data keys: {list(data.keys())}")logger.info(f"π¦ Full request data: {json.dumps(data, indent=2)}")# Check if this is a prompt-based requestif "prompt" in data:logger.info(f"π€ Processing prompt-based request")prompt = data.get('prompt', '')session_id = data.get('session_id', '')context = data.get('context', {})client_token = data.get('client_token', '')logger.info(f"π Prompt length: {len(prompt)} characters")logger.info(f"π Session ID: {session_id}")logger.info(f"πͺ Client token: {client_token[:8]}***{client_token[-4:] if len(client_token) > 12 else 'invalid'}")logger.info(f"π Context keys: {list(context.keys())}")logger.info(f"π Prompt preview: {prompt[:200]}{'...' if len(prompt) > 200 else ''}")# TODO: Look up shop information from client_token in database# For now, we'll proceed with the request but log the token for identificationif client_token:logger.info(f"πͺ Authenticated request from client token: {client_token[:8]}***")else:logger.warning(f"β οΈ Unauthenticated request - no client token provided")try:logger.info(f"π§ Creating ChatInput object")chat_input = ChatInput(message=prompt,conversation_history=context.get('history', []),session_id=session_id,client_token=client_token)logger.info(f"β ChatInput created successfully")logger.info(f"π Calling chat_handler.process_message")chat_result = await chat_handler.process_message(chat_input)logger.info(f"β Chat processing completed")response_time = time.time() - request_startlogger.info(f"π€ Prompt request completed in {response_time:.3f}s")logger.info(f"π Response length: {len(chat_result.response)} characters")logger.info(f"π οΈ Tool used: {getattr(chat_result, 'tool_used', 'None')}")result = InferenceOutput(ok=True,response=chat_result.response,tool=chat_result.tool_used if hasattr(chat_result, 'tool_used') else None)logger.info(f"β Returning successful prompt response")return resultexcept Exception as e:response_time = time.time() - request_startlogger.error(f"π₯ Prompt processing error after {response_time:.3f}s: {e}")logger.error(f"π Exception type: {type(e).__name__}")logger.error(f"π Exception details: {str(e)}")import tracebacklogger.error(f"π¬ Full traceback: {traceback.format_exc()}")result = InferenceOutput(ok=False,error=f"Failed to process prompt: {str(e)}")logger.info(f"β Returning error response for prompt")return resultelse:# Handle traditional MCP tool requesttool_name = data.get('tool', 'unknown')arguments = data.get('arguments', {})logger.info(f"π§ Processing tool-based request")logger.info(f"π οΈ Tool name: {tool_name}")logger.info(f"οΏ½ Arguments: {json.dumps(arguments, indent=2)}")try:logger.info(f"π Calling handler for tool request")result = await handler(data)response_time = time.time() - request_startlogger.info(f"β Tool request completed in {response_time:.3f}s")logger.info(f"π€ Tool result keys: {list(result.keys()) if isinstance(result, dict) else 'not dict'}")logger.info(f"π Tool result: {json.dumps(result, indent=2) if isinstance(result, dict) else str(result)}")final_result = InferenceOutput(**result)logger.info(f"β Returning successful tool response")return final_resultexcept Exception as e:response_time = time.time() - request_startlogger.error(f"π₯ Tool processing error after {response_time:.3f}s: {e}")logger.error(f"π Exception type: {type(e).__name__}")logger.error(f"π Exception details: {str(e)}")import tracebacklogger.error(f"π¬ Full traceback: {traceback.format_exc()}")result = InferenceOutput(ok=False,error=f"Failed to process tool request: {str(e)}")logger.info(f"β Returning error response for tool")return result@app.get("/health", response_model=HealthResponse)async def health_check():"""Health check endpoint"""logger.info("π Health check requested")global mcp_clientmcp_available = mcp_client is not Noneavailable_tools = ["get_product_details", "get_product_features", "get_product_images", "search_products"]logger.info(f"π MCP client available: {mcp_available}")logger.info(f"π οΈ Available tools: {available_tools}")health_response = HealthResponse(status="healthy",mcp_available=mcp_available,available_tools=available_tools)logger.info(f"β Health check completed - Status: healthy")return health_response@app.get("/tools")async def list_tools():54 unmodified linesif __name__ == "__main__":port = int(os.getenv("PORT", "7860")) # HF Spaces default portlogger.info("π Starting HF Inference Point server")logger.info(f"π Host: 0.0.0.0")logger.info(f"π Port: {port}")logger.info(f"π Environment: {os.getenv('ENVIRONMENT', 'development')}")logger.info(f"π Log level: {logging.getLevelName(logger.level)}")logger.info(f"π Working directory: {os.getcwd()}")logger.info(f"π Python version: {sys.version}")# Configure uvicorn logging to be more verboseuvicorn_config = uvicorn.Config(app=app,host="0.0.0.0",port=port,log_level="debug",access_log=True)logger.info("π― Starting uvicorn server with debug logging")server = uvicorn.Server(uvicorn_config)server.run()
12345678910111213141516171819202025-09-12 19:04:04,701 - __main__ - INFO - π Starting HF Inference Point server2025-09-12 19:04:04,701 - __main__ - INFO - π Host: 0.0.0.02025-09-12 19:04:04,701 - __main__ - INFO - π Port: 78602025-09-12 19:04:04,701 - __main__ - INFO - π Environment: development2025-09-12 19:04:04,701 - __main__ - INFO - π Log level: DEBUG2025-09-12 19:04:04,701 - __main__ - INFO - π Working directory: /Users/jdewitte/www/mcp/huggingface/inference_point2025-09-12 19:04:04,701 - __main__ - INFO - π Python version: 3.13.5 (main, Jun 11 2025, 15:36:57) [Clang 17.0.0 (clang-1700.0.13.3)]2025-09-12 19:04:04,702 - __main__ - INFO - π― Starting uvicorn server with debug logging2025-09-12 19:04:04,703 - asyncio - DEBUG - Using selector: KqueueSelector2025-09-12 19:04:04,723 - __main__ - INFO - π Starting HF Inference Point application2025-09-12 19:04:04,723 - __main__ - INFO - π¦ Environment: unknown2025-09-12 19:04:04,723 - __main__ - INFO - π Default PrestaShop URL: https://shop.mcp.integration.ambris.com2025-09-12 19:04:04,723 - __main__ - INFO - π§ Attempting to initialize MCP client...2025-09-12 19:04:04,723 - mcp.server.lowlevel.server - DEBUG - Initializing server 'prestashop-mcp'2025-09-12 19:04:04,723 - mcp.server.lowlevel.server - DEBUG - Registering handler for ListToolsRequest2025-09-12 19:04:04,723 - mcp.server.lowlevel.server - DEBUG - Registering handler for CallToolRequest2025-09-12 19:04:04,723 - prestashop_mcp.client - INFO - MCP client initialized with 4 tools2025-09-12 19:04:04,723 - __main__ - INFO - β
MCP client initialized successfully in 0.00s2025-09-12 19:04:04,723 - __main__ - INFO - π οΈ MCP client type: <class 'prestashop_mcp.client.LocalMCPClient'>2025-09-12 19:04:04,723 - __main__ - INFO - π― Application startup complete, ready to serve requests31 unmodified lines3233343536373831 unmodified lineslogger = logging.getLogger(__name__)# Default PrestaShop API configurationDEFAULT_API_BASE = "https://shop.mcp.integration.ambris.com"DEFAULT_TIMEOUT = 30class PrestaShopMCPServer:31 unmodified lines3233343536373831 unmodified lineslogger = logging.getLogger(__name__)# Default PrestaShop API configurationDEFAULT_API_BASE = "https://hub.mcp.integration.ambris.com"DEFAULT_TIMEOUT = 30class PrestaShopMCPServer:
app.py+201-22
inference_app.logAdded+20
prestashop_mcp/__pycache__/server.cpython-313.pyc
prestashop_mcp/server.py+1-1